Debian Codegraph @

test/test_graclus.py

raw symbols SCIP
1 from itertools import product
2
3 import pytest
4 import torch
5 from torch_cluster import graclus_cluster
6 from torch_cluster.testing import devices, dtypes, tensor
7
8 tests = [{
9 'row': [0, 0, 1, 1, 1, 2, 2, 2, 3, 3],
10 'col': [1, 2, 0, 2, 3, 0, 1, 3, 1, 2],
11 }, {
12 'row': [0, 0, 1, 1, 1, 2, 2, 2, 3, 3],
13 'col': [1, 2, 0, 2, 3, 0, 1, 3, 1, 2],
14 'weight': [1, 2, 1, 3, 2, 2, 3, 1, 2, 1],
15 }]
16
17
18 def assert_correct(row, col, cluster):
19 row, col, cluster = row.to('cpu'), col.to('cpu'), cluster.to('cpu')
20 n = cluster.size(0)
21
22 # Every node was assigned a cluster.
23 assert cluster.min() >= 0
24
25 # There are no more than two nodes in each cluster.
26 _, index = torch.unique(cluster, return_inverse=True)
27 count = torch.zeros_like(cluster)
28 count.scatter_add_(0, index, torch.ones_like(cluster))
29 assert (count > 2).max() == 0
30
31 # Cluster value is minimal.
32 assert (cluster <= torch.arange(n, dtype=cluster.dtype)).sum() == n
33
34 # Corresponding clusters must be adjacent.
35 for i in range(n):
36 x = cluster[col[row == i]] == cluster[i] # Neighbors with same cluster
37 y = cluster == cluster[i] # Nodes with same cluster.
38 y[i] = 0 # Do not look at cluster of `i`.
39 assert x.sum() == y.sum()
40
41
42 @pytest.mark.parametrize('test,dtype,device', product(tests, dtypes, devices))
43 def test_graclus_cluster(test, dtype, device):
44 if dtype == torch.bfloat16 and device == torch.device('cuda:0'):
45 return
46
47 row = tensor(test['row'], torch.long, device)
48 col = tensor(test['col'], torch.long, device)
49 weight = tensor(test.get('weight'), dtype, device)
50
51 cluster = graclus_cluster(row, col, weight)
52 assert_correct(row, col, cluster)
53
54 jit = torch.jit.script(graclus_cluster)
55 cluster = jit(row, col, weight)
56 assert_correct(row, col, cluster)