delete nodes from a graph in for loop

Viewed 173

I'm using igraph-python. I'm trying to solve a problem called the longest induced path, I'm choosing, in the beginning, a random node , find it's neighbors then choose one from the neighbors based on the value of closeness centrality, delete the others and so on My code is the following

from random import randint
import networkx as nx
import numpy as np
from igraph import *
from numpy import random
def maximum(a, n):
maxpos = a.index ( max ( a ) )
return maxpos

G = Graph ()
G.add_vertices(5)
G.add_edges([(0, 1), (0, 2),(1,3),(2,3),(3,4)])

n = G.vcount()
first = random.randint(n)
neigh = G.neighbors(first)
clos = G.closeness(vertices=neigh)
induced_path = first
G.delete_vertices(first)
while len(neigh) > 0:
     pos = maximum(clos, len(clos))
     j= neigh[pos]
     np.append(induced_path,j)
     print(induced_path)
     neigh = np.setdiff1d(neigh,j)
     G.delete_vertices(neigh)
     neigh = G.neighbors(j)
     clos = G.closeness(vertices=neigh)
     G.delete_vertices(j)
     print(len(induced_path))

when I'm running this code python giving me this error:

Cannot create iterator, invalid vertex id, Invalid vertex id

also there is a problem in the line of finding the neighbours of j as follows:

cannot get neighbors, Invalid vertex id

Traceback:

File "E:/inducedpath/indu.py", line 30, in <module> G.delete_vertices(neigh) igraph._igraph.InternalError: Error at c:\projects\python-igraph\vendor\build\igraph\igraph-0.8.0-msvc\src\iterators.c:764: Cannot create iterator, invalid vertex id, Invalid vertex id
1 Answers

As mentioned in the docs you should't use the label of the vertex but the id(s).

Have a look at the answer of this question.

For multiple ids:

to_delete_ids = [x.index for x in G.vs]
G.delete_vertices(to_delete_ids)

For a single vertex: G.delete_vertices(x.index)

Related