"""Plan a priority review plus a simple random audit, then bound the remaining misses.""" import argparse import csv import json import math import random import secrets from pathlib import Path def select_scans(ids, priority, audit, seed): if not ids or any(not isinstance(key, str) or not key for key in ids): raise ValueError("Each scan needs a nonempty string ID") if len(set(ids)) != len(ids): raise ValueError("Each physical scan must appear once") tail = len(ids) - priority if not 0 <= priority <= len(ids) or not 0 <= audit <= tail or (tail and not audit): raise ValueError("Use a valid priority count and sample at least one scan if the tail is nonempty") return ids[:priority], random.Random(seed).sample(ids[priority:], audit) def compatible(population, sampled, observed, total): """Does the hypergeometric probability of this few misses exceed 5%?""" # Interchanging the sample and the set of misses preserves their overlap. # Choose the representation with the smaller binomial denominator. if min(total, population - total) < min(sampled, population - sampled): sampled, total = total, sampled lower = max(0, sampled + total - population) upper = min(observed, total, sampled) ways = sum(math.comb(total, j) * math.comb(population - total, sampled - j) for j in range(lower, upper + 1)) return 20 * ways > math.comb(population, sampled) def upper_total(population, sampled, misses): """Largest feasible total whose lower-tail probability exceeds 1/20.""" if not 0 <= misses <= sampled <= population: raise ValueError("Invalid population, sample or miss count") if misses == sampled: return population # Invert the CDF using integer arithmetic, with no numerical cutoff in the tails. lo = misses largest = population - sampled + misses step = 1 hi = min(largest, misses + step) while hi < largest and compatible(population, sampled, misses, hi): lo = hi step *= 2 hi = min(largest, misses + step) while lo < hi: total = (lo + hi + 1) // 2 if compatible(population, sampled, misses, total): lo = total else: hi = total - 1 return lo def plan_size(population, limit, allowed): """Smallest fixed draw meeting the remaining-miss target for up to allowed observed misses.""" if population < 0 or limit < 0 or not 0 <= allowed <= population: raise ValueError("Use nonnegative sizes and an allowed miss count no larger than the tail") lo = int(population > 0) # Nonempty audits use at least one observation. hi = population while lo < hi: n = (lo + hi) // 2 x = min(n, allowed) # Rule out the first total that would leave more than the target uninspected. if population - n <= limit or not compatible(population, n, x, x + limit + 1): hi = n else: lo = n + 1 x = min(lo, allowed) return dict(tail_population=population, remaining_miss_limit=limit, allowed_audit_misses=allowed, audit_size=lo, uninspected_scans=population-lo, upper_95_if_zero=upper_total(population,lo,0), upper_95_if_maximum_allowed=upper_total(population,lo,x)-x) def load_queue(path): ids = [] views = set() for line in path.read_text(encoding="utf-8-sig").splitlines(): if line.strip(): row = json.loads(line) if not isinstance(row, dict): raise ValueError("Each queue row must be an object") ids.append(row.get("id")) views.add(row.get("view")) if len(views) != 1: raise ValueError("Supply the complete ranked queue for one view") return ids def draw(args): ids = load_queue(args.queue) seed = args.seed if args.seed is not None else secrets.randbits(128) priority, sample = select_scans(ids, args.priority, args.audit, seed) plan = dict(version=1, total_scans=len(ids), priority_ids=priority, audit_ids=sample, seed=seed) args.output.mkdir() (args.output/"plan.json").write_text(json.dumps(plan, ensure_ascii=False), encoding="utf-8") with (args.output/"labels.csv").open("w", newline="", encoding="utf-8") as file: writer = csv.writer(file) writer.writerow(["id", "miss"]) writer.writerows((key, "") for key in priority + sample) def summarize(args): plan = json.loads((args.folder/"plan.json").read_text(encoding="utf-8")) if plan["version"] != 1: raise ValueError("Unknown plan version") priority, sample = plan["priority_ids"], plan["audit_ids"] size = plan["total_scans"] selected = priority + sample if (type(size) is not int or size < 1 or len(selected) > size or (len(priority) < size and not sample) or any(not isinstance(key, str) or not key for key in selected) or len(set(selected)) != len(selected)): raise ValueError("Invalid review plan") labels = {} with (args.folder/"labels.csv").open(encoding="utf-8-sig", newline="") as file: reader = csv.DictReader(file) if reader.fieldnames != ["id", "miss"]: raise ValueError("Expected id and miss columns") for row in reader: key = row["id"] if key in labels or row["miss"] not in ("0", "1") or None in row: raise ValueError("Each selected scan needs exactly one binary miss label") labels[key] = int(row["miss"]) if labels.keys() != set(priority + sample): raise ValueError("Labels must cover exactly the planned review") tail = size - len(priority) n = len(sample) x = sum(labels[key] for key in sample) print(json.dumps(dict(total_scans=size, priority_reviewed=len(priority), priority_misses=sum(labels[key] for key in priority), tail_population=tail, audit_reviewed=n, audit_misses=x, uninspected_scans=tail-n, estimated_uninspected_misses=(tail-n)*x/n if n else 0, upper_95_uninspected_misses=upper_total(tail,n,x)-x), indent=2)) def main(): parser = argparse.ArgumentParser(description=__doc__) commands = parser.add_subparsers(dest="command", required=True) plan = commands.add_parser("draw", help="Create a fixed sample and blank labels in a new directory") plan.add_argument("queue", type=Path) plan.add_argument("output", type=Path) plan.add_argument("--priority", type=int, required=True) plan.add_argument("--audit", type=int, required=True) plan.add_argument("--seed", type=int, help="Reproduce a predetermined sample") size = commands.add_parser("size", help="Plan the fixed random draw before labeling") size.add_argument("population", type=int, help="Number of scans left after priority review") size.add_argument("--remaining-limit", type=int, required=True, help="Target upper bound for still-uninspected misses") size.add_argument("--allow-misses", type=int, default=0, help="Design for up to this many misses in the random draw") report = commands.add_parser("summarize", help="Score every planned label in a completed audit folder") report.add_argument("folder", type=Path) args = parser.parse_args() try: if args.command == "draw": draw(args) elif args.command == "size": print(json.dumps(plan_size(args.population,args.remaining_limit,args.allow_misses), indent=2)) else: summarize(args) except (OSError, ValueError, KeyError, TypeError) as err: parser.exit(1, f"{err}\n") if __name__ == "__main__": main()