File size: 2,381 Bytes
0cef53c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import math

import pytest
import torch
from conftest import random_events

from gnn4colliders.data import pack_events
from gnn4colliders.graphs import (
    PADDING_GRAPHS,
    StaticGraphBatch,
    collate_graph_batch,
    edge_features,
    fully_connected_edges,
    graph_batch_capacity,
)
from gnn4colliders.models import EdgeNetwork


def test_fully_connected_edges_are_source_major_without_self_loops():
    src, dst, counts = fully_connected_edges(torch.tensor([3, 1, 2]))
    assert counts.tolist() == [6, 1, 2]
    pairs = list(zip(src.tolist(), dst.tolist()))
    assert pairs[:6] == [(0, 1), (0, 2), (1, 0), (1, 2), (2, 0), (2, 1)]
    # A one-node graph keeps its single self-loop.
    assert pairs[6:] == [(3, 3), (4, 5), (5, 4)]


def test_edge_features_wrap_delta_phi():
    nodes = torch.zeros((2, 7))
    nodes[:, 1] = torch.tensor([0.5, -0.5])
    nodes[:, 2] = torch.tensor([3.0, -3.0])
    features = edge_features(nodes, torch.tensor([0]), torch.tensor([1]))
    deta, dphi, dr = features[0].tolist()
    assert deta == pytest.approx(1.0)
    assert dphi == pytest.approx(6.0 - 2 * math.pi)
    assert dr == pytest.approx(math.hypot(deta, dphi))


def test_padded_batch_reproduces_real_graph_outputs():
    events = random_events(12)
    batch = collate_graph_batch(events, torch.arange(len(events)))
    torch.manual_seed(0)
    model = EdgeNetwork(7, 3, 0, 16, 3, 2, 2).eval()
    static = StaticGraphBatch(
        batch, graph_batch_capacity(batch, node_multiple=32, edge_multiple=64)
    )
    # Garbage left in padding rows by an earlier, larger batch must not leak.
    static.graph.node_features.normal_()
    static.graph.edge_features.normal_()
    static.load(batch)
    with torch.no_grad():
        expected, padded = model(batch), model(static.batch)
    assert padded.shape[0] == len(events) + PADDING_GRAPHS
    torch.testing.assert_close(padded[: len(events)], expected, rtol=1e-5, atol=1e-6)


def test_static_batch_rejects_batches_beyond_capacity():
    def batch(nodes: int):
        events = pack_events([torch.rand((nodes, 7)) for _ in range(4)], [0] * 4)
        return collate_graph_batch(events, torch.arange(4))

    small = batch(1)
    static = StaticGraphBatch(
        small, graph_batch_capacity(small, node_multiple=1, edge_multiple=1)
    )
    with pytest.raises(ValueError, match="capacity"):
        static.load(batch(5))