% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/example.R
\name{write_stan_file}
\alias{write_stan_file}
\title{Write Stan code to a file}
\usage{
write_stan_file(
  code,
  dir = getOption("cmdstanr_write_stan_file_dir", tempdir()),
  basename = NULL,
  force_overwrite = FALSE,
  hash_salt = ""
)
}
\arguments{
\item{code}{(character vector) The Stan code to write to the file. This can
be a character vector of length one (a string) containing the entire Stan
program or a character vector with each element containing one line of the
Stan program.}

\item{dir}{(string) An optional path to the directory where the file will be
written. If omitted, a global option \code{cmdstanr_write_stan_file_dir} is
used. If the global options is not set, \link[base:tempfile]{temporary directory}
is used.}

\item{basename}{(string) If \code{dir} is specified, optionally the basename to
use for the file created. If not specified a file name is generated
from \link[rlang:hash]{hashing} the code.}

\item{force_overwrite}{(logical) If set to \code{TRUE} the file will always be
overwritten and thus the resulting model will always be recompiled.}

\item{hash_salt}{(string) Text to add to the model code prior to hashing to
determine the file name if \code{basename} is not set.}
}
\value{
The path to the file.
}
\description{
Convenience function for writing Stan code to a (possibly
\link[base:tempfile]{temporary}) file with a \code{.stan} extension. By default, the
file name is chosen deterministically based on a \link[rlang:hash]{hash}
of the Stan code, and the file is not overwritten if it already has correct
contents. This means that calling this function multiple times with the same
Stan code will reuse the compiled model. This also however means that the
function is potentially not thread-safe. Using \code{hash_salt = Sys.getpid()}
should ensure thread-safety in the rare cases when it is needed.
}
\examples{
# stan program as a single string
stan_program <- "
data {
  int<lower=0> N;
  int<lower=0,upper=1> y[N];
}
parameters {
  real<lower=0,upper=1> theta;
}
model {
  y ~ bernoulli(theta);
}
"

f <- write_stan_file(stan_program)
print(f)

lines <- readLines(f)
print(lines)
cat(lines, sep = "\n")

# stan program as character vector of lines
f2 <- write_stan_file(lines)
identical(readLines(f), readLines(f2))

}
