uchrom.io¶
Readers and writers of the file formats: contact pairs and maps (including pairs → per-cell .scool, per-cell
contact-distance histograms ContactStats and contacts in windows of the map WindowCounts),
Juicer loop / domain lists (read_juicer_loops, read_juicer_domains), tracing and seqFISH tables.
I/O helpers with lazy optional-dependency imports.
- class uchrom.io.ContactStats(cells: Sequence, chroms: Sequence[str], edges: ndarray, *, orientation: bool = True)[source]¶
Bases:
objectContact-distance histograms and trans counts of many cells, accumulated over chunks of contacts.
- Parameters:
cells – The cell ids (the rows of every array).
chroms – The chromosomes counted (contacts with a leg elsewhere are left out and counted in
n_other).edges – Distance-bin edges (
distance_edges()).orientation – Keep the histogram per read orientation as well (needs the strands in
add()).
- Variables:
distance (ndarray (n_cells, n_chroms, n_edges + 1), int64) – Cis contacts per cell, chromosome and distance bin; column 0 is d < edges[0], the last d > edges[-1].
orientation (ndarray (n_cells, 4, n_edges + 1), int64, or None) – Cis contacts per cell, orientation (
ORIENTATIONS) and distance bin, summed over chromosomes.trans (ndarray (n_cells, n_chroms), int64) – Trans contacts per cell with a leg on each chromosome (a trans contact counts on both of its chromosomes;
trans.sum(1) / 2is the number of trans contacts).
- add(cell, chrom1, pos1, chrom2, pos2, strand1=None, strand2=None) None[source]¶
Count a chunk of contacts.
cellis the row of each contact (-1: not counted),chrom1/chrom2the index of its chromosomes inchroms(-1: another chromosome),pos1/pos2its positions;strand1/strand2(‘+’ / ‘-’ or booleans for ‘-’) are needed whenorientationis kept.
- distance_bin(d: ndarray) ndarray[source]¶
The histogram column of each distance (0: below the first edge; n_edges: above the last).
- classmethod load(path: str | PathLike) ContactStats[source]¶
- merge(other: ContactStats) ContactStats[source]¶
Add another accumulator over the same cells, chromosomes and edges (e.g. of another file).
- save(path: str | PathLike, **meta) None[source]¶
Write the arrays to one
.npz(meta: JSON-able notes, e.g. the filters applied).
- write(cd, *, key: str = 'contacts', source: str | None = None, per_chromosome: bool = True, dtype=<class 'numpy.int64'>) None[source]¶
Store the histograms on
cd, aligned tocd.cellsby cell id (cells without counts get zeros).cd.cellm["<key>.distance"]: (n_cells, n_chroms, n_bins), or (n_cells, n_bins) summed over the chromosomes withper_chromosome=False(an atlas store: 21-24x smaller);["<key>.orientation"](n_cells, 4, n_bins);["<key>.cis"]and["<key>.trans"](n_cells, n_chroms; trans: legs on each chromosome); the columns<key>.n_cis/<key>.n_transofcd.cells; the recordcd.uns["contact_stats"][key](edges, chromosomes, orientations, columns).dtype: of the arrays (int32 holds any spot’s counts).
- class uchrom.io.GenomeRange(chr, start=0, end=100000000000000000000)[source]¶
Bases:
object- SUPER_MAX = 100000000000000000000¶
- class uchrom.io.WindowCounts(cells: Sequence, windows: DataFrame, resolution: int, chroms: Sequence[str])[source]¶
Bases:
objectContacts per cell in each window.
- Parameters:
cells – The cell ids (rows of
counts).windows –
chrom, start1, end1, start2, end2(+ any other columns, kept), bp.resolution – The bin size the windows are counted at.
chroms – The chromosomes, in the order of the codes given to
add().
- Variables:
counts (ndarray (n_cells, n_windows), int64)
- add(cell, chrom1, pos1, chrom2, pos2) None[source]¶
Count a chunk of contacts:
cellrows (-1: skip), chromosome codes (index intochroms, -1: other), 1-based positions. Trans contacts are ignored.
- by_part(kind: str | None = None, values: ndarray | None = None)[source]¶
Counts and pixels summed per (feature, part) of the windows of one
kind(columnkind; all windows when None):({part: ndarray (n_cells, n_features)}, {part: ndarray (n_features,)}), features 0 … max(feature) in order.values: an (n_cells, n_windows) array summed instead of the counts (e.g.uchrom.fea.window_expected()).
- classmethod load(path: str | PathLike) WindowCounts[source]¶
- merge(other: WindowCounts) WindowCounts[source]¶
- uchrom.io.bin_pairs(src: str | PathLike | Callable[[], IOBase], chromsizes: Mapping, resolution: int, *, name: str | None = None, chunk_lines: int = 2000000) Tuple[DataFrame, Dict[str, int]][source]¶
One cell’s contacts summed into the genome-wide bins of
genome_bins()(upper triangle).- Returns:
pixels (DataFrame) –
bin1_id, bin2_id, countsorted by (bin1, bin2),bin1_id <= bin2_id.stats (dict) –
n_lines(contacts in the file),n_contacts(binned),n_cis,n_trans,n_dropped(other chromosomes / beyond an end),n_pixels.
- uchrom.io.boundary_windows(boundaries: DataFrame, *, window: int, resolution: int) DataFrame[source]¶
Three windows per boundary (
chrom,posbp, snapped to the bin grid):left(both ends in thewindowbp upstream),right(both downstream) andcross(one end on each side). The columnsfeature(the boundary’s row) andpartsay which.
- uchrom.io.chrom_sort_key(name) tuple[source]¶
Natural sort key of a chromosome name:
chr1 < chr2 < ... < chr10 < ... < chrX < chrY < chrM(with or without thechrprefix; numbered chromosomes first, then the others by name, the mitochondrialM/MTlast).
- uchrom.io.convert_chromdata(src: str | Path, dst: str | Path | None = None, *, overwrite: bool = False, coord_dtype: str = 'float64') dict¶
Read
src(.h5cd1.x / 2.0, or any ChromData store) and write it todstin the current format (.chromdata.zarr/.cdz); a zarr / cdz source is read in its original row order.dstdefaults to<src stem>.chromdata.zarrnext tosrc; its suffix picks the container.coord_dtypeis the storage dtype ofcoords/layers(seeChromData.write()).Returns a summary: source / target versions and containers,
n_spots,n_binsand which tracks are bin- vs spot-level.srcis never modified;dstmust differ from it.
- uchrom.io.distance_edges(chromsizes: Mapping | None = None, *, max_distance: float | None = None, base: float = 2500.0, per_octave: int = 8) ndarray[source]¶
The edges of the contact-distance bins (bp):
base * 2 ** (k / per_octave), k = 0 … n, with n = floor(per_octave * log2(max_distance / base)) andmax_distancethe longest chromosome ofchromsizesby default. With the defaults these are scHiCluster’s edges, bit for bit.
- uchrom.io.file_format_version(path: str | Path) str[source]¶
The
uchrom_format_versionof a ChromData file ("1.0"for an unversioned.h5cd).
- uchrom.io.genome_bins(chromsizes: Mapping, resolution: int) DataFrame[source]¶
Fixed-size bins
chrom, start, endof every chromosome (the last bin ends at the chromosome end).
- uchrom.io.iter_pairs(src: str | PathLike | Callable[[], IOBase], *, name: str | None = None, chunk_lines: int = 2000000) Iterator[DataFrame][source]¶
The contacts of a pairs /
.confile as chunkschrom1, pos1, chrom2, pos2(chromosomes as categoricals, 1-based positions).srcis a path or a callable opening a binary stream (e.g. a member of a tarball);nameis the file name that tells a.confrom a.pairswhensrcis a callable.
- uchrom.io.load_seqfish_multiomics_linked(spot_glob: str | Iterable[str | Path], *, locus_annotation: str | Path, cell_clustering: str | Path | None = None, transcriptomic_data: str | Path | Iterable[str | Path] | None = None, transcriptome_dataset: str = 'cerebellum', transcriptome_assay: str = 'mrna', transcriptome_replicate: int | None = None, transcriptome_chunksize: int = 500000, download_transcriptome: bool = False, data_dir: str | Path | None = None, cd_path: str | Path | None = None, h5ad_path: str | Path | None = None, h5cd_path: str | Path | None = None, **kwargs)[source]¶
Build linked Takei 2025 ChromData and AnnData artifacts.
Returns a
ChromDatathat stores chromatin tracing geometry and spot-level tracks. The aggregated RNA expression matrix is attached ascd.linked_adata. Both objects are ordered on the same cell ids, and the ChromData receivesadata.obs/adata.obsmviaChromData.link_anndata().cd_pathis where the ChromData is written (.chromdata.zarror.cdz).h5cd_pathis its deprecated former name.
- uchrom.io.load_takei2025_cerebellum(*, replicate: int = 1, data_dir: str | Path | None = None, download: bool = True, rebuild: bool = False, transcriptome_chunksize: int = 500000, **kwargs)[source]¶
Load linked Takei 2025 cerebellum
ChromData+ AnnData.This convenience loader returns a
ChromData. The aggregated RNA expression matrix is available ascd.linked_adata. If paired.chromdata.zarr/.h5adartifacts already exist underdata_dir, they are reused. Otherwise, whendownload=True, the DNA seqFISH+ archive, the transcriptome zip (Zenodo record 7693825) and the annotation / clustering tables (CaiGroup GitHub) are fetched withuchrom.datasets(takei2025_cerebellumortakei2025_cerebellum_rep2,takei2025_rna; md5-checked, into the data directory) and the linked artifacts are built.- Parameters:
replicate – Cerebellum replicate to load. Currently
1or2.data_dir – Build directory of the extracted archive and the linked artifacts (default:
<uchrom.datasets.data_dir()>/takei2025_cerebellum).download – If False, missing raw/build artifacts raise
FileNotFoundError.rebuild – If True, rebuild the paired artifacts even when they exist.
transcriptome_chunksize – Chunk size used while aggregating RNA spot CSVs into AnnData.
**kwargs – Forwarded to
load_seqfish_multiomics_linked().
- uchrom.io.loop_windows(loops: DataFrame, *, resolution: int, peak: int = 1, donut: Sequence[int] = (2, 5)) DataFrame[source]¶
Windows of each loop (
chrom1, start1, start2: its anchors, bp) atresolution:peak— the (2 peak + 1)^2 pixels around the loop pixel — anddonut— the ring of pixels betweendonut[0]anddonut[1]pixels from it (Chebyshev distance), as four non-overlapping strips. Columnsfeatureandpart.
- uchrom.io.make_higashi_config(*, data_dir: str, genome_reference: str, resolution: int, chrom_list: list[str], temp_dir: str | None = None, cell_feats: list[str] | None = None, overrides: dict[str, Any] | None = None) dict[str, Any][source]¶
Build a Higashi
config.JSONdict.Fields follow the v2 schema from the Higashi wiki and FastHigashi’s runtime expectations (
input_format,contact_header,header_included).overridesare merged last, so callers can tweak any field (including the required ones) without forking this helper.
- uchrom.io.pairs_chromsizes(src: str | PathLike | Callable[[], IOBase]) Dict[str, int][source]¶
The chromosome sizes a pairs file declares (
#chromsize:/#chromosome:header lines), in order.
- uchrom.io.pairs_contact_stats(cells: Mapping, *, chromsizes: Mapping, edges: ndarray | None = None, chunk_lines: int | None = None) ContactStats[source]¶
ContactStatsof per-cell contact files ({cell: path}, the inputs ofpairs_to_scool()). The files’ strands are not read, soorientationis None; chromosome names match with or without achrprefix.
- uchrom.io.pairs_df_to_higashi(pairs: DataFrame, *, resolution: int) DataFrame[source]¶
Convert a
read_pairs-style DataFrame to Higashi’s per-cell format.Input columns:
chr1, pos1, chr2, pos2(extra columns are ignored). Output columns:chrom1, pos1, chrom2, pos2, count.Positions are binned to
resolution(floor), intra-chromosomal pairs are ordered sopos1 <= pos2, and duplicates are collapsed by summing intocount.
- uchrom.io.pairs_to_scool(cells: Mapping, out: str | PathLike, *, chromsizes: Mapping, resolution: int, assembly: str | None = None, metadata: dict | None = None, verbose: bool = False) DataFrame[source]¶
Bin the contacts of every cell into one
.scool(cooler’s single-cell format, shared bins).- Parameters:
cells –
{cell name: source}; a source is a path of a.pairs[.gz]/.con[.gz]file or a tuple(opener, file name)whereopener()returns a binary stream (e.g. a tarball member).out – The
.scoolto write (atomically: written next to it, then renamed).chromsizes –
{chromosome: length}in genome order: the bins (genome_bins()) and the kept chromosomes.resolution – Bin size (bp).
assembly – Recorded in the file.
metadata – Recorded in the file.
- Returns:
DataFrame indexed by cell (
n_lines, n_contacts, n_cis, n_trans, n_dropped, n_pixels(see)
- uchrom.io.read_3dg_cells(files: Mapping[str, str | PathLike], *, layers: Mapping[str, Mapping[str, str | PathLike]] | None = None, cells: DataFrame | None = None, uns: dict | None = None, **read_kw)[source]¶
Several cells’
.3dgstructures as oneChromData: a trace per cell, chromosome and homolog.- Parameters:
files –
{cell id: .3dg path}(the main structure of each cell).layers – More runs of the same cells,
{layer name: {cell id: path}}(e.g. Dip-C’srep1/rep2): stored ascd.layers[name]on the particles of the main run — NaN where a run lacks a particle; particles only in a layer run are left out (counted inuns["structures"]["layers"]). Each run has its own frame (no superposition here; seereplicate_deviation()).cells – Cell metadata indexed by cell id (default: just the ids of
files).uns – Extra
unsentries.**read_kw – For
read_3dg_structure()(particle_size,particle_position,hap_names, …).
- Returns:
spots:chrom, start, end, trace_id, cell_idsorted by cell, chromosome (genome order), homolog and position; trace ids<cell>_<chrom>_<homolog>(<cell>_<chrom>without homolog);traces(index trace id):cell_id, chrom, homolog, n_particles;cellsgainsn_particlesandn_traces;uns["structures"]: format, particle size and position convention (particle_position: the meaning of the file positions; the loci are the particles’ intervals), per-layer counts;uns["xyz_unit"].- Return type:
- uchrom.io.read_3dg_structure(path: str | PathLike, *, particle_size: int | None = None, particle_position: str = 'auto', hap_names: Sequence[str] = ('pat', 'mat'), chr_prefix: str | bool = 'auto') DataFrame[source]¶
One single-cell structure in the
.3dglayout (Dip-C or hickit) as a table of particles.- Parameters:
path – A
.3dgfile, plain or gzipped (Dip-C*.3dg.txt.gz/ hickit*.3dg.gz).particle_size – Bin size of the particles (bp).
None: the most common distance between consecutive particles of a chromosome copy (20 kb for the Tan 2018 structures).particle_position – What a particle’s position is:
"end"(it holds(p - size, p]: Dip-C / NucDynamics),"start"([p, p + size): hickit),"mid"([p - size/2, p + size/2)) or"auto"(by the layout: Dip-C names →"end", hickit or plain names →"start"; see the module docstring).hap_names – Names of hickit’s
a/bhomologs (default("pat", "mat"), as Dip-C names them;ais the phase-0 haplotype of the phased variants). Dip-C names are kept as written.chr_prefix – Prefix
chrto chromosome names without it ("auto"/True;False: keep the names).
- Returns:
One row per particle in file order:
chrom,start,end(the particle’s interval, bp,startclipped at 0),homolog(Nonefor a chromosome without homolog suffix),position(as in the file),x,y,z(the file’s unit: particle radii for Dip-C, hickit’s own scale). Withparticle_position="end"a particle at position 0 (it would hold(-size, 0], i.e. nothing: Dip-C starts some chains there) is left out.attrsholdsformat,particle_size,particle_positionandn_dropped_before_start.- Return type:
DataFrame
- uchrom.io.read_4dn_tracing(experiments: Iterable[Mapping], *, genome_assembly: str | None = None)[source]¶
Read 4DN FOF-CT chromatin-tracing experiments into one
ChromData(coordinates in µm).- Parameters:
experiments (iterable of mappings) – One per experiment:
name(prefix of its ids),core(the core table, or a list of them — their trace ids prefixedc<k>-,traces["core_file"]naming the table) and optionallyspot_quality/spot_bio(one or several tables keyed bySpot_ID),trace_data,cell_data(companion tables),rna_spot(RNA-spot tables:points['rna']),meta(a mapping of values given to each of its cells, e.g. the experiment set, condition and biosample) andlocus_shifts((chrom, start_from, start_to, offset): loci whose start lies in the range moved byoffsetbp — a correction the caller knows from the authors, recorded inuns["fofct_locus_shifts"]) andtrace_by(core columns whose values, joined, are the trace id, where the deposit’sTrace_IDis not one; recorded inuns["fofct_trace_keys"]) andfov_from(spot-table columns, the first present taken, that give each spot’s field of view where the core has none: cells and traces are then numbered per field; recorded inuns["fofct_fov_columns"]).genome_assembly (str, optional) – Recorded in
uns; default: thegenome_assemblyof the core tables’ headers (they must agree).
- Returns:
spots: one per detected spot (rows without coordinates or without a locus — an emptyChrom, as the unassigned spots of Hafner et al. 2023 — left out, counted inuns["fofct_dropped_spots"]),trace_id = "<name>_<Trace_ID>",cell_id = "<name>_<Cell_ID>"where the experiment gives cells (in the core, or in a cell table keyed by trace),"<name>_<FOV>-<Cell_ID>"where its spots (core columnFOVid/FOV) or traces have a field of view (the authors number cells per field;"<name>_<run>-<FOV>-<Cell_ID>"where the core also has the imaging run,Dataset ID, fields being numbered per run), else — and forCell_ID0, a trace in no cell —"<name>_t<Trace_ID>"(one cell per trace);spot_tracks: the spot-quality columns;traces:experiment, the trace-data columns and per-trace cell values;cells:experiment, themetavalues and the cell-data columns.uns:genome_assembly,xyz_unit(micron),fofct_headers(per experiment),fofct_unit_fixes,fofct_dropped_spots(also exact duplicate rows),fofct_trace_splits(ids reused for several traces:_split_reused_traces()),fofct_column_fixes(core tables whose declared columns were one too many or one too few:_fix_columns()),fofct_chrom_renames(chromosome names given the UCSCchrprefix:3R->chr3R,19->chr19,Chr14->chr14).- Return type:
- uchrom.io.read_igs(path, *, resolution: int = 1000000)[source]¶
Read an IGS data table (Payne et al. 2021) into a
ChromDataof reads.- Parameters:
path (path) –
Table_S1_pgp1_data_table.csv(human fibroblasts) orTable_S2_embryo_data_table.csv(mouse embryos); the table is recognised by its columns.resolution (int) – Size of the genomic bins (bp) the reads are placed in; the read’s own position stays in the spot column
pos.
- Returns:
One spot per read on a primary chromosome, coordinates in µm.
trace_id = "<cell>_<chrom>_<homolog>": the reads of one chromosome territory, an unordered set (uns['trace_kind'] = 'set'; several reads may share a bin),homologas in the traces table —mat/pat(embryos),h1/h2,none(reads outside the territories),overlap. Spot columnsspot_id(row in the file),pos, the authors’ labels (cluster,cluster_hap_imputed,amp_ind, …) and text columns (umi_seq, repeat annotations); the other numeric columns (quality scores, distances to the lamina / nucleolar bodies, GC) arespot_tracks. Cells: PGP1"<cell_id>"; embryos"e<embryo_id>.<cell_id>"withembryo,stage,cell_index. Reads off the primary chromosomes (chrM, unplaced contigs, several UMIs, codes the authors leave undescribed) arepoints['other_reads']with theirchrom_labelandpos.- Return type:
- uchrom.io.read_juicer_domains(path: str | PathLike, *, chrom: None | str | Sequence[str] = None, chrom_prefix: str | None = 'chr', sheet: str | None = None) DataFrame[source]¶
A Juicer domain list (Arrowhead; e.g. GEO GSE63525
*_Arrowhead_domainlist.txt.gz) as a domain table.- Parameters:
path – The list (optionally gzipped), or a workbook (
.xlsx) withsheet.chrom – Only the domains on these chromosomes (names with or without the prefix).
chrom_prefix – Added to chromosome names that lack it;
Nonekeeps the names of the file.
- Returns:
chrom, start, endfollowed by the list’s other columns as they are (Arrowhead:colorand the scoresf1…f5), sorted by position; domains may nest.- Return type:
DataFrame
- uchrom.io.read_juicer_loops(path: str | PathLike, *, chrom: None | str | Sequence[str] = None, chrom_prefix: str | None = 'chr', sheet: str | None = None) DataFrame[source]¶
A Juicer loop list (HiCCUPS; e.g. GEO GSE63525
*_HiCCUPS_looplist.txt.gz) as a pair table.- Parameters:
path – The list (
.txt/.bedpe, optionally gzipped), or a workbook (.xlsx, e.g. a paper’s supplementary data; needsopenpyxl) withsheet.chrom – Only the loops on these chromosomes (names with or without the prefix).
chrom_prefix – Added to chromosome names that lack it (
"21"→"chr21", the names of UCSC-style maps);Nonekeeps the names of the file.
- Returns:
chrom1, start1, end1, chrom2, start2, end2(the two anchors, bp) followed by the list’s other columns as they are (HiCCUPS:color, o— observed —, the four local expectedse_bl, e_donut, e_h, e_vand their FDRs,num_collapsed,centroid1, centroid2, radius), sorted by position.- Return type:
DataFrame
- uchrom.io.read_looptrace(path, *, spot_size: dict | None = None)[source]¶
Read a LoopTrace table of Beckwith et al. 2025 into a
ChromDataof traces.- Parameters:
path (path or file object) – One of the three tables (
.csv/.csv.gz); the table is recognised by its columns.spot_size (dict, optional) – Spot size (bp) of each library, default
SPOT_SIZE.
- Returns:
One spot per fitted locus (rows without a genomic position — the region-detection frame — are left out), coordinates in nm; bins = windows of the library’s spot size centred on
g_pos(clipped halfway to the neighbours),bins['region']the library. The fit (A,BG,sigma_xy,sigma_z) is inspot_tracks(NaN for the authors’ placeholder of a spot that was not fitted,A = BG = -1,sigma_z = -300,sigma_xy = -140);g_pos, the frame and the fieldpositionare spot columns. Mitotic table: the authors’QCis the spot columnqc_pass,coordshold the spots that passed it (NaN otherwise) andlayers['fit']every fit (NaN where none was made); cells = nuclei (<exp>/<position>/<nuc_label>) withcell_typeandphase. Comparison table: cells = nuclei withnuc_total_int. Combined table: traces numbered per (cell type, experiment, region) from the row blocks, no cells (coordinates in each trace’s crop).tracesholdregion,chrom,cell_type,exp,position(andcell_id/phase).- Return type:
- uchrom.io.read_mina_mat(paths, loci: DataFrame, *, cell_prefix: str = '', cell_fields: Sequence[str] = ('seurat_midgroup', 'CellType', 'CellLableAssign'), trace_fields: Sequence[str] = ('CellLableAssign', 'rg'), replicates_by_fov_order: bool = False, genome_assembly: str = 'hg38', source: str | None = None)[source]¶
Read Wang-lab MATLAB traces (module docstring) into a
ChromData(coordinates in µm).- Parameters:
paths (path or list of paths) –
.matfiles of one layout (oneChrFOV*/ChrAllstruct each); a list is read in order and concatenated (e.g. the 64 per-FOV files of one tonsil section).loci (DataFrame or list of DataFrames) –
chrom,start,endof the loci in the order of the traces’r/xvectors. For the per-cell layout alsochrom_id(theTracesentry, 1-based): the rows of onechrom_idin locus order. A list gives each file its own loci (e.g. two regions traced in the same cells).cell_prefix (str) – Put before every cell id:
"<prefix><FOV>_<CellID>". Traces are"<cell>_<chrom>_<k>"(per-cell layout, k = copy) or"<prefix>t<n>"(per-trace layout, n = element).cell_fields (names) – Scalar fields copied to
cells(per-cell layout) ortraces(per-trace layout) when present (seurat_midgroup->cell_type; others keep their names).CellLableValuesandCenterof the per-trace layout go totracesaslabel_value_<i>/center_x/center_y.trace_fields (names) – Scalar fields copied to
cells(per-cell layout) ortraces(per-trace layout) when present (seurat_midgroup->cell_type; others keep their names).CellLableValuesandCenterof the per-trace layout go totracesaslabel_value_<i>/center_x/center_y.replicates_by_fov_order (bool) – Per-trace layout: the file concatenates experiments whose fields of view are each numbered from 0 (the lab’s merged
ChrAllof two replicates); a new experiment starts wherever the FOV number decreases. The cells become"<prefix>r<rep>_<FOV>_<CellID>"withcells["replicate"](1, 2, …).
- Returns:
cells:fov,cell_label(the file’sCellID),n_traces, the fields;traces:cell_id,chrom(per-cell layout:copy), the fields;uns:genome_assembly,xyz_unit=micron.- Return type:
- uchrom.io.read_phased_pairs(path) DataFrame[source]¶
Read phased contacts (hickit
.pairsor Dip-C.con) into a DataFrame withchrom1, pos1, hap1, chrom2, pos2, hap2(+phase_prob00 .. phase_prob11when present). Haplotypes are int8: 0, 1, -1 = unknown. A.pairsfile without phase columns gives -1 everywhere.
- uchrom.io.read_seqfish_detections(path, *, loci: ~pandas.DataFrame, member: str | None = None, voxel_nm: ~typing.Sequence[float] = (103.0, 103.0, 250.0), chrom_name: ~typing.Callable[[int], str] = <function mouse_chrom_name>, cell_prefix: str = '')[source]¶
Read raw DNA seqFISH+ detections into a
ChromDataof untraced spots.- Parameters:
path (path) – A detection CSV, or a zip of them (then
membernames the CSV, e.g."DNAseqFISH+25kbloci-E14-replicate1.csv"); read in place, nothing is extracted.loci (DataFrame) – The genomic locus of every probe:
chrom, start, endand the key of the file’s locus column —region(theregionIDwithin its chromosome, 25-kb files) orname(thegeneID, 1-Mb files). Every detection’s locus must be in it.member (str, optional) – The CSV inside a zip.
voxel_nm ((float, float, float)) – Voxel size: coordinates become nm (
x * voxel_nm[0]…).chrom_name (callable) –
chromID-> chromosome name (default: mouse, 20 = chrX).cell_prefix (str) – Prefixed to the cell ids (
"<prefix><fov>_<cellID>"), e.g. to tell replicates apart.
- Returns:
One spot per detection, in the file’s order; coordinates in nm.
cell_id = "<fov>_<cellID>";trace_id = "<cell_id>_<chrom>": one candidate set per (cell, chromosome) — all detections of a chromosome in a cell, both homologs together, not a fibre (uns['trace_kind'] = 'set'). Spot columnsspot_id(row number in the file),fov,channel, the locus key (regionorname) andlabel(labelID, when the file has it); the other numeric columns (intensities) arespot_tracks.- Return type:
See also
uchrom.im.trace.align_spotslink the detections into fibres.
- uchrom.io.read_seqfish_multiomics(spot_glob: str | Iterable[PathLike], *, locus_annotation: PathLike, cell_clustering: PathLike | None = None, leiden_to_cell_type: Dict[int, str] | None = None, allele_col: str = 'dbscan_ldp_nbr_allele', keep_unclustered: bool = False, out: PathLike | None = None, memory_budget=None) ChromData[source]¶
Load Takei 2025 DNA seqFISH+ cerebellum data into a ChromData.
- Parameters:
spot_glob – Either a single CSV path, a glob string (e.g.
'cerebellum_rep*/cerebellum_rep*_pos*.csv'), or an iterable of paths. Each file is the per-FOV DNA seqFISH+ spot table with 76 columns documented in the Zenodo 7693825 readme.locus_annotation – Path to the 25-kb locus map CSV from the CaiGroup/dna-seqfish-plus-multi-omics GitHub repo (
data/annotation/LC1-100k-09022022-mm10-25kb-meta.csv). Used to resolve thenamecolumn (e.g.chr7-1628) tochrom/start/end.cell_clustering – Optional path to the per-cell clustering CSV (
data/cerebellum/clustering/100k-002-001-cerebellum_mRNA_cluster_nuc_vol_filtered.csv). If given, the loader populatescells(withleiden,cell_type, the cell positioncentroid_x/y/z— voxel coordinates in the FOV, recorded inuns['cell_spatial']with the voxel size, socd.cell_positions(physical=True)is in µm in the frame ofcoords—fov("{rep}_{fov}"), nuclear volume, doublet, batch) andcellm['umap']. (Before format 2.3 the centroid columns werex_centroid…;cell_positions()still reads them.)leiden_to_cell_type – Mapping from leiden cluster id (int) to cell-type string. Used to derive
cells.cell_type. IfNone, the published cerebellum mapping is used (Granule/Bergmann/MLI1/Purkinje/MLI2+PLI), with all uncovered clusters labelled'Other'.allele_col –
Which homologous-chromosome assignment defines
trace_id. One of'dbscan_allele','dbscan_ldp_allele','dbscan_ldp_nbr_allele'. Defaults to the highest-recalldbscan_ldp_nbr_allele(the column referenced as canonical in the published analysis notebooks).Warning
dbscan_ldp_nbr_alleleoften merges the two homologs of a chromosome into one trace. On the Takei 2025 cerebellum data (1e7 spots) 75.6 % of its traces observe some locus twice and the median genomic–spatial Spearman ρ per trace is 0.19;dbscan_ldp_allelegives 0 % such traces and ρ = 0.41 but keeps only 54 % of the spots. For analyses that need one fibre per trace (distance maps, TAD / loop calling, tracing statistics) preferallele_col="dbscan_ldp_allele"; checktraces["n_duplicate_loci"]whichever column you use.keep_unclustered – DBSCAN noise spots have
allele == -1. WhenFalse(default) these are dropped before constructing theChromData. SetTrueto keep them as their ownallele=-1traces (useful for QC).out – Streaming import: write the result to this
.chromdata.zarrstore, one CSV (FOV) at a time, withChromDataWriter, and return it opened backed. Peak memory is one FOV’s parse (the raw CSV frame) — not the sum of the FOVs — plus the writer’s merge pieces (bounded bymemory_budget). The store equalsread_seqfish_multiomics(...).write(out).memory_budget – Working-memory budget of the streaming writer (default
uchrom.settings.memory_budget).
- Returns:
coords: (n_spots, 3) μmspots: chrom / start / end / trace_id / cell_id (compositef"{rep}_{fov}_{cellID}"andf"{rep}_{fov}_{cellID}_{chrom}_a{allele}")tracks: 62 columns = 59 z-scores +dot_int, n_rad_score, n_per_dist(um)traces(indextrace_id):allele(theallele_colvalue that defines the trace),n_spots,n_loci,n_duplicate_loci(spots whose locus already occurs in the trace — > 0 means homologs were merged), and for each other allele column<col>_majority/<col>_agreement(its most common value in the trace and the fraction of spots with it)cellsandcellm['umap']ifcell_clusteringis givenuns: genome_assembly=’mm10’, xyz_unit=’um’, voxel sizes, Zenodo record id, the leiden map actually used, and the allele-column choice
- Return type:
- uchrom.io.read_seqfish_transcriptome(transcriptomic_data: str | Path | Iterable[str | Path] | None = None, *, dataset: str = 'cerebellum', assay: str = 'mrna', replicate: int | None = None, observed_cell_ids: Iterable[str] | None = None, download: bool = False, data_dir: str | Path | None = None, chunksize: int = 500000)[source]¶
Read Takei 2025 RNA seqFISH spot CSVs into a cell × gene AnnData.
The Zenodo transcriptomic archive stores super-resolved RNA spots, not a precomputed expression matrix. This function aggregates those spots into a sparse count matrix with cell ids matching
read_seqfish_multiomics():rep_fov_cellID.
- uchrom.io.read_snapfish(coor, ann, *, chrom: None | str | Mapping[str, str] = None, region_name: str = 'region', cell_id: bool | Callable[[str], str] = False, keep_missing: bool = True, xyz_unit: str = 'nm', genome_assembly: str | None = None, sep: str = '\t')[source]¶
Read a SnapFISH / SnapFISH-IMPUTE coordinate table and its locus annotation into a
ChromData.- Parameters:
coor (path or DataFrame) – Coordinate table:
region(orchr),haploid(orcell_id),pos,x,y,z; undetected loci are rows with NaN coordinates (SnapFISH-IMPUTE’s*_coor_wnan.txt).ann (path or DataFrame) – Locus annotation:
region(orchr),pos,start,end. Its loci become the locus axisbins(the whole probe panel, also loci without any detection).chrom (str or dict, optional) –
None(default): each region is a chromosome of its own, named as the region (SnapFISH’s view). A chromosome name: every region is a copy (allele) of that chromosome — e.g. the 129 and CAST alleles of mouse chr3 — and the region is kept as the spot columnregion_name; a dict maps region -> chromosome the same way.region_name (str) – The spot (and trace) column that holds the region when
chromis given (e.g."allele").cell_id (bool or callable) –
False: no cells.True: the haploid ids are cell ids (one trace per cell and region, as when the regions are the two alleles of a locus); a callable maps a haploid id to its cell id.keep_missing (bool) – Keep the undetected loci as NaN rows (default) or drop them (absent rows).
xyz_unit (str) – Recorded in
uns(SnapFISH coordinates are in nm; the tables name no assembly).genome_assembly (str) – Recorded in
uns(SnapFISH coordinates are in nm; the tables name no assembly).sep (str) – Column separator of the files.
- Returns:
One trace per (haploid, region),
trace_id = "<haploid>_<region>"; spot columnspos(andregion_name);traceswith the region, chromosome, cell, number of loci and of detected loci;cells(in the order of the table) whencell_idis given. Rows keep the table’s order.- Return type:
Examples
>>> cd = read_snapfish("mESC_Sox2_coor_wnan.txt", "mESC_Sox2_ann.txt", ... chrom="chr3", region_name="allele", cell_id=True, genome_assembly="mm10")
- uchrom.io.read_su2020_hic(path, *, label_offset: int | None = None) Tuple[DataFrame, ndarray][source]¶
Read one of the Su et al. 2020 binned Hi-C tables (
Hi-C_contacts_chromosome21.tsv, …).The authors summed Rao et al. 2014 IMR90 Hi-C reads into bins centred on their imaged loci (50 kb for the chromosome-scale loci, 500 kb around each 100 kb genome-scale locus) and label rows and columns with the locus names of the tracing tables.
uchrom.io.write_locus_cool()writes the result as a.cool.- Parameters:
path (str or Path) – The square tab-separated table (first column and header: locus labels).
label_offset (int, optional) – Subtracted from both ends of a label; default 1 when every label start and end is odd (the chromosome-scale labels count from 1,
chr21:10400001-10450001), else 0 (genome scale) — as inread_su2020_tracing().
- Returns:
loci (DataFrame) –
chrom,start,endof the rows / columns, in file order (index 0..n-1).counts (ndarray (n, n)) – float64, as in the file (read counts).
- uchrom.io.read_su2020_tracing(path, *, unit: str = 'micron', keep_missing: bool = False, extras: bool | str | Iterable[str] = True, label_offset: int | None = None, genome_assembly: str = 'hg38')[source]¶
Read a Su et al. 2020 chromatin-tracing table into a
ChromData.Reads both layouts of the authors’ Zenodo record 3928890 (module docstring): the chromosome-scale tables (
chromosome21.tsv,chromosome2.tsv, …: one trace per imaged chromosome copy,trace_id= the authors’ copy number, no cells) and the genome-scale DNA-MERFISH tables (genomic-scale.tsv, …:cell_id= the authors’ cell number, one trace per cell, chromosome and homolog,trace_id = "<cell>_<chrom>_h<homolog>";cells["experiment"],traces[["cell_id", "chrom", "homolog"]]). Every locus of the file is a bin, also one that was never detected.- Parameters:
path (str or Path) – The
.tsvtable.unit ({"micron", "nm"}) – Unit of the coordinates (and of the distance columns); the files are in nm.
keep_missing (bool) – Keep undetected loci as rows with NaN coordinates; by default they are left out.
extras (bool, str or list of str) – The optional columns to read —
True(default): all the file has;False: none; or names among"genes"(bin_tracks: the genes listed for the locus,;-separated),"n_genes"(bin_tracks: their number),"transcription"(spot_tracks:on/offper gene of the locus,;-separated, in the order ofgenes),"distance_to_lamina"/"distance_to_nucleoli"/"distance_to_speckles"(spot_tracks, inunit) and"cell_cycle"(traces: the cell-cycle state of the copy).TSS ZXY(nm)is not read.label_offset (int, optional) – Subtracted from both ends of a locus label. Default: 1 for the chromosome-scale tables (their labels count from 1:
chr21:10400001-10450001is the 50 kb locus starting at 10,400,000 andchr2:1-50001the first 50 kb of chr2), 0 for the genome-scale ones (chr1:2950000-3050000, 100 kb).genome_assembly (str) – Recorded in
uns(the files are on hg38).
- Returns:
uns:genome_assembly,xyz_unit,source.- Return type:
- uchrom.io.replicate_deviation(cd, layers: Sequence[str] = ('rep1', 'rep2'), *, reflection: bool = True) Tuple[DataFrame, ndarray][source]¶
How far other runs of the same cells (
cd.layers) are fromcd.coords, after superposition.Each layer is superposed on the main structure cell by cell (one rigid motion for all of a cell’s particles, all homologs; mirror images allowed with
reflection, since contacts do not fix the handedness) and the deviations of the particles measured — the replicate RMSD by which Tan et al. 2018 (Science 361:924) judged their Dip-C structures.- Parameters:
cd – Structures with the runs as layers (
read_3dg_cells()).layers – Layer names.
reflection – Allow an improper rotation.
- Returns:
per_cell (DataFrame) – Indexed by cell:
rmsd_<layer>(RMSD over the particles of both),median_dev_<layer>(median particle deviation) for every layer, andmirrored_<layer>(the mirror image fitted better).per_spot (ndarray (n_spots,)) – Root mean square over the layers of each particle’s deviation (NaN without any layer value).
- uchrom.io.sort_chroms(names) list[source]¶
The distinct chromosome names of
names(any iterable, e.g.cd.bins["chrom"]) in natural order (chrom_sort_key()):["chr1", "chr2", ..., "chr10", ..., "chrX"].
- uchrom.io.upgrade_h5cd(src: str | Path, dst: str | Path | None = None, *, overwrite: bool = False, coord_dtype: str = 'float64') dict[source]¶
Read
src(.h5cd1.x / 2.0, or any ChromData store) and write it todstin the current format (.chromdata.zarr/.cdz); a zarr / cdz source is read in its original row order.dstdefaults to<src stem>.chromdata.zarrnext tosrc; its suffix picks the container.coord_dtypeis the storage dtype ofcoords/layers(seeChromData.write()).Returns a summary: source / target versions and containers,
n_spots,n_binsand which tracks are bin- vs spot-level.srcis never modified;dstmust differ from it.
- uchrom.io.write_higashi_inputs(pairs_files: Mapping[str, str | Path], out_dir: str | Path, *, label_info: DataFrame, resolution: int, genome_reference: str, chrom_list: list[str], chromsizes: Mapping[str, int] | str | Path | None = None, config_overrides: dict[str, Any] | None = None) Path[source]¶
Materialise a full Higashi v2 input directory.
Produces under
out_dir:data/<cell_name>.txt— one per cell, tab-separatedchrom1, pos1, chrom2, pos2, count(no header).filelist.txt— one absolute path per line, inlabel_inforow order.label_info.pickle— metadata aligned to filelist row order.chromsizes.tsv—chrom<TAB>size(only ifchromsizesgiven).config.JSON— pointers + genome + resolution + chrom_list +genome_reference_path(when chromsizes were provided).
label_infomust contain acell_namecolumn whose values exactly match the keys ofpairs_files; filelist followslabel_inforow order so FastHigashi’srestore_order=Truealigns to it.chromsizesis required by FastHigashi at runtime (config['genome_reference_path']). Pass either a{chrom: size}mapping (a chromsizes.tsv will be written toout_dir) or an existing path to a tab-separated chromsizes file.
- uchrom.io.write_label_info(cells: DataFrame, out_path: str | Path) Path[source]¶
Write a per-cell metadata DataFrame to Higashi’s
label_info.pickle.Higashi expects a
dict[str, np.ndarray], one entry per metadata column, aligned row-by-row to the filelist order. Row order ofcellsis preserved.
- uchrom.io.write_locus_cool(loci, matrix, path, *, assembly: str | None = None, balance: bool | dict = True) str[source]¶
Write a contact matrix over arbitrary loci (e.g. imaged loci, uneven) as a
.cool.Cooler bins tile each chromosome, so the bin of a locus runs from its start to the start of the next locus of the chromosome (the last one to its own end), after an empty leading bin from 0 to the first locus (left out when the first locus starts at 0). Fetching a region then returns the loci whose start lies in it, and
cd.link_cool(path, key=...)links the file to theChromDataof the loci.- Parameters:
loci (DataFrame) –
chrom,start,endof the rows / columns ofmatrix. Starts must differ within a chromosome; the loci are sorted (chromosomes in order of first appearance, then start).matrix (array-like (n, n)) – Symmetric, non-negative counts; zeros and NaN are not stored. Integer-valued matrices are stored as integer counts, others as float counts.
path (str or Path) – The
.coolfile to write (replaced atomically).assembly (str, optional) – Genome assembly recorded in the file.
balance (bool or dict) – ICE-balance the map and store the
weightcolumn (cooler.balance_coolerwith its defaults, or with the keyword arguments of a dict).
- Returns:
path.- Return type:
- uchrom.io.write_phased_pairs(df: DataFrame, path, chrom_sizes=None) None[source]¶
Write a phased table as a hickit-readable
.pairs(readID chr1 pos1 chr2 pos2 strand1 strand2 phase0 phase1; strands.;#chromsize:lines fromchrom_sizes).
- uchrom.io.write_pyhim_trace(cd, path, *, comments: None | Sequence[str] | Mapping[str, object] = None, loci: bool = True, overwrite: bool = True) Path[source]¶
Write a
ChromDataas a PyHiM chromatin-trace table (Astropy ECSV; needsastropy).PyHiM (Devos et al. 2024, Genome Biology) writes one row per spot with the columns
Spot_ID, Trace_ID, x, y, z, Chrom, Chrom_Start, Chrom_End, ROI #, Mask_id, Barcode #, labelandkey=valuestrings inmeta['comments'];ChromData.from_pyhim_trace()reads it back.Column mapping (the inverse of the reader’s):
x, y, z:coordsin µm (PyHiM’s unit), converted fromuns['xyz_unit'](nm, µm);Chrom, Chrom_Start, Chrom_End: the spot loci (loci=Falseleaves them empty / 0, as PyHiM writes them without a barcode -> genome map; read such a file withbarcode_dict=);Trace_ID:trace_id;Mask_id:cell_id(integers when every id is one; 0 without cells);Barcode #: spot columnbarcode, else the locus number within its chromosome (1 = the first bin of the chromosome inbins);Spot_ID: spot columnspot_id, else"<trace_id>_<barcode>";ROI #: spot columnroi_id, else 0;label: spot columnlabel, else"None".
Spots with NaN coordinates are written as NaN rows.
- Parameters:
cd (ChromData)
path (path of the
.ecsvfile)comments (list of str or dict, optional) – More
meta['comments']("key=value"strings, or a dict);xyz_unit=micronandgenome_assembly=(fromuns) come first.loci (bool) – Write the genomic columns (default) or leave them empty.
overwrite (bool) – Replace an existing file.
- Return type:
Path of the written file.
Format upgrade¶
Convert ChromData files to the current container (.chromdata.zarr).
ChromData.read no longer reads the HDF5 .h5cd container (format 1.x
and 2.0); this converts such a file once, after which it reads fast and can
be backed (ChromData.read(path, backed=True)):
python -m uchrom.io.upgrade old.h5cd new.chromdata.zarr
python -m uchrom.io.upgrade data/*.h5cd --out-dir converted/ # <stem>.chromdata.zarr
python -m uchrom.io.upgrade data/*.h5cd --out-dir converted/ --format cdz
What changes (see docs/source/guide/chromdata_2_0_design.md):
1.x → 2.0 data model:
bins= the unique spot loci;spotsstorebin_idinstead ofchrom/start/end(still available viacd.spots/cd.to_dataframe()); the spot-aligned 1.xtrackssplit into bin-leveltracks(columns constant within every bin) andspot_tracks;the container: Zarr v3 + Parquet, spots sorted by (cell, trace, bin) with an
index/of row offsets (index/source_rowkeeps the original order).
The target format follows the destination suffix (.chromdata.zarr or
.cdz). The source is never modified. Older zarr / cdz stores are
rewritten in the current layout too.
- uchrom.io.upgrade.convert(src: str | Path, dst: str | Path | None = None, *, overwrite: bool = False, coord_dtype: str = 'float64') dict¶
the conversion is not specific to .h5cd sources
- uchrom.io.upgrade.default_target(src: str | Path, fmt: str = 'zarr', out_dir: str | Path | None = None) Path[source]¶
<dir>/<stem>.chromdata.zarr(or.cdz) forsrc.
- uchrom.io.upgrade.file_format_version(path: str | Path) str[source]¶
The
uchrom_format_versionof a ChromData file ("1.0"for an unversioned.h5cd).
- uchrom.io.upgrade.upgrade_h5cd(src: str | Path, dst: str | Path | None = None, *, overwrite: bool = False, coord_dtype: str = 'float64') dict[source]¶
Read
src(.h5cd1.x / 2.0, or any ChromData store) and write it todstin the current format (.chromdata.zarr/.cdz); a zarr / cdz source is read in its original row order.dstdefaults to<src stem>.chromdata.zarrnext tosrc; its suffix picks the container.coord_dtypeis the storage dtype ofcoords/layers(seeChromData.write()).Returns a summary: source / target versions and containers,
n_spots,n_binsand which tracks are bin- vs spot-level.srcis never modified;dstmust differ from it.