Download code/compact_v1/test_compact_graph_dataset.py from liofoil/copuladock: direct link, hf CLI and curl.
- Browser
- Download file 11.9 kB
-
https://huggingface.co/datasets/liofoil/copuladock/resolve/main/code/compact_v1/test_compact_graph_dataset.py
- Command line
-
hf download hf://datasets/liofoil/copuladock/code/compact_v1/test_compact_graph_dataset.py
-
curl -L -o test_compact_graph_dataset.py https://huggingface.co/datasets/liofoil/copuladock/resolve/main/code/compact_v1/test_compact_graph_dataset.py
11.9 kB
| #!/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() | |