File size: 2,195 Bytes
638ea38
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import json
import urllib.request
import numpy as np
from Bio.Align import PairwiseAligner, substitution_matrices


def alphafold_model(acc, directory):
    directory.mkdir(parents=True, exist_ok=True)
    f = directory / f"{acc}.pdb"
    if not f.exists():
        meta = json.load(urllib.request.urlopen(f"https://alphafold.ebi.ac.uk/api/prediction/{acc}", timeout=60))[0]
        urllib.request.urlretrieve(meta["pdbUrl"], f)
    return f

ALIGNER = PairwiseAligner(mode="global", open_gap_score=-11, extend_gap_score=-1)
ALIGNER.substitution_matrix = substitution_matrices.load("BLOSUM62")


def correspondence(s1, s2):
    aln = ALIGNER.align(s1, s2)[0]
    i1, i2 = [], []
    for (a0, a1), (b0, b1) in zip(*aln.aligned):
        i1.extend(range(a0, a1))
        i2.extend(range(b0, b1))
    return np.array(i1), np.array(i2)


def kabsch(P, Q):
    pc, qc = P.mean(0), Q.mean(0)
    U, _, Vt = np.linalg.svd((P - pc).T @ (Q - qc))
    d = np.sign(np.linalg.det(U @ Vt))
    R = U @ np.diag([1.0, 1.0, d]) @ Vt
    return R, pc, qc


def tm_score(P, Q, L):
    n = len(P)
    d0 = max(1.24 * (max(L, 19) - 15) ** (1 / 3) - 1.8, 0.5)
    d0s = min(max(d0, 4.5), 8.0)
    best, best_rmsd = 0.0, np.nan
    sizes, f = [], n
    while f >= 4 and len(sizes) < 6:
        sizes.append(f)
        f //= 2
    for size in sizes:
        step = max(1, size // 2)
        for start in range(0, n - size + 1, step):
            sel = np.arange(start, start + size)
            for _ in range(20):
                R, pc, qc = kabsch(P[sel], Q[sel])
                d = np.linalg.norm((P - pc) @ R + qc - Q, axis=1)
                tm = np.sum(1 / (1 + (d / d0) ** 2)) / L
                if tm > best:
                    best, best_rmsd = tm, float(np.sqrt(np.mean(d[d < 5] ** 2))) if np.any(d < 5) else np.nan
                cut = d0s
                new = np.where(d < cut)[0]
                while len(new) < 3:
                    cut += 0.5
                    new = np.where(d < cut)[0]
                if len(new) == len(sel) and np.all(new == sel):
                    break
                sel = new
    return best, best_rmsd