CmdStanPHP

Helper classes

Classes for figures, in-process model code, and statistics on plain arrays. Their methods are camelCase.

Figures

Figure

Returned by the figure functions and Plot. The statistics are computed once, so every rendering shows the same numbers. Casting a figure to a string gives ascii().

Method Purpose
->ascii() Text rendering. null sizes use per-kind defaults.
->vegaLite() Vega-Lite spec with the data inlined. Sizes are in pixels, per facet for per-chain figures. maxRows thins trace and scatter data by keeping every k-th row.
->json() The spec as JSON, safe to embed in an HTML script element.
->html() A standalone HTML page that renders the spec with vega-embed from the jsDelivr CDN.
->svg() SVG through the vl-convert binary, found through VL_CONVERT or PATH.
->png() PNG bytes through vl-convert at scale.
Signatures
ascii(?int $width = null, ?int $height = null): stringvegaLite(int $width = 480, int $height = 240, ?int $maxRows = null): arrayjson(int $width = 480, int $height = 240, ?int $maxRows = null): stringhtml(int $width = 480, int $height = 240, ?int $maxRows = null): stringsvg(int $width = 480, int $height = 240, ?int $maxRows = null, ?float $timeout = 60.0): stringpng(int $width = 480, int $height = 240, ?int $maxRows = null, float $scale = 2.0, ?float $timeout = 60.0): string

Plot

Static methods. Draws come from a fit or a draws_array. Densities use a Gaussian kernel with R’s bw.nrd0 bandwidth on 512 points, quantiles use R’s type 7 rule, and ranks average ties.

Method Purpose
Plot::trace() Chains overlaid by iteration (mcmc_trace()).
Plot::hist() Histogram of all draws (mcmc_hist()).
Plot::dens() Kernel density of all draws, or of each chain with byChain (mcmc_dens(), mcmc_dens_overlay()).
Plot::intervals() Inner and outer intervals with a point estimate (mcmc_intervals()).
Plot::rankHist() Rank histogram of each chain (mcmc_rank_hist()).
Plot::scatter() Joint draws of two variables (mcmc_scatter()).
Plot::acf() Autocorrelation of each chain (mcmc_acf()).
Plot::paretoK() Pareto k by observation (pareto_k_plot()).
Plot::bandwidth() R’s bw.nrd0 bandwidth.
Plot::density() Gaussian kernel density of x at each point of at.
Plot::autocorrelation() Autocorrelations for lags 0 to lags, as R’s acf().
Plot::ranks() One-based ranks with ties averaged, as R’s rank().
Plot::range() The data range, padded when every value is equal.
Signatures
trace(CmdStanFit|array $draws, string $variable): Figurehist(CmdStanFit|array $draws, string $variable, int $bins = 30): Figuredens(CmdStanFit|array $draws, string $variable, bool $byChain = false): Figureintervals(CmdStanFit|array $draws, array|string|null $variables = null, float $prob = 0.5, float $probOuter = 0.9, string $pointEst = 'median'): FigurerankHist(CmdStanFit|array $draws, string $variable, int $bins = 20): Figurescatter(CmdStanFit|array $draws, string $xVariable, string $yVariable): Figureacf(CmdStanFit|array $draws, string $variable, int $lags = 20): FigureparetoK(array $loo): Figurebandwidth(array $x): floatdensity(array $x, array $at, ?float $bw = null): arrayautocorrelation(array $x, int $lags): arrayranks(array $x): arrayrange(array $values): array

Model methods and Stan functions

StanFunctions

Returned by exposeFunctions(). Arguments and results use PHP numbers and zero-indexed lists: vectors and arrays are lists, matrices are lists of rows, complex numbers are [re, im], and tuples are lists. Call a function as a method, such as $f->add(1.5, 2). Needs the FFI extension.

Method Purpose
StanFunctions::compile() Compile, or reuse, the functions library for a Stan file. Libraries are cached beside the file.
->functions() Each function’s return_type, arguments, rng, supported, and reason, with Stan type names.
->call() Call a function with positional or named arguments. _rng functions also accept seed.
->library() The compiled library path.
Signatures
compile(string $stanFile, array $stancOptions = [], ?string $outputDir = null, ?float $timeout = null): selffunctions(): arraycall(string $function, mixed ...$arguments): mixedlibrary(): ?string

ModelMethods

What a fit’s model methods use, without a fit. Densities drop constants, as in CmdStanR. Named variables are nested zero-indexed lists, and unconstrained vectors are flat lists. Needs the FFI extension.

Method Purpose
ModelMethods::compile() Build, or reuse, the library for a Stan file and bind it to data.
ModelMethods::build() Build, or reuse, the library and return its path.
new ModelMethods() Bind a built library to data: an array, a StanData, a table, or a JSON file.
->logProb() Log density at unconstrained values.
->gradLogProb() log_prob and gradient.
->hessian() log_prob, grad_log_prob, and hessian, by finite differences of autodiff gradients.
->unconstrainVariables() A flat unconstrained list from values keyed by parameter name.
->unconstrainDraws() Unconstrained rows from draw rows keyed by names such as x[1,2].
->constrainVariables() Constrained values keyed by variable.
->unconstrainedParamNames() Unconstrained parameter names, such as s[1].
->constrainedParamNames() Constrained names in CmdStan CSV column order.
->variableSkeleton() Each variable’s dimensions: [] for scalars, a trailing 2 for complex values.
->numUnconstrained() The number of unconstrained parameters.
->seedRng() Reseed the generator that constrainVariables() uses for generated quantities.
->seed() The current seed.
->library() The library path.
Signatures
compile(string $stanFile, object|array|string|null $data = null, int $seed = 1, array $stancOptions = [], ?string $outputDir = null, ?float $timeout = null): selfbuild(string $stanFile, array $stancOptions = [], ?string $outputDir = null, ?float $timeout = null): stringnew ModelMethods(string $library, object|array|string|null $data = null, int $seed = 1)logProb(array $unconstrainedVariables, bool $jacobian = true): floatgradLogProb(array $unconstrainedVariables, bool $jacobian = true): arrayhessian(array $unconstrainedVariables, bool $jacobian = true): arrayunconstrainVariables(array $variables): arrayunconstrainDraws(array $draws): arrayconstrainVariables(array $unconstrainedVariables, bool $transformedParameters = true, bool $generatedQuantities = true): arrayunconstrainedParamNames(): arrayconstrainedParamNames(bool $transformedParameters = true, bool $generatedQuantities = true): arrayvariableSkeleton(bool $transformedParameters = true, bool $generatedQuantities = true): arraynumUnconstrained(): intseedRng(int $seed): voidseed(): intlibrary(): string

Summaries and diagnostics

Summary

Static methods on a draws_list ([chain][variable => list]) or, for single measures, a list of chains. CmdStanFit::summary() with measures uses these.

Method Purpose
Summary::summarise() One row per variable, with posterior’s summarise_draws() semantics.
Summary::fromDrawsArray() A draws_list from a draws_array.
Summary::measure() One named measure. Quantile measures return named arrays such as q5 and ess_q5.
Summary::defaultSummaryMeasures() The names in default_summary_measures.
Summary::defaultConvergenceMeasures() The names in default_convergence_measures.
Summary::defaultMcseMeasures() The names in default_mcse_measures.
Summary::mean() Mean.
Summary::median() Median.
Summary::var() Variance.
Summary::sd() Standard deviation.
Summary::mad() Median absolute deviation, scaled by 1.4826.
Summary::quantile2() Quantiles keyed q5, q95, and so on. All NAN when draws contain NaN.
Summary::rhat() Rank-normalized split R-hat.
Summary::rhatBasic() Basic R-hat, split by default.
Summary::essBulk() Bulk ESS.
Summary::essTail() Tail ESS.
Summary::essBasic() Basic ESS, split by default.
Summary::essMean() ESS of the mean.
Summary::essSd() ESS of the standard deviation.
Summary::essMedian() ESS of the median.
Summary::essQuantile() ESS of quantiles, keyed ess_q5 and so on.
Summary::mcseMean() Monte Carlo standard error of the mean.
Summary::mcseSd() MCSE of the standard deviation.
Summary::mcseMedian() MCSE of the median.
Summary::mcseQuantile() MCSE of quantiles, keyed mcse_q5 and so on.
Summary::chains() Draws as a list of float chains.
Summary::splitChains() Each chain halved, dropping the middle draw of odd-length chains.
Summary::percent() A probability formatted as posterior names quantiles, such as 5 for 0.05.
Signatures
summarise(array $draws, array $measures = [], array $probs = [0.05, 0.95]): arrayfromDrawsArray(array $draws): arraymeasure(string $name, array $x, array $probs = [0.05, 0.95]): array|floatdefaultSummaryMeasures(): arraydefaultConvergenceMeasures(): arraydefaultMcseMeasures(): arraymean(array $x): floatmedian(array $x): floatvar(array $x): floatsd(array $x): floatmad(array $x): floatquantile2(array $x, array $probs = [0.05, 0.95]): arrayrhat(array $x): floatrhatBasic(array $x, bool $split = true): floatessBulk(array $x): floatessTail(array $x): floatessBasic(array $x, bool $split = true): floatessMean(array $x): floatessSd(array $x): floatessMedian(array $x): floatessQuantile(array $x, array $probs = [0.05, 0.95]): arraymcseMean(array $x): floatmcseSd(array $x): floatmcseMedian(array $x): floatmcseQuantile(array $x, array $probs = [0.05, 0.95]): arraychains(array $x): arraysplitChains(array $x): arraypercent(float $p): string

Psis

Static methods following posterior and loo.

Method Purpose
Psis::paretoSmooth() posterior’s pareto_smooth() with return_k and extra_diags: smoothed values, diagnostics, and warnings.
Psis::paretoKhat() The Pareto k diagnostic without smoothing.
Psis::paretoSmoothLogWeights() Right-tail smoothing of log weights.
Psis::psis() loo’s psis() for a vector or a draws-by-observations matrix of log ratios.
Psis::gpdfit() Zhang and Stephens’ generalized Pareto fit: k and sigma, NAN when undefined.
Psis::qgeneralizedPareto() The generalized Pareto quantile function.
Psis::psTailLength() The tail length for a number of draws and relative efficiency.
Psis::psKhatThreshold() The Pareto k threshold for a number of draws.
Psis::psMinSs() The minimum sample size for a Pareto k.
Psis::psConvergenceRate() The convergence rate for a Pareto k and number of draws.
Psis::prepareReff() loo’s preparation of relative efficiencies for PSIS.
Signatures
paretoSmooth(array $x, string $tail = 'both', ?float $rEff = null, ?int $ndrawsTail = null, bool $areLogWeights = false, bool $smoothDraws = true): arrayparetoKhat(array $x, string $tail = 'both', ?float $rEff = null, ?int $ndrawsTail = null, bool $areLogWeights = false): floatparetoSmoothLogWeights(array $logWeights): arraypsis(array $logRatios, array|float|null $rEff = 1.0): arraygpdfit(array $x, bool $wip = true, int $minGridPts = 30, bool $sortX = true): arrayqgeneralizedPareto(array|float $p, float $mu = 0.0, float $sigma = 1.0, float $k = 0.0): array|floatpsTailLength(int $ndraws, float $rEff): floatpsKhatThreshold(int $ndraws): floatpsMinSs(float $k): floatpsConvergenceRate(float $k, int $ndraws): floatprepareReff(array|float|null $rEff, int $len): array

Loo

Static methods on a draws_array or draws_matrix of log-likelihood values. CmdStanMCMC::loo() and waic() use these.

Method Purpose
Loo::loo() PSIS-LOO: estimates, pointwise rows, diagnostics, and warnings. rEff: true computes relative efficiencies as CmdStanR does.
Loo::fromFit() PSIS-LOO for a fit’s variable, as CmdStanMCMC::loo().
Loo::waic() WAIC: estimates, pointwise rows, and warnings.
Loo::waicFromFit() WAIC for a fit’s variable.
Loo::relativeEff() loo’s relative_eff() for likelihood values.
Loo::relativeEffLogLik() Relative efficiencies from log-likelihood values, as CmdStanR computes them.
Loo::paretoKTable() Counts, proportions, and minimum n_eff per Pareto k interval.
Signatures
loo(array $logLik, array|float|bool|null $rEff = true): arrayfromFit(CmdStanFit $fit, string $variables = 'log_lik', array|float|bool|null $rEff = true): arraywaic(array $logLik): arraywaicFromFit(CmdStanFit $fit, string $variables = 'log_lik'): arrayrelativeEff(array $x): arrayrelativeEffLogLik(array $logLik): arrayparetoKTable(array $loo): array

MomentMatch

Static methods. Needs the phit draw kernels. Compatibility lists the differences from loo.

Method Purpose
MomentMatch::loo() Moment matching on unconstrained draws, with log-density and log-likelihood callbacks. Returns the loo() result with updated rows and a moment_match key.
MomentMatch::fromFit() PSIS-LOO, then moment matching with the fit’s model methods.
MomentMatch::transform() One shift, scale, or covariance step.
MomentMatch::splitTransform() The split proposal’s affine map and its exact inverse.
MomentMatch::splitLogRatios() Split-proposal log importance ratios.
Signatures
loo(array $loo, array $upars, array $logLik, callable $logProbUpars, callable $logLikIUpars, int $maxIters = 30, ?float $kThreshold = null, bool $split = true, bool $cov = true): arrayfromFit(CmdStanFit $fit, string $variables = 'log_lik', array|float|bool|null $rEff = true, int $maxIters = 30, ?float $kThreshold = null, bool $split = true, bool $cov = true): arraytransform(string $kind, array $upars, array $lwi): arraysplitTransform(array $upars, array $shift, array $scaling, array $maps, ?array $steps = null): arraysplitLogRatios(array $lpZ, array $lpInverse, array $llZ, float $logAbsDet): array

DrawKernels

Static methods around Phit\draws_moments(), Phit\draws_covariance_map(), and Phit\draws_affine().

Method Purpose
DrawKernels::available() Whether the three kernels are available.
DrawKernels::missing() The kernel functions that are not available.
DrawKernels::require() Throw a RuntimeException naming the missing kernels.
DrawKernels::moments() Weighted mean and covariance.
DrawKernels::covarianceMap() The map A with A · source · Aᵀ = target, and its log absolute determinant.
DrawKernels::affine() y = A x + b for every draw.
DrawKernels::affineAbout() y = A (x − from) + to for every draw.
DrawKernels::isNumericalFailure() Whether a kernel exception reports a numerical failure.
DrawKernels::apply() Matrix-vector product.
DrawKernels::multiply() Product of square matrices.
DrawKernels::diagonal() A diagonal matrix.
DrawKernels::identity() An identity matrix.
Signatures
available(): boolmissing(array $functions = self::FUNCTIONS): arrayrequire(): voidmoments(array $draws, ?array $weights = null, string $normalization = 'population'): arraycovarianceMap(array $source, array $target): arrayaffine(array $draws, array $matrix, array $shift): arrayaffineAbout(array $draws, array $matrix, array $from, array $to): arrayisNumericalFailure(Throwable $e): boolapply(array $matrix, array $x): arraymultiply(array $a, array $b): arraydiagonal(array $diagonal): arrayidentity(int $n): array

Draws and initial values

Rvars

Static methods. draws(format: 'draws_rvars') uses these.

Method Purpose
Rvars::fromFit() draws_rvars for a fit’s variables.
Rvars::fromDrawsDf() draws_rvars from draws_df rows.
Rvars::fromDrawsArray() draws_rvars from a draws_array.
Rvars::draw() The values of one zero-based draw, nested by dimensions.
Rvars::parseName() Split x[1,2] into ['x', [1, 2]].
Signatures
fromFit(CmdStanFit $fit, array|string|null $variables = null): arrayfromDrawsDf(array $rows): arrayfromDrawsArray(array $draws): arraydraw(array $rvar, int $draw): array|floatparseName(string $name): array

Inits

Static methods. The init option uses these when given a fit or draws.

Method Purpose
Inits::fromFit() One set of initial values per process from a fit’s draws.
Inits::fromDraws() The same from draw rows or a draws_array. Fewer draws than processes are recycled, and more are resampled without replacement.
Inits::nest() One draw’s flat columns as nested arrays sized by the largest index, keeping only model parameters.
Inits::validate() Check a list of per-process initial values.
Inits::sampleNoReplace() Weighted sampling without replacement, returning zero-based indices.
Signatures
fromFit(CmdStanFit $fit, int $numProcs, ?array $parameters = null, ?int $seed = null, bool $warnPartial = true): arrayfromDraws(array $draws, int $numProcs, ?array $parameters = null, ?int $seed = null, bool $warnPartial = true): arraynest(array $row, ?array $parameters = null): arrayvalidate(array $inits, int $numProcs, ?array $parameters = null, bool $warnPartial = true): arraysampleNoReplace(array $weights, int $size, Random\Randomizer $rng): array