Source code for uchrom.fea.contact_decay

"""Contact decay P(s): the contact probability of two loci as a function of their genomic separation.

:func:`contact_ps` sums the raw cis counts of a contact map linked to a ``ChromData`` per diagonal (genomic
separation ``s = k * bin size``), divides by the number of bin pairs on that diagonal and by the total cis
contacts, and fits the power-law exponent (the slope of log10 P(s) on log10 s, OLS, one point per diagonal).
It reads the map where it is — a copy embedded in the store (an atlas store over HTTP: only the partitions of the
chosen chromosomes are read), else the linked local ``.scool`` / ``.cool`` / ``.mcool`` — and takes the scope of
the web browser's Stats pane (``uchrom_browser``, ``stats="ps"``): all chromosomes, one chromosome, or a
genomic window ``[start, end)`` of one chromosome (pixels with both bins in the window); per-cell maps summed
over ``cells`` (default all).  The numbers are those of the browser's ``Dataset.stats_ps`` and of the skill
``call-structures`` (``structures.py ps``).

:func:`log_bin_ps` groups the diagonals into log-spaced bins, the curve the browser draws.

The slope of a pooled map is one number per group of cells: it has no cell-level replication, and it depends on
sequencing depth and on which chromosomes / window it is computed over — compare groups at matched depth (e.g.
:func:`uchrom.fea.sample_cells_by_depth`) before reading a difference as a change of folding.
"""

from __future__ import annotations

from typing import Dict, Iterable, Iterator, List, Optional, Sequence, Tuple

import numpy as np
import pandas as pd

__all__ = ["contact_ps", "log_bin_ps"]

#: a resolution is chosen so that the scope spans at most this many bins (the browser's rule)
MAX_SCOPE_BINS = 25_000
#: pixels read per chunk of a local cooler's pixel table
CHUNK = 2_000_000


# ----------------------------------------------------------------------------------------------------------
# sources: (chromosome, chromosome-local bin1, bin2, count) blocks of the selected chromosomes
# ----------------------------------------------------------------------------------------------------------

class _Embedded:
    def __init__(self, e, cells: Optional[Sequence[str]]):
        self.e = e
        self.per_cell = e.kind == "per_cell"
        self.resolutions = sorted(int(r) for r in e.resolutions)
        self.idx = None
        self.n_cells = len(e.cells) if self.per_cell else None
        if cells is not None:
            if not self.per_cell:
                raise ValueError(f"contact map {e.key!r} is not per-cell: cells= needs per-cell maps")
            index = {c: i for i, c in enumerate(e.cells)}
            idx = [index[str(c)] for c in cells if str(c) in index]
            if not idx:
                raise LookupError(f"none of the cells has a map in {e.key!r}")
            self.idx = sorted(set(idx))
            self.n_cells = len(self.idx)

    def chromsizes(self, res: int) -> Dict[str, int]:
        sizes = self.e.chromsizes(res)
        return {c: int(sizes[c]) for c in self.e.chroms if c in sizes}

    def blocks(self, chrom: str, b0: int, b1: int, res: int) -> Iterator[np.ndarray]:
        part = f"cis/{chrom}"
        if part not in self.e.g[f"r{res}"]:
            return
        if not self.per_cell:
            yield self.e.region_pixels(chrom, b0, b1, res)
        elif self.idx is None and self.e.has_sum(res):
            yield self.e.sum_pixels(part, res)
        else:
            idx = self.idx if self.idx is not None else range(len(self.e.cells))
            yield from self.e.cell_pixel_blocks(part, idx, res)


class _Cooler:
    """A local ``.cool`` / ``.mcool`` level, or the cells of a ``.scool``: pixels read with the bin1 index."""

    def __init__(self, path: str, scool: bool, cells: Optional[Sequence[str]]):
        import h5py

        self.path, self.scool = str(path), scool
        with h5py.File(self.path, "r") as f:
            if scool:
                available = [str(c) for c in f["cells"]]
                if cells is None:
                    names = available
                else:
                    have = set(available)
                    names = [str(c) for c in cells if str(c) in have]
                    if not names:
                        raise LookupError(f"none of the cells has a map in {self.path}")
                self.groups = [f"cells/{c}" for c in names]
                self.n_cells = len(names)
                self.resolutions = [self._binsize(f["cells"][names[0]])]
            else:
                if cells is not None:
                    raise ValueError(f"{self.path} is not per-cell: cells= needs per-cell maps")
                self.n_cells = None
                if "resolutions" in f:
                    self.resolutions = sorted(int(r) for r in f["resolutions"])
                else:
                    self.resolutions = [self._binsize(f)]

    @staticmethod
    def _binsize(grp) -> int:
        b = grp.attrs.get("bin-size")
        if b is None or (isinstance(b, str) and b == "None"):
            raise ValueError("P(s) needs uniform bins (the map has no bin-size)")
        return int(b)

    def _group(self, f, res: int):
        if self.scool:
            return [f[g] for g in self.groups]
        return [f[f"resolutions/{res}"] if "resolutions" in f else f]

    def chromsizes(self, res: int) -> Dict[str, int]:
        import h5py

        with h5py.File(self.path, "r") as f:
            g = self._group(f, res)[0]
            names = np.asarray(g["chroms/name"][:]).astype(str)
            lengths = np.asarray(g["chroms/length"][:], np.int64)
        return {str(c): int(n) for c, n in zip(names, lengths)}

    def blocks(self, chrom: str, b0: int, b1: int, res: int) -> Iterator[np.ndarray]:
        import h5py

        with h5py.File(self.path, "r") as f:
            groups = self._group(f, res)
            if not groups:
                return
            # the cells of a .scool share one bin table: the chromosome's first bin is read once
            names = list(np.asarray(groups[0]["chroms/name"][:]).astype(str))
            if chrom not in names:
                return
            first = int(np.asarray(groups[0]["indexes/chrom_offset"][names.index(chrom)]))
            for g in groups:
                off = np.asarray(g["indexes/bin1_offset"][first + b0: first + b1 + 1], np.int64)
                s0, s1 = int(off[0]), int(off[-1])
                px = g["pixels"]
                for s in range(s0, s1, CHUNK):
                    e = min(s1, s + CHUNK)
                    yield np.column_stack([px["bin1_id"][s:e].astype(np.int64) - first,
                                           px["bin2_id"][s:e].astype(np.int64) - first,
                                           px["count"][s:e].astype(np.int64)])


def _source(cd, contacts: Optional[str], cells):
    """(source, key) of the map ``contacts`` (default: the first per-cell map, else the first bulk map)."""
    from chromdata.cdata import _linked_records

    scool = _linked_records(cd.uns.get("linked_scool"))
    cool = _linked_records(cd.uns.get("linked_cool"))
    embedded = cd.embedded_links()["contacts"] if hasattr(cd, "embedded_links") else {}
    if contacts is None:
        keys = list(scool) + [k for k in cool if k not in scool] + [k for k in embedded if k not in scool
                                                                    and k not in cool]
        if not keys:
            raise KeyError("no contact map is linked to this object (cd.link_scool / cd.link_cool)")
        contacts = keys[0]
    contacts = str(contacts)
    if contacts in embedded:                          # the embedded copy first: no file, no cooler / h5py
        from chromdata.embedded import EmbeddedContacts

        return _Embedded(EmbeddedContacts(str(cd._links_from()), embedded[contacts]), cells), contacts
    for records, per in ((scool, True), (cool, False)):
        if contacts in records:
            path = cd.resolve_link_path(records[contacts]["path"])
            if not path.exists():
                raise FileNotFoundError(f"contact map {contacts!r}: {path} does not exist and it is not embedded")
            return _Cooler(str(path), per, cells), contacts
    raise KeyError(f"contacts={contacts!r} is not a linked or embedded map; linked: "
                   f"{sorted(set(scool) | set(cool) | set(embedded))}")


# ----------------------------------------------------------------------------------------------------------
# P(s)
# ----------------------------------------------------------------------------------------------------------

def _fit(s: np.ndarray, p: np.ndarray, smin, smax) -> Tuple[Optional[float], Optional[float], Optional[list]]:
    ok = (p > 0) & np.isfinite(p)
    if smin is not None:
        ok &= s >= float(smin)
    if smax is not None:
        ok &= s <= float(smax)
    if int(ok.sum()) < 3:
        return None, None, None
    slope, icpt = np.polyfit(np.log10(s[ok]), np.log10(p[ok]), 1)
    return float(slope), float(icpt), [int(s[ok][0]), int(s[ok][-1])]


[docs] def contact_ps(cd, contacts: Optional[str] = None, *, chrom: Optional[str] = None, start: Optional[int] = None, end: Optional[int] = None, cells: Optional[Iterable] = None, resolution: Optional[int] = None, smin: Optional[float] = None, smax: Optional[float] = None, key_added: Optional[str] = None, copy: bool = False): """Contact probability P(s) of a linked contact map and its power-law slope. Parameters ---------- cd A ``ChromData`` with a contact map linked (``cd.link_scool`` / ``cd.link_cool``) or embedded in its store. contacts The map's key (default: the first per-cell map, else the first bulk map). chrom One chromosome (default: every chromosome of the map, their diagonals summed). start, end A window ``[start, end)`` of ``chrom`` (bp): only pixels with both bins in the bins that overlap it. cells Per-cell maps: the cells summed (default all). resolution Bin size (default: the finest level at which the scope spans at most 25,000 bins). smin, smax The separations (bp) of the fit (default: every diagonal from one bin up). key_added ``cd.results`` key of the table (default ``None``: not stored). copy Return a new ``ChromData`` holding the result. Returns ------- DataFrame One row per diagonal ``k >= 1``: ``s_bp`` (= k * resolution), ``n_pairs`` (bin pairs on the diagonal in the scope), ``n_contacts`` (raw counts), ``p`` (= n_contacts / n_pairs / total cis contacts). ``attrs``: ``slope``, ``intercept`` (of log10 P on log10 s over the diagonals with ``p > 0``), ``fit_range_bp``, ``total_cis_contacts`` (diagonal 0 included), ``resolution``, ``n_cells``, ``contacts``, ``chrom``, ``start``, ``end``. """ from ..convention import store_and_return if (start is not None or end is not None) and chrom is None: raise ValueError("start / end need one chromosome (chrom=)") src, key = _source(cd, contacts, None if cells is None else list(cells)) resolutions = src.resolutions sizes0 = src.chromsizes(resolutions[0]) if chrom is not None and str(chrom) not in sizes0: raise ValueError(f"unknown chromosome {chrom!r} in contact map {key!r}") lo = hi = None if start is not None or end is not None: clen = sizes0[str(chrom)] lo = max(0, 0 if start is None else int(start)) hi = clen if end is None else min(clen, int(end)) if start is not None and end is not None and int(end) <= int(start): raise ValueError("end must be greater than start") if hi <= lo: raise ValueError("empty window") if resolution is not None: res = int(resolution) if res not in resolutions: raise ValueError(f"resolution must be one of {resolutions}") else: span = (hi - lo) if lo is not None else (sizes0[str(chrom)] if chrom is not None else sum(sizes0.values())) res = next((r for r in resolutions if r > 0 and span / r <= MAX_SCOPE_BINS), resolutions[-1]) sizes = src.chromsizes(res) chroms = [str(chrom)] if chrom is not None else list(sizes) ranges = {} for c in chroms: n = -(-int(sizes.get(c, 0)) // res) b0 = 0 if lo is None else lo // res b1 = n if hi is None else min(n, -(-hi // res)) if b1 - b0 >= 1: ranges[c] = (b0, b1) width = max((b1 - b0 for b0, b1 in ranges.values()), default=0) diag = np.zeros(width, np.float64) pairs = np.zeros(width, np.int64) for c, (b0, b1) in ranges.items(): nc = b1 - b0 if nc < 2: continue pairs[:nc] += nc - np.arange(nc, dtype=np.int64) for d in src.blocks(c, b0, b1, res): if not len(d): continue ok = (d[:, 0] >= b0) & (d[:, 1] < b1) & (d[:, 1] >= d[:, 0]) if ok.any(): diag[:nc] += np.bincount(d[ok, 1] - d[ok, 0], weights=d[ok, 2].astype(np.float64), minlength=nc) total = float(diag.sum()) k = np.arange(1, width, dtype=np.int64) keep = pairs[1:] > 0 k, n_pairs, n_contacts = k[keep], pairs[1:][keep], diag[1:][keep] with np.errstate(divide="ignore", invalid="ignore"): p = (n_contacts / n_pairs) / total if total > 0 else np.zeros(len(k)) s = k * res out = pd.DataFrame({"s_bp": s, "n_pairs": n_pairs, "n_contacts": n_contacts, "p": p}) slope, icpt, rng = _fit(s.astype(np.float64), p, smin, smax) if total > 0 else (None, None, None) out.attrs.update(slope=slope, intercept=icpt, fit_range_bp=rng, total_cis_contacts=total, resolution=int(res), n_cells=src.n_cells, contacts=key, chrom=None if chrom is None else str(chrom), start=lo, end=hi) if key_added is None: return cd.copy() if copy else out target = store_and_return(cd, out, key_added=key_added, copy=copy, kind="table", function="uchrom.fea.contact_ps", params={"chrom": chrom, "start": lo, "end": hi, "resolution": int(res), "smin": smin, "smax": smax}, inputs={"contacts": key, "n_cells": src.n_cells, "slope": slope}) return target
[docs] def log_bin_ps(ps: pd.DataFrame, n_bins: int = 24) -> pd.DataFrame: """The diagonals of :func:`contact_ps` in ``n_bins`` log-spaced bins of separation (the browser's curve). Each bin: ``s_bp`` = geometric mean of its first and last separation, ``p`` = its contacts over its bin pairs over the total cis contacts; bins without contacts are left out. """ res = int(ps.attrs.get("resolution") or (ps["s_bp"].iloc[0] if len(ps) else 1)) total = float(ps.attrs.get("total_cis_contacts") or 0.0) cols = ["s_bp", "p", "n_pairs", "n_contacts"] if not len(ps) or total <= 0: return pd.DataFrame(columns=cols) k = (ps["s_bp"].to_numpy() // res).astype(np.int64) edges = np.geomspace(1.0, float(k[-1]) + 1e-4, int(n_bins) + 1) which = np.digitize(k, edges) - 1 rows = [] for b in range(int(n_bins)): m = which == b c = float(ps["n_contacts"].to_numpy()[m].sum()) if not m.any() or c <= 0: continue npairs = int(ps["n_pairs"].to_numpy()[m].sum()) rows.append((float(np.sqrt(k[m][0] * res * k[m][-1] * res)), c / npairs / total, npairs, c)) out = pd.DataFrame(rows, columns=cols) out.attrs.update(ps.attrs) return out