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.

829 lines
28 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. this._cluster(childNodesObj, childEdgesObj, options, refreshData);
  208. }
  209. /**
  210. * This function creates the edges that will be attached to the cluster
  211. * It looks for edges that are connected to the nodes from the "outside' of the cluster.
  212. *
  213. * @param childNodesObj
  214. * @param childEdgesObj
  215. * @param clusterNodeProperties
  216. * @param clusterEdgeProperties
  217. * @private
  218. */
  219. _createClusterEdges (childNodesObj, childEdgesObj, clusterNodeProperties, clusterEdgeProperties) {
  220. let edge, childNodeId, childNode, toId, fromId, otherNodeId;
  221. // loop over all child nodes and their edges to find edges going out of the cluster
  222. // these edges will be replaced by clusterEdges.
  223. let childKeys = Object.keys(childNodesObj);
  224. let createEdges = [];
  225. for (let i = 0; i < childKeys.length; i++) {
  226. childNodeId = childKeys[i];
  227. childNode = childNodesObj[childNodeId];
  228. // construct new edges from the cluster to others
  229. for (let j = 0; j < childNode.edges.length; j++) {
  230. edge = childNode.edges[j];
  231. // we only handle edges that are visible to the system, not the disabled ones from the clustering process.
  232. if (this.clusteredEdges[edge.id] === undefined) {
  233. // self-referencing edges will be added to the "hidden" list
  234. if (edge.toId == edge.fromId) {
  235. childEdgesObj[edge.id] = edge;
  236. }
  237. else {
  238. // set up the from and to.
  239. if (edge.toId == childNodeId) { // this is a double equals because ints and strings can be interchanged here.
  240. toId = clusterNodeProperties.id;
  241. fromId = edge.fromId;
  242. otherNodeId = fromId;
  243. }
  244. else {
  245. toId = edge.toId;
  246. fromId = clusterNodeProperties.id;
  247. otherNodeId = toId;
  248. }
  249. }
  250. // Only edges from the cluster outwards are being replaced.
  251. if (childNodesObj[otherNodeId] === undefined) {
  252. createEdges.push({edge: edge, fromId: fromId, toId: toId});
  253. }
  254. }
  255. }
  256. }
  257. // here we actually create the replacement edges. We could not do this in the loop above as the creation process
  258. // would add an edge to the edges array we are iterating over.
  259. for (let j = 0; j < createEdges.length; j++) {
  260. let edge = createEdges[j].edge;
  261. // copy the options of the edge we will replace
  262. let clonedOptions = NetworkUtil.cloneOptions(edge, 'edge');
  263. // make sure the properties of clusterEdges are superimposed on it
  264. util.deepExtend(clonedOptions, clusterEdgeProperties);
  265. // set up the edge
  266. clonedOptions.from = createEdges[j].fromId;
  267. clonedOptions.to = createEdges[j].toId;
  268. clonedOptions.id = 'clusterEdge:' + util.randomUUID();
  269. //clonedOptions.id = '(cf: ' + createEdges[j].fromId + " to: " + createEdges[j].toId + ")" + Math.random();
  270. // create the edge and give a reference to the one it replaced.
  271. let newEdge = this.body.functions.createEdge(clonedOptions);
  272. newEdge.clusteringEdgeReplacingId = edge.id;
  273. // also reference the new edge in the old edge
  274. this.body.edges[edge.id].edgeReplacedById = newEdge.id;
  275. // connect the edge.
  276. this.body.edges[newEdge.id] = newEdge;
  277. newEdge.connect();
  278. // hide the replaced edge
  279. this._backupEdgeOptions(edge);
  280. edge.setOptions({physics:false, hidden:true});
  281. }
  282. }
  283. /**
  284. * This function checks the options that can be supplied to the different cluster functions
  285. * for certain fields and inserts defaults if needed
  286. * @param options
  287. * @returns {*}
  288. * @private
  289. */
  290. _checkOptions(options = {}) {
  291. if (options.clusterEdgeProperties === undefined) {options.clusterEdgeProperties = {};}
  292. if (options.clusterNodeProperties === undefined) {options.clusterNodeProperties = {};}
  293. return options;
  294. }
  295. /**
  296. *
  297. * @param {Object} childNodesObj | object with node objects, id as keys, same as childNodes except it also contains a source node
  298. * @param {Object} childEdgesObj | object with edge objects, id as keys
  299. * @param {Array} options | object with {clusterNodeProperties, clusterEdgeProperties, processProperties}
  300. * @param {Boolean} refreshData | when true, do not wrap up
  301. * @private
  302. */
  303. _cluster(childNodesObj, childEdgesObj, options, refreshData = true) {
  304. // kill condition: no nodes don't bother
  305. if (Object.keys(childNodesObj).length == 0) {return;}
  306. // allow clusters of 1 if options allow
  307. if (Object.keys(childNodesObj).length == 1 && options.clusterNodeProperties.allowSingleNodeCluster != true) {return;}
  308. // check if this cluster call is not trying to cluster anything that is in another cluster.
  309. for (let nodeId in childNodesObj) {
  310. if (childNodesObj.hasOwnProperty(nodeId)) {
  311. if (this.clusteredNodes[nodeId] !== undefined) {
  312. return;
  313. }
  314. }
  315. }
  316. let clusterNodeProperties = util.deepExtend({},options.clusterNodeProperties);
  317. // construct the clusterNodeProperties
  318. if (options.processProperties !== undefined) {
  319. // get the childNode options
  320. let childNodesOptions = [];
  321. for (let nodeId in childNodesObj) {
  322. if (childNodesObj.hasOwnProperty(nodeId)) {
  323. let clonedOptions = NetworkUtil.cloneOptions(childNodesObj[nodeId]);
  324. childNodesOptions.push(clonedOptions);
  325. }
  326. }
  327. // get cluster properties based on childNodes
  328. let childEdgesOptions = [];
  329. for (let edgeId in childEdgesObj) {
  330. if (childEdgesObj.hasOwnProperty(edgeId)) {
  331. // these cluster edges will be removed on creation of the cluster.
  332. if (edgeId.substr(0, 12) !== "clusterEdge:") {
  333. let clonedOptions = NetworkUtil.cloneOptions(childEdgesObj[edgeId], 'edge');
  334. childEdgesOptions.push(clonedOptions);
  335. }
  336. }
  337. }
  338. clusterNodeProperties = options.processProperties(clusterNodeProperties, childNodesOptions, childEdgesOptions);
  339. if (!clusterNodeProperties) {
  340. throw new Error("The processProperties function does not return properties!");
  341. }
  342. }
  343. // check if we have an unique id;
  344. if (clusterNodeProperties.id === undefined) {clusterNodeProperties.id = 'cluster:' + util.randomUUID();}
  345. let clusterId = clusterNodeProperties.id;
  346. if (clusterNodeProperties.label === undefined) {
  347. clusterNodeProperties.label = 'cluster';
  348. }
  349. // give the clusterNode a position if it does not have one.
  350. let pos = undefined;
  351. if (clusterNodeProperties.x === undefined) {
  352. pos = this._getClusterPosition(childNodesObj);
  353. clusterNodeProperties.x = pos.x;
  354. }
  355. if (clusterNodeProperties.y === undefined) {
  356. if (pos === undefined) {pos = this._getClusterPosition(childNodesObj);}
  357. clusterNodeProperties.y = pos.y;
  358. }
  359. // force the ID to remain the same
  360. clusterNodeProperties.id = clusterId;
  361. // create the clusterNode
  362. let clusterNode = this.body.functions.createNode(clusterNodeProperties, Cluster);
  363. clusterNode.isCluster = true;
  364. clusterNode.containedNodes = childNodesObj;
  365. clusterNode.containedEdges = childEdgesObj;
  366. // cache a copy from the cluster edge properties if we have to reconnect others later on
  367. clusterNode.clusterEdgeProperties = options.clusterEdgeProperties;
  368. // finally put the cluster node into global
  369. this.body.nodes[clusterNodeProperties.id] = clusterNode;
  370. // create the new edges that will connect to the cluster, all self-referencing edges will be added to childEdgesObject here.
  371. this._createClusterEdges(childNodesObj, childEdgesObj, clusterNodeProperties, options.clusterEdgeProperties);
  372. // disable the childEdges
  373. for (let edgeId in childEdgesObj) {
  374. if (childEdgesObj.hasOwnProperty(edgeId)) {
  375. if (this.body.edges[edgeId] !== undefined) {
  376. let edge = this.body.edges[edgeId];
  377. // cache the options before changing
  378. this._backupEdgeOptions(edge);
  379. // disable physics and hide the edge
  380. edge.setOptions({physics:false, hidden:true});
  381. }
  382. }
  383. }
  384. // disable the childNodes
  385. for (let nodeId in childNodesObj) {
  386. if (childNodesObj.hasOwnProperty(nodeId)) {
  387. this.clusteredNodes[nodeId] = {clusterId:clusterNodeProperties.id, node: this.body.nodes[nodeId]};
  388. this.body.nodes[nodeId].setOptions({hidden:true, physics:false});
  389. }
  390. }
  391. // set ID to undefined so no duplicates arise
  392. clusterNodeProperties.id = undefined;
  393. // wrap up
  394. if (refreshData === true) {
  395. this.body.emitter.emit('_dataChanged');
  396. }
  397. }
  398. _backupEdgeOptions(edge) {
  399. if (this.clusteredEdges[edge.id] === undefined) {
  400. this.clusteredEdges[edge.id] = {physics: edge.options.physics, hidden: edge.options.hidden};
  401. }
  402. }
  403. _restoreEdge(edge) {
  404. let originalOptions = this.clusteredEdges[edge.id];
  405. if (originalOptions !== undefined) {
  406. edge.setOptions({physics: originalOptions.physics, hidden: originalOptions.hidden});
  407. delete this.clusteredEdges[edge.id];
  408. }
  409. }
  410. /**
  411. * Check if a node is a cluster.
  412. * @param nodeId
  413. * @returns {*}
  414. */
  415. isCluster(nodeId) {
  416. if (this.body.nodes[nodeId] !== undefined) {
  417. return this.body.nodes[nodeId].isCluster === true;
  418. }
  419. else {
  420. console.log("Node does not exist.");
  421. return false;
  422. }
  423. }
  424. /**
  425. * get the position of the cluster node based on what's inside
  426. * @param {object} childNodesObj | object with node objects, id as keys
  427. * @returns {{x: number, y: number}}
  428. * @private
  429. */
  430. _getClusterPosition(childNodesObj) {
  431. let childKeys = Object.keys(childNodesObj);
  432. let minX = childNodesObj[childKeys[0]].x;
  433. let maxX = childNodesObj[childKeys[0]].x;
  434. let minY = childNodesObj[childKeys[0]].y;
  435. let maxY = childNodesObj[childKeys[0]].y;
  436. let node;
  437. for (let i = 1; i < childKeys.length; i++) {
  438. node = childNodesObj[childKeys[i]];
  439. minX = node.x < minX ? node.x : minX;
  440. maxX = node.x > maxX ? node.x : maxX;
  441. minY = node.y < minY ? node.y : minY;
  442. maxY = node.y > maxY ? node.y : maxY;
  443. }
  444. return {x: 0.5*(minX + maxX), y: 0.5*(minY + maxY)};
  445. }
  446. /**
  447. * Open a cluster by calling this function.
  448. * @param {String} clusterNodeId | the ID of the cluster node
  449. * @param {Boolean} refreshData | wrap up afterwards if not true
  450. */
  451. openCluster(clusterNodeId, options, refreshData = true) {
  452. // kill conditions
  453. if (clusterNodeId === undefined) {throw new Error("No clusterNodeId supplied to openCluster.");}
  454. if (this.body.nodes[clusterNodeId] === undefined) {throw new Error("The clusterNodeId supplied to openCluster does not exist.");}
  455. if (this.body.nodes[clusterNodeId].containedNodes === undefined) {
  456. console.log("The node:" + clusterNodeId + " is not a cluster.");
  457. return
  458. }
  459. let clusterNode = this.body.nodes[clusterNodeId];
  460. let containedNodes = clusterNode.containedNodes;
  461. let containedEdges = clusterNode.containedEdges;
  462. // allow the user to position the nodes after release.
  463. if (options !== undefined && options.releaseFunction !== undefined && typeof options.releaseFunction === 'function') {
  464. let positions = {};
  465. let clusterPosition = {x:clusterNode.x, y:clusterNode.y};
  466. for (let nodeId in containedNodes) {
  467. if (containedNodes.hasOwnProperty(nodeId)) {
  468. let containedNode = this.body.nodes[nodeId];
  469. positions[nodeId] = {x: containedNode.x, y: containedNode.y};
  470. }
  471. }
  472. let newPositions = options.releaseFunction(clusterPosition, positions);
  473. for (let nodeId in containedNodes) {
  474. if (containedNodes.hasOwnProperty(nodeId)) {
  475. let containedNode = this.body.nodes[nodeId];
  476. if (newPositions[nodeId] !== undefined) {
  477. containedNode.x = (newPositions[nodeId].x === undefined ? clusterNode.x : newPositions[nodeId].x);
  478. containedNode.y = (newPositions[nodeId].y === undefined ? clusterNode.y : newPositions[nodeId].y);
  479. }
  480. }
  481. }
  482. }
  483. else {
  484. // copy the position from the cluster
  485. for (let nodeId in containedNodes) {
  486. if (containedNodes.hasOwnProperty(nodeId)) {
  487. let containedNode = this.body.nodes[nodeId];
  488. containedNode = containedNodes[nodeId];
  489. // inherit position
  490. if (containedNode.options.fixed.x === false) {containedNode.x = clusterNode.x;}
  491. if (containedNode.options.fixed.y === false) {containedNode.y = clusterNode.y;}
  492. }
  493. }
  494. }
  495. // release nodes
  496. for (let nodeId in containedNodes) {
  497. if (containedNodes.hasOwnProperty(nodeId)) {
  498. let containedNode = this.body.nodes[nodeId];
  499. // inherit speed
  500. containedNode.vx = clusterNode.vx;
  501. containedNode.vy = clusterNode.vy;
  502. // we use these methods to avoid re-instantiating the shape, which happens with setOptions.
  503. containedNode.setOptions({hidden:false, physics:true});
  504. delete this.clusteredNodes[nodeId];
  505. }
  506. }
  507. // copy the clusterNode edges because we cannot iterate over an object that we add or remove from.
  508. let edgesToBeDeleted = [];
  509. for (let i = 0; i < clusterNode.edges.length; i++) {
  510. edgesToBeDeleted.push(clusterNode.edges[i]);
  511. }
  512. // actually handling the deleting.
  513. for (let i = 0; i < edgesToBeDeleted.length; i++) {
  514. let edge = edgesToBeDeleted[i];
  515. let otherNodeId = this._getConnectedId(edge, clusterNodeId);
  516. // if the other node is in another cluster, we transfer ownership of this edge to the other cluster
  517. if (this.clusteredNodes[otherNodeId] !== undefined) {
  518. // transfer ownership:
  519. let otherCluster = this.body.nodes[this.clusteredNodes[otherNodeId].clusterId];
  520. let transferEdge = this.body.edges[edge.clusteringEdgeReplacingId];
  521. if (transferEdge !== undefined) {
  522. otherCluster.containedEdges[transferEdge.id] = transferEdge;
  523. // delete local reference
  524. delete containedEdges[transferEdge.id];
  525. // create new cluster edge from the otherCluster:
  526. // get to and from
  527. let fromId = transferEdge.fromId;
  528. let toId = transferEdge.toId;
  529. if (transferEdge.toId == otherNodeId) {
  530. toId = this.clusteredNodes[otherNodeId].clusterId;
  531. }
  532. else {
  533. fromId = this.clusteredNodes[otherNodeId].clusterId;
  534. }
  535. // clone the options and apply the cluster options to them
  536. let clonedOptions = NetworkUtil.cloneOptions(transferEdge, 'edge');
  537. util.deepExtend(clonedOptions, otherCluster.clusterEdgeProperties);
  538. // apply the edge specific options to it.
  539. let id = 'clusterEdge:' + util.randomUUID();
  540. util.deepExtend(clonedOptions, {from: fromId, to: toId, hidden: false, physics: true, id: id});
  541. // create it
  542. let newEdge = this.body.functions.createEdge(clonedOptions);
  543. newEdge.clusteringEdgeReplacingId = transferEdge.id;
  544. this.body.edges[id] = newEdge;
  545. this.body.edges[id].connect();
  546. }
  547. }
  548. else {
  549. let replacedEdge = this.body.edges[edge.clusteringEdgeReplacingId];
  550. if (replacedEdge !== undefined) {
  551. this._restoreEdge(replacedEdge);
  552. }
  553. }
  554. edge.cleanup();
  555. // this removes the edge from node.edges, which is why edgeIds is formed
  556. edge.disconnect();
  557. delete this.body.edges[edge.id];
  558. }
  559. // handle the releasing of the edges
  560. for (let edgeId in containedEdges) {
  561. if (containedEdges.hasOwnProperty(edgeId)) {
  562. this._restoreEdge(containedEdges[edgeId]);
  563. }
  564. }
  565. // remove clusterNode
  566. delete this.body.nodes[clusterNodeId];
  567. if (refreshData === true) {
  568. this.body.emitter.emit('_dataChanged');
  569. }
  570. }
  571. getNodesInCluster(clusterId) {
  572. let nodesArray = [];
  573. if (this.isCluster(clusterId) === true) {
  574. let containedNodes = this.body.nodes[clusterId].containedNodes;
  575. for (let nodeId in containedNodes) {
  576. if (containedNodes.hasOwnProperty(nodeId)) {
  577. nodesArray.push(this.body.nodes[nodeId].id)
  578. }
  579. }
  580. }
  581. return nodesArray;
  582. }
  583. /**
  584. * Get the stack clusterId's that a certain node resides in. cluster A -> cluster B -> cluster C -> node
  585. * @param nodeId
  586. * @returns {Array}
  587. */
  588. findNode(nodeId) {
  589. let stack = [];
  590. let max = 100;
  591. let counter = 0;
  592. while (this.clusteredNodes[nodeId] !== undefined && counter < max) {
  593. stack.push(this.body.nodes[nodeId].id);
  594. nodeId = this.clusteredNodes[nodeId].clusterId;
  595. counter++;
  596. }
  597. stack.push(this.body.nodes[nodeId].id);
  598. stack.reverse();
  599. return stack;
  600. }
  601. /**
  602. * Using a clustered nodeId, update with the new options
  603. * @param clusteredNodeId
  604. * @param {object} newOptions
  605. */
  606. updateClusteredNode(clusteredNodeId, newOptions) {
  607. if (clusteredNodeId === undefined) {throw new Error("No clusteredNodeId supplied to updateClusteredNode.");}
  608. if (newOptions === undefined) {throw new Error("No newOptions supplied to updateClusteredNode.");}
  609. if (this.body.nodes[clusteredNodeId] === undefined) {throw new Error("The clusteredNodeId supplied to updateClusteredNode does not exist.");}
  610. this.body.nodes[clusteredNodeId].setOptions(newOptions);
  611. this.body.emitter.emit('_dataChanged');
  612. }
  613. /**
  614. * Using a base edgeId, update all related clustered edges with the new options
  615. * @param startEdgeId
  616. * @param {object} newOptions
  617. */
  618. updateEdge(startEdgeId, newOptions) {
  619. if (startEdgeId === undefined) {throw new Error("No startEdgeId supplied to updateEdge.");}
  620. if (newOptions === undefined) {throw new Error("No newOptions supplied to updateEdge.");}
  621. if (this.body.edges[startEdgeId] === undefined) {throw new Error("The startEdgeId supplied to updateEdge does not exist.");}
  622. let allEdgeIds = this.getClusteredEdges(startEdgeId);
  623. for (let i = 0; i < allEdgeIds.length; i++) {
  624. var edge = this.body.edges[allEdgeIds[i]];
  625. edge.setOptions(newOptions);
  626. }
  627. this.body.emitter.emit('_dataChanged');
  628. }
  629. /**
  630. * 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)
  631. * @param edgeId
  632. * @returns {Array}
  633. */
  634. getClusteredEdges(edgeId) {
  635. let stack = [];
  636. let max = 100;
  637. let counter = 0;
  638. while (edgeId !== undefined && this.body.edges[edgeId] !== undefined && counter < max) {
  639. stack.push(this.body.edges[edgeId].id);
  640. edgeId = this.body.edges[edgeId].edgeReplacedById;
  641. counter++;
  642. }
  643. stack.reverse();
  644. return stack;
  645. }
  646. /**
  647. * Get the base edge id of clusterEdgeId. cluster edge (clusteredEdgeId) -> cluster edge B -> cluster edge C -> base edge
  648. * @param clusteredEdgeId
  649. * @returns baseEdgeId
  650. */
  651. getBaseEdge(clusteredEdgeId) {
  652. let baseEdgeId = clusteredEdgeId;
  653. let max = 100;
  654. let counter = 0;
  655. while (clusteredEdgeId !== undefined && this.body.edges[clusteredEdgeId] !== undefined && counter < max) {
  656. clusteredEdgeId = this.body.edges[clusteredEdgeId].clusteringEdgeReplacingId;
  657. counter++;
  658. if (clusteredEdgeId !== undefined) {
  659. baseEdgeId = clusteredEdgeId;
  660. }
  661. }
  662. return baseEdgeId;
  663. }
  664. /**
  665. * Get the Id the node is connected to
  666. * @param edge
  667. * @param nodeId
  668. * @returns {*}
  669. * @private
  670. */
  671. _getConnectedId(edge, nodeId) {
  672. if (edge.toId != nodeId) {
  673. return edge.toId;
  674. }
  675. else if (edge.fromId != nodeId) {
  676. return edge.fromId;
  677. }
  678. else {
  679. return edge.fromId;
  680. }
  681. }
  682. /**
  683. * We determine how many connections denote an important hub.
  684. * We take the mean + 2*std as the important hub size. (Assuming a normal distribution of data, ~2.2%)
  685. *
  686. * @private
  687. */
  688. _getHubSize() {
  689. let average = 0;
  690. let averageSquared = 0;
  691. let hubCounter = 0;
  692. let largestHub = 0;
  693. for (let i = 0; i < this.body.nodeIndices.length; i++) {
  694. let node = this.body.nodes[this.body.nodeIndices[i]];
  695. if (node.edges.length > largestHub) {
  696. largestHub = node.edges.length;
  697. }
  698. average += node.edges.length;
  699. averageSquared += Math.pow(node.edges.length,2);
  700. hubCounter += 1;
  701. }
  702. average = average / hubCounter;
  703. averageSquared = averageSquared / hubCounter;
  704. let variance = averageSquared - Math.pow(average,2);
  705. let standardDeviation = Math.sqrt(variance);
  706. let hubThreshold = Math.floor(average + 2*standardDeviation);
  707. // always have at least one to cluster
  708. if (hubThreshold > largestHub) {
  709. hubThreshold = largestHub;
  710. }
  711. return hubThreshold;
  712. };
  713. }
  714. export default ClusterEngine;