File size: 17,327 Bytes
355e019
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Build viewer-friendly Parquet splits for LiteFold/IEDB."""

from __future__ import annotations

import argparse
import hashlib
import json
from collections import Counter
from pathlib import Path
from zipfile import ZipFile

import pyarrow as pa
import pyarrow.parquet as pq
from lxml import etree


ASSAY_TAGS = {"BCell", "TCell", "MhcBinding", "MhcLigandElution"}
ASSAY_ID_TAG = {
    "BCell": "BCellId",
    "TCell": "TCellId",
    "MhcBinding": "MhcBindingId",
    "MhcLigandElution": "MhcLigandElutionId",
}


FIELDS = [
    ("xml_file", pa.string()),
    ("reference_id", pa.string()),
    ("date_last_updated", pa.string()),
    ("pubmed_id", pa.string()),
    ("article_year", pa.int64()),
    ("article_title", pa.string()),
    ("journal_title", pa.string()),
    ("authors", pa.string()),
    ("epitope_id", pa.string()),
    ("epitope_name", pa.string()),
    ("epitope_structure_type", pa.string()),
    ("epitope_chemical_type", pa.string()),
    ("linear_sequence", pa.string()),
    ("linear_sequence_length", pa.int64()),
    ("discontinuous_residues", pa.string()),
    ("starting_position", pa.int64()),
    ("ending_position", pa.int64()),
    ("source_organism_id", pa.string()),
    ("source_molecule_genbank_id", pa.string()),
    ("reference_region", pa.string()),
    ("epitope_structure_defines", pa.string()),
    ("epitope_evidence_code", pa.string()),
    ("assay_category", pa.string()),
    ("assay_id", pa.string()),
    ("assay_type_id", pa.string()),
    ("assay_location_of_data", pa.string()),
    ("qualitative_measurement", pa.string()),
    ("is_positive", pa.bool_()),
    ("quantitative_measurement", pa.string()),
    ("host_organism_id", pa.string()),
    ("host_sex", pa.string()),
    ("host_age", pa.string()),
    ("disease_state", pa.string()),
    ("mhc_allele_id", pa.string()),
    ("mhc_allele_types_present", pa.string()),
    ("cell_type", pa.string()),
    ("cell_tissue_type", pa.string()),
    ("cell_culture_conditions", pa.string()),
    ("antigen_evidence_code", pa.string()),
    ("immunogen_evidence_code", pa.string()),
    ("assay_comments", pa.string()),
    ("split_bucket", pa.int64()),
]
SCHEMA = pa.schema(FIELDS)


def local_name(elem: etree._Element) -> str:
    tag = elem.tag
    if not isinstance(tag, str):
        return ""
    return etree.QName(tag).localname


def text_content(elem: etree._Element | None) -> str | None:
    if elem is None:
        return None
    text = " ".join(part.strip() for part in elem.itertext() if part and part.strip())
    return text or None


def direct_child(elem: etree._Element | None, name: str) -> etree._Element | None:
    if elem is None:
        return None
    for child in elem:
        if local_name(child) == name:
            return child
    return None


def direct_text(elem: etree._Element | None, name: str) -> str | None:
    return text_content(direct_child(elem, name))


def first_descendant(elem: etree._Element | None, name: str) -> etree._Element | None:
    if elem is None:
        return None
    for child in elem.iter():
        if child is not elem and local_name(child) == name:
            return child
    return None


def first_desc_text(elem: etree._Element | None, name: str) -> str | None:
    return text_content(first_descendant(elem, name))


def all_desc_text(elem: etree._Element | None, name: str) -> list[str]:
    if elem is None:
        return []
    values = []
    for child in elem.iter():
        if child is not elem and local_name(child) == name:
            value = text_content(child)
            if value:
                values.append(value)
    return values


def int_or_none(value: str | None) -> int | None:
    if value is None:
        return None
    try:
        return int(value)
    except ValueError:
        return None


def positive_flag(value: str | None) -> bool | None:
    if not value:
        return None
    lower = value.lower()
    if "negative" in lower:
        return False
    if "positive" in lower:
        return True
    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_for_row(row: dict) -> str:
    key = row.get("epitope_id") or row.get("reference_id") or row.get("assay_id") or row["xml_file"]
    return "test" if row["split_bucket"] == 0 else "train"


def cleanup(elem: etree._Element) -> None:
    elem.clear()
    parent = elem.getparent()
    while parent is not None and elem.getprevious() is not None:
        del parent[0]


def parse_epitope_structure(elem: etree._Element) -> dict:
    structure = next((child for child in elem if isinstance(child.tag, str)), None)
    return {
        "epitope_structure_type": local_name(structure) if structure is not None else None,
        "epitope_chemical_type": first_desc_text(structure, "ChemicalType"),
        "linear_sequence": first_desc_text(structure, "LinearSequence"),
        "discontinuous_residues": first_desc_text(structure, "DiscontinuousResidues"),
        "starting_position": int_or_none(first_desc_text(structure, "StartingPosition")),
        "ending_position": int_or_none(first_desc_text(structure, "EndingPosition")),
        "source_organism_id": first_desc_text(structure, "SourceOrganismId"),
        "source_molecule_genbank_id": first_desc_text(structure, "GenBankId"),
    }


def parse_authors(author_parent: etree._Element) -> str | None:
    authors = []
    for author in author_parent:
        if local_name(author) != "Author":
            continue
        first = direct_text(author, "ForeName")
        last = direct_text(author, "LastName")
        name = " ".join(part for part in [first, last] if part)
        if name:
            authors.append(name)
    return "; ".join(authors) or None


def parse_assay(elem: etree._Element, category: str) -> dict:
    assay_info = first_descendant(elem, "AssayInformation")
    immunization = first_descendant(elem, "Immunization")
    host = first_descendant(immunization, "HostOrganism")
    mhc = first_descendant(elem, "MhcAllele")
    effector = first_descendant(elem, "EffectorCells")
    antigen = first_descendant(elem, "Antigen")
    return {
        "assay_category": category,
        "assay_id": direct_text(elem, ASSAY_ID_TAG[category]),
        "assay_type_id": first_desc_text(assay_info, "AssayTypeId"),
        "assay_location_of_data": direct_text(elem, "LocationOfData"),
        "qualitative_measurement": first_desc_text(assay_info, "QualitativeMeasurement"),
        "quantitative_measurement": first_desc_text(assay_info, "QuantitativeMeasurement"),
        "host_organism_id": first_desc_text(host, "OrganismId"),
        "host_sex": first_desc_text(host, "Sex"),
        "host_age": first_desc_text(host, "Age"),
        "disease_state": first_desc_text(immunization, "DiseaseState"),
        "mhc_allele_id": first_desc_text(mhc, "MhcAlleleId"),
        "mhc_allele_types_present": "; ".join(all_desc_text(elem, "MhcAlleleTypesPresent")) or None,
        "cell_type": first_desc_text(effector, "CellType"),
        "cell_tissue_type": first_desc_text(effector, "CellTissueType"),
        "cell_culture_conditions": first_desc_text(effector, "CellCultureConditions"),
        "antigen_evidence_code": first_desc_text(antigen, "AntigenEvidenceCode"),
        "immunogen_evidence_code": first_desc_text(immunization, "ImmunogenEvidenceCode"),
        "assay_comments": direct_text(elem, "AssayComments"),
    }


def path_is_top_epitope(path: list[str]) -> bool:
    return len(path) >= 4 and path[-4:] == ["References", "Reference", "Epitopes", "Epitope"]


def flush_batch(rows: list[dict], writer: pq.ParquetWriter) -> int:
    if not rows:
        return 0
    table = pa.Table.from_pylist(rows, schema=SCHEMA)
    writer.write_table(table)
    count = len(rows)
    rows.clear()
    return count


def build_dataset(zip_path: Path, out_dir: Path, batch_size: int, limit_files: int | None = None) -> dict:
    data_dir = out_dir / "data"
    data_dir.mkdir(parents=True, exist_ok=True)
    train_path = data_dir / "train-00000-of-00001.parquet"
    test_path = data_dir / "test-00000-of-00001.parquet"
    train_writer = pq.ParquetWriter(train_path, SCHEMA, compression="zstd")
    test_writer = pq.ParquetWriter(test_path, SCHEMA, compression="zstd")

    train_rows: list[dict] = []
    test_rows: list[dict] = []
    summary_counts = Counter()
    assay_category_counts = Counter()
    qualitative_counts = Counter()
    chemical_type_counts = Counter()
    structure_type_counts = Counter()
    parse_errors: list[dict] = []
    references = set()
    epitopes = set()

    with ZipFile(zip_path) as zf:
        infos = [info for info in zf.infolist() if info.filename.endswith(".xml")]
        if limit_files is not None:
            infos = infos[:limit_files]
        summary_counts["xml_files"] = len(infos)
        summary_counts["zip_uncompressed_xml_bytes"] = sum(info.file_size for info in infos)
        summary_counts["zip_compressed_xml_bytes"] = sum(info.compress_size for info in infos)

        for index, info in enumerate(infos, start=1):
            if index % 1000 == 0:
                print(f"parsed {index}/{len(infos)} files; rows={summary_counts['assay_rows']}", flush=True)
            reference = {"xml_file": info.filename}
            epitope: dict | None = None
            path: list[str] = []
            try:
                with zf.open(info) as handle:
                    context = etree.iterparse(
                        handle,
                        events=("start", "end"),
                        recover=True,
                        huge_tree=True,
                    )
                    for event, elem in context:
                        name = local_name(elem)
                        if event == "start":
                            path.append(name)
                            if name == "Epitope" and path_is_top_epitope(path):
                                epitope = {}
                            continue

                        if name == "ReferenceId" and path[-2:] == ["Reference", "ReferenceId"]:
                            reference["reference_id"] = text_content(elem)
                        elif name == "DateLastUpdated" and path[-2:] == ["Reference", "DateLastUpdated"]:
                            reference["date_last_updated"] = text_content(elem)
                        elif name == "PubmedId" and path[-2:] == ["Article", "PubmedId"]:
                            reference["pubmed_id"] = text_content(elem)
                        elif name == "ArticleYear" and path[-2:] == ["Article", "ArticleYear"]:
                            reference["article_year"] = int_or_none(text_content(elem))
                        elif name == "ArticleTitle" and path[-2:] == ["Article", "ArticleTitle"]:
                            reference["article_title"] = text_content(elem)
                        elif name == "Title" and path[-2:] == ["Journal", "Title"]:
                            reference["journal_title"] = text_content(elem)
                        elif name == "Authors" and path[-2:] == ["Article", "Authors"]:
                            reference["authors"] = parse_authors(elem)

                        if epitope is not None and "Assays" not in path:
                            if name == "EpitopeId" and path[-2:] == ["Epitope", "EpitopeId"]:
                                epitope["epitope_id"] = text_content(elem)
                            elif name == "EpitopeName" and path[-2:] == ["Epitope", "EpitopeName"]:
                                epitope["epitope_name"] = text_content(elem)
                            elif name == "ReferenceRegion" and path[-2:] == ["Epitope", "ReferenceRegion"]:
                                epitope["reference_region"] = text_content(elem)
                            elif name == "EpitopeStructureDefines" and path[-2:] == ["Epitope", "EpitopeStructureDefines"]:
                                epitope["epitope_structure_defines"] = text_content(elem)
                            elif name == "EpitopeEvidenceCode" and path[-2:] == ["Epitope", "EpitopeEvidenceCode"]:
                                epitope["epitope_evidence_code"] = text_content(elem)
                            elif name == "EpitopeStructure" and path[-2:] == ["Epitope", "EpitopeStructure"]:
                                epitope.update(parse_epitope_structure(elem))

                        if name in ASSAY_TAGS:
                            row = {field_name: None for field_name, _ in FIELDS}
                            row.update(reference)
                            if epitope:
                                row.update(epitope)
                            row.update(parse_assay(elem, name))
                            sequence = row.get("linear_sequence")
                            row["linear_sequence_length"] = len(sequence) if sequence else None
                            row["is_positive"] = positive_flag(row.get("qualitative_measurement"))
                            key = row.get("epitope_id") or row.get("reference_id") or row.get("assay_id") or row["xml_file"]
                            row["split_bucket"] = stable_bucket(str(key))

                            split = split_for_row(row)
                            if split == "test":
                                test_rows.append(row)
                            else:
                                train_rows.append(row)
                            summary_counts["assay_rows"] += 1
                            assay_category_counts[row["assay_category"]] += 1
                            if row.get("qualitative_measurement"):
                                qualitative_counts[row["qualitative_measurement"]] += 1
                            if row.get("epitope_chemical_type"):
                                chemical_type_counts[row["epitope_chemical_type"]] += 1
                            if row.get("epitope_structure_type"):
                                structure_type_counts[row["epitope_structure_type"]] += 1
                            if row.get("reference_id"):
                                references.add(row["reference_id"])
                            if row.get("epitope_id"):
                                epitopes.add(row["epitope_id"])
                            cleanup(elem)

                            summary_counts["train_rows"] += flush_batch(train_rows, train_writer) if len(train_rows) >= batch_size else 0
                            summary_counts["test_rows"] += flush_batch(test_rows, test_writer) if len(test_rows) >= batch_size else 0

                        if name == "Epitope" and epitope is not None and path_is_top_epitope(path):
                            epitope = None
                            cleanup(elem)

                        if path:
                            path.pop()
            except Exception as exc:
                parse_errors.append({"xml_file": info.filename, "error": f"{type(exc).__name__}: {exc}"})
                summary_counts["parse_error_files"] += 1

    summary_counts["train_rows"] += flush_batch(train_rows, train_writer)
    summary_counts["test_rows"] += flush_batch(test_rows, test_writer)
    train_writer.close()
    test_writer.close()

    summary = {
        "source": "LiteFold/IEDB",
        "source_file": zip_path.name,
        "xml_files": int(summary_counts["xml_files"]),
        "parse_error_files": int(summary_counts["parse_error_files"]),
        "assay_rows": int(summary_counts["assay_rows"]),
        "unique_references_with_assays": len(references),
        "unique_epitopes_with_assays": len(epitopes),
        "splits": {
            "train": int(summary_counts["train_rows"]),
            "test": int(summary_counts["test_rows"]),
        },
        "split_strategy": "deterministic sha256(epitope_id) % 10; bucket 0 is test, buckets 1-9 are train; reference_id/assay_id/file used as fallback",
        "zip_uncompressed_xml_bytes": int(summary_counts["zip_uncompressed_xml_bytes"]),
        "zip_compressed_xml_bytes": int(summary_counts["zip_compressed_xml_bytes"]),
        "assay_category_counts": dict(assay_category_counts),
        "top_qualitative_measurements": dict(qualitative_counts.most_common(20)),
        "top_epitope_chemical_types": dict(chemical_type_counts.most_common(20)),
        "top_epitope_structure_types": dict(structure_type_counts.most_common(20)),
        "columns": [name for name, _ in FIELDS],
        "parse_errors": parse_errors[:100],
    }
    (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("--zip-path", type=Path, default=Path("LiteFold_IEDB_raw/iedb_export.zip"))
    parser.add_argument("--out-dir", type=Path, default=Path("LiteFold_IEDB_processed"))
    parser.add_argument("--batch-size", type=int, default=50_000)
    parser.add_argument("--limit-files", type=int)
    args = parser.parse_args()

    summary = build_dataset(args.zip_path, args.out_dir, args.batch_size, args.limit_files)
    print(json.dumps(summary, indent=2))


if __name__ == "__main__":
    main()