Contact decay, per-cell Rg and the browser’s Stats pane¶
Two summaries describe how compact chromatin is, whatever the assay: for contact maps, the contact decay
P(s) — the probability that two loci s bp apart are in contact, which falls roughly as a power law
P(s) ∝ s^α; for 3-D coordinates, the radius of gyration (Rg) of each traced chromosome segment. This
tutorial computes both on real data, over the whole genome and in a genomic window [start, end),
compares groups of cells, and then shows the same numbers in the web browser’s Stats pane, driven from
Python and from the uchrom-web command line that coding agents use.
uchrom.fea.contact_ps(cd, chrom=, start=, end=, cells=)— P(s) of the contact map linked to (or embedded in) aChromData, summed over the chosen cells, with its power-law slope (OLS of log10 P on log10 s, one point per diagonal);log_bin_psgives the log-binned curve that the browser draws;uchrom.fea.radius_of_gyration(cd, chrom, start=, end=)— Rg per trace, of the spots inside a window;the browser:
Contact decay P(s)andRg per tracecharts with the scopes all chromosomes / locus chromosome / locus window, groups compared, Rg per cell (median of its traces) with a Mann–Whitney test.
Data
Kim et al. 2020 sci-Hi-C (PLoS Comput. Biol. 16:e1008173, Noble lab; library H1Esc-HFF.R1): 1,931 cells of a mix of H1 embryonic stem cells and HFF fibroblasts with their cell types, 500 kb contact maps per cell —
ds.load("kim2020_scihic")builds it once from the authors’ files (128 MB) and links the maps as a.scool.Cheng et al. 2026 chromatin tracing (Science, Zenodo 19959235): IGH (48 loci of 10 kb, chr14:105.50–105.98 Mb, hg38) and IGL in 36,089 RAD21-degron Ramos cells after 0, 2, 6 and 12 h of dTAG — the atlas store
cheng2026_ramos_igh_igl, opened backed over HTTP; only the chr14 coordinates are read (2.1 M spots).
Runtime: about 3 minutes on a laptop (most of it summing the per-cell maps genome-wide). The last part starts
the browser in this process and opens it in a headless Chromium (Playwright,
pip install playwright && playwright install chromium); it is skipped without Playwright.
import importlib.util
import json
import subprocess
import sys
import time
from pathlib import Path
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from scipy.stats import mannwhitneyu
import uchrom.datasets as ds
from uchrom.fea import contact_ps, log_bin_ps, radius_of_gyration, sample_cells_by_depth
plt.rcParams["figure.dpi"] = 90
OUT = Path("_out") / "contact_decay_rg"; OUT.mkdir(parents=True, exist_ok=True) # outputs: tutorials/_out/ (ignored by git)
T0 = time.time()
1. Contact decay P(s) of single-cell Hi-C¶
ds.load("kim2020_scihic") gives a ChromData without coordinates: the cells with their type and number of
contacts, and the per-cell maps linked under the key per_cell. The two cell types differ in depth: an H1Esc
cell has almost three times the contacts of an HFF cell.
hic = ds.load("kim2020_scihic") # built once from the authors' files; the per-cell maps linked (.scool)
print(hic)
CT = hic.cells["cell_type"].astype(str)
GROUPS = ["H1Esc", "HFF"]
hic.cells.groupby("cell_type")["n_contacts"].agg(cells="size", contacts="sum", median_per_cell="median")
ChromData: n_spots=0, n_traces=0, n_cells=1931, n_bins=0
spots: ['chrom', 'start', 'end', 'trace_id', 'cell_id', 'bin_id']
cells: ['cell_type', 'n_contacts'] (1931 cells)
uns: ['genome_assembly', 'source', 'linked_scool', 'dataset']
| cells | contacts | median_per_cell | |
|---|---|---|---|
| cell_type | |||
| H1Esc | 750 | 13777141 | 8180.5 |
| HFF | 1181 | 5634189 | 2898.0 |
contact_ps sums the raw counts of the chosen cells per diagonal, over every chromosome by default. P(s) on
diagonal k (separation s = k × 500 kb) is the mean count per bin pair on that diagonal divided by the total
cis contacts, so curves of groups of different depth are on one scale. The table has one row per diagonal; the
slope and the rest are in attrs. With chrom=, start=, end= only the pixels with both bins in the window
count — here the first 100 Mb of chr1, all on its p arm (the centromere is at 121–125 Mb in hg19).
WINDOW = dict(chrom="chr1", start=0, end=100_000_000)
ps = {}
for g in GROUPS + ["all"]:
cells = None if g == "all" else CT.index[CT == g]
ps[g, "genome"] = contact_ps(hic, cells=cells) # all chromosomes
ps[g, "window"] = contact_ps(hic, cells=cells, **WINDOW) # chr1:[0, 100 Mb)
ps["H1Esc", "window"].head()
| s_bp | n_pairs | n_contacts | p | |
|---|---|---|---|---|
| 0 | 500000 | 199 | 89642.0 | 0.001058 |
| 1 | 1000000 | 198 | 26053.0 | 0.000309 |
| 2 | 1500000 | 197 | 12349.0 | 0.000147 |
| 3 | 2000000 | 196 | 7313.0 | 0.000088 |
| 4 | 2500000 | 195 | 5102.0 | 0.000061 |
def summary(t):
a = t.attrs
return {"cells": a["n_cells"], "cis contacts": int(a["total_cis_contacts"]), "bin (kb)": a["resolution"] // 1000,
"diagonals": len(t), "slope": a["slope"]}
slopes = pd.DataFrame({(g, scope): summary(t) for (g, scope), t in ps.items()}).T
slopes.index.names = ["group", "scope"]
slopes.style.format({"slope": "{:.3f}"})
| cells | cis contacts | bin (kb) | diagonals | slope | ||
|---|---|---|---|---|---|---|
| group | scope | |||||
| H1Esc | genome | 750.000000 | 11388784.000000 | 500.000000 | 498.000000 | -0.655 |
| window | 750.000000 | 425626.000000 | 500.000000 | 199.000000 | -1.478 | |
| HFF | genome | 1181.000000 | 4715456.000000 | 500.000000 | 498.000000 | -0.704 |
| window | 1181.000000 | 183213.000000 | 500.000000 | 199.000000 | -0.995 | |
| all | genome | 1931.000000 | 16104240.000000 | 500.000000 | 498.000000 | -0.677 |
| window | 1931.000000 | 608839.000000 | 500.000000 | 199.000000 | -1.252 |
Genome-wide, both cell types decay with a slope near −0.7 (H1Esc −0.66, HFF −0.70). Within chr1:0–100 Mb the
curves separate: H1Esc falls as s^−1.48, HFF as s^−0.99. Part of the difference is the range of the fit: over all
chromosomes it runs to 250 Mb, where few bin pairs remain and the curve turns up again (figure below). smax=
(and smin=) limit the fit without changing the curve:
pd.DataFrame({g: {"all chromosomes, s <= 100 Mb": contact_ps(hic, cells=CT.index[CT == g], smax=100e6).attrs["slope"],
"chr1, s <= 100 Mb": contact_ps(hic, cells=CT.index[CT == g], chrom="chr1", smax=100e6).attrs["slope"],
"chr1:0-100 Mb": ps[g, "window"].attrs["slope"]} for g in GROUPS}).round(3)
| H1Esc | HFF | |
|---|---|---|
| all chromosomes, s <= 100 Mb | -1.215 | -1.102 |
| chr1, s <= 100 Mb | -1.268 | -1.132 |
| chr1:0-100 Mb | -1.478 | -0.995 |
Fitted up to 100 Mb, the slopes over all chromosomes are steeper (H1Esc −1.22, HFF −1.10), and so is chr1 as a whole (−1.27, −1.13); the window, which leaves out the q arm and every contact between the arms, separates the cell types most. The scope is part of the result: report it with the slope.
COL = {"H1Esc": "#d62728", "HFF": "#1f77b4", "all": "0.4"}
fig, axes = plt.subplots(1, 2, figsize=(10, 4), sharey=False)
for ax, scope, title in zip(axes, ["genome", "window"], ["all chromosomes", "chr1:0-100 Mb"]):
for g in GROUPS + ["all"]:
t = ps[g, scope]
b = log_bin_ps(t) # the browser's 24 log-spaced bins
a = t.attrs
ax.loglog(b["s_bp"], b["p"], "o-", ms=3, color=COL[g], lw=1.5 if g != "all" else 1,
label=f"{g} (n={a['n_cells']}): slope {a['slope']:.2f}")
s = t["s_bp"].to_numpy(float)
ax.loglog(s, 10 ** (a["intercept"] + a["slope"] * np.log10(s)), ":", color=COL[g], lw=1)
ax.set(title=title, xlabel="genomic separation s (bp)")
ax.legend(fontsize=8, frameon=False)
axes[0].set_ylabel("contact probability P(s)")
fig.tight_layout()
Depth¶
A slope from a pooled map is one number per group, without replicates, and it depends on depth: sparse maps lose
long-range contacts first. sample_cells_by_depth draws disjoint sets of cells holding the same number of
contacts — here sets of 2 M contacts, up to three per cell type (HFF has enough contacts for two) — and each set
gets its own slope.
import warnings
with warnings.catch_warnings():
warnings.simplefilter("ignore") # it warns that HFF has contacts for two sets only
sets = sample_cells_by_depth(hic, "cell_type", n_contacts=2e6, replicates=3)
rows = []
for name, idx in sets.groupby("set").groups.items():
g = sets.loc[idx, "group"].iloc[0]
rows.append({"set": name, "group": g, "cells": len(idx),
"genome-wide slope": contact_ps(hic, cells=idx).attrs["slope"],
"chr1:0-100 Mb slope": contact_ps(hic, cells=idx, **WINDOW).attrs["slope"]})
matched = pd.DataFrame(rows).set_index("set")
display(matched.round(3))
matched.groupby("group")[["genome-wide slope", "chr1:0-100 Mb slope"]].agg(["min", "max"]).round(3)
| group | cells | genome-wide slope | chr1:0-100 Mb slope | |
|---|---|---|---|---|
| set | ||||
| H1Esc | 1 | H1Esc | 129 | -0.690 | -1.536 |
| H1Esc | 2 | H1Esc | 154 | -0.668 | -1.373 |
| H1Esc | 3 | H1Esc | 155 | -0.645 | -1.325 |
| HFF | 1 | HFF | 359 | -0.706 | -1.006 |
| HFF | 2 | HFF | 472 | -0.701 | -0.961 |
| genome-wide slope | chr1:0-100 Mb slope | |||
|---|---|---|---|---|
| min | max | min | max | |
| group | ||||
| H1Esc | -0.690 | -0.645 | -1.536 | -1.325 |
| HFF | -0.706 | -0.701 | -1.006 | -0.961 |
At matched depth the window slopes stay apart — H1Esc −1.33 to −1.54, HFF −0.96 to −1.01 — while the genome-wide slopes overlap (H1Esc −0.65 to −0.69, HFF −0.70 to −0.71): the genome-wide difference of the full groups is within the spread of random sets of cells, the windowed one is not. Sets of cells are not biological replicates (all cells come from one experiment), so this is a check of robustness to depth and sampling, not a test.
The same numbers in the browser and the agent skill¶
The browser’s Stats pane computes P(s) on the server (uchrom_browser.data.Dataset.stats_ps, the endpoint
/api/datasets/{id}/stats/ps) and the agent skill call-structures has its own reader
(skills/call-structures/scripts/structures.py ps, one chromosome at a time). All three read the same pixels:
from uchrom_browser.data import Dataset
browser = Dataset(id="d1", name="kim2020_scihic", path=str(hic._links_from()), cd=hic)
spec = importlib.util.spec_from_file_location("structures", "../skills/call-structures/scripts/structures.py")
skill = importlib.util.module_from_spec(spec); spec.loader.exec_module(skill)
rows = []
for g in GROUPS + ["all"]:
cells = None if g == "all" else list(CT.index[CT == g])
group = None if g == "all" else f"field:cell_type={g}"
for label, scope in [("all chromosomes", {}), ("chr1", {"chrom": "chr1"}), ("chr1:0-100 Mb", WINDOW)]:
lib = contact_ps(hic, cells=cells, **scope)
b = browser.stats_ps(group=group, **scope)
row = {"group": g, "scope": label, "slope (uchrom.fea)": lib.attrs["slope"],
"browser - fea": b["slope"] - lib.attrs["slope"],
"browser curve = log_bin_ps": np.array_equal(b["p"], log_bin_ps(lib)["p"].to_numpy())}
if "chrom" in scope: # the skill takes one chromosome
s = skill.contact_ps(hic, scope["chrom"], cells=cells, start=scope.get("start"), end=scope.get("end"))
row["skill - fea"] = s["slope"] - lib.attrs["slope"]
rows.append(row)
pd.DataFrame(rows).set_index(["group", "scope"])
| slope (uchrom.fea) | browser - fea | browser curve = log_bin_ps | skill - fea | ||
|---|---|---|---|---|---|
| group | scope | ||||
| H1Esc | all chromosomes | -0.655023 | 0.0 | True | NaN |
| chr1 | -0.655170 | 0.0 | True | 0.0 | |
| chr1:0-100 Mb | -1.478428 | 0.0 | True | 0.0 | |
| HFF | all chromosomes | -0.703733 | 0.0 | True | NaN |
| chr1 | -0.715547 | 0.0 | True | 0.0 | |
| chr1:0-100 Mb | -0.994509 | 0.0 | True | 0.0 | |
| all | all chromosomes | -0.676876 | 0.0 | True | NaN |
| chr1 | -0.680080 | 0.0 | True | 0.0 | |
| chr1:0-100 Mb | -1.252488 | 0.0 | True | 0.0 |
The slopes agree to the last bit (difference 0.0) and the browser’s curve is log_bin_ps of the library’s
table. contact_ps reads the map where it is: the copy embedded in a store when there is one (an atlas store
over HTTP: only the chosen chromosome partitions are read, no cooler needed), else the linked .scool /
.cool / .mcool.
2. Rg per cell in a genomic window of chromatin tracing¶
The atlas store cheng2026_ramos_igh_igl holds the IGH and IGL traces of RAD21-degron Ramos cells. (ds.load
of this id would build it from the 2.65 GB original files; ds.atlas opens the published store over HTTP.)
get_chrom("chr14", columns="coords") reads the IGH coordinates only.
ramos = ds.atlas("cheng2026_ramos_igh_igl") # backed, over HTTP
print(ramos)
t0 = time.time()
igh = ramos.get_chrom("chr14", columns="coords") # IGH: one partition of the store
print(f"chr14: {igh.n_spots:,} spots, {igh.n_traces:,} traces, {igh.n_cells:,} cells read in {time.time() - t0:.0f} s")
ramos.cells.groupby("dtag_time", sort=False).size().rename("cells").to_frame().T
ChromData (backed: cheng2026_ramos_igh_igl.chromdata.zarr): n_spots=2643267, n_traces=101982, n_cells=36089, n_bins=73
spots: ['chrom', 'start', 'end', 'trace_id', 'cell_id', 'bin_id']
cells: ['dtag_time', 'fov', 'cell_label', 'n_traces', 'replicate'] (36089 cells)
traces: ['cell_id', 'chrom', 'CellLableAssign', 'rg', 'label_value_1', 'label_value_2', 'label_value_3', 'label_value_4', 'center_x', 'center_y', 'library'] (101982 traces)
uns: ['genome_assembly', 'xyz_unit', 'source', 'dataset']
chr14: 2,097,957 spots, 64,851 traces, 34,443 cells read in 4 s
| dtag_time | 0 h | 2 h | 6 h | 12 h |
|---|---|---|---|---|
| cells | 7256 | 11850 | 12006 | 4977 |
First a check against the authors: their MATLAB files carry an Rg per trace (ramos.traces["rg"], over every
detected locus of the trace). radius_of_gyration on the whole traces gives the same values:
rg_full = radius_of_gyration(igh, "chr14")
authors = ramos.traces["rg"].reindex(rg_full.index)
ok = authors.notna() & rg_full.notna()
print(f"{ok.sum():,} IGH traces: max |ours - authors'| = {(rg_full[ok] - authors[ok]).abs().max():.1e} µm")
64,851 IGH traces: max |ours - authors'| = 4.4e-16 µm
Now a window inside the locus, chr14:105.55–105.85 Mb (30 of the 48 loci): only spots whose locus overlaps
[start, end) count, and a trace with fewer than two of them gets NaN (dropped). A cell can have several IGH traces,
so the unit of comparison is the
cell: the median Rg of its traces.
IGH_WINDOW = dict(start=105_550_000, end=105_850_000)
TIMES = ["0 h", "2 h", "6 h", "12 h"]
rg = radius_of_gyration(igh, "chr14", **IGH_WINDOW).dropna()
trace_cell = igh.spots.drop_duplicates("trace_id").set_index("trace_id")["cell_id"].astype(str)
per_trace = pd.DataFrame({"rg": rg, "cell_id": trace_cell.reindex(rg.index).to_numpy()})
per_cell = per_trace.groupby("cell_id")["rg"].median().rename("rg").to_frame()
per_cell["dtag_time"] = ramos.cells["dtag_time"].astype(str).reindex(per_cell.index).to_numpy()
by_time = per_cell.groupby("dtag_time")["rg"].agg(cells="size", median="median",
q25=lambda x: x.quantile(0.25), q75=lambda x: x.quantile(0.75))
by_time.loc[TIMES].round(3)
| cells | median | q25 | q75 | |
|---|---|---|---|---|
| dtag_time | ||||
| 0 h | 6958 | 0.232 | 0.200 | 0.271 |
| 2 h | 11403 | 0.261 | 0.224 | 0.304 |
| 6 h | 11408 | 0.265 | 0.228 | 0.306 |
| 12 h | 4674 | 0.277 | 0.237 | 0.320 |
a = per_cell.loc[per_cell["dtag_time"] == "0 h", "rg"]
b = per_cell.loc[per_cell["dtag_time"] == "12 h", "rg"]
mw = mannwhitneyu(a, b, alternative="two-sided") # tie- and continuity-corrected normal approximation
r = 2 * mw.statistic / (len(a) * len(b)) - 1 # rank-biserial correlation
print(f"0 h vs 12 h: {len(a):,} vs {len(b):,} cells, median {a.median():.3f} vs {b.median():.3f} µm; "
f"U = {mw.statistic:,.0f}, p = {mw.pvalue:.1e}, rank-biserial r = {r:.2f}")
0 h vs 12 h: 6,958 vs 4,674 cells, median 0.232 vs 0.277 µm; U = 9,884,681, p = 2.1e-282, rank-biserial r = -0.39
The IGH window expands as RAD21 is degraded: the median cell goes from 0.232 µm at 0 h to 0.261, 0.265 and 0.277 µm at 2, 6 and 12 h. With thousands of cells per time point any shift is “significant” (p ≈ 10⁻²⁸²); the effect size, r = −0.39 (a 12 h cell is larger than a 0 h cell in about 70 % of pairs), says more. The time points were barcoded and imaged together, and the experiment has two biological replicates; the shift is there in each:
per_cell["replicate"] = ramos.cells["replicate"].astype(str).reindex(per_cell.index).to_numpy()
per_cell.pivot_table(index="replicate", columns="dtag_time", values="rg", aggfunc="median")[TIMES].round(3)
| dtag_time | 0 h | 2 h | 6 h | 12 h |
|---|---|---|---|---|
| replicate | ||||
| Rep-1 | 0.237 | 0.267 | 0.269 | 0.283 |
| Rep-2 | 0.225 | 0.254 | 0.258 | 0.269 |
fig, axes = plt.subplots(1, 2, figsize=(10, 3.8))
data = [per_cell.loc[per_cell["dtag_time"] == t, "rg"] for t in TIMES]
axes[0].violinplot(data, showmedians=True, showextrema=False)
axes[0].set(xticks=range(1, 5), xticklabels=TIMES, ylim=(0, 0.7), xlabel="dTAG treatment",
ylabel="cell median Rg (µm)", title="IGH chr14:105.55-105.85 Mb")
for t, c in zip(["0 h", "12 h"], ["#d62728", "#9467bd"]):
x = np.sort(per_cell.loc[per_cell["dtag_time"] == t, "rg"])
axes[1].plot(x, np.arange(1, len(x) + 1) / len(x), color=c, label=f"{t} ({len(x):,} cells)")
axes[1].set(xlim=(0, 0.7), xlabel="cell median Rg (µm)", ylabel="fraction of cells",
title=f"Mann-Whitney p = {mw.pvalue:.1e}, r = {r:.2f}")
axes[1].legend(frameon=False)
fig.tight_layout()
The browser’s stats_rg on the same window and groups gives the same traces and the same per-cell medians:
rbrowser = Dataset(id="d2", name="cheng2026_ramos_igh_igl", path=None, cd=ramos)
rows = []
for t in ["0 h", "12 h"]:
out = rbrowser.stats_rg(chrom="chr14", group=f"field:dtag_time={t}", **IGH_WINDOW)
theirs = pd.Series(out["rg"], index=out["trace_ids"])
ours = per_trace.loc[per_trace["cell_id"].isin(per_cell.index[per_cell["dtag_time"] == t]), "rg"]
rows.append({"time": t, "traces (browser)": len(theirs), "traces (fea)": len(ours),
"max |Rg difference|": (theirs.reindex(ours.index) - ours).abs().max(),
"per-cell median (browser)": out["per_cell_median"], "cells (browser)": out["n_cells"],
"median of cell medians (fea)": per_cell.loc[per_cell["dtag_time"] == t, "rg"].median(),
"sampled": out["note"]})
pd.DataFrame(rows).set_index("time")
| traces (browser) | traces (fea) | max |Rg difference| | per-cell median (browser) | cells (browser) | median of cell medians (fea) | sampled | |
|---|---|---|---|---|---|---|---|
| time | |||||||
| 0 h | 11381 | 11381 | 1.110223e-16 | 0.231967 | 6958 | 0.231967 | None |
| 12 h | 10381 | 10381 | 1.110223e-16 | 0.276614 | 4674 | 0.276614 | None |
(The differences are floating-point rounding, ~10⁻¹⁶ µm. For a large store the browser computes Stats on a
random sample of at most 2 M spots and says so in the pane’s badge — note; these two groups fit whole.)
3. The Stats pane of the browser¶
The browser shows these charts in a Stats view (+ View → Stats); its inspector picks the chart (Rg per
trace, Distance vs genomic distance, Contact decay P(s), …), the scope (all chromosomes, locus
chromosome — the chromosome of the locus bar —, or locus window — the locus bar’s [start, end)), for Rg the
unit (per trace or per cell median), and the groups to compare (any categorical cell field). The pane’s badge
names the window and any sampling. Contact-map-only datasets (no coordinates) get a Stats view too, for P(s).
Normally you start the browser from a terminal (python -m uchrom_browser store.chromdata.zarr, or with the URL
of an atlas store) and click. Here the server runs inside this notebook and a headless Chromium opens the page;
the views are opened with the same actions that the buttons trigger — once from the shell with uchrom-web, once
from Python with uchrom_browser.connect().
import socket
import threading
import uvicorn
import uchrom_browser as ub
from uchrom_browser import DatasetStore, create_app
try:
from playwright.async_api import async_playwright
except ImportError:
async_playwright = None
print("Playwright is not installed: the rest of this section is skipped")
def serve(path):
"""Serve one store on a free local port in a background thread; returns its URL."""
store = DatasetStore()
store.load(path)
with socket.socket() as s:
s.bind(("127.0.0.1", 0)); port = s.getsockname()[1]
server = uvicorn.Server(uvicorn.Config(create_app(store, atlas=""), host="127.0.0.1", port=port, log_level="warning"))
threading.Thread(target=server.run, daemon=True).start()
while not server.started:
time.sleep(0.05)
return f"http://127.0.0.1:{port}"
async def open_page(url):
page = await chromium.new_page(viewport={"width": 1500, "height": 900})
await page.goto(url + "/")
for _ in range(240): # until the page has connected and opened the dataset
try:
if ub.connect(url).describe().get("dataset"):
return page
except ub.BrowserError:
pass
await page.wait_for_timeout(500)
raise RuntimeError("the page did not connect")
def uchrom_web(url, *args):
"""Run the agent CLI `uchrom-web` (= python -m uchrom_browser.cli) and return its JSON answer."""
out = subprocess.run([sys.executable, "-m", "uchrom_browser.cli", "--url", url, *args],
capture_output=True, text=True, check=True)
return json.loads(out.stdout)
if async_playwright is not None:
pw = await async_playwright().start()
chromium = await pw.chromium.launch()
P(s) of the two cell types, from the shell¶
uchrom-web is a standard-library-only command line for agents (Claude Code, Codex) and scripts: every action of
ui_tools.json is uchrom-web call <action> --json '{…}', and every answer is JSON. We set the locus to
chr1:0–100 Mb, close the default views and open a contact map and two P(s) charts — all chromosomes and the
locus window — each comparing H1Esc with HFF:
if async_playwright is not None:
KIM = serve(str(hic._links_from()))
kim_page = await open_page(KIM)
for view in uchrom_web(KIM, "describe")["views"]:
uchrom_web(KIM, "call", "close_view", "--json", json.dumps({"pane": view["pane"]}))
uchrom_web(KIM, "call", "set_locus", "--json", '{"chrom": "chr1", "start": 0, "end": 100000000}')
compare = ["field:cell_type=H1Esc", "field:cell_type=HFF"]
panes = [uchrom_web(KIM, "call", "open_view", "--json", json.dumps(v))["pane"] for v in (
{"type": "matrix", "source": "per_cell", "cells": "all"},
{"type": "stats", "stats": "ps", "source": "per_cell", "cells": "all", "chrom_scope": "all", "compare_groups": compare},
{"type": "stats", "stats": "ps", "source": "per_cell", "cells": "all", "chrom_scope": "window", "compare_groups": compare})]
for view in uchrom_web(KIM, "describe")["views"]: # closing the last view leaves an empty one: drop it
if view["pane"] not in panes:
uchrom_web(KIM, "call", "close_view", "--json", json.dumps({"pane": view["pane"]}))
uchrom_web(KIM, "call", "arrange", "--json", '{"layout": "grid"}')
await kim_page.wait_for_timeout(45_000) # the server sums the maps of 1,931 cells per chart
print(json.dumps([{k: v.get(k) for k in ("pane", "type", "stats", "chrom_scope")}
for v in uchrom_web(KIM, "describe")["views"]], indent=1))
[
{
"pane": "P3",
"type": "matrix",
"stats": null,
"chrom_scope": null
},
{
"pane": "P4",
"type": "stats",
"stats": "ps",
"chrom_scope": "all"
},
{
"pane": "P5",
"type": "stats",
"stats": "ps",
"chrom_scope": "window"
}
]
from IPython.display import Image
if async_playwright is not None:
print("badges:", await kim_page.locator(".pane-badge").all_inner_texts(),
"| errors shown:", await kim_page.locator(".pane-error").count())
display(Image(await kim_page.screenshot()))
badges: ['All cells · 1931', 'chr1:0-100M'] | errors shown: 0
The labels repeat section 1: all chromosomes H1Esc −0.66 (n=750), HFF −0.70 (n=1,181), all cells −0.68; in the
locus window (badge chr1:0-100M) −1.48 and −0.99. A chart can be saved as an editable vector file:
uchrom-web capture --pane P4 --out ps.svg (or ws.capture(pane=..., path="ps.svg")).
Rg per cell in the IGH window, from Python¶
ub.connect(url) returns a Workspace whose methods are the same actions. The Ramos store is served from its
atlas URL:
if async_playwright is not None:
RAMOS = serve(ds._atlas_entry("cheng2026_ramos_igh_igl")["url"])
ramos_page = await open_page(RAMOS)
ws = ub.connect(RAMOS)
for view in ws.describe()["views"]:
ws.close_view(pane=view["pane"])
ws.set_locus(chrom="chr14", start=105_550_000, end=105_850_000)
compare = ["field:dtag_time=0 h", "field:dtag_time=12 h"]
panes = [ws.open_view(type="stats", stats="rg", rg_unit="cell", chrom_scope="window", cells="field:dtag_time=0 h",
compare_groups=compare)["pane"],
ws.open_view(type="stats", stats="scaling", chrom_scope="window", cells="field:dtag_time=0 h",
compare_groups=compare)["pane"]]
for view in ws.describe()["views"]:
if view["pane"] not in panes:
ws.close_view(pane=view["pane"])
ws.arrange(layout="grid")
await ramos_page.wait_for_timeout(30_000)
print("badges:", await ramos_page.locator(".pane-badge").all_inner_texts(),
"| errors shown:", await ramos_page.locator(".pane-error").count())
display(Image(await ramos_page.screenshot()))
badges: ['chr14:105.55M-105.85M | 0 h (7256 cells)', 'chr14:105.55M-105.85M | 0 h (7256 cells)'] | errors shown: 0
Left, the per-cell median Rg of 0 h (bars) and 12 h (outline): cell medians 0.23 and 0.28 µm over 6,958 and 4,674 cells, as in section 2. The pane computes the Mann–Whitney test in the page (the same U; its p-value, 2.4 × 10⁻²⁸², comes from a polynomial approximation of the normal tail — scipy’s is 2.1 × 10⁻²⁸² —, and r = −0.39). Right, the median distance against genomic separation within the window, with the interquartile band of 0 h.
if async_playwright is not None:
await chromium.close()
await pw.stop()
print(f"total runtime {time.time() - T0:.0f} s")
total runtime 208 s
Agents: uchrom-web and the MCP server¶
uchrom-web (installed with uchrom-browser) drives the page of a running browser from a terminal; it finds the
server from --url, $UCHROM_BROWSER_URL or the last one started:
uchrom-browser kim2020_scihic.chromdata.zarr --port 8791 # serve a store (default port 8765)
uchrom-web doctor # server, connected tabs, proxy settings
uchrom-web pages # tabs and what they show; `bind <page>` when there are several
uchrom-web tools --schema open_view # an action's arguments
uchrom-web call set_locus --json '{"chrom": "chr1", "start": 0, "end": 100000000}'
uchrom-web call open_view --json '{"type": "stats", "stats": "ps", "chrom_scope": "window",
"compare_groups": ["field:cell_type=H1Esc", "field:cell_type=HFF"]}'
uchrom-web capture --out ps_window.svg # the active view as SVG / PDF / PNG (never overwrites)
Exit codes say what went wrong (2 invalid arguments, 3 server or tab unreachable, 4 several tabs and none chosen, 5 the action or the file write failed). For MCP hosts (Claude Desktop, Cursor, Claude Code, Codex) the same actions are tools of a stdio MCP server:
uchrom-web mcp --print-config json # the "mcpServers" entry to paste (or: codex, for its TOML config)
uchrom-web mcp --doctor # check the server, datasets and tabs it would use
The tools are uchrom_list_pages, uchrom_bind_page, uchrom_wait_for_page, uchrom_batch (up to 20 actions
in one call) and uchrom_<action> for each action — e.g. uchrom_open_view with stats="ps",
chrom_scope="window" — and uchrom_capture_view, which writes the figure to a file and returns its path. See
the web browser for the whole interface.
Summary¶
H1Esc |
HFF |
|
|---|---|---|
P(s) slope, all chromosomes |
−0.66 |
−0.70 |
P(s) slope, chr1:0–100 Mb |
−1.48 |
−0.99 |
same, sets of 2 M contacts |
−1.33 to −1.54 |
−0.96 to −1.01 |
IGH chr14:105.55–105.85 Mb |
0 h |
2 h |
6 h |
12 h |
|---|---|---|---|---|
median cell Rg (µm) |
0.232 |
0.261 |
0.265 |
0.277 |
contact_ps= the browser’sstats_ps= the skill’scontact_ps(slope difference 0.0);radius_of_gyration= the authors’ Rg (whole traces) and the browser’sstats_rg(window).A pooled P(s) slope has no replicates and depends on depth and scope: compare at matched depth, in a window that means something (one arm, a domain), and report the range of slopes over sets of cells.