"""Scientific Academy v0.6. Fictional counts, no patient data.
Run: python3 diagnostic_case.py diagnostic_case.csv
Copyright 2026 Evelyn Bandeca. Educational example; CC BY-NC-ND 4.0.
https://evelynbandeca.com/pt/scientificplatform/#editorial-policy
Completed research records may be used under the specific instrument permission.
This is not clinical software.
"""
import csv
import math
import sys

def wilson(k, n, z=1.959963984540054):
    if n == 0:
        return None
    p = k / n
    den = 1 + z*z/n
    center = (p + z*z/(2*n))/den
    half = z*math.sqrt(p*(1-p)/n + z*z/(4*n*n))/den
    return max(0, center-half), min(1, center+half)

def read_counts(path):
    counts = {}
    with open(path, encoding="utf-8", newline="") as f:
        for row in csv.DictReader(f):
            key, value = row["classification"], int(row["count"])
            if key not in {"TP", "FP", "FN", "TN"} or key in counts or value < 0:
                raise ValueError("Invalid or duplicate classification")
            counts[key] = value
    if set(counts) != {"TP", "FP", "FN", "TN"}:
        raise ValueError("Four classifications required")
    return counts

def main(path):
    c = read_counts(path)
    tp, fp, fn, tn = (c[key] for key in ("TP", "FP", "FN", "TN"))
    metrics = {
        "Sensitivity": (tp, tp+fn),
        "Specificity": (tn, tn+fp),
        "Positive predictive value": (tp, tp+fp),
        "Negative predictive value": (tn, tn+fn)
    }
    print("Fictional data; N =", sum(c.values()))
    for name, (k, n) in metrics.items():
        interval = wilson(k, n)
        if interval is None:
            print(name, "undefined")
        else:
            lo, hi = interval
            print(f"{name}: {k/n:.4f} (95% Wilson CI {lo:.4f}, {hi:.4f})")

if __name__ == "__main__":
    main(sys.argv[1] if len(sys.argv)>1 else "diagnostic_case.csv")
