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.

563 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 levels = 0;
  170. let clusterThreshold = 100;
  171. // if there are a lot of nodes, we cluster before we run the algorithm.
  172. if (this.body.nodeIndices.length > clusterThreshold) {
  173. let startLength = this.body.nodeIndices.length;
  174. while (this.body.nodeIndices.length > clusterThreshold) {
  175. levels += 1;
  176. let before = this.body.nodeIndices.length;
  177. // if there are many nodes we do a hubsize cluster
  178. if (levels % 3 === 0) {
  179. this.body.modules.clustering.clusterBridges();
  180. }
  181. else {
  182. this.body.modules.clustering.clusterOutliers();
  183. }
  184. let after = this.body.nodeIndices.length;
  185. if (before == after && levels % 3 !== 0) {
  186. this._declusterAll();
  187. console.info("This network could not be positioned by this version of the improved layout algorithm.");
  188. return;
  189. }
  190. }
  191. // increase the size of the edges
  192. this.body.modules.kamadaKawai.setOptions({springLength: Math.max(150, 2 * startLength)})
  193. }
  194. // position the system for these nodes and edges
  195. this.body.modules.kamadaKawai.solve(this.body.nodeIndices, this.body.edgeIndices, true);
  196. // uncluster all clusters
  197. this._declusterAll();
  198. // reposition all bezier nodes.
  199. this.body.emitter.emit("_repositionBezierNodes");
  200. }
  201. }
  202. }
  203. _declusterAll() {
  204. let clustersPresent = true;
  205. while (clustersPresent === true) {
  206. clustersPresent = false;
  207. for (let i = 0; i < this.body.nodeIndices.length; i++) {
  208. if (this.body.nodes[this.body.nodeIndices[i]].isCluster === true) {
  209. clustersPresent = true;
  210. this.body.modules.clustering.openCluster(this.body.nodeIndices[i], {}, false);
  211. }
  212. }
  213. if (clustersPresent === true) {
  214. this.body.emitter.emit('_dataChanged');
  215. }
  216. }
  217. }
  218. getSeed() {
  219. return this.initialRandomSeed;
  220. }
  221. /**
  222. * This is the main function to layout the nodes in a hierarchical way.
  223. * It checks if the node details are supplied correctly
  224. *
  225. * @private
  226. */
  227. setupHierarchicalLayout() {
  228. if (this.options.hierarchical.enabled === true && this.body.nodeIndices.length > 0) {
  229. // get the size of the largest hubs and check if the user has defined a level for a node.
  230. let node, nodeId;
  231. let definedLevel = false;
  232. let undefinedLevel = false;
  233. this.hierarchicalLevels = {};
  234. this.nodeSpacing = 100;
  235. for (nodeId in this.body.nodes) {
  236. if (this.body.nodes.hasOwnProperty(nodeId)) {
  237. node = this.body.nodes[nodeId];
  238. if (node.options.level !== undefined) {
  239. definedLevel = true;
  240. this.hierarchicalLevels[nodeId] = node.options.level;
  241. }
  242. else {
  243. undefinedLevel = true;
  244. }
  245. }
  246. }
  247. // if the user defined some levels but not all, alert and run without hierarchical layout
  248. if (undefinedLevel === true && definedLevel === true) {
  249. throw new Error('To use the hierarchical layout, nodes require either no predefined levels or levels have to be defined for all nodes.');
  250. return;
  251. }
  252. else {
  253. // setup the system to use hierarchical method.
  254. //this._changeConstants();
  255. // define levels if undefined by the users. Based on hubsize
  256. if (undefinedLevel === true) {
  257. if (this.options.hierarchical.sortMethod === 'hubsize') {
  258. this._determineLevelsByHubsize();
  259. }
  260. else if (this.options.hierarchical.sortMethod === 'directed' || 'direction') {
  261. this._determineLevelsDirected();
  262. }
  263. }
  264. // check the distribution of the nodes per level.
  265. let distribution = this._getDistribution();
  266. // place the nodes on the canvas.
  267. this._placeNodesByHierarchy(distribution);
  268. }
  269. }
  270. }
  271. /**
  272. * This function places the nodes on the canvas based on the hierarchial distribution.
  273. *
  274. * @param {Object} distribution | obtained by the function this._getDistribution()
  275. * @private
  276. */
  277. _placeNodesByHierarchy(distribution) {
  278. let nodeId, node;
  279. this.positionedNodes = {};
  280. // start placing all the level 0 nodes first. Then recursively position their branches.
  281. for (let level in distribution) {
  282. if (distribution.hasOwnProperty(level)) {
  283. for (nodeId in distribution[level].nodes) {
  284. if (distribution[level].nodes.hasOwnProperty(nodeId)) {
  285. node = distribution[level].nodes[nodeId];
  286. if (this.options.hierarchical.direction === 'UD' || this.options.hierarchical.direction === 'DU') {
  287. if (node.x === undefined) {node.x = distribution[level].distance;}
  288. distribution[level].distance = node.x + this.nodeSpacing;
  289. }
  290. else {
  291. if (node.y === undefined) {node.y = distribution[level].distance;}
  292. distribution[level].distance = node.y + this.nodeSpacing;
  293. }
  294. this.positionedNodes[nodeId] = true;
  295. this._placeBranchNodes(node.edges,node.id,distribution,level);
  296. }
  297. }
  298. }
  299. }
  300. }
  301. /**
  302. * This function get the distribution of levels based on hubsize
  303. *
  304. * @returns {Object}
  305. * @private
  306. */
  307. _getDistribution() {
  308. let distribution = {};
  309. let nodeId, node;
  310. // 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.
  311. // the fix of X is removed after the x value has been set.
  312. for (nodeId in this.body.nodes) {
  313. if (this.body.nodes.hasOwnProperty(nodeId)) {
  314. node = this.body.nodes[nodeId];
  315. let level = this.hierarchicalLevels[nodeId] === undefined ? 0 : this.hierarchicalLevels[nodeId];
  316. if (this.options.hierarchical.direction === 'UD' || this.options.hierarchical.direction === 'DU') {
  317. node.y = this.options.hierarchical.levelSeparation * level;
  318. node.options.fixed.y = true;
  319. }
  320. else {
  321. node.x = this.options.hierarchical.levelSeparation * level;
  322. node.options.fixed.x = true;
  323. }
  324. if (distribution[level] === undefined) {
  325. distribution[level] = {amount: 0, nodes: {}, distance: 0};
  326. }
  327. distribution[level].amount += 1;
  328. distribution[level].nodes[nodeId] = node;
  329. }
  330. }
  331. return distribution;
  332. }
  333. /**
  334. * Get the hubsize from all remaining unlevelled nodes.
  335. *
  336. * @returns {number}
  337. * @private
  338. */
  339. _getHubSize() {
  340. let hubSize = 0;
  341. for (let nodeId in this.body.nodes) {
  342. if (this.body.nodes.hasOwnProperty(nodeId)) {
  343. let node = this.body.nodes[nodeId];
  344. if (this.hierarchicalLevels[nodeId] === undefined) {
  345. hubSize = node.edges.length < hubSize ? hubSize : node.edges.length;
  346. }
  347. }
  348. }
  349. return hubSize;
  350. }
  351. /**
  352. * this function allocates nodes in levels based on the recursive branching from the largest hubs.
  353. *
  354. * @param hubsize
  355. * @private
  356. */
  357. _determineLevelsByHubsize() {
  358. let nodeId, node;
  359. let hubSize = 1;
  360. while (hubSize > 0) {
  361. // determine hubs
  362. hubSize = this._getHubSize();
  363. if (hubSize === 0)
  364. break;
  365. for (nodeId in this.body.nodes) {
  366. if (this.body.nodes.hasOwnProperty(nodeId)) {
  367. node = this.body.nodes[nodeId];
  368. if (node.edges.length === hubSize) {
  369. this._setLevelByHubsize(0, node);
  370. }
  371. }
  372. }
  373. }
  374. }
  375. /**
  376. * this function is called recursively to enumerate the barnches of the largest hubs and give each node a level.
  377. *
  378. * @param level
  379. * @param edges
  380. * @param parentId
  381. * @private
  382. */
  383. _setLevelByHubsize(level, node) {
  384. if (this.hierarchicalLevels[node.id] !== undefined)
  385. return;
  386. let childNode;
  387. this.hierarchicalLevels[node.id] = level;
  388. for (let i = 0; i < node.edges.length; i++) {
  389. if (node.edges[i].toId === node.id) {
  390. childNode = node.edges[i].from;
  391. }
  392. else {
  393. childNode = node.edges[i].to;
  394. }
  395. this._setLevelByHubsize(level + 1, childNode);
  396. }
  397. }
  398. /**
  399. * this function allocates nodes in levels based on the direction of the edges
  400. *
  401. * @param hubsize
  402. * @private
  403. */
  404. _determineLevelsDirected() {
  405. let nodeId, node;
  406. let minLevel = 10000;
  407. // set first node to source
  408. for (nodeId in this.body.nodes) {
  409. if (this.body.nodes.hasOwnProperty(nodeId)) {
  410. node = this.body.nodes[nodeId];
  411. this._setLevelDirected(minLevel,node);
  412. }
  413. }
  414. // get the minimum level
  415. for (nodeId in this.body.nodes) {
  416. if (this.body.nodes.hasOwnProperty(nodeId)) {
  417. minLevel = this.hierarchicalLevels[nodeId] < minLevel ? this.hierarchicalLevels[nodeId] : minLevel;
  418. }
  419. }
  420. // subtract the minimum from the set so we have a range starting from 0
  421. for (nodeId in this.body.nodes) {
  422. if (this.body.nodes.hasOwnProperty(nodeId)) {
  423. this.hierarchicalLevels[nodeId] -= minLevel;
  424. }
  425. }
  426. }
  427. /**
  428. * this function is called recursively to enumerate the branched of the first node and give each node a level based on edge direction
  429. *
  430. * @param level
  431. * @param edges
  432. * @param parentId
  433. * @private
  434. */
  435. _setLevelDirected(level, node) {
  436. if (this.hierarchicalLevels[node.id] !== undefined)
  437. return;
  438. let childNode;
  439. this.hierarchicalLevels[node.id] = level;
  440. for (let i = 0; i < node.edges.length; i++) {
  441. if (node.edges[i].toId === node.id) {
  442. childNode = node.edges[i].from;
  443. this._setLevelDirected(level - 1, childNode);
  444. }
  445. else {
  446. childNode = node.edges[i].to;
  447. this._setLevelDirected(level + 1, childNode);
  448. }
  449. }
  450. }
  451. /**
  452. * This is a recursively called function to enumerate the branches from the largest hubs and place the nodes
  453. * on a X position that ensures there will be no overlap.
  454. *
  455. * @param edges
  456. * @param parentId
  457. * @param distribution
  458. * @param parentLevel
  459. * @private
  460. */
  461. _placeBranchNodes(edges, parentId, distribution, parentLevel) {
  462. for (let i = 0; i < edges.length; i++) {
  463. let childNode = undefined;
  464. let parentNode = undefined;
  465. if (edges[i].toId === parentId) {
  466. childNode = edges[i].from;
  467. parentNode = edges[i].to;
  468. }
  469. else {
  470. childNode = edges[i].to;
  471. parentNode = edges[i].from;
  472. }
  473. let childNodeLevel = this.hierarchicalLevels[childNode.id];
  474. if (this.positionedNodes[childNode.id] === undefined) {
  475. // if a node is conneceted to another node on the same level (or higher (means lower level))!, this is not handled here.
  476. if (childNodeLevel > parentLevel) {
  477. if (this.options.hierarchical.direction === 'UD' || this.options.hierarchical.direction === 'DU') {
  478. if (childNode.x === undefined) {
  479. childNode.x = Math.max(distribution[childNodeLevel].distance, parentNode.x);
  480. }
  481. distribution[childNodeLevel].distance = childNode.x + this.nodeSpacing;
  482. this.positionedNodes[childNode.id] = true;
  483. }
  484. else {
  485. if (childNode.y === undefined) {
  486. childNode.y = Math.max(distribution[childNodeLevel].distance, parentNode.y)
  487. }
  488. distribution[childNodeLevel].distance = childNode.y + this.nodeSpacing;
  489. }
  490. this.positionedNodes[childNode.id] = true;
  491. if (childNode.edges.length > 1) {
  492. this._placeBranchNodes(childNode.edges, childNode.id, distribution, childNodeLevel);
  493. }
  494. }
  495. }
  496. }
  497. }
  498. }
  499. export default LayoutEngine;