一、IC模型(独立级联模型)
红色为处于激活态的种子节点,每条边都有一个传播概率p,激活的节点会以p的概率去激活邻居节点,一个节点有且只有一次机会去激活另一个节点,如果失败,则不再去尝试激活这个节点。
def preprocess(G):
p = 0
directedGraph = nx.DiGraph()
for u in G.nodes():
for v in G.neighbors(u):
if (v != u):
#propProb = G.number_of_edges(u, v) / G.in_degree(v)
propProb = G.number_of_edges(u, v) / G.degree(v)
directedGraph.add_edge(u, v, pp=propProb)
#p += propProb
#print(propProb)
#print('平均阈值:', p/2939)
return directedGraph
def simulate(G, seedNode, propProbability):
newActive = True
currentActiveNodes = copy.deepcopy(seedNode)
newActiveNodes = set()
activatedNodes = copy.deepcopy(seedNode) # Biar ga keaktivasi 2 kali
influenceSpread = len(seedNode)
while (newActive):
for node in currentActiveNodes:
for neighbor in G.neighbors(node): # Harus dicek udah aktif apa belom, jangan sampe ngaktifin yang udah aktif
if (neighbor not in activatedNodes):
if (G[node][neighbor]['pp']>propProbability): #flipCoin(propProbability)
newActiveNodes.add(neighbor)
activatedNodes.append(neighbor)
influenceSpread += len(newActiveNodes)
if newActiveNodes:
currentActiveNodes = list(newActiveNodes)
newActiveNodes = set()
else:
newActive = False
# print("activatedNodes",len(activatedNodes),activatedNodes)
return influenceSpread
def flipCoin(probability):
return random.random() < probability
二、LT模型(线性阈值模型)
红色节点为处于激活状态的节点,每个节点会有一个激活阈值,如果该节点的处于激活态的邻居节点的激活概率相加大于这个节点的激活阈值,则该节点被激活,每个节点会有多次机会被激活。
def weight(G, u, v):
if G.has_edge(u, v):
return G[u][v]['weight']
else:
return 0
# LT传播模型
def simulate(G, seedNode,threshold_active):
# Set Random threshold for every node ~ [0,1]
# nodeThresholds = {}
# for node in G.nodes():
# nodeThresholds[node] = random.uniform(0, 1)
# Set predefined threshold for every node ~ threshold_active [0,1]
nodeThresholds = {}
for node in G.nodes():
nodeThresholds[node] = threshold_active
nodeValues = {}
for node in G.nodes():
nodeValues[node] = 0
newActive = True
currentActiveNodes = copy.deepcopy(seedNode)
newActiveNodes = set()
activatedNodes = copy.deepcopy(seedNode) # Prevent from activating node twice
influenceSpread = len(seedNode)
while (newActive):
for node in currentActiveNodes:
for neighbor in G.neighbors(node):
if (neighbor not in activatedNodes):
nodeValues[neighbor] += weight(G, node, neighbor)
if (nodeValues[neighbor] >= nodeThresholds[neighbor]):
newActiveNodes.add(neighbor)
activatedNodes.append(neighbor)
influenceSpread += len(newActiveNodes)
if newActiveNodes:
currentActiveNodes = list(newActiveNodes)
newActiveNodes = set()
else:
newActive = False
return influenceSpread