File size: 3,782 Bytes
6f32cc3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
"""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()