radius.py 5.5 KB
Newer Older
rusty1s's avatar
rusty1s committed
1
from typing import Optional
rusty1s's avatar
rusty1s committed
2
import torch
3
import numpy as np
rusty1s's avatar
rusty1s committed
4

5

rusty1s's avatar
rusty1s committed
6
7
8
def radius(x: torch.Tensor, y: torch.Tensor, r: float,
           batch_x: Optional[torch.Tensor] = None,
           batch_y: Optional[torch.Tensor] = None,
9
           max_num_neighbors: int = 32, n_threads: int = 1) -> torch.Tensor:
rusty1s's avatar
rusty1s committed
10
11
    r"""Finds for each element in :obj:`y` all points in :obj:`x` within
    distance :obj:`r`.
rusty1s's avatar
docs  
rusty1s committed
12
13

    Args:
rusty1s's avatar
rusty1s committed
14
15
16
        x (Tensor): Node feature matrix
            :math:`\mathbf{X} \in \mathbb{R}^{N \times F}`.
        y (Tensor): Node feature matrix
Vadim Bereznyuk's avatar
typos  
Vadim Bereznyuk committed
17
            :math:`\mathbf{Y} \in \mathbb{R}^{M \times F}`.
rusty1s's avatar
docs  
rusty1s committed
18
        r (float): The radius.
19
        batch_x (LongTensor, optional): Batch vector (must be sorted)
rusty1s's avatar
rusty1s committed
20
21
            :math:`\mathbf{b} \in {\{ 0, \ldots, B-1\}}^N`, which assigns each
            node to a specific example. (default: :obj:`None`)
22
        batch_y (LongTensor, optional): Batch vector (must be sorted)
rusty1s's avatar
rusty1s committed
23
24
            :math:`\mathbf{b} \in {\{ 0, \ldots, B-1\}}^M`, which assigns each
            node to a specific example. (default: :obj:`None`)
rusty1s's avatar
docs  
rusty1s committed
25
        max_num_neighbors (int, optional): The maximum number of neighbors to
rusty1s's avatar
rusty1s committed
26
            return for each element in :obj:`y`. (default: :obj:`32`)
27
28
29
        n_threads (int): number of threads when the input is on CPU. Note
            that this has no effect when batch_x or batch_y is not None, or
            x is on GPU. (default: :obj:`1`)
rusty1s's avatar
docs  
rusty1s committed
30

rusty1s's avatar
rusty1s committed
31
    .. code-block:: python
rusty1s's avatar
rusty1s committed
32
33
34
35

        import torch
        from torch_cluster import radius

rusty1s's avatar
rusty1s committed
36
37
38
39
40
        x = torch.Tensor([[-1, -1], [-1, 1], [1, -1], [1, 1]])
        batch_x = torch.tensor([0, 0, 0, 0])
        y = torch.Tensor([[-1, 0], [1, 0]])
        batch_y = torch.tensor([0, 0])
        assign_index = radius(x, y, 1.5, batch_x, batch_y)
rusty1s's avatar
docs  
rusty1s committed
41
    """
rusty1s's avatar
rusty1s committed
42
43
44
45

    x = x.view(-1, 1) if x.dim() == 1 else x
    y = y.view(-1, 1) if y.dim() == 1 else y

46
47
48
    def is_sorted(x):
        return (np.diff(x.detach().cpu()) >= 0).all()

rusty1s's avatar
rusty1s committed
49
    if x.is_cuda:
rusty1s's avatar
rusty1s committed
50
51
        if batch_x is not None:
            assert x.size(0) == batch_x.numel()
52
            assert is_sorted(batch_x)
rusty1s's avatar
rusty1s committed
53
54
55
56
57
58
            batch_size = int(batch_x.max()) + 1

            deg = x.new_zeros(batch_size, dtype=torch.long)
            deg.scatter_add_(0, batch_x, torch.ones_like(batch_x))

            ptr_x = deg.new_zeros(batch_size + 1)
rusty1s's avatar
fix  
rusty1s committed
59
            torch.cumsum(deg, 0, out=ptr_x[1:])
rusty1s's avatar
rusty1s committed
60
        else:
61
            ptr_x = None
rusty1s's avatar
rusty1s committed
62
63
64

        if batch_y is not None:
            assert y.size(0) == batch_y.numel()
65
            assert is_sorted(batch_y)
rusty1s's avatar
fix  
rusty1s committed
66
            batch_size = int(batch_y.max()) + 1
rusty1s's avatar
rusty1s committed
67
68
69
70

            deg = y.new_zeros(batch_size, dtype=torch.long)
            deg.scatter_add_(0, batch_y, torch.ones_like(batch_y))
            ptr_y = deg.new_zeros(batch_size + 1)
rusty1s's avatar
fix  
rusty1s committed
71
            torch.cumsum(deg, 0, out=ptr_y[1:])
rusty1s's avatar
rusty1s committed
72
        else:
73
            ptr_y = None
rusty1s's avatar
rusty1s committed
74

75
        result = torch.ops.torch_cluster.radius(x, y, ptr_x, ptr_y, r,
76
                                                max_num_neighbors, n_threads)
rusty1s's avatar
rusty1s committed
77
    else:
78
        assert x.dim() == 2
79
        if batch_x is not None:
80
            assert batch_x.dim() == 1
81
            assert is_sorted(batch_x)
82
83
84
            assert x.size(0) == batch_x.size(0)

        assert y.dim() == 2
85
        if batch_y is not None:
86
            assert batch_y.dim() == 1
87
            assert is_sorted(batch_y)
88
            assert y.size(0) == batch_y.size(0)
rusty1s's avatar
rusty1s committed
89
90
        assert x.size(1) == y.size(1)

91
        result = torch.ops.torch_cluster.radius(x, y, batch_x, batch_y, r,
92
                                                max_num_neighbors, n_threads)
rusty1s's avatar
rusty1s committed
93

94
    return result
rusty1s's avatar
rusty1s committed
95

Alexander Liao's avatar
Alexander Liao committed
96

rusty1s's avatar
rusty1s committed
97
98
99
def radius_graph(x: torch.Tensor, r: float,
                 batch: Optional[torch.Tensor] = None, loop: bool = False,
                 max_num_neighbors: int = 32,
100
101
                 flow: str = 'source_to_target',
                 n_threads: int = 1) -> torch.Tensor:
rusty1s's avatar
rusty1s committed
102
    r"""Computes graph edges to all points within a given distance.
rusty1s's avatar
docs  
rusty1s committed
103
104

    Args:
rusty1s's avatar
rusty1s committed
105
106
        x (Tensor): Node feature matrix
            :math:`\mathbf{X} \in \mathbb{R}^{N \times F}`.
rusty1s's avatar
docs  
rusty1s committed
107
        r (float): The radius.
108
        batch (LongTensor, optional): Batch vector (must be sorted)
rusty1s's avatar
rusty1s committed
109
110
            :math:`\mathbf{b} \in {\{ 0, \ldots, B-1\}}^N`, which assigns each
            node to a specific example. (default: :obj:`None`)
rusty1s's avatar
rusty1s committed
111
112
        loop (bool, optional): If :obj:`True`, the graph will contain
            self-loops. (default: :obj:`False`)
rusty1s's avatar
docs  
rusty1s committed
113
        max_num_neighbors (int, optional): The maximum number of neighbors to
rusty1s's avatar
rusty1s committed
114
            return for each element in :obj:`y`. (default: :obj:`32`)
rusty1s's avatar
rusty1s committed
115
116
117
        flow (string, optional): The flow direction when using in combination
            with message passing (:obj:`"source_to_target"` or
            :obj:`"target_to_source"`). (default: :obj:`"source_to_target"`)
118
119
120
        n_threads (int): number of threads when the input is on CPU. Note
            that this has no effect when batch_x or batch_y is not None, or
            x is on GPU. (default: :obj:`1`)
rusty1s's avatar
docs  
rusty1s committed
121
122
123

    :rtype: :class:`LongTensor`

rusty1s's avatar
rusty1s committed
124
    .. code-block:: python
rusty1s's avatar
rusty1s committed
125
126
127
128

        import torch
        from torch_cluster import radius_graph

rusty1s's avatar
rusty1s committed
129
130
131
        x = torch.Tensor([[-1, -1], [-1, 1], [1, -1], [1, 1]])
        batch = torch.tensor([0, 0, 0, 0])
        edge_index = radius_graph(x, r=1.5, batch=batch, loop=False)
rusty1s's avatar
docs  
rusty1s committed
132
133
    """

rusty1s's avatar
rusty1s committed
134
    assert flow in ['source_to_target', 'target_to_source']
135
    row, col = radius(x, x, r, batch, batch,
136
137
                      max_num_neighbors if loop else max_num_neighbors + 1,
                      n_threads)
138
    row, col = (col, row) if flow == 'source_to_target' else (row, col)
rusty1s's avatar
rusty1s committed
139
140
141
    if not loop:
        mask = row != col
        row, col = row[mask], col[mask]
rusty1s's avatar
rusty1s committed
142
    return torch.stack([row, col], dim=0)