Fine-mapping · Python + RustLucaJiang/prusie
On this page

Quick start: fit, read and report

This tutorial walks through a complete SuSiE-RSS workflow using the synthetic dataset bundled with prusie. The dataset contains 500 correlated variants—two with true nonzero effects—and is available offline immediately after installation. We will fit the model once and reuse the fitted posterior to inspect posterior inclusion probabilities (PIPs), credible sets, diagnostic plots, and an offline HTML report.

Load inputs and fit

Load the packaged summary statistics and linkage disequilibrium (LD) matrix, then fit the SuSiE-RSS model:

import numpy as np
import prusie

example = prusie.load_example()
inputs = example["inputs"]
print(inputs["R"].shape, inputs["n"])
fit = prusie.susie_rss(
    **inputs,
    **example["parameters"],
    track_fit="compact",
    retain_data=True,
)
print("Converged:", fit.converged, "Iterations:", fit.niter)

Expected output:

(500, 500) 1000
Converged: True Iterations: 3

Here example["parameters"] configures up to five single-effect components (L=5), max_iter=100, and an ELBO convergence tolerance of tol=0.001, with estimated prior variances, residual variance fixed at 1, and the default credible-set thresholds (coverage=0.95 and min_abs_corr=0.5; see shared fitting options). Passing track_fit="compact" records per-sweep convergence metrics in fit.trace for plotting, while retain_data=True preserves the prepared inputs for downstream continuation or refinement.

When analyzing your own data, ensure that the signed zz-scores, variant_ids, and both axes of the signed LD correlation matrix R share the exact same variant order and effect-allele orientation (note that unsigned r2r^2 matrices cannot be used in place of signed rr). See Inputs, alignment and priors for data preparation guidelines.

Read PIPs and credible sets

Each single-effect component captures one putative association signal and yields a credible set of candidate variants, while a variant's marginal PIP aggregates its inclusion probability across all active components. We can inspect the top variant and list all retained credible sets directly from fit:

lead = int(np.argmax(fit.pip))
print(f"Lead: {fit.variant_ids[lead]}, PIP={fit.pip[lead]:.6g}")
for k, component in enumerate(fit.sets["cs_index"]):
    members = fit.variant_ids[fit.sets["cs"][k]].tolist()
    print(
        f"Component {int(component)}: {', '.join(members)}; "
        f"mass={fit.sets['coverage'][k]:.6g}; "
        f"minimum |r|={fit.sets['purity']['min_abs_corr'][k]:.6g}"
    )

Expected output:

Lead: syn0350, PIP=0.999937
Component 0: syn0100; mass=0.969674; minimum |r|=1
Component 1: syn0350; mass=0.999937; minimum |r|=1

fit.sets["coverage"] reports the cumulative posterior mass attained by each credible set, which is at least the requested coverage=0.95. Component indices in fit.sets["cs_index"] refer to zero-based rows of fit.alpha and need not be consecutive if inactive or low-purity components were filtered out. Because both credible sets in this example are singletons, their within-set LD purity is 1 by convention. See credible-set fields for full details on returned fields and filtering rules.

Summarize the fitted posterior

prusie.summarize organizes a fitted model into structured variant, component, and credible-set tables without refitting. Passing R also identifies high-LD proxy variants outside each credible set and records between-set correlations:

summary = prusie.summarize(fit, inputs["R"], z=inputs["z"])
print(prusie.summary_text(summary).splitlines()[0])
print("Stop:", summary["convergence"]["stop_reason"])

Expected output:

500 variants; 2 retained credible sets; 2 active components.
Stop: criterion_satisfied

Printing the full string from prusie.summary_text(summary) displays credible-set summaries, top variants by PIP, and the status of optional post-fitting checks (such as refinement or LD consistency diagnostics).

Write an offline report

With the analysis extra installed, you can generate diagnostic figures and bundle the entire analysis into a self-contained HTML report:

from prusie.report import write_report
from prusie.viz import plot_convergence, plot_locus

report = write_report(
    summary,
    "output/analysis",
    title="Synthetic fine-mapping example",
    figures={
        "Locus overview": plot_locus(summary, R=inputs["R"], layout="compact"),
        "Convergence": plot_convergence(fit, layout="compact"),
    },
)
print(report["html"])

Opening the printed HTML path in a browser displays key diagnostic checks, credible-set and candidate-variant tables, and interactive views of the supplied figures. The output directory contains both human-readable and machine-readable artifacts:

Export Description
index.html Self-contained offline HTML report
summary.txt, analysis_summary.json Plain-text and structured JSON summaries
tables/*.csv, plot_data.json Exported summary tables and underlying figure coordinates
figure_index.json, *.png, *.svg Rendered raster and vector figures with metadata index
evidence.json Full-precision scalar metrics with stable JSON pointers
analysis.json, arrays.npz Reloadable summary tables, diagnostics, and metadata

Keep the report directory intact when moving or sharing it so relative links to images and CSV tables remain valid. To archive the full SusieResult posterior arrays (alpha, mu, mu2), save the fit object as shown below.

Save and reload a result

save_analysis and load_analysis serialize and restore a SusieResult using analysis.json and arrays.npz without loss of floating-point precision:

from prusie.report import load_analysis, save_analysis

save_analysis(fit, "output/fit")
restored = load_analysis("output/fit")
print("PIPs identical:", np.array_equal(restored.pip, fit.pip))

Expected output: PIPs identical: True. (Calling load_analysis("output/analysis") on a report directory returns a dictionary containing the saved "summary" tables.)

To keep saved archives compact, save_analysis omits the in-memory input snapshot (R and z), which means prusie.continue_fit(restored) cannot be called directly on a reloaded result. However, you can pass s_init=restored alongside the original inputs to warm-start a new susie_rss call; see retained inputs and warm starts.

From here, continue to Reading fine-mapping results, Convergence and refinement, Sensitivity and LD diagnostics, or the Toy example.

Advanced export and example provenance

Manual arrays and metadata export

If you only need specific NumPy arrays and JSON metadata for downstream pipelines rather than a reloadable SusieResult, you can export them directly:

import json
from pathlib import Path

out = Path("fine-mapping-result")
out.mkdir(exist_ok=True)
np.savez_compressed(
    out / "posterior.npz",
    pip=fit.pip, alpha=fit.alpha, mu=fit.mu, mu2=fit.mu2,
    lbf_variable=fit.lbf_variable, V=fit.V, elbo=fit.elbo,
    variant_ids=fit.variant_ids,
)
sets = [
    {
        "component": int(component),
        "members": fit.variant_ids[fit.sets["cs"][k]].tolist(),
        "posterior_mass": float(fit.sets["coverage"][k]),
    }
    for k, component in enumerate(fit.sets["cs_index"])
]
metadata = {
    "prusie_version": prusie.__version__,
    "parameters": fit.params,
    "converged": fit.converged,
    "niter": fit.niter,
    "sets": sets,
    "generation": example["metadata"],
}
(out / "metadata.json").write_text(json.dumps(metadata, indent=2), encoding="utf-8")
Generation, frozen reference and numerical agreement

The bundled example dataset is simulated by tools/generate_example.py using NumPy's PCG64 generator (seed=20261007) with n=1000n=1000 observations and p=500p=500 stationary Gaussian AR(1) predictors (ρ=0.85\rho=0.85), centered and standardized to unit sample variance. Two variants at zero-based indices 99 (syn0100) and 349 (syn0350) carry true effects of 0.350.35 and −0.30-0.30 under standard normal noise. Marginal zz-scores are computed from univariate tt-statistics (z=β^/SEz = \hat\beta / \mathrm{SE}), and R is the in-sample Pearson correlation matrix.

The independent 500-variant toy example converged in 3 iterations and returned 2 credible sets. Its maximum absolute PIP difference from the separately generated susieR 0.16.6 reference was 1.66e-10.

Original component Synthetic variants Returned posterior mass Minimum |r|
0 syn0100 0.969674 1.000000
1 syn0350 0.999937 1.000000
Signed z and fitted PIPs, with the two synthetic true effects marked.
Open original figure

Running python tools/generate_example.py --check verifies that regenerating the dataset reproduces the packaged arrays within documented floating-point roundoff bounds, and prusie.load_example() validates SHA-256 checksums of the packaged files on load. The reference posterior was fitted independently in susieR 0.16.6 under identical settings; see Reproducibility and Numerical accuracy for verification commands.