@knowvah/dot-engine 2.7.1 → 2.8.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 (128) hide show
  1. package/dist/api.js.map +2 -2
  2. package/dist/common/agerr.d.ts +8 -1
  3. package/dist/common/agerr.d.ts.map +1 -1
  4. package/dist/common/fma.d.ts.map +1 -1
  5. package/dist/common/htmltable-emit-fill.d.ts.map +1 -1
  6. package/dist/common/htmltable-emit.d.ts +6 -11
  7. package/dist/common/htmltable-emit.d.ts.map +1 -1
  8. package/dist/common/htmltable-label.d.ts +3 -0
  9. package/dist/common/htmltable-label.d.ts.map +1 -1
  10. package/dist/common/htmltable-lex-attvalue.d.ts.map +1 -1
  11. package/dist/common/htmltable.d.ts +5 -0
  12. package/dist/common/htmltable.d.ts.map +1 -1
  13. package/dist/common/layers.d.ts +12 -0
  14. package/dist/common/layers.d.ts.map +1 -1
  15. package/dist/common/layout-state.d.ts +8 -0
  16. package/dist/common/layout-state.d.ts.map +1 -0
  17. package/dist/common/make-label.d.ts.map +1 -1
  18. package/dist/common/multicolor.d.ts +6 -3
  19. package/dist/common/multicolor.d.ts.map +1 -1
  20. package/dist/common/nodeinit.d.ts.map +1 -1
  21. package/dist/common/poly-gencode.d.ts.map +1 -1
  22. package/dist/common/poly-init.d.ts +21 -0
  23. package/dist/common/poly-init.d.ts.map +1 -1
  24. package/dist/common/poly-sizing.d.ts +1 -0
  25. package/dist/common/poly-sizing.d.ts.map +1 -1
  26. package/dist/common/postproc.d.ts.map +1 -1
  27. package/dist/common/style-resolve.d.ts +11 -9
  28. package/dist/common/style-resolve.d.ts.map +1 -1
  29. package/dist/gvc/device-cluster.d.ts +5 -6
  30. package/dist/gvc/device-cluster.d.ts.map +1 -1
  31. package/dist/gvc/device.d.ts.map +1 -1
  32. package/dist/gvc/first-layer.d.ts +21 -5
  33. package/dist/gvc/first-layer.d.ts.map +1 -1
  34. package/dist/gvc/gvrender-set-style.d.ts.map +1 -1
  35. package/dist/gvc/render-usershape.d.ts +60 -0
  36. package/dist/gvc/render-usershape.d.ts.map +1 -0
  37. package/dist/gvc/usershape.d.ts +20 -0
  38. package/dist/gvc/usershape.d.ts.map +1 -1
  39. package/dist/index.js +8838 -8465
  40. package/dist/index.js.map +4 -4
  41. package/dist/layout/circo/index.d.ts.map +1 -1
  42. package/dist/layout/dot/init.d.ts +10 -0
  43. package/dist/layout/dot/init.d.ts.map +1 -1
  44. package/dist/layout/dot/splines.d.ts.map +1 -1
  45. package/dist/layout/fdp/init.d.ts.map +1 -1
  46. package/dist/layout/neato/conjgrad-mkernel.d.ts.map +1 -1
  47. package/dist/layout/neato/constrained-majorization.d.ts.map +1 -1
  48. package/dist/layout/neato/edge-len.d.ts +6 -2
  49. package/dist/layout/neato/edge-len.d.ts.map +1 -1
  50. package/dist/layout/neato/init.d.ts.map +1 -1
  51. package/dist/layout/neato/kk.d.ts.map +1 -1
  52. package/dist/layout/neato/make-graph-data.d.ts.map +1 -1
  53. package/dist/layout/neato/matrix-ops.d.ts +0 -6
  54. package/dist/layout/neato/matrix-ops.d.ts.map +1 -1
  55. package/dist/layout/neato/smart-ini-x.d.ts.map +1 -1
  56. package/dist/layout/neato/splines.d.ts.map +1 -1
  57. package/dist/layout/neato/start.d.ts.map +1 -1
  58. package/dist/layout/neato/stress-kernel.d.ts +2 -5
  59. package/dist/layout/neato/stress-kernel.d.ts.map +1 -1
  60. package/dist/layout/neato/stress.d.ts +6 -0
  61. package/dist/layout/neato/stress.d.ts.map +1 -1
  62. package/dist/layout/osage/index.d.ts.map +1 -1
  63. package/dist/layout/patchwork/index.d.ts.map +1 -1
  64. package/dist/layout/sfdp/init.d.ts.map +1 -1
  65. package/dist/layout/twopi/init.d.ts +12 -6
  66. package/dist/layout/twopi/init.d.ts.map +1 -1
  67. package/dist/model/cgraph-ops.d.ts +9 -0
  68. package/dist/model/cgraph-ops.d.ts.map +1 -1
  69. package/dist/render/color-resolve.d.ts +7 -0
  70. package/dist/render/color-resolve.d.ts.map +1 -1
  71. package/dist/render/dot.d.ts +8 -1
  72. package/dist/render/dot.d.ts.map +1 -1
  73. package/dist/render/json.d.ts +17 -2
  74. package/dist/render/json.d.ts.map +1 -1
  75. package/dist/render/map.d.ts +3 -5
  76. package/dist/render/map.d.ts.map +1 -1
  77. package/dist/render.js +711 -338
  78. package/dist/render.js.map +4 -4
  79. package/package.json +1 -1
  80. package/src/common/agerr.ts +69 -8
  81. package/src/common/fma.ts +11 -1
  82. package/src/common/htmltable-emit-fill.ts +11 -7
  83. package/src/common/htmltable-emit.ts +11 -46
  84. package/src/common/htmltable-label.ts +6 -3
  85. package/src/common/htmltable-lex-attvalue.ts +17 -1
  86. package/src/common/htmltable.ts +10 -5
  87. package/src/common/layers.ts +31 -2
  88. package/src/common/layout-state.ts +35 -0
  89. package/src/common/make-label.ts +6 -2
  90. package/src/common/multicolor.ts +12 -6
  91. package/src/common/nodeinit.ts +4 -1
  92. package/src/common/poly-gencode.ts +51 -2
  93. package/src/common/poly-init.ts +34 -13
  94. package/src/common/poly-sizing.ts +4 -4
  95. package/src/common/postproc.ts +4 -1
  96. package/src/common/style-resolve.ts +118 -50
  97. package/src/gvc/device-cluster.ts +33 -40
  98. package/src/gvc/device.ts +56 -43
  99. package/src/gvc/first-layer.ts +60 -11
  100. package/src/gvc/gvrender-set-style.ts +1 -6
  101. package/src/gvc/render-usershape.ts +209 -0
  102. package/src/gvc/usershape.ts +40 -0
  103. package/src/layout/circo/index.ts +4 -0
  104. package/src/layout/dot/init.ts +32 -0
  105. package/src/layout/dot/splines.ts +3 -0
  106. package/src/layout/fdp/init.ts +17 -0
  107. package/src/layout/neato/conjgrad-mkernel.ts +2 -3
  108. package/src/layout/neato/constrained-majorization.ts +2 -1
  109. package/src/layout/neato/edge-len.ts +39 -7
  110. package/src/layout/neato/init.ts +8 -3
  111. package/src/layout/neato/kk.ts +2 -1
  112. package/src/layout/neato/make-graph-data.ts +1 -2
  113. package/src/layout/neato/matrix-ops.ts +1 -11
  114. package/src/layout/neato/smart-ini-x.ts +1 -1
  115. package/src/layout/neato/splines.ts +3 -1
  116. package/src/layout/neato/start.ts +3 -2
  117. package/src/layout/neato/stress-kernel.ts +45 -86
  118. package/src/layout/neato/stress.ts +19 -0
  119. package/src/layout/osage/index.ts +8 -1
  120. package/src/layout/patchwork/index.ts +4 -0
  121. package/src/layout/sfdp/init.ts +3 -0
  122. package/src/layout/twopi/init.ts +21 -9
  123. package/src/layout/twopi/pipeline.ts +3 -3
  124. package/src/model/cgraph-ops.ts +19 -0
  125. package/src/render/color-resolve.ts +17 -2
  126. package/src/render/dot.ts +14 -1
  127. package/src/render/json.ts +9 -10
  128. package/src/render/map.ts +5 -6
@@ -6,9 +6,8 @@
6
6
  * C statement `a += b * c` on floats is one `fmadd`/`fmla` (clang's default
7
7
  * contraction), and a reduction the vectoriser took in blocks of 16 rounds
8
8
  * the products of those leading elements before its in-order adds (strict FP
9
- * forbids reassociation) while the scalar remainder is fused. `stress-kernel.ts`
10
- * keeps the unfused rounding of these loops; the constrained-majorization driver
11
- * needs the oracle's bits.
9
+ * forbids reassociation) while the scalar remainder is fused. These kernels run
10
+ * `stress_majorization_kD_mkernel` and the constrained-majorization driver.
12
11
  *
13
12
  * @see lib/neatogen/conjgrad.c:conjugate_gradient_mkernel
14
13
  * @see lib/neatogen/matrix_ops.c:right_mult_with_vector_ff
@@ -14,6 +14,7 @@
14
14
  * @see lib/neatogen/constrained_majorization.c
15
15
  */
16
16
 
17
+ import { fma } from '../../common/fma.js';
17
18
  import { RenderError } from '../../errors.js';
18
19
  import type { Node } from '../../model/node.js';
19
20
  import { conjugateGradientMkernelFused, rightMultWithVectorFFFused } from './conjgrad-mkernel.js';
@@ -21,7 +22,7 @@ import { computeHierarchy, type Hierarchy } from './compute-hierarchy.js';
21
22
  import type { VtxData } from './dijkstra.js';
22
23
  import { MODEL_CIRCUIT, MODEL_MDS, MODEL_SUBSET } from './init.js';
23
24
  import {
24
- fma, invertSqrtVec, invertVec, orthog1, sqrtVecF, squareVec, vectorsInnerProductF,
25
+ invertSqrtVec, invertVec, orthog1, sqrtVecF, squareVec, vectorsInnerProductF,
25
26
  } from './matrix-ops.js';
26
27
  import type { DirectedVtxData } from './opt-arrangement.js';
27
28
  import { computeYCoords } from './opt-arrangement.js';
@@ -8,12 +8,33 @@
8
8
  */
9
9
 
10
10
  import type { Graph } from '../../model/graph.js';
11
+ import { agNameOf } from '../../model/cgraph-ops.js';
11
12
  import type { Edge } from '../../model/edge.js';
12
13
  import { agwarningf } from '../../common/agerr.js';
14
+ import { buildOutEdgeIndex } from '../../model/node.js';
13
15
 
14
16
  /** `dfltlen` passed by scan_graph_mode. @see lib/neatogen/stuff.c:scan_graph_mode */
15
17
  export const DEFAULT_EDGE_LEN = 1.0;
16
18
 
19
+ /** sscanf("%lf") number prefix: decimal, hex, inf/infinity, nan (case-insensitive). */
20
+ const DOUBLE_PREFIX =
21
+ /^\s*([+-]?)(0x(?:[\da-f]+\.?[\da-f]*|\.[\da-f]+)(?:p[+-]?\d+)?|(?:\d+\.?\d*|\.\d+)(?:e[+-]?\d+)?|inf(?:inity)?|nan(?:\([\w]*\))?)/i;
22
+
23
+ /** `sscanf(s, "%lf", &v)`: the parsed value (NaN for "nan"), or null when nothing scans. */
24
+ function scanDouble(s: string): number | null {
25
+ const m = DOUBLE_PREFIX.exec(s);
26
+ if (m === null) return null;
27
+ const body = m[2]!.toLowerCase();
28
+ const sign = m[1] === '-' ? -1 : 1;
29
+ if (body.startsWith('nan')) return Number.NaN;
30
+ if (body.startsWith('inf')) return sign * Infinity;
31
+ if (!body.startsWith('0x')) return sign * parseFloat(body);
32
+ const [mant, exp] = body.slice(2).split('p');
33
+ const [ip = '', fp = ''] = mant!.split('.');
34
+ const digits = parseInt(ip + fp || '0', 16);
35
+ return sign * digits * 2 ** (Number(exp ?? 0) - 4 * fp.length);
36
+ }
37
+
17
38
  /**
18
39
  * The edge's `len`, or the default when it is absent or empty; a value that
19
40
  * does not parse as a positive number warns and falls back to the default.
@@ -22,16 +43,27 @@ export const DEFAULT_EDGE_LEN = 1.0;
22
43
  export function lenattr(ep: Edge, g: Graph): number {
23
44
  const s = ep.attrs.get('len');
24
45
  if (s === undefined || s === '') return DEFAULT_EDGE_LEN;
25
- const val = /^\s*[+-]?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?/.exec(s);
26
- const len = val === null ? Number.NaN : parseFloat(val[0]);
27
- if (Number.isNaN(len) || len < 0 || len === 0) {
28
- agwarningf(`bad edge len "${s}" in ${g.name} - setting to ${DEFAULT_EDGE_LEN.toFixed(2)}`);
46
+ const len = scanDouble(s);
47
+ if (len === null || len < 0 || len === 0) {
48
+ agwarningf(`bad edge len "${s}" in ${agNameOf(g)} - setting to ${DEFAULT_EDGE_LEN.toFixed(2)}`);
29
49
  return DEFAULT_EDGE_LEN;
30
50
  }
31
51
  return len;
32
52
  }
33
53
 
34
- /** Store every edge's length in `info.dist` (ED_dist). @see lib/neatogen/stuff.c:setEdgeLen */
35
- export function setEdgeLen(g: Graph): void {
36
- for (const ep of g.edges) ep.info.dist = lenattr(ep, g);
54
+ /**
55
+ * Store every edge's length in `info.dist` (ED_dist), visiting nodes in order and each
56
+ * node's out-edges in `agfstout` order as scan_graph_mode does; returns the total length.
57
+ * @see lib/neatogen/stuff.c:setEdgeLen
58
+ */
59
+ export function setEdgeLen(g: Graph): number {
60
+ const out = buildOutEdgeIndex(g);
61
+ let total = 0;
62
+ for (const np of g.nodes.values()) {
63
+ for (const ep of out.get(np) ?? []) {
64
+ ep.info.dist = lenattr(ep, g);
65
+ total += ep.info.dist;
66
+ }
67
+ }
68
+ return total;
37
69
  }
@@ -11,12 +11,14 @@
11
11
 
12
12
  import type { ShapeDesc } from '../../common/types.js';
13
13
  import type { Graph } from '../../model/graph.js';
14
+ import { gvCleanupEdgeLabels, gvCleanupNodeLabels } from '../dot/init.js';
14
15
  import type { Node } from '../../model/node.js';
15
16
  import type { Edge } from '../../model/edge.js';
16
17
  import type { VtxData } from './dijkstra.js';
17
18
  import {
18
19
  DFLT_ITERATIONS,
19
20
  OPT_SMART_INIT as STRESS_OPT_SMART_INIT,
21
+ checkExp,
20
22
  MODEL_MDS as STRESS_MODEL_MDS,
21
23
  MODEL_CIRCUIT as STRESS_MODEL_CIRCUIT,
22
24
  MODEL_SUBSET as STRESS_MODEL_SUBSET,
@@ -26,6 +28,7 @@ import { kkNeato } from './kk.js';
26
28
  import {
27
29
  checkStart, assertSupported, parseStart, INIT_RANDOM, INIT_REGULAR, INIT_SELF,
28
30
  } from './start.js';
31
+ import { setEdgeLen } from './edge-len.js';
29
32
  import { makeGraphDataC, graphHasLen } from './make-graph-data.js';
30
33
  import type { DirectedVtxData } from './opt-arrangement.js';
31
34
  import { stressMajorizationWithHierarchy } from './constrained-majorization.js';
@@ -37,7 +40,6 @@ import {
37
40
  computeApspPacked,
38
41
  computeWeightedApspPacked,
39
42
  stressMajorizationKDMkernel,
40
- OPT_EXP_FLAG,
41
43
  } from './stress-kernel.js';
42
44
  import { lateDouble } from '../../common/nodeinit.js';
43
45
  import { inputscaleDivisor } from '../../common/utils-inputscale.js';
@@ -373,18 +375,19 @@ function solveStress(
373
375
  const weighted = haveLen && mode !== MODE_IPSEP;
374
376
  const Dij = weighted ? computeWeightedApspPacked(vtx, n) : computeApspPacked(vtx, n);
375
377
  return stressMajorizationKDMkernel(Dij, n, dCoords, nodeList, {
376
- dim: DFLT_DIM, opts, maxi, epsilon,
378
+ dim: DFLT_DIM, opts, maxi, epsilon, cola: mode === MODE_IPSEP,
377
379
  });
378
380
  }
379
381
 
380
382
  /** Run stress majorization and write positions back. @see lib/neatogen/neatoinit.c:majorization */
381
383
  export function runMajorization(g: Graph, mode: number, model: number): void {
382
384
  const nodeList = assignNodeIds(g);
385
+ setEdgeLen(g); // scan_graph_mode else-branch: ED_dist for major/hier/ipsep
383
386
  const n = nodeList.length;
384
387
  const haveLen = graphHasLen(g);
385
388
  // C: srand48(seed) immediately before initLayout draws; hier starts from self
386
389
  const init = checkStart(g, n, mode === MODE_HIER ? INIT_SELF : INIT_RANDOM);
387
- const opts = init === INIT_SELF ? OPT_EXP_FLAG | STRESS_OPT_SMART_INIT : OPT_EXP_FLAG;
390
+ const opts = checkExp(g) | (init === INIT_SELF ? STRESS_OPT_SMART_INIT : 0);
388
391
  const haveDir = mode === MODE_HIER || mode === MODE_IPSEP;
389
392
  const vtx = makeGraphDataC(g, nodeList, haveLen, haveDir, mode);
390
393
  const dCoords = [new Float64Array(n), new Float64Array(n)];
@@ -489,6 +492,8 @@ export function neatoSetAspect(g: Graph): void {
489
492
  * @see lib/neatogen/neatoinit.c:neato_cleanup
490
493
  */
491
494
  export function neatoCleanup(g: Graph): void {
495
+ for (const e of g.edges) gvCleanupEdgeLabels(e); // gv_cleanup_edge: per-node agfstout, all edges of root g
496
+ for (const n of g.nodes.values()) gvCleanupNodeLabels(n); // gv_cleanup_node
492
497
  for (const [, n] of g.nodes) {
493
498
  n.info.pos = undefined;
494
499
  n.info.pinned = undefined;
@@ -17,6 +17,7 @@
17
17
  */
18
18
 
19
19
  import type { Graph } from '../../model/graph.js';
20
+ import { agNameOf } from '../../model/cgraph-ops.js';
20
21
  import type { Node } from '../../model/node.js';
21
22
  import type { Edge } from '../../model/edge.js';
22
23
  import { buildOutEdgeIndex } from '../../model/node.js';
@@ -290,7 +291,7 @@ function moveNode(st: KkState, m: number): void {
290
291
  function solveModel(g: Graph, st: KkState): void {
291
292
  for (let m = chooseNode(st); m >= 0; m = chooseNode(st)) moveNode(st, m);
292
293
  if (st.move === st.maxIter) {
293
- agwarningf(`Max. iterations (${st.maxIter}) reached on graph ${g.name}`);
294
+ agwarningf(`Max. iterations (${st.maxIter}) reached on graph ${agNameOf(g)}`);
294
295
  }
295
296
  }
296
297
 
@@ -6,7 +6,6 @@
6
6
  * @see lib/neatogen/neatoinit.c
7
7
  */
8
8
 
9
- import { lateDouble } from '../../common/nodeinit.js';
10
9
  import type { Graph } from '../../model/graph.js';
11
10
  import type { Node } from '../../model/node.js';
12
11
  import type { DirectedVtxData } from './opt-arrangement.js';
@@ -129,7 +128,7 @@ function addNeighbours(g: Graph, np: Node, entry: DirectedVtxData, o: GraphDataO
129
128
  if (ep.head === ep.tail) continue;
130
129
  const vp = ep.tail === np ? ep.head : ep.tail;
131
130
  const vid = vp.info.id!;
132
- const dist = o.haveLen ? lateDouble(ep.attrs.get('len'), 1.0, 0) : 1.0;
131
+ const dist = o.haveLen ? (ep.info.dist ?? 0) : 1.0; // ED_dist (calloc 0)
133
132
  const idx = seen.get(vid);
134
133
  if (idx !== undefined) {
135
134
  if (o.haveLen) entry.ewgts[idx] = Math.max(entry.ewgts[idx]!, dist);
@@ -11,21 +11,11 @@
11
11
  */
12
12
 
13
13
  import { crand } from '../../common/crand.js';
14
- import { fma as softFma } from '../../common/fma.js';
14
+ import { fma } from '../../common/fma.js';
15
15
  import type { VtxData } from './dijkstra.js';
16
16
 
17
17
  const fr = Math.fround;
18
18
 
19
- /**
20
- * fmadd: round(a * b + c) once. `common/fma` splits operands (Dekker), which
21
- * turns an infinite operand into NaN where the hardware fmadd gives inf, so
22
- * non-finite products and addends take the plain expression (exact then).
23
- */
24
- export function fma(a: number, b: number, c: number): number {
25
- const p = a * b;
26
- return Number.isFinite(p) && Number.isFinite(c) ? softFma(a, b, c) : p + c;
27
- }
28
-
29
19
  /** Subtract the mean (double precision). @see matrix_ops.c:orthog1 */
30
20
  export function orthog1(n: number, vec: Float64Array): void {
31
21
  let sum = 0;
@@ -11,13 +11,13 @@
11
11
  */
12
12
 
13
13
  import { crand } from '../../common/crand.js';
14
+ import { fma } from '../../common/fma.js';
14
15
  import { conjugateGradientF } from './conjgrad.js';
15
16
  import type { VtxData } from './dijkstra.js';
16
17
  import { computeApsp } from './kkutils.js';
17
18
  import {
18
19
  BLOCK_NONE,
19
20
  copyVector,
20
- fma,
21
21
  innerProduct,
22
22
  norm,
23
23
  scadd,
@@ -21,6 +21,7 @@ import type { SplineInfo, PolygonT, TextlabelT } from '../../common/types.js';
21
21
  import { polygonOutlineRing } from '../../common/poly-sizing.js';
22
22
  import { fma, fms } from '../../common/fma.js';
23
23
  import { ShapeKind } from '../../common/types.js';
24
+ import { setState, GVSPLINES } from '../../common/layout-state.js';
24
25
  import { esepFactor, type ExpandT } from './sep-factor.js';
25
26
  import { libmCos, libmSin } from '../../common/libm-trig.js';
26
27
  import type { Poly, VConfig } from '../../pathplan/types.js';
@@ -821,10 +822,11 @@ export function splineEdges(g: Graph): void {
821
822
  }
822
823
  // C splineEdges wrapper: coalesce equivalent edges before routing.
823
824
  coalesceEdges(g);
824
- if (edgetype === EDGETYPE_LINE) { RoutingHelper.straight(g, edgetype); return; }
825
+ if (edgetype === EDGETYPE_LINE) { RoutingHelper.straight(g, edgetype); setState(GVSPLINES); return; }
825
826
  // C: margin = esepFactor(g) — the edge separation, default {3.2, 3.2, add}.
826
827
  // @see lib/neatogen/neatosplines.c:746
827
828
  splineEdgesImpl(g, esepFactor(g), edgetype);
829
+ setState(GVSPLINES); // State = GVSPLINES, neatosplines.c:778 (also the LINE path)
828
830
  }
829
831
 
830
832
  // ---------------------------------------------------------------------------
@@ -14,6 +14,7 @@
14
14
  */
15
15
 
16
16
  import { RenderError } from '../../errors.js';
17
+ import { agNameOf } from '../../model/cgraph-ops.js';
17
18
  import type { Graph } from '../../model/graph.js';
18
19
  import { srand48 } from '../../common/random.js';
19
20
  import { registerRenderState } from '../../common/render-state.js';
@@ -147,7 +148,7 @@ export function neatoMode(g: Graph): number {
147
148
  if (str === undefined || str === '') return MODE_MAJOR;
148
149
  const mode = modeByName().get(str);
149
150
  if (mode !== undefined) return mode;
150
- agwarningf(`Illegal value ${str} for attribute "mode" in graph ${g.root.name} - ignored`);
151
+ agwarningf(`Illegal value ${str} for attribute "mode" in graph ${agNameOf(g.root)} - ignored`);
151
152
  return MODE_MAJOR;
152
153
  }
153
154
 
@@ -195,7 +196,7 @@ function warnCircuitDisconnected(g: Graph): void {
195
196
  circuitWarned.add(g.root);
196
197
  agerrLineOn(
197
198
  'warn',
198
- `graph ${g.root.name} is disconnected. Hence, the circuit model\n`
199
+ `graph ${agNameOf(g.root)} is disconnected. Hence, the circuit model\n`
199
200
  + 'is undefined. Reverting to the shortest path model.\n'
200
201
  + 'Alternatively, consider running neato using -Gpack=true or decomposing\n'
201
202
  + 'the graph into connected components.',
@@ -19,31 +19,24 @@ import type { Node } from '../../model/node.js';
19
19
  import { drand48 } from '../../common/random.js';
20
20
  import { bfs } from './bfs.js';
21
21
  import { dijkstra, type VtxData } from './dijkstra.js';
22
+ import {
23
+ conjugateGradientMkernelFused, rightMultWithVectorFFFused, type CgMkernelOptions,
24
+ } from './conjgrad-mkernel.js';
22
25
  import {
23
26
  copyVectorF,
24
27
  invertSqrtVec,
25
28
  invertVec,
26
- maxAbsF,
27
29
  orthog1,
28
- orthog1f,
29
30
  rightMultWithVectorFF,
30
31
  sqrtVecF,
31
32
  squareVec,
32
33
  vectorsInnerProductF,
33
- vectorsMultAdditionF,
34
- vectorsSubtractionF,
35
34
  } from './matrix-ops.js';
35
+ import { fmaf } from './quad-prog-solve.js';
36
+ import { OPT_EXP_FLAG, TOLERANCE_CG } from './stress.js';
36
37
 
37
38
  const fr = Math.fround;
38
39
 
39
- /** @see lib/neatogen/stress.h:tolerance_cg */
40
- const TOLERANCE_CG = 1e-3;
41
-
42
- /** Stress options bit: weight exponent (1 or 2). @see lib/neatogen/stress.h */
43
- export const OPT_EXP_FLAG = 2;
44
- /** Stress options bit: smart initialisation. @see lib/neatogen/stress.h */
45
- export const OPT_SMART_INIT = 1;
46
-
47
40
  /**
48
41
  * Packed all-pairs shortest paths over unit weights (BFS hops).
49
42
  * @see lib/neatogen/stress.c:compute_apsp_packed
@@ -115,71 +108,32 @@ export function initLayout(
115
108
  return pinned;
116
109
  }
117
110
 
118
- /**
119
- * Conjugate gradients on a packed symmetric float matrix.
120
- * Returns negative on error.
121
- * @see lib/neatogen/conjgrad.c:conjugate_gradient_mkernel
122
- */
123
- /** Mutable CG iteration state. */
124
- interface CgState {
125
- A: Float32Array;
126
- x: Float32Array;
127
- b: Float32Array;
128
- n: number;
129
- r: Float32Array;
130
- p: Float32Array;
131
- Ap: Float32Array;
132
- rR: number;
133
- }
134
-
135
- /** One CG step; returns false on a zero-length residual error. */
136
- function cgStep(st: CgState, last: boolean): boolean {
137
- const { n } = st;
138
- orthog1f(n, st.p);
139
- orthog1f(n, st.x);
140
- orthog1f(n, st.r);
141
- rightMultWithVectorFF(st.A, n, st.p, st.Ap);
142
- orthog1f(n, st.Ap);
143
- const pAp = vectorsInnerProductF(n, st.p, st.Ap);
144
- if (pAp === 0) return true; // C: break
145
- const alpha = st.rR / pAp;
146
- vectorsMultAdditionF(n, st.x, alpha, st.p);
147
- if (!last) {
148
- vectorsMultAdditionF(n, st.r, -alpha, st.Ap);
149
- const rRNew = vectorsInnerProductF(n, st.r, st.r);
150
- if (st.rR === 0) return false;
151
- const betaF = fr(rRNew / st.rR);
152
- st.rR = rRNew;
153
- for (let j = 0; j < n; j++) st.p[j] = fr(betaF * st.p[j]!) + st.r[j]!;
154
- }
155
- return true;
111
+ /** The right-multiply and conjugate-gradient kernels one caller runs. */
112
+ interface KernelOps {
113
+ /** `acc + tmp*tmp`, the distance accumulation of the Laplacian build. */
114
+ squareAdd(tmp: number, acc: number): number;
115
+ rightMult(m: Float32Array, n: number, vector: Float32Array, result: Float32Array): void;
116
+ /** Returns nonzero on an unexpected zero residual. */
117
+ cg(A: Float32Array, x: Float32Array, b: Float32Array, n: number, o: CgMkernelOptions): number;
156
118
  }
157
119
 
158
- export function conjugateGradientMkernel(
159
- A: Float32Array, x: Float32Array, b: Float32Array, n: number,
160
- tol: number, maxIterations: number,
161
- ): number {
162
- const st: CgState = {
163
- A, x, b, n,
164
- r: new Float32Array(n),
165
- p: new Float32Array(n),
166
- Ap: new Float32Array(n),
167
- rR: 0,
168
- };
169
- orthog1f(n, x);
170
- orthog1f(n, b);
171
- const Ax = new Float32Array(n);
172
- rightMultWithVectorFF(A, n, x, Ax);
173
- orthog1f(n, Ax);
174
- vectorsSubtractionF(n, b, Ax, st.r);
175
- copyVectorF(n, st.r, st.p);
176
- st.rR = vectorsInnerProductF(n, st.r, st.r);
177
-
178
- for (let i = 0; i < maxIterations && maxAbsF(n, st.r) > tol; i++) {
179
- if (!cgStep(st, i >= maxIterations - 1)) return -1;
180
- }
181
- return 0;
182
- }
120
+ /** The oracle's fused kernels, as `stress_majorization_kD_mkernel` runs them. */
121
+ const FUSED_OPS: KernelOps = {
122
+ squareAdd: (tmp, acc) => fmaf(tmp, tmp, acc),
123
+ rightMult: rightMultWithVectorFFFused, cg: conjugateGradientMkernelFused,
124
+ };
125
+ /**
126
+ * The kernels as `stress_majorization_cola` (mode=ipsep) runs them: its squared
127
+ * distances are `square_vec` then `vectors_additionf` (two loops, so the product
128
+ * is rounded before the add), its inlined `right_mult_with_vector_ff` copy is not
129
+ * read from the disassembly (kept unfused), and its conjugate gradient is the same
130
+ * out-of-line `conjugate_gradient_mkernel` the kD kernel calls.
131
+ * @see lib/neatogen/constrained_majorization_ipsep.c:stress_majorization_cola
132
+ */
133
+ const COLA_OPS: KernelOps = {
134
+ squareAdd: (tmp, acc) => acc + fr(tmp * tmp),
135
+ rightMult: rightMultWithVectorFF, cg: conjugateGradientMkernelFused,
136
+ };
183
137
 
184
138
  /** Laplacian off-diagonal prep + diagonal degrees. @see stress.c (Laplacian computation) */
185
139
  function buildLap2(lap2: Float32Array, n: number, exp: number): void {
@@ -207,9 +161,9 @@ function buildLap2(lap2: Float32Array, n: number, exp: number): void {
207
161
  /** Per-iteration Laplacian of 1/(d_ij*|p_i-p_j|). @see stress.c (main loop head) */
208
162
  function buildLap1(
209
163
  lap1: Float32Array, lap2: Float32Array, coords: Float32Array[],
210
- shape: { n: number; dim: number; exp: number },
164
+ shape: { n: number; dim: number; exp: number; ops: KernelOps },
211
165
  ): void {
212
- const { n, dim, exp } = shape;
166
+ const { n, dim, exp, ops } = shape;
213
167
  const lapLength = (n * (n + 1)) / 2;
214
168
  const degrees = new Float64Array(n);
215
169
  const distAccumulator = new Float32Array(n);
@@ -222,7 +176,7 @@ function buildLap1(
222
176
  const ck = coords[k]!;
223
177
  for (let x = 0; x < len; x++) {
224
178
  const tmp = fr(ck[i]! + fr(-1 * ck[i + 1 + x]!));
225
- distAccumulator[x] = distAccumulator[x]! + fr(tmp * tmp);
179
+ distAccumulator[x] = ops.squareAdd(tmp, distAccumulator[x]!);
226
180
  }
227
181
  }
228
182
  invertSqrtVec(len, distAccumulator);
@@ -264,32 +218,34 @@ interface KernelState {
264
218
  b: Float32Array[];
265
219
  tmpCoords: Float32Array;
266
220
  constantTerm: number;
221
+ ops: KernelOps;
267
222
  }
268
223
 
269
224
  /** One stress evaluation. @see stress.c (compute new stress block) */
270
225
  function computeStress(st: KernelState): number {
271
226
  let stress = 0;
272
227
  for (let k = 0; k < st.dim; k++) {
273
- rightMultWithVectorFF(st.lap1, st.n, st.coords[k]!, st.b[k]!);
228
+ st.ops.rightMult(st.lap1, st.n, st.coords[k]!, st.b[k]!);
274
229
  stress += vectorsInnerProductF(st.n, st.coords[k]!, st.b[k]!);
275
230
  }
276
231
  stress *= 2;
277
232
  stress += st.constantTerm;
278
233
  for (let k = 0; k < st.dim; k++) {
279
- rightMultWithVectorFF(st.lap2, st.n, st.coords[k]!, st.tmpCoords);
234
+ st.ops.rightMult(st.lap2, st.n, st.coords[k]!, st.tmpCoords);
280
235
  stress -= vectorsInnerProductF(st.n, st.coords[k]!, st.tmpCoords);
281
236
  }
282
237
  return stress;
283
238
  }
284
239
 
285
- /** Solve one axis, respecting pinned nodes. @see stress.c (CG block) */
240
+ /** Solve one axis, respecting pinned nodes; nonzero on a CG error. @see stress.c (CG block) */
286
241
  function solveAxis(st: KernelState, k: number, havePinned: boolean, nodes: Node[]): number {
242
+ const cg = { tol: TOLERANCE_CG, maxIterations: st.n };
287
243
  if (!havePinned) {
288
- return conjugateGradientMkernel(st.lap2, st.coords[k]!, st.b[k]!, st.n, TOLERANCE_CG, st.n);
244
+ return st.ops.cg(st.lap2, st.coords[k]!, st.b[k]!, st.n, cg);
289
245
  }
290
246
  copyVectorF(st.n, st.coords[k]!, st.tmpCoords);
291
- const rc = conjugateGradientMkernel(st.lap2, st.tmpCoords, st.b[k]!, st.n, TOLERANCE_CG, st.n);
292
- if (rc < 0) return rc;
247
+ const rc = st.ops.cg(st.lap2, st.tmpCoords, st.b[k]!, st.n, cg);
248
+ if (rc !== 0) return rc;
293
249
  for (let i = 0; i < st.n; i++) {
294
250
  if (!isFixed(nodes[i]!)) st.coords[k]![i] = st.tmpCoords[i]!;
295
251
  }
@@ -304,6 +260,8 @@ export interface StressOpts {
304
260
  /** MODEL_* — only the resulting Dij matters here; pass it in. */
305
261
  maxi: number;
306
262
  epsilon: number;
263
+ /** Run the kernels as `stress_majorization_cola` does (mode=ipsep). */
264
+ cola?: boolean;
307
265
  }
308
266
 
309
267
  /**
@@ -338,20 +296,21 @@ export function stressMajorizationKDMkernel(
338
296
  b: Array.from({ length: dim }, () => new Float32Array(n)),
339
297
  tmpCoords: new Float32Array(n),
340
298
  constantTerm,
299
+ ops: o.cola === true ? COLA_OPS : FUSED_OPS,
341
300
  };
342
301
 
343
302
  let oldStress = Number.MAX_VALUE;
344
303
  let converged = false;
345
304
  let iterations = 0;
346
305
  for (; iterations < maxi && !converged; iterations++) {
347
- buildLap1(st.lap1, lap2, coords, { n, dim, exp });
306
+ buildLap1(st.lap1, lap2, coords, { n, dim, exp, ops: st.ops });
348
307
  const newStress = computeStress(st);
349
308
  if (typeof process !== 'undefined' && process.env['STRESS_DEBUG'] && iterations % 5 === 0) console.error(newStress.toFixed(3));
350
309
  const change = Math.abs(oldStress - newStress);
351
310
  converged = change / oldStress < o.epsilon || newStress < o.epsilon;
352
311
  oldStress = newStress;
353
312
  for (let k = 0; k < dim; k++) {
354
- if (solveAxis(st, k, havePinned, nodes) < 0) return -1;
313
+ if (solveAxis(st, k, havePinned, nodes) !== 0) return -1;
355
314
  }
356
315
  }
357
316
 
@@ -14,6 +14,9 @@
14
14
  * @see lib/neatogen/stress.h
15
15
  */
16
16
 
17
+ import { agwarningf } from '../../common/agerr.js';
18
+ import { lateInt } from '../../common/nodeinit.js';
19
+ import type { Graph } from '../../model/graph.js';
17
20
  import type { VtxData } from './dijkstra.js';
18
21
  import {
19
22
  computeApspPacked,
@@ -41,6 +44,22 @@ export const OPT_SMART_INIT = 0x4;
41
44
  /** Exponent flag in opts bitmask (exp=2 when set, exp=1 when clear). */
42
45
  export const OPT_EXP_FLAG = 0x3;
43
46
 
47
+ /** Name of the stress weight-exponent graph attribute. @see lib/neatogen/neatoinit.c:exp_name */
48
+ const EXP_NAME = 'stresswt';
49
+
50
+ /**
51
+ * The `stresswt` exponent, 1 or 2 (default 2).
52
+ * @see lib/neatogen/neatoinit.c:checkExp
53
+ */
54
+ export function checkExp(g: Graph): number {
55
+ const exp = lateInt(g.attrs.get(EXP_NAME), 2, 0);
56
+ if (exp === 0 || exp > 2) {
57
+ agwarningf(`${EXP_NAME} attribute value must be 1 or 2 - ignoring`);
58
+ return 2;
59
+ }
60
+ return exp;
61
+ }
62
+
44
63
  /** Model: MDS (user-supplied edge lengths). */
45
64
  export const MODEL_MDS = 1;
46
65
 
@@ -11,6 +11,7 @@
11
11
  */
12
12
 
13
13
  import type { Graph } from '../../model/graph.js';
14
+ import { gvCleanupEdgeLabels, gvCleanupNodeLabels } from '../dot/init.js';
14
15
  import type { Node } from '../../model/node.js';
15
16
  import type { Box } from '../../model/geom.js';
16
17
  import type { LayoutEngine } from '../../gvc/context.js';
@@ -507,7 +508,11 @@ export function osageLayout(g: Graph): void {
507
508
  /** Recursively clear cluster arrays from g and all subclusters. */
508
509
  export function cleanupGraphs(g: Graph): void {
509
510
  const nClust = g.info.n_cluster ?? 0;
510
- for (let i = 1; i <= nClust; i++) cleanupGraphs(g.info.clust![i - 1]);
511
+ for (let i = 1; i <= nClust; i++) {
512
+ const subg = g.info.clust![i - 1];
513
+ subg.info.label = undefined; // free_label(GD_label(subg))
514
+ cleanupGraphs(subg);
515
+ }
511
516
  g.info.clust = undefined;
512
517
  g.info.n_cluster = undefined;
513
518
  }
@@ -525,6 +530,8 @@ export function cleanupGraphs(g: Graph): void {
525
530
  * @see lib/osage/osageinit.c:osage_cleanup
526
531
  */
527
532
  export function osageCleanup(g: Graph): void {
533
+ for (const e of g.edges) gvCleanupEdgeLabels(e); // gv_cleanup_edge: per-node agfstout, all edges of root g
534
+ for (const n of g.nodes.values()) gvCleanupNodeLabels(n); // gv_cleanup_node
528
535
  for (const n of g.nodes.values()) {
529
536
  if (n.info.alg?.kind === 'osage') n.info.alg = undefined;
530
537
  }
@@ -15,6 +15,7 @@
15
15
  */
16
16
 
17
17
  import type { Graph } from '../../model/graph.js';
18
+ import { gvCleanupEdgeLabels, gvCleanupNodeLabels } from '../dot/init.js';
18
19
  import type { Node } from '../../model/node.js';
19
20
  import type { LayoutEngine } from '../../gvc/context.js';
20
21
  import { ps2inch } from '../pack/index.js';
@@ -425,6 +426,9 @@ export function patchworkEngineLayout(g: Graph): void {
425
426
 
426
427
  /** @see lib/patchwork/patchworkinit.c:patchwork_cleanup */
427
428
  export function patchworkEngineCleanup(g: Graph): void {
429
+ if (g.nodes.size === 0) return; // C: if (!n) return
430
+ for (const e of g.edges) gvCleanupEdgeLabels(e); // gv_cleanup_edge: per-node agfstout, all edges of root g
431
+ for (const n of g.nodes.values()) gvCleanupNodeLabels(n); // gv_cleanup_node
428
432
  g.info.clust = undefined;
429
433
  g.info.n_cluster = undefined;
430
434
  for (const n of g.nodes.values()) { n.info.alg = undefined; }
@@ -12,6 +12,7 @@
12
12
 
13
13
  import { RenderError } from '../../errors.js';
14
14
  import type { Graph } from '../../model/graph.js';
15
+ import { gvCleanupEdgeLabels, gvCleanupNodeLabels } from '../dot/init.js';
15
16
  import { setEdgeTypeFromAttr } from '../dot/index.js';
16
17
  import { EDGETYPE_LINE } from '../neato/splines.js';
17
18
  import { neatoInitNode } from '../neato/init.js';
@@ -264,6 +265,8 @@ export function getPos(g: Graph, dim: number): number[] {
264
265
  * @see lib/sfdpgen/sfdpinit.c:sfdp_cleanup
265
266
  */
266
267
  export function sfdpCleanup(g: Graph): void {
268
+ for (const e of g.edges) gvCleanupEdgeLabels(e); // gv_cleanup_edge: per-node agfstout, all edges of root g
269
+ for (const n of g.nodes.values()) gvCleanupNodeLabels(n); // gv_cleanup_node
267
270
  for (const n of g.nodes.values()) {
268
271
  n.info.pos = undefined;
269
272
  n.info.id = undefined;