anindya64 commited on
Commit
fb0a48b
·
verified ·
1 Parent(s): 23f91a9

Add normalized Parquet train/test mmCIF index

Browse files
README.md ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ pretty_name: PDB mmCIF Entry Index
3
+ license: cc0-1.0
4
+ tags:
5
+ - biology
6
+ - proteins
7
+ - protein-structure
8
+ - pdb
9
+ - rcsb
10
+ - mmcif
11
+ - parquet
12
+ configs:
13
+ - config_name: default
14
+ data_files:
15
+ - split: train
16
+ path: data/train-*.parquet
17
+ - split: test
18
+ path: data/test-*.parquet
19
+ ---
20
+
21
+ # PDB mmCIF Entry Index
22
+
23
+ This repository contains mirrored Protein Data Bank mmCIF files under `mmcif/` plus the PDB `entries.idx` index. The added Parquet files make the mirrored entries loadable in the Hugging Face Dataset Viewer and the `datasets` API.
24
+
25
+ The default dataset table has one row per mmCIF file present in this repository. Rows are joined with matching metadata from `entries.idx`, including classification, accession date, title, source organism, author list, resolution, and experimental method.
26
+
27
+ ## Splits
28
+
29
+ | Split | Rows |
30
+ |---|---:|
31
+ | train | 88,873 |
32
+ | test | 9,951 |
33
+ | total | 98,824 |
34
+
35
+ The split is deterministic: `sha256(pdb_id) % 10 == 0` goes to `test`; buckets `1` through `9` go to `train`.
36
+
37
+ ## Dataset Statistics
38
+
39
+ | Metric | Value |
40
+ |---|---:|
41
+ | mmCIF files in this repo | 98,824 |
42
+ | Rows joined to `entries.idx` metadata | 98,824 |
43
+ | Full `entries.idx` rows | 252,816 |
44
+ | Total mirrored mmCIF compressed size | 31.08 GB |
45
+ | Known-resolution rows | 93,997 |
46
+ | Unknown-resolution rows | 4,827 |
47
+ | Median known resolution | 2.10 A |
48
+ | Mean known resolution | 2.33 A |
49
+
50
+ Top experimental methods:
51
+
52
+ | Method | Rows |
53
+ |---|---:|
54
+ | X-RAY DIFFRACTION | 82,380 |
55
+ | ELECTRON MICROSCOPY | 11,433 |
56
+ | SOLUTION NMR | 4,707 |
57
+ | ELECTRON CRYSTALLOGRAPHY | 101 |
58
+ | X-RAY DIFFRACTION, NEUTRON DIFFRACTION | 50 |
59
+
60
+ Top classifications:
61
+
62
+ | Classification | Rows |
63
+ |---|---:|
64
+ | HYDROLASE | 14,117 |
65
+ | TRANSFERASE | 9,970 |
66
+ | OXIDOREDUCTASE | 7,743 |
67
+ | VIRAL PROTEIN | 4,333 |
68
+ | MEMBRANE PROTEIN | 3,206 |
69
+
70
+ ## Load With `datasets`
71
+
72
+ ```python
73
+ from datasets import load_dataset
74
+
75
+ ds = load_dataset("LiteFold/PDB")
76
+ print(ds)
77
+
78
+ row = ds["train"][0]
79
+ print(row)
80
+ ```
81
+
82
+ Load one split directly:
83
+
84
+ ```python
85
+ from datasets import load_dataset
86
+
87
+ train = load_dataset("LiteFold/PDB", split="train")
88
+ test = load_dataset("LiteFold/PDB", split="test")
89
+ ```
90
+
91
+ Stream rows without materializing the full table locally:
92
+
93
+ ```python
94
+ from datasets import load_dataset
95
+
96
+ streamed = load_dataset("LiteFold/PDB", split="train", streaming=True)
97
+ first_row = next(iter(streamed))
98
+ ```
99
+
100
+ Use the `mmcif_path` column with `hf_hub_download` to fetch a structure file:
101
+
102
+ ```python
103
+ from datasets import load_dataset
104
+ from huggingface_hub import hf_hub_download
105
+
106
+ row = load_dataset("LiteFold/PDB", split="train[0]")[0]
107
+ local_path = hf_hub_download(
108
+ repo_id="LiteFold/PDB",
109
+ repo_type="dataset",
110
+ filename=row["mmcif_path"],
111
+ )
112
+ ```
113
+
114
+ Filter to X-ray structures with known resolution:
115
+
116
+ ```python
117
+ from datasets import load_dataset
118
+
119
+ train = load_dataset("LiteFold/PDB", split="train")
120
+ xray = train.filter(
121
+ lambda row: row["experimental_method"] == "X-RAY DIFFRACTION"
122
+ and not row["resolution_is_unknown"]
123
+ )
124
+ ```
125
+
126
+ ## Columns
127
+
128
+ | Column | Description |
129
+ |---|---|
130
+ | `pdb_id` | Four-character PDB identifier in lowercase. |
131
+ | `mmcif_path` | Path to the mirrored gzipped mmCIF file in this repository. |
132
+ | `mmcif_file_size_bytes` | Compressed mmCIF file size from Hugging Face Hub file metadata. |
133
+ | `mmcif_blob_id` | Hub blob identifier for the mmCIF object. |
134
+ | `pdb_url` | RCSB PDB structure page URL. |
135
+ | `rcsb_download_url` | Direct RCSB mmCIF download URL. |
136
+ | `classification` | PDB header classification. |
137
+ | `accession_date` | Original `entries.idx` accession date string. |
138
+ | `accession_date_iso` | Parsed ISO date when available. |
139
+ | `title` | Structure title from `entries.idx`. |
140
+ | `source_organism` | Source organism field from `entries.idx`. |
141
+ | `authors` | Author list from `entries.idx`. |
142
+ | `raw_resolution` | Original resolution field from `entries.idx`. |
143
+ | `resolution_angstrom` | Numeric resolution in Angstroms, nullable for non-numeric values such as `NOT`. |
144
+ | `resolution_is_unknown` | Whether `resolution_angstrom` is null. |
145
+ | `experimental_method` | Experimental method field from `entries.idx`. |
146
+ | `has_entries_idx_metadata` | Whether the mmCIF file matched a row in `entries.idx`. |
147
+ | `split_bucket` | Deterministic hash bucket; bucket 0 is test. |
148
+
149
+ ## Source Files Used
150
+
151
+ - `entries.idx`
152
+ - Hub file metadata for paths under `mmcif/**/*.cif.gz`
153
+
154
+ The full parsed `entries.idx` table is also included as `metadata/entries_idx.parquet`. The preparation script is included at `scripts/prepare_pdb_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:76872f95cd05e29c6b8db16dcdea43e1812b22a616f293156bddbc71ca8b9cc8
3
+ size 1183585
data/train-00000-of-00001.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:031ab8fc3a3f1d632cf72ee13d52e18f8e51b3b69f711cf10fdfdb12f23b3210
3
+ size 7506645
dataset_summary.json ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "source": "LiteFold/PDB",
3
+ "full_entries_idx_rows": 252816,
4
+ "mmcif_rows_in_repo": 98824,
5
+ "metadata_joined_rows": 98824,
6
+ "splits": {
7
+ "train": 88873,
8
+ "test": 9951
9
+ },
10
+ "split_strategy": "deterministic sha256(pdb_id) % 10; bucket 0 is test, buckets 1-9 are train",
11
+ "total_mmcif_size_bytes": 31077163473,
12
+ "resolution": {
13
+ "known_rows": 93997,
14
+ "unknown_rows": 4827,
15
+ "min": 0.0,
16
+ "median": 2.1,
17
+ "mean": 2.3307838436333053,
18
+ "max": 50.0
19
+ },
20
+ "top_experimental_methods": {
21
+ "X-RAY DIFFRACTION": 82380,
22
+ "ELECTRON MICROSCOPY": 11433,
23
+ "SOLUTION NMR": 4707,
24
+ "ELECTRON CRYSTALLOGRAPHY": 101,
25
+ "X-RAY DIFFRACTION, NEUTRON DIFFRACTION": 50,
26
+ "SOLID-STATE NMR": 37,
27
+ "NEUTRON DIFFRACTION": 29,
28
+ "FIBER DIFFRACTION": 28,
29
+ "SOLUTION SCATTERING": 16,
30
+ "POWDER DIFFRACTION": 12,
31
+ "SOLUTION NMR, SOLUTION SCATTERING": 7,
32
+ "NEUTRON DIFFRACTION, X-RAY DIFFRACTION": 6,
33
+ "X-RAY DIFFRACTION, SOLUTION SCATTERING": 4,
34
+ "SOLUTION NMR, THEORETICAL MODEL": 4,
35
+ "X-RAY DIFFRACTION, EPR": 3,
36
+ "INFRARED SPECTROSCOPY": 2,
37
+ "X-RAY DIFFRACTION, SOLUTION NMR": 1,
38
+ "SOLID-STATE NMR, SOLUTION SCATTERING, ELECTRON MICROSCOPY": 1,
39
+ "ELECTRON MICROSCOPY, SOLUTION NMR": 1,
40
+ "ELECTRON MICROSCOPY, SOLUTION NMR, SOLID-STATE NMR": 1
41
+ },
42
+ "top_classifications": {
43
+ "HYDROLASE": 14117,
44
+ "TRANSFERASE": 9970,
45
+ "OXIDOREDUCTASE": 7743,
46
+ "VIRAL PROTEIN": 4333,
47
+ "MEMBRANE PROTEIN": 3206,
48
+ "IMMUNE SYSTEM": 2912,
49
+ "TRANSCRIPTION": 2611,
50
+ "LYASE": 2562,
51
+ "TRANSPORT PROTEIN": 2384,
52
+ "SIGNALING PROTEIN": 2367,
53
+ "LIGASE": 1617,
54
+ "ISOMERASE": 1500,
55
+ "DNA BINDING PROTEIN": 1369,
56
+ "STRUCTURAL PROTEIN": 1278,
57
+ "PROTEIN BINDING": 1265,
58
+ "DNA": 1218,
59
+ "HYDROLASE/HYDROLASE INHIBITOR": 1167,
60
+ "METAL BINDING PROTEIN": 1038,
61
+ "SUGAR BINDING PROTEIN": 955,
62
+ "CHAPERONE": 884
63
+ },
64
+ "columns": [
65
+ "pdb_id",
66
+ "mmcif_path",
67
+ "mmcif_file_size_bytes",
68
+ "mmcif_blob_id",
69
+ "pdb_url",
70
+ "rcsb_download_url",
71
+ "classification",
72
+ "accession_date",
73
+ "accession_date_iso",
74
+ "title",
75
+ "source_organism",
76
+ "authors",
77
+ "raw_resolution",
78
+ "resolution_angstrom",
79
+ "resolution_is_unknown",
80
+ "experimental_method",
81
+ "has_entries_idx_metadata",
82
+ "split_bucket"
83
+ ]
84
+ }
metadata/entries_idx.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:275b08dd96248e366203bd94e03f2101642414b0b16f6cbd36d13266c736155e
3
+ size 11586301
scripts/prepare_pdb_dataset.py ADDED
@@ -0,0 +1,211 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Build viewer-friendly Parquet splits for LiteFold/PDB."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+ import hashlib
8
+ import json
9
+ import re
10
+ from datetime import date, datetime
11
+ from pathlib import Path
12
+
13
+ import pandas as pd
14
+ import pyarrow as pa
15
+ import pyarrow.parquet as pq
16
+ from huggingface_hub import HfApi
17
+
18
+
19
+ ENTRY_COLUMNS = [
20
+ "pdb_id",
21
+ "classification",
22
+ "accession_date",
23
+ "title",
24
+ "source_organism",
25
+ "authors",
26
+ "raw_resolution",
27
+ "experimental_method",
28
+ ]
29
+
30
+
31
+ def load_hf_token(env_path: Path) -> str | None:
32
+ if not env_path.exists():
33
+ return None
34
+ for line in env_path.read_text(encoding="utf-8").splitlines():
35
+ line = line.strip()
36
+ if not line or line.startswith("#") or "=" not in line:
37
+ continue
38
+ key, value = line.split("=", 1)
39
+ if key.strip() in {"HF_TOKEN", "HUGGINGFACE_HUB_TOKEN"}:
40
+ return value.strip().strip('"').strip("'")
41
+ return None
42
+
43
+
44
+ def parse_accession_date(value: str, current_year: int) -> str | None:
45
+ value = (value or "").strip()
46
+ if not value:
47
+ return None
48
+ try:
49
+ month, day, year = [int(part) for part in value.split("/")]
50
+ except ValueError:
51
+ return None
52
+
53
+ current_two_digit_year = current_year % 100
54
+ full_year = 2000 + year if year <= current_two_digit_year else 1900 + year
55
+ try:
56
+ return date(full_year, month, day).isoformat()
57
+ except ValueError:
58
+ return None
59
+
60
+
61
+ def parse_entries_idx(path: Path) -> pd.DataFrame:
62
+ rows = []
63
+ current_year = datetime.utcnow().year
64
+ with path.open("r", encoding="utf-8", errors="replace") as handle:
65
+ for line_number, line in enumerate(handle, start=1):
66
+ line = line.rstrip("\n")
67
+ if line_number <= 2 or not line:
68
+ continue
69
+ parts = line.split("\t")
70
+ if len(parts) < len(ENTRY_COLUMNS):
71
+ parts = parts + [""] * (len(ENTRY_COLUMNS) - len(parts))
72
+ elif len(parts) > len(ENTRY_COLUMNS):
73
+ parts = parts[: len(ENTRY_COLUMNS) - 1] + [" ".join(parts[len(ENTRY_COLUMNS) - 1 :])]
74
+ rows.append(dict(zip(ENTRY_COLUMNS, parts)))
75
+
76
+ df = pd.DataFrame.from_records(rows)
77
+ df["pdb_id"] = df["pdb_id"].str.lower()
78
+ df["accession_date_iso"] = df["accession_date"].map(
79
+ lambda value: parse_accession_date(value, current_year)
80
+ )
81
+ df["resolution_angstrom"] = pd.to_numeric(df["raw_resolution"], errors="coerce")
82
+ df["resolution_is_unknown"] = df["resolution_angstrom"].isna()
83
+ for column in ["classification", "title", "source_organism", "authors", "experimental_method"]:
84
+ df[column] = df[column].fillna("").str.strip()
85
+ return df
86
+
87
+
88
+ def mmcif_rows_from_hub(repo_id: str, token: str | None) -> pd.DataFrame:
89
+ api = HfApi(token=token)
90
+ info = api.dataset_info(repo_id, files_metadata=True)
91
+ records = []
92
+ for sibling in info.siblings or []:
93
+ path = sibling.rfilename
94
+ if not path.startswith("mmcif/") or not path.endswith(".cif.gz"):
95
+ continue
96
+ filename = Path(path).name
97
+ pdb_id = filename.removesuffix(".cif.gz").lower()
98
+ records.append(
99
+ {
100
+ "pdb_id": pdb_id,
101
+ "mmcif_path": path,
102
+ "mmcif_file_size_bytes": int(sibling.size) if sibling.size is not None else None,
103
+ "mmcif_blob_id": sibling.blob_id,
104
+ }
105
+ )
106
+ return pd.DataFrame.from_records(records)
107
+
108
+
109
+ def stable_bucket(value: str, buckets: int = 10) -> int:
110
+ digest = hashlib.sha256(value.encode("utf-8")).hexdigest()[:16]
111
+ return int(digest, 16) % buckets
112
+
113
+
114
+ def write_parquet(df: pd.DataFrame, path: Path) -> None:
115
+ path.parent.mkdir(parents=True, exist_ok=True)
116
+ table = pa.Table.from_pandas(df, preserve_index=False)
117
+ pq.write_table(table, path, compression="zstd")
118
+
119
+
120
+ def build_dataset(raw_dir: Path, out_dir: Path, repo_id: str, token: str | None) -> dict:
121
+ entries = parse_entries_idx(raw_dir / "entries.idx")
122
+ mmcif = mmcif_rows_from_hub(repo_id, token)
123
+ if mmcif.empty:
124
+ raise RuntimeError(f"No mmCIF files found in {repo_id}")
125
+
126
+ df = mmcif.merge(entries, on="pdb_id", how="left", validate="one_to_one")
127
+ df["has_entries_idx_metadata"] = df["title"].notna()
128
+ for column in ["classification", "accession_date", "accession_date_iso", "title", "source_organism", "authors", "raw_resolution", "experimental_method"]:
129
+ df[column] = df[column].fillna("")
130
+ df["resolution_angstrom"] = df["resolution_angstrom"].astype("Float64")
131
+ df["resolution_is_unknown"] = df["resolution_angstrom"].isna()
132
+ df["pdb_url"] = "https://www.rcsb.org/structure/" + df["pdb_id"].str.upper()
133
+ df["rcsb_download_url"] = "https://files.rcsb.org/download/" + df["pdb_id"] + ".cif.gz"
134
+ df["split_bucket"] = df["pdb_id"].map(stable_bucket).astype("int64")
135
+ df["split"] = df["split_bucket"].map(lambda bucket: "test" if bucket == 0 else "train")
136
+
137
+ ordered_columns = [
138
+ "pdb_id",
139
+ "mmcif_path",
140
+ "mmcif_file_size_bytes",
141
+ "mmcif_blob_id",
142
+ "pdb_url",
143
+ "rcsb_download_url",
144
+ "classification",
145
+ "accession_date",
146
+ "accession_date_iso",
147
+ "title",
148
+ "source_organism",
149
+ "authors",
150
+ "raw_resolution",
151
+ "resolution_angstrom",
152
+ "resolution_is_unknown",
153
+ "experimental_method",
154
+ "has_entries_idx_metadata",
155
+ "split_bucket",
156
+ ]
157
+ df = df[ordered_columns + ["split"]].sort_values(["split", "pdb_id"], kind="mergesort")
158
+
159
+ data_dir = out_dir / "data"
160
+ for split in ["train", "test"]:
161
+ split_df = df[df["split"].eq(split)].drop(columns=["split"])
162
+ write_parquet(split_df, data_dir / f"{split}-00000-of-00001.parquet")
163
+
164
+ metadata_dir = out_dir / "metadata"
165
+ write_parquet(entries.sort_values("pdb_id", kind="mergesort"), metadata_dir / "entries_idx.parquet")
166
+
167
+ method_counts = (
168
+ df["experimental_method"].replace("", "UNKNOWN").value_counts().head(20).to_dict()
169
+ )
170
+ class_counts = df["classification"].replace("", "UNKNOWN").value_counts().head(20).to_dict()
171
+ summary = {
172
+ "source": repo_id,
173
+ "full_entries_idx_rows": int(len(entries)),
174
+ "mmcif_rows_in_repo": int(len(df)),
175
+ "metadata_joined_rows": int(df["has_entries_idx_metadata"].sum()),
176
+ "splits": {
177
+ "train": int(df["split"].eq("train").sum()),
178
+ "test": int(df["split"].eq("test").sum()),
179
+ },
180
+ "split_strategy": "deterministic sha256(pdb_id) % 10; bucket 0 is test, buckets 1-9 are train",
181
+ "total_mmcif_size_bytes": int(df["mmcif_file_size_bytes"].fillna(0).sum()),
182
+ "resolution": {
183
+ "known_rows": int(df["resolution_angstrom"].notna().sum()),
184
+ "unknown_rows": int(df["resolution_angstrom"].isna().sum()),
185
+ "min": float(df["resolution_angstrom"].min(skipna=True)),
186
+ "median": float(df["resolution_angstrom"].median(skipna=True)),
187
+ "mean": float(df["resolution_angstrom"].mean(skipna=True)),
188
+ "max": float(df["resolution_angstrom"].max(skipna=True)),
189
+ },
190
+ "top_experimental_methods": method_counts,
191
+ "top_classifications": class_counts,
192
+ "columns": ordered_columns,
193
+ }
194
+ (out_dir / "dataset_summary.json").write_text(json.dumps(summary, indent=2) + "\n", encoding="utf-8")
195
+ return summary
196
+
197
+
198
+ def main() -> None:
199
+ parser = argparse.ArgumentParser()
200
+ parser.add_argument("--raw-dir", type=Path, default=Path("LiteFold_PDB_raw"))
201
+ parser.add_argument("--out-dir", type=Path, default=Path("LiteFold_PDB_processed"))
202
+ parser.add_argument("--repo-id", default="LiteFold/PDB")
203
+ parser.add_argument("--env-file", type=Path, default=Path(".env"))
204
+ args = parser.parse_args()
205
+
206
+ summary = build_dataset(args.raw_dir, args.out_dir, args.repo_id, load_hf_token(args.env_file))
207
+ print(json.dumps(summary, indent=2))
208
+
209
+
210
+ if __name__ == "__main__":
211
+ main()