File size: 2,404 Bytes
473c56f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python
"""classifier2: candidate/lesion tables for the DEV-TEST cohorts (same columns as dethead_table) + loaders for all pops.
  cls2_table.py build          -> classifier2/feat/test.pkl, test_lesions.pkl   (cohort column; LAB separate in eval)
"""
from __future__ import annotations
import json, sys
from pathlib import Path
import numpy as np
import pandas as pd

sys.path.insert(0, str(Path(__file__).resolve().parent))
import cls2_common as Q   # noqa: E402


def build():
    import dethead_table as T
    rows, lrows = [], []
    for p in sorted((Q.OUT / "cand" / "test").glob("*.npz")):
        d = json.loads(str(np.load(Q.guard(p))["json"]))
        for s, v in d["sources"].items():
            for i, (f, lb) in enumerate(zip(v["feats"], v["labels"]), start=1):
                r = {"key": d["key"], "pop": "test", "src": s, "cid": i, "fold": -1}
                r.update(f); r.update(lb); rows.append(r)
            for l in v["lesions"]:
                lrows.append({"key": d["key"], "pop": "test", "src": s, "fold": -1, "gid": l["gid"], "vox": l["vox"], "cands": l["cands"],
                              "c_t1": l["c_t1"], "dv_min": l["dv_min"], "douter_min": l["douter_min"], "pos_si": l["pos_si"]})
    df = pd.DataFrame(rows)
    df["pos10"] = (df["frac_cand"] >= 0.10).astype(int)
    df["amb"] = ((df["pos"] == 0) & (df["near"] == 0) & (df["c6_t1"] <= -0.5) & (df["dv_min"] > 3) & (df["douter_min"] > 2)).astype(int)
    df["sbin"] = [T.sbin(v) if p else "neg" for v, p in zip(df["les_vox"], df["pos"])]
    lf = pd.DataFrame(lrows)
    lf["sbin"] = [T.sbin(v) for v in lf["vox"]]
    lf["marked"] = lf["cands"].map(len) > 0
    for x in (df, lf):
        x["cohort"] = x["key"].str.split("_").str[0]
    od = Q.OUT / "feat"; od.mkdir(parents=True, exist_ok=True)
    df.to_pickle(Q.guard_write(od / "test.pkl")); lf.to_pickle(Q.guard_write(od / "test_lesions.pkl"))
    print("TABLE test", df["key"].nunique(), "keys", len(df), "cands", int(df["pos"].sum()), "pos", len(lf), "lesions")


def load(pop):
    """pop: test | contra | dev | t1fam (dethead tables)."""
    if pop == "test":
        d = Q.OUT / "feat"
        return pd.read_pickle(Q.guard(d / "test.pkl")), pd.read_pickle(Q.guard(d / "test_lesions.pkl"))
    d = Q.DH / "feat"
    return pd.read_pickle(d / f"{pop}.pkl"), pd.read_pickle(d / f"{pop}_lesions.pkl")


if __name__ == "__main__":
    build()