Debian Codegraph @

torch_cluster/graclus.py

raw
1 from typing import Optional
2
3 import torch
4
5
6 def graclus_cluster(
7 row: torch.Tensor,
8 col: torch.Tensor,
9 weight: Optional[torch.Tensor] = None,
10 num_nodes: Optional[int] = None,
11 ) -> torch.Tensor:
12 """A greedy clustering algorithm of picking an unmarked vertex and matching
13 it with one its unmarked neighbors (that maximizes its edge weight).
14
15 Args:
16 row (LongTensor): Source nodes.
17 col (LongTensor): Target nodes.
18 weight (Tensor, optional): Edge weights. (default: :obj:`None`)
19 num_nodes (int, optional): The number of nodes. (default: :obj:`None`)
20
21 :rtype: :class:`LongTensor`
22
23 .. code-block:: python
24
25 import torch
26 from torch_cluster import graclus_cluster
27
28 row = torch.tensor([0, 1, 1, 2])
29 col = torch.tensor([1, 0, 2, 1])
30 weight = torch.Tensor([1, 1, 1, 1])
31 cluster = graclus_cluster(row, col, weight)
32 """
33
34 if num_nodes is None:
35 num_nodes = max(int(row.max()), int(col.max())) + 1
36
37 # Remove self-loops.
38 mask = row != col
39 row, col = row[mask], col[mask]
40
41 if weight is not None:
42 weight = weight[mask]
43
44 # Randomly shuffle nodes.
45 if weight is None:
46 perm = torch.randperm(row.size(0), dtype=torch.long, device=row.device)
47 row, col = row[perm], col[perm]
48
49 # To CSR.
50 perm = torch.argsort(row)
51 row, col = row[perm], col[perm]
52
53 if weight is not None:
54 weight = weight[perm]
55
56 deg = row.new_zeros(num_nodes)
57 deg.scatter_add_(0, row, torch.ones_like(row))
58 rowptr = row.new_zeros(num_nodes + 1)
59 torch.cumsum(deg, 0, out=rowptr[1:])
60
61 return torch.ops.torch_cluster.graclus(rowptr, col, weight)