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.

874 lines
30 KiB

9 years ago
9 years ago
  1. let util = require("../../util");
  2. var NetworkUtil = require('../NetworkUtil').default;
  3. var Cluster = require('./components/nodes/Cluster').default;
  4. class ClusterEngine {
  5. constructor(body) {
  6. this.body = body;
  7. this.clusteredNodes = {}; // Set of all nodes which are in a cluster
  8. this.clusteredEdges = {}; // Set of all edges replaced by a clustering edge
  9. this.options = {};
  10. this.defaultOptions = {};
  11. util.extend(this.options, this.defaultOptions);
  12. this.body.emitter.on('_resetData', () => {this.clusteredNodes = {}; this.clusteredEdges = {};})
  13. }
  14. /**
  15. *
  16. * @param hubsize
  17. * @param options
  18. */
  19. clusterByHubsize(hubsize, options) {
  20. if (hubsize === undefined) {
  21. hubsize = this._getHubSize();
  22. }
  23. else if (typeof(hubsize) === "object") {
  24. options = this._checkOptions(hubsize);
  25. hubsize = this._getHubSize();
  26. }
  27. let nodesToCluster = [];
  28. for (let i = 0; i < this.body.nodeIndices.length; i++) {
  29. let node = this.body.nodes[this.body.nodeIndices[i]];
  30. if (node.edges.length >= hubsize) {
  31. nodesToCluster.push(node.id);
  32. }
  33. }
  34. for (let i = 0; i < nodesToCluster.length; i++) {
  35. this.clusterByConnection(nodesToCluster[i],options,true);
  36. }
  37. this.body.emitter.emit('_dataChanged');
  38. }
  39. /**
  40. * loop over all nodes, check if they adhere to the condition and cluster if needed.
  41. * @param options
  42. * @param refreshData
  43. */
  44. cluster(options = {}, refreshData = true) {
  45. if (options.joinCondition === undefined) {throw new Error("Cannot call clusterByNodeData without a joinCondition function in the options.");}
  46. // check if the options object is fine, append if needed
  47. options = this._checkOptions(options);
  48. let childNodesObj = {};
  49. let childEdgesObj = {};
  50. // collect the nodes that will be in the cluster
  51. for (let nodeId in this.body.nodes) {
  52. if (!this.body.nodes.hasOwnProperty(nodeId)) continue;
  53. let node = this.body.nodes[nodeId];
  54. let clonedOptions = NetworkUtil.cloneOptions(node);
  55. if (options.joinCondition(clonedOptions) === true) {
  56. childNodesObj[nodeId] = this.body.nodes[nodeId];
  57. // collect the edges that will be in the cluster
  58. for (let i = 0; i < node.edges.length; i++) {
  59. let edge = node.edges[i];
  60. if (this.clusteredEdges[edge.id] === undefined) {
  61. childEdgesObj[edge.id] = edge;
  62. }
  63. }
  64. }
  65. }
  66. this._cluster(childNodesObj, childEdgesObj, options, refreshData);
  67. }
  68. /**
  69. * Cluster all nodes in the network that have only X edges
  70. * @param edgeCount
  71. * @param options
  72. * @param refreshData
  73. */
  74. clusterByEdgeCount(edgeCount, options, refreshData = true) {
  75. options = this._checkOptions(options);
  76. let clusters = [];
  77. let usedNodes = {};
  78. let edge, edges, node, nodeId, relevantEdgeCount;
  79. // collect the nodes that will be in the cluster
  80. for (let i = 0; i < this.body.nodeIndices.length; i++) {
  81. let childNodesObj = {};
  82. let childEdgesObj = {};
  83. nodeId = this.body.nodeIndices[i];
  84. // if this node is already used in another cluster this session, we do not have to re-evaluate it.
  85. if (usedNodes[nodeId] === undefined) {
  86. relevantEdgeCount = 0;
  87. node = this.body.nodes[nodeId];
  88. edges = [];
  89. for (let j = 0; j < node.edges.length; j++) {
  90. edge = node.edges[j];
  91. if (this.clusteredEdges[edge.id] === undefined) {
  92. if (edge.toId !== edge.fromId) {
  93. relevantEdgeCount++;
  94. }
  95. edges.push(edge);
  96. }
  97. }
  98. // this node qualifies, we collect its neighbours to start the clustering process.
  99. if (relevantEdgeCount === edgeCount) {
  100. let gatheringSuccessful = true;
  101. for (let j = 0; j < edges.length; j++) {
  102. edge = edges[j];
  103. let childNodeId = this._getConnectedId(edge, nodeId);
  104. // add the nodes to the list by the join condition.
  105. if (options.joinCondition === undefined) {
  106. childEdgesObj[edge.id] = edge;
  107. childNodesObj[nodeId] = this.body.nodes[nodeId];
  108. childNodesObj[childNodeId] = this.body.nodes[childNodeId];
  109. usedNodes[nodeId] = true;
  110. }
  111. else {
  112. let clonedOptions = NetworkUtil.cloneOptions(this.body.nodes[nodeId]);
  113. if (options.joinCondition(clonedOptions) === true) {
  114. childEdgesObj[edge.id] = edge;
  115. childNodesObj[nodeId] = this.body.nodes[nodeId];
  116. usedNodes[nodeId] = true;
  117. }
  118. else {
  119. // this node does not qualify after all.
  120. gatheringSuccessful = false;
  121. break;
  122. }
  123. }
  124. }
  125. // add to the cluster queue
  126. if (Object.keys(childNodesObj).length > 0 && Object.keys(childEdgesObj).length > 0 && gatheringSuccessful === true) {
  127. clusters.push({nodes: childNodesObj, edges: childEdgesObj})
  128. }
  129. }
  130. }
  131. }
  132. for (let i = 0; i < clusters.length; i++) {
  133. this._cluster(clusters[i].nodes, clusters[i].edges, options, false)
  134. }
  135. if (refreshData === true) {
  136. this.body.emitter.emit('_dataChanged');
  137. }
  138. }
  139. /**
  140. * Cluster all nodes in the network that have only 1 edge
  141. * @param options
  142. * @param refreshData
  143. */
  144. clusterOutliers(options, refreshData = true) {
  145. this.clusterByEdgeCount(1,options,refreshData);
  146. }
  147. /**
  148. * Cluster all nodes in the network that have only 2 edge
  149. * @param options
  150. * @param refreshData
  151. */
  152. clusterBridges(options, refreshData = true) {
  153. this.clusterByEdgeCount(2,options,refreshData);
  154. }
  155. /**
  156. * suck all connected nodes of a node into the node.
  157. * @param nodeId
  158. * @param options
  159. * @param refreshData
  160. */
  161. clusterByConnection(nodeId, options, refreshData = true) {
  162. // kill conditions
  163. if (nodeId === undefined) {throw new Error("No nodeId supplied to clusterByConnection!");}
  164. if (this.body.nodes[nodeId] === undefined) {throw new Error("The nodeId given to clusterByConnection does not exist!");}
  165. let node = this.body.nodes[nodeId];
  166. options = this._checkOptions(options, node);
  167. if (options.clusterNodeProperties.x === undefined) {options.clusterNodeProperties.x = node.x;}
  168. if (options.clusterNodeProperties.y === undefined) {options.clusterNodeProperties.y = node.y;}
  169. if (options.clusterNodeProperties.fixed === undefined) {
  170. options.clusterNodeProperties.fixed = {};
  171. options.clusterNodeProperties.fixed.x = node.options.fixed.x;
  172. options.clusterNodeProperties.fixed.y = node.options.fixed.y;
  173. }
  174. let childNodesObj = {};
  175. let childEdgesObj = {};
  176. let parentNodeId = node.id;
  177. let parentClonedOptions = NetworkUtil.cloneOptions(node);
  178. childNodesObj[parentNodeId] = node;
  179. // collect the nodes that will be in the cluster
  180. for (let i = 0; i < node.edges.length; i++) {
  181. let edge = node.edges[i];
  182. if (this.clusteredEdges[edge.id] === undefined) {
  183. let childNodeId = this._getConnectedId(edge, parentNodeId);
  184. // if the child node is not in a cluster
  185. if (this.clusteredNodes[childNodeId] === undefined) {
  186. if (childNodeId !== parentNodeId) {
  187. if (options.joinCondition === undefined) {
  188. childEdgesObj[edge.id] = edge;
  189. childNodesObj[childNodeId] = this.body.nodes[childNodeId];
  190. }
  191. else {
  192. // clone the options and insert some additional parameters that could be interesting.
  193. let childClonedOptions = NetworkUtil.cloneOptions(this.body.nodes[childNodeId]);
  194. if (options.joinCondition(parentClonedOptions, childClonedOptions) === true) {
  195. childEdgesObj[edge.id] = edge;
  196. childNodesObj[childNodeId] = this.body.nodes[childNodeId];
  197. }
  198. }
  199. }
  200. else {
  201. // swallow the edge if it is self-referencing.
  202. childEdgesObj[edge.id] = edge;
  203. }
  204. }
  205. }
  206. }
  207. var childNodeIDs = Object.keys(childNodesObj).map(function(childNode){
  208. return childNodesObj[childNode].id;
  209. })
  210. for (childNode in childNodesObj) {
  211. var childNode = childNodesObj[childNode];
  212. for (var y=0; y < childNode.edges.length; y++){
  213. var childEdge = childNode.edges[y];
  214. if (childNodeIDs.indexOf(this._getConnectedId(childEdge,childNode.id)) > -1){
  215. childEdgesObj[childEdge.id] = childEdge;
  216. }
  217. }
  218. }
  219. this._cluster(childNodesObj, childEdgesObj, options, refreshData);
  220. }
  221. /**
  222. * This function creates the edges that will be attached to the cluster
  223. * It looks for edges that are connected to the nodes from the "outside' of the cluster.
  224. *
  225. * @param childNodesObj
  226. * @param childEdgesObj
  227. * @param clusterNodeProperties
  228. * @param clusterEdgeProperties
  229. * @private
  230. */
  231. _createClusterEdges (childNodesObj, childEdgesObj, clusterNodeProperties, clusterEdgeProperties) {
  232. let edge, childNodeId, childNode, toId, fromId, otherNodeId;
  233. // loop over all child nodes and their edges to find edges going out of the cluster
  234. // these edges will be replaced by clusterEdges.
  235. let childKeys = Object.keys(childNodesObj);
  236. let createEdges = [];
  237. for (let i = 0; i < childKeys.length; i++) {
  238. childNodeId = childKeys[i];
  239. childNode = childNodesObj[childNodeId];
  240. // construct new edges from the cluster to others
  241. for (let j = 0; j < childNode.edges.length; j++) {
  242. edge = childNode.edges[j];
  243. // we only handle edges that are visible to the system, not the disabled ones from the clustering process.
  244. if (this.clusteredEdges[edge.id] === undefined) {
  245. // self-referencing edges will be added to the "hidden" list
  246. if (edge.toId == edge.fromId) {
  247. childEdgesObj[edge.id] = edge;
  248. }
  249. else {
  250. // set up the from and to.
  251. if (edge.toId == childNodeId) { // this is a double equals because ints and strings can be interchanged here.
  252. toId = clusterNodeProperties.id;
  253. fromId = edge.fromId;
  254. otherNodeId = fromId;
  255. }
  256. else {
  257. toId = edge.toId;
  258. fromId = clusterNodeProperties.id;
  259. otherNodeId = toId;
  260. }
  261. }
  262. // Only edges from the cluster outwards are being replaced.
  263. if (childNodesObj[otherNodeId] === undefined) {
  264. createEdges.push({edge: edge, fromId: fromId, toId: toId});
  265. }
  266. }
  267. }
  268. }
  269. // here we actually create the replacement edges. We could not do this in the loop above as the creation process
  270. // would add an edge to the edges array we are iterating over.
  271. for (let j = 0; j < createEdges.length; j++) {
  272. let edge = createEdges[j].edge;
  273. // copy the options of the edge we will replace
  274. let clonedOptions = NetworkUtil.cloneOptions(edge, 'edge');
  275. // make sure the properties of clusterEdges are superimposed on it
  276. util.deepExtend(clonedOptions, clusterEdgeProperties);
  277. // set up the edge
  278. clonedOptions.from = createEdges[j].fromId;
  279. clonedOptions.to = createEdges[j].toId;
  280. clonedOptions.id = 'clusterEdge:' + util.randomUUID();
  281. //clonedOptions.id = '(cf: ' + createEdges[j].fromId + " to: " + createEdges[j].toId + ")" + Math.random();
  282. // create the edge and give a reference to the one it replaced.
  283. let newEdge = this.body.functions.createEdge(clonedOptions);
  284. newEdge.clusteringEdgeReplacingId = edge.id;
  285. // also reference the new edge in the old edge
  286. this.body.edges[edge.id].edgeReplacedById = newEdge.id;
  287. // connect the edge.
  288. this.body.edges[newEdge.id] = newEdge;
  289. newEdge.connect();
  290. // hide the replaced edge
  291. this._backupEdgeOptions(edge);
  292. edge.setOptions({physics:false});
  293. }
  294. }
  295. /**
  296. * This function checks the options that can be supplied to the different cluster functions
  297. * for certain fields and inserts defaults if needed
  298. * @param options
  299. * @returns {*}
  300. * @private
  301. */
  302. _checkOptions(options = {}) {
  303. if (options.clusterEdgeProperties === undefined) {options.clusterEdgeProperties = {};}
  304. if (options.clusterNodeProperties === undefined) {options.clusterNodeProperties = {};}
  305. return options;
  306. }
  307. /**
  308. *
  309. * @param {Object} childNodesObj | object with node objects, id as keys, same as childNodes except it also contains a source node
  310. * @param {Object} childEdgesObj | object with edge objects, id as keys
  311. * @param {Array} options | object with {clusterNodeProperties, clusterEdgeProperties, processProperties}
  312. * @param {Boolean} refreshData | when true, do not wrap up
  313. * @private
  314. */
  315. _cluster(childNodesObj, childEdgesObj, options, refreshData = true) {
  316. // kill condition: no nodes don't bother
  317. if (Object.keys(childNodesObj).length == 0) {return;}
  318. // allow clusters of 1 if options allow
  319. if (Object.keys(childNodesObj).length == 1 && options.clusterNodeProperties.allowSingleNodeCluster != true) {return;}
  320. // check if this cluster call is not trying to cluster anything that is in another cluster.
  321. for (let nodeId in childNodesObj) {
  322. if (childNodesObj.hasOwnProperty(nodeId)) {
  323. if (this.clusteredNodes[nodeId] !== undefined) {
  324. return;
  325. }
  326. }
  327. }
  328. let clusterNodeProperties = util.deepExtend({},options.clusterNodeProperties);
  329. // construct the clusterNodeProperties
  330. if (options.processProperties !== undefined) {
  331. // get the childNode options
  332. let childNodesOptions = [];
  333. for (let nodeId in childNodesObj) {
  334. if (childNodesObj.hasOwnProperty(nodeId)) {
  335. let clonedOptions = NetworkUtil.cloneOptions(childNodesObj[nodeId]);
  336. childNodesOptions.push(clonedOptions);
  337. }
  338. }
  339. // get cluster properties based on childNodes
  340. let childEdgesOptions = [];
  341. for (let edgeId in childEdgesObj) {
  342. if (childEdgesObj.hasOwnProperty(edgeId)) {
  343. // these cluster edges will be removed on creation of the cluster.
  344. if (edgeId.substr(0, 12) !== "clusterEdge:") {
  345. let clonedOptions = NetworkUtil.cloneOptions(childEdgesObj[edgeId], 'edge');
  346. childEdgesOptions.push(clonedOptions);
  347. }
  348. }
  349. }
  350. clusterNodeProperties = options.processProperties(clusterNodeProperties, childNodesOptions, childEdgesOptions);
  351. if (!clusterNodeProperties) {
  352. throw new Error("The processProperties function does not return properties!");
  353. }
  354. }
  355. // check if we have an unique id;
  356. if (clusterNodeProperties.id === undefined) {clusterNodeProperties.id = 'cluster:' + util.randomUUID();}
  357. let clusterId = clusterNodeProperties.id;
  358. if (clusterNodeProperties.label === undefined) {
  359. clusterNodeProperties.label = 'cluster';
  360. }
  361. // give the clusterNode a position if it does not have one.
  362. let pos = undefined;
  363. if (clusterNodeProperties.x === undefined) {
  364. pos = this._getClusterPosition(childNodesObj);
  365. clusterNodeProperties.x = pos.x;
  366. }
  367. if (clusterNodeProperties.y === undefined) {
  368. if (pos === undefined) {pos = this._getClusterPosition(childNodesObj);}
  369. clusterNodeProperties.y = pos.y;
  370. }
  371. // force the ID to remain the same
  372. clusterNodeProperties.id = clusterId;
  373. // create the clusterNode
  374. let clusterNode = this.body.functions.createNode(clusterNodeProperties, Cluster);
  375. clusterNode.isCluster = true;
  376. clusterNode.containedNodes = childNodesObj;
  377. clusterNode.containedEdges = childEdgesObj;
  378. // cache a copy from the cluster edge properties if we have to reconnect others later on
  379. clusterNode.clusterEdgeProperties = options.clusterEdgeProperties;
  380. // finally put the cluster node into global
  381. this.body.nodes[clusterNodeProperties.id] = clusterNode;
  382. // create the new edges that will connect to the cluster, all self-referencing edges will be added to childEdgesObject here.
  383. this._createClusterEdges(childNodesObj, childEdgesObj, clusterNodeProperties, options.clusterEdgeProperties);
  384. // disable the childEdges
  385. for (let edgeId in childEdgesObj) {
  386. if (childEdgesObj.hasOwnProperty(edgeId)) {
  387. if (this.body.edges[edgeId] !== undefined) {
  388. let edge = this.body.edges[edgeId];
  389. // cache the options before changing
  390. this._backupEdgeOptions(edge);
  391. // disable physics and hide the edge
  392. edge.setOptions({physics:false});
  393. }
  394. }
  395. }
  396. // disable the childNodes
  397. for (let nodeId in childNodesObj) {
  398. if (childNodesObj.hasOwnProperty(nodeId)) {
  399. this.clusteredNodes[nodeId] = {clusterId:clusterNodeProperties.id, node: this.body.nodes[nodeId]};
  400. this.body.nodes[nodeId].setOptions({physics:false});
  401. }
  402. }
  403. // set ID to undefined so no duplicates arise
  404. clusterNodeProperties.id = undefined;
  405. // wrap up
  406. if (refreshData === true) {
  407. this.body.emitter.emit('_dataChanged');
  408. }
  409. }
  410. _backupEdgeOptions(edge) {
  411. if (this.clusteredEdges[edge.id] === undefined) {
  412. this.clusteredEdges[edge.id] = {physics: edge.options.physics};
  413. }
  414. }
  415. _restoreEdge(edge) {
  416. let originalOptions = this.clusteredEdges[edge.id];
  417. if (originalOptions !== undefined) {
  418. edge.setOptions({physics: originalOptions.physics});
  419. delete this.clusteredEdges[edge.id];
  420. }
  421. }
  422. /**
  423. * Check if a node is a cluster.
  424. * @param nodeId
  425. * @returns {*}
  426. */
  427. isCluster(nodeId) {
  428. if (this.body.nodes[nodeId] !== undefined) {
  429. return this.body.nodes[nodeId].isCluster === true;
  430. }
  431. else {
  432. console.log("Node does not exist.");
  433. return false;
  434. }
  435. }
  436. /**
  437. * get the position of the cluster node based on what's inside
  438. * @param {object} childNodesObj | object with node objects, id as keys
  439. * @returns {{x: number, y: number}}
  440. * @private
  441. */
  442. _getClusterPosition(childNodesObj) {
  443. let childKeys = Object.keys(childNodesObj);
  444. let minX = childNodesObj[childKeys[0]].x;
  445. let maxX = childNodesObj[childKeys[0]].x;
  446. let minY = childNodesObj[childKeys[0]].y;
  447. let maxY = childNodesObj[childKeys[0]].y;
  448. let node;
  449. for (let i = 1; i < childKeys.length; i++) {
  450. node = childNodesObj[childKeys[i]];
  451. minX = node.x < minX ? node.x : minX;
  452. maxX = node.x > maxX ? node.x : maxX;
  453. minY = node.y < minY ? node.y : minY;
  454. maxY = node.y > maxY ? node.y : maxY;
  455. }
  456. return {x: 0.5*(minX + maxX), y: 0.5*(minY + maxY)};
  457. }
  458. /**
  459. * Open a cluster by calling this function.
  460. * @param {String} clusterNodeId | the ID of the cluster node
  461. * @param {Boolean} refreshData | wrap up afterwards if not true
  462. */
  463. openCluster(clusterNodeId, options, refreshData = true) {
  464. // kill conditions
  465. if (clusterNodeId === undefined) {throw new Error("No clusterNodeId supplied to openCluster.");}
  466. if (this.body.nodes[clusterNodeId] === undefined) {throw new Error("The clusterNodeId supplied to openCluster does not exist.");}
  467. if (this.body.nodes[clusterNodeId].containedNodes === undefined) {
  468. console.log("The node:" + clusterNodeId + " is not a cluster.");
  469. return
  470. }
  471. let clusterNode = this.body.nodes[clusterNodeId];
  472. let containedNodes = clusterNode.containedNodes;
  473. let containedEdges = clusterNode.containedEdges;
  474. // allow the user to position the nodes after release.
  475. if (options !== undefined && options.releaseFunction !== undefined && typeof options.releaseFunction === 'function') {
  476. let positions = {};
  477. let clusterPosition = {x:clusterNode.x, y:clusterNode.y};
  478. for (let nodeId in containedNodes) {
  479. if (containedNodes.hasOwnProperty(nodeId)) {
  480. let containedNode = this.body.nodes[nodeId];
  481. positions[nodeId] = {x: containedNode.x, y: containedNode.y};
  482. }
  483. }
  484. let newPositions = options.releaseFunction(clusterPosition, positions);
  485. for (let nodeId in containedNodes) {
  486. if (containedNodes.hasOwnProperty(nodeId)) {
  487. let containedNode = this.body.nodes[nodeId];
  488. if (newPositions[nodeId] !== undefined) {
  489. containedNode.x = (newPositions[nodeId].x === undefined ? clusterNode.x : newPositions[nodeId].x);
  490. containedNode.y = (newPositions[nodeId].y === undefined ? clusterNode.y : newPositions[nodeId].y);
  491. }
  492. }
  493. }
  494. }
  495. else {
  496. // copy the position from the cluster
  497. for (let nodeId in containedNodes) {
  498. if (containedNodes.hasOwnProperty(nodeId)) {
  499. let containedNode = this.body.nodes[nodeId];
  500. containedNode = containedNodes[nodeId];
  501. // inherit position
  502. if (containedNode.options.fixed.x === false) {containedNode.x = clusterNode.x;}
  503. if (containedNode.options.fixed.y === false) {containedNode.y = clusterNode.y;}
  504. }
  505. }
  506. }
  507. // release nodes
  508. for (let nodeId in containedNodes) {
  509. if (containedNodes.hasOwnProperty(nodeId)) {
  510. let containedNode = this.body.nodes[nodeId];
  511. // inherit speed
  512. containedNode.vx = clusterNode.vx;
  513. containedNode.vy = clusterNode.vy;
  514. containedNode.setOptions({physics:true});
  515. delete this.clusteredNodes[nodeId];
  516. }
  517. }
  518. // copy the clusterNode edges because we cannot iterate over an object that we add or remove from.
  519. let edgesToBeDeleted = [];
  520. for (let i = 0; i < clusterNode.edges.length; i++) {
  521. edgesToBeDeleted.push(clusterNode.edges[i]);
  522. }
  523. // actually handling the deleting.
  524. for (let i = 0; i < edgesToBeDeleted.length; i++) {
  525. let edge = edgesToBeDeleted[i];
  526. let otherNodeId = this._getConnectedId(edge, clusterNodeId);
  527. // if the other node is in another cluster, we transfer ownership of this edge to the other cluster
  528. if (this.clusteredNodes[otherNodeId] !== undefined) {
  529. // transfer ownership:
  530. let otherCluster = this.body.nodes[this.clusteredNodes[otherNodeId].clusterId];
  531. let transferEdge = this.body.edges[edge.clusteringEdgeReplacingId];
  532. if (transferEdge !== undefined) {
  533. otherCluster.containedEdges[transferEdge.id] = transferEdge;
  534. // delete local reference
  535. delete containedEdges[transferEdge.id];
  536. // create new cluster edge from the otherCluster:
  537. // get to and from
  538. let fromId = transferEdge.fromId;
  539. let toId = transferEdge.toId;
  540. if (transferEdge.toId == otherNodeId) {
  541. toId = this.clusteredNodes[otherNodeId].clusterId;
  542. }
  543. else {
  544. fromId = this.clusteredNodes[otherNodeId].clusterId;
  545. }
  546. // clone the options and apply the cluster options to them
  547. let clonedOptions = NetworkUtil.cloneOptions(transferEdge, 'edge');
  548. util.deepExtend(clonedOptions, otherCluster.clusterEdgeProperties);
  549. // apply the edge specific options to it.
  550. let id = 'clusterEdge:' + util.randomUUID();
  551. util.deepExtend(clonedOptions, {from: fromId, to: toId, hidden: false, physics: true, id: id});
  552. // create it
  553. let newEdge = this.body.functions.createEdge(clonedOptions);
  554. newEdge.clusteringEdgeReplacingId = transferEdge.id;
  555. this.body.edges[id] = newEdge;
  556. this.body.edges[id].connect();
  557. }
  558. }
  559. else {
  560. let replacedEdge = this.body.edges[edge.clusteringEdgeReplacingId];
  561. if (replacedEdge !== undefined) {
  562. this._restoreEdge(replacedEdge);
  563. }
  564. }
  565. edge.cleanup();
  566. // this removes the edge from node.edges, which is why edgeIds is formed
  567. edge.disconnect();
  568. delete this.body.edges[edge.id];
  569. }
  570. // handle the releasing of the edges
  571. for (let edgeId in containedEdges) {
  572. if (containedEdges.hasOwnProperty(edgeId)) {
  573. this._restoreEdge(containedEdges[edgeId]);
  574. }
  575. }
  576. // remove clusterNode
  577. delete this.body.nodes[clusterNodeId];
  578. if (refreshData === true) {
  579. this.body.emitter.emit('_dataChanged');
  580. }
  581. }
  582. getNodesInCluster(clusterId) {
  583. let nodesArray = [];
  584. if (this.isCluster(clusterId) === true) {
  585. let containedNodes = this.body.nodes[clusterId].containedNodes;
  586. for (let nodeId in containedNodes) {
  587. if (containedNodes.hasOwnProperty(nodeId)) {
  588. nodesArray.push(this.body.nodes[nodeId].id)
  589. }
  590. }
  591. }
  592. return nodesArray;
  593. }
  594. /**
  595. * Get the stack clusterId's that a certain node resides in. cluster A -> cluster B -> cluster C -> node
  596. *
  597. * If a node can't be found in the chain, return an empty array.
  598. *
  599. * @param {string|number} nodeId
  600. * @returns {Array}
  601. */
  602. findNode(nodeId) {
  603. let stack = [];
  604. let max = 100;
  605. let counter = 0;
  606. let node;
  607. while (this.clusteredNodes[nodeId] !== undefined && counter < max) {
  608. node = this.body.nodes[nodeId]
  609. if (node === undefined) return [];
  610. stack.push(node.id);
  611. nodeId = this.clusteredNodes[nodeId].clusterId;
  612. counter++;
  613. }
  614. node = this.body.nodes[nodeId]
  615. if (node === undefined) return [];
  616. stack.push(node.id);
  617. stack.reverse();
  618. return stack;
  619. }
  620. /**
  621. * Using a clustered nodeId, update with the new options
  622. * @param clusteredNodeId
  623. * @param {object} newOptions
  624. */
  625. updateClusteredNode(clusteredNodeId, newOptions) {
  626. if (clusteredNodeId === undefined) {throw new Error("No clusteredNodeId supplied to updateClusteredNode.");}
  627. if (newOptions === undefined) {throw new Error("No newOptions supplied to updateClusteredNode.");}
  628. if (this.body.nodes[clusteredNodeId] === undefined) {throw new Error("The clusteredNodeId supplied to updateClusteredNode does not exist.");}
  629. this.body.nodes[clusteredNodeId].setOptions(newOptions);
  630. this.body.emitter.emit('_dataChanged');
  631. }
  632. /**
  633. * Using a base edgeId, update all related clustered edges with the new options
  634. * @param startEdgeId
  635. * @param {object} newOptions
  636. */
  637. updateEdge(startEdgeId, newOptions) {
  638. if (startEdgeId === undefined) {throw new Error("No startEdgeId supplied to updateEdge.");}
  639. if (newOptions === undefined) {throw new Error("No newOptions supplied to updateEdge.");}
  640. if (this.body.edges[startEdgeId] === undefined) {throw new Error("The startEdgeId supplied to updateEdge does not exist.");}
  641. let allEdgeIds = this.getClusteredEdges(startEdgeId);
  642. for (let i = 0; i < allEdgeIds.length; i++) {
  643. var edge = this.body.edges[allEdgeIds[i]];
  644. edge.setOptions(newOptions);
  645. }
  646. this.body.emitter.emit('_dataChanged');
  647. }
  648. /**
  649. * 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)
  650. * @param edgeId
  651. * @returns {Array}
  652. */
  653. getClusteredEdges(edgeId) {
  654. let stack = [];
  655. let max = 100;
  656. let counter = 0;
  657. while (edgeId !== undefined && this.body.edges[edgeId] !== undefined && counter < max) {
  658. stack.push(this.body.edges[edgeId].id);
  659. edgeId = this.body.edges[edgeId].edgeReplacedById;
  660. counter++;
  661. }
  662. stack.reverse();
  663. return stack;
  664. }
  665. /**
  666. * Get the base edge id of clusterEdgeId. cluster edge (clusteredEdgeId) -> cluster edge B -> cluster edge C -> base edge
  667. * @param clusteredEdgeId
  668. * @returns baseEdgeId
  669. */
  670. getBaseEdge(clusteredEdgeId) {
  671. let baseEdgeId = clusteredEdgeId;
  672. let max = 100;
  673. let counter = 0;
  674. while (clusteredEdgeId !== undefined && this.body.edges[clusteredEdgeId] !== undefined && counter < max) {
  675. clusteredEdgeId = this.body.edges[clusteredEdgeId].clusteringEdgeReplacingId;
  676. counter++;
  677. if (clusteredEdgeId !== undefined) {
  678. baseEdgeId = clusteredEdgeId;
  679. }
  680. }
  681. return baseEdgeId;
  682. }
  683. /**
  684. * Get the Id the node is connected to
  685. * @param edge
  686. * @param nodeId
  687. * @returns {*}
  688. * @private
  689. */
  690. _getConnectedId(edge, nodeId) {
  691. if (edge.toId != nodeId) {
  692. return edge.toId;
  693. }
  694. else if (edge.fromId != nodeId) {
  695. return edge.fromId;
  696. }
  697. else {
  698. return edge.fromId;
  699. }
  700. }
  701. /**
  702. * We determine how many connections denote an important hub.
  703. * We take the mean + 2*std as the important hub size. (Assuming a normal distribution of data, ~2.2%)
  704. *
  705. * @private
  706. */
  707. _getHubSize() {
  708. let average = 0;
  709. let averageSquared = 0;
  710. let hubCounter = 0;
  711. let largestHub = 0;
  712. for (let i = 0; i < this.body.nodeIndices.length; i++) {
  713. let node = this.body.nodes[this.body.nodeIndices[i]];
  714. if (node.edges.length > largestHub) {
  715. largestHub = node.edges.length;
  716. }
  717. average += node.edges.length;
  718. averageSquared += Math.pow(node.edges.length,2);
  719. hubCounter += 1;
  720. }
  721. average = average / hubCounter;
  722. averageSquared = averageSquared / hubCounter;
  723. let variance = averageSquared - Math.pow(average,2);
  724. let standardDeviation = Math.sqrt(variance);
  725. let hubThreshold = Math.floor(average + 2*standardDeviation);
  726. // always have at least one to cluster
  727. if (hubThreshold > largestHub) {
  728. hubThreshold = largestHub;
  729. }
  730. return hubThreshold;
  731. };
  732. /**
  733. * Determine if node with given id is part of a cluster.
  734. *
  735. * @return {boolean} true if part of a cluster.
  736. */
  737. _isClusteredNode(nodeId) {
  738. return this.clusteredNodes[nodeId] !== undefined;
  739. }
  740. /**
  741. * Determine if edge with given id is not visible due to clustering.
  742. *
  743. * An edge is considered clustered if:
  744. * - it is directly replaced by a clustering edge
  745. * - any of its connecting nodes is in a cluster
  746. *
  747. * @return {boolean} true if part of a cluster.
  748. */
  749. _isClusteredEdge(edgeId) {
  750. return this.clusteredEdges[edgeId] !== undefined;
  751. }
  752. }
  753. export default ClusterEngine;