python - 如何更改 python igraph 中的边方向?

标签 python graph igraph data-manipulation

我有一个具有单个根顶点的有向 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))

enter image description here

关于python - 如何更改 python igraph 中的边方向?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70715111/

相关文章:

python - 属性错误 : module 'community' has no attribute 'best_partition'

Python 包导入错误

java - 如何在java web应用程序中的pdf报告中绘制图表

python - igraph 到达边界框的最边缘

python - 从命令行运行 SikuliX 1.1.4 Python 脚本

python - Python 2.7 中有什么类似于 Go 的 `time.Tick` 或 Netty 的 `HashedWheelTimer` 吗?

algorithm - 最小化图中的交叉边

azure - 用于获取带有员工 ID 的整个用户列表的图形 API

python - 从 R 代码到 Python 变体的 IGRAPH 转换

python - 从共同作者数据创建边缘列表