SSP / scripts /compare_casp12_archive.py
hazemessam's picture
Remove CASP14 bug reproduction and old-file comparison; analysis scripts read TAPE's download directly
7bf35b0 verified
Raw History Blame Contribute Delete
4.13 kB
"""How faithful is TAPE's CASP12 to CASP12? Counts, and mkdssp on CASP12's own target files vs TAPE's labels."""
import os, re, sys, glob, json, html
sys.path.insert(0, "scripts")
import numpy as np
import gemmi
import ss_assign as A
from Bio import Align
from Bio.Align import substitution_matrices
S8 = "GHIBESTC"
D = "data/original/casp12"
seqs, cur = {}, None
for line in open(f"{D}/casp12.seq.txt"):
line = line.strip()
if line.startswith(">"):
cur = line[1:].split()[0]; seqs[cur] = ""
elif cur:
seqs[cur] += line
# CASP12 target list: which targets were canceled
page = open(f"{D}/targetlist.html", errors="ignore").read()
canceled = set()
for row in re.split(r"<tr", page):
m = re.search(r">\s*(T\d{4}[A-Za-z0-9_]*)\s*<", row)
if m and "canceled" in html.unescape(re.sub(r"<[^>]+>", " ", row)).lower():
canceled.add(m.group(1))
files = {os.path.basename(p)[:-4]: p for p in glob.glob(f"{D}/x/**/*.pdb", recursive=True)}
tape = json.load(open("data/original/tape/secondary_structure/secondary_structure/secondary_structure_casp12.json"))
T_targets = [t for t in seqs if t.startswith("T")]
print("=== Counts")
print(f"CASP12 sequence file: {len(seqs)} entries ({len(T_targets)} 'T' targets), of which {len(canceled & set(T_targets))} canceled -> {len(set(T_targets) - canceled)} live")
print(f"CASP12 public structure archive (casp12.targets_T0): {len(files)} target files")
print(f"TAPE CASP12: {len(tape)} chains")
al = Align.PairwiseAligner(mode="local", substitution_matrix=substitution_matrices.load("BLOSUM62"),
open_gap_score=-11, extend_gap_score=-1)
def mapping(a, b):
"""Local alignment a->b; returns dict index_in_a -> index_in_b for aligned positions."""
aln = al.align(a, b)[0]
return {i: j for (i0, i1), (j0, j1) in zip(*aln.aligned) for i, j in zip(range(i0, i1), range(j0, j1))}
print("\n=== mkdssp on CASP12's own target files vs TAPE (residues resolved in both)")
tot = {"n": 0, "s8": 0, "s3": 0}
rows = []
for r in tape:
# which CASP12 target is this chain? best identical-residue count over the target
best = max(T_targets, key=lambda t: sum(r["primary"][i] == seqs[t][j] for i, j in mapping(r["primary"], seqs[t]).items()))
tseq = seqs[best]
m = mapping(r["primary"], tseq)
ident = sum(r["primary"][i] == tseq[j] for i, j in m.items())
if best not in files:
rows.append((r["id"], best, "no file in CASP12 archive", ""))
continue
lab, mism = A.casp_target_assign(files[best], tseq, "mkdssp")
n = s8 = s3 = 0
for i, j in m.items():
if r["disorder"][i] == 1 and lab[j] is not None:
l8 = "C" if lab[j] == "P" else lab[j]
n += 1; s8 += l8 == S8[r["ss8"][i]]; s3 += A.SS8_TO_SS3[l8] == "HEC"[r["ss3"][i]]
tot["n"] += n; tot["s8"] += s8; tot["s3"] += s3
# same coordinates as the PDB entry? compare CA positions of matched residues without superposition
pdb, ch = r["id"].split("-")
st = A.load(f"data/original/casp12_pdb/{pdb}.cif.gz")
seqres, residues = A.chain_info(st, ch)
m_pdb = mapping(seqres, tseq)
ca_pdb = {m_pdb[res.label_seq - 1]: res.find_atom("CA", "*").pos for res in residues
if res.label_seq - 1 in m_pdb and res.find_atom("CA", "*")}
cst = gemmi.read_structure(files[best])
ca_casp = {res.seqid.num - 1: res.find_atom("CA", "*").pos for res in cst[0][0] if res.find_atom("CA", "*")}
common = sorted(set(ca_pdb) & set(ca_casp))
dmax = max((ca_pdb[k].dist(ca_casp[k]) for k in common), default=float("nan"))
rows.append((r["id"], best, f"target {len(tseq)} aa, TAPE {len(r['primary'])} aa, {ident} identical aligned",
f"compared {n:4d}: ss8 {100 * s8 / max(n, 1):6.2f}% ss3 {100 * s3 / max(n, 1):6.2f}% | "
f"CA vs PDB entry: max shift {dmax:.2f} A over {len(common)} residues | file/sequence mismatches {len(mism)}"))
for row in rows:
print(f"{row[0]:8s} {row[1]:7s} {row[2]:48s} {row[3]}")
print(f"\nTOTAL over {tot['n']:,} residues: ss8 {100 * tot['s8'] / tot['n']:.2f}% ss3 {100 * tot['s3'] / tot['n']:.2f}%")