gunz_cm.structs package#
Module contents#
Data structures module.
This module is the home for typed data shapes that the DOP campaign
(v2.18.0 → v2.25.0) populated. It is the canonical surface for
DOP Principle 1 (separate code from data) and Principle 4 (illegal
states unrepresentable): data shapes live here as frozen Pydantic
models, NamedTuples, and Annotated type aliases, while the code
that operates on them lives in loaders/, converters/,
reconstructions/, etc.
Public exports#
Annotated type aliases (Phase 1):
BinSizeBP—intwithField(gt=0)for bin sizes in bpDownsampleRatio—intwithField(gt=0)for downsampling factorsBinCount—intwithge=1, le=10_000_000for bin countsChromName—strwith regex^(chr)?[A-Za-z0-9_.-]+$for chrom namesRegionSpec—strwithmin_length=1, max_length=128for region specs
Frozen Pydantic models:
CmFrameSchema— column contract for a contact-matrix DataFrameLoaderConfig— typed boundary forload_cm_data
Value types:
LazyMatrixView— NamedTuple holding a loader + kwargs for deferred materializationmaterialize()— free function: invokeview.loader(**view.kwargs)
Conflict policy (Phase 7):
ConflictPolicy—Literal["error", "overwrite", "skip"]from_legacy_flags()— migrate legacy(overwrite, exist_ok)pair
DOP alignment#
Phase 1 establishes DOP Principles 1 and 3. Phases 2/6/7 extend the
module with conversion functions (Phase 2), loader config (Phase 6),
and conflict policy (Phase 7). See the release notes at
docs/release-notes/v2.{18..25}.0.md for per-phase detail.
Examples
Canonical import path for users:
from gunz_cm.structs import (
LoaderConfig, RegionSpec, ConflictPolicy, from_legacy_flags,
CmFrameSchema, LazyMatrixView, materialize,
)
- class gunz_cm.structs.CmFrameSchema(*, row_col: str, col_col: str, count_col: str, raw_count_col: str | None = None)[source]#
Bases:
BaseModelCanonical column contract for a contact-matrix DataFrame.
- Parameters:
row_col (str) – Column name holding the row bin index (0-based, local to the loaded region).
col_col (str) – Column name holding the column bin index (0-based, local to the loaded region).
count_col (str) – Column name holding the count (raw or balanced, depending on the loader’s
balancingargument).raw_count_col (str or None) – Optional column name holding raw (unbalanced) counts. Present only when the loader is invoked with
return_raw_counts=True.
Examples
- has_raw_count() bool[source]#
Return True if this schema carries a separate raw-count column.
Examples
>>> CmFrameSchema(row_col="r", col_col="c", count_col="v").has_raw_count() False >>> CmFrameSchema(row_col="r", col_col="c", count_col="v", raw_count_col="raw_v").has_raw_count() True
- model_config: ClassVar[ConfigDict] = {'extra': 'forbid', 'frozen': True}#
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class gunz_cm.structs.LazyMatrixView(loader: t.Callable[..., t.Any], kwargs: dict[str, t.Any])[source]#
Bases:
NamedTupleImmutable recipe for materializing a contact matrix on demand.
- Parameters:
loader (Callable[..., t.Any]) – Zero-argument-callable that, when invoked, returns the materialized contact matrix (typically a
scipy.sparse.csr_matrixornumpy.ndarray). The loader is invoked bymaterialize(), passingself.kwargs.kwargs (dict[str, t.Any]) – Keyword arguments to pass to
loaderat materialize time. Stored as a plaindict(not aMappingProxyType) for ergonomicview.kwargs["path"] = "x.hic"updates prior to materialization, since NamedTuples are immutable and we do not want to break the ergonomic “configure then load” pattern.
Examples
- class gunz_cm.structs.LoaderConfig(*, fpath: Path, bin_size_bp: Optional[int] = None, region1: Optional[str] = None, region2: Optional[str] = None, balancing: Optional[Union[Balancing, List[Balancing]]] = None, output_format: DataStructure = DataStructure.DF, fformat: Optional[Format] = None, backend: Optional[Backend] = None, return_raw_counts: bool = False, chunksize: Optional[int] = None)[source]#
Bases:
BaseModelCanonical loader configuration consumed by every format-specific loader.
Frozen, immutable, and validated at construction. The fields mirror the union of all keyword arguments accepted by
_load_cooler_data,_load_hic_data,_load_csv_data,_load_memmap_data, and_load_gzcm_data.- fpath#
Path to the contact-matrix file. Required.
- Type:
- bin_size_bp#
Bin size in base pairs. Uses
BinSizeBP(positive int).Noneis allowed because some loaders (CSV, GZCM, PICKLE) do not require an explicit bin size — the value is inferred from the file header.- Type:
Optional[int]
- region1, region2
Genomic regions to load.
region2=Nonemeans “intra-chromosomal of region1”. Both default toNoneso format-specific loaders that don’t support regions (NPY, PICKLE) can still construct a validLoaderConfig. Accepts chromosome names (“chr1”), region ranges (“chr1:1-10000”), or the whole-chromosome alias (“ALL”). The strictChromNameregex from_typesis intentionally not used here because loaders accept a broader range of region formats.
- balancing#
Balancing (normalization) method(s).
Nonemeans “no balancing”; some formats also accept a list of methods to return multiple normalised columns in one call.- Type:
Optional[Union[gunz_cm.consts.Balancing, List[gunz_cm.consts.Balancing]]]
- output_format#
In-memory representation of the loaded data. Defaults to
DataStructure.DF(DataFrame).
- fformat#
Explicit file format.
Nonetriggers extension-based inference.- Type:
Optional[gunz_cm.consts.Format]
- backend#
Loader backend.
Noneselects the format’s default backend. This is the resolved representation — the legacyuse_fast_hicparameter is translated tobackend=Backend.STRAWupstream.- Type:
Optional[gunz_cm.consts.Backend]
- return_raw_counts#
If True, the loader returns raw counts alongside balanced counts. Not supported by every format; loaders that don’t support it raise
NotImplementedErrorat runtime.- Type:
- chunksize#
Optional chunked-streaming parameter.
Nonemeans “load the full region in one go”. Used by COOLER and HIC loaders.- Type:
Optional[int]
Examples
>>> cfg = LoaderConfig( ... fpath=pathlib.Path("data.hic"), ... bin_size_bp=50_000, ... region1="chr1", ... backend=Backend.STRAW, ... ) >>> cfg.model_dump() {'fpath': PosixPath('data.hic'), 'bin_size_bp': 50000, ...}
- bin_size_bp: t.Optional[BinSizeBP]#
- fpath: pathlib.Path#
- model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True, 'extra': 'forbid', 'frozen': True}#
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- output_format: DataStructure#
- region1: t.Optional[RegionSpec]#
- region2: t.Optional[RegionSpec]#
- gunz_cm.structs.from_legacy_flags(*, overwrite: bool, exist_ok: bool) Literal['error', 'overwrite', 'skip'][source]#
Translate the legacy
(overwrite, exist_ok)pair to aConflictPolicy.This is the single point of conversion during the v2.24.0 deprecation window. It exists so that:
The four legal
(overwrite, exist_ok)combinations map to exactly one of the three named modes.The illegal
(True, True)combination produces a clearValueErrorrather than silently falling through to one of the other branches.
Mapping#
(False, False)→"error"(raise on conflict)(True, False)→"overwrite"(replace existing)(False, True)→"skip"(log + return)(True, True)→ValueError(ambiguous — prefer the newon_conflictparameter for clarity)
- param overwrite:
The legacy
overwriteflag.- param exist_ok:
The legacy
exist_okflag.- returns:
The corresponding named mode.
- rtype:
ConflictPolicy
- raises ValueError:
If both flags are
True— the combination is ambiguous.
Examples
>>> from_legacy_flags(overwrite=False, exist_ok=False) 'error' >>> from_legacy_flags(overwrite=True, exist_ok=False) 'overwrite' >>> from_legacy_flags(overwrite=False, exist_ok=True) 'skip'
- gunz_cm.structs.materialize(view: LazyMatrixView) Any[source]#
Materialize a
LazyMatrixViewby invoking its loader.This is the canonical way to convert a lazy view into concrete data. Free function (not a method on
LazyMatrixView) so the caller can substitute their own materialization strategy.- Parameters:
view (LazyMatrixView) – The lazy view to materialize.
- Returns:
Whatever
view.loader(**view.kwargs)returns.- Return type:
t.Any
Examples
>>> def fake(**kw): return kw >>> v = LazyMatrixView(loader=fake, kwargs={"x": 1}) >>> materialize(v) == {"x": 1} True