echarts-graph-modularity.js 50.9 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
(function webpackUniversalModuleDefinition(root, factory) {
	if(typeof exports === 'object' && typeof module === 'object')
		module.exports = factory(require("echarts"));
	else if(typeof define === 'function' && define.amd)
		define(["echarts"], factory);
	else if(typeof exports === 'object')
		exports["echarts-graph-modularity"] = factory(require("echarts"));
	else
		root["echarts-graph-modularity"] = factory(root["echarts"]);
})(this, function(__WEBPACK_EXTERNAL_MODULE_9__) {
return /******/ (function(modules) { // webpackBootstrap
/******/ 	// The module cache
/******/ 	var installedModules = {};
/******/
/******/ 	// The require function
/******/ 	function __webpack_require__(moduleId) {
/******/
/******/ 		// Check if module is in cache
/******/ 		if(installedModules[moduleId]) {
/******/ 			return installedModules[moduleId].exports;
/******/ 		}
/******/ 		// Create a new module (and put it into the cache)
/******/ 		var module = installedModules[moduleId] = {
/******/ 			i: moduleId,
/******/ 			l: false,
/******/ 			exports: {}
/******/ 		};
/******/
/******/ 		// Execute the module function
/******/ 		modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ 		// Flag the module as loaded
/******/ 		module.l = true;
/******/
/******/ 		// Return the exports of the module
/******/ 		return module.exports;
/******/ 	}
/******/
/******/
/******/ 	// expose the modules object (__webpack_modules__)
/******/ 	__webpack_require__.m = modules;
/******/
/******/ 	// expose the module cache
/******/ 	__webpack_require__.c = installedModules;
/******/
/******/ 	// define getter function for harmony exports
/******/ 	__webpack_require__.d = function(exports, name, getter) {
/******/ 		if(!__webpack_require__.o(exports, name)) {
/******/ 			Object.defineProperty(exports, name, {
/******/ 				configurable: false,
/******/ 				enumerable: true,
/******/ 				get: getter
/******/ 			});
/******/ 		}
/******/ 	};
/******/
/******/ 	// getDefaultExport function for compatibility with non-harmony modules
/******/ 	__webpack_require__.n = function(module) {
/******/ 		var getter = module && module.__esModule ?
/******/ 			function getDefault() { return module['default']; } :
/******/ 			function getModuleExports() { return module; };
/******/ 		__webpack_require__.d(getter, 'a', getter);
/******/ 		return getter;
/******/ 	};
/******/
/******/ 	// Object.prototype.hasOwnProperty.call
/******/ 	__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ 	// __webpack_public_path__
/******/ 	__webpack_require__.p = "";
/******/
/******/ 	// Load entry module and return exports
/******/ 	return __webpack_require__(__webpack_require__.s = 0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports, __webpack_require__) {

module.exports = __webpack_require__(1);

/***/ }),
/* 1 */
/***/ (function(module, exports, __webpack_require__) {

var Modularity = __webpack_require__(2);
var echarts = __webpack_require__(9);
var createNGraph = __webpack_require__(10);

function createModularityVisual(chartType) {
    return function (ecModel, api) {
        var paletteScope = {};
        ecModel.eachSeriesByType(chartType, function (seriesModel) {
            var modularityOpt = seriesModel.get('modularity');
            if (modularityOpt) {
                var graph = seriesModel.getGraph();
                var idIndexMap = {};
                var ng = createNGraph();
                graph.data.each(function (idx) {
                    var node = graph.getNodeByIndex(idx);
                    idIndexMap[node.id] = idx;
                    ng.addNode(node.id);
                    return node.id;
                });
                graph.edgeData.each('value', function (val, idx) {
                    var edge = graph.getEdgeByIndex(idx);
                    ng.addLink(edge.node1.id, edge.node2.id);
                    return {
                        source: edge.node1.id,
                        target: edge.node2.id,
                        value: val
                    };
                });

                var modularity = new Modularity(seriesModel.get('modularity.resolution') || 1);
                var result = modularity.execute(ng);

                var communities = {};
                for (var id in result) {
                    var comm = result[id];
                    communities[comm] = communities[comm] || 0;
                    communities[comm]++;
                }
                var communitiesList = Object.keys(communities);
                if (seriesModel.get('modularity.sort')) {
                    communitiesList.sort(function (a, b) {
                        return b - a;
                    });
                }
                var colors = {};
                communitiesList.forEach(function (comm) {
                    colors[comm] = seriesModel.getColorFromPalette(comm, paletteScope);
                });

                for (var id in result) {
                    var comm = result[id];
                    graph.data.setItemVisual(idIndexMap[id], 'color', colors[comm]);
                }

                graph.edgeData.each(function (idx) {
                    var itemModel = graph.edgeData.getItemModel(idx);
                    var edge = graph.getEdgeByIndex(idx);
                    var color = itemModel.get('lineStyle.normal.color');

                    switch (color) {
                        case 'source':
                            color = edge.node1.getVisual('color');
                            break;
                        case 'target':
                            color = edge.node2.getVisual('color');
                            break;
                    }

                    if (color != null) {
                        edge.setVisual('color', color);
                    }
                });
            }
        });
    };
}

echarts.registerVisual(echarts.PRIORITY.VISUAL.CHART + 1, createModularityVisual('graph'));
echarts.registerVisual(echarts.PRIORITY.VISUAL.CHART + 1, createModularityVisual('graphGL'));

/***/ }),
/* 2 */
/***/ (function(module, exports, __webpack_require__) {

/*
 Copyright 2008-2011 Gephi
 Authors : Patick J. McSweeney <pjmcswee@syr.edu>, Sebastien Heymann <seb@gephi.org>
 Website : http://www.gephi.org

 This file is part of Gephi.

 DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.

 Copyright 2011 Gephi Consortium. All rights reserved.

 The contents of this file are subject to the terms of either the GNU
 General Public License Version 3 only ("GPL") or the Common
 Development and Distribution License("CDDL") (collectively, the
 "License"). You may not use this file except in compliance with the
 License. You can obtain a copy of the License at
 http://gephi.org/about/legal/license-notice/
 or /cddl-1.0.txt and /gpl-3.0.txt. See the License for the
 specific language governing permissions and limitations under the
 License.  When distributing the software, include this License Header
 Notice in each file and include the License files at
 /cddl-1.0.txt and /gpl-3.0.txt. If applicable, add the following below the
 License Header, with the fields enclosed by brackets [] replaced by
 your own identifying information:
 "Portions Copyrighted [year] [name of copyright owner]"

 If you wish your version of this file to be governed by only the CDDL
 or only the GPL Version 3, indicate your decision by adding
 "[Contributor] elects to include this software in this distribution
 under the [CDDL or GPL Version 3] license." If you do not indicate a
 single choice of license, a recipient has the option to distribute
 your version of this file under either the CDDL, the GPL Version 3 or
 to extend the choice of license to its licensees as provided above.
 However, if you add GPL Version 3 code and therefore, elected the GPL
 Version 3 license, then the option applies only if the new code is
 made subject to such option by the copyright holder.

 Contributor(s): Thomas Aynaud <taynaud@gmail.com>

 Portions Copyrighted 2011 Gephi Consortium.
 */
var CommunityStructure = __webpack_require__(3)
    , centrality = __webpack_require__(6)
    ;

/**
 * @constructor
 */
function Modularity (resolution, useWeight) {
    this.isRandomized = false;
    this.useWeight = useWeight;
    this.resolution = resolution || 1.;
    /**
     * @type {CommunityStructure}
     */
    this.structure = null;
}

/**
 * @param {IGraph} graph
 */
Modularity.prototype.execute = function (graph/*, AttributeModel attributeModel*/) {


    this.structure = new CommunityStructure(graph, this.useWeight);

    var comStructure = new Array(graph.getNodesCount());

    var computedModularityMetrics = this.computeModularity(
        graph
        , this.structure
        , comStructure
        , this.resolution
        , this.isRandomized
        , this.useWeight
    );

    var result = {};
    this.structure.map.forEach(function (i, node) {
        result[node] = comStructure[i];
    });

    return result;

};


/**
 *
 * @param {IGraph} graph
 * @param {CommunityStructure} theStructure
 * @param {Array.<Number>} comStructure
 * @param {Number} currentResolution
 * @param {Boolean} randomized
 * @param {Boolean} weighted
 * @returns {Object.<String, Number>}
 */
Modularity.prototype.computeModularity = function(graph, theStructure, comStructure,  currentResolution, randomized, weighted) {


    function getRandomInt(min, max) {
        return Math.floor(Math.random() * (max - min)) + min;
    }

    var totalWeight = theStructure.graphWeightSum;
    var nodeDegrees = theStructure.weights.slice();


    var /** @type {Object.<String, Number>} */ results = Object.create(null);


    var someChange = true;

    while (someChange) {
        someChange = false;
        var localChange = true;
        while (localChange) {
            localChange = false;
            var start = 0;
            if (randomized) {
                //start = Math.abs(rand.nextInt()) % theStructure.N;
                start = getRandomInt(0,theStructure.N);
            }
            var step = 0;
            for (var i = start; step < theStructure.N; i = (i + 1) % theStructure.N) {
                step++;
                var bestCommunity = this.updateBestCommunity(theStructure, i, currentResolution);
                if ((theStructure.nodeCommunities[i] != bestCommunity) && (bestCommunity != null)) {
                    theStructure.moveNodeTo(i, bestCommunity);
                    localChange = true;
                }

            }

            someChange = localChange || someChange;

        }

        if (someChange) {
            theStructure.zoomOut();
        }
    }

    this.fillComStructure(graph, theStructure, comStructure);

    /*
    //TODO: uncomment when finalQ will be implemented
    var degreeCount = this.fillDegreeCount(graph, theStructure, comStructure, nodeDegrees, weighted);


    var computedModularity = this._finalQ(comStructure, degreeCount, graph, theStructure, totalWeight, 1., weighted);
    var computedModularityResolution = this._finalQ(comStructure, degreeCount, graph, theStructure, totalWeight, currentResolution, weighted);

    results["modularity"] =  computedModularity;
    results["modularityResolution"] =  computedModularityResolution;
    */

    return results;
};


/**
 * @param {CommunityStructure} theStructure
 * @param {Number} i
 * @param {Number} currentResolution
 * @returns {Community}
 */
Modularity.prototype.updateBestCommunity = function(theStructure,  i, currentResolution) {
    var best = this.q(i, theStructure.nodeCommunities[i], theStructure, currentResolution);
    var bestCommunity = theStructure.nodeCommunities[i];
    //var /*Set<Community>*/ iter = theStructure.nodeConnectionsWeight[i].keySet();
    theStructure.nodeConnectionsWeight[i].forEach(function (_$$val, com) {

        var qValue = this.q(i, com, theStructure, currentResolution);
        if (qValue > best) {
            best = qValue;
            bestCommunity = com;
        }

    }, this);
    return bestCommunity;
};

/**
 *
 * @param {IGraph} graph
 * @param {CommunityStructure} theStructure
 * @param {Array.<Number>} comStructure
 * @returns {Array.<Number>}
 */
Modularity.prototype.fillComStructure = function(graph, theStructure, comStructure) {

    var count = 0;

    theStructure.communities.forEach(function (com) {

        com.nodes.forEach(function (node) {

            var hidden = theStructure.invMap.get(node);
            hidden.nodes.forEach( function (nodeInt){
                comStructure[nodeInt] = count;
            });

        });
        count++;

    });


    return comStructure;
};

/**
 * @param {IGraph} graph
 * @param {CommunityStructure} theStructure
 * @param {Array.<Number>} comStructure
 * @param {Array.<Number>} nodeDegrees
 * @param {Boolean} weighted
 * @returns {Array.<Number>}
 */
Modularity.prototype.fillDegreeCount = function(graph, theStructure, comStructure, nodeDegrees, weighted) {

    var degreeCount = new Array(theStructure.communities.length);
    var degreeCentrality = centrality.degree(graph);

    graph.forEachNode(function(node){

        var index = theStructure.map.get(node);
        if (weighted) {
            degreeCount[comStructure[index]] += nodeDegrees[index];
        } else {
            degreeCount[comStructure[index]] += degreeCentrality[node.id];
        }

    });
    return degreeCount;

};


/**
 *
 * @param {Array.<Number>} struct
 * @param {Array.<Number>} degrees
 * @param {IGraph} graph
 * @param {CommunityStructure} theStructure
 * @param {Number} totalWeight
 * @param {Number} usedResolution
 * @param {Boolean} weighted
 * @returns {Number}
 */
Modularity.prototype._finalQ = function(struct, degrees, graph, theStructure, totalWeight, usedResolution, weighted) {

    //TODO: rewrite for wighted version of algorithm
    throw new Error("not implemented properly");
    var  res = 0;
    var  internal = new Array(degrees.length);

    graph.forEachNode(function(n){
        var n_index = theStructure.map.get(n);

        graph.forEachLinkedNode(n.id, function(neighbor){
            if (n == neighbor) {
                return;
            }
            var neigh_index = theStructure.map.get(neighbor);
            if (struct[neigh_index] == struct[n_index]) {
                if (weighted) {
                    //throw new Error("weighted aren't implemented");
                    //internal[struct[neigh_index]] += graph.getEdge(n, neighbor).getWeight();
                } else {
                    internal[struct[neigh_index]]++;
                }
            }
        }.bind(this), false);

    }.bind(this));

    for (var i = 0; i < degrees.length; i++) {
        internal[i] /= 2.0;
        res += usedResolution * (internal[i] / totalWeight) - Math.pow(degrees[i] / (2 * totalWeight), 2);//HERE
    }
    return res;
};



/**
 *
 * @param {Number} nodeId
 * @param {Community} community
 * @param {CommunityStructure} theStructure
 * @param {Number} currentResolution
 * @returns {Number}
 */
Modularity.prototype.q = function(nodeId, community, theStructure, currentResolution) {

    var edgesToFloat = theStructure.nodeConnectionsWeight[nodeId].get(community);
    var edgesTo = 0;
    if (edgesToFloat != null) {
        edgesTo = edgesToFloat;
    }
    var weightSum = community.weightSum;
    var nodeWeight = theStructure.weights[nodeId];
    var qValue = currentResolution * edgesTo - (nodeWeight * weightSum) / (2.0 * theStructure.graphWeightSum);
    if ((theStructure.nodeCommunities[nodeId] == community) && (theStructure.nodeCommunities[nodeId].size() > 1)) {
        qValue = currentResolution * edgesTo - (nodeWeight * (weightSum - nodeWeight)) / (2.0 * theStructure.graphWeightSum);
    }
    if ((theStructure.nodeCommunities[nodeId] == community) && (theStructure.nodeCommunities[nodeId].size() == 1)) {
        qValue = 0.;
    }
    return qValue;

};

module.exports = Modularity;

/***/ }),
/* 3 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var Community = __webpack_require__(4)
    , ModEdge = __webpack_require__(5)
    ;

/**
 *
 * @param {IGraph} graph
 * @param useWeight
 * @param {CommunityStructure} structure
 * @constructor
 */
function CommunityStructure(graph, useWeight) {

    //this.graph = graph;
    this.N = graph.getNodesCount();
    this.graphWeightSum = 0;
    this.structure = this;

    /** @type {Map.<Number, Community>} */
    this.invMap = new Map();

    /** @type {Array.< Map.<Community, Number> >} */
    this.nodeConnectionsWeight = new Array(this.N);

    /** @type {Array.< Map.<Community, Number> >} */
    this.nodeConnectionsCount = new Array(this.N);

    /** @type {Array.<Community>} */
    this.nodeCommunities = new Array(this.N);

    /** @type {Map.<Node, Number>} */
    this.map = new Map();

    /** @type {Array.< Array.<ModEdge> >} */
    this.topology = new Array(this.N);
    for (var i = 0; i < this.N; i++) this.topology[i] = [];

    /** @type {Array.<Community>} */
    this.communities = [];

    /**@type {Array.<Number>} */
    this.weights = new Array(this.N);

    var index = 0;

    graph.forEachNode(function (node) {

        this.map.set(node.id, index);
        this.nodeCommunities[index] = new Community(this);
        this.nodeConnectionsWeight[index] = new Map();
        this.nodeConnectionsCount[index] = new Map();
        this.weights[index] = 0;
        this.nodeCommunities[index].seed(index);
        var hidden = new Community(this);
        hidden.nodes.add(index);
        this.invMap.set(index, hidden);
        this.communities.push(this.nodeCommunities[index]);
        index++;

    }.bind(this));


    graph.forEachLink(function (link) {

        var node_index = this.map.get(link.fromId)
            , neighbor_index = this.map.get(link.toId)
            , weight = 1
            ;

        if (node_index === neighbor_index) {
            return;
        }

        if (useWeight) {
            weight = link.data.weight;
        }

        this.setUpLink(node_index, neighbor_index, weight);
        this.setUpLink(neighbor_index, node_index, weight);


    }.bind(this));


    this.graphWeightSum /= 2.0;
}


CommunityStructure.prototype.setUpLink = function (node_index, neighbor_index, weight) {

    this.weights[node_index] += weight;
    var /** @type {ModEdge} */ me = new ModEdge(node_index, neighbor_index, weight);
    this.topology[node_index].push(me);
    var /** @type {Community} **/ adjCom = this.nodeCommunities[neighbor_index];
    this.nodeConnectionsWeight[node_index].set(adjCom, weight);
    this.nodeConnectionsCount[node_index].set(adjCom, 1);
    this.nodeCommunities[node_index].connectionsWeight.set(adjCom, weight);
    this.nodeCommunities[node_index].connectionsCount.set(adjCom, 1);
    this.nodeConnectionsWeight[neighbor_index].set(this.nodeCommunities[node_index], weight);
    this.nodeConnectionsCount[neighbor_index].set(this.nodeCommunities[node_index], 1);
    this.nodeCommunities[neighbor_index].connectionsWeight.set(this.nodeCommunities[node_index], weight);
    this.nodeCommunities[neighbor_index].connectionsCount.set(this.nodeCommunities[node_index], 1);
    this.graphWeightSum += weight;

};

/**
 * @param {Number} node
 * @param {Community} to
 */
CommunityStructure.prototype.addNodeTo = function (node, to) {

    to.add(node);
    this.nodeCommunities[node] = to;

    var nodeTopology = this.topology[node];
    for (var topologyKey in nodeTopology) {

        //noinspection JSUnfilteredForInLoop
        var /** @type {ModEdge} */ e = nodeTopology[topologyKey];

        var neighbor = e.target;


        //Remove Node Connection to this community
        var neighEdgesTo = this.nodeConnectionsWeight[neighbor].get(to);
        if (neighEdgesTo === undefined) {
            this.nodeConnectionsWeight[neighbor].set(to, e.weight);
        } else {
            this.nodeConnectionsWeight[neighbor].set(to, neighEdgesTo + e.weight);
        }

        var neighCountEdgesTo = this.nodeConnectionsCount[neighbor].get(to);
        if (neighCountEdgesTo === undefined) {
            this.nodeConnectionsCount[neighbor].set(to, 1);
        } else {
            this.nodeConnectionsCount[neighbor].set(to, neighCountEdgesTo + 1);
        }


        var /** @type {Community} */ adjCom = this.nodeCommunities[neighbor];
        var wEdgesto = adjCom.connectionsWeight.get(to);
        if (wEdgesto === undefined) {
            adjCom.connectionsWeight.set(to, e.weight);
        } else {
            adjCom.connectionsWeight.set(to, wEdgesto + e.weight);
        }

        var cEdgesto = adjCom.connectionsCount.get(to);
        if (cEdgesto === undefined) {
            adjCom.connectionsCount.set(to, 1);
        } else {
            adjCom.connectionsCount.set(to, cEdgesto + 1);
        }

        var nodeEdgesTo = this.nodeConnectionsWeight[node].get(adjCom);
        if (nodeEdgesTo === undefined) {
            this.nodeConnectionsWeight[node].set(adjCom, e.weight);
        } else {
            this.nodeConnectionsWeight[node].set(adjCom, nodeEdgesTo + e.weight);
        }

        var nodeCountEdgesTo = this.nodeConnectionsCount[node].get(adjCom);
        if (nodeCountEdgesTo === undefined) {
            this.nodeConnectionsCount[node].set(adjCom, 1);
        } else {
            this.nodeConnectionsCount[node].set(adjCom, nodeCountEdgesTo + 1);
        }

        if (to != adjCom) {
            var comEdgesto = to.connectionsWeight.get(adjCom);
            if (comEdgesto === undefined) {
                to.connectionsWeight.set(adjCom, e.weight);
            } else {
                to.connectionsWeight.set(adjCom, comEdgesto + e.weight);
            }

            var comCountEdgesto = to.connectionsCount.get(adjCom);
            if (comCountEdgesto === undefined) {
                to.connectionsCount.set(adjCom, 1);
            } else {
                to.connectionsCount.set(adjCom, comCountEdgesto + 1);
            }

        }
    }
};

/**
 * @param {Number} node
 * @param {Community} source
 */
CommunityStructure.prototype.removeNodeFrom = function (node, source) {

    var community = this.nodeCommunities[node];


    var nodeTopology = this.topology[node];
    for (var topologyKey in nodeTopology) {

        //noinspection JSUnfilteredForInLoop
        var /** @type {ModEdge} */ e = nodeTopology[topologyKey];

        var neighbor = e.target;

        //Remove Node Connection to this community
        var edgesTo = this.nodeConnectionsWeight[neighbor].get(community);
        var countEdgesTo = this.nodeConnectionsCount[neighbor].get(community);

        if ((countEdgesTo - 1) == 0) {
            this.nodeConnectionsWeight[neighbor].delete(community);
            this.nodeConnectionsCount[neighbor].delete(community);
        } else {
            this.nodeConnectionsWeight[neighbor].set(community, edgesTo - e.weight);
            this.nodeConnectionsCount[neighbor].set(community, countEdgesTo - 1);
        }


        //Remove Adjacency Community's connection to this community
        var adjCom = this.nodeCommunities[neighbor];
        var oEdgesto = adjCom.connectionsWeight.get(community);
        var oCountEdgesto = adjCom.connectionsCount.get(community);
        if ((oCountEdgesto - 1) == 0) {
            adjCom.connectionsWeight.delete(community);
            adjCom.connectionsCount.delete(community);
        } else {
            adjCom.connectionsWeight.set(community, oEdgesto - e.weight);
            adjCom.connectionsCount.set(community, oCountEdgesto - 1);
        }

        if (node == neighbor) {
            continue;
        }

        if (adjCom != community) {

            var comEdgesto = community.connectionsWeight.get(adjCom);
            var comCountEdgesto = community.connectionsCount.get(adjCom);

            if (comCountEdgesto - 1 == 0) {
                community.connectionsWeight.delete(adjCom);
                community.connectionsCount.delete(adjCom);
            } else {
                community.connectionsWeight.set(adjCom, comEdgesto - e.weight);
                community.connectionsCount.set(adjCom, comCountEdgesto - 1);
            }

        }

        var nodeEdgesTo = this.nodeConnectionsWeight[node].get(adjCom);
        var nodeCountEdgesTo = this.nodeConnectionsCount[node].get(adjCom);

        if ((nodeCountEdgesTo - 1) == 0) {
            this.nodeConnectionsWeight[node].delete(adjCom);
            this.nodeConnectionsCount[node].delete(adjCom);
        } else {
            this.nodeConnectionsWeight[node].set(adjCom, nodeEdgesTo - e.weight);
            this.nodeConnectionsCount[node].set(adjCom, nodeCountEdgesTo - 1);
        }

    }

    source.remove(node);
};

/**
 * @param {Number} node
 * @param {Community} to
 */
CommunityStructure.prototype.moveNodeTo = function (node, to) {

    var source = this.nodeCommunities[node];
    this.removeNodeFrom(node, source);
    this.addNodeTo(node, to);

};


CommunityStructure.prototype.zoomOut = function () {
    var realCommunities = this.communities.reduce(function (arr, value) {
        arr.push(value);
        return arr;
    }, []);
    var M = realCommunities.length; // size
    var /** @type Array.< Array.<ModEdge> > */ newTopology = new Array(M);
    var index = 0;

    this.nodeCommunities = new Array(M);
    this.nodeConnectionsWeight = new Array(M);
    this.nodeConnectionsCount = new Array(M);

    var /** @type Map.<Number, Community>*/ newInvMap = new Map();
    realCommunities.forEach(function (com) {

        var weightSum = 0;
        this.nodeConnectionsWeight[index] = new Map();
        this.nodeConnectionsCount[index] = new Map();
        newTopology[index] = [];
        this.nodeCommunities[index] = new Community(com);
        //var iter = com.connectionsWeight.keySet();

        var hidden = new Community(this.structure);

        com.nodes.forEach(function (nodeInt) {

            var oldHidden = this.invMap.get(nodeInt);
            oldHidden.nodes.forEach(hidden.nodes.add.bind(hidden.nodes));

        }, this);

        newInvMap.set(index, hidden);
        com.connectionsWeight.forEach(function (weight, adjCom) {

            var target = realCommunities.indexOf(adjCom);
            if (!~target) return;
            if (target == index) {
                weightSum += 2. * weight;
            } else {
                weightSum += weight;
            }
            var e = new ModEdge(index, target, weight);
            newTopology[index].push(e);

        }, this);

        this.weights[index] = weightSum;
        this.nodeCommunities[index].seed(index);

        index++;

    }.bind(this));

    this.communities = [];

    for (var i = 0; i < M; i++) {
        var com = this.nodeCommunities[i];
        this.communities.push(com);
        for (var ei in newTopology[i]) {
            //noinspection JSUnfilteredForInLoop
            var e = newTopology[i][ei];
            this.nodeConnectionsWeight[i].set(this.nodeCommunities[e.target], e.weight);
            this.nodeConnectionsCount[i].set(this.nodeCommunities[e.target], 1);
            com.connectionsWeight.set(this.nodeCommunities[e.target], e.weight);
            com.connectionsCount.set(this.nodeCommunities[e.target], 1);
        }

    }

    this.N = M;
    this.topology = newTopology;
    this.invMap = newInvMap;

};

module.exports = CommunityStructure;

/***/ }),
/* 4 */
/***/ (function(module, exports) {

/**
 * @param {CommunityStructure|Community} com
 * @constructor
 */
function Community(com) {

    /** @type {CommunityStructure} */
    this.structure = com.structure ? com.structure : com;

    /** @type {Map.<Community, Number>} */
    this.connectionsWeight = new Map();

    /** @type {Map.<Community, Number>} */
    this.connectionsCount = new Map();

    /** @type {Set.<Number>} */
    this.nodes = new Set;

    this.weightSum = 0;


}

/**
 * @public
 * @returns {Number}
 */
Community.prototype.size = function() {
    return this.nodes.size;
};


/**
 * @param {Number} node
 */
Community.prototype.seed = function(node) {

    this.nodes.add(node);
    this.weightSum += this.structure.weights[node];

};

/**
 * @param {Number} nodeId
 * @returns {boolean}
 */
Community.prototype.add = function(nodeId) {

    this.nodes.add(nodeId);
    this.weightSum += this.structure.weights[nodeId];
    return true;

};

/**
 * @param {Number} node
 * @returns {boolean}
 */
Community.prototype.remove = function(node) {

    var result = this.nodes.delete(node);

    this.weightSum -= this.structure.weights[node];
    if (!this.nodes.size) {
        var index = this.structure.communities.indexOf(this);
        delete this.structure.communities[index];
    }

    return result;
};

module.exports = Community;


/***/ }),
/* 5 */
/***/ (function(module, exports) {

/**
 *
 * @param s
 * @param t
 * @param w
 * @constructor
 */
function ModEdge(s, t, w) {
    /** @type {Number} */
    this.source = s;
    /** @type {Number} */
    this.target = t;
    /** @type {Number} */
    this.weight = w;
}

module.exports = ModEdge;


/***/ }),
/* 6 */
/***/ (function(module, exports, __webpack_require__) {

module.exports.degree = __webpack_require__(7);
module.exports.betweenness = __webpack_require__(8);


/***/ }),
/* 7 */
/***/ (function(module, exports) {

module.exports = degree;

/**
 * Calculates graph nodes degree centrality (in/out or both).
 *
 * @see http://en.wikipedia.org/wiki/Centrality#Degree_centrality
 *
 * @param {ngraph.graph} graph object for which we are calculating centrality.
 * @param {string} [kind=both] What kind of degree centrality needs to be calculated:
 *   'in'    - calculate in-degree centrality
 *   'out'   - calculate out-degree centrality
 *   'inout' - (default) generic degree centrality is calculated
 */
function degree(graph, kind) {
  var getNodeDegree,
    sortedDegrees = [],
    result = Object.create(null),
    nodeDegree;

  kind = (kind || 'both').toLowerCase();
  if (kind === 'both' || kind === 'inout') {
    getNodeDegree = inoutDegreeCalculator;
  } else if (kind === 'in') {
    getNodeDegree = inDegreeCalculator;
  } else if (kind === 'out') {
    getNodeDegree = outDegreeCalculator;
  } else {
    throw new Error('Expected centrality degree kind is: in, out or both');
  }

  graph.forEachNode(calculateNodeDegree);

  return result;

  function calculateNodeDegree(node) {
    var links = graph.getLinks(node.id);
    result[node.id] = getNodeDegree(links, node.id);
  }
}

function inDegreeCalculator(links, nodeId) {
  var total = 0;
  if (!links) return total;

  for (var i = 0; i < links.length; i += 1) {
    total += (links[i].toId === nodeId) ? 1 : 0;
  }
  return total;
}

function outDegreeCalculator(links, nodeId) {
  var total = 0;
  if (!links) return total;

  for (var i = 0; i < links.length; i += 1) {
    total += (links[i].fromId === nodeId) ? 1 : 0;
  }
  return total;
}

function inoutDegreeCalculator(links) {
  if (!links) return 0;

  return links.length;
}


/***/ }),
/* 8 */
/***/ (function(module, exports) {

module.exports = betweennes;

/**
 * I'm using http://www.inf.uni-konstanz.de/algo/publications/b-vspbc-08.pdf
 * as a reference for this implementation
 */
function betweennes(graph, oriented) {
  var Q = [],
    S = []; // Queue and Stack
  // list of predcessors on shorteest paths from source
  var pred = Object.create(null);
  // distance from source
  var dist = Object.create(null);
  // number of shortest paths from source to key
  var sigma = Object.create(null);
  // dependency of source on key
  var delta = Object.create(null);

  var currentNode;
  var centrality = Object.create(null);

  graph.forEachNode(setCentralityToZero);
  graph.forEachNode(calculateCentrality);

  if (!oriented) {
    // The centrality scores need to be divided by two if the graph is not oriented,
    // since all shortest paths are considered twice
    Object.keys(centrality).forEach(divideByTwo);
  }

  return centrality;

  function divideByTwo(key) {
    centrality[key] /= 2;
  }

  function setCentralityToZero(node) {
    centrality[node.id] = 0;
  }

  function calculateCentrality(node) {
    currentNode = node.id;
    singleSourceShortestPath(currentNode);
    accumulate();
  }

  function accumulate() {
    graph.forEachNode(setDeltaToZero);
    while (S.length) {
      var w = S.pop();
      var coeff = (1 + delta[w])/sigma[w];
      var predcessors = pred[w];
      for (var idx = 0; idx < predcessors.length; ++idx) {
        var v = predcessors[idx];
        delta[v] += sigma[v] * coeff;
      }
      if (w !== currentNode) {
        centrality[w] += delta[w];
      }
    }
  }

  function setDeltaToZero(node) {
    delta[node.id] = 0;
  }

  function singleSourceShortestPath(source) {
    graph.forEachNode(initNode);
    dist[source] = 0;
    sigma[source] = 1;
    Q.push(source);

    while (Q.length) {
      var v = Q.shift();
      var dedup = Object.create(null);
      S.push(v);
      graph.forEachLinkedNode(v, toId, oriented);
    }

    function toId(otherNode) {
      // NOTE: This code will also consider multi-edges, which are often
      // ignored by popular software (Gephi/NetworkX). Depending on your use
      // case this may not be desired and deduping needs to be performed. To
      // save memory I'm not deduping here...
      processNode(otherNode.id);
    }

    function initNode(node) {
      var nodeId = node.id;
      pred[nodeId] = []; // empty list
      dist[nodeId] = -1;
      sigma[nodeId] = 0;
    }

    function processNode(w) {
      // path discovery
      if (dist[w] === -1) {
        // Node w is found for the first time
        dist[w] = dist[v] + 1;
        Q.push(w);
      }
      // path counting
      if (dist[w] === dist[v] + 1) {
        // edge (v, w) on a shortest path
        sigma[w] += sigma[v];
        pred[w].push(v);
      }
    }
  }
}


/***/ }),
/* 9 */
/***/ (function(module, exports) {

module.exports = __WEBPACK_EXTERNAL_MODULE_9__;

/***/ }),
/* 10 */
/***/ (function(module, exports, __webpack_require__) {

/**
 * @fileOverview Contains definition of the core graph object.
 */

/**
 * @example
 *  var graph = require('ngraph.graph')();
 *  graph.addNode(1);     // graph has one node.
 *  graph.addLink(2, 3);  // now graph contains three nodes and one link.
 *
 */
module.exports = createGraph;

var eventify = __webpack_require__(11);

/**
 * Creates a new graph
 */
function createGraph(options) {
  // Graph structure is maintained as dictionary of nodes
  // and array of links. Each node has 'links' property which
  // hold all links related to that node. And general links
  // array is used to speed up all links enumeration. This is inefficient
  // in terms of memory, but simplifies coding.
  options = options || {};
  if (options.uniqueLinkId === undefined) {
    // Request each link id to be unique between same nodes. This negatively
    // impacts `addLink()` performance (O(n), where n - number of edges of each
    // vertex), but makes operations with multigraphs more accessible.
    options.uniqueLinkId = true;
  }

  var nodes = typeof Object.create === 'function' ? Object.create(null) : {},
    links = [],
    // Hash of multi-edges. Used to track ids of edges between same nodes
    multiEdges = {},
    nodesCount = 0,
    suspendEvents = 0,

    forEachNode = createNodeIterator(),
    createLink = options.uniqueLinkId ? createUniqueLink : createSingleLink,

    // Our graph API provides means to listen to graph changes. Users can subscribe
    // to be notified about changes in the graph by using `on` method. However
    // in some cases they don't use it. To avoid unnecessary memory consumption
    // we will not record graph changes until we have at least one subscriber.
    // Code below supports this optimization.
    //
    // Accumulates all changes made during graph updates.
    // Each change element contains:
    //  changeType - one of the strings: 'add', 'remove' or 'update';
    //  node - if change is related to node this property is set to changed graph's node;
    //  link - if change is related to link this property is set to changed graph's link;
    changes = [],
    recordLinkChange = noop,
    recordNodeChange = noop,
    enterModification = noop,
    exitModification = noop;

  // this is our public API:
  var graphPart = {
    /**
     * Adds node to the graph. If node with given id already exists in the graph
     * its data is extended with whatever comes in 'data' argument.
     *
     * @param nodeId the node's identifier. A string or number is preferred.
     * @param [data] additional data for the node being added. If node already
     *   exists its data object is augmented with the new one.
     *
     * @return {node} The newly added node or node with given id if it already exists.
     */
    addNode: addNode,

    /**
     * Adds a link to the graph. The function always create a new
     * link between two nodes. If one of the nodes does not exists
     * a new node is created.
     *
     * @param fromId link start node id;
     * @param toId link end node id;
     * @param [data] additional data to be set on the new link;
     *
     * @return {link} The newly created link
     */
    addLink: addLink,

    /**
     * Removes link from the graph. If link does not exist does nothing.
     *
     * @param link - object returned by addLink() or getLinks() methods.
     *
     * @returns true if link was removed; false otherwise.
     */
    removeLink: removeLink,

    /**
     * Removes node with given id from the graph. If node does not exist in the graph
     * does nothing.
     *
     * @param nodeId node's identifier passed to addNode() function.
     *
     * @returns true if node was removed; false otherwise.
     */
    removeNode: removeNode,

    /**
     * Gets node with given identifier. If node does not exist undefined value is returned.
     *
     * @param nodeId requested node identifier;
     *
     * @return {node} in with requested identifier or undefined if no such node exists.
     */
    getNode: getNode,

    /**
     * Gets number of nodes in this graph.
     *
     * @return number of nodes in the graph.
     */
    getNodesCount: function() {
      return nodesCount;
    },

    /**
     * Gets total number of links in the graph.
     */
    getLinksCount: function() {
      return links.length;
    },

    /**
     * Gets all links (inbound and outbound) from the node with given id.
     * If node with given id is not found null is returned.
     *
     * @param nodeId requested node identifier.
     *
     * @return Array of links from and to requested node if such node exists;
     *   otherwise null is returned.
     */
    getLinks: getLinks,

    /**
     * Invokes callback on each node of the graph.
     *
     * @param {Function(node)} callback Function to be invoked. The function
     *   is passed one argument: visited node.
     */
    forEachNode: forEachNode,

    /**
     * Invokes callback on every linked (adjacent) node to the given one.
     *
     * @param nodeId Identifier of the requested node.
     * @param {Function(node, link)} callback Function to be called on all linked nodes.
     *   The function is passed two parameters: adjacent node and link object itself.
     * @param oriented if true graph treated as oriented.
     */
    forEachLinkedNode: forEachLinkedNode,

    /**
     * Enumerates all links in the graph
     *
     * @param {Function(link)} callback Function to be called on all links in the graph.
     *   The function is passed one parameter: graph's link object.
     *
     * Link object contains at least the following fields:
     *  fromId - node id where link starts;
     *  toId - node id where link ends,
     *  data - additional data passed to graph.addLink() method.
     */
    forEachLink: forEachLink,

    /**
     * Suspend all notifications about graph changes until
     * endUpdate is called.
     */
    beginUpdate: enterModification,

    /**
     * Resumes all notifications about graph changes and fires
     * graph 'changed' event in case there are any pending changes.
     */
    endUpdate: exitModification,

    /**
     * Removes all nodes and links from the graph.
     */
    clear: clear,

    /**
     * Detects whether there is a link between two nodes.
     * Operation complexity is O(n) where n - number of links of a node.
     * NOTE: this function is synonim for getLink()
     *
     * @returns link if there is one. null otherwise.
     */
    hasLink: getLink,

    /**
     * Gets an edge between two nodes.
     * Operation complexity is O(n) where n - number of links of a node.
     *
     * @param {string} fromId link start identifier
     * @param {string} toId link end identifier
     *
     * @returns link if there is one. null otherwise.
     */
    getLink: getLink
  };

  // this will add `on()` and `fire()` methods.
  eventify(graphPart);

  monitorSubscribers();

  return graphPart;

  function monitorSubscribers() {
    var realOn = graphPart.on;

    // replace real `on` with our temporary on, which will trigger change
    // modification monitoring:
    graphPart.on = on;

    function on() {
      // now it's time to start tracking stuff:
      graphPart.beginUpdate = enterModification = enterModificationReal;
      graphPart.endUpdate = exitModification = exitModificationReal;
      recordLinkChange = recordLinkChangeReal;
      recordNodeChange = recordNodeChangeReal;

      // this will replace current `on` method with real pub/sub from `eventify`.
      graphPart.on = realOn;
      // delegate to real `on` handler:
      return realOn.apply(graphPart, arguments);
    }
  }

  function recordLinkChangeReal(link, changeType) {
    changes.push({
      link: link,
      changeType: changeType
    });
  }

  function recordNodeChangeReal(node, changeType) {
    changes.push({
      node: node,
      changeType: changeType
    });
  }

  function addNode(nodeId, data) {
    if (nodeId === undefined) {
      throw new Error('Invalid node identifier');
    }

    enterModification();

    var node = getNode(nodeId);
    if (!node) {
      node = new Node(nodeId);
      nodesCount++;
      recordNodeChange(node, 'add');
    } else {
      recordNodeChange(node, 'update');
    }

    node.data = data;

    nodes[nodeId] = node;

    exitModification();
    return node;
  }

  function getNode(nodeId) {
    return nodes[nodeId];
  }

  function removeNode(nodeId) {
    var node = getNode(nodeId);
    if (!node) {
      return false;
    }

    enterModification();

    if (node.links) {
      while (node.links.length) {
        var link = node.links[0];
        removeLink(link);
      }
    }

    delete nodes[nodeId];
    nodesCount--;

    recordNodeChange(node, 'remove');

    exitModification();

    return true;
  }


  function addLink(fromId, toId, data) {
    enterModification();

    var fromNode = getNode(fromId) || addNode(fromId);
    var toNode = getNode(toId) || addNode(toId);

    var link = createLink(fromId, toId, data);

    links.push(link);

    // TODO: this is not cool. On large graphs potentially would consume more memory.
    addLinkToNode(fromNode, link);
    if (fromId !== toId) {
      // make sure we are not duplicating links for self-loops
      addLinkToNode(toNode, link);
    }

    recordLinkChange(link, 'add');

    exitModification();

    return link;
  }

  function createSingleLink(fromId, toId, data) {
    var linkId = makeLinkId(fromId, toId);
    return new Link(fromId, toId, data, linkId);
  }

  function createUniqueLink(fromId, toId, data) {
    // TODO: Get rid of this method.
    var linkId = makeLinkId(fromId, toId);
    var isMultiEdge = multiEdges.hasOwnProperty(linkId);
    if (isMultiEdge || getLink(fromId, toId)) {
      if (!isMultiEdge) {
        multiEdges[linkId] = 0;
      }
      var suffix = '@' + (++multiEdges[linkId]);
      linkId = makeLinkId(fromId + suffix, toId + suffix);
    }

    return new Link(fromId, toId, data, linkId);
  }

  function getLinks(nodeId) {
    var node = getNode(nodeId);
    return node ? node.links : null;
  }

  function removeLink(link) {
    if (!link) {
      return false;
    }
    var idx = indexOfElementInArray(link, links);
    if (idx < 0) {
      return false;
    }

    enterModification();

    links.splice(idx, 1);

    var fromNode = getNode(link.fromId);
    var toNode = getNode(link.toId);

    if (fromNode) {
      idx = indexOfElementInArray(link, fromNode.links);
      if (idx >= 0) {
        fromNode.links.splice(idx, 1);
      }
    }

    if (toNode) {
      idx = indexOfElementInArray(link, toNode.links);
      if (idx >= 0) {
        toNode.links.splice(idx, 1);
      }
    }

    recordLinkChange(link, 'remove');

    exitModification();

    return true;
  }

  function getLink(fromNodeId, toNodeId) {
    // TODO: Use sorted links to speed this up
    var node = getNode(fromNodeId),
      i;
    if (!node || !node.links) {
      return null;
    }

    for (i = 0; i < node.links.length; ++i) {
      var link = node.links[i];
      if (link.fromId === fromNodeId && link.toId === toNodeId) {
        return link;
      }
    }

    return null; // no link.
  }

  function clear() {
    enterModification();
    forEachNode(function(node) {
      removeNode(node.id);
    });
    exitModification();
  }

  function forEachLink(callback) {
    var i, length;
    if (typeof callback === 'function') {
      for (i = 0, length = links.length; i < length; ++i) {
        callback(links[i]);
      }
    }
  }

  function forEachLinkedNode(nodeId, callback, oriented) {
    var node = getNode(nodeId);

    if (node && node.links && typeof callback === 'function') {
      if (oriented) {
        return forEachOrientedLink(node.links, nodeId, callback);
      } else {
        return forEachNonOrientedLink(node.links, nodeId, callback);
      }
    }
  }

  function forEachNonOrientedLink(links, nodeId, callback) {
    var quitFast;
    for (var i = 0; i < links.length; ++i) {
      var link = links[i];
      var linkedNodeId = link.fromId === nodeId ? link.toId : link.fromId;

      quitFast = callback(nodes[linkedNodeId], link);
      if (quitFast) {
        return true; // Client does not need more iterations. Break now.
      }
    }
  }

  function forEachOrientedLink(links, nodeId, callback) {
    var quitFast;
    for (var i = 0; i < links.length; ++i) {
      var link = links[i];
      if (link.fromId === nodeId) {
        quitFast = callback(nodes[link.toId], link);
        if (quitFast) {
          return true; // Client does not need more iterations. Break now.
        }
      }
    }
  }

  // we will not fire anything until users of this library explicitly call `on()`
  // method.
  function noop() {}

  // Enter, Exit modification allows bulk graph updates without firing events.
  function enterModificationReal() {
    suspendEvents += 1;
  }

  function exitModificationReal() {
    suspendEvents -= 1;
    if (suspendEvents === 0 && changes.length > 0) {
      graphPart.fire('changed', changes);
      changes.length = 0;
    }
  }

  function createNodeIterator() {
    // Object.keys iterator is 1.3x faster than `for in` loop.
    // See `https://github.com/anvaka/ngraph.graph/tree/bench-for-in-vs-obj-keys`
    // branch for perf test
    return Object.keys ? objectKeysIterator : forInIterator;
  }

  function objectKeysIterator(callback) {
    if (typeof callback !== 'function') {
      return;
    }

    var keys = Object.keys(nodes);
    for (var i = 0; i < keys.length; ++i) {
      if (callback(nodes[keys[i]])) {
        return true; // client doesn't want to proceed. Return.
      }
    }
  }

  function forInIterator(callback) {
    if (typeof callback !== 'function') {
      return;
    }
    var node;

    for (node in nodes) {
      if (callback(nodes[node])) {
        return true; // client doesn't want to proceed. Return.
      }
    }
  }
}

// need this for old browsers. Should this be a separate module?
function indexOfElementInArray(element, array) {
  if (!array) return -1;

  if (array.indexOf) {
    return array.indexOf(element);
  }

  var len = array.length,
    i;

  for (i = 0; i < len; i += 1) {
    if (array[i] === element) {
      return i;
    }
  }

  return -1;
}

/**
 * Internal structure to represent node;
 */
function Node(id) {
  this.id = id;
  this.links = null;
  this.data = null;
}

function addLinkToNode(node, link) {
  if (node.links) {
    node.links.push(link);
  } else {
    node.links = [link];
  }
}

/**
 * Internal structure to represent links;
 */
function Link(fromId, toId, data, id) {
  this.fromId = fromId;
  this.toId = toId;
  this.data = data;
  this.id = id;
}

function hashCode(str) {
  var hash = 0, i, chr, len;
  if (str.length == 0) return hash;
  for (i = 0, len = str.length; i < len; i++) {
    chr   = str.charCodeAt(i);
    hash  = ((hash << 5) - hash) + chr;
    hash |= 0; // Convert to 32bit integer
  }
  return hash;
}

function makeLinkId(fromId, toId) {
  return hashCode(fromId.toString() + '👉 ' + toId.toString());
}


/***/ }),
/* 11 */
/***/ (function(module, exports) {

module.exports = function(subject) {
  validateSubject(subject);

  var eventsStorage = createEventsStorage(subject);
  subject.on = eventsStorage.on;
  subject.off = eventsStorage.off;
  subject.fire = eventsStorage.fire;
  return subject;
};

function createEventsStorage(subject) {
  // Store all event listeners to this hash. Key is event name, value is array
  // of callback records.
  //
  // A callback record consists of callback function and its optional context:
  // { 'eventName' => [{callback: function, ctx: object}] }
  var registeredEvents = Object.create(null);

  return {
    on: function (eventName, callback, ctx) {
      if (typeof callback !== 'function') {
        throw new Error('callback is expected to be a function');
      }
      var handlers = registeredEvents[eventName];
      if (!handlers) {
        handlers = registeredEvents[eventName] = [];
      }
      handlers.push({callback: callback, ctx: ctx});

      return subject;
    },

    off: function (eventName, callback) {
      var wantToRemoveAll = (typeof eventName === 'undefined');
      if (wantToRemoveAll) {
        // Killing old events storage should be enough in this case:
        registeredEvents = Object.create(null);
        return subject;
      }

      if (registeredEvents[eventName]) {
        var deleteAllCallbacksForEvent = (typeof callback !== 'function');
        if (deleteAllCallbacksForEvent) {
          delete registeredEvents[eventName];
        } else {
          var callbacks = registeredEvents[eventName];
          for (var i = 0; i < callbacks.length; ++i) {
            if (callbacks[i].callback === callback) {
              callbacks.splice(i, 1);
            }
          }
        }
      }

      return subject;
    },

    fire: function (eventName) {
      var callbacks = registeredEvents[eventName];
      if (!callbacks) {
        return subject;
      }

      var fireArguments;
      if (arguments.length > 1) {
        fireArguments = Array.prototype.splice.call(arguments, 1);
      }
      for(var i = 0; i < callbacks.length; ++i) {
        var callbackInfo = callbacks[i];
        callbackInfo.callback.apply(callbackInfo.ctx, fireArguments);
      }

      return subject;
    }
  };
}

function validateSubject(subject) {
  if (!subject) {
    throw new Error('Eventify cannot use falsy object as events subject');
  }
  var reservedWords = ['on', 'fire', 'off'];
  for (var i = 0; i < reservedWords.length; ++i) {
    if (subject.hasOwnProperty(reservedWords[i])) {
      throw new Error("Subject cannot be eventified, since it already has property '" + reservedWords[i] + "'");
    }
  }
}


/***/ })
/******/ ]);
});