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.

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