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.

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