uchrom.recon

Single-cell reconstruction

EMber: noise-aware single-cell Hi-C 3-D genome reconstruction.

EMber (EM + annealing / sampling) is the native engine’s protocol "robust" (uchrom_recon; packages/uchrom-recon/src/robust.rs): the NucDynamics 2017 hierarchical annealing with a mixture observation model — every contact is a true proximity or a false contact (rate ε), contact restraints are re-weighted by their posterior probability of being true (EM; ε and the contact-kernel width learned from the data, plus structure-free local-support evidence) — a short schedule (2,500 MD steps per stage), a sampling stage at finite temperature (calibrated ensembles) and adaptive resolution below 25 kb.

It was pre-registered, developed on a development set, frozen (tag robust-frozen) and tested once against NucDynamics (an unpublished design note, TEST_RESULTS.md). The defaults below are the frozen method.

from uchrom.recon.sc import reconstruct_ember cd = reconstruct_ember(“cell1.pairs”, n_models=10, device=”auto”) cd.layers[“model_0”] # one model per layer cd.results[“ember.contact_weights”] # posterior weight of every input contact

Phased (homolog-resolved) contacts — hickit .pairs with phase0 / phase1, Dip-C .con — give a diploid reconstruction: one particle chain per chromosome copy, the copy pair of every contact with an unphased end inferred by EM from the structure (the copy pair is a latent variable of the same mixture model):

cd = reconstruct_ember("cell.contacts.pairs.gz", ploidy="auto")   # traces chr1(pat), chr1(mat), ...
cd.results["ember.imputed_phase"]           # most probable (hap_a, hap_b) of every contact

The diploid extension is new (not part of the frozen, pre-registered test); its haploid behaviour is unchanged.

uchrom.recon.sc.ember.EMBER_PROTOCOL = 'robust'

engine protocol implementing EMber

uchrom.recon.sc.ember.reconstruct_ember(contacts: str | PathLike | DataFrame, *, chrom: None | str | Sequence[str] = None, n_models: int = 10, params: Mapping[str, Any] | None = None, device: str = 'auto', n_threads: int = 0, seed: int = 0, particle_sizes: Sequence[float] = (8000000.0, 4000000.0, 2000000.0, 400000.0, 200000.0, 100000.0), cell_id: str | None = None, key_added: str | None = 'ember', copy: bool = False, verbose: bool = False, ploidy: Any = None, hap_names: Sequence[str] = ('pat', 'mat'), phase_prior: bool = False, **engine_params: Any)[source]

Single-cell Hi-C genome structure ensemble with EMber.

Parameters:
  • contacts – Path (.ncc, .pairs[.gz], GEO chr_A pos_A chr_B pos_B table) or DataFrame of contacts (see uchrom.recon.sc.nucdyn.load_contacts()).

  • chrom – None (default): the whole genome. A chromosome name / range ("chr19", "chr1:1000000-5000000") or a list of them restricts the contacts to those regions (calling convention: chrom=None runs everything).

  • n_models – Models (structures) in the ensemble.

  • params – Engine parameters overriding the frozen defaults (see uchrom_recon.default_params(); the robust_* fields are EMber’s); keyword arguments are merged into it.

  • device – "auto" (GPU when available), "cpu" (f64, multi-core) or "gpu" (f32, wgpu).

  • n_threads – As uchrom.recon.sc.nucdyn.reconstruct_nucdyn().

  • seed – As uchrom.recon.sc.nucdyn.reconstruct_nucdyn().

  • particle_sizes – As uchrom.recon.sc.nucdyn.reconstruct_nucdyn().

  • cell_id – As uchrom.recon.sc.nucdyn.reconstruct_nucdyn().

  • verbose – As uchrom.recon.sc.nucdyn.reconstruct_nucdyn().

  • key_added – Key of cd.uns[key_added] (method, engine, protocol, parameters) and of the results <key>.stages / <key>.em (EM log) / <key>.contact_weights; None stores neither.

  • copy – Reconstruction always creates a new ChromData from the contacts; accepted for the calling convention (no effect).

  • ploidy – Phased (diploid) input, see uchrom.recon.sc.nucdyn.reconstruct_nucdyn(): copies per chromosome (None = "auto": male when chrY is present; "haploid" ignores the phases), haplotype names in the trace ids, and whether hickit’s imputed phase probabilities (when present) are used as an extra prior of the copy pairs (default False: the frozen configuration, EMber’s own neighbourhood prior only; an unpublished design note §6). Adds the results <key>.phase_probs / <key>.imputed_phase and uns[key]["diploid"] (phasing statistics).

  • hap_names – Phased (diploid) input, see uchrom.recon.sc.nucdyn.reconstruct_nucdyn(): copies per chromosome (None = "auto": male when chrY is present; "haploid" ignores the phases), haplotype names in the trace ids, and whether hickit’s imputed phase probabilities (when present) are used as an extra prior of the copy pairs (default False: the frozen configuration, EMber’s own neighbourhood prior only; an unpublished design note §6). Adds the results <key>.phase_probs / <key>.imputed_phase and uns[key]["diploid"] (phasing statistics).

  • phase_prior – Phased (diploid) input, see uchrom.recon.sc.nucdyn.reconstruct_nucdyn(): copies per chromosome (None = "auto": male when chrY is present; "haploid" ignores the phases), haplotype names in the trace ids, and whether hickit’s imputed phase probabilities (when present) are used as an extra prior of the copy pairs (default False: the frozen configuration, EMber’s own neighbourhood prior only; an unpublished design note §6). Adds the results <key>.phase_probs / <key>.imputed_phase and uns[key]["diploid"] (phasing statistics).

Returns:

One spot per particle; coords = model 0, layers['model_<k>'] = every model; units: particle radii. Same layout as uchrom.recon.sc.nucdyn.reconstruct_nucdyn() with protocol="robust" (identical coordinates for the same seed).

Return type:

ChromData

NucDynamics: single-cell Hi-C genome structure calculation.

reconstruct_nucdyn(contacts, ...) returns a ChromData ensemble computed by the native engine (uchrom_recon: Rust, multi-core CPU and wgpu GPU; pip install u-chrom[recon]). main (also python -m uchrom.recon.sc.nucdyn) is the file-level entry point.

uchrom.recon.sc.nucdyn.engine_info() → Dict[str, Any][source]

Version of the native engine and the GPU it would use.

uchrom.recon.sc.nucdyn.load_contacts(contacts, genome_ranges=None) → Dict[str, ndarray][source]

Contacts as arrays chrom_a, pos_a, chrom_b, pos_b, ambiguity, active.

contacts is a path (.ncc as written by NucProcess; .pairs / .pairs.gz; a whitespace table chr_A pos_A chr_B pos_B such as the GEO files of Stevens et al. 2017) or a DataFrame with columns chr1, pos1, chr2, pos2 (as uchrom.io.read_pairs() returns) or chrom1, pos1, chrom2, pos2; optional ambiguity / active. genome_ranges keeps only contacts with both ends in the given ranges ("chr19", "chr1:1000000-5000000", or a list).

Phased (homolog-resolved) contacts add hap_a / hap_b (int8: 0, 1, -1 = unknown) and, for hickit’s imputed pairs, phase_prob ((n, 4), index 2 hap_a + hap_b): files for which is_phased_file() is true (hickit .pairs with phase0 / phase1; Dip-C .con), or DataFrames with hap1 / hap2 (or phase0 / phase1; . = unknown) and optionally phase_prob00 .. phase_prob11 (uchrom.io.read_phased_pairs()).

uchrom.recon.sc.nucdyn.main(in_file, out_file, arch='gpu', device_memory_fraction=0.9, cell_id=None, engine='auto', n_models=None, device=None, n_threads=0, seed=None, protocol='nuc_dynamics_2017', size_steps=None, genome_ranges=None, **kwargs)[source]

Calculate a single-cell genome structure from contacts and write it.

in_file: contacts (.pairs[.gz], .ncc, GEO contact table). out_file: .chromdata.zarr / .cdz / .h5cd (the whole ensemble: coords = model 0, layers['model_<k>'] = every model) or .csv (model 0 only).

engine: the native engine (uchrom_recon; "auto" / "native"). The Taichi port ("taichi") was removed: it needs u-chrom 0.2 from before the monorepo (commit 0063b92). device (auto / cpu / gpu) defaults from arch (cpu -> cpu; gpu / cuda / metal -> gpu). size_steps: particle sizes in Mb (default 8 4 2 0.4 0.2 0.1). Other keyword arguments: native engine parameters, or those of the former Taichi port (dyns, hot, cold, random_seed, … are mapped to the native ones).

uchrom.recon.sc.nucdyn.native_available() → bool[source]

True when the native engine (uchrom_recon) can be imported.

uchrom.recon.sc.nucdyn.reconstruct_nucdyn(contacts: str | PathLike | DataFrame, *, n_models: int = 10, device: str = 'auto', n_threads: int = 0, seed: int = 0, protocol: str = 'nuc_dynamics_2017', particle_sizes: Sequence[float] = (8000000.0, 4000000.0, 2000000.0, 400000.0, 200000.0, 100000.0), genome_ranges=None, cell_id: str | None = None, key_added: str | None = 'nucdyn', params: Mapping[str, Any] | None = None, verbose: bool = False, ploidy: Any = None, hap_names: Sequence[str] = ('pat', 'mat'), phase_prior: bool = False, _method: str = 'nucdyn', **engine_params: Any)[source]

Single-cell Hi-C genome structure ensemble with NucDynamics.

Runs the hierarchical simulated-annealing protocol of NucDynamics (Stevens et al. 2017, Nature 544:59) on the native engine and returns the ensemble as a new ChromData.

Parameters:
  • contacts – Path (.ncc, .pairs[.gz], GEO chr_A pos_A chr_B pos_B table) or DataFrame of contacts, see load_contacts().

  • n_models – Number of structures (models) in the ensemble. All models are computed at once (in parallel on the CPU, in one batch on the GPU).

  • device – "auto" (GPU when available, else CPU), "cpu" (f64, multi-core) or "gpu" (f32, wgpu: Metal / Vulkan / DX12).

  • n_threads – CPU worker threads (0 = all cores).

  • seed – Random seed (start coordinates and velocities); on the CPU a seed gives bitwise-identical results.

  • protocol – "nuc_dynamics_2017" (default): the code that produced the published 2017 structures (tjs23/nuc_dynamics master). "release_1.3": the later bead-size-scaled version with ambiguity resolution and model selection (2 x n_models above 1 Mb, the n_models closest to the mean kept). "robust" (public name EMber, alias "ember"; see uchrom.recon.sc.ember.reconstruct_ember()): the 2017 protocol with a noise-aware observation model (contact restraints re-weighted by their posterior probability of being true contacts; false-contact rate and contact-kernel width learned by EM; robust_* engine parameters). Adds the results <key_added>.em (EM log) and <key_added>.contact_weights (final weight of every input contact, NaN = filtered out).

  • particle_sizes – Hierarchical particle sizes in bp (coarse to fine).

  • genome_ranges – Restrict the contacts to these ranges (e.g. "chr19").

  • cell_id – Written to spots['cell_id'].

  • key_added – Key of the provenance record in cd.results (per-stage log) and of cd.uns[key_added]; None stores neither.

  • params – Further engine parameters (see uchrom_recon.default_params(): temp_steps, dynamics_steps, temp_start, temp_end, time_step, contact_dist_lower, …); keyword arguments are merged into it.

  • ploidy – Phased (homolog-resolved) contacts — hickit .pairs with phase0 / phase1, Dip-C .con, a DataFrame with hap1 / hap2 (see load_contacts()) — are reconstructed as a diploid genome (protocols "nuc_dynamics_2017" and "robust" / EMber): one particle chain per chromosome copy, contacts with an unphased end ambiguous between the candidate copies (2017: NucDynamics ambiguous restraint; EMber: the copy pair is inferred by EM from the structure). ploidy gives the copies per chromosome: None / "auto" (male — X and Y single copy — when a Y chromosome is present, as hickit), "diploid", "male", a dict {chrom: 1 | 2}, or "haploid" (ignore the phases: one chain per chromosome).

  • hap_names – Names of haplotypes 0 and 1 in the trace ids (default Dip-C’s ("pat", "mat"): traces chr1(pat) / chr1(mat); single-copy chromosomes keep the plain name).

  • phase_prior – Also use hickit’s imputed phase_prob00 .. phase_prob11 (when present) as a prior over the candidate copy pairs (default False, the frozen diploid EMber configuration: EMber’s own 2-D neighbourhood prior robust_dip_nbr_prior only, no external prior).

Returns:

One spot per particle; one trace per chromosome (diploid: per chromosome copy, spot column haplotype = 0 / 1; both copies share the bins). coords holds model 0 and layers['model_<k>'] holds every model k (model 0 included), so the whole ensemble travels with the object. Units are particle radii. Bins are the particles’ genomic intervals: in the 2017 protocol a particle at sequence position p collects the contacts in (p - size, p] (bins.start = p - size, bins.end = p); in release_1.3 [p, p + size). uns[key_added] records the engine, protocol, parameters and per-stage log.

Return type:

ChromData

Bulk reconstruction (MDS)

MDS-based 3-D structure of a bulk Hi-C map (GPU-accelerated with PyTorch).

reconstruct_mds() runs on a ChromData with a linked map (or a path) and returns the structure as a ChromData; run_mds(), partitioned_mds() and inter_mds() are the matrix-level kernels.

uchrom.recon.bulk.mds.apply_distance_decay_prior(contact_mat, weight=0.05)[source]

Apply distance decay prior to smooth contact frequencies. Expected values computed from nonzero contacts only (matching miniMDS).

uchrom.recon.bulk.mds.apply_transform(coords, rotation=None, translation=None, scale=1.0)[source]

Apply rotation, translation and scaling.

uchrom.recon.bulk.mds.compute_radius_of_gyration(coords)[source]

Rg = sqrt(mean(||x - centroid||^2)).

uchrom.recon.bulk.mds.compute_stress(coords, dist_mat, weights=None)[source]

Compute MDS stress, skipping missing-data pairs (dist_mat == 0).

uchrom.recon.bulk.mds.contact_to_distance(contact_mat, alpha=4.0)[source]

Convert contact frequencies to distances: d = c^(-1/alpha). Zero contacts are treated as missing data (distance = 0).

uchrom.recon.bulk.mds.fill_missing_distances(dist_mat, contact_mat=None)[source]

Fill zero (missing) distances using genomic distance prior. After contact_to_distance, zeros represent missing data, not zero distance.

uchrom.recon.bulk.mds.inter_mds(input_path, resolution_inter=1000000, resolution_intra=100000, chroms=None, alpha=4.0, weight=0.05, n_iter=1000, device='auto', output_dir=None, verbose=True)[source]

Whole-genome 3D reconstruction with inter-chromosomal contacts.

Parameters:
  • input_path – Path to .hic or .mcool file

  • resolution_inter – Resolution for inter-chromosomal scaffold (default 1Mb)

  • resolution_intra – Resolution for intra-chromosomal structures (default 100kb)

  • chroms – List of chromosomes (default: autosomes + X)

  • alpha – Contact-to-distance exponent

  • weight – Distance decay prior weight

  • n_iter – MDS iterations

  • device – ‘auto’, ‘cpu’, ‘cuda’, ‘mps’

  • output_dir – Output directory (None = don’t save)

  • verbose – Print progress

Returns:

DataFrame with chrom, start, end, x, y, z for all bins

Return type:

genome_df

uchrom.recon.bulk.mds.normalize_distances(dist_mat)[source]

Normalize distance matrix to have unit mean. Includes zeros in mean calculation to match miniMDS behavior (miniMDS divides by np.mean(distMat) which includes zeros).

uchrom.recon.bulk.mds.partitioned_mds(contact_mat, tad_regions=None, device='auto', res_ratio=10, alpha=4.0, alpha2=2.5, weight=0.05, n_iter=1000, verbose=False, n_workers=1)[source]

Partitioned MDS for high-resolution Hi-C data.

uchrom.recon.bulk.mds.procrustes_alignment(source, target, scale=True)[source]

Align source to target using SVD-based Procrustes analysis.

uchrom.recon.bulk.mds.reconstruct_mds(cd: Any, *, contacts: str | None = None, chrom: None | str | Sequence[str] = None, resolution: int | None = None, balance: bool = True, mode: str = 'intra', alpha: float = 4.0, weight: float = 0.05, method: str = 'smacof', n_iter: int = 1000, lr: float = 0.01, tol: float = 1e-06, device: str = 'auto', cell_id: str | None = None, key_added: str | None = 'mds', verbose: bool = False, **mode_kw: Any)[source]

A consensus 3-D structure of a bulk Hi-C map by multidimensional scaling.

Every chromosome is reconstructed from its balanced intra-chromosomal matrix: bins without contacts are dropped, the map is smoothed with a distance-decay prior (weight), contacts become distances d = c^(-1/alpha) (mean 1), and the stress is minimised by SMACOF from a classical-MDS start (method="adam": autograd + Adam on the same stress) — run_mds(), PyTorch on the CPU, CUDA or Apple MPS.

hic = ds.load("rao2014_imr90_chr21")                  # the 5 kb map, linked as "bulk"
rebin_map(hic, "bulk", resolution=100_000)             # -> "bulk_100kb" (ICE-balanced)
mds = reconstruct_mds(hic, contacts="bulk_100kb")
Parameters:
  • cd – A ChromData with the map linked (cd.link_cool), or the path of a .cool / .mcool.

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

  • chrom – Chromosome(s) (default: every chromosome of the map); each becomes one trace.

  • resolution – The level of an .mcool (a .cool must be at it; uchrom.fea.rebin_map() makes coarser maps).

  • balance – Use the balanced matrix (weight column).

  • mode – "intra" (default; chromosomes independently), "partitioned" (TAD-wise divide and conquer at high resolution, partitioned_mds(); mode_kw: res_ratio, alpha2, n_workers, tad_regions) or "inter" (whole genome placed by the inter-chromosomal contacts, inter_mds(); mode_kw: resolution_inter; a .hic or .mcool).

  • alpha – Contact-to-distance exponent, distance-decay prior weight and the solver (see run_mds()).

  • weight – Contact-to-distance exponent, distance-decay prior weight and the solver (see run_mds()).

  • method – Contact-to-distance exponent, distance-decay prior weight and the solver (see run_mds()).

  • n_iter – Contact-to-distance exponent, distance-decay prior weight and the solver (see run_mds()).

  • lr – Contact-to-distance exponent, distance-decay prior weight and the solver (see run_mds()).

  • tol – Contact-to-distance exponent, distance-decay prior weight and the solver (see run_mds()).

  • device – "auto" (CUDA / MPS when available, float32 there), "cpu", "cuda", "mps".

  • cell_id – spots["cell_id"] of the structure (e.g. the sample).

  • key_added – uns key of the settings and results["<key_added>.chroms"] (bins kept and time per chromosome); None stores neither.

  • verbose – Print the solver’s progress.

Returns:

One spot per kept bin, one trace per chromosome; coordinates in arbitrary units (mean target distance 1); uns["xyz_unit"] = "arbitrary (MDS)".

Return type:

ChromData

uchrom.recon.bulk.mds.run_mds(contact_mat, alpha=4.0, device='auto', weight=0.05, **kwargs)[source]

Full MDS pipeline: contact matrix -> 3D coordinates.

Zero-contact bins (rows/columns with no observed contacts) are removed before MDS, matching miniMDS behavior. Returns coordinates only for non-zero bins.

Returns:

np.ndarray of shape (n_nonzero, 3) nonzero_mask: np.ndarray boolean mask of shape (n_total,), indicating which bins were kept

Return type:

coords

uchrom.recon.bulk.mds.torch_mds.cmds_init(dist_mat)[source]

Classical MDS initialization via eigendecomposition.

uchrom.recon.bulk.mds.torch_mds.compute_stress(coords, dist_mat, weights=None)[source]

Compute MDS stress, skipping missing-data pairs (dist_mat == 0).

uchrom.recon.bulk.mds.torch_mds.get_device(device='auto')[source]

Get appropriate torch device.

uchrom.recon.bulk.mds.torch_mds.get_dtype(device)[source]

MPS only supports float32.

uchrom.recon.bulk.mds.torch_mds.run_mds(contact_mat, alpha=4.0, device='auto', weight=0.05, **kwargs)[source]

Full MDS pipeline: contact matrix -> 3D coordinates.

Zero-contact bins (rows/columns with no observed contacts) are removed before MDS, matching miniMDS behavior. Returns coordinates only for non-zero bins.

Returns:

np.ndarray of shape (n_nonzero, 3) nonzero_mask: np.ndarray boolean mask of shape (n_total,), indicating which bins were kept

Return type:

coords

uchrom.recon.bulk.mds.torch_mds.smacof(dist_mat, device='auto', n_iter=1000, tol=1e-06, init='cmds', verbose=False)[source]

Run SMACOF (Scaling by MAjorizing a Complicated Function) MDS.

Unlike the Adam-based approach, SMACOF uses a majorization algorithm that does not require autograd, resulting in much lower per-iteration overhead on CPU.

uchrom.recon.bulk.mds.torch_mds.torch_mds(dist_mat, device='auto', n_iter=1000, lr=0.01, tol=1e-06, init='cmds', verbose=False, method='smacof')[source]

Run iterative MDS.

Parameters:

method – ‘smacof’ (default, fast) or ‘adam’ (gradient descent).

uchrom.recon.bulk.mds.inter.inter_mds(input_path, resolution_inter=1000000, resolution_intra=100000, chroms=None, alpha=4.0, weight=0.05, n_iter=1000, device='auto', output_dir=None, verbose=True)[source]

Whole-genome 3D reconstruction with inter-chromosomal contacts.

Parameters:
  • input_path – Path to .hic or .mcool file

  • resolution_inter – Resolution for inter-chromosomal scaffold (default 1Mb)

  • resolution_intra – Resolution for intra-chromosomal structures (default 100kb)

  • chroms – List of chromosomes (default: autosomes + X)

  • alpha – Contact-to-distance exponent

  • weight – Distance decay prior weight

  • n_iter – MDS iterations

  • device – ‘auto’, ‘cpu’, ‘cuda’, ‘mps’

  • output_dir – Output directory (None = don’t save)

  • verbose – Print progress

Returns:

DataFrame with chrom, start, end, x, y, z for all bins

Return type:

genome_df

uchrom.recon.bulk.mds.transforms.align_substructure_to_scaffold(high_res_coords, low_res_coords, scaffold_coords, res_ratio=10)[source]

Align high-res substructure to global scaffold via Procrustes.

uchrom.recon.bulk.mds.transforms.apply_transform(coords, rotation=None, translation=None, scale=1.0)[source]

Apply rotation, translation and scaling.

uchrom.recon.bulk.mds.transforms.center_coords(coords)[source]

Center coordinates to zero mean.

uchrom.recon.bulk.mds.transforms.compute_radius_of_gyration(coords)[source]

Rg = sqrt(mean(||x - centroid||^2)).

uchrom.recon.bulk.mds.transforms.downsample_coords(coords, res_ratio, method='mean')[source]

Downsample coordinates by resolution ratio.

uchrom.recon.bulk.mds.transforms.procrustes_alignment(source, target, scale=True)[source]

Align source to target using SVD-based Procrustes analysis.

Bulk reconstruction (IGM population models)

Deconvolution of population (bulk) Hi-C into a population of structures.

deconvolve(...) dispatches to a method subpackage:

  • method="igm" — uchrom.recon.bulk.deconv.igm, the A/M population modelling of IGM (Boninsegna et al. 2022, Nat Methods 19:938; predecessor PGS, Tjong et al. 2016 PNAS 113:E1663, Hua et al. 2018 Nat Protoc 13:915) on the native engine (uchrom_recon, protocol igm; multi-core CPU or GPU).

A later method="pgs" will live next to it. The shared Hi-C → contact-probability preprocessing is uchrom.recon.bulk.deconv.preprocess.

from uchrom.recon.bulk.deconv import deconvolve, preprocess_hic
prob = preprocess_hic(cd, contacts="bulk", chroms=["chr21"])     # a ChromData with a linked Hi-C map
pop = deconvolve(prob, method="igm", n_structures=1000, out="pop.chromdata.zarr")
pop.get_cell("s00000")          # one structure: one trace per chromosome copy
class uchrom.recon.bulk.deconv.IgmParams(n_structures: int = 10000, ploidy: str | ~typing.Dict[str, int]='diploid', occupancy: float | None = None, nucleus_shape: str = 'sphere', nucleus_radius: float = 5000.0, nucleus_semiaxes: List[float] = <factory>, init_radius: float = 0.0, contact_range: float = 2.0, evfactor: float = 1.0, contact_kspring: float = 1.0, polymer_kspring: float = 1.0, nucleus_kspring: float = 1.0, polymer_bonds_style: str = 'simple', stages: Dict[str, float]]=<factory>, relax: Dict[str, float] | None=<factory>, timestep: float = 0.25, max_velocity: float = 1000.0, rescale_window: float = 0.1, rescale_fraction: float = 1.0, cg_etol: float = 0.0001, cg_ftol: float = 1e-06, cg_max_iter: int = 500, cg_max_eval: int = 500, cg_dmax: float = 0.1, intra_sigma_list: List[float] = <factory>, inter_sigma_list: List[float] = <factory>, max_violations: float = 0.01, violation_tolerance: float = 0.05, min_iterations: int = 5, max_iterations: int = 10, force_last_iteration: bool = False, force_minimum_iterations_hic_cutoff: float = 0.0, random_shuffling: bool = False, skip_relax_init: bool = False, n_threads: int = 0, batch_size: int = 0, verbose: bool = False, bead_radius: float | None = None, occupancy_scope: str | float = 'model', iterative_correction: bool = True, assignment_pooling: str = 'igm', init_noise: float = 0.0)[source]

Bases: object

IGM population modelling parameters.

Defaults: the IGM configuration schema with the annealing protocol of the IGM demo (an unpublished design note §2.2, §3.2, §4.3, §5, §6.2); the user-level defaults of U-Chrom are 10,000 structures (1 Mb bins) — for the IGM paper setting (200 kb, 1,000 structures, 40 % occupancy, prolate ellipsoid) see boninsegna2022().

ploidy: "diploid" (every chromosome twice, as IGM’s default), "male" (autosomes ×2, X and Y ×1), "haploid", or a dict {chrom: copies}.

Opt-in options (IGM-Plus / IGM_2.0; every default is the IGM 1.0 behaviour, see packages/uchrom-recon/README.md):

occupancy / bead_radius

Bead radii from the genome-to-nucleus volume occupancy (default 0.2 when neither is given) or one radius in nm for every bead (IGM-Plus model/bead_radius); mutually exclusive.

occupancy_scope

What the occupancy refers to when only some chromosomes are modelled (deconvolve(..., chrom=)): "model" (default; the modelled chromosomes fill occupancy of the whole nucleus, as IGM / IGM-Plus compute it), "genome" (all bins of the input, times their copies: beads keep their whole-genome size and the modelled chromosomes occupy their share of the nucleus), or a genome size in bp (all copies).

iterative_correction

False: the A-step uses p = f instead of the iteratively corrected probability (IGM-Plus iter_corr_knob = 0).

assignment_pooling

"igm" (IGM 1.0) or "gp" (G. Polles’ approximation, IGM_2.0 GP_ActivationDistanceStep: all copy combinations pooled, n_possible = min(copies) smallest per structure) — for the sensitivity analysis of an unpublished design note.

init_noise

Gaussian noise (nm, standard deviation) added to every initial coordinate (IGM-Plus model/init_noise; with deconvolve(..., init_positions=)).

assignment_pooling: str = 'igm'
batch_size: int = 0
bead_radius: float | None = None
classmethod boninsegna2022(**kw: Any) → IgmParams[source]

The IGM paper’s HFFc6 setting: 1,000 structures, 40 % occupancy, prolate ellipsoid (7,840, 6,470, 2,450) nm (use with 200 kb bins).

cg_dmax: float = 0.1
cg_etol: float = 0.0001
cg_ftol: float = 1e-06
cg_max_eval: int = 500
cg_max_iter: int = 500
contact_kspring: float = 1.0
contact_range: float = 2.0
property effective_occupancy: float | None

The occupancy used (None when bead_radius sets the radii).

evfactor: float = 1.0
force_last_iteration: bool = False
force_minimum_iterations_hic_cutoff: float = 0.0
init_noise: float = 0.0
init_radius: float = 0.0
inter_sigma_list: List[float]
intra_sigma_list: List[float]
iterative_correction: bool = True
max_iterations: int = 10
max_velocity: float = 1000.0
max_violations: float = 0.01
min_iterations: int = 5
n_structures: int = 10000
n_threads: int = 0
nucleus_kspring: float = 1.0
nucleus_radius: float = 5000.0
nucleus_semiaxes: List[float]
nucleus_shape: str = 'sphere'
occupancy: float | None = None

None = 0.2 unless bead_radius is given

occupancy_scope: str | float = 'model'
ploidy: str | Dict[str, int] = 'diploid'
polymer_bonds_style: str = 'simple'
polymer_kspring: float = 1.0
random_shuffling: bool = False
relax: Dict[str, float] | None
replace(**kw: Any) → IgmParams[source]

A copy with fields replaced; giving bead_radius alone drops the occupancy (and vice versa), since the two are mutually exclusive.

rescale_fraction: float = 1.0
rescale_window: float = 0.1
skip_relax_init: bool = False
stages: List[Dict[str, float]]
timestep: float = 0.25
to_native() → Dict[str, Any][source]

Fields understood by uchrom_recon.calc_population (without ploidy and occupancy_scope, which the caller resolves to occupancy_total_bp).

verbose: bool = False
violation_tolerance: float = 0.05
uchrom.recon.bulk.deconv.METHODS = ('igm',)

Available methods.

uchrom.recon.bulk.deconv.deconvolve(data: Any = None, *, method: str = 'igm', **kwargs: Any)[source]

Fit a population of structures to a contact-probability matrix.

Parameters:
  • data – The ProbabilityMatrix of preprocess_hic() (matrix and bins), a haploid contact-probability matrix (scipy.sparse or dense, bins × bins; pass bins=), or a ChromData whose bins define the loci (pass the matrix as probabilities=).

  • method – "igm" (default). The remaining keywords go to the method (uchrom.recon.bulk.deconv.igm.deconvolve_igm()).

Returns:

  • ChromData (in memory, or backed on ``out=``) (one cell per structure,)

  • one trace per chromosome copy.

uchrom.recon.bulk.deconv.deconvolve_igm(data: Any = None, *, probabilities: Any = None, bins: DataFrame | None = None, chrom: str | Sequence[str] | None = None, params: IgmParams | None = None, device: str = 'auto', seed: int = 0, out: str | PathLike | None = None, keep_intermediate: bool = False, key_added: str | None = 'deconv.igm', progress: Any | None = None, init_positions: DataFrame | None = None, **overrides: Any)[source]

IGM population modelling of a contact-probability matrix.

The defaults run the faithful IGM 1.0 protocol. Opt-in options from IGM-Plus (alberlab/IGM-Plus v2.0.2) and IGM_2.0 (fields of IgmParams, also accepted as keyword overrides): chrom= with occupancy_scope (chromosome-subset models), bead_radius (radii set directly, exclusive with occupancy), iterative_correction=False, assignment_pooling="gp", init_positions + init_noise (expanded initialisation). The per-round logs always carry the violation breakdown by restraint kind (Hi-C intra / inter, polymer, envelope) with the most violating structure; uns["deconv"]["relax_init"] holds that of the initial relaxation.

Parameters:
  • data – The haploid contact-probability matrix (scipy.sparse or dense, entries = probability that the two loci are in contact, neighbours 1) and its bins (chrom, start, end; each chromosome contiguous): deconvolve_igm(P, bins=bins), the ProbabilityMatrix of preprocess_hic (deconvolve_igm(prob): its matrix and bins), or deconvolve_igm(cd, probabilities=P) with the bins of cd.

  • probabilities – The haploid contact-probability matrix (scipy.sparse or dense, entries = probability that the two loci are in contact, neighbours 1) and its bins (chrom, start, end; each chromosome contiguous): deconvolve_igm(P, bins=bins), the ProbabilityMatrix of preprocess_hic (deconvolve_igm(prob): its matrix and bins), or deconvolve_igm(cd, probabilities=P) with the bins of cd.

  • bins – The haploid contact-probability matrix (scipy.sparse or dense, entries = probability that the two loci are in contact, neighbours 1) and its bins (chrom, start, end; each chromosome contiguous): deconvolve_igm(P, bins=bins), the ProbabilityMatrix of preprocess_hic (deconvolve_igm(prob): its matrix and bins), or deconvolve_igm(cd, probabilities=P) with the bins of cd.

  • chrom – Restrict the model to these chromosomes (default: all bins), e.g. one chromosome: its copies follow ploidy ("haploid", "diploid" or {chrom: copies}); the nuclear envelope stays the full nucleus. The bead radii follow params.occupancy_scope: "model" (default, as IGM-Plus: the modelled chromosomes alone fill occupancy of the nucleus, so beads grow as fewer chromosomes are modelled), "genome" (radii of the whole-genome model of the input bins) — or set bead_radius.

  • params – IgmParams; keyword overrides replace single fields (n_structures=1000, occupancy=0.4, …).

  • device – "auto" (GPU if available), "cpu" or "gpu".

  • seed – Master seed (initial structures, velocities).

  • out – *.chromdata.zarr path: the population is streamed to it with ChromData.writer() and returned backed (large populations). None: an in-memory ChromData.

  • keep_intermediate – Keep the population after every M-step (round) as layers["round_<k>"] (spot-aligned coordinates; round 0 = the relaxed random start). Off by default.

  • key_added – cd.results key of the last activation-distance table.

  • progress – Callback progress(round_log: dict) after every M-step (round 0: the initial relaxation).

  • init_positions – Optional table of loci placed at given initial positions (IGM-Plus expanded initialisation): columns structure (0..S-1 or "s00012"), chrom, start (a position inside the bin), copy (default 0), x, y, z (nm, nucleus centred at the origin). Beads between two pinned beads of one chain are linearly interpolated; the rest keep the random-territory start. Only the start is set — no positional restraint is added (see the stage-2 design in an unpublished design note).

Returns:

  • ChromData (bins = the (haploid) model bins; one cell per structure)

  • (s00000 …, per-structure violation statistics in cells), one

  • **trace** per chromosome copy (s00000:chr1:0; traces has

  • chrom / copy), one spot per bead pointing to its bin; coordinates

  • in nm. bin_tracks["radius_nm"], bin_tracks["input_prob_rowsum"];

  • ``uns[“deconv”]`` (method, parameters, per-round log (with)

  • breakdown), relax_init, engine, timing. cells also has

  • hic_inter_imposed / hic_inter_violated (the inter-chromosomal

  • subset of hic_*).

Bulk Hi-C -> haploid contact-probability matrix (IGM protocol, method-independent).

Implements the preprocessing of Boninsegna et al. 2022 (Nat Methods 19:938; Supplementary Information section 6, “HFFc6 experimental data pre-processing”), as specified in an unpublished design note section 1.2. The same input serves every population deconvolution method (uchrom.recon.bulk.deconv.deconvolve(method="igm")).

Protocol (defaults = the paper’s values; resolutions are parameters):

  1. Coverage filter at the fine resolution (20 kb): bins with coverage < 3 % are discarded (see coverage_mask() for what “coverage” means here - the SI wording “sequence coverage” is ambiguous; a per-bin sequence-coverage array can be given instead).

  2. Knight-Ruiz balancing at the fine resolution -> frequency matrix G (kr_balance(), a re-implementation of Knight & Ruiz 2013’s bnewt on the symmetric sparse matrix, diagonal included, masked bins removed; balance="ice" / "weights" / "none" are alternatives, "weights" e.g. for Juicer KR vectors).

  3. p_ij = min(g_ij / f_max, 1).

  4. Coarse matrix (200 kb): a_IJ = mean of the top 10 % of the fine probabilities of the block b(I) x b(J) after excluding outliers above the box-plot fence Q3 + 1.5 IQR (topmean_summary(); the block statistics follow alabtools cmtools.cpp:TopmeanSummaryMatrix: zeros count, the fine diagonal counts as zero, top = n // 10 values not above the fence divided by n // 10; when the fence is 0 the block mean is used). Values equal to the fence are kept, as the SI states (“excluding outliers p > Q3 + 1.5 IQR”); alabtools keeps only values strictly below it, which zeroes a block whose probabilities are all clipped to 1 - fence_inclusive=False reproduces that.

  5. f_max and the coarse mapping are determined jointly: f_max is found by a bracketed bisection (in log space) such that the mean non-zero row sum of the coarse matrix, after zeroing entries below theta = 0.001, is target_contacts = 24 within tol = 1 % (alabtools Contactmatrix.iterativeScaling semantics; the bracketing is more robust than alabtools’ fixed [0, 2 f_0] interval).

  6. Spurious inter-chromosomal probabilities: coarse inter-chromosomal entries > inter_max = 0.2 are traced back to the fine inter-chromosomal entries > 0.2 of their block; those fine bins are removed and steps 2-5 are repeated until no coarse inter-chromosomal probability exceeds 0.2 (at most max_rounds).

  7. Nearest neighbours (consecutive coarse bins of one chromosome) are set to probability 1; the coarse diagonal to 1 (as in IGM’s demo .hcs).

Output: a ProbabilityMatrix with a symmetric scipy.sparse.csr_matrix of haploid contact probabilities (both triangles and the diagonal stored), the coarse bins DataFrame (chrom, start, end + bookkeeping columns) and a JSON-serialisable provenance dict. upper_coo() gives the upper-triangular (i, j, p) arrays the engine consumes.

Input: a sparse raw count matrix + fine bins (preprocess_igm()), or a file (preprocess_hic(): .cool, .mcool[::/resolutions/N], .hic through hicstraw when installed). When the file has no level at the fine resolution, the finest level dividing it is read and summed (e.g. 10 kb -> 20 kb).

class uchrom.recon.bulk.deconv.preprocess.IGMPreprocessParams(fine_resolution: int = 20000, coarse_resolution: int = 200000, min_coverage: float = 0.03, coverage: str = 'relative_rowsum', balance: str = 'kr', kr_tol: float = 1e-06, kr_max_iter: int = 500, top_fraction: float = 0.1, iqr_factor: float = 1.5, fence_inclusive: bool = True, masked_as_zero: bool = True, target_contacts: float = 24.0, tol: float = 0.01, theta: float = 0.001, max_bisection: int = 80, inter_max: float = 0.2, max_rounds: int = 5, neighbour_probability: float = 1.0, diagonal_probability: float = 1.0)[source]

Bases: object

Parameters of the IGM SI section 6 protocol (defaults = the paper).

balance: str = 'kr'

“kr” | “ice” | “weights” (given multiplicative weights) | “none”

Type:

step 2

coarse_resolution: int = 200000
coverage: str = 'relative_rowsum'

“relative_rowsum” (raw contacts of the bin / median over non-empty bins) or “nonzero_fraction” (fraction of non-zero pixels of the row / median); ignored when sequence_coverage is passed to preprocess_igm()

diagonal_probability: float = 1.0
fence_inclusive: bool = True

keep values equal to the fence (SI wording); False = alabtools’ strict “<”

fine_resolution: int = 20000
inter_max: float = 0.2

step 6

iqr_factor: float = 1.5
kr_max_iter: int = 500
kr_tol: float = 1e-06
masked_as_zero: bool = True

masked fine bins count as zeros in a block (alabtools) or are left out (PGS NaN rule)

max_bisection: int = 80
max_rounds: int = 5
min_coverage: float = 0.03

bins below this coverage are discarded

Type:

step 1

neighbour_probability: float = 1.0

step 7

target_contacts: float = 24.0

step 5

theta: float = 0.001
to_dict() → dict[source]
tol: float = 0.01
top_fraction: float = 0.1

step 4

class uchrom.recon.bulk.deconv.preprocess.ProbabilityMatrix(probabilities: scipy.sparse.csr_matrix, bins: DataFrame, provenance: dict = <factory>, fine_bins: DataFrame | None = None, fine_mask: ndarray | None = None)[source]

Bases: object

Result of the preprocessing.

probabilities: symmetric CSR (n_coarse x n_coarse) haploid contact probabilities in [0, 1]; bins: chrom, start, end, n_fine (fine bins in the coarse bin), n_fine_valid (after the filters), masked (no valid fine bin), rowsum; fine_mask: bool per fine bin (True = discarded); provenance: parameters and per-round diagnostics.

bins: DataFrame
fine_bins: DataFrame | None = None
fine_mask: ndarray | None = None
classmethod load(path) → ProbabilityMatrix[source]
probabilities: scipy.sparse.csr_matrix
provenance: dict
save(path) → None[source]

.npz with i, j, p (upper triangle incl. diagonal), the bins columns and the provenance as JSON.

upper_coo(k: int = 0)[source]

(i, j, p) of the upper triangle (k=1 leaves the diagonal out).

uchrom.recon.bulk.deconv.preprocess.aggregate_bins(u: scipy.sparse.csr_matrix, bins: DataFrame, factor: int) → tuple[scipy.sparse.csr_matrix, DataFrame][source]

Sum a fixed-bin matrix into bins factor times larger (within chromosomes).

uchrom.recon.bulk.deconv.preprocess.canonical_upper(m) → scipy.sparse.csr_matrix[source]

Upper triangle (incl. diagonal) of a square sparse / dense matrix given as upper, lower or full symmetric storage (full storage: the upper triangle is used).

uchrom.recon.bulk.deconv.preprocess.coarse_index(fine_bins: DataFrame, coarse: int | DataFrame) → tuple[ndarray, DataFrame][source]

Map fine bins to coarse bins.

coarse: a resolution in bp (coarse bin = start // coarse within each chromosome) or a DataFrame of coarse bins (chrom, start, end; fine bins are mapped by their midpoint, fine bins outside every coarse bin get -1). Returns (fine -> coarse index, coarse bins).

uchrom.recon.bulk.deconv.preprocess.coverage_mask(u: scipy.sparse.csr_matrix, min_coverage: float = 0.03, kind: str = 'relative_rowsum', sequence_coverage: ndarray | None = None) → ndarray[source]

Step 1: True for fine bins to discard.

The SI says “bins with sequence coverage lower than 3 % were discarded”. With sequence_coverage (fraction of the bin covered by mappable / non-N sequence, one value per bin) that rule is applied literally. Without it, coverage is measured from the matrix: relative_rowsum = off-diagonal raw contacts of the bin divided by the median over non-empty bins (so unmappable, centromeric and gap bins, which have ~0 contacts, go); nonzero_fraction = the same with the number of non-zero pixels. Empty rows are always masked.

uchrom.recon.bulk.deconv.preprocess.fit_fmax(blocks: _BlockEntries, target: float = 24.0, tol: float = 0.01, theta: float = 0.001, top_fraction: float = 0.1, iqr_factor: float = 1.5, fmax0: float | None = None, max_iter: int = 80, fence_inclusive: bool = True) → tuple[float, float, list][source]

Step 5: f_max such that the mean non-zero row sum of the coarse matrix (entries < theta zeroed) is target within tol (relative). The average decreases with f_max; bracket by doubling / halving, then bisect in log space. Returns (fmax, average, trace).

uchrom.recon.bulk.deconv.preprocess.ice_balance(u, mask: ndarray | None = None, tol: float = 1e-05, max_iter: int = 1000)[source]

Iterative correction (Imakaev et al. 2012) to equal row sums; weights normalised so that the balanced matrix has unit mean row sum (for comparison with kr_balance()).

uchrom.recon.bulk.deconv.preprocess.kr_balance(u, mask: ndarray | None = None, tol: float = 1e-06, max_iter: int = 500, delta: float = 0.1, Delta: float = 3.0) → tuple[ndarray, dict][source]

Knight-Ruiz matrix balancing (Knight & Ruiz 2013, IMA J Numer Anal 33:1029, algorithm bnewt: Newton outer iteration, conjugate-gradient inner iteration with a step length keeping the scaling in [delta, Delta]).

u: upper triangle (or full symmetric) sparse matrix; mask: True = excluded bin (also bins whose row is empty after masking). Returns (w, info) with w the multiplicative weights (NaN for excluded bins) such that diag(w) A diag(w) has unit row sums over the kept bins. The diagonal of the matrix is included.

uchrom.recon.bulk.deconv.preprocess.load_contacts(path, resolution: int, chroms: Sequence[str] | None = None, balance_column: str | None = None)[source]

Read a raw contact matrix at resolution from .cool / .mcool / .hic.

If the file has no level at resolution, the coarsest level that divides it is read and summed. chroms: subset (all by default; .hic: names as in the file, a chr prefix is added to the output names when missing). Returns (upper csr counts, bins, weights or None); weights is bins[balance_column] of a cooler (e.g. "KR" in 4DN mcools, "weight") summed levels have no weights.

uchrom.recon.bulk.deconv.preprocess.preprocess_hic(data=None, *, contacts: str | None = None, chroms: Sequence[str] | None = None, params: IGMPreprocessParams | None = None, coarse_bins: DataFrame | None = None, verbose: bool = False, path=None) → ProbabilityMatrix[source]

Hi-C map -> haploid contact probabilities (load_contacts() at params.fine_resolution + preprocess_igm()).

Parameters:
  • data – A ChromData with the map linked (cd.link_cool; key contacts, None: the only one), or the path of a .cool / .mcool / .hic (also as path=). Raw counts are read.

  • contacts – Key of the linked map.

  • chroms – Chromosomes (default: all of the map).

  • params – See preprocess_igm().

  • coarse_bins – See preprocess_igm().

  • verbose – See preprocess_igm().

Returns:

ProbabilityMatrix (``provenance[“input”]`` records the map

Return type:

key and path).

uchrom.recon.bulk.deconv.preprocess.preprocess_igm(counts, bins: DataFrame, *, params: IGMPreprocessParams | None = None, coarse_bins: DataFrame | None = None, sequence_coverage=None, weights: ndarray | None = None, verbose: bool = False) → ProbabilityMatrix[source]

Raw fine-resolution counts -> coarse haploid probability matrix (IGM SI section 6).

Parameters:
  • counts – square sparse (or dense) raw contact matrix over bins (upper, lower or full symmetric storage).

  • bins – fine bins: chrom, start, end (genome order).

  • params – IGMPreprocessParams; params.fine_resolution is informational here (the matrix is taken as given), params.coarse_resolution defines the coarse bins unless coarse_bins (DataFrame chrom, start, end) is given.

  • sequence_coverage – optional per-fine-bin sequence coverage fraction for step 1.

  • weights – multiplicative balancing weights (params.balance="weights"), e.g. a Juicer KR vector converted to cooler’s convention; NaN = masked.

uchrom.recon.bulk.deconv.preprocess.topmean_summary(blocks: _BlockEntries, fmax: float, top_fraction: float = 0.1, iqr_factor: float = 1.5, fence_inclusive: bool = True) → ndarray[source]

Top-mean block summary of p = min(g / fmax, 1) for every block with entries.

Per block of n fine pairs (zeros included): sorted values, Q1 = x[int(0.25 n + 0.5)], Q3 = x[int(0.75 n + 0.5)], fence Q3 + iqr_factor (Q3 - Q1); t = int(n * top_fraction) (n if 0); summary = (sum of the t largest values not above the fence - strictly below it with fence_inclusive=False) / t; a zero fence means the block mean (alabtools TopmeanSummaryMatrix). Returns one value per blocks.ukey.