@mark1russell7/capacity 0.0.0-bootstrap.0 → 0.1.0

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.
Files changed (45) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1107 -1
  3. package/build/index.d.ts +858 -0
  4. package/build/index.d.ts.map +1 -0
  5. package/build/index.js +1713 -0
  6. package/build/index.js.map +1 -0
  7. package/build/instance-0n6WhJzF.d.ts +782 -0
  8. package/build/instance-0n6WhJzF.d.ts.map +1 -0
  9. package/build/instance-check-CAuD9L4Z.js +1711 -0
  10. package/build/instance-check-CAuD9L4Z.js.map +1 -0
  11. package/build/schema.d.ts +69 -0
  12. package/build/schema.d.ts.map +1 -0
  13. package/build/schema.js +315 -0
  14. package/build/schema.js.map +1 -0
  15. package/limits/alerts-routes.line.json +78 -0
  16. package/limits/alerts-scale.limits.json +10 -0
  17. package/limits/alerts-start-gate.limits.json +1149 -0
  18. package/limits/alerts-start-routes-limit-home.bracket.json +543 -0
  19. package/limits/alerts-start-routes-limit-mid.bracket.json +464 -0
  20. package/limits/alerts-start-routes-limit.bracket.json +579 -0
  21. package/limits/alerts-tail-gate.limits.json +610 -0
  22. package/package.json +79 -4
  23. package/src/app-check.ts +477 -0
  24. package/src/app-metrics.ts +105 -0
  25. package/src/app.ts +239 -0
  26. package/src/check.ts +228 -0
  27. package/src/composition.ts +680 -0
  28. package/src/demand.ts +312 -0
  29. package/src/fit.ts +153 -0
  30. package/src/forms.ts +358 -0
  31. package/src/gate.ts +237 -0
  32. package/src/index.ts +142 -0
  33. package/src/instance-check.ts +122 -0
  34. package/src/instance.ts +84 -0
  35. package/src/knee.ts +606 -0
  36. package/src/law.ts +215 -0
  37. package/src/limit.ts +112 -0
  38. package/src/names.ts +19 -0
  39. package/src/observe.ts +74 -0
  40. package/src/program.ts +74 -0
  41. package/src/scale.ts +617 -0
  42. package/src/schema.ts +260 -0
  43. package/src/value.ts +206 -0
  44. package/src/workload-check.ts +130 -0
  45. package/src/workload.ts +88 -0
package/src/demand.ts ADDED
@@ -0,0 +1,312 @@
1
+ import { err, ok, type Result } from "@mark1russell7/optional";
2
+ import {
3
+ add,
4
+ compare,
5
+ convertible,
6
+ isCanonicalUnit,
7
+ isQuantity,
8
+ kindOf,
9
+ factorOf,
10
+ quantity,
11
+ scale,
12
+ whyNotConvertible,
13
+ type Quantity,
14
+ } from "@mark1russell7/quantity";
15
+ import type { Law, Variable } from "./law.ts";
16
+ import { finite } from "./names.ts";
17
+ import type { LoadPoint } from "./value.ts";
18
+ import { demandProblems, workloadProblem } from "./workload-check.ts";
19
+ import { RATE, type Amounts, type Demand, type WorkloadClass, type WorkloadProblem } from "./workload.ts";
20
+
21
+ /** This function gives the first problem of a demand, or undefined. The text `owner` goes before the path of the problem. */
22
+ const firstProblem = (demand: Demand, owner = ""): WorkloadProblem | undefined => {
23
+ const found = demandProblems(demand)[0];
24
+ return found === undefined || owner === "" ? found : { ...found, path: `${owner}.${found.path}` };
25
+ };
26
+
27
+ /**
28
+ * This function gives a demand with a change of each rate and each level. The variables of the
29
+ * requests stay. The function `change` gets the name of a level, and no name for a rate. It gives
30
+ * undefined for an amount that it cannot change.
31
+ */
32
+ const changed = (
33
+ demand: Demand,
34
+ change: (amount: Quantity, level?: string) => Quantity | undefined,
35
+ ): Result<Demand, WorkloadProblem> => {
36
+ const classes: WorkloadClass[] = [];
37
+ for (const [index, entry] of demand.classes.entries()) {
38
+ const rate = change(entry.rate);
39
+ if (rate === undefined) {
40
+ return err(workloadProblem("amount", `classes[${index}].rate`, `The rate of the class "${entry.id}" is not finite after the change.`));
41
+ }
42
+ classes.push({ id: entry.id, rate, request: entry.request });
43
+ }
44
+ const levels: Record<string, Quantity> = {};
45
+ for (const [name, amount] of Object.entries(demand.levels)) {
46
+ const level = change(amount, name);
47
+ if (level === undefined) return err(workloadProblem("amount", `levels.${name}`, `The level "${name}" is not finite after the change.`));
48
+ levels[name] = level;
49
+ }
50
+ return ok({ classes, levels });
51
+ };
52
+
53
+ /**
54
+ * This function gives a demand that is `by` times as large: each rate and each level, times `by`.
55
+ * The variables of the requests stay, because more clients do not make a request larger.
56
+ *
57
+ * It gives a problem for a demand that is not correct, and for a factor that is not a finite number
58
+ * of 0 or more.
59
+ */
60
+ export const scaleDemand = (demand: Demand, by: number): Result<Demand, WorkloadProblem> => {
61
+ const bad = firstProblem(demand);
62
+ if (bad !== undefined) return err(bad);
63
+ if (!finite(by) || by < 0) return err(workloadProblem("factor", "by", `The factor ${by} is not a finite number of 0 or more.`));
64
+ return changed(demand, (amount) => {
65
+ const product = scale(amount, by);
66
+ return finite(product.value) ? product : undefined;
67
+ });
68
+ };
69
+
70
+ /** These options name the levels that do not divide between instances. Each instance has the whole of such a level. */
71
+ export interface ShareOptions {
72
+ readonly whole?: readonly string[];
73
+ }
74
+
75
+ /**
76
+ * This function gives the demand on one instance when `instances` equal instances serve a demand:
77
+ * each rate and each level, divided by the count. The variables of the requests stay.
78
+ *
79
+ * A level in `options.whole` does not divide. For example, each instance of an app that keeps all
80
+ * open incidents in memory has the whole level.
81
+ *
82
+ * It gives a problem for a demand that is not correct. It gives a problem for a count that is not
83
+ * a whole number of 1 or more. It gives a problem for a name in `options.whole` that is not a level.
84
+ */
85
+ export const shareOf = (demand: Demand, instances: number, options: ShareOptions = {}): Result<Demand, WorkloadProblem> => {
86
+ const bad = firstProblem(demand);
87
+ if (bad !== undefined) return err(bad);
88
+ if (!Number.isSafeInteger(instances) || instances < 1) {
89
+ return err(workloadProblem("factor", "instances", `The count of instances ${instances} is not a whole number of 1 or more.`));
90
+ }
91
+ const whole = options.whole ?? [];
92
+ const unknown = whole.find((name) => !Object.hasOwn(demand.levels, name));
93
+ if (unknown !== undefined) return err(workloadProblem("variable", "whole", `The demand has no level "${unknown}".`));
94
+ return changed(demand, (amount, level) =>
95
+ level !== undefined && whole.includes(level) ? amount : quantity(amount.value / instances, amount.unit),
96
+ );
97
+ };
98
+
99
+ /**
100
+ * This function gives a portion of a demand for a search. Each rate and each level is times
101
+ * `shared`, and each level in `whole` is times `kept`. It does not examine the demand or the names.
102
+ *
103
+ * The demand on one of `n` instances at `s` times the load is the portion with `shared` equal to
104
+ * `s / n` and `kept` equal to `s`.
105
+ */
106
+ export const portionOf = (demand: Demand, shared: number, kept: number, whole: readonly string[]): Result<Demand, WorkloadProblem> =>
107
+ changed(demand, (amount, level) => {
108
+ const product = scale(amount, level !== undefined && whole.includes(level) ? kept : shared);
109
+ return finite(product.value) ? product : undefined;
110
+ });
111
+
112
+ /** This function gives the sum of two amounts, or the problem that stops it. */
113
+ const plus = (a: Quantity, b: Quantity, path: string, what: string): Result<Quantity, WorkloadProblem> => {
114
+ if (!convertible(a.unit, b.unit)) {
115
+ return err(workloadProblem("unit", path, `${what} do not add: ${whyNotConvertible(a.unit, b.unit) ?? "the units are different"}.`));
116
+ }
117
+ const total = add(a, b);
118
+ return finite(total.value) ? ok(total) : err(workloadProblem("amount", path, `${what} do not have a finite sum.`));
119
+ };
120
+
121
+ /** This function tells if two sets of amounts have the same names and equal amounts. */
122
+ const sameAmounts = (a: Amounts, b: Amounts): boolean => {
123
+ const names = Object.keys(a);
124
+ return (
125
+ names.length === Object.keys(b).length &&
126
+ names.every((name) => {
127
+ const other = b[name];
128
+ const amount = a[name] as Quantity;
129
+ return Object.hasOwn(b, name) && other !== undefined && convertible(amount.unit, other.unit) && compare(amount, other) === 0;
130
+ })
131
+ );
132
+ };
133
+
134
+ const inOrder = (a: string, b: string): number => (a < b ? -1 : a > b ? 1 : 0);
135
+
136
+ /**
137
+ * This function gives the sum of two demands. A class of one demand stays. A class of the two
138
+ * demands has the sum of its rates, and its request must be equal in the two. The levels add, and a
139
+ * level of one demand stays. The classes and the levels of the sum are in the order of their names.
140
+ *
141
+ * The sum has the laws of addition: the order of the demands does not change it, and `NO_DEMAND`
142
+ * is its zero. An amount of the sum is in the unit of the first demand that gives it. Thus the
143
+ * order can change the unit of an amount, and not the amount.
144
+ *
145
+ * It gives a problem for a demand that is not correct, and for amounts that do not add. A path of
146
+ * a problem starts with `first` or `second`, or with neither for a problem of the sum.
147
+ */
148
+ export const mergeDemands = (first: Demand, second: Demand): Result<Demand, WorkloadProblem> => {
149
+ const bad = firstProblem(first, "first") ?? firstProblem(second, "second");
150
+ if (bad !== undefined) return err(bad);
151
+
152
+ const classes = new Map<string, WorkloadClass>(first.classes.map((entry) => [entry.id, entry]));
153
+ for (const [index, entry] of second.classes.entries()) {
154
+ const same = classes.get(entry.id);
155
+ if (same === undefined) {
156
+ classes.set(entry.id, entry);
157
+ continue;
158
+ }
159
+ const path = `second.classes[${index}]`;
160
+ if (!sameAmounts(same.request, entry.request)) {
161
+ return err(workloadProblem("class", `${path}.request`, `The class "${entry.id}" has a different request in the two demands.`));
162
+ }
163
+ const rate = plus(same.rate, entry.rate, `${path}.rate`, `The rates of the class "${entry.id}"`);
164
+ if (rate.tag === "err") return rate;
165
+ classes.set(entry.id, { id: same.id, rate: rate.value, request: same.request });
166
+ }
167
+
168
+ const levels = new Map<string, Quantity>(Object.entries(first.levels));
169
+ for (const [name, amount] of Object.entries(second.levels)) {
170
+ const same = levels.get(name);
171
+ if (same === undefined) {
172
+ levels.set(name, amount);
173
+ continue;
174
+ }
175
+ const level = plus(same, amount, `second.levels.${name}`, `The levels "${name}"`);
176
+ if (level.tag === "err") return level;
177
+ levels.set(name, level.value);
178
+ }
179
+
180
+ const total: Demand = {
181
+ classes: [...classes.values()].sort((a, b) => inOrder(a.id, b.id)),
182
+ levels: Object.fromEntries([...levels].sort(([a], [b]) => inOrder(a, b))),
183
+ };
184
+ // The sum can have a problem that no part has: a level of one demand with the name of a variable of the other.
185
+ const together = firstProblem(total);
186
+ return together === undefined ? ok(total) : err(together);
187
+ };
188
+
189
+ /**
190
+ * This function gives the sum of the rates of the classes of a demand, in `unit`. A demand with no
191
+ * class has a rate of 0.
192
+ *
193
+ * It gives a problem for a demand that is not correct, and for a unit that is not a unit of a
194
+ * rate. It gives a problem for a class whose rate counts a different thing, for example events.
195
+ */
196
+ export const totalRate = (demand: Demand, unit: string): Result<Quantity, WorkloadProblem> => {
197
+ const bad = firstProblem(demand);
198
+ if (bad !== undefined) return err(bad);
199
+ if (!isCanonicalUnit(unit) || kindOf(unit) !== "frequency") {
200
+ return err(workloadProblem("unit", "unit", `"${unit}" is not a canonical unit of a rate, for example "{request}/s".`));
201
+ }
202
+ for (const [index, entry] of demand.classes.entries()) {
203
+ if (!convertible(entry.rate.unit, unit)) {
204
+ const why = whyNotConvertible(entry.rate.unit, unit) ?? "the units are different";
205
+ return err(workloadProblem("unit", `classes[${index}].rate`, `The rate of the class "${entry.id}" is not in "${unit}": ${why}.`));
206
+ }
207
+ }
208
+ // One cached factor for each pair of units: the search calls this function at each load.
209
+ let value = 0;
210
+ for (const entry of demand.classes) value += entry.rate.value * factorOf(entry.rate.unit, unit);
211
+ const total = quantity(value, unit);
212
+ return finite(total.value) ? ok(total) : err(workloadProblem("amount", "classes", "The rates do not have a finite sum."));
213
+ };
214
+
215
+ /**
216
+ * A load tells which rate the variable `rate` of a law reads. The load `class` is the rate of one
217
+ * class. The load `total` is the sum of the rates of all classes, the load of the whole instance.
218
+ */
219
+ export type Load = "class" | "total";
220
+
221
+ /** These options tell which rate the variable `rate` of a law reads. The load is `class` when the options give none. */
222
+ export interface PointOptions {
223
+ readonly load?: Load;
224
+ }
225
+
226
+ /**
227
+ * A point law is the part of a law that a load point reads: its id, and the id and the unit of each
228
+ * variable. Thus a caller can get the points of a law before the fit of the law.
229
+ */
230
+ export interface PointLaw extends Pick<Law, "id"> {
231
+ readonly variables: readonly Pick<Variable, "id" | "unit">[];
232
+ }
233
+
234
+ /** This function gives the point of a law from a rate, the variables of one request, the levels of a demand and `given`. */
235
+ const pointOf = (demand: Demand, law: PointLaw, rate: Quantity | "total", request: Amounts, given: Amounts): Result<LoadPoint, WorkloadProblem> => {
236
+ const point: Record<string, number> = {};
237
+ for (const variable of law.variables) {
238
+ const name = variable.id;
239
+ const found: unknown[] = [];
240
+ if (name === RATE) {
241
+ if (rate === "total") {
242
+ const total = totalRate(demand, variable.unit);
243
+ if (total.tag === "err") return err({ ...total.error, path: name, message: `The variable "${name}" of the law "${law.id}" reads the total rate. ${total.error.message}` });
244
+ found.push(total.value);
245
+ } else found.push(rate);
246
+ }
247
+ for (const amounts of [request, demand.levels, given]) {
248
+ if (Object.hasOwn(amounts, name)) found.push(amounts[name]);
249
+ }
250
+ const [amount] = found;
251
+ if (found.length === 0) {
252
+ return err(workloadProblem("variable", name, `The demand gives no amount for the variable "${name}" of the law "${law.id}".`));
253
+ }
254
+ if (found.length > 1) {
255
+ return err(workloadProblem("variable", name, `The demand gives the variable "${name}", and the caller gives it also.`));
256
+ }
257
+ if (!isQuantity(amount)) {
258
+ return err(workloadProblem("amount", name, `The amount of "${name}" from the caller is not a finite amount in a canonical unit.`));
259
+ }
260
+ if (!isCanonicalUnit(variable.unit)) {
261
+ return err(workloadProblem("unit", name, `The unit "${variable.unit}" of the variable "${name}" of the law "${law.id}" is not canonical.`));
262
+ }
263
+ if (!convertible(amount.unit, variable.unit)) {
264
+ const why = whyNotConvertible(amount.unit, variable.unit) ?? "the units are different";
265
+ return err(
266
+ workloadProblem("unit", name, `The variable "${name}" of the law "${law.id}" is in "${variable.unit}", not in "${amount.unit}": ${why}.`),
267
+ );
268
+ }
269
+ point[name] = amount.value * factorOf(amount.unit, variable.unit);
270
+ }
271
+ return ok(point);
272
+ };
273
+
274
+ /**
275
+ * This function gives the load point of one class of a demand for a law. The point has one number
276
+ * for each variable of the law, in the unit of that variable.
277
+ *
278
+ * The variable `rate` is the rate of the class, or the total rate with the load `total`. Each other
279
+ * variable is a variable of the request of the class, a level of the demand, or an amount of
280
+ * `given`. The amounts of `given` are the state of an instance, for example the size of its heap
281
+ * and its age. No workload gives that state.
282
+ *
283
+ * It gives a problem for a demand that is not correct and for a class that the demand does not
284
+ * have. It gives a problem for a variable with no amount or with two amounts. It gives a problem
285
+ * for an amount that does not convert to the unit of the variable.
286
+ */
287
+ export const loadPointOf = (
288
+ demand: Demand,
289
+ id: string,
290
+ law: PointLaw,
291
+ given: Amounts = {},
292
+ options: PointOptions = {},
293
+ ): Result<LoadPoint, WorkloadProblem> => {
294
+ const bad = firstProblem(demand);
295
+ if (bad !== undefined) return err(bad);
296
+ const entry = demand.classes.find((candidate) => candidate.id === id);
297
+ if (entry === undefined) return err(workloadProblem("class", "classes", `The demand has no class "${id}".`));
298
+ return pointOf(demand, law, (options.load ?? "class") === "class" ? entry.rate : "total", entry.request, given);
299
+ };
300
+
301
+ /**
302
+ * This function gives the load point of a whole instance for a law: a point with no class. The
303
+ * variable `rate` is the total rate of the demand. Each other variable is a level of the demand or
304
+ * an amount of `given`. A variable of a request has no amount here.
305
+ *
306
+ * It gives the problems of `loadPointOf`, with no problem of a class.
307
+ */
308
+ export const instancePointOf = (demand: Demand, law: PointLaw, given: Amounts = {}): Result<LoadPoint, WorkloadProblem> => {
309
+ const bad = firstProblem(demand);
310
+ if (bad !== undefined) return err(bad);
311
+ return pointOf(demand, law, "total", {}, given);
312
+ };
package/src/fit.ts ADDED
@@ -0,0 +1,153 @@
1
+ import { err, ok, type Result } from "@mark1russell7/optional";
2
+ import {
3
+ bootstrapSeparable,
4
+ heldOutSeparable,
5
+ rankSeparable,
6
+ SEPARABLE_BOOTSTRAP_RUNS,
7
+ type SeparableGroup,
8
+ type SeparableModel,
9
+ } from "@mark1russell7/rigor-statistics";
10
+ import { FORM_VARIABLE, FORMS, constantIdsOf, formOf, modelProblem, pointsProblem, separableOf } from "./forms.ts";
11
+ import type { Binding, CatalogForm, Points } from "./forms.ts";
12
+ import { DEFAULT_LEVEL, bootstrapDraws, leastCount, leastGroups, type FitError, type Law, type Loser, type ResidualKind } from "./law.ts";
13
+
14
+ /** The options of `fitLaw`. */
15
+ export interface LawFitOptions {
16
+ /** These forms compete for the law. The default is each form of the catalog. */
17
+ readonly forms?: readonly CatalogForm[];
18
+ /** This binding puts the form that wins into the law. The default is the variable `x` and the ids of the catalog. */
19
+ readonly binding?: Binding;
20
+ /**
21
+ * This kind tells how the fit compares a value with a form. The default is `"absolute"`. A `"relative"` fit uses the
22
+ * weights `1 / y^2`. Thus each value of a relative fit is not 0.
23
+ */
24
+ readonly residual?: ResidualKind;
25
+ /**
26
+ * This list gives the group of each point. The points of one group are replicates of one load. The held-out fit holds
27
+ * out each group. The default group of a point is its value of the variable.
28
+ */
29
+ readonly groups?: readonly SeparableGroup[];
30
+ /**
31
+ * This list gives the group of each point for the bootstrap. Each run of the bootstrap draws whole groups of this
32
+ * list. The default is the list `groups`. A group of the bootstrap is an independent unit of the data, for example
33
+ * the job that measured its points. A plan that fixes its loads has no random load, thus a draw of whole loads is
34
+ * the wrong model for it.
35
+ */
36
+ readonly bootstrapGroups?: readonly SeparableGroup[];
37
+ /** This number is the number of runs of the bootstrap. The default is `SEPARABLE_BOOTSTRAP_RUNS` of rigor-statistics. */
38
+ readonly runs?: number;
39
+ /** This seed starts the draws of the bootstrap. The default is 1. */
40
+ readonly seed?: number;
41
+ }
42
+
43
+ /** A form rank is one form that competed in a law fit, with the error of its held-out residuals. */
44
+ export interface FormRank {
45
+ readonly form: string;
46
+ /** This error comes from the held-out residuals that have a value. With no such residual, each error is NaN. */
47
+ readonly error: FitError;
48
+ /** This number is the number of points with no held-out prediction. */
49
+ readonly missing: number;
50
+ /** This text tells why the form has no fit. A form with a fit has no reason. */
51
+ readonly reason?: string;
52
+ }
53
+
54
+ /**
55
+ * A law fit is the part of a law that comes from a fit of its points. It has the form, the constants, the replicates and
56
+ * the record of the fit. The list `ranks` keeps each form that competed, best first.
57
+ */
58
+ export interface LawFit extends Pick<Law, "form" | "constants" | "replicates" | "fit"> {
59
+ readonly ranks: readonly FormRank[];
60
+ }
61
+
62
+ /**
63
+ * This function fits a law of one variable to its points. Each form competes, and the form with the smallest root mean
64
+ * square of its held-out residuals wins. A form with a point that has no held-out prediction ranks after each form with
65
+ * a prediction at each point.
66
+ *
67
+ * The fit of each form is `fitSeparable` of `@mark1russell7/rigor-statistics`. Each held-out residual comes from a fit of
68
+ * the other groups. The replicates of the winner come from a bootstrap of the whole groups of `bootstrapGroups`. The losers of the record are
69
+ * the other forms with a held-out prediction at each point.
70
+ *
71
+ * The function gives an error for points that a fit cannot use, and when no form has a held-out prediction at each point.
72
+ * It gives an error for fewer groups of the bootstrap than `leastGroups` of the level 0.95, because their draws are too few for an interval.
73
+ */
74
+ export const fitLaw = (points: Points, options: LawFitOptions = {}): Result<LawFit, string> => {
75
+ const fault = pointsProblem(points);
76
+ if (fault !== undefined) return err(fault);
77
+ const n = points.x.length;
78
+ const forms = options.forms ?? FORMS;
79
+ if (forms.length === 0) return err("The fit has no form.");
80
+ const twice = forms.find((form, index) => forms.findIndex((other) => other.id === form.id) !== index);
81
+ if (twice !== undefined) return err(`The form "${twice.id}" is in the list of forms two times.`);
82
+ const residual = options.residual ?? "absolute";
83
+ if (residual === "relative" && points.y.some((y) => y === 0)) return err("A relative fit needs values that are not 0.");
84
+ const groups = options.groups ?? points.x;
85
+ if (groups.length !== n) return err(`The fit has ${groups.length} groups for ${n} points.`);
86
+ const groupCount = new Set(groups).size;
87
+ if (groupCount < 2) return err("The fit needs two groups or more, because the held-out fit holds out one group.");
88
+ const bootstrapGroups = options.bootstrapGroups ?? groups;
89
+ if (bootstrapGroups.length !== n) return err(`The fit has ${bootstrapGroups.length} groups of the bootstrap for ${n} points.`);
90
+ const bootstrapCount = new Set(bootstrapGroups).size;
91
+ const leastBootstrap = leastGroups(DEFAULT_LEVEL);
92
+ if (bootstrapCount < leastBootstrap) {
93
+ return err(
94
+ `The bootstrap draws whole groups, and the fit has ${bootstrapCount} of them. Thus the count of different draws is ` +
95
+ `${bootstrapDraws(bootstrapCount)}. The level ${DEFAULT_LEVEL} needs ${leastCount(DEFAULT_LEVEL)}, thus ${leastBootstrap} groups or more.`,
96
+ );
97
+ }
98
+ const weighted = residual === "relative" ? { weights: points.y.map((y) => 1 / (y * y)) } : {};
99
+
100
+ const models: Record<string, SeparableModel<number>> = {};
101
+ const skipped: FormRank[] = [];
102
+ for (const form of forms) {
103
+ const model = separableOf(form, points.x);
104
+ const reason = modelProblem(form, model);
105
+ if (reason === undefined) models[form.id] = model;
106
+ else skipped.push({ form: form.id, error: { mae: Number.NaN, rmse: Number.NaN }, missing: n, reason });
107
+ }
108
+ const ranked = rankSeparable(models, points.x, points.y, { groups, residual, ...weighted });
109
+ const ranks: FormRank[] = [
110
+ ...ranked.map((rank): FormRank => ({
111
+ form: rank.id,
112
+ error: { mae: rank.error.mae, rmse: rank.error.rmse },
113
+ missing: rank.error.missing,
114
+ ...(rank.fit === null ? { reason: `The form "${rank.id}" has no least-squares fit to ${n} points.` } : {}),
115
+ })),
116
+ ...skipped,
117
+ ];
118
+ const best = ranked[0];
119
+ if (best === undefined || best.fit === null || best.error.missing > 0) {
120
+ return err(`No form of ${forms.length} has a held-out prediction at each of the ${n} points.`);
121
+ }
122
+ const winner = forms.find((form) => form.id === best.id) as CatalogForm;
123
+ const model = models[best.id] as SeparableModel<number>;
124
+ const held = heldOutSeparable(model, points.x, points.y, { groups, residual, ...weighted });
125
+ const boot = bootstrapSeparable(model, points.x, points.y, {
126
+ groups: bootstrapGroups,
127
+ ...weighted,
128
+ runs: options.runs ?? SEPARABLE_BOOTSTRAP_RUNS,
129
+ seed: options.seed ?? 1,
130
+ });
131
+ if (boot === null) return err(`The form "${winner.id}" has no fit for the bootstrap.`);
132
+ const least = leastCount(DEFAULT_LEVEL);
133
+ if (boot.replicates.length < least) {
134
+ return err(`The bootstrap gave ${boot.replicates.length} fits in ${boot.runs} runs. The level ${DEFAULT_LEVEL} needs ${least}.`);
135
+ }
136
+ const binding = options.binding ?? { variable: FORM_VARIABLE };
137
+ const values = [...best.fit.coefficients, ...best.fit.shapes];
138
+ const constants = constantIdsOf(winner).map((id, index) => ({ id: binding.constants?.[id] ?? id, value: values[index] as number }));
139
+ const losers: Loser[] = ranks
140
+ .slice(1)
141
+ .filter((rank) => rank.missing === 0 && rank.reason === undefined)
142
+ .map((rank) => ({ form: rank.form, error: rank.error }));
143
+ const method =
144
+ `separable least squares: ${Object.keys(models).length} forms ranked by the rmse of the held-out residuals of ${groupCount} groups, ` +
145
+ `${boot.replicates.length} fits in ${boot.runs} bootstrap runs of ${bootstrapCount} whole groups (seed ${boot.seed})`;
146
+ return ok({
147
+ form: formOf(winner, binding),
148
+ constants,
149
+ replicates: boot.replicates,
150
+ fit: { method, residual, residuals: held.residuals, losers },
151
+ ranks,
152
+ });
153
+ };