structa-maestro 0.2.0__py3-none-any.whl

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 (55) hide show
  1. structa_maestro/__init__.py +294 -0
  2. structa_maestro/batch.py +564 -0
  3. structa_maestro/binding.py +206 -0
  4. structa_maestro/builder/__init__.py +0 -0
  5. structa_maestro/builder/result_builder.py +308 -0
  6. structa_maestro/cli.py +730 -0
  7. structa_maestro/confidence/__init__.py +49 -0
  8. structa_maestro/confidence/calibration.py +990 -0
  9. structa_maestro/confidence/normalizer.py +203 -0
  10. structa_maestro/config.py +111 -0
  11. structa_maestro/contracts/__init__.py +0 -0
  12. structa_maestro/contracts/enums.py +86 -0
  13. structa_maestro/contracts/models.py +229 -0
  14. structa_maestro/contracts/serialization.py +169 -0
  15. structa_maestro/documents/__init__.py +32 -0
  16. structa_maestro/documents/docx_parser.py +215 -0
  17. structa_maestro/documents/eml_parser.py +360 -0
  18. structa_maestro/documents/html_parser.py +337 -0
  19. structa_maestro/documents/inputs.py +277 -0
  20. structa_maestro/documents/loader.py +675 -0
  21. structa_maestro/documents/markdown_parser.py +225 -0
  22. structa_maestro/documents/models.py +33 -0
  23. structa_maestro/documents/normalization.py +24 -0
  24. structa_maestro/documents/pdf_parser.py +186 -0
  25. structa_maestro/documents/txt_parser.py +169 -0
  26. structa_maestro/engine.py +1201 -0
  27. structa_maestro/exceptions.py +38 -0
  28. structa_maestro/provenance/__init__.py +0 -0
  29. structa_maestro/provenance/associator.py +234 -0
  30. structa_maestro/py.typed +0 -0
  31. structa_maestro/review.py +1234 -0
  32. structa_maestro/schema/__init__.py +19 -0
  33. structa_maestro/schema/loader.py +616 -0
  34. structa_maestro/schema/models.py +269 -0
  35. structa_maestro/schema/pydantic_adapter.py +566 -0
  36. structa_maestro/schema/rules.py +526 -0
  37. structa_maestro/schema/serializer.py +156 -0
  38. structa_maestro/strategies/__init__.py +45 -0
  39. structa_maestro/strategies/base.py +101 -0
  40. structa_maestro/strategies/llm_anthropic.py +1142 -0
  41. structa_maestro/strategies/llm_config.py +154 -0
  42. structa_maestro/strategies/llm_gemini.py +1171 -0
  43. structa_maestro/strategies/llm_helpers.py +240 -0
  44. structa_maestro/strategies/llm_openai_compat.py +1183 -0
  45. structa_maestro/strategies/schema_compiler.py +248 -0
  46. structa_maestro/strategies/testing.py +71 -0
  47. structa_maestro/telemetry.py +800 -0
  48. structa_maestro/validation/__init__.py +0 -0
  49. structa_maestro/validation/cross_field.py +463 -0
  50. structa_maestro/validation/validator.py +531 -0
  51. structa_maestro-0.2.0.dist-info/METADATA +394 -0
  52. structa_maestro-0.2.0.dist-info/RECORD +55 -0
  53. structa_maestro-0.2.0.dist-info/WHEEL +4 -0
  54. structa_maestro-0.2.0.dist-info/entry_points.txt +2 -0
  55. structa_maestro-0.2.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,990 @@
1
+ """Zero-dependency empirical confidence calibration models, fitters, metrics, and persistence.
2
+
3
+ Implements pure-stdlib deterministic fitting and inference for:
4
+ - Isotonic regression (Pool Adjacent Violators Algorithm — PAVA + piecewise-linear interpolation)
5
+ - Platt / logistic scaling on clamped logits (regularized damped Newton with non-negative slope)
6
+ - Histogram / quantile binning (with empirical neighbor fallback for empty bins)
7
+
8
+ Calibration artifacts are immutable, versioned (`1.0`), pure JSON (`extra="forbid"`), and strictly
9
+ validated on load with zero third-party ML runtime dependencies.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import json
15
+ import math
16
+ from bisect import bisect_right
17
+ from collections.abc import Mapping, Sequence
18
+ from datetime import UTC, datetime
19
+ from enum import StrEnum
20
+ from pathlib import Path
21
+ from typing import Any, Literal, Protocol, runtime_checkable
22
+
23
+ from pydantic import BaseModel, ConfigDict, Field, ValidationError, field_validator, model_validator
24
+
25
+ from structa_maestro.exceptions import ConfigurationError
26
+
27
+ CALIBRATION_ARTIFACT_VERSION: Literal["1.0"] = "1.0"
28
+ DEFAULT_CALIBRATION_MIN_SAMPLES = 20
29
+ MIN_CALIBRATION_SAMPLES_FLOOR = 4
30
+ MAX_CALIBRATION_ARTIFACT_BYTES = 5 * 1024 * 1024 # 5 MiB
31
+ _DEFAULT_PLATT_EPSILON = 1e-6
32
+ _PLATT_L2_REG = 1e-4
33
+ _MAX_HISTOGRAM_BINS = 50
34
+ _MAX_METRIC_BINS = 100
35
+
36
+
37
+ class CalibrationMethod(StrEnum):
38
+ """Supported deterministic empirical confidence calibration methods."""
39
+
40
+ ISOTONIC = "isotonic"
41
+ PLATT = "platt"
42
+ HISTOGRAM = "histogram"
43
+
44
+
45
+ class BinningStrategy(StrEnum):
46
+ """Bin boundary strategy for histogram confidence calibration."""
47
+
48
+ UNIFORM = "uniform"
49
+ QUANTILE = "quantile"
50
+
51
+
52
+ @runtime_checkable
53
+ class ConfidenceCalibrator(Protocol):
54
+ """Runtime-checkable protocol for stateless, deterministic confidence calibrators."""
55
+
56
+ @property
57
+ def scale(self) -> str:
58
+ """Confidence scale supported by this calibrator (e.g., ``'0-1'``)."""
59
+ ...
60
+
61
+ @property
62
+ def method(self) -> str:
63
+ """Non-empty calibration method identifier (e.g., ``'isotonic'``)."""
64
+ ...
65
+
66
+ def calibrate(self, raw_score: float) -> float:
67
+ """Map a finite raw confidence score on ``scale`` to a calibrated probability in [0, 1]."""
68
+ ...
69
+
70
+
71
+ def _validate_strict_float(value: Any, *, field_name: str) -> float:
72
+ if isinstance(value, bool) or not isinstance(value, (int, float)):
73
+ raise ValueError(f"{field_name} must be a finite numeric value.")
74
+ num = float(value)
75
+ if not math.isfinite(num):
76
+ raise ValueError(f"{field_name} must be finite (NaN/inf not allowed).")
77
+ return num
78
+
79
+
80
+ def _validate_unit_float(value: Any, *, field_name: str) -> float:
81
+ num = _validate_strict_float(value, field_name=field_name)
82
+ if not (0.0 <= num <= 1.0):
83
+ raise ValueError(f"{field_name} must be within [0.0, 1.0].")
84
+ return num
85
+
86
+
87
+ def _validate_strict_int(value: Any, *, field_name: str) -> int:
88
+ if isinstance(value, bool) or not isinstance(value, int):
89
+ raise ValueError(f"{field_name} must be an integer.")
90
+ return value
91
+
92
+
93
+ def _validate_optional_nonblank(value: Any, *, field_name: str) -> str | None:
94
+ if value is None:
95
+ return None
96
+ if not isinstance(value, str) or not value.strip():
97
+ raise ValueError(f"{field_name} must be a non-empty string or None.")
98
+ return value.strip()
99
+
100
+
101
+ def _clamp_unit(value: float) -> float:
102
+ return min(1.0, max(0.0, value))
103
+
104
+
105
+ def _safe_logit(p: float, eps: float) -> float:
106
+ pc = min(max(p, eps), 1.0 - eps)
107
+ return math.log(pc / (1.0 - pc))
108
+
109
+
110
+ def _safe_sigmoid(u: float) -> float:
111
+ if u >= 0.0:
112
+ return 1.0 / (1.0 + math.exp(-u))
113
+ eu = math.exp(u)
114
+ return eu / (1.0 + eu)
115
+
116
+
117
+ def _log1p_exp(u: float) -> float:
118
+ if u > 0.0:
119
+ return u + math.log1p(math.exp(-u))
120
+ return math.log1p(math.exp(u))
121
+
122
+
123
+ class _CalibrationBaseModel(BaseModel):
124
+ model_config = ConfigDict(frozen=True, extra="forbid")
125
+
126
+
127
+ class CalibrationSample(_CalibrationBaseModel):
128
+ """Labeled observation pairing a raw [0, 1] confidence score with observed correctness."""
129
+
130
+ raw_score: float
131
+ is_correct: bool
132
+
133
+ @field_validator("raw_score", mode="before")
134
+ @classmethod
135
+ def _check_raw_score(cls, value: Any) -> float:
136
+ return _validate_unit_float(value, field_name="CalibrationSample.raw_score")
137
+
138
+ @field_validator("is_correct", mode="before")
139
+ @classmethod
140
+ def _check_is_correct(cls, value: Any) -> bool:
141
+ if not isinstance(value, bool):
142
+ raise ValueError("CalibrationSample.is_correct must be a strict boolean.")
143
+ return value
144
+
145
+
146
+ class CalibrationBin(_CalibrationBaseModel):
147
+ """Reliability summary for a single equal-width confidence interval."""
148
+
149
+ bin_index: int = Field(ge=0)
150
+ lower_bound: float
151
+ upper_bound: float
152
+ count: int = Field(ge=0)
153
+ mean_confidence: float | None = None
154
+ empirical_accuracy: float | None = None
155
+ calibration_gap: float | None = None
156
+
157
+ @field_validator("bin_index", "count", mode="before")
158
+ @classmethod
159
+ def _check_ints(cls, value: Any) -> int:
160
+ return _validate_strict_int(value, field_name="CalibrationBin integer field")
161
+
162
+ @field_validator("lower_bound", "upper_bound", mode="before")
163
+ @classmethod
164
+ def _check_bounds(cls, value: Any) -> float:
165
+ return _validate_unit_float(value, field_name="CalibrationBin bound")
166
+
167
+ @field_validator("mean_confidence", "empirical_accuracy", "calibration_gap", mode="before")
168
+ @classmethod
169
+ def _check_opt_unit(cls, value: Any) -> float | None:
170
+ if value is None:
171
+ return None
172
+ return _validate_unit_float(value, field_name="CalibrationBin metric")
173
+
174
+ @model_validator(mode="after")
175
+ def _check_consistency(self) -> CalibrationBin:
176
+ if not (self.lower_bound < self.upper_bound):
177
+ raise ValueError("CalibrationBin.lower_bound must be < upper_bound.")
178
+ if self.count == 0:
179
+ if (
180
+ self.mean_confidence is not None
181
+ or self.empirical_accuracy is not None
182
+ or self.calibration_gap is not None
183
+ ):
184
+ raise ValueError("Empty CalibrationBin must have None mean/accuracy/gap.")
185
+ else:
186
+ if (
187
+ self.mean_confidence is None
188
+ or self.empirical_accuracy is None
189
+ or self.calibration_gap is None
190
+ ):
191
+ raise ValueError("Non-empty CalibrationBin must populate mean/accuracy/gap.")
192
+ return self
193
+
194
+
195
+ class CalibrationMetrics(_CalibrationBaseModel):
196
+ """Aggregate empirical calibration quality metrics (ECE, MCE, Brier score, and bins)."""
197
+
198
+ sample_count: int = Field(ge=0)
199
+ num_bins: int = Field(ge=1, le=_MAX_METRIC_BINS)
200
+ ece: float
201
+ mce: float
202
+ brier_score: float
203
+ bins: tuple[CalibrationBin, ...]
204
+
205
+ @field_validator("sample_count", "num_bins", mode="before")
206
+ @classmethod
207
+ def _check_ints(cls, value: Any) -> int:
208
+ return _validate_strict_int(value, field_name="CalibrationMetrics integer field")
209
+
210
+ @field_validator("ece", "mce", "brier_score", mode="before")
211
+ @classmethod
212
+ def _check_metrics(cls, value: Any) -> float:
213
+ return _validate_unit_float(value, field_name="CalibrationMetrics score")
214
+
215
+ @model_validator(mode="after")
216
+ def _check_bin_count(self) -> CalibrationMetrics:
217
+ if len(self.bins) != self.num_bins:
218
+ raise ValueError("CalibrationMetrics.bins length must equal num_bins.")
219
+ return self
220
+
221
+
222
+ class CalibrationMetadata(_CalibrationBaseModel):
223
+ """Immutable provenance and quality summary stored inside every calibration artifact."""
224
+
225
+ artifact_version: Literal["1.0"] = CALIBRATION_ARTIFACT_VERSION
226
+ method: CalibrationMethod
227
+ scale: str = "0-1"
228
+ sample_count: int = Field(ge=MIN_CALIBRATION_SAMPLES_FLOOR)
229
+ positive_count: int = Field(ge=1)
230
+ negative_count: int = Field(ge=1)
231
+ fitted_at: str
232
+ ece_before: float
233
+ ece_after: float
234
+ mce_before: float
235
+ mce_after: float
236
+ brier_before: float
237
+ brier_after: float
238
+ schema_id: str | None = None
239
+ strategy_name: str | None = None
240
+ description: str | None = None
241
+
242
+ @field_validator("sample_count", "positive_count", "negative_count", mode="before")
243
+ @classmethod
244
+ def _check_counts(cls, value: Any) -> int:
245
+ return _validate_strict_int(value, field_name="CalibrationMetadata count")
246
+
247
+ @field_validator("scale", mode="before")
248
+ @classmethod
249
+ def _check_scale(cls, value: Any) -> str:
250
+ if not isinstance(value, str) or value.strip() != "0-1":
251
+ raise ValueError("CalibrationMetadata.scale must be '0-1' for built-in artifacts.")
252
+ return "0-1"
253
+
254
+ @field_validator("fitted_at", mode="before")
255
+ @classmethod
256
+ def _check_fitted_at(cls, value: Any) -> str:
257
+ if not isinstance(value, str) or not value.strip():
258
+ raise ValueError("CalibrationMetadata.fitted_at must be a non-empty ISO timestamp.")
259
+ return value.strip()
260
+
261
+ @field_validator(
262
+ "ece_before",
263
+ "ece_after",
264
+ "mce_before",
265
+ "mce_after",
266
+ "brier_before",
267
+ "brier_after",
268
+ mode="before",
269
+ )
270
+ @classmethod
271
+ def _check_unit_metrics(cls, value: Any) -> float:
272
+ return _validate_unit_float(value, field_name="CalibrationMetadata metric")
273
+
274
+ @field_validator("schema_id", "strategy_name", "description", mode="before")
275
+ @classmethod
276
+ def _check_optional_tags(cls, value: Any) -> str | None:
277
+ return _validate_optional_nonblank(value, field_name="CalibrationMetadata tag")
278
+
279
+ @model_validator(mode="after")
280
+ def _check_count_sum(self) -> CalibrationMetadata:
281
+ if self.positive_count + self.negative_count != self.sample_count:
282
+ raise ValueError(
283
+ "CalibrationMetadata.positive_count + negative_count must equal sample_count."
284
+ )
285
+ return self
286
+
287
+
288
+ class IsotonicParameters(_CalibrationBaseModel):
289
+ """Strictly ordered x-knots paired with monotonically non-decreasing y-knots in [0, 1]."""
290
+
291
+ x_knots: tuple[float, ...]
292
+ y_knots: tuple[float, ...]
293
+
294
+ @field_validator("x_knots", "y_knots", mode="before")
295
+ @classmethod
296
+ def _check_knot_tuples(cls, value: Any) -> tuple[float, ...]:
297
+ if not isinstance(value, (list, tuple)):
298
+ raise ValueError("Isotonic knots must be a sequence of floats.")
299
+ return tuple(_validate_unit_float(v, field_name="Isotonic knot") for v in value)
300
+
301
+ @model_validator(mode="after")
302
+ def _check_monotonicity(self) -> IsotonicParameters:
303
+ if len(self.x_knots) < 1:
304
+ raise ValueError("IsotonicParameters.x_knots must contain at least one knot.")
305
+ if len(self.x_knots) != len(self.y_knots):
306
+ raise ValueError("IsotonicParameters x_knots and y_knots must have equal length.")
307
+ for idx in range(len(self.x_knots) - 1):
308
+ if not (self.x_knots[idx] < self.x_knots[idx + 1]):
309
+ raise ValueError("IsotonicParameters.x_knots must be strictly increasing.")
310
+ if not (self.y_knots[idx] <= self.y_knots[idx + 1]):
311
+ raise ValueError("IsotonicParameters.y_knots must be monotonically non-decreasing.")
312
+ return self
313
+
314
+
315
+ class PlattParameters(_CalibrationBaseModel):
316
+ """Monotonic logistic scaling parameters evaluated on clamped logits."""
317
+
318
+ slope: float
319
+ intercept: float
320
+ epsilon: float = _DEFAULT_PLATT_EPSILON
321
+
322
+ @field_validator("slope", mode="before")
323
+ @classmethod
324
+ def _check_slope(cls, value: Any) -> float:
325
+ num = _validate_strict_float(value, field_name="PlattParameters.slope")
326
+ if num < 0.0:
327
+ raise ValueError("PlattParameters.slope must be >= 0.0 to preserve monotonicity.")
328
+ return num
329
+
330
+ @field_validator("intercept", mode="before")
331
+ @classmethod
332
+ def _check_intercept(cls, value: Any) -> float:
333
+ return _validate_strict_float(value, field_name="PlattParameters.intercept")
334
+
335
+ @field_validator("epsilon", mode="before")
336
+ @classmethod
337
+ def _check_epsilon(cls, value: Any) -> float:
338
+ num = _validate_strict_float(value, field_name="PlattParameters.epsilon")
339
+ if not (0.0 < num < 0.5):
340
+ raise ValueError("PlattParameters.epsilon must lie strictly within (0.0, 0.5).")
341
+ return num
342
+
343
+
344
+ class HistogramParameters(_CalibrationBaseModel):
345
+ """Strictly increasing [0.0, ..., 1.0] bin edges paired with calibrated empirical rates."""
346
+
347
+ binning_strategy: BinningStrategy
348
+ bin_edges: tuple[float, ...]
349
+ bin_values: tuple[float, ...]
350
+
351
+ @field_validator("bin_edges", "bin_values", mode="before")
352
+ @classmethod
353
+ def _check_sequences(cls, value: Any) -> tuple[float, ...]:
354
+ if not isinstance(value, (list, tuple)):
355
+ raise ValueError("Histogram edges/values must be sequences of floats.")
356
+ return tuple(_validate_unit_float(v, field_name="Histogram parameter") for v in value)
357
+
358
+ @model_validator(mode="after")
359
+ def _check_edges_and_values(self) -> HistogramParameters:
360
+ if len(self.bin_edges) < 2:
361
+ raise ValueError("HistogramParameters.bin_edges must have at least 2 edges.")
362
+ if self.bin_edges[0] != 0.0 or self.bin_edges[-1] != 1.0:
363
+ raise ValueError("HistogramParameters.bin_edges must start at 0.0 and end at 1.0.")
364
+ for idx in range(len(self.bin_edges) - 1):
365
+ if not (self.bin_edges[idx] < self.bin_edges[idx + 1]):
366
+ raise ValueError("HistogramParameters.bin_edges must be strictly increasing.")
367
+ if len(self.bin_values) != len(self.bin_edges) - 1:
368
+ raise ValueError("HistogramParameters.bin_values length must equal len(bin_edges) - 1.")
369
+ return self
370
+
371
+
372
+ class CalibrationModel(_CalibrationBaseModel):
373
+ """Immutable, versioned, JSON-serializable empirical confidence calibration artifact."""
374
+
375
+ artifact_version: Literal["1.0"] = CALIBRATION_ARTIFACT_VERSION
376
+ metadata: CalibrationMetadata
377
+ isotonic: IsotonicParameters | None = None
378
+ platt: PlattParameters | None = None
379
+ histogram: HistogramParameters | None = None
380
+
381
+ @model_validator(mode="after")
382
+ def _check_method_payload(self) -> CalibrationModel:
383
+ if self.artifact_version != self.metadata.artifact_version:
384
+ raise ValueError("CalibrationModel.artifact_version must match metadata version.")
385
+ expected = self.metadata.method
386
+ present = {
387
+ CalibrationMethod.ISOTONIC: self.isotonic is not None,
388
+ CalibrationMethod.PLATT: self.platt is not None,
389
+ CalibrationMethod.HISTOGRAM: self.histogram is not None,
390
+ }
391
+ for method_key, is_present in present.items():
392
+ if method_key == expected and not is_present:
393
+ raise ValueError(
394
+ f"CalibrationModel missing parameter payload for method '{expected.value}'."
395
+ )
396
+ if method_key != expected and is_present:
397
+ raise ValueError(
398
+ f"CalibrationModel contains unexpected payload for '{method_key.value}' "
399
+ f"when metadata.method is '{expected.value}'."
400
+ )
401
+ return self
402
+
403
+ @property
404
+ def scale(self) -> str:
405
+ """Confidence scale supported by this artifact."""
406
+ return self.metadata.scale
407
+
408
+ @property
409
+ def method(self) -> str:
410
+ """Calibration algorithm identifier."""
411
+ return self.metadata.method.value
412
+
413
+ def calibrate(self, raw_score: float) -> float:
414
+ """Map a finite raw confidence score in [0.0, 1.0] to a calibrated probability."""
415
+ x = _validate_unit_float(raw_score, field_name="raw_score")
416
+ if self.isotonic is not None:
417
+ return _eval_isotonic(self.isotonic, x)
418
+ if self.platt is not None:
419
+ return _eval_platt(self.platt, x)
420
+ if self.histogram is not None:
421
+ return _eval_histogram(self.histogram, x)
422
+ raise ConfigurationError("CalibrationModel has no active calibration parameters.")
423
+
424
+ def to_dict(self) -> dict[str, Any]:
425
+ """Serialize this calibration artifact into a plain JSON-compatible dictionary."""
426
+ return self.model_dump(mode="json")
427
+
428
+ def to_json(self, *, indent: int | None = None) -> str:
429
+ """Serialize this calibration artifact to deterministic UTF-8 JSON."""
430
+ return json.dumps(self.to_dict(), indent=indent, sort_keys=False)
431
+
432
+ def to_file(self, path: str | Path, *, indent: int = 2) -> Path:
433
+ """Persist this calibration artifact to disk as UTF-8 JSON."""
434
+ target = Path(path)
435
+ try:
436
+ target.parent.mkdir(parents=True, exist_ok=True)
437
+ target.write_text(self.to_json(indent=indent) + "\n", encoding="utf-8")
438
+ except OSError as exc:
439
+ raise ConfigurationError(
440
+ f"Failed to write calibration artifact ({type(exc).__name__})."
441
+ ) from exc
442
+ return target
443
+
444
+ @classmethod
445
+ def from_dict(cls, data: Mapping[str, Any]) -> CalibrationModel:
446
+ """Validate and load a CalibrationModel from a mapping, raising ConfigurationError."""
447
+ if not isinstance(data, Mapping):
448
+ raise ConfigurationError("Calibration artifact payload must be a JSON object.")
449
+ try:
450
+ return cls.model_validate(dict(data))
451
+ except ValidationError as exc:
452
+ first_loc = ".".join(str(p) for p in exc.errors()[0].get("loc", ())) or "<root>"
453
+ first_type = exc.errors()[0].get("type", "validation_error")
454
+ raise ConfigurationError(
455
+ f"Invalid calibration artifact at '{first_loc}' ({first_type})."
456
+ ) from exc
457
+
458
+ @classmethod
459
+ def from_json(cls, raw_json: str) -> CalibrationModel:
460
+ """Validate and load a CalibrationModel from a JSON string."""
461
+ if not isinstance(raw_json, str) or not raw_json.strip():
462
+ raise ConfigurationError("Calibration artifact JSON must be a non-empty string.")
463
+ if len(raw_json.encode("utf-8")) > MAX_CALIBRATION_ARTIFACT_BYTES:
464
+ raise ConfigurationError(
465
+ f"Calibration artifact exceeds maximum size limit "
466
+ f"({MAX_CALIBRATION_ARTIFACT_BYTES} bytes)."
467
+ )
468
+ try:
469
+ parsed = json.loads(raw_json)
470
+ except json.JSONDecodeError as exc:
471
+ raise ConfigurationError("Calibration artifact is not valid JSON.") from exc
472
+ if not isinstance(parsed, Mapping):
473
+ raise ConfigurationError("Calibration artifact JSON root must be an object.")
474
+ return cls.from_dict(parsed)
475
+
476
+ @classmethod
477
+ def from_file(cls, path: str | Path) -> CalibrationModel:
478
+ """Validate and load a CalibrationModel from a JSON file with strict size limits."""
479
+ if isinstance(path, str) and not path.strip():
480
+ raise ConfigurationError("Calibration artifact file path must be non-empty.")
481
+ target = Path(path)
482
+ try:
483
+ if not target.exists() or not target.is_file():
484
+ raise ConfigurationError(f"Calibration artifact file not found: '{target.name}'.")
485
+ size = target.stat().st_size
486
+ if size > MAX_CALIBRATION_ARTIFACT_BYTES:
487
+ raise ConfigurationError(
488
+ f"Calibration artifact exceeds maximum size limit "
489
+ f"({MAX_CALIBRATION_ARTIFACT_BYTES} bytes)."
490
+ )
491
+ raw_text = target.read_text(encoding="utf-8")
492
+ except ConfigurationError:
493
+ raise
494
+ except (OSError, UnicodeDecodeError) as exc:
495
+ raise ConfigurationError(
496
+ f"Unable to read calibration artifact ({type(exc).__name__})."
497
+ ) from exc
498
+ return cls.from_json(raw_text)
499
+
500
+
501
+ def _eval_isotonic(params: IsotonicParameters, x: float) -> float:
502
+ xs = params.x_knots
503
+ ys = params.y_knots
504
+ if x <= xs[0]:
505
+ return ys[0]
506
+ if x >= xs[-1]:
507
+ return ys[-1]
508
+ idx = bisect_right(xs, x)
509
+ if idx <= 0:
510
+ return ys[0]
511
+ if idx >= len(xs):
512
+ return ys[-1]
513
+ x0, x1 = xs[idx - 1], xs[idx]
514
+ y0, y1 = ys[idx - 1], ys[idx]
515
+ span = x1 - x0
516
+ if span <= 0.0:
517
+ return y1
518
+ frac = (x - x0) / span
519
+ return _clamp_unit(y0 + frac * (y1 - y0))
520
+
521
+
522
+ def _eval_platt(params: PlattParameters, x: float) -> float:
523
+ z = _safe_logit(x, params.epsilon)
524
+ return _clamp_unit(_safe_sigmoid(params.slope * z + params.intercept))
525
+
526
+
527
+ def _eval_histogram(params: HistogramParameters, x: float) -> float:
528
+ idx = bisect_right(params.bin_edges, x) - 1
529
+ if idx < 0:
530
+ idx = 0
531
+ elif idx >= len(params.bin_values):
532
+ idx = len(params.bin_values) - 1
533
+ return params.bin_values[idx]
534
+
535
+
536
+ def _coerce_samples(
537
+ samples: Sequence[CalibrationSample | tuple[float, bool]],
538
+ ) -> list[CalibrationSample]:
539
+ if isinstance(samples, (str, bytes)) or not isinstance(samples, Sequence):
540
+ raise ConfigurationError(
541
+ "samples must be a sequence of CalibrationSample or (score, bool)."
542
+ )
543
+ coerced: list[CalibrationSample] = []
544
+ for idx, item in enumerate(samples):
545
+ if isinstance(item, CalibrationSample):
546
+ coerced.append(item)
547
+ continue
548
+ if isinstance(item, tuple) and len(item) == 2:
549
+ raw_score, is_correct = item
550
+ try:
551
+ coerced.append(CalibrationSample(raw_score=raw_score, is_correct=is_correct))
552
+ except ValidationError as exc:
553
+ raise ConfigurationError(f"Invalid calibration sample at index {idx}.") from exc
554
+ continue
555
+ raise ConfigurationError(
556
+ f"Calibration sample at index {idx} must be a CalibrationSample or (float, bool) tuple."
557
+ )
558
+ return coerced
559
+
560
+
561
+ def compute_calibration_metrics(
562
+ samples: Sequence[CalibrationSample | tuple[float, bool]],
563
+ *,
564
+ num_bins: int = 10,
565
+ ) -> CalibrationMetrics:
566
+ """Compute deterministic ECE, MCE, Brier score, and per-bin reliability statistics."""
567
+ if isinstance(num_bins, bool) or not isinstance(num_bins, int) or not (1 <= num_bins <= 100):
568
+ raise ConfigurationError("num_bins must be an integer between 1 and 100.")
569
+
570
+ coerced = _coerce_samples(samples)
571
+ total = len(coerced)
572
+ counts = [0] * num_bins
573
+ sum_conf = [0.0] * num_bins
574
+ sum_acc = [0.0] * num_bins
575
+ brier_total = 0.0
576
+
577
+ for sample in coerced:
578
+ y = 1.0 if sample.is_correct else 0.0
579
+ diff = sample.raw_score - y
580
+ brier_total += diff * diff
581
+ bin_idx = min(int(sample.raw_score * num_bins), num_bins - 1)
582
+ counts[bin_idx] += 1
583
+ sum_conf[bin_idx] += sample.raw_score
584
+ sum_acc[bin_idx] += y
585
+
586
+ bins: list[CalibrationBin] = []
587
+ ece_acc = 0.0
588
+ mce_val = 0.0
589
+ for idx in range(num_bins):
590
+ lower = idx / num_bins
591
+ upper = 1.0 if idx == num_bins - 1 else (idx + 1) / num_bins
592
+ cnt = counts[idx]
593
+ if cnt == 0:
594
+ bins.append(
595
+ CalibrationBin(
596
+ bin_index=idx,
597
+ lower_bound=round(lower, 6),
598
+ upper_bound=round(upper, 6),
599
+ count=0,
600
+ )
601
+ )
602
+ else:
603
+ mean_c = _clamp_unit(sum_conf[idx] / cnt)
604
+ emp_a = _clamp_unit(sum_acc[idx] / cnt)
605
+ gap = _clamp_unit(abs(emp_a - mean_c))
606
+ ece_acc += (cnt / total) * gap
607
+ if gap > mce_val:
608
+ mce_val = gap
609
+ bins.append(
610
+ CalibrationBin(
611
+ bin_index=idx,
612
+ lower_bound=round(lower, 6),
613
+ upper_bound=round(upper, 6),
614
+ count=cnt,
615
+ mean_confidence=round(mean_c, 6),
616
+ empirical_accuracy=round(emp_a, 6),
617
+ calibration_gap=round(gap, 6),
618
+ )
619
+ )
620
+
621
+ brier = _clamp_unit(brier_total / total) if total > 0 else 0.0
622
+ return CalibrationMetrics(
623
+ sample_count=total,
624
+ num_bins=num_bins,
625
+ ece=round(_clamp_unit(ece_acc), 6),
626
+ mce=round(_clamp_unit(mce_val), 6),
627
+ brier_score=round(brier, 6),
628
+ bins=tuple(bins),
629
+ )
630
+
631
+
632
+ def _fit_isotonic(samples: list[CalibrationSample]) -> IsotonicParameters:
633
+ ordered = sorted(samples, key=lambda s: s.raw_score)
634
+ grouped: list[tuple[float, float, int]] = []
635
+ for sample in ordered:
636
+ y = 1.0 if sample.is_correct else 0.0
637
+ if grouped and grouped[-1][0] == sample.raw_score:
638
+ prev_x, prev_sum, prev_cnt = grouped[-1]
639
+ grouped[-1] = (prev_x, prev_sum + y, prev_cnt + 1)
640
+ else:
641
+ grouped.append((sample.raw_score, y, 1))
642
+
643
+ # Pool Adjacent Violators Algorithm (PAVA): blocks are [x_min, x_max, sum_y, weight]
644
+ blocks: list[list[float]] = []
645
+ for x_val, sum_y, cnt in grouped:
646
+ blocks.append([x_val, x_val, sum_y, float(cnt)])
647
+ while len(blocks) >= 2:
648
+ prev_mean = blocks[-2][2] / blocks[-2][3]
649
+ curr_mean = blocks[-1][2] / blocks[-1][3]
650
+ if prev_mean > curr_mean:
651
+ merged_sum = blocks[-2][2] + blocks[-1][2]
652
+ merged_weight = blocks[-2][3] + blocks[-1][3]
653
+ blocks[-2][1] = blocks[-1][1]
654
+ blocks[-2][2] = merged_sum
655
+ blocks[-2][3] = merged_weight
656
+ blocks.pop()
657
+ else:
658
+ break
659
+
660
+ x_knots: list[float] = []
661
+ y_knots: list[float] = []
662
+ prev_y = 0.0
663
+ for x_min, x_max, sum_y, weight in blocks:
664
+ y_val = _clamp_unit(sum_y / weight)
665
+ if y_val < prev_y:
666
+ y_val = prev_y
667
+ prev_y = y_val
668
+ x_knots.append(x_min)
669
+ y_knots.append(y_val)
670
+ if x_max > x_min:
671
+ x_knots.append(x_max)
672
+ y_knots.append(y_val)
673
+
674
+ return IsotonicParameters(x_knots=tuple(x_knots), y_knots=tuple(y_knots))
675
+
676
+
677
+ def _fit_platt(samples: list[CalibrationSample]) -> PlattParameters:
678
+ eps = _DEFAULT_PLATT_EPSILON
679
+ n = float(len(samples))
680
+ zs = [_safe_logit(s.raw_score, eps) for s in samples]
681
+ ys = [1.0 if s.is_correct else 0.0 for s in samples]
682
+
683
+ def _loss(a: float, b: float) -> float:
684
+ nll = 0.0
685
+ for z, y in zip(zs, ys, strict=True):
686
+ u = a * z + b
687
+ nll += _log1p_exp(u) - y * u
688
+ return (nll / n) + 0.5 * _PLATT_L2_REG * ((a - 1.0) ** 2 + b * b)
689
+
690
+ a = 1.0
691
+ b = 0.0
692
+ for _ in range(100):
693
+ ga = 0.0
694
+ gb = 0.0
695
+ haa = 0.0
696
+ hab = 0.0
697
+ hbb = 0.0
698
+ for z, y in zip(zs, ys, strict=True):
699
+ q = _safe_sigmoid(a * z + b)
700
+ err = q - y
701
+ w = max(q * (1.0 - q), 1e-12)
702
+ ga += err * z
703
+ gb += err
704
+ haa += w * z * z
705
+ hab += w * z
706
+ hbb += w
707
+ ga = (ga / n) + _PLATT_L2_REG * (a - 1.0)
708
+ gb = (gb / n) + _PLATT_L2_REG * b
709
+ haa = (haa / n) + _PLATT_L2_REG
710
+ hab = hab / n
711
+ hbb = (hbb / n) + _PLATT_L2_REG
712
+
713
+ if max(abs(ga), abs(gb)) < 1e-9:
714
+ break
715
+
716
+ det = haa * hbb - hab * hab
717
+ if det <= 1e-15:
718
+ da = -ga
719
+ db = -gb
720
+ else:
721
+ da = -(hbb * ga - hab * gb) / det
722
+ db = -(-hab * ga + haa * gb) / det
723
+
724
+ cur_loss = _loss(a, b)
725
+ step = 1.0
726
+ improved = False
727
+ for _ in range(30):
728
+ cand_a = a + step * da
729
+ cand_b = b + step * db
730
+ if _loss(cand_a, cand_b) < cur_loss:
731
+ a, b = cand_a, cand_b
732
+ improved = True
733
+ break
734
+ step *= 0.5
735
+ if not improved:
736
+ break
737
+
738
+ # Project slope >= 0.0 to mathematically preserve monotonicity over [0.0, 1.0]
739
+ if a < 0.0:
740
+ a = 0.0
741
+ pos_rate = sum(ys) / n
742
+ b = _safe_logit(pos_rate, eps)
743
+ for _ in range(50):
744
+ gb = 0.0
745
+ hbb = 0.0
746
+ for y in ys:
747
+ q = _safe_sigmoid(b)
748
+ gb += q - y
749
+ hbb += max(q * (1.0 - q), 1e-12)
750
+ gb = (gb / n) + _PLATT_L2_REG * b
751
+ hbb = (hbb / n) + _PLATT_L2_REG
752
+ if abs(gb) < 1e-9:
753
+ break
754
+ b -= gb / hbb
755
+
756
+ return PlattParameters(slope=a, intercept=b, epsilon=eps)
757
+
758
+
759
+ def _fit_histogram(
760
+ samples: list[CalibrationSample],
761
+ *,
762
+ num_bins: int,
763
+ binning_strategy: BinningStrategy,
764
+ ) -> HistogramParameters:
765
+ if (
766
+ isinstance(num_bins, bool)
767
+ or not isinstance(num_bins, int)
768
+ or not (2 <= num_bins <= _MAX_HISTOGRAM_BINS)
769
+ ):
770
+ raise ConfigurationError(
771
+ f"num_bins for histogram calibration must be an integer in [2, {_MAX_HISTOGRAM_BINS}]."
772
+ )
773
+
774
+ if binning_strategy == BinningStrategy.UNIFORM:
775
+ edges = [0.0] + [i / num_bins for i in range(1, num_bins)] + [1.0]
776
+ else:
777
+ sorted_scores = sorted(s.raw_score for s in samples)
778
+ n = len(sorted_scores)
779
+ raw_edges: list[float] = [0.0]
780
+ for k in range(1, num_bins):
781
+ pos = (k * (n - 1)) / num_bins
782
+ lo = math.floor(pos)
783
+ hi = min(math.ceil(pos), n - 1)
784
+ frac = pos - lo
785
+ q_val = sorted_scores[lo] + frac * (sorted_scores[hi] - sorted_scores[lo])
786
+ if 0.0 < q_val < 1.0:
787
+ raw_edges.append(q_val)
788
+ raw_edges.append(1.0)
789
+ edges = [0.0]
790
+ for edge in raw_edges[1:]:
791
+ if edge > edges[-1]:
792
+ edges.append(edge)
793
+ if edges[-1] != 1.0:
794
+ edges[-1] = 1.0
795
+
796
+ b_count = len(edges) - 1
797
+ counts = [0] * b_count
798
+ sum_y = [0.0] * b_count
799
+ for sample in samples:
800
+ idx = bisect_right(edges, sample.raw_score) - 1
801
+ if idx < 0:
802
+ idx = 0
803
+ elif idx >= b_count:
804
+ idx = b_count - 1
805
+ counts[idx] += 1
806
+ sum_y[idx] += 1.0 if sample.is_correct else 0.0
807
+
808
+ populated: list[float | None] = [
809
+ _clamp_unit(sum_y[i] / counts[i]) if counts[i] > 0 else None for i in range(b_count)
810
+ ]
811
+
812
+ # Deterministic nearest-populated-neighbor fallback for empty bins
813
+ global_pos_rate = _clamp_unit(sum(1.0 for s in samples if s.is_correct) / len(samples))
814
+ bin_values: list[float] = []
815
+ for i in range(b_count):
816
+ val = populated[i]
817
+ if val is not None:
818
+ bin_values.append(val)
819
+ continue
820
+ left_idx: int | None = None
821
+ for j in range(i - 1, -1, -1):
822
+ if populated[j] is not None:
823
+ left_idx = j
824
+ break
825
+ right_idx: int | None = None
826
+ for j in range(i + 1, b_count):
827
+ if populated[j] is not None:
828
+ right_idx = j
829
+ break
830
+ left_val = populated[left_idx] if left_idx is not None else None
831
+ right_val = populated[right_idx] if right_idx is not None else None
832
+ if (
833
+ left_idx is not None
834
+ and right_idx is not None
835
+ and left_val is not None
836
+ and right_val is not None
837
+ ):
838
+ frac = (i - left_idx) / (right_idx - left_idx)
839
+ bin_values.append(_clamp_unit(left_val + frac * (right_val - left_val)))
840
+ elif left_val is not None:
841
+ bin_values.append(left_val)
842
+ elif right_val is not None:
843
+ bin_values.append(right_val)
844
+ else:
845
+ bin_values.append(global_pos_rate)
846
+
847
+ return HistogramParameters(
848
+ binning_strategy=binning_strategy,
849
+ bin_edges=tuple(edges),
850
+ bin_values=tuple(bin_values),
851
+ )
852
+
853
+
854
+ def fit_calibrator(
855
+ samples: Sequence[CalibrationSample | tuple[float, bool]],
856
+ *,
857
+ method: CalibrationMethod | str = CalibrationMethod.ISOTONIC,
858
+ num_bins: int = 10,
859
+ binning_strategy: BinningStrategy | str = BinningStrategy.UNIFORM,
860
+ min_samples: int = DEFAULT_CALIBRATION_MIN_SAMPLES,
861
+ metric_bins: int = 10,
862
+ schema_id: str | None = None,
863
+ strategy_name: str | None = None,
864
+ description: str | None = None,
865
+ ) -> CalibrationModel:
866
+ """Deterministically fit an immutable, verified CalibrationModel from labeled samples."""
867
+ try:
868
+ resolved_method = (
869
+ method if isinstance(method, CalibrationMethod) else CalibrationMethod(method)
870
+ )
871
+ except ValueError as exc:
872
+ raise ConfigurationError(f"Unsupported calibration method: {method!r}.") from exc
873
+
874
+ try:
875
+ resolved_binning = (
876
+ binning_strategy
877
+ if isinstance(binning_strategy, BinningStrategy)
878
+ else BinningStrategy(binning_strategy)
879
+ )
880
+ except ValueError as exc:
881
+ raise ConfigurationError(f"Unsupported binning_strategy: {binning_strategy!r}.") from exc
882
+
883
+ if (
884
+ isinstance(min_samples, bool)
885
+ or not isinstance(min_samples, int)
886
+ or min_samples < MIN_CALIBRATION_SAMPLES_FLOOR
887
+ ):
888
+ raise ConfigurationError(
889
+ f"min_samples must be an integer >= {MIN_CALIBRATION_SAMPLES_FLOOR}."
890
+ )
891
+
892
+ coerced = _coerce_samples(samples)
893
+ if len(coerced) < min_samples:
894
+ raise ConfigurationError(
895
+ f"Calibration requires at least {min_samples} labeled samples; got {len(coerced)}."
896
+ )
897
+
898
+ pos_count = sum(1 for s in coerced if s.is_correct)
899
+ neg_count = len(coerced) - pos_count
900
+ if pos_count < 1 or neg_count < 1:
901
+ raise ConfigurationError(
902
+ "Calibration requires both positive (True) and negative (False) labeled outcomes; "
903
+ f"got positive={pos_count}, negative={neg_count}."
904
+ )
905
+
906
+ raw_metrics = compute_calibration_metrics(coerced, num_bins=metric_bins)
907
+
908
+ isotonic_params: IsotonicParameters | None = None
909
+ platt_params: PlattParameters | None = None
910
+ histogram_params: HistogramParameters | None = None
911
+
912
+ if resolved_method == CalibrationMethod.ISOTONIC:
913
+ isotonic_params = _fit_isotonic(coerced)
914
+ calibrated_samples = [
915
+ CalibrationSample(
916
+ raw_score=_eval_isotonic(isotonic_params, s.raw_score),
917
+ is_correct=s.is_correct,
918
+ )
919
+ for s in coerced
920
+ ]
921
+ elif resolved_method == CalibrationMethod.PLATT:
922
+ platt_params = _fit_platt(coerced)
923
+ calibrated_samples = [
924
+ CalibrationSample(
925
+ raw_score=_eval_platt(platt_params, s.raw_score),
926
+ is_correct=s.is_correct,
927
+ )
928
+ for s in coerced
929
+ ]
930
+ else:
931
+ histogram_params = _fit_histogram(
932
+ coerced,
933
+ num_bins=num_bins,
934
+ binning_strategy=resolved_binning,
935
+ )
936
+ calibrated_samples = [
937
+ CalibrationSample(
938
+ raw_score=_eval_histogram(histogram_params, s.raw_score),
939
+ is_correct=s.is_correct,
940
+ )
941
+ for s in coerced
942
+ ]
943
+
944
+ after_metrics = compute_calibration_metrics(calibrated_samples, num_bins=metric_bins)
945
+
946
+ try:
947
+ metadata = CalibrationMetadata(
948
+ artifact_version=CALIBRATION_ARTIFACT_VERSION,
949
+ method=resolved_method,
950
+ scale="0-1",
951
+ sample_count=len(coerced),
952
+ positive_count=pos_count,
953
+ negative_count=neg_count,
954
+ fitted_at=datetime.now(UTC).isoformat(),
955
+ ece_before=raw_metrics.ece,
956
+ ece_after=after_metrics.ece,
957
+ mce_before=raw_metrics.mce,
958
+ mce_after=after_metrics.mce,
959
+ brier_before=raw_metrics.brier_score,
960
+ brier_after=after_metrics.brier_score,
961
+ schema_id=schema_id,
962
+ strategy_name=strategy_name,
963
+ description=description,
964
+ )
965
+ return CalibrationModel(
966
+ artifact_version=CALIBRATION_ARTIFACT_VERSION,
967
+ metadata=metadata,
968
+ isotonic=isotonic_params,
969
+ platt=platt_params,
970
+ histogram=histogram_params,
971
+ )
972
+ except ValidationError as exc:
973
+ raise ConfigurationError("Failed to construct validated CalibrationModel.") from exc
974
+
975
+
976
+ def validate_calibrator(calibrator: Any) -> ConfidenceCalibrator | None:
977
+ """Validate an optional calibrator argument eagerly, raising ConfigurationError if invalid."""
978
+ if calibrator is None:
979
+ return None
980
+ if not isinstance(calibrator, ConfidenceCalibrator):
981
+ raise ConfigurationError(
982
+ "calibrator must implement ConfidenceCalibrator (scale, method, calibrate) or be None."
983
+ )
984
+ scale = calibrator.scale
985
+ method = calibrator.method
986
+ if not isinstance(scale, str) or not scale.strip():
987
+ raise ConfigurationError("ConfidenceCalibrator.scale must be a non-empty string.")
988
+ if not isinstance(method, str) or not method.strip():
989
+ raise ConfigurationError("ConfidenceCalibrator.method must be a non-empty string.")
990
+ return calibrator