uchrom.im

Imaging-side processing of DNA-FISH data: detections into traces, missing loci, duplicate spots.

Imaging-side processing: spot-to-trace alignment (uchrom.im.trace), coordinate imputation (uchrom.im.impute) and spot-level preprocessing (merge_duplicate_spots()).

uchrom.im.merge_duplicate_spots(cd, *, how: str = 'mean')[source]

One spot per (trace, locus): merge the spots of a trace that share a bin.

Multiplexed DNA-FISH often detects a locus twice in one trace (sister chromatids, a stray spot); per-trace statistics then depend on which spot is used — uchrom.fea.distance_map() keeps the last one unless duplicates= says otherwise (the same reductions as here), the web browser averages them. This merges them once, for every analysis that follows.

Parameters:
  • cd (ChromData)

  • how ("mean" (default), "median", "first" or "last") – How the coordinates, the layers and the numeric spot_tracks of a group are combined (NaN values are skipped by mean / median); other spot columns keep the group’s first value.

Returns:

A new object (cd is not modified) with one spot per (trace, bin), in the order of each group’s first spot, and the spot column n_merged (spots per group); the locus axis, cells, traces and every other attribute are kept.

Return type:

ChromData

Spot-to-fibre tracing

The jie spatial genome aligner, an independent re-implementation of Jia et al. 2023, Nature Biotechnology 41:1004 (doi:10.1038/s41587-022-01568-9).

Spot → fiber tracing algorithms for multiplexed DNA-FISH data.

Takes detected-and-decoded spots with ambiguous trace assignments (multiple candidate spots per genomic locus per cell) and decides which spots belong to the same chromatin fiber. Output is a chromdata.ChromData with a populated trace_id column.

The first backend, uchrom.im.trace.jie, is an independent reimplementation of Jia & Ren 2022 (Nature Biotechnology, doi:10.1038/s41587-022-01568-9) — a spatial genome aligner that uses a Gaussian-chain polymer model to score candidate spot-to-fiber assignments, then picks fibers via iterative shortest-path. score_alignment() compares the fibres with a reference assignment.

class uchrom.im.trace.SpotAlignerParams(persistence_length_bp: float = 150.0, tau_nm_per_bp: float | None = None, scaling_exponent_fixed: bool = True, default_sigma_nm: float = 50.0, max_skip: int = 3, gap_penalty: float = 3.0, max_fibers_per_chrom: int = 8, min_spots_per_fiber: int = 5, mean_edge_weight_cutoff: float = inf, detect_sisters: bool = True, sister_pair_radius_nm: float = 300.0, verbose: bool = False)[source]

Bases: object

Runtime parameters for align_spots().

default_sigma_nm: float = 50.0

Fallback localisation σ when sigma_* columns absent from spots_df (axis-wise, nm).

detect_sisters: bool = True
gap_penalty: float = 3.0

Additive per-skip penalty in the Mahalanobis-cost edge weight. A skip-0 edge (adjacent locus) adds nothing; a skip-2 edge adds 2 * gap_penalty. Calibrate against typical R² / 2S² (around 1.5 for on-chain matches).

max_fibers_per_chrom: int = 8
max_skip: int = 3
mean_edge_weight_cutoff: float = inf
min_spots_per_fiber: int = 5
persistence_length_bp: float = 150.0
scaling_exponent_fixed: bool = True

If True, force α=0.5 (ideal Gaussian chain) in the τ fit. Set False to fit α jointly — useful for crumpled-globule chromatin.

sister_pair_radius_nm: float = 300.0
tau_nm_per_bp: float | None = None

Genomic-to-spatial scale. If None, fit per-chromosome from the aggregate observed-distance-vs-genomic-distance curve.

verbose: bool = False
uchrom.im.trace.align_spots(spots_df, params: SpotAlignerParams | None = None, tau_by_chrom: Dict[str, float] | None = None, *, chrom=None, cells=None) → ChromData[source]

Assign detected FISH spots to chromatin fibers.

Parameters:
  • spots_df (ChromData or DataFrame) – The detections (see the module docstring): a ChromData whose spots carry cell_id (its trace_id is ignored — e.g. one candidate set per cell and chromosome, as uchrom.io.read_seqfish_detections() gives), or a table with cell_id, chrom, start, end, x, y, z in nm.

  • params (SpotAlignerParams, optional)

  • tau_by_chrom (dict, optional) – τ (nm per bp) per chromosome; fitted from the data when omitted.

  • chrom (str or list, optional) – Align these chromosomes only.

  • cells (list, optional) – Align these cells only.

Returns:

The detections placed on a fibre, trace_id = the fibre; traces (one row per fibre), results['ploidy'], uns['jie_polymer'] / uns['jie_params']. From a ChromData the result keeps its locus axis (bins), cells, uns, coordinate unit, the other spot columns (spot_id, label, …) and spot_tracks; from a table, coordinates are in nm.

Return type:

ChromData

uchrom.im.trace.score_alignment(cd, reference, *, label: str | None = None, per: str | None = None)[source]

Compare the fibres of an alignment with a reference assignment of the same detections.

The detections are matched by spot_id (which align_spots() carries through). Scored are the reference spots with a label (missing or negative labels — e.g. labelID == -1, rejected by the upstream pipeline — are left out) in the (cell, chromosome) groups the alignment processed (its results['ploidy']; so a reference may hold more chromosomes or cells than were aligned):

  • assigned — fraction of them placed on some fibre;

  • purity — per fibre, the fraction of its spots from its majority reference label, averaged over the fibres;

  • median ARI — per (cell, chromosome) with more than one reference label, the adjusted Rand index between fibres and labels (spots on no fibre form one extra group); the median over those;

  • n_spots, n_fibres — the scored spots and the fibres they fall on.

Parameters:
  • cd (ChromData) – The alignment (align_spots()): spot_id and trace_id (the fibre) per spot.

  • reference (ChromData or DataFrame) – The detections with spot_id, cell_id, chrom and the reference label.

  • label (str, optional) – The reference spot column with the assignment (e.g. "label", the upstream homolog call); default trace_id (a traced reference). Labels are compared within (cell, chromosome).

  • per (None or "chrom") – One set of scores, or one row per chromosome.

Return type:

Series (or DataFrame with one row per chromosome, per="chrom")

Gaussian-chain polymer primitives

Gaussian-chain polymer primitives for the spatial genome aligner.

Two-end distance distribution of an ideal Gaussian chain of contour length L with Kuhn segment b = 2 * l_p (persistence length) is isotropic Gaussian with variance Nb² / 3 per axis — i.e. <R²> = 2 * l_p * L for the 3-D distance, and <R²> / 3 per axis.

Adding independent Gaussian localisation noise with axis variance σ² at each end yields

S²(i, j) = σ_i² + σ_j² + (2/3) · l_p · τ · L_ij

which is the expected axis-wise variance of the observed distance between two FISH spots connected by a contour length L_ij bp under a scale factor τ (nm/bp). S² scales the Gaussian-chain bond probability used by the aligner.

All lengths here are in nm and all genomic distances in bp.

uchrom.im.trace._polymer.PERSISTENCE_LENGTH_BP_DEFAULT: float = 150.0

Persistence length of bare B-form dsDNA, in bp.

One persistence length ≈ 50 nm at the canonical 0.34 nm/bp rise, which gives ~150 bp. For chromatin the effective persistence length is much larger, but is folded into the fitted scale factor τ so we keep the bp value constant.

uchrom.im.trace._polymer.bond_log_probability(R_nm: ndarray | float, S2_nm2: ndarray | float) → ndarray[source]

Log probability density of an observed distance R under an isotropic 3-D Gaussian with axis variance S².

log p = -1.5 · log(2π·S²) - R² / (2·S²)

uchrom.im.trace._polymer.expected_distance(L_bp: ndarray | float, l_p_bp: float = 150.0, tau_nm_per_bp: float = 0.01) → ndarray[source]

Gaussian-chain mean 3-D end-to-end distance <R> ≈ √(2·l_p·τ·L).

Strictly <R> = √(8/(3π)) · √(<R²>) for a 3-D Gaussian variable, but the scaling-law form √(<R²>) is what the literature calls the “Gaussian chain” expected distance and what jie uses.

uchrom.im.trace._polymer.expected_distance_sq(L_bp: ndarray | float, l_p_bp: float = 150.0, tau_nm_per_bp: float = 0.01, sigma_nm: ndarray | float = 0.0) → ndarray[source]

Gaussian-chain axis variance of the end-to-end distance.

S²(L) = 2·σ² + (2/3)·l_p·τ·L

Parameters:
  • L_bp (ndarray or float) – Genomic distance(s) in bp between the two loci.

  • l_p_bp (float) – Persistence length in bp.

  • tau_nm_per_bp (float) – Genomic-to-spatial scale factor (nm / bp).

  • sigma_nm (ndarray or float) – Axis-wise localisation uncertainty of each endpoint, in nm. A scalar is broadcast to both endpoints; an array of shape (2,) or matching L_bp is also accepted.

Returns:

S2 – Axis-wise variance of the observed distance, in nm².

Return type:

ndarray or float

uchrom.im.trace._polymer.fit_scale_factor(observed_dist_nm: ndarray, genomic_dist_bp: ndarray, l_p_bp: float = 150.0, fix_exponent: bool = True) → Tuple[float, float][source]

Fit Gaussian-chain scale factor τ to observed trace distances.

Performs a log-log regression of R on L:

log R = 0.5 · log(2·l_p·τ) + α · log L

with α = 0.5 fixed for an ideal Gaussian chain (fix_exponent= True) or fitted jointly. Returns (τ, α).

Parameters:
  • observed_dist_nm (ndarray) – Observed 3-D distances (nm). NaN and non-positive values are dropped.

  • genomic_dist_bp (ndarray) – Genomic separations (bp) with the same shape as observed_dist_nm.

  • l_p_bp (float) – Persistence length (bp).

  • fix_exponent (bool) – If True, force α = 0.5 (ideal Gaussian chain). If False, fit it jointly — useful for chromatin where α often ≈ 0.33 (crumpled globule).

Returns:

  • tau_nm_per_bp (float)

  • scaling_exponent (float) – 0.5 when fix_exponent=True; otherwise the fitted value.

uchrom.im.trace._polymer.fit_scale_factor_from_matrix(dist_matrix_nm: ndarray, bin_genomic_bp: ndarray, l_p_bp: float = 150.0, aggregator: str = 'median', fix_exponent: bool = True) → Tuple[float, float][source]

Fit τ from a (n_bins, n_bins) distance matrix.

For each unique off-diagonal genomic separation L, aggregates the observed distances (median or mean) across all bin pairs with that separation, then runs fit_scale_factor() on the result.

Parameters:
  • dist_matrix_nm (ndarray (n_bins, n_bins)) – Pairwise distances in nm. NaNs are ignored.

  • bin_genomic_bp (ndarray (n_bins,)) – Genomic midpoint of each bin, in bp.

  • l_p_bp (float)

  • aggregator ('median' | 'mean')

  • fix_exponent (bool)

Returns:

  • tau_nm_per_bp (float)

  • scaling_exponent (float)

uchrom.im.trace._polymer.mahalanobis_cost(R_nm: ndarray | float, S2_nm2: ndarray | float) → ndarray[source]

Mahalanobis-style squared cost R² / (2·S²).

This is the data-dependent part of the negative log Gaussian density (the exponent, without the -1.5·log(2π·S²) normalisation constant). For shortest-path aligners this has a useful property that bond_log_probability() does not: the cost of a single edge is independent of how many loci lie between its endpoints, so paths with different numbers of skipped loci can be compared fairly.

Together with a per-skip gap_penalty it gives well-calibrated edge weights:

w_ij = R²_ij / (2·S²_ij) + (c - 1) · gap_penalty

Imputation

FISH data imputation module for uchrom.

This module provides coordinate imputation methods for multiplexed DNA FISH data, including linear interpolation and the SnapFISH-IMPUTE algorithm, and a hold-out test of their accuracy on real traces (evaluate_imputation()).

class uchrom.im.impute.ImputationHoldout[source]

Bases: dict

Result of evaluate_imputation() (a dict with attribute access):

  • summary: one column per method, rows median error, mean error, not imputed, median neighbour distance, true / imputed (in the unit of uns['xyz_unit']) and seconds;

  • errors: one row per hidden spot (index trace_id, chrom, start), the 3-D error of each method;

  • n_observed, n_hidden, frac, seed, neighbour_bp, unit.

uchrom.im.impute.evaluate_imputation(cd, methods: Sequence[str] = ('linear', 'cubic', 'snapfish'), *, frac: float = 0.1, seed: int = 0, neighbour_bp: int | None = None, trace_ids: Iterable | None = None, cells: Iterable | None = None, method_kwargs: Mapping[str, Mapping] | None = None, key_added: str | None = 'imputation.holdout') → ImputationHoldout[source]

Hide observed spots, impute them with each method and compare with the truth.

The observed spots (one per trace and locus) are put in a canonical order — trace (ids sorted: integers numerically, strings lexicographically), chromosome, start — so that the hidden set does not depend on how the rows are stored; frac of them are drawn with numpy.random.default_rng(seed) and removed (absent rows), every method of impute_coordinates() fills them back in, and the result is compared with the hidden truth:

  • error — the 3-D distance between the imputed and the true position;

  • neighbour distance — imputation should also keep the local chain geometry: the distances from each hidden locus to the observed (not hidden) loci of its trace within neighbour_bp, from the true and from the imputed position (medians over all such pairs).

Parameters:
  • cd (ChromData) – Traces with real coordinates (spots with NaN coordinates are never hidden; they stay missing).

  • methods (sequence of str) – Methods of impute_coordinates() ("linear", "cubic", "snapfish").

  • frac (float) – Fraction of the observed spots to hide.

  • seed (int) – Seed of the random draw.

  • neighbour_bp (int, optional) – Genomic window of the neighbour distances; default three times the median bin size.

  • trace_ids (optional) – Evaluate on these traces / cells only (the calling convention’s selection).

  • cells (optional) – Evaluate on these traces / cells only (the calling convention’s selection).

  • method_kwargs (dict, optional) – Keyword arguments per method, e.g. {"snapfish": {"max_iter": 50, "n_jobs": 4}} (SnapFISH-IMPUTE runs with verbose=False unless given).

  • key_added (str or None) – cd.results key of the summary table (None: not stored).

Returns:

summary (metrics x methods), errors (per hidden spot and method) and the settings.

Return type:

ImputationHoldout

Examples

>>> res = evaluate_imputation(cd, trace_ids=cd.spots["trace_id"].cat.categories[:300],
...                           method_kwargs={"snapfish": {"n_jobs": 4}})
>>> res.summary.round(1)
uchrom.im.impute.impute_coordinates(cd, method='linear', **kwargs)[source]

Impute missing 3D coordinates in ChromData.

Parameters:
  • cd (ChromData) – Input ChromData with missing coordinates (NaN values).

  • method ({'linear', 'cubic', 'snapfish'}, default 'linear') – Imputation method: - ‘linear’: Linear interpolation (no extra dependencies) - ‘cubic’: Cubic spline interpolation (no extra dependencies) - ‘snapfish’: SnapFISH-IMPUTE algorithm (scipy / scikit-learn, both core dependencies)

  • **kwargs – Additional arguments passed to the specific imputation method.

Returns:

ChromData with imputed coordinates, on the dense (trace x locus) grid of each chromosome; the spot column imputed marks the loci that had no coordinate in the input (still NaN where a method could not fill them).

Return type:

ChromData

Raises:

ValueError – If method is not recognized.

Examples

>>> cd = uc.ChromData.from_fofct('data.csv')
>>> cd_imputed = uc.im.impute.impute_coordinates(cd, method='linear')
>>> # For SnapFISH-IMPUTE algorithm
>>> cd_imputed = uc.im.impute.impute_coordinates(
...     cd, method='snapfish', max_iter=50, verbose=True
... )

Notes

The SnapFISH-IMPUTE algorithm (Yu et al.) uses a similarity-weighted approach to impute missing coordinates based on cells with similar conformations. For large datasets (>1000 cells), consider using external MPI tools for better performance.

uchrom.im.impute.impute_cubic(cd, extrapolate=True, ann=None)[source]

Impute missing coordinates using cubic spline interpolation.

The input is first densified onto the per-chrom locus panel, so loci that are missing as absent rows (not just NaN rows) are also imputed.

Parameters:
  • cd (ChromData) – Input ChromData with missing coordinates (NaN values and/or absent rows).

  • extrapolate (bool, default True) – Whether to extrapolate values outside the range of known coordinates.

  • ann (pd.DataFrame, optional) – Authoritative locus panel (columns chrom|region, start, end).

Returns:

ChromData on the dense grid with cubic-spline interpolated coordinates.

Return type:

ChromData

Examples

>>> cd_imputed = impute_cubic(cd)
uchrom.im.impute.impute_linear(cd, extrapolate=True, ann=None)[source]

Impute missing coordinates using linear interpolation.

The input is first densified onto the per-chrom locus panel, so loci that are missing as absent rows (not just NaN rows) are also imputed.

Parameters:
  • cd (ChromData) – Input ChromData with missing coordinates (NaN values and/or absent rows).

  • extrapolate (bool, default True) – Whether to extrapolate values outside the range of known coordinates.

  • ann (pd.DataFrame, optional) – Authoritative locus panel (columns chrom|region, start, end). When given, loci absent from every haploid are still restored.

Returns:

ChromData on the dense grid with linearly interpolated coordinates.

Return type:

ChromData

Examples

>>> cd_imputed = impute_linear(cd)
uchrom.im.impute.impute_snapfish(cd, max_iter=50, ann=None, n_jobs=1, verbose=True)[source]

Impute missing coordinates using SnapFISH-IMPUTE algorithm.

This is a single-machine implementation with optional multiprocessing. For very large datasets, the original MPI tools remain an option.

Parameters:
  • cd (ChromData) – Input ChromData with missing coordinates (NaN values and/or absent rows).

  • max_iter (int, default 50) – Maximum number of imputation iterations.

  • ann (pd.DataFrame, optional) – Authoritative locus panel (columns chrom|region, start, end). When given, loci absent from every haploid are still restored. When omitted, the panel is the union of observed loci per chrom.

  • n_jobs (int, default 1) – Number of worker processes for the per-haploid 3D recovery step (L-BFGS-B), which dominates runtime. 1 runs serially and is bit-for-bit identical to the original single-process algorithm; >1 distributes haploids across processes (joblib loky backend, inner BLAS threads pinned to avoid oversubscription). The algorithm is unchanged – only independent per-haploid work is parallelized, so results are identical. Process-based parallelism is required here because the L-BFGS objective and Jacobian are Python callbacks (GIL-bound); thread backends do not help. On a ~300-haploid dataset this gives roughly 2.5x at n_jobs=4 and 4x at n_jobs=8 end-to-end (the recovery step alone scales ~3.4x; the serial normalization/iteration phase caps the overall speedup).

  • verbose (bool, default True) – Print progress information.

Returns:

ChromData on the dense grid with SnapFISH-imputed coordinates.

Return type:

ChromData

Notes

Algorithm steps: 1. Densify onto the per-chrom locus panel (insert NaN rows for absent loci) 2. Linear interpolation for initialization 3. Compute pairwise distance matrices 4. Normalize by 1D genomic distance (Box-Cox transformation) 5. Iteratively impute missing distances via similarity weighting 6. Recover 3D coordinates via L-BFGS-B optimization

References

Yu, H. et al. SnapFISH-IMPUTE (2023) https://github.com/hyuyu104/SnapFISH-IMPUTE