@mark1russell7/layout-contract 0.5.1 → 0.5.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/build/index.d.ts +13 -1
- package/build/index.d.ts.map +1 -1
- package/build/index.js +59 -16
- package/build/index.js.map +1 -1
- package/package.json +1 -1
- package/src/space-walk.ts +63 -0
- package/src/strategy-space.ts +33 -21
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"$schema": "https://json.schemastore.org/package",
|
|
3
3
|
"name": "@mark1russell7/layout-contract",
|
|
4
|
-
"version": "0.5.
|
|
4
|
+
"version": "0.5.3",
|
|
5
5
|
"description": "The shared contract of the packing and highways layout engines: the input and record formats, the turn rule, margins, tolerances and hard rules.",
|
|
6
6
|
"keywords": [
|
|
7
7
|
"layout",
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
// The walk draw of a sample of a strategy space (`docs/STRATEGY-SPACE.md`). The package root does not export this file.
|
|
2
|
+
import type { OptionRef, SpaceConstraint, SpaceStage, StageOption } from "./strategy-space.ts";
|
|
3
|
+
|
|
4
|
+
const refMatches = (ref: OptionRef, choices: ReadonlyMap<string, string | null>): boolean => (choices.get(ref.stage) ?? null) === ref.option;
|
|
5
|
+
|
|
6
|
+
/** This function tells if the option choices keep a constraint. */
|
|
7
|
+
export function holds(c: SpaceConstraint, choices: ReadonlyMap<string, string | null>): boolean {
|
|
8
|
+
if (!refMatches(c.if, choices)) return true;
|
|
9
|
+
return "not" in c.then ? !refMatches(c.then.not, choices) : refMatches(c.then, choices);
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
const otherStage = (c: SpaceConstraint): string => ("not" in c.then ? c.then.not.stage : c.then.stage);
|
|
13
|
+
|
|
14
|
+
/** This function tells if an option of a stage keeps each constraint between that stage and the stages that a walk has fixed. */
|
|
15
|
+
export function fitsWalk(constraints: readonly SpaceConstraint[], fixed: Map<string, string | null>, stage: string, id: string | null): boolean {
|
|
16
|
+
fixed.set(stage, id);
|
|
17
|
+
const ok = constraints.every((c) => !fixed.has(c.if.stage === stage ? otherStage(c) : c.if.stage) || holds(c, fixed));
|
|
18
|
+
fixed.delete(stage);
|
|
19
|
+
return ok;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** The order of the stages of a walk, and the constraints that name each stage. */
|
|
23
|
+
export interface WalkPlan {
|
|
24
|
+
/** The stages of the space. */
|
|
25
|
+
readonly stages: readonly SpaceStage[];
|
|
26
|
+
/** The options of each stage for a draw. */
|
|
27
|
+
readonly lists: readonly (readonly (StageOption | null)[])[];
|
|
28
|
+
/** The indexes of the stages, from the largest stage to the smallest. */
|
|
29
|
+
readonly order: readonly number[];
|
|
30
|
+
/** The constraints that name each stage. */
|
|
31
|
+
readonly naming: readonly (readonly SpaceConstraint[])[];
|
|
32
|
+
/** The count of points of a round. */
|
|
33
|
+
readonly n: number;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** This function gives the plan of a walk. Stages of equal size keep the order of the space. */
|
|
37
|
+
export function walkPlan(stages: readonly SpaceStage[], lists: readonly (readonly (StageOption | null)[])[], constraints: readonly SpaceConstraint[], n: number): WalkPlan {
|
|
38
|
+
return {
|
|
39
|
+
stages,
|
|
40
|
+
lists,
|
|
41
|
+
n,
|
|
42
|
+
order: stages.map((_, k) => k).sort((a, b) => lists[b]!.length - lists[a]!.length || a - b),
|
|
43
|
+
naming: stages.map((s) => constraints.filter((c) => c.if.stage === s.name || otherStage(c) === s.name)),
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* This function gives the options of one point of a walk. It fixes the largest stage first. Thus that stage keeps its equal strata, and the constraints limit only the smaller stages.
|
|
49
|
+
* The value `picks[k][i]` is the stratum of the stage `k` for the point `i`. A stage with no open option gets `null`, and the caller rejects that point.
|
|
50
|
+
* The argument `fits` lets a test give a fault. The default is `fitsWalk`.
|
|
51
|
+
*/
|
|
52
|
+
export function walkPoint(plan: WalkPlan, picks: readonly (readonly number[])[], i: number, fits: typeof fitsWalk = fitsWalk): Map<string, StageOption | null> {
|
|
53
|
+
const fixed = new Map<string, string | null>();
|
|
54
|
+
const out = new Map<string, StageOption | null>();
|
|
55
|
+
for (const k of plan.order) {
|
|
56
|
+
const s = plan.stages[k]!;
|
|
57
|
+
const open = plan.lists[k]!.filter((o) => fits(plan.naming[k]!, fixed, s.name, o?.id ?? null));
|
|
58
|
+
const o = open[Math.floor((picks[k]![i]! * open.length) / plan.n)] ?? null;
|
|
59
|
+
fixed.set(s.name, o?.id ?? null);
|
|
60
|
+
out.set(s.name, o);
|
|
61
|
+
}
|
|
62
|
+
return out;
|
|
63
|
+
}
|
package/src/strategy-space.ts
CHANGED
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
import type { ClaimBreak } from "./corpus.ts";
|
|
3
3
|
import { canonicalJson, sha256Hex } from "./hash.ts";
|
|
4
4
|
import { stepRandom } from "./random.ts";
|
|
5
|
+
import { holds, walkPlan, walkPoint } from "./space-walk.ts";
|
|
5
6
|
import { isShapeKind, SHAPE_KIND_IDS, type ShapeKind } from "./shapes.ts";
|
|
6
7
|
|
|
7
8
|
/** The schema of a strategy space. */
|
|
@@ -41,7 +42,10 @@ export interface SpaceParam {
|
|
|
41
42
|
readonly when?: ParamWhen;
|
|
42
43
|
}
|
|
43
44
|
|
|
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
|
+
*/
|
|
45
49
|
export interface MemberRule {
|
|
46
50
|
readonly min: number;
|
|
47
51
|
readonly max: number;
|
|
@@ -164,6 +168,14 @@ export interface SampleOptions extends ShapeFilter {
|
|
|
164
168
|
readonly meta?: "skip" | "sample";
|
|
165
169
|
/** The largest count of option draws. The default is the larger value of 1000 and `100 * n`. */
|
|
166
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
|
+
* A space whose constraints reject most draws gets its sample with `walk`. The two values give different configs for one seed.
|
|
175
|
+
* 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.
|
|
176
|
+
* Thus a mean over this sample is not a mean of the space.
|
|
177
|
+
*/
|
|
178
|
+
readonly draw?: "reject" | "walk";
|
|
167
179
|
}
|
|
168
180
|
|
|
169
181
|
/** The options of `enumerateSpace`. */
|
|
@@ -245,14 +257,6 @@ function partOf(space: StrategySpace, stage: string): { readonly space: Strategy
|
|
|
245
257
|
/** This function gives the prefix of the innermost part of each stage. */
|
|
246
258
|
const prefixes = (space: StrategySpace): Map<string, string> => new Map(space.stages.map((s) => [s.name, partOf(space, s.name).prefix]));
|
|
247
259
|
|
|
248
|
-
const refMatches = (ref: OptionRef, choices: ReadonlyMap<string, string | null>): boolean => (choices.get(ref.stage) ?? null) === ref.option;
|
|
249
|
-
|
|
250
|
-
/** This function tells if the option choices keep a constraint. */
|
|
251
|
-
function holds(c: SpaceConstraint, choices: ReadonlyMap<string, string | null>): boolean {
|
|
252
|
-
if (!refMatches(c.if, choices)) return true;
|
|
253
|
-
return "not" in c.then ? !refMatches(c.then.not, choices) : refMatches(c.then, choices);
|
|
254
|
-
}
|
|
255
|
-
|
|
256
260
|
const describe = (c: SpaceConstraint): string => {
|
|
257
261
|
const ref = (r: OptionRef): string => `${r.stage}=${r.option ?? "null"}`;
|
|
258
262
|
return "not" in c.then ? `if ${ref(c.if)} then not ${ref(c.then.not)}` : `if ${ref(c.if)} then ${ref(c.then)}`;
|
|
@@ -315,8 +319,11 @@ function optionProblems(stage: SpaceStage, o: StageOption): Problem[] {
|
|
|
315
319
|
if (o.supports !== undefined) out.push(...supportsProblems(o.supports, at));
|
|
316
320
|
if (o.members !== undefined) {
|
|
317
321
|
const { min, max, ordered } = o.members;
|
|
318
|
-
|
|
319
|
-
|
|
322
|
+
const noList = min === 0 && max === 0;
|
|
323
|
+
if (!Number.isInteger(min) || !Number.isInteger(max) || (!noList && (min < 1 || min > max)) || typeof ordered !== "boolean")
|
|
324
|
+
out.push(["members", `${at} has a member rule without whole counts 1 <= min <= max or min = max = 0, and a boolean ordered`]);
|
|
325
|
+
if (noList && (o.members.pool !== undefined || o.members.view !== undefined))
|
|
326
|
+
out.push(["members", `${at} has no member list, so its member rule cannot have a pool or a view`]);
|
|
320
327
|
const pool: unknown = o.members.pool;
|
|
321
328
|
if (pool !== undefined && (!Array.isArray(pool) || pool.length === 0 || !pool.every((entry: unknown) => Array.isArray(entry))))
|
|
322
329
|
out.push(["pool", `${at} has a pool that is not a list of one or more member lists`]);
|
|
@@ -837,7 +844,7 @@ const memberSpaces = /* @__PURE__ */ new WeakMap<StageOption, StrategySpace>();
|
|
|
837
844
|
* A different meta option has one when its members have a base config. `restrict` keeps only the pool entries that fit.
|
|
838
845
|
*/
|
|
839
846
|
const hasMembers = (space: StrategySpace, stage: string, o: StageOption): boolean =>
|
|
840
|
-
o.members === undefined || o.members.pool !== undefined || combos(memberSpaces.get(o) ?? partOf(space, stage).space, 1, false, 0n).length > 0;
|
|
847
|
+
o.members === undefined || o.members.max === 0 || o.members.pool !== undefined || combos(memberSpaces.get(o) ?? partOf(space, stage).space, 1, false, 0n).length > 0;
|
|
841
848
|
|
|
842
849
|
/** 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. */
|
|
843
850
|
const hasConfig = (space: StrategySpace, meta: boolean): boolean =>
|
|
@@ -949,11 +956,11 @@ const subSeed = (seed: number, step: string): number => Math.floor(stepRandom(se
|
|
|
949
956
|
* This function gives a sample of a space: Latin hypercube strata over the options, the params and the member counts.
|
|
950
957
|
* `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.
|
|
951
958
|
*/
|
|
952
|
-
function sampleConfigs(space: StrategySpace, n: number, seed: number, meta: boolean, maxTries: number, canon: StrategySpace = space): StrategyConfig[] {
|
|
959
|
+
function sampleConfigs(space: StrategySpace, n: number, seed: number, meta: boolean, maxTries: number, canon: StrategySpace = space, walk = false): StrategyConfig[] {
|
|
953
960
|
const stages = space.stages;
|
|
954
961
|
const prefix = prefixes(space);
|
|
955
|
-
// A stage without options can stay empty in a part with a meta option of `view: "bounds"
|
|
956
|
-
const bounded = new Set(stages.filter((s) => meta && s.options.some((o) => memberSpaces.has(o))).map((s) => prefix.get(s.name)!));
|
|
962
|
+
// 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.
|
|
963
|
+
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)!));
|
|
957
964
|
const lists = stages.map((s) => {
|
|
958
965
|
const list: (StageOption | null)[] = s.options.filter((o) => meta || o.members === undefined);
|
|
959
966
|
if (s.optional) list.push(null);
|
|
@@ -968,15 +975,17 @@ function sampleConfigs(space: StrategySpace, n: number, seed: number, meta: bool
|
|
|
968
975
|
if (!usable.has(o)) usable.set(o, hasMembers(space, s.name, o));
|
|
969
976
|
return usable.get(o)!;
|
|
970
977
|
};
|
|
978
|
+
const plan = walk ? walkPlan(stages, lists, space.constraints ?? [], n) : null;
|
|
971
979
|
const points: Map<string, StageOption | null>[] = [];
|
|
972
980
|
let tries = 0;
|
|
973
981
|
for (let round = 0; points.length < n; round++) {
|
|
974
982
|
const r = stepRandom(seed, `options:${round}`);
|
|
975
|
-
const
|
|
983
|
+
const picks = walk ? lists.map(() => permutation(n, r)) : [];
|
|
984
|
+
const columns = walk ? [] : lists.map((list) => permutation(n, r).map((p) => list[Math.floor((p * list.length) / n)]!));
|
|
976
985
|
for (let i = 0; i < n && points.length < n; i++) {
|
|
977
|
-
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
|
|
986
|
+
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.'}`);
|
|
978
987
|
tries++;
|
|
979
|
-
const choices = new Map<string, StageOption | null>(stages.map((s, k) => [s.name, columns[k]![i]!]));
|
|
988
|
+
const choices = plan !== null ? walkPoint(plan, picks, i) : new Map<string, StageOption | null>(stages.map((s, k) => [s.name, columns[k]![i]!]));
|
|
980
989
|
const metaPart = new Map<string, string>();
|
|
981
990
|
for (const s of stages) {
|
|
982
991
|
const o = choices.get(s.name);
|
|
@@ -1003,7 +1012,7 @@ function sampleConfigs(space: StrategySpace, n: number, seed: number, meta: bool
|
|
|
1003
1012
|
values[active[j]!]![k]![p.name] = sampleValue(p, (stratum + r()) / active.length);
|
|
1004
1013
|
});
|
|
1005
1014
|
}
|
|
1006
|
-
if (o.members === undefined) continue;
|
|
1015
|
+
if (o.members === undefined || o.members.max === 0) continue;
|
|
1007
1016
|
const fixed = o.members.pool;
|
|
1008
1017
|
if (fixed !== undefined) {
|
|
1009
1018
|
const r = stepRandom(seed, `pool-entry:${s.name}:${o.id}`);
|
|
@@ -1015,7 +1024,7 @@ function sampleConfigs(space: StrategySpace, n: number, seed: number, meta: bool
|
|
|
1015
1024
|
const part = memberSpaces.get(o) ?? partOf(space, s.name).space;
|
|
1016
1025
|
const poolSize = Math.max(n, 4 * o.members.max, 8);
|
|
1017
1026
|
const seen = new Set<string>();
|
|
1018
|
-
const pool = sampleConfigs(part, poolSize, subSeed(seed, `pool:${s.name}:${o.id}`), false, Math.max(1000, 100 * poolSize)).filter((c) => {
|
|
1027
|
+
const pool = sampleConfigs(part, poolSize, subSeed(seed, `pool:${s.name}:${o.id}`), false, Math.max(1000, 100 * poolSize), part, walk).filter((c) => {
|
|
1019
1028
|
const id = idOf(c);
|
|
1020
1029
|
return seen.has(id) ? false : (seen.add(id), true);
|
|
1021
1030
|
});
|
|
@@ -1045,6 +1054,7 @@ function sampleConfigs(space: StrategySpace, n: number, seed: number, meta: bool
|
|
|
1045
1054
|
* - 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.
|
|
1046
1055
|
* - 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.
|
|
1047
1056
|
* - A sample draws again when a point breaks a constraint. After `maxTries` draws, it throws an `Error`. Two sampled configs can be equal.
|
|
1057
|
+
* - 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.
|
|
1048
1058
|
* - With `shapes`, only the options that support each kind of the list count. Without `shapes`, the result does not change.
|
|
1049
1059
|
* - A meta option with a `pool` gives only the entries of its pool. With `shapes`, only the entries whose members support each kind count.
|
|
1050
1060
|
* - A sample draws again when a point chooses a meta option without a member list. `spaceSize` gives such an option 0.
|
|
@@ -1062,10 +1072,12 @@ export function enumerateSpace(space: StrategySpace, options: EnumerateOptions):
|
|
|
1062
1072
|
if (!Number.isInteger(options.seed)) throw new RangeError(`The seed ${options.seed} is not a whole number.`);
|
|
1063
1073
|
const meta = options.meta ?? "skip";
|
|
1064
1074
|
if (meta !== "skip" && meta !== "sample") throw new RangeError(`The option meta is ${String(meta)}, not skip or sample.`);
|
|
1075
|
+
const draw = options.draw ?? "reject";
|
|
1076
|
+
if (draw !== "reject" && draw !== "walk") throw new RangeError(`The option draw is ${String(draw)}, not reject or walk.`);
|
|
1065
1077
|
if (options.n === 0) return [];
|
|
1066
1078
|
const kept = restrict(space, options.shapes);
|
|
1067
1079
|
try {
|
|
1068
|
-
return sampleConfigs(kept, options.n, options.seed, meta === "sample", options.maxTries ?? Math.max(1000, 100 * options.n), space);
|
|
1080
|
+
return sampleConfigs(kept, options.n, options.seed, meta === "sample", options.maxTries ?? Math.max(1000, 100 * options.n), space, draw === "walk");
|
|
1069
1081
|
} catch (error) {
|
|
1070
1082
|
// Only a space without a config for the shape kinds gives the RangeError. A different failure keeps its own error.
|
|
1071
1083
|
if (options.shapes !== undefined && !hasConfig(kept, meta === "sample")) throw noSample(space, kept, options.shapes, meta === "sample");
|