Python 代码:模拟删除物理网络边后逻辑网络正常工作概率
以下是一个示例代码,用于估计在物理网络删除 6 条边之后,断开的路径通过备用路线使逻辑网络能正常工作的概率:
import numpy as np
import pandas as pd
from collections import deque
import heapq
# 读取网络数据
logicalNetwork = pd.read_excel('逻辑网络1.xls', header=None).to_numpy()
physicalNetwork = pd.read_excel('物理网络1.xls', header=None).to_numpy()
# 获取网络的节点数
num_nodes = logicalNetwork.shape[0]
# 随机删除6条物理边
np.random.seed(0)
deleted_edges = np.random.choice(np.argwhere(physicalNetwork != 0).flatten(), size=6, replace=False)
for edge in deleted_edges:
physicalNetwork[np.unravel_index(edge, physicalNetwork.shape)] = 0
# 用于Dijkstra搜索的辅助函数
def dijkstra(source, target, graph):
# 初始化优先队列,格式为(最小负载,当前节点,路径)
queue = [(-graph[source].max(), source, [source])]
# 初始化一个集合存储已经访问过的节点
visited = set([source])
while queue:
min_load, node, path = heapq.heappop(queue)
min_load = -min_load # 因为Python的heapq是最小堆,所以我们存储负载的相反数,使得负载最大的路径优先出队
if node == target:
return [n+1 for n in path] # 返回的路径节点编号要加1,因为我们的节点编号是从0开始的
for next_node, next_load in enumerate(graph[node]):
if next_node not in visited and next_load >= min_load:
heapq.heappush(queue, (-next_load, next_node, path + [next_node]))
visited.add(next_node)
return []
# 用于广度优先搜索的辅助函数
def bfs(source, target):
queue = deque([[source]])
while queue:
path = queue.popleft()
node = path[-1]
if node == target:
return [n+1 for n in path]
for next_node, next_load in enumerate(physicalNetwork[node]):
if next_load > 0 and next_node not in path:
queue.append(path + [next_node])
return []
# 进行蒙特卡罗模拟的次数
num_simulations = 1000
# 统计逻辑网络能正常工作的次数
num_working_networks = 0
# 遍历所有模拟
for _ in range(num_simulations):
# 创建物理网络的副本
physicalNetwork_copy = physicalNetwork.copy()
# 随机删除6条物理边
np.random.seed(_)
deleted_edges = np.random.choice(np.argwhere(physicalNetwork_copy != 0).flatten(), size=6, replace=False)
for edge in deleted_edges:
physicalNetwork_copy[np.unravel_index(edge, physicalNetwork_copy.shape)] = 0
# 判断逻辑网络是否能正常工作
is_working_network = True
for i in range(num_nodes):
for j in range(i+1, num_nodes):
if logicalNetwork[i, j] != 0: # 如果逻辑网络中的节点对是直接连接的
# 使用BFS找到节点数最少的路径
path = bfs(i, j)
# 使用Dijkstra搜索找到备用路径
path2 = dijkstra(i, j, physicalNetwork_copy)
# 如果备用路径为空或者备用路径上的负载不满足需求,逻辑网络无法正常工作
if not path2 or min(physicalNetwork_copy[path2[k]-1, path2[k+1]-1] for k in range(len(path2)-1)) < 10:
is_working_network = False
break
if not is_working_network:
break
# 如果逻辑网络能正常工作,增加计数
if is_working_network:
num_working_networks += 1
# 计算正常工作的概率
working_probability = num_working_networks / num_simulations
print(f'The probability of the logic network working properly after deleting 6 edges is: {working_probability}')
请注意,以上代码使用了蒙特卡罗模拟的方法,通过多次模拟来估计逻辑网络能正常工作的概率。模拟的次数可以根据需要进行调整。代码中的模拟过程会随机删除 6 条物理边,并判断逻辑网络是否能通过备用路径恢复联通并满足需求。
希望以上的示例代码能满足您的需求!如有任何问题,请随时提问。
原文地址: https://www.cveoy.top/t/topic/UK4 著作权归作者所有。请勿转载和采集!