工具函数

工具函数模块。

提供通用的工具函数。

pynetim.utils.all_pairs_shortest_path_length(graph, nodes=None, use_weight=False)[source]

计算节点对之间的最短路径长度。

Parameters:
  • graph (IMGraph) – 图对象。

  • nodes (List[int] | None) – 要计算的节点列表,如果为 None 则计算所有节点。

  • use_weight (bool) – 是否使用边权重。

Returns:

嵌套字典,distances[u][v] 表示 u 到 v 的最短路径长度。

Return type:

dict

Example

>>> from pynetim.utils import all_pairs_shortest_path_length
>>> distances = all_pairs_shortest_path_length(graph, nodes=[0, 1, 2])
>>> print(distances[0][1])
pynetim.utils.compute_sir_beta(graph, gamma=0.1, c=1.3)[source]

计算 SIR 模型的感染率 β。

基于配置模型近似 (Configuration Model Approximation) 计算感染率。

公式:

β_c = γ · <k> / <k²> β = c · β_c

其中:
  • <k>: 平均度

  • <k²>: 度的平方均值

  • γ: 恢复率

  • c: 调节系数

Parameters

graphIMGraph

图对象。

gammafloat, optional

恢复率,默认 0.1。

cfloat, optional

调节系数,默认 1.3。 - c < 1: 不爆发 - c = 1: 临界状态 - c > 1: 爆发

Returns

tuple[float, float]

(beta, beta_c): 感染率和临界感染率。

References

Pastor-Satorras, R., Castellano, C., Van Mieghem, P., & Vespignani, A. (2015). Epidemic processes in complex networks. Reviews of Modern Physics, 87(3), 925.

Examples

>>> from pynetim.utils import generate_er_graph, compute_sir_beta
>>> g = generate_er_graph(n=100, p=0.1, random_seed=42)
>>> beta, beta_c = compute_sir_beta(g, gamma=0.1, c=1.3)
>>> print(f"感染率: {beta:.4f}, 临界感染率: {beta_c:.4f}")
Parameters:
Return type:

Tuple[float, float]

pynetim.utils.generate_ba_graph(n, m, directed=True, random_seed=None)[source]

生成 Barabási-Albert 无标度网络。

通过优先连接机制生成具有幂律度分布的网络。

Parameters

nint

最终节点数量。

mint

每个新节点连接的边数,必须小于 n。

directedbool, optional

是否有向图,默认 True。

random_seedint, optional

随机种子,用于可重复性。

Returns

IMGraph

生成的无标度网络。

References

Barabási, A. L., & Albert, R. (1999). Emergence of scaling in random networks. Science, 286(5439), 509-512.

Examples

>>> from pynetim.graph import generate_ba_graph
>>> g = generate_ba_graph(n=100, m=3, random_seed=42)
>>> print(f"节点数: {g.num_nodes}, 边数: {g.num_edges}")
Parameters:
Return type:

IMGraph

pynetim.utils.generate_er_graph(n, p, directed=True, random_seed=None)[source]

生成 Erdős-Rényi 随机图 (G(n, p) 模型)。

每对节点之间以概率 p 连接一条边。

Parameters

nint

节点数量。

pfloat

边连接概率,取值范围 [0, 1]。

directedbool, optional

是否有向图,默认 True。

random_seedint, optional

随机种子,用于可重复性。

Returns

IMGraph

生成的随机图。

References

Erdős, P., & Rényi, A. (1959). On random graphs I. Publicationes Mathematicae, 6, 290-297.

Examples

>>> from pynetim.graph import generate_er_graph
>>> g = generate_er_graph(n=100, p=0.1, random_seed=42)
>>> print(f"节点数: {g.num_nodes}, 边数: {g.num_edges}")
Parameters:
Return type:

IMGraph

pynetim.utils.generate_rr_sets(graph: IMGraph, num_sets: int, model: str = 'IC', seed: int | None = None) list[list[int]]

生成多个 RR 集合。

Parameters:
  • graph – IMGraph 图对象。

  • num_sets – 要生成的 RR 集合数量。

  • model – 传播模型,支持 ‘IC’ 或 ‘LT’,默认为 ‘IC’。

  • seed – 随机种子,可选。

Returns:

RR 集合列表。

Return type:

list[list[int]]

Example

>>> from pynetim.utils import generate_rr_sets
>>> rr_sets = generate_rr_sets(graph, 1000, model='IC', seed=42)
pynetim.utils.generate_ws_graph(n, k, beta, directed=True, random_seed=None)[source]

生成 Watts-Strogatz 小世界网络。

从环形规则网络开始,以概率 beta 重连边。

Parameters

nint

节点数量。

kint

每个节点连接的邻居数(必须是偶数)。

betafloat

重连概率,取值范围 [0, 1]。 - beta=0: 规则网络 - beta=1: 随机网络 - beta~0.1: 小世界网络

directedbool, optional

是否有向图,默认 True。

random_seedint, optional

随机种子,用于可重复性。

Returns

IMGraph

生成的小世界网络。

References

Watts, D. J., & Strogatz, S. H. (1998). Collective dynamics of ‘small-world’ networks. Nature, 393(6684), 440-442.

Examples

>>> from pynetim.graph import generate_ws_graph
>>> g = generate_ws_graph(n=100, k=4, beta=0.1, random_seed=42)
>>> print(f"节点数: {g.num_nodes}, 边数: {g.num_edges}")
Parameters:
Return type:

IMGraph

pynetim.utils.load_edgelist(filepath, directed=True, renumber=False, comment=None, skip_lines=0)[source]

从文件读取边列表构造 IMGraph。

文件格式:每行 u v [weight],分隔符支持空格/制表符/逗号。 第三列可选,默认权重为 1.0。

Parameters

filepathstr or Path

边列表文件路径

directedbool, optional

是否有向图,默认 True

renumberbool, optional

是否重编号节点为连续整数,默认 False

commentstr, optional

注释行前缀,如 ‘#’ 或 ‘%’,默认 None

skip_linesint, optional

跳过文件开头的行数,默认 0

Returns

IMGraph

构造的图对象

Examples

文件内容 (edges.txt): 0 1 0.5 1 2 0.8 2 3

>>> g = load_edgelist("edges.txt")
>>> g.num_nodes
4
>>> g.num_edges
3
Parameters:
Return type:

IMGraph

pynetim.utils.renumber_edges(edges)[source]

重新编号边列表中的节点为连续整数。

Parameters:

edges (List[Tuple[int, int]]) – 边列表,每个元素为 (u, v) 元组。

Returns:

  • 重编号后的边列表

  • 原始节点ID到新节点ID的映射

  • 新节点ID到原始节点ID的映射

Return type:

Tuple[List[Tuple[int, int]], dict, List[int]]

Example

>>> from pynetim.utils import renumber_edges
>>> edges = [(10, 20), (20, 30), (30, 40)]
>>> new_edges, mapping, reverse_mapping = renumber_edges(edges)
>>> print(new_edges)  # [(0, 1), (1, 2), (2, 3)]
pynetim.utils.sample_rr_set_ic(graph: IMGraph, seed: int | None = None) list[int]

采样一个 IC 模型的 RR 集合。

Parameters:
  • graph – IMGraph 图对象。

  • seed – 随机种子,可选。

Returns:

RR 集合中的节点列表。

Return type:

list[int]

Example

>>> from pynetim.utils import sample_rr_set_ic
>>> rr_set = sample_rr_set_ic(graph, seed=42)
pynetim.utils.sample_rr_set_lt(graph: IMGraph, seed: int | None = None) list[int]

采样一个 LT 模型的 RR 集合。

Parameters:
  • graph – IMGraph 图对象。

  • seed – 随机种子,可选。

Returns:

RR 集合中的节点列表。

Return type:

list[int]

Example

>>> from pynetim.utils import sample_rr_set_lt
>>> rr_set = sample_rr_set_lt(graph, seed=42)
pynetim.utils.save_edgelist(graph, filepath, delimiter='\t', include_weight=True)[source]

将 IMGraph 保存为边列表文件。

Parameters

graphIMGraph

图对象

filepathstr or Path

输出文件路径

delimiterstr, optional

分隔符,默认制表符

include_weightbool, optional

是否包含权重列,默认 True

Examples

>>> g = IMGraph(edges=[(0, 1), (1, 2)], weights=[0.5, 0.8])
>>> save_edgelist(g, "output.txt")
Parameters:
Return type:

None

pynetim.utils.shortest_path_length(graph, source, target, use_weight=False)[source]

计算两个节点之间的最短路径长度。

Parameters:
  • graph (IMGraph) – 图对象。

  • source (int) – 源节点。

  • target (int) – 目标节点。

  • use_weight (bool) – 是否使用边权重计算最短路径。 - False (默认): 使用跳数(边数)作为距离 - True: 使用边权重之和作为距离

Returns:

最短路径长度,如果不可达则返回 None。
  • use_weight=False 时返回整数(跳数)

  • use_weight=True 时返回浮点数(权重和)

Return type:

Optional[float]

Example

>>> from pynetim.utils import shortest_path_length
>>> # 基于跳数
>>> dist = shortest_path_length(graph, 0, 5, use_weight=False)
>>> # 基于权重
>>> dist = shortest_path_length(graph, 0, 5, use_weight=True)
pynetim.utils.to_igraph(graph)[source]

将 IMGraph 转换为 igraph.Graph。

Parameters

graphIMGraph

图对象

Returns

igraph.Graph

igraph 图对象,边权重存储在 ‘weight’ 属性中

Examples

>>> g = IMGraph(edges=[(0, 1), (1, 2)], directed=True)
>>> ig_g = to_igraph(g)
>>> ig_g.vcount()
3
Parameters:

graph (IMGraph)

pynetim.utils.to_networkx(graph)[source]

将 IMGraph 转换为 networkx.DiGraph 或 networkx.Graph。

Parameters

graphIMGraph

图对象

Returns

networkx.DiGraph 或 networkx.Graph

取决于原图是否有向

Examples

>>> g = IMGraph(edges=[(0, 1), (1, 2)], directed=True)
>>> nx_g = to_networkx(g)
>>> nx_g.number_of_nodes()
3
Parameters:

graph (IMGraph)

pynetim.utils.to_pyg(graph)[source]

将 IMGraph 转换为 PyTorch Geometric Data 对象。

Parameters

graphIMGraph

图对象

Returns

torch_geometric.data.Data

PyG Data 对象,包含 edge_index 和 edge_attr (权重)

Examples

>>> g = IMGraph(edges=[(0, 1), (1, 2)], weights=[0.5, 0.8], directed=True)
>>> pyg_g = to_pyg(g)
>>> pyg_g.num_nodes
3
Parameters:

graph (IMGraph)

pynetim.utils.to_scipy_sparse(graph, format='csr')[source]

将 IMGraph 转换为 scipy 稀疏矩阵。

Parameters

graphIMGraph

图对象

formatstr, optional

稀疏矩阵格式,可选 ‘csr’, ‘csc’, ‘coo’, ‘lil’, ‘dok’,默认 ‘csr’

Returns

scipy.sparse.spmatrix

稀疏邻接矩阵,matrix[i, j] 表示边 (i, j) 的权重

Examples

>>> g = IMGraph(edges=[(0, 1), (1, 2)], weights=[0.5, 0.8], directed=True)
>>> mat = to_scipy_sparse(g)
>>> mat.toarray()
array([[0. , 0.5, 0. ],
       [0. , 0. , 0.8],
       [0. , 0. , 0. ]])
Parameters: