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

Python API

prusie fits SuSiE fine-mapping models from individual-level data, centered sufficient statistics, or marginal summary statistics with linkage disequilibrium (LD), returning fitted models as SusieResult objects.

All numerical arrays are converted to float64 internally, and both variant and component indices are zero-based. See Inputs, alignment and priors for data preparation, Reading fine-mapping results for output fields, and the quick-start tutorial for an end-to-end walkthrough. Complete function signatures and docstrings are also accessible via Python's built-in help() (e.g., help(prusie.susie_rss)).

Fitting entry points

Select the fitting function corresponding to your input data format:

Function Inputs and purpose
susie Individual-level predictor matrix X (dense NumPy array or SciPy sparse matrix) and response vector y
susie_suff_stat Centered sufficient statistics XtX, Xty, yty, and sample size n (susie_ss is an alias)
susie_rss Marginal zz-scores z (or bhat and shat) with signed LD matrix R or reference genotypes X
susie_rss_lambda Marginal z, LD R (or reference X), and regularization parameter lambda_ for an isotropic covariance component
susie_ser Marginal z (or bhat and shat); fits a single-effect regression model without LD
susie_auto Individual-level X, y; runs staged susie fits that progressively double the component count LL
susie_trendfilter Ordered 1D response y; performs trend filtering using an implicit cumulative design operator (order=0 by default)

For a standard SuSiE-RSS analysis with signed marginal zz-scores z, signed LD correlation matrix R, association sample size n, and aligned variant_ids:

import prusie

fit = prusie.susie_rss(
    z=z, R=R, n=n,
    L=10, max_iter=100,
    estimate_residual_variance=False,
    variant_ids=variant_ids,
)

Ensure that z, both axes of R, and variant_ids share the same variant order and effect alleles (see Variant order and alleles).

Key behavior across entry points:

  • Individual-level and matrix-free designs: susie centers X and y (intercept=True) and standardizes predictors (standardize=True) by default, drops missing outcomes when na_rm=True, and computes univariate zz-scores when compute_univariate_zscore=True. Dense, sparse, and trend-filtering designs apply matrix–vector products directly without forming a dense p×pp \times p Gram matrix.
  • Reference genotypes and multi-panel RSS: In susie_rss(..., X=X), rows of X represent reference individuals (whose count may differ from study sample size n). Passing a sequence of LD matrices R or reference matrices X fits a multi-panel RSS model (requiring shared z and n). SciPy is required for sparse matrices, susie_rss_lambda, finite-reference or LD-mismatch models, and multi-panel RSS.
  • Deferred execution and warm starts: Passing init_only=True to susie, susie_suff_stat, susie_rss, or susie_rss_lambda (or susie_trendfilter with use_mad=False) returns a prepared SusieInputs object that can be fitted later via prusie.susie_workhorse(inputs). Passing a previous fit or posterior state dictionary to model_init (or its alias s_init) warm-starts the solver; see Convergence and refinement.

Shared fitting options

Most fitting entry points accept the following shared parameters (see Defaults by entry point for function-specific defaults):

Option Description
L=10 Maximum number of single-effect components (capped at the column count)
n_threads=1 Per-fit native thread count (1 to 32) for dense matrix preparation and products
scaled_prior_variance=0.2 Initial Gaussian effect variance relative to working phenotype variance (or NIG slab variance relative to σ2\sigma^2); scalar or length-L vector
prior_variance=50 Initial effect variance for susie_rss without n and for susie_rss_lambda
residual_variance=None Initial or fixed residual variance σ2\sigma^2 (defaults to working outcome variance; in susie_rss_lambda, specifies total variance before subtracting lambda_)
estimate_prior_variance=True Whether to estimate component prior variances VℓV_\ell during IBSS
estimate_prior_method="optim" Prior-variance estimation method: "optim" (Brent search), "EM", or "simple" (susie_ser supports "optim" and "simple")
prior_variance_grid, mixture_weights Fixed grid of positive prior variances and optional mixture weights (uniform by default); replaces scalar prior-variance estimation
estimate_residual_method="MoM" Residual-variance update method: "MoM", "MLE", or conjugate "NIG" (susie_rss_lambda supports "MLE" only)
alpha0, beta0 Positive NIG prior hyperparameters (each defaulting to 1/n1/\sqrt{n})
residual_variance_lowerbound, residual_variance_upperbound Lower and upper bounds applied to residual-variance updates
prior_weights=None, null_weight=0 Variant prior inclusion weights (uniform by default) and optional null-component prior weight
slot_prior=None Hierarchical component-activity prior constructed via slot_prior_betabinom or slot_prior_poisson
L_greedy, greedy_lbf_cutoff=0.1 Incrementally grow LL in steps of L_greedy, stopping when the weakest component log Bayes factor falls below greedy_lbf_cutoff or LL is reached
convergence_method, convergence Stopping rule selection: "elbo" (default), "pip", or a ConvergenceConfig instance for custom "elbo", "alpha_pip", or "joint" tolerances
coverage=0.95, min_abs_corr=0.5 Credible-set cumulative posterior mass target and minimum within-set absolute LD correlation threshold
n_purity Maximum set size for full pairwise purity evaluation on individual-level X ("auto" in susie/susie_rss_lambda, None in matrix-based fits)
median_abs_corr, cs_extension_corr Optional median-purity threshold and single-hop LD correlation threshold for extending credible sets
maf, maf_thresh=0 Filter inputs to retain variants with maf > maf_thresh (susie_suff_stat and susie_rss)
verbose=False Emit sweep count, convergence, and credible-set summaries via the prusie Python logger
variant_ids, variant_metadata Ordered variant identifiers and dictionary of aligned per-variant annotation columns

Key interactions among shared options:

  • Defaults across data modalities: susie and susie_suff_stat default to max_iter=100 and estimate_residual_variance=True, whereas susie_rss and susie_rss_lambda default to max_iter=50 and estimate_residual_variance=False (keeping residual variance fixed is recommended when using an external LD reference). Default convergence tolerance tol is 1e-4 for standard Gaussian fits, 1e-6 when tol=None is paired with "NIG", and 1e-3 for susie_rss_lambda.
  • Extended priors: Selecting estimate_residual_method="NIG" automatically enables residual-variance estimation and uses "EM" for prior-variance updates. Both slot priors and multi-component NIG models use the PIP stopping rule; see Additional model options and Convergence diagnostics.
  • Multithreading: n_threads (1 to 32, recorded in fit.params["n_threads"]) configures a private per-fit thread pool for large dense Gram products and eligible RSS LD preparation without altering global BLAS, OpenMP, or Rayon thread settings; see Native threading.

Optional LD workspace

By default, susie_rss(..., overwrite_ld=False) preserves all caller arrays unchanged. Setting overwrite_ld=True allows the solver to reuse the caller's LD matrix R in place as a workspace when symmetry repair and sample-size scaling (XtX = (n - 1) * R) are needed, avoiding the allocation of a separate p×pp \times p repair buffer.

Important: When overwrite_ld=True, once in-place writes begin, R (and any views or aliases sharing its memory) is modified permanently without rollback—even if a subsequent validation check or fitting step raises an exception. Always reload R before reusing it in another call.

To use overwrite_ld=True, the call must satisfy the standard dense Gaussian RSS contract:

  • Array layout: R must be a square, writable, aligned, C-contiguous float64 NumPy array owning its heap buffer (or a reshape view thereof) and must not overlap any other input array. Subclasses, memory-mapped arrays, Fortran-ordered arrays, and non-contiguous slices are rejected before any writes occur.
  • Model settings: Requires single-panel z, R, and known n with var_y=None, estimate_residual_method="MoM", convergence_method=None or "elbo", R_mismatch="none", R_finite=None or False, and control=None. It cannot be combined with bhat/shat, reference X, maf filtering, null_weight, mixture/slot/NIG priors, L_greedy, warm starts, check_input=True, track_fit, retain_data, refine, or init_only=True.

On completion, fit.qc["ld_overwrite"]["action"] records how R was handled (with s = n - 1):

Recorded action State of R after the call
ordered_scaled_xtx An asymmetric pair was detected; all of R was overwritten with the symmetrized scaled matrix XtX, each entry storing ((n - 1) * R_ij + (n - 1) * R_ji) / 2
symmetric_no_write Vectorized exact-symmetry proof succeeded (x86-64 builds); R remains untouched
no_witness_eager_no_write No finite pair had unequal scaled values; R remains untouched

See Dense storage and matrix products for implementation details and Additional model options for other RSS parameters (z_method, R_finite, R_mismatch, susie_rss_control, and lambda_).

SusieResult

Fitting functions return a SusieResult dataclass providing direct attribute access to posterior arrays (fit.pip, fit.alpha, fit.mu, fit.mu2, fit.coef), credible sets (fit.sets), convergence records (fit.convergence, fit.elbo), and input quality checks (fit.qc, fit.input_quality). See Posterior fields for complete field definitions and array shapes.

Calling fit.as_dict() returns a dictionary of stored public attributes without copying the underlying arrays (omitting computed properties like coef and private retained-input snapshots; see Convergence and post-analysis).

Posterior and model helpers

prusie exports top-level helper functions modeled after susieR for extracting posterior summaries and preparing regression inputs:

Function Purpose
susie_get_pip Compute marginal PIPs from a SusieResult or raw alpha matrix
susie_get_cs Extract credible sets from a SusieResult or alpha matrix (pass X or Xcorr for purity filtering and LD extension)
susie_get_cs_attainable Screen credible sets by attainable posterior mass and entropy without LD purity filtering
susie_get_posterior_mean, susie_get_posterior_sd Compute variant posterior means and standard deviations across active components on the input predictor scale
susie_get_lfsr Compute component-level alpha-weighted Gaussian local false-sign rates (lfsr)
susie_get_posterior_samples Draw posterior regression coefficients (b) and causal indicators (gamma); requires num_samples and keyword seed
susie_get_objective, susie_get_niter Return the final recorded ELBO (last_only=False returns the full trace) and completed sweep count
susie_get_prior_variance, susie_get_residual_variance Return fitted component prior variances V and residual variance sigma2
get_cs_correlation Compute correlations among the highest-PIP variants of retained credible sets
coef, predict, summary Extract regression coefficients (with intercept prepended), response predictions, or vars/cs summary lists
compute_suff_stat Compute centered sufficient statistics (XtX, Xty, yty, n, means) from X and y
univariate_regression, calc_z Compute marginal univariate effect estimates and standard errors, or marginal zz-scores
susie_init_coef Build alpha, mu, and mu2 warm-start arrays from a vector of initial working-scale coefficients
susie_post_outcome_configuration Evaluate multi-outcome activation configurations (method="susiex") or pairwise colocalization H0–H4 probabilities ("coloc_pairwise") from existing fits (requires SciPy)

Note that top-level coef(fit) prepends fit.intercept (and includes any null column), whereas the property fit.coef returns only the pp biological variant effects. Both coef and predict apply slot_weights when a slot-activity prior is used. Lower-level array routines prusie.posterior.marginal_pip and prusie.posterior.credible_sets operate directly on NumPy arrays; see Credible-set fields.

load_example

prusie.load_example() loads the bundled 500-variant synthetic dataset and its default fitting parameters:

import prusie

example = prusie.load_example()
fit = prusie.susie_rss(**example["inputs"], **example["parameters"])

The returned dictionary contains "inputs" (z, R, n, variant_ids), "parameters", and "metadata". Each call verifies SHA-256 checksums of the packaged files and returns fresh caller-owned NumPy arrays without requiring network access or R; see the quick-start tutorial.

Convergence and post-analysis

To inspect convergence behavior, read fit.convergence or call prusie.diagnose_convergence(fit). When track_fit=True (or "compact") is enabled during fitting, fit.trace stores per-sweep scalar metrics and a compact sparse snapshot of alpha (track_fit="dense" stores full alpha, mu, and mu2 arrays at every sweep). Calling assess_convergence(fit_or_summary, *, tail=5, pip_stability=1e-3) classifies the stopping trajectory (converged, slow_monotone, oscillating, elbo_decreasing, etc.), estimates remaining sweeps for slowly converging fits, and checks whether leading variants and PIPs have stabilized; see Assess the last few sweeps and Convergence diagnostics.

For fits with retained inputs (retain_data=True), three post-fitting operations are available:

Function Purpose
continue_fit Run additional IBSS sweeps starting from the saved posterior (max_iter=100 specifies the additional sweep budget)
refine_fit Search alternative credible-set exclusion initializations for a higher-ELBO solution, recording search history in fit.refinement
evaluate_objective Recompute the exact post-trimming ELBO, KL divergences, and fitted crossproducts from the finalized posterior without running IBSS

Input retention (retain_data=True, also enabled automatically by track_fit, refine, or warm starts on supported routes) is supported for standard materialized Gaussian susie_suff_stat and susie_rss fits using default or ConvergenceConfig stopping rules. Matrix-free individual-level designs, dynamic RSS routes (susie_rss_lambda, R_finite, R_mismatch, multi-panel RSS), mixture/NIG/slot priors, convergence_method="pip", L_greedy, and non-default median_abs_corr / cs_extension_corr do not store retained snapshots (on those routes, passing refine=True to the entry point performs refinement by refitting, except in multi-panel RSS where refinement is unsupported).

When refine_fit returns, fit.converged reflects the outer refinement search status (matching susieR), while fit.convergence["inner_ibss_converged"] records whether the accepted fit's inner IBSS loop converged and fit.refinement["status"] (plus fit.refinement["relative_stop"], when applicable) describes the search termination; see The relative stop in large samples and the Convergence and refinement guide.

Summaries, comparisons and reports

The following functions summarize fitted models, compare alternative specifications, diagnose LD consistency, and generate offline reports:

Function Purpose
summarize Build structured variant, component, credible-set, LD-proxy, and prior-influence tables from a SusieResult
summary_text Format a concise plain-text summary of a summarize result (plus optional ld= and comparison= records)
compare_fits Compare a dictionary of named SusieResult objects across variants (mode="union" or "common")
run_sensitivity Execute a list of named sensitivity specifications (parameter overrides, alternative inputs, or coverage/purity re-extractions) against a baseline fit
standard_sensitivity_plan Generate a default sensitivity plan (halving/doubling LL, 90%/99% coverage, 0.8 purity, and refinement)
diagnose_ld Evaluate conditional zz-score residuals and allele-flip likelihood ratios against R
write_report Export a self-contained directory containing an offline HTML report, CSV tables, JSON summaries, and rendered figures

summarize, summary_text, compare_fits, run_sensitivity, standard_sensitivity_plan, and diagnose_ld are exported at the top level of prusie, while write_report, analysis_summary, save_analysis, and load_analysis are imported from prusie.report. In write_report (as well as analysis_summary and summary_text), competing_elbo_gap (default 1.0 nat) sets the ELBO margin within which an alternative refinement candidate with different credible sets is flagged for attention, and figure_sections maps custom figure titles to report sections ("locus", "fit", "variance", "signal", "sensitivity", or "ld"). See the quick-start report guide and Sensitivity and LD diagnostics.

Figures and local style

The prusie.viz module (also aliased as prusie.plots; requires the analysis extra) provides publication-ready Matplotlib plotting functions. Every plotting function returns a (figure, axes, plotted_data) tuple and supports layout="full" (default) or layout="compact":

Function Visualization
plot_locus Regional association (−log⁡10P-\log_{10} P), marginal PIPs, credible sets, per-CS lead-variant LD r2r^2 tracks, and optional gene track
plot_convergence Per-sweep ELBO, ΔELBO\Delta\mathrm{ELBO}, and maximum alpha/PIP changes ("compact"), variance trajectories ("variance"), or both ("full")
plot_refinement Before-and-after PIP comparison, per-attempt ELBO gains, and accepted objective progression
plot_sensitivity Baseline-first PIP heatmap across sensitivity runs (candidates_only=True and layer="signals" by default, or layer="components")
plot_signal Single-component alpha profile, cumulative posterior mass, and within-CS pairwise LD heatmap (selected by component_id or variant_id)
plot_prior_influence Prior weights, component-conditional log Bayes factors, and final alpha for a selected component
plot_ld_diagnostics Observed versus expected conditional zz-scores, standardized residuals (or auxiliary="log_lr"), and allele-flip flags

All plotting functions apply a clean white-background theme scoped via a context manager so global Matplotlib rcParams are never permanently altered. You can customize fonts, sizes, or styling locally by passing a dictionary to style= (or pass style=False to inherit your active Matplotlib settings):

from prusie.viz import plot_convergence

figure, axes, data = plot_convergence(
    fit, layout="compact", style={"font.size": 11, "axes.labelsize": 11},
)
figure.savefig("convergence.svg", bbox_inches="tight")

Heatmap scales and labels

PIP heatmaps (plot_sensitivity) use the Blues colormap on a fixed linear [0, 1] scale, shading variants absent from a fit in grey (NA) and formatting cell labels as 0, 1, <0.01, >0.99, or two-decimal probabilities (see Common and union comparison support). Within-CS LD heatmaps (plot_signal) default to signed correlation rr on [-1, 1] (RdBu_r), or r2r^2 on [0, 1] (Reds) when ld_measure="r2"; custom colormaps can be passed via cmap= (see the Toy example).

Other display controls

  • Relative ELBO trajectories: Passing relative_elbo=True to plot_convergence shifts each curve relative to its initial finite ELBO value.
  • Genomic coordinates and LD tracks in plot_locus: When finite physical positions are present in variant metadata, plot_locus scales the horizontal axis in "bp", "kb", or "Mb" (position_unit="auto" by default) and plots one LD r2r^2 track per retained credible set referenced to its highest-alpha lead variant (or a single track when reference_variant is specified, or colored scatter points when color_by_ld=True).
  • Gene annotation tracks: prusie.viz.read_gene_track parses gene intervals from a local GTF file (using 1-based closed coordinates and checking chromosome/build metadata) for display in plot_locus.