CmdStanModel
On this page
- Creating a model
-
Inspecting a model
- stanFile(), exeFile(), hppFile()
- saveHppFile()
- code()
- print()
- variables()
- modelName(), hasStanFile()
- includePaths(), userHeader(), stancOptions(), cppOptions()
- nativeStancOptions()
- cmdstanVersion()
- reportedFeatures()
- buildInfo()
- CmdStanModel::stanBuildInfo()
- isCurrent()
- cmdstanDefaults()
- checkSyntax()
- format()
- exposeFunctions(), functions()
- Running a model
Examples
CmdStanModel compiles a Stan program and runs CmdStan’s methods on it. Method names are camelCase versions of CmdStanR’s.
Creating a model
cmdstan_model() and new CmdStanModel() return a model.
new CmdStanModel()
new CmdStanModel( ?string $stanFile = null, ?string $exeFile = null, bool $quiet = true, ?string $dir = null, bool $pedantic = false, ?array $includePaths = null, ?string $userHeader = null, ?array $cppOptions = null, ?array $stancOptions = null, ?bool $forceRecompile = null, ?float $timeout = null,)Compiles the program, or reuses an up-to-date executable, before it returns. cmdstan_model() takes the same arguments except timeout, the compile limit in seconds.
- Give
stanFile, whose executable goes beside it or indir, orexeFilealone to use an existing executable. A model fromexeFilealone refuses the build arguments, because there is nothing to build. cppOptionsare named make variables, such as['STAN_THREADS' => true]. Names are uppercased, andfalseturns an option off even whenmake/localturns it on. Unnamed entries and values containing command expansions or shell metacharacters are rejected. Usecmdstan_make_local()for other make lines.stancOptionstake flags and values, such as['O1', 'canonicalize' => 'deprecations', 'max-line-length' => 78]. Flags with their own argument are rejected: useincludePaths,pedantic,userHeader, orcppOptions: ['STAN_OPENCL' => true].- A rebuild happens when the build record shows that the program, its
#includefiles, the user header,cppOptions,stancOptions,make/local, or the selected CmdStan changed.forceRecompile: truerebuilds anyway, and its default comes from thecmdstanr_force_recompileoption. quiet: false, or thecmdstanr_verboseoption, reports whether and why the model compiles.
Compiling models covers rebuilds, StaleExecutableException, and concurrent builds.
Inspecting a model
stanFile(), exeFile(), hppFile()
$model->stanFile(): ?string$model->exeFile(): string$model->hppFile(): ?stringstanFile() and hppFile() are null for a model from exeFile alone. hppFile() writes the generated C++ to a temporary file on first use.
saveHppFile()
$model->saveHppFile(string $dir): stringReturns the copied path. The directory must exist. Throws for a model from exeFile alone.
code()
$model->code(): ?stringnull, with a warning, for a model from exeFile alone.
print()
$model->print(?bool $lineNumbers = null): voidWith line numbers when lineNumbers is true, or when the cmdstanr_print_line_numbers option is set.
variables()
$model->variables(): arrayReturns data, parameters, transformed_parameters, and generated_quantities, each keyed by variable name with its type and dimensions, from stanc --info.
modelName(), hasStanFile()
$model->modelName(): string$model->hasStanFile(): boolThe name is the Stan file’s or executable’s base name.
includePaths(), userHeader(), stancOptions(), cppOptions()
$model->includePaths(): array$model->userHeader(): ?string$model->stancOptions(): array$model->cppOptions(): arraycppOptions() returns make variables and values, so ['stan_threads' => true] comes back as ['STAN_THREADS' => 'true']. stancOptions() returns the stanc arguments given as stancOptions.
nativeStancOptions()
$model->nativeStancOptions(): arrayThe stanc options used when building exposed functions and model methods.
cmdstanVersion()
$model->cmdstanVersion(): ?stringFrom the build record, else the Stan version the executable reports. null when neither is known.
reportedFeatures()
$model->reportedFeatures(): arraystan_threads, stan_mpi, stan_opencl, stan_no_range_checks, and stan_version, from <exe> info.
buildInfo()
$model->buildInfo(): arrayThe same as stan_build_info() for this model’s executable.
CmdStanModel::stanBuildInfo()
CmdStanModel::stanBuildInfo(string $exeFile): arrayStatic form of stan_build_info() for any executable.
isCurrent()
$model->isCurrent(): boolfalse when the program or its build settings changed after the build. Other failures, such as a stanc error, throw.
cmdstanDefaults()
$model->cmdstanDefaults(string $method = 'sample'): arraymethod is sample, optimize, variational, pathfinder, or laplace. Returns the defaults from <exe> <method> help-all, under this package’s option names (such as iter_sampling and adapt_delta), in help order.
checkSyntax()
$model->checkSyntax( bool $pedantic = false, ?array $includePaths = null, array $stancOptions = [], bool $quiet = false,): boolReturns true, or throws for invalid Stan. Include paths default to the model’s.
format()
$model->format( bool $overwriteFile = false, array|bool $canonicalize = false, bool $backup = true, ?int $maxLineLength = null, bool $quiet = false,): stringReturns the formatted program, with format_stan_file()’s options. After overwriteFile: true, create the model again to use the rewritten file.
exposeFunctions(), functions()
$model->exposeFunctions( ?float $timeout = null, bool $quiet = false,): StanFunctions$model->functions(): StanFunctionsexposeFunctions() compiles the functions into a library called through PHP FFI and returns a StanFunctions. functions() returns it afterwards and throws before exposeFunctions(). Needs the FFI extension. Log density and model methods gives examples.
Running a model
Each method takes PHP named arguments or one associative options array. An option left out or null uses the installed CmdStan’s default. Every data option accepts an array, a JSON file, a StanData, or a table.
sample()
$model->sample(mixed ...$options): CmdStanMCMCReturns a CmdStanMCMC. Options are named arguments or one associative array, and unknown options throw. Options lists them, and MCMC sampling explains them.
$fit = $model->sample(data: $data, seed: 123, chains: 4);sampleMpi()
$model->sampleMpi( string $mpiCmd = 'mpiexec', array $mpiArgs = [], mixed ...$options,): CmdStanMCMCReturns a CmdStanMCMC. Takes the sampling options, defaults to one chain, and runs chains one after another. An associative mpiArgs such as ['n' => 4] becomes -n 4, and a list is passed as literal arguments. Compile with ['STAN_MPI' => true, 'CXX' => 'mpicxx', 'TBB_CXX_TYPE' => 'gcc'] and install an MPI runtime. The launch command is unit-tested, but no run on a real MPI cluster has been tested.
optimize()
$model->optimize(mixed ...$options): CmdStanMLEReturns a CmdStanMLE. Optimization explains the options.
laplace()
$model->laplace(mixed ...$options): CmdStanLaplaceReturns a CmdStanLaplace. mode is an optimization fit, a CSV or JSON file, or null to run optimize() first with opt_args. jacobian defaults to true.
variational()
$model->variational(mixed ...$options): CmdStanVBReturns a CmdStanVB. Variational inference explains the options.
pathfinder()
$model->pathfinder(mixed ...$options): CmdStanPathfinderReturns a CmdStanPathfinder.
generateQuantities()
$model->generateQuantities( CmdStanFit|array|string $fittedParams, mixed ...$options,): CmdStanGQReturns a CmdStanGQ. fittedParams is an MCMC fit, an optimization, Laplace, variational, or Pathfinder fit (its draws are written as one sample-style CSV file, as in CmdStanR 1.0), or a list of CmdStan CSV files. Generated quantities gives examples.
diagnose()
$model->diagnose(mixed ...$options): CmdStanDiagnoseReturns a CmdStanDiagnose. epsilon and error set the finite-difference step and tolerance.
logProb()
$model->logProb(mixed ...$options): CmdStanFitReturns a CmdStanFit with the log density and gradient at the given parameter values. Give exactly one of unconstrained_params and constrained_params, and optionally jacobian. For in-process evaluation, use the fit’s model methods.