API Reference
High-level inference wrappers
The primary entry point for all runs — unsupervised and semi-supervised.
.. py:module:: pyroNMF.run_inference
.. py:function:: prepare_tensors(data, layer=None, uncertainty=’auto’, scale=None, device=None, spatial=False) :module: pyroNMF.run_inference
Prepare and move tensors to the specified device.
Parameters:
data: AnnData object containing the data
layer: Layer key to use instead of data.X (optional)
uncertainty: Pre-computed uncertainty tensor (optional)
scale: Scale factor (optional; defaults to 2*std of data)
device: Target device (‘cpu’, ‘cuda’, ‘mps’, or None for auto-detection)
spatial: Whether to extract spatial coordinates from data.obsm[‘spatial’]
Returns:
D: Data tensor
U: Uncertainty tensor
scale: Scale factor tensor
device: Selected device
coords: Spatial coordinates array if spatial=True, else None
.. py:function:: setup_model_and_optimizer(D, num_patterns, scale=1, NB_probs=0.5, use_chisq=False, use_pois=False, device=None, fixed_patterns=None, model_type=’gamma_unsupervised’, supervision_type=None, optimizer=pyro.optim.Adam, init_method=’random’, debug=False) :module: pyroNMF.run_inference
Setup the NMF model and optimizer.
Parameters:
D: Data tensor
num_patterns: Number of patterns
scale: Scale for gamma
NB_probs: Negative binomial probability
use_chisq: Whether to use chi-squared loss
device: Device to run on
fixed_patterns: Fixed patterns for supervised learning
model_type: ‘gamma_unsupervised’, ‘gamma_supervised’, ‘exponential_unsupervised’, ‘exponential_supervised’, , ‘exponentialSingle_unsupervised’, ‘exponentialSingle_supervised’
supervision_type: ‘fixed_genes’ or ‘fixed_samples’ (for supervised models)
supervision_type: ‘fixed_genes’ or ‘fixed_samples’ (supervised models only)
optimizer: Pyro optimizer instance
Returns:
model: Initialized model
guide: AutoNormal guide
svi: SVI optimizer
.. py:function:: _assert_supervision_type(supervision_type, cls_map) :module: pyroNMF.run_inference
Raise a clear error when supervision_type is not one of the expected values.
.. py:function:: debug_param_store(step) :module: pyroNMF.run_inference
.. py:function:: run_inference_loop(svi, model, D, U, num_burnin, num_sample_steps, use_tensorboard_id=None, spatial=False, coords=None, plot_dims=None) :module: pyroNMF.run_inference
Run the inference loop with optional tensorboard logging.
Parameters:
svi: SVI optimizer
model: The model
D: Data tensor
U: Probability tensor
num_steps: Number of optimization steps
use_tensorboard_id: Tensorboard identifier
spatial: Whether to include spatial plots
coords: Spatial coordinates
plot_dims: Plotting dimensions
Returns:
losses: List of loss values
steps: List of step numbers
runtime: Runtime in seconds
writer: Tensorboard writer (if used)
.. py:function:: log_adam_state_all(writer, svi, step, tag_prefix=’OptimAdam’, log_every=1) :module: pyroNMF.run_inference
.. py:function:: _log_tensorboard_metrics(writer, model, D, step, loss, spatial=False, coords=None, plot_dims=None) :module: pyroNMF.run_inference
Log metrics to tensorboard.
Parameters:
writer: Tensorboard writer
model: The model
D: Observed data tensor (used for residual plots)
step: Current step
loss: Current loss
spatial: Whether to include spatial plots
coords: Spatial coordinates
plot_dims: Plotting dimensions [rows, cols]
.. py:function:: _log_param_figures(writer, model, step, spatial, coords, plot_dims) :module: pyroNMF.run_inference
Log parameter histograms and spatial grids to tensorboard.
.. py:function:: _log_reconstructed_figures(writer, model, D, step) :module: pyroNMF.run_inference
Log D_reconstructed diagnostics to tensorboard.
.. py:function:: _log_memory(writer, step) :module: pyroNMF.run_inference
Log GPU/MPS memory usage to tensorboard.
.. py:function:: _pattern_cols(shape_ncols, learned_pattern_names, full_pattern_names) :module: pyroNMF.run_inference
Return the correct column-name list for a result matrix.
If the matrix has more columns than the number of learned patterns it must come from a semi-supervised run and we use the full (fixed + learned) names. full_pattern_names must not be None when shape_ncols != len(learned_pattern_names).
.. py:function:: _detect_and_save_parameters(result_anndata, model, settings, fixed_pattern_names=None, num_learned_patterns=None) :module: pyroNMF.run_inference
Auto-detect and save all model parameters from the model and param store.
Parameters:
result_anndata: AnnData object to save results into
model: The trained model
settings: Settings dict (used to read num_sample_steps)
fixed_pattern_names: Names of fixed patterns (supervised models only)
num_learned_patterns: Number of learned patterns
FIX: full_pattern_names is always defined (None in unsupervised mode) so the obs_df/var_df closures never hit an unbound name.
.. py:function:: save_results_to_anndata(result_anndata, model, losses, steps, runtime, scale, settings, fixed_pattern_names=None, num_learned_patterns=None, supervised=None) :module: pyroNMF.run_inference
Save results to AnnData object with auto-detection of parameters.
Parameters:
result_anndata: AnnData object to save to
model: Trained model
losses: Training losses
steps: Training steps
runtime: Training runtime
scale: Scale factor used
settings: Training settings
fixed_pattern_names: Names of fixed patterns (for supervised)
num_learned_patterns: Number of learned patterns (for supervised)
Returns:
result_anndata: AnnData object with results
.. py:function:: create_settings_dict(num_patterns, num_total_steps, num_sample_steps, device, NB_probs, use_chisq, scale, model_type, seed, use_tensorboard_id=None, writer=None) :module: pyroNMF.run_inference
Create settings dictionary for saving.
Parameters:
num_patterns: Number of patterns
num_total_steps: Number of total training steps
num_sample_steps: Number of sampling steps
device: Device used
NB_probs: Negative binomial probability
use_chisq: Whether chi-squared loss was used
scale: Scale factor
model_type: Type of model used
use_tensorboard_id: Tensorboard identifier
writer: Tensorboard writer
Returns:
settings: Dictionary of settings
.. py:function:: run_nmf(data, num_patterns, layer=None, uncertainty=’auto’, fixed_patterns=None, num_burnin=1000, num_sample_steps=20000, device=None, NB_probs=0.5, use_chisq=False, use_pois=False, use_tensorboard_id=None, spatial=False, plot_dims=None, scale=None, model_family=None, supervision_type=None, model=None, init_method=’random’, debug=False, optimizer=pyro.optim.Adam, seed=123) :module: pyroNMF.run_inference
Run supervised or unsupervised NMF analysis.
Parameters:
data: AnnData object with raw counts in X
num_patterns: Number of patterns to learn
layer: Layer key to use instead of data.X (optional)
uncertainty: Pre-computed uncertainty array (optional)
fixed_patterns: DataFrame with fixed patterns for supervised mode (optional)
num_burnin: Number of burn-in steps
num_sample_steps: Number of sampling steps
device: Device (‘cpu’, ‘cuda’, ‘mps’, or None for auto-detection)
NB_probs: Negative binomial probability
use_chisq: Whether to use chi-squared loss
use_pois: Whether to use Poisson loss
use_tensorboard_id: Tensorboard logging identifier (optional)
spatial: Whether to include spatial analysis
plot_dims: Plotting dimensions [rows, cols]
scale: Scale factor (computed automatically if None)
model_family: ‘gamma’, ‘exponential’, or ‘exponentialSingle’
supervision_type: ‘fixed_genes’ or ‘fixed_samples’ (supervised mode only)
optimizer: Pyro optimizer instance
Returns:
result_anndata: AnnData object with all results and metadata
Utilities
Device detection and spatial/pattern plotting helpers.
.. py:module:: pyroNMF.utils
Utility functions for device selection and spatial/pattern plotting.
.. py:function:: detect_device() :module: pyroNMF.utils
Select an available PyTorch device.
Checks for CUDA, then MPS (Apple Silicon), then falls back to CPU.
:returns: cuda if available, mps if available, otherwise cpu.
:rtype: torch.device
.. py:function:: plot_grid(patterns, coords, nrows, ncols, size=10, savename=None) :module: pyroNMF.utils
Plot spatial patterns on a grid of scatter plots with alpha scaling.
Colour scale is clipped to the 5th–95th percentile of each pattern. Alpha transparency is linearly scaled from 0.3 (minimum) to 1.0 (maximum) based on per-spot intensity.
:param patterns: Pattern matrix. Each column is one pattern. :type patterns: array-like of shape (n_samples, n_patterns) :param coords: Spatial coordinates. Column 0 is x, column 1 is y. :type coords: array-like of shape (n_samples, 2) :param nrows: Number of rows in the plot grid. :type nrows: int :param ncols: Number of columns in the plot grid. :type ncols: int :param size: Marker size for scatter points. :type size: float, optional :param savename: If provided, save the figure to this path. :type savename: str or None, optional
.. py:function:: plot_grid_noAlpha(patterns, coords, nrows, ncols, s=10, savename=None) :module: pyroNMF.utils
Plot spatial patterns without alpha scaling.
Full opacity scatter plots with per-panel colour bars. Coordinates
are expected as a mapping with 'x' and 'y' keys.
:param patterns: Pattern matrix. Each column is one pattern.
:type patterns: array-like of shape (n_samples, n_patterns)
:param coords: Spatial coordinates with keys 'x' and 'y', each of
length n_samples.
:type coords: Mapping
:param nrows: Number of rows in the plot grid.
:type nrows: int
:param ncols: Number of columns in the plot grid.
:type ncols: int
:param s: Marker size for scatter points.
:type s: float, optional
:param savename: If provided, save the figure to this path.
:type savename: str or None, optional
.. py:function:: plot_results(adata, nrows, ncols, which=’best_P’, s=4, a=1, scale_alpha=False, scale_values=False, savename=None, title=None) :module: pyroNMF.utils
Plot patterns stored in an AnnData object on spatial coordinates.
Requires adata.obsm['spatial'] to be present. Any key in
adata.obsm that holds a DataFrame of shape
(n_samples, n_patterns) can be visualised.
:param adata: AnnData with spatial coordinates in obsm['spatial'] and a
pattern DataFrame in obsm[which].
:type adata: anndata.AnnData
:param nrows: Number of rows in the plot grid.
:type nrows: int
:param ncols: Number of columns in the plot grid.
:type ncols: int
:param which: Key in adata.obsm to plot. Default is 'best_P'.
Common choices: 'mean_P', 'best_P', 'last_P',
'best_P_scaled', 'markers_P'.
:type which: str, optional
:param s: Marker size for scatter points.
:type s: float, optional
:param a: Base alpha (opacity) for scatter points.
:type a: float, optional
:param scale_alpha: If True, scale alpha linearly with per-spot intensity
(0.3 at minimum, 1.0 at maximum).
:type scale_alpha: bool, optional
:param scale_values: If True, clip the colour scale to the 5th–95th percentile
of each pattern.
:type scale_values: bool, optional
:param savename: If provided, save the figure to this path.
:type savename: str or None, optional
:param title: Overall figure title.
:type title: str or None, optional
.. py:function:: plot_results_sorted(adata, nrows, ncols, which=’best_P’, s=4, a=1, scale_alpha=False, scale_values=False, savename=None, title=None) :module: pyroNMF.utils
.. py:function:: plot_results_multisample(adata, nrows, ncols, which=’best_P’, split_by=’sample’, sample_order=None, s=4, a=1, scale_alpha=False, scale_values=False, savename=None, title=None) :module: pyroNMF.utils
.. py:function:: plot_results_multisample_sorted(adata, nrows, ncols, which=’best_P’, split_by=’sample’, sample_order=None, s=4, a=1, scale_alpha=False, scale_values=False, min_percentile=1, max_percentile=99, savename=None, title=None) :module: pyroNMF.utils
.. py:function:: plot_genes(adata, nrows, ncols, which_genes, s=4, a=1, scale_alpha=False, scale_values=False, savename=None, title=None) :module: pyroNMF.utils
.. py:function:: debug_cuda_tensors(step, top_n=20) :module: pyroNMF.utils
Print the largest tensors currently allocated on CUDA.
.. py:function:: _pattern_markers_all(ssranks: pandas.DataFrame) :module: pyroNMF.utils
.. py:function:: _pattern_markers_cut(ssranks: pandas.DataFrame) :module: pyroNMF.utils
Keep markers for a pattern until an item is ranked better (smaller) in some OTHER pattern than in this one.
.. py:function:: pattern_markers_pyronmf(adata, threshold=’all’, lp=None, axis=1, A_key=’mean_A’, P_key=’mean_P’) :module: pyroNMF.utils
CoGAPS-like patternMarkers for pyro_nmf outputs.
Returns dict with: - PatternMarkers: dict(pattern -> list of markers) - PatternRanks: DataFrame (items x patterns) integer ranks (lower = more associated) - PatternScores: DataFrame (items x patterns) L2 distances (lower = closer)
.. py:function:: set_seed(seed) :module: pyroNMF.utils
Model families
Exponential — Negative Binomial (primary)
The recommended model family. Places an independent Exponential prior on
every element of both A and P. The variational parameters (loc_A and
loc_P) are per-element rate values learned by SVI. This family is the
primary choice for most datasets.
.. py:module:: pyroNMF.models.exp_NB_models
.. py:class:: Exponential_NegBinomial_base(*args: Any, **kwargs: Any) :module: pyroNMF.models.exp_NB_models
Bases: :py:class:~pyro.nn.PyroModule
.. py:method:: Exponential_NegBinomial_base.forward(D, U=None, samp=False) :module: pyroNMF.models.exp_NB_models
.. py:method:: Exponential_NegBinomial_base.guide() :module: pyroNMF.models.exp_NB_models
.. py:class:: Exponential_NegBinomial_SSFixedGenes(*args: Any, **kwargs: Any) :module: pyroNMF.models.exp_NB_models
Bases: :py:class:~pyroNMF.models.exp_NB_models.Exponential_NegBinomial_base
.. py:method:: Exponential_NegBinomial_SSFixedGenes.forward(D, U=None, samp=False) :module: pyroNMF.models.exp_NB_models
.. py:method:: Exponential_NegBinomial_SSFixedGenes.guide() :module: pyroNMF.models.exp_NB_models
.. py:class:: Exponential_NegBinomial_SSFixedSamples(*args: Any, **kwargs: Any) :module: pyroNMF.models.exp_NB_models
Bases: :py:class:~pyroNMF.models.exp_NB_models.Exponential_NegBinomial_base
.. py:method:: Exponential_NegBinomial_SSFixedSamples.forward(D, U=None, samp=False) :module: pyroNMF.models.exp_NB_models
.. py:function:: guide(D) :module: pyroNMF.models.exp_NB_models
Gamma — Negative Binomial (alternative)
Places a Gamma prior on every element of A and P. Variational
parameters are per-element location values (loc_A, loc_P); a shared
scalar scale controls the concentration. Use this family when you want
heavier-tailed priors or when the Gamma parameterisation fits domain
knowledge better.
.. py:module:: pyroNMF.models.gamma_NB_models
.. py:class:: Gamma_NegBinomial_base(*args: Any, **kwargs: Any) :module: pyroNMF.models.gamma_NB_models
Bases: :py:class:~pyro.nn.PyroModule
.. py:method:: Gamma_NegBinomial_base.forward(D, U=None, samp=False) :module: pyroNMF.models.gamma_NB_models
.. py:method:: Gamma_NegBinomial_base.guide() :module: pyroNMF.models.gamma_NB_models
.. py:class:: Gamma_NegBinomial_SSFixedGenes(*args: Any, **kwargs: Any) :module: pyroNMF.models.gamma_NB_models
Bases: :py:class:~pyroNMF.models.gamma_NB_models.Gamma_NegBinomial_base
.. py:method:: Gamma_NegBinomial_SSFixedGenes.forward(D, U=None, samp=False) :module: pyroNMF.models.gamma_NB_models
.. py:method:: Gamma_NegBinomial_SSFixedGenes.guide() :module: pyroNMF.models.gamma_NB_models
.. py:class:: Gamma_NegBinomial_SSFixedSamples(*args: Any, **kwargs: Any) :module: pyroNMF.models.gamma_NB_models
Bases: :py:class:~pyroNMF.models.gamma_NB_models.Gamma_NegBinomial_base
.. py:method:: Gamma_NegBinomial_SSFixedSamples.forward(D, U=None, samp=False) :module: pyroNMF.models.gamma_NB_models
.. py:function:: guide(D) :module: pyroNMF.models.gamma_NB_models
ExponentialSingle — Negative Binomial (alternative)
A more parsimonious Exponential parameterisation that uses a single shared
scalar rate per matrix (scale_A for A, scale_P for P) rather than
per-element rates. Faster convergence on smaller datasets; less flexible
than the per-element Exponential model.
.. py:module:: pyroNMF.models.expSingle_NB_models
.. py:class:: ExponentialSingle_base(*args: Any, **kwargs: Any) :module: pyroNMF.models.expSingle_NB_models
Bases: :py:class:~pyro.nn.PyroModule
.. py:method:: ExponentialSingle_base.forward(D, U=None, samp=False) :module: pyroNMF.models.expSingle_NB_models
.. py:method:: ExponentialSingle_base.guide() :module: pyroNMF.models.expSingle_NB_models
.. py:class:: ExponentialSingle_SSFixedGenes(*args: Any, **kwargs: Any) :module: pyroNMF.models.expSingle_NB_models
Bases: :py:class:~pyroNMF.models.expSingle_NB_models.ExponentialSingle_base
.. py:method:: ExponentialSingle_SSFixedGenes.forward(D, U=None, samp=False) :module: pyroNMF.models.expSingle_NB_models
.. py:method:: ExponentialSingle_SSFixedGenes.guide() :module: pyroNMF.models.expSingle_NB_models
.. py:class:: ExponentialSingle_SSFixedSamples(*args: Any, **kwargs: Any) :module: pyroNMF.models.expSingle_NB_models
Bases: :py:class:~pyroNMF.models.expSingle_NB_models.ExponentialSingle_base
.. py:method:: ExponentialSingle_SSFixedSamples.forward(D, U=None, samp=False) :module: pyroNMF.models.expSingle_NB_models
.. py:function:: guide(D) :module: pyroNMF.models.expSingle_NB_models