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.

553 lines
18 KiB

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