dagre.js 102 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410
  1. var dagre = dagre || {};
  2. // Dagre graph layout
  3. // https://github.com/dagrejs/dagre
  4. // https://github.com/dagrejs/graphlib
  5. dagre.layout = (graph, options) => {
  6. options = options || {};
  7. // options.time = true;
  8. const time = (name, callback) => {
  9. const start = Date.now();
  10. const result = callback();
  11. const duration = Date.now() - start;
  12. if (options.time) {
  13. /* eslint-disable */
  14. console.log(name + ': ' + duration + 'ms');
  15. /* eslint-enable */
  16. }
  17. return result;
  18. };
  19. // Constructs a new graph from the input graph, which can be used for layout.
  20. // This process copies only whitelisted attributes from the input graph to the
  21. // layout graph. Thus this function serves as a good place to determine what
  22. // attributes can influence layout.
  23. const buildLayoutGraph = (graph) => {
  24. const g = new dagre.Graph({ compound: true });
  25. g.setGraph(Object.assign({}, { ranksep: 50, edgesep: 20, nodesep: 50, rankdir: 'tb' }, graph.graph()));
  26. for (const entry of graph.nodes()) {
  27. const v = entry[0];
  28. const node = entry[1];
  29. g.setNode(v, {
  30. width: node.width || 0,
  31. height: node.height || 0
  32. });
  33. g.setParent(v, graph.parent(v));
  34. }
  35. for (const e of graph.edges().values()) {
  36. const edge = e.label;
  37. g.setEdge(e.v, e.w, {
  38. minlen: edge.minlen || 1,
  39. weight: edge.weight || 1,
  40. width: edge.width || 0,
  41. height: edge.height || 0,
  42. labeloffset: edge.labeloffset || 10,
  43. labelpos: edge.labelpos || 'r'
  44. });
  45. }
  46. return g;
  47. };
  48. const runLayout = (g, time) => {
  49. let uniqueIdCounter = 0;
  50. const uniqueId = (prefix) => {
  51. const id = ++uniqueIdCounter;
  52. return prefix + id;
  53. };
  54. const flat = (list) => {
  55. if (Array.isArray(list) && list.every((item) => !Array.isArray(item))) {
  56. return list;
  57. }
  58. const target = [];
  59. for (const item of list) {
  60. if (!Array.isArray(item)) {
  61. target.push(item);
  62. continue;
  63. }
  64. for (const entry of item) {
  65. target.push(entry);
  66. }
  67. }
  68. return target;
  69. };
  70. // Adds a dummy node to the graph and return v.
  71. const addDummyNode = (g, type, node, name) => {
  72. let v;
  73. do {
  74. v = uniqueId(name);
  75. } while (g.hasNode(v));
  76. node.dummy = type;
  77. g.setNode(v, node);
  78. return v;
  79. };
  80. const asNonCompoundGraph = (g) => {
  81. const graph = new dagre.Graph({});
  82. graph.setGraph(g.graph());
  83. for (const entry of g.nodes()) {
  84. const v = entry[0];
  85. if (g.children(v).length === 0) {
  86. const node = entry[1];
  87. graph.setNode(v, node);
  88. }
  89. }
  90. for (const e of g.edges().values()) {
  91. graph.setEdge(e.v, e.w, e.label);
  92. }
  93. return graph;
  94. };
  95. const maxRank = (g) => {
  96. let rank = Number.NEGATIVE_INFINITY;
  97. for (const node of g.nodes().values()) {
  98. const x = node.rank;
  99. if (x !== undefined && x > rank) {
  100. rank = x;
  101. }
  102. }
  103. return rank === Number.NEGATIVE_INFINITY ? undefined : rank;
  104. };
  105. // Given a DAG with each node assigned 'rank' and 'order' properties, this function will produce a matrix with the ids of each node.
  106. const buildLayerMatrix = (g) => {
  107. const rank = maxRank(g);
  108. const length = rank === undefined ? 0 : rank + 1;
  109. const layering = Array.from(new Array(length), () => []);
  110. for (const entry of g.nodes()) {
  111. const node = entry[1];
  112. const rank = node.rank;
  113. if (rank !== undefined) {
  114. layering[rank][node.order] = entry[0];
  115. }
  116. }
  117. return layering;
  118. };
  119. // This idea comes from the Gansner paper: to account for edge labels in our layout we split each rank in half by doubling minlen and halving ranksep.
  120. // Then we can place labels at these mid-points between nodes.
  121. // We also add some minimal padding to the width to push the label for the edge away from the edge itself a bit.
  122. const makeSpaceForEdgeLabels = (g) => {
  123. const graph = g.graph();
  124. graph.ranksep /= 2;
  125. for (const e of g.edges().values()) {
  126. const edge = e.label;
  127. edge.minlen *= 2;
  128. if (edge.labelpos.toLowerCase() !== 'c') {
  129. if (graph.rankdir === 'TB' || graph.rankdir === 'BT') {
  130. edge.width += edge.labeloffset;
  131. }
  132. else {
  133. edge.height += edge.labeloffset;
  134. }
  135. }
  136. }
  137. };
  138. /*
  139. * A helper that preforms a pre- or post-order traversal on the input graph
  140. * and returns the nodes in the order they were visited. If the graph is
  141. * undirected then this algorithm will navigate using neighbors. If the graph
  142. * is directed then this algorithm will navigate using successors.
  143. *
  144. * Order must be one of 'pre' or 'post'.
  145. */
  146. const dfs = (g, vs, order) => {
  147. const doDfs = (g, v, postorder, visited, navigation, acc) => {
  148. if (!visited.has(v)) {
  149. visited.add(v);
  150. if (!postorder) {
  151. acc.push(v);
  152. }
  153. for (const w of navigation(v)) {
  154. doDfs(g, w, postorder, visited, navigation, acc);
  155. }
  156. if (postorder) {
  157. acc.push(v);
  158. }
  159. }
  160. };
  161. if (!Array.isArray(vs)) {
  162. vs = [ vs ];
  163. }
  164. const navigation = (g.isDirected() ? g.successors : g.neighbors).bind(g);
  165. const acc = [];
  166. const visited = new Set();
  167. for (const v of vs) {
  168. if (!g.hasNode(v)) {
  169. throw new Error('Graph does not have node: ' + v);
  170. }
  171. doDfs(g, v, order === 'post', visited, navigation, acc);
  172. }
  173. return acc;
  174. };
  175. const postorder = (g, vs) => {
  176. return dfs(g, vs, 'post');
  177. };
  178. const preorder = (g, vs) => {
  179. return dfs(g, vs, 'pre');
  180. };
  181. const removeSelfEdges = (g) => {
  182. for (const e of g.edges().values()) {
  183. if (e.v === e.w) {
  184. const node = g.node(e.v);
  185. if (!node.selfEdges) {
  186. node.selfEdges = [];
  187. }
  188. node.selfEdges.push({ e: e, label: e.label });
  189. g.removeEdge(e);
  190. }
  191. }
  192. };
  193. const acyclic_run = (g) => {
  194. const dfsFAS = (g) => {
  195. const fas = [];
  196. const stack = new Set();
  197. const visited = new Set();
  198. const dfs = (v) => {
  199. if (!visited.has(v)) {
  200. visited.add(v);
  201. stack.add(v);
  202. for (const e of g.outEdges(v)) {
  203. if (stack.has(e.w)) {
  204. fas.push(e);
  205. }
  206. else {
  207. dfs(e.w);
  208. }
  209. }
  210. stack.delete(v);
  211. }
  212. };
  213. for (const v of g.nodes().keys()) {
  214. dfs(v);
  215. }
  216. return fas;
  217. };
  218. for (const e of dfsFAS(g)) {
  219. const label = e.label;
  220. g.removeEdge(e);
  221. label.forwardName = e.name;
  222. label.reversed = true;
  223. g.setEdge(e.w, e.v, label, uniqueId('rev'));
  224. }
  225. };
  226. const acyclic_undo = (g) => {
  227. for (const e of g.edges().values()) {
  228. const edge = e.label;
  229. if (edge.reversed) {
  230. edge.points.reverse();
  231. g.removeEdge(e);
  232. const forwardName = edge.forwardName;
  233. delete edge.reversed;
  234. delete edge.forwardName;
  235. g.setEdge(e.w, e.v, edge, forwardName);
  236. }
  237. }
  238. };
  239. // Returns the amount of slack for the given edge. The slack is defined as the
  240. // difference between the length of the edge and its minimum length.
  241. const slack = (g, e) => {
  242. return g.node(e.w).rank - g.node(e.v).rank - e.label.minlen;
  243. };
  244. /*
  245. * Assigns a rank to each node in the input graph that respects the 'minlen'
  246. * constraint specified on edges between nodes.
  247. *
  248. * This basic structure is derived from Gansner, et al., 'A Technique for
  249. * Drawing Directed Graphs.'
  250. *
  251. * Pre-conditions:
  252. *
  253. * 1. Graph must be a connected DAG
  254. * 2. Graph nodes must be objects
  255. * 3. Graph edges must have 'weight' and 'minlen' attributes
  256. *
  257. * Post-conditions:
  258. *
  259. * 1. Graph nodes will have a 'rank' attribute based on the results of the
  260. * algorithm. Ranks can start at any index (including negative), we'll
  261. * fix them up later.
  262. */
  263. const rank = (g) => {
  264. /*
  265. * Constructs a spanning tree with tight edges and adjusted the input node's
  266. * ranks to achieve this. A tight edge is one that is has a length that matches
  267. * its 'minlen' attribute.
  268. *
  269. * The basic structure for this function is derived from Gansner, et al., 'A
  270. * Technique for Drawing Directed Graphs.'
  271. *
  272. * Pre-conditions:
  273. *
  274. * 1. Graph must be a DAG.
  275. * 2. Graph must be connected.
  276. * 3. Graph must have at least one node.
  277. * 5. Graph nodes must have been previously assigned a 'rank' property that
  278. * respects the 'minlen' property of incident edges.
  279. * 6. Graph edges must have a 'minlen' property.
  280. *
  281. * Post-conditions:
  282. *
  283. * - Graph nodes will have their rank adjusted to ensure that all edges are
  284. * tight.
  285. *
  286. * Returns a tree (undirected graph) that is constructed using only 'tight'
  287. * edges.
  288. */
  289. const feasibleTree = (g) => {
  290. const t = new dagre.Graph({ directed: false });
  291. // Choose arbitrary node from which to start our tree
  292. const start = g.nodes().keys().next().value;
  293. const size = g.nodes().size;
  294. t.setNode(start, {});
  295. // Finds the edge with the smallest slack that is incident on tree and returns it.
  296. const findMinSlackEdge = (t, g) => {
  297. let minKey = Number.POSITIVE_INFINITY;
  298. let minValue = undefined;
  299. for (const e of g.edges().values()) {
  300. if (t.hasNode(e.v) !== t.hasNode(e.w)) {
  301. const key = slack(g, e);
  302. if (key < minKey) {
  303. minKey = key;
  304. minValue = e;
  305. }
  306. }
  307. }
  308. return minValue;
  309. };
  310. // Finds a maximal tree of tight edges and returns the number of nodes in the tree.
  311. const tightTree = (t, g) => {
  312. const stack = Array.from(t.nodes().keys()).reverse();
  313. while (stack.length > 0) {
  314. const v = stack.pop();
  315. for (const e of g.nodeEdges(v)) {
  316. const edgeV = e.v;
  317. const w = (v === edgeV) ? e.w : edgeV;
  318. if (!t.hasNode(w) && !slack(g, e)) {
  319. t.setNode(w, {});
  320. t.setEdge(v, w, {});
  321. stack.push(w);
  322. }
  323. }
  324. }
  325. return t.nodes().size;
  326. };
  327. while (tightTree(t, g) < size) {
  328. const edge = findMinSlackEdge(t, g);
  329. const delta = t.hasNode(edge.v) ? slack(g, edge) : -slack(g, edge);
  330. for (const v of t.nodes().keys()) {
  331. g.node(v).rank += delta;
  332. }
  333. }
  334. return t;
  335. };
  336. /*
  337. * Initializes ranks for the input graph using the longest path algorithm. This
  338. * algorithm scales well and is fast in practice, it yields rather poor
  339. * solutions. Nodes are pushed to the lowest layer possible, leaving the bottom
  340. * ranks wide and leaving edges longer than necessary. However, due to its
  341. * speed, this algorithm is good for getting an initial ranking that can be fed
  342. * into other algorithms.
  343. *
  344. * This algorithm does not normalize layers because it will be used by other
  345. * algorithms in most cases. If using this algorithm directly, be sure to
  346. * run normalize at the end.
  347. *
  348. * Pre-conditions:
  349. *
  350. * 1. Input graph is a DAG.
  351. * 2. Input graph node labels can be assigned properties.
  352. *
  353. * Post-conditions:
  354. *
  355. * 1. Each node will be assign an (unnormalized) 'rank' property.
  356. */
  357. const longestPath = (g) => {
  358. const visited = new Set();
  359. const dfs = (v) => {
  360. const node = g.node(v);
  361. if (visited.has(v)) {
  362. return node.rank;
  363. }
  364. visited.add(v);
  365. let rank = Number.MAX_SAFE_INTEGER;
  366. for (const e of g.outEdges(v)) {
  367. const x = dfs(e.w) - e.label.minlen;
  368. if (x < rank) {
  369. rank = x;
  370. }
  371. }
  372. if (rank === Number.MAX_SAFE_INTEGER) {
  373. rank = 0;
  374. }
  375. node.rank = rank;
  376. return rank;
  377. };
  378. for (const v of g.sources()) {
  379. dfs(v);
  380. }
  381. };
  382. /*
  383. * The network simplex algorithm assigns ranks to each node in the input graph
  384. * and iteratively improves the ranking to reduce the length of edges.
  385. *
  386. * Preconditions:
  387. *
  388. * 1. The input graph must be a DAG.
  389. * 2. All nodes in the graph must have an object value.
  390. * 3. All edges in the graph must have 'minlen' and 'weight' attributes.
  391. *
  392. * Postconditions:
  393. *
  394. * 1. All nodes in the graph will have an assigned 'rank' attribute that has
  395. * been optimized by the network simplex algorithm. Ranks start at 0.
  396. *
  397. *
  398. * A rough sketch of the algorithm is as follows:
  399. *
  400. * 1. Assign initial ranks to each node. We use the longest path algorithm,
  401. * which assigns ranks to the lowest position possible. In general this
  402. * leads to very wide bottom ranks and unnecessarily long edges.
  403. * 2. Construct a feasible tight tree. A tight tree is one such that all
  404. * edges in the tree have no slack (difference between length of edge
  405. * and minlen for the edge). This by itself greatly improves the assigned
  406. * rankings by shorting edges.
  407. * 3. Iteratively find edges that have negative cut values. Generally a
  408. * negative cut value indicates that the edge could be removed and a new
  409. * tree edge could be added to produce a more compact graph.
  410. *
  411. * Much of the algorithms here are derived from Gansner, et al., 'A Technique
  412. * for Drawing Directed Graphs.' The structure of the file roughly follows the
  413. * structure of the overall algorithm.
  414. */
  415. const networkSimplex = (g) => {
  416. /*
  417. * Returns a new graph with only simple edges. Handles aggregation of data
  418. * associated with multi-edges.
  419. */
  420. const simplify = (g) => {
  421. const graph = new dagre.Graph();
  422. graph.setGraph(g.graph());
  423. for (const entry of g.nodes()) {
  424. graph.setNode(entry[0], entry[1]);
  425. }
  426. for (const e of g.edges().values()) {
  427. const simpleEdge = graph.edge(e.v, e.w);
  428. const simpleLabel = simpleEdge ? simpleEdge.label : { weight: 0, minlen: 1 };
  429. const label = e.label;
  430. graph.setEdge(e.v, e.w, {
  431. weight: simpleLabel.weight + label.weight,
  432. minlen: Math.max(simpleLabel.minlen, label.minlen)
  433. });
  434. }
  435. return graph;
  436. };
  437. const initLowLimValues = (tree, root) => {
  438. root = tree.nodes().keys().next().value;
  439. const dfsAssignLowLim = (tree, visited, nextLim, v, parent) => {
  440. const low = nextLim;
  441. const label = tree.node(v);
  442. visited.add(v);
  443. for (const w of tree.neighbors(v)) {
  444. if (!visited.has(w)) {
  445. nextLim = dfsAssignLowLim(tree, visited, nextLim, w, v);
  446. }
  447. }
  448. label.low = low;
  449. label.lim = nextLim++;
  450. if (parent) {
  451. label.parent = parent;
  452. }
  453. else {
  454. // TODO should be able to remove this when we incrementally update low lim
  455. delete label.parent;
  456. }
  457. return nextLim;
  458. };
  459. const visited = new Set();
  460. dfsAssignLowLim(tree, visited, 1, root);
  461. };
  462. // Initializes cut values for all edges in the tree.
  463. const initCutValues = (t, g) => {
  464. // Given the tight tree, its graph, and a child in the graph calculate and
  465. // return the cut value for the edge between the child and its parent.
  466. const calcCutValue = (t, g, child) => {
  467. const childLab = t.node(child);
  468. const parent = childLab.parent;
  469. // The graph's view of the tree edge we're inspecting
  470. const edge = g.edge(child, parent);
  471. // True if the child is on the tail end of the edge in the directed graph
  472. const childIsTail = edge ? true : false;
  473. // The accumulated cut value for the edge between this node and its parent
  474. const graphEdge = edge ? edge.label : g.edge(parent, child).label;
  475. let cutValue = graphEdge.weight;
  476. for (const e of g.nodeEdges(child)) {
  477. const isOutEdge = e.v === child;
  478. const other = isOutEdge ? e.w : e.v;
  479. if (other !== parent) {
  480. const pointsToHead = isOutEdge === childIsTail;
  481. const otherWeight = e.label.weight;
  482. cutValue += pointsToHead ? otherWeight : -otherWeight;
  483. const edge = t.edge(child, other);
  484. if (edge) {
  485. const otherCutValue = edge.label.cutvalue;
  486. cutValue += pointsToHead ? -otherCutValue : otherCutValue;
  487. }
  488. }
  489. }
  490. return cutValue;
  491. };
  492. const assignCutValue = (t, g, child) => {
  493. const childLab = t.node(child);
  494. const parent = childLab.parent;
  495. t.edge(child, parent).label.cutvalue = calcCutValue(t, g, child);
  496. };
  497. let vs = postorder(t, Array.from(t.nodes().keys()));
  498. vs = vs.slice(0, vs.length - 1);
  499. for (const v of vs) {
  500. assignCutValue(t, g, v);
  501. }
  502. };
  503. const leaveEdge = (tree) => {
  504. return Array.from(tree.edges().values()).find((e) => e.label.cutvalue < 0);
  505. };
  506. const enterEdge = (t, g, edge) => {
  507. let v = edge.v;
  508. let w = edge.w;
  509. // For the rest of this function we assume that v is the tail and w is the
  510. // head, so if we don't have this edge in the graph we should flip it to
  511. // match the correct orientation.
  512. if (!g.edge(v, w)) {
  513. v = edge.w;
  514. w = edge.v;
  515. }
  516. const vLabel = t.node(v);
  517. const wLabel = t.node(w);
  518. let tailLabel = vLabel;
  519. let flip = false;
  520. // If the root is in the tail of the edge then we need to flip the logic that
  521. // checks for the head and tail nodes in the candidates function below.
  522. if (vLabel.lim > wLabel.lim) {
  523. tailLabel = wLabel;
  524. flip = true;
  525. }
  526. // Returns true if the specified node is descendant of the root node per the
  527. // assigned low and lim attributes in the tree.
  528. const isDescendant = (tree, vLabel, rootLabel) => {
  529. return rootLabel.low <= vLabel.lim && vLabel.lim <= rootLabel.lim;
  530. };
  531. const candidates = Array.from(g.edges().values()).filter((edge) => flip === isDescendant(t, t.node(edge.v), tailLabel) && flip !== isDescendant(t, t.node(edge.w), tailLabel));
  532. let minKey = Number.POSITIVE_INFINITY;
  533. let minValue = undefined;
  534. for (const edge of candidates) {
  535. const key = slack(g, edge);
  536. if (key < minKey) {
  537. minKey = key;
  538. minValue = edge;
  539. }
  540. }
  541. return minValue;
  542. };
  543. const exchangeEdges = (t, g, e, f) => {
  544. t.removeEdge(e);
  545. t.setEdge(f.v, f.w, {});
  546. initLowLimValues(t);
  547. initCutValues(t, g);
  548. const updateRanks = (t, g) => {
  549. const root = Array.from(t.nodes().keys()).find((v) => !g.node(v).parent);
  550. let vs = preorder(t, root);
  551. vs = vs.slice(1);
  552. for (const v of vs) {
  553. const parent = t.node(v).parent;
  554. let edge = g.edge(v, parent);
  555. let flipped = false;
  556. if (!edge) {
  557. edge = g.edge(parent, v);
  558. flipped = true;
  559. }
  560. g.node(v).rank = g.node(parent).rank + (flipped ? edge.label.minlen : -edge.label.minlen);
  561. }
  562. };
  563. updateRanks(t, g);
  564. };
  565. g = simplify(g);
  566. longestPath(g);
  567. const tree = feasibleTree(g);
  568. initLowLimValues(tree);
  569. initCutValues(tree, g);
  570. let e;
  571. let f;
  572. while ((e = leaveEdge(tree))) {
  573. f = enterEdge(tree, g, e);
  574. exchangeEdges(tree, g, e, f);
  575. }
  576. };
  577. switch(g.graph().ranker) {
  578. case 'tight-tree': {
  579. longestPath(g);
  580. feasibleTree(g);
  581. break;
  582. }
  583. case 'longest-path': {
  584. longestPath(g);
  585. break;
  586. }
  587. default: {
  588. networkSimplex(g);
  589. break;
  590. }
  591. }
  592. };
  593. // Creates temporary dummy nodes that capture the rank in which each edge's label is going to, if it has one of non-zero width and height.
  594. // We do this so that we can safely remove empty ranks while preserving balance for the label's position.
  595. const injectEdgeLabelProxies = (g) => {
  596. for (const e of g.edges().values()) {
  597. const edge = e.label;
  598. if (edge.width && edge.height) {
  599. const v = g.node(e.v);
  600. const w = g.node(e.w);
  601. const label = { rank: (w.rank - v.rank) / 2 + v.rank, e: e };
  602. addDummyNode(g, 'edge-proxy', label, '_ep');
  603. }
  604. }
  605. };
  606. const removeEmptyRanks = (g) => {
  607. // Ranks may not start at 0, so we need to offset them
  608. if (g.nodes().size > 0) {
  609. let minRank = Number.POSITIVE_INFINITY;
  610. let maxRank = Number.NEGATIVE_INFINITY;
  611. for (const node of g.nodes().values()) {
  612. if (node.rank !== undefined) {
  613. if (node.rank < minRank) {
  614. minRank = node.rank;
  615. }
  616. if (node.rank > maxRank) {
  617. maxRank = node.rank;
  618. }
  619. }
  620. }
  621. const size = maxRank - minRank;
  622. if (size > 0) {
  623. const layers = new Array(size);
  624. for (const entry of g.nodes()) {
  625. const node = entry[1];
  626. if (node.rank !== undefined) {
  627. const rank = node.rank - minRank;
  628. if (!layers[rank]) {
  629. layers[rank] = [];
  630. }
  631. layers[rank].push(entry[0]);
  632. }
  633. }
  634. let delta = 0;
  635. const nodeRankFactor = g.graph().nodeRankFactor;
  636. for (let i = 0; i < layers.length; i++) {
  637. const vs = layers[i];
  638. if (vs === undefined && i % nodeRankFactor !== 0) {
  639. --delta;
  640. }
  641. else if (delta && vs) {
  642. for (const v of vs) {
  643. g.node(v).rank += delta;
  644. }
  645. }
  646. }
  647. }
  648. }
  649. };
  650. /*
  651. * A nesting graph creates dummy nodes for the tops and bottoms of subgraphs,
  652. * adds appropriate edges to ensure that all cluster nodes are placed between
  653. * these boundries, and ensures that the graph is connected.
  654. *
  655. * In addition we ensure, through the use of the minlen property, that nodes
  656. * and subgraph border nodes to not end up on the same rank.
  657. *
  658. * Preconditions:
  659. *
  660. * 1. Input graph is a DAG
  661. * 2. Nodes in the input graph has a minlen attribute
  662. *
  663. * Postconditions:
  664. *
  665. * 1. Input graph is connected.
  666. * 2. Dummy nodes are added for the tops and bottoms of subgraphs.
  667. * 3. The minlen attribute for nodes is adjusted to ensure nodes do not
  668. * get placed on the same rank as subgraph border nodes.
  669. *
  670. * The nesting graph idea comes from Sander, 'Layout of Compound Directed
  671. * Graphs.'
  672. */
  673. const nestingGraph_run = (g) => {
  674. const root = addDummyNode(g, 'root', {}, '_root');
  675. const treeDepths = (g) => {
  676. const depths = {};
  677. const dfs = (v, depth) => {
  678. const children = g.children(v);
  679. if (children && children.length > 0) {
  680. for (const child of children) {
  681. dfs(child, depth + 1);
  682. }
  683. }
  684. depths[v] = depth;
  685. };
  686. for (const v of g.children()) {
  687. dfs(v, 1);
  688. }
  689. return depths;
  690. };
  691. const dfs = (g, root, nodeSep, weight, height, depths, v) => {
  692. const children = g.children(v);
  693. if (!children.length) {
  694. if (v !== root) {
  695. g.setEdge(root, v, { weight: 0, minlen: nodeSep });
  696. }
  697. return;
  698. }
  699. const top = addDummyNode(g, 'border', { width: 0, height: 0 }, '_bt');
  700. const bottom = addDummyNode(g, 'border', { width: 0, height: 0 }, '_bb');
  701. const label = g.node(v);
  702. g.setParent(top, v);
  703. label.borderTop = top;
  704. g.setParent(bottom, v);
  705. label.borderBottom = bottom;
  706. for (const child of children) {
  707. dfs(g, root, nodeSep, weight, height, depths, child);
  708. const childNode = g.node(child);
  709. const childTop = childNode.borderTop ? childNode.borderTop : child;
  710. const childBottom = childNode.borderBottom ? childNode.borderBottom : child;
  711. const thisWeight = childNode.borderTop ? weight : 2 * weight;
  712. const minlen = childTop !== childBottom ? 1 : height - depths[v] + 1;
  713. g.setEdge(top, childTop, { weight: thisWeight, minlen: minlen, nestingEdge: true });
  714. g.setEdge(childBottom, bottom, { weight: thisWeight, minlen: minlen, nestingEdge: true });
  715. }
  716. if (!g.parent(v)) {
  717. g.setEdge(root, top, { weight: 0, minlen: height + depths[v] });
  718. }
  719. };
  720. const depths = treeDepths(g);
  721. const height = Math.max(...Object.values(depths)) - 1; // Note: depths is an Object not an array
  722. const nodeSep = 2 * height + 1;
  723. g.graph().nestingRoot = root;
  724. // Multiply minlen by nodeSep to align nodes on non-border ranks.
  725. for (const e of g.edges().values()) {
  726. e.label.minlen *= nodeSep;
  727. }
  728. // Calculate a weight that is sufficient to keep subgraphs vertically compact
  729. const sumWeights = (g) => {
  730. return Array.from(g.edges().values()).reduce((acc, e) => acc + e.label.weight, 0);
  731. };
  732. const weight = sumWeights(g) + 1;
  733. // Create border nodes and link them up
  734. for (const child of g.children()) {
  735. dfs(g, root, nodeSep, weight, height, depths, child);
  736. }
  737. // Save the multiplier for node layers for later removal of empty border layers.
  738. g.graph().nodeRankFactor = nodeSep;
  739. };
  740. const nestingGraph_cleanup = (g) => {
  741. const graphLabel = g.graph();
  742. g.removeNode(graphLabel.nestingRoot);
  743. delete graphLabel.nestingRoot;
  744. for (const e of g.edges().values()) {
  745. if (e.label.nestingEdge) {
  746. g.removeEdge(e);
  747. }
  748. }
  749. };
  750. // Adjusts the ranks for all nodes in the graph such that all nodes v have rank(v) >= 0 and at least one node w has rank(w) = 0.
  751. const normalizeRanks = (g) => {
  752. let min = Number.POSITIVE_INFINITY;
  753. for (const node of g.nodes().values()) {
  754. const rank = node.rank;
  755. if (rank !== undefined && rank < min) {
  756. min = rank;
  757. }
  758. }
  759. for (const node of g.nodes().values()) {
  760. if (node.rank !== undefined) {
  761. node.rank -= min;
  762. }
  763. }
  764. };
  765. const assignRankMinMax = (g) => {
  766. let maxRank = 0;
  767. for (const node of g.nodes().values()) {
  768. if (node.borderTop) {
  769. node.minRank = g.node(node.borderTop).rank;
  770. node.maxRank = g.node(node.borderBottom).rank;
  771. maxRank = Math.max(maxRank, node.maxRank);
  772. }
  773. }
  774. g.graph().maxRank = maxRank;
  775. };
  776. // Breaks any long edges in the graph into short segments that span 1 layer each.
  777. // This operation is undoable with the denormalize function.
  778. //
  779. // Pre-conditions:
  780. // 1. The input graph is a DAG.
  781. // 2. Each node in the graph has a 'rank' property.
  782. //
  783. // Post-condition:
  784. // 1. All edges in the graph have a length of 1.
  785. // 2. Dummy nodes are added where edges have been split into segments.
  786. // 3. The graph is augmented with a 'dummyChains' attribute which contains
  787. // the first dummy in each chain of dummy nodes produced.
  788. const normalize = (g) => {
  789. g.graph().dummyChains = [];
  790. for (const e of g.edges().values()) {
  791. let v = e.v;
  792. let vRank = g.node(v).rank;
  793. const w = e.w;
  794. const wRank = g.node(w).rank;
  795. const name = e.name;
  796. const edgeLabel = e.label;
  797. const labelRank = edgeLabel.labelRank;
  798. if (wRank !== vRank + 1) {
  799. g.removeEdge(e);
  800. let dummy;
  801. let attrs;
  802. let first = true;
  803. vRank++;
  804. while (vRank < wRank) {
  805. edgeLabel.points = [];
  806. attrs = {
  807. width: 0, height: 0,
  808. edgeLabel: edgeLabel,
  809. edgeObj: e,
  810. rank: vRank
  811. };
  812. dummy = addDummyNode(g, 'edge', attrs, '_d');
  813. if (vRank === labelRank) {
  814. attrs.width = edgeLabel.width;
  815. attrs.height = edgeLabel.height;
  816. attrs.dummy = 'edge-label';
  817. attrs.labelpos = edgeLabel.labelpos;
  818. }
  819. g.setEdge(v, dummy, { weight: edgeLabel.weight }, name);
  820. if (first) {
  821. g.graph().dummyChains.push(dummy);
  822. first = false;
  823. }
  824. v = dummy;
  825. vRank++;
  826. }
  827. g.setEdge(v, w, { weight: edgeLabel.weight }, name);
  828. }
  829. }
  830. };
  831. const denormalize = (g) => {
  832. for (let v of g.graph().dummyChains) {
  833. let node = g.node(v);
  834. const origLabel = node.edgeLabel;
  835. let w;
  836. const e = node.edgeObj;
  837. g.setEdge(e.v, e.w, origLabel, e.name);
  838. while (node.dummy) {
  839. w = g.successors(v)[0];
  840. g.removeNode(v);
  841. origLabel.points.push({ x: node.x, y: node.y });
  842. if (node.dummy === 'edge-label') {
  843. origLabel.x = node.x;
  844. origLabel.y = node.y;
  845. origLabel.width = node.width;
  846. origLabel.height = node.height;
  847. }
  848. v = w;
  849. node = g.node(v);
  850. }
  851. }
  852. };
  853. const removeEdgeLabelProxies = (g) => {
  854. for (const entry of g.nodes()) {
  855. const node = entry[1];
  856. if (node.dummy === 'edge-proxy') {
  857. node.e.label.labelRank = node.rank;
  858. g.removeNode(entry[0]);
  859. }
  860. }
  861. };
  862. const parentDummyChains = (g) => {
  863. // Find a path from v to w through the lowest common ancestor (LCA). Return the full path and the LCA.
  864. const findPath = (g, postorderNums, v, w) => {
  865. const vPath = [];
  866. const wPath = [];
  867. const low = Math.min(postorderNums[v].low, postorderNums[w].low);
  868. const lim = Math.max(postorderNums[v].lim, postorderNums[w].lim);
  869. // Traverse up from v to find the LCA
  870. let parent = v;
  871. do {
  872. parent = g.parent(parent);
  873. vPath.push(parent);
  874. }
  875. while (parent && (postorderNums[parent].low > low || lim > postorderNums[parent].lim));
  876. const lca = parent;
  877. // Traverse from w to LCA
  878. parent = w;
  879. while ((parent = g.parent(parent)) !== lca) {
  880. wPath.push(parent);
  881. }
  882. return { path: vPath.concat(wPath.reverse()), lca: lca };
  883. };
  884. const postorder = (g) => {
  885. const result = {};
  886. let lim = 0;
  887. const dfs = (v) => {
  888. const low = lim;
  889. for (const u of g.children(v)) {
  890. dfs(u);
  891. }
  892. result[v] = { low: low, lim: lim++ };
  893. };
  894. for (const v of g.children()) {
  895. dfs(v);
  896. }
  897. return result;
  898. };
  899. const postorderNums = postorder(g);
  900. for (let v of g.graph().dummyChains || []) {
  901. let node = g.node(v);
  902. const edgeObj = node.edgeObj;
  903. const pathData = findPath(g, postorderNums, edgeObj.v, edgeObj.w);
  904. const path = pathData.path;
  905. const lca = pathData.lca;
  906. let pathIdx = 0;
  907. let pathV = path[pathIdx];
  908. let ascending = true;
  909. while (v !== edgeObj.w) {
  910. node = g.node(v);
  911. if (ascending) {
  912. while ((pathV = path[pathIdx]) !== lca && g.node(pathV).maxRank < node.rank) {
  913. pathIdx++;
  914. }
  915. if (pathV === lca) {
  916. ascending = false;
  917. }
  918. }
  919. if (!ascending) {
  920. while (pathIdx < path.length - 1 && g.node(pathV = path[pathIdx + 1]).minRank <= node.rank) {
  921. pathIdx++;
  922. }
  923. pathV = path[pathIdx];
  924. }
  925. g.setParent(v, pathV);
  926. v = g.successors(v)[0];
  927. }
  928. }
  929. };
  930. const addBorderSegments = (g) => {
  931. const addBorderNode = (g, prop, prefix, sg, sgNode, rank) => {
  932. const label = { width: 0, height: 0, rank: rank, borderType: prop };
  933. const prev = sgNode[prop][rank - 1];
  934. const curr = addDummyNode(g, 'border', label, prefix);
  935. sgNode[prop][rank] = curr;
  936. g.setParent(curr, sg);
  937. if (prev) {
  938. g.setEdge(prev, curr, { weight: 1 });
  939. }
  940. };
  941. const dfs = (v) => {
  942. const children = g.children(v);
  943. const node = g.node(v);
  944. if (children.length) {
  945. for (const v of children) {
  946. dfs(v);
  947. }
  948. }
  949. if ('minRank' in node) {
  950. node.borderLeft = [];
  951. node.borderRight = [];
  952. for (let rank = node.minRank, maxRank = node.maxRank + 1; rank < maxRank; ++rank) {
  953. addBorderNode(g, 'borderLeft', '_bl', v, node, rank);
  954. addBorderNode(g, 'borderRight', '_br', v, node, rank);
  955. }
  956. }
  957. };
  958. for (const v of g.children()) {
  959. dfs(v);
  960. }
  961. };
  962. /*
  963. * Applies heuristics to minimize edge crossings in the graph and sets the best
  964. * order solution as an order attribute on each node.
  965. *
  966. * Pre-conditions:
  967. *
  968. * 1. Graph must be DAG
  969. * 2. Graph nodes must be objects with a 'rank' attribute
  970. * 3. Graph edges must have the 'weight' attribute
  971. *
  972. * Post-conditions:
  973. *
  974. * 1. Graph nodes will have an 'order' attribute based on the results of the algorithm.
  975. */
  976. const order = (g) => {
  977. const sortSubgraph = (g, v, cg, biasRight) => {
  978. /*
  979. * Given a list of entries of the form {v, barycenter, weight} and a
  980. * constraint graph this function will resolve any conflicts between the
  981. * constraint graph and the barycenters for the entries. If the barycenters for
  982. * an entry would violate a constraint in the constraint graph then we coalesce
  983. * the nodes in the conflict into a new node that respects the contraint and
  984. * aggregates barycenter and weight information.
  985. *
  986. * This implementation is based on the description in Forster, 'A Fast and Simple Hueristic for Constrained Two-Level Crossing Reduction,' thought it differs in some specific details.
  987. *
  988. * Pre-conditions:
  989. *
  990. * 1. Each entry has the form {v, barycenter, weight}, or if the node has
  991. * no barycenter, then {v}.
  992. *
  993. * Returns:
  994. *
  995. * A new list of entries of the form {vs, i, barycenter, weight}. The list
  996. * `vs` may either be a singleton or it may be an aggregation of nodes
  997. * ordered such that they do not violate constraints from the constraint
  998. * graph. The property `i` is the lowest original index of any of the
  999. * elements in `vs`.
  1000. */
  1001. const resolveConflicts = (entries, cg) => {
  1002. const mergeEntries = (target, source) => {
  1003. let sum = 0;
  1004. let weight = 0;
  1005. if (target.weight) {
  1006. sum += target.barycenter * target.weight;
  1007. weight += target.weight;
  1008. }
  1009. if (source.weight) {
  1010. sum += source.barycenter * source.weight;
  1011. weight += source.weight;
  1012. }
  1013. target.vs = source.vs.concat(target.vs);
  1014. target.barycenter = sum / weight;
  1015. target.weight = weight;
  1016. target.i = Math.min(source.i, target.i);
  1017. source.merged = true;
  1018. };
  1019. const mappedEntries = {};
  1020. entries.forEach(function(entry, i) {
  1021. const tmp = mappedEntries[entry.v] = {
  1022. indegree: 0,
  1023. 'in': [],
  1024. out: [],
  1025. vs: [entry.v],
  1026. i: i
  1027. };
  1028. if (entry.barycenter !== undefined) {
  1029. tmp.barycenter = entry.barycenter;
  1030. tmp.weight = entry.weight;
  1031. }
  1032. });
  1033. for (const e of cg.edges().values()) {
  1034. const entryV = mappedEntries[e.v];
  1035. const entryW = mappedEntries[e.w];
  1036. if (entryV !== undefined && entryW !== undefined) {
  1037. entryW.indegree++;
  1038. entryV.out.push(mappedEntries[e.w]);
  1039. }
  1040. }
  1041. const sourceSet = Object.values(mappedEntries).filter((entry) => !entry.indegree);
  1042. const results = [];
  1043. function handleIn(vEntry) {
  1044. return function(uEntry) {
  1045. if (uEntry.merged) {
  1046. return;
  1047. }
  1048. if (uEntry.barycenter === undefined || vEntry.barycenter === undefined || uEntry.barycenter >= vEntry.barycenter) {
  1049. mergeEntries(vEntry, uEntry);
  1050. }
  1051. };
  1052. }
  1053. function handleOut(vEntry) {
  1054. return function(wEntry) {
  1055. wEntry.in.push(vEntry);
  1056. if (--wEntry.indegree === 0) {
  1057. sourceSet.push(wEntry);
  1058. }
  1059. };
  1060. }
  1061. while (sourceSet.length) {
  1062. const entry = sourceSet.pop();
  1063. results.push(entry);
  1064. entry.in.reverse().forEach(handleIn(entry));
  1065. entry.out.forEach(handleOut(entry));
  1066. }
  1067. const pick = (obj, attrs) => {
  1068. const value = {};
  1069. for (const key of attrs) {
  1070. if (obj[key] !== undefined) {
  1071. value[key] = obj[key];
  1072. }
  1073. }
  1074. return value;
  1075. };
  1076. return Object.values(results).filter((entry) => !entry.merged).map((entry) => pick(entry, ['vs', 'i', 'barycenter', 'weight']));
  1077. };
  1078. let movable = g.children(v);
  1079. const node = g.node(v);
  1080. const bl = node ? node.borderLeft : undefined;
  1081. const br = node ? node.borderRight: undefined;
  1082. const subgraphs = {};
  1083. if (bl) {
  1084. movable = movable.filter((w) => w !== bl && w !== br);
  1085. }
  1086. const barycenter = (g, movable) => {
  1087. return (movable || []).map((v) => {
  1088. const inV = g.inEdges(v);
  1089. if (!inV.length) {
  1090. return { v: v };
  1091. }
  1092. else {
  1093. const result = inV.reduce((acc, e) => {
  1094. const edge = e.label;
  1095. const nodeU = g.node(e.v);
  1096. return {
  1097. sum: acc.sum + (edge.weight * nodeU.order),
  1098. weight: acc.weight + edge.weight
  1099. };
  1100. }, { sum: 0, weight: 0 });
  1101. return {
  1102. v: v,
  1103. barycenter: result.sum / result.weight,
  1104. weight: result.weight
  1105. };
  1106. }
  1107. });
  1108. };
  1109. const mergeBarycenters = (target, other) => {
  1110. if (target.barycenter !== undefined) {
  1111. target.barycenter = (target.barycenter * target.weight + other.barycenter * other.weight) / (target.weight + other.weight);
  1112. target.weight += other.weight;
  1113. }
  1114. else {
  1115. target.barycenter = other.barycenter;
  1116. target.weight = other.weight;
  1117. }
  1118. };
  1119. const barycenters = barycenter(g, movable);
  1120. for (const entry of barycenters) {
  1121. if (g.children(entry.v).length) {
  1122. const subgraphResult = sortSubgraph(g, entry.v, cg, biasRight);
  1123. subgraphs[entry.v] = subgraphResult;
  1124. if ('barycenter' in subgraphResult) {
  1125. mergeBarycenters(entry, subgraphResult);
  1126. }
  1127. }
  1128. }
  1129. const entries = resolveConflicts(barycenters, cg);
  1130. // expand subgraphs
  1131. for (const entry of entries) {
  1132. entry.vs = flat(entry.vs.map((v) => subgraphs[v] ? subgraphs[v].vs : v));
  1133. }
  1134. const sort = (entries, biasRight) => {
  1135. const consumeUnsortable = (vs, unsortable, index) => {
  1136. let last;
  1137. while (unsortable.length && (last = unsortable[unsortable.length - 1]).i <= index) {
  1138. unsortable.pop();
  1139. vs.push(last.vs);
  1140. index++;
  1141. }
  1142. return index;
  1143. };
  1144. const compareWithBias = (bias) => {
  1145. return function(entryV, entryW) {
  1146. if (entryV.barycenter < entryW.barycenter) {
  1147. return -1;
  1148. }
  1149. else if (entryV.barycenter > entryW.barycenter) {
  1150. return 1;
  1151. }
  1152. return !bias ? entryV.i - entryW.i : entryW.i - entryV.i;
  1153. };
  1154. };
  1155. // partition
  1156. const parts = { lhs: [], rhs: [] };
  1157. for (const value of entries) {
  1158. if ('barycenter' in value) {
  1159. parts.lhs.push(value);
  1160. }
  1161. else {
  1162. parts.rhs.push(value);
  1163. }
  1164. }
  1165. const sortable = parts.lhs;
  1166. const unsortable = parts.rhs.sort((a, b) => -a.i + b.i);
  1167. const vs = [];
  1168. let sum = 0;
  1169. let weight = 0;
  1170. let vsIndex = 0;
  1171. sortable.sort(compareWithBias(!!biasRight));
  1172. vsIndex = consumeUnsortable(vs, unsortable, vsIndex);
  1173. for (const entry of sortable) {
  1174. vsIndex += entry.vs.length;
  1175. vs.push(entry.vs);
  1176. sum += entry.barycenter * entry.weight;
  1177. weight += entry.weight;
  1178. vsIndex = consumeUnsortable(vs, unsortable, vsIndex);
  1179. }
  1180. const result = { vs: flat(vs) };
  1181. if (weight) {
  1182. result.barycenter = sum / weight;
  1183. result.weight = weight;
  1184. }
  1185. return result;
  1186. };
  1187. const result = sort(entries, biasRight);
  1188. if (bl) {
  1189. result.vs = flat([bl, result.vs, br]);
  1190. if (g.predecessors(bl).length) {
  1191. const blPred = g.node(g.predecessors(bl)[0]);
  1192. const brPred = g.node(g.predecessors(br)[0]);
  1193. if (!('barycenter' in result)) {
  1194. result.barycenter = 0;
  1195. result.weight = 0;
  1196. }
  1197. result.barycenter = (result.barycenter * result.weight + blPred.order + brPred.order) / (result.weight + 2);
  1198. result.weight += 2;
  1199. }
  1200. }
  1201. return result;
  1202. };
  1203. const addSubgraphConstraints = (g, cg, vs) => {
  1204. const prev = {};
  1205. let rootPrev;
  1206. for (const v of vs) {
  1207. let child = g.parent(v);
  1208. let prevChild;
  1209. while (child) {
  1210. const parent = g.parent(child);
  1211. if (parent) {
  1212. prevChild = prev[parent];
  1213. prev[parent] = child;
  1214. }
  1215. else {
  1216. prevChild = rootPrev;
  1217. rootPrev = child;
  1218. }
  1219. if (prevChild && prevChild !== child) {
  1220. cg.setEdge(prevChild, child, null);
  1221. return;
  1222. }
  1223. child = parent;
  1224. }
  1225. }
  1226. };
  1227. const sweepLayerGraphs = (layerGraphs, biasRight) => {
  1228. const cg = new dagre.Graph();
  1229. for (const lg of layerGraphs) {
  1230. const root = lg.graph().root;
  1231. const sorted = sortSubgraph(lg, root, cg, biasRight);
  1232. const vs = sorted.vs;
  1233. const length = vs.length;
  1234. for (let i = 0; i < length; i++) {
  1235. lg.node(vs[i]).order = i;
  1236. }
  1237. addSubgraphConstraints(lg, cg, sorted.vs);
  1238. }
  1239. };
  1240. /*
  1241. * A function that takes a layering (an array of layers, each with an array of
  1242. * ordererd nodes) and a graph and returns a weighted crossing count.
  1243. *
  1244. * Pre-conditions:
  1245. *
  1246. * 1. Input graph must be simple (not a multigraph), directed, and include
  1247. * only simple edges.
  1248. * 2. Edges in the input graph must have assigned weights.
  1249. *
  1250. * Post-conditions:
  1251. *
  1252. * 1. The graph and layering matrix are left unchanged.
  1253. *
  1254. * This algorithm is derived from Barth, et al., 'Bilayer Cross Counting.'
  1255. */
  1256. const crossCount = (g, layering) => {
  1257. let count = 0;
  1258. for (let i = 1; i < layering.length; i++) {
  1259. const northLayer = layering[i - 1];
  1260. const southLayer = layering[i];
  1261. // Sort all of the edges between the north and south layers by their position
  1262. // in the north layer and then the south. Map these edges to the position of
  1263. // their head in the south layer.
  1264. const southPos = {};
  1265. for (let i = 0; i < southLayer.length; i++) {
  1266. southPos[southLayer[i]] = i;
  1267. }
  1268. const southEntries = [];
  1269. for (const v of northLayer) {
  1270. const edges = g.outEdges(v);
  1271. const entries = [];
  1272. for (const e of edges) {
  1273. entries.push({
  1274. pos: southPos[e.w],
  1275. weight: e.label.weight
  1276. });
  1277. }
  1278. entries.sort((a, b) => a.pos - b.pos);
  1279. for (const entry of entries) {
  1280. southEntries.push(entry);
  1281. }
  1282. }
  1283. // Build the accumulator tree
  1284. let firstIndex = 1;
  1285. while (firstIndex < southLayer.length) {
  1286. firstIndex <<= 1;
  1287. }
  1288. const treeSize = 2 * firstIndex - 1;
  1289. firstIndex -= 1;
  1290. const tree = Array.from(new Array(treeSize), () => 0);
  1291. // Calculate the weighted crossings
  1292. for (const entry of southEntries) {
  1293. let index = entry.pos + firstIndex;
  1294. tree[index] += entry.weight;
  1295. let weightSum = 0;
  1296. while (index > 0) {
  1297. if (index % 2) {
  1298. weightSum += tree[index + 1];
  1299. }
  1300. index = (index - 1) >> 1;
  1301. tree[index] += entry.weight;
  1302. }
  1303. count += entry.weight * weightSum;
  1304. }
  1305. }
  1306. return count;
  1307. };
  1308. /*
  1309. * Assigns an initial order value for each node by performing a DFS search
  1310. * starting from nodes in the first rank. Nodes are assigned an order in their
  1311. * rank as they are first visited.
  1312. *
  1313. * This approach comes from Gansner, et al., 'A Technique for Drawing Directed
  1314. * Graphs.'
  1315. *
  1316. * Returns a layering matrix with an array per layer and each layer sorted by
  1317. * the order of its nodes.
  1318. */
  1319. const initOrder = (g) => {
  1320. const visited = new Set();
  1321. const nodes = Array.from(g.nodes().keys()).filter((v) => !g.children(v).length);
  1322. let maxRank = undefined;
  1323. for (const v of nodes) {
  1324. if (!g.children(v).length > 0) {
  1325. const rank = g.node(v).rank;
  1326. if (maxRank === undefined || (rank !== undefined && rank > maxRank)) {
  1327. maxRank = rank;
  1328. }
  1329. }
  1330. }
  1331. if (maxRank !== undefined) {
  1332. const layers = Array.from(new Array(maxRank + 1), () => []);
  1333. for (const v of nodes.map((v) => [ g.node(v).rank, v ]).sort((a, b) => a[0] - b[0]).map((item) => item[1])) {
  1334. const queue = [ v ];
  1335. while (queue.length > 0) {
  1336. const v = queue.shift();
  1337. if (!visited.has(v)) {
  1338. visited.add(v);
  1339. const rank = g.node(v).rank;
  1340. layers[rank].push(v);
  1341. queue.push(...g.successors(v));
  1342. }
  1343. }
  1344. }
  1345. return layers;
  1346. }
  1347. return [];
  1348. };
  1349. // Constructs a graph that can be used to sort a layer of nodes. The graph will
  1350. // contain all base and subgraph nodes from the request layer in their original
  1351. // hierarchy and any edges that are incident on these nodes and are of the type
  1352. // requested by the 'relationship' parameter.
  1353. //
  1354. // Nodes from the requested rank that do not have parents are assigned a root
  1355. // node in the output graph, which is set in the root graph attribute. This
  1356. // makes it easy to walk the hierarchy of movable nodes during ordering.
  1357. //
  1358. // Pre-conditions:
  1359. // 1. Input graph is a DAG
  1360. // 2. Base nodes in the input graph have a rank attribute
  1361. // 3. Subgraph nodes in the input graph has minRank and maxRank attributes
  1362. // 4. Edges have an assigned weight
  1363. //
  1364. // Post-conditions:
  1365. // 1. Output graph has all nodes in the movable rank with preserved
  1366. // hierarchy.
  1367. // 2. Root nodes in the movable layer are made children of the node
  1368. // indicated by the root attribute of the graph.
  1369. // 3. Non-movable nodes incident on movable nodes, selected by the
  1370. // relationship parameter, are included in the graph (without hierarchy).
  1371. // 4. Edges incident on movable nodes, selected by the relationship
  1372. // parameter, are added to the output graph.
  1373. // 5. The weights for copied edges are aggregated as need, since the output
  1374. // graph is not a multi-graph.
  1375. const buildLayerGraph = (g, rank, relationship) => {
  1376. let root;
  1377. while (g.hasNode((root = uniqueId('_root'))));
  1378. const graph = new dagre.Graph({ compound: true });
  1379. graph.setGraph({ root: root });
  1380. graph.setDefaultNodeLabel((v) => g.node(v));
  1381. for (const entry of g.nodes()) {
  1382. const node = entry[1];
  1383. if (node.rank === rank || node.minRank <= rank && rank <= node.maxRank) {
  1384. const v = entry[0];
  1385. graph.setNode(v);
  1386. const parent = g.parent(v);
  1387. graph.setParent(v, parent || root);
  1388. // This assumes we have only short edges!
  1389. if (relationship) {
  1390. for (const e of g.inEdges(v)) {
  1391. graph.setEdge(e.v, v, { weight: e.label.weight });
  1392. }
  1393. }
  1394. else {
  1395. for (const e of g.outEdges(v)) {
  1396. graph.setEdge(e.w, v, { weight: e.label.weight });
  1397. }
  1398. }
  1399. if ('minRank' in node) {
  1400. graph.setNode(v, {
  1401. borderLeft: node.borderLeft[rank],
  1402. borderRight: node.borderRight[rank]
  1403. });
  1404. }
  1405. }
  1406. }
  1407. return graph;
  1408. };
  1409. let layering = initOrder(g);
  1410. const assignOrder = (g, layering) => {
  1411. for (const layer of layering) {
  1412. for (let i = 0; i < layer.length; i++) {
  1413. g.node(layer[i]).order = i;
  1414. }
  1415. }
  1416. };
  1417. assignOrder(g, layering);
  1418. const rank = maxRank(g);
  1419. const downLayerGraphs = new Array(rank !== undefined ? rank : 0);
  1420. const upLayerGraphs = new Array(rank !== undefined ? rank : 0);
  1421. for (let i = 0; i < rank; i++) {
  1422. downLayerGraphs[i] = buildLayerGraph(g, i + 1, true);
  1423. upLayerGraphs[i] = buildLayerGraph(g, rank - i - 1, false);
  1424. }
  1425. let bestCC = Number.POSITIVE_INFINITY;
  1426. let best;
  1427. for (let i = 0, lastBest = 0; lastBest < 4; ++i, ++lastBest) {
  1428. sweepLayerGraphs(i % 2 ? downLayerGraphs : upLayerGraphs, i % 4 >= 2);
  1429. layering = buildLayerMatrix(g);
  1430. const cc = crossCount(g, layering);
  1431. if (cc < bestCC) {
  1432. lastBest = 0;
  1433. const length = layering.length;
  1434. best = new Array(length);
  1435. for (let j = 0; j < length; j++) {
  1436. best[j] = layering[j].slice();
  1437. }
  1438. bestCC = cc;
  1439. }
  1440. }
  1441. assignOrder(g, best);
  1442. };
  1443. const insertSelfEdges = (g) => {
  1444. const layers = buildLayerMatrix(g);
  1445. for (const layer of layers) {
  1446. let orderShift = 0;
  1447. layer.forEach(function(v, i) {
  1448. const node = g.node(v);
  1449. node.order = i + orderShift;
  1450. if (node.selfEdges) {
  1451. for (const selfEdge of node.selfEdges) {
  1452. addDummyNode(g, 'selfedge', {
  1453. width: selfEdge.label.width,
  1454. height: selfEdge.label.height,
  1455. rank: node.rank,
  1456. order: i + (++orderShift),
  1457. e: selfEdge.e,
  1458. label: selfEdge.label
  1459. }, '_se');
  1460. }
  1461. delete node.selfEdges;
  1462. }
  1463. });
  1464. }
  1465. };
  1466. const coordinateSystem_adjust = (g) => {
  1467. const rankDir = g.graph().rankdir.toLowerCase();
  1468. if (rankDir === 'lr' || rankDir === 'rl') {
  1469. coordinateSystem_swapWidthHeight(g);
  1470. }
  1471. };
  1472. const coordinateSystem_undo = (g) => {
  1473. const swapXY = (g) => {
  1474. const swapXYOne = (attrs) => {
  1475. const x = attrs.x;
  1476. attrs.x = attrs.y;
  1477. attrs.y = x;
  1478. };
  1479. for (const node of g.nodes().values()) {
  1480. swapXYOne(node);
  1481. }
  1482. for (const e of g.edges().values()) {
  1483. const edge = e.label;
  1484. for (const e of edge.points) {
  1485. swapXYOne(e);
  1486. }
  1487. if (edge.x !== undefined) {
  1488. swapXYOne(edge);
  1489. }
  1490. }
  1491. };
  1492. const rankDir = g.graph().rankdir.toLowerCase();
  1493. if (rankDir === 'bt' || rankDir === 'rl') {
  1494. for (const node of g.nodes().values()) {
  1495. node.y = -node.y;
  1496. }
  1497. for (const e of g.edges().values()) {
  1498. const edge = e.label;
  1499. for (const attr of edge.points) {
  1500. attr.y = -attr.y;
  1501. }
  1502. if ('y' in edge) {
  1503. edge.y = -edge.y;
  1504. }
  1505. }
  1506. }
  1507. if (rankDir === 'lr' || rankDir === 'rl') {
  1508. swapXY(g);
  1509. coordinateSystem_swapWidthHeight(g);
  1510. }
  1511. };
  1512. const coordinateSystem_swapWidthHeight = (g) => {
  1513. for (const node of g.nodes().values()) {
  1514. const w = node.width;
  1515. node.width = node.height;
  1516. node.height = w;
  1517. }
  1518. for (const e of g.edges().values()) {
  1519. const label = e.label;
  1520. const w = label.width;
  1521. label.width = label.height;
  1522. label.height = w;
  1523. }
  1524. };
  1525. const position = (g) => {
  1526. const addConflict = (conflicts, v, w) => {
  1527. if (v > w) {
  1528. const tmp = v;
  1529. v = w;
  1530. w = tmp;
  1531. }
  1532. let conflictsV = conflicts[v];
  1533. if (!conflictsV) {
  1534. conflicts[v] = conflictsV = {};
  1535. }
  1536. conflictsV[w] = true;
  1537. };
  1538. const hasConflict = (conflicts, v, w) => {
  1539. if (v > w) {
  1540. const tmp = v;
  1541. v = w;
  1542. w = tmp;
  1543. }
  1544. return conflicts[v] && w in conflicts[v];
  1545. };
  1546. // Try to align nodes into vertical 'blocks' where possible. This algorithm
  1547. // attempts to align a node with one of its median neighbors. If the edge
  1548. // connecting a neighbor is a type-1 conflict then we ignore that possibility.
  1549. // If a previous node has already formed a block with a node after the node
  1550. // we're trying to form a block with, we also ignore that possibility - our
  1551. // blocks would be split in that scenario.
  1552. const verticalAlignment = (g, layering, conflicts, neighborFn) => {
  1553. const root = {};
  1554. const align = {};
  1555. const pos = {};
  1556. // We cache the position here based on the layering because the graph and layering may be out of sync.
  1557. // The layering matrix is manipulated to generate different extreme alignments.
  1558. for (const layer of layering) {
  1559. let order = 0;
  1560. for (const v of layer) {
  1561. root[v] = v;
  1562. align[v] = v;
  1563. pos[v] = order;
  1564. order++;
  1565. }
  1566. }
  1567. for (const layer of layering) {
  1568. let prevIdx = -1;
  1569. for (const v of layer) {
  1570. let ws = neighborFn(v);
  1571. if (ws.length > 0) {
  1572. ws = ws.sort((a, b) => pos[a] - pos[b]);
  1573. const mp = (ws.length - 1) / 2.0;
  1574. const il = Math.ceil(mp);
  1575. for (let i = Math.floor(mp); i <= il; i++) {
  1576. const w = ws[i];
  1577. if (align[v] === v && prevIdx < pos[w] && !hasConflict(conflicts, v, w)) {
  1578. align[w] = v;
  1579. align[v] = root[v] = root[w];
  1580. prevIdx = pos[w];
  1581. }
  1582. }
  1583. }
  1584. }
  1585. }
  1586. return { root: root, align: align };
  1587. };
  1588. const horizontalCompaction = (g, layering, root, align, reverseSep) => {
  1589. // This portion of the algorithm differs from BK due to a number of problems.
  1590. // Instead of their algorithm we construct a new block graph and do two sweeps.
  1591. // The first sweep places blocks with the smallest possible coordinates.
  1592. // The second sweep removes unused space by moving blocks to the greatest coordinates without violating separation.
  1593. const xs = {};
  1594. const blockG = buildBlockGraph(g, layering, root, reverseSep);
  1595. const borderType = reverseSep ? 'borderLeft' : 'borderRight';
  1596. const iterate = (setXsFunc, nextNodesFunc) => {
  1597. let stack = Array.from(blockG.nodes().keys());
  1598. const visited = new Set();
  1599. while (stack.length > 0) {
  1600. const v = stack.pop();
  1601. if (visited.has(v)) {
  1602. setXsFunc(v);
  1603. }
  1604. else {
  1605. visited.add(v);
  1606. stack.push(v);
  1607. stack = stack.concat(nextNodesFunc(v));
  1608. }
  1609. }
  1610. };
  1611. // First pass, assign smallest coordinates
  1612. const pass1 = (v) => {
  1613. let max = 0;
  1614. for (const e of blockG.inEdges(v)) {
  1615. max = Math.max(max, xs[e.v] + e.label);
  1616. }
  1617. xs[v] = max;
  1618. };
  1619. // Second pass, assign greatest coordinates
  1620. const pass2 = (v) => {
  1621. let min = Number.POSITIVE_INFINITY;
  1622. for (const e of blockG.outEdges(v)) {
  1623. min = Math.min(min, xs[e.w] - e.label);
  1624. }
  1625. const node = g.node(v);
  1626. if (min !== Number.POSITIVE_INFINITY && node.borderType !== borderType) {
  1627. xs[v] = Math.max(xs[v], min);
  1628. }
  1629. };
  1630. iterate(pass1, blockG.predecessors.bind(blockG));
  1631. iterate(pass2, blockG.successors.bind(blockG));
  1632. // Assign x coordinates to all nodes
  1633. for (const v of Object.values(align)) {
  1634. xs[v] = xs[root[v]];
  1635. }
  1636. return xs;
  1637. };
  1638. const buildBlockGraph = (g, layering, root, reverseSep) => {
  1639. const nodeSep = g.graph().nodesep;
  1640. const edgeSep = g.graph().edgesep;
  1641. const sep = (vLabel, wLabel) => {
  1642. let sum = 0;
  1643. let delta;
  1644. sum += vLabel.width / 2;
  1645. if ('labelpos' in vLabel) {
  1646. switch (vLabel.labelpos) {
  1647. case 'l': delta = -vLabel.width / 2; break;
  1648. case 'r': delta = vLabel.width / 2; break;
  1649. }
  1650. }
  1651. if (delta) {
  1652. sum += reverseSep ? delta : -delta;
  1653. }
  1654. delta = 0;
  1655. sum += (vLabel.dummy ? edgeSep : nodeSep) / 2;
  1656. sum += (wLabel.dummy ? edgeSep : nodeSep) / 2;
  1657. sum += wLabel.width / 2;
  1658. if ('labelpos' in wLabel) {
  1659. switch (wLabel.labelpos) {
  1660. case 'l': delta = wLabel.width / 2; break;
  1661. case 'r': delta = -wLabel.width / 2; break;
  1662. }
  1663. }
  1664. if (delta) {
  1665. sum += reverseSep ? delta : -delta;
  1666. }
  1667. delta = 0;
  1668. return sum;
  1669. };
  1670. const blockGraph = new dagre.Graph();
  1671. for (const layer of layering) {
  1672. let u;
  1673. for (const v of layer) {
  1674. const vRoot = root[v];
  1675. blockGraph.setNode(vRoot, {});
  1676. if (u) {
  1677. const uRoot = root[u];
  1678. const edge = blockGraph.edge(uRoot, vRoot);
  1679. const prevMax = edge ? edge.label : 0;
  1680. blockGraph.setEdge(uRoot, vRoot, Math.max(sep(g.node(v), g.node(u)), prevMax));
  1681. }
  1682. u = v;
  1683. }
  1684. }
  1685. return blockGraph;
  1686. };
  1687. // Returns the alignment that has the smallest width of the given alignments.
  1688. const findSmallestWidthAlignment = (g, xss) => {
  1689. let minKey = Number.POSITIVE_INFINITY;
  1690. let minValue = undefined;
  1691. for (const xs of Object.values(xss)) {
  1692. let max = Number.NEGATIVE_INFINITY;
  1693. let min = Number.POSITIVE_INFINITY;
  1694. for (const entry of Object.entries(xs)) {
  1695. const v = entry[0];
  1696. const x = entry[1];
  1697. const halfWidth = g.node(v).width / 2.0;
  1698. max = Math.max(x + halfWidth, max);
  1699. min = Math.min(x - halfWidth, min);
  1700. }
  1701. const key = max - min;
  1702. if (key < minKey) {
  1703. minKey = key;
  1704. minValue = xs;
  1705. }
  1706. }
  1707. return minValue;
  1708. };
  1709. const balance = (xss, align) => {
  1710. const value = {};
  1711. if (align) {
  1712. const xs = xss[align.toLowerCase()];
  1713. for (const v of Object.keys(xss.ul)) {
  1714. value[v] = xs[v];
  1715. }
  1716. }
  1717. else {
  1718. for (const v of Object.keys(xss.ul)) {
  1719. const xs = [ xss.ul[v], xss.ur[v], xss.dl[v], xss.dr[v] ].sort((a, b) => a - b);
  1720. value[v] = (xs[1] + xs[2]) / 2.0;
  1721. }
  1722. }
  1723. return value;
  1724. };
  1725. // Marks all edges in the graph with a type-1 conflict with the 'type1Conflict' property.
  1726. // A type-1 conflict is one where a non-inner segment crosses an inner segment.
  1727. // An inner segment is an edge with both incident nodes marked with the 'dummy' property.
  1728. //
  1729. // This algorithm scans layer by layer, starting with the second, for type-1
  1730. // conflicts between the current layer and the previous layer. For each layer
  1731. // it scans the nodes from left to right until it reaches one that is incident
  1732. // on an inner segment. It then scans predecessors to determine if they have
  1733. // edges that cross that inner segment. At the end a final scan is done for all
  1734. // nodes on the current rank to see if they cross the last visited inner segment.
  1735. //
  1736. // This algorithm (safely) assumes that a dummy node will only be incident on a
  1737. // single node in the layers being scanned.
  1738. const findType1Conflicts = (g, layering) => {
  1739. const conflicts = {};
  1740. if (layering.length > 0) {
  1741. let prev = layering[0];
  1742. for (let k = 1; k < layering.length; k++) {
  1743. const layer = layering[k];
  1744. // last visited node in the previous layer that is incident on an inner segment.
  1745. let k0 = 0;
  1746. // Tracks the last node in this layer scanned for crossings with a type-1 segment.
  1747. let scanPos = 0;
  1748. const prevLayerLength = prev.length;
  1749. const lastNode = layer[layer.length - 1];
  1750. for (let i = 0; i < layer.length; i++) {
  1751. const v = layer[i];
  1752. const w = g.node(v).dummy ? g.predecessors(v).find((u) => g.node(u).dummy) : null;
  1753. if (w || v === lastNode) {
  1754. const k1 = w ? g.node(w).order : prevLayerLength;
  1755. for (const scanNode of layer.slice(scanPos, i + 1)) {
  1756. // for (const scanNode of layer.slice(scanPos, scanPos + 1)) {
  1757. for (const u of g.predecessors(scanNode)) {
  1758. const uLabel = g.node(u);
  1759. const uPos = uLabel.order;
  1760. if ((uPos < k0 || k1 < uPos) && !(uLabel.dummy && g.node(scanNode).dummy)) {
  1761. // addConflict(conflicts, u, scanNode);
  1762. }
  1763. }
  1764. }
  1765. // scanPos += 1;
  1766. scanPos = i + 1;
  1767. k0 = k1;
  1768. }
  1769. }
  1770. prev = layer;
  1771. }
  1772. }
  1773. return conflicts;
  1774. };
  1775. const findType2Conflicts = (g, layering) => {
  1776. const conflicts = {};
  1777. const scan = (south, southPos, southEnd, prevNorthBorder, nextNorthBorder) => {
  1778. let v;
  1779. for (let i = southPos; i < southEnd; i++) {
  1780. v = south[i];
  1781. if (g.node(v).dummy) {
  1782. for (const u of g.predecessors(v)) {
  1783. const uNode = g.node(u);
  1784. if (uNode.dummy && (uNode.order < prevNorthBorder || uNode.order > nextNorthBorder)) {
  1785. addConflict(conflicts, u, v);
  1786. }
  1787. }
  1788. }
  1789. }
  1790. };
  1791. if (layering.length > 0) {
  1792. let north = layering[0];
  1793. for (let i = 1; i < layering.length; i++) {
  1794. const south = layering[i];
  1795. let prevNorthPos = -1;
  1796. let nextNorthPos;
  1797. let southPos = 0;
  1798. south.forEach(function(v, southLookahead) {
  1799. if (g.node(v).dummy === 'border') {
  1800. const predecessors = g.predecessors(v);
  1801. if (predecessors.length) {
  1802. nextNorthPos = g.node(predecessors[0]).order;
  1803. scan(south, southPos, southLookahead, prevNorthPos, nextNorthPos);
  1804. southPos = southLookahead;
  1805. prevNorthPos = nextNorthPos;
  1806. }
  1807. }
  1808. scan(south, southPos, south.length, nextNorthPos, north.length);
  1809. });
  1810. north = south;
  1811. }
  1812. }
  1813. return conflicts;
  1814. };
  1815. // Align the coordinates of each of the layout alignments such that
  1816. // left-biased alignments have their minimum coordinate at the same point as
  1817. // the minimum coordinate of the smallest width alignment and right-biased
  1818. // alignments have their maximum coordinate at the same point as the maximum
  1819. // coordinate of the smallest width alignment.
  1820. const alignCoordinates = (xss, alignTo) => {
  1821. const range = (values) => {
  1822. let min = Number.POSITIVE_INFINITY;
  1823. let max = Number.NEGATIVE_INFINITY;
  1824. for (const value of values) {
  1825. if (value < min) {
  1826. min = value;
  1827. }
  1828. if (value > max) {
  1829. max = value;
  1830. }
  1831. }
  1832. return [ min, max ];
  1833. };
  1834. const alignToRange = range(Object.values(alignTo));
  1835. for (const vert of ['u', 'd']) {
  1836. for (const horiz of ['l', 'r']) {
  1837. const alignment = vert + horiz;
  1838. const xs = xss[alignment];
  1839. let delta;
  1840. if (xs !== alignTo) {
  1841. const vsValsRange = range(Object.values(xs));
  1842. delta = horiz === 'l' ? alignToRange[0] - vsValsRange[0] : alignToRange[1] - vsValsRange[1];
  1843. if (delta) {
  1844. const list = {};
  1845. for (const key of Object.keys(xs)) {
  1846. list[key] = xs[key] + delta;
  1847. }
  1848. xss[alignment] = list;
  1849. }
  1850. }
  1851. }
  1852. }
  1853. };
  1854. g = asNonCompoundGraph(g);
  1855. const layering = buildLayerMatrix(g);
  1856. const ranksep = g.graph().ranksep;
  1857. let prevY = 0;
  1858. for (const layer of layering) {
  1859. const heights = layer.map((v) => g.node(v).height);
  1860. const maxHeight = Math.max(...heights);
  1861. for (const v of layer) {
  1862. g.node(v).y = prevY + maxHeight / 2.0;
  1863. }
  1864. prevY += maxHeight + ranksep;
  1865. }
  1866. // Coordinate assignment based on Brandes and Köpf, 'Fast and Simple Horizontal Coordinate Assignment.'
  1867. const conflicts = Object.assign(findType1Conflicts(g, layering), findType2Conflicts(g, layering));
  1868. const xss = {};
  1869. for (const vert of ['u', 'd']) {
  1870. let adjustedLayering = vert === 'u' ? layering : Object.values(layering).reverse();
  1871. for (const horiz of ['l', 'r']) {
  1872. if (horiz === 'r') {
  1873. adjustedLayering = adjustedLayering.map((inner) => Object.values(inner).reverse());
  1874. }
  1875. const neighborFn = (vert === 'u' ? g.predecessors : g.successors).bind(g);
  1876. const align = verticalAlignment(g, adjustedLayering, conflicts, neighborFn);
  1877. const xs = horizontalCompaction(g, adjustedLayering, align.root, align.align, horiz === 'r');
  1878. if (horiz === 'r') {
  1879. for (const entry of Object.entries(xs)) {
  1880. xs[entry[0]] = -entry[1];
  1881. }
  1882. }
  1883. xss[vert + horiz] = xs;
  1884. }
  1885. }
  1886. const smallestWidth = findSmallestWidthAlignment(g, xss);
  1887. alignCoordinates(xss, smallestWidth);
  1888. const xs = balance(xss, g.graph().align);
  1889. for (const entry of Object.entries(xs)) {
  1890. g.node(entry[0]).x = entry[1];
  1891. }
  1892. };
  1893. const positionSelfEdges = (g) => {
  1894. for (const entry of g.nodes()) {
  1895. const node = entry[1];
  1896. if (node.dummy === 'selfedge') {
  1897. const v = entry[0];
  1898. const selfNode = g.node(node.e.v);
  1899. const x = selfNode.x + selfNode.width / 2;
  1900. const y = selfNode.y;
  1901. const dx = node.x - x;
  1902. const dy = selfNode.height / 2;
  1903. g.setEdge(node.e.v, node.e.w, node.label);
  1904. g.removeNode(v);
  1905. node.label.points = [
  1906. { x: x + 2 * dx / 3, y: y - dy },
  1907. { x: x + 5 * dx / 6, y: y - dy },
  1908. { x: x + dx , y: y },
  1909. { x: x + 5 * dx / 6, y: y + dy },
  1910. { x: x + 2 * dx / 3, y: y + dy }
  1911. ];
  1912. node.label.x = node.x;
  1913. node.label.y = node.y;
  1914. }
  1915. }
  1916. };
  1917. const removeBorderNodes = (g) => {
  1918. for (const entry of g.nodes()) {
  1919. const v = entry[0];
  1920. if (g.children(v).length) {
  1921. const node = entry[1];
  1922. const t = g.node(node.borderTop);
  1923. const b = g.node(node.borderBottom);
  1924. const l = g.node(node.borderLeft[node.borderLeft.length - 1]);
  1925. const r = g.node(node.borderRight[node.borderRight.length - 1]);
  1926. node.width = Math.abs(r.x - l.x);
  1927. node.height = Math.abs(b.y - t.y);
  1928. node.x = l.x + node.width / 2;
  1929. node.y = t.y + node.height / 2;
  1930. }
  1931. }
  1932. for (const entry of g.nodes()) {
  1933. const node = entry[1];
  1934. if (node.dummy === 'border') {
  1935. const v = entry[0];
  1936. g.removeNode(v);
  1937. }
  1938. }
  1939. };
  1940. const fixupEdgeLabelCoords = (g) => {
  1941. for (const e of g.edges().values()) {
  1942. const edge = e.label;
  1943. if ('x' in edge) {
  1944. if (edge.labelpos === 'l' || edge.labelpos === 'r') {
  1945. edge.width -= edge.labeloffset;
  1946. }
  1947. switch (edge.labelpos) {
  1948. case 'l': edge.x -= edge.width / 2 + edge.labeloffset; break;
  1949. case 'r': edge.x += edge.width / 2 + edge.labeloffset; break;
  1950. }
  1951. }
  1952. }
  1953. };
  1954. const translateGraph = (g) => {
  1955. let minX = Number.POSITIVE_INFINITY;
  1956. let maxX = 0;
  1957. let minY = Number.POSITIVE_INFINITY;
  1958. let maxY = 0;
  1959. const getExtremes = (attrs) => {
  1960. const x = attrs.x;
  1961. const y = attrs.y;
  1962. const w = attrs.width;
  1963. const h = attrs.height;
  1964. minX = Math.min(minX, x - w / 2);
  1965. maxX = Math.max(maxX, x + w / 2);
  1966. minY = Math.min(minY, y - h / 2);
  1967. maxY = Math.max(maxY, y + h / 2);
  1968. };
  1969. for (const node of g.nodes().values()) {
  1970. getExtremes(node);
  1971. }
  1972. for (const e of g.edges().values()) {
  1973. const edge = e.label;
  1974. if ('x' in edge) {
  1975. getExtremes(edge);
  1976. }
  1977. }
  1978. for (const node of g.nodes().values()) {
  1979. node.x -= minX;
  1980. node.y -= minY;
  1981. }
  1982. for (const e of g.edges().values()) {
  1983. const edge = e.label;
  1984. for (const p of edge.points) {
  1985. p.x -= minX;
  1986. p.y -= minY;
  1987. }
  1988. if ('x' in edge) {
  1989. edge.x -= minX;
  1990. }
  1991. if ('y' in edge) {
  1992. edge.y -= minY;
  1993. }
  1994. }
  1995. const graphLabel = g.graph();
  1996. graphLabel.width = maxX - minX;
  1997. graphLabel.height = maxY - minY;
  1998. };
  1999. const assignNodeIntersects = (g) => {
  2000. // Finds where a line starting at point ({x, y}) would intersect a rectangle
  2001. // ({x, y, width, height}) if it were pointing at the rectangle's center.
  2002. const intersectRect = (rect, point) => {
  2003. const x = rect.x;
  2004. const y = rect.y;
  2005. // Rectangle intersection algorithm from: http://math.stackexchange.com/questions/108113/find-edge-between-two-boxes
  2006. const dx = point.x - x;
  2007. const dy = point.y - y;
  2008. let w = rect.width / 2;
  2009. let h = rect.height / 2;
  2010. if (!dx && !dy) {
  2011. throw new Error('Not possible to find intersection inside of the rectangle');
  2012. }
  2013. let sx;
  2014. let sy;
  2015. if (Math.abs(dy) * w > Math.abs(dx) * h) {
  2016. // Intersection is top or bottom of rect.
  2017. if (dy < 0) {
  2018. h = -h;
  2019. }
  2020. sx = h * dx / dy;
  2021. sy = h;
  2022. }
  2023. else {
  2024. // Intersection is left or right of rect.
  2025. if (dx < 0) {
  2026. w = -w;
  2027. }
  2028. sx = w;
  2029. sy = w * dy / dx;
  2030. }
  2031. return { x: x + sx, y: y + sy };
  2032. };
  2033. for (const e of g.edges().values()) {
  2034. const edge = e.label;
  2035. const nodeV = g.node(e.v);
  2036. const nodeW = g.node(e.w);
  2037. let p1;
  2038. let p2;
  2039. if (!edge.points) {
  2040. edge.points = [];
  2041. p1 = nodeW;
  2042. p2 = nodeV;
  2043. }
  2044. else {
  2045. p1 = edge.points[0];
  2046. p2 = edge.points[edge.points.length - 1];
  2047. }
  2048. edge.points.unshift(intersectRect(nodeV, p1));
  2049. edge.points.push(intersectRect(nodeW, p2));
  2050. }
  2051. };
  2052. time(' makeSpaceForEdgeLabels', () => { makeSpaceForEdgeLabels(g); });
  2053. time(' removeSelfEdges', () => { removeSelfEdges(g); });
  2054. time(' acyclic_run', () => { acyclic_run(g); });
  2055. time(' nestingGraph_run', () => { nestingGraph_run(g); });
  2056. time(' rank', () => { rank(asNonCompoundGraph(g)); });
  2057. time(' injectEdgeLabelProxies', () => { injectEdgeLabelProxies(g); });
  2058. time(' removeEmptyRanks', () => { removeEmptyRanks(g); });
  2059. time(' nestingGraph_cleanup', () => { nestingGraph_cleanup(g); });
  2060. time(' normalizeRanks', () => { normalizeRanks(g); });
  2061. time(' assignRankMinMax', () => { assignRankMinMax(g); });
  2062. time(' removeEdgeLabelProxies', () => { removeEdgeLabelProxies(g); });
  2063. time(' normalize', () => { normalize(g); });
  2064. time(' parentDummyChains', () => { parentDummyChains(g); });
  2065. time(' addBorderSegments', () => { addBorderSegments(g); });
  2066. time(' order', () => { order(g); });
  2067. time(' insertSelfEdges', () => { insertSelfEdges(g); });
  2068. time(' coordinateSystem_adjust', () => { coordinateSystem_adjust(g); });
  2069. time(' position', () => { position(g); });
  2070. time(' positionSelfEdges', () => { positionSelfEdges(g); });
  2071. time(' removeBorderNodes', () => { removeBorderNodes(g); });
  2072. time(' denormalize', () => { denormalize(g); });
  2073. time(' fixupEdgeLabelCoords', () => { fixupEdgeLabelCoords(g); });
  2074. time(' coordinateSystem_undo', () => { coordinateSystem_undo(g); });
  2075. time(' translateGraph', () => { translateGraph(g); });
  2076. time(' assignNodeIntersects', () => { assignNodeIntersects(g); });
  2077. time(' acyclic_undo', () => { acyclic_undo(g); });
  2078. };
  2079. /*
  2080. * Copies final layout information from the layout graph back to the input
  2081. * graph. This process only copies whitelisted attributes from the layout graph
  2082. * to the input graph, so it serves as a good place to determine what
  2083. * attributes can influence layout.
  2084. */
  2085. const updateInputGraph = (inputGraph, layoutGraph) => {
  2086. for (const entry of inputGraph.nodes()) {
  2087. const inputLabel = entry[1];
  2088. if (inputLabel) {
  2089. const v = entry[0];
  2090. const layoutLabel = layoutGraph.node(v);
  2091. inputLabel.x = layoutLabel.x;
  2092. inputLabel.y = layoutLabel.y;
  2093. if (layoutGraph.children(v).length) {
  2094. inputLabel.width = layoutLabel.width;
  2095. inputLabel.height = layoutLabel.height;
  2096. }
  2097. }
  2098. }
  2099. for (const e of inputGraph.edges().values()) {
  2100. const inputLabel = e.label;
  2101. const layoutLabel = layoutGraph.edge(e.v, e.w).label;
  2102. inputLabel.points = layoutLabel.points;
  2103. if ('x' in layoutLabel) {
  2104. inputLabel.x = layoutLabel.x;
  2105. inputLabel.y = layoutLabel.y;
  2106. }
  2107. }
  2108. inputGraph.graph().width = layoutGraph.graph().width;
  2109. inputGraph.graph().height = layoutGraph.graph().height;
  2110. };
  2111. time('layout', () => {
  2112. const layoutGraph =
  2113. time(' buildLayoutGraph', () => { return buildLayoutGraph(graph); });
  2114. time(' runLayout', () => { runLayout(layoutGraph, time); });
  2115. time(' updateInputGraph', () => { updateInputGraph(graph, layoutGraph); });
  2116. });
  2117. };
  2118. dagre.Graph = class {
  2119. constructor(options) {
  2120. options = options || {};
  2121. this._isDirected = 'directed' in options ? options.directed : true;
  2122. this._isCompound = 'compound' in options ? options.compound : false;
  2123. this._label = undefined;
  2124. this._defaultNodeLabelFn = () => {
  2125. return undefined;
  2126. };
  2127. this._nodes = new Map();
  2128. if (this._isCompound) {
  2129. this._parent = {};
  2130. this._children = {};
  2131. this._children['\x00'] = {};
  2132. }
  2133. this._in = {};
  2134. this._predecessors = {};
  2135. this._out = {};
  2136. this._successors = {};
  2137. this._edges = new Map();
  2138. }
  2139. isDirected() {
  2140. return this._isDirected;
  2141. }
  2142. isCompound() {
  2143. return this._isCompound;
  2144. }
  2145. setGraph(label) {
  2146. this._label = label;
  2147. }
  2148. graph() {
  2149. return this._label;
  2150. }
  2151. setDefaultNodeLabel(newDefault) {
  2152. this._defaultNodeLabelFn = newDefault;
  2153. }
  2154. nodes() {
  2155. return this._nodes;
  2156. }
  2157. sources() {
  2158. return Array.from(this.nodes().keys()).filter((v) => {
  2159. const value = this._in[v];
  2160. return value && Object.keys(value).length === 0 && value.constructor === Object;
  2161. });
  2162. }
  2163. setNode(v, node) {
  2164. if (this._nodes.has(v)) {
  2165. if (node) {
  2166. this._nodes.set(v, node);
  2167. }
  2168. }
  2169. else {
  2170. this._nodes.set(v, node ? node : this._defaultNodeLabelFn(v));
  2171. if (this._isCompound) {
  2172. this._parent[v] = '\x00';
  2173. this._children[v] = {};
  2174. this._children['\x00'][v] = true;
  2175. }
  2176. this._in[v] = {};
  2177. this._predecessors[v] = {};
  2178. this._out[v] = {};
  2179. this._successors[v] = {};
  2180. }
  2181. }
  2182. node(v) {
  2183. return this._nodes.get(v);
  2184. }
  2185. hasNode(v) {
  2186. return this._nodes.has(v);
  2187. }
  2188. removeNode(v) {
  2189. if (this._nodes.has(v)) {
  2190. delete this._nodes.delete(v);
  2191. if (this._isCompound) {
  2192. delete this._children[this._parent[v]][v];
  2193. delete this._parent[v];
  2194. for (const child of this.children(v)) {
  2195. this.setParent(child);
  2196. }
  2197. delete this._children[v];
  2198. }
  2199. for (const e of Object.keys(this._in[v])) {
  2200. this.removeEdge(this._edges.get(e));
  2201. }
  2202. delete this._in[v];
  2203. delete this._predecessors[v];
  2204. for (const e of Object.keys(this._out[v])) {
  2205. this.removeEdge(this._edges.get(e));
  2206. }
  2207. delete this._out[v];
  2208. delete this._successors[v];
  2209. }
  2210. }
  2211. setParent(v, parent) {
  2212. if (!this._isCompound) {
  2213. throw new Error('Cannot set parent in a non-compound graph');
  2214. }
  2215. if (parent) {
  2216. for (let ancestor = parent; ancestor !== undefined; ancestor = this.parent(ancestor)) {
  2217. if (ancestor === v) {
  2218. throw new Error('Setting ' + parent + ' as parent of ' + v + ' would create a cycle.');
  2219. }
  2220. }
  2221. this.setNode(parent);
  2222. }
  2223. else {
  2224. parent = '\x00';
  2225. }
  2226. delete this._children[this._parent[v]][v];
  2227. this._parent[v] = parent;
  2228. this._children[parent][v] = true;
  2229. }
  2230. parent(v) {
  2231. if (this._isCompound) {
  2232. const parent = this._parent[v];
  2233. if (parent !== '\x00') {
  2234. return parent;
  2235. }
  2236. }
  2237. }
  2238. children(v) {
  2239. if (v === undefined) {
  2240. v = '\x00';
  2241. }
  2242. if (this._isCompound) {
  2243. const children = this._children[v];
  2244. if (children) {
  2245. return Object.keys(children);
  2246. }
  2247. }
  2248. else if (v === '\x00') {
  2249. return this.nodes().keys();
  2250. }
  2251. else if (this.hasNode(v)) {
  2252. return [];
  2253. }
  2254. }
  2255. predecessors(v) {
  2256. return Object.keys(this._predecessors[v]);
  2257. }
  2258. successors(v) {
  2259. return Object.keys(this._successors[v]);
  2260. }
  2261. neighbors(v) {
  2262. return Array.from(new Set(this.predecessors(v).concat(this.successors(v))));
  2263. }
  2264. edges() {
  2265. return this._edges;
  2266. }
  2267. edge(v, w) {
  2268. return this._edges.get(this._edgeKey(this._isDirected, v, w));
  2269. }
  2270. setEdge(v, w, value, name) {
  2271. const e = this._edgeKey(this._isDirected, v, w, name);
  2272. const edge = this._edges.get(e);
  2273. if (edge) {
  2274. edge.label = value;
  2275. }
  2276. else {
  2277. this.setNode(v);
  2278. this.setNode(w);
  2279. if (!this._isDirected && v > w) {
  2280. const tmp = v;
  2281. v = w;
  2282. w = tmp;
  2283. }
  2284. const edge = { label: value, v: v, w: w, name: name };
  2285. this._edges.set(e, edge);
  2286. const incrementOrInitEntry = (map, k) => {
  2287. if (map[k]) {
  2288. map[k]++;
  2289. }
  2290. else {
  2291. map[k] = 1;
  2292. }
  2293. };
  2294. incrementOrInitEntry(this._predecessors[w], v);
  2295. incrementOrInitEntry(this._successors[v], w);
  2296. this._in[w][e] = edge;
  2297. this._out[v][e] = edge;
  2298. }
  2299. }
  2300. removeEdge(e) {
  2301. const key = this._edgeKey(this._isDirected, e.v, e.w, e.name);
  2302. const edge = this._edges.get(key);
  2303. if (edge) {
  2304. const v = edge.v;
  2305. const w = edge.w;
  2306. this._edges.delete(key);
  2307. const decrementOrRemoveEntry = (map, k) => {
  2308. if (!--map[k]) {
  2309. delete map[k];
  2310. }
  2311. };
  2312. decrementOrRemoveEntry(this._predecessors[w], v);
  2313. decrementOrRemoveEntry(this._successors[v], w);
  2314. delete this._in[w][key];
  2315. delete this._out[v][key];
  2316. }
  2317. }
  2318. inEdges(v) {
  2319. return Object.values(this._in[v]);
  2320. }
  2321. outEdges(v) {
  2322. return Object.values(this._out[v]);
  2323. }
  2324. nodeEdges(v) {
  2325. return this.inEdges(v).concat(this.outEdges(v));
  2326. }
  2327. _edgeKey(isDirected, v, w, name) {
  2328. if (!isDirected && v > w) {
  2329. return name ? w + ':' + v + ':' + name : w + ':' + v + ':';
  2330. }
  2331. return name ? v + ':' + w + ':' + name : v + ':' + w + ':';
  2332. }
  2333. };
  2334. if (typeof module !== 'undefined' && typeof module.exports === 'object') {
  2335. module.exports = dagre;
  2336. }