📚 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 np18from qiskit import BasicAer, execute19from qiskit.aqua.translators.ising import max_cut20from vqe_playground.utils.colors import WHITE, BLACK21from vqe_playground.utils.fonts import ARIAL_30, ARIAL_3622from vqe_playground.utils.labels import graph_node_labels_reversed_str23from vqe_playground.utils.states import comp_basis_states, NUM_QUBITS, NUM_STATE_DIMS242526class ExpectationGrid(pygame.sprite.Sprite):27"""Displays a grid that contains basis states, eigenvalues, and probabilities"""28def __init__(self, circuit, adj_matrix):29pygame.sprite.Sprite.__init__(self)30self.eigenvalues = None31self.maxcut_shift = 032self.image = None33self.rect = None34self.basis_states = comp_basis_states(NUM_QUBITS)35self.quantum_state = None36self.cur_exp_val = 037self.cur_basis_state_idx = 038self.basis_state_dirty = False3940# When setting circuit this first time,41# don't calculate the expectation value42# or draw the expectation grid, as the43# adjacency matrix hasn't yet been supplied44self.set_circuit(circuit, recalc=False)45self.set_adj_matrix(adj_matrix)4647# def update(self):48# # Nothing yet49# a = 15051def set_circuit(self, circuit, recalc=True):52backend_sv_sim = BasicAer.get_backend('statevector_simulator')53job_sim = execute(circuit, backend_sv_sim)54result_sim = job_sim.result()55self.quantum_state = result_sim.get_statevector(circuit, decimals=3)5657if recalc:58self.calc_expectation_value()59self.draw_expectation_grid()6061def set_adj_matrix(self, adj_matrix):62maxcut_op, self.maxcut_shift = max_cut.get_max_cut_qubitops(adj_matrix)63# print("maxcut_op: ", maxcut_op, ", maxcut_shift: ", maxcut_shift)6465# TODO: Find different approach of calculating and retrieving diagonal66maxcut_op._paulis_to_matrix()67self.eigenvalues = maxcut_op._dia_matrix6869self.calc_expectation_value()70self.draw_expectation_grid()7172def draw_expectation_grid(self):73self.image = pygame.Surface([(NUM_QUBITS + 1) * 50 + 450, 100 + NUM_STATE_DIMS * 50])74self.image.convert()75self.image.fill(WHITE)76self.rect = self.image.get_rect()7778block_size = 2679x_offset = 40080y_offset = 108182# Display expectation value and other relevant values83text_surface = ARIAL_36.render('Weighted average: ' + str(round(self.cur_exp_val, 2)), False, (0, 0, 0))84self.image.blit(text_surface, (0, y_offset + block_size * 13))8586text_surface = ARIAL_36.render('Lowest eigenvalue: ' + str(round(min(self.eigenvalues), 1)), False, (0, 0, 0))87self.image.blit(text_surface, (0, y_offset + block_size * 14))8889maxcut_cost = round(self.cur_exp_val - min(self.eigenvalues), 2)90text_surface = ARIAL_36.render('Maxcut cost: ' + str(maxcut_cost), False, (0, 0, 0))91self.image.blit(text_surface, (0, y_offset + block_size * 15))9293text_surface = ARIAL_36.render('Basis state: ' + str(self.basis_states[self.cur_basis_state_idx]),94False, (0, 0, 0))95self.image.blit(text_surface, (0, y_offset + block_size * 16))9697text_surface = ARIAL_36.render('Maxcut eigenval shift: ' + str(round(self.maxcut_shift, 1)), False, (0, 0, 0))98self.image.blit(text_surface, (0, y_offset + block_size * 17))99100text_surface = ARIAL_36.render('Maxcut weight total: ' + str(round(self.cur_exp_val + self.maxcut_shift, 2)), False, (0, 0, 0))101self.image.blit(text_surface, (0, y_offset + block_size * 18))102103# Display column headings104node_letter_str = graph_node_labels_reversed_str(NUM_QUBITS)105text_surface = ARIAL_30.render(node_letter_str + ' Eigenval Prob', False, (0, 0, 0))106self.image.blit(text_surface, (x_offset, y_offset + block_size / 2))107108for y in range(NUM_STATE_DIMS):109text_surface = ARIAL_36.render(self.basis_states[y] + ": " + str(round(self.eigenvalues[y], 1)),110False, (0, 0, 0))111self.image.blit(text_surface, (x_offset, (y + 2) * block_size + y_offset))112113prop_square_side = abs(self.quantum_state[y]) * block_size114rect = pygame.Rect(x_offset + 40 - (prop_square_side / 2) + NUM_QUBITS * 30,115(y + 1) * block_size + 35 + ((block_size - prop_square_side) / 2),116prop_square_side,117prop_square_side)118if abs(self.quantum_state[y]) > 0:119pygame.draw.rect(self.image, BLACK, rect, 2)120121def calc_expectation_value(self):122statevector_probs = np.absolute(self.quantum_state) ** 2123exp_val = np.sum(self.eigenvalues * statevector_probs)124self.cur_exp_val = exp_val125126basis_state_idx = np.argmax(statevector_probs)127128if basis_state_idx != self.cur_basis_state_idx:129self.basis_state_dirty = True130self.cur_basis_state_idx = basis_state_idx131132# print ("in calc_expectation_value, exp_val: ", exp_val, ", basis state: ", self.basis_states[basis_state_idx])133return exp_val, self.basis_states[basis_state_idx]134135136137