uchrom.strc.loop¶
- class uchrom.strc.loop.HiccupsParams(p: int | None = None, w: int | None = None, max_dist: int = 10000000, fdr: float = 0.1, ignore_diags: int = 2, lambda_base: float = 1.2599210498948732, pvalue: str = 'hiccups', cluster_radius: int | None = None, filter: bool = True, enrichment_vh: float = 1.5, enrichment_d_and_ll: float = 1.75, enrichment_d_or_ll: float = 2.0, fdr_orphan: float = 0.02)[source]¶
Bases:
objectKnobs of
call_loops_hiccups()(defaults: Rao et al. 2014 / cooltoolsdots).- Variables:
w (p,) – Half-widths (bins) of the peak and of the window of the kernels.
None: Rao 2014’s choice for the resolution —p=4, w=7at 4-8 kb,p=2, w=5at 8-18 kb,p=1, w=3at 18-28 kb.max_dist (int) – Largest separation of a tested pixel, bp (pixels with
j - i < max_dist / binsize; cooltools’max_loci_separation).fdr (float) – Benjamini–Hochberg FDR within each λ-chunk.
ignore_diags (int) – Diagonals whose expected is undefined (cooltools
expected_cis(ignore_diags=2)); kernels may not touch them.lambda_base (float) – Ratio of successive λ-chunk edges (
2^(1/3)).pvalue ({"hiccups", "cooltools"}) –
"hiccups":P(X ≥ obs)(Juicer HiCCUPS);"cooltools":P(X > obs)(cooltoolsdots).cluster_radius (int or None) – Radius of the greedy clustering, bp;
None: 20 kb below 18 kb resolution, 50 kb above (Juicer).filter (bool) – Apply the Rao 2014 enrichment / singleton filter to the cluster summits.
enrichment_d_or_ll (enrichment_vh, enrichment_d_and_ll,) – Summit counts must exceed
enrichment_vh× the vertical and horizontal expecteds,enrichment_d_and_ll× the donut and lower-left ones, andenrichment_d_or_ll× one of them.fdr_orphan (float) – A single-pixel cluster needs the sum of its four q-values ≤ this.
- class uchrom.strc.loop.LoopCallerParams(cut_lo: float = 100000.0, cut_up: float = 1000000.0, inner_cut: float = 25000.0, outer_cut: float = 50000.0, fdr_cutoff: float = 0.1, pval_cutoff: float = 1e-05, gap: float = 50000.0, contact_sep: float = 25000.0, k_sigma: float = 4.0, frac: float = 0.1, min_cluster_size: int = 1)[source]¶
Bases:
objectRuntime parameters for
call_loops_axiswise_f()(ArcFISH’sLoopCallerdefaults; distances in bp).inner_cutandcontact_separe fixed at 25 kb in the authors’ code;min_cluster_size(U-Chrom, default 1 = off) drops clusters with fewer candidate pairs.k_sigma/frac: the outlier filter and LOWESS span ofuchrom.fea.arc.filter_normalize().Before U-Chrom 0.3 (2026-10) the background ring was rounded to bins, untestable axes entered the combination with
p = 1, summits were chosen by a weighted log-p and the contact cutoff used pairs one median bin apart; results differ from the authors’ (docs/source/reference/changelog.md).
- class uchrom.strc.loop.MustacheParams(sigma0: float = 1.6, octaves: int = 2, scales: int = 10, fdr: float = 0.1, sparsity: float = 0.88, sparsity_outer: float = 0.6, max_dist: int | None = None, min_diag: int = 4, norm_window: int = 2000000, min_window_pixels: int = 30, enrichment: float = 2.0, min_pixels: int = 10000)[source]¶
Bases:
objectParameters of
call_loops_mustache()(defaults: the reference’s, tuned for 5 kb maps).- Variables:
sigma0 (float) – Smallest Gaussian of the first octave (pixels); 1.6 in the paper.
octaves (int) – Octaves (each doubles sigma); 2.
scales (int) – Gaussian levels per octave (DoG layers
scales + 1); 10.fdr (float) – Benjamini-Hochberg threshold (the reference’s
-pt).sparsity (float) – Least share of observed pixels around a candidate (
-st); lower it for sparse maps (0.8).sparsity_outer (float) – The same in a window twice as wide.
max_dist (int, optional) – Largest anchor separation (bp). Default: the reference’s rule, 2 Mb clamped to
[200, 2000]bins (2 Mb at 5 / 10 kb, 5 Mb at 25 kb).min_diag (int) – Diagonals
j - i <= min_diagare not analysed (bins).norm_window (int) – Width of the sliding window of the per-diagonal normalisation (bp).
min_window_pixels (int) – Fewer present pixels in the window: the diagonal-wide mean / sd are used.
enrichment (float) – A loop’s z-score must exceed this multiple of its diagonal’s mean non-zero z-score.
min_pixels (int) – Chromosomes with fewer analysable pixels give no loops (the reference applies 10,000 per block).
- class uchrom.strc.loop.SnapHiCParams(rp: float = 0.05, window: int | str | None = None, step: int | None = None, min_dist: int = 100000, max_dist: int = 2000000, buffer: int = 50000, min_sep: int = 2, trim: float = 0.01, outlier: float = 1.96, inner: int = 2, outer: int = 5, fdr: float = 0.1, tstat: float = 3.0, min_outlier_frac: float = 0.1, circle: float = 1.33, donut: float = 1.33, lower_left: float = 1.33, horizontal: float = 1.2, vertical: float = 1.2, clustering_gap: int = 1, summit_gap: int = 20000, batch: int = 0, sliding_window_holes: bool = False)[source]¶
Bases:
objectKnobs of
call_loops_snaphic()(defaults: SnapHiC v0.2’s).- Variables:
rp (float) – Restart probability of the random walk (
--alpha).step (window,) – The RWR of whole chromosomes (
None, the published SnapHiC and the default: its calls match the paper’s best) or of sliding windows, bp ("auto"= SnapHiC2’s 10-100 Mb rule; much faster, more loops at lower precision — see the module docstring).max_dist (min_dist,) – Separation of the candidate pixels, bp (
--candidate-lower-distance,--dist). The paper reports loops in 100 kb - 1 Mb; the software’s default upper end is 2 Mb.buffer (int) – bp: diagonals imputed beyond
max_distand bins left out at the chromosome ends (50 kb).min_sep (int) – Contacts closer than this many bins are left out before the imputation (2: neighbouring bins).
trim (float) – Share of each diagonal’s largest values left out of its z-score mean / sd.
outlier (float) – z-score above which a cell counts as an outlier at a pixel (1.96).
outer (inner,) – Local background: the
(2 outer + 1)^2square around a pixel minus the(2 inner + 1)^2one, and the ring of the neighbourhood filters (--local-lower/upper-limit,--postproc-gap-small/large).min_outlier_frac (fdr, tstat,) – Candidates: FDR (per distance) below
fdr, t-statistic abovetstat, more thanmin_outlier_fracof the cells outliers.vertical (circle, donut, lower_left, horizontal,) –
outlier_countmust exceed these multiples of its mean over each neighbourhood.clustering_gap (int) – Bins: density radius
sqrt(2) * gapof the clustering.summit_gap (int) – bp: further summits of a cluster lie farther than this from the previous ones (in either anchor).
batch (int) – Cells imputed at once by the native path (0: one per thread); memory ~3 bands per cell.
sliding_window_holes (bool) – Reproduce SnapHiC v0.2’s sliding windows exactly, including the pixels they never set (left at 0: sums
i + j = (2k + 1) stepandi + j <= step). Only to compare with the authors’ code.
- uchrom.strc.loop.call_loops_axiswise_f(cd, *args, chrom=None, trace_ids=None, cells=None, params: LoopCallerParams | None = None, device: str = 'auto', key_added: str | None = UNSET, copy: bool = False, verbose: bool = False, streaming: bool | None = None, batch='auto', memory_budget=None, store=UNSET, result_key=UNSET)[source]¶
ArcFISH’s axis-wise F-test loop caller (chromatin tracing; module docstring).
- Parameters:
cd (
uchrom.ChromData) – Tracing data. Must containtrace_idinspots.chrom (str, sequence of str, or None) – Chromosome(s) — matched against
cd.spots['chrom'].None(default) calls every chromosome and merges the tables.trace_ids (sequence, optional) – Restrict the population to these traces / cells.
cells (sequence, optional) – Restrict the population to these traces / cells.
params (LoopCallerParams, optional) – Override any default.
device (str) –
'auto' | 'cpu' | 'cuda' | 'mps'— passed to GPU-friendly preprocessing.key_added (str or None) –
cd.resultskey (default"loops.axiswise_f");Nonedoes not store.copy (bool) –
True→ return a new ChromData holding the result.streaming (bool, optional) – Compute the axis-variance cube by streaming over the traces (
uchrom.fea.arc_stream.axis_cube_streaming(): exact medians per row band, memoryO(n_bins²)instead ofO(n_traces × n_bins²)). Default:Truefor a backedChromData. Results equal the in-memory path up to floating-point rounding of the variance sums.batch – Traces per batch (
"auto") and working-memory budget of the streaming path (defaultuchrom.settings.memory_budget).memory_budget – Traces per batch (
"auto") and working-memory budget of the streaming path (defaultuchrom.settings.memory_budget).
- Returns:
One row per called loop (a summit with
pval < pval_cutoff): BEDPE-stylechrom1 … end2plusstat, pval, fdr, score(-log10 pval),cluster_size(candidate pairs of its cluster),contact_freqandsummit_i, summit_j(per-chromosome locus indices). The test matrices arearcfish_loop_matrices().- Return type:
DataFrame (
copy=False) or ChromData (copy=True)
Notes
Deprecated 1.x forms (positional
chrom,store=,result_key=) still work with aDeprecationWarningand default to the 1.x key"loops".
- uchrom.strc.loop.call_loops_hiccups(cd, *, contacts=None, chrom=None, resolution: None | int | Sequence[int] = None, params: HiccupsParams | None = None, key_added: str | None = 'loops.hiccups', copy: bool = False, timing: dict | None = None)[source]¶
Loops of a Hi-C map by local enrichment: HiCCUPS (Rao et al. 2014; cooltools
dots, Open2C 2024).Every pixel of the band
0 < j - i < max_distis tested (Poisson) against four locally adjusted expected counts — from the donut, vertical, horizontal and lower-left neighbourhoods — with a Benjamini–Hochberg FDR per λ-chunk; pixels enriched for all four are clustered greedily, the brightest pixel of each cluster is the loop, and the Rao 2014 enrichment filter is applied. See the module docstring for the details and the deviations from cooltools.- Parameters:
cd (ChromData) – Holds the link (
cd.link_cool(path, key=...)) and receives the result.contacts (str, cooler.Cooler, or a list of them) – Key of a linked map (
None: the only one), the path of a.cool/.mcool, or an open cooler. The map must be balanced (weight;uchrom.fea.rebin_map()balances). A list = one map per resolution (e.g.["bulk", "bulk_10kb", "bulk_25kb"]): called at each, merged (merge_resolutions()).chrom (str, sequence of str, or None) –
None: the chromosomes ofcdthat the map has (every map chromosome whencdhas no spots). The FDR is computed over all of them together.resolution (int or sequence of int, optional) – The level(s) of an
.mcool; several → called at each and merged.params (HiccupsParams, optional)
key_added (str or None) –
cd.results/cd.intervalskey (default"loops.hiccups");Nonedoes not store.copy (bool) –
True→ return a new ChromData holding the result.timing (dict, optional) – Filled with the seconds of each step (profiling).
- Returns:
A
pairtable, one row per loop (the summit pixel):chrom1, start1, end1, chrom2, start2, end2,score(-log10pval),pval(largest Poisson p-value of the four kernels, at the λ-chunk’s upper edge),fdr(largest q-value),count(raw),exp_<kernel>(locally adjusted expected, raw counts),fdr_<kernel>,enrichment(count / donut expected),cluster_size,centroid1/2andradiusof the cluster (bp),resolution,summit_i/j(bins of the chromosome).- Return type:
DataFrame (
copy=False) or ChromData (copy=True)
Examples
>>> hic = ds.load("rao2014_imr90_chr21") >>> rebin_map(hic, "bulk", resolution=10_000) >>> loops = call_loops_hiccups(hic, contacts="bulk_10kb")
- uchrom.strc.loop.call_loops_mustache(cd, *, contacts: str | None = None, chrom=None, resolution: int | None = None, balance: bool = True, params: MustacheParams | None = None, key_added: str | None = 'loops.mustache', copy: bool = False, tile: int = 256, verbose: bool = False)[source]¶
Loops of a Hi-C map by multi-scale blob detection (Mustache).
Each diagonal of the balanced map is turned into local z-scores; the band near the diagonal is smoothed with Gaussians of growing width, and loops are the pixels where the difference of Gaussians is a maximum in space and across scales, significant against an exponential fit of the responses (Benjamini-Hochberg), in a densely observed neighbourhood and enriched over their diagonal (Roayaei Ardakany et al. 2020; steps and deviations from the reference code in the module docstring). The map is read and processed as a band (memory linear in the chromosome length).
- Parameters:
cd (ChromData, str or cooler.Cooler) – A
ChromDatawith the map linked (cd.link_cool), or the path of a.cool/.mcool/ acooler.Cooler(then nothing is stored:key_addedis ignored).contacts (str, optional) – Key of the linked map (
None: the only one) or the path of a map.chrom (str, sequence of str, or None) – Chromosome(s), as named in the map.
None: the chromosomes ofcd.spotsthe map has, or every chromosome of the map (Hi-C-only data); chromosomes with too few pixels give no loops.resolution (int, optional) – The level of an
.mcool; checked against a.cool.balance (bool) – Use the balancing weights (
weightcolumn; raw counts with a warning when there are none).params (MustacheParams, optional)
key_added (str or None) –
cd.results/cd.intervalskey (default"loops.mustache");Nonedoes not store.copy (bool) –
True: return a new ChromData holding the result.tile (int) – Rows of the map processed at once (memory / speed only; results do not depend on it).
verbose (bool) – Print counts and timings per chromosome.
- Returns:
A
pairinterval table, one row per loop:chrom1, start1, end1, chrom2, start2, end2(the two anchor bins),score(-log10 pval),pval,fdr(Benjamini-Hochberg),scale(detection sigma, pixels),response(difference of Gaussians),cluster_size(candidate pixels merged) andsummit_i/summit_j(bin indices within the chromosome).- Return type:
DataFrame (
copy=False) or ChromData (copy=True)
References
Roayaei Ardakany A, Gezer HT, Lonardi S, Ay F (2020). Mustache: multi-scale detection of chromatin loops from Hi-C and Micro-C maps using scale-space representation. Genome Biology 21:256.
Examples
>>> hic = ds.load("rao2014_imr90_chr21") >>> rebin_map(hic, "bulk", resolution=10_000) >>> loops = call_loops_mustache(hic, contacts="bulk_10kb")
- uchrom.strc.loop.call_loops_snaphic(cd, *, contacts: str = 'per_cell', cells: Sequence | None = None, chrom: None | str | Sequence[str] = None, resolution: int | None = None, params: SnapHiCParams | None = None, exclude=None, key_added: str | None = 'loops.snaphic', copy: bool = False, backend: str | None = None, n_threads: int = 0, timing: dict | None = None)[source]¶
Loops from single-cell Hi-C maps, tested across cells: SnapHiC (Yu et al. 2021; SnapHiC2 windows, Li et al. 2022). See the module docstring for the steps and the deviations from the authors’ code.
- Parameters:
cd (ChromData) – With per-cell maps linked (
cd.link_scool) or embedded in its atlas store.contacts (str) – Key of the per-cell maps (or the path of a
.scoolwhose cells are named by cell id).cells (sequence, optional) – Cells to use (default: every cell of
cd.cells).chrom (str or sequence, optional) – Chromosomes (default: the autosomes of the maps, as SnapHiC).
resolution (int, optional) – Bin size the maps must have (SnapHiC: 10 kb); default: the maps’ own.
params (SnapHiCParams, optional)
exclude (DataFrame or path, optional) – Bins excluded from the loop anchors (
chrom, start[, end]; a BED file): SnapHiC removes 10-kb bins of mappability <= 0.8 and the ENCODE blacklist (itsext/<genome>_filter_regions.txt).key_added (str or None) –
cd.results/cd.intervalskey (None: not stored); the clustered candidates go tocd.results[key_added + ".candidates"].copy (bool) – Return a new
ChromDataholding the result.backend ({"auto", "native", "numpy"}, optional) – Steps 1-3 (default: the module’s
BACKEND).n_threads (int) – Threads of the native path (0: all).
timing (dict, optional) – Filled with seconds per step and the backend.
- Returns:
A
pairtable, one row per loop summit:chrom1, start1, end1, chrom2, start2, end2,score(-log10fdr_dist),outlier_count(cells with z > 1.96),pvalue,tstat(paired t-test against the local background),fdr_dist(BH among the pixels at the same distance),case_avg/control_avg(mean z-score of the pixel / its background), the neighbourhood meanscircle, donut, horizontal, vertical, lower_leftofoutlier_count,cluster_size,neg_log10_fdr(of the cluster).- Return type:
DataFrame (
copy=False) or ChromData (copy=True)
- uchrom.strc.loop.hiccups_pixels(clr, chroms: Sequence[str], params: HiccupsParams | None = None, *, timing: dict | None = None) Tuple[DataFrame, dict][source]¶
The enriched pixels of a balanced map (steps 1-2 of
call_loops_hiccups(): before clustering).- Parameters:
clr (cooler.Cooler) – A balanced map (
weightcolumn).chroms (sequence of str) – Chromosomes scored together (one genome-wide FDR over all of them).
params (HiccupsParams, optional)
timing (dict, optional) – Filled with seconds per step (
read_s,kernel_sums_s,histogram_s,thresholds_s; with the native kernelsexpected_sandnative_score_s) and thebackendused.
- Returns:
pixels (DataFrame) –
chrom, i, j(bins of the chromosome),start1, start2,count,exp_<kernel>(λ, raw counts),pval_<kernel>andfdr_<kernel>(q-value) for the four kernels.info (dict) –
p, w, max_diag, n_tested(pixels scored),thresholds(per kernel: the smallest passing count of each λ-chunk).
- uchrom.strc.loop.match_loops(reference: DataFrame, calls: DataFrame, *, tol: int = 25000) Series[source]¶
Which loops of
referencewere called: both anchors of a call withintolbp of theirs.- Parameters:
reference (DataFrame) – BEDPE-like loop tables with
start1andstart2(anchor starts, bp). When both have a chromosome column (chrom1orchrom) a match must also be on the same chromosome.calls (DataFrame) – BEDPE-like loop tables with
start1andstart2(anchor starts, bp). When both have a chromosome column (chrom1orchrom) a match must also be on the same chromosome.tol (int) – Largest distance between anchor starts, bp (default one 25-kb bin).
- Return type:
Series of bool, indexed like
reference.
Examples
>>> ref = pd.DataFrame({"start1": [50_300_000], "start2": [50_525_000]}) >>> match_loops(ref, cd.intervals["loops.axiswise_f"])
- uchrom.strc.loop.merge_resolutions(calls: Dict[int, DataFrame]) DataFrame[source]¶
Merge loop calls made at several resolutions as Rao et al. 2014 (Juicer
mergeAllResolutions).5 kb + 10 kb: the 5-kb loops with a 10-kb loop within 20 kb, the 10-kb loops without a 5-kb loop within 20 kb, and the 5-kb loops closer than 110 kb to the diagonal or with more than 100 contacts. 25 kb: added when no loop of the merged list lies within 50 kb. Other resolutions (not 5 / 10 / 25 kb), from the finest up: a coarser loop is added when no merged loop lies within twice its bin size. Distances are Euclidean between anchor starts.
- Parameters:
calls (dict) – Resolution (bp) → loop table (
chrom1, start1, start2, count, …).- Return type:
DataFrame with the rows kept (their
resolutioncolumn says where each was called).
- uchrom.strc.loop.score_loops(cd, loops: str | DataFrame = 'loops.axiswise_f', *, chrom=None, trace_ids=None, cells=None) DataFrame[source]¶
How much closer the two anchors of each loop are than other locus pairs at the same genomic separation.
For each loop, the 3-D distance of its two anchor loci in every trace that detected both, against the distances of every other pair of loci of the chromosome exactly as far apart (same start-to-start separation), pooled over the traces. A loop called from imaging should have
ratio< 1.- Parameters:
cd (ChromData) – The traces (in memory or backed; one chromosome is read at a time).
loops (str or DataFrame) – A key of
cd.results/cd.intervals(default"loops.axiswise_f") or a loop table withchrom1(orchrom),start1,start2; anchors are matched to loci by their start.chrom (str or sequence of str, optional) – Score only the loops on these chromosomes.
trace_ids (sequence, optional) – Use only these traces / cells.
cells (sequence, optional) – Use only these traces / cells.
- Returns:
The loop table with
n_traces(traces that detected both anchors),anchor_distance(their median distance),n_background(distances of the other pairs),background_distance(their median) andratio(= anchor / background). Distances in the unit ofcd.coords.- Return type:
DataFrame
- class uchrom.strc.loop.axiswise_f.LoopCallerParams(cut_lo: float = 100000.0, cut_up: float = 1000000.0, inner_cut: float = 25000.0, outer_cut: float = 50000.0, fdr_cutoff: float = 0.1, pval_cutoff: float = 1e-05, gap: float = 50000.0, contact_sep: float = 25000.0, k_sigma: float = 4.0, frac: float = 0.1, min_cluster_size: int = 1)[source]¶
Bases:
objectRuntime parameters for
call_loops_axiswise_f()(ArcFISH’sLoopCallerdefaults; distances in bp).inner_cutandcontact_separe fixed at 25 kb in the authors’ code;min_cluster_size(U-Chrom, default 1 = off) drops clusters with fewer candidate pairs.k_sigma/frac: the outlier filter and LOWESS span ofuchrom.fea.arc.filter_normalize().Before U-Chrom 0.3 (2026-10) the background ring was rounded to bins, untestable axes entered the combination with
p = 1, summits were chosen by a weighted log-p and the contact cutoff used pairs one median bin apart; results differ from the authors’ (docs/source/reference/changelog.md).
- uchrom.strc.loop.axiswise_f.call_loops_axiswise_f(cd, *args, chrom=None, trace_ids=None, cells=None, params: LoopCallerParams | None = None, device: str = 'auto', key_added: str | None = UNSET, copy: bool = False, verbose: bool = False, streaming: bool | None = None, batch='auto', memory_budget=None, store=UNSET, result_key=UNSET)[source]¶
ArcFISH’s axis-wise F-test loop caller (chromatin tracing; module docstring).
- Parameters:
cd (
uchrom.ChromData) – Tracing data. Must containtrace_idinspots.chrom (str, sequence of str, or None) – Chromosome(s) — matched against
cd.spots['chrom'].None(default) calls every chromosome and merges the tables.trace_ids (sequence, optional) – Restrict the population to these traces / cells.
cells (sequence, optional) – Restrict the population to these traces / cells.
params (LoopCallerParams, optional) – Override any default.
device (str) –
'auto' | 'cpu' | 'cuda' | 'mps'— passed to GPU-friendly preprocessing.key_added (str or None) –
cd.resultskey (default"loops.axiswise_f");Nonedoes not store.copy (bool) –
True→ return a new ChromData holding the result.streaming (bool, optional) – Compute the axis-variance cube by streaming over the traces (
uchrom.fea.arc_stream.axis_cube_streaming(): exact medians per row band, memoryO(n_bins²)instead ofO(n_traces × n_bins²)). Default:Truefor a backedChromData. Results equal the in-memory path up to floating-point rounding of the variance sums.batch – Traces per batch (
"auto") and working-memory budget of the streaming path (defaultuchrom.settings.memory_budget).memory_budget – Traces per batch (
"auto") and working-memory budget of the streaming path (defaultuchrom.settings.memory_budget).
- Returns:
One row per called loop (a summit with
pval < pval_cutoff): BEDPE-stylechrom1 … end2plusstat, pval, fdr, score(-log10 pval),cluster_size(candidate pairs of its cluster),contact_freqandsummit_i, summit_j(per-chromosome locus indices). The test matrices arearcfish_loop_matrices().- Return type:
DataFrame (
copy=False) or ChromData (copy=True)
Notes
Deprecated 1.x forms (positional
chrom,store=,result_key=) still work with aDeprecationWarningand default to the 1.x key"loops".
HiCCUPS (Hi-C maps)¶
Loops of a linked contact map by local enrichment (Rao et al. 2014, in cooltools’ formulation).
- class uchrom.strc.loop.hiccups.HiccupsParams(p: int | None = None, w: int | None = None, max_dist: int = 10000000, fdr: float = 0.1, ignore_diags: int = 2, lambda_base: float = 1.2599210498948732, pvalue: str = 'hiccups', cluster_radius: int | None = None, filter: bool = True, enrichment_vh: float = 1.5, enrichment_d_and_ll: float = 1.75, enrichment_d_or_ll: float = 2.0, fdr_orphan: float = 0.02)[source]¶
Bases:
objectKnobs of
call_loops_hiccups()(defaults: Rao et al. 2014 / cooltoolsdots).- Variables:
w (p,) – Half-widths (bins) of the peak and of the window of the kernels.
None: Rao 2014’s choice for the resolution —p=4, w=7at 4-8 kb,p=2, w=5at 8-18 kb,p=1, w=3at 18-28 kb.max_dist (int) – Largest separation of a tested pixel, bp (pixels with
j - i < max_dist / binsize; cooltools’max_loci_separation).fdr (float) – Benjamini–Hochberg FDR within each λ-chunk.
ignore_diags (int) – Diagonals whose expected is undefined (cooltools
expected_cis(ignore_diags=2)); kernels may not touch them.lambda_base (float) – Ratio of successive λ-chunk edges (
2^(1/3)).pvalue ({"hiccups", "cooltools"}) –
"hiccups":P(X ≥ obs)(Juicer HiCCUPS);"cooltools":P(X > obs)(cooltoolsdots).cluster_radius (int or None) – Radius of the greedy clustering, bp;
None: 20 kb below 18 kb resolution, 50 kb above (Juicer).filter (bool) – Apply the Rao 2014 enrichment / singleton filter to the cluster summits.
enrichment_d_or_ll (enrichment_vh, enrichment_d_and_ll,) – Summit counts must exceed
enrichment_vh× the vertical and horizontal expecteds,enrichment_d_and_ll× the donut and lower-left ones, andenrichment_d_or_ll× one of them.fdr_orphan (float) – A single-pixel cluster needs the sum of its four q-values ≤ this.
- uchrom.strc.loop.hiccups.call_loops_hiccups(cd, *, contacts=None, chrom=None, resolution: None | int | Sequence[int] = None, params: HiccupsParams | None = None, key_added: str | None = 'loops.hiccups', copy: bool = False, timing: dict | None = None)[source]¶
Loops of a Hi-C map by local enrichment: HiCCUPS (Rao et al. 2014; cooltools
dots, Open2C 2024).Every pixel of the band
0 < j - i < max_distis tested (Poisson) against four locally adjusted expected counts — from the donut, vertical, horizontal and lower-left neighbourhoods — with a Benjamini–Hochberg FDR per λ-chunk; pixels enriched for all four are clustered greedily, the brightest pixel of each cluster is the loop, and the Rao 2014 enrichment filter is applied. See the module docstring for the details and the deviations from cooltools.- Parameters:
cd (ChromData) – Holds the link (
cd.link_cool(path, key=...)) and receives the result.contacts (str, cooler.Cooler, or a list of them) – Key of a linked map (
None: the only one), the path of a.cool/.mcool, or an open cooler. The map must be balanced (weight;uchrom.fea.rebin_map()balances). A list = one map per resolution (e.g.["bulk", "bulk_10kb", "bulk_25kb"]): called at each, merged (merge_resolutions()).chrom (str, sequence of str, or None) –
None: the chromosomes ofcdthat the map has (every map chromosome whencdhas no spots). The FDR is computed over all of them together.resolution (int or sequence of int, optional) – The level(s) of an
.mcool; several → called at each and merged.params (HiccupsParams, optional)
key_added (str or None) –
cd.results/cd.intervalskey (default"loops.hiccups");Nonedoes not store.copy (bool) –
True→ return a new ChromData holding the result.timing (dict, optional) – Filled with the seconds of each step (profiling).
- Returns:
A
pairtable, one row per loop (the summit pixel):chrom1, start1, end1, chrom2, start2, end2,score(-log10pval),pval(largest Poisson p-value of the four kernels, at the λ-chunk’s upper edge),fdr(largest q-value),count(raw),exp_<kernel>(locally adjusted expected, raw counts),fdr_<kernel>,enrichment(count / donut expected),cluster_size,centroid1/2andradiusof the cluster (bp),resolution,summit_i/j(bins of the chromosome).- Return type:
DataFrame (
copy=False) or ChromData (copy=True)
Examples
>>> hic = ds.load("rao2014_imr90_chr21") >>> rebin_map(hic, "bulk", resolution=10_000) >>> loops = call_loops_hiccups(hic, contacts="bulk_10kb")
- uchrom.strc.loop.hiccups.merge_resolutions(calls: Dict[int, DataFrame]) DataFrame[source]¶
Merge loop calls made at several resolutions as Rao et al. 2014 (Juicer
mergeAllResolutions).5 kb + 10 kb: the 5-kb loops with a 10-kb loop within 20 kb, the 10-kb loops without a 5-kb loop within 20 kb, and the 5-kb loops closer than 110 kb to the diagonal or with more than 100 contacts. 25 kb: added when no loop of the merged list lies within 50 kb. Other resolutions (not 5 / 10 / 25 kb), from the finest up: a coarser loop is added when no merged loop lies within twice its bin size. Distances are Euclidean between anchor starts.
- Parameters:
calls (dict) – Resolution (bp) → loop table (
chrom1, start1, start2, count, …).- Return type:
DataFrame with the rows kept (their
resolutioncolumn says where each was called).
- uchrom.strc.loop.hiccups.hiccups_pixels(clr, chroms: Sequence[str], params: HiccupsParams | None = None, *, timing: dict | None = None) Tuple[DataFrame, dict][source]¶
The enriched pixels of a balanced map (steps 1-2 of
call_loops_hiccups(): before clustering).- Parameters:
clr (cooler.Cooler) – A balanced map (
weightcolumn).chroms (sequence of str) – Chromosomes scored together (one genome-wide FDR over all of them).
params (HiccupsParams, optional)
timing (dict, optional) – Filled with seconds per step (
read_s,kernel_sums_s,histogram_s,thresholds_s; with the native kernelsexpected_sandnative_score_s) and thebackendused.
- Returns:
pixels (DataFrame) –
chrom, i, j(bins of the chromosome),start1, start2,count,exp_<kernel>(λ, raw counts),pval_<kernel>andfdr_<kernel>(q-value) for the four kernels.info (dict) –
p, w, max_diag, n_tested(pixels scored),thresholds(per kernel: the smallest passing count of each λ-chunk).
Mustache (Hi-C maps)¶
Loops of a linked contact map by scale-space blob detection (Roayaei Ardakany et al. 2020).
- class uchrom.strc.loop.mustache.MustacheParams(sigma0: float = 1.6, octaves: int = 2, scales: int = 10, fdr: float = 0.1, sparsity: float = 0.88, sparsity_outer: float = 0.6, max_dist: int | None = None, min_diag: int = 4, norm_window: int = 2000000, min_window_pixels: int = 30, enrichment: float = 2.0, min_pixels: int = 10000)[source]¶
Bases:
objectParameters of
call_loops_mustache()(defaults: the reference’s, tuned for 5 kb maps).- Variables:
sigma0 (float) – Smallest Gaussian of the first octave (pixels); 1.6 in the paper.
octaves (int) – Octaves (each doubles sigma); 2.
scales (int) – Gaussian levels per octave (DoG layers
scales + 1); 10.fdr (float) – Benjamini-Hochberg threshold (the reference’s
-pt).sparsity (float) – Least share of observed pixels around a candidate (
-st); lower it for sparse maps (0.8).sparsity_outer (float) – The same in a window twice as wide.
max_dist (int, optional) – Largest anchor separation (bp). Default: the reference’s rule, 2 Mb clamped to
[200, 2000]bins (2 Mb at 5 / 10 kb, 5 Mb at 25 kb).min_diag (int) – Diagonals
j - i <= min_diagare not analysed (bins).norm_window (int) – Width of the sliding window of the per-diagonal normalisation (bp).
min_window_pixels (int) – Fewer present pixels in the window: the diagonal-wide mean / sd are used.
enrichment (float) – A loop’s z-score must exceed this multiple of its diagonal’s mean non-zero z-score.
min_pixels (int) – Chromosomes with fewer analysable pixels give no loops (the reference applies 10,000 per block).
- uchrom.strc.loop.mustache.call_loops_mustache(cd, *, contacts: str | None = None, chrom=None, resolution: int | None = None, balance: bool = True, params: MustacheParams | None = None, key_added: str | None = 'loops.mustache', copy: bool = False, tile: int = 256, verbose: bool = False)[source]¶
Loops of a Hi-C map by multi-scale blob detection (Mustache).
Each diagonal of the balanced map is turned into local z-scores; the band near the diagonal is smoothed with Gaussians of growing width, and loops are the pixels where the difference of Gaussians is a maximum in space and across scales, significant against an exponential fit of the responses (Benjamini-Hochberg), in a densely observed neighbourhood and enriched over their diagonal (Roayaei Ardakany et al. 2020; steps and deviations from the reference code in the module docstring). The map is read and processed as a band (memory linear in the chromosome length).
- Parameters:
cd (ChromData, str or cooler.Cooler) – A
ChromDatawith the map linked (cd.link_cool), or the path of a.cool/.mcool/ acooler.Cooler(then nothing is stored:key_addedis ignored).contacts (str, optional) – Key of the linked map (
None: the only one) or the path of a map.chrom (str, sequence of str, or None) – Chromosome(s), as named in the map.
None: the chromosomes ofcd.spotsthe map has, or every chromosome of the map (Hi-C-only data); chromosomes with too few pixels give no loops.resolution (int, optional) – The level of an
.mcool; checked against a.cool.balance (bool) – Use the balancing weights (
weightcolumn; raw counts with a warning when there are none).params (MustacheParams, optional)
key_added (str or None) –
cd.results/cd.intervalskey (default"loops.mustache");Nonedoes not store.copy (bool) –
True: return a new ChromData holding the result.tile (int) – Rows of the map processed at once (memory / speed only; results do not depend on it).
verbose (bool) – Print counts and timings per chromosome.
- Returns:
A
pairinterval table, one row per loop:chrom1, start1, end1, chrom2, start2, end2(the two anchor bins),score(-log10 pval),pval,fdr(Benjamini-Hochberg),scale(detection sigma, pixels),response(difference of Gaussians),cluster_size(candidate pixels merged) andsummit_i/summit_j(bin indices within the chromosome).- Return type:
DataFrame (
copy=False) or ChromData (copy=True)
References
Roayaei Ardakany A, Gezer HT, Lonardi S, Ay F (2020). Mustache: multi-scale detection of chromatin loops from Hi-C and Micro-C maps using scale-space representation. Genome Biology 21:256.
Examples
>>> hic = ds.load("rao2014_imr90_chr21") >>> rebin_map(hic, "bulk", resolution=10_000) >>> loops = call_loops_mustache(hic, contacts="bulk_10kb")
SnapHiC (single cells)¶
Loops called across single cells without pooling them: each cell’s map imputed by a random walk with restart, then a paired test of every candidate pixel against its local background over the cells (Yu et al. 2021).
- class uchrom.strc.loop.snaphic.SnapHiCParams(rp: float = 0.05, window: int | str | None = None, step: int | None = None, min_dist: int = 100000, max_dist: int = 2000000, buffer: int = 50000, min_sep: int = 2, trim: float = 0.01, outlier: float = 1.96, inner: int = 2, outer: int = 5, fdr: float = 0.1, tstat: float = 3.0, min_outlier_frac: float = 0.1, circle: float = 1.33, donut: float = 1.33, lower_left: float = 1.33, horizontal: float = 1.2, vertical: float = 1.2, clustering_gap: int = 1, summit_gap: int = 20000, batch: int = 0, sliding_window_holes: bool = False)[source]¶
Bases:
objectKnobs of
call_loops_snaphic()(defaults: SnapHiC v0.2’s).- Variables:
rp (float) – Restart probability of the random walk (
--alpha).step (window,) – The RWR of whole chromosomes (
None, the published SnapHiC and the default: its calls match the paper’s best) or of sliding windows, bp ("auto"= SnapHiC2’s 10-100 Mb rule; much faster, more loops at lower precision — see the module docstring).max_dist (min_dist,) – Separation of the candidate pixels, bp (
--candidate-lower-distance,--dist). The paper reports loops in 100 kb - 1 Mb; the software’s default upper end is 2 Mb.buffer (int) – bp: diagonals imputed beyond
max_distand bins left out at the chromosome ends (50 kb).min_sep (int) – Contacts closer than this many bins are left out before the imputation (2: neighbouring bins).
trim (float) – Share of each diagonal’s largest values left out of its z-score mean / sd.
outlier (float) – z-score above which a cell counts as an outlier at a pixel (1.96).
outer (inner,) – Local background: the
(2 outer + 1)^2square around a pixel minus the(2 inner + 1)^2one, and the ring of the neighbourhood filters (--local-lower/upper-limit,--postproc-gap-small/large).min_outlier_frac (fdr, tstat,) – Candidates: FDR (per distance) below
fdr, t-statistic abovetstat, more thanmin_outlier_fracof the cells outliers.vertical (circle, donut, lower_left, horizontal,) –
outlier_countmust exceed these multiples of its mean over each neighbourhood.clustering_gap (int) – Bins: density radius
sqrt(2) * gapof the clustering.summit_gap (int) – bp: further summits of a cluster lie farther than this from the previous ones (in either anchor).
batch (int) – Cells imputed at once by the native path (0: one per thread); memory ~3 bands per cell.
sliding_window_holes (bool) – Reproduce SnapHiC v0.2’s sliding windows exactly, including the pixels they never set (left at 0: sums
i + j = (2k + 1) stepandi + j <= step). Only to compare with the authors’ code.
- uchrom.strc.loop.snaphic.call_loops_snaphic(cd, *, contacts: str = 'per_cell', cells: Sequence | None = None, chrom: None | str | Sequence[str] = None, resolution: int | None = None, params: SnapHiCParams | None = None, exclude=None, key_added: str | None = 'loops.snaphic', copy: bool = False, backend: str | None = None, n_threads: int = 0, timing: dict | None = None)[source]¶
Loops from single-cell Hi-C maps, tested across cells: SnapHiC (Yu et al. 2021; SnapHiC2 windows, Li et al. 2022). See the module docstring for the steps and the deviations from the authors’ code.
- Parameters:
cd (ChromData) – With per-cell maps linked (
cd.link_scool) or embedded in its atlas store.contacts (str) – Key of the per-cell maps (or the path of a
.scoolwhose cells are named by cell id).cells (sequence, optional) – Cells to use (default: every cell of
cd.cells).chrom (str or sequence, optional) – Chromosomes (default: the autosomes of the maps, as SnapHiC).
resolution (int, optional) – Bin size the maps must have (SnapHiC: 10 kb); default: the maps’ own.
params (SnapHiCParams, optional)
exclude (DataFrame or path, optional) – Bins excluded from the loop anchors (
chrom, start[, end]; a BED file): SnapHiC removes 10-kb bins of mappability <= 0.8 and the ENCODE blacklist (itsext/<genome>_filter_regions.txt).key_added (str or None) –
cd.results/cd.intervalskey (None: not stored); the clustered candidates go tocd.results[key_added + ".candidates"].copy (bool) – Return a new
ChromDataholding the result.backend ({"auto", "native", "numpy"}, optional) – Steps 1-3 (default: the module’s
BACKEND).n_threads (int) – Threads of the native path (0: all).
timing (dict, optional) – Filled with seconds per step and the backend.
- Returns:
A
pairtable, one row per loop summit:chrom1, start1, end1, chrom2, start2, end2,score(-log10fdr_dist),outlier_count(cells with z > 1.96),pvalue,tstat(paired t-test against the local background),fdr_dist(BH among the pixels at the same distance),case_avg/control_avg(mean z-score of the pixel / its background), the neighbourhood meanscircle, donut, horizontal, vertical, lower_leftofoutlier_count,cluster_size,neg_log10_fdr(of the cluster).- Return type:
DataFrame (
copy=False) or ChromData (copy=True)
Comparing loop calls¶
- uchrom.strc.loop.compare.match_loops(reference: DataFrame, calls: DataFrame, *, tol: int = 25000) Series[source]¶
Which loops of
referencewere called: both anchors of a call withintolbp of theirs.- Parameters:
reference (DataFrame) – BEDPE-like loop tables with
start1andstart2(anchor starts, bp). When both have a chromosome column (chrom1orchrom) a match must also be on the same chromosome.calls (DataFrame) – BEDPE-like loop tables with
start1andstart2(anchor starts, bp). When both have a chromosome column (chrom1orchrom) a match must also be on the same chromosome.tol (int) – Largest distance between anchor starts, bp (default one 25-kb bin).
- Return type:
Series of bool, indexed like
reference.
Examples
>>> ref = pd.DataFrame({"start1": [50_300_000], "start2": [50_525_000]}) >>> match_loops(ref, cd.intervals["loops.axiswise_f"])
- uchrom.strc.loop.compare.score_loops(cd, loops: str | DataFrame = 'loops.axiswise_f', *, chrom=None, trace_ids=None, cells=None) DataFrame[source]¶
How much closer the two anchors of each loop are than other locus pairs at the same genomic separation.
For each loop, the 3-D distance of its two anchor loci in every trace that detected both, against the distances of every other pair of loci of the chromosome exactly as far apart (same start-to-start separation), pooled over the traces. A loop called from imaging should have
ratio< 1.- Parameters:
cd (ChromData) – The traces (in memory or backed; one chromosome is read at a time).
loops (str or DataFrame) – A key of
cd.results/cd.intervals(default"loops.axiswise_f") or a loop table withchrom1(orchrom),start1,start2; anchors are matched to loci by their start.chrom (str or sequence of str, optional) – Score only the loops on these chromosomes.
trace_ids (sequence, optional) – Use only these traces / cells.
cells (sequence, optional) – Use only these traces / cells.
- Returns:
The loop table with
n_traces(traces that detected both anchors),anchor_distance(their median distance),n_background(distances of the other pairs),background_distance(their median) andratio(= anchor / background). Distances in the unit ofcd.coords.- Return type:
DataFrame