# NOT RUN {
# see the examples in the help for stanfit as well
# do a simple optimization problem
opcode <- "
parameters {
real y;
}
model {
target += log(square(y - 5) + 1);
}
"
opfit <- stan(model_code = opcode, chains = 0)
tfun <- function(y) log_prob(opfit, y)
tgrfun <- function(y) grad_log_prob(opfit, y)
or <- optim(1, tfun, tgrfun, method = 'BFGS')
print(or)
# return the gradient as an attribute
tfun2 <- function(y) {
g <- grad_log_prob(opfit, y)
lp <- attr(g, "log_prob")
attr(lp, "gradient") <- g
lp
}
or2 <- nlm(tfun2, 10)
or2
# }
Run the code above in your browser using DataLab