CmdStanPHP

Reference

API reference

All classes and functions are in the CmdStan namespace. Standalone functions keep CmdStanR’s snake_case spelling. Methods, parameters, and properties are camelCase, as PSR-1 requires, so CmdStanR’s fit$output_files() is $fit->outputFiles(); the compatibility contract maps every renamed method. CmdStan option names are unchanged. Inference methods accept PHP named arguments or one associative options array; they reject unknown options instead of silently ignoring them. null generally leaves the installed CmdStan default in effect. Check the compatibility contract for exceptions.

Functions

Function Purpose
cmdstan_model(stanFile: null, exeFile: null, quiet: true, dir: null, pedantic: false, includePaths: null, userHeader: null, cppOptions: null, stancOptions: null, forceRecompile: null) Compile a model, or reuse its up-to-date executable, and return it ready to run
compile_stan_file(stanFile, ...) Compile a Stan file, or reuse its up-to-date executable, without a model object; returns the executable path. Takes cmdstan_model()’s build arguments
check_syntax_stan_file(stanFile, includePaths: null, pedantic: false, stancOptions: [], quiet: false) Check a Stan file’s syntax with stanc; throws on an error
format_stan_file(stanFile, includePaths: null, overwriteFile: false, canonicalize: false, backup: true, maxLineLength: null, quiet: false) Return the formatted program; overwriteFile rewrites the file and keeps a .bak-YYYYMMDDHHMMSS copy unless backup: false
variables_stan_file(stanFile, includePaths: null) / print_stan_file(stanFile, lineNumbers: null) Read a Stan file’s declarations, or print it, without compiling
stan_build_info(exeFile) How an executable was built, from its build record, and what it reports about itself
set_cmdstan_path(path) / cmdstan_path() Select/read CmdStan installation
cmdstan_version() Read installed release version
check_cmdstan_toolchain() Return paths and versions of make, CmdStan’s C++ compiler, and stanc; throws when make or the compiler is missing. It does not prove a compilation will succeed
install_cmdstan(version: null, dir: null, cores: null, timeout: null, overwrite: false, releaseUrl: null, releaseFile: null, cppOptions: [], checkToolchain: true, copyMakeLocal: null) Download or unpack and build a release (see Installation)
cmdstan_make_local(dir: null, cppOptions: [], append: true) Read or write CmdStan’s make/local
rebuild_cmdstan(cores: null, timeout: null) Clean and rebuild selected CmdStan
options(set: []) / cmdstan_option(name, default: null) Set global options, returning previous values, or read one option
write_stan_file(code, file: null, dir: null, basename: null, forceOverwrite: false, hashSalt: '') Write Stan source to model_<hash>.stan, reusing identical files
write_stan_json(data, file, alwaysDecimal: false, variables: null) Write data, initialization, or metric JSON; data may also be a StanData or a table. With variables (stanc’s declarations, such as $model->variables()['data']), int variables are written as integers and tuples as Stan’s {"1": ..., "2": ...} objects
read_cmdstan_csv(files) / as_cmdstan_fit(files, variables: null, checkDiagnostics: true, format: null) Import one or more CmdStan CSV files (.csv, .csv.gz, or .csv.bz2) into a typed fit. variables reads only those variables, and format sets the fit’s default draws format
read_cmdstan_csv_list(files, variables: null, samplerDiagnostics: null, format: null) Return CmdStanR’s read_cmdstan_csv() list shape
draws_to_csv(chains, dir) Export [chain][iteration][variable] associative draw rows to separate CSV files
mcmc_trace, mcmc_hist, mcmc_dens, mcmc_dens_overlay, mcmc_intervals, mcmc_rank_hist, mcmc_scatter, mcmc_acf, pareto_k_plot Return a Figure named after its bayesplot or loo counterpart; see Figures
cmdstanr_example(example: 'logistic', method: 'sample', ...options) / print_example_program(example) Run or print the logistic, schools, or schools_ncp example

num_threads() remains as a deprecated CmdStanR name. CmdStanR 1.0 removed read_sample_csv() and write_stan_tempfile(), and this package no longer has them.

Global options

options() accepts cmdstanr_output_dir, cmdstanr_write_stan_file_dir, cmdstanr_force_recompile, cmdstanr_draws_format, cmdstanr_warn_inits, cmdstanr_verbose, cmdstanr_no_ver_check, cmdstanr_max_rows, cmdstanr_print_line_numbers, cmdstanr_compress, cmdstanr_progress_bar, cmdstanr_save_metric, cmdstanr_save_config, cmdstanr_spinner, mc.cores, and cmdstanphp_example_dir. A null value unsets an option. Unknown names and values of the wrong type throw. mc.cores sets the default parallel_chains and installer core count. cmdstanr_compress ('none', 'gzip', or 'bzip2') is the fitting methods’ default compress, cmdstanr_progress_bar is sample()’s default show_progress_bar, cmdstanr_save_metric is sample()’s default save_metric, and cmdstanr_save_config is the default save_cmdstan_config. cmdstanr_spinner is accepted and has no effect.

Data arrays use named PHP arrays at the top level and zero-indexed lists for Stan arrays, vectors, and matrices. Boolean values become 0/1. Matrices are rows of rows, with no R column-major conversion. Empty top-level data becomes {}. Missing values, strings, objects, nonfinite numbers, sparse indices, invalid variable names, and ragged arrays are rejected. The fitting methods write data with the model’s declarations, so every declared data variable is required, int variables are written as integers (a non-integer is truncated with a warning), a single value for a one-dimensional array becomes a one-element array, and a tuple is passed as a list of its elements. Complex numbers are [re, im] pairs. Errors name the variable.

Model methods

cmdstan_model() and new CmdStanModel() take the same arguments. They compile the model, or reuse an up-to-date executable, before they return. Give stanFile, whose executable goes beside it or in dir, or exeFile alone to use an existing executable. The two cannot be combined, and a model from exeFile alone refuses the build arguments, because there is nothing to build. A hidden build record beside the executable, .<exe>.cmdstanphp.json, records the Stan program and its #include files, the user header, cppOptions, stancOptions, make/local, and the CmdStan that built the executable. The model is rebuilt exactly when one of these changed. quiet: false (or the cmdstanr_verbose option) reports whether and why it compiles, and forceRecompile: true rebuilds anyway. Compiling models describes builds and build records.

Processes that create the same model at once, such as queue workers after a deploy changes a .stan file, build it once. Building holds an exclusive lock on a second hidden file beside the executable, .<exe>.cmdstanphp.lock, which is never removed. The others wait, then find the new executable current. Checking an executable against its record holds the same lock shared, so a check never sees an executable and record that another process is midway through replacing. forceRecompile: true still rebuilds in every process, one after another, so models that were created earlier report a replaced executable. Locking needs a file system with working flock(), and a model in a read-only directory is checked without the lock.

cppOptions are named make variables, such as ['STAN_THREADS' => true]. Names are uppercased, true becomes true, and false turns an option off even when make/local turns it on. Unnamed entries are rejected; use cmdstan_make_local() for other make lines. stancOptions take flags and values, such as ['O1', 'canonicalize' => 'deprecations', 'max-line-length' => 78], and values may contain spaces or quotes. Flags that have their own argument are rejected: use includePaths, pedantic, userHeader, or cppOptions: ['STAN_OPENCL' => true] instead. Make values containing command expansions or shell metacharacters are rejected.

stanFile(), exeFile(), hppFile(), and code() return paths or source text. code() is the program as it was when the model was created, and hppFile() writes the generated C++ to a temporary file on first use; both are null for a model from exeFile alone. exposeFunctions(timeout: null, quiet: false) compiles the model’s user-defined functions and returns a StanFunctions object; functions() returns it afterwards. modelName(), hasStanFile(), cppOptions(), stancOptions(), includePaths(), and userHeader() expose model identity and the recorded build settings. cppOptions() returns make variables and values, so ['stan_threads' => true] comes back as ['STAN_THREADS' => 'true']. cmdstanVersion() is the version of CmdStan that built the executable, and reportedFeatures() is what the executable reports about its build (stan_threads, stan_mpi, stan_opencl, stan_no_range_checks, and stan_version). buildInfo() combines the record and the reported features, as stan_build_info() does. isCurrent() returns false when the executable is out of date. print(lineNumbers: null) writes source to stdout. saveHppFile(dir) copies the generated header. variables() returns the program’s data, parameters, transformed_parameters, and generated_quantities declarations from stanc. format(overwriteFile: false, canonicalize: false, backup: true, maxLineLength: null, quiet: false) returns the formatted program and optionally rewrites the source; create the model again to pick up the rewritten file. checkSyntax(pedantic: false, includePaths: null, stancOptions: [], quiet: false) throws on invalid Stan and returns true on success. cmdstanDefaults(method: 'sample') returns CmdStan’s default argument values for sample, optimize, variational, pathfinder, or laplace, read from <exe> <method> help-all and named as this package’s options.

Every run first checks that the executable is still the one the model built, from the current program. A changed Stan file, include, user header, make/local, or CmdStan throws StaleExecutableException with the reasons; call cmdstan_model() again to rebuild. The Stan file must therefore exist whenever the model runs. When none of the files’ status has changed, the check skips hashing and stanc.

Method Fit type Required CmdStan
sample() / sampleMpi() CmdStanMCMC 2.37+
optimize() CmdStanMLE 2.37+
variational() CmdStanVB 2.37+
pathfinder() CmdStanPathfinder 2.37+
laplace() CmdStanLaplace 2.37+
generateQuantities(fittedParams, ...) CmdStanGQ 2.37+
diagnose() CmdStanDiagnose 2.37+
logProb() CmdStanFit 2.37+

CmdStan 2.37 is the oldest supported release, as in CmdStanR 1.0. set_cmdstan_path() refuses an older installation, discovery skips one, and install_cmdstan() rejects older versions. The CI version targets are 2.37 and 2.40. Availability of individual options remains determined by the selected CmdStan; options added in newer releases can fail on older releases with CmdStan’s error message.

Shared options

data, seed, refresh, init, output_dir, output_basename, sig_figs, opencl_ids, show_messages, show_exceptions, save_cmdstan_config, timeout. Every method except diagnose() and logProb() also takes compress.

init additionally accepts a fit object (see initial values). The CmdStanR names that CmdStanR 1.0 removed are unknown options here too: sample()’s cores, num_cores, num_chains, num_warmup, num_samples, max_depth, stepsize, save_extra_diagnostics, and validate_csv, and the jacobian_adjustment argument.

The thread option depends on the method: threads_per_chain for sample() and generateQuantities(), and threads for optimize(), variational(), pathfinder(), and laplace(). pathfinder() still accepts num_threads with an E_USER_DEPRECATED notice. Asking for more than one thread from an executable built without threading is an error. compress ('none', 'gzip', or 'bzip2'; default: the cmdstanr_compress option) compresses the output and latent-dynamics CSVs after the run. sig_figs is 1–18. opencl_ids contains platform/device IDs and requires an OpenCL build. output_basename contains only letters, numbers, dots, underscores, and hyphens. save_latent_dynamics, a sample() and variational() option, creates auxiliary diagnostic CSVs. save_cmdstan_config requests CmdStan configuration JSON beside the CSVs.

Method-specific options

  • sample: threads_per_chain, save_latent_dynamics, show_progress_bar, chains (default 4), parallel_chains (default 1), chain_ids, iter_warmup, iter_sampling, save_warmup, thin, max_treedepth, adapt_engaged, adapt_delta, step_size, metric, metric_file, inv_metric, init_buffer, term_buffer, window, fixed_param, save_metric, diagnostics.
  • optimize: threads, algorithm, jacobian, init_alpha, iter, tol_obj, tol_rel_obj, tol_grad, tol_rel_grad, tol_param, history_size, save_iterations.
  • variational: threads, save_latent_dynamics, algorithm, iter, grad_samples, elbo_samples, eta, adapt_engaged, adapt_iter, tol_rel_obj, eval_elbo, draws (CmdStan’s output_samples).
  • pathfinder: threads, init_alpha, tol_obj, tol_rel_obj, tol_grad, tol_rel_grad, tol_param, history_size, single_path_draws, draws, num_paths, max_lbfgs_iters, num_elbo_draws, save_single_paths, psis_resample, calculate_lp.
  • laplace: threads, mode, opt_args, jacobian (default true), draws, calculate_lp.
  • generate_quantities: required fittedParams is a fit, filename, or filename list; threads_per_chain; parallel_chains controls concurrency.
  • diagnose: epsilon, error for finite-difference gradient checks.
  • log_prob: exactly one of unconstrained_params, constrained_params, and optional jacobian.

sampleMpi(mpiCmd: 'mpiexec', mpiArgs: [], ...options) accepts sampling options, defaults to one chain, and executes chains sequentially. An associative MPI argument such as ['n' => 4] becomes -n 4; a list is passed as a literal argument vector. Compile with ['STAN_MPI' => true, 'CXX' => 'mpicxx', 'TBB_CXX_TYPE' => 'gcc'] and install an MPI runtime. MPI launch construction is unit-tested; a real MPI cluster run is not validated here.

Fit methods

  • draws(variables: null, format: null, incWarmup: false): select posterior variables. Formats are draws_array, draws_matrix, draws_df, draws_list, and draws_rvars; null uses the cmdstanr_draws_format option or the method default.
  • samplerDiagnostics(format: null, incWarmup: false): diagnostic columns ending in __, excluding lp__.
  • summary(variables: null, probs: [0.05, 0.95], measures: []): descriptive and MCMC convergence summaries, or the requested summary measures.
  • diagnosticSummary(): per-chain num_divergent, num_max_treedepth, and ebfmi arrays.
  • checkDiagnostics(checks: ['divergences', 'treedepth', 'ebfmi']), diagnosticWarnings(): check and read messages.
  • cmdstanDiagnose(): invoke CmdStan’s diagnostic utility and return text.
  • metadata(), chainMetadata(), variables(), numChains(), numDrawsSampling(), numDrawsWarmup(): inspect parsed CSV.
  • stepSize(), invMetric(matrix: true): adaptation results, one entry per chain.
  • time(): per-chain warmup, sampling, and total time when available.
  • output(), returnCodes(), command(): captured console output, process status, and the shell-quoted command line of each process. command() leaves out STAN_NUM_THREADS and an MPI launcher. Imported fits have none of these.
  • init(): the initial values each process used, read from the init files. materialize() reads the draws, initial values, and profiles into memory, so the fit no longer needs its files.
  • Draws are read lazily, as in CmdStanR. A fit first reads only its CSV metadata and checks every row; draws(), summary(), and the diagnostics then read just the columns they use and keep them as packed doubles (8 bytes per value). Memory for one variable does not grow with the number of other columns. Each read of new columns passes over the files again, so ask for the variables you need together. Until materialize(), the fit needs its CSV files.
  • outputFiles(), latentDynamicsFiles(), profileFiles(), profiles(): output paths and parsed profiling data. The file accessors accept includeFailed for CmdStanR compatibility; fits only contain successful runs. Latent-dynamics and profile accessors throw when no such files exist.
  • dataFile(), configFiles(), metricFiles(), cmdstanConfig(), metric(): data and auxiliary JSON paths and their decoded contents. Imported fits use the data file recorded in the CSV when it still exists.
  • code(), numProcs(), lp(), cmdstanSummary(): stored source, number of processes, log-density matrix, and native text summary. Imported CSV fits do not include source code.
  • saveOutputFiles(), saveLatentDynamicsFiles(), saveProfileFiles(), saveDataFile(), saveConfigFiles(), saveMetricFiles(): each takes dir: '.', basename: null, timestamp: true, random: true and names files basename-YYYYmmddHHMM-id-xxxxxx.ext as CmdStanR does, with ids padded to at least two digits. saveOutputFiles() and saveLatentDynamicsFiles() also take compress (null keeps the current compression). Files created by the run are moved. Imported files and the data file are copied. Existing destinations are never overwritten.
  • saveObject(file): materialize the fit, then serialize it (with native MCMC summary statistics) to a PHP object file.
  • print(variables: null, maxRows: null): emit summary JSON to stdout, limited to cmdstanr_max_rows (default 10) variables.
  • drawsColumns(), summaryColumns(), drawsTable(), summaryTable(): column-oriented draws and summaries for data frames; see data frames.

Model methods

These methods need PHP FFI. The first call compiles a shared library for the fit’s model and data; initModelMethods(data: null, seed: 1, verbose: false, quiet: false, model: null) does this explicitly. data binds other data, such as the data of a fit reloaded after its data file is gone, and dataFile() then points to it. Imported CSV fits must pass model:. A model from exeFile alone has no Stan program to build them from.

  • logProb(unconstrainedVariables, jacobian: true): log density with constants dropped.
  • gradLogProb(...): ['log_prob' => float, 'gradient' => list].
  • hessian(...): ['log_prob' => float, 'grad_log_prob' => list, 'hessian' => rows].
  • unconstrainVariables(variables): a flat unconstrained list from parameter values keyed by name, structured as constrainVariables() returns them.
  • unconstrainDraws(files: null, draws: null, format: null, incWarmup: false): the fit’s draws, another set of CSV files, or draws_df rows, in unconstrained space.
  • constrainVariables(unconstrainedVariables, transformedParameters: true, generatedQuantities: true): variables keyed by name as nested arrays, with tuples as lists of their elements and complex values as [re, im].
  • exposeFunctions(timeout: null) / functions(): the model’s user-defined functions.

CmdStan\ModelMethods and CmdStan\StanFunctions can also be used directly with a Stan file.

Method-specific fit methods

CmdStanMCMC adds loo(variables: 'log_lik', rEff: false, momentMatch: false, maxIters: 30, kThreshold: null, split: true, cov: true) and waic(variables: 'log_lik'). Both return estimates (each with Estimate and SE), pointwise rows, and flat keys such as elpd_loo and se_elpd_loo. rEff: false, CmdStanR 1.0’s default, skips the relative efficiencies; rEff: true computes them. LOO also returns diagnostics with Pareto k values. momentMatch: true needs model methods and the phit posterior-draw kernels, and adds a moment_match key; see moment matching.

CmdStanMLE adds mle()/optimizedParams() (the estimates by variable, without lp__) and lp(); its summary() returns variable/estimate rows, matching CmdStanR’s optimization summary. CmdStanVB adds variationalMean() and lpApprox(), the approximation’s log density at each draw as one list in draw order. Pathfinder and Laplace also expose lpApprox(); Laplace exposes mode(), and generated quantities fits expose fittedParamsFiles(). CmdStanPathfinder adds singlePathFiles(), singlePathJsonFiles(), singlePathFits(), and singlePathDiagnostics() for runs with save_single_paths: true, and lists lp_approx__ and path__ among its variables. CmdStanDiagnose adds gradients() (gradient-check console output).

Statistics helpers

CmdStan\Figure renders computed figures with ascii(), vegaLite(), json(), html(), svg(), and png(); casting a figure to a string gives its ASCII form. CmdStan\Plot computes the figures, plus bandwidth(), density(), autocorrelation(), and ranks() for the values they draw. CmdStan\Psis (paretoSmooth(), paretoKhat(), psis(), gpdfit()), CmdStan\Loo (loo(), waic(), relativeEff()), CmdStan\MomentMatch (loo() on unconstrained draws with log-density and log-likelihood callbacks, fromFit()), CmdStan\DrawKernels (detection of and wrappers for the phit draw kernels), CmdStan\Summary (summarise() and each posterior measure), CmdStan\Rvars, and CmdStan\Inits (fromFit(), fromDraws(), nest(), validate()) operate on plain draws arrays. Their docblocks describe the input and output shapes.

Data frames and the phpstats family

CmdStanPHP works with the phpstats family without depending on it. phibble is detected by method and class names. The phit extension is detected by function name.

Data in

Every data argument (sample(), sampleMpi(), optimize(), variational(), pathfinder(), laplace(), generateQuantities(), diagnose(), and logProb()) and write_stan_json() accept a plain array, a JSON file, a CmdStan\StanData, or a table. A table is any object with toModelData() or toColumns(), such as a phibble Phibble\DataFrame. toModelData() is used when both exist. StanData::fromTable($table, addN: true) performs the same conversion and keeps the factor labels.

Column Stan data
int or float The list of values, unchanged
bool 0/1 integers
list cells Nested arrays, which must be rectangular
factor 1-based integer indices in level order, plus J_<name>, the number of levels
string Rejected, as in CmdStanR 1.0; make the column a factor so its levels set the codes
null, dates, other objects Rejected with the column name and row, because Stan data has no missing values

Factor levels come from a toModelData() descriptor (['levels' => list<string>, 'codes' => list<?int>, 'ordered' => bool], with 0-based codes, as phibble’s DataFrame::toModelData() returns them from phibble 0.1.0; add 'base' => 1 for 1-based codes) or, for a toColumns() table, from levels($name) when types() reports a factor. The ordered flag is ignored. Labels cannot be written to Stan JSON, so they are returned in StanData::$levels, keyed by data variable, where label i has index i + 1. The conversion adds N, the row count, unless the table has a column named N, and adds J_<name> unless a column already has that name. CmdStan ignores data variables that the program does not declare. Column names must be valid Stan identifiers.

Fit methods are camelCase, as are StanData‘s and Tables’ from...() constructors and the package’s other static helpers, such as CmdStanFit::fromCsv() and Inits::fromFit(). StanData is a value object with readonly data, levels, columns (the names of the columns of X), and meta. toArray() returns data, and with(['prior_scale' => 2.5]) adds or replaces variables.

Regression data

StanData::fromColumns($columns, y: 'y', x: ['x1', 'x2'], groups: 'school', intercept: false) builds the usual hierarchical regression data block from named columns or a table:

Variable Contents
N Number of rows
K Number of predictors (columns of X)
X N rows of K floats, in the order of x
y The outcome, keeping integers as integers
<g>_id For each grouping column g, the 1-based group index of each row
J_<g> For each grouping column, the number of groups
J The number of groups, when there is exactly one grouping column

Groups are numbered over sorted unique values (numbers numerically, otherwise in strcmp order) or over a factor’s levels, and the labels are in levels['<g>_id']. Predictors must be numeric. intercept: true prepends a column of ones named (Intercept). It is off by default because Stan programs usually give the intercept its own parameter.

$data = CmdStan\StanData::fromColumns($df, 'score', ['hours'], 'school');
$fit = $model->sample(data: $data, seed: 1);
data {
  int<lower=0> N;
  int<lower=0> K;
  matrix[N, K] X;
  vector[N] y;
  int<lower=1> J;
  array[N] int<lower=1, upper=J> school_id;
}

StanData::fromFormula('y ~ x1 + f + (1 + x1 | g)', $data, dropIntercept: false, missing: 'drop') builds regression data from an R-style formula through Phit\model_matrix() in the phit extension (phit 0.1.0 and later). The function handles factor predictors (treatment contrasts), interactions, transforms, and offsets, and keeps the (Intercept) column in X unless dropIntercept: true. $data can be columns, factor descriptors, or a table, whose toModelData() is passed unchanged. Without the function, fromFormula() throws a RuntimeException that names the requirement. StanData::fromModelMatrix($result) maps an existing Phit\model_matrix() result and is the only code that depends on its shape.

Formula part Stan data
Design matrix N (retained rows), K, and X; the column names are in columns
Numeric response y, as integers when every value is integral, so it suits int and real declarations
Factor response y as 0/1 for two levels (Bernoulli), or 1..C with C levels (categorical); labels in levels['y']
cbind(s, f) response y (successes) and trials (successes plus failures)
offset() offset
(... \| g) <g>_id (1-based) and J_<g> per grouping factor, and J when there is one grouping factor
Random slopes, such as (1 + x \| g) Z_<g> (N rows of the group’s columns, including the intercept column) and Q_<g>, the number of columns; omitted when every term on the group is intercept-only

Group names that are not Stan identifiers have other characters replaced by _, so the nested group g2:g1 gives g2_g1_id. Groups are numbered in factor level order when the data has descriptors or table factors, and otherwise over sorted labels (numbers numerically, otherwise byte order, as Phit\model_matrix() sorts levels). Terms on the same group are concatenated into one Z_<g>, intercept-only terms included, so (1 | g) + (0 + x | g) gives the same Z_g as (1 + x | g). Two groups whose names map to the same <g>, such as a.b and a_b, are rejected. Factors reach Phit\model_matrix() as descriptors in the data’s level order, so the first level is the reference level and a factor response is coded in that order, while plain string columns use sorted levels. missing: 'drop' removes rows with missing values in any variable the formula uses, with one E_WARNING from Phit\model_matrix(), and missing: 'raise' rejects them. The remaining result keys, including retained_rows, dropped_rows, n_input, n_dropped, terms, and assign, are kept in meta, and meta['random'][<g>] lists each group’s columns and terms.

data {
  int<lower=0> N;
  int<lower=1> K;
  matrix[N, K] X;          // includes the intercept column
  vector[N] y;
  int<lower=1> J;
  array[N] int<lower=1, upper=J> g_id;
  int<lower=1> Q_g;
  matrix[N, Q_g] Z_g;      // (1 + x1 | g)
}

Draws and summaries out

  • drawsColumns(variables: null, incWarmup: false) returns draws as columns, like posterior’s as_draws_df(): one list per variable element (such as beta[2]), then one-based .chain, .iteration, and .draw columns.
  • summaryColumns(variables: null, probs: [0.05, 0.95], measures: []) returns summary() as columns: variable and one column per measure.
  • drawsTable() and summaryTable() take the same arguments and return a Phibble\DataFrame built with DataFrame::fromColumns(). They need phpstats/phibble, which requires PHP 8.3 or later, and throw a RuntimeException explaining this when it is not installed.
  • CmdStan\Tables::fromRows($rows) converts any list of associative rows, such as loo()['pointwise'], to columns.

The column arrays need no other package and suit any data frame library that accepts name-to-values columns.

Part of the phpstats family

CmdStanPHP is part of the phpstats family of PHP statistics packages:

  • phit: the phit native extension (Phit\ functions), which provides the moment-matching draw kernels and, when available, Phit\model_matrix().
  • phibble: data frames (Phibble\DataFrame).
  • phplyr: dplyr-style verbs for phibble tables.
  • phiz: a Vega-Lite grammar of graphics.

CmdStanPHP requires none of them. phibble, phplyr, and phiz require PHP 8.3 or later, and the phit extension supports PHP 8.3, 8.4, and 8.5.

Errors

Invalid PHP data or options throw InvalidArgumentException. Missing files/toolchain, timeouts, and malformed CSV throw runtime errors. Running an out-of-date executable throws StaleExecutableException. A nonzero command exit throws ProcessException, whose public readonly properties are command, exitCode, stdout, and stderr. A failing chain terminates other active chains; partial output files remain available for investigation. CmdStan processes still running when PHP shuts down are terminated. Partial outputs are not returned as a successful fit.

From phpstats/CmdStanPHP@7e99709.