File size: 10,948 Bytes
e499a9b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Build viewer-friendly Parquet splits for LiteFold/CATH."""

from __future__ import annotations

import argparse
import hashlib
import json
import re
from pathlib import Path

import pandas as pd


DOMAIN_COLUMNS = [
    "domain_id",
    "class_number",
    "architecture_number",
    "topology_number",
    "homologous_superfamily_number",
    "s35_cluster_id",
    "s60_cluster_id",
    "s95_cluster_id",
    "s100_cluster_id",
    "s100_sequence_count",
    "domain_length",
    "raw_structure_resolution_angstrom",
]


def iter_data_lines(path: Path):
    with path.open("r", encoding="utf-8") as handle:
        for line in handle:
            line = line.rstrip("\n")
            if not line or line.startswith("#"):
                continue
            yield line


def parse_domain_list(path: Path) -> pd.DataFrame:
    records = []
    for line in iter_data_lines(path):
        parts = line.split()
        if len(parts) != len(DOMAIN_COLUMNS):
            raise ValueError(f"Expected {len(DOMAIN_COLUMNS)} columns in {path}, got {len(parts)}: {line}")
        records.append(parts)

    df = pd.DataFrame(records, columns=DOMAIN_COLUMNS)
    int_columns = [
        "class_number",
        "architecture_number",
        "topology_number",
        "homologous_superfamily_number",
        "s35_cluster_id",
        "s60_cluster_id",
        "s95_cluster_id",
        "s100_cluster_id",
        "s100_sequence_count",
        "domain_length",
    ]
    for col in int_columns:
        df[col] = df[col].astype("int64")
    df["raw_structure_resolution_angstrom"] = df["raw_structure_resolution_angstrom"].astype("float64")
    df["structure_resolution_is_unknown"] = df["raw_structure_resolution_angstrom"].eq(999.0)
    df["structure_resolution_angstrom"] = df["raw_structure_resolution_angstrom"].mask(
        df["structure_resolution_is_unknown"]
    )
    df["structure_resolution_angstrom"] = df["structure_resolution_angstrom"].astype("Float64")

    df["pdb_id"] = df["domain_id"].str.slice(0, 4)
    df["chain_id"] = df["domain_id"].str.slice(4, 5)
    df["pdb_chain_id"] = df["domain_id"].str.slice(0, 5)
    df["domain_suffix"] = df["domain_id"].str.slice(5, 7)
    df["domain_index"] = df["domain_suffix"].astype("int64")

    df["class_code"] = df["class_number"].astype(str)
    df["architecture_code"] = df["class_code"] + "." + df["architecture_number"].astype(str)
    df["topology_code"] = df["architecture_code"] + "." + df["topology_number"].astype(str)
    df["homologous_superfamily_code"] = (
        df["topology_code"] + "." + df["homologous_superfamily_number"].astype(str)
    )
    df["cath_code"] = df["homologous_superfamily_code"]
    df["s35_cluster_key"] = df["homologous_superfamily_code"] + ":S35:" + df["s35_cluster_id"].astype(str)
    return df


def parse_names(path: Path) -> pd.DataFrame:
    records = []
    for line in iter_data_lines(path):
        if ":" not in line:
            continue
        left, name = line.split(":", 1)
        parts = left.split()
        if len(parts) < 2:
            continue
        records.append(
            {
                "cath_node_code": parts[0],
                "example_domain_id": parts[1],
                "cath_node_name": name.strip(),
            }
        )
    return pd.DataFrame.from_records(records)


_RANGE_SEGMENT_RE = re.compile(r"^\s*(-?\d+)(?:\([A-Za-z0-9]+\))?-(-?\d+)(?:\([A-Za-z0-9]+\))?\s*$")


def parse_range_summary(sequence_range: str) -> tuple[int | None, int | None, int]:
    starts: list[int] = []
    ends: list[int] = []
    segments = [segment for segment in sequence_range.split("_") if segment]
    for segment in segments:
        match = _RANGE_SEGMENT_RE.match(segment)
        if not match:
            continue
        starts.append(int(match.group(1)))
        ends.append(int(match.group(2)))
    if not starts:
        return None, None, len(segments)
    return min(starts), max(ends), len(segments)


def parse_fasta(path: Path) -> pd.DataFrame:
    records = []
    header: str | None = None
    sequence_chunks: list[str] = []

    def flush() -> None:
        if header is None:
            return
        try:
            _, version, payload = header.split("|", 2)
            domain_id, sequence_range = payload.split("/", 1)
        except ValueError as exc:
            raise ValueError(f"Unexpected FASTA header in {path}: {header}") from exc
        sequence = "".join(sequence_chunks)
        start, end, segment_count = parse_range_summary(sequence_range)
        records.append(
            {
                "domain_id": domain_id,
                "cath_version": version.replace("_", "."),
                "sequence": sequence,
                "sequence_length": len(sequence),
                "sequence_range": sequence_range,
                "sequence_range_start": start,
                "sequence_range_end": end,
                "sequence_segment_count": segment_count,
            }
        )

    with path.open("r", encoding="utf-8") as handle:
        for line in handle:
            line = line.strip()
            if not line:
                continue
            if line.startswith(">"):
                flush()
                header = line[1:]
                sequence_chunks = []
            else:
                sequence_chunks.append(line)
    flush()
    return pd.DataFrame.from_records(records)


def subset_domain_ids(path: Path) -> set[str]:
    return {line.split()[0] for line in iter_data_lines(path)}


def stable_hash_int(value: str) -> int:
    return int(hashlib.sha256(value.encode("utf-8")).hexdigest()[:16], 16)


def add_cluster_aware_split(df: pd.DataFrame, test_size: float) -> pd.DataFrame:
    cluster_counts = (
        df.groupby("s35_cluster_key", sort=False)
        .size()
        .rename("row_count")
        .reset_index()
    )
    cluster_counts["hash"] = cluster_counts["s35_cluster_key"].map(stable_hash_int)
    cluster_counts = cluster_counts.sort_values(["hash", "s35_cluster_key"], kind="mergesort")

    target_rows = round(len(df) * test_size)
    test_keys: set[str] = set()
    test_rows = 0
    for row in cluster_counts.itertuples(index=False):
        if test_rows >= target_rows:
            break
        test_keys.add(row.s35_cluster_key)
        test_rows += int(row.row_count)

    df = df.copy()
    df["split"] = df["s35_cluster_key"].map(lambda key: "test" if key in test_keys else "train")
    return df


def build_dataset(raw_dir: Path, out_dir: Path, test_size: float) -> dict:
    domains = parse_domain_list(raw_dir / "cath-domain-list.txt")
    names = parse_names(raw_dir / "cath-names.txt")
    names_by_code = names.set_index("cath_node_code")

    for level, code_col in [
        ("class", "class_code"),
        ("architecture", "architecture_code"),
        ("topology", "topology_code"),
        ("homologous_superfamily", "homologous_superfamily_code"),
    ]:
        domains[f"{level}_name"] = domains[code_col].map(names_by_code["cath_node_name"])
        domains[f"{level}_example_domain_id"] = domains[code_col].map(names_by_code["example_domain_id"])

    sequences = parse_fasta(raw_dir / "cath-domain-seqs.fa")
    df = domains.merge(sequences, on="domain_id", how="left", validate="one_to_one")

    missing_sequences = int(df["sequence"].isna().sum())
    if missing_sequences:
        raise ValueError(f"{missing_sequences} domain-list rows did not have FASTA sequences")

    for subset in ["S35", "S60", "S95", "S100"]:
        ids = subset_domain_ids(raw_dir / f"cath-domain-list-{subset}.txt")
        df[f"in_{subset.lower()}_nonredundant_subset"] = df["domain_id"].isin(ids)

    df = add_cluster_aware_split(df, test_size)

    ordered_columns = [
        "domain_id",
        "pdb_id",
        "chain_id",
        "pdb_chain_id",
        "domain_suffix",
        "domain_index",
        "cath_version",
        "cath_code",
        "class_number",
        "class_code",
        "class_name",
        "class_example_domain_id",
        "architecture_number",
        "architecture_code",
        "architecture_name",
        "architecture_example_domain_id",
        "topology_number",
        "topology_code",
        "topology_name",
        "topology_example_domain_id",
        "homologous_superfamily_number",
        "homologous_superfamily_code",
        "homologous_superfamily_name",
        "homologous_superfamily_example_domain_id",
        "s35_cluster_id",
        "s60_cluster_id",
        "s95_cluster_id",
        "s100_cluster_id",
        "s100_sequence_count",
        "s35_cluster_key",
        "domain_length",
        "raw_structure_resolution_angstrom",
        "structure_resolution_angstrom",
        "structure_resolution_is_unknown",
        "sequence",
        "sequence_length",
        "sequence_range",
        "sequence_range_start",
        "sequence_range_end",
        "sequence_segment_count",
        "in_s35_nonredundant_subset",
        "in_s60_nonredundant_subset",
        "in_s95_nonredundant_subset",
        "in_s100_nonredundant_subset",
        "split",
    ]
    df = df[ordered_columns].sort_values(["split", "domain_id"], kind="mergesort")

    data_dir = out_dir / "data"
    data_dir.mkdir(parents=True, exist_ok=True)
    split_counts = {}
    for split in ["train", "test"]:
        split_df = df[df["split"].eq(split)].drop(columns=["split"])
        split_counts[split] = len(split_df)
        split_df.to_parquet(
            data_dir / f"{split}-00000-of-00001.parquet",
            index=False,
            compression="zstd",
        )

    summary = {
        "source": "LiteFold/CATH",
        "cath_version": str(df["cath_version"].iloc[0]),
        "total_rows": len(df),
        "splits": split_counts,
        "test_size_requested": test_size,
        "split_strategy": "deterministic S35-cluster-aware split using sha256(s35_cluster_key)",
        "unique_s35_clusters": int(df["s35_cluster_key"].nunique()),
        "columns": [column for column in ordered_columns if column != "split"],
        "subset_rows": {
            "s35": int(df["in_s35_nonredundant_subset"].sum()),
            "s60": int(df["in_s60_nonredundant_subset"].sum()),
            "s95": int(df["in_s95_nonredundant_subset"].sum()),
            "s100": int(df["in_s100_nonredundant_subset"].sum()),
        },
    }
    (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_CATH_raw"))
    parser.add_argument("--out-dir", type=Path, default=Path("LiteFold_CATH_processed"))
    parser.add_argument("--test-size", type=float, default=0.10)
    args = parser.parse_args()

    summary = build_dataset(args.raw_dir, args.out_dir, args.test_size)
    print(json.dumps(summary, indent=2))


if __name__ == "__main__":
    main()