@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.
package/build/index.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { canonicalJson as canonicalJson$1, deriveSeed, fnv1a32 as fnv1a32$1, mulberry32 as mulberry32$1, sha256Hex as sha256Hex$1 } from "@mark1russell7/rigor-generators";
2
+ import { STRATEGY_SPACE_SCHEMA, canonicalConfig, checkConfig, checkOptions, checkSchema, checkSpace as checkSpace$1, clampOptions, configId, declarationIssues, enumerateSpace as enumerateSpace$1, joinConfigs, listOptions, optionDefaults, optionIssue, paramActive, paramLevels, paramProblem, paramValue, productSpace, spaceShapeKinds as spaceShapeKinds$1, spaceSize as spaceSize$1, splitConfig, sweepGrid, sweepOf, sweepValues } from "@mark1russell7/strategy-space";
2
3
  import { bootstrap, bootstrapStrata, signFlipTest, signTest } from "@mark1russell7/rigor-statistics";
3
4
  // src/geometry.ts
4
5
  /** The sides in clockwise order, from the top. */
@@ -1930,6 +1931,164 @@ function balanceMeasureSpecs(stage) {
1930
1931
  }
1931
1932
  ]);
1932
1933
  }
1934
+ // src/frame.ts
1935
+ /** The schema of a frame. */
1936
+ const FRAME_SCHEMA = "layout-frame/1";
1937
+ /** The states of a box in a frame: in the two layouts, only in the end layout, or only in the start layout. */
1938
+ const FRAME_STATES = [
1939
+ "stay",
1940
+ "enter",
1941
+ "leave"
1942
+ ];
1943
+ /** This function throws a `RangeError` for a value that is not a finite number. */
1944
+ function finite(value, name) {
1945
+ if (!Number.isFinite(value)) throw new RangeError(`layout-frame: the ${name} ${value} is not a finite number.`);
1946
+ }
1947
+ /** This function gives the boxes of a frame by id. An id two times or a bad value causes a `RangeError`. */
1948
+ function byId$1(frame, name) {
1949
+ if (frame.schema !== "layout-frame/1") throw new RangeError(`layout-frame: the ${name} frame has the schema ${String(frame.schema)}, not ${FRAME_SCHEMA}.`);
1950
+ const map = /* @__PURE__ */ new Map();
1951
+ for (const b of frame.boxes) {
1952
+ if (map.has(b.id)) throw new RangeError(`layout-frame: the id ${b.id} occurs two times in the ${name} frame.`);
1953
+ for (const k of [
1954
+ "x",
1955
+ "y",
1956
+ "w",
1957
+ "h",
1958
+ "presence"
1959
+ ]) finite(b[k], `${k} of ${b.id}`);
1960
+ if (b.presence < 0 || b.presence > 1) throw new RangeError(`layout-frame: the presence ${b.presence} of ${b.id} is not between 0 and 1.`);
1961
+ if (b.turn !== void 0 && b.turn !== 0 && b.turn !== 90) throw new RangeError(`layout-frame: the turn ${String(b.turn)} of ${b.id} is not 0 or 90.`);
1962
+ if (!FRAME_STATES.includes(b.state)) throw new RangeError(`layout-frame: the state ${String(b.state)} of ${b.id} is not one of ${FRAME_STATES.join(", ")}.`);
1963
+ map.set(b.id, b);
1964
+ }
1965
+ return map;
1966
+ }
1967
+ /** This function gives a box with the optional turn of `turn`. */
1968
+ function withTurn(box, turn) {
1969
+ return turn === void 0 ? box : {
1970
+ ...box,
1971
+ turn
1972
+ };
1973
+ }
1974
+ /** This function makes a frame of a layout. Each box has the state `stay` and the presence 1. */
1975
+ function frameOf(boxes) {
1976
+ const frame = {
1977
+ schema: FRAME_SCHEMA,
1978
+ boxes: boxes.map((b) => withTurn({
1979
+ id: b.id,
1980
+ x: b.x,
1981
+ y: b.y,
1982
+ w: b.w,
1983
+ h: b.h,
1984
+ presence: 1,
1985
+ state: "stay"
1986
+ }, b.turn))
1987
+ };
1988
+ byId$1(frame, "made");
1989
+ return frame;
1990
+ }
1991
+ /** This function gives the placements of a frame: the boxes with the state `stay` or `enter`, in the order of the frame. An engine starts a layout from them. */
1992
+ function outputOf(frame) {
1993
+ byId$1(frame, "given");
1994
+ return frame.boxes.filter((b) => b.state !== "leave").map((b) => b.turn === void 0 ? {
1995
+ id: b.id,
1996
+ x: b.x,
1997
+ y: b.y
1998
+ } : {
1999
+ id: b.id,
2000
+ x: b.x,
2001
+ y: b.y,
2002
+ turn: b.turn
2003
+ });
2004
+ }
2005
+ /** This function gives the presence of a box that enters (`up`) or leaves, at the time `t`. */
2006
+ function presenceAt(mode, up, from, t) {
2007
+ const to = up ? 1 : 0;
2008
+ if (mode === "fade") return from + (to - from) * t;
2009
+ if (up) return t > 0 ? 1 : from;
2010
+ return t < 1 ? from : 0;
2011
+ }
2012
+ /**
2013
+ * This function gives the frame at the time `t` of the change from `from` to `to`. The time is a number from 0 to 1.
2014
+ * A box in the two frames moves on a straight line, and its size and presence change on a straight line. It keeps the turn of `from` before the time 1.
2015
+ *
2016
+ * A box only in `to` enters at its place in `to`. A box only in `from` leaves at its place in `from`. `options` sets how their presence changes.
2017
+ * At the time 1, the result has the boxes of `to`. At the time 0, the result has the boxes of `from` and the entering boxes.
2018
+ * The order of the result: the boxes of `to`, then the leaving boxes in the order of `from`.
2019
+ */
2020
+ function frameAt(from, to, t, options = {}) {
2021
+ finite(t, "time");
2022
+ if (t < 0 || t > 1) throw new RangeError(`layout-frame: the time ${t} is not between 0 and 1.`);
2023
+ const a = byId$1(from, "start");
2024
+ byId$1(to, "end");
2025
+ if (t === 1) return {
2026
+ schema: FRAME_SCHEMA,
2027
+ boxes: [...to.boxes]
2028
+ };
2029
+ const enter = options.enter ?? "fade";
2030
+ const leave = options.leave ?? "fade";
2031
+ const lerp = (p, q) => p + (q - p) * t;
2032
+ const boxes = [];
2033
+ const seen = /* @__PURE__ */ new Set();
2034
+ for (const q of to.boxes) {
2035
+ seen.add(q.id);
2036
+ const p = a.get(q.id);
2037
+ if (p === void 0) {
2038
+ boxes.push({
2039
+ ...q,
2040
+ presence: presenceAt(enter, true, 0, t),
2041
+ state: "enter"
2042
+ });
2043
+ continue;
2044
+ }
2045
+ const state = p.state === "stay" ? q.state : p.state;
2046
+ const presence = p.state === "enter" ? presenceAt(enter, true, p.presence, t) : p.state === "leave" && q.state === "leave" ? presenceAt(leave, false, p.presence, t) : lerp(p.presence, q.presence);
2047
+ boxes.push(withTurn({
2048
+ id: q.id,
2049
+ x: lerp(p.x, q.x),
2050
+ y: lerp(p.y, q.y),
2051
+ w: lerp(p.w, q.w),
2052
+ h: lerp(p.h, q.h),
2053
+ presence,
2054
+ state
2055
+ }, p.turn));
2056
+ }
2057
+ for (const p of from.boxes) {
2058
+ if (seen.has(p.id)) continue;
2059
+ boxes.push({
2060
+ ...p,
2061
+ presence: presenceAt(leave, false, p.presence, t),
2062
+ state: "leave"
2063
+ });
2064
+ }
2065
+ return {
2066
+ schema: FRAME_SCHEMA,
2067
+ boxes
2068
+ };
2069
+ }
2070
+ /**
2071
+ * This function gives the move from `a` to `b`: the sum of the distances of the box centers, over the ids in the two frames.
2072
+ * A box that enters or leaves does not move, so it adds nothing. A start frame that an engine does not change gives 0.
2073
+ */
2074
+ function frameMove(a, b) {
2075
+ const before = byId$1(a, "first");
2076
+ byId$1(b, "second");
2077
+ let sum = 0;
2078
+ for (const q of b.boxes) {
2079
+ const p = before.get(q.id);
2080
+ if (p === void 0) continue;
2081
+ sum += Math.hypot(q.x + q.w / 2 - (p.x + p.w / 2), q.y + q.h / 2 - (p.y + p.h / 2));
2082
+ }
2083
+ return sum;
2084
+ }
2085
+ /**
2086
+ * This function gives the move of an engine from a start frame: `frameMove(start, run(start))`.
2087
+ * The gate of a start: a start that is a fixed point of the engine gives 0.
2088
+ */
2089
+ function fixedPointMove(start, run) {
2090
+ return frameMove(start, run(start));
2091
+ }
1933
2092
  // src/random.ts
1934
2093
  /**
1935
2094
  * This function gives a generator of random numbers in [0, 1). It is `mulberry32`, as in `docs/FORMAT.md` of `packing`.
@@ -2626,7 +2785,7 @@ const FAMILY_ANY_KIND = "*";
2626
2785
  /** The separator of the parts of a family key. */
2627
2786
  const FAMILY_SEP = "/";
2628
2787
  /** This function gives the text of a dimension value. A missing value, or a value that is not a string, a number or a boolean, gives `undefined`. */
2629
- function partOf$1(value) {
2788
+ function partOf(value) {
2630
2789
  if (typeof value === "string") return value;
2631
2790
  if (typeof value === "number" || typeof value === "boolean") return String(value);
2632
2791
  }
@@ -2638,7 +2797,7 @@ function familyParts(cell, familyBy) {
2638
2797
  if (Array.isArray(familyBy)) dims = familyBy;
2639
2798
  else {
2640
2799
  const map = familyBy;
2641
- kind = partOf$1(cell["kind"]);
2800
+ kind = partOf(cell["kind"]);
2642
2801
  if (kind === void 0) return { problem: "a cell without kind, which the map form of familyBy needs" };
2643
2802
  const entry = Object.hasOwn(map, kind) ? map[kind] : Object.hasOwn(map, "*") ? map["*"] : void 0;
2644
2803
  if (entry === void 0) return { problem: `the kind "${kind}", which has no entry in familyBy and no entry "*"` };
@@ -2646,7 +2805,7 @@ function familyParts(cell, familyBy) {
2646
2805
  parts.push(kind);
2647
2806
  }
2648
2807
  for (const dim of dims) {
2649
- const part = partOf$1(cell[dim]);
2808
+ const part = partOf(cell[dim]);
2650
2809
  if (part === void 0) return { problem: `a cell${kind === void 0 ? "" : ` of the kind "${kind}"`} without the dimension "${dim}" of familyBy` };
2651
2810
  parts.push(part);
2652
2811
  }
@@ -2665,7 +2824,7 @@ function familyOf(cell, familyBy) {
2665
2824
  /** This function tells if a value is a `FamilyBy`: a list of dimensions, or a map from a kind to a list of dimensions. */
2666
2825
  function isFamilyBy(value) {
2667
2826
  const isDims = (v) => Array.isArray(v) && v.every((d) => typeof d === "string");
2668
- return isDims(value) || isObject$1(value) && Object.values(value).every(isDims);
2827
+ return isDims(value) || isObject(value) && Object.values(value).every(isDims);
2669
2828
  }
2670
2829
  /**
2671
2830
  * This function gives the count of the inputs for each property id. Each id of `ids` has a count, also when the count is 0.
@@ -2677,7 +2836,7 @@ function declaredCounts(inputs, declares, ids = []) {
2677
2836
  return out;
2678
2837
  }
2679
2838
  /** This function tells if a value is a plain object. */
2680
- const isObject$1 = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
2839
+ const isObject = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
2681
2840
  /**
2682
2841
  * This function reads the field `claims.declared` of a manifest. A manifest without it gives `undefined`.
2683
2842
  * It throws an `Error` for a claim without a whole `minCount`, a list `thin` of ids and a whole count for each id.
@@ -2685,14 +2844,14 @@ const isObject$1 = (value) => value !== null && typeof value === "object" && !Ar
2685
2844
  function declaredClaimOf(manifest) {
2686
2845
  const claims = manifest["claims"];
2687
2846
  if (claims === void 0) return void 0;
2688
- if (!isObject$1(claims)) throw new Error("The field claims of a corpus file is an object.");
2847
+ if (!isObject(claims)) throw new Error("The field claims of a corpus file is an object.");
2689
2848
  const declared = claims["declared"];
2690
2849
  if (declared === void 0) return void 0;
2691
- if (!isObject$1(declared)) throw new Error("The field claims.declared of a corpus file is an object.");
2850
+ if (!isObject(declared)) throw new Error("The field claims.declared of a corpus file is an object.");
2692
2851
  const { minCount, thin, counts } = declared;
2693
2852
  if (!Number.isInteger(minCount) || minCount < 0) throw new Error("The field claims.declared.minCount is a whole number of 0 or more.");
2694
2853
  if (!Array.isArray(thin) || !thin.every((id) => typeof id === "string")) throw new Error("The field claims.declared.thin is a list of property ids.");
2695
- if (!isObject$1(counts) || !Object.values(counts).every((n) => Number.isInteger(n) && n >= 0)) throw new Error("The field claims.declared.counts gives a whole count for each property id.");
2854
+ if (!isObject(counts) || !Object.values(counts).every((n) => Number.isInteger(n) && n >= 0)) throw new Error("The field claims.declared.counts gives a whole count for each property id.");
2696
2855
  const { familyBy, familyMin } = declared;
2697
2856
  if (familyBy !== void 0 && !isFamilyBy(familyBy)) throw new Error("The field claims.declared.familyBy is a list of dimensions, or a map from a kind to a list of dimensions.");
2698
2857
  if (familyMin !== void 0 && (!Number.isInteger(familyMin) || familyMin < 0)) throw new Error("The field claims.declared.familyMin is a whole number of 0 or more.");
@@ -2738,12 +2897,12 @@ function checkDeclared(inputs, declares, claim, ids = Object.keys(claim.counts),
2738
2897
  }
2739
2898
  /** This function gives the field `cell` of an input, when it is an object. */
2740
2899
  function cellField(input) {
2741
- const cell = isObject$1(input) ? input["cell"] : void 0;
2742
- return isObject$1(cell) ? cell : void 0;
2900
+ const cell = isObject(input) ? input["cell"] : void 0;
2901
+ return isObject(cell) ? cell : void 0;
2743
2902
  }
2744
2903
  /** This function gives the field `id` of an input, or its place in the list. */
2745
2904
  function inputId(input, at) {
2746
- const id = isObject$1(input) ? input["id"] : void 0;
2905
+ const id = isObject(input) ? input["id"] : void 0;
2747
2906
  return typeof id === "string" ? id : `#${at}`;
2748
2907
  }
2749
2908
  /** This function gives the breaks of the family keys of the inputs: the problems of each key, the collisions and the thin families. */
@@ -2872,1265 +3031,39 @@ function leaveOneSeedOut(seeds) {
2872
3031
  heldOut: [s]
2873
3032
  }));
2874
3033
  }
2875
- // src/space-walk.ts
2876
- const refMatches = (ref, choices) => (choices.get(ref.stage) ?? null) === ref.option;
2877
- /** This function tells if the option choices keep a constraint. */
2878
- function holds(c, choices) {
2879
- if (!refMatches(c.if, choices)) return true;
2880
- return "not" in c.then ? !refMatches(c.then.not, choices) : refMatches(c.then, choices);
2881
- }
2882
- const otherStage = (c) => "not" in c.then ? c.then.not.stage : c.then.stage;
2883
- /** This function tells if an option of a stage keeps each constraint between that stage and the stages that a walk has fixed. */
2884
- function fitsWalk(constraints, fixed, stage, id) {
2885
- fixed.set(stage, id);
2886
- const ok = constraints.every((c) => !fixed.has(c.if.stage === stage ? otherStage(c) : c.if.stage) || holds(c, fixed));
2887
- fixed.delete(stage);
2888
- return ok;
2889
- }
2890
- /**
2891
- * This function gives the plan of a walk. Stages of equal size keep the order of the space.
2892
- * 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.
2893
- */
2894
- function walkPlan(stages, lists, constraints, n, first = /* @__PURE__ */ new Set()) {
2895
- return {
2896
- stages,
2897
- lists,
2898
- n,
2899
- 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),
2900
- naming: stages.map((s) => constraints.filter((c) => c.if.stage === s.name || otherStage(c) === s.name))
2901
- };
2902
- }
2903
- /**
2904
- * 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.
2905
- * 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.
2906
- * The argument `fits` lets a test give a fault. The default is `fitsWalk`.
2907
- */
2908
- function walkPoint(plan, picks, i, fits = fitsWalk) {
2909
- const fixed = /* @__PURE__ */ new Map();
2910
- const out = /* @__PURE__ */ new Map();
2911
- for (const k of plan.order) {
2912
- const s = plan.stages[k];
2913
- const open = plan.lists[k].filter((o) => fits(plan.naming[k], fixed, s.name, o?.id ?? null));
2914
- const o = open[Math.floor(picks[k][i] * open.length / plan.n)] ?? null;
2915
- fixed.set(s.name, o?.id ?? null);
2916
- out.set(s.name, o);
2917
- }
2918
- return out;
2919
- }
2920
3034
  // src/strategy-space.ts
2921
- /** The schema of a strategy space. */
2922
- const STRATEGY_SPACE_SCHEMA = "strategy-space/1";
2923
- const isObject = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
2924
- const show = (value) => typeof value === "string" ? `"${value}"` : String(value);
2925
- const isNumeric = (p) => p.kind === "int" || p.kind === "real";
2926
- const zero = (v) => v === 0 ? 0 : v;
2927
- /** This function gives the stable form of a real number: 12 significant digits, with `-0` as `0`. */
2928
- const realForm = (v, digits = 12) => zero(Number(v.toPrecision(digits)));
2929
- /** This function gives the stable form of a value of a param. */
2930
- function normalize(p, v) {
2931
- if (typeof v !== "number") return v;
2932
- if (p.kind !== "real") return zero(v);
2933
- return Math.min(p.max ?? Infinity, Math.max(p.min ?? -Infinity, realForm(v)));
2934
- }
2935
- /** This function tells if a value is on the step of a param. */
2936
- function onStep(p, v) {
2937
- if (p.step === void 0 || p.min === void 0) return true;
2938
- const q = (v - p.min) / p.step;
2939
- return Math.abs(q - Math.round(q)) <= 1e-9 * Math.max(1, Math.abs(q));
2940
- }
2941
- /** This function gives the problem of a value of a param, or `undefined` for a value in the range. */
2942
- function valueProblem(p, v) {
2943
- if (p.kind === "bool") return typeof v === "boolean" ? void 0 : `${show(v)} is not true or false`;
2944
- if (p.kind === "enum") return (p.values ?? []).some((x) => x === v) ? void 0 : `${show(v)} is not one of ${(p.values ?? []).map(show).join(", ")}`;
2945
- if (typeof v !== "number" || !Number.isFinite(v)) return `${show(v)} is not a finite number`;
2946
- if (p.kind === "int" && !Number.isInteger(v)) return `${v} is not a whole number`;
2947
- if (p.min !== void 0 && v < p.min) return `${v} is less than the min ${p.min}`;
2948
- if (p.max !== void 0 && v > p.max) return `${v} is more than the max ${p.max}`;
2949
- if (!onStep(p, v)) return `${v} is not on the step ${p.step} from ${p.min}`;
2950
- }
2951
- /** This function tells if a param is active for the values of the earlier params. */
2952
- function isActive(p, values) {
2953
- if (p.when === void 0) return true;
2954
- if (!Object.hasOwn(values, p.when.param)) return false;
2955
- const v = values[p.when.param];
2956
- return p.when.in.some((x) => x === v);
2957
- }
2958
- /** 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. */
2959
- function paramProblem(param, value) {
2960
- return valueProblem(param, value);
2961
- }
2962
- /** This function tells if a param is active for the values of the earlier params. A param without `when` is always active. */
2963
- function paramActive(param, values) {
2964
- return isActive(param, values);
2965
- }
2966
- /** This function gives the stable form of a value of a param: a real number gets 12 significant digits, and `-0` becomes `0`. */
2967
- function paramValue(param, value) {
2968
- return normalize(param, value);
2969
- }
2970
- /** This function gives the part of a space that has a stage, and the prefix of the names of its stages. */
2971
- function partOf(space, stage) {
2972
- for (const part of space.parts ?? []) {
2973
- const head = `${part.engine}.`;
2974
- if (stage.startsWith(head)) {
2975
- const inner = partOf(part, stage.slice(head.length));
2976
- return {
2977
- space: inner.space,
2978
- prefix: head + inner.prefix
2979
- };
2980
- }
2981
- }
2982
- return {
2983
- space,
2984
- prefix: ""
2985
- };
2986
- }
2987
- /** This function gives the prefix of the innermost part of each stage. */
2988
- const prefixes = (space) => new Map(space.stages.map((s) => [s.name, partOf(space, s.name).prefix]));
2989
- const describe = (c) => {
2990
- const ref = (r) => `${r.stage}=${r.option ?? "null"}`;
2991
- return "not" in c.then ? `if ${ref(c.if)} then not ${ref(c.then.not)}` : `if ${ref(c.if)} then ${ref(c.then)}`;
2992
- };
2993
- /** This function gives the problems of the range and the default of one param. */
2994
- function paramProblems(p, at) {
2995
- const out = [];
2996
- if (isNumeric(p)) {
2997
- const { min, max, step } = p;
2998
- if (typeof min !== "number" || typeof max !== "number" || !Number.isFinite(min) || !Number.isFinite(max)) {
2999
- out.push(["range", `${at} has no finite min and max`]);
3000
- return out;
3001
- }
3002
- if (min > max) out.push(["range", `${at} has an empty range: the min ${min} is more than the max ${max}`]);
3003
- 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`]);
3004
- if (step !== void 0 && (!Number.isFinite(step) || step <= 0 || p.kind === "int" && !Number.isInteger(step))) out.push(["range", `${at} has the step ${step}, which is not a ${p.kind === "int" ? "whole " : ""}number above 0`]);
3005
- if (p.scale === "log" && min <= 0) out.push(["scale", `${at} has the scale log with the min ${min}, which is not above 0`]);
3006
- } else {
3007
- if (p.scale !== void 0) out.push(["scale", `${at} is a ${p.kind} param with a scale`]);
3008
- if (p.kind === "enum") {
3009
- if (!Array.isArray(p.values) || p.values.length === 0) out.push(["values", `${at} is an enum without values`]);
3010
- else {
3011
- const seen = /* @__PURE__ */ new Set();
3012
- for (const v of p.values) {
3013
- if (seen.has(v)) out.push(["duplicate", `${at} has the value ${show(v)} two times`]);
3014
- seen.add(v);
3015
- }
3016
- }
3017
- }
3018
- }
3019
- if (out.length === 0) {
3020
- const problem = valueProblem(p, p.default);
3021
- if (problem !== void 0) out.push(["default", `the default of ${at} is not in its range: ${problem}`]);
3022
- }
3023
- return out;
3024
- }
3025
- /** This function gives the problems of one stage option. */
3026
- function optionProblems(stage, o) {
3027
- const out = [];
3028
- const at = `the option ${stage.name}.${o.id}`;
3029
- if (!Array.isArray(o.params)) return [["config", `${at} has no list of params`]];
3030
- const names = o.params.map((p) => p.name);
3031
- o.params.forEach((p, i) => {
3032
- const pat = `the param ${stage.name}.${o.id}.${p.name}`;
3033
- if (names.indexOf(p.name) !== i) out.push(["duplicate", `${at} has the param ${p.name} two times`]);
3034
- out.push(...paramProblems(p, pat));
3035
- if (p.when === void 0) return;
3036
- const j = names.indexOf(p.when.param);
3037
- if (j < 0) out.push(["unknown", `${pat} has a when with the unknown param ${p.when.param}`]);
3038
- else if (j >= i) out.push(["when", `${pat} has a when with the param ${p.when.param}, which does not come before it`]);
3039
- else if (!Array.isArray(p.when.in) || p.when.in.length === 0) out.push(["when", `${pat} has a when with no values`]);
3040
- else for (const v of p.when.in) {
3041
- const problem = valueProblem(o.params[j], v);
3042
- if (problem !== void 0) out.push(["when", `${pat} has a when value that is not a value of ${p.when.param}: ${problem}`]);
3043
- }
3044
- });
3045
- if (o.supports !== void 0) out.push(...supportsProblems(o.supports, at));
3046
- if (o.members !== void 0) {
3047
- const { min, max, ordered } = o.members;
3048
- const noList = min === 0 && max === 0;
3049
- if (!Number.isInteger(min) || !Number.isInteger(max) || !noList && (min < 1 || min > max) || typeof ordered !== "boolean") out.push(["members", `${at} has a member rule without whole counts 1 <= min <= max or min = max = 0, and a boolean ordered`]);
3050
- if (noList && (o.members.pool !== void 0 || o.members.view !== void 0)) out.push(["members", `${at} has no member list, so its member rule cannot have a pool or a view`]);
3051
- const pool = o.members.pool;
3052
- if (pool !== void 0 && (!Array.isArray(pool) || pool.length === 0 || !pool.every((entry) => Array.isArray(entry)))) out.push(["pool", `${at} has a pool that is not a list of one or more member lists`]);
3053
- const view = o.members.view;
3054
- if (view !== void 0 && view !== "bounds") out.push(["view", `${at} has the member view ${show(view)}, not "bounds"`]);
3055
- }
3056
- return out;
3057
- }
3058
- /** This function gives the problems of the `supports` of an option. */
3059
- function supportsProblems(supports, at) {
3060
- if (!isObject(supports)) return [["shape", `the supports of ${at} are not an object`]];
3061
- const shape = supports["shape"];
3062
- if (shape === void 0) return [];
3063
- if (!Array.isArray(shape) || shape.length === 0) return [["shape", `${at} supports no shape kind. Remove shape to support each kind`]];
3064
- const out = [];
3065
- shape.forEach((k, i) => {
3066
- if (!isShapeKind(k)) out.push(["shape", `${at} supports the shape kind ${show(k)}, which is not one of ${SHAPE_KIND_IDS.join(", ")}`]);
3067
- else if (shape.indexOf(k) !== i) out.push(["duplicate", `${at} has the shape kind ${k} two times`]);
3068
- });
3069
- return out;
3070
- }
3071
- /** This function tells if an option supports each shape kind of the list. */
3072
- const supportsShapes = (o, shapes) => shapes === void 0 || o.supports?.shape === void 0 || shapes.every((k) => o.supports.shape.includes(k));
3073
- /** The shape kinds that the members of an option with `view: "bounds"` see: a bounding box is a `rect`. */
3074
- const BOUNDS_VIEW = /* @__PURE__ */ Object.freeze(["rect"]);
3075
- /**
3076
- * This function gives the shape kinds of the members of a meta option. With `view: "bounds"`, a list with a kind becomes `BOUNDS_VIEW`.
3077
- * Without a list, or with an empty list, the value does not change.
3078
- */
3079
- const memberShapes = (rule, shapes) => rule.view === "bounds" && shapes !== void 0 && shapes.length > 0 ? BOUNDS_VIEW : shapes;
3080
- /** This function tells if two lists have the same shape kinds. */
3081
- const sameKinds = (a, b) => a.every((k) => b.includes(k)) && b.every((k) => a.includes(k));
3082
- /** This function gives the problems of the params of one stage choice. */
3083
- function choiceParamProblems(o, params, at) {
3084
- if (params !== void 0 && !isObject(params)) return [["config", `the params of ${at} are not an object`]];
3085
- const given = params ?? {};
3086
- const out = [];
3087
- for (const key of Object.keys(given)) if (!o.params.some((p) => p.name === key)) out.push(["unknown", `${at} has the unknown param ${key}`]);
3088
- const values = {};
3089
- for (const p of o.params) {
3090
- const has = Object.hasOwn(given, p.name);
3091
- if (!isActive(p, values)) {
3092
- if (has) out.push(["inactive", `${at} sets the param ${p.name}, which is not active`]);
3093
- continue;
3094
- }
3095
- const v = has ? given[p.name] : p.default;
3096
- const problem = valueProblem(p, v);
3097
- if (problem !== void 0) out.push(["param", `the param ${p.name} of ${at} is not in its range: ${problem}`]);
3098
- else values[p.name] = normalize(p, v);
3099
- }
3100
- return out;
3101
- }
3102
- /** This function gives the problems of a config of a space. A member of a meta option has `member: true`. */
3103
- function configProblems(space, config, member, shapes) {
3104
- if (!isObject(config) || !isObject(config["stages"])) return [["config", "the config is not an object with stages"]];
3105
- const out = [];
3106
- const stages = config["stages"];
3107
- if (config["space"] !== space.engine) out.push(["space", `the space of the config is ${show(config["space"])}, not ${show(space.engine)}`]);
3108
- 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}`]);
3109
- const optionOf = (s) => {
3110
- const c = stages[s.name];
3111
- return isObject(c) ? s.options.find((o) => o.id === c["option"]) : void 0;
3112
- };
3113
- const prefix = prefixes(space);
3114
- const metaStage = /* @__PURE__ */ new Map();
3115
- for (const s of space.stages) {
3116
- if (optionOf(s)?.members === void 0) continue;
3117
- const p = prefix.get(s.name);
3118
- if (metaStage.has(p)) out.push(["meta", `the stages ${metaStage.get(p)} and ${s.name} both have a meta option`]);
3119
- else metaStage.set(p, s.name);
3120
- }
3121
- const chosen = /* @__PURE__ */ new Map();
3122
- for (const s of space.stages) {
3123
- const c = Object.hasOwn(stages, s.name) ? stages[s.name] : void 0;
3124
- const meta = metaStage.get(prefix.get(s.name));
3125
- chosen.set(s.name, null);
3126
- if (c === void 0 || c === null) {
3127
- if (!s.optional && meta === void 0) out.push(["missing", `the config has no option for the stage ${s.name}`]);
3128
- continue;
3129
- }
3130
- if (!isObject(c) || typeof c["option"] !== "string") {
3131
- out.push(["config", `the choice of the stage ${s.name} has no option`]);
3132
- continue;
3133
- }
3134
- const o = s.options.find((x) => x.id === c["option"]);
3135
- if (o === void 0) {
3136
- out.push(["unknown", `the stage ${s.name} has no option ${c["option"]}`]);
3137
- continue;
3138
- }
3139
- chosen.set(s.name, o.id);
3140
- const at = `the option ${s.name}.${o.id}`;
3141
- if (!supportsShapes(o, shapes)) {
3142
- const missing = shapes.filter((k) => !o.supports.shape.includes(k));
3143
- out.push(["shape", `${at} supports the shape kinds ${o.supports.shape.join(", ")}, not ${missing.join(", ")}`]);
3144
- }
3145
- if (meta !== void 0 && 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`]);
3146
- out.push(...choiceParamProblems(o, c["params"], at));
3147
- if (o.members === void 0) {
3148
- if (c["members"] !== void 0) out.push(["members", `${at} is not a meta option, but the config gives members`]);
3149
- continue;
3150
- }
3151
- if (member) {
3152
- out.push(["depth", `a member has the meta option ${s.name}.${o.id}. The depth of a meta config is 1`]);
3153
- continue;
3154
- }
3155
- out.push(...memberProblems(partOf(space, s.name).space, o.members, c["members"], at, memberShapes(o.members, shapes)));
3156
- }
3157
- for (const c of space.constraints ?? []) if (!holds(c, chosen)) out.push(["constraint", `the config breaks the constraint ${describe(c)}`]);
3158
- return out;
3159
- }
3160
- /** This function gives the problems of the members of a meta option. `part` is the space of the members. */
3161
- function memberProblems(part, rule, members, at, shapes) {
3162
- if (!Array.isArray(members)) return [["members", `${at} is a meta option without a list of members`]];
3163
- const out = [];
3164
- if (members.length < rule.min || members.length > rule.max) out.push(["members", `${at} has ${members.length} members, not ${rule.min} to ${rule.max}`]);
3165
- const ids = /* @__PURE__ */ new Map();
3166
- members.forEach((m, k) => {
3167
- const inner = configProblems(part, m, true, shapes);
3168
- for (const [claim, detail] of inner) out.push([claim, `the member ${k} of ${at}: ${detail}`]);
3169
- if (inner.length > 0) return;
3170
- const id = idOf(canonicalOf(part, m, true));
3171
- if (ids.has(id)) out.push(["duplicate", `the members ${ids.get(id)} and ${k} of ${at} are the same config ${id}`]);
3172
- else ids.set(id, k);
3173
- });
3174
- if (rule.pool !== void 0 && out.length === 0) {
3175
- const key = memberKey(part, rule, members);
3176
- if (!rule.pool.some((entry) => memberKey(part, rule, entry) === key)) out.push(["pool", `${at} has a member list that is not in its pool of ${rule.pool.length} ${rule.pool.length === 1 ? "list" : "lists"}`]);
3177
- }
3178
- return out;
3179
- }
3180
- /** This function gives the key of a good member list: the `configId` of each member, sorted when the rule is not ordered. */
3181
- function memberKey(part, rule, members) {
3182
- const ids = members.map((m) => idOf(canonicalOf(part, m, true)));
3183
- if (!rule.ordered) ids.sort();
3184
- return ids.join(",");
3185
- }
3186
- /** This function gives the problems of the pool of a meta option of a good space. `part` is the space of the members. */
3187
- function poolProblems(part, rule, at) {
3188
- const out = [];
3189
- const keys = /* @__PURE__ */ new Map();
3190
- const plain = {
3191
- min: rule.min,
3192
- max: rule.max,
3193
- ordered: rule.ordered
3194
- };
3195
- (rule.pool ?? []).forEach((entry, j) => {
3196
- const inner = memberProblems(part, plain, entry, `the pool entry ${j} of ${at}`);
3197
- out.push(...inner);
3198
- if (inner.length > 0) return;
3199
- const key = memberKey(part, rule, entry);
3200
- if (keys.has(key)) out.push(["duplicate", `the pool entries ${keys.get(key)} and ${j} of ${at} have the same members`]);
3201
- else keys.set(key, j);
3202
- });
3203
- return out;
3204
- }
3205
- /** 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. */
3206
- const fits = (part, entry) => entry.every((m) => configProblems(part, m, true).length === 0);
3207
- const toBreaks = (problems, inputs = []) => problems.map(([claim, detail]) => ({
3208
- claim,
3209
- detail,
3210
- inputs
3211
- }));
3212
- /**
3213
- * This function checks one config of a space. It gives one break for each problem. An empty list tells that the config is good.
3214
- * The `claim` of a break is the kind of the problem, for example `missing`, `unknown`, `inactive`, `param`, `constraint`, `members` or `depth`.
3215
- *
3216
- * A member list that is not an entry of the `pool` of its option gives the claim `pool`.
3217
- * 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.
3218
- * A member of an option with `view: "bounds"` gets the check with the kind `rect`.
3219
- */
3220
- function checkConfig(space, config, options = {}) {
3221
- return toBreaks(configProblems(space, config, false, options.shapes));
3222
- }
3223
- /**
3224
- * This function checks a space. It gives one break for each problem. An empty list tells that the space is good.
3225
- * It finds duplicate names, empty ranges, defaults out of range, enums without values, bad log scales, unknown names and bad named configs.
3226
- * It also checks each entry of a `pool`: the count of its members, each member and a repeated entry.
3227
- * The `inputs` of a break of a named config have the name of the config.
3228
- */
3229
- function checkSpace(space) {
3230
- if (!isObject(space) || !Array.isArray(space.stages)) return toBreaks([["schema", "the space is not an object with stages"]]);
3231
- const out = [];
3232
- if (space.schema !== "strategy-space/1") out.push(["schema", `the schema is ${show(space.schema)}, not ${STRATEGY_SPACE_SCHEMA}`]);
3233
- if (typeof space.engine !== "string" || space.engine === "") out.push(["schema", "the space has no engine name"]);
3234
- if (typeof space.version !== "string") out.push(["schema", "the space has no version"]);
3235
- const names = space.stages.map((s) => s.name);
3236
- space.stages.forEach((s, i) => {
3237
- if (names.indexOf(s.name) !== i) out.push(["duplicate", `the space has the stage ${s.name} two times`]);
3238
- const options = Array.isArray(s.options) ? s.options : [];
3239
- if (options.length === 0) {
3240
- out.push(["options", `the stage ${s.name} has no options`]);
3241
- return;
3242
- }
3243
- const ids = options.map((o) => o.id);
3244
- options.forEach((o, j) => {
3245
- if (ids.indexOf(o.id) !== j) out.push(["duplicate", `the stage ${s.name} has the option ${o.id} two times`]);
3246
- out.push(...optionProblems(s, o));
3247
- });
3248
- if (!s.optional && options.every((o) => o.members !== void 0)) out.push(["meta", `the stage ${s.name} is not optional and has only meta options, so no base config exists`]);
3249
- });
3250
- const known = (ref, at) => {
3251
- const s = space.stages.find((x) => x.name === ref?.stage);
3252
- if (s === void 0) out.push(["unknown", `${at} has the unknown stage ${ref?.stage}`]);
3253
- else if (ref.option === null ? !s.optional : !s.options.some((o) => o.id === ref.option)) out.push(["unknown", `${at} has the unknown option ${s.name}=${ref.option ?? "null"}`]);
3254
- };
3255
- (space.constraints ?? []).forEach((c, k) => {
3256
- known(c.if, `the constraint ${k}`);
3257
- known("not" in c.then ? c.then.not : c.then, `the constraint ${k}`);
3258
- });
3259
- for (const part of space.parts ?? []) for (const b of checkSpace(part)) out.push([b.claim, `the part ${part.engine}: ${b.detail}`]);
3260
- if (space.parts !== void 0) {
3261
- 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`]);
3262
- }
3263
- const breaks = toBreaks(out);
3264
- if (breaks.length > 0) return breaks;
3265
- for (const s of space.stages) for (const o of s.options) if (o.members?.pool !== void 0) breaks.push(...toBreaks(poolProblems(partOf(space, s.name).space, o.members, `the option ${s.name}.${o.id}`)));
3266
- if (breaks.length > 0) return breaks;
3267
- for (const [name, config] of Object.entries(space.named ?? {})) breaks.push(...toBreaks(configProblems(space, config, false).map(([c, d]) => [c, `the named config ${name}: ${d}`]), [name]));
3268
- return breaks;
3269
- }
3270
- /** This function gives the canonical form of a config that is known to be good. */
3271
- function canonicalOf(space, config, member) {
3272
- const stages = {};
3273
- for (const s of space.stages) {
3274
- const c = Object.hasOwn(config.stages, s.name) ? config.stages[s.name] : void 0;
3275
- if (c === void 0 || c === null) {
3276
- stages[s.name] = null;
3277
- continue;
3278
- }
3279
- const o = s.options.find((x) => x.id === c.option);
3280
- const given = c.params ?? {};
3281
- const params = {};
3282
- 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);
3283
- if (o.members === void 0 || member) {
3284
- stages[s.name] = {
3285
- option: o.id,
3286
- params
3287
- };
3288
- continue;
3289
- }
3290
- const part = partOf(space, s.name).space;
3291
- const members = (c.members ?? []).map((m) => canonicalOf(part, m, true));
3292
- if (!o.members.ordered) members.sort((a, b) => idOf(a) < idOf(b) ? -1 : idOf(a) > idOf(b) ? 1 : 0);
3293
- stages[s.name] = {
3294
- option: o.id,
3295
- params,
3296
- members
3297
- };
3298
- }
3299
- return {
3300
- space: space.engine,
3301
- stages
3302
- };
3303
- }
3304
- const idOf = (canonical) => sha256Hex(canonicalJson(canonical)).slice(0, 16);
3305
- /**
3306
- * This function gives the canonical form of a config: each stage of the space, the active params only, the defaults, and stable numbers.
3307
- * An unused optional stage is `null`. The members of an unordered meta option are sorted by their `configId`.
3308
- * It throws an `Error` for a config with a break of `checkConfig`.
3309
- */
3310
- function canonicalConfig(space, config) {
3311
- const problems = configProblems(space, config, false);
3312
- if (problems.length > 0) throw new Error(`The config of the space ${space.engine} is not good: ${problems.map((p) => p[1]).join("; ")}.`);
3313
- return canonicalOf(space, config, false);
3314
- }
3315
- /**
3316
- * This function gives the id of a config: the first 16 hex characters of the SHA-256 of `canonicalJson` of `canonicalConfig`.
3317
- * Two spellings of one config get one id. The version of the space is not part of the id.
3318
- */
3319
- function configId(space, config) {
3320
- return idOf(canonicalConfig(space, config));
3321
- }
3322
- /** This function throws an `Error` for a space with a break of `checkSpace`. */
3323
- function assertSpace(space) {
3324
- const breaks = checkSpace(space);
3325
- if (breaks.length > 0) throw new Error(`The space ${String(space?.engine)} is not good: ${breaks.map((b) => b.detail).join("; ")}.`);
3326
- }
3327
- /** This function throws a `RangeError` when a value is not a whole number of `min` or more. */
3328
- function assertWhole(value, name, min) {
3329
- if (!Number.isInteger(value) || value < min) throw new RangeError(`The option ${name} is ${value}, not a whole number of ${min} or more.`);
3330
- }
3331
- /** This function gives the last point of the step grid of a numeric param. */
3332
- function lastPoint(p) {
3333
- const min = p.min;
3334
- const step = p.step ?? (p.kind === "int" ? 1 : void 0);
3335
- if (step === void 0) return p.max;
3336
- return min + Math.floor((p.max - min) / step + 1e-9) * step;
3337
- }
3338
- /** This function moves a value of a numeric param onto its step and into its range. */
3339
- function snap(p, x, digits) {
3340
- const min = p.min;
3341
- const step = p.step ?? (p.kind === "int" ? 1 : void 0);
3342
- let v = step === void 0 ? x : min + Math.round((x - min) / step) * step;
3343
- v = Math.min(lastPoint(p), Math.max(min, v));
3344
- return p.kind === "int" ? zero(Math.round(v)) : Math.min(p.max, Math.max(min, realForm(v, digits)));
3345
- }
3346
- /** This function gives the point at the fraction `t` of the range of a numeric param, on its scale. */
3347
- function at01(p, t) {
3348
- const min = p.min;
3349
- const max = p.max;
3350
- if (p.scale === "log") return Math.exp(Math.log(min) + t * (Math.log(max) - Math.log(min)));
3351
- return min + t * (max - min);
3352
- }
3353
- /**
3354
- * This function gives the grid values of one param, in increasing order. An `enum` gives its values, and a `bool` gives `false` and `true`.
3355
- * 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.
3356
- */
3357
- function paramLevels(param, levels) {
3358
- assertWhole(levels, "levels", 1);
3359
- if (param.kind === "bool") return [false, true];
3360
- if (param.kind === "enum") return [...param.values ?? []];
3361
- if (levels === 1 || param.min === param.max) return [normalize(param, param.default)];
3362
- const out = [];
3363
- const steps = param.kind === "int" || param.step !== void 0 ? Math.round((lastPoint(param) - param.min) / (param.step ?? 1)) + 1 : Infinity;
3364
- if (steps <= levels && param.scale !== "log") for (let j = 0; j < steps; j++) out.push(snap(param, param.min + j * (param.step ?? 1), 12));
3365
- else for (let j = 0; j < levels; j++) out.push(snap(param, at01(param, j / (levels - 1)), 12));
3366
- return [...new Set(out)];
3367
- }
3368
- /** This function tells if a later param of the list reads a param in its `when`. */
3369
- const readLater = (params, i) => params.slice(i + 1).some((q) => q.when?.param === params[i].name);
3370
- /** This function gives the count of the grid assignments of the params of an option, with only the active params. */
3371
- function countParams(params, levels, i = 0, values = {}) {
3372
- if (i === params.length) return 1n;
3373
- const p = params[i];
3374
- if (!isActive(p, values)) return countParams(params, levels, i + 1, values);
3375
- const lv = paramLevels(p, levels);
3376
- if (!readLater(params, i)) return BigInt(lv.length) * countParams(params, levels, i + 1, values);
3377
- let sum = 0n;
3378
- for (const v of lv) sum += countParams(params, levels, i + 1, {
3379
- ...values,
3380
- [p.name]: v
3381
- });
3382
- return sum;
3383
- }
3384
- /** This function gives the grid assignments of the params of an option, in a stable order. */
3385
- function* gridParams(params, levels, i = 0, values = {}) {
3386
- if (i === params.length) {
3387
- yield { ...values };
3388
- return;
3389
- }
3390
- const p = params[i];
3391
- if (!isActive(p, values)) {
3392
- yield* gridParams(params, levels, i + 1, values);
3393
- return;
3394
- }
3395
- for (const v of paramLevels(p, levels)) yield* gridParams(params, levels, i + 1, {
3396
- ...values,
3397
- [p.name]: v
3398
- });
3399
- }
3400
- const optionIds = (choices) => new Map([...choices].map(([k, o]) => [k, o?.id ?? null]));
3401
- const keeps = (space, choices) => (space.constraints ?? []).every((c) => holds(c, optionIds(choices)));
3035
+ /** This function gives the known shape kinds of a check: the list of the caller, or `SHAPE_KIND_IDS`. */
3036
+ const withKinds = (options) => ({
3037
+ kinds: SHAPE_KIND_IDS,
3038
+ ...options
3039
+ });
3402
3040
  /**
3403
- * This function gives the constraints of a space for each stage: a constraint goes to the last stage that it names.
3404
- * The last list holds each constraint that names a stage outside the space, so a walk examines it at the end.
3041
+ * This function checks a space with `checkSpace` of `@mark1russell7/strategy-space`.
3042
+ * Without `kinds`, a shape kind of a `supports` that is not in `SHAPE_KIND_IDS` gives the claim `shape`.
3405
3043
  */
3406
- function constraintsByStage(space) {
3407
- const place = new Map(space.stages.map((s, i) => [s.name, i]));
3408
- const lists = Array.from({ length: space.stages.length + 1 }, () => []);
3409
- for (const c of space.constraints ?? []) {
3410
- const named = [c.if.stage, "not" in c.then ? c.then.not.stage : c.then.stage];
3411
- lists[Math.max(...named.map((name) => place.get(name) ?? space.stages.length))].push(c);
3412
- }
3413
- return lists;
3414
- }
3415
- /** This function gives the count of the member lists of a meta option without a pool from `base` base configs, or `null` above `limit`. */
3416
- function memberLists(base, rule, limit) {
3417
- let sum = 0n;
3418
- for (let m = rule.min; m <= rule.max; m++) {
3419
- let n = 1n;
3420
- for (let k = 0; k < m; k++) {
3421
- n = n * (base - BigInt(k)) / (rule.ordered ? 1n : BigInt(k + 1));
3422
- if (n <= 0n) break;
3423
- }
3424
- if (n <= 0n) break;
3425
- sum += n;
3426
- if (sum > limit) return null;
3427
- }
3428
- return sum;
3044
+ function checkSpace(space, kindOptions = {}) {
3045
+ return checkSpace$1(space, withKinds(kindOptions));
3429
3046
  }
3430
- /** This function multiplies two counts. A `null` count or a product above `limit` gives `null`. */
3431
- const times = (a, b, limit) => a === null || b === null ? null : a * b > limit ? null : a * b;
3432
3047
  /**
3433
- * This function gives the combinations of options of a space and their grid counts.
3434
- * A product space joins the combinations of its parts. Each combination keeps the constraints.
3435
- */
3436
- function combos(space, levels, meta, limit) {
3437
- if (space.parts !== void 0 && space.parts.length > 0) {
3438
- let acc = [{
3439
- choices: /* @__PURE__ */ new Map(),
3440
- base: true,
3441
- weight: 1n
3442
- }];
3443
- for (const part of space.parts) {
3444
- const head = `${part.engine}.`;
3445
- const own = combos(part, levels, meta, limit);
3446
- const next = [];
3447
- for (const a of acc) for (const b of own) {
3448
- const choices = new Map(a.choices);
3449
- for (const [k, o] of b.choices) choices.set(head + k, o);
3450
- const base = a.base && b.base;
3451
- next.push({
3452
- choices,
3453
- base,
3454
- weight: base ? a.weight * b.weight : times(a.weight, b.weight, limit)
3455
- });
3456
- }
3457
- acc = next;
3458
- }
3459
- return acc.filter((c) => keeps(space, c.choices));
3460
- }
3461
- const counts = /* @__PURE__ */ new Map();
3462
- const countOf = (o) => {
3463
- if (!counts.has(o)) counts.set(o, countParams(o.params, levels));
3464
- return counts.get(o);
3465
- };
3466
- const out = [];
3467
- const stages = space.stages;
3468
- const checks = constraintsByStage(space);
3469
- const ids = /* @__PURE__ */ new Map();
3470
- const walk = (i, choices, weight) => {
3471
- if (i === stages.length) {
3472
- if (checks[i].every((c) => holds(c, ids))) out.push({
3473
- choices: new Map(choices),
3474
- base: true,
3475
- weight
3476
- });
3477
- return;
3478
- }
3479
- const s = stages[i];
3480
- const list = s.options.filter((o) => o.members === void 0);
3481
- if (s.optional) list.push(null);
3482
- for (const o of list) {
3483
- choices.set(s.name, o);
3484
- ids.set(s.name, o?.id ?? null);
3485
- if (checks[i].every((c) => holds(c, ids))) walk(i + 1, choices, o === null ? weight : weight * countOf(o));
3486
- }
3487
- choices.delete(s.name);
3488
- ids.delete(s.name);
3489
- };
3490
- walk(0, /* @__PURE__ */ new Map(), 1n);
3491
- if (!meta) return out;
3492
- const base = out.reduce((sum, c) => sum + c.weight, 0n);
3493
- for (const s of stages) for (const o of s.options) {
3494
- if (o.members === void 0) continue;
3495
- const choices = new Map(stages.map((x) => [x.name, x === s ? o : null]));
3496
- const own = memberSpaces.get(o);
3497
- const from = own === void 0 ? base : baseCount(own, levels, limit);
3498
- const lists = o.members.pool === void 0 ? memberLists(from, o.members, limit) : BigInt(o.members.pool.length);
3499
- if (keeps(space, choices)) out.push({
3500
- choices,
3501
- base: false,
3502
- weight: times(countOf(o), lists, limit)
3503
- });
3504
- }
3505
- return out;
3506
- }
3507
- /**
3508
- * This function gives the count of the grid points of a space, with `levels` levels for each numeric param.
3509
- * It counts only the active params and the combinations that keep the constraints. It gives the meta configs apart.
3510
- * A meta option with a `pool` counts each entry of the pool one time.
3511
- * With `shapes`, it counts only the options that support each kind of the list.
3048
+ * This function counts the grid points of a space with `spaceSize` of `@mark1russell7/strategy-space`.
3049
+ * Without `kinds`, a shape kind that is not in `SHAPE_KIND_IDS` causes an error.
3512
3050
  */
3513
3051
  function spaceSize(space, options) {
3514
- assertSpace(space);
3515
- assertWhole(options.levels, "levels", 1);
3516
- assertShapes(options.shapes);
3517
- return sizeOf(restrict(space, options.shapes), options.levels, options.maxMeta ?? 10n ** 18n);
3518
- }
3519
- /**
3520
- * This function gives the space with only the options that support each shape kind of `shapes`. Without `shapes`, it gives the same space.
3521
- * A stage can lose all of its options. Then the space has no config with that stage.
3522
- * A pool keeps only the entries whose members fit the smaller space. A meta option without such an entry goes out.
3523
- *
3524
- * The members of an option with `view: "bounds"` come from the space for the kinds of `memberShapes`. `memberSpaces` keeps that space.
3525
- */
3526
- function restrict(space, shapes) {
3527
- if (shapes === void 0) return space;
3528
- const kept = {
3529
- ...space,
3530
- stages: space.stages.map((s) => ({
3531
- ...s,
3532
- options: s.options.filter((o) => supportsShapes(o, shapes))
3533
- })),
3534
- ...space.parts === void 0 ? {} : { parts: space.parts.map((p) => restrict(p, shapes)) }
3535
- };
3536
- const withPool = (s, o) => {
3537
- if (o.members === void 0) return [o];
3538
- const inner = memberShapes(o.members, shapes);
3539
- const own = sameKinds(inner, shapes) ? void 0 : restrict(partOf(space, s.name).space, inner);
3540
- const mark = (option) => {
3541
- if (own !== void 0) memberSpaces.set(option, own);
3542
- return [option];
3543
- };
3544
- if (o.members.pool === void 0) return own === void 0 ? [o] : mark({ ...o });
3545
- const part = own ?? partOf(kept, s.name).space;
3546
- const pool = o.members.pool.filter((entry) => fits(part, entry));
3547
- return pool.length === 0 ? [] : mark({
3548
- ...o,
3549
- members: {
3550
- ...o.members,
3551
- pool
3552
- }
3553
- });
3554
- };
3555
- return {
3556
- ...kept,
3557
- stages: kept.stages.map((s) => ({
3558
- ...s,
3559
- options: s.options.flatMap((o) => withPool(s, o))
3560
- }))
3561
- };
3562
- }
3563
- /** 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. */
3564
- const memberSpaces = /* @__PURE__ */ new WeakMap();
3565
- /**
3566
- * 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.
3567
- * A different meta option has one when its members have a base config. `restrict` keeps only the pool entries that fit.
3568
- */
3569
- const hasMembers = (space, stage, o) => o.members === void 0 || o.members.max === 0 || o.members.pool !== void 0 || combos(memberSpaces.get(o) ?? partOf(space, stage).space, 1, false, 0n).length > 0;
3570
- /** 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. */
3571
- const hasConfig = (space, meta) => combos(space, 1, meta, 0n).some((c) => c.base || [...c.choices].every(([stage, o]) => o === null || hasMembers(space, stage, o)));
3572
- /** 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. */
3573
- function noSample(space, kept, shapes, meta) {
3574
- const list = (names, one, more) => names.length === 1 ? `${one} ${names[0]}` : `${more} ${names.join(", ")}`;
3575
- const empty = kept.stages.filter((s) => !s.optional && !s.options.some((o) => meta || o.members === void 0)).map((s) => s.name);
3576
- const removed = !meta ? [] : space.stages.flatMap((s) => s.options.filter((o) => o.members !== void 0 && o.members.view !== "bounds" && supportsShapes(o, shapes)).filter((o) => {
3577
- const own = kept.stages.find((x) => x.name === s.name)?.options.find((x) => x.id === o.id);
3578
- return own === void 0 || !hasMembers(kept, s.name, own);
3579
- }).map((o) => `${s.name}.${o.id}`));
3580
- let text = `The space ${space.engine} has no config for a sample with the shape kinds ${shapes.join(", ")}.`;
3581
- if (empty.length > 0) text += ` ${list(empty, "The stage", "The stages")} ${empty.length === 1 ? "has" : "have"} no option for these kinds.`;
3582
- if (removed.length > 0) 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.`;
3583
- if (empty.length === 0 && removed.length === 0) text += " The constraints remove each config.";
3584
- return new RangeError(text);
3585
- }
3586
- /** This function gives a constraint in words, for the reason of an error. */
3587
- function constraintText(c) {
3588
- const ref = (r) => `${r.stage} ${r.option === null ? "has no option" : `is ${r.option}`}`;
3589
- return "not" in c.then ? `if ${ref(c.if)}, then not ${ref(c.then.not)}` : `if ${ref(c.if)}, then ${ref(c.then)}`;
3590
- }
3591
- /**
3592
- * 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.
3593
- * A meta option without `meta: "sample"` is bad, and so are two fixed options that a constraint forbids.
3594
- */
3595
- function assertFixed(space, fixed, meta) {
3596
- for (const [stage, id] of Object.entries(fixed)) {
3597
- const s = space.stages.find((x) => x.name === stage);
3598
- if (s === void 0) throw new RangeError(`The option fixed names the stage ${stage}, and the space ${space.engine} has no such stage.`);
3599
- const o = s.options.find((x) => x.id === id);
3600
- if (o === void 0) throw new RangeError(`The option fixed names the option ${String(id)} of the stage ${stage}, and the stage has no such option.`);
3601
- if (o.members !== void 0 && !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".`);
3602
- }
3603
- const ids = new Map(Object.entries(fixed));
3604
- const other = (c) => "not" in c.then ? c.then.not.stage : c.then.stage;
3605
- const broken = (space.constraints ?? []).filter((c) => ids.has(c.if.stage) && ids.has(other(c)) && !holds(c, ids));
3606
- if (broken.length > 0) {
3607
- const names = Object.entries(fixed).map(([stage, id]) => `${stage}.${id}`);
3608
- throw new RangeError(`The constraints of the space ${space.engine} forbid the fixed options ${names.join(", ")}. The broken constraints: ${broken.map(constraintText).join("; ")}.`);
3609
- }
3610
- }
3611
- /**
3612
- * 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.
3613
- * 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.
3614
- */
3615
- function fixStages(space, kept, fixed, shapes) {
3616
- const prefix = prefixes(kept);
3617
- const parts = new Set(Object.keys(fixed).map((stage) => prefix.get(stage)));
3618
- const stages = kept.stages.map((s) => {
3619
- const id = fixed[s.name];
3620
- if (id === void 0) return parts.has(prefix.get(s.name)) ? {
3621
- ...s,
3622
- options: s.options.filter((o) => o.members === void 0)
3623
- } : s;
3624
- const options = s.options.filter((o) => o.id === id).map((o) => o.members === void 0 ? o : withMemberSpace(o, memberSpaces.get(o) ?? partOf(kept, s.name).space));
3625
- 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(", ")}.`);
3626
- return {
3627
- ...s,
3628
- options,
3629
- optional: false
3630
- };
3631
- });
3632
- return {
3633
- ...kept,
3634
- stages
3635
- };
3636
- }
3637
- /** This function gives a copy of a meta option whose members come from `members`. */
3638
- function withMemberSpace(o, members) {
3639
- const copy = { ...o };
3640
- memberSpaces.set(copy, members);
3641
- return copy;
3642
- }
3643
- /** 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. */
3644
- function noFixedSample(space, fixed) {
3645
- const names = Object.entries(fixed).map(([stage, id]) => `${stage}.${id}`);
3646
- return /* @__PURE__ */ new RangeError(`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.`);
3647
- }
3648
- /** This function gives the count of the base configs of a space that is known to be good. */
3649
- const baseCount = (space, levels, limit) => combos(space, levels, false, limit).reduce((sum, c) => sum + c.weight, 0n);
3650
- /** This function throws a `RangeError` for a list of shape kinds with a kind that is not declared. */
3651
- function assertShapes(shapes) {
3652
- if (shapes === void 0) return;
3653
- if (!Array.isArray(shapes)) throw new RangeError("The option shapes is not a list of shape kinds.");
3654
- for (const k of shapes) if (!isShapeKind(k)) throw new RangeError(`The shape kind ${show(k)} is not one of ${SHAPE_KIND_IDS.join(", ")}.`);
3655
- }
3656
- /** This function gives the count of the grid points of a space that is known to be good. */
3657
- function sizeOf(space, levels, limit) {
3658
- let base = 0n;
3659
- let meta = 0n;
3660
- for (const c of combos(space, levels, true, limit)) if (c.base) base += c.weight;
3661
- else meta = meta === null || c.weight === null || meta + c.weight > limit ? null : meta + c.weight;
3662
- return {
3663
- base,
3664
- meta
3665
- };
3052
+ return spaceSize$1(space, withKinds(options));
3666
3053
  }
3667
- /** This function gives the cartesian product of lists, with the last list as the fastest. */
3668
- function* product(lists, i = 0, acc = []) {
3669
- if (i === lists.length) {
3670
- yield [...acc];
3671
- return;
3672
- }
3673
- for (const x of lists[i]) {
3674
- acc.push(x);
3675
- yield* product(lists, i + 1, acc);
3676
- acc.pop();
3677
- }
3678
- }
3679
- /** This function gives the configs of the grid of a space, without meta options. */
3680
- function gridConfigs(space, levels, limit, shapes) {
3681
- const kept = restrict(space, shapes);
3682
- const size = sizeOf(kept, levels, 0n).base;
3683
- if (size > BigInt(limit)) throw new RangeError(`The grid of the space ${space.engine} has ${size} configs, more than the limit ${limit}.`);
3684
- const out = [];
3685
- for (const c of combos(kept, levels, false, 0n)) {
3686
- const names = [...c.choices.keys()];
3687
- const lists = names.map((k) => {
3688
- const o = c.choices.get(k);
3689
- return o === null ? [null] : [...gridParams(o.params, levels)].map((params) => ({
3690
- option: o.id,
3691
- params
3692
- }));
3693
- });
3694
- for (const row of product(lists)) out.push(canonicalOf(space, {
3695
- space: space.engine,
3696
- stages: Object.fromEntries(names.map((k, i) => [k, row[i]]))
3697
- }, false));
3698
- }
3699
- return out;
3700
- }
3701
- /** This function gives a random order of the numbers from 0 to `n - 1`. */
3702
- function permutation(n, r) {
3703
- const out = Array.from({ length: n }, (_, i) => i);
3704
- for (let i = n - 1; i > 0; i--) {
3705
- const j = Math.floor(r() * (i + 1));
3706
- [out[i], out[j]] = [out[j], out[i]];
3707
- }
3708
- return out;
3709
- }
3710
- /** This function gives the value of a param at the fraction `u` of its range. A sampled real number has 6 significant digits. */
3711
- function sampleValue(p, u) {
3712
- if (p.kind === "bool") return u >= .5;
3713
- if (p.kind === "enum") {
3714
- const values = p.values;
3715
- return values[Math.min(values.length - 1, Math.floor(u * values.length))];
3716
- }
3717
- if (p.min === p.max) return normalize(p, p.min);
3718
- if (p.scale !== "log" && (p.kind === "int" || p.step !== void 0)) {
3719
- const steps = Math.round((lastPoint(p) - p.min) / (p.step ?? 1)) + 1;
3720
- return snap(p, p.min + Math.min(steps - 1, Math.floor(u * steps)) * (p.step ?? 1), 6);
3721
- }
3722
- return snap(p, at01(p, u), 6);
3723
- }
3724
- /** This function gives a seed of 32 bits from a seed and a step name. */
3725
- const subSeed = (seed, step) => Math.floor(stepRandom(seed, step)() * 4294967296);
3726
3054
  /**
3727
- * This function gives a sample of a space: Latin hypercube strata over the options, the params and the member counts.
3728
- * `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.
3729
- */
3730
- function sampleConfigs(space, n, seed, meta, maxTries, canon = space, walk = false, first = /* @__PURE__ */ new Set()) {
3731
- const stages = space.stages;
3732
- const prefix = prefixes(space);
3733
- 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)));
3734
- const lists = stages.map((s) => {
3735
- const list = s.options.filter((o) => meta || o.members === void 0);
3736
- if (s.optional) list.push(null);
3737
- if (list.length === 0 && bounded.has(prefix.get(s.name))) list.push(null);
3738
- 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.`);
3739
- return list;
3740
- });
3741
- const usable = /* @__PURE__ */ new Map();
3742
- const withMembers = (s, o) => {
3743
- if (o === null || o === void 0 || o.members === void 0) return true;
3744
- if (!usable.has(o)) usable.set(o, hasMembers(space, s.name, o));
3745
- return usable.get(o);
3746
- };
3747
- const plan = walk ? walkPlan(stages, lists, space.constraints ?? [], n, first) : null;
3748
- const points = [];
3749
- let tries = 0;
3750
- for (let round = 0; points.length < n; round++) {
3751
- const r = stepRandom(seed, `options:${round}`);
3752
- const picks = walk ? lists.map(() => permutation(n, r)) : [];
3753
- const columns = walk ? [] : lists.map((list) => permutation(n, r).map((p) => list[Math.floor(p * list.length / n)]));
3754
- for (let i = 0; i < n && points.length < n; i++) {
3755
- 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."}`);
3756
- tries++;
3757
- const choices = plan !== null ? walkPoint(plan, picks, i) : new Map(stages.map((s, k) => [s.name, columns[k][i]]));
3758
- const metaPart = /* @__PURE__ */ new Map();
3759
- for (const s of stages) if (choices.get(s.name)?.members !== void 0 && !metaPart.has(prefix.get(s.name))) metaPart.set(prefix.get(s.name), s.name);
3760
- for (const s of stages) {
3761
- const m = metaPart.get(prefix.get(s.name));
3762
- if (m !== void 0 && m !== s.name) choices.set(s.name, null);
3763
- }
3764
- if (stages.every((s) => s.optional === true || choices.get(s.name) !== null || metaPart.has(prefix.get(s.name))) && keeps(space, choices) && stages.every((s) => withMembers(s, choices.get(s.name)))) points.push(choices);
3765
- }
3766
- }
3767
- const values = points.map(() => stages.map(() => ({})));
3768
- const members = points.map(() => stages.map(() => []));
3769
- stages.forEach((s, k) => {
3770
- for (const o of s.options) {
3771
- const users = points.flatMap((c, i) => c.get(s.name) === o ? [i] : []);
3772
- if (users.length === 0) continue;
3773
- for (const p of o.params) {
3774
- const active = users.filter((i) => isActive(p, values[i][k]));
3775
- const r = stepRandom(seed, `param:${s.name}:${o.id}:${p.name}`);
3776
- permutation(active.length, r).forEach((stratum, j) => {
3777
- values[active[j]][k][p.name] = sampleValue(p, (stratum + r()) / active.length);
3778
- });
3779
- }
3780
- if (o.members === void 0 || o.members.max === 0) continue;
3781
- const fixed = o.members.pool;
3782
- if (fixed !== void 0) {
3783
- const r = stepRandom(seed, `pool-entry:${s.name}:${o.id}`);
3784
- permutation(users.length, r).forEach((stratum, j) => {
3785
- members[users[j]][k] = [...fixed[Math.min(fixed.length - 1, Math.floor((stratum + r()) / users.length * fixed.length))]];
3786
- });
3787
- continue;
3788
- }
3789
- const part = memberSpaces.get(o) ?? partOf(space, s.name).space;
3790
- const poolSize = Math.max(n, 4 * o.members.max, 8);
3791
- const seen = /* @__PURE__ */ new Set();
3792
- const pool = sampleConfigs(part, poolSize, subSeed(seed, `pool:${s.name}:${o.id}`), false, Math.max(1e3, 100 * poolSize), part, walk).filter((c) => {
3793
- const id = idOf(c);
3794
- return seen.has(id) ? false : (seen.add(id), true);
3795
- });
3796
- const r = stepRandom(seed, `members:${s.name}:${o.id}`);
3797
- const { min, max } = o.members;
3798
- permutation(users.length, r).forEach((stratum, j) => {
3799
- const count = min + Math.min(max - min, Math.floor((stratum + r()) / users.length * (max - min + 1)));
3800
- 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}.`);
3801
- const picked = permutation(pool.length, r).slice(0, count);
3802
- members[users[j]][k] = picked.map((x) => pool[x]);
3803
- });
3804
- }
3805
- });
3806
- return points.map((choices, i) => {
3807
- const out = {};
3808
- stages.forEach((s, k) => {
3809
- const o = choices.get(s.name);
3810
- out[s.name] = o === null ? null : o.members === void 0 ? {
3811
- option: o.id,
3812
- params: values[i][k]
3813
- } : {
3814
- option: o.id,
3815
- params: values[i][k],
3816
- members: members[i][k]
3817
- };
3818
- });
3819
- return canonicalConfig(canon, {
3820
- space: space.engine,
3821
- stages: out
3822
- });
3823
- });
3824
- }
3825
- /**
3826
- * This function gives configs of a space, in their canonical form. Each config keeps the constraints. The result is deterministic.
3827
- *
3828
- * - 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.
3829
- * - 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.
3830
- * - A sample draws again when a point breaks a constraint. After `maxTries` draws, it throws an `Error`. Two sampled configs can be equal.
3831
- * - 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.
3832
- * - With `shapes`, only the options that support each kind of the list count. Without `shapes`, the result does not change.
3833
- * - A meta option with a `pool` gives only the entries of its pool. With `shapes`, only the entries whose members support each kind count.
3834
- * - A sample draws again when a point chooses a meta option without a member list. `spaceSize` gives such an option 0.
3835
- * - 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.
3836
- * - 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.
3055
+ * This function gives the configs of a grid or a sample with `enumerateSpace` of `@mark1russell7/strategy-space`.
3056
+ * Without `kinds`, a shape kind that is not in `SHAPE_KIND_IDS` causes an error.
3837
3057
  */
3838
3058
  function enumerateSpace(space, options) {
3839
- assertSpace(space);
3840
- assertShapes(options.shapes);
3841
- if (options.mode === "grid") {
3842
- assertWhole(options.levels, "levels", 1);
3843
- return gridConfigs(space, options.levels, options.limit ?? 1e5, options.shapes);
3844
- }
3845
- if (options.mode !== "sample") throw new RangeError(`The mode ${String(options.mode)} is not grid or sample.`);
3846
- assertWhole(options.n, "n", 0);
3847
- if (!Number.isInteger(options.seed)) throw new RangeError(`The seed ${options.seed} is not a whole number.`);
3848
- const meta = options.meta ?? "skip";
3849
- if (meta !== "skip" && meta !== "sample") throw new RangeError(`The option meta is ${String(meta)}, not skip or sample.`);
3850
- const draw = options.draw ?? "reject";
3851
- if (draw !== "reject" && draw !== "walk") throw new RangeError(`The option draw is ${String(draw)}, not reject or walk.`);
3852
- const fixed = options.fixed;
3853
- if (fixed !== void 0) assertFixed(space, fixed, meta === "sample");
3854
- if (options.n === 0) return [];
3855
- const kept = restrict(space, options.shapes);
3856
- const drawn = fixed === void 0 ? kept : fixStages(space, kept, fixed, options.shapes);
3857
- try {
3858
- return sampleConfigs(drawn, options.n, options.seed, meta === "sample", options.maxTries ?? Math.max(1e3, 100 * options.n), space, draw === "walk", new Set(Object.keys(fixed ?? {})));
3859
- } catch (error) {
3860
- if (options.shapes !== void 0 && !hasConfig(kept, meta === "sample")) throw noSample(space, kept, options.shapes, meta === "sample");
3861
- if (fixed !== void 0 && !hasConfig(drawn, meta === "sample")) throw noFixedSample(space, fixed);
3862
- throw error;
3863
- }
3864
- }
3865
- /**
3866
- * 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.
3867
- * A space accepts a kind when it has at least one config without a meta option on that kind.
3868
- */
3869
- function spaceShapeKinds(space) {
3870
- assertSpace(space);
3871
- return SHAPE_KIND_IDS.filter((k) => sizeOf(restrict(space, [k]), 1, 0n).base > 0n);
3872
- }
3873
- /**
3874
- * This function joins configs of the parts of a product space into one config of the space `space`.
3875
- * The name of each stage gets the prefix `<space of the part>.`. The members of a meta option do not change.
3876
- */
3877
- function joinConfigs(space, parts) {
3878
- const stages = {};
3879
- for (const part of parts) for (const [k, c] of Object.entries(part.stages)) stages[`${part.space}.${k}`] = c;
3880
- return {
3881
- space,
3882
- stages
3883
- };
3884
- }
3885
- /** This function gives the config of the part `engine` of a joint config. It throws a `RangeError` when no stage has the prefix `<engine>.`. */
3886
- function splitConfig(config, engine) {
3887
- const head = `${engine}.`;
3888
- const entries = Object.entries(config.stages).filter(([k]) => k.startsWith(head));
3889
- if (entries.length === 0) throw new RangeError(`The config of the space ${config.space} has no stage of the part ${engine}.`);
3890
- return {
3891
- space: engine,
3892
- stages: Object.fromEntries(entries.map(([k, c]) => [k.slice(head.length), c]))
3893
- };
3894
- }
3895
- /**
3896
- * 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>.`.
3897
- * 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.
3898
- */
3899
- function productSpace(a, b, name) {
3900
- if (a.engine === b.engine) throw new RangeError(`The two spaces have the same engine ${a.engine}.`);
3901
- if (name === "") throw new RangeError("The product space has no name.");
3902
- const stagesOf = (s) => s.stages.map((x) => ({
3903
- ...x,
3904
- name: `${s.engine}.${x.name}`
3905
- }));
3906
- const ref = (s, r) => ({
3907
- stage: `${s.engine}.${r.stage}`,
3908
- option: r.option
3909
- });
3910
- const constraintsOf = (s) => (s.constraints ?? []).map((c) => ({
3911
- if: ref(s, c.if),
3912
- then: "not" in c.then ? { not: ref(s, c.then.not) } : ref(s, c.then)
3913
- }));
3914
- const named = {};
3915
- 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]);
3916
- const constraints = [...constraintsOf(a), ...constraintsOf(b)];
3917
- return {
3918
- schema: STRATEGY_SPACE_SCHEMA,
3919
- engine: name,
3920
- version: `${a.engine}@${a.version}+${b.engine}@${b.version}`,
3921
- stages: [...stagesOf(a), ...stagesOf(b)],
3922
- ...constraints.length > 0 ? { constraints } : {},
3923
- ...Object.keys(named).length > 0 ? { named } : {},
3924
- parts: [a, b]
3925
- };
3926
- }
3927
- // src/strategy-options.ts
3928
- /** The number of values of a sweep on a range when the call and the declaration give no number. */
3929
- const SWEEP_COUNT = 5;
3930
- /** This function gives the declarations of a strategy as a record. A strategy without a schema gives an empty record. */
3931
- function schemaOf(strategy) {
3932
- return strategy.schema ?? {};
3933
- }
3934
- /** This function gives the declared options of a strategy, in the order of its schema, with the effective default of each one. */
3935
- function listOptions(strategy) {
3936
- const defaults = optionDefaults(strategy);
3937
- return Object.entries(schemaOf(strategy)).map(([key, declaration]) => ({
3938
- key,
3939
- declaration,
3940
- value: defaults[key]
3941
- }));
3059
+ return enumerateSpace$1(space, withKinds(options));
3942
3060
  }
3943
3061
  /**
3944
- * This function gives the effective default of each declared option: the value of `defaults`, else the `default` of the declaration.
3945
- * An option without either value stays out. The strategy gives the same output with this object as with no options.
3062
+ * This function gives the shape kinds that a space accepts, with `spaceShapeKinds` of `@mark1russell7/strategy-space`.
3063
+ * Without `kinds`, it examines the kinds of `SHAPE_KIND_IDS`, in their order.
3946
3064
  */
3947
- function optionDefaults(strategy) {
3948
- const out = {};
3949
- const defaults = strategy.defaults;
3950
- for (const [key, declaration] of Object.entries(schemaOf(strategy))) if (key in defaults) out[key] = defaults[key];
3951
- else if (declaration.default !== void 0) out[key] = declaration.default;
3952
- for (const key of Object.keys(defaults)) if (!(key in out)) out[key] = defaults[key];
3953
- return out;
3954
- }
3955
- /** This function gives `true` if the number is one of the special values of the declaration. */
3956
- const isSpecial = (d, v) => (d.special ?? []).some((s) => Object.is(s, v) || s === v);
3957
- /** This function gives the problem of one value against its declaration, or `undefined` when the value fits. */
3958
- function optionIssue(key, value, d) {
3959
- const issue = (problem, message) => ({
3960
- key,
3961
- value,
3962
- problem,
3963
- message
3964
- });
3965
- if (value === void 0) return void 0;
3966
- switch (d.type) {
3967
- case "number":
3968
- case "integer":
3969
- if (typeof value !== "number" || Number.isNaN(value)) return issue("type", `The option "${key}" takes a number.`);
3970
- if (isSpecial(d, value)) return void 0;
3971
- if (d.values !== void 0 && !d.values.includes(value)) return issue("value", `The option "${key}" takes ${d.values.join(", ")}, not ${value}.`);
3972
- if (value < d.min || value > d.max) return issue("range", `The option "${key}" is ${value}, out of the range ${d.min} to ${d.max}.`);
3973
- if (d.type === "integer" && !Number.isInteger(value)) return issue("integer", `The option "${key}" takes a whole number, not ${value}.`);
3974
- return;
3975
- case "boolean": return typeof value === "boolean" ? void 0 : issue("type", `The option "${key}" takes true or false.`);
3976
- case "enum":
3977
- if (d.custom === "function" && typeof value === "function") return void 0;
3978
- return d.values.includes(value) ? void 0 : issue("value", `The option "${key}" takes ${d.values.join(", ")}, not ${String(value)}.`);
3979
- case "function": return typeof value === "function" ? void 0 : issue("type", `The option "${key}" takes a function.`);
3980
- case "list": return Array.isArray(value) ? void 0 : issue("type", `The option "${key}" takes a list.`);
3981
- default: return typeof value === "object" && value !== null ? void 0 : issue("type", `The option "${key}" takes an object.`);
3982
- }
3983
- }
3984
- /**
3985
- * This function examines option values against the schema of a strategy. It gives one issue for each key without a declaration.
3986
- * It also gives one issue for each value of the wrong type, out of the range, not whole or not one of the values.
3987
- * It changes no value.
3988
- * A strategy without a schema gives no issue.
3989
- */
3990
- function checkOptions(strategy, options) {
3991
- if (strategy.schema === void 0) return [];
3992
- const schema = schemaOf(strategy);
3993
- const out = [];
3994
- for (const [key, value] of Object.entries(options)) {
3995
- const d = schema[key];
3996
- const issue = d ? optionIssue(key, value, d) : {
3997
- key,
3998
- value,
3999
- problem: "unknown",
4000
- message: `The strategy "${strategy.name}" has no option "${key}".`
4001
- };
4002
- if (issue) out.push(issue);
4003
- }
4004
- return out;
4005
- }
4006
- /**
4007
- * This function moves each number option into the range of its declaration, for a control. An integer option gets the nearest whole number.
4008
- * An option with a list of `values` gets the nearest value of the list. A special value stays. The function keeps each other value as it is. `checkOptions` reports the values that this function cannot correct.
4009
- */
4010
- function clampOptions(strategy, options) {
4011
- const schema = schemaOf(strategy);
4012
- const out = { ...options };
4013
- for (const [key, value] of Object.entries(options)) {
4014
- const d = schema[key];
4015
- if (!d || d.type !== "number" && d.type !== "integer" || typeof value !== "number" || Number.isNaN(value) || isSpecial(d, value)) continue;
4016
- if (d.values !== void 0 && d.values.length > 0) {
4017
- out[key] = d.values.reduce((best, v) => Math.abs(v - value) < Math.abs(best - value) ? v : best);
4018
- continue;
4019
- }
4020
- const v = Math.min(d.max, Math.max(d.min, value));
4021
- out[key] = d.type === "integer" ? Math.min(d.max, Math.max(d.min, Math.round(v))) : v;
4022
- }
4023
- return out;
4024
- }
4025
- /** This function gives `count` values from `min` to `max` on the scale, on the grain of the step, without repeats. */
4026
- function rangeValues(d, count) {
4027
- const n = Math.max(1, Math.floor(count));
4028
- const log = d.scale === "log" && d.min > 0;
4029
- const at = (t) => log ? d.min * (d.max / d.min) ** t : d.min + (d.max - d.min) * t;
4030
- const step = d.step ?? (d.type === "integer" ? 1 : void 0);
4031
- const snap = (v) => {
4032
- const s = step === void 0 ? v : d.min + Math.round((v - d.min) / step) * step;
4033
- const r = Number(s.toPrecision(12));
4034
- return Math.min(d.max, Math.max(d.min, d.type === "integer" ? Math.round(r) : r));
4035
- };
4036
- const out = [];
4037
- for (let i = 0; i < n; i++) {
4038
- const v = snap(at(n === 1 ? 0 : i / (n - 1)));
4039
- if (!out.includes(v)) out.push(v);
4040
- }
4041
- return out;
4042
- }
4043
- /**
4044
- * This function gives the values of a sweep of one option declaration.
4045
- * A number option gives its `marks`, or its list of `values`, or `count` values on its range and its scale. A boolean gives `false` and `true`. An enum gives its values.
4046
- * An option of another type has no sweep, so the function throws an error.
4047
- */
4048
- function sweepValues(declaration, options = {}) {
4049
- switch (declaration.type) {
4050
- case "number":
4051
- case "integer": {
4052
- if (options.count === void 0 && declaration.marks !== void 0) return [...declaration.marks];
4053
- if (declaration.values !== void 0) return [...declaration.values];
4054
- const values = rangeValues(declaration, options.count ?? SWEEP_COUNT);
4055
- return options.special ? [...values, ...(declaration.special ?? []).filter((s) => !values.includes(s))] : values;
4056
- }
4057
- case "boolean": return [false, true];
4058
- case "enum": return [...declaration.values];
4059
- default: throw new Error(`An option of the type "${declaration.type}" has no sweep. A sweep takes a number, an integer, a boolean or an enum.`);
4060
- }
4061
- }
4062
- /** This function gives the declaration of one option of a strategy. When the strategy has no such declaration, the function throws an error. */
4063
- function declarationOf(strategy, key) {
4064
- const d = schemaOf(strategy)[key];
4065
- if (!d) throw new Error(`The strategy "${strategy.name}" has no declaration of the option "${key}".`);
4066
- return d;
4067
- }
4068
- /**
4069
- * This function gives the settings of a sweep of one option of a strategy, from its declaration only.
4070
- * The name of each setting is the key and the value, for example `stretch 1.5`.
4071
- */
4072
- function sweepOf(strategy, key, options = {}) {
4073
- return sweepValues(declarationOf(strategy, key), options).map((value) => ({
4074
- name: `${key} ${String(value)}`,
4075
- options: { [key]: value }
4076
- }));
4077
- }
4078
- /**
4079
- * This function gives the settings of a grid of options: each combination of the values of the sweeps of the keys.
4080
- * The name of a setting joins the names of its values with commas, in the order of the keys.
4081
- */
4082
- function sweepGrid(strategy, keys, options = {}) {
4083
- let out = [{
4084
- name: "",
4085
- options: {}
4086
- }];
4087
- for (const key of keys) {
4088
- const sweep = sweepOf(strategy, key, options);
4089
- out = out.flatMap((s) => sweep.map((t) => ({
4090
- name: s.name === "" ? t.name : `${s.name}, ${t.name}`,
4091
- options: {
4092
- ...s.options,
4093
- ...t.options
4094
- }
4095
- })));
4096
- }
4097
- return keys.length === 0 ? [] : out;
4098
- }
4099
- /** This function gives the problems of one declaration: a bad range, a bad step, or marks and a default that do not fit. */
4100
- function declarationIssues(key, d) {
4101
- const out = [];
4102
- if (d.describe.trim().length === 0) out.push(`The option "${key}" has no description.`);
4103
- if (d.type === "number" || d.type === "integer") {
4104
- if (!Number.isFinite(d.min) || !Number.isFinite(d.max) || d.min > d.max) out.push(`The option "${key}" has the bad range ${d.min} to ${d.max}.`);
4105
- if (d.type === "integer" && (!Number.isInteger(d.min) || !Number.isInteger(d.max))) out.push(`The integer option "${key}" has a range that is not whole.`);
4106
- if (d.step !== void 0 && !(d.step > 0)) out.push(`The option "${key}" has the step ${d.step}. A step is more than 0.`);
4107
- if (d.scale === "log" && !(d.min > 0)) out.push(`The option "${key}" has the scale log and the min ${d.min}. The scale log needs a min above 0.`);
4108
- if (d.values !== void 0 && d.values.length === 0) out.push(`The number option "${key}" has an empty list of values.`);
4109
- for (const v of d.values ?? []) if (v < d.min || v > d.max || d.type === "integer" && !Number.isInteger(v)) out.push(`The value ${v} of the option "${key}" is not on its range ${d.min} to ${d.max}.`);
4110
- for (const v of [...d.marks ?? [], ...d.default === void 0 ? [] : [d.default]]) {
4111
- const issue = optionIssue(key, v, d);
4112
- if (issue) out.push(issue.message);
4113
- }
4114
- } else if (d.type === "enum") {
4115
- if (d.values.length === 0) out.push(`The enum option "${key}" has no values.`);
4116
- if (d.default !== void 0 && !d.values.includes(d.default)) out.push(`The default of the option "${key}" is not one of its values.`);
4117
- } else if (d.type === "boolean") {
4118
- if (d.default !== void 0 && typeof d.default !== "boolean") out.push(`The default of the option "${key}" is not true or false.`);
4119
- }
4120
- return out;
4121
- }
4122
- /**
4123
- * This function examines the schema of a strategy. It gives one message for each option of `defaults` without a declaration.
4124
- * It also gives one message for each bad declaration, and for each value of `defaults` that does not fit its declaration.
4125
- * A good schema gives an empty list.
4126
- */
4127
- function checkSchema(strategy) {
4128
- const schema = schemaOf(strategy);
4129
- const out = [];
4130
- for (const key of Object.keys(strategy.defaults)) if (!(key in schema)) out.push(`The strategy "${strategy.name}" has the option "${key}" in its defaults, without a declaration.`);
4131
- for (const [key, d] of Object.entries(schema)) out.push(...declarationIssues(key, d).map((m) => `The strategy "${strategy.name}": ${m}`));
4132
- out.push(...checkOptions(strategy, strategy.defaults).filter((i) => i.problem !== "unknown").map((i) => `The strategy "${strategy.name}": ${i.message}`));
4133
- return out;
3065
+ function spaceShapeKinds(space, options = {}) {
3066
+ return spaceShapeKinds$1(space, withKinds(options));
4134
3067
  }
4135
3068
  // src/strategy-catalog.ts
4136
3069
  /** The newest schema of a strategy catalog. A new field is a new version of the schema. */
@@ -6122,6 +5055,6 @@ const RECT_SCATTERED = /* @__PURE__ */ Object.freeze({
6122
5055
  };
6123
5056
  }
6124
5057
  });
6125
- export { BALANCE_MEASURE_SUFFIXES, BALANCE_SIDE_DEPTH, CIRCLE_SCATTERED, CORPUS_DIMENSIONS, DEFAULT_FAMILY_BY, DEFAULT_RNG, DEFAULT_SHAPES, DEFAULT_TOLERANCE, EDGES_STEP, EDGE_DENSITY, EDGE_KEY_STEP, EDGE_KEY_STEP_VERSION, EDGE_STEP_VERSION, EPS, EPS_STEPS, FAMILY_ANY_KIND, HARD_RULE_VERSION, INVALIDATED_FIELD, JOINT_MEASURES, JOINT_MOVED_MIN, NODE_POSITIONS_DIMENSION, OUTPUT_CLASS_MIN_INPUTS, OUTPUT_GRID_PROPERTIES, OUTPUT_NEAR_WHOLE, PACK_HARD_RULES, RECORD_EPS, RECORD_SCALE, RECT_SCATTERED, REFUSED_PROBE, SHAPE_KINDS, SHAPE_KIND_IDS, SIDES, SPLIT_SCHEMA, STRATEGY_CATALOG_SCHEMA, STRATEGY_CATALOG_SCHEMAS, STRATEGY_SPACE_SCHEMA, VERDICT_DRAWS, VERDICT_EXACT_CAP, VERDICT_EXACT_MAX, VERDICT_RUNS, VERDICT_SEED, applyPack, balanceMeasureSpecs, balanceMeasures, balanceOf, boundsOf, boxArea, canonicalConfig, canonicalInput, canonicalJson, carryRecord, catalogChoices, catalogDefaults, catalogKey, catalogOptions, checkCatalog, checkConfig, checkDeclared, checkInput, checkLayoutRecord, checkOptions, checkSchema, checkShapes, checkSpace, checkSplit, circleOverlaps, circlesOutside, clampOptions, compareMeasure, composeFamily, configId, corpusHashOf, countLinksThroughShapes, countObstacleHits, countOutside, countOverlaps, countPortsOffBorder, createFamilyRegistry, crossingPoint, declarationIssues, declaredClaimOf, declaredCounts, decodeOptionValue, dimensionAt, dimensionSupports, dimensionUnit, documentHash, dropIndex, edgeKeyStep, edgeStep, encodeOptionValue, enumerateSpace, exercised, familyKind, familyOf, fingerprintOf, fnv1a32, grow, hardRuleOf, inputShapeLevel, isShapeKind, itemShapeOf, joinConfigs, leaveOneSeedOut, levelsOf, listOptions, marginSides, minEffectOf, mulberry32, nearestGaps, optionDefaults, optionIssue, outputGridClass, outputGroups, outputHash, overlapOf, ownerDimension, packHard, packLinks, packOutputForm, paramActive, paramLevels, paramProblem, paramValue, parseLayoutRecord, parseStrategyCatalog, perChange, pickMoves, placedCircle, placedRect, pointSegmentDistance, portPoint, portfolio, probeHash, procrustesOf, productSpace, randomInt, rectInRegion, regionArea, regionHitsRect, resolveDimensions, ruleLevel, segmentThroughShape, segmentsCross, selectBest, sha256Hex, shapeKindOf, shapeKindProblem, shapeKindsOf, shapeLevel, shapeSupportProblems, shapesOf, shapesOverlap, sharedDimension, spaceShapeKinds, spaceSize, splitConfig, splitFileName, splitFolds, stepRandom, sweepGrid, sweepOf, sweepValues, toLayoutRecord, toPackInput, toRect, toSizedRect, translate, turnBox, turnMargin, turnPoint, turnPort, turnRegion, turnSide, verdict, writeStrategyCatalog };
5058
+ export { BALANCE_MEASURE_SUFFIXES, BALANCE_SIDE_DEPTH, CIRCLE_SCATTERED, CORPUS_DIMENSIONS, DEFAULT_FAMILY_BY, DEFAULT_RNG, DEFAULT_SHAPES, DEFAULT_TOLERANCE, EDGES_STEP, EDGE_DENSITY, EDGE_KEY_STEP, EDGE_KEY_STEP_VERSION, EDGE_STEP_VERSION, EPS, EPS_STEPS, FAMILY_ANY_KIND, FRAME_SCHEMA, FRAME_STATES, HARD_RULE_VERSION, INVALIDATED_FIELD, JOINT_MEASURES, JOINT_MOVED_MIN, NODE_POSITIONS_DIMENSION, OUTPUT_CLASS_MIN_INPUTS, OUTPUT_GRID_PROPERTIES, OUTPUT_NEAR_WHOLE, PACK_HARD_RULES, RECORD_EPS, RECORD_SCALE, RECT_SCATTERED, REFUSED_PROBE, SHAPE_KINDS, SHAPE_KIND_IDS, SIDES, SPLIT_SCHEMA, STRATEGY_CATALOG_SCHEMA, STRATEGY_CATALOG_SCHEMAS, STRATEGY_SPACE_SCHEMA, VERDICT_DRAWS, VERDICT_EXACT_CAP, VERDICT_EXACT_MAX, VERDICT_RUNS, VERDICT_SEED, applyPack, balanceMeasureSpecs, balanceMeasures, balanceOf, boundsOf, boxArea, canonicalConfig, canonicalInput, canonicalJson, carryRecord, catalogChoices, catalogDefaults, catalogKey, catalogOptions, checkCatalog, checkConfig, checkDeclared, checkInput, checkLayoutRecord, checkOptions, checkSchema, checkShapes, checkSpace, checkSplit, circleOverlaps, circlesOutside, clampOptions, compareMeasure, composeFamily, configId, corpusHashOf, countLinksThroughShapes, countObstacleHits, countOutside, countOverlaps, countPortsOffBorder, createFamilyRegistry, crossingPoint, declarationIssues, declaredClaimOf, declaredCounts, decodeOptionValue, dimensionAt, dimensionSupports, dimensionUnit, documentHash, dropIndex, edgeKeyStep, edgeStep, encodeOptionValue, enumerateSpace, exercised, familyKind, familyOf, fingerprintOf, fixedPointMove, fnv1a32, frameAt, frameMove, frameOf, grow, hardRuleOf, inputShapeLevel, isShapeKind, itemShapeOf, joinConfigs, leaveOneSeedOut, levelsOf, listOptions, marginSides, minEffectOf, mulberry32, nearestGaps, optionDefaults, optionIssue, outputGridClass, outputGroups, outputHash, outputOf, overlapOf, ownerDimension, packHard, packLinks, packOutputForm, paramActive, paramLevels, paramProblem, paramValue, parseLayoutRecord, parseStrategyCatalog, perChange, pickMoves, placedCircle, placedRect, pointSegmentDistance, portPoint, portfolio, probeHash, procrustesOf, productSpace, randomInt, rectInRegion, regionArea, regionHitsRect, resolveDimensions, ruleLevel, segmentThroughShape, segmentsCross, selectBest, sha256Hex, shapeKindOf, shapeKindProblem, shapeKindsOf, shapeLevel, shapeSupportProblems, shapesOf, shapesOverlap, sharedDimension, spaceShapeKinds, spaceSize, splitConfig, splitFileName, splitFolds, stepRandom, sweepGrid, sweepOf, sweepValues, toLayoutRecord, toPackInput, toRect, toSizedRect, translate, turnBox, turnMargin, turnPoint, turnPort, turnRegion, turnSide, verdict, writeStrategyCatalog };
6126
5059
 
6127
5060
  //# sourceMappingURL=index.js.map