uchrom.strc.comp¶
A/B compartment detection from chromatin-tracing data, and from linked Hi-C maps (cis eigenvector, saddle strength).
- class uchrom.strc.comp.CompartmentCallerParams(n_clusters: int = 2, min_compartment_bp: float = 0.0, min_bins: int | None = None, k_sigma: float = 4.0, frac: float = 0.1, random_state: int = 0, n_init: int = 1, a_cluster: int | None = None, a_track: str | None = None)[source]¶
Bases:
objectKnobs of
call_compartments_axes_pc()(module docstring).min_compartment_bp(ArcFISHmin_cpmt_size; default 0 as in the authors’ tutorial);n_init/random_stateof the k-means;a_cluster/a_trackname the A compartment (else the authors’ rule);k_sigma/fracofuchrom.fea.arc.filter_normalize().min_bins(deprecated) is the former minimum run in loci; given, it flips runs of fewer loci the same way.Before U-Chrom 0.3 (2026-10) missing variances were dropped from the kernel, the k-means ran 10 times, short runs were merged by bin count and A was the more compact cluster — the opposite of the authors’ rule (
docs/source/reference/changelog.md).
- class uchrom.strc.comp.EigCompartmentParams(ignore_diags: int | None = None, clip_percentile: float = 99.9, dist_bin_ratio: float = 1.03, phasing_method: str = 'spearman', sort_by_phasing: bool = False)[source]¶
Bases:
objectKnobs of
call_compartments_eig()(defaults: cooltoolseigs_cis).ignore_diags: the diagonals next to the main one that are left out (set to the expected);Nonetakes the value the map was balanced with (ignore_diagsattribute of its weights, else 2).clip_percentile: observed / expected values above this percentile of all valid pairs are clipped (0 or 100: no clipping).dist_bin_ratio: the expected is the mean over classes of separation whose edges grow by this ratio (cooltools: 1.03); 1 = one class per diagonal.phasing_method: the correlation ("spearman"as cooltools, or"pearson") by which each eigenvector is oriented against the phasing track;sort_by_phasingreorders the eigenvectors of a region by decreasing absolute correlation with the track (cooltoolssort_metric), which keeps a chromosome-arm or translocation eigenvector from being reported as E1.
- class uchrom.strc.comp.HiCCompartmentParams(n_distance_classes: int = 60, min_separation_bp: float = 31622.776601683792, balance: bool = False)[source]¶
Bases:
objectKnobs of
call_compartments_hic().The expected count of a bin pair is the mean count of the pairs in its class of genomic separation (
n_distance_classeslog-spaced classes frommin_separation_bpto the largest separation, pairs closer thanmin_separation_bpin one class) — so uneven loci are handled.
- class uchrom.strc.comp.SaddleParams(qrange: Tuple[float, float] | None = (0.025, 0.975), vrange: Tuple[float, float] | None = None, min_diag: int = 3, max_diag: int | None = None, corner: float = 0.2)[source]¶
Bases:
objectKnobs of
compartment_strength()(defaults: the Open2C saddle examples).The bins are grouped by E1 between the quantiles
qrange(or the valuesvrange) inton_binsgroups plus one outlier group at each end; pairs closer thanmin_diagdiagonals (and farther thanmax_diag,None: no limit) are left out.corner: the fraction of bins at each end of the E1 ranking that make the AA / BB / AB corners of the scalar strength (0.2: the top and bottom 20 %, as Flyamer et al. 2017 and Nora et al. 2017).
- class uchrom.strc.comp.ScABParams(contacts: str = 'all', min_separation: int = 1, normalize: str = 'rank', min_contacts: int = 1, sequence_feature: str = 'cpg_frequency', empty: str = 'nan')[source]¶
Bases:
objectKnobs of
single_cell_compartments()(defaults: Dip-C, Tan et al. 2021).contacts: which contacts count —"all"(intra- and inter-chromosomal; Dip-Ccolor2),"cis"(each chromosome on its own; scHiCluster) or"trans".min_separation: intra-chromosomal contacts between bins fewer than this many bins apart are left out (1: only contacts within one bin, as both implementations).normalize: per cell, over the bins returned —"rank"(ranks, ties averaged, scaled to 0-1: Dip-Ccolor_to_rank.py),"zscore"or"none"(the mean CpG frequency of the partners: scHiCluster).min_contacts: a bin gets a value in a cell when it has at least this many contacts with partners that have a track value (NaN otherwise).sequence_feature: the track computed whentrackis a FASTA ("cpg_frequency": Dip-C;"cpg_density","gc_fraction").empty: the value of a bin belowmin_contacts—"nan"(Dip-C) or"own", its own track value (scHiCluster).
- uchrom.strc.comp.call_compartments_axes_pc(cd, *args, chrom=None, trace_ids=None, cells=None, params: CompartmentCallerParams | None = None, device: str = 'auto', key_added: str | None = UNSET, copy: bool = False, verbose: bool = False, centromeres=None, store=UNSET, result_key=UNSET)[source]¶
Call A/B compartments with ArcFISH’s axes-PC method (chromatin tracing; module docstring).
- Parameters:
cd (ChromData)
chrom (str, sequence of str, or None) –
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 (CompartmentCallerParams, optional)
device (
'auto' | 'cpu' | 'cuda' | 'mps')key_added (str or None) –
cd.resultskey (default"compartments.axes_pc");Nonedoes not store.copy (bool) –
True→ return a new ChromData holding the result.centromeres (mapping or DataFrame, optional) – Centromere position per chromosome (
{chrom: bp}, or a table withchromandmid/pos/start, end; asuchrom.strc.comp.call_compartments_eig()): each arm is called on its own, as the authors’ caller does with a reference genome — the normalised variances of the whole chromosome, the p arm the loci withend <= centromere; with fewer than 2 loci on an arm the whole chromosome is called. For whole chromosomes of reconstructed single-cell structures, whose two arms often lie apart, the second eigenvector of a metacentric chromosome otherwise separates the arms rather than the compartments (Tan et al. 2018 Dip-C GM12878 at 250 kb: per-chromosome r with the E1 of the same cells’ contacts -0.36-0.21 on chr2, 3, 4, 5, 8, 10 whole, 0.31-0.78 per arm; uchrom-reproducibility/supp_table3/sc_structures).
- Returns:
One row per locus:
chrom, start, end, bin_index, cluster, compartment, pc2, eig_x, eig_y, eig_z(bin_indexcounts within the chromosome;eig_*the per-axis eigenvectors,pc2their weighted sum oriented so that A > 0); withcentromeresalsoregion(<chrom>_p/<chrom>_q, or the chromosome).- 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"compartments".
- uchrom.strc.comp.call_compartments_eig(cd, *, contacts: str | None = None, chrom=None, resolution: int | None = None, phasing=None, centromeres=None, n_eigs: int = 3, params: EigCompartmentParams | None = None, key_added: str | None = 'compartments.eig', copy: bool = False)[source]¶
A/B compartments of a contact map: the cis eigenvectors of observed / expected, per chromosome (arm).
The eigenvector decomposition of Lieberman-Aiden et al. 2009 (Science 326:289) in the formulation of cooltools
eigs_cis(Open2C, Abdennur et al. 2024, PLoS Comput Biol 20:e1012067): on the balanced map of each chromosome (or chromosome arm), bins without contacts are dropped, the firstignore_diagsdiagonals ignored, the contacts divided by their expected (mean over log-spaced classes of separation), clipped at the 99.9th percentile, and the leading eigenvectors ofO/E - 1taken (by absolute eigenvalue), each scaled by the square root of its eigenvalue. Each eigenvector is then flipped to correlate positively with thephasingtrack, so thatE1 > 0is the A (active, GC-rich, gene-rich) compartment. For a map whose loci are uneven (imaged segments), usecall_compartments_hic().- Parameters:
cd (ChromData, path or cooler.Cooler) – Holds the link (
cd.link_cool(path, key=...)) and receives the result. A path / cooler is read directly and nothing is stored.contacts (str, optional) – Key of the linked map (
None: the only one) or the path of a.cool/.mcool. The map must be balanced (rebin_mapbalances what it writes).chrom (str, sequence of str, or None) –
None: the chromosomes ofcdthat the map has (every map chromosome whencdhas no spots).resolution (int, optional) – The level of an
.mcool.phasing (str, path or DataFrame, optional) – The track the eigenvectors are oriented by (higher in A): the path of a FASTA (the GC content of every map bin,
uchrom.fea.compute_sequence_features()), the name of acd.bin_trackscolumn (gene density, an active mark), the key of a compartment table incd.results(itsE1: e.g. cell-type maps oriented like the all-cells map), or a DataFrame withchrom, start, endand one value column (valuewhen it has several) — each map bin takes the mean of the loci whose midpoint it holds (or the locus holding its midpoint). Without it the signs, and so which label is A, are arbitrary.centromeres (mapping or DataFrame, optional) – Centromere position per chromosome (
{chrom: bp}, or a table withchromandmid/pos/start, end): each arm is decomposed on its own (a bin belongs to the arm holding its start), which keeps the arms’ contrast out of E1.n_eigs (int) – Eigenvectors per region (
E1 .. En).params (EigCompartmentParams, optional)
key_added (str or None) –
cd.resultskey (default"compartments.eig");Nonedoes not store.copy (bool) –
True→ return a new ChromData holding the result.
- Returns:
One row per valid map bin:
chrom, start, end, bin_index(in the map, per chromosome),region(the chromosome, or<chrom>_p/<chrom>_q),compartment("A"whereE1 > 0) andE1 .. En. When stored, also the eigenvalues per region (region, chrom, start, end, eigval1 .., phasing_r1 ..: the correlation of each eigenvector with the phasing track) ascd.results[f"{key_added}.eigvals"], the runs of equal label (broken at masked bins) as thesegmenttablecd.intervals[key_added], and E1 on the loci ofcd(the map bin holding each locus’ midpoint) ascd.bin_tracks[f"{key_added}.E1"].- Return type:
DataFrame (
copy=False) or ChromData (copy=True)
- uchrom.strc.comp.call_compartments_hic(cd, *, contacts='default', resolution: int | None = None, chrom=None, orient_by: str | None = None, params: HiCCompartmentParams | None = None, key_added: str | None = 'compartments.hic_pc1', copy: bool = False)[source]¶
A/B compartments of a Hi-C map linked to
cd: PC1 of the observed / expected correlation matrix.Works on bins of any size and spacing (dense matrices: small maps). For a map of regular bins, the cooltools-style cis eigenvector
uchrom.strc.comp.eig.call_compartments_eig()is the standard and scales to high resolution.- Parameters:
cd (ChromData) – Holds the link (
cd.link_cool(path, key=...)) and receives the result.contacts (str) – Key of
cd.uns['linked_cool'](default"default") or a path to a.cool/.mcool.resolution (int, optional) – Required for
.mcool.chrom (str, sequence of str, or None) –
None: the chromosomes ofcdthat the map has (every map chromosome whencdhas no spots).orient_by (str, optional) – A
cd.bin_trackscolumn that is higher in A (gene density, an active mark): PC1 is oriented to correlate positively with it (the track of the loci inside each Hi-C bin, averaged). Without it the sign — and so which label is A — is arbitrary.params (HiCCompartmentParams, optional) – Distance classes of the expected counts;
balance=Truefor the ICE-balanced matrix.key_added (str or None) –
cd.resultskey (default"compartments.hic_pc1");Nonedoes not store.copy (bool) –
True→ return a new ChromData holding the result.
- Returns:
One row per Hi-C bin with contacts:
chrom, start, end, bin_index(in the map, per chromosome),compartment("A"wherepc1 > 0) andpc1. When stored, also the runs of equal label as thesegmenttablecd.intervals[key_added]and PC1 on the loci ofcd(the Hi-C bin holding each locus’ midpoint) ascd.bin_tracks[f"{key_added}.pc1"].- Return type:
DataFrame (
copy=False) or ChromData (copy=True)
- uchrom.strc.comp.cis_eigs(band, *, lo: int = 0, hi: int | None = None, n_eigs: int = 3, ignore_diags: int = 2, clip_percentile: float = 99.9, dist_bin_ratio: float = 1.03) Tuple[ndarray, ndarray][source]¶
Compartment eigenvectors of one cis region of a balanced map (cooltools
cis_eig, sparse).The region is bins
[lo, hi)ofband(auchrom.fea.band.read_band()of the whole chromosome). Valid bins are those with a positive balanced contact sum; the firstignore_diagsdiagonals are set to 1 (so to the expected); observed / expected uses the mean over classes of separation growing bydist_bin_ratioand the valid pairs only (pairs without contacts count as 0); values above theclip_percentileof all valid pairs are clipped; the matrixO/E - 1of the valid bins is decomposed (Lieberman-Aiden et al. 2009; Imakaev et al. 2012; Open2C 2024).- Returns:
eigvals (ndarray (n_eigs,)) – Sorted by decreasing absolute value (NaN when the region is too small).
eigvecs (ndarray (n_eigs, hi - lo)) – Unit norm times
sqrt(|eigval|); NaN on invalid bins. Signs are arbitrary.
- uchrom.strc.comp.compare_compartments(cd, query: str | DataFrame, reference: str | DataFrame, *, chrom=None) Dict[str, float][source]¶
How well two compartment calls agree on the loci of
cd.- Parameters:
cd (ChromData) – Its
binsare the common axis: each locus takes the label and score of the bin of each call that holds its midpoint.query (str or DataFrame) – Keys of
cd.resultsor per-bin tables withchrom, start, end,compartment(orlabel) and a score column (pc2,pc1,E1orscore), e.g.call_compartments_axes_pc()on the imaging andcall_compartments_hic()/call_compartments_eig()on Hi-C of the same loci.reference (str or DataFrame) – Keys of
cd.resultsor per-bin tables withchrom, start, end,compartment(orlabel) and a score column (pc2,pc1,E1orscore), e.g.call_compartments_axes_pc()on the imaging andcall_compartments_hic()/call_compartments_eig()on Hi-C of the same loci.chrom (str or sequence of str, optional) – Compare only these chromosomes.
- Returns:
n_bins(loci called by both),agreement(fraction of them with the same label) andpearson_r(correlation of the two scores).- Return type:
- uchrom.strc.comp.compartment_segments(table: DataFrame, score: str = 'pc2') DataFrame[source]¶
Per-bin compartment calls → runs of equal label per chromosome.
Columns
chrom, start, end, label, n_binsandscore(defaultpc2: its mean over the run’s bins). Stored as thesegmentinterval tablecd.intervals[key_added].
- uchrom.strc.comp.compartment_strength(cd, *, contacts: str | None = None, compartments: str | DataFrame = 'compartments.eig', track: str = 'E1', chrom=None, resolution: int | None = None, n_bins: int = 38, params: SaddleParams | None = None, key_added: str | None = 'compartment_strength.saddle', copy: bool = False)[source]¶
Compartment strength by saddle analysis: observed / expected contacts averaged over pairs of E1 quantile groups, and
(AA + BB) / (AB + BA)from its corners.Following Nora et al. 2017 (Cell 169:930), Flyamer et al. 2017 (Nature 544:110), Schwarzer et al. 2017 (Nature 551:51) and cooltools
saddle/saddle_strength(Open2C 2024): the valid bins of the chromosomes are pooled and split by the quantiles oftrackinton_binsgroups (plus an outlier group at each end); every cis pair of valid bins at leastmin_diagdiagonals apart adds its observed / expected (balanced contacts over the mean of their diagonal,uchrom.fea.expected_cis(); pairs without contacts add 0) to the cell of its two groups. The saddle is the mean per cell; the strength the pooled mean of the AA and BB corners over that of the AB and BA corners, for every corner size (strength_curve) and for the top / bottomcornerfraction of bins (strength).- Parameters:
cd (ChromData, path or cooler.Cooler) – Holds the map link and the compartment call; a path / cooler (with
compartmentsa DataFrame) is read directly and nothing is stored.contacts (str, optional) – Key of the linked map (
None: the only one) or a path; balanced.compartments (str or DataFrame) – The compartment call: a
cd.resultskey (default"compartments.eig") or a table withchrom, start, endandtrack. Each map bin takes the value of the call’s bin holding its midpoint.track (str) – Column of
compartmentsto group by (E1; higher = A).chrom (str, sequence of str, or None) – Chromosomes to pool (default: those of the call that the map has).
resolution (int, optional) – The level of an
.mcool.n_bins (int) – Quantile groups between
params.qrange(cooltools / Open2C examples: 38 groups of 2.5 %).params (SaddleParams, optional)
key_added (str or None) –
cd.resultskey (a mapping);Nonedoes not store.copy (bool) –
True→ return a new ChromData holding the result.
- Returns:
saddle((n_bins + 2) x (n_bins + 2)mean observed / expected, outlier groups first and last),sumandcount(as cooltools: over both triangles, symmetrised),edges(thetrackvalues at the group edges),group_size(bins per group),strength_curve(by corner sizek; index 0 NaN),corner_groups(thekofstrength),strength,AA,BB,AB(mean observed / expected in the corners),chrom.- Return type:
dict (
copy=False) or ChromData (copy=True)
- uchrom.strc.comp.hic_compartment_pc1(counts: ndarray, positions, *, marker=None, params: HiCCompartmentParams | None = None) ndarray[source]¶
PC1 of the correlation matrix of the log2 observed / expected contact matrix.
- Parameters:
counts (ndarray (n, n)) – Contact matrix of one chromosome (bins without contacts removed beforehand).
positions (array (n,)) – Genomic position of each bin (bp; e.g. its start) — the separations of the expected counts.
marker (array (n,), optional) – A track that is higher in A (gene density, an active mark); PC1 is oriented to correlate positively with it (NaN values are left out). Without it the sign is arbitrary.
params (HiCCompartmentParams, optional)
- Returns:
Unit-norm PC1;
> 0is A when amarkeris given.- Return type:
ndarray (n,)
- uchrom.strc.comp.normalize_scab(values: ndarray, method: str = 'rank') ndarray[source]¶
Normalise raw scA/B values per cell (row), over the finite entries of the row.
"rank": ranks (ties averaged) scaled to 0-1,(rank - 1) / (n - 1)(Dip-Ccolor_to_rank.py, Tan et al. 2021);"zscore": minus the row mean, over the row standard deviation;"none": unchanged. Rows with fewer than two finite values become NaN (except"none").
- uchrom.strc.comp.saddle_strength(S: ndarray, C: ndarray) ndarray[source]¶
Compartment strength for every corner extent
kof a saddle (cooltoolssaddle_strength):(AA + BB) / (AB + BA)with the sums and counts of thek x kcorners pooled; index 0 is NaN.
- uchrom.strc.comp.scab_sums(rows, bin1, bin2, count, track, *, n_rows: int | None = None, chrom_of_bin: ndarray | None = None, params: ScABParams | None = None) Tuple[ndarray, ndarray, ndarray][source]¶
The raw scA/B values of in-memory pixels: the kernel of
single_cell_compartments().- Parameters:
rows (array-like) – One entry per pixel (or per contact): the cell (row of the result,
0 .. n_rows-1), its two bins (genome-wide indices intotrack) and its count. Each pixel counts once (give the upper triangle of a symmetric map).bin1 (array-like) – One entry per pixel (or per contact): the cell (row of the result,
0 .. n_rows-1), its two bins (genome-wide indices intotrack) and its count. Each pixel counts once (give the upper triangle of a symmetric map).bin2 (array-like) – One entry per pixel (or per contact): the cell (row of the result,
0 .. n_rows-1), its two bins (genome-wide indices intotrack) and its count. Each pixel counts once (give the upper triangle of a symmetric map).count (array-like) – One entry per pixel (or per contact): the cell (row of the result,
0 .. n_rows-1), its two bins (genome-wide indices intotrack) and its count. Each pixel counts once (give the upper triangle of a symmetric map).track (array-like (n_bins,)) – The value of every bin (CpG frequency); NaN: the bin is no partner.
n_rows (int, optional) – Cells (default
max(rows) + 1).chrom_of_bin (array-like (n_bins,), optional) – Chromosome of each bin (any labels), for the cis / trans selection and
min_separation; default: one chromosome.params (ScABParams, optional) –
contacts,min_separation,min_contactsapply; no normalisation (normalize_scab()).
- Returns:
values (ndarray (n_rows, n_bins)) – Mean track value of each bin’s partners in each cell (NaN below
min_contacts).partner_contacts (ndarray (n_rows, n_bins)) – The contacts averaged over (those with a partner that has a track value).
n_contacts (ndarray (n_rows,)) – The contacts counted per cell (after the cis / trans and separation filters).
- uchrom.strc.comp.single_cell_compartments(cd, *, contacts: str = 'per_cell', track=None, cells: Sequence | None = None, chrom=None, resolution: int | None = None, params: ScABParams | None = None, key_added: str | None = 'compartments.scab', copy: bool = False, max_pixels: int | None = None, workers: int | None = None, verbose: bool = False)[source]¶
Single-cell compartment values (scA/B): per cell and bin, the mean CpG frequency of the bin’s contact partners in that cell, normalised per cell.
The definition of Tan et al. 2018 (Science 361:924) and 2021 (Cell 184:741; Dip-C
color2+color_to_rank.py): every contact of a cell between binsi != jadds the track value (CpG frequency) ofjtoiand that ofitoj; the value of a bin is the mean over its contacts; each cell’s values are then replaced by their ranks scaled to 0-1.ScABParams(contacts="cis", normalize="none", empty="own")gives the compartment score of scHiClustercomp-cpg-cell(Zhou et al. 2019, PNAS 116:14011): cis contacts only, no normalisation. A bin’s value is high (A-like) when it contacts CpG-rich regions. The cells × bins matrix separates cell types (PCA → t-SNE: Tan et al. 2021’s “structure typing”) and, averaged over the cells of a type, follows the type’s bulk compartment eigenvector.- Parameters:
cd (ChromData) – With
cellsand 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).contacts (str) – Key of the linked per-cell maps (
cd.uns['linked_scool']), or the path of a.scoolwhose cell names are the cell ids.track (path, str, DataFrame or ndarray) – The value of every map bin: the path of a genome FASTA (
params.sequence_featureof each bin, Dip-C’s CpG frequency by default;uchrom.fea.compute_sequence_features(); e.g.uchrom.datasets.fetch("mm10_genome")), acd.bin_trackscolumn, the key of a compartment table incd.results(itsE1), a DataFramechrom, start, end+ one value column (each map bin takes the mean of the loci whose midpoint it holds), or an array with one value per map bin. The values computed are kept in the result table (columntrack): pass that table to skip the FASTA next time.cells (sequence of cell ids, optional) – Cells to compute (default: every cell of
cd.cellswith a map); the other rows are NaN.chrom (str, sequence of str, or None) – Chromosomes whose bins are returned (and ranked); default every chromosome of the maps. Partners on every chromosome count (
params.contacts).resolution (int, optional) – Bin size (bp), a multiple of the per-cell maps’ (default: theirs).
params (ScABParams, optional) – Which contacts, the normalisation, the minimum contacts per bin.
key_added (str or None) –
cd.results/cd.cellmkey (default"compartments.scab");Nonedoes not store.copy (bool) –
True→ return a new ChromData holding the result.max_pixels – Pixels per read and reads in flight (embedded maps; defaults of
uchrom.fea.pseudobulk()).workers – Pixels per read and reads in flight (embedded maps; defaults of
uchrom.fea.pseudobulk()).verbose (bool) – Print progress.
- Returns:
Cells (the computed ones) × bins (
"chrom:start-end"), float32; NaN where a bin has fewer thanparams.min_contactscontacts with partners that have a track value. When stored: the matrix for every cell ofcd.cellsascd.cellm[key_added](NaN rows for cells not computed), the bins as the tablecd.results[key_added](chrom, start, end, track, n_cells— cells with a value —,mean,sdover the cells; rowk= columnkof the matrix) with the call’s provenance, and per cellcd.cells[f"{key_added}.n_contacts"](contacts counted) andcd.cells[f"{key_added}.n_bins"](bins with a value).- Return type:
DataFrame (
copy=False) or ChromData (copy=True)
Notes
Bins: those of the per-cell maps (
[k * resolution, (k + 1) * resolution)); Dip-C centres its bins on multiples of the bin size — the values differ by that half-bin shift only. Memory: per block of cells the two sums (BLOCK_BYTES) plus the reads in flight, and the result (cells × bins, float32). Time on an atlas store over HTTP is mostly the transfer of the per-cell maps (contacts="cis"reads no trans partition).
- class uchrom.strc.comp.axes_pc.CompartmentCallerParams(n_clusters: int = 2, min_compartment_bp: float = 0.0, min_bins: int | None = None, k_sigma: float = 4.0, frac: float = 0.1, random_state: int = 0, n_init: int = 1, a_cluster: int | None = None, a_track: str | None = None)[source]¶
Bases:
objectKnobs of
call_compartments_axes_pc()(module docstring).min_compartment_bp(ArcFISHmin_cpmt_size; default 0 as in the authors’ tutorial);n_init/random_stateof the k-means;a_cluster/a_trackname the A compartment (else the authors’ rule);k_sigma/fracofuchrom.fea.arc.filter_normalize().min_bins(deprecated) is the former minimum run in loci; given, it flips runs of fewer loci the same way.Before U-Chrom 0.3 (2026-10) missing variances were dropped from the kernel, the k-means ran 10 times, short runs were merged by bin count and A was the more compact cluster — the opposite of the authors’ rule (
docs/source/reference/changelog.md).
- uchrom.strc.comp.axes_pc.call_compartments_axes_pc(cd, *args, chrom=None, trace_ids=None, cells=None, params: CompartmentCallerParams | None = None, device: str = 'auto', key_added: str | None = UNSET, copy: bool = False, verbose: bool = False, centromeres=None, store=UNSET, result_key=UNSET)[source]¶
Call A/B compartments with ArcFISH’s axes-PC method (chromatin tracing; module docstring).
- Parameters:
cd (ChromData)
chrom (str, sequence of str, or None) –
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 (CompartmentCallerParams, optional)
device (
'auto' | 'cpu' | 'cuda' | 'mps')key_added (str or None) –
cd.resultskey (default"compartments.axes_pc");Nonedoes not store.copy (bool) –
True→ return a new ChromData holding the result.centromeres (mapping or DataFrame, optional) – Centromere position per chromosome (
{chrom: bp}, or a table withchromandmid/pos/start, end; asuchrom.strc.comp.call_compartments_eig()): each arm is called on its own, as the authors’ caller does with a reference genome — the normalised variances of the whole chromosome, the p arm the loci withend <= centromere; with fewer than 2 loci on an arm the whole chromosome is called. For whole chromosomes of reconstructed single-cell structures, whose two arms often lie apart, the second eigenvector of a metacentric chromosome otherwise separates the arms rather than the compartments (Tan et al. 2018 Dip-C GM12878 at 250 kb: per-chromosome r with the E1 of the same cells’ contacts -0.36-0.21 on chr2, 3, 4, 5, 8, 10 whole, 0.31-0.78 per arm; uchrom-reproducibility/supp_table3/sc_structures).
- Returns:
One row per locus:
chrom, start, end, bin_index, cluster, compartment, pc2, eig_x, eig_y, eig_z(bin_indexcounts within the chromosome;eig_*the per-axis eigenvectors,pc2their weighted sum oriented so that A > 0); withcentromeresalsoregion(<chrom>_p/<chrom>_q, or the chromosome).- 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"compartments".
Hi-C maps: cis eigenvector and saddle strength¶
A/B compartments of a linked contact map (bulk or pseudo-bulk) by the cis eigenvector of observed / expected, and their strength by saddle analysis.
- class uchrom.strc.comp.eig.EigCompartmentParams(ignore_diags: int | None = None, clip_percentile: float = 99.9, dist_bin_ratio: float = 1.03, phasing_method: str = 'spearman', sort_by_phasing: bool = False)[source]¶
Bases:
objectKnobs of
call_compartments_eig()(defaults: cooltoolseigs_cis).ignore_diags: the diagonals next to the main one that are left out (set to the expected);Nonetakes the value the map was balanced with (ignore_diagsattribute of its weights, else 2).clip_percentile: observed / expected values above this percentile of all valid pairs are clipped (0 or 100: no clipping).dist_bin_ratio: the expected is the mean over classes of separation whose edges grow by this ratio (cooltools: 1.03); 1 = one class per diagonal.phasing_method: the correlation ("spearman"as cooltools, or"pearson") by which each eigenvector is oriented against the phasing track;sort_by_phasingreorders the eigenvectors of a region by decreasing absolute correlation with the track (cooltoolssort_metric), which keeps a chromosome-arm or translocation eigenvector from being reported as E1.
- uchrom.strc.comp.eig.call_compartments_eig(cd, *, contacts: str | None = None, chrom=None, resolution: int | None = None, phasing=None, centromeres=None, n_eigs: int = 3, params: EigCompartmentParams | None = None, key_added: str | None = 'compartments.eig', copy: bool = False)[source]¶
A/B compartments of a contact map: the cis eigenvectors of observed / expected, per chromosome (arm).
The eigenvector decomposition of Lieberman-Aiden et al. 2009 (Science 326:289) in the formulation of cooltools
eigs_cis(Open2C, Abdennur et al. 2024, PLoS Comput Biol 20:e1012067): on the balanced map of each chromosome (or chromosome arm), bins without contacts are dropped, the firstignore_diagsdiagonals ignored, the contacts divided by their expected (mean over log-spaced classes of separation), clipped at the 99.9th percentile, and the leading eigenvectors ofO/E - 1taken (by absolute eigenvalue), each scaled by the square root of its eigenvalue. Each eigenvector is then flipped to correlate positively with thephasingtrack, so thatE1 > 0is the A (active, GC-rich, gene-rich) compartment. For a map whose loci are uneven (imaged segments), usecall_compartments_hic().- Parameters:
cd (ChromData, path or cooler.Cooler) – Holds the link (
cd.link_cool(path, key=...)) and receives the result. A path / cooler is read directly and nothing is stored.contacts (str, optional) – Key of the linked map (
None: the only one) or the path of a.cool/.mcool. The map must be balanced (rebin_mapbalances what it writes).chrom (str, sequence of str, or None) –
None: the chromosomes ofcdthat the map has (every map chromosome whencdhas no spots).resolution (int, optional) – The level of an
.mcool.phasing (str, path or DataFrame, optional) – The track the eigenvectors are oriented by (higher in A): the path of a FASTA (the GC content of every map bin,
uchrom.fea.compute_sequence_features()), the name of acd.bin_trackscolumn (gene density, an active mark), the key of a compartment table incd.results(itsE1: e.g. cell-type maps oriented like the all-cells map), or a DataFrame withchrom, start, endand one value column (valuewhen it has several) — each map bin takes the mean of the loci whose midpoint it holds (or the locus holding its midpoint). Without it the signs, and so which label is A, are arbitrary.centromeres (mapping or DataFrame, optional) – Centromere position per chromosome (
{chrom: bp}, or a table withchromandmid/pos/start, end): each arm is decomposed on its own (a bin belongs to the arm holding its start), which keeps the arms’ contrast out of E1.n_eigs (int) – Eigenvectors per region (
E1 .. En).params (EigCompartmentParams, optional)
key_added (str or None) –
cd.resultskey (default"compartments.eig");Nonedoes not store.copy (bool) –
True→ return a new ChromData holding the result.
- Returns:
One row per valid map bin:
chrom, start, end, bin_index(in the map, per chromosome),region(the chromosome, or<chrom>_p/<chrom>_q),compartment("A"whereE1 > 0) andE1 .. En. When stored, also the eigenvalues per region (region, chrom, start, end, eigval1 .., phasing_r1 ..: the correlation of each eigenvector with the phasing track) ascd.results[f"{key_added}.eigvals"], the runs of equal label (broken at masked bins) as thesegmenttablecd.intervals[key_added], and E1 on the loci ofcd(the map bin holding each locus’ midpoint) ascd.bin_tracks[f"{key_added}.E1"].- Return type:
DataFrame (
copy=False) or ChromData (copy=True)
- class uchrom.strc.comp.eig.SaddleParams(qrange: Tuple[float, float] | None = (0.025, 0.975), vrange: Tuple[float, float] | None = None, min_diag: int = 3, max_diag: int | None = None, corner: float = 0.2)[source]¶
Bases:
objectKnobs of
compartment_strength()(defaults: the Open2C saddle examples).The bins are grouped by E1 between the quantiles
qrange(or the valuesvrange) inton_binsgroups plus one outlier group at each end; pairs closer thanmin_diagdiagonals (and farther thanmax_diag,None: no limit) are left out.corner: the fraction of bins at each end of the E1 ranking that make the AA / BB / AB corners of the scalar strength (0.2: the top and bottom 20 %, as Flyamer et al. 2017 and Nora et al. 2017).
- uchrom.strc.comp.eig.compartment_strength(cd, *, contacts: str | None = None, compartments: str | DataFrame = 'compartments.eig', track: str = 'E1', chrom=None, resolution: int | None = None, n_bins: int = 38, params: SaddleParams | None = None, key_added: str | None = 'compartment_strength.saddle', copy: bool = False)[source]¶
Compartment strength by saddle analysis: observed / expected contacts averaged over pairs of E1 quantile groups, and
(AA + BB) / (AB + BA)from its corners.Following Nora et al. 2017 (Cell 169:930), Flyamer et al. 2017 (Nature 544:110), Schwarzer et al. 2017 (Nature 551:51) and cooltools
saddle/saddle_strength(Open2C 2024): the valid bins of the chromosomes are pooled and split by the quantiles oftrackinton_binsgroups (plus an outlier group at each end); every cis pair of valid bins at leastmin_diagdiagonals apart adds its observed / expected (balanced contacts over the mean of their diagonal,uchrom.fea.expected_cis(); pairs without contacts add 0) to the cell of its two groups. The saddle is the mean per cell; the strength the pooled mean of the AA and BB corners over that of the AB and BA corners, for every corner size (strength_curve) and for the top / bottomcornerfraction of bins (strength).- Parameters:
cd (ChromData, path or cooler.Cooler) – Holds the map link and the compartment call; a path / cooler (with
compartmentsa DataFrame) is read directly and nothing is stored.contacts (str, optional) – Key of the linked map (
None: the only one) or a path; balanced.compartments (str or DataFrame) – The compartment call: a
cd.resultskey (default"compartments.eig") or a table withchrom, start, endandtrack. Each map bin takes the value of the call’s bin holding its midpoint.track (str) – Column of
compartmentsto group by (E1; higher = A).chrom (str, sequence of str, or None) – Chromosomes to pool (default: those of the call that the map has).
resolution (int, optional) – The level of an
.mcool.n_bins (int) – Quantile groups between
params.qrange(cooltools / Open2C examples: 38 groups of 2.5 %).params (SaddleParams, optional)
key_added (str or None) –
cd.resultskey (a mapping);Nonedoes not store.copy (bool) –
True→ return a new ChromData holding the result.
- Returns:
saddle((n_bins + 2) x (n_bins + 2)mean observed / expected, outlier groups first and last),sumandcount(as cooltools: over both triangles, symmetrised),edges(thetrackvalues at the group edges),group_size(bins per group),strength_curve(by corner sizek; index 0 NaN),corner_groups(thekofstrength),strength,AA,BB,AB(mean observed / expected in the corners),chrom.- Return type:
dict (
copy=False) or ChromData (copy=True)
Low-level kernels:
- uchrom.strc.comp.eig.cis_eigs(band, *, lo: int = 0, hi: int | None = None, n_eigs: int = 3, ignore_diags: int = 2, clip_percentile: float = 99.9, dist_bin_ratio: float = 1.03) Tuple[ndarray, ndarray][source]¶
Compartment eigenvectors of one cis region of a balanced map (cooltools
cis_eig, sparse).The region is bins
[lo, hi)ofband(auchrom.fea.band.read_band()of the whole chromosome). Valid bins are those with a positive balanced contact sum; the firstignore_diagsdiagonals are set to 1 (so to the expected); observed / expected uses the mean over classes of separation growing bydist_bin_ratioand the valid pairs only (pairs without contacts count as 0); values above theclip_percentileof all valid pairs are clipped; the matrixO/E - 1of the valid bins is decomposed (Lieberman-Aiden et al. 2009; Imakaev et al. 2012; Open2C 2024).- Returns:
eigvals (ndarray (n_eigs,)) – Sorted by decreasing absolute value (NaN when the region is too small).
eigvecs (ndarray (n_eigs, hi - lo)) – Unit norm times
sqrt(|eigval|); NaN on invalid bins. Signs are arbitrary.
Single cells: scA/B¶
Each cell’s compartment value per bin: the mean CpG frequency of the bin’s contact partners in that cell (Tan et al. 2021, Dip-C; scHiCluster’s compartment score as an option).
- class uchrom.strc.comp.single_cell.ScABParams(contacts: str = 'all', min_separation: int = 1, normalize: str = 'rank', min_contacts: int = 1, sequence_feature: str = 'cpg_frequency', empty: str = 'nan')[source]¶
Bases:
objectKnobs of
single_cell_compartments()(defaults: Dip-C, Tan et al. 2021).contacts: which contacts count —"all"(intra- and inter-chromosomal; Dip-Ccolor2),"cis"(each chromosome on its own; scHiCluster) or"trans".min_separation: intra-chromosomal contacts between bins fewer than this many bins apart are left out (1: only contacts within one bin, as both implementations).normalize: per cell, over the bins returned —"rank"(ranks, ties averaged, scaled to 0-1: Dip-Ccolor_to_rank.py),"zscore"or"none"(the mean CpG frequency of the partners: scHiCluster).min_contacts: a bin gets a value in a cell when it has at least this many contacts with partners that have a track value (NaN otherwise).sequence_feature: the track computed whentrackis a FASTA ("cpg_frequency": Dip-C;"cpg_density","gc_fraction").empty: the value of a bin belowmin_contacts—"nan"(Dip-C) or"own", its own track value (scHiCluster).
- uchrom.strc.comp.single_cell.single_cell_compartments(cd, *, contacts: str = 'per_cell', track=None, cells: Sequence | None = None, chrom=None, resolution: int | None = None, params: ScABParams | None = None, key_added: str | None = 'compartments.scab', copy: bool = False, max_pixels: int | None = None, workers: int | None = None, verbose: bool = False)[source]¶
Single-cell compartment values (scA/B): per cell and bin, the mean CpG frequency of the bin’s contact partners in that cell, normalised per cell.
The definition of Tan et al. 2018 (Science 361:924) and 2021 (Cell 184:741; Dip-C
color2+color_to_rank.py): every contact of a cell between binsi != jadds the track value (CpG frequency) ofjtoiand that ofitoj; the value of a bin is the mean over its contacts; each cell’s values are then replaced by their ranks scaled to 0-1.ScABParams(contacts="cis", normalize="none", empty="own")gives the compartment score of scHiClustercomp-cpg-cell(Zhou et al. 2019, PNAS 116:14011): cis contacts only, no normalisation. A bin’s value is high (A-like) when it contacts CpG-rich regions. The cells × bins matrix separates cell types (PCA → t-SNE: Tan et al. 2021’s “structure typing”) and, averaged over the cells of a type, follows the type’s bulk compartment eigenvector.- Parameters:
cd (ChromData) – With
cellsand 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).contacts (str) – Key of the linked per-cell maps (
cd.uns['linked_scool']), or the path of a.scoolwhose cell names are the cell ids.track (path, str, DataFrame or ndarray) – The value of every map bin: the path of a genome FASTA (
params.sequence_featureof each bin, Dip-C’s CpG frequency by default;uchrom.fea.compute_sequence_features(); e.g.uchrom.datasets.fetch("mm10_genome")), acd.bin_trackscolumn, the key of a compartment table incd.results(itsE1), a DataFramechrom, start, end+ one value column (each map bin takes the mean of the loci whose midpoint it holds), or an array with one value per map bin. The values computed are kept in the result table (columntrack): pass that table to skip the FASTA next time.cells (sequence of cell ids, optional) – Cells to compute (default: every cell of
cd.cellswith a map); the other rows are NaN.chrom (str, sequence of str, or None) – Chromosomes whose bins are returned (and ranked); default every chromosome of the maps. Partners on every chromosome count (
params.contacts).resolution (int, optional) – Bin size (bp), a multiple of the per-cell maps’ (default: theirs).
params (ScABParams, optional) – Which contacts, the normalisation, the minimum contacts per bin.
key_added (str or None) –
cd.results/cd.cellmkey (default"compartments.scab");Nonedoes not store.copy (bool) –
True→ return a new ChromData holding the result.max_pixels – Pixels per read and reads in flight (embedded maps; defaults of
uchrom.fea.pseudobulk()).workers – Pixels per read and reads in flight (embedded maps; defaults of
uchrom.fea.pseudobulk()).verbose (bool) – Print progress.
- Returns:
Cells (the computed ones) × bins (
"chrom:start-end"), float32; NaN where a bin has fewer thanparams.min_contactscontacts with partners that have a track value. When stored: the matrix for every cell ofcd.cellsascd.cellm[key_added](NaN rows for cells not computed), the bins as the tablecd.results[key_added](chrom, start, end, track, n_cells— cells with a value —,mean,sdover the cells; rowk= columnkof the matrix) with the call’s provenance, and per cellcd.cells[f"{key_added}.n_contacts"](contacts counted) andcd.cells[f"{key_added}.n_bins"](bins with a value).- Return type:
DataFrame (
copy=False) or ChromData (copy=True)
Notes
Bins: those of the per-cell maps (
[k * resolution, (k + 1) * resolution)); Dip-C centres its bins on multiples of the bin size — the values differ by that half-bin shift only. Memory: per block of cells the two sums (BLOCK_BYTES) plus the reads in flight, and the result (cells × bins, float32). Time on an atlas store over HTTP is mostly the transfer of the per-cell maps (contacts="cis"reads no trans partition).
- uchrom.strc.comp.single_cell.scab_sums(rows, bin1, bin2, count, track, *, n_rows: int | None = None, chrom_of_bin: ndarray | None = None, params: ScABParams | None = None) Tuple[ndarray, ndarray, ndarray][source]¶
The raw scA/B values of in-memory pixels: the kernel of
single_cell_compartments().- Parameters:
rows (array-like) – One entry per pixel (or per contact): the cell (row of the result,
0 .. n_rows-1), its two bins (genome-wide indices intotrack) and its count. Each pixel counts once (give the upper triangle of a symmetric map).bin1 (array-like) – One entry per pixel (or per contact): the cell (row of the result,
0 .. n_rows-1), its two bins (genome-wide indices intotrack) and its count. Each pixel counts once (give the upper triangle of a symmetric map).bin2 (array-like) – One entry per pixel (or per contact): the cell (row of the result,
0 .. n_rows-1), its two bins (genome-wide indices intotrack) and its count. Each pixel counts once (give the upper triangle of a symmetric map).count (array-like) – One entry per pixel (or per contact): the cell (row of the result,
0 .. n_rows-1), its two bins (genome-wide indices intotrack) and its count. Each pixel counts once (give the upper triangle of a symmetric map).track (array-like (n_bins,)) – The value of every bin (CpG frequency); NaN: the bin is no partner.
n_rows (int, optional) – Cells (default
max(rows) + 1).chrom_of_bin (array-like (n_bins,), optional) – Chromosome of each bin (any labels), for the cis / trans selection and
min_separation; default: one chromosome.params (ScABParams, optional) –
contacts,min_separation,min_contactsapply; no normalisation (normalize_scab()).
- Returns:
values (ndarray (n_rows, n_bins)) – Mean track value of each bin’s partners in each cell (NaN below
min_contacts).partner_contacts (ndarray (n_rows, n_bins)) – The contacts averaged over (those with a partner that has a track value).
n_contacts (ndarray (n_rows,)) – The contacts counted per cell (after the cis / trans and separation filters).
- uchrom.strc.comp.single_cell.normalize_scab(values: ndarray, method: str = 'rank') ndarray[source]¶
Normalise raw scA/B values per cell (row), over the finite entries of the row.
"rank": ranks (ties averaged) scaled to 0-1,(rank - 1) / (n - 1)(Dip-Ccolor_to_rank.py, Tan et al. 2021);"zscore": minus the row mean, over the row standard deviation;"none": unchanged. Rows with fewer than two finite values become NaN (except"none").