# lab2_SDT_Model_Graph.R
# 13 September 2010
# script for drawing a signal detection model
# with decision criteria

# read the RscorePlus graphic file into a data frame
fn <- file.choose()					# choose file
df <- read.delim(fn, header=TRUE)	# read data from file

# Edit below to put in your own name
myName = "Your Name"
mdName = paste(df$Model[1], "Detection Model")	# name of model

# check that the input file is an RscorePlus graphics file
doGrf <- pmatch("_grf", fn)

# check that the model is Gaussian
doPlot <- pmatch("Gaussian", df$Model, nomatch=FALSE)

if(doPlot) {
	# plot distribution for without eyes in red
	# and with eyes in blue

	# ###########################################################
	# Figure out how many criteria and how many signal conditions 
	nsig <- df$nsig[1]	# number of signals
	nrat <- df$nrat[1]	# number of ratings
	ncrt <- nrat - 1	# number of criteria

	# Plot the signal detection model
	# find the maximum density value for setting y-axis
	# find the s0 probability density column: save in ind0
	# find the last signal column: save in ind1
	ind0 <- match("Pred_Density0", names(df))
	ind1 <- ind0 + nsig - 1
	max.density <- 1.2 * max(df[, ind0:ind1], na.rm = TRUE)

	par(pty = "m")
	# Set up the plot
	plot(df[, ind0] ~ Xc, data = df, type = "n",
		lwd = 2, col = "black",
		xlim = c(min(df$Xc, na.rm = TRUE), max(df$Xc, na.rm = TRUE)),
		ylim = c(-0.03, max.density),
		xlab = "Decision Axis (standard deviations of S0)",
		ylab = "Probability Density",
		main = paste(myName, mdName, sep = "\n"))
	
	# plot the probability density functions (s0, s1 ...)
	colors <- c("black", "red", "blue")
	for (i in 0:(nsig-1)){
		lines(df[, ind0+i] ~ Xc, data = df,
		type = "l",
		lwd = 2,
		col = colors[i+1])
	}
	abline(h = 0, col = "gray", lty = "solid")

	# extract the criterion coordinates
	crit <- subset(df, Criteria != is.na(Criteria))[c("Xc", "Xc_se", "Criteria")]
	xc <- df$Xc[1:ncrt]	
	# plot the decision criterion markers
	for (i in 1:ncrt){
		segments(crit$Xc[(2*i)-1], crit$Criteria[(2*i)-1], crit$Xc[2*i], crit$Criteria[2*i], col="darkgreen")}
	# plot the standard error of each criterion marker
	for (i in 1:ncrt){
		segments(crit$Xc[2*i]-crit$Xc_se[2*i], crit$Criteria[2*i],
		crit$Xc[2*i]+crit$Xc_se[2*i], crit$Criteria[2*i], col = "darkgreen")}
	
	# label the response categories
	xc.lab <- rep(0, nrat)
	xc.lab[2:ncrt] <- xc[1:ncrt-1] + diff(xc)/2
	xc.lab[1] <- xc[1] - (diff(xc)/2)[1]
	xc.lab[nrat] <- xc[ncrt] + (diff(xc)/2)[ncrt-1]
	text(xc.lab, -0.025, labels = 1:nrat, cex = 0.7, col="darkgreen")

	# label the distributions
	text(-1, .35, "new\nfaces", cex=0.7, col=colors[1])
	text(1.8, .23, "old\nno eyes", cex=0.7, col=colors[2])
	text(2.9, .29, "old\neyes", cex=0.7, col=colors[3])
} else
{
	print("This script can only plot Gaussian models.")
	print("Make sure you selected the correct input grf file.")
}
