邻接矩阵合并

邻接矩阵合并

文章目录


代码如下

# -*- 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()

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值