File size: 28,004 Bytes
1c12c1a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7bf35b0
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
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
"""Write the dataset card for hazemessam/SSP from a built and validated SSP.

Numbers about the data are computed here from the files and logs; check results come from logs/validation.json
(written by validate_ssp.py). Numbers from the earlier analyses are listed in ANALYSES with the script that computed them.

usage: python -I scripts/make_ssp_readme.py [build/ssp]   -> {out}/README.md, and copies the scripts to {out}/scripts/
"""
import os, sys, glob, json, shutil, hashlib, statistics, collections
import pyarrow as pa, pyarrow.parquet as pq, pyarrow.compute as pc

OUT = sys.argv[1] if len(sys.argv) > 1 else "build/ssp"
TAPE_SPLITS = ["train", "validation", "cb513", "ts115", "casp12"]
ROUNDS = ["casp12", "casp13", "casp14", "casp15", "casp16"]
SCRIPTS = ["build_ssp.py", "ssp_lib.py", "validate_ssp.py", "make_ssp_readme.py", "compare_ss_tools_helpers.py",
           "check_modified_residues.py", "check_netsurfp_train.py", "compare_ss_tools.py", "ss_assign.py",
           "compare_casp12_archive.py", "casp12_superpose.py"]
# Results of the analyses run before the build (outputs recorded in reports/SSP_report.md)
ANALYSES = {
    "train_check": dict(script="check_netsurfp_train.py", chains=200, residues=48_889, ss8=99.95, ss3=99.96, identical=191),
    "tools": dict(script="compare_ss_tools.py", residues=6_417, chain=99.94, entry=99.77),
    "casp_files": dict(script="compare_casp12_archive.py, casp12_superpose.py", in_archive=16, residues=4_121, ss8=91.92,
                       ss3=94.69, same=9, same_rmsd="0.00-0.06", slight=2, slight_rmsd="0.35-0.55", far=5, far_rmsd="1.5-5.6"),
    "modified": dict(script="check_modified_residues.py", casp12_chains=20, casp12_mod=44, train_chains=238, train_mod=308,
                     train_res="MSE 296, FME 2, ACE 2, CSO 2, 6V1 2, CSD 1, CME 1, PCA 1, TOX 1"),
    "tape_code": "tape/datasets.py, class SecondaryStructureDataset, commit 6d345c2 (github.com/songlab-cal/tape)",
}
A = ANALYSES
V = json.load(open(f"{OUT}/logs/validation.json"))
assert V["passed"], "validation did not pass; run validate_ssp.py first"


def n(x):
    return f"{x:,}"


def table(headers, rows):
    out = ["| " + " | ".join(headers) + " |", "| " + " | ".join("---" for _ in headers) + " |"]
    return "\n".join(out + ["| " + " | ".join(str(c) for c in r) + " |" for r in rows])


def sha256(path):
    h = hashlib.sha256()
    with open(path, "rb") as f:
        for b in iter(lambda: f.read(1 << 20), b""):
            h.update(b)
    return h.hexdigest()


def flat(col):
    return pc.list_flatten(col)


# ------------------------------------------------------------------------------------------------ statistics
stats = {}
for path in sorted(glob.glob(f"{OUT}/*/*.parquet")):
    key = os.path.relpath(path, OUT)
    t = pq.read_table(path, columns=["id", "sequence", "ss3", "ss8", "resolved", "valid_mask", "casp_targets",
                                     "target_match", "target_identity", "in_tape"])
    seq, res, vm = t["sequence"].to_pylist(), t["resolved"].to_pylist(), t["valid_mask"].to_pylist()
    lens = [len(s) for s in seq]
    c3, c8 = collections.Counter(), collections.Counter()
    for a, b, r in zip(t["ss3"].to_pylist(), t["ss8"].to_pylist(), res):
        c3.update(x for x, m in zip(a, r) if m); c8.update(x for x, m in zip(b, r) if m)
    pairs = [(m, i) for ms, ids in zip(t["target_match"].to_pylist(), t["target_identity"].to_pylist()) if ms for m, i in zip(ms, ids)]
    stats[key] = dict(rows=len(seq), ids=len(set(t["id"].to_pylist())), residues=sum(lens), resolved=sum(sum(r) for r in res),
                      masked=sum(v.count(0) for v in vm if v), min=min(lens), max=max(lens), median=int(statistics.median(lens)),
                      c3=c3, c8=c8, match=collections.Counter(m for m, _ in pairs),
                      differs=[i for m, i in pairs if m == "differs"], targets=len(pairs),
                      in_tape=sum(1 for x in t["in_tape"].to_pylist() if x), sha=sha256(path), mb=os.path.getsize(path) / 2 ** 20)
    if key == "tape/cb513.parquet":
        def runs(m):
            return sum(1 for a, b in zip([0] + m, m) if b == 1 and a == 0)
        stats[key].update(one_run=sum(1 for m in vm if runs(m) == 1), no_run=sum(1 for m in vm if 1 not in m),
                          masked_resolved=sum(1 for v, r in zip(vm, res) for a, b in zip(v, r) if a == 0 and b == 1))
S = stats.get

# rcsb/casp: residues with a complete backbone (N, CA, C, O) that mkdssp left without a label
full_bb = full_bb_unlabelled = 0
for v in ("rcsb", "casp"):
    for r in ROUNDS:
        for row in pq.read_table(f"{OUT}/{v}/{r}.parquet", columns=["resolved", "n_xyz", "ca_xyz", "c_xyz", "o_xyz"]).to_pylist():
            for k, m in enumerate(row["resolved"]):
                if all(row[a][k] is not None for a in ("n_xyz", "ca_xyz", "c_xyz", "o_xyz")):
                    full_bb += 1; full_bb_unlabelled += m == 0
assert full_bb_unlabelled == 1, "the card describes exactly one such residue (DHI in 7utd-A); update the text"
_t12 = pq.read_table(f"{OUT}/rcsb/casp12.parquet", columns=["casp_targets", "in_tape"]).to_pylist()
tape12_targets = sum(len(r["casp_targets"]) for r in _t12 if r["in_tape"])

# TAPE's extra fields, measured over all five TAPE splits
fields = collections.Counter()
rng = {}
for s in TAPE_SPLITS:
    t = pq.read_table(f"{OUT}/tape/{s}.parquet", columns=["sequence", "resolved", "rsa", "asa_max", "phi", "psi", "interface", "evolutionary"])
    R = flat(t["resolved"])
    res_mask, unres_mask = pc.equal(R, 1), pc.equal(R, 0)
    for f in ("rsa", "asa_max", "phi", "psi"):
        v = pc.filter(flat(t[f]), res_mask)
        if f in ("phi", "psi"):
            v = pc.filter(v, pc.not_equal(v, 360))
        if f == "asa_max":
            v = pc.filter(v, pc.not_equal(v, -1))
        mm = pc.min_max(v).as_py()
        lo, hi = rng.get(f, (float("inf"), float("-inf")))
        rng[f] = (min(lo, mm["min"]), max(hi, mm["max"]))
        u = pc.filter(flat(t[f]), unres_mask)
        fields[f"{f}_unresolved_nonzero"] += len(u) - pc.sum(pc.equal(u, 0)).as_py() if f != "asa_max" else 0
    e = pc.list_flatten(flat(t["evolutionary"]))
    mm = pc.min_max(e).as_py()
    lo, hi = rng.get("evolutionary", (float("inf"), float("-inf")))
    rng["evolutionary"] = (min(lo, mm["min"]), max(hi, mm["max"]))
    fields["evo_len_not_30"] += pc.sum(pc.not_equal(pc.list_value_length(flat(t["evolutionary"])), 30)).as_py()
    fields["interface_1"] += pc.sum(flat(t["interface"])).as_py()
    fields["interface_unresolved_1"] += pc.sum(pc.filter(flat(t["interface"]), unres_mask)).as_py()
    seqs = t["sequence"].to_pylist()
    for sq, r, phi, psi, am in zip(seqs, t["resolved"].to_pylist(), t["phi"].to_pylist(), t["psi"].to_pylist(), t["asa_max"].to_pylist()):
        L_ = len(r)
        for k in range(L_):
            if not r[k]:
                continue
            if phi[k] == 360:
                fields["phi360"] += 1; fields["phi360_end"] += k == 0 or not r[k - 1]
            if psi[k] == 360:
                fields["psi360"] += 1; fields["psi360_end"] += k == L_ - 1 or not r[k + 1]
            if am[k] == -1:
                fields["asa_max_-1"] += 1; fields["asa_max_-1_X"] += sq[k] == "X"
assert all(fields[f"{f}_unresolved_nonzero"] == 0 for f in ("rsa", "phi", "psi")) and fields["interface_unresolved_1"] == 0
assert fields["evo_len_not_30"] == 0 and fields["asa_max_-1"] == fields["asa_max_-1_X"]

logs = {}
for f in sorted(glob.glob(f"{OUT}/logs/*_*.json")):
    l = json.load(open(f))
    if "split" in l:
        logs[f"{l['source']}/{l['split']}.parquet"] = l
pp = collections.Counter()
for l in logs.values():
    pp.update(l.get("polyproline") or {})
dssp_version = next(l["dssp"] for l in logs.values() if l.get("dssp"))
tape_ok = all(c["ok"] for c in V["checks"] if "identical to TAPE's" in c["check"])
r12 = V["rcsb_casp12_vs_tape"]
flag = r12["disorder_flag_vs_pdb"]
tape12_resolved = sum(v for k, v in flag.items() if k.startswith("tape_disorder_1"))
tape12_missing = sum(v for k, v in flag.items() if k.startswith("tape_disorder_0"))
cb = S("tape/cb513.parquet")
tr = S("tape/train.parquet")
listed = {"casp12": 45, "casp13": 41, "casp14": 26, "casp15": 65, "casp16": 44}


def lenstr(s):
    return f"{n(s['min'])} to {n(s['max'])} (median {n(s['median'])})"


# ------------------------------------------------------------------------------------------------ front matter
configs = {
    "rcsb": [(s, f"tape/{s}.parquet") for s in TAPE_SPLITS[:4]] + [(r, f"rcsb/{r}.parquet") for r in ROUNDS],
    "casp": [(s, f"tape/{s}.parquet") for s in TAPE_SPLITS[:4]] + [(r, f"casp/{r}.parquet") for r in ROUNDS],
    "tape": [(s, f"tape/{s}.parquet") for s in TAPE_SPLITS],
}
fm = ["---", "pretty_name: SSP (protein secondary structure)", "license: other", "license_name: mixed",
      "tags:", "- biology", "- proteins", "- protein-language-models", "- secondary-structure", "- token-classification",
      "- dssp", "- casp", "- tape", "size_categories:", "- 10K<n<100K", "configs:"]
for name, files in configs.items():
    fm.append(f"- config_name: {name}")
    if name == "rcsb":
        fm.append("  default: true")
    fm.append("  data_files:")
    for split, path in files:
        fm += [f"  - split: {split}", f"    path: {path}"]
fm.append("---")

# ------------------------------------------------------------------------------------------------ tables
split_rows = []
for s in TAPE_SPLITS[:4]:
    st = S(f"tape/{s}.parquet")
    split_rows.append([f"`{s}`", "TAPE (all versions)", n(st["rows"]), n(st["residues"]),
                       f"{100 * st['resolved'] / st['residues']:.1f}%", lenstr(st)])
for r in ROUNDS:
    for v in ("rcsb", "casp", "tape"):
        st = S(f"{v}/{r}.parquet")
        if st:
            split_rows.append([f"`{r}`", f"`{v}`", n(st["rows"]), n(st["residues"]),
                               f"{100 * st['resolved'] / st['residues']:.1f}%", lenstr(st)])

drop_rows = []
for r in ROUNDS:
    for v in ("rcsb", "casp"):
        l, st = logs[f"{v}/{r}.parquet"], S(f"{v}/{r}.parquet")
        reasons = collections.Counter("same sequence as another row" if d["reason"].startswith("same sequence") else d["reason"]
                                      for d in l["dropped"])
        cover = f"{st['targets']} of {listed[r]} CASP-listed targets, in {st['rows']} rows" if v == "rcsb" else f"{st['rows']} targets"
        m = ", ".join(f"{k} {c}" for k, c in sorted(st["match"].items())) if v == "rcsb" else "—"
        drop_rows.append([r.upper(), f"`{v}`", cover, m, "; ".join(f"{k} ({c})" for k, c in reasons.items()) or "none"])

rcsb_pairs = collections.Counter()
differs = []
for r in ROUNDS:
    rcsb_pairs.update(S(f"rcsb/{r}.parquet")["match"]); differs += S(f"rcsb/{r}.parquet")["differs"]

c3, c8 = tr["c3"], tr["c8"]
names8 = {"G": "3-10 helix", "H": "alpha helix", "I": "pi helix", "B": "beta bridge", "E": "beta strand", "S": "bend",
          "T": "turn", "C": "coil / other"}
F = fields

body = f"""
# SSP: protein secondary structure

Protein chains with a secondary-structure label for every residue, written as strings (`"CCHHHHEEE…"`):

- **Training data and classic test sets from TAPE** (Rao et al., 2019): `train`, `validation`, `cb513`, `ts115`, `casp12`.
  TAPE took this data from NetSurfP-2.0 (Klausen et al., 2019). Every row and value is TAPE's; the integer labels are
  written as letters, `primary` is renamed `sequence`, `disorder` is renamed `resolved`, and `protein_length` (always equal to
  the sequence length) is dropped.
- **CASP test sets, CASP12 to CASP16**, labelled with DSSP by a procedure that reproduces NetSurfP-2.0's training labels on
  {A['train_check']['ss8']}% of residues (see [How the CASP test sets were built](#how-the-casp-test-sets-were-built)). Each round
  comes in two versions: built from the PDB entries CASP lists (`rcsb`, default) and from CASP's own target files (`casp`).

**The task:** given a chain's amino-acid sequence (`sequence`), predict each residue's 3-state (`ss3`) or 8-state (`ss8`) label.

## Quick start

```python
from datasets import load_dataset

ssp = load_dataset("hazemessam/SSP")             # version `rcsb` (default)
train, valid, test = ssp["train"], ssp["validation"], ssp["casp14"]
print(train[0]["sequence"][:40], train[0]["ss3"][:40])

tape = load_dataset("hazemessam/SSP", "tape")    # TAPE's data only: train, validation, cb513, ts115, casp12
casp = load_dataset("hazemessam/SSP", "casp")    # CASP test sets built from CASP's own target files
```

## Versions (subsets) and splits

All three versions have the same columns and the same `train`, `validation`, `cb513` and `ts115` (the files in `tape/`).
They differ in the CASP splits:

{table(["", "`rcsb` (default)", "`casp`", "`tape`"], [
    ["Splits", "train, validation, cb513, ts115, casp12 … casp16", "train, validation, cb513, ts115, casp12 … casp16",
     "train, validation, cb513, ts115, casp12"],
    ["CASP structures", "the PDB entry CASP lists for the target, current version from RCSB", "CASP's public target files", "TAPE's CASP12"],
    ["CASP row", "one PDB chain (lists the CASP targets it contains)", "one CASP target", "one PDB chain"],
    ["CASP sequence", "the PDB entity's full canonical sequence", "CASP's target sequence", "TAPE's"],
    ["CASP labels", "mkdssp on the chain alone", "mkdssp on CASP's target structure", "TAPE's"],
])}

{table(["split", "version", "chains", "residues", "with structure (`resolved`)", "sequence length"], split_rows)}

## Labels

| `ss3` | meaning | `train` residues with structure |
| --- | --- | --- |
| `H` | helix (G, H, I) | {n(c3['H'])} |
| `E` | strand (B, E) | {n(c3['E'])} |
| `C` | coil / other (S, T, C) | {n(c3['C'])} |

{table(["`ss8`", "meaning", "`train` residues with structure"], [[f"`{k}`", names8[k], n(c8[k])] for k in "GHIBESTC"])}

- **`ss8`** has the eight DSSP states. **`ss3`** is `ss8` reduced with TAPE's rule (G, H, I → H; B, E → E; S, T, C → C);
  `validate_ssp.py` checks this on every residue of every split.
- **`ss8_pp`** (`rcsb` and `casp` only) is the output of {dssp_version}, which has a ninth state, `P` (polyproline II). In
  `ss8`, a `P` residue is written `T` if DSSP's turn columns place it inside a 3-, 4- or 5-turn, `S` if DSSP's bend column
  marks it, and `C` otherwise. In this build {n(pp['P_total'])} residues are `P`: {n(pp['P_was_turn'])} became `T`,
  {n(pp['P_was_bend'])} became `S`, {n(pp['P_total'] - pp['P_was_turn'] - pp['P_was_bend'])} became `C`.

### Which residues to score

- **`resolved`**: `1` = the residue has structure; `0` = it has none, and is labelled `C`, as in TAPE (so the labels have
  only 3 or 8 classes).
  - TAPE's splits: TAPE's `disorder` values. In all five splits every residue with `0` is labelled coil. On TAPE's CASP12,
    {n(flag.get('tape_disorder_1__pdb_resolved_1', 0))} of the {n(tape12_resolved)} residues with `1` have a DSSP label in today's PDB entry, and
    {n(flag.get('tape_disorder_0__pdb_resolved_0', 0))} of the {n(tape12_missing)} residues with `0` have none.
  - `rcsb` and `casp`: `1` exactly where mkdssp gives the residue a label. Every residue with `1` has N, CA, C and O
    coordinates. Of the {n(full_bb)} residues that have all four, {full_bb_unlabelled} has no label: a D-histidine (`DHI`,
    a HETATM record) in 7utd-A.
- **`valid_mask`** (TAPE's splits only): TAPE's `valid_mask` values. It is `0` only in `cb513`: {n(cb['masked'])} residues,
  {n(cb['masked_resolved'])} of them with structure. In {n(cb['one_run'])} of the {n(cb['rows'])} `cb513` rows, `valid_mask = 1`
  on one continuous stretch of the chain; in {n(cb['no_run'])} rows on no residue. The {n(cb['rows'])} rows have
  {n(cb['ids'])} distinct ids; rows sharing an id have the same sequence and labels, and differ only in `valid_mask`, whose
  stretches do not overlap.
- TAPE's own training and evaluation code ({A['tape_code']}) reads only `primary` and `ss3`, so it scores every residue,
  including residues without structure (as coil). Scoring only `resolved == 1` (and `valid_mask == 1`) gives different
  numbers; state which one you use.

```python
def accuracy(pred: str, row: dict, labels: str = "ss3"):
    \"\"\"Correct and scored residues of one row, over residues with structure (and valid_mask == 1 where present).\"\"\"
    mask = row["resolved"]
    if row["valid_mask"] is not None:
        mask = [a & b for a, b in zip(mask, row["valid_mask"])]
    hits = sum(p == t for p, t, m in zip(pred, row[labels], mask) if m)
    return hits, sum(mask)
```

## Columns

{table(["column", "type", "filled in", "content"], [
    ["`id`", "string", "all", "`rcsb`/`tape`: PDB chain, e.g. `5uvn-A`; `casp`: CASP target, e.g. `T1024`"],
    ["`sequence`", "string", "all", "**input**: amino-acid sequence, one letter per residue (for `X`, see [Modified residues](#modified-residues))"],
    ["`ss3`, `ss8`", "string", "all", "**labels**: one letter per residue (tables above)"],
    ["`ss8_pp`", "string", "`rcsb`, `casp`", "DSSP 4 labels including `P`"],
    ["`resolved`", "list of 0/1", "all", "1 = residue has structure (see above)"],
    ["`valid_mask`", "list of 0/1", "TAPE splits", "TAPE's `valid_mask` (see above)"],
    ["`rsa`", "list of float", "TAPE splits", f"TAPE's `rsa` (relative solvent accessibility): {rng['rsa'][0]:g} to {rng['rsa'][1]:g} on residues with structure; 0 on residues without"],
    ["`asa_max`", "list of float", "TAPE splits", f"TAPE's `asa_max`: {rng['asa_max'][0]:g} to {rng['asa_max'][1]:g}; -1 at {n(F['asa_max_-1'])} residues, all `X`"],
    ["`phi`, `psi`", "list of float", "TAPE splits", f"TAPE's backbone dihedral angles: {rng['phi'][0]:g} to {rng['phi'][1]:g}, or 360 ({n(F['phi360_end'])} of {n(F['phi360'])} `phi` = 360 are at the chain's first residue or after a residue without structure; {n(F['psi360_end'])} of {n(F['psi360'])} `psi` = 360 at the last residue or before one without structure); 0 on residues without structure"],
    ["`interface`", "list of 0/1", "TAPE splits", f"TAPE's `interface` (1 on {n(F['interface_1'])} residues, none of them without structure)"],
    ["`evolutionary`", "list of [30 floats]", "TAPE splits", f"TAPE's `evolutionary`: 30 values per residue, {rng['evolutionary'][0]:g} to {rng['evolutionary'][1]:g}"],
    ["`n_xyz`, `ca_xyz`, `c_xyz`, `o_xyz`, `cb_xyz`", "list of [x, y, z] or null", "`rcsb`, `casp`",
     "coordinates (Å) of the N, CA, C, O and CB atoms from the structure used; null where the atom is absent (e.g. CB of glycine) or the residue is missing"],
    ["`casp_targets`", "list of string", "CASP splits", "CASP targets this row covers"],
    ["`target_match`", "list of string", "CASP splits", "per target: `byte-identical`, `contained` (one stretch of `sequence`), `pieces` (several separate stretches in order) or `differs`"],
    ["`target_identity`", "list of float", "CASP splits", "per target: fraction of the CASP sequence's residues identical in `sequence` (local alignment, BLOSUM62)"],
    ["`target_regions`", "list of [[start, end], …]", "CASP splits", "per target: 1-based, inclusive positions in `sequence` (null for `differs`)"],
    ["`pdb_id`, `chain`", "string", "all", "PDB entry and author chain (`casp`: the PDB code(s) CASP lists, if any)"],
    ["`method`, `resolution`, `release_date`, `pdb_revision_date`", "string / float", "`rcsb`", "from the PDB entry used"],
    ["`source_files`", "list of string", "all", "the file(s) the row was built from"],
    ["`in_tape`", "bool", "all", "the row's chain (`casp`: the target's CASP-listed chain) is in TAPE's data"],
])}

Columns a split can't fill are null.

## How the CASP test sets were built

1. **Targets.** CASP's target list for each round, canceled targets removed. `rcsb`: the PDB code(s) CASP's target list
   gives for the target (no sequence search). `casp`: every target structure in CASP's public target archive.
2. **Structure.** `rcsb`: the current mmCIF entry from RCSB, and in it the protein chain whose sequence has the highest
   identity to the CASP target sequence; hydrogens, alternative conformations (all but the first), ligands and water
   removed. `casp`: CASP's target file (CASP15: the domain files of a target merged back into one chain by residue number;
   CASP16: the first version of targets released in several versions).
3. **Labels.** {dssp_version} on the chain alone (not the whole entry).
4. **Duplicates.** Within a round, rows with identical sequences are kept once (the others are listed in `logs/`).

**Checks behind these choices** (scripts in `scripts/`):

{table(["check", "result", "script"], [
    [f"labels from this procedure vs NetSurfP-2.0's training labels ({A['train_check']['chains']} random `train` chains, seed 0, today's PDB entries)",
     f"{A['train_check']['ss8']}% (8-state), {A['train_check']['ss3']}% (3-state) of {n(A['train_check']['residues'])} residues; {A['train_check']['identical']} of {A['train_check']['chains']} chains identical",
     f"`{A['train_check']['script']}`"],
    ["mkdssp on the chain alone vs on the whole entry, against TAPE's CASP12 labels",
     f"{A['tools']['chain']}% vs {A['tools']['entry']}% (8-state) of {n(A['tools']['residues'])} residues", f"`{A['tools']['script']}`"],
    ["TAPE's CASP12 chains vs the PDB entries CASP lists", "21 of 21 are the CASP-listed entry and chain", "`build_ssp.py` (`in_tape`), `validate_ssp.py`"],
    [f"`rcsb` CASP12 labels vs TAPE's", f"{100 * r12['agree'] / r12['residues']:.2f}% of {n(r12['residues'])} residues with structure in both", "`validate_ssp.py`"],
    [f"CASP's archive files vs TAPE's CASP12 ({A['casp_files']['in_archive']} of TAPE's 21 targets are in the archive)",
     f"labels: {A['casp_files']['ss8']}% (8-state), {A['casp_files']['ss3']}% (3-state) of {n(A['casp_files']['residues'])} residues; CA RMSD to the PDB entry after superposition: "
     f"{A['casp_files']['same']} targets {A['casp_files']['same_rmsd']} Å, {A['casp_files']['slight']} targets {A['casp_files']['slight_rmsd']} Å, {A['casp_files']['far']} targets {A['casp_files']['far_rmsd']} Å",
     f"`compare_casp12_archive.py`, `casp12_superpose.py`"],
])}

The `rcsb` version uses the PDB entries because they reproduce TAPE's CASP12 labels ({100 * r12['agree'] / r12['residues']:.2f}%) and
CASP's archive files do not ({A['casp_files']['ss8']}%); the table above shows that the archive files differ in coordinates
from the PDB entries for 7 of the 16 targets.

{table(["round", "version", "rows", "CASP target vs PDB chain (target, row) pairs", "left out (reason: count)"], drop_rows)}

## Modified residues

In every TAPE chain compared, TAPE writes every non-standard residue as `X`. `rcsb` sequences are the PDB canonical
sequence, which writes the parent amino acid where there is one (selenomethionine `MSE` as `M`).

How this was found (`scripts/check_modified_residues.py`): each TAPE chain was compared position by position with the
canonical sequence of its current PDB entry, and the PDB residue name was read at every position.

{table(["chains", "chains compared", "non-standard residues", "TAPE's letter there", "residues"], [
    ["TAPE's CASP12", A["modified"]["casp12_chains"], A["modified"]["casp12_mod"], f"`X` at all {A['modified']['casp12_mod']}", "MSE 44"],
    ["TAPE's `train` (entries of the 200-chain check above)", A["modified"]["train_chains"], A["modified"]["train_mod"], f"`X` at all {A['modified']['train_mod']}", A["modified"]["train_res"]],
])}

(One CASP12 chain, 5uvn-A, was not compared: its current PDB entry is 453 residues long, TAPE's sequence 455.)

## Notes

- Sequence overlap between the CASP rows and `train`/`validation` was not checked. TAPE's CASP12 has 21 chains; in
  `rcsb` they cover {tape12_targets} of the {listed['casp12']} CASP12 targets with a CASP-listed PDB code. `in_tape` marks them in every version.
- `rcsb` sequences are the full canonical sequence of the PDB entity, so they can be longer than the CASP target. Of the
  {sum(rcsb_pairs.values())} (target, row) pairs in `rcsb`: {', '.join(f'{k} {v}' for k, v in sorted(rcsb_pairs.items()))}.
  Use `target_regions` to cut out a target. For `differs`, `target_identity` ranges from {min(differs):.2f} to {max(differs):.2f}.
- CB513 ids are not unique (see `valid_mask`).

## Verification

`scripts/validate_ssp.py` ran on {V['date']}; all {len(V['checks'])} checks passed (results in `logs/validation.json`):

- every file has the same columns and types;
- per row: every per-residue column has the sequence's length; label alphabets; `ss3` derived from `ss8`, and `ss8` from
  `ss8_pp`; residues without structure labelled `C`; residues with structure have N, CA, C and O coordinates (`rcsb`, `casp`);
- TAPE's splits equal TAPE's JSON files field by field, same rows in the same order;
- `rcsb` CASP12 contains TAPE's 21 chains; labels agree with TAPE on {100 * r12['agree'] / r12['residues']:.2f}% of {n(r12['residues'])} residues;
- every CASP-listed target is in a row or listed in `logs/` with the reason it was left out.

{table(["file", "rows", "MB", "SHA-256"], [[f"`{k}`", n(v["rows"]), f"{v['mb']:.1f}", f"`{v['sha']}`"] for k, v in sorted(stats.items())])}

`scripts/` holds the code that built and checked this repository and the analyses cited above; they read the source
downloads from `data/original/` (paths in each script). `logs/` records, per version and split, every target left out and
why, how `P` residues were converted, and the DSSP version.

## Sources, licenses and citation

- TAPE's splits: TAPE's download
  <http://s3.amazonaws.com/songlabdata/proteindata/data_raw_pytorch/secondary_structure.tar.gz>; TAPE's repository is
  BSD-3-Clause.
- `rcsb`: mmCIF files from the RCSB PDB (<https://www.rcsb.org>); PDB data are CC0 1.0.
- `casp`: target structures and sequences from the Protein Structure Prediction Center (<https://predictioncenter.org>).
- Labels: DSSP ({dssp_version}, <https://github.com/PDB-REDO/dssp>).

Please cite TAPE and NetSurfP-2.0 for the training data and the classic test sets, and CASP, the PDB and DSSP for the CASP test sets:

```bibtex
@inproceedings{{rao2019tape,
  title     = {{Evaluating Protein Transfer Learning with TAPE}},
  author    = {{Rao, Roshan and Bhattacharya, Nicholas and Thomas, Neil and Duan, Yan and Chen, Xi and Canny, John and Abbeel, Pieter and Song, Yun S.}},
  booktitle = {{Advances in Neural Information Processing Systems}},
  year      = {{2019}}
}}

@article{{klausen2019netsurfp,
  title   = {{NetSurfP-2.0: Improved prediction of protein structural features by integrated deep learning}},
  author  = {{Klausen, Michael Schantz and Jespersen, Martin Closter and Nielsen, Henrik and Jensen, Kamilla Kjaergaard and Jurtz, Vanessa Isabell and Soenderby, Casper Kaae and Sommer, Morten Otto Alexander and Winther, Ole and Nielsen, Morten and Petersen, Bent and others}},
  journal = {{Proteins: Structure, Function, and Bioinformatics}},
  year    = {{2019}}
}}

@article{{kabsch1983dssp,
  title   = {{Dictionary of protein secondary structure: pattern recognition of hydrogen-bonded and geometrical features}},
  author  = {{Kabsch, Wolfgang and Sander, Christian}},
  journal = {{Biopolymers}},
  volume  = {{22}},
  number  = {{12}},
  pages   = {{2577--2637}},
  year    = {{1983}}
}}

@article{{berman2000pdb,
  title   = {{The Protein Data Bank}},
  author  = {{Berman, Helen M. and Westbrook, John and Feng, Zukang and Gilliland, Gary and Bhat, T. N. and Weissig, Helge and Shindyalov, Ilya N. and Bourne, Philip E.}},
  journal = {{Nucleic Acids Research}},
  volume  = {{28}},
  number  = {{1}},
  pages   = {{235--242}},
  year    = {{2000}}
}}
```

For CASP, cite the CASP assessment paper of the round you use.

## Changes

Created on {V['date']}.
"""

os.makedirs(f"{OUT}/scripts", exist_ok=True)
for s in SCRIPTS:
    shutil.copy(f"scripts/{s}", f"{OUT}/scripts/{s}")
open(f"{OUT}/README.md", "w").write("\n".join(fm) + "\n" + body)
print(f"wrote {OUT}/README.md and {len(SCRIPTS)} scripts")