scientific-skills/pydeseq2/references/api_reference.md
This document provides comprehensive API reference for PyDESeq2 classes, methods, and utilities.
The main class for differential expression analysis that handles data processing from normalization through log-fold change fitting.
Purpose: Implements dispersion and log fold-change (LFC) estimation for RNA-seq count data.
Initialization Parameters:
counts: pandas DataFrame of shape (samples × genes) containing non-negative integer read countsmetadata: pandas DataFrame of shape (samples × variables) with sample annotationsdesign: str, Wilkinson formula specifying the statistical model (e.g., "~condition", "~group + condition")refit_cooks: bool, whether to refit parameters after removing Cook's distance outliers (default: True)n_cpus: int, number of CPUs to use for parallel processing (optional)quiet: bool, suppress progress messages (default: False)Key Methods:
deseq2()Run the complete DESeq2 pipeline for normalization and dispersion/LFC fitting.
Steps performed:
refit_cooks=TrueReturns: None (modifies object in-place)
to_picklable_anndata()Convert the DeseqDataSet to an AnnData object that can be saved with pickle.
Returns: AnnData object with:
X: count data matrixobs: sample-level metadata (1D)var: gene-level metadata (1D)varm: gene-level multi-dimensional data (e.g., LFC estimates)Usage:
import pickle
with open("result_adata.pkl", "wb") as f:
pickle.dump(dds.to_picklable_anndata(), f)
Attributes (after running deseq2()):
layers: dict containing various matrices (normalized counts, etc.)varm: dict containing gene-level results (log fold changes, dispersions, etc.)obsm: dict containing sample-level informationuns: dict containing global parametersClass for performing statistical tests and computing p-values for differential expression.
Purpose: Facilitates PyDESeq2 statistical tests using Wald tests and optional LFC shrinkage.
Initialization Parameters:
dds: DeseqDataSet object that has been processed with deseq2()contrast: list or None, specifies the contrast for testing
[variable, test_level, reference_level]["condition", "treated", "control"] tests treated vs controlalpha: float, significance threshold for independent filtering (default: 0.05)cooks_filter: bool, whether to filter outliers based on Cook's distance (default: True)independent_filter: bool, whether to perform independent filtering (default: True)n_cpus: int, number of CPUs for parallel processing (optional)quiet: bool, suppress progress messages (default: False)Key Methods:
summary()Run Wald tests and compute p-values and adjusted p-values.
Steps performed:
Returns: None (results stored in results_df attribute)
Result DataFrame columns:
baseMean: mean normalized count across all sampleslog2FoldChange: log2 fold change between conditionslfcSE: standard error of the log2 fold changestat: Wald test statisticpvalue: raw p-valuepadj: adjusted p-value (FDR-corrected)lfc_shrink(coeff=None)Apply shrinkage to log fold changes using the apeGLM method.
Purpose: Reduces noise in LFC estimates for better visualization and ranking, especially for genes with low counts or high variability.
Parameters:
coeff: str or None, coefficient name to shrink (if None, uses the coefficient from the contrast)Important: Shrinkage is applied only for visualization/ranking purposes. The statistical test results (p-values, adjusted p-values) remain unchanged.
Returns: None (updates results_df with shrunk LFCs)
Attributes:
results_df: pandas DataFrame containing test results (available after summary())pydeseq2.utils.load_example_data(modality="single-factor")Load synthetic example datasets for testing and tutorials.
Parameters:
modality: str, either "single-factor" or "multi-factor"Returns: tuple of (counts_df, metadata_df)
counts_df: pandas DataFrame with synthetic count datametadata_df: pandas DataFrame with sample annotationsThe pydeseq2.preprocessing module provides utilities for data preparation.
Common operations:
Abstract base class defining the interface for DESeq2-related inference methods.
Default implementation of inference methods using scipy, sklearn, and numpy.
Purpose: Provides the mathematical implementations for:
counts_df = counts_df.Tfrom pydeseq2.dds import DeseqDataSet
from pydeseq2.ds import DeseqStats
# 1. Initialize dataset
dds = DeseqDataSet(
counts=counts_df,
metadata=metadata,
design="~condition",
refit_cooks=True
)
# 2. Fit dispersions and LFCs
dds.deseq2()
# 3. Perform statistical testing
ds = DeseqStats(
dds,
contrast=["condition", "treated", "control"],
alpha=0.05
)
ds.summary()
# 4. Optional: Shrink LFCs for visualization
ds.lfc_shrink()
# 5. Access results
results = ds.results_df
PyDESeq2 aims to match the default settings of DESeq2 v1.34.0. Some differences may exist as it is a from-scratch reimplementation in Python.
Tested with: