@mark1russell7/capacity 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +1110 -2
- package/build/index.d.ts +858 -0
- package/build/index.d.ts.map +1 -0
- package/build/index.js +1713 -0
- package/build/index.js.map +1 -0
- package/build/instance-check-Bt-SI8va.js +1732 -0
- package/build/instance-check-Bt-SI8va.js.map +1 -0
- package/build/instance-sZmVOOvz.d.ts +801 -0
- package/build/instance-sZmVOOvz.d.ts.map +1 -0
- package/build/schema.d.ts +69 -0
- package/build/schema.d.ts.map +1 -0
- package/build/schema.js +325 -0
- package/build/schema.js.map +1 -0
- package/limits/alerts-routes.line.json +78 -0
- package/limits/alerts-scale.limits.json +10 -0
- package/limits/alerts-start-gate.limits.json +1149 -0
- package/limits/alerts-start-routes-limit-home.bracket.json +543 -0
- package/limits/alerts-start-routes-limit-mid.bracket.json +464 -0
- package/limits/alerts-start-routes-limit.bracket.json +579 -0
- package/limits/alerts-tail-gate.limits.json +610 -0
- package/package.json +85 -3
- package/src/app-check.ts +477 -0
- package/src/app-metrics.ts +105 -0
- package/src/app.ts +239 -0
- package/src/check.ts +253 -0
- package/src/composition.ts +680 -0
- package/src/demand.ts +312 -0
- package/src/fit.ts +153 -0
- package/src/forms.ts +358 -0
- package/src/gate.ts +237 -0
- package/src/index.ts +143 -0
- package/src/instance-check.ts +122 -0
- package/src/instance.ts +84 -0
- package/src/knee.ts +606 -0
- package/src/law.ts +236 -0
- package/src/limit.ts +112 -0
- package/src/names.ts +19 -0
- package/src/observe.ts +74 -0
- package/src/program.ts +74 -0
- package/src/scale.ts +617 -0
- package/src/schema.ts +263 -0
- package/src/value.ts +206 -0
- package/src/workload-check.ts +130 -0
- package/src/workload.ts +88 -0
|
@@ -0,0 +1,680 @@
|
|
|
1
|
+
import { err, ok, type Result } from "@mark1russell7/optional";
|
|
2
|
+
import {
|
|
3
|
+
UnitError,
|
|
4
|
+
convertible,
|
|
5
|
+
divideUnits,
|
|
6
|
+
isCanonicalUnit,
|
|
7
|
+
kindOf,
|
|
8
|
+
multiplyUnits,
|
|
9
|
+
parseUnit,
|
|
10
|
+
factorOf,
|
|
11
|
+
isQuantity,
|
|
12
|
+
whyNotConvertible,
|
|
13
|
+
} from "@mark1russell7/quantity";
|
|
14
|
+
import { instancePointOf, loadPointOf, totalRate, type Load } from "./demand.ts";
|
|
15
|
+
import { DEFAULT_LEVEL, type Law, type Measure, type Problem, type ProblemCode } from "./law.ts";
|
|
16
|
+
import { NAME, SLUG, finite, repeated } from "./names.ts";
|
|
17
|
+
import { recordOf, valuesAt } from "./program.ts";
|
|
18
|
+
import { edgePointOf, edgeValuesOf, heldValue, intervalOf, levelProblem, pointValuesOf, runOf, type LevelOptions, type LoadPoint, type Range } from "./value.ts";
|
|
19
|
+
import { demandProblems } from "./workload-check.ts";
|
|
20
|
+
import { RATE, type Amounts, type Demand, type WorkloadClass, type WorkloadProblemCode } from "./workload.ts";
|
|
21
|
+
|
|
22
|
+
/** This text is the format of a composition file. */
|
|
23
|
+
export const COMPOSITION_FORMAT = "capacity-composition/1";
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* The scope of a law term tells where the law applies. The scope `instance` gives one part with no
|
|
27
|
+
* class. The scope `each` gives one part for each class of the demand. A list of class ids gives
|
|
28
|
+
* one part for each class in the list.
|
|
29
|
+
*/
|
|
30
|
+
export type Over = "instance" | "each" | readonly string[];
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* A law term adds a law to a composition, times `factor` (1 when the term gives none). The field
|
|
34
|
+
* `load` tells which rate the variable `rate` of the law reads. A term over the instance always
|
|
35
|
+
* reads the total rate.
|
|
36
|
+
*
|
|
37
|
+
* A term with a `base` gives the change of its law from the base point. The change is the value at
|
|
38
|
+
* the load point less the value at the base point. The base point is the load point, with the
|
|
39
|
+
* amount of `base` for each variable that `base` names. Use it for a law of a ladder of one level.
|
|
40
|
+
* That ladder holds the other levels at a base point. A demand with no amount for a variable of
|
|
41
|
+
* `base` stays at the base point, thus the change is 0.
|
|
42
|
+
*/
|
|
43
|
+
export interface LawTerm {
|
|
44
|
+
readonly law: string;
|
|
45
|
+
readonly over: Over;
|
|
46
|
+
readonly load?: Load | undefined;
|
|
47
|
+
readonly factor?: number | undefined;
|
|
48
|
+
readonly base?: Amounts | undefined;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* A nested term adds the value of a different composition over the same demand, times `factor`.
|
|
53
|
+
* Thus layer 3 of an app names layer 2, and layer 2 names layer 1. No layer copies the terms of
|
|
54
|
+
* an other layer.
|
|
55
|
+
*/
|
|
56
|
+
export interface NestedTerm {
|
|
57
|
+
readonly composition: string;
|
|
58
|
+
readonly factor?: number | undefined;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** A composition term is a law term or a nested term. */
|
|
62
|
+
export type CompositionTerm = LawTerm | NestedTerm;
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* A composition gives one measure of a subject as a sum of laws over a demand. Each term gives
|
|
66
|
+
* parts, and the value is the sum of the parts in the unit of the measure.
|
|
67
|
+
*
|
|
68
|
+
* The units of a law term tell if a part is the value of the law times a rate. A law of the CPU
|
|
69
|
+
* time of one request, in `{core}·ms/{request}`, gives `{core}` times the rate of its class. A law
|
|
70
|
+
* of the memory of an instance, in `MiB`, gives `MiB` with no rate.
|
|
71
|
+
*/
|
|
72
|
+
export interface Composition {
|
|
73
|
+
readonly format: typeof COMPOSITION_FORMAT;
|
|
74
|
+
readonly id: string;
|
|
75
|
+
readonly title: string;
|
|
76
|
+
readonly subject: string;
|
|
77
|
+
readonly measure: Measure;
|
|
78
|
+
readonly terms: readonly CompositionTerm[];
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** A catalog holds the laws and the compositions that the terms of a composition can name. */
|
|
82
|
+
export interface Catalog {
|
|
83
|
+
readonly laws: readonly Law[];
|
|
84
|
+
readonly compositions?: readonly Composition[];
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** These options set the level of the intervals and the state of the instance: its heap and its age, for example. */
|
|
88
|
+
export interface CompositionOptions extends LevelOptions {
|
|
89
|
+
readonly given?: Amounts;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** A composition problem code names the part of a composition, or of a query, that is not correct. */
|
|
93
|
+
export type CompositionProblemCode = ProblemCode | WorkloadProblemCode | "term" | "law" | "composition";
|
|
94
|
+
|
|
95
|
+
/** A composition problem tells what is not correct, and where. */
|
|
96
|
+
export type CompositionProblem = Problem<CompositionProblemCode>;
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* A part value is one part of a composition value, in the unit of the composition. The `weight`
|
|
100
|
+
* is the number that multiplies the value of the law or of the nested composition. The ends of a
|
|
101
|
+
* range change places when the weight is less than 0.
|
|
102
|
+
*/
|
|
103
|
+
interface PartBase {
|
|
104
|
+
readonly term: number;
|
|
105
|
+
readonly weight: number;
|
|
106
|
+
readonly value: number;
|
|
107
|
+
readonly interval: Range;
|
|
108
|
+
readonly run: Range;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* A law part is the value of a law at the point of one class. When `class` is null, it is the
|
|
113
|
+
* value at the point of the instance. A term with a base gives two parts. The first part is at the load point.
|
|
114
|
+
* The second part is at the base point, with `base` true and the weight times -1.
|
|
115
|
+
*/
|
|
116
|
+
export interface LawPart extends PartBase {
|
|
117
|
+
readonly kind: "law";
|
|
118
|
+
readonly law: string;
|
|
119
|
+
readonly class: string | null;
|
|
120
|
+
readonly base: boolean;
|
|
121
|
+
readonly outside: readonly string[];
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/** A nested part is the value of a nested composition, with its own parts. */
|
|
125
|
+
export interface NestedPart extends PartBase {
|
|
126
|
+
readonly kind: "composition";
|
|
127
|
+
readonly composition: string;
|
|
128
|
+
readonly parts: readonly PartValue[];
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** A part value is a law part or a nested part. */
|
|
132
|
+
export type PartValue = LawPart | NestedPart;
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* A composition value is the answer of a composition over a demand, in the unit of its measure.
|
|
136
|
+
*
|
|
137
|
+
* Replicate `i` is the sum of row `i` of each law, each times its weight. The `interval` is the
|
|
138
|
+
* share `level` of the replicates, made wider to hold the value. The range `run` is where one
|
|
139
|
+
* measured run falls. The value is an extrapolation when `extrapolated` is true: a part reads a
|
|
140
|
+
* variable outside its range.
|
|
141
|
+
*/
|
|
142
|
+
export interface CompositionValue {
|
|
143
|
+
readonly value: number;
|
|
144
|
+
readonly unit: string;
|
|
145
|
+
readonly level: number;
|
|
146
|
+
readonly interval: Range;
|
|
147
|
+
readonly run: Range;
|
|
148
|
+
readonly replicates: readonly number[];
|
|
149
|
+
readonly parts: readonly PartValue[];
|
|
150
|
+
readonly extrapolated: boolean;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
const problem = (code: CompositionProblemCode, path: string, message: string): CompositionProblem => ({ code, path, message });
|
|
154
|
+
|
|
155
|
+
/** This function tells if a term names a law. */
|
|
156
|
+
export const isLawTerm = (term: CompositionTerm): term is LawTerm => Object.hasOwn(term, "law");
|
|
157
|
+
|
|
158
|
+
/** This function gives the reason that the values of a unit do not add, or undefined when they add. */
|
|
159
|
+
const sumUnitProblem = (unit: string): string | undefined => {
|
|
160
|
+
if (!isCanonicalUnit(unit)) return `"${unit}" is not a canonical unit.`;
|
|
161
|
+
const parsed = parseUnit(unit);
|
|
162
|
+
if (parsed.log) return `"${unit}" is a level, and levels do not add.`;
|
|
163
|
+
if (parsed.offset !== undefined) return `"${unit}" is an absolute temperature, and absolute temperatures do not add.`;
|
|
164
|
+
return undefined;
|
|
165
|
+
};
|
|
166
|
+
|
|
167
|
+
const NOT_SLUG = 'is not lower-case words joined by ".", "-" or "/".';
|
|
168
|
+
|
|
169
|
+
/**
|
|
170
|
+
* This function examines a composition and gives each problem that it finds. A composition with no
|
|
171
|
+
* problem gives an empty list.
|
|
172
|
+
*
|
|
173
|
+
* It examines the format, the ids, the title and the unit of the measure. It examines that each
|
|
174
|
+
* term names a law or a composition and has a correct scope. It examines that each factor is a
|
|
175
|
+
* finite number other than 0. It does not look for the laws: `compositionValue` does that.
|
|
176
|
+
*/
|
|
177
|
+
export const checkComposition = (composition: Composition): readonly CompositionProblem[] => {
|
|
178
|
+
const problems: CompositionProblem[] = [];
|
|
179
|
+
const add = (code: CompositionProblemCode, path: string, message: string): void => {
|
|
180
|
+
problems.push(problem(code, path, message));
|
|
181
|
+
};
|
|
182
|
+
if (composition.format !== COMPOSITION_FORMAT) add("format", "format", `The format is not "${COMPOSITION_FORMAT}".`);
|
|
183
|
+
for (const [path, id] of [
|
|
184
|
+
["id", composition.id],
|
|
185
|
+
["subject", composition.subject],
|
|
186
|
+
["measure.id", composition.measure.id],
|
|
187
|
+
] as const) {
|
|
188
|
+
if (!SLUG.test(id)) add("id", path, `"${id}" ${NOT_SLUG}`);
|
|
189
|
+
}
|
|
190
|
+
if (composition.title.trim() === "") add("id", "title", "The title is empty.");
|
|
191
|
+
const unit = sumUnitProblem(composition.measure.unit);
|
|
192
|
+
if (unit !== undefined) add("unit", "measure.unit", unit);
|
|
193
|
+
if (composition.terms.length === 0) add("term", "terms", "The composition has no term.");
|
|
194
|
+
|
|
195
|
+
for (const [index, term] of composition.terms.entries()) {
|
|
196
|
+
const path = `terms[${index}]`;
|
|
197
|
+
if (term.factor !== undefined && (!finite(term.factor) || term.factor === 0)) {
|
|
198
|
+
add("factor", `${path}.factor`, `The factor ${term.factor} is not a finite number other than 0.`);
|
|
199
|
+
}
|
|
200
|
+
if (!isLawTerm(term)) {
|
|
201
|
+
if (!SLUG.test(term.composition)) add("id", `${path}.composition`, `"${term.composition}" ${NOT_SLUG}`);
|
|
202
|
+
else if (term.composition === composition.id) add("composition", `${path}.composition`, "The composition names itself.");
|
|
203
|
+
continue;
|
|
204
|
+
}
|
|
205
|
+
if (!SLUG.test(term.law)) add("id", `${path}.law`, `"${term.law}" ${NOT_SLUG}`);
|
|
206
|
+
if (typeof term.over !== "string") {
|
|
207
|
+
if (term.over.length === 0) add("class", `${path}.over`, "The list of classes is empty.");
|
|
208
|
+
for (const [at, id] of term.over.entries()) {
|
|
209
|
+
if (!SLUG.test(id)) add("id", `${path}.over[${at}]`, `"${id}" ${NOT_SLUG}`);
|
|
210
|
+
}
|
|
211
|
+
const twice = repeated(term.over);
|
|
212
|
+
if (twice !== undefined) add("class", `${path}.over`, `The list has the class "${twice}" two times.`);
|
|
213
|
+
} else if (term.over !== "instance" && term.over !== "each") {
|
|
214
|
+
add("term", `${path}.over`, `The scope "${String(term.over)}" is not "instance", "each" or a list of classes.`);
|
|
215
|
+
}
|
|
216
|
+
if (term.over === "instance" && term.load === "class") {
|
|
217
|
+
add("term", `${path}.load`, "A term over the instance has no class. Its law reads the total rate.");
|
|
218
|
+
}
|
|
219
|
+
if (term.base !== undefined) {
|
|
220
|
+
const names = Object.keys(term.base);
|
|
221
|
+
if (names.length === 0) add("term", `${path}.base`, "The base names no variable.");
|
|
222
|
+
for (const name of names) {
|
|
223
|
+
const where = `${path}.base.${name}`;
|
|
224
|
+
if (!NAME.test(name)) add("variable", where, `"${name}" is not a name: a lower-case letter, then letters and digits.`);
|
|
225
|
+
else if (name === RATE) add("variable", where, "The rate comes from the demand. A base does not hold it.");
|
|
226
|
+
else if (!isQuantity(term.base[name])) add("amount", where, `The amount of "${name}" is not a finite amount in a canonical unit.`);
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
return problems;
|
|
231
|
+
};
|
|
232
|
+
|
|
233
|
+
/**
|
|
234
|
+
* A weight multiplies the value of the law of a term. It is the number `by`. When the units of the
|
|
235
|
+
* law need a rate, it is also times the rate of the part in the unit `rate`.
|
|
236
|
+
*/
|
|
237
|
+
interface Weight {
|
|
238
|
+
readonly by: number;
|
|
239
|
+
readonly rate: string | undefined;
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
/**
|
|
243
|
+
* This function gives the weight that changes a value in `from` to a value in `to`. The quotient
|
|
244
|
+
* `to / from` decides. A quotient with no dimension needs no rate. A quotient that is a rate needs
|
|
245
|
+
* the rate of the part, in the unit of the quotient.
|
|
246
|
+
*/
|
|
247
|
+
const weightOf = (from: string, to: string, factor: number, path: string): Result<Weight, CompositionProblem> => {
|
|
248
|
+
try {
|
|
249
|
+
const per = divideUnits(to, from);
|
|
250
|
+
if (convertible(per, "count")) return ok({ by: factor * factorOf(from, to), rate: undefined });
|
|
251
|
+
if (kindOf(per) === "frequency") return ok({ by: factor * factorOf(multiplyUnits(from, per), to), rate: per });
|
|
252
|
+
return err(problem("unit", path, `The law gives "${from}". That unit does not give "${to}", alone or times a rate.`));
|
|
253
|
+
} catch (error) {
|
|
254
|
+
if (error instanceof UnitError) return err(problem("unit", path, `The law gives "${from}", and "${to}" does not come from it: ${error.message}`));
|
|
255
|
+
throw error;
|
|
256
|
+
}
|
|
257
|
+
};
|
|
258
|
+
|
|
259
|
+
/** This function gives the number that the rate of a class is in the unit of a weight, or the problem that stops it. */
|
|
260
|
+
const classRate = (demand: Demand, id: string, unit: string, path: string): Result<number, CompositionProblem> => {
|
|
261
|
+
const rate = (demand.classes.find((entry) => entry.id === id) as WorkloadClass).rate;
|
|
262
|
+
if (!convertible(rate.unit, unit)) {
|
|
263
|
+
const why = whyNotConvertible(rate.unit, unit) ?? "the units are different";
|
|
264
|
+
return err(problem("unit", `${path}.rate`, `The rate of the class "${id}" is in "${rate.unit}". The law needs a rate in "${unit}": ${why}.`));
|
|
265
|
+
}
|
|
266
|
+
return ok(rate.value * factorOf(rate.unit, unit));
|
|
267
|
+
};
|
|
268
|
+
|
|
269
|
+
/** This function gives the number that the total rate of a demand is in the unit of a weight, or the problem that stops it. */
|
|
270
|
+
const instanceRate = (demand: Demand, unit: string, path: string): Result<number, CompositionProblem> => {
|
|
271
|
+
const total = totalRate(demand, unit);
|
|
272
|
+
return total.tag === "err" ? err(under(total.error, path)) : ok(total.value.value);
|
|
273
|
+
};
|
|
274
|
+
|
|
275
|
+
/**
|
|
276
|
+
* This function gives the problem of the base of a term for its law, or undefined. Each name of the
|
|
277
|
+
* base is a variable of the law, and its amount converts to the unit of that variable.
|
|
278
|
+
*/
|
|
279
|
+
const baseProblem = (law: Law, base: Amounts, path: string): CompositionProblem | undefined => {
|
|
280
|
+
for (const [name, amount] of Object.entries(base)) {
|
|
281
|
+
const variable = law.variables.find((each) => each.id === name);
|
|
282
|
+
if (variable === undefined) return problem("variable", `${path}.${name}`, `The law "${law.id}" has no variable "${name}".`);
|
|
283
|
+
if (!convertible(amount.unit, variable.unit)) {
|
|
284
|
+
const why = whyNotConvertible(amount.unit, variable.unit) ?? "the units are different";
|
|
285
|
+
return problem("unit", `${path}.${name}`, `The variable "${name}" of the law "${law.id}" is in "${variable.unit}", not in "${amount.unit}": ${why}.`);
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
return undefined;
|
|
289
|
+
};
|
|
290
|
+
|
|
291
|
+
/** This function gives the amounts of a base that no list of amounts gives. The point holds them at the base. */
|
|
292
|
+
const heldOf = (base: Amounts, lists: readonly Amounts[]): Amounts =>
|
|
293
|
+
Object.fromEntries(Object.entries(base).filter(([name]) => !lists.some((amounts) => Object.hasOwn(amounts, name))));
|
|
294
|
+
|
|
295
|
+
/** This function gives the base point of a term: the load point, with the amount of the base for each variable that it names. */
|
|
296
|
+
const basePointOf = (law: Law, point: LoadPoint, base: Amounts): LoadPoint => {
|
|
297
|
+
const next: Record<string, number> = { ...point };
|
|
298
|
+
for (const [name, amount] of Object.entries(base)) {
|
|
299
|
+
const variable = law.variables.find((each) => each.id === name) as Law["variables"][number];
|
|
300
|
+
next[name] = amount.value * factorOf(amount.unit, variable.unit);
|
|
301
|
+
}
|
|
302
|
+
return next;
|
|
303
|
+
};
|
|
304
|
+
|
|
305
|
+
/** The sum of the parts of one composition, with the change from its interval to its run. */
|
|
306
|
+
interface Sum {
|
|
307
|
+
readonly unit: string;
|
|
308
|
+
readonly value: number;
|
|
309
|
+
readonly replicates: readonly number[];
|
|
310
|
+
readonly widen: Range;
|
|
311
|
+
readonly parts: readonly PartValue[];
|
|
312
|
+
readonly extrapolated: boolean;
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
/** This function gives a range times a weight. The ends change places for a weight less than 0. */
|
|
316
|
+
const times = (range: Range, weight: number): Range =>
|
|
317
|
+
weight >= 0 ? { low: weight * range.low, high: weight * range.high } : { low: weight * range.high, high: weight * range.low };
|
|
318
|
+
|
|
319
|
+
/** This function gives a problem of a query with the path of its term in front. */
|
|
320
|
+
const under = (found: Problem<string>, path: string): CompositionProblem => ({
|
|
321
|
+
code: found.code as CompositionProblemCode,
|
|
322
|
+
path: `${path}.${found.path}`,
|
|
323
|
+
message: found.message,
|
|
324
|
+
});
|
|
325
|
+
|
|
326
|
+
/** This function gives a map of records by id, or the problem of an id that the list has two times. */
|
|
327
|
+
const byId = <T extends { readonly id: string }>(records: readonly T[], what: string): Result<Map<string, T>, CompositionProblem> => {
|
|
328
|
+
const map = new Map<string, T>();
|
|
329
|
+
for (const [index, record] of records.entries()) {
|
|
330
|
+
if (map.has(record.id)) return err(problem(what === "laws" ? "law" : "composition", `${what}[${index}].id`, `The catalog has two ${what} with the id "${record.id}".`));
|
|
331
|
+
map.set(record.id, record);
|
|
332
|
+
}
|
|
333
|
+
return ok(map);
|
|
334
|
+
};
|
|
335
|
+
|
|
336
|
+
/** A prepared composition holds each law and each nested composition that a composition reads, and the count of its rows. */
|
|
337
|
+
export interface Prepared {
|
|
338
|
+
readonly composition: Composition;
|
|
339
|
+
readonly reads: ReadonlyMap<string, Law>;
|
|
340
|
+
readonly nested: ReadonlyMap<string, Composition>;
|
|
341
|
+
/** This count is the count of replicates of the composition: the least count of the laws that it reads. */
|
|
342
|
+
readonly rows: number;
|
|
343
|
+
readonly level: number;
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
/**
|
|
347
|
+
* This function examines a composition and its catalog one time, for the queries over many demands.
|
|
348
|
+
* It gives each problem of `compositionValue` that does not come from a demand.
|
|
349
|
+
*/
|
|
350
|
+
export const preparedOf = (composition: Composition, catalog: Catalog, level: number): Result<Prepared, CompositionProblem> => {
|
|
351
|
+
const own = checkComposition(composition)[0];
|
|
352
|
+
if (own !== undefined) return err(own);
|
|
353
|
+
const laws = byId(catalog.laws, "laws");
|
|
354
|
+
if (laws.tag === "err") return laws;
|
|
355
|
+
const nested = byId(catalog.compositions ?? [], "compositions");
|
|
356
|
+
if (nested.tag === "err") return nested;
|
|
357
|
+
|
|
358
|
+
// The walk finds each law that the composition reads, and each problem of a name or a cycle.
|
|
359
|
+
const reads = new Map<string, Law>();
|
|
360
|
+
const walked = new Set<string>();
|
|
361
|
+
const walk = (at: Composition, prefix: string, stack: readonly string[]): CompositionProblem | undefined => {
|
|
362
|
+
for (const [index, term] of at.terms.entries()) {
|
|
363
|
+
const path = `${prefix}terms[${index}]`;
|
|
364
|
+
if (isLawTerm(term)) {
|
|
365
|
+
const law = laws.value.get(term.law);
|
|
366
|
+
if (law === undefined) return problem("law", `${path}.law`, `The catalog has no law "${term.law}".`);
|
|
367
|
+
const badBase = baseProblem(law, term.base ?? {}, `${path}.base`);
|
|
368
|
+
if (badBase !== undefined) return badBase;
|
|
369
|
+
reads.set(law.id, law);
|
|
370
|
+
continue;
|
|
371
|
+
}
|
|
372
|
+
if (stack.includes(term.composition)) {
|
|
373
|
+
return problem("composition", `${path}.composition`, `The compositions make a cycle: ${[...stack, term.composition].join(" → ")}.`);
|
|
374
|
+
}
|
|
375
|
+
const next = nested.value.get(term.composition);
|
|
376
|
+
if (next === undefined) return problem("composition", `${path}.composition`, `The catalog has no composition "${term.composition}".`);
|
|
377
|
+
if (walked.has(next.id)) continue;
|
|
378
|
+
const inner = `compositions.${next.id}.`;
|
|
379
|
+
const bad = checkComposition(next)[0];
|
|
380
|
+
if (bad !== undefined) return { ...bad, path: `${inner}${bad.path}` };
|
|
381
|
+
const deeper = walk(next, inner, [...stack, next.id]);
|
|
382
|
+
if (deeper !== undefined) return deeper;
|
|
383
|
+
walked.add(next.id);
|
|
384
|
+
}
|
|
385
|
+
return undefined;
|
|
386
|
+
};
|
|
387
|
+
const broken = walk(composition, "", [composition.id]);
|
|
388
|
+
if (broken !== undefined) return err(broken);
|
|
389
|
+
|
|
390
|
+
for (const law of reads.values()) {
|
|
391
|
+
const noLevel = levelProblem(law, level, true);
|
|
392
|
+
if (noLevel !== undefined) return err(under(noLevel, `laws.${law.id}`));
|
|
393
|
+
}
|
|
394
|
+
const rows = Math.min(...[...reads.values()].map((law) => law.replicates.length));
|
|
395
|
+
return ok({ composition, reads, nested: nested.value, rows, level });
|
|
396
|
+
};
|
|
397
|
+
|
|
398
|
+
/** A leaf is the law of one part at its load point, times its weight. The path names the part in a problem. */
|
|
399
|
+
interface Leaf {
|
|
400
|
+
readonly kind: "law";
|
|
401
|
+
readonly term: number;
|
|
402
|
+
readonly law: Law;
|
|
403
|
+
readonly class: string | null;
|
|
404
|
+
readonly base: boolean;
|
|
405
|
+
readonly weight: number;
|
|
406
|
+
readonly point: LoadPoint;
|
|
407
|
+
readonly path: string;
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
/** A branch is the tree of a nested composition, times its weight. */
|
|
411
|
+
interface Branch {
|
|
412
|
+
readonly kind: "composition";
|
|
413
|
+
readonly term: number;
|
|
414
|
+
readonly composition: string;
|
|
415
|
+
readonly weight: number;
|
|
416
|
+
readonly tree: Tree;
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
/** A tree is the parts of one composition over one demand, before the laws give their values. */
|
|
420
|
+
interface Tree {
|
|
421
|
+
readonly unit: string;
|
|
422
|
+
readonly nodes: readonly (Leaf | Branch)[];
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
/** This function gives the tree of a prepared composition over a demand, or the problem that stops it. It does not examine the demand. */
|
|
426
|
+
const treeOf = (prepared: Prepared, demand: Demand, given: Amounts): Result<Tree, CompositionProblem> => {
|
|
427
|
+
const trees = new Map<string, Tree>();
|
|
428
|
+
const build = (at: Composition, prefix: string): Result<Tree, CompositionProblem> => {
|
|
429
|
+
const unit = at.measure.unit;
|
|
430
|
+
const nodes: (Leaf | Branch)[] = [];
|
|
431
|
+
for (const [index, term] of at.terms.entries()) {
|
|
432
|
+
const path = `${prefix}terms[${index}]`;
|
|
433
|
+
const factor = term.factor ?? 1;
|
|
434
|
+
if (!isLawTerm(term)) {
|
|
435
|
+
const inner = prepared.nested.get(term.composition) as Composition;
|
|
436
|
+
let tree = trees.get(inner.id);
|
|
437
|
+
if (tree === undefined) {
|
|
438
|
+
const found = build(inner, `compositions.${inner.id}.`);
|
|
439
|
+
if (found.tag === "err") return found;
|
|
440
|
+
tree = found.value;
|
|
441
|
+
trees.set(inner.id, tree);
|
|
442
|
+
}
|
|
443
|
+
if (!convertible(tree.unit, unit)) {
|
|
444
|
+
const why = whyNotConvertible(tree.unit, unit) ?? "the units are different";
|
|
445
|
+
return err(problem("unit", `${path}.composition`, `The composition "${inner.id}" gives "${tree.unit}", not "${unit}": ${why}.`));
|
|
446
|
+
}
|
|
447
|
+
nodes.push({ kind: "composition", term: index, composition: inner.id, weight: factor * factorOf(tree.unit, unit), tree });
|
|
448
|
+
continue;
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
const law = prepared.reads.get(term.law) as Law;
|
|
452
|
+
const weight = weightOf(law.measure.unit, unit, factor, `${path}.law`);
|
|
453
|
+
if (weight.tag === "err") return weight;
|
|
454
|
+
const targets: readonly (string | null)[] =
|
|
455
|
+
term.over === "instance" ? [null] : term.over === "each" ? demand.classes.map((entry) => entry.id) : term.over;
|
|
456
|
+
for (const id of targets) {
|
|
457
|
+
const where = `${path}.${id ?? "instance"}`;
|
|
458
|
+
const request = id === null ? {} : (demand.classes.find((entry) => entry.id === id)?.request ?? {});
|
|
459
|
+
const state = term.base === undefined ? given : { ...heldOf(term.base, [request, demand.levels, given]), ...given };
|
|
460
|
+
const point = id === null ? instancePointOf(demand, law, state) : loadPointOf(demand, id, law, state, { load: term.load ?? "class" });
|
|
461
|
+
if (point.tag === "err") return err(under(point.error, where));
|
|
462
|
+
let by = weight.value.by;
|
|
463
|
+
const rateUnit = weight.value.rate;
|
|
464
|
+
if (rateUnit !== undefined) {
|
|
465
|
+
const rate = id === null ? instanceRate(demand, rateUnit, where) : classRate(demand, id, rateUnit, where);
|
|
466
|
+
if (rate.tag === "err") return rate;
|
|
467
|
+
by *= rate.value;
|
|
468
|
+
}
|
|
469
|
+
nodes.push({ kind: "law", term: index, law, class: id, base: false, weight: by, point: point.value, path: where });
|
|
470
|
+
if (term.base !== undefined) {
|
|
471
|
+
nodes.push({ kind: "law", term: index, law, class: id, base: true, weight: -by, point: basePointOf(law, point.value, term.base), path: `${where}.base` });
|
|
472
|
+
}
|
|
473
|
+
}
|
|
474
|
+
}
|
|
475
|
+
return ok({ unit, nodes });
|
|
476
|
+
};
|
|
477
|
+
return build(prepared.composition, "");
|
|
478
|
+
};
|
|
479
|
+
|
|
480
|
+
/** This function gives the sum of the parts of a tree, with the values of its laws. The map `sums` keeps the sum of each nested tree. */
|
|
481
|
+
const sumOf = (tree: Tree, rows: number, level: number, sums: Map<Tree, Sum>): Result<Sum, CompositionProblem> => {
|
|
482
|
+
const known = sums.get(tree);
|
|
483
|
+
if (known !== undefined) return ok(known);
|
|
484
|
+
const replicates = new Array<number>(rows).fill(0);
|
|
485
|
+
const widen = { low: 0, high: 0 };
|
|
486
|
+
const parts: PartValue[] = [];
|
|
487
|
+
let value = 0;
|
|
488
|
+
let extrapolated = false;
|
|
489
|
+
const keep = (part: PartValue, spread: readonly number[], change: Range): void => {
|
|
490
|
+
parts.push(part);
|
|
491
|
+
value += part.value;
|
|
492
|
+
for (const [row, draw] of spread.entries()) replicates[row] = (replicates[row] as number) + part.weight * draw;
|
|
493
|
+
const scaled = times(change, part.weight);
|
|
494
|
+
widen.low += scaled.low;
|
|
495
|
+
widen.high += scaled.high;
|
|
496
|
+
};
|
|
497
|
+
|
|
498
|
+
for (const node of tree.nodes) {
|
|
499
|
+
if (node.kind === "composition") {
|
|
500
|
+
const found = sumOf(node.tree, rows, level, sums);
|
|
501
|
+
if (found.tag === "err") return found;
|
|
502
|
+
const sum = found.value;
|
|
503
|
+
const { weight } = node;
|
|
504
|
+
const interval = intervalOf(sum.value, sum.replicates, level);
|
|
505
|
+
const scaled = times(interval, weight);
|
|
506
|
+
const change = times(sum.widen, weight);
|
|
507
|
+
keep(
|
|
508
|
+
{
|
|
509
|
+
kind: "composition",
|
|
510
|
+
term: node.term,
|
|
511
|
+
composition: node.composition,
|
|
512
|
+
weight,
|
|
513
|
+
value: weight * sum.value,
|
|
514
|
+
interval: scaled,
|
|
515
|
+
run: { low: scaled.low + change.low, high: scaled.high + change.high },
|
|
516
|
+
parts: sum.parts,
|
|
517
|
+
},
|
|
518
|
+
sum.replicates,
|
|
519
|
+
sum.widen,
|
|
520
|
+
);
|
|
521
|
+
extrapolated ||= sum.extrapolated;
|
|
522
|
+
continue;
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
const evaluated = pointValuesOf(node.law, node.point);
|
|
526
|
+
if (evaluated.tag === "err") return err(under(evaluated.error, node.path));
|
|
527
|
+
const by = node.weight;
|
|
528
|
+
const [estimate, ...all] = evaluated.value.values;
|
|
529
|
+
const spread = all.slice(0, rows);
|
|
530
|
+
const interval = intervalOf(estimate, spread, level);
|
|
531
|
+
const run = runOf(node.law, interval, level);
|
|
532
|
+
const change = { low: run.low - interval.low, high: run.high - interval.high };
|
|
533
|
+
const scaled = times(interval, by);
|
|
534
|
+
const scaledChange = times(change, by);
|
|
535
|
+
keep(
|
|
536
|
+
{
|
|
537
|
+
kind: "law",
|
|
538
|
+
term: node.term,
|
|
539
|
+
law: node.law.id,
|
|
540
|
+
class: node.class,
|
|
541
|
+
base: node.base,
|
|
542
|
+
weight: by,
|
|
543
|
+
value: by * estimate,
|
|
544
|
+
interval: scaled,
|
|
545
|
+
run: { low: scaled.low + scaledChange.low, high: scaled.high + scaledChange.high },
|
|
546
|
+
outside: evaluated.value.outside,
|
|
547
|
+
},
|
|
548
|
+
spread,
|
|
549
|
+
change,
|
|
550
|
+
);
|
|
551
|
+
extrapolated ||= evaluated.value.outside.length > 0;
|
|
552
|
+
}
|
|
553
|
+
const sum: Sum = { unit: tree.unit, value, replicates, widen, parts, extrapolated };
|
|
554
|
+
sums.set(tree, sum);
|
|
555
|
+
return ok(sum);
|
|
556
|
+
};
|
|
557
|
+
|
|
558
|
+
/**
|
|
559
|
+
* This function gives the value of a composition over a demand, with its interval. The catalog
|
|
560
|
+
* gives each law and each nested composition that a term names. It can hold more.
|
|
561
|
+
*
|
|
562
|
+
* Each part pairs its replicates by row. Row `i` of each law is one draw of the doubt of that law.
|
|
563
|
+
* Laws from separate fits have independent rows. Two laws that share points share their doubt
|
|
564
|
+
* only when their fits use the same resample for row `i`. The count of rows is the least count of
|
|
565
|
+
* the laws that the composition reads.
|
|
566
|
+
*
|
|
567
|
+
* The range `run` adds the change from the interval to the run of each part. That sum is exact
|
|
568
|
+
* when the noise of each part moves with the noise of each other part. For independent noise, the
|
|
569
|
+
* sum is wider than the true range. Thus the range is on the safe side for a limit.
|
|
570
|
+
*
|
|
571
|
+
* The function gives a problem for a composition that is not correct, for a missing law or
|
|
572
|
+
* composition, and for a cycle of compositions. It gives the problems of `loadPointOf` and of
|
|
573
|
+
* `lawValue` for each part, with the path of the term in front.
|
|
574
|
+
*/
|
|
575
|
+
export const compositionValue = (
|
|
576
|
+
composition: Composition,
|
|
577
|
+
catalog: Catalog,
|
|
578
|
+
demand: Demand,
|
|
579
|
+
options: CompositionOptions = {},
|
|
580
|
+
): Result<CompositionValue, CompositionProblem> => {
|
|
581
|
+
const level = options.level ?? DEFAULT_LEVEL;
|
|
582
|
+
const own = checkComposition(composition)[0];
|
|
583
|
+
if (own !== undefined) return err(own);
|
|
584
|
+
const badDemand = demandProblems(demand)[0];
|
|
585
|
+
if (badDemand !== undefined) return err(under(badDemand, "demand"));
|
|
586
|
+
const prepared = preparedOf(composition, catalog, level);
|
|
587
|
+
if (prepared.tag === "err") return prepared;
|
|
588
|
+
const tree = treeOf(prepared.value, demand, options.given ?? {});
|
|
589
|
+
if (tree.tag === "err") return tree;
|
|
590
|
+
const sum = sumOf(tree.value, prepared.value.rows, level, new Map());
|
|
591
|
+
if (sum.tag === "err") return sum;
|
|
592
|
+
const { value, replicates, widen, parts, extrapolated } = sum.value;
|
|
593
|
+
const interval = intervalOf(value, replicates, level);
|
|
594
|
+
return ok({
|
|
595
|
+
value,
|
|
596
|
+
unit: composition.measure.unit,
|
|
597
|
+
level,
|
|
598
|
+
interval,
|
|
599
|
+
run: { low: interval.low + widen.low, high: interval.high + widen.high },
|
|
600
|
+
replicates,
|
|
601
|
+
parts,
|
|
602
|
+
extrapolated,
|
|
603
|
+
});
|
|
604
|
+
};
|
|
605
|
+
|
|
606
|
+
/** A flat part is the law of one part at its load point, times the product of the weights down to it. */
|
|
607
|
+
export interface FlatPart {
|
|
608
|
+
readonly law: Law;
|
|
609
|
+
readonly point: LoadPoint;
|
|
610
|
+
readonly weight: number;
|
|
611
|
+
}
|
|
612
|
+
|
|
613
|
+
/** This function adds the leaves of a tree to `into`, each times `weight`. */
|
|
614
|
+
const flatten = (tree: Tree, weight: number, into: FlatPart[]): void => {
|
|
615
|
+
for (const node of tree.nodes) {
|
|
616
|
+
if (node.kind === "composition") flatten(node.tree, weight * node.weight, into);
|
|
617
|
+
else into.push({ law: node.law, point: node.point, weight: weight * node.weight });
|
|
618
|
+
}
|
|
619
|
+
};
|
|
620
|
+
|
|
621
|
+
/**
|
|
622
|
+
* This function gives the flat parts of a prepared composition over a demand, or the problem that
|
|
623
|
+
* stops them. The value of a row is the sum of the law of each part at its point, times its weight.
|
|
624
|
+
* The function does not examine the demand.
|
|
625
|
+
*/
|
|
626
|
+
export const flatPartsOf = (prepared: Prepared, demand: Demand, given: Amounts = {}): Result<readonly FlatPart[], CompositionProblem> => {
|
|
627
|
+
const tree = treeOf(prepared, demand, given);
|
|
628
|
+
if (tree.tag === "err") return tree;
|
|
629
|
+
const parts: FlatPart[] = [];
|
|
630
|
+
flatten(tree.value, 1, parts);
|
|
631
|
+
return ok(parts);
|
|
632
|
+
};
|
|
633
|
+
|
|
634
|
+
/**
|
|
635
|
+
* This function gives the value of one row of some flat parts. Row 0 is the estimate, and row `i`
|
|
636
|
+
* is replicate `i - 1` of each law. A part with no finite value gives undefined.
|
|
637
|
+
*/
|
|
638
|
+
export const rowValueOf = (parts: readonly FlatPart[], row: number): number | undefined => rowValuesOf(parts, row, row)[0];
|
|
639
|
+
|
|
640
|
+
/** This function gives the record that the law of a part reads in one row, or undefined when the law has no such row. */
|
|
641
|
+
const rowRecordOf = (law: Law, point: LoadPoint, row: number): Readonly<Record<string, number>> | undefined => {
|
|
642
|
+
const values = row === 0 ? law.constants.map((constant) => constant.value) : law.replicates[row - 1];
|
|
643
|
+
return values === undefined ? undefined : recordOf(law.constants.map((constant) => constant.id), values, point);
|
|
644
|
+
};
|
|
645
|
+
|
|
646
|
+
/**
|
|
647
|
+
* This function gives the value of each row from `first` to `last` of some flat parts, as `rowValueOf` gives it.
|
|
648
|
+
* It evaluates the law of each part over all the rows in one call. Thus a search that reads each row at one load
|
|
649
|
+
* evaluates each law one time for that load. Past the range of a variable, each value holds, as heldValue tells.
|
|
650
|
+
*/
|
|
651
|
+
export const rowValuesOf = (parts: readonly FlatPart[], first: number, last: number): readonly (number | undefined)[] => {
|
|
652
|
+
const sums: (number | undefined)[] = [];
|
|
653
|
+
for (let row = first; row <= last; row += 1) sums.push(0);
|
|
654
|
+
for (const { law, point, weight } of parts) {
|
|
655
|
+
const edge = edgePointOf(law, point);
|
|
656
|
+
const atEdge = edge === undefined ? undefined : edgeValuesOf(law, edge);
|
|
657
|
+
const records: Readonly<Record<string, number>>[] = [];
|
|
658
|
+
const slots: number[] = [];
|
|
659
|
+
for (let row = first; row <= last; row += 1) {
|
|
660
|
+
const record = sums[row - first] === undefined ? undefined : rowRecordOf(law, point, row);
|
|
661
|
+
if (record === undefined) sums[row - first] = undefined;
|
|
662
|
+
else {
|
|
663
|
+
records.push(record);
|
|
664
|
+
slots.push(row - first);
|
|
665
|
+
}
|
|
666
|
+
}
|
|
667
|
+
valuesAt(law.form.program, records).forEach((value, index) => {
|
|
668
|
+
const slot = slots[index] as number;
|
|
669
|
+
const found = atEdge === undefined ? value : heldValue(value, atEdge[slot + first]);
|
|
670
|
+
sums[slot] = found === undefined ? undefined : (sums[slot] as number) + weight * found;
|
|
671
|
+
});
|
|
672
|
+
}
|
|
673
|
+
return sums.map((value) => (value !== undefined && Number.isFinite(value) ? value : undefined));
|
|
674
|
+
};
|
|
675
|
+
|
|
676
|
+
/** This function tells if a flat part reads a variable of its law outside the range of that variable. */
|
|
677
|
+
export const partsOutside = (parts: readonly FlatPart[]): boolean =>
|
|
678
|
+
parts.some(({ law, point }) =>
|
|
679
|
+
law.variables.some((variable) => (point[variable.id] as number) < variable.min || (point[variable.id] as number) > variable.max),
|
|
680
|
+
);
|