@mark1russell7/layout-contract 0.5.2 → 0.5.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "$schema": "https://json.schemastore.org/package",
3
3
  "name": "@mark1russell7/layout-contract",
4
- "version": "0.5.2",
4
+ "version": "0.5.4",
5
5
  "description": "The shared contract of the packing and highways layout engines: the input and record formats, the turn rule, margins, tolerances and hard rules.",
6
6
  "keywords": [
7
7
  "layout",
package/src/space-walk.ts CHANGED
@@ -25,7 +25,7 @@ export interface WalkPlan {
25
25
  readonly stages: readonly SpaceStage[];
26
26
  /** The options of each stage for a draw. */
27
27
  readonly lists: readonly (readonly (StageOption | null)[])[];
28
- /** The indexes of the stages, from the largest stage to the smallest. */
28
+ /** The indexes of the stages. The stages of `first` come first, in the order of the space. The others follow, from the largest stage to the smallest. */
29
29
  readonly order: readonly number[];
30
30
  /** The constraints that name each stage. */
31
31
  readonly naming: readonly (readonly SpaceConstraint[])[];
@@ -33,13 +33,22 @@ export interface WalkPlan {
33
33
  readonly n: number;
34
34
  }
35
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 {
36
+ /**
37
+ * This function gives the plan of a walk. Stages of equal size keep the order of the space.
38
+ * The stages of `first` go first, for example the stages of the sample option `fixed`. Thus the other stages draw only from the options that keep the constraints with them.
39
+ */
40
+ export function walkPlan(
41
+ stages: readonly SpaceStage[],
42
+ lists: readonly (readonly (StageOption | null)[])[],
43
+ constraints: readonly SpaceConstraint[],
44
+ n: number,
45
+ first: ReadonlySet<string> = new Set(),
46
+ ): WalkPlan {
38
47
  return {
39
48
  stages,
40
49
  lists,
41
50
  n,
42
- order: stages.map((_, k) => k).sort((a, b) => lists[b]!.length - lists[a]!.length || a - b),
51
+ order: stages.map((_, k) => k).sort((a, b) => Number(first.has(stages[b]!.name)) - Number(first.has(stages[a]!.name)) || lists[b]!.length - lists[a]!.length || a - b),
43
52
  naming: stages.map((s) => constraints.filter((c) => c.if.stage === s.name || otherStage(c) === s.name)),
44
53
  };
45
54
  }
@@ -42,7 +42,10 @@ export interface SpaceParam {
42
42
  readonly when?: ParamWhen;
43
43
  }
44
44
 
45
- /** The rule of the members of a meta option: a count from `min` to `max`. Members with `ordered: false` are sorted by their `configId`. */
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
+ */
46
49
  export interface MemberRule {
47
50
  readonly min: number;
48
51
  readonly max: number;
@@ -168,11 +171,19 @@ export interface SampleOptions extends ShapeFilter {
168
171
  /**
169
172
  * How a point keeps the constraints. With `reject` (the default), a point that breaks a constraint draws again.
170
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.
171
175
  * A space whose constraints reject most draws gets its sample with `walk`. The two values give different configs for one seed.
172
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.
173
177
  * Thus a mean over this sample is not a mean of the space.
174
178
  */
175
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>>;
176
187
  }
177
188
 
178
189
  /** The options of `enumerateSpace`. */
@@ -316,8 +327,11 @@ function optionProblems(stage: SpaceStage, o: StageOption): Problem[] {
316
327
  if (o.supports !== undefined) out.push(...supportsProblems(o.supports, at));
317
328
  if (o.members !== undefined) {
318
329
  const { min, max, ordered } = o.members;
319
- if (!Number.isInteger(min) || !Number.isInteger(max) || min < 1 || min > max || typeof ordered !== "boolean")
320
- out.push(["members", `${at} has a member rule without whole counts 1 <= min <= max and a boolean ordered`]);
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`]);
321
335
  const pool: unknown = o.members.pool;
322
336
  if (pool !== undefined && (!Array.isArray(pool) || pool.length === 0 || !pool.every((entry: unknown) => Array.isArray(entry))))
323
337
  out.push(["pool", `${at} has a pool that is not a list of one or more member lists`]);
@@ -838,7 +852,7 @@ const memberSpaces = /* @__PURE__ */ new WeakMap<StageOption, StrategySpace>();
838
852
  * A different meta option has one when its members have a base config. `restrict` keeps only the pool entries that fit.
839
853
  */
840
854
  const hasMembers = (space: StrategySpace, stage: string, o: StageOption): boolean =>
841
- o.members === undefined || o.members.pool !== undefined || combos(memberSpaces.get(o) ?? partOf(space, stage).space, 1, false, 0n).length > 0;
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;
842
856
 
843
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. */
844
858
  const hasConfig = (space: StrategySpace, meta: boolean): boolean =>
@@ -867,6 +881,66 @@ function noSample(space: StrategySpace, kept: StrategySpace, shapes: readonly Sh
867
881
  return new RangeError(text);
868
882
  }
869
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
+
870
944
  /** This function gives the count of the base configs of a space that is known to be good. */
871
945
  const baseCount = (space: StrategySpace, levels: number, limit: bigint): bigint => combos(space, levels, false, limit).reduce((sum, c) => sum + c.weight!, 0n);
872
946
 
@@ -950,11 +1024,20 @@ const subSeed = (seed: number, step: string): number => Math.floor(stepRandom(se
950
1024
  * This function gives a sample of a space: Latin hypercube strata over the options, the params and the member counts.
951
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.
952
1026
  */
953
- function sampleConfigs(space: StrategySpace, n: number, seed: number, meta: boolean, maxTries: number, canon: StrategySpace = space, walk = false): StrategyConfig[] {
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[] {
954
1037
  const stages = space.stages;
955
1038
  const prefix = prefixes(space);
956
- // A stage without options can stay empty in a part with a meta option of `view: "bounds"`, because that option replaces the stage.
957
- const bounded = new Set(stages.filter((s) => meta && s.options.some((o) => memberSpaces.has(o))).map((s) => prefix.get(s.name)!));
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)!));
958
1041
  const lists = stages.map((s) => {
959
1042
  const list: (StageOption | null)[] = s.options.filter((o) => meta || o.members === undefined);
960
1043
  if (s.optional) list.push(null);
@@ -969,7 +1052,7 @@ function sampleConfigs(space: StrategySpace, n: number, seed: number, meta: bool
969
1052
  if (!usable.has(o)) usable.set(o, hasMembers(space, s.name, o));
970
1053
  return usable.get(o)!;
971
1054
  };
972
- const plan = walk ? walkPlan(stages, lists, space.constraints ?? [], n) : null;
1055
+ const plan = walk ? walkPlan(stages, lists, space.constraints ?? [], n, first) : null;
973
1056
  const points: Map<string, StageOption | null>[] = [];
974
1057
  let tries = 0;
975
1058
  for (let round = 0; points.length < n; round++) {
@@ -1006,7 +1089,7 @@ function sampleConfigs(space: StrategySpace, n: number, seed: number, meta: bool
1006
1089
  values[active[j]!]![k]![p.name] = sampleValue(p, (stratum + r()) / active.length);
1007
1090
  });
1008
1091
  }
1009
- if (o.members === undefined) continue;
1092
+ if (o.members === undefined || o.members.max === 0) continue;
1010
1093
  const fixed = o.members.pool;
1011
1094
  if (fixed !== undefined) {
1012
1095
  const r = stepRandom(seed, `pool-entry:${s.name}:${o.id}`);
@@ -1053,6 +1136,7 @@ function sampleConfigs(space: StrategySpace, n: number, seed: number, meta: bool
1053
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.
1054
1137
  * - A sample draws again when a point chooses a meta option without a member list. `spaceSize` gives such an option 0.
1055
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.
1056
1140
  */
1057
1141
  export function enumerateSpace(space: StrategySpace, options: EnumerateOptions): StrategyConfig[] {
1058
1142
  assertSpace(space);
@@ -1068,13 +1152,17 @@ export function enumerateSpace(space: StrategySpace, options: EnumerateOptions):
1068
1152
  if (meta !== "skip" && meta !== "sample") throw new RangeError(`The option meta is ${String(meta)}, not skip or sample.`);
1069
1153
  const draw = options.draw ?? "reject";
1070
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");
1071
1157
  if (options.n === 0) return [];
1072
1158
  const kept = restrict(space, options.shapes);
1159
+ const drawn = fixed === undefined ? kept : fixStages(space, kept, fixed, options.shapes);
1073
1160
  try {
1074
- return sampleConfigs(kept, options.n, options.seed, meta === "sample", options.maxTries ?? Math.max(1000, 100 * options.n), space, draw === "walk");
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 ?? {})));
1075
1162
  } catch (error) {
1076
- // Only a space without a config for the shape kinds gives the RangeError. A different failure keeps its own 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.
1077
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);
1078
1166
  throw error;
1079
1167
  }
1080
1168
  }