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: object

Knobs of call_compartments_axes_pc() (module docstring).

min_compartment_bp (ArcFISH min_cpmt_size; default 0 as in the authors’ tutorial); n_init / random_state of the k-means; a_cluster / a_track name the A compartment (else the authors’ rule); k_sigma / frac of uchrom.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).

a_cluster: int | None = None
a_track: str | None = None
frac: float = 0.1
k_sigma: float = 4.0
min_bins: int | None = None
min_compartment_bp: float = 0.0
n_clusters: int = 2
n_init: int = 1
random_state: int = 0
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: object

Knobs of call_compartments_eig() (defaults: cooltools eigs_cis).

ignore_diags: the diagonals next to the main one that are left out (set to the expected); None takes the value the map was balanced with (ignore_diags attribute 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_phasing reorders the eigenvectors of a region by decreasing absolute correlation with the track (cooltools sort_metric), which keeps a chromosome-arm or translocation eigenvector from being reported as E1.

clip_percentile: float = 99.9
dist_bin_ratio: float = 1.03
ignore_diags: int | None = None
phasing_method: str = 'spearman'
sort_by_phasing: bool = False
class uchrom.strc.comp.HiCCompartmentParams(n_distance_classes: int = 60, min_separation_bp: float = 31622.776601683792, balance: bool = False)[source]

Bases: object

Knobs 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_classes log-spaced classes from min_separation_bp to the largest separation, pairs closer than min_separation_bp in one class) — so uneven loci are handled.

balance: bool = False
min_separation_bp: float = 31622.776601683792
n_distance_classes: int = 60
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: object

Knobs of compartment_strength() (defaults: the Open2C saddle examples).

The bins are grouped by E1 between the quantiles qrange (or the values vrange) into n_bins groups plus one outlier group at each end; pairs closer than min_diag diagonals (and farther than max_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).

corner: float = 0.2
max_diag: int | None = None
min_diag: int = 3
qrange: Tuple[float, float] | None = (0.025, 0.975)
vrange: Tuple[float, float] | None = None
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: object

Knobs of single_cell_compartments() (defaults: Dip-C, Tan et al. 2021).

contacts: which contacts count — "all" (intra- and inter-chromosomal; Dip-C color2), "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-C color_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 when track is a FASTA ("cpg_frequency": Dip-C; "cpg_density", "gc_fraction"). empty: the value of a bin below min_contacts — "nan" (Dip-C) or "own", its own track value (scHiCluster).

check() → None[source]
contacts: str = 'all'
empty: str = 'nan'
min_contacts: int = 1
min_separation: int = 1
normalize: str = 'rank'
sequence_feature: str = 'cpg_frequency'
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.results key (default "compartments.axes_pc"); None does 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 with chrom and mid / pos / start, end; as uchrom.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 with end <= 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_index counts within the chromosome; eig_* the per-axis eigenvectors, pc2 their weighted sum oriented so that A > 0); with centromeres also region (<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 a DeprecationWarning and 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 first ignore_diags diagonals ignored, the contacts divided by their expected (mean over log-spaced classes of separation), clipped at the 99.9th percentile, and the leading eigenvectors of O/E - 1 taken (by absolute eigenvalue), each scaled by the square root of its eigenvalue. Each eigenvector is then flipped to correlate positively with the phasing track, so that E1 > 0 is the A (active, GC-rich, gene-rich) compartment. For a map whose loci are uneven (imaged segments), use call_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_map balances what it writes).

  • chrom (str, sequence of str, or None) – None: the chromosomes of cd that the map has (every map chromosome when cd has 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 a cd.bin_tracks column (gene density, an active mark), the key of a compartment table in cd.results (its E1: e.g. cell-type maps oriented like the all-cells map), or a DataFrame with chrom, start, end and one value column (value when 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 with chrom and mid / 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.results key (default "compartments.eig"); None does 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" where E1 > 0) and E1 .. En. When stored, also the eigenvalues per region (region, chrom, start, end, eigval1 .., phasing_r1 ..: the correlation of each eigenvector with the phasing track) as cd.results[f"{key_added}.eigvals"], the runs of equal label (broken at masked bins) as the segment table cd.intervals[key_added], and E1 on the loci of cd (the map bin holding each locus’ midpoint) as cd.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 of cd that the map has (every map chromosome when cd has no spots).

  • orient_by (str, optional) – A cd.bin_tracks column 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=True for the ICE-balanced matrix.

  • key_added (str or None) – cd.results key (default "compartments.hic_pc1"); None does 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" where pc1 > 0) and pc1. When stored, also the runs of equal label as the segment table cd.intervals[key_added] and PC1 on the loci of cd (the Hi-C bin holding each locus’ midpoint) as cd.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) of band (a uchrom.fea.band.read_band() of the whole chromosome). Valid bins are those with a positive balanced contact sum; the first ignore_diags diagonals are set to 1 (so to the expected); observed / expected uses the mean over classes of separation growing by dist_bin_ratio and the valid pairs only (pairs without contacts count as 0); values above the clip_percentile of all valid pairs are clipped; the matrix O/E - 1 of 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:
Returns:

n_bins (loci called by both), agreement (fraction of them with the same label) and pearson_r (correlation of the two scores).

Return type:

dict

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_bins and score (default pc2: its mean over the run’s bins). Stored as the segment interval table cd.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 of track into n_bins groups (plus an outlier group at each end); every cis pair of valid bins at least min_diag diagonals 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 / bottom corner fraction of bins (strength).

Parameters:
  • cd (ChromData, path or cooler.Cooler) – Holds the map link and the compartment call; a path / cooler (with compartments a 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.results key (default "compartments.eig") or a table with chrom, start, end and track. Each map bin takes the value of the call’s bin holding its midpoint.

  • track (str) – Column of compartments to 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.results key (a mapping); None does 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), sum and count (as cooltools: over both triangles, symmetrised), edges (the track values at the group edges), group_size (bins per group), strength_curve (by corner size k; index 0 NaN), corner_groups (the k of strength), 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; > 0 is A when a marker is 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-C color_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 k of a saddle (cooltools saddle_strength): (AA + BB) / (AB + BA) with the sums and counts of the k x k corners 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 into track) 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 into track) 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 into track) 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 into track) 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_contacts apply; 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 bins i != j adds the track value (CpG frequency) of j to i and that of i to j; 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 scHiCluster comp-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 cells and 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 .scool whose 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_feature of each bin, Dip-C’s CpG frequency by default; uchrom.fea.compute_sequence_features(); e.g. uchrom.datasets.fetch("mm10_genome")), a cd.bin_tracks column, the key of a compartment table in cd.results (its E1), a DataFrame chrom, 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 (column track): pass that table to skip the FASTA next time.

  • cells (sequence of cell ids, optional) – Cells to compute (default: every cell of cd.cells with 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.cellm key (default "compartments.scab"); None does 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 than params.min_contacts contacts with partners that have a track value. When stored: the matrix for every cell of cd.cells as cd.cellm[key_added] (NaN rows for cells not computed), the bins as the table cd.results[key_added] (chrom, start, end, track, n_cells — cells with a value —, mean, sd over the cells; row k = column k of the matrix) with the call’s provenance, and per cell cd.cells[f"{key_added}.n_contacts"] (contacts counted) and cd.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: object

Knobs of call_compartments_axes_pc() (module docstring).

min_compartment_bp (ArcFISH min_cpmt_size; default 0 as in the authors’ tutorial); n_init / random_state of the k-means; a_cluster / a_track name the A compartment (else the authors’ rule); k_sigma / frac of uchrom.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).

a_cluster: int | None = None
a_track: str | None = None
frac: float = 0.1
k_sigma: float = 4.0
min_bins: int | None = None
min_compartment_bp: float = 0.0
n_clusters: int = 2
n_init: int = 1
random_state: int = 0
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.results key (default "compartments.axes_pc"); None does 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 with chrom and mid / pos / start, end; as uchrom.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 with end <= 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_index counts within the chromosome; eig_* the per-axis eigenvectors, pc2 their weighted sum oriented so that A > 0); with centromeres also region (<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 a DeprecationWarning and 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: object

Knobs of call_compartments_eig() (defaults: cooltools eigs_cis).

ignore_diags: the diagonals next to the main one that are left out (set to the expected); None takes the value the map was balanced with (ignore_diags attribute 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_phasing reorders the eigenvectors of a region by decreasing absolute correlation with the track (cooltools sort_metric), which keeps a chromosome-arm or translocation eigenvector from being reported as E1.

clip_percentile: float = 99.9
dist_bin_ratio: float = 1.03
ignore_diags: int | None = None
phasing_method: str = 'spearman'
sort_by_phasing: bool = False
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 first ignore_diags diagonals ignored, the contacts divided by their expected (mean over log-spaced classes of separation), clipped at the 99.9th percentile, and the leading eigenvectors of O/E - 1 taken (by absolute eigenvalue), each scaled by the square root of its eigenvalue. Each eigenvector is then flipped to correlate positively with the phasing track, so that E1 > 0 is the A (active, GC-rich, gene-rich) compartment. For a map whose loci are uneven (imaged segments), use call_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_map balances what it writes).

  • chrom (str, sequence of str, or None) – None: the chromosomes of cd that the map has (every map chromosome when cd has 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 a cd.bin_tracks column (gene density, an active mark), the key of a compartment table in cd.results (its E1: e.g. cell-type maps oriented like the all-cells map), or a DataFrame with chrom, start, end and one value column (value when 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 with chrom and mid / 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.results key (default "compartments.eig"); None does 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" where E1 > 0) and E1 .. En. When stored, also the eigenvalues per region (region, chrom, start, end, eigval1 .., phasing_r1 ..: the correlation of each eigenvector with the phasing track) as cd.results[f"{key_added}.eigvals"], the runs of equal label (broken at masked bins) as the segment table cd.intervals[key_added], and E1 on the loci of cd (the map bin holding each locus’ midpoint) as cd.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: object

Knobs of compartment_strength() (defaults: the Open2C saddle examples).

The bins are grouped by E1 between the quantiles qrange (or the values vrange) into n_bins groups plus one outlier group at each end; pairs closer than min_diag diagonals (and farther than max_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).

corner: float = 0.2
max_diag: int | None = None
min_diag: int = 3
qrange: Tuple[float, float] | None = (0.025, 0.975)
vrange: Tuple[float, float] | None = None
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 of track into n_bins groups (plus an outlier group at each end); every cis pair of valid bins at least min_diag diagonals 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 / bottom corner fraction of bins (strength).

Parameters:
  • cd (ChromData, path or cooler.Cooler) – Holds the map link and the compartment call; a path / cooler (with compartments a 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.results key (default "compartments.eig") or a table with chrom, start, end and track. Each map bin takes the value of the call’s bin holding its midpoint.

  • track (str) – Column of compartments to 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.results key (a mapping); None does 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), sum and count (as cooltools: over both triangles, symmetrised), edges (the track values at the group edges), group_size (bins per group), strength_curve (by corner size k; index 0 NaN), corner_groups (the k of strength), 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) of band (a uchrom.fea.band.read_band() of the whole chromosome). Valid bins are those with a positive balanced contact sum; the first ignore_diags diagonals are set to 1 (so to the expected); observed / expected uses the mean over classes of separation growing by dist_bin_ratio and the valid pairs only (pairs without contacts count as 0); values above the clip_percentile of all valid pairs are clipped; the matrix O/E - 1 of 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: object

Knobs of single_cell_compartments() (defaults: Dip-C, Tan et al. 2021).

contacts: which contacts count — "all" (intra- and inter-chromosomal; Dip-C color2), "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-C color_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 when track is a FASTA ("cpg_frequency": Dip-C; "cpg_density", "gc_fraction"). empty: the value of a bin below min_contacts — "nan" (Dip-C) or "own", its own track value (scHiCluster).

check() → None[source]
contacts: str = 'all'
empty: str = 'nan'
min_contacts: int = 1
min_separation: int = 1
normalize: str = 'rank'
sequence_feature: str = 'cpg_frequency'
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 bins i != j adds the track value (CpG frequency) of j to i and that of i to j; 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 scHiCluster comp-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 cells and 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 .scool whose 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_feature of each bin, Dip-C’s CpG frequency by default; uchrom.fea.compute_sequence_features(); e.g. uchrom.datasets.fetch("mm10_genome")), a cd.bin_tracks column, the key of a compartment table in cd.results (its E1), a DataFrame chrom, 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 (column track): pass that table to skip the FASTA next time.

  • cells (sequence of cell ids, optional) – Cells to compute (default: every cell of cd.cells with 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.cellm key (default "compartments.scab"); None does 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 than params.min_contacts contacts with partners that have a track value. When stored: the matrix for every cell of cd.cells as cd.cellm[key_added] (NaN rows for cells not computed), the bins as the table cd.results[key_added] (chrom, start, end, track, n_cells — cells with a value —, mean, sd over the cells; row k = column k of the matrix) with the call’s provenance, and per cell cd.cells[f"{key_added}.n_contacts"] (contacts counted) and cd.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 into track) 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 into track) 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 into track) 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 into track) 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_contacts apply; 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-C color_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.eig.saddle_strength(S: ndarray, C: ndarray) → ndarray[source]

Compartment strength for every corner extent k of a saddle (cooltools saddle_strength): (AA + BB) / (AB + BA) with the sums and counts of the k x k corners pooled; index 0 is NaN.