邻接矩阵合并
文章目录
代码如下
# -*- coding: utf-8 -*-
"""
Created on Thu May 13 19:52:11 2021
@author: Administrator
"""
import networkx as nx
#改变邻接矩阵的形式
def change_matrix(G):
s = str(nx.to_numpy_matrix(G))
ss = s.replace(".",",")
sss = ss.replace(",]","],")
result = sss.replace("],]","]]")
return result
#用来将两个层内网络和一个
#层间网络合并成一个大的网络
def merge():
# 用来存储整个网络的邻接矩阵
file = open("all.txt",'w')
G = nx.DiGraph()
filestr = ""
#这里为层间网络
with open("c.txt") as files:
for line in files:
filestr += line.strip()
#将字符串转换成列表
matrix = eval(filestr)
nodes = range(len(matrix))
G.add_nodes_from(nodes * 2)
length = len(matrix)
for i in range(length):
for j in range(length):
if(matrix[i][j] == 1):
t = j + length
G.add_edge(i, t)
G.add_edge(t, i)
s = ""
#第一层层内
with open("one.txt") as files:
for line in files:
s += line.strip()
matrix1 = eval(s)
for i in range(length):
for j in range(length):
if(matrix1[i][j] == 1):
G.add_edge(i, j)
ss = ""
#第二层层内
with open("two.txt") as files:
for line in files:
ss += line.strip()
matrix2 = eval(ss)
for i in range(length):
for j in range(length):
if(matrix2[i][j] == 1):
G.add_edge(i + length, j + length)
print("--------网络节点如下--------")
print(G.nodes())
print("--------网络的边如下--------")
print(G.edges())
#用来构建整个网络
print("整个网络的邻接矩阵为:")
print(nx.to_numpy_matrix(G))
result = change_matrix(G)
file.write(str(result).strip())
merge()