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], GEOchr_A pos_A chr_B pos_Btable) or DataFrame of contacts (seeuchrom.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=Noneruns everything).n_models – Models (structures) in the ensemble.
params – Engine parameters overriding the frozen defaults (see
uchrom_recon.default_params(); therobust_*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;Nonestores neither.copy – Reconstruction always creates a new
ChromDatafrom 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 (defaultFalse: the frozen configuration, EMber’s own neighbourhood prior only; an unpublished design note §6). Adds the results<key>.phase_probs/<key>.imputed_phaseanduns[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 (defaultFalse: the frozen configuration, EMber’s own neighbourhood prior only; an unpublished design note §6). Adds the results<key>.phase_probs/<key>.imputed_phaseanduns[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 (defaultFalse: the frozen configuration, EMber’s own neighbourhood prior only; an unpublished design note §6). Adds the results<key>.phase_probs/<key>.imputed_phaseanduns[key]["diploid"](phasing statistics).
- Returns:
One spot per particle;
coords= model 0,layers['model_<k>']= every model; units: particle radii. Same layout asuchrom.recon.sc.nucdyn.reconstruct_nucdyn()withprotocol="robust"(identical coordinates for the same seed).- Return type:
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.contactsis a path (.nccas written by NucProcess;.pairs/.pairs.gz; a whitespace tablechr_A pos_A chr_B pos_Bsuch as the GEO files of Stevens et al. 2017) or a DataFrame with columnschr1, pos1, chr2, pos2(asuchrom.io.read_pairs()returns) orchrom1, pos1, chrom2, pos2; optionalambiguity/active.genome_rangeskeeps 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 whichis_phased_file()is true (hickit.pairswithphase0/phase1; Dip-C.con), or DataFrames withhap1/hap2(orphase0/phase1;.= unknown) and optionallyphase_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 fromarch(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], GEOchr_A pos_A chr_B pos_Btable) or DataFrame of contacts, seeload_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_dynamicsmaster)."release_1.3": the later bead-size-scaled version with ambiguity resolution and model selection (2 xn_modelsabove 1 Mb, then_modelsclosest to the mean kept)."robust"(public name EMber, alias"ember"; seeuchrom.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 ofcd.uns[key_added];Nonestores 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
.pairswithphase0/phase1, Dip-C.con, a DataFrame withhap1/hap2(seeload_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).ploidygives 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"): traceschr1(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 (defaultFalse, the frozen diploid EMber configuration: EMber’s own 2-D neighbourhood priorrobust_dip_nbr_prioronly, 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).coordsholds model 0 andlayers['model_<k>']holds every modelk(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 positionpcollects 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:
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 distancesd = 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
ChromDatawith 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.coolmust be at it;uchrom.fea.rebin_map()makes coarser maps).balance – Use the balanced matrix (
weightcolumn).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.hicor.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 –
unskey of the settings andresults["<key_added>.chroms"](bins kept and time per chromosome);Nonestores 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:
- 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:
- 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.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:
- 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.compute_radius_of_gyration(coords)[source]¶
Rg = sqrt(mean(||x - centroid||^2)).
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, protocoligm; 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:
objectIGM 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_radiusBead 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_scopeWhat the occupancy refers to when only some chromosomes are modelled (
deconvolve(..., chrom=)):"model"(default; the modelled chromosomes filloccupancyof 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_correctionFalse: the A-step uses
p = finstead of the iteratively corrected probability (IGM-Plusiter_corr_knob = 0).assignment_pooling"igm"(IGM 1.0) or"gp"(G. Polles’ approximation, IGM_2.0GP_ActivationDistanceStep: all copy combinations pooled,n_possible = min(copies)smallest per structure) — for the sensitivity analysis of an unpublished design note.init_noiseGaussian noise (nm, standard deviation) added to every initial coordinate (IGM-Plus
model/init_noise; withdeconvolve(..., init_positions=)).
- 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).
- property effective_occupancy: float | None¶
The occupancy used (None when
bead_radiussets the radii).
- replace(**kw: Any) IgmParams[source]¶
A copy with fields replaced; giving
bead_radiusalone drops the occupancy (and vice versa), since the two are mutually exclusive.
- 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
ProbabilityMatrixofpreprocess_hic()(matrix and bins), a haploid contact-probability matrix (scipy.sparseor dense, bins × bins; passbins=), or aChromDatawhosebinsdefine the loci (pass the matrix asprobabilities=).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=withoccupancy_scope(chromosome-subset models),bead_radius(radii set directly, exclusive withoccupancy),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.sparseor 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), theProbabilityMatrixofpreprocess_hic(deconvolve_igm(prob): its matrix and bins), ordeconvolve_igm(cd, probabilities=P)with the bins ofcd.probabilities – The haploid contact-probability matrix (
scipy.sparseor 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), theProbabilityMatrixofpreprocess_hic(deconvolve_igm(prob): its matrix and bins), ordeconvolve_igm(cd, probabilities=P)with the bins ofcd.bins – The haploid contact-probability matrix (
scipy.sparseor 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), theProbabilityMatrixofpreprocess_hic(deconvolve_igm(prob): its matrix and bins), ordeconvolve_igm(cd, probabilities=P)with the bins ofcd.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 followparams.occupancy_scope:"model"(default, as IGM-Plus: the modelled chromosomes alone filloccupancyof the nucleus, so beads grow as fewer chromosomes are modelled),"genome"(radii of the whole-genome model of the input bins) — or setbead_radius.params –
IgmParams; keywordoverridesreplace single fields (n_structures=1000,occupancy=0.4, …).device –
"auto"(GPU if available),"cpu"or"gpu".seed – Master seed (initial structures, velocities).
out –
*.chromdata.zarrpath: the population is streamed to it withChromData.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.resultskey 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 incells), one**trace** per chromosome copy (
s00000:chr1:0;traceshaschrom/copy), one spot per bead pointing to its bin; coordinatesin nm.
bin_tracks["radius_nm"],bin_tracks["input_prob_rowsum"];``uns[“deconv”]`` (method, parameters, per-round log (with)
breakdown),relax_init, engine, timing.cellsalso hashic_inter_imposed/hic_inter_violated(the inter-chromosomalsubset 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):
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).Knight-Ruiz balancing at the fine resolution -> frequency matrix
G(kr_balance(), a re-implementation of Knight & Ruiz 2013’sbnewton the symmetric sparse matrix, diagonal included, masked bins removed;balance="ice"/"weights"/"none"are alternatives,"weights"e.g. for Juicer KR vectors).p_ij = min(g_ij / f_max, 1).Coarse matrix (200 kb):
a_IJ= mean of the top 10 % of the fine probabilities of the blockb(I) x b(J)after excluding outliers above the box-plot fenceQ3 + 1.5 IQR(topmean_summary(); the block statistics follow alabtoolscmtools.cpp:TopmeanSummaryMatrix: zeros count, the fine diagonal counts as zero,top = n // 10values not above the fence divided byn // 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=Falsereproduces that.f_maxand the coarse mapping are determined jointly:f_maxis found by a bracketed bisection (in log space) such that the mean non-zero row sum of the coarse matrix, after zeroing entries belowtheta = 0.001, istarget_contacts = 24withintol = 1 %(alabtoolsContactmatrix.iterativeScalingsemantics; the bracketing is more robust than alabtools’ fixed[0, 2 f_0]interval).Spurious inter-chromosomal probabilities: coarse inter-chromosomal entries
> inter_max = 0.2are traced back to the fine inter-chromosomal entries> 0.2of their block; those fine bins are removed and steps 2-5 are repeated until no coarse inter-chromosomal probability exceeds 0.2 (at mostmax_rounds).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:
objectParameters of the IGM SI section 6 protocol (defaults = the paper).
- 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_coverageis passed topreprocess_igm()
- fence_inclusive: bool = True¶
keep values equal to the fence (SI wording); False = alabtools’ strict “<”
- 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:
objectResult 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.- classmethod load(path) ProbabilityMatrix[source]¶
- probabilities: scipy.sparse.csr_matrix¶
- 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
factortimes 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 // coarsewithin 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_maxsuch that the mean non-zero row sum of the coarse matrix (entries < theta zeroed) istargetwithintol(relative). The average decreases withf_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)withwthe multiplicative weights (NaN for excluded bins) such thatdiag(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
resolutionfrom.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, achrprefix is added to the output names when missing). Returns(upper csr counts, bins, weights or None);weightsisbins[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()atparams.fine_resolution+preprocess_igm()).- Parameters:
data – A
ChromDatawith the map linked (cd.link_cool; keycontacts,None: the only one), or the path of a.cool/.mcool/.hic(also aspath=). 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_resolutionis informational here (the matrix is taken as given),params.coarse_resolutiondefines the coarse bins unlesscoarse_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
nfine pairs (zeros included): sorted values,Q1 = x[int(0.25 n + 0.5)],Q3 = x[int(0.75 n + 0.5)], fenceQ3 + iqr_factor (Q3 - Q1);t = int(n * top_fraction)(nif 0); summary = (sum of thetlargest values not above the fence - strictly below it withfence_inclusive=False) /t; a zero fence means the block mean (alabtoolsTopmeanSummaryMatrix). Returns one value perblocks.ukey.