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"(rnaand unknown prefixes)log1pthen z-score per feature (optionally library-size first)."zscore"(if,protein,ab)continuous intensities: z-score per feature,
log=Trueaddslog1p."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_tracksseen per spot) into per-cell features.On a backed
ChromData(ChromData.read(..., backed=True), an atlas store fromuchrom.datasets.load) the spots are streamed in batches ofbatchcells (iter_cells()), reading only the coordinates’ keys and thefieldstracks, so the whole table is never in memory; give several statistics instatto compute them in the same pass.- Parameters:
cd (ChromData) – With tracks and a
cell_idcolumn incd.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 withstat="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
cdis backed.
- Returns:
DataFrame indexed like
cd.cells(cells without spots are NaN) — or,when
statis 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) ofcd.cellm[use](firstn_componentscolumns) is partitioned with the Leiden algorithm (leidenalg, RB configuration model atresolution, seeded). Clusters are numbered"0", "1", …by decreasing size and stored as a categorical columncd.cells[key_added](defaultf"leiden_{use}"); the parameters go tocd.uns["clusters"][key_added]. Cells whose embedding row is missing (NaN: not embedded, seeembed_cells(cells=)) get no label. Needsleidenalgandpython-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 outputsf"{source}_{method}"(rna_pca,if_umap,atac_lsi, …).fields (sequence of str, optional) – Explicit
cd.cellscolumns to use instead of the prefix.matrix (array or scipy.sparse matrix, optional) – cells × features input instead of
cd.cellscolumns (rows incd.cellsorder, or in the order ofcells) — e.g. a genome-wide ATAC bin matrix too large to keep as cell columns. Describe it withfeatures=.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:log1pfirst (needs non-negative intensities).methods (subset of
("pca", "tsne", "umap")) – With"tfidf"the linear step is LSI and is stored asf"{source}_lsi". UMAP needsumap-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 beforelog1p(seenormalize_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 followcells.copy (bool) – Return a new
ChromDataholding the embeddings instead of modifyingcd.
- Returns:
dict mapping cellm key → array (also written to
cd.cellm) — or, withcopy=True, the newChromData.
- 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
prefixcolumns ofcd.cellsranked by the difference of the mean (log1pwhenlog) between the group and the other cells.
- uchrom.emb.cells.normalize_counts(counts: ndarray, *, library_size: bool = False) ndarray[source]¶
log1pand 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). UseTruefor 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) andRunSVD(each component scaled to mean 0, sd 1). Dense orscipy.sparseinput; 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; passdrop_depth_r=Noneto 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
embrows to matchcd_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, keycontacts; or embedded in an atlas store).The Higashi inputs (one contact table per cell, label info, chromosome sizes,
config.JSON) are written from the.scoolunderwork_dir, FastHigashi runs there (its output goes towork_dir/fasthigashi.logwithlog=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=Truealso stores every otherembed_*variant ascd.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 incd.cellm[key_added], FastHigashi’s QC incd.cells[key_added + "_qc"], the settings incd.uns[key_added]andcd.uns["embeddings"], the call incd.results) — or a newChromDataholding 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
cellsframe containingcell_id_col.contacts_dir (path) – Directory produced by
uchrom.io.write_higashi_inputs(). Must containconfig.JSONandlabel_info.pickle.which ({"fast", "full"}) – FastHigashi (default) or full Higashi.
rank (int) – Tucker rank passed to FastHigashi’s
run_modeland used asfinal_diminfetch_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(letswrite_higashi_inputsand FastHigashi share one directory tree).cache_dir (path, optional) – Where FastHigashi caches per-cell tensors and writes results. Default to
contacts_dir(letswrite_higashi_inputsand 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_convetc.).run_model_kwargs (dict, optional) – Forwarded to
run_model.rankfrom the top-level kwarg wins unless explicitly overridden here.
- Returns:
The same
cdobject, mutated in place.- Return type:
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):
A = log2(S + diag(S) + 1)— the authors buildA + Aᵀfrom the upper triangle, which counts the diagonal twice;the
(2·pad+1)²mean filter, zeros outside the map (by cumulative sums, rounded to 8 decimals, as the code);the random walk with restart: the diagonal set to 0, then to 1 in the columns without contacts,
Pthe column-normalised map,Q ← (1 − rp)·I + rp·Q·PfromQ = Iuntil the Frobenius norm of the change is belowtol(1e-6), at mostmax_iter(30) steps, each cell on its own;the features:
Qof every cell flattened (alln²entries), set to 1 above the cell’s100 − top_pctpercentile and 0 elsewhere; per chromosome a PCA across the cells withint(0.2 · min(cells, n²)) − 1components (the authors’ rule;n_per_chromsets 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 fixedn_per_chromsuch 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, keycontacts; 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 (toptop_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 withcd.linked_scool_path(contacts, cells=..., trans=False): the linked.scoolitself, 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 useuchrom.emb.embed_higashi().- Parameters:
cd (ChromData) – With
cellsand 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; seeschicluster_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; seeschicluster_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; seeschicluster_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; seeschicluster_features()).pca (
"full"or"incremental") – How each chromosome’s PCA is fitted (schicluster_features());"incremental"(withn_per_chrom) for 10⁵ cells.methods – Passed to
uchrom.emb.embed_cells()(random_statealso seeds the per-chromosome PCAs).n_pcs – Passed to
uchrom.emb.embed_cells()(random_statealso seeds the per-chromosome PCAs).random_state – Passed to
uchrom.emb.embed_cells()(random_statealso seeds the per-chromosome PCAs).key_added (str) – Names the outputs:
cd.cellm[f"{key_added}_pca"](_tsne,_umap), registered incd.uns["embeddings"]as the Hi-C modality; the number of contacts used per cell (intra- chromosomal, ofchroms) incd.cells[f"{key_added}_n_cis_contacts"]; the settings incd.uns[key_added]; the scHiCluster features (cells × the PCs of every chromosome, float32, on the cells axis) incd.results[key_added]with the call’s provenance.copy (bool) – Return a new
ChromDataholding the results instead of modifyingcd.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 newChromData(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_chrommaps chrom → either an(n_cells, n, n)array of raw counts or a callablef(lo, hi) -> (hi - lo, n, n)array for a batch of cells (so all maps never need to be dense at once) together withn_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_pctthe share set to 1 (top_pct < 0: the imputed values, not binarised, as the authors’prct=-1);n_threadsasschicluster_impute().pca="incremental"(needsn_per_chrom) fits each chromosome’s PCA in batches of cells (scikit-learn’sIncrementalPCA, 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.scoolstores 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=-1returns 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). ReturnsQas the authors’ code (not symmetric:(Q + Qᵀ) / 2symmetrises 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
.scooland computeschicluster_features().cell_namesare 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.cellscolumnsrna.<gene>.The counts come from
cd.linked_adata(an.h5adlinked with the store, or the copy embedded in an atlas store, read on first access); its rows are matched tocd.cellsby cell id. Withoutgenesthehighly_variable_genes()ofcd’s cells are taken.- Parameters:
cd (ChromData) – With a
cellstable and a linked AnnData (cells × genes counts inX).genes (sequence of str, optional) – Genes to add (
var_names); default: then_tophighly variable genes of the cells ofcd.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.cellscolumns that already start withf"{prefix}."(e.g. a smaller gene panel stored with the data), so thatembed_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:
- 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 dispersionlog(variance / mean)is z-scored withinn_binsequal-width bins of the mean. Genes detected (count > 0) in fewer thanmin_fracof the cells are left out.- Parameters:
- Returns:
Column indices of the
n_topmost variable genes, most variable first (fewer when fewer genes passmin_frac).- Return type:
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
knearest 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 labelscd.cells[truth].ARI/NMI: k-means with as many clusters as labels (n_clusters) against the labels;kNN purity:knn_purity()withkneighbours;|r| dim 1 ~ log depth(withdepth, a cells column such as the number of contacts): how much the first dimension follows sequencing depth rather than biology.
cellsrestricts 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.cellscolumn or one value per cell. Text / categorical values are drawn as groups (palette, defaulttab20+Dark2), numbers on the colour mapcmapwith a colour bar. Cells without a value are drawn in light grey.ax (matplotlib Axes, optional) – Where to draw (default: a new figure).
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, …).