Core¶
The core module contains the single-modal GEDIModel, the hub-and-spoke
MultiGEDIModel, and global settings.
MultiGEDIModel¶
- class multigedi.MultiGEDIModel(K=10, mode='Bsphere', seed=None, num_threads=0, verbose=1)[source]¶
Bases:
objectHub-and-spoke multi-modal GEDI, mirroring multigedi R’s CreateMultiGEDIObject.
- add_modality(name, data, sample_vec, obs_type='M', orthoZ=True, adjustD=True, is_si_fixed=False, fixed_si=None, Z_shrinkage=1.0, A_shrinkage=1.0, Qi_shrinkage=1.0, Rk_shrinkage=1.0, oi_shrinkage=1.0, o_shrinkage=1.0, si_shrinkage=1.0, init_state=None, forward_inputs=True)[source]¶
Register a modality.
- Parameters:
name (
str) – Unique modality label (e.g., ‘rna’).data (
numpy / scipy-sparse / tuple) – For obs_type=’M’ — one (J × N) matrix (sparse preferred). For obs_type=’M_list’ — a 2-tuple/list of (J × N) matrices. For obs_type=’X’ — one (J × N) dense matrix of {0,1,NaN}.sample_vec (
array-likeofstr,length N) – Per-cell sample label. Whole sample blocks may be absent from a modality. When a sample is present in multiple modalities, the caller must provide the same cells in the same within-sample order; this low-level matrix API has no cell IDs with which to validate that contract.tl.multigedivalidates it fromobs_names.obs_type (
{'M','M_list','X'})orthoZ (
see R multigedi.)adjustD (
see R multigedi.)is_si_fixed (
see R multigedi.)fixed_si (
float, optional) – R-compatible scalar fixed cell effect. When supplied,siandsi_0are initialized to this value and latersiupdates are disabled.NoneandNaNleavesioptimized; infinities are rejected.Z_shrinkage (
float, default:1.0)A_shrinkage (
float, default:1.0)Qi_shrinkage (
float, default:1.0)Rk_shrinkage (
float, default:1.0)
- Return type:
:param : :type oi_shrinkage:
float, default:1.0:param oi_shrinkage: R-compatible per-modality regularization strengths. Values must befinite positive real scalars.
A_shrinkageandRk_shrinkageare recorded but inactive while the Python model has noCorHprior.- Parameters:
o_shrinkage (
float, default1) – R-compatible per-modality regularization strengths. Values must be finite positive real scalars.A_shrinkageandRk_shrinkageare recorded but inactive while the Python model has noCorHprior.si_shrinkage (
float, default1) – R-compatible per-modality regularization strengths. Values must be finite positive real scalars.A_shrinkageandRk_shrinkageare recorded but inactive while the Python model has noCorHprior.init_state (
dict, optional) – Pre-initialized parameters (e.g. R’s iter_0) to seed the spoke, skipping the rSVD initializer.forward_inputs (
bool, defaultTrue) – Build and hand the per-sample raw inputs to the CPU spoke. Required for any CPUoptimize()/train()— the solver reads them. SetFalseonly on the GPU path, whererun_gpu_pipelineuploads its own copy and the CPU solver never runs; skipping then avoids a wasted densification/copy. Independent ofinit_state: seeding withinit_stateand then optimizing on CPU needs the inputs.
- setup()[source]¶
Wire hub to spokes by building the global sample map.
Must be called before
initialize()ortrain(). Automatically called bytrain()if not already done.- Return type:
- initialize()[source]¶
Run randomized-SVD initialization on every spoke.
Calls
setup()first if not already done. Skip this if every modality was added withinit_state=(pre-seeded).- Return type:
- train(iterations=30, track_interval=1)[source]¶
Initialize spokes (rSVD) then run block-coordinate-descent.
- optimize(iterations=30, track_interval=1)[source]¶
Run the solver without re-running rSVD initialization.
Use this after
add_modality(init_state=...)has seeded every spoke with pre-initialized params (e.g., from an R reference snapshot).
- get_Z(modality)[source]¶
Shared metagene matrix for a modality.
- Returns:
Gene loadings — J features × K latent factors.
- Return type:
np.ndarray,shape (J,K)
- get_Bi(modality)[source]¶
Per-sample cell loading matrices for a modality.
- Returns:
One matrix per sample, in the order of
modality_sample_names.- Return type:
listofnp.ndarray,each shape (K,N_i)
Hub-level shared cell loadings (consensus across modalities).
- Returns:
One matrix per global sample, in
global_sample_namesorder. Usenp.hstack(model.get_shared_Bi())to get (K × N_total).- Return type:
listofnp.ndarray,each shape (K,N_i)
- get_tracking(modality)[source]¶
Optimization tracking traces for a modality.
- Returns:
"sigma2"— noise variance recorded everytrack_intervaliterations."dZ"— Frobenius change in Z recorded everytrack_intervaliterations.- Return type:
dict with keys
MultiGEDIModel is the low-level builder used by
multigedi.tools.multigedi(). Its native matrices are features by cells;
most scverse users should prefer the high-level MuData function, which handles
AnnData orientation and result storage.
GEDIModel¶
- class multigedi.GEDIModel(adata, batch_key, *, n_latent=10, layer=None, layer2=None, mode='Bsphere', ortho_Z=True, C=None, H=None, random_state=None, verbose=None, n_jobs=None)[source]¶
Bases:
objectGEDI model for single-cell RNA-seq data integration.
Gene Expression Decomposition for Integration (GEDI) learns shared metagenes and sample-specific factors for batch effect correction.
- Parameters:
adata (
AnnData) – Annotated data matrix with cells as observations (n_cells x n_genes).batch_key (
str) – Key inadata.obscontaining batch/sample labels.n_latent (
int, default:10) – Number of latent factors (K). Default: 10.layer (
str|None, default:None) – Layer to use instead ofadata.X. If None, usesadata.X. For paired data (e.g., CITE-seq), this is the first count matrix.layer2 (
str|None, default:None) – Second layer for paired count data (M_paired mode). When specified along withlayer, GEDI models the log-ratio: Yi = log((M1+1)/(M2+1)). This is useful for CITE-seq ADT/RNA ratios or similar paired assays.mode (
Literal['Bl2','Bsphere'], default:'Bsphere') – Normalization mode for B matrices: “Bsphere” (recommended) or “Bl2”.ortho_Z (
bool, default:True) – Whether to orthogonalize Z matrix. Default: True.C (
ndarray[tuple[Any,...],dtype[TypeVar(_ScalarT, bound=generic)]] |None, default:None) – Gene × pathway prior matrix for pathway analysis. Optional.H (
ndarray[tuple[Any,...],dtype[TypeVar(_ScalarT, bound=generic)]] |None, default:None) – Covariate × sample prior matrix. Optional.random_state (
int|None, default:None) – Random seed for reproducibility.verbose (
int|None, default:None) – Verbosity level (0-3). If None, uses global settings.n_jobs (
int|None, default:None) – Number of parallel jobs. -1 uses all available cores.
- is_trained¶
Whether the model has been trained.
- n_iter¶
Number of iterations completed.
Examples
Standard usage:
>>> import multigedi as gd >>> import scanpy as sc >>> adata = sc.read_h5ad("data.h5ad") >>> model = gd.GEDIModel(adata, batch_key="sample", n_latent=10) >>> model.train(max_iterations=100) >>> Z = model.get_Z() >>> embeddings = model.get_latent_representation()
Paired data mode (e.g., CITE-seq):
>>> model = gd.GEDIModel( ... adata, batch_key="sample", n_latent=10, ... layer="adt", layer2="rna" ... ) >>> model.train(max_iterations=100)
The GEDIModel class provides fine-grained control over the GEDI algorithm.
Basic Usage
import multigedi as gd # Create model model = gd.GEDIModel( adata, batch_key="sample", n_latent=10, ) # Train model.train(max_iterations=100) # Get results Z = model.get_Z() embeddings = model.get_latent_representation()
Step-by-Step Training
For more control, initialize and optimize separately:
model = gd.GEDIModel(adata, batch_key="sample", n_latent=10) # Initialize parameters model.initialize() # Run optimization in batches for i in range(10): model.optimize(iterations=10) print(f"sigma2: {model.get_sigma2()}")
Parameters
Parameter
Type
Description
adata
AnnData
Annotated data matrix with cells as observations
batch_key
str
Column in
adata.obscontaining sample/batch labelsn_latent
int
Number of latent factors (default: 10)
layer
str | None
Layer to use (default: None uses
adata.X)mode
str
Constraint mode: “Bsphere” or “Bl2” (default: “Bsphere”)
ortho_Z
bool
Orthogonalize Z matrix (default: True)
C
NDArray | None
Gene-pathway prior matrix (default: None)
H
NDArray | None
Covariate-sample prior matrix (default: None)
random_state
int | None
Random seed for reproducibility
verbose
int | None
Verbosity level (0-3)
n_jobs
int | None
Number of threads (-1 for all)
Attributes
Attribute
Description
is_trained
Whether the model has been trained
n_iter
Number of optimization iterations completed
Methods
Method
Description
initialize()
Initialize model parameters using randomized SVD
optimize(iterations, track_interval)
Run optimization iterations
train(max_iterations, track_interval)
Full training (initialize + optimize)
get_Z()
Get shared metagenes (n_genes × n_latent)
get_D()
Get scaling factors (n_latent,)
get_sigma2()
Get noise variance
get_Bi()
Get sample-specific cell factors
get_latent_representation()
Get DB projection (n_cells × n_latent)
get_tracking()
Get convergence tracking data
- __init__(adata, batch_key, *, n_latent=10, layer=None, layer2=None, mode='Bsphere', ortho_Z=True, C=None, H=None, random_state=None, verbose=None, n_jobs=None)[source]¶
- initialize()[source]¶
Initialize model parameters using randomized SVD.
This is called automatically by
train(), but can be called separately for more control.- Return type:
- get_Z()[source]¶
Get shared metagenes matrix.
- Returns:
Shared metagenes of shape (n_genes, n_latent).
- Return type:
np.ndarray
- get_D()[source]¶
Get scaling factors.
- Returns:
Scaling factors of shape (n_latent,).
- Return type:
np.ndarray
- get_Bi()[source]¶
Get sample-specific cell factor matrices.
- Returns:
List of Bi matrices, each of shape (n_latent, n_cells_in_sample).
- Return type:
listofnp.ndarray
Settings¶
- multigedi.settings¶
Configuration for multigedi.
- multigedi.verbosity¶
Verbosity level: 0 (silent), 1 (normal), 2 (verbose), 3 (debug).
- multigedi.n_jobs¶
Number of parallel jobs. -1 means all available cores.
- multigedi.random_state¶
Default random state for reproducibility.
Global configuration settings for multigedi.
import multigedi as gd
# Set verbosity (0=silent, 1=progress, 2=detailed, 3=debug)
gd.settings.verbosity = 1
# Set number of threads (-1 for all available)
gd.settings.n_jobs = 4
# Set random seed for reproducibility
gd.settings.random_state = 42
Available Settings
Setting |
Default |
Description |
|---|---|---|
verbosity |
1 |
Verbosity level (0-3) |
n_jobs |
-1 |
Number of threads for parallel operations |
random_state |
0 |
Default random seed |