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.

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