One-stop MCMC learning center · 0.8.0+

Choose one route into Bayesian modeling with JDistlib

You do not need to read every page or know Stan. Pick the route that matches how you want to define a model; return here later for examples, diagnostics, and advanced topics.

Java models · RJMCMC · JDM scripts · Stan source · MCMC review

Start here

What are you trying to do?

A · Recommended quick start

Run one complete analysis

Load a CSV and JDM file, compile the model, customize NUTS, run four chains, print diagnostics, plot convergence, summarize the posterior, and reach a conclusion.

Follow the worked analysis →
B · No model script

Construct the model in pure Java

Use ModelBuilder, constraints, and model factors directly, then send the resulting BayesianModel through the same samplers and diagnostics.

Use the Java route →
C · Variable model dimension · expanded in 0.9.1

Select covariates with RJMCMC

Move between genuinely different parameter dimensions with Java-only add/drop/swap proposals, scale to sparse candidate universes, inspect inclusion mixing, export ragged draws, and resume exact checkpoints.

Open the reversible-jump route →
D · Learn from code

Browse available features

Find runnable examples for MCMC, distributions, copulas, mixtures, transformations, custom laws, FDR, numerical solvers, and autodiff.

Choose an example catalog →
E · Text models

Use JDM or existing Stan source

Learn data binding and compilation, browse JDM and ordinary .stan models, or follow focused container, function, and solver tutorials.

Choose a script route →
New to the language?

Learn the Stan model structure first

Start with introductory material instead of jumping into compatibility tables. JDM is Stan-inspired, but using the pure-Java route requires no Stan knowledge.

Open beginner resources →
Already sampling?

Tune, diagnose, or go deeper

Choose samplers and metrics, interpret R-hat/ESS/MCSE, investigate divergences, review plots, checkpoint runs, and inspect modern MCMC features.

Open review resources →

Route A · recommended quick start

CSV → JDM → compiled model → MCMC → conclusion

WorkedMcmcCsvJdmExample.java is a deliberately verbose, line-by-line-commented Java program. It uses the checked-in CSV dataset and JDM model, so it runs without downloads or editing.

  1. Load and validate dataRead the named y CSV column into a primitive double[].
  2. Load and compile JDMRead UTF-8 source, bind N/y, call ModelScript.compile, and check its gradient.
  3. Customize and sampleSet warmup, retained draws, target acceptance, tree depth, and metric adaptation; launch four dispersed seeded NUTS chains.
  4. Diagnose and visualizePrint R-hat, ESS, MCSE, acceptance, divergences, depth, E-BFMI, and failures; export trace, rank, ACF, and energy plots.
  5. Summarize and concludeReport posterior summaries, P(mu > 0), an exact cross-check, a predictive draw, and a conclusion conditional on convergence.
double[] y = readNumericColumn(csvPath, "y");
String source = new String(Files.readAllBytes(modelPath), UTF_8);
Map<String, double[]> data = new LinkedHashMap<>();
data.put("N", new double[] {y.length});
data.put("y", y);

CompiledModelScript compiled = ModelScript.compile(source, data);
BayesianModel model = compiled.model();
SamplingOptions options = SamplingOptions.builder()
    .warmupIterations(600).sampleIterations(1200)
    .targetAcceptance(0.90).maximumTreeDepth(11)
    .adaptMassMatrix(true).denseMassMatrix(false).build();
ChainResult[] chains = Chains.parallel(
    new NoUTurnSampler(), model, initialStates,
    options, BASE_SEED, 4);
McmcDiagnosticReport report = McmcDiagnostics.analyze(
    new String[] {"mu"}, chains);

Run the complete file

From the repository root, compile the packaged JAR and examples with ./gradlew compileDocumentationExamples on macOS/Linux or gradlew.bat compileDocumentationExamples on Windows. The classpath wildcard deliberately remains valid when the project version changes.

macOS/Linux:

java -cp "build/libs/*:build/documentation-examples" \
  examples.WorkedMcmcCsvJdmExample

Windows:

java -cp "build\libs\*;build\documentation-examples" examples.WorkedMcmcCsvJdmExample

Optional arguments are CSV_PATH JDM_PATH OUTPUT_DIRECTORY. The default output directory contains mu-trace.svg, mu-ranks.svg, mu-autocorrelation.svg, energy.svg, retained-draws.csv, diagnostics.json, and a self-contained report.html.

Interpret computation before evidence

For the checked-in data, the seeded run has a posterior mean near 0.22, posterior SD near 0.35, and a 95% interval crossing zero. The example first verifies chain status, R-hat, ESS, divergences, depth, E-BFMI, and failures; only then does it conclude that computation is healthy but the data do not establish the sign of the mean.

Route B · pure Java

Build a posterior without learning JDM or Stan

McmcWorkflowExamples.java constructs a beta-binomial model entirely with Java objects. The model definition changes, but gradient checking, SamplingOptions, parallel chains, diagnostics, and graph exports are the same.

BayesianModel model = new ModelBuilder()
    .data("n", 10).data("y", 7)
    .parameter("theta", Constraints.bounded(0, 1), 0.5)
    .factor("prior", new String[] {"theta"},
        ModelFactors.betaPrior("theta", 2, 2))
    .factor("likelihood", new String[] {"n", "y", "theta"},
        ModelFactors.binomialObservation("y", "n", "theta"))
    .build();

Use this route when models are assembled dynamically, data already live in Java services, or your team prefers compiler-checked Java APIs. For a CSV array bound to both the Java builder and JDM frontend, see McmcDataIngestionExamples.java. Continue with the model-layer reference and ModelBuilder JavaDoc.

Route C · trans-dimensional Java · expanded in 0.9.1

Use reversible-jump MCMC when model dimension really changes

JDistlib’s Java-only RJMCMC layer stores variable-length parameter states. The general engine accounts for forward and reverse proposal densities, boundary-dependent move-selection probabilities, dimension matching, and Jacobians. The additive sparse-subset engine uses sorted integer indices when the candidate universe is much larger than a bit mask.

Small exact example

Covariate selection

Follow a normalized linear-regression target through four add/drop/swap chains, model and inclusion diagnostics, ragged export, and exact checkpoint continuation.

Read the worked RJMCMC example →
Public data · 17,000 genes · mixed effects

Sparse transcriptome selection

Download GSE93272, fit a subject random-intercept model, use GPU-assisted residual proposals, and continue bounded segments safely after reboots.

Read the sparse public-data tutorial →
API contract

When to choose it

Use RJMCMC for genuine shape changes such as variable selection, change points, mixture components, or split/merge constructions. Use fixed-dimensional indicators when padding is simpler.

Review the RJMCMC contract →

Route D · examples by feature

Start from code the build verifies

Complete example center

Browse ordinary Java integrations plus the JDM and Stan fixture catalogs. Filter by copula, mixture, transformation, FDR, custom distribution, MCMC, numerical integration, autodiff, or solvers.

Browse all feature examples →

Fifteen Bayesian models

Study conjugate models, regression, hierarchy, robust likelihoods, difficult geometry, multimodality, simplexes, Gibbs updates, and dense metrics as named executable tests.

Browse the Bayesian showcase →

For an applied narrative rather than an API catalog, use the posterior-prediction vignette or the difficult-chain diagnostics vignette.

Route E · JDM and Stan source

Choose the script depth you need

Data and compilation

Compile a JDM model

Bind CSV-derived arrays and compare in-memory, cached, and ahead-of-time compilation.

Open the JDM tutorial →
JDM catalog

Browse fifty-one scripts

Find regression, count, robust, survival, Wiener reaction-time, constraints, control flow, file-backed data, and generated quantities.

Browse JDM examples →
Ordinary Stan source

Browse compatibility fixtures

Inspect arrays, matrices, tuples, functions, sparse kernels, solvers, and probability models compiled by JDistlib.

Browse .stan fixtures →
Coming from Stan

Map the workflow to Java

Compare data, compilation, sampling, generated quantities, output, and execution semantics.

Open the Stan-user guide →
Numerical systems

Roots, ODEs, and DAEs

Use Java or script callbacks, sensitivities, stiff integration, and higher-index projection.

Solver tutorial →

No Stan background required

Learn only as much model language as your route needs

Tune, diagnose, and extend

Open advanced material when you have a specific question

Operating reference

Choose and tune samplers

Review warmup, metrics, R-hat, ESS, MCSE, divergences, tree depth, E-BFMI, plots, performance, checkpoints, and failures.

Open inference reference →
Computational review

Diagnose unhealthy chains

Use trace, rank, pairs, and energy evidence to distinguish too few draws from difficult geometry.

Open diagnostics vignette →
Development features

Explore the modern MCMC core

Read about staged warmup, metrics, exact NUTS checkpoints, adjusted MCLMC, additional kernels, streaming, and future work.

Modern MCMC guide →