API 参考

Python 模块

图模块

class pynetim.py.graph.IMGraph(graph: Graph | DiGraph, edge_weight_type: str, constant_weight: float | None = None)[source]

Bases: object

影响最大化图类,用于封装网络图结构和边权重设置。

该类提供了对NetworkX图对象的封装,支持设置不同类型的边权重, 并提供了便捷的图属性访问接口。

graph

networkx图对象,可以是有向图或无向图

Type:

Graph | DiGraph

direction

指示图是否有向

Type:

bool

number_of_nodes

图中节点总数

Type:

int

number_of_edges

图中边总数

Type:

int

edge_weight_type

边权重类型

Type:

str

batch_degree(nodes)[source]

批量获取指定节点的度。

Parameters:

nodes – 节点列表

Returns:

每个节点的度列表

Return type:

list

batch_in_degree(nodes)[source]

批量获取指定节点的入度。

Parameters:

nodes – 节点列表

Returns:

每个节点的入度列表

Return type:

list

batch_out_degree(nodes)[source]

批量获取指定节点的出度。

Parameters:

nodes – 节点列表

Returns:

每个节点的出度列表

Return type:

list

degree()[source]

获取图的度。

Returns:

图的度视图

Return type:

int

property edges

获取图中所有边。

Returns:

图中所有边的视图

Return type:

EdgeView

property in_degree

获取图的入度。

Returns:

图的入度视图

Return type:

int

in_neighbors(node)[source]

获取指定节点的入邻居节点。

对于有向图,返回前驱节点;对于无向图,返回所有邻居节点。

Parameters:

node – 节点标识符

Returns:

指定节点的入邻居节点迭代器

Return type:

iterator

neighbors(node)[source]

获取指定节点的邻居节点。

Parameters:

node – 节点标识符

Returns:

指定节点的所有邻居节点迭代器

Return type:

iterator

property nodes

获取图中所有节点。

Returns:

图中所有节点的视图

Return type:

NodeView

property out_degree

获取图的出度。

Returns:

图的出度视图

Return type:

int

out_neighbors(node)[source]

获取指定节点的出邻居节点。(同neighbors方法)

Parameters:

node – 节点标识符

Returns:

指定节点的出邻居节点迭代器

Return type:

iterator

算法模块

class pynetim.py.algorithms.BaseRISAlgorithm(graph: IMGraph, diffusion_model: str = 'IC', multi_process: bool = False, processes: int | None = None, seed: int | None = None)[source]

Bases: BaseAlgorithm

最简版反向影响采样算法(Reverse Influence Sampling, RIS)

说明: - 不自动估计采样数量 - 用户指定RR集合数量(num_rr_sets) - 使用堆优化贪心选择(O(R log k)而非O(R k)) - 支持IC/LT模型

参考文献:
  • Borgs, C., Brautbar, M., Chitnis, N., & Tardos, É. (2014). “Maximizing social influence in nearly optimal time.” Proceedings of the 25th ACM-SIAM Symposium on Discrete Algorithms (SODA), 946-957. DOI: 10.1137/1.9781611973402.70 URL: https://epubs.siam.org/doi/10.1137/1.9781611973402.70

graph

输入图对象

Type:

IMGraph

model

扩散模型名称(‘IC’或’LT’)

Type:

str

nodes

图中所有节点的列表

Type:

list

rr_func

用于生成RR集合的函数

Type:

Callable

multi_process

是否启用多进程模式

Type:

bool

processes

多进程模式下的进程数

Type:

int

seed

随机种子

Type:

int

run(k: int, num_rr_sets: int) List[int][source]

执行简单RIS算法。

Parameters:
  • k (int) – 种子集合大小

  • num_rr_sets (int) – RR集合采样数量(越大越准)

Returns:

选出的k个种子节点

Return type:

Set[int]

class pynetim.py.algorithms.CELFAlgorithm(graph: IMGraph, diffusion_model: BaseDiffusionModel)[source]

Bases: BaseAlgorithm

CELF算法选择影响力最大化种子节点

CELF (Cost-Effective Lazy Forward) 算法是贪婪算法的优化版本, 利用边际增益的子模特性减少计算量,通过优先队列维护节点的边际增益, 避免重复计算已失效的边际增益。

graph

输入图对象

Type:

IMGraph

diffusion_model_class

影响传播模型类

Type:

BaseDiffusionModel

run(k: int, round: int, multi_process=False, processes=None, show_progress=True, seed: int | None = None)[source]

运行CELF算法选择影响力最大化种子节点。

Parameters:
  • k (int) – 种子节点数量

  • round (int) – 蒙特卡洛模拟次数

  • multi_process (bool, optional) – 是否启用多进程模式,默认为False

  • processes (int, optional) – 多进程模式下的进程数,为None时使用默认值

  • show_progress (bool, optional) – 是否显示进度条,默认为True

  • seed (int, optional) – 模拟的随机数种子,默认为None

Returns:

选择的种子节点列表

Return type:

list

class pynetim.py.algorithms.DegreeDiscountAlgorithm(graph: IMGraph, diffusion_model='IC')[source]

Bases: BaseAlgorithm

度折扣启发式算法(Degree Discount)用于选择影响力最大化种子节点。

该算法是Single Discount的改进版本,考虑了邻居节点之间的影响关系, 使用更复杂的折扣公式来更好地评估节点的边际影响力。

参考文献:
  • Chen, W., Wang, Y., & Yang, S. (2009). “Efficient influence maximization in social networks.” Proceedings of the 15th ACM SIGKDD International Conference on Knowledge Discovery and Data Mining (KDD), 199-208. DOI: 10.1145/1557019.1557047 URL: https://dl.acm.org/doi/10.1145/1557019.1557047

run(k: int)[source]

运行度折扣算法选择k个种子节点。

Parameters:

k (int) – 需要选择的种子节点数量

Returns:

选择的种子节点列表

Return type:

list

class pynetim.py.algorithms.GreedyAlgorithm(graph: IMGraph, diffusion_model: BaseDiffusionModel)[source]

Bases: BaseAlgorithm

贪婪算法 (Greedy) 选择影响力最大化种子节点

该算法通过迭代地选择具有最大边际影响力的节点作为种子节点, 直到选够k个种子节点。每次选择都需要计算所有候选节点的边际增益。

graph

输入图对象

Type:

IMGraph

diffusion_model_class

影响传播模型类

Type:

BaseDiffusionModel

run(k: int, round: int, multi_process=False, processes=None, show_progress=True, seed: int | None = None)[source]

运行贪婪算法选择影响力最大化种子节点。

Parameters:
  • k (int) – 种子节点数量

  • round (int) – 每次计算边际增益的蒙特卡洛模拟次数

  • multi_process (bool, optional) – 是否启用多进程模式,默认为False

  • processes (int, optional) – 多进程模式下的进程数,为None时使用默认值

  • show_progress (bool, optional) – 是否显示进度条,默认为True

  • seed (int, optional) – 模拟的随机种子,默认为None

Returns:

选择的种子节点列表

Return type:

list

class pynetim.py.algorithms.IMMAlgorithm(graph: IMGraph, diffusion_model: str = 'IC', eps: float = 0.5, l: int = 1, multi_process: bool = False, processes: int | None = None, seed: int | None = None)[source]

Bases: BaseRISAlgorithm

基于鞅的影响力最大化算法(Influence Maximization via Martingales, IMM)

支持IC和LT两种扩散模型

参考文献:
  • Tang, Y., Xiao, X., & Shi, Y. (2015). “Influence maximization: Near-optimal time complexity meets practical efficiency.” Proceedings of the 2015 ACM SIGMOD International Conference on Management of Data (SIGMOD), 75-86. DOI: 10.1145/2723372.2723734 URL: https://dl.acm.org/doi/10.1145/2723372.2723734

eps

近似参数ε

Type:

float

l

失败概率参数l

Type:

float

run(k: int) List[int][source]

执行IMM算法,返回大小为k的种子集合。

Parameters:

k (int) – 需要选择的种子节点数量

Returns:

选出的种子节点集合

Return type:

Set[int]

class pynetim.py.algorithms.SingleDiscountAlgorithm(graph: IMGraph, diffusion_model=None)[source]

Bases: BaseAlgorithm

简单度折扣启发式算法(Single Discount)用于选择影响力最大化种子节点。

该算法通过逐步选择具有最高度数的节点作为种子,并对其邻居节点的度数进行折扣, 以避免选择过多相互连接的节点。

参考文献:
  • Chen, W., Wang, Y., & Yang, S. (2009). “Efficient influence maximization in social networks.” Proceedings of the 15th ACM SIGKDD International Conference on Knowledge Discovery and Data Mining (KDD), 199-208. DOI: 10.1145/1557019.1557047 URL: https://dl.acm.org/doi/10.1145/1557019.1557047

run(k: int)[source]

运行简单度折扣算法选择k个种子节点。

Parameters:

k (int) – 需要选择的种子节点数量

Returns:

选择的种子节点列表

Return type:

list

扩散模型模块

class pynetim.py.diffusion_model.IndependentCascadeModel(graph: IMGraph, init_seeds: list, record_states: bool = False)[source]

Bases: BaseDiffusionModel

独立级联模型(Independent Cascade Model)。

实现了经典的独立级联传播模型,该模型是一种离散时间传播模型, 在每一轮中,已激活的节点尝试激活其未激活的邻居节点。 每条边都有固定的传播概率,当节点尝试传播时,根据概率决定是否成功激活邻居。

参考文献:
  • Kempe, D., Kleinberg, J., & Tardos, É. (2003). “Maximizing the spread of influence through a social network.” Proceedings of the 9th ACM SIGKDD International Conference on Knowledge Discovery and Data Mining (KDD), 137-146. DOI: 10.1145/956750.956769 URL: https://dl.acm.org/doi/10.1145/956750.956769

activated_nodes

所有已被激活的节点集合

Type:

set

graph

表示传播网络结构(继承自BaseDiffusionModel)

Type:

IMGraph

init_seeds

初始种子集(继承自BaseDiffusionModel)

Type:

list

record_states

指示是否记录传播过程中的状态变化(继承自BaseDiffusionModel)

Type:

bool

states

当record_states为True时存储传播过程的状态历史(继承自BaseDiffusionModel)

Type:

list

diffusion(update_counts=None)[source]

执行完整的扩散过程。

进行指定轮次的传播更新,直到达到最大轮次或没有新的节点被激活。

Parameters:

update_counts (int, optional) – 最大更新轮次数。如果为None则持续传播直到无新节点激活

Returns:

最终所有被激活的节点集合

Return type:

set

reset(init_seeds=None)[source]

重置模型状态。

将模型恢复到初始状态,如果启用状态记录则清空已记录的状态历史, 并重新设置初始种子节点状态。

Parameters:

init_seeds (list, optional) – 新的初始种子节点集合,若为None则使用原有种子集

run_monte_carlo_diffusion(rounds: int, update_counts: int | None = None, multi_process: bool = False, processes: int | None = None, seed: int | None = None)[source]

执行蒙特卡洛模拟扩散过程。

Parameters:
  • rounds (int) – 总模拟轮数

  • update_counts (int, optional) – 更新轮次数,适用于SI模型等需要限制传播轮次的模型

  • multi_process (bool) – 是否启用多进程模式,默认为False

  • processes (int, optional) – 多进程模式下的进程数,为None时使用CPU核心数

  • seed (int, optional) – 模拟时的随机种子

Returns:

所有模拟轮次的平均激活节点数

Return type:

float

update(current_activated_nodes: set)[source]

执行一次传播更新。

在当前轮次中,所有新激活的节点尝试激活它们的未激活邻居节点。 成功激活的节点将在下一轮继续传播。

Parameters:

current_activated_nodes (set) – 当前轮次需要尝试传播的已激活节点集合

Returns:

本轮新激活的节点集合

Return type:

set

class pynetim.py.diffusion_model.LinearThresholdModel(graph: IMGraph, init_seeds: list, record_states: bool = False)[source]

Bases: BaseDiffusionModel

线性阈值模型(Linear Threshold Model)。

实现了经典的线性阈值传播模型,该模型是一种离散时间传播模型, 每个节点都有一个随机阈值,当其已激活邻居的影响力总和超过该阈值时, 节点被激活。每个节点对其他节点的影响力通过边权重表示。

参考文献:
  • Granovetter, M. (1978). “Threshold models of collective behavior.” American Journal of Sociology, 83(6), 1420-1443. DOI: 10.1086/226707 URL: https://www.jstor.org/stable/2778111

activated_nodes

所有已被激活的节点集合

Type:

set

graph

表示传播网络结构(继承自BaseDiffusionModel)

Type:

IMGraph

init_seeds

初始种子集(继承自BaseDiffusionModel)

Type:

list

record_states

指示是否记录传播过程中的状态变化(继承自BaseDiffusionModel)

Type:

bool

states

当record_states为True时存储传播过程的状态历史(继承自BaseDiffusionModel)

Type:

list

diffusion(update_counts: int | None = None)[source]

执行完整的扩散过程。

进行指定轮次的传播更新,直到达到最大轮次或没有新的节点被激活。

Parameters:

update_counts (int, optional) – 最大更新轮次数。如果为None则持续传播直到无新节点激活

Returns:

最终所有被激活的节点集合

Return type:

set

reset(init_seeds=None)[source]

重置模型状态。

将模型恢复到初始状态,如果启用状态记录则清空已记录的状态历史, 并重新设置初始种子节点状态。

Parameters:

init_seeds (list, optional) – 新的初始种子节点集合,若为None则使用原有种子集

run_monte_carlo_diffusion(rounds: int, update_counts: int | None = None, multi_process: bool = False, processes: int | None = None, seed: int | None = None)[source]

执行蒙特卡洛模拟扩散过程。

Parameters:
  • rounds (int) – 总模拟轮数

  • update_counts (int, optional) – 更新轮次数,适用于SI模型等需要限制传播轮次的模型

  • multi_process (bool) – 是否启用多进程模式,默认为False

  • processes (int, optional) – 多进程模式下的进程数,为None时使用CPU核心数

  • seed (int, optional) – 模拟时的随机种子

Returns:

所有模拟轮次的平均激活节点数

Return type:

float

update(current_activated_nodes: set)[source]

执行一次传播更新。

在线性阈值模型中,未激活的节点检查其已激活邻居的影响力总和, 如果超过节点的阈值则被激活。

Parameters:

current_activated_nodes (set) – 当前轮次需要尝试传播的已激活节点集合

Returns:

本轮新激活的节点集合

Return type:

set

class pynetim.py.diffusion_model.SusceptibleInfectedModel(graph: IMGraph, init_seeds: list, beta: float | None = None, record_states: bool = False)[source]

Bases: BaseDiffusionModel

SI模型(Susceptible-Infected Model)。

实现了经典的SI传播模型,该模型是一种简单的传染病传播模型, 节点只有两种状态:易感(S)和感染(I)。一旦节点被感染,它将始终保持感染状态 并持续尝试感染其邻居节点。

参考文献:
infected_nodes

所有已被感染的节点集合

Type:

set

graph

表示传播网络结构(继承自BaseDiffusionModel)

Type:

IMGraph

init_seeds

初始感染节点集(继承自BaseDiffusionModel)

Type:

list

record_states

指示是否记录传播过程中的状态变化(继承自BaseDiffusionModel)

Type:

bool

states

当record_states为True时存储传播过程的状态历史(继承自BaseDiffusionModel)

Type:

list

beta

感染概率

Type:

float

diffusion(update_counts)[source]

执行完整的扩散过程。

进行指定轮次的传播更新,直到达到最大轮次或没有新的节点被感染。

Parameters:

update_counts (int) – 最大更新轮次数。

Returns:

最终所有被感染的节点集合

Return type:

set

reset(init_seeds=None)[source]

重置模型状态。

将模型恢复到初始状态,如果启用状态记录则清空已记录的状态历史, 并重新设置初始感染节点状态。

Parameters:

init_seeds (list, optional) – 新的初始感染节点集合,若为None则使用原有种子集

run_monte_carlo_diffusion(rounds: int, update_counts: int, multi_process: bool = False, processes: int | None = None, seed: int | None = None)[source]

执行蒙特卡洛模拟扩散过程。

Parameters:
  • rounds (int) – 总模拟轮数

  • update_counts (int) – 更新轮次数,适用于SI模型等需要限制传播轮次的模型

  • multi_process (bool) – 是否启用多进程模式,默认为False

  • processes (int, optional) – 多进程模式下的进程数,为None时使用CPU核心数

  • seed (int, optional) – 模拟时的随机种子

Returns:

所有模拟轮次的平均激活节点数

Return type:

float

update()[source]

执行一次传播更新。

在当前轮次中,所有已感染的节点尝试感染它们的易感邻居节点。 成功感染的节点将在后续所有轮次中继续传播。

Returns:

本轮新感染的节点集合

Return type:

set

class pynetim.py.diffusion_model.SusceptibleInfectedRecoveredModel(graph: IMGraph, init_seeds: list, gamma: float, beta: float | None = None, record_states: bool = False)[source]

Bases: BaseDiffusionModel

SIR模型(Susceptible-Infected-Recovered Model)。

实现了经典的SIR传播模型,该模型是一种传染病传播模型, 节点有三种状态:易感(S)、感染(I)和康复(R)。 易感节点可被感染节点感染,感染节点可以康复为免疫状态。

参考文献:
infected_nodes

所有已被感染的节点集合

Type:

set

recovered_nodes

所有已康复的节点集合

Type:

set

graph

表示传播网络结构(继承自BaseDiffusionModel)

Type:

IMGraph

init_seeds

初始感染节点集(继承自BaseDiffusionModel)

Type:

list

record_states

指示是否记录传播过程中的状态变化(继承自BaseDiffusionModel)

Type:

bool

states

当record_states为True时存储传播过程的状态历史(继承自BaseDiffusionModel)

Type:

list

gamma

康复率

Type:

float

beta

感染率

Type:

float

diffusion(update_counts=None)[source]

执行完整的扩散过程。

进行指定轮次的传播更新,直到达到最大轮次或没有新的节点被感染。

Parameters:

update_counts (int, optional) – 最大更新轮次数。如果为None则持续传播直到无新节点感染

Returns:

包含最终各状态节点集合的字典
  • ’infected’: 最终被感染的节点集合

  • ’recovered’: 最终已康复的节点集合

  • ’susceptible’: 最终仍处于易感状态的节点集合

Return type:

dict

reset(init_seeds=None)[source]

重置模型状态。

将模型恢复到初始状态,如果启用状态记录则清空已记录的状态历史, 并重新设置初始感染节点状态。

Parameters:

init_seeds (list, optional) – 新的初始感染节点集合,若为None则使用原有种子集

run_monte_carlo_diffusion(rounds: int, update_counts: int | None = None, multi_process: bool = False, processes: int | None = None, seed: int | None = None)[source]

执行蒙特卡洛模拟扩散过程。

Parameters:
  • rounds (int) – 总模拟轮数

  • update_counts (int, optional) – 更新轮次数,适用于SI模型等需要限制传播轮次的模型

  • multi_process (bool) – 是否启用多进程模式,默认为False

  • processes (int, optional) – 多进程模式下的进程数,为None时使用CPU核心数

  • seed (int, optional) – 模拟时的随机种子

Returns:

所有模拟轮次的平均激活节点数

Return type:

float

update()[source]

执行一次传播更新。

在当前轮次中,先处理感染节点的康复,然后已感染的节点尝试感染它们的易感邻居节点。

Returns:

本轮新感染的节点集合

Return type:

set

pynetim.py.diffusion_model.run_monte_carlo_diffusion(diffusion_model: BaseDiffusionModel, rounds: int, update_counts: int | None = None, multi_process: bool = False, processes: int | None = None, seed: int | None = None)[source]

执行蒙特卡洛模拟扩散过程,支持单进程和多进程模式。

Parameters:
  • diffusion_model (BaseDiffusionModel) – 扩散模型实例

  • rounds (int) – 总模拟轮数

  • update_counts (int, optional) – 更新轮次数,适用于SI等模型

  • multi_process (bool, optional) – 是否启用多进程模式,默认为False

  • processes (int, optional) – 多进程模式下的进程数,为None时使用CPU核心数

  • seed (int, optional) – 随机种子的基础值,默认为None

Returns:

所有模拟轮次的平均激活节点数

Return type:

float

工具函数模块

pynetim.utils.connectivity_analysis(graph: Graph | DiGraph | IMGraphCpp) Dict[str, Any][source]

分析图的连通性(支持NetworkX图和C++图)

参数:

graph (Graph|DiGraph|IMGraphCpp): 网络图对象,可以是有向图、无向图或C++图

返回:
dict: 包含以下连通性信息的字典
  • is_connected: 是否连通(仅NetworkX图支持)

  • num_components: 连通分量数(仅NetworkX图支持)

  • largest_component_size: 最大连通分量大小(仅NetworkX图支持)

  • component_sizes: 所有连通分量大小列表(仅NetworkX图支持)

  • weakly_connected: 是否弱连通(仅NetworkX图支持)

pynetim.utils.graph_density(graph: Graph | DiGraph | IMGraphCpp) float[source]

计算图的密度(支持NetworkX图和C++图)

参数:

graph (Graph|DiGraph|IMGraphCpp): 网络图对象,可以是有向图、无向图或C++图

返回:

float: 图密度值,范围在[0, 1]之间

说明:

图密度定义为实际边数与可能的最大边数的比值 有向图: |E| / (|V| * (|V| - 1)) 无向图: 2 * |E| / (|V| * (|V| - 1))

pynetim.utils.graph_statistics(graph: Graph | DiGraph | IMGraphCpp) Dict[str, Any][source]

计算并返回图的详细统计信息(支持NetworkX图和C++图)

参数:

graph (Graph|DiGraph|IMGraphCpp): 网络图对象,可以是有向图、无向图或C++图

返回:
dict: 包含以下统计信息的字典
  • num_nodes: 节点数

  • num_edges: 边数

  • avg_degree: 平均度

  • max_degree: 最大度

  • min_degree: 最小度

  • degree_distribution: 度分布

  • density: 图密度

  • is_connected: 是否连通(仅NetworkX图支持)

  • num_components: 连通分量数(仅NetworkX图支持)

pynetim.utils.infection_threshold(graph: Graph | DiGraph | IMGraphCpp) float[source]

计算基于图graph的度分布的感染阈值。

参数:

graph (Graph|DiGraph|IMGraphCpp): 网络图对象,可以是有向图、无向图或C++图

返回:

float: 感染阈值(是1.05倍的阈值)。

说明:

该函数首先计算图中所有节点的度之和(k),然后计算所有节点度的平方和(k2)。 感染阈值计算公式为 k / (k2 - k),其中k2是度的平方和,k是度的总和。 这个阈值在某些流行病学模型(如SIR模型)中用于预测疾病传播的临界条件。

参考文献:
pynetim.utils.set_edge_weight(graph: Graph | DiGraph | IMGraphCpp, edge_weight_type: str, constant_weight: float = None)[source]

根据指定的权重模型为图中的边设置权重值。

参数:

graph (Graph|DiGraph|IMGraphCpp): 网络图对象,可以是有向图、无向图或C++图 edge_weight_type (str): 边权重类型,支持 ‘CONSTANT’、’TV’、’WC’ 三种模式 constant_weight (float, optional): 当使用常量权重模式时,指定的权重值

异常:

ValueError: 当权重类型不支持或参数不符合要求时抛出

pynetim.utils.topk(res_dict: dict, k: int, largest: bool = True) List[source]

从字典中返回具有最大(或最小)k个值的键的列表。

参数:

res_dict (dict): 输入的字典,其值用于比较以决定键的排序。 k (int): 要返回的键的数量。 largest (bool): 如果为True,则返回具有最大值的k个键;如果为False,则返回具有最小值的k个键。

返回:

list: 一个包含k个键的列表,这些键对应于字典中最大(或最小)的值。

pynetim.utils.truncate_padding(seq, max_len, pad=0)[source]

C++ 模块

C++ 图模块

class pynetim.cpp.graph.IMGraphCpp

Bases: pybind11_object

add_edge(self: pynetim.cpp.graph.graph.IMGraphCpp, u: SupportsInt | SupportsIndex, v: SupportsInt | SupportsIndex, w: SupportsFloat | SupportsIndex = 1.0) None

Add a weighted edge u -> v (or u - v if undirected)

add_edges(self: pynetim.cpp.graph.graph.IMGraphCpp, edges: collections.abc.Sequence[tuple[SupportsInt | SupportsIndex, SupportsInt | SupportsIndex]], weights: collections.abc.Sequence[SupportsFloat | SupportsIndex] = []) None

Add multiple edges at once. edges is a list of (u, v) tuples.

batch_degree(self: pynetim.cpp.graph.graph.IMGraphCpp, nodes: collections.abc.Sequence[SupportsInt | SupportsIndex]) list[int]

Return degrees of specified nodes

batch_get_edge_weight(self: pynetim.cpp.graph.graph.IMGraphCpp, edges: collections.abc.Sequence[tuple[SupportsInt | SupportsIndex, SupportsInt | SupportsIndex]]) list[float]

Return weights of specified edges (list of (u, v) tuples)

batch_in_degree(self: pynetim.cpp.graph.graph.IMGraphCpp, nodes: collections.abc.Sequence[SupportsInt | SupportsIndex]) list[int]

Return in-degrees of specified nodes

batch_out_degree(self: pynetim.cpp.graph.graph.IMGraphCpp, nodes: collections.abc.Sequence[SupportsInt | SupportsIndex]) list[int]

Return out-degrees of specified nodes

batch_out_neighbors(self: pynetim.cpp.graph.graph.IMGraphCpp, nodes: collections.abc.Sequence[SupportsInt | SupportsIndex]) list[list[tuple[int, float]]]

Return outgoing neighbors of specified nodes (list of lists of (neighbor, weight) tuples)

degree(self: pynetim.cpp.graph.graph.IMGraphCpp, u: SupportsInt | SupportsIndex) int
property directed

Whether the graph is directed

property edges

Edges and weights of graph

get_adj_list(self: pynetim.cpp.graph.graph.IMGraphCpp) list[list[pynetim.cpp.graph.graph.Edge]]

Return the full adjacency list (list of lists of Edge objects)

get_adj_matrix(self: pynetim.cpp.graph.graph.IMGraphCpp) list[list[float]]

Return dense adjacency matrix (list of lists of float)

get_adj_matrix_sparse(self: pynetim.cpp.graph.graph.IMGraphCpp) list[tuple[int, int, float]]

Return sparse adjacency matrix (list of (u, v, weight) tuples)

get_all_degrees(self: pynetim.cpp.graph.graph.IMGraphCpp) list[int]

Return degree of all nodes as a list

get_all_in_degrees(self: pynetim.cpp.graph.graph.IMGraphCpp) list[int]

Return in-degree of all nodes as a list

get_all_out_degrees(self: pynetim.cpp.graph.graph.IMGraphCpp) list[int]

Return out-degree of all nodes as a list

get_edge_weight(self: pynetim.cpp.graph.graph.IMGraphCpp, u: SupportsInt | SupportsIndex, v: SupportsInt | SupportsIndex) float

Get the weight of edge (u, v)

in_degree(self: pynetim.cpp.graph.graph.IMGraphCpp, u: SupportsInt | SupportsIndex) int
in_neighbors(self: pynetim.cpp.graph.graph.IMGraphCpp, u: SupportsInt | SupportsIndex) list[int]

Return incoming neighbors of node u (as list of node IDs)

property num_edges

Number of edges

property num_nodes

Number of nodes

out_degree(self: pynetim.cpp.graph.graph.IMGraphCpp, u: SupportsInt | SupportsIndex) int
out_neighbors(self: pynetim.cpp.graph.graph.IMGraphCpp, u: SupportsInt | SupportsIndex) list[pynetim.cpp.graph.graph.Edge]

Return outgoing neighbors of node u (as list of Edge objects)

remove_edge(self: pynetim.cpp.graph.graph.IMGraphCpp, u: SupportsInt | SupportsIndex, v: SupportsInt | SupportsIndex) None
remove_edges(self: pynetim.cpp.graph.graph.IMGraphCpp, edges: collections.abc.Sequence[tuple[SupportsInt | SupportsIndex, SupportsInt | SupportsIndex]]) None
update_edge_weight(self: pynetim.cpp.graph.graph.IMGraphCpp, u: SupportsInt | SupportsIndex, v: SupportsInt | SupportsIndex, w: SupportsFloat | SupportsIndex) None

Update the weight of an existing edge

C++ 扩散模型模块

class pynetim.cpp.diffusion_model.IndependentCascadeModel

Bases: pybind11_object

get_activated_nodes(self: pynetim.cpp.diffusion_model.independent_cascade_model.IndependentCascadeModel) set[int]

Get set of activated nodes from last simulation.

Returns:

Set of activated nodes from the last simulation. For single simulation: nodes activated in that simulation. For Monte Carlo: union of all activated nodes across all trials. Only valid when record_activated is set to True.

Return type:

Set[int]

Examples

>>> model.set_record_activated(True)
>>> count = model.run_single_simulation()
>>> activated_nodes = model.get_activated_nodes()
>>> print(f"Activated {count} nodes: {activated_nodes}")
get_activation_frequency(self: pynetim.cpp.diffusion_model.independent_cascade_model.IndependentCascadeModel) list[int]

Get activation frequency of each node from all simulations.

Returns:

List where index i represents how many times node i was activated. Only valid when record_activation_frequency is set to True.

Return type:

List[int]

Examples

>>> model.set_record_activation_frequency(True)
>>> avg = model.run_monte_carlo_diffusion(1000)
>>> freq = model.get_activation_frequency()
>>> print(f"Node 0 was activated {freq[0]} times")
run_monte_carlo_diffusion(self: pynetim.cpp.diffusion_model.independent_cascade_model.IndependentCascadeModel, rounds: SupportsInt | SupportsIndex, seed: object = None, use_multithread: bool = False, num_threads: SupportsInt | SupportsIndex = 0) float

Run Monte Carlo simulation of IC diffusion. Returns average number of activated nodes over ‘rounds’ trials.

Parameters:
  • rounds (int) – Number of simulation trials

  • seed (int or None, optional) – Random seed for reproducibility. If None (default), uses a truly random seed. Use the same seed to get reproducible results.

  • use_multithread (bool, optional) – Whether to use multithreading (default: False)

  • num_threads (int, optional) – Number of threads to use (0 = auto-detect, default: 0)

Returns:

Average number of activated nodes over all trials

Return type:

float

Examples

>>> avg = model.run_monte_carlo_diffusion(1000)  # Random seed
>>> avg = model.run_monte_carlo_diffusion(1000, seed=42)  # Reproducible result
>>> avg = model.run_monte_carlo_diffusion(1000, seed=42, use_multithread=True, num_threads=4)
run_single_simulation(self: pynetim.cpp.diffusion_model.independent_cascade_model.IndependentCascadeModel, seed: object = None) int

Run a single diffusion simulation and return number of activated nodes.

Parameters:

seed (int or None, optional) – Random seed for reproducibility. If None (default), uses a truly random seed. Use the same seed to get reproducible results.

Returns:

Number of activated nodes in this simulation

Return type:

int

Examples

>>> count = model.run_single_simulation()  # Random result
>>> count = model.run_single_simulation(seed=42)  # Reproducible result
>>> activated_nodes = model.get_activated_nodes()  # Get recorded nodes (if record_activated=True)
set_record_activated(self: pynetim.cpp.diffusion_model.independent_cascade_model.IndependentCascadeModel, record: bool) None

Enable or disable recording of activated nodes

set_record_activation_frequency(self: pynetim.cpp.diffusion_model.independent_cascade_model.IndependentCascadeModel, record: bool) None

Enable or disable recording of activation frequency

set_seeds(self: pynetim.cpp.diffusion_model.independent_cascade_model.IndependentCascadeModel, new_seeds: collections.abc.Set[SupportsInt | SupportsIndex]) None

Update seed set

class pynetim.cpp.diffusion_model.LinearThresholdModel

Bases: pybind11_object

get_activated_nodes(self: pynetim.cpp.diffusion_model.linear_threshold_model.LinearThresholdModel) set[int]

Get set of activated nodes from last simulation.

Returns:

Set of activated nodes from the last simulation. For single simulation: nodes activated in that simulation. For Monte Carlo: union of all activated nodes across all trials. Only valid when record_activated is set to True.

Return type:

Set[int]

Examples

>>> model.set_record_activated(True)
>>> count = model.run_single_simulation()
>>> activated_nodes = model.get_activated_nodes()
>>> print(f"Activated {count} nodes: {activated_nodes}")
get_activation_frequency(self: pynetim.cpp.diffusion_model.linear_threshold_model.LinearThresholdModel) list[int]

Get activation frequency of each node from all simulations.

Returns:

List where index i represents how many times node i was activated. Only valid when record_activation_frequency is set to True.

Return type:

List[int]

Examples

>>> model.set_record_activation_frequency(True)
>>> avg = model.run_monte_carlo_diffusion(1000)
>>> freq = model.get_activation_frequency()
>>> print(f"Node 0 was activated {freq[0]} times")
run_monte_carlo_diffusion(self: pynetim.cpp.diffusion_model.linear_threshold_model.LinearThresholdModel, rounds: SupportsInt | SupportsIndex, seed: object = None, use_multithread: bool = False, num_threads: SupportsInt | SupportsIndex = 0) float

Run Monte Carlo simulation of LT diffusion. Returns average number of activated nodes.

Parameters:
  • rounds (int) – Number of simulation trials

  • seed (int or None, optional) – Random seed for reproducibility. If None (default), uses a truly random seed. Use the same seed to get reproducible results.

  • use_multithread (bool, optional) – Whether to use multithreading (default: False)

  • num_threads (int, optional) – Number of threads to use (0 = auto-detect, default: 0)

Returns:

Average number of activated nodes over all trials

Return type:

float

Examples

>>> avg = model.run_monte_carlo_diffusion(1000)  # Random seed
>>> avg = model.run_monte_carlo_diffusion(1000, seed=42)  # Reproducible result
>>> avg = model.run_monte_carlo_diffusion(1000, seed=42, use_multithread=True, num_threads=4)
run_single_simulation(self: pynetim.cpp.diffusion_model.linear_threshold_model.LinearThresholdModel, seed: object = None) int

Run a single diffusion simulation and return number of activated nodes.

Parameters:

seed (int or None, optional) – Random seed for reproducibility. If None (default), uses a truly random seed. Use the same seed to get reproducible results.

Returns:

Number of activated nodes in this simulation

Return type:

int

Examples

>>> count = model.run_single_simulation()  # Random result
>>> count = model.run_single_simulation(seed=42)  # Reproducible result
>>> activated_nodes = model.get_activated_nodes()  # Get recorded nodes (if record_activated=True)
set_record_activated(self: pynetim.cpp.diffusion_model.linear_threshold_model.LinearThresholdModel, record: bool) None

Enable or disable recording of activated nodes

set_record_activation_frequency(self: pynetim.cpp.diffusion_model.linear_threshold_model.LinearThresholdModel, record: bool) None

Enable or disable recording of activation frequency

set_seeds(self: pynetim.cpp.diffusion_model.linear_threshold_model.LinearThresholdModel, new_seeds: collections.abc.Set[SupportsInt | SupportsIndex]) None

Update seed set

class pynetim.cpp.diffusion_model.SusceptibleInfectedModel

Bases: pybind11_object

get_activated_nodes(self: pynetim.cpp.diffusion_model.susceptible_infected_model.SusceptibleInfectedModel) set[int]

Get set of infected nodes from last simulation.

Returns:

Set of infected nodes from the last simulation. For single simulation: nodes infected in that simulation. For Monte Carlo: union of all infected nodes across all trials. Only valid when record_activated is set to True.

Return type:

Set[int]

Examples

>>> model.set_record_activated(True)
>>> count = model.run_single_simulation()
>>> infected_nodes = model.get_activated_nodes()
>>> print(f"Infected {count} nodes: {infected_nodes}")
get_activation_frequency(self: pynetim.cpp.diffusion_model.susceptible_infected_model.SusceptibleInfectedModel) list[int]

Get infection frequency of each node from all simulations.

Returns:

List where index i represents how many times node i was infected. Only valid when record_activation_frequency is set to True.

Return type:

List[int]

Examples

>>> model.set_record_activation_frequency(True)
>>> avg = model.run_monte_carlo_diffusion(1000)
>>> freq = model.get_activation_frequency()
>>> print(f"Node 0 was infected {freq[0]} times")
run_monte_carlo_diffusion(self: pynetim.cpp.diffusion_model.susceptible_infected_model.SusceptibleInfectedModel, rounds: SupportsInt | SupportsIndex, seed: object = None, use_multithread: bool = False, num_threads: SupportsInt | SupportsIndex = 0) float

Run Monte Carlo simulation of SI diffusion. Returns average number of infected nodes over ‘rounds’ trials.

Parameters:
  • rounds (int) – Number of simulation trials

  • seed (int or None, optional) – Random seed for reproducibility. If None (default), uses a truly random seed. Use the same seed to get reproducible results.

  • use_multithread (bool, optional) – Whether to use multithreading (default: False)

  • num_threads (int, optional) – Number of threads to use (0 = auto-detect, default: 0)

Returns:

Average number of infected nodes over all trials

Return type:

float

Examples

>>> avg = model.run_monte_carlo_diffusion(1000)  # Random seed
>>> avg = model.run_monte_carlo_diffusion(1000, seed=42)  # Reproducible result
>>> avg = model.run_monte_carlo_diffusion(1000, seed=42, use_multithread=True, num_threads=4)
run_single_simulation(self: pynetim.cpp.diffusion_model.susceptible_infected_model.SusceptibleInfectedModel, seed: object = None) int

Run a single diffusion simulation and return number of infected nodes.

Parameters:

seed (int or None, optional) – Random seed for reproducibility. If None (default), uses a truly random seed. Use the same seed to get reproducible results.

Returns:

Number of infected nodes in this simulation

Return type:

int

Examples

>>> count = model.run_single_simulation()  # Random result
>>> count = model.run_single_simulation(seed=42)  # Reproducible result
>>> infected_nodes = model.get_activated_nodes()  # Get recorded nodes (if record_activated=True)
set_beta(self: pynetim.cpp.diffusion_model.susceptible_infected_model.SusceptibleInfectedModel, beta: SupportsFloat | SupportsIndex) None

Set infection probability

set_max_steps(self: pynetim.cpp.diffusion_model.susceptible_infected_model.SusceptibleInfectedModel, max_steps: SupportsInt | SupportsIndex) None

Set maximum propagation steps

set_record_activated(self: pynetim.cpp.diffusion_model.susceptible_infected_model.SusceptibleInfectedModel, record: bool) None

Enable or disable recording of activated nodes

set_record_activation_frequency(self: pynetim.cpp.diffusion_model.susceptible_infected_model.SusceptibleInfectedModel, record: bool) None

Enable or disable recording of activation frequency

set_seeds(self: pynetim.cpp.diffusion_model.susceptible_infected_model.SusceptibleInfectedModel, new_seeds: collections.abc.Set[SupportsInt | SupportsIndex]) None

Update seed set

class pynetim.cpp.diffusion_model.SusceptibleInfectedRecoveredModel

Bases: pybind11_object

get_activated_nodes(self: pynetim.cpp.diffusion_model.susceptible_infected_recovered_model.SusceptibleInfectedRecoveredModel) set[int]

Get set of infected + recovered nodes from last simulation.

Returns:

Set of infected + recovered nodes from the last simulation. For single simulation: nodes infected or recovered in that simulation. For Monte Carlo: union of all infected/recovered nodes across all trials. Only valid when record_activated is set to True.

Return type:

Set[int]

Examples

>>> model.set_record_activated(True)
>>> count = model.run_single_simulation()
>>> activated_nodes = model.get_activated_nodes()
>>> print(f"Activated {count} nodes: {activated_nodes}")
get_activation_frequency(self: pynetim.cpp.diffusion_model.susceptible_infected_recovered_model.SusceptibleInfectedRecoveredModel) list[int]

Get activation frequency of each node from all simulations.

Returns:

List where index i represents how many times node i was infected or recovered. Only valid when record_activation_frequency is set to True.

Return type:

List[int]

Examples

>>> model.set_record_activation_frequency(True)
>>> avg = model.run_monte_carlo_diffusion(1000)
>>> freq = model.get_activation_frequency()
>>> print(f"Node 0 was activated {freq[0]} times")
run_monte_carlo_diffusion(self: pynetim.cpp.diffusion_model.susceptible_infected_recovered_model.SusceptibleInfectedRecoveredModel, rounds: SupportsInt | SupportsIndex, seed: object = None, use_multithread: bool = False, num_threads: SupportsInt | SupportsIndex = 0) float

Run Monte Carlo simulation of SIR diffusion. Returns average number of infected + recovered nodes over ‘rounds’ trials.

Parameters:
  • rounds (int) – Number of simulation trials

  • seed (int or None, optional) – Random seed for reproducibility. If None (default), uses a truly random seed. Use the same seed to get reproducible results.

  • use_multithread (bool, optional) – Whether to use multithreading (default: False)

  • num_threads (int, optional) – Number of threads to use (0 = auto-detect, default: 0)

Returns:

Average number of infected + recovered nodes over all trials

Return type:

float

Examples

>>> avg = model.run_monte_carlo_diffusion(1000)  # Random seed
>>> avg = model.run_monte_carlo_diffusion(1000, seed=42)  # Reproducible result
>>> avg = model.run_monte_carlo_diffusion(1000, seed=42, use_multithread=True, num_threads=4)
run_single_simulation(self: pynetim.cpp.diffusion_model.susceptible_infected_recovered_model.SusceptibleInfectedRecoveredModel, seed: object = None) int

Run a single diffusion simulation and return number of infected + recovered nodes.

Parameters:

seed (int or None, optional) – Random seed for reproducibility. If None (default), uses a truly random seed. Use the same seed to get reproducible results.

Returns:

Number of infected + recovered nodes in this simulation

Return type:

int

Examples

>>> count = model.run_single_simulation()  # Random result
>>> count = model.run_single_simulation(seed=42)  # Reproducible result
>>> activated_nodes = model.get_activated_nodes()  # Get recorded nodes (if record_activated=True)
set_beta(self: pynetim.cpp.diffusion_model.susceptible_infected_recovered_model.SusceptibleInfectedRecoveredModel, beta: SupportsFloat | SupportsIndex) None

Set infection probability

set_gamma(self: pynetim.cpp.diffusion_model.susceptible_infected_recovered_model.SusceptibleInfectedRecoveredModel, gamma: SupportsFloat | SupportsIndex) None

Set recovery probability

set_record_activated(self: pynetim.cpp.diffusion_model.susceptible_infected_recovered_model.SusceptibleInfectedRecoveredModel, record: bool) None

Enable or disable recording of activated nodes

set_record_activation_frequency(self: pynetim.cpp.diffusion_model.susceptible_infected_recovered_model.SusceptibleInfectedRecoveredModel, record: bool) None

Enable or disable recording of activation frequency

set_seeds(self: pynetim.cpp.diffusion_model.susceptible_infected_recovered_model.SusceptibleInfectedRecoveredModel, new_seeds: collections.abc.Set[SupportsInt | SupportsIndex]) None

Update seed set