### Installation: Docker Source: https://github.com/michaelnowotny/pyjags/blob/master/docs/index.md Build and start the JAGSlab environment using Docker for a quick setup. ```bash ./scripts/jagslab build && ./scripts/jagslab start ``` -------------------------------- ### Build and Start PyJAGS Docker Environment Source: https://github.com/michaelnowotny/pyjags/blob/master/docs/getting-started/installation.md Use this command to build the Docker image and launch Jupyter Lab for a pre-configured PyJAGS environment. This is the fastest installation method and works on any platform with Docker installed. ```bash git clone https://github.com/michaelnowotny/pyjags.git cd pyjags cp .env.example .env ./scripts/jagslab build # build Docker image ./scripts/jagslab start # launch Jupyter Lab at http://localhost:8888 ``` -------------------------------- ### Installation: Native Linux Source: https://github.com/michaelnowotny/pyjags/blob/master/docs/index.md Install JAGS using apt and then install PyJAGS using pip. ```bash sudo apt install jags && pip install pyjags ``` -------------------------------- ### Installation: Native macOS Source: https://github.com/michaelnowotny/pyjags/blob/master/docs/index.md Install JAGS using Homebrew and then install PyJAGS using pip. ```bash brew install jags && pip install pyjags ``` -------------------------------- ### Install JAGS and PyJAGS on Linux (Debian/Ubuntu) Source: https://github.com/michaelnowotny/pyjags/blob/master/docs/getting-started/installation.md Installs JAGS and pkg-config using apt, then installs PyJAGS using pip. ```bash # Debian/Ubuntu sudo apt-get install jags pkg-config pip install pyjags ``` -------------------------------- ### Build and Start Docker Environment Source: https://github.com/michaelnowotny/pyjags/blob/master/CLAUDE.md Use these commands to build the Docker images for the development environment and start the JupyterLab server. The `jagslab` script manages these operations. ```bash ./scripts/jagslab build # Build base + lab images ./scripts/jagslab test # Run all tests ./scripts/jagslab start # Start Jupyter Lab (port from .env, default 8889) ./scripts/jagslab install # Recompile C++ extension after editing console.cc ./scripts/jagslab shell # Bash shell in the container ``` -------------------------------- ### Install PyJAGS with GPU Support Source: https://github.com/michaelnowotny/pyjags/blob/master/README.md Install PyJAGS with diagnostics and enable GPU acceleration for Divergence computations using JAX. ```bash pip install pyjags[diagnostics] jax[cuda12] ``` -------------------------------- ### Install PyJAGS from Source Source: https://github.com/michaelnowotny/pyjags/blob/master/docs/getting-started/installation.md Clones the PyJAGS repository, navigates into the directory, and installs the package in editable mode with development dependencies. It also installs pre-commit hooks. ```bash git clone https://github.com/michaelnowotny/pyjags.git cd pyjags pip install -e ".[dev]" pre-commit install ``` -------------------------------- ### Install JAGS and PyJAGS on Intel Mac Source: https://github.com/michaelnowotny/pyjags/blob/master/docs/getting-started/installation.md Installs JAGS via Homebrew and then installs PyJAGS using pip. ```bash brew install jags pip install pyjags ``` -------------------------------- ### Install PyJAGS with Diagnostics Source: https://github.com/michaelnowotny/pyjags/blob/master/README.md Install PyJAGS with the necessary dependencies for advanced diagnostics and visualization. ```bash pip install pyjags[diagnostics] ``` -------------------------------- ### Install CMake for macOS or Linux Source: https://github.com/michaelnowotny/pyjags/blob/master/docs/getting-started/installation.md Installs the CMake build system, which may be required for certain build processes or troubleshooting. ```bash brew install cmake # macOS sudo apt install cmake # Linux ``` -------------------------------- ### Manual Release Build and Upload Source: https://github.com/michaelnowotny/pyjags/blob/master/RELEASING.md Commands for building the source distribution and uploading to PyPI. Requires pip, twine, and build to be installed. Upload to Test PyPI first for verification. ```bash pip install twine build # Build rm -rf dist/ build/ python -m build --sdist # Upload to Test PyPI first twine upload --repository-url https://test.pypi.org/legacy/ dist/pyjags-X.Y.Z.tar.gz # Verify, then upload to real PyPI twine upload dist/pyjags-X.Y.Z.tar.gz ``` -------------------------------- ### Install JAGS and PyJAGS on Apple Silicon Mac Source: https://github.com/michaelnowotny/pyjags/blob/master/docs/getting-started/installation.md This sequence installs JAGS using Homebrew, configures the package configuration path, sets up a Python environment using 'uv', and finally installs PyJAGS and its diagnostics. ```bash # 1. Install JAGS brew install jags # 2. Set PKG_CONFIG_PATH (add to ~/.zprofile) export PKG_CONFIG_PATH="/opt/homebrew/lib/pkgconfig:$PKG_CONFIG_PATH" # 3. Python environment with uv curl -LsSf https://astral.sh/uv/install.sh | sh uv python install 3.12 uv venv --python 3.12 .venv source .venv/bin/activate # 4. Install PyJAGS uv pip install pyjags # 5. Optional: advanced diagnostics uv pip install pyjags[diagnostics] ``` -------------------------------- ### Basic PyJAGS Model Setup and Sampling Source: https://github.com/michaelnowotny/pyjags/blob/master/README.md This snippet demonstrates how to define a JAGS model, initialize a PyJAGS model object, perform burn-in sampling, and then sample for production. It also shows how to convert the samples to an ArviZ InferenceData object for analysis. ```python import pyjags import arviz as az model_code = """ model { mu ~ dnorm(0, 0.001) sigma ~ dunif(0, 100) tau <- pow(sigma, -2) for (i in 1:N) { y[i] ~ dnorm(mu, tau) } } """ model = pyjags.Model(code=model_code, data=dict(y=y, N=len(y)), chains=4, adapt=1000, seed=42) model.sample(1000, vars=[]) # burn-in samples = model.sample(5000, vars=["mu", "sigma"]) # production idata = pyjags.from_pyjags(samples) az.summary(idata) ``` -------------------------------- ### Quick Start: Model Sampling Source: https://github.com/michaelnowotny/pyjags/blob/master/docs/index.md Initialize a PyJAGS model and perform sampling for burn-in and production. Convert the samples to an ArviZ InferenceData object for analysis. ```python import pyjags import arviz as az model = pyjags.Model(code=model_code, data=data, chains=4, seed=42) # model_code and data are assumed to be defined elsewhere model.sample(1000, vars=[]) # burn-in samples = model.sample(5000, vars=["mu", "sigma"]) # production idata = pyjags.from_pyjags(samples) az.summary(idata) ``` -------------------------------- ### Install CMake for Build Systems Source: https://github.com/michaelnowotny/pyjags/blob/master/README.md Install CMake, a build system generator, on macOS, Linux, or any environment where Python is available. This is often required to resolve CMake errors during the build process. ```bash brew install cmake # macOS ``` ```bash sudo apt install cmake # Linux ``` ```bash pip install cmake # anywhere ``` -------------------------------- ### Find Python, NumPy, and pybind11 Source: https://github.com/michaelnowotny/pyjags/blob/master/CMakeLists.txt Locates the required Python interpreter, development headers, NumPy library, and pybind11. Ensure these are installed in your system for the build to succeed. ```cmake find_package(Python3 REQUIRED COMPONENTS Interpreter Development.Module NumPy) find_package(pybind11 REQUIRED) ``` -------------------------------- ### Install PyJAGS Package Source: https://github.com/michaelnowotny/pyjags/blob/master/CLAUDE.md Install the PyJAGS package in editable mode. This command is used for development and allows changes in the source code to be reflected immediately without reinstallation. ```bash pip install -e . ``` -------------------------------- ### Find JAGS using PkgConfig or Direct Search Source: https://github.com/michaelnowotny/pyjags/blob/master/CMakeLists.txt Attempts to find the JAGS library, prioritizing pkg-config for system-wide installations. If pkg-config is not available or fails, it falls back to a direct path search. Includes architecture checks for macOS. ```cmake find_package(PkgConfig) if(PkgConfig_FOUND) pkg_check_modules(JAGS jags) endif() ``` -------------------------------- ### Tagging a Release Source: https://github.com/michaelnowotny/pyjags/blob/master/RELEASING.md Use this command to create a version tag for a release. Ensure tags have no prefix. ```bash git tag X.Y.Z ``` -------------------------------- ### Information Gain and Convergence Report Source: https://github.com/michaelnowotny/pyjags/blob/master/README.md Calculate Kullback-Leibler divergence and convergence diagnostics using ArviZ InferenceData. Requires installation with `pip install pyjags[diagnostics]`. ```python from pyjags.diagnostics import information_gain, convergence_report idata = pyjags.from_pyjags(posterior, prior=prior_samples) ig = information_gain(idata) # KL divergence: prior -> posterior report = convergence_report(idata) # R-hat + ESS + chain energy distance ``` -------------------------------- ### Initialize and Sample Market Model Source: https://github.com/michaelnowotny/pyjags/blob/master/docs/notebooks/Trading Cost Estimation.ipynb Initializes a pyjags Model with the market factor code and data, then samples from the posterior distribution. The results are converted to an ArviZ InferenceData object for analysis. ```python market_model = pyjags.Model( code=market_model_code, data=market_data, chains=4, threads=4, progress_bar=False, seed=42, ) market_model.sample(1000, vars=[]) market_samples = market_model.sample(2000, vars=["c", "sigma", "beta_m", "q"]) idata_market = pyjags.from_pyjags(market_samples) c_mkt = market_samples["c"].flatten() beta_mkt = market_samples["beta_m"].flatten() print(f"Half-spread: {c_mkt.mean():.4f} ({c_mkt.mean()*100:.2f}%)") print(f"Market beta: {beta_mkt.mean():.3f}") print(f" (A beta of {beta_mkt.mean():.2f} means Ford moves ~{beta_mkt.mean():.0%} as much as the S&P 500)") ``` -------------------------------- ### Install JAGS via ARM Homebrew for macOS Architecture Mismatch Source: https://github.com/michaelnowotny/pyjags/blob/master/docs/getting-started/installation.md If encountering architecture mismatches on macOS, ensure JAGS is installed using the ARM-specific Homebrew path. ```bash /opt/homebrew/bin/brew install jags ``` -------------------------------- ### pyjags.modules.get_modules_dir Source: https://github.com/michaelnowotny/pyjags/blob/master/docs/api/modules.md Gets the current directory where JAGS modules are searched for. ```APIDOC ## pyjags.modules.get_modules_dir ### Description Gets the current directory where JAGS modules are searched for. ### Method GET ### Endpoint /modules/dir ### Response #### Success Response (200) - **modules_dir** (string) - The path to the JAGS modules directory. ``` -------------------------------- ### Loading Models from File Source: https://github.com/michaelnowotny/pyjags/blob/master/docs/notebooks/Getting Started.ipynb Demonstrates how to load BUGS model code from a file, supporting both string paths and pathlib.Path objects. This is useful for managing larger model definitions. ```python from pathlib import Path import tempfile model_file = Path(tempfile.mktemp(suffix=".bug")) model_file.write_text(model_code) model_from_file = pyjags.Model(file=model_file, data=data, chains=4, adapt=1000, progress_bar=False) print(model_from_file) model_file.unlink() # clean up ``` -------------------------------- ### Check JAGS Architecture Compatibility Source: https://github.com/michaelnowotny/pyjags/blob/master/CMakeLists.txt Verifies if the found JAGS library matches the expected architecture. This is crucial for ensuring compatibility between the build and the installed library. ```cmake if(JAGS_FOUND AND JAGS_LINK_LIBRARIES) _check_jags_arch("${JAGS_LINK_LIBRARIES}" _pkg_arch_ok) if(NOT _pkg_arch_ok) message(STATUS "pkg-config found JAGS but wrong architecture — trying fallback paths") set(JAGS_FOUND FALSE) endif() elseif(JAGS_FOUND AND JAGS_LIBRARY_DIRS) # pkg-config gave us a directory + library name; resolve to full path for arch check find_library(_JAGS_PKGCONF_LIB NAMES jags PATHS ${JAGS_LIBRARY_DIRS} NO_DEFAULT_PATH) if(_JAGS_PKGCONF_LIB) _check_jags_arch("${_JAGS_PKGCONF_LIB}" _pkg_arch_ok) if(NOT _pkg_arch_ok) message(STATUS "pkg-config found JAGS but wrong architecture — trying fallback paths") set(JAGS_FOUND FALSE) endif() endif() unset(_JAGS_PKGCONF_LIB CACHE) endif() ``` -------------------------------- ### Run Pytest Directly Source: https://github.com/michaelnowotny/pyjags/blob/master/CLAUDE.md Execute tests directly using the `pytest` module. This can be done inside the Docker container or on a system with JAGS installed locally. ```bash python -m pytest test/ -v ``` -------------------------------- ### Compare Spread and Volatility Estimates Source: https://github.com/michaelnowotny/pyjags/blob/master/docs/notebooks/Trading Cost Estimation.ipynb Visualizes the posterior distributions of the half-spread (c) and residual volatility (sigma) for both the basic model and the model with a market factor. Use this to compare how the market factor influences these estimates. ```python fig, axes = plt.subplots(1, 2, figsize=(12, 4)) # Compare spread estimates axes[0].hist(samples["c"].flatten(), bins=50, alpha=0.5, density=True, color="steelblue", label="Basic model") axes[0].hist(market_samples["c"].flatten(), bins=50, alpha=0.5, density=True, color="darkorange", label="With market factor") axes[0].set_xlabel("Half-spread (c)") axes[0].set_ylabel("Posterior density") axes[0].set_title("Spread estimate shrinks with market factor") axes[0].legend() # Compare sigma axes[1].hist(samples["sigma"].flatten(), bins=50, alpha=0.5, density=True, color="steelblue", label="Basic model") axes[1].hist(market_samples["sigma"].flatten(), bins=50, alpha=0.5, density=True, color="darkorange", label="With market factor") axes[1].set_xlabel(r"Residual volatility (\sigma)") axes[1].set_ylabel("Posterior density") axes[1].set_title("Idiosyncratic volatility drops: the market explains some 'noise'") axes[1].legend() plt.tight_layout() plt.show() ``` -------------------------------- ### Build and Sample First Bayesian Model with Pyjags Source: https://github.com/michaelnowotny/pyjags/blob/master/docs/getting-started/quickstart.md Define a Bayesian model, compile it, adapt samplers, run burn-in, and draw production samples. Requires `pyjags`, `numpy`, and `arviz`. ```python import pyjags import numpy as np import arviz as az # Some data np.random.seed(42) y = np.random.normal(loc=5.0, scale=2.0, size=30) # Write the model in the BUGS language model_code = """ model { mu ~ dnorm(0, 0.001) sigma ~ dunif(0, 100) tau <- pow(sigma, -2) for (i in 1:N) { y[i] ~ dnorm(mu, tau) } } """ # Compile, adapt, and sample model = pyjags.Model( code=model_code, data=dict(y=y, N=len(y)), chains=4, adapt=1000, seed=42, ) model.sample(1000, vars=[]) # burn-in samples = model.sample(5000, vars=["mu", "sigma"]) # production # Analyze with ArviZ idata = pyjags.from_pyjags(samples) az.summary(idata) ``` -------------------------------- ### Fatal Error on JAGS Not Found Source: https://github.com/michaelnowotny/pyjags/blob/master/CMakeLists.txt Displays a fatal error message with installation instructions if JAGS cannot be found after attempting all search paths. Provides platform-specific guidance. ```cmake if(NOT JAGS_FOUND) if(APPLE AND PYTHON_ARCH STREQUAL "arm64") message(FATAL_ERROR "Could not find an arm64 JAGS installation.\n" "Install JAGS via ARM Homebrew:\n" " /opt/homebrew/bin/brew install jags\n" ) else() message(FATAL_ERROR "Could not find JAGS. Install it via:\n" " macOS: brew install jags\n" " Debian: sudo apt-get install jags\n" " conda: conda install -c conda-forge jags\n" ) endif() endif() ``` -------------------------------- ### pyjags.arviz.summary Source: https://github.com/michaelnowotny/pyjags/blob/master/docs/api/arviz.md Generates a summary of the PyJAGS samples, compatible with ArviZ. ```APIDOC ## pyjags.arviz.summary ### Description Generates a summary of the PyJAGS samples, compatible with ArviZ. ### Method (Not specified, likely a Python function call) ### Parameters (Details not provided in the source) ### Request Example (Not provided in the source) ### Response (Details not provided in the source) ``` -------------------------------- ### Plot Trace and Distribution of Model Parameters Source: https://github.com/michaelnowotny/pyjags/blob/master/docs/notebooks/Trading Cost Estimation.ipynb Visualizes the trace plots and posterior distributions for the 'c' (half-spread) and 'sigma' (volatility) parameters using ArviZ. This helps assess model convergence and the shape of the posterior distributions. ```python import arviz as az import matplotlib.pyplot as plt az.plot_trace_dist(idata, var_names=["c", "sigma"]) plt.tight_layout() plt.show() ``` -------------------------------- ### Summarize MCMC Convergence Diagnostics Source: https://github.com/michaelnowotny/pyjags/blob/master/docs/notebooks/Eight Schools.ipynb Use az.summary to check R-hat and ESS for model parameters. Ensure R-hat is close to 1.0 and ESS is high for converged chains. ```python az.summary(idata, var_names=["mu", "tau", "theta_tilde"]) ``` -------------------------------- ### Define Stochastic Volatility Model in JAGS Source: https://github.com/michaelnowotny/pyjags/blob/master/notebooks/Advanced Functionality.ipynb Defines a stochastic volatility model using JAGS syntax. This model assumes volatility is a time-varying latent process. Ensure JAGS is installed and configured for use with Pyjags. ```python model { phi_v ~ dunif(0.0, 1.0) # persistence of volatility sigma_v ~ dunif(0.0, 1.0) # volatility of volatility tau_v = 1.0 / sigma_v^2 v[1] ~ dnorm(0.0, 0.01) # initial log-volatility (vague) for (t in 2:length(r)) { v[t] ~ dnorm(phi_v * v[t-1], tau_v) # AR(1) log-volatility r[t] ~ dnorm(0.0, exp(-v[t])) # return | volatility } } ``` -------------------------------- ### Visualize Shrinkage: Raw vs. Partial Pooling Source: https://github.com/michaelnowotny/pyjags/blob/master/docs/notebooks/Eight Schools.ipynb Generates a bar chart comparing raw estimates, posterior means (partial pooling), and the grand mean (complete pooling) for each school. This visualization demonstrates the effect of shrinkage. ```python fig, ax = plt.subplots(figsize=(10, 5)) x = np.arange(8) width = 0.35 # Raw estimates ax.bar(x - width/2, y, width, color="lightcoral", edgecolor="white", label="Raw estimate (no pooling)", alpha=0.8) # Posterior means (partial pooling) ax.bar(x + width/2, theta_means, width, color="steelblue", edgecolor="white", label="Posterior mean (partial pooling)", alpha=0.8) # Grand mean (complete pooling) ax.axhline(y.mean(), color="darkorange", linestyle="--", linewidth=2, label=f"Grand mean = {y.mean():.1f} (complete pooling)") ax.set_xticks(x) ax.set_xticklabels(schools) ax.set_xlabel("School") ax.set_ylabel("Treatment effect (points)") ax.set_title("The magic of shrinkage: raw estimates vs. partial pooling") ax.legend(loc="upper right") plt.tight_layout() plt.show() ``` -------------------------------- ### Apple Silicon Architecture Validation Source: https://github.com/michaelnowotny/pyjags/blob/master/CMakeLists.txt Validates that Python and CMake architectures match on Apple Silicon to prevent issues with mixed Homebrew installations. This script checks for a common scenario where Python is ARM64 but CMake is x86_64. ```cmake if(APPLE) # Detect Python's architecture execute_process( COMMAND python3 -c "import struct; print(struct.calcsize('P') * 8)" OUTPUT_VARIABLE PYTHON_BITS OUTPUT_STRIP_TRAILING_WHITESPACE ERROR_QUIET ) execute_process( COMMAND python3 -c "import platform; print(platform.machine())" OUTPUT_VARIABLE PYTHON_ARCH OUTPUT_STRIP_TRAILING_WHITESPACE ERROR_QUIET ) # Detect CMake's own architecture execute_process( COMMAND file "${CMAKE_COMMAND}" OUTPUT_VARIABLE CMAKE_FILE_OUTPUT OUTPUT_STRIP_TRAILING_WHITESPACE ERROR_QUIET ) if(PYTHON_ARCH STREQUAL "arm64" AND CMAKE_FILE_OUTPUT MATCHES "x86_64" AND NOT CMAKE_FILE_OUTPUT MATCHES "arm64") message(FATAL_ERROR "Architecture mismatch: Python is arm64 but cmake is x86_64.\n" "This happens on Apple Silicon Macs with an Intel Homebrew cmake.\n" "Fix: install ARM-native cmake:\n" " /opt/homebrew/bin/brew install cmake\n" "Then ensure /opt/homebrew/bin is before /usr/local/bin in PATH:\n" " export PATH=\"/opt/homebrew/bin:$PATH\" ) endif() endif() ``` -------------------------------- ### Run PyJAGS Model and Sample Posterior Source: https://github.com/michaelnowotny/pyjags/blob/master/notebooks/Trading Cost Estimation.ipynb Initializes and samples from the PyJAGS model to obtain posterior distributions for the parameters 'c' (half-spread) and 'sigma' (volatility). It performs burn-in and then collects samples for analysis. ```python model = pyjags.Model( code=basic_model_code, data=basic_data, chains=4, threads=4, progress_bar=False, seed=42, ) model.sample(1000, vars=[]) # burn-in samples = model.sample(2000, vars=["c", "sigma", "q"]) idata = pyjags.from_pyjags(samples) c_post = samples["c"].flatten() print(f"Estimated half-spread: {c_post.mean():.4f} ({c_post.mean()*100:.2f}%)") print(f" 95% interval: [{np.percentile(c_post, 2.5):.4f}, {np.percentile(c_post, 97.5):.4f}]") ``` -------------------------------- ### Sample from Posterior Model Source: https://github.com/michaelnowotny/pyjags/blob/master/notebooks/Eight Schools.ipynb Initializes and samples from the posterior model using PyJAGS. This step generates samples representing updated beliefs after data observation. Includes a longer burn-in for stability. ```python # Sample from the posterior posterior_model = pyjags.Model( code=posterior_code, data=data, chains=4, threads=4, chains_per_thread=1, progress_bar=False, seed=42, ) posterior_model.sample(2000, vars=[]) # longer burn-in for stability posterior_samples = posterior_model.sample( 10000, vars=["mu", "tau", "theta_tilde", "log_like"]) ``` -------------------------------- ### Bundle JAGS Modules Source: https://github.com/michaelnowotny/pyjags/blob/master/CMakeLists.txt This snippet finds and installs JAGS shared object (.so) and dynamic library (.dylib) files into the pyjags/jags_modules directory. It provides status messages indicating the number of modules found or if none were found. ```cmake if(_JAGS_MODULES_DIR AND EXISTS "${_JAGS_MODULES_DIR}") file(GLOB _JAGS_MODULE_SO_FILES "${_JAGS_MODULES_DIR}/*.so") file(GLOB _JAGS_MODULE_DYLIB_FILES "${_JAGS_MODULES_DIR}/*.dylib") list(APPEND _JAGS_MODULE_FILES ${_JAGS_MODULE_SO_FILES} ${_JAGS_MODULE_DYLIB_FILES}) if(_JAGS_MODULE_FILES) install(FILES ${_JAGS_MODULE_FILES} DESTINATION pyjags/jags_modules) message(STATUS "Bundling JAGS modules from: ${_JAGS_MODULES_DIR}") list(LENGTH _JAGS_MODULE_FILES _nmodules) message(STATUS " ${_nmodules} module(s) found") else() message(STATUS "No JAGS module .so files found in: ${_JAGS_MODULES_DIR}") endif() else() message(STATUS "JAGS modules directory not found -- modules will not be bundled") endif() ``` -------------------------------- ### Sample from Prior Model Source: https://github.com/michaelnowotny/pyjags/blob/master/notebooks/Eight Schools.ipynb Initializes and samples from the prior model using PyJAGS. This step generates samples representing beliefs before data observation. ```python # Sample from the prior prior_model = pyjags.Model( code=prior_code, data={"J": 8}, chains=4, threads=4, chains_per_thread=1, progress_bar=False, seed=42, ) prior_model.sample(2000, vars=[]) prior_samples = prior_model.sample(10000, vars=["mu", "tau", "theta_tilde"]) ``` -------------------------------- ### Sample from Posterior Distribution using Pyjags Source: https://github.com/michaelnowotny/pyjags/blob/master/notebooks/Logistic Regression.ipynb Initializes and samples from the Pyjags model, performing adaptation and then collecting posterior samples for the model parameters. The results are converted to an ArviZ InferenceData object for analysis. ```python model = pyjags.Model( code=model_code, data=jags_data, chains=4, adapt=1000, progress_bar=False, seed=42, ) model.sample(1000, vars=[]) # burn-in samples = model.sample(5000, vars=["alpha", "beta_dist", "beta_arsenic", "beta_educ"]) idata = pyjags.from_pyjags(samples) az.summary(idata) ``` -------------------------------- ### Initialize Eight Schools Data Source: https://github.com/michaelnowotny/pyjags/blob/master/docs/notebooks/Eight Schools.ipynb Initializes the 'schools', 'y' (estimated treatment effects), and 'sigma' (standard errors) arrays for the Eight Schools dataset. This data is used for subsequent analysis and visualization. ```python schools = ["A", "B", "C", "D", "E", "F", "G", "H"] y = np.array([28.39, 7.94, -2.75, 6.82, -0.64, 0.63, 18.01, 12.16]) sigma = np.array([14.9, 10.2, 16.3, 11.0, 9.4, 11.4, 10.4, 17.6]) data = {"J": 8, "y": y, "sigma": sigma} ``` -------------------------------- ### Run All Tests with jagslab Source: https://github.com/michaelnowotny/pyjags/blob/master/CLAUDE.md Execute all tests within the project using the `jagslab` script. This is the recommended method for ensuring the project's integrity. ```bash ./scripts/jagslab test ``` -------------------------------- ### load_samples_dictionary_from_file Source: https://github.com/michaelnowotny/pyjags/blob/master/docs/api/io.md Loads MCMC samples from an HDF5 file into a dictionary. ```APIDOC ## load_samples_dictionary_from_file ### Description Loads MCMC samples from a specified HDF5 file path and returns them as a dictionary. This function is essential for retrieving previously saved MCMC simulation results. ### Method Not applicable (Python function) ### Endpoint Not applicable (Python function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python # Example usage samples = load_samples_dictionary_from_file("path/to/your/samples.h5") ``` ### Response #### Success Response (200) - **samples** (dict) - A dictionary containing the loaded MCMC samples. #### Response Example ```json { "samples": { "chain1": { "variable1": [1.0, 2.0, 3.0], "variable2": [4.0, 5.0, 6.0] }, "chain2": { "variable1": [1.1, 2.1, 3.1], "variable2": [4.1, 5.1, 6.1] } } } ``` ``` -------------------------------- ### Perform MCMC Sampling (Burn-in and Production) Source: https://github.com/michaelnowotny/pyjags/blob/master/docs/notebooks/Getting Started.ipynb Execute MCMC sampling for the model. This involves a burn-in phase to discard initial samples and a production phase to collect samples for analysis. ```python model.sample(1000, vars=[]) # burn-in (discard) samples = model.sample(5000, vars=["mu", "sigma"]) # production (keep) ``` -------------------------------- ### Sample and Analyze PyJAGS Model Source: https://github.com/michaelnowotny/pyjags/blob/master/docs/notebooks/Trading Cost Estimation.ipynb Initializes and samples from a PyJAGS model to estimate the half-spread and volatility. Converts samples to an ArviZ InferenceData object for further analysis and prints the estimated half-spread with its 95% credible interval. ```python import pyjags import arviz as az import numpy as np model = pyjags.Model( code=basic_model_code, data=basic_data, chains=4, threads=4, progress_bar=False, seed=42, ) model.sample(1000, vars=[]) # burn-in samples = model.sample(2000, vars=["c", "sigma", "q"]) idata = pyjags.from_pyjags(samples) c_post = samples["c"].flatten() print(f"Estimated half-spread: {c_post.mean():.4f} ({c_post.mean()*100:.2f}%)") print(f" 95% interval: [{np.percentile(c_post, 2.5):.4f}, {np.percentile(c_post, 97.5):.4f}]") ``` -------------------------------- ### Define Fallback Search Paths for JAGS Source: https://github.com/michaelnowotny/pyjags/blob/master/CMakeLists.txt Sets up platform-specific and environment-based paths to search for JAGS include files and libraries when pkg-config fails or provides insufficient information. Includes special handling for Apple Silicon. ```cmake if(NOT JAGS_FOUND) # Build platform-appropriate search paths. # On Apple Silicon, search /opt/homebrew first and skip /usr/local (Intel). if(APPLE AND PYTHON_ARCH STREQUAL "arm64") set(_JAGS_INCLUDE_HINTS /opt/homebrew/include /opt/homebrew/opt/jags/include ) set(_JAGS_LIB_HINTS /opt/homebrew/lib /opt/homebrew/opt/jags/lib ) elseif(APPLE) set(_JAGS_INCLUDE_HINTS /usr/local/include /opt/homebrew/include /opt/homebrew/opt/jags/include ) set(_JAGS_LIB_HINTS /usr/local/lib /opt/homebrew/lib /opt/homebrew/opt/jags/lib ) else() set(_JAGS_INCLUDE_HINTS /usr/local/include /usr/include ) set(_JAGS_LIB_HINTS /usr/local/lib /usr/lib /usr/lib/x86_64-linux-gnu /usr/lib/aarch64-linux-gnu ) endif() # Always include conda and JAGS_HOME paths list(APPEND _JAGS_INCLUDE_HINTS $ENV{CONDA_PREFIX}/include $ENV{JAGS_HOME}/include) list(APPEND _JAGS_LIB_HINTS $ENV{CONDA_PREFIX}/lib $ENV{JAGS_HOME}/lib) # Use unique variable names to avoid CMake find_* cache collisions find_path(_JAGS_FB_INCLUDE Console.h PATH_SUFFIXES JAGS PATHS ${_JAGS_INCLUDE_HINTS} NO_DEFAULT_PATH ) find_library(_JAGS_FB_LIB NAMES jags JAGS PATHS ${_JAGS_LIB_HINTS} NO_DEFAULT_PATH ) if(_JAGS_FB_INCLUDE AND _JAGS_FB_LIB) # Final architecture check on the fallback result _check_jags_arch("${_JAGS_FB_LIB}" _fb_arch_ok) if(_fb_arch_ok) set(JAGS_FOUND TRUE) set(JAGS_INCLUDE_DIRS "${_JAGS_FB_INCLUDE}") set(JAGS_LIBRARIES "${_JAGS_FB_LIB}") get_filename_component(JAGS_LIBRARY_DIRS "${_JAGS_FB_LIB}" DIRECTORY) else() set(JAGS_FOUND FALSE) endif() else() set(JAGS_FOUND FALSE) endif() unset(_JAGS_FB_INCLUDE CACHE) unset(_JAGS_FB_LIB CACHE) endif() ``` -------------------------------- ### Print Model Summary Source: https://github.com/michaelnowotny/pyjags/blob/master/notebooks/Eight Schools.ipynb Prints a summary of the initialized PyJAGS models, showing the number of chains, variables, and iterations. ```python print(f"Prior model: {prior_model}") print(f"Posterior model: {posterior_model}") ``` -------------------------------- ### Plotting Prior vs. Posterior Distributions Source: https://github.com/michaelnowotny/pyjags/blob/master/docs/notebooks/Eight Schools.ipynb Visualizes the prior and posterior distributions for model parameters 'mu' and 'tau'. Requires matplotlib and arviz. Ensure 'idata' is loaded. ```python fig, axes = plt.subplots(1, 2, figsize=(12, 4)) for ax, param, xlim in zip(axes, ["mu", "tau"], [(-20, 30), (0, 30)]): prior_vals = idata["prior"][param].values.flatten() post_vals = idata["posterior"][param].values.flatten() ax.hist(prior_vals, bins=80, density=True, alpha=0.4, color="steelblue", label="Prior (before data)", range=xlim) ax.hist(post_vals, bins=80, density=True, alpha=0.7, color="darkorange", label="Posterior (after data)", range=xlim) ax.set_xlabel(param) ax.set_ylabel("Density") ax.set_xlim(xlim) ax.set_title(f"{param}: before vs. after seeing the data") ax.legend() plt.tight_layout() plt.show() ``` -------------------------------- ### Load and Preprocess Well Data Source: https://github.com/michaelnowotny/pyjags/blob/master/notebooks/Logistic Regression.ipynb Loads well data from a CSV file, converts the 'switch' column to a binary indicator 'y', and scales the 'distance' feature. It then prints summary statistics of the dataset. ```python df = pd.read_csv(os.path.join("data", "wells.csv"), index_col=0) # Convert switch to binary df["y"] = (df["switch"] == "yes").astype(int) # Scale distance to 100m units for numerical stability df["dist100"] = df["distance"] / 100 print(f"Households: {len(df)}") print(f"Switched: {df['y'].sum()} ({df['y'].mean():.0%})") print(f"Did not: {(1 - df['y']).sum():.0f} ({1 - df['y'].mean():.0%})") df[["y", "arsenic", "dist100", "education"]].describe().round(2) ``` -------------------------------- ### Plot MCMC Trace and Density Source: https://github.com/michaelnowotny/pyjags/blob/master/docs/notebooks/Getting Started.ipynb Visualize the exploration of parameter space by MCMC chains. Use this to check for convergence and mixing. ```python az.plot_trace_dist(idata, var_names=["mu", "sigma"]) plt.tight_layout() plt.show() ``` -------------------------------- ### Pushing Tag to Remote Source: https://github.com/michaelnowotny/pyjags/blob/master/RELEASING.md Push the newly created tag to the remote repository to trigger the release workflow. ```bash git push origin master git push origin X.Y.Z ``` -------------------------------- ### Build Pybind11 Extension Module Source: https://github.com/michaelnowotny/pyjags/blob/master/CMakeLists.txt Configures the build for the pybind11 extension module 'console'. It specifies source files, include directories, library linking, and compile definitions. ```cmake pybind11_add_module(console src/pyjags/console.cc) target_include_directories(console PRIVATE ${JAGS_INCLUDE_DIRS}) if(JAGS_LIBRARY_DIRS) target_link_directories(console PRIVATE ${JAGS_LIBRARY_DIRS}) endif() target_link_libraries(console PRIVATE ${JAGS_LIBRARIES} Python3::NumPy) # Define PYJAGS_JAGS_VERSION macro (used in commented-out version check) if(JAGS_VERSION) target_compile_definitions(console PRIVATE PYJAGS_JAGS_VERSION="${JAGS_VERSION}" ) endif() # Ensure libjags is found at runtime via RPATH if(JAGS_LIBRARY_DIRS) set_target_properties(console PROPERTIES BUILD_RPATH "${JAGS_LIBRARY_DIRS}" INSTALL_RPATH "${JAGS_LIBRARY_DIRS}" ) endif() install(TARGETS console DESTINATION pyjags) ``` -------------------------------- ### Generate ArviZ Summary Statistics Source: https://github.com/michaelnowotny/pyjags/blob/master/notebooks/Trading Cost Estimation.ipynb Computes and displays a summary table of the posterior distributions for 'c' and 'sigma', including mean, standard deviation, credible intervals, effective sample size, and R-hat values. ```python az.summary(idata, var_names=["c", "sigma"]) ``` -------------------------------- ### Plotting Trace Distributions Source: https://github.com/michaelnowotny/pyjags/blob/master/docs/notebooks/Advanced Functionality.ipynb Visualizes the trace and posterior distributions for specified variables. Useful for a quick visual assessment of convergence and parameter exploration. ```python az.plot_trace_dist(idata_final, var_names=["phi_v", "sigma_v"]) plt.tight_layout() plt.show() ``` -------------------------------- ### Prepare Data for JAGS Model Source: https://github.com/michaelnowotny/pyjags/blob/master/notebooks/Advanced Functionality.ipynb Prepares the demeaned log returns data for input into the JAGS stochastic volatility model. This involves creating a dictionary with the data. ```python jags_data = {"r": demeaned} ```