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

Contact-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) / 2 is the number of trans contacts).

add(cell, chrom1, pos1, chrom2, pos2, strand1=None, strand2=None) → None[source]

Count a chunk of contacts.

cell is the row of each contact (-1: not counted), chrom1 / chrom2 the index of its chromosomes in chroms (-1: another chromosome), pos1 / pos2 its positions; strand1 / strand2 (‘+’ / ‘-’ or booleans for ‘-’) are needed when orientation is 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).

property n_cis: ndarray
property n_trans: ndarray
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 to cd.cells by 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 with per_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_trans of cd.cells; the record cd.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
static parse_text(text, valid_chr_names=None)[source]
class uchrom.io.WindowCounts(cells: Sequence, windows: DataFrame, resolution: int, chroms: Sequence[str])[source]

Bases: object

Contacts 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: cell rows (-1: skip), chromosome codes (index into chroms, -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 (column kind; 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]
save(path: str | PathLike, **meta) → None[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, count sorted 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, pos bp, snapped to the bin grid): left (both ends in the window bp upstream), right (both downstream) and cross (one end on each side). The columns feature (the boundary’s row) and part say 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 the chr prefix; numbered chromosomes first, then the others by name, the mitochondrial M / MT last).

uchrom.io.convert_chromdata(src: str | Path, dst: str | Path | None = None, *, overwrite: bool = False, coord_dtype: str = 'float64') → dict

Read src (.h5cd 1.x / 2.0, or any ChromData store) and write it to dst in the current format (.chromdata.zarr / .cdz); a zarr / cdz source is read in its original row order.

dst defaults to <src stem>.chromdata.zarr next to src; its suffix picks the container. coord_dtype is the storage dtype of coords / layers (see ChromData.write()).

Returns a summary: source / target versions and containers, n_spots, n_bins and which tracks are bin- vs spot-level. src is never modified; dst must differ from it.

uchrom.io.count_contacts(df, particles, min_skip=2)[source]

Count contacts between all particles.

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)) and max_distance the longest chromosome of chromsizes by 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_version of a ChromData file ("1.0" for an unversioned .h5cd).

uchrom.io.genome_bins(chromsizes: Mapping, resolution: int) → DataFrame[source]

Fixed-size bins chrom, start, end of 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 / .con file as chunks chrom1, pos1, chrom2, pos2 (chromosomes as categoricals, 1-based positions).

src is a path or a callable opening a binary stream (e.g. a member of a tarball); name is the file name that tells a .con from a .pairs when src is 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 ChromData that stores chromatin tracing geometry and spot-level tracks. The aggregated RNA expression matrix is attached as cd.linked_adata. Both objects are ordered on the same cell ids, and the ChromData receives adata.obs/adata.obsm via ChromData.link_anndata().

cd_path is where the ChromData is written (.chromdata.zarr or .cdz). h5cd_path is 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 as cd.linked_adata. If paired .chromdata.zarr / .h5ad artifacts already exist under data_dir, they are reused. Otherwise, when download=True, the DNA seqFISH+ archive, the transcriptome zip (Zenodo record 7693825) and the annotation / clustering tables (CaiGroup GitHub) are fetched with uchrom.datasets (takei2025_cerebellum or takei2025_cerebellum_rep2, takei2025_rna; md5-checked, into the data directory) and the linked artifacts are built.

Parameters:
  • replicate – Cerebellum replicate to load. Currently 1 or 2.

  • 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) at resolution: peak — the (2 peak + 1)^2 pixels around the loop pixel — and donut — the ring of pixels between donut[0] and donut[1] pixels from it (Chebyshev distance), as four non-overlapping strips. Columns feature and part.

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.JSON dict.

Fields follow the v2 schema from the Higashi wiki and FastHigashi’s runtime expectations (input_format, contact_header, header_included). overrides are 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]

ContactStats of per-cell contact files ({cell: path}, the inputs of pairs_to_scool()). The files’ strands are not read, so orientation is None; chromosome names match with or without a chr prefix.

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 so pos1 <= pos2, and duplicates are collapsed by summing into count.

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) where opener() returns a binary stream (e.g. a tarball member).

  • out – The .scool to 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)

  • bin_pairs()).

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’ .3dg structures as one ChromData: 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’s rep1 / rep2): stored as cd.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 in uns["structures"]["layers"]). Each run has its own frame (no superposition here; see replicate_deviation()).

  • cells – Cell metadata indexed by cell id (default: just the ids of files).

  • uns – Extra uns entries.

  • **read_kw – For read_3dg_structure() (particle_size, particle_position, hap_names, …).

Returns:

spots: chrom, start, end, trace_id, cell_id sorted 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; cells gains n_particles and n_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:

ChromData

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 .3dg layout (Dip-C or hickit) as a table of particles.

Parameters:
  • path – A .3dg file, 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 / b homologs (default ("pat", "mat"), as Dip-C names them; a is the phase-0 haplotype of the phased variants). Dip-C names are kept as written.

  • chr_prefix – Prefix chr to 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, start clipped at 0), homolog (None for 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). With particle_position="end" a particle at position 0 (it would hold (-size, 0], i.e. nothing: Dip-C starts some chains there) is left out. attrs holds format, particle_size, particle_position and n_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 prefixed c<k>-, traces["core_file"] naming the table) and optionally spot_quality / spot_bio (one or several tables keyed by Spot_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) and locus_shifts ((chrom, start_from, start_to, offset): loci whose start lies in the range moved by offset bp — a correction the caller knows from the authors, recorded in uns["fofct_locus_shifts"]) and trace_by (core columns whose values, joined, are the trace id, where the deposit’s Trace_ID is not one; recorded in uns["fofct_trace_keys"]) and fov_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 in uns["fofct_fov_columns"]).

  • genome_assembly (str, optional) – Recorded in uns; default: the genome_assembly of the core tables’ headers (they must agree).

Returns:

spots: one per detected spot (rows without coordinates or without a locus — an empty Chrom, as the unassigned spots of Hafner et al. 2023 — left out, counted in uns["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 column FOVid / 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 for Cell_ID 0, 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, the meta values 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 UCSC chr prefix: 3R -> chr3R, 19 -> chr19, Chr14 -> chr14).

Return type:

ChromData

uchrom.io.read_igs(path, *, resolution: int = 1000000)[source]

Read an IGS data table (Payne et al. 2021) into a ChromData of reads.

Parameters:
  • path (path) – Table_S1_pgp1_data_table.csv (human fibroblasts) or Table_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), homolog as in the traces table — mat / pat (embryos), h1 / h2, none (reads outside the territories), overlap. Spot columns spot_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) are spot_tracks. Cells: PGP1 "<cell_id>"; embryos "e<embryo_id>.<cell_id>" with embryo, stage, cell_index. Reads off the primary chromosomes (chrM, unplaced contigs, several UMIs, codes the authors leave undescribed) are points['other_reads'] with their chrom_label and pos.

Return type:

ChromData

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) with sheet.

  • chrom – Only the domains on these chromosomes (names with or without the prefix).

  • chrom_prefix – Added to chromosome names that lack it; None keeps the names of the file.

Returns:

chrom, start, end followed by the list’s other columns as they are (Arrowhead: color and the scores f1 … 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; needs openpyxl) with sheet.

  • 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); None keeps 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 expecteds e_bl, e_donut, e_h, e_v and 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 ChromData of 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 in spot_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 field position are spot columns. Mitotic table: the authors’ QC is the spot column qc_pass, coords hold the spots that passed it (NaN otherwise) and layers['fit'] every fit (NaN where none was made); cells = nuclei (<exp>/<position>/<nuc_label>) with cell_type and phase. Comparison table: cells = nuclei with nuc_total_int. Combined table: traces numbered per (cell type, experiment, region) from the row blocks, no cells (coordinates in each trace’s crop). traces hold region, chrom, cell_type, exp, position (and cell_id / phase).

Return type:

ChromData

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) – .mat files of one layout (one ChrFOV* / ChrAll struct 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, end of the loci in the order of the traces’ r / x vectors. For the per-cell layout also chrom_id (the Traces entry, 1-based): the rows of one chrom_id in 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) or traces (per-trace layout) when present (seurat_midgroup -> cell_type; others keep their names). CellLableValues and Center of the per-trace layout go to traces as label_value_<i> / center_x / center_y.

  • trace_fields (names) – Scalar fields copied to cells (per-cell layout) or traces (per-trace layout) when present (seurat_midgroup -> cell_type; others keep their names). CellLableValues and Center of the per-trace layout go to traces as label_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 ChrAll of two replicates); a new experiment starts wherever the FOV number decreases. The cells become "<prefix>r<rep>_<FOV>_<CellID>" with cells["replicate"] (1, 2, …).

Returns:

cells: fov, cell_label (the file’s CellID), n_traces, the fields; traces: cell_id, chrom (per-cell layout: copy), the fields; uns: genome_assembly, xyz_unit = micron.

Return type:

ChromData

uchrom.io.read_phased_pairs(path) → DataFrame[source]

Read phased contacts (hickit .pairs or Dip-C .con) into a DataFrame with chrom1, pos1, hap1, chrom2, pos2, hap2 (+ phase_prob00 .. phase_prob11 when present). Haplotypes are int8: 0, 1, -1 = unknown. A .pairs file 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 ChromData of untraced spots.

Parameters:
  • path (path) – A detection CSV, or a zip of them (then member names 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, end and the key of the file’s locus column — region (the regionID within its chromosome, 25-kb files) or name (the geneID, 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 columns spot_id (row number in the file), fov, channel, the locus key (region or name) and label (labelID, when the file has it); the other numeric columns (intensities) are spot_tracks.

Return type:

ChromData

See also

uchrom.im.trace.align_spots

link 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 the name column (e.g. chr7-1628) to chrom/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 populates cells (with leiden, cell_type, the cell position centroid_x/y/z — voxel coordinates in the FOV, recorded in uns['cell_spatial'] with the voxel size, so cd.cell_positions(physical=True) is in µm in the frame of coords — fov ("{rep}_{fov}"), nuclear volume, doublet, batch) and cellm['umap']. (Before format 2.3 the centroid columns were x_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. If None, 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-recall dbscan_ldp_nbr_allele (the column referenced as canonical in the published analysis notebooks).

    Warning

    dbscan_ldp_nbr_allele often 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_allele gives 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) prefer allele_col="dbscan_ldp_allele"; check traces["n_duplicate_loci"] whichever column you use.

  • keep_unclustered – DBSCAN noise spots have allele == -1. When False (default) these are dropped before constructing the ChromData. Set True to keep them as their own allele=-1 traces (useful for QC).

  • out – Streaming import: write the result to this .chromdata.zarr store, one CSV (FOV) at a time, with ChromDataWriter, 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 by memory_budget). The store equals read_seqfish_multiomics(...).write(out).

  • memory_budget – Working-memory budget of the streaming writer (default uchrom.settings.memory_budget).

Returns:

  • coords: (n_spots, 3) μm

  • spots: chrom / start / end / trace_id / cell_id (composite f"{rep}_{fov}_{cellID}" and f"{rep}_{fov}_{cellID}_{chrom}_a{allele}")

  • tracks: 62 columns = 59 z-scores + dot_int, n_rad_score, n_per_dist(um)

  • traces (index trace_id): allele (the allele_col value 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)

  • cells and cellm['umap'] if cell_clustering is given

  • uns: genome_assembly=’mm10’, xyz_unit=’um’, voxel sizes, Zenodo record id, the leiden map actually used, and the allele-column choice

Return type:

ChromData

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 (or chr), haploid (or cell_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 (or chr), pos, start, end. Its loci become the locus axis bins (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 column region_name; a dict maps region -> chromosome the same way.

  • region_name (str) – The spot (and trace) column that holds the region when chrom is 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 columns pos (and region_name); traces with the region, chromosome, cell, number of loci and of detected loci; cells (in the order of the table) when cell_id is given. Rows keep the table’s order.

Return type:

ChromData

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 in read_su2020_tracing().

Returns:

  • loci (DataFrame) – chrom, start, end of 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 .tsv table.

  • 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 / off per gene of the locus, ;-separated, in the order of genes), "distance_to_lamina" / "distance_to_nucleoli" / "distance_to_speckles" (spot_tracks, in unit) 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-10450001 is the 50 kb locus starting at 10,400,000 and chr2:1-50001 the 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:

ChromData

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 from cd.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, and mirrored_<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 (.h5cd 1.x / 2.0, or any ChromData store) and write it to dst in the current format (.chromdata.zarr / .cdz); a zarr / cdz source is read in its original row order.

dst defaults to <src stem>.chromdata.zarr next to src; its suffix picks the container. coord_dtype is the storage dtype of coords / layers (see ChromData.write()).

Returns a summary: source / target versions and containers, n_spots, n_bins and which tracks are bin- vs spot-level. src is never modified; dst must 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-separated chrom1, pos1, chrom2, pos2, count (no header).

  • filelist.txt — one absolute path per line, in label_info row order.

  • label_info.pickle — metadata aligned to filelist row order.

  • chromsizes.tsv — chrom<TAB>size (only if chromsizes given).

  • config.JSON — pointers + genome + resolution + chrom_list + genome_reference_path (when chromsizes were provided).

label_info must contain a cell_name column whose values exactly match the keys of pairs_files; filelist follows label_info row order so FastHigashi’s restore_order=True aligns to it.

chromsizes is required by FastHigashi at runtime (config['genome_reference_path']). Pass either a {chrom: size} mapping (a chromsizes.tsv will be written to out_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 of cells is 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 the ChromData of the loci.

Parameters:
  • loci (DataFrame) – chrom, start, end of the rows / columns of matrix. 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 .cool file to write (replaced atomically).

  • assembly (str, optional) – Genome assembly recorded in the file.

  • balance (bool or dict) – ICE-balance the map and store the weight column (cooler.balance_cooler with its defaults, or with the keyword arguments of a dict).

Returns:

path.

Return type:

str

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 from chrom_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 ChromData as a PyHiM chromatin-trace table (Astropy ECSV; needs astropy).

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 #, label and key=value strings in meta['comments']; ChromData.from_pyhim_trace() reads it back.

Column mapping (the inverse of the reader’s):

  • x, y, z: coords in µm (PyHiM’s unit), converted from uns['xyz_unit'] (nm, µm);

  • Chrom, Chrom_Start, Chrom_End: the spot loci (loci=False leaves them empty / 0, as PyHiM writes them without a barcode -> genome map; read such a file with barcode_dict=);

  • Trace_ID: trace_id; Mask_id: cell_id (integers when every id is one; 0 without cells);

  • Barcode #: spot column barcode, else the locus number within its chromosome (1 = the first bin of the chromosome in bins);

  • Spot_ID: spot column spot_id, else "<trace_id>_<barcode>";

  • ROI #: spot column roi_id, else 0; label: spot column label, else "None".

Spots with NaN coordinates are written as NaN rows.

Parameters:
  • cd (ChromData)

  • path (path of the .ecsv file)

  • comments (list of str or dict, optional) – More meta['comments'] ("key=value" strings, or a dict); xyz_unit=micron and genome_assembly= (from uns) 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; spots store bin_id instead of chrom/start/end (still available via cd.spots / cd.to_dataframe()); the spot-aligned 1.x tracks split into bin-level tracks (columns constant within every bin) and spot_tracks;

  • the container: Zarr v3 + Parquet, spots sorted by (cell, trace, bin) with an index/ of row offsets (index/source_row keeps 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) for src.

uchrom.io.upgrade.file_format_version(path: str | Path) → str[source]

The uchrom_format_version of a ChromData file ("1.0" for an unversioned .h5cd).

uchrom.io.upgrade.main(argv: list | None = None) → int[source]
uchrom.io.upgrade.upgrade_h5cd(src: str | Path, dst: str | Path | None = None, *, overwrite: bool = False, coord_dtype: str = 'float64') → dict[source]

Read src (.h5cd 1.x / 2.0, or any ChromData store) and write it to dst in the current format (.chromdata.zarr / .cdz); a zarr / cdz source is read in its original row order.

dst defaults to <src stem>.chromdata.zarr next to src; its suffix picks the container. coord_dtype is the storage dtype of coords / layers (see ChromData.write()).

Returns a summary: source / target versions and containers, n_spots, n_bins and which tracks are bin- vs spot-level. src is never modified; dst must differ from it.