GraphCanvas.py 109 KB
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 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 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 352 353 354 355 356 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 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 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Aug  5 15:43:59 2019

@author: pavel
    The GraphCanvas class that extends the scene class in vispy in order to draw
    the graph object. This class is wrapped in a QTcanvas.
"""

from vispy import gloo, scene
from vispy.gloo import set_viewport, set_state, clear, set_blend_color, context
from vispy.util.transforms import perspective, translate, rotate, scale
import vispy.gloo.gl as glcore
from vispy import app
#from shapely.geometry import Polygon
#from shapely.geometry import Point
#from shapely.geometry import MultiPoint
from scipy.spatial import ConvexHull
from scipy.spatial import Delaunay
#import scipy.spatial.ConvexHull

from vispy.scene.visuals import Text
from vispy.scene.visuals import ColorBar



import copy

import numpy as np
import math
import network_dep as nwt

#import the graph shaders.
from graph_shaders import vert, frag, vs, fs
from subgraph_shaders import vert_s, frag_s, vs_s, fs_s

DEBUG = False

#class storing the path. a vertex in the path is defined as a vertex idx
#and a list of all vertices required to reach the next point in the path
class path_point:
    #Init an empty vertex with no path
    def __init__(self, idx):
        self.idx = idx
        self.v_path = []
        self.e_path = []
    
    #Remove all future path vertices attached to this vertex
    def clear_path(self):
        self.v_path = []
        self.e_path = []
        
    # == comparison operator    
    def __eq__(self, other):
        if self.idx == other.idx:
            return True
        else:
            return False
    # != comparison operator
    def __ne__(self, other):
        if self.idx != other.idx:
            return True
        else:
            return False
        
    def __str__(self):
        print("PathPoint[", self.idx, "], Chain = [", self.v_path, "]")
        

#The graph canvas class that 
class GraphCanvas(scene.SceneCanvas):
    
    """
        Initialization method.
        Generates the 512x512 canvas, makes it available for drawing the fills all
        the GLSL shaders with dummy data.
    """
    def __init__(self, **kwargs):
        # Initialize the canvas for real
        scene.SceneCanvas.__init__(self, size=(512, 512), **kwargs)
        #Unfreeze the canvas to make dynamic interaction possible
        self.unfreeze()
        
        #initialize all the boolean and dictionary variables.
        ps = self.pixel_scale
        self.subgraphs = False
        self.position = 50, 50
        self.down=False;
        
        #Dictionaries to store the unique color ID, cluster ID, and edge-to-ID
        #dictionaries.
        self.color_dict = {}
        self.cluster_dict = {}
        self.edge_dict = {}

        #Booleans the storage for the current "Path", i.e. edges the user selected.
        self.pathing = False
        self.path = []
        self.full_path = []

        #utility variables used for storing the cluster being moved and all the
        #nodes and edges that belong to that cluster and move along with it.
        self.moving = False
        self.moving_cluster = False
        self.selection = False
        n = 10
        ne = 10
        #Init dummy structures
        #self.uniforms = [('u_graph_size', np.float32, 3)]
        self.data = np.zeros(n, dtype=[('a_position', np.float32, 3),
                                  ('a_fg_color', np.float32, 4),
                                  ('a_bg_color', np.float32, 4),
                                  ('a_size', np.float32, 1),
                                  ('a_linewidth', np.float32, 1),
                                  ('a_unique_id', np.float32, 4),
                                  ])
    
        self.line_data = np.zeros(ne, dtype=[('a_position', np.float32, 3),
                                  ('a_normal', np.float32, 2),
                                  ('a_fg_color', np.float32, 4),
                                  ('a_linewidth', np.float32, 1),
                                  ])
    
            
        self.clusters = np.zeros(n*4, dtype=[('a_position', np.float32, 3),
                      ('a_value', np.float32, 2),
                      ('a_bg_color', np.float32, 4),
                      ('a_cluster_color', np.float32, 4),
                      ('a_arc_length', np.float32, 1),
                      ('a_outer_arc_length', np.float32, 4),
                      ('a_unique_id', np.float32, 4),
                      ])

        self.cluster_line_data = np.zeros(ne, dtype=[('a_position', np.float32, 3),
                          ('a_normal', np.float32, 2),
                          ('a_fg_color', np.float32, 4),
                          ('a_linewidth', np.float32, 1),
                          ])

    
        self.edges = np.random.randint(size=(ne, 2), low=0,
                                  high=n-1).astype(np.uint32)
        self.edges_s = np.random.randint(size=(ne, 4), low=0,
                                  high=n-1).astype(np.uint32)
        self.data['a_position'] = np.hstack((0.25 * np.random.randn(n, 2),
                                       np.zeros((n, 1))))
        self.data['a_fg_color'] = 0, 0, 0, 1.0
        color = np.random.uniform(0.5, 1., (n, 3))
        self.data['a_bg_color'] = np.hstack((color, np.zeros((n, 1))))
        self.data['a_size'] = np.random.randint(size=n, low=8*ps, high=20*ps)
        self.data['a_linewidth'] = 8.*ps
        self.data['a_unique_id'] = np.hstack((color, np.ones((n, 1))))
        #self.uniforms['u_graph_size'] = [1.0, 1.0, 1.0]
        self.translate = [0,0,0]
        self.scale = [1,1,1]
        #color = np.random.uniform(0.5, 1., (ne, 3))
        #self.linecolor = np.hstack((color, np.ones((ne, 1))))
        #color = np.random.uniform(0.5, 1., (ne, 3))
        #self.linecolor = np.hstack((color, np.ones((ne, 1))))
        self.u_antialias = 1

        #init dummy vertex and index buffers.
        self.vbo = gloo.VertexBuffer(self.data)
        self.vbo_s = gloo.VertexBuffer(self.clusters)

        #Need to initialize thic/k lines.
        self.index = gloo.IndexBuffer(self.edges)
        self.index_s = gloo.IndexBuffer(self.edges_s)

        #Set the view matrices.
        self.view = np.eye(4, dtype=np.float32)
        self.model = np.eye(4, dtype=np.float32)
        self.projection = np.eye(4, dtype=np.float32)

        #init shaders used for vertices of the full graph.
        self.program = gloo.Program(vert, frag)
        self.program.bind(self.vbo)
        self.program['u_size'] = 1
        self.program['u_antialias'] = self.u_antialias
        self.program['u_model'] = self.model
        self.program['u_view'] = self.view
        self.program['u_projection'] = self.projection
        #self.program['u_graph_size'] = [1.0, 1.0, 1.0]
        self.program['u_picking'] = False

        self.vbo_line = gloo.VertexBuffer(self.line_data)
        #init shades used for the edges in the graph
        self.program_e = gloo.Program(vs, fs)
#        self.program_e['u_size'] = 1
        self.program_e['u_model'] = self.model
        self.program_e['u_view'] = self.view
        self.program_e['u_projection'] = self.projection
        #self.program_e['l_color'] = self.linecolor.astype(np.float32)
        self.program_e.bind(self.vbo_line)
    
        #init shaders used to the vertices in the subgraph graph.
        self.program_s = gloo.Program(vert_s, frag_s)
        self.program_s.bind(self.vbo_s)
        self.program_s['u_model'] = self.model
        self.program_s['u_view'] = self.view
        self.program_s['u_projection'] = self.projection
        #self.program_s['u_graph_size'] = [1.0, 1.0, 1.0]
        self.program_s['u_picking'] = False

        #init shaders used for the subgraph-edges
        self.program_e_s = gloo.Program(vs_s, fs_s)
        self.program_e_s['u_model'] = self.model
        self.program_e_s['u_view'] = self.view
        self.program_e_s['u_projection'] = self.projection
        #self.program_e['l_color'] = self.linecolor.astype(np.float32)
        self.vbo_cluster_lines = gloo.VertexBuffer(self.cluster_line_data)
        self.program_e_s.bind(self.vbo_cluster_lines)


        #set up the viewport and the gl state.
        set_viewport(0, 0, *self.physical_size)

        set_state(clear_color='white', depth_test=True, blend=True,
                  blend_func=('src_alpha', 'one_minus_src_alpha'), depth_func = ('lequal'))
        
        
        self.timer = app.Timer('auto', connect=self.on_timer, start=False)
        #self.constant = app.Timer('auto', connect=self.update, start=True)
        self.num=0
        self.current_color = ""
        self.update_text(self.current_color)
        self.update_color_bar(self.current_color)
        
        print(self.context.config)
        
    def on_timer(self, event):
        #get the temporary positions of the vertices (and edges)
        self.old_pos = np.add(self.old_pos, self.slopes)
        #during each iteration set the new positions in the GPU 
        self.data['a_position'] = self.old_pos
        #Adjust the edges
        edges = self.G.get_edges()
        for e in range(edges.shape[0]):
            idx = int(4*edges[e][2])
            p0 = self.old_pos[edges[e][0], :]
            p1 = self.old_pos[edges[e][1], :]
            d = np.subtract(p1, p0)
            #d_norm = np.multiply(d, 1/np.sqrt(np.power(d[0],2) + np.power(d[1],2)))
            d_norm = d[0:2]
            d_norm = d_norm / np.sqrt(np.power(d_norm[0],2) + np.power(d_norm[1],2))
            norm = np.zeros((2,), dtype=np.float32)
            norm[0] = d_norm[1]
            norm[1] = d_norm[0]*-1

            self.edge_dict[int(edges[e][0]), int(edges[e][1])] = int(edges[e][2])
            self.line_data['a_position'][idx] = p0
            self.line_data['a_normal'][idx] = norm

            self.line_data['a_position'][idx+1] = p1
            self.line_data['a_normal'][idx+1] = norm

            self.line_data['a_position'][idx+2] = p0
            self.line_data['a_normal'][idx+2] = -norm

            self.line_data['a_position'][idx+3] = p1
            self.line_data['a_normal'][idx+3] = -norm
        
        #send data to GPU renderer
        self.vbo.set_data(self.data)
        self.program.bind(self.vbo)
        self.vbo_line = gloo.VertexBuffer(self.line_data)
        self.program_e.bind(self.vbo_line)

        if(self.subgraphs):
            self.update_clusters(self.old_pos)
            edges = self.G_cluster.get_edges()
    #        #generate the vertex buffer and the connections buffer.
            for e in range(edges.shape[0]):
                idx = int(4*edges[e][2])
                p0 = self.cluster_pos[int(edges[e][0])]
                p1 = self.cluster_pos[int(edges[e][1])]
                #p0 = self.G_cluster.vertex_properties["pos"][self.G_cluster.vertex(edges[e][0])]
                #p1 = self.G_cluster.vertex_properties["pos"][self.G_cluster.vertex(edges[e][1])]
                d = np.subtract(p1, p0)
                #d_norm = np.multiply(d, 1/np.sqrt(np.power(d[0],2) + np.power(d[1],2)))
                d_norm = d[0:2]
                d_norm = d_norm / np.sqrt(np.power(d_norm[0],2) + np.power(d_norm[1],2))
                norm = np.zeros((2,), dtype=np.float32)
                norm[0] = d_norm[1]
                norm[1] = d_norm[0]*-1
                #print(np.sqrt(norm[0]*norm[0] + norm[1]*norm[1]))
                #thickness = G.edge_properties["thickness"][e]
                #self.cluster_dict[int(edges[e][0]), int(edges[e][1])] = int(edges[e][2])
                self.cluster_line_data['a_position'][idx] = p0
                self.cluster_line_data['a_normal'][idx] = norm
    
                self.cluster_line_data['a_position'][idx+1] = p1
                self.cluster_line_data['a_normal'][idx+1] = norm
    
                self.cluster_line_data['a_position'][idx+2] = p0
                self.cluster_line_data['a_normal'][idx+2] = -norm
    
                self.cluster_line_data['a_position'][idx+3] = p1
                self.cluster_line_data['a_normal'][idx+3] = -norm
    
            self.vbo_cluster_lines.set_data(self.cluster_line_data)
            self.vbo_s.set_data(self.clusters)
            self.program_s.bind(self.vbo_s)
            self.program_e_s.bind(self.vbo_cluster_lines)

        self.refresh()

    """
        Function that recolors vertices based on the selected statistic
        Maps the statisic stored in G to a colormap passed to the function
        Then updates the necessary color array.
    """    
    def color_vertices(self, G, vertex_property, dtype = False, cm = 'plasma'):
        #if we are visualing the clusters we should use a discrete colormap
        #otherwise use the passed colormap
        if dtype == True:
            G.vertex_properties["RGBA"] = nwt.Network.map_property_to_color(G, G.vertex_properties["clusters"])
        else:
            G.vertex_properties["RGBA"] = nwt.Network.map_property_to_color(G, G.vertex_properties[vertex_property], colormap=cm)
        #set the color and update the Vertices.
        self.current_color = vertex_property
        color = G.vertex_properties["RGBA"].get_2d_array(range(4)).T
        self.data['a_bg_color'] = color
        self.vbo = gloo.VertexBuffer(self.data)
        self.program.bind(self.vbo)
        #self.program_e.bind(self.vbo)
        self.update_text(self.current_color)
        self.update_color_bar(self.current_color)
        self.refresh()
        
    def update_color_buffers(self):
        color = self.G.vertex_properties["RGBA"].get_2d_array(range(4)).T
        self.data['a_bg_color'] = color
        edges = self.G.get_edges()
        for e in range(edges.shape[0]):
            idx = int(4*edges[e][2])
            self.line_data['a_fg_color'][idx] = color[edges[e][0]]
            self.line_data['a_fg_color'][idx+1] = color[edges[e][1]]
            self.line_data['a_fg_color'][idx+2] = color[edges[e][0]]
            self.line_data['a_fg_color'][idx+3] = color[edges[e][1]]



        self.vbo = gloo.VertexBuffer(self.data)
        self.vbo_line = gloo.VertexBuffer(self.line_data)
        self.program.bind(self.vbo)
        self.program_e.bind(self.vbo_line)
        
        
    """
        Function takes a graph and a state and sets all vertices and edges to 
        the transparency defined by state
    """
    def make_all_transparent(self, state):
        for v in self.G.vertices():
            temp = self.G.vertex_properties["RGBA"][v]
            temp[3] = state
            self.G.vertex_properties["RGBA"][v] = temp
        for e in self.G.edges():
            temp = self.G.edge_properties["RGBA"][e]
            temp[3] = state
            self.G.edge_properties["RGBA"][e] = temp
        self.update_color_buffers()

    """
        Maps a statistic of the vertices based on the size of the canvas to size of
        the drawn object.
    """
    def size_vertices(self, G, propertymap):
        size = nwt.Network.map_vertices_to_range(G, [30*self.pixel_scale, 8*self.pixel_scale], propertymap).get_array()
        self.data['a_size'] = size
        self.vbo = gloo.VertexBuffer(self.data)
        self.program.bind(self.vbo)
        #self.program_e.bind(self.vbo)
        self.refresh()


    """
        Function to dim all nodes and edges that do not belong to a cluster chosen 
        in the graph view. Returns a copy of the graph with the alpha channel saved.
        OPTMIZE HERE: could just return an alpha array to reduce memory usage.
    """
    def focus_on_cluster(self, G, c_id):
        G_copy = nwt.gt.Graph(G, directed=False)
        e_color = G_copy.edge_properties["RGBA"].get_2d_array(range(4)).T
        vertices = np.argwhere(self.labels != c_id)
        for v in range(vertices.shape[0]):
            idx = vertices[v][0]
            vtx = G_copy.vertex(idx)
            for e in vtx.all_edges():
                if (int(e.source()), int(e.target())) in self.edge_dict.keys():
                    index = int(self.edge_dict[int(e.source()), int(e.target())])
                    if vtx == int(e.source()):
                        e_color[index][3] = 0.05
                    elif vtx == int(e.target()):
                        e_color[index][3] = 0.05
                else:
                    index = int(self.edge_dict[int(e.target()), int(e.source())])
                    if vtx == int(e.target()):
                        e_color[index][3] = 0.05
                    elif vtx == int(e.source()):
                        e_color[index][3] = 0.05

        G_copy.edge_properties["RGBA"] = G_copy.new_edge_property("vector<double>", vals = e_color)

        return G_copy

    """
        Function that sets the size of the vertices based on the distance from the 
        camera.
    """
    def vertexSizeFromDistance(self, G, camera_pos):
        location = G.vertex_properties["p"].get_2d_array(range(3)).T
        cam_array = np.zeros(location.shape, dtype=np.float32)
        len_array = np.zeros(location.shape[0])
        offset_array = np.zeros(location.shape, dtype=np.float32)
        cam_array[:][0:3] = camera_pos
        offset = [(self.bbu[0]-self.bbl[0])/2, (self.bbu[1]-self.bbl[1])/2, (self.bbu[2]-self.bbl[2])/2]
        location = location - offset
        location = location - camera_pos
        for i in range(location.shape[0]):
            len_array[i] = np.sqrt(np.power(location[i][0],2) + np.power(location[i][1],2) + np.power(location[i][2],2))


        G.vertex_properties['dist_from_camera'] = G.new_vertex_property('float', vals=len_array)
        self.data['a_size'] = nwt.Network.map_vertices_to_range(G, [1*self.pixel_scale, 60*self.pixel_scale], 'dist_from_camera').get_array()


        size = nwt.Network.map_vertices_to_range(G, [1.0, 0.5], 'dist_from_camera').get_array()
        edges = G.get_edges()
        for e in range(edges.shape[0]):
            idx = int(4*edges[e][2])
            self.line_data['a_linewidth'][idx] = size[edges[e][0]]
            self.line_data['a_linewidth'][idx+1] = size[edges[e][1]]
            self.line_data['a_linewidth'][idx+2] = size[edges[e][0]]
            self.line_data['a_linewidth'][idx+3] = size[edges[e][1]]


        #self.vbo = gloo.VertexBuffer(self.data)
        #self.vbo_line = gloo.VertexBuffer(self.line_data)
        #self.program.bind(self.vbo)
        #self.program_e.bind(self.vbo_line)
        #self.update()

    """
        Function that scales the alpha channel of each vertex in the graph based on
        The distance from the camera.
        Sometimes needs to be done separetly.
    """
    def vertexAlphaFromDistance(self, G, camera_pos):
        location = G.vertex_properties["p"].get_2d_array(range(3)).T
        cam_array = np.zeros(location.shape, dtype=np.float32)
        len_array = np.zeros(location.shape[0])
        #offset_array = np.zeros(location.shape, dtype=np.float32)
        cam_array[:][0:3] = camera_pos
        offset = [(self.bbu[0]-self.bbl[0])/2, (self.bbu[1]-self.bbl[1])/2, (self.bbu[2]-self.bbl[2])/2]
        location = location - offset
        location = location - camera_pos
        for i in range(location.shape[0]):
            len_array[i] = np.sqrt(np.power(location[i][0],2) + np.power(location[i][1],2) + np.power(location[i][2],2))


        test = nwt.Network.map_vertices_to_range(G, [0.0, 1.0], 'dist_from_camera').get_array()
        color = G.vertex_properties["RGBA"].get_2d_array(range(4)).T
        for i in range(location.shape[0]):
            color[i][3] = test[i]
        G.vertex_properties["RGBA"] = G.new_vertex_property("vector<double>", vals = color)
        self.data['a_bg_color'] = color

        edges = G.get_edges()
        for e in range(edges.shape[0]):
            idx = int(4*edges[e][2])
            self.line_data['a_fg_color'][idx] = color[edges[e][0]]
            self.line_data['a_fg_color'][idx+1] = color[edges[e][1]]
            self.line_data['a_fg_color'][idx+2] = color[edges[e][0]]
            self.line_data['a_fg_color'][idx+3] = color[edges[e][1]]



        self.vbo = gloo.VertexBuffer(self.data)
        self.vbo_line = gloo.VertexBuffer(self.line_data)
        self.program.bind(self.vbo)
        self.program_e.bind(self.vbo_line)
        self.refresh()

    """
        Sets the edge color based on the the cluster the vertices belongs to
        Propertymap is a VERTEXPROPERTYMAP since the color of the edges is based
        on the clusters the edges belong to.
    """    
    def color_edges(self, G, propertymap="clusters"):
        if propertymap == "clusters":
            for e in G.edges():
                if G.vertex_properties[propertymap][e.source()] == G.vertex_properties[propertymap][e.target()]:
                    G.edge_properties["RGBA"][e] = G.vertex_properties["RGBA"][e.source()]
                else:
                    G.edge_properties["RGBA"][e] = [0.0, 0.0, 0.0, 0.8]

    """
        Test function that only binds the buffer
    """
    def gen_vertex_vbo_minimalist(self):
        self.refresh()
        self.vbo.set_data(self.data)
        self.program.bind(self.vbo)
        self.refresh()

    """
        Helper function that generates the framebuffer object that stores the vertices
        Generates the vertex buffer based on the graph G that is passed to the function
        Sets the color, generates the graph and subgraph color if necessary.
    """
    def gen_vertex_vbo(self, G):
        color = G.vertex_properties["RGBA"].get_2d_array(range(4)).T
        size = nwt.Network.map_vertices_to_range(G, [30*self.pixel_scale, 8*self.pixel_scale], 'degree').get_array()

        position = G.vertex_properties["pos"].get_2d_array(range(3)).T
        #for p in range(position.shape[0]):
        #    position[p][0] = position[p][0] + self.clusters["a_position"][G.vertex_properties["clusters"][G.vertex(p)]][0]
        #    position[p][1] = position[p][1] + self.clusters["a_position"][G.vertex_properties["clusters"][G.vertex(p)]][1]
        #    position[p][2] = position[p][2] + self.clusters["a_position"][G.vertex_properties["clusters"][G.vertex(p)]][2]
        #G.vertex_properties["pos"] = G.new_vertex_property("vector<double>", vals = position)
        edges = G.get_edges();
        edges = edges[:, 0:2]
        #width = nwt.Network.map_edges_to_range(G, [1*self.pixel_scale, 5*self.pixel_scale], 'volume').get_array()
        #ecolor = G.edge_properties["RGBA"].get_2d_array(range(4)).T

        self.data = np.zeros(G.num_vertices(), dtype=[('a_position', np.float32, 3),
                  ('a_fg_color', np.float32, 4),
                  ('a_bg_color', np.float32, 4),
                  ('a_size', np.float32, 1),
                  ('a_linewidth', np.float32, 1),
                  ('a_unique_id', np.float32, 4),
                  ('a_selection', np.float32, 1),
                  ])

        #self.edges = edges.astype(np.uint32)
        self.data['a_position'] = position
        #fg color is the color of the ring
        self.data['a_fg_color'] = 0, 0, 0, 1
        self.data['a_bg_color'] = color
        self.data['a_size'] = size
        self.data['a_linewidth'] = 4.*self.pixel_scale
        self.data['a_unique_id'] = self.gen_vertex_id(G)
        self.data['a_selection'] = G.vertex_properties["selection"].get_array()
        #self.data['a_graph_size'] = [bbu-bbl]

        #self.program['u_graph_size'] = [self.bbu-self.bbl]

        self.vbo = gloo.VertexBuffer(self.data)
        self.gen_line_vbo(G)
        if(self.subgraphs):
            self.vbo_s = gloo.VertexBuffer(self.clusters)
            self.index_s = gloo.IndexBuffer(self.edges_s)
        #self.index = gloo.IndexBuffer(self.edges)
        self.program_e.bind(self.vbo_line)
        self.program.bind(self.vbo)
        if(self.subgraphs):
            #self.program_e_s.bind(self.vbo_s)
            self.program_s.bind(self.vbo_s)
        if DEBUG:
            print(self.view)
        self.refresh()

    """
        Helper function that creates colored "block" lines based on the edges
        in the graph. Generates the framebuffer object and fills it with the relavant data.
        Note that each line segment is saved as a two triangles that share the same
        two points on the centerline, but are offset according to the normal of the
        line segmente to control thickness dynamically.
    """    
    def gen_line_vbo(self, G):
        #Set the data.
        self.line_data = np.zeros(G.num_edges()*4, dtype=[('a_position', np.float32, 3),
                                  ('a_normal', np.float32, 2),
                                  ('a_fg_color', np.float32, 4),
                                  ('a_linewidth', np.float32, 1),
                                  ])
        self.edges = np.random.randint(size=(G.num_edges()*2, 3), low=0,
                                  high=(G.num_edges()-1)).astype(np.uint32)
        color = G.edge_properties["RGBA"].get_2d_array(range(4)).T
        edges = G.get_edges()
        #size need to be changed to the size based on the current property map
        size = nwt.Network.map_vertices_to_range(G, [1.0, 0.5], 'degree').get_array()
        for e in range(edges.shape[0]):
            idx = int(4*edges[e][2])
            p0 = G.vertex_properties["pos"][G.vertex(edges[e][0])]
            p1 = G.vertex_properties["pos"][G.vertex(edges[e][1])]
            d = np.subtract(p1, p0)
            #d_norm = np.multiply(d, 1/np.sqrt(np.power(d[0],2) + np.power(d[1],2)))
            d_norm = d[0:2]
            d_norm = d_norm / np.sqrt(np.power(d_norm[0],2) + np.power(d_norm[1],2))
            norm = np.zeros((2,), dtype=np.float32)
            norm[0] = d_norm[1]
            norm[1] = d_norm[0]*-1
            #print(np.sqrt(norm[0]*norm[0] + norm[1]*norm[1]))
            #thickness = G.edge_properties["thickness"][e]
            thickness = 1.0
            self.edge_dict[int(edges[e][0]), int(edges[e][1])] = int(edges[e][2])
            self.line_data['a_position'][idx] = p0
            self.line_data['a_normal'][idx] = norm
            self.line_data['a_fg_color'][idx] = color[edges[e][2]]
            #a_linewidth is a vector.
            self.line_data['a_linewidth'][idx] = size[edges[e][0]]

            self.line_data['a_position'][idx+1] = p1
            self.line_data['a_normal'][idx+1] = norm
            self.line_data['a_fg_color'][idx+1] = color[edges[e][2]]
            self.line_data['a_linewidth'][idx+1] = size[edges[e][1]]

            self.line_data['a_position'][idx+2] = p0
            self.line_data['a_normal'][idx+2] = -norm
            self.line_data['a_fg_color'][idx+2] = color[edges[e][2]]
            self.line_data['a_linewidth'][idx+2] = size[edges[e][0]]

            self.line_data['a_position'][idx+3] = p1
            self.line_data['a_normal'][idx+3] = -norm
            self.line_data['a_fg_color'][idx+3] = color[edges[e][2]]
            self.line_data['a_linewidth'][idx+3] = size[edges[e][1]]

            self.edges[e*2] = [idx, idx+1, idx+3]
            self.edges[e*2+1] = [idx, idx+2, idx+3]
        
        #Set the buffer object and update the shader programs.
        self.program_e = gloo.Program(vs, fs)
        #self.program_e['l_color'] = self.linecolor.astype(np.float32)
        self.vbo_line = gloo.VertexBuffer(self.line_data)
        self.index = gloo.IndexBuffer(self.edges)
#        self.program_e['u_size'] = 1
        self.program_e['u_model'] = self.model
        self.program_e['u_view'] = self.view
        self.program_e['u_projection'] = self.projection
        self.program_e.bind(self.vbo_line)


    """
        Helper function that generates the edges between the cluster in the layout.
        Color is based on the cluster source/target color and transitions between the
        two.
    """
    def gen_cluster_line_vbo(self, G):
        
        self.G_cluster = nwt.gt.Graph(directed=False)
        self.G_cluster.vertex_properties["pos"] = self.G_cluster.new_vertex_property("vector<double>", val=np.zeros((3,1), dtype=np.float32))
        self.G_cluster.vertex_properties["RGBA"] = self.G_cluster.new_vertex_property("vector<double>", val=np.zeros((4,1), dtype=np.float32))
        for v in range(len(self.cluster_pos)):
            self.G_cluster.add_vertex()
            self.G_cluster.vertex_properties["pos"][self.G_cluster.vertex(v)] = np.asarray(self.cluster_pos[v], dtype=np.float32)
        self.G_cluster.edge_properties["weight"] = self.G_cluster.new_edge_property("int", val = 0)
        self.G_cluster.edge_properties["volume"] = self.G_cluster.new_edge_property("float", val = 0.0)
        #for each edge in the original graph, generate appropriate subgraph edges without repretiions
        #i.e. controls the thichness of the edges in the subgraph view.
        for e in G.edges():
            #if the source and target cluster is not equal to each other
            #add an inter subgraph edge.
            if(G.vertex_properties["clusters"][e.source()] != G.vertex_properties["clusters"][e.target()]):
                t0 = e.source()
                t1 = e.target()
                ct0 = self.G_cluster.vertex(G.vertex_properties["clusters"][t0])
                ct1 = self.G_cluster.vertex(G.vertex_properties["clusters"][t1])
                if(self.G_cluster.edge(ct0, ct1) == None):
                    if(self.G_cluster.edge(ct1, ct0) == None):
                #temp_e.append([G.vertex_properties["clusters"][e.source()], G.vertex_properties["clusters"][e.target()]])
                        self.G_cluster.add_edge(self.G_cluster.vertex(G.vertex_properties["clusters"][t0]), \
                                                 self.G_cluster.vertex(G.vertex_properties["clusters"][t1]))
                        self.G_cluster.edge_properties["weight"][self.G_cluster.edge(self.G_cluster.vertex(G.vertex_properties["clusters"][t0]), \
                                                       self.G_cluster.vertex(G.vertex_properties["clusters"][t1]))] += 1
                        self.G_cluster.edge_properties["volume"][self.G_cluster.edge(self.G_cluster.vertex(G.vertex_properties["clusters"][t0]), \
                                                   self.G_cluster.vertex(G.vertex_properties["clusters"][t1]))] += G.edge_properties["volume"][e]
                        self.G_cluster.vertex_properties["RGBA"][self.G_cluster.vertex(G.vertex_properties["clusters"][t0])]    \
                                                = G.vertex_properties["RGBA"][t0]
                        self.G_cluster.vertex_properties["RGBA"][self.G_cluster.vertex(G.vertex_properties["clusters"][t1])]    \
                                                = G.vertex_properties["RGBA"][t1]
                    else:
                        self.G_cluster.edge_properties["weight"][self.G_cluster.edge(self.G_cluster.vertex(G.vertex_properties["clusters"][t1]), \
                                                       self.G_cluster.vertex(G.vertex_properties["clusters"][t0]))] += 1
                        self.G_cluster.edge_properties["volume"][self.G_cluster.edge(self.G_cluster.vertex(G.vertex_properties["clusters"][t1]), \
                                                   self.G_cluster.vertex(G.vertex_properties["clusters"][t0]))] += G.edge_properties["volume"][e]
                        self.G_cluster.vertex_properties["RGBA"][self.G_cluster.vertex(G.vertex_properties["clusters"][t1])]    \
                                                = G.vertex_properties["RGBA"][t1]
                        self.G_cluster.vertex_properties["RGBA"][self.G_cluster.vertex(G.vertex_properties["clusters"][t0])]    \
                                                = G.vertex_properties["RGBA"][t0]
                else:
                    self.G_cluster.edge_properties["weight"][self.G_cluster.edge(self.G_cluster.vertex(G.vertex_properties["clusters"][t0]), \
                                             self.G_cluster.vertex(G.vertex_properties["clusters"][t1]))] += 1
                    self.G_cluster.edge_properties["volume"][self.G_cluster.edge(self.G_cluster.vertex(G.vertex_properties["clusters"][t0]), \
                                               self.G_cluster.vertex(G.vertex_properties["clusters"][t1]))] += G.edge_properties["volume"][e]
                    self.G_cluster.vertex_properties["RGBA"][self.G_cluster.vertex(G.vertex_properties["clusters"][t0])]    \
                                            = G.vertex_properties["RGBA"][t0]
                    self.G_cluster.vertex_properties["RGBA"][self.G_cluster.vertex(G.vertex_properties["clusters"][t1])]    \
                                            = G.vertex_properties["RGBA"][t1]
        #create a graph that stores the edges of between the clusters
#        self.G_cluster = nwt.gt.Graph(directed=False)
#        self.G_cluster.vertex_properties["pos"] = self.G_cluster.new_vertex_property("vector<double>", val=np.zeros((3,1), dtype=np.float32))
#        self.G_cluster.vertex_properties["RGBA"] = self.G_cluster.new_vertex_property("vector<double>", val=np.zeros((4,1), dtype=np.float32))
#        for v in range(len(self.cluster_pos)):
#            self.G_cluster.add_vertex()
#            self.G_cluster.vertex_properties["pos"][self.G_cluster.vertex(v)] = np.asarray(self.cluster_pos[v], dtype=np.float32)
#        self.G_cluster.edge_properties["weight"] = self.G_cluster.new_edge_property("int", val = 0)
#        #for each edge in the original graph, generate appropriate subgraph edges without repretiions
#        #i.e. controls the thichness of the edges in the subgraph view.
#        for e in G.edges():
#            #if the source and target cluster is not equal to each other
#            #add an inter subgraph edge.
#            if(G.vertex_properties["clusters"][e.source()] != G.vertex_properties["clusters"][e.target()]):
#                #temp_e.append([G.vertex_properties["clusters"][e.source()], G.vertex_properties["clusters"][e.target()]])
#                self.G_cluster.add_edge(self.G_cluster.vertex(G.vertex_properties["clusters"][e.source()]), \
#                                         self.G_cluster.vertex(G.vertex_properties["clusters"][e.target()]))
#                self.G_cluster.edge_properties["weight"][self.G_cluster.edge(self.G_cluster.vertex(G.vertex_properties["clusters"][e.source()]), \
#                                               self.G_cluster.vertex(G.vertex_properties["clusters"][e.target()]))] += 1
#                self.G_cluster.vertex_properties["RGBA"][self.G_cluster.vertex(G.vertex_properties["clusters"][e.source()])]    \
#                                        = G.vertex_properties["RGBA"][e.source()]
#                self.G_cluster.vertex_properties["RGBA"][self.G_cluster.vertex(G.vertex_properties["clusters"][e.target()])]    \
#                                        = G.vertex_properties["RGBA"][e.target()]

        self.G_cluster.vertex_properties["degree"] = self.G_cluster.degree_property_map("total")
        self.cluster_line_data = np.zeros(self.G_cluster.num_edges()*4, dtype=[('a_position', np.float32, 3),
                          ('a_normal', np.float32, 2),
                          ('a_fg_color', np.float32, 4),
                          ('a_linewidth', np.float32, 1),
                          ])
        self.cluster_edges = np.random.randint(size=(self.G_cluster.num_edges()*2, 3), low=0,
                                  high=(G.num_edges()-1)).astype(np.uint32)

        edges = self.G_cluster.get_edges()
        #size need to be changed to the size based on the current property map
        size = nwt.Network.map_edges_to_range(self.G_cluster, [1.0, 0.5], 'weight').get_array()
        color = self.G_cluster.vertex_properties["RGBA"].get_2d_array(range(4)).T
        #generate the vertex buffer and the connections buffer.
        for e in range(edges.shape[0]):
            idx = int(4*edges[e][2])
            p0 = self.G_cluster.vertex_properties["pos"][self.G_cluster.vertex(edges[e][0])]
            p1 = self.G_cluster.vertex_properties["pos"][self.G_cluster.vertex(edges[e][1])]
            d = np.subtract(p1, p0)
            #d_norm = np.multiply(d, 1/np.sqrt(np.power(d[0],2) + np.power(d[1],2)))
            d_norm = d[0:2]
            d_norm = d_norm / np.sqrt(np.power(d_norm[0],2) + np.power(d_norm[1],2))
            norm = np.zeros((2,), dtype=np.float32)
            norm[0] = d_norm[1]
            norm[1] = d_norm[0]*-1
            #print(np.sqrt(norm[0]*norm[0] + norm[1]*norm[1]))
            #thickness = G.edge_properties["thickness"][e]
            self.cluster_dict[int(edges[e][0]), int(edges[e][1])] = int(edges[e][2])
            self.cluster_line_data['a_position'][idx] = p0
            self.cluster_line_data['a_normal'][idx] = norm
            self.cluster_line_data['a_fg_color'][idx] = color[edges[e][0]]
            self.cluster_line_data['a_linewidth'][idx] = size[e]

            self.cluster_line_data['a_position'][idx+1] = p1
            self.cluster_line_data['a_normal'][idx+1] = norm
            self.cluster_line_data['a_fg_color'][idx+1] = color[edges[e][1]]
            self.cluster_line_data['a_linewidth'][idx+1] = size[e]

            self.cluster_line_data['a_position'][idx+2] = p0
            self.cluster_line_data['a_normal'][idx+2] = -norm
            self.cluster_line_data['a_fg_color'][idx+2] = color[edges[e][0]]
            self.cluster_line_data['a_linewidth'][idx+2] = size[e]

            self.cluster_line_data['a_position'][idx+3] = p1
            self.cluster_line_data['a_normal'][idx+3] = -norm
            self.cluster_line_data['a_fg_color'][idx+3] = color[edges[e][1]]
            self.cluster_line_data['a_linewidth'][idx+3] = size[e]

            self.cluster_edges[e*2] = [idx, idx+1, idx+3]
            self.cluster_edges[e*2+1] = [idx, idx+2, idx+3]


        self.program_e_s = gloo.Program(vs_s, fs_s)
        self.index_clusters_s = gloo.IndexBuffer(self.cluster_edges)
        self.vbo_cluster_lines = gloo.VertexBuffer(self.cluster_line_data)

        self.program_e_s['u_model'] = self.model
        self.program_e_s['u_view'] = self.view
        self.program_e_s['u_projection'] = self.projection
        self.program_e_s.bind(self.vbo_cluster_lines)


    """
        Updates the vertex buffers based on the current position of the cluster.
        Updates it's position.    
    """
    def update_cluster_line_vbo(self):

        for v in range(len(self.cluster_pos)):
            self.G_cluster.vertex_properties["pos"][self.G_cluster.vertex(v)] = np.asarray(self.cluster_pos[v], dtype=np.float32)
        #OPTIMIZE HERE to update only one cluster at a time.
        edges = self.G_cluster.get_edges()
        #size need to be changed to the size based on the current property map
        size = nwt.Network.map_edges_to_range(self.G_cluster, [1.0, 0.5], 'weight').get_array()
        color = self.G_cluster.vertex_properties["RGBA"].get_2d_array(range(4)).T
        for e in range(edges.shape[0]):
            idx = int(4*edges[e][2])
            p0 = self.G_cluster.vertex_properties["pos"][self.G_cluster.vertex(edges[e][0])]
            p1 = self.G_cluster.vertex_properties["pos"][self.G_cluster.vertex(edges[e][1])]
            d = np.subtract(p1, p0)
            #d_norm = np.multiply(d, 1/np.sqrt(np.power(d[0],2) + np.power(d[1],2)))
            d_norm = d[0:2]
            d_norm = d_norm / np.sqrt(np.power(d_norm[0],2) + np.power(d_norm[1],2))
            norm = np.zeros((2,), dtype=np.float32)
            norm[0] = d_norm[1]
            norm[1] = d_norm[0]*-1
            #print(np.sqrt(norm[0]*norm[0] + norm[1]*norm[1]))
            #thickness = G.edge_properties["thickness"][e]
            self.cluster_dict[int(edges[e][0]), int(edges[e][1])] = int(edges[e][2])
            self.cluster_line_data['a_position'][idx] = p0
            self.cluster_line_data['a_normal'][idx] = norm
            self.cluster_line_data['a_fg_color'][idx] = color[edges[e][0]]
            self.cluster_line_data['a_linewidth'][idx] = size[e]

            self.cluster_line_data['a_position'][idx+1] = p1
            self.cluster_line_data['a_normal'][idx+1] = norm
            self.cluster_line_data['a_fg_color'][idx+1] = color[edges[e][1]]
            self.cluster_line_data['a_linewidth'][idx+1] = size[e]

            self.cluster_line_data['a_position'][idx+2] = p0
            self.cluster_line_data['a_normal'][idx+2] = -norm
            self.cluster_line_data['a_fg_color'][idx+2] = color[edges[e][0]]
            self.cluster_line_data['a_linewidth'][idx+2] = size[e]

            self.cluster_line_data['a_position'][idx+3] = p1
            self.cluster_line_data['a_normal'][idx+3] = -norm
            self.cluster_line_data['a_fg_color'][idx+3] = color[edges[e][1]]
            self.cluster_line_data['a_linewidth'][idx+3] = size[e]

        self.program_e_s = gloo.Program(vs_s, fs_s)
        self.index_clusters_s = gloo.IndexBuffer(self.cluster_edges)
        self.vbo_cluster_lines = gloo.VertexBuffer(self.cluster_line_data)
        
        self.program_e_s['u_model'] = self.model
        self.program_e_s['u_view'] = self.view
        self.program_e_s['u_projection'] = self.projection
        self.program_e_s.bind(self.vbo_cluster_lines)

    """
        Genererates a unique index for every vertex.
    """    
    def gen_vertex_id(self, G):
        self.color_dict = {}
        base = [0, 0, 0, 255]
        idx = 0
        #colors = cm.get_cmap('Wistia', G.num_vertices()*2)
        v_id = np.zeros((G.num_vertices(), 4), dtype=np.float32)
        for v in G.vertices():
            color = np.multiply(base, 1/255.0)
            v_id[int(v)] = color
            self.color_dict[tuple(color)] = int(v)
            idx += 1
            base = [int(idx/(255*255)), int((idx/255)%255), int(idx%255), 255]

        return(v_id)

    """
        Generates a unique index for every cluster.
    """
    def gen_cluster_id(self, G):
        self.cluster_dict = {}
        base = [0, 0, 0, 255]
        idx = 0
        #colors = cm.get_cmap('Wistia', G.num_vertices()*2)
        v_id = np.zeros((self.n_c, 4), dtype=np.float32)
        for v in range(self.n_c):
            color = np.multiply(base, 1/255.0)
            v_id[int(v)] = color
            self.cluster_dict[tuple(color)] = int(v)
            idx += 1
            base = [int(idx/(255*255)), int((idx/255)%255), int(idx%255), 255]

        return(v_id)


    """
        Generates the bounding box of the radial glyph.
    """
    def gen_cluster_coords(self, center, diameter):
        radius = diameter/2.0
        top = center[1]+radius
        bottom = center[1]-radius
        left = center[0]-radius
        right = center[0]+radius

        positions = [[right, bottom, center[2]],
                    [right, top, center[2]],
                    [left, top, center[2]],
                    [left, bottom, center[2]]]


        values = [[1.0, -1.0],
                  [1.0, 1.0,],
                  [-1.0, 1.0],
                  [-1.0, -1.0]]
        return positions, values


    """
        Generates a hierarchical layout based on the cluster graph (spdf) and subclusters
    """
    def voronoi_layout(self, G = None, n_c = None, G_c = None):
        
        def gen_subclusters(G, G_cluster, i, reposition = False):
            vfilt = np.zeros([G.num_vertices(), 1], dtype='bool')
            labels = G.vertex_properties["clusters"].get_array()
            num_v_in_cluster = len(np.argwhere(labels == i))
            vfilt[np.argwhere(labels == i)] = 1
            vfilt_prop = G.new_vertex_property("bool", vals = vfilt)
            G.set_vertex_filter(vfilt_prop)
            
            g = nwt.gt.Graph(G, prune=True, directed=False)
        
            
            if reposition == True:
                vbetweeness_centrality = g.new_vertex_property("double")
                ebetweeness_centrality = g.new_edge_property("double")
                nwt.gt.graph_tool.centrality.betweenness(g, vprop=vbetweeness_centrality, eprop=ebetweeness_centrality, norm=True)
                g.vertex_properties["bc"] = vbetweeness_centrality
                g.edge_properties["bc"] = ebetweeness_centrality
                g.vertex_properties["pos"] = nwt.gt.sfdp_layout(g, eweight = ebetweeness_centrality)
    
            positions = g.vertex_properties["pos"].get_2d_array(range(2)).T
            center = np.sum(positions, 0)/num_v_in_cluster
            G.clear_filters()
            return g, center
        
        if G_c == None:
            G_c = self.G_cluster
            G_c.vertex_properties["pos"] = nwt.gt.sfdp_layout(G_c, eweight=G_c.edge_properties["volume"], vweight=G_c.vertex_properties["degree"], C = 1.0, K = 10)
            if(G == None):
                G = self.G
            if(n_c == None):
                n_c = self.n_c
        else:
            if(G == None):
                G = self.G
            if(n_c == None):
                n_c = self.n_c
            if self.n_c == G_c.num_vertices():
                for i in range(n_c):
                    self.G_cluster.vertex_properties["pos"][self.G_cluster.vertex(i)] = G_c.vertex_properties["pos"][G_c.vertex(i)] 
            
        
        for i in range(n_c):
            g, center = gen_subclusters(G, G_c, i, reposition=True)
            d = G_c.vertex_properties["pos"][i] - center
            for v in g.vertices():
                G.vertex_properties["pos"][g.vertex_properties["idx"][v]] = g.vertex_properties["pos"][v] + d
                g.vertex_properties["pos"][v] = g.vertex_properties["pos"][v] + d
        #print("stuff")
        


    """
        Layout algorithm that expands the cluster based on the location of the of the clusters
    """
    def expand_based_on_clusters(self, G, n):
        pos = G.vertex_properties["pos"].get_2d_array(range(3)).T
        for p in range(pos.shape[0]):
            pos[p][0] = pos[p][0] - self.clusters["a_position"][G.vertex_properties["clusters"][G.vertex(p)]][0]
            pos[p][1] = pos[p][1] - self.clusters["a_position"][G.vertex_properties["clusters"][G.vertex(p)]][1]
            pos[p][2] = pos[p][2] - self.clusters["a_position"][G.vertex_properties["clusters"][G.vertex(p)]][2]
        G.vertex_properties["pos"] = G.new_vertex_property("vector<double>", vals = pos)
#        for i in range(n):
#            index = 4*i
#            #generate the vertex filter for this cluster
#            num_v_in_cluster = len(np.argwhere(self.labels == i))
#            vfilt = np.zeros([G.num_vertices(), 1], dtype="bool")
#            vfilt[np.argwhere(self.labels == i)] = 1
#            vfilt_prop = G.new_vertex_property("bool", vals = vfilt)
#            G.set_vertex_filter(vfilt_prop)
#
#            #get the filtered properties
#            g = nwt.gt.Graph(G, prune=True, directed=False)
#            positions = g.vertex_properties["pos"].get_2d_array(range(3)).T
#            position = np.sum(positions, 0)/num_v_in_cluster
#            p, v = self.gen_cluster_coords(position, np.sum(g.vertex_properties['degree'].get_array()))
#            self.clusters['a_position'][index:index+4] = np.asarray(p, dtype=np.float32)
#            self.clusters['a_value'][index:index+4] = np.asarray(v, dtype=np.float32)
#            G.clear_filters()
#            self.cluster_pos[i] = position
#        color = G.vertex_properties["RGBA"].get_2d_array(range(4)).T
#        size = nwt.Network.map_vertices_to_range(G, [30*self.pixel_scale, 8*self.pixel_scale], 'degree').get_array()
#
#        position = G.vertex_properties["pos"].get_2d_array(range(3)).T
#        #for p in range(position.shape[0]):
#        #    position[p][0] = position[p][0] + self.clusters["a_position"][G.vertex_properties["clusters"][G.vertex(p)]][0]
#        #    position[p][1] = position[p][1] + self.clusters["a_position"][G.vertex_properties["clusters"][G.vertex(p)]][1]
#        #    position[p][2] = position[p][2] + self.clusters["a_position"][G.vertex_properties["clusters"][G.vertex(p)]][2]
#        #G.vertex_properties["pos"] = G.new_vertex_property("vector<double>", vals = position)
#        
#        
#        edges = G.get_edges();
#        edges = edges[:, 0:2]
#        #width = nwt.Network.map_edges_to_range(G, [1*self.pixel_scale, 5*self.pixel_scale], 'volume').get_array()
#        #ecolor = G.edge_properties["RGBA"].get_2d_array(range(4)).T
#
#        self.data = np.zeros(G.num_vertices(), dtype=[('a_position', np.float32, 3),
#                  ('a_fg_color', np.float32, 4),
#                  ('a_bg_color', np.float32, 4),
#                  ('a_size', np.float32, 1),
#                  ('a_linewidth', np.float32, 1),
#                  ('a_unique_id', np.float32, 4),
#                  ('a_selection', np.float32, 1),
#                  ])
#
#        #self.edges = edges.astype(np.uint32)
#        self.data['a_position'] = position
#        #fg color is the color of the ring
#        self.data['a_fg_color'] = 0, 0, 0, 1
#        self.data['a_bg_color'] = color
#        self.data['a_size'] = size
#        self.data['a_linewidth'] = 4.*self.pixel_scale
#        self.data['a_unique_id'] = self.gen_vertex_id(G)
#        self.data['a_selection'] = G.vertex_properties["selection"].get_array()
#        #self.data['a_graph_size'] = [bbu-bbl]
#
#        self.program['u_graph_size'] = [self.bbu-self.bbl]
#        self.vbo = gloo.VertexBuffer(self.data)
#        self.gen_line_vbo(G)
#        if(self.subgraphs):
#            self.vbo_s = gloo.VertexBuffer(self.clusters)
#            self.index_s = gloo.IndexBuffer(self.edges_s)
#        #self.index = gloo.IndexBuffer(self.edges)
#        self.program_e.bind(self.vbo_line)
#        self.program.bind(self.vbo)
#        if(self.subgraphs):
#            #self.program_e_s.bind(self.vbo_s)
#            self.program_s.bind(self.vbo_s)
#        if DEBUG:
#            print(self.view)
#        self.refresh()


    """
        Function that updates the cluster positions based on new vertex positions
        in the graph. Primarity used for animation.
    """
    def update_clusters(self, new_pos):
        clusters = self.G.vertex_properties["clusters"].get_array().T
        for i in range(self.n_c):
            idx = np.argwhere(clusters == i)
            pos = np.sum(new_pos[idx], 0)/len(idx)
            self.cluster_pos[i] = pos.reshape(3)
            index = i*4
            p, v = self.gen_cluster_coords(self.cluster_pos[i], self.cluster_size[i])
            self.clusters['a_position'][index:index+4] = np.asarray(p, dtype=np.float32)
            self.clusters['a_value'][index:index+4] = np.asarray(v, dtype=np.float32)
            self.G_cluster.vertex_properties["pos"][self.G_cluster.vertex(i)] = self.cluster_pos[i]
            
    """
        Function that creates the clusters, assuming that all the data is set already.

    """
    def gen_cluster_vbo(self, G, bbl, bbu, num_clusters, edge_metric = 'volume', vertex_metric = 'degree', update_color = True):
               #add colormap
        if(update_color == True):
            G.vertex_properties["RGBA"] = nwt.Network.map_property_to_color(G, G.vertex_properties["clusters"])

        #generate an empty property set for the clusters.
        self.clusters = np.zeros(num_clusters*4, dtype=[('a_position', np.float32, 3),
                      ('a_value', np.float32, 2),
                      ('a_bg_color', np.float32, 4),
                      ('a_cluster_color', np.float32, 4),
                      ('a_arc_length', np.float32, 1),
                      ('a_outer_arc_length', np.float32, 4),
                      ('a_unique_id', np.float32, 4),
                      ])
        self.edges_s = np.random.randint(size=(num_clusters*2, 3), low=0,
                                  high=4).astype(np.uint32)
        #fill the foreground color as halo
        #self.clusters['a_fg_color'] = 1., 1., 1., 0.0
        #self.clusters['a_linewidth'] = 4.*self.pixel_scale

        G.vertex_properties["pos"] = nwt.gt.sfdp_layout(G, groups = G.vertex_properties["clusters"], pos = G.vertex_properties["pos"], C = 1.0, K = 10)
        temp = []
        temp_pos = []
        #Find the global total of the metric.
        global_metric = np.sum(G.edge_properties[edge_metric].get_array(), 0)
        unique_color = self.gen_cluster_id(G)

        #generate the property values for every cluster
        for i in range(num_clusters):
            idx = 4*i
            #generate the vertex filter for this cluster
            num_v_in_cluster = len(np.argwhere(self.labels == i))
            vfilt = np.zeros([G.num_vertices(), 1], dtype="bool")
            vfilt[np.argwhere(self.labels == i)] = 1
            vfilt_prop = G.new_vertex_property("bool", vals = vfilt)
            G.set_vertex_filter(vfilt_prop)

            #get the filtered properties
            g = nwt.gt.Graph(G, prune=True, directed=False)
            positions = g.vertex_properties["pos"].get_2d_array(range(3)).T
            position = np.sum(positions, 0)/num_v_in_cluster

            #calculate the arclength for the global statistic
            arc_length = np.sum(g.edge_properties[edge_metric].get_array(), 0)/global_metric*np.pi*2
            arc_length_vertex = np.ones((4,1), dtype = np.float32)
            array = g.vertex_properties[vertex_metric].get_array()

            #calculate metric distribution and turn it into arc_lengths
            t_vertex_metric = np.sum(array)
            arc_length_vertex[0] = np.sum(array < 2)/t_vertex_metric
            arc_length_vertex[1] = np.sum(array == 2)/t_vertex_metric
            arc_length_vertex[2] = np.sum(array == 3)/t_vertex_metric
            arc_length_vertex[3] = np.sum(array > 3)/t_vertex_metric

            #arc_length_vertex = np.asarray(arc_length_vertex, dtype = np.float32)
            #arc_length_vertex = (max(arc_length_vertex) - min(arc_length_vertex)) \
            #* (arc_length_vertex- min(arc_length_vertex))
            for j in range(len(arc_length_vertex)):
                if j != 0:
                    arc_length_vertex[j] += arc_length_vertex[j-1]
            if DEBUG:
                print("arc_length before ", arc_length_vertex, " and sum to ", sum(arc_length_vertex))
            arc_length_vertex = np.asarray(arc_length_vertex, dtype = np.float32)
            arc_length_vertex = (np.pi - -np.pi)/(max(arc_length_vertex) - min(arc_length_vertex)) \
            * (arc_length_vertex- min(arc_length_vertex)) + (-np.pi)
            if DEBUG:
                print(arc_length_vertex)
            #print(arc_length)


            temp_pos.append(position)

            #generate the color for every vertex,
            #since all vertices belong to the same cluster we can check only
            #one vertex for the cluster color.

            self.clusters['a_cluster_color'][idx:idx+4] = g.vertex_properties["RGBA"][g.vertex(0)]
            self.clusters['a_bg_color'][idx:idx+4] = [0.1, 0.1, 0.1, 1.0]
            self.clusters['a_unique_id'][idx:idx+4] = unique_color[i]

            #The arc-length representing one global metric.
            self.clusters['a_arc_length'][idx:idx+4] = arc_length
            self.clusters['a_outer_arc_length'][idx:idx+4] = arc_length_vertex[:].T

            temp.append(np.sum(g.vertex_properties['degree'].get_array()))
            G.clear_filters()
        if DEBUG:
            print(self.clusters['a_outer_arc_length'])
        maximum = max(temp)
        minimum = min(temp)
        temp = ((temp-minimum)/(maximum-minimum)*(60*self.pixel_scale)+20*self.pixel_scale)*2.0
        for i in range(num_clusters):
            index = i*4
            index_t = i*2
            p, v = self.gen_cluster_coords(temp_pos[i], temp[i])
            self.clusters['a_position'][index:index+4] = np.asarray(p, dtype=np.float32)
            self.clusters['a_value'][index:index+4] = np.asarray(v, dtype=np.float32)

            self.edges_s[index_t] = [index, index+1, index+2]
            self.edges_s[index_t+1] = [index, index+2, index+3]
            #self.edges_s[i][0:4] = np.asarray(range(index, index+4), dtype=np.uint32)
            #self.edges_s[i]
        self.cluster_pos = temp_pos
        self.cluster_size = temp
        #self.expand_based_on_clusters(G, self.n_c)
        G.clear_filters()
#        self.edges_s[1][0:4] = np.asarray(range(0, 0+4), dtype=np.uint32)
#        self.edges_s[1][4] = 0
#        self.edges_s[1][5] = 0+2
#
#        self.edges_s[0][0:4] = np.asarray(range(index, index+4), dtype=np.uint32)
#        self.edges_s[0][4] = index
#        self.edges_s[0][5] = index+2
        #self.clusters['a_size'] = temp
        self.gen_cluster_line_vbo(G)
        #self.program_s['u_graph_size'] = [bbu-bbl]
        #if len(temp_e) > 0:
        #    self.edges_s = np.unique(np.asarray(temp_e, np.uint32), axis=0)
        #else:
        #    self.edges_s = []
        #print(self.edges_s)

    """
        Function that generates the clusters for an unclustered graph
        These are to be represented by the arcs
    """    
    def gen_clusters(self, G, bbl, bbu, n_c = None, edge_metric = 'volume', vertex_metric = 'degree'):

        #Generate the clusters
        self.labels = nwt.Network.spectral_clustering(G,'length', n_clusters = n_c)
        bb = nwt.AABB(G)
        #print("FLJKKHDFLKJFDLKJFDLKJ ", m)
        pts = []
        x, y, z = bb.project_grid(3)
        for i in range(3):
            for j in range(3):
                for k in range(3):
                    pts.append(np.array([x[i], y[j], z[k]]))
        
        
        #self.labels = nwt.Network.spectral_clustering(G,'length')
        #Add clusters as a vertex property
        G.vertex_properties["clusters"] = G.new_vertex_property("int", vals=self.labels)
        num_clusters = len(np.unique(self.labels))
        self.n_c = n_c
        new_indices = []
        pos = G.vertex_properties["p"].get_2d_array(range(3)).T
        
        #for each cluster find the average vertex position and match to closest point
        #in the unique grid.
        for i in range(n_c):
            point = np.sum(pos[np.argwhere(self.labels == i)], axis=0)/len(np.argwhere(self.labels == i))
            d = 100000000.0
            idx = -1
            for j in range(len(pts)):
                dist = np.sqrt(np.power(pts[j][0]-point[0,0],2) + np.power(pts[j][1]-point[0,1],2) + np.power(pts[j][2]-point[0,2],2))
                if dist < d:
                    d = dist
                    idx = j
            new_indices.append(idx)
            pts[idx] = np.array([100000000.0, 1000000000.0, 100000000.0])
        #since there are more points than clusters, we need to make the indices range from
        #[0, n_c)
        j=0
        unique_indices = np.array(new_indices)
        for i in range(n_c):
            idx = np.argmin(new_indices)
            unique_indices[idx] = j
            j += 1
            new_indices[idx] = 100
            
        lbl = np.zeros(self.labels.shape)
        for i in range(n_c):
            idxs = np.argwhere(self.labels == i)
            new_idx = np.argwhere(unique_indices == i)
            lbl[idxs] = unique_indices[i]
            
        self.labels = lbl
        G.vertex_properties["clusters"] = G.new_vertex_property("int", vals=self.labels)
        self.gen_cluster_vbo(self.G, bbl, bbu, num_clusters, edge_metric, vertex_metric)
        


    """
        Function that expands that generates the layout and updates the buffer
    
    """
    def expand_clusters(self, G, n_c):
        self.expand_based_on_clusters(G, n_c)
        self.gen_cluster_line_vbo(G)
        if(self.subgraphs):
            self.vbo_s = gloo.VertexBuffer(self.clusters)
            self.index_s = gloo.IndexBuffer(self.edges_s)
        self.program_e.bind(self.vbo_line)
        self.program.bind(self.vbo)
        if(self.subgraphs):
            self.program_s.bind(self.vbo_s)
        if DEBUG:
            print(self.view)
        self.refresh()


    """
        Function for generating a distance field based on the clusters in the 
        clustered 3D network.
    """
    def distancefield(self, G):
        
        import scipy as sp
        #generate a meshgrid of the appropriate size and resolution to surround the network
        #get the space occupied by the network
        lower = self.bbl
        upper = self.bbu
        R = np.asarray(np.floor(abs(lower-upper)), dtype=np.int)

        x = np.linspace(lower[0], upper[0], R[0])   #get the grid points for uniform sampling of this space
        y = np.linspace(lower[1], upper[1], R[1])
        z = np.linspace(lower[2], upper[2], R[2])
        X, Y, Z = np.meshgrid(x, y, z, indexing='ij')
               
        Q = np.stack((X, Y, Z), 3)
        #get a list of all node positions in the network
        P = []
        #get a mirrored list of all the point labels
        L = []
      
        for e in G.edges():
            X_p = G.edge_properties["x"][e]
            Y_p = G.edge_properties["y"][e]
            Z_p = G.edge_properties["z"][e]
            l = list(np.array([X_p,Y_p,Z_p]).T)
            #generate points list foe each edge

            P = P + l
            #generate labels list for each edge
            if G.vertex_properties["clusters"][e.source()] == G.vertex_properties["clusters"][e.target()]:
                c = G.vertex_properties["clusters"][e.source()]
                for i in range(len(l)):
                    L.append(c)
            #if source and target have the same label, all points have that label
            else:
                #if source != target label, then point takes on the closest label
                source = []
                source.append(0.0)
                target = []
                for i in range(1, len(l)):
                    dist = math.sqrt(pow(l[i][0]-l[i-1][0],2) + pow(l[i][1]-l[i-1][1],2) + pow(l[i][2]-l[i-1][2],2))
                    source.append(dist + source[len(source)-1])
                target = source[::-1]
                for i in range(len(l)):
                    if source[i] > target[i]:
                        L.append(G.vertex_properties["clusters"][e.source()])
                    else:
                        L.append(G.vertex_properties["clusters"][e.target()])
                        
        #turn that list into a Numpy array so that we can create a KD tree
        P = np.array(P)
      
        #generate a KD-Tree out of the network point array
        tree = sp.spatial.cKDTree(P)
        
        D, I = tree.query(Q)
        C = np.zeros(I.shape, dtype=np.int)
        for i in range(I.shape[0]):
            for j in range(I.shape[1]):
                for k in range(I.shape[2]):
                    C[i,j,k] = L[I[i,j,k]]
        
        self.write_VTK_R(G, "./test_field.vtk", Q, C, X, Y, Z)
        return D, x, y, z, C

    """
        Function for saving the distance field based on the clusters in the 
        clustered 3D network.
    """
    def write_VTK_R(self, G, filepath, Q, C, X, Y, Z):\
    
        from pyevtk.hl import gridToVTK
        from pyevtk.hl import imageToVTK
        from pyevtk.vtk import VtkFile, VtkImageData
        import vtk
        #T = C.reshape(C.shape[0]*C.shape[1]*C.shape[2])
        #C = T.reshape((C.shape[0], C.shape[1], C.shape[2]), order = 'C')
        ColorR = np.zeros((C.shape[0], C.shape[1], C.shape[2]))
        ColorG = np.zeros((C.shape[0], C.shape[1], C.shape[2]))
        ColorB = np.zeros((C.shape[0], C.shape[1], C.shape[2]))
        ColorA = np.zeros((C.shape[0], C.shape[1], C.shape[2]))
        #ColorR = ColorG = ColorB = ColorA = np.chararray((P.shape[0], P.shape[1], P.shape[2]))
        G.vertex_properties["RGBA"] = nwt.Network.map_property_to_color(G, G.vertex_properties["clusters"])
        self.color_edges(G)
        thisdict = {}
        otherdict = {}
        for v in G.vertices():
            thisdict[G.vertex_properties["clusters"][v]] = G.vertex_properties["RGBA"][v]
            color = G.vertex_properties["RGBA"][v].get_array()
            c = '#%02x%02x%02x%02x' % (int(color[0]*255), int(color[1]*255), int(color[2]*255), int(color[3]*255*0.3))
            otherdict[G.vertex_properties["clusters"][v]] = c
        
        print(thisdict, file=open('myfile.txt', 'w'))    
        i = 0
        for i in range(C.shape[0]):
            for j in range(C.shape[1]):
                for k in range(C.shape[2]):
                    c = thisdict[C[i,j,k]]
                    ColorR[i,j,k] = c[0]
                    ColorG[i,j,k] = c[1]
                    ColorB[i,j,k] = c[2]
                    ColorA[i,j,k] = c[3]
        
        
    #    fig = plt.figure()
    #    ax = fig.gca(projection='3d')
    #    for e in G.edges():
    #        X = G.edge_properties["x"][e]
    #        Y = G.edge_properties["y"][e]
    #        Z = G.edge_properties["z"][e]
    #        color = G.edge_properties['RGBA'][e].get_array()
    #        c = '#%02x%02x%02x' % (int(color[0]*255), int(color[1]*255), int(color[2]*255))
    #        ax.plot(X,Y,Z, color=c)
    #        print("plotting line")
    #    
    #    
    #    print("generating cells")
    #    x, y, z = np.indices(np.array(C.shape) + 1).astype(float)
    #    filled = np.ones(C.shape)
    #    print("replacing dict")
    #    vox = replace_with_dict(C, otherdict)
    #    
    #    print("plotting voxels")
    #    ax.voxels(x, y, z, filled, facecolors=vox)
        
        
        #ax.imshow(np.stack((ColorR[:,:,0], ColorG[:,:,0], ColorB[:,:,0]), axis = 2))
        
        #plt.show()
            
            
            
        
        
        filename = "./image_fixed.vti"
        imageData = vtk.vtkImageData()
        imageData.SetDimensions(C.shape[0], C.shape[1], C.shape[2])
        imageData.SetOrigin(0.0, 0.0, 0.0)
        imageData.SetSpacing(1.0, 1.0, 1.0)
        if vtk.VTK_MAJOR_VERSION <= 5:
            imageData.SetNumberOfScalarComponents(4)
            imageData.SetScalarTypeToDouble()
        else:
            imageData.AllocateScalars(vtk.VTK_DOUBLE, 4)
            
        for z in range(C.shape[2]):
            for y in range(C.shape[1]):
                for x in range(C.shape[0]):
                    imageData.SetScalarComponentFromDouble(x, y, z, 0, ColorR[x,y,z])
                    imageData.SetScalarComponentFromDouble(x, y, z, 1, ColorG[x,y,z])
                    imageData.SetScalarComponentFromDouble(x, y, z, 2, ColorB[x,y,z])
                    imageData.SetScalarComponentFromDouble(x, y, z, 3, ColorA[x,y,z])
        
        
        writer = vtk.vtkXMLImageDataWriter()
        writer.SetFileName(filename)
        if vtk.VTK_MAJOR_VERSION <= 5:
            writer.SetInputConnection(imageData.GetProducerPort())
        else:
            writer.SetInputData(imageData)
        
        writer.Write()
        nwt.Network.write_vtk(G, "./vessels_fixed.vtk", binning = False)

    def set_graph(self, G, bbl, bbu, subgraph = False):
        self.G = G
        self.bbl = bbl
        self.bbu = bbu
        clear(color=True, depth=True)
        self.subgraphs = subgraph
        self.current_color = "clusters"
        self.color_edges(G)                    
        print(self.G)
        color = G.vertex_properties["RGBA"].get_2d_array(range(4)).T
        size = nwt.Network.map_vertices_to_range(G, [30*self.pixel_scale, 8*self.pixel_scale], 'degree').get_array()

        position = G.vertex_properties["pos"].get_2d_array(range(3)).T
        #for p in range(position.shape[0]):
        #    position[p][0] = position[p][0] + self.clusters["a_position"][G.vertex_properties["clusters"][G.vertex(p)]][0]
        #    position[p][1] = position[p][1] + self.clusters["a_position"][G.vertex_properties["clusters"][G.vertex(p)]][1]
        #    position[p][2] = position[p][2] + self.clusters["a_position"][G.vertex_properties["clusters"][G.vertex(p)]][2]
        #G.vertex_properties["pos"] = G.new_vertex_property("vector<double>", vals = position)
        edges = G.get_edges();
        edges = edges[:, 0:2]
        #width = nwt.Network.map_edges_to_range(G, [1*self.pixel_scale, 5*self.pixel_scale], 'volume').get_array()
        #ecolor = G.edge_properties["RGBA"].get_2d_array(range(4)).T

        self.data = np.zeros(G.num_vertices(), dtype=[('a_position', np.float32, 3),
                  ('a_fg_color', np.float32, 4),
                  ('a_bg_color', np.float32, 4),
                  ('a_size', np.float32, 1),
                  ('a_linewidth', np.float32, 1),
                  ('a_unique_id', np.float32, 4),
                  ('a_selection', np.float32, 1),
                  ])

        #self.edges = edges.astype(np.uint32)
        self.data['a_position'] = position
        #fg color is the color of the ring
        self.data['a_fg_color'] = 0, 0, 0, 1
        self.data['a_bg_color'] = color
        self.data['a_size'] = size
        self.data['a_linewidth'] = 4.*self.pixel_scale
        self.data['a_unique_id'] = self.gen_vertex_id(G)
        self.data['a_selection'] = G.vertex_properties["selection"].get_array()
        #self.data['a_graph_size'] = [bbu-bbl]

        #self.program['u_graph_size'] = [bbu-bbl]

        self.vbo = gloo.VertexBuffer(self.data)
        self.gen_line_vbo(G)
        #self.gen_cylinder_vbo(G)
        if(self.subgraphs):
            self.labels = self.G.vp["clusters"].get_array()
            self.gen_cluster_vbo(self.G, bbl, bbu, self.n_c)
            self.vbo_s = gloo.VertexBuffer(self.clusters)
            self.index_s = gloo.IndexBuffer(self.edges_s)
        #self.index = gloo.IndexBuffer(self.edges)
        self.program_e.bind(self.vbo_line)
        self.program.bind(self.vbo)
        if(self.subgraphs):
            #self.program_e_s.bind(self.vbo_s)
            self.program_s.bind(self.vbo_s)
        if DEBUG:
            print(self.view)
        self.update_text(self.current_color)
        self.update_color_bar(self.current_color)
        self.refresh()
   
    
    def update_text(self, text):
        self.t1 = Text(text, parent=self.scene, color = 'black', method='gpu', anchor_x = 'right', anchor_y='top')
        self.t1.font_size = 24
        #self.t1.anchor_y = 'top'
        #self.t1.anchor_x = 'right'
#        print(self.t1.bounds(0), self.t1.bounds(1))
        self.t1.pos = self.size[0]-10, self.size[1] // 24
        self.refresh()
        
    def update_color_bar(self, color_property):
        if color_property != "":
            prop = self.G.vp[color_property].get_array().T
            mx = max(prop)
            mn = min(prop)
        else:
            mx = 1.0
            mn = 0.0
        if(color_property=="clusters"):
            cm = 'tab20'
        else:
            cm = 'plasma'
        self.c_bar = ColorBar(cmap=cm, orientation = 'bottom', 
                              size = (self.size[0] // 3, self.size[1] // 24), clim = (mn, mx),
                              border_width = 10.0,border_color = 'white', 
                              parent=self.scene, 
                              pos=(self.size[0] // 3 // 2 + 20, self.size[1] // 24),
                              padding = (100, 100)
                              )
        self.refresh()
        
    """
        Loads the data G and generates all the buffers necessary as well as performs
        spectral clustering on the graph passed if the subgraph is set to true.
    """
    def set_data(self, G, bbl, bbu, subgraph=True, G_other = None):
        
        def in_hull(point, hull, tolerance=1e-6):
            return all(
                (np.dot(eq[:-1], point) + eq[-1] <= tolerance)
                for eq in hull.equations)
            
#        def in_hull(p, hull):
#            if not isinstance(hull,Delaunay):
#                hull = Delaunay(hull)
#        
#            return hull.find_simplex(p)>=0
        
        if DEBUG:
            print("Setting data")
        self.G = G
        self.bbl = bbl
        self.bbu = bbu
        clear(color=True, depth=True)
        self.subgraphs = True
        self.current_color = "clusters"

        if(subgraph==True and G_other == None):
            self.gen_clusters(G, bbl, bbu, n_c=19)
            self.G.vertex_properties["idx"] = self.G.vertex_index
            #color based on clusters
            self.color_edges(G)
        else:
            #polygons = []
            self.G.vertex_properties["idx"] = self.G.vertex_index
            self.G.vertex_properties["clusters"] = self.G.new_vertex_property("int", vals=np.full(self.G.num_vertices(), -1, dtype="int"))
            num_clusters = len(np.unique(G_other.vertex_properties["clusters"].get_array().T))
            color_lookup = []
            lbls = G_other.vertex_properties["clusters"].get_array().T
            for i in range(num_clusters):
                idx = np.where(lbls == i)[0][0]
                color_lookup.append(G_other.vertex_properties["RGBA"][G_other.vertex(idx)])
                
                
            self.n_c = num_clusters
            D, x, y, z, C = self.distancefield(G_other)
            print(len(x), len(y), len(z))
            for v in self.G.vertices():
                p = self.G.vertex_properties["p"][v]
                x_temp = np.fabs(x - p[0])
                idx_x = x_temp.argmin()
                y_temp = np.fabs(y - p[1])
                idx_y = y_temp.argmin()
                z_temp = np.fabs(z - p[2])
                idx_z = z_temp.argmin()
                cluster = C[idx_x][idx_y][idx_z]
                self.G.vertex_properties["clusters"][v] = cluster
                self.G.vertex_properties["RGBA"][v] = color_lookup[cluster]
                
            
            
            ###############OLD Comparison mechanic########################
#            polygons = []
#            for i in range(num_clusters):
#                #num_v_in_cluster = len(np.argwhere(self.labels == i))
#                vfilt = np.zeros([G_other.num_vertices(), 1], dtype="bool")
#                vfilt[np.argwhere(G_other.vertex_properties["clusters"].get_array().T == i)] = 1
#                vfilt_prop = G_other.new_vertex_property("bool", vals = vfilt)
#                G_other.set_vertex_filter(vfilt_prop)
#            
#                #get the filtered properties
#                g = nwt.gt.Graph(G_other, prune=True, directed=False)
#                color = g.vertex_properties["RGBA"][g.vertex(0)]
#                positions = g.vertex_properties["p"].get_2d_array(range(3)).T
#                hull = ConvexHull(positions)
#                #hull = Delaunay(positions)
#                #hull = multipoint.convex_hull
#                polygons.append(hull)
#                G_other.clear_filters()
#                for v in self.G.vertices():
#                    if in_hull(self.G.vertex_properties["p"][v], hull) and self.G.vertex_properties["clusters"][v] == -1:
#                        self.G.vertex_properties["clusters"][v] = i
#                        self.G.vertex_properties["RGBA"][v] = color
##                    if hull.contains(Point(self.G.vertex_properties["p"][v])):
##                        self.G.vertex_properties["clusters"][v] = i
##                        self.G.vertex_properties["RGBA"][v] = color
#            
#            unassigned = np.argwhere(self.G.vertex_properties["clusters"].get_array().T == -1)
#            while len(unassigned > 0):
#                for i in range(len(unassigned)):
#                    gen = self.G.vertex(unassigned[i]).all_neighbors()
#                    neighbors = []
#                    neighbors_clusters = []
#                    for j in gen:
#                        neighbors.append(j)
#                        neighbors_clusters.append(self.G.vertex_properties["clusters"][j])
#                    if len(np.unique(neighbors_clusters)) == 1 and np.unique(neighbors_clusters[0]) != -1:
#                        self.G.vertex_properties["clusters"][self.G.vertex(unassigned[i])] = \
#                            self.G.vertex_properties["clusters"][neighbors[0]]
#                        self.G.vertex_properties["RGBA"][self.G.vertex(unassigned[i])] = \
#                            self.G.vertex_properties["RGBA"][neighbors[0]]
#                    else:
#                        c, count = np.unique(neighbors_clusters, return_counts=True)
#                        for k in range(len(c)):
#                            if c[k] == -1:
#                                c = np.delete(c, k)
#                                count = np.delete(count, k)
#                                break
#                        if len(c) > 0:
#                            cluster = np.argwhere(count == max(count))[0]
#                            self.G.vertex_properties["clusters"][self.G.vertex(unassigned[i])] = c[cluster[0]]
#                            for v in range(len(neighbors)):
#                                if self.G.vertex_properties["clusters"][self.G.vertex(unassigned[i])] == c[cluster[0]]:
#                                    self.G.vertex_properties["RGBA"][self.G.vertex(unassigned[i])] = \
#                                        self.G.vertex_properties["RGBA"][neighbors[v]]
#                unassigned = np.argwhere(self.G.vertex_properties["clusters"].get_array().T == -1)
#                    #print("stuff")
#                    #for j in range(len(neighbors_clusters)):
#                        
#            #self.G.vertex_properties["RGBA"] = nwt.Network.map_property_to_color(self.G, self.G.vertex_properties["clusters"])
            temp = self.G.vertex_properties["clusters"].get_array().T
            print(np.unique(temp))
            self.labels = copy.copy(temp)
#            c = np.unique(temp)
#            idx = 0
#            for i in range(len(c)):
#                self.labels[np.argwhere(temp == c[i])] = idx
#                idx += 1
#                
            ###############/OLD Comparison mechanic########################
            self.G.vertex_properties["clusters"] = self.G.new_vertex_property("int", vals = self.labels)
            self.n_c = len(np.unique(self.labels))
            self.gen_cluster_vbo(self.G, bbl, bbu, self.n_c, update_color = False)
            self.color_edges(self.G)
                        

        color = G.vertex_properties["RGBA"].get_2d_array(range(4)).T
        size = nwt.Network.map_vertices_to_range(G, [30*self.pixel_scale, 8*self.pixel_scale], 'degree').get_array()

        position = G.vertex_properties["pos"].get_2d_array(range(3)).T
        #for p in range(position.shape[0]):
        #    position[p][0] = position[p][0] + self.clusters["a_position"][G.vertex_properties["clusters"][G.vertex(p)]][0]
        #    position[p][1] = position[p][1] + self.clusters["a_position"][G.vertex_properties["clusters"][G.vertex(p)]][1]
        #    position[p][2] = position[p][2] + self.clusters["a_position"][G.vertex_properties["clusters"][G.vertex(p)]][2]
        #G.vertex_properties["pos"] = G.new_vertex_property("vector<double>", vals = position)
        edges = G.get_edges();
        edges = edges[:, 0:2]
        #width = nwt.Network.map_edges_to_range(G, [1*self.pixel_scale, 5*self.pixel_scale], 'volume').get_array()
        #ecolor = G.edge_properties["RGBA"].get_2d_array(range(4)).T

        self.data = np.zeros(G.num_vertices(), dtype=[('a_position', np.float32, 3),
                  ('a_fg_color', np.float32, 4),
                  ('a_bg_color', np.float32, 4),
                  ('a_size', np.float32, 1),
                  ('a_linewidth', np.float32, 1),
                  ('a_unique_id', np.float32, 4),
                  ('a_selection', np.float32, 1),
                  ])

        #self.edges = edges.astype(np.uint32)
        self.data['a_position'] = position
        #fg color is the color of the ring
        self.data['a_fg_color'] = 0, 0, 0, 1
        self.data['a_bg_color'] = color
        self.data['a_size'] = size
        self.data['a_linewidth'] = 4.*self.pixel_scale
        self.data['a_unique_id'] = self.gen_vertex_id(G)
        self.data['a_selection'] = G.vertex_properties["selection"].get_array()
        #self.data['a_graph_size'] = [bbu-bbl]

        #self.program['u_graph_size'] = [bbu-bbl]

        self.vbo = gloo.VertexBuffer(self.data)
        self.gen_line_vbo(G)
        #self.gen_cylinder_vbo(G)
        if(self.subgraphs):
            self.vbo_s = gloo.VertexBuffer(self.clusters)
            self.index_s = gloo.IndexBuffer(self.edges_s)
        #self.index = gloo.IndexBuffer(self.edges)
        self.program_e.bind(self.vbo_line)
        self.program.bind(self.vbo)
        if(self.subgraphs):
            #self.program_e_s.bind(self.vbo_s)
            self.program_s.bind(self.vbo_s)
        if DEBUG:
            print(self.view)
        self.update_text(self.current_color)
        self.update_color_bar(self.current_color)
        self.refresh()

    """
        Function that changes and redraws the buffer during a resize event.
    """
    def on_resize(self, event):
        set_viewport(0, 0, *event.physical_size)
        self.fbo = gloo.FrameBuffer(color=gloo.RenderBuffer(self.size[::-1]), depth=gloo.RenderBuffer(self.size[::-1]))
        self.update_text(self.current_color)
        self.update_color_bar(self.current_color)
        self.refresh()
        app.Canvas.update(self)

    """
        Overloaded function that is called during every self.update() call
    """
    def on_draw(self, event):
        gloo.clear()
        clear(color='white', depth=True)
        self.program_e.draw('triangles', indices=self.index)
        self.program.draw('points')
        #self.program_e.draw('lines')
        if(self.subgraphs):
            self.program_e_s.draw('triangles', indices=self.index_clusters_s)
            self.program_s.draw('triangles', indices=self.index_s)
        #print("updated  ", self.num)
        #self.num += 1
        self.t1.draw()
        self.c_bar.draw()
        #self._u
        #self._update_pending = True
        #app.Canvas.update(self)
        #super(scene.SceneCanvas, self).update()    #This forces redrawd

    """
        refreshes the canvas and forces the redraw. A workaround for issue in
        vispy 0.6.3
    """
    def refresh(self):
        self.update_view_global()
        self.update()
        app.Canvas.update(self)

#    """
#        A function to animate from one layout to another layout given a new G.
#    """
    def animate(self, old_pos, new_pos):
            
#        old_pos = self.G.vertex_properties["pos"].get_2d_array(range(3)).T
#        new_pos = new_G.vertex_properties["pos"].get_2d_array(range(3)).T
        #we want to animate the move over 2 seconds. At 60 frames per second
        #we'd get 120 different positions along the transitional distance.
        self.new_pos = new_pos
        self.old_pos = old_pos
        self.slopes = np.zeros(old_pos.shape)
        for i in range(old_pos.shape[0]):
            self.slopes[i, 0] =  (new_pos[i, 0] - old_pos[i, 0])/120.0
            self.slopes[i, 1] =  (new_pos[i, 1] - old_pos[i, 1])/120.0
            
        #self.timer.start()
        #for i in range(120):
        #self.old_pos = np.add(old_pos, self.slopes)
        self.timer.start(iterations=120)
        #self.data['a_position'] = old_pos
        #self.gen_vertex_vbo_minimalist()
        #self.update()
##            self.gen_line_vbo(self.G)
##            self.program_e.bind(self.vbo_line)
##            self.program.bind(self.vbo)
#            self.update()
#            #self.program_e.draw('lines')
#            print(i)
        #self.timer.stop()
        
        #self.G = new_G
        #self.gen_vertex_vbo(self.G)
        #self.update()
        
#    def on_timer(self, event):
#        self.vbo = gloo.VertexBuffer(self.data)
#        #self.gen_line_vbo(self.G)
#        #self.program_e.bind(self.vbo_line)
#        self.program.bind(self.vbo)
#        self.update()
#        gloo.wrappers.flush()
    """
        Function performed during a mouse click (either right or left)
        gets the unique id of the object drawn underneath the cursor
        handles the cases depending on whether the click happened to a cluster
        or a vertex. Edges are not interactable (yet)
    """
    def get_clicked_id(self, event, clusters = False):
        #Get the framebuffer coordinates of the click
        coord = self.transforms.get_transform('canvas', 'framebuffer').map(event.pos)

        #get the framebuffer where each element is rendered as a unique color
        size = self.size;
        self.fbo = gloo.FrameBuffer(color=gloo.RenderBuffer(size[::-1]), depth=gloo.RenderBuffer(size[::-1]))
        buff = gloo.read_pixels((0,0,self.physical_size[0], self.physical_size[1]))
        #imsave("test_ori.png", buff)
        self.fbo.activate()
        if clusters == False:
            self.refresh()
            self.program['u_picking'] = True
            clear(color='white', depth=True)
            self.program.draw('points')
            buff = gloo.read_pixels((0,0,self.physical_size[0], self.physical_size[1]))
            #imsave("test.png", buff)

            #return to the original state
            self.fbo.deactivate()
            self.program['u_picking'] = False
        else:
            self.program_s['u_picking'] = True
            clear(color='white', depth=True)
            self.program_s.draw('triangles', indices=self.index_s)
            buff = gloo.read_pixels((0,0,self.physical_size[0], self.physical_size[1]))
            #imsave("test.png", buff)

            #return to the original state
            self.fbo.deactivate()
            self.program_s['u_picking'] = False

        #print(buff[self.physical_size[1]-int(coord[1]), int(coord[0])])

        #Get the color under the click.
        #Keep in mind that the buff is y, x
        #And 0,0 is in the top RIGHT corner.
        #IGNORE THE DOCUMENTATION
        color = np.multiply(buff[self.physical_size[1]-int(coord[1]), int(coord[0])], 1/255.0)
        #if (tuple(color) not in self.color_dict):
        #    print("clicked on nothing")
        #else:
        #    print(self.color_dict[tuple(color)])

        #reset the original buffer
        self.refresh()

        #Return the element under the click.
        if clusters == False:
            if(tuple(color) not in self.color_dict):
                return None
            else:
                return self.color_dict[tuple(color)]
        else:
            if(tuple(color) not in self.cluster_dict):
                return None
            else:
                return self.cluster_dict[tuple(color)]

    def update_view_global(self):
        self.program['u_view'] = self.view
        self.program_e['u_view'] = self.view
        self.program_s['u_view'] = self.view
        self.program_e_s['u_view'] = self.view


    """
        Top level handle-mouse presee event for either left or right click
    """
    def on_mouse_press(self, event):

        def update_view():
            self.location = event.pos
            self.program['u_view'] = self.view
            self.program_e['u_view'] = self.view
            self.program_s['u_view'] = self.view
            self.program_e_s['u_view'] = self.view
            self.down = True


#        if(event.button == 2):
##            menu = QtWidgets.QMenu(self.parent)
##            NS = menu.addAction('Node Size')
##            NC = menu.addAction('Node Color')
##            action = menu.exec_(self.parent.globalPos())
##            if action == NS:
#            print("right_click")
#            #if menu.exec_(event.globalPos()):
#            #    print(item.text())
        if(event.button == 1):
            if(self.view[0][0] > 0.0024):
                self.refresh()
                c_id = self.get_clicked_id(event)
                self.refresh()
                if(c_id != None):
                    self.original_point = self.G.vertex_properties["pos"][self.G.vertex(c_id)]
                    self.location = event.pos
                    self.moving = True
                    self.down = True
                    self.c_id = [c_id]
                else:
                    update_view()
                    #print("Clicked on:", event.pos)
            else:
#                c_id = None
                self.refresh()
                c_id = self.get_clicked_id(event, True)
                self.refresh()
                if DEBUG:
                    print(c_id)
                if(c_id != None):
                    self.original_point = self.cluster_pos[c_id]
                    self.location = event.pos
                    self.moving = True
                    self.down = True
                    self.c_id = [c_id]
                    self.moving_cluster = True
                else:
                    update_view()

    """
        Gets the path and formats it in terms of vertex-to-vertex
        instead of source(obj)-to-source(obj)
    """
    
    def get_cluster(self, cluster_id):
        p = []
        num_v_in_cluster = len(np.argwhere(self.labels == cluster_id))
        vfilt = np.zeros([self.G.num_vertices(), 1], dtype="bool")
        vfilt[np.argwhere(self.labels == cluster_id)] = 1
        vfilt_prop = self.G.new_vertex_property("bool", vals = vfilt)
        self.G.set_vertex_filter(vfilt_prop)
    
        #get the filtered properties
        g = nwt.gt.Graph(self.G, prune=True, directed=False)
        self.G.clear_filters()
        for e in g.edges():
            source = g.vp["idx"][e.source()]
            target = g.vp["idx"][e.target()]
            temp = (int(source), int(target))
            p.append(temp)
            
        return p
    
    
    def get_path(self):
        p = []
        for s in self.path:
            for e in s.e_path:
                temp = (int(e.source()), int(e.target()))
                if (temp not in p):
                    p.append(temp)
                    
        return p
        

    def update_path(self, event):
        #Method to update the vertex buffer of the nodes in the graph view
        def update_vbo(self):
            self.vbo = gloo.VertexBuffer(self.data)
            self.program.bind(self.vbo)
            self.refresh()

        def update_vertex_alpha(self, vertex, alpha):
            temp = self.G.vertex_properties["RGBA"][vertex]
            temp[3] = alpha
            self.G.vertex_properties["RGBA"][vertex] = temp

        #updates the path structure of the class
        #source and target are of type "source" defined in this class.
        def add_to_path(self, source, target):
            vl, el = nwt.gt.graph_tool.topology.shortest_path(self.G, self.G.vertex(source.idx), self.G.vertex(target.idx), weights=self.G.edge_properties["av_radius"])
            for v in range(1, len(vl)-1):
                if (self.G.vertex_properties["selection"][vl[v]] != 1.0):
                    self.G.vertex_properties["selection"][vl[v]] = 2.0
                    update_vertex_alpha(self, self.G.vertex(vl[v]), 1.0)
                    self.data['a_selection'][int(vl[v])] = 2.0
                    self.G.vp["exclude"][self.G.vertex(vl[v])] = True
                source.v_path.append(int(vl[v]))
            for e in el:
                source.e_path.append(e)
                temp = self.G.edge_properties["RGBA"][e]
                temp[3] = 1.0
                self.G.edge_properties["RGBA"][e] = temp
                self.G.edge_properties["exclude"][e] = True
                
        
        def remove_from_path(self, source):
            for v in source.v_path:
                self.G.vertex_properties["selection"][self.G.vertex(v)] = 0.0
                update_vertex_alpha(self,self.G.vertex(v), 0.5)
                self.data['a_selection'][v] = 0.0
                self.G.vertex_properties["exclude"][v] = False
            for e in source.e_path:
                temp = self.G.edge_properties["RGBA"][e]
                temp[3] = 0.0
                self.G.edge_properties["RGBA"][e] = temp
                self.G.edge_properties["exclude"][e] = False
            source.clear_path()

        if (event.button == 1):
            if(self.view[0][0] > 0.0024):
                self.refresh()
                c_id = self.get_clicked_id(event)
                self.refresh()
            if(c_id != None):
                #check whether this is the first node to be selected
                if(self.pathing == False):
                    #if it is, select that node and turn the pathing variable on.
                    self.G.vertex_properties["selection"][self.G.vertex(c_id)] = 1.0
                    self.pathing = True
                    self.path.append(path_point(c_id))
                    self.data['a_selection'][c_id] = 1.0
                    self.make_all_transparent(0.5)
                    update_vertex_alpha(self, self.G.vertex(c_id), 1.0)
                    self.update_color_buffers()
                    print("I turned on the first node")
                else:
                    #If the node is selected already, unselect it and remove from path the last occurance in the path
                    if(self.G.vertex_properties["selection"][self.G.vertex(c_id)] == 1.0):
                        self.G.vertex_properties["selection"][self.G.vertex(c_id)] = 0.0
                        update_vertex_alpha(self, self.G.vertex(c_id), 1.0)
                        self.data['a_selection'][c_id] = 0.0
                        s_id = self.path.index(path_point(c_id))
                        if(s_id == 0):
                            remove_from_path(self, self.path[s_id])
                        else:
                            remove_from_path(self, self.path[s_id-1])
                            remove_from_path(self, self.path[s_id])
                        self.path.remove(path_point(c_id))
                        #self.data['a_selection'][c_id] = 0.0
                        #update_vbo(self)
                        print("I turned off a node")
                    elif(self.G.vertex_properties["selection"][self.G.vertex(c_id)] == 0.0):
                        self.G.vertex_properties["selection"][self.G.vertex(c_id)] = 1.0
                        #if the source is not in the path add it
                        if(path_point(c_id) not in self.path):
                            self.path.append(path_point(c_id))
                            self.G.vertex_properties["selection"][self.G.vertex(c_id)] = 1.0
                            update_vertex_alpha(self, self.G.vertex(c_id), 1.0)
                            self.data['a_selection'][c_id] = 1.0
                        #if the source is not LAST in the path, add it.
                        elif(self.path[len(self.path)-1] != path_point(c_id)):
                            self.path.append(path_point(c_id))
                            self.G.vertex_properties["selection"][self.G.vertex(c_id)] = 1.0
                            update_vertex_alpha(self, self.G.vertex(c_id), 1.0)
                            self.data['a_selection'][c_id] = 1.0
                        print("I turned on a node")
                    if(len(self.path) >= 1):
                        for i in range(len(self.path)-1):
                            add_to_path(self, self.path[i], self.path[i+1])
                        self.update_color_buffers()
                            #THIS IS WHERE I LEFT IT OFF.
                    if(np.sum(self.G.vertex_properties["selection"].get_array()) == 0):
                        self.pathing = False
                        self.make_all_transparent(1.0)
                        self.update_color_buffers()
                        self.refresh()



#                elif(np.sum(self.G.vertex_properties["selection"].get_array()) :
#                    self.G.vertex_properties["selection"][self.G.vertex(c_id)] == False
                print("clicked on: ", c_id, " ", self.path)


    """
        Handles the double click event that it responsible for path selection.
        Generates paths our of consecutive paths out of the selected vertices.
    """
    def on_mouse_double_click(self, event):
        n=1
                
    """
        Resets the variables that are used during the pressdown and move events
    """
    def on_mouse_release(self, event):
        self.down = False
        self.moving = False
        self.moving_cluster = False
        self.c_id = []
        #self.location = event.pos
        #print("Clicked off:", event.pos)

    """
        used during the drag evern to update the position of the clusters
    """
    def update_cluster_position(self, G, pos, offset, c_id):
        v_pos = G.vertex_properties["pos"].get_2d_array(range(3)).T
        vertices = np.argwhere(self.labels == c_id)
        for v in range(vertices.shape[0]):
            idx = vertices[v][0]
            v_pos[idx][0] = v_pos[idx][0] + offset[0]
            v_pos[idx][1] = v_pos[idx][1] + offset[1]
            v_pos[idx][2] = v_pos[idx][2] + offset[2]
            self.data['a_position'][idx] = np.asarray([v_pos[idx][0], v_pos[idx][1], v_pos[idx][2]], dtype = np.float32)
            #update the edge data by finding all edges connected to the vertex
            vtx = self.G.vertex(idx)
            for e in vtx.all_edges():
                d = np.subtract(G.vertex_properties["pos"][e.source()], G.vertex_properties["pos"][e.target()])
                d_norm = d[0:2]
                d_norm = d_norm / np.sqrt(np.power(d_norm[0],2) + np.power(d_norm[1],2))
                norm = np.zeros((2,), dtype=np.float32)
                norm[0] = d_norm[1]
                norm[1] = d_norm[0]*-1
                if (int(e.source()), int(e.target())) in self.edge_dict.keys():
                    index = int(self.edge_dict[int(e.source()), int(e.target())])
                    if vtx == int(e.source()):
                        self.line_data['a_position'][index*4]   = v_pos[idx]
                        self.line_data['a_position'][index*4+2] = v_pos[idx]
                        self.line_data['a_normal'][index*4] = norm
                        self.line_data['a_normal'][index*4+2] = -norm
                        self.line_data['a_normal'][index*4+1] = norm
                        self.line_data['a_normal'][index*4+3] = -norm
                    elif vtx == int(e.target()):
                        self.line_data['a_position'][index*4+1] = v_pos[idx]
                        self.line_data['a_position'][index*4+3] = v_pos[idx]
                        self.line_data['a_normal'][index*4] = norm
                        self.line_data['a_normal'][index*4+2] = -norm
                        self.line_data['a_normal'][index*4+1] = norm
                        self.line_data['a_normal'][index*4+3] = -norm
                else:
                    index = int(self.edge_dict[int(e.target()), int(e.source())])
                    if vtx == int(e.target()):
                        self.line_data['a_position'][index*4]   = v_pos[idx]
                        self.line_data['a_position'][index*4+2] = v_pos[idx]
                        self.line_data['a_normal'][index*4] = norm
                        self.line_data['a_normal'][index*4+2] = -norm
                        self.line_data['a_normal'][index*4+1] = norm
                        self.line_data['a_normal'][index*4+3] = -norm
                    elif vtx == int(e.source()):
                        self.line_data['a_position'][index*4+1] = v_pos[idx]
                        self.line_data['a_position'][index*4+3] = v_pos[idx]
                        self.line_data['a_normal'][index*4] = norm
                        self.line_data['a_normal'][index*4+2] = -norm
                        self.line_data['a_normal'][index*4+1] = norm
                        self.line_data['a_normal'][index*4+3] = -norm


        G.vertex_properties["pos"] = G.new_vertex_property("vector<double>", vals = v_pos)
        index = 4*c_id
        #generate the vertex filter for this cluster
        vfilt = np.zeros([G.num_vertices(), 1], dtype="bool")
        vfilt[np.argwhere(self.labels == c_id)] = 1
        vfilt_prop = G.new_vertex_property("bool", vals = vfilt)
        G.set_vertex_filter(vfilt_prop)

        #get the filtered properties
        g = nwt.gt.Graph(G, prune=True, directed=False)
        p, v = self.gen_cluster_coords(pos, self.cluster_size[c_id])
        self.clusters['a_position'][index:index+4] = np.asarray(p, dtype=np.float32)
        self.clusters['a_value'][index:index+4] = np.asarray(v, dtype=np.float32)
        G.clear_filters()
        self.cluster_pos[c_id] = pos
        self.original_point = pos


    """
        function that handles the mouse move event in a way that depends on a set
        of variables: state of the mouse button, the type of object selected and
        the number of objects.
    """
    def on_mouse_move(self, event):
        if(self.down == True):
            if(self.moving == True and self.moving_cluster == False):
                if(len(self.c_id) < 2):
                    #Project into GLSpace and get before and after move coordinates
                    coord = self.transforms.get_transform('canvas', 'render').map(self.location)[:2]
                    coord2 = self.transforms.get_transform('canvas', 'render').map(event.pos)[:2]
                    cur_pos = self.G.vertex_properties["pos"][self.G.vertex(self.c_id[0])]
                    #print(cur_pos, " Before")

                    #Adjust the position of the node based on the current view matrix.
                    cur_pos[0] = cur_pos[0] - (coord[0]-coord2[0])/self.view[0][0]
                    cur_pos[1] = cur_pos[1] - (coord[1]-coord2[1])/self.view[0][0]

                    #print(cur_pos, " After")
                    #Upload the changed data.
                    self.G.vertex_properties["pos"][self.G.vertex(self.c_id[0])] = cur_pos
                    self.data['a_position'][self.c_id[0]] = cur_pos

                    #update the edge data by finding all edges connected to the vertex
                    v = self.G.vertex(self.c_id[0])
                    for e in v.all_edges():
                        d = np.subtract(self.G.vertex_properties["pos"][e.source()], self.G.vertex_properties["pos"][e.target()])
                        d_norm = d[0:2]
                        d_norm = d_norm / np.sqrt(np.power(d_norm[0],2) + np.power(d_norm[1],2))
                        norm = np.zeros((2,), dtype=np.float32)
                        norm[0] = d_norm[1]
                        norm[1] = d_norm[0]*-1
                        if (int(e.source()), int(e.target())) in self.edge_dict.keys():
                            idx = int(self.edge_dict[int(e.source()), int(e.target())])
                            if self.c_id[0] == int(e.source()):
                                self.line_data['a_position'][idx*4] = cur_pos
                                self.line_data['a_position'][idx*4+2] = cur_pos
                                self.line_data['a_normal'][idx*4] = norm
                                self.line_data['a_normal'][idx*4+2] = -norm
                                self.line_data['a_normal'][idx*4+1] = norm
                                self.line_data['a_normal'][idx*4+3] = -norm
                            elif self.c_id[0] == int(e.target()):
                                self.line_data['a_position'][idx*4+1] = cur_pos
                                self.line_data['a_position'][idx*4+3] = cur_pos
                                self.line_data['a_normal'][idx*4] = norm
                                self.line_data['a_normal'][idx*4+2] = -norm
                                self.line_data['a_normal'][idx*4+1] = norm
                                self.line_data['a_normal'][idx*4+3] = -norm
                        else:
                            idx = int(self.edge_dict[int(e.target()), int(e.source())])
                            if self.c_id[0] == int(e.target()):
                                self.line_data['a_position'][idx*4] = cur_pos
                                self.line_data['a_position'][idx*4+2] = cur_pos
                                self.line_data['a_normal'][idx*4] = norm
                                self.line_data['a_normal'][idx*4+2] = -norm
                                self.line_data['a_normal'][idx*4+1] = norm
                                self.line_data['a_normal'][idx*4+3] = -norm
                            elif self.c_id[0] == int(e.source()):
                                self.line_data['a_position'][idx*4+1] = cur_pos
                                self.line_data['a_position'][idx*4+3] = cur_pos
                                self.line_data['a_normal'][idx*4] = norm
                                self.line_data['a_normal'][idx*4+2] = -norm
                                self.line_data['a_normal'][idx*4+1] = norm
                                self.line_data['a_normal'][idx*4+3] = -norm
                    #self.line_data['a_position'][self.c_id[0]] =
                    self.vbo = gloo.VertexBuffer(self.data)
                    self.vbo_line = gloo.VertexBuffer(self.line_data)
                    #Bind the buffer and redraw.
                    self.program.bind(self.vbo)
                    self.program_e.bind(self.vbo_line)
                    #self.program.draw('points')
                    self.location = event.pos
                    self.refresh()
            elif(self.moving == True and self.moving_cluster == True):
                if(len(self.c_id) < 2):
                    #Project into GLSpace and get before and after move coordinates
                    coord = self.transforms.get_transform('canvas', 'render').map(self.location)[:2]
                    coord2 = self.transforms.get_transform('canvas', 'render').map(event.pos)[:2]
                    cur_pos = np.zeros(self.cluster_pos[self.c_id[0]].shape, dtype = np.float32)
                    offset = np.zeros(self.cluster_pos[self.c_id[0]].shape, dtype = np.float32)
                    cur_pos[0] = self.cluster_pos[self.c_id[0]][0]
                    cur_pos[1] = self.cluster_pos[self.c_id[0]][1]
                    cur_pos[2] = self.cluster_pos[self.c_id[0]][2]
                    offset[0] = self.cluster_pos[self.c_id[0]][0]
                    offset[1] = self.cluster_pos[self.c_id[0]][1]
                    offset[2] = self.cluster_pos[self.c_id[0]][2]
#                    ofset = self.cluster_pos[self.c_id[0]]

                    #Adjust the position of the node based on the current view matrix.
                    offset[0] = self.original_point[0] - cur_pos[0] - (coord[0]-coord2[0])/self.view[0][0]
                    offset[1] = self.original_point[1] - cur_pos[1] - (coord[1]-coord2[1])/self.view[0][0]
                    cur_pos[0] = cur_pos[0] - (coord[0]-coord2[0])/self.view[0][0]
                    cur_pos[1] = cur_pos[1] - (coord[1]-coord2[1])/self.view[0][0]

                    self.update_cluster_position(self.G, cur_pos, offset, self.c_id[0])
                    #self.original_point = cur_pos
                    self.vbo = gloo.VertexBuffer(self.data)
                    self.vbo_line = gloo.VertexBuffer(self.line_data)
                    #Bind the buffer and redraw.
                    self.program.bind(self.vbo)
                    self.program_e.bind(self.vbo_line)
                    #self.program.draw('points')
                    self.location = event.pos
                    if(self.subgraphs):
                        self.vbo_s = gloo.VertexBuffer(self.clusters)
                        self.program_s.bind(self.vbo_s)
                    self.update_cluster_line_vbo()
                    self.refresh()


            else:
            #print("Mouse at:", event.pos)
            #new_model = np.eye(4, dtype=np.float32)
                coord = self.transforms.get_transform('canvas', 'render').map(self.location)[:2]
                coord2 = self.transforms.get_transform('canvas', 'render').map(event.pos)[:2]
                self.translate[0] += (coord[0]-coord2[0])/self.view[0][0]
                self.translate[1] += (coord[1]-coord2[1])/self.view[1][1]
                #self.view[3][0] = self.view[3][0]-(self.location[0]-event.pos[0])/10000.0
                #self.view[3][1] = self.view[3][1]+(self.location[1]-event.pos[1])/10000.0

                self.view = np.matmul(translate((self.translate[0], self.translate[1], 0)), scale((self.scale[0], self.scale[1], 0)))

                self.program['u_view'] = self.view
                self.program_e['u_view'] = self.view
                self.program_s['u_view'] = self.view
                self.program_e_s['u_view'] = self.view
                self.location = event.pos
                self.refresh()

    def set_view_matrix(self, matrix):
        self.view = matrix
        self.program['u_view'] = self.view
        self.program_e['u_view'] = self.view
        self.program_s['u_view'] = self.view
        self.program_e_s['u_view'] = self.view
        self.refresh()


    def center_camera_on(self, camera):
        self.translate[0] += (0.0 - camera[0])/self.view[0][0]
        self.translate[1] += (0.0 - camera[1])/self.view[1][1]
        #self.view[3][0] = self.view[3][0]-(self.location[0]-event.pos[0])/10000.0
        #self.view[3][1] = self.view[3][1]+(self.location[1]-event.pos[1])/10000.0

        self.view = np.matmul(translate((self.translate[0], self.translate[1], 0)), scale((self.scale[0], self.scale[1], 0)))

        self.program['u_view'] = self.view
        self.program_e['u_view'] = self.view
        self.program_s['u_view'] = self.view
        self.program_e_s['u_view'] = self.view
        self.refresh()

    def zoom_camera_on(self, zoom):
        self.scale[0] = zoom[0]
        self.scale[1] = zoom[1]

        self.view = np.matmul(translate((self.translate[0], self.translate[1], 0)),
        scale((self.scale[0], self.scale[1], 0)))

        self.program['u_view'] = self.view
        self.program_e['u_view'] = self.view
        self.program_s['u_view'] = self.view
        self.program_e_s['u_view'] = self.view
        #print(event.delta[1])
        self.refresh()

    """
        Handles the mouse wheel zoom event.
    """
    def on_mouse_wheel(self, event):

        #print(self.view)
        #TO_DO IMPLEMENT ZOOM TO CURSOR
        #self.view[3][0] = self.view[3][0]-event.pos[0]/10000.0
        #self.view[3][1] = self.view[3][1]-event.pos[1]/10000.0
        #print(self.scale[0] , self.scale[0]*event.delta[1]*0.05)
        self.scale[0] = self.scale[0] + self.scale[0]*event.delta[1]*0.05
        self.scale[1] = self.scale[1] + self.scale[1]*event.delta[1]*0.05

        self.view = np.matmul(translate((self.translate[0], self.translate[1], 0)),
        scale((self.scale[0], self.scale[1], 0)))

        #self.view[0][0] = self.view[0][0]+self.view[0][0]*event.delta[1]*0.05
        #self.view[1][1] = self.view[1][1]+self.view[1][1]*event.delta[1]*0.05
        #print(self.view[0][0], " ",self.view[1][1])
        #print(self.view)
        self.program['u_view'] = self.view
        self.program_e['u_view'] = self.view
        self.program_s['u_view'] = self.view
        self.program_e_s['u_view'] = self.view
        #print(event.delta[1])
        self.refresh()