Datasets:
Download scripts/og2stats.py from AutomatedScientist/og2_small: direct link, hf CLI and curl.
- Browser
- Download file 7.21 kB
-
https://huggingface.co/datasets/AutomatedScientist/og2_small/resolve/main/scripts/og2stats.py
- Command line
-
hf download hf://datasets/AutomatedScientist/og2_small/scripts/og2stats.py
-
curl -L -o og2stats.py https://huggingface.co/datasets/AutomatedScientist/og2_small/resolve/main/scripts/og2stats.py
7.21 kB
| """Gross statistics of the subset: base frequencies, GC, soft-masking, CpG, k-mer spectra, Markov entropies. | |
| python og2stats.py [--root .] [--splits train heldout valid] [--workers 8] | |
| For every split, per subset (directory), per domain (D__ of the window's tag; '(untagged)' otherwise) and overall: | |
| tokens, windows; counts of A, C, G, T, N; GC fraction (of ACGT); soft-masked (lowercase) fraction; | |
| CpG observed/expected = f(CG) / (f(C) f(G)) from dinucleotides. | |
| Overall and per subset, from 8-mer counts (case folded; k-mers containing N or crossing a window boundary skipped): | |
| k-mer counts for k = 1..8 (by marginalising the 8-mer counts over trailing positions), the entropy H_k of each | |
| k-mer distribution and the Markov conditional entropies h_k = H_{k+1} - H_k (bits per base given the previous k | |
| bases: the in-sample bits/base of an order-k model), distinct 8-mers, the 20 most frequent 8-mers, and | |
| Chargaff's second rule (mean |f(w) - f(revcomp w)| / (f(w) + f(revcomp w)) over 4-mers). | |
| Windows are those listed in <split>/selected.json when present (`og2subset.py finalize`), else all. | |
| Writes <root>/stats/<split>.json and <root>/stats/<split>_kmer8.npz (8-mer counts, overall and per subset). | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import json | |
| import math | |
| import re | |
| from collections import defaultdict | |
| from concurrent.futures import ProcessPoolExecutor | |
| from pathlib import Path | |
| import numpy as np | |
| K = 8 | |
| BASES = "ACGT" | |
| def taxon(tag: str, rank: str) -> str: | |
| m = re.search(rf"{rank}__([^;|]*)", tag) | |
| return m.group(1) if m else "(untagged)" | |
| def shard_stats(npy: str, ids: list[int] | None) -> dict: | |
| """Counts for one shard: per domain base/lower/CpG counts and the shard's 8-mer counts.""" | |
| base = Path(npy).with_suffix("") | |
| arr = np.load(npy) | |
| rows = [json.loads(line) for line in base.with_suffix(".jsonl").read_text().splitlines()] | |
| if ids is not None: | |
| rows = [rows[i] for i in ids] | |
| kmer = np.zeros(4**K, dtype=np.int64) | |
| dom: dict[str, np.ndarray] = defaultdict(lambda: np.zeros(8, dtype=np.int64)) # A C G T N lower CG windows | |
| for r in rows: | |
| w = arr[r["offset"]: r["offset"] + r["len"]] | |
| b = (w & 7).astype(np.int64) | |
| d = dom[taxon(r["tag"], "D")] | |
| d[:5] += np.bincount(b, minlength=5)[:5] | |
| d[5] += int(np.count_nonzero(w & 0x80)) | |
| if len(b) > 1: | |
| d[6] += int(np.count_nonzero((b[:-1] == 1) & (b[1:] == 2))) | |
| d[7] += 1 | |
| n = len(b) - K + 1 | |
| if n <= 0: | |
| continue | |
| bad = np.concatenate([[0], np.cumsum(b >= 4)]) | |
| ok = (bad[K:] - bad[:-K]) == 0 # no N in positions i..i+K-1 | |
| idx = np.zeros(n, dtype=np.int64) | |
| for j in range(K): | |
| idx = idx * 4 + np.minimum(b[j:j + n], 3) | |
| kmer += np.bincount(idx[ok], minlength=4**K) | |
| return {"subset": base.parent.name, "domains": {k: v.tolist() for k, v in dom.items()}, "kmer": kmer} | |
| def entropy(counts: np.ndarray) -> float: | |
| p = counts[counts > 0] / counts.sum() | |
| return float(-(p * np.log2(p)).sum()) | |
| def kmer_summary(k8: np.ndarray) -> dict: | |
| if k8.sum() == 0: | |
| return {} | |
| t = k8.reshape([4] * K) | |
| H = {} | |
| for k in range(1, K + 1): | |
| ck = t.sum(axis=tuple(range(k, K))) if k < K else t | |
| H[k] = entropy(ck.ravel()) | |
| h = {0: H[1], **{k: H[k + 1] - H[k] for k in range(1, K)}} | |
| c4 = t.sum(axis=tuple(range(4, K))).ravel().astype(float) | |
| rc = np.array([int("".join(str(3 - int(c)) for c in np.base_repr(i, 4).zfill(4)[::-1]), 4) for i in range(256)]) | |
| ch2 = float(np.mean(np.abs(c4 - c4[rc]) / np.maximum(c4 + c4[rc], 1))) | |
| top = np.argsort(k8)[::-1][:20] | |
| word = lambda i: "".join(BASES[int(c)] for c in np.base_repr(int(i), 4).zfill(K)) | |
| return {"kmers_counted": int(k8.sum()), "distinct_8mers": int((k8 > 0).sum()), | |
| "entropy_bits": {str(k): round(v, 5) for k, v in H.items()}, | |
| "markov_bits_per_base": {str(k): round(v, 5) for k, v in h.items()}, | |
| "chargaff2_4mer_asymmetry": round(ch2, 5), | |
| "top_8mers": [[word(i), round(float(k8[i] / k8.sum()), 6)] for i in top]} | |
| def base_summary(c: np.ndarray) -> dict: | |
| a, cc, g, t, n, low, cg, win = (int(x) for x in c) | |
| acgt = a + cc + g + t | |
| tot = acgt + n | |
| fc, fg = cc / max(acgt, 1), g / max(acgt, 1) | |
| return {"tokens": tot, "windows": win, | |
| "freq": {"A": a / max(tot, 1), "C": cc / max(tot, 1), "G": g / max(tot, 1), "T": t / max(tot, 1), | |
| "N": n / max(tot, 1)}, | |
| "gc": (cc + g) / max(acgt, 1), "soft_masked": low / max(tot, 1), | |
| "cpg_obs_exp": (cg / max(acgt - win, 1)) / (fc * fg) if fc * fg > 0 else math.nan} | |
| def split_stats(root: Path, split: str, workers: int) -> dict: | |
| sel_path = root / split / "selected.json" | |
| sel = json.loads(sel_path.read_text())["shards"] if sel_path.exists() else None | |
| jobs = [] | |
| for npy in sorted((root / split).glob("*/*.npy")): | |
| key = str(npy.with_suffix("").relative_to(root)) | |
| jobs.append((str(npy), None if sel is None else sel.get(key, []))) | |
| sub_k: dict[str, np.ndarray] = defaultdict(lambda: np.zeros(4**K, dtype=np.int64)) | |
| sub_c: dict[str, np.ndarray] = defaultdict(lambda: np.zeros(8, dtype=np.int64)) | |
| dom_c: dict[str, np.ndarray] = defaultdict(lambda: np.zeros(8, dtype=np.int64)) | |
| with ProcessPoolExecutor(workers) as ex: | |
| for res in ex.map(shard_stats, *zip(*jobs), chunksize=4): | |
| sub_k[res["subset"]] += res["kmer"] | |
| for d, v in res["domains"].items(): | |
| sub_c[res["subset"]] += np.array(v) | |
| dom_c[d] += np.array(v) | |
| allk = sum(sub_k.values()) if sub_k else np.zeros(4**K, dtype=np.int64) | |
| allc = sum(sub_c.values()) if sub_c else np.zeros(8, dtype=np.int64) | |
| out_dir = root / "stats" | |
| out_dir.mkdir(exist_ok=True) | |
| np.savez_compressed(out_dir / f"{split}_kmer8.npz", overall=allk, **{f"subset_{k}": v for k, v in sub_k.items()}) | |
| st = {"split": split, "selected": sel is not None, "overall": {**base_summary(allc), **kmer_summary(allk)}, | |
| "subsets": {k: {**base_summary(sub_c[k]), **kmer_summary(sub_k[k])} | |
| for k in sorted(sub_c, key=lambda s: -sub_c[s][:5].sum())}, | |
| "domains": {k: base_summary(v) for k, v in sorted(dom_c.items(), key=lambda kv: -kv[1][:5].sum())}} | |
| (out_dir / f"{split}.json").write_text(json.dumps(st, indent=1)) | |
| o = st["overall"] | |
| print(f"{split}: {o['tokens'] / 1e9:.3f}B tokens, GC {o['gc']:.4f}, soft-masked {o['soft_masked']:.4f}, " | |
| f"CpG o/e {o['cpg_obs_exp']:.3f}, h_k " + " ".join(f"{v:.3f}" for v in o.get("markov_bits_per_base", {}).values())) | |
| return st | |
| def main() -> None: | |
| ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) | |
| ap.add_argument("--root", type=Path, default=Path(".")) | |
| ap.add_argument("--splits", nargs="+", default=["train", "heldout", "valid"]) | |
| ap.add_argument("--workers", type=int, default=8) | |
| a = ap.parse_args() | |
| for split in a.splits: | |
| if (a.root / split).exists(): | |
| split_stats(a.root, split, a.workers) | |
| if __name__ == "__main__": | |
| main() | |