2

I'd like to get common neighbors of two vertices on graph-tool.

According to the document, several similarity measures are available and all of them use the number of common neighbors. So, I guess it should be easy to get the common neighbors. But, I could not find how.

Light Yagmi
  • 5,085
  • 12
  • 43
  • 64

2 Answers2

4

From the Sørensen–Dice similarity this is obtained easily:

>>> g = collection.data["karate"]
>>> u, v = g.vertex(0), g.vertex(1)
>>> n = vertex_similarity(g, "dice", [(u, v)], self_loops=False) * (u.out_degree() + v.out_degree()) / 2
>>> print(n)
7
Tiago Peixoto
  • 5,149
  • 2
  • 28
  • 28
1

In case somebody wants to find out the actual common neighbours also, following would work:

In [2]: g = gt.collection.data["karate"]

In [11]: u, v = g.vertex(32), g.vertex(33)

In [16]: set(u.out_neighbours()) & set(v.out_neighbours())
Out[16]: 
{<Vertex object with index '8' at 0x7f2b62ae82a0>,
 <Vertex object with index '14' at 0x7f2b62ae8318>,
 <Vertex object with index '15' at 0x7f2b62ae8390>,
 <Vertex object with index '18' at 0x7f2b62ae8408>,
 <Vertex object with index '20' at 0x7f2b62ae8480>,
 <Vertex object with index '22' at 0x7f2b62ae84f8>,
 <Vertex object with index '23' at 0x7f2b62ae8570>,
 <Vertex object with index '29' at 0x7f2b62ae85e8>,
 <Vertex object with index '30' at 0x7f2b62ae8660>,
 <Vertex object with index '31' at 0x7f2b62ae86d8>}

Length of this set gives you the total number of common neighbours.

Peaceful
  • 4,920
  • 15
  • 54
  • 79