httpstan

4.13.0 · maintenance · verified Mon Apr 13

httpstan provides an HTTP-based REST interface to Stan, a powerful package for Bayesian inference. It acts as a lightweight shim that allows clients to interact with the Stan C++ library using a REST API. Key features include automatic caching of compiled Stan models and samples, and parallel sampling. It is currently at version 4.13.0. While the primary maintainer is taking a hiatus, the project has historically seen releases roughly every few months, and automated processes attempt to build and publish new wheels every two days upon changes in the codebase.

Warnings

Install

Imports

Quickstart

To use httpstan, first run it as a standalone server. Then, interact with its REST API using HTTP requests to compile Stan models and draw samples. This example demonstrates compiling a simple Stan program and initiating sampling using the `requests` library.

import os
import subprocess
import time
import requests

# Ensure httpstan is running in the background
# In a real application, you might use a more robust process management.
# For this example, we assume it's already running or launched separately.
# If not running, uncomment the subprocess call below and handle its lifecycle.
# subprocess.Popen(['python3', '-m', 'httpstan'])
# time.sleep(5) # Give the server a moment to start

# Define a simple Stan program
program_code = """
parameters {real y;} model {y ~ normal(0,1);}
"""

# Compile the Stan program
response = requests.post(
    'http://localhost:8080/v1/models',
    json={'program_code': program_code}
)
response.raise_for_status()
model_name = response.json()['name']
print(f"Model compiled with name: {model_name}")

# Draw samples from the compiled model
sample_response = requests.post(
    f'http://localhost:8080/v1/{model_name}/actions',
    json={'type': 'stan::services::sample::hmc_nuts_diag_e_adapt'}
)
sample_response.raise_for_status()

# In a real scenario, you'd typically stream the results from the response.iter_lines()
# For simplicity, this example just prints the first few lines of the output.
print("\nFirst few lines of sampling output:")
for line in sample_response.iter_lines():
    print(line.decode('utf-8'))
    # Break after a few lines for brevity in quickstart
    if len(line) > 100: # Heuristic to get some actual output
        break

view raw JSON →