Debian Codegraph @

torch_cluster/rw.py

raw
1 from typing import Optional, Tuple, Union
2
3 import torch
4 from torch import Tensor
5
6
7 def random_walk(
8 row: Tensor,
9 col: Tensor,
10 start: Tensor,
11 walk_length: int,
12 p: float = 1,
13 q: float = 1,
14 coalesced: bool = True,
15 num_nodes: Optional[int] = None,
16 return_edge_indices: bool = False,
17 ) -> Union[Tensor, Tuple[Tensor, Tensor]]:
18 """Samples random walks of length :obj:`walk_length` from all node indices
19 in :obj:`start` in the graph given by :obj:`(row, col)` as described in the
20 `"node2vec: Scalable Feature Learning for Networks"
21 <https://arxiv.org/abs/1607.00653>`_ paper.
22 Edge indices :obj:`(row, col)` need to be coalesced/sorted according to
23 :obj:`row` (use the :obj:`coalesced` attribute to force).
24
25 Args:
26 row (LongTensor): Source nodes.
27 col (LongTensor): Target nodes.
28 start (LongTensor): Nodes from where random walks start.
29 walk_length (int): The walk length.
30 p (float, optional): Likelihood of immediately revisiting a node in the
31 walk. (default: :obj:`1`)
32 q (float, optional): Control parameter to interpolate between
33 breadth-first strategy and depth-first strategy (default: :obj:`1`)
34 coalesced (bool, optional): If set to :obj:`True`, will coalesce/sort
35 the graph given by :obj:`(row, col)` according to :obj:`row`.
36 (default: :obj:`True`)
37 num_nodes (int, optional): The number of nodes. (default: :obj:`None`)
38 return_edge_indices (bool, optional): Whether to additionally return
39 the indices of edges traversed during the random walk.
40 (default: :obj:`False`)
41
42 :rtype: :class:`LongTensor`
43 """
44 if num_nodes is None:
45 num_nodes = max(int(row.max()), int(col.max()), int(start.max())) + 1
46
47 if coalesced:
48 perm = torch.argsort(row * num_nodes + col)
49 row, col = row[perm], col[perm]
50
51 deg = row.new_zeros(num_nodes)
52 deg.scatter_add_(0, row, torch.ones_like(row))
53 rowptr = row.new_zeros(num_nodes + 1)
54 torch.cumsum(deg, 0, out=rowptr[1:])
55
56 node_seq, edge_seq = torch.ops.torch_cluster.random_walk(
57 rowptr, col, start, walk_length, p, q)
58
59 if return_edge_indices:
60 return node_seq, edge_seq
61
62 return node_seq