File size: 3,044 Bytes
44fc8dd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Within-split diagnostics: duplicate sequences and label conflicts inside a
single split, plus repeat / low-complexity warnings that make coincidental
k-mer matches likely."""
from __future__ import annotations

import argparse
import math
import sys
from collections import Counter, defaultdict
from pathlib import Path

import polars as pl

sys.path.insert(0, str(Path(__file__).resolve().parent))
from common import StageLog  # noqa: E402


def entropy(s: str) -> float:
    if not s:
        return 0.0
    c = Counter(s)
    n = len(s)
    return -sum((v / n) * math.log2(v / n) for v in c.values())


def max_run(s: str) -> int:
    best = cur = 1
    for i in range(1, len(s)):
        cur = cur + 1 if s[i] == s[i - 1] else 1
        best = max(best, cur)
    return best


def main() -> int:
    ap = argparse.ArgumentParser()
    ap.add_argument("--work", default="/workspace/nt-audit")
    ap.add_argument("--pkg", default="/workspace/nt-revised-audit")
    args = ap.parse_args()
    work, pkg = Path(args.work), Path(args.pkg)
    log = StageLog(pkg / "logs" / "stage.jsonl", "within_split")
    rows = []
    for path in sorted((work / "prep").glob("*.parquet")):
        task = path.stem
        df = pl.read_parquet(path, columns=["split", "uid", "canon", "canon_sha", "label"])
        for split in ("train", "test"):
            d = df.filter(pl.col("split") == split)
            n = d.height
            groups = defaultdict(list)
            for r in d.iter_rows(named=True):
                groups[r["canon_sha"]].append(r["label"])
            dup_seq = sum(len(v) - 1 for v in groups.values() if len(v) > 1)
            conflicting = sum(1 for v in groups.values() if len(v) > 1 and len(set(v)) > 1)
            sizes = sorted((len(v) for v in groups.values()), reverse=True)
            seqs = d["canon"].to_list()
            ents = [entropy(s) for s in seqs]
            runs = [max_run(s) for s in seqs]
            nfrac = [(s.count("N") / len(s)) if s else 0.0 for s in seqs]
            rows.append({
                "task": task, "split": split, "rows": n,
                "unique_sequences": len(groups),
                "duplicate_sequence_rows": dup_seq,
                "duplicate_groups": sum(1 for s in sizes if s > 1),
                "largest_duplicate_group": sizes[0] if sizes else 0,
                "groups_with_conflicting_labels": conflicting,
                "rows_low_entropy_lt_1.5": sum(1 for e in ents if e < 1.5),
                "rows_all_n": sum(1 for s in seqs if s and set(s) == {"N"}),
                "rows_n_fraction_gt_0.1": sum(1 for f in nfrac if f > 0.1),
                "mean_n_fraction": round(sum(nfrac) / n, 6) if n else None,
                "rows_homopolymer_run_ge_20": sum(1 for r in runs if r >= 20),
                "max_homopolymer_run": max(runs) if runs else None,
            })
    out = pl.DataFrame(rows)
    out.write_csv(pkg / "results" / "within_split.csv")
    log.done(rows=len(rows))
    return 0


if __name__ == "__main__":
    raise SystemExit(main())