我有一个具有单个根顶点的有向 TreeMap ,其中方向似乎是任意的。 我希望所有边都从单个根指向各个分支的末端。
我的第一个原始尝试是交换源顶点和目标顶点,如下所示(但正如假设的那样,这是行不通的。
temp = g.es[e_idx].source
g.es[e_idx].source = g.es[e_idx].target
g.es[e_idx].target = temp
是否有一个函数或一组函数允许交换可用的特定边缘的方向?
或者一种操作边的源/目标属性而不需要更改任何顶点属性的方法?
如果我需要进一步说明任何内容,请告诉我。
我们将非常感谢您的帮助。
最佳答案
这是保留所有图形属性的可能解决方案:
- 我们将重新排序顶点,使那些更接近根的顶点排在前面
- 然后我们将
to_directed
与“非循环”
模式结合使用,该模式将边从索引较低的顶点引导到索引较高的顶点 - 最后我们恢复原来的顶点顺序
import igraph as ig
from igraph import Graph
# Set seed for reproducibility
import random
random.seed(123)
# Create an undirected tree. If your tree is not undirected,
# convert it to undirected first.
g = Graph.Tree_Game(10)
# Our chosen root:
root = 3
ig.plot(g, vertex_label=range(g.vcount()), layout = g.layout_reingold_tilford(root=root), bbox=(300,300))
# Distances from the root, will be used for ordering:
dist=g.shortest_paths(source=root)[0]
# This function computes the permutation that would
# sort 'elems'. It also serves as a way to invert
# permutations.
def ordering(elems):
return sorted(range(len(elems)), key=elems.__getitem__)
# Compute orderings based on the distance from the root:
perm = ordering(dist)
invperm = ordering(perm)
# Reorder, direct, restore order:
dg = g.permute_vertices(invperm)
dg.to_directed('acyclic')
dg = dg.permute_vertices(perm)
# Plot again.
# Now the root does not need to be given,
# as it is auto-detected from the directions.
ig.plot(dg, vertex_label=range(g.vcount()), layout='reingold_tilford', bbox=(300,300))
关于python - 如何更改 python igraph 中的边方向?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70715111/