Source code for uchrom.io.orca_fits

"""ORCA traces of the Boettiger lab's ChromTracer: per-field ``*_ORCA_Fits.csv`` tables (Mateo et al. 2021, *Nat
Protoc* 16:1647).

One table per field of view (FOV); one row per fitted barcode spot: ``x``, ``y``, ``z`` (nm, drift-corrected, local
to the image crop around the fiducial spot), the fit (``h`` brightness, ``wx`` / ``wy`` / ``wz`` widths, ``a``, ``b``,
``fitQuality``), ``readout`` / ``hybe`` / ``panel`` (the barcode, 1-based), ``dataType`` (``H`` barcode, ``R`` repeat,
``A`` / ``B`` alignment images), ``s`` (the fiducial spot = the traced locus, numbered within the FOV), ``idx``,
``fov``, ``fs`` (``CantorPair(fov, s)``), ``locusX`` / ``locusY`` (the fiducial's position in the FOV, nm), the drift
applied (``xshift`` / ``yshift`` / ``zshift``, ``shiftScore``) and the fiducial's own fit (``fid_x`` ... ``fid_h``);
newer tables add the chromatic shift (``xcShift`` / ``ycShift`` / ``zcShift``).

The lab's MATLAB turns the tables into a stack of polymers (barcodes x 3 x traces) in two ways, both reproduced
(``method``):

* ``"TableToPolymer"`` (``TableToPolymer(file, 'bins', n)``): one trace per ``fs`` of the table, the barcode from
  ``readout`` (rows of ``H`` / ``R`` data with ``readout`` <= n), the chromatic shift added when the table has it;
* ``"CombineFOVdataFromFolder"`` (its defaults: ``TableToDistMap`` by ``hybe``, no chromatic shift; traces of at
  least two rows; ``RemoveBadPts`` with ``maxJump`` 250 nm, ``maxDist`` 2000 nm over all the barcodes of the FOV):
  points whose distance to both neighbours exceeds ``maxJump``, or whose median distance to the other points of the
  trace exceeds ``maxDist``, are strays; only the FOVs with the largest barcode count are stacked.

Strays are kept as spots and flagged (``spot_tracks["stray"]``; ``flag_strays=True`` flags them for
``"TableToPolymer"`` too, which does not remove them).  A trace's ``n_detected`` is what the lab's QC counts (barcodes
among the loci with a position, strays excluded by ``"CombineFOVdataFromFolder"`` only); ``qc_pass`` applies a detection window (the
Buckley et al. 2026 scripts keep 25 <= ``n_detected`` <= 86 of 90).  ``stack_index`` is the trace's 1-based position
in the lab's stack (files in the order given), by which the lab's processed tables refer to traces.
"""

from __future__ import annotations

from pathlib import Path
from typing import Optional, Sequence, Tuple

import numpy as np
import pandas as pd

__all__ = ["read_orca_fits", "remove_bad_points", "ORCA_FIT_COLUMNS"]

#: per-spot columns kept as ``spot_tracks`` (when the table has them)
ORCA_FIT_COLUMNS = ("h", "wx", "wy", "wz", "a", "b", "fitQuality", "xshift", "yshift", "zshift", "shiftScore")
#: per-trace columns of the fiducial (first row of the trace)
_TRACE_COLUMNS = {"locusX": "locus_x", "locusY": "locus_y", "fid_x": "fid_x", "fid_y": "fid_y", "fid_z": "fid_z",
                  "fid_h": "fid_h"}
METHODS = ("TableToPolymer", "CombineFOVdataFromFolder")


def remove_bad_points(polymers: np.ndarray, max_jump: float = 250.0, max_dist: float = 2000.0) -> np.ndarray:
    """The strays of the lab's ``RemoveBadPts`` (polymers: traces x barcodes x 3, NaN = not detected): a point whose
    distances to the previous and to the next barcode both exceed ``max_jump``, or whose median distance to the
    trace's points (itself included, as in the lab's distance maps) exceeds ``max_dist``.  Returns traces x barcodes
    booleans."""
    p = np.asarray(polymers, dtype=np.float64)
    n, r, _ = p.shape
    stray = np.zeros((n, r), dtype=bool)
    if r == 0 or n == 0:
        return stray
    step = np.linalg.norm(p[:, 1:] - p[:, :-1], axis=2)                    # d(k, k+1); NaN when one is missing
    with np.errstate(invalid="ignore"):
        jump = step > max_jump
    stray[:, 1:-1] |= jump[:, :-1] & jump[:, 1:]
    for i in range(n):                                                      # median distance: one trace at a time
        ok = np.isfinite(p[i]).all(1)
        if not ok.any():
            continue
        q = p[i, ok]
        d = np.sqrt(((q[:, None, :] - q[None, :, :]) ** 2).sum(-1))
        med = np.median(d, axis=0)
        stray[i, np.flatnonzero(ok)[med > max_dist]] = True
    return stray


def _fov_of(path: Path, table: pd.DataFrame):
    """The FOV number: the table's ``fov`` column, else the digits of the file name (some tables left it empty)."""
    if "fov" in table and table["fov"].notna().any():
        return int(table["fov"].dropna().iloc[0])
    import re
    m = re.search(r"(\d+)_ORCA", path.name) or re.search(r"(\d+)", path.name)
    if m is None:
        raise ValueError(f"{path.name}: no fov column and no number in the file name")
    return int(m.group(1))


[docs] def read_orca_fits( paths, loci: pd.DataFrame, *, method: str = "TableToPolymer", max_jump: float = 250.0, max_dist: float = 2000.0, qc_detected: Optional[Tuple[int, int]] = (25, 86), flag_strays: Optional[bool] = None, trace_prefix: str = "", fit_columns: Sequence[str] = ORCA_FIT_COLUMNS, genome_assembly: Optional[str] = None, source: Optional[str] = None, ): """Read ChromTracer ``*_ORCA_Fits.csv`` tables (module docstring) into a ``ChromData`` (coordinates in nm, local to each trace's image crop). Parameters ---------- paths : path or list of paths One table per FOV, in the order the lab's scripts list them (sorted by name); an empty file is a FOV without traces. loci : DataFrame ``chrom``, ``start``, ``end`` [, ``name``] of barcodes 1, 2, ... in order. Barcodes beyond the table (e.g. extra readouts of the imaging run) are not kept; their row count is ``uns["orca_fits"]``. method : ``"TableToPolymer"`` or ``"CombineFOVdataFromFolder"`` Which of the lab's readers to follow (module docstring): the barcode column, the chromatic shift, which traces exist, strays. max_jump, max_dist : float ``RemoveBadPts`` thresholds (nm) of ``"CombineFOVdataFromFolder"``. flag_strays : bool, optional Flag ``RemoveBadPts`` strays in ``spot_tracks["stray"]`` (default: for ``"CombineFOVdataFromFolder"``, which also leaves them out of ``n_detected``; for ``"TableToPolymer"`` they are flagged only, over the loci). qc_detected : (min, max) or None ``traces["qc_pass"]``: ``min <= n_detected <= max`` (and, for ``"CombineFOVdataFromFolder"``, the FOV is in the stack). trace_prefix : str Trace ids are ``"<prefix>f<fov>_s<s>"``. Returns ------- ChromData ``spots``: ``trace_id``, ``bin_id``; ``spot_tracks``: the fit columns, ``stray``; ``traces``: ``fov``, ``s``, ``locus_x`` / ``locus_y`` (the fiducial in the FOV, nm), ``fid_x`` ... ``fid_h``, ``n_detected``, ``qc_pass``, ``stack_index`` (missing for traces outside the lab's stack); ``uns``: ``xyz_unit`` = ``nm``, ``orca_fits`` (method, counts). """ from chromdata import ChromData if method not in METHODS: raise ValueError(f"method must be one of {METHODS}, not {method!r}") combine = method == "CombineFOVdataFromFolder" barcode_col = "hybe" if combine else "readout" paths = [Path(p) for p in ([paths] if isinstance(paths, (str, Path)) else paths)] loci = loci.reset_index(drop=True) n_loci = len(loci) bins = loci[["chrom", "start", "end"] + (["name"] if "name" in loci else [])].copy() parts, trace_parts, counts = [], [], {"files": len(paths), "empty_files": 0, "rows": 0, "rows_beyond_loci": 0, "rows_not_barcode": 0, "duplicate_rows": 0, "single_row_traces": 0} n_reads = [] for path in paths: table = pd.read_csv(path) if path.stat().st_size else pd.DataFrame() if table.empty: counts["empty_files"] += 1 n_reads.append(0) continue counts["rows"] += len(table) fov = _fov_of(path, table) if combine: data = table[table["idx"] == 1] if "idx" in table else table # idx 2: a second spot of the fiducial else: data = table[table["dataType"].isin(["H", "R"]) & (table["readout"] != 0)] counts["rows_not_barcode"] += len(table) - len(data) sid = data["s"].to_numpy(np.int64) bc = data[barcode_col].to_numpy(np.int64) xyz = data[["x", "y", "z"]].to_numpy(np.float64) if not combine and "xcShift" in data: xyz = xyz + data[["xcShift", "ycShift", "zcShift"]].to_numpy(np.float64) # traces: every s of the table (TableToPolymer: unique fs of the whole table) / s with >= 2 rows (combine) all_s = np.unique(table["s"].to_numpy(np.int64)) rows_per_s = pd.Series(sid).value_counts() if combine: trace_s = np.sort(rows_per_s.index[rows_per_s.to_numpy() > 1].to_numpy()) counts["single_row_traces"] += int((rows_per_s == 1).sum()) width = int(table["hybe"].max()) # the FOV's distance-map size else: trace_s = all_s width = n_loci n_reads.append(width) tpos = {s: i for i, s in enumerate(trace_s)} ti = np.array([tpos.get(s, -1) for s in sid], dtype=np.int64) counts["rows_beyond_loci"] += int(((ti >= 0) & (bc > n_loci)).sum()) keep = (ti >= 0) & (bc >= 1) & (bc <= width) # the lab assigns rows in table order: a repeated (trace, barcode) keeps its last row last = ~pd.DataFrame({"t": ti, "b": bc}).duplicated(keep="last").to_numpy() counts["duplicate_rows"] += int((keep & ~last).sum()) keep &= last poly = np.full((len(trace_s), width, 3), np.nan) poly[ti[keep], bc[keep] - 1] = xyz[keep] flag = combine if flag_strays is None else flag_strays stray = remove_bad_points(poly, max_jump, max_dist) if flag else np.zeros(poly.shape[:2], bool) on_locus = keep & (bc <= n_loci) rows = np.flatnonzero(on_locus) spot = pd.DataFrame({"t": ti[rows], "bin_id": bc[rows] - 1}) spot["stray"] = stray[ti[rows], bc[rows] - 1] for c in fit_columns: if c in data: spot[c] = data[c].to_numpy(np.float32)[rows] spot[["x", "y", "z"]] = xyz[rows] detected = np.isfinite(poly[:, :n_loci, 0]) & ~(stray[:, :n_loci] if combine else False) first = data.groupby("s", sort=True).head(1).set_index("s") tr = pd.DataFrame({"fov": fov, "s": trace_s, "n_detected": detected.sum(1)}) for c, name in _TRACE_COLUMNS.items(): if c in first: tr[name] = first[c].reindex(trace_s).to_numpy(np.float64) tr["trace_id"] = [f"{trace_prefix}f{fov}_s{s}" for s in trace_s] spot["trace_id"] = tr["trace_id"].to_numpy()[spot["t"].to_numpy()] parts.append(spot.drop(columns="t")) trace_parts.append(tr) stacked = [w == max(n_reads) for w in n_reads] if combine else [True] * len(n_reads) traces, offset = [], 0 for tr, w in zip(trace_parts, [w for w in n_reads if w]): in_stack = (w == max(n_reads)) if combine else True tr["in_stack"] = in_stack tr["stack_index"] = pd.array(np.arange(offset + 1, offset + len(tr) + 1) if in_stack else np.full(len(tr), pd.NA), dtype="Int64") offset += len(tr) if in_stack else 0 traces.append(tr) traces = pd.concat(traces, ignore_index=True) if traces else pd.DataFrame( columns=["trace_id", "fov", "s", "n_detected", "in_stack", "stack_index"]) lo, hi = qc_detected if qc_detected is not None else (-np.inf, np.inf) traces["qc_pass"] = traces["in_stack"].astype(bool) & (traces["n_detected"] >= lo) & (traces["n_detected"] <= hi) spots = pd.concat(parts, ignore_index=True) if parts else pd.DataFrame(columns=["trace_id", "bin_id", "x", "y", "z"]) has = spots["trace_id"].unique() counts["traces_without_spots"] = int((~traces["trace_id"].isin(has)).sum()) traces = traces[traces["trace_id"].isin(has)].set_index("trace_id") track_cols = ["stray"] + [c for c in fit_columns if c in spots] counts.update({"method": method, "fovs_in_stack": int(sum(stacked[i] for i, w in enumerate(n_reads) if w)), "barcodes_per_fov": sorted(set(int(w) for w in n_reads if w))}) counts["strays_flagged"] = bool(combine if flag_strays is None else flag_strays) counts["strays_counted_out"] = combine if counts["strays_flagged"]: counts.update({"max_jump_nm": max_jump, "max_dist_nm": max_dist}) if qc_detected is not None: counts["qc_detected"] = [int(lo), int(hi)] uns = {"xyz_unit": "nm", "orca_fits": counts, "source": source or ", ".join(p.name for p in paths[:3])} if genome_assembly: uns["genome_assembly"] = genome_assembly return ChromData(coords=spots[["x", "y", "z"]].to_numpy(np.float64), spots=spots[["trace_id", "bin_id"]].reset_index(drop=True), bins=bins, spot_tracks=spots[track_cols].reset_index(drop=True), traces=traces, uns=uns)