python-3.x - 如何计算 igraph(python)中图形的全局效率?
问题描述
我正在尝试计算 igraph 中图形的全局效率,但我不确定我是否正确使用了该模块。我认为有一个解决方案可能有点道理,但它在 r 中,我无法破译他们在说什么。
我曾尝试以 networkx 方式编写代码,试图模仿他们计算全局效率的方式,但到目前为止我还没有成功。我正在使用 igraph,因为我正在处理大图。任何帮助将不胜感激:D
这是我尝试过的:
import igraph
import pandas as pd
import numpy as np
from itertools import permutations
datasafe = pd.read_csv("b1.csv", index_col=0)
D = datasafe.values
g = igraph.Graph.Adjacency((D > 0).tolist())
g.es['weight'] = D[D.nonzero()]
def efficiency_weighted(g):
weights = g.es["weight"][:]
eff = (1.0 / np.array(g.shortest_paths_dijkstra(weights=weights)))
return eff
def global_efficiecny_weighted(g):
n=180.0
denom=n*(n-1)
g_eff = sum(efficiency_weighted(g) for u, v in permutations(g, 2))
return g_eff
global_efficiecny_weighted(g)
我收到的错误消息是:- TypeError: 'Graph' object is not iterable
解决方案
假设您想要所有节点的节点效率,那么您可以这样做:
import numpy as np
from igraph import *
np.seterr(divide='ignore')
# Example using a random graph with 20 nodes
g = Graph.Erdos_Renyi(20,0.5)
# Assign weights on the edges. Here 1s everywhere
g.es["weight"] = np.ones(g.ecount())
def nodal_eff(g):
weights = g.es["weight"][:]
sp = (1.0 / np.array(g.shortest_paths_dijkstra(weights=weights)))
np.fill_diagonal(sp,0)
N=sp.shape[0]
ne= (1.0/(N-1)) * np.apply_along_axis(sum,0,sp)
return ne
eff = nodal_eff(g)
print(eff)
#[0.68421053 0.81578947 0.73684211 0.76315789 0.76315789 0.71052632
# 0.81578947 0.81578947 0.81578947 0.73684211 0.71052632 0.68421053
# 0.71052632 0.81578947 0.84210526 0.76315789 0.68421053 0.68421053
# 0.78947368 0.76315789]
要获得全局,只需执行以下操作:
np.mean(eff)
推荐阅读
- swift - 无法使用 Vapor-Fluent 在 Swift 中跨 Web 服务实例持久化数据
- c# - C# - 静态初始化程序的顺序问题
- dart - 如何将 flutter_local_notifications 添加到我的应用程序中?
- sql - SQL Server:在查询中获取按日期安全计数 - 有没有更简单的方法来编写它?
- javascript - Javascript - 按前 2 个空格分割字符串
- r - 我正在尝试使用 Ubuntu 18.04 在 R 中安装 openssl 包但没有成功
- rust - 如何在 rust 中连接静态数组?
- mysql - mysql - 如何获取父表中缺少的所有关系外键?
- db2 - SQLCODE -981,SQLERRMC:00C12219
- powershell - 将脚本指向最新文件