@ac-kit/math-graph 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (88) hide show
  1. package/CHANGELOG.md +183 -0
  2. package/LICENSE +28 -0
  3. package/README.md +118 -2
  4. package/dist/index.d.ts +12 -0
  5. package/dist/index.d.ts.map +1 -0
  6. package/dist/index.js +11 -0
  7. package/dist/index.js.map +1 -0
  8. package/dist/layout/_force-forces.d.ts +227 -0
  9. package/dist/layout/_force-forces.d.ts.map +1 -0
  10. package/dist/layout/_force-forces.js +1572 -0
  11. package/dist/layout/_force-forces.js.map +1 -0
  12. package/dist/layout/_hierarchy-table.d.ts +34 -0
  13. package/dist/layout/_hierarchy-table.d.ts.map +1 -0
  14. package/dist/layout/_hierarchy-table.js +131 -0
  15. package/dist/layout/_hierarchy-table.js.map +1 -0
  16. package/dist/layout/_index-graph.d.ts +32 -0
  17. package/dist/layout/_index-graph.d.ts.map +1 -0
  18. package/dist/layout/_index-graph.js +51 -0
  19. package/dist/layout/_index-graph.js.map +1 -0
  20. package/dist/layout/_layer-order.d.ts +138 -0
  21. package/dist/layout/_layer-order.d.ts.map +1 -0
  22. package/dist/layout/_layer-order.js +954 -0
  23. package/dist/layout/_layer-order.js.map +1 -0
  24. package/dist/layout/_layered-acyclic.d.ts +28 -0
  25. package/dist/layout/_layered-acyclic.d.ts.map +1 -0
  26. package/dist/layout/_layered-acyclic.js +179 -0
  27. package/dist/layout/_layered-acyclic.js.map +1 -0
  28. package/dist/layout/_layered-position.d.ts +56 -0
  29. package/dist/layout/_layered-position.d.ts.map +1 -0
  30. package/dist/layout/_layered-position.js +369 -0
  31. package/dist/layout/_layered-position.js.map +1 -0
  32. package/dist/layout/_layered-rank.d.ts +58 -0
  33. package/dist/layout/_layered-rank.d.ts.map +1 -0
  34. package/dist/layout/_layered-rank.js +529 -0
  35. package/dist/layout/_layered-rank.js.map +1 -0
  36. package/dist/layout/_tree-common.d.ts +38 -0
  37. package/dist/layout/_tree-common.d.ts.map +1 -0
  38. package/dist/layout/_tree-common.js +73 -0
  39. package/dist/layout/_tree-common.js.map +1 -0
  40. package/dist/layout/_treemap-tiling.d.ts +73 -0
  41. package/dist/layout/_treemap-tiling.d.ts.map +1 -0
  42. package/dist/layout/_treemap-tiling.js +247 -0
  43. package/dist/layout/_treemap-tiling.js.map +1 -0
  44. package/dist/layout/circular-layout.d.ts +27 -0
  45. package/dist/layout/circular-layout.d.ts.map +1 -0
  46. package/dist/layout/circular-layout.js +35 -0
  47. package/dist/layout/circular-layout.js.map +1 -0
  48. package/dist/layout/create-force-step.d.ts +127 -0
  49. package/dist/layout/create-force-step.d.ts.map +1 -0
  50. package/dist/layout/create-force-step.js +167 -0
  51. package/dist/layout/create-force-step.js.map +1 -0
  52. package/dist/layout/dendrogram-layout.d.ts +32 -0
  53. package/dist/layout/dendrogram-layout.d.ts.map +1 -0
  54. package/dist/layout/dendrogram-layout.js +110 -0
  55. package/dist/layout/dendrogram-layout.js.map +1 -0
  56. package/dist/layout/force-directed-layout.d.ts +42 -0
  57. package/dist/layout/force-directed-layout.d.ts.map +1 -0
  58. package/dist/layout/force-directed-layout.js +112 -0
  59. package/dist/layout/force-directed-layout.js.map +1 -0
  60. package/dist/layout/layered-layout.d.ts +109 -0
  61. package/dist/layout/layered-layout.d.ts.map +1 -0
  62. package/dist/layout/layered-layout.js +124 -0
  63. package/dist/layout/layered-layout.js.map +1 -0
  64. package/dist/layout/partition-layout.d.ts +31 -0
  65. package/dist/layout/partition-layout.d.ts.map +1 -0
  66. package/dist/layout/partition-layout.js +78 -0
  67. package/dist/layout/partition-layout.js.map +1 -0
  68. package/dist/layout/phyllotaxis-layout.d.ts +17 -0
  69. package/dist/layout/phyllotaxis-layout.d.ts.map +1 -0
  70. package/dist/layout/phyllotaxis-layout.js +32 -0
  71. package/dist/layout/phyllotaxis-layout.js.map +1 -0
  72. package/dist/layout/sankey-layout.d.ts +113 -0
  73. package/dist/layout/sankey-layout.d.ts.map +1 -0
  74. package/dist/layout/sankey-layout.js +641 -0
  75. package/dist/layout/sankey-layout.js.map +1 -0
  76. package/dist/layout/tidy-tree-layout.d.ts +25 -0
  77. package/dist/layout/tidy-tree-layout.d.ts.map +1 -0
  78. package/dist/layout/tidy-tree-layout.js +197 -0
  79. package/dist/layout/tidy-tree-layout.js.map +1 -0
  80. package/dist/layout/treemap-layout.d.ts +63 -0
  81. package/dist/layout/treemap-layout.d.ts.map +1 -0
  82. package/dist/layout/treemap-layout.js +126 -0
  83. package/dist/layout/treemap-layout.js.map +1 -0
  84. package/dist/layout/types.d.ts +90 -0
  85. package/dist/layout/types.d.ts.map +1 -0
  86. package/dist/layout/types.js +2 -0
  87. package/dist/layout/types.js.map +1 -0
  88. package/package.json +68 -3
@@ -0,0 +1,954 @@
1
+ import { groupIndices, sortedIndices } from "@ac-kit/algo";
2
+ import { binaryExponent, compareNaturalAscending, compareNaturalDescending, describeValue, isIntegerInRange, nextAfter, runToCompletion, scaleByPowerOfTwoInPlace, } from "@ac-kit/core";
3
+ import { DotExactAccumulator, twoProductError, twoSumError, } from "@ac-kit/math-scalar";
4
+ const EFFORTS_ = ["fast", "thorough"];
5
+ const DEFAULT_PATIENCE = 4;
6
+ // Each pass is charged to the budget; a pass that still swaps is rare past a few.
7
+ const TRANSPOSE_PASSES = 8;
8
+ /**
9
+ * Segments grouped by `groupOf`, each group listing its segments by ascending
10
+ * neighbour key (then segment index), so nothing depends on link order. The key
11
+ * of a neighbour vertex is the vertex itself, or `keys[vertex]` below
12
+ * `keyCount` (its position in its layer, say).
13
+ */
14
+ export function groupByNeighbour(vertexCount, groupOf, neighbourOf, keys, keyCount = vertexCount) {
15
+ const byNeighbour = groupIndices(neighbourOf, keys === undefined
16
+ ? (neighbour) => neighbour
17
+ : (neighbour) => keys[neighbour], keyCount).indices;
18
+ const permutedGroups = new Uint32Array(byNeighbour.length);
19
+ for (let index = 0; index < byNeighbour.length; index++) {
20
+ permutedGroups[index] = groupOf[byNeighbour[index]];
21
+ }
22
+ const { offsets, indices } = groupIndices(permutedGroups, (group) => group, vertexCount);
23
+ for (let index = 0; index < indices.length; index++) {
24
+ indices[index] = byNeighbour[indices[index]];
25
+ }
26
+ return { offsets, indices };
27
+ }
28
+ /**
29
+ * Weighted number of crossings between two adjacent layers. Edge `i` joins
30
+ * position `lower[i]` of the lower layer to position `upper[i]` of the upper
31
+ * one; two edges cross when their positions are in opposite orders, and edges
32
+ * sharing an endpoint never cross. Barth, Jünger and Mutzel (2004): edges
33
+ * sorted by lower then upper position, and an accumulator tree over the upper
34
+ * positions counts, for each edge, the weight of the earlier edges that end to
35
+ * its right. The result is the exact weighted count `Σ wᵢ · wⱼ` over the
36
+ * crossing pairs rounded once (ties to even), for any finite weights ≥ 0:
37
+ * `Infinity` only when that rounding overflows.
38
+ *
39
+ * Integer weights whose total stays within 2^26 count in plain arithmetic,
40
+ * which is then exact. Weights from 2^−400 to 2^400 count in doubled precision
41
+ * (the tree's sums, the products and the total compensated by TwoSum and
42
+ * TwoProduct), with a rigorous bound on what that loses: the nearest double to
43
+ * the computed count is returned wherever the bound keeps the exact count on
44
+ * the same side of every midpoint between doubles. Where it does not, or for
45
+ * other weights, the weights are split into bands of exponents narrow enough
46
+ * that the tree's sums of one band are integers below 2^104 in units of the
47
+ * band's last place, held exactly in two 52-bit parts; one pass per band feeds
48
+ * every edge's weight times its sum into a long accumulator
49
+ * (`DotExactAccumulator`), rounded once at the end. A band spans `52 −
50
+ * ⌈log₂(edges + 1)⌉` binades, so there is one for weights within that span of
51
+ * one another, and a bounded number (the 2 098 binades over that span) for
52
+ * any.
53
+ *
54
+ * Complexity: O(edges + lowerSize + upperSize + edges · log upperSize) for
55
+ * moderate weights away from a midpoint, and O(bands · edges · log upperSize)
56
+ * for the exact passes, `bands` the number of bands the weights fall in.
57
+ */
58
+ export function countBilayerCrossings(lower, upper, lowerSize, upperSize, weights) {
59
+ const edgeCount = lower.length;
60
+ if (edgeCount < 2) {
61
+ return 0;
62
+ }
63
+ // Two stable counting sorts: by upper position, then by lower position.
64
+ const byUpper = groupIndices(upper, (position) => position, upperSize).indices;
65
+ const lowerByUpper = new Uint32Array(edgeCount);
66
+ for (let rank = 0; rank < edgeCount; rank++) {
67
+ lowerByUpper[rank] = lower[byUpper[rank]];
68
+ }
69
+ const byLower = groupIndices(lowerByUpper, (position) => position, lowerSize).indices;
70
+ let leafCount = 1;
71
+ while (leafCount < upperSize) {
72
+ leafCount *= 2;
73
+ }
74
+ const firstLeaf = leafCount - 1;
75
+ const edgeWeights = new Float64Array(edgeCount);
76
+ let total = 0;
77
+ let isIntegral = true;
78
+ let isFinite = true;
79
+ let isModerate = true;
80
+ for (let edge = 0; edge < edgeCount; edge++) {
81
+ const weight = weights === undefined ? 1 : +weights[edge];
82
+ edgeWeights[edge] = weight;
83
+ total += weight;
84
+ isIntegral &&= Number.isInteger(weight);
85
+ isFinite &&= weight - weight === 0;
86
+ isModerate &&=
87
+ weight === 0 || (weight >= MODERATE_MIN_ && weight <= MODERATE_MAX_);
88
+ }
89
+ if (!isFinite) {
90
+ // A weight that is NaN or infinite.
91
+ return Number.NaN;
92
+ }
93
+ // Weight sums per tree node: the band's high parts in the exact passes.
94
+ const tree = new Float64Array(2 * leafCount - 1);
95
+ if (isIntegral && total <= PLAIN_TOTAL_MAX_) {
96
+ // Every sum and product an integer below 2⁵³: exact as it comes.
97
+ let crossings = 0;
98
+ for (let rank = 0; rank < edgeCount; rank++) {
99
+ const edge = byUpper[byLower[rank]];
100
+ const weight = edgeWeights[edge];
101
+ let node = upper[edge] + firstLeaf;
102
+ tree[node] += weight;
103
+ let rightWeight = 0;
104
+ while (node > 0) {
105
+ if (node % 2 === 1) {
106
+ rightWeight += tree[node + 1];
107
+ }
108
+ node = (node - 1) >> 1;
109
+ tree[node] += weight;
110
+ }
111
+ crossings += weight * rightWeight;
112
+ }
113
+ return crossings;
114
+ }
115
+ if (isModerate) {
116
+ // Compensated: the tree's sums, the products and the total in doubled
117
+ // precision (TwoSum, TwoProduct). Every term is ≥ 0, so what that loses
118
+ // is below 8 (edges + depth + 2)² u² of the total (u = 2^−53; Higham,
119
+ // "Accuracy and Stability of Numerical Algorithms", §4.3, for each
120
+ // compensated sum), with no product below 2^−800 to underflow. The count
121
+ // rounds to the double nearest the computed one unless the exact one may
122
+ // lie across a midpoint between doubles; then the exact passes decide.
123
+ const low = new Float64Array(2 * leafCount - 1);
124
+ let crossings = 0;
125
+ let dropped = 0;
126
+ for (let rank = 0; rank < edgeCount; rank++) {
127
+ const edge = byUpper[byLower[rank]];
128
+ const weight = edgeWeights[edge];
129
+ let node = upper[edge] + firstLeaf;
130
+ let rightWeight = 0;
131
+ let rightError = 0;
132
+ for (;;) {
133
+ const nodeSum = tree[node] + weight;
134
+ low[node] += twoSumError(tree[node], weight, nodeSum);
135
+ tree[node] = nodeSum;
136
+ if (node === 0) {
137
+ break;
138
+ }
139
+ if (node % 2 === 1) {
140
+ const sibling = tree[node + 1];
141
+ const rightSum = rightWeight + sibling;
142
+ rightError +=
143
+ twoSumError(rightWeight, sibling, rightSum) + low[node + 1];
144
+ rightWeight = rightSum;
145
+ }
146
+ node = (node - 1) >> 1;
147
+ }
148
+ const product = weight * rightWeight;
149
+ const sum = crossings + product;
150
+ dropped +=
151
+ twoProductError(weight, rightWeight, product) +
152
+ twoSumError(crossings, product, sum) +
153
+ weight * rightError;
154
+ crossings = sum;
155
+ }
156
+ const result = crossings + dropped;
157
+ const residual = crossings - result + dropped;
158
+ const depth = Math.log2(leafCount);
159
+ const bound = 8 *
160
+ ((edgeCount + depth + 2) * UNIT_ROUNDOFF_) ** 2 *
161
+ result *
162
+ (1 + UNIT_ROUNDOFF_);
163
+ // The gap to the next double on the residual's side, halved: the exact
164
+ // count lies on the same side of that midpoint.
165
+ const gap = residual >= 0
166
+ ? nextAfter(result, Infinity) - result
167
+ : result - nextAfter(result, 0);
168
+ if (Math.abs(residual) * (1 + 2 * UNIT_ROUNDOFF_) + bound < gap / 2) {
169
+ return result;
170
+ }
171
+ tree.fill(0);
172
+ }
173
+ // The band of a weight w > 0 of leading exponent t: ⌊(t + 1074) / width⌋.
174
+ // The weights of a band are integers below 2^(width + 52) in units of
175
+ // 2^g, g its least exponent less 52, so any sum of them is below 2^104.
176
+ const width = BAND_BITS_ - Math.ceil(Math.log2(edgeCount + 1));
177
+ const bands = new Uint8Array(Math.ceil(EXPONENT_SPAN_ / width) + 1);
178
+ for (let edge = 0; edge < edgeCount; edge++) {
179
+ const weight = edgeWeights[edge];
180
+ if (weight > 0) {
181
+ bands[Math.floor((binaryExponent(weight) + 1074) / width)] = 1;
182
+ }
183
+ }
184
+ const low = new Float64Array(2 * leafCount - 1);
185
+ const sum = CROSSINGS_;
186
+ const left = PRODUCT_LEFT_;
187
+ const right = PRODUCT_RIGHT_;
188
+ const units = UNITS_;
189
+ sum.reset();
190
+ for (let band = 0; band < bands.length; band++) {
191
+ if (bands[band] === 0) {
192
+ continue;
193
+ }
194
+ const unitExponent = Math.max(-1074 + band * width - 52, -1074);
195
+ tree.fill(0);
196
+ low.fill(0);
197
+ let pending = 0;
198
+ for (let rank = 0; rank < edgeCount; rank++) {
199
+ const edge = byUpper[byLower[rank]];
200
+ const weight = edgeWeights[edge];
201
+ if (weight === 0) {
202
+ continue;
203
+ }
204
+ // This band's weight in its units, as two 52-bit parts; 0 for another.
205
+ let high = 0;
206
+ let rest = 0;
207
+ if (Math.floor((binaryExponent(weight) + 1074) / width) === band) {
208
+ units[0] = weight;
209
+ scaleByPowerOfTwoInPlace(units, 0, -unitExponent);
210
+ high = Math.floor(units[0] * LIMB_INVERSE_);
211
+ rest = units[0] - high * LIMB_;
212
+ }
213
+ let node = upper[edge] + firstLeaf;
214
+ let rightHigh = 0;
215
+ let rightLow = 0;
216
+ for (;;) {
217
+ if (high !== 0 || rest !== 0) {
218
+ // Integers below 2⁵³ throughout: exact.
219
+ let sumLow = low[node] + rest;
220
+ let sumHigh = tree[node] + high;
221
+ if (sumLow >= LIMB_) {
222
+ sumLow -= LIMB_;
223
+ sumHigh += 1;
224
+ }
225
+ low[node] = sumLow;
226
+ tree[node] = sumHigh;
227
+ }
228
+ if (node === 0) {
229
+ break;
230
+ }
231
+ if (node % 2 === 1) {
232
+ rightLow += low[node + 1];
233
+ rightHigh += tree[node + 1];
234
+ if (rightLow >= LIMB_) {
235
+ rightLow -= LIMB_;
236
+ rightHigh += 1;
237
+ }
238
+ }
239
+ node = (node - 1) >> 1;
240
+ }
241
+ if (rightHigh === 0 && rightLow === 0) {
242
+ continue;
243
+ }
244
+ left[pending] = weight;
245
+ right[pending] = rightHigh * LIMB_;
246
+ left[pending + 1] = weight;
247
+ right[pending + 1] = rightLow;
248
+ pending += 2;
249
+ if (pending === left.length) {
250
+ sum.addProducts(left, right, unitExponent);
251
+ pending = 0;
252
+ }
253
+ }
254
+ if (pending > 0) {
255
+ left.fill(0, pending);
256
+ sum.addProducts(left, right, unitExponent);
257
+ }
258
+ }
259
+ sum.writeValue(units, 0);
260
+ return units[0];
261
+ }
262
+ /** Integral weights up to this total count exactly in plain arithmetic. */
263
+ const PLAIN_TOTAL_MAX_ = 2 ** 26;
264
+ /** The unit roundoff, 2^−53. */
265
+ const UNIT_ROUNDOFF_ = 2 ** -53;
266
+ /**
267
+ * Weights the compensated pass takes: their products and sums neither underflow
268
+ * nor overflow.
269
+ */
270
+ const MODERATE_MIN_ = 2 ** -400;
271
+ const MODERATE_MAX_ = 2 ** 400;
272
+ /**
273
+ * The bits of a band's weights in its units and of the log of the edge count
274
+ * together: the sums of a band then stay below 2^104, two 52-bit parts.
275
+ */
276
+ const BAND_BITS_ = 52;
277
+ /** The leading exponents a positive double can have, −1074 to 1023. */
278
+ const EXPONENT_SPAN_ = 2098;
279
+ /** One 52-bit part of a band's sum, and its inverse. */
280
+ const LIMB_ = 2 ** 52;
281
+ const LIMB_INVERSE_ = 2 ** -52;
282
+ /** The weighted crossings of {@link countBilayerCrossings}, exactly. */
283
+ const CROSSINGS_ = new DotExactAccumulator();
284
+ /** Products waiting for {@link CROSSINGS_}: weights, and sums of a band. */
285
+ const PRODUCT_LEFT_ = new Float64Array(128);
286
+ const PRODUCT_RIGHT_ = new Float64Array(128);
287
+ /** A weight scaled to its band's units, and then the result. */
288
+ const UNITS_ = new Float64Array(1);
289
+ /**
290
+ * Orders the vertices of each layer to reduce crossings. Layers are the given
291
+ * ranks and need not be contiguous; a link joins its endpoints of different
292
+ * rank, whichever the direction (reversed links included), through one dummy
293
+ * per intermediate layer. Self-loops and links between equal ranks are left
294
+ * out.
295
+ *
296
+ * The initial order is the pre-order of a depth-first search from the vertices
297
+ * by layer, then index (Gansner et al. 1993). Sweeps alternate down and up;
298
+ * each sweep reorders a layer by the weighted barycentre of its neighbours in
299
+ * the fixed adjacent layer (Sugiyama, Tagawa and Toda 1981), a vertex with no
300
+ * neighbour there keeping its slot, ties alternating between the current and
301
+ * the reversed order to leave plateaus. Transpose passes then swap adjacent
302
+ * vertices while that lowers the crossings, the gain of a swap compensated so
303
+ * that widely spread weights do not hide its sign, and the order before a
304
+ * transpose is kept when the count does not confirm it. With `"thorough"`
305
+ * effort (the default), sifting rounds and sweeps then alternate from the best
306
+ * order of each starting order while either lowers the count (Matuszewski,
307
+ * Schönfeld and Molitor 1999): each vertex in turn moves to the first slot of
308
+ * its layer with the fewest crossings, plateaus included, layer by layer down
309
+ * then up, until `patience` rounds find no fewer crossings. The fewest-crossing
310
+ * order seen is returned, so the result never has more crossings than the
311
+ * initial order, nor with `"thorough"` effort than with `"fast"`. The sweeps
312
+ * stop after `patience` sweeps without improvement, or at zero crossings;
313
+ * `patience` 0 leaves only the transposes.
314
+ *
315
+ * Complexity: O(V′ + E′) to build the layered graph, with D dummies V′ = V + D
316
+ * and E′ = E + D; each sweep and transpose pass O(E′ log V′); each sifting
317
+ * round O(Σ k · e) over the layers, k vertices and e segments at each.
318
+ *
319
+ * @throws {RangeError} A rank that is not a non-negative integer, a wrong
320
+ * `ranks` or `weights` length, a negative or non-finite weight, an invalid
321
+ * `patience` or `effort`.
322
+ */
323
+ export function orderLayers(graph, ranks, options) {
324
+ return runToCompletion(orderLayerSteps(graph, ranks, options));
325
+ }
326
+ /**
327
+ * {@link orderLayers} as steps: yields right after each budget charge (every
328
+ * sweep and every transpose pass), so a runner can stop or give up the thread
329
+ * between them. Returns the layered graph.
330
+ */
331
+ export function* orderLayerSteps(graph, ranks, options) {
332
+ const { nodeCount, linkCount, sources, targets } = graph;
333
+ const weights = options?.weights;
334
+ const patience = options?.patience ?? DEFAULT_PATIENCE;
335
+ const budget = options?.budget;
336
+ const effort = options?.effort ?? "thorough";
337
+ if (!EFFORTS_.includes(effort)) {
338
+ throw new RangeError(`orderLayers: effort must be "fast" or "thorough", got ${describeValue(effort)}`);
339
+ }
340
+ if (ranks.length !== nodeCount) {
341
+ throw new RangeError(`orderLayers: ranks has ${ranks.length} entries for ${nodeCount} nodes`);
342
+ }
343
+ if (weights !== undefined && weights.length !== linkCount) {
344
+ throw new RangeError(`orderLayers: weights has ${weights.length} entries for ${linkCount} links`);
345
+ }
346
+ if (!isIntegerInRange(patience, 0, 2 ** 32)) {
347
+ throw new RangeError(`orderLayers: patience must be a non-negative integer, got ${describeValue(patience)}`);
348
+ }
349
+ let layerCount = 0;
350
+ for (let node = 0; node < nodeCount; node++) {
351
+ const rank = ranks[node];
352
+ if (!isIntegerInRange(rank, 0, 2 ** 32 - 1)) {
353
+ throw new RangeError(`orderLayers: rank of node ${node} must be a non-negative integer, got ${describeValue(rank)}`);
354
+ }
355
+ layerCount = Math.max(layerCount, rank + 1);
356
+ }
357
+ if (weights !== undefined) {
358
+ for (let link = 0; link < linkCount; link++) {
359
+ const weight = weights[link];
360
+ if (!Number.isFinite(weight) || weight < 0) {
361
+ throw new RangeError(`orderLayers: weight of link ${link} must be finite and ≥ 0, got ${describeValue(weight)}`);
362
+ }
363
+ }
364
+ }
365
+ // Layered graph: chains of dummies and unit-span segments.
366
+ const chainStarts = new Uint32Array(linkCount + 1);
367
+ let dummyCount = 0;
368
+ let segmentCount = 0;
369
+ for (let link = 0; link < linkCount; link++) {
370
+ chainStarts[link] = dummyCount;
371
+ const span = Math.abs(ranks[targets[link]] - ranks[sources[link]]);
372
+ if (span > 0) {
373
+ dummyCount += span - 1;
374
+ segmentCount += span;
375
+ }
376
+ }
377
+ chainStarts[linkCount] = dummyCount;
378
+ const vertexCount = nodeCount + dummyCount;
379
+ const layerOf = new Uint32Array(vertexCount);
380
+ for (let node = 0; node < nodeCount; node++) {
381
+ layerOf[node] = ranks[node];
382
+ }
383
+ const segmentSources = new Uint32Array(segmentCount);
384
+ const segmentTargets = new Uint32Array(segmentCount);
385
+ const segmentLinks = new Uint32Array(segmentCount);
386
+ const segmentWeights = new Float64Array(segmentCount);
387
+ let segment = 0;
388
+ for (let link = 0; link < linkCount; link++) {
389
+ const first = sources[link];
390
+ const second = targets[link];
391
+ const lowRank = Math.min(ranks[first], ranks[second]);
392
+ const highRank = Math.max(ranks[first], ranks[second]);
393
+ if (lowRank === highRank) {
394
+ continue;
395
+ }
396
+ const low = ranks[first] < ranks[second] ? first : second;
397
+ const high = low === first ? second : first;
398
+ const weight = weights === undefined ? 1 : weights[link];
399
+ let previous = low;
400
+ for (let rank = lowRank + 1; rank <= highRank; rank++) {
401
+ let next = high;
402
+ if (rank < highRank) {
403
+ next = nodeCount + chainStarts[link] + (rank - lowRank - 1);
404
+ layerOf[next] = rank;
405
+ }
406
+ segmentSources[segment] = previous;
407
+ segmentTargets[segment] = next;
408
+ segmentLinks[segment] = link;
409
+ segmentWeights[segment] = weight;
410
+ segment++;
411
+ previous = next;
412
+ }
413
+ }
414
+ const outgoing = groupByNeighbour(vertexCount, segmentSources, segmentTargets);
415
+ const incoming = groupByNeighbour(vertexCount, segmentTargets, segmentSources);
416
+ const layers = groupIndices(layerOf, (layer) => layer, layerCount);
417
+ const layerStarts = layers.offsets;
418
+ const orders = new Uint32Array(vertexCount);
419
+ const current = new Uint32Array(vertexCount);
420
+ const backwardRoots = new Uint32Array(vertexCount);
421
+ for (let layer = layerCount - 1, filled = 0; layer >= 0; layer--) {
422
+ for (let slot = layerStarts[layer]; slot < layerStarts[layer + 1]; slot++) {
423
+ backwardRoots[filled++] = layers.indices[slot];
424
+ }
425
+ }
426
+ const startingOrders = [
427
+ initialOrder(vertexCount, layerStarts, layers.indices, layerOf, outgoing, segmentTargets),
428
+ initialOrder(vertexCount, layerStarts, backwardRoots, layerOf, incoming, segmentSources),
429
+ ];
430
+ function load(order) {
431
+ current.set(order);
432
+ for (let layer = 0; layer < layerCount; layer++) {
433
+ for (let slot = layerStarts[layer]; slot < layerStarts[layer + 1]; slot++) {
434
+ orders[current[slot]] = slot - layerStarts[layer];
435
+ }
436
+ }
437
+ }
438
+ const segmentLayer = new Uint32Array(segmentCount);
439
+ for (let index = 0; index < segmentCount; index++) {
440
+ segmentLayer[index] = layerOf[segmentSources[index]];
441
+ }
442
+ const segmentsByLayer = groupIndices(segmentLayer, (layer) => layer, layerCount);
443
+ function countCrossings() {
444
+ let total = 0;
445
+ for (let layer = 0; layer + 1 < layerCount; layer++) {
446
+ const begin = segmentsByLayer.offsets[layer];
447
+ const end = segmentsByLayer.offsets[layer + 1];
448
+ const lower = new Uint32Array(end - begin);
449
+ const upper = new Uint32Array(end - begin);
450
+ const weight = new Float64Array(end - begin);
451
+ for (let index = begin; index < end; index++) {
452
+ const edge = segmentsByLayer.indices[index];
453
+ lower[index - begin] = orders[segmentSources[edge]];
454
+ upper[index - begin] = orders[segmentTargets[edge]];
455
+ weight[index - begin] = segmentWeights[edge];
456
+ }
457
+ total += countBilayerCrossings(lower, upper, layerStarts[layer + 1] - layerStarts[layer], layerStarts[layer + 2] - layerStarts[layer + 1], weight);
458
+ }
459
+ return total;
460
+ }
461
+ const barycentre = new Float64Array(vertexCount);
462
+ function sweepLayer(layer, fromBelow, reverseTies, useMedian) {
463
+ const begin = layerStarts[layer];
464
+ const end = layerStarts[layer + 1];
465
+ const adjacency = fromBelow ? incoming : outgoing;
466
+ const neighbours = fromBelow ? segmentSources : segmentTargets;
467
+ const movable = [];
468
+ const slots = [];
469
+ for (let slot = begin; slot < end; slot++) {
470
+ const vertex = current[slot];
471
+ let weightSum = 0;
472
+ let positionSum = 0;
473
+ const positions = [];
474
+ for (let index = adjacency.offsets[vertex]; index < adjacency.offsets[vertex + 1]; index++) {
475
+ const edge = adjacency.indices[index];
476
+ weightSum += segmentWeights[edge];
477
+ positionSum += segmentWeights[edge] * orders[neighbours[edge]];
478
+ positions.push(orders[neighbours[edge]]);
479
+ }
480
+ if (weightSum > 0) {
481
+ barycentre[vertex] = useMedian
482
+ ? medianOf(positions)
483
+ : positionSum / weightSum;
484
+ movable.push(vertex);
485
+ slots.push(slot);
486
+ }
487
+ }
488
+ const sorted = sortedIndices(movable, (left, right) => {
489
+ const difference = barycentre[left] - barycentre[right];
490
+ if (difference !== 0) {
491
+ return difference < 0 ? -1 : 1;
492
+ }
493
+ return reverseTies
494
+ ? compareNaturalDescending(orders[left], orders[right])
495
+ : compareNaturalAscending(orders[left], orders[right]);
496
+ });
497
+ for (let rank = 0; rank < sorted.length; rank++) {
498
+ const vertex = movable[sorted[rank]];
499
+ current[slots[rank]] = vertex;
500
+ }
501
+ for (let slot = begin; slot < end; slot++) {
502
+ orders[current[slot]] = slot - begin;
503
+ }
504
+ }
505
+ // Gansner et al. 1993: swap adjacent vertices while it lowers the crossings
506
+ // they have with the neighbours in both adjacent layers. Per pair, the
507
+ // crossings come from one merge of the two sorted neighbour lists, so the
508
+ // cost is O(degrees) and parallel links add no quadratic term. The lists of
509
+ // a layer are sorted by neighbour position when the layer is visited: moves
510
+ // within a layer leave them valid, moves in an adjacent layer do not.
511
+ const sortedIncoming = incoming.indices.slice();
512
+ const sortedOutgoing = outgoing.indices.slice();
513
+ const byIncomingNeighbour = (first, second) => orders[segmentSources[first]] - orders[segmentSources[second]] ||
514
+ first - second;
515
+ const byOutgoingNeighbour = (first, second) => orders[segmentTargets[first]] - orders[segmentTargets[second]] ||
516
+ first - second;
517
+ function sortLayerEdges(layer) {
518
+ for (let slot = layerStarts[layer]; slot < layerStarts[layer + 1]; slot++) {
519
+ const vertex = current[slot];
520
+ let begin = incoming.offsets[vertex];
521
+ let end = incoming.offsets[vertex + 1];
522
+ if (end - begin > 1) {
523
+ sortedIncoming.subarray(begin, end).sort(byIncomingNeighbour);
524
+ }
525
+ begin = outgoing.offsets[vertex];
526
+ end = outgoing.offsets[vertex + 1];
527
+ if (end - begin > 1) {
528
+ sortedOutgoing.subarray(begin, end).sort(byOutgoingNeighbour);
529
+ }
530
+ }
531
+ }
532
+ // Adds, into `gain` (sum, then dropped error), the weight of the crossings
533
+ // of `left` placed before `right` minus that of `right` before `left`, over
534
+ // one adjacent layer, from edge lists sorted by `sortLayerEdges`. The
535
+ // weights of `right`'s edges below and above each of `left`'s are summed
536
+ // directly, from either end, never as a total minus a prefix that would
537
+ // cancel; the products and their sum are compensated (TwoProduct and
538
+ // TwoSum), so the sign is that of the true gain unless it lies within a few
539
+ // ulps of the doubled-precision result.
540
+ function addPairGain(left, right, offsets, sorted, neighbours, gain) {
541
+ const leftBegin = offsets[left];
542
+ const leftEnd = offsets[left + 1];
543
+ const rightBegin = offsets[right];
544
+ const rightEnd = offsets[right + 1];
545
+ let below = 0;
546
+ let belowError = 0;
547
+ let lower = rightBegin;
548
+ for (let index = leftBegin; index < leftEnd; index++) {
549
+ const edge = sorted[index];
550
+ const position = orders[neighbours[edge]];
551
+ while (lower < rightEnd &&
552
+ orders[neighbours[sorted[lower]]] < position) {
553
+ const weight = segmentWeights[sorted[lower++]];
554
+ const sum = below + weight;
555
+ belowError += twoSumError(below, weight, sum);
556
+ below = sum;
557
+ }
558
+ addProduct(gain, segmentWeights[edge], below, belowError);
559
+ }
560
+ let above = 0;
561
+ let aboveError = 0;
562
+ let upper = rightEnd - 1;
563
+ for (let index = leftEnd - 1; index >= leftBegin; index--) {
564
+ const edge = sorted[index];
565
+ const position = orders[neighbours[edge]];
566
+ while (upper >= rightBegin &&
567
+ orders[neighbours[sorted[upper]]] > position) {
568
+ const weight = segmentWeights[sorted[upper--]];
569
+ const sum = above + weight;
570
+ aboveError += twoSumError(above, weight, sum);
571
+ above = sum;
572
+ }
573
+ addProduct(gain, -segmentWeights[edge], above, aboveError);
574
+ }
575
+ }
576
+ // Adds factor · (weight + weightError) into the compensated `gain`.
577
+ function addProduct(gain, factor, weight, weightError) {
578
+ const product = factor * weight;
579
+ const sum = gain[0] + product;
580
+ gain[1] +=
581
+ twoProductError(factor, weight, product) +
582
+ twoSumError(gain[0], product, sum) +
583
+ factor * weightError;
584
+ gain[0] = sum;
585
+ }
586
+ const gainScratch = new Float64Array(2);
587
+ function pairGain(left, right) {
588
+ gainScratch[0] = 0;
589
+ gainScratch[1] = 0;
590
+ addPairGain(left, right, incoming.offsets, sortedIncoming, segmentSources, gainScratch);
591
+ addPairGain(left, right, outgoing.offsets, sortedOutgoing, segmentTargets, gainScratch);
592
+ return gainScratch[0] + gainScratch[1];
593
+ }
594
+ function* transpose() {
595
+ for (let pass = 0; pass < TRANSPOSE_PASSES; pass++) {
596
+ budget?.spend(vertexCount + segmentCount);
597
+ yield;
598
+ let improved = false;
599
+ for (let layer = 0; layer < layerCount; layer++) {
600
+ sortLayerEdges(layer);
601
+ const begin = layerStarts[layer];
602
+ for (let slot = begin; slot + 1 < layerStarts[layer + 1]; slot++) {
603
+ const left = current[slot];
604
+ const right = current[slot + 1];
605
+ if (pairGain(left, right) > 0) {
606
+ current[slot] = right;
607
+ current[slot + 1] = left;
608
+ orders[right] = slot - begin;
609
+ orders[left] = slot + 1 - begin;
610
+ improved = true;
611
+ }
612
+ }
613
+ }
614
+ if (!improved) {
615
+ return;
616
+ }
617
+ }
618
+ }
619
+ // Transposes, then keeps whichever of the orders before and after has fewer
620
+ // crossings: a swap is decided on its local gain, which a count of the whole
621
+ // order, rounded otherwise, may not confirm. Returns the kept crossings.
622
+ function* transposeKeepingBetter() {
623
+ const before = countCrossings();
624
+ const saved = current.slice();
625
+ yield* transpose();
626
+ const after = countCrossings();
627
+ if ((yield* compareWith(saved, after, before)) <= 0) {
628
+ return after;
629
+ }
630
+ load(saved);
631
+ return before;
632
+ }
633
+ // Each layer pair's count is rounded once, and the pairs are summed: two
634
+ // counts within this many units of the larger's last place may be in
635
+ // either order, which an exact comparison then decides.
636
+ const tieEpsilons = 2 * (layerCount + 2);
637
+ // Integer weights count exactly while the total stays below 2⁵³.
638
+ const areWeightsIntegers = segmentWeights.every(Number.isInteger);
639
+ let exactWork = 0;
640
+ for (let layer = 0; layer + 1 < layerCount; layer++) {
641
+ const count = segmentsByLayer.offsets[layer + 1] - segmentsByLayer.offsets[layer];
642
+ exactWork += count * count;
643
+ }
644
+ const exactSum = new DotExactAccumulator();
645
+ const exactLeft = new Float64Array(1);
646
+ const exactRight = new Float64Array(1);
647
+ const exactValue = new Float64Array(1);
648
+ const exactScratch = new Uint32Array(vertexCount);
649
+ /** Set when a sweep or sifting phase keeps an order with fewer crossings. */
650
+ let improved = false;
651
+ // Adds `sign` times the weighted crossings of the loaded order to
652
+ // `exactSum`, every pair's product exactly, at any magnitude.
653
+ function addExactCrossings(sign) {
654
+ const { offsets, indices } = segmentsByLayer;
655
+ for (let layer = 0; layer + 1 < layerCount; layer++) {
656
+ for (let first = offsets[layer]; first < offsets[layer + 1]; first++) {
657
+ const edge = indices[first];
658
+ const lower = orders[segmentSources[edge]];
659
+ const upper = orders[segmentTargets[edge]];
660
+ const weight = sign * segmentWeights[edge];
661
+ for (let second = first + 1; second < offsets[layer + 1]; second++) {
662
+ const other = indices[second];
663
+ const lowerOther = orders[segmentSources[other]];
664
+ const upperOther = orders[segmentTargets[other]];
665
+ if ((lower < lowerOther && upper > upperOther) ||
666
+ (lower > lowerOther && upper < upperOther)) {
667
+ exactLeft[0] = weight;
668
+ exactRight[0] = segmentWeights[other];
669
+ exactSum.addProducts(exactLeft, exactRight);
670
+ }
671
+ }
672
+ }
673
+ }
674
+ }
675
+ // Sign of the loaded order's crossings minus those of `reference`, from
676
+ // their counts unless rounding could decide it, then exactly: the pairs of
677
+ // both orders summed with opposite signs, rounded once. Charged the pairs
678
+ // it compares.
679
+ function* compareWith(reference, crossings, referenceCrossings) {
680
+ const gap = crossings - referenceCrossings;
681
+ const scale = Math.max(crossings, referenceCrossings);
682
+ if (Math.abs(gap) > tieEpsilons * Number.EPSILON * scale ||
683
+ (areWeightsIntegers && scale < 2 ** 53)) {
684
+ return gap > 0 ? 1 : gap < 0 ? -1 : 0;
685
+ }
686
+ budget?.spend(2 * exactWork + vertexCount);
687
+ yield;
688
+ exactSum.reset();
689
+ addExactCrossings(1);
690
+ exactScratch.set(current);
691
+ load(reference);
692
+ addExactCrossings(-1);
693
+ load(exactScratch);
694
+ exactSum.writeValue(exactValue, 0);
695
+ const difference = exactValue[0];
696
+ return difference > 0 ? 1 : difference < 0 ? -1 : 0;
697
+ }
698
+ let widestLayer = 0;
699
+ for (let layer = 0; layer < layerCount; layer++) {
700
+ widestLayer = Math.max(widestLayer, layerStarts[layer + 1] - layerStarts[layer]);
701
+ }
702
+ const degreeOf = (vertex) => incoming.offsets[vertex + 1] -
703
+ incoming.offsets[vertex] +
704
+ outgoing.offsets[vertex + 1] -
705
+ outgoing.offsets[vertex];
706
+ const byDegree = (first, second) => degreeOf(second) - degreeOf(first) || orders[first] - orders[second];
707
+ // Per slot of the sifted vertex: its crossings with the rest of its layer,
708
+ // relative to the first slot, as a sum and its dropped error (TwoSum).
709
+ const siftCosts = new Float64Array(widestLayer + 1);
710
+ const siftErrors = new Float64Array(widestLayer + 1);
711
+ const siftOthers = new Uint32Array(widestLayer);
712
+ const siftSequence = new Uint32Array(widestLayer);
713
+ // Sifting (Matuszewski, Schönfeld and Molitor, "Using sifting for k-layer
714
+ // straightline crossing minimization", GD 1999): each vertex of the layer,
715
+ // by decreasing degree, is taken out and put back in the first slot of
716
+ // fewest crossings with the rest of its layer, over both adjacent layers, so
717
+ // it also moves along plateaus of equal count, which lets later moves leave
718
+ // the minimum. Moving it past another vertex changes the
719
+ // crossings by minus their pair gain, which does not depend on where either
720
+ // stands in the layer, so one scan prices every slot: O(k · e) for k
721
+ // vertices and e segments at the layer.
722
+ function* siftLayer(layer) {
723
+ const begin = layerStarts[layer];
724
+ const end = layerStarts[layer + 1];
725
+ const size = end - begin;
726
+ if (size < 2) {
727
+ return;
728
+ }
729
+ let layerSegments = 0;
730
+ for (let slot = begin; slot < end; slot++) {
731
+ layerSegments += degreeOf(current[slot]);
732
+ }
733
+ budget?.spend(size * (size + 2 * layerSegments));
734
+ yield;
735
+ sortLayerEdges(layer);
736
+ const sequence = siftSequence.subarray(0, size);
737
+ sequence.set(current.subarray(begin, end));
738
+ sequence.sort(byDegree);
739
+ for (let rank = 0; rank < size; rank++) {
740
+ const vertex = sequence[rank];
741
+ const from = orders[vertex];
742
+ let others = 0;
743
+ let cost = 0;
744
+ let costError = 0;
745
+ siftCosts[0] = 0;
746
+ siftErrors[0] = 0;
747
+ for (let slot = begin; slot < end; slot++) {
748
+ const other = current[slot];
749
+ if (other === vertex) {
750
+ continue;
751
+ }
752
+ siftOthers[others++] = other;
753
+ const step = -pairGain(vertex, other);
754
+ const sum = cost + step;
755
+ costError += twoSumError(cost, step, sum);
756
+ cost = sum;
757
+ siftCosts[others] = cost;
758
+ siftErrors[others] = costError;
759
+ }
760
+ let to = 0;
761
+ for (let index = 1; index <= others; index++) {
762
+ if (siftCosts[index] -
763
+ siftCosts[to] +
764
+ (siftErrors[index] - siftErrors[to]) <
765
+ 0) {
766
+ to = index;
767
+ }
768
+ }
769
+ if (to === from) {
770
+ continue;
771
+ }
772
+ let slot = begin;
773
+ for (let index = 0; index <= others; index++) {
774
+ if (index === to) {
775
+ current[slot++] = vertex;
776
+ }
777
+ if (index < others) {
778
+ current[slot++] = siftOthers[index];
779
+ }
780
+ }
781
+ for (slot = begin; slot < end; slot++) {
782
+ orders[current[slot]] = slot - begin;
783
+ }
784
+ }
785
+ }
786
+ // Sifting rounds, every layer down then up, until `patience` rounds in a
787
+ // row find no fewer crossings in the whole order. Leaves the best order
788
+ // seen loaded and returns its crossings.
789
+ function* siftKeepingBetter(crossings) {
790
+ let kept = current.slice();
791
+ for (let sinceBest = 0; sinceBest < patience && crossings > 0; sinceBest++) {
792
+ for (let layer = 0; layer < layerCount; layer++) {
793
+ yield* siftLayer(layer);
794
+ }
795
+ for (let layer = layerCount - 2; layer >= 0; layer--) {
796
+ yield* siftLayer(layer);
797
+ }
798
+ budget?.spend(vertexCount + segmentCount);
799
+ yield;
800
+ const after = countCrossings();
801
+ if ((yield* compareWith(kept, after, crossings)) < 0) {
802
+ crossings = after;
803
+ kept = current.slice();
804
+ sinceBest = -1;
805
+ improved = true;
806
+ }
807
+ }
808
+ load(kept);
809
+ return crossings;
810
+ }
811
+ // Barycentre sweeps (Sugiyama et al.), then median sweeps (Eades and Wormald
812
+ // 1994) from the best order the first found, each followed by a transpose,
813
+ // from the loaded order of `crossings` crossings. Leaves the best order seen
814
+ // loaded and returns its crossings.
815
+ function* sweepPhase(crossings) {
816
+ let phaseBest = current.slice();
817
+ for (const useMedian of [false, true]) {
818
+ load(phaseBest);
819
+ let sinceBest = 0;
820
+ for (let sweep = 0; sinceBest < patience && crossings > 0; sweep++, sinceBest++) {
821
+ budget?.spend(vertexCount + segmentCount);
822
+ yield;
823
+ const reverseTies = sweep % 4 >= 2;
824
+ if (sweep % 2 === 1) {
825
+ for (let layer = 1; layer < layerCount; layer++) {
826
+ sweepLayer(layer, true, reverseTies, useMedian);
827
+ }
828
+ }
829
+ else {
830
+ for (let layer = layerCount - 2; layer >= 0; layer--) {
831
+ sweepLayer(layer, false, reverseTies, useMedian);
832
+ }
833
+ }
834
+ const swept = yield* transposeKeepingBetter();
835
+ if ((yield* compareWith(phaseBest, swept, crossings)) < 0) {
836
+ crossings = swept;
837
+ phaseBest = current.slice();
838
+ improved = true;
839
+ sinceBest = -1;
840
+ }
841
+ }
842
+ }
843
+ load(phaseBest);
844
+ return crossings;
845
+ }
846
+ let bestCrossings = Infinity;
847
+ let best = current;
848
+ // From each starting order: the sweep phase, then, with `"thorough"`
849
+ // effort, sifting and sweep phases in turn while either lowers the count:
850
+ // each leaves the local minima of the other. Every retention is decided on
851
+ // the exact weighted count where the rounded ones could mislead it.
852
+ for (const start of startingOrders) {
853
+ load(start);
854
+ let crossings = yield* transposeKeepingBetter();
855
+ crossings = yield* sweepPhase(crossings);
856
+ while (effort === "thorough" && crossings > 0) {
857
+ improved = false;
858
+ crossings = yield* siftKeepingBetter(crossings);
859
+ if (!improved) {
860
+ break;
861
+ }
862
+ improved = false;
863
+ crossings = yield* sweepPhase(crossings);
864
+ if (!improved) {
865
+ break;
866
+ }
867
+ }
868
+ if (bestCrossings === Infinity ||
869
+ (yield* compareWith(best, crossings, bestCrossings)) < 0) {
870
+ bestCrossings = crossings;
871
+ best = current.slice();
872
+ }
873
+ }
874
+ load(best);
875
+ return {
876
+ vertexCount,
877
+ layerCount,
878
+ layerOf,
879
+ orders,
880
+ layerStarts,
881
+ layerVertices: best,
882
+ chainStarts,
883
+ segmentCount,
884
+ segmentSources,
885
+ segmentTargets,
886
+ segmentLinks,
887
+ segmentWeights,
888
+ crossings: bestCrossings,
889
+ };
890
+ }
891
+ /**
892
+ * Median of neighbour positions, the weighted form of Eades and Wormald 1994
893
+ * for an even count above two (leaning to the denser side). Link weights are
894
+ * not used.
895
+ */
896
+ function medianOf(positions) {
897
+ positions.sort((left, right) => left - right);
898
+ const count = positions.length;
899
+ const middle = count >> 1;
900
+ if (count % 2 === 1) {
901
+ return positions[middle];
902
+ }
903
+ if (count === 2) {
904
+ return (positions[0] + positions[1]) / 2;
905
+ }
906
+ const leftSpan = positions[middle - 1] - positions[0];
907
+ const rightSpan = positions[count - 1] - positions[middle];
908
+ if (leftSpan + rightSpan === 0) {
909
+ return positions[middle];
910
+ }
911
+ return ((positions[middle - 1] * rightSpan + positions[middle] * leftSpan) /
912
+ (leftSpan + rightSpan));
913
+ }
914
+ /**
915
+ * Pre-order of an iterative depth-first search over the segments, started from
916
+ * the vertices by layer then index; each vertex is appended to its layer when
917
+ * first reached. Fills `orders` and returns the vertices grouped by layer.
918
+ */
919
+ function initialOrder(vertexCount, layerStarts, roots, layerOf, adjacency, neighbours) {
920
+ const result = new Uint32Array(vertexCount);
921
+ const filled = layerStarts.slice(0, layerStarts.length - 1);
922
+ const visited = new Uint8Array(vertexCount);
923
+ const stack = new Uint32Array(vertexCount);
924
+ const cursor = new Uint32Array(vertexCount);
925
+ function visit(vertex) {
926
+ visited[vertex] = 1;
927
+ result[filled[layerOf[vertex]]++] = vertex;
928
+ cursor[vertex] = adjacency.offsets[vertex];
929
+ }
930
+ for (let root = 0; root < roots.length; root++) {
931
+ const start = roots[root];
932
+ if (visited[start] === 1) {
933
+ continue;
934
+ }
935
+ let depth = 0;
936
+ stack[0] = start;
937
+ visit(start);
938
+ while (depth >= 0) {
939
+ const vertex = stack[depth];
940
+ if (cursor[vertex] < adjacency.offsets[vertex + 1]) {
941
+ const child = neighbours[adjacency.indices[cursor[vertex]++]];
942
+ if (visited[child] === 0) {
943
+ stack[++depth] = child;
944
+ visit(child);
945
+ }
946
+ }
947
+ else {
948
+ depth--;
949
+ }
950
+ }
951
+ }
952
+ return result;
953
+ }
954
+ //# sourceMappingURL=_layer-order.js.map