Datasets:
Remove CASP14 bug reproduction and old-file comparison; analysis scripts read TAPE's download directly
7bf35b0 verified Download scripts/validate_ssp.py from hazemessam/SSP: direct link, hf CLI and curl.
- Browser
- Download file 8.57 kB
-
https://huggingface.co/datasets/hazemessam/SSP/resolve/main/scripts/validate_ssp.py
- Command line
-
hf download hf://datasets/hazemessam/SSP/scripts/validate_ssp.py
-
curl -L -o validate_ssp.py https://huggingface.co/datasets/hazemessam/SSP/resolve/main/scripts/validate_ssp.py
8.57 kB
| """Check a built SSP (output of build_ssp.py). Read-only; prints a report and exits non-zero on any failure. | |
| usage: python -I scripts/validate_ssp.py [build/ssp] | |
| Checks | |
| 1. every file has exactly the shared schema (same column names and types) | |
| 2. per row: every per-residue column as long as the sequence; label alphabets (H E C / G H I B E S T C / + P); | |
| ss3 = TAPE's 8->3 reduction of ss8; ss8 = ss8_pp with P replaced by C, T or S; resolved = 0 -> labelled C; | |
| rcsb/casp: resolved = 1 -> backbone N, CA, C, O present | |
| 3. rcsb/casp: no duplicate sequences within a file (tape: duplicates reported, kept as TAPE has them) | |
| 4. tape: identical to TAPE's files (same rows in the same order; every field equal; only ints -> letters) | |
| 5. rcsb CASP12: TAPE's 21 chains present (in_tape) and labels agree with TAPE (>= 99.9% on resolved residues) | |
| 6. coverage: every CASP-listed target is in an rcsb row or logged as dropped (with a reason) | |
| 7. summary: rows per file, dropped targets by reason, polyproline handling | |
| Results are saved to {out}/logs/validation.json. | |
| """ | |
| import os, sys, json, glob, collections | |
| sys.path.insert(0, "scripts") | |
| import pyarrow.parquet as pq | |
| import ssp_lib as L | |
| OUT = sys.argv[1] if len(sys.argv) > 1 else "build/ssp" | |
| TAPE_DIR = "data/original/tape/secondary_structure/secondary_structure" | |
| TAPE_FILES = {"train": "secondary_structure_train.json", "validation": "secondary_structure_valid.json", | |
| "cb513": "secondary_structure_cb513.json", "ts115": "secondary_structure_ts115.json", | |
| "casp12": "secondary_structure_casp12.json"} | |
| PER_RESIDUE = ["ss3", "ss8", "ss8_pp", "resolved", "valid_mask", "rsa", "asa_max", "phi", "psi", "interface", | |
| "evolutionary", "n_xyz", "ca_xyz", "c_xyz", "o_xyz", "cb_xyz"] | |
| fail, results = [], {"checks": []} | |
| def check(ok, msg): | |
| print((" ok " if ok else " FAIL ") + msg, flush=True) | |
| results["checks"].append({"ok": bool(ok), "check": msg}) | |
| if not ok: | |
| fail.append(msg) | |
| def rows_of(name, batch=200): | |
| for b in pq.ParquetFile(f"{OUT}/{name}").iter_batches(batch_size=batch): | |
| yield from b.to_pylist() | |
| files = sorted(os.path.relpath(f, OUT) for f in glob.glob(f"{OUT}/*/*.parquet")) | |
| meta = {k: pq.ParquetFile(f"{OUT}/{k}") for k in files} | |
| print(f"== {len(files)} files in {OUT}: {files}") | |
| # 1. schema | |
| first = next(iter(meta.values())).schema_arrow | |
| check(all(m.schema_arrow.equals(first) for m in meta.values()), "all files share one schema (names and types)") | |
| # 2-3. per-row consistency and duplicates | |
| S3OF = L.SS8_TO_SS3 | |
| for name in files: | |
| bad, seqs, ids, n = collections.Counter(), collections.Counter(), collections.Counter(), 0 | |
| for r in rows_of(name): | |
| n += 1 | |
| L_ = len(r["sequence"]) | |
| seqs[r["sequence"]] += 1; ids[r["id"]] += 1 | |
| bad["length"] += any(r[c] is not None and len(r[c]) != L_ for c in PER_RESIDUE) | |
| bad["no_resolved"] += r["resolved"] is None | |
| bad["alphabet"] += not (set(r["ss3"]) <= set("HEC") and set(r["ss8"]) <= set("GHIBESTC") | |
| and (r["ss8_pp"] is None or set(r["ss8_pp"]) <= set("GHIBESTCP"))) | |
| bad["ss3_from_ss8"] += any(S3OF[a] != b for a, b in zip(r["ss8"], r["ss3"]) if a in S3OF) | |
| if r["ss8_pp"] is not None: | |
| bad["ss8_from_ss8_pp"] += any(p != c and not (p == "P" and c in "CTS") for p, c in zip(r["ss8_pp"], r["ss8"])) | |
| if r["resolved"] is not None: | |
| bad["unresolved_not_C"] += any(m == 0 and (s != "C" or (r["ss8_pp"] or "C" * L_)[k] != "C") | |
| for k, (m, s) in enumerate(zip(r["resolved"], r["ss8"]))) | |
| if r["ca_xyz"] is not None: # rcsb / casp: DSSP labels only residues with a complete backbone | |
| bad["resolved_without_backbone"] += sum( | |
| 1 for k, m in enumerate(r["resolved"]) | |
| if m == 1 and any(r[f"{a}_xyz"][k] is None for a in ("n", "ca", "c", "o"))) | |
| dup = sum(v - 1 for v in seqs.values()) | |
| if name.startswith("tape/"): | |
| check(not any(bad.values()), f"{name}: {n} rows, consistent ({dict(+bad) or 'no problems'}); " | |
| f"kept as in TAPE: {dup} repeated sequences, {sum(v - 1 for v in ids.values())} repeated ids") | |
| else: | |
| check(not any(bad.values()) and dup == 0, | |
| f"{name}: {n} rows, consistent ({dict(+bad) or 'no problems'}), duplicate sequences: {dup}") | |
| # 4. tape == TAPE, field by field, in TAPE's order | |
| for split, fn in TAPE_FILES.items(): | |
| name = f"tape/{split}.parquet" | |
| if name not in meta: | |
| continue | |
| src = json.load(open(f"{TAPE_DIR}/{fn}")) | |
| diff, k = collections.Counter(), -1 | |
| for k, r in enumerate(rows_of(name)): | |
| s = src[k] | |
| diff["id"] += r["id"] != s["id"] | |
| diff["sequence"] += r["sequence"] != s["primary"] | |
| diff["ss8"] += r["ss8"] != "".join("GHIBESTC"[c] for c in s["ss8"]) | |
| diff["ss3"] += r["ss3"] != "".join("HEC"[c] for c in s["ss3"]) | |
| diff["resolved=disorder"] += r["resolved"] != s["disorder"] | |
| for f in ("valid_mask", "rsa", "asa_max", "phi", "psi", "interface", "evolutionary"): | |
| diff[f] += r[f] != s[f] | |
| src[k] = None | |
| diff["row_count"] += k + 1 != len(src) | |
| del src | |
| check(not any(diff.values()), f"{name}: identical to TAPE's {fn} ({k + 1} rows; differences: {dict(+diff) or 'none'})") | |
| # 5. rcsb CASP12 vs TAPE | |
| if "rcsb/casp12.parquet" in meta: | |
| tape_src = {r["id"]: r for r in json.load(open(f"{TAPE_DIR}/{TAPE_FILES['casp12']}"))} | |
| rr = {r["id"]: r for r in rows_of("rcsb/casp12.parquet")} | |
| in_tape = {i for i, r in rr.items() if r["in_tape"]} | |
| check(in_tape == set(tape_src), f"rcsb/casp12: TAPE's 21 chains present and flagged in_tape ({len(in_tape)})") | |
| from compare_ss_tools_helpers import project | |
| n = same = 0 | |
| flag = collections.Counter() # TAPE's disorder flag vs whether the residue has structure in today's PDB entry | |
| for i in in_tape: | |
| s = tape_src[i] | |
| lab, _ = project(s["primary"], rr[i]["sequence"], list(zip(rr[i]["ss8"], rr[i]["resolved"]))) | |
| for k, d in enumerate(s["disorder"]): | |
| flag[f"tape_disorder_{d}__pdb_" + ("not_aligned" if lab[k] is None else f"resolved_{lab[k][1]}")] += 1 | |
| if d == 1 and lab[k] is not None and lab[k][1] == 1: | |
| n += 1; same += lab[k][0] == "GHIBESTC"[s["ss8"][k]] | |
| results["rcsb_casp12_vs_tape"] = {"residues": n, "agree": same, "disorder_flag_vs_pdb": dict(flag)} | |
| print(" TAPE disorder flag vs structure in today's PDB entry:", dict(flag)) | |
| check(n > 0 and same / n >= 0.999, f"rcsb/casp12: labels agree with TAPE on {100 * same / max(n, 1):.2f}% of {n:,} residues resolved in both") | |
| # 6. coverage of CASP-listed targets by rcsb rows | |
| for f in sorted(glob.glob(f"{OUT}/logs/rcsb_casp*.json")): | |
| log = json.load(open(f)) | |
| split = log["split"] | |
| if f"rcsb/{split}.parquet" not in meta: | |
| continue | |
| listed = {t for t, c in L.listed_targets(f"data/original/{split}").items() if c} | |
| covered = {t for r in rows_of(f"rcsb/{split}.parquet") for t in r["casp_targets"]} | |
| dropped_ids = {d["id"] for d in log["dropped"]} | |
| deduped_targets = set() # targets whose whole row was dropped as a duplicate | |
| for d in log["dropped"]: | |
| if "-" in d["id"]: | |
| deduped_targets |= {t for t, v in log["targets"].items() if f"{v['pdb']}-{v['chain']}" == d["id"]} | |
| missing = listed - covered - dropped_ids - deduped_targets | |
| check(not missing, f"rcsb/{split}: all {len(listed)} CASP-listed targets covered or logged ({len(covered)} in rows)" | |
| + (f"; unaccounted: {sorted(missing)}" if missing else "")) | |
| # 7. summary | |
| print("\n== summary") | |
| for f in sorted(glob.glob(f"{OUT}/logs/*_*.json")): | |
| log = json.load(open(f)) | |
| if "split" not in log: | |
| continue | |
| key = f"{log['source']}/{log['split']}.parquet" | |
| if log.get("source") is None: | |
| continue | |
| reasons = collections.Counter(d["reason"].split(" as ")[0] if d["reason"].startswith("same sequence") else d["reason"] for d in log["dropped"]) | |
| print(f" {key:26s} rows {meta[key].metadata.num_rows if key in meta else '-':>5} | dropped {len(log['dropped'])}: {dict(reasons)} | polyproline {log.get('polyproline') or '-'}") | |
| print(f"\n{'ALL CHECKS PASSED' if not fail else f'{len(fail)} CHECK(S) FAILED'}") | |
| import datetime | |
| results.update(passed=not fail, date=datetime.date.today().isoformat()) | |
| json.dump(results, open(f"{OUT}/logs/validation.json", "w"), indent=1) | |
| sys.exit(1 if fail else 0) | |