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 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193
| import networkx as nx import matplotlib.pyplot as plt
class Graph_Matrix: """ 邻接矩阵 (Adjacency Matrix) """ def __init__(self, vertices=[], matrix=[]): """ :param vertices: 带有顶点id和矩阵索引的字典,如 {vertex:index}. :param matrix: 一个矩阵 """ self.matrix = matrix self.edges_dict = {} self.edges_array = [] self.vertices = vertices self.num_edges = 0 if len(matrix) > 0: if len(vertices) != len(matrix): raise IndexError self.edges = self.getAllEdges() self.num_edges = len(self.edges) 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 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): 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 tail not in self.vertices: self.add_vertex(tail) if head not in self.vertices: self.add_vertex(head) self.matrix[self.vertices.index(tail)][self.vertices.index(head)] = 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, nodes, matrix): nodes,matrix = nodes,matrix return Graph_Matrix(nodes, matrix)
def draw_undircted_graph(my_graph): G = nx.Graph() 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("节点:", G.nodes()) print("边:", G.edges()) print("边数:", G.number_of_edges()) nx.draw(G, with_labels=True) plt.savefig("undirected_graph.png") plt.show()
if __name__ == '__main__': my_graph = Graph_Matrix() nodes = [0, 1, 2, 3, 4, 5, 6, 7] matrix = [[0, 1, 1, 1, 0, 0, 0, 0], [1, 0, 0, 0, 1, 0, 1, 0], [1, 0, 0, 1, 0, 0, 0, 0], [1, 0, 1, 0, 1, 0, 0, 0], [0, 1, 0, 1, 0, 1, 1, 0], [0, 0, 0, 0, 1, 0, 0, 1], [0, 1, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0]] created_graph = create_undirected_matrix(my_graph, nodes, matrix) draw_undircted_graph(created_graph)
def create_directed_matrix(my_graph, nodes, matrix): nodes,matrix = nodes,matrix return Graph_Matrix(nodes, matrix)
def draw_directed_graph(my_graph): G = nx.DiGraph() 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()) labels = nx.get_edge_attributes(G, "weight") print(type(labels)) print(labels) for key, values in labels.items(): weight = {} weight[list(key)[0] + "-" + list(key)[1]] = values labels[key] = weight plt.figure(3, figsize=(12, 12)) pos = nx.circular_layout(G) nx.draw_networkx_nodes(G, pos=nx.circular_layout(G), nodelist=G.nodes, alpha=0.4, node_color='red', node_shape='v', node_size=220) nx.draw_networkx_labels(G, pos=nx.circular_layout(G), font_color='k', alpha=1) nx.draw_networkx_edge_labels(G, pos=nx.circular_layout(G), edge_labels=labels, label_pos=0.3, font_size=7) nx.draw(G, with_labels=True, pos=nx.circular_layout(G), node_size=1500, alpha=0.3, font_weight="bold", arrows=True, connectionstyle='arc3, rad = 0.1') plt.savefig("directed_graph3.png") plt.show()
if __name__ == '__main__': my_graph = Graph_Matrix() nodes = ['0', '1', '2', '3'] inf = float('inf') matrix = [[0, inf, inf, inf], [3, 0, inf, 2], [inf, 6, 0, inf], [4, 2, inf, 0]] created_graph = create_directed_matrix(my_graph, nodes, matrix) draw_directed_graph(created_graph)
|
评论区
欢迎你留下宝贵的意见,昵称输入QQ号会显示QQ头像哦~