File size: 11,888 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
#!/usr/bin/env python3
"""Tiny synthetic round-trip test for CompactGraphDataset.

The test creates only a few dozen tensor values in a temporary directory.  It
does not read any production dataset.
"""

from __future__ import annotations

import json
import pickle
import subprocess
import sys
import tempfile
import unittest
from pathlib import Path
from typing import Dict, List, Sequence, Tuple

import torch
from torch_geometric.data import Data
from torch_geometric.loader import DataLoader

from compact_graph_dataset import CompactGraphDataset


CUTOFF = 2.5


def _upper_edges(pos: torch.Tensor, n_protein: int) -> Tuple[torch.Tensor, torch.Tensor]:
    pairs: List[Tuple[int, int]] = []
    nonpp: List[Tuple[int, int]] = []
    for src in range(pos.shape[0]):
        for dst in range(src + 1, pos.shape[0]):
            distance = torch.sqrt(
                torch.sum(
                    (pos[src].to(torch.float64) - pos[dst].to(torch.float64)) ** 2
                )
            )
            if float(distance) <= CUTOFF:
                if dst < n_protein:
                    pairs.append((src, dst))
                else:
                    nonpp.append((src, dst))
    pp_tensor = (
        torch.tensor(pairs, dtype=torch.int32).t().contiguous()
        if pairs
        else torch.empty((2, 0), dtype=torch.int32)
    )
    nonpp_tensor = (
        torch.tensor(nonpp, dtype=torch.int32).t().contiguous()
        if nonpp
        else torch.empty((2, 0), dtype=torch.int32)
    )
    return pp_tensor, nonpp_tensor


def _legacy_graph(
    static: torch.Tensor,
    dynamic: torch.Tensor,
    protein: torch.Tensor,
    ligand: torch.Tensor,
    native: torch.Tensor,
    pp_upper: torch.Tensor,
    nonpp_upper: torch.Tensor,
) -> Data:
    n_protein = protein.shape[0]
    n = static.shape[0]
    x = torch.empty((n, 82), dtype=torch.float32)
    x[:, :34] = static[:, :34]
    x[:, 34:61] = dynamic[:, :27]
    x[:, 61:71] = static[:, 34:44]
    x[:, 71:82] = dynamic[:, 27:38]
    pos = torch.cat((protein, ligand), dim=0)
    y_grt = torch.cat((protein, native), dim=0)
    is_protein = torch.zeros((n, 1), dtype=torch.float32)
    is_protein[:n_protein] = 1
    y_true = torch.zeros((n, 1), dtype=torch.float32)
    y_true[n_protein:, 0] = torch.sqrt(
        torch.sum((ligand - native) ** 2, dim=1)
    )

    upper = torch.cat((pp_upper.to(torch.int64), nonpp_upper.to(torch.int64)), dim=1)
    src = torch.cat((upper[0], upper[1]))
    dst = torch.cat((upper[1], upper[0]))
    distance = torch.sqrt(
        torch.sum(
            (
                pos[upper[0]].to(torch.float64)
                - pos[upper[1]].to(torch.float64)
            )
            ** 2,
            dim=1,
        )
    )
    attr0 = torch.cat(((distance / CUTOFF).float(), (distance / CUTOFF).float()))
    attr1 = torch.cat((torch.exp(-distance / 3).float(), torch.exp(-distance / 3).float()))
    order = torch.argsort(src * n + dst)
    src, dst = src[order], dst[order]
    edge_index = torch.stack((src, dst))
    edge_attr = torch.stack(
        (
            attr0[order],
            attr1[order],
            (src < n_protein).float(),
            (dst < n_protein).float(),
        ),
        dim=1,
    )
    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,
        y_grt=y_grt,
        num_nodes=n,
    )


def _make_dataset(root: Path) -> Sequence[Data]:
    generator = torch.Generator().manual_seed(17)

    protein_a = torch.tensor(
        [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]],
        dtype=torch.float32,
    )
    native_a = torch.tensor([[1.4, 1.1, 0.0], [2.0, 1.0, 0.0]], dtype=torch.float32)
    ligands_a = [
        native_a + torch.tensor([[0.1, 0.0, 0.0], [0.0, -0.2, 0.1]]),
        native_a + torch.tensor([[-0.2, 0.1, 0.0], [0.2, 0.0, -0.1]]),
    ]
    protein_b = torch.tensor([[10.0, 0.0, 0.0], [11.0, 0.0, 0.0]], dtype=torch.float32)
    native_b = torch.tensor([[10.5, 1.0, 0.0]], dtype=torch.float32)
    ligands_b = [native_b + torch.tensor([[0.0, 0.2, -0.1]])]

    systems = [
        (protein_a, native_a, ligands_a),
        (protein_b, native_b, ligands_b),
    ]
    static_parts = [
        torch.randn((protein.shape[0] + native.shape[0], 44), generator=generator)
        for protein, native, _ in systems
    ]
    pp_parts: List[torch.Tensor] = []
    for protein, native, _ in systems:
        pp, _ = _upper_edges(torch.cat((protein, native), dim=0), protein.shape[0])
        pp_parts.append(pp)

    # Local pose order: A0, A1, B0.  Original/source order: B0, A0, A1.
    pose_system = torch.tensor([0, 0, 1], dtype=torch.int32)
    source_graph_index = torch.tensor([1, 2, 0], dtype=torch.int64)
    dynamic_parts: List[torch.Tensor] = []
    ligand_parts: List[torch.Tensor] = []
    nonpp_parts: List[torch.Tensor] = []
    local_graphs: List[Data] = []
    for system_index, (_, _, ligands) in enumerate(systems):
        protein, native, _ = systems[system_index]
        for ligand in ligands:
            n = protein.shape[0] + ligand.shape[0]
            dynamic = torch.randn((n, 38), generator=generator)
            _, nonpp = _upper_edges(torch.cat((protein, ligand), dim=0), protein.shape[0])
            dynamic_parts.append(dynamic)
            ligand_parts.append(ligand)
            nonpp_parts.append(nonpp)
            local_graphs.append(
                _legacy_graph(
                    static_parts[system_index],
                    dynamic,
                    protein,
                    ligand,
                    native,
                    pp_parts[system_index],
                    nonpp,
                )
            )

    def pointer(lengths: Sequence[int]) -> torch.Tensor:
        result = [0]
        for length in lengths:
            result.append(result[-1] + int(length))
        return torch.tensor(result, dtype=torch.int64)

    shard: Dict[str, torch.Tensor] = {
        "schema_version": torch.tensor([1], dtype=torch.int32),
        "system_graph_ptr": torch.tensor([0, 2, 3], dtype=torch.int64),
        "pose_system": pose_system,
        "source_graph_index": source_graph_index,
        "system_node_ptr": pointer([part.shape[0] for part in static_parts]),
        "n_protein": torch.tensor(
            [protein.shape[0] for protein, _, _ in systems], dtype=torch.int32
        ),
        "x_static": torch.cat(static_parts, dim=0),
        "protein_ptr": pointer([protein.shape[0] for protein, _, _ in systems]),
        "protein_pos": torch.cat([protein for protein, _, _ in systems], dim=0),
        "native_ligand_ptr": pointer([native.shape[0] for _, native, _ in systems]),
        "native_ligand_pos": torch.cat([native for _, native, _ in systems], dim=0),
        "pose_node_ptr": pointer([part.shape[0] for part in dynamic_parts]),
        "x_dynamic": torch.cat(dynamic_parts, dim=0),
        "pose_ligand_ptr": pointer([part.shape[0] for part in ligand_parts]),
        "ligand_pos": torch.cat(ligand_parts, dim=0),
        "pp_edge_ptr": pointer([part.shape[1] for part in pp_parts]),
        "pp_edge_upper": torch.cat(pp_parts, dim=1),
        "nonpp_edge_ptr": pointer([part.shape[1] for part in nonpp_parts]),
        "nonpp_edge_upper": torch.cat(nonpp_parts, dim=1),
    }
    (root / "shards").mkdir()
    torch.save(shard, root / "shards" / "shard_00000.pt")
    manifest = {
        "format": "gnncp_compact_v1",
        "schema_version": 1,
        "cutoff": CUTOFF,
        "num_graphs": 3,
        "static_columns": [[0, 34], [61, 71]],
        "dynamic_columns": [[34, 61], [71, 82]],
        "shards": [
            {
                "path": "shards/shard_00000.pt",
                "num_graphs": 3,
                "system_ids": ["system_a", "system_b"],
            }
        ],
        "graph_map": [[0, 2], [0, 0], [0, 1]],
    }
    (root / "manifest.json").write_text(json.dumps(manifest), encoding="utf-8")
    return [local_graphs[2], local_graphs[0], local_graphs[1]]


class CompactGraphDatasetTest(unittest.TestCase):
    def test_round_trip_and_batch(self) -> None:
        with tempfile.TemporaryDirectory() as temporary:
            root = Path(temporary)
            references = _make_dataset(root)
            dataset = CompactGraphDataset(root)
            self.assertEqual(len(dataset), 3)
            for index, reference in enumerate(references):
                actual = dataset[index]
                for field in (
                    "x",
                    "edge_index",
                    "edge_attr",
                    "pos",
                    "is_protein",
                    "y_true",
                    "y_pred",
                    "y_grt",
                ):
                    self.assertTrue(
                        torch.equal(getattr(actual, field), getattr(reference, field)),
                        msg=f"mismatch at graph={index}, field={field}",
                    )
                self.assertEqual(dataset.metadata(index)["source_graph_index"], index)

            batch = next(iter(DataLoader(dataset, batch_size=2, shuffle=False)))
            self.assertEqual(batch.x.shape[1], 82)
            self.assertEqual(batch.edge_attr.shape[1], 4)
            self.assertEqual(batch.num_graphs, 2)

            # DataLoader spawn/fork must not serialise mmap shard objects.
            restored = pickle.loads(pickle.dumps(dataset))
            self.assertEqual(len(restored._cache), 0)
            self.assertTrue(torch.equal(restored[-1].x, references[-1].x))

    def test_converter_cli_round_trip(self) -> None:
        with tempfile.TemporaryDirectory() as temporary:
            root = Path(temporary)
            seed_root = root / "seed"
            seed_root.mkdir()
            references = _make_dataset(seed_root)
            legacy = root / "legacy.pt"
            system_index = root / "system_index.json"
            output = root / "converted"
            torch.save(list(references), legacy)
            system_index.write_text(
                json.dumps(
                    {"graph_to_system": ["system_b", "system_a", "system_a"]}
                ),
                encoding="utf-8",
            )
            script = Path(__file__).with_name("convert_to_compact_v1.py")
            subprocess.run(
                [
                    sys.executable,
                    str(script),
                    "--input",
                    str(legacy),
                    "--output-dir",
                    str(output),
                    "--method",
                    "synthetic",
                    "--system-index",
                    str(system_index),
                    "--target-shard-mib",
                    "1",
                    "--cutoff",
                    str(CUTOFF),
                ],
                check=True,
                cwd=script.parent,
                capture_output=True,
                text=True,
            )

            dataset = CompactGraphDataset(output)
            self.assertEqual(len(dataset), len(references))
            for index, reference in enumerate(references):
                actual = dataset[index]
                for field in (
                    "x",
                    "edge_index",
                    "edge_attr",
                    "pos",
                    "is_protein",
                    "y_true",
                    "y_pred",
                    "y_grt",
                ):
                    self.assertTrue(
                        torch.equal(getattr(actual, field), getattr(reference, field)),
                        msg=f"writer round-trip mismatch graph={index}, field={field}",
                    )
                self.assertEqual(dataset.metadata(index)["source_graph_index"], index)


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