CmdStanPHP

Guide

CmdStanPHP

CmdStanPHP fits Bayesian statistical models from PHP with Stan. You write a model in the Stan language and pass it data from PHP. Stan estimates the model’s unknown parameters and returns them as draws from their posterior distribution. From the draws you get estimates, uncertainty intervals, and predictions.

Stan programs run through CmdStan, Stan’s command-line interface. CmdStanPHP compiles each program to an executable, runs it in separate processes, and reads its output into PHP arrays. It is a port of CmdStanR 1.0, the R interface to CmdStan, and keeps CmdStanR’s function and option names. No R installation is needed.

An example

This Stan program, examples/bernoulli.stan in the repository, estimates the probability theta of a success from ten yes-or-no outcomes:

data {
  int<lower=0> N;
  array[N] int<lower=0, upper=1> y;
}
parameters {
  real<lower=0, upper=1> theta;
}
model {
  theta ~ beta(1, 1);
  y ~ bernoulli(theta);
}

This PHP script compiles the program and draws 4,000 samples of theta from four Markov chains:

<?php
require __DIR__.'/vendor/autoload.php';

use function CmdStan\cmdstan_model;

$model = cmdstan_model(__DIR__.'/bernoulli.stan');

$fit = $model->sample(
    data: ['N' => 10, 'y' => [0, 1, 0, 0, 0, 0, 0, 0, 0, 1]],
    seed: 123,
    chains: 4,
    parallel_chains: 4,
    show_messages: false,
);

print_r($fit->summary('theta'));

Save both files in a project with CmdStanPHP installed and run php bernoulli.php. Getting started shows the output and explains it.

What it does

  • Compiles Stan programs and rebuilds them only when the program or its build settings change.
  • Fits models with MCMC (parallel chains), L-BFGS, BFGS, and Newton optimization, the Laplace approximation, meanfield and fullrank ADVI, and Pathfinder.
  • Runs generated quantities on existing fits, and checks gradients.
  • Returns draws in posterior’s formats, and summaries with R-hat, bulk and tail effective sample size, and sampler diagnostics.
  • Computes PSIS-LOO and WAIC, with optional moment matching.
  • Evaluates log densities, gradients, and transforms in process, and calls a model’s Stan functions from PHP, through the FFI extension.
  • Draws bayesplot’s diagnostic plots as ASCII text, Vega-Lite specs, HTML, SVG, or PNG.
  • Accepts a phibble data frame as model data and returns draws and summaries as data frames.

Compatibility lists how CmdStanPHP differs from CmdStanR and which CmdStanR features it does not implement.

From phpstats/CmdStanPHP@7e99709.