@mark1russell7/layout-contract 0.8.0 → 0.9.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,1220 +1,110 @@
1
- // The strategy space of an engine (`docs/STRATEGY-SPACE.md`): its stages, their options and the ranges of their params, as data.
1
+ // The format of a strategy space has its home in `@mark1russell7/strategy-space` (`docs/STRATEGY-SPACE.md` of that repository).
2
+ // This module re-exports the format. Its checks take the shape kinds of this package, `SHAPE_KIND_IDS`, when a caller gives no list.
3
+ import {
4
+ checkSpace as checkSpaceOf,
5
+ enumerateSpace as enumerateSpaceOf,
6
+ type EnumerateOptions,
7
+ type KindOptions,
8
+ type SpaceSize,
9
+ type SpaceSizeOptions,
10
+ spaceShapeKinds as spaceShapeKindsOf,
11
+ spaceSize as spaceSizeOf,
12
+ type StrategyConfig,
13
+ type StrategySpace,
14
+ } from "@mark1russell7/strategy-space";
2
15
  import type { ClaimBreak } from "./corpus.ts";
3
- import { canonicalJson, sha256Hex } from "./hash.ts";
4
- import { stepRandom } from "./random.ts";
5
- import { holds, walkPlan, walkPoint } from "./space-walk.ts";
6
- import { isShapeKind, SHAPE_KIND_IDS, type ShapeKind } from "./shapes.ts";
7
-
8
- /** The schema of a strategy space. */
9
- export const STRATEGY_SPACE_SCHEMA = "strategy-space/1";
10
-
11
- /** The kind of a param: a whole number, a real number, one value of a list, or `true` and `false`. */
12
- export type ParamKind = "int" | "real" | "enum" | "bool";
13
-
14
- /** The value of one param in a config. */
15
- export type ParamValue = number | string | boolean;
16
-
17
- /** 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`. */
18
- export interface ParamWhen {
19
- /** The name of an earlier param of the same option. */
20
- readonly param: string;
21
- /** The values of that param that make this param active. */
22
- readonly in: readonly ParamValue[];
23
- }
24
-
25
- /** One param of a stage option, with its range. */
26
- export interface SpaceParam {
27
- readonly name: string;
28
- readonly kind: ParamKind;
29
- /** The smallest value of an `int` or `real` param. */
30
- readonly min?: number;
31
- /** The largest value of an `int` or `real` param. */
32
- readonly max?: number;
33
- /** The step of the values from `min`. An `int` param has the step 1 by default. */
34
- readonly step?: number;
35
- /** The scale of the grid and of the samples. The scale `log` needs a `min` above 0. The default is `linear`. */
36
- readonly scale?: "linear" | "log";
37
- /** The values of an `enum` param. */
38
- readonly values?: readonly (string | number)[];
39
- /** The value that a config gets when it does not set the param. */
40
- readonly default: ParamValue;
41
- /** Without `when`, the param is active each time its option is chosen. */
42
- readonly when?: ParamWhen;
43
- }
44
-
45
- /**
46
- * The rule of the members of a meta option: a count from `min` to `max`. Members with `ordered: false` are sorted by their `configId`.
47
- * With `min` and `max` 0, the option chooses its members from the input, so a config lists none. This form has no `pool` and no `view`.
48
- */
49
- export interface MemberRule {
50
- readonly min: number;
51
- readonly max: number;
52
- readonly ordered: boolean;
53
- /**
54
- * The member lists that the option permits. Each entry is a list of whole configs of the space of the members.
55
- * Without `pool`, each list of base configs with a good count is a member list.
56
- * With `pool`, a config of the option has the members of one entry, and `spaceSize` counts each entry one time.
57
- */
58
- readonly pool?: readonly (readonly StrategyConfig[])[];
59
- /**
60
- * The view of the items that the members get. With `bounds`, the option gives its members the bounding box of each item.
61
- * Then a shape filter checks the members with the kind `rect`, and the option itself with the kinds of the input. Without `view`, the members get the kinds of the input.
62
- */
63
- readonly view?: "bounds";
64
- }
65
-
66
- /** The inputs that an option supports. A missing field supports each value. */
67
- export interface OptionSupports {
68
- /** The shape kinds of the boxes (`docs/SHAPES.md`). Without it, the option supports each kind. */
69
- readonly shape?: readonly ShapeKind[];
70
- }
71
-
72
- /** One implementation of a stage. An option with `members` is a meta option: it chooses between whole configs, or wraps them. */
73
- export interface StageOption {
74
- readonly id: string;
75
- readonly params: readonly SpaceParam[];
76
- readonly members?: MemberRule;
77
- /** The inputs that the option supports. It describes the option, so it is not part of a config or of its id. */
78
- readonly supports?: OptionSupports;
79
- }
80
-
81
- /** The shape kinds of the inputs of a check, a count or an enumeration. Without `shapes`, each option counts. */
82
- export interface ShapeFilter {
83
- /** The shape kinds of the input. Only the options that support each of these kinds count. */
84
- readonly shapes?: readonly ShapeKind[];
85
- }
86
-
87
- /** One stage of the pipeline of an engine. A config of an `optional` stage can have no option. */
88
- export interface SpaceStage {
89
- readonly name: string;
90
- readonly options: readonly StageOption[];
91
- readonly optional?: boolean;
92
- }
93
-
94
- /** A reference to one option of a stage. The option `null` refers to an optional stage that a config does not use. */
95
- export interface OptionRef {
96
- readonly stage: string;
97
- readonly option: string | null;
98
- }
99
-
100
- /** 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`. */
101
- export interface SpaceConstraint {
102
- readonly if: OptionRef;
103
- readonly then: OptionRef | { readonly not: OptionRef };
104
- }
105
-
106
- /** The strategy space of an engine: the stages, the constraints and the named configs. `docs/STRATEGY-SPACE.md` tells the rules. */
107
- export interface StrategySpace {
108
- readonly schema: typeof STRATEGY_SPACE_SCHEMA;
109
- /** The name of the space. A config names the space with this value. */
110
- readonly engine: string;
111
- /** The version of the space. It is not part of a config or of its id. A record writes it. */
112
- readonly version: string;
113
- readonly stages: readonly SpaceStage[];
114
- readonly constraints?: readonly SpaceConstraint[];
115
- /** The named strategies of the engine, as points of the space. Old records stay comparable through them. */
116
- readonly named?: Readonly<Record<string, StrategyConfig>>;
117
- /** The spaces of a product space, from `productSpace`. A meta option of a part takes members of that part. */
118
- readonly parts?: readonly StrategySpace[];
119
- }
120
-
121
- /** The choice of one stage in a config: an option, its params and, for a meta option, its members. */
122
- export interface StageChoice {
123
- readonly option: string;
124
- /** The values of the active params. A param that is not set gets its default. */
125
- readonly params?: Readonly<Record<string, ParamValue>>;
126
- /** The members of a meta option: configs of the same space, with no meta option. */
127
- readonly members?: readonly StrategyConfig[];
128
- }
129
-
130
- /** One point of a strategy space. The value `null` of a stage tells that the config does not use the optional stage. */
131
- export interface StrategyConfig {
132
- /** The `engine` of the space, without its version. */
133
- readonly space: string;
134
- readonly stages: Readonly<Record<string, StageChoice | null>>;
135
- }
136
-
137
- /** The count of the grid points of a space. */
138
- export interface SpaceSize {
139
- /** The count of the configs without a meta option. */
140
- readonly base: bigint;
141
- /** The count of the configs with a meta option. The value is `null` when the count is more than `maxMeta`. */
142
- readonly meta: bigint | null;
143
- }
144
-
145
- /** The options of `spaceSize`. */
146
- export interface SpaceSizeOptions extends ShapeFilter {
147
- /** The count of the levels of each numeric param, a whole number of 1 or more. */
148
- readonly levels: number;
149
- /** The largest meta count that `spaceSize` gives. The default is `10n ** 18n`. */
150
- readonly maxMeta?: bigint;
151
- }
152
-
153
- /** The options of a grid. The grid gives only the configs without a meta option. */
154
- export interface GridOptions extends ShapeFilter {
155
- readonly mode: "grid";
156
- readonly levels: number;
157
- /** The largest count of configs. A larger grid causes a `RangeError`. The default is 100000. */
158
- readonly limit?: number;
159
- }
160
-
161
- /** The options of a sample. */
162
- export interface SampleOptions extends ShapeFilter {
163
- readonly mode: "sample";
164
- /** The count of the configs, a whole number of 0 or more. */
165
- readonly n: number;
166
- readonly seed: number;
167
- /** With `skip` (the default), the sample has no meta option. With `sample`, a meta option draws its members from base samples, or one entry of its `pool`. */
168
- readonly meta?: "skip" | "sample";
169
- /** The largest count of option draws. The default is the larger value of 1000 and `100 * n`. */
170
- readonly maxTries?: number;
171
- /**
172
- * How a point keeps the constraints. With `reject` (the default), a point that breaks a constraint draws again.
173
- * With `walk`, a point draws its stages from the largest to the smallest. Each stage draws only from the options that keep the constraints with the stages before it.
174
- * The stages of `fixed` draw before the other stages.
175
- * A space whose constraints reject most draws gets its sample with `walk`. The two values give different configs for one seed.
176
- * A sample of `walk` is not uniform over the valid configs. Each option of the largest stage gets an equal share, whatever count of valid configs it has.
177
- * Thus a mean over this sample is not a mean of the space.
178
- */
179
- readonly draw?: "reject" | "walk";
180
- /**
181
- * The options that each config of the sample has. A key is the name of a stage, and its value is the id of one option of that stage. The other stages draw as before.
182
- * A stage of a product space has the name of its part before its own name, for example `pack.placement`.
183
- * A fixed meta option needs `meta: "sample"`. A meta option of another stage of the same part goes out, because such an option replaces the fixed stage.
184
- * A fixed option that the shape filter removes, or that the constraints forbid, gets a `RangeError` with the reason.
185
- */
186
- readonly fixed?: Readonly<Record<string, string>>;
187
- }
188
-
189
- /** The options of `enumerateSpace`. */
190
- export type EnumerateOptions = GridOptions | SampleOptions;
191
-
192
- type Problem = readonly [claim: string, detail: string];
193
- type Choices = ReadonlyMap<string, StageOption | null>;
194
- type Values = Record<string, ParamValue>;
195
-
196
- const isObject = (value: unknown): value is Record<string, unknown> => value !== null && typeof value === "object" && !Array.isArray(value);
197
- const show = (value: unknown): string => (typeof value === "string" ? `"${value}"` : String(value));
198
- const isNumeric = (p: SpaceParam): boolean => p.kind === "int" || p.kind === "real";
199
- const zero = (v: number): number => (v === 0 ? 0 : v);
200
-
201
- /** This function gives the stable form of a real number: 12 significant digits, with `-0` as `0`. */
202
- const realForm = (v: number, digits = 12): number => zero(Number(v.toPrecision(digits)));
203
-
204
- /** This function gives the stable form of a value of a param. */
205
- function normalize(p: SpaceParam, v: ParamValue): ParamValue {
206
- if (typeof v !== "number") return v;
207
- if (p.kind !== "real") return zero(v);
208
- return Math.min(p.max ?? Infinity, Math.max(p.min ?? -Infinity, realForm(v)));
209
- }
210
-
211
- /** This function tells if a value is on the step of a param. */
212
- function onStep(p: SpaceParam, v: number): boolean {
213
- if (p.step === undefined || p.min === undefined) return true;
214
- const q = (v - p.min) / p.step;
215
- return Math.abs(q - Math.round(q)) <= 1e-9 * Math.max(1, Math.abs(q));
216
- }
217
-
218
- /** This function gives the problem of a value of a param, or `undefined` for a value in the range. */
219
- function valueProblem(p: SpaceParam, v: unknown): string | undefined {
220
- if (p.kind === "bool") return typeof v === "boolean" ? undefined : `${show(v)} is not true or false`;
221
- if (p.kind === "enum") return (p.values ?? []).some((x) => x === v) ? undefined : `${show(v)} is not one of ${(p.values ?? []).map(show).join(", ")}`;
222
- if (typeof v !== "number" || !Number.isFinite(v)) return `${show(v)} is not a finite number`;
223
- if (p.kind === "int" && !Number.isInteger(v)) return `${v} is not a whole number`;
224
- if (p.min !== undefined && v < p.min) return `${v} is less than the min ${p.min}`;
225
- if (p.max !== undefined && v > p.max) return `${v} is more than the max ${p.max}`;
226
- if (!onStep(p, v)) return `${v} is not on the step ${p.step} from ${p.min}`;
227
- return undefined;
228
- }
229
-
230
- /** This function tells if a param is active for the values of the earlier params. */
231
- function isActive(p: SpaceParam, values: Values): boolean {
232
- if (p.when === undefined) return true;
233
- if (!Object.hasOwn(values, p.when.param)) return false;
234
- const v = values[p.when.param];
235
- return p.when.in.some((x) => x === v);
236
- }
237
-
238
- /** This function gives the problem of a value of a param, or `undefined` for a value in its range. The corpus dimensions of `families.ts` use it. */
239
- export function paramProblem(param: SpaceParam, value: unknown): string | undefined {
240
- return valueProblem(param, value);
241
- }
242
-
243
- /** This function tells if a param is active for the values of the earlier params. A param without `when` is always active. */
244
- export function paramActive(param: SpaceParam, values: Readonly<Record<string, ParamValue>>): boolean {
245
- return isActive(param, values);
246
- }
247
-
248
- /** This function gives the stable form of a value of a param: a real number gets 12 significant digits, and `-0` becomes `0`. */
249
- export function paramValue(param: SpaceParam, value: ParamValue): ParamValue {
250
- return normalize(param, value);
251
- }
252
-
253
- /** This function gives the part of a space that has a stage, and the prefix of the names of its stages. */
254
- function partOf(space: StrategySpace, stage: string): { readonly space: StrategySpace; readonly prefix: string } {
255
- for (const part of space.parts ?? []) {
256
- const head = `${part.engine}.`;
257
- if (stage.startsWith(head)) {
258
- const inner = partOf(part, stage.slice(head.length));
259
- return { space: inner.space, prefix: head + inner.prefix };
260
- }
261
- }
262
- return { space, prefix: "" };
263
- }
264
-
265
- /** This function gives the prefix of the innermost part of each stage. */
266
- const prefixes = (space: StrategySpace): Map<string, string> => new Map(space.stages.map((s) => [s.name, partOf(space, s.name).prefix]));
267
-
268
- const describe = (c: SpaceConstraint): string => {
269
- const ref = (r: OptionRef): string => `${r.stage}=${r.option ?? "null"}`;
270
- return "not" in c.then ? `if ${ref(c.if)} then not ${ref(c.then.not)}` : `if ${ref(c.if)} then ${ref(c.then)}`;
271
- };
272
-
273
- /** This function gives the problems of the range and the default of one param. */
274
- function paramProblems(p: SpaceParam, at: string): Problem[] {
275
- const out: Problem[] = [];
276
- if (isNumeric(p)) {
277
- const { min, max, step } = p;
278
- if (typeof min !== "number" || typeof max !== "number" || !Number.isFinite(min) || !Number.isFinite(max)) {
279
- out.push(["range", `${at} has no finite min and max`]);
280
- return out;
281
- }
282
- if (min > max) out.push(["range", `${at} has an empty range: the min ${min} is more than the max ${max}`]);
283
- 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`]);
284
- if (step !== undefined && (!Number.isFinite(step) || step <= 0 || (p.kind === "int" && !Number.isInteger(step))))
285
- out.push(["range", `${at} has the step ${step}, which is not a ${p.kind === "int" ? "whole " : ""}number above 0`]);
286
- if (p.scale === "log" && min <= 0) out.push(["scale", `${at} has the scale log with the min ${min}, which is not above 0`]);
287
- } else {
288
- if (p.scale !== undefined) out.push(["scale", `${at} is a ${p.kind} param with a scale`]);
289
- if (p.kind === "enum") {
290
- if (!Array.isArray(p.values) || p.values.length === 0) out.push(["values", `${at} is an enum without values`]);
291
- else {
292
- const seen = new Set<unknown>();
293
- for (const v of p.values) {
294
- if (seen.has(v)) out.push(["duplicate", `${at} has the value ${show(v)} two times`]);
295
- seen.add(v);
296
- }
297
- }
298
- }
299
- }
300
- if (out.length === 0) {
301
- const problem = valueProblem(p, p.default);
302
- if (problem !== undefined) out.push(["default", `the default of ${at} is not in its range: ${problem}`]);
303
- }
304
- return out;
305
- }
306
-
307
- /** This function gives the problems of one stage option. */
308
- function optionProblems(stage: SpaceStage, o: StageOption): Problem[] {
309
- const out: Problem[] = [];
310
- const at = `the option ${stage.name}.${o.id}`;
311
- if (!Array.isArray(o.params)) return [["config", `${at} has no list of params`]];
312
- const names = o.params.map((p) => p.name);
313
- o.params.forEach((p, i) => {
314
- const pat = `the param ${stage.name}.${o.id}.${p.name}`;
315
- if (names.indexOf(p.name) !== i) out.push(["duplicate", `${at} has the param ${p.name} two times`]);
316
- out.push(...paramProblems(p, pat));
317
- if (p.when === undefined) return;
318
- const j = names.indexOf(p.when.param);
319
- if (j < 0) out.push(["unknown", `${pat} has a when with the unknown param ${p.when.param}`]);
320
- else if (j >= i) out.push(["when", `${pat} has a when with the param ${p.when.param}, which does not come before it`]);
321
- else if (!Array.isArray(p.when.in) || p.when.in.length === 0) out.push(["when", `${pat} has a when with no values`]);
322
- else for (const v of p.when.in) {
323
- const problem = valueProblem(o.params[j]!, v);
324
- if (problem !== undefined) out.push(["when", `${pat} has a when value that is not a value of ${p.when.param}: ${problem}`]);
325
- }
326
- });
327
- if (o.supports !== undefined) out.push(...supportsProblems(o.supports, at));
328
- if (o.members !== undefined) {
329
- const { min, max, ordered } = o.members;
330
- const noList = min === 0 && max === 0;
331
- if (!Number.isInteger(min) || !Number.isInteger(max) || (!noList && (min < 1 || min > max)) || typeof ordered !== "boolean")
332
- out.push(["members", `${at} has a member rule without whole counts 1 <= min <= max or min = max = 0, and a boolean ordered`]);
333
- if (noList && (o.members.pool !== undefined || o.members.view !== undefined))
334
- out.push(["members", `${at} has no member list, so its member rule cannot have a pool or a view`]);
335
- const pool: unknown = o.members.pool;
336
- if (pool !== undefined && (!Array.isArray(pool) || pool.length === 0 || !pool.every((entry: unknown) => Array.isArray(entry))))
337
- out.push(["pool", `${at} has a pool that is not a list of one or more member lists`]);
338
- const view: unknown = o.members.view;
339
- if (view !== undefined && view !== "bounds") out.push(["view", `${at} has the member view ${show(view)}, not "bounds"`]);
340
- }
341
- return out;
342
- }
343
-
344
- /** This function gives the problems of the `supports` of an option. */
345
- function supportsProblems(supports: unknown, at: string): Problem[] {
346
- if (!isObject(supports)) return [["shape", `the supports of ${at} are not an object`]];
347
- const shape = supports["shape"];
348
- if (shape === undefined) return [];
349
- if (!Array.isArray(shape) || shape.length === 0) return [["shape", `${at} supports no shape kind. Remove shape to support each kind`]];
350
- const out: Problem[] = [];
351
- shape.forEach((k: unknown, i) => {
352
- if (!isShapeKind(k)) out.push(["shape", `${at} supports the shape kind ${show(k)}, which is not one of ${SHAPE_KIND_IDS.join(", ")}`]);
353
- else if (shape.indexOf(k) !== i) out.push(["duplicate", `${at} has the shape kind ${k} two times`]);
354
- });
355
- return out;
356
- }
357
-
358
- /** This function tells if an option supports each shape kind of the list. */
359
- const supportsShapes = (o: StageOption, shapes: readonly ShapeKind[] | undefined): boolean =>
360
- shapes === undefined || o.supports?.shape === undefined || shapes.every((k) => o.supports!.shape!.includes(k));
361
-
362
- /** The shape kinds that the members of an option with `view: "bounds"` see: a bounding box is a `rect`. */
363
- const BOUNDS_VIEW: readonly ShapeKind[] = /* @__PURE__ */ Object.freeze(["rect"] as const);
364
-
365
- /**
366
- * This function gives the shape kinds of the members of a meta option. With `view: "bounds"`, a list with a kind becomes `BOUNDS_VIEW`.
367
- * Without a list, or with an empty list, the value does not change.
368
- */
369
- const memberShapes = (rule: MemberRule, shapes: readonly ShapeKind[] | undefined): readonly ShapeKind[] | undefined =>
370
- rule.view === "bounds" && shapes !== undefined && shapes.length > 0 ? BOUNDS_VIEW : shapes;
371
-
372
- /** This function tells if two lists have the same shape kinds. */
373
- const sameKinds = (a: readonly ShapeKind[], b: readonly ShapeKind[]): boolean => a.every((k) => b.includes(k)) && b.every((k) => a.includes(k));
374
-
375
- /** This function gives the problems of the params of one stage choice. */
376
- function choiceParamProblems(o: StageOption, params: unknown, at: string): Problem[] {
377
- if (params !== undefined && !isObject(params)) return [["config", `the params of ${at} are not an object`]];
378
- const given = (params ?? {}) as Values;
379
- const out: Problem[] = [];
380
- for (const key of Object.keys(given)) if (!o.params.some((p) => p.name === key)) out.push(["unknown", `${at} has the unknown param ${key}`]);
381
- const values: Values = {};
382
- for (const p of o.params) {
383
- const has = Object.hasOwn(given, p.name);
384
- if (!isActive(p, values)) {
385
- if (has) out.push(["inactive", `${at} sets the param ${p.name}, which is not active`]);
386
- continue;
387
- }
388
- const v = has ? given[p.name] : p.default;
389
- const problem = valueProblem(p, v);
390
- if (problem !== undefined) out.push(["param", `the param ${p.name} of ${at} is not in its range: ${problem}`]);
391
- else values[p.name] = normalize(p, v as ParamValue);
392
- }
393
- return out;
394
- }
395
-
396
- /** This function gives the problems of a config of a space. A member of a meta option has `member: true`. */
397
- function configProblems(space: StrategySpace, config: unknown, member: boolean, shapes?: readonly ShapeKind[]): Problem[] {
398
- if (!isObject(config) || !isObject(config["stages"])) return [["config", "the config is not an object with stages"]];
399
- const out: Problem[] = [];
400
- const stages = config["stages"];
401
- if (config["space"] !== space.engine) out.push(["space", `the space of the config is ${show(config["space"])}, not ${show(space.engine)}`]);
402
- 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}`]);
403
- const optionOf = (s: SpaceStage): StageOption | undefined => {
404
- const c = stages[s.name];
405
- return isObject(c) ? s.options.find((o) => o.id === c["option"]) : undefined;
406
- };
407
- const prefix = prefixes(space);
408
- const metaStage = new Map<string, string>();
409
- for (const s of space.stages) {
410
- if (optionOf(s)?.members === undefined) continue;
411
- const p = prefix.get(s.name)!;
412
- if (metaStage.has(p)) out.push(["meta", `the stages ${metaStage.get(p)} and ${s.name} both have a meta option`]);
413
- else metaStage.set(p, s.name);
414
- }
415
- const chosen = new Map<string, string | null>();
416
- for (const s of space.stages) {
417
- const c = Object.hasOwn(stages, s.name) ? stages[s.name] : undefined;
418
- const meta = metaStage.get(prefix.get(s.name)!);
419
- chosen.set(s.name, null);
420
- if (c === undefined || c === null) {
421
- if (!s.optional && meta === undefined) out.push(["missing", `the config has no option for the stage ${s.name}`]);
422
- continue;
423
- }
424
- if (!isObject(c) || typeof c["option"] !== "string") {
425
- out.push(["config", `the choice of the stage ${s.name} has no option`]);
426
- continue;
427
- }
428
- const o = s.options.find((x) => x.id === c["option"]);
429
- if (o === undefined) {
430
- out.push(["unknown", `the stage ${s.name} has no option ${c["option"]}`]);
431
- continue;
432
- }
433
- chosen.set(s.name, o.id);
434
- const at = `the option ${s.name}.${o.id}`;
435
- if (!supportsShapes(o, shapes)) {
436
- const missing = shapes!.filter((k) => !o.supports!.shape!.includes(k));
437
- out.push(["shape", `${at} supports the shape kinds ${o.supports!.shape!.join(", ")}, not ${missing.join(", ")}`]);
438
- }
439
- 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`]);
440
- out.push(...choiceParamProblems(o, c["params"], at));
441
- if (o.members === undefined) {
442
- if (c["members"] !== undefined) out.push(["members", `${at} is not a meta option, but the config gives members`]);
443
- continue;
444
- }
445
- if (member) {
446
- out.push(["depth", `a member has the meta option ${s.name}.${o.id}. The depth of a meta config is 1`]);
447
- continue;
448
- }
449
- out.push(...memberProblems(partOf(space, s.name).space, o.members, c["members"], at, memberShapes(o.members, shapes)));
450
- }
451
- for (const c of space.constraints ?? []) if (!holds(c, chosen)) out.push(["constraint", `the config breaks the constraint ${describe(c)}`]);
452
- return out;
453
- }
454
-
455
- /** This function gives the problems of the members of a meta option. `part` is the space of the members. */
456
- function memberProblems(part: StrategySpace, rule: MemberRule, members: unknown, at: string, shapes?: readonly ShapeKind[]): Problem[] {
457
- if (!Array.isArray(members)) return [["members", `${at} is a meta option without a list of members`]];
458
- const out: Problem[] = [];
459
- if (members.length < rule.min || members.length > rule.max) out.push(["members", `${at} has ${members.length} members, not ${rule.min} to ${rule.max}`]);
460
- const ids = new Map<string, number>();
461
- members.forEach((m: unknown, k) => {
462
- const inner = configProblems(part, m, true, shapes);
463
- for (const [claim, detail] of inner) out.push([claim, `the member ${k} of ${at}: ${detail}`]);
464
- if (inner.length > 0) return;
465
- const id = idOf(canonicalOf(part, m as StrategyConfig, true));
466
- if (ids.has(id)) out.push(["duplicate", `the members ${ids.get(id)} and ${k} of ${at} are the same config ${id}`]);
467
- else ids.set(id, k);
468
- });
469
- if (rule.pool !== undefined && out.length === 0) {
470
- const key = memberKey(part, rule, members as readonly StrategyConfig[]);
471
- if (!rule.pool.some((entry) => memberKey(part, rule, entry) === key))
472
- out.push(["pool", `${at} has a member list that is not in its pool of ${rule.pool.length} ${rule.pool.length === 1 ? "list" : "lists"}`]);
473
- }
474
- return out;
475
- }
476
-
477
- /** This function gives the key of a good member list: the `configId` of each member, sorted when the rule is not ordered. */
478
- function memberKey(part: StrategySpace, rule: MemberRule, members: readonly StrategyConfig[]): string {
479
- const ids = members.map((m) => idOf(canonicalOf(part, m, true)));
480
- if (!rule.ordered) ids.sort();
481
- return ids.join(",");
482
- }
483
-
484
- /** This function gives the problems of the pool of a meta option of a good space. `part` is the space of the members. */
485
- function poolProblems(part: StrategySpace, rule: MemberRule, at: string): Problem[] {
486
- const out: Problem[] = [];
487
- const keys = new Map<string, number>();
488
- const plain: MemberRule = { min: rule.min, max: rule.max, ordered: rule.ordered };
489
- (rule.pool ?? []).forEach((entry, j) => {
490
- const inner = memberProblems(part, plain, entry, `the pool entry ${j} of ${at}`);
491
- out.push(...inner);
492
- if (inner.length > 0) return;
493
- const key = memberKey(part, rule, entry);
494
- if (keys.has(key)) out.push(["duplicate", `the pool entries ${keys.get(key)} and ${j} of ${at} have the same members`]);
495
- else keys.set(key, j);
496
- });
497
- return out;
498
- }
499
-
500
- /** This function tells if a member list fits a space: each member is a good config of the space. A shape filter removes options from the space. */
501
- const fits = (part: StrategySpace, entry: readonly StrategyConfig[]): boolean => entry.every((m) => configProblems(part, m, true).length === 0);
502
-
503
- const toBreaks = (problems: readonly Problem[], inputs: readonly string[] = []): ClaimBreak[] => problems.map(([claim, detail]) => ({ claim, detail, inputs }));
504
-
505
- /**
506
- * This function checks one config of a space. It gives one break for each problem. An empty list tells that the config is good.
507
- * The `claim` of a break is the kind of the problem, for example `missing`, `unknown`, `inactive`, `param`, `constraint`, `members` or `depth`.
508
- *
509
- * A member list that is not an entry of the `pool` of its option gives the claim `pool`.
510
- * With `shapes`, an option that does not support a kind of the list gives the claim `shape`. A member of a meta option gets the same check.
511
- * A member of an option with `view: "bounds"` gets the check with the kind `rect`.
512
- */
513
- export function checkConfig(space: StrategySpace, config: StrategyConfig, options: ShapeFilter = {}): ClaimBreak[] {
514
- return toBreaks(configProblems(space, config, false, options.shapes));
515
- }
516
-
517
- /**
518
- * This function checks a space. It gives one break for each problem. An empty list tells that the space is good.
519
- * It finds duplicate names, empty ranges, defaults out of range, enums without values, bad log scales, unknown names and bad named configs.
520
- * It also checks each entry of a `pool`: the count of its members, each member and a repeated entry.
521
- * The `inputs` of a break of a named config have the name of the config.
522
- */
523
- export function checkSpace(space: StrategySpace): ClaimBreak[] {
524
- if (!isObject(space) || !Array.isArray(space.stages)) return toBreaks([["schema", "the space is not an object with stages"]]);
525
- const out: Problem[] = [];
526
- if (space.schema !== STRATEGY_SPACE_SCHEMA) out.push(["schema", `the schema is ${show(space.schema)}, not ${STRATEGY_SPACE_SCHEMA}`]);
527
- if (typeof space.engine !== "string" || space.engine === "") out.push(["schema", "the space has no engine name"]);
528
- if (typeof space.version !== "string") out.push(["schema", "the space has no version"]);
529
- const names = space.stages.map((s) => s.name);
530
- space.stages.forEach((s, i) => {
531
- if (names.indexOf(s.name) !== i) out.push(["duplicate", `the space has the stage ${s.name} two times`]);
532
- const options: readonly StageOption[] = Array.isArray(s.options) ? s.options : [];
533
- if (options.length === 0) {
534
- out.push(["options", `the stage ${s.name} has no options`]);
535
- return;
536
- }
537
- const ids = options.map((o) => o.id);
538
- options.forEach((o, j) => {
539
- if (ids.indexOf(o.id) !== j) out.push(["duplicate", `the stage ${s.name} has the option ${o.id} two times`]);
540
- out.push(...optionProblems(s, o));
541
- });
542
- 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`]);
543
- });
544
- const known = (ref: OptionRef, at: string): void => {
545
- const s = space.stages.find((x) => x.name === ref?.stage);
546
- if (s === undefined) out.push(["unknown", `${at} has the unknown stage ${ref?.stage}`]);
547
- else if (ref.option === null ? !s.optional : !s.options.some((o) => o.id === ref.option))
548
- out.push(["unknown", `${at} has the unknown option ${s.name}=${ref.option ?? "null"}`]);
549
- };
550
- (space.constraints ?? []).forEach((c, k) => {
551
- known(c.if, `the constraint ${k}`);
552
- known("not" in c.then ? c.then.not : c.then, `the constraint ${k}`);
553
- });
554
- for (const part of space.parts ?? []) for (const b of checkSpace(part)) out.push([b.claim, `the part ${part.engine}: ${b.detail}`]);
555
- if (space.parts !== undefined)
556
- 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`]);
557
- const breaks = toBreaks(out);
558
- if (breaks.length > 0) return breaks;
559
- for (const s of space.stages)
560
- for (const o of s.options) if (o.members?.pool !== undefined) breaks.push(...toBreaks(poolProblems(partOf(space, s.name).space, o.members, `the option ${s.name}.${o.id}`)));
561
- if (breaks.length > 0) return breaks;
562
- for (const [name, config] of Object.entries(space.named ?? {}))
563
- breaks.push(...toBreaks(configProblems(space, config, false).map(([c, d]) => [c, `the named config ${name}: ${d}`] as const), [name]));
564
- return breaks;
565
- }
566
-
567
- /** This function gives the canonical form of a config that is known to be good. */
568
- function canonicalOf(space: StrategySpace, config: StrategyConfig, member: boolean): StrategyConfig {
569
- const stages: Record<string, StageChoice | null> = {};
570
- for (const s of space.stages) {
571
- const c = Object.hasOwn(config.stages, s.name) ? config.stages[s.name] : undefined;
572
- if (c === undefined || c === null) {
573
- stages[s.name] = null;
574
- continue;
575
- }
576
- const o = s.options.find((x) => x.id === c.option)!;
577
- const given = c.params ?? {};
578
- const params: Values = {};
579
- 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);
580
- if (o.members === undefined || member) {
581
- stages[s.name] = { option: o.id, params };
582
- continue;
583
- }
584
- const part = partOf(space, s.name).space;
585
- const members = (c.members ?? []).map((m) => canonicalOf(part, m, true));
586
- if (!o.members.ordered) members.sort((a, b) => (idOf(a) < idOf(b) ? -1 : idOf(a) > idOf(b) ? 1 : 0));
587
- stages[s.name] = { option: o.id, params, members };
588
- }
589
- return { space: space.engine, stages };
590
- }
591
-
592
- const idOf = (canonical: StrategyConfig): string => sha256Hex(canonicalJson(canonical)).slice(0, 16);
593
-
594
- /**
595
- * This function gives the canonical form of a config: each stage of the space, the active params only, the defaults, and stable numbers.
596
- * An unused optional stage is `null`. The members of an unordered meta option are sorted by their `configId`.
597
- * It throws an `Error` for a config with a break of `checkConfig`.
598
- */
599
- export function canonicalConfig(space: StrategySpace, config: StrategyConfig): StrategyConfig {
600
- const problems = configProblems(space, config, false);
601
- if (problems.length > 0) throw new Error(`The config of the space ${space.engine} is not good: ${problems.map((p) => p[1]).join("; ")}.`);
602
- return canonicalOf(space, config, false);
603
- }
604
-
605
- /**
606
- * This function gives the id of a config: the first 16 hex characters of the SHA-256 of `canonicalJson` of `canonicalConfig`.
607
- * Two spellings of one config get one id. The version of the space is not part of the id.
608
- */
609
- export function configId(space: StrategySpace, config: StrategyConfig): string {
610
- return idOf(canonicalConfig(space, config));
611
- }
612
-
613
- /** This function throws an `Error` for a space with a break of `checkSpace`. */
614
- function assertSpace(space: StrategySpace): void {
615
- const breaks = checkSpace(space);
616
- if (breaks.length > 0) throw new Error(`The space ${String(space?.engine)} is not good: ${breaks.map((b) => b.detail).join("; ")}.`);
617
- }
618
-
619
- /** This function throws a `RangeError` when a value is not a whole number of `min` or more. */
620
- function assertWhole(value: number, name: string, min: number): void {
621
- if (!Number.isInteger(value) || value < min) throw new RangeError(`The option ${name} is ${value}, not a whole number of ${min} or more.`);
622
- }
623
-
624
- /** This function gives the last point of the step grid of a numeric param. */
625
- function lastPoint(p: SpaceParam): number {
626
- const min = p.min!;
627
- const step = p.step ?? (p.kind === "int" ? 1 : undefined);
628
- if (step === undefined) return p.max!;
629
- return min + Math.floor((p.max! - min) / step + 1e-9) * step;
630
- }
631
-
632
- /** This function moves a value of a numeric param onto its step and into its range. */
633
- function snap(p: SpaceParam, x: number, digits: number): number {
634
- const min = p.min!;
635
- const step = p.step ?? (p.kind === "int" ? 1 : undefined);
636
- let v = step === undefined ? x : min + Math.round((x - min) / step) * step;
637
- v = Math.min(lastPoint(p), Math.max(min, v));
638
- return p.kind === "int" ? zero(Math.round(v)) : Math.min(p.max!, Math.max(min, realForm(v, digits)));
639
- }
640
-
641
- /** This function gives the point at the fraction `t` of the range of a numeric param, on its scale. */
642
- function at01(p: SpaceParam, t: number): number {
643
- const min = p.min!;
644
- const max = p.max!;
645
- if (p.scale === "log") return Math.exp(Math.log(min) + t * (Math.log(max) - Math.log(min)));
646
- return min + t * (max - min);
647
- }
648
-
649
- /**
650
- * This function gives the grid values of one param, in increasing order. An `enum` gives its values, and a `bool` gives `false` and `true`.
651
- * 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.
652
- */
653
- export function paramLevels(param: SpaceParam, levels: number): ParamValue[] {
654
- assertWhole(levels, "levels", 1);
655
- if (param.kind === "bool") return [false, true];
656
- if (param.kind === "enum") return [...(param.values ?? [])];
657
- if (levels === 1 || param.min === param.max) return [normalize(param, param.default)];
658
- const out: number[] = [];
659
- const steps = param.kind === "int" || param.step !== undefined ? Math.round((lastPoint(param) - param.min!) / (param.step ?? 1)) + 1 : Infinity;
660
- if (steps <= levels && param.scale !== "log") {
661
- for (let j = 0; j < steps; j++) out.push(snap(param, param.min! + j * (param.step ?? 1), 12));
662
- } else {
663
- for (let j = 0; j < levels; j++) out.push(snap(param, at01(param, j / (levels - 1)), 12));
664
- }
665
- return [...new Set(out)];
666
- }
667
-
668
- /** This function tells if a later param of the list reads a param in its `when`. */
669
- const readLater = (params: readonly SpaceParam[], i: number): boolean => params.slice(i + 1).some((q) => q.when?.param === params[i]!.name);
670
-
671
- /** This function gives the count of the grid assignments of the params of an option, with only the active params. */
672
- function countParams(params: readonly SpaceParam[], levels: number, i = 0, values: Values = {}): bigint {
673
- if (i === params.length) return 1n;
674
- const p = params[i]!;
675
- if (!isActive(p, values)) return countParams(params, levels, i + 1, values);
676
- const lv = paramLevels(p, levels);
677
- if (!readLater(params, i)) return BigInt(lv.length) * countParams(params, levels, i + 1, values);
678
- let sum = 0n;
679
- for (const v of lv) sum += countParams(params, levels, i + 1, { ...values, [p.name]: v });
680
- return sum;
681
- }
682
-
683
- /** This function gives the grid assignments of the params of an option, in a stable order. */
684
- function* gridParams(params: readonly SpaceParam[], levels: number, i = 0, values: Values = {}): Generator<Values> {
685
- if (i === params.length) {
686
- yield { ...values };
687
- return;
688
- }
689
- const p = params[i]!;
690
- if (!isActive(p, values)) {
691
- yield* gridParams(params, levels, i + 1, values);
692
- return;
693
- }
694
- for (const v of paramLevels(p, levels)) yield* gridParams(params, levels, i + 1, { ...values, [p.name]: v });
695
- }
696
-
697
- /** One combination of options of a space, with its count of grid points. */
698
- interface Combo {
699
- readonly choices: Choices;
700
- readonly base: boolean;
701
- /** The count of the grid points, or `null` when the count is more than the limit. */
702
- readonly weight: bigint | null;
703
- }
704
-
705
- const optionIds = (choices: Choices): Map<string, string | null> => new Map([...choices].map(([k, o]) => [k, o?.id ?? null]));
706
- const keeps = (space: StrategySpace, choices: Choices): boolean => (space.constraints ?? []).every((c) => holds(c, optionIds(choices)));
707
-
708
- /**
709
- * This function gives the constraints of a space for each stage: a constraint goes to the last stage that it names.
710
- * The last list holds each constraint that names a stage outside the space, so a walk examines it at the end.
711
- */
712
- function constraintsByStage(space: StrategySpace): readonly (readonly SpaceConstraint[])[] {
713
- const place = new Map(space.stages.map((s, i) => [s.name, i]));
714
- const lists: SpaceConstraint[][] = Array.from({ length: space.stages.length + 1 }, () => []);
715
- for (const c of space.constraints ?? []) {
716
- const named = [c.if.stage, "not" in c.then ? c.then.not.stage : c.then.stage];
717
- lists[Math.max(...named.map((name) => place.get(name) ?? space.stages.length))]!.push(c);
718
- }
719
- return lists;
720
- }
721
-
722
- /** This function gives the count of the member lists of a meta option without a pool from `base` base configs, or `null` above `limit`. */
723
- function memberLists(base: bigint, rule: MemberRule, limit: bigint): bigint | null {
724
- let sum = 0n;
725
- for (let m = rule.min; m <= rule.max; m++) {
726
- let n = 1n;
727
- for (let k = 0; k < m; k++) {
728
- n = (n * (base - BigInt(k))) / (rule.ordered ? 1n : BigInt(k + 1));
729
- if (n <= 0n) break;
730
- }
731
- if (n <= 0n) break;
732
- sum += n;
733
- if (sum > limit) return null;
734
- }
735
- return sum;
736
- }
737
-
738
- /** This function multiplies two counts. A `null` count or a product above `limit` gives `null`. */
739
- const times = (a: bigint | null, b: bigint | null, limit: bigint): bigint | null => (a === null || b === null ? null : a * b > limit ? null : a * b);
740
-
741
- /**
742
- * This function gives the combinations of options of a space and their grid counts.
743
- * A product space joins the combinations of its parts. Each combination keeps the constraints.
744
- */
745
- function combos(space: StrategySpace, levels: number, meta: boolean, limit: bigint): Combo[] {
746
- if (space.parts !== undefined && space.parts.length > 0) {
747
- let acc: Combo[] = [{ choices: new Map(), base: true, weight: 1n }];
748
- for (const part of space.parts) {
749
- const head = `${part.engine}.`;
750
- const own = combos(part, levels, meta, limit);
751
- const next: Combo[] = [];
752
- for (const a of acc)
753
- for (const b of own) {
754
- const choices = new Map(a.choices);
755
- for (const [k, o] of b.choices) choices.set(head + k, o);
756
- const base = a.base && b.base;
757
- next.push({ choices, base, weight: base ? a.weight! * b.weight! : times(a.weight, b.weight, limit) });
758
- }
759
- acc = next;
760
- }
761
- return acc.filter((c) => keeps(space, c.choices));
762
- }
763
- const counts = new Map<StageOption, bigint>();
764
- const countOf = (o: StageOption): bigint => {
765
- if (!counts.has(o)) counts.set(o, countParams(o.params, levels));
766
- return counts.get(o)!;
767
- };
768
- const out: Combo[] = [];
769
- const stages = space.stages;
770
- // A space can have hundreds of constraints. Each one is examined at its last stage, so the walk leaves a branch at the first break.
771
- const checks = constraintsByStage(space);
772
- const ids = new Map<string, string | null>();
773
- const walk = (i: number, choices: Map<string, StageOption | null>, weight: bigint): void => {
774
- if (i === stages.length) {
775
- if (checks[i]!.every((c) => holds(c, ids))) out.push({ choices: new Map(choices), base: true, weight });
776
- return;
777
- }
778
- const s = stages[i]!;
779
- const list: (StageOption | null)[] = s.options.filter((o) => o.members === undefined);
780
- if (s.optional) list.push(null);
781
- for (const o of list) {
782
- choices.set(s.name, o);
783
- ids.set(s.name, o?.id ?? null);
784
- if (checks[i]!.every((c) => holds(c, ids))) walk(i + 1, choices, o === null ? weight : weight * countOf(o));
785
- }
786
- choices.delete(s.name);
787
- ids.delete(s.name);
788
- };
789
- walk(0, new Map(), 1n);
790
- if (!meta) return out;
791
- const base = out.reduce((sum, c) => sum + c.weight!, 0n);
792
- for (const s of stages)
793
- for (const o of s.options) {
794
- if (o.members === undefined) continue;
795
- const choices = new Map<string, StageOption | null>(stages.map((x) => [x.name, x === s ? o : null]));
796
- const own = memberSpaces.get(o);
797
- const from = own === undefined ? base : baseCount(own, levels, limit);
798
- const lists = o.members.pool === undefined ? memberLists(from, o.members, limit) : BigInt(o.members.pool.length);
799
- if (keeps(space, choices)) out.push({ choices, base: false, weight: times(countOf(o), lists, limit) });
800
- }
801
- return out;
802
- }
803
-
804
- /**
805
- * This function gives the count of the grid points of a space, with `levels` levels for each numeric param.
806
- * It counts only the active params and the combinations that keep the constraints. It gives the meta configs apart.
807
- * A meta option with a `pool` counts each entry of the pool one time.
808
- * With `shapes`, it counts only the options that support each kind of the list.
16
+ import { SHAPE_KIND_IDS } from "./shapes.ts";
17
+
18
+ export {
19
+ type AnyOption,
20
+ type BooleanOption,
21
+ canonicalConfig,
22
+ checkConfig,
23
+ checkOptions,
24
+ checkSchema,
25
+ clampOptions,
26
+ configId,
27
+ type DeclaredStrategy,
28
+ declarationIssues,
29
+ type EnumerateOptions,
30
+ type EnumOption,
31
+ type GridOptions,
32
+ joinConfigs,
33
+ type KindOptions,
34
+ type ListItem,
35
+ listOptions,
36
+ type MemberRule,
37
+ type NoDefault,
38
+ type NoDefaultReason,
39
+ type NumberOption,
40
+ type OptionDeclaration,
41
+ optionDefaults,
42
+ type OptionIssue,
43
+ optionIssue,
44
+ type OptionRef,
45
+ type OptionScale,
46
+ type OptionSchema,
47
+ type OptionSetting,
48
+ type OptionSupports,
49
+ paramActive,
50
+ type ParamKind,
51
+ paramLevels,
52
+ paramProblem,
53
+ type ParamValue,
54
+ paramValue,
55
+ type ParamWhen,
56
+ productSpace,
57
+ type SampleOptions,
58
+ type ShapeFilter,
59
+ type SpaceConstraint,
60
+ type SpaceParam,
61
+ type SpaceSize,
62
+ type SpaceSizeOptions,
63
+ type SpaceStage,
64
+ splitConfig,
65
+ type StageChoice,
66
+ type StageOption,
67
+ STRATEGY_SPACE_SCHEMA,
68
+ type StrategyConfig,
69
+ type StrategySpace,
70
+ sweepGrid,
71
+ sweepOf,
72
+ type SweepOptions,
73
+ sweepValues,
74
+ type ValueOption,
75
+ } from "@mark1russell7/strategy-space";
76
+
77
+ /** This function gives the known shape kinds of a check: the list of the caller, or `SHAPE_KIND_IDS`. */
78
+ const withKinds = <T extends KindOptions>(options: T): T => ({ kinds: SHAPE_KIND_IDS, ...options });
79
+
80
+ /**
81
+ * This function checks a space with `checkSpace` of `@mark1russell7/strategy-space`.
82
+ * Without `kinds`, a shape kind of a `supports` that is not in `SHAPE_KIND_IDS` gives the claim `shape`.
83
+ */
84
+ export function checkSpace(space: StrategySpace, kindOptions: KindOptions = {}): ClaimBreak[] {
85
+ return checkSpaceOf(space, withKinds(kindOptions));
86
+ }
87
+
88
+ /**
89
+ * This function counts the grid points of a space with `spaceSize` of `@mark1russell7/strategy-space`.
90
+ * Without `kinds`, a shape kind that is not in `SHAPE_KIND_IDS` causes an error.
809
91
  */
810
92
  export function spaceSize(space: StrategySpace, options: SpaceSizeOptions): SpaceSize {
811
- assertSpace(space);
812
- assertWhole(options.levels, "levels", 1);
813
- assertShapes(options.shapes);
814
- return sizeOf(restrict(space, options.shapes), options.levels, options.maxMeta ?? 10n ** 18n);
93
+ return spaceSizeOf(space, withKinds(options));
815
94
  }
816
95
 
817
96
  /**
818
- * This function gives the space with only the options that support each shape kind of `shapes`. Without `shapes`, it gives the same space.
819
- * A stage can lose all of its options. Then the space has no config with that stage.
820
- * A pool keeps only the entries whose members fit the smaller space. A meta option without such an entry goes out.
821
- *
822
- * The members of an option with `view: "bounds"` come from the space for the kinds of `memberShapes`. `memberSpaces` keeps that space.
823
- */
824
- function restrict(space: StrategySpace, shapes: readonly ShapeKind[] | undefined): StrategySpace {
825
- if (shapes === undefined) return space;
826
- const kept: StrategySpace = {
827
- ...space,
828
- stages: space.stages.map((s) => ({ ...s, options: s.options.filter((o) => supportsShapes(o, shapes)) })),
829
- ...(space.parts === undefined ? {} : { parts: space.parts.map((p) => restrict(p, shapes)) }),
830
- };
831
- const withPool = (s: SpaceStage, o: StageOption): StageOption[] => {
832
- if (o.members === undefined) return [o];
833
- const inner = memberShapes(o.members, shapes)!;
834
- const own = sameKinds(inner, shapes) ? undefined : restrict(partOf(space, s.name).space, inner);
835
- const mark = (option: StageOption): StageOption[] => {
836
- if (own !== undefined) memberSpaces.set(option, own);
837
- return [option];
838
- };
839
- if (o.members.pool === undefined) return own === undefined ? [o] : mark({ ...o });
840
- const part = own ?? partOf(kept, s.name).space;
841
- const pool = o.members.pool.filter((entry) => fits(part, entry));
842
- return pool.length === 0 ? [] : mark({ ...o, members: { ...o.members, pool } });
843
- };
844
- return { ...kept, stages: kept.stages.map((s) => ({ ...s, options: s.options.flatMap((o) => withPool(s, o)) })) };
845
- }
846
-
847
- /** The space of the members of a meta option of a restricted space, when it is not the part of the option. Only `view: "bounds"` makes such a space. */
848
- const memberSpaces = /* @__PURE__ */ new WeakMap<StageOption, StrategySpace>();
849
-
850
- /**
851
- * This function tells if an option of a restricted space has a member list. A base option and a meta option with a `pool` have one.
852
- * A different meta option has one when its members have a base config. `restrict` keeps only the pool entries that fit.
853
- */
854
- const hasMembers = (space: StrategySpace, stage: string, o: StageOption): boolean =>
855
- o.members === undefined || o.members.max === 0 || o.members.pool !== undefined || combos(memberSpaces.get(o) ?? partOf(space, stage).space, 1, false, 0n).length > 0;
856
-
857
- /** This function tells if a restricted space has a config. A base config counts. With `meta`, a meta config counts when each of its meta options has a member list. */
858
- const hasConfig = (space: StrategySpace, meta: boolean): boolean =>
859
- combos(space, 1, meta, 0n).some((c) => c.base || [...c.choices].every(([stage, o]) => o === null || hasMembers(space, stage, o)));
860
-
861
- /** This function gives the error of a sample of a space that has no config for the shape kinds `shapes`. `kept` is the restricted space. */
862
- function noSample(space: StrategySpace, kept: StrategySpace, shapes: readonly ShapeKind[], meta: boolean): RangeError {
863
- const list = (names: readonly string[], one: string, more: string): string => (names.length === 1 ? `${one} ${names[0]}` : `${more} ${names.join(", ")}`);
864
- const empty = kept.stages.filter((s) => !s.optional && !s.options.some((o) => meta || o.members === undefined)).map((s) => s.name);
865
- const removed = !meta
866
- ? []
867
- : space.stages.flatMap((s) =>
868
- s.options
869
- .filter((o) => o.members !== undefined && o.members.view !== "bounds" && supportsShapes(o, shapes))
870
- .filter((o) => {
871
- const own = kept.stages.find((x) => x.name === s.name)?.options.find((x) => x.id === o.id);
872
- return own === undefined || !hasMembers(kept, s.name, own);
873
- })
874
- .map((o) => `${s.name}.${o.id}`),
875
- );
876
- let text = `The space ${space.engine} has no config for a sample with the shape kinds ${shapes.join(", ")}.`;
877
- if (empty.length > 0) text += ` ${list(empty, "The stage", "The stages")} ${empty.length === 1 ? "has" : "have"} no option for these kinds.`;
878
- if (removed.length > 0)
879
- text += ` ${list(removed, "The meta option", "The meta options")} ${removed.length === 1 ? "has" : "have"} no member config for these kinds. Set members.view to "bounds" when the members see only the bounding boxes.`;
880
- if (empty.length === 0 && removed.length === 0) text += " The constraints remove each config.";
881
- return new RangeError(text);
882
- }
883
-
884
- /** This function gives a constraint in words, for the reason of an error. */
885
- function constraintText(c: SpaceConstraint): string {
886
- const ref = (r: OptionRef): string => `${r.stage} ${r.option === null ? "has no option" : `is ${r.option}`}`;
887
- return "not" in c.then ? `if ${ref(c.if)}, then not ${ref(c.then.not)}` : `if ${ref(c.if)}, then ${ref(c.then)}`;
888
- }
889
-
890
- /**
891
- * This function throws a `RangeError` for a bad `fixed` option of a sample. A stage or an option that the space does not have is bad.
892
- * A meta option without `meta: "sample"` is bad, and so are two fixed options that a constraint forbids.
893
- */
894
- function assertFixed(space: StrategySpace, fixed: Readonly<Record<string, string>>, meta: boolean): void {
895
- for (const [stage, id] of Object.entries(fixed)) {
896
- const s = space.stages.find((x) => x.name === stage);
897
- if (s === undefined) throw new RangeError(`The option fixed names the stage ${stage}, and the space ${space.engine} has no such stage.`);
898
- const o = s.options.find((x) => x.id === id);
899
- if (o === undefined) throw new RangeError(`The option fixed names the option ${String(id)} of the stage ${stage}, and the stage has no such option.`);
900
- if (o.members !== undefined && !meta) throw new RangeError(`The option fixed names the meta option ${stage}.${id}, and a sample with meta skip has no meta option. Set meta to "sample".`);
901
- }
902
- const ids = new Map<string, string | null>(Object.entries(fixed));
903
- const other = (c: SpaceConstraint): string => ("not" in c.then ? c.then.not.stage : c.then.stage);
904
- const broken = (space.constraints ?? []).filter((c) => ids.has(c.if.stage) && ids.has(other(c)) && !holds(c, ids));
905
- if (broken.length > 0) {
906
- const names = Object.entries(fixed).map(([stage, id]) => `${stage}.${id}`);
907
- throw new RangeError(`The constraints of the space ${space.engine} forbid the fixed options ${names.join(", ")}. The broken constraints: ${broken.map(constraintText).join("; ")}.`);
908
- }
909
- }
910
-
911
- /**
912
- * This function gives the restricted space `kept` with only the fixed option at each fixed stage. A fixed stage that was optional stops being optional.
913
- * A meta option of another stage of the part of a fixed stage goes out. A sample gives no option to the other stages of the part of its meta option.
914
- */
915
- function fixStages(space: StrategySpace, kept: StrategySpace, fixed: Readonly<Record<string, string>>, shapes: readonly ShapeKind[] | undefined): StrategySpace {
916
- const prefix = prefixes(kept);
917
- const parts = new Set(Object.keys(fixed).map((stage) => prefix.get(stage)!));
918
- const stages = kept.stages.map((s) => {
919
- const id = fixed[s.name];
920
- if (id === undefined) return parts.has(prefix.get(s.name)!) ? { ...s, options: s.options.filter((o) => o.members === undefined) } : s;
921
- // A fixed meta option takes its members from the space before the fix, because the fix removes each base config of its own stage.
922
- const options = s.options.filter((o) => o.id === id).map((o) => (o.members === undefined ? o : withMemberSpace(o, memberSpaces.get(o) ?? partOf(kept, s.name).space)));
923
- if (options.length === 0) throw new RangeError(`The fixed option ${s.name}.${id} of the space ${space.engine} does not support the shape kinds ${(shapes ?? []).join(", ")}.`);
924
- return { ...s, options, optional: false };
925
- });
926
- return { ...kept, stages };
927
- }
928
-
929
- /** This function gives a copy of a meta option whose members come from `members`. */
930
- function withMemberSpace(o: StageOption, members: StrategySpace): StageOption {
931
- const copy = { ...o };
932
- memberSpaces.set(copy, members);
933
- return copy;
934
- }
935
-
936
- /** This function gives the error of a sample whose fixed options keep each constraint between them. The constraints with the other stages remove each config. */
937
- function noFixedSample(space: StrategySpace, fixed: Readonly<Record<string, string>>): RangeError {
938
- const names = Object.entries(fixed).map(([stage, id]) => `${stage}.${id}`);
939
- return new RangeError(
940
- `The space ${space.engine} has no config with the fixed options ${names.join(", ")}. No constraint between two fixed options breaks, so the constraints with the other stages remove each config.`,
941
- );
942
- }
943
-
944
- /** This function gives the count of the base configs of a space that is known to be good. */
945
- const baseCount = (space: StrategySpace, levels: number, limit: bigint): bigint => combos(space, levels, false, limit).reduce((sum, c) => sum + c.weight!, 0n);
946
-
947
- /** This function throws a `RangeError` for a list of shape kinds with a kind that is not declared. */
948
- function assertShapes(shapes: readonly ShapeKind[] | undefined): void {
949
- if (shapes === undefined) return;
950
- if (!Array.isArray(shapes)) throw new RangeError("The option shapes is not a list of shape kinds.");
951
- for (const k of shapes) if (!isShapeKind(k)) throw new RangeError(`The shape kind ${show(k)} is not one of ${SHAPE_KIND_IDS.join(", ")}.`);
952
- }
953
-
954
- /** This function gives the count of the grid points of a space that is known to be good. */
955
- function sizeOf(space: StrategySpace, levels: number, limit: bigint): SpaceSize {
956
- let base = 0n;
957
- let meta: bigint | null = 0n;
958
- for (const c of combos(space, levels, true, limit)) {
959
- if (c.base) base += c.weight!;
960
- else meta = meta === null || c.weight === null || meta + c.weight > limit ? null : meta + c.weight;
961
- }
962
- return { base, meta };
963
- }
964
-
965
- /** This function gives the cartesian product of lists, with the last list as the fastest. */
966
- function* product<T>(lists: readonly (readonly T[])[], i = 0, acc: T[] = []): Generator<T[]> {
967
- if (i === lists.length) {
968
- yield [...acc];
969
- return;
970
- }
971
- for (const x of lists[i]!) {
972
- acc.push(x);
973
- yield* product(lists, i + 1, acc);
974
- acc.pop();
975
- }
976
- }
977
-
978
- /** This function gives the configs of the grid of a space, without meta options. */
979
- function gridConfigs(space: StrategySpace, levels: number, limit: number, shapes: readonly ShapeKind[] | undefined): StrategyConfig[] {
980
- const kept = restrict(space, shapes);
981
- const size = sizeOf(kept, levels, 0n).base;
982
- if (size > BigInt(limit)) throw new RangeError(`The grid of the space ${space.engine} has ${size} configs, more than the limit ${limit}.`);
983
- const out: StrategyConfig[] = [];
984
- for (const c of combos(kept, levels, false, 0n)) {
985
- const names = [...c.choices.keys()];
986
- const lists = names.map((k) => {
987
- const o = c.choices.get(k)!;
988
- return o === null ? [null] : [...gridParams(o.params, levels)].map((params): StageChoice => ({ option: o.id, params }));
989
- });
990
- 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));
991
- }
992
- return out;
993
- }
994
-
995
- /** This function gives a random order of the numbers from 0 to `n - 1`. */
996
- function permutation(n: number, r: () => number): number[] {
997
- const out = Array.from({ length: n }, (_, i) => i);
998
- for (let i = n - 1; i > 0; i--) {
999
- const j = Math.floor(r() * (i + 1));
1000
- [out[i], out[j]] = [out[j]!, out[i]!];
1001
- }
1002
- return out;
1003
- }
1004
-
1005
- /** This function gives the value of a param at the fraction `u` of its range. A sampled real number has 6 significant digits. */
1006
- function sampleValue(p: SpaceParam, u: number): ParamValue {
1007
- if (p.kind === "bool") return u >= 0.5;
1008
- if (p.kind === "enum") {
1009
- const values = p.values!;
1010
- return values[Math.min(values.length - 1, Math.floor(u * values.length))]!;
1011
- }
1012
- if (p.min === p.max) return normalize(p, p.min!);
1013
- if (p.scale !== "log" && (p.kind === "int" || p.step !== undefined)) {
1014
- const steps = Math.round((lastPoint(p) - p.min!) / (p.step ?? 1)) + 1;
1015
- return snap(p, p.min! + Math.min(steps - 1, Math.floor(u * steps)) * (p.step ?? 1), 6);
1016
- }
1017
- return snap(p, at01(p, u), 6);
1018
- }
1019
-
1020
- /** This function gives a seed of 32 bits from a seed and a step name. */
1021
- const subSeed = (seed: number, step: string): number => Math.floor(stepRandom(seed, step)() * 4294967296);
1022
-
1023
- /**
1024
- * This function gives a sample of a space: Latin hypercube strata over the options, the params and the member counts.
1025
- * `canon` is the space of `canonicalConfig`: the space before a shape filter. A member of an option with `view: "bounds"` can have an option that the filter removed.
1026
- */
1027
- function sampleConfigs(
1028
- space: StrategySpace,
1029
- n: number,
1030
- seed: number,
1031
- meta: boolean,
1032
- maxTries: number,
1033
- canon: StrategySpace = space,
1034
- walk = false,
1035
- first: ReadonlySet<string> = new Set(),
1036
- ): StrategyConfig[] {
1037
- const stages = space.stages;
1038
- const prefix = prefixes(space);
1039
- // A stage without options can stay empty in a part with a meta option of `view: "bounds"` or with no member list, because that option replaces the stage.
1040
- const bounded = new Set(stages.filter((s) => meta && s.options.some((o) => memberSpaces.has(o) || o.members?.max === 0)).map((s) => prefix.get(s.name)!));
1041
- const lists = stages.map((s) => {
1042
- const list: (StageOption | null)[] = s.options.filter((o) => meta || o.members === undefined);
1043
- if (s.optional) list.push(null);
1044
- if (list.length === 0 && bounded.has(prefix.get(s.name)!)) list.push(null);
1045
- if (list.length === 0) throw new Error(`The stage ${s.name} of the space ${space.engine} has no option for a sample. A shape filter can remove all of its options.`);
1046
- return list;
1047
- });
1048
- // A meta option without a member list stays in its list, so the strata of 0.2.16 do not change. A point that chooses it draws again.
1049
- const usable = new Map<StageOption, boolean>();
1050
- const withMembers = (s: SpaceStage, o: StageOption | null | undefined): boolean => {
1051
- if (o === null || o === undefined || o.members === undefined) return true;
1052
- if (!usable.has(o)) usable.set(o, hasMembers(space, s.name, o));
1053
- return usable.get(o)!;
1054
- };
1055
- const plan = walk ? walkPlan(stages, lists, space.constraints ?? [], n, first) : null;
1056
- const points: Map<string, StageOption | null>[] = [];
1057
- let tries = 0;
1058
- for (let round = 0; points.length < n; round++) {
1059
- const r = stepRandom(seed, `options:${round}`);
1060
- const picks = walk ? lists.map(() => permutation(n, r)) : [];
1061
- const columns = walk ? [] : lists.map((list) => permutation(n, r).map((p) => list[Math.floor((p * list.length) / n)]!));
1062
- for (let i = 0; i < n && points.length < n; i++) {
1063
- 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.${walk ? "" : ' The option draw: "walk" gets a sample of a space with many constraints.'}`);
1064
- tries++;
1065
- const choices = plan !== null ? walkPoint(plan, picks, i) : new Map<string, StageOption | null>(stages.map((s, k) => [s.name, columns[k]![i]!]));
1066
- const metaPart = new Map<string, string>();
1067
- for (const s of stages) {
1068
- const o = choices.get(s.name);
1069
- if (o?.members !== undefined && !metaPart.has(prefix.get(s.name)!)) metaPart.set(prefix.get(s.name)!, s.name);
1070
- }
1071
- for (const s of stages) {
1072
- const m = metaPart.get(prefix.get(s.name)!);
1073
- if (m !== undefined && m !== s.name) choices.set(s.name, null);
1074
- }
1075
- const filled = stages.every((s) => s.optional === true || choices.get(s.name) !== null || metaPart.has(prefix.get(s.name)!));
1076
- if (filled && keeps(space, choices) && stages.every((s) => withMembers(s, choices.get(s.name)))) points.push(choices);
1077
- }
1078
- }
1079
- const values: Values[][] = points.map(() => stages.map(() => ({})));
1080
- const members: StrategyConfig[][][] = points.map(() => stages.map(() => []));
1081
- stages.forEach((s, k) => {
1082
- for (const o of s.options) {
1083
- const users = points.flatMap((c, i) => (c.get(s.name) === o ? [i] : []));
1084
- if (users.length === 0) continue;
1085
- for (const p of o.params) {
1086
- const active = users.filter((i) => isActive(p, values[i]![k]!));
1087
- const r = stepRandom(seed, `param:${s.name}:${o.id}:${p.name}`);
1088
- permutation(active.length, r).forEach((stratum, j) => {
1089
- values[active[j]!]![k]![p.name] = sampleValue(p, (stratum + r()) / active.length);
1090
- });
1091
- }
1092
- if (o.members === undefined || o.members.max === 0) continue;
1093
- const fixed = o.members.pool;
1094
- if (fixed !== undefined) {
1095
- const r = stepRandom(seed, `pool-entry:${s.name}:${o.id}`);
1096
- permutation(users.length, r).forEach((stratum, j) => {
1097
- members[users[j]!]![k] = [...fixed[Math.min(fixed.length - 1, Math.floor(((stratum + r()) / users.length) * fixed.length))]!];
1098
- });
1099
- continue;
1100
- }
1101
- const part = memberSpaces.get(o) ?? partOf(space, s.name).space;
1102
- const poolSize = Math.max(n, 4 * o.members.max, 8);
1103
- const seen = new Set<string>();
1104
- const pool = sampleConfigs(part, poolSize, subSeed(seed, `pool:${s.name}:${o.id}`), false, Math.max(1000, 100 * poolSize), part, walk).filter((c) => {
1105
- const id = idOf(c);
1106
- return seen.has(id) ? false : (seen.add(id), true);
1107
- });
1108
- const r = stepRandom(seed, `members:${s.name}:${o.id}`);
1109
- const { min, max } = o.members;
1110
- permutation(users.length, r).forEach((stratum, j) => {
1111
- const count = min + Math.min(max - min, Math.floor(((stratum + r()) / users.length) * (max - min + 1)));
1112
- 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}.`);
1113
- const picked = permutation(pool.length, r).slice(0, count);
1114
- members[users[j]!]![k] = picked.map((x) => pool[x]!);
1115
- });
1116
- }
1117
- });
1118
- return points.map((choices, i) => {
1119
- const out: Record<string, StageChoice | null> = {};
1120
- stages.forEach((s, k) => {
1121
- const o = choices.get(s.name)!;
1122
- 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]! };
1123
- });
1124
- return canonicalConfig(canon, { space: space.engine, stages: out });
1125
- });
1126
- }
1127
-
1128
- /**
1129
- * This function gives configs of a space, in their canonical form. Each config keeps the constraints. The result is deterministic.
1130
- *
1131
- * - 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.
1132
- * - 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.
1133
- * - A sample draws again when a point breaks a constraint. After `maxTries` draws, it throws an `Error`. Two sampled configs can be equal.
1134
- * - With `draw: "walk"`, each stage draws only from the options that keep the constraints with the stages before it. The largest stage keeps its equal strata.
1135
- * - With `shapes`, only the options that support each kind of the list count. Without `shapes`, the result does not change.
1136
- * - A meta option with a `pool` gives only the entries of its pool. With `shapes`, only the entries whose members support each kind count.
1137
- * - A sample draws again when a point chooses a meta option without a member list. `spaceSize` gives such an option 0.
1138
- * - With `shapes`, a sample throws a `RangeError` when the space has no config for the kinds. The error names the stages without an option and the meta options without members.
1139
- * - With `fixed`, each config has the fixed option at each named stage. A fixed option that the space, the shape filter or the constraints do not permit gets a `RangeError` with the reason.
97
+ * This function gives the configs of a grid or a sample with `enumerateSpace` of `@mark1russell7/strategy-space`.
98
+ * Without `kinds`, a shape kind that is not in `SHAPE_KIND_IDS` causes an error.
1140
99
  */
1141
100
  export function enumerateSpace(space: StrategySpace, options: EnumerateOptions): StrategyConfig[] {
1142
- assertSpace(space);
1143
- assertShapes(options.shapes);
1144
- if (options.mode === "grid") {
1145
- assertWhole(options.levels, "levels", 1);
1146
- return gridConfigs(space, options.levels, options.limit ?? 100_000, options.shapes);
1147
- }
1148
- if (options.mode !== "sample") throw new RangeError(`The mode ${String((options as { mode?: unknown }).mode)} is not grid or sample.`);
1149
- assertWhole(options.n, "n", 0);
1150
- if (!Number.isInteger(options.seed)) throw new RangeError(`The seed ${options.seed} is not a whole number.`);
1151
- const meta = options.meta ?? "skip";
1152
- if (meta !== "skip" && meta !== "sample") throw new RangeError(`The option meta is ${String(meta)}, not skip or sample.`);
1153
- const draw = options.draw ?? "reject";
1154
- if (draw !== "reject" && draw !== "walk") throw new RangeError(`The option draw is ${String(draw)}, not reject or walk.`);
1155
- const fixed = options.fixed;
1156
- if (fixed !== undefined) assertFixed(space, fixed, meta === "sample");
1157
- if (options.n === 0) return [];
1158
- const kept = restrict(space, options.shapes);
1159
- const drawn = fixed === undefined ? kept : fixStages(space, kept, fixed, options.shapes);
1160
- try {
1161
- return sampleConfigs(drawn, options.n, options.seed, meta === "sample", options.maxTries ?? Math.max(1000, 100 * options.n), space, draw === "walk", new Set(Object.keys(fixed ?? {})));
1162
- } catch (error) {
1163
- // Only a space without a config for the shape kinds, or for the fixed options, gives the RangeError. A different failure keeps its own error.
1164
- if (options.shapes !== undefined && !hasConfig(kept, meta === "sample")) throw noSample(space, kept, options.shapes, meta === "sample");
1165
- if (fixed !== undefined && !hasConfig(drawn, meta === "sample")) throw noFixedSample(space, fixed);
1166
- throw error;
1167
- }
1168
- }
1169
-
1170
- /**
1171
- * This function gives the shape kinds that a space accepts, in the order of `SHAPE_KINDS`. The value comes from the `supports` of the options.
1172
- * A space accepts a kind when it has at least one config without a meta option on that kind.
1173
- */
1174
- export function spaceShapeKinds(space: StrategySpace): ShapeKind[] {
1175
- assertSpace(space);
1176
- return SHAPE_KIND_IDS.filter((k) => sizeOf(restrict(space, [k]), 1, 0n).base > 0n);
1177
- }
1178
-
1179
- /**
1180
- * This function joins configs of the parts of a product space into one config of the space `space`.
1181
- * The name of each stage gets the prefix `<space of the part>.`. The members of a meta option do not change.
1182
- */
1183
- export function joinConfigs(space: string, parts: readonly StrategyConfig[]): StrategyConfig {
1184
- const stages: Record<string, StageChoice | null> = {};
1185
- for (const part of parts) for (const [k, c] of Object.entries(part.stages)) stages[`${part.space}.${k}`] = c;
1186
- return { space, stages };
1187
- }
1188
-
1189
- /** This function gives the config of the part `engine` of a joint config. It throws a `RangeError` when no stage has the prefix `<engine>.`. */
1190
- export function splitConfig(config: StrategyConfig, engine: string): StrategyConfig {
1191
- const head = `${engine}.`;
1192
- const entries = Object.entries(config.stages).filter(([k]) => k.startsWith(head));
1193
- if (entries.length === 0) throw new RangeError(`The config of the space ${config.space} has no stage of the part ${engine}.`);
1194
- return { space: engine, stages: Object.fromEntries(entries.map(([k, c]) => [k.slice(head.length), c])) };
101
+ return enumerateSpaceOf(space, withKinds(options));
1195
102
  }
1196
103
 
1197
104
  /**
1198
- * 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>.`.
1199
- * 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.
105
+ * This function gives the shape kinds that a space accepts, with `spaceShapeKinds` of `@mark1russell7/strategy-space`.
106
+ * Without `kinds`, it examines the kinds of `SHAPE_KIND_IDS`, in their order.
1200
107
  */
1201
- export function productSpace(a: StrategySpace, b: StrategySpace, name: string): StrategySpace {
1202
- if (a.engine === b.engine) throw new RangeError(`The two spaces have the same engine ${a.engine}.`);
1203
- if (name === "") throw new RangeError("The product space has no name.");
1204
- const stagesOf = (s: StrategySpace): SpaceStage[] => s.stages.map((x) => ({ ...x, name: `${s.engine}.${x.name}` }));
1205
- const ref = (s: StrategySpace, r: OptionRef): OptionRef => ({ stage: `${s.engine}.${r.stage}`, option: r.option });
1206
- const constraintsOf = (s: StrategySpace): SpaceConstraint[] =>
1207
- (s.constraints ?? []).map((c) => ({ if: ref(s, c.if), then: "not" in c.then ? { not: ref(s, c.then.not) } : ref(s, c.then) }));
1208
- const named: Record<string, StrategyConfig> = {};
1209
- 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]);
1210
- const constraints = [...constraintsOf(a), ...constraintsOf(b)];
1211
- return {
1212
- schema: STRATEGY_SPACE_SCHEMA,
1213
- engine: name,
1214
- version: `${a.engine}@${a.version}+${b.engine}@${b.version}`,
1215
- stages: [...stagesOf(a), ...stagesOf(b)],
1216
- ...(constraints.length > 0 ? { constraints } : {}),
1217
- ...(Object.keys(named).length > 0 ? { named } : {}),
1218
- parts: [a, b],
1219
- };
108
+ export function spaceShapeKinds(space: StrategySpace, options: KindOptions = {}): string[] {
109
+ return spaceShapeKindsOf(space, withKinds(options));
1220
110
  }