Imputing missing FISH coordinates¶
Chromatin tracing misses loci: a probe is too dim, two spots overlap, a hybridisation round
fails. Typically 5–30 % of the (trace, locus) positions have no coordinate, either as NaN rows
or as absent rows. uchrom.im.impute.impute_coordinates fills them with one of three
methods: linear or cubic interpolation along the genomic coordinate of each trace, or
SnapFISH-IMPUTE (Yu et al., github.com/hyuyu104/SnapFISH-IMPUTE),
which borrows the missing pairwise distances from the most similar other traces and
recovers 3-D positions that fit them. You will run all three, see how absent rows and the
locus panel are handled, and then measure on held-out real spots how close each method gets
(uchrom.im.impute.evaluate_imputation).
Data: ORCA tracing of the Sox2 locus in 129 × CAST mouse ES cells at 5 kb (Huang et al.
2021, Nature Genetics, doi:10.1038/s41588-021-00863-6) as distributed with SnapFISH-IMPUTE:
ds.load("huang2021_sox2") builds it once from SnapFISH-IMPUTE’s coordinate and locus tables
(GitHub, 7 MB) — 1,416 cells × 2 alleles × 41 loci of chr3 (mm10); we use the first 5 cells, 129
allele. For the accuracy test, 300 IMR90 chr21 traces of Bintu et al. 2018, Science (65 loci ×
30 kb; ds.load("bintu_imr90") builds them from the authors’ CSV on GitHub, 2 MB).
Runtime: about 2 minutes.
from pathlib import Path
import time
import warnings
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import uchrom.datasets as ds
from uchrom.im.impute import evaluate_imputation, impute_coordinates
plt.rcParams["figure.dpi"] = 90
# SnapFISH's NaN-aware numerics (Box-Cox on masked distance matrices) emit harmless warnings
warnings.filterwarnings("ignore", category=RuntimeWarning)
OUT = Path("_out"); OUT.mkdir(exist_ok=True) # outputs: tutorials/_out/ (ignored by git)
sox2 = ds.load("huang2021_sox2") # built once from SnapFISH-IMPUTE's tables, then read from the data directory
print(sox2)
ChromData: n_spots=116112, n_traces=2832, n_cells=1416, n_bins=41
spots: ['chrom', 'start', 'end', 'trace_id', 'cell_id', 'allele', 'pos', 'bin_id']
cells: [] (1416 cells)
traces: ['cell_id', 'allele', 'chrom', 'n_loci', 'n_detected'] (2832 traces)
uns: ['xyz_unit', 'source', 'genome_assembly', 'dataset']
1. The data and its gaps¶
SnapFISH-IMPUTE’s format is two tab-separated tables. The coordinate table has one row per
(region, haploid, pos): here region is the allele (129 or CAST), haploid the cell, pos
the locus number, and a missing locus is a row with empty x, y, z. The locus table maps
(region, pos) to start, end. uchrom.io.read_snapfish reads the pair; the loader declares
both alleles copies of chr3 (chrom="chr3", the allele kept as the spot column allele), so a
trace is one allele of one cell (trace_id <cell>_<allele>) and the missing loci stay NaN rows.
Coordinates are in nm; the loci are 5-kb bins of the Sox2 region. Take the first five cells and
their 129 allele (few enough to see every trace in the figures below) with ordinary subsetting.
print(f"{sox2.n_cells:,} cells x {sox2.traces['allele'].nunique()} alleles x {sox2.n_bins} loci, "
f"{np.isnan(sox2.coords[:, 0]).mean():.0%} without coordinates\n")
five = sox2.get_cells(sox2.cells.index[:5])
cd = five[(five.spots["allele"] == "129").to_numpy()] # the 129 allele of the first five cells
print(cd)
missing = np.isnan(cd.coords[:, 0])
print(f"\n{cd.n_traces} traces x {cd.n_bins} loci = {cd.n_spots} spots; {missing.sum()} without coordinates "
f"({missing.mean():.0%})")
sp = cd.spots_with_loci()
grid = (pd.DataFrame({"trace": sp["trace_id"].astype(str), "locus": sp["bin_id"], "missing": missing})
.pivot(index="trace", columns="locus", values="missing"))
fig, ax = plt.subplots(figsize=(7, 1.6))
ax.imshow(grid.to_numpy(), cmap="Greys", aspect="auto", interpolation="nearest")
ax.set_yticks(range(len(grid)), grid.index, fontsize=7); ax.set_xlabel("locus (5 kb)")
ax.set_title("missing coordinates (black)", fontsize=9)
plt.tight_layout(); plt.show()
1,416 cells x 2 alleles x 41 loci, 29% without coordinates
ChromData: n_spots=205, n_traces=5, n_cells=5, n_bins=41
spots: ['chrom', 'start', 'end', 'trace_id', 'cell_id', 'allele', 'pos', 'bin_id']
cells: [] (5 cells)
traces: ['cell_id', 'allele', 'chrom', 'n_loci', 'n_detected'] (5 traces)
uns: ['xyz_unit', 'source', 'genome_assembly', 'dataset']
5 traces x 41 loci = 205 spots; 49 without coordinates (24%)
2. Linear and cubic interpolation¶
Each trace is interpolated on its own, x, y and z separately, as a function of the locus start;
loci before the first / after the last detection are extrapolated (extrapolate=True).
Observed coordinates are kept exactly. The result is a new ChromData on the dense
(trace × locus) grid whose spot column imputed marks the loci that had no coordinate; per-spot
tracks and layers are dropped, cell / trace metadata and uns are kept.
lin = impute_coordinates(cd, method="linear")
cub = impute_coordinates(cd, method="cubic")
def xyz(x):
"""Coordinates indexed by (trace, locus start): imputation may reorder rows."""
return x.to_dataframe().astype({"trace_id": str}).set_index(["trace_id", "start"])[["x", "y", "z"]]
before = xyz(cd).dropna()
for name, out in [("linear", lin), ("cubic", cub)]:
kept = np.abs(xyz(out).loc[before.index].to_numpy() - before.to_numpy()).max()
print(f"{name:6s}: {out.n_spots} spots ({int(out.spots['imputed'].sum())} imputed), "
f"{np.isnan(out.coords[:, 0]).sum()} still missing, observed spots moved by at most {kept:.1e} nm")
linear: 205 spots (49 imputed), 0 still missing, observed spots moved by at most 0.0e+00 nm
cubic : 205 spots (49 imputed), 0 still missing, observed spots moved by at most 2.9e-11 nm
3. SnapFISH-IMPUTE¶
SnapFISH-IMPUTE works on pairwise distances rather than positions:
densify the traces onto the locus panel and fill a first guess by linear interpolation;
turn each trace into its locus–locus distances and normalise every distance by its genomic separation (Box-Cox, then mean 0 / variance 1 per separation);
iteratively fill each missing distance from the most similar trace that has it (similarity = distance between the normalised distance vectors);
move the missing loci (L-BFGS, starting from the linear guess) so that the trace’s distances match the filled ones; observed loci stay fixed.
It needs many traces of the same region: with only five, loci whose distances no similar
trace provides stay NaN. n_jobs > 1 runs step 4 in parallel processes.
t0 = time.perf_counter()
snap = impute_coordinates(cd, method="snapfish", max_iter=50, n_jobs=1, verbose=True)
print(f"\n{time.perf_counter() - t0:.1f} s; {np.isnan(snap.coords[:, 0]).sum()} of {snap.n_spots} spots still missing")
print(f"observed spots moved by at most {np.abs(xyz(snap).loc[before.index].to_numpy() - before.to_numpy()).max():.1e} nm")
Input: 147/615 (23.9%) coordinates missing
Dense grid: 205 rows, 49 loci missing coords
Step 1/4: Linear interpolation initialization...
Step 2/4: Computing pairwise distance matrices...
Step 3/4: Iterative similarity-weighted imputation...
Iteration 1: 1447 NaN values remaining
Iteration 2: 814 NaN values remaining
Iteration 3: 200 NaN values remaining
Iteration 4: 200 NaN values remaining
Converged: no further improvement
Step 4/4: Recovering 3D coordinates...
Done! Result has 15 coordinates still missing
Note: 15 coordinates remain missing (no reference data)
0.8 s; 5 of 205 spots still missing
observed spots moved by at most 0.0e+00 nm
4. Absent rows and the locus panel¶
Most tracing tables simply omit undetected loci. All three methods first densify each
chromosome onto its locus panel — by default the union of the loci observed in any trace — so
absent rows come back as imputed rows. A locus that no trace observed is not in that union;
pass the probe panel as ann= (columns chrom or region, start, end) to restore it too.
The locus axis cd.bins is that panel: a subset keeps the bins of its whole dataset.
Here locus 26 (index 25 in the figure above) has no coordinate in any of the five traces —
SnapFISH-IMPUTE’s preprocessing removed it from the 129 allele of every cell — so the union
panel has 40 loci and the dense grid 200 rows.
absent = cd[np.flatnonzero(~missing)] # drop the NaN rows: loci are now absent
print(f"absent-row input: {absent.n_spots} rows, none NaN")
filled = impute_coordinates(absent, method="linear")
print(f"linear : {filled.n_spots} rows (dense grid), {np.isnan(filled.coords[:, 0]).sum()} NaN")
# remove one locus from every trace: the observed union no longer contains it ...
dropped_start = int(cd.bins["start"].iloc[20])
no_locus = absent[np.flatnonzero(absent.spots_with_loci()["start"].to_numpy() != dropped_start)]
print(f"without locus {dropped_start:,}: union panel -> {impute_coordinates(no_locus, method='linear').n_spots} rows")
# ... the locus axis (the 41-locus probe panel, kept whole by every subset) restores it
print("panel: no_locus.bins,", list(no_locus.bins.columns), len(no_locus.bins), "loci")
restored = impute_coordinates(no_locus, method="linear", ann=no_locus.bins)
print(f"with ann=bins -> {restored.n_spots} rows, {np.isnan(restored.coords[:, 0]).sum()} NaN")
absent-row input: 156 rows, none NaN
linear : 200 rows (dense grid), 0 NaN
without locus 34,701,078: union panel -> 195 rows
panel: no_locus.bins, ['chrom', 'start', 'end'] 41 loci
with ann=bins -> 205 rows, 0 NaN
5. One trace, three methods¶
The imputed loci (open circles; the spot column imputed) on one trace, projected on x–y, with
the chain drawn in genomic order.
tid = "26_129" # cell 26, 129 allele
fig, axes = plt.subplots(1, 3, figsize=(7.5, 2.8), sharex=True, sharey=True)
for ax, (name, out) in zip(axes, [("linear", lin), ("cubic", cub), ("SnapFISH-IMPUTE", snap)]):
t = out.get_trace(tid).to_dataframe().sort_values("start")
x, y, imp = t["x"] / 1000, t["y"] / 1000, t["imputed"].to_numpy()
ax.plot(x, y, "-", color="0.7", lw=0.8, zorder=1)
ax.scatter(x[~imp], y[~imp], s=12, c="tab:blue", label="observed", zorder=2)
ax.scatter(x[imp], y[imp], s=22, facecolors="none", edgecolors="tab:red", label="imputed", zorder=3)
ax.set_title(name, fontsize=9); ax.set_xlabel("x (um)")
axes[0].set_ylabel("y (um)"); axes[0].legend(fontsize=7)
fig.suptitle(f"trace {tid}: {int(imp.sum())} imputed of {len(t)} loci", fontsize=10)
plt.tight_layout(); plt.show()
6. How accurate is each method? A hold-out test on real traces¶
Five traces are too few to judge, so take 300 IMR90 chr21 traces of Bintu et al. 2018
(ds.load("bintu_imr90"); undetected segments are absent rows). evaluate_imputation hides a
random 10 % of the detected spots (drawn in trace / locus order with seed=0, so the draw
does not depend on how the rows are stored), imputes them with every method and compares with
the hidden truth:
error — 3-D distance between the imputed and the true position;
distance to the neighbouring loci — imputation should also keep the local chain geometry: compare the distance from each hidden locus to the observed loci within 3 segments (
neighbour_bp, by default three bins: ≤ 90 kb) of it, true vs imputed.
bintu = ds.load("bintu_imr90")
first300 = bintu.spots["trace_id"].cat.categories[:300] # traces 1-300
sub = bintu[bintu.spots["trace_id"].isin(first300).to_numpy()]
print(f"{sub.n_traces} traces, {sub.n_spots:,} detected spots "
f"({1 - sub.n_spots / (sub.n_traces * sub.n_bins):.1%} of the trace x locus grid undetected)")
res = evaluate_imputation(sub, ["linear", "cubic", "snapfish"], frac=0.1, seed=0,
method_kwargs={"snapfish": {"max_iter": 50, "n_jobs": 4}})
print(f"{res.n_hidden:,} hidden spots; the summary is also stored as sub.results['imputation.holdout']")
res.summary.round(1)
300 traces, 18,255 detected spots (6.4% of the trace x locus grid undetected)
1,825 hidden spots; the summary is also stored as sub.results['imputation.holdout']
| linear | cubic | snapfish | |
|---|---|---|---|
| median error (nm) | 279.1 | 368.8 | 436.7 |
| mean error (nm) | 331.9 | 523.4 | 477.2 |
| not imputed | 0.0 | 0.0 | 0.0 |
| median neighbour distance, true (nm) | 345.9 | 345.9 | 345.9 |
| median neighbour distance, imputed (nm) | 258.6 | 332.7 | 419.2 |
| seconds | 0.1 | 0.1 | 27.0 |
fig, ax = plt.subplots(figsize=(5, 2.8))
bins = np.linspace(0, 1500, 61)
for method, colour in [("linear", "tab:blue"), ("cubic", "tab:orange"), ("snapfish", "tab:green")]:
err = res.errors[method]
ax.hist(err, bins=bins, histtype="step", lw=1.5, color=colour, label=f"{method} (median {np.nanmedian(err):.0f} nm)")
ax.set_xlabel("error of the imputed position (nm)"); ax.set_ylabel("hidden spots"); ax.legend(fontsize=8)
plt.tight_layout(); plt.show()
On these real traces linear interpolation places the hidden loci best (median error ~280 nm, below the ~350 nm median distance between neighbouring segments); cubic splines overshoot between noisy detections, and SnapFISH-IMPUTE is worse still in median error: it reproduces the distances of the most similar other trace, not this trace’s own path. The neighbour distances show a second effect: linear puts a hidden locus on the straight line between its neighbours and so shrinks local distances (~260 vs ~350 nm true), while SnapFISH-IMPUTE inflates them (~420 nm); cubic is closest in this one statistic. So: linear for positions (and as a default), and keep in mind that every method biases distance statistics — compute distance-based features on observed spots where you can.
7. Save¶
Write the imputed objects as stores (here under tutorials/_out/).
for name, out in [("linear", lin), ("snapfish", snap)]:
path = OUT / f"mESC_Sox2_5cells_imputed_{name}.chromdata.zarr"
out.write(path)
print("wrote", path)
wrote _out/mESC_Sox2_5cells_imputed_linear.chromdata.zarr
wrote _out/mESC_Sox2_5cells_imputed_snapfish.chromdata.zarr
Next steps¶
jie_aligner.ipynb— build traces from raw detections first;import_fofct.ipynb,import_pyhim_ecsv.ipynb— load traced tables.Downstream on imputed or observed traces:
tad_calling.ipynb,loop_calling.ipynb,fishnet_domains.ipynb.Compare observed and imputed traces in the web browser:
python -m uchrom_browser tutorials/_out/mESC_Sox2_5cells_imputed_linear.chromdata.zarr.