@mark1russell7/layout-contract 0.2.9 → 0.2.10

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.
@@ -0,0 +1,854 @@
1
+ // The strategy space of an engine (`docs/STRATEGY-SPACE.md`): its stages, their options and the ranges of their params, as data.
2
+ import type { ClaimBreak } from "./corpus.ts";
3
+ import { canonicalJson, sha256Hex } from "./hash.ts";
4
+ import { stepRandom } from "./random.ts";
5
+
6
+ /** The schema of a strategy space. */
7
+ export const STRATEGY_SPACE_SCHEMA = "strategy-space/1";
8
+
9
+ /** The kind of a param: a whole number, a real number, one value of a list, or `true` and `false`. */
10
+ export type ParamKind = "int" | "real" | "enum" | "bool";
11
+
12
+ /** The value of one param in a config. */
13
+ export type ParamValue = number | string | boolean;
14
+
15
+ /** The condition of a conditional param: the param is active only when an earlier param of the same option has one of the values `in`. */
16
+ export interface ParamWhen {
17
+ /** The name of an earlier param of the same option. */
18
+ readonly param: string;
19
+ /** The values of that param that make this param active. */
20
+ readonly in: readonly ParamValue[];
21
+ }
22
+
23
+ /** One param of a stage option, with its range. */
24
+ export interface SpaceParam {
25
+ readonly name: string;
26
+ readonly kind: ParamKind;
27
+ /** The smallest value of an `int` or `real` param. */
28
+ readonly min?: number;
29
+ /** The largest value of an `int` or `real` param. */
30
+ readonly max?: number;
31
+ /** The step of the values from `min`. An `int` param has the step 1 by default. */
32
+ readonly step?: number;
33
+ /** The scale of the grid and of the samples. The scale `log` needs a `min` above 0. The default is `linear`. */
34
+ readonly scale?: "linear" | "log";
35
+ /** The values of an `enum` param. */
36
+ readonly values?: readonly (string | number)[];
37
+ /** The value that a config gets when it does not set the param. */
38
+ readonly default: ParamValue;
39
+ /** Without `when`, the param is active each time its option is chosen. */
40
+ readonly when?: ParamWhen;
41
+ }
42
+
43
+ /** The rule of the members of a meta option: a count from `min` to `max`. Members with `ordered: false` are sorted by their `configId`. */
44
+ export interface MemberRule {
45
+ readonly min: number;
46
+ readonly max: number;
47
+ readonly ordered: boolean;
48
+ }
49
+
50
+ /** One implementation of a stage. An option with `members` is a meta option: it chooses between whole configs, or wraps them. */
51
+ export interface StageOption {
52
+ readonly id: string;
53
+ readonly params: readonly SpaceParam[];
54
+ readonly members?: MemberRule;
55
+ }
56
+
57
+ /** One stage of the pipeline of an engine. A config of an `optional` stage can have no option. */
58
+ export interface SpaceStage {
59
+ readonly name: string;
60
+ readonly options: readonly StageOption[];
61
+ readonly optional?: boolean;
62
+ }
63
+
64
+ /** A reference to one option of a stage. The option `null` refers to an optional stage that a config does not use. */
65
+ export interface OptionRef {
66
+ readonly stage: string;
67
+ readonly option: string | null;
68
+ }
69
+
70
+ /** A rule that keeps out invalid combinations. A config with the option `if` also has the option `then`, or does not have the option `then.not`. */
71
+ export interface SpaceConstraint {
72
+ readonly if: OptionRef;
73
+ readonly then: OptionRef | { readonly not: OptionRef };
74
+ }
75
+
76
+ /** The strategy space of an engine: the stages, the constraints and the named configs. `docs/STRATEGY-SPACE.md` tells the rules. */
77
+ export interface StrategySpace {
78
+ readonly schema: typeof STRATEGY_SPACE_SCHEMA;
79
+ /** The name of the space. A config names the space with this value. */
80
+ readonly engine: string;
81
+ /** The version of the space. It is not part of a config or of its id. A record writes it. */
82
+ readonly version: string;
83
+ readonly stages: readonly SpaceStage[];
84
+ readonly constraints?: readonly SpaceConstraint[];
85
+ /** The named strategies of the engine, as points of the space. Old records stay comparable through them. */
86
+ readonly named?: Readonly<Record<string, StrategyConfig>>;
87
+ /** The spaces of a product space, from `productSpace`. A meta option of a part takes members of that part. */
88
+ readonly parts?: readonly StrategySpace[];
89
+ }
90
+
91
+ /** The choice of one stage in a config: an option, its params and, for a meta option, its members. */
92
+ export interface StageChoice {
93
+ readonly option: string;
94
+ /** The values of the active params. A param that is not set gets its default. */
95
+ readonly params?: Readonly<Record<string, ParamValue>>;
96
+ /** The members of a meta option: configs of the same space, with no meta option. */
97
+ readonly members?: readonly StrategyConfig[];
98
+ }
99
+
100
+ /** One point of a strategy space. The value `null` of a stage tells that the config does not use the optional stage. */
101
+ export interface StrategyConfig {
102
+ /** The `engine` of the space, without its version. */
103
+ readonly space: string;
104
+ readonly stages: Readonly<Record<string, StageChoice | null>>;
105
+ }
106
+
107
+ /** The count of the grid points of a space. */
108
+ export interface SpaceSize {
109
+ /** The count of the configs without a meta option. */
110
+ readonly base: bigint;
111
+ /** The count of the configs with a meta option. The value is `null` when the count is more than `maxMeta`. */
112
+ readonly meta: bigint | null;
113
+ }
114
+
115
+ /** The options of `spaceSize`. */
116
+ export interface SpaceSizeOptions {
117
+ /** The count of the levels of each numeric param, a whole number of 1 or more. */
118
+ readonly levels: number;
119
+ /** The largest meta count that `spaceSize` gives. The default is `10n ** 18n`. */
120
+ readonly maxMeta?: bigint;
121
+ }
122
+
123
+ /** The options of a grid. The grid gives only the configs without a meta option. */
124
+ export interface GridOptions {
125
+ readonly mode: "grid";
126
+ readonly levels: number;
127
+ /** The largest count of configs. A larger grid causes a `RangeError`. The default is 100000. */
128
+ readonly limit?: number;
129
+ }
130
+
131
+ /** The options of a sample. */
132
+ export interface SampleOptions {
133
+ readonly mode: "sample";
134
+ /** The count of the configs, a whole number of 0 or more. */
135
+ readonly n: number;
136
+ readonly seed: number;
137
+ /** With `skip` (the default), the sample has no meta option. With `sample`, a meta option draws its members from base samples. */
138
+ readonly meta?: "skip" | "sample";
139
+ /** The largest count of option draws. The default is the larger value of 1000 and `100 * n`. */
140
+ readonly maxTries?: number;
141
+ }
142
+
143
+ /** The options of `enumerateSpace`. */
144
+ export type EnumerateOptions = GridOptions | SampleOptions;
145
+
146
+ type Problem = readonly [claim: string, detail: string];
147
+ type Choices = ReadonlyMap<string, StageOption | null>;
148
+ type Values = Record<string, ParamValue>;
149
+
150
+ const isObject = (value: unknown): value is Record<string, unknown> => value !== null && typeof value === "object" && !Array.isArray(value);
151
+ const show = (value: unknown): string => (typeof value === "string" ? `"${value}"` : String(value));
152
+ const isNumeric = (p: SpaceParam): boolean => p.kind === "int" || p.kind === "real";
153
+ const zero = (v: number): number => (v === 0 ? 0 : v);
154
+
155
+ /** This function gives the stable form of a real number: 12 significant digits, with `-0` as `0`. */
156
+ const realForm = (v: number, digits = 12): number => zero(Number(v.toPrecision(digits)));
157
+
158
+ /** This function gives the stable form of a value of a param. */
159
+ function normalize(p: SpaceParam, v: ParamValue): ParamValue {
160
+ if (typeof v !== "number") return v;
161
+ if (p.kind !== "real") return zero(v);
162
+ return Math.min(p.max ?? Infinity, Math.max(p.min ?? -Infinity, realForm(v)));
163
+ }
164
+
165
+ /** This function tells if a value is on the step of a param. */
166
+ function onStep(p: SpaceParam, v: number): boolean {
167
+ if (p.step === undefined || p.min === undefined) return true;
168
+ const q = (v - p.min) / p.step;
169
+ return Math.abs(q - Math.round(q)) <= 1e-9 * Math.max(1, Math.abs(q));
170
+ }
171
+
172
+ /** This function gives the problem of a value of a param, or `undefined` for a value in the range. */
173
+ function valueProblem(p: SpaceParam, v: unknown): string | undefined {
174
+ if (p.kind === "bool") return typeof v === "boolean" ? undefined : `${show(v)} is not true or false`;
175
+ if (p.kind === "enum") return (p.values ?? []).some((x) => x === v) ? undefined : `${show(v)} is not one of ${(p.values ?? []).map(show).join(", ")}`;
176
+ if (typeof v !== "number" || !Number.isFinite(v)) return `${show(v)} is not a finite number`;
177
+ if (p.kind === "int" && !Number.isInteger(v)) return `${v} is not a whole number`;
178
+ if (p.min !== undefined && v < p.min) return `${v} is less than the min ${p.min}`;
179
+ if (p.max !== undefined && v > p.max) return `${v} is more than the max ${p.max}`;
180
+ if (!onStep(p, v)) return `${v} is not on the step ${p.step} from ${p.min}`;
181
+ return undefined;
182
+ }
183
+
184
+ /** This function tells if a param is active for the values of the earlier params. */
185
+ function isActive(p: SpaceParam, values: Values): boolean {
186
+ if (p.when === undefined) return true;
187
+ if (!Object.hasOwn(values, p.when.param)) return false;
188
+ const v = values[p.when.param];
189
+ return p.when.in.some((x) => x === v);
190
+ }
191
+
192
+ /** This function gives the part of a space that has a stage, and the prefix of the names of its stages. */
193
+ function partOf(space: StrategySpace, stage: string): { readonly space: StrategySpace; readonly prefix: string } {
194
+ for (const part of space.parts ?? []) {
195
+ const head = `${part.engine}.`;
196
+ if (stage.startsWith(head)) {
197
+ const inner = partOf(part, stage.slice(head.length));
198
+ return { space: inner.space, prefix: head + inner.prefix };
199
+ }
200
+ }
201
+ return { space, prefix: "" };
202
+ }
203
+
204
+ /** This function gives the prefix of the innermost part of each stage. */
205
+ const prefixes = (space: StrategySpace): Map<string, string> => new Map(space.stages.map((s) => [s.name, partOf(space, s.name).prefix]));
206
+
207
+ const refMatches = (ref: OptionRef, choices: ReadonlyMap<string, string | null>): boolean => (choices.get(ref.stage) ?? null) === ref.option;
208
+
209
+ /** This function tells if the option choices keep a constraint. */
210
+ function holds(c: SpaceConstraint, choices: ReadonlyMap<string, string | null>): boolean {
211
+ if (!refMatches(c.if, choices)) return true;
212
+ return "not" in c.then ? !refMatches(c.then.not, choices) : refMatches(c.then, choices);
213
+ }
214
+
215
+ const describe = (c: SpaceConstraint): string => {
216
+ const ref = (r: OptionRef): string => `${r.stage}=${r.option ?? "null"}`;
217
+ return "not" in c.then ? `if ${ref(c.if)} then not ${ref(c.then.not)}` : `if ${ref(c.if)} then ${ref(c.then)}`;
218
+ };
219
+
220
+ /** This function gives the problems of the range and the default of one param. */
221
+ function paramProblems(p: SpaceParam, at: string): Problem[] {
222
+ const out: Problem[] = [];
223
+ if (isNumeric(p)) {
224
+ const { min, max, step } = p;
225
+ if (typeof min !== "number" || typeof max !== "number" || !Number.isFinite(min) || !Number.isFinite(max)) {
226
+ out.push(["range", `${at} has no finite min and max`]);
227
+ return out;
228
+ }
229
+ if (min > max) out.push(["range", `${at} has an empty range: the min ${min} is more than the max ${max}`]);
230
+ if (p.kind === "int" && (!Number.isInteger(min) || !Number.isInteger(max))) out.push(["range", `${at} is an int with a min or a max that is not whole`]);
231
+ if (step !== undefined && (!Number.isFinite(step) || step <= 0 || (p.kind === "int" && !Number.isInteger(step))))
232
+ out.push(["range", `${at} has the step ${step}, which is not a ${p.kind === "int" ? "whole " : ""}number above 0`]);
233
+ if (p.scale === "log" && min <= 0) out.push(["scale", `${at} has the scale log with the min ${min}, which is not above 0`]);
234
+ } else {
235
+ if (p.scale !== undefined) out.push(["scale", `${at} is a ${p.kind} param with a scale`]);
236
+ if (p.kind === "enum") {
237
+ if (!Array.isArray(p.values) || p.values.length === 0) out.push(["values", `${at} is an enum without values`]);
238
+ else {
239
+ const seen = new Set<unknown>();
240
+ for (const v of p.values) {
241
+ if (seen.has(v)) out.push(["duplicate", `${at} has the value ${show(v)} two times`]);
242
+ seen.add(v);
243
+ }
244
+ }
245
+ }
246
+ }
247
+ if (out.length === 0) {
248
+ const problem = valueProblem(p, p.default);
249
+ if (problem !== undefined) out.push(["default", `the default of ${at} is not in its range: ${problem}`]);
250
+ }
251
+ return out;
252
+ }
253
+
254
+ /** This function gives the problems of one stage option. */
255
+ function optionProblems(stage: SpaceStage, o: StageOption): Problem[] {
256
+ const out: Problem[] = [];
257
+ const at = `the option ${stage.name}.${o.id}`;
258
+ if (!Array.isArray(o.params)) return [["config", `${at} has no list of params`]];
259
+ const names = o.params.map((p) => p.name);
260
+ o.params.forEach((p, i) => {
261
+ const pat = `the param ${stage.name}.${o.id}.${p.name}`;
262
+ if (names.indexOf(p.name) !== i) out.push(["duplicate", `${at} has the param ${p.name} two times`]);
263
+ out.push(...paramProblems(p, pat));
264
+ if (p.when === undefined) return;
265
+ const j = names.indexOf(p.when.param);
266
+ if (j < 0) out.push(["unknown", `${pat} has a when with the unknown param ${p.when.param}`]);
267
+ else if (j >= i) out.push(["when", `${pat} has a when with the param ${p.when.param}, which does not come before it`]);
268
+ else if (!Array.isArray(p.when.in) || p.when.in.length === 0) out.push(["when", `${pat} has a when with no values`]);
269
+ else for (const v of p.when.in) {
270
+ const problem = valueProblem(o.params[j]!, v);
271
+ if (problem !== undefined) out.push(["when", `${pat} has a when value that is not a value of ${p.when.param}: ${problem}`]);
272
+ }
273
+ });
274
+ if (o.members !== undefined) {
275
+ const { min, max, ordered } = o.members;
276
+ if (!Number.isInteger(min) || !Number.isInteger(max) || min < 1 || min > max || typeof ordered !== "boolean")
277
+ out.push(["members", `${at} has a member rule without whole counts 1 <= min <= max and a boolean ordered`]);
278
+ }
279
+ return out;
280
+ }
281
+
282
+ /** This function gives the problems of the params of one stage choice. */
283
+ function choiceParamProblems(o: StageOption, params: unknown, at: string): Problem[] {
284
+ if (params !== undefined && !isObject(params)) return [["config", `the params of ${at} are not an object`]];
285
+ const given = (params ?? {}) as Values;
286
+ const out: Problem[] = [];
287
+ for (const key of Object.keys(given)) if (!o.params.some((p) => p.name === key)) out.push(["unknown", `${at} has the unknown param ${key}`]);
288
+ const values: Values = {};
289
+ for (const p of o.params) {
290
+ const has = Object.hasOwn(given, p.name);
291
+ if (!isActive(p, values)) {
292
+ if (has) out.push(["inactive", `${at} sets the param ${p.name}, which is not active`]);
293
+ continue;
294
+ }
295
+ const v = has ? given[p.name] : p.default;
296
+ const problem = valueProblem(p, v);
297
+ if (problem !== undefined) out.push(["param", `the param ${p.name} of ${at} is not in its range: ${problem}`]);
298
+ else values[p.name] = normalize(p, v as ParamValue);
299
+ }
300
+ return out;
301
+ }
302
+
303
+ /** This function gives the problems of a config of a space. A member of a meta option has `member: true`. */
304
+ function configProblems(space: StrategySpace, config: unknown, member: boolean): Problem[] {
305
+ if (!isObject(config) || !isObject(config["stages"])) return [["config", "the config is not an object with stages"]];
306
+ const out: Problem[] = [];
307
+ const stages = config["stages"];
308
+ if (config["space"] !== space.engine) out.push(["space", `the space of the config is ${show(config["space"])}, not ${show(space.engine)}`]);
309
+ for (const key of Object.keys(stages)) if (!space.stages.some((s) => s.name === key)) out.push(["unknown", `the config has the unknown stage ${key}`]);
310
+ const optionOf = (s: SpaceStage): StageOption | undefined => {
311
+ const c = stages[s.name];
312
+ return isObject(c) ? s.options.find((o) => o.id === c["option"]) : undefined;
313
+ };
314
+ const prefix = prefixes(space);
315
+ const metaStage = new Map<string, string>();
316
+ for (const s of space.stages) {
317
+ if (optionOf(s)?.members === undefined) continue;
318
+ const p = prefix.get(s.name)!;
319
+ if (metaStage.has(p)) out.push(["meta", `the stages ${metaStage.get(p)} and ${s.name} both have a meta option`]);
320
+ else metaStage.set(p, s.name);
321
+ }
322
+ const chosen = new Map<string, string | null>();
323
+ for (const s of space.stages) {
324
+ const c = Object.hasOwn(stages, s.name) ? stages[s.name] : undefined;
325
+ const meta = metaStage.get(prefix.get(s.name)!);
326
+ chosen.set(s.name, null);
327
+ if (c === undefined || c === null) {
328
+ if (!s.optional && meta === undefined) out.push(["missing", `the config has no option for the stage ${s.name}`]);
329
+ continue;
330
+ }
331
+ if (!isObject(c) || typeof c["option"] !== "string") {
332
+ out.push(["config", `the choice of the stage ${s.name} has no option`]);
333
+ continue;
334
+ }
335
+ const o = s.options.find((x) => x.id === c["option"]);
336
+ if (o === undefined) {
337
+ out.push(["unknown", `the stage ${s.name} has no option ${c["option"]}`]);
338
+ continue;
339
+ }
340
+ chosen.set(s.name, o.id);
341
+ const at = `the option ${s.name}.${o.id}`;
342
+ if (meta !== undefined && meta !== s.name) out.push(["meta", `the stage ${s.name} is set, but the meta option of ${meta} replaces the other stages of its part`]);
343
+ out.push(...choiceParamProblems(o, c["params"], at));
344
+ if (o.members === undefined) {
345
+ if (c["members"] !== undefined) out.push(["members", `${at} is not a meta option, but the config gives members`]);
346
+ continue;
347
+ }
348
+ if (member) {
349
+ out.push(["depth", `a member has the meta option ${s.name}.${o.id}. The depth of a meta config is 1`]);
350
+ continue;
351
+ }
352
+ out.push(...memberProblems(partOf(space, s.name).space, o.members, c["members"], at));
353
+ }
354
+ for (const c of space.constraints ?? []) if (!holds(c, chosen)) out.push(["constraint", `the config breaks the constraint ${describe(c)}`]);
355
+ return out;
356
+ }
357
+
358
+ /** This function gives the problems of the members of a meta option. `part` is the space of the members. */
359
+ function memberProblems(part: StrategySpace, rule: MemberRule, members: unknown, at: string): Problem[] {
360
+ if (!Array.isArray(members)) return [["members", `${at} is a meta option without a list of members`]];
361
+ const out: Problem[] = [];
362
+ if (members.length < rule.min || members.length > rule.max) out.push(["members", `${at} has ${members.length} members, not ${rule.min} to ${rule.max}`]);
363
+ const ids = new Map<string, number>();
364
+ members.forEach((m: unknown, k) => {
365
+ const inner = configProblems(part, m, true);
366
+ for (const [claim, detail] of inner) out.push([claim, `the member ${k} of ${at}: ${detail}`]);
367
+ if (inner.length > 0) return;
368
+ const id = idOf(canonicalOf(part, m as StrategyConfig, true));
369
+ if (ids.has(id)) out.push(["duplicate", `the members ${ids.get(id)} and ${k} of ${at} are the same config ${id}`]);
370
+ else ids.set(id, k);
371
+ });
372
+ return out;
373
+ }
374
+
375
+ const toBreaks = (problems: readonly Problem[], inputs: readonly string[] = []): ClaimBreak[] => problems.map(([claim, detail]) => ({ claim, detail, inputs }));
376
+
377
+ /**
378
+ * This function checks one config of a space. It gives one break for each problem. An empty list tells that the config is good.
379
+ * The `claim` of a break is the kind of the problem, for example `missing`, `unknown`, `inactive`, `param`, `constraint`, `members` or `depth`.
380
+ */
381
+ export function checkConfig(space: StrategySpace, config: StrategyConfig): ClaimBreak[] {
382
+ return toBreaks(configProblems(space, config, false));
383
+ }
384
+
385
+ /**
386
+ * This function checks a space. It gives one break for each problem. An empty list tells that the space is good.
387
+ * It finds duplicate names, empty ranges, defaults out of range, enums without values, bad log scales, unknown names and bad named configs.
388
+ * The `inputs` of a break of a named config have the name of the config.
389
+ */
390
+ export function checkSpace(space: StrategySpace): ClaimBreak[] {
391
+ if (!isObject(space) || !Array.isArray(space.stages)) return toBreaks([["schema", "the space is not an object with stages"]]);
392
+ const out: Problem[] = [];
393
+ if (space.schema !== STRATEGY_SPACE_SCHEMA) out.push(["schema", `the schema is ${show(space.schema)}, not ${STRATEGY_SPACE_SCHEMA}`]);
394
+ if (typeof space.engine !== "string" || space.engine === "") out.push(["schema", "the space has no engine name"]);
395
+ if (typeof space.version !== "string") out.push(["schema", "the space has no version"]);
396
+ const names = space.stages.map((s) => s.name);
397
+ space.stages.forEach((s, i) => {
398
+ if (names.indexOf(s.name) !== i) out.push(["duplicate", `the space has the stage ${s.name} two times`]);
399
+ const options: readonly StageOption[] = Array.isArray(s.options) ? s.options : [];
400
+ if (options.length === 0) {
401
+ out.push(["options", `the stage ${s.name} has no options`]);
402
+ return;
403
+ }
404
+ const ids = options.map((o) => o.id);
405
+ options.forEach((o, j) => {
406
+ if (ids.indexOf(o.id) !== j) out.push(["duplicate", `the stage ${s.name} has the option ${o.id} two times`]);
407
+ out.push(...optionProblems(s, o));
408
+ });
409
+ if (!s.optional && options.every((o) => o.members !== undefined)) out.push(["meta", `the stage ${s.name} is not optional and has only meta options, so no base config exists`]);
410
+ });
411
+ const known = (ref: OptionRef, at: string): void => {
412
+ const s = space.stages.find((x) => x.name === ref?.stage);
413
+ if (s === undefined) out.push(["unknown", `${at} has the unknown stage ${ref?.stage}`]);
414
+ else if (ref.option === null ? !s.optional : !s.options.some((o) => o.id === ref.option))
415
+ out.push(["unknown", `${at} has the unknown option ${s.name}=${ref.option ?? "null"}`]);
416
+ };
417
+ (space.constraints ?? []).forEach((c, k) => {
418
+ known(c.if, `the constraint ${k}`);
419
+ known("not" in c.then ? c.then.not : c.then, `the constraint ${k}`);
420
+ });
421
+ for (const part of space.parts ?? []) for (const b of checkSpace(part)) out.push([b.claim, `the part ${part.engine}: ${b.detail}`]);
422
+ if (space.parts !== undefined)
423
+ for (const s of space.stages) if (partOf(space, s.name).prefix === "") out.push(["parts", `the stage ${s.name} is not a stage of a part`]);
424
+ const breaks = toBreaks(out);
425
+ if (breaks.length > 0) return breaks;
426
+ for (const [name, config] of Object.entries(space.named ?? {}))
427
+ breaks.push(...toBreaks(configProblems(space, config, false).map(([c, d]) => [c, `the named config ${name}: ${d}`] as const), [name]));
428
+ return breaks;
429
+ }
430
+
431
+ /** This function gives the canonical form of a config that is known to be good. */
432
+ function canonicalOf(space: StrategySpace, config: StrategyConfig, member: boolean): StrategyConfig {
433
+ const stages: Record<string, StageChoice | null> = {};
434
+ for (const s of space.stages) {
435
+ const c = Object.hasOwn(config.stages, s.name) ? config.stages[s.name] : undefined;
436
+ if (c === undefined || c === null) {
437
+ stages[s.name] = null;
438
+ continue;
439
+ }
440
+ const o = s.options.find((x) => x.id === c.option)!;
441
+ const given = c.params ?? {};
442
+ const params: Values = {};
443
+ for (const p of o.params) if (isActive(p, params)) params[p.name] = normalize(p, Object.hasOwn(given, p.name) ? given[p.name]! : p.default);
444
+ if (o.members === undefined || member) {
445
+ stages[s.name] = { option: o.id, params };
446
+ continue;
447
+ }
448
+ const part = partOf(space, s.name).space;
449
+ const members = (c.members ?? []).map((m) => canonicalOf(part, m, true));
450
+ if (!o.members.ordered) members.sort((a, b) => (idOf(a) < idOf(b) ? -1 : idOf(a) > idOf(b) ? 1 : 0));
451
+ stages[s.name] = { option: o.id, params, members };
452
+ }
453
+ return { space: space.engine, stages };
454
+ }
455
+
456
+ const idOf = (canonical: StrategyConfig): string => sha256Hex(canonicalJson(canonical)).slice(0, 16);
457
+
458
+ /**
459
+ * This function gives the canonical form of a config: each stage of the space, the active params only, the defaults, and stable numbers.
460
+ * An unused optional stage is `null`. The members of an unordered meta option are sorted by their `configId`.
461
+ * It throws an `Error` for a config with a break of `checkConfig`.
462
+ */
463
+ export function canonicalConfig(space: StrategySpace, config: StrategyConfig): StrategyConfig {
464
+ const problems = configProblems(space, config, false);
465
+ if (problems.length > 0) throw new Error(`The config of the space ${space.engine} is not good: ${problems.map((p) => p[1]).join("; ")}.`);
466
+ return canonicalOf(space, config, false);
467
+ }
468
+
469
+ /**
470
+ * This function gives the id of a config: the first 16 hex characters of the SHA-256 of `canonicalJson` of `canonicalConfig`.
471
+ * Two spellings of one config get one id. The version of the space is not part of the id.
472
+ */
473
+ export function configId(space: StrategySpace, config: StrategyConfig): string {
474
+ return idOf(canonicalConfig(space, config));
475
+ }
476
+
477
+ /** This function throws an `Error` for a space with a break of `checkSpace`. */
478
+ function assertSpace(space: StrategySpace): void {
479
+ const breaks = checkSpace(space);
480
+ if (breaks.length > 0) throw new Error(`The space ${String(space?.engine)} is not good: ${breaks.map((b) => b.detail).join("; ")}.`);
481
+ }
482
+
483
+ /** This function throws a `RangeError` when a value is not a whole number of `min` or more. */
484
+ function assertWhole(value: number, name: string, min: number): void {
485
+ if (!Number.isInteger(value) || value < min) throw new RangeError(`The option ${name} is ${value}, not a whole number of ${min} or more.`);
486
+ }
487
+
488
+ /** This function gives the last point of the step grid of a numeric param. */
489
+ function lastPoint(p: SpaceParam): number {
490
+ const min = p.min!;
491
+ const step = p.step ?? (p.kind === "int" ? 1 : undefined);
492
+ if (step === undefined) return p.max!;
493
+ return min + Math.floor((p.max! - min) / step + 1e-9) * step;
494
+ }
495
+
496
+ /** This function moves a value of a numeric param onto its step and into its range. */
497
+ function snap(p: SpaceParam, x: number, digits: number): number {
498
+ const min = p.min!;
499
+ const step = p.step ?? (p.kind === "int" ? 1 : undefined);
500
+ let v = step === undefined ? x : min + Math.round((x - min) / step) * step;
501
+ v = Math.min(lastPoint(p), Math.max(min, v));
502
+ return p.kind === "int" ? zero(Math.round(v)) : Math.min(p.max!, Math.max(min, realForm(v, digits)));
503
+ }
504
+
505
+ /** This function gives the point at the fraction `t` of the range of a numeric param, on its scale. */
506
+ function at01(p: SpaceParam, t: number): number {
507
+ const min = p.min!;
508
+ const max = p.max!;
509
+ if (p.scale === "log") return Math.exp(Math.log(min) + t * (Math.log(max) - Math.log(min)));
510
+ return min + t * (max - min);
511
+ }
512
+
513
+ /**
514
+ * This function gives the grid values of one param, in increasing order. An `enum` gives its values, and a `bool` gives `false` and `true`.
515
+ * With 1 level, a numeric param gives its default. With k levels, it gives k points from `min` to `max` on its scale and step, without repeats.
516
+ */
517
+ export function paramLevels(param: SpaceParam, levels: number): ParamValue[] {
518
+ assertWhole(levels, "levels", 1);
519
+ if (param.kind === "bool") return [false, true];
520
+ if (param.kind === "enum") return [...(param.values ?? [])];
521
+ if (levels === 1 || param.min === param.max) return [normalize(param, param.default)];
522
+ const out: number[] = [];
523
+ const steps = param.kind === "int" || param.step !== undefined ? Math.round((lastPoint(param) - param.min!) / (param.step ?? 1)) + 1 : Infinity;
524
+ if (steps <= levels && param.scale !== "log") {
525
+ for (let j = 0; j < steps; j++) out.push(snap(param, param.min! + j * (param.step ?? 1), 12));
526
+ } else {
527
+ for (let j = 0; j < levels; j++) out.push(snap(param, at01(param, j / (levels - 1)), 12));
528
+ }
529
+ return [...new Set(out)];
530
+ }
531
+
532
+ /** This function tells if a later param of the list reads a param in its `when`. */
533
+ const readLater = (params: readonly SpaceParam[], i: number): boolean => params.slice(i + 1).some((q) => q.when?.param === params[i]!.name);
534
+
535
+ /** This function gives the count of the grid assignments of the params of an option, with only the active params. */
536
+ function countParams(params: readonly SpaceParam[], levels: number, i = 0, values: Values = {}): bigint {
537
+ if (i === params.length) return 1n;
538
+ const p = params[i]!;
539
+ if (!isActive(p, values)) return countParams(params, levels, i + 1, values);
540
+ const lv = paramLevels(p, levels);
541
+ if (!readLater(params, i)) return BigInt(lv.length) * countParams(params, levels, i + 1, values);
542
+ let sum = 0n;
543
+ for (const v of lv) sum += countParams(params, levels, i + 1, { ...values, [p.name]: v });
544
+ return sum;
545
+ }
546
+
547
+ /** This function gives the grid assignments of the params of an option, in a stable order. */
548
+ function* gridParams(params: readonly SpaceParam[], levels: number, i = 0, values: Values = {}): Generator<Values> {
549
+ if (i === params.length) {
550
+ yield { ...values };
551
+ return;
552
+ }
553
+ const p = params[i]!;
554
+ if (!isActive(p, values)) {
555
+ yield* gridParams(params, levels, i + 1, values);
556
+ return;
557
+ }
558
+ for (const v of paramLevels(p, levels)) yield* gridParams(params, levels, i + 1, { ...values, [p.name]: v });
559
+ }
560
+
561
+ /** One combination of options of a space, with its count of grid points. */
562
+ interface Combo {
563
+ readonly choices: Choices;
564
+ readonly base: boolean;
565
+ /** The count of the grid points, or `null` when the count is more than the limit. */
566
+ readonly weight: bigint | null;
567
+ }
568
+
569
+ const optionIds = (choices: Choices): Map<string, string | null> => new Map([...choices].map(([k, o]) => [k, o?.id ?? null]));
570
+ const keeps = (space: StrategySpace, choices: Choices): boolean => (space.constraints ?? []).every((c) => holds(c, optionIds(choices)));
571
+
572
+ /** This function gives the count of the member lists of a meta option from `base` base configs, or `null` above `limit`. */
573
+ function memberLists(base: bigint, rule: MemberRule, limit: bigint): bigint | null {
574
+ let sum = 0n;
575
+ for (let m = rule.min; m <= rule.max; m++) {
576
+ let n = 1n;
577
+ for (let k = 0; k < m; k++) {
578
+ n = (n * (base - BigInt(k))) / (rule.ordered ? 1n : BigInt(k + 1));
579
+ if (n <= 0n) break;
580
+ }
581
+ if (n <= 0n) break;
582
+ sum += n;
583
+ if (sum > limit) return null;
584
+ }
585
+ return sum;
586
+ }
587
+
588
+ /** This function multiplies two counts. A `null` count or a product above `limit` gives `null`. */
589
+ const times = (a: bigint | null, b: bigint | null, limit: bigint): bigint | null => (a === null || b === null ? null : a * b > limit ? null : a * b);
590
+
591
+ /**
592
+ * This function gives the combinations of options of a space and their grid counts.
593
+ * A product space joins the combinations of its parts. Each combination keeps the constraints.
594
+ */
595
+ function combos(space: StrategySpace, levels: number, meta: boolean, limit: bigint): Combo[] {
596
+ if (space.parts !== undefined && space.parts.length > 0) {
597
+ let acc: Combo[] = [{ choices: new Map(), base: true, weight: 1n }];
598
+ for (const part of space.parts) {
599
+ const head = `${part.engine}.`;
600
+ const own = combos(part, levels, meta, limit);
601
+ const next: Combo[] = [];
602
+ for (const a of acc)
603
+ for (const b of own) {
604
+ const choices = new Map(a.choices);
605
+ for (const [k, o] of b.choices) choices.set(head + k, o);
606
+ const base = a.base && b.base;
607
+ next.push({ choices, base, weight: base ? a.weight! * b.weight! : times(a.weight, b.weight, limit) });
608
+ }
609
+ acc = next;
610
+ }
611
+ return acc.filter((c) => keeps(space, c.choices));
612
+ }
613
+ const counts = new Map<StageOption, bigint>();
614
+ const countOf = (o: StageOption): bigint => {
615
+ if (!counts.has(o)) counts.set(o, countParams(o.params, levels));
616
+ return counts.get(o)!;
617
+ };
618
+ const out: Combo[] = [];
619
+ const stages = space.stages;
620
+ const walk = (i: number, choices: Map<string, StageOption | null>, weight: bigint): void => {
621
+ if (i === stages.length) {
622
+ if (keeps(space, choices)) out.push({ choices: new Map(choices), base: true, weight });
623
+ return;
624
+ }
625
+ const s = stages[i]!;
626
+ const list: (StageOption | null)[] = s.options.filter((o) => o.members === undefined);
627
+ if (s.optional) list.push(null);
628
+ for (const o of list) {
629
+ choices.set(s.name, o);
630
+ walk(i + 1, choices, o === null ? weight : weight * countOf(o));
631
+ }
632
+ choices.delete(s.name);
633
+ };
634
+ walk(0, new Map(), 1n);
635
+ if (!meta) return out;
636
+ const base = out.reduce((sum, c) => sum + c.weight!, 0n);
637
+ for (const s of stages)
638
+ for (const o of s.options) {
639
+ if (o.members === undefined) continue;
640
+ const choices = new Map<string, StageOption | null>(stages.map((x) => [x.name, x === s ? o : null]));
641
+ if (keeps(space, choices)) out.push({ choices, base: false, weight: times(countOf(o), memberLists(base, o.members, limit), limit) });
642
+ }
643
+ return out;
644
+ }
645
+
646
+ /**
647
+ * This function gives the count of the grid points of a space, with `levels` levels for each numeric param.
648
+ * It counts only the active params and the combinations that keep the constraints. It gives the meta configs apart.
649
+ */
650
+ export function spaceSize(space: StrategySpace, options: SpaceSizeOptions): SpaceSize {
651
+ assertSpace(space);
652
+ assertWhole(options.levels, "levels", 1);
653
+ const limit = options.maxMeta ?? 10n ** 18n;
654
+ let base = 0n;
655
+ let meta: bigint | null = 0n;
656
+ for (const c of combos(space, options.levels, true, limit)) {
657
+ if (c.base) base += c.weight!;
658
+ else meta = meta === null || c.weight === null || meta + c.weight > limit ? null : meta + c.weight;
659
+ }
660
+ return { base, meta };
661
+ }
662
+
663
+ /** This function gives the cartesian product of lists, with the last list as the fastest. */
664
+ function* product<T>(lists: readonly (readonly T[])[], i = 0, acc: T[] = []): Generator<T[]> {
665
+ if (i === lists.length) {
666
+ yield [...acc];
667
+ return;
668
+ }
669
+ for (const x of lists[i]!) {
670
+ acc.push(x);
671
+ yield* product(lists, i + 1, acc);
672
+ acc.pop();
673
+ }
674
+ }
675
+
676
+ /** This function gives the configs of the grid of a space, without meta options. */
677
+ function gridConfigs(space: StrategySpace, levels: number, limit: number): StrategyConfig[] {
678
+ const size = spaceSize(space, { levels, maxMeta: 0n }).base;
679
+ if (size > BigInt(limit)) throw new RangeError(`The grid of the space ${space.engine} has ${size} configs, more than the limit ${limit}.`);
680
+ const out: StrategyConfig[] = [];
681
+ for (const c of combos(space, levels, false, 0n)) {
682
+ const names = [...c.choices.keys()];
683
+ const lists = names.map((k) => {
684
+ const o = c.choices.get(k)!;
685
+ return o === null ? [null] : [...gridParams(o.params, levels)].map((params): StageChoice => ({ option: o.id, params }));
686
+ });
687
+ for (const row of product<StageChoice | null>(lists)) out.push(canonicalOf(space, { space: space.engine, stages: Object.fromEntries(names.map((k, i) => [k, row[i]!])) }, false));
688
+ }
689
+ return out;
690
+ }
691
+
692
+ /** This function gives a random order of the numbers from 0 to `n - 1`. */
693
+ function permutation(n: number, r: () => number): number[] {
694
+ const out = Array.from({ length: n }, (_, i) => i);
695
+ for (let i = n - 1; i > 0; i--) {
696
+ const j = Math.floor(r() * (i + 1));
697
+ [out[i], out[j]] = [out[j]!, out[i]!];
698
+ }
699
+ return out;
700
+ }
701
+
702
+ /** This function gives the value of a param at the fraction `u` of its range. A sampled real number has 6 significant digits. */
703
+ function sampleValue(p: SpaceParam, u: number): ParamValue {
704
+ if (p.kind === "bool") return u >= 0.5;
705
+ if (p.kind === "enum") {
706
+ const values = p.values!;
707
+ return values[Math.min(values.length - 1, Math.floor(u * values.length))]!;
708
+ }
709
+ if (p.min === p.max) return normalize(p, p.min!);
710
+ if (p.scale !== "log" && (p.kind === "int" || p.step !== undefined)) {
711
+ const steps = Math.round((lastPoint(p) - p.min!) / (p.step ?? 1)) + 1;
712
+ return snap(p, p.min! + Math.min(steps - 1, Math.floor(u * steps)) * (p.step ?? 1), 6);
713
+ }
714
+ return snap(p, at01(p, u), 6);
715
+ }
716
+
717
+ /** This function gives a seed of 32 bits from a seed and a step name. */
718
+ const subSeed = (seed: number, step: string): number => Math.floor(stepRandom(seed, step)() * 4294967296);
719
+
720
+ /** This function gives a sample of a space: Latin hypercube strata over the options, the params and the member counts. */
721
+ function sampleConfigs(space: StrategySpace, n: number, seed: number, meta: boolean, maxTries: number): StrategyConfig[] {
722
+ const stages = space.stages;
723
+ const prefix = prefixes(space);
724
+ const lists = stages.map((s) => {
725
+ const list: (StageOption | null)[] = s.options.filter((o) => meta || o.members === undefined);
726
+ if (s.optional) list.push(null);
727
+ return list;
728
+ });
729
+ const points: Map<string, StageOption | null>[] = [];
730
+ let tries = 0;
731
+ for (let round = 0; points.length < n; round++) {
732
+ const r = stepRandom(seed, `options:${round}`);
733
+ const columns = lists.map((list) => permutation(n, r).map((p) => list[Math.floor((p * list.length) / n)]!));
734
+ for (let i = 0; i < n && points.length < n; i++) {
735
+ if (tries >= maxTries) throw new Error(`The constraints of the space ${space.engine} remove too many points: ${points.length} of ${n} configs after ${tries} tries.`);
736
+ tries++;
737
+ const choices = new Map<string, StageOption | null>(stages.map((s, k) => [s.name, columns[k]![i]!]));
738
+ const metaPart = new Map<string, string>();
739
+ for (const s of stages) {
740
+ const o = choices.get(s.name);
741
+ if (o?.members !== undefined && !metaPart.has(prefix.get(s.name)!)) metaPart.set(prefix.get(s.name)!, s.name);
742
+ }
743
+ for (const s of stages) {
744
+ const m = metaPart.get(prefix.get(s.name)!);
745
+ if (m !== undefined && m !== s.name) choices.set(s.name, null);
746
+ }
747
+ if (keeps(space, choices)) points.push(choices);
748
+ }
749
+ }
750
+ const values: Values[][] = points.map(() => stages.map(() => ({})));
751
+ const members: StrategyConfig[][][] = points.map(() => stages.map(() => []));
752
+ stages.forEach((s, k) => {
753
+ for (const o of s.options) {
754
+ const users = points.flatMap((c, i) => (c.get(s.name) === o ? [i] : []));
755
+ if (users.length === 0) continue;
756
+ for (const p of o.params) {
757
+ const active = users.filter((i) => isActive(p, values[i]![k]!));
758
+ const r = stepRandom(seed, `param:${s.name}:${o.id}:${p.name}`);
759
+ permutation(active.length, r).forEach((stratum, j) => {
760
+ values[active[j]!]![k]![p.name] = sampleValue(p, (stratum + r()) / active.length);
761
+ });
762
+ }
763
+ if (o.members === undefined) continue;
764
+ const part = partOf(space, s.name).space;
765
+ const poolSize = Math.max(n, 4 * o.members.max, 8);
766
+ const seen = new Set<string>();
767
+ const pool = sampleConfigs(part, poolSize, subSeed(seed, `pool:${s.name}:${o.id}`), false, Math.max(1000, 100 * poolSize)).filter((c) => {
768
+ const id = idOf(c);
769
+ return seen.has(id) ? false : (seen.add(id), true);
770
+ });
771
+ const r = stepRandom(seed, `members:${s.name}:${o.id}`);
772
+ const { min, max } = o.members;
773
+ permutation(users.length, r).forEach((stratum, j) => {
774
+ const count = min + Math.min(max - min, Math.floor(((stratum + r()) / users.length) * (max - min + 1)));
775
+ if (pool.length < count) throw new Error(`The space ${part.engine} has only ${pool.length} distinct base samples, fewer than the ${count} members of ${s.name}.${o.id}.`);
776
+ const picked = permutation(pool.length, r).slice(0, count);
777
+ members[users[j]!]![k] = picked.map((x) => pool[x]!);
778
+ });
779
+ }
780
+ });
781
+ return points.map((choices, i) => {
782
+ const out: Record<string, StageChoice | null> = {};
783
+ stages.forEach((s, k) => {
784
+ const o = choices.get(s.name)!;
785
+ out[s.name] = o === null ? null : o.members === undefined ? { option: o.id, params: values[i]![k]! } : { option: o.id, params: values[i]![k]!, members: members[i]![k]! };
786
+ });
787
+ return canonicalConfig(space, { space: space.engine, stages: out });
788
+ });
789
+ }
790
+
791
+ /**
792
+ * This function gives configs of a space, in their canonical form. Each config keeps the constraints. The result is deterministic.
793
+ *
794
+ * - The mode `grid` gives each grid point without a meta option, in a stable order. Stages, options and values go in the order of the space.
795
+ * - The mode `sample` gives `n` configs of a seeded Latin hypercube. The options of a stage get equal strata, and each active param gets its own strata.
796
+ * - A sample draws again when a point breaks a constraint. After `maxTries` draws, it throws an `Error`. Two sampled configs can be equal.
797
+ */
798
+ export function enumerateSpace(space: StrategySpace, options: EnumerateOptions): StrategyConfig[] {
799
+ assertSpace(space);
800
+ if (options.mode === "grid") {
801
+ assertWhole(options.levels, "levels", 1);
802
+ return gridConfigs(space, options.levels, options.limit ?? 100_000);
803
+ }
804
+ if (options.mode !== "sample") throw new RangeError(`The mode ${String((options as { mode?: unknown }).mode)} is not grid or sample.`);
805
+ assertWhole(options.n, "n", 0);
806
+ if (!Number.isInteger(options.seed)) throw new RangeError(`The seed ${options.seed} is not a whole number.`);
807
+ const meta = options.meta ?? "skip";
808
+ if (meta !== "skip" && meta !== "sample") throw new RangeError(`The option meta is ${String(meta)}, not skip or sample.`);
809
+ if (options.n === 0) return [];
810
+ return sampleConfigs(space, options.n, options.seed, meta === "sample", options.maxTries ?? Math.max(1000, 100 * options.n));
811
+ }
812
+
813
+ /**
814
+ * This function joins configs of the parts of a product space into one config of the space `space`.
815
+ * The name of each stage gets the prefix `<space of the part>.`. The members of a meta option do not change.
816
+ */
817
+ export function joinConfigs(space: string, parts: readonly StrategyConfig[]): StrategyConfig {
818
+ const stages: Record<string, StageChoice | null> = {};
819
+ for (const part of parts) for (const [k, c] of Object.entries(part.stages)) stages[`${part.space}.${k}`] = c;
820
+ return { space, stages };
821
+ }
822
+
823
+ /** This function gives the config of the part `engine` of a joint config. It throws a `RangeError` when no stage has the prefix `<engine>.`. */
824
+ export function splitConfig(config: StrategyConfig, engine: string): StrategyConfig {
825
+ const head = `${engine}.`;
826
+ const entries = Object.entries(config.stages).filter(([k]) => k.startsWith(head));
827
+ if (entries.length === 0) throw new RangeError(`The config of the space ${config.space} has no stage of the part ${engine}.`);
828
+ return { space: engine, stages: Object.fromEntries(entries.map(([k, c]) => [k.slice(head.length), c])) };
829
+ }
830
+
831
+ /**
832
+ * This function joins two spaces, for example a packer and a router, into the space `name`. The stages of `a` and `b` get the prefixes `<a.engine>.` and `<b.engine>.`.
833
+ * The constraints get the same prefixes. The named configs are the pairs `<name of a>+<name of b>`. It throws a `RangeError` when the two engines have the same name.
834
+ */
835
+ export function productSpace(a: StrategySpace, b: StrategySpace, name: string): StrategySpace {
836
+ if (a.engine === b.engine) throw new RangeError(`The two spaces have the same engine ${a.engine}.`);
837
+ if (name === "") throw new RangeError("The product space has no name.");
838
+ const stagesOf = (s: StrategySpace): SpaceStage[] => s.stages.map((x) => ({ ...x, name: `${s.engine}.${x.name}` }));
839
+ const ref = (s: StrategySpace, r: OptionRef): OptionRef => ({ stage: `${s.engine}.${r.stage}`, option: r.option });
840
+ const constraintsOf = (s: StrategySpace): SpaceConstraint[] =>
841
+ (s.constraints ?? []).map((c) => ({ if: ref(s, c.if), then: "not" in c.then ? { not: ref(s, c.then.not) } : ref(s, c.then) }));
842
+ const named: Record<string, StrategyConfig> = {};
843
+ for (const [ka, ca] of Object.entries(a.named ?? {})) for (const [kb, cb] of Object.entries(b.named ?? {})) named[`${ka}+${kb}`] = joinConfigs(name, [ca, cb]);
844
+ const constraints = [...constraintsOf(a), ...constraintsOf(b)];
845
+ return {
846
+ schema: STRATEGY_SPACE_SCHEMA,
847
+ engine: name,
848
+ version: `${a.engine}@${a.version}+${b.engine}@${b.version}`,
849
+ stages: [...stagesOf(a), ...stagesOf(b)],
850
+ ...(constraints.length > 0 ? { constraints } : {}),
851
+ ...(Object.keys(named).length > 0 ? { named } : {}),
852
+ parts: [a, b],
853
+ };
854
+ }