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.

564 lines
19 KiB

9 years ago
9 years ago
9 years ago
  1. 'use strict'
  2. let util = require('../../util');
  3. class LayoutEngine {
  4. constructor(body) {
  5. this.body = body;
  6. this.initialRandomSeed = Math.round(Math.random() * 1000000);
  7. this.randomSeed = this.initialRandomSeed;
  8. this.options = {};
  9. this.optionsBackup = {};
  10. this.defaultOptions = {
  11. randomSeed: undefined,
  12. improvedLayout: true,
  13. hierarchical: {
  14. enabled:false,
  15. levelSeparation: 150,
  16. direction: 'UD', // UD, DU, LR, RL
  17. sortMethod: 'hubsize' // hubsize, directed
  18. }
  19. };
  20. util.extend(this.options, this.defaultOptions);
  21. this.hierarchicalLevels = {};
  22. this.bindEventListeners();
  23. }
  24. bindEventListeners() {
  25. this.body.emitter.on('_dataChanged', () => {
  26. this.setupHierarchicalLayout();
  27. });
  28. this.body.emitter.on('_dataLoaded', () => {
  29. this.layoutNetwork();
  30. });
  31. this.body.emitter.on('_resetHierarchicalLayout', () => {
  32. this.setupHierarchicalLayout();
  33. });
  34. }
  35. setOptions(options, allOptions) {
  36. if (options !== undefined) {
  37. let prevHierarchicalState = this.options.hierarchical.enabled;
  38. util.selectiveDeepExtend(["randomSeed", "improvedLayout"],this.options, options);
  39. util.mergeOptions(this.options, options, 'hierarchical');
  40. if (options.randomSeed !== undefined) {this.initialRandomSeed = options.randomSeed;}
  41. if (this.options.hierarchical.enabled === true) {
  42. if (prevHierarchicalState === true) {
  43. // refresh the overridden options for nodes and edges.
  44. this.body.emitter.emit('refresh', true);
  45. }
  46. // make sure the level seperation is the right way up
  47. if (this.options.hierarchical.direction === 'RL' || this.options.hierarchical.direction === 'DU') {
  48. if (this.options.hierarchical.levelSeparation > 0) {
  49. this.options.hierarchical.levelSeparation *= -1;
  50. }
  51. }
  52. else {
  53. if (this.options.hierarchical.levelSeparation < 0) {
  54. this.options.hierarchical.levelSeparation *= -1;
  55. }
  56. }
  57. this.body.emitter.emit('_resetHierarchicalLayout');
  58. // because the hierarchical system needs it's own physics and smooth curve settings, we adapt the other options if needed.
  59. return this.adaptAllOptions(allOptions);
  60. }
  61. else {
  62. if (prevHierarchicalState === true) {
  63. // refresh the overridden options for nodes and edges.
  64. this.body.emitter.emit('refresh');
  65. return util.deepExtend(allOptions,this.optionsBackup);
  66. }
  67. }
  68. }
  69. return allOptions;
  70. }
  71. adaptAllOptions(allOptions) {
  72. if (this.options.hierarchical.enabled === true) {
  73. // set the physics
  74. if (allOptions.physics === undefined || allOptions.physics === true) {
  75. allOptions.physics = {solver: 'hierarchicalRepulsion'};
  76. this.optionsBackup.physics = {solver:'barnesHut'};
  77. }
  78. else if (typeof allOptions.physics === 'object') {
  79. this.optionsBackup.physics = {solver:'barnesHut'};
  80. if (allOptions.physics.solver !== undefined) {
  81. this.optionsBackup.physics = {solver:allOptions.physics.solver};
  82. }
  83. allOptions.physics['solver'] = 'hierarchicalRepulsion';
  84. }
  85. else if (allOptions.physics !== false) {
  86. this.optionsBackup.physics = {solver:'barnesHut'};
  87. allOptions.physics['solver'] = 'hierarchicalRepulsion';
  88. }
  89. // get the type of static smooth curve in case it is required
  90. let type = 'horizontal';
  91. if (this.options.hierarchical.direction === 'RL' || this.options.hierarchical.direction === 'LR') {
  92. type = 'vertical';
  93. }
  94. // disable smooth curves if nothing is defined. If smooth curves have been turned on, turn them into static smooth curves.
  95. if (allOptions.edges === undefined) {
  96. this.optionsBackup.edges = {smooth:{enabled:true, type:'dynamic'}};
  97. allOptions.edges = {smooth: false};
  98. }
  99. else if (allOptions.edges.smooth === undefined) {
  100. this.optionsBackup.edges = {smooth:{enabled:true, type:'dynamic'}};
  101. allOptions.edges.smooth = false;
  102. }
  103. else {
  104. if (typeof allOptions.edges.smooth === 'boolean') {
  105. this.optionsBackup.edges = {smooth:allOptions.edges.smooth};
  106. allOptions.edges.smooth = {enabled: allOptions.edges.smooth, type:type}
  107. }
  108. else {
  109. // allow custom types except for dynamic
  110. if (allOptions.edges.smooth.type !== undefined && allOptions.edges.smooth.type !== 'dynamic') {
  111. type = allOptions.edges.smooth.type;
  112. }
  113. this.optionsBackup.edges = {
  114. smooth: allOptions.edges.smooth.enabled === undefined ? true : allOptions.edges.smooth.enabled,
  115. type:allOptions.edges.smooth.type === undefined ? 'dynamic' : allOptions.edges.smooth.type,
  116. roundness: allOptions.edges.smooth.roundness === undefined ? 0.5 : allOptions.edges.smooth.roundness,
  117. forceDirection: allOptions.edges.smooth.forceDirection === undefined ? false : allOptions.edges.smooth.forceDirection
  118. };
  119. allOptions.edges.smooth = {
  120. enabled: allOptions.edges.smooth.enabled === undefined ? true : allOptions.edges.smooth.enabled,
  121. type:type,
  122. roundness: allOptions.edges.smooth.roundness === undefined ? 0.5 : allOptions.edges.smooth.roundness,
  123. forceDirection: allOptions.edges.smooth.forceDirection === undefined ? false : allOptions.edges.smooth.forceDirection
  124. }
  125. }
  126. }
  127. // force all edges into static smooth curves. Only applies to edges that do not use the global options for smooth.
  128. this.body.emitter.emit('_forceDisableDynamicCurves', type);
  129. }
  130. return allOptions;
  131. }
  132. seededRandom() {
  133. let x = Math.sin(this.randomSeed++) * 10000;
  134. return x - Math.floor(x);
  135. }
  136. positionInitially(nodesArray) {
  137. if (this.options.hierarchical.enabled !== true) {
  138. this.randomSeed = this.initialRandomSeed;
  139. for (let i = 0; i < nodesArray.length; i++) {
  140. let node = nodesArray[i];
  141. let radius = 10 * 0.1 * nodesArray.length + 10;
  142. let angle = 2 * Math.PI * this.seededRandom();
  143. if (node.x === undefined) {
  144. node.x = radius * Math.cos(angle);
  145. }
  146. if (node.y === undefined) {
  147. node.y = radius * Math.sin(angle);
  148. }
  149. }
  150. }
  151. }
  152. /**
  153. * Use KamadaKawai to position nodes. This is quite a heavy algorithm so if there are a lot of nodes we
  154. * cluster them first to reduce the amount.
  155. */
  156. layoutNetwork() {
  157. if (this.options.hierarchical.enabled !== true && this.options.improvedLayout === true) {
  158. // first check if we should KamadaKawai to layout. The threshold is if less than half of the visible
  159. // nodes have predefined positions we use this.
  160. let positionDefined = 0;
  161. for (let i = 0; i < this.body.nodeIndices.length; i++) {
  162. let node = this.body.nodes[this.body.nodeIndices[i]];
  163. if (node.predefinedPosition === true) {
  164. positionDefined += 1;
  165. }
  166. }
  167. // if less than half of the nodes have a predefined position we continue
  168. if (positionDefined < 0.5 * this.body.nodeIndices.length) {
  169. let MAX_LEVELS = 200;
  170. let levels = 0;
  171. let clusterThreshold = 100;
  172. // if there are a lot of nodes, we cluster before we run the algorithm.
  173. if (this.body.nodeIndices.length > clusterThreshold) {
  174. let startLength = this.body.nodeIndices.length;
  175. while (this.body.nodeIndices.length > clusterThreshold) {
  176. levels += 1;
  177. let before = this.body.nodeIndices.length;
  178. // if there are many nodes we do a hubsize cluster
  179. if (levels % 3 === 0) {
  180. this.body.modules.clustering.clusterBridges();
  181. }
  182. else {
  183. this.body.modules.clustering.clusterOutliers();
  184. }
  185. let after = this.body.nodeIndices.length;
  186. if ((before == after && levels % 3 !== 0) || levels > MAX_LEVELS) {
  187. this._declusterAll();
  188. console.info("This network could not be positioned by this version of the improved layout algorithm.");
  189. return;
  190. }
  191. }
  192. // increase the size of the edges
  193. this.body.modules.kamadaKawai.setOptions({springLength: Math.max(150, 2 * startLength)})
  194. }
  195. // position the system for these nodes and edges
  196. this.body.modules.kamadaKawai.solve(this.body.nodeIndices, this.body.edgeIndices, true);
  197. // uncluster all clusters
  198. this._declusterAll();
  199. // reposition all bezier nodes.
  200. this.body.emitter.emit("_repositionBezierNodes");
  201. }
  202. }
  203. }
  204. _declusterAll() {
  205. let clustersPresent = true;
  206. while (clustersPresent === true) {
  207. clustersPresent = false;
  208. for (let i = 0; i < this.body.nodeIndices.length; i++) {
  209. if (this.body.nodes[this.body.nodeIndices[i]].isCluster === true) {
  210. clustersPresent = true;
  211. this.body.modules.clustering.openCluster(this.body.nodeIndices[i], {}, false);
  212. }
  213. }
  214. if (clustersPresent === true) {
  215. this.body.emitter.emit('_dataChanged');
  216. }
  217. }
  218. }
  219. getSeed() {
  220. return this.initialRandomSeed;
  221. }
  222. /**
  223. * This is the main function to layout the nodes in a hierarchical way.
  224. * It checks if the node details are supplied correctly
  225. *
  226. * @private
  227. */
  228. setupHierarchicalLayout() {
  229. if (this.options.hierarchical.enabled === true && this.body.nodeIndices.length > 0) {
  230. // get the size of the largest hubs and check if the user has defined a level for a node.
  231. let node, nodeId;
  232. let definedLevel = false;
  233. let undefinedLevel = false;
  234. this.hierarchicalLevels = {};
  235. this.nodeSpacing = 100;
  236. for (nodeId in this.body.nodes) {
  237. if (this.body.nodes.hasOwnProperty(nodeId)) {
  238. node = this.body.nodes[nodeId];
  239. if (node.options.level !== undefined) {
  240. definedLevel = true;
  241. this.hierarchicalLevels[nodeId] = node.options.level;
  242. }
  243. else {
  244. undefinedLevel = true;
  245. }
  246. }
  247. }
  248. // if the user defined some levels but not all, alert and run without hierarchical layout
  249. if (undefinedLevel === true && definedLevel === true) {
  250. throw new Error('To use the hierarchical layout, nodes require either no predefined levels or levels have to be defined for all nodes.');
  251. return;
  252. }
  253. else {
  254. // setup the system to use hierarchical method.
  255. //this._changeConstants();
  256. // define levels if undefined by the users. Based on hubsize
  257. if (undefinedLevel === true) {
  258. if (this.options.hierarchical.sortMethod === 'hubsize') {
  259. this._determineLevelsByHubsize();
  260. }
  261. else if (this.options.hierarchical.sortMethod === 'directed' || 'direction') {
  262. this._determineLevelsDirected();
  263. }
  264. }
  265. // check the distribution of the nodes per level.
  266. let distribution = this._getDistribution();
  267. // place the nodes on the canvas.
  268. this._placeNodesByHierarchy(distribution);
  269. }
  270. }
  271. }
  272. /**
  273. * This function places the nodes on the canvas based on the hierarchial distribution.
  274. *
  275. * @param {Object} distribution | obtained by the function this._getDistribution()
  276. * @private
  277. */
  278. _placeNodesByHierarchy(distribution) {
  279. let nodeId, node;
  280. this.positionedNodes = {};
  281. // start placing all the level 0 nodes first. Then recursively position their branches.
  282. for (let level in distribution) {
  283. if (distribution.hasOwnProperty(level)) {
  284. for (nodeId in distribution[level].nodes) {
  285. if (distribution[level].nodes.hasOwnProperty(nodeId)) {
  286. node = distribution[level].nodes[nodeId];
  287. if (this.options.hierarchical.direction === 'UD' || this.options.hierarchical.direction === 'DU') {
  288. if (node.x === undefined) {node.x = distribution[level].distance;}
  289. distribution[level].distance = node.x + this.nodeSpacing;
  290. }
  291. else {
  292. if (node.y === undefined) {node.y = distribution[level].distance;}
  293. distribution[level].distance = node.y + this.nodeSpacing;
  294. }
  295. this.positionedNodes[nodeId] = true;
  296. this._placeBranchNodes(node.edges,node.id,distribution,level);
  297. }
  298. }
  299. }
  300. }
  301. }
  302. /**
  303. * This function get the distribution of levels based on hubsize
  304. *
  305. * @returns {Object}
  306. * @private
  307. */
  308. _getDistribution() {
  309. let distribution = {};
  310. let nodeId, node;
  311. // we fix Y because the hierarchy is vertical, we fix X so we do not give a node an x position for a second time.
  312. // the fix of X is removed after the x value has been set.
  313. for (nodeId in this.body.nodes) {
  314. if (this.body.nodes.hasOwnProperty(nodeId)) {
  315. node = this.body.nodes[nodeId];
  316. let level = this.hierarchicalLevels[nodeId] === undefined ? 0 : this.hierarchicalLevels[nodeId];
  317. if (this.options.hierarchical.direction === 'UD' || this.options.hierarchical.direction === 'DU') {
  318. node.y = this.options.hierarchical.levelSeparation * level;
  319. node.options.fixed.y = true;
  320. }
  321. else {
  322. node.x = this.options.hierarchical.levelSeparation * level;
  323. node.options.fixed.x = true;
  324. }
  325. if (distribution[level] === undefined) {
  326. distribution[level] = {amount: 0, nodes: {}, distance: 0};
  327. }
  328. distribution[level].amount += 1;
  329. distribution[level].nodes[nodeId] = node;
  330. }
  331. }
  332. return distribution;
  333. }
  334. /**
  335. * Get the hubsize from all remaining unlevelled nodes.
  336. *
  337. * @returns {number}
  338. * @private
  339. */
  340. _getHubSize() {
  341. let hubSize = 0;
  342. for (let nodeId in this.body.nodes) {
  343. if (this.body.nodes.hasOwnProperty(nodeId)) {
  344. let node = this.body.nodes[nodeId];
  345. if (this.hierarchicalLevels[nodeId] === undefined) {
  346. hubSize = node.edges.length < hubSize ? hubSize : node.edges.length;
  347. }
  348. }
  349. }
  350. return hubSize;
  351. }
  352. /**
  353. * this function allocates nodes in levels based on the recursive branching from the largest hubs.
  354. *
  355. * @param hubsize
  356. * @private
  357. */
  358. _determineLevelsByHubsize() {
  359. let nodeId, node;
  360. let hubSize = 1;
  361. while (hubSize > 0) {
  362. // determine hubs
  363. hubSize = this._getHubSize();
  364. if (hubSize === 0)
  365. break;
  366. for (nodeId in this.body.nodes) {
  367. if (this.body.nodes.hasOwnProperty(nodeId)) {
  368. node = this.body.nodes[nodeId];
  369. if (node.edges.length === hubSize) {
  370. this._setLevelByHubsize(0, node);
  371. }
  372. }
  373. }
  374. }
  375. }
  376. /**
  377. * this function is called recursively to enumerate the barnches of the largest hubs and give each node a level.
  378. *
  379. * @param level
  380. * @param edges
  381. * @param parentId
  382. * @private
  383. */
  384. _setLevelByHubsize(level, node) {
  385. if (this.hierarchicalLevels[node.id] !== undefined)
  386. return;
  387. let childNode;
  388. this.hierarchicalLevels[node.id] = level;
  389. for (let i = 0; i < node.edges.length; i++) {
  390. if (node.edges[i].toId === node.id) {
  391. childNode = node.edges[i].from;
  392. }
  393. else {
  394. childNode = node.edges[i].to;
  395. }
  396. this._setLevelByHubsize(level + 1, childNode);
  397. }
  398. }
  399. /**
  400. * this function allocates nodes in levels based on the direction of the edges
  401. *
  402. * @param hubsize
  403. * @private
  404. */
  405. _determineLevelsDirected() {
  406. let nodeId, node;
  407. let minLevel = 10000;
  408. // set first node to source
  409. for (nodeId in this.body.nodes) {
  410. if (this.body.nodes.hasOwnProperty(nodeId)) {
  411. node = this.body.nodes[nodeId];
  412. this._setLevelDirected(minLevel,node);
  413. }
  414. }
  415. // get the minimum level
  416. for (nodeId in this.body.nodes) {
  417. if (this.body.nodes.hasOwnProperty(nodeId)) {
  418. minLevel = this.hierarchicalLevels[nodeId] < minLevel ? this.hierarchicalLevels[nodeId] : minLevel;
  419. }
  420. }
  421. // subtract the minimum from the set so we have a range starting from 0
  422. for (nodeId in this.body.nodes) {
  423. if (this.body.nodes.hasOwnProperty(nodeId)) {
  424. this.hierarchicalLevels[nodeId] -= minLevel;
  425. }
  426. }
  427. }
  428. /**
  429. * this function is called recursively to enumerate the branched of the first node and give each node a level based on edge direction
  430. *
  431. * @param level
  432. * @param edges
  433. * @param parentId
  434. * @private
  435. */
  436. _setLevelDirected(level, node) {
  437. if (this.hierarchicalLevels[node.id] !== undefined)
  438. return;
  439. let childNode;
  440. this.hierarchicalLevels[node.id] = level;
  441. for (let i = 0; i < node.edges.length; i++) {
  442. if (node.edges[i].toId === node.id) {
  443. childNode = node.edges[i].from;
  444. this._setLevelDirected(level - 1, childNode);
  445. }
  446. else {
  447. childNode = node.edges[i].to;
  448. this._setLevelDirected(level + 1, childNode);
  449. }
  450. }
  451. }
  452. /**
  453. * This is a recursively called function to enumerate the branches from the largest hubs and place the nodes
  454. * on a X position that ensures there will be no overlap.
  455. *
  456. * @param edges
  457. * @param parentId
  458. * @param distribution
  459. * @param parentLevel
  460. * @private
  461. */
  462. _placeBranchNodes(edges, parentId, distribution, parentLevel) {
  463. for (let i = 0; i < edges.length; i++) {
  464. let childNode = undefined;
  465. let parentNode = undefined;
  466. if (edges[i].toId === parentId) {
  467. childNode = edges[i].from;
  468. parentNode = edges[i].to;
  469. }
  470. else {
  471. childNode = edges[i].to;
  472. parentNode = edges[i].from;
  473. }
  474. let childNodeLevel = this.hierarchicalLevels[childNode.id];
  475. if (this.positionedNodes[childNode.id] === undefined) {
  476. // if a node is conneceted to another node on the same level (or higher (means lower level))!, this is not handled here.
  477. if (childNodeLevel > parentLevel) {
  478. if (this.options.hierarchical.direction === 'UD' || this.options.hierarchical.direction === 'DU') {
  479. if (childNode.x === undefined) {
  480. childNode.x = Math.max(distribution[childNodeLevel].distance, parentNode.x);
  481. }
  482. distribution[childNodeLevel].distance = childNode.x + this.nodeSpacing;
  483. this.positionedNodes[childNode.id] = true;
  484. }
  485. else {
  486. if (childNode.y === undefined) {
  487. childNode.y = Math.max(distribution[childNodeLevel].distance, parentNode.y)
  488. }
  489. distribution[childNodeLevel].distance = childNode.y + this.nodeSpacing;
  490. }
  491. this.positionedNodes[childNode.id] = true;
  492. if (childNode.edges.length > 1) {
  493. this._placeBranchNodes(childNode.edges, childNode.id, distribution, childNodeLevel);
  494. }
  495. }
  496. }
  497. }
  498. }
  499. }
  500. export default LayoutEngine;