@memberjunction/testing-engine 6.2.2 → 6.3.0-edge.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.
Files changed (32) hide show
  1. package/dist/decision-eval/calibration-fit.d.ts +176 -0
  2. package/dist/decision-eval/calibration-fit.d.ts.map +1 -0
  3. package/dist/decision-eval/calibration-fit.js +309 -0
  4. package/dist/decision-eval/calibration-fit.js.map +1 -0
  5. package/dist/decision-eval/calibration-points.d.ts +158 -0
  6. package/dist/decision-eval/calibration-points.d.ts.map +1 -0
  7. package/dist/decision-eval/calibration-points.js +207 -0
  8. package/dist/decision-eval/calibration-points.js.map +1 -0
  9. package/dist/decision-eval/index.d.ts +2 -0
  10. package/dist/decision-eval/index.d.ts.map +1 -1
  11. package/dist/decision-eval/index.js +2 -0
  12. package/dist/decision-eval/index.js.map +1 -1
  13. package/dist/decision-eval/types.d.ts +4 -0
  14. package/dist/decision-eval/types.d.ts.map +1 -1
  15. package/dist/decision-eval/types.js +4 -0
  16. package/dist/decision-eval/types.js.map +1 -1
  17. package/dist/drivers/AgentEvalDriver.d.ts +5 -2
  18. package/dist/drivers/AgentEvalDriver.d.ts.map +1 -1
  19. package/dist/drivers/AgentEvalDriver.js.map +1 -1
  20. package/dist/drivers/DecisionEvalDriver.d.ts.map +1 -1
  21. package/dist/drivers/DecisionEvalDriver.js +3 -3
  22. package/dist/drivers/DecisionEvalDriver.js.map +1 -1
  23. package/dist/index.d.ts +1 -0
  24. package/dist/index.d.ts.map +1 -1
  25. package/dist/index.js +1 -0
  26. package/dist/index.js.map +1 -1
  27. package/dist/oracles/judge-trace.d.ts +18 -0
  28. package/dist/oracles/judge-trace.d.ts.map +1 -1
  29. package/dist/oracles/judge-trace.js +16 -1
  30. package/dist/oracles/judge-trace.js.map +1 -1
  31. package/dist/tsconfig.tsbuildinfo +1 -0
  32. package/package.json +16 -15
@@ -0,0 +1,176 @@
1
+ /**
2
+ * @fileoverview Fits Platt calibrations for any decision use and any model, from labelled points,
3
+ * and emits them in the shape the model catalog stores: `ModelConfiguration.Decision.Calibrations`
4
+ * on the `MJ: AI Models` row of the decision model that answered.
5
+ *
6
+ * A point is one answered question: the raw probability the model gave (a Likelihood's probability,
7
+ * or a Choice's or Score's confidence) and whether the thing it predicts was true. Points are
8
+ * grouped by (use, question, model, resolved model), because a fit holds only for the exact model
9
+ * and question it was made on; each group is fitted with {@link FitPlatt}, scored out of fold, and,
10
+ * when asked, re-targeted to the class mix production sees (see {@link ShiftPlattIntercept}).
11
+ *
12
+ * Pure: no I/O. `rigs/fit-decision-calibration.ts` in `@memberjunction/integration-test-suite`
13
+ * reads the points and writes what this returns.
14
+ *
15
+ * @module @memberjunction/testing-engine
16
+ */
17
+ import type { DecisionCalibrationEntry } from '@memberjunction/ai';
18
+ import { type LabelledProbability, type PlattParameters } from './metrics.js';
19
+ /** The fewest points a group needs before it is fitted, unless the caller sets another floor. */
20
+ export declare const CALIBRATION_FIT_DEFAULT_MIN_POINTS = 30;
21
+ /** The fewest points of each class a group needs before it is fitted, unless the caller sets another floor. */
22
+ export declare const CALIBRATION_FIT_DEFAULT_MIN_PER_CLASS = 5;
23
+ /** One answered question, labelled. */
24
+ export interface CalibrationPoint {
25
+ /** The decision use, such as `conversation-routing` or `memory-note-gate`. */
26
+ Use: string;
27
+ /** The question's key in that use. */
28
+ Question: string;
29
+ /** The MJ decision model that answered (`Jev`, `LLM Decision`): the `MJ: AI Models` row the fit belongs on. */
30
+ ModelName: string;
31
+ /** The exact model behind it, as the driver reports it (`DecisionResult.ResolvedModel`). */
32
+ ResolvedModel: string;
33
+ /** The raw probability: a Likelihood's probability, or a Choice's or Score's confidence. */
34
+ RawProbability: number;
35
+ /** Whether the predicted thing was true: the statement held, or the chosen value was right. */
36
+ Label: boolean;
37
+ /** How many times the point counts: a positive integer, 1 when absent. */
38
+ Weight?: number;
39
+ /**
40
+ * The fold the point is held out in when the group is scored out of fold. Give every repeat of
41
+ * one case the same fold, so no case is scored by a fit that saw it. When any point of a group
42
+ * lacks one, the group's folds are dealt at random instead.
43
+ */
44
+ Fold?: number;
45
+ }
46
+ /** The calibrations for one decision model: what goes into its `Decision.Calibrations`. */
47
+ export interface ModelCalibrationEntries {
48
+ /** The `MJ: AI Models` row they belong on. */
49
+ ModelName: string;
50
+ Calibrations: DecisionCalibrationEntry[];
51
+ }
52
+ /** A target class mix: one prior for every group, or one per use (keyed by use, `*` for the rest). */
53
+ export type CalibrationTargetPrior = number | Readonly<Record<string, number>>;
54
+ /** Options for {@link FitDecisionCalibrations}. Every one has a default. */
55
+ export interface CalibrationFitOptions {
56
+ /** The fewest points (weights counted) a group needs. Default {@link CALIBRATION_FIT_DEFAULT_MIN_POINTS}. */
57
+ MinPoints?: number;
58
+ /** The fewest points of each class a group needs. Default {@link CALIBRATION_FIT_DEFAULT_MIN_PER_CLASS}. */
59
+ MinPerClass?: number;
60
+ /** The share of positives production sees, to re-target each fit to. Absent: the corpus's own mix. */
61
+ TargetPrior?: CalibrationTargetPrior;
62
+ /** Folds for the out-of-fold scores when the points carry none. Default {@link DECISION_EVAL_CALIBRATION_FOLDS}. */
63
+ Folds?: number;
64
+ /** Seed for the random folds. Default {@link DECISION_EVAL_SEED}. */
65
+ Seed?: number;
66
+ /** The threshold balanced accuracy is scored at. Default {@link DECISION_EVAL_DEFAULT_THRESHOLD}. */
67
+ Threshold?: number;
68
+ /** Names the corpus in each entry's `FittedOn`, such as `routing corpus 08dd187a`. */
69
+ CorpusLabel?: string;
70
+ /** The date written into `FittedOn`. Default: now. */
71
+ FittedAt?: Date;
72
+ }
73
+ /** The scores of one set of probabilities against their labels. */
74
+ export interface CalibrationScores {
75
+ BalancedAccuracy: number | null;
76
+ ECE: number | null;
77
+ Brier: number | null;
78
+ }
79
+ /** One group's fit, or the reason it was not fitted. */
80
+ export interface CalibrationGroupResult {
81
+ Use: string;
82
+ Question: string;
83
+ ModelName: string;
84
+ ResolvedModel: string;
85
+ /** Points, weights counted. */
86
+ N: number;
87
+ Positives: number;
88
+ /** The share of positives in the points. */
89
+ SamplePrior: number | null;
90
+ /** The share the shipped intercept is shifted to, or null when it is not shifted. */
91
+ TargetPrior: number | null;
92
+ /** The fit on every point, before any shift. Null when the group was refused. */
93
+ Fit: PlattParameters | null;
94
+ /** The raw probabilities' scores. */
95
+ Raw: CalibrationScores;
96
+ /** The out-of-fold calibrated scores, at the corpus's own mix. Null when the group was refused. */
97
+ Calibrated: CalibrationScores | null;
98
+ /** What to store. Absent when the group was refused. */
99
+ Entry?: DecisionCalibrationEntry;
100
+ /** Why the group was not fitted. */
101
+ Refused?: string;
102
+ }
103
+ /** A point left out before grouping, and why. */
104
+ export interface SkippedCalibrationPoint {
105
+ Index: number;
106
+ Reason: string;
107
+ }
108
+ /** What {@link FitDecisionCalibrations} returns. */
109
+ export interface CalibrationFitResult {
110
+ Groups: CalibrationGroupResult[];
111
+ /** The fitted entries, grouped by the model row they belong on. */
112
+ Entries: ModelCalibrationEntries[];
113
+ Skipped: SkippedCalibrationPoint[];
114
+ }
115
+ /** The key one group is fitted under. */
116
+ export interface CalibrationGroupKey {
117
+ Use: string;
118
+ Question: string;
119
+ ModelName: string;
120
+ ResolvedModel: string;
121
+ }
122
+ /** One group's points, expanded by weight, with their folds when every point has one. */
123
+ export interface CalibrationPointGroup extends CalibrationGroupKey {
124
+ Points: LabelledProbability[];
125
+ Folds: number[] | null;
126
+ }
127
+ /**
128
+ * Fits a calibration for every (use, question, model, resolved model) the points cover.
129
+ *
130
+ * Points with an unusable probability, label, weight or name are skipped and listed; a group is
131
+ * refused when it has too few points, too few of either class, or its fit does not converge.
132
+ *
133
+ * @param points The labelled points.
134
+ * @param options Floors, target prior, folds and the `FittedOn` text.
135
+ */
136
+ export declare function FitDecisionCalibrations(points: readonly CalibrationPoint[], options?: CalibrationFitOptions): CalibrationFitResult;
137
+ /**
138
+ * Groups points by (use, question, model, resolved model), in first-seen order, expanding each by its
139
+ * weight, and lists the points that cannot be used.
140
+ *
141
+ * @param points The labelled points.
142
+ */
143
+ export declare function GroupCalibrationPoints(points: readonly CalibrationPoint[]): {
144
+ Groups: CalibrationPointGroup[];
145
+ Skipped: SkippedCalibrationPoint[];
146
+ };
147
+ /**
148
+ * The Platt intercept re-targeted from the class mix it was fitted at to another.
149
+ *
150
+ * A Platt fit approximates the posterior log-odds at the corpus's mix:
151
+ * `logit P(y=1 | p) = A · logit(p) + B`. By Bayes' rule the posterior odds are the likelihood ratio
152
+ * times the prior odds, so when only the class mix changes (the score distribution within each class
153
+ * stays the same, the label-shift assumption) the log-odds move by the change in the prior's log-odds:
154
+ * `B' = B + logit(targetPrior) − logit(samplePrior)`. `A` is unchanged.
155
+ *
156
+ * @param b The fitted intercept.
157
+ * @param samplePrior The share of positives the fit was made on, in (0, 1).
158
+ * @param targetPrior The share of positives to re-target to, in (0, 1).
159
+ */
160
+ export declare function ShiftPlattIntercept(b: number, samplePrior: number, targetPrior: number): number;
161
+ /**
162
+ * The target prior for one use: a single number for every use, or the use's own entry, or `*`.
163
+ * Null when none applies.
164
+ *
165
+ * @param target The option as given.
166
+ * @param use The decision use.
167
+ */
168
+ export declare function ResolveTargetPrior(target: CalibrationTargetPrior | undefined, use: string): number | null;
169
+ /**
170
+ * The fit as a markdown report: one row per group, with its counts, scores and parameters or the
171
+ * reason it was refused, then the skipped points.
172
+ *
173
+ * @param result What {@link FitDecisionCalibrations} returned.
174
+ */
175
+ export declare function RenderCalibrationFitReport(result: CalibrationFitResult): string;
176
+ //# sourceMappingURL=calibration-fit.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"calibration-fit.d.ts","sourceRoot":"","sources":["../../src/decision-eval/calibration-fit.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AAEH,OAAO,KAAK,EAAE,wBAAwB,EAAE,MAAM,oBAAoB,CAAC;AACnE,OAAO,EAWH,KAAK,mBAAmB,EACxB,KAAK,eAAe,EACvB,MAAM,WAAW,CAAC;AAEnB,iGAAiG;AACj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;CACzB;AAED,yFAAyF;AACzF,MAAM,WAAW,qBAAsB,SAAQ,mBAAmB;IAC9D,MAAM,EAAE,mBAAmB,EAAE,CAAC;IAC9B,KAAK,EAAE,MAAM,EAAE,GAAG,IAAI,CAAC;CAC1B;AAED;;;;;;;;GAQG;AACH,wBAAgB,uBAAuB,CAAC,MAAM,EAAE,SAAS,gBAAgB,EAAE,EAAE,OAAO,GAAE,qBAA0B,GAAG,oBAAoB,CAKtI;AAED;;;;;GAKG;AACH,wBAAgB,sBAAsB,CAAC,MAAM,EAAE,SAAS,gBAAgB,EAAE,GAAG;IAAE,MAAM,EAAE,qBAAqB,EAAE,CAAC;IAAC,OAAO,EAAE,uBAAuB,EAAE,CAAA;CAAE,CAsBnJ;AAED;;;;;;;;;;;;GAYG;AACH,wBAAgB,mBAAmB,CAAC,CAAC,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM,GAAG,MAAM,CAK/F;AAED;;;;;;GAMG;AACH,wBAAgB,kBAAkB,CAAC,MAAM,EAAE,sBAAsB,GAAG,SAAS,EAAE,GAAG,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CASzG;AAwKD;;;;;GAKG;AACH,wBAAgB,0BAA0B,CAAC,MAAM,EAAE,oBAAoB,GAAG,MAAM,CAuB/E"}
@@ -0,0 +1,309 @@
1
+ /**
2
+ * @fileoverview Fits Platt calibrations for any decision use and any model, from labelled points,
3
+ * and emits them in the shape the model catalog stores: `ModelConfiguration.Decision.Calibrations`
4
+ * on the `MJ: AI Models` row of the decision model that answered.
5
+ *
6
+ * A point is one answered question: the raw probability the model gave (a Likelihood's probability,
7
+ * or a Choice's or Score's confidence) and whether the thing it predicts was true. Points are
8
+ * grouped by (use, question, model, resolved model), because a fit holds only for the exact model
9
+ * and question it was made on; each group is fitted with {@link FitPlatt}, scored out of fold, and,
10
+ * when asked, re-targeted to the class mix production sees (see {@link ShiftPlattIntercept}).
11
+ *
12
+ * Pure: no I/O. `rigs/fit-decision-calibration.ts` in `@memberjunction/integration-test-suite`
13
+ * reads the points and writes what this returns.
14
+ *
15
+ * @module @memberjunction/testing-engine
16
+ */
17
+ import { ApplyPlatt, BalancedAccuracy, BrierScore, CalibrationBins, ClampedLogit, DECISION_EVAL_CALIBRATION_FOLDS, DECISION_EVAL_DEFAULT_THRESHOLD, DECISION_EVAL_SEED, FitPlatt, OutOfFoldPlatt } from './metrics.js';
18
+ /** The fewest points a group needs before it is fitted, unless the caller sets another floor. */
19
+ export const CALIBRATION_FIT_DEFAULT_MIN_POINTS = 30;
20
+ /** The fewest points of each class a group needs before it is fitted, unless the caller sets another floor. */
21
+ export const CALIBRATION_FIT_DEFAULT_MIN_PER_CLASS = 5;
22
+ /**
23
+ * Fits a calibration for every (use, question, model, resolved model) the points cover.
24
+ *
25
+ * Points with an unusable probability, label, weight or name are skipped and listed; a group is
26
+ * refused when it has too few points, too few of either class, or its fit does not converge.
27
+ *
28
+ * @param points The labelled points.
29
+ * @param options Floors, target prior, folds and the `FittedOn` text.
30
+ */
31
+ export function FitDecisionCalibrations(points, options = {}) {
32
+ assertTargetPrior(options.TargetPrior);
33
+ const { Groups, Skipped } = GroupCalibrationPoints(points);
34
+ const results = Groups.map(group => fitGroup(group, options));
35
+ return { Groups: results, Entries: collectEntries(results), Skipped };
36
+ }
37
+ /**
38
+ * Groups points by (use, question, model, resolved model), in first-seen order, expanding each by its
39
+ * weight, and lists the points that cannot be used.
40
+ *
41
+ * @param points The labelled points.
42
+ */
43
+ export function GroupCalibrationPoints(points) {
44
+ const groups = new Map();
45
+ const skipped = [];
46
+ points.forEach((point, index) => {
47
+ const problem = pointProblem(point);
48
+ if (problem) {
49
+ skipped.push({ Index: index, Reason: problem });
50
+ return;
51
+ }
52
+ const key = groupKey(point);
53
+ const id = JSON.stringify([key.Use, key.Question, key.ModelName, key.ResolvedModel]);
54
+ const group = groups.get(id) ?? { ...key, Points: [], Folds: [], AllHaveFolds: true };
55
+ groups.set(id, group);
56
+ const weight = point.Weight ?? 1;
57
+ for (let i = 0; i < weight; i++) {
58
+ group.Points.push({ Probability: point.RawProbability, Positive: point.Label });
59
+ group.Folds?.push(point.Fold ?? -1);
60
+ }
61
+ group.AllHaveFolds = group.AllHaveFolds && point.Fold !== undefined;
62
+ });
63
+ const result = [...groups.values()].map(({ AllHaveFolds, ...group }) => ({ ...group, Folds: AllHaveFolds ? group.Folds : null }));
64
+ return { Groups: result, Skipped: skipped };
65
+ }
66
+ /**
67
+ * The Platt intercept re-targeted from the class mix it was fitted at to another.
68
+ *
69
+ * A Platt fit approximates the posterior log-odds at the corpus's mix:
70
+ * `logit P(y=1 | p) = A · logit(p) + B`. By Bayes' rule the posterior odds are the likelihood ratio
71
+ * times the prior odds, so when only the class mix changes (the score distribution within each class
72
+ * stays the same, the label-shift assumption) the log-odds move by the change in the prior's log-odds:
73
+ * `B' = B + logit(targetPrior) − logit(samplePrior)`. `A` is unchanged.
74
+ *
75
+ * @param b The fitted intercept.
76
+ * @param samplePrior The share of positives the fit was made on, in (0, 1).
77
+ * @param targetPrior The share of positives to re-target to, in (0, 1).
78
+ */
79
+ export function ShiftPlattIntercept(b, samplePrior, targetPrior) {
80
+ if (!isOpenUnitInterval(samplePrior) || !isOpenUnitInterval(targetPrior)) {
81
+ throw new Error(`Priors must be in (0, 1); got sample ${samplePrior} and target ${targetPrior}`);
82
+ }
83
+ return b + ClampedLogit(targetPrior) - ClampedLogit(samplePrior);
84
+ }
85
+ /**
86
+ * The target prior for one use: a single number for every use, or the use's own entry, or `*`.
87
+ * Null when none applies.
88
+ *
89
+ * @param target The option as given.
90
+ * @param use The decision use.
91
+ */
92
+ export function ResolveTargetPrior(target, use) {
93
+ if (target === undefined) {
94
+ return null;
95
+ }
96
+ if (typeof target === 'number') {
97
+ return target;
98
+ }
99
+ const prior = Object.hasOwn(target, use) ? target[use] : Object.hasOwn(target, '*') ? target['*'] : undefined;
100
+ return prior ?? null;
101
+ }
102
+ /** Throws when a target prior is not a share in (0, 1), before anything is fitted. */
103
+ function assertTargetPrior(target) {
104
+ const priors = target === undefined ? [] : typeof target === 'number' ? [['', target]] : Object.entries(target);
105
+ for (const [use, prior] of priors) {
106
+ if (!isOpenUnitInterval(prior)) {
107
+ throw new Error(`The target prior${use ? ` for '${use}'` : ''} must be a share in (0, 1), got ${String(prior)}`);
108
+ }
109
+ }
110
+ }
111
+ /** Why a point cannot be used, or undefined when it can. */
112
+ function pointProblem(point) {
113
+ for (const field of ['Use', 'Question', 'ModelName', 'ResolvedModel']) {
114
+ if (typeof point[field] !== 'string' || point[field].trim().length === 0) {
115
+ return `${field} is missing: a calibration is keyed on the use, the question, the model and the exact model behind it`;
116
+ }
117
+ }
118
+ if (typeof point.RawProbability !== 'number' || !Number.isFinite(point.RawProbability) || point.RawProbability < 0 || point.RawProbability > 1) {
119
+ return `RawProbability must be a finite number in [0, 1], got ${String(point.RawProbability)}`;
120
+ }
121
+ if (typeof point.Label !== 'boolean') {
122
+ return `Label must be true or false, got ${String(point.Label)}`;
123
+ }
124
+ if (point.Weight !== undefined && (!Number.isInteger(point.Weight) || point.Weight < 1)) {
125
+ return `Weight must be a positive integer (a repetition count), got ${String(point.Weight)}`;
126
+ }
127
+ if (point.Fold !== undefined && (!Number.isInteger(point.Fold) || point.Fold < 0)) {
128
+ return `Fold must be a non-negative integer, got ${String(point.Fold)}`;
129
+ }
130
+ return undefined;
131
+ }
132
+ function groupKey(point) {
133
+ return { Use: point.Use.trim(), Question: point.Question.trim(), ModelName: point.ModelName.trim(), ResolvedModel: point.ResolvedModel.trim() };
134
+ }
135
+ /** Fits, scores and shifts one group, or refuses it. */
136
+ function fitGroup(group, options) {
137
+ const base = describeGroup(group, options);
138
+ const refusal = groupRefusal(group.Points, options);
139
+ if (refusal) {
140
+ return { ...base, Refused: refusal };
141
+ }
142
+ const fit = FitPlatt(group.Points);
143
+ if (!fit.Converged) {
144
+ return { ...base, Fit: fit, Refused: `the fit did not converge after ${fit.Iterations} iterations` };
145
+ }
146
+ const calibrated = scoreOutOfFold(group, options);
147
+ if (!calibrated) {
148
+ return { ...base, Fit: fit, Refused: 'the out-of-fold scores need at least two folds with points in them' };
149
+ }
150
+ const b = base.TargetPrior !== null && base.SamplePrior !== null ? ShiftPlattIntercept(fit.B, base.SamplePrior, base.TargetPrior) : fit.B;
151
+ const entry = {
152
+ Use: group.Use,
153
+ Question: group.Question,
154
+ ResolvedModel: group.ResolvedModel,
155
+ A: roundParameter(fit.A),
156
+ B: roundParameter(b),
157
+ FittedOn: describeFit(base, calibrated, options)
158
+ };
159
+ return { ...base, Fit: fit, Calibrated: calibrated, Entry: entry };
160
+ }
161
+ /** The parts of a group's result that don't depend on its fit. */
162
+ function describeGroup(group, options) {
163
+ const positives = group.Points.filter(p => p.Positive).length;
164
+ const n = group.Points.length;
165
+ const target = ResolveTargetPrior(options.TargetPrior, group.Use);
166
+ return {
167
+ Use: group.Use,
168
+ Question: group.Question,
169
+ ModelName: group.ModelName,
170
+ ResolvedModel: group.ResolvedModel,
171
+ N: n,
172
+ Positives: positives,
173
+ SamplePrior: n > 0 ? positives / n : null,
174
+ TargetPrior: target,
175
+ Fit: null,
176
+ Raw: scorePoints(group.Points, options),
177
+ Calibrated: null
178
+ };
179
+ }
180
+ /** Why a group can't be fitted: too few points, too few of a class, or a bad target prior. */
181
+ function groupRefusal(points, options) {
182
+ const minPoints = options.MinPoints ?? CALIBRATION_FIT_DEFAULT_MIN_POINTS;
183
+ const minPerClass = options.MinPerClass ?? CALIBRATION_FIT_DEFAULT_MIN_PER_CLASS;
184
+ const positives = points.filter(p => p.Positive).length;
185
+ const negatives = points.length - positives;
186
+ if (points.length < minPoints) {
187
+ return `${points.length} points, fewer than the ${minPoints} a fit needs`;
188
+ }
189
+ if (positives === 0 || negatives === 0) {
190
+ return `every point is ${positives === 0 ? 'negative' : 'positive'}: a fit needs both classes`;
191
+ }
192
+ if (positives < minPerClass || negatives < minPerClass) {
193
+ return `${positives} positive and ${negatives} negative points; each class needs at least ${minPerClass}`;
194
+ }
195
+ return undefined;
196
+ }
197
+ /** The out-of-fold calibrated scores: the caller's folds when every point has one, random folds otherwise. */
198
+ function scoreOutOfFold(group, options) {
199
+ const calibrated = group.Folds
200
+ ? outOfFoldByAssignment(group.Points, group.Folds)
201
+ : OutOfFoldPlatt(group.Points, options.Folds ?? DECISION_EVAL_CALIBRATION_FOLDS, options.Seed ?? DECISION_EVAL_SEED);
202
+ if (!calibrated) {
203
+ return null;
204
+ }
205
+ return scorePoints(group.Points.map((p, i) => ({ Probability: calibrated[i], Positive: p.Positive })), options);
206
+ }
207
+ /**
208
+ * Out-of-fold calibration with the caller's folds: each fold is calibrated by a fit on the others.
209
+ * Null when fewer than two folds hold points.
210
+ */
211
+ function outOfFoldByAssignment(points, folds) {
212
+ const distinct = [...new Set(folds)];
213
+ if (distinct.length < 2) {
214
+ return null;
215
+ }
216
+ const calibrated = new Array(points.length);
217
+ for (const fold of distinct) {
218
+ const fit = FitPlatt(points.filter((_, i) => folds[i] !== fold));
219
+ points.forEach((point, i) => {
220
+ if (folds[i] === fold) {
221
+ calibrated[i] = ApplyPlatt(point.Probability, fit);
222
+ }
223
+ });
224
+ }
225
+ return calibrated;
226
+ }
227
+ function scorePoints(points, options) {
228
+ return {
229
+ BalancedAccuracy: BalancedAccuracy(points, options.Threshold ?? DECISION_EVAL_DEFAULT_THRESHOLD),
230
+ ECE: CalibrationBins(points).ECE,
231
+ Brier: BrierScore(points)
232
+ };
233
+ }
234
+ /** The `FittedOn` text: the corpus, the date, the counts and the out-of-fold scores, and any shift. */
235
+ function describeFit(group, calibrated, options) {
236
+ const date = (options.FittedAt ?? new Date()).toISOString().slice(0, 10);
237
+ const parts = [
238
+ `${options.CorpusLabel ? `${options.CorpusLabel}, ` : ''}fitted ${date}: n=${group.N} (${group.Positives} positive)`,
239
+ `out of fold, balanced accuracy ${formatScore(group.Raw.BalancedAccuracy)} raw → ${formatScore(calibrated.BalancedAccuracy)}`,
240
+ `ECE ${formatScore(group.Raw.ECE)} → ${formatScore(calibrated.ECE)}`,
241
+ `Brier ${formatScore(group.Raw.Brier)} → ${formatScore(calibrated.Brier)}`
242
+ ];
243
+ if (group.TargetPrior !== null && group.SamplePrior !== null) {
244
+ parts.push(`intercept shifted from the corpus mix ${formatScore(group.SamplePrior)} to ${formatScore(group.TargetPrior)}`);
245
+ }
246
+ return parts.join('; ');
247
+ }
248
+ function collectEntries(groups) {
249
+ const byModel = new Map();
250
+ for (const group of groups) {
251
+ if (group.Entry) {
252
+ byModel.set(group.ModelName, [...(byModel.get(group.ModelName) ?? []), group.Entry]);
253
+ }
254
+ }
255
+ return [...byModel.entries()].map(([ModelName, Calibrations]) => ({ ModelName, Calibrations }));
256
+ }
257
+ /**
258
+ * The fit as a markdown report: one row per group, with its counts, scores and parameters or the
259
+ * reason it was refused, then the skipped points.
260
+ *
261
+ * @param result What {@link FitDecisionCalibrations} returned.
262
+ */
263
+ export function RenderCalibrationFitReport(result) {
264
+ const lines = [
265
+ '# Decision calibration fit',
266
+ '',
267
+ 'Scores are out of fold, at the corpus\'s own class mix. Paste each model\'s entries into',
268
+ '`ModelConfiguration.Decision.Calibrations` on its `MJ: AI Models` row (`calibrations.json`).',
269
+ '',
270
+ '| Use | Question | Model | Resolved model | n | Positive | BA raw → cal | ECE raw → cal | Brier raw → cal | A | B | Status |',
271
+ '|---|---|---|---|---|---|---|---|---|---|---|---|'
272
+ ];
273
+ for (const group of result.Groups) {
274
+ lines.push(renderGroupRow(group));
275
+ }
276
+ if (result.Skipped.length > 0) {
277
+ lines.push('', `## Skipped points (${result.Skipped.length})`, '');
278
+ for (const skip of result.Skipped.slice(0, 50)) {
279
+ lines.push(`- point ${skip.Index}: ${skip.Reason}`);
280
+ }
281
+ if (result.Skipped.length > 50) {
282
+ lines.push(`- … and ${result.Skipped.length - 50} more`);
283
+ }
284
+ }
285
+ return `${lines.join('\n')}\n`;
286
+ }
287
+ function renderGroupRow(group) {
288
+ const scores = (key) => `${formatScore(group.Raw[key])} → ${group.Calibrated ? formatScore(group.Calibrated[key]) : '—'}`;
289
+ const status = group.Refused
290
+ ? `refused: ${group.Refused}`
291
+ : group.TargetPrior !== null ? `fitted; B shifted to prior ${formatScore(group.TargetPrior)}` : 'fitted';
292
+ const cells = [
293
+ group.Use, group.Question, group.ModelName, group.ResolvedModel, String(group.N), String(group.Positives),
294
+ scores('BalancedAccuracy'), scores('ECE'), scores('Brier'),
295
+ group.Entry ? String(group.Entry.A) : '—', group.Entry ? String(group.Entry.B) : '—', status
296
+ ];
297
+ return `| ${cells.map(cell => cell.replace(/\\/g, '\\\\').replace(/\|/g, '\\|')).join(' | ')} |`;
298
+ }
299
+ function formatScore(value) {
300
+ return value === null ? 'n/a' : value.toFixed(3);
301
+ }
302
+ /** Four decimal places, as the shipped fits are written. */
303
+ function roundParameter(value) {
304
+ return Math.round(value * 10_000) / 10_000;
305
+ }
306
+ function isOpenUnitInterval(value) {
307
+ return typeof value === 'number' && Number.isFinite(value) && value > 0 && value < 1;
308
+ }
309
+ //# sourceMappingURL=calibration-fit.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"calibration-fit.js","sourceRoot":"","sources":["../../src/decision-eval/calibration-fit.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AAGH,OAAO,EACH,UAAU,EACV,gBAAgB,EAChB,UAAU,EACV,eAAe,EACf,YAAY,EACZ,+BAA+B,EAC/B,+BAA+B,EAC/B,kBAAkB,EAClB,QAAQ,EACR,cAAc,EAGjB,MAAM,WAAW,CAAC;AAEnB,iGAAiG;AACjG,MAAM,CAAC,MAAM,kCAAkC,GAAG,EAAE,CAAC;AAErD,+GAA+G;AAC/G,MAAM,CAAC,MAAM,qCAAqC,GAAG,CAAC,CAAC;AAoHvD;;;;;;;;GAQG;AACH,MAAM,UAAU,uBAAuB,CAAC,MAAmC,EAAE,UAAiC,EAAE;IAC5G,iBAAiB,CAAC,OAAO,CAAC,WAAW,CAAC,CAAC;IACvC,MAAM,EAAE,MAAM,EAA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