简体   繁体   English

在for循环中从图中删除节点

[英]delete nodes from a graph in for loop

I'm using igraph-python .我正在使用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:当我运行此代码时,python 给了我这个错误:

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:在寻找 j 的邻居的过程中也存在如下问题:

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

As mentioned in the docs you should't use the label of the vertex but the id(s).文档中所述,您不应使用顶点的标签,而应使用 id(s)。

Have a look at the answer of this question .看看这个问题的答案。

For multiple ids:对于多个 ID:

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)对于单个顶点: G.delete_vertices(x.index)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM