import networkx as nx
import matplotlib.pyplot as plt
import xlrd
import numpy as np
class Graph_Matrix:
"""
Adjacency Matrix
"""
def __init__(self, vertices=[], matrix=[]):
"""
:param vertices:a dict with vertex id and index of matrix , such as {vertex:index}
:param matrix: a matrix
"""
self.matrix = matrix
self.edges_dict = {} # {(tail, head):weight}
self.edges_array = [] # (tail, head, weight)
self.vertices = vertices
self.num_edges = 0
# if provide adjacency matrix then create the edges list
if len(matrix) > 0:
if len(vertices) != len(matrix):
raise IndexError
self.edges = self.getAllEdges()
self.num_edges = len(self.edges)
# if do not provide a adjacency matrix, but provide the vertices list, build a matrix with 0
elif len(vertices) > 0:
self.matrix = [[0 for col in range(len(vertices))] for row in range(len(vertices))]
self.num_vertices = len(self.matrix)
def isOutRange(self, x):
try:
if x >= self.num_vertices or x <= 0:
raise IndexError
except IndexError:
print("节点下标出界")
def isEmpty(self):
if self.num_vertices == 0:
self.num_vertices = len(self.matrix)
return self.num_vertices == 0
def add_vertex(self, key):
if key not in self.vertices:
self.vertices[key] = len(self.vertices) + 1
# add a vertex mean add a row and a column
# add a column for every row
for i in range(self.getVerticesNumbers()):
self.matrix[i].append(0)
self.num_vertices += 1
nRow = [0] * self.num_vertices
self.matrix.append(nRow)
def getVertex(self, key):
pass
def add_edges_from_list(self, edges_list): # edges_list : [(tail, head, weight),()]
for i in range(len(edges_list)):
self.add_edge(edges_list[i][0], edges_list[i][1], edges_list[i][2], )
def add_edge(self, tail, head, cost=0):
# if self.vertices.index(tail) >= 0:
# self.addVertex(tail)
if tail not in self.vertices:
self.add_vertex(tail)
# if self.vertices.index(head) >= 0:
# self.addVertex(head)
if head not in self.vertices:
self.add_vertex(head)
# for directory matrix
self.matrix[self.vertices.index(tail)][self.vertices.index(head)] = cost
# for non-directory matrix
# self.matrix[self.vertices.index(fromV)][self.vertices.index(toV)] = \
# self.matrix[self.vertices.index(toV)][self.vertices.index(fromV)] = cost
self.edges_dict[(tail, head)] = cost
self.edges_array.append((tail, head, cost))
self.num_edges = len(self.edges_dict)
def getEdges(self, V):
pass
def getVerticesNumbers(self):
if self.num_vertices == 0:
self.num_vertices = len(self.matrix)
return self.num_vertices
def getAllVertices(self):
return self.vertices
def getAllEdges(self):
for i in range(len(self.matrix)):
for j in range(len(self.matrix)):
if 0 < self.matrix[i][j] < float('inf'):
self.edges_dict[self.vertices[i], self.vertices[j]] = self.matrix[i][j]
self.edges_array.append([self.vertices[i], self.vertices[j], self.matrix[i][j]])
return self.edges_array
def __repr__(self):
return str(''.join(str(i) for i in self.matrix))
def to_do_vertex(self, i):
print('vertex: %s' % (self.vertices[i]))
def to_do_edge(self, w, k):
print('edge tail: %s, edge head: %s, weight: %s' % (self.vertices[w], self.vertices[k], str(self.matrix[w][k])))
def create_undirected_matrix(my_graph,matrix):
#nodes = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
nodes = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10',
'11', '12', '13', '14', '15', '16', '17', '18', '19', '20',
'21', '22', '23', '24', '25', '26', '27', '28', '29', '30',
'31', '32', '33', '34', '35', '36', '37', '38', '39', '40',
'41', '42', '43', '44', '45', '46', '47', '48', '49', '50',
'51', '52', '53', '54', '55', '56', '57', '58', '59', '60',
'61', '62', '63', '64', '65', '66', '67', '68', '69', '70',
'71', '72', '73', '74', '75', '76', '77', '78', '79', '80',
]
#matrix = [[0, 1, 1, 1, 1, 1, 0, 0], # a
# [0, 0, 1, 0, 1, 0, 0, 0], # b
# [0, 0, 0, 1, 0, 0, 0, 0], # c
# [0, 0, 0, 0, 1, 0, 0, 0], # d
# [0, 0, 0, 0, 0, 1, 0, 0], # e
# [0, 0, 1, 0, 0, 0, 1, 1], # f
# [0, 0, 0, 0, 0, 1, 0, 1], # g
# [0, 0, 0, 0, 0, 1, 1, 0]] # h
my_graph = Graph_Matrix(nodes, matrix)
print(my_graph)
return my_graph
def matrix(path):#读取excel表格里的数据
table = xlrd.open_workbook(path).sheets()[6] # 获取第6个sheet表
row = table.nrows # 行数
col = table.ncols # 列数
datamatrix = np.zeros((row, col)) # 生成一个nrows行ncols列,且元素均为0的初始矩阵
for x in range(col):
try:
cols = np.matrix(table.col_values(x)) # 把list转换为矩阵进行矩阵操作
datamatrix[:, x] = cols # 按列把数据存进矩阵中
except:
print(x)
print(datamatrix.shape)
return datamatrix
def create_directed_matrix(my_graph):#二维数组生成有向图
nodes = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
inf = float('inf')
matrix = [[0, 2, 1, 3, 9, 4, inf, inf], # a
[inf, 0, 4, inf, 3, inf, inf, inf], # b
[inf, inf, 0, 8, inf, inf, inf, inf], # c
[inf, inf, inf, 0, 7, inf, inf, inf], # d
[inf, inf, inf, inf, 0, 5, inf, inf], # e
[inf, inf, 2, inf, inf, 0, 2, 2], # f
[inf, inf, inf, inf, inf, 1, 0, 6], # g
[inf, inf, inf, inf, inf, 9, 8, 0]] # h
my_graph = Graph_Matrix(nodes, matrix)
print(my_graph)
return my_graph
def create_directed_graph_from_edges(my_graph):#用边生成有向图
nodes = ['A', 'B', 'C', 'D', 'E', 'F', 'G']
edge_list = [('A', 'F', 9), ('A', 'B', 10), ('A', 'G', 15), ('B', 'F', 2),
('G', 'F', 3), ('G', 'E', 12), ('G', 'C', 10), ('C', 'E', 1),
('E', 'D', 7)]
my_graph = Graph_Matrix(nodes)
my_graph.add_edges_from_list(edge_list)
print(my_graph)
return my_graph
def draw_undircted_graph(my_graph):#显示无向图
G = nx.Graph() # 建立一个空的无向图G
for node in my_graph.vertices:
G.add_node(str(node))
for edge in my_graph.edges:
G.add_edge(str(edge[0]), str(edge[1]))
print("nodes:", G.nodes()) # 输出全部的节点: [1, 2, 3]
print("edges:", G.edges()) # 输出全部的边:[(2, 3)]
print("number of edges:", G.number_of_edges()) # 输出边的数量:1
nx.draw(G, node_color = 'b',edge_color = 'r',with_labels=True)
plt.savefig("undirected_graph.png")
plt.show()
def draw_directed_graph(my_graph):#显示有向图,带权
G = nx.DiGraph() # 建立一个空的无向图G
for node in my_graph.vertices:
G.add_node(str(node))
G.add_weighted_edges_from(my_graph.edges_array)
print("nodes:", G.nodes()) # 输出全部的节点
print("edges:", G.edges()) # 输出全部的边
print("number of edges:", G.number_of_edges()) # 输出边的数量
nx.draw(
大不怪将军
- 粉丝: 6297
- 资源: 31
最新资源
- Chart.js 的 Vue.js 包装器.zip
- BootstrapVue 为 Vue.js 提供了最全面的 Bootstrap v4 实现之一 具有广泛且自动化的 WAI-ARIA 可访问性标记 .zip
- Babel , Vue JSX 相关软件包的 monorepo.zip
- Java多线程基础学习指南:原理、实现与实战
- 西电微机原理实验:实验内容、步骤与实践指导 - 计算机科学与技术专业的教学辅助材料
- adminLTE 到 vuejs v2.x 转换项目.zip
- unity场景设置,unity入门编程
- Visual Basic 注册表类模块源码
- Android游戏开发之旅中文最新版本
- Androidmakefile编译系统Android.mk文件语法规范中文最新版本
资源上传下载、课程学习等过程中有任何疑问或建议,欢迎提出宝贵意见哦~我们会及时处理!
点击此处反馈