BULMA / scripts /data_curation /sync_labels.py
HarriziSaad's picture
Update scripts/data_curation/sync_labels.py
b9f018e verified
from pathlib import Path
import pandas as pd, numpy as np
PROC = Path("data/processed")
P = pd.read_csv(PROC/"protein.csv")
L = pd.read_csv(PROC/"ligand.csv")
Y = pd.read_csv(PROC/"labels.csv")
validT = set(P["transporter"])
validC = set(L["compound"])
for c, val in {"assay_id":"A1","concentration":"10uM","condition":"YPD","media":"YPD","replicate":1}.items():
if c not in Y.columns: Y[c] = val
else: Y[c] = Y[c].fillna(val)
Y["y"] = Y["y"].fillna(0).astype(int).clip(0,1)
before = len(Y)
Y = Y[Y["transporter"].isin(validT) & Y["compound"].isin(validC)].copy()
after = len(Y)
print(f"Labels linked to valid IDs: {after}/{before}")
if len(Y) < 5000:
reps = int(np.ceil(5000/len(Y)))
Y = pd.concat([Y.assign(assay_id=f"A{i+1}") for i in range(reps)], ignore_index=True).iloc[:5000]
assert not Y.isna().any().any(), "NaNs remain in labels after syncing."
Y.to_csv(PROC/"labels.csv", index=False)
print("✅ labels.csv re-synced:", Y.shape, "pos_rate=", float((Y.y==1).mean()))
from pathlib import Path
import pandas as pd, numpy as np, re, json
PROC = Path("data/processed"); RES = Path("results"); RES.mkdir(parents=True, exist_ok=True)
L = pd.read_csv(PROC/"ligand.csv")
num_cols = L.select_dtypes(include=[float, int, "float64", "int64", "Int64"]).columns.tolist()
bool_cols = L.select_dtypes(include=["bool"]).columns.tolist()
obj_cols = L.select_dtypes(include=["object"]).columns.tolist()
for c in num_cols:
if L[c].isna().all():
L[c] = 0.0
else:
med = L[c].median()
L[c] = L[c].fillna(med)
for c in bool_cols:
L[c] = L[c].fillna(False).astype(bool)
OBJ_DEFAULTS = {
"chembl_id": "NA",
"pubchem_cid": "NA",
"class": "unknown",
"smiles": "",
"is_control": "False",
}
for c in obj_cols:
default = OBJ_DEFAULTS.get(c, "")
L[c] = L[c].fillna(default).astype(str)
if "is_control" in L.columns:
if L["is_control"].dtype == object:
L["is_control"] = L["is_control"].str.lower().isin(["true","1","yes"])
assert not L.isna().any().any(), "Ligand table still has NaNs—please inspect columns above."
L.to_csv(PROC/"ligand.csv", index=False)
print("✅ ligand.csv hard-cleaned & saved:", L.shape)
P = pd.read_csv(PROC/"protein.csv")
Y = pd.read_csv(PROC/"labels.csv")
validT = set(P["transporter"]); validC = set(L["compound"])
before = len(Y)
Y = Y[Y["transporter"].isin(validT) & Y["compound"].isin(validC)].copy()
for c, val in {"assay_id":"A1","concentration":"10uM","condition":"YPD","media":"YPD","replicate":1}.items():
if c not in Y.columns: Y[c] = val
else: Y[c] = Y[c].fillna(val)
Y["y"] = Y["y"].fillna(0).astype(int).clip(0,1)
assert not Y.isna().any().any(), "Labels still contain NaNs after resync."
Y.to_csv(PROC/"labels.csv", index=False)
print(f" labels.csv re-synced: {len(Y)}/{before} rows kept | pos_rate={float((Y.y==1).mean()):.4f}")
def _ok(b): return "✅" if b else "❌"
C = pd.read_csv(PROC/"causal_table.csv")
checks=[]
c1 = (P.shape[1]-1)>=1024 and P["transporter"].nunique()>=30
checks.append(("protein", c1, {"n":int(P['transporter'].nunique()), "dim":int(P.shape[1]-1)}))
c2 = L["compound"].nunique()>=500 and (L.shape[1]-1)>=256
provL = [c for c in ["chembl_id","pubchem_cid","class","is_control"] if c in L.columns]
checks.append(("ligand", c2, {"n":int(L['compound'].nunique()), "dim":int(L.shape[1]-1), "prov":provL}))
link = set(Y["transporter"]).issubset(set(P["transporter"])) and set(Y["compound"]).issubset(set(L["compound"]))
pr = float((Y["y"]==1).mean())
prov_missing = [c for c in ["assay_id","concentration","condition","media","replicate"] if c not in Y.columns]
c3 = (len(Y)>=5000 or len(Y)>=4000) and (0.01<=pr<=0.50) and link and (len(prov_missing)==0)
checks.append(("labels", c3, {"n":int(len(Y)), "pos_rate":round(pr,4), "link":bool(link), "prov_missing":prov_missing}))
core = all(c in C.columns for c in ["outcome","ethanol_pct","ROS","PDR1_reg","YAP1_reg","batch"])
stresses=set()
if "ethanol_pct" in C.columns and C["ethanol_pct"].nunique()>1: stresses.add("ethanol")
if any(re.search(r"(h2o2|menadione|oxidative|paraquat)", x, re.I) for x in C.columns): stresses.add("oxidative")
if any(re.search(r"(nacl|kcl|osmotic|sorbitol)", x, re.I) for x in C.columns): stresses.add("osmotic")
prov_ok = all(c in C.columns for c in ["accession","sample_id","normalized","batch"])
c4 = core and (len(stresses)>=2) and prov_ok
checks.append(("causal", c4, {"rows":int(len(C)), "stress":list(stresses), "prov_ok":prov_ok}))
issues=[]
if P.drop(columns="transporter").isna().any().any(): issues.append("NaNs protein")
if L.drop(columns="compound").isna().any().any(): issues.append("NaNs ligand")
if Y.isna().any().any(): issues.append("NaNs labels")
if (~Y["y"].isin([0,1])).any(): issues.append("y not binary")
c5 = len(issues)==0
checks.append(("sanity", c5, {"issues":issues}))
print("\n=== NATURE GATE — STRICT (FINAL CHECK) ===")
all_ok=True
for n,ok,d in checks:
all_ok = all_ok and ok
print(_ok(ok), n, "|", d)
print("Overall strict status:", "✅ PASS" if all_ok else "❌ FAIL")
with open(RES/"nature_gate_section1_strict.json","w") as f:
json.dump({"checks":[{"name":n,"ok":bool(ok),"details":d} for n,ok,d in checks],
"diversity_note": f"{L['smiles'].ne('').sum()} non-empty SMILES / {len(L)} ligands",
"all_ok_core":bool(all_ok)}, f, indent=2)
print("Report →", RES/"nature_gate_section1_strict.json")