[英]Cannot add edges, Invalid vertex ID in IGraph
我試圖使用 igraph 在 python 中編寫代碼,當我嘗試使用 while 循環添加邊時出現此錯誤
while(i<k)
g.add_vertices(theInts[i])
i=i+1
g.add_edges([(theInts[i-1],theInts[i])])
我認為索引可能是個問題,所以我還包含了一個 if 語句,但這似乎不是問題所在。
請幫忙!!!
我認為這完全取決於g
對頂點的影響。 如果你從一個空的g
開始,你只有頂點0
,所以如果你試圖用兩個不同的頂點調用add_edges
,它就不會工作。 你必須添加更多的頂點。 當然,這一切都取決於你的圖表在循環之前的樣子,以及i
是什么。
您可以使用print
顯示有關圖形的一些簡要信息。 例如,
>>> import igraph
>>> graph = igraph.Graph()
>>> print graph
Undirected graph (|V| = 1, |E| = 0)
如果i
從 0 開始,那么您將不會在第一次循環中添加任何頂點。 因此,當您嘗試添加邊時,您是在嘗試添加不存在的頂點。
>>> graph.add_vertices(0)
<igraph.Graph object at 0xcea850>
>>> print graph
Undirected graph (|V| = 1, |E| = 0)
>>> graph.add_edges([(0, 1)])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
igraph.core.InternalError: Error at type_indexededgelist.c:245: cannot add edges, Invalid vertex id
如果這不是問題,請嘗試打印邊緣並查看它們是否與您想要的相匹配。
>>> graph.add_vertices(5)
<igraph.Graph object at 0xcea850>
>>> print graph
Undirected graph (|V| = 6, |E| = 3)
>>> graph.add_edges([(1, 1), (2, 3), (3, 5)])
<igraph.Graph object at 0xcea850>
>>> graph.get_edgelist()
[(1, 1), (2, 3), (3, 5)]
此外,擁有完整的 TraceBack 可能會更有幫助。
編輯:根據您的評論
所以你說你有這樣的結構:
>>> graph = igraph.Graph()
>>> print graph
Undirected graph (|V| = 1, |E| = 0)
你只想添加頂點 2? 我不確定您是否可以使用 igraph 做到這一點。 似乎必須按順序排列每個頂點。 您可以檢查是否有頂點,然后在必要時添加它們,記住這些圖是從 0 開始的。 像這樣的東西。
>>> vertices = 1, 2, 13, 4, 21, 5
>>> map_graph = igraph.Graph()
>>> print map_graph
Undirected graph (|V| = 1, |E| = 0)
>>> map_graph.add_vertices(max(vertices))
<igraph.Graph object at 0xceaa50>
>>> print map_graph
Undirected graph (|V| = 22, |E| = 0)
>>> map(map_graph.add_edges, zip(vertices, vertices[1:]))
[<igraph.Graph object at 0xceaa50>, <igraph.Graph object at 0xceaa50>, <igraph.Graph object at 0xceaa50>, <igraph.Graph object at 0xceaa50>, <igraph.Graph object at 0xceaa50>]
>>> print map_graph
Undirected graph (|V| = 22, |E| = 5)
>>> map_graph.get_edgelist()
[(1, 2), (2, 13), (4, 13), (4, 21), (5, 21)]
或者,如果您不喜歡地圖,可以將其循環播放。
>>> vertices = 1, 2, 13, 4, 21, 5
>>> loop_graph = igraph.Graph()
>>> print loop_graph
Undirected graph (|V| = 1, |E| = 0)
>>> loop_graph.add_vertices(max(vertices))
<igraph.Graph object at 0xcea950>
>>> print loop_graph
Undirected graph (|V| = 22, |E| = 0)
>>> for pair in zip(vertices, vertices[1:]):
... loop_graph.add_edges(pair)
...
<igraph.Graph object at 0xcea950>
<igraph.Graph object at 0xcea950>
<igraph.Graph object at 0xcea950>
<igraph.Graph object at 0xcea950>
<igraph.Graph object at 0xcea950>
>>> print loop_graph
Undirected graph (|V| = 22, |E| = 5)
>>> loop_graph.get_edgelist()
[(1, 2), (2, 13), (4, 13), (4, 21), (5, 21)]
不過,可能有更好的方法來做到這一點。 如果這不是您要查找的內容,請使用更多詳細信息和一些實際代碼來編輯您的原始問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.