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.

586 lines
18 KiB

  1. /**
  2. * Created by Alex on 24-Feb-15.
  3. */
  4. var util = require("../../util");
  5. import Cluster from './components/nodes/cluster'
  6. class ClusterEngine {
  7. constructor(body) {
  8. this.body = body;
  9. this.clusteredNodes = {};
  10. }
  11. setOptions(options) {
  12. }
  13. /**
  14. *
  15. * @param hubsize
  16. * @param options
  17. */
  18. clusterByConnectionCount(hubsize, options) {
  19. if (hubsize === undefined) {
  20. hubsize = this._getHubSize();
  21. }
  22. else if (tyepof(hubsize) == "object") {
  23. options = this._checkOptions(hubsize);
  24. hubsize = this._getHubSize();
  25. }
  26. var nodesToCluster = [];
  27. for (var i = 0; i < this.body.nodeIndices.length; i++) {
  28. var node = this.body.nodes[this.body.nodeIndices[i]];
  29. if (node.edges.length >= hubsize) {
  30. nodesToCluster.push(node.id);
  31. }
  32. }
  33. for (var i = 0; i < nodesToCluster.length; i++) {
  34. var node = this.body.nodes[nodesToCluster[i]];
  35. this.clusterByConnection(node,options,{},{},false);
  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. clusterByNodeData(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. var childNodesObj = {};
  49. var childEdgesObj = {}
  50. // collect the nodes that will be in the cluster
  51. for (var i = 0; i < this.body.nodeIndices.length; i++) {
  52. var nodeId = this.body.nodeIndices[i];
  53. var clonedOptions = this._cloneOptions(nodeId);
  54. if (options.joinCondition(clonedOptions) == true) {
  55. childNodesObj[nodeId] = this.body.nodes[nodeId];
  56. }
  57. }
  58. this._cluster(childNodesObj, childEdgesObj, options, refreshData);
  59. }
  60. /**
  61. * Cluster all nodes in the network that have only 1 edge
  62. * @param options
  63. * @param refreshData
  64. */
  65. clusterOutliers(options, refreshData = true) {
  66. options = this._checkOptions(options);
  67. var clusters = [];
  68. // collect the nodes that will be in the cluster
  69. for (var i = 0; i < this.body.nodeIndices.length; i++) {
  70. var childNodesObj = {};
  71. var childEdgesObj = {};
  72. var nodeId = this.body.nodeIndices[i];
  73. if (this.body.nodes[nodeId].edges.length == 1) {
  74. var edge = this.body.nodes[nodeId].edges[0];
  75. var childNodeId = this._getConnectedId(edge, nodeId);
  76. if (childNodeId != nodeId) {
  77. if (options.joinCondition === undefined) {
  78. childNodesObj[nodeId] = this.body.nodes[nodeId];
  79. childNodesObj[childNodeId] = this.body.nodes[childNodeId];
  80. }
  81. else {
  82. var clonedOptions = this._cloneOptions(nodeId);
  83. if (options.joinCondition(clonedOptions) == true) {
  84. childNodesObj[nodeId] = this.body.nodes[nodeId];
  85. }
  86. clonedOptions = this._cloneOptions(childNodeId);
  87. if (options.joinCondition(clonedOptions) == true) {
  88. childNodesObj[childNodeId] = this.body.nodes[childNodeId];
  89. }
  90. }
  91. clusters.push({nodes:childNodesObj, edges:childEdgesObj})
  92. }
  93. }
  94. }
  95. for (var i = 0; i < clusters.length; i++) {
  96. this._cluster(clusters[i].nodes, clusters[i].edges, options, false)
  97. }
  98. if (refreshData === true) {
  99. this.body.emitter.emit('_dataChanged');
  100. }
  101. }
  102. /**
  103. *
  104. * @param nodeId
  105. * @param options
  106. * @param refreshData
  107. */
  108. clusterByConnection(nodeId, options, refreshData = true) {
  109. // kill conditions
  110. if (nodeId === undefined) {throw new Error("No nodeId supplied to clusterByConnection!");}
  111. if (this.body.nodes[nodeId] === undefined) {throw new Error("The nodeId given to clusterByConnection does not exist!");}
  112. var node = this.body.nodes[nodeId];
  113. options = this._checkOptions(options, node);
  114. if (options.clusterNodeProperties.x === undefined) {options.clusterNodeProperties.x = node.x; options.clusterNodeProperties.allowedToMoveX = !node.xFixed;}
  115. if (options.clusterNodeProperties.y === undefined) {options.clusterNodeProperties.y = node.y; options.clusterNodeProperties.allowedToMoveY = !node.yFixed;}
  116. var childNodesObj = {};
  117. var childEdgesObj = {}
  118. var parentNodeId = node.id;
  119. var parentClonedOptions = this._cloneOptions(parentNodeId);
  120. childNodesObj[parentNodeId] = node;
  121. // collect the nodes that will be in the cluster
  122. for (var i = 0; i < node.edges.length; i++) {
  123. var edge = node.edges[i];
  124. var childNodeId = this._getConnectedId(edge, parentNodeId);
  125. if (childNodeId !== parentNodeId) {
  126. if (options.joinCondition === undefined) {
  127. childEdgesObj[edge.id] = edge;
  128. childNodesObj[childNodeId] = this.body.nodes[childNodeId];
  129. }
  130. else {
  131. // clone the options and insert some additional parameters that could be interesting.
  132. var childClonedOptions = this._cloneOptions(childNodeId);
  133. if (options.joinCondition(parentClonedOptions, childClonedOptions) == true) {
  134. childEdgesObj[edge.id] = edge;
  135. childNodesObj[childNodeId] = this.body.nodes[childNodeId];
  136. }
  137. }
  138. }
  139. else {
  140. childEdgesObj[edge.id] = edge;
  141. }
  142. }
  143. this._cluster(childNodesObj, childEdgesObj, options, refreshData);
  144. }
  145. /**
  146. * This returns a clone of the options or options of the edge or node to be used for construction of new edges or check functions for new nodes.
  147. * @param objId
  148. * @param type
  149. * @returns {{}}
  150. * @private
  151. */
  152. _cloneOptions(objId, type) {
  153. var clonedOptions = {};
  154. if (type === undefined || type == 'node') {
  155. util.deepExtend(clonedOptions, this.body.nodes[objId].options, true);
  156. util.deepExtend(clonedOptions, this.body.nodes[objId].properties, true);
  157. clonedOptions.amountOfConnections = this.body.nodes[objId].edges.length;
  158. }
  159. else {
  160. util.deepExtend(clonedOptions, this.body.edges[objId].properties, true);
  161. }
  162. return clonedOptions;
  163. }
  164. /**
  165. * This function creates the edges that will be attached to the cluster.
  166. *
  167. * @param childNodesObj
  168. * @param childEdgesObj
  169. * @param newEdges
  170. * @param options
  171. * @private
  172. */
  173. _createClusterEdges (childNodesObj, childEdgesObj, newEdges, options) {
  174. var edge, childNodeId, childNode;
  175. var childKeys = Object.keys(childNodesObj);
  176. for (var i = 0; i < childKeys.length; i++) {
  177. childNodeId = childKeys[i];
  178. childNode = childNodesObj[childNodeId];
  179. // mark all edges for removal from global and construct new edges from the cluster to others
  180. for (var j = 0; j < childNode.edges.length; j++) {
  181. edge = childNode.edges[j];
  182. childEdgesObj[edge.id] = edge;
  183. var otherNodeId = edge.toId;
  184. var otherOnTo = true;
  185. if (edge.toId != childNodeId) {
  186. otherNodeId = edge.toId;
  187. otherOnTo = true;
  188. }
  189. else if (edge.fromId != childNodeId) {
  190. otherNodeId = edge.fromId;
  191. otherOnTo = false;
  192. }
  193. if (childNodesObj[otherNodeId] === undefined) {
  194. var clonedOptions = this._cloneOptions(edge.id, 'edge');
  195. util.deepExtend(clonedOptions, options.clusterEdgeProperties);
  196. if (otherOnTo === true) {
  197. clonedOptions.from = options.clusterNodeProperties.id;
  198. clonedOptions.to = otherNodeId;
  199. }
  200. else {
  201. clonedOptions.from = otherNodeId;
  202. clonedOptions.to = options.clusterNodeProperties.id;
  203. }
  204. clonedOptions.id = 'clusterEdge:' + util.randomUUID();
  205. newEdges.push(this.body.functions.createEdge(clonedOptions))
  206. }
  207. }
  208. }
  209. }
  210. /**
  211. * This function checks the options that can be supplied to the different cluster functions
  212. * for certain fields and inserts defaults if needed
  213. * @param options
  214. * @returns {*}
  215. * @private
  216. */
  217. _checkOptions(options = {}) {
  218. if (options.clusterEdgeProperties === undefined) {options.clusterEdgeProperties = {};}
  219. if (options.clusterNodeProperties === undefined) {options.clusterNodeProperties = {};}
  220. return options;
  221. }
  222. /**
  223. *
  224. * @param {Object} childNodesObj | object with node objects, id as keys, same as childNodes except it also contains a source node
  225. * @param {Object} childEdgesObj | object with edge objects, id as keys
  226. * @param {Array} options | object with {clusterNodeProperties, clusterEdgeProperties, processProperties}
  227. * @param {Boolean} refreshData | when true, do not wrap up
  228. * @private
  229. */
  230. _cluster(childNodesObj, childEdgesObj, options, refreshData = true) {
  231. // kill condition: no children so cant cluster
  232. if (Object.keys(childNodesObj).length == 0) {return;}
  233. // check if we have an unique id;
  234. if (options.clusterNodeProperties.id === undefined) {options.clusterNodeProperties.id = 'cluster:' + util.randomUUID();}
  235. var clusterId = options.clusterNodeProperties.id;
  236. // create the new edges that will connect to the cluster
  237. var newEdges = [];
  238. this._createClusterEdges(childNodesObj, childEdgesObj, newEdges, options);
  239. // construct the clusterNodeProperties
  240. var clusterNodeProperties = options.clusterNodeProperties;
  241. if (options.processProperties !== undefined) {
  242. // get the childNode options
  243. var childNodesOptions = [];
  244. for (var nodeId in childNodesObj) {
  245. var clonedOptions = this._cloneOptions(nodeId);
  246. childNodesOptions.push(clonedOptions);
  247. }
  248. // get clusterproperties based on childNodes
  249. var childEdgesOptions = [];
  250. for (var edgeId in childEdgesObj) {
  251. var clonedOptions = this._cloneOptions(edgeId, 'edge');
  252. childEdgesOptions.push(clonedOptions);
  253. }
  254. clusterNodeProperties = options.processProperties(clusterNodeProperties, childNodesOptions, childEdgesOptions);
  255. if (!clusterNodeProperties) {
  256. throw new Error("The processClusterProperties function does not return properties!");
  257. }
  258. }
  259. if (clusterNodeProperties.label === undefined) {
  260. clusterNodeProperties.label = 'cluster';
  261. }
  262. // give the clusterNode a postion if it does not have one.
  263. var pos = undefined;
  264. if (clusterNodeProperties.x === undefined) {
  265. pos = this._getClusterPosition(childNodesObj);
  266. clusterNodeProperties.x = pos.x;
  267. clusterNodeProperties.allowedToMoveX = true;
  268. }
  269. if (clusterNodeProperties.x === undefined) {
  270. if (pos === undefined) {
  271. pos = this._getClusterPosition(childNodesObj);
  272. }
  273. clusterNodeProperties.y = pos.y;
  274. clusterNodeProperties.allowedToMoveY = true;
  275. }
  276. // force the ID to remain the same
  277. clusterNodeProperties.id = clusterId;
  278. // create the clusterNode
  279. var clusterNode = this.body.functions.createNode(clusterNodeProperties, Cluster);
  280. clusterNode.isCluster = true;
  281. clusterNode.containedNodes = childNodesObj;
  282. clusterNode.containedEdges = childEdgesObj;
  283. // disable the childEdges
  284. for (var edgeId in childEdgesObj) {
  285. if (childEdgesObj.hasOwnProperty(edgeId)) {
  286. if (this.body.edges[edgeId] !== undefined) {
  287. let edge = this.body.edges[edgeId];
  288. edge.togglePhysics(false);
  289. edge.options.hidden = true;
  290. }
  291. }
  292. }
  293. // disable the childNodes
  294. for (var nodeId in childNodesObj) {
  295. if (childNodesObj.hasOwnProperty(nodeId)) {
  296. this.clusteredNodes[nodeId] = {clusterId:clusterNodeProperties.id, node: this.body.nodes[nodeId]};
  297. this.body.nodes[nodeId].togglePhysics(false);
  298. this.body.nodes[nodeId].options.hidden = true;
  299. }
  300. }
  301. // finally put the cluster node into global
  302. this.body.nodes[clusterNodeProperties.id] = clusterNode;
  303. // push new edges to global
  304. for (var i = 0; i < newEdges.length; i++) {
  305. this.body.edges[newEdges[i].id] = newEdges[i];
  306. this.body.edges[newEdges[i].id].connect();
  307. }
  308. // set ID to undefined so no duplicates arise
  309. clusterNodeProperties.id = undefined;
  310. // wrap up
  311. if (refreshData === true) {
  312. this.body.emitter.emit('_dataChanged');
  313. }
  314. }
  315. /**
  316. * Check if a node is a cluster.
  317. * @param nodeId
  318. * @returns {*}
  319. */
  320. isCluster(nodeId) {
  321. if (this.body.nodes[nodeId] !== undefined) {
  322. return this.body.nodes[nodeId].isCluster === true;
  323. }
  324. else {
  325. console.log("Node does not exist.")
  326. return false;
  327. }
  328. }
  329. /**
  330. * get the position of the cluster node based on what's inside
  331. * @param {object} childNodesObj | object with node objects, id as keys
  332. * @returns {{x: number, y: number}}
  333. * @private
  334. */
  335. _getClusterPosition(childNodesObj) {
  336. var childKeys = Object.keys(childNodesObj);
  337. var minX = childNodesObj[childKeys[0]].x;
  338. var maxX = childNodesObj[childKeys[0]].x;
  339. var minY = childNodesObj[childKeys[0]].y;
  340. var maxY = childNodesObj[childKeys[0]].y;
  341. var node;
  342. for (var i = 0; i < childKeys.lenght; i++) {
  343. node = childNodesObj[childKeys[0]];
  344. minX = node.x < minX ? node.x : minX;
  345. maxX = node.x > maxX ? node.x : maxX;
  346. minY = node.y < minY ? node.y : minY;
  347. maxY = node.y > maxY ? node.y : maxY;
  348. }
  349. return {x: 0.5*(minX + maxX), y: 0.5*(minY + maxY)};
  350. }
  351. /**
  352. * Open a cluster by calling this function.
  353. * @param {String} clusterNodeId | the ID of the cluster node
  354. * @param {Boolean} refreshData | wrap up afterwards if not true
  355. */
  356. openCluster(clusterNodeId, refreshData = true) {
  357. // kill conditions
  358. if (clusterNodeId === undefined) {throw new Error("No clusterNodeId supplied to openCluster.");}
  359. if (this.body.nodes[clusterNodeId] === undefined) {throw new Error("The clusterNodeId supplied to openCluster does not exist.");}
  360. if (this.body.nodes[clusterNodeId].containedNodes === undefined) {console.log("The node:" + clusterNodeId + " is not a cluster."); return};
  361. var clusterNode = this.body.nodes[clusterNodeId];
  362. var containedNodes = clusterNode.containedNodes;
  363. var containedEdges = clusterNode.containedEdges;
  364. // release nodes
  365. for (var nodeId in containedNodes) {
  366. if (containedNodes.hasOwnProperty(nodeId)) {
  367. let containedNode = this.body.nodes[nodeId];
  368. containedNode = containedNodes[nodeId];
  369. // inherit position
  370. containedNode.x = clusterNode.x;
  371. containedNode.y = clusterNode.y;
  372. // inherit speed
  373. containedNode.vx = clusterNode.vx;
  374. containedNode.vy = clusterNode.vy;
  375. containedNode.options.hidden = false;
  376. containedNode.togglePhysics(true);
  377. delete this.clusteredNodes[nodeId];
  378. }
  379. }
  380. // release edges
  381. for (var edgeId in containedEdges) {
  382. if (containedEdges.hasOwnProperty(edgeId)) {
  383. var edge = this.body.edges[edgeId];
  384. edge.options.hidden = false;
  385. edge.togglePhysics(true);
  386. }
  387. }
  388. // remove all temporary edges
  389. for (var i = 0; i < clusterNode.edges.length; i++) {
  390. var edgeId = clusterNode.edges[i].id;
  391. var viaId = this.body.edges[edgeId].via.id;
  392. if (viaId) {
  393. this.body.edges[edgeId].via = undefined;
  394. delete this.body.nodes[viaId];
  395. }
  396. // this removes the edge from node.edges, which is why edgeIds is formed
  397. this.body.edges[edgeId].disconnect();
  398. delete this.body.edges[edgeId];
  399. }
  400. // remove clusterNode
  401. delete this.body.nodes[clusterNodeId];
  402. if (refreshData === true) {
  403. this.body.emitter.emit('_dataChanged');
  404. }
  405. }
  406. /**
  407. * Connect an edge that was previously contained from cluster A to cluster B if the node that it was originally connected to
  408. * is currently residing in cluster B
  409. * @param edge
  410. * @param nodeId
  411. * @param from
  412. * @private
  413. */
  414. _connectEdge(edge, nodeId, from) {
  415. var clusterStack = this._getClusterStack(nodeId);
  416. if (from == true) {
  417. edge.from = clusterStack[clusterStack.length - 1];
  418. edge.fromId = clusterStack[clusterStack.length - 1].id;
  419. clusterStack.pop()
  420. edge.fromArray = clusterStack;
  421. }
  422. else {
  423. edge.to = clusterStack[clusterStack.length - 1];
  424. edge.toId = clusterStack[clusterStack.length - 1].id;
  425. clusterStack.pop();
  426. edge.toArray = clusterStack;
  427. }
  428. edge.connect();
  429. }
  430. /**
  431. * Get the stack clusterId's that a certain node resides in. cluster A -> cluster B -> cluster C -> node
  432. * @param nodeId
  433. * @returns {Array}
  434. * @private
  435. */
  436. _getClusterStack(nodeId) {
  437. var stack = [];
  438. var max = 100;
  439. var counter = 0;
  440. while (this.clusteredNodes[nodeId] !== undefined && counter < max) {
  441. stack.push(this.clusteredNodes[nodeId].node);
  442. nodeId = this.clusteredNodes[nodeId].clusterId;
  443. counter++;
  444. }
  445. stack.push(this.body.nodes[nodeId]);
  446. return stack;
  447. }
  448. /**
  449. * Get the Id the node is connected to
  450. * @param edge
  451. * @param nodeId
  452. * @returns {*}
  453. * @private
  454. */
  455. _getConnectedId(edge, nodeId) {
  456. if (edge.toId != nodeId) {
  457. return edge.toId;
  458. }
  459. else if (edge.fromId != nodeId) {
  460. return edge.fromId;
  461. }
  462. else {
  463. return edge.fromId;
  464. }
  465. }
  466. /**
  467. * We determine how many connections denote an important hub.
  468. * We take the mean + 2*std as the important hub size. (Assuming a normal distribution of data, ~2.2%)
  469. *
  470. * @private
  471. */
  472. _getHubSize() {
  473. var average = 0;
  474. var averageSquared = 0;
  475. var hubCounter = 0;
  476. var largestHub = 0;
  477. for (var i = 0; i < this.body.nodeIndices.length; i++) {
  478. var node = this.body.nodes[this.body.nodeIndices[i]];
  479. if (node.edges.length > largestHub) {
  480. largestHub = node.edges.length;
  481. }
  482. average += node.edges.length;
  483. averageSquared += Math.pow(node.edges.length,2);
  484. hubCounter += 1;
  485. }
  486. average = average / hubCounter;
  487. averageSquared = averageSquared / hubCounter;
  488. var variance = averageSquared - Math.pow(average,2);
  489. var standardDeviation = Math.sqrt(variance);
  490. var hubThreshold = Math.floor(average + 2*standardDeviation);
  491. // always have at least one to cluster
  492. if (hubThreshold > largestHub) {
  493. hubThreshold = largestHub;
  494. }
  495. return hubThreshold;
  496. };
  497. }
  498. export default ClusterEngine;