# Original Bopbun synthetic input, code and figures: CC0-1.0.
library(ggplot2)
out <- dirname(normalizePath(sub('^--file=', '', grep('^--file=',commandArgs(),value=TRUE)[1])))
d <- data.frame(group=rep(c('A','B'),each=10),
  value=c(0,.2,.3,.4,.5,.6,.7,.8,1.2,2.5,0,.5,1,1.5,2,2.5,3,3.5,4,4.5))
d$id <- seq_len(nrow(d))
write.csv(d,file.path(out,'synthetic.csv'),row.names=FALSE)
# Gaussian kernel estimate at each observation, calculated within its group.
h <- 0.5
d$kde <- NA_real_
for (g in unique(d$group)) {
  i <- which(d$group==g)
  y <- d$value[i]
  d$kde[i] <- vapply(y,function(v) mean(dnorm(v,mean=y,sd=h)),numeric(1))
}
write.csv(d,file.path(out,'point-density.csv'),row.names=FALSE)
base <- ggplot(d,aes(group,value)) +
  scale_y_continuous(breaks=0:5,limits=c(-.25,5)) +
  labs(x='Group',y='Value (a.u.)') + theme_classic(base_size=13)
pos <- position_jitter(width=.12,height=0,seed=23)
before <- base + geom_point(position=pos,size=3,colour='#666666')
after <- base + geom_point(aes(colour=kde),position=pos,size=3) +
  scale_colour_gradient(low='#dbe9f6',high='#163f70',limits=c(0,.6),
                        name='KDE\n(1/a.u.)')
bad <- base + geom_jitter(aes(colour=after_stat(density)),width=.12,height=0)
message <- tryCatch({ggplot_build(bad);'unexpected success'},error=function(e)conditionMessage(e))
writeLines(message,file.path(out,'actual-error.txt'))
stopifnot(grepl('density',message),message!='unexpected success')
b <- ggplot_build(before)$data[[1]]
a <- ggplot_build(after)$data[[1]]
stopifnot(nrow(a)==20,identical(a$x,b$x),identical(a$y,b$y),identical(a$y,d$value))
write.csv(data.frame(id=d$id,source_y=d$value,before_x=b$x,after_x=a$x,
  before_y=b$y,after_y=a$y),file.path(out,'position-check.csv'),row.names=FALSE)
ggsave(file.path(out,'before.png'),before,width=6,height=4.5,units='in',dpi=200,bg='white')
ggsave(file.path(out,'after.png'),after,width=6,height=4.5,units='in',dpi=200,bg='white')
ggsave(file.path(out,'after.pdf'),after,width=6,height=4.5,units='in',bg='white',timestamp=FALSE)
sink(file.path(out,'session-info.txt')); print(sessionInfo()); sink()
print(aggregate(kde~group,d,range))
