Demonstration of using Stan for optimization. See Appendix B in Regression and Other Stories.


Load packages

library("rprojroot")
root<-has_file(".ROS-Examples-root")$make_fix_file()
library("rstan")
rstan_options(auto_write = TRUE)

Plot a parabola \(y = 15 + 10 x - 2 x^2\)

curve(15+10*x-2*x^2, from=-2, to=5)

Show Stan code

writeLines(readLines(root("Parabola","parabola.stan")))
parameters {
  real x;
}
model {
  target += 15 + 10*x - 2*x^2;
}

Compile Stan code

model <- stan_model(root("Parabola","parabola.stan"))
# alternative way
# model <- stan_model(model_code="parameters {real x;} model {target += 15 + 10*x - 2*x^2;}")

Optimize

fit <- optimizing(model)
print(fit)
$par
  x 
2.5 

$value
[1] 27.5

$return_code
[1] 0

$theta_tilde
       x
[1,] 2.5
LS0tCnRpdGxlOiAiUmVncmVzc2lvbiBhbmQgT3RoZXIgU3RvcmllczogUGFyYWJvbGEiCmF1dGhvcjogIkFuZHJldyBHZWxtYW4sIEplbm5pZmVyIEhpbGwsIEFraSBWZWh0YXJpIgpkYXRlOiAiYHIgZm9ybWF0KFN5cy5EYXRlKCkpYCIKb3V0cHV0OgogIGh0bWxfZG9jdW1lbnQ6CiAgICB0aGVtZTogcmVhZGFibGUKICAgIHRvYzogdHJ1ZQogICAgdG9jX2RlcHRoOiAyCiAgICB0b2NfZmxvYXQ6IHRydWUKICAgIGNvZGVfZG93bmxvYWQ6IHRydWUKLS0tCkRlbW9uc3RyYXRpb24gb2YgdXNpbmcgU3RhbiBmb3Igb3B0aW1pemF0aW9uLiBTZWUgQXBwZW5kaXggQiBpbgpSZWdyZXNzaW9uIGFuZCBPdGhlciBTdG9yaWVzLgoKLS0tLS0tLS0tLS0tLQoKCmBgYHtyIHNldHVwLCBpbmNsdWRlPUZBTFNFfQprbml0cjo6b3B0c19jaHVuayRzZXQobWVzc2FnZT1GQUxTRSwgZXJyb3I9RkFMU0UsIHdhcm5pbmc9RkFMU0UsIGNvbW1lbnQ9TkEpCmBgYAoKIyMjIyBMb2FkIHBhY2thZ2VzCgpgY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