@ac-kit/math-graph 0.1.0 → 0.2.1

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 (37) hide show
  1. package/CHANGELOG.md +122 -0
  2. package/README.md +42 -16
  3. package/dist/layout/_force-forces.d.ts +140 -16
  4. package/dist/layout/_force-forces.d.ts.map +1 -1
  5. package/dist/layout/_force-forces.js +1204 -122
  6. package/dist/layout/_force-forces.js.map +1 -1
  7. package/dist/layout/_hierarchy-table.js.map +1 -1
  8. package/dist/layout/_layer-order.d.ts +52 -10
  9. package/dist/layout/_layer-order.d.ts.map +1 -1
  10. package/dist/layout/_layer-order.js +565 -73
  11. package/dist/layout/_layer-order.js.map +1 -1
  12. package/dist/layout/_layered-rank.d.ts +8 -4
  13. package/dist/layout/_layered-rank.d.ts.map +1 -1
  14. package/dist/layout/_layered-rank.js +113 -20
  15. package/dist/layout/_layered-rank.js.map +1 -1
  16. package/dist/layout/_treemap-tiling.d.ts +13 -2
  17. package/dist/layout/_treemap-tiling.d.ts.map +1 -1
  18. package/dist/layout/_treemap-tiling.js +70 -10
  19. package/dist/layout/_treemap-tiling.js.map +1 -1
  20. package/dist/layout/create-force-step.d.ts +39 -24
  21. package/dist/layout/create-force-step.d.ts.map +1 -1
  22. package/dist/layout/create-force-step.js +45 -12
  23. package/dist/layout/create-force-step.js.map +1 -1
  24. package/dist/layout/layered-layout.d.ts +15 -2
  25. package/dist/layout/layered-layout.d.ts.map +1 -1
  26. package/dist/layout/layered-layout.js +5 -1
  27. package/dist/layout/layered-layout.js.map +1 -1
  28. package/dist/layout/sankey-layout.d.ts +10 -1
  29. package/dist/layout/sankey-layout.d.ts.map +1 -1
  30. package/dist/layout/sankey-layout.js +5 -0
  31. package/dist/layout/sankey-layout.js.map +1 -1
  32. package/dist/layout/tidy-tree-layout.js.map +1 -1
  33. package/dist/layout/treemap-layout.d.ts +14 -5
  34. package/dist/layout/treemap-layout.d.ts.map +1 -1
  35. package/dist/layout/treemap-layout.js +13 -8
  36. package/dist/layout/treemap-layout.js.map +1 -1
  37. package/package.json +11 -9
@@ -1,5 +1,7 @@
1
1
  import { groupIndices, sortedIndices } from "@ac-kit/algo";
2
- import { compareNaturalAscending, compareNaturalDescending, describeValue, isIntegerInRange, runToCompletion, } from "@ac-kit/core";
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"];
3
5
  const DEFAULT_PATIENCE = 4;
4
6
  // Each pass is charged to the budget; a pass that still swaps is rare past a few.
5
7
  const TRANSPOSE_PASSES = 8;
@@ -30,9 +32,28 @@ export function groupByNeighbour(vertexCount, groupOf, neighbourOf, keys, keyCou
30
32
  * sharing an endpoint never cross. Barth, Jünger and Mutzel (2004): edges
31
33
  * sorted by lower then upper position, and an accumulator tree over the upper
32
34
  * positions counts, for each edge, the weight of the earlier edges that end to
33
- * its right.
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.
34
38
  *
35
- * Complexity: O(edges + lowerSize + upperSize + edges · log upperSize).
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.
36
57
  */
37
58
  export function countBilayerCrossings(lower, upper, lowerSize, upperSize, weights) {
38
59
  const edgeCount = lower.length;
@@ -51,25 +72,220 @@ export function countBilayerCrossings(lower, upper, lowerSize, upperSize, weight
51
72
  leafCount *= 2;
52
73
  }
53
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.
54
94
  const tree = new Float64Array(2 * leafCount - 1);
55
- let crossings = 0;
56
- for (let rank = 0; rank < edgeCount; rank++) {
57
- const edge = byUpper[byLower[rank]];
58
- const weight = weights === undefined ? 1 : weights[edge];
59
- let node = upper[edge] + firstLeaf;
60
- tree[node] += weight;
61
- let rightWeight = 0;
62
- while (node > 0) {
63
- if (node % 2 === 1) {
64
- rightWeight += tree[node + 1];
65
- }
66
- node = (node - 1) >> 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;
67
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;
68
170
  }
69
- crossings += weight * rightWeight;
171
+ tree.fill(0);
70
172
  }
71
- return crossings;
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];
72
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);
73
289
  /**
74
290
  * Orders the vertices of each layer to reduce crossings. Layers are the given
75
291
  * ranks and need not be contiguous; a link joins its endpoints of different
@@ -82,17 +298,27 @@ export function countBilayerCrossings(lower, upper, lowerSize, upperSize, weight
82
298
  * each sweep reorders a layer by the weighted barycentre of its neighbours in
83
299
  * the fixed adjacent layer (Sugiyama, Tagawa and Toda 1981), a vertex with no
84
300
  * neighbour there keeping its slot, ties alternating between the current and
85
- * the reversed order to leave plateaus. The fewest-crossing order seen is
86
- * returned, so the result never has more crossings than the initial order. The
87
- * search stops after `patience` sweeps without improvement, or at zero
88
- * crossings.
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.
89
314
  *
90
315
  * Complexity: O(V′ + E′) to build the layered graph, with D dummies V′ = V + D
91
- * and E′ = E + D; each sweep O(E′ log V′).
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.
92
318
  *
93
319
  * @throws {RangeError} A rank that is not a non-negative integer, a wrong
94
320
  * `ranks` or `weights` length, a negative or non-finite weight, an invalid
95
- * `patience`.
321
+ * `patience` or `effort`.
96
322
  */
97
323
  export function orderLayers(graph, ranks, options) {
98
324
  return runToCompletion(orderLayerSteps(graph, ranks, options));
@@ -107,6 +333,10 @@ export function* orderLayerSteps(graph, ranks, options) {
107
333
  const weights = options?.weights;
108
334
  const patience = options?.patience ?? DEFAULT_PATIENCE;
109
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
+ }
110
340
  if (ranks.length !== nodeCount) {
111
341
  throw new RangeError(`orderLayers: ranks has ${ranks.length} entries for ${nodeCount} nodes`);
112
342
  }
@@ -275,45 +505,91 @@ export function* orderLayerSteps(graph, ranks, options) {
275
505
  // Gansner et al. 1993: swap adjacent vertices while it lowers the crossings
276
506
  // they have with the neighbours in both adjacent layers. Per pair, the
277
507
  // crossings come from one merge of the two sorted neighbour lists, so the
278
- // cost is O((degrees) log) and parallel links add no quadratic term.
279
- function sortedByNeighbour(vertex, adjacency, neighbours) {
280
- const edges = Array.from(adjacency.indices.subarray(adjacency.offsets[vertex], adjacency.offsets[vertex + 1]));
281
- return sortedIndices(edges, (first, second) => compareNaturalAscending(orders[neighbours[first]], orders[neighbours[second]])).map((index) => edges[index]);
282
- }
283
- // Weight of the crossings of `left` placed before `right` (`crossing`) and
284
- // of `right` before `left` (`uncrossing`), over one adjacent layer.
285
- function pairCrossings(left, right, adjacency, neighbours) {
286
- const leftEdges = sortedByNeighbour(left, adjacency, neighbours);
287
- const rightEdges = sortedByNeighbour(right, adjacency, neighbours);
288
- let rightTotal = 0;
289
- for (const edge of rightEdges) {
290
- rightTotal += segmentWeights[edge];
291
- }
292
- let crossing = 0;
293
- let uncrossing = 0;
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];
294
545
  let below = 0;
295
- let belowOrEqual = 0;
296
- let lower = 0;
297
- let lowerOrEqual = 0;
298
- for (const edge of leftEdges) {
546
+ let belowError = 0;
547
+ let lower = rightBegin;
548
+ for (let index = leftBegin; index < leftEnd; index++) {
549
+ const edge = sorted[index];
299
550
  const position = orders[neighbours[edge]];
300
- while (lower < rightEdges.length &&
301
- orders[neighbours[rightEdges[lower]]] < position) {
302
- below += segmentWeights[rightEdges[lower++]];
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;
303
557
  }
304
- while (lowerOrEqual < rightEdges.length &&
305
- orders[neighbours[rightEdges[lowerOrEqual]]] <= position) {
306
- belowOrEqual += segmentWeights[rightEdges[lowerOrEqual++]];
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;
307
572
  }
308
- crossing += segmentWeights[edge] * below;
309
- uncrossing += segmentWeights[edge] * (rightTotal - belowOrEqual);
573
+ addProduct(gain, -segmentWeights[edge], above, aboveError);
310
574
  }
311
- return [crossing, uncrossing];
312
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);
313
587
  function pairGain(left, right) {
314
- const [crossingBelow, uncrossingBelow] = pairCrossings(left, right, incoming, segmentSources);
315
- const [crossingAbove, uncrossingAbove] = pairCrossings(left, right, outgoing, segmentTargets);
316
- return crossingBelow + crossingAbove - (uncrossingBelow + uncrossingAbove);
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];
317
593
  }
318
594
  function* transpose() {
319
595
  for (let pass = 0; pass < TRANSPOSE_PASSES; pass++) {
@@ -321,6 +597,7 @@ export function* orderLayerSteps(graph, ranks, options) {
321
597
  yield;
322
598
  let improved = false;
323
599
  for (let layer = 0; layer < layerCount; layer++) {
600
+ sortLayerEdges(layer);
324
601
  const begin = layerStarts[layer];
325
602
  for (let slot = begin; slot + 1 < layerStarts[layer + 1]; slot++) {
326
603
  const left = current[slot];
@@ -339,19 +616,208 @@ export function* orderLayerSteps(graph, ranks, options) {
339
616
  }
340
617
  }
341
618
  }
342
- let bestCrossings = Infinity;
343
- let best = current;
344
- // From each starting order: barycentre sweeps first (Sugiyama et al.), then
345
- // median sweeps from the best order found (Eades and Wormald 1994).
346
- for (const start of startingOrders) {
347
- load(start);
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();
348
625
  yield* transpose();
349
- let startCrossings = countCrossings();
350
- let startBest = current.slice();
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();
351
817
  for (const useMedian of [false, true]) {
352
- load(startBest);
818
+ load(phaseBest);
353
819
  let sinceBest = 0;
354
- for (let sweep = 0; sinceBest < patience && startCrossings > 0; sweep++, sinceBest++) {
820
+ for (let sweep = 0; sinceBest < patience && crossings > 0; sweep++, sinceBest++) {
355
821
  budget?.spend(vertexCount + segmentCount);
356
822
  yield;
357
823
  const reverseTies = sweep % 4 >= 2;
@@ -365,18 +831,44 @@ export function* orderLayerSteps(graph, ranks, options) {
365
831
  sweepLayer(layer, false, reverseTies, useMedian);
366
832
  }
367
833
  }
368
- yield* transpose();
369
- const crossings = countCrossings();
370
- if (crossings < startCrossings) {
371
- startCrossings = crossings;
372
- startBest = current.slice();
834
+ const swept = yield* transposeKeepingBetter();
835
+ if ((yield* compareWith(phaseBest, swept, crossings)) < 0) {
836
+ crossings = swept;
837
+ phaseBest = current.slice();
838
+ improved = true;
373
839
  sinceBest = -1;
374
840
  }
375
841
  }
376
842
  }
377
- if (startCrossings < bestCrossings) {
378
- bestCrossings = startCrossings;
379
- best = startBest;
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();
380
872
  }
381
873
  }
382
874
  load(best);