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: object

Hub-and-spoke multi-modal GEDI, mirroring multigedi R’s CreateMultiGEDIObject.

__init__(K=10, mode='Bsphere', seed=None, num_threads=0, verbose=1)[source]
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-like of str, 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.multigedi validates it from obs_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, si and si_0 are initialized to this value and later si updates are disabled. None and NaN leave si optimized; 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:

None

:param : :type oi_shrinkage: float, default: 1.0 :param oi_shrinkage: R-compatible per-modality regularization strengths. Values must be

finite positive real scalars. A_shrinkage and Rk_shrinkage are recorded but inactive while the Python model has no C or H prior.

Parameters:
  • o_shrinkage (float, default 1) – R-compatible per-modality regularization strengths. Values must be finite positive real scalars. A_shrinkage and Rk_shrinkage are recorded but inactive while the Python model has no C or H prior.

  • si_shrinkage (float, default 1) – R-compatible per-modality regularization strengths. Values must be finite positive real scalars. A_shrinkage and Rk_shrinkage are recorded but inactive while the Python model has no C or H prior.

  • init_state (dict, optional) – Pre-initialized parameters (e.g. R’s iter_0) to seed the spoke, skipping the rSVD initializer.

  • forward_inputs (bool, default True) – Build and hand the per-sample raw inputs to the CPU spoke. Required for any CPU optimize()/train() — the solver reads them. Set False only on the GPU path, where run_gpu_pipeline uploads its own copy and the CPU solver never runs; skipping then avoids a wasted densification/copy. Independent of init_state: seeding with init_state and then optimizing on CPU needs the inputs.

setup()[source]

Wire hub to spokes by building the global sample map.

Must be called before initialize() or train(). Automatically called by train() if not already done.

Return type:

None

initialize()[source]

Run randomized-SVD initialization on every spoke.

Calls setup() first if not already done. Skip this if every modality was added with init_state= (pre-seeded).

Return type:

None

train(iterations=30, track_interval=1)[source]

Initialize spokes (rSVD) then run block-coordinate-descent.

Parameters:
  • iterations (int, default: 30) – Number of optimization iterations.

  • track_interval (int, default: 1) – Record sigma² and dZ every this many iterations.

Return type:

None

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).

Parameters:
  • iterations (int, default: 30) – Number of optimization iterations.

  • track_interval (int, default: 1) – Record sigma² and dZ every this many iterations.

Return type:

None

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_D(modality)[source]

Scaling factors for a modality.

Return type:

np.ndarray, shape (K,)

get_o(modality)[source]

Global gene offsets for a modality.

Return type:

np.ndarray, shape (J,)

get_sigma2(modality)[source]

Estimated noise variance for a modality.

Return type:

float

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:

list of np.ndarray, each shape (K, N_i)

get_Qi(modality)[source]

Per-sample feature loading deviations for a modality.

Return type:

list[ndarray]

get_oi(modality)[source]

Per-sample feature offsets for a modality.

Return type:

list[ndarray]

get_si(modality)[source]

Per-sample cell offsets for a modality.

Return type:

list[ndarray]

get_shared_Bi()[source]

Hub-level shared cell loadings (consensus across modalities).

Returns:

One matrix per global sample, in global_sample_names order. Use np.hstack(model.get_shared_Bi()) to get (K × N_total).

Return type:

list of np.ndarray, each shape (K, N_i)

get_tracking(modality)[source]

Optimization tracking traces for a modality.

Returns:

"sigma2" — noise variance recorded every track_interval iterations. "dZ" — Frobenius change in Z recorded every track_interval iterations.

Return type:

dict with keys

get_shrinkages(modality)[source]

Return the validated per-modality shrinkage request.

Return type:

dict[str, float]

get_hyperparams(modality)[source]

Return the effective initial prior variances used by the solvers.

Return type:

dict[str, float | list[float]]

get_num_modalities()[source]

Number of registered modalities.

Return type:

int

property modality_names: list[str]

Names of all registered modalities, in registration order.

property global_sample_names: list[str]

Global sample order (union across all modalities, insertion order).

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: object

GEDI 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 in adata.obs containing batch/sample labels.

  • n_latent (int, default: 10) – Number of latent factors (K). Default: 10.

  • layer (str | None, default: None) – Layer to use instead of adata.X. If None, uses adata.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 with layer, 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.obs containing sample/batch labels

n_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:

None

optimize(iterations=100, track_interval=5)[source]

Run optimization iterations.

Parameters:
  • iterations (int, default: 100) – Number of optimization iterations.

  • track_interval (int, default: 5) – Interval for tracking convergence metrics.

Return type:

None

train(max_iterations=100, track_interval=5)[source]

Train the GEDI model (initialize + optimize).

Parameters:
  • max_iterations (int, default: 100) – Maximum number of optimization iterations.

  • track_interval (int, default: 5) – Interval for tracking convergence metrics.

Return type:

None

property is_trained: bool

Whether the model has been trained.

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_sigma2()[source]

Get estimated noise variance.

Returns:

Noise variance (sigma^2).

Return type:

float

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:

list of np.ndarray

get_latent_representation()[source]

Get cell embeddings in latent space (DB projection).

Returns:

Cell embeddings of shape (n_cells, n_latent).

Return type:

np.ndarray

get_tracking()[source]

Get tracking data from optimization.

Returns:

Dictionary with tracking data (sigma2, etc.).

Return type:

dict

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