📚 The CoCalc Library - books, templates and other resources
License: OTHER
#!/usr/bin/env python1#2# Copyright 2019 the original author or authors.3#4# Licensed under the Apache License, Version 2.0 (the "License");5# you may not use this file except in compliance with the License.6# You may obtain a copy of the License at7#8# http://www.apache.org/licenses/LICENSE-2.09#10# Unless required by applicable law or agreed to in writing, software11# distributed under the License is distributed on an "AS IS" BASIS,12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.13# See the License for the specific language governing permissions and14# limitations under the License.15#16import pygame17import numpy as np18import matplotlib.pyplot as plt19import networkx as nx20from cmath import isclose21import io2223from vqe_playground.utils.resources import load_mem_image24from vqe_playground.utils.labels import comp_graph_node_labels252627class NetworkGraph(pygame.sprite.Sprite):28"""Displays a network graph"""29def __init__(self, adj_matrix):30pygame.sprite.Sprite.__init__(self)31self.image = None32self.rect = None33self.adj_matrix = None34self.solution = None35self.graph = nx.Graph()36self.graph_pos = None37self.num_nodes = adj_matrix.shape[0] # Number of nodes in graph38self.set_adj_matrix(adj_matrix)3940def update(self):41self.draw_network_graph(self.calc_node_colors())4243def set_adj_matrix(self, adj_matrix):44self.graph = nx.Graph()45self.adj_matrix = adj_matrix46self.solution = np.zeros(self.num_nodes)4748fig = plt.figure(figsize=(7, 5))4950self.graph.add_nodes_from(np.arange(0, self.num_nodes, 1))5152# tuple is (i,j,weight) where (i,j) is the edge53edge_list = []54for i in range(self.num_nodes):55for j in range(i + 1, self.num_nodes):56if not isclose(adj_matrix[i, j], 0.0):57edge_list.append((i, j, adj_matrix[i, j]))5859self.graph.add_weighted_edges_from(edge_list)6061self.graph_pos = nx.spring_layout(self.graph)62self.draw_network_graph(self.calc_node_colors())6364def set_solution(self, solution):65self.solution = solution6667self.draw_network_graph(self.calc_node_colors())6869def draw_network_graph(self, colors):70edge_labels = dict([((u, v,), self.adj_matrix[u, v]) for u, v, d in self.graph.edges(data=True)])71nx.draw_networkx_edge_labels(self.graph, self.graph_pos, edge_labels=edge_labels)7273labels = comp_graph_node_labels(self.num_nodes)74nx.draw_networkx_labels(self.graph, self.graph_pos, labels, font_size=16, font_color='white')7576nx.draw_networkx(self.graph, self.graph_pos, with_labels=False, node_color=colors, node_size=600, alpha=.8, font_color='white')77plt.axis('off')78buf = io.BytesIO()79plt.savefig(buf, format="png")8081self.image, self.rect = load_mem_image(buf, -1)82self.image.convert()8384def calc_node_colors(self):85return ['r' if self.solution[self.num_nodes - i - 1] == 0 else 'b' for i in range(self.num_nodes)]86878889