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.

627 lines
21 KiB

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