File size: 5,318 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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
"""k-mer (Markov) baselines: bits per base of order-0..7 models fitted on train, scored out of sample.

  python og2baseline.py [--root .] [--fit train] [--eval heldout valid] [--alpha 0.5] [--workers 8]

Fit: the train split's 8-mer counts (stats/train_kmer8.npz from og2stats.py; case folded, k-mers with N or crossing a
window boundary excluded) give, for each order k, P(b | previous k bases) = (c(ctx, b) + alpha) / (c(ctx) + 4 alpha).
Score: on each evaluation split, every position i of every window whose target and 7 previous bases are A/C/G/T (the
same positions for every order, so orders are comparable; these are exactly the targets kept by the loss mask, minus
the first 7 of each window). Reports bits/base overall and per subset, plus the best order, and the in-sample value on
train for reference (lower than out of sample: the model has seen those counts).
Writes stats/baseline.json. A trained model's masked bits/base on heldout should be compared with the best order.
"""

from __future__ import annotations

import argparse
import json
from collections import defaultdict
from concurrent.futures import ProcessPoolExecutor
from pathlib import Path

import numpy as np

K = 8
ORDERS = list(range(K))


def tables(k8: np.ndarray, alpha: float) -> dict[int, np.ndarray]:
    """log2 P(b | ctx) for each order: [4**k, 4] arrays."""
    t = k8.reshape([4] * K).astype(np.float64)
    out = {}
    for k in ORDERS:
        c = t.sum(axis=tuple(range(k + 1, K))) if k + 1 < K else t  # (k+1)-mer counts
        c = c.reshape(4**k, 4)
        out[k] = np.log2((c + alpha) / (c.sum(1, keepdims=True) + 4 * alpha))
    return out


_T: dict[int, np.ndarray] = {}


def _init(tabs: dict[int, np.ndarray]) -> None:
    _T.update(tabs)


def score_shard(npy: str, ids: list[int] | None) -> dict:
    """Summed -log2 P per order and position count for one shard."""
    base = Path(npy).with_suffix("")
    arr = np.load(npy, mmap_mode="r")
    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]
    bits = np.zeros(K)
    n = 0
    for r in rows:
        b = (np.asarray(arr[r["offset"]: r["offset"] + r["len"]]) & 7).astype(np.int64)
        L = len(b)
        if L <= K - 1:
            continue
        bad = np.concatenate([[0], np.cumsum(b >= 4)])
        pos = np.arange(K - 1, L)  # target positions with 7 previous bases
        ok = (bad[pos + 1] - bad[pos - (K - 1)]) == 0  # context + target all A/C/G/T
        pos = pos[ok]
        if len(pos) == 0:
            continue
        tgt = b[pos]
        ctx = np.zeros(len(pos), dtype=np.int64)
        for k in ORDERS:  # ctx = code of the k bases before the target (grows one base per order)
            if k > 0:
                ctx = ctx + b[pos - k] * 4 ** (k - 1)
            bits[k] -= _T[k][ctx, tgt].sum()
        n += len(pos)
    return {"subset": base.parent.name, "bits": bits.tolist(), "n": n}


def evaluate(root: Path, split: str, tabs: dict, workers: int) -> dict:
    sel_path = root / split / "selected.json"
    sel = json.loads(sel_path.read_text())["shards"] if sel_path.exists() else None
    jobs = [(str(p), None if sel is None else sel.get(str(p.with_suffix("").relative_to(root)), []))
            for p in sorted((root / split).glob("*/*.npy"))]
    agg: dict[str, list] = defaultdict(lambda: [np.zeros(K), 0])
    with ProcessPoolExecutor(workers, initializer=_init, initargs=(tabs,)) as ex:
        for res in ex.map(score_shard, *zip(*jobs), chunksize=4):
            g = agg[res["subset"]]
            g[0] += np.array(res["bits"])
            g[1] += res["n"]
    tot_bits = sum((g[0] for g in agg.values()), np.zeros(K))
    tot_n = sum(g[1] for g in agg.values())

    def row(bits, n):
        bpb = {str(k): round(float(bits[k] / max(n, 1)), 5) for k in ORDERS}
        best = min(ORDERS, key=lambda k: bpb[str(k)])
        return {"positions": int(n), "bits_per_base": bpb, "best_order": best, "best": bpb[str(best)]}

    return {"overall": row(tot_bits, tot_n),
            "subsets": {k: row(g[0], g[1]) for k, g in sorted(agg.items(), key=lambda kv: -kv[1][1])}}


def main(argv: list[str] | None = None) -> None:
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("--root", type=Path, default=Path("."))
    ap.add_argument("--fit", default="train")
    ap.add_argument("--eval", nargs="+", default=["heldout", "valid", "train"])
    ap.add_argument("--alpha", type=float, default=0.5)
    ap.add_argument("--workers", type=int, default=8)
    a = ap.parse_args(argv)
    k8 = np.load(a.root / "stats" / f"{a.fit}_kmer8.npz")["overall"]
    tabs = tables(k8, a.alpha)
    out = {"fit": a.fit, "alpha": a.alpha, "orders": ORDERS, "splits": {}}
    for split in a.eval:
        if (a.root / split).exists():
            out["splits"][split] = r = evaluate(a.root, split, tabs, a.workers)
            o = r["overall"]
            print(f"{split}: " + " ".join(f"k{k}={v:.4f}" for k, v in o["bits_per_base"].items())
                  + f"  best k{o['best_order']} {o['best']:.4f} ({o['positions']:,} positions)")
    (a.root / "stats" / "baseline.json").write_text(json.dumps(out, indent=1))


if __name__ == "__main__":
    main()