"""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 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