"""Metrics for InjectDetX, in plain Python (no dependencies, deterministic). Conventions: a higher score means "more likely an injection". A threshold t flags an item when score > t. """ import math import random def average_precision(y, s): """AP as the step-wise area under precision-recall: sum over distinct thresholds of (R_n - R_{n-1}) * P_n. Tied scores are one threshold. Returns nan when there is no positive.""" pos = sum(y) if pos == 0: return math.nan pairs = sorted(zip(s, y), key=lambda p: -p[0]) tp = fp = 0 ap, last_r = 0.0, 0.0 i = 0 while i < len(pairs): j = i while j < len(pairs) and pairs[j][0] == pairs[i][0]: tp += pairs[j][1] fp += 1 - pairs[j][1] j += 1 r = tp / pos ap += (r - last_r) * (tp / (tp + fp)) last_r = r i = j return ap def threshold_at_fpr(y, s, fpr=0.01): """The lowest threshold t (flag when score > t) whose false-alarm rate on these items is at most `fpr`.""" neg = sorted((v for v, lab in zip(s, y) if lab == 0), reverse=True) if not neg: raise ValueError("no negatives to fix a threshold on") k = math.floor(fpr * len(neg)) # false alarms allowed return neg[k] if k < len(neg) else -math.inf def rates(y, flagged): """Recall on positives and false-alarm rate on negatives for 0/1 decisions.""" pos = [f for f, lab in zip(flagged, y) if lab == 1] neg = [f for f, lab in zip(flagged, y) if lab == 0] return (sum(pos) / len(pos) if pos else math.nan, sum(neg) / len(neg) if neg else math.nan) def pair_accuracy(pairs): """pairs: (attack score, clean score). Share where the attack half scores higher; ties count half.""" if not pairs: return math.nan return sum(1.0 if a > c else 0.5 if a == c else 0.0 for a, c in pairs) / len(pairs) def bootstrap(groups, stat, n=1000, seed=0, alpha=0.05): """Percentile interval of stat(items) over resamples of whole groups. groups: list of item lists.""" rng = random.Random(seed) vals = [] for _ in range(n): sample = [it for _ in groups for it in groups[rng.randrange(len(groups))]] v = stat(sample) if not math.isnan(v): vals.append(v) if not vals: return (math.nan, math.nan) vals.sort() lo = vals[int(alpha / 2 * (len(vals) - 1))] hi = vals[int((1 - alpha / 2) * (len(vals) - 1))] return (lo, hi)