uchrom.fea

Geometric / statistical features over chromatin traces.

class uchrom.fea.Band(chrom: str, binsize: int, starts: ndarray, i: ndarray, j: ndarray, count: ndarray, weight: ndarray | None, max_diag: int)[source]

Bases: object

One chromosome’s pixels within max_diag bins of the diagonal (upper triangle, i <= j).

binsize: int
chrom: str
count: ndarray
dense(lo: int = 0, hi: int | None = None, *, balance: bool = True) → ndarray[source]

The symmetric dense matrix of bins [lo, hi) (pixels beyond the band are 0; masked bins NaN).

property diag: ndarray
i: ndarray
j: ndarray
max_diag: int
property n: int
starts: ndarray
property valid: ndarray

Bins with a finite weight (all bins of an unbalanced map).

values(balance: bool = True) → ndarray[source]

Balanced (weight[i] * weight[j] * count; NaN on masked bins) or raw values of the pixels.

weight: ndarray | None
class uchrom.fea.Comparison[source]

Bases: dict

Result of a comparison: a dict with attribute access; scores holds its scalar entries (for a table), the other entries are arrays / tables (matrices, the shared bins).

property scores: Dict[str, float]
class uchrom.fea.ContactFeatureParams(min_distance: float = 5000.0, short: Tuple[float, float] = (200000.0, 2000000.0), long: Tuple[float, float] = (20000000.0, 50000000.0), short_bins: Tuple[int, int] | None = None, long_bins: Tuple[int, int] | None = None, bands: Sequence[Tuple[float, float]] = ((2000000.0, 12000000.0),), slopes: Sequence[Tuple[float, float]] = ((100000.0, 1000000.0), (1000000.0, 10000000.0)), chroms: Sequence[str] | None = None, per_chromosome: bool = False)[source]

Bases: object

Ranges (bp) of the contact features.

Variables:
  • min_distance (float) – Cis contacts closer than this are left out of every fraction (undigested / self-ligated fragments).

  • long (short,) – The short- and long-range ranges of short_long_ratio; short_bins / long_bins (half-open index ranges into the histogram’s distance bins, scHiCluster numbering) override them.

  • bands (Sequence[Tuple[float, float]]) – More ranges reported as fractions of the cis contacts (frac_<lo>_<hi>), e.g. the mitotic band 2-12 Mb of Nagano et al. 2017.

  • slopes (Sequence[Tuple[float, float]]) – Ranges over which the slope of log10 P(s) on log10 s is fitted (contacts per bp of distance).

  • chroms (Sequence[str] | None) – The chromosomes counted (default: all of the histograms; with per_chromosome, those whose pooled histogram over all cells has at least half the genome-wide share of long-range contacts – the chromosomes long enough for the long range).

  • per_chromosome (bool) – Each feature computed per chromosome and averaged over chroms with equal weights (needs the histograms per chromosome, ContactStats.write(per_chromosome=True)); n_cis / n_trans / n_used stay totals and trans_share.<chrom> per chromosome.

bands: Sequence[Tuple[float, float]] = ((2000000.0, 12000000.0),)
chroms: Sequence[str] | None = None
classmethod guo2026(**kw) → ContactFeatureParams[source]

The short / long ranges of Guo et al. 2026 (Spatial-Hi-C-RNA, MouseBrain/02_short_long_contact_ratio): scHiCluster bins 51-76 (207 kb - 1.97 Mb) and 103-114 (18.8 - 53.1 Mb), contacts < 5 kb removed.

long: Tuple[float, float] = (20000000.0, 50000000.0)
long_bins: Tuple[int, int] | None = None
min_distance: float = 5000.0
per_chromosome: bool = False
short: Tuple[float, float] = (200000.0, 2000000.0)
short_bins: Tuple[int, int] | None = None
slopes: Sequence[Tuple[float, float]] = ((100000.0, 1000000.0), (1000000.0, 10000000.0))
class uchrom.fea.DistanceMap[source]

Bases: dict

Result of distance_map() (a dict with attribute access): matrix (n_bins × n_bins), count (traces observing each pair; the diagonal counts the traces observing the bin), bins (bin_id, chrom, start, end of the rows), n_traces, stat, streaming, n_passes (reads of the chromosome’s traces), n_bands and duplicates. coarsen() pools it into blocks.

coarsen(k: int, stat: str = 'median', *, diagonal: bool = False) → DistanceMap[source]

The map pooled into blocks of k × k rows (e.g. 20 × 25-kb bins = 500 kb), for display or to gather the sparse pairs of a large locus panel.

Parameters:
  • k (int) – Rows per block; the last block holds the rest (n_bins % k rows) when k does not divide the number of rows. The rows are the map’s own (observed) bins, in order — gaps between bins are not filled in.

  • stat ("median" (default) or "mean") – How the finite values of a block are combined (NaN when it has none).

  • diagonal (bool) – Include the self-distances (0) of the original diagonal; by default they are left out, so the blocks on the diagonal hold the distances between the different bins of the block.

Returns:

matrix and count (pair observations pooled into each block: the sum of the original count over the block’s entries, both triangles) of the blocks, bins (chrom, start of the first bin, end of the last, n_bins), block_size = k, and the other fields of this map.

Return type:

DistanceMap

class uchrom.fea.ImputeParams(rp: float = 0.05, window: int | str | None = None, step: int | None = None, max_dist: int = 2050000, min_sep: int = 2, chain: bool = True, normalize: bool = True, edge: int = 5, trim: float = 0.01, min_sd: float = 1e-06)[source]

Bases: object

Knobs of the RWR imputation (defaults: SnapHiC at 10 kb).

Variables:
  • rp (float) – Restart probability (SnapHiC 0.05; scHiCluster 0.5).

  • window (int, "auto" or None) – None (default): each chromosome solved whole, as the published SnapHiC (in the numpy path memory and time grow as n^2 / n^3: a dense chromosome matrix); or a sliding-window size, bp (a multiple of the bin size), "auto": SnapHiC2’s rule (auto_window()).

  • step (int, optional) – Window step, bp; default half the window.

  • max_dist (int) – Band of the output, bp: pixels up to this separation (SnapHiC: the loop range plus a 50 kb buffer).

  • min_sep (int) – Contacts closer than this many bins are left out (SnapHiC removes neighbouring bins: 2).

  • chain (bool) – Link neighbouring bins (SnapHiC).

  • normalize (bool) – SnapHiC’s z-scores per diagonal (zscore_band()) instead of the raw RWR values.

  • edge (int) – Bins at each chromosome end left out of the z-scores (SnapHiC: the 50 kb buffer, 5 bins at 10 kb).

  • trim (float) – Share of each diagonal’s largest values left out of its mean / standard deviation (1 %).

  • min_sd (float) – Diagonals with a smaller standard deviation are set to 0.

chain: bool = True
edge: int = 5
max_dist: int = 2050000
min_sd: float = 1e-06
min_sep: int = 2
normalize: bool = True
rp: float = 0.05
step: int | None = None
trim: float = 0.01
window: int | str | None = None
class uchrom.fea.SeparationParams(short: Tuple[float, float] = (1000000.0, 2000000.0), long: Tuple[float, float] = (19000000.0, 54000000.0), edges: Sequence[float] | None = None, chroms: Sequence[str] | None = None, exclude: Sequence[str] = ('chrX', 'chrY', 'chrM'), stat: str = 'median', threshold: float | None = None, pseudocount: float = 0.5, duplicates: str = 'last')[source]

Bases: object

Ranges and reductions of separation_profile().

Variables:
  • long (short,) – Half-open separation ranges [lo, hi) (bp, midpoint to midpoint) of the summary. The defaults take map offset 1 (1 Mb) and offsets 19-53 of a 1-Mb map, and loci 1-2 Mb and 19-54 Mb apart.

  • edges (Sequence[float] | None) – Separation bin edges (bp, increasing; bins [edges[k], edges[k + 1])) of the profile stored per cell; None: no profile.

  • chroms (Sequence[str] | None) – The chromosomes used (default: every chromosome but those in exclude).

  • exclude (Sequence[str]) – Left out when chroms is not given (matched without the chr prefix, any case): the sex chromosomes, whose copy number differs between cells and sexes, and the mitochondrial genome.

  • stat (str) – "median" (default) or "mean" distance of a cell’s pairs in a range (coordinates).

  • threshold (float | None) – Coordinates: also the share of a cell’s pairs in a range closer than this distance (the units of the coordinates), f_short / f_long.

  • pseudocount (float) – Added to both counts of the contact ratio (cells without contacts in a range keep a finite ratio).

  • duplicates (str) – Coordinates: the spot a trace keeps at a bin it observed more than once ("last", "first", "mean", "median"; as uchrom.fea.distance_map()).

chroms: Sequence[str] | None = None
duplicates: str = 'last'
edges: Sequence[float] | None = None
exclude: Sequence[str] = ('chrX', 'chrY', 'chrM')
long: Tuple[float, float] = (19000000.0, 54000000.0)
pseudocount: float = 0.5
short: Tuple[float, float] = (1000000.0, 2000000.0)
stat: str = 'median'
threshold: float | None = None
uchrom.fea.add_annotation_features(cdata, gtf: str | Path | DataFrame, *, features: Sequence[str] | None = None, prefix: str = 'gtf', result_key: str = 'bin_features', project: bool = True, store: bool = True, overwrite: bool = False, promoter_window: tuple[int, int] = (-2000, 500), hash_source: bool = False) → DataFrame[source]

Compute annotation features for the loci of a ChromData and write them to cd.bin_tracks.

gtf is a GTF / GFF path or a table from read_gtf(); a UCSC refGene GTF, which has transcripts but no gene rows, works as is (gene bodies are derived from the transcripts, gene_bodies()). The features (gene_body_overlap_bp / _fraction, gene_count, exon_overlap_*, promoter_overlap_* with the promoter promoter_window around the TSS, nearest_tss_distance) go to cd.bin_tracks as <prefix>.<feature> (project=True) and to cd.results[result_key] (store=True), with an entry in cd.uns["feature_registry"]; the per-locus table is returned.

uchrom.fea.add_peak_features(cdata, peaks: DataFrame, *, name: str = 'peak', prefix: str = 'peak', result_key: str = 'bin_features', project: bool = True, store: bool = True, overwrite: bool = False, source_peak_key: str | None = None) → DataFrame[source]

Project an existing peak table into interval and spot features.

uchrom.fea.add_sequence_features(cdata, fasta: str | Path, *, features: Sequence[str] | None = None, prefix: str = 'seq', result_key: str = 'bin_features', project: bool = True, store: bool = True, overwrite: bool = False, hash_source: bool = False, g4_pattern: str = 'G{3,}[ACGTN]{1,7}G{3,}[ACGTN]{1,7}G{3,}[ACGTN]{1,7}G{3,}') → DataFrame[source]

Compute sequence features for a ChromData object.

The canonical interval table is returned. When store=True it is also merged into cdata.results[result_key]. When project=True feature columns are projected onto cdata.bin_tracks using prefix.

uchrom.fea.aggregate_track_by_interval(cdata, track: str, *, agg: str = 'mean', signal_col: str = 'signal') → DataFrame[source]

Aggregate a spot-aligned track to unique genomic intervals.

Multiple spots can share the same genomic bin across cells or traces. Peak callers should operate on the genomic bin signal rather than individual spot rows, so this helper collapses duplicate intervals first.

uchrom.fea.aggregate_tracks_by_interval(cdata, tracks: Sequence[str], *, agg: str = 'mean') → DataFrame[source]

Aggregate multiple spot-aligned tracks to unique genomic intervals.

uchrom.fea.append_feature_registry_entry(cdata, entry: Mapping[str, Any], *, key: str = 'feature_registry') → dict[str, Any][source]

Append a provenance record to cdata.uns[key].

The registry is stored as a list of JSON-like dicts so it round-trips through the existing uns serializer.

uchrom.fea.axis_variance_cube(cd, chrom: str, device: str = 'auto') → dict[source]

Per-axis pairwise variance and count cubes of one chromosome, before filtering.

Returns a dict with var, count, mean (all (3, B, B)), bin_ids, n_traces, chrom, axis_weight (axis_weight() of the same cube) and, for filter_normalize(), the (T, B, 3) coordinate tensor on the torch device under "coords". Pairwise differences are formed block by block, so memory stays near _BLOCK_BYTES whatever B.

uchrom.fea.axis_weight(cd, chrom: str | None = None, device: str = 'auto') → ndarray[source]

ArcFISH’s axis weights of a chromosome (module docstring, step 3): per axis, each trace centred at its mean over the loci, the mean square of each locus over the traces, 1 / median over the loci, normalised to sum 1.

chrom=None averages the weights of every chromosome. device is accepted for compatibility (numpy).

uchrom.fea.band_observed_over_expected(band: Band, expected: DataFrame | None = None) → ndarray[source]

Observed / expected (balanced) of every pixel of band: the expected per diagonal of its chromosome (expected_cis(); computed from the band when not given). NaN where the expected is 0 or a bin is masked.

uchrom.fea.bin_index(bins, chrom, pos, *, closed: str = 'left') → ndarray[source]

The row of bins (0 .. len(bins) - 1) whose interval holds each position; -1 when none does.

Parameters:
  • bins – A table with chrom, start, end (or a ChromData: its bins); intervals of one chromosome must not overlap; gaps are allowed.

  • chrom – A chromosome and a position (bp) per query (arrays of the same length, or a scalar chromosome).

  • pos – A chromosome and a position (bp) per query (arrays of the same length, or a scalar chromosome).

  • closed – "left": [start, end) (genomic bins); "right": (start, end] (NucDynamics particles).

uchrom.fea.call_macs_bdgpeaks_from_bedgraph(path: str | Path, *, signal_col: str = 'score', cutoff: float = 5.0, min_length: int = 200, max_gap: int = 30, name: str = 'MACS', name_prefix: str | None = None) → DataFrame[source]

Read a bedGraph file and call MACS3 bdgpeakcall-compatible peaks.

uchrom.fea.call_macs_bdgpeaks_from_signal(signal_table: DataFrame, *, signal_col: str = 'score', cutoff: float = 5.0, min_length: int = 200, max_gap: int = 30, name: str = 'MACS', name_prefix: str | None = None) → DataFrame[source]

Call peaks using a Python port of MACS3 bdgpeakcall.

This mirrors MACS3’s bedGraphTrackI.call_peaks behavior for score tracks: regions with values at or above cutoff are merged when the intervening gap is at most max_gap bases, peaks shorter than min_length bases are discarded, and the summit follows MACS3’s tie-breaking rule. The port follows MACS3’s BSD-licensed bdgpeakcall and narrowPeak semantics without vendoring the MACS3 package at runtime.

uchrom.fea.call_macs_peaks_from_signal(signal_table: DataFrame, *, signal_col: str = 'signal', control_col: str | None = None, qvalue: float | None = 0.05, pvalue: float | None = None, genome_size: int | float | None = None, small_local_window_bins: int = 10, large_local_window_bins: int = 100, fragment_size_bins: int = 1, nolambda: bool = False, min_width_bins: int = 1, max_gap_bins: int = 0, signal_scale: float = 1.0, control_scale: float | None = None, negative: str = 'clip', name: str = 'peak') → DataFrame[source]

Call peaks with U-Chrom’s legacy dynamic Poisson approximation.

Observed binned signal is tested against a dynamic local lambda using Poisson tail probabilities, p-values are Benjamini-Hochberg adjusted, and significant adjacent bins are merged into peak intervals. Use call_macs_bdgpeaks_from_signal for the MACS3 bdgpeakcall port.

uchrom.fea.call_peaks_from_signal(signal_table: DataFrame, *, signal_col: str = 'signal', threshold: float | None = None, quantile: float = 0.95, min_width_bins: int = 1, max_gap_bins: int = 0, name: str = 'peak') → DataFrame[source]

Call simple contiguous high-signal peaks from an interval signal table.

The input table should have chrom, start, end, and signal_col. If threshold is omitted it is estimated from the requested quantile of finite signal values.

uchrom.fea.call_peaks_from_track(cdata, track: str, *, method: str = 'auto', control_track: str | None = None, agg: str = 'mean', threshold: float | None = None, quantile: float = 0.95, cutoff: float | None = None, min_length: int = 200, max_gap: int = 30, qvalue: float | None = 0.05, pvalue: float | None = None, genome_size: int | float | None = None, small_local_window_bins: int = 10, large_local_window_bins: int = 100, fragment_size_bins: int = 1, nolambda: bool = False, min_width_bins: int = 1, max_gap_bins: int = 0, signal_scale: float = 1.0, control_scale: float | None = None, negative: str = 'clip', peaks_key: str | None = None, feature_name: str | None = None, prefix: str = 'peak', result_key: str = 'bin_features', project: bool = True, store: bool = True, overwrite: bool = False) → DataFrame[source]

Aggregate a track, call peaks, and project peak features to bins.

uchrom.fea.chromosome_dosage(cd, *, key: str = 'contacts', cells=None, groupby: str | None = None, exclude: Sequence[str] = ('chrY',), n_pcs: int = 0, key_added=UNSET, copy: bool = False)[source]

Per-cell copy-number profile from the contacts: log2 of each chromosome’s share of the cell’s contact legs over the cells’ median share.

A cis contact puts two legs on its chromosome, a trans contact one on each of its two. A chromosome present in three copies instead of two carries about 1.5 times the legs, so the log2 share over the median is about the log2 of its copies over the typical cell’s: a coverage profile at the resolution of whole chromosomes, as a copy-number caller reads from sequencing depth. It is a proxy. It is relative to the median cell, so a gain that every cell carries does not show. The shares sum to one, so a gain lowers the other chromosomes a little. And anything else that changes how many contacts a chromosome gives shifts it too.

Parameters:
  • cd – A ChromData with ContactStats.write(cd, key=key).

  • key – The contact statistics’ key.

  • cells – Only these cells (default all); the median is taken over them.

  • groupby – A cd.cells column (section, sample): the median of each group is its cells’ reference.

  • exclude – Chromosomes left out of the shares (default chrY: a few contacts or none).

  • n_pcs – Also the first n_pcs principal components of the profiles (each chromosome z-scored over the cells, missing values at 0; signs arbitrary): the axes along which the cells’ profiles differ most. A tumour clone changes several chromosomes at once, so one component can carry its whole pattern; as covariates they stand for copy number in a spatial test (uchrom.spatial.spatially_variable()).

  • key_added – Where to store (default "<key>.dosage"; None: nothing stored): cd.cellm[key_added] (n_cells, n_chroms; NaN for cells left out), cd.cellm["<key_added>.pcs"] and the table cd.results[key_added].

Returns:

Indexed by cell id (in the order of cells): one column per chromosome, then PC1 … with n_pcs. A cell without contacts, or a chromosome without legs in a cell, is NaN. attrs["pc_variance"]: the share of the z-scored profiles’ variance of each component.

Return type:

DataFrame

uchrom.fea.cluster_pixels(cd, key: str, *, chromsizes: Mapping, resolution: int, cells=None, min_size: int = 2, max_size: int | None = 1000) → Tuple[DataFrame, DataFrame][source]

Binned fragment pairs of the clusters cd.clusters[key] (of cells, default all).

Returns (bins, pixels): the genome bins of chromsizes (chrom, start, end) and the upper-triangle pixels bin1_id, bin2_id, count (count = fragment pairs; a fragment is binned by its start).

uchrom.fea.clusters_to_mcool(cd, key: str, out: str | PathLike, *, chromsizes: Mapping, resolutions: Sequence[int], cells=None, min_size: int = 2, max_size: int | None = 1000, balance: bool = True, link_key: str | None = None, label: str | None = None, n_threads: int = 1) → Path[source]

The fragment pairs of the clusters cd.clusters[key] (of cells, default all) pooled into one .mcool: binned at the finest of resolutions, coarsened to the others (cooler.zoomify_cooler), ICE-balanced when balance; linked as link_key (default f"{key}_pooled") with cd.link_cool.

uchrom.fea.clusters_to_scool(cd, key: str, out: str | PathLike, *, chromsizes: Mapping, resolution: int, min_size: int = 2, max_size: int | None = 1000, link_key: str | None = None, label: str | None = None) → DataFrame[source]

One map per cell of cd.clusters[key] in a .scool (cell names = cell ids), linked as link_key (default key) with cd.link_scool.

Returns per cell: n_clusters (of min_size–max_size fragments), n_pairs (fragment pairs in the kept chromosomes), n_cis and n_pixels.

uchrom.fea.compare_distances(cd, ref, *, bins=None, stat: str = 'median', by: str = 'trace', position: str = 'mid', closed: str | None = None) → Comparison[source]

Distance statistics of two objects on shared bins — a structure (or a population of structures) against chromatin tracing, typically.

Both are averaged onto the same bins (rebin_coords(), per trace), the pairwise distances of every trace are reduced to one matrix per object (median over traces; a single structure is its own distance matrix), and the two matrices are compared over the bin pairs both observe.

Parameters:
  • cd – The model: a structure, a population (one trace per chromosome copy), or any traced data.

  • ref – The reference, e.g. chromatin tracing (distances in nm).

  • bins – The shared grid (default: the bins of cd).

  • stat – "median" or "mean" over traces.

  • by – Group spots by "trace" (default) or "cell".

  • position – How spots are put onto the grid (see rebin_coords()).

  • closed – How spots are put onto the grid (see rebin_coords()).

Returns:

pearson (Pearson r of the two matrices over the shared pairs), rel_error (mean of |s * d_cd - d_ref| / d_ref after rescaling cd by the least-squares factor s of that error, GEM-FISH’s error measure), scale (s: units of ref per unit of cd), ratio (median of d_cd / d_ref), n_bins, n_pairs; bins (the shared bins: rows of the grid, with their positions in it as the index), model and reference (the two matrices on them).

Return type:

Comparison

uchrom.fea.compare_structures(cd, ref, *, n_models: int | None = None, ref_models: int | None = None, position: str = 'mid', closed: str | None = None, min_particles: int = 10) → Comparison[source]

Two structure ensembles of one cell compared model by model — e.g. a reconstruction against the published structures of the same cell, or two solvers.

The particles of ref are averaged onto the particles of cd (a particle of ref goes to the particle of cd whose interval holds its position); then, for every model of cd and every model of ref, distance_correlation() by chromosome over the particles of cd that received one.

Parameters:
  • cd – One structure (ensemble) with one particle per bin (haploid; e.g. one cell).

  • ref – The other one (any particles; e.g. ds.load("stevens2017_mesc").get_cell("Cell_1")).

  • n_models – Use the first models of each ensemble (ensemble_models(); None: all).

  • ref_models – Use the first models of each ensemble (ensemble_models(); None: all).

  • position – The position of a ref particle: "mid", "start" or "end" of its locus.

  • closed – The intervals of cd’s particles (None: as the reconstruction recorded, see the module).

  • min_particles – Chromosomes with fewer matched particles are left out.

Returns:

distance_r (mean over the model pairs of the median correlation by chromosome), n_particles (particles of cd matched), r (n_models x ref_models).

Return type:

Comparison

uchrom.fea.compute_annotation_features(intervals: DataFrame, gtf: str | Path | DataFrame, *, features: Sequence[str] | None = None, promoter_window: tuple[int, int] = (-2000, 500), gene_feature: str = 'gene', exon_feature: str = 'exon') → DataFrame[source]

Compute GTF-derived features for genomic intervals.

The returned table preserves the input interval order and uses 0-based half-open coordinates. Gene bodies, TSSs and promoters come from the gene_feature rows; an annotation without them but with transcript rows (UCSC refGene) gets them from the transcripts (gene_bodies()), as read_gtf() does.

uchrom.fea.compute_peak_features(intervals: DataFrame, peaks: DataFrame, *, name: str = 'peak') → DataFrame[source]

Compute overlap/count/distance features from peak intervals.

uchrom.fea.compute_sequence_features(intervals: DataFrame, fasta: str | Path, *, features: Sequence[str] | None = None, g4_pattern: str = 'G{3,}[ACGTN]{1,7}G{3,}[ACGTN]{1,7}G{3,}[ACGTN]{1,7}G{3,}', missing: str = 'raise') → DataFrame[source]

Compute FASTA-derived features for genomic intervals.

Parameters:
  • intervals – DataFrame with chrom, start, and end columns.

  • fasta – FASTA file path. Plain text and .gz files are supported.

  • features – Sequence feature names. Defaults to DEFAULT_SEQUENCE_FEATURES; OPTIONAL_SEQUENCE_FEATURES (cpg_frequency: CG over the A/C/G/T dinucleotides that lie in the interval) on request.

  • g4_pattern – Regular expression used for G-quadruplex motif counting.

  • missing – "raise" to reject intervals whose chromosomes are absent from the FASTA, or "ignore" to leave their feature values as NaN.

  • to (An interval that runs past the end of its sequence (the last fixed-size bin of a chromosome) is clipped)

  • it (its features describe the sequence that exists; one that starts past the end is an error.)

Returns:

Interval columns plus requested feature columns, preserving the input row order.

Return type:

DataFrame

uchrom.fea.contact_agreement(cd, hic, *, contacts: str | None = None, chrom=None, resolution: int | None = None, balance: bool = True, max_separation: float | None = None, closed: str | None = None) → Comparison[source]

How well a structure reproduces a contact map: Spearman correlation of the contact frequency and 1 / distance over the bin pairs, raw and after removing the distance decay (both sides divided by their mean at each genomic separation — in bins of the map, so bins the structure lacks leave gaps — observed_over_expected()).

Parameters:
  • cd – A structure (or a population: median distance over its traces).

  • hic – A ChromData with the map linked (may be cd itself), or the path of a .cool / .mcool.

  • contacts – Key of the linked map (None: the only one).

  • chrom – Chromosome(s) (default: those of cd); pairs of different chromosomes are not compared.

  • resolution – The map level (an .mcool) and whether to use balanced values (see contact_matrix()).

  • balance – The map level (an .mcool) and whether to use balanced values (see contact_matrix()).

  • max_separation – Only pairs at most this far apart (bp, bin starts).

  • closed – How the particles of cd are put onto the map’s bins (by the midpoint of their locus).

Returns:

spearman (pairs with contacts), spearman_oe, n_pairs.

Return type:

Comparison

uchrom.fea.contact_distances(cd, contacts, *, layer: str | None = None, closed: str | None = None) → ndarray[source]

The distance, in a structure, between the two ends of every contact.

Each end goes to the particle whose interval holds its position.

Parameters:
  • cd – One structure with one particle per bin (haploid; e.g. reconstruct_ember output).

  • contacts – A table / dict with chrom_a, pos_a, chrom_b, pos_b (e.g. uchrom.recon.sc.nucdyn.load_contacts(path)).

  • layer – A model layer instead of coords (model 0).

  • closed – The particles’ intervals (None: as the reconstruction recorded; NucDynamics: (start, end]).

Returns:

  • ndarray, one distance per contact — NaN where an end has no particle or both ends fall into the same

  • particle (no restraint between two particles).

uchrom.fea.contact_features(cd, *, key: str = 'contacts', cells=None, params: ContactFeatureParams | None = None, key_added=UNSET, copy: bool = False)[source]

Per-cell contact features from the stored contact-distance histograms.

Parameters:
  • cd – A ChromData with ContactStats.write(cd, key=key).

  • key – The histograms’ key.

  • cells – Only these cells (default all).

  • params – ContactFeatureParams (default: Guo et al. 2026’s ranges by bin centre).

  • key_added – Prefix of the cd.cells columns written (default key; None: nothing written) — e.g. contacts.short_long_ratio; the table is also cd.results["<key_added>.features"].

Returns:

Indexed by cell id: n_cis (all distances), n_trans, cis_fraction, n_used (cis at >= min_distance), frac_short, frac_long, short_long_ratio, frac_<band>, ps_slope_<range>, trans_share.<chrom> (each chromosome’s trans legs over all its legs).

Return type:

DataFrame

uchrom.fea.contact_frequency(data, threshold: float, chrom=None, *, trace_ids: Iterable | None = None, cells: Iterable | None = None, duplicates: str = 'last', streaming=None, batch='auto', memory_budget=None)[source]

Fraction of traces where a pair of bins are within threshold.

NaN distances (missing spots) are excluded from both numerator and denominator — each bin pair’s frequency is over the set of traces that have both endpoints detected.

Parameters:
  • data (ChromData or DataFrame) – A ChromData (in memory or backed: the traces are streamed as by distance_map(), so no (n_traces, n_bins, n_bins) tensor is built), or the flat table chrom, start, end, x, y, z, trace_id (to_dataframe(); the dense computation). Both give the same matrix.

  • threshold (float) – Distance threshold in the unit of the coordinates.

  • chrom (str, optional) – The chromosome; with a ChromData it may be left out when the data have one.

  • trace_ids (optional) – Use only these traces / cells.

  • cells (optional) – Use only these traces / cells.

  • duplicates ("last" (default), "first", "mean" or "median") – With a ChromData: the spot a trace keeps at a bin it observed twice (see distance_map()). The table form keeps the last.

  • streaming – With a ChromData: as for distance_map().

  • batch – With a ChromData: as for distance_map().

  • memory_budget – With a ChromData: as for distance_map().

Returns:

  • frequency (ndarray (n_bins, n_bins) in [0, 1], NaN where no) – trace had both endpoints detected; rows = the observed bins sorted by start.

  • bin_ids (list of (start, end))

  • n_traces (int)

uchrom.fea.contact_matrix(cd, contacts: str | None = None, *, chrom: str, resolution: int | None = None, balance: bool = True) → Tuple[DataFrame, ndarray][source]

The contact matrix of one chromosome from a linked map.

Parameters:
  • cd – A ChromData with the map linked (cd.link_cool), the path of a .cool / .mcool, or a cooler.Cooler (open_map(); resolution is then ignored).

  • contacts – Key of the linked map (None: the only one) or the path of a map.

  • chrom – Chromosome (as named in the map).

  • resolution – The level of an .mcool (required when it has several); checked against a .cool.

  • balance – Balanced values (the cooler weight column; raw counts with a warning when the map has none).

Returns:

  • bins (DataFrame) – chrom, start, end of the rows (index 0..n-1).

  • matrix (ndarray (n, n)) – float64; masked (NaN) entries of a balanced map are 0.

uchrom.fea.distance_correlation(a, b, *, groups=None, min_size: int = 10) → float[source]

Pearson correlation of the pairwise distances of two coordinate sets of the same points — the median over groups (e.g. chromosomes) of the correlation within each group.

Parameters:
  • a – (n, 3) coordinates, row i the same point in both.

  • b – (n, 3) coordinates, row i the same point in both.

  • groups – A label per row (e.g. the chromosome); None: one group. Only distances within a group count.

  • min_size – Groups with fewer points are left out.

Return type:

The median correlation (NaN when no group is large enough).

uchrom.fea.distance_map(cd, chrom=None, stat: str = 'median', *, trace_ids: Iterable | None = None, cells: Iterable | None = None, duplicates: str = 'last', streaming=None, batch='auto', memory_budget=None, observed: bool = True) → DistanceMap[source]

Population median / mean 3-D distance of every bin pair of one chromosome — exact, in memory or streaming over the traces.

Same definition as mean_distance_matrix() (per trace, the Euclidean distance of its two spots; NaN / missing spots skipped; a trace observing a bin twice keeps its last spot, unless duplicates says otherwise), but without the dense (n_traces, n_bins, n_bins) tensor, so it runs on genome-wide data:

  • stat="mean" accumulates per-pair sums and counts in trace order (np.add.at) — the additions the dense np.nanmean makes, in the same order, so the result is bitwise identical (float64); memory O(n_bins²).

  • stat="median" is an exact median (the mean of the two middle values for an even count, as np.nanmedian). An exact median needs all values of a pair at once, so the observations are gathered for one row band of the matrix at a time — the rows i whose pairs (i, j > i) fit memory_budget (BYTES_PER_OBS bytes each) — and reduced with a grouped median (pandas). A band costs one pass over the chromosome’s traces; memory is the band plus the n_bins² output, independent of the number of traces. No approximation.

Parameters:
  • cd (ChromData, in memory or backed)

  • chrom (str, optional) – The chromosome; may be left out when the data have one.

  • stat ("median" or "mean")

  • trace_ids (optional) – Use only these traces / cells (read in memory first).

  • cells (optional) – Use only these traces / cells (read in memory first).

  • duplicates ("last" (default), "first", "mean" or "median") – The spot a trace keeps at a bin it observed more than once (sister chromatids, a stray spot): its last or first one, or the per-axis mean / median of them (NaN values skipped) — exactly the coordinates uchrom.im.merge_duplicate_spots() (how=) gives, so distance_map(cd, c, duplicates="mean") equals distance_map(merge_duplicate_spots(cd), c).

  • streaming (bool, optional) – Read the traces in batches (iter_traces(chrom=..., columns="coords")) and band the median; default True for a backed object. False gathers every observation at once (the in-memory baseline).

  • batch (int or "auto") – Traces per batch, or "auto" (from the memory budget).

  • memory_budget (default uchrom.settings.memory_budget)

  • observed (rows / columns = the chromosome's observed bins sorted by) – start (the mean_distance_matrix() convention), or every bin of the chromosome in cd.bins

Return type:

DistanceMap

uchrom.fea.ensemble_agreement(cd, *, n_by_chrom: int | None = 4, min_particles: int = 10, reflection: bool = False) → Comparison[source]

How much the models of an ensemble (ensemble_models()) agree.

Parameters:
  • cd – One structure ensemble (e.g. reconstruct_nucdyn / reconstruct_ember output, or one cell of published structures).

  • n_by_chrom – The per-chromosome measures use the pairs of the first n_by_chrom models (None: all; each pair costs a distance matrix per chromosome).

  • min_particles – Chromosomes (traces) with fewer particles are left out of the per-chromosome measures.

  • reflection – Allow mirror images in the superposition (see kabsch_rmsd()).

Returns:

rmsd (n_models x n_models, genome-wide RMSD after superposition), rmsd_mean (mean over the pairs), rmsd_per_chrom (median over model pairs and chromosomes of the RMSD of one chromosome superposed alone), distance_r (median over model pairs of distance_correlation() by chromosome), n_models. Per chromosome means per trace (a chromosome copy).

Return type:

Comparison

uchrom.fea.ensemble_models(cd) → List[ndarray][source]

The models of a structure ensemble, each (n_spots, 3) in spot order: the layers model_<k> in the order of k, preceded by coords unless it is one of them (a reconstruction keeps model 0 in coords and every model as a layer; a published ensemble may keep model 1 in coords and models 2-10 as layers). Without such layers: [coords].

uchrom.fea.expected_cis(cd, contacts: str | None = None, *, chroms: Sequence[str] | None = None, resolution: int | None = None, max_dist: int | None = None, balance: bool = True, bands: Iterable[Band] | None = None) → DataFrame[source]

Mean contact per separation, per chromosome: chrom, diag, dist, n_valid, count_sum, balanced_sum, balanced_avg (balanced_avg = balanced_sum / n_valid over the pairs of unmasked bins).

Give bands (read_band() results) to reuse pixels already read; otherwise every chromosome of the map (or chroms) is read up to max_dist.

uchrom.fea.filter_clusters(cd, key: str, *, min_size: int = 2, max_size: int | None = 1000, min_chrom_share: float = 0.15, min_cis_share: float = 0.2, key_added: str | None = None)[source]

The clusters of cd.clusters[key] filtered as the SpaceA authors filter them (Ma et al. 2026; their 2_Filter_SpotsClustersReads/filter_sprite.py, spot_qc, at commit c1e1753 of github.com/YuetongXU/SpaceA-Paper), stored as cd.clusters[key_added] (default f"{key}_filtered").

  1. clusters of min_size–max_size fragments are kept;

  2. in each, the fragments of a chromosome holding no more than min_chrom_share of the cluster are dropped;

  3. a cluster whose remaining fragment pairs are less than min_cis_share within a chromosome (or that keeps fewer than two fragments) is dropped.

Clusters mixing the fragments of several complexes (two barcodes alike) are mostly trans; the filter keeps the part of a cluster that is on its main chromosomes. As the authors count reads by chromosome and start, fragments of a cluster with the same start count once (the first is kept). Returns the new table.

uchrom.fea.filter_normalize(cube: dict, k_sigma: float = 4.0, frac: float = 0.1) → dict[source]

ArcFISH’s outlier filter and normalisation by genomic distance (module docstring, step 2).

Rebuilds the (3, n_traces, n_bins, n_bins) pairwise differences block by block from cube['coords']. Output (numpy, on CPU): var (filtered variance), count (traces left per pair), norm_var, expected, raw_var, genomic_distance, plus the input’s other keys; the device tensor under "coords" is dropped.

uchrom.fea.gene_bodies(annotations: DataFrame, *, transcript_feature: str = 'transcript') → DataFrame[source]

Gene rows from transcript rows: one per gene locus, the span of a gene’s overlapping transcripts.

The transcripts of a gene_id on one strand are sorted by start and merged while they overlap (or touch); a gene id found at several places (paralogous copies, _alt / _fix contigs) gives one row per place.

Parameters:
  • annotations (DataFrame) – An annotation table (read_gtf()) with chrom, feature, start, end, strand, gene_id.

  • transcript_feature (str) – The feature of the transcript rows.

Returns:

The columns of annotations with feature = "gene" (source = "<source>:derived" when there is a source column), sorted by gene_id, strand and start.

Return type:

DataFrame

uchrom.fea.ice(b1: ndarray, b2: ndarray, count: ndarray, chrom_offsets: ndarray, *, cis_only: bool = False, ignore_diags: int = 2, min_nnz: int = 10, mad_max: float = 5, tol: float = 1e-05, max_iters: int = 200) → Tuple[ndarray, dict][source]

Iterative correction (ICE; Imakaev et al. 2012, Nat Methods 9:999) of an in-memory map, the algorithm and filters of cooler.balance_cooler (Abdennur & Mirny 2020; as of cooler 0.12) without re-reading the file each iteration.

Pixels of one chromosome with |bin1 - bin2| < ignore_diags (and, cis_only, the trans pixels) are left out — neighbouring bins across a chromosome boundary are trans; bins with fewer than min_nnz non-zero pixels, and bins whose marginal (normalised by its chromosome’s median) lies mad_max median absolute deviations below the median in log space, are masked; then the bias is divided by the normalised marginal of the bias-corrected map until the marginals’ variance is under tol, and rescaled so that the balanced marginals are 1; bins left with no data are masked. The main diagonal counts once in the marginals. cis_only: each chromosome on its own.

Parameters:
  • b1 – Upper-triangle pixels (genome-wide bin ids).

  • b2 – Upper-triangle pixels (genome-wide bin ids).

  • count – Upper-triangle pixels (genome-wide bin ids).

  • chrom_offsets – First bin of every chromosome plus the number of bins (cooler’s indexes/chrom_offset).

Returns:

  • bias (ndarray (n_bins,)) – Balanced = count * bias[i] * bias[j]; NaN on masked bins.

  • stats (dict) – As cooler.balance_cooler: tol, min_nnz, min_count, mad_max, cis_only, trans_only, ignore_diags, scale, converged, var, divisive_weights (per chromosome when cis_only).

uchrom.fea.impute_maps(cd, *, contacts: str = 'per_cell', cells: Sequence | None = None, chrom: None | str | Sequence[str] = None, params: ImputeParams | None = None, backend: str | None = None, n_threads: int = 0) → Iterator[Tuple[str, str, ndarray]][source]

Impute the per-cell contact maps of cd by random walk with restart (SnapHiC; Yu et al. 2021 — or scHiCluster’s RWR with rp=0.5, Zhou et al. 2019): yields (cell, chrom, band) per cell and chromosome, chromosome by chromosome.

Parameters:
  • cd (ChromData) – With per-cell maps linked (cd.link_scool; or embedded in its atlas store: the cells are exported once, cis only).

  • contacts (str) – Key of the linked per-cell maps, or the path of a .scool named by cell id.

  • cells (sequence, optional) – Cell ids (default: every cell of cd.cells).

  • chrom (str or sequence, optional) – Chromosomes (default: the autosomes of the maps).

  • params (ImputeParams, optional) – RWR and normalisation settings (default: SnapHiC’s, whole chromosomes). window="auto" is chosen from the contacts of cells on the autosomes of the maps.

  • backend – See rwr_band().

  • n_threads – See rwr_band().

Yields:

(cell, chrom, band) – band: (n_bins, max_diag + 1) float64, band[i, d] = imputed contact of bins i and i + d (z-scores with params.normalize; NaN beyond the chromosome, on the diagonal when normalised).

uchrom.fea.kabsch_rmsd(a, b, *, reflection: bool = False) → float[source]

Root-mean-square deviation of two coordinate sets of the same points after optimal superposition (translation + rotation, Kabsch 1976).

Parameters:
  • a – (n, 3) coordinates, row i the same point in both; rows with a NaN in either are left out.

  • b – (n, 3) coordinates, row i the same point in both; rows with a NaN in either are left out.

  • reflection – Allow the mirror image as well (an improper rotation) — for structures computed from contacts, which a structure and its mirror image satisfy equally.

Return type:

RMSD in the units of the coordinates.

uchrom.fea.macs_bdgpeaks_to_narrowpeak(peaks: DataFrame, *, name: str = 'MACS', name_prefix: str | None = None, trackline: bool = False, score_column: str = 'score') → str[source]

Render MACS bdgpeakcall-compatible peaks as narrowPeak text.

uchrom.fea.map_path(cd, contacts: str | None = None, *, resolution: int | None = None) → str[source]

Path of a contact map: the file linked to cd under contacts (None: the only linked map; an embedded copy is exported once — only the level resolution when given —, see chromdata.ChromData.linked_cool_path()), or contacts itself when it is not a linked key but the path of a .cool / .mcool — or cd itself when it is such a path.

uchrom.fea.match_spots(a, b, on=None) → Tuple[ndarray, ndarray][source]

Rows of the same spots in two objects (e.g. before and after a round trip through a store, which sorts the spots).

Parameters:
  • a – ChromData objects.

  • b – ChromData objects.

  • on – Spot column(s) that identify a spot; default "spot_id" when both have it, else the cell, trace and locus (cell_id, trace_id, chrom, start, end, those present in both).

Returns:

Row positions such that a row ia[k] and b row ib[k] are the same spot, sorted by the key; spots of only one object are left out.

Return type:

(ia, ib)

uchrom.fea.mean_distance_matrix(data, chrom=None, reduce: str = 'median', *, trace_ids: Iterable | None = None, cells: Iterable | None = None)[source]

Population median / mean pairwise distance matrix — the dense reference of distance_map().

For each pair of genomic bins (i, j), the distance is computed per trace and then reduced across traces with np.nanmedian (the Bintu 2018 convention) or np.nanmean. The whole (n_traces, n_bins, n_bins) tensor is built, so this is for a locus of a few hundred bins; distance_map() gives the same matrix without it.

Parameters:
  • data (ChromData or DataFrame) – A ChromData, or the flat table chrom, start, end, x, y, z, trace_id (to_dataframe()).

  • chrom (str, optional) – The chromosome; with a ChromData it may be left out when the data have one. A table without chrom is used whole.

  • reduce ("median" (default) or "mean")

  • trace_ids (optional) – Use only these traces / cells.

  • cells (optional) – Use only these traces / cells.

Returns:

  • matrix (ndarray (n_bins, n_bins)) – Rows / columns = the observed bins sorted by start; a trace observing a bin twice keeps its last spot (merge them first with uchrom.im.merge_duplicate_spots()).

  • bin_ids (list of (start, end))

  • n_traces (int)

uchrom.fea.observed_over_expected(matrix, *, positions=None) → ndarray[source]

Every entry of a contact (or distance) matrix divided by the mean at its genomic separation.

The expected value of a separation is the mean of its positive, finite entries; entries that are not positive (or NaN) and the diagonal are NaN in the result.

Parameters:
  • matrix – Square, symmetric (n, n).

  • positions – Genomic position of every row (e.g. bin starts). Default: the rows are equally spaced, so the separation is the diagonal; with gaps (bins left out), entries are grouped by their separation |positions[i] - positions[j]| instead.

Return type:

ndarray (n, n), symmetric.

uchrom.fea.open_map(cd, contacts: str | None = None, *, resolution: int | None = None)[source]

A contact map as a cooler.Cooler.

Parameters:
  • cd – A ChromData with the map linked (cd.link_cool), or the path of a .cool / .mcool.

  • contacts – Key of the linked map (None: the only one) or the path of a map.

  • resolution – The level of an .mcool (required when it has several); checked against a .cool.

Return type:

cooler.Cooler

uchrom.fea.pileup(cd, features, *, contacts=None, resolution: int | None = None, chrom=None, flank: int | None = None, expected: bool | DataFrame = True, balance: bool = True, min_separation: int | None = None, max_separation: int | None = None, corner: int | None = None, ignore_diags: int = 2, aggregate: str = 'sum', shifts: Sequence[int] | None = None, key_added: str | None = 'pileup', copy: bool = False)[source]

The average observed / expected Hi-C map around a set of features (APA; Rao et al. 2014).

Parameters:
  • cd (ChromData) – Holds the map (cd.link_cool) and receives the result; or the path of a .cool / .mcool (then nothing is stored).

  • features (DataFrame or str) – Pairs (chrom1, start1, end1, chrom2, start2, end2; e.g. loops from call_loops_hiccups(), call_loops_axiswise_f(), a published list) or points (chrom, start, end; e.g. domain boundaries), or a key of cd.intervals / cd.results. An anchor sits in the map bin holding its midpoint; pairs between chromosomes are left out.

  • contacts (str, optional) – Key of the linked map (None: the only one) or the path of a .cool / .mcool.

  • resolution (int, optional) – The level of an .mcool.

  • chrom (str or sequence of str, optional) – Only the features on these chromosomes.

  • flank (int, optional) – Half-width of the window, bp (default 10 bins, as Juicer APA).

  • expected (bool or DataFrame) – True: divide every pixel by the mean contact of its diagonal on its chromosome (uchrom.fea.band.expected_cis(), from the map itself); a DataFrame: that expected (chrom, diag, balanced_avg — or count_avg with balance=False); False: the (balanced) observed.

  • balance (bool) – Balanced values (cooler weight); False = raw counts (a map too sparse to balance).

  • min_separation (int, optional) – Pairs whose anchors are closer / farther (bins) are left out. Default minimum: the window stays off the ignored diagonals (2 * flank_bins + ignore_diags).

  • max_separation (int, optional) – Pairs whose anchors are closer / farther (bins) are left out. Default minimum: the window stays off the ignored diagonals (2 * flank_bins + ignore_diags).

  • corner (int, optional) – Side of the lower-left square of the APA score, bins (Juicer: 3 at 5 kb, else 6).

  • ignore_diags (int) – Diagonals left out (NaN): the first two, as for the expected.

  • aggregate ({"sum", "mean"}) – "sum" (default): per pixel, the summed observed over the summed expected of the features — the Poisson maximum-likelihood enrichment of the set; features weigh by their expected, so a few far-apart pairs (tiny expected, huge O/E) cannot dominate, and it is steadier in sparse maps. "mean": the mean of the features’ observed / expected windows (every feature weighs the same).

  • shifts (sequence of int, optional) – Controls: the same features moved along the chromosome by each shift (bp; e.g. (-1_000_000, -500_000, 500_000, 1_000_000)), piled up the same way. Their score (pairs: apa; points: score) is what the set gives without the features’ own enrichment — a pair keeps its separation, so the distance decay is the same.

  • key_added (str or None) – cd.results key (default "pileup"); None does not store.

  • copy (bool) – True → return a new ChromData holding the result.

Returns:

matrix (the mean window, (2f+1, 2f+1); rows = first anchor ± f bins, columns = second), n_pixels (features contributing to each pixel), n (features used), n_dropped, kind, resolution, flank_bins, the scores of pileup_scores() (pairs: apa, p2m, zscore_ll; points: score), and features: the feature table with used, center (their centre pixel), lower_left (mean of their lower-left square) for pairs. With shifts: control (the mean score of the shifted sets) and controls ({shift: score}).

Return type:

dict (copy=False) or ChromData (copy=True)

Examples

>>> loops = ds.fetch("rao2014_annotations")
>>> apa = pileup(hic, published_loops, contacts="bulk_10kb")
>>> apa["apa"]
uchrom.fea.pileup_scores(matrix: ndarray, *, kind: str = 'pair', corner: int = 6) → dict[source]

Scores of a pileup window ((2f+1) x (2f+1), rows = first anchor, columns = second).

kind="pair": apa (P2LL: centre / mean of the lower-left corner x corner square), p2m (centre / mean of the other pixels), zscore_ll (centre’s z-score in the lower-left square, sample s.d.). kind="point": score = mean of the on-diagonal quadrants / mean of the upstream x downstream quadrant (centre row and column left out). NaN pixels are left out.

uchrom.fea.project_interval_features_to_bins(cdata_or_bins, features: DataFrame, *, prefix: str | None = None, value_columns: Sequence[str] | None = None, into: DataFrame | None = None, overwrite: bool = False) → DataFrame[source]

Project interval-level features onto the bin axis.

Parameters:
  • cdata_or_bins – A ChromData (its bins are used) or a bin table with chrom, start, end.

  • features – DataFrame with one row per interval (matched to bins by exact chrom, start, end) and feature columns.

  • prefix – Optional namespace prefix, e.g. "seq" → seq.gc_fraction.

  • value_columns – Feature columns to project (default: all non-interval columns).

  • into – Existing bin-aligned table to extend (usually cd.bin_tracks).

  • overwrite – If False, raise when a projected column already exists in into.

Returns:

n_bins rows indexed by bin_id: the into columns plus the projected ones (NaN for bins without a feature row).

Return type:

DataFrame

uchrom.fea.project_interval_features_to_spots(cdata_or_spots, features: DataFrame, *, prefix: str | None = None, value_columns: Sequence[str] | None = None, into: DataFrame | None = None, overwrite: bool = False) → DataFrame[source]

Project interval-level features onto the spot axis.

Parameters:
  • cdata_or_spots – A ChromData-like object or a spot DataFrame with chrom, start, and end columns.

  • features – DataFrame with one row per interval and feature columns.

  • prefix – Optional namespace prefix for projected columns. For example, prefix="seq" maps gc_fraction to seq.gc_fraction.

  • value_columns – Feature columns to project. By default all non-interval columns are used.

  • into – Optional existing spot-aligned DataFrame to extend.

  • overwrite – If False, raise when projected columns already exist in into.

Returns:

  • DataFrame – A spot-aligned DataFrame containing the existing into columns plus projected feature columns.

  • .. deprecated:: format 2.0 – Per-locus features belong on the bin axis: use project_interval_features_to_bins() (cd.bin_tracks).

uchrom.fea.pseudobulk(cd, groupby: None | str | Series | Mapping = None, *, contacts: str = 'per_cell', groups: Sequence | None = None, cells: Sequence | None = None, min_cells: int = 1, resolution: int | None = None, trans: bool = True, balance: bool = True, out_dir: None | str | PathLike = None, key_prefix: str = 'pseudobulk', overwrite: bool = False, max_pixels: int = 2000000, workers: int = 4, copy: bool = False, verbose: bool = False)[source]

Sum the per-cell contact maps of each group of cells into one ICE-balanced map per group, linked to cd.

The pseudo-bulk map of a group is the sum over its cells of their contact maps (contacts of every cell counted once, as in the per-cell maps — a diploid cell’s map already sums its homologs), written as a .cool at the per-cell resolution or a coarser one and balanced by iterative correction (ICE; Imakaev et al. 2012, Nat Methods 9:999, with the cooler balance defaults of Abdennur & Mirny 2020, Bioinformatics 36:311: genome-wide, the first two diagonals ignored, bins with < 10 non-zero pixels and MAD-max outliers masked). Summing single-cell maps by cell type into pseudo-bulk maps follows e.g. Lee et al. 2019 (Nat Methods 16:999) and Tan et al. 2021 (Cell 184:741).

Parameters:
  • cd – ChromData with per-cell maps linked (cd.link_scool): a local .scool, or maps embedded in the store it was read from (an atlas store, also over HTTP).

  • groupby – A column of cd.cells, or a Series / mapping cell id -> group. None: all cells, one group "all". Cells without a group (NaN) are left out.

  • contacts – Key of the linked per-cell maps (cd.uns['linked_scool']), or the path of a .scool whose cell names are the cell ids.

  • groups – Make only these groups (in this order; default every group, category order for a categorical column).

  • cells – Use only these cells.

  • min_cells – Groups with fewer cells (that have per-cell maps) are skipped, with a warning.

  • resolution – Bin size of the pseudo-bulk maps (bp), a multiple of the per-cell maps’ (default: theirs); bin edges at k * resolution and the chromosome ends, as cooler coarsen.

  • trans – Keep the contacts between chromosomes (balanced genome-wide); False: cis only (balanced per chromosome, cis_only), which reads far less of an embedded map.

  • balance – ICE-balance the maps (weight column).

  • out_dir – Where the .cool files go (see the module docstring for the default). Files are named <key_prefix>.<group>.<resolution>.cool.

  • key_prefix – The maps are linked under "<key_prefix>.<group>"; the summary is stored as cd.results[key_prefix].

  • overwrite – Recompute maps that already exist with the same cells and parameters (default: reuse them).

  • max_pixels – Pixels per read (whole cells; memory of a read: ~24 bytes a pixel).

  • workers – Reads of embedded maps running at once (HTTP range reads overlap; memory: workers + 1 reads).

  • copy – True: link the maps to a copy of cd and return that.

  • verbose – Print progress.

Returns:

One row per group: group, n_cells, n_contacts, n_cis, n_pixels, key, path, balanced (whether ICE converged; None when not balanced), reused. Or the copy of cd (copy=True).

Return type:

DataFrame (copy=False)

Notes

Memory: an embedded map is read one chromosome partition at a time, workers + 1 reads of max_pixels in flight; the sums of a partition are held per group (a dense array up to DENSE_MAX entries, sparse beyond), so memory is the pseudo-bulk maps plus the reads in flight plus one partition’s sums (a .scool keeps every partition’s sums until its last cell; they share the dense budget). Time on an atlas store over HTTP is the transfer of the per-cell maps (trans=False reads the cis partitions only).

uchrom.fea.radial_position(cd, *, by: str = 'cell', centre: str = 'median', scale: float | None = 0.95, key_added: str | None = 'radial_position', copy: bool = False)[source]

Radial position of every spot: its distance from the centre of its cell’s spots, scaled per cell.

The centre is the per-axis centre (median by default) of the cell’s spots (spot_centroids()); the distance is divided by the scale quantile of the distances of that cell’s spots (the 95th percentile by default — a robust nuclear radius), so ~0 is the nucleus centre and ~1 its edge, comparable between cells of different size. scale=None keeps the distance in the unit of the coordinates.

Parameters:
  • cd (ChromData) – In memory (a backed object needs key_added=None: its spot tracks are read-only).

  • by ("cell" (default; needs cell_id) or "trace") – The group whose spots give the centre (and the scale): the nucleus, or one chromatin fibre.

  • centre ("median" (default) or "mean")

  • scale (float in (0, 1] or None) – Quantile of the group’s distances to divide by; None: no scaling.

  • key_added (str or None) – The cd.spot_tracks column to write (default "radial_position"), recorded in cd.uns["feature_registry"]; None: only return the values.

  • copy (bool) – True: write to a copy of cd and return it.

Returns:

One value per spot (index = the rows of cd.spots); NaN for spots with a NaN coordinate.

Return type:

Series (copy=False) or ChromData (copy=True)

uchrom.fea.radius_of_gyration(data, chrom=None, *, trace_ids: Iterable | None = None, cells: Iterable | None = None) → Series[source]

Per-trace radius of gyration.

Rg = sqrt(mean over spots of ||r - centroid||²) over every spot of the trace (a locus detected twice counts twice). Traces with fewer than 2 spots get NaN.

Parameters:
  • data (ChromData or DataFrame) – A ChromData — spots with a non-finite coordinate (undetected loci) are left out, and a trace without a detected spot is not listed — or the flat table chrom, start, end, x, y, z, trace_id (to_dataframe(); every row is used, so a NaN coordinate makes the trace’s Rg NaN: drop such rows first).

  • chrom (str, optional) – Only the traces of this chromosome (default: all).

  • trace_ids (optional) – Use only these traces / cells.

  • cells (optional) – Use only these traces / cells.

Returns:

rg per trace, indexed by trace_id (sorted), in the unit of the coordinates.

Return type:

Series

uchrom.fea.read_band(cd, contacts: str | None = None, *, chrom: str, resolution: int | None = None, max_dist: int | None = None, balance: bool = True, chunk: int = 2000000) → Band[source]

The pixels of chrom within max_dist bp of the diagonal (default: all) as a Band.

Reads the chromosome’s rows of the pixel table in chunks of chunk pixels, so memory stays at the band. balance=True keeps the weight column (an unbalanced map warns and gives weight=None).

uchrom.fea.read_bedgraph(path: str | Path, *, signal_col: str = 'score') → DataFrame[source]

Read a MACS-compatible bedGraph score track into an interval table.

uchrom.fea.read_gtf(path: str | Path, *, derive_genes: bool = True) → DataFrame[source]

Read a GTF/GFF-like file into a normalized annotation table.

Coordinates are converted from 1-based inclusive GTF convention to 0-based half-open intervals.

Parameters:
  • path (str or Path) – GTF / GFF file (gzipped when it ends in .gz).

  • derive_genes (bool) – When the file has transcript rows but no gene rows (UCSC refGene / ncbiRefSeq GTFs), add one gene row per gene locus — the span of the overlapping transcripts of a gene_id on one strand (gene_bodies(); a gene id found at several places gives several rows) — so that compute_annotation_features() finds gene bodies, TSSs and promoters.

Returns:

chrom, source, feature, start, end, score, strand, frame, attribute, gene_id, gene_name, gene_biotype; derived gene rows (source = "<source>:derived") come after the file’s rows.

Return type:

DataFrame

uchrom.fea.rebin_coords(cd, bins, *, by: str | None = 'trace', position: str = 'mid', closed: str | None = None, layer: str | None = None) → Tuple[ndarray, ndarray][source]

The coordinates of cd averaged onto other bins, one row per trace (or cell).

Every spot goes to the bin of bins that holds its position (the midpoint, start or end of its locus); the spots of one trace in one bin are averaged.

Parameters:
  • cd – Spots with coordinates (chromatin tracing, a structure, a population).

  • bins – Target bins (chrom, start, end; or a ChromData: its bins).

  • by – "trace", "cell" or None (all spots together).

  • position – "mid" (default), "start" or "end" of a spot’s locus.

  • closed – Target intervals "left" = [start, end), "right" = (start, end]; None: "left" unless bins is a reconstruction with NucDynamics particles.

  • layer – Use this layer instead of coords.

Returns:

  • cube (ndarray (n_groups, len(bins), 3)) – NaN where a group has no spot in a bin.

  • groups (ndarray) – The trace (cell) id of every row (order of first appearance).

uchrom.fea.rebin_map(cd, contacts: str | None = None, *, resolution: int, anchor: int = 0, chrom: None | str | Sequence[str] = None, balance: bool = True, out: None | str | PathLike = None, key_added: str | None = 'auto', copy: bool = False)[source]

A linked contact map summed into coarser bins, written as a .cool and linked to cd.

The bins of the new map have edges at anchor + k * resolution (anchor snapped down to the map’s own grid) and at the chromosome ends — anchor=0 coarsens the map as cooler coarsen does; another anchor puts the edges on the grid of other data, e.g. the first segment of a chromatin tracing experiment, so that every imaged segment falls into exactly one bin. The counts of the original bins are summed into the bin that holds their start; the new map is ICE-balanced (cooler balance defaults) unless balance=False.

Parameters:
  • cd – ChromData with the map linked, or a path (then nothing is linked and the path is returned).

  • contacts – Key of the linked map (None: the only one). An .mcool is read at its finest level.

  • resolution – Bin size of the new map (bp), a multiple of the map’s own.

  • anchor – A position that is a bin edge of the new map.

  • chrom – Chromosome(s) to keep (default: all of the map).

  • balance – ICE-balance the new map (weight column).

  • out – Where to write it (default: a scratch directory removed at exit).

  • key_added – Key under which the new map is linked (cd.link_cool; default "<contacts>_<resolution>", e.g. "bulk_100kb"; None: not linked).

  • copy – True: link it to a copy of cd and return that.

Return type:

The path of the new map (copy=False), or the copy of cd with the map linked.

uchrom.fea.rebin_scool(cd, contacts: str = 'per_cell', *, resolution: int, out: str | PathLike, key_added: str | None = 'auto')[source]

The linked per-cell maps (.scool) summed into coarser bins, written as a new .scool and linked.

Single-cell maps are kept at a fine resolution (5-10 kb) to be looked at; an embedding of the cells by their maps (uchrom.emb.embed_contacts()) wants them at about 1 Mb. The counts of each cell’s bins are summed into the bin of the new grid (edges at multiples of resolution and at the chromosome ends) that holds their start; raw counts, no balancing (as the per-cell maps).

Parameters:
  • cd – ChromData with the per-cell maps linked (cd.link_scool) or embedded.

  • contacts – Key of the linked maps.

  • resolution – Bin size of the new maps (bp), a multiple of the maps’ own.

  • out – Where to write the .scool (it is linked by this path; give one next to the store for a relative link).

  • key_added – Key of the new maps (default "<contacts>_<resolution>", e.g. "per_cell_1mb"; None: not linked).

Return type:

The path of the new .scool.

uchrom.fea.rwr_band(i, j, n: int, *, rp: float = 0.05, window: int = 0, step: int = 0, max_diag: int = 205, min_sep: int = 2, chain: bool = True, backend: str | None = None, n_threads: int = 0, holes: bool = False) → ndarray[source]

The RWR-imputed map of one cell’s chromosome, as a band (SnapHiC; Yu et al. 2021).

Parameters:
  • i (array of int) – The cell’s contacts (bins of the chromosome; duplicates and order do not matter: the graph is binary).

  • j (array of int) – The cell’s contacts (bins of the chromosome; duplicates and order do not matter: the graph is binary).

  • n (int) – Bins of the chromosome.

  • rp (float) – Restart probability.

  • window (int) – Sliding windows, in bins (window=0: the whole chromosome, one graph).

  • step (int) – Sliding windows, in bins (window=0: the whole chromosome, one graph).

  • max_diag (int) – Offsets 0 ..= max_diag are returned (window - step >= max_diag is required).

  • min_sep – Contacts closer than min_sep bins are left out; chain links neighbouring bins.

  • chain – Contacts closer than min_sep bins are left out; chain links neighbouring bins.

  • backend ({"auto", "native", "numpy"}, optional) – Default: the module’s BACKEND.

  • n_threads (int) – Threads of the native path (0: all).

  • holes (bool) – Leave at 0 the pixels SnapHiC v0.2’s sliding windows never set (sums i + j = (2k + 1) step and i + j <= step): only to compare with the authors’ code.

Returns:

out[i, d] = R(i, i + d), R = Q + Q^T; NaN beyond the chromosome.

Return type:

ndarray (n, max_diag + 1)

uchrom.fea.sample_cells_by_depth(cd, groupby: None | str | Sequence[str] | Series | Mapping = None, *, n_contacts: float | Sequence[float], replicates: int = 1, contacts: str | Series = 'n_contacts', cells: Sequence | None = None, seed: int = 0) → DataFrame[source]

Disjoint random sets of cells holding the same number of contacts, per group: the cells of pseudo-bulk maps compared at matched depth.

Each group’s cells are shuffled and taken in turn until their contacts reach n_contacts (the set holds at least that many, by less than one cell’s contacts more); the next set starts from the cells left, so no cell is in two sets. A group too small for a set gets fewer sets (a warning names it).

Parameters:
  • cd (ChromData or DataFrame) – Its cells table (or the table itself).

  • groupby – A column of cells, several columns (the group is their values joined by " | "), a Series / mapping cell → group, or None (all cells one group).

  • n_contacts – Contacts per set; a sequence draws one set per amount (a depth series) from each group.

  • replicates – Sets per group and amount.

  • contacts – The contacts per cell: a column of cells (default "n_contacts") or a Series — e.g. the cis contacts, cells["n_contacts"] * (1 - cells["frac_trans"]), for maps of cis contacts only.

  • cells – Only these cells (e.g. the cells not drawn by an earlier call).

  • seed – Seed of the shuffles.

Returns:

Index = the drawn cells; group, n_contacts (the set’s target), replicate (1, 2, …) and set ("<group> | <amount> | <replicate>", the parts that vary): pass sets["set"] as the groupby of pseudobulk().

Return type:

DataFrame

uchrom.fea.separation_profile(cd, *, source: str = 'auto', contacts: None | str | Sequence[str] = None, cells: Sequence | None = None, params: SeparationParams | None = None, batch: int | str = 256, workers: int = 4, max_pixels: int = 2000000, key_added=UNSET, copy: bool = False)[source]

Per-cell proximity at short and long genomic separations (and optionally the whole profile), from the per-cell contact maps or from the traced coordinates of a ChromData.

Parameters:
  • cd – A ChromData, in memory or backed: with per-cell maps linked (cd.link_scool; a local .scool or maps embedded in the store, also an atlas store over HTTP), or with spots (one trace per chromosome copy; cell_id groups them into cells, without it every trace is a unit).

  • source – "contacts", "coords" or "auto" (the one cd holds; both: an error).

  • contacts – Keys of the linked per-cell maps (default: all of them, e.g. the two sections of a spatial Hi-C store), or a .scool path whose cell names are the cell ids.

  • cells – Only these cells (default all; traces without cells: these trace ids).

  • params – SeparationParams.

  • batch – Coordinates: cells read at a time (iter_cells; "auto" from the memory budget).

  • workers – Contacts: reads of embedded maps in flight and pixels per read (uchrom.fea.pseudobulk()).

  • max_pixels – Contacts: reads of embedded maps in flight and pixels per read (uchrom.fea.pseudobulk()).

  • key_added – Prefix of the cd.cells columns written (default "separation"; None: nothing stored), e.g. separation.log2_short_long; the table is also cd.results[key_added], the profile (with edges) cd.cellm["<key_added>.profile"] (cells x separation bins; coordinates also "<key_added>.n_pairs"), with the bins in the result’s parameters.

  • copy – Store on a copy of cd and return it.

Returns:

Indexed by cell id (trace id for traces without cells), one row per cell used (NaN for a cell without maps or spots). Contacts: n_cis (cis contacts of the chromosomes used, also within a bin), n_apart (between different bins), n_short, n_long, log2_short_long. Coordinates: n_traces, n_spots (finite), d_short, d_long (median or mean distance), n_pairs_short, n_pairs_long, f_short / f_long (with threshold), log2_short_long. Without a stored key the profile is out.attrs["profile"].

Return type:

DataFrame

uchrom.fea.spot_centroids(cd, *, by: str = 'cell', stat: str = 'mean') → DataFrame[source]

The centre of the spots of every cell (or trace): the per-axis mean or median of their coordinates.

An estimate of the nucleus centre from the DNA spots alone — e.g. to check that a segmentation centroid shares the frame of coords, or to register it as an inferred cell position (cd.set_cell_positions(spot_centroids(cd), status="inferred", ...)).

Parameters:
  • cd (ChromData)

  • by ("cell" (default; needs cell_id) or "trace")

  • stat ("mean" (default) or "median") – Per axis; NaN coordinates are skipped.

Returns:

x, y, z indexed by cell_id (or trace_id) as strings, sorted.

Return type:

DataFrame

uchrom.fea.thin_map(cd, contacts: str | None = None, *, fraction: float | None = None, n_contacts: int | None = None, seed: int = 0, resolution: int | None = None, balance: bool = True, out: None | str | PathLike = None, key_added: str | None = 'auto', copy: bool = False)[source]

A linked contact map at a lower sequencing depth: every contact of the raw counts kept with probability fraction (binomial thinning), written as a .cool and linked to cd.

Cell-type pseudo-bulks often hold 1-20 % of the contacts of a bulk map; thinning the bulk map to their depth shows what a caller still finds there (e.g. loops are no longer called below ~5 %, while the pileup of known loops still scores them). Thinning keeps the bins and the counting statistics of a shallower experiment of the same library (Poisson counts stay Poisson).

Parameters:
  • cd – ChromData with the map linked, or a path (then nothing is linked and the path is returned).

  • contacts – Key of the linked map (None: the only one).

  • fraction – The share of the contacts to keep, or their expected number (one of the two).

  • n_contacts – The share of the contacts to keep, or their expected number (one of the two).

  • seed – Seed of the random draws (the same seed gives the same map).

  • resolution – The level of an .mcool (required when it has several).

  • balance – ICE-balance the thinned map (weight column; cooler balance defaults).

  • out – Where to write it (default: a scratch directory removed at exit).

  • key_added – Key under which the new map is linked (default "<contacts>_<percent>pct", e.g. "bulk_5pct"; None: not linked).

  • copy – True: link it to a copy of cd and return that.

Return type:

The path of the new map (copy=False), or the copy of cd with the map linked.

uchrom.fea.trace_distance_matrix(cd, trace_id, chrom: str | None = None, *, duplicates: str = 'last') → Tuple[ndarray, DataFrame][source]

The pairwise 3-D distances of one trace over every locus of its chromosome.

Unlike cd.compute_distances(trace_id=...) (the trace’s own spots), the rows are the loci of the chromosome in cd.bins, so matrices of different traces — and the population map of distance_map() with observed=False — share one axis.

Parameters:
  • cd (ChromData)

  • trace_id – The trace ("12" finds an integer id 12 and the reverse).

  • chrom (str, optional) – Its chromosome, needed only when the trace spans several.

  • duplicates ("last" (default), "first", "mean" or "median") – The spot kept at a locus the trace observed more than once (as for distance_map()).

Returns:

  • matrix (ndarray (n_loci, n_loci)) – NaN for loci the trace did not detect.

  • loci (DataFrame) – bin_id, chrom, start, end of the rows (the chromosome’s loci sorted by start).

uchrom.fea.unique_spot_intervals(cdata_or_spots) → DataFrame[source]

Return the unique chrom/start/end intervals of the data.

For a ChromData these are its bins (in bin_id order). For a spot DataFrame the first-occurrence order is preserved.

uchrom.fea.window_expected(counts, stats, *, chromsizes: Mapping, samples: int = 16) → ndarray[source]

The contacts each cell is expected to have in each window, from its own contact-distance histogram of the window’s chromosome.

Parameters:
  • counts – WindowCounts (its windows, resolution and cells).

  • stats – ContactStats of the same contacts (distance per chromosome; cells matched by id).

  • chromsizes – Chromosome lengths (bp).

  • samples – Distances per histogram bin in the integration.

Returns:

  • ndarray (n_cells of ``counts``, n_windows), float (per window, sum over distance bins of the cell’s contacts)

  • on that chromosome in the bin times the fraction of such contacts the window holds (contacts placed uniformly

  • along the chromosome). NaN for cells without statistics, 0 for windows on chromosomes the statistics lack.

uchrom.fea.window_scores(counts, *, expected: ndarray | None = None, pseudo: float = 0.5, per_structure: bool = True) → dict[source]

Scores of each cell from WindowCounts with windows of kinds boundary, interior (optional) and loop; expected (window_expected(), cells x windows) adds the scores against each cell’s own expected.

Returns:

"cells": DataFrame indexed by cell — boundary_strength (with interiors), boundary_ratio (log2 within / cross at the boundaries, without the interior correction), interior_ratio, loop_strength, the summed counts n_boundary, n_interior, n_loop_peak, n_loop_donut; with per_structure: "insulation" (cells x boundaries, log2 cross / within minus the cell’s interior ratio) and "loops" (cells x loops, log2 peak / donut per pixel), plus "boundary_counts" and "loop_counts" (dicts of raw count matrices by part). With expected: the columns boundary_strength_oe, interior_oe, loop_strength_oe and, with per_structure, "insulation_oe" / "loops_oe" (cells x structures, observed minus expected shares).

Return type:

dict

uchrom.fea.zscore_band(band: ndarray, *, edge: int = 5, trim: float = 0.01, min_sd: float = 1e-06, backend: str | None = None, n_threads: int = 0) → ndarray[source]

SnapHiC’s normalisation of an RWR band: z-scores per diagonal (Yu et al. 2021).

On every diagonal d >= 1 the pixels of the rows edge <= i, i + d <= n - 1 - edge are converted to (x - mean) / sd, the mean and the (population) standard deviation taken without the largest round(trim * len) - 1 values; a diagonal with sd < min_sd is 0. Pixels of those diagonals outside the trimmed rows are 0 (SnapHiC drops them: zeros in its matrices); the main diagonal and pixels beyond the chromosome are NaN.

Returns a new array of the band’s shape.

Distance-based aggregates

Distance-based statistics of chromatin traces: population distance maps, contact frequency, radius of gyration and the distance matrix of one trace.

Every function takes a ChromData (in memory or backed) and the chromosome to use (chrom=; may be left out when the data have one chromosome), optionally restricted to some traces / cells (trace_ids=, cells=):

dm = distance_map(cd, "chr2")                        # exact median map, streams a backed store
freq, bins, n = contact_frequency(cd, 0.18, chrom="chr2")
rg = radius_of_gyration(cd, chrom="chr2")            # one value per trace
d, loci = trace_distance_matrix(cd, "2_45_2_1")     # one trace on every locus of its chromosome

mean_distance_matrix(), contact_frequency() and radius_of_gyration() also take the flat table chrom, start, end, x, y, z, trace_id that ChromData.to_dataframe() produces (the 1.x form, kept). The dense helper _bin_coord_cube() pivots such a table into a (n_traces, n_bins, 3) array with NaN for missing spots, which makes every statistic a NaN-aware reduction; distance_map() and the ChromData form of contact_frequency() never build it.

class uchrom.fea.distance.DistanceMap[source]

Bases: dict

Result of distance_map() (a dict with attribute access): matrix (n_bins × n_bins), count (traces observing each pair; the diagonal counts the traces observing the bin), bins (bin_id, chrom, start, end of the rows), n_traces, stat, streaming, n_passes (reads of the chromosome’s traces), n_bands and duplicates. coarsen() pools it into blocks.

coarsen(k: int, stat: str = 'median', *, diagonal: bool = False) → DistanceMap[source]

The map pooled into blocks of k × k rows (e.g. 20 × 25-kb bins = 500 kb), for display or to gather the sparse pairs of a large locus panel.

Parameters:
  • k (int) – Rows per block; the last block holds the rest (n_bins % k rows) when k does not divide the number of rows. The rows are the map’s own (observed) bins, in order — gaps between bins are not filled in.

  • stat ("median" (default) or "mean") – How the finite values of a block are combined (NaN when it has none).

  • diagonal (bool) – Include the self-distances (0) of the original diagonal; by default they are left out, so the blocks on the diagonal hold the distances between the different bins of the block.

Returns:

matrix and count (pair observations pooled into each block: the sum of the original count over the block’s entries, both triangles) of the blocks, bins (chrom, start of the first bin, end of the last, n_bins), block_size = k, and the other fields of this map.

Return type:

DistanceMap

uchrom.fea.distance.contact_frequency(data, threshold: float, chrom=None, *, trace_ids: Iterable | None = None, cells: Iterable | None = None, duplicates: str = 'last', streaming=None, batch='auto', memory_budget=None)[source]

Fraction of traces where a pair of bins are within threshold.

NaN distances (missing spots) are excluded from both numerator and denominator — each bin pair’s frequency is over the set of traces that have both endpoints detected.

Parameters:
  • data (ChromData or DataFrame) – A ChromData (in memory or backed: the traces are streamed as by distance_map(), so no (n_traces, n_bins, n_bins) tensor is built), or the flat table chrom, start, end, x, y, z, trace_id (to_dataframe(); the dense computation). Both give the same matrix.

  • threshold (float) – Distance threshold in the unit of the coordinates.

  • chrom (str, optional) – The chromosome; with a ChromData it may be left out when the data have one.

  • trace_ids (optional) – Use only these traces / cells.

  • cells (optional) – Use only these traces / cells.

  • duplicates ("last" (default), "first", "mean" or "median") – With a ChromData: the spot a trace keeps at a bin it observed twice (see distance_map()). The table form keeps the last.

  • streaming – With a ChromData: as for distance_map().

  • batch – With a ChromData: as for distance_map().

  • memory_budget – With a ChromData: as for distance_map().

Returns:

  • frequency (ndarray (n_bins, n_bins) in [0, 1], NaN where no) – trace had both endpoints detected; rows = the observed bins sorted by start.

  • bin_ids (list of (start, end))

  • n_traces (int)

uchrom.fea.distance.distance_map(cd, chrom=None, stat: str = 'median', *, trace_ids: Iterable | None = None, cells: Iterable | None = None, duplicates: str = 'last', streaming=None, batch='auto', memory_budget=None, observed: bool = True) → DistanceMap[source]

Population median / mean 3-D distance of every bin pair of one chromosome — exact, in memory or streaming over the traces.

Same definition as mean_distance_matrix() (per trace, the Euclidean distance of its two spots; NaN / missing spots skipped; a trace observing a bin twice keeps its last spot, unless duplicates says otherwise), but without the dense (n_traces, n_bins, n_bins) tensor, so it runs on genome-wide data:

  • stat="mean" accumulates per-pair sums and counts in trace order (np.add.at) — the additions the dense np.nanmean makes, in the same order, so the result is bitwise identical (float64); memory O(n_bins²).

  • stat="median" is an exact median (the mean of the two middle values for an even count, as np.nanmedian). An exact median needs all values of a pair at once, so the observations are gathered for one row band of the matrix at a time — the rows i whose pairs (i, j > i) fit memory_budget (BYTES_PER_OBS bytes each) — and reduced with a grouped median (pandas). A band costs one pass over the chromosome’s traces; memory is the band plus the n_bins² output, independent of the number of traces. No approximation.

Parameters:
  • cd (ChromData, in memory or backed)

  • chrom (str, optional) – The chromosome; may be left out when the data have one.

  • stat ("median" or "mean")

  • trace_ids (optional) – Use only these traces / cells (read in memory first).

  • cells (optional) – Use only these traces / cells (read in memory first).

  • duplicates ("last" (default), "first", "mean" or "median") – The spot a trace keeps at a bin it observed more than once (sister chromatids, a stray spot): its last or first one, or the per-axis mean / median of them (NaN values skipped) — exactly the coordinates uchrom.im.merge_duplicate_spots() (how=) gives, so distance_map(cd, c, duplicates="mean") equals distance_map(merge_duplicate_spots(cd), c).

  • streaming (bool, optional) – Read the traces in batches (iter_traces(chrom=..., columns="coords")) and band the median; default True for a backed object. False gathers every observation at once (the in-memory baseline).

  • batch (int or "auto") – Traces per batch, or "auto" (from the memory budget).

  • memory_budget (default uchrom.settings.memory_budget)

  • observed (rows / columns = the chromosome's observed bins sorted by) – start (the mean_distance_matrix() convention), or every bin of the chromosome in cd.bins

Return type:

DistanceMap

uchrom.fea.distance.mean_distance_matrix(data, chrom=None, reduce: str = 'median', *, trace_ids: Iterable | None = None, cells: Iterable | None = None)[source]

Population median / mean pairwise distance matrix — the dense reference of distance_map().

For each pair of genomic bins (i, j), the distance is computed per trace and then reduced across traces with np.nanmedian (the Bintu 2018 convention) or np.nanmean. The whole (n_traces, n_bins, n_bins) tensor is built, so this is for a locus of a few hundred bins; distance_map() gives the same matrix without it.

Parameters:
  • data (ChromData or DataFrame) – A ChromData, or the flat table chrom, start, end, x, y, z, trace_id (to_dataframe()).

  • chrom (str, optional) – The chromosome; with a ChromData it may be left out when the data have one. A table without chrom is used whole.

  • reduce ("median" (default) or "mean")

  • trace_ids (optional) – Use only these traces / cells.

  • cells (optional) – Use only these traces / cells.

Returns:

  • matrix (ndarray (n_bins, n_bins)) – Rows / columns = the observed bins sorted by start; a trace observing a bin twice keeps its last spot (merge them first with uchrom.im.merge_duplicate_spots()).

  • bin_ids (list of (start, end))

  • n_traces (int)

uchrom.fea.distance.radius_of_gyration(data, chrom=None, *, trace_ids: Iterable | None = None, cells: Iterable | None = None) → Series[source]

Per-trace radius of gyration.

Rg = sqrt(mean over spots of ||r - centroid||²) over every spot of the trace (a locus detected twice counts twice). Traces with fewer than 2 spots get NaN.

Parameters:
  • data (ChromData or DataFrame) – A ChromData — spots with a non-finite coordinate (undetected loci) are left out, and a trace without a detected spot is not listed — or the flat table chrom, start, end, x, y, z, trace_id (to_dataframe(); every row is used, so a NaN coordinate makes the trace’s Rg NaN: drop such rows first).

  • chrom (str, optional) – Only the traces of this chromosome (default: all).

  • trace_ids (optional) – Use only these traces / cells.

  • cells (optional) – Use only these traces / cells.

Returns:

rg per trace, indexed by trace_id (sorted), in the unit of the coordinates.

Return type:

Series

uchrom.fea.distance.trace_distance_matrix(cd, trace_id, chrom: str | None = None, *, duplicates: str = 'last') → Tuple[ndarray, DataFrame][source]

The pairwise 3-D distances of one trace over every locus of its chromosome.

Unlike cd.compute_distances(trace_id=...) (the trace’s own spots), the rows are the loci of the chromosome in cd.bins, so matrices of different traces — and the population map of distance_map() with observed=False — share one axis.

Parameters:
  • cd (ChromData)

  • trace_id – The trace ("12" finds an integer id 12 and the reverse).

  • chrom (str, optional) – Its chromosome, needed only when the trace spans several.

  • duplicates ("last" (default), "first", "mean" or "median") – The spot kept at a locus the trace observed more than once (as for distance_map()).

Returns:

  • matrix (ndarray (n_loci, n_loci)) – NaN for loci the trace did not detect.

  • loci (DataFrame) – bin_id, chrom, start, end of the rows (the chromosome’s loci sorted by start).

Contact maps

Maps linked to a ChromData as matrices, rebinned, observed / expected.

Contact maps linked to a ChromData: read one as a matrix, rebin it onto other bins, observed / expected.

A bulk (or pseudo-bulk) Hi-C map stays in its .cool / .mcool file and is linked to the ChromData (cd.link_cool(path, key=...); uchrom.datasets.load does this for the Hi-C datasets). The functions here take the ChromData and the key of the map (contacts=; None = the only linked map, or the path of a .cool / .mcool), or a path:

hic = ds.load("rao2014_imr90_chr21")                  # the 5 kb map, linked as "bulk"
rebin_map(hic, "bulk", resolution=100_000)             # -> linked as "bulk_100kb" (ICE-balanced)
thin_map(hic, "bulk", fraction=0.05)                   # -> "bulk_5pct": the map at 5 % of its depth
bins, M = contact_matrix(hic, "bulk_100kb", chrom="chr21")
oe = observed_over_expected(M)
uchrom.fea.maps.contact_matrix(cd, contacts: str | None = None, *, chrom: str, resolution: int | None = None, balance: bool = True) → Tuple[DataFrame, ndarray][source]

The contact matrix of one chromosome from a linked map.

Parameters:
  • cd – A ChromData with the map linked (cd.link_cool), the path of a .cool / .mcool, or a cooler.Cooler (open_map(); resolution is then ignored).

  • contacts – Key of the linked map (None: the only one) or the path of a map.

  • chrom – Chromosome (as named in the map).

  • resolution – The level of an .mcool (required when it has several); checked against a .cool.

  • balance – Balanced values (the cooler weight column; raw counts with a warning when the map has none).

Returns:

  • bins (DataFrame) – chrom, start, end of the rows (index 0..n-1).

  • matrix (ndarray (n, n)) – float64; masked (NaN) entries of a balanced map are 0.

uchrom.fea.maps.map_path(cd, contacts: str | None = None, *, resolution: int | None = None) → str[source]

Path of a contact map: the file linked to cd under contacts (None: the only linked map; an embedded copy is exported once — only the level resolution when given —, see chromdata.ChromData.linked_cool_path()), or contacts itself when it is not a linked key but the path of a .cool / .mcool — or cd itself when it is such a path.

uchrom.fea.maps.observed_over_expected(matrix, *, positions=None) → ndarray[source]

Every entry of a contact (or distance) matrix divided by the mean at its genomic separation.

The expected value of a separation is the mean of its positive, finite entries; entries that are not positive (or NaN) and the diagonal are NaN in the result.

Parameters:
  • matrix – Square, symmetric (n, n).

  • positions – Genomic position of every row (e.g. bin starts). Default: the rows are equally spaced, so the separation is the diagonal; with gaps (bins left out), entries are grouped by their separation |positions[i] - positions[j]| instead.

Return type:

ndarray (n, n), symmetric.

uchrom.fea.maps.open_map(cd, contacts: str | None = None, *, resolution: int | None = None)[source]

A contact map as a cooler.Cooler.

Parameters:
  • cd – A ChromData with the map linked (cd.link_cool), or the path of a .cool / .mcool.

  • contacts – Key of the linked map (None: the only one) or the path of a map.

  • resolution – The level of an .mcool (required when it has several); checked against a .cool.

Return type:

cooler.Cooler

uchrom.fea.maps.rebin_map(cd, contacts: str | None = None, *, resolution: int, anchor: int = 0, chrom: None | str | Sequence[str] = None, balance: bool = True, out: None | str | PathLike = None, key_added: str | None = 'auto', copy: bool = False)[source]

A linked contact map summed into coarser bins, written as a .cool and linked to cd.

The bins of the new map have edges at anchor + k * resolution (anchor snapped down to the map’s own grid) and at the chromosome ends — anchor=0 coarsens the map as cooler coarsen does; another anchor puts the edges on the grid of other data, e.g. the first segment of a chromatin tracing experiment, so that every imaged segment falls into exactly one bin. The counts of the original bins are summed into the bin that holds their start; the new map is ICE-balanced (cooler balance defaults) unless balance=False.

Parameters:
  • cd – ChromData with the map linked, or a path (then nothing is linked and the path is returned).

  • contacts – Key of the linked map (None: the only one). An .mcool is read at its finest level.

  • resolution – Bin size of the new map (bp), a multiple of the map’s own.

  • anchor – A position that is a bin edge of the new map.

  • chrom – Chromosome(s) to keep (default: all of the map).

  • balance – ICE-balance the new map (weight column).

  • out – Where to write it (default: a scratch directory removed at exit).

  • key_added – Key under which the new map is linked (cd.link_cool; default "<contacts>_<resolution>", e.g. "bulk_100kb"; None: not linked).

  • copy – True: link it to a copy of cd and return that.

Return type:

The path of the new map (copy=False), or the copy of cd with the map linked.

uchrom.fea.maps.thin_map(cd, contacts: str | None = None, *, fraction: float | None = None, n_contacts: int | None = None, seed: int = 0, resolution: int | None = None, balance: bool = True, out: None | str | PathLike = None, key_added: str | None = 'auto', copy: bool = False)[source]

A linked contact map at a lower sequencing depth: every contact of the raw counts kept with probability fraction (binomial thinning), written as a .cool and linked to cd.

Cell-type pseudo-bulks often hold 1-20 % of the contacts of a bulk map; thinning the bulk map to their depth shows what a caller still finds there (e.g. loops are no longer called below ~5 %, while the pileup of known loops still scores them). Thinning keeps the bins and the counting statistics of a shallower experiment of the same library (Poisson counts stay Poisson).

Parameters:
  • cd – ChromData with the map linked, or a path (then nothing is linked and the path is returned).

  • contacts – Key of the linked map (None: the only one).

  • fraction – The share of the contacts to keep, or their expected number (one of the two).

  • n_contacts – The share of the contacts to keep, or their expected number (one of the two).

  • seed – Seed of the random draws (the same seed gives the same map).

  • resolution – The level of an .mcool (required when it has several).

  • balance – ICE-balance the thinned map (weight column; cooler balance defaults).

  • out – Where to write it (default: a scratch directory removed at exit).

  • key_added – Key under which the new map is linked (default "<contacts>_<percent>pct", e.g. "bulk_5pct"; None: not linked).

  • copy – True: link it to a copy of cd and return that.

Return type:

The path of the new map (copy=False), or the copy of cd with the map linked.

Banded reads of large maps

One chromosome’s pixels near the diagonal as a sparse band, and the expected contact per separation: what the Hi-C structure callers share.

Banded access to large contact maps: what the Hi-C structure callers share.

A 5 kb map of a large chromosome is too big for a dense matrix (chr1: 50,000 bins), but the callers only look near the diagonal — insulation within a window, loops within a few Mb, the expected contact frequency per separation. read_band() reads one chromosome’s pixels up to max_dist from the diagonal, in chunks of the cooler’s pixel table, and keeps them as a sparse Band (raw counts, balancing weights). expected_cis() is the mean balanced contact per diagonal over the valid (unmasked) pairs — the “expected” of observed / expected.

cd is a ChromData with the map linked (contacts= its key), the path of a .cool / .mcool, or an open cooler.Cooler, as for uchrom.fea.contact_matrix().

class uchrom.fea.band.Band(chrom: str, binsize: int, starts: ndarray, i: ndarray, j: ndarray, count: ndarray, weight: ndarray | None, max_diag: int)[source]

Bases: object

One chromosome’s pixels within max_diag bins of the diagonal (upper triangle, i <= j).

binsize: int
chrom: str
count: ndarray
dense(lo: int = 0, hi: int | None = None, *, balance: bool = True) → ndarray[source]

The symmetric dense matrix of bins [lo, hi) (pixels beyond the band are 0; masked bins NaN).

property diag: ndarray
i: ndarray
j: ndarray
max_diag: int
property n: int
starts: ndarray
property valid: ndarray

Bins with a finite weight (all bins of an unbalanced map).

values(balance: bool = True) → ndarray[source]

Balanced (weight[i] * weight[j] * count; NaN on masked bins) or raw values of the pixels.

weight: ndarray | None
uchrom.fea.band.band_observed_over_expected(band: Band, expected: DataFrame | None = None) → ndarray[source]

Observed / expected (balanced) of every pixel of band: the expected per diagonal of its chromosome (expected_cis(); computed from the band when not given). NaN where the expected is 0 or a bin is masked.

uchrom.fea.band.expected_cis(cd, contacts: str | None = None, *, chroms: Sequence[str] | None = None, resolution: int | None = None, max_dist: int | None = None, balance: bool = True, bands: Iterable[Band] | None = None) → DataFrame[source]

Mean contact per separation, per chromosome: chrom, diag, dist, n_valid, count_sum, balanced_sum, balanced_avg (balanced_avg = balanced_sum / n_valid over the pairs of unmasked bins).

Give bands (read_band() results) to reuse pixels already read; otherwise every chromosome of the map (or chroms) is read up to max_dist.

uchrom.fea.band.read_band(cd, contacts: str | None = None, *, chrom: str, resolution: int | None = None, max_dist: int | None = None, balance: bool = True, chunk: int = 2000000) → Band[source]

The pixels of chrom within max_dist bp of the diagonal (default: all) as a Band.

Reads the chromosome’s rows of the pixel table in chunks of chunk pixels, so memory stays at the band. balance=True keeps the weight column (an unbalanced map warns and gives weight=None).

Pseudo-bulk maps

Per-cell maps summed per group of cells into ICE-balanced maps linked to the cells.

Pseudo-bulk contact maps: the per-cell maps of each group of cells summed into one map per group.

Single-cell Hi-C maps are too sparse for structure calling; summed over the cells of a cell type (or a cluster, a condition, all cells) they become bulk-like maps that the callers of uchrom.strc read. pseudobulk() sums the per-cell maps linked to a ChromData (cd.link_scool) per group of cells, writes one ICE-balanced .cool per group and links it to cd (cd.link_cool) under "<key_prefix>.<group>":

cd = ds.load("dschic_aging_cortex")                         # 32,777 cells, 1 Mb maps embedded (HTTP)
summary = pseudobulk(cd, "cell_type")                       # one map per cell type
cd.uns["linked_cool"]["pseudobulk.Astrocytes"]              # {"path": ..., "n_cells": 4578, ...}
call_compartments_hic(cd, contacts="pseudobulk.Astrocytes", ...)

The per-cell maps are read where they are:

  • a linked local .scool: every cell’s pixels are read once (cooler’s single-cell format);

  • maps embedded in a store (an atlas store over HTTP, chromdata.embedded): each chromosome partition is read once for all the selected cells, in blocks of whole cells, and added by group as it streams — no per-cell file is exported.

One .cool per group (not one multi-resolution file): each group’s map is a separate linked map that the callers take by key, can be replaced or embedded on its own, and uchrom.fea.rebin_map() makes coarser levels of it on demand; resolution= sums into coarser bins in the same pass.

Where the files go (out_dir= overrides): next to a local store (<store dir>/<store name>_pseudobulk/, linked by a path relative to the store’s folder, so the folder moves as a whole); for a store read over HTTP the data directory (<data dir>/pseudobulk/<store name>/, uchrom.datasets.data_dir(): kept across sessions); for a ChromData not read from a store a scratch directory removed at exit. A map already there with the same cells, source and parameters (recorded in the file) is reused unless overwrite=True.

Depth matters when pseudo-bulks are compared (e.g. the compartment strength rises in shallow maps): sample_cells_by_depth() draws disjoint random sets of cells with the same number of contacts per group, the groups of a matched-depth comparison:

sets = sample_cells_by_depth(cd, ["cell_type", "age"], n_contacts=5e6, replicates=3)
pseudobulk(cd, sets["set"])                                 # one map per set: "Astrocytes | 3mo | 1", ...
uchrom.fea.pseudobulk_maps.ice(b1: ndarray, b2: ndarray, count: ndarray, chrom_offsets: ndarray, *, cis_only: bool = False, ignore_diags: int = 2, min_nnz: int = 10, mad_max: float = 5, tol: float = 1e-05, max_iters: int = 200) → Tuple[ndarray, dict][source]

Iterative correction (ICE; Imakaev et al. 2012, Nat Methods 9:999) of an in-memory map, the algorithm and filters of cooler.balance_cooler (Abdennur & Mirny 2020; as of cooler 0.12) without re-reading the file each iteration.

Pixels of one chromosome with |bin1 - bin2| < ignore_diags (and, cis_only, the trans pixels) are left out — neighbouring bins across a chromosome boundary are trans; bins with fewer than min_nnz non-zero pixels, and bins whose marginal (normalised by its chromosome’s median) lies mad_max median absolute deviations below the median in log space, are masked; then the bias is divided by the normalised marginal of the bias-corrected map until the marginals’ variance is under tol, and rescaled so that the balanced marginals are 1; bins left with no data are masked. The main diagonal counts once in the marginals. cis_only: each chromosome on its own.

Parameters:
  • b1 – Upper-triangle pixels (genome-wide bin ids).

  • b2 – Upper-triangle pixels (genome-wide bin ids).

  • count – Upper-triangle pixels (genome-wide bin ids).

  • chrom_offsets – First bin of every chromosome plus the number of bins (cooler’s indexes/chrom_offset).

Returns:

  • bias (ndarray (n_bins,)) – Balanced = count * bias[i] * bias[j]; NaN on masked bins.

  • stats (dict) – As cooler.balance_cooler: tol, min_nnz, min_count, mad_max, cis_only, trans_only, ignore_diags, scale, converged, var, divisive_weights (per chromosome when cis_only).

uchrom.fea.pseudobulk_maps.pseudobulk(cd, groupby: None | str | Series | Mapping = None, *, contacts: str = 'per_cell', groups: Sequence | None = None, cells: Sequence | None = None, min_cells: int = 1, resolution: int | None = None, trans: bool = True, balance: bool = True, out_dir: None | str | PathLike = None, key_prefix: str = 'pseudobulk', overwrite: bool = False, max_pixels: int = 2000000, workers: int = 4, copy: bool = False, verbose: bool = False)[source]

Sum the per-cell contact maps of each group of cells into one ICE-balanced map per group, linked to cd.

The pseudo-bulk map of a group is the sum over its cells of their contact maps (contacts of every cell counted once, as in the per-cell maps — a diploid cell’s map already sums its homologs), written as a .cool at the per-cell resolution or a coarser one and balanced by iterative correction (ICE; Imakaev et al. 2012, Nat Methods 9:999, with the cooler balance defaults of Abdennur & Mirny 2020, Bioinformatics 36:311: genome-wide, the first two diagonals ignored, bins with < 10 non-zero pixels and MAD-max outliers masked). Summing single-cell maps by cell type into pseudo-bulk maps follows e.g. Lee et al. 2019 (Nat Methods 16:999) and Tan et al. 2021 (Cell 184:741).

Parameters:
  • cd – ChromData with per-cell maps linked (cd.link_scool): a local .scool, or maps embedded in the store it was read from (an atlas store, also over HTTP).

  • groupby – A column of cd.cells, or a Series / mapping cell id -> group. None: all cells, one group "all". Cells without a group (NaN) are left out.

  • contacts – Key of the linked per-cell maps (cd.uns['linked_scool']), or the path of a .scool whose cell names are the cell ids.

  • groups – Make only these groups (in this order; default every group, category order for a categorical column).

  • cells – Use only these cells.

  • min_cells – Groups with fewer cells (that have per-cell maps) are skipped, with a warning.

  • resolution – Bin size of the pseudo-bulk maps (bp), a multiple of the per-cell maps’ (default: theirs); bin edges at k * resolution and the chromosome ends, as cooler coarsen.

  • trans – Keep the contacts between chromosomes (balanced genome-wide); False: cis only (balanced per chromosome, cis_only), which reads far less of an embedded map.

  • balance – ICE-balance the maps (weight column).

  • out_dir – Where the .cool files go (see the module docstring for the default). Files are named <key_prefix>.<group>.<resolution>.cool.

  • key_prefix – The maps are linked under "<key_prefix>.<group>"; the summary is stored as cd.results[key_prefix].

  • overwrite – Recompute maps that already exist with the same cells and parameters (default: reuse them).

  • max_pixels – Pixels per read (whole cells; memory of a read: ~24 bytes a pixel).

  • workers – Reads of embedded maps running at once (HTTP range reads overlap; memory: workers + 1 reads).

  • copy – True: link the maps to a copy of cd and return that.

  • verbose – Print progress.

Returns:

One row per group: group, n_cells, n_contacts, n_cis, n_pixels, key, path, balanced (whether ICE converged; None when not balanced), reused. Or the copy of cd (copy=True).

Return type:

DataFrame (copy=False)

Notes

Memory: an embedded map is read one chromosome partition at a time, workers + 1 reads of max_pixels in flight; the sums of a partition are held per group (a dense array up to DENSE_MAX entries, sparse beyond), so memory is the pseudo-bulk maps plus the reads in flight plus one partition’s sums (a .scool keeps every partition’s sums until its last cell; they share the dense budget). Time on an atlas store over HTTP is the transfer of the per-cell maps (trans=False reads the cis partitions only).

uchrom.fea.pseudobulk_maps.sample_cells_by_depth(cd, groupby: None | str | Sequence[str] | Series | Mapping = None, *, n_contacts: float | Sequence[float], replicates: int = 1, contacts: str | Series = 'n_contacts', cells: Sequence | None = None, seed: int = 0) → DataFrame[source]

Disjoint random sets of cells holding the same number of contacts, per group: the cells of pseudo-bulk maps compared at matched depth.

Each group’s cells are shuffled and taken in turn until their contacts reach n_contacts (the set holds at least that many, by less than one cell’s contacts more); the next set starts from the cells left, so no cell is in two sets. A group too small for a set gets fewer sets (a warning names it).

Parameters:
  • cd (ChromData or DataFrame) – Its cells table (or the table itself).

  • groupby – A column of cells, several columns (the group is their values joined by " | "), a Series / mapping cell → group, or None (all cells one group).

  • n_contacts – Contacts per set; a sequence draws one set per amount (a depth series) from each group.

  • replicates – Sets per group and amount.

  • contacts – The contacts per cell: a column of cells (default "n_contacts") or a Series — e.g. the cis contacts, cells["n_contacts"] * (1 - cells["frac_trans"]), for maps of cis contacts only.

  • cells – Only these cells (e.g. the cells not drawn by an earlier call).

  • seed – Seed of the shuffles.

Returns:

Index = the drawn cells; group, n_contacts (the set’s target), replicate (1, 2, …) and set ("<group> | <amount> | <replicate>", the parts that vary): pass sets["set"] as the groupby of pseudobulk().

Return type:

DataFrame

Imputing single-cell maps

Random walk with restart on each cell’s contact graph (scHiCluster, SnapHiC), whole chromosomes or sliding windows, and SnapHiC’s per-diagonal z-scores; native kernels in uchrom-maps.

Imputation of single-cell contact maps: convolution and random walk with restart (RWR).

A single cell’s contact map is too sparse to be read pixel by pixel. scHiCluster (Zhou et al. 2019, PNAS 116:14011) and SnapHiC (Yu et al. 2021, Nat Methods 18:1056) impute it by a random walk with restart on the cell’s chromosome graph — a node per bin, an edge between neighbouring bins and between the two bins of every contact — whose stationary distribution spreads each contact to the bins around it:

Q = rp (I - (1 - rp) P)^-1,    P = D^-1 A    (A adjacency, D degrees; rp: restart probability)

SnapHiC symmetrises R = Q + Q^T and normalises every diagonal (genomic distance) to z-scores. With M = D - (1 - rp) A (symmetric positive definite) R_ij = rp (M^-1)_ij (d_i + d_j), which is how both implementations here compute it:

  • numpy (the reference): per window a dense M and its inverse (scipy.linalg.cho_solve, LAPACK);

  • native (uchrom_maps.rwr_band, Rust, when packages/uchrom-maps is installed): a Cholesky factorisation of M in profile storage and the selected inversion of Takahashi et al. (1973) — only the entries of M^-1 inside the profile, which holds the band — windows in parallel. Equal to the reference up to rounding: on real cells (Nagano 2017 mES, chr1 / chr19, 10 kb) the bands differ by at most 9e-15 relatively and the z-scores by 9e-14 (uchrom-reproducibility supp_table3/sc_structures/impute_speed.py); 7x faster on one thread, ~60x on 16 (chr1; AMD EPYC 9754).

BACKEND ("auto", "native", "numpy") forces either path.

Sliding windows (SnapHiC2: Li et al. 2022, Comput Struct Biotechnol J 20:2778): the RWR of a whole chromosome needs its dense inverse (n^3; 20,000 bins at 10 kb); instead each window of window bins (the chain and the contacts with both ends in it) is solved alone, windows start every step bins (window / 2), and a pixel takes the value of the window whose centre is nearest to its midpoint. SnapHiC2 chooses the window as the smallest of 10, 20, …, 100 Mb holding more than 80 % of the cells’ contacts (auto_window()). window=None solves each chromosome whole (SnapHiC’s original method).

Functions

rwr_band() — one cell, one chromosome: the band R(i, i + d), 0 <= d <= max_diag. zscore_band() — SnapHiC’s per-diagonal z-scores of a band. impute_maps() — every cell of a ChromData (maps linked as .scool or embedded): yields (cell, chrom, band). convolve_maps(), rwr_dense() — a dense batch imputation in scHiCluster’s style (row-normalised, with self-loops, symmetrised); uchrom.emb.hic follows the authors’ code instead.

Deliberate deviations from SnapHiC’s code (github.com/HuMingLab/SnapHiC v0.2.x, read for the method): the windows here own every pixel — SnapHiC’s sliding windows leave the anti-diagonals i + j = (2k + 1) * step and the corner i + j <= step at 0; the linear systems are solved by a symmetric factorisation (SnapHiC: scipy.linalg.solve of I - (1 - rp) P^T, the same matrix up to a diagonal scaling).

uchrom.fea.impute_rwr.BACKEND = 'auto'

"auto" (the native uchrom_maps when installed, else numpy), "native" or "numpy"

class uchrom.fea.impute_rwr.ImputeParams(rp: float = 0.05, window: int | str | None = None, step: int | None = None, max_dist: int = 2050000, min_sep: int = 2, chain: bool = True, normalize: bool = True, edge: int = 5, trim: float = 0.01, min_sd: float = 1e-06)[source]

Bases: object

Knobs of the RWR imputation (defaults: SnapHiC at 10 kb).

Variables:
  • rp (float) – Restart probability (SnapHiC 0.05; scHiCluster 0.5).

  • window (int, "auto" or None) – None (default): each chromosome solved whole, as the published SnapHiC (in the numpy path memory and time grow as n^2 / n^3: a dense chromosome matrix); or a sliding-window size, bp (a multiple of the bin size), "auto": SnapHiC2’s rule (auto_window()).

  • step (int, optional) – Window step, bp; default half the window.

  • max_dist (int) – Band of the output, bp: pixels up to this separation (SnapHiC: the loop range plus a 50 kb buffer).

  • min_sep (int) – Contacts closer than this many bins are left out (SnapHiC removes neighbouring bins: 2).

  • chain (bool) – Link neighbouring bins (SnapHiC).

  • normalize (bool) – SnapHiC’s z-scores per diagonal (zscore_band()) instead of the raw RWR values.

  • edge (int) – Bins at each chromosome end left out of the z-scores (SnapHiC: the 50 kb buffer, 5 bins at 10 kb).

  • trim (float) – Share of each diagonal’s largest values left out of its mean / standard deviation (1 %).

  • min_sd (float) – Diagonals with a smaller standard deviation are set to 0.

chain: bool = True
edge: int = 5
max_dist: int = 2050000
min_sd: float = 1e-06
min_sep: int = 2
normalize: bool = True
rp: float = 0.05
step: int | None = None
trim: float = 0.01
window: int | str | None = None
uchrom.fea.impute_rwr.auto_window(distances, *, binsize: int, windows: Sequence[int] = (10000000, 20000000, 30000000, 40000000, 50000000, 60000000, 70000000, 80000000, 90000000, 100000000), share: float = 0.8) → int[source]

SnapHiC2’s window size: the smallest of windows (bp) such that more than share of the contacts are closer than it.

Parameters:
  • distances (array or sequence of arrays) – Separations of the contacts in bins (j - i), pooled over cells and chromosomes.

  • binsize (int) – Bin size, bp.

uchrom.fea.impute_rwr.convolve_maps(mats: ndarray, pad: int = 1) → ndarray[source]

The (2 pad + 1)^2 mean filter of scHiCluster (zeros outside the map) over a batch (k, n, n).

uchrom.fea.impute_rwr.impute_maps(cd, *, contacts: str = 'per_cell', cells: Sequence | None = None, chrom: None | str | Sequence[str] = None, params: ImputeParams | None = None, backend: str | None = None, n_threads: int = 0) → Iterator[Tuple[str, str, ndarray]][source]

Impute the per-cell contact maps of cd by random walk with restart (SnapHiC; Yu et al. 2021 — or scHiCluster’s RWR with rp=0.5, Zhou et al. 2019): yields (cell, chrom, band) per cell and chromosome, chromosome by chromosome.

Parameters:
  • cd (ChromData) – With per-cell maps linked (cd.link_scool; or embedded in its atlas store: the cells are exported once, cis only).

  • contacts (str) – Key of the linked per-cell maps, or the path of a .scool named by cell id.

  • cells (sequence, optional) – Cell ids (default: every cell of cd.cells).

  • chrom (str or sequence, optional) – Chromosomes (default: the autosomes of the maps).

  • params (ImputeParams, optional) – RWR and normalisation settings (default: SnapHiC’s, whole chromosomes). window="auto" is chosen from the contacts of cells on the autosomes of the maps.

  • backend – See rwr_band().

  • n_threads – See rwr_band().

Yields:

(cell, chrom, band) – band: (n_bins, max_diag + 1) float64, band[i, d] = imputed contact of bins i and i + d (z-scores with params.normalize; NaN beyond the chromosome, on the diagonal when normalised).

uchrom.fea.impute_rwr.plan_windows(n: int, window: int, step: int, max_diag: int) → Tuple[ndarray, ndarray, ndarray, ndarray][source]

The windows of a chromosome of n bins (all in bins): (starts, ends, c_lo, c_hi) — window k spans starts[k] .. ends[k] - 1 and owns the pixels with c_lo[k] <= i + j < c_hi[k] (the pixel’s midpoint nearest to the window’s centre). window == 0 or >= n: one window, the chromosome.

uchrom.fea.impute_rwr.read_cell_pixels(scool: str, cells: Sequence[str], chrom: str) → Tuple[int, List[Tuple[ndarray, ndarray]]][source]

(n_bins, [(i, j), ...]): every cell’s cis contacts of chrom in a .scool (cells missing from the file: no contacts).

uchrom.fea.impute_rwr.rwr_band(i, j, n: int, *, rp: float = 0.05, window: int = 0, step: int = 0, max_diag: int = 205, min_sep: int = 2, chain: bool = True, backend: str | None = None, n_threads: int = 0, holes: bool = False) → ndarray[source]

The RWR-imputed map of one cell’s chromosome, as a band (SnapHiC; Yu et al. 2021).

Parameters:
  • i (array of int) – The cell’s contacts (bins of the chromosome; duplicates and order do not matter: the graph is binary).

  • j (array of int) – The cell’s contacts (bins of the chromosome; duplicates and order do not matter: the graph is binary).

  • n (int) – Bins of the chromosome.

  • rp (float) – Restart probability.

  • window (int) – Sliding windows, in bins (window=0: the whole chromosome, one graph).

  • step (int) – Sliding windows, in bins (window=0: the whole chromosome, one graph).

  • max_diag (int) – Offsets 0 ..= max_diag are returned (window - step >= max_diag is required).

  • min_sep – Contacts closer than min_sep bins are left out; chain links neighbouring bins.

  • chain – Contacts closer than min_sep bins are left out; chain links neighbouring bins.

  • backend ({"auto", "native", "numpy"}, optional) – Default: the module’s BACKEND.

  • n_threads (int) – Threads of the native path (0: all).

  • holes (bool) – Leave at 0 the pixels SnapHiC v0.2’s sliding windows never set (sums i + j = (2k + 1) step and i + j <= step): only to compare with the authors’ code.

Returns:

out[i, d] = R(i, i + d), R = Q + Q^T; NaN beyond the chromosome.

Return type:

ndarray (n, max_diag + 1)

uchrom.fea.impute_rwr.rwr_dense(mats: ndarray, *, rp: float = 0.5, tol: float = 1e-06, max_iter: int = 100, self_loops: bool = True, method: str = 'iterative') → ndarray[source]

Random walk with restart on a batch of dense symmetric maps (k, n, n) (in scHiCluster’s style; the authors’ exact random_walk_cpu is uchrom.emb.hic.schicluster_impute).

P is the row-normalised map (with self_loops: plus the identity, which keeps the rows of empty bins stochastic). method="iterative": Q <- (1 - rp) Q P + rp I from Q = I until the largest change is below tol (at most max_iter steps); "exact": Q = rp (I - (1 - rp) P)^-1. Returns (Q + Q^T) / 2.

uchrom.fea.impute_rwr.zscore_band(band: ndarray, *, edge: int = 5, trim: float = 0.01, min_sd: float = 1e-06, backend: str | None = None, n_threads: int = 0) → ndarray[source]

SnapHiC’s normalisation of an RWR band: z-scores per diagonal (Yu et al. 2021).

On every diagonal d >= 1 the pixels of the rows edge <= i, i + d <= n - 1 - edge are converted to (x - mean) / sd, the mean and the (population) standard deviation taken without the largest round(trim * len) - 1 values; a diagonal with sd < min_sd is 0. Pixels of those diagonals outside the trimmed rows are 0 (SnapHiC drops them: zeros in its matrices); the main diagonal and pixels beyond the chromosome are NaN.

Returns a new array of the band’s shape.

Pileups (APA)

A linked map aggregated around known loops or boundaries.

Pileups of a Hi-C map around a set of features: aggregate peak analysis (APA) of loops, on-diagonal pileups of points (domain boundaries, peaks).

A loop that is too weak to be called in a sparse map — a cell-type pseudo-bulk, a few deep single cells — still shows when the map is averaged over many loops: pileup() cuts a (2f+1) x (2f+1) window of the map around every feature and aggregates observed over expected (the expected contact at each pixel’s separation): the summed observed over the summed expected of every pixel of the window (default), or the mean of the features’ observed / expected windows. Pairs (loops chrom1, start1, end1, chrom2, start2, end2; called in bulk Hi-C, or from imaging) are centred on the pixel of their two anchors (Rao et al. 2014, APA); points (chrom, start, end) on the diagonal at the point.

The scores follow Juicer APA (Rao et al. 2014; Durand et al. 2016): for pairs apa = P2LL, the centre pixel over the mean of the lower-left corner (the corner x corner square towards the diagonal), p2m the centre over the mean of the rest of the window and zscore_ll the centre’s z-score in the lower-left corner — above 1 (P2LL) when the loops are enriched. For points score = mean of the two on-diagonal quadrants (upstream x upstream, downstream x downstream) over the mean of the cross quadrant (upstream x downstream) — above 1 at insulating boundaries.

References

Rao, S. S. P. et al. (2014) Cell 159:1665-1680 (APA). Durand, N. C. et al. (2016) Juicer provides a one-click system for analyzing loop-resolution Hi-C experiments. Cell Syst. 3:95-98. Flyamer, I. M., Illingworth, R. S. & Bickmore, W. A. (2020) Coolpup.py: versatile pile-up analysis of Hi-C data. Bioinformatics 36:2980-2985.

uchrom.fea.pileup_maps.pileup(cd, features, *, contacts=None, resolution: int | None = None, chrom=None, flank: int | None = None, expected: bool | DataFrame = True, balance: bool = True, min_separation: int | None = None, max_separation: int | None = None, corner: int | None = None, ignore_diags: int = 2, aggregate: str = 'sum', shifts: Sequence[int] | None = None, key_added: str | None = 'pileup', copy: bool = False)[source]

The average observed / expected Hi-C map around a set of features (APA; Rao et al. 2014).

Parameters:
  • cd (ChromData) – Holds the map (cd.link_cool) and receives the result; or the path of a .cool / .mcool (then nothing is stored).

  • features (DataFrame or str) – Pairs (chrom1, start1, end1, chrom2, start2, end2; e.g. loops from call_loops_hiccups(), call_loops_axiswise_f(), a published list) or points (chrom, start, end; e.g. domain boundaries), or a key of cd.intervals / cd.results. An anchor sits in the map bin holding its midpoint; pairs between chromosomes are left out.

  • contacts (str, optional) – Key of the linked map (None: the only one) or the path of a .cool / .mcool.

  • resolution (int, optional) – The level of an .mcool.

  • chrom (str or sequence of str, optional) – Only the features on these chromosomes.

  • flank (int, optional) – Half-width of the window, bp (default 10 bins, as Juicer APA).

  • expected (bool or DataFrame) – True: divide every pixel by the mean contact of its diagonal on its chromosome (uchrom.fea.band.expected_cis(), from the map itself); a DataFrame: that expected (chrom, diag, balanced_avg — or count_avg with balance=False); False: the (balanced) observed.

  • balance (bool) – Balanced values (cooler weight); False = raw counts (a map too sparse to balance).

  • min_separation (int, optional) – Pairs whose anchors are closer / farther (bins) are left out. Default minimum: the window stays off the ignored diagonals (2 * flank_bins + ignore_diags).

  • max_separation (int, optional) – Pairs whose anchors are closer / farther (bins) are left out. Default minimum: the window stays off the ignored diagonals (2 * flank_bins + ignore_diags).

  • corner (int, optional) – Side of the lower-left square of the APA score, bins (Juicer: 3 at 5 kb, else 6).

  • ignore_diags (int) – Diagonals left out (NaN): the first two, as for the expected.

  • aggregate ({"sum", "mean"}) – "sum" (default): per pixel, the summed observed over the summed expected of the features — the Poisson maximum-likelihood enrichment of the set; features weigh by their expected, so a few far-apart pairs (tiny expected, huge O/E) cannot dominate, and it is steadier in sparse maps. "mean": the mean of the features’ observed / expected windows (every feature weighs the same).

  • shifts (sequence of int, optional) – Controls: the same features moved along the chromosome by each shift (bp; e.g. (-1_000_000, -500_000, 500_000, 1_000_000)), piled up the same way. Their score (pairs: apa; points: score) is what the set gives without the features’ own enrichment — a pair keeps its separation, so the distance decay is the same.

  • key_added (str or None) – cd.results key (default "pileup"); None does not store.

  • copy (bool) – True → return a new ChromData holding the result.

Returns:

matrix (the mean window, (2f+1, 2f+1); rows = first anchor ± f bins, columns = second), n_pixels (features contributing to each pixel), n (features used), n_dropped, kind, resolution, flank_bins, the scores of pileup_scores() (pairs: apa, p2m, zscore_ll; points: score), and features: the feature table with used, center (their centre pixel), lower_left (mean of their lower-left square) for pairs. With shifts: control (the mean score of the shifted sets) and controls ({shift: score}).

Return type:

dict (copy=False) or ChromData (copy=True)

Examples

>>> loops = ds.fetch("rao2014_annotations")
>>> apa = pileup(hic, published_loops, contacts="bulk_10kb")
>>> apa["apa"]
uchrom.fea.pileup_maps.pileup_scores(matrix: ndarray, *, kind: str = 'pair', corner: int = 6) → dict[source]

Scores of a pileup window ((2f+1) x (2f+1), rows = first anchor, columns = second).

kind="pair": apa (P2LL: centre / mean of the lower-left corner x corner square), p2m (centre / mean of the other pixels), zscore_ll (centre’s z-score in the lower-left square, sample s.d.). kind="point": score = mean of the on-diagonal quadrants / mean of the upstream x downstream quadrant (centre row and column left out). NaN pixels are left out.

Contact features per cell

From the contact-distance histograms of every cell or spatial Hi-C spot (uchrom.io.ContactStats): the short / long-range ratio (Guo et al. 2026’s bins), distance bands, contact-decay slopes, cis fraction, trans share per chromosome; and a copy-number profile, each chromosome’s share of the contact legs (chromosome_dosage).

Global 3-D genome features of every cell from its contacts: the share of short- and long-range cis contacts and their ratio, the slope of the contact-decay curve P(s), the cis fraction and the share of each chromosome’s contacts that are trans — from the contact-distance histograms of uchrom.io.ContactStats stored on the object (cd.cellm["<key>.distance"], cd.uns["contact_stats"][key]).

The short / long-range ratio is that of Guo et al. 2026 by default: contacts closer than 5 kb are left out, short = 200 kb - 2 Mb and long = 20 - 50 Mb as fractions of the remaining cis contacts (scHiCluster’s bins 51-76 and 103-114, ContactFeatureParams.guo2026()). A bin counts in a range when its centre (geometric mean of its edges) lies inside; guo2026() gives the exact bins of the paper.

Pooled over the chromosomes (the default, as the papers compute them), the features also depend on which chromosomes the contacts come from: long-range contacts exist only on long chromosomes, and the cis fraction on how many chromosomes there are. In an aneuploid tissue (a tumour’s clones) a gain of small chromosomes raises a cell’s short / long ratio without any change of folding. per_chromosome=True computes every feature on each chromosome’s own histogram and averages them over a fixed set of chromosomes with equal weights, so a gain or loss of whole chromosomes leaves them unchanged (a gain of part of a chromosome still shifts that chromosome’s distances).

chromosome_dosage() reads the same statistics as a copy-number profile: each chromosome’s share of a cell’s contact legs, relative to the cells’ median share.

class uchrom.fea.contact_stats.ContactFeatureParams(min_distance: float = 5000.0, short: Tuple[float, float] = (200000.0, 2000000.0), long: Tuple[float, float] = (20000000.0, 50000000.0), short_bins: Tuple[int, int] | None = None, long_bins: Tuple[int, int] | None = None, bands: Sequence[Tuple[float, float]] = ((2000000.0, 12000000.0),), slopes: Sequence[Tuple[float, float]] = ((100000.0, 1000000.0), (1000000.0, 10000000.0)), chroms: Sequence[str] | None = None, per_chromosome: bool = False)[source]

Bases: object

Ranges (bp) of the contact features.

Variables:
  • min_distance (float) – Cis contacts closer than this are left out of every fraction (undigested / self-ligated fragments).

  • long (short,) – The short- and long-range ranges of short_long_ratio; short_bins / long_bins (half-open index ranges into the histogram’s distance bins, scHiCluster numbering) override them.

  • bands (Sequence[Tuple[float, float]]) – More ranges reported as fractions of the cis contacts (frac_<lo>_<hi>), e.g. the mitotic band 2-12 Mb of Nagano et al. 2017.

  • slopes (Sequence[Tuple[float, float]]) – Ranges over which the slope of log10 P(s) on log10 s is fitted (contacts per bp of distance).

  • chroms (Sequence[str] | None) – The chromosomes counted (default: all of the histograms; with per_chromosome, those whose pooled histogram over all cells has at least half the genome-wide share of long-range contacts – the chromosomes long enough for the long range).

  • per_chromosome (bool) – Each feature computed per chromosome and averaged over chroms with equal weights (needs the histograms per chromosome, ContactStats.write(per_chromosome=True)); n_cis / n_trans / n_used stay totals and trans_share.<chrom> per chromosome.

bands: Sequence[Tuple[float, float]] = ((2000000.0, 12000000.0),)
chroms: Sequence[str] | None = None
classmethod guo2026(**kw) → ContactFeatureParams[source]

The short / long ranges of Guo et al. 2026 (Spatial-Hi-C-RNA, MouseBrain/02_short_long_contact_ratio): scHiCluster bins 51-76 (207 kb - 1.97 Mb) and 103-114 (18.8 - 53.1 Mb), contacts < 5 kb removed.

long: Tuple[float, float] = (20000000.0, 50000000.0)
long_bins: Tuple[int, int] | None = None
min_distance: float = 5000.0
per_chromosome: bool = False
short: Tuple[float, float] = (200000.0, 2000000.0)
short_bins: Tuple[int, int] | None = None
slopes: Sequence[Tuple[float, float]] = ((100000.0, 1000000.0), (1000000.0, 10000000.0))
uchrom.fea.contact_stats.chromosome_dosage(cd, *, key: str = 'contacts', cells=None, groupby: str | None = None, exclude: Sequence[str] = ('chrY',), n_pcs: int = 0, key_added=UNSET, copy: bool = False)[source]

Per-cell copy-number profile from the contacts: log2 of each chromosome’s share of the cell’s contact legs over the cells’ median share.

A cis contact puts two legs on its chromosome, a trans contact one on each of its two. A chromosome present in three copies instead of two carries about 1.5 times the legs, so the log2 share over the median is about the log2 of its copies over the typical cell’s: a coverage profile at the resolution of whole chromosomes, as a copy-number caller reads from sequencing depth. It is a proxy. It is relative to the median cell, so a gain that every cell carries does not show. The shares sum to one, so a gain lowers the other chromosomes a little. And anything else that changes how many contacts a chromosome gives shifts it too.

Parameters:
  • cd – A ChromData with ContactStats.write(cd, key=key).

  • key – The contact statistics’ key.

  • cells – Only these cells (default all); the median is taken over them.

  • groupby – A cd.cells column (section, sample): the median of each group is its cells’ reference.

  • exclude – Chromosomes left out of the shares (default chrY: a few contacts or none).

  • n_pcs – Also the first n_pcs principal components of the profiles (each chromosome z-scored over the cells, missing values at 0; signs arbitrary): the axes along which the cells’ profiles differ most. A tumour clone changes several chromosomes at once, so one component can carry its whole pattern; as covariates they stand for copy number in a spatial test (uchrom.spatial.spatially_variable()).

  • key_added – Where to store (default "<key>.dosage"; None: nothing stored): cd.cellm[key_added] (n_cells, n_chroms; NaN for cells left out), cd.cellm["<key_added>.pcs"] and the table cd.results[key_added].

Returns:

Indexed by cell id (in the order of cells): one column per chromosome, then PC1 … with n_pcs. A cell without contacts, or a chromosome without legs in a cell, is NaN. attrs["pc_variance"]: the share of the z-scored profiles’ variance of each component.

Return type:

DataFrame

uchrom.fea.contact_stats.contact_features(cd, *, key: str = 'contacts', cells=None, params: ContactFeatureParams | None = None, key_added=UNSET, copy: bool = False)[source]

Per-cell contact features from the stored contact-distance histograms.

Parameters:
  • cd – A ChromData with ContactStats.write(cd, key=key).

  • key – The histograms’ key.

  • cells – Only these cells (default all).

  • params – ContactFeatureParams (default: Guo et al. 2026’s ranges by bin centre).

  • key_added – Prefix of the cd.cells columns written (default key; None: nothing written) — e.g. contacts.short_long_ratio; the table is also cd.results["<key_added>.features"].

Returns:

Indexed by cell id: n_cis (all distances), n_trans, cis_fraction, n_used (cis at >= min_distance), frac_short, frac_long, short_long_ratio, frac_<band>, ps_slope_<range>, trans_share.<chrom> (each chromosome’s trans legs over all its legs).

Return type:

DataFrame

Proximity by genomic separation

One per-cell summary from contacts or from traced coordinates: the contacts at short over long separations of the per-cell maps (.scool or embedded), or the 3-D distances of locus pairs at long over short separations of the traces, separations measured midpoint to midpoint in both; optionally the whole profile per cell (contact decay or distance scaling).

Per-cell proximity by genomic separation, from contacts or from 3-D coordinates: one question asked of sequencing and imaging data alike.

Single-cell Hi-C counts how often two loci touch; chromatin tracing measures how far apart they are. Both change with the genomic separation of the two loci, and how they change differs between cell types (the share of short- over long-range contacts: Nagano et al. 2017, Nature 547:61; Tan et al. 2021, Cell 184:741). separation_profile() computes for every cell the same summary from either kind of data:

  • contacts — the per-cell maps linked to the object (a .scool, or maps embedded in an atlas store, also over HTTP): the cis contacts whose two bins lie a separation apart;

  • coordinates — the spots of the cell’s traces: the 3-D distance of every pair of spots of one trace (one chromosome copy) whose loci lie a separation apart, reduced per cell to the median (or mean) and, with threshold, to the share of pairs closer than it.

The separation is that of the bin or locus midpoints in both, so the contacts of a 1-Mb map at offset k are at k Mb, as are two loci imaged k Mb apart. short and long (half-open ranges, bp) give the summary:

log2_short_long = log2((n_short + pseudocount) / (n_long + pseudocount))     contacts
log2_short_long = log2(d_long / d_short)                                     coordinates

both higher when the short range is relatively closer (more contacts, shorter distances). Only differences within a dataset (between cell types, conditions) are meant to be compared, never values across assays. edges adds the whole profile per cell: contacts per separation bin (the cell’s contact-decay curve) or the distance per separation bin (its distance scaling):

t = separation_profile(cd)                                   # per-cell maps or traces, whichever cd holds
t.groupby(cd.cells["cell_type"])["log2_short_long"].median()
separation_profile(cd, params=SeparationParams(edges=np.arange(0.5, 100.5) * 1e6))
cd.cellm["separation.profile"]                               # cells x 100 separation bins
class uchrom.fea.separation.SeparationParams(short: Tuple[float, float] = (1000000.0, 2000000.0), long: Tuple[float, float] = (19000000.0, 54000000.0), edges: Sequence[float] | None = None, chroms: Sequence[str] | None = None, exclude: Sequence[str] = ('chrX', 'chrY', 'chrM'), stat: str = 'median', threshold: float | None = None, pseudocount: float = 0.5, duplicates: str = 'last')[source]

Bases: object

Ranges and reductions of separation_profile().

Variables:
  • long (short,) – Half-open separation ranges [lo, hi) (bp, midpoint to midpoint) of the summary. The defaults take map offset 1 (1 Mb) and offsets 19-53 of a 1-Mb map, and loci 1-2 Mb and 19-54 Mb apart.

  • edges (Sequence[float] | None) – Separation bin edges (bp, increasing; bins [edges[k], edges[k + 1])) of the profile stored per cell; None: no profile.

  • chroms (Sequence[str] | None) – The chromosomes used (default: every chromosome but those in exclude).

  • exclude (Sequence[str]) – Left out when chroms is not given (matched without the chr prefix, any case): the sex chromosomes, whose copy number differs between cells and sexes, and the mitochondrial genome.

  • stat (str) – "median" (default) or "mean" distance of a cell’s pairs in a range (coordinates).

  • threshold (float | None) – Coordinates: also the share of a cell’s pairs in a range closer than this distance (the units of the coordinates), f_short / f_long.

  • pseudocount (float) – Added to both counts of the contact ratio (cells without contacts in a range keep a finite ratio).

  • duplicates (str) – Coordinates: the spot a trace keeps at a bin it observed more than once ("last", "first", "mean", "median"; as uchrom.fea.distance_map()).

chroms: Sequence[str] | None = None
duplicates: str = 'last'
edges: Sequence[float] | None = None
exclude: Sequence[str] = ('chrX', 'chrY', 'chrM')
long: Tuple[float, float] = (19000000.0, 54000000.0)
pseudocount: float = 0.5
short: Tuple[float, float] = (1000000.0, 2000000.0)
stat: str = 'median'
threshold: float | None = None
uchrom.fea.separation.separation_profile(cd, *, source: str = 'auto', contacts: None | str | Sequence[str] = None, cells: Sequence | None = None, params: SeparationParams | None = None, batch: int | str = 256, workers: int = 4, max_pixels: int = 2000000, key_added=UNSET, copy: bool = False)[source]

Per-cell proximity at short and long genomic separations (and optionally the whole profile), from the per-cell contact maps or from the traced coordinates of a ChromData.

Parameters:
  • cd – A ChromData, in memory or backed: with per-cell maps linked (cd.link_scool; a local .scool or maps embedded in the store, also an atlas store over HTTP), or with spots (one trace per chromosome copy; cell_id groups them into cells, without it every trace is a unit).

  • source – "contacts", "coords" or "auto" (the one cd holds; both: an error).

  • contacts – Keys of the linked per-cell maps (default: all of them, e.g. the two sections of a spatial Hi-C store), or a .scool path whose cell names are the cell ids.

  • cells – Only these cells (default all; traces without cells: these trace ids).

  • params – SeparationParams.

  • batch – Coordinates: cells read at a time (iter_cells; "auto" from the memory budget).

  • workers – Contacts: reads of embedded maps in flight and pixels per read (uchrom.fea.pseudobulk()).

  • max_pixels – Contacts: reads of embedded maps in flight and pixels per read (uchrom.fea.pseudobulk()).

  • key_added – Prefix of the cd.cells columns written (default "separation"; None: nothing stored), e.g. separation.log2_short_long; the table is also cd.results[key_added], the profile (with edges) cd.cellm["<key_added>.profile"] (cells x separation bins; coordinates also "<key_added>.n_pairs"), with the bins in the result’s parameters.

  • copy – Store on a copy of cd and return it.

Returns:

Indexed by cell id (trace id for traces without cells), one row per cell used (NaN for a cell without maps or spots). Contacts: n_cis (cis contacts of the chromosomes used, also within a bin), n_apart (between different bins), n_short, n_long, log2_short_long. Coordinates: n_traces, n_spots (finite), d_short, d_long (median or mean distance), n_pairs_short, n_pairs_long, f_short / f_long (with threshold), log2_short_long. Without a stored key the profile is out.attrs["profile"].

Return type:

DataFrame

Known structures scored per cell

Boundaries and loops called on a pooled map, scored in every cell from the contacts counted in their windows (uchrom.io.WindowCounts): insulation against domain interiors, peak over donut, and both against the cell’s own expected from its contact-distance histograms (window_expected).

Per-cell strength of known boundaries and loops from contacts counted in their windows (uchrom.io.WindowCounts): structures called once on a pooled map, scored in every cell or spatial Hi-C spot that is too shallow to call them itself.

Boundaries. Per cell and boundary, the insulation is log2 of the contacts per pixel crossing the boundary over the contacts per pixel within its flanks. It depends on the cell’s contact-decay shape (the cross square lies further from the diagonal than the flanks), so it is compared with the same ratio at domain interiors (windows of kind="interior", no boundary): boundary_strength = log2(within / cross at the boundaries) - log2(within / cross at the interiors) over all boundaries — a cell’s overall insulation — and insulation[k] = boundary k’s log2(cross / within) minus the interiors’ — negative where the boundary insulates in that cell.

Loops. Per cell and loop, log2 of the contacts per pixel at the loop (the peak) over those around it (the donut); loop_strength pools all loops (an aggregate peak analysis per cell).

Pseudo-counts (pseudo, per window) keep the logs finite; per-structure scores of a cell with few contacts are noisy, the pooled ones much less so.

Against the cell’s own expected (expected=, window_expected(): each window’s contacts predicted from the cell’s contact-distance histogram of that chromosome, uchrom.io.ContactStats). A structure’s per-cell log ratio depends on more than the structure: on the cell’s contact decay (the windows lie at different distances from the diagonal) and, at a few contacts per window, on how many contacts the cell has on that chromosome (the log of a few counts plus a pseudo-count is biased, by an amount that changes with the counts). Where the decay or the coverage varies across a tissue (copy number, a haploid chromosome X), these scores can vary with it, alike for the structures of a chromosome or the loops of a size. The scores against the expected remove both: insulation_oe[k] = the share of boundary k’s contacts that cross it minus the share the cell’s decay predicts (negative where it insulates), loops_oe[k] = the share of loop k’s contacts at its peak (of peak + donut) minus the predicted share; a share is unbiased at any number of contacts (NaN at none). Pooled: boundary_strength_oe (log2 observed / expected within the flanks minus the same across the boundaries), loop_strength_oe (peak minus donut) and interior_oe (the same as boundary_strength_oe at the interiors: about 0 where the expected describes the cell).

uchrom.fea.window_scores.window_expected(counts, stats, *, chromsizes: Mapping, samples: int = 16) → ndarray[source]

The contacts each cell is expected to have in each window, from its own contact-distance histogram of the window’s chromosome.

Parameters:
  • counts – WindowCounts (its windows, resolution and cells).

  • stats – ContactStats of the same contacts (distance per chromosome; cells matched by id).

  • chromsizes – Chromosome lengths (bp).

  • samples – Distances per histogram bin in the integration.

Returns:

  • ndarray (n_cells of ``counts``, n_windows), float (per window, sum over distance bins of the cell’s contacts)

  • on that chromosome in the bin times the fraction of such contacts the window holds (contacts placed uniformly

  • along the chromosome). NaN for cells without statistics, 0 for windows on chromosomes the statistics lack.

uchrom.fea.window_scores.window_scores(counts, *, expected: ndarray | None = None, pseudo: float = 0.5, per_structure: bool = True) → dict[source]

Scores of each cell from WindowCounts with windows of kinds boundary, interior (optional) and loop; expected (window_expected(), cells x windows) adds the scores against each cell’s own expected.

Returns:

"cells": DataFrame indexed by cell — boundary_strength (with interiors), boundary_ratio (log2 within / cross at the boundaries, without the interior correction), interior_ratio, loop_strength, the summed counts n_boundary, n_interior, n_loop_peak, n_loop_donut; with per_structure: "insulation" (cells x boundaries, log2 cross / within minus the cell’s interior ratio) and "loops" (cells x loops, log2 peak / donut per pixel), plus "boundary_counts" and "loop_counts" (dicts of raw count matrices by part). With expected: the columns boundary_strength_oe, interior_oe, loop_strength_oe and, with per_structure, "insulation_oe" / "loops_oe" (cells x structures, observed minus expected shares).

Return type:

dict

Comparing structures

Model ensembles, models against imaging, models against their contacts.

Comparing 3-D structures: with each other, with imaging, with the contacts they come from.

A few ideas cover the usual checks of a reconstruction:

Bins are genomic intervals [start, end). NucDynamics / EMber particles are (start, end] (the particle at position p holds the contacts in (p - size, p]); a reconstruction records this in uns[...]["particle_position"] == "end", and closed=None follows it.

class uchrom.fea.compare.Comparison[source]

Bases: dict

Result of a comparison: a dict with attribute access; scores holds its scalar entries (for a table), the other entries are arrays / tables (matrices, the shared bins).

property scores: Dict[str, float]
uchrom.fea.compare.bin_index(bins, chrom, pos, *, closed: str = 'left') → ndarray[source]

The row of bins (0 .. len(bins) - 1) whose interval holds each position; -1 when none does.

Parameters:
  • bins – A table with chrom, start, end (or a ChromData: its bins); intervals of one chromosome must not overlap; gaps are allowed.

  • chrom – A chromosome and a position (bp) per query (arrays of the same length, or a scalar chromosome).

  • pos – A chromosome and a position (bp) per query (arrays of the same length, or a scalar chromosome).

  • closed – "left": [start, end) (genomic bins); "right": (start, end] (NucDynamics particles).

uchrom.fea.compare.compare_distances(cd, ref, *, bins=None, stat: str = 'median', by: str = 'trace', position: str = 'mid', closed: str | None = None) → Comparison[source]

Distance statistics of two objects on shared bins — a structure (or a population of structures) against chromatin tracing, typically.

Both are averaged onto the same bins (rebin_coords(), per trace), the pairwise distances of every trace are reduced to one matrix per object (median over traces; a single structure is its own distance matrix), and the two matrices are compared over the bin pairs both observe.

Parameters:
  • cd – The model: a structure, a population (one trace per chromosome copy), or any traced data.

  • ref – The reference, e.g. chromatin tracing (distances in nm).

  • bins – The shared grid (default: the bins of cd).

  • stat – "median" or "mean" over traces.

  • by – Group spots by "trace" (default) or "cell".

  • position – How spots are put onto the grid (see rebin_coords()).

  • closed – How spots are put onto the grid (see rebin_coords()).

Returns:

pearson (Pearson r of the two matrices over the shared pairs), rel_error (mean of |s * d_cd - d_ref| / d_ref after rescaling cd by the least-squares factor s of that error, GEM-FISH’s error measure), scale (s: units of ref per unit of cd), ratio (median of d_cd / d_ref), n_bins, n_pairs; bins (the shared bins: rows of the grid, with their positions in it as the index), model and reference (the two matrices on them).

Return type:

Comparison

uchrom.fea.compare.compare_structures(cd, ref, *, n_models: int | None = None, ref_models: int | None = None, position: str = 'mid', closed: str | None = None, min_particles: int = 10) → Comparison[source]

Two structure ensembles of one cell compared model by model — e.g. a reconstruction against the published structures of the same cell, or two solvers.

The particles of ref are averaged onto the particles of cd (a particle of ref goes to the particle of cd whose interval holds its position); then, for every model of cd and every model of ref, distance_correlation() by chromosome over the particles of cd that received one.

Parameters:
  • cd – One structure (ensemble) with one particle per bin (haploid; e.g. one cell).

  • ref – The other one (any particles; e.g. ds.load("stevens2017_mesc").get_cell("Cell_1")).

  • n_models – Use the first models of each ensemble (ensemble_models(); None: all).

  • ref_models – Use the first models of each ensemble (ensemble_models(); None: all).

  • position – The position of a ref particle: "mid", "start" or "end" of its locus.

  • closed – The intervals of cd’s particles (None: as the reconstruction recorded, see the module).

  • min_particles – Chromosomes with fewer matched particles are left out.

Returns:

distance_r (mean over the model pairs of the median correlation by chromosome), n_particles (particles of cd matched), r (n_models x ref_models).

Return type:

Comparison

uchrom.fea.compare.contact_agreement(cd, hic, *, contacts: str | None = None, chrom=None, resolution: int | None = None, balance: bool = True, max_separation: float | None = None, closed: str | None = None) → Comparison[source]

How well a structure reproduces a contact map: Spearman correlation of the contact frequency and 1 / distance over the bin pairs, raw and after removing the distance decay (both sides divided by their mean at each genomic separation — in bins of the map, so bins the structure lacks leave gaps — observed_over_expected()).

Parameters:
  • cd – A structure (or a population: median distance over its traces).

  • hic – A ChromData with the map linked (may be cd itself), or the path of a .cool / .mcool.

  • contacts – Key of the linked map (None: the only one).

  • chrom – Chromosome(s) (default: those of cd); pairs of different chromosomes are not compared.

  • resolution – The map level (an .mcool) and whether to use balanced values (see contact_matrix()).

  • balance – The map level (an .mcool) and whether to use balanced values (see contact_matrix()).

  • max_separation – Only pairs at most this far apart (bp, bin starts).

  • closed – How the particles of cd are put onto the map’s bins (by the midpoint of their locus).

Returns:

spearman (pairs with contacts), spearman_oe, n_pairs.

Return type:

Comparison

uchrom.fea.compare.contact_distances(cd, contacts, *, layer: str | None = None, closed: str | None = None) → ndarray[source]

The distance, in a structure, between the two ends of every contact.

Each end goes to the particle whose interval holds its position.

Parameters:
  • cd – One structure with one particle per bin (haploid; e.g. reconstruct_ember output).

  • contacts – A table / dict with chrom_a, pos_a, chrom_b, pos_b (e.g. uchrom.recon.sc.nucdyn.load_contacts(path)).

  • layer – A model layer instead of coords (model 0).

  • closed – The particles’ intervals (None: as the reconstruction recorded; NucDynamics: (start, end]).

Returns:

  • ndarray, one distance per contact — NaN where an end has no particle or both ends fall into the same

  • particle (no restraint between two particles).

uchrom.fea.compare.distance_correlation(a, b, *, groups=None, min_size: int = 10) → float[source]

Pearson correlation of the pairwise distances of two coordinate sets of the same points — the median over groups (e.g. chromosomes) of the correlation within each group.

Parameters:
  • a – (n, 3) coordinates, row i the same point in both.

  • b – (n, 3) coordinates, row i the same point in both.

  • groups – A label per row (e.g. the chromosome); None: one group. Only distances within a group count.

  • min_size – Groups with fewer points are left out.

Return type:

The median correlation (NaN when no group is large enough).

uchrom.fea.compare.ensemble_agreement(cd, *, n_by_chrom: int | None = 4, min_particles: int = 10, reflection: bool = False) → Comparison[source]

How much the models of an ensemble (ensemble_models()) agree.

Parameters:
  • cd – One structure ensemble (e.g. reconstruct_nucdyn / reconstruct_ember output, or one cell of published structures).

  • n_by_chrom – The per-chromosome measures use the pairs of the first n_by_chrom models (None: all; each pair costs a distance matrix per chromosome).

  • min_particles – Chromosomes (traces) with fewer particles are left out of the per-chromosome measures.

  • reflection – Allow mirror images in the superposition (see kabsch_rmsd()).

Returns:

rmsd (n_models x n_models, genome-wide RMSD after superposition), rmsd_mean (mean over the pairs), rmsd_per_chrom (median over model pairs and chromosomes of the RMSD of one chromosome superposed alone), distance_r (median over model pairs of distance_correlation() by chromosome), n_models. Per chromosome means per trace (a chromosome copy).

Return type:

Comparison

uchrom.fea.compare.ensemble_models(cd) → List[ndarray][source]

The models of a structure ensemble, each (n_spots, 3) in spot order: the layers model_<k> in the order of k, preceded by coords unless it is one of them (a reconstruction keeps model 0 in coords and every model as a layer; a published ensemble may keep model 1 in coords and models 2-10 as layers). Without such layers: [coords].

uchrom.fea.compare.kabsch_rmsd(a, b, *, reflection: bool = False) → float[source]

Root-mean-square deviation of two coordinate sets of the same points after optimal superposition (translation + rotation, Kabsch 1976).

Parameters:
  • a – (n, 3) coordinates, row i the same point in both; rows with a NaN in either are left out.

  • b – (n, 3) coordinates, row i the same point in both; rows with a NaN in either are left out.

  • reflection – Allow the mirror image as well (an improper rotation) — for structures computed from contacts, which a structure and its mirror image satisfy equally.

Return type:

RMSD in the units of the coordinates.

uchrom.fea.compare.match_spots(a, b, on=None) → Tuple[ndarray, ndarray][source]

Rows of the same spots in two objects (e.g. before and after a round trip through a store, which sorts the spots).

Parameters:
  • a – ChromData objects.

  • b – ChromData objects.

  • on – Spot column(s) that identify a spot; default "spot_id" when both have it, else the cell, trace and locus (cell_id, trace_id, chrom, start, end, those present in both).

Returns:

Row positions such that a row ia[k] and b row ib[k] are the same spot, sorted by the key; spots of only one object are left out.

Return type:

(ia, ib)

uchrom.fea.compare.rebin_coords(cd, bins, *, by: str | None = 'trace', position: str = 'mid', closed: str | None = None, layer: str | None = None) → Tuple[ndarray, ndarray][source]

The coordinates of cd averaged onto other bins, one row per trace (or cell).

Every spot goes to the bin of bins that holds its position (the midpoint, start or end of its locus); the spots of one trace in one bin are averaged.

Parameters:
  • cd – Spots with coordinates (chromatin tracing, a structure, a population).

  • bins – Target bins (chrom, start, end; or a ChromData: its bins).

  • by – "trace", "cell" or None (all spots together).

  • position – "mid" (default), "start" or "end" of a spot’s locus.

  • closed – Target intervals "left" = [start, end), "right" = (start, end]; None: "left" unless bins is a reconstruction with NucDynamics particles.

  • layer – Use this layer instead of coords.

Returns:

  • cube (ndarray (n_groups, len(bins), 3)) – NaN where a group has no spot in a bin.

  • groups (ndarray) – The trace (cell) id of every row (order of first appearance).

Positions in the nucleus

Where the spots sit in their nucleus: the centre of a cell’s (or a trace’s) spots and each spot’s radial position relative to it.

centres = spot_centroids(cd, by=”cell”, stat=”median”) # x, y, z per cell radial_position(cd) # -> cd.spot_tracks[“radial_position”]

uchrom.fea.positions.radial_position(cd, *, by: str = 'cell', centre: str = 'median', scale: float | None = 0.95, key_added: str | None = 'radial_position', copy: bool = False)[source]

Radial position of every spot: its distance from the centre of its cell’s spots, scaled per cell.

The centre is the per-axis centre (median by default) of the cell’s spots (spot_centroids()); the distance is divided by the scale quantile of the distances of that cell’s spots (the 95th percentile by default — a robust nuclear radius), so ~0 is the nucleus centre and ~1 its edge, comparable between cells of different size. scale=None keeps the distance in the unit of the coordinates.

Parameters:
  • cd (ChromData) – In memory (a backed object needs key_added=None: its spot tracks are read-only).

  • by ("cell" (default; needs cell_id) or "trace") – The group whose spots give the centre (and the scale): the nucleus, or one chromatin fibre.

  • centre ("median" (default) or "mean")

  • scale (float in (0, 1] or None) – Quantile of the group’s distances to divide by; None: no scaling.

  • key_added (str or None) – The cd.spot_tracks column to write (default "radial_position"), recorded in cd.uns["feature_registry"]; None: only return the values.

  • copy (bool) – True: write to a copy of cd and return it.

Returns:

One value per spot (index = the rows of cd.spots); NaN for spots with a NaN coordinate.

Return type:

Series (copy=False) or ChromData (copy=True)

uchrom.fea.positions.spot_centroids(cd, *, by: str = 'cell', stat: str = 'mean') → DataFrame[source]

The centre of the spots of every cell (or trace): the per-axis mean or median of their coordinates.

An estimate of the nucleus centre from the DNA spots alone — e.g. to check that a segmentation centroid shares the frame of coords, or to register it as an inferred cell position (cd.set_cell_positions(spot_centroids(cd), status="inferred", ...)).

Parameters:
  • cd (ChromData)

  • by ("cell" (default; needs cell_id) or "trace")

  • stat ("mean" (default) or "median") – Per axis; NaN coordinates are skipped.

Returns:

x, y, z indexed by cell_id (or trace_id) as strings, sorted.

Return type:

DataFrame

Axis-wise preprocessing

ArcFISH preprocessing of chromatin tracing data: per-axis pairwise variances, their outlier filter and normalisation by genomic distance, and the axis weights.

Reference

Yu H. et al. ArcFISH: accurate and robust 3D genome feature discovery from chromatin tracing data. bioRxiv 2025.11.26.690837 (software: github.com/hyuyu104/ArcFISH). U-Chrom’s own implementation of the published algorithm; its output is checked against the authors’ package (commit a21d889) by uchrom-reproducibility supp_table3/arcfish_parity/ (per-position statistics and calls on the datasets of the authors’ tutorials and others).

Conventions (the authors’, so that the results agree)

  • The loci of a chromosome are its bins with at least one finite coordinate, keyed and sorted by start; the genomic distance of two loci is |start_i - start_j|.

  • A trace that observed a locus more than once keeps its first spot (spot order).

  • Medians are the usual medians: the mean of the two middle values for an even count.

  • A variance within 1e-8 of zero (numpy.isclose) is left out of a LOWESS fit.

Pipeline (per chromosome)

  1. axis_variance_cube(): the coordinates as a (traces, loci, 3) cube, the per-axis pairwise variance / count / mean (unfiltered) and the axis weights.

  2. filter_normalize(), per axis and locus pair, over the traces observing both loci:

    • pass 1: the raw variance is the median squared deviation of the differences from their median; LOWESS of log raw variance on log genomic distance (frac 0.1, upper triangle) gives a stratified variance, its square root the stratified s.d.; a difference farther than k_sigma (4) s.d. from the pair’s median is an outlier and is removed;

    • pass 2: count = the remaining traces, var = the mean squared deviation from their mean; LOWESS of log var on log genomic distance gives the expected variance and norm_var = var / expected (diagonal 0).

  3. axis_weight(): per axis, each trace centred at its mean over loci; per locus the mean square over the traces; the weight is 1 / median over loci, normalised to sum 1.

The pairwise differences run on a torch device ('auto' | 'cpu' | 'cuda' | 'mps') in row blocks; the LOWESS fits use statsmodels on the CPU. uchrom.fea.arc_stream computes the same without the (3, traces, loci, loci) tensor.

uchrom.fea.arc.axis_variance_cube(cd, chrom: str, device: str = 'auto') → dict[source]

Per-axis pairwise variance and count cubes of one chromosome, before filtering.

Returns a dict with var, count, mean (all (3, B, B)), bin_ids, n_traces, chrom, axis_weight (axis_weight() of the same cube) and, for filter_normalize(), the (T, B, 3) coordinate tensor on the torch device under "coords". Pairwise differences are formed block by block, so memory stays near _BLOCK_BYTES whatever B.

uchrom.fea.arc.axis_weight(cd, chrom: str | None = None, device: str = 'auto') → ndarray[source]

ArcFISH’s axis weights of a chromosome (module docstring, step 3): per axis, each trace centred at its mean over the loci, the mean square of each locus over the traces, 1 / median over the loci, normalised to sum 1.

chrom=None averages the weights of every chromosome. device is accepted for compatibility (numpy).

uchrom.fea.arc.filter_normalize(cube: dict, k_sigma: float = 4.0, frac: float = 0.1) → dict[source]

ArcFISH’s outlier filter and normalisation by genomic distance (module docstring, step 2).

Rebuilds the (3, n_traces, n_bins, n_bins) pairwise differences block by block from cube['coords']. Output (numpy, on CPU): var (filtered variance), count (traces left per pair), norm_var, expected, raw_var, genomic_distance, plus the input’s other keys; the device tensor under "coords" is dropped.

Interval projection

Projection helpers for genomic interval features.

The functions in this module are deliberately independent of uchrom_discovery. They map canonical interval-level feature tables (one row per chrom, start, end) onto the bin axis of a ChromData (cd.bins → cd.bin_tracks), once per locus rather than once per spot. The spot-axis projection of format 1.x is kept as a deprecated helper.

uchrom.fea.project.project_interval_features_to_bins(cdata_or_bins, features: DataFrame, *, prefix: str | None = None, value_columns: Sequence[str] | None = None, into: DataFrame | None = None, overwrite: bool = False) → DataFrame[source]

Project interval-level features onto the bin axis.

Parameters:
  • cdata_or_bins – A ChromData (its bins are used) or a bin table with chrom, start, end.

  • features – DataFrame with one row per interval (matched to bins by exact chrom, start, end) and feature columns.

  • prefix – Optional namespace prefix, e.g. "seq" → seq.gc_fraction.

  • value_columns – Feature columns to project (default: all non-interval columns).

  • into – Existing bin-aligned table to extend (usually cd.bin_tracks).

  • overwrite – If False, raise when a projected column already exists in into.

Returns:

n_bins rows indexed by bin_id: the into columns plus the projected ones (NaN for bins without a feature row).

Return type:

DataFrame

uchrom.fea.project.project_interval_features_to_spots(cdata_or_spots, features: DataFrame, *, prefix: str | None = None, value_columns: Sequence[str] | None = None, into: DataFrame | None = None, overwrite: bool = False) → DataFrame[source]

Project interval-level features onto the spot axis.

Parameters:
  • cdata_or_spots – A ChromData-like object or a spot DataFrame with chrom, start, and end columns.

  • features – DataFrame with one row per interval and feature columns.

  • prefix – Optional namespace prefix for projected columns. For example, prefix="seq" maps gc_fraction to seq.gc_fraction.

  • value_columns – Feature columns to project. By default all non-interval columns are used.

  • into – Optional existing spot-aligned DataFrame to extend.

  • overwrite – If False, raise when projected columns already exist in into.

Returns:

  • DataFrame – A spot-aligned DataFrame containing the existing into columns plus projected feature columns.

  • .. deprecated:: format 2.0 – Per-locus features belong on the bin axis: use project_interval_features_to_bins() (cd.bin_tracks).

uchrom.fea.project.unique_spot_intervals(cdata_or_spots) → DataFrame[source]

Return the unique chrom/start/end intervals of the data.

For a ChromData these are its bins (in bin_id order). For a spot DataFrame the first-occurrence order is preserved.

Sequence features

Sequence-derived genomic interval features.

uchrom.fea.sequence.OPTIONAL_SEQUENCE_FEATURES = ('cpg_frequency',)

cpg_frequency is the CpG dinucleotide frequency of Dip-C (scripts/cpg.sh; Tan et al. 2018, Science 361:924), CG dinucleotides over the dinucleotides whose two bases are A/C/G/T (soft-masked bases counted), the reference of single-cell compartment values

Type:

features computed on request only (not by default)

uchrom.fea.sequence.add_sequence_features(cdata, fasta: str | Path, *, features: Sequence[str] | None = None, prefix: str = 'seq', result_key: str = 'bin_features', project: bool = True, store: bool = True, overwrite: bool = False, hash_source: bool = False, g4_pattern: str = 'G{3,}[ACGTN]{1,7}G{3,}[ACGTN]{1,7}G{3,}[ACGTN]{1,7}G{3,}') → DataFrame[source]

Compute sequence features for a ChromData object.

The canonical interval table is returned. When store=True it is also merged into cdata.results[result_key]. When project=True feature columns are projected onto cdata.bin_tracks using prefix.

uchrom.fea.sequence.compute_sequence_features(intervals: DataFrame, fasta: str | Path, *, features: Sequence[str] | None = None, g4_pattern: str = 'G{3,}[ACGTN]{1,7}G{3,}[ACGTN]{1,7}G{3,}[ACGTN]{1,7}G{3,}', missing: str = 'raise') → DataFrame[source]

Compute FASTA-derived features for genomic intervals.

Parameters:
  • intervals – DataFrame with chrom, start, and end columns.

  • fasta – FASTA file path. Plain text and .gz files are supported.

  • features – Sequence feature names. Defaults to DEFAULT_SEQUENCE_FEATURES; OPTIONAL_SEQUENCE_FEATURES (cpg_frequency: CG over the A/C/G/T dinucleotides that lie in the interval) on request.

  • g4_pattern – Regular expression used for G-quadruplex motif counting.

  • missing – "raise" to reject intervals whose chromosomes are absent from the FASTA, or "ignore" to leave their feature values as NaN.

  • to (An interval that runs past the end of its sequence (the last fixed-size bin of a chromosome) is clipped)

  • it (its features describe the sequence that exists; one that starts past the end is an error.)

Returns:

Interval columns plus requested feature columns, preserving the input row order.

Return type:

DataFrame

Annotation features

Genome annotation-derived interval features.

uchrom.fea.annotation.add_annotation_features(cdata, gtf: str | Path | DataFrame, *, features: Sequence[str] | None = None, prefix: str = 'gtf', result_key: str = 'bin_features', project: bool = True, store: bool = True, overwrite: bool = False, promoter_window: tuple[int, int] = (-2000, 500), hash_source: bool = False) → DataFrame[source]

Compute annotation features for the loci of a ChromData and write them to cd.bin_tracks.

gtf is a GTF / GFF path or a table from read_gtf(); a UCSC refGene GTF, which has transcripts but no gene rows, works as is (gene bodies are derived from the transcripts, gene_bodies()). The features (gene_body_overlap_bp / _fraction, gene_count, exon_overlap_*, promoter_overlap_* with the promoter promoter_window around the TSS, nearest_tss_distance) go to cd.bin_tracks as <prefix>.<feature> (project=True) and to cd.results[result_key] (store=True), with an entry in cd.uns["feature_registry"]; the per-locus table is returned.

uchrom.fea.annotation.compute_annotation_features(intervals: DataFrame, gtf: str | Path | DataFrame, *, features: Sequence[str] | None = None, promoter_window: tuple[int, int] = (-2000, 500), gene_feature: str = 'gene', exon_feature: str = 'exon') → DataFrame[source]

Compute GTF-derived features for genomic intervals.

The returned table preserves the input interval order and uses 0-based half-open coordinates. Gene bodies, TSSs and promoters come from the gene_feature rows; an annotation without them but with transcript rows (UCSC refGene) gets them from the transcripts (gene_bodies()), as read_gtf() does.

uchrom.fea.annotation.gene_bodies(annotations: DataFrame, *, transcript_feature: str = 'transcript') → DataFrame[source]

Gene rows from transcript rows: one per gene locus, the span of a gene’s overlapping transcripts.

The transcripts of a gene_id on one strand are sorted by start and merged while they overlap (or touch); a gene id found at several places (paralogous copies, _alt / _fix contigs) gives one row per place.

Parameters:
  • annotations (DataFrame) – An annotation table (read_gtf()) with chrom, feature, start, end, strand, gene_id.

  • transcript_feature (str) – The feature of the transcript rows.

Returns:

The columns of annotations with feature = "gene" (source = "<source>:derived" when there is a source column), sorted by gene_id, strand and start.

Return type:

DataFrame

uchrom.fea.annotation.read_gtf(path: str | Path, *, derive_genes: bool = True) → DataFrame[source]

Read a GTF/GFF-like file into a normalized annotation table.

Coordinates are converted from 1-based inclusive GTF convention to 0-based half-open intervals.

Parameters:
  • path (str or Path) – GTF / GFF file (gzipped when it ends in .gz).

  • derive_genes (bool) – When the file has transcript rows but no gene rows (UCSC refGene / ncbiRefSeq GTFs), add one gene row per gene locus — the span of the overlapping transcripts of a gene_id on one strand (gene_bodies(); a gene id found at several places gives several rows) — so that compute_annotation_features() finds gene bodies, TSSs and promoters.

Returns:

chrom, source, feature, start, end, score, strand, frame, attribute, gene_id, gene_name, gene_biotype; derived gene rows (source = "<source>:derived") come after the file’s rows.

Return type:

DataFrame

Peak features

Peak calling and peak-derived interval features.

uchrom.fea.peaks.add_peak_features(cdata, peaks: DataFrame, *, name: str = 'peak', prefix: str = 'peak', result_key: str = 'bin_features', project: bool = True, store: bool = True, overwrite: bool = False, source_peak_key: str | None = None) → DataFrame[source]

Project an existing peak table into interval and spot features.

uchrom.fea.peaks.aggregate_track_by_interval(cdata, track: str, *, agg: str = 'mean', signal_col: str = 'signal') → DataFrame[source]

Aggregate a spot-aligned track to unique genomic intervals.

Multiple spots can share the same genomic bin across cells or traces. Peak callers should operate on the genomic bin signal rather than individual spot rows, so this helper collapses duplicate intervals first.

uchrom.fea.peaks.aggregate_tracks_by_interval(cdata, tracks: Sequence[str], *, agg: str = 'mean') → DataFrame[source]

Aggregate multiple spot-aligned tracks to unique genomic intervals.

uchrom.fea.peaks.call_macs_bdgpeaks_from_bedgraph(path: str | Path, *, signal_col: str = 'score', cutoff: float = 5.0, min_length: int = 200, max_gap: int = 30, name: str = 'MACS', name_prefix: str | None = None) → DataFrame[source]

Read a bedGraph file and call MACS3 bdgpeakcall-compatible peaks.

uchrom.fea.peaks.call_macs_bdgpeaks_from_signal(signal_table: DataFrame, *, signal_col: str = 'score', cutoff: float = 5.0, min_length: int = 200, max_gap: int = 30, name: str = 'MACS', name_prefix: str | None = None) → DataFrame[source]

Call peaks using a Python port of MACS3 bdgpeakcall.

This mirrors MACS3’s bedGraphTrackI.call_peaks behavior for score tracks: regions with values at or above cutoff are merged when the intervening gap is at most max_gap bases, peaks shorter than min_length bases are discarded, and the summit follows MACS3’s tie-breaking rule. The port follows MACS3’s BSD-licensed bdgpeakcall and narrowPeak semantics without vendoring the MACS3 package at runtime.

uchrom.fea.peaks.call_macs_peaks_from_signal(signal_table: DataFrame, *, signal_col: str = 'signal', control_col: str | None = None, qvalue: float | None = 0.05, pvalue: float | None = None, genome_size: int | float | None = None, small_local_window_bins: int = 10, large_local_window_bins: int = 100, fragment_size_bins: int = 1, nolambda: bool = False, min_width_bins: int = 1, max_gap_bins: int = 0, signal_scale: float = 1.0, control_scale: float | None = None, negative: str = 'clip', name: str = 'peak') → DataFrame[source]

Call peaks with U-Chrom’s legacy dynamic Poisson approximation.

Observed binned signal is tested against a dynamic local lambda using Poisson tail probabilities, p-values are Benjamini-Hochberg adjusted, and significant adjacent bins are merged into peak intervals. Use call_macs_bdgpeaks_from_signal for the MACS3 bdgpeakcall port.

uchrom.fea.peaks.call_peaks_from_signal(signal_table: DataFrame, *, signal_col: str = 'signal', threshold: float | None = None, quantile: float = 0.95, min_width_bins: int = 1, max_gap_bins: int = 0, name: str = 'peak') → DataFrame[source]

Call simple contiguous high-signal peaks from an interval signal table.

The input table should have chrom, start, end, and signal_col. If threshold is omitted it is estimated from the requested quantile of finite signal values.

uchrom.fea.peaks.call_peaks_from_track(cdata, track: str, *, method: str = 'auto', control_track: str | None = None, agg: str = 'mean', threshold: float | None = None, quantile: float = 0.95, cutoff: float | None = None, min_length: int = 200, max_gap: int = 30, qvalue: float | None = 0.05, pvalue: float | None = None, genome_size: int | float | None = None, small_local_window_bins: int = 10, large_local_window_bins: int = 100, fragment_size_bins: int = 1, nolambda: bool = False, min_width_bins: int = 1, max_gap_bins: int = 0, signal_scale: float = 1.0, control_scale: float | None = None, negative: str = 'clip', peaks_key: str | None = None, feature_name: str | None = None, prefix: str = 'peak', result_key: str = 'bin_features', project: bool = True, store: bool = True, overwrite: bool = False) → DataFrame[source]

Aggregate a track, call peaks, and project peak features to bins.

uchrom.fea.peaks.compute_peak_features(intervals: DataFrame, peaks: DataFrame, *, name: str = 'peak') → DataFrame[source]

Compute overlap/count/distance features from peak intervals.

uchrom.fea.peaks.macs_bdgpeaks_to_narrowpeak(peaks: DataFrame, *, name: str = 'MACS', name_prefix: str | None = None, trackline: bool = False, score_column: str = 'score') → str[source]

Render MACS bdgpeakcall-compatible peaks as narrowPeak text.

uchrom.fea.peaks.read_bedgraph(path: str | Path, *, signal_col: str = 'score') → DataFrame[source]

Read a MACS-compatible bedGraph score track into an interval table.

Feature registry

Feature registry helpers for ChromData.uns.

uchrom.fea.registry.append_feature_registry_entry(cdata, entry: Mapping[str, Any], *, key: str = 'feature_registry') → dict[str, Any][source]

Append a provenance record to cdata.uns[key].

The registry is stored as a list of JSON-like dicts so it round-trips through the existing uns serializer.

uchrom.fea.registry.file_sha256(path: str | Path, *, chunk_size: int = 1048576) → str[source]

Return the SHA-256 digest for a local source file.

uchrom.fea.registry.table_provenance(table, *, value_columns=None) → dict[str, Any][source]

Small JSON-friendly summary for an enrichment output table.