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.

592 lines
20 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. // place the nodes on the canvas.
  293. this._placeNodesByHierarchy(distribution);
  294. }
  295. }
  296. }
  297. /**
  298. * This function places the nodes on the canvas based on the hierarchial distribution.
  299. *
  300. * @param {Object} distribution | obtained by the function this._getDistribution()
  301. * @private
  302. */
  303. _placeNodesByHierarchy(distribution) {
  304. let nodeId, node;
  305. this.positionedNodes = {};
  306. // start placing all the level 0 nodes first. Then recursively position their branches.
  307. for (let level in distribution) {
  308. if (distribution.hasOwnProperty(level)) {
  309. for (nodeId in distribution[level].nodes) {
  310. if (distribution[level].nodes.hasOwnProperty(nodeId)) {
  311. node = distribution[level].nodes[nodeId];
  312. if (this.options.hierarchical.direction === 'UD' || this.options.hierarchical.direction === 'DU') {
  313. if (node.x === undefined) {node.x = distribution[level].distance;}
  314. distribution[level].distance = node.x + this.nodeSpacing;
  315. }
  316. else {
  317. if (node.y === undefined) {node.y = distribution[level].distance;}
  318. distribution[level].distance = node.y + this.nodeSpacing;
  319. }
  320. this.positionedNodes[nodeId] = true;
  321. this._placeBranchNodes(node.edges,node.id,distribution,level);
  322. }
  323. }
  324. }
  325. }
  326. }
  327. /**
  328. * This function get the distribution of levels based on hubsize
  329. *
  330. * @returns {Object}
  331. * @private
  332. */
  333. _getDistribution() {
  334. let distribution = {};
  335. let nodeId, node;
  336. // 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.
  337. // the fix of X is removed after the x value has been set.
  338. for (nodeId in this.body.nodes) {
  339. if (this.body.nodes.hasOwnProperty(nodeId)) {
  340. node = this.body.nodes[nodeId];
  341. let level = this.hierarchicalLevels[nodeId] === undefined ? 0 : this.hierarchicalLevels[nodeId];
  342. if (this.options.hierarchical.direction === 'UD' || this.options.hierarchical.direction === 'DU') {
  343. node.y = this.options.hierarchical.levelSeparation * level;
  344. node.options.fixed.y = true;
  345. }
  346. else {
  347. node.x = this.options.hierarchical.levelSeparation * level;
  348. node.options.fixed.x = true;
  349. }
  350. if (distribution[level] === undefined) {
  351. distribution[level] = {amount: 0, nodes: {}, distance: 0};
  352. }
  353. distribution[level].amount += 1;
  354. distribution[level].nodes[nodeId] = node;
  355. }
  356. }
  357. return distribution;
  358. }
  359. /**
  360. * Get the hubsize from all remaining unlevelled nodes.
  361. *
  362. * @returns {number}
  363. * @private
  364. */
  365. _getHubSize() {
  366. let hubSize = 0;
  367. for (let nodeId in this.body.nodes) {
  368. if (this.body.nodes.hasOwnProperty(nodeId)) {
  369. let node = this.body.nodes[nodeId];
  370. if (this.hierarchicalLevels[nodeId] === undefined) {
  371. hubSize = node.edges.length < hubSize ? hubSize : node.edges.length;
  372. }
  373. }
  374. }
  375. return hubSize;
  376. }
  377. /**
  378. * this function allocates nodes in levels based on the recursive branching from the largest hubs.
  379. *
  380. * @param hubsize
  381. * @private
  382. */
  383. _determineLevelsByHubsize() {
  384. let nodeId, node;
  385. let hubSize = 1;
  386. while (hubSize > 0) {
  387. // determine hubs
  388. hubSize = this._getHubSize();
  389. if (hubSize === 0)
  390. break;
  391. for (nodeId in this.body.nodes) {
  392. if (this.body.nodes.hasOwnProperty(nodeId)) {
  393. node = this.body.nodes[nodeId];
  394. if (node.edges.length === hubSize) {
  395. this._setLevelByHubsize(0, node);
  396. }
  397. }
  398. }
  399. }
  400. }
  401. /**
  402. * this function is called recursively to enumerate the barnches of the largest hubs and give each node a level.
  403. *
  404. * @param level
  405. * @param edges
  406. * @param parentId
  407. * @private
  408. */
  409. _setLevelByHubsize(level, node) {
  410. if (this.hierarchicalLevels[node.id] !== undefined)
  411. return;
  412. let childNode;
  413. this.hierarchicalLevels[node.id] = level;
  414. for (let i = 0; i < node.edges.length; i++) {
  415. if (node.edges[i].toId === node.id) {
  416. childNode = node.edges[i].from;
  417. }
  418. else {
  419. childNode = node.edges[i].to;
  420. }
  421. this._setLevelByHubsize(level + 1, childNode);
  422. }
  423. }
  424. /**
  425. * this function allocates nodes in levels based on the direction of the edges
  426. *
  427. * @param hubsize
  428. * @private
  429. */
  430. _determineLevelsDirected() {
  431. let nodeId, node;
  432. let minLevel = 10000;
  433. // set first node to source
  434. for (nodeId in this.body.nodes) {
  435. if (this.body.nodes.hasOwnProperty(nodeId)) {
  436. node = this.body.nodes[nodeId];
  437. this._setLevelDirected(minLevel,node);
  438. }
  439. }
  440. // get the minimum level
  441. for (nodeId in this.body.nodes) {
  442. if (this.body.nodes.hasOwnProperty(nodeId)) {
  443. minLevel = this.hierarchicalLevels[nodeId] < minLevel ? this.hierarchicalLevels[nodeId] : minLevel;
  444. }
  445. }
  446. // subtract the minimum from the set so we have a range starting from 0
  447. for (nodeId in this.body.nodes) {
  448. if (this.body.nodes.hasOwnProperty(nodeId)) {
  449. this.hierarchicalLevels[nodeId] -= minLevel;
  450. }
  451. }
  452. }
  453. /**
  454. * this function is called recursively to enumerate the branched of the first node and give each node a level based on edge direction
  455. *
  456. * @param level
  457. * @param edges
  458. * @param parentId
  459. * @private
  460. */
  461. _setLevelDirected(level, node) {
  462. if (this.hierarchicalLevels[node.id] !== undefined)
  463. return;
  464. let childNode;
  465. this.hierarchicalLevels[node.id] = level;
  466. for (let i = 0; i < node.edges.length; i++) {
  467. if (node.edges[i].toId === node.id) {
  468. childNode = node.edges[i].from;
  469. this._setLevelDirected(level - 1, childNode);
  470. }
  471. else {
  472. childNode = node.edges[i].to;
  473. this._setLevelDirected(level + 1, childNode);
  474. }
  475. }
  476. }
  477. /**
  478. * This is a recursively called function to enumerate the branches from the largest hubs and place the nodes
  479. * on a X position that ensures there will be no overlap.
  480. *
  481. * @param edges
  482. * @param parentId
  483. * @param distribution
  484. * @param parentLevel
  485. * @private
  486. */
  487. _placeBranchNodes(edges, parentId, distribution, parentLevel) {
  488. for (let i = 0; i < edges.length; i++) {
  489. let childNode = undefined;
  490. let parentNode = undefined;
  491. if (edges[i].toId === parentId) {
  492. childNode = edges[i].from;
  493. parentNode = edges[i].to;
  494. }
  495. else {
  496. childNode = edges[i].to;
  497. parentNode = edges[i].from;
  498. }
  499. let childNodeLevel = this.hierarchicalLevels[childNode.id];
  500. if (this.positionedNodes[childNode.id] === undefined) {
  501. // if a node is conneceted to another node on the same level (or higher (means lower level))!, this is not handled here.
  502. if (childNodeLevel > parentLevel) {
  503. if (this.options.hierarchical.direction === 'UD' || this.options.hierarchical.direction === 'DU') {
  504. if (childNode.x === undefined) {
  505. childNode.x = Math.max(distribution[childNodeLevel].distance, parentNode.x);
  506. }
  507. distribution[childNodeLevel].distance = childNode.x + this.nodeSpacing;
  508. this.positionedNodes[childNode.id] = true;
  509. }
  510. else {
  511. if (childNode.y === undefined) {
  512. childNode.y = Math.max(distribution[childNodeLevel].distance, parentNode.y)
  513. }
  514. distribution[childNodeLevel].distance = childNode.y + this.nodeSpacing;
  515. }
  516. this.positionedNodes[childNode.id] = true;
  517. if (childNode.edges.length > 1) {
  518. this._placeBranchNodes(childNode.edges, childNode.id, distribution, childNodeLevel);
  519. }
  520. }
  521. }
  522. }
  523. }
  524. }
  525. export default LayoutEngine;