File size: 7,618 Bytes
1c12c1a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
"""Secondary-structure assignment from an mmCIF chain, mapped onto the chain's full SEQRES sequence.

Each assigner returns a list (one entry per SEQRES residue) of 8-state DSSP letters (G H I B E S T C, loops as C)
or None where the residue has no usable coordinates. 3-state uses TAPE's reduction: G,H,I->H; B,E->E; S,T,C->C.
"""
import os, tempfile, subprocess
import numpy as np
import gemmi

SS8_TO_SS3 = {"G": "H", "H": "H", "I": "H", "B": "E", "E": "E", "S": "C", "T": "C", "C": "C", "P": "C"}
TMP = os.environ.get("SS_TMP", tempfile.gettempdir())


def one_letter(resname):
    t = gemmi.find_tabulated_residue(resname)
    if t is None or not t.one_letter_code.strip():
        return "X"
    c = t.one_letter_code.upper()
    return c if c != "?" else "X"


def load(cif_path):
    st = gemmi.read_structure(cif_path)
    st.setup_entities()
    st.remove_hydrogens()
    st.remove_alternative_conformations()
    st.remove_ligands_and_waters()
    return st


def chain_info(st, auth_chain):
    """SEQRES sequence of the chain's entity and the observed polymer residues with their 1-based SEQRES index."""
    model = st[0]
    poly = model[auth_chain].get_polymer()
    ent = st.get_entity_of(poly)
    seqres = "".join(one_letter(gemmi.Entity.first_mon(m)) for m in ent.full_sequence)
    residues = [r for r in poly if r.label_seq is not None]
    return seqres, residues


def _subset_structure(st, chains, renumber):
    """New structure with only the polymer residues of `chains`; residues renumbered to label_seq (no icodes)."""
    ns = gemmi.Structure()
    ns.cell = st.cell
    ns.spacegroup_hm = st.spacegroup_hm
    m = gemmi.Model("1")
    for name in chains:
        nc = gemmi.Chain(name)
        for r in st[0][name].get_polymer():
            if r.label_seq is None:
                continue
            nc.add_residue(r)
            if renumber:
                nc[len(nc) - 1].seqid = gemmi.SeqId(r.label_seq, " ")
        m.add_chain(nc)
    ns.add_model(m)
    ns.setup_entities()
    return ns


def mdtraj_assign(st, auth_chain, context="chain"):
    """mdtraj.compute_dssp (port of DSSP 2.2). context='chain': the chain alone; 'asu': all polymer chains of model 1."""
    import mdtraj as md
    seqres, residues = chain_info(st, auth_chain)
    names = [auth_chain] if context == "chain" else [c.name for c in st[0] if len(c.get_polymer()) > 0]
    ns = _subset_structure(st, names, renumber=True)
    if any(len(n) > 1 for n in names):
        ns.shorten_chain_names()
    target_index = names.index(auth_chain)
    fd, path = tempfile.mkstemp(suffix=".pdb", dir=TMP)
    os.close(fd)
    try:
        ns.write_pdb(path)
        traj = md.load_pdb(path, standard_names=False)
    finally:
        os.remove(path)
    codes = md.compute_dssp(traj, simplified=False)[0]
    out = [None] * len(seqres)
    chain = traj.topology.chain(target_index)
    for res in chain.residues:
        c = codes[res.index]
        if c == "NA":
            continue
        out[res.resSeq - 1] = "C" if c == " " else c
    return seqres, out


def pydssp_assign(st, auth_chain):
    """PyDSSP (simplified, 3-state) on the chain alone, using residues that have N, CA, C and O."""
    import pydssp
    seqres, residues = chain_info(st, auth_chain)
    keep, coords = [], []
    for r in residues:
        atoms = {a.name: a.pos for a in r}
        if all(k in atoms for k in ("N", "CA", "C", "O")):
            keep.append(r.label_seq)
            coords.append([[atoms[k].x, atoms[k].y, atoms[k].z] for k in ("N", "CA", "C", "O")])
    ss = pydssp.assign(np.asarray(coords, dtype=np.float32), out_type="c3")
    out = [None] * len(seqres)
    for i, c in zip(keep, ss):
        out[i - 1] = "C" if c == "-" else c
    return seqres, out


def mkdssp_assign(st, auth_chain, binary="mkdssp", context="chain", extra_args=()):
    """External DSSP binary (2.x or 4.x), via a PDB file of the chain (or the whole ASU); parses the classic DSSP output."""
    seqres, residues = chain_info(st, auth_chain)
    names = [auth_chain] if context == "chain" else [c.name for c in st[0] if len(c.get_polymer()) > 0]
    ns = _subset_structure(st, names, renumber=True)
    if context == "chain":
        ns[0][0].name = "A"  # PDB format holds 1-character chain IDs; the chain is alone, so its name doesn't matter
    fd, pdb = tempfile.mkstemp(suffix=".pdb", dir=TMP)
    os.close(fd)
    dssp_out = pdb[:-4] + ".dssp"
    try:
        ns.write_pdb(pdb)
        args = [binary, pdb, dssp_out]
        if "4" in subprocess.run([binary, "--version"], capture_output=True, text=True).stdout.split("version")[-1][:3]:
            args = [binary, "--output-format", "dssp", *extra_args, pdb, dssp_out]
        subprocess.run(args, check=True, capture_output=True)
        lines = open(dssp_out).read().splitlines()
    finally:
        for p in (pdb, dssp_out):
            if os.path.exists(p):
                os.remove(p)
    start = next(i for i, l in enumerate(lines) if l.startswith("  #  RESIDUE"))
    out = [None] * len(seqres)
    for l in lines[start + 1:]:
        if l[13] == "!":  # chain break marker
            continue
        if l[11] != auth_chain[0] and context != "chain":
            continue
        resnum = int(l[5:10])
        c = l[16]
        out[resnum - 1] = "C" if c == " " else c
    return seqres, out


def casp_target_assign(pdb_path, target_seq, tool="mdtraj", extra_args=()):
    """mdtraj DSSP on an official CASP target file, whose residue numbers are 1-based positions in the target sequence.
    Returns (labels per target residue or None, list of (pos, file_resname, seq_letter) mismatches)."""
    import mdtraj as md
    st = gemmi.read_structure(pdb_path)
    st.setup_entities()
    st.remove_hydrogens()
    st.remove_alternative_conformations()
    st.remove_ligands_and_waters()
    st.raw_remarks = []  # CASP target files start with a free-text 'REMARK  Txxxx' line that DSSP 4 cannot parse
    chain = st[0][0]
    if not chain.name.strip():
        chain.name = "A"  # CASP target files have an empty chain ID, which DSSP 4 rejects
    mism = [(r.seqid.num, r.name, target_seq[r.seqid.num - 1] if 0 < r.seqid.num <= len(target_seq) else "?")
            for r in chain if one_letter(r.name) != (target_seq[r.seqid.num - 1] if 0 < r.seqid.num <= len(target_seq) else "?")]
    if tool == "mkdssp":
        fd, path = tempfile.mkstemp(suffix=".pdb", dir=TMP)
        os.close(fd)
        out_path = path[:-4] + ".dssp"
        try:
            st.write_pdb(path)
            subprocess.run(["mkdssp", "--output-format", "dssp", *extra_args, path, out_path], check=True, capture_output=True)
            lines = open(out_path).read().splitlines()
        finally:
            for q in (path, out_path):
                if os.path.exists(q):
                    os.remove(q)
        start = next(i for i, l in enumerate(lines) if l.startswith("  #  RESIDUE"))
        out = [None] * len(target_seq)
        for l in lines[start + 1:]:
            if l[13] == "!":
                continue
            out[int(l[5:10]) - 1] = "C" if l[16] == " " else l[16]
        return out, mism
    fd, path = tempfile.mkstemp(suffix=".pdb", dir=TMP)
    os.close(fd)
    try:
        st.write_pdb(path)
        traj = md.load_pdb(path, standard_names=False)
    finally:
        os.remove(path)
    codes = md.compute_dssp(traj, simplified=False)[0]
    out = [None] * len(target_seq)
    for res in traj.topology.chain(0).residues:
        if codes[res.index] != "NA":
            out[res.resSeq - 1] = "C" if codes[res.index] == " " else codes[res.index]
    return out, mism