@metronforge/concept-map 0.3.1 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (186) hide show
  1. package/README.md +5 -2
  2. package/dist/layout/index.js +4 -11
  3. package/dist/layout/index.js.map +1 -1
  4. package/dist/layout/place-sketch.d.ts +74 -0
  5. package/dist/layout/place-sketch.d.ts.map +1 -0
  6. package/dist/layout/place-sketch.js +16 -0
  7. package/dist/layout/place-sketch.js.map +1 -0
  8. package/dist/layout/place-with-hints.d.ts +7 -0
  9. package/dist/layout/place-with-hints.d.ts.map +1 -0
  10. package/dist/layout/place-with-hints.js +17 -0
  11. package/dist/layout/place-with-hints.js.map +1 -0
  12. package/dist/layout/relations/align-layout.d.ts.map +1 -1
  13. package/dist/layout/relations/align-layout.js +6 -2
  14. package/dist/layout/relations/align-layout.js.map +1 -1
  15. package/dist/layout/relations/apply.js +1 -1
  16. package/dist/layout/relations/apply.js.map +1 -1
  17. package/dist/layout/relations/bounds.d.ts +24 -0
  18. package/dist/layout/relations/bounds.d.ts.map +1 -0
  19. package/dist/layout/relations/bounds.js +126 -0
  20. package/dist/layout/relations/bounds.js.map +1 -0
  21. package/dist/layout/relations/check-linear.d.ts +17 -0
  22. package/dist/layout/relations/check-linear.d.ts.map +1 -0
  23. package/dist/layout/relations/check-linear.js +88 -0
  24. package/dist/layout/relations/check-linear.js.map +1 -0
  25. package/dist/layout/relations/check-objective.d.ts +10 -0
  26. package/dist/layout/relations/check-objective.d.ts.map +1 -0
  27. package/dist/layout/relations/check-objective.js +41 -0
  28. package/dist/layout/relations/check-objective.js.map +1 -0
  29. package/dist/layout/relations/check-witness.d.ts +4 -0
  30. package/dist/layout/relations/check-witness.d.ts.map +1 -1
  31. package/dist/layout/relations/check-witness.js +86 -5
  32. package/dist/layout/relations/check-witness.js.map +1 -1
  33. package/dist/layout/relations/cross.d.ts +1 -1
  34. package/dist/layout/relations/cross.d.ts.map +1 -1
  35. package/dist/layout/relations/cross.js +2 -2
  36. package/dist/layout/relations/cross.js.map +1 -1
  37. package/dist/layout/relations/derive.d.ts.map +1 -1
  38. package/dist/layout/relations/derive.js +18 -9
  39. package/dist/layout/relations/derive.js.map +1 -1
  40. package/dist/layout/relations/derived-input.d.ts +3 -0
  41. package/dist/layout/relations/derived-input.d.ts.map +1 -1
  42. package/dist/layout/relations/derived-input.js +9 -0
  43. package/dist/layout/relations/derived-input.js.map +1 -1
  44. package/dist/layout/relations/explain.d.ts +5 -0
  45. package/dist/layout/relations/explain.d.ts.map +1 -1
  46. package/dist/layout/relations/explain.js +53 -28
  47. package/dist/layout/relations/explain.js.map +1 -1
  48. package/dist/layout/relations/free-witness.d.ts +8 -0
  49. package/dist/layout/relations/free-witness.d.ts.map +1 -0
  50. package/dist/layout/relations/free-witness.js +38 -0
  51. package/dist/layout/relations/free-witness.js.map +1 -0
  52. package/dist/layout/relations/implication.d.ts +4 -0
  53. package/dist/layout/relations/implication.d.ts.map +1 -0
  54. package/dist/layout/relations/implication.js +23 -0
  55. package/dist/layout/relations/implication.js.map +1 -0
  56. package/dist/layout/relations/linear-differences.d.ts +16 -0
  57. package/dist/layout/relations/linear-differences.d.ts.map +1 -0
  58. package/dist/layout/relations/linear-differences.js +57 -0
  59. package/dist/layout/relations/linear-differences.js.map +1 -0
  60. package/dist/layout/relations/linear.d.ts +25 -0
  61. package/dist/layout/relations/linear.d.ts.map +1 -0
  62. package/dist/layout/relations/linear.js +75 -0
  63. package/dist/layout/relations/linear.js.map +1 -0
  64. package/dist/layout/relations/min-cost-flow.d.ts +7 -0
  65. package/dist/layout/relations/min-cost-flow.d.ts.map +1 -0
  66. package/dist/layout/relations/min-cost-flow.js +79 -0
  67. package/dist/layout/relations/min-cost-flow.js.map +1 -0
  68. package/dist/layout/relations/objective.d.ts +14 -0
  69. package/dist/layout/relations/objective.d.ts.map +1 -0
  70. package/dist/layout/relations/objective.js +33 -0
  71. package/dist/layout/relations/objective.js.map +1 -0
  72. package/dist/layout/relations/optimise.d.ts +20 -0
  73. package/dist/layout/relations/optimise.d.ts.map +1 -0
  74. package/dist/layout/relations/optimise.js +54 -0
  75. package/dist/layout/relations/optimise.js.map +1 -0
  76. package/dist/layout/relations/paths.d.ts +6 -0
  77. package/dist/layout/relations/paths.d.ts.map +1 -1
  78. package/dist/layout/relations/paths.js +35 -0
  79. package/dist/layout/relations/paths.js.map +1 -1
  80. package/dist/layout/relations/rank.d.ts +3 -2
  81. package/dist/layout/relations/rank.d.ts.map +1 -1
  82. package/dist/layout/relations/rank.js +5 -5
  83. package/dist/layout/relations/rank.js.map +1 -1
  84. package/dist/layout/relations/rational.d.ts +13 -0
  85. package/dist/layout/relations/rational.d.ts.map +1 -0
  86. package/dist/layout/relations/rational.js +28 -0
  87. package/dist/layout/relations/rational.js.map +1 -0
  88. package/dist/layout/relations/reduce-objective.d.ts +12 -0
  89. package/dist/layout/relations/reduce-objective.d.ts.map +1 -0
  90. package/dist/layout/relations/reduce-objective.js +37 -0
  91. package/dist/layout/relations/reduce-objective.js.map +1 -0
  92. package/dist/layout/relations/sketch-order.d.ts +6 -0
  93. package/dist/layout/relations/sketch-order.d.ts.map +1 -0
  94. package/dist/layout/relations/sketch-order.js +66 -0
  95. package/dist/layout/relations/sketch-order.js.map +1 -0
  96. package/dist/layout/relations/sketch-placement.d.ts +13 -0
  97. package/dist/layout/relations/sketch-placement.d.ts.map +1 -0
  98. package/dist/layout/relations/sketch-placement.js +123 -0
  99. package/dist/layout/relations/sketch-placement.js.map +1 -0
  100. package/dist/layout/relations/sketch-ranks.d.ts +5 -0
  101. package/dist/layout/relations/sketch-ranks.d.ts.map +1 -0
  102. package/dist/layout/relations/sketch-ranks.js +26 -0
  103. package/dist/layout/relations/sketch-ranks.js.map +1 -0
  104. package/dist/layout/relations/solve.d.ts +4 -1
  105. package/dist/layout/relations/solve.d.ts.map +1 -1
  106. package/dist/layout/relations/solve.js +10 -6
  107. package/dist/layout/relations/solve.js.map +1 -1
  108. package/dist/layout/route/channel-layout.d.ts +1 -0
  109. package/dist/layout/route/channel-layout.d.ts.map +1 -1
  110. package/dist/layout/route/channel-layout.js +4 -0
  111. package/dist/layout/route/channel-layout.js.map +1 -1
  112. package/dist/layout/route/channel-moved.d.ts +1 -1
  113. package/dist/layout/route/channel-moved.d.ts.map +1 -1
  114. package/dist/layout/route/channel-moved.js +8 -5
  115. package/dist/layout/route/channel-moved.js.map +1 -1
  116. package/dist/layout/sketch-agreement.d.ts +7 -0
  117. package/dist/layout/sketch-agreement.d.ts.map +1 -0
  118. package/dist/layout/sketch-agreement.js +48 -0
  119. package/dist/layout/sketch-agreement.js.map +1 -0
  120. package/dist/layout/sketch-bends.d.ts +5 -0
  121. package/dist/layout/sketch-bends.d.ts.map +1 -0
  122. package/dist/layout/sketch-bends.js +21 -0
  123. package/dist/layout/sketch-bends.js.map +1 -0
  124. package/dist/layout/sketch-returns.d.ts +4 -0
  125. package/dist/layout/sketch-returns.d.ts.map +1 -0
  126. package/dist/layout/sketch-returns.js +67 -0
  127. package/dist/layout/sketch-returns.js.map +1 -0
  128. package/dist/layout/sketch-route.d.ts +11 -0
  129. package/dist/layout/sketch-route.d.ts.map +1 -0
  130. package/dist/layout/sketch-route.js +109 -0
  131. package/dist/layout/sketch-route.js.map +1 -0
  132. package/dist/layout/sketch-safety.d.ts +6 -0
  133. package/dist/layout/sketch-safety.d.ts.map +1 -0
  134. package/dist/layout/sketch-safety.js +29 -0
  135. package/dist/layout/sketch-safety.js.map +1 -0
  136. package/dist/layout/sketch-shortcuts.d.ts +4 -0
  137. package/dist/layout/sketch-shortcuts.d.ts.map +1 -0
  138. package/dist/layout/sketch-shortcuts.js +51 -0
  139. package/dist/layout/sketch-shortcuts.js.map +1 -0
  140. package/dist/layout/stages/refine.d.ts +1 -1
  141. package/dist/layout/stages/refine.d.ts.map +1 -1
  142. package/dist/layout/stages/refine.js +2 -3
  143. package/dist/layout/stages/refine.js.map +1 -1
  144. package/dist/layout/width.d.ts +1 -0
  145. package/dist/layout/width.d.ts.map +1 -1
  146. package/dist/layout/width.js +3 -0
  147. package/dist/layout/width.js.map +1 -1
  148. package/package.json +2 -2
  149. package/src/layout/index.ts +10 -17
  150. package/src/layout/place-sketch.ts +34 -0
  151. package/src/layout/place-with-hints.ts +32 -0
  152. package/src/layout/relations/align-layout.ts +11 -6
  153. package/src/layout/relations/apply.ts +1 -1
  154. package/src/layout/relations/bounds.ts +163 -0
  155. package/src/layout/relations/check-linear.ts +153 -0
  156. package/src/layout/relations/check-objective.ts +60 -0
  157. package/src/layout/relations/check-witness.ts +118 -5
  158. package/src/layout/relations/cross.ts +2 -1
  159. package/src/layout/relations/derive.ts +24 -9
  160. package/src/layout/relations/derived-input.ts +13 -0
  161. package/src/layout/relations/explain.ts +69 -32
  162. package/src/layout/relations/free-witness.ts +41 -0
  163. package/src/layout/relations/implication.ts +30 -0
  164. package/src/layout/relations/linear-differences.ts +77 -0
  165. package/src/layout/relations/linear.ts +107 -0
  166. package/src/layout/relations/min-cost-flow.ts +96 -0
  167. package/src/layout/relations/objective.ts +53 -0
  168. package/src/layout/relations/optimise.ts +97 -0
  169. package/src/layout/relations/paths.ts +35 -0
  170. package/src/layout/relations/rank.ts +7 -4
  171. package/src/layout/relations/rational.ts +39 -0
  172. package/src/layout/relations/reduce-objective.ts +60 -0
  173. package/src/layout/relations/sketch-order.ts +79 -0
  174. package/src/layout/relations/sketch-placement.ts +168 -0
  175. package/src/layout/relations/sketch-ranks.ts +29 -0
  176. package/src/layout/relations/solve.ts +14 -6
  177. package/src/layout/route/channel-layout.ts +7 -0
  178. package/src/layout/route/channel-moved.ts +8 -6
  179. package/src/layout/sketch-agreement.ts +69 -0
  180. package/src/layout/sketch-bends.ts +29 -0
  181. package/src/layout/sketch-returns.ts +81 -0
  182. package/src/layout/sketch-route.ts +196 -0
  183. package/src/layout/sketch-safety.ts +64 -0
  184. package/src/layout/sketch-shortcuts.ts +65 -0
  185. package/src/layout/stages/refine.ts +2 -4
  186. package/src/layout/width.ts +4 -0
@@ -0,0 +1,163 @@
1
+ import { longestPaths } from "./paths.js";
2
+ import type { RelationEdge, RelationGraph, RelationSource } from "./types.js";
3
+
4
+ export interface RelationBound {
5
+ variable: string;
6
+ determined: boolean;
7
+ lower: number | null;
8
+ upper: number | null;
9
+ lowerPath: RelationSource[] | null;
10
+ upperPath: RelationSource[] | null;
11
+ /** Feasible coordinates in ticks with this finite end reached. */
12
+ lowerAttainment: number[] | null;
13
+ upperAttainment: number[] | null;
14
+ /** A feasible placement and a group that can move without limit. */
15
+ lowerRay: { placement: number[]; variables: string[] } | null;
16
+ upperRay: { placement: number[]; variables: string[] } | null;
17
+ }
18
+
19
+ function ray(
20
+ graph: RelationGraph,
21
+ target: number,
22
+ neighbors: number[][],
23
+ placement: number[],
24
+ ) {
25
+ const seen = new Set([target]);
26
+ const queue = [target];
27
+ for (let i = 0; i < queue.length; i++)
28
+ for (const to of neighbors[queue[i]]) {
29
+ if (seen.has(to)) continue;
30
+ seen.add(to);
31
+ queue.push(to);
32
+ }
33
+ if (seen.has(0)) throw new Error("Unbounded ray reaches the origin");
34
+ return {
35
+ placement,
36
+ variables: queue.sort((a, b) => a - b).map((i) => graph.variables[i - 1]),
37
+ };
38
+ }
39
+
40
+ function attain(graph: RelationGraph, target: number, value: number | null) {
41
+ if (value === null) return null;
42
+ const source = { kind: "anchor" as const, id: "attainment", reverse: false };
43
+ const anchored = {
44
+ ...graph,
45
+ edges: [
46
+ ...graph.edges,
47
+ { from: 0, to: target, weight: value, source },
48
+ { from: target, to: 0, weight: -value, source },
49
+ ],
50
+ };
51
+ const result = longestPaths(
52
+ anchored,
53
+ Array(graph.variables.length + 1).fill(0),
54
+ );
55
+ if (result.changed !== undefined)
56
+ throw new Error("Interval endpoint is infeasible");
57
+ return result.distances.map((distance) => distance - result.distances[0]);
58
+ }
59
+
60
+ function tightPaths(edges: RelationEdge[][], distances: number[]) {
61
+ const paths = new Map<number, RelationSource[]>([[0, []]]);
62
+ const queue = [0];
63
+ for (let i = 0; i < queue.length; i++) {
64
+ const from = queue[i];
65
+ for (const edge of edges[from]) {
66
+ if (paths.has(edge.to)) continue;
67
+ if (distances[edge.to] !== distances[from] + edge.weight) continue;
68
+ paths.set(edge.to, [...paths.get(from)!, edge.source]);
69
+ queue.push(edge.to);
70
+ }
71
+ }
72
+ return paths;
73
+ }
74
+
75
+ function edgeIndex(graph: RelationGraph) {
76
+ const size = graph.variables.length + 1;
77
+ const outgoing: RelationEdge[][] = Array.from({ length: size }, () => []);
78
+ const incoming: RelationEdge[][] = Array.from({ length: size }, () => []);
79
+ const successors: number[][] = Array.from({ length: size }, () => []);
80
+ const predecessors: number[][] = Array.from({ length: size }, () => []);
81
+ for (const edge of graph.edges) {
82
+ outgoing[edge.from].push(edge);
83
+ incoming[edge.to].push({ ...edge, from: edge.to, to: edge.from });
84
+ successors[edge.from].push(edge.to);
85
+ predecessors[edge.to].push(edge.from);
86
+ }
87
+ return { outgoing, incoming, successors, predecessors };
88
+ }
89
+
90
+ function feasiblePlacement(graph: RelationGraph): number[] {
91
+ const initial = Array(graph.variables.length + 1).fill(0);
92
+ const feasible = longestPaths(graph, initial).distances;
93
+ return feasible.map((value) => value - feasible[0]);
94
+ }
95
+
96
+ function startingPlacement(graph: RelationGraph, feasible?: number[]) {
97
+ return feasible
98
+ ? feasible.map((value) => value - feasible[0])
99
+ : feasiblePlacement(graph);
100
+ }
101
+
102
+ function endpointPlacement(
103
+ graph: RelationGraph,
104
+ target: number,
105
+ value: number | null,
106
+ placement: number[],
107
+ ): number[] | null {
108
+ return value !== null && placement[target] === value
109
+ ? placement
110
+ : attain(graph, target, value);
111
+ }
112
+
113
+ function upperValue(negativeUpper: number): number | null {
114
+ if (negativeUpper === -Infinity) return null;
115
+ return negativeUpper === 0 ? 0 : -negativeUpper;
116
+ }
117
+
118
+ function reverseGraph(graph: RelationGraph): RelationGraph {
119
+ return {
120
+ ...graph,
121
+ edges: graph.edges.map((edge) => ({
122
+ ...edge,
123
+ from: edge.to,
124
+ to: edge.from,
125
+ })),
126
+ };
127
+ }
128
+
129
+ /** Feasible bounds in exact 1/64 ticks; null means no bound on that side. */
130
+ export function relationBounds(
131
+ graph: RelationGraph,
132
+ feasible?: number[],
133
+ ): RelationBound[] {
134
+ const initial = [0, ...graph.variables.map(() => -Infinity)];
135
+ const lower = longestPaths(graph, initial).distances;
136
+ // For y = -x, x[to] - x[from] >= weight becomes
137
+ // y[from] - y[to] >= weight. The same path search gives -upper.
138
+ const reversed = reverseGraph(graph);
139
+ const negativeUpper = longestPaths(reversed, initial).distances;
140
+ const index = edgeIndex(graph);
141
+ const lowerPaths = tightPaths(index.outgoing, lower);
142
+ const upperPaths = tightPaths(index.incoming, negativeUpper);
143
+ const placement = startingPlacement(graph, feasible);
144
+ return graph.variables.map((variable, i) => {
145
+ const low = lower[i + 1] === -Infinity ? null : lower[i + 1];
146
+ const high = upperValue(negativeUpper[i + 1]);
147
+ const lowerAttainment = endpointPlacement(graph, i + 1, low, placement);
148
+ return {
149
+ variable,
150
+ determined: low !== null && high !== null && low === high,
151
+ lower: low,
152
+ lowerPath: lowerPaths.get(i + 1) ?? null,
153
+ lowerAttainment,
154
+ upper: high,
155
+ upperPath: upperPaths.get(i + 1) ?? null,
156
+ upperAttainment: endpointPlacement(graph, i + 1, high, placement),
157
+ lowerRay:
158
+ low === null ? ray(graph, i + 1, index.predecessors, placement) : null,
159
+ upperRay:
160
+ high === null ? ray(graph, i + 1, index.successors, placement) : null,
161
+ };
162
+ });
163
+ }
@@ -0,0 +1,153 @@
1
+ import { add, multiply, ratio, zero } from "./rational.js";
2
+ import type { Rational } from "./rational.js";
3
+ import type { LinearRelation } from "./linear.js";
4
+
5
+ type Claim =
6
+ | { status: "contradictory"; witness: Rational[] }
7
+ | { status: "determined"; values: Rational[] }
8
+ | { status: "underdetermined"; particular: Rational[]; basis: Rational[][] };
9
+
10
+ function matrix(variables: string[], relations: LinearRelation[]): bigint[][] {
11
+ const index = new Map(variables.map((name, column) => [name, column]));
12
+ if (index.size !== variables.length)
13
+ throw new Error("Duplicate linear variable");
14
+ return relations.map((relation) => {
15
+ const row = variables.map(() => 0n);
16
+ for (const term of relation.terms) {
17
+ const column = index.get(term.variable);
18
+ if (column === undefined)
19
+ throw new Error(`Unknown linear variable: ${term.variable}`);
20
+ if (
21
+ typeof term.coefficient !== "bigint" &&
22
+ !Number.isSafeInteger(term.coefficient)
23
+ )
24
+ throw new RangeError("Unsafe coefficient");
25
+ row[column] += BigInt(term.coefficient);
26
+ }
27
+ return row;
28
+ });
29
+ }
30
+
31
+ function rank(input: bigint[][], columns: number): number {
32
+ const rows = input.map((row) => [...row]);
33
+ let pivots = 0;
34
+ for (let column = 0; column < columns; column++) {
35
+ const found = rows.findIndex(
36
+ (row, index) => index >= pivots && row[column] !== 0n,
37
+ );
38
+ if (found < 0) continue;
39
+ [rows[pivots], rows[found]] = [rows[found], rows[pivots]];
40
+ for (let index = pivots + 1; index < rows.length; index++) {
41
+ const factor = rows[index][column];
42
+ if (factor === 0n) continue;
43
+ const pivot = rows[pivots][column];
44
+ rows[index] = rows[index].map(
45
+ (value, at) => pivot * value - factor * rows[pivots][at],
46
+ );
47
+ }
48
+ pivots++;
49
+ }
50
+ return pivots;
51
+ }
52
+
53
+ function equals(a: Rational, b: Rational): boolean {
54
+ return (
55
+ a.denominator !== 0n &&
56
+ b.denominator !== 0n &&
57
+ a.numerator * b.denominator === b.numerator * a.denominator
58
+ );
59
+ }
60
+
61
+ function dot(row: bigint[], values: Rational[]): Rational {
62
+ return row.reduce(
63
+ (sum, value, index) => add(sum, multiply(ratio(value), values[index])),
64
+ zero,
65
+ );
66
+ }
67
+
68
+ function satisfies(
69
+ rows: bigint[][],
70
+ right: bigint[],
71
+ values: Rational[],
72
+ columns: number,
73
+ ): boolean {
74
+ return (
75
+ values.length === columns &&
76
+ rows.every((row, index) => equals(dot(row, values), ratio(right[index])))
77
+ );
78
+ }
79
+
80
+ function checksConflict(
81
+ rows: bigint[][],
82
+ right: bigint[],
83
+ witness: Rational[],
84
+ columns: number,
85
+ ): boolean {
86
+ if (witness.length !== rows.length) return false;
87
+ const left = Array.from({ length: columns }, (_, column) =>
88
+ dot(
89
+ rows.map((row) => row[column]),
90
+ witness,
91
+ ),
92
+ );
93
+ return (
94
+ left.every((value) => equals(value, zero)) &&
95
+ !equals(dot(right, witness), zero)
96
+ );
97
+ }
98
+
99
+ function checksBasis(
100
+ rows: bigint[][],
101
+ directions: Rational[][],
102
+ columns: number,
103
+ ): boolean {
104
+ if (directions.length !== columns - rank(rows, columns)) return false;
105
+ if (
106
+ !directions.every((direction) =>
107
+ satisfies(
108
+ rows,
109
+ rows.map(() => 0n),
110
+ direction,
111
+ columns,
112
+ ),
113
+ )
114
+ )
115
+ return false;
116
+ const integers = directions.map((direction) => {
117
+ const factor = direction.reduce(
118
+ (product, value) => product * value.denominator,
119
+ 1n,
120
+ );
121
+ return direction.map(
122
+ (value) => (value.numerator * factor) / value.denominator,
123
+ );
124
+ });
125
+ return rank(integers, columns) === directions.length;
126
+ }
127
+
128
+ /** Check exact equality certificates using only the source equations and claim. */
129
+ export function checkLinearEqualities(
130
+ variables: string[],
131
+ relations: LinearRelation[],
132
+ claim: Claim,
133
+ ): boolean {
134
+ const rows = matrix(variables, relations);
135
+ const right = relations.map((relation) => {
136
+ if (
137
+ typeof relation.constant !== "bigint" &&
138
+ !Number.isSafeInteger(relation.constant)
139
+ )
140
+ throw new RangeError("Unsafe constant");
141
+ return BigInt(relation.constant);
142
+ });
143
+ const columns = variables.length;
144
+ if (claim.status === "contradictory")
145
+ return checksConflict(rows, right, claim.witness, columns);
146
+ if (claim.status === "determined")
147
+ return (
148
+ rank(rows, columns) === columns &&
149
+ satisfies(rows, right, claim.values, columns)
150
+ );
151
+ if (!satisfies(rows, right, claim.particular, columns)) return false;
152
+ return checksBasis(rows, claim.basis, columns);
153
+ }
@@ -0,0 +1,60 @@
1
+ import type { ArrowTerm } from "./objective.js";
2
+ import type { RelationGraph } from "./types.js";
3
+
4
+ /** A flow on each bound and a signed slope for each absolute-value term. */
5
+ export interface ObjectiveCertificate {
6
+ slopes: number[];
7
+ flows: number[];
8
+ }
9
+
10
+ function validShape(
11
+ graph: RelationGraph,
12
+ terms: ArrowTerm[],
13
+ positions: number[],
14
+ certificate: ObjectiveCertificate,
15
+ ): boolean {
16
+ return (
17
+ positions.length === graph.variables.length + 1 &&
18
+ certificate.slopes.length === terms.length &&
19
+ certificate.flows.length === graph.edges.length &&
20
+ positions[0] === 0 &&
21
+ positions.every(Number.isSafeInteger)
22
+ );
23
+ }
24
+
25
+ /** Check feasibility and equal primal/dual values without running an optimiser. */
26
+ export function checkObjectiveCertificate(
27
+ graph: RelationGraph,
28
+ terms: ArrowTerm[],
29
+ positions: number[],
30
+ certificate: ObjectiveCertificate,
31
+ ): boolean {
32
+ const count = graph.variables.length + 1;
33
+ if (!validShape(graph, terms, positions, certificate)) return false;
34
+ const values = positions.map(BigInt);
35
+ const balance = Array<bigint>(count).fill(0n);
36
+ let primal = 0n;
37
+ let dual = 0n;
38
+ for (const [i, edge] of graph.edges.entries()) {
39
+ const flow = certificate.flows[i];
40
+ if (!Number.isSafeInteger(flow) || flow < 0) return false;
41
+ if (values[edge.to] - values[edge.from] < BigInt(edge.weight)) return false;
42
+ const amount = BigInt(flow);
43
+ balance[edge.from] += amount;
44
+ balance[edge.to] -= amount;
45
+ dual += amount * BigInt(edge.weight);
46
+ }
47
+ for (const [i, term] of terms.entries()) {
48
+ const slope = certificate.slopes[i];
49
+ if (!Number.isSafeInteger(slope) || Math.abs(slope) > term.weight)
50
+ return false;
51
+ const difference =
52
+ values[term.from] - values[term.to] + BigInt(term.offset);
53
+ primal +=
54
+ BigInt(term.weight) * (difference < 0n ? -difference : difference);
55
+ dual += BigInt(slope) * BigInt(term.offset);
56
+ balance[term.from] += BigInt(slope);
57
+ balance[term.to] -= BigInt(slope);
58
+ }
59
+ return balance.slice(1).every((value) => value === 0n) && primal === dual;
60
+ }
@@ -1,4 +1,5 @@
1
1
  import type { RelationEdge, RelationGraph, RelationSource } from "./types.js";
2
+ import type { RelationBound } from "./bounds.js";
2
3
 
3
4
  /** Claims can contain extreme values: use integers even for their differences. */
4
5
  export function exactTicks(value: number): bigint | undefined {
@@ -73,15 +74,127 @@ export function checkShift(
73
74
  (id) => graph.variables.indexOf(id) + 1,
74
75
  );
75
76
  const moving = new Set(indices);
76
- if (delta === undefined || delta >= 0n || !moving.size || moving.has(0))
77
+ if (delta === undefined || delta === 0n || !moving.size || moving.has(0))
77
78
  return false;
78
79
  if (moving.size !== indices.length) return false;
79
- // No incoming bound: the set can move down indefinitely, not just through
80
- // slack in a nonminimal placement of an otherwise determined system.
81
- if (graph.edges.some((edge) => moving.has(edge.to) && !moving.has(edge.from)))
82
- return false;
80
+ // A second feasible placement proves freedom even when a bound limits
81
+ // how far the group can move.
83
82
  return satisfies(
84
83
  graph,
85
84
  coordinates.map((value, i) => value + (moving.has(i) ? delta : 0n)),
86
85
  );
87
86
  }
87
+
88
+ /** Check a path to the origin, or independently prove that none exists. */
89
+ function checkBoundPath(
90
+ graph: RelationGraph,
91
+ target: number,
92
+ value: number | null,
93
+ path: RelationSource[] | null,
94
+ reverse: boolean,
95
+ ): boolean {
96
+ const seen = new Set([0]);
97
+ const queue = [0];
98
+ for (let i = 0; i < queue.length; i++)
99
+ for (const edge of graph.edges) {
100
+ const from = reverse ? edge.to : edge.from;
101
+ const to = reverse ? edge.from : edge.to;
102
+ if (from !== queue[i] || seen.has(to)) continue;
103
+ seen.add(to);
104
+ queue.push(to);
105
+ }
106
+ if (value === null) return path === null && !seen.has(target);
107
+ if (!Number.isSafeInteger(value) || !path?.length || !seen.has(target))
108
+ return false;
109
+ let vertex = 0;
110
+ let weight = 0n;
111
+ for (const source of path) {
112
+ const edge = sourceEdge(graph, source);
113
+ if (!edge || (reverse ? edge.to : edge.from) !== vertex) return false;
114
+ vertex = reverse ? edge.from : edge.to;
115
+ weight += BigInt(edge.weight);
116
+ }
117
+ return vertex === target && weight === BigInt(reverse ? -value : value);
118
+ }
119
+
120
+ function checkAttainment(
121
+ graph: RelationGraph,
122
+ target: number,
123
+ value: number | null,
124
+ placement: number[] | null,
125
+ ): boolean {
126
+ if (value === null) return placement === null;
127
+ if (
128
+ !Array.isArray(placement) ||
129
+ placement.length !== graph.variables.length + 1
130
+ )
131
+ return false;
132
+ if (placement[0] !== 0 || placement[target] !== value) return false;
133
+ if (!placement.every(Number.isSafeInteger)) return false;
134
+ return satisfies(graph, placement.map(BigInt));
135
+ }
136
+
137
+ function checkRay(
138
+ graph: RelationGraph,
139
+ target: number,
140
+ value: number | null,
141
+ ray: { placement: number[]; variables: string[] } | null,
142
+ upward: boolean,
143
+ ): boolean {
144
+ if (value !== null) return ray === null;
145
+ if (!ray || !Array.isArray(ray.placement) || !Array.isArray(ray.variables))
146
+ return false;
147
+ if (
148
+ ray.placement.length !== graph.variables.length + 1 ||
149
+ ray.placement[0] !== 0
150
+ )
151
+ return false;
152
+ if (!ray.placement.every(Number.isSafeInteger)) return false;
153
+ const moving = new Set(
154
+ ray.variables.map((id) => graph.variables.indexOf(id) + 1),
155
+ );
156
+ if (
157
+ moving.has(0) ||
158
+ !moving.has(target) ||
159
+ moving.size !== ray.variables.length
160
+ )
161
+ return false;
162
+ if (!satisfies(graph, ray.placement.map(BigInt))) return false;
163
+ return graph.edges.every((edge) =>
164
+ upward
165
+ ? !moving.has(edge.from) || moving.has(edge.to)
166
+ : !moving.has(edge.to) || moving.has(edge.from),
167
+ );
168
+ }
169
+
170
+ /** Check endpoint paths, reachability and feasible attainment independently. */
171
+ export function checkRelationBoundPaths(
172
+ graph: RelationGraph,
173
+ bounds: RelationBound[],
174
+ ): boolean {
175
+ if (bounds.length !== graph.variables.length) return false;
176
+ return bounds.every(
177
+ (bound, i) =>
178
+ bound.variable === graph.variables[i] &&
179
+ bound.determined ===
180
+ (bound.lower !== null &&
181
+ bound.upper !== null &&
182
+ bound.lower === bound.upper) &&
183
+ checkBoundPath(graph, i + 1, bound.lower, bound.lowerPath, false) &&
184
+ checkBoundPath(graph, i + 1, bound.upper, bound.upperPath, true) &&
185
+ checkAttainment(graph, i + 1, bound.lower, bound.lowerAttainment) &&
186
+ checkAttainment(graph, i + 1, bound.upper, bound.upperAttainment) &&
187
+ checkRay(graph, i + 1, bound.lower, bound.lowerRay, false) &&
188
+ checkRay(graph, i + 1, bound.upper, bound.upperRay, true),
189
+ );
190
+ }
191
+ export function checkRelationBoundStatus(
192
+ graph: RelationGraph,
193
+ bounds: RelationBound[],
194
+ status: "determined" | "underdetermined" | "contradictory",
195
+ ): boolean {
196
+ if (status === "contradictory" || !checkRelationBoundPaths(graph, bounds))
197
+ return false;
198
+ const fixed = bounds.every((bound) => bound.determined);
199
+ return status === (fixed ? "determined" : "underdetermined");
200
+ }
@@ -45,6 +45,7 @@ export function crossRelations(
45
45
  problem: LayoutProblem,
46
46
  boxes: LayoutResult["nodes"],
47
47
  nodeGap: number,
48
+ minimum?: number,
48
49
  ): RelationSystem {
49
50
  const direction = problem.constraints.find((c) => c.kind === "direction");
50
51
  const axis = direction?.direction === "right" ? 1 : 0;
@@ -64,7 +65,7 @@ export function crossRelations(
64
65
  from: origin,
65
66
  to: id,
66
67
  kind: "minimum",
67
- gap: boxes[id][axis],
68
+ gap: minimum ?? boxes[id][axis],
68
69
  })),
69
70
  ...separationRelations(
70
71
  problem.nodes.map(({ id }) => id),
@@ -1,9 +1,14 @@
1
- /** Derived positions stay on the 1/64 grid: a + round(k * (b - a) / n)
2
- * in ticks, ties toward minus infinity. Error is at most half a tick (1/128
3
- * drawing unit). Integer division avoids floating-point products and ties.
4
- * These positions are computed after placement and add no solver constraints.
1
+ /** Check an exact linear equality for each derived position, then round its
2
+ * rational solution to the 1/64 grid. Ties go toward minus infinity and the
3
+ * error is at most half a tick. Derivations add no box constraints.
5
4
  */
6
- import { prepareDerivations, roundRatio } from "./derived-input.js";
5
+ import {
6
+ derivedEquation,
7
+ prepareDerivations,
8
+ roundRatio,
9
+ } from "./derived-input.js";
10
+ import { solveLinearEqualities } from "./linear.js";
11
+ import { checkLinearEqualities } from "./check-linear.js";
7
12
  import type { DerivedPosition } from "./derived-input.js";
8
13
  import type { RelationPlacement } from "./result.js";
9
14
 
@@ -11,8 +16,18 @@ export function derivePositions(
11
16
  placements: RelationPlacement[],
12
17
  requests: DerivedPosition[],
13
18
  ): RelationPlacement[] {
14
- return prepareDerivations(placements, requests).map(({ id, a, b, k, n }) => ({
15
- variable: id,
16
- position: Number(a + roundRatio(k * (b - a), n)) / 64,
17
- }));
19
+ return prepareDerivations(placements, requests).map((input) => {
20
+ const equation = derivedEquation(input);
21
+ const result = solveLinearEqualities([input.id], [equation]);
22
+ if (
23
+ result.status !== "determined" ||
24
+ !checkLinearEqualities([input.id], [equation], result)
25
+ )
26
+ throw new Error("Invalid derived equality certificate");
27
+ const value = result.values[0];
28
+ return {
29
+ variable: input.id,
30
+ position: Number(roundRatio(value.numerator, value.denominator)) / 64,
31
+ };
32
+ });
18
33
  }
@@ -1,5 +1,6 @@
1
1
  import { exactTicks } from "./check-witness.js";
2
2
  import type { RelationPlacement } from "./result.js";
3
+ import type { LinearRelation } from "./linear.js";
3
4
 
4
5
  /** A position at part / parts between two already placed variables.
5
6
  * Midpoints use part = 1, parts = 2; rows use successive parts from 0 to parts.
@@ -52,6 +53,18 @@ export function prepareDerivations(
52
53
  });
53
54
  }
54
55
 
56
+ /** Exact unrounded relation n * position = (n - k) * a + k * b. */
57
+ export function derivedEquation(
58
+ input: ReturnType<typeof prepareDerivations>[number],
59
+ ): LinearRelation {
60
+ const { id, a, b, k, n } = input;
61
+ return {
62
+ kind: "linear",
63
+ terms: [{ variable: id, coefficient: n }],
64
+ constant: (n - k) * a + k * b,
65
+ };
66
+ }
67
+
55
68
  /** Exact nearest integer, with ties toward minus infinity, even below zero. */
56
69
  export function roundRatio(numerator: bigint, denominator: bigint): bigint {
57
70
  const remainder = ((numerator % denominator) + denominator) % denominator;