certlim 0.1.1__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.
- certlim/__init__.py +124 -0
- certlim/calibration.py +185 -0
- certlim/cli.py +314 -0
- certlim/core.py +274 -0
- certlim/experiment.py +505 -0
- certlim/frontier.py +158 -0
- certlim/procurement.py +119 -0
- certlim/py.typed +0 -0
- certlim/quantize.py +153 -0
- certlim/report.py +456 -0
- certlim/rules.py +187 -0
- certlim/transport.py +91 -0
- certlim-0.1.1.dist-info/METADATA +301 -0
- certlim-0.1.1.dist-info/RECORD +18 -0
- certlim-0.1.1.dist-info/WHEEL +5 -0
- certlim-0.1.1.dist-info/entry_points.txt +2 -0
- certlim-0.1.1.dist-info/licenses/LICENSE +21 -0
- certlim-0.1.1.dist-info/top_level.txt +1 -0
certlim/__init__.py
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
"""certlim -- finite-evidence certification limits for safety-critical decisions.
|
|
2
|
+
|
|
3
|
+
The question this package answers is not "is my model accurate?" but "does the
|
|
4
|
+
evidence I can actually buy support a reliable Certify or Reject decision, and if
|
|
5
|
+
not, is that fixable by collecting more of the same or only by changing the
|
|
6
|
+
measurement?"
|
|
7
|
+
|
|
8
|
+
Given two registered classes of systems -- those that are safe under a proposed
|
|
9
|
+
policy and those that are unsafe -- and the evidence law each induces, it computes
|
|
10
|
+
|
|
11
|
+
* ``Delta(n)``, the exact composite separation from ``n`` independent units;
|
|
12
|
+
* the exact best achievable three-state decisiveness under two-sided error control;
|
|
13
|
+
* whether an obstruction is temporary (repetition opens it at a finite ``n``) or
|
|
14
|
+
permanent (only a different measurement can);
|
|
15
|
+
* the deployable Certify / Alert / Reject rule itself;
|
|
16
|
+
* finite-sample calibration, transport margin, and procurement screening.
|
|
17
|
+
|
|
18
|
+
Quick start
|
|
19
|
+
-----------
|
|
20
|
+
>>> import numpy as np
|
|
21
|
+
>>> from certlim import Experiment, frontier
|
|
22
|
+
>>> exp = Experiment(safe=[[0.25, 0.75], [0.75, 0.25]], unsafe=[[0.5, 0.5]])
|
|
23
|
+
>>> exp.diagnose().region
|
|
24
|
+
'delayed'
|
|
25
|
+
>>> exp.n_star()
|
|
26
|
+
2
|
|
27
|
+
>>> round(exp.delta(2), 6)
|
|
28
|
+
0.125
|
|
29
|
+
>>> round(exp.decisiveness(1), 6) # hulls intersect: no rule beats alpha + beta
|
|
30
|
+
0.1
|
|
31
|
+
|
|
32
|
+
Scope
|
|
33
|
+
-----
|
|
34
|
+
Every number is relative to the registered classes and to the evidence alphabet.
|
|
35
|
+
The package computes population geometry exactly; it does not know whether your
|
|
36
|
+
classes are correctly registered, whether your grades were identified by a
|
|
37
|
+
reference experiment rather than by the channel under test, or whether your
|
|
38
|
+
sampling unit is the physical unit it should be. Those are design decisions and
|
|
39
|
+
the package will not make them for you.
|
|
40
|
+
"""
|
|
41
|
+
|
|
42
|
+
from __future__ import annotations
|
|
43
|
+
|
|
44
|
+
from .calibration import (
|
|
45
|
+
BootstrapResult,
|
|
46
|
+
PermutationResult,
|
|
47
|
+
bootstrap_delta,
|
|
48
|
+
permutation_test,
|
|
49
|
+
)
|
|
50
|
+
from .core import (
|
|
51
|
+
DEFAULT_MAX_STATES,
|
|
52
|
+
ZERO_TOL,
|
|
53
|
+
StateSpaceTooLarge,
|
|
54
|
+
block_laws,
|
|
55
|
+
count_states,
|
|
56
|
+
decisiveness,
|
|
57
|
+
hull_tv,
|
|
58
|
+
multinomial_law,
|
|
59
|
+
n_states,
|
|
60
|
+
separating_statistic,
|
|
61
|
+
sion_gap,
|
|
62
|
+
)
|
|
63
|
+
from .experiment import Diagnosis, Experiment, Separator, pairwise_min_tv
|
|
64
|
+
from .frontier import Frontier, FrontierPoint, frontier
|
|
65
|
+
from .procurement import Plan, ProcurementResult, screen
|
|
66
|
+
from .report import build as certification_report
|
|
67
|
+
from .report import write as write_report
|
|
68
|
+
from .quantize import NestedQuantizer, check_data_processing, coarsen_counts
|
|
69
|
+
from .rules import ALERT, CERTIFY, REJECT, Decision, ThreeStateRule, build_rule
|
|
70
|
+
from .transport import TransportReport, class_drift, transport_margin
|
|
71
|
+
|
|
72
|
+
__version__ = "0.1.1"
|
|
73
|
+
|
|
74
|
+
__all__ = [
|
|
75
|
+
"__version__",
|
|
76
|
+
# experiment and geometry
|
|
77
|
+
"Experiment",
|
|
78
|
+
"Diagnosis",
|
|
79
|
+
"Separator",
|
|
80
|
+
"pairwise_min_tv",
|
|
81
|
+
"hull_tv",
|
|
82
|
+
"decisiveness",
|
|
83
|
+
"sion_gap",
|
|
84
|
+
"separating_statistic",
|
|
85
|
+
# frontier
|
|
86
|
+
"frontier",
|
|
87
|
+
"Frontier",
|
|
88
|
+
"FrontierPoint",
|
|
89
|
+
# rule
|
|
90
|
+
"build_rule",
|
|
91
|
+
"ThreeStateRule",
|
|
92
|
+
"Decision",
|
|
93
|
+
"CERTIFY",
|
|
94
|
+
"ALERT",
|
|
95
|
+
"REJECT",
|
|
96
|
+
# evidence menus
|
|
97
|
+
"NestedQuantizer",
|
|
98
|
+
"coarsen_counts",
|
|
99
|
+
"check_data_processing",
|
|
100
|
+
# finite-sample calibration
|
|
101
|
+
"permutation_test",
|
|
102
|
+
"bootstrap_delta",
|
|
103
|
+
"PermutationResult",
|
|
104
|
+
"BootstrapResult",
|
|
105
|
+
# deployment
|
|
106
|
+
"transport_margin",
|
|
107
|
+
"class_drift",
|
|
108
|
+
"TransportReport",
|
|
109
|
+
# report
|
|
110
|
+
"certification_report",
|
|
111
|
+
"write_report",
|
|
112
|
+
# procurement
|
|
113
|
+
"screen",
|
|
114
|
+
"Plan",
|
|
115
|
+
"ProcurementResult",
|
|
116
|
+
# low-level
|
|
117
|
+
"count_states",
|
|
118
|
+
"n_states",
|
|
119
|
+
"multinomial_law",
|
|
120
|
+
"block_laws",
|
|
121
|
+
"StateSpaceTooLarge",
|
|
122
|
+
"DEFAULT_MAX_STATES",
|
|
123
|
+
"ZERO_TOL",
|
|
124
|
+
]
|
certlim/calibration.py
ADDED
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
"""Finite-sample calibration for a plug-in separation estimate.
|
|
2
|
+
|
|
3
|
+
A plug-in ``Delta`` computed from observed counts is an estimate, and a positive
|
|
4
|
+
estimate is not by itself evidence that the channel separates the grades. Two
|
|
5
|
+
checks belong next to it:
|
|
6
|
+
|
|
7
|
+
* a **block permutation test**, which asks whether relabelling the physical
|
|
8
|
+
units at random would produce as much separation. The resampling unit must be
|
|
9
|
+
the physical unit -- the cell, the pack, the battery -- never a row, a cycle or
|
|
10
|
+
a time point, or the test will be anticonservative by orders of magnitude.
|
|
11
|
+
* a **whole-unit bootstrap**, which quantifies sampling variability.
|
|
12
|
+
|
|
13
|
+
Neither is a lower confidence bound on the population ``Delta``. A significant
|
|
14
|
+
permutation p-value rejects label exchangeability; it does not certify
|
|
15
|
+
separation with coverage.
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
from __future__ import annotations
|
|
19
|
+
|
|
20
|
+
from dataclasses import dataclass
|
|
21
|
+
|
|
22
|
+
import numpy as np
|
|
23
|
+
|
|
24
|
+
from .experiment import Experiment
|
|
25
|
+
|
|
26
|
+
__all__ = ["PermutationResult", "BootstrapResult", "permutation_test", "bootstrap_delta"]
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@dataclass(frozen=True)
|
|
30
|
+
class PermutationResult:
|
|
31
|
+
"""Outcome of a unit-blocked label permutation test."""
|
|
32
|
+
|
|
33
|
+
observed: float
|
|
34
|
+
p_value: float
|
|
35
|
+
null_mean: float
|
|
36
|
+
null_q95: float
|
|
37
|
+
n_permutations: int
|
|
38
|
+
blocked_by: str | None
|
|
39
|
+
|
|
40
|
+
def __str__(self) -> str:
|
|
41
|
+
return (
|
|
42
|
+
f"Delta = {self.observed:.4f}, permutation p = {self.p_value:.4f} "
|
|
43
|
+
f"(null mean {self.null_mean:.4f}, q95 {self.null_q95:.4f}, "
|
|
44
|
+
f"B = {self.n_permutations})"
|
|
45
|
+
)
|
|
46
|
+
|
|
47
|
+
@property
|
|
48
|
+
def note(self) -> str:
|
|
49
|
+
return (
|
|
50
|
+
"A permutation p-value tests label exchangeability. It is not a lower "
|
|
51
|
+
"confidence bound on the population separation."
|
|
52
|
+
)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
@dataclass(frozen=True)
|
|
56
|
+
class BootstrapResult:
|
|
57
|
+
"""Whole-unit bootstrap distribution of the plug-in separation."""
|
|
58
|
+
|
|
59
|
+
observed: float
|
|
60
|
+
median: float
|
|
61
|
+
ci_low: float
|
|
62
|
+
ci_high: float
|
|
63
|
+
n_resamples: int
|
|
64
|
+
|
|
65
|
+
def __str__(self) -> str:
|
|
66
|
+
return (
|
|
67
|
+
f"Delta = {self.observed:.4f}, bootstrap median {self.median:.4f}, "
|
|
68
|
+
f"95% interval [{self.ci_low:.4f}, {self.ci_high:.4f}]"
|
|
69
|
+
)
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _validate(unit_counts: np.ndarray, labels: np.ndarray, blocks) -> tuple[np.ndarray, np.ndarray, np.ndarray | None]:
|
|
73
|
+
counts = np.atleast_2d(np.asarray(unit_counts, dtype=float))
|
|
74
|
+
labels = np.asarray(labels).ravel()
|
|
75
|
+
if labels.size != counts.shape[0]:
|
|
76
|
+
raise ValueError("one label per physical unit is required")
|
|
77
|
+
uniq = set(np.unique(labels).tolist())
|
|
78
|
+
if not uniq <= {"safe", "unsafe"} or len(uniq) != 2:
|
|
79
|
+
raise ValueError("labels must contain exactly the values 'safe' and 'unsafe'")
|
|
80
|
+
if (counts < 0).any():
|
|
81
|
+
raise ValueError("counts must be non-negative")
|
|
82
|
+
if blocks is None:
|
|
83
|
+
return counts, labels, None
|
|
84
|
+
blocks = np.asarray(blocks).ravel()
|
|
85
|
+
if blocks.size != labels.size:
|
|
86
|
+
raise ValueError("one block id per physical unit is required")
|
|
87
|
+
return counts, labels, blocks
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def _plug_in_delta(counts: np.ndarray, labels: np.ndarray, smoothing: float, n: int) -> float:
|
|
91
|
+
safe = counts[labels == "safe"]
|
|
92
|
+
unsafe = counts[labels == "unsafe"]
|
|
93
|
+
if safe.size == 0 or unsafe.size == 0:
|
|
94
|
+
return float("nan")
|
|
95
|
+
return Experiment.from_counts(safe, unsafe, smoothing=smoothing).delta(n)
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def permutation_test(
|
|
99
|
+
unit_counts,
|
|
100
|
+
labels,
|
|
101
|
+
*,
|
|
102
|
+
blocks=None,
|
|
103
|
+
n: int = 1,
|
|
104
|
+
smoothing: float = 0.5,
|
|
105
|
+
n_permutations: int = 999,
|
|
106
|
+
seed: int = 0,
|
|
107
|
+
) -> PermutationResult:
|
|
108
|
+
"""Permute grade labels across physical units and recompute the separation.
|
|
109
|
+
|
|
110
|
+
Parameters
|
|
111
|
+
----------
|
|
112
|
+
unit_counts:
|
|
113
|
+
``(n_units, alphabet)`` symbol counts, one row per physical unit.
|
|
114
|
+
labels:
|
|
115
|
+
``'safe'`` or ``'unsafe'`` per unit.
|
|
116
|
+
blocks:
|
|
117
|
+
Optional grouping within which labels are permuted. Blocking on a
|
|
118
|
+
nuisance factor -- chemistry, test rig, temperature -- keeps that factor's
|
|
119
|
+
association with the grade in the null, so a surviving effect cannot be
|
|
120
|
+
explained by it alone.
|
|
121
|
+
"""
|
|
122
|
+
counts, labels, blocks = _validate(unit_counts, labels, blocks)
|
|
123
|
+
observed = _plug_in_delta(counts, labels, smoothing, n)
|
|
124
|
+
rng = np.random.default_rng(seed)
|
|
125
|
+
draws = np.empty(n_permutations)
|
|
126
|
+
for b in range(n_permutations):
|
|
127
|
+
shuffled = labels.copy()
|
|
128
|
+
if blocks is None:
|
|
129
|
+
shuffled = rng.permutation(shuffled)
|
|
130
|
+
else:
|
|
131
|
+
for key in np.unique(blocks):
|
|
132
|
+
idx = np.flatnonzero(blocks == key)
|
|
133
|
+
shuffled[idx] = rng.permutation(shuffled[idx])
|
|
134
|
+
draws[b] = _plug_in_delta(counts, shuffled, smoothing, n)
|
|
135
|
+
finite = draws[np.isfinite(draws)]
|
|
136
|
+
hits = int(np.sum(finite >= observed - 1e-12))
|
|
137
|
+
p = (hits + 1) / (finite.size + 1)
|
|
138
|
+
return PermutationResult(
|
|
139
|
+
observed=float(observed),
|
|
140
|
+
p_value=float(p),
|
|
141
|
+
null_mean=float(finite.mean()) if finite.size else float("nan"),
|
|
142
|
+
null_q95=float(np.quantile(finite, 0.95)) if finite.size else float("nan"),
|
|
143
|
+
n_permutations=int(finite.size),
|
|
144
|
+
blocked_by=None if blocks is None else "blocks",
|
|
145
|
+
)
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def bootstrap_delta(
|
|
149
|
+
unit_counts,
|
|
150
|
+
labels,
|
|
151
|
+
*,
|
|
152
|
+
n: int = 1,
|
|
153
|
+
smoothing: float = 0.5,
|
|
154
|
+
n_resamples: int = 2000,
|
|
155
|
+
seed: int = 0,
|
|
156
|
+
level: float = 0.95,
|
|
157
|
+
) -> BootstrapResult:
|
|
158
|
+
"""Resample whole physical units, stratified by grade, and recompute ``Delta``.
|
|
159
|
+
|
|
160
|
+
Stratifying keeps both classes non-empty in every resample. Resampling rows
|
|
161
|
+
or cycles instead of units would understate the interval badly, because
|
|
162
|
+
repeated measurements of one unit are not independent evidence about the
|
|
163
|
+
population of units.
|
|
164
|
+
"""
|
|
165
|
+
counts, labels, _ = _validate(unit_counts, labels, None)
|
|
166
|
+
observed = _plug_in_delta(counts, labels, smoothing, n)
|
|
167
|
+
safe_idx = np.flatnonzero(labels == "safe")
|
|
168
|
+
unsafe_idx = np.flatnonzero(labels == "unsafe")
|
|
169
|
+
rng = np.random.default_rng(seed)
|
|
170
|
+
draws = np.empty(n_resamples)
|
|
171
|
+
for b in range(n_resamples):
|
|
172
|
+
pick = np.concatenate([
|
|
173
|
+
rng.choice(safe_idx, safe_idx.size, replace=True),
|
|
174
|
+
rng.choice(unsafe_idx, unsafe_idx.size, replace=True),
|
|
175
|
+
])
|
|
176
|
+
draws[b] = _plug_in_delta(counts[pick], labels[pick], smoothing, n)
|
|
177
|
+
finite = draws[np.isfinite(draws)]
|
|
178
|
+
lo, hi = (1.0 - level) / 2.0, 1.0 - (1.0 - level) / 2.0
|
|
179
|
+
return BootstrapResult(
|
|
180
|
+
observed=float(observed),
|
|
181
|
+
median=float(np.median(finite)),
|
|
182
|
+
ci_low=float(np.quantile(finite, lo)),
|
|
183
|
+
ci_high=float(np.quantile(finite, hi)),
|
|
184
|
+
n_resamples=int(finite.size),
|
|
185
|
+
)
|
certlim/cli.py
ADDED
|
@@ -0,0 +1,314 @@
|
|
|
1
|
+
"""Command line interface: ``certlim``.
|
|
2
|
+
|
|
3
|
+
Input is a CSV of per-unit symbol counts plus a grade column, or a JSON file of
|
|
4
|
+
probability laws. Nothing is fitted and no state is written unless an output path
|
|
5
|
+
is given.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import argparse
|
|
11
|
+
import csv
|
|
12
|
+
import json
|
|
13
|
+
import sys
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
|
|
16
|
+
import numpy as np
|
|
17
|
+
|
|
18
|
+
from . import __version__
|
|
19
|
+
from .calibration import bootstrap_delta, permutation_test
|
|
20
|
+
from .core import StateSpaceTooLarge
|
|
21
|
+
from .experiment import Experiment
|
|
22
|
+
from .frontier import frontier as build_frontier
|
|
23
|
+
from .report import write as write_report
|
|
24
|
+
from .rules import build_rule
|
|
25
|
+
|
|
26
|
+
_GRADES = ("safe", "unsafe")
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _load(path: Path, grade_col: str, block_col: str | None):
|
|
30
|
+
"""Read counts, grades and optional blocks from CSV or laws from JSON."""
|
|
31
|
+
if path.suffix.lower() == ".json":
|
|
32
|
+
payload = json.loads(path.read_text(encoding="utf-8"))
|
|
33
|
+
safe = np.atleast_2d(np.asarray(payload["safe"], dtype=float))
|
|
34
|
+
unsafe = np.atleast_2d(np.asarray(payload["unsafe"], dtype=float))
|
|
35
|
+
counts = np.vstack([safe, unsafe])
|
|
36
|
+
labels = np.array(["safe"] * len(safe) + ["unsafe"] * len(unsafe))
|
|
37
|
+
return counts, labels, None, True
|
|
38
|
+
|
|
39
|
+
with path.open(newline="", encoding="utf-8") as handle:
|
|
40
|
+
rows = list(csv.DictReader(handle))
|
|
41
|
+
if not rows:
|
|
42
|
+
raise SystemExit(f"{path}: no rows")
|
|
43
|
+
header = list(rows[0])
|
|
44
|
+
if grade_col not in header:
|
|
45
|
+
raise SystemExit(f"{path}: no column {grade_col!r}; columns are {header}")
|
|
46
|
+
if block_col and block_col not in header:
|
|
47
|
+
raise SystemExit(f"{path}: no column {block_col!r}; columns are {header}")
|
|
48
|
+
skip = {grade_col} | ({block_col} if block_col else set())
|
|
49
|
+
candidates = [c for c in header if c not in skip]
|
|
50
|
+
if not candidates:
|
|
51
|
+
raise SystemExit(f"{path}: no count columns besides {sorted(skip)}")
|
|
52
|
+
|
|
53
|
+
# Real CSVs carry ids, timestamps and metadata alongside the counts. Drop the
|
|
54
|
+
# columns that are not numeric throughout, and say which, rather than failing
|
|
55
|
+
# on the first one or silently coercing it to zero.
|
|
56
|
+
value_cols, dropped = [], []
|
|
57
|
+
for col in candidates:
|
|
58
|
+
try:
|
|
59
|
+
for row in rows:
|
|
60
|
+
float(row[col])
|
|
61
|
+
except (TypeError, ValueError):
|
|
62
|
+
dropped.append(col)
|
|
63
|
+
else:
|
|
64
|
+
value_cols.append(col)
|
|
65
|
+
if not value_cols:
|
|
66
|
+
raise SystemExit(
|
|
67
|
+
f"{path}: none of {candidates} is numeric; count columns are required"
|
|
68
|
+
)
|
|
69
|
+
if dropped:
|
|
70
|
+
print(f"certlim: ignoring non-numeric column(s) {dropped}", file=sys.stderr)
|
|
71
|
+
|
|
72
|
+
labels, counts, blocks = [], [], []
|
|
73
|
+
for row in rows:
|
|
74
|
+
grade = str(row[grade_col]).strip().lower()
|
|
75
|
+
if grade not in _GRADES:
|
|
76
|
+
continue
|
|
77
|
+
labels.append(grade)
|
|
78
|
+
counts.append([float(row[c]) for c in value_cols])
|
|
79
|
+
if block_col:
|
|
80
|
+
blocks.append(row[block_col])
|
|
81
|
+
if not labels:
|
|
82
|
+
raise SystemExit(f"{path}: column {grade_col!r} has no 'safe'/'unsafe' values")
|
|
83
|
+
if len(set(labels)) != 2:
|
|
84
|
+
raise SystemExit(f"{path}: only grade {labels[0]!r} present; both are required")
|
|
85
|
+
return np.array(counts, float), np.array(labels), (np.array(blocks) if block_col else None), False
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def _experiment(counts, labels, smoothing, already_laws, max_states):
|
|
89
|
+
safe, unsafe = counts[labels == "safe"], counts[labels == "unsafe"]
|
|
90
|
+
if already_laws:
|
|
91
|
+
return Experiment(safe, unsafe, max_states=max_states)
|
|
92
|
+
return Experiment.from_counts(safe, unsafe, smoothing=smoothing, max_states=max_states)
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def _emit(payload: dict, out: str | None) -> None:
|
|
96
|
+
text = json.dumps(payload, indent=2, default=float)
|
|
97
|
+
if out:
|
|
98
|
+
Path(out).write_text(text + "\n", encoding="utf-8")
|
|
99
|
+
print(f"written: {out}")
|
|
100
|
+
else:
|
|
101
|
+
print(text)
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def _add_common(p: argparse.ArgumentParser) -> None:
|
|
105
|
+
p.add_argument("input", type=Path, help="CSV of per-unit counts, or JSON of laws")
|
|
106
|
+
p.add_argument("--grade-col", default="grade", help="grade column (default: grade)")
|
|
107
|
+
p.add_argument("--smoothing", type=float, default=0.5,
|
|
108
|
+
help="add-delta smoothing on counts (default: 0.5)")
|
|
109
|
+
p.add_argument("--max-states", type=int, default=250_000,
|
|
110
|
+
help="ceiling on exact enumeration (default: 250000)")
|
|
111
|
+
p.add_argument("--block-col", default=None,
|
|
112
|
+
help="metadata column to treat as a block, not a count")
|
|
113
|
+
p.add_argument("--json", dest="out", default=None, help="write the report to this path")
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def cmd_diagnose(args) -> int:
|
|
117
|
+
counts, labels, _, laws = _load(args.input, args.grade_col, args.block_col)
|
|
118
|
+
exp = _experiment(counts, labels, args.smoothing, laws, args.max_states)
|
|
119
|
+
d = exp.diagnose()
|
|
120
|
+
n_safe, n_unsafe = exp.n_models
|
|
121
|
+
payload = {
|
|
122
|
+
"alphabet": exp.alphabet_size,
|
|
123
|
+
"models": {"safe": n_safe, "unsafe": n_unsafe},
|
|
124
|
+
"region": d.region,
|
|
125
|
+
"n_star": d.n_star,
|
|
126
|
+
"delta_one": d.delta_one,
|
|
127
|
+
"pairwise_min_tv": d.pairwise_min_tv,
|
|
128
|
+
"exact_collision": d.exact_collision,
|
|
129
|
+
"stopping_bound": d.stopping_bound,
|
|
130
|
+
"verdict": d.explain(),
|
|
131
|
+
}
|
|
132
|
+
if not args.out:
|
|
133
|
+
print(f"region {d.region}")
|
|
134
|
+
print(f"Delta(1) {d.delta_one:.6f}")
|
|
135
|
+
print(f"min pairwise TV {d.pairwise_min_tv:.6f}")
|
|
136
|
+
print(f"n* {d.n_star} (search ceiling {d.stopping_bound})")
|
|
137
|
+
print()
|
|
138
|
+
print(d.explain())
|
|
139
|
+
if d.delta_one <= 1e-9 < d.pairwise_min_tv:
|
|
140
|
+
print()
|
|
141
|
+
print("Note: every safe/unsafe pair is separated, yet the hulls still meet. "
|
|
142
|
+
"A pairwise criterion would have reported success here.")
|
|
143
|
+
return 0
|
|
144
|
+
_emit(payload, args.out)
|
|
145
|
+
return 0
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def cmd_frontier(args) -> int:
|
|
149
|
+
counts, labels, _, laws = _load(args.input, args.grade_col, args.block_col)
|
|
150
|
+
exp = _experiment(counts, labels, args.smoothing, laws, args.max_states)
|
|
151
|
+
try:
|
|
152
|
+
f = build_frontier(exp, n_grid=args.n, alpha=args.alpha, beta=args.beta)
|
|
153
|
+
except StateSpaceTooLarge as exc:
|
|
154
|
+
raise SystemExit(str(exc)) from exc
|
|
155
|
+
if args.out:
|
|
156
|
+
_emit({"alpha": f.alpha, "beta": f.beta, "points": f.to_records(),
|
|
157
|
+
"bound_holds": f.bound_holds(), "monotone": f.is_monotone()}, args.out)
|
|
158
|
+
return 0
|
|
159
|
+
print(f)
|
|
160
|
+
print()
|
|
161
|
+
print(f"bound holds: {f.bound_holds()} monotone: {f.is_monotone()}")
|
|
162
|
+
if args.target:
|
|
163
|
+
n = f.units_for(args.target)
|
|
164
|
+
print(f"units for decisiveness >= {args.target}: {n if n else 'not reached on this grid'}")
|
|
165
|
+
return 0
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def cmd_calibrate(args) -> int:
|
|
169
|
+
counts, labels, blocks, laws = _load(args.input, args.grade_col, args.block_col)
|
|
170
|
+
if laws:
|
|
171
|
+
raise SystemExit("calibrate needs per-unit counts (CSV), not aggregate laws (JSON)")
|
|
172
|
+
perm = permutation_test(counts, labels, blocks=blocks, n=args.n,
|
|
173
|
+
smoothing=args.smoothing, n_permutations=args.permutations,
|
|
174
|
+
seed=args.seed)
|
|
175
|
+
boot = bootstrap_delta(counts, labels, n=args.n, smoothing=args.smoothing,
|
|
176
|
+
n_resamples=args.resamples, seed=args.seed)
|
|
177
|
+
payload = {
|
|
178
|
+
"units": int(len(labels)),
|
|
179
|
+
"permutation": {"observed": perm.observed, "p_value": perm.p_value,
|
|
180
|
+
"null_mean": perm.null_mean, "null_q95": perm.null_q95,
|
|
181
|
+
"n_permutations": perm.n_permutations,
|
|
182
|
+
"blocked": perm.blocked_by is not None},
|
|
183
|
+
"bootstrap": {"median": boot.median, "ci_low": boot.ci_low,
|
|
184
|
+
"ci_high": boot.ci_high, "n_resamples": boot.n_resamples},
|
|
185
|
+
"note": perm.note,
|
|
186
|
+
}
|
|
187
|
+
if args.out:
|
|
188
|
+
_emit(payload, args.out)
|
|
189
|
+
return 0
|
|
190
|
+
print(f"units {len(labels)}")
|
|
191
|
+
print(perm)
|
|
192
|
+
print(boot)
|
|
193
|
+
print()
|
|
194
|
+
print(perm.note)
|
|
195
|
+
return 0
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def cmd_rule(args) -> int:
|
|
199
|
+
counts, labels, _, laws = _load(args.input, args.grade_col, args.block_col)
|
|
200
|
+
exp = _experiment(counts, labels, args.smoothing, laws, args.max_states)
|
|
201
|
+
rule = build_rule(exp, n=args.n, alpha=args.alpha, beta=args.beta)
|
|
202
|
+
profile = rule.error_profile(exp)
|
|
203
|
+
payload = {
|
|
204
|
+
"n": rule.n, "alphabet": rule.alphabet,
|
|
205
|
+
"alpha": rule.alpha, "beta": rule.beta,
|
|
206
|
+
"decisiveness": rule.decisiveness,
|
|
207
|
+
"alert_floor": rule.alert_rate_floor(),
|
|
208
|
+
"certify_prob": rule.certify_prob.tolist(),
|
|
209
|
+
"reject_prob": rule.reject_prob.tolist(),
|
|
210
|
+
"states": rule.states.tolist(),
|
|
211
|
+
"error_profile": profile,
|
|
212
|
+
}
|
|
213
|
+
if args.out:
|
|
214
|
+
_emit(payload, args.out)
|
|
215
|
+
return 0
|
|
216
|
+
print(f"block length n {rule.n}")
|
|
217
|
+
print(f"decisiveness {rule.decisiveness:.6f}")
|
|
218
|
+
print(f"forced Alert rate {rule.alert_rate_floor():.6f}")
|
|
219
|
+
print(f"unsafe->certify {profile['unsafe_to_certify']:.6f} (alpha {rule.alpha})")
|
|
220
|
+
print(f"safe->reject {profile['safe_to_reject']:.6f} (beta {rule.beta})")
|
|
221
|
+
if exp.gate(rule.n):
|
|
222
|
+
print()
|
|
223
|
+
print("The hulls still intersect at this block length, so the optimal rule "
|
|
224
|
+
"ignores the data and answers at the allowed error rates. That is the "
|
|
225
|
+
"signal to change the measurement, not to deploy this rule.")
|
|
226
|
+
return 0
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
def cmd_report(args) -> int:
|
|
230
|
+
counts, labels, blocks, laws = _load(args.input, args.grade_col, args.block_col)
|
|
231
|
+
exp = _experiment(counts, labels, args.smoothing, laws, args.max_states)
|
|
232
|
+
write_report(
|
|
233
|
+
args.output, exp, n_grid=args.n, alpha=args.alpha, beta=args.beta,
|
|
234
|
+
rule_n=args.rule_n,
|
|
235
|
+
unit_counts=None if laws else counts, labels=None if laws else labels,
|
|
236
|
+
blocks=None if laws else blocks, smoothing=args.smoothing,
|
|
237
|
+
n_permutations=args.permutations, n_resamples=args.resamples, seed=args.seed,
|
|
238
|
+
title=args.title, subject=args.subject, timestamp=args.timestamp,
|
|
239
|
+
notes=tuple(args.note or ()),
|
|
240
|
+
)
|
|
241
|
+
print(f"written: {args.output}")
|
|
242
|
+
if laws:
|
|
243
|
+
print("certlim: aggregate laws given, so the calibration section is marked not run")
|
|
244
|
+
return 0
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
248
|
+
p = argparse.ArgumentParser(
|
|
249
|
+
prog="certlim",
|
|
250
|
+
description="Finite-evidence certification limits: what any Certify/Reject "
|
|
251
|
+
"rule can achieve from the evidence you have.",
|
|
252
|
+
)
|
|
253
|
+
p.add_argument("--version", action="version", version=f"certlim {__version__}")
|
|
254
|
+
sub = p.add_subparsers(dest="command", required=True)
|
|
255
|
+
|
|
256
|
+
d = sub.add_parser("diagnose", help="is the obstruction permanent, delayed, or absent?")
|
|
257
|
+
_add_common(d)
|
|
258
|
+
d.set_defaults(func=cmd_diagnose)
|
|
259
|
+
|
|
260
|
+
f = sub.add_parser("frontier", help="Delta(n), decisiveness and the bound over a grid")
|
|
261
|
+
_add_common(f)
|
|
262
|
+
f.add_argument("--n", type=int, nargs="+", default=[1, 2, 3, 4, 5, 6, 8, 10])
|
|
263
|
+
f.add_argument("--alpha", type=float, default=0.05)
|
|
264
|
+
f.add_argument("--beta", type=float, default=0.05)
|
|
265
|
+
f.add_argument("--target", type=float, default=None,
|
|
266
|
+
help="report the units needed for this decisiveness")
|
|
267
|
+
f.set_defaults(func=cmd_frontier)
|
|
268
|
+
|
|
269
|
+
c = sub.add_parser("calibrate", help="unit-blocked permutation test and whole-unit bootstrap")
|
|
270
|
+
_add_common(c)
|
|
271
|
+
c.add_argument("--n", type=int, default=1)
|
|
272
|
+
c.add_argument("--permutations", type=int, default=999)
|
|
273
|
+
c.add_argument("--resamples", type=int, default=2000)
|
|
274
|
+
c.add_argument("--seed", type=int, default=0)
|
|
275
|
+
c.set_defaults(func=cmd_calibrate)
|
|
276
|
+
|
|
277
|
+
r = sub.add_parser("rule", help="build the deployable Certify/Alert/Reject rule")
|
|
278
|
+
_add_common(r)
|
|
279
|
+
r.add_argument("--n", type=int, default=1)
|
|
280
|
+
r.add_argument("--alpha", type=float, default=0.05)
|
|
281
|
+
r.add_argument("--beta", type=float, default=0.05)
|
|
282
|
+
r.set_defaults(func=cmd_rule)
|
|
283
|
+
|
|
284
|
+
rep = sub.add_parser("report", help="one-page self-contained HTML certification report")
|
|
285
|
+
_add_common(rep)
|
|
286
|
+
rep.add_argument("-o", "--output", default="certification_report.html")
|
|
287
|
+
rep.add_argument("--n", type=int, nargs="+", default=[1, 2, 3, 4, 5, 6, 8, 10])
|
|
288
|
+
rep.add_argument("--alpha", type=float, default=0.05)
|
|
289
|
+
rep.add_argument("--beta", type=float, default=0.05)
|
|
290
|
+
rep.add_argument("--rule-n", type=int, default=None,
|
|
291
|
+
help="block length for the decision table (default: n* if the gate opens)")
|
|
292
|
+
rep.add_argument("--permutations", type=int, default=999)
|
|
293
|
+
rep.add_argument("--resamples", type=int, default=2000)
|
|
294
|
+
rep.add_argument("--seed", type=int, default=0)
|
|
295
|
+
rep.add_argument("--title", default="Certification report")
|
|
296
|
+
rep.add_argument("--subject", default=None, help="what is being certified")
|
|
297
|
+
rep.add_argument("--timestamp", default=None,
|
|
298
|
+
help="free text for the header; omitting it keeps the output byte-identical")
|
|
299
|
+
rep.add_argument("--note", action="append", help="extra scope caveat (repeatable)")
|
|
300
|
+
rep.set_defaults(func=cmd_report)
|
|
301
|
+
return p
|
|
302
|
+
|
|
303
|
+
|
|
304
|
+
def main(argv=None) -> int:
|
|
305
|
+
args = build_parser().parse_args(argv)
|
|
306
|
+
try:
|
|
307
|
+
return args.func(args)
|
|
308
|
+
except (ValueError, RuntimeError) as exc:
|
|
309
|
+
print(f"certlim: {exc}", file=sys.stderr)
|
|
310
|
+
return 2
|
|
311
|
+
|
|
312
|
+
|
|
313
|
+
if __name__ == "__main__":
|
|
314
|
+
raise SystemExit(main())
|