File size: 16,536 Bytes
0cb481f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Small, CPU-only tests for the resumable direct compact_v1 builder."""

from __future__ import annotations

import json
import tempfile
import time
import unittest
from pathlib import Path
from unittest import mock

import torch
from torch_geometric.data import Data

import build_compact_v1_direct as direct
from compact_graph_dataset import CompactGraphDataset


def _synthetic_graph(
    system_id: str,
    pose_number: int,
    *,
    split_static: bool = False,
) -> Data:
    n_protein = 2
    n_nodes = 4
    x = torch.zeros((n_nodes, 82), dtype=torch.float32)
    x[:, 0] = 1.0
    x[:n_protein, 11] = 1.0
    x[n_protein:, 31] = 1.0
    x[:n_protein, 32] = 1.0
    x[n_protein:, 33] = 1.0
    x[:, 61:71] = 0.25
    x[:, 34:61] = float(pose_number)
    x[:, 71:82] = float(pose_number) / 10.0
    if split_static and pose_number == 2:
        x[2, 0] = 0.0
        x[2, 1] = 1.0

    system_offset = 5.0 if system_id == "sys_b" else 0.0
    protein_pos = torch.tensor(
        [[system_offset, 0.0, 0.0], [system_offset + 1.0, 0.0, 0.0]],
        dtype=torch.float32,
    )
    ligand_pos = torch.tensor(
        [
            [system_offset + 1.5, 0.1 * pose_number, 0.0],
            [system_offset + 2.0, 0.2 * pose_number, 0.0],
        ],
        dtype=torch.float32,
    )
    native_ligand = torch.tensor(
        [
            [system_offset + 1.5, 0.0, 0.0],
            [system_offset + 2.0, 0.0, 0.0],
        ],
        dtype=torch.float32,
    )
    pos = torch.cat((protein_pos, ligand_pos), dim=0)
    y_grt = torch.cat((protein_pos, native_ligand), dim=0)
    y_true = torch.linalg.vector_norm(pos - y_grt, dim=1, keepdim=True)
    edge_index = torch.tensor(
        [[0, 1, 1, 2, 2, 3], [1, 0, 2, 1, 3, 2]],
        dtype=torch.int64,
    )
    src, dst = edge_index
    distance = torch.linalg.vector_norm(
        pos[src].to(torch.float64) - pos[dst].to(torch.float64),
        dim=1,
    )
    edge_attr = torch.stack(
        (
            (distance / 6.0).to(torch.float32),
            torch.exp(-distance / 3.0).to(torch.float32),
            (src < n_protein).to(torch.float32),
            (dst < n_protein).to(torch.float32),
        ),
        dim=1,
    )
    is_protein = torch.zeros((n_nodes, 1), dtype=torch.float32)
    is_protein[:n_protein] = 1.0
    return Data(
        x=x,
        edge_index=edge_index,
        edge_attr=edge_attr,
        pos=pos,
        is_protein=is_protein,
        y_true=y_true,
        y_pred=pos.clone(),
        y_grt=y_grt,
        num_nodes=n_nodes,
    )


class DirectCompactBuilderTest(unittest.TestCase):
    def test_exclusive_output_lock_rejects_concurrent_resume(self) -> None:
        with tempfile.TemporaryDirectory(prefix="direct_compact_lock_") as temp:
            output = Path(temp) / "compact"
            with direct._exclusive_build_lock(output):
                with self.assertRaisesRegex(
                    RuntimeError, "another direct compact build"
                ):
                    with direct._exclusive_build_lock(output):
                        self.fail("the second lock must not be acquired")

    def test_corrupt_pose_checkpoint_is_rebuilt(self) -> None:
        with tempfile.TemporaryDirectory(prefix="direct_compact_corrupt_") as temp:
            root = Path(temp)
            for name in ("protein.pdb", "native.pdb", "pose_1.pdb"):
                (root / name).write_text("test\n", encoding="utf-8")
            pose = direct.PoseSpec(
                source_graph_index=0,
                system_id="sys_a",
                protein=(root / "protein.pdb"),
                ligand_native=(root / "native.pdb"),
                ligand_pred=(root / "pose_1.pdb"),
            )
            system = direct.SystemSpec(
                ordinal=0,
                system_id="sys_a",
                protein=pose.protein,
                ligand_native=pose.ligand_native,
                poses=(pose,),
            )
            work_dir = root / "work"
            work_dir.mkdir()
            corrupt = direct._pose_graph_path(work_dir, 0)
            corrupt.write_bytes(b"not a torch checkpoint")
            calls = []

            def graph_builder(**kwargs):
                calls.append(kwargs["ligand_pred_pdb"])
                return _synthetic_graph("sys_a", 1)

            config = direct.BuildConfig(
                data_dir=root,
                output_dir=root / "output",
                method="protenix",
            )
            graphs = direct.build_pose_graphs(
                system,
                work_dir,
                config,
                graph_builder=graph_builder,
            )
            self.assertEqual(len(calls), 1)
            self.assertEqual(len(graphs), 1)
            rebuilt = torch.load(corrupt, map_location="cpu", weights_only=False)
            self.assertTrue(torch.equal(rebuilt.x, graphs[0].x))

    def test_resume_atomic_publish_and_original_system_index(self) -> None:
        with tempfile.TemporaryDirectory(prefix="direct_compact_test_") as temp:
            root = Path(temp)
            data_dir = root / "docking"
            output_dir = root / "compact"
            raw_poses = []
            for system_id in ("sys_a", "sys_b"):
                system_dir = data_dir / system_id
                system_dir.mkdir(parents=True)
                protein = system_dir / "protein.pdb"
                native = system_dir / "ligand_native.pdb"
                protein.write_text("test\n", encoding="utf-8")
                native.write_text("test\n", encoding="utf-8")
                for pose_number in (1, 2):
                    pose = system_dir / f"{system_id}_pose_{pose_number}.pdb"
                    pose.write_text("test\n", encoding="utf-8")
                    raw_poses.append(
                        {
                            "pdb_id": system_id,
                            "protein": str(protein),
                            "ligand_native": str(native),
                            "ligand_pred": str(pose),
                        }
                    )

            def graph_builder(**kwargs):
                pose_path = Path(kwargs["ligand_pred_pdb"])
                system_id = pose_path.parent.name
                pose_number = int(pose_path.stem.rsplit("_", 1)[1])
                return _synthetic_graph(
                    system_id,
                    pose_number,
                    split_static=system_id == "sys_b",
                )

            def first_attempt_builder(**kwargs):
                if Path(kwargs["ligand_pred_pdb"]).parent.name == "sys_b":
                    raise RuntimeError("intentional interruption")
                return graph_builder(**kwargs)

            config = direct.BuildConfig(
                data_dir=data_dir.resolve(),
                output_dir=output_dir.resolve(),
                method="protenix",
                target_shard_mib=1,
                num_workers=1,
            )
            with mock.patch.object(direct, "find_docking_poses", return_value=raw_poses):
                with self.assertRaisesRegex(RuntimeError, "intentional interruption"):
                    direct.run(config, graph_builder=first_attempt_builder)

                progress_path = (
                    output_dir.with_name(".compact.building")
                    / ".build_state"
                    / "progress.json"
                )
                with progress_path.open("r", encoding="utf-8") as handle:
                    progress = json.load(handle)
                self.assertEqual(progress["next_system_index"], 1)
                self.assertEqual(progress["successful_source_systems"], 1)

                resumed = direct.BuildConfig(
                    **{**config.__dict__, "resume": True}
                )
                manifest = direct.run(resumed, graph_builder=graph_builder)

            self.assertTrue((output_dir / "manifest.json").is_file())
            self.assertFalse(output_dir.with_name(".compact.building").exists())
            self.assertFalse((output_dir / ".build_state").exists())
            self.assertEqual(manifest["n_graphs"], 4)
            self.assertEqual(manifest["n_source_systems"], 2)
            # sys_b is intentionally split into two exact-content storage groups.
            self.assertEqual(manifest["n_systems"], 3)

            with (output_dir / "system_index.json").open(
                "r", encoding="utf-8"
            ) as handle:
                system_index = json.load(handle)
            self.assertEqual(
                system_index["graph_to_system"],
                ["sys_a", "sys_a", "sys_b", "sys_b"],
            )
            self.assertEqual(system_index["n_systems"], 2)

            dataset = CompactGraphDataset(output_dir)
            self.assertEqual(len(dataset), 4)
            expected = [
                _synthetic_graph("sys_a", 1),
                _synthetic_graph("sys_a", 2),
                _synthetic_graph("sys_b", 1, split_static=True),
                _synthetic_graph("sys_b", 2, split_static=True),
            ]
            for actual, reference in zip(dataset, expected):
                for name in (
                    "x",
                    "edge_index",
                    "edge_attr",
                    "pos",
                    "is_protein",
                    "y_true",
                    "y_pred",
                    "y_grt",
                ):
                    self.assertTrue(
                        torch.allclose(
                            getattr(actual, name),
                            getattr(reference, name),
                            rtol=1e-6,
                            atol=1e-6,
                        ),
                        msg=name,
                    )

    def test_parallel_system_build_matches_serial_order(self) -> None:
        """Out-of-order worker completion must not change source graph order."""
        with tempfile.TemporaryDirectory(prefix="direct_compact_parallel_") as temp:
            root = Path(temp)
            data_dir = root / "docking"
            raw_poses = []
            for system_id in ("sys_a", "sys_b", "sys_c"):
                system_dir = data_dir / system_id
                system_dir.mkdir(parents=True)
                protein = system_dir / "protein.pdb"
                native = system_dir / "ligand_native.pdb"
                protein.write_text("test\n", encoding="utf-8")
                native.write_text("test\n", encoding="utf-8")
                for pose_number in (1, 2):
                    pose = system_dir / f"{system_id}_pose_{pose_number}.pdb"
                    pose.write_text("test\n", encoding="utf-8")
                    raw_poses.append(
                        {
                            "pdb_id": system_id,
                            "protein": str(protein),
                            "ligand_native": str(native),
                            "ligand_pred": str(pose),
                        }
                    )

            def graph_builder(**kwargs):
                pose_path = Path(kwargs["ligand_pred_pdb"])
                system_id = pose_path.parent.name
                # sys_a is deliberately slower so workers complete out of order.
                if system_id == "sys_a":
                    time.sleep(0.15)
                pose_number = int(pose_path.stem.rsplit("_", 1)[1])
                return _synthetic_graph(system_id, pose_number)

            serial_output = root / "serial"
            parallel_output = root / "parallel"
            serial_config = direct.BuildConfig(
                data_dir=data_dir.resolve(),
                output_dir=serial_output.resolve(),
                method="protenix",
                target_shard_mib=1,
                num_workers=1,
            )
            parallel_config = direct.BuildConfig(
                data_dir=data_dir.resolve(),
                output_dir=parallel_output.resolve(),
                method="protenix",
                target_shard_mib=1,
                num_workers=1,
                system_workers=2,
                memory_budget_gib=8.0,
            )
            with mock.patch.object(direct, "find_docking_poses", return_value=raw_poses):
                serial_manifest = direct.run(serial_config, graph_builder=graph_builder)
                parallel_manifest = direct.run(parallel_config, graph_builder=graph_builder)

            self.assertEqual(serial_manifest["n_graphs"], parallel_manifest["n_graphs"])
            self.assertEqual(serial_manifest["graph_map"], parallel_manifest["graph_map"])
            self.assertEqual(serial_manifest["shards"], parallel_manifest["shards"])
            with (serial_output / "system_index.json").open("r", encoding="utf-8") as handle:
                serial_index = json.load(handle)
            with (parallel_output / "system_index.json").open("r", encoding="utf-8") as handle:
                parallel_index = json.load(handle)
            self.assertEqual(serial_index, parallel_index)

    def test_parallel_ready_checkpoint_resumes_in_source_order(self) -> None:
        """A later ready system survives interruption before the earlier system."""
        with tempfile.TemporaryDirectory(prefix="direct_compact_parallel_resume_") as temp:
            root = Path(temp)
            data_dir = root / "docking"
            output_dir = root / "compact"
            raw_poses = []
            for system_id in ("sys_a", "sys_b"):
                system_dir = data_dir / system_id
                system_dir.mkdir(parents=True)
                protein = system_dir / "protein.pdb"
                native = system_dir / "ligand_native.pdb"
                protein.write_text("test\n", encoding="utf-8")
                native.write_text("test\n", encoding="utf-8")
                for pose_number in (1, 2):
                    pose = system_dir / f"{system_id}_pose_{pose_number}.pdb"
                    pose.write_text("test\n", encoding="utf-8")
                    raw_poses.append(
                        {
                            "pdb_id": system_id,
                            "protein": str(protein),
                            "ligand_native": str(native),
                            "ligand_pred": str(pose),
                        }
                    )

            def graph_builder(**kwargs):
                pose_path = Path(kwargs["ligand_pred_pdb"])
                system_id = pose_path.parent.name
                pose_number = int(pose_path.stem.rsplit("_", 1)[1])
                return _synthetic_graph(system_id, pose_number)

            def interrupted_builder(**kwargs):
                pose_path = Path(kwargs["ligand_pred_pdb"])
                if pose_path.parent.name == "sys_a":
                    time.sleep(0.35)
                    raise RuntimeError("intentional parallel interruption")
                return graph_builder(**kwargs)

            config = direct.BuildConfig(
                data_dir=data_dir.resolve(),
                output_dir=output_dir.resolve(),
                method="protenix",
                target_shard_mib=1,
                num_workers=1,
                system_workers=2,
                memory_budget_gib=8.0,
            )
            with mock.patch.object(direct, "find_docking_poses", return_value=raw_poses):
                with self.assertRaisesRegex(RuntimeError, "parallel worker.*sys_a"):
                    direct.run(config, graph_builder=interrupted_builder)

                stage_dir = output_dir.with_name(".compact.building")
                progress_path = stage_dir / ".build_state" / "progress.json"
                with progress_path.open("r", encoding="utf-8") as handle:
                    progress = json.load(handle)
                self.assertEqual(progress["next_system_index"], 0)
                self.assertTrue(
                    (stage_dir / ".build_state" / "ready" / "system_00000001.pt").is_file()
                )

                resumed = direct.BuildConfig(**{**config.__dict__, "resume": True})
                manifest = direct.run(resumed, graph_builder=graph_builder)

            self.assertEqual(manifest["n_graphs"], 4)
            with (output_dir / "system_index.json").open("r", encoding="utf-8") as handle:
                system_index = json.load(handle)
            self.assertEqual(
                system_index["graph_to_system"], ["sys_a", "sys_a", "sys_b", "sys_b"]
            )


if __name__ == "__main__":
    unittest.main()