@mark1russell7/layout-contract 0.9.0 → 0.9.2

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.9.0",
4
+ "version": "0.9.2",
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",
@@ -51,6 +51,7 @@
51
51
  "devDependencies": {
52
52
  "@mark1russell7/cue": "^2.1.1",
53
53
  "@types/node": "^26.6.4",
54
+ "@vitest/coverage-v8": "5.0.5",
54
55
  "esbuild": "^0.28.2",
55
56
  "fast-check": "^4.10.2",
56
57
  "layout-contract-0221": "npm:@mark1russell7/layout-contract@0.2.21",
@@ -0,0 +1,94 @@
1
+ // The manifest of a corpus, `layout-corpus/1`, and the one writer of its text (`docs/CORPUS.md`).
2
+ // The bench of each engine and the joint bench write the same form: one line for each field, and one line for each item of a list.
3
+ import type { DeclaredClaim } from "./corpus.ts";
4
+
5
+ /** The schema of a corpus manifest. */
6
+ export const CORPUS_MANIFEST_SCHEMA = "layout-corpus/1";
7
+
8
+ /** The held-out split of a portfolio report: a seed, or `all` when each input is held out. */
9
+ export type HeldOut = number | "all";
10
+
11
+ /** The claims of a corpus that each bench reads. `declared` is the count of the inputs of each declared property. */
12
+ export interface ManifestClaims {
13
+ readonly declared?: DeclaredClaim;
14
+ }
15
+
16
+ /**
17
+ * A corpus manifest: the name, the specs of the inputs and, as an option, the held-out split, the claims and the inputs.
18
+ * `Spec`, `Claims` and `Input` are the types of the bench that writes the manifest.
19
+ */
20
+ export interface CorpusManifest<Spec = unknown, Claims extends object = ManifestClaims, Input = unknown> {
21
+ readonly schema: typeof CORPUS_MANIFEST_SCHEMA;
22
+ readonly corpus: string;
23
+ readonly heldOut?: HeldOut;
24
+ readonly claims?: Claims;
25
+ readonly specs: readonly Spec[];
26
+ readonly inputs?: readonly Input[];
27
+ }
28
+
29
+ /**
30
+ * The form of a JSON value on one line.
31
+ * With `spaced`, a space comes after each colon and each comma. With `compact`, the text is the text of `JSON.stringify`.
32
+ */
33
+ export type JsonStyle = "spaced" | "compact";
34
+
35
+ /** This function gives a JSON value on one line, in the style `style`. The keys of an object keep their order. */
36
+ export function lineJson(value: unknown, style: JsonStyle = "spaced"): string {
37
+ if (style === "compact") return JSON.stringify(value);
38
+ if (Array.isArray(value)) return `[${value.map((v) => lineJson(v)).join(", ")}]`;
39
+ if (value !== null && typeof value === "object") return `{${Object.entries(value).map(([k, v]) => `${JSON.stringify(k)}: ${lineJson(v)}`).join(", ")}}`;
40
+ return JSON.stringify(value);
41
+ }
42
+
43
+ /** One field of a manifest text. */
44
+ export interface ManifestField {
45
+ readonly key: string;
46
+ /** The value. With `rows`, it is an array, and each item gets its own line. */
47
+ readonly value: unknown;
48
+ readonly rows?: boolean;
49
+ /** The style of the value or of each item. The default is the style of the options. */
50
+ readonly style?: JsonStyle;
51
+ }
52
+
53
+ /** The options of `manifestText`. */
54
+ export interface ManifestTextOptions {
55
+ /** The style of each field with no style of its own. The default is `spaced`. */
56
+ readonly style?: JsonStyle;
57
+ /** The text of a list with no item: `[]` (the default), or `[` and `]` with an empty line between them. */
58
+ readonly emptyRows?: "brackets" | "line";
59
+ }
60
+
61
+ /** This function gives the text of a manifest: `{`, one line for each field in the order of `fields`, `}` and a newline. */
62
+ export function manifestText(fields: readonly ManifestField[], options: ManifestTextOptions = {}): string {
63
+ const keys = new Set<string>();
64
+ const lines = fields.map((field, i) => {
65
+ if (keys.has(field.key)) throw new RangeError(`manifestText: the key ${field.key} occurs two times.`);
66
+ keys.add(field.key);
67
+ const style = field.style ?? options.style ?? "spaced";
68
+ const end = i === fields.length - 1 ? "" : ",";
69
+ const head = ` ${JSON.stringify(field.key)}: `;
70
+ if (field.rows !== true) return `${head}${lineJson(field.value, style)}${end}`;
71
+ if (!Array.isArray(field.value)) throw new RangeError(`manifestText: the field ${field.key} has rows, so its value is an array.`);
72
+ if (field.value.length === 0 && options.emptyRows !== "line") return `${head}[]${end}`;
73
+ return `${head}[\n${field.value.map((item) => ` ${lineJson(item, style)}`).join(",\n")}\n ]${end}`;
74
+ });
75
+ return `{\n${lines.join("\n")}\n}\n`;
76
+ }
77
+
78
+ /**
79
+ * This function gives the text of a corpus manifest.
80
+ * The fields come in the order `schema`, `corpus`, `heldOut`, `claims`, `specs` and `inputs`. A field with no value is not in the text.
81
+ * `specs` and `inputs` have one line for each item.
82
+ */
83
+ export function corpusManifestText<Spec, Claims extends object, Input>(manifest: CorpusManifest<Spec, Claims, Input>, options: ManifestTextOptions = {}): string {
84
+ if (manifest.schema !== CORPUS_MANIFEST_SCHEMA) throw new RangeError(`corpusManifestText: the schema is ${String(manifest.schema)}, not ${CORPUS_MANIFEST_SCHEMA}.`);
85
+ const fields: ManifestField[] = [
86
+ { key: "schema", value: manifest.schema },
87
+ { key: "corpus", value: manifest.corpus },
88
+ ];
89
+ if (manifest.heldOut !== undefined) fields.push({ key: "heldOut", value: manifest.heldOut });
90
+ if (manifest.claims !== undefined) fields.push({ key: "claims", value: manifest.claims });
91
+ fields.push({ key: "specs", value: manifest.specs, rows: true });
92
+ if (manifest.inputs !== undefined) fields.push({ key: "inputs", value: manifest.inputs, rows: true });
93
+ return manifestText(fields, options);
94
+ }
package/src/frame.ts ADDED
@@ -0,0 +1,155 @@
1
+ // The frames of a layout change (`docs/FRAMES.md`): the record `layout-frame/1`, the frame at a time between two layouts, and the move between two frames.
2
+ // A frame is a layout at one time of a change. A caller can stop at a frame and start the next layout from it.
3
+ import type { PlacedBox } from "./balance.ts";
4
+ import type { Placement } from "./output.ts";
5
+
6
+ /** The schema of a frame. */
7
+ export const FRAME_SCHEMA = "layout-frame/1";
8
+
9
+ /** The states of a box in a frame: in the two layouts, only in the end layout, or only in the start layout. */
10
+ export const FRAME_STATES = ["stay", "enter", "leave"] as const;
11
+
12
+ /** The state of a box in a frame. */
13
+ export type FrameState = (typeof FRAME_STATES)[number];
14
+
15
+ /** One box of a frame: its rectangle, its turn, its presence and its state. */
16
+ export interface FrameBox extends PlacedBox {
17
+ readonly turn?: 0 | 90;
18
+ /** The visible share of the box, from 0 (not visible) to 1 (fully visible). */
19
+ readonly presence: number;
20
+ readonly state: FrameState;
21
+ }
22
+
23
+ /** A frame: the boxes of a layout by id, at one time of a change. Each id occurs one time. */
24
+ export interface LayoutFrame {
25
+ readonly schema: typeof FRAME_SCHEMA;
26
+ readonly boxes: readonly FrameBox[];
27
+ }
28
+
29
+ /**
30
+ * The change of the presence of a box that enters or leaves.
31
+ * With `fade`, the presence changes in a straight line with the time.
32
+ * With `cut`, an entering box is fully visible after the time 0, and a leaving box is fully visible before the time 1.
33
+ */
34
+ export type Presence = "fade" | "cut";
35
+
36
+ /** The options of `frameAt`. The default of each is `fade`. */
37
+ export interface FrameAtOptions {
38
+ readonly enter?: Presence;
39
+ readonly leave?: Presence;
40
+ }
41
+
42
+ /** One box of a layout for `frameOf`: a placed rectangle, with an optional turn. */
43
+ export interface FrameSource extends PlacedBox {
44
+ readonly turn?: 0 | 90;
45
+ }
46
+
47
+ /** This function throws a `RangeError` for a value that is not a finite number. */
48
+ function finite(value: number, name: string): void {
49
+ if (!Number.isFinite(value)) throw new RangeError(`layout-frame: the ${name} ${value} is not a finite number.`);
50
+ }
51
+
52
+ /** This function gives the boxes of a frame by id. An id two times or a bad value causes a `RangeError`. */
53
+ function byId(frame: LayoutFrame, name: string): Map<string, FrameBox> {
54
+ if (frame.schema !== FRAME_SCHEMA) throw new RangeError(`layout-frame: the ${name} frame has the schema ${String(frame.schema)}, not ${FRAME_SCHEMA}.`);
55
+ const map = new Map<string, FrameBox>();
56
+ for (const b of frame.boxes) {
57
+ if (map.has(b.id)) throw new RangeError(`layout-frame: the id ${b.id} occurs two times in the ${name} frame.`);
58
+ for (const k of ["x", "y", "w", "h", "presence"] as const) finite(b[k], `${k} of ${b.id}`);
59
+ if (b.presence < 0 || b.presence > 1) throw new RangeError(`layout-frame: the presence ${b.presence} of ${b.id} is not between 0 and 1.`);
60
+ if (b.turn !== undefined && b.turn !== 0 && b.turn !== 90) throw new RangeError(`layout-frame: the turn ${String(b.turn)} of ${b.id} is not 0 or 90.`);
61
+ if (!FRAME_STATES.includes(b.state)) throw new RangeError(`layout-frame: the state ${String(b.state)} of ${b.id} is not one of ${FRAME_STATES.join(", ")}.`);
62
+ map.set(b.id, b);
63
+ }
64
+ return map;
65
+ }
66
+
67
+ /** This function gives a box with the optional turn of `turn`. */
68
+ function withTurn(box: Omit<FrameBox, "turn">, turn: 0 | 90 | undefined): FrameBox {
69
+ return turn === undefined ? box : { ...box, turn };
70
+ }
71
+
72
+ /** This function makes a frame of a layout. Each box has the state `stay` and the presence 1. */
73
+ export function frameOf(boxes: readonly FrameSource[]): LayoutFrame {
74
+ const frame: LayoutFrame = {
75
+ schema: FRAME_SCHEMA,
76
+ boxes: boxes.map((b) => withTurn({ id: b.id, x: b.x, y: b.y, w: b.w, h: b.h, presence: 1, state: "stay" }, b.turn)),
77
+ };
78
+ byId(frame, "made");
79
+ return frame;
80
+ }
81
+
82
+ /** This function gives the placements of a frame: the boxes with the state `stay` or `enter`, in the order of the frame. An engine starts a layout from them. */
83
+ export function outputOf(frame: LayoutFrame): Placement[] {
84
+ byId(frame, "given");
85
+ return frame.boxes.filter((b) => b.state !== "leave").map((b) => (b.turn === undefined ? { id: b.id, x: b.x, y: b.y } : { id: b.id, x: b.x, y: b.y, turn: b.turn }));
86
+ }
87
+
88
+ /** This function gives the presence of a box that enters (`up`) or leaves, at the time `t`. */
89
+ function presenceAt(mode: Presence, up: boolean, from: number, t: number): number {
90
+ const to = up ? 1 : 0;
91
+ if (mode === "fade") return from + (to - from) * t;
92
+ if (up) return t > 0 ? 1 : from;
93
+ return t < 1 ? from : 0;
94
+ }
95
+
96
+ /**
97
+ * This function gives the frame at the time `t` of the change from `from` to `to`. The time is a number from 0 to 1.
98
+ * A box in the two frames moves on a straight line, and its size and presence change on a straight line. It keeps the turn of `from` before the time 1.
99
+ *
100
+ * A box only in `to` enters at its place in `to`. A box only in `from` leaves at its place in `from`. `options` sets how their presence changes.
101
+ * At the time 1, the result has the boxes of `to`. At the time 0, the result has the boxes of `from` and the entering boxes.
102
+ * The order of the result: the boxes of `to`, then the leaving boxes in the order of `from`.
103
+ */
104
+ export function frameAt(from: LayoutFrame, to: LayoutFrame, t: number, options: FrameAtOptions = {}): LayoutFrame {
105
+ finite(t, "time");
106
+ if (t < 0 || t > 1) throw new RangeError(`layout-frame: the time ${t} is not between 0 and 1.`);
107
+ const a = byId(from, "start");
108
+ byId(to, "end");
109
+ if (t === 1) return { schema: FRAME_SCHEMA, boxes: [...to.boxes] };
110
+ const enter = options.enter ?? "fade";
111
+ const leave = options.leave ?? "fade";
112
+ const lerp = (p: number, q: number): number => p + (q - p) * t;
113
+ const boxes: FrameBox[] = [];
114
+ const seen = new Set<string>();
115
+ for (const q of to.boxes) {
116
+ seen.add(q.id);
117
+ const p = a.get(q.id);
118
+ if (p === undefined) {
119
+ boxes.push({ ...q, presence: presenceAt(enter, true, 0, t), state: "enter" });
120
+ continue;
121
+ }
122
+ const state: FrameState = p.state === "stay" ? q.state : p.state;
123
+ const presence = p.state === "enter" ? presenceAt(enter, true, p.presence, t) : p.state === "leave" && q.state === "leave" ? presenceAt(leave, false, p.presence, t) : lerp(p.presence, q.presence);
124
+ boxes.push(withTurn({ id: q.id, x: lerp(p.x, q.x), y: lerp(p.y, q.y), w: lerp(p.w, q.w), h: lerp(p.h, q.h), presence, state }, p.turn));
125
+ }
126
+ for (const p of from.boxes) {
127
+ if (seen.has(p.id)) continue;
128
+ boxes.push({ ...p, presence: presenceAt(leave, false, p.presence, t), state: "leave" });
129
+ }
130
+ return { schema: FRAME_SCHEMA, boxes };
131
+ }
132
+
133
+ /**
134
+ * This function gives the move from `a` to `b`: the sum of the distances of the box centers, over the ids in the two frames.
135
+ * A box that enters or leaves does not move, so it adds nothing. A start frame that an engine does not change gives 0.
136
+ */
137
+ export function frameMove(a: LayoutFrame, b: LayoutFrame): number {
138
+ const before = byId(a, "first");
139
+ byId(b, "second");
140
+ let sum = 0;
141
+ for (const q of b.boxes) {
142
+ const p = before.get(q.id);
143
+ if (p === undefined) continue;
144
+ sum += Math.hypot(q.x + q.w / 2 - (p.x + p.w / 2), q.y + q.h / 2 - (p.y + p.h / 2));
145
+ }
146
+ return sum;
147
+ }
148
+
149
+ /**
150
+ * This function gives the move of an engine from a start frame: `frameMove(start, run(start))`.
151
+ * The gate of a start: a start that is a fixed point of the engine gives 0.
152
+ */
153
+ export function fixedPointMove(start: LayoutFrame, run: (start: LayoutFrame) => LayoutFrame): number {
154
+ return frameMove(start, run(start));
155
+ }
package/src/index.ts CHANGED
@@ -8,12 +8,14 @@ export * from "./rules.ts";
8
8
  export * from "./turn.ts";
9
9
  export * from "./measures.ts";
10
10
  export * from "./balance.ts";
11
+ export * from "./frame.ts";
11
12
  export * from "./strategy.ts";
12
13
  export * from "./random.ts";
13
14
  export * from "./edges.ts";
14
15
  export * from "./hash.ts";
15
16
  export * from "./portfolio.ts";
16
17
  export * from "./corpus.ts";
18
+ export * from "./corpus-manifest.ts";
17
19
  export * from "./strategy-space.ts";
18
20
  export * from "./strategy-catalog.ts";
19
21
  export * from "./verdict.ts";