@actuarial-ts/core 0.5.0 → 0.6.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/README.md +65 -226
- package/dist/capping.d.ts.map +1 -1
- package/dist/capping.js +39 -6
- package/dist/capping.js.map +1 -1
- package/dist/casualtyDiagnostics.d.ts +19 -49
- package/dist/casualtyDiagnostics.d.ts.map +1 -1
- package/dist/casualtyDiagnostics.js +84 -116
- package/dist/casualtyDiagnostics.js.map +1 -1
- package/dist/diagnosticAggregation.d.ts +32 -0
- package/dist/diagnosticAggregation.d.ts.map +1 -0
- package/dist/diagnosticAggregation.js +73 -0
- package/dist/diagnosticAggregation.js.map +1 -0
- package/dist/diagnosticDefinitions.d.ts +289 -0
- package/dist/diagnosticDefinitions.d.ts.map +1 -0
- package/dist/diagnosticDefinitions.js +1688 -0
- package/dist/diagnosticDefinitions.js.map +1 -0
- package/dist/diagnosticDerivations.d.ts +35 -0
- package/dist/diagnosticDerivations.d.ts.map +1 -0
- package/dist/diagnosticDerivations.js +224 -0
- package/dist/diagnosticDerivations.js.map +1 -0
- package/dist/diagnosticExposure.d.ts +51 -0
- package/dist/diagnosticExposure.d.ts.map +1 -0
- package/dist/diagnosticExposure.js +273 -0
- package/dist/diagnosticExposure.js.map +1 -0
- package/dist/diagnosticExpressions.d.ts +56 -0
- package/dist/diagnosticExpressions.d.ts.map +1 -0
- package/dist/diagnosticExpressions.js +124 -0
- package/dist/diagnosticExpressions.js.map +1 -0
- package/dist/diagnosticFormulas.d.ts +198 -0
- package/dist/diagnosticFormulas.d.ts.map +1 -0
- package/dist/diagnosticFormulas.js +219 -0
- package/dist/diagnosticFormulas.js.map +1 -0
- package/dist/diagnosticIdentity.d.ts +251 -0
- package/dist/diagnosticIdentity.d.ts.map +1 -0
- package/dist/diagnosticIdentity.js +721 -0
- package/dist/diagnosticIdentity.js.map +1 -0
- package/dist/diagnosticOrdering.d.ts +8 -0
- package/dist/diagnosticOrdering.d.ts.map +1 -0
- package/dist/diagnosticOrdering.js +73 -0
- package/dist/diagnosticOrdering.js.map +1 -0
- package/dist/diagnosticPeriodAxis.d.ts +9 -0
- package/dist/diagnosticPeriodAxis.d.ts.map +1 -0
- package/dist/diagnosticPeriodAxis.js +69 -0
- package/dist/diagnosticPeriodAxis.js.map +1 -0
- package/dist/diagnosticPeriods.d.ts +15 -0
- package/dist/diagnosticPeriods.d.ts.map +1 -0
- package/dist/diagnosticPeriods.js +50 -0
- package/dist/diagnosticPeriods.js.map +1 -0
- package/dist/diagnosticPreparation.d.ts +131 -0
- package/dist/diagnosticPreparation.d.ts.map +1 -0
- package/dist/diagnosticPreparation.js +1539 -0
- package/dist/diagnosticPreparation.js.map +1 -0
- package/dist/diagnosticReview.d.ts +66 -0
- package/dist/diagnosticReview.d.ts.map +1 -0
- package/dist/diagnosticReview.js +490 -0
- package/dist/diagnosticReview.js.map +1 -0
- package/dist/diagnosticRules.d.ts +32 -0
- package/dist/diagnosticRules.d.ts.map +1 -0
- package/dist/diagnosticRules.js +32 -0
- package/dist/diagnosticRules.js.map +1 -0
- package/dist/diagnosticRunner.d.ts +86 -0
- package/dist/diagnosticRunner.d.ts.map +1 -0
- package/dist/diagnosticRunner.js +703 -0
- package/dist/diagnosticRunner.js.map +1 -0
- package/dist/diagnosticRuntime.d.ts +26 -0
- package/dist/diagnosticRuntime.d.ts.map +1 -0
- package/dist/diagnosticRuntime.js +243 -0
- package/dist/diagnosticRuntime.js.map +1 -0
- package/dist/diagnosticSourceOrdering.d.ts +6 -0
- package/dist/diagnosticSourceOrdering.d.ts.map +1 -0
- package/dist/diagnosticSourceOrdering.js +38 -0
- package/dist/diagnosticSourceOrdering.js.map +1 -0
- package/dist/index.d.ts +28 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +16 -1
- package/dist/index.js.map +1 -1
- package/dist/mack.d.ts +4 -0
- package/dist/mack.d.ts.map +1 -1
- package/dist/mack.js +32 -4
- package/dist/mack.js.map +1 -1
- package/dist/triangle.d.ts.map +1 -1
- package/dist/triangle.js +59 -9
- package/dist/triangle.js.map +1 -1
- package/dist/types.d.ts +21 -0
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js +128 -0
- package/dist/types.js.map +1 -1
- package/dist/version.d.ts +3 -0
- package/dist/version.d.ts.map +1 -0
- package/dist/version.js +3 -0
- package/dist/version.js.map +1 -0
- package/package.json +4 -3
- package/src/capping.ts +109 -18
- package/src/casualtyDiagnostics.ts +79 -189
- package/src/diagnosticAggregation.ts +128 -0
- package/src/diagnosticDefinitions.ts +3624 -0
- package/src/diagnosticDerivations.ts +321 -0
- package/src/diagnosticExposure.ts +482 -0
- package/src/diagnosticExpressions.ts +255 -0
- package/src/diagnosticFormulas.ts +350 -0
- package/src/diagnosticIdentity.ts +1267 -0
- package/src/diagnosticOrdering.ts +106 -0
- package/src/diagnosticPeriodAxis.ts +92 -0
- package/src/diagnosticPeriods.ts +102 -0
- package/src/diagnosticPreparation.ts +2475 -0
- package/src/diagnosticReview.ts +897 -0
- package/src/diagnosticRules.ts +69 -0
- package/src/diagnosticRunner.ts +1114 -0
- package/src/diagnosticRuntime.ts +264 -0
- package/src/diagnosticSourceOrdering.ts +50 -0
- package/src/index.ts +184 -1
- package/src/mack.ts +72 -9
- package/src/triangle.ts +103 -13
- package/src/types.ts +196 -0
- package/src/version.ts +2 -0
- package/dist/metricDiagnostics.d.ts +0 -212
- package/dist/metricDiagnostics.d.ts.map +0 -1
- package/dist/metricDiagnostics.js +0 -627
- package/dist/metricDiagnostics.js.map +0 -1
- package/src/metricDiagnostics.ts +0 -876
package/src/capping.ts
CHANGED
|
@@ -39,7 +39,10 @@ function accidentYear(snap: ClaimSnapshot): number {
|
|
|
39
39
|
* diverge from what the exhibits report; services should resolve it once via
|
|
40
40
|
* this helper and pass baseYear explicitly to both.
|
|
41
41
|
*/
|
|
42
|
-
export function latestAccidentYear(
|
|
42
|
+
export function latestAccidentYear(
|
|
43
|
+
claims: ClaimSnapshot[],
|
|
44
|
+
asOfDate?: string,
|
|
45
|
+
): number {
|
|
43
46
|
const asOf = asOfDate ?? "9999-12-31";
|
|
44
47
|
let year = -Infinity;
|
|
45
48
|
for (const snap of claims) {
|
|
@@ -56,25 +59,61 @@ export function latestAccidentYear(claims: ClaimSnapshot[], asOfDate?: string):
|
|
|
56
59
|
}
|
|
57
60
|
|
|
58
61
|
/** The effective cap for one accident year under the index. */
|
|
59
|
-
export function effectiveCap(
|
|
60
|
-
|
|
62
|
+
export function effectiveCap(
|
|
63
|
+
options: Required<CapOptions>,
|
|
64
|
+
year: number,
|
|
65
|
+
): number {
|
|
66
|
+
if (
|
|
67
|
+
!isNum(options.cap) ||
|
|
68
|
+
options.cap <= 0 ||
|
|
69
|
+
!isNum(options.indexRate) ||
|
|
70
|
+
options.indexRate <= -1 ||
|
|
71
|
+
!Number.isSafeInteger(options.baseYear) ||
|
|
72
|
+
!Number.isSafeInteger(year)
|
|
73
|
+
) {
|
|
74
|
+
throw new ReservingError(
|
|
75
|
+
"BAD_CAP",
|
|
76
|
+
"Cap, index rate, base year, and accident year must define a finite positive layer",
|
|
77
|
+
);
|
|
78
|
+
}
|
|
79
|
+
const value =
|
|
80
|
+
options.cap * Math.pow(1 + options.indexRate, year - options.baseYear);
|
|
81
|
+
if (!Number.isFinite(value) || value <= 0)
|
|
82
|
+
throw new ReservingError(
|
|
83
|
+
"BAD_CAP",
|
|
84
|
+
"Indexed effective cap must be finite and positive",
|
|
85
|
+
);
|
|
86
|
+
return value;
|
|
61
87
|
}
|
|
62
88
|
|
|
63
|
-
function resolveOptions(
|
|
89
|
+
function resolveOptions(
|
|
90
|
+
claims: ClaimSnapshot[],
|
|
91
|
+
options: CapOptions,
|
|
92
|
+
): Required<CapOptions> {
|
|
64
93
|
if (!isNum(options.cap) || options.cap <= 0) {
|
|
65
|
-
throw new ReservingError(
|
|
94
|
+
throw new ReservingError(
|
|
95
|
+
"BAD_CAP",
|
|
96
|
+
"The per-occurrence cap must be a positive number",
|
|
97
|
+
);
|
|
66
98
|
}
|
|
67
99
|
const indexRate = options.indexRate ?? 0;
|
|
68
100
|
if (!isNum(indexRate) || indexRate <= -1) {
|
|
69
|
-
throw new ReservingError(
|
|
101
|
+
throw new ReservingError(
|
|
102
|
+
"BAD_CAP",
|
|
103
|
+
"The cap index rate must be a number greater than -100%",
|
|
104
|
+
);
|
|
70
105
|
}
|
|
71
106
|
let baseYear = options.baseYear ?? null;
|
|
72
107
|
if (baseYear === null) {
|
|
73
108
|
baseYear = -Infinity;
|
|
74
|
-
for (const snap of claims)
|
|
109
|
+
for (const snap of claims)
|
|
110
|
+
baseYear = Math.max(baseYear, accidentYear(snap));
|
|
75
111
|
}
|
|
76
|
-
if (!isNum(baseYear) || !Number.
|
|
77
|
-
throw new ReservingError(
|
|
112
|
+
if (!isNum(baseYear) || !Number.isSafeInteger(baseYear)) {
|
|
113
|
+
throw new ReservingError(
|
|
114
|
+
"BAD_CAP",
|
|
115
|
+
"Could not resolve a base year for the cap index",
|
|
116
|
+
);
|
|
78
117
|
}
|
|
79
118
|
return { cap: options.cap, indexRate, baseYear };
|
|
80
119
|
}
|
|
@@ -86,14 +125,18 @@ function resolveOptions(claims: ClaimSnapshot[], options: CapOptions): Required<
|
|
|
86
125
|
* negative by construction). Claim counts and statuses are untouched - the
|
|
87
126
|
* cap limits dollars, not claims.
|
|
88
127
|
*/
|
|
89
|
-
export function capClaims(
|
|
128
|
+
export function capClaims(
|
|
129
|
+
claims: ClaimSnapshot[],
|
|
130
|
+
options: CapOptions,
|
|
131
|
+
): ClaimSnapshot[] {
|
|
90
132
|
const resolved = resolveOptions(claims, options);
|
|
91
133
|
return claims.map((snap) => {
|
|
92
134
|
const capY = effectiveCap(resolved, accidentYear(snap));
|
|
93
135
|
const incurred = snap.paidToDate + snap.caseReserve;
|
|
94
136
|
const cappedIncurred = Math.min(incurred, capY);
|
|
95
137
|
const cappedPaid = Math.min(snap.paidToDate, capY);
|
|
96
|
-
if (cappedIncurred === incurred && cappedPaid === snap.paidToDate)
|
|
138
|
+
if (cappedIncurred === incurred && cappedPaid === snap.paidToDate)
|
|
139
|
+
return snap;
|
|
97
140
|
return {
|
|
98
141
|
...snap,
|
|
99
142
|
paidToDate: cappedPaid,
|
|
@@ -161,7 +204,10 @@ const PERCENTILES = [0.5, 0.75, 0.9, 0.95, 0.99];
|
|
|
161
204
|
// interpolated refinement in stochastic.ts's percentileOfSorted buys nothing.
|
|
162
205
|
function percentile(sorted: number[], p: number): number {
|
|
163
206
|
if (sorted.length === 0) return 0;
|
|
164
|
-
const idx = Math.min(
|
|
207
|
+
const idx = Math.min(
|
|
208
|
+
sorted.length - 1,
|
|
209
|
+
Math.max(0, Math.ceil(p * sorted.length) - 1),
|
|
210
|
+
);
|
|
165
211
|
return sorted[idx]!;
|
|
166
212
|
}
|
|
167
213
|
|
|
@@ -183,7 +229,10 @@ export function claimSizeDiagnostics(
|
|
|
183
229
|
options: ClaimSizeDiagnosticsOptions = {},
|
|
184
230
|
): ClaimSizeDiagnostics {
|
|
185
231
|
if (claims.length === 0) {
|
|
186
|
-
throw new ReservingError(
|
|
232
|
+
throw new ReservingError(
|
|
233
|
+
"NO_CLAIMS",
|
|
234
|
+
"Cannot analyze claim sizes with no claims",
|
|
235
|
+
);
|
|
187
236
|
}
|
|
188
237
|
const asOf = options.asOfDate ?? "9999-12-31";
|
|
189
238
|
// Latest evaluation per claim on or before the analysis date.
|
|
@@ -191,20 +240,48 @@ export function claimSizeDiagnostics(
|
|
|
191
240
|
for (const snap of claims) {
|
|
192
241
|
if (snap.evaluationDate > asOf) continue;
|
|
193
242
|
const prev = latest.get(snap.claimId);
|
|
194
|
-
if (!prev || snap.evaluationDate > prev.evaluationDate)
|
|
243
|
+
if (!prev || snap.evaluationDate > prev.evaluationDate)
|
|
244
|
+
latest.set(snap.claimId, snap);
|
|
195
245
|
}
|
|
196
246
|
|
|
197
247
|
const byYear = new Map<number, number[]>();
|
|
198
248
|
for (const snap of latest.values()) {
|
|
199
249
|
const year = accidentYear(snap);
|
|
200
250
|
const incurred = snap.paidToDate + snap.caseReserve;
|
|
251
|
+
if (
|
|
252
|
+
!Number.isSafeInteger(year) ||
|
|
253
|
+
year < 1 ||
|
|
254
|
+
year > 9999 ||
|
|
255
|
+
!Number.isFinite(incurred) ||
|
|
256
|
+
incurred < 0
|
|
257
|
+
) {
|
|
258
|
+
throw new ReservingError(
|
|
259
|
+
"BAD_LOSSES",
|
|
260
|
+
"Claim-size diagnostics require valid accident years and finite nonnegative incurred amounts",
|
|
261
|
+
);
|
|
262
|
+
}
|
|
201
263
|
let arr = byYear.get(year);
|
|
202
264
|
if (!arr) byYear.set(year, (arr = []));
|
|
203
265
|
arr.push(incurred);
|
|
204
266
|
}
|
|
205
267
|
const years = [...byYear.keys()].sort((a, b) => a - b);
|
|
206
268
|
const indexRate = options.indexRate ?? 0;
|
|
269
|
+
if (years.length === 0)
|
|
270
|
+
throw new ReservingError(
|
|
271
|
+
"NO_CLAIMS",
|
|
272
|
+
"No claim snapshots on or before the analysis date; cannot analyze claim sizes",
|
|
273
|
+
);
|
|
274
|
+
if (!isNum(indexRate) || indexRate <= -1)
|
|
275
|
+
throw new ReservingError(
|
|
276
|
+
"BAD_CAP",
|
|
277
|
+
"The cap index rate must be finite and greater than -100%",
|
|
278
|
+
);
|
|
207
279
|
const baseYear = options.baseYear ?? years[years.length - 1]!;
|
|
280
|
+
if (!Number.isSafeInteger(baseYear))
|
|
281
|
+
throw new ReservingError(
|
|
282
|
+
"BAD_CAP",
|
|
283
|
+
"The cap base year must be a safe integer",
|
|
284
|
+
);
|
|
208
285
|
|
|
209
286
|
const yearRows: ClaimSizeYearRow[] = years.map((year) => {
|
|
210
287
|
const sorted = [...byYear.get(year)!].sort((a, b) => a - b);
|
|
@@ -213,7 +290,10 @@ export function claimSizeDiagnostics(
|
|
|
213
290
|
claimCount: sorted.length,
|
|
214
291
|
totalIncurred: sorted.reduce((a, v) => a + v, 0),
|
|
215
292
|
maxClaim: sorted[sorted.length - 1] ?? 0,
|
|
216
|
-
percentiles: PERCENTILES.map((p) => ({
|
|
293
|
+
percentiles: PERCENTILES.map((p) => ({
|
|
294
|
+
p,
|
|
295
|
+
value: percentile(sorted, p),
|
|
296
|
+
})),
|
|
217
297
|
};
|
|
218
298
|
});
|
|
219
299
|
|
|
@@ -223,6 +303,16 @@ export function claimSizeDiagnostics(
|
|
|
223
303
|
// incurred is deflated to that level before taking percentiles - otherwise
|
|
224
304
|
// a nominal anchor re-indexed forward overshoots the whole distribution
|
|
225
305
|
// and every derived candidate reads near-zero pierce.
|
|
306
|
+
for (const [label, values] of [
|
|
307
|
+
["candidateCaps", options.candidateCaps],
|
|
308
|
+
["extraCaps", options.extraCaps],
|
|
309
|
+
] as const) {
|
|
310
|
+
if (values?.some((value) => !isNum(value) || value <= 0))
|
|
311
|
+
throw new ReservingError(
|
|
312
|
+
"BAD_CAP",
|
|
313
|
+
`${label} must contain only finite positive caps`,
|
|
314
|
+
);
|
|
315
|
+
}
|
|
226
316
|
let candidateCaps = options.candidateCaps;
|
|
227
317
|
if (!candidateCaps || candidateCaps.length === 0) {
|
|
228
318
|
const pooled = [...latest.values()]
|
|
@@ -251,7 +341,7 @@ export function claimSizeDiagnostics(
|
|
|
251
341
|
let totalExcess = 0;
|
|
252
342
|
let totalIncurred = 0;
|
|
253
343
|
const cells: CapCandidateYearCell[] = years.map((year) => {
|
|
254
|
-
const capY =
|
|
344
|
+
const capY = effectiveCap({ ...resolved, cap }, year);
|
|
255
345
|
const values = byYear.get(year)!;
|
|
256
346
|
let pierce = 0;
|
|
257
347
|
let excess = 0;
|
|
@@ -289,7 +379,8 @@ export function claimSizeDiagnostics(
|
|
|
289
379
|
candidates,
|
|
290
380
|
baseYear,
|
|
291
381
|
indexRate,
|
|
292
|
-
nonZeroClaimCount: [...latest.values()].filter(
|
|
293
|
-
.
|
|
382
|
+
nonZeroClaimCount: [...latest.values()].filter(
|
|
383
|
+
(s) => s.paidToDate + s.caseReserve > 0,
|
|
384
|
+
).length,
|
|
294
385
|
};
|
|
295
386
|
}
|
|
@@ -1,204 +1,94 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
type MeasureExpression,
|
|
5
|
-
type MetricDefinition,
|
|
6
|
-
type MetricWarningRule,
|
|
7
|
-
} from "./metricDiagnostics.js";
|
|
8
|
-
import { ReservingError } from "./types.js";
|
|
1
|
+
import { CASUALTY_FORMULA_TEMPLATES } from "./diagnosticFormulas.js";
|
|
2
|
+
import { DiagnosticValidationError } from "./types.js";
|
|
3
|
+
import type { DiagnosticMetricInstance, DiagnosticMetricPresentation } from "./diagnosticDefinitions.js";
|
|
9
4
|
|
|
10
|
-
|
|
11
|
-
const sub = (left: MeasureExpression, right: MeasureExpression): MeasureExpression => ({ op: "subtract", left, right });
|
|
5
|
+
export { CASUALTY_FORMULA_TEMPLATES };
|
|
12
6
|
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
7
|
+
export interface CasualtyCountBindings { readonly reported: string; readonly open: string; readonly closedNoPay: string; readonly closedWithPay: string }
|
|
8
|
+
export interface CasualtyAmountBinding { readonly id: string; readonly paid: string; readonly incurred: string }
|
|
9
|
+
export type DiagnosticMetricPresentationOverride = Partial<DiagnosticMetricPresentation>;
|
|
10
|
+
export interface CreateCasualtyMetricInstancesInput {
|
|
11
|
+
readonly counts: CasualtyCountBindings;
|
|
12
|
+
readonly exposure: string;
|
|
13
|
+
readonly amountBindings: readonly CasualtyAmountBinding[];
|
|
14
|
+
readonly presentationOverrides?: Readonly<Record<string, DiagnosticMetricPresentationOverride>>;
|
|
18
15
|
}
|
|
19
16
|
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
closedNoPay: string;
|
|
24
|
-
closedWithPay: string;
|
|
25
|
-
exposure: string;
|
|
26
|
-
paid250: string;
|
|
27
|
-
incurred250: string;
|
|
28
|
-
paidPrimary: string;
|
|
29
|
-
incurredPrimary: string;
|
|
30
|
-
}
|
|
31
|
-
|
|
32
|
-
export const CASUALTY_DIAGNOSTIC_COMPONENTS: Readonly<CasualtyDiagnosticComponentKeys> = {
|
|
33
|
-
reported: "reportedCount",
|
|
34
|
-
open: "openCount",
|
|
35
|
-
closedNoPay: "closedNoPayCount",
|
|
36
|
-
closedWithPay: "closedWithPayCount",
|
|
37
|
-
exposure: "exposure",
|
|
38
|
-
paid250: "paid250",
|
|
39
|
-
incurred250: "incurred250",
|
|
40
|
-
paidPrimary: "paidPrimary",
|
|
41
|
-
incurredPrimary: "incurredPrimary",
|
|
42
|
-
} as const;
|
|
43
|
-
|
|
44
|
-
type MetricDisplayOverride = Partial<Pick<
|
|
45
|
-
MetricDefinition,
|
|
46
|
-
"displayName" | "description" | "unit" | "numeratorLabel" | "denominatorLabel" | "basis"
|
|
47
|
-
>>;
|
|
17
|
+
type Spec = readonly [suffix: string, formulaId: string, numerator: import("./diagnosticExpressions.js").DiagnosticMeasureExpression, denominator: import("./diagnosticExpressions.js").DiagnosticMeasureExpression, presentation: DiagnosticMetricPresentation];
|
|
18
|
+
const m = (measureId: string) => ({ op: "measure" as const, measureId });
|
|
19
|
+
const sub = (left: ReturnType<typeof m>, right: ReturnType<typeof m>) => ({ op: "subtract" as const, left, right });
|
|
48
20
|
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
displayOverrides?: Readonly<Record<string, MetricDisplayOverride>>;
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
function metric(
|
|
61
|
-
id: string,
|
|
62
|
-
displayName: string,
|
|
63
|
-
description: string,
|
|
64
|
-
unit: MetricDefinition["unit"],
|
|
65
|
-
scale: number,
|
|
66
|
-
numerator: MeasureExpression,
|
|
67
|
-
denominator: MeasureExpression,
|
|
68
|
-
numeratorLabel: string,
|
|
69
|
-
denominatorLabel: string,
|
|
70
|
-
basis: string,
|
|
71
|
-
version: string,
|
|
72
|
-
override: MetricDisplayOverride | undefined,
|
|
73
|
-
warningRules?: readonly MetricWarningRule[],
|
|
74
|
-
): MetricDefinition {
|
|
75
|
-
const definition: MetricDefinition = {
|
|
76
|
-
id,
|
|
77
|
-
version,
|
|
78
|
-
displayName,
|
|
79
|
-
description,
|
|
80
|
-
unit,
|
|
81
|
-
scale,
|
|
82
|
-
numerator,
|
|
83
|
-
denominator,
|
|
84
|
-
numeratorLabel,
|
|
85
|
-
denominatorLabel,
|
|
86
|
-
basis,
|
|
87
|
-
requiredComponents: [...new Set([
|
|
88
|
-
...measureExpressionComponents(numerator),
|
|
89
|
-
...measureExpressionComponents(denominator),
|
|
90
|
-
])],
|
|
91
|
-
warningRules,
|
|
92
|
-
};
|
|
93
|
-
return { ...definition, ...definedProperties(override) };
|
|
21
|
+
function validToken(value: string): boolean {
|
|
22
|
+
if (value.length === 0 || /^[\t-\r ]|[\t-\r ]$/.test(value) || value.includes("\0")) return false;
|
|
23
|
+
for (let index = 0; index < value.length; index++) {
|
|
24
|
+
const code = value.charCodeAt(index);
|
|
25
|
+
if (code >= 0xd800 && code <= 0xdbff) { const next = value.charCodeAt(++index); if (!(next >= 0xdc00 && next <= 0xdfff)) return false; }
|
|
26
|
+
else if (code >= 0xdc00 && code <= 0xdfff) return false;
|
|
27
|
+
}
|
|
28
|
+
return true;
|
|
94
29
|
}
|
|
95
30
|
|
|
96
|
-
|
|
97
|
-
code: "PAID_EXCEEDS_INCURRED",
|
|
98
|
-
when: "numerator-greater-than-denominator",
|
|
99
|
-
message: "Paid exceeds incurred on the selected amount basis",
|
|
100
|
-
tolerance: 1e-9,
|
|
101
|
-
}];
|
|
31
|
+
function encodeBindingId(value: string): string { return encodeURIComponent(value).replace(/[!'()*]/g, (character) => `%${character.charCodeAt(0).toString(16).toUpperCase()}`); }
|
|
102
32
|
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
options: CasualtyMetricPresetOptions = {},
|
|
106
|
-
): readonly MetricDefinition[] {
|
|
107
|
-
const C = {
|
|
108
|
-
...CASUALTY_DIAGNOSTIC_COMPONENTS,
|
|
109
|
-
...definedProperties(options.components),
|
|
110
|
-
};
|
|
111
|
-
const frequencyScale = options.frequencyScale ?? 1_000_000;
|
|
112
|
-
if (!Number.isFinite(frequencyScale) || frequencyScale <= 0) {
|
|
113
|
-
throw new ReservingError("BAD_RATIO", `Casualty frequency scale must be positive; got ${frequencyScale}`);
|
|
114
|
-
}
|
|
115
|
-
const version = options.definitionVersion ?? "casualty-quarterly-v1";
|
|
116
|
-
const frequencyUnit = options.frequencyUnit ?? (frequencyScale === 1_000_000
|
|
117
|
-
? "count-per-million"
|
|
118
|
-
: "count-per-exposure-scale");
|
|
119
|
-
const limitedBasis = options.basisLabels?.limited250 ?? "$250K pre-capped total";
|
|
120
|
-
const primaryBasis = options.basisLabels?.primary ?? "$1M capped indemnity plus unlimited expense";
|
|
121
|
-
const countBasis = options.basisLabels?.counts ?? "count";
|
|
122
|
-
const override = (id: string) => options.displayOverrides?.[id];
|
|
123
|
-
const nonClosedNoPay = sub(m(C.reported), m(C.closedNoPay));
|
|
124
|
-
return [
|
|
125
|
-
metric("reported-frequency", "Reported claim frequency", "Reported claims per scaled exposure units", frequencyUnit, frequencyScale, m(C.reported), m(C.exposure), "reported claims", "exposure", countBasis, version, override("reported-frequency")),
|
|
126
|
-
metric("open-frequency", "Open claim frequency", "Open claims per scaled exposure units", frequencyUnit, frequencyScale, m(C.open), m(C.exposure), "open claims", "exposure", countBasis, version, override("open-frequency")),
|
|
127
|
-
metric("closed-no-pay-frequency", "Closed-no-pay frequency", "Closed-no-pay claims per scaled exposure units", frequencyUnit, frequencyScale, m(C.closedNoPay), m(C.exposure), "closed-no-pay claims", "exposure", countBasis, version, override("closed-no-pay-frequency")),
|
|
128
|
-
metric("closed-with-pay-frequency", "Closed-with-pay frequency", "Closed-with-pay claims per scaled exposure units", frequencyUnit, frequencyScale, m(C.closedWithPay), m(C.exposure), "closed-with-pay claims", "exposure", countBasis, version, override("closed-with-pay-frequency")),
|
|
129
|
-
metric("non-closed-no-pay-frequency", "Non-closed-no-pay frequency", "Reported less closed-no-pay claims per scaled exposure units", frequencyUnit, frequencyScale, nonClosedNoPay, m(C.exposure), "reported less closed-no-pay claims", "exposure", countBasis, version, override("non-closed-no-pay-frequency")),
|
|
130
|
-
metric("closed-no-pay-share", "Closed-no-pay share", "Closed-no-pay claims divided by reported claims", "ratio", 1, m(C.closedNoPay), m(C.reported), "closed-no-pay claims", "reported claims", countBasis, version, override("closed-no-pay-share")),
|
|
131
|
-
metric("closed-with-pay-share", "Closed-with-pay share", "Closed-with-pay claims divided by reported claims", "ratio", 1, m(C.closedWithPay), m(C.reported), "closed-with-pay claims", "reported claims", countBasis, version, override("closed-with-pay-share")),
|
|
132
|
-
metric("closed-with-pay-share-of-non-cnp", "Closed-with-pay share of non-CNP claims", "Closed-with-pay claims divided by reported less closed-no-pay claims", "ratio", 1, m(C.closedWithPay), nonClosedNoPay, "closed-with-pay claims", "reported less closed-no-pay claims", countBasis, version, override("closed-with-pay-share-of-non-cnp")),
|
|
133
|
-
metric("open-share", "Open share", "Open claims divided by reported claims", "ratio", 1, m(C.open), m(C.reported), "open claims", "reported claims", countBasis, version, override("open-share")),
|
|
134
|
-
metric("open-share-of-non-cnp", "Open share of non-CNP claims", "Open claims divided by reported less closed-no-pay claims", "ratio", 1, m(C.open), nonClosedNoPay, "open claims", "reported less closed-no-pay claims", countBasis, version, override("open-share-of-non-cnp")),
|
|
135
|
-
metric("paid-to-incurred-250", "Paid-to-incurred ($250K)", "Paid divided by incurred on the pre-capped $250K basis", "ratio", 1, m(C.paid250), m(C.incurred250), "$250K paid", "$250K incurred", limitedBasis, version, override("paid-to-incurred-250"), paidWarning),
|
|
136
|
-
metric("paid-to-incurred-primary", "Paid-to-incurred (primary)", "Paid divided by incurred on the primary basis", "ratio", 1, m(C.paidPrimary), m(C.incurredPrimary), "primary paid", "primary incurred", primaryBasis, version, override("paid-to-incurred-primary"), paidWarning),
|
|
137
|
-
metric("incurred-250-per-exposure", "Incurred per exposure ($250K)", "$250K incurred divided by exposure", "currency-per-exposure", 1, m(C.incurred250), m(C.exposure), "$250K incurred", "exposure", limitedBasis, version, override("incurred-250-per-exposure")),
|
|
138
|
-
metric("incurred-primary-per-exposure", "Incurred per exposure (primary)", "Primary incurred divided by exposure", "currency-per-exposure", 1, m(C.incurredPrimary), m(C.exposure), "primary incurred", "exposure", primaryBasis, version, override("incurred-primary-per-exposure")),
|
|
139
|
-
metric("incurred-250-per-non-cnp", "Incurred severity ($250K)", "$250K incurred divided by reported less closed-no-pay claims", "currency-per-claim", 1, m(C.incurred250), nonClosedNoPay, "$250K incurred", "reported less closed-no-pay claims", limitedBasis, version, override("incurred-250-per-non-cnp")),
|
|
140
|
-
metric("incurred-primary-per-non-cnp", "Incurred severity (primary)", "Primary incurred divided by reported less closed-no-pay claims", "currency-per-claim", 1, m(C.incurredPrimary), nonClosedNoPay, "primary incurred", "reported less closed-no-pay claims", primaryBasis, version, override("incurred-primary-per-non-cnp")),
|
|
141
|
-
metric("paid-250-per-exposure", "Paid per exposure ($250K)", "$250K paid divided by exposure", "currency-per-exposure", 1, m(C.paid250), m(C.exposure), "$250K paid", "exposure", limitedBasis, version, override("paid-250-per-exposure")),
|
|
142
|
-
metric("paid-primary-per-exposure", "Paid per exposure (primary)", "Primary paid divided by exposure", "currency-per-exposure", 1, m(C.paidPrimary), m(C.exposure), "primary paid", "exposure", primaryBasis, version, override("paid-primary-per-exposure")),
|
|
143
|
-
metric("paid-250-per-closed-with-pay", "Paid severity ($250K)", "$250K paid divided by closed-with-pay claims", "currency-per-claim", 1, m(C.paid250), m(C.closedWithPay), "$250K paid", "closed-with-pay claims", limitedBasis, version, override("paid-250-per-closed-with-pay")),
|
|
144
|
-
metric("paid-primary-per-closed-with-pay", "Paid severity (primary)", "Primary paid divided by closed-with-pay claims", "currency-per-claim", 1, m(C.paidPrimary), m(C.closedWithPay), "primary paid", "closed-with-pay claims", primaryBasis, version, override("paid-primary-per-closed-with-pay")),
|
|
145
|
-
metric("case-250-per-open", "Case reserve per open claim ($250K)", "$250K incurred less paid divided by open claims", "currency-per-claim", 1, sub(m(C.incurred250), m(C.paid250)), m(C.open), "$250K incurred less paid", "open claims", limitedBasis, version, override("case-250-per-open")),
|
|
146
|
-
metric("case-primary-per-open", "Case reserve per open claim (primary)", "Primary incurred less paid divided by open claims", "currency-per-claim", 1, sub(m(C.incurredPrimary), m(C.paidPrimary)), m(C.open), "primary incurred less paid", "open claims", primaryBasis, version, override("case-primary-per-open")),
|
|
147
|
-
];
|
|
33
|
+
function presentation(displayName: string, description: string, displayUnit: string, numeratorLabel: string, denominatorLabel: string): DiagnosticMetricPresentation {
|
|
34
|
+
return { displayName, description, displayUnit, scale: 1, numeratorLabel, denominatorLabel };
|
|
148
35
|
}
|
|
149
36
|
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
paidSourceMeasure?: string;
|
|
158
|
-
incurredSourceMeasure?: string;
|
|
159
|
-
};
|
|
160
|
-
primary?: {
|
|
161
|
-
id?: string;
|
|
162
|
-
displayName?: string;
|
|
163
|
-
indemnityPaidMeasure?: string;
|
|
164
|
-
indemnityIncurredMeasure?: string;
|
|
165
|
-
expensePaidMeasure?: string;
|
|
166
|
-
expenseIncurredMeasure?: string;
|
|
167
|
-
indemnityLimit?: number;
|
|
168
|
-
};
|
|
37
|
+
function overridePresentation(id: string, base: DiagnosticMetricPresentation, overrides: CreateCasualtyMetricInstancesInput["presentationOverrides"]): DiagnosticMetricPresentation {
|
|
38
|
+
const override = overrides?.[id];
|
|
39
|
+
if (!override) return base;
|
|
40
|
+
for (const [key, value] of Object.entries(override)) if (value === undefined) throw new DiagnosticValidationError([{ domain: "configuration", code: "invalid-type", path: `$.presentationOverrides[${JSON.stringify(id)}].${key}`, message: "Presentation override cannot contain undefined" }]);
|
|
41
|
+
const result = { ...base, ...override };
|
|
42
|
+
if (!Number.isFinite(result.scale) || result.scale <= 0) throw new DiagnosticValidationError([{ domain: "configuration", code: "invalid-number", path: `$.presentationOverrides[${JSON.stringify(id)}].scale`, message: "Presentation scale must be finite and positive" }]);
|
|
43
|
+
return result;
|
|
169
44
|
}
|
|
170
45
|
|
|
171
|
-
export function
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
const
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
const limit = options.primary?.indemnityLimit ?? 1_000_000;
|
|
179
|
-
if (!Number.isFinite(limit) || limit <= 0) {
|
|
180
|
-
throw new ReservingError("BAD_CAP", `Primary indemnity limit must be positive; got ${limit}`);
|
|
46
|
+
export function createCasualtyMetricInstances(input: CreateCasualtyMetricInstancesInput): readonly DiagnosticMetricInstance[] {
|
|
47
|
+
for (const [key, value] of Object.entries({ ...input.counts, exposure: input.exposure })) if (!validToken(value)) throw new DiagnosticValidationError([{ domain: "configuration", code: "invalid-string", path: `$.${key}`, message: "Measure binding must be a token" }]);
|
|
48
|
+
const ids = new Set<string>();
|
|
49
|
+
for (const [index, binding] of input.amountBindings.entries()) {
|
|
50
|
+
if (!validToken(binding.id) || !validToken(binding.paid) || !validToken(binding.incurred)) throw new DiagnosticValidationError([{ domain: "configuration", code: "invalid-string", path: `$.amountBindings[${index}]`, message: "Amount binding fields must be tokens" }]);
|
|
51
|
+
if (ids.has(binding.id)) throw new DiagnosticValidationError([{ domain: "configuration", code: "duplicate-id", path: `$.amountBindings[${index}].id`, message: `Duplicate amount binding ${binding.id}` }]);
|
|
52
|
+
ids.add(binding.id);
|
|
181
53
|
}
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
displayName: options.primary?.displayName ?? "Primary: $1M capped indemnity plus unlimited expense",
|
|
195
|
-
paidMeasure: C.paidPrimary,
|
|
196
|
-
incurredMeasure: C.incurredPrimary,
|
|
197
|
-
paid: { op: "add", terms: [{ op: "claim-cap", measure: options.primary?.indemnityPaidMeasure ?? "indemnityPaid", limit }, { op: "measure", measure: options.primary?.expensePaidMeasure ?? "expensePaid" }] },
|
|
198
|
-
incurred: { op: "add", terms: [{ op: "claim-cap", measure: options.primary?.indemnityIncurredMeasure ?? "indemnityIncurred", limit }, { op: "measure", measure: options.primary?.expenseIncurredMeasure ?? "expenseIncurred" }] },
|
|
199
|
-
basis: "claim-level-cap",
|
|
200
|
-
},
|
|
54
|
+
const nonClosedNoPay = sub(m(input.counts.reported), m(input.counts.closedNoPay));
|
|
55
|
+
const countSpecs: Spec[] = [
|
|
56
|
+
["reported-frequency", "frequency", m(input.counts.reported), m(input.exposure), presentation("Reported frequency", "Reported count divided by exposure", "count per exposure", "reported", "exposure")],
|
|
57
|
+
["open-frequency", "frequency", m(input.counts.open), m(input.exposure), presentation("Open frequency", "Open count divided by exposure", "count per exposure", "open", "exposure")],
|
|
58
|
+
["closed-no-pay-frequency", "frequency", m(input.counts.closedNoPay), m(input.exposure), presentation("Closed-no-pay frequency", "Closed-no-pay count divided by exposure", "count per exposure", "closed-no-pay", "exposure")],
|
|
59
|
+
["closed-with-pay-frequency", "frequency", m(input.counts.closedWithPay), m(input.exposure), presentation("Closed-with-pay frequency", "Closed-with-pay count divided by exposure", "count per exposure", "closed-with-pay", "exposure")],
|
|
60
|
+
["non-closed-no-pay-frequency", "frequency", nonClosedNoPay, m(input.exposure), presentation("Non-closed-no-pay frequency", "Reported less closed-no-pay count divided by exposure", "count per exposure", "reported less closed-no-pay", "exposure")],
|
|
61
|
+
["closed-no-pay-share", "share", m(input.counts.closedNoPay), m(input.counts.reported), presentation("Closed-no-pay share", "Closed-no-pay count divided by reported count", "ratio", "closed-no-pay", "reported")],
|
|
62
|
+
["closed-with-pay-share", "share", m(input.counts.closedWithPay), m(input.counts.reported), presentation("Closed-with-pay share", "Closed-with-pay count divided by reported count", "ratio", "closed-with-pay", "reported")],
|
|
63
|
+
["closed-with-pay-share-of-non-closed-no-pay", "share", m(input.counts.closedWithPay), nonClosedNoPay, presentation("Closed-with-pay share of non-closed-no-pay", "Closed-with-pay count divided by reported less closed-no-pay count", "ratio", "closed-with-pay", "reported less closed-no-pay")],
|
|
64
|
+
["open-share", "share", m(input.counts.open), m(input.counts.reported), presentation("Open share", "Open count divided by reported count", "ratio", "open", "reported")],
|
|
65
|
+
["open-share-of-non-closed-no-pay", "share", m(input.counts.open), nonClosedNoPay, presentation("Open share of non-closed-no-pay", "Open count divided by reported less closed-no-pay count", "ratio", "open", "reported less closed-no-pay")],
|
|
201
66
|
];
|
|
67
|
+
const specs: { id: string; formulaId: string; bindings: Record<string, import("./diagnosticExpressions.js").DiagnosticMeasureExpression>; presentation: DiagnosticMetricPresentation; rules: DiagnosticMetricInstance["rules"] }[] = [];
|
|
68
|
+
for (const [suffix, formulaId, numerator, denominator, display] of countSpecs) {
|
|
69
|
+
const id = `casualty/count/${suffix}`;
|
|
70
|
+
const bindings: Record<string, import("./diagnosticExpressions.js").DiagnosticMeasureExpression> = formulaId === "frequency"
|
|
71
|
+
? { claims: numerator, exposure: denominator }
|
|
72
|
+
: { part: numerator, whole: denominator };
|
|
73
|
+
specs.push({ id, formulaId, bindings, presentation: display, rules: [] });
|
|
74
|
+
}
|
|
75
|
+
for (const binding of input.amountBindings) {
|
|
76
|
+
const prefix = `casualty/amount/${encodeBindingId(binding.id)}`;
|
|
77
|
+
const amountSpecs = [
|
|
78
|
+
["paid-to-incurred", "paid-to-incurred", { paid: m(binding.paid), incurred: m(binding.incurred) }, presentation("Paid to incurred", "Paid divided by incurred on the bound amount basis", "ratio", "paid", "incurred")],
|
|
79
|
+
["incurred-per-exposure", "amount-per-exposure", { amount: m(binding.incurred), exposure: m(input.exposure) }, presentation("Incurred per exposure", "Incurred divided by exposure", "amount per exposure", "incurred", "exposure")],
|
|
80
|
+
["incurred-per-non-closed-no-pay-claim", "amount-per-claim", { amount: m(binding.incurred), claims: nonClosedNoPay }, presentation("Incurred per non-closed-no-pay claim", "Incurred divided by reported less closed-no-pay count", "amount per claim", "incurred", "reported less closed-no-pay")],
|
|
81
|
+
["paid-per-exposure", "amount-per-exposure", { amount: m(binding.paid), exposure: m(input.exposure) }, presentation("Paid per exposure", "Paid divided by exposure", "amount per exposure", "paid", "exposure")],
|
|
82
|
+
["paid-per-closed-with-pay-claim", "amount-per-claim", { amount: m(binding.paid), claims: m(input.counts.closedWithPay) }, presentation("Paid per closed-with-pay claim", "Paid divided by closed-with-pay count", "amount per claim", "paid", "closed-with-pay")],
|
|
83
|
+
["case-per-open-claim", "case-per-open", { incurred: m(binding.incurred), paid: m(binding.paid), open: m(input.counts.open) }, presentation("Case reserve per open claim", "Incurred less paid divided by open count", "amount per claim", "incurred less paid", "open")],
|
|
84
|
+
] as const;
|
|
85
|
+
for (const [suffix, formulaId, bindings, display] of amountSpecs) {
|
|
86
|
+
const id = `${prefix}/${suffix}`;
|
|
87
|
+
const rules = suffix === "paid-to-incurred" ? [{ id: `${id}/rule/paid-exceeds-incurred`, code: "paid-exceeds-incurred", message: "Paid exceeds incurred on the bound amount basis", severity: "warning" as const, when: { left: { source: "calculation" as const, field: "numerator" as const }, operator: "gt" as const, right: { source: "calculation" as const, field: "denominator" as const }, tolerance: { absolute: 0, relative: 0 } } }] : suffix === "case-per-open-claim" ? [{ id: `${id}/rule/negative-case`, code: "negative-case", message: "Incurred less paid is negative on the bound amount basis", severity: "warning" as const, when: { left: { source: "calculation" as const, field: "numerator" as const }, operator: "lt" as const, right: { source: "constant" as const, value: 0 }, tolerance: { absolute: 0, relative: 0 } } }] : [];
|
|
88
|
+
specs.push({ id, formulaId, bindings: { ...bindings }, presentation: display, rules });
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
const validIds = new Set(specs.map((spec) => spec.id));
|
|
92
|
+
for (const key of Object.keys(input.presentationOverrides ?? {})) if (!validIds.has(key)) throw new DiagnosticValidationError([{ domain: "configuration", code: "unknown-reference", path: `$.presentationOverrides[${JSON.stringify(key)}]`, message: "Presentation override names an unknown generated instance" }]);
|
|
93
|
+
return Object.freeze(specs.map((spec) => Object.freeze({ id: spec.id, version: "1.0.0", formulaId: spec.formulaId, bindings: spec.bindings, presentation: overridePresentation(spec.id, spec.presentation, input.presentationOverrides), rules: spec.rules })));
|
|
202
94
|
}
|
|
203
|
-
|
|
204
|
-
export const CASUALTY_AMOUNT_LAYERS = createCasualtyAmountLayers();
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
import type {
|
|
2
|
+
DiagnosticMeasureStats,
|
|
3
|
+
DiagnosticMissingPolicy,
|
|
4
|
+
DiagnosticSourceLocation,
|
|
5
|
+
} from "./diagnosticDefinitions.js";
|
|
6
|
+
import type { DiagnosticMetricFinding } from "./diagnosticFormulas.js";
|
|
7
|
+
import { compareDiagnosticContributions } from "./diagnosticOrdering.js";
|
|
8
|
+
|
|
9
|
+
export interface DiagnosticStructuralBlocker {
|
|
10
|
+
readonly code: string;
|
|
11
|
+
readonly message: string;
|
|
12
|
+
readonly sourceIds: readonly string[];
|
|
13
|
+
readonly sources: readonly DiagnosticSourceLocation[];
|
|
14
|
+
/** Exact preparation finding whose dependency this blocker represents. */
|
|
15
|
+
readonly finding?: DiagnosticMetricFinding;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export interface DiagnosticMeasureContributionBase {
|
|
19
|
+
readonly sourceId: string;
|
|
20
|
+
readonly sources: readonly DiagnosticSourceLocation[];
|
|
21
|
+
readonly deduplicated: number;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export type DiagnosticMeasureContribution =
|
|
25
|
+
| (DiagnosticMeasureContributionBase & {
|
|
26
|
+
readonly status: "observed";
|
|
27
|
+
readonly value: number;
|
|
28
|
+
})
|
|
29
|
+
| (DiagnosticMeasureContributionBase & {
|
|
30
|
+
readonly status: "imputed-zero";
|
|
31
|
+
readonly value: 0;
|
|
32
|
+
})
|
|
33
|
+
| (DiagnosticMeasureContributionBase & {
|
|
34
|
+
readonly status: "missing";
|
|
35
|
+
readonly value: null;
|
|
36
|
+
})
|
|
37
|
+
| (DiagnosticMeasureContributionBase & {
|
|
38
|
+
readonly status: "non-finite";
|
|
39
|
+
readonly value: null;
|
|
40
|
+
readonly nonFiniteKind: "nan" | "positive-infinity" | "negative-infinity";
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
export function auditedDiagnosticContribution(
|
|
44
|
+
sourceId: string,
|
|
45
|
+
value: number | null | undefined,
|
|
46
|
+
missing: DiagnosticMissingPolicy,
|
|
47
|
+
sources: readonly DiagnosticSourceLocation[] = [],
|
|
48
|
+
deduplicated = 0,
|
|
49
|
+
): DiagnosticMeasureContribution {
|
|
50
|
+
const base = {
|
|
51
|
+
sourceId,
|
|
52
|
+
sources: Object.freeze([...sources]),
|
|
53
|
+
deduplicated,
|
|
54
|
+
} as const;
|
|
55
|
+
if (value === null || value === undefined)
|
|
56
|
+
return missing === "zero"
|
|
57
|
+
? Object.freeze({
|
|
58
|
+
...base,
|
|
59
|
+
status: "imputed-zero" as const,
|
|
60
|
+
value: 0 as const,
|
|
61
|
+
})
|
|
62
|
+
: Object.freeze({ ...base, status: "missing" as const, value: null });
|
|
63
|
+
if (!Number.isFinite(value))
|
|
64
|
+
return Object.freeze({
|
|
65
|
+
...base,
|
|
66
|
+
status: "non-finite" as const,
|
|
67
|
+
value: null,
|
|
68
|
+
nonFiniteKind: Number.isNaN(value)
|
|
69
|
+
? ("nan" as const)
|
|
70
|
+
: value > 0
|
|
71
|
+
? ("positive-infinity" as const)
|
|
72
|
+
: ("negative-infinity" as const),
|
|
73
|
+
});
|
|
74
|
+
return Object.freeze({
|
|
75
|
+
...base,
|
|
76
|
+
status: "observed" as const,
|
|
77
|
+
value: Object.is(value, -0) ? 0 : value,
|
|
78
|
+
});
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function neumaier(values: readonly number[]): number | null {
|
|
82
|
+
let sum = 0;
|
|
83
|
+
let correction = 0;
|
|
84
|
+
for (const value of values) {
|
|
85
|
+
const next = sum + value;
|
|
86
|
+
correction +=
|
|
87
|
+
Math.abs(sum) >= Math.abs(value)
|
|
88
|
+
? sum - next + value
|
|
89
|
+
: value - next + sum;
|
|
90
|
+
sum = next;
|
|
91
|
+
if (!Number.isFinite(sum) || !Number.isFinite(correction)) return null;
|
|
92
|
+
}
|
|
93
|
+
const result = sum + correction;
|
|
94
|
+
return Number.isFinite(result) ? (Object.is(result, -0) ? 0 : result) : null;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
export function finalizeDiagnosticContributions(
|
|
98
|
+
contributions: readonly DiagnosticMeasureContribution[],
|
|
99
|
+
missingPolicy: DiagnosticMissingPolicy,
|
|
100
|
+
blockers: readonly DiagnosticStructuralBlocker[] = [],
|
|
101
|
+
): DiagnosticMeasureStats {
|
|
102
|
+
const ordered = [...contributions].sort(compareDiagnosticContributions);
|
|
103
|
+
const observed = ordered.filter((item) => item.status === "observed");
|
|
104
|
+
const imputed = ordered.filter((item) => item.status === "imputed-zero");
|
|
105
|
+
const missing =
|
|
106
|
+
ordered.filter((item) => item.status === "missing").length + imputed.length;
|
|
107
|
+
const nonFinite = ordered.filter(
|
|
108
|
+
(item) => item.status === "non-finite",
|
|
109
|
+
).length;
|
|
110
|
+
const finiteSum = neumaier([
|
|
111
|
+
...observed.map((item) => item.value),
|
|
112
|
+
...imputed.map(() => 0),
|
|
113
|
+
]);
|
|
114
|
+
const blocked = blockers.length > 0;
|
|
115
|
+
const sum = nonFinite > 0 || blocked || finiteSum === null ? null : finiteSum;
|
|
116
|
+
const value =
|
|
117
|
+
sum === null || (missingPolicy === "unknown" && missing > 0) ? null : sum;
|
|
118
|
+
return Object.freeze({
|
|
119
|
+
value,
|
|
120
|
+
sum,
|
|
121
|
+
observed: observed.length,
|
|
122
|
+
missing,
|
|
123
|
+
nonFinite,
|
|
124
|
+
imputedZero: imputed.length,
|
|
125
|
+
deduplicated: ordered.reduce((total, item) => total + item.deduplicated, 0),
|
|
126
|
+
structural: blockers.length,
|
|
127
|
+
});
|
|
128
|
+
}
|