Datasets:
Download scripts/og2load.py from AutomatedScientist/og2_small: direct link, hf CLI and curl.
- Browser
- Download file 3.78 kB
-
https://huggingface.co/datasets/AutomatedScientist/og2_small/resolve/main/scripts/og2load.py
- Command line
-
hf download hf://datasets/AutomatedScientist/og2_small/scripts/og2load.py
-
curl -L -o og2load.py https://huggingface.co/datasets/AutomatedScientist/og2_small/resolve/main/scripts/og2load.py
3.78 kB
| """Read the subset: iterate windows (optionally by subset or taxon) or draw random training crops. | |
| python og2load.py [--root .] [--split train] [--subset ncbi_eukaryotic_genomes] [--taxon "S__HOMO SAPIENS"] [--n 3] | |
| Library use: | |
| from og2load import Windows | |
| ds = Windows(root, "train", taxon=r"P__CHORDATA") # memory-maps every shard's .npy | |
| for codes, meta in ds: # uint8 codes of one window + its index row and subset | |
| ... | |
| x = ds.random_crops(batch=8, length=4096, rng=np.random.default_rng(0)) # [8, 4096] uint8, length-weighted | |
| Codes: low 3 bits A=0 C=1 G=2 T=3 N=4, bit 7 (0x80) = lowercase (soft-masked repeat); `codes & 7` drops case. | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import json | |
| import re | |
| from collections.abc import Iterator | |
| from pathlib import Path | |
| import numpy as np | |
| class Windows: | |
| def __init__(self, root: Path | str, split: str, subset: str | None = None, taxon: str | None = None) -> None: | |
| root = Path(root) | |
| sel_path = root / split / "selected.json" | |
| sel = json.loads(sel_path.read_text())["shards"] if sel_path.exists() else None | |
| pat = re.compile(taxon) if taxon else None | |
| self.items: list[tuple[np.ndarray, dict]] = [] | |
| for npy in sorted((root / split).glob("*/*.npy")): | |
| sub = npy.parent.name | |
| if subset and sub != subset: | |
| continue | |
| key = str(npy.with_suffix("").relative_to(root)) | |
| rows = [json.loads(line) for line in npy.with_suffix(".jsonl").read_text().splitlines()] | |
| keep = range(len(rows)) if sel is None else sel.get(key, []) | |
| arr = np.load(npy, mmap_mode="r") | |
| for i in keep: | |
| r = rows[i] | |
| if pat is None or pat.search(r["tag"]): | |
| self.items.append((arr, {**r, "subset": sub, "shard": key})) | |
| self.lengths = np.array([m["len"] for _, m in self.items], dtype=np.int64) | |
| def __len__(self) -> int: | |
| return len(self.items) | |
| def __iter__(self) -> Iterator[tuple[np.ndarray, dict]]: | |
| for arr, m in self.items: | |
| yield np.asarray(arr[m["offset"]: m["offset"] + m["len"]]), m | |
| def random_crops(self, batch: int, length: int, rng: np.random.Generator) -> np.ndarray: | |
| """Crops of `length` bases from windows chosen with probability proportional to their usable length.""" | |
| usable = np.maximum(self.lengths - length + 1, 0) | |
| if usable.sum() == 0: | |
| raise ValueError(f"no window has {length} bases") | |
| idx = rng.choice(len(self.items), size=batch, p=usable / usable.sum()) | |
| out = np.empty((batch, length), dtype=np.uint8) | |
| for j, i in enumerate(idx): | |
| arr, m = self.items[i] | |
| s = m["offset"] + int(rng.integers(0, usable[i])) | |
| out[j] = arr[s: s + length] | |
| return out | |
| def main() -> None: | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("--root", default=".") | |
| ap.add_argument("--split", default="train") | |
| ap.add_argument("--subset", default=None) | |
| ap.add_argument("--taxon", default=None, help="regex on the window's taxonomy tag, e.g. 'S__HOMO SAPIENS'") | |
| ap.add_argument("--n", type=int, default=3) | |
| a = ap.parse_args() | |
| ds = Windows(a.root, a.split, a.subset, a.taxon) | |
| print(f"{len(ds)} windows, {int(ds.lengths.sum()):,} bases") | |
| up, low = np.frombuffer(b"ACGTN", dtype=np.uint8), np.frombuffer(b"acgtn", dtype=np.uint8) | |
| for k, (codes, m) in enumerate(ds): | |
| if k >= a.n: | |
| break | |
| s = np.where(codes & 0x80, low[codes & 7], up[codes & 7]).astype(np.uint8).tobytes().decode() | |
| print(f"{m['subset']} {m['len']} bp {m['tag'][:90]}\n {s[:100]}...") | |
| if __name__ == "__main__": | |
| main() | |