fbcert 1.0.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.
fbcert/__init__.py ADDED
@@ -0,0 +1,18 @@
1
+ """Finite-batch support tests for label-shift EM."""
2
+
3
+ from .binary import BinaryBatch, exact_support
4
+ from .multiclass import MulticlassBatch
5
+ from .results import Decision, Diagnostics, EMFit, EscapeStep, Optimum
6
+
7
+ __version__ = "1.0.0"
8
+
9
+ __all__ = [
10
+ "BinaryBatch",
11
+ "Decision",
12
+ "Diagnostics",
13
+ "EMFit",
14
+ "EscapeStep",
15
+ "MulticlassBatch",
16
+ "Optimum",
17
+ "exact_support",
18
+ ]
fbcert/__main__.py ADDED
@@ -0,0 +1,127 @@
1
+ """Command line for a fixed batch of binary scores."""
2
+
3
+ import argparse
4
+ import csv
5
+ import json
6
+ import os
7
+ from collections.abc import Sequence
8
+ from pathlib import Path
9
+ from tempfile import NamedTemporaryFile
10
+
11
+ from . import BinaryBatch, __version__
12
+
13
+
14
+ def _read_scores(path: Path) -> list[float]:
15
+ with path.open(encoding="utf-8-sig", newline="") as stream:
16
+ rows = csv.DictReader(stream, strict=True)
17
+ if (rows.fieldnames or []).count("score") != 1:
18
+ raise ValueError("scores CSV must have exactly one column named 'score'")
19
+ values = []
20
+ for row in rows:
21
+ try:
22
+ value = float(row["score"])
23
+ except (TypeError, ValueError):
24
+ raise ValueError(
25
+ f"score on CSV line {rows.line_num} must be a number"
26
+ ) from None
27
+ if not 0 < value < 1:
28
+ raise ValueError(
29
+ f"score on CSV line {rows.line_num} must be strictly between 0 and 1, got {value}"
30
+ )
31
+ values.append(value)
32
+ return values
33
+
34
+
35
+ def _write_report(path: Path, report: str) -> None:
36
+ path.parent.mkdir(parents=True, exist_ok=True)
37
+ temporary = None
38
+ try:
39
+ with NamedTemporaryFile(
40
+ "w", encoding="utf-8", dir=path.parent, delete=False
41
+ ) as stream:
42
+ temporary = Path(stream.name)
43
+ stream.write(report)
44
+ # Publish the complete report only if this name is still free.
45
+ # Both paths are on the same filesystem and have the same owner.
46
+ os.link(temporary, path)
47
+ finally:
48
+ if temporary is not None:
49
+ temporary.unlink(missing_ok=True)
50
+
51
+
52
+ def main(argv: Sequence[str] | None = None) -> None:
53
+ """Print the binary support decision, optimum and EM fit for a CSV score column."""
54
+ parser = argparse.ArgumentParser(
55
+ prog="fbcert",
56
+ description="Test whether the label-shift likelihood optimum exceeds a workload floor.",
57
+ )
58
+ parser.add_argument(
59
+ "--version", action="version", version=f"%(prog)s {__version__}"
60
+ )
61
+ parser.add_argument(
62
+ "scores",
63
+ type=Path,
64
+ help="CSV with a header and one 'score' column of probabilities in (0, 1).",
65
+ )
66
+ parser.add_argument(
67
+ "--source-prior", type=float, required=True, help="Source event rate in (0, 1)."
68
+ )
69
+ parser.add_argument(
70
+ "--floor", type=float, required=True, help="Workload floor in (0, 1)."
71
+ )
72
+ parser.add_argument(
73
+ "--initial", type=float, help="Starting EM prevalence (default: source prior)."
74
+ )
75
+ parser.add_argument(
76
+ "--decision-tolerance",
77
+ type=float,
78
+ default=1e-12,
79
+ help="Absolute numerical tolerance on the mean support (default: %(default)s).",
80
+ )
81
+ parser.add_argument(
82
+ "--em-tolerance",
83
+ type=float,
84
+ default=1e-8,
85
+ help="Stop EM when the change in prevalence falls below this value (default: %(default)s).",
86
+ )
87
+ parser.add_argument(
88
+ "--max-iter",
89
+ type=int,
90
+ default=1000,
91
+ help="Maximum number of EM updates (default: %(default)s).",
92
+ )
93
+ parser.add_argument(
94
+ "--output",
95
+ type=Path,
96
+ help="New file for the JSON report (default: standard output).",
97
+ )
98
+ args = parser.parse_args(argv)
99
+ try:
100
+ if args.output is not None and os.path.lexists(args.output):
101
+ raise FileExistsError(f"output already exists: {args.output}")
102
+ scores = _read_scores(args.scores)
103
+ batch = BinaryBatch(scores, args.source_prior)
104
+ em = batch.em(
105
+ args.source_prior if args.initial is None else args.initial,
106
+ args.em_tolerance,
107
+ args.max_iter,
108
+ )
109
+ report = {
110
+ "n": len(scores),
111
+ "source_prior": batch.source_prior,
112
+ "mu": batch.mu,
113
+ "decision": batch.decide(args.floor, args.decision_tolerance).to_dict(),
114
+ "optimum": batch.optimum().to_dict(),
115
+ "em": em.to_dict(),
116
+ }
117
+ rendered = json.dumps(report, indent=2, allow_nan=False) + "\n"
118
+ if args.output is None:
119
+ print(rendered, end="")
120
+ else:
121
+ _write_report(args.output, rendered)
122
+ except (OSError, csv.Error, ValueError) as error:
123
+ parser.error(str(error))
124
+
125
+
126
+ if __name__ == "__main__":
127
+ main()
fbcert/_validation.py ADDED
@@ -0,0 +1,79 @@
1
+ """Numeric input domains shared by the score-batch classes."""
2
+
3
+ import math
4
+ import operator
5
+ from decimal import Decimal
6
+ from numbers import Real
7
+
8
+ import numpy as np
9
+ from numpy.typing import ArrayLike, NDArray
10
+
11
+ FloatArray = NDArray[np.float64]
12
+
13
+
14
+ def real_array(values: ArrayLike, name: str) -> FloatArray:
15
+ """Copy real numeric input to a rectangular binary64 array."""
16
+ try:
17
+ # Keep the types of Python sequences until validation; NumPy otherwise
18
+ # converts a Boolean mixed with numbers to an integer or a float.
19
+ if isinstance(values, np.ndarray):
20
+ array = np.asarray(values)
21
+ else:
22
+ array = np.asarray(values, dtype=object)
23
+ if array.dtype.kind == "O":
24
+ if any(
25
+ isinstance(v, (bool, np.bool_)) or not isinstance(v, (Real, Decimal))
26
+ for v in array.flat
27
+ ):
28
+ raise ValueError
29
+ elif array.dtype.kind not in "iuf":
30
+ raise ValueError
31
+ with np.errstate(over="ignore", invalid="ignore"):
32
+ return np.array(array, dtype=np.float64, copy=True)
33
+ except (TypeError, ValueError, OverflowError):
34
+ raise ValueError(
35
+ f"{name} must contain real numbers in a rectangular array"
36
+ ) from None
37
+
38
+
39
+ def read_only(array: FloatArray) -> FloatArray:
40
+ """Copy an array onto immutable storage."""
41
+ return np.frombuffer(array.tobytes(), dtype=np.float64).reshape(array.shape)
42
+
43
+
44
+ def real_number(value: float, name: str) -> float:
45
+ """Return a finite real scalar."""
46
+ if isinstance(value, (bool, np.bool_)) or not isinstance(value, (Real, Decimal)):
47
+ raise ValueError(f"{name} must be a finite real number, got {value!r}")
48
+ try:
49
+ number = float(value)
50
+ except OverflowError:
51
+ raise ValueError(f"{name} exceeds floating-point range") from None
52
+ if not math.isfinite(number):
53
+ raise ValueError(f"{name} must be finite, got {number}")
54
+ return number
55
+
56
+
57
+ def probability(value: float, name: str, *, interior: bool = False) -> float:
58
+ """Validate a scalar probability on the closed or open unit interval."""
59
+ number = real_number(value, name)
60
+ if interior and not 0 < number < 1:
61
+ raise ValueError(f"{name} must be strictly between 0 and 1, got {number}")
62
+ if not 0 <= number <= 1:
63
+ raise ValueError(f"{name} must be in [0, 1], got {number}")
64
+ return number
65
+
66
+
67
+ def integer(value: int, name: str, minimum: int) -> int:
68
+ """Validate an integer argument against its lower bound."""
69
+ if isinstance(value, (bool, np.bool_)):
70
+ raise ValueError(f"{name} must be an integer >= {minimum}, got {value!r}")
71
+ try:
72
+ number = operator.index(value)
73
+ except TypeError:
74
+ raise ValueError(
75
+ f"{name} must be an integer >= {minimum}, got {value!r}"
76
+ ) from None
77
+ if number < minimum:
78
+ raise ValueError(f"{name} must be an integer >= {minimum}, got {number}")
79
+ return number