# Area under the curve
#
# Trapezoidal rule
# x values need not be equally spaced
#
trapezoid <- function(x,y) sum(diff(x)*(y[-1]+y[-length(y)]))/2
#
#
# Simpson's rule when `n' is odd
# Composite Simpson and Trapezoidal rules when `n' is even
# x values must be equally spaced
#
simpson <- function(x, y){
n <- length(y)
odd <- n %% 2
if (odd) area <- 1/3*sum( y[1] + 2*sum(y[seq(3,(n-2),by=2)]) +
        4*sum(y[seq(2,(n-1),by=2)]) + y[n])

if (!odd) area <- 1/3*sum( y[1] + 2*sum(y[seq(3,(n-3),by=2)]) +
        4*sum(y[seq(2,(n-2),by=2)]) + y[n-1]) + 1/2*(y[n-1] + y[n])

dx <- x[2] - x[1]
return(area * dx)
}
#
# An example for AUC calculation
x1 <- seq(0, 1, length=21)

roc <- function(x1, a) x1 + a * x1 * (1 - x1)

plot(x, roc(x1, a=0.5), type="l")
lines(x, roc(x1, a=0.8), col=2)
lines(x, roc(x1, a=1.2), col=3)
abline(b=1, lty=2)

y <- roc(x, a=1)

trapezoid(x, y)  # exact answer is 2/3

simpson(x, y) # exact answer is 2/3 