##################################################
### load code
library(Rcpp)
dyn.load("cmLL.so")
source("mLL.R")


##################################################
### simulate fake data to use in call to rexample
dt = read.csv("rsimdata.csv")

## check
lglm = glm(y~x,dt,family=binomial())
print(summary(lglm))


##################################################
###  call C++ from R
beta = c(1,.5)
temp = mLL(dt$x,dt$y,beta)
cat("temp is list with:\n")
print(names(temp))

# vectorized R function for comparison
rmLL = function(x,y,beta) {
   py1 = 1/(1+exp(-(beta[1] + beta[2]*x)))
   return(-sum(ifelse(y==1,log(py1),log(1-py1))))
}

# check we get the same value
junk = rmLL(dt$x,dt$y,beta)
cat("R,C++: ",junk,temp$mLL,"\n")

## time over 2d grid
nval=100
b1g = seq(from=0,to=2,length.out=nval)
b2g = seq(from=0,to=1,length.out=nval)
## bg will be bivariate grid, all vals of b1g x all vals of b2g
bg = expand.grid(b1g,b2g)
nn = nrow(bg)
bgMM = cbind(bg[,1],bg[,2])


## loop over rows of bg and compute -LL
llv1 = rep(0,nn)
tm1 = system.time({
for(i in 1:nn) {
   llv1[i] = mLL(dt$x,dt$y,bgMM[i,])$mLL
}
})

## loop over rows of bg and compute -LL
llv2 = rep(0,nn)
tm2 = system.time({
for(i in 1:nn) {
   llv2[i] = rmLL(dt$x,dt$y,bgMM[i,])
}
})



