uchrom.emb

Cells by their measurements: embeddings and clusters from contact maps (FastHigashi, scHiCluster), from RNA, accessibility, chromatin marks or any per-cell matrix, and how well an embedding separates known types.

Cell embeddings from per-cell features of any modality.

embed_cells() turns a group of numeric cd.cells columns — the rna.<gene> counts written by from_fofct(), if.<mark> immunofluorescence summaries from aggregate_tracks(), atac.<gene> accessibility, … — or an explicit cells × features matrix into PCA (or LSI) / t-SNE / UMAP coordinates stored in cd.cellm (rows aligned with cd.cells). Parameters, including the normalisation, are recorded in cd.uns["embeddings"] so they round-trip through ChromData files and the web browser can group the embeddings by modality.

Normalisations (normalization=; "auto" picks one from source):

"counts" (rna and unknown prefixes)

log1p then z-score per feature (optionally library-size first).

"zscore" (if, protein, ab)

continuous intensities: z-score per feature, log=True adds log1p.

"tfidf" (atac)

sparse accessibility: TF-IDF → truncated SVD (latent semantic indexing); component 1 is dropped when it tracks sequencing depth.

"none"

features used as given (already normalised, e.g. Hi-C vectors).

uchrom.emb.cells.aggregate_tracks(cd, fields: Sequence[str] | None = None, *, prefix: str = 'if', stat: str | Sequence[str] = 'mean', by: None | str | int = None, min_spots: int = 1, write: bool = True, batch: int = 64)[source]

Summarise tracks (cd.spot_tracks + cd.bin_tracks seen per spot) into per-cell features.

On a backed ChromData (ChromData.read(..., backed=True), an atlas store from uchrom.datasets.load) the spots are streamed in batches of batch cells (iter_cells()), reading only the coordinates’ keys and the fields tracks, so the whole table is never in memory; give several statistics in stat to compute them in the same pass.

Parameters:
  • cd (ChromData) – With tracks and a cell_id column in cd.spots.

  • fields (sequence of str, optional) – Track columns to use (default: every numeric track).

  • prefix (str) – Output columns are named f"{prefix}.{field}".

  • stat ("mean", "median", "std", "corr", or a list of them) – Per-cell statistic. "corr" gives the within-cell Pearson correlation of every pair of fields (f"{prefix}.{a}~{b}") — how marks co-occur on the same loci, which is insensitive to per-cell intensity scaling.

  • by (None, "chrom" or int) – Also split by chromosome (…@chr1) or by genomic bins of this many bp (…@chr1:10 = 10th bin); not with stat="corr".

  • min_spots (int) – Groups with fewer spots become NaN.

  • write (bool) – Add the columns to cd.cells (replacing ones of the same name).

  • batch (int) – Cells per chunk when cd is backed.

Returns:

  • DataFrame indexed like cd.cells (cells without spots are NaN) — or,

  • when stat is a list, a dict {stat: DataFrame}.

uchrom.emb.cells.cluster_cells(cd, *, use: str = 'rna_pca', n_neighbors: int = 15, resolution: float = 1.0, n_components: int | None = None, random_state: int = 0, key_added: str | None = None) → Series[source]

Leiden clusters of the cells from an embedding in cd.cellm.

A k-nearest-neighbour graph (n_neighbors, Euclidean, symmetrised) of cd.cellm[use] (first n_components columns) is partitioned with the Leiden algorithm (leidenalg, RB configuration model at resolution, seeded). Clusters are numbered "0", "1", … by decreasing size and stored as a categorical column cd.cells[key_added] (default f"leiden_{use}"); the parameters go to cd.uns["clusters"][key_added]. Cells whose embedding row is missing (NaN: not embedded, see embed_cells(cells=)) get no label. Needs leidenalg and python-igraph (pip install leidenalg).

Returns the cluster labels (a Series indexed like cd.cells).

uchrom.emb.cells.embed_cells(cd, *, source: str = 'rna', fields: Sequence[str] | None = None, matrix=None, normalization: str = 'auto', log: bool = False, methods: Sequence[str] = ('pca', 'tsne', 'umap'), n_pcs: int = 10, n_lsi: int = 30, drop_depth_r: float | None = 0.5, random_state: int = 0, tsne_perplexity: float | None = None, umap_neighbors: int = 15, umap_min_dist: float = 0.3, library_size: bool = False, modality: str | None = None, features: str | None = None, cells=None, copy: bool = False)[source]

Compute cell embeddings and store them in cd.cellm.

Parameters:
  • cd (ChromData) – Needs a non-empty cd.cells; rows of the embeddings follow it.

  • source (str) – Feature group; selects the numeric columns f"{source}.*" and names the outputs f"{source}_{method}" (rna_pca, if_umap, atac_lsi, …).

  • fields (sequence of str, optional) – Explicit cd.cells columns to use instead of the prefix.

  • matrix (array or scipy.sparse matrix, optional) – cells × features input instead of cd.cells columns (rows in cd.cells order, or in the order of cells) — e.g. a genome-wide ATAC bin matrix too large to keep as cell columns. Describe it with features=.

  • normalization ("auto", "counts", "zscore", "tfidf", "none") – See the module docstring. "auto": atac → tfidf, if / protein → zscore, hic → none, anything else → counts.

  • log (bool) – "zscore" only: log1p first (needs non-negative intensities).

  • methods (subset of ("pca", "tsne", "umap")) – With "tfidf" the linear step is LSI and is stored as f"{source}_lsi". UMAP needs umap-learn (pip install "u-chrom[umap]"); it is skipped with a warning when missing. t-SNE and UMAP run on the PCs / LSI components.

  • n_pcs (int) – Principal components kept (and fed to t-SNE / UMAP).

  • n_lsi (int) – LSI components kept ("tfidf").

  • drop_depth_r (float or None) – "tfidf": drop LSI component 1 if |r(component, log depth)| exceeds this.

  • library_size (bool) – "counts": divide by each cell’s total before log1p (see normalize_counts(); off by default for targeted panels).

  • modality (str, optional) – Display name (default from MODALITY_LABELS, e.g. atac → "ATAC"); the browser groups embeddings by it.

  • features (str, optional) – Free-text description of the features, recorded in the metadata.

  • cells (sequence of cell ids or boolean mask, optional) – Embed only these cells (default: all); the other rows of the embeddings are NaN. With matrix, its rows follow cells.

  • copy (bool) – Return a new ChromData holding the embeddings instead of modifying cd.

Returns:

  • dict mapping cellm key → array (also written to cd.cellm) — or, with

  • copy=True, the new ChromData.

uchrom.emb.cells.marker_features(cd, groups: str | Series, *, prefix: str = 'rna.', n_top: int = 5, log: bool = True) → Dict[str, List[str]][source]

Top features of each group of cells: the prefix columns of cd.cells ranked by the difference of the mean (log1p when log) between the group and the other cells.

uchrom.emb.cells.normalize_counts(counts: ndarray, *, library_size: bool = False) → ndarray[source]

log1p and z-score each feature (optionally library-size first).

library_size=False (default) suits small targeted panels (seqFISH, MERFISH): there one or two housekeeping genes dominate the total, so dividing by it turns PC1 into “that gene vs the rest” (on Takei 2021, Eef2 ≈ 16 % of all counts). Use True for transcriptome-wide data. Constant features become zero.

uchrom.emb.cells.tfidf_lsi(x, n_components: int = 30, *, depth: ndarray | None = None, drop_depth_r: float = 0.5, random_state: int = 0)[source]

TF-IDF + truncated SVD (LSI) of a cells × features count matrix.

Follows Signac’s RunTFIDF (method 1: log1p(tf · idf · 1e4), tf = count / cell total, idf = n_cells / feature total) and RunSVD (each component scaled to mean 0, sd 1). Dense or scipy.sparse input; sparse stays sparse.

Component 1 of scATAC LSI usually tracks sequencing depth. It is dropped when |Pearson r(component, log depth)| > drop_depth_r (only component 1 is tested; pass drop_depth_r=None to keep all).

Returns:

  • (lsi, info) — lsi ((n_cells, n_kept) array; info: dict with)

  • depth_r (per component), dropped (1-based component numbers),

  • explained_variance_ratio.

FastHigashi / Higashi wrapper for uchrom.emb.

Design notes

The expensive dependency (fasthigashi / higashi) is imported lazily and can also be injected via wrapper_factory for testing.

FastHigashi’s row order

FastHigashi.fetch_cell_embedding(restore_order=True) returns rows in the same order as label_info.pickle. We always pass restore_order=True and read that order from the pickle next to config.JSON — that’s the canonical row anchor and avoids relying on internal attributes that may change between FastHigashi versions.

Why we don’t store imputed maps in ChromData

Per-cell imputed contact maps are O(n²) per cell. ChromData is deliberately O(n) (no global spotp). When the user wants imputed maps, they live on disk under path2result_dir and we only record the path in cd.uns[embed_key]['result_dir'].

Apple Silicon shim

FastHigashi 0.1.1a0 calls tensor.pin_memory() unconditionally during prep_dataset, which crashes on PyTorch ≥2.x on Apple Silicon when MPS is the only non-CPU device available (PyTorch tries to pin against MPS, which is not a real pinned-memory backend). When CUDA isn’t available we no-op pin_memory for the duration of run() — pinned memory only matters for CUDA host→device transfers anyway.

uchrom.emb.higashi.align_embedding(emb: ndarray, emb_order: list[str], cd_cells: DataFrame, *, cell_id_col: str = 'cell_name') → ndarray[source]

Reorder emb rows to match cd_cells[cell_id_col] exactly.

Misaligning silently poisons every downstream analysis, so we fail loudly on missing / extra names rather than pad with NaNs.

uchrom.emb.higashi.embed_higashi(cd, *, contacts: str = 'per_cell', cells=None, chroms: list[str] | None = None, rank: int = 64, variant: str = 'embed_l2_norm_correct_coverage_fh', which: Literal['fast', 'full'] = 'fast', conv: bool = True, rwr: bool = True, col: bool = True, off_diag: int = 100, filter: bool = False, seed: int = 0, keep_variants: bool = False, work_dir: str | Path | None = None, log: bool = True, key_added: str = 'higashi', copy: bool = False, wrapper_factory: Callable[[...], Any] | None = None, run_model_kwargs: dict[str, Any] | None = None)[source]

Embed cells by their single-cell Hi-C contact maps with FastHigashi (Zhang et al. 2022) — from the per-cell maps linked to cd (cd.link_scool, key contacts; or embedded in an atlas store).

The Higashi inputs (one contact table per cell, label info, chromosome sizes, config.JSON) are written from the .scool under work_dir, FastHigashi runs there (its output goes to work_dir/fasthigashi.log with log=True), and the embedding comes back on the cells axis.

Parameters:
  • contacts – Key of the linked per-cell contact maps (cd.uns["linked_scool"]).

  • cells – Cell ids to embed (default: every cell of cd); other cells get NaN rows.

  • chroms – Chromosomes to use (default: those of the maps without Y and M).

  • rank – FastHigashi’s tensor rank and preprocessing: 3x3 convolution, random walk with restart, column normalisation, the band of diagonals kept, its cell filter.

  • conv – FastHigashi’s tensor rank and preprocessing: 3x3 convolution, random walk with restart, column normalisation, the band of diagonals kept, its cell filter.

  • rwr – FastHigashi’s tensor rank and preprocessing: 3x3 convolution, random walk with restart, column normalisation, the band of diagonals kept, its cell filter.

  • col – FastHigashi’s tensor rank and preprocessing: 3x3 convolution, random walk with restart, column normalisation, the band of diagonals kept, its cell filter.

  • off_diag – FastHigashi’s tensor rank and preprocessing: 3x3 convolution, random walk with restart, column normalisation, the band of diagonals kept, its cell filter.

  • filter – FastHigashi’s tensor rank and preprocessing: 3x3 convolution, random walk with restart, column normalisation, the band of diagonals kept, its cell filter.

  • variant – The embedding FastHigashi computes that is stored (default: L2-normalised, with the coverage regressed out); keep_variants=True also stores every other embed_* variant as cd.cellm["<key_added>.<variant>"].

  • seed – Seeds torch / numpy / random first (FastHigashi’s initialisation and final SVD are random).

  • work_dir – Where the inputs, FastHigashi’s cache and results go (default: a new temporary directory, kept; its path is in cd.uns[key_added]["work_dir"]). Started clean on every call.

Returns:

  • The embedding, (n_cells, rank) on the cells axis (copy=False; also stored in

  • cd.cellm[key_added], FastHigashi’s QC in cd.cells[key_added + "_qc"], the settings in

  • cd.uns[key_added] and cd.uns["embeddings"], the call in cd.results) — or a new ChromData

  • holding them (copy=True).

uchrom.emb.higashi.run(cd, contacts_dir: str | Path, *, which: Literal['fast', 'full'] = 'fast', config_path: str | Path | None = None, rank: int = 256, embed_key: str = 'higashi', cell_id_col: str = 'cell_name', embed_variant: str = 'embed_l2_norm', result_dir: str | Path | None = None, cache_dir: str | Path | None = None, wrapper_factory: Callable[[...], Any] | None = None, wrapper_kwargs: dict[str, Any] | None = None, run_model_kwargs: dict[str, Any] | None = None)[source]

Run FastHigashi (or Higashi) and stash the cell embedding on cd.

Parameters:
  • cd (ChromData) – Must have a cells frame containing cell_id_col.

  • contacts_dir (path) – Directory produced by uchrom.io.write_higashi_inputs(). Must contain config.JSON and label_info.pickle.

  • which ({"fast", "full"}) – FastHigashi (default) or full Higashi.

  • rank (int) – Tucker rank passed to FastHigashi’s run_model and used as final_dim in fetch_cell_embedding.

  • embed_variant (str) – Which key from FastHigashi’s embedding dict to use. Default is embed_l2_norm (L2-normalised, what the official tutorial uses).

  • result_dir (path, optional) – Where FastHigashi caches per-cell tensors and writes results. Default to contacts_dir (lets write_higashi_inputs and FastHigashi share one directory tree).

  • cache_dir (path, optional) – Where FastHigashi caches per-cell tensors and writes results. Default to contacts_dir (lets write_higashi_inputs and FastHigashi share one directory tree).

  • wrapper_factory (callable, optional) – For tests / alt backends. Called as factory(config_path, path2input_cache, path2result_dir, off_diag, filter, do_conv, do_rwr, do_col, no_col) — the real FastHigashi constructor takes positional args.

  • wrapper_kwargs (dict, optional) – Override the FastHigashi __init__ defaults (off_diag, filter, do_conv etc.).

  • run_model_kwargs (dict, optional) – Forwarded to run_model. rank from the top-level kwarg wins unless explicitly overridden here.

Returns:

The same cd object, mutated in place.

Return type:

ChromData

scHiCluster cell features from single-cell contact maps (.scool).

Zhou et al. 2019 (PNAS 116:14011, “Robust single-cell Hi-C clustering by convolution- and random-walk-based imputation”), as the authors’ code computes them (schicluster.schicluster: impute_cpu → neighbor_ave_cpu / random_walk_cpu, then hicluster_cpu; github.com/zhoujt1994/scHiCluster, PyPI 1.3.2, MIT licence). For each cell and chromosome, from the cell’s contact counts S (symmetric, the diagonal once):

  1. A = log2(S + diag(S) + 1) — the authors build A + Aᵀ from the upper triangle, which counts the diagonal twice;

  2. the (2·pad+1)² mean filter, zeros outside the map (by cumulative sums, rounded to 8 decimals, as the code);

  3. the random walk with restart: the diagonal set to 0, then to 1 in the columns without contacts, P the column-normalised map, Q ← (1 − rp)·I + rp·Q·P from Q = I until the Frobenius norm of the change is below tol (1e-6), at most max_iter (30) steps, each cell on its own;

  4. the features: Q of every cell flattened (all n² entries), set to 1 above the cell’s 100 − top_pct percentile and 0 elsewhere; per chromosome a PCA across the cells with int(0.2 · min(cells, n²)) − 1 components (the authors’ rule; n_per_chrom sets a number instead); the chromosomes’ PCs concatenated. With the authors’ rule this PCA (scikit-learn’s, as theirs) is the slowest step (2,000 cells, 8 CPUs: about 400 of 506 s); a fixed n_per_chrom such as 20 makes it much shorter.

embed_contacts() does all of it on a ChromData (it reads the per-cell maps linked to it, or embedded in its atlas store) and then embeds the cells with uchrom.emb.embed_cells() (PCA → t-SNE / UMAP; the authors cluster their concatenated PCs with k-means instead).

uchrom.emb.hic.embed_contacts(cd, *, contacts: str = 'per_cell', method: str = 'schicluster', cells=None, chroms: Sequence[str] | None = None, pad: int = 1, rp: float = 0.5, top_pct: float = 20.0, n_per_chrom: int | None = None, pca: str = 'full', methods: Sequence[str] = ('pca', 'tsne', 'umap'), n_pcs: int = 20, random_state: int = 0, key_added: str = 'hic', copy: bool = False, n_threads: int = 0)[source]

Embed cells by their single-cell contact maps — from the per-cell maps linked to cd (cd.link_scool, key contacts; or embedded in an atlas store).

method="schicluster" (Zhou et al. 2019, PNAS 116:14011; the authors’ computation, module docstring): each cell’s intra-chromosomal maps are log-transformed, smoothed by a (2·pad+1)² mean filter, imputed by a random walk (rp) and binarised (top top_pct %); each chromosome is reduced to PCs across the cells (n_per_chrom; default the authors’ int(0.2 · min(cells, n²)) − 1) and the PCs of all chromosomes are concatenated (scool_cell_features()). uchrom.emb.embed_cells() then runs PCA (n_pcs) → t-SNE / UMAP on these features. The maps are read with cd.linked_scool_path(contacts, cells=..., trans=False): the linked .scool itself, or — on an atlas store — the cells’ maps exported once from the embedded copy (one read per chromosome, the contacts between chromosomes left out). For FastHigashi use uchrom.emb.embed_higashi().

Parameters:
  • cd (ChromData) – With cells and linked per-cell contact maps (cd.uns["linked_scool"][contacts]).

  • contacts (str) – Key of the linked per-cell maps.

  • method ("schicluster") – The contact-map features.

  • cells (sequence of cell ids, optional) – Cells to embed (default: every cell of cd); the other rows of the embeddings are NaN.

  • chroms (sequence of str, optional) – Chromosomes to use, in this order (default: those of the maps without Y and M).

  • pad – scHiCluster’s filter half-width, walk weight (Q ← (1 − rp) I + rp Q P; 0.5), share of entries kept, PCs per chromosome (None: the authors’ rule; see schicluster_features()).

  • rp – scHiCluster’s filter half-width, walk weight (Q ← (1 − rp) I + rp Q P; 0.5), share of entries kept, PCs per chromosome (None: the authors’ rule; see schicluster_features()).

  • top_pct – scHiCluster’s filter half-width, walk weight (Q ← (1 − rp) I + rp Q P; 0.5), share of entries kept, PCs per chromosome (None: the authors’ rule; see schicluster_features()).

  • n_per_chrom – scHiCluster’s filter half-width, walk weight (Q ← (1 − rp) I + rp Q P; 0.5), share of entries kept, PCs per chromosome (None: the authors’ rule; see schicluster_features()).

  • pca ("full" or "incremental") – How each chromosome’s PCA is fitted (schicluster_features()); "incremental" (with n_per_chrom) for 10⁵ cells.

  • methods – Passed to uchrom.emb.embed_cells() (random_state also seeds the per-chromosome PCAs).

  • n_pcs – Passed to uchrom.emb.embed_cells() (random_state also seeds the per-chromosome PCAs).

  • random_state – Passed to uchrom.emb.embed_cells() (random_state also seeds the per-chromosome PCAs).

  • key_added (str) – Names the outputs: cd.cellm[f"{key_added}_pca"] (_tsne, _umap), registered in cd.uns["embeddings"] as the Hi-C modality; the number of contacts used per cell (intra- chromosomal, of chroms) in cd.cells[f"{key_added}_n_cis_contacts"]; the settings in cd.uns[key_added]; the scHiCluster features (cells × the PCs of every chromosome, float32, on the cells axis) in cd.results[key_added] with the call’s provenance.

  • copy (bool) – Return a new ChromData holding the results instead of modifying cd.

  • n_threads (int) – Maps imputed side by side (0: every CPU this process may use); the results do not depend on it.

Return type:

dict mapping cellm key → embedding (copy=False), or the new ChromData (copy=True).

uchrom.emb.hic.schicluster_features(per_chrom, *, pad: int = 1, rp: float = 0.5, log: bool = True, top_pct: float = 20.0, n_per_chrom: int | None = None, batch: int = 256, random_state: int = 0, n_threads: int = 0, pca: str = 'full') → Tuple[ndarray, List[str]][source]

scHiCluster features, per chromosome (module docstring, step 4).

per_chrom maps chrom → either an (n_cells, n, n) array of raw counts or a callable f(lo, hi) -> (hi - lo, n, n) array for a batch of cells (so all maps never need to be dense at once) together with n_cells — pass (callable, n_cells, n) tuples for that. n_per_chrom: PCs per chromosome (None: the authors’ int(0.2 · min(cells, n²)) − 1); top_pct the share set to 1 (top_pct < 0: the imputed values, not binarised, as the authors’ prct=-1); n_threads as schicluster_impute(). pca="incremental" (needs n_per_chrom) fits each chromosome’s PCA in batches of cells (scikit-learn’s IncrementalPCA, float32) instead of on a float64 copy of all cells’ features: for 10⁵ cells; the components agree with the full PCA up to sign and rounding.

Returns (features, column_names) — the PCs of all chromosomes, concatenated (chr1_PC1, …).

uchrom.emb.hic.schicluster_impute(mats: ndarray, *, pad: int = 1, rp: float = 0.5, log: bool = True, tol: float = 1e-06, max_iter: int = 30, n_threads: int = 0) → ndarray[source]

scHiCluster’s imputation (module docstring, steps 1-3) of a batch of contact maps (n_cells, n, n) (or one (n, n)): symmetric raw counts with the diagonal once, as a .scool stores them.

log: the authors’ log2(S + diag(S) + 1) (False: the counts as given, S + diag(S)). rp: the weight of the walk as the authors’ code uses it, Q ← (1 − rp) I + rp Q P (their default 0.5; rp=-1 returns the smoothed map without the walk, as their code). Each map stops at its own step. n_threads: maps imputed side by side (0: every CPU this process may use). Returns Q as the authors’ code (not symmetric: (Q + Qᵀ) / 2 symmetrises it).

uchrom.emb.hic.scool_cell_features(scool: str, cell_names: Sequence[str], *, chroms: Sequence[str] | None = None, pad: int = 1, rp: float = 0.5, top_pct: float = 20.0, n_per_chrom: int | None = None, random_state: int = 0, n_threads: int = 0, pca: str = 'full') → Tuple[ndarray, List[str], ndarray][source]

Read one contact map per cell from a .scool and compute schicluster_features().

cell_names are the scool cell names, in the order wanted for the output rows; cells missing from the file get all-zero maps.

Returns (features, column_names, n_contacts_per_cell) (all the contacts of each cell in the file).

Genes for a cell embedding: highly variable genes of a count matrix, added to cd.cells.

highly_variable_genes() ranks the genes of a cells × genes count matrix (Seurat v1 “mean.var.plot”: log-normalise, then z-score the dispersion within bins of mean expression). add_gene_counts() reads the count matrix linked to a ChromData (cd.linked_adata: a linked .h5ad or the copy embedded in an atlas store), picks genes and writes their counts as rna.<gene> columns of cd.cells — what uchrom.emb.embed_cells() (source="rna") and uchrom.emb.marker_features() read.

uchrom.emb.genes.add_gene_counts(cd, genes: Sequence[str] | None = None, *, n_top: int = 2000, n_bins: int = 20, min_frac: float = 0.01, prefix: str = 'rna', replace: bool = True, adata=None) → List[str][source]

Write per-cell counts of genes from the linked count matrix as cd.cells columns rna.<gene>.

The counts come from cd.linked_adata (an .h5ad linked with the store, or the copy embedded in an atlas store, read on first access); its rows are matched to cd.cells by cell id. Without genes the highly_variable_genes() of cd’s cells are taken.

Parameters:
  • cd (ChromData) – With a cells table and a linked AnnData (cells × genes counts in X).

  • genes (sequence of str, optional) – Genes to add (var_names); default: the n_top highly variable genes of the cells of cd.

  • n_top – See highly_variable_genes().

  • n_bins – See highly_variable_genes().

  • min_frac – See highly_variable_genes().

  • prefix (str) – Column names are f"{prefix}.{gene}".

  • replace (bool) – Drop the cd.cells columns that already start with f"{prefix}." (e.g. a smaller gene panel stored with the data), so that embed_cells(cd, source=prefix) uses only the new genes.

  • adata (AnnData, optional) – A count matrix to use instead of cd.linked_adata.

Returns:

The genes added, in the order of their columns (most variable first). The selection is recorded in cd.results[f"{prefix}.genes"] (per gene: mean, dispersion and its z-score, fraction of cells).

Return type:

list of str

uchrom.emb.genes.highly_variable_genes(counts, *, n_top: int = 2000, n_bins: int = 20, min_frac: float = 0.01) → ndarray[source]

Rank genes by their normalised dispersion (Seurat v1, “mean.var.plot”).

Each cell’s counts are scaled to 10,000 and log1p-transformed; per gene, the dispersion log(variance / mean) is z-scored within n_bins equal-width bins of the mean. Genes detected (count > 0) in fewer than min_frac of the cells are left out.

Parameters:
  • counts (array or scipy.sparse matrix) – Cells × genes raw counts.

  • n_top (int) – Number of genes returned.

  • n_bins (int) – Bins of mean expression the dispersion is standardised in.

  • min_frac (float) – Minimum fraction of cells in which a gene is detected.

Returns:

Column indices of the n_top most variable genes, most variable first (fewer when fewer genes pass min_frac).

Return type:

numpy.ndarray

How well cells group: clusters against known labels, neighbourhoods, and what drives an embedding.

uchrom.emb.metrics.cluster_agreement(labels, truth) → Dict[str, float][source]

Adjusted Rand index and normalised mutual information of two labellings of the same cells.

uchrom.emb.metrics.knn_purity(x, truth, *, k: int = 10) → float[source]

Mean fraction of each cell’s k nearest neighbours (Euclidean, the cell itself left out) that share its label.

uchrom.emb.metrics.score_embedding(cd, use: str, truth: str, *, cells: None | str | Sequence = None, n_clusters: int | None = None, k: int = 10, depth: str | None = None, random_state: int = 0) → Dict[str, float][source]

Score an embedding cd.cellm[use] against known labels cd.cells[truth].

  • ARI / NMI: k-means with as many clusters as labels (n_clusters) against the labels;

  • kNN purity: knn_purity() with k neighbours;

  • |r| dim 1 ~ log depth (with depth, a cells column such as the number of contacts): how much the first dimension follows sequencing depth rather than biology.

cells restricts the scoring: cell ids, a boolean mask, or a cells column ("higashi_qc": the cells marked "pass"). Cells with a missing embedding row are left out.

A cell embedding as a scatter plot (matplotlib).

uchrom.emb.plot.plot_embedding(cd, use: str, color: None | str | Sequence = None, *, ax=None, dims: Sequence[int] = (0, 1), palette: Dict[str, object] | None = None, cmap: str = 'viridis', annotate: bool = True, legend: bool = False, colorbar: bool = True, colorbar_label: str | None = None, s: float = 4, title: str | None = None)[source]

Scatter plot of the embedding cd.cellm[use], the cells coloured by a label or a value.

Parameters:
  • cd (ChromData) – With cd.cellm[use] (rows = cd.cells).

  • use (str) – The embedding ("rna_umap", "hic_umap", "higashi", …).

  • color (str or array-like, optional) – A cd.cells column or one value per cell. Text / categorical values are drawn as groups (palette, default tab20 + Dark2), numbers on the colour map cmap with a colour bar. Cells without a value are drawn in light grey.

  • ax (matplotlib Axes, optional) – Where to draw (default: a new figure).

  • dims ((int, int)) – The two dimensions shown (0-based).

  • annotate (bool) – Write each group’s name at the median position of its cells.

  • legend (bool) – Add a legend of the groups.

  • colorbar – For numeric colours: draw a colour bar, with this label (default: the column name).

  • colorbar_label – For numeric colours: draw a colour bar, with this label (default: the column name).

  • s (float) – Marker size.

  • title (str, optional) – Default: the embedding’s label (cd.uns["embeddings"][use]["label"]) and the colour’s name.

Returns:

  • The matplotlib Axes. Cells whose embedding row is missing (NaN) are not drawn; the axes are labelled

  • with the embedding’s axis_prefix (UMAP1, PC2, …).