vis.js is a dynamic, browser-based visualization library
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1301 lines
41 KiB

9 years ago
9 years ago
  1. /* ===========================================================================
  2. # TODO
  3. - `edgeReplacedById` not cleaned up yet on cluster edge removal
  4. - check correct working for everything for clustered clusters (could use a unit test)
  5. - Handle recursive unclustering on node removal
  6. - `updateState()` not complete; scan TODO's there
  7. ----------------------------------------------
  8. # State Model for Clustering
  9. The total state for clustering is non-trivial. It is useful to have a model
  10. available as to how it works. The following documents the relevant state items.
  11. ## Network State
  12. The following `network`-members are relevant to clustering:
  13. - `body.nodes` - all nodes actively participating in the network
  14. - `body.edges` - same for edges
  15. - `body.nodeIndices` - id's of nodes that are visible at a given moment
  16. - `body.edgeIndices` - same for edges
  17. This includes:
  18. - helper nodes for dragging in `manipulation`
  19. - helper nodes for edge type `dynamic`
  20. - cluster nodes and edges
  21. - there may be more than this.
  22. A node/edge may be missing in the `Indices` member if:
  23. - it is a helper node
  24. - the node or edge state has option `hidden` set
  25. - It is not visible due to clustering
  26. ## Clustering State
  27. For the hashes, the id's of the nodes/edges are used as key.
  28. Member `network.clustering` contains the following items:
  29. - `clusteredNodes` - hash with values: { clusterId: <id of cluster>, node: <node instance>}
  30. - `clusteredEdges` - hash with values: restore information for given edge
  31. Due to nesting of clusters, these members can contain cluster nodes and edges as well.
  32. The important thing to note here, is that the clustered nodes and edges also
  33. appear in the members of the cluster nodes. For data update, it is therefore
  34. important to scan these lists as well as the cluster nodes.
  35. ### Cluster Node
  36. A cluster node has the following extra fields:
  37. - `isCluster : true` - indication that this is a cluster node
  38. - `containedNodes` - hash of nodes contained in this cluster
  39. - `containedEdges` - same for edges
  40. - `edges` - hash of cluster edges for this node
  41. **NOTE:**
  42. - `containedEdges` can also contain edges which are not clustered; e.g. an edge
  43. connecting two nodes in the same cluster.
  44. ### Cluster Edge
  45. These are the items in the `edges` member of a clustered node. They have the
  46. following relevant members:
  47. - 'clusteringEdgeReplacingIds` - array of id's of edges replaced by this edge
  48. Note that it's possible to nest clusters, so that `clusteringEdgeReplacingIds`
  49. can contain edge id's of other clusters.
  50. ### Clustered Edge
  51. This is any edge contained by a cluster edge. It gets the following additional
  52. member:
  53. - `edgeReplacedById` - id of the cluster edge in which current edge is clustered
  54. =========================================================================== */
  55. let util = require("../../util");
  56. var NetworkUtil = require('../NetworkUtil').default;
  57. var Cluster = require('./components/nodes/Cluster').default;
  58. var Edge = require('./components/Edge').default; // Only needed for check on type!
  59. var Node = require('./components/Node').default; // Only needed for check on type!
  60. class ClusterEngine {
  61. constructor(body) {
  62. this.body = body;
  63. this.clusteredNodes = {}; // key: node id, value: { clusterId: <id of cluster>, node: <node instance>}
  64. this.clusteredEdges = {}; // key: edge id, value: restore information for given edge
  65. this.options = {};
  66. this.defaultOptions = {};
  67. util.extend(this.options, this.defaultOptions);
  68. this.body.emitter.on('_resetData', () => {this.clusteredNodes = {}; this.clusteredEdges = {};})
  69. }
  70. /**
  71. *
  72. * @param hubsize
  73. * @param options
  74. */
  75. clusterByHubsize(hubsize, options) {
  76. if (hubsize === undefined) {
  77. hubsize = this._getHubSize();
  78. }
  79. else if (typeof(hubsize) === "object") {
  80. options = this._checkOptions(hubsize);
  81. hubsize = this._getHubSize();
  82. }
  83. let nodesToCluster = [];
  84. for (let i = 0; i < this.body.nodeIndices.length; i++) {
  85. let node = this.body.nodes[this.body.nodeIndices[i]];
  86. if (node.edges.length >= hubsize) {
  87. nodesToCluster.push(node.id);
  88. }
  89. }
  90. for (let i = 0; i < nodesToCluster.length; i++) {
  91. this.clusterByConnection(nodesToCluster[i],options,true);
  92. }
  93. this.body.emitter.emit('_dataChanged');
  94. }
  95. /**
  96. * loop over all nodes, check if they adhere to the condition and cluster if needed.
  97. * @param options
  98. * @param refreshData
  99. */
  100. cluster(options = {}, refreshData = true) {
  101. if (options.joinCondition === undefined) {throw new Error("Cannot call clusterByNodeData without a joinCondition function in the options.");}
  102. // check if the options object is fine, append if needed
  103. options = this._checkOptions(options);
  104. let childNodesObj = {};
  105. let childEdgesObj = {};
  106. // collect the nodes that will be in the cluster
  107. for (let nodeId in this.body.nodes) {
  108. if (!this.body.nodes.hasOwnProperty(nodeId)) continue;
  109. let node = this.body.nodes[nodeId];
  110. let clonedOptions = NetworkUtil.cloneOptions(node);
  111. if (options.joinCondition(clonedOptions) === true) {
  112. childNodesObj[nodeId] = this.body.nodes[nodeId];
  113. // collect the edges that will be in the cluster
  114. for (let i = 0; i < node.edges.length; i++) {
  115. let edge = node.edges[i];
  116. if (this.clusteredEdges[edge.id] === undefined) {
  117. childEdgesObj[edge.id] = edge;
  118. }
  119. }
  120. }
  121. }
  122. this._cluster(childNodesObj, childEdgesObj, options, refreshData);
  123. }
  124. /**
  125. * Cluster all nodes in the network that have only X edges
  126. * @param edgeCount
  127. * @param options
  128. * @param refreshData
  129. */
  130. clusterByEdgeCount(edgeCount, options, refreshData = true) {
  131. options = this._checkOptions(options);
  132. let clusters = [];
  133. let usedNodes = {};
  134. let edge, edges, node, nodeId, relevantEdgeCount;
  135. // collect the nodes that will be in the cluster
  136. for (let i = 0; i < this.body.nodeIndices.length; i++) {
  137. let childNodesObj = {};
  138. let childEdgesObj = {};
  139. nodeId = this.body.nodeIndices[i];
  140. // if this node is already used in another cluster this session, we do not have to re-evaluate it.
  141. if (usedNodes[nodeId] === undefined) {
  142. relevantEdgeCount = 0;
  143. node = this.body.nodes[nodeId];
  144. edges = [];
  145. for (let j = 0; j < node.edges.length; j++) {
  146. edge = node.edges[j];
  147. if (this.clusteredEdges[edge.id] === undefined) {
  148. if (edge.toId !== edge.fromId) {
  149. relevantEdgeCount++;
  150. }
  151. edges.push(edge);
  152. }
  153. }
  154. // this node qualifies, we collect its neighbours to start the clustering process.
  155. if (relevantEdgeCount === edgeCount) {
  156. let gatheringSuccessful = true;
  157. for (let j = 0; j < edges.length; j++) {
  158. edge = edges[j];
  159. let childNodeId = this._getConnectedId(edge, nodeId);
  160. // add the nodes to the list by the join condition.
  161. if (options.joinCondition === undefined) {
  162. childEdgesObj[edge.id] = edge;
  163. childNodesObj[nodeId] = this.body.nodes[nodeId];
  164. childNodesObj[childNodeId] = this.body.nodes[childNodeId];
  165. usedNodes[nodeId] = true;
  166. }
  167. else {
  168. let clonedOptions = NetworkUtil.cloneOptions(this.body.nodes[nodeId]);
  169. if (options.joinCondition(clonedOptions) === true) {
  170. childEdgesObj[edge.id] = edge;
  171. childNodesObj[nodeId] = this.body.nodes[nodeId];
  172. usedNodes[nodeId] = true;
  173. }
  174. else {
  175. // this node does not qualify after all.
  176. gatheringSuccessful = false;
  177. break;
  178. }
  179. }
  180. }
  181. // add to the cluster queue
  182. if (Object.keys(childNodesObj).length > 0 && Object.keys(childEdgesObj).length > 0 && gatheringSuccessful === true) {
  183. clusters.push({nodes: childNodesObj, edges: childEdgesObj})
  184. }
  185. }
  186. }
  187. }
  188. for (let i = 0; i < clusters.length; i++) {
  189. this._cluster(clusters[i].nodes, clusters[i].edges, options, false)
  190. }
  191. if (refreshData === true) {
  192. this.body.emitter.emit('_dataChanged');
  193. }
  194. }
  195. /**
  196. * Cluster all nodes in the network that have only 1 edge
  197. * @param options
  198. * @param refreshData
  199. */
  200. clusterOutliers(options, refreshData = true) {
  201. this.clusterByEdgeCount(1,options,refreshData);
  202. }
  203. /**
  204. * Cluster all nodes in the network that have only 2 edge
  205. * @param options
  206. * @param refreshData
  207. */
  208. clusterBridges(options, refreshData = true) {
  209. this.clusterByEdgeCount(2,options,refreshData);
  210. }
  211. /**
  212. * suck all connected nodes of a node into the node.
  213. * @param nodeId
  214. * @param options
  215. * @param refreshData
  216. */
  217. clusterByConnection(nodeId, options, refreshData = true) {
  218. // kill conditions
  219. if (nodeId === undefined) {throw new Error("No nodeId supplied to clusterByConnection!");}
  220. if (this.body.nodes[nodeId] === undefined) {throw new Error("The nodeId given to clusterByConnection does not exist!");}
  221. let node = this.body.nodes[nodeId];
  222. options = this._checkOptions(options, node);
  223. if (options.clusterNodeProperties.x === undefined) {options.clusterNodeProperties.x = node.x;}
  224. if (options.clusterNodeProperties.y === undefined) {options.clusterNodeProperties.y = node.y;}
  225. if (options.clusterNodeProperties.fixed === undefined) {
  226. options.clusterNodeProperties.fixed = {};
  227. options.clusterNodeProperties.fixed.x = node.options.fixed.x;
  228. options.clusterNodeProperties.fixed.y = node.options.fixed.y;
  229. }
  230. let childNodesObj = {};
  231. let childEdgesObj = {};
  232. let parentNodeId = node.id;
  233. let parentClonedOptions = NetworkUtil.cloneOptions(node);
  234. childNodesObj[parentNodeId] = node;
  235. // collect the nodes that will be in the cluster
  236. for (let i = 0; i < node.edges.length; i++) {
  237. let edge = node.edges[i];
  238. if (this.clusteredEdges[edge.id] === undefined) {
  239. let childNodeId = this._getConnectedId(edge, parentNodeId);
  240. // if the child node is not in a cluster
  241. if (this.clusteredNodes[childNodeId] === undefined) {
  242. if (childNodeId !== parentNodeId) {
  243. if (options.joinCondition === undefined) {
  244. childEdgesObj[edge.id] = edge;
  245. childNodesObj[childNodeId] = this.body.nodes[childNodeId];
  246. }
  247. else {
  248. // clone the options and insert some additional parameters that could be interesting.
  249. let childClonedOptions = NetworkUtil.cloneOptions(this.body.nodes[childNodeId]);
  250. if (options.joinCondition(parentClonedOptions, childClonedOptions) === true) {
  251. childEdgesObj[edge.id] = edge;
  252. childNodesObj[childNodeId] = this.body.nodes[childNodeId];
  253. }
  254. }
  255. }
  256. else {
  257. // swallow the edge if it is self-referencing.
  258. childEdgesObj[edge.id] = edge;
  259. }
  260. }
  261. }
  262. }
  263. var childNodeIDs = Object.keys(childNodesObj).map(function(childNode){
  264. return childNodesObj[childNode].id;
  265. })
  266. for (childNode in childNodesObj) {
  267. var childNode = childNodesObj[childNode];
  268. for (var y=0; y < childNode.edges.length; y++){
  269. var childEdge = childNode.edges[y];
  270. if (childNodeIDs.indexOf(this._getConnectedId(childEdge,childNode.id)) > -1){
  271. childEdgesObj[childEdge.id] = childEdge;
  272. }
  273. }
  274. }
  275. this._cluster(childNodesObj, childEdgesObj, options, refreshData);
  276. }
  277. /**
  278. * This function creates the edges that will be attached to the cluster
  279. * It looks for edges that are connected to the nodes from the "outside' of the cluster.
  280. *
  281. * @param childNodesObj
  282. * @param childEdgesObj
  283. * @param clusterNodeProperties
  284. * @param clusterEdgeProperties
  285. * @private
  286. */
  287. _createClusterEdges (childNodesObj, childEdgesObj, clusterNodeProperties, clusterEdgeProperties) {
  288. let edge, childNodeId, childNode, toId, fromId, otherNodeId;
  289. // loop over all child nodes and their edges to find edges going out of the cluster
  290. // these edges will be replaced by clusterEdges.
  291. let childKeys = Object.keys(childNodesObj);
  292. let createEdges = [];
  293. for (let i = 0; i < childKeys.length; i++) {
  294. childNodeId = childKeys[i];
  295. childNode = childNodesObj[childNodeId];
  296. // construct new edges from the cluster to others
  297. for (let j = 0; j < childNode.edges.length; j++) {
  298. edge = childNode.edges[j];
  299. // we only handle edges that are visible to the system, not the disabled ones from the clustering process.
  300. if (this.clusteredEdges[edge.id] === undefined) {
  301. // self-referencing edges will be added to the "hidden" list
  302. if (edge.toId == edge.fromId) {
  303. childEdgesObj[edge.id] = edge;
  304. }
  305. else {
  306. // set up the from and to.
  307. if (edge.toId == childNodeId) { // this is a double equals because ints and strings can be interchanged here.
  308. toId = clusterNodeProperties.id;
  309. fromId = edge.fromId;
  310. otherNodeId = fromId;
  311. }
  312. else {
  313. toId = edge.toId;
  314. fromId = clusterNodeProperties.id;
  315. otherNodeId = toId;
  316. }
  317. }
  318. // Only edges from the cluster outwards are being replaced.
  319. if (childNodesObj[otherNodeId] === undefined) {
  320. createEdges.push({edge: edge, fromId: fromId, toId: toId});
  321. }
  322. }
  323. }
  324. }
  325. //
  326. // Here we actually create the replacement edges.
  327. //
  328. // We could not do this in the loop above as the creation process
  329. // would add an edge to the edges array we are iterating over.
  330. //
  331. // NOTE: a clustered edge can have multiple base edges!
  332. //
  333. var newEdges = [];
  334. /**
  335. * Find a cluster edge which matches the given created edge.
  336. */
  337. var getNewEdge = function(createdEdge) {
  338. for (let j = 0; j < newEdges.length; j++) {
  339. let newEdge = newEdges[j];
  340. // We replace both to and from edges with a single cluster edge
  341. let matchToDirection = (createdEdge.fromId === newEdge.fromId && createdEdge.toId === newEdge.toId);
  342. let matchFromDirection = (createdEdge.fromId === newEdge.toId && createdEdge.toId === newEdge.fromId);
  343. if (matchToDirection || matchFromDirection ) {
  344. return newEdge;
  345. }
  346. }
  347. return null;
  348. };
  349. for (let j = 0; j < createEdges.length; j++) {
  350. let createdEdge = createEdges[j];
  351. let edge = createdEdge.edge;
  352. let newEdge = getNewEdge(createdEdge);
  353. if (newEdge === null) {
  354. // Create a clustered edge for this connection
  355. newEdge = this._createClusteredEdge(
  356. createdEdge.fromId,
  357. createdEdge.toId,
  358. edge,
  359. clusterEdgeProperties);
  360. newEdges.push(newEdge);
  361. } else {
  362. newEdge.clusteringEdgeReplacingIds.push(edge.id);
  363. }
  364. // also reference the new edge in the old edge
  365. this.body.edges[edge.id].edgeReplacedById = newEdge.id;
  366. // hide the replaced edge
  367. this._backupEdgeOptions(edge);
  368. edge.setOptions({physics:false});
  369. }
  370. }
  371. /**
  372. * This function checks the options that can be supplied to the different cluster functions
  373. * for certain fields and inserts defaults if needed
  374. * @param options
  375. * @returns {*}
  376. * @private
  377. */
  378. _checkOptions(options = {}) {
  379. if (options.clusterEdgeProperties === undefined) {options.clusterEdgeProperties = {};}
  380. if (options.clusterNodeProperties === undefined) {options.clusterNodeProperties = {};}
  381. return options;
  382. }
  383. /**
  384. *
  385. * @param {Object} childNodesObj | object with node objects, id as keys, same as childNodes except it also contains a source node
  386. * @param {Object} childEdgesObj | object with edge objects, id as keys
  387. * @param {Array} options | object with {clusterNodeProperties, clusterEdgeProperties, processProperties}
  388. * @param {Boolean} refreshData | when true, do not wrap up
  389. * @private
  390. */
  391. _cluster(childNodesObj, childEdgesObj, options, refreshData = true) {
  392. // kill condition: no nodes don't bother
  393. if (Object.keys(childNodesObj).length == 0) {return;}
  394. // allow clusters of 1 if options allow
  395. if (Object.keys(childNodesObj).length == 1 && options.clusterNodeProperties.allowSingleNodeCluster != true) {return;}
  396. // check if this cluster call is not trying to cluster anything that is in another cluster.
  397. for (let nodeId in childNodesObj) {
  398. if (childNodesObj.hasOwnProperty(nodeId)) {
  399. if (this.clusteredNodes[nodeId] !== undefined) {
  400. return;
  401. }
  402. }
  403. }
  404. let clusterNodeProperties = util.deepExtend({},options.clusterNodeProperties);
  405. // construct the clusterNodeProperties
  406. if (options.processProperties !== undefined) {
  407. // get the childNode options
  408. let childNodesOptions = [];
  409. for (let nodeId in childNodesObj) {
  410. if (childNodesObj.hasOwnProperty(nodeId)) {
  411. let clonedOptions = NetworkUtil.cloneOptions(childNodesObj[nodeId]);
  412. childNodesOptions.push(clonedOptions);
  413. }
  414. }
  415. // get cluster properties based on childNodes
  416. let childEdgesOptions = [];
  417. for (let edgeId in childEdgesObj) {
  418. if (childEdgesObj.hasOwnProperty(edgeId)) {
  419. // these cluster edges will be removed on creation of the cluster.
  420. if (edgeId.substr(0, 12) !== "clusterEdge:") {
  421. let clonedOptions = NetworkUtil.cloneOptions(childEdgesObj[edgeId], 'edge');
  422. childEdgesOptions.push(clonedOptions);
  423. }
  424. }
  425. }
  426. clusterNodeProperties = options.processProperties(clusterNodeProperties, childNodesOptions, childEdgesOptions);
  427. if (!clusterNodeProperties) {
  428. throw new Error("The processProperties function does not return properties!");
  429. }
  430. }
  431. // check if we have an unique id;
  432. if (clusterNodeProperties.id === undefined) {clusterNodeProperties.id = 'cluster:' + util.randomUUID();}
  433. let clusterId = clusterNodeProperties.id;
  434. if (clusterNodeProperties.label === undefined) {
  435. clusterNodeProperties.label = 'cluster';
  436. }
  437. // give the clusterNode a position if it does not have one.
  438. let pos = undefined;
  439. if (clusterNodeProperties.x === undefined) {
  440. pos = this._getClusterPosition(childNodesObj);
  441. clusterNodeProperties.x = pos.x;
  442. }
  443. if (clusterNodeProperties.y === undefined) {
  444. if (pos === undefined) {pos = this._getClusterPosition(childNodesObj);}
  445. clusterNodeProperties.y = pos.y;
  446. }
  447. // force the ID to remain the same
  448. clusterNodeProperties.id = clusterId;
  449. // create the clusterNode
  450. let clusterNode = this.body.functions.createNode(clusterNodeProperties, Cluster);
  451. clusterNode.isCluster = true;
  452. clusterNode.containedNodes = childNodesObj;
  453. clusterNode.containedEdges = childEdgesObj;
  454. // cache a copy from the cluster edge properties if we have to reconnect others later on
  455. clusterNode.clusterEdgeProperties = options.clusterEdgeProperties;
  456. // finally put the cluster node into global
  457. this.body.nodes[clusterNodeProperties.id] = clusterNode;
  458. this._clusterEdges(childNodesObj, childEdgesObj, clusterNodeProperties, options.clusterEdgeProperties);
  459. // set ID to undefined so no duplicates arise
  460. clusterNodeProperties.id = undefined;
  461. // wrap up
  462. if (refreshData === true) {
  463. this.body.emitter.emit('_dataChanged');
  464. }
  465. }
  466. _backupEdgeOptions(edge) {
  467. if (this.clusteredEdges[edge.id] === undefined) {
  468. this.clusteredEdges[edge.id] = {physics: edge.options.physics};
  469. }
  470. }
  471. _restoreEdge(edge) {
  472. let originalOptions = this.clusteredEdges[edge.id];
  473. if (originalOptions !== undefined) {
  474. edge.setOptions({physics: originalOptions.physics});
  475. delete this.clusteredEdges[edge.id];
  476. }
  477. }
  478. /**
  479. * Check if a node is a cluster.
  480. * @param nodeId
  481. * @returns {*}
  482. */
  483. isCluster(nodeId) {
  484. if (this.body.nodes[nodeId] !== undefined) {
  485. return this.body.nodes[nodeId].isCluster === true;
  486. }
  487. else {
  488. console.log("Node does not exist.");
  489. return false;
  490. }
  491. }
  492. /**
  493. * get the position of the cluster node based on what's inside
  494. * @param {object} childNodesObj | object with node objects, id as keys
  495. * @returns {{x: number, y: number}}
  496. * @private
  497. */
  498. _getClusterPosition(childNodesObj) {
  499. let childKeys = Object.keys(childNodesObj);
  500. let minX = childNodesObj[childKeys[0]].x;
  501. let maxX = childNodesObj[childKeys[0]].x;
  502. let minY = childNodesObj[childKeys[0]].y;
  503. let maxY = childNodesObj[childKeys[0]].y;
  504. let node;
  505. for (let i = 1; i < childKeys.length; i++) {
  506. node = childNodesObj[childKeys[i]];
  507. minX = node.x < minX ? node.x : minX;
  508. maxX = node.x > maxX ? node.x : maxX;
  509. minY = node.y < minY ? node.y : minY;
  510. maxY = node.y > maxY ? node.y : maxY;
  511. }
  512. return {x: 0.5*(minX + maxX), y: 0.5*(minY + maxY)};
  513. }
  514. /**
  515. * Open a cluster by calling this function.
  516. * @param {String} clusterNodeId | the ID of the cluster node
  517. * @param {Boolean} refreshData | wrap up afterwards if not true
  518. */
  519. openCluster(clusterNodeId, options, refreshData = true) {
  520. // kill conditions
  521. if (clusterNodeId === undefined) {throw new Error("No clusterNodeId supplied to openCluster.");}
  522. if (this.body.nodes[clusterNodeId] === undefined) {throw new Error("The clusterNodeId supplied to openCluster does not exist.");}
  523. if (this.body.nodes[clusterNodeId].containedNodes === undefined) {
  524. console.log("The node:" + clusterNodeId + " is not a cluster.");
  525. return
  526. }
  527. let clusterNode = this.body.nodes[clusterNodeId];
  528. let containedNodes = clusterNode.containedNodes;
  529. let containedEdges = clusterNode.containedEdges;
  530. // allow the user to position the nodes after release.
  531. if (options !== undefined && options.releaseFunction !== undefined && typeof options.releaseFunction === 'function') {
  532. let positions = {};
  533. let clusterPosition = {x:clusterNode.x, y:clusterNode.y};
  534. for (let nodeId in containedNodes) {
  535. if (containedNodes.hasOwnProperty(nodeId)) {
  536. let containedNode = this.body.nodes[nodeId];
  537. positions[nodeId] = {x: containedNode.x, y: containedNode.y};
  538. }
  539. }
  540. let newPositions = options.releaseFunction(clusterPosition, positions);
  541. for (let nodeId in containedNodes) {
  542. if (containedNodes.hasOwnProperty(nodeId)) {
  543. let containedNode = this.body.nodes[nodeId];
  544. if (newPositions[nodeId] !== undefined) {
  545. containedNode.x = (newPositions[nodeId].x === undefined ? clusterNode.x : newPositions[nodeId].x);
  546. containedNode.y = (newPositions[nodeId].y === undefined ? clusterNode.y : newPositions[nodeId].y);
  547. }
  548. }
  549. }
  550. }
  551. else {
  552. // copy the position from the cluster
  553. for (let nodeId in containedNodes) {
  554. if (containedNodes.hasOwnProperty(nodeId)) {
  555. let containedNode = this.body.nodes[nodeId];
  556. containedNode = containedNodes[nodeId];
  557. // inherit position
  558. if (containedNode.options.fixed.x === false) {containedNode.x = clusterNode.x;}
  559. if (containedNode.options.fixed.y === false) {containedNode.y = clusterNode.y;}
  560. }
  561. }
  562. }
  563. // release nodes
  564. for (let nodeId in containedNodes) {
  565. if (containedNodes.hasOwnProperty(nodeId)) {
  566. let containedNode = this.body.nodes[nodeId];
  567. // inherit speed
  568. containedNode.vx = clusterNode.vx;
  569. containedNode.vy = clusterNode.vy;
  570. containedNode.setOptions({physics:true});
  571. delete this.clusteredNodes[nodeId];
  572. }
  573. }
  574. // copy the clusterNode edges because we cannot iterate over an object that we add or remove from.
  575. let edgesToBeDeleted = [];
  576. for (let i = 0; i < clusterNode.edges.length; i++) {
  577. edgesToBeDeleted.push(clusterNode.edges[i]);
  578. }
  579. // actually handling the deleting.
  580. for (let i = 0; i < edgesToBeDeleted.length; i++) {
  581. let edge = edgesToBeDeleted[i];
  582. let otherNodeId = this._getConnectedId(edge, clusterNodeId);
  583. let otherNode = this.clusteredNodes[otherNodeId];
  584. for (let j = 0; j < edge.clusteringEdgeReplacingIds.length; j++) {
  585. let transferId = edge.clusteringEdgeReplacingIds[j];
  586. let transferEdge = this.body.edges[transferId];
  587. if (transferEdge === undefined) continue;
  588. // if the other node is in another cluster, we transfer ownership of this edge to the other cluster
  589. if (otherNode !== undefined) {
  590. // transfer ownership:
  591. let otherCluster = this.body.nodes[otherNode.clusterId];
  592. otherCluster.containedEdges[transferEdge.id] = transferEdge;
  593. // delete local reference
  594. delete containedEdges[transferEdge.id];
  595. // get to and from
  596. let fromId = transferEdge.fromId;
  597. let toId = transferEdge.toId;
  598. if (transferEdge.toId == otherNodeId) {
  599. toId = otherNode.clusterId;
  600. }
  601. else {
  602. fromId = otherNode.clusterId;
  603. }
  604. // create new cluster edge from the otherCluster
  605. this._createClusteredEdge(
  606. fromId,
  607. toId,
  608. transferEdge,
  609. otherCluster.clusterEdgeProperties,
  610. {hidden: false, physics: true});
  611. } else {
  612. this._restoreEdge(transferEdge);
  613. }
  614. }
  615. edge.remove();
  616. }
  617. // handle the releasing of the edges
  618. for (let edgeId in containedEdges) {
  619. if (containedEdges.hasOwnProperty(edgeId)) {
  620. this._restoreEdge(containedEdges[edgeId]);
  621. }
  622. }
  623. // remove clusterNode
  624. delete this.body.nodes[clusterNodeId];
  625. if (refreshData === true) {
  626. this.body.emitter.emit('_dataChanged');
  627. }
  628. }
  629. getNodesInCluster(clusterId) {
  630. let nodesArray = [];
  631. if (this.isCluster(clusterId) === true) {
  632. let containedNodes = this.body.nodes[clusterId].containedNodes;
  633. for (let nodeId in containedNodes) {
  634. if (containedNodes.hasOwnProperty(nodeId)) {
  635. nodesArray.push(this.body.nodes[nodeId].id)
  636. }
  637. }
  638. }
  639. return nodesArray;
  640. }
  641. /**
  642. * Get the stack clusterId's that a certain node resides in. cluster A -> cluster B -> cluster C -> node
  643. *
  644. * If a node can't be found in the chain, return an empty array.
  645. *
  646. * @param {string|number} nodeId
  647. * @returns {Array}
  648. */
  649. findNode(nodeId) {
  650. let stack = [];
  651. let max = 100;
  652. let counter = 0;
  653. let node;
  654. while (this.clusteredNodes[nodeId] !== undefined && counter < max) {
  655. node = this.body.nodes[nodeId]
  656. if (node === undefined) return [];
  657. stack.push(node.id);
  658. nodeId = this.clusteredNodes[nodeId].clusterId;
  659. counter++;
  660. }
  661. node = this.body.nodes[nodeId]
  662. if (node === undefined) return [];
  663. stack.push(node.id);
  664. stack.reverse();
  665. return stack;
  666. }
  667. /**
  668. * Using a clustered nodeId, update with the new options
  669. * @param clusteredNodeId
  670. * @param {object} newOptions
  671. */
  672. updateClusteredNode(clusteredNodeId, newOptions) {
  673. if (clusteredNodeId === undefined) {throw new Error("No clusteredNodeId supplied to updateClusteredNode.");}
  674. if (newOptions === undefined) {throw new Error("No newOptions supplied to updateClusteredNode.");}
  675. if (this.body.nodes[clusteredNodeId] === undefined) {throw new Error("The clusteredNodeId supplied to updateClusteredNode does not exist.");}
  676. this.body.nodes[clusteredNodeId].setOptions(newOptions);
  677. this.body.emitter.emit('_dataChanged');
  678. }
  679. /**
  680. * Using a base edgeId, update all related clustered edges with the new options
  681. * @param startEdgeId
  682. * @param {object} newOptions
  683. */
  684. updateEdge(startEdgeId, newOptions) {
  685. if (startEdgeId === undefined) {throw new Error("No startEdgeId supplied to updateEdge.");}
  686. if (newOptions === undefined) {throw new Error("No newOptions supplied to updateEdge.");}
  687. if (this.body.edges[startEdgeId] === undefined) {throw new Error("The startEdgeId supplied to updateEdge does not exist.");}
  688. let allEdgeIds = this.getClusteredEdges(startEdgeId);
  689. for (let i = 0; i < allEdgeIds.length; i++) {
  690. var edge = this.body.edges[allEdgeIds[i]];
  691. edge.setOptions(newOptions);
  692. }
  693. this.body.emitter.emit('_dataChanged');
  694. }
  695. /**
  696. * Get a stack of clusterEdgeId's (+base edgeid) that a base edge is the same as. cluster edge C -> cluster edge B -> cluster edge A -> base edge(edgeId)
  697. * @param edgeId
  698. * @returns {Array}
  699. */
  700. getClusteredEdges(edgeId) {
  701. let stack = [];
  702. let max = 100;
  703. let counter = 0;
  704. while (edgeId !== undefined && this.body.edges[edgeId] !== undefined && counter < max) {
  705. stack.push(this.body.edges[edgeId].id);
  706. edgeId = this.body.edges[edgeId].edgeReplacedById;
  707. counter++;
  708. }
  709. stack.reverse();
  710. return stack;
  711. }
  712. /**
  713. * Get the base edge id of clusterEdgeId. cluster edge (clusteredEdgeId) -> cluster edge B -> cluster edge C -> base edge
  714. * @param clusteredEdgeId
  715. * @returns baseEdgeId
  716. *
  717. * TODO: deprecate in 5.0.0. Method getBaseEdges() is the correct one to use.
  718. */
  719. getBaseEdge(clusteredEdgeId) {
  720. // Just kludge this by returning the first base edge id found
  721. return this.getBaseEdges(clusteredEdgeId)[0];
  722. }
  723. /**
  724. * Get all regular edges for this clustered edge id.
  725. *
  726. * @param {Number} clusteredEdgeId
  727. * @returns {Array[Number} all baseEdgeId's under this clustered edge
  728. */
  729. getBaseEdges(clusteredEdgeId) {
  730. let IdsToHandle = [clusteredEdgeId];
  731. let doneIds = [];
  732. let foundIds = [];
  733. let max = 100;
  734. let counter = 0;
  735. while (IdsToHandle.length > 0 && counter < max) {
  736. let nextId = IdsToHandle.pop();
  737. if (nextId === undefined) continue; // Paranoia here and onwards
  738. let nextEdge = this.body.edges[nextId];
  739. if (nextEdge === undefined) continue;
  740. counter++;
  741. let replacingIds = nextEdge.clusteringEdgeReplacingIds;
  742. if (replacingIds === undefined) {
  743. // nextId is a base id
  744. foundIds.push(nextId);
  745. } else {
  746. // Another cluster edge, unravel this one as well
  747. for (let i = 0; i < replacingIds.length; ++i) {
  748. let replacingId = replacingIds[i];
  749. // Don't add if already handled
  750. // TODO: never triggers; find a test-case which does
  751. if (IdsToHandle.indexOf(replacingIds) !== -1 || doneIds.indexOf(replacingIds) !== -1) {
  752. continue;
  753. }
  754. IdsToHandle.push(replacingId);
  755. }
  756. }
  757. doneIds.push(nextId);
  758. }
  759. return foundIds;
  760. }
  761. /**
  762. * Get the Id the node is connected to
  763. * @param edge
  764. * @param nodeId
  765. * @returns {*}
  766. * @private
  767. */
  768. _getConnectedId(edge, nodeId) {
  769. if (edge.toId != nodeId) {
  770. return edge.toId;
  771. }
  772. else if (edge.fromId != nodeId) {
  773. return edge.fromId;
  774. }
  775. else {
  776. return edge.fromId;
  777. }
  778. }
  779. /**
  780. * We determine how many connections denote an important hub.
  781. * We take the mean + 2*std as the important hub size. (Assuming a normal distribution of data, ~2.2%)
  782. *
  783. * @private
  784. */
  785. _getHubSize() {
  786. let average = 0;
  787. let averageSquared = 0;
  788. let hubCounter = 0;
  789. let largestHub = 0;
  790. for (let i = 0; i < this.body.nodeIndices.length; i++) {
  791. let node = this.body.nodes[this.body.nodeIndices[i]];
  792. if (node.edges.length > largestHub) {
  793. largestHub = node.edges.length;
  794. }
  795. average += node.edges.length;
  796. averageSquared += Math.pow(node.edges.length,2);
  797. hubCounter += 1;
  798. }
  799. average = average / hubCounter;
  800. averageSquared = averageSquared / hubCounter;
  801. let variance = averageSquared - Math.pow(average,2);
  802. let standardDeviation = Math.sqrt(variance);
  803. let hubThreshold = Math.floor(average + 2*standardDeviation);
  804. // always have at least one to cluster
  805. if (hubThreshold > largestHub) {
  806. hubThreshold = largestHub;
  807. }
  808. return hubThreshold;
  809. }
  810. /**
  811. * Create an edge for the cluster representation.
  812. *
  813. * @return {Edge} newly created clustered edge
  814. * @private
  815. */
  816. _createClusteredEdge(fromId, toId, baseEdge, clusterEdgeProperties, extraOptions) {
  817. // copy the options of the edge we will replace
  818. let clonedOptions = NetworkUtil.cloneOptions(baseEdge, 'edge');
  819. // make sure the properties of clusterEdges are superimposed on it
  820. util.deepExtend(clonedOptions, clusterEdgeProperties);
  821. // set up the edge
  822. clonedOptions.from = fromId;
  823. clonedOptions.to = toId;
  824. clonedOptions.id = 'clusterEdge:' + util.randomUUID();
  825. // apply the edge specific options to it if specified
  826. if (extraOptions !== undefined) {
  827. util.deepExtend(clonedOptions, extraOptions);
  828. }
  829. let newEdge = this.body.functions.createEdge(clonedOptions);
  830. newEdge.clusteringEdgeReplacingIds = [baseEdge.id];
  831. newEdge.connect();
  832. // Register the new edge
  833. this.body.edges[newEdge.id] = newEdge;
  834. return newEdge;
  835. }
  836. /**
  837. * Add the passed child nodes and edges to the given cluster node.
  838. *
  839. * @param childNodes {Object|Node} hash of nodes or single node to add in cluster
  840. * @param childEdges {Object|Edge} hash of edges or single edge to take into account when clustering
  841. * @param clusterNode {Node} cluster node to add nodes and edges to
  842. * @private
  843. */
  844. _clusterEdges(childNodes, childEdges, clusterNode, clusterEdgeProperties) {
  845. if (childEdges instanceof Edge) {
  846. let edge = childEdges;
  847. let obj = {};
  848. obj[edge.id] = edge;
  849. childEdges = obj;
  850. }
  851. if (childNodes instanceof Node) {
  852. let node = childNodes;
  853. let obj = {};
  854. obj[node.id] = node;
  855. childNodes = obj;
  856. }
  857. if (clusterNode === undefined || clusterNode === null) {
  858. throw new Error("_clusterEdges: parameter clusterNode required");
  859. }
  860. if (clusterEdgeProperties === undefined) {
  861. // Take the required properties from the cluster node
  862. clusterEdgeProperties = clusterNode.clusterEdgeProperties;
  863. }
  864. // create the new edges that will connect to the cluster.
  865. // All self-referencing edges will be added to childEdges here.
  866. this._createClusterEdges(childNodes, childEdges, clusterNode, clusterEdgeProperties);
  867. // disable the childEdges
  868. for (let edgeId in childEdges) {
  869. if (childEdges.hasOwnProperty(edgeId)) {
  870. if (this.body.edges[edgeId] !== undefined) {
  871. let edge = this.body.edges[edgeId];
  872. // cache the options before changing
  873. this._backupEdgeOptions(edge);
  874. // disable physics and hide the edge
  875. edge.setOptions({physics:false});
  876. }
  877. }
  878. }
  879. // disable the childNodes
  880. for (let nodeId in childNodes) {
  881. if (childNodes.hasOwnProperty(nodeId)) {
  882. this.clusteredNodes[nodeId] = {clusterId:clusterNode.id, node: this.body.nodes[nodeId]};
  883. this.body.nodes[nodeId].setOptions({physics:false});
  884. }
  885. }
  886. }
  887. /**
  888. * Determine in which cluster given nodeId resides.
  889. *
  890. * If not in cluster, return undefined.
  891. *
  892. * NOTE: If you know a cleaner way to do this, please enlighten me (wimrijnders).
  893. *
  894. * @return {Node|undefined} Node instance for cluster, if present
  895. * @private
  896. */
  897. _getClusterNodeForNode(nodeId) {
  898. if (nodeId === undefined) return undefined;
  899. let clusteredNode = this.clusteredNodes[nodeId];
  900. // NOTE: If no cluster info found, it should actually be an error
  901. if (clusteredNode === undefined) return undefined;
  902. let clusterId = clusteredNode.clusterId;
  903. if (clusterId === undefined) return undefined;
  904. return this.body.nodes[clusterId];
  905. }
  906. /**
  907. * Internal helper function for conditionally removing items in array
  908. *
  909. * Done like this because Array.filter() is not fully supported by all IE's.
  910. * @private
  911. */
  912. _filter(arr, callback) {
  913. let ret = [];
  914. for (var n in arr) {
  915. if (callback(arr[n])) {
  916. ret.push(arr[n]);
  917. }
  918. }
  919. return ret;
  920. }
  921. /**
  922. * Scan all edges for changes in clustering and adjust this if necessary.
  923. *
  924. * Call this (internally) after there has been a change in node or edge data.
  925. */
  926. _updateState() {
  927. // Pre: States of this.body.nodes and this.body.edges consistent
  928. // Pre: this.clusteredNodes and this.clusteredEdge consistent with containedNodes and containedEdges
  929. // of cluster nodes.
  930. let nodeId;
  931. let edgeId;
  932. let m, n;
  933. let deletedNodeIds = [];
  934. let deletedEdgeIds = [];
  935. let self = this;
  936. let eachClusterNode = (callback) => {
  937. for (nodeId in this.body.nodes) {
  938. let node = this.body.nodes[nodeId];
  939. if (node.isCluster !== true) continue;
  940. callback(node);
  941. }
  942. };
  943. //
  944. // Remove deleted regular nodes from clustering
  945. //
  946. // Determine the deleted nodes
  947. for (nodeId in this.clusteredNodes) {
  948. let node = this.body.nodes[nodeId];
  949. if (node === undefined) {
  950. deletedNodeIds.push(nodeId);
  951. }
  952. }
  953. // Remove nodes from cluster nodes
  954. eachClusterNode(function(clusterNode) {
  955. for (n in deletedNodeIds) {
  956. delete clusterNode.containedNodes[deletedNodeIds[n]];
  957. }
  958. });
  959. // Remove nodes from cluster list
  960. for (n in deletedNodeIds) {
  961. delete this.clusteredNodes[deletedNodeIds[n]];
  962. }
  963. //
  964. // Remove deleted edges from clustering
  965. //
  966. // Add the deleted clustered edges to the list
  967. for (edgeId in this.clusteredEdges) {
  968. let edge = this.body.edges[edgeId];
  969. if (edge === undefined || !edge.endPointsValid()) {
  970. deletedEdgeIds.push(edgeId);
  971. }
  972. }
  973. // Cluster nodes can also contain edges which are not clustered,
  974. // i.e. nodes 1-2 within cluster with an edge in between.
  975. // So the cluster nodes also need to be scanned for invalid edges
  976. eachClusterNode(function(clusterNode) {
  977. for (edgeId in clusterNode.containedEdges) {
  978. let edge = clusterNode.containedEdges[edgeId];
  979. if (!edge.endPointsValid() && deletedEdgeIds.indexOf(edgeId) === -1) {
  980. deletedEdgeIds.push(edgeId);
  981. }
  982. }
  983. });
  984. // Also scan for cluster edges which need to be removed in the active list.
  985. // Regular edges have been removed beforehand, so this only picks up the cluster edges.
  986. for (edgeId in this.body.edges) {
  987. let edge = this.body.edges[edgeId];
  988. if (!edge.endPointsValid()) {
  989. deletedEdgeIds.push(edgeId);
  990. }
  991. }
  992. // Remove edges from cluster nodes
  993. eachClusterNode(function(clusterNode) {
  994. for (n in deletedEdgeIds) {
  995. let deletedEdgeId = deletedEdgeIds[n];
  996. delete clusterNode.containedEdges[deletedEdgeId];
  997. for (m in clusterNode.edges) {
  998. let edge = clusterNode.edges[m];
  999. if (edge.id === deletedEdgeId) {
  1000. clusterNode.edges[m] = null; // Don't want to directly delete here, because in the loop
  1001. continue;
  1002. }
  1003. edge.clusteringEdgeReplacingIds = self._filter(edge.clusteringEdgeReplacingIds, function(id) {
  1004. return deletedEdgeIds.indexOf(id) === -1;
  1005. });
  1006. }
  1007. // Clean up the nulls
  1008. clusterNode.edges = self._filter(clusterNode.edges, function(item) {return item !== null});
  1009. }
  1010. });
  1011. // Remove from cluster list
  1012. for (n in deletedEdgeIds) {
  1013. delete this.clusteredEdges[deletedEdgeIds[n]];
  1014. }
  1015. // Remove cluster edges from active list (this.body.edges).
  1016. // deletedEdgeIds still contains id of regular edges, but these should all
  1017. // be gone upon entering this method
  1018. for (n in deletedEdgeIds) {
  1019. delete this.body.edges[deletedEdgeIds[n]];
  1020. }
  1021. //
  1022. // Check changed cluster state of edges
  1023. //
  1024. // Iterating over keys here, because edges may be removed in the loop
  1025. let ids = Object.keys(this.body.edges);
  1026. for (n in ids) {
  1027. let edgeId = ids[n];
  1028. let edge = this.body.edges[edgeId];
  1029. let shouldBeClustered = this._isClusteredNode(edge.fromId) || this._isClusteredNode(edge.toId);
  1030. if (shouldBeClustered === this._isClusteredEdge(edge.id)) {
  1031. continue; // all is well
  1032. }
  1033. if (shouldBeClustered) {
  1034. // add edge to clustering
  1035. let clusterFrom = this._getClusterNodeForNode(edge.fromId);
  1036. if (clusterFrom !== undefined) {
  1037. this._clusterEdges(this.body.nodes[edge.fromId], edge, clusterFrom);
  1038. }
  1039. let clusterTo = this._getClusterNodeForNode(edge.toId);
  1040. if (clusterTo !== undefined) {
  1041. this._clusterEdges(this.body.nodes[edge.toId], edge, clusterTo);
  1042. }
  1043. // TODO: check that it works for both edges clustered
  1044. } else {
  1045. // undo clustering for this edge
  1046. throw new Error('remove edge from clustering not implemented!');
  1047. }
  1048. }
  1049. // TODO: Cluster nodes may now be empty or because of selected options may not be allowed to contain 1 node
  1050. // Remove these cluster nodes if necessary.
  1051. }
  1052. /**
  1053. * Determine if node with given id is part of a cluster.
  1054. *
  1055. * @return {boolean} true if part of a cluster.
  1056. */
  1057. _isClusteredNode(nodeId) {
  1058. return this.clusteredNodes[nodeId] !== undefined;
  1059. }
  1060. /**
  1061. * Determine if edge with given id is not visible due to clustering.
  1062. *
  1063. * An edge is considered clustered if:
  1064. * - it is directly replaced by a clustering edge
  1065. * - any of its connecting nodes is in a cluster
  1066. *
  1067. * @return {boolean} true if part of a cluster.
  1068. */
  1069. _isClusteredEdge(edgeId) {
  1070. return this.clusteredEdges[edgeId] !== undefined;
  1071. }
  1072. }
  1073. export default ClusterEngine;