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