susieR: Sum of Single Effects (SuSiE) Model

repository·master·Indexed 42 days ago

https://github.com/stephenslab/susier

An R package implementing the Sum of Single Effects (SuSiE) model for sparse multiple regression and variable selection. It is specifically designed for settings with highly correlated predictors and sparse true effects, such as genetic fine-mapping. The package uses Iterative Bayesian Step-wise Selection (IBSS) to produce Credible Sets (CSs) and supports individual-level data, sufficient statistics, and regression summary statistics. It can also be used in Python via rpy2.

Tokens
3.7K
Snippets
10
Records
18
Agent score
55%

What's inside susieR

  1. What is the Sum of Single Effects (SuSiE) model?

    master

    The susieR package implements the "Sum of Single Effects" (SuSiE) model for variable selection in multiple regression ($y=Xb+e$).

    Key Characteristics:

    • Use Case: Particularly well-suited for settings where $X$ variables are highly correlated and the true effects are highly sparse (e.g., <20 non-zero effects).
    • Fitting Procedure: Uses "Iterative Bayesian Step-wise Selection", which is a Bayesian modification of simple forward selection.
    • Output: Produces "Credible Sets" (CSs). A Credible Set is a group of highly correlated variables that have a high probability of containing at least one variable with a non-zero effect, while remaining as small as possible.
  2. Core objects in susieR 2.0

    master

    The architecture is built around three primary object types:

    Data Object

    • Purpose: Holds processed, algorithm-ready input data.
    • S3 Classes: individual, ss, or rss_lambda (this determines which backend methods are used).
    • Properties: Immutable. Contains input matrices (e.g., X/y, XtX/Xty/yty, or z/R), metadata (n, p), and scaling attributes.

    Params Object

    • Purpose: Holds all algorithm parameters and user settings.
    • Properties: Immutable. Contains settings for L (number of effects), max_iter, tol, convergence_method, estimate_prior_method, estimate_residual_method, and model options like unmappable_effects, refine, standardize, and intercept.
    • Note: For rss_lambda data, certain parameters are fixed (e.g., unmappable_effects = "none", standardize = FALSE).

    Model Object

    • Purpose: Holds the fitted state, results, and algorithm outputs.
    • Properties: Mutable. Updated during the fitting process. Contains model matrices (alpha, mu, mu2, V, sigma2), fitted values, algorithm outputs (ELBO, niter, converged), and final results (credible sets, PIPs, intercept, z-scores).
  3. How susieR 2.0 architecture works

    master

    susieR 2.0 uses a unified architecture to support multiple data types (individual-level, sufficient statistics, and regression summary statistics) through a single algorithmic pipeline. It relies on S3 method dispatch to route different data representations to the appropriate backend computations.

    The workflow follows this pattern:

    1. Interface: You call high-level functions like susie(), susie_ss(), or susie_rss().
    2. Constructor: These functions call constructors that validate your inputs and create immutable Data and Params objects.
    3. Workhorse: The validated objects are passed to a workhorse function that orchestrates the main SuSiE algorithm.
    4. IBSS Core: The core Iterative Bayesian Stepwise Selection (IBSS) algorithm executes the fitting process.
    5. Backend Methods: S3 dispatch ensures the correct mathematical operations are performed based on whether the data is individual, ss, or rss_lambda type.
  4. Install susieR from CRAN or GitHub

    master

    You can install the stable version of susieR from CRAN or the latest development version directly from GitHub using the remotes package.

    # Install from CRAN
    install.packages("susieR")
    
    # Install development version from GitHub
    # install.packages("remotes")
    remotes::install_github("stephenslab/susieR")
  5. Understand the SuSiE vs SuSiE-SS Small-Sample Overfitting Problem

    master

    In small-sample scenarios where the number of variants $p$ is much larger than the sample size $n$ ($n \ll p$), standard SuSiE can overfit by underestimating the residual variance $\sigma^2$. This leads to:

    • Inflated Bayes factors.
    • Spurious credible sets (CS).

    SuSiE-SS (Servin-Stephens) addresses this by integrating out $\sigma^2$ analytically using a Normal-Inverse-Gamma (NIG) conjugate prior. This produces $t$-distributed marginals that are more conservative and better calibrated for small samples.

  6. Use stochastic LD sketches in susie_rss()

    master

    When individual-level genotype data is unavailable, susie_rss() can use a stochastic LD sketch to approximate the LD matrix. This is useful when you only have summary statistics or want to avoid the computational cost of the full LD matrix.

    To use a stochastic sketch:

    1. Generate a sketch matrix $U = X_{\text{std}}^ op W$, where $W \sim N(0, I_B / n)$ and $B$ is the sketch size.
    2. Pass the transpose of this sketch, X = t(U), to the susie_rss() function. The function treats this $B \times p$ matrix as a genotype-like input that approximates the LD structure.

    Important: Variance Inflation Correction Using a noisy sketch $\hat{R}$ can inflate the variance of the Single-Effect Regression (SER) residuals, leading to an elevated False Discovery Rate (FDR). To correct this, set the stochastic_ld_sample parameter to the sketch size $B$. This activates a dynamic variance inflation correction that accounts for the noise in the sketch at every iteration.

    # Example: Using a stochastic sketch with correction
    # Assuming U is your pre-computed sketch matrix (p x B)
    # and B is the sketch size
    
    susie_rss(
      z = z_scores,
      n = n_samples,
      L = L_signals,
      X = t(U),                # Pass the sketch as X
      stochastic_ld_sample = B  # Activate the dynamic correction
    )
  7. Run the Small-Sample Benchmark Simulation

    master

    To execute the benchmark comparing standard SuSiE (Gaussian) against SuSiE-SS (Servin-Stephens), use jupyter nbconvert from the inst/notebooks/ directory. The simulation is designed to be incremental and uses a checkpoint system to avoid redundant computations.

    Execution Command

    jupyter nbconvert --to notebook --execute \
      --ExecutePreprocessor.timeout=0 \
      --output small_sample_benchmark_executed.ipynb \
      small_sample_benchmark.ipynb

    Key Behaviors

    • Timeout: The --ExecutePreprocessor.timeout=0 flag is required because the simulation can take several hours.
    • Incremental Runs: If you increase n_rep in the notebook configuration, the system will only compute the new replicates and append them to the existing results in benchmark_results/.
    • Starting Fresh: To invalidate existing results (e.g., after changing data or noise calibration), delete the benchmark_results/_meta.rds file. The system uses an MD5 hash of all simulation parameters to detect configuration changes and will automatically clear old results if a mismatch is detected.
  8. Use susieR in Python via rpy2

    master

    To use the susieR R package within a Python environment, you must use the rpy2 library. This requires importing the R package using importr and setting up conversion rules (using numpy2ri.converter and ro.default_converter) to ensure seamless data exchange between NumPy arrays and R objects. Most calls to susieR functions should be wrapped in a with conversion_rules.context(): block to handle type conversions correctly.

    import numpy as np
    import pandas as pd
    import rpy2.robjects as ro
    from rpy2.robjects.packages import importr, data
    from rpy2.robjects import numpy2ri
    
    # Import the R package
    susie = importr('susieR')
    
    # Setup conversion rules for NumPy/R interoperability
    conversion_rules = numpy2ri.converter + ro.default_converter
    
    with conversion_rules.context():
        # Your susieR calls go here
        pass
  9. Execute the stochastic LD benchmark notebook

    master

    The stochastic LD benchmark can be run via jupyter nbconvert. Because the output of cat() is captured within the notebook and not displayed in the terminal during execution, you should monitor progress using a separate terminal window.

    1. Run the notebook: Use nbconvert with an increased timeout to ensure long-running simulations complete.
    2. Monitor progress: Use tail -f on the log file specified in the notebook (e.g., stochastic_ld_benchmark.log).
    # Terminal 1: run the notebook
    jupyter nbconvert --execute --to notebook \
        --output stochastic_ld_benchmark_executed.ipynb \
        --ExecutePreprocessor.timeout=7200 \
        stochastic_ld_benchmark.ipynb
    
    # Terminal 2: monitor progress
    tail -f stochastic_ld_benchmark.log
  10. Extract results from a fitted model

    master

    Once a model is fitted, use the exported accessor functions in susie_get_functions.R to retrieve specific results.

    Common accessors include:

    • susie_get_cs(): Extract credible sets.
    • susie_get_pip(): Extract posterior inclusion probabilities (PIPs).
    • Other accessors are available for various model components.
  11. Configure the Small-Sample Benchmark Simulation

    master

    The simulation parameters are defined in the notebook's configuration section. Key parameters include:

    • n_rep: Number of replicates per setting (e.g., 200).
    • L: Number of effects to estimate.
    • N_vals: Vector of subsample sizes (e.g., c(30, 50, 70, 100)).
    • h2_sparse: Target sparse heritability values (e.g., c(0.25, 0.50, 0.75)).
    • L_causal: Number of causal variants to simulate (e.g., c(1, 2, 3, 4, 5)).

    Parallelization Note: To avoid fork + BLAS crashes, use plan(multisession, workers = ncores) from the future package.

    # --- Configuration ---
    ncores    <- max(1, parallelly::availableCores() - 2)
    n_rep     <- 200       # replicates per setting
    L         <- 10
    N_vals    <- c(30, 50, 70, 100)
    h2_sparse <- c(0.25, 0.50, 0.75)
    L_causal  <- c(1, 2, 3, 4, 5)
    
    # Use multisession (PSOCK) to avoid fork + BLAS crashes
    plan(multisession, workers = ncores)
  12. Supported data types in susieR

    master

    susieR supports three main data representations, each mapped to a specific S3 class for backend dispatch:

    S3 ClassData DescriptionTypical Inputs
    individualIndividual-level dataX (design matrix) and y (response)
    ssSufficient statisticsXtX, Xty, yty, and n
    rss_lambdaRSS with regularized R matrixz, R, and lambda > 0