@mark1russell7/layout-contract 0.2.17 → 0.2.19

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.
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "$schema": "https://json.schemastore.org/package",
3
3
  "name": "@mark1russell7/layout-contract",
4
- "version": "0.2.17",
4
+ "version": "0.2.19",
5
5
  "description": "The shared contract of the packing and highways layout engines: the input and record formats, the turn rule, margins, tolerances and hard rules.",
6
6
  "keywords": [
7
7
  "layout",
package/src/balance.ts ADDED
@@ -0,0 +1,233 @@
1
+ import { SIDES, type Rect, type Side } from "./geometry.ts";
2
+ import type { MeasureSpec } from "./measures.ts";
3
+ import { SHAPE_KIND_IDS, type ShapeKind } from "./shapes.ts";
4
+
5
+ /** A placed box: its id and its bounding box. */
6
+ export interface PlacedBox extends Rect {
7
+ readonly id: string;
8
+ }
9
+
10
+ /** The balance of one layout. `docs/BALANCE.md` gives the definitions. */
11
+ export interface Balance {
12
+ /** The standard deviation of the nearest-neighbour gaps divided by their mean. */
13
+ readonly gapCv: number;
14
+ /** The distance from the centroid of the free area to the center of the container, as a share of the half-diagonal. */
15
+ readonly centroidOffset: number;
16
+ /** The empty share of the strip at each side of the container. */
17
+ readonly side: Readonly<Record<Side, number>>;
18
+ /** The largest value of `side` minus the smallest value. */
19
+ readonly sideRange: number;
20
+ }
21
+
22
+ /** The depth of the strip of each side, as a share of the container. For `top` and `bottom`, it is a share of the height. For `left` and `right`, it is a share of the width. */
23
+ export const BALANCE_SIDE_DEPTH = 0.25;
24
+
25
+ /** A suffix of a balance or stability measure. A stage adds its prefix, for example `pack.balance.gapCv`. */
26
+ export type BalanceMeasureSuffix =
27
+ | "balance.gapCv"
28
+ | "balance.centroidOffset"
29
+ | "balance.side.top"
30
+ | "balance.side.right"
31
+ | "balance.side.bottom"
32
+ | "balance.side.left"
33
+ | "balance.sideRange"
34
+ | "stability.procrustes"
35
+ | "stability.seed";
36
+
37
+ /** The suffixes of the balance and stability measures, in the order of `docs/BALANCE.md`. */
38
+ export const BALANCE_MEASURE_SUFFIXES: readonly BalanceMeasureSuffix[] = Object.freeze([
39
+ "balance.gapCv",
40
+ "balance.centroidOffset",
41
+ "balance.side.top",
42
+ "balance.side.right",
43
+ "balance.side.bottom",
44
+ "balance.side.left",
45
+ "balance.sideRange",
46
+ "stability.procrustes",
47
+ "stability.seed",
48
+ ] as const);
49
+
50
+ /** This function gives the area of the overlap of two rectangles. */
51
+ function overlapArea(a: Rect, b: Rect): number {
52
+ const w = Math.min(a.x + a.w, b.x + b.w) - Math.max(a.x, b.x);
53
+ const h = Math.min(a.y + a.h, b.y + b.h) - Math.max(a.y, b.y);
54
+ return w > 0 && h > 0 ? w * h : 0;
55
+ }
56
+
57
+ /** This function gives the distance between two rectangles. Two rectangles that touch or overlap give 0. */
58
+ function rectDistance(a: Rect, b: Rect): number {
59
+ const dx = Math.max(0, b.x - (a.x + a.w), a.x - (b.x + b.w));
60
+ const dy = Math.max(0, b.y - (a.y + a.h), a.y - (b.y + b.h));
61
+ return Math.hypot(dx, dy);
62
+ }
63
+
64
+ /**
65
+ * This function gives the gap of each box to its nearest other box, in the order of `boxes`.
66
+ * Each box scans the boxes sorted by `x` in the two directions. A scan stops when the distance on `x` alone is above the best gap of the box.
67
+ * To the left, the distance on `x` is at least `a.x - b.x - maxW`, with `maxW` the largest width. With fewer than 2 boxes, a gap is `Infinity`.
68
+ */
69
+ export function nearestGaps(boxes: readonly Rect[]): number[] {
70
+ const order = boxes.map((_, i) => i).sort((i, j) => boxes[i]!.x - boxes[j]!.x || i - j);
71
+ const maxW = boxes.reduce((m, b) => Math.max(m, b.w), 0);
72
+ const gaps = new Array<number>(boxes.length).fill(Infinity);
73
+ for (let k = 0; k < order.length; k++) {
74
+ const a = boxes[order[k]!]!;
75
+ let best = Infinity;
76
+ for (let m = k + 1; m < order.length; m++) {
77
+ const b = boxes[order[m]!]!;
78
+ if (b.x - (a.x + a.w) > best) break;
79
+ best = Math.min(best, rectDistance(a, b));
80
+ }
81
+ for (let m = k - 1; m >= 0; m--) {
82
+ const b = boxes[order[m]!]!;
83
+ if (a.x - b.x - maxW > best) break;
84
+ best = Math.min(best, rectDistance(a, b));
85
+ }
86
+ gaps[order[k]!] = best;
87
+ }
88
+ return gaps;
89
+ }
90
+
91
+ /**
92
+ * This function gives the balance of the placed boxes in the container: the evenness of the gaps and the place of the free space.
93
+ * The boxes do not overlap, as in the output of a packer. The area of a box outside the container does not count.
94
+ * `docs/BALANCE.md` gives the definitions and the reasons.
95
+ */
96
+ export function balanceOf(boxes: readonly Rect[], container: Rect): Balance {
97
+ const gaps = boxes.length < 2 ? [] : nearestGaps(boxes);
98
+ const mean = gaps.length === 0 ? 0 : gaps.reduce((s, g) => s + g, 0) / gaps.length;
99
+ const sd = gaps.length === 0 ? 0 : Math.sqrt(gaps.reduce((s, g) => s + (g - mean) ** 2, 0) / gaps.length);
100
+ const gapCv = mean > 0 ? sd / mean : 0;
101
+
102
+ const area = container.w * container.h;
103
+ const cx = container.x + container.w / 2;
104
+ const cy = container.y + container.h / 2;
105
+ let used = 0;
106
+ let mx = 0;
107
+ let my = 0;
108
+ for (const b of boxes) {
109
+ const x0 = Math.max(b.x, container.x);
110
+ const y0 = Math.max(b.y, container.y);
111
+ const x1 = Math.min(b.x + b.w, container.x + container.w);
112
+ const y1 = Math.min(b.y + b.h, container.y + container.h);
113
+ if (x1 <= x0 || y1 <= y0) continue;
114
+ const a = (x1 - x0) * (y1 - y0);
115
+ used += a;
116
+ mx += a * (x0 + x1) / 2;
117
+ my += a * (y0 + y1) / 2;
118
+ }
119
+ const free = area - used;
120
+ const half = Math.hypot(container.w, container.h) / 2;
121
+ let centroidOffset = 0;
122
+ if (free > 0 && half > 0) {
123
+ const fx = (area * cx - mx) / free;
124
+ const fy = (area * cy - my) / free;
125
+ centroidOffset = Math.min(1, Math.hypot(fx - cx, fy - cy) / half);
126
+ }
127
+
128
+ const dh = container.h * BALANCE_SIDE_DEPTH;
129
+ const dw = container.w * BALANCE_SIDE_DEPTH;
130
+ const strips: Record<Side, Rect> = {
131
+ top: { x: container.x, y: container.y, w: container.w, h: dh },
132
+ right: { x: container.x + container.w - dw, y: container.y, w: dw, h: container.h },
133
+ bottom: { x: container.x, y: container.y + container.h - dh, w: container.w, h: dh },
134
+ left: { x: container.x, y: container.y, w: dw, h: container.h },
135
+ };
136
+ const side = {} as Record<Side, number>;
137
+ for (const s of SIDES) {
138
+ const strip = strips[s];
139
+ const stripArea = strip.w * strip.h;
140
+ const filled = boxes.reduce((sum, b) => sum + overlapArea(b, strip), 0);
141
+ side[s] = stripArea > 0 ? Math.min(1, Math.max(0, 1 - filled / stripArea)) : 0;
142
+ }
143
+ const values = SIDES.map((s) => side[s]);
144
+ return { gapCv, centroidOffset, side, sideRange: Math.max(...values) - Math.min(...values) };
145
+ }
146
+
147
+ /** The options of `procrustesOf`. */
148
+ export interface ProcrustesOptions {
149
+ /** The unit of the result: the width `W` of the base, as in `joint.stability.mean`. A finite number above 0. */
150
+ readonly unit: number;
151
+ /** With `true` (the default), the alignment also rotates. With `false`, it only moves. */
152
+ readonly rotate?: boolean;
153
+ }
154
+
155
+ /**
156
+ * This function gives the root mean square move of the box centers from `base` to `next`, after the best alignment, in units of `unit`.
157
+ * The alignment is the orthogonal Procrustes fit: one move and, by default, one rotation. Only the ids in the two lists count.
158
+ * Fewer than 2 shared ids give 0, because the alignment then removes each move.
159
+ */
160
+ export function procrustesOf(base: readonly PlacedBox[], next: readonly PlacedBox[], options: ProcrustesOptions): number {
161
+ if (!(Number.isFinite(options.unit) && options.unit > 0)) throw new RangeError(`procrustesOf: the unit is a finite number above 0, not ${options.unit}.`);
162
+ const after = new Map(next.map((b) => [b.id, b]));
163
+ const a: [number, number][] = [];
164
+ const b: [number, number][] = [];
165
+ for (const p of base) {
166
+ const q = after.get(p.id);
167
+ if (q === undefined) continue;
168
+ a.push([p.x + p.w / 2, p.y + p.h / 2]);
169
+ b.push([q.x + q.w / 2, q.y + q.h / 2]);
170
+ }
171
+ const n = a.length;
172
+ if (n < 2) return 0;
173
+ const mean = (list: [number, number][]): [number, number] => [list.reduce((s, p) => s + p[0], 0) / n, list.reduce((s, p) => s + p[1], 0) / n];
174
+ const [ax, ay] = mean(a);
175
+ const [bx, by] = mean(b);
176
+ let dot = 0;
177
+ let cross = 0;
178
+ for (let i = 0; i < n; i++) {
179
+ const [px, py] = [a[i]![0] - ax, a[i]![1] - ay];
180
+ const [qx, qy] = [b[i]![0] - bx, b[i]![1] - by];
181
+ dot += px * qx + py * qy;
182
+ cross += px * qy - py * qx;
183
+ }
184
+ const theta = options.rotate === false || (dot === 0 && cross === 0) ? 0 : Math.atan2(cross, dot);
185
+ const cos = Math.cos(theta);
186
+ const sin = Math.sin(theta);
187
+ let sum = 0;
188
+ for (let i = 0; i < n; i++) {
189
+ const [px, py] = [a[i]![0] - ax, a[i]![1] - ay];
190
+ const [qx, qy] = [b[i]![0] - bx, b[i]![1] - by];
191
+ sum += (cos * px - sin * py - qx) ** 2 + (sin * px + cos * py - qy) ** 2;
192
+ }
193
+ return Math.sqrt(sum / n) / options.unit;
194
+ }
195
+
196
+ /**
197
+ * This function gives the value of `stability.procrustes`: the move of `procrustesOf` divided by the change share.
198
+ * The change share is `changed / count`, and it is at least `1 / count`. Thus a change of one box divides by the smallest share.
199
+ */
200
+ export function perChange(move: number, changed: number, count: number): number {
201
+ if (!(Number.isInteger(count) && count >= 1)) throw new RangeError(`perChange: the count is an integer of 1 or more, not ${count}.`);
202
+ const share = Math.max(1, Math.min(count, changed)) / count;
203
+ return move / share;
204
+ }
205
+
206
+ /** This function gives the balance values as measures, with the prefix of the stage, for example `pack.balance.gapCv`. */
207
+ export function balanceMeasures<S extends string>(stage: S, balance: Balance): Record<`${S}.${BalanceMeasureSuffix}`, number> {
208
+ const m: Record<string, number> = {
209
+ [`${stage}.balance.gapCv`]: balance.gapCv,
210
+ [`${stage}.balance.centroidOffset`]: balance.centroidOffset,
211
+ [`${stage}.balance.sideRange`]: balance.sideRange,
212
+ };
213
+ for (const s of SIDES) m[`${stage}.balance.side.${s}`] = balance.side[s];
214
+ return m as Record<`${S}.${BalanceMeasureSuffix}`, number>;
215
+ }
216
+
217
+ /**
218
+ * This function gives the specs of the balance and stability measures, with the prefix of the stage.
219
+ * The balance measures read the area of each box, so they support only `rect`. The stability measures read only the centers.
220
+ */
221
+ export function balanceMeasureSpecs<S extends string>(stage: S): readonly MeasureSpec<`${S}.${BalanceMeasureSuffix}`>[] {
222
+ const id = (suffix: BalanceMeasureSuffix): `${S}.${BalanceMeasureSuffix}` => `${stage}.${suffix}`;
223
+ const rect: readonly ShapeKind[] = ["rect"];
224
+ const centers = SHAPE_KIND_IDS;
225
+ return Object.freeze([
226
+ { id: id("balance.gapCv"), unit: "ratio", direction: "lower", min: 0, max: Infinity, minEffect: 0.01, family: "balance", shapes: rect },
227
+ { id: id("balance.centroidOffset"), unit: "0 to 1", direction: "lower", min: 0, max: 1, minEffect: 0.01, family: "balance", shapes: rect },
228
+ ...SIDES.map((s) => ({ id: id(`balance.side.${s}`), unit: "0 to 1", direction: "lower" as const, min: 0, max: 1, family: "balance", role: "diagnostic" as const, shapes: rect })),
229
+ { id: id("balance.sideRange"), unit: "0 to 1", direction: "lower", min: 0, max: 1, minEffect: 0.02, family: "balance", shapes: rect },
230
+ { id: id("stability.procrustes"), unit: "W for each change share", direction: "lower", min: 0, max: Infinity, floor: 0, tol: 0.005, minEffect: 0.005, family: "stability", role: "change-guard", shapes: centers },
231
+ { id: id("stability.seed"), unit: "W", direction: "lower", min: 0, max: Infinity, floor: 0, tol: 0.005, minEffect: 0.005, family: "stability", shapes: centers },
232
+ ]);
233
+ }
package/src/index.ts CHANGED
@@ -7,6 +7,7 @@ export * from "./record.ts";
7
7
  export * from "./rules.ts";
8
8
  export * from "./turn.ts";
9
9
  export * from "./measures.ts";
10
+ export * from "./balance.ts";
10
11
  export * from "./strategy.ts";
11
12
  export * from "./random.ts";
12
13
  export * from "./edges.ts";
package/src/shapes.ts CHANGED
@@ -68,6 +68,21 @@ export interface ShapeSupport<Id extends string = string> {
68
68
  /**
69
69
  * The kinds where a measure gives a bound of the true value, and the side of the bound.
70
70
  * With `upper`, the value is the true value or more. With `lower`, the value is the true value or less.
71
+ *
72
+ * @remarks
73
+ * The side and the `direction` of the measure tell what a bound value `v` proves about a threshold `t`.
74
+ * A bound is optimistic on the better side of the true value, and pessimistic on the worse side.
75
+ *
76
+ * | `direction` | `side` | The bound | The proof | No proof |
77
+ * |---|---|---|---|---|
78
+ * | `higher` | `upper` | optimistic | `v < t`: the true value is less than `t`. | `v >= t` |
79
+ * | `higher` | `lower` | pessimistic | `v >= t`: the true value is `t` or more. | `v < t` |
80
+ * | `lower` | `upper` | pessimistic | `v <= t`: the true value is `t` or less. | `v > t` |
81
+ * | `lower` | `lower` | optimistic | `v > t`: the true value is more than `t`. | `v <= t` |
82
+ *
83
+ * For a floor or a guard, a pessimistic bound proves a pass, and an optimistic bound proves a fail.
84
+ * `compareMeasure` on two bound values proves nothing. A tie with a bound value proves nothing.
85
+ * Against an exact baseline, an optimistic candidate proves only `worse`, and a pessimistic candidate proves only `better`.
71
86
  */
72
87
  export interface ShapeBound {
73
88
  readonly shapes: readonly ShapeKind[];