SSP / scripts /ssp_lib.py
hazemessam's picture
SSP: protein secondary structure (TAPE training data + CASP12-16 test sets, rcsb/casp/tape versions)
1c12c1a verified
Raw History Blame Contribute Delete
12.4 kB
"""Shared helpers for building SSP (secondary structure datasets), versions `rcsb` and `casp`."""
import os, re, glob, gzip, html, json, time, tempfile, subprocess, urllib.request
import gemmi
from Bio import Align
from Bio.Align import substitution_matrices
TMP = os.environ.get("SS_TMP", tempfile.gettempdir())
SS8_TO_SS3 = {"G": "H", "H": "H", "I": "H", "B": "E", "E": "E", "S": "C", "T": "C", "C": "C"}
ATOMS = ("N", "CA", "C", "O", "CB")
DSSP_VERSION = subprocess.run(["mkdssp", "--version"], capture_output=True, text=True).stdout.strip()
# ----------------------------------------------------------------------------------------------------- CASP pages
def listed_targets(casp_dir):
"""Live (not canceled) targets on CASP's target list -> sorted list of PDB codes CASP gives (may be empty)."""
page = open(f"{casp_dir}/targetlist.html", errors="ignore").read()
out = {}
for p in re.split(r'(?=<td[^>]*>\s*(?:<[^>]+>\s*)*T\d{4}[A-Za-z0-9_]*\s*<)', page)[1:]:
m = re.match(r'<td[^>]*>\s*(?:<[^>]+>\s*)*(T\d{4}[A-Za-z0-9_]*)\s*<', p)
if not m:
continue
row = p.split("</tr>")[0]
text = re.sub(r"\s+", " ", html.unescape(re.sub(r"<[^>]+>", " ", row)))
if "canceled" in text.lower():
continue
codes = set(x.lower() for x in re.findall(r"rcsb\.org/[^\"']*?([0-9][A-Za-z0-9]{3})\b", row))
codes |= set(x.lower() for x in re.findall(r"PDB code\s+([0-9][A-Za-z0-9]{3})\b", text))
out[m.group(1)] = sorted(codes)
return out
def _read_fasta(path, into):
cur = None
for line in open(path):
line = line.strip()
if line.startswith(">"):
cur = line[1:].split()[0]; into[cur] = ""
elif cur:
into[cur] += line
def target_sequences(rnd, casp_dir, needed):
"""CASP target sequences: the round's *.seq.txt files, then per-target pages (cached) for anything missing."""
seqs = {}
for f in sorted(glob.glob(f"{casp_dir}/*.seq.txt")):
if not f.endswith("target_pages.seq.txt"):
_read_fasta(f, seqs)
cache = f"{casp_dir}/target_pages.seq.txt"
if os.path.exists(cache):
_read_fasta(cache, seqs)
missing = [t for t in needed if t not in seqs]
if missing:
with open(cache, "a") as out:
for t in missing:
txt = urllib.request.urlopen(f"https://predictioncenter.org/casp{rnd}/target.cgi?target={t}&view=sequence",
timeout=60).read().decode(errors="ignore")
lines = [l.strip() for l in txt.splitlines() if l.strip()]
if lines and lines[0].startswith(">"):
seqs[t] = "".join(l for l in lines[1:] if not l.startswith(">"))
out.write(f">{t}\n{seqs[t]}\n")
time.sleep(0.2)
return seqs
# ----------------------------------------------------------------------------------------------------- matching
_al = Align.PairwiseAligner(mode="local", substitution_matrix=substitution_matrices.load("BLOSUM62"),
open_gap_score=-11, extend_gap_score=-1)
def pieces(t, p, minlen=8):
"""t as separate, non-overlapping exact stretches of p in chain order -> [(t0,t1,p0,p1)], or None."""
out, i, pos = [], 0, 0
while i < len(t):
for L in range(len(t) - i, minlen - 1, -1):
j = p.find(t[i:i + L], pos)
if j >= 0:
out.append((i, i + L, j, j + L)); i += L; pos = j + L; break
else:
return None
return out
def match(target, chain_seq):
"""How a CASP target sequence relates to a chain sequence.
Returns (category, fraction of target residues identical, regions as 1-based [start, end] in the chain or None)."""
if target == chain_seq:
return "byte-identical", 1.0, [[1, len(chain_seq)]]
j = chain_seq.find(target)
if j >= 0:
return "contained", 1.0, [[j + 1, j + len(target)]]
segs = pieces(target, chain_seq)
if segs:
return "pieces", 1.0, [[c + 1, d] for a, b, c, d in segs]
try:
aln = _al.align(target, chain_seq)[0]
except IndexError:
return "differs", 0.0, None
same = sum(target[i] == chain_seq[j] for (a0, a1), (b0, b1) in zip(*aln.aligned)
for i, j in zip(range(a0, a1), range(b0, b1)))
return "differs", round(same / len(target), 4), None
# ----------------------------------------------------------------------------------------------------- RCSB
def post(url, payload):
req = urllib.request.Request(url, data=json.dumps(payload).encode(), headers={"Content-Type": "application/json"})
with urllib.request.urlopen(req, timeout=180) as r:
return json.loads(r.read())
def entry_info(codes, cache_path):
"""Per entry: release date, method(s), resolution, and protein entities (canonical sequence, author chains)."""
os.makedirs(os.path.dirname(cache_path), exist_ok=True)
cache = json.load(open(cache_path)) if os.path.exists(cache_path) else {}
todo = sorted({c.upper() for c in codes} - set(cache))
gql = """query($ids:[String!]!){ entries(entry_ids:$ids){ rcsb_id rcsb_accession_info{ initial_release_date }
exptl{ method } rcsb_entry_info{ resolution_combined }
polymer_entities{ rcsb_id entity_poly{ pdbx_seq_one_letter_code_can rcsb_entity_polymer_type }
rcsb_polymer_entity_container_identifiers{ auth_asym_ids } } } }"""
for k in range(0, len(todo), 50):
got = post("https://data.rcsb.org/graphql", {"query": gql, "variables": {"ids": todo[k:k + 50]}})["data"]["entries"] or []
found = {e["rcsb_id"] for e in got}
for e in got:
cache[e["rcsb_id"]] = {
"release_date": e["rcsb_accession_info"]["initial_release_date"][:10],
"method": "; ".join(x["method"] for x in e["exptl"]),
"resolution": (e["rcsb_entry_info"].get("resolution_combined") or [None])[0],
"entities": [{"entity": pe["rcsb_id"], "sequence": pe["entity_poly"]["pdbx_seq_one_letter_code_can"].replace("\n", ""),
"chains": pe["rcsb_polymer_entity_container_identifiers"]["auth_asym_ids"]}
for pe in e["polymer_entities"] or [] if pe["entity_poly"]["rcsb_entity_polymer_type"] == "Protein"]}
for c in set(todo[k:k + 50]) - found:
cache[c] = None # not available from RCSB (e.g. obsoleted or never released)
json.dump(cache, open(cache_path, "w"), indent=1)
return {c.lower(): cache[c.upper()] for c in codes}
def download_cif(code, cache_dir):
os.makedirs(cache_dir, exist_ok=True)
path = f"{cache_dir}/{code}.cif.gz"
if not os.path.exists(path):
urllib.request.urlretrieve(f"https://files.rcsb.org/download/{code}.cif.gz", path)
return path
def latest_revision(cif_path):
block = gemmi.cif.read(cif_path).sole_block()
dates = [gemmi.cif.as_string(d) for d in block.find_values("_pdbx_audit_revision_history.revision_date")]
return max(dates) if dates else None
def clean(st):
st.setup_entities()
st.remove_hydrogens()
st.remove_alternative_conformations() # keeps the first conformer
st.remove_ligands_and_waters()
return st
def rcsb_chain(cif_path, chain_name):
"""Canonical sequence of the chain's entity and {1-based position: residue} for its observed residues."""
st = clean(gemmi.read_structure(cif_path))
poly = st[0][chain_name].get_polymer()
ent = st.get_entity_of(poly)
block = gemmi.cif.read(cif_path).sole_block()
can = None
for row in block.find("_entity_poly.", ["entity_id", "pdbx_seq_one_letter_code_can"]):
if gemmi.cif.as_string(row[0]) == ent.name:
can = gemmi.cif.as_string(row[1]).replace("\n", "").replace(" ", "")
if can is None or len(can) != len(ent.full_sequence):
raise ValueError(f"canonical sequence of entity {ent.name} does not line up with its monomer list")
residues = {r.label_seq: r for r in poly if r.label_seq is not None}
return st, can, residues
# ----------------------------------------------------------------------------------------------------- CASP files
def casp_chain(paths, target_seq):
"""Merge one or more CASP target files (domain pieces of one target) into {position: residue}; residue numbers in
CASP target files are 1-based positions in the target sequence. Returns (structure, residues, name mismatches)."""
residues = {}
keep = None
for p in paths:
st = clean(gemmi.read_structure(p))
keep = keep or st
for r in st[0][0]:
residues.setdefault(r.seqid.num, r)
mism = [(n, r.name) for n, r in residues.items()
if not (0 < n <= len(target_seq)) or _one(r.name) != target_seq[n - 1]]
return keep, residues, mism
def _one(resname):
t = gemmi.find_tabulated_residue(resname)
return t.one_letter_code.upper() if t and t.one_letter_code.strip() and t.one_letter_code != "?" else "X"
# ----------------------------------------------------------------------------------------------------- DSSP
def dssp(residues, cell=None):
"""Run mkdssp on the given residues as one chain (residue number = position). Returns
{position: (ss8_pp letter, classic ss8 letter)} and counts of how polyproline residues were resolved."""
ns = gemmi.Structure()
if cell is not None:
ns.cell = cell
m, ch = gemmi.Model("1"), gemmi.Chain("A")
for pos in sorted(residues):
ch.add_residue(residues[pos])
ch[len(ch) - 1].seqid = gemmi.SeqId(pos, " ")
m.add_chain(ch)
ns.add_model(m)
ns.setup_entities()
fd, pdb = tempfile.mkstemp(suffix=".pdb", dir=TMP)
os.close(fd)
out = pdb[:-4] + ".dssp"
try:
ns.write_pdb(pdb)
subprocess.run(["mkdssp", "--output-format", "dssp", pdb, out], check=True, capture_output=True)
lines = open(out).read().splitlines()
finally:
for p in (pdb, out):
if os.path.exists(p):
os.remove(p)
start = next(i for i, l in enumerate(lines) if l.startswith(" # RESIDUE"))
recs = [l for l in lines[start + 1:] if l[13] != "!"]
# residues inside an n-turn (n = 3, 4, 5), from the turn-start markers ('>' or 'X') in columns 19-21
in_turn = [False] * len(recs)
for k, l in enumerate(recs):
for n, col in ((3, 18), (4, 19), (5, 20)):
if l[col] in ">X":
for j in range(k + 1, min(k + n, len(recs))):
in_turn[j] = True
bad = [l for k, l in enumerate(recs) if l[16] == "T" and not in_turn[k]]
if bad:
raise RuntimeError(f"DSSP column reading is wrong: {len(bad)} residues DSSP calls T are not inside a turn")
labels, pp = {}, {"P_total": 0, "P_was_turn": 0, "P_was_bend": 0}
for k, l in enumerate(recs):
pos, s = int(l[5:10]), l[16]
s = "C" if s == " " else s
classic = s
if s == "P": # DSSP 4 polyproline; classic DSSP (no P) would give T, S or coil here
pp["P_total"] += 1
if in_turn[k]:
classic = "T"; pp["P_was_turn"] += 1
elif l[21] == "S":
classic = "S"; pp["P_was_bend"] += 1
else:
classic = "C"
labels[pos] = (s, classic)
return labels, pp
def label_strings(length, labels):
"""Label strings plus the `resolved` mask. As in NetSurfP-2.0/TAPE, a residue DSSP gives no label (missing from the
structure, or backbone incomplete) is labelled C and gets resolved = 0 (TAPE's `disorder` = 0)."""
pos = range(1, length + 1)
resolved = [1 if i in labels else 0 for i in pos]
ss8_pp = "".join(labels[i][0] if i in labels else "C" for i in pos)
ss8 = "".join(labels[i][1] if i in labels else "C" for i in pos)
ss3 = "".join(SS8_TO_SS3[c] for c in ss8)
return ss3, ss8, ss8_pp, resolved
def coordinates(length, residues):
"""Per atom name: list over positions of [x, y, z] or None (residue missing, or atom absent e.g. CB of glycine)."""
out = {a: [None] * length for a in ATOMS}
for pos, r in residues.items():
if not 0 < pos <= length:
continue
for a in ATOMS:
at = r.find_atom(a, "*")
if at is not None:
out[a][pos - 1] = [round(at.pos.x, 3), round(at.pos.y, 3), round(at.pos.z, 3)]
return out