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

Implementation

This page documents prusie's internal architecture, tracing how a fitting call flows from the public Python API through the PyO3 native binding to the Rust IBSS solver and back into a SusieResult object. See Statistical model for the mathematical equations and Speed and memory optimization for details on the computational algorithms.

The codebase is organized into three layers:

  1. Python package (src/prusie): Validates arguments, constructs working sufficient statistics or matrix-free design operators, dispatches the appropriate fitting route, and assembles posterior summaries, plots, and HTML reports.
  2. Rust PyO3 binding (rust/prusie-python, imported as prusie._native): Verifies NumPy array memory layouts and borrows, parses solver options, manages per-fit thread pools, and converts native outputs into NumPy arrays.
  3. Rust solver core (rust/prusie-core): A standalone Rust crate (with no Python dependency) implementing iterative Bayesian stepwise selection (IBSS), single-effect regression (SER), matrix operators, exact signed-column grouping, and convergence checks.

Architecture

Fitting call paths through Python input preparation, the native binding and the Rust solver, with a separate Python sweep loop for dynamic RSS models.
Open original figure

As shown in the diagram above, public entry points validate and normalize their inputs before calling workhorse._fit, which dispatches the prepared _FitRequest to the native Rust solver (or the Python dynamic RSS loop) and wraps the resulting posterior arrays, PIPs, and credible sets in a SusieResult (see Call paths).

Layer Primary modules Responsibilities
Python entry points (src/prusie/) individual.py, suff_stat.py, rss.py, rss_lambda.py, constructors.py, ser.py Public interfaces for individual-level data, sufficient statistics, SuSiE-RSS, RSS-lambda, susie_auto, susie_trendfilter, and standalone SER
Python shared core (src/prusie/) _request.py, workhorse.py, rss_models.py, posterior.py, result.py, refinement.py, _validation.py Request preparation, solver dispatch, dynamic RSS sweeps, PIP and credible-set construction, continuation, and refinement
Rust PyO3 binding (rust/prusie-python/src/) lib.rs, options.rs, array_layout.rs, summary_helpers.rs, prepare_helpers.rs, design.rs, ser.rs, output.rs, executor.rs Zero-copy NumPy array borrowing, option parsing, LD validation/repair bindings, purity helpers, and private thread-pool management
Rust solver core (rust/prusie-core/src/) Modules listed below Core IBSS loop, SER updates, matrix operators, variance estimation, ELBO evaluation, and stopping criteria

The core solver crate (rust/prusie-core/src/) is divided into focused modules:

Solver module Contents
ibss.rs Dense entry points (fit_controlled, fit_controlled_with_executor), generic fit_operator IBSS sweep loop, ELBO evaluation, variance updates, and final component trimming
ser.rs, optimizer.rs Gaussian and fixed-mixture SER updates, standalone ser_update, and Brent prior-variance optimization
residual.rs, diagnostics.rs Expected residual sum of squares (ER2), per-sweep convergence metrics, stopping rules, and cycle detection
operator.rs, exact_columns.rs, activation.rs GramOperator trait, dense matrix–vector kernels, implicit scaling, exact signed-column equivalence classes, and work-count activation logic
design.rs Matrix-free operators for dense individual-level X, sparse CSC X, and trend-filtering designs
nig.rs, slot.rs Conjugate Normal–Inverse-Gamma residual-variance inference and hierarchical slot-activity priors
input_validation.rs, input_validation/ Tiled finiteness/diagonal/symmetry validation, vectorized exact-symmetry proofs, and fused RSS repair
execution.rs, parallel.rs Per-fit Rayon thread pools and row-partitioned parallel matrix–vector products
vector_math.rs, numerical.rs libmvec SIMD exponentials, compensated summation, and digamma evaluation
types.rs, options.rs, model.rs Configuration structs, model extensions, and result containers

Fitting routes

After _request._prepare_request constructs a _FitRequest, workhorse._fit selects one of three execution routes (where native entry points belong to prusie._native):

Route Applicable models Native entry point IBSS sweep loop
Dynamic RSS susie_rss with R_finite, R_mismatch, or multi-panel R/X sequences; susie_rss_lambda ser_update (called per component update) Python rss_models.fit_dynamic
Dense Gram susie_suff_stat (susie_ss); standard single-panel susie_rss with dense R (or reference X paired with bhat, shat, and var_y) fit Rust fit_operator with DenseGram
Matrix-free design susie, susie_trendfilter, and standard single-panel susie_rss with reference genotypes X fit_design_dense, fit_design_csc, fit_design_trend Rust fit_operator with Design or TrendDesign

When L_greedy is enabled, workhorse._fit_greedy wraps _fit in an outer loop that incrementally increases LL and warm-starts each stage from the previous stage's posterior. Similarly, susie_auto runs staged calls to susie, while susie_ser invokes _native.ser_update directly for a single component.

Call paths

The trees below trace execution from the public entry points through the native solver (fitting routes determine which branch is taken).

susie_rss

susie_rss                                              rss.py
├─ argument checks; construct RSSControl
├─ R/X panel sequence → prepare_multipanel
│    panel fits → select initial LD panel by final ELBO → joint dynamic fit
├─ z, or z ← bhat/shat; missing z ← 0 with a warning
├─ reference X → _validated_design → _column_stats → _DesignData
│    bhat, shat and var_y → _design_correlation → dense R
├─ dense R → native validation and repair when required
├─ construct working statistics or retain the design
├─ enabled R_finite or R_mismatch → dynamic-model configuration
├─ _prepare_request → _FitRequest                       _request.py
└─ _fit                                                workhorse.py
   ├─ init_only → SusieInputs
   ├─ L_greedy → _fit_greedy → repeated _fit
   ├─ dynamic → fit_dynamic → _native.ser_update
   ├─ design  → _native.fit_design_dense | _native.fit_design_csc
   ├─ dense   → _native.fit
   ├─ credible_sets; marginal_pip; convergence_summary
   └─ SusieResult; optional refinement

susie

susie                                                  individual.py
├─ type checks; _validated_design
│    dense → F-ordered float64; sparse → canonical CSC copy
│    TrendDesign → retain implicit representation
├─ _column_stats → column means and centered sums of squares
├─ response, crossproducts, means and scales → _DesignData
├─ _prepare_request(XtX=None, ..., _design=design) → _FitRequest
└─ _fit                                                workhorse.py
   ├─ _native.fit_design_dense | fit_design_csc | fit_design_trend
   ├─ credible_sets (member correlations computed from X); marginal_pip
   └─ SusieResult with fitted values

In susie, column centering and standardization are applied implicitly inside the matrix-free design operator without forming XTX\mathbf{X}^T\mathbf{X}.

Inside the native fit

For a standard dense Gaussian fit, _native.fit executes the following sequence inside Rust:

_native.fit                                            prusie-python/src/lib.rs
├─ options::parse → FitOptions, FitControl
├─ check NumPy layout and borrow read-only views
├─ fit_controlled                                      prusie-core/src/ibss.rs
│  ├─ check sizes, scalars and scale factors
│  ├─ implicit scaling, or a materialized working matrix
│  ├─ nonnegative working diagonal → DenseGram
│  └─ fit_operator
│     ├─ initialize posterior; rebuild products for a warm start
│     ├─ each sweep: update components in order
│     │  ├─ single_effect (optim method → optimizer::minimize)
│     │  ├─ compute component KL term
│     │  └─ GramOperator::apply → store component product
│     ├─ expected_residual_sum_squares; ELBO; convergence diagnostics
│     ├─ stopping decision; residual-variance update if no stop
│     └─ trim components below prior_tol
└─ output::fit_result → NumPy arrays, warnings and diagnostics

The matrix-free design entry points construct a Design or TrendDesign operator and enter the same generic fit_operator loop. During the native call, the binding holds the Python GIL and borrows the input NumPy arrays read-only.

Refinement, continuation and warm starts

For supported materialized Gaussian fits, _prepare_request creates a PreparedData snapshot (storing read-only input views and a SHA-256 data_signature) whenever retain_data=True, track_fit, refine, or warm-start initialization is used. Both continue_fit and refine_fit invoke refinement._run, which calls _native.fit directly on the retained snapshot and recomputes PIPs and credible sets (see Convergence and refinement). On routes that do not use PreparedData (such as matrix-free designs, dynamic RSS except multi-panel, or mixture/NIG/slot priors), passing refine=True to the entry point runs workhorse._refine_by_refitting by repeating full _fit calls.

When a warm start is passed via model_init (or s_init), initial_options validates that alpha, mu, mu2, variant IDs, allele labels, scales, and null-column layout match the target inputs, and the Rust solver rebuilds all cached component products uℓ=Qmℓ\mathbf{u}_\ell = \mathbf{Q}\mathbf{m}_\ell prior to the first sweep.

Pseudocode

The pseudocode below summarizes input preparation and the native Gaussian IBSS solver (see Additional model options for mixture, NIG, and slot-prior extensions).

Preparation

After the entry point constructs working sufficient statistics (see From summaries to working sufficient statistics) or a design operator, request preparation and dispatch proceed as follows:

function _request._prepare_request(statistics or design, options):
    validate statistics, identifiers, metadata, priors and controls
    apply the requested MAF filter; add a null predictor if requested
    normalize prior weights; resolve the component count
    obtain predictor scales and the working crossresponse
    prepare a dense matrix with scale factors, a scaled matrix, or a design
    prepare initial variances, convergence controls and any warm start
    if supported and requested: retain read-only inputs and their signature
    return _FitRequest

function workhorse._fit(request):
    if init_only: return SusieInputs(request)
    if L_greedy is set: return _fit_greedy(request)
    output ← fit using the request's dense, design or dynamic route
    emit output warnings; warn if not converged
    sets ← credible_sets(output, correlation or design)
    pip ← marginal_pip(output)
    result ← SusieResult(output, pip, sets, diagnostics, …)
    if requested: apply the supported refinement route
    return result

IBSS

Using the working notation (Q,g,sy,n)(\mathbf{Q}, \mathbf{g}, s_y, n) from Data, notation and scale, let uℓ=Q(αℓ⊙μℓ)\mathbf{u}_\ell = \mathbf{Q}(\boldsymbol{\alpha}_\ell \odot \boldsymbol{\mu}_\ell) denote the cached product for component ℓ\ell, f=∑ℓuℓ\mathbf{f} = \sum_\ell \mathbf{u}_\ell their sum, and ε\varepsilon float64 machine epsilon:

function fit_operator(Q, g, s_y, n, options):
    α_ℓj ← 1/p;  μ_ℓj, μ2_ℓj ← 0
    V_ℓ, σ² ← prepared initial variances
    u_ℓ ← 0;  f ← 0
    if warm start:
        load posterior and any supplied variances; rebuild u_ℓ and f
    method ← estimate_prior_method if estimate_prior_variance else "none"
    log_prior_j ← log(π_j + √ε)
    for t = 1, …, max_iter:
        for ℓ = 1, …, L in order:
            f ← f − u_ℓ;  r ← g − f
            α_ℓ, μ_ℓ, μ2_ℓ, V_ℓ, lbf_variable_ℓ, lbf_ℓ ← single_effect(
                r, diag Q, σ², V_ℓ, log_prior, method)
            compute KL_ℓ from this SER posterior and its evidence
            u_ℓ ← Q(α_ℓ ⊙ μ_ℓ);  f ← f + u_ℓ
        if check_prior: check V against scores using the current σ²
        ER2 ← expected_residual_sum_squares(g, s_y, diag Q, α, μ, μ2, u)
        ELBO ← −(n/2) log(2πσ²) − ER2 / (2σ²) − Σ_ℓ KL_ℓ
        if ELBO is infinite: error
        if ELBO is NaN and any of α, μ, μ2, V is nonfinite: error
        decision ← stopping_decision(current sweep, changes, cycles, controls)
        apply alpha-cycle averaging when required; record diagnostics
        if decision ≠ continue: break
        if estimate_residual_variance:
            estimate ← ER2 / n;  reject a nonpositive or nonfinite estimate
            σ² ← clamp(estimate, residual lower bound, residual upper bound)
    for ℓ with V_ℓ < prior_tol:
        α_ℓ ← π;  μ_ℓ, μ2_ℓ, lbf_variable_ℓ, lbf_ℓ, KL_ℓ, V_ℓ ← 0
    return posterior, variances, ELBO history, f, diagnostics

See Iterations and finalization for how the trailing residual-variance update and post-loop trimming interact with fit.sigma2, fit.elbo, and fit.XtXr.

Single-effect regression

Each call to single_effect evaluates the Gaussian SER equations using smoothed log prior weights log⁡(πj+ε)\log(\pi_j + \sqrt{\varepsilon}) and a variance floor of ε\varepsilon in the log Bayes factor calculation:

function single_effect(r, diag Q, σ², V, log_prior, method):
    b̂_j ← (1/Q_jj) r_j;  s_j² ← σ²/Q_jj
    logBF_j(V) ← Gaussian log BF using max(s_j², ε)
                  (zero if b̂_j or s_j² is nonfinite)
    h(V) ← logsumexp(logBF_j(V) + log_prior_j)
    if method = "optim":
        candidate ← Brent search maximizing h(V) over log V ∈ [−30, 15]
        if h(candidate) ≥ h(V): V ← candidate
    if method ∈ {"optim", "simple"} and h(0) + check_null_threshold ≥ h(V): V ← 0
    lbf_variable_j ← logBF_j(V);  w_j ← lbf_variable_j + log_prior_j
    weights_j ← exp(w_j − max_k w_k);  total ← Σ_j weights_j
    α_j ← weights_j / total;  lbf ← max_j w_j + log(total)
    for each variant j:
        if r_j/Q_jj and s_j² are finite:
            v_j ← V s_j² / (V + s_j²)
            μ_j ← (v_j / s_j²) (r_j/Q_jj);  μ2_j ← v_j + μ_j²
        else: μ_j, μ2_j ← 0
    if method = "EM": V ← Σ_j α_j μ2_j
    reject nonfinite evidence or moments
    return α, μ, μ2, V, lbf_variable, lbf

Stopping rule

Given finite posterior arrays and a non-infinite ELBO, stopping_decision evaluates convergence at the end of sweep tt (see Stopping rules):

function stopping_decision(t, ELBO, ΔELBO, Δα, ΔPIP, cycle, controls):
    if ELBO is NaN and criterion = "joint": return numerical_failure
    if t < min_iter: return continue
    fallback ← ELBO is NaN and criterion = "elbo"
    pip_rule ← criterion = "pip" or (fallback and nan_elbo_pip)
    posterior_stable ← Δα < alpha_tol and ΔPIP < pip_tol
    objective_stable ← ELBO is finite and 0 ≤ ΔELBO < tol
    if pip_rule: satisfied ← Δα < tol and ΔPIP < tol
    else if criterion = "alpha_pip" or fallback: satisfied ← posterior_stable
    else if criterion = "joint": satisfied ← objective_stable and posterior_stable
    else: satisfied ← objective_stable
    if satisfied: return converged
    if cycle lag > 1 and (criterion ≠ "elbo" or fallback):
        if pip_rule: return converged
        return cycle_detected
    return continue

Boundaries and exceptions

Errors

Invalid array shapes, out-of-range parameters, incompatible option combinations, and native solver errors raise ValueError, while invalid argument types (such as non-boolean standardize or invalid slot_prior / convergence objects) raise TypeError. Non-fatal anomalies emit RuntimeWarning and append their messages to fit.warnings.

Input checks

Matrix-based entry points (susie_suff_stat and susie_rss) enforce matching dimensions, finite entries, and nonnegative diagonals (see Shapes and numerical checks and Priors and zero-information columns):

Condition Behavior
Asymmetric off-diagonal entries in working matrix Emits RuntimeWarning and averages (Q+QT)/2(\mathbf{Q} + \mathbf{Q}^T)/2
check_input=True Runs an eigendecomposition before standardization; rejects eigenvalues ≤−r_tol\le -\mathtt{r\_tol} and warns if the near-null projection of Xty exceeds machine epsilon
Missing (NaN) zz-scores in susie_rss Replaced with 0 with a RuntimeWarning; infinite zz-scores raise ValueError
Missing (NaN) Xty entries in susie_suff_stat Replaced with 0 with a RuntimeWarning when check_input=False; raises ValueError when check_input=True
bhat and shat inputs Requires finite bhat and positive non-NaN shat (+inf in shat yields z=0z = 0)
yty = 0 in Gaussian susie_suff_stat Requires Xty = 0, positive residual_variance, and estimate_residual_variance=False

Numerical safeguards

To prevent exponential overflow when normalizing posterior weights, prusie shifts log weights by their maximum before exponentiating. For example, with log weights (1000,999)(1000, 999), direct evaluation of e1000e^{1000} overflows float64, whereas the shifted log-sum-exp remains exact:

A 60-digit decimal calculation gives 1000.313261687518; the first normalized weight is 0.731058578630.

Additional numerical safeguards include flooring finite sampling variances at ε\varepsilon in log Bayes factor calculations, smoothing prior weights as log⁡(πj+ε)\log(\pi_j + \sqrt{\varepsilon}) (see Single-effect regression), clamping slot-prior log-odds to [−20,20][-20, 20], and verifying after each sweep (when check_prior=True) that no component variance VℓV_\ell exceeds 100max⁡j: Qjj>0gj2/(Qjjσ2)100 \max_{j:\,Q_{jj}>0} g_j^2 / (Q_{jj}\sigma^2).

Convergence outcomes

The native IBSS loop records one of four terminal stop_reason states in fit.convergence (for dynamic RSS routes, which report elbo_tolerance, alpha_pip_fixed_point, alpha_pip_cycle_<lag>, or max_iter, see Iterations and finalization):

stop_reason converged Description
criterion_satisfied True Active stopping criterion was met (including an accepted PIP-rule cycle)
iteration_limit False Reached max_iter sweeps without satisfying the stopping rule
cycle_detected False Detected an alpha/PIP cycle at lag >1>1 under "alpha_pip", "joint", or an explicit-tolerance ELBO fallback (see Stopping rule)
numerical_failure False Encountered a NaN ELBO in "joint" mode

Trimming and output shapes

At completion, components with Vℓ<prior_tolV_\ell < \mathtt{prior\_tol} have their V, mu, mu2, lbf_variable, lbf, and KL zeroed and their alpha row reset to π\boldsymbol{\pi} while keeping all LL rows in the output arrays (see Iterations and finalization). When a null column is present, alpha, mu, mu2, and lbf_variable have p+1p + 1 columns, whereas pip and coef always have length pp.

Native threading

n_threads (1 to 32, default 1) controls a private per-call Rayon thread pool without reading PRUSIE_NUM_THREADS or altering global Rayon/BLAS thread pools. When n_threads > 1:

  • Dense matrix–vector products with at least 10241024 output rows and 102421024^2 matrix entries partition output rows across worker threads while preserving sequential column accumulation within each row and sequential IBSS component updates.
  • RSS LD preparation (susie_rss with known n, var_y=None, overwrite_ld=False, p≥1024p \ge 1024, and a plain aligned C-contiguous float64 R on GNU/Linux x86-64 builds with standard IEEE-754 rounding/subnormal modes) parallelizes the exact-symmetry proof and fused validation/repair across threads, joining all workers before returning to Python (whereas overwrite_ld=True preparation is always single-threaded; see Optional LD workspace).

Numerical reproducibility

prusie performs all calculations in IEEE-754 float64. On GNU/Linux x86-64 builds, SER exponentials use glibc libmvec (AVX2/SSE2) when standard rounding and subnormal modes are active; building with --features portable-math disables libmvec and uses scalar exponentials everywhere. Because SIMD instructions and grouped operations reorder floating-point arithmetic relative to R, consistency is verified numerically against susieR 0.16.6 via DαD_\alpha (see Computational compatibility and Numerical accuracy).

Dense storage and matrix products

A dense p×pp \times p float64 matrix occupies 8p28p^2 bytes:

At p=5000p=5000, 8p2=200,000,0008p^2=200,000,000 bytes, or approximately 190.7 MiB.

By default, susie_rss preserves the caller's R matrix (or reuses it in place when overwrite_ld=True is specified) and applies sample-size and standardization scaling on the fly whenever the implicit-scaling bounds hold.

Validation passes

Each full pass over R reads 8p28p^2 bytes. prusie minimizes validation passes according to the input layout:

Path Condition Behavior
Fast symmetry proof x86-64; standard RSS; contiguous R with diagonal within 10−810^{-8} of 1, entries ≤1+10−8\le 1 + 10^{-8} in magnitude, and exact symmetry Single vectorized pass proves validity and skips general traversal
Fused validation and repair overwrite_ld=False, known n, var_y=None, plain aligned C-contiguous float64 R Single pass validates entries and populates a repair buffer (freed immediately if R is symmetric)
Separate validation and repair All other matrix inputs Validates in one tiled pass, then allocates and repairs only if asymmetry is detected

Dense products

The column-major product kernel skips zero coefficients, accumulates four nonzero columns per inner loop iteration (using AVX2 on x86-64 when available), combines identical or sign-reversed columns via exact signed-column classes, and partitions rows across threads when native threading is enabled.

Single-effect regression kernels

During prior-variance optimization, the SER objective kernel combines four optimizations:

Optimization Activation condition Fallback
Shared sampling-variance group terms At most 16 distinct floored sampling variances sj2s_j^2 Per-variant log-determinant and precision evaluation
AVX2 4-wide log-weight evaluation libmvec available, AVX2 CPU, uniform prior weights, ≤4\le 4 variance groups Scalar fill using the shared group terms
Vectorized exponentials (libmvec) GNU/Linux x86-64, standard IEEE-754 control modes, portable-math disabled Standard scalar exp
Balanced pairwise-tree weight sum Always active in the prior-variance search objective —

Credible-set purity

When evaluating credible-set purity from a dense matrix via _native.cs_pairwise_abs with min_abs_corr set and median_abs_corr=None, the scan exits immediately at the first member pair whose absolute correlation falls below min_abs_corr (purity_evaluation="threshold_short_circuit"), avoiding the O(m2)\mathcal{O}(m^2) pairwise array allocation for rejected candidate sets.

Individual-level designs and imports

For individual-level and trend-filtering fits, prusie applies Qv=XT(Xv)\mathbf{Q}\mathbf{v} = \mathbf{X}^T(\mathbf{X}\mathbf{v}) directly through matrix-free Design operators:

Design representation Work per product Workspace
Dense X O(np)\mathcal{O}(np) O(n+p)\mathcal{O}(n + p)
Sparse CSC X O(nnz+n+p)\mathcal{O}(\mathrm{nnz} + n + p) O(n+p)\mathcal{O}(n + p)
susie_trendfilter (order kk) O((k+1)n)\mathcal{O}((k + 1)n) via repeated cumulative sums O(n)\mathcal{O}(n)

At import time, import prusie loads only the lightweight core fitting interface; optional submodules (analysis, comparison, ld, plots, report, viz) and their SciPy/Matplotlib dependencies are loaded lazily via package __getattr__ only when accessed.

Reference source mapping

The table below maps prusie's core Python (src/prusie/) and Rust (rust/prusie-core/src/) modules to their corresponding routines in susieR 0.16.6 (commit 8e56a8e038e989856d106d9ca5175cc664fea9d2):

prusie module / routine susieR 0.16.6 source file / function
individual.py: susie; suff_stat.py: susie_suff_stat (susie_ss); rss.py: susie_rss; rss_lambda.py: susie_rss_lambda susie, susie_ss, susie_rss, susie_rss_lambda in R/susie.R
Entry-point preparation and _request.py: _prepare_request individual_data_constructor, sufficient_stats_constructor, summary_stats_constructor, rss_lambda_constructor in R/susie_constructors.R
workhorse.py: _fit; ibss.rs: fit_operator susie_workhorse in R/susie_workhorse.R; ibss_fit in R/iterative_bayesian_stepwise_selection.R
Component updates in ibss.rs; ser.rs: single_effect; optimizer.rs: minimize single_effect_update, single_effect_regression, optimize_prior_variance in R/single_effect_regression.R
residual.rs: expected_residual_sum_squares; ELBO evaluation in ibss.rs get_ER2.ss, Eloglik.ss in R/sufficient_stats_methods.R; get_objective.default in R/model_methods.R
diagnostics.rs: stopping_decision, detect_cycle check_convergence.default in R/model_methods.R; check_alpha_pip_cycle_convergence in R/susie_utils.R
Residual-variance updates and component trimming in ibss.rs update_model_variance.default, trim_null_effects.default in R/model_methods.R

The 1D Brent optimizer in optimizer.rs is adapted from Brent_fmin in R's src/library/stats/src/optimize.c (GPL-2.0-or-later); full license attributions are provided in THIRD_PARTY_NOTICES.md.