"""Global 3-D genome features of every cell from its contacts: the share of short- and long-range cis contacts
and their ratio, the slope of the contact-decay curve P(s), the cis fraction and the share of each chromosome's
contacts that are trans — from the contact-distance histograms of :class:`uchrom.io.ContactStats` stored on the
object (``cd.cellm["<key>.distance"]``, ``cd.uns["contact_stats"][key]``).
The short / long-range ratio is that of Guo et al. 2026 by default: contacts closer than 5 kb are left out,
short = 200 kb - 2 Mb and long = 20 - 50 Mb as fractions of the remaining cis contacts (scHiCluster's bins
51-76 and 103-114, :meth:`ContactFeatureParams.guo2026`). A bin counts in a range when its centre (geometric
mean of its edges) lies inside; ``guo2026()`` gives the exact bins of the paper.
Pooled over the chromosomes (the default, as the papers compute them), the features also depend on which
chromosomes the contacts come from: long-range contacts exist only on long chromosomes, and the cis fraction on
how many chromosomes there are. In an aneuploid tissue (a tumour's clones) a gain of small chromosomes raises a
cell's short / long ratio without any change of folding. ``per_chromosome=True`` computes every feature on each
chromosome's own histogram and averages them over a fixed set of chromosomes with equal weights, so a gain or loss
of whole chromosomes leaves them unchanged (a gain of part of a chromosome still shifts that chromosome's
distances).
:func:`chromosome_dosage` reads the same statistics as a copy-number profile: each chromosome's share of a cell's
contact legs, relative to the cells' median share.
"""
from __future__ import annotations
from dataclasses import asdict, dataclass
from typing import Optional, Sequence, Tuple
import numpy as np
import pandas as pd
from ..convention import UNSET
__all__ = ["ContactFeatureParams", "chromosome_dosage", "contact_features"]
def _label(lo: float, hi: float) -> str:
def f(v):
return f"{v / 1e6:g}M" if v >= 1e6 else f"{v / 1e3:g}k"
return f"{f(lo)}_{f(hi)}"
[docs]
def chromosome_dosage(cd, *, key: str = "contacts", cells=None, groupby: Optional[str] = None,
exclude: Sequence[str] = ("chrY",), n_pcs: int = 0, key_added=UNSET, copy: bool = False):
"""Per-cell copy-number profile from the contacts: log2 of each chromosome's share of the cell's contact legs
over the cells' median share.
A cis contact puts two legs on its chromosome, a trans contact one on each of its two. A chromosome present in
three copies instead of two carries about 1.5 times the legs, so the log2 share over the median is about the
log2 of its copies over the typical cell's: a coverage profile at the resolution of whole chromosomes, as a
copy-number caller reads from sequencing depth. It is a proxy. It is relative to the median cell, so a gain
that every cell carries does not show. The shares sum to one, so a gain lowers the other chromosomes a little.
And anything else that changes how many contacts a chromosome gives shifts it too.
Parameters
----------
cd
A ``ChromData`` with ``ContactStats.write(cd, key=key)``.
key
The contact statistics' key.
cells
Only these cells (default all); the median is taken over them.
groupby
A ``cd.cells`` column (section, sample): the median of each group is its cells' reference.
exclude
Chromosomes left out of the shares (default chrY: a few contacts or none).
n_pcs
Also the first ``n_pcs`` principal components of the profiles (each chromosome z-scored over the cells,
missing values at 0; signs arbitrary): the axes along which the cells' profiles differ most. A tumour clone
changes several chromosomes at once, so one component can carry its whole pattern; as covariates they
stand for copy number in a spatial test (:func:`uchrom.spatial.spatially_variable`).
key_added
Where to store (default ``"<key>.dosage"``; None: nothing stored): ``cd.cellm[key_added]`` (n_cells,
n_chroms; NaN for cells left out), ``cd.cellm["<key_added>.pcs"]`` and the table
``cd.results[key_added]``.
Returns
-------
DataFrame
Indexed by cell id (in the order of ``cells``): one column per chromosome, then ``PC1`` ... with
``n_pcs``. A cell without contacts, or a chromosome without legs in a cell, is NaN.
``attrs["pc_variance"]``: the share of the z-scored profiles' variance of each component.
"""
from ..convention import store_and_return
rec = cd.uns.get("contact_stats", {}).get(key)
if rec is None or f"{key}.trans" not in cd.cellm:
raise KeyError(f"no contact statistics {key!r}: run ContactStats.write(cd, key={key!r}) first")
chroms = list(rec["chroms"])
ids = pd.Index([str(c) for c in cd._cell_ids_axis()], name="cell_id")
rows = np.arange(len(ids))
if cells is not None:
rows = ids.get_indexer([str(c) for c in cells])
if (rows < 0).any():
raise KeyError("cells not in cd.cells")
if f"{key}.cis" in cd.cellm:
cis = np.asarray(cd.cellm[f"{key}.cis"])[rows]
else:
dist = np.asarray(cd.cellm[f"{key}.distance"])
if dist.ndim != 3:
raise ValueError(f"the statistics {key!r} have no cis counts per chromosome")
cis = dist[rows].sum(axis=2)
use = [i for i, c in enumerate(chroms) if c not in set(exclude)]
legs = (2 * cis + np.asarray(cd.cellm[f"{key}.trans"])[rows])[:, use].astype(float)
with np.errstate(divide="ignore", invalid="ignore"):
share = legs / legs.sum(axis=1, keepdims=True) # NaN for a cell without legs
groups = (np.zeros(len(rows), int) if groupby is None
else pd.factorize(cd.cells[groupby].to_numpy()[rows])[0])
prof = np.full_like(share, np.nan)
for gi in np.unique(groups[groups >= 0]): # a cell without a group stays NaN
m = groups == gi
if np.isfinite(share[m]).any():
with np.errstate(divide="ignore", invalid="ignore"):
prof[m] = np.log2(share[m] / np.nanmedian(share[m], axis=0))
prof[~np.isfinite(prof)] = np.nan
out = pd.DataFrame(prof, index=ids[rows], columns=[chroms[i] for i in use])
pc_var = []
if n_pcs:
with np.errstate(divide="ignore", invalid="ignore"):
Z = (prof - np.nanmean(prof, axis=0)) / np.nanstd(prof, axis=0, ddof=1)
Z[~np.isfinite(Z)] = 0.0
u, sv, _ = np.linalg.svd(Z, full_matrices=False)
k = min(n_pcs, len(sv))
for j in range(k):
out[f"PC{j + 1}"] = u[:, j] * sv[j]
pc_var = (sv ** 2 / max((sv ** 2).sum(), 1e-300))[:k].tolist()
out.attrs["pc_variance"] = pc_var
if key_added is UNSET:
key_added = f"{key}.dosage"
if key_added is None:
return out
target = cd.copy() if copy else cd
def on_cells(values: np.ndarray) -> np.ndarray:
arr = np.full((len(ids), values.shape[1]), np.nan)
arr[rows] = values
return arr
target.cellm[key_added] = on_cells(prof)
if n_pcs:
target.cellm[f"{key_added}.pcs"] = on_cells(out[[f"PC{j + 1}" for j in range(len(pc_var))]].to_numpy())
store_and_return(target, out.reset_index(), key_added=key_added, copy=False, kind="table",
function="uchrom.fea.chromosome_dosage",
params={"exclude": list(exclude), "groupby": groupby, "n_pcs": int(n_pcs)},
inputs={"contact_stats": key, "chroms": list(out.columns[:len(use)]), "n_cells": int(len(out)),
"pc_variance": pc_var, "source": rec.get("source"), "filter": rec.get("filter")})
return target if copy else out
def _features(h: np.ndarray, centre, lo_e, hi_e, keep, p: ContactFeatureParams) -> dict:
"""The distance features of histograms h (cells x (n_edges + 1)): n_used, the fractions, the ratio, the bands,
the slopes."""
real = h[:, 1:-1]
n_used = real[:, keep].sum(axis=1)
def frac(lo, hi, bins=None):
if bins is not None:
sel = np.zeros(len(centre), bool)
sel[bins[0]:bins[1]] = True
else:
sel = (centre >= lo) & (centre < hi)
sel &= keep
with np.errstate(divide="ignore", invalid="ignore"):
return real[:, sel].sum(axis=1) / n_used
out = {"n_used": n_used, "frac_short": frac(*p.short, bins=p.short_bins),
"frac_long": frac(*p.long, bins=p.long_bins)}
with np.errstate(divide="ignore", invalid="ignore"):
out["short_long_ratio"] = out["frac_short"] / out["frac_long"]
for lo, hi in p.bands:
out[f"frac_{_label(lo, hi)}"] = frac(lo, hi)
width = hi_e - lo_e
for lo, hi in p.slopes:
sel = (centre >= lo) & (centre < hi) & keep
x = np.log10(centre[sel])
with np.errstate(divide="ignore", invalid="ignore"):
yv = np.log10(real[:, sel] / width[sel])
out[f"ps_slope_{_label(lo, hi)}"] = _slopes(x, yv)
return out
def _long_enough(dist: np.ndarray, centre, keep, p: ContactFeatureParams) -> list:
"""The chromosomes whose histogram summed over all cells has at least half the genome-wide share of
long-range contacts (the long range fits on them)."""
pooled = dist.sum(axis=0)[:, 1:-1].astype(float) # chroms x bins
if p.long_bins is not None:
sel = np.zeros(len(centre), bool)
sel[p.long_bins[0]:p.long_bins[1]] = True
else:
sel = (centre >= p.long[0]) & (centre < p.long[1])
sel &= keep
used = pooled[:, keep].sum(axis=1)
with np.errstate(divide="ignore", invalid="ignore"):
share = pooled[:, sel].sum(axis=1) / used
genome = pooled[:, sel].sum() / max(pooled[:, keep].sum(), 1)
return [i for i in range(len(share)) if np.isfinite(share[i]) and share[i] >= 0.5 * genome]
def _slopes(x: np.ndarray, Y: np.ndarray) -> np.ndarray:
"""Least-squares slope of each row of Y on x, over the finite values (NaN with fewer than 3)."""
out = np.full(Y.shape[0], np.nan)
ok = np.isfinite(Y)
for i in range(Y.shape[0]):
m = ok[i]
if m.sum() >= 3:
xm = x[m] - x[m].mean()
out[i] = (xm * (Y[i, m] - Y[i, m].mean())).sum() / (xm ** 2).sum()
return out