File size: 20,543 Bytes
6d19a18
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
#!/usr/bin/env python3
"""Analyse docking poses with PoseBusters and OST.

The script processes one docking run directory (for example
``docking/gnina_redock``) and writes pose-level CSV and Parquet files beneath a
shared analysis directory.
"""

from __future__ import annotations

import argparse
import csv
import json
import logging
import re
import shutil
import subprocess
from concurrent.futures import ProcessPoolExecutor, as_completed
from pathlib import Path
from typing import Sequence

import pandas as pd
from posebusters import PoseBusters
from rdkit import Chem, RDLogger


SUPPORTED_METHODS = {"gnina", "smina", "diffdock"}


def file_ok(path: Path) -> bool:
    """Return whether a file exists and is non-empty."""
    return path.is_file() and path.stat().st_size > 0


def infer_similarity_label(path: Path) -> str:
    """Infer a date label from a similarity TSV filename."""
    match = re.search(r"\d{4}-\d{2}-\d{2}", path.name)
    if match is None:
        raise ValueError(f"Could not infer date label from similarity TSV: {path}")
    return match.group(0)


def load_similarity_dicts(
    similarity_tsvs: Sequence[Path] | None,
) -> dict[str, dict[str, str]] | None:
    """Load optional similarity TSVs and suffix metric names by date."""
    if not similarity_tsvs:
        return None

    metric_cols = ["sucos_shape", "pocket_qcov", "sucos_shape_pocket_qcov"]
    similarity_dict: dict[str, dict[str, str]] = {}

    for similarity_tsv in similarity_tsvs:
        path = similarity_tsv.expanduser().resolve()
        if not file_ok(path):
            raise FileNotFoundError(f"Similarity TSV not found or empty: {path}")

        label = infer_similarity_label(path)
        with path.open("r", encoding="utf-8", newline="") as handle:
            reader = csv.DictReader(handle, delimiter="\t")
            if reader.fieldnames is None or reader.fieldnames[0] is None:
                raise ValueError(f"Similarity TSV has no header: {path}")
            missing = set(metric_cols) - set(reader.fieldnames)
            if missing:
                raise ValueError(
                    f"Similarity TSV is missing columns {sorted(missing)}: {path}"
                )

            id_column = reader.fieldnames[0]
            for row in reader:
                complex_id = row[id_column]
                similarity_dict.setdefault(complex_id, {})
                for col in metric_cols:
                    similarity_dict[complex_id][f"{col}-{label}"] = row[col]

    return similarity_dict


def add_similarity_metrics(
    df: pd.DataFrame,
    similarity_dict: dict[str, dict[str, str]] | None,
) -> pd.DataFrame:
    """Attach optional similarity metrics for each comparison complex."""
    if similarity_dict is None:
        return df
    metric_cols = sorted({col for values in similarity_dict.values() for col in values})
    for col in metric_cols:
        df[col] = df["compare_id"].map(
            lambda complex_id: similarity_dict.get(complex_id, {}).get(col)
        )
    return df


def structure_root_from_run(run_dir: Path) -> Path:
    """Resolve the dataset root from ``<dataset>/docking/<run>``."""
    if run_dir.parent.name != "docking":
        raise ValueError(
            f"Run directory must be directly beneath a 'docking' directory: {run_dir}"
        )
    structure_root = run_dir.parent.parent
    if not (structure_root / "prepared_inputs" / "redock").is_dir():
        raise FileNotFoundError(
            f"Redock prepared inputs not found beneath dataset root: {structure_root}"
        )
    return structure_root


def reference_paths(structure_root: Path, complex_id: str) -> tuple[Path, Path]:
    """Return the redock receptor and crystallographic ligand for one complex."""
    directory = structure_root / "prepared_inputs" / "redock" / complex_id
    protein = directory / f"{complex_id}_prepared.pdb"
    ligand = directory / f"{complex_id}_reference_ligand.sdf"
    if not file_ok(protein):
        raise FileNotFoundError(f"Missing reference receptor: {protein}")
    if not file_ok(ligand):
        raise FileNotFoundError(f"Missing reference ligand: {ligand}")
    return protein, ligand


def docked_protein_path(structure_root: Path, mode: str, complex_id: str) -> Path:
    """Return the exact receptor used for one docking mode."""
    directory = structure_root / "prepared_inputs" / mode / complex_id
    if not directory.is_dir():
        raise FileNotFoundError(f"Prepared receptor directory not found: {directory}")

    if mode == "redock":
        path = directory / f"{complex_id}_prepared.pdb"
    elif mode == "fragment_crossdock":
        matches = sorted(directory.glob("fragment_crossdock_*_aligned.pdb"))
        if len(matches) != 1:
            raise FileNotFoundError(
                f"Expected one fragment-crossdock receptor in {directory}; found {len(matches)}"
            )
        path = matches[0]
    else:
        path = directory / f"{mode}_prepared_aligned.pdb"

    if not file_ok(path):
        raise FileNotFoundError(f"Docked receptor not found or empty: {path}")
    return path


def seed_dirs(complex_dir: Path) -> list[Path]:
    """Return immediate seed directories for one docked complex."""
    directories = sorted(path for path in complex_dir.glob("seed_*") if path.is_dir())
    if not directories:
        raise FileNotFoundError(f"No seed directories found in: {complex_dir}")
    return directories


def pose_dir(seed_dir: Path) -> Path:
    """Return the canonical docked-pose directory."""
    directory = seed_dir / "docked_poses"
    if not directory.is_dir():
        raise FileNotFoundError(f"Docked-pose directory not found: {directory}")
    return directory


def format_chain_mapping(mapping: dict | None) -> str | None:
    """Format an OST chain mapping as a compact string."""
    if not mapping:
        return None
    return ",".join(f"{key}:{value}" for key, value in sorted(mapping.items()))


def ost_to_df(path: Path) -> pd.DataFrame:
    """Convert OST ligand-comparison output to a pose-level table."""
    with path.open("r", encoding="utf-8") as handle:
        ost = json.load(handle)

    lddt_rows = []
    for row in ost["lddt_pli"]["full_results"]:
        sample = int(row["model_ligand"].rsplit(":", 1)[1])
        score = row.get("score")
        lddt_rows.append(
            {"sample": sample, "lddt_pli": float(score) if score is not None else 0.0}
        )

    rmsd_rows = []
    for row in ost["rmsd"]["full_results"]:
        sample = int(row["model_ligand"].rsplit(":", 1)[1])
        score = row.get("score")
        rmsd_rows.append(
            {
                "sample": sample,
                "lig_rmsd": float(score) if score is not None else 99.0,
                "rmsd_chain_mapping": format_chain_mapping(row.get("chain_mapping")),
                "lddt_lp": row.get("lddt_lp"),
                "pocket_bb_rmsd": row.get("bb_rmsd"),
            }
        )
    return pd.DataFrame(lddt_rows).merge(
        pd.DataFrame(rmsd_rows), on="sample", how="outer"
    )


def posebusters_to_df(path: Path) -> pd.DataFrame:
    """Convert PoseBusters output to a pose-level validity table."""
    df = pd.read_csv(path).copy()

    if "position" in df.columns:
        df["sample"] = df["position"].astype(int)
    else:
        df["sample"] = range(len(df))

    meta_cols = {"file", "molecule", "position", "sample"}
    metric_cols = [col for col in df.columns if col not in meta_cols]

    if not metric_cols:
        raise ValueError(f"PoseBusters output contains no check columns: {path}")

    df["pb_valid"] = df[metric_cols].all(axis=1)

    return df[["sample", "pb_valid"]]


def sdf_to_pose_df(
    path: Path, score_property: str, flip_sign: bool = False
) -> pd.DataFrame:
    """Read pose scores from a ranked SDF file."""
    rows: list[dict[str, object]] = []
    for sample, mol in enumerate(Chem.SDMolSupplier(str(path), removeHs=False)):
        if mol is None:
            raise ValueError(f"Invalid molecule at position {sample} in {path}")
        if not mol.HasProp(score_property):
            raise ValueError(f"Pose {sample} in {path} is missing '{score_property}'")
        score = float(mol.GetProp(score_property))
        rows.append({"sample": sample, "rank_score": -score if flip_sign else score})
    if not rows:
        raise ValueError(f"No poses found in SDF: {path}")
    return pd.DataFrame(rows)


def rank_molecules(
    molecules: list[Chem.Mol],
    score_property: str,
    descending: bool,
) -> list[Chem.Mol]:
    """Rank molecules by an SDF score property and annotate their rank."""
    for molecule in molecules:
        if not molecule.HasProp(score_property):
            raise ValueError(
                f"Molecule is missing required score property '{score_property}'"
            )
    ranked = sorted(
        molecules,
        key=lambda molecule: float(molecule.GetProp(score_property)),
        reverse=descending,
    )
    for rank, molecule in enumerate(ranked, start=1):
        molecule.SetIntProp("rank", rank)
    return ranked


def join_diffdock_sdfs(input_dir: Path, output_sdf: Path) -> None:
    """Combine DiffDock rank files while preserving confidence and rank metadata."""
    files = sorted(input_dir.glob("rank*_confidence*.sdf"))
    if not files:
        raise FileNotFoundError(f"No DiffDock SDF files found in: {input_dir}")

    def parse_rank_conf(path: Path) -> tuple[int, float]:
        match = re.search(r"rank(\d+)_confidence([-\d\.eE]+)", path.stem)
        if match is None:
            raise ValueError(f"Unexpected DiffDock filename: {path.name}")
        return int(match.group(1)), float(match.group(2))

    with Chem.SDWriter(str(output_sdf)) as writer:
        for path in sorted(files, key=lambda item: parse_rank_conf(item)[0]):
            molecules = [mol for mol in Chem.SDMolSupplier(str(path), removeHs=False)]
            if len(molecules) != 1 or molecules[0] is None:
                raise ValueError(f"Expected exactly one valid molecule in {path}")
            rank, confidence = parse_rank_conf(path)
            molecule = molecules[0]
            molecule.SetIntProp("rank", rank)
            molecule.SetProp("confidence", f"{confidence:.6f}")
            writer.write(molecule)


def join_docking_sdfs(
    input_dir: Path,
    output_sdf: Path,
    score_property: str,
    descending: bool,
) -> None:
    """Combine all GNINA/Smina pose files and rank poses globally."""
    files = sorted(input_dir.glob("*_docked_*.sdf"))
    if not files:
        raise FileNotFoundError(f"No docking SDF files found in: {input_dir}")

    molecules: list[Chem.Mol] = []
    for path in files:
        for index, molecule in enumerate(Chem.SDMolSupplier(str(path), removeHs=False)):
            if molecule is None:
                raise ValueError(f"Invalid molecule at position {index} in {path}")
            molecules.append(molecule)

    with Chem.SDWriter(str(output_sdf)) as writer:
        for molecule in rank_molecules(molecules, score_property, descending):
            writer.write(molecule)


def run_posebusters(
    buster: PoseBusters,
    sdf_path: Path,
    receptor_path: Path,
    output_path: Path,
    overwrite: bool,
) -> None:
    """Run PoseBusters unless a valid cached output is available."""
    if file_ok(output_path) and not overwrite:
        return
    molecules = list(Chem.SDMolSupplier(str(sdf_path), removeHs=False))
    if not molecules or any(molecule is None for molecule in molecules):
        raise ValueError(f"Could not read all poses from {sdf_path}")
    results = buster.bust(molecules, None, receptor_path)
    results.to_csv(output_path, index=False)


def run_ost(
    sdf_path: Path,
    docked_receptor_path: Path,
    reference_receptor_path: Path,
    reference_ligand_path: Path,
    output_path: Path,
    overwrite: bool,
) -> None:
    """Run OST ligand-structure comparison unless cached output is available."""
    if file_ok(output_path) and not overwrite:
        return
    command = [
        "ost",
        "compare-ligand-structures",
        "-m",
        str(docked_receptor_path),
        "-ml",
        str(sdf_path),
        "-r",
        str(reference_receptor_path),
        "-rl",
        str(reference_ligand_path),
        "--lddt-pli",
        "--rmsd",
        "-o",
        str(output_path),
        "-v",
        "0",
        "--full-results",
    ]
    subprocess.run(command, check=True)


def process_complex(
    complex_dir: Path,
    structure_root: Path,
    method: str,
    mode: str,
    run_label: str,
    overwrite: bool,
    similarity_dict: dict[str, dict[str, str]] | None,
) -> pd.DataFrame:
    """Analyse all seeds for one complex."""
    complex_id = complex_dir.name
    RDLogger.DisableLog("rdApp.warning")
    buster = PoseBusters(config="dock")

    reference_receptor, reference_ligand = reference_paths(structure_root, complex_id)
    docked_receptor = docked_protein_path(structure_root, mode, complex_id)
    reference_mol = Chem.MolFromMolFile(str(reference_ligand), removeHs=False)
    if reference_mol is None:
        raise ValueError(f"Could not read reference ligand: {reference_ligand}")
    ligand_smiles = Chem.MolToSmiles(reference_mol)

    if method == "gnina":
        score_property, flip_sign, descending = "CNNscore", False, True
    elif method == "smina":
        score_property, flip_sign, descending = "minimizedAffinity", True, False
    elif method == "diffdock":
        score_property, flip_sign, descending = "confidence", False, True
    else:
        raise ValueError(f"Unsupported method: {method}")

    results: list[pd.DataFrame] = []
    for seed_dir in seed_dirs(complex_dir):
        raw_pose_dir = pose_dir(seed_dir)
        joined_sdf = seed_dir / f"{complex_id}_{run_label}_joined.sdf"

        if method == "diffdock":
            if not file_ok(joined_sdf) or overwrite:
                join_diffdock_sdfs(raw_pose_dir, joined_sdf)
        else:
            if not file_ok(joined_sdf) or overwrite:
                join_docking_sdfs(raw_pose_dir, joined_sdf, score_property, descending)

        pb_path = seed_dir / f"PB_{complex_id}_{run_label}.csv"
        run_posebusters(buster, joined_sdf, docked_receptor, pb_path, overwrite)
        ost_path = seed_dir / f"OST_{complex_id}_{run_label}.json"
        run_ost(
            joined_sdf,
            docked_receptor,
            reference_receptor,
            reference_ligand,
            ost_path,
            overwrite,
        )

        pose_df = sdf_to_pose_df(joined_sdf, score_property, flip_sign=flip_sign)
        pb_df = posebusters_to_df(pb_path)
        ost_df = ost_to_df(ost_path)
        ost_df["compare_id"] = complex_id

        df = pose_df.merge(pb_df, on="sample", how="left", validate="one_to_one").merge(
            ost_df, on="sample", how="left", validate="one_to_one"
        )
        df = add_similarity_metrics(df, similarity_dict)
        df["dock_prot"] = mode
        df["complex_id"] = complex_id
        df["seed"] = seed_dir.name
        df["method"] = method
        df["ligand_smiles"] = ligand_smiles
        results.append(df)

    return pd.concat(results, ignore_index=True)


def build_parser() -> argparse.ArgumentParser:
    """Build the command-line parser."""
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument(
        "run_dir", type=Path, help="One method/mode docking run directory."
    )
    parser.add_argument("--method", required=True, choices=sorted(SUPPORTED_METHODS))
    parser.add_argument("--mode", required=True, help="Prepared docking mode name.")
    parser.add_argument(
        "--similarity-tsv",
        type=Path,
        nargs="+",
        default=None,
        help="Optional similarity TSV file(s).",
    )
    parser.add_argument(
        "--num-workers",
        "-j",
        type=int,
        default=8,
        help="Number of complexes analysed in parallel (default: 8).",
    )
    parser.add_argument(
        "--overwrite",
        action="store_true",
        help="Recompute cached OST/PoseBusters outputs.",
    )
    parser.add_argument(
        "--output-dir",
        type=Path,
        default=None,
        help="Analysis root (default: sibling analysis directory).",
    )
    parser.add_argument("--suffix", default="", help="Optional output filename suffix.")
    parser.add_argument("--verbose", "-v", action="store_true")
    return parser


def main() -> None:
    """Run docking analysis."""
    args = build_parser().parse_args()
    logging.basicConfig(
        level=logging.DEBUG if args.verbose else logging.INFO,
        format="%(asctime)s %(levelname)s %(message)s",
        datefmt="%Y-%m-%d %H:%M:%S",
    )
    logging.getLogger("posebusters").setLevel(logging.ERROR)
    RDLogger.DisableLog("rdApp.warning")

    if shutil.which("ost") is None:
        raise FileNotFoundError("OST executable 'ost' was not found on PATH")
    if args.num_workers < 1:
        raise ValueError("--num-workers must be at least 1")

    run_dir = args.run_dir.expanduser().resolve()
    if not run_dir.is_dir():
        raise FileNotFoundError(f"Docking run directory not found: {run_dir}")
    expected_name = f"{args.method}_{args.mode}"
    if run_dir.name != expected_name:
        raise ValueError(
            f"Run directory name must be '{expected_name}', got '{run_dir.name}'"
        )

    structure_root = structure_root_from_run(run_dir)
    output_dir = (
        args.output_dir.expanduser().resolve()
        if args.output_dir is not None
        else run_dir.parent.parent / "analysis"
    )
    similarity_dict = load_similarity_dicts(args.similarity_tsv)
    run_label = run_dir.name

    complex_dirs = sorted(path for path in run_dir.iterdir() if path.is_dir())
    if not complex_dirs:
        raise ValueError(f"No complex directories found in: {run_dir}")

    all_results: list[pd.DataFrame] = []
    failures: list[tuple[str, str]] = []
    jobs = [
        (
            complex_dir,
            structure_root,
            args.method,
            args.mode,
            run_label,
            args.overwrite,
            similarity_dict,
        )
        for complex_dir in complex_dirs
    ]

    with ProcessPoolExecutor(max_workers=args.num_workers) as executor:
        futures = {executor.submit(process_complex, *job): job[0].name for job in jobs}
        for future in as_completed(futures):
            complex_id = futures[future]
            try:
                all_results.append(future.result())
                logging.info("Finished %s", complex_id)
            except Exception as exc:
                failures.append((complex_id, str(exc)))
                logging.exception("Failed %s", complex_id)

    if not all_results:
        raise RuntimeError("Analysis produced no results")

    final_df = pd.concat(all_results, ignore_index=True)
    column_order = [
        "complex_id",
        "dock_prot",
        "method",
        "seed",
        "sample",
        "rank_score",
        "pb_valid",
        "lig_rmsd",
        "lddt_pli",
        "compare_id",
        "lddt_lp",
        "pocket_bb_rmsd",
        "rmsd_chain_mapping",
        "ligand_smiles",
    ]
    existing = [column for column in column_order if column in final_df.columns]
    extra = [column for column in final_df.columns if column not in column_order]
    final_df = final_df[existing + extra]

    suffix = args.suffix
    if suffix and not suffix.startswith("_"):
        suffix = f"_{suffix}"
    base_name = f"{run_label}{suffix}"
    csv_dir = output_dir / "csv"
    parquet_dir = output_dir / "parquet"
    csv_dir.mkdir(parents=True, exist_ok=True)
    parquet_dir.mkdir(parents=True, exist_ok=True)
    final_df.to_csv(csv_dir / f"{base_name}.csv", index=False)
    final_df.to_parquet(parquet_dir / f"{base_name}.parquet", index=False)

    logging.info("Wrote %d pose rows for %s", len(final_df), run_label)
    if failures:
        failure_path = output_dir / "logs" / f"{run_label}_failed_complexes.tsv"
        failure_path.parent.mkdir(parents=True, exist_ok=True)
        with failure_path.open("w", encoding="utf-8") as handle:
            handle.write("complex_id\treason\n")
            for complex_id, reason in failures:
                handle.write(
                    f"{complex_id}\t{reason.replace(chr(9), ' ').replace(chr(10), ' ')}\n"
                )
        raise SystemExit(f"Analysis completed with {len(failures)} failed complexes")


if __name__ == "__main__":
    main()