File size: 4,581 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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
"""Cross-task descriptive overlap: identical sequences and identical parsed loci

reused between different task folders.



This is deliberately descriptive. Shared loci across different histone marks or

different label vocabularies are expected biology, not a split violation.

"""
from __future__ import annotations

import argparse
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, json_dump  # noqa: E402

MAX_EXAMPLES = 3


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", "cross_task")

    tasks = sorted(p.stem for p in (work / "prep").glob("*.parquet"))
    seq_groups: dict[str, list[tuple]] = defaultdict(list)
    loc_groups: dict[tuple, list[tuple]] = defaultdict(list)
    for task in tasks:
        df = pl.read_parquet(work / "prep" / f"{task}.parquet",
                             columns=["uid", "split", "name", "label", "canon_sha",
                                      "chrom", "start", "end"])
        for r in df.iter_rows(named=True):
            seq_groups[r["canon_sha"]].append(
                (task, r["split"], r["uid"], r["label"], r["name"]))
            if r["chrom"] is not None:
                loc_groups[(r["chrom"], r["start"], r["end"])].append(
                    (task, r["split"], r["uid"], r["label"], r["name"]))
    log.info("groups built", sequences=len(seq_groups), loci=len(loc_groups))

    rows = []
    for kind, groups in (("exact_sequence", seq_groups), ("exact_locus", loc_groups)):
        pair_counts = defaultdict(lambda: {"rows": 0, "test_a": 0, "test_both": 0,
                                           "examples": [], "labels": Counter()})
        for key, members in groups.items():
            task_counts = Counter(m[0] for m in members)
            if len(task_counts) < 2:
                continue
            by_task = defaultdict(list)
            for m in members:
                by_task[m[0]].append(m)
            for i, ta in enumerate(sorted(by_task)):
                for tb in sorted(by_task)[i + 1:]:
                    k = (ta, tb)
                    cell = pair_counts[k]
                    cell["rows"] += len(by_task[ta]) * len(by_task[tb])
                    cell["test_a"] += sum(1 for m in by_task[ta] if m[1] == "test") * len(by_task[tb])
                    cell["test_both"] += (sum(1 for m in by_task[ta] if m[1] == "test")
                                          * sum(1 for m in by_task[tb] if m[1] == "test"))
                    for m in by_task[ta][:1]:
                        for n in by_task[tb][:1]:
                            if len(cell["examples"]) < MAX_EXAMPLES:
                                cell["examples"].append(f"{m[2]}<->{n[2]}")
                            cell["labels"][f"{m[3]}~{n[3]}"] += 1
        for (ta, tb), cell in sorted(pair_counts.items()):
            rows.append({
                "kind": kind, "task_a": ta, "task_b": tb,
                "row_pairs": cell["rows"],
                "test_a_vs_any_b": cell["test_a"],
                "test_test_pairs": cell["test_both"],
                "distinct_label_combos": len(cell["labels"]),
                "representative_label_combos": ";".join(f"{k}:{v}" for k, v in cell["labels"].most_common(3)),
                "example_uids": ";".join(cell["examples"]),
            })
    df = pl.DataFrame(rows, schema={
        "kind": pl.String, "task_a": pl.String, "task_b": pl.String,
        "row_pairs": pl.Int64, "test_a_vs_any_b": pl.Int64, "test_test_pairs": pl.Int64,
        "distinct_label_combos": pl.Int64, "representative_label_combos": pl.String,
        "example_uids": pl.String})
    df.write_csv(pkg / "results" / "cross_task.csv")
    json_dump({"pairs": rows, "n_pairs": len(rows),
               "sequences_shared_across_tasks": sum(
                   1 for v in seq_groups.values() if len({m[0] for m in v}) > 1),
               "loci_shared_across_tasks": sum(
                   1 for v in loc_groups.values() if len({m[0] for m in v}) > 1)},
              work / "out" / "cross_task.json")
    log.done(pairs=len(rows))
    return 0


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