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/binary.py ADDED
@@ -0,0 +1,533 @@
1
+ """Binary label-shift likelihood for a fixed batch of probability scores."""
2
+
3
+ import math
4
+ from collections.abc import Iterable
5
+ from fractions import Fraction
6
+
7
+ import numpy as np
8
+ from numpy.typing import ArrayLike
9
+
10
+ from ._validation import (
11
+ FloatArray,
12
+ integer,
13
+ probability,
14
+ read_only,
15
+ real_array,
16
+ real_number,
17
+ )
18
+ from .results import Decision, EMFit, Optimum
19
+
20
+ _UNIT = 2.0**-53
21
+
22
+
23
+ def exact_support(
24
+ scores: Iterable[float | str | Fraction],
25
+ source_prior: float | str | Fraction,
26
+ floor: float | str | Fraction,
27
+ ) -> Fraction:
28
+ """Evaluate the support C(t) of Proposition 2.1 by rational arithmetic.
29
+
30
+ Parameters
31
+ ----------
32
+ scores : iterable of numbers or strings
33
+ Nonempty sequence of scores strictly between zero and one.
34
+ source_prior : number or str
35
+ Source event rate, strictly between zero and one.
36
+ floor : number or str
37
+ Prevalence t in [0, 1]. Strings preserve decimal or fractional values.
38
+ Each float is read through its shortest decimal representation.
39
+
40
+ Returns
41
+ -------
42
+ Fraction
43
+ Mean of (X_i - 1)/(1 + t(X_i - 1)), for relative score odds X_i.
44
+
45
+ Raises
46
+ ------
47
+ ValueError
48
+ An argument is outside its domain.
49
+ """
50
+
51
+ def fraction(value: float | str | Fraction, name: str) -> Fraction:
52
+ try:
53
+ return Fraction(str(value))
54
+ except (ValueError, ZeroDivisionError):
55
+ raise ValueError(
56
+ f"{name} must be a finite rational number, got {value!r}"
57
+ ) from None
58
+
59
+ prior, t = fraction(source_prior, "source_prior"), fraction(floor, "floor")
60
+ values = [fraction(value, "scores") for value in scores]
61
+ if not 0 < prior < 1:
62
+ raise ValueError(f"source_prior must be strictly between 0 and 1, got {prior}")
63
+ if not 0 <= t <= 1:
64
+ raise ValueError(f"floor must be in [0, 1], got {t}")
65
+ if not values or any(not 0 < value < 1 for value in values):
66
+ raise ValueError(
67
+ "scores must contain at least one value and all must be strictly between 0 and 1"
68
+ )
69
+ odds = [(1 - prior) * v / (prior * (1 - v)) for v in values]
70
+ return sum(((x - 1) / (1 + t * (x - 1)) for x in odds), Fraction(0)) / len(values)
71
+
72
+
73
+ def _bound_ratio(value: float, exponent: int, count: int, slope: float) -> float:
74
+ """Upper bound on value*2**exponent/(count*slope) for value >= 0, slope > 0."""
75
+ if value <= 0:
76
+ return 0.0
77
+ if not math.isfinite(value):
78
+ return math.inf
79
+ log_ratio = (
80
+ math.log(value) + exponent * math.log(2) - math.log(count) - math.log(slope)
81
+ )
82
+ if log_ratio > 700:
83
+ return math.inf
84
+ # The factor exceeds the rounding of the logarithms and the exponential.
85
+ return float(np.nextafter(math.exp(log_ratio) * (1 + 1e-11), math.inf))
86
+
87
+
88
+ class BinaryBatch:
89
+ """Locate the maximum of the binary label-shift likelihood (Proposition 2.1).
90
+
91
+ For a score s and source event rate p, the relative odds are
92
+ X = s(1-p)/(p(1-s)). The likelihood at q is the product of 1 + q(X_i - 1).
93
+
94
+ Parameters
95
+ ----------
96
+ scores : array_like of shape (n,)
97
+ At least one probability strictly between zero and one.
98
+ source_prior : float
99
+ Event rate in the source population, strictly between zero and one.
100
+
101
+ Raises
102
+ ------
103
+ ValueError
104
+ A score, source prevalence or relative odds is outside the floating-point domain.
105
+
106
+ Examples
107
+ --------
108
+ >>> batch = BinaryBatch([.001, .002, .004, .007, .013, .029], source_prior=.01)
109
+ >>> round(batch.mu, 4), batch.decide(.005).side
110
+ (0.9423, 'below')
111
+ >>> batch.optimum().kind
112
+ 'zero'
113
+ """
114
+
115
+ __slots__ = (
116
+ "_at_one",
117
+ "_at_zero",
118
+ "_excess",
119
+ "_relative_odds",
120
+ "_scores",
121
+ "_source_prior",
122
+ )
123
+
124
+ def __init__(self, scores: ArrayLike, source_prior: float) -> None:
125
+ self._source_prior = probability(source_prior, "source_prior", interior=True)
126
+ values = real_array(scores, "scores")
127
+ if values.ndim != 1 or not values.size:
128
+ raise ValueError("scores must be a nonempty vector")
129
+ if not np.all((values > 0) & (values < 1)):
130
+ raise ValueError("scores must be finite and strictly between 0 and 1")
131
+ self._scores = read_only(values)
132
+ # Scale before taking the odds ratio so an intermediate quotient cannot overflow.
133
+ a, ae = np.frexp(values)
134
+ b, be = math.frexp(1 - self.source_prior)
135
+ c, ce = math.frexp(self.source_prior)
136
+ d, de = np.frexp(1 - values)
137
+ with np.errstate(over="ignore", under="ignore"):
138
+ ratios = np.ldexp((a * b) / (c * d), ae + be - ce - de)
139
+ ratios[values == self.source_prior] = 1.0
140
+ if not np.all(np.isfinite(ratios) & (ratios > 0)):
141
+ raise ValueError(
142
+ "scores and source_prior give relative odds outside floating-point range"
143
+ )
144
+ self._relative_odds = read_only(ratios)
145
+ # Scale both scores and prior by the same exact power of two before forming
146
+ # signed support terms. Adjacent floats then retain their direction.
147
+ shift = -np.frexp(np.maximum(values, self.source_prior))[1]
148
+ scaled_score = np.ldexp(values, shift)
149
+ scaled_prior = np.ldexp(self.source_prior, shift)
150
+ self._excess = scaled_score - scaled_prior
151
+ self._at_zero = scaled_prior * (1 - values)
152
+ self._at_one = (1 - self.source_prior) * scaled_score
153
+
154
+ @property
155
+ def scores(self) -> FloatArray:
156
+ """Scores s_i in batch order (read-only)."""
157
+ return self._scores.view()
158
+
159
+ @property
160
+ def source_prior(self) -> float:
161
+ """Source event rate used to compute the relative score odds."""
162
+ return self._source_prior
163
+
164
+ @property
165
+ def relative_odds(self) -> FloatArray:
166
+ """Relative odds X_i = s_i(1-p)/(p(1-s_i)) in batch order (read-only)."""
167
+ return self._relative_odds.view()
168
+
169
+ @property
170
+ def mu(self) -> float:
171
+ """EM-map slope mu = n^-1 sum_i X_i = 1 + C(0), the mean relative odds (Proposition 2.1)."""
172
+ # Use the same scaled summation as for C(t); summing X_i directly avoids
173
+ # loss of the entire mean when C(0) rounds to -1.
174
+ total, _, exponent = self._certified_sum(
175
+ self.relative_odds, np.zeros_like(self.relative_odds)
176
+ )
177
+ return math.ldexp(total / self.scores.size, exponent)
178
+
179
+ def _terms(self, t: float) -> tuple[FloatArray, FloatArray]:
180
+ """Support terms with exact signs and a relative rounding-error bound for each term."""
181
+ with np.errstate(
182
+ over="ignore", under="ignore", divide="ignore", invalid="ignore"
183
+ ):
184
+ denominators = (1 - t) * self._at_zero + t * self._at_one
185
+ terms = np.where(self._excess == 0, 0.0, self._excess / denominators)
186
+ # At most seven roundings stay below 8u; underflow adds at most 2**-1073 to a denominator.
187
+ errors = np.where(
188
+ denominators >= 2.0**-1072,
189
+ 8 * _UNIT + 2.0**-1071 / denominators,
190
+ np.inf,
191
+ )
192
+ return terms, np.where(terms == 0, 0.0, errors)
193
+
194
+ @staticmethod
195
+ def _certified_sum(
196
+ terms: FloatArray, errors: FloatArray
197
+ ) -> tuple[float, float, int]:
198
+ """Return (total, bound, exponent): total is the correctly rounded sum of
199
+ the computed terms times 2**-exponent, and the exact sum of the true
200
+ terms lies in [total-bound, total+bound]*2**exponent."""
201
+ if np.any(np.isinf(terms)):
202
+ # A term overflows only next to an endpoint, where every term of the
203
+ # opposite sign is below 2**54 in magnitude.
204
+ positive, negative = (
205
+ bool(np.any(terms == np.inf)),
206
+ bool(np.any(terms == -np.inf)),
207
+ )
208
+ if positive == negative:
209
+ return 0.0, math.inf, 0
210
+ return (math.inf if positive else -math.inf), 0.0, 0
211
+ exponent = math.frexp(float(np.max(np.abs(terms))))[1]
212
+ scaled = np.ldexp(terms, -exponent) # exact unless a negligible term underflows
213
+ total = math.fsum(scaled)
214
+ if np.any(np.isinf(errors)):
215
+ return total, math.inf, exponent
216
+ error = math.fsum(errors * np.abs(scaled))
217
+ return (
218
+ total,
219
+ error * (1 + 4 * _UNIT) + 2 * _UNIT * abs(total) + terms.size * 2.0**-1072,
220
+ exponent,
221
+ )
222
+
223
+ def _support(self, t: float) -> tuple[float, float, float, int]:
224
+ """C(t) with the certified sum of its terms; raises if C(t) is not representable."""
225
+ terms, errors = self._terms(t)
226
+ if not np.all(np.isfinite(terms)):
227
+ raise ValueError("support terms exceed floating-point range")
228
+ total, bound, exponent = self._certified_sum(terms, errors)
229
+ try:
230
+ value = math.ldexp(total / terms.size, exponent)
231
+ except OverflowError:
232
+ raise ValueError("support mean exceeds floating-point range") from None
233
+ return value, total, bound, exponent
234
+
235
+ def support(self, floor: float) -> float:
236
+ """Evaluate C(t), the mean derivative of the log likelihood (Proposition 2.1).
237
+
238
+ Parameters
239
+ ----------
240
+ floor : float
241
+ Prevalence t in [0, 1].
242
+
243
+ Returns
244
+ -------
245
+ float
246
+ Mean of (X_i - 1)/(1 + t(X_i - 1)).
247
+
248
+ Raises
249
+ ------
250
+ ValueError
251
+ The floor is outside [0, 1] or a support term is outside floating-point range.
252
+ """
253
+ return self._support(probability(floor, "floor"))[0]
254
+
255
+ def decide(self, floor: float, tolerance: float = 1e-12) -> Decision:
256
+ """Compare the likelihood optimum with a floor (Proposition 2.1).
257
+
258
+ Parameters
259
+ ----------
260
+ floor : float
261
+ Prevalence t strictly between zero and one.
262
+ tolerance : float
263
+ Nonnegative absolute numerical tolerance on C(t).
264
+
265
+ Returns
266
+ -------
267
+ Decision
268
+ The optimum lies above or below t if the rounding interval clears the tolerance.
269
+
270
+ Raises
271
+ ------
272
+ ValueError
273
+ A parameter is outside its domain or a support term exceeds floating-point range.
274
+ """
275
+ t = probability(floor, "floor", interior=True)
276
+ tolerance = real_number(tolerance, "tolerance")
277
+ if tolerance < 0:
278
+ raise ValueError(f"tolerance must be nonnegative, got {tolerance}")
279
+ value, total, bound, exponent = self._support(t)
280
+ if math.isfinite(bound):
281
+ scale = Fraction(2) ** exponent / self.scores.size
282
+ if (Fraction(total) - Fraction(bound)) * scale > tolerance:
283
+ return Decision(t, value, "above", tolerance)
284
+ if (Fraction(total) + Fraction(bound)) * scale < -tolerance:
285
+ return Decision(t, value, "below", tolerance)
286
+ return Decision(t, value, "unresolved", tolerance)
287
+
288
+ def _near_stationary_update(self, q: float) -> float:
289
+ # Bound the mean posterior on a shared fixed-point grid. Each row
290
+ # contributes an interval smaller than 1/65536 of one ulp of q, even
291
+ # when nearly equal and opposite score contributions cancel.
292
+ start, source = Fraction(q), Fraction(self.source_prior)
293
+ unit = Fraction(math.ulp(q)) / 65536
294
+ left, right = 0, 0
295
+ scores, counts = np.unique(self.scores, return_counts=True)
296
+ for score, count in zip(scores, counts, strict=True):
297
+ value = Fraction(float(score))
298
+ event = start * (1 - source) * value
299
+ other = (1 - start) * source * (1 - value)
300
+ scaled = event / ((event + other) * unit)
301
+ integer_part, remainder = divmod(scaled.numerator, scaled.denominator)
302
+ left += int(count) * integer_part
303
+ right += int(count) * (integer_part + bool(remainder))
304
+ scale = unit / self.scores.size
305
+ # When the exact result straddles a rounding midpoint, choose the
306
+ # possible rounded value closest to q. It cannot move against the slope.
307
+ return min(max(q, float(left * scale)), float(right * scale))
308
+
309
+ def update(self, prevalence: float) -> float:
310
+ """Take one EM step from q using the mean posterior (Proposition 2.1).
311
+
312
+ Parameters
313
+ ----------
314
+ prevalence : float
315
+ Current prevalence q in [0, 1].
316
+
317
+ Returns
318
+ -------
319
+ float
320
+ Mean of q X_i/(1 - q + q X_i).
321
+
322
+ Raises
323
+ ------
324
+ ValueError
325
+ The prevalence is outside [0, 1].
326
+ """
327
+ q = probability(prevalence, "prevalence")
328
+ if q in (0, 1) or not self._excess.any():
329
+ return q
330
+ # Close to a fixed point, compute movement directly to keep its sign.
331
+ terms, errors = self._terms(q)
332
+ if np.all(np.isfinite(terms)):
333
+ total, bound, exponent = self._certified_sum(terms, errors)
334
+ left, le = math.frexp(q)
335
+ right, re = math.frexp(1 - q)
336
+ move = math.ldexp(
337
+ (left * right) * (total / self.scores.size), exponent + le + re
338
+ )
339
+ if abs(move) <= min(q, 1 - q) / 2:
340
+ if q + move != q and abs(total) <= bound:
341
+ return self._near_stationary_update(q)
342
+ return q + move
343
+ # Normalize the two Bayes numerators at a common row scale. Sum the posteriors
344
+ # at a common column scale before rounding subnormal results.
345
+ a, ae = np.frexp(self.scores)
346
+ b, be = math.frexp(q)
347
+ cp, cpe = math.frexp(1 - self.source_prior)
348
+ d, de = np.frexp(1 - self.scores)
349
+ f, fe = math.frexp(1 - q)
350
+ gp, gpe = math.frexp(self.source_prior)
351
+ numerator = (a * b) * cp
352
+ complement = (d * f) * gp
353
+ e = ae + be + cpe
354
+ ce = de + fe + gpe
355
+ top = np.maximum(e, ce)
356
+ denominator = np.ldexp(numerator, e - top) + np.ldexp(complement, ce - top)
357
+ weights = numerator / denominator
358
+ offsets = e - top
359
+ largest = int(offsets.max())
360
+ return math.ldexp(
361
+ math.fsum(np.ldexp(weights, offsets - largest)) / weights.size, largest
362
+ )
363
+
364
+ def log_likelihood(self, prevalence: float) -> float:
365
+ """Evaluate the summed binary log likelihood (Proposition 2.1).
366
+
367
+ Parameters
368
+ ----------
369
+ prevalence : float
370
+ Prevalence q in [0, 1].
371
+
372
+ Returns
373
+ -------
374
+ float
375
+ Sum of log(1 + q(X_i - 1)) relative to q = 0.
376
+
377
+ Raises
378
+ ------
379
+ ValueError
380
+ The prevalence is outside [0, 1].
381
+ """
382
+ q = probability(prevalence, "prevalence")
383
+ if q == 0:
384
+ return 0.0
385
+ with np.errstate(
386
+ over="ignore", under="ignore", divide="ignore", invalid="ignore"
387
+ ):
388
+ # Form q (s_i-p)/(p(1-s_i)) without rounding an intermediate
389
+ # product to zero when one of the factors is subnormal.
390
+ a, ae = np.frexp(self.scores - self.source_prior)
391
+ b, be = math.frexp(q)
392
+ c, ce = math.frexp(self.source_prior)
393
+ d, de = np.frexp(1 - self.scores)
394
+ deviation = np.ldexp((a * b) / (c * d), ae + be - ce - de)
395
+ direct = (deviation >= -0.5) & np.isfinite(deviation)
396
+ terms = np.empty_like(deviation)
397
+ terms[direct] = np.log1p(deviation[direct])
398
+ tail = self.scores[~direct]
399
+ log_ratio = (
400
+ np.log(tail)
401
+ - np.log1p(-tail)
402
+ + math.log1p(-self.source_prior)
403
+ - math.log(self.source_prior)
404
+ )
405
+ terms[~direct] = np.logaddexp(np.log1p(-q), math.log(q) + log_ratio)
406
+ return math.fsum(terms)
407
+
408
+ def optimum(self, width: float = 1e-12, max_iter: int = 256) -> Optimum:
409
+ """Bracket the maximizer of the binary likelihood (Proposition 2.1).
410
+
411
+ Parameters
412
+ ----------
413
+ width : float
414
+ Positive target width for an interior bracket.
415
+ max_iter : int
416
+ Maximum number of bisection steps, at least one.
417
+
418
+ Returns
419
+ -------
420
+ Optimum
421
+ Endpoint, interval around an interior optimum, or [0, 1] for a flat likelihood.
422
+ A rounding interval that leaves a wider bracket gives 'unresolved'.
423
+
424
+ Raises
425
+ ------
426
+ ValueError
427
+ The width or iteration budget is outside its domain.
428
+ RuntimeError
429
+ Bisection exhausts the iteration budget.
430
+ """
431
+ width = real_number(width, "width")
432
+ if width <= 0:
433
+ raise ValueError(f"width must be positive, got {width}")
434
+ max_iter = integer(max_iter, "max_iter", 1)
435
+ above = bool(np.any(self.scores > self.source_prior))
436
+ below = bool(np.any(self.scores < self.source_prior))
437
+ if not above and not below:
438
+ return Optimum("flat", 0.0, 1.0, False)
439
+ if not below:
440
+ return Optimum("one", 1.0, 1.0, True)
441
+ if not above:
442
+ return Optimum("zero", 0.0, 0.0, True)
443
+ # A mixed batch has a strictly concave likelihood.
444
+ terms0, errors0 = self._terms(0.0)
445
+ total0, bound0, exponent0 = self._certified_sum(terms0, errors0)
446
+ if total0 + bound0 <= 0:
447
+ return Optimum("zero", 0.0, 0.0, True)
448
+ terms1, errors1 = self._terms(1.0)
449
+ total1, bound1, exponent1 = self._certified_sum(terms1, errors1)
450
+ if total1 - bound1 >= 0:
451
+ return Optimum("one", 1.0, 1.0, True)
452
+ # On [0,1] each |term| is at least its smaller endpoint value, so L'
453
+ # falls at rate at least n*slope and an uncertain sign confines the root.
454
+ with np.errstate(over="ignore", invalid="ignore"):
455
+ least = np.minimum(
456
+ np.where(errors0 < 1, np.abs(terms0) * (1 - errors0), 0.0),
457
+ np.where(errors1 < 1, np.abs(terms1) * (1 - errors1), 0.0),
458
+ )
459
+ slope = float(np.mean(np.minimum(least, 1e150) ** 2)) * (1 - 1e-12)
460
+ if total0 - bound0 <= 0 or total1 + bound1 >= 0:
461
+ lower, upper = 0.0, 1.0
462
+ if slope > 0:
463
+ if total0 - bound0 <= 0:
464
+ upper = min(
465
+ 1.0,
466
+ _bound_ratio(total0 + bound0, exponent0, terms0.size, slope),
467
+ )
468
+ if total1 + bound1 >= 0:
469
+ gap = _bound_ratio(bound1 - total1, exponent1, terms1.size, slope)
470
+ lower = max(0.0, float(np.nextafter(1 - gap, 0.0)))
471
+ return Optimum("unresolved", lower, upper, True)
472
+ # L'(lo) > 0 > L'(hi) stays certified, so [lo, hi] always contains the maximizer.
473
+ lo, hi = 0.0, 1.0
474
+ for _ in range(max_iter):
475
+ mid = (lo + hi) / 2
476
+ total, bound, exponent = self._certified_sum(*self._terms(mid))
477
+ if total - bound > 0:
478
+ lo = mid
479
+ elif total + bound < 0:
480
+ hi = mid
481
+ else:
482
+ # The sign at mid is uncertain: confine the root around mid instead.
483
+ if slope > 0:
484
+ left = _bound_ratio(
485
+ bound - total, exponent, self.scores.size, slope
486
+ )
487
+ right = _bound_ratio(
488
+ total + bound, exponent, self.scores.size, slope
489
+ )
490
+ lo = max(lo, float(np.nextafter(mid - left, -np.inf)))
491
+ hi = min(hi, float(np.nextafter(mid + right, np.inf)))
492
+ kind = "interior" if hi - lo <= width else "unresolved"
493
+ return Optimum(kind, lo, hi, True)
494
+ if hi - lo <= width:
495
+ return Optimum("interior", lo, hi, True)
496
+ raise RuntimeError("bisection budget exhausted")
497
+
498
+ def em(
499
+ self, initial: float, tolerance: float = 1e-8, max_iter: int = 1000
500
+ ) -> EMFit:
501
+ """Iterate the binary EM update until its movement is small (Corollary 2.3).
502
+
503
+ Parameters
504
+ ----------
505
+ initial : float
506
+ Starting prevalence strictly between zero and one.
507
+ tolerance : float
508
+ Positive threshold for the absolute change in prevalence.
509
+ max_iter : int
510
+ Maximum number of EM updates, at least one.
511
+
512
+ Returns
513
+ -------
514
+ EMFit
515
+ Last estimate and the movement that ended the run.
516
+
517
+ Raises
518
+ ------
519
+ ValueError
520
+ A parameter is outside its domain.
521
+ """
522
+ q = probability(initial, "initial", interior=True)
523
+ tolerance = real_number(tolerance, "tolerance")
524
+ if tolerance <= 0:
525
+ raise ValueError(f"tolerance must be positive, got {tolerance}")
526
+ max_iter = integer(max_iter, "max_iter", 1)
527
+ for iteration in range(1, max_iter + 1):
528
+ new = self.update(q)
529
+ movement = abs(new - q)
530
+ q = new
531
+ if movement < tolerance:
532
+ return EMFit(q, iteration, True, movement, tolerance, max_iter)
533
+ return EMFit(q, max_iter, False, movement, tolerance, max_iter)