@metronforge/concept-map 0.3.2 → 0.4.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 (201) hide show
  1. package/README.md +5 -2
  2. package/dist/layout/hints.d.ts +2 -2
  3. package/dist/layout/hints.d.ts.map +1 -1
  4. package/dist/layout/hints.js.map +1 -1
  5. package/dist/layout/index.d.ts +1 -6
  6. package/dist/layout/index.d.ts.map +1 -1
  7. package/dist/layout/index.js +1 -89
  8. package/dist/layout/index.js.map +1 -1
  9. package/dist/layout/layout.d.ts +7 -0
  10. package/dist/layout/layout.d.ts.map +1 -0
  11. package/dist/layout/layout.js +83 -0
  12. package/dist/layout/layout.js.map +1 -0
  13. package/dist/layout/place-sketch.d.ts +74 -0
  14. package/dist/layout/place-sketch.d.ts.map +1 -0
  15. package/dist/layout/place-sketch.js +20 -0
  16. package/dist/layout/place-sketch.js.map +1 -0
  17. package/dist/layout/place-with-hints.d.ts +7 -0
  18. package/dist/layout/place-with-hints.d.ts.map +1 -0
  19. package/dist/layout/place-with-hints.js +17 -0
  20. package/dist/layout/place-with-hints.js.map +1 -0
  21. package/dist/layout/relations/align-layout.d.ts.map +1 -1
  22. package/dist/layout/relations/align-layout.js +6 -2
  23. package/dist/layout/relations/align-layout.js.map +1 -1
  24. package/dist/layout/relations/apply.js +1 -1
  25. package/dist/layout/relations/apply.js.map +1 -1
  26. package/dist/layout/relations/bounds.d.ts +24 -0
  27. package/dist/layout/relations/bounds.d.ts.map +1 -0
  28. package/dist/layout/relations/bounds.js +126 -0
  29. package/dist/layout/relations/bounds.js.map +1 -0
  30. package/dist/layout/relations/check-linear.d.ts +17 -0
  31. package/dist/layout/relations/check-linear.d.ts.map +1 -0
  32. package/dist/layout/relations/check-linear.js +88 -0
  33. package/dist/layout/relations/check-linear.js.map +1 -0
  34. package/dist/layout/relations/check-objective.d.ts +10 -0
  35. package/dist/layout/relations/check-objective.d.ts.map +1 -0
  36. package/dist/layout/relations/check-objective.js +41 -0
  37. package/dist/layout/relations/check-objective.js.map +1 -0
  38. package/dist/layout/relations/check-witness.d.ts +4 -0
  39. package/dist/layout/relations/check-witness.d.ts.map +1 -1
  40. package/dist/layout/relations/check-witness.js +86 -5
  41. package/dist/layout/relations/check-witness.js.map +1 -1
  42. package/dist/layout/relations/cross.d.ts +1 -1
  43. package/dist/layout/relations/cross.d.ts.map +1 -1
  44. package/dist/layout/relations/cross.js +2 -2
  45. package/dist/layout/relations/cross.js.map +1 -1
  46. package/dist/layout/relations/derive.d.ts.map +1 -1
  47. package/dist/layout/relations/derive.js +18 -9
  48. package/dist/layout/relations/derive.js.map +1 -1
  49. package/dist/layout/relations/derived-input.d.ts +3 -0
  50. package/dist/layout/relations/derived-input.d.ts.map +1 -1
  51. package/dist/layout/relations/derived-input.js +9 -0
  52. package/dist/layout/relations/derived-input.js.map +1 -1
  53. package/dist/layout/relations/explain.d.ts +5 -0
  54. package/dist/layout/relations/explain.d.ts.map +1 -1
  55. package/dist/layout/relations/explain.js +53 -28
  56. package/dist/layout/relations/explain.js.map +1 -1
  57. package/dist/layout/relations/free-witness.d.ts +8 -0
  58. package/dist/layout/relations/free-witness.d.ts.map +1 -0
  59. package/dist/layout/relations/free-witness.js +38 -0
  60. package/dist/layout/relations/free-witness.js.map +1 -0
  61. package/dist/layout/relations/implication.d.ts +4 -0
  62. package/dist/layout/relations/implication.d.ts.map +1 -0
  63. package/dist/layout/relations/implication.js +23 -0
  64. package/dist/layout/relations/implication.js.map +1 -0
  65. package/dist/layout/relations/linear-differences.d.ts +16 -0
  66. package/dist/layout/relations/linear-differences.d.ts.map +1 -0
  67. package/dist/layout/relations/linear-differences.js +57 -0
  68. package/dist/layout/relations/linear-differences.js.map +1 -0
  69. package/dist/layout/relations/linear.d.ts +25 -0
  70. package/dist/layout/relations/linear.d.ts.map +1 -0
  71. package/dist/layout/relations/linear.js +75 -0
  72. package/dist/layout/relations/linear.js.map +1 -0
  73. package/dist/layout/relations/min-cost-flow.d.ts +7 -0
  74. package/dist/layout/relations/min-cost-flow.d.ts.map +1 -0
  75. package/dist/layout/relations/min-cost-flow.js +79 -0
  76. package/dist/layout/relations/min-cost-flow.js.map +1 -0
  77. package/dist/layout/relations/objective.d.ts +14 -0
  78. package/dist/layout/relations/objective.d.ts.map +1 -0
  79. package/dist/layout/relations/objective.js +33 -0
  80. package/dist/layout/relations/objective.js.map +1 -0
  81. package/dist/layout/relations/optimise.d.ts +20 -0
  82. package/dist/layout/relations/optimise.d.ts.map +1 -0
  83. package/dist/layout/relations/optimise.js +54 -0
  84. package/dist/layout/relations/optimise.js.map +1 -0
  85. package/dist/layout/relations/paths.d.ts +6 -0
  86. package/dist/layout/relations/paths.d.ts.map +1 -1
  87. package/dist/layout/relations/paths.js +35 -0
  88. package/dist/layout/relations/paths.js.map +1 -1
  89. package/dist/layout/relations/rank.d.ts +3 -2
  90. package/dist/layout/relations/rank.d.ts.map +1 -1
  91. package/dist/layout/relations/rank.js +5 -5
  92. package/dist/layout/relations/rank.js.map +1 -1
  93. package/dist/layout/relations/rational.d.ts +13 -0
  94. package/dist/layout/relations/rational.d.ts.map +1 -0
  95. package/dist/layout/relations/rational.js +28 -0
  96. package/dist/layout/relations/rational.js.map +1 -0
  97. package/dist/layout/relations/reduce-objective.d.ts +12 -0
  98. package/dist/layout/relations/reduce-objective.d.ts.map +1 -0
  99. package/dist/layout/relations/reduce-objective.js +37 -0
  100. package/dist/layout/relations/reduce-objective.js.map +1 -0
  101. package/dist/layout/relations/sketch-order.d.ts +7 -0
  102. package/dist/layout/relations/sketch-order.d.ts.map +1 -0
  103. package/dist/layout/relations/sketch-order.js +67 -0
  104. package/dist/layout/relations/sketch-order.js.map +1 -0
  105. package/dist/layout/relations/sketch-placement.d.ts +14 -0
  106. package/dist/layout/relations/sketch-placement.d.ts.map +1 -0
  107. package/dist/layout/relations/sketch-placement.js +123 -0
  108. package/dist/layout/relations/sketch-placement.js.map +1 -0
  109. package/dist/layout/relations/sketch-ranks.d.ts +5 -0
  110. package/dist/layout/relations/sketch-ranks.d.ts.map +1 -0
  111. package/dist/layout/relations/sketch-ranks.js +26 -0
  112. package/dist/layout/relations/sketch-ranks.js.map +1 -0
  113. package/dist/layout/relations/solve.d.ts +4 -1
  114. package/dist/layout/relations/solve.d.ts.map +1 -1
  115. package/dist/layout/relations/solve.js +10 -6
  116. package/dist/layout/relations/solve.js.map +1 -1
  117. package/dist/layout/route/channel-layout.d.ts +1 -0
  118. package/dist/layout/route/channel-layout.d.ts.map +1 -1
  119. package/dist/layout/route/channel-layout.js +4 -0
  120. package/dist/layout/route/channel-layout.js.map +1 -1
  121. package/dist/layout/route/channel-moved.d.ts +1 -1
  122. package/dist/layout/route/channel-moved.d.ts.map +1 -1
  123. package/dist/layout/route/channel-moved.js +8 -5
  124. package/dist/layout/route/channel-moved.js.map +1 -1
  125. package/dist/layout/sketch-agreement.d.ts +7 -0
  126. package/dist/layout/sketch-agreement.d.ts.map +1 -0
  127. package/dist/layout/sketch-agreement.js +48 -0
  128. package/dist/layout/sketch-agreement.js.map +1 -0
  129. package/dist/layout/sketch-bends.d.ts +5 -0
  130. package/dist/layout/sketch-bends.d.ts.map +1 -0
  131. package/dist/layout/sketch-bends.js +21 -0
  132. package/dist/layout/sketch-bends.js.map +1 -0
  133. package/dist/layout/sketch-conflicts.d.ts +8 -0
  134. package/dist/layout/sketch-conflicts.d.ts.map +1 -0
  135. package/dist/layout/sketch-conflicts.js +56 -0
  136. package/dist/layout/sketch-conflicts.js.map +1 -0
  137. package/dist/layout/sketch-returns.d.ts +4 -0
  138. package/dist/layout/sketch-returns.d.ts.map +1 -0
  139. package/dist/layout/sketch-returns.js +67 -0
  140. package/dist/layout/sketch-returns.js.map +1 -0
  141. package/dist/layout/sketch-route.d.ts +12 -0
  142. package/dist/layout/sketch-route.d.ts.map +1 -0
  143. package/dist/layout/sketch-route.js +109 -0
  144. package/dist/layout/sketch-route.js.map +1 -0
  145. package/dist/layout/sketch-safety.d.ts +6 -0
  146. package/dist/layout/sketch-safety.d.ts.map +1 -0
  147. package/dist/layout/sketch-safety.js +29 -0
  148. package/dist/layout/sketch-safety.js.map +1 -0
  149. package/dist/layout/sketch-shortcuts.d.ts +4 -0
  150. package/dist/layout/sketch-shortcuts.d.ts.map +1 -0
  151. package/dist/layout/sketch-shortcuts.js +51 -0
  152. package/dist/layout/sketch-shortcuts.js.map +1 -0
  153. package/dist/layout/stages/hints.d.ts.map +1 -1
  154. package/dist/layout/stages/hints.js +33 -15
  155. package/dist/layout/stages/hints.js.map +1 -1
  156. package/dist/layout/width.d.ts +1 -0
  157. package/dist/layout/width.d.ts.map +1 -1
  158. package/dist/layout/width.js +3 -0
  159. package/dist/layout/width.js.map +1 -1
  160. package/package.json +2 -2
  161. package/src/layout/hints.ts +2 -2
  162. package/src/layout/index.ts +1 -155
  163. package/src/layout/layout.ts +147 -0
  164. package/src/layout/place-sketch.ts +39 -0
  165. package/src/layout/place-with-hints.ts +32 -0
  166. package/src/layout/relations/align-layout.ts +11 -6
  167. package/src/layout/relations/apply.ts +1 -1
  168. package/src/layout/relations/bounds.ts +163 -0
  169. package/src/layout/relations/check-linear.ts +153 -0
  170. package/src/layout/relations/check-objective.ts +60 -0
  171. package/src/layout/relations/check-witness.ts +118 -5
  172. package/src/layout/relations/cross.ts +2 -1
  173. package/src/layout/relations/derive.ts +24 -9
  174. package/src/layout/relations/derived-input.ts +13 -0
  175. package/src/layout/relations/explain.ts +69 -32
  176. package/src/layout/relations/free-witness.ts +41 -0
  177. package/src/layout/relations/implication.ts +30 -0
  178. package/src/layout/relations/linear-differences.ts +77 -0
  179. package/src/layout/relations/linear.ts +107 -0
  180. package/src/layout/relations/min-cost-flow.ts +96 -0
  181. package/src/layout/relations/objective.ts +53 -0
  182. package/src/layout/relations/optimise.ts +97 -0
  183. package/src/layout/relations/paths.ts +35 -0
  184. package/src/layout/relations/rank.ts +7 -4
  185. package/src/layout/relations/rational.ts +39 -0
  186. package/src/layout/relations/reduce-objective.ts +60 -0
  187. package/src/layout/relations/sketch-order.ts +90 -0
  188. package/src/layout/relations/sketch-placement.ts +174 -0
  189. package/src/layout/relations/sketch-ranks.ts +29 -0
  190. package/src/layout/relations/solve.ts +14 -6
  191. package/src/layout/route/channel-layout.ts +7 -0
  192. package/src/layout/route/channel-moved.ts +8 -6
  193. package/src/layout/sketch-agreement.ts +69 -0
  194. package/src/layout/sketch-bends.ts +29 -0
  195. package/src/layout/sketch-conflicts.ts +69 -0
  196. package/src/layout/sketch-returns.ts +81 -0
  197. package/src/layout/sketch-route.ts +199 -0
  198. package/src/layout/sketch-safety.ts +64 -0
  199. package/src/layout/sketch-shortcuts.ts +65 -0
  200. package/src/layout/stages/hints.ts +47 -19
  201. package/src/layout/width.ts +4 -0
@@ -37,8 +37,10 @@ function forwardRelations(
37
37
  }));
38
38
  }
39
39
 
40
- function hintRelations(problem: LayoutProblem): DifferenceRelation[] {
41
- return problem.constraints.flatMap((hint, index) => {
40
+ export function hintRelations(
41
+ constraints: LayoutProblem["constraints"],
42
+ ): DifferenceRelation[] {
43
+ return constraints.flatMap((hint, index) => {
42
44
  if (hint.kind !== "sameRank") return [];
43
45
  return hint.nodes.slice(1).map((node, i) => ({
44
46
  id: `${hint.path ?? `constraints[${index}]`}.nodes[${i + 1}]`,
@@ -58,6 +60,7 @@ export function rankRelations(
58
60
  problem: LayoutProblem,
59
61
  boxes: LayoutResult["nodes"],
60
62
  rankGap: number,
63
+ minimum?: number,
61
64
  ): RelationSystem {
62
65
  const direction = problem.constraints.find((c) => c.kind === "direction");
63
66
  const axis = direction?.direction === "right" ? 0 : 1;
@@ -77,10 +80,10 @@ export function rankRelations(
77
80
  from: origin,
78
81
  to: id,
79
82
  kind: "minimum",
80
- gap: boxes[id][axis],
83
+ gap: minimum ?? boxes[id][axis],
81
84
  })),
82
85
  ...forwardRelations(problem, boxes, axis, rankGap),
83
- ...hintRelations(problem),
86
+ ...hintRelations(problem.constraints),
84
87
  ],
85
88
  };
86
89
  }
@@ -0,0 +1,39 @@
1
+ /** Exact reduced rational used by the internal equality solver. */
2
+ export interface Rational {
3
+ numerator: bigint;
4
+ denominator: bigint;
5
+ }
6
+
7
+ function gcd(a: bigint, b: bigint): bigint {
8
+ while (b !== 0n) [a, b] = [b, a % b];
9
+ return a < 0n ? -a : a;
10
+ }
11
+
12
+ export function ratio(numerator: bigint, denominator = 1n): Rational {
13
+ if (denominator === 0n) throw new RangeError("Zero denominator");
14
+ if (denominator < 0n) return ratio(-numerator, -denominator);
15
+ const divisor = gcd(numerator, denominator);
16
+ return { numerator: numerator / divisor, denominator: denominator / divisor };
17
+ }
18
+
19
+ export function add(a: Rational, b: Rational): Rational {
20
+ return ratio(
21
+ a.numerator * b.denominator + b.numerator * a.denominator,
22
+ a.denominator * b.denominator,
23
+ );
24
+ }
25
+
26
+ export function negate(a: Rational): Rational {
27
+ return { numerator: -a.numerator, denominator: a.denominator };
28
+ }
29
+
30
+ export function multiply(a: Rational, b: Rational): Rational {
31
+ return ratio(a.numerator * b.numerator, a.denominator * b.denominator);
32
+ }
33
+
34
+ export function divide(a: Rational, b: Rational): Rational {
35
+ return ratio(a.numerator * b.denominator, a.denominator * b.numerator);
36
+ }
37
+
38
+ export const zero = ratio(0n);
39
+ export const one = ratio(1n);
@@ -0,0 +1,60 @@
1
+ import type { ArrowTerm } from "./objective.js";
2
+ import type { RelationEdge, RelationGraph } from "./types.js";
3
+
4
+ export interface ReducedObjective {
5
+ graph: RelationGraph;
6
+ costs: number[];
7
+ constant: bigint;
8
+ }
9
+
10
+ /** Each arrow gets a node above both endpoints, making L1 cost linear. */
11
+ export function reduceArrowObjective(
12
+ graph: RelationGraph,
13
+ terms: ArrowTerm[],
14
+ ): ReducedObjective {
15
+ const variables = [...graph.variables];
16
+ const edges = [...graph.edges];
17
+ const costs = graph.edges.map(() => 0);
18
+ let constant = 0n;
19
+ for (const [i, term] of terms.entries()) {
20
+ let id = `#arrow:${i}`;
21
+ while (variables.includes(id)) id = `#${id}`;
22
+ variables.push(id);
23
+ const auxiliary = variables.length;
24
+ const source: RelationEdge["source"] = {
25
+ kind: "relation",
26
+ id,
27
+ reverse: false,
28
+ };
29
+ edges.push(
30
+ { from: term.from, to: auxiliary, weight: 0, source },
31
+ { from: term.to, to: auxiliary, weight: -term.offset, source },
32
+ );
33
+ costs.push(term.weight, term.weight);
34
+ constant += BigInt(term.weight) * BigInt(term.offset);
35
+ }
36
+ return {
37
+ graph: { variables, sizes: [...graph.sizes, ...terms.map(() => 0)], edges },
38
+ costs,
39
+ constant,
40
+ };
41
+ }
42
+
43
+ /** Evaluate the linear objective in exact grid-tick integers. */
44
+ export function reducedCost(
45
+ reduced: ReducedObjective,
46
+ positions: number[],
47
+ ): bigint {
48
+ if (
49
+ positions.length !== reduced.graph.variables.length + 1 ||
50
+ !positions.every(Number.isSafeInteger)
51
+ )
52
+ throw new RangeError("Reduced positions must be exact grid ticks");
53
+ return reduced.graph.edges.reduce(
54
+ (sum, edge, i) =>
55
+ sum +
56
+ BigInt(reduced.costs[i]) *
57
+ (BigInt(positions[edge.to]) - BigInt(positions[edge.from])),
58
+ reduced.constant,
59
+ );
60
+ }
@@ -0,0 +1,90 @@
1
+ import { rankTick } from "./sketch-ranks.js";
2
+ import type { LayoutProblem } from "../problem.js";
3
+ import { checkRelations } from "./check.js";
4
+ import { solveRelations } from "./solve.js";
5
+ import type { DifferenceRelation, RelationSystem } from "./types.js";
6
+
7
+ export type RecordSketchConflict = (
8
+ relation: DifferenceRelation,
9
+ cycle: readonly string[],
10
+ ) => void;
11
+
12
+ /** Restore the engine bound for each sketch pair in a checked positive cycle. */
13
+ export function restoreConflicts(
14
+ system: RelationSystem,
15
+ originals: ReadonlyMap<string, DifferenceRelation | null>,
16
+ record?: RecordSketchConflict,
17
+ ): DifferenceRelation[] | null {
18
+ const dropped: DifferenceRelation[] = [];
19
+ for (;;) {
20
+ const result = solveRelations(system);
21
+ if (result.status !== "contradictory") break;
22
+ if (!checkRelations(system, result))
23
+ throw new Error("Invalid sketch cycle");
24
+ const pairs = new Set(
25
+ result.cycle.filter((s) => s.kind === "relation").map((s) => s.id),
26
+ );
27
+ const count = dropped.length;
28
+ system.relations = system.relations.flatMap((relation) => {
29
+ const engine = originals.get(relation.id);
30
+ if (engine === undefined || !pairs.has(relation.id)) return relation;
31
+ dropped.push(relation);
32
+ record?.(
33
+ relation,
34
+ result.cycle.map((source) => source.id),
35
+ );
36
+ return engine ?? [];
37
+ });
38
+ if (dropped.length === count) return null;
39
+ }
40
+ return dropped;
41
+ }
42
+
43
+ function preferredPins(problem: LayoutProblem) {
44
+ return new Map(
45
+ problem.constraints.flatMap((c) =>
46
+ c.kind === "pin" && c.strength === "preferred"
47
+ ? [[c.node, c.position] as const]
48
+ : [],
49
+ ),
50
+ );
51
+ }
52
+
53
+ export function followSketchOrder(
54
+ problem: LayoutProblem,
55
+ system: RelationSystem,
56
+ cross: 0 | 1,
57
+ gap: number,
58
+ record?: RecordSketchConflict,
59
+ ): DifferenceRelation[] | null {
60
+ const rank = 1 - cross;
61
+ const pins = preferredPins(problem);
62
+ const originals = new Map<string, DifferenceRelation | null>();
63
+ const indices = new Map(system.relations.map((r, i) => [r.id, i]));
64
+ for (const [from, a] of pins) {
65
+ for (const [to, b] of pins) {
66
+ if (rankTick(a[rank]) !== rankTick(b[rank]) || a[cross] >= b[cross])
67
+ continue;
68
+ if (indices.has(`separate.${from}:${to}`)) continue;
69
+ const id = `sketch.${from}:${to}`;
70
+ const order: DifferenceRelation = {
71
+ id,
72
+ from,
73
+ to,
74
+ kind: "minimum",
75
+ gap,
76
+ size: from,
77
+ };
78
+ const reverse = indices.get(`separate.${to}:${from}`);
79
+ if (reverse === undefined) {
80
+ // Boxes on separate drawn ranks have no engine bound to restore.
81
+ originals.set(id, null);
82
+ system.relations.push(order);
83
+ } else {
84
+ originals.set(id, system.relations[reverse]);
85
+ system.relations[reverse] = order;
86
+ }
87
+ }
88
+ }
89
+ return restoreConflicts(system, originals, record);
90
+ }
@@ -0,0 +1,174 @@
1
+ import type { LayoutProblem } from "../problem.js";
2
+ import type { LayoutResult } from "../types.js";
3
+ import { crossRelations } from "./cross.js";
4
+ import { normalizeRelations } from "./normalize.js";
5
+ import { sketchRanks } from "./sketch-ranks.js";
6
+ import { hintRelations, rankRelations } from "./rank.js";
7
+ import { solveRelations } from "./solve.js";
8
+ import type { RelationGraph, RelationSystem } from "./types.js";
9
+ import { arrowObjective } from "./objective.js";
10
+ import { optimiseArrows } from "./optimise.js";
11
+ import type { RecordSketchConflict } from "./sketch-order.js";
12
+ import { followSketchOrder, restoreConflicts } from "./sketch-order.js";
13
+
14
+ /** Measure centre-to-pin distance against the graph's fixed zero vertex. */
15
+ function pinObjective(
16
+ problem: LayoutProblem,
17
+ graph: RelationGraph,
18
+ axis: 0 | 1,
19
+ ) {
20
+ const vertices = new Map(graph.variables.map((id, i) => [id, i + 1]));
21
+ return problem.constraints.flatMap((hint) => {
22
+ if (hint.kind !== "pin" || hint.strength !== "preferred") return [];
23
+ const from = vertices.get(hint.node)!;
24
+ const offset = -Math.round(
25
+ hint.position[axis] * 64 - graph.sizes[from - 1] / 2,
26
+ );
27
+ if (!Number.isSafeInteger(offset))
28
+ throw new RangeError(
29
+ "Preferred pin offset exceeds the exact integer range",
30
+ );
31
+ return [{ from, to: 0, weight: 1, offset }];
32
+ });
33
+ }
34
+
35
+ /** Propose certified cross-axis positions after engine placement. Rank
36
+ * coordinates stay fixed; boxes sharing a rank follow their sketch pins.
37
+ * Routing and quality inspection decide separately whether to use the result.
38
+ */
39
+ export function sketchPlacement(
40
+ problem: LayoutProblem,
41
+ original: LayoutResult,
42
+ minimum?: number,
43
+ sketchOrder = true,
44
+ record?: RecordSketchConflict,
45
+ ): LayoutResult["nodes"] | null {
46
+ const direction = problem.constraints.find((c) => c.kind === "direction");
47
+ const cross = direction?.direction === "right" ? 1 : 0;
48
+ const gap = 16;
49
+ const system = crossRelations(problem, original.nodes, gap, minimum);
50
+ containMembers(problem, original, system, cross);
51
+ if (
52
+ sketchOrder
53
+ ? !followSketchOrder(problem, system, cross, gap, record)
54
+ : solveRelations(system).status === "contradictory"
55
+ )
56
+ return null;
57
+ const graph = normalizeRelations(system);
58
+ return placeAxis(original, graph, cross, [
59
+ ...arrowObjective(problem, graph),
60
+ ...pinObjective(problem, graph, cross),
61
+ ]);
62
+ }
63
+
64
+ /** Keep the existing lane boxes while optimising member positions inside them. */
65
+ function containMembers(
66
+ problem: LayoutProblem,
67
+ original: LayoutResult,
68
+ system: RelationSystem,
69
+ axis: 0 | 1,
70
+ preserveHeading = false,
71
+ ) {
72
+ const origin = system.anchors[0].variable;
73
+ for (const lane of problem.groups) {
74
+ const members = problem.nodes.filter((node) => node.lane === lane.id);
75
+ // Keep the engine's heading space while using the full trailing extent.
76
+ const boxes = members.map((node) => original.nodes[node.id]);
77
+ const laneBox = original.lanes[lane.id];
78
+ const start = preserveHeading
79
+ ? Math.min(...boxes.map((box) => box[axis]))
80
+ : laneBox[axis];
81
+ const end = laneBox[axis] + laneBox[axis + 2];
82
+ for (const { id } of members) {
83
+ system.relations.push(
84
+ {
85
+ id: `lane.start.${id}`,
86
+ from: origin,
87
+ to: id,
88
+ kind: "minimum",
89
+ gap: start,
90
+ },
91
+ {
92
+ id: `lane.end.${id}`,
93
+ from: id,
94
+ to: origin,
95
+ kind: "minimum",
96
+ gap: -end,
97
+ size: id,
98
+ },
99
+ );
100
+ }
101
+ }
102
+ }
103
+
104
+ /** The rank axis fits pin centres subject to forward-arrow gaps. */
105
+ export function sketchRankPlacement(
106
+ problem: LayoutProblem,
107
+ original: LayoutResult,
108
+ groupRanks = false,
109
+ record?: RecordSketchConflict,
110
+ ) {
111
+ const direction = problem.constraints.find((c) => c.kind === "direction");
112
+ const rank = direction?.direction === "right" ? 0 : 1;
113
+ const system = rankRelations(problem, original.nodes, 64, 0);
114
+ containMembers(problem, original, system, rank, true);
115
+ const groups = groupRanks ? hintRelations(sketchRanks(problem, rank)) : [];
116
+ if (groupRanks && !groups.length) return null;
117
+ system.relations.push(...groups);
118
+ if (
119
+ !restoreConflicts(system, new Map(groups.map((r) => [r.id, null])), record)
120
+ )
121
+ return null;
122
+ const graph = normalizeRelations(system);
123
+ return placeAxis(original, graph, rank, pinObjective(problem, graph, rank));
124
+ }
125
+
126
+ function placeAxis(
127
+ original: LayoutResult,
128
+ graph: RelationGraph,
129
+ axis: 0 | 1,
130
+ terms: ReturnType<typeof arrowObjective>,
131
+ ) {
132
+ if (!terms.length) return null;
133
+ try {
134
+ const optimum = optimiseArrows(graph, terms, [
135
+ 0,
136
+ ...graph.variables.map((id) => (original.nodes[id]?.[axis] ?? 0) * 64),
137
+ ]);
138
+ if (!optimum) return null;
139
+ return Object.fromEntries(
140
+ graph.variables.slice(1).map((id, i) => {
141
+ const box = [...original.nodes[id]] as LayoutResult["nodes"][string];
142
+ box[axis] = optimum.positions[i + 2] / 64;
143
+ return [id, box];
144
+ }),
145
+ );
146
+ } catch (error) {
147
+ if (
148
+ error instanceof Error &&
149
+ error.message.includes("objective pivot limit")
150
+ )
151
+ return null;
152
+ throw error;
153
+ }
154
+ }
155
+
156
+ export function sketchPlacements(
157
+ problem: LayoutProblem,
158
+ original: LayoutResult,
159
+ record?: RecordSketchConflict,
160
+ ) {
161
+ const placements = [
162
+ sketchPlacement(problem, original, 0, false),
163
+ sketchPlacement(problem, original, 0, true, record),
164
+ ];
165
+ for (const grouped of [false, true]) {
166
+ const ranked = sketchRankPlacement(problem, original, grouped, record);
167
+ if (!ranked) continue;
168
+ placements.push(
169
+ ranked,
170
+ sketchPlacement(problem, { ...original, nodes: ranked }, 0, true, record),
171
+ );
172
+ }
173
+ return placements;
174
+ }
@@ -0,0 +1,29 @@
1
+ import type { Constraint, LayoutProblem } from "../problem.js";
2
+
3
+ export function rankTick(coordinate: number): number {
4
+ return Math.round(coordinate * 64);
5
+ }
6
+
7
+ /** Pin centres on the same solver tick describe a preferred rank. */
8
+ export function sketchRanks(problem: LayoutProblem, rank: 0 | 1): Constraint[] {
9
+ const groups = new Map<number, Set<string>>();
10
+ for (const hint of problem.constraints) {
11
+ if (hint.kind !== "pin" || hint.strength !== "preferred") continue;
12
+ const tick = rankTick(hint.position[rank]);
13
+ const group = groups.get(tick) ?? new Set<string>();
14
+ group.add(hint.node);
15
+ groups.set(tick, group);
16
+ }
17
+ return [...groups].flatMap(([tick, members]) =>
18
+ members.size < 2
19
+ ? []
20
+ : [
21
+ {
22
+ kind: "sameRank",
23
+ strength: "preferred",
24
+ path: `sketch.rank.${tick}`,
25
+ nodes: [...members],
26
+ },
27
+ ],
28
+ );
29
+ }
@@ -49,12 +49,11 @@ function feasibleResult(
49
49
  };
50
50
  }
51
51
 
52
- /** Internal proposal only: independent witness checking is a separate step. */
53
- export function solveRelations(system: RelationSystem): RelationSolution {
54
- const graph = normalizeRelations(system);
55
- // Starting everywhere detects contradictions outside the anchored component.
56
- const initial = Array<number>(graph.variables.length + 1).fill(0);
57
- const paths = longestPaths(graph, initial);
52
+ /** Turn already relaxed exact paths into a checked witness candidate. */
53
+ export function solutionFromPaths(
54
+ graph: RelationGraph,
55
+ paths: ReturnType<typeof longestPaths>,
56
+ ): RelationSolution {
58
57
  if (paths.changed !== undefined) {
59
58
  const cycle = positiveCycle(paths.predecessors, paths.changed);
60
59
  return {
@@ -65,3 +64,12 @@ export function solveRelations(system: RelationSystem): RelationSolution {
65
64
  }
66
65
  return feasibleResult(graph, paths.distances);
67
66
  }
67
+
68
+ /** Internal proposal only: independent witness checking is a separate step. */
69
+ export function solveRelations(system: RelationSystem): RelationSolution {
70
+ const graph = normalizeRelations(system);
71
+ // Starting everywhere detects contradictions outside the anchored component.
72
+ const initial = Array<number>(graph.variables.length + 1).fill(0);
73
+ const paths = longestPaths(graph, initial);
74
+ return solutionFromPaths(graph, paths);
75
+ }
@@ -28,3 +28,10 @@ export function routeLayout(
28
28
  }
29
29
  return { ...original, nodes, edges };
30
30
  }
31
+
32
+ export function routeBounds(nodes: LayoutResult["nodes"]): [number, number] {
33
+ const boxes = Object.values(nodes);
34
+ return [0, 1].map(
35
+ (axis) => Math.max(...boxes.map((box) => box[axis] + box[axis + 2])) + 20,
36
+ ) as [number, number];
37
+ }
@@ -8,6 +8,7 @@ export function routeMoved(
8
8
  nodes: LayoutResult["nodes"],
9
9
  viewBox: LayoutPoint,
10
10
  pins: ReadonlySet<string> = new Set(),
11
+ perpendicular = false,
11
12
  ): LayoutResult | null {
12
13
  const moved = (id: string) =>
13
14
  nodes[id].some(
@@ -21,7 +22,7 @@ export function routeMoved(
21
22
  if (!pins.has(edge.from) || !pins.has(edge.to)) return [];
22
23
  const from = nodes[edge.from],
23
24
  to = nodes[edge.to];
24
- return [[edge.id, pinnedSides(from, to)]];
25
+ return [[edge.id, pinnedSides(from, to, perpendicular)]];
25
26
  }),
26
27
  ) as NonNullable<Parameters<typeof routeLayout>[4]>;
27
28
  return edges.length
@@ -32,15 +33,16 @@ export function routeMoved(
32
33
  function pinnedSides(
33
34
  from: LayoutResult["nodes"][string],
34
35
  to: LayoutResult["nodes"][string],
36
+ perpendicular: boolean,
35
37
  ) {
36
38
  const dx = to[0] + to[2] / 2 - from[0] - from[2] / 2;
37
39
  const dy = to[1] + to[3] / 2 - from[1] - from[3] / 2;
40
+ const gapX = Math.abs(dx) - (from[2] + to[2]) / 2;
41
+ const gapY = Math.abs(dy) - (from[3] + to[3]) / 2;
42
+ if (perpendicular && gapX > 0 && gapY > 0)
43
+ return { from: dx > 0 ? "right" : "left", to: dy > 0 ? "top" : "bottom" };
38
44
  if (Math.abs(dx) >= Math.abs(dy)) {
39
- if (
40
- Math.abs(dx) < (from[2] + to[2]) / 2 &&
41
- Math.abs(dy) < (from[3] + to[3]) / 2
42
- )
43
- return { from: "bottom", to: "bottom" };
45
+ if (gapX < 0 && gapY < 0) return { from: "bottom", to: "bottom" };
44
46
  return dx >= 0
45
47
  ? { from: "right", to: "left" }
46
48
  : { from: "left", to: "right" };
@@ -0,0 +1,69 @@
1
+ import { bendCount } from "./sketch-bends.js";
2
+ import { rankTick } from "./relations/sketch-ranks.js";
3
+ import type { LayoutProblem } from "./problem.js";
4
+ import type { LayoutResult } from "./types.js";
5
+
6
+ export function sketchOrder(
7
+ problem: LayoutProblem,
8
+ nodes: LayoutResult["nodes"],
9
+ ): number {
10
+ const direction = problem.constraints.find((c) => c.kind === "direction");
11
+ const cross = direction?.direction === "right" ? 1 : 0;
12
+ const rank = 1 - cross;
13
+ const pins = problem.constraints.filter(
14
+ (c): c is Extract<typeof c, { kind: "pin" }> =>
15
+ c.kind === "pin" && c.strength === "preferred",
16
+ );
17
+ let matching = 0;
18
+ for (const [index, first] of pins.entries())
19
+ for (const second of pins.slice(index + 1)) {
20
+ if (rankTick(first.position[rank]) !== rankTick(second.position[rank]))
21
+ continue;
22
+ const hand = Math.sign(first.position[cross] - second.position[cross]);
23
+ const a = nodes[first.node];
24
+ const b = nodes[second.node];
25
+ const drawn = Math.sign(
26
+ a[cross] + a[cross + 2] / 2 - b[cross] - b[cross + 2] / 2,
27
+ );
28
+ if (hand && hand === drawn) matching++;
29
+ }
30
+ return matching;
31
+ }
32
+ /** Compare the shape of a sketch independently of its origin. */
33
+ export function translatedPinDistance(
34
+ problem: LayoutProblem,
35
+ result: LayoutResult,
36
+ ): number {
37
+ const offsets = problem.constraints.flatMap((hint) => {
38
+ if (hint.kind !== "pin" || hint.strength !== "preferred") return [];
39
+ const [x, y, width, height] = result.nodes[hint.node];
40
+ return [
41
+ [x + width / 2 - hint.position[0], y + height / 2 - hint.position[1]],
42
+ ];
43
+ });
44
+ if (!offsets.length) return 0;
45
+ const meanX = offsets.reduce((sum, [x]) => sum + x, 0) / offsets.length;
46
+ const meanY = offsets.reduce((sum, [, y]) => sum + y, 0) / offsets.length;
47
+ return offsets.reduce(
48
+ (sum, [x, y]) => sum + Math.hypot(x - meanX, y - meanY),
49
+ 0,
50
+ );
51
+ }
52
+
53
+ export function meritsSketchCheck(
54
+ problem: LayoutProblem,
55
+ orderGain: number,
56
+ best: LayoutResult,
57
+ option: LayoutResult,
58
+ ): boolean {
59
+ const bends = bendCount(option);
60
+ const bestBends = bendCount(best);
61
+ return (
62
+ (orderGain >= 0 && bends < bestBends) ||
63
+ (orderGain > 0 && bends <= bestBends + 4) ||
64
+ (orderGain === 0 &&
65
+ bends === bestBends &&
66
+ translatedPinDistance(problem, option) <
67
+ translatedPinDistance(problem, best))
68
+ );
69
+ }
@@ -0,0 +1,29 @@
1
+ import type { ResolvedMap } from "../schema.js";
2
+ import type { LayoutResult } from "./types.js";
3
+ import type { Vec } from "./stages/plane.js";
4
+ import { polylines } from "./stages/paths.js";
5
+
6
+ export function resolvedBends(resolved: ResolvedMap): number {
7
+ return turns(
8
+ Object.values(resolved.edges).flatMap((edge) => polylines(edge.path)),
9
+ );
10
+ }
11
+
12
+ export function bendCount(result: LayoutResult): number {
13
+ return turns(Object.values(result.edges).map((edge) => edge.points));
14
+ }
15
+
16
+ function turns(lines: Vec[][]): number {
17
+ let total = 0;
18
+ for (const points of lines) {
19
+ for (let i = 1; i < points.length - 1; i++) {
20
+ const [a, b, c] = [points[i - 1], points[i], points[i + 1]];
21
+ const ux = b[0] - a[0],
22
+ uy = b[1] - a[1];
23
+ const vx = c[0] - b[0],
24
+ vy = c[1] - b[1];
25
+ if (Math.abs(ux * vy - uy * vx) > 1e-7 || ux * vx + uy * vy < 0) total++;
26
+ }
27
+ }
28
+ return total;
29
+ }
@@ -0,0 +1,69 @@
1
+ import type { LayoutProblem } from "./problem.js";
2
+ import type { UnsupportedHint } from "./types.js";
3
+ import { sketchRanks } from "./relations/sketch-ranks.js";
4
+ import { hintRelations } from "./relations/rank.js";
5
+ import type { RecordSketchConflict } from "./relations/sketch-order.js";
6
+
7
+ /** Translate checked solver cycles to the author's pin and lane paths. */
8
+ function conflictPaths(
9
+ problem: LayoutProblem,
10
+ pins: ReadonlyMap<string, { path?: string }>,
11
+ ) {
12
+ const pairs = new Map<string, readonly string[]>();
13
+ for (const from of pins.keys())
14
+ for (const to of pins.keys()) pairs.set(`sketch.${from}:${to}`, [from, to]);
15
+ const direction = problem.constraints.find(
16
+ (hint) => hint.kind === "direction",
17
+ );
18
+ for (const relation of hintRelations(
19
+ sketchRanks(problem, direction?.direction === "right" ? 0 : 1),
20
+ ))
21
+ pairs.set(relation.id, [relation.from, relation.to]);
22
+ const paths = new Map(
23
+ [...pairs].map(([id, nodes]) => [
24
+ id,
25
+ nodes.map((node) => pins.get(node)!.path!),
26
+ ]),
27
+ );
28
+ for (const node of problem.nodes) {
29
+ if (!node.lane) continue;
30
+ paths.set(`lane.start.${node.id}`, [`lanes.${node.lane}`]);
31
+ paths.set(`lane.end.${node.id}`, [`lanes.${node.lane}`]);
32
+ }
33
+ return paths;
34
+ }
35
+
36
+ export function sketchConflicts(problem: LayoutProblem) {
37
+ const pins = new Map(
38
+ problem.constraints.flatMap((hint) =>
39
+ hint.kind === "pin" && hint.strength === "preferred" && hint.path
40
+ ? [[hint.node, hint] as const]
41
+ : [],
42
+ ),
43
+ );
44
+ const paths = conflictPaths(problem, pins);
45
+ const hints: UnsupportedHint[] = [];
46
+ const seen = new Set<string>();
47
+ const record: RecordSketchConflict = (relation, cycle) => {
48
+ const conflicts = cycle.flatMap((id) => paths.get(id) ?? [id]);
49
+ for (const node of [relation.from, relation.to]) {
50
+ const pin = pins.get(node);
51
+ if (!pin) continue;
52
+ const hint: UnsupportedHint = {
53
+ kind: "pin",
54
+ node,
55
+ at: [...pin.position],
56
+ strength: pin.strength,
57
+ origin: "stated",
58
+ path: pin.path!,
59
+ reason: "contradiction",
60
+ conflicts,
61
+ };
62
+ const key = JSON.stringify(hint);
63
+ if (seen.has(key)) continue;
64
+ seen.add(key);
65
+ hints.push(hint);
66
+ }
67
+ };
68
+ return { hints, record };
69
+ }