# Inverse prediction

set1 <- data.frame(y = c(95.71, 98.16, 99.52, 102.09, 103.79, 106.18, 108.14, 110.21),
                   x = c(   96,    98,    100,   102,    104,    106,    108,    110))
set1


mod.fit <- lm(formula = y ~ x, data = set1)
sum.fit <- summary(mod.fit)
sum.fit

ynew <- 102
alpha <- 0.05
n <- nrow(set1)
xhat.new <- (ynew - mod.fit$coefficients[1])/mod.fit$coefficients[2]
as.numeric(xhat.new)

# Package that performs the needed calculations
library(chemCal)
options(width = 60)
methods(class = "lm")
methods(generic.function = "inverse.predict")
save.x <- inverse.predict(object = mod.fit, newdata = 102, alpha = 0.05)
save.x

save.x$Prediction
# save.x$Confidence Limits # Does not work because of the space!
save.x$"Confidence Limits"
# Note: Can always put quotes around component name
save.x$"Prediction"

# t.quantile * sqrt(Varhat(xhat.new)) portion of the CI
#  This is poorly documented in the help, so I tracked it down
#  by looking at the code of the function (it is in .inverse.predict())
save.x$Confidence


# Equations given in notes
sum.sq <- var(set1$x)*(n-1)
var.xhat.new <- sum.fit$sigma^2 / mod.fit$coefficients[2]^2 * (1 + 1/n + (xhat.new - mean(set1$x))^2/sum.sq)
save.ci <- xhat.new - qt(p = c(1-alpha/2,alpha/2), df = mod.fit$df.residual)*sqrt(var.xhat.new)
round(save.ci, 2)


# pty = "s": Use square plot here since both variables are measured on the same scale - "m" is default
# xaxs and yaxs = "i" forces the x and y-axes to be exactly within the given range - "r" is default
par(pty = "s", xaxs = "i", yaxs = "i")  
plot(x = set1$x, y = set1$y, xlab = "Correct temperature", ylab = "Thermometer temperature",
     main = "Thermometer temperature vs. correct temperature", panel.first = grid(col = "gray", lty = "dotted"),
     xlim = c(95, 112), ylim = c(95, 112))

# Finer control of the tick marks
#   Add tick marks without labels, side = 1 is x-axis, tcl is length of tick mark
axis(side = 1, at = seq(from = 95, to = 112, by = 1), labels = FALSE, tcl = -0.25)
#Add tick marks without labels, side = 2 is y-axis
axis(side = 2, at = seq(from = 95, to = 112, by = 1), labels = FALSE, tcl = -0.25)

# Add estimated regression model
curve(expr = predict(object = mod.fit, newdata = data.frame(x = x)),
      col = "red", lty = "solid", lwd = 1, add = TRUE, xlim = c(min(set1$x), max(set1$x)))

# Add inverse prediction
segments(x0 = 0, y0 = ynew, x1 = xhat.new, y1 = ynew, col = "darkgreen", lty = "dashed", lwd = 2)
segments(x0 = xhat.new, y0 = ynew, x1 = xhat.new, y1 = 0, col = "darkgreen", lty = "dashed", lwd = 2)
points(x = save.x$"Confidence Limits", y = c(95.1, 95.1), pch = c("(", ")"), col = "darkgreen")  #Plot CI



#
