@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/knee.ts ADDED
@@ -0,0 +1,606 @@
1
+ import { err, ok, type Result } from "@mark1russell7/optional";
2
+ import { convertible, isQuantity, type Quantity, valueIn, whyNotConvertible } from "@mark1russell7/quantity";
3
+ import type { Expr } from "@mark1russell7/vex";
4
+ import { DEFAULT_LEVEL, leastCount, type Law, type LawProblem, type Variable } from "./law.ts";
5
+ import { recordOf, valuesAt } from "./program.ts";
6
+ import { intervalOf, levelProblem, type LevelOptions, type LoadPoint, type Range } from "./value.ts";
7
+
8
+ /** This number is the count of steps of the grid of a knee search when the options give none. */
9
+ export const KNEE_STEPS = 64;
10
+
11
+ /** This number is the largest count of steps of the grid of a knee search. It sets a limit on the work of one search. */
12
+ export const MAX_STEPS = 4096;
13
+
14
+ /**
15
+ * A knee rule tells where a law leaves its cheap region.
16
+ *
17
+ * - `rise`: the value is more than `1 + share` times the value at the start of the search.
18
+ * - `slope`: the slope is more than `factor` times the slope at the start of the search.
19
+ * - `floor`: the value is more than `1 + share` times the floor of the row. The floor of a row is its
20
+ * least value on the grid of the search, before its edge. The search of a row starts at its floor.
21
+ */
22
+ export type KneeRule =
23
+ | { readonly kind: "rise"; readonly share: number }
24
+ | { readonly kind: "slope"; readonly factor: number }
25
+ | { readonly kind: "floor"; readonly share: number };
26
+
27
+ /** The floor of a law is its least value with its constants on the grid of a search, and the load of that value. */
28
+ export interface Floor {
29
+ readonly load: number;
30
+ readonly value: number;
31
+ }
32
+
33
+ /**
34
+ * These options set a knee search. The search goes along one variable, from `from` to `to`, on a
35
+ * grid of `steps` steps. The point `at` gives the value of each other variable of the law.
36
+ *
37
+ * The search goes from the minimum to the maximum of the variable, on 64 steps, when the options
38
+ * give no value. The level of the intervals is 0.95 when the options give none.
39
+ */
40
+ export interface KneeOptions extends LevelOptions {
41
+ readonly at?: LoadPoint;
42
+ readonly from?: number;
43
+ readonly to?: number;
44
+ readonly steps?: number;
45
+ }
46
+
47
+ /** An open range goes from `low` to `high`. A null end is past the end of the search. */
48
+ export interface OpenRange {
49
+ readonly low: number | null;
50
+ readonly high: number | null;
51
+ }
52
+
53
+ /**
54
+ * A crossing is a load on the variable of a search, with the interval of its replicates. A null
55
+ * value tells that the crossing is not in the search. The flag `outside` tells that the value is
56
+ * outside the range of the variable. Then the value is an extrapolation.
57
+ */
58
+ export interface Crossing {
59
+ readonly value: number | null;
60
+ readonly interval: OpenRange;
61
+ readonly outside: boolean;
62
+ }
63
+
64
+ /**
65
+ * A knee is the result of a knee search along one variable of a law, in the unit of the variable.
66
+ *
67
+ * The `knee` is the first load where the law obeys the rule: there the law leaves its cheap region.
68
+ * The `edge` is the first load where the law has no finite value. This is a pole, where the value
69
+ * grows with no limit, or the start of a region with no value. The knee is always before the edge.
70
+ * The list `outside` names each other variable whose value is outside its range. Only a knee of the
71
+ * rule `floor` has the fields `floor` and `noFloor`.
72
+ */
73
+ export interface Knee {
74
+ readonly variable: string;
75
+ readonly unit: string;
76
+ readonly rule: KneeRule;
77
+ readonly level: number;
78
+ readonly search: Range;
79
+ readonly knee: Crossing;
80
+ readonly edge: Crossing;
81
+ readonly outside: readonly string[];
82
+ /** This floor is the floor of the law with its constants. */
83
+ readonly floor?: Floor;
84
+ /** This number is the count of replicates with no floor above 0. The rule cannot apply to them, thus the interval of the knee leaves them out. */
85
+ readonly noFloor?: number;
86
+ }
87
+
88
+ /** A curve gives the value of one row of a law or of a composition at each load. A load with no finite value gives undefined. */
89
+ export type Curve = (loads: readonly number[]) => readonly (number | undefined)[];
90
+
91
+ /** This number sets the farthest distance from a peak where the pole test reads the size of the law. It is a share of the width of the bracket. */
92
+ const NEAR = 1e-6;
93
+
94
+ /** Each distance of the pole test is this share of the distance before it. */
95
+ const CLOSER = 1e-3;
96
+
97
+ /** At a pole, the gain of size in the second step nearer is at least this share of the gain in the first step. */
98
+ const POLE_GAIN = 0.9;
99
+
100
+ /** A gain of size less than this share of the size is the noise of the floats, not a pole. */
101
+ const NOISE = 1e-9;
102
+
103
+ /** The step of a difference quotient, for each unit of the load. */
104
+ const STEP = 1e-7;
105
+
106
+ /** The most rounds of a bisection or of a golden-section search. Each search stops before, when its bracket has no middle. */
107
+ const ROUNDS = 400;
108
+
109
+ const INVERSE_PHI = (Math.sqrt(5) - 1) / 2;
110
+
111
+ const problem = (code: LawProblem["code"], path: string, message: string): LawProblem => ({ code, path, message });
112
+
113
+ /** This function gives the value of a curve at one load. */
114
+ const valueOf = (curve: Curve, load: number): number | undefined => curve([load])[0];
115
+
116
+ /**
117
+ * This function gives the load where a test changes from false to true, with a bisection. The test
118
+ * is false at `low` and true at `high`. The function gives the end of the last bracket where the test is true.
119
+ */
120
+ const crossingOf = (test: (load: number) => boolean, low: number, high: number): number => {
121
+ let [a, b] = [low, high];
122
+ for (let round = 0; round < ROUNDS; round += 1) {
123
+ const middle = a + (b - a) / 2;
124
+ if (middle <= a || middle >= b) break;
125
+ if (test(middle)) b = middle;
126
+ else a = middle;
127
+ }
128
+ return b;
129
+ };
130
+
131
+ /** This function gives the load of the largest size in a bracket, with a golden-section search. */
132
+ const peakOf = (size: (load: number) => number, low: number, high: number): number => {
133
+ let [a, b] = [low, high];
134
+ let c = b - INVERSE_PHI * (b - a);
135
+ let d = a + INVERSE_PHI * (b - a);
136
+ let [sizeC, sizeD] = [size(c), size(d)];
137
+ for (let round = 0; round < ROUNDS && a < c && c < d && d < b; round += 1) {
138
+ if (sizeC >= sizeD) {
139
+ [b, d, sizeD] = [d, c, sizeC];
140
+ c = b - INVERSE_PHI * (b - a);
141
+ sizeC = size(c);
142
+ } else {
143
+ [a, c, sizeC] = [c, d, sizeD];
144
+ d = a + INVERSE_PHI * (b - a);
145
+ sizeD = size(d);
146
+ }
147
+ }
148
+ return sizeC >= sizeD ? c : d;
149
+ };
150
+
151
+ /**
152
+ * This function tells if the size of a law grows with no bound near the top of a peak. It reads the
153
+ * size at three distances from the top, each 1000 times nearer than the distance before it.
154
+ *
155
+ * At a pole, each step nearer adds as much size as the step before, or more. A power pole adds more,
156
+ * and a logarithm pole adds the same. Near a finite peak, the second step adds about a millionth of
157
+ * the first. A load with no value at one of the distances is an edge near the top.
158
+ */
159
+ const diverges = (size: (load: number) => number, top: number, near: number): boolean => {
160
+ const sizeAt = (distance: number): number => Math.max(size(top - distance), size(top + distance));
161
+ const [far, middle, close] = [near, near * CLOSER, near * CLOSER * CLOSER].map(sizeAt) as [number, number, number];
162
+ if (!Number.isFinite(close) || !Number.isFinite(middle) || !Number.isFinite(far)) return true;
163
+ const first = middle - far;
164
+ return first > NOISE * middle && close - middle >= POLE_GAIN * first;
165
+ };
166
+
167
+ /**
168
+ * This function gives the edge of one row of a law: the first load of the grid where the law has
169
+ * no finite value. It gives Infinity when the law has a finite value on all of the grid.
170
+ *
171
+ * The size of a law at a load is the distance of its value from the start value. A load with no
172
+ * value has an infinite size. The search examines each peak of the size on the grid, in order. A
173
+ * golden-section search finds the top of the peak, and the pole test examines it. A peak with no
174
+ * value at its top starts a region with no value.
175
+ */
176
+ const edgeOf = (curve: Curve, grid: readonly number[], values: readonly (number | undefined)[], start: number): number => {
177
+ const sizeOf = (value: number | undefined): number => (value === undefined ? Infinity : Math.abs(value - start));
178
+ const size = (load: number): number => sizeOf(valueOf(curve, load));
179
+ const noValue = (load: number): boolean => valueOf(curve, load) === undefined;
180
+ const sizes = values.map(sizeOf);
181
+ const last = grid.length - 1;
182
+ for (let index = 1; index <= last; index += 1) {
183
+ const here = sizes[index] as number;
184
+ const missing = values[index] === undefined;
185
+ const peak = here > (sizes[index - 1] as number) && (index === last || missing || here >= (sizes[index + 1] as number));
186
+ if (!peak) continue;
187
+ const low = grid[index - 1] as number;
188
+ const high = grid[missing ? index : Math.min(index + 1, last)] as number;
189
+ const top = peakOf(size, low, high);
190
+ if (noValue(top)) return crossingOf(noValue, low, top);
191
+ if (diverges(size, top, NEAR * (high - low))) return top;
192
+ if (missing) return crossingOf(noValue, low, grid[index] as number);
193
+ }
194
+ return Infinity;
195
+ };
196
+
197
+ /** This function gives the step of a difference quotient at a load. The unit is the width of the search on a linear scale, and 0 on a log scale. */
198
+ const stepAt = (load: number, unit: number): number => STEP * Math.max(Math.abs(load), unit);
199
+
200
+ /**
201
+ * A test tells if the law passes a mark at one load. The value at the load is optional: without
202
+ * it, the test reads the curve. A load with no finite value does not pass.
203
+ */
204
+ export type Test = (load: number, value?: number) => boolean;
205
+
206
+ /**
207
+ * The context of the test of one row: its curve, its start value, its path, its start load and its
208
+ * step unit. It also has the grid, the values of the row on the grid and the edge of the row.
209
+ */
210
+ export interface TestContext {
211
+ readonly curve: Curve;
212
+ readonly start: number;
213
+ readonly path: string;
214
+ readonly from: number;
215
+ readonly unit: number;
216
+ readonly grid: readonly number[];
217
+ readonly values: readonly (number | undefined)[];
218
+ readonly edge: number;
219
+ }
220
+
221
+ /**
222
+ * A test maker gives the test of one row, or the problem that stops the test at the start of the
223
+ * search. An undefined test tells that the rule cannot apply to the row. Then the row has no crossing.
224
+ */
225
+ export type TestOf = (context: TestContext) => Result<Test | undefined, LawProblem>;
226
+
227
+ /**
228
+ * This function gives the first load before the edge where the test holds. It gives Infinity when
229
+ * the test does not hold before the edge or the end of the grid.
230
+ *
231
+ * The search tests the loads of the grid before the edge, and one load near the edge. A bisection
232
+ * then finds the load between the last load that fails the test and the first load that passes it.
233
+ */
234
+ const firstHolds = (holds: Test, grid: readonly number[], values: readonly (number | undefined)[], edge: number): number => {
235
+ const loads = grid.map((load, index) => ({ load, value: values[index] })).filter(({ load }) => load < edge);
236
+ if (Number.isFinite(edge)) {
237
+ const before = loads.at(-1)?.load ?? (grid[0] as number);
238
+ loads.push({ load: edge - NEAR * (edge - before), value: undefined });
239
+ }
240
+ let previous: number | undefined;
241
+ for (const { load, value } of loads) {
242
+ if (holds(load, value)) return previous === undefined ? load : crossingOf((x) => holds(x), previous, load);
243
+ previous = load;
244
+ }
245
+ return Infinity;
246
+ };
247
+
248
+ /** The crossing and the edge of one row of a law. An undefined crossing tells that the rule cannot apply to the row. */
249
+ export interface RowResult {
250
+ readonly crossing: number | undefined;
251
+ readonly edge: number;
252
+ }
253
+
254
+ /** This function gives the first load where one row passes its test, and the edge of the row. The text `what` names the owner of the row in a problem. */
255
+ export const rowOf = (
256
+ curve: Curve,
257
+ path: string,
258
+ testOf: TestOf,
259
+ grid: readonly number[],
260
+ unit: number,
261
+ what = "law",
262
+ ): Result<RowResult, LawProblem> => {
263
+ const values = curve(grid);
264
+ const start = values[0];
265
+ const from = grid[0] as number;
266
+ if (start === undefined) return err(problem("value", path, `The ${what} has no value at the start of the search, ${from}.`));
267
+ const edge = edgeOf(curve, grid, values, start);
268
+ const test = testOf({ curve, start, path, from, unit, grid, values, edge });
269
+ if (test.tag === "err") return test;
270
+ return ok({ crossing: test.value === undefined ? undefined : firstHolds(test.value, grid, values, edge), edge });
271
+ };
272
+
273
+ /** This function gives the test of a knee rule: the value or the slope is above its mark from the start of the search. */
274
+ const ruleTest =
275
+ (rule: Exclude<KneeRule, { readonly kind: "floor" }>): TestOf =>
276
+ ({ curve, start, path, from, unit }) => {
277
+ if (rule.kind === "rise") {
278
+ if (!(start > 0)) {
279
+ return err(problem("knee", path, `The rule "rise" needs a value above 0 at the start of the search. The value is ${start}.`));
280
+ }
281
+ const limit = (1 + rule.share) * start;
282
+ return ok((load, value = valueOf(curve, load)) => value !== undefined && value > limit);
283
+ }
284
+ const slopeAt = (load: number, value: number | undefined): number | undefined => {
285
+ const step = stepAt(load, unit);
286
+ const before = valueOf(curve, load - step);
287
+ return value === undefined || before === undefined ? undefined : (value - before) / step;
288
+ };
289
+ const step = stepAt(from, unit);
290
+ const after = valueOf(curve, from + step);
291
+ const first = after === undefined ? undefined : (after - start) / step;
292
+ if (first === undefined || !(first > 0)) {
293
+ return err(problem("knee", path, `The rule "slope" needs a slope above 0 at the start of the search. The slope is ${String(first)}.`));
294
+ }
295
+ const limit = rule.factor * first;
296
+ return ok((load, value) => {
297
+ const slope = slopeAt(load, value ?? valueOf(curve, load));
298
+ return slope !== undefined && slope > limit;
299
+ });
300
+ };
301
+
302
+ /** This function gives the test of an amount: the value is above the amount. */
303
+ export const amountTest =
304
+ (amount: number): TestOf =>
305
+ ({ curve }) =>
306
+ ok((load, value = valueOf(curve, load)) => value !== undefined && value > amount);
307
+
308
+ /** These kinds name the knee rules. */
309
+ const KNEE_KINDS: readonly KneeRule["kind"][] = ["rise", "slope", "floor"];
310
+
311
+ /**
312
+ * This function gives the problem of a knee rule, or undefined for a correct rule. The rule can come
313
+ * from data, thus the function also examines its shape. The path of a problem starts with `path`.
314
+ */
315
+ export const kneeRuleProblem = (rule: unknown, path = "rule"): LawProblem | undefined => {
316
+ if (typeof rule !== "object" || rule === null || Array.isArray(rule)) return problem("knee", path, "The rule is not a record.");
317
+ const { kind, share, factor } = rule as Readonly<Record<string, unknown>>;
318
+ if (kind === "rise" || kind === "floor") {
319
+ if (typeof share === "number" && Number.isFinite(share) && share > 0) return undefined;
320
+ return problem("knee", `${path}.share`, `The share of the rule "${kind}" is ${String(share)}. It must be a finite number above 0.`);
321
+ }
322
+ if (kind === "slope") {
323
+ if (typeof factor === "number" && Number.isFinite(factor) && factor > 1) return undefined;
324
+ return problem("knee", `${path}.factor`, `The factor of the rule "slope" is ${String(factor)}. It must be a finite number above 1.`);
325
+ }
326
+ return problem("knee", `${path}.kind`, `The kind of the rule is ${JSON.stringify(kind) ?? "undefined"}. It must be one of ${KNEE_KINDS.join(", ")}.`);
327
+ };
328
+
329
+ /** An open value is a value of a search with the interval of its replicates. A null value or end is past the end of the search. */
330
+ export interface OpenValue {
331
+ readonly value: number | null;
332
+ readonly interval: OpenRange;
333
+ }
334
+
335
+ /**
336
+ * This function gives the open value of the values of the rows. The first value is the value of the
337
+ * estimate. A value past `end` is past the end of the search, and an infinite value is too.
338
+ */
339
+ export const openValueOf = (values: readonly number[], level: number, end: number): OpenValue => {
340
+ // The quantiles interpolate. A large finite number keeps each interpolation finite, and each end past the search becomes null.
341
+ const [value, ...spread] = values.map((entry) => (Number.isFinite(entry) ? entry : Number.MAX_VALUE));
342
+ const interval = intervalOf(value as number, spread, level);
343
+ const open = (entry: number): number | null => (entry > end ? null : entry);
344
+ return { value: open(value as number), interval: { low: open(interval.low), high: open(interval.high) } };
345
+ };
346
+
347
+ /** This function gives the crossing of the values of the rows. The flag `outside` tells that the value is outside `range`. */
348
+ const crossingFrom = (values: readonly number[], level: number, range: Range, end: number): Crossing => {
349
+ const found = openValueOf(values, level, end);
350
+ return { ...found, outside: found.value !== null && (found.value < range.low || found.value > range.high) };
351
+ };
352
+
353
+ /**
354
+ * A search is the setup of a search along one variable of a law. It holds the target variable, the level,
355
+ * the range and the grid, and the variables outside their range. The function `curveOf` gives the curve
356
+ * of one row of constants.
357
+ */
358
+ interface Search {
359
+ readonly target: Variable;
360
+ readonly level: number;
361
+ readonly search: Range;
362
+ readonly grid: readonly number[];
363
+ readonly unit: number;
364
+ readonly curveOf: (values: readonly number[]) => Curve;
365
+ readonly outside: readonly string[];
366
+ }
367
+
368
+ /**
369
+ * The result of a search along one variable of a law: the first load that passes the test, and the
370
+ * edge. The count `skipped` tells the replicates where the rule cannot apply. The crossing leaves them out.
371
+ */
372
+ interface Along {
373
+ readonly crossing: Crossing;
374
+ readonly edge: Crossing;
375
+ readonly skipped: number;
376
+ }
377
+
378
+ /**
379
+ * This function gives the grid of a search from `from` to `to` in `steps` steps, or its problem. A
380
+ * grid on the scale `log` starts above 0. The text `owner` names the variable of the search in a problem.
381
+ */
382
+ export const searchGrid = (from: number, to: number, steps: number, log: boolean, owner: string): Result<readonly number[], LawProblem> => {
383
+ if (!(Number.isFinite(from) && Number.isFinite(to) && from < to)) {
384
+ return err(problem("range", "from", `The search goes from ${from} to ${to}. It must go from a finite number to a larger finite number.`));
385
+ }
386
+ if (log && !(from > 0)) return err(problem("range", "from", `${owner} has the scale "log", thus the search starts above 0.`));
387
+ if (!(Number.isInteger(steps) && steps >= 2 && steps <= MAX_STEPS)) {
388
+ return err(problem("knee", "steps", `The search has ${steps} steps. It must have a whole number of steps from 2 to ${MAX_STEPS}.`));
389
+ }
390
+ return ok(
391
+ Array.from({ length: steps + 1 }, (_, index) =>
392
+ index === steps ? to : log ? from * (to / from) ** (index / steps) : from + ((to - from) * index) / steps,
393
+ ),
394
+ );
395
+ };
396
+
397
+ /**
398
+ * This function gives the setup of a search along one variable of a law, or its problem. The function
399
+ * `check` gives the problem of the test before the setup.
400
+ */
401
+ const searchOf = (law: Law, variable: string, options: KneeOptions, check: () => LawProblem | undefined): Result<Search, LawProblem> => {
402
+ const level = options.level ?? DEFAULT_LEVEL;
403
+ const noLevel = levelProblem(law, level, false);
404
+ if (noLevel !== undefined) return err(noLevel);
405
+ const target = law.variables.find((entry) => entry.id === variable);
406
+ if (target === undefined) return err(problem("point", "variable", `The law has no variable "${variable}".`));
407
+ const badTest = check();
408
+ if (badTest !== undefined) return err(badTest);
409
+
410
+ const at = options.at ?? {};
411
+ for (const name of Object.keys(at)) {
412
+ if (name === variable) return err(problem("point", `at.${name}`, `The point "at" gives "${name}", the variable of the search.`));
413
+ if (!law.variables.some((entry) => entry.id === name)) return err(problem("point", `at.${name}`, `The law has no variable "${name}".`));
414
+ }
415
+ const base: Record<string, number> = {};
416
+ for (const other of law.variables) {
417
+ if (other.id === variable) continue;
418
+ const value = at[other.id];
419
+ if (typeof value !== "number" || !Number.isFinite(value)) {
420
+ return err(problem("point", `at.${other.id}`, `The point "at" gives no finite value for the variable "${other.id}".`));
421
+ }
422
+ base[other.id] = value;
423
+ }
424
+
425
+ const from = options.from ?? target.min;
426
+ const to = options.to ?? target.max;
427
+ const log = target.scale === "log";
428
+ const grid = searchGrid(from, to, options.steps ?? KNEE_STEPS, log, `The variable "${variable}"`);
429
+ if (grid.tag === "err") return grid;
430
+ const names = law.constants.map((constant) => constant.id);
431
+ const program: Expr = law.form.program;
432
+ const curveOf =
433
+ (values: readonly number[]): Curve =>
434
+ (loads) =>
435
+ valuesAt(program, loads.map((load) => recordOf(names, values, { ...base, [variable]: load })));
436
+ const outside = law.variables
437
+ .filter((entry) => entry.id !== variable && ((base[entry.id] as number) < entry.min || (base[entry.id] as number) > entry.max))
438
+ .map((entry) => entry.id);
439
+ return ok({ target, level, search: { low: from, high: to }, grid: grid.value, unit: log ? 0 : to - from, curveOf, outside });
440
+ };
441
+
442
+ /** This function searches a law for the first load that passes a test, in the constants and in each replicate. */
443
+ const along = (law: Law, setup: Search, testOf: TestOf): Result<Along, LawProblem> => {
444
+ const rows = [
445
+ { path: "constants", values: law.constants.map((constant) => constant.value) },
446
+ ...law.replicates.map((row, index) => ({ path: `replicates[${index}]`, values: row })),
447
+ ];
448
+ const crossings: number[] = [];
449
+ const edges: number[] = [];
450
+ let skipped = 0;
451
+ for (const row of rows) {
452
+ const result = rowOf(setup.curveOf(row.values), row.path, testOf, setup.grid, setup.unit);
453
+ if (result.tag === "err") return result;
454
+ edges.push(result.value.edge);
455
+ const { crossing } = result.value;
456
+ if (crossing === undefined) {
457
+ // The first crossing is the crossing of the estimate. Thus the rule must apply to the constants.
458
+ if (row.path === "constants") return err(problem("knee", row.path, "The rule cannot apply to the constants of the law."));
459
+ skipped += 1;
460
+ } else {
461
+ crossings.push(crossing);
462
+ }
463
+ }
464
+ const range: Range = { low: setup.target.min, high: setup.target.max };
465
+ return ok({
466
+ crossing: crossingFrom(crossings, setup.level, range, setup.search.high),
467
+ edge: crossingFrom(edges, setup.level, range, setup.search.high),
468
+ skipped,
469
+ });
470
+ };
471
+
472
+ /** This function gives the floor of one row: its least value on the grid, at the loads before its edge. */
473
+ const rowFloor = (grid: readonly number[], values: readonly (number | undefined)[], edge: number, start: number): Floor => {
474
+ let floor: Floor = { load: grid[0] as number, value: start };
475
+ grid.forEach((load, index) => {
476
+ const value = values[index];
477
+ if (load < edge && value !== undefined && value < floor.value) floor = { load, value };
478
+ });
479
+ return floor;
480
+ };
481
+
482
+ /**
483
+ * This function gives the floor of a law on the grid of a search. The floor is the least value of the
484
+ * law with its constants, at the loads before its edge. The rule `floor` needs a floor above 0.
485
+ */
486
+ const floorOf = (law: Law, setup: Search): Result<Floor, LawProblem> => {
487
+ const curve = setup.curveOf(law.constants.map((constant) => constant.value));
488
+ const values = curve(setup.grid);
489
+ const start = values[0];
490
+ if (start === undefined) return err(problem("value", "constants", `The law has no value at the start of the search, ${setup.grid[0]}.`));
491
+ const floor = rowFloor(setup.grid, values, edgeOf(curve, setup.grid, values, start), start);
492
+ if (!(floor.value > 0)) {
493
+ return err(problem("knee", "constants", `The rule "floor" needs a floor above 0. The floor is ${floor.value} at ${floor.load}.`));
494
+ }
495
+ return ok(floor);
496
+ };
497
+
498
+ /**
499
+ * This function gives the test of the rule `floor` for one row. From the load of the floor of the
500
+ * row, the value is above `1 + share` times that floor. A row with no floor above 0 has no test.
501
+ */
502
+ const floorTest =
503
+ (share: number): TestOf =>
504
+ ({ curve, start, grid, values, edge }) => {
505
+ const floor = rowFloor(grid, values, edge, start);
506
+ if (!(floor.value > 0)) return ok(undefined);
507
+ const limit = (1 + share) * floor.value;
508
+ return ok((load, value = valueOf(curve, load)) => load >= floor.load && value !== undefined && value > limit);
509
+ };
510
+
511
+ /**
512
+ * This function gives the largest count of replicates that a knee interval can leave out. The count is
513
+ * at most the replicates of one tail of the level, and at least `leastCount` replicates stay.
514
+ */
515
+ const mostSkipped = (replicates: number, level: number): number =>
516
+ Math.min(Math.floor((replicates * (1 - level)) / 2 + 1e-9), replicates - leastCount(level));
517
+
518
+ /**
519
+ * This function gives the knee of a law along one variable, with an interval. It also gives the
520
+ * edge: the first load where the law has no finite value.
521
+ *
522
+ * The point `at` of the options gives each other variable of the law. The function evaluates the
523
+ * law with its constants, then with each replicate. The interval of the knee and of the edge is the
524
+ * share `level` of the values of the replicates, made wider to hold the value.
525
+ *
526
+ * The search tests a grid of loads, then a bisection finds each crossing. A crossing between two
527
+ * loads of the grid is found. Two edges in one step of the grid can hide the first edge.
528
+ *
529
+ * The rule `floor` gives each row its own floor. Thus the knee of a row is always after its floor,
530
+ * and the uncertainty of the floor is in the interval. A replicate with no floor above 0 has no knee:
531
+ * the field `noFloor` counts these replicates, and the interval leaves them out. When they are more
532
+ * than one tail of the level, the function gives a problem.
533
+ *
534
+ * The function gives a problem for a variable or a point that the law cannot read. A bad search
535
+ * range, rule or count of steps, and a level that the law cannot show, also give a problem. The last
536
+ * problems are a law with no value at the start of the search, and a rule that cannot apply there.
537
+ */
538
+ export const lawKnee = (law: Law, variable: string, rule: KneeRule, options: KneeOptions = {}): Result<Knee, LawProblem> => {
539
+ const setup = searchOf(law, variable, options, () => kneeRuleProblem(rule));
540
+ if (setup.tag === "err") return setup;
541
+ let floor: Floor | undefined;
542
+ if (rule.kind === "floor") {
543
+ const least = floorOf(law, setup.value);
544
+ if (least.tag === "err") return least;
545
+ floor = least.value;
546
+ }
547
+ const found = along(law, setup.value, rule.kind === "floor" ? floorTest(rule.share) : ruleTest(rule));
548
+ if (found.tag === "err") return found;
549
+ const { target, level, search, outside } = setup.value;
550
+ const knee: Knee = { variable, unit: target.unit, rule, level, search, knee: found.value.crossing, edge: found.value.edge, outside };
551
+ if (floor === undefined) return ok(knee);
552
+ const { skipped } = found.value;
553
+ const most = mostSkipped(law.replicates.length, level);
554
+ if (skipped > most) {
555
+ const message = `The rule "floor" needs a floor above 0. ${skipped} of ${law.replicates.length} replicates have a floor of 0 or less. The interval of the level ${level} can leave out at most ${most}.`;
556
+ return err(problem("knee", "replicates", message));
557
+ }
558
+ return ok({ ...knee, floor, noFloor: skipped });
559
+ };
560
+
561
+ /**
562
+ * A reach is the result of a search along one variable for the first load where a law is above an
563
+ * amount. The loads are in the unit of the variable. Before the `crossing`, the law holds the amount.
564
+ *
565
+ * Thus for a law that grows along the variable, the crossing is the largest load that holds the
566
+ * amount. The `edge` and the list `outside` are as in a knee.
567
+ */
568
+ export interface Reach {
569
+ readonly variable: string;
570
+ readonly unit: string;
571
+ /** This amount is the amount of the search, in the unit of the measure of the law. */
572
+ readonly amount: number;
573
+ readonly level: number;
574
+ readonly search: Range;
575
+ readonly crossing: Crossing;
576
+ readonly edge: Crossing;
577
+ readonly outside: readonly string[];
578
+ }
579
+
580
+ /**
581
+ * This function gives the first load along one variable where a law is above an amount, with an
582
+ * interval. This is the inverse query of one law: the largest load that one limit holds.
583
+ *
584
+ * The options are the options of `lawKnee`. When the law is above the amount at the start of the
585
+ * search, the crossing is the start. When the law holds the amount on all of the search, the
586
+ * crossing is null. A pole is above each amount, so the crossing is before the pole.
587
+ *
588
+ * The function gives each problem of `lawKnee` that is not about a rule. An amount that is not finite
589
+ * gives a problem. An amount that does not convert to the unit of the measure also gives a problem.
590
+ */
591
+ export const lawReach = (law: Law, variable: string, amount: Quantity, options: KneeOptions = {}): Result<Reach, LawProblem> => {
592
+ if (!isQuantity(amount) || !Number.isFinite(amount.value)) {
593
+ return err(problem("value", "amount", "The amount is not a finite quantity."));
594
+ }
595
+ if (!convertible(amount.unit, law.measure.unit)) {
596
+ const why = whyNotConvertible(amount.unit, law.measure.unit) ?? "the units are different";
597
+ return err(problem("unit", "amount", `The amount is in "${amount.unit}", and the measure of the law is in "${law.measure.unit}": ${why}.`));
598
+ }
599
+ const value = valueIn(amount, law.measure.unit);
600
+ const setup = searchOf(law, variable, options, () => undefined);
601
+ if (setup.tag === "err") return setup;
602
+ const found = along(law, setup.value, amountTest(value));
603
+ if (found.tag === "err") return found;
604
+ const { target, level, search, outside } = setup.value;
605
+ return ok({ variable, unit: target.unit, amount: value, level, search, crossing: found.value.crossing, edge: found.value.edge, outside });
606
+ };