scviva.tl.VisionAnalysis#

class scviva.tl.VisionAnalysis(adata, norm_data_key=None, protein_obsm_key=None)[source]#

Unsupervised transcriptome analysis and gene-signature scoring.

Computes a cell neighbor-weight graph, per-cell gene-signature scores, their spatial/graph autocorrelation (Geary’s C), and one-vs-all differential expression of signatures and metadata across clusters — mirroring R VISION’s analyze() pipeline.

Parameters:
adata AnnData

Annotated data object.

norm_data_key str | None

Key in adata.layers for scaled/library-size-normalised expression. Use "use_raw" to pull from adata.raw. None (default) uses adata.X directly.

Matching R VISION’s documented contract, this data should be normalized but not log-transformed – VISION log-transforms it internally wherever needed (log2p1()). If it looks already log-transformed (small, non-integer values), that internal step is skipped automatically and a warning is logged the first time it would otherwise have double-transformed your data; pass genuinely non-log-transformed data to avoid relying on that detection.

protein_obsm_key str | None

Key in adata.obsm for CITE-seq protein (ADT) data, if any.

Notes

Lower-level VISION functions are available as va.tl.<method>, defaulting to this object’s AnnData; see VisionToolsAccessor.

Examples

>>> va = VisionAnalysis(adata)
>>> va.setup(compute_neighbors_on_key="X_pca")
>>> va.load_signatures(gmt_files=["h.all.v7.symbols.gmt"])
>>> va.compute_signatures()
>>> va.compute_differential_expression()
>>> results = va.results

Without a precomputed latent space:

>>> va = VisionAnalysis(adata)
>>> va.compute_latent_space()
>>> va.setup()

Attributes table

adata

The working AnnData object.

has_signatures

True if signatures have been scored via compute_signatures().

is_set_up

True if setup() has been called.

norm_data_key

Expression layer used for scoring (None uses adata.X).

results

Typed view over the analysis results stored in adata.uns/adata.obsm.

var_names

Gene names, respecting norm_data_key == "use_raw".

Methods table

attach_signatures([varm_key])

Point this session at signatures already loaded into adata.varm.

compute_differential_expression()

Compute one-vs-all differential expression of metadata and signatures.

compute_latent_space([max_components, ...])

Compute a PCA latent space, stored as adata.obsm["X_pca"].

compute_one_vs_one_de(key, group1, group2)

Wilcoxon one-vs-one differential expression between two groups of adata.obs[key].

compute_signatures([...])

Score loaded signatures per-cell and compute their graph autocorrelation.

filter_genes([filters])

Compute a boolean gene filter mask; does not mutate adata in place.

generate_projections([methods])

Generate 2-D visualisation projections (tSNE, UMAP, ISOMap, …).

get_gene_expression(genes)

Return the (dense) expression of one or more genes for every cell.

get_genes_by_signature(sig_name)

Genes belonging to signature sig_name, indexed by gene name with +/-1 signs.

load_signatures([gmt_files, dicts, use_raw, ...])

Load gene signatures into adata.varm ahead of compute_signatures().

pool_cells([cells_per_partition])

Micro-cluster ("pool") cells into supercells for scalable analysis.

setup([compute_neighbors_on_key, ...])

Build the VISION neighbor-weight graph and Louvain cell clusters.

Attributes

VisionAnalysis.adata#

The working AnnData object.

VisionAnalysis.has_signatures#

True if signatures have been scored via compute_signatures().

VisionAnalysis.is_set_up#

True if setup() has been called.

VisionAnalysis.norm_data_key#

Expression layer used for scoring (None uses adata.X).

VisionAnalysis.results#

Typed view over the analysis results stored in adata.uns/adata.obsm.

VisionAnalysis.var_names#

Gene names, respecting norm_data_key == "use_raw".

Methods

VisionAnalysis.attach_signatures(varm_key='signatures')[source]#

Point this session at signatures already loaded into adata.varm.

Use this instead of load_signatures() when signatures were already loaded by another call on the same adata (e.g. a prior VisionAnalysis session, or load_signatures() called directly) and re-parsing the source GMT/dict would be redundant.

Parameters:
varm_key str

Key in adata.varm (or adata.raw.varm when norm_data_key == "use_raw") for the gene x signature weight matrix to use.

Return type:

None

VisionAnalysis.compute_differential_expression()[source]#

Compute one-vs-all differential expression of metadata and signatures.

Requires setup(). If signatures have been scored via compute_signatures(), also computes signature differential expression, per-signature gene importance, a signature dendrogram, and signature clusters — mirroring R VISION’s ClusterComparisons.

Return type:

None

VisionAnalysis.compute_latent_space(max_components=30, use_permutation_wpca=False, **kwargs)[source]#

Compute a PCA latent space, stored as adata.obsm["X_pca"].

Parameters:
max_components int

Maximum number of principal components to compute.

use_permutation_wpca bool

If True, run permutation weighted PCA and keep only the statistically significant components. If False, keep all max_components components (mirrors R VISION’s perm_wPCA=FALSE default).

**kwargs

Forwarded to compute_latent_space() (e.g. filters, threshold, num_mad, projection_genes).

Return type:

None

VisionAnalysis.compute_one_vs_one_de(key, group1, group2)[source]#

Wilcoxon one-vs-one differential expression between two groups of adata.obs[key].

Full results are also stored in adata.uns[f"rank_genes_groups_{key}"] (overwriting any previous comparison for the same key).

Parameters:
key str

Column of adata.obs defining the groups.

group1 str

Group of adata.obs[key] to test.

group2 str

Reference group of adata.obs[key] that group1 is compared against.

Return type:

DataFrame

Returns:

pandas.DataFrame Per-gene results for group1 versus group2 as returned by scanpy.get.rank_genes_groups_df() (gene names, scores, log fold changes, p-values and adjusted p-values).

VisionAnalysis.compute_signatures(signature_names_uns_key=None, sig_norm_method='znorm_columns', device='auto', batch_size=1200, random_state=0)[source]#

Score loaded signatures per-cell and compute their graph autocorrelation.

Requires setup() (the neighbor-weight graph is used for Geary’s C).

Parameters:
signature_names_uns_key str | None

Key in adata.uns holding custom signature names, if any.

sig_norm_method str

Normalisation method for the sparse scoring path. See compute_signatures_anndata().

device str

Compute device: "auto", "cuda", "mps", or "cpu". "cpu" forces the deterministic scipy sparse path (a dense torch CPU tensor path is not offered, since its multi-threaded matmul is not run-to-run bit-reproducible).

batch_size int

Number of signatures scored per device batch.

random_state int

Seed for the Geary’s C permutation-null background signature generation (see generate_permutations_null()).

Return type:

None

VisionAnalysis.filter_genes(filters=('threshold', 'fano'), **kwargs)[source]#

Compute a boolean gene filter mask; does not mutate adata in place.

Parameters:
filters tuple[str, ...]

Names of filters to apply in sequence, e.g. "novar", "threshold", "fano". See apply_filters().

**kwargs

Forwarded to apply_filters() (e.g. threshold, num_mad).

Return type:

ndarray

Returns:

np.ndarray Boolean mask of shape (n_vars,). Apply with adata[:, mask].copy().

VisionAnalysis.generate_projections(methods=None, **kwargs)[source]#

Generate 2-D visualisation projections (tSNE, UMAP, ISOMap, …).

Parameters:
methods list[str] | None

Projection methods to compute, chosen from "tSNE30", "tSNE10", "UMAP", "ISOMap", "ICA" and "RBFPCA". If None, all six methods are computed.

**kwargs

Forwarded to generate_projections() (e.g. obsm_key, K, projection_genes).

Return type:

None

VisionAnalysis.get_gene_expression(genes)[source]#

Return the (dense) expression of one or more genes for every cell.

Expression is read from adata.raw when norm_data_key == "use_raw", from adata.X when norm_data_key is None, and from adata.layers[norm_data_key] otherwise.

Parameters:
genes str | list[str]

Gene name or list of gene names.

Return type:

ndarray

Returns:

numpy.ndarray Dense array of shape (n_cells, n_genes) (n_genes == 1 when a single gene name is given).

VisionAnalysis.get_genes_by_signature(sig_name)[source]#

Genes belonging to signature sig_name, indexed by gene name with +/-1 signs.

Parameters:
sig_name str

Name of a signature loaded via load_signatures() (or attach_signatures()) and scored via compute_signatures().

Return type:

DataFrame

Returns:

pandas.DataFrame Single-column frame indexed by the genes with a non-zero weight in the signature, holding each gene’s signature weight (sign).

VisionAnalysis.load_signatures(gmt_files=None, dicts=None, use_raw=False, min_signature_genes=5, sig_gene_threshold=0.001, varm_key='signatures', split_signed=True)[source]#

Load gene signatures into adata.varm ahead of compute_signatures().

Parameters:
gmt_files list[str] | None

Paths to one or more GMT signature files.

dicts list[dict] | None

Signature definitions as Python dicts (see load_signatures()).

use_raw bool

Use adata.raw gene names/expression for gene-presence filtering.

min_signature_genes int

Minimum number of matching genes required to retain a signature.

sig_gene_threshold float

Minimum fraction of cells expressing a gene for it to be eligible for signature membership.

varm_key str

Key in adata.varm to store the resulting gene x signature matrix.

split_signed bool

Auto-expand bidirectional (+/-) signatures into _UP/_DOWN sub-columns after loading, matching R VISION’s signature handling.

Return type:

None

VisionAnalysis.pool_cells(cells_per_partition=10, **kwargs)[source]#

Micro-cluster (“pool”) cells into supercells for scalable analysis.

Parameters:
cells_per_partition int

Target number of cells per micro-cluster (supercell).

**kwargs

Forwarded to apply_micro_clustering() (e.g. filter_input, filter_threshold, latent_space_key, K, uns_key).

Return type:

None

VisionAnalysis.setup(compute_neighbors_on_key=None, num_neighbors=None, exact_knn=False, tree=None, lca_knn=False, lca_min_size=20, random_state=0)[source]#

Build the VISION neighbor-weight graph and Louvain cell clusters.

Parameters:
compute_neighbors_on_key str | None

Key in adata.obsm to use as the latent space for the KNN weight graph. If None and adata.obsm["X_pca"] exists, that is used automatically. Falls back to L1-normalising adata.obsp["connectivities"] if available.

num_neighbors int | None

Number of KNN neighbors for the weight graph. Defaults to round(sqrt(n_cells)), matching R VISION.

exact_knn bool

Use exact (brute-force/kd-tree) KNN instead of approximate.

tree str | None

Newick string or path to a newick file for PhyloVision mode: build KNN weights from phylogenetic tree structure instead of an expression/embedding latent space.

lca_knn bool

When tree is set, use LCA-distance-based tree weights instead of cophenetic-distance-based weights.

lca_min_size int

Minimum clade size for the LCA-based tree KNN weights.

random_state int

Seed for the Louvain clustering used to build VISION_Clusters (igraph’s community_multilevel has no seed parameter of its own and is otherwise non-deterministic between runs).

Return type:

None