anindya64 commited on
Commit
2defbcb
·
verified ·
1 Parent(s): 79fc1dc

Add normalized Parquet train/test SwissSidechain table

Browse files
README.md ADDED
@@ -0,0 +1,206 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ pretty_name: SwissSidechain Residues
3
+ license: other
4
+ tags:
5
+ - biology
6
+ - chemistry
7
+ - protein
8
+ - amino-acids
9
+ - sidechains
10
+ - molecular-dynamics
11
+ - smiles
12
+ - pdb
13
+ - mol2
14
+ - parquet
15
+ configs:
16
+ - config_name: default
17
+ data_files:
18
+ - split: train
19
+ path: data/train-*.parquet
20
+ - split: test
21
+ path: data/test-*.parquet
22
+ ---
23
+
24
+ # SwissSidechain Residues
25
+
26
+ This dataset contains a viewer-friendly Parquet table derived from the SwissSidechain archives in this repository. Each row is one unique residue entry from the L or D SMI archives, with parsed availability and summary fields for PDB, MOL2, CHARMM topology, GROMACS RTP/HDB, bundle files, and rotamer libraries.
27
+
28
+ The original ZIP archives remain in the repository. The default `datasets` configuration uses the normalized Parquet files under `data/` so that the Hugging Face Dataset Viewer and `load_dataset()` can read the residue table directly.
29
+
30
+ The source library comments state that the SwissSidechain entries are copyright of the Swiss Institute of Bioinformatics, with non-profit use allowed when the content is not modified and the copyright statement is retained. Commercial use requires a license agreement. Check the original SwissSidechain terms before commercial use.
31
+
32
+ ## Splits
33
+
34
+ The split is deterministic by entry identifier: `sha256(entry_id) % 10`. Bucket `0` is `test`; buckets `1` through `9` are `train`.
35
+
36
+ | Split | Rows |
37
+ |---|---:|
38
+ | train | 400 |
39
+ | test | 59 |
40
+ | total | 459 |
41
+
42
+ ## Dataset Statistics
43
+
44
+ | Field | Value |
45
+ |---|---:|
46
+ | Unique residue entries | 459 |
47
+ | L entries | 230 |
48
+ | D entries | 229 |
49
+ | Entries with PDB | 459 |
50
+ | Entries with MOL2 | 459 |
51
+ | Entries with CHARMM topologies | 437 |
52
+ | Entries with GROMACS RTP/HDB | 437 |
53
+ | Entries with source bundles | 459 |
54
+ | Entries with backbone-dependent rotamers | 454 |
55
+ | Entries with backbone-independent rotamers | 453 |
56
+ | Backbone-dependent rotamer rows | 15,256,136 |
57
+ | Backbone-independent rotamer rows | 11,144 |
58
+
59
+ ## Usage
60
+
61
+ Install the Hugging Face Datasets library:
62
+
63
+ ```bash
64
+ pip install datasets
65
+ ```
66
+
67
+ Load all splits:
68
+
69
+ ```python
70
+ from datasets import load_dataset
71
+
72
+ ds = load_dataset("LiteFold/SwissSidechain")
73
+ print(ds)
74
+
75
+ row = ds["train"][0]
76
+ print(row["entry_id"], row["residue_code"], row["smiles"])
77
+ ```
78
+
79
+ Load one split:
80
+
81
+ ```python
82
+ from datasets import load_dataset
83
+
84
+ train = load_dataset("LiteFold/SwissSidechain", split="train")
85
+ test = load_dataset("LiteFold/SwissSidechain", split="test")
86
+ ```
87
+
88
+ Stream rows without downloading the full table first:
89
+
90
+ ```python
91
+ from datasets import load_dataset
92
+
93
+ stream = load_dataset("LiteFold/SwissSidechain", split="train", streaming=True)
94
+ for row in stream.take(5):
95
+ print(row["entry_id"], row["stereochemistry"], row["pdb_atom_count"])
96
+ ```
97
+
98
+ Filter D residues with complete topology files:
99
+
100
+ ```python
101
+ from datasets import load_dataset
102
+
103
+ ds = load_dataset("LiteFold/SwissSidechain", split="train")
104
+ d_topologies = ds.filter(
105
+ lambda row: row["stereochemistry"] == "D"
106
+ and row["has_top"]
107
+ and row["has_rtp"]
108
+ and row["has_hdb"]
109
+ )
110
+ print(d_topologies[0])
111
+ ```
112
+
113
+ Find entries with rotamer data:
114
+
115
+ ```python
116
+ from datasets import load_dataset
117
+
118
+ ds = load_dataset("LiteFold/SwissSidechain", split="train")
119
+ with_rotamers = ds.filter(lambda row: row["bbdep_rotamer_rows"] > 0)
120
+ print(with_rotamers[0]["entry_id"], with_rotamers[0]["bbdep_rotamer_rows"])
121
+ ```
122
+
123
+ Load metadata tables directly:
124
+
125
+ ```python
126
+ import pandas as pd
127
+ from huggingface_hub import hf_hub_download
128
+
129
+ rotamer_path = hf_hub_download(
130
+ repo_id="LiteFold/SwissSidechain",
131
+ repo_type="dataset",
132
+ filename="metadata/rotamer_library_counts.parquet",
133
+ )
134
+ rotamers = pd.read_parquet(rotamer_path)
135
+ print(rotamers.head())
136
+
137
+ manifest_path = hf_hub_download(
138
+ repo_id="LiteFold/SwissSidechain",
139
+ repo_type="dataset",
140
+ filename="metadata/archive_manifest.parquet",
141
+ )
142
+ manifest = pd.read_parquet(manifest_path)
143
+ print(manifest)
144
+ ```
145
+
146
+ ## Columns
147
+
148
+ | Column | Description |
149
+ |---|---|
150
+ | `entry_id` | Stable table ID in the form `L:<code>` or `D:<code>`. |
151
+ | `residue_code` | Residue code from the source file names. |
152
+ | `stereochemistry` | Source stereochemistry group: `L` or `D`. |
153
+ | `smiles` | SMILES string from the SMI archive. |
154
+ | `smiles_reference_file` | Filename referenced inside the SMI row. |
155
+ | `source_*_path` | Source archive path used for each parsed format. |
156
+ | `has_smi` | Whether an SMI file exists. |
157
+ | `has_pdb` | Whether a PDB file exists. |
158
+ | `has_mol2` | Whether a MOL2 file exists. |
159
+ | `has_top` | Whether a CHARMM `.top` file exists. |
160
+ | `has_rtp` | Whether a GROMACS `.rtp` file exists. |
161
+ | `has_hdb` | Whether a GROMACS `.hdb` file exists. |
162
+ | `has_bundle` | Whether the entry appears in `L_sidechain.zip` or `D_residues.zip`. |
163
+ | `has_png` | Whether the source bundle contains a PNG image. |
164
+ | `has_bundle_bbdep_lib` | Whether the source bundle contains a per-entry backbone-dependent rotamer ZIP. |
165
+ | `has_bundle_bbind_lib` | Whether the source bundle contains a per-entry backbone-independent rotamer ZIP. |
166
+ | `bundle_file_extensions` | File extensions found in the source bundle. |
167
+ | `pdb_residue_names` | Residue names parsed from PDB records. |
168
+ | `pdb_atom_names` | Atom names parsed from PDB records. |
169
+ | `pdb_elements` | Element symbols parsed from PDB records. |
170
+ | `pdb_atom_count` | Number of PDB atoms. |
171
+ | `pdb_heavy_atom_count` | Number of non-hydrogen PDB atoms. |
172
+ | `pdb_hydrogen_atom_count` | Number of hydrogen PDB atoms. |
173
+ | `mol2_molecule_name` | Molecule name from the MOL2 file. |
174
+ | `mol2_molecule_type` | MOL2 molecule type. |
175
+ | `mol2_charge_type` | MOL2 charge type. |
176
+ | `mol2_atom_names` | Atom names parsed from MOL2. |
177
+ | `mol2_atom_types` | Atom types parsed from MOL2. |
178
+ | `mol2_atom_charges` | Partial charges parsed from MOL2. |
179
+ | `mol2_atom_count` | Number of MOL2 atoms. |
180
+ | `mol2_bond_count` | Number of MOL2 bonds. |
181
+ | `mol2_total_partial_charge` | Sum of MOL2 partial charges. |
182
+ | `charmm_residue_name` | Residue name parsed from CHARMM `RESI`. |
183
+ | `charmm_residue_charge` | Residue charge parsed from CHARMM `RESI`. |
184
+ | `charmm_residue_comment` | Comment attached to the CHARMM `RESI` line. |
185
+ | `charmm_atom_names` | Atom names from CHARMM topology. |
186
+ | `charmm_atom_types` | Atom types from CHARMM topology. |
187
+ | `charmm_atom_charges` | Atom charges from CHARMM topology. |
188
+ | `charmm_atom_count` | Number of CHARMM atoms. |
189
+ | `charmm_bond_count` | Number of CHARMM bond pairs. |
190
+ | `gromacs_residue_name` | Residue name from GROMACS RTP. |
191
+ | `gromacs_residue_comment` | Comment attached to the GROMACS residue header. |
192
+ | `gromacs_atom_names` | Atom names from GROMACS RTP. |
193
+ | `gromacs_atom_types` | Atom types from GROMACS RTP. |
194
+ | `gromacs_atom_charges` | Atom charges from GROMACS RTP. |
195
+ | `gromacs_atom_count` | Number of GROMACS RTP atoms. |
196
+ | `gromacs_bond_count` | Number of GROMACS RTP bonds. |
197
+ | `gromacs_improper_count` | Number of GROMACS RTP impropers. |
198
+ | `hdb_rule_count` | Number of hydrogen database rules. |
199
+ | `hdb_declared_rule_count` | Rule count declared in the HDB header. |
200
+ | `bbind_rotamer_rows` | Rows in the backbone-independent rotamer library for this residue code. |
201
+ | `bbdep_rotamer_rows` | Rows in the backbone-dependent rotamer library for this residue code. |
202
+ | `split_bucket` | Deterministic split bucket from `sha256(entry_id) % 10`. |
203
+
204
+ ## Preparation
205
+
206
+ The normalization script used to create the Parquet files is included at `scripts/prepare_swisssidechain_dataset.py`.
data/test-00000-of-00001.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1c74a19da06f19a4a44cf02d4fe1d088c863fcb9b5d90ad9ee6012181c516556
3
+ size 60683
data/train-00000-of-00001.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6895a385691791b6c69ae8ea888c356b7f5bad7c44c4214e672dd174f294ab8c
3
+ size 133936
dataset_summary.json ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "source": "LiteFold/SwissSidechain",
3
+ "entry_rows": 459,
4
+ "splits": {
5
+ "train": 400,
6
+ "test": 59
7
+ },
8
+ "split_strategy": "deterministic sha256(entry_id) % 10; bucket 0 is test, buckets 1-9 are train",
9
+ "stereochemistry_counts": {
10
+ "L": 230,
11
+ "D": 229
12
+ },
13
+ "entries_with_pdb": 459,
14
+ "entries_with_mol2": 459,
15
+ "entries_with_top": 437,
16
+ "entries_with_rtp": 437,
17
+ "entries_with_hdb": 437,
18
+ "entries_with_bundle": 459,
19
+ "entries_with_bbdep_rotamers": 454,
20
+ "entries_with_bbind_rotamers": 453,
21
+ "total_bbdep_rotamer_rows": 15256136,
22
+ "total_bbind_rotamer_rows": 11144,
23
+ "archive_manifest_rows": 12,
24
+ "rotamer_library_count_rows": 907,
25
+ "columns": [
26
+ "entry_id",
27
+ "residue_code",
28
+ "stereochemistry",
29
+ "smiles",
30
+ "smiles_reference_file",
31
+ "source_smi_path",
32
+ "source_pdb_path",
33
+ "source_mol2_path",
34
+ "source_top_path",
35
+ "source_rtp_path",
36
+ "source_hdb_path",
37
+ "has_smi",
38
+ "has_pdb",
39
+ "has_mol2",
40
+ "has_top",
41
+ "has_rtp",
42
+ "has_hdb",
43
+ "has_bundle",
44
+ "has_png",
45
+ "has_bundle_bbdep_lib",
46
+ "has_bundle_bbind_lib",
47
+ "bundle_file_extensions",
48
+ "pdb_residue_names",
49
+ "pdb_atom_names",
50
+ "pdb_elements",
51
+ "pdb_atom_count",
52
+ "pdb_heavy_atom_count",
53
+ "pdb_hydrogen_atom_count",
54
+ "mol2_molecule_name",
55
+ "mol2_molecule_type",
56
+ "mol2_charge_type",
57
+ "mol2_atom_names",
58
+ "mol2_atom_types",
59
+ "mol2_atom_charges",
60
+ "mol2_atom_count",
61
+ "mol2_bond_count",
62
+ "mol2_total_partial_charge",
63
+ "charmm_residue_name",
64
+ "charmm_residue_charge",
65
+ "charmm_residue_comment",
66
+ "charmm_atom_names",
67
+ "charmm_atom_types",
68
+ "charmm_atom_charges",
69
+ "charmm_atom_count",
70
+ "charmm_bond_count",
71
+ "gromacs_residue_name",
72
+ "gromacs_residue_comment",
73
+ "gromacs_atom_names",
74
+ "gromacs_atom_types",
75
+ "gromacs_atom_charges",
76
+ "gromacs_atom_count",
77
+ "gromacs_bond_count",
78
+ "gromacs_improper_count",
79
+ "hdb_rule_count",
80
+ "hdb_declared_rule_count",
81
+ "bbind_rotamer_rows",
82
+ "bbdep_rotamer_rows",
83
+ "split_bucket"
84
+ ],
85
+ "source_files_used": [
86
+ "D_MOL2.zip",
87
+ "D_PDB.zip",
88
+ "D_SMI.zip",
89
+ "D_bbdep_Gfeller.lib.zip",
90
+ "D_bbind_Gfeller.lib.zip",
91
+ "D_residues.zip",
92
+ "D_rtp.zip",
93
+ "D_top.zip",
94
+ "L_MOL2.zip",
95
+ "L_PDB.zip",
96
+ "L_SMI.zip",
97
+ "L_bbdep_Gfeller.lib.zip",
98
+ "L_bbind_Gfeller.lib.zip",
99
+ "L_rtp.zip",
100
+ "L_sidechain.zip",
101
+ "L_top.zip"
102
+ ]
103
+ }
metadata/archive_manifest.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b4360169d42d19aef8ae7d8cfbafd5ed8b43e6ec3312474142e945b5db5c420f
3
+ size 6836
metadata/rotamer_library_counts.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:63a956fbb355e37b3670fe437f0f39ac88700e190bf30205db975568e88fac6f
3
+ size 5981
scripts/prepare_swisssidechain_dataset.py ADDED
@@ -0,0 +1,519 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Build viewer-friendly Parquet splits for LiteFold/SwissSidechain."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+ import hashlib
8
+ import json
9
+ import re
10
+ import shutil
11
+ import zipfile
12
+ from collections import Counter, defaultdict
13
+ from pathlib import Path
14
+ from typing import Any
15
+
16
+ import pandas as pd
17
+
18
+
19
+ ENTRY_COLUMNS = [
20
+ "entry_id",
21
+ "residue_code",
22
+ "stereochemistry",
23
+ "smiles",
24
+ "smiles_reference_file",
25
+ "source_smi_path",
26
+ "source_pdb_path",
27
+ "source_mol2_path",
28
+ "source_top_path",
29
+ "source_rtp_path",
30
+ "source_hdb_path",
31
+ "has_smi",
32
+ "has_pdb",
33
+ "has_mol2",
34
+ "has_top",
35
+ "has_rtp",
36
+ "has_hdb",
37
+ "has_bundle",
38
+ "has_png",
39
+ "has_bundle_bbdep_lib",
40
+ "has_bundle_bbind_lib",
41
+ "bundle_file_extensions",
42
+ "pdb_residue_names",
43
+ "pdb_atom_names",
44
+ "pdb_elements",
45
+ "pdb_atom_count",
46
+ "pdb_heavy_atom_count",
47
+ "pdb_hydrogen_atom_count",
48
+ "mol2_molecule_name",
49
+ "mol2_molecule_type",
50
+ "mol2_charge_type",
51
+ "mol2_atom_names",
52
+ "mol2_atom_types",
53
+ "mol2_atom_charges",
54
+ "mol2_atom_count",
55
+ "mol2_bond_count",
56
+ "mol2_total_partial_charge",
57
+ "charmm_residue_name",
58
+ "charmm_residue_charge",
59
+ "charmm_residue_comment",
60
+ "charmm_atom_names",
61
+ "charmm_atom_types",
62
+ "charmm_atom_charges",
63
+ "charmm_atom_count",
64
+ "charmm_bond_count",
65
+ "gromacs_residue_name",
66
+ "gromacs_residue_comment",
67
+ "gromacs_atom_names",
68
+ "gromacs_atom_types",
69
+ "gromacs_atom_charges",
70
+ "gromacs_atom_count",
71
+ "gromacs_bond_count",
72
+ "gromacs_improper_count",
73
+ "hdb_rule_count",
74
+ "hdb_declared_rule_count",
75
+ "bbind_rotamer_rows",
76
+ "bbdep_rotamer_rows",
77
+ "split_bucket",
78
+ ]
79
+
80
+
81
+ def stable_bucket(value: str, buckets: int = 10) -> int:
82
+ digest = hashlib.sha256(value.encode("utf-8")).hexdigest()[:16]
83
+ return int(digest, 16) % buckets
84
+
85
+
86
+ def parse_float(value: str | None) -> float | None:
87
+ if value is None:
88
+ return None
89
+ try:
90
+ return float(value)
91
+ except ValueError:
92
+ return None
93
+
94
+
95
+ def is_canonical_zip_path(name: str, expected_prefix: str) -> bool:
96
+ parts = Path(name).parts
97
+ return len(parts) >= 2 and parts[0] == expected_prefix
98
+
99
+
100
+ def read_zip_text_by_stem(path: Path, expected_prefix: str, suffixes: tuple[str, ...]) -> dict[str, dict[str, str]]:
101
+ items: dict[str, dict[str, str]] = {}
102
+ with zipfile.ZipFile(path) as zf:
103
+ for name in zf.namelist():
104
+ if name.endswith("/") or not name.lower().endswith(suffixes):
105
+ continue
106
+ stem = Path(name).stem
107
+ text = zf.read(name).decode("utf-8", errors="replace")
108
+ existing = items.get(stem)
109
+ if existing is None or (
110
+ is_canonical_zip_path(name, expected_prefix) and not is_canonical_zip_path(existing["path"], expected_prefix)
111
+ ):
112
+ items[stem] = {"path": name, "text": text}
113
+ return items
114
+
115
+
116
+ def read_rtp_hdb_zip(path: Path, expected_prefix: str) -> tuple[dict[str, dict[str, str]], dict[str, dict[str, str]]]:
117
+ rtp: dict[str, dict[str, str]] = {}
118
+ hdb: dict[str, dict[str, str]] = {}
119
+ with zipfile.ZipFile(path) as zf:
120
+ for name in zf.namelist():
121
+ if name.endswith("/"):
122
+ continue
123
+ stem = Path(name).stem
124
+ suffix = Path(name).suffix.lower()
125
+ target = rtp if suffix == ".rtp" else hdb if suffix == ".hdb" else None
126
+ if target is None:
127
+ continue
128
+ text = zf.read(name).decode("utf-8", errors="replace")
129
+ existing = target.get(stem)
130
+ if existing is None or (
131
+ is_canonical_zip_path(name, expected_prefix) and not is_canonical_zip_path(existing["path"], expected_prefix)
132
+ ):
133
+ target[stem] = {"path": name, "text": text}
134
+ return rtp, hdb
135
+
136
+
137
+ def parse_smi(text: str) -> tuple[str | None, str | None]:
138
+ for line in text.splitlines():
139
+ stripped = line.strip()
140
+ if not stripped:
141
+ continue
142
+ parts = stripped.split()
143
+ return parts[0], parts[1] if len(parts) > 1 else None
144
+ return None, None
145
+
146
+
147
+ def parse_pdb(text: str) -> dict[str, Any]:
148
+ atom_names: list[str] = []
149
+ elements: list[str] = []
150
+ residue_names: set[str] = set()
151
+ for line in text.splitlines():
152
+ if not (line.startswith("ATOM") or line.startswith("HETATM")):
153
+ continue
154
+ atom_name = line[12:16].strip()
155
+ residue_name = line[17:20].strip()
156
+ element = line[76:78].strip() if len(line) >= 78 else ""
157
+ if not element:
158
+ element = re.sub(r"[^A-Za-z]", "", atom_name)[:1]
159
+ if atom_name:
160
+ atom_names.append(atom_name)
161
+ if residue_name:
162
+ residue_names.add(residue_name)
163
+ if element:
164
+ elements.append(element.upper())
165
+ return {
166
+ "pdb_residue_names": sorted(residue_names),
167
+ "pdb_atom_names": atom_names,
168
+ "pdb_elements": elements,
169
+ "pdb_atom_count": len(atom_names),
170
+ "pdb_heavy_atom_count": sum(1 for element in elements if element != "H"),
171
+ "pdb_hydrogen_atom_count": sum(1 for element in elements if element == "H"),
172
+ }
173
+
174
+
175
+ def parse_mol2(text: str) -> dict[str, Any]:
176
+ section: str | None = None
177
+ molecule_lines: list[str] = []
178
+ atom_names: list[str] = []
179
+ atom_types: list[str] = []
180
+ charges: list[float] = []
181
+ bond_count = 0
182
+ for raw in text.splitlines():
183
+ line = raw.rstrip()
184
+ if line.startswith("@<TRIPOS>"):
185
+ section = line.removeprefix("@<TRIPOS>").strip()
186
+ continue
187
+ if not line.strip():
188
+ continue
189
+ if section == "MOLECULE":
190
+ molecule_lines.append(line.strip())
191
+ elif section == "ATOM":
192
+ parts = line.split()
193
+ if len(parts) >= 6:
194
+ atom_names.append(parts[1])
195
+ atom_types.append(parts[5])
196
+ if len(parts) >= 9:
197
+ charge = parse_float(parts[8])
198
+ if charge is not None:
199
+ charges.append(charge)
200
+ elif section == "BOND":
201
+ parts = line.split()
202
+ if len(parts) >= 4:
203
+ bond_count += 1
204
+
205
+ counts = molecule_lines[1].split() if len(molecule_lines) > 1 else []
206
+ declared_bonds = int(counts[1]) if len(counts) > 1 and counts[1].isdigit() else bond_count
207
+ return {
208
+ "mol2_molecule_name": molecule_lines[0] if molecule_lines else None,
209
+ "mol2_molecule_type": molecule_lines[2] if len(molecule_lines) > 2 else None,
210
+ "mol2_charge_type": molecule_lines[3] if len(molecule_lines) > 3 else None,
211
+ "mol2_atom_names": atom_names,
212
+ "mol2_atom_types": atom_types,
213
+ "mol2_atom_charges": charges,
214
+ "mol2_atom_count": len(atom_names),
215
+ "mol2_bond_count": declared_bonds,
216
+ "mol2_total_partial_charge": round(sum(charges), 6) if charges else None,
217
+ }
218
+
219
+
220
+ def parse_charmm_top(text: str) -> dict[str, Any]:
221
+ residue_name = None
222
+ residue_charge = None
223
+ residue_comment = None
224
+ atom_names: list[str] = []
225
+ atom_types: list[str] = []
226
+ atom_charges: list[float] = []
227
+ bond_count = 0
228
+ for raw in text.splitlines():
229
+ line = raw.strip()
230
+ if not line or line.startswith("!"):
231
+ continue
232
+ data, _, comment = line.partition("!")
233
+ parts = data.split()
234
+ if not parts:
235
+ continue
236
+ keyword = parts[0].upper()
237
+ if keyword == "RESI" and len(parts) >= 3:
238
+ residue_name = parts[1]
239
+ residue_charge = parse_float(parts[2])
240
+ residue_comment = comment.strip() or None
241
+ elif keyword == "ATOM" and len(parts) >= 4:
242
+ atom_names.append(parts[1])
243
+ atom_types.append(parts[2])
244
+ charge = parse_float(parts[3])
245
+ if charge is not None:
246
+ atom_charges.append(charge)
247
+ elif keyword in {"BOND", "DOUBLE"}:
248
+ bond_count += len(parts[1:]) // 2
249
+ return {
250
+ "charmm_residue_name": residue_name,
251
+ "charmm_residue_charge": residue_charge,
252
+ "charmm_residue_comment": residue_comment,
253
+ "charmm_atom_names": atom_names,
254
+ "charmm_atom_types": atom_types,
255
+ "charmm_atom_charges": atom_charges,
256
+ "charmm_atom_count": len(atom_names),
257
+ "charmm_bond_count": bond_count,
258
+ }
259
+
260
+
261
+ def parse_gromacs_rtp(text: str) -> dict[str, Any]:
262
+ residue_name = None
263
+ residue_comment = None
264
+ section = None
265
+ atom_names: list[str] = []
266
+ atom_types: list[str] = []
267
+ atom_charges: list[float] = []
268
+ bond_count = 0
269
+ improper_count = 0
270
+ for raw in text.splitlines():
271
+ line = raw.strip()
272
+ if not line or line.startswith(";"):
273
+ continue
274
+ data, _, comment = line.partition(";")
275
+ data = data.strip()
276
+ if data.startswith("[") and data.endswith("]"):
277
+ label = data.strip("[]").strip()
278
+ if residue_name is None and label not in {"atoms", "bonds", "impropers", "cmap"}:
279
+ residue_name = label
280
+ residue_comment = comment.strip() or None
281
+ section = None
282
+ else:
283
+ section = label.lower()
284
+ continue
285
+ parts = data.split()
286
+ if section == "atoms" and len(parts) >= 3:
287
+ atom_names.append(parts[0])
288
+ atom_types.append(parts[1])
289
+ charge = parse_float(parts[2])
290
+ if charge is not None:
291
+ atom_charges.append(charge)
292
+ elif section == "bonds" and len(parts) >= 2:
293
+ bond_count += 1
294
+ elif section == "impropers" and len(parts) >= 4:
295
+ improper_count += 1
296
+ return {
297
+ "gromacs_residue_name": residue_name,
298
+ "gromacs_residue_comment": residue_comment,
299
+ "gromacs_atom_names": atom_names,
300
+ "gromacs_atom_types": atom_types,
301
+ "gromacs_atom_charges": atom_charges,
302
+ "gromacs_atom_count": len(atom_names),
303
+ "gromacs_bond_count": bond_count,
304
+ "gromacs_improper_count": improper_count,
305
+ }
306
+
307
+
308
+ def parse_hdb(text: str) -> dict[str, Any]:
309
+ lines = [line.strip() for line in text.splitlines() if line.strip() and not line.strip().startswith(";")]
310
+ declared = None
311
+ if lines:
312
+ parts = lines[0].split()
313
+ if len(parts) >= 2:
314
+ try:
315
+ declared = int(parts[1])
316
+ except ValueError:
317
+ declared = None
318
+ return {
319
+ "hdb_rule_count": max(len(lines) - 1, 0),
320
+ "hdb_declared_rule_count": declared,
321
+ }
322
+
323
+
324
+ def archive_bundle_manifest(path: Path, stereochemistry: str) -> dict[str, dict[str, Any]]:
325
+ manifest: dict[str, dict[str, Any]] = defaultdict(lambda: {"extensions": Counter(), "paths": []})
326
+ with zipfile.ZipFile(path) as zf:
327
+ for name in zf.namelist():
328
+ if name.endswith("/"):
329
+ continue
330
+ parts = Path(name).parts
331
+ if len(parts) < 2:
332
+ continue
333
+ residue_code = parts[-2]
334
+ suffix = Path(name).suffix.lower() or "<none>"
335
+ manifest[residue_code]["extensions"][suffix] += 1
336
+ manifest[residue_code]["paths"].append(name)
337
+ result = {}
338
+ for residue_code, item in manifest.items():
339
+ extensions = item["extensions"]
340
+ result[residue_code] = {
341
+ "bundle_file_extensions": sorted(extensions),
342
+ "has_png": extensions.get(".png", 0) > 0,
343
+ "has_bundle_bbdep_lib": any(path.endswith("_bbdep_Gfeller.lib.zip") for path in item["paths"]),
344
+ "has_bundle_bbind_lib": any(path.endswith("_bbind_Gfeller.lib.zip") for path in item["paths"]),
345
+ "stereochemistry": stereochemistry,
346
+ }
347
+ return result
348
+
349
+
350
+ def parse_rotamer_counts(path: Path, stereochemistry: str, library_type: str) -> tuple[dict[str, int], list[dict[str, Any]]]:
351
+ counts: Counter[str] = Counter()
352
+ with zipfile.ZipFile(path) as zf:
353
+ name = next(n for n in zf.namelist() if n.endswith(".lib"))
354
+ with zf.open(name) as handle:
355
+ for raw in handle:
356
+ line = raw.decode("utf-8", errors="replace").strip()
357
+ if not line or line.startswith("#"):
358
+ continue
359
+ counts[line.split()[0]] += 1
360
+ rows = [
361
+ {
362
+ "stereochemistry": stereochemistry,
363
+ "library_type": library_type,
364
+ "residue_code": residue_code,
365
+ "row_count": int(row_count),
366
+ }
367
+ for residue_code, row_count in sorted(counts.items())
368
+ ]
369
+ return dict(counts), rows
370
+
371
+
372
+ def build_rows_for_stereo(raw_dir: Path, stereochemistry: str) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]:
373
+ prefix = "L" if stereochemistry == "L" else "D"
374
+ smi = read_zip_text_by_stem(raw_dir / f"{prefix}_SMI.zip", f"{prefix}_SMI", (".smi",))
375
+ pdb = read_zip_text_by_stem(raw_dir / f"{prefix}_PDB.zip", f"{prefix}_PDB", (".pdb",))
376
+ mol2 = read_zip_text_by_stem(raw_dir / f"{prefix}_MOL2.zip", f"{prefix}_MOL2", (".mol2",))
377
+ top = read_zip_text_by_stem(raw_dir / f"{prefix}_top.zip", f"{prefix}_top", (".top",))
378
+ rtp, hdb = read_rtp_hdb_zip(raw_dir / f"{prefix}_rtp.zip", f"{prefix}_rtp")
379
+ bundle = archive_bundle_manifest(
380
+ raw_dir / ("L_sidechain.zip" if stereochemistry == "L" else "D_residues.zip"),
381
+ stereochemistry=stereochemistry,
382
+ )
383
+ bbind_counts, bbind_rows = parse_rotamer_counts(
384
+ raw_dir / f"{prefix}_bbind_Gfeller.lib.zip",
385
+ stereochemistry=stereochemistry,
386
+ library_type="bbind",
387
+ )
388
+ bbdep_counts, bbdep_rows = parse_rotamer_counts(
389
+ raw_dir / f"{prefix}_bbdep_Gfeller.lib.zip",
390
+ stereochemistry=stereochemistry,
391
+ library_type="bbdep",
392
+ )
393
+
394
+ rows: list[dict[str, Any]] = []
395
+ for residue_code in sorted(smi):
396
+ smiles, reference_file = parse_smi(smi[residue_code]["text"])
397
+ entry_id = f"{stereochemistry}:{residue_code}"
398
+ row = {
399
+ "entry_id": entry_id,
400
+ "residue_code": residue_code,
401
+ "stereochemistry": stereochemistry,
402
+ "smiles": smiles,
403
+ "smiles_reference_file": reference_file,
404
+ "source_smi_path": smi[residue_code]["path"],
405
+ "source_pdb_path": pdb.get(residue_code, {}).get("path"),
406
+ "source_mol2_path": mol2.get(residue_code, {}).get("path"),
407
+ "source_top_path": top.get(residue_code, {}).get("path"),
408
+ "source_rtp_path": rtp.get(residue_code, {}).get("path"),
409
+ "source_hdb_path": hdb.get(residue_code, {}).get("path"),
410
+ "has_smi": True,
411
+ "has_pdb": residue_code in pdb,
412
+ "has_mol2": residue_code in mol2,
413
+ "has_top": residue_code in top,
414
+ "has_rtp": residue_code in rtp,
415
+ "has_hdb": residue_code in hdb,
416
+ "has_bundle": residue_code in bundle,
417
+ "has_png": bool(bundle.get(residue_code, {}).get("has_png", False)),
418
+ "has_bundle_bbdep_lib": bool(bundle.get(residue_code, {}).get("has_bundle_bbdep_lib", False)),
419
+ "has_bundle_bbind_lib": bool(bundle.get(residue_code, {}).get("has_bundle_bbind_lib", False)),
420
+ "bundle_file_extensions": bundle.get(residue_code, {}).get("bundle_file_extensions", []),
421
+ "bbind_rotamer_rows": int(bbind_counts.get(residue_code, 0)),
422
+ "bbdep_rotamer_rows": int(bbdep_counts.get(residue_code, 0)),
423
+ "split_bucket": stable_bucket(entry_id),
424
+ }
425
+ row.update(parse_pdb(pdb[residue_code]["text"]) if residue_code in pdb else parse_pdb(""))
426
+ row.update(parse_mol2(mol2[residue_code]["text"]) if residue_code in mol2 else parse_mol2(""))
427
+ row.update(parse_charmm_top(top[residue_code]["text"]) if residue_code in top else parse_charmm_top(""))
428
+ row.update(parse_gromacs_rtp(rtp[residue_code]["text"]) if residue_code in rtp else parse_gromacs_rtp(""))
429
+ row.update(parse_hdb(hdb[residue_code]["text"]) if residue_code in hdb else parse_hdb(""))
430
+ rows.append(row)
431
+
432
+ manifest_rows = []
433
+ for label, mapping in [
434
+ ("SMI", smi),
435
+ ("PDB", pdb),
436
+ ("MOL2", mol2),
437
+ ("top", top),
438
+ ("rtp", rtp),
439
+ ("hdb", hdb),
440
+ ]:
441
+ manifest_rows.append(
442
+ {
443
+ "stereochemistry": stereochemistry,
444
+ "archive_kind": label,
445
+ "unique_residue_codes": len(mapping),
446
+ "residue_codes": sorted(mapping),
447
+ }
448
+ )
449
+ return rows, bbind_rows + bbdep_rows + manifest_rows
450
+
451
+
452
+ def build_dataset(raw_dir: Path, out_dir: Path) -> dict[str, Any]:
453
+ l_rows, l_metadata = build_rows_for_stereo(raw_dir, "L")
454
+ d_rows, d_metadata = build_rows_for_stereo(raw_dir, "D")
455
+ rows = l_rows + d_rows
456
+
457
+ if out_dir.exists():
458
+ shutil.rmtree(out_dir)
459
+ data_dir = out_dir / "data"
460
+ metadata_dir = out_dir / "metadata"
461
+ data_dir.mkdir(parents=True, exist_ok=True)
462
+ metadata_dir.mkdir(parents=True, exist_ok=True)
463
+
464
+ df = pd.DataFrame.from_records(rows, columns=ENTRY_COLUMNS)
465
+ df = df.sort_values(["split_bucket", "entry_id"], kind="mergesort")
466
+ train = df[df["split_bucket"].ne(0)].sort_values("entry_id", kind="mergesort")
467
+ test = df[df["split_bucket"].eq(0)].sort_values("entry_id", kind="mergesort")
468
+ train.to_parquet(data_dir / "train-00000-of-00001.parquet", index=False, compression="zstd")
469
+ test.to_parquet(data_dir / "test-00000-of-00001.parquet", index=False, compression="zstd")
470
+
471
+ rotamer_rows = [row for row in l_metadata + d_metadata if row.get("library_type")]
472
+ manifest_rows = [row for row in l_metadata + d_metadata if row.get("archive_kind")]
473
+ pd.DataFrame.from_records(rotamer_rows).to_parquet(
474
+ metadata_dir / "rotamer_library_counts.parquet", index=False, compression="zstd"
475
+ )
476
+ pd.DataFrame.from_records(manifest_rows).to_parquet(
477
+ metadata_dir / "archive_manifest.parquet", index=False, compression="zstd"
478
+ )
479
+
480
+ stereo_counts = df["stereochemistry"].value_counts().to_dict()
481
+ summary = {
482
+ "source": "LiteFold/SwissSidechain",
483
+ "entry_rows": int(len(df)),
484
+ "splits": {
485
+ "train": int(len(train)),
486
+ "test": int(len(test)),
487
+ },
488
+ "split_strategy": "deterministic sha256(entry_id) % 10; bucket 0 is test, buckets 1-9 are train",
489
+ "stereochemistry_counts": {str(k): int(v) for k, v in stereo_counts.items()},
490
+ "entries_with_pdb": int(df["has_pdb"].sum()),
491
+ "entries_with_mol2": int(df["has_mol2"].sum()),
492
+ "entries_with_top": int(df["has_top"].sum()),
493
+ "entries_with_rtp": int(df["has_rtp"].sum()),
494
+ "entries_with_hdb": int(df["has_hdb"].sum()),
495
+ "entries_with_bundle": int(df["has_bundle"].sum()),
496
+ "entries_with_bbdep_rotamers": int(df["bbdep_rotamer_rows"].gt(0).sum()),
497
+ "entries_with_bbind_rotamers": int(df["bbind_rotamer_rows"].gt(0).sum()),
498
+ "total_bbdep_rotamer_rows": int(df["bbdep_rotamer_rows"].sum()),
499
+ "total_bbind_rotamer_rows": int(df["bbind_rotamer_rows"].sum()),
500
+ "archive_manifest_rows": int(len(manifest_rows)),
501
+ "rotamer_library_count_rows": int(len(rotamer_rows)),
502
+ "columns": ENTRY_COLUMNS,
503
+ "source_files_used": sorted(path.name for path in raw_dir.glob("*.zip")),
504
+ }
505
+ (out_dir / "dataset_summary.json").write_text(json.dumps(summary, indent=2) + "\n", encoding="utf-8")
506
+ return summary
507
+
508
+
509
+ def main() -> None:
510
+ parser = argparse.ArgumentParser()
511
+ parser.add_argument("--raw-dir", type=Path, default=Path("LiteFold_SwissSidechain_raw"))
512
+ parser.add_argument("--out-dir", type=Path, default=Path("LiteFold_SwissSidechain_processed"))
513
+ args = parser.parse_args()
514
+ summary = build_dataset(args.raw_dir, args.out_dir)
515
+ print(json.dumps(summary, indent=2))
516
+
517
+
518
+ if __name__ == "__main__":
519
+ main()