File size: 5,043 Bytes
c289d87
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24f6204
c289d87
 
24f6204
 
 
 
 
 
c289d87
24f6204
c289d87
 
 
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
from __future__ import annotations

import csv
import math
import re
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Iterable

from .provenance import RDockPipelineError, require_file

TAG_RE = re.compile(r"^>\s*<\s*([^>]+?)\s*>", flags=re.IGNORECASE)


@dataclass(frozen=True)
class SDFRecord:
    block: str
    index: int
    ligand_id: str
    score: float | None
    tags: dict[str, str]
    numeric_tags: dict[str, float]


def split_sdf_text(text: str) -> list[str]:
    blocks: list[str] = []
    for part in text.split("$$$$"):
        body = part.strip()
        if body:
            blocks.append(body + "\n$$$$\n")
    return blocks


def split_sdf_file(path: str | Path) -> list[str]:
    source = require_file(path, "SDF file")
    blocks = split_sdf_text(source.read_text(encoding="utf-8", errors="ignore"))
    if not blocks:
        raise RDockPipelineError(f"No SDF records found in {source}")
    return blocks


def parse_tags(block: str) -> dict[str, str]:
    lines = block.splitlines()
    tags: dict[str, str] = {}
    i = 0
    while i < len(lines):
        m = TAG_RE.match(lines[i].strip())
        if not m:
            i += 1
            continue
        key = m.group(1).strip()
        values: list[str] = []
        j = i + 1
        while j < len(lines) and lines[j].strip() and lines[j].strip() != "$$$$" and not TAG_RE.match(lines[j].strip()):
            values.append(lines[j].strip())
            j += 1
        tags[key] = "\n".join(values).strip()
        i = j
    return tags


def _safe_float(value: Any) -> float | None:
    try:
        out = float(str(value).strip())
    except Exception:
        return None
    if not math.isfinite(out):
        return None
    return out


def _record_name(block: str, fallback: str) -> str:
    first = block.splitlines()[0].strip() if block.splitlines() else ""
    return first or fallback


def ligand_id_from_block(block: str, tags: dict[str, str], index: int) -> str:
    for key in ("ligand_id", "LigandID", "LIGAND_ID", "ID", "Name", "_Name"):
        value = tags.get(key)
        if value:
            return value.split()[0].strip()
    return _record_name(block, f"ligand_{index:06d}").split()[0].strip()


def parse_rdock_sdf_records(path: str | Path, require_score: bool = True) -> list[SDFRecord]:
    records: list[SDFRecord] = []
    for idx, block in enumerate(split_sdf_file(path)):
        tags = parse_tags(block)
        numeric = {k: v for k, raw in tags.items() if (v := _safe_float(raw)) is not None}
        score = numeric.get("SCORE")
        if require_score and score is None:
            raise RDockPipelineError(f"Missing required rDock SCORE field in SDF record {idx} of {path}")
        records.append(
            SDFRecord(
                block=block,
                index=idx,
                ligand_id=ligand_id_from_block(block, tags, idx),
                score=score,
                tags=tags,
                numeric_tags=numeric,
            )
        )
    return records


def write_sdf_records(records: Iterable[SDFRecord], path: str | Path) -> Path:
    target = Path(path)
    target.parent.mkdir(parents=True, exist_ok=True)
    target.write_text("".join(rec.block for rec in records), encoding="utf-8")
    return target


def write_sdf_blocks(blocks: Iterable[str], path: str | Path) -> Path:
    target = Path(path)
    target.parent.mkdir(parents=True, exist_ok=True)
    target.write_text("".join(blocks), encoding="utf-8")
    return target


def best_per_ligand(records: Iterable[SDFRecord]) -> list[SDFRecord]:
    best: dict[str, SDFRecord] = {}
    for rec in records:
        if rec.score is None:
            raise RDockPipelineError(f"Cannot rank ligand {rec.ligand_id}: missing SCORE")
        prev = best.get(rec.ligand_id)
        if prev is None or float(rec.score) < float(prev.score):
            best[rec.ligand_id] = rec
    return sorted(best.values(), key=lambda r: (float(r.score), r.ligand_id, r.index))


def records_to_rows(records: Iterable[SDFRecord]) -> list[dict[str, object]]:
    rows: list[dict[str, object]] = []
    for rec in records:
        row: dict[str, object] = {
            "pose_index": rec.index,
            "ligand_id": rec.ligand_id,
            "SCORE": rec.score,
        }
        for key, value in sorted(rec.numeric_tags.items()):
            row[key] = value
        rows.append(row)
    return rows


def write_rows_csv(rows: list[dict[str, object]], path: str | Path, fieldnames: list[str] | None = None) -> Path:
    target = Path(path)
    target.parent.mkdir(parents=True, exist_ok=True)
    fields: list[str] = list(fieldnames or [])
    if not fields:
        for row in rows:
            for key in row:
                if key not in fields:
                    fields.append(key)
    with target.open("w", encoding="utf-8", newline="") as handle:
        writer = csv.DictWriter(handle, fieldnames=fields, extrasaction="ignore")
        writer.writeheader()
        writer.writerows(rows)
    return target