"""Does our label pipeline reproduce NetSurfP-2.0's TRAINING labels (TAPE's secondary_structure_train.json)? 1. sample 200 training chains (seed 0), download their current PDB entries from RCSB 2. mkdssp on each chain alone, polyproline (P) counted as coil, TAPE's 8->3 mapping 3. compare with the training labels on residues NetSurfP marks as resolved (disorder == 1) """ import os, sys, json, random, collections, urllib.request, urllib.error from concurrent.futures import ThreadPoolExecutor sys.path.insert(0, "scripts") import ijson import ss_assign as A from compare_ss_tools_helpers import project S8, S3 = "GHIBESTC", "HEC" TRAIN = "data/original/tape/secondary_structure/secondary_structure/secondary_structure_train.json" # TAPE's download, extracted PDB_DIR = "data/original/netsurfp_train_pdb" os.makedirs(PDB_DIR, exist_ok=True) N = 8678 pick = set(random.Random(0).sample(range(N), 200)) recs = [] with open(TRAIN, "rb") as f: for i, r in enumerate(ijson.items(f, "item", use_float=True)): if i in pick: recs.append({k: r[k] for k in ("id", "primary", "ss8", "ss3", "disorder", "valid_mask")}) print(f"sampled {len(recs)} training chains", flush=True) def fetch(pdb): path = f"{PDB_DIR}/{pdb}.cif.gz" if os.path.exists(path): return pdb, "ok" try: urllib.request.urlretrieve(f"https://files.rcsb.org/download/{pdb}.cif.gz", path) return pdb, "ok" except urllib.error.HTTPError as e: return pdb, f"HTTP {e.code}" with ThreadPoolExecutor(8) as ex: status = dict(ex.map(fetch, sorted({r["id"].split("-")[0] for r in recs}))) print("downloads:", collections.Counter(status.values()), flush=True) tot = collections.Counter() per = [] for r in recs: pdb, ch = r["id"].split("-", 1) if status[pdb] != "ok": per.append((r["id"], None, f"entry not downloadable ({status[pdb]})")); continue try: st = A.load(f"{PDB_DIR}/{pdb}.cif.gz") seqres, lab = A.mkdssp_assign(st, ch, "mkdssp", "chain") except Exception as e: per.append((r["id"], None, f"failed: {type(e).__name__}: {str(e)[:60]}")); continue lab, how = project(r["primary"], seqres, lab) c = collections.Counter() for i, d in enumerate(r["disorder"]): mine = lab[i] if d == 1 and mine is None: c["resolved_in_netsurfp_missing_now"] += 1 if d == 1 and mine is not None: l8 = "C" if mine == "P" else mine c["n"] += 1; c["s8"] += l8 == S8[r["ss8"][i]]; c["s3"] += A.SS8_TO_SS3[l8] == S3[r["ss3"][i]] tot.update(c) per.append((r["id"], c, how)) ok = [p for p in per if p[1] is not None and p[1]["n"] > 0] print(f"\nchains compared: {len(ok)} of {len(recs)}") print(f"OVERALL on {tot['n']:,} residues: ss8 {100 * tot['s8'] / tot['n']:.2f}% ss3 {100 * tot['s3'] / tot['n']:.2f}%" f" | residues resolved in NetSurfP but missing in today's entry: {tot['resolved_in_netsurfp_missing_now']}") bins = collections.Counter() for _, c, _ in ok: a8 = c["s8"] / c["n"] bins["100%" if a8 == 1 else ">=99%" if a8 >= .99 else ">=95%" if a8 >= .95 else "<95%"] += 1 print("chains by ss8 agreement:", dict(bins)) print("\nlowest-agreement chains:") for pid, c, how in sorted(ok, key=lambda p: p[1]["s8"] / p[1]["n"])[:10]: print(f" {pid:9s} ss8 {100 * c['s8'] / c['n']:6.2f}% on {c['n']} residues | sequence vs NetSurfP: {how}") for pid, c, why in per: if c is None: print(f" {pid:9s} {why}") json.dump({"ids": [r["id"] for r in recs], "total": tot}, open("reports/netsurfp_train_check.json", "w"), indent=1)