################################
### HW2 Q13
### Lower scores suggest disease => T+ if R <= theta (notes' cognitive-test convention).
### PPV = P(D+ | T+) = a / (a + b). Compute PPV(theta=30) - PPV(theta=50).
### ! Rscript "/mnt/c/Users/kirch/OneDrive/Documents/dev/ut-11-hdi/docs/part1/hw2_q13.R"
################################

Dpos = c(107, 128, 62, 2, 5, 23, 46, 41, 36, 101)   # 10 diseased
Dneg = c(38, 60, 78, 46, 34, 67, 46, 7)             #  8 not diseased

ppv.at = function(theta) {
  a = sum(Dpos <= theta)   # true positives
  b = sum(Dneg <= theta)   # false positives
  c = sum(Dpos >  theta)   # false negatives
  d = sum(Dneg >  theta)   # true negatives
  cat(sprintf("theta = %d:  a(TP)=%d  b(FP)=%d  c(FN)=%d  d(TN)=%d", theta, a, b, c, d))
  cat(sprintf("   sens=%.3f  spec=%.3f  PPV=a/(a+b)=%d/%d=%.4f\n",
              a/(a+c), d/(b+d), a, a+b, a/(a+b)))
  a/(a+b)
}
cat("any score exactly at a threshold? ", any(c(Dpos, Dneg) %in% c(30, 50)),
    " (so <= vs < makes no difference)\n\n")
p30 = ppv.at(30)
p50 = ppv.at(50)
cat("\nPPV(30) - PPV(50) :", p30 - p50, "\n")
cat("ANSWER (2 dp)     :", round(p30 - p50, 2), "\n")
