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.

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