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.

841 lines
29 KiB

9 years ago
9 years ago
  1. let util = require("../../util");
  2. import NetworkUtil from '../NetworkUtil';
  3. import Cluster from './components/nodes/Cluster'
  4. class ClusterEngine {
  5. constructor(body) {
  6. this.body = body;
  7. this.clusteredNodes = {};
  8. this.clusteredEdges = {};
  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 i = 0; i < this.body.nodeIndices.length; i++) {
  52. let nodeId = this.body.nodeIndices[i];
  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 nodes 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, hidden:true});
  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, hidden:true});
  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({hidden:true, 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, hidden: edge.options.hidden};
  413. }
  414. }
  415. _restoreEdge(edge) {
  416. let originalOptions = this.clusteredEdges[edge.id];
  417. if (originalOptions !== undefined) {
  418. edge.setOptions({physics: originalOptions.physics, hidden: originalOptions.hidden});
  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. // we use these methods to avoid re-instantiating the shape, which happens with setOptions.
  515. containedNode.setOptions({hidden:false, physics:true});
  516. delete this.clusteredNodes[nodeId];
  517. }
  518. }
  519. // copy the clusterNode edges because we cannot iterate over an object that we add or remove from.
  520. let edgesToBeDeleted = [];
  521. for (let i = 0; i < clusterNode.edges.length; i++) {
  522. edgesToBeDeleted.push(clusterNode.edges[i]);
  523. }
  524. // actually handling the deleting.
  525. for (let i = 0; i < edgesToBeDeleted.length; i++) {
  526. let edge = edgesToBeDeleted[i];
  527. let otherNodeId = this._getConnectedId(edge, clusterNodeId);
  528. // if the other node is in another cluster, we transfer ownership of this edge to the other cluster
  529. if (this.clusteredNodes[otherNodeId] !== undefined) {
  530. // transfer ownership:
  531. let otherCluster = this.body.nodes[this.clusteredNodes[otherNodeId].clusterId];
  532. let transferEdge = this.body.edges[edge.clusteringEdgeReplacingId];
  533. if (transferEdge !== undefined) {
  534. otherCluster.containedEdges[transferEdge.id] = transferEdge;
  535. // delete local reference
  536. delete containedEdges[transferEdge.id];
  537. // create new cluster edge from the otherCluster:
  538. // get to and from
  539. let fromId = transferEdge.fromId;
  540. let toId = transferEdge.toId;
  541. if (transferEdge.toId == otherNodeId) {
  542. toId = this.clusteredNodes[otherNodeId].clusterId;
  543. }
  544. else {
  545. fromId = this.clusteredNodes[otherNodeId].clusterId;
  546. }
  547. // clone the options and apply the cluster options to them
  548. let clonedOptions = NetworkUtil.cloneOptions(transferEdge, 'edge');
  549. util.deepExtend(clonedOptions, otherCluster.clusterEdgeProperties);
  550. // apply the edge specific options to it.
  551. let id = 'clusterEdge:' + util.randomUUID();
  552. util.deepExtend(clonedOptions, {from: fromId, to: toId, hidden: false, physics: true, id: id});
  553. // create it
  554. let newEdge = this.body.functions.createEdge(clonedOptions);
  555. newEdge.clusteringEdgeReplacingId = transferEdge.id;
  556. this.body.edges[id] = newEdge;
  557. this.body.edges[id].connect();
  558. }
  559. }
  560. else {
  561. let replacedEdge = this.body.edges[edge.clusteringEdgeReplacingId];
  562. if (replacedEdge !== undefined) {
  563. this._restoreEdge(replacedEdge);
  564. }
  565. }
  566. edge.cleanup();
  567. // this removes the edge from node.edges, which is why edgeIds is formed
  568. edge.disconnect();
  569. delete this.body.edges[edge.id];
  570. }
  571. // handle the releasing of the edges
  572. for (let edgeId in containedEdges) {
  573. if (containedEdges.hasOwnProperty(edgeId)) {
  574. this._restoreEdge(containedEdges[edgeId]);
  575. }
  576. }
  577. // remove clusterNode
  578. delete this.body.nodes[clusterNodeId];
  579. if (refreshData === true) {
  580. this.body.emitter.emit('_dataChanged');
  581. }
  582. }
  583. getNodesInCluster(clusterId) {
  584. let nodesArray = [];
  585. if (this.isCluster(clusterId) === true) {
  586. let containedNodes = this.body.nodes[clusterId].containedNodes;
  587. for (let nodeId in containedNodes) {
  588. if (containedNodes.hasOwnProperty(nodeId)) {
  589. nodesArray.push(this.body.nodes[nodeId].id)
  590. }
  591. }
  592. }
  593. return nodesArray;
  594. }
  595. /**
  596. * Get the stack clusterId's that a certain node resides in. cluster A -> cluster B -> cluster C -> node
  597. * @param nodeId
  598. * @returns {Array}
  599. */
  600. findNode(nodeId) {
  601. let stack = [];
  602. let max = 100;
  603. let counter = 0;
  604. while (this.clusteredNodes[nodeId] !== undefined && counter < max) {
  605. stack.push(this.body.nodes[nodeId].id);
  606. nodeId = this.clusteredNodes[nodeId].clusterId;
  607. counter++;
  608. }
  609. stack.push(this.body.nodes[nodeId].id);
  610. stack.reverse();
  611. return stack;
  612. }
  613. /**
  614. * Using a clustered nodeId, update with the new options
  615. * @param clusteredNodeId
  616. * @param {object} newOptions
  617. */
  618. updateClusteredNode(clusteredNodeId, newOptions) {
  619. if (clusteredNodeId === undefined) {throw new Error("No clusteredNodeId supplied to updateClusteredNode.");}
  620. if (newOptions === undefined) {throw new Error("No newOptions supplied to updateClusteredNode.");}
  621. if (this.body.nodes[clusteredNodeId] === undefined) {throw new Error("The clusteredNodeId supplied to updateClusteredNode does not exist.");}
  622. this.body.nodes[clusteredNodeId].setOptions(newOptions);
  623. this.body.emitter.emit('_dataChanged');
  624. }
  625. /**
  626. * Using a base edgeId, update all related clustered edges with the new options
  627. * @param startEdgeId
  628. * @param {object} newOptions
  629. */
  630. updateEdge(startEdgeId, newOptions) {
  631. if (startEdgeId === undefined) {throw new Error("No startEdgeId supplied to updateEdge.");}
  632. if (newOptions === undefined) {throw new Error("No newOptions supplied to updateEdge.");}
  633. if (this.body.edges[startEdgeId] === undefined) {throw new Error("The startEdgeId supplied to updateEdge does not exist.");}
  634. let allEdgeIds = this.getClusteredEdges(startEdgeId);
  635. for (let i = 0; i < allEdgeIds.length; i++) {
  636. var edge = this.body.edges[allEdgeIds[i]];
  637. edge.setOptions(newOptions);
  638. }
  639. this.body.emitter.emit('_dataChanged');
  640. }
  641. /**
  642. * 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)
  643. * @param edgeId
  644. * @returns {Array}
  645. */
  646. getClusteredEdges(edgeId) {
  647. let stack = [];
  648. let max = 100;
  649. let counter = 0;
  650. while (edgeId !== undefined && this.body.edges[edgeId] !== undefined && counter < max) {
  651. stack.push(this.body.edges[edgeId].id);
  652. edgeId = this.body.edges[edgeId].edgeReplacedById;
  653. counter++;
  654. }
  655. stack.reverse();
  656. return stack;
  657. }
  658. /**
  659. * Get the base edge id of clusterEdgeId. cluster edge (clusteredEdgeId) -> cluster edge B -> cluster edge C -> base edge
  660. * @param clusteredEdgeId
  661. * @returns baseEdgeId
  662. */
  663. getBaseEdge(clusteredEdgeId) {
  664. let baseEdgeId = clusteredEdgeId;
  665. let max = 100;
  666. let counter = 0;
  667. while (clusteredEdgeId !== undefined && this.body.edges[clusteredEdgeId] !== undefined && counter < max) {
  668. clusteredEdgeId = this.body.edges[clusteredEdgeId].clusteringEdgeReplacingId;
  669. counter++;
  670. if (clusteredEdgeId !== undefined) {
  671. baseEdgeId = clusteredEdgeId;
  672. }
  673. }
  674. return baseEdgeId;
  675. }
  676. /**
  677. * Get the Id the node is connected to
  678. * @param edge
  679. * @param nodeId
  680. * @returns {*}
  681. * @private
  682. */
  683. _getConnectedId(edge, nodeId) {
  684. if (edge.toId != nodeId) {
  685. return edge.toId;
  686. }
  687. else if (edge.fromId != nodeId) {
  688. return edge.fromId;
  689. }
  690. else {
  691. return edge.fromId;
  692. }
  693. }
  694. /**
  695. * We determine how many connections denote an important hub.
  696. * We take the mean + 2*std as the important hub size. (Assuming a normal distribution of data, ~2.2%)
  697. *
  698. * @private
  699. */
  700. _getHubSize() {
  701. let average = 0;
  702. let averageSquared = 0;
  703. let hubCounter = 0;
  704. let largestHub = 0;
  705. for (let i = 0; i < this.body.nodeIndices.length; i++) {
  706. let node = this.body.nodes[this.body.nodeIndices[i]];
  707. if (node.edges.length > largestHub) {
  708. largestHub = node.edges.length;
  709. }
  710. average += node.edges.length;
  711. averageSquared += Math.pow(node.edges.length,2);
  712. hubCounter += 1;
  713. }
  714. average = average / hubCounter;
  715. averageSquared = averageSquared / hubCounter;
  716. let variance = averageSquared - Math.pow(average,2);
  717. let standardDeviation = Math.sqrt(variance);
  718. let hubThreshold = Math.floor(average + 2*standardDeviation);
  719. // always have at least one to cluster
  720. if (hubThreshold > largestHub) {
  721. hubThreshold = largestHub;
  722. }
  723. return hubThreshold;
  724. };
  725. }
  726. export default ClusterEngine;