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
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
#!/usr/bin/env python3
"""Build viewer-friendly Parquet splits for LiteFold/PDB-CCD."""

from __future__ import annotations

import argparse
import gzip
import hashlib
import json
import re
import shutil
from collections import Counter
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Iterator

import pandas as pd


COMPONENT_COLUMNS = [
    "component_id",
    "name",
    "component_type",
    "pdbx_type",
    "formula",
    "formula_weight",
    "formal_charge",
    "mon_nstd_parent_comp_id",
    "one_letter_code",
    "three_letter_code",
    "pdbx_synonyms",
    "synonym_names",
    "synonym_provenances",
    "synonym_types",
    "initial_date",
    "modified_date",
    "release_status",
    "ambiguous_flag",
    "replaced_by",
    "replaces",
    "model_coordinates_missing_flag",
    "ideal_coordinates_missing_flag",
    "model_coordinates_db_code",
    "processing_site",
    "atom_ids",
    "atom_alt_ids",
    "atom_elements",
    "atom_charges",
    "atom_aromatic_flags",
    "atom_leaving_flags",
    "atom_stereo_configs",
    "atom_count",
    "heavy_atom_count",
    "hydrogen_atom_count",
    "bond_atom_id_1",
    "bond_atom_id_2",
    "bond_orders",
    "bond_aromatic_flags",
    "bond_stereo_configs",
    "bond_count",
    "descriptor_types",
    "descriptor_programs",
    "descriptor_program_versions",
    "descriptors",
    "canonical_smiles",
    "smiles",
    "inchi",
    "inchikey",
    "identifier_types",
    "identifier_programs",
    "identifier_program_versions",
    "identifiers",
    "systematic_names",
    "audit_actions",
    "audit_dates",
    "audit_processing_sites",
    "related_component_ids",
    "related_relationship_types",
    "pcm_ids",
    "pcm_modified_residue_ids",
    "pcm_types",
    "pcm_categories",
    "pcm_positions",
    "feature_types",
    "feature_values",
    "split_bucket",
]


@dataclass
class TokenStream:
    iterator: Iterator[str]
    pushed: list[str]

    def next(self) -> str | None:
        if self.pushed:
            return self.pushed.pop()
        return next(self.iterator, None)

    def push(self, token: str) -> None:
        self.pushed.append(token)


def cif_tokens(path: Path) -> Iterator[str]:
    with gzip.open(path, "rt", encoding="utf-8", errors="replace") as handle:
        multiline: list[str] | None = None
        for raw_line in handle:
            line = raw_line.rstrip("\n")
            if multiline is not None:
                if line.startswith(";"):
                    yield "\n".join(multiline).strip()
                    multiline = None
                else:
                    multiline.append(line)
                continue
            if line.startswith(";"):
                multiline = [line[1:]]
                continue

            i = 0
            length = len(line)
            while i < length:
                while i < length and line[i].isspace():
                    i += 1
                if i >= length:
                    break
                if line[i] == "#":
                    break
                if line[i] in {"'", '"'}:
                    quote = line[i]
                    i += 1
                    value: list[str] = []
                    while i < length:
                        char = line[i]
                        if char == quote:
                            next_index = i + 1
                            if next_index >= length or line[next_index].isspace() or line[next_index] == "#":
                                i += 1
                                break
                        value.append(char)
                        i += 1
                    yield "".join(value)
                    continue

                start = i
                while i < length and not line[i].isspace() and line[i] != "#":
                    i += 1
                yield line[start:i]
                if i < length and line[i] == "#":
                    break


def clean_value(value: str | None) -> Any:
    if value in {None, "?", "."}:
        return None
    return re.sub(r"\s+", " ", value).strip()


def parse_int(value: Any) -> int | None:
    value = clean_value(value)
    if value is None:
        return None
    try:
        return int(value)
    except (TypeError, ValueError):
        return None


def parse_float(value: Any) -> float | None:
    value = clean_value(value)
    if value is None:
        return None
    try:
        return float(value)
    except (TypeError, ValueError):
        return None


def stable_bucket(value: str, buckets: int = 10) -> int:
    digest = hashlib.sha256(value.encode("utf-8")).hexdigest()[:16]
    return int(digest, 16) % buckets


def split_tag(tag: str) -> tuple[str, str]:
    body = tag[1:]
    category, field = body.split(".", 1)
    return category, field


def finish_loop(tags: list[str], values: list[str], loops: dict[str, list[dict[str, Any]]]) -> None:
    if not tags:
        return
    categories = {split_tag(tag)[0] for tag in tags}
    if len(categories) != 1:
        return
    category = categories.pop()
    fields = [split_tag(tag)[1] for tag in tags]
    width = len(fields)
    rows = []
    for start in range(0, len(values) - (len(values) % width), width):
        rows.append({field: clean_value(values[start + index]) for index, field in enumerate(fields)})
    loops.setdefault(category, []).extend(rows)


def parse_cif_blocks(path: Path) -> Iterator[dict[str, Any]]:
    stream = TokenStream(cif_tokens(path), [])
    block: dict[str, Any] | None = None

    while True:
        token = stream.next()
        if token is None:
            if block is not None:
                yield block
            break

        if token.startswith("data_"):
            if block is not None:
                yield block
            block = {"name": token[5:], "scalars": {}, "loops": {}}
            continue

        if block is None:
            continue

        if token == "loop_":
            tags: list[str] = []
            values: list[str] = []
            while True:
                item = stream.next()
                if item is None:
                    break
                if item.startswith("_"):
                    tags.append(item)
                    continue
                stream.push(item)
                break
            while True:
                item = stream.next()
                if item is None:
                    finish_loop(tags, values, block["loops"])
                    return
                if item == "loop_" or item.startswith("data_") or item.startswith("_"):
                    stream.push(item)
                    break
                values.append(item)
            finish_loop(tags, values, block["loops"])
            continue

        if token.startswith("_"):
            value = stream.next()
            if value is None:
                continue
            if value == "loop_" or value.startswith("data_") or value.startswith("_"):
                stream.push(value)
                continue
            category, field = split_tag(token)
            block["scalars"].setdefault(category, {})[field] = clean_value(value)


def first_by_type(rows: list[dict[str, Any]], wanted_type: str) -> str | None:
    for row in rows:
        if row.get("type") == wanted_type and row.get("descriptor"):
            return str(row["descriptor"])
    return None


def values(rows: list[dict[str, Any]], field: str) -> list[Any]:
    return [row[field] for row in rows if row.get(field) is not None]


def string_values(rows: list[dict[str, Any]], field: str) -> list[str]:
    return [str(row[field]) for row in rows if row.get(field) is not None]


def int_values(rows: list[dict[str, Any]], field: str) -> list[int]:
    parsed = []
    for row in rows:
        value = parse_int(row.get(field))
        if value is not None:
            parsed.append(value)
    return parsed


def component_row(block: dict[str, Any]) -> dict[str, Any]:
    scalars = block["scalars"].get("chem_comp", {})
    loops = block["loops"]
    atoms = loops.get("chem_comp_atom", [])
    bonds = loops.get("chem_comp_bond", [])
    descriptors = loops.get("pdbx_chem_comp_descriptor", [])
    identifiers = loops.get("pdbx_chem_comp_identifier", [])
    audits = loops.get("pdbx_chem_comp_audit", [])
    synonyms = loops.get("pdbx_chem_comp_synonyms", [])
    related = loops.get("pdbx_chem_comp_related", [])
    pcms = loops.get("pdbx_chem_comp_pcm", [])
    features = loops.get("pdbx_chem_comp_feature", [])

    component_id = str(scalars.get("id") or block["name"])
    atom_elements = string_values(atoms, "type_symbol")
    heavy_atom_count = sum(1 for element in atom_elements if element.upper() != "H")
    hydrogen_atom_count = sum(1 for element in atom_elements if element.upper() == "H")

    return {
        "component_id": component_id,
        "name": scalars.get("name"),
        "component_type": scalars.get("type"),
        "pdbx_type": scalars.get("pdbx_type"),
        "formula": scalars.get("formula"),
        "formula_weight": parse_float(scalars.get("formula_weight")),
        "formal_charge": parse_int(scalars.get("pdbx_formal_charge")),
        "mon_nstd_parent_comp_id": scalars.get("mon_nstd_parent_comp_id"),
        "one_letter_code": scalars.get("one_letter_code"),
        "three_letter_code": scalars.get("three_letter_code"),
        "pdbx_synonyms": scalars.get("pdbx_synonyms"),
        "synonym_names": string_values(synonyms, "name"),
        "synonym_provenances": string_values(synonyms, "provenance"),
        "synonym_types": string_values(synonyms, "type"),
        "initial_date": scalars.get("pdbx_initial_date"),
        "modified_date": scalars.get("pdbx_modified_date"),
        "release_status": scalars.get("pdbx_release_status"),
        "ambiguous_flag": scalars.get("pdbx_ambiguous_flag"),
        "replaced_by": scalars.get("pdbx_replaced_by"),
        "replaces": scalars.get("pdbx_replaces"),
        "model_coordinates_missing_flag": scalars.get("pdbx_model_coordinates_missing_flag"),
        "ideal_coordinates_missing_flag": scalars.get("pdbx_ideal_coordinates_missing_flag"),
        "model_coordinates_db_code": scalars.get("pdbx_model_coordinates_db_code"),
        "processing_site": scalars.get("pdbx_processing_site"),
        "atom_ids": string_values(atoms, "atom_id"),
        "atom_alt_ids": string_values(atoms, "alt_atom_id"),
        "atom_elements": atom_elements,
        "atom_charges": int_values(atoms, "charge"),
        "atom_aromatic_flags": string_values(atoms, "pdbx_aromatic_flag"),
        "atom_leaving_flags": string_values(atoms, "pdbx_leaving_atom_flag"),
        "atom_stereo_configs": string_values(atoms, "pdbx_stereo_config"),
        "atom_count": len(atoms),
        "heavy_atom_count": heavy_atom_count,
        "hydrogen_atom_count": hydrogen_atom_count,
        "bond_atom_id_1": string_values(bonds, "atom_id_1"),
        "bond_atom_id_2": string_values(bonds, "atom_id_2"),
        "bond_orders": string_values(bonds, "value_order"),
        "bond_aromatic_flags": string_values(bonds, "pdbx_aromatic_flag"),
        "bond_stereo_configs": string_values(bonds, "pdbx_stereo_config"),
        "bond_count": len(bonds),
        "descriptor_types": string_values(descriptors, "type"),
        "descriptor_programs": string_values(descriptors, "program"),
        "descriptor_program_versions": string_values(descriptors, "program_version"),
        "descriptors": string_values(descriptors, "descriptor"),
        "canonical_smiles": first_by_type(descriptors, "SMILES_CANONICAL"),
        "smiles": first_by_type(descriptors, "SMILES"),
        "inchi": first_by_type(descriptors, "InChI"),
        "inchikey": first_by_type(descriptors, "InChIKey"),
        "identifier_types": string_values(identifiers, "type"),
        "identifier_programs": string_values(identifiers, "program"),
        "identifier_program_versions": string_values(identifiers, "program_version"),
        "identifiers": string_values(identifiers, "identifier"),
        "systematic_names": [
            str(row["identifier"])
            for row in identifiers
            if row.get("type") == "SYSTEMATIC NAME" and row.get("identifier") is not None
        ],
        "audit_actions": string_values(audits, "action_type"),
        "audit_dates": string_values(audits, "date"),
        "audit_processing_sites": string_values(audits, "processing_site"),
        "related_component_ids": string_values(related, "related_comp_id"),
        "related_relationship_types": string_values(related, "relationship_type"),
        "pcm_ids": string_values(pcms, "pcm_id"),
        "pcm_modified_residue_ids": string_values(pcms, "modified_residue_id"),
        "pcm_types": string_values(pcms, "type"),
        "pcm_categories": string_values(pcms, "category"),
        "pcm_positions": string_values(pcms, "position"),
        "feature_types": string_values(features, "type"),
        "feature_values": string_values(features, "value"),
        "split_bucket": stable_bucket(component_id),
    }


def build_dataset(raw_dir: Path, out_dir: Path) -> dict[str, Any]:
    cif_path = raw_dir / "components.cif.gz"
    rows = [component_row(block) for block in parse_cif_blocks(cif_path)]

    if out_dir.exists():
        shutil.rmtree(out_dir)
    data_dir = out_dir / "data"
    data_dir.mkdir(parents=True, exist_ok=True)

    df = pd.DataFrame.from_records(rows, columns=COMPONENT_COLUMNS)
    df = df.sort_values(["split_bucket", "component_id"], kind="mergesort")
    train = df[df["split_bucket"].ne(0)].sort_values("component_id", kind="mergesort")
    test = df[df["split_bucket"].eq(0)].sort_values("component_id", kind="mergesort")
    train.to_parquet(data_dir / "train-00000-of-00001.parquet", index=False, compression="zstd")
    test.to_parquet(data_dir / "test-00000-of-00001.parquet", index=False, compression="zstd")

    def count_column(column: str) -> dict[str, int]:
        return {
            str(key): int(value)
            for key, value in df[column].fillna("missing").value_counts(dropna=False).to_dict().items()
        }

    release_status_counts = count_column("release_status")
    type_counts = count_column("component_type")
    pdbx_type_counts = count_column("pdbx_type")
    element_counts = Counter(element for elements in df["atom_elements"] for element in elements)
    descriptor_type_counts = Counter(kind for kinds in df["descriptor_types"] for kind in kinds)
    identifier_type_counts = Counter(kind for kinds in df["identifier_types"] for kind in kinds)
    max_modified_date = max((value for value in df["modified_date"].dropna().tolist()), default=None)

    summary = {
        "source": "LiteFold/PDB-CCD",
        "component_rows": int(len(df)),
        "splits": {
            "train": int(len(train)),
            "test": int(len(test)),
        },
        "split_strategy": "deterministic sha256(component_id) % 10; bucket 0 is test, buckets 1-9 are train",
        "release_status_counts": release_status_counts,
        "component_type_counts": type_counts,
        "pdbx_type_counts": pdbx_type_counts,
        "max_modified_date": max_modified_date,
        "components_with_atoms": int(df["atom_count"].gt(0).sum()),
        "components_with_bonds": int(df["bond_count"].gt(0).sum()),
        "components_with_descriptors": int(df["descriptors"].map(len).gt(0).sum()),
        "components_with_identifiers": int(df["identifiers"].map(len).gt(0).sum()),
        "components_with_pcm": int(df["pcm_ids"].map(len).gt(0).sum()),
        "top_elements": dict(element_counts.most_common(30)),
        "descriptor_type_counts": dict(descriptor_type_counts.most_common()),
        "identifier_type_counts": dict(identifier_type_counts.most_common()),
        "columns": COMPONENT_COLUMNS,
        "source_files_used": ["components.cif.gz"],
    }
    (out_dir / "dataset_summary.json").write_text(json.dumps(summary, indent=2) + "\n", encoding="utf-8")
    return summary


def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument("--raw-dir", type=Path, default=Path("LiteFold_PDB_CCD_raw"))
    parser.add_argument("--out-dir", type=Path, default=Path("LiteFold_PDB_CCD_processed"))
    args = parser.parse_args()
    summary = build_dataset(args.raw_dir, args.out_dir)
    print(json.dumps(summary, indent=2))


if __name__ == "__main__":
    main()