Debian Codegraph @

torch_cluster/knn.py

raw
1 from typing import Optional
2
3 import torch
4
5
6 def knn(
7 x: torch.Tensor,
8 y: torch.Tensor,
9 k: int,
10 batch_x: Optional[torch.Tensor] = None,
11 batch_y: Optional[torch.Tensor] = None,
12 cosine: bool = False,
13 num_workers: int = 1,
14 batch_size: Optional[int] = None,
15 ) -> torch.Tensor:
16 r"""Finds for each element in :obj:`y` the :obj:`k` nearest points in
17 :obj:`x`.
18
19 Args:
20 x (Tensor): Node feature matrix
21 :math:`\mathbf{X} \in \mathbb{R}^{N \times F}`.
22 y (Tensor): Node feature matrix
23 :math:`\mathbf{X} \in \mathbb{R}^{M \times F}`.
24 k (int): The number of neighbors.
25 batch_x (LongTensor, optional): Batch vector
26 :math:`\mathbf{b} \in {\{ 0, \ldots, B-1\}}^N`, which assigns each
27 node to a specific example. :obj:`batch_x` needs to be sorted.
28 (default: :obj:`None`)
29 batch_y (LongTensor, optional): Batch vector
30 :math:`\mathbf{b} \in {\{ 0, \ldots, B-1\}}^M`, which assigns each
31 node to a specific example. :obj:`batch_y` needs to be sorted.
32 (default: :obj:`None`)
33 cosine (boolean, optional): If :obj:`True`, will use the Cosine
34 distance instead of the Euclidean distance to find nearest
35 neighbors. (default: :obj:`False`)
36 num_workers (int): Number of workers to use for computation. Has no
37 effect in case :obj:`batch_x` or :obj:`batch_y` is not
38 :obj:`None`, or the input lies on the GPU. (default: :obj:`1`)
39 batch_size (int, optional): The number of examples :math:`B`.
40 Automatically calculated if not given. (default: :obj:`None`)
41
42 :rtype: :class:`LongTensor`
43
44 .. code-block:: python
45
46 import torch
47 from torch_cluster import knn
48
49 x = torch.Tensor([[-1, -1], [-1, 1], [1, -1], [1, 1]])
50 batch_x = torch.tensor([0, 0, 0, 0])
51 y = torch.Tensor([[-1, 0], [1, 0]])
52 batch_y = torch.tensor([0, 0])
53 assign_index = knn(x, y, 2, batch_x, batch_y)
54 """
55 if x.numel() == 0 or y.numel() == 0:
56 return torch.empty(2, 0, dtype=torch.long, device=x.device)
57
58 x = x.view(-1, 1) if x.dim() == 1 else x
59 y = y.view(-1, 1) if y.dim() == 1 else y
60 x, y = x.contiguous(), y.contiguous()
61
62 if batch_size is None:
63 batch_size = 1
64 if batch_x is not None:
65 assert x.size(0) == batch_x.numel()
66 batch_size = int(batch_x.max()) + 1
67 if batch_y is not None:
68 assert y.size(0) == batch_y.numel()
69 batch_size = max(batch_size, int(batch_y.max()) + 1)
70 assert batch_size > 0
71
72 ptr_x: Optional[torch.Tensor] = None
73 ptr_y: Optional[torch.Tensor] = None
74 if batch_size > 1:
75 assert batch_x is not None
76 assert batch_y is not None
77 arange = torch.arange(batch_size + 1, device=x.device)
78 ptr_x = torch.bucketize(arange, batch_x)
79 ptr_y = torch.bucketize(arange, batch_y)
80
81 return torch.ops.torch_cluster.knn(x, y, ptr_x, ptr_y, k, cosine,
82 num_workers)
83
84
85 def knn_graph(
86 x: torch.Tensor,
87 k: int,
88 batch: Optional[torch.Tensor] = None,
89 loop: bool = False,
90 flow: str = 'source_to_target',
91 cosine: bool = False,
92 num_workers: int = 1,
93 batch_size: Optional[int] = None,
94 ) -> torch.Tensor:
95 r"""Computes graph edges to the nearest :obj:`k` points.
96
97 Args:
98 x (Tensor): Node feature matrix
99 :math:`\mathbf{X} \in \mathbb{R}^{N \times F}`.
100 k (int): The number of neighbors.
101 batch (LongTensor, optional): Batch vector
102 :math:`\mathbf{b} \in {\{ 0, \ldots, B-1\}}^N`, which assigns each
103 node to a specific example. :obj:`batch` needs to be sorted.
104 (default: :obj:`None`)
105 loop (bool, optional): If :obj:`True`, the graph will contain
106 self-loops. (default: :obj:`False`)
107 flow (string, optional): The flow direction when used in combination
108 with message passing (:obj:`"source_to_target"` or
109 :obj:`"target_to_source"`). (default: :obj:`"source_to_target"`)
110 cosine (boolean, optional): If :obj:`True`, will use the Cosine
111 distance instead of Euclidean distance to find nearest neighbors.
112 (default: :obj:`False`)
113 num_workers (int): Number of workers to use for computation. Has no
114 effect in case :obj:`batch` is not :obj:`None`, or the input lies
115 on the GPU. (default: :obj:`1`)
116 batch_size (int, optional): The number of examples :math:`B`.
117 Automatically calculated if not given. (default: :obj:`None`)
118
119 :rtype: :class:`LongTensor`
120
121 .. code-block:: python
122
123 import torch
124 from torch_cluster import knn_graph
125
126 x = torch.Tensor([[-1, -1], [-1, 1], [1, -1], [1, 1]])
127 batch = torch.tensor([0, 0, 0, 0])
128 edge_index = knn_graph(x, k=2, batch=batch, loop=False)
129 """
130
131 assert flow in ['source_to_target', 'target_to_source']
132 edge_index = knn(x, x, k if loop else k + 1, batch, batch, cosine,
133 num_workers, batch_size)
134
135 if flow == 'source_to_target':
136 row, col = edge_index[1], edge_index[0]
137 else:
138 row, col = edge_index[0], edge_index[1]
139
140 if not loop:
141 mask = row != col
142 row, col = row[mask], col[mask]
143
144 return torch.stack([row, col], dim=0)