| 1 |
from typing import Optional |
| 2 |
|
| 3 |
import scipy.cluster |
| 4 |
import torch |
| 5 |
|
| 6 |
|
| 7 |
def nearest( |
| 8 |
x: torch.Tensor, |
| 9 |
y: torch.Tensor, |
| 10 |
batch_x: Optional[torch.Tensor] = None, |
| 11 |
batch_y: Optional[torch.Tensor] = None, |
| 12 |
) -> torch.Tensor: |
| 13 |
r"""Clusters points in :obj:`x` together which are nearest to a given query |
| 14 |
point in :obj:`y`. |
| 15 |
|
| 16 |
Args: |
| 17 |
x (Tensor): Node feature matrix |
| 18 |
:math:`\mathbf{X} \in \mathbb{R}^{N \times F}`. |
| 19 |
y (Tensor): Node feature matrix |
| 20 |
:math:`\mathbf{Y} \in \mathbb{R}^{M \times F}`. |
| 21 |
batch_x (LongTensor, optional): Batch vector |
| 22 |
:math:`\mathbf{b} \in {\{ 0, \ldots, B-1\}}^N`, which assigns each |
| 23 |
node to a specific example. :obj:`batch_x` needs to be sorted. |
| 24 |
(default: :obj:`None`) |
| 25 |
batch_y (LongTensor, optional): Batch vector |
| 26 |
:math:`\mathbf{b} \in {\{ 0, \ldots, B-1\}}^M`, which assigns each |
| 27 |
node to a specific example. :obj:`batch_y` needs to be sorted. |
| 28 |
(default: :obj:`None`) |
| 29 |
|
| 30 |
:rtype: :class:`LongTensor` |
| 31 |
|
| 32 |
.. code-block:: python |
| 33 |
|
| 34 |
import torch |
| 35 |
from torch_cluster import nearest |
| 36 |
|
| 37 |
x = torch.Tensor([[-1, -1], [-1, 1], [1, -1], [1, 1]]) |
| 38 |
batch_x = torch.tensor([0, 0, 0, 0]) |
| 39 |
y = torch.Tensor([[-1, 0], [1, 0]]) |
| 40 |
batch_y = torch.tensor([0, 0]) |
| 41 |
cluster = nearest(x, y, batch_x, batch_y) |
| 42 |
""" |
| 43 |
|
| 44 |
x = x.view(-1, 1) if x.dim() == 1 else x |
| 45 |
y = y.view(-1, 1) if y.dim() == 1 else y |
| 46 |
assert x.size(1) == y.size(1) |
| 47 |
|
| 48 |
if batch_x is not None and (batch_x[1:] - batch_x[:-1] < 0).any(): |
| 49 |
raise ValueError("'batch_x' is not sorted") |
| 50 |
if batch_y is not None and (batch_y[1:] - batch_y[:-1] < 0).any(): |
| 51 |
raise ValueError("'batch_y' is not sorted") |
| 52 |
|
| 53 |
if x.is_cuda: |
| 54 |
if batch_x is not None: |
| 55 |
assert x.size(0) == batch_x.numel() |
| 56 |
batch_size = int(batch_x.max()) + 1 |
| 57 |
|
| 58 |
deg = x.new_zeros(batch_size, dtype=torch.long) |
| 59 |
deg.scatter_add_(0, batch_x, torch.ones_like(batch_x)) |
| 60 |
|
| 61 |
ptr_x = deg.new_zeros(batch_size + 1) |
| 62 |
torch.cumsum(deg, 0, out=ptr_x[1:]) |
| 63 |
else: |
| 64 |
ptr_x = torch.tensor([0, x.size(0)], device=x.device) |
| 65 |
|
| 66 |
if batch_y is not None: |
| 67 |
assert y.size(0) == batch_y.numel() |
| 68 |
batch_size = int(batch_y.max()) + 1 |
| 69 |
|
| 70 |
deg = y.new_zeros(batch_size, dtype=torch.long) |
| 71 |
deg.scatter_add_(0, batch_y, torch.ones_like(batch_y)) |
| 72 |
|
| 73 |
ptr_y = deg.new_zeros(batch_size + 1) |
| 74 |
torch.cumsum(deg, 0, out=ptr_y[1:]) |
| 75 |
else: |
| 76 |
ptr_y = torch.tensor([0, y.size(0)], device=y.device) |
| 77 |
|
| 78 |
# If an instance in `batch_x` is non-empty, it must be non-empty in |
| 79 |
# `batch_y `as well: |
| 80 |
nonempty_ptr_x = (ptr_x[1:] - ptr_x[:-1]) > 0 |
| 81 |
nonempty_ptr_y = (ptr_y[1:] - ptr_y[:-1]) > 0 |
| 82 |
if not torch.equal(nonempty_ptr_x, nonempty_ptr_y): |
| 83 |
raise ValueError("Some batch indices occur in 'batch_x' " |
| 84 |
"that do not occur in 'batch_y'") |
| 85 |
|
| 86 |
return torch.ops.torch_cluster.nearest(x, y, ptr_x, ptr_y) |
| 87 |
|
| 88 |
else: |
| 89 |
|
| 90 |
if batch_x is None and batch_y is not None: |
| 91 |
batch_x = x.new_zeros(x.size(0), dtype=torch.long) |
| 92 |
if batch_y is None and batch_x is not None: |
| 93 |
batch_y = y.new_zeros(y.size(0), dtype=torch.long) |
| 94 |
|
| 95 |
# Translate and rescale x and y to [0, 1]. |
| 96 |
if batch_x is not None and batch_y is not None: |
| 97 |
# If an instance in `batch_x` is non-empty, it must be non-empty in |
| 98 |
# `batch_y `as well: |
| 99 |
unique_batch_x = batch_x.unique_consecutive() |
| 100 |
unique_batch_y = batch_y.unique_consecutive() |
| 101 |
if not torch.equal(unique_batch_x, unique_batch_y): |
| 102 |
raise ValueError("Some batch indices occur in 'batch_x' " |
| 103 |
"that do not occur in 'batch_y'") |
| 104 |
|
| 105 |
assert x.dim() == 2 and batch_x.dim() == 1 |
| 106 |
assert y.dim() == 2 and batch_y.dim() == 1 |
| 107 |
assert x.size(0) == batch_x.size(0) |
| 108 |
assert y.size(0) == batch_y.size(0) |
| 109 |
|
| 110 |
min_xy = min(x.min().item(), y.min().item()) |
| 111 |
x, y = x - min_xy, y - min_xy |
| 112 |
|
| 113 |
max_xy = max(x.max().item(), y.max().item()) |
| 114 |
x.div_(max_xy) |
| 115 |
y.div_(max_xy) |
| 116 |
|
| 117 |
# Concat batch/features to ensure no cross-links between examples. |
| 118 |
D = x.size(-1) |
| 119 |
x = torch.cat([x, 2 * D * batch_x.view(-1, 1).to(x.dtype)], -1) |
| 120 |
y = torch.cat([y, 2 * D * batch_y.view(-1, 1).to(y.dtype)], -1) |
| 121 |
|
| 122 |
return torch.from_numpy( |
| 123 |
scipy.cluster.vq.vq(x.detach().cpu(), |
| 124 |
y.detach().cpu())[0]).to(torch.long) |