Public: anyone can read this; the crew can change it.

Map layout of 2,000 nodes: get it from about 235 ms to the 150 ms target #15614

Merged opened this

Check · Review · Land · Live done — Landed and live in production.

Merged

torque/forge:torque/15612-map-layout-of-2-000-nodes-get-it-from-ab → main 0 commits fork 1 thread · 1 unresolved

  • Merged. torque/15612-map-layout-of-2-000-nodes-get-it-from-ab was merged into main as ceae157.

Review

Sign in to review this change.
2 files changed +148 −83
src/web/pages/map.ts +128 −80
@@ -283,63 +283,78 @@ export function layout(graph: Graph): Layout {
283283 /**
284284 * Whether two hops cross, drawn as monotone curves between their ends:
285285 * their spans of levels overlap and their ends are in opposite order.
286 * Hops that share an end never cross; they meet.
286 * Hops that share an end never cross; they meet. Ends are indexes into
287 * `lv` (level) and `ps` (position).
287288 */
288 function cross(
289 s: Seg,
290 t: Seg,
291 level: Map<string, number>,
292 pos: Map<string, number>,
289 function crossAt(
290 sf: Int32Array,
291 st: Int32Array,
292 s: number,
293 t: number,
294 lv: Int32Array,
295 ps: Int32Array,
293296 ): boolean {
294 if (s.from === t.from || s.to === t.to || s.from === t.to || s.to === t.from)
295 return false;
296 const sa = level.get(s.from)!;
297 const sb = level.get(s.to)!;
298 const ta = level.get(t.from)!;
299 const tb = level.get(t.to)!;
297 const s0 = sf[s]!;
298 const s1 = st[s]!;
299 const t0 = sf[t]!;
300 const t1 = st[t]!;
301 if (s0 === t0 || s1 === t1 || s0 === t1 || s1 === t0) return false;
302 const sa = lv[s0]!;
303 const sb = lv[s1]!;
304 const ta = lv[t0]!;
305 const tb = lv[t1]!;
300306 if (
301307 Math.max(Math.min(sa, sb), Math.min(ta, tb)) >=
302308 Math.min(Math.max(sa, sb), Math.max(ta, tb))
303309 )
304310 return false;
305 const top = pos.get(s.from)! - pos.get(t.from)!;
306 const bottom = pos.get(s.to)! - pos.get(t.to)!;
307 return top * bottom < 0;
311 return (ps[s0]! - ps[t0]!) * (ps[s1]! - ps[t1]!) < 0;
308312 }
309313
314 /** Hops are packed `top * PACK + bottom` so one numeric sort orders both. */
315 const PACK = 1 << 22;
316
310317 /**
311 * The same count as comparing every pair of hops with `cross`, without
318 * The same count as comparing every pair of hops with `crossAt`, without
312319 * doing so (#3693: 2,266 edges drew 30 s of layout). A hop down one level crosses
313320 * another in the same gap exactly when their ends are in opposite order,
314321 * so each gap is an inversion count over a Fenwick tree, O(k log k). Hops
315322 * that point up or skip levels (only a cycle draws them) keep the pairwise
316323 * test against every hop; hops within one level never cross anything.
324 * Over integer indexes, so the layout's sweeps touch no string or Map
325 * (#15612: 2,000 nodes took 235 ms, mostly in lookups).
317326 */
318 export function countCrossings(
319 segs: readonly Seg[],
320 level: Map<string, number>,
321 pos: Map<string, number>,
327 function countAt(
328 sf: Int32Array,
329 st: Int32Array,
330 lv: Int32Array,
331 ps: Int32Array,
322332 ): number {
323 const gaps = new Map<number, [number, number][]>();
324 const odd: Seg[] = [];
325 const spanning: Seg[] = [];
326 for (const s of segs) {
327 const a = level.get(s.from)!;
328 const b = level.get(s.to)!;
333 const gaps = new Map<number, number[]>();
334 const odd: number[] = [];
335 const spanning: number[] = [];
336 for (let i = 0; i < sf.length; i++) {
337 const a = lv[sf[i]!]!;
338 const b = lv[st[i]!]!;
329339 if (a === b) continue;
330 spanning.push(s);
331 if (b === a + 1) push(gaps, a, [pos.get(s.from)!, pos.get(s.to)!]);
332 else odd.push(s);
340 spanning.push(i);
341 if (b === a + 1) push(gaps, a, ps[sf[i]!]! * PACK + ps[st[i]!]!);
342 else odd.push(i);
333343 }
334344 let n = 0;
345 let tree = new Int32Array(0);
335346 for (const hops of gaps.values()) {
336347 // Top end ascending, bottom ascending on ties: an equal top or an equal
337348 // bottom is a shared card, which meets rather than crosses.
338 hops.sort((x, y) => x[0] - y[0] || x[1] - y[1]);
339 const size = hops.reduce((most, h) => Math.max(most, h[1]), 0) + 2;
340 const tree = new Int32Array(size + 1);
349 const packed = Float64Array.from(hops).sort();
350 let size = 0;
351 for (const h of packed) size = Math.max(size, h % PACK);
352 size += 2;
353 if (tree.length < size + 1) tree = new Int32Array(size + 1);
354 else tree.fill(0, 0, size + 1);
341355 let seen = 0;
342 for (const [, bottom] of hops) {
356 for (const h of packed) {
357 const bottom = h % PACK;
343358 // Hops already seen with a bottom strictly right of this one's.
344359 let atMost = 0;
345360 for (let i = bottom + 1; i > 0; i -= i & -i) atMost += tree[i]!;
@@ -353,12 +368,35 @@ export function countCrossings(
353368 odd.forEach((s, i) => {
354369 for (const t of spanning) {
355370 const j = oddAt.get(t);
356 if ((j === undefined || j > i) && cross(s, t, level, pos)) n++;
371 if ((j === undefined || j > i) && crossAt(sf, st, s, t, lv, ps)) n++;
357372 }
358373 });
359374 return n;
360375 }
361376
377 /** The count over ids: `countAt` after numbering every end once. */
378 export function countCrossings(
379 segs: readonly Seg[],
380 level: Map<string, number>,
381 pos: Map<string, number>,
382 ): number {
383 const idx = new Map<string, number>();
384 const at = (id: string): number => {
385 let i = idx.get(id);
386 if (i === undefined) idx.set(id, (i = idx.size));
387 return i;
388 };
389 const sf = Int32Array.from(segs, (s) => at(s.from));
390 const st = Int32Array.from(segs, (s) => at(s.to));
391 const lv = new Int32Array(idx.size);
392 const ps = new Int32Array(idx.size);
393 for (const [id, i] of idx) {
394 lv[i] = level.get(id)!;
395 ps[i] = pos.get(id)!;
396 }
397 return countAt(sf, st, lv, ps);
398 }
399
362400 /**
363401 * How many crossings a layout draws between its edges, card to card; what
364402 * `order` minimises, counted the way a reader sees it.
@@ -378,85 +416,95 @@ export function crossings(graph: Graph, placed: Layout): number {
378416 * hangs from it (back up), a few times, keeping the best ordering seen.
379417 * Then a transposition pass: neighbours swap wherever that draws fewer
380418 * crossings between the hops they touch. Pure, and deterministic — ties
381 * fall back to the issue number, waypoints after cards.
419 * fall back to the issue number, waypoints after cards. Works on integer
420 * indexes throughout; the rows come back as ids, ordered.
382421 */
383422 function order(
384423 rows: string[][],
385424 segs: readonly Seg[],
386425 level: Map<string, number>,
387426 tie: Map<string, number>,
388 ): Map<string, number> {
389 const pos = new Map<string, number>();
390 for (const row of rows) row.forEach((id, n) => pos.set(id, n));
391 if (rows.length < 2) return pos;
392 const up = new Map<string, string[]>();
393 const down = new Map<string, string[]>();
394 for (const s of segs) {
395 push(up, s.to, s.from);
396 push(down, s.from, s.to);
427 ): void {
428 if (rows.length < 2) return;
429 const ids: string[] = [];
430 const idx = new Map<string, number>();
431 for (const row of rows)
432 for (const id of row) {
433 idx.set(id, ids.length);
434 ids.push(id);
435 }
436 const lv = Int32Array.from(ids, (id) => level.get(id)!);
437 const tn = Float64Array.from(ids, (id) => tie.get(id)!);
438 const ps = new Int32Array(ids.length);
439 const grid = rows.map((row) => row.map((id) => idx.get(id)!));
440 for (const row of grid) row.forEach((id, n) => (ps[id] = n));
441 const sf = Int32Array.from(segs, (s) => idx.get(s.from)!);
442 const st = Int32Array.from(segs, (s) => idx.get(s.to)!);
443 const up: number[][] = ids.map(() => []);
444 const down: number[][] = ids.map(() => []);
445 const touching: number[][] = ids.map(() => []);
446 for (let i = 0; i < sf.length; i++) {
447 up[st[i]!]!.push(sf[i]!);
448 down[sf[i]!]!.push(st[i]!);
449 touching[st[i]!]!.push(i);
450 touching[sf[i]!]!.push(i);
397451 }
398 const sortRow = (row: string[], near: Map<string, string[]>): void => {
399 const keyed = row.map((id) => {
400 const ids = near.get(id) ?? [];
401 const k =
402 ids.length === 0
403 ? pos.get(id)!
404 : ids.reduce((s, n) => s + (pos.get(n) ?? 0), 0) / ids.length;
405 return { id, k };
406 });
407 keyed.sort((a, b) => a.k - b.k || tie.get(a.id)! - tie.get(b.id)!);
408 keyed.forEach((k, n) => {
409 row[n] = k.id;
410 pos.set(k.id, n);
411 });
452 const key = new Float64Array(ids.length);
453 const sortRow = (row: number[], near: number[][]): void => {
454 for (const id of row) {
455 const list = near[id]!;
456 if (list.length === 0) key[id] = ps[id]!;
457 else {
458 let sum = 0;
459 for (const m of list) sum += ps[m]!;
460 key[id] = sum / list.length;
461 }
462 }
463 row.sort((a, b) => key[a]! - key[b]! || tn[a]! - tn[b]!);
464 row.forEach((id, n) => (ps[id] = n));
412465 };
413 let best = countCrossings(segs, level, pos);
414 let bestPos = new Map(pos);
466 let best = countAt(sf, st, lv, ps);
467 let bestPos = ps.slice();
415468 for (let sweep = 0; sweep < 4 && best > 0; sweep++) {
416 for (let l = 1; l < rows.length; l++) sortRow(rows[l]!, up);
417 for (let l = rows.length - 2; l >= 0; l--) sortRow(rows[l]!, down);
418 const n = countCrossings(segs, level, pos);
469 for (let l = 1; l < grid.length; l++) sortRow(grid[l]!, up);
470 for (let l = grid.length - 2; l >= 0; l--) sortRow(grid[l]!, down);
471 const n = countAt(sf, st, lv, ps);
419472 if (n < best) {
420473 best = n;
421 bestPos = new Map(pos);
474 bestPos = ps.slice();
422475 }
423476 }
424 for (const [id, n] of bestPos) pos.set(id, n);
425 for (const row of rows) row.sort((a, b) => pos.get(a)! - pos.get(b)!);
477 ps.set(bestPos);
478 for (const row of grid) row.sort((a, b) => ps[a]! - ps[b]!);
426479
427 const touching = new Map<string, Seg[]>();
428 for (const s of segs) {
429 push(touching, s.to, s);
430 push(touching, s.from, s);
431 }
432 const between = (a: string, b: string): number => {
480 const between = (a: number, b: number): number => {
433481 let n = 0;
434 for (const s of touching.get(a) ?? [])
435 for (const t of touching.get(b) ?? []) if (cross(s, t, level, pos)) n++;
482 for (const s of touching[a]!)
483 for (const t of touching[b]!) if (crossAt(sf, st, s, t, lv, ps)) n++;
436484 return n;
437485 };
438486 for (let round = 0; round < 4 && best > 0; round++) {
439487 let improved = false;
440 for (const row of rows)
488 for (const row of grid)
441489 for (let i = 0; i + 1 < row.length; i++) {
442490 const a = row[i]!;
443491 const b = row[i + 1]!;
444492 const before = between(a, b);
445493 if (before === 0) continue;
446 pos.set(a, i + 1);
447 pos.set(b, i);
494 ps[a] = i + 1;
495 ps[b] = i;
448496 if (between(a, b) < before) {
449497 row[i] = b;
450498 row[i + 1] = a;
451499 improved = true;
452500 } else {
453 pos.set(a, i);
454 pos.set(b, i + 1);
501 ps[a] = i;
502 ps[b] = i + 1;
455503 }
456504 }
457505 if (!improved) break;
458506 }
459 return pos;
507 rows.forEach((row, l) => grid[l]!.forEach((id, n) => (row[n] = ids[id]!)));
460508 }
461509
462510 // ---- the words ----
test/map-scale.test.ts +20 −3
@@ -1,9 +1,12 @@
11 /**
22 * The map at 2,000 nodes (#15588): a regression guard, not the issue's
3 * target. The issue asks for a 150 ms layout; layout takes about 235 ms here
4 * and that is not met (the speed work is its own issue). What these tests
5 * hold is the shape of the cost, so a change that makes it worse fails:
3 * target. #15612 sped the layout up about 2.5 times (ordering runs over integer
4 * indexes). What these tests hold is the cost, so a change that makes it worse fails:
65 *
6 * - layout of 2,000 nodes against a fixed calibration job (sorting 200,000
7 * numbers) timed in the same run: the current code costs about 1.8 to 2.2
8 * calibrations, the code before #15612 about 5 to 7, and the bound sits
9 * between at 4, so the old ordering fails it and a loaded machine passes;
710 * - layout of 2,000 nodes against layout of 500 nodes, timed in the same run
811 * (no constant guessed for the machine: a loaded machine slows both);
912 * - the first paint's markup against that same layout;
@@ -21,6 +24,11 @@ import { productionGraph } from "./helpers/map-graph.ts";
2124 const NODES = 2000;
2225 /** Four times the nodes costs about this many times the layout; 16 would be quadratic. */
2326 const LAYOUT_RATIO = 14;
27 /**
28 * Layout of 2,000 nodes costs at most this many calibration jobs (measured 1.8 to 2.2; old code 5
29 * to 7).
30 */
31 const CALIBRATED = 4;
2432 /** Markup for the first paint costs at most this many layouts. */
2533 const PAINT_RATIO = 1.5;
2634 const PAN_MS = 16;
@@ -47,6 +55,15 @@ test(`layout of ${NODES} nodes costs under ${LAYOUT_RATIO}x layout of 500, same
4755 expect(ratio).toBeLessThan(LAYOUT_RATIO);
4856 });
4957
58 test(`layout of ${NODES} nodes costs under ${CALIBRATED} calibration jobs, same run`, () => {
59 const job = () => {
60 const a = Array.from({ length: 200000 }, (_, i) => (i * 7919) % 100003);
61 a.sort((x, y) => x - y);
62 };
63 const calibration = best(job, 5);
64 expect(best(() => layout(graph), 5) / calibration).toBeLessThan(CALIBRATED);
65 });
66
5067 test(`first paint's markup of ${NODES} nodes costs under ${PAINT_RATIO}x its layout, same run`, () => {
5168 const placed = layout(graph);
5269 const marks = emphasisFor([], [], NO_MARKS);

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs