repo
stringclasses 900
values | file
stringclasses 754
values | content
stringlengths 4
215k
|
|---|---|---|
https://github.com/Shashankaubaru/NISQ-TDA
|
Shashankaubaru
|
# from qiskit.circuit import Parameter
#For state vector initializing
# from qiskit.aqua.components.initial_states.custom import Custom
# from qiskit.quantum_info import Pauli
# from qiskit.aqua.operators import MatrixOperator, WeightedPauliOperator, op_converter
# from qiskit.aqua.utils import decimal_to_binary, CircuitFactory, get_subsystem_density_matrix
# from qiskit.aqua.algorithms import ExactEigensolver
# from qiskit.aqua.components.iqfts import Standard as StandardIQFTS
# from qiskit.aqua.algorithms import QPE
# from qiskit.aqua.operators.op_converter import to_matrix_operator
# from qiskit.aqua.circuits import FourierTransformCircuits as Fourier_circ
# from qiskit.circuit.quantumregister import Qubit
# #from qiskit.circuit import Instruction
# from qiskit.extensions.quantum_initializer.initializer import Initialize
# #For running
# from qiskit import BasicAer
# from qiskit.aqua import QuantumInstance
# from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute
# from qiskit.aqua.utils import summarize_circuits
# iqft = QFT(num_ancillae).inverse()
# my_phase_estimation_circuit = PhaseEstimationCircuit(iqft=iqft, num_ancillae=num_ancillae, unitary_circuit_factory=test_boundary_factory)
# mycirc += my_phase_estimation_circuit.construct_circuit(ancillary_register=myancillae)
# # mycirc.measure(myancillae, c_ancilla)
# simulator = 'qasm_simulator'
# # simulator = 'statevector_simulator'
# backend = BasicAer.get_backend(simulator)
# result = execute(mycirc, backend=backend).result()
# ancilla_counts = result.get_counts(mycirc)
# post_select_ancilla_counts = get_subsystems_counts(ancilla_counts,post_select_index=1,post_select_flag='0'*test_boundary_factory._num_projection_bits)
# top_measurement_label = \
# sorted([(post_select_ancilla_counts[k], k) for k in post_select_ancilla_counts])[::-1][0][-1][::-1]
# _binary_fractions = [1 / 2 ** p for p in range(1, num_ancillae + 1)]
# top_measurement_decimal = sum(
# [t[0] * t[1] for t in zip(_binary_fractions,
# [int(n) for n in top_measurement_label])]
# )
# print(top_measurement_label)
# print(top_measurement_decimal)
# mycirc.count_ops()
# summarize_circuits(mycirc)
# summarize_circuits(mycirc.decompose())
#mycirc.draw()
# ########################################
# ### CALCULATE THE NUMBER OF SIMPLICES
# ########################################
# #The quantum circuit to arrive at num_complex_simplices e.g = [3,3,0]
# #This can possibly be dequantized! Ken!? -> Yes, according to Ken
# num_complex_simplices = np.zeros(num_qubits)
# num_complex_simplices[0] = num_qubits
# mycirc = QuantumCircuit(mycomplex, mycounter)
# #create_unfilled_triangle_circ(mycirc, mycomplex)
# mycirc.initialize(state_vector, mycomplex)
# split_k(mycirc, mycomplex, mycounter)
# simulator = 'statevector_simulator'
# backend = BasicAer.get_backend(simulator)
# result = execute(mycirc, backend=backend).result()
# mystate=result.get_statevector(mycirc).reshape(num_basis, num_counts, order='F')
# projected_state = mystate[:, 1]
# total_num_simplices = num_qubits/norm(projected_state)**2
# for k in range(1, num_qubits):
# projected_state = mystate[:, k+1]
# print(projected_state)
# num_complex_simplices[k] = (norm(projected_state)**2)*total_num_simplices
# print("Number of complex simplices of each degree:")
# print(num_complex_simplices)
# ########################################
# mycirc.count_ops()
# summarize_circuits(mycirc.decompose())
# mycirc.draw()
########################################
### Construct Vitoris Vector
########################################
# vit_vec = construct_unfilled_triangle()
# vit_vec = construct_unfilled_square()
# vit_vec_no_signs = np.abs(vit_vec)
# num_qubits = num_underlying_vertices_vector_length(len(vit_vec_no_signs))
# num_basis = 1 << num_qubits
# state_vector = 1/norm(vit_vec_no_signs)*vit_vec_no_signs
# print("State Vector: ", state_vector)
# print("Num qubits: ", num_qubits)
# mycomplex = QuantumRegister(num_qubits)
# #mycirc = QuantumCircuit(mycomplex, mycounter)
# mycirc = QuantumCircuit(mycomplex)
# mycirc.initialize(state_vector, mycomplex)
# simulator = 'statevector_simulator'
# backend = BasicAer.get_backend(simulator)
# result = execute(mycirc, backend=backend).result()
# backend = BasicAer.get_backend(simulator)
# result = execute(mycirc, backend=backend).result()
# mystate=result.get_statevector(mycirc).reshape(num_basis, 1, order='F')
# print_matrix(mystate)
# b = transpile(circuit, basis_gates=['u1', 'u2', 'u3', 'cx'], optimization_level=3)
#full_circ.isometry(state_vector, None, simplicial_complex_register)
# temp_reg = QuantumRegister(boundary_evolution_instruction.num_qubits)
# temp_circ = QuantumCircuit(temp_reg)
# temp_circ.append(boundary_evolution_instruction, qargs=temp_reg)
# boundary_evolution_unitary = execute(temp_circ, backend=UnitarySimulatorPy()).result().get_unitary()
# num_ancillae = 5
# exact_eigensolver = NumPyMinimumEigensolver(PrimitiveOp(boundary_evolution_unitary))
# results = exact_eigensolver.run()
# ref_eigenval = results.eigenvalue
# ref_eigenvec = results.eigenstate
# ws, vs = np.linalg.eig(boundary_sum_matrix)
# ref_eigenval = ws[0]
# ref_eigenvec = vs[0]
# print('The exact eigenvalue is: %s', ref_eigenval)
# print('The corresponding eigenvector: %s', ref_eigenvec)
# #qubit_op = boundary_evolution_operator
# qubit_op = boundary_sum
# state_in = Custom(qubit_op.num_qubits, state_vector=ref_eigenvec)
# iqft = QFT(num_ancillae).inverse()
# qpe = QPE(qubit_op, state_in, iqft, num_time_slices=1, num_ancillae=num_ancillae,
# expansion_mode='suzuki', expansion_order=2,
# shallow_circuit_concat=True)
# backend = BasicAer.get_backend(simulator)
# quantum_instance = QuantumInstance(backend, shots=1000, seed_transpiler=1, seed_simulator=1)
# # run qpe
# result = qpe.run(quantum_instance)
# # report result
# print('top result str label: %s', result.top_measurement_label)
# print('top result in decimal: %s', result.top_measurement_decimal)
# print('stretch: %s', result.stretch)
# print('translation: %s', result.translation)
# print('final eigenvalue from QPE: %s', result.eigenvalue)
# print('reference eigenvalue: %s', ref_eigenval)
# print('ref eigenvalue (transformed): %s',
# (ref_eigenval + result.translation) * result.stretch)
# print('reference binary str label: %s', decimal_to_binary(
# (ref_eigenval.real + result.translation) * result.stretch,
# max_num_digits=num_ancillae + 3,
# fractional_part_only=True
# ))
###################
#IF WE COULD CONSTRUCT EQUAL SUP OVER EIGENVECTORS, FOR EG WITH VQE MAXIMISING EXPECTATION, ALTERNATIVELY, WE HAVE THE COMPLEX, WHICH IS CLOSE TO EQUAL SUP, THIS COULD BE A GOOD LOWER BOUND!
###################
#OLD PROJECTION EXPERIMENTS
########################################
### CREATE UNFILLED TRIANGLE
########################################
# def create_unfilled_triangle_circ(circ, qreg):
# #create full simplicial complex of unfilled triangle on first three qubits
# circ.h(qreg[2])
# circ.ry(1.91063323624902, qreg[1])
# circ.ry(3*np.pi/4, qreg[0])
# circ.cx(qreg[1], qreg[0])
# circ.ry(np.pi/4, qreg[0])
# circ.cx(qreg[1], qreg[0])
# circ.cx(qreg[2], qreg[0])
# circ.cx(qreg[2], qreg[1])
# return circ
########################################
### PROJECTION ONTO COMPLEX
########################################
# def project_onto_triangle(circ, from_qreg, project_qreg):
# # copy into project register (creating entangled copy)
# circ.cx(from_qreg, project_qreg)
# #create full simplicial complex of unfilled triangle on temp circuit
# circ_complex = QuantumCircuit(project_qreg)
# create_unfilled_triangle_circ(circ_complex, project_qreg)
# #add reverse of circuit to project onto complex
# circ += circ_complex.inverse()
# def project_onto_complex(complex_vector, circ, from_qreg, project_qreg):
# # copy into project register (creating entangled copy)
# circ.cx(from_qreg, project_qreg)
# #create full simplicial complex of unfilled triangle on temp circuit
# # circ_complex = QuantumCircuit(project_qreg)
# # circ_complex.initialize(complex_vector, project_qreg)
# myinit = Initialize(complex_vector)
# # add reverse of circuit to project onto complex
# # circ.data.append(circ_complex.data[0][0].gates_to_uncompute())
# circ.append(myinit.gates_to_uncompute().to_instruction(), project_qreg)
# # circ += circ_complex.inverse()
# #Alternative:
# #Collapse only if boundary simplex was in original complex
# #This is more complicated, below detects 0-1 errors
# #still need 1-0 zero errors and then maybe X and AND and then collapse?
# #circ.ccx(from_qreg, project_qreg, myproject)
# #Haha, this then reminded Lior about QEEC, so next try to use QEEC for projection, does not work
# #KEY PROBLEM IS TENSOR OF SUPERPOSITION ALWAYS CREATES ALL POSSIBILITIES
# #same for product of coefficients, Almudena et.al!
# simplex_qreg = QuantumRegister(num_qubits)
# pairs_qreg = QuantumRegister(num_pairs)
# simplex_in = QuantumRegister(num_pairs)
|
https://github.com/Shashankaubaru/NISQ-TDA
|
Shashankaubaru
|
import numpy as np
import pdb
from pdb import set_trace as bp
# Import Qiskit
from qiskit import QuantumCircuit, QuantumRegister
from qiskit import Aer, transpile
from qiskit.tools.visualization import plot_histogram, plot_state_city
import qiskit.quantum_info as qi
from qiskit.providers.aer import AerError
# Create circuit
myreg = QuantumRegister(16)
circ = QuantumCircuit(myreg)
circ.h(myreg)
circ.cx(0, 1)
circ.measure_all()
# Initialize a GPU backend
# Note that the cloud instance for tutorials does not have a GPU
# so this will raise an exception.
try:
print(Aer.backends())
simulator_gpu = Aer.get_backend('aer_simulator_statevector_gpu')
# simulator_gpu.set_options(device='GPU')
# bp()
circ = transpile(circ, simulator_gpu)
# Run and get counts
result = simulator_gpu.run(circ).result()
counts = result.get_counts(circ)
print(len(counts))
except AerError as e:
print(e)
|
https://github.com/Shashankaubaru/NISQ-TDA
|
Shashankaubaru
|
# noqa: E501,E402,E401,E128
# flake8 disable errors
# -*- coding: utf-8 -*-
# Copyright 2018 IBM.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# =============================================================================
# import warnings
# warnings.filterwarnings("ignore", category=DeprecationWarning)
# For Homology
from classical_homology import \
construct_unfilled_triangle, \
construct_unfilled_square, \
complete_unsigned_complex, \
one_skeleton_triangle, \
one_skeleton_square, \
one_skeleton_pyramid, \
one_skeleton_random, \
one_skeleton_fully_connected, \
one_skeleton_tetrahedron, \
one_skeleton_square_with_diagonal, \
one_skeleton_unfilled_cube, \
one_skeleton_n_disconnected_squares
from homology_tools import d_dim_simplices_mask, num_underlying_vertices_vector_length, num_underlying_vertices_simplices, print_signs_simplicial_vector_parts, reshape_vector_to_matrix_and_index, simplices_to_count_vector, count_vector_to_simplices
from math_fiddling import binarize, print_matrix, format_basic, format_complex, print_matrix_and_info, format_real, countBits, num_bits, integer_to_binary_as_string, pair_index_to_two_power_2s, two_power_2s_to_pair_index, num_qubits_from_num_pairs, is_power_of_2, first_non_zero_bit, bin_string2int
#For General Computing
import itertools
import numpy as np
from numpy.linalg import norm as norm
import time
import secrets
#from scipy.spatial.KDTree import query_pairs as find_pairs
from scipy.special import rel_entr, entr
import json
import copy
#For Qiskit use
from qiskit.quantum_info import Pauli
from qiskit.aqua.operators import PrimitiveOp, MatrixOp
from qiskit import BasicAer, Aer
import qiskit.providers.aer.noise as qnoise
from qiskit.providers.aer import AerSimulator
from qiskit.test.mock import fake_pulse_backend
from qiskit.aqua import QuantumInstance
from qiskit.aqua.utils import decimal_to_binary
from qiskit.aqua.algorithms import NumPyMinimumEigensolver
from qiskit.aqua.algorithms import QPE
from qiskit.circuit.library import QFT
from qiskit.aqua.components.initial_states import Custom
#from qiskit.aqua.operators.legacy import MatrixOperator, WeightedPauliOperator
#from qiskit.aqua.operators.legacy import op_converter
from qiskit import AncillaRegister, QuantumRegister, ClassicalRegister, QuantumCircuit, execute
from qiskit.aqua.utils import summarize_circuits
from qiskit.circuit.quantumregister import Qubit
# from qiskit.aqua.circuits import FourierTransformCircuits as Fourier_circ
# from qiskit.circuit.library import QFT
# from qiskit.circuit import Parameter
# from qiskit.aqua.operators import PauliTrotterEvolution, Suzuki
from qiskit.extensions.quantum_initializer.initializer import Initialize
from qiskit.providers.basicaer import UnitarySimulatorPy
from qiskit.aqua import AquaError
from qiskit.aqua.utils import CircuitFactory
from qiskit.aqua.utils.controlled_circuit import get_controlled_circuit
from qiskit.aqua.circuits import PhaseEstimationCircuit
from qiskit.aqua.utils.subsystem import get_subsystems_counts
from qiskit.circuit.library import TwoLocal
from qiskit.compiler import transpile, assemble
from qiskit.transpiler import PassManager
from qiskit.transpiler.passes import Unroller
from qiskit import IBMQ
from qiskit.providers.ibmq import least_busy
from qiskit.providers.jobstatus import JobStatus
from qiskit.providers.ibmq.managed import IBMQJobManager
from datetime import datetime, timedelta
from dateutil import tz
# from qiskit_ionq import IonQProvider
from qiskit.providers.honeywell import Honeywell
# from qiskit.providers.basicaer import BasicAerJob
import matplotlib.pyplot as plot
from qiskit.visualization import plot_histogram
import glob
# import pdb
# from pdb import set_trace as bp
EPS = 1e-16
JOB_RETRIEVE_LIMIT = 300
JOB_PREVIOUS_DAYS = 20
#######################################################################
############################################
### HARDWARE HELPER FUNCTIONS
############################################
def get_post_select_counts(complete_system_counts, post_select_indices_set=None,
post_select_flags_set=None):
if len(post_select_indices_set)!=len(post_select_flags_set):
raise ValueError("indices list not same length as flags list.")
mixed_measurements = list(complete_system_counts)
num_registers = len(mixed_measurements[0].split())
count_dicts = [{} for _ in range(len(post_select_flags_set))]
post_selections = [(i,j,k) for i, (j,k) in enumerate(zip(post_select_indices_set,
post_select_flags_set))]
for mixed_measurement in mixed_measurements:
split_measurement = np.array(mixed_measurement.split()[::-1], dtype=str) #-1 reverses so registers are correct, strings themselves remain in qiskit ordering
for i, post_select_indices, post_select_flags in post_selections:
if np.all(split_measurement[post_select_indices] == post_select_flags):
other_indices = list(range(num_registers))
list(map(other_indices.remove, post_select_indices))
if other_indices:
count_dicts[i][" ".join(split_measurement[other_indices])] = \
complete_system_counts[mixed_measurement]
else:
count_dicts[i][mixed_measurement] = complete_system_counts[mixed_measurement]
return count_dicts # remember other_indices registers are in qiskit ordering
# TODO: make unittests
# get_post_select_counts({'0 0': 10, '1 1' : 20}, [[1],[1]], [['0'],['1']])
# get_post_select_counts({'0 0': 10, '1 1' : 20, '1 2': 30}, [[1],[1]], [['0'],['1']])
def get_fraction_count_for_all_k(complete_system_counts, laplacian, sqrt):
# 0 simplicies are points, remember, may not be able to count _num_main_qubits in count register, so let's return size num_main_qubits - 1
# Main
# main_0_indices = [0]
# main_0_flags = ['0'*laplacian._num_main_qubits]
# no, rather let vary
count_start = 0
# Ancilla: Not measuring for now! TODO implement error mitigation.
# count_start = int((laplacian._num_clean_ancillae > 0))
# ancilla_indices = [1]*count_start #count_start is zero or one only
# ancilla_flags = ['0'*laplacian._num_clean_ancillae]*count_start
ancilla_indices = []
ancilla_flags = []
# Project Complex
count_start += 1
count_end = count_start + laplacian._num_complex_projections
project_complex_indices = list(range(count_start, count_end))
project_complex_flags = ['0'*laplacian._num_pairs]*laplacian._num_complex_projections
# Split
count_start = count_end
count_end = count_start + laplacian._num_split_projections
matching_split_indices_set = [list(range(count_start, count_end))]*\
(laplacian._num_main_qubits-1)
matching_split_flags_set = []
for k in range(0, laplacian._num_main_qubits-1): # k is simplex dim
# k+1 is num vertices:
k_as_bin_str = integer_to_binary_as_string(k+1, width=laplacian._count_bits_per_projection)
matching_split_flags_set.append([k_as_bin_str]*laplacian._num_split_projections)
projection_indices = ancilla_indices + project_complex_indices
projection_flags = ancilla_flags + project_complex_flags
projection_indices_set = list(map(lambda matching_split_indices: \
projection_indices + matching_split_indices,
matching_split_indices_set))
projection_flags_set = list(map(lambda matching_split_flags: \
projection_flags + matching_split_flags,
matching_split_flags_set))
counts_dicts = get_post_select_counts(complete_system_counts,
projection_indices_set,
projection_flags_set)
#prob0 = [dict_k['00']/sum(dict_k.values()) for dict_k in prob0_dicts], no forgot about footnote 12, go back to over everything else!
total_counts = sum(complete_system_counts.values())
# old confused way, when restricted counts to k simplices
# frac_counts = []
# for k, dict_k in enumerate(counts_dicts):
# valid_keys = [select_key for select_key in dict_k.keys()
# if sum(map(int, list(select_key))) == k+1]
# frac_counts.append(sum([*map(dict_k.get, valid_keys)])/total_counts)
if sqrt:
frac_counts = [sum(dict_k.values())/total_counts for dict_k in counts_dicts]
else:
frac_counts = [dict_k['0'*laplacian._num_main_qubits]/total_counts for dict_k in counts_dicts]
return frac_counts
############################################
### BOUNDARY OPERATOR HELPER FUNCTIONS
############################################
def operator_from_pauli_labels(coeff, paulis):
pauli_ops = []
for w, p in zip(coeff, paulis):
pauli_ops += [PrimitiveOp(Pauli.from_label(p), coeff=np.real(w) + np.imag(w)*1.j)]
return sum(pauli_ops)
# We go straight to the Pauli representation of b + b*
def boundary_operator_plus_conjugate_as_pauli_labels(num_vertices):
boundary_map_pauli_coeff = [1 for _ in range(num_vertices)]
first_part = "Z"*(num_vertices-1)
last_part = "I"*(num_vertices-1)
boundary_map_pauli_strings = map(lambda i:
first_part[:i] + "X" + last_part[i:],
range(num_vertices))
return boundary_map_pauli_coeff, list(boundary_map_pauli_strings)
def boundary_operator_hermitian(num_vertices):
qubit_op = operator_from_pauli_labels(
*boundary_operator_plus_conjugate_as_pauli_labels(
num_vertices))
return qubit_op
# return (1/np.sqrt(num_vertices))*qubit_op #normalize
def Ri_add(to_add_circ, three_qubits, theta):
qubit0 = three_qubits[1]
qubit1 = three_qubits[0]
target_qubit = three_qubits[2]
# Yi-1
# D
to_add_circ.x(qubit0)
to_add_circ.s(qubit0)
to_add_circ.h(qubit0)
# CNOT
to_add_circ.cx(qubit0, target_qubit)
# Xi
to_add_circ.h(qubit1)
to_add_circ.cx(qubit1, target_qubit)
to_add_circ.rz(theta, target_qubit)
# Xi\dagger
to_add_circ.cx(qubit1, target_qubit)
to_add_circ.h(qubit1)
# Yi-1\dagger
to_add_circ.cx(qubit0, target_qubit)
# D\dagger
to_add_circ.h(qubit0)
to_add_circ.sdg(qubit0)
to_add_circ.x(qubit0)
def boundary_operator_unitary_circuit(main_qreg=None, target_register=None, control_qubit=None):
if isinstance(main_qreg, int):
main_qreg = QuantumRegister(main_qreg)
num_vertices = len(main_qreg)
if target_register is None:
target_register = QuantumRegister(1)
boundary_circ = QuantumCircuit(main_qreg, target_register)
R_circ = QuantumCircuit(main_qreg, target_register)
#if isinstance(target_qubit, QuantumRegister):
target_qubit = target_register[0]
for i in range(1, num_vertices):
Ri_add(R_circ, [main_qreg[i-1], main_qreg[i], target_qubit],
np.arctan2(np.sqrt(i), 1))
# R
boundary_circ += R_circ
# P_0
if control_qubit is None:
boundary_circ.x(main_qreg[-1])
else:
boundary_circ.cx(control_qubit, main_qreg[-1])
# R\dagger
boundary_circ += R_circ.inverse()
return boundary_circ
# Just to check, we can define the boundary operator separately:
def boundary_operator_as_pauli_labels(num_vertices):
boundary_map_pauli_coeff = [[1/2, 1j/2] for _ in range(num_vertices)]
first_part = "Z"*(num_vertices-1)
last_part = "I"*(num_vertices-1)
boundary_map_pauli_strings = map(lambda i: list(map(
lambda B01_term: first_part[:i] + B01_term + last_part[i:],
["X", "Y"])), range(num_vertices))
return list(itertools.chain.from_iterable(boundary_map_pauli_coeff)),\
list(itertools.chain.from_iterable(boundary_map_pauli_strings))
def boundary_operator(num_vertices):
qubit_op = operator_from_pauli_labels(
*boundary_operator_as_pauli_labels(num_vertices))
return qubit_op
# def boundary_operator_conjugate_as_pauli_labels(num_vertices):
# coeffs, paulis = boundary_operator_as_pauli_labels(num_vertices)
# for i in range(num_vertices):
# coeffs[2*i+1] = -coeffs[2*i+1]
# return coeffs, paulis
#
# def boundary_operator_hermitian_derived_separately(num_vertices):
# qubit_op = operator_from_pauli_labels(
# *boundary_operator_conjugate_as_pauli_labels(num_vertices)) \
# + operator_from_pauli_labels(
# *boundary_operator_as_pauli_labels(num_vertices))
# return qubit_op
# def boundary_operator_squared_normalized(num_vertices):
# # this is automatically hermitian
# qubit_op = boundary_operator_hermitian(num_vertices)
# qubit_op *= (1/num_vertices)*qubit_op
# qubit_op.simplify()
# return qubit_op
# def boundary_reworked_to_kernel(num_vertices):
# qubit_op = boundary_operator_squared_normalized(num_vertices)
# return WeightedPauliOperator.from_list([Pauli.from_label("I"*(num_vertices+1))]) + (-1)*qubit_op
#Careful, here we take the real part only because we expect only real entries!
def classical_matrix_from_pauli_operator(qubit_op):
return np.real(qubit_op.to_matrix())
def rbs(circ, pair_reg, angle):
circ.h(pair_reg)
circ.cz(pair_reg[0], pair_reg[1])
circ.ry(-angle, pair_reg[0])
circ.ry(angle, pair_reg[1])
circ.cz(pair_reg[0], pair_reg[1])
circ.h(pair_reg)
return circ
def parity(circ, reg):
num_left = len(reg)
qubit_indices = list(range(num_left))
while num_left > 1:
new_qubit_indices = []
for start_index in range(0, num_left-1, 2):
circ.cx(reg[qubit_indices[start_index+1]], reg[qubit_indices[start_index]])
new_qubit_indices.append(qubit_indices[start_index])
if start_index < num_left - 2:
new_qubit_indices.append(qubit_indices[-1])
qubit_indices = new_qubit_indices[:]
num_left = len(qubit_indices)
return circ
def fbs(circ, reg, i, j, theta):
if i+2<j:
temp_circ = QuantumCircuit(reg)
parity(temp_circ, reg[i+1:j])
circ += temp_circ.inverse()
if i+1<j:
circ.cz(i+1,i)
rbs(circ, [reg[i], reg[j]], theta)
if i+1<j:
circ.cz(i+1,i)
if i+2<j:
circ += temp_circ
return circ
def clifford_loader(circ, reg, theta):
temp_circ = QuantumCircuit(reg)
num_left = len(reg)
qubit_indices = list(range(num_left))
while num_left > 1:
new_qubit_indices = []
for start_index in range(0, num_left-1, 2):
fbs(temp_circ, reg, qubit_indices[start_index], qubit_indices[start_index+1], theta)
new_qubit_indices.append(qubit_indices[start_index])
if start_index < num_left - 2:
new_qubit_indices.append(qubit_indices[-1])
qubit_indices = new_qubit_indices[:]
num_left = len(qubit_indices)
circ += temp_circ.inverse()
circ.x(reg[0])
circ += temp_circ
return circ
#######################################################################
############################################
### PROJECT ONTO COMPLEX HELPER FUNCTIONS
############################################
############################################
### Controlled Permutation (Add 1 And Cycle)
############################################
def permutation_circuit(qr=None, qancilla=None, circ=None):
# By permutation we mean "add 1 with wrapping". The key insight was seeing the 4x4 permutation matrix as a swapped flipped CNOT! Then for the 8x8: swap rows 000 and 100 and so on for higher order.
#NB: assumes Qiskit ordering
if qr is None:
raise Exception("Need to operate on a quantum register.")
if circ is None:
raise Exception("Need to operate on a circuit.")
num_qubits = len(qr)
if num_qubits==1:
circ.x(qr[0])
return circ
else:
if num_qubits > 3:
if qancilla is None:
qancilla = QuantumRegister(num_qubits - 2)
circ.add_register(qancilla)
print("Warning: adding ancilla ", qancilla.name)
for i in range(1, num_qubits):
if i > 1:
circ.x(qr[i-1])
if i == 1:
circ.cx(qr[0], qr[i])
else:
if i == 2:
circ.ccx(qr[0], qr[1], qr[i])
else:
circ.mct(qr[0:i], qr[i], qancilla, mode="v-chain")
if i == (num_qubits - 1):
circ.x(qr[0:i])
return qancilla
def diagonal_permutation_circuit(qr=None, angle=None, circ=None):
#default angle for permutation dagger (+ angle)
if qr is None:
raise Exception("Need to operate on a quantum register.")
if circ is None:
raise Exception("Need to operate on a circuit.")
n = len(qr)
if angle is None:
angle = 2*np.pi/(1<<n)
for i in range(0,n):
#circ.u1(angle*(1<<i), qr[i])
circ.p(angle*(1<<i), qr[i])
def multiplex_diagonal_permutation_circuit(qcontrol=None, qr=None, angle=None, circ=None): #create control permutation_dagger_permutation circuit. This circuit comes from Shende and Bullock, a multiplexed diagonal is a multiplexed Rz gate. Since we have very special structure to the diagonal elements, the multiplexed recursion is short-circuited!
if circ is None:
raise Exception("Need to operate on a circuit.")
if (qr is None) or (qcontrol is None):
raise Exception("Need to operate on a quantum registers")
if (type(qcontrol) != Qubit):
raise Exception("Need first argument to be the single control qubit.")
n = len(qr) + 1
if angle is None:
angle = 2*np.pi/(1<<(n-1))
for i in range(0,n-1):
circ.cx(qcontrol, qr[i])
#circ.u1(angle*(1<<i), qr[i])
circ.p(angle*(1<<i), qr[i])
circ.cx(qcontrol, qr[i])
#circ.u1(-angle*((1<<(n-1))-1), qcontrol)
circ.p(-angle*((1<<(n-1))-1), qcontrol)
# technically need to inverse(), since the algorithm takes desired state to zero but can use circ.mirror(). With mirror we do not take the minus sign of the desired angle, but with inverse we would have had to. Finally, we do not even need to call mirror because recursion is short-circuited and this particular circuit is invariant to mirroring because all the subparts commute: the target of CNOTs between subparts are different and U1 on source commutes with CNOT.
def control_permutation_circuit(qcontrol=None, count_register=None,
angle=None, qancilla=None, circ=None, leave_out_W=False, leave_out_V=False):
if circ is None:
raise Exception("Need to operate on a circuit.")
if (count_register is None) or (qcontrol is None):
raise Exception("Need to operate on a quantum registers")
if (type(qcontrol) != Qubit):
raise Exception("Need first argument to be the single control qubit.")
num_count_qubits = len(count_register)
if angle is None:
angle = 2*np.pi/(1 << (num_count_qubits + 1))
########## AAAAAAAAAAAAAA DOCUMENT!!! This is taking the square root! D^2 is the diagonal of the permutation matrix, D is the square root of D^2
count_register_flipped = count_register[::-1]
# iqft_inst = QFT(num_count_qubits, inverse=True,
# do_swaps=False).to_instruction()
iqft_inst = QFT(num_count_qubits, do_swaps=False).inverse().to_instruction()
qft_inst = QFT(num_count_qubits, inverse=False,
do_swaps=False).to_instruction()
# iqft_inst = QFT(num_count_qubits, do_swaps=False).inverse().to_instruction()
# qft_inst = QFT(num_count_qubits, inverse=False,
# do_swaps=True).to_instruction()
# W in paper
if not leave_out_W:
qancilla = permutation_circuit(count_register, qancilla, circ=circ)
# Fourier_circ.construct_circuit(circ, count_register,
# inverse=True, do_swaps=False)
circ.append(iqft_inst, count_register_flipped)#count_register)
#In the forward Fourier circuit, the swaps come at the beginning, for the inverse, the swaps come at the end. Switching off the swaps implies that after this inverse circuit, the ordering significance is now swapped and subsequent placement of gates must be flipped.
# diagonal_permutation_circuit(count_register_flipped, angle=angle, circ=circ)
diagonal_permutation_circuit(count_register_flipped, angle=angle, circ=circ)
#gates are flipped because one swap is missing (the significance is swapped)
# (D D^) in paper
#multiplex_diagonal_permutation_circuit(qcontrol, count_register_flipped, angle=angle, circ=circ)
multiplex_diagonal_permutation_circuit(qcontrol, count_register_flipped, angle=angle, circ=circ)
#gates still flipped because one swap is missing
# V in paper
# Fourier_circ.construct_circuit(circ, count_register, inverse=False, do_swaps=False)
if not leave_out_V:
circ.append(qft_inst, count_register_flipped) # count_register)
#with swaps off at the beginning, the flipped significance is already in the flipped order required for the subsequent placement of gates, thereafter everything is back to normal
return qancilla
##################################################
# def rccx(circ, qubit0, qubit1, target_qubit):
# circ.ry(np.pi/4, target_qubit)
# circ.cx(qubit1, target_qubit)
# circ.ry(np.pi/4, target_qubit)
# circ.cx(qubit0, target_qubit)
# circ.ry(-np.pi/4, target_qubit)
# circ.cx(qubit1, target_qubit)
# circ.ry(-np.pi/4, target_qubit)
def num_complex_projections(powers=[1], sqrt=False):
sum_projections = 0
coeff = 1 if sqrt else 2
for p in powers:
sum_projections += coeff*p + 1
return sum_projections
# flag register: n/2 qubits
# Code up n-1 rounds of n/2 CCNOTS. Placing the gate only if the pair under consideration is not (is) present in edges_in.
# mid-circuit measurement on the flag register
# Bail out if flag register is not all ones (zeros)
def project_onto_complex(circ, edges_in, simplex_qreg, simplex_in, measure_reg=None, num_resets=1,
do_rccx=True):
#simplex_in flag register of size n/2
#measure_reg size n C 2
#edges_in are pairs of points. points are identified by their point index (starting at 0)
#edges_in must be list of list
num_main_qubits = len(simplex_qreg)
num_pairs = num_main_qubits*(num_main_qubits - 1)//2
half_num_main_qubits = num_main_qubits//2
if measure_reg is not None:
if (half_num_main_qubits != len(simplex_in)):
raise ValueError("Size of simplex_in register, "
"does not equal n/2.")
else:
if (num_pairs != len(simplex_in)):
raise ValueError("Size of simplex_in register, "
"does not equal num_pairs.")
if not isinstance(edges_in, list):
raise ValueError("edges_in not a list of a list of two ints.")
for pair in edges_in:
if not isinstance(pair, list) or len(pair) != 2:
raise ValueError("edges_in does not contain lists of two ints.")
if not isinstance(pair[0], int) or not isinstance(pair[1], int):
raise ValueError("edges_in inner lists do not contain ints.")
top_qubits = np.arange(num_main_qubits)
bottom_qubits = np.arange(num_main_qubits)
bottom_qubits = np.roll(bottom_qubits,-1)
# gates = []
for count_round in range(1, half_num_main_qubits+1): # R from spreadsheet
count_round_from_zero = count_round - 1
pair_qubits = np.array([*zip(top_qubits, bottom_qubits)])
take = 1 << (first_non_zero_bit(count_round))
#the last round only has one inner_round
if count_round < half_num_main_qubits:
rounds = [0, 1]
else:
rounds = [0]
for inner_round in rounds:
take_in_a_row = np.array(range(take))
take_indices = np.zeros((half_num_main_qubits), dtype=int)
for i in range((half_num_main_qubits)//take):
take_indices[i*take:(i+1)*take] = \
(take_in_a_row + i*(2*take) + inner_round*take) % num_main_qubits
for pairs_index, pair in enumerate(pair_qubits[take_indices].tolist()):
if pair not in edges_in: # consider using bisect search of sorted list
pair.reverse()
if pair not in edges_in:
if measure_reg is not None:
qubits = (pair[0], pair[1], simplex_in[pairs_index])
else:
qubits = (pair[0], pair[1], simplex_in[
count_round_from_zero*num_main_qubits +
inner_round*half_num_main_qubits + pairs_index])
if do_rccx:
circ.rccx(*qubits)
# rccx(circ, *qubits)
else:
circ.ccx(*qubits)
if measure_reg is not None:
# could use: circ._mid_circuit, but prefer not to delve into internals
circ.measure(simplex_in, measure_reg[
count_round_from_zero*num_main_qubits + inner_round*half_num_main_qubits:
count_round_from_zero*num_main_qubits + (inner_round+1)*half_num_main_qubits])
for _ in range(num_resets):
circ.reset(simplex_in)
bottom_qubits = np.roll(bottom_qubits, -1)
return circ
#######################################################################
### SPLIT BY SIMPLEX DEGREE K (entangle with counter reg, then PROJECT)
#######################################################################
def split_k(circ, from_qreg, counter_qreg, qancilla=None):
# , reshuffle=False):
# PROJECTION ONTO K-SIMPLICES
#warning, code similar to within control_permutation_circuit
count_register_flipped = counter_qreg[::-1]
num_count_qubits = len(counter_qreg)
angle = -2*np.pi/(1 << (num_count_qubits + 1))
# separate by k for k-simplices
for i in range(len(from_qreg)):
leave_out_W = True if i > 0 else False
leave_out_V = True if i < len(from_qreg)-1 else False
qancilla = control_permutation_circuit(from_qreg[i], counter_qreg, qancilla=qancilla,
circ=circ, leave_out_V=leave_out_V,
leave_out_W=leave_out_W)
if leave_out_V:
diagonal_permutation_circuit(count_register_flipped, angle=angle, circ=circ)
return qancilla
# #make 1 and 2, 1x neighbours, if we measure counter_qreg[1], it collapses the entangled simplices
# if reshuffle:
# circ.cx(counter_qreg[0], counter_qreg[1])
#interfere neighbours -> not necessary (maybe it could help later?)
#circ.h(counter_qreg[0])
def split_k_inverse(circ, from_qreg, counter_qreg):
# TODO: decide what to do about qancilla
tempCirc = QuantumCircuit(from_qreg, counter_qreg)
split_k(tempCirc, from_qreg, counter_qreg)
circ.data += tempCirc.inverse().data
def num_split_projections(powers=[1], sqrt=False):
sum_projections = 0
add_proj = 0 if sqrt else 1
intdiv = 2 if sqrt else 1
for p in powers:
sum_projections += p//intdiv + 1
return sum_projections
#######################################################################
############################################
### OTHER HELPER FUNCTIONS
############################################
def initialize_register(qcirc, complex_vector, qreg, inverse=False):
circ_complex = QuantumCircuit(qreg)
myinit = Initialize(complex_vector)
circ_complex.append(
myinit.gates_to_uncompute().to_instruction(), qreg)
if inverse:
qcirc += circ_complex
else:
qcirc += circ_complex.inverse()
def unroll_projections(list_projs):
unrolled_proj = []
for projs in list_projs:
unrolled_proj.extend(projs)
return unrolled_proj
def advanced_index_selecting_diagonal_of_split_k(laplacian):
# Old:
# select_dim = [0, 0]
# select_dim.extend(list(np.ones(
# laplacian._num_complex_projections, dtype=int)
# * ((1 << num_pairs) - 1)))
# select_dim.extend([np.array(range(1, num_main_qubits + 1), dtype=int)
# for _ in
# range(
# laplacian._num_split_projections)])
num_main_qubits = laplacian._num_main_qubits
advanced_index_array_base = np.arange(1, num_main_qubits, dtype=int)
# This is counting vertices, 1, num_main_qubits+1 is from 1 to num_main_qubits, inclusive. Careful if complex is fully connected, introduce check or wrap % num_main_qubits - 1, or leave out num_main_qubits, yes do this
advanced_index_array = np.zeros(num_main_qubits - 1, dtype=int)
for i in range(laplacian._num_split_projections):
advanced_index_array += \
advanced_index_array_base*(1 << (i*laplacian._count_bits_per_projection))
return advanced_index_array
def reshape_into_tensor_of_dim_main_ancilla_proj_split(circ_output, laplacian):
# Old:
# reshape_dim = np.zeros(2 + laplacian._num_complex_projections +
# laplacian._num_split_projections, dtype=int)
# reshape_dim[0] = 1 << num_main_qubits
# reshape_dim[1] = 1 << laplacian._num_clean_ancillae
# reshape_dim[2:2+laplacian._num_complex_projections] = \
# np.ones(laplacian._num_complex_projections) *\
# (1 << num_pairs)
# reshape_dim[2+laplacian._num_complex_projections:] = \
# np.ones(laplacian._num_split_projections) *\
# (1 << laplacian._count_bits_per_projection)
# output_tensor = circ_output.reshape(tuple(reshape_dim),
# order='F')
output_tensor = circ_output.reshape(
1 << laplacian._num_main_qubits,
1 << laplacian._num_clean_ancillae,
1 << laplacian._num_complex_projections*laplacian._num_pairs,
1 << laplacian._num_split_projections* \
laplacian._count_bits_per_projection,
order='F')
return output_tensor
#######################################################################
#######################################################################
############################################################
### MAIN CLASSES TO CREATE CIRCUITS FOR MOMENTS OF LAPLACIAN
############################################################
class Projected_Laplacian(QuantumCircuit):
# Since Laplacian is implemented using Taylor expansion
# a lot of post-processing is required
# leave out first projection because assuming only one simplex already in
# the complex (Ken) -> yes option open again? -> no, because using
# Rademacher vectors
"""
Direct Unitary Method: boundary_operator_unitary_circuit(num_vertices)
"""
def __init__(self, *, num_vertices=None, edges_in=None, power=1,
num_ancillae_eigenvalue_resolution=0,
sqrt=False, mid_circuit=False, num_resets=None, do_rccx=True):
# Registers: _main_qreg, _clean_ancilla, _reusable_qreg OR (_complex_qregs AND _split_qregs)
# Size: _num_main_qubits, _num_clean_ancillae, ._num_projection_qubits (= _half_num_main_qubits* OR
# (_num_complex_projections*_num_pairs +
# _num_split_projections*_count_bits_per_projection))
####################################################
# Consume num_vertices, edges_in
####################################################
if num_vertices is None:
raise(ValueError("num_vertices not specified from which to build up complex."))
if edges_in is None:
raise(ValueError("edges_in not specified from which to build up complex."))
# TODO: worry about user inputing the wrong size edges_in
self._edges_in = edges_in
# self._num_pairs = len(edges_in)
# self._num_qubits = num_qubits_from_num_pairs(self._num_pairs)
if not is_power_of_2(num_vertices):
raise ValueError("For now, num_vertices must be a power of two.")
self._num_main_qubits = num_vertices # consider getting from largest vertex in edges_in, nah, see remap
self._half_num_main_qubits = num_vertices // 2
self._num_pairs = num_vertices*(num_vertices-1)//2
self._main_qreg = QuantumRegister(self._num_main_qubits, "mainqreg")
super().__init__(self._main_qreg)
self._count_bits_per_projection = num_bits(self._num_main_qubits)
# Should be number + 1, to store the all-vertex simplex. Decided to save that bit (we're in the case of power of 2). We could introduce check for the fully connected one-skeleton and return something meaningful, but rather just say we're not interested in simplices of order num_vertices, which is the case.
self._num_permutation_ancillae = max(0,
self._count_bits_per_projection - 2)
if not mid_circuit: # and self._num_permutation_ancillae > 0:
self._num_clean_ancillae = max(self._num_permutation_ancillae, 1)
# max(# self._num_pairs, # n^2 vs logn, don't need. The 1 is for boundary.
# in NISQ it may be better to have separate registers to limit
# noise? or use mid-circuit reset!!
self._clean_ancilla = AncillaRegister(self._num_clean_ancillae, # could multiply by numsplit and measure all at the end as a noise detection scheme
name="clean_ancillae")
self.add_register(self._clean_ancilla)
else: # for the case mid_circuit=True, we still don't need extra quantum ancillae, even though we could get classical ancillae answers out. TODO: do just that for error mitigation.
self._num_clean_ancillae = 0
self._clean_ancilla = None
####################################################
# Consume power, num_ancillae_eigenvalue_resolution
####################################################
self.base_power = power
self._num_ancillae_eigenvalue_resolution = \
int(num_ancillae_eigenvalue_resolution)
if self._num_ancillae_eigenvalue_resolution > 0:
self.powers = [int(self.base_power*(2**i)) for i in range(
self._num_ancillae_eigenvalue_resolution)]
self._control_reg_consolidate = QuantumRegister(1)
self.add_register(self._control_reg_consolidate)
if self._num_ancillae_eigenvalue_resolution == 1:
self._control_reg = None
else:
self._control_reg = QuantumRegister(self._num_ancillae_eigenvalue_resolution)
self.add_register(self._control_reg)
else:
self.powers = [int(self.base_power)]
self._control_reg_consolidate = None
####################################################
# Consume sqrt, mid_circuit
####################################################
self._sqrt = sqrt
self._mid_circuit = mid_circuit
self._num_complex_projections = num_complex_projections(self.powers,
self._sqrt)
self._num_split_projections = num_split_projections(self.powers,
self._sqrt)
if mid_circuit:
self._reusable_qreg = AncillaRegister(
max(self._half_num_main_qubits,
self._count_bits_per_projection + self._num_permutation_ancillae,
1),
name="reusableprojqreg")
# Complex projection (always the max), Order projection (count + mct), boundary circ exponentiate Z on target
self._num_projection_qubits = len(self._reusable_qreg)
self.add_register(self._reusable_qreg)
self._boundary_sum_unitary_circuit = \
boundary_operator_unitary_circuit(self._main_qreg,
self._reusable_qreg, # don't worry whole reg not used
self._control_reg_consolidate)
# consider reset -> yes see power
else:
self._boundary_sum_unitary_circuit = \
boundary_operator_unitary_circuit(self._main_qreg,
self._clean_ancilla,
self._control_reg_consolidate)
self._complex_qregs = []
self._split_qregs = []
for power in self.powers:
projections_for_power = []
power_num_complex_projections = num_complex_projections([power], self._sqrt)
for projection in range(power_num_complex_projections):
projections_for_power.append(
AncillaRegister(self._num_pairs,
name="power" + str(power) +
"complexqproj" + str(projection)))
self._complex_qregs.append(projections_for_power)
projections_for_power = []
power_num_split_projections = num_split_projections([power], self._sqrt)
for projection in range(power_num_split_projections):
projections_for_power.append(
AncillaRegister(self._count_bits_per_projection,
name="power" + str(power) +
"splitqproj" + str(projection)))
self._split_qregs.append(projections_for_power)
self.add_register(*unroll_projections(self._complex_qregs),
*unroll_projections(self._split_qregs))
self._num_projection_qubits = self._num_complex_projections*self._num_pairs + \
self._num_split_projections*self._count_bits_per_projection
#technically don't need _main_creg at all, if backend is statevector_simulator, but can't check here, because don't know what backend is, no need to pass because no harm if created.
if self._sqrt:
self._main_creg = ClassicalRegister(self._num_main_qubits)
self.add_register(self._main_creg)
else:
self._main_creg = ClassicalRegister(1)
self.add_register(self._main_creg)
self._complex_cregs = []
self._split_cregs = []
for power in self.powers:
projections_for_power = []
for projection in range(num_complex_projections([power],
self._sqrt)):
projections_for_power.append(
ClassicalRegister(self._num_pairs,
name="power" + str(power) +
"complexcproj" + str(projection)))
self._complex_cregs.append(projections_for_power)
projections_for_power = []
for projection in range(num_split_projections([power],
self._sqrt)):
projections_for_power.append(
ClassicalRegister(self._count_bits_per_projection,
name="power" + str(power) +
"splitcproj" + str(projection)))
self._split_cregs.append(projections_for_power)
self.add_register(*unroll_projections(self._complex_cregs),
*unroll_projections(self._split_cregs))
self._num_total_qubits = self._num_main_qubits + self._num_clean_ancillae + \
self._num_projection_qubits
# Uncomment to use as a form of error detection
# # put at end (first in count list) to allow for easier removal
# if (not mid_circuit) and self._num_permutation_ancillae > 0:
# self._clean_ancilla_creg = ClassicalRegister(
# self._num_permutation_ancillae)
# self.add_register(self._clean_ancilla_creg)
# else:
# self._clean_ancilla_creg = None
# # should actually peal away case of mid-circuit and possibly measure
# # for split_projection as a noise detection mechanism! also reset reusable quantum register
# Both mid_circuit=True and False need classical registers
####################################################
# Consume num_resets and do_rccx
####################################################
if num_resets is None:
self._num_resets = int(mid_circuit)
else:
self._num_resets = num_resets
if mid_circuit:
if num_resets == 0:
print("Warning: mid_circuit==True and num_resets==0.")
elif num_resets > 0:
print("Warning: mid_circuit==False but num_resets>0.")
self._do_rccx = do_rccx
def measure_all_qregs(self):
"""Only to be called for "count" backends (sim or hardware), not to be called for statevector backends. Place measurements on projection registers if mid_circuit is false. Always place measurements on main register (sqrt uses all counts on main reg, not sqrt uses 0 of main reg)! Technically don't need to place measurements on ancillae, but could be used to check for errors?"""
if self._sqrt:
self.measure(self._main_qreg, self._main_creg)
else:
self.measure(self._main_qreg[0], self._main_creg[0])
if not self._mid_circuit:
for qreg_for_power, creg_for_power in zip(unroll_projections(self._complex_qregs),
unroll_projections(self._complex_cregs)):
self.measure(qreg_for_power, creg_for_power)
for qreg_for_power, creg_for_power in zip(unroll_projections(self._split_qregs),
unroll_projections(self._split_cregs)):
self.measure(qreg_for_power, creg_for_power)
# uncomment to use as a form of error detection also introduce such measurements for
# mid_circuit=True in the loop
# if self._num_clean_ancillae > 0:
# self.measure(self._clean_ancilla, self._clean_ancilla_creg)
def split_ancillae(self):
if self._num_permutation_ancillae > 0:
return self._clean_ancilla[:self._num_permutation_ancillae]
else: return None
def power(self, power, matrix_power=False):
# Warning returns first entry only, but should only have one and only one
# Note not storing power, so .power(2).control() won't control the square, rather: .control(power=2) -> reconsider this now that control automatically handled?
if matrix_power:
raise Exception("Matrix Power not supported")
power_index = self.powers.index(power)
count_complex_projection = 0
count_split_projection = 0
def place_complex_projection():
nonlocal count_complex_projection
if self._mid_circuit:
complex_qreg = self._reusable_qreg[:self._half_num_main_qubits] # self._num_pairs]
complex_creg = self._complex_cregs[power_index][count_complex_projection]
else:
complex_qreg = self._complex_qregs[power_index][count_complex_projection]
complex_creg = None
project_onto_complex(self, self._edges_in, self._main_qreg,
complex_qreg, complex_creg, self._num_resets, do_rccx=self._do_rccx)
count_complex_projection += 1
def place_split_projection():
nonlocal count_split_projection
if self._mid_circuit:
split_qreg = self._reusable_qreg[:self._count_bits_per_projection]
ancilla_qreg = self._reusable_qreg[self._count_bits_per_projection:]
else:
split_qreg = self._split_qregs[power_index][count_split_projection]
ancilla_qreg = self.split_ancillae()
split_k(self, self._main_qreg, split_qreg,
qancilla=ancilla_qreg) # self.split_ancillae())
if self._mid_circuit:
self.measure(split_qreg,
self._split_cregs[power_index][count_split_projection])
for _ in range(self._num_resets):
self.reset(split_qreg)
count_split_projection += 1
place_complex_projection()
place_split_projection()
if self._sqrt:
number_of_PB_pairs = power
else:
number_of_PB_pairs = 2*power
for i in range(number_of_PB_pairs):
self += self._boundary_sum_unitary_circuit # automatically caters for control
if self._mid_circuit:
for _ in range(self._num_resets):
self.reset(self._reusable_qreg[0]) # boundary circuit uses the first qubit of the reusable register as the ancilla
place_complex_projection()
if (i % 2):
place_split_projection()
def control(self, num_ctrl_qubits=None, label=None, ctrl_state=None,
power=1, use_basis_gates=True): # TODO: write unit tests and use in QPE
# overloading, not controlling projection since shouldn't change anything?
# consider doing the 'wrong' black-box control!
if num_ctrl_qubits is None:
num_ctrl_qubits = self._num_ancillae_eigenvalue_resolution
if label is None:
label='c_{}'.format(self.name)
if ctrl_state is not None:
raise Exception("Not handling ctrl_state=True at the moment.")
if self._control_reg is not None:
self.mct(self._control_reg, self._control_reg_consolidate)
self.power(power)
class Project_and_Split(Projected_Laplacian): # TODO: still to write unit_tests
def __init__(self, edges_in=None, num_vertices=None, mid_circuit=False):
super().__init__(edges_in=edges_in, num_vertices=num_vertices, power=0, mid_circuit=mid_circuit)
# self.power(0)
class Projected_Boundary(Projected_Laplacian):
def __init__(self, edges_in=None, num_vertices=None, power=1,
num_ancillae_eigenvalue_resolution=0, mid_circuit=False):
super().__init__(edges_in=edges_in, num_vertices=num_vertices, power=power,
num_ancillae_eigenvalue_resolution=num_ancillae_eigenvalue_resolution,
sqrt=True, mid_circuit=mid_circuit)
#######################################################################
#######################################################################
# FUNCTIONS TO RUN CIRCUITS and POST-PROCESS
#######################################################################
def print_unitary_and_trace(circ, trace=True):
usim = BasicAer.get_backend('unitary_simulator')
# usim = Aer.get_backend('aer_simulator')
# laplacian.save_unitary()
temp_circuit = transpile(circ, backend=usim, optimization_level=0)
qobj = assemble(temp_circuit)
unitary = usim.run(qobj).result().get_unitary()
print_matrix(unitary, vecfunc=format_real)
if trace:
import pdb
pdb.set_trace()
def expectation_of_laplacian(*, num_vertices, edges_in, vec_in=None, vec_in_circ=None,
power=1, mid_circuit=False, sqrt=True, num_resets=None,
job_name=None, backend_name="aer_simulator_statevector",
rename_job_after_done=False, do_rccx=True,
noise=None, shots=None):
def rename_job(job):
nonlocal job_name
nonlocal backend_local_sim
nonlocal rename_job_after_done
job_name = job_name + "_" + secrets.token_urlsafe(8)
if not backend_local_sim and rename_job_after_done:
# not isinstance(job, BasicAerJob)
print("Renaming ibmq job to: ", job_name)
job.update_name(job_name)
if vec_in is not None and vec_in_circ is not None:
raise ValueError("Error: vec_in and vec_in_circ specified. Specify one or neither.")
# TODO: rather check type of single argument
else:
qreg_temp = QuantumRegister(num_vertices)
vec_circ = QuantumCircuit(qreg_temp)
if vec_in is not None:
initialize_register(vec_circ, vec_in, qreg_temp)
elif vec_in_circ is not None:
vec_circ = vec_in_circ
else:
vec_circ.h(qreg_temp)
vec_circ_inst = vec_circ.to_instruction()
vec_circ_inverse_inst = vec_circ.copy().inverse().to_instruction()
result = None
if backend_name is None:
backend_any_asked = True
else:
backend_any_asked = False
backend_local_sim = (backend_name == 'qasm_simulator' or # old python simulator
backend_name == 'statevector_simulator' or # old python
backend_name == 'aer_simulator_statevector' or # new C++
backend_name == 'aer_simulator_statevector_gpu' or # new GPU
backend_name == 'aer_simulator_density_matrix' or # new C++
backend_name == 'aer_simulator_density_matrix_gpu') # new GPU
gpu = (backend_name == 'aer_simulator_statevector_gpu' or
backend_name == 'aer_simulator_density_matrix_gpu')
if backend_local_sim:
if mid_circuit or noise is not None:
if backend_name == 'statevector_simulator':
raise ValueError('mid_circuit/noise not compatible with old statevector '
'simulator')
backend = Aer.get_backend(backend_name)
if gpu:
backend.device="GPU" # should not be needed
backend.set_options(batched_shots_gpu=True)
backend.set_options(batched_shots_gpu_max_qubits=32)
if shots is None:
shots = 50000
if noise is not None:
# Error probabilities
prob_1 = noise[0] # 1-qubit gate
prob_2 = noise[1] # 2-qubit gate
prob_mat = [[1-prob_2,prob_2],[prob_2,1-prob_2]]
# Depolarizing quantum errors
error_1 = qnoise.depolarizing_error(prob_1, 1)
error_2 = qnoise.depolarizing_error(prob_2, 2)
read_err = qnoise.ReadoutError(prob_mat)
# Add errors to noise model
noise_model = qnoise.NoiseModel()
noise_model.add_all_qubit_quantum_error(error_1, ['u1', 'u2', 'u3'])
noise_model.add_all_qubit_quantum_error(error_2, ['cx'])
noise_model.add_all_qubit_readout_error(read_err)
# Get basis gates from noise model
basis_gates = noise_model.basis_gates
backend.set_options(noise_model=noise_model, basis_gates=basis_gates)
else:
noise_model = None
# mybackend_shots = 80000
# backend._configuration.n_qubits = 24
# if backend_name == 'qasm_simulator':
# backend._configuration.max_shots = 2*10**3#10**6 #1000 # 10**7
else:
backend = None
if backend_name == "ionq_qpu":
provider = IonQProvider("YKI565sxYHK1Pe3w4mRRHOQ6EvhbGXeF")
# print(provider.backends())
backend = provider.get_backend("ionq_qpu")
if shots is None:
shots = 100 # backend._configuration.max_shots
elif backend_name == "HQS-LT-S1-SIM" or backend_name == "HQS-LT-S2-SIM" \
or backend_name == "HQS-LT-S1" or backend_name == "HQS-LT-S2":
Honeywell.load_account()
backend = Honeywell.get_backend(backend_name)
if shots is None:
shots = 2000
else:
if IBMQ.active_account() is None:
IBMQ.enable_account(\
'ec1952054b99bc0febe3c3d296521da193190fb4f9c3925d7'
'b7a015c443240f07263c4f9b6bdbf1a0c99f6fe7451af029b'
'2c52d06f222e94bc467f14b8e2adf6')
provider = IBMQ.get_provider(hub='ibm-q-internal') # ('ibm-q-internal')
if backend_name is not None:
backend = provider.get_backend(backend_name)
if job_name is not None:
past_days = datetime.now() - timedelta(days=JOB_PREVIOUS_DAYS)
# Add local tz in order to compare to `creation_date` which is tz aware.
# past_days_tz_aware = past_days.replace(tzinfo=tz.tzlocal())
if backend is None:
myjobs = provider.backends.jobs(limit=JOB_RETRIEVE_LIMIT,
start_datetime=past_days)
else:
myjobs = backend.jobs(limit=JOB_RETRIEVE_LIMIT,
start_datetime=past_days)
myjob_dict = {myjob.name():myjob for myjob in myjobs}
if job_name in list(myjob_dict):
myjob_status = myjob_dict[job_name].status()
if backend is None:
backend = myjob_dict[job_name].backend()
backend_name = backend.name()
if myjob_status is not JobStatus.DONE:
print("Found job: ", job_name, ", Status is: ",
myjob_status, ". Rerun later.")
return (backend_name, job_name)
else:
result = myjob_dict[job_name].result()
print("Found job: ", job_name, ", Status is: ",
myjob_status, ".")
rename_job(myjob_dict[job_name])
# Need the laplacian object to choose hardware backend, run and/or to analyse results
laplacian = Projected_Laplacian(num_vertices=num_vertices,
edges_in=edges_in, power=power,
mid_circuit=mid_circuit, sqrt=sqrt,
num_resets=num_resets,
do_rccx=do_rccx)
q_main_reg = laplacian._main_qreg
num_main_qubits = laplacian._num_main_qubits
num_pairs = laplacian._num_pairs
num_total_qubits = laplacian._num_total_qubits
if result is None:
if backend is None: # when sim is False and no job found
available_devices = provider.backends(
filters=lambda x: (x.configuration().n_qubits >= num_total_qubits) and
(not x.configuration().simulator)) # and x.status().operational==True)
if not available_devices:
raise AssertionError("No available devices with at least " +
str(num_total_qubits)
+ " qubits.")
backend = least_busy(available_devices)
backend_name = backend.configuration().backend_name
backend_any_asked = True
print("Least Busy Backend:", backend_name)
if shots is None:
shots = backend._configuration.max_shots
# CIRCUIT CONSTRUCTION
laplacian.append(vec_circ_inst, qargs=q_main_reg)
laplacian.power(power) # already taking into account sqrt (during _init_)
if not sqrt: # here and below could use laplacian._sqrt to emphasise laplacian, chose not to since did assign local variables to other laplcian variables
laplacian.append(vec_circ_inverse_inst, qargs=q_main_reg)
# print_unitary_and_trace(laplacian)
if backend_name != 'statevector_simulator': # may need to check for ibmq statevector_simulator
laplacian.measure_all_qregs()
if backend.configuration().n_qubits == 27:
if num_main_qubits == 2:
if mid_circuit:
rqreg = laplacian._reusable_qreg
initial_layout = {q_main_reg[0]: 11,
q_main_reg[1]: 16,
rqreg[0]: 14}
else:
cqreg = laplacian._complex_qregs[0]
sqreg = laplacian._split_qregs[0]
aqreg = laplacian._clean_ancilla
initial_layout = {q_main_reg[0]: 11,
q_main_reg[1]: 16,
aqreg[0]: 14,
sqreg[0][0]: 13,
cqreg[0][0]: 8,
cqreg[1][0]: 19}
elif num_main_qubits >= 4:
if mid_circuit:
rqreg = laplacian._reusable_qreg
initial_layout = {q_main_reg[0]: 11,
q_main_reg[1]: 16,
q_main_reg[2]: 15,
q_main_reg[3]: 10,
rqreg[0]: 14,
rqreg[1]: 12}
#rqreg[2]: 13}
else:
cqreg = laplacian._complex_qregs[0]
sqreg = laplacian._split_qregs[0]
aqreg = laplacian._clean_ancilla
initial_layout = {q_main_reg[0]: 11,
q_main_reg[1]: 16,
q_main_reg[2]: 15,
q_main_reg[3]: 10,
aqreg[0]: 13,
sqreg[0][0]: 14,
sqreg[0][1]: 12,
cqreg[0][0]: 8,
cqreg[0][1]: 19,
cqreg[0][2]: 18,
cqreg[0][3]: 7,
cqreg[0][4]: 5,
cqreg[0][5]: 22,
cqreg[1][0]: 9,
cqreg[1][1]: 20,
cqreg[1][2]: 17,
cqreg[1][3]: 6,
cqreg[1][4]: 21,
cqreg[1][5]: 4}
else:
initial_layout = None
else:
initial_layout = None
# RUN CIRCUIT
unrolled_laplacian = transpile(laplacian, backend=backend,
seed_transpiler=11, optimization_level=0)
optimized_laplacian = transpile(laplacian, backend=backend,
seed_transpiler=11, optimization_level=3,
initial_layout=initial_layout)
print("width: ", optimized_laplacian.width(), "depth: ",
optimized_laplacian.depth())
if backend_name == "ionq_qpu":
job = backend.run(optimized_laplacian, shots=shots)
import time
while job.status() is not JobStatus.DONE:
print("Job status is", job.status())
time.sleep(60)
result = job # sic, weird IonQ convention
if rename_job_after_done:
print("Warning: Ignoring rename job on IonQ server, no functionality.")
rename_job_after_done = False
rename_job(job)
elif backend_name == "HQS-LT-S1-SIM" or backend_name == "HQS-LT-S2-SIM" \
or backend_name == "HQS-LT-S1" or backend_name == "HQS-LT-S2":
job_honey = execute(optimized_laplacian, backend, shots=shots)
job_honey_id = job_honey.job_ids()[0]
print("Honeywell Job id: ", job_honey_id)
return (backend_name, job_honey_id)
else:
if job_name is None:
job_name = str(num_vertices) + "_" \
+ ("True" if mid_circuit else "False") + "_" \
+ ("True" if sqrt else "False")
job = execute(optimized_laplacian, backend, job_name=job_name,
shots=shots)
# time.sleep(5)
if job.status() is JobStatus.DONE or backend_local_sim:
result = job.result()
rename_job(job)
else:
print("Job submitted, please rerun to collect results.")
return (backend_name, job_name)
else:
print("Laplacian Original:")
print("width: ", laplacian.width())
# print("depth: ", laplacian.depth()) -> zero if reached
if backend_name == 'statevector_simulator':
circ_output = result.get_statevector(optimized_laplacian)
output_tensor = reshape_into_tensor_of_dim_main_ancilla_proj_split(circ_output,
laplacian)
main_qreg_select = slice(0, None) if sqrt else 0
advanced_index_array = advanced_index_selecting_diagonal_of_split_k(laplacian)
expectation_laplacian = output_tensor[
main_qreg_select,
0,
0,
advanced_index_array]
if sqrt:
expectation_laplacian = np.linalg.norm(expectation_laplacian, axis=0)**2
else: # 'qasm_simulator' or hardware
counts = result.get_counts()
counts_file = open("../output/" + (backend_name + "_" if backend_any_asked else "") + job_name +
".json", "w")
json.dump(counts, counts_file)
counts_file.close()
frac_counts = np.array(get_fraction_count_for_all_k(counts, laplacian, sqrt))
expectation_laplacian = frac_counts if sqrt else np.sqrt(frac_counts)
# num_Bs = power*(1 if sqrt else 2) not actual B's, but analytical number
# num_Bs = power*2
#expectation_laplacian *= np.sqrt(num_vertices)**(num_Bs) # final correction since B = sqrt(n)RXR
# expectation_laplacian *= num_vertices**power times (num_vertices^power) to correct for B, divide by to make largest eigenvalue 1
# expectation_laplacian[0] -= 1/(num_vertices**power) # correction for augmented Laplacian, see Goldeberg Page 42 v^T(P_kP_GBP_GBP_GP_k)v, since v^TUv = 0 for Hadamard vectors, we ignore this term
return expectation_laplacian
# if power > 0:
# # expectation_projections = fraction_in_complex_of_all_orders(num_vertices=num_vertices,
# # edges_in=edges_in,
# # vec_in_circ=vec_circ)
# # # Boundary squared = identity * num_main_qubits
# # expectation_boundary_squared = expectation_projections*num_main_qubits
# # expectation_laplacian = ((-1)**sqrt)*((expectation_projections -
# # expectation_taylor)/(laplacian._time_evolution**2) -
# # expectation_boundary_squared*power)
# return expectation_laplacian
# else:
# return expectation_taylor
def fraction_in_complex_of_all_orders(*, num_vertices, edges_in, vec_in=None, vec_in_circ=None, mid_circuit=False, sqrt=True, job_name=None, backend_name="statevector_simulator"):
return expectation_of_laplacian(num_vertices=num_vertices, edges_in=edges_in, vec_in=vec_in,
vec_in_circ=vec_in_circ, power=0, mid_circuit=mid_circuit,
sqrt=sqrt, job_name=job_name, backend_name=backend_name)
# def average_expectation_over_random_two_local_vec_circs(num_vertices, edges_in, power=1, num_samples=1):
# expectation_val = 0
# for i in range(num_samples):
# random_circ = TwoLocal(num_vertices, 'ry', 'cx', 'linear',
# parameter_prefix='theta', reps=1)
# param_dict = {}
# for param in random_circ.ordered_parameters:
# param_dict[param] = np.random.rand()*2*np.pi
# random_circ = random_circ.bind_parameters(param_dict)
# expectation_run = expectation_of_laplacian(num_vertices=num_vertices, edges_in=edges_in,
# vec_in_circ=random_circ,
# power=power, backend_name="statevector_simulator")
# expectation_val += expectation_run
# expectation_val = expectation_val/num_samples
# return expectation_val
def expectation_over_random_hadamard_vecs(num_vertices, edges_in, powers=[1], num_samples=10, noise = [0.001,0.1], expt_name= None, gpu = True):
# expectation_val = 0
expectation_matrix = np.zeros((num_samples,
int(len(powers)),
num_vertices-1))
for sample in range(num_samples):
random_circ = QuantumCircuit(num_vertices)
count_h = 0
for i in range(num_vertices):
if (np.random.rand() < 0.5):
count_h+=1
random_circ.x(i)
if count_h == 0:
random_circ.x(np.random.randint(0,num_vertices))
for i in range(num_vertices):
random_circ.h(i)
for power_index, power in enumerate(powers):
if expt_name is not None:
job_name = expt_name+"degree"+str(power_index)+"sample"+str(sample)
if gpu:
b_name = "qasm_simulator"
else:
b_name = "ibmq_qasm_simulator"
temp = expectation_of_laplacian(num_vertices=num_vertices,
edges_in=edges_in,
vec_in_circ=random_circ,
power=power,
mid_circuit=True,
backend_name=b_name, noise = noise, job_name = job_name, gpu = gpu)
if isinstance(temp[0], str):
continue
else:
expectation_matrix[sample, power_index, :] = temp
else:
expectation_matrix[sample, power_index, :] = \
expectation_of_laplacian(num_vertices=num_vertices,
edges_in=edges_in,
vec_in_circ=random_circ,
power=power,
mid_circuit=True,
backend_name="qasm_simulator", noise = noise)
return expectation_matrix
def help_setting_laplacian_arguments(num_vertices=4, mid_circuit=True, do_rccx=True, sqrt=True, num_resets=None, backend_name=None, make_edges_in=10, make_vec_in_circ=5, noise_lvl=None, shots=1000):
if make_edges_in == 0:
edges_in, min_num_vert, edges_in_type = [], 2, "noedge"
elif make_edges_in == 1:
edges_in, min_num_vert, edges_in_type = [[0,1]], 2, "edge"
elif make_edges_in == 2:
edges_in, min_num_vert = one_skeleton_triangle()
edges_in_type = "triangle"
elif make_edges_in == 3:
edges_in, min_num_vert = one_skeleton_square()
edges_in_type = "square"
elif make_edges_in == 4:
edges_in, min_num_vert = one_skeleton_tetrahedron()
edges_in_type = "tetrahedron"
elif make_edges_in == 5:
edges_in, min_num_vert = one_skeleton_square_with_diagonal()
edges_in_type = "square_diag"
elif make_edges_in == 6:
edges_in, min_num_vert = one_skeleton_pyramid()
edges_in_type = "pyramid"
elif make_edges_in == 7:
edges_in, min_num_vert = one_skeleton_unfilled_cube()
edges_in_type = "cube"
elif make_edges_in == 8:
edges_in, min_num_vert = one_skeleton_n_disconnected_squares(num_vertices)
edges_in_type = "disconnected_squares"
elif make_edges_in == 9:
one_skel, _ = one_skeleton_fully_connected(num_vertices)
edges_in = one_skel[:len(one_skel)//2]
min_num_vert = num_vertices
edges_in_type = "half_all_edges"
elif make_edges_in == 10:
one_skel, _ = one_skeleton_fully_connected(num_vertices//2)
edges_in = one_skel + (np.array(one_skel) + [[num_vertices//2, num_vertices//2]]).tolist()
min_num_vert = num_vertices
edges_in_type = "two_fully_connected_clusters"
else:
raise ValueError("Unknown option for 'make_edges_in': ", make_edges_in)
if min_num_vert > num_vertices:
raise ValueError("Need more vertices than requested: " +
str(min_num_vert) + " > " + str(num_vertices))
if make_vec_in_circ == 1:
vec_in_circ = QuantumCircuit(num_vertices)
for i in range(num_vertices):
if (np.random.rand() < 0.5):
vec_in_circ.x(i)
for i in range(num_vertices):
vec_in_circ.h(i)
print(vec_in_circ._data)
vec_in_circ_type = "random_vec"
elif make_vec_in_circ == 2:
vec_in_circ = QuantumCircuit(num_vertices)
vec_in_circ.x(0)
vec_in_circ.x(1)
vec_in_circ_type = "edge_only_vec"
elif make_vec_in_circ == 3:
vec_in_circ = None
vec_in_circ_type = "uniform_vec"
elif make_vec_in_circ == 4:
vec_in_circ = QuantumCircuit(num_vertices)
vec_in_circ.x(0)
vec_in_circ.h(1)
vec_in_circ.cx(1, 0)
vec_in_circ_type = "two_vertices_vec"
elif make_vec_in_circ == 5:
vec_in_circ = QuantumCircuit(num_vertices)
vec_in_circ.x(0)
for i in range(num_vertices):
vec_in_circ.h(i)
vec_in_circ_type = "fixed_rademacher"
else:
raise ValueError("Unknown option for 'make_vec_in_circ': ", make_vec_in_circ)
if noise_lvl == 0:
noise = None
elif noise_lvl == 1:
noise = [0.0001, 0.001]
elif noise_lvl == 2:
noise = [0.001, 0.01]
elif noise_lvl == 3:
noise = [0.01, 0.1]
elif noise_lvl == 4:
noise = [10**(-5), 10**(-4)]
elif noise_lvl == 5:
noise = [10**(-4), 0.001]
elif noise_lvl == 6:
noise = [0.0002, 0.002]
elif noise_lvl == 7:
noise = [0.0005, 0.005]
elif noise_lvl == 8:
noise = [0.001, 0.01]
else:
raise ValueError("Unknown option for 'noise_lvl': ", noise_lvl)
job_name = ((backend_name + "_" if backend_name is not None else "")
+ edges_in_type + "_"
+ "vert_" + str(num_vertices) + "_"
+ "mid_circ_" + str(mid_circuit) + "_"
+ "sqrt_" + str(sqrt) + "_"
+ (("r_" + str(num_resets) +
"_") if mid_circuit and num_resets is not None else "")
+ vec_in_circ_type + "_"
+ ("rccx_" if do_rccx else
"ccx_")
+ (str(noise[0])+"_"+str(noise[1]) + "_"
if noise is not None else
"no_noise_")
+ "shots_" + ("*" if shots is None else str(shots)))
return edges_in, min_num_vert, edges_in_type, vec_in_circ, vec_in_circ_type, noise, job_name
##########################################################################
def compare_counts_hellinger(counts1, counts2):
if isinstance(counts1, str):
counts1 = json.load(open(counts1, "r"))
elif not isinstance(counts1, dict):
raise ValueError("Argument must be filename string or counts dictionary.")
if isinstance(counts2, str):
counts2 = json.load(open(counts2, "r"))
elif not isinstance(counts2, dict):
raise ValueError("Argument must be filename string or counts dictionary.")
total1 = sum(counts1.values())
total2 = sum(counts2.values())
all_keys = set(list(counts1.keys()) + list(counts2.keys()))
hellinger = 0
for key in all_keys:
hellinger += (np.sqrt(counts1.get(key, 0)/total1) - np.sqrt(counts2.get(key, 0)/total2))**2
hellinger /= 2
return hellinger
def compare_counts(counts1, counts2, interpret_counts_as_integers=False, wrap_at=0, kl_frac=True):
if isinstance(counts1, str):
counts1 = json.load(open(counts1, "r"))
elif not isinstance(counts1, dict):
raise ValueError("Argument must be filename string or counts dictionary.")
if isinstance(counts2, str):
counts2 = json.load(open(counts2, "r"))
elif not isinstance(counts2, dict):
raise ValueError("Argument must be filename string or counts dictionary.")
total1 = sum(counts1.values())
total2 = sum(counts2.values())
matching_counts = []
if interpret_counts_as_integers:
counts1_list_of_reg_strings = list(map(lambda count: count.split(), counts1.keys()))
counts1keys = list(map(bin_string2int, counts1_list_of_reg_strings))
counts1values = list(counts1.values())
counts2_list_of_reg_strings = list(map(lambda count: count.split(), counts2.keys()))
counts2keys = np.array(list(map(bin_string2int, counts2_list_of_reg_strings)))
# if bug_fix_ancilla:
# counts2keys = np.delete(counts2keys, -2, axis=1)
# # uneccessarily long for noise, but saves me from calc lookup
num_vertices_2 = len(counts2_list_of_reg_strings[0][-1])
counts2values = list(counts2.values())
for place_in_counts1, integer_list_key_in_counts1 in enumerate(counts1keys):
if wrap_at:
source_keys_count_reg = (integer_list_key_in_counts1[0] +
np.arange(0, num_vertices_2, wrap_at)).reshape(-1,1)
num_source = source_keys_count_reg.shape[0]
remaining_regs = integer_list_key_in_counts1[1:]
num_remaining = len(remaining_regs)
group_keys = np.concatenate((source_keys_count_reg,
np.broadcast_to(remaining_regs,
(num_source, num_remaining))),
axis=1).tolist()
else:
group_keys = [integer_list_key_in_counts1]
accumulate_counts = 0
for integer_list_key_in_group in group_keys:
look_for_key = np.all(counts2keys == integer_list_key_in_group, axis=1)
place_in_counts2 = np.where(look_for_key)[0]
if place_in_counts2.size > 0:
accumulate_counts += counts2values[place_in_counts2[0]]
if accumulate_counts == 0:
print("KL: to infinity and beyond!")
return np.inf
matching_counts.append((counts1values[place_in_counts1],
accumulate_counts))
else:
for i in counts1.keys():
count2 = counts2.get(i)
if count2 is None:
print("KL: to infinity and beyond!")
return np.inf
matching_counts.append((counts1[i], count2))
matching_counts = np.array(matching_counts)
kl_div = sum(rel_entr(matching_counts[:, 0]/total1, matching_counts[:, 1]/total2))
if kl_frac:
num_qubits = sum(map(len, next(iter(counts2)).split()))
entropy_counts1 = sum(entr(matching_counts[:, 0]/total1))
kl_div = kl_div/(num_qubits*np.log(2)-entropy_counts1)
print("KL Fraction: ", kl_div)
return kl_div
else:
print("KL: ", kl_div)
return kl_div
def merge_counts(dict_or_filenames_list, clip_val=None, keep_keys=None, template=None, salt_rest=False):
merged_dict = {}
if len(dict_or_filenames_list) == 0:
ValueError("Argument must be filename string or counts dictionary list.")
for counts_dict in dict_or_filenames_list:
if isinstance(counts_dict, str):
counts_dict = json.load(open(counts_dict, "r"))
elif not isinstance(counts_dict, dict):
raise ValueError("Argument must be filename string or counts dictionary list.")
if template is not None:
template = template[::-1]
fixed_counts_dict = {}
num_registers = len(template)
expected_key_len = sum(template)
for key in counts_dict:
# if key =='1':
# pdb.set_trace()
actual_key_len = len(key)
padded_key = '0'*(expected_key_len - actual_key_len) + key
start_index = 0
end_index = template[0]
# Reverse
# start_index = -template[0]
# end_index = expected_key_len
new_key = ''
for i in range(num_registers):
new_key = padded_key[start_index:end_index] + new_key
if i < num_registers-1:
new_key = ' ' + new_key
start_index = end_index
end_index = end_index + template[i+1]
# Reverse
# end_index = start_index
# start_index = start_index - template[i+1]
fixed_counts_dict[new_key] = counts_dict[key]
counts_dict = fixed_counts_dict
for key in counts_dict: # actually don't need to run if only one dict
old_val = merged_dict.get(key, 0)
merged_dict[key] = old_val + counts_dict[key]
normalize_count = sum(list(merged_dict.values()))
if keep_keys is not None:
new_dict = {}
for key in keep_keys:
old_val = merged_dict.get(key, 0)
if old_val > 0:
new_dict[key] = old_val
else:
new_dict = merged_dict
if clip_val is not None:
new_dict_2 = {}
# normalize_count = 0
for key in new_dict:
old_val = new_dict.get(key)
# normalize_count += old_val
if old_val > clip_val:
new_dict_2[key] = old_val
# del merged_dict[key] -> problem in for loop
new_dict = new_dict_2
if (keep_keys or clip_val):
new_dict['rest' + (secrets.token_urlsafe(8) if salt_rest else "")] = normalize_count-sum(new_dict.values())
# new_dict[key] = int((new_dict.get(key)/normalize_count)*10**6)
# new_dict['rest'] = int(10**6-sum(new_dict.values()))
return new_dict
def load_merge_compare(list1, list2, interpret_counts_as_integers=True, wrap_at=0, kl_frac=True):
list1_counts = merge_counts(list1)
list1_counts_num_shots = sum(list1_counts.values())
list2_counts = merge_counts(list2)
list2_counts_num_shots = sum(list2_counts.values())
print("List 1 counts:", list1_counts_num_shots)
print("List 2 counts:", list2_counts_num_shots)
kl = compare_counts(list1_counts, list2_counts,
interpret_counts_as_integers=interpret_counts_as_integers,
wrap_at=wrap_at, kl_frac=kl_frac)
return kl
def expectation_of_laplacian_json(filename, num_vertices, power=1, mid_circuit=True, sqrt=True, num_resets=None,
do_rccx=True ):
laplacian = Projected_Laplacian(num_vertices=num_vertices, edges_in=[], power=power,
mid_circuit=mid_circuit, sqrt=sqrt, num_resets=num_resets,
do_rccx=do_rccx)
template = [laplacian._count_bits_per_projection]*laplacian._num_split_projections + [laplacian._num_pairs]*laplacian._num_complex_projections + [num_vertices]
counts = merge_counts([filename], clip_val=None, keep_keys=None, template=template)
frac_counts = np.array(get_fraction_count_for_all_k(counts, laplacian, sqrt))
expectation_laplacian = frac_counts if sqrt else np.sqrt(frac_counts)
return expectation_laplacian
def calc_circuit_depths(*, log_num_vertices_start=1, log_num_vertices_end=6, power=1, mid_circuit=False, sqrt=True, do_rccx=True, num_resets=None, backend_name_or_Fake="statevector_simulator"):
# ibmq_qasm_simulator ibmq_armonk ibmq_montreal ibmq_toronto ibmq_santiago ibmq_bogota ibmq_manhattan ibmq_casablanca ibmq_sydney ibmq_mumbai ibmq_lima ibmq_belem ibmq_quito ibmq_guadalupe ibmq_brooklyn ibmq_jakarta ibmq_manila ibm_hanoi ibm_lagos ibm_cairo
# https://github.com/Qiskit/qiskit-terra/tree/795e845bd83deda54c527bb3d750df00d9d03431/qiskit/test/mock/backends
# properties = backend.properties()
# coupling_map = backend.configuration().coupling_map
# simulator = Aer.get_backend('qasm_simulator')
depths = []
backend = None
honeywell=False
if backend_name_or_Fake == "ionq_simulator":
from qiskit_ionq import IonQProvider
provider = IonQProvider()
# backend = provider.get_backend("ionq_simulator")
# provider = IonQProvider("YKI565sxYHK1Pe3w4mRRHOQ6EvhbGXeF")
# print(provider.backends())
# backend = provider.get_backend("ionq_qpu")
elif backend_name_or_Fake in ['HQS-LT-S2-APIVAL', 'HQS-LT-S2-SIM', 'HQS-LT-S1-SIM', 'HQS-LT-S1-APIVAL', 'H1-2E',
'H1-1E']:
Honeywell.load_account()
# backends = Honeywell.backends()
backend = Honeywell.get_backend(backend_name_or_Fake)
honeywell=True
elif backend_name_or_Fake == "statevector_simulator" or \
backend_name_or_Fake == "qasm_simulator":
backend = BasicAer.get_backend(backend_name_or_Fake)
elif backend_name_or_Fake.__class__.__bases__[0] is fake_pulse_backend.FakePulseBackend:
backend = backend_name_or_Fake
else:
raise(ValueError("Error: backend_name_or_Fake not sim string or FakeBackend."))
# exec("from qiskit.test.mock import " + backend_name)
# # Security risk!
# exec("backend = " + backend_name + "()")
# pass # Wow, weird error if leave out
for log_num in range(log_num_vertices_start, log_num_vertices_end):
num_vertices = 1 << log_num
vec_circ = QuantumCircuit(num_vertices)
for i in range(num_vertices//2):
vec_circ.x(i)
for i in range(num_vertices):
vec_circ.h(i)
vec_circ_inst = vec_circ.to_instruction()
vec_circ_inverse_inst = \
vec_circ.copy().inverse().to_instruction()
one_skel, _ = one_skeleton_fully_connected(num_vertices)
half_one_skel = one_skel[:len(one_skel)//2]
laplacian = Projected_Laplacian(num_vertices=num_vertices, edges_in=half_one_skel, power=power,
mid_circuit=mid_circuit, sqrt=sqrt, num_resets=num_resets,
do_rccx=do_rccx)
q_main_reg = laplacian._main_qreg
num_main_qubits = laplacian._num_main_qubits
num_pairs = laplacian._num_pairs
num_total_qubits = laplacian._num_total_qubits
# CIRCUIT CONSTRUCTION
laplacian.append(vec_circ_inst, qargs=q_main_reg)
laplacian.power(power) # already taking into account sqrt (during _init_)
if not sqrt: # here and below could use laplacian._sqrt to emphasise laplacian, chose not to since did assign local variables to other laplcian variables
laplacian.append(vec_circ_inverse_inst, qargs=q_main_reg)
# print_unitary_and_trace(laplacian)
if backend_name_or_Fake != 'statevector_simulator': #may need to check for ibmq statevector_simulator
laplacian.measure_all_qregs()
unrolled_laplacian = transpile(laplacian, backend=backend,
seed_transpiler=11,
optimization_level=0)
print(unrolled_laplacian.count_ops())
unrolled_depth = unrolled_laplacian.depth()
print("width: ", unrolled_laplacian.width(), "depth: ", unrolled_depth)
print("Laplacian Optimized:")
optimized_laplacian = transpile(laplacian, backend=backend,
seed_transpiler=11, optimization_level=3)
print(optimized_laplacian.count_ops())
optimized_depth = optimized_laplacian.depth()
print("width: ", optimized_laplacian.width(), "depth: ", optimized_depth)
# if honeywell:
# job = execute(unrolled_laplacian, backend)
# print("HQC: ", job.__dict__)#job._experiment_results)#[0]['cost'])
depths.append((num_vertices, unrolled_depth, optimized_depth))
return depths
def produce_depths_plot(do_rccx=True):
import matplotlib.pyplot as plot
# depths_False_True = np.array(calc_circuit_depths(mid_circuit=False,
# sqrt=True, do_rccx=do_rccx))
depths_True_True = np.array(calc_circuit_depths(log_num_vertices_end=8, mid_circuit=True,
sqrt=True, do_rccx=do_rccx, power=3,
backend_name_or_Fake="qasm_simulator"))
# depths_True_True_Honeywell2 = np.array(calc_circuit_depths(log_num_vertices_end=4, mid_circuit=True,
# sqrt=True, do_rccx=do_rccx,
# backend_name_or_Fake='H1-2E'))
depths_True_True_Honeywell1 = np.array(calc_circuit_depths(log_num_vertices_end=4, mid_circuit=True,
sqrt=True, do_rccx=do_rccx, power=3,
backend_name_or_Fake='H1-1E'))
# backend_name_or_Fake="HQS-LT-S1-APIVAL"))
# from qiskit.test.mock import FakeManhattan
# fake_backend = FakeManhattan()
# depths_True_True_fake = \
# np.array(calc_circuit_depths(mid_circuit=True,
# sqrt=True, do_rccx=do_rccx,
# backend_name_or_Fake=fake_backend))
# depths_True_True_IonQ = np.array(calc_circuit_depths(mid_circuit=True,
# sqrt=True, do_rccx=do_rccx,
# backend_name_or_Fake="ionq_simulator"))
# mycolors = ('green', 'blue', 'orange', 'red')
# mycirc_names = ('Statevector Simulation', 'Mid-circuit QASM all-to-all connectivity', 'Mid-circuit IonQ all-to-all connectivity', 'Mid-circuit IBM hardware connectivity')
# circuits = [depths_False_True, depths_True_True, depths_True_True_IonQ,
# depths_True_True_fake]
# mycolors = ('blue', 'magenta')
mycolors = ("#0c276c", "#7b1547")
mydarkcolors = ("#648fff", "#dc006c")
mycirc_names = ('QASM all-to-all connectivity', 'Ion-trap')
circuits = [depths_True_True, depths_True_True_Honeywell1]
fig, ax = plot.subplots()
ax.set_title("Depth vs Num Vertices")
ax.set_xlabel("Number of Vertices")
ax.set_ylabel("Depth")
for i, depths in enumerate(circuits):
print("Depths: ", depths)
ax.plot(depths[:, 0], depths[:, 1], label="Non-optimized " + mycirc_names[i], color=mycolors[i])
ax.plot(depths[:, 0], depths[:, 2], label="Optimized " + mycirc_names[i],
color=mydarkcolors[i])#'dark'+mycolors[i])
ax.legend()
plot.show()
# plot.savefig("../output/circuit_depth_vs_vertices_with_honeywell" + ("rccx" if do_rccx else "ccx") + ".png")
def honeywell_save_account_and_info():
Honeywell.save_account('lhoresh@us.ibm.com')
Honeywell.load_account()
# backend = Honeywell.get_backend('HQS-LT-S1-APIVAL')
# backend = Honeywell.get_backend('HQS-LT-S2-APIVAL')
backends = Honeywell.backends()
print("Backends: ", backends)
# for backend in honey_backends:
# # backend = Honeywell.get_backend(backend_name)
# print(backend._configuration.n_qubits)
# raise(ValueError("Stop, but keep interpreter."))
# backend = Honeywell.get_backend('HQS-LT-S1-APIVAL')
# backend = Honeywell.get_backend('HQS-LT-S2-APIVAL')
def honeywell_retrieve_counts(backend_name, job_honey_id):
Honeywell.load_account()
backend = Honeywell.get_backend(backend_name)
job = backend.retrieve_job(job_honey_id)
result = job.result()
counts = result.get_counts()
print(counts)
json.dump(counts, open('../output/' + job_honey_id + '.json', 'w'))
edge_2_qasm = \
"../output/qasm_simulator_edge_2_True_True_r_None_uniform_vec_rccx_*.json"
# wQwZaMMxCsc.json"
square_4_qasm = \
"../output/qasm_simulator_square_4_True_True_r_None_uniform_vec_rccx_*.json"
# Oo7V2RA5lHI.json"
cube_8_qasm = \
"../output/qasm_simulator_cube_8_True_True_r_None_uniform_vec_rccx_2Wh8W7eFp9k.json"
#_*.json" #DB7w1fJK6e4.json"
edge_2_honeywell = \
"../output/32f5839d79674998aa80c261dfe8a1bb.json"
square_4_honeywell = \
"../output/c90c48da23c448dc97f6054bd9d45cee.json"
cube_8_honeywell = \
"../output/5b5a56527ed24073aab10011699e493d.json"
if __name__ == '__main__':
# depths = calc_circuit_depths(log_num_vertices_start=3, log_num_vertices_end=3, power=1, mid_circuit=True, backend_name_or_Fake='qasm_simulator')
# print("Depths: ", depths)
# raise(ValueError("Stop, but keep interpreter."))
# depths = calc_circuit_depths(log_num_vertices_end=4, mid_circuit=True, backend_name_or_Fake='HQS-LT-S1-APIVAL')
# print("Depths: ", depths)
# raise(ValueError("Stop, but keep interpreter."))
#####################################
# Depth plots
#####################################
honeywell_save_account_and_info()
produce_depths_plot(do_rccx=True)
# raise ValueError("Exiting, but keeping interpreter.")
#####################################
# Unit test all
#####################################
# import unittest
# unittest.main(module='test.test_quantum_homology_advanced')
#####################################
# Unit test specific
#####################################
# import test.test_quantum_homology_advanced
# mylaplace = test.test_quantum_homology_advanced.Expectation_of_Laplacian_TestCase()
# mylaplace.setUp()
# mylaplace.test_expectation_01() # (backend="ionq_qpu")
# mylaplace.test_expectation_02() # (backend="ionq_qpu")
# mylaplace.test_expectation_03() # (backend="ionq_qpu")
# mylaplace.test_expectation_04() # (backend="ionq_qpu")
# mylaplace.test_expectation_05() # (backend="ionq_qpu")
# # mylaplace.test_expectation_05()
# mylaplace.test_run_random()
# raise(ValueError("Stop, but keep interpreter."))
# honeywell_save_account_and_info()
# honeywell_retrieve_counts('HQS-LT-S2', 'c90c48da23c448dc97f6054bd9d45cee')
# honeywell_retrieve_counts('HQS-LT-S2', '5b5a56527ed24073aab10011699e493d')
pass
# job.result()
# Result(backend_name='ionq_qpu', backend_version='0.0.1', qobj_id='None', job_id='5286dc3f-fdbd-4a6b-8231-af79375e143d', success=True, results=[ExperimentResult(shots=100, success=True, meas_level=2, data=ExperimentResultData(counts={'0x1': 1, '0x2': 4, '0x4': 2, '0x5': 44, '0x6': 38, '0x7': 1, '0xd': 4, '0xe': 1, '0xf': 2, '0x14': 1, '0x16': 2}, probabilities={'0x1': 0.01, '0x2': 0.04, '0x4': 0.02, '0x5': 0.44, '0x6': 0.38, '0x7': 0.01, '0xd': 0.04, '0xe': 0.01, '0xf': 0.02, '0x14': 0.01, '0x16': 0.02}), header=QobjExperimentHeader(memory_slots=5, global_phase=2.356194490192344, n_qubits=6, name='circuit-16', creg_sizes=[['c0', 2], ['power1complexcproj0', 1], ['power1complexcproj1', 1], ['power1splitcproj0', 1]], clbit_labels=[['c0', 0], ['c0', 1], ['power1complexcproj0', 0], ['power1complexcproj1', 0], ['power1splitcproj0', 0]], qreg_sizes=[['mainqreg', 2], ['clean_ancillae', 1], ['power1complexqproj0', 1], ['power1complexqproj1', 1], ['power1splitqproj0', 1]], qubit_labels=[['mainqreg', 0], ['mainqreg', 1], ['clean_ancillae', 0], ['power1complexqproj0', 0], ['power1complexqproj1', 0], ['power1splitqproj0', 0]]))], time_taken=2.579)
|
https://github.com/Shashankaubaru/NISQ-TDA
|
Shashankaubaru
|
import qiskit
from qiskit import IBMQ
from qiskit.providers.aer import AerSimulator
import qiskit.providers.aer.noise as qnoise
# Generate 3-qubit GHZ state
circ = qiskit.QuantumCircuit(3)
circ.h(0)
circ.cx(0, 1)
circ.cx(1, 2)
circ.measure_all()
# Construct an ideal simulator
aersim = AerSimulator()
# Perform an ideal simulation
result_ideal = qiskit.execute(circ, aersim).result()
counts_ideal = result_ideal.get_counts(0)
print('Counts(ideal):', counts_ideal)
# Counts(ideal): {'000': 493, '111': 531}
# Construct a noisy simulator backend from an IBMQ backend
# This simulator backend will be automatically configured
# using the device configuration and noise model
# provider = IBMQ.load_account()
# backend = provider.get_backend('ibmq_athens')
# aersim_backend = AerSimulator.from_backend(backend)
noise = [0.00001, 0.0001]
gpu = True
# Error probabilities
prob_1 = noise[0] # 1-qubit gate
prob_2 = noise[1] # 2-qubit gate
prob_mat = [[1-prob_2,prob_2],[prob_2,1-prob_2]]
# Depolarizing quantum errors
error_1 = qnoise.depolarizing_error(prob_1, 1)
error_2 = qnoise.depolarizing_error(prob_2, 2)
read_err = qnoise.ReadoutError(prob_mat)
# Add errors to noise model
noise_model = qnoise.NoiseModel()
noise_model.add_all_qubit_quantum_error(error_1, ['u1', 'u2', 'u3'])
noise_model.add_all_qubit_quantum_error(error_2, ['cx'])
noise_model.add_all_qubit_readout_error(read_err)
# Get basis gates from noise model
basis_gates = noise_model.basis_gates
if gpu:
# backend = Aer.get_backend('aer_simulator_statevector_gpu')
if noise is not None:
backend = AerSimulator(device="GPU", noise_model = noise_model, basis_gates= basis_gates,
batched_shots_gpu_max_qubits = 32)
else:
backend = AerSimulator(device="GPU", batched_shots_gpu_max_qubits = 32)
else:
# Perform noisy simulation
if noise is not None:
backend = AerSimulator(device="CPU", noise_model = noise_model, basis_gates= basis_gates)
else:
backend = AerSimulator(device="CPU")
result_noise = qiskit.execute(circ, backend).result()
counts_noise = result_noise.get_counts(0)
print('Counts(noise):', counts_noise)
|
https://github.com/EavCmr/QKD-E91
|
EavCmr
|
#!pip install qiskit
from qiskit import QuantumCircuit, Aer, transpile, assemble, execute, IBMQ
from qiskit.visualization import plot_histogram
import numpy as np
import random
import math
import warnings
warnings.filterwarnings('ignore')
# Determine the amount of entanglement between these bits using the CHSH value
def entanglement_amount(alice_choices, alice_bits, bob_choices, bob_bits):
# count the different measurement results
# rows correspond to Alice and Bob's circuit choices: 00, 02, 20, 22
# NOTE: We do not consider circuits 1 or 3 for this test
# columns correspond to Alice and Bob's qubit measurements: 00, 01, 10, and 11
circuits = {'00': 0, '02': 1, '20': 2, '22': 3}
counts = [[0]*4 for i in range(4)]
for i in range(len(alice_choices)):
circuit = str(alice_choices[i]) + str(bob_choices[i])
state = int(alice_bits[i]) + 2*int(bob_bits[i])
if circuit in circuits: counts[circuits[circuit]][state] += 1
# expectation values calculated by
# adding times Alice and Bob's bits agreed and
# subtracting times Alice and Bob's bits disagreed
expectations = []
for circuit in range(4):
expectations += [counts[circuit][0] + counts[circuit][3] - counts[circuit][1] - counts[circuit][2]]
total = sum(counts[circuit])
if total != 0: expectations[circuit] /= total
# returning CHSH correlation
return expectations[0] - expectations[1] + expectations[2] + expectations[3]
print("Libraries Imported Successfully!")
alice_bob_qubits = QuantumCircuit(2, 2)
alice_bob_qubits.# COMPLETE THIS CODE
alice_bob_qubits.# COMPLETE THIS CODE
alice_bob_qubits.# COMPLETE THIS CODE
alice_bob_qubits.# COMPLETE THIS CODE
alice_bob_qubits.draw()
alice_option_1 = QuantumCircuit(1, 1)
alice_option_1.h(0)
alice_option_1.measure(0, 0)
alice_option_2 = QuantumCircuit(1, 1)
alice_option_2.rz(math.pi# COMPLETE THIS LINE
alice_option_2.h(0)
alice_option_2.measure(0, 0)
alice_option_3 = QuantumCircuit(1, 1)
alice_option_3.# COMPLETE THIS LINE
alice_alice_option_3.h(0)
alice_option_3.measure(0, 0)
alice_options = [alice_option_1, # COMPLETE THIS LINE WITH THE OTHER OPTIONS
alice_choice = random.randint(0, 2)
alice_circuit = options[alice_choice]
alice_circuit.draw()
alice_bob_qubits = alice_bob_qubits.compose(alice_circuit, qubits = 0, clbits = 0)
alice_bob_qubits.draw()
bob_option_1 = QuantumCircuit(1, 1)
bob_option_1.# COMPLETE THIS LINE
bob_option_1.# COMPLETE THIS LINE
bob_option_1.measure(0, 0)
bob_option_2 # COMPLETE THIS CODE
bob_option_3 # COMPLETE THIS CODE
bob_options = # COMPLETE THIS LINE
bob_choice = random.randint(0, 2)
bob_circuit = options[bob_choice]
bob_circuit.draw()
alice_bob_qubits = alice_bob_qubits.compose(bob_circuit, qubits = 1, clbits = 1)
alice_bob_qubits.draw()
backend = Aer.get_backend('qasm_simulator')
job = execute(alice_bob_qubits, backend = backend, shots = 1024)
result = job.result()
counts = result.get_counts()
bits = random.choices(list(counts.keys()), weights = counts.values(), k = 1)[0]
alice_bits = bits[0]
bob_bits = bits[1]
plot_histogram(counts)
alice_key = []
alice_mismatched_choices = []
alice_mismatched_choice_bits = []
bob_key = []
bob_mismatched_choices = []
bob_mismatched_choice_bits = []
# MATCHING CHOICE
if alice_options[alice_choice] == bob_options[bob_choice]:
alice_key += [int(alice_bits[0])]
bob_key += [1 - int(bob_bits[0])]
# MISMATCHING CHOICE
else:
alice_mismatched_choices += [alice_choice]
bob_mismatched_choices += [bob_choice]
alice_mismatched_choice_bits += [alice_bits[0]]
bob_mismatched_choice_bits += [bob_bits[0]]
entanglement = entanglement_amount(alice_mismatched_choices, alice_mismatched_choice_bits, bob_mismatched_choices, bob_mismatched_choice_bits)
print("Entanglement of Mismatched Choices: " + str(entanglement))
print("Alice's Key: " + str(alice_key))
print("Bob's Key: " + str(bob_key))
#========
# STEP 1
#========
alice_bob_qubits = QuantumCircuit(2, 2)
# COMPLETE THIS CODE
#========
# STEP 2
#========
alice_choice = random.randint(0, 2)
alice_circuit = # COMPLETE THIS LINE
#========
# STEP 3
#========
alice_bob_qubits = alice_bob_qubits.compose(# COMPLETE THIS LINE
#========
# STEP 4
#========
bob_choice = random.randint(0, 2)
bob_circuit = # COMPLETE THIS LINE
#========
# STEP 5
#========
alice_bob_qubits = alice_bob_qubits.compose(# COMPLETE THIS LINE
#======================
# SIMULATE THE CIRCUIT
#======================
backend = Aer.get_backend('qasm_simulator')
job = execute(alice_bob_qubits, backend = backend, shots = 1024)
result = job.result()
counts = result.get_counts()
bits = random.choices(list(counts.keys()), weights = counts.values(), k = 1)[0]
alice_bits = bits[0]
bob_bits = bits[1]
plot_histogram(counts)
#========
# STEP 6
#========
alice_key = []
alice_mismatched_choices = []
alice_mismatched_choice_bits = []
bob_key = []
bob_mismatched_choices = []
bob_mismatched_choice_bits = []
# MATCHING CHOICE
if alice_options[alice_choice] == bob_options[bob_choice]:
alice_key += [int(# COMPLETE THIS LINE
bob_key += [1 - int(# COMPLETE THIS LINE
# MISMATCHING CHOICE
else:
alice_mismatched_choices += [# COMPLETE THIS LINE
bob_mismatched_choices += [# COMPLETE THIS LINE
alice_mismatched_choice_bits += [# COMPLETE THIS LINE
bob_mismatched_choice_bits += [# COMPLETE THIS LINE
entanglement = entanglement_amount(alice_mismatched_choices, alice_mismatched_choice_bits, bob_mismatched_choices, bob_mismatched_choice_bits)
print("Entanglement of Mismatched Choices: " + str(entanglement))
print("Alice's Key: " + str(alice_key))
print("Bob's Key: " + str(bob_key))
n = 100
alice_bob_qubits = []
for i in range(# COMPLETE THIS LINE
alice_bob_qubits += [QuantumCircuit(# COMPLETE THIS LINE
alice_bob_qubits[i].# COMPLETE THIS LINE
alice_bob_qubits[i].# COMPLETE THIS LINE
alice_bob_qubits[i].# COMPLETE THIS LINE
alice_bob_qubits[i].# COMPLETE THIS LINE
alice_choices = []
alice_circuits = []
for # COMPLETE THIS LINE
alice_choices += [random.randint(0, 2)]
alice_circuits += [# COMPLETE THIS LINE
# COMPLETE THIS LINE
alice_bob_qubits[i] = alice_bob_qubits[i].compose(# COMPLETE THIS LINE
# COMPLETE THIS CODE
# COMPLETE THIS CODE
backend = Aer.get_backend('qasm_simulator')
job = execute(alice_bob_qubits, backend = backend, shots = 1)
result = job.result()
counts = result.get_counts()
alice_bits = []
bob_bits = []
for i in range(n):
bits = list(counts[i].keys())[0]
alice_bits += [bits[0]]
bob_bits += [bits[1]]
alice_key = []
alice_mismatched_choices = []
alice_mismatched_choice_bits = []
bob_key = []
bob_mismatched_choices = []
bob_mismatched_choice_bits = []
for # COMPLETE THIS LINE
# MATCHING CHOICE
if alice_options[alice_choices[i]] == # COMPLETE THIS LINE
alice_key += [int(alice_bits[i])]
bob_key += [1 - int(# COMPLETE THIS LINE
# MISMATCHING CHOICE
else:
alice_mismatched_choices += [alice_choices[i]]
bob_mismatched_choices += [ # COMPLETE THIS LINE
alice_mismatched_choice_bits += [ # COMPLETE THIS LINE
bob_mismatched_choice_bits += [# COMPLETE THIS LINE
entanglement = entanglement_amount(alice_mismatched_choices, alice_mismatched_choice_bits, bob_mismatched_choices, bob_mismatched_choice_bits)
print("Entanglement of Mismatched Choices: " + str(entanglement))
print("Alice's Key: " + str(alice_key))
print("Bob's Key: " + str(bob_key))
print("Key Length: " + str(len(bob_key)))
print("Number of Disagreeing Key Bits: " + str(sum([alice_key[i] != bob_key[i] for i in range(len(alice_key))])))
#========
# STEP 1
#========
n = 100
#========
# STEP 2
#========
#========
# STEP 3
#========
#========
# STEP 4
#========
#========
# STEP 5
#========
#======================
# SIMULATE THE CIRCUIT
#======================
#========
# STEP 6
#========
#========
# STEP 1
#========
n = 100
# COMPLETE THIS CODE WITH YOUR SOLUTION FROM PART 2
#================
# EVE INTERCEPTS!
#================
for i in range(# COMPLETE THIS LINE
alice_bob_qubits[i].measure(# COMPLETE THIS LINE
backend = Aer.get_backend('qasm_simulator')
job = execute(alice_bob_qubits, backend = backend, shots = 1)
result = job.result()
counts = result.get_counts()
eve_alice_bits = []
eve_bob_bits = []
for # COMPLETE THIS LINE
# Looks at measurement results
bits = list(counts[i].keys())[0]
eve_alice_bits += [bits[0]]
eve_bob_bits += [# COMPLETE THIS LINE
# Prepares new qubits for Alice and Bob
alice_bob_qubits[i] = QuantumCircuit(# COMPLETE THIS LINE
# Makes sure they are in the same state she measured
if eve_alice_bits[i] == 1: alice_bob_qubits[i].# COMPLETE THIS LINE
if # COMPLETE THIS LINE
#========
# STEP 6
#========
alice_key = []
alice_mismatched_choices = []
alice_mismatched_choice_bits = []
bob_key = []
bob_mismatched_choices = []
bob_mismatched_choice_bits = []
eve_key = []
# COMPLETE THIS CODE
entanglement = entanglement_amount(alice_mismatched_choices, alice_mismatched_choice_bits, bob_mismatched_choices, bob_mismatched_choice_bits)
print("Entanglement of Mismatched Choices: " + str(entanglement))
print("Alice's Key: " + str(alice_key))
print("Bob's Key: " + str(bob_key))
print("Eve's Key: " + str(eve_key))
print("Key Length: " + str(len(bob_key)))
print("Number of Disagreeing Key Bits between Alice and Bob: " + str(sum([alice_key[i] != bob_key[i] for i in range(len(alice_key))])))
print("Number of Disagreeing Key Bits between Alice and Eve: " + str(sum([alice_key[i] != eve_key[i] for i in range(len(alice_key))])))
print("Number of Disagreeing Key Bits between Bob and Eve: " + str(sum([bob_key[i] != eve_key[i] for i in range(len(alice_key))])))
|
https://github.com/EavCmr/QKD-E91
|
EavCmr
|
#!pip install qiskit
from qiskit import QuantumCircuit, Aer, transpile, assemble, execute, IBMQ
from qiskit.visualization import plot_histogram
import numpy as np
import random
import math
import warnings
warnings.filterwarnings('ignore')
# Determine the amount of entanglement between these bits using the CHSH value
def entanglement_amount(alice_choices, alice_bits, bob_choices, bob_bits):
# count the different measurement results
# rows correspond to Alice and Bob's circuit choices: 00, 02, 20, 22
# NOTE: We do not consider circuits 1 or 3 for this test
# columns correspond to Alice and Bob's qubit measurements: 00, 01, 10, and 11
circuits = {'00': 0, '02': 1, '20': 2, '22': 3}
counts = [[0]*4 for i in range(4)]
for i in range(len(alice_choices)):
circuit = str(alice_choices[i]) + str(bob_choices[i])
state = int(alice_bits[i]) + 2*int(bob_bits[i])
if circuit in circuits: counts[circuits[circuit]][state] += 1
# expectation values calculated by
# adding times Alice and Bob's bits agreed and
# subtracting times Alice and Bob's bits disagreed
expectations = []
for circuit in range(4):
expectations += [counts[circuit][0] + counts[circuit][3] - counts[circuit][1] - counts[circuit][2]]
total = sum(counts[circuit])
if total != 0: expectations[circuit] /= total
# returning CHSH correlation
return expectations[0] - expectations[1] + expectations[2] + expectations[3]
print("Libraries Imported Successfully!")
alice_bob_qubits = QuantumCircuit(2, 2)
alice_bob_qubits.h(0)
alice_bob_qubits.cx(0,1)
alice_bob_qubits.x(0)
alice_bob_qubits.z(0)
alice_bob_qubits.draw()
alice_option_1 = QuantumCircuit(1, 1)
alice_option_1.rz(0,0)
alice_option_1.h(0)
alice_option_1.measure(0, 0)
alice_option_2 = QuantumCircuit(1, 1)
alice_option_2.rz(math.pi/4,0) # COMPLETE THIS LINE
alice_option_2.h(0)
alice_option_2.measure(0, 0)
alice_option_3 = QuantumCircuit(1, 1)
alice_option_3.rz(math.pi/2,0) # COMPLETE THIS LINE
alice_option_3.h(0)
alice_option_3.measure(0, 0)
alice_options = [alice_option_1,alice_option_2,alice_option_3] # COMPLETE THIS LINE WITH THE OTHER OPTIONS
alice_choice = random.randint(0, 2)
alice_circuit = alice_options[alice_choice]
alice_circuit.draw()
alice_bob_qubits = alice_bob_qubits.compose(alice_circuit, qubits = [0] , clbits = [0])
alice_bob_qubits.draw()
bob_option_1 = QuantumCircuit(1, 1)
bob_option_1.rz(math.pi/4,0)# COMPLETE THIS LINE
bob_option_1.h(0) # COMPLETE THIS LINE
bob_option_1.measure(0, 0)
bob_option_2 = QuantumCircuit(1, 1)
bob_option_2.rz(math.pi/4,0)# COMPLETE THIS LINE
bob_option_2.h(0) # COMPLETE THIS CODE
bob_option_2.measure(0, 0)
bob_option_3= QuantumCircuit(1, 1) # COMPLETE THIS CODE
bob_option_3.rz(math.pi*3/4,0)
bob_option_3.h(0)
bob_option_3.measure(0, 0)
bob_options = [bob_option_1,bob_option_2,bob_option_3]# COMPLETE THIS LINE
bob_choice = random.randint(0, 2)
bob_circuit = bob_options[bob_choice]
bob_circuit.draw()
alice_bob_qubits = alice_bob_qubits.compose(bob_circuit, qubits = [1], clbits = [1])
alice_bob_qubits.draw()
backend = Aer.get_backend('qasm_simulator')
job = execute(alice_bob_qubits, backend = backend, shots = 1024)
result = job.result()
counts = result.get_counts()
bits = random.choices(list(counts.keys()), weights = counts.values(), k = 1)[0]
alice_bits = bits[0]
bob_bits = bits[1]
plot_histogram(counts)
alice_key = []
alice_mismatched_choices = []
alice_mismatched_choice_bits = []
bob_key = []
bob_mismatched_choices = []
bob_mismatched_choice_bits = []
# MATCHING CHOICE
if alice_options[alice_choice] == bob_options[bob_choice]:
alice_key += [int(alice_bits[0])]
bob_key += [1 - int(bob_bits[0])]
# MISMATCHING CHOICE
else:
alice_mismatched_choices += [alice_choice]
bob_mismatched_choices += [bob_choice]
alice_mismatched_choice_bits += [alice_bits[0]]
bob_mismatched_choice_bits += [bob_bits[0]]
entanglement = entanglement_amount(alice_mismatched_choices, alice_mismatched_choice_bits, bob_mismatched_choices, bob_mismatched_choice_bits)
print("Entanglement of Mismatched Choices: " + str(entanglement))
print("Alice's Key: " + str(alice_key))
print("Bob's Key: " + str(bob_key))
#========
# STEP 1
#========
alice_bob_qubits = QuantumCircuit(2, 2)
alice_bob_qubits.h(0)
alice_bob_qubits.cx(0,1)
alice_bob_qubits.x(0)
alice_bob_qubits.z(0)
alice_bob_qubits.draw()
#========
# STEP 2
#========
alice_choice = random.randint(0, 2)
alice_circuit = alice_options[alice_choice]
alice_circuit.draw()
#========
# STEP 3
#========
alice_bob_qubits = alice_bob_qubits.compose(alice_circuit, qubits = [0], clbits = [0])
#========
# STEP 4
#========
bob_choice = random.randint(0, 2)
bob_circuit = bob_options[bob_choice]
#========
# STEP 5
#========
alice_bob_qubits = alice_bob_qubits.compose(bob_circuit, qubits = [1], clbits = [1])
#======================
# SIMULATE THE CIRCUIT
#======================
backend = Aer.get_backend('qasm_simulator')
job = execute(alice_bob_qubits, backend = backend, shots = 1024)
result = job.result()
counts = result.get_counts()
bits = random.choices(list(counts.keys()), weights = counts.values(), k = 1)[0]
alice_bits = bits[0]
bob_bits = bits[1]
plot_histogram(counts)
#========
# STEP 6
#========
alice_key = []
alice_mismatched_choices = []
alice_mismatched_choice_bits = []
bob_key = []
bob_mismatched_choices = []
bob_mismatched_choice_bits = []
# MATCHING CHOICE
if alice_options[alice_choice] == bob_options[bob_choice]:
alice_key += [int(alice_bits[0])]
bob_key += [1 - int(bob_bits[0])]
# MISMATCHING CHOICE
else:
alice_mismatched_choices += [alice_choice]
bob_mismatched_choices += [bob_choice]
alice_mismatched_choice_bits += [alice_bits[0]]
bob_mismatched_choice_bits += [bob_bits[0]]
entanglement = entanglement_amount(alice_mismatched_choices, alice_mismatched_choice_bits, bob_mismatched_choices, bob_mismatched_choice_bits)
print("Entanglement of Mismatched Choices: " + str(entanglement))
print("Alice's Key: " + str(alice_key))
print("Bob's Key: " + str(bob_key))
n = 100
alice_bob_qubits = []
for i in range(n):
alice_bob_qubits += [QuantumCircuit(2,2)]
alice_bob_qubits[i].h(0)
alice_bob_qubits[i].cx(0,1)
alice_bob_qubits[i].x(0)
alice_bob_qubits[i].z(0)
alice_choices = []
alice_circuits = []
for i in range(n):
alice_choices += [random.randint(0, 2)]
alice_circuits += [alice_options[alice_choices[i]]]
for i in range(100):
alice_bob_qubits[i] = alice_bob_qubits[i].compose(alice_circuit, qubits = [0] , clbits = [0])
bob_choices = []
bob_circuits = []
for i in range(n):
bob_choices += [random.randint(0, 2)]
bob_circuits += [bob_options[bob_choices[i]]]
for i in range(100):
alice_bob_qubits[i] = alice_bob_qubits[i].compose(alice_circuit, qubits = [1] , clbits = [1])
backend = Aer.get_backend('qasm_simulator')
job = execute(alice_bob_qubits, backend = backend, shots = 1)
result = job.result()
counts = result.get_counts()
alice_bits = []
bob_bits = []
for i in range(n):
bits = list(counts[i].keys())[0]
alice_bits += [bits[0]]
bob_bits += [bits[1]]
alice_key = []
alice_mismatched_choices = []
alice_mismatched_choice_bits = []
bob_key = []
bob_mismatched_choices = []
bob_mismatched_choice_bits = []
for i in range(n):
# MATCHING CHOICE
if alice_options[alice_choices[i]] == bob_options[bob_choices[i]]:
alice_key += [int(alice_bits[i])]
bob_key += [1 - int(bob_bits[i])]
# MISMATCHING CHOICE
else:
alice_mismatched_choices += [alice_choices[i]]
bob_mismatched_choices += [bob_choices[i]] # COMPLETE THIS LINE
alice_mismatched_choice_bits += [alice_bits[i]] # COMPLETE THIS LINE
bob_mismatched_choice_bits += [bob_bits[i]] # COMPLETE THIS LINE
entanglement = entanglement_amount(alice_mismatched_choices, alice_mismatched_choice_bits, bob_mismatched_choices, bob_mismatched_choice_bits)
print("Entanglement of Mismatched Choices: " + str(entanglement))
print("Alice's Key: " + str(alice_key))
print("Bob's Key: " + str(bob_key))
print("Key Length: " + str(len(bob_key)))
print("Number of Disagreeing Key Bits: " + str(sum([alice_key[i] != bob_key[i] for i in range(len(alice_key))])))
#========
# STEP 1
#========
n = 100
#========
# STEP 2
#========
alice_bob_qubits = []
for i in range(n):
alice_bob_qubits += [QuantumCircuit(2,2)]
alice_bob_qubits[i].h(0)
alice_bob_qubits[i].cx(0,1)
alice_bob_qubits[i].x(0)
alice_bob_qubits[i].z(0)
#========
# STEP 3
#========
alice_choices = []
alice_circuits = []
for i in range(n):
alice_choices += [random.randint(0, 2)]
alice_circuits += alice_options[alice_choice]
for i in range(100):
alice_bob_qubits[i] = alice_bob_qubits[i].compose(alice_circuit, qubits = [0] , clbits = [0])
#========
# STEP 4
#========
bob_choices = []
bob_circuits = []
for i in range(n):
bob_choices += [random.randint(0, 2)]
bob_circuits += bob_options[bob_choice]
#========
# STEP 5
#========
for i in range(100):
alice_bob_qubits[i] = alice_bob_qubits[i].compose(alice_circuit, qubits = [1] , clbits = [1])
#======================
# SIMULATE THE CIRCUIT
#======================
backend = Aer.get_backend('qasm_simulator')
job = execute(alice_bob_qubits, backend = backend, shots = 1)
result = job.result()
counts = result.get_counts()
alice_bits = []
bob_bits = []
for i in range(n):
bits = list(counts[i].keys())[0]
alice_bits += [bits[0]]
bob_bits += [bits[1]]
#========
# STEP 6
#========
alice_key = []
alice_mismatched_choices = []
alice_mismatched_choice_bits = []
bob_key = []
bob_mismatched_choices = []
bob_mismatched_choice_bits = []
for i in range(n):
# MATCHING CHOICE
if alice_options[alice_choices[i]] == bob_options[bob_choices[i]]:
alice_key += [int(alice_bits[i])]
bob_key += [1 - int(bob_bits[i])]
# MISMATCHING CHOICE
else:
alice_mismatched_choices += [alice_choices[i]]
bob_mismatched_choices += [bob_choices[i]]
alice_mismatched_choice_bits += [alice_bits[i]]
bob_mismatched_choice_bits += [bob_bits[i]]
entanglement = entanglement_amount(alice_mismatched_choices, alice_mismatched_choice_bits, bob_mismatched_choices, bob_mismatched_choice_bits)
print("Entanglement of Mismatched Choices: " + str(entanglement))
print("Alice's Key: " + str(alice_key))
print("Bob's Key: " + str(bob_key))
print("Key Length: " + str(len(bob_key)))
print("Number of Disagreeing Key Bits: " + str(sum([alice_key[i] != bob_key[i] for i in range(len(alice_key))])))
#========
# STEP 1
#========
n = 100
# COMPLETE THIS CODE WITH YOUR SOLUTION FROM PART 2
#================
# EVE INTERCEPTS!
#================
for i in range(n):
alice_bob_qubits[i].measure(0,0)
backend = Aer.get_backend('qasm_simulator')
job = execute(alice_bob_qubits, backend = backend, shots = 1)
result = job.result()
counts = result.get_counts()
eve_alice_bits = []
eve_bob_bits = []
for i in range(100):# COMPLETE THIS LINE
# Looks at measurement results
bits = list(counts[i].keys())[0]
eve_alice_bits += [bits[0]]
eve_bob_bits += [bits[1]]
# Prepares new qubits for Alice and Bob
alice_bob_qubits[i] = QuantumCircuit(2,2)
# Makes sure they are in the same state she measured
if eve_alice_bits[i] == 1: alice_bob_qubits[i] == 1
if eve_bob_bits[i] == 1: alice_bob_qubits[i] ==1
alice_choices = []
alice_circuits = []
for i in range(n):
alice_choices += [random.randint(0, 2)]
alice_circuits += alice_options[alice_choice]
for i in range(100):
alice_bob_qubits[i] = alice_bob_qubits[i].compose(alice_circuit, qubits = [0] , clbits = [0])
#========
# STEP 4
#========
bob_choices = []
bob_circuits = []
for i in range(n):
bob_choices += [random.randint(0, 2)]
bob_circuits += bob_options[bob_choice]
#========
# STEP 5
#========
for i in range(100):
alice_bob_qubits[i] = alice_bob_qubits[i].compose(alice_circuit, qubits = [1] , clbits = [1])
#======================
# SIMULATE THE CIRCUIT
#======================
backend = Aer.get_backend('qasm_simulator')
job = execute(alice_bob_qubits, backend = backend, shots = 1)
result = job.result()
counts = result.get_counts()
alice_bits = []
bob_bits = []
for i in range(n):
bits = list(counts[i].keys())[0]
alice_bits += [bits[0]]
bob_bits += [bits[1]]
#========
# STEP 6
#========
alice_key = []
alice_mismatched_choices = []
alice_mismatched_choice_bits = []
bob_key = []
bob_mismatched_choices = []
bob_mismatched_choice_bits = []
eve_key = []
eve_mismatched_choices = []
eve_mismatched_choice_bits = []
for i in range(n):
# MATCHING CHOICE
if alice_options[alice_choices[i]] == bob_options[bob_choices[i]]:
alice_key += [int(alice_bits[i])]
bob_key += [1 - int(bob_bits[i])]
eve_key += [int(eve_bob_bits[i])]
else:
alice_mismatched_choices += [alice_choices[i]]
bob_mismatched_choices += [bob_choices[i]]
bob_mismatched_choices += [bob_choices[i]]
alice_mismatched_choice_bits += [alice_bits[i]]
bob_mismatched_choice_bits += [bob_bits[i]]
entanglement = entanglement_amount(alice_mismatched_choices, alice_mismatched_choice_bits, bob_mismatched_choices, bob_mismatched_choice_bits)
print("Entanglement of Mismatched Choices: " + str(entanglement))
print("Alice's Key: " + str(alice_key))
print("Bob's Key: " + str(bob_key))
print("Eve's Key: " + str(eve_key))
print("Key Length: " + str(len(bob_key)))
print("Number of Disagreeing Key Bits between Alice and Bob: " + str(sum([alice_key[i] != bob_key[i] for i in range(len(alice_key))])))
print("Number of Disagreeing Key Bits between Alice and Eve: " + str(sum([alice_key[i] != eve_key[i] for i in range(len(alice_key))])))
print("Number of Disagreeing Key Bits between Bob and Eve: " + str(sum([bob_key[i] != eve_key[i] for i in range(len(alice_key))])))
n = 100
# COMPLETE THIS CODE WITH YOUR SOLUTION FROM PART 2
alice_bob_qubits = []
for i in range(n):# COMPLETE THIS LINE
alice_bob_qubits += [QuantumCircuit(2,2)]# COMPLETE THIS LINE
alice_bob_qubits[i].h(0) # COMPLETE THIS LINE
alice_bob_qubits[i].cx(0,1) # COMPLETE THIS LINE
alice_bob_qubits[i].x(0) # COMPLETE THIS LINE
alice_bob_qubits[i].z(0) # COMPLETE THIS LINE
#========
# STEP 3
#========
alice_choices = []
alice_circuits = []
for i in range(n): # COMPLETE THIS LINE
alice_choices += [random.randint(0, 2)]
alice_circuits += [alice_options[alice_choices[i]]] # COMPLETE THIS LINE
for i in range(100): # COMPLETE THIS LINE
alice_bob_qubits[i] = alice_bob_qubits[i].compose(alice_circuit, qubits = [0] , clbits = [0])# COMPLETE THIS LINE
#========
# STEP 4
#========
bob_choices = []
bob_circuits = []
for i in range(n): # COMPLETE THIS LINE
bob_choices += [random.randint(0, 2)]
bob_circuits += [bob_options[bob_choices[i]]]# COMPLETE THIS CODE
#========
# STEP 5
#========
for i in range(100):
alice_bob_qubits[i] = alice_bob_qubits[i].compose(alice_circuit, qubits = [1] , clbits = [1])# COMPLETE THIS CODE
#================
# EVE INTERCEPTS!
#================
for i in range(n):# COMPLETE THIS LINE
alice_bob_qubits[i].measure(0,0)# COMPLETE THIS LINE
backend = Aer.get_backend('qasm_simulator')
job = execute(alice_bob_qubits, backend = backend, shots = 1)
result = job.result()
counts = result.get_counts()
#================
#================
eve_alice_bits = []
eve_bob_bits = []
for i in range(100):# COMPLETE THIS LINE
# Looks at measurement results
bits = list(counts[i].keys())[0]
eve_alice_bits += [bits[0]]
eve_bob_bits += [bits[1]]# COMPLETE THIS LINE
# Prepares new qubits for Alice and Bob
alice_bob_qubits[i] = QuantumCircuit(2,2)# COMPLETE THIS LINE
# Makes sure they are in the same state she measured
if eve_alice_bits[i] == 1: alice_bob_qubits[i].measure(0,0)# COMPLETE THIS LINE
if eve_bob_bits[i] == 1: alice_bob_qubits[i].measure(0,0) # COMPLETE THIS LINE
#================
#================
alice_choices = []
alice_circuits = []
for i in range(n): # COMPLETE THIS LINE
alice_choices += [random.randint(0, 2)]
alice_circuits += [alice_options[alice_choices[i]]] # COMPLETE THIS LINE
for i in range(100): # COMPLETE THIS LINE
alice_bob_qubits[i] = alice_bob_qubits[i].compose(alice_circuit, qubits = [0] , clbits = [0])# COMPLETE THIS LINE
#========
# STEP 4
#========
bob_choices = []
bob_circuits = []
for i in range(n): # COMPLETE THIS LINE
bob_choices += [random.randint(0, 2)]
bob_circuits += [bob_options[bob_choices[i]]]# COMPLETE THIS CODE
#========
# STEP 5
#========
for i in range(100):
alice_bob_qubits[i] = alice_bob_qubits[i].compose(alice_circuit, qubits = [1] , clbits = [1])# COMPLETE THIS CODE
#======================
# SIMULATE THE CIRCUIT
#======================
backend = Aer.get_backend('qasm_simulator')
job = execute(alice_bob_qubits, backend = backend, shots = 1)
result = job.result()
counts = result.get_counts()
alice_bits = []
bob_bits = []
for i in range(n):
bits = list(counts[i].keys())[0]
alice_bits += [bits[0]]
bob_bits += [bits[1]]
#========
# STEP 6
#========
alice_key = []
alice_mismatched_choices = []
alice_mismatched_choice_bits = []
bob_key = []
bob_mismatched_choices = []
bob_mismatched_choice_bits = []
eve_key = []
eve_mismatched_choices = []
eve_mismatched_choice_bits = []
for i in range(n):# COMPLETE THIS LINE
# MATCHING CHOICE
if alice_options[alice_choices[i]] == bob_options[bob_choices[i]]: # COMPLETE THIS LINE
alice_key += [int(alice_bits[i])]
bob_key += [1 - int(bob_bits[i])]# COMPLETE THIS LINE
eve_key += [int(eve_bob_bits[i])]
# MISMATCHING CHOICE
else:
alice_mismatched_choices += [alice_choices[i]]
bob_mismatched_choices += [bob_choices[i]] # COMPLETE THIS LINE
alice_mismatched_choice_bits += [alice_bits[i]] # COMPLETE THIS LINE
bob_mismatched_choice_bits += [bob_bits[i]] # COMPLETE THIS LINE# COMPLETE THIS CODE
entanglement = entanglement_amount(alice_mismatched_choices, alice_mismatched_choice_bits, bob_mismatched_choices, bob_mismatched_choice_bits)
print("Entanglement of Mismatched Choices: " + str(entanglement))
print("Alice's Key: " + str(alice_key))
print("Bob's Key: " + str(bob_key))
print("Eve's Key: " + str(eve_key))
print("Key Length: " + str(len(bob_key)))
print("Number of Disagreeing Key Bits between Alice and Bob: " + str(sum([alice_key[i] != bob_key[i] for i in range(len(alice_key))])))
print("Number of Disagreeing Key Bits between Alice and Eve: " + str(sum([alice_key[i] != eve_key[i] for i in range(len(alice_key))])))
print("Number of Disagreeing Key Bits between Bob and Eve: " + str(sum([bob_key[i] != eve_key[i] for i in range(len(alice_key))])))
|
https://github.com/JoelJJoseph/QUANTUM-TRADE
|
JoelJJoseph
|
import numpy as np
import networkx as nx
import qiskit
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer, assemble
from qiskit.quantum_info import Statevector
from qiskit.aqua.algorithms import NumPyEigensolver
from qiskit.quantum_info import Pauli
from qiskit.aqua.operators import op_converter
from qiskit.aqua.operators import WeightedPauliOperator
from qiskit.visualization import plot_histogram
from qiskit.providers.aer.extensions.snapshot_statevector import *
from thirdParty.classical import rand_graph, classical, bitstring_to_path, calc_cost
from utils import mapeo_grafo
from collections import defaultdict
from operator import itemgetter
from scipy.optimize import minimize
import matplotlib.pyplot as plt
LAMBDA = 10
SEED = 10
SHOTS = 10000
# returns the bit index for an alpha and j
def bit(i_city, l_time, num_cities):
return i_city * num_cities + l_time
# e^(cZZ)
def append_zz_term(qc, q_i, q_j, gamma, constant_term):
qc.cx(q_i, q_j)
qc.rz(2*gamma*constant_term,q_j)
qc.cx(q_i, q_j)
# e^(cZ)
def append_z_term(qc, q_i, gamma, constant_term):
qc.rz(2*gamma*constant_term, q_i)
# e^(cX)
def append_x_term(qc,qi,beta):
qc.rx(-2*beta, qi)
def get_not_edge_in(G):
N = G.number_of_nodes()
not_edge = []
for i in range(N):
for j in range(N):
if i != j:
buffer_tupla = (i,j)
in_edges = False
for edge_i, edge_j in G.edges():
if ( buffer_tupla == (edge_i, edge_j) or buffer_tupla == (edge_j, edge_i)):
in_edges = True
if in_edges == False:
not_edge.append((i, j))
return not_edge
def get_classical_simplified_z_term(G, _lambda):
# recorrer la formula Z con datos grafo se va guardando en diccionario que acumula si coinciden los terminos
N = G.number_of_nodes()
E = G.edges()
# z term #
z_classic_term = [0] * N**2
# first term
for l in range(N):
for i in range(N):
z_il_index = bit(i, l, N)
z_classic_term[z_il_index] += -1 * _lambda
# second term
for l in range(N):
for j in range(N):
for i in range(N):
if i < j:
# z_il
z_il_index = bit(i, l, N)
z_classic_term[z_il_index] += _lambda / 2
# z_jl
z_jl_index = bit(j, l, N)
z_classic_term[z_jl_index] += _lambda / 2
# third term
for i in range(N):
for l in range(N):
for j in range(N):
if l < j:
# z_il
z_il_index = bit(i, l, N)
z_classic_term[z_il_index] += _lambda / 2
# z_ij
z_ij_index = bit(i, j, N)
z_classic_term[z_ij_index] += _lambda / 2
# fourth term
not_edge = get_not_edge_in(G) # include order tuples ej = (1,0), (0,1)
for edge in not_edge:
for l in range(N):
i = edge[0]
j = edge[1]
# z_il
z_il_index = bit(i, l, N)
z_classic_term[z_il_index] += _lambda / 4
# z_j(l+1)
l_plus = (l+1) % N
z_jlplus_index = bit(j, l_plus, N)
z_classic_term[z_jlplus_index] += _lambda / 4
# fifthy term
weights = nx.get_edge_attributes(G,'weight')
for edge_i, edge_j in G.edges():
weight_ij = weights.get((edge_i,edge_j))
weight_ji = weight_ij
for l in range(N):
# z_il
z_il_index = bit(edge_i, l, N)
z_classic_term[z_il_index] += weight_ij / 4
# z_jlplus
l_plus = (l+1) % N
z_jlplus_index = bit(edge_j, l_plus, N)
z_classic_term[z_jlplus_index] += weight_ij / 4
# add order term because G.edges() do not include order tuples #
# z_i'l
z_il_index = bit(edge_j, l, N)
z_classic_term[z_il_index] += weight_ji / 4
# z_j'lplus
l_plus = (l+1) % N
z_jlplus_index = bit(edge_i, l_plus, N)
z_classic_term[z_jlplus_index] += weight_ji / 4
return z_classic_term
def tsp_obj_2(x, G,_lambda):
# obtenemos el valor evaluado en f(x_1, x_2,... x_n)
not_edge = get_not_edge_in(G)
N = G.number_of_nodes()
tsp_cost=0
#Distancia
weights = nx.get_edge_attributes(G,'weight')
for edge_i, edge_j in G.edges():
weight_ij = weights.get((edge_i,edge_j))
weight_ji = weight_ij
for l in range(N):
# x_il
x_il_index = bit(edge_i, l, N)
# x_jlplus
l_plus = (l+1) % N
x_jlplus_index = bit(edge_j, l_plus, N)
tsp_cost+= int(x[x_il_index]) * int(x[x_jlplus_index]) * weight_ij
# add order term because G.edges() do not include order tuples #
# x_i'l
x_il_index = bit(edge_j, l, N)
# x_j'lplus
x_jlplus_index = bit(edge_i, l_plus, N)
tsp_cost += int(x[x_il_index]) * int(x[x_jlplus_index]) * weight_ji
#Constraint 1
for l in range(N):
penal1 = 1
for i in range(N):
x_il_index = bit(i, l, N)
penal1 -= int(x[x_il_index])
tsp_cost += _lambda * penal1**2
#Contstraint 2
for i in range(N):
penal2 = 1
for l in range(N):
x_il_index = bit(i, l, N)
penal2 -= int(x[x_il_index])
tsp_cost += _lambda*penal2**2
#Constraint 3
for edge in not_edge:
for l in range(N):
i = edge[0]
j = edge[1]
# x_il
x_il_index = bit(i, l, N)
# x_j(l+1)
l_plus = (l+1) % N
x_jlplus_index = bit(j, l_plus, N)
tsp_cost += int(x[x_il_index]) * int(x[x_jlplus_index]) * _lambda
return tsp_cost
def get_classical_simplified_zz_term(G, _lambda):
# recorrer la formula Z con datos grafo se va guardando en diccionario que acumula si coinciden los terminos
N = G.number_of_nodes()
E = G.edges()
# zz term #
zz_classic_term = [[0] * N**2 for i in range(N**2) ]
# first term
for l in range(N):
for j in range(N):
for i in range(N):
if i < j:
# z_il
z_il_index = bit(i, l, N)
# z_jl
z_jl_index = bit(j, l, N)
zz_classic_term[z_il_index][z_jl_index] += _lambda / 2
# second term
for i in range(N):
for l in range(N):
for j in range(N):
if l < j:
# z_il
z_il_index = bit(i, l, N)
# z_ij
z_ij_index = bit(i, j, N)
zz_classic_term[z_il_index][z_ij_index] += _lambda / 2
# third term
not_edge = get_not_edge_in(G)
for edge in not_edge:
for l in range(N):
i = edge[0]
j = edge[1]
# z_il
z_il_index = bit(i, l, N)
# z_j(l+1)
l_plus = (l+1) % N
z_jlplus_index = bit(j, l_plus, N)
zz_classic_term[z_il_index][z_jlplus_index] += _lambda / 4
# fourth term
weights = nx.get_edge_attributes(G,'weight')
for edge_i, edge_j in G.edges():
weight_ij = weights.get((edge_i,edge_j))
weight_ji = weight_ij
for l in range(N):
# z_il
z_il_index = bit(edge_i, l, N)
# z_jlplus
l_plus = (l+1) % N
z_jlplus_index = bit(edge_j, l_plus, N)
zz_classic_term[z_il_index][z_jlplus_index] += weight_ij / 4
# add order term because G.edges() do not include order tuples #
# z_i'l
z_il_index = bit(edge_j, l, N)
# z_j'lplus
l_plus = (l+1) % N
z_jlplus_index = bit(edge_i, l_plus, N)
zz_classic_term[z_il_index][z_jlplus_index] += weight_ji / 4
return zz_classic_term
def get_classical_simplified_hamiltonian(G, _lambda):
# z term #
z_classic_term = get_classical_simplified_z_term(G, _lambda)
# zz term #
zz_classic_term = get_classical_simplified_zz_term(G, _lambda)
return z_classic_term, zz_classic_term
def get_cost_circuit(G, gamma, _lambda):
N = G.number_of_nodes()
N_square = N**2
qc = QuantumCircuit(N_square,N_square)
z_classic_term, zz_classic_term = get_classical_simplified_hamiltonian(G, _lambda)
# z term
for i in range(N_square):
if z_classic_term[i] != 0:
append_z_term(qc, i, gamma, z_classic_term[i])
# zz term
for i in range(N_square):
for j in range(N_square):
if zz_classic_term[i][j] != 0:
append_zz_term(qc, i, j, gamma, zz_classic_term[i][j])
return qc
def get_mixer_operator(G,beta):
N = G.number_of_nodes()
qc = QuantumCircuit(N**2,N**2)
for n in range(N**2):
append_x_term(qc, n, beta)
return qc
def get_QAOA_circuit(G, beta, gamma, _lambda):
assert(len(beta)==len(gamma))
N = G.number_of_nodes()
qc = QuantumCircuit(N**2,N**2)
# init min mix state
qc.h(range(N**2))
p = len(beta)
for i in range(p):
qc = qc.compose(get_cost_circuit(G, gamma[i], _lambda))
qc = qc.compose(get_mixer_operator(G, beta[i]))
qc.barrier(range(N**2))
qc.snapshot_statevector("final_state")
qc.measure(range(N**2),range(N**2))
return qc
def invert_counts(counts):
return {k[::-1] :v for k,v in counts.items()}
# Sample expectation value
def compute_tsp_energy_2(counts, G):
energy = 0
get_counts = 0
total_counts = 0
for meas, meas_count in counts.items():
obj_for_meas = tsp_obj_2(meas, G, LAMBDA)
energy += obj_for_meas*meas_count
total_counts += meas_count
mean = energy/total_counts
return mean
def get_black_box_objective_2(G,p):
backend = Aer.get_backend('qasm_simulator')
sim = Aer.get_backend('aer_simulator')
# function f costo
def f(theta):
beta = theta[:p]
gamma = theta[p:]
# Anzats
qc = get_QAOA_circuit(G, beta, gamma, LAMBDA)
result = execute(qc, backend, seed_simulator=SEED, shots= SHOTS).result()
final_state_vector = result.data()["snapshots"]["statevector"]["final_state"][0]
state_vector = Statevector(final_state_vector)
probabilities = state_vector.probabilities()
probabilities_states = invert_counts(state_vector.probabilities_dict())
expected_value = 0
for state,probability in probabilities_states.items():
cost = tsp_obj_2(state, G, LAMBDA)
expected_value += cost*probability
counts = result.get_counts()
mean = compute_tsp_energy_2(invert_counts(counts),G)
return mean
return f
def crear_grafo(cantidad_ciudades):
pesos, conexiones = None, None
mejor_camino = None
while not mejor_camino:
pesos, conexiones = rand_graph(cantidad_ciudades)
mejor_costo, mejor_camino = classical(pesos, conexiones, loop=False)
G = mapeo_grafo(conexiones, pesos)
return G, mejor_costo, mejor_camino
def run_QAOA(p,ciudades, grafo):
if grafo == None:
G, mejor_costo, mejor_camino = crear_grafo(ciudades)
print("Mejor Costo")
print(mejor_costo)
print("Mejor Camino")
print(mejor_camino)
print("Bordes del grafo")
print(G.edges())
print("Nodos")
print(G.nodes())
print("Pesos")
labels = nx.get_edge_attributes(G,'weight')
print(labels)
else:
G = grafo
intial_random = []
# beta, mixer Hammiltonian
for i in range(p):
intial_random.append(np.random.uniform(0,np.pi))
# gamma, cost Hammiltonian
for i in range(p):
intial_random.append(np.random.uniform(0,2*np.pi))
init_point = np.array(intial_random)
obj = get_black_box_objective_2(G,p)
res_sample = minimize(obj, init_point,method="COBYLA",options={"maxiter":2500,"disp":True})
print(res_sample)
if __name__ == '__main__':
# Run QAOA parametros: profundidad p, numero d ciudades,
run_QAOA(5, 3, None)
|
https://github.com/lzylili/grovers-algo
|
lzylili
|
#Import libraries from qiskit
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
from qiskit import *
from qiskit.providers.ibmq import least_busy
import math
# Initializing circuit: define as 2 qubits
q = QuantumRegister(2, 'q')
c = ClassicalRegister(2, 'c')
# Create the quantum circuit
qc = QuantumCircuit(q,c)
## Step 1: Apply a Hadarmard gate to all qubits
qc.h(q)
## Step 2: Implement the Oracle circuit for state |11> + Grover diffusion
qc.cz(q[1],q[0])
qc.barrier(q)
qc.h(q)
qc.x(q)
qc.cz(q[1],q[0])
qc.x(q)
qc.h(q)
qc.barrier(q)
qc.draw(output='mpl')
## Don't forget about the measurement gates!
qc.measure(q[0],c[0])
qc.measure(q[1],c[1])
qc.draw(output='mpl')
## Step 4: Run on backend simulator and print results
simulator = Aer.get_backend('qasm_simulator')
result = execute(qc, backend = simulator, shots = 2048).result()
counts = result.get_counts()
print('RESULT: ',counts,'\n')
from qiskit.tools.visualization import plot_histogram
plot_histogram(counts)
## Step 4: Run on real device from IBM - load account and get least busy backend
provider = IBMQ.load_account()
device = least_busy(provider.backends(simulator=False))
print("Running on current least busy device: ", device)
from qiskit.tools.monitor import job_monitor
job = execute(qc, backend=device, shots=1024, max_credits=10)
job_monitor(job, interval = 2)
## Print results from device from IBM
results = job.result()
answer = results.get_counts(qc)
plot_histogram(answer)
pi = math.pi
# Initializing circuit: define as 3 qubits
q = QuantumRegister(3, 'q')
c = ClassicalRegister(3, 'c')
# Create the quantum circuit
qc = QuantumCircuit(q,c)
## Step 1: Apply a Hadarmard gate to all qubits
qc.h(q)
## Step 2: Implement the Oracle circuit for state |111> + Grover diffusion
qc.cz(q[2],q[0])
qc.barrier(q)
qc.h(q)
qc.x(q)
qc.barrier(q)
qc.cx(q[1],q[0])
qc.z(q[0]),-pi/4
qc.cx(q[2],q[0])
qc.z(q[0]),pi/4
qc.cx(q[1],q[0])
qc.z(q[0]),-pi/4
qc.barrier(q)
qc.cx(q[2],q[0])
qc.z(q[0]),pi/4
qc.z(q[1]),pi/4
qc.barrier(q)
qc.cx(q[2],q[1])
qc.z(q[1]),-pi/4
qc.cx(q[2],q[1])
qc.z(q[2]),pi/4
qc.barrier(q)
qc.x(q)
qc.h(q)
qc.barrier(q)
qc.draw(output='mpl')
## Don't forget about the measurement gates!
qc.measure(q[0],c[0])
qc.measure(q[1],c[1])
qc.measure(q[2],c[2])
qc.draw(output='mpl')
## Step 4: Run on backend simulator and print results
simulator = Aer.get_backend('qasm_simulator')
result = execute(qc, backend = simulator, shots = 2048).result()
counts = result.get_counts()
print('RESULT: ',counts,'\n')
from qiskit.tools.visualization import plot_histogram
plot_histogram(counts)
## Note: accuracy of this implementation is not 100% (may need to run a couple iterations before achieving desired result)
## Step 4: Run on real device from IBM - load account and get least busy backend
provider = IBMQ.load_account()
device = least_busy(provider.backends(simulator=False))
print("Running on current least busy device: ", device)
from qiskit.tools.monitor import job_monitor
job = execute(qc, backend=device, shots=1024, max_credits=10)
job_monitor(job, interval = 2)
## Print results from device from IBM
results = job.result()
answer = results.get_counts(qc)
plot_histogram(answer)
# Initializing circuit: define as 2 qubits
q = QuantumRegister(4, 'q')
c = ClassicalRegister(4, 'c')
# Create the quantum circuit
qc = QuantumCircuit(q,c)
## Step 1: Apply a Hadarmard gate to all qubits
qc.h(q)
## Step 2: Implement the Oracle circuit for state |111> + Grover diffusion
qc.cz(q[3],q[0])
qc.barrier(q)
qc.h(q)
qc.x(q)
qc.barrier(q)
qc.h(q[1])
qc.cx(q[2],q[1])
qc.tdg(q[1])
qc.cx(q[3],q[1])
qc.t(q[1])
qc.cx(q[2],q[1])
qc.tdg(q[1])
qc.cx(q[3],q[1])
qc.barrier(q)
qc.t(q[1])
qc.tdg(q[2])
qc.h(q[1])
qc.barrier(q)
qc.h(q[2])
qc.h(q[3])
qc.cx(q[3],q[2])
qc.h(q[2])
qc.h(q[3])
qc.tdg(q[2])
qc.barrier(q)
qc.h(q[2])
qc.h(q[3])
qc.cx(q[3],q[2])
qc.h(q[2])
qc.h(q[3])
qc.s(q[2])
qc.t(q[3])
qc.barrier(q)
qc.cx(q[1],q[0])
qc.t(q[0])
qc.cx(q[1],q[0])
qc.tdg(q[0])
qc.tdg(q[1])
qc.h(q[1])
qc.cx(q[2],q[1])
qc.tdg(q[1])
qc.cx(q[3],q[1])
qc.t(q[1])
qc.cx(q[2],q[1])
qc.tdg(q[1])
qc.cx(q[3],q[1])
qc.t(q[1])
qc.tdg(q[2])
qc.h(q[1])
qc.barrier(q)
qc.h(q[2])
qc.h(q[3])
qc.cx(q[3],q[2])
qc.h(q[2])
qc.h(q[3])
qc.tdg(q[2])
qc.barrier(q)
qc.h(q[2])
qc.h(q[3])
qc.cx(q[3],q[2])
qc.h(q[2])
qc.h(q[3])
qc.s(q[2])
qc.t(q[3])
qc.barrier(q)
qc.cx(q[1],q[0])
qc.tdg(q[0])
qc.cx(q[1],q[0])
qc.t(q[0])
qc.t(q[1])
qc.barrier(q)
qc.h(q[2])
qc.h(q[3])
qc.cx(q[3],q[2])
qc.h(q[2])
qc.h(q[3])
qc.cx(q[1],q[0])
qc.h(q[0])
qc.h(q[1])
qc.cx(q[1],q[0])
qc.h(q[0])
qc.h(q[1])
qc.cx(q[1],q[0])
qc.h(q[0])
qc.h(q[1])
qc.barrier(q)
qc.cx(q[2],q[1])
qc.u1(pi/8,q[1])
qc.cx(q[2],q[1])
qc.u1(-pi/8,q[1])
qc.u1(pi/8,q[2])
qc.barrier(q)
qc.h(q[2])
qc.h(q[3])
qc.cx(q[3],q[2])
qc.h(q[2])
qc.h(q[3])
qc.cx(q[2],q[1])
qc.u1(pi/8,q[1])
qc.cx(q[2],q[1])
qc.u1(pi/8,q[1])
qc.u1(pi/8,q[2])
qc.cx(q[3],q[1])
qc.u1(-pi/8,q[1])
qc.cx(q[3],q[1])
qc.u1(pi/8,q[1])
qc.u1(pi/8,q[3])
qc.barrier(q)
qc.cx(q[1],q[0])
qc.h(q[0])
qc.h(q[1])
qc.cx(q[1],q[0])
qc.h(q[0])
qc.h(q[1])
qc.cx(q[1],q[0])
qc.h(q[0])
qc.h(q[1])
qc.barrier(q)
qc.x(q)
qc.h(q)
qc.barrier(q)
qc.draw(output='mpl')
## Don't forget about the measurement gates!
qc.measure(q[0],c[0])
qc.measure(q[1],c[1])
qc.measure(q[2],c[2])
qc.measure(q[3],c[3])
qc.draw(output='mpl')
## Step 4: Run on backend simulator and print results
simulator = Aer.get_backend('qasm_simulator')
result = execute(qc, backend = simulator, shots = 2048).result()
counts = result.get_counts()
print('RESULT: ',counts,'\n')
from qiskit.tools.visualization import plot_histogram
plot_histogram(counts)
## Note: accuracy of this implementation not 100% (may need to run a couple iterations before achieving desired result)
## Step 4: Run on real device from IBM - load account and get least busy backend
provider = IBMQ.load_account()
device = least_busy(provider.backends(simulator=False))
print("Running on current least busy device: ", device)
from qiskit.tools.monitor import job_monitor
job = execute(qc, backend=device, shots=1024, max_credits=10)
job_monitor(job, interval = 2)
## Print results from device from IBM
results = job.result()
answer = results.get_counts(qc)
plot_histogram(answer)
|
https://github.com/DEBARGHYA4469/quantum-compiler
|
DEBARGHYA4469
|
from qiskit import register, available_backends , get_backend
# Establish connection with IBMQuantum Experience
try :
import sys
sys.path.append('../')
import Qconfig
qx_config = { # configuration details
'APItoken' : Qconfig.APItoken ,
'url' : Qconfig.config['url']}
except Exception as e :
print(e)
print("Check your API token")
register(qx_config['APItoken'],qx_config['url'])
def lowest_pending_jobs(): # find the best backend available
list_backends = available_backends({'local':False,'simulator':False})
device_status = [get_backend(backend).status for backend in list_backends]
best = min([x for x in device_status if x['available'] is True],key = lambda x: x['pending_jobs'])
return best['name']
def get_qc():
backend = lowest_pending_jobs()
print("The best backend is",backend)
return backend
|
https://github.com/DEBARGHYA4469/quantum-compiler
|
DEBARGHYA4469
|
#THIS PROGRAM IS MODIFIED FROM THE DJ ALGORITHM PRESENT IN QISKIT TUTORIAL WHERE I FEEL THAT THE NOTION OF TAKING THE RANDOM BALANCED
#FUNCTION IS QUITE ABSTRACT AND DIFFICULT TO GRASP FOR A BEGINNER.SO I ADDED SOME PIECE OF CODE FOR PRINTING THE RANDOM FUNCTION
#AND PROVE THERE IS A DETERMINISTIC WAY OF DERIVING A BALANCED FUNCTION BY SEEDING A RANDOM NUMBER!!
from connection import *
import numpy as np
import random
import matplotlib.pyplot as plt
from qiskit import QuantumCircuit,ClassicalRegister,QuantumRegister,QuantumJob
from qiskit import available_backends,execute,register,get_backend
from qiskit.tools.visualization import plot_histogram,circuit_drawer
backend = get_qc() # get the quantum computer with least jobs queued up
def flip_x(arr,binlength,l):
if(l == 0):
newstr = ""
for b in range(binlength):newstr = newstr + str(arr[b])
print("f(",newstr,")=1")
else:
for pv in range(2):
acopy = []
for i in range(binlength): acopy.append(arr[i])
for k in range(binlength):
if(acopy[k] == -1):
acopy[k] = pv
break
flip_x(acopy,binlength,l-1)
def mark_ones(j,shift,pos_ones,arr):
for i in range(j):
arr[pos_ones[shift+i]] = 1
return arr
def rec_util(j,binlength,pos_ones,shift):
if(shift+j-1 >= len(pos_ones)):
return
arr = []
for i in range(binlength): arr.append(-1)
arr = mark_ones(j,shift,pos_ones,arr)
flip_x(arr,binlength,binlength-j)
rec_util(j,binlength,pos_ones,shift+1)
def ones_in_binary(r): # Decimal to binary conversion
num = r
bry = 0
m = []
j = 0
f=1
while(num>0):
bry = bry + (num%2)*f
if(num%2 == 1):
m.append(j)
num = num//2
f=f*10
j=j+1
for i in range(len(m)):
m[i] = j -1- m[i]
pos_ones = []
for i in range(len(m)):
pos_ones.append(m[len(m)-i-1])
print(pos_ones)
return pos_ones,j
def print_fx(r,n):
j=1
pos_ones,binlength = ones_in_binary(r)#position of the ones and total length of binary string
binlength = n
while(j <= len(pos_ones)): #only odd results in flip by CNOT
shift = 0 # to traverse the pos_ones
rec_util(j,binlength,pos_ones,shift)
j=j+2
print("\n................DEUTSCH JOZSA ALGORITHM....................\n")
print("\nInput the size of the domain of the function..\n")
n = int(input())
print("\nInput 0 if you want a constant function,1 otherwise\n")
oracle_Type = int(input()) # constant or balanced
if(oracle_Type == 0): # constant function
print("What is the constant value 0/1 ?")
oracle_val = int(input())
else:
print("The function is balanced...Generating a random f(x)")
fx_generator = np.random.randint(1,2**n) # this variable creates the quantum circuit of the f(x)
print("\nYour Balanced Function is .........................")
print(fx_generator)
print_fx(fx_generator,n) # print the function
print("\nn Rest all values are 0s")
print("\nTHIS FUNCTION WILL REMAIN HIDDEN AND ONLY BE QUERIED TO ITS EQUIVALENT QUANTUM CIRCUIT")
#Print the quantum circuit for your random balanced oracle
file = open("oracle.qasm","a") # append mode
file.write("\n")
# Interfacing with quantum computer
qr = QuantumRegister(n+1) # query string
cr = ClassicalRegister(n) # first register
circuitName = "Deutsch_Joszsa"
djCircuit = QuantumCircuit(qr,cr)
for i in range(n+1):
file.write(" qubit q"+str(i)+"\n")
#superposition of all input queries by hadamard transform
for i in range(n):
file.write(" h q"+str(i)+"\n")
djCircuit.h(qr[i])
#FLip the second register and apply hadamard
djCircuit.x(qr[n])
file.write(" X q"+str(n)+"\n")
djCircuit.h(qr[n])
file.write(" h q"+str(n)+"\n")
djCircuit.barrier()
# IMPLEMENTING THE ORACLE BUT ITS VALUES ARE HIDDEN
if(oracle_Type == 0): # if constant
if(oracle_val==1):
djCircuit.x(qr[n])
file.write(" X q"+str(n)+"\n")
else:
djCircuit.iden(qr[n])
else:
for i in range(n):
if(fx_generator & (1 << i)):
djCircuit.cx(qr[i],qr[n])
file.write(" cnot q"+str(i)+",q"+str(n)+"\n")
djCircuit.barrier()
#apply hadamard after querying the oracle
for i in range(n):
djCircuit.h(qr[i])
file.write(" h q"+str(i)+"\n")
#measurements
for i in range(n):
djCircuit.measure(qr[i],cr[i])
file.write(" measure q"+str(i)+"\n")
#circuit_drawer(djCircuit)
file.close()
#backend = "local_qasm_simulator" #FOR local testing...
shots = 1000
job = execute(djCircuit,backend=backend,shots=shots)
results=job.result()
answer = results.get_counts()
plot_histogram(answer)
|
https://github.com/DEBARGHYA4469/quantum-compiler
|
DEBARGHYA4469
|
from qiskit import register, available_backends , get_backend
# Establish connection with IBMQuantum Experience
try :
import sys
sys.path.append('../')
import Qconfig
qx_config = { # configuration details
'APItoken' : Qconfig.APItoken ,
'url' : Qconfig.config['url']}
except Exception as e :
print(e)
print("Check your API token")
register(qx_config['APItoken'],qx_config['url'])
def lowest_pending_jobs(): # find the best backend available
list_backends = available_backends({'local':False,'simulator':False})
device_status = [get_backend(backend).status for backend in list_backends]
best = min([x for x in device_status if x['available'] is True],key = lambda x: x['pending_jobs'])
return best['name']
def get_qc():
backend = lowest_pending_jobs()
print("The best backend is",backend)
return backend
|
https://github.com/DEBARGHYA4469/quantum-compiler
|
DEBARGHYA4469
|
"""Python implementation of Grovers algorithm through use of the Qiskit library to find the value 3 (|11>)
out of four possible values."""
#import numpy and plot library
import matplotlib.pyplot as plt
import numpy as np
# importing Qiskit
from qiskit import IBMQ, Aer, QuantumCircuit, ClassicalRegister, QuantumRegister, execute
from qiskit.providers.ibmq import least_busy
from qiskit.quantum_info import Statevector
# import basic plot tools
from qiskit.visualization import plot_histogram
# define variables, 1) initialize qubits to zero
n = 2
grover_circuit = QuantumCircuit(n)
#define initialization function
def initialize_s(qc, qubits):
'''Apply a H-gate to 'qubits' in qc'''
for q in qubits:
qc.h(q)
return qc
### begin grovers circuit ###
#2) Put qubits in equal state of superposition
grover_circuit = initialize_s(grover_circuit, [0,1])
# 3) Apply oracle reflection to marked instance x_0 = 3, (|11>)
grover_circuit.cz(0,1)
statevec = job_sim.result().get_statevector()
from qiskit_textbook.tools import vector2latex
vector2latex(statevec, pretext="|\\psi\\rangle =")
# 4) apply additional reflection (diffusion operator)
grover_circuit.h([0,1])
grover_circuit.z([0,1])
grover_circuit.cz(0,1)
grover_circuit.h([0,1])
# 5) measure the qubits
grover_circuit.measure_all()
# Load IBM Q account and get the least busy backend device
provider = IBMQ.load_account()
device = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 3 and
not x.configuration().simulator and x.status().operational==True))
print("Running on current least busy device: ", device)
from qiskit.tools.monitor import job_monitor
job = execute(grover_circuit, backend=device, shots=1024, optimization_level=3)
job_monitor(job, interval = 2)
results = job.result()
answer = results.get_counts(grover_circuit)
plot_histogram(answer)
#highest amplitude should correspond with marked value x_0 (|11>)
|
https://github.com/DEBARGHYA4469/quantum-compiler
|
DEBARGHYA4469
|
from qiskit import ClassicalRegister,QuantumRegister,QuantumJob
from qiskit import available_backends,execute,register,get_backend
from qiskit.tools.visualization import plot_histogram
from qiskit import QuantumCircuit
from zy_decomposition import *
from control_U2 import *
#.................................................................
def swaper(ckt,ctr,tgt,q): # swap control and target bit
ckt.cx(q[ctr],q[tgt])
ckt.h(q[ctr])
ckt.h(q[tgt])
ckt.cx(q[ctr],q[tgt])
ckt.h(q[ctr])
ckt.h(q[tgt])
ckt.cx(q[ctr],q[tgt])
return ckt
#.................................................................
#.........................................................n-Q Toffolli...................................................
def nQ_tofolli(ckt,n,q): # always take first n-1 as ctr,n as tgt
i = 0
anc = n # ancillas are from n to 2*n-1
while(i < n-2):
if(i==0):
ckt.ccx(q[0],q[1],q[anc])
else :
ckt.ccx(q[i+1],q[anc+i-1],q[anc+i])
i = i + 1
i = i - 1
# Perform the controlled operations
ckt.cx(q[anc+i],q[n-1]) # Controlled-U operation
# Free the ancillas....
while(i >= 0):
if(i==0):
ckt.ccx(q[0],q[1],q[anc])
else :
ckt.ccx(q[i+1],q[anc+i-1],q[anc+i])
i = i - 1
return ckt
#.......................................................n-Q Tofolli ......................................................
#................................................Controlled-U operations .................................................
def Control_U(ckt,V_tilde,q,n): # n is no of qubits
i = 0
anc = n # ancillas are from n to 2*n-1
while(i < n-2):
if(i==0):
ckt.ccx(q[0],q[1],q[anc])
else :
ckt.ccx(q[i+1],q[anc+i-1],q[anc+i])
i = i + 1
i = i - 1
# Perform the controlled operations
ckt = CU2(V_tilde,ckt,q,n) # Controlled-U operation
# Free the ancillas....
while(i >= 0):
if(i==0):
ckt.ccx(q[0],q[1],q[anc])
else :
ckt.ccx(q[i+1],q[anc+i-1],q[anc+i])
i = i - 1
return ckt
#................................................Controlled-U operations .................................................
def test_block():
q = QuantumRegister(5+4) # Quantum bits
c = ClassicalRegister(9) #Classical Register
U = np.array([[1,1],[1,-1]])/math.sqrt(2.0)
ckt = QuantumCircuit(q,c)
for j in range(5):
ckt.x(q[j])
ckt.x(q[4])
ckt = Control_U(ckt,U,q,5)
for i in range(9):
ckt.measure(q[i],c[i])
get_result(ckt)
|
https://github.com/DEBARGHYA4469/quantum-compiler
|
DEBARGHYA4469
|
# Implement the control_U2 gate
# Written by Debarghya Kundu
# Email : debarghya4469@iitg.ernet.in
from zy_decomposition import *
from qiskit import ClassicalRegister,QuantumRegister,QuantumJob
from qiskit import available_backends,execute,register,get_backend
from qiskit.tools.visualization import plot_histogram
from qiskit import QuantumCircuit
def Rzz(ckt,theta,q,n): # Phase-Shift gate
ckt.u1(theta,q[n-1]) # Rzz for last qubit is required
ckt.x(q[n-1])
ckt.u1(theta,q[n-1])
ckt.x(q[n-1])
return ckt
def Rz(ckt,theta,q,n): #rotation along -z axis
ckt.u1(theta,q[n-1])
ckt = Rzz(ckt,-1.0*theta/2.0,q,n)
return ckt
def Ry(ckt,theta,q,n): #rotation along -y axis
ckt.u3(theta,0,0,q[n-1])
return ckt
def CU2(U,ckt,q,n):
alpha,beta,gama,delta = zy_decompose(U)
ckt = Rz(ckt,(delta-beta)/2.0,q,n) # Apply :: C
ckt.cx(q[2*n-3],q[n-1]) # ancilla as ctr,tgt
ckt = Rz(ckt,-1.0*(beta+delta)/2.0,q,n) # Apply :: B
ckt = Ry(ckt,-1.0*gama/2.0,q,n) # Apply :: B
ckt.cx(q[2*n-3],q[n-1]) # ancilla as ctr,tgt
ckt = Ry(ckt,gama/2.0,q,n) # Apply :: A
ckt = Rz(ckt,beta,q,n) # Apply :: A
ckt.u1(alpha,q[2*n-3]) # phase to ancilla -> ref: N&C
return ckt
def get_result(ckt):
shots = 10000
backend = 'local_qasm_simulator'
job = execute(ckt,backend=backend,shots=shots)
results = job.result()
answer = results.get_counts()
plot_histogram(answer)
def test_main():
q = QuantumRegister(3+1)
c = ClassicalRegister(4)
a = math.cos(3.0)
b = math.sin(3.0)
U = np.array([[a,-1.0*b.conjugate()],[b,a.conjugate()]])
ckt = QuantumCircuit(q,c)
# ckt.x(q[3])
ckt = CU2(U,ckt,q,3)
for i in range(4):
ckt.measure(q[i],c[i])
get_result(ckt)
|
https://github.com/DEBARGHYA4469/quantum-compiler
|
DEBARGHYA4469
|
# Main routine for synthesis of n-qubit unitary
# Written by Debarghya Kundu
# Email : debarghya4469@iitg.ernet.in
from two_level_decompose import *
from two_dimensionalise import *
from block import *
import numpy as np
import math
from random import randint
from graycode import *
from nontrivial import *
from qiskit import ClassicalRegister,QuantumRegister
from qiskit import available_backends,execute,register
from qiskit import get_backend,QuantumJob
from zy_decomposition import *
from control_U2 import *
def dagger(U):
return U.conjugate().transpose()
def get_Vk(U,dim,l):# call only once .........
VSET = dcmp(U,dim) # set of all two-level-matrices
Vk = []
for V in VSET:
V = dagger(V)
Vk.append(V)
V_tilde = []
ntv_cols = []
for V in Vk :
V_tilde.append(twoD(V,dim)[0]) # only matrix...
ntv_cols.append([twoD(V,dim)[1],twoD(V,dim)[2]])
return Vk,V_tilde,ntv_cols
#------------------------------------------------------TRAVERSAL ---------------------------------------------------------
#
# U = V1 x V2 x V3 x V4 x .....................x Vk
#
# <--------- V1 ------------------------------> <--------------------V2--------------------------> .......Vk........>
# g11 g21 g31 g41 ............gm-1,1 C~U gm-1,1 ........g12 g22............gm...........................................
# [ Call this part a BLOCK 1 ]
#
# g(i,j)'s are represented by n qubit tofolli gate. Stimulate this by 3-Q Tofollis
# Controlled-U by SWAP and Tofolli operations ............
#
# 1. Get the set of matrices Vi's
# 2. Get the two-dimensional form of it
# 3. get the set of non-trivial qubits g1 and gm from Vk
# 4. Get the Grey code sequence
# 5. Traverse g1 to gm-1
# 6. Apply controlled-U
# 7. Traverse gm-1 to gm
# 8. Go to step 1 unless set replenishes
#----------------------------------------------------TRAVERSAL------------------------------------------------------------
def bitflip(gi,gj,n): # checked..................................
for i in range(n):
if(gi[i] != gj[i]):
return i
def cUop2(ckt,V_tilde,q,n):
alpha,beta,gama,delta = zy_decompose(V_tilde)
ckt = Rz(ckt,(delta-beta)/2.0,q,n) # Apply :: C
ckt.cx(q[0],q[1]) # ancilla as ctr,tgt
ckt = Rz(ckt,-1.0*(beta+delta)/2.0,q,n) # Apply :: B
ckt = Ry(ckt,-1.0*gama/2.0,q,n) # Apply :: B
ckt.cx(q[0],q[1]) # ancilla as ctr,tgt
ckt = Ry(ckt,gama/2.0,q,n) # Apply :: A
ckt = Rz(ckt,beta,q,n) # Apply :: A
ckt.u1(alpha,q[0]) # phase to ancilla -> ref: N&C
return ckt
def synth(U,dim,nqubit):
q = QuantumRegister(2*nqubit-1)
c = ClassicalRegister(2*nqubit-1)
ckt = QuantumCircuit(q,c)
Vk,V_tilde,ntv_cols = get_Vk(U,dim,dim) # all the two-level matrices
for block in range(len(Vk)):
#print("\n--------------------------NEW BLOCK----------------------------------\n")
#print(np.round(Vk[block],decimals=2))
#print(np.round(V_tilde[block],decimals=2))
g1,gm = ntvl(ntv_cols[block][0],ntv_cols[block][1],nqubit) # correct
Gcode_sq = []
g1_list = []
gm_list = []
for k in range(nqubit):
g1_list.append(g1[k])
gm_list.append(gm[k])
Gcode_sq = graycodes(g1_list,gm_list) # all the gray codes for Vk
m = len(Gcode_sq) # g1----->gm
#print(g1,gm,Gcode_sq,m) # correct
j = 1
#....................................................DEBUGGED........................................................................
while(j<=m-2): # all the first m-2 tofollis
#print("\n.........Each tofollis...................\n")
bflip=bitflip(Gcode_sq[j-1],Gcode_sq[j],nqubit)
#print("bitflip:-->",bflip)
for bi in range(nqubit):
if(bflip==bi):continue
if(Gcode_sq[j][bi]=='0'):
ckt.x(q[bi]) # X
# print("x is done on:",bi)
if(bflip != nqubit-1):#not last bit flip
ckt = swaper(ckt,bflip,nqubit-1,q)
# print("swap",bflip,nqubit-1)
if(nqubit ==2): ckt.cx(q[0],q[1])
if(nqubit > 2): ckt = nQ_tofolli(ckt,nqubit,q)
#print("Toffoli")
if(bflip != nqubit-1):#not last bit flip
ckt = swaper(ckt,bflip,nqubit-1,q)
# print("swap",bflip,nqubit-1)
for bi in range(nqubit):
if(bflip==bi):continue
if(Gcode_sq[j][bi]=='0'):
ckt.x(q[bi]) # X
# print("x is done on:",bi)
j = j + 1
# Apply controlled-U for change from gm-1 to gm
#---------------------------------------------------------------------------------------------------------------------
bflip = bitflip(Gcode_sq[m-2],Gcode_sq[m-1],nqubit)
for bi in range(nqubit):
if(bflip==bi):continue
if(Gcode_sq[j][bi]=='0'):
ckt.x(q[bi]) # X
if(bflip != nqubit-1):#not last bit flip
ckt = swaper(ckt,bflip,nqubit-1,q)
if(nqubit == 2): ckt = cUop2(ckt,V_tilde,q,nqubit)
if(nqubit > 2): ckt = Control_U(ckt,V_tilde[block],q,nqubit)
if(bflip != nqubit-1):#not last bit flip
ckt = swaper(ckt,bflip,nqubit-1,q)
for bi in range(nqubit):
if(bflip==bi):continue
if(Gcode_sq[j][bi]=='0'):
ckt.x(q[bi]) # X
#----------------------------------------------------------------------------------------------------------------------
# Reverse the states ......................................
j = m-2
while(j >= 1): # all the first m-2 tofollis
bflip=bitflip(Gcode_sq[j-1],Gcode_sq[j],nqubit)
#print("bitflip:",j,"-->",bflip)
for bi in range(nqubit):
if(bflip==bi):continue
if(Gcode_sq[j][bi]=='0'):
ckt.x(q[bi]) # X
if(bflip != nqubit-1):#not last bit flip
ckt = swaper(ckt,bflip,nqubit-1,q)
if(nqubit ==2): ckt.cx(q[0],q[1])
if(nqubit > 2): ckt = nQ_tofolli(ckt,nqubit,q)
#print("Toffoli")
if(bflip != nqubit-1):#not last bit flip
ckt = swaper(ckt,bflip,nqubit-1,q)
for bi in range(nqubit):
if(bflip==bi):continue
if(Gcode_sq[j][bi]=='0'):
ckt.x(q[bi]) # X
j = j - 1
for i in range(2*nqubit-1):
ckt.measure(q[i],c[i])
get_result(ckt)
def kronecker(str): # find the kroncker product
z=0
if(str[0]=='0'):
z=np.array([[1],[0]])
if(str[0]=='1'):
z=np.array([[0],[1]])
for i in range(len(str)-1):
if(str[i+1]=='0'): z = np.kron(z,np.array([[1],[0]]))
if(str[i+1]=='1'): z = np.kron(z,np.array([[0],[1]]))
print(z)
def handle_1Qgates(U,dim,n):
q = QuantumRegister(n)
c = ClassicalRegister(n)
ckt = QuantumCircuit(q,c)
alpha,beta,gama,delta = zy_decompose(U) # decompose
ckt = Rz(ckt,(delta-beta)/2.0,q,n) # Apply :: C
ckt.x(q[0]) # ancilla as ctr,tgt
ckt = Rz(ckt,-1.0*(beta+delta)/2.0,q,n) # Apply :: B
ckt = Ry(ckt,-1.0*gama/2.0,q,n) # Apply :: B
ckt.x(q[0]) # ancilla as ctr,tgt
ckt = Ry(ckt,gama/2.0,q,n) # Apply :: A
ckt = Rz(ckt,beta,q,n) # Apply :: A
ckt.u1(alpha,q[0]) # phase to ancilla -> ref: N&C
for i in range(n):
ckt.measure(q[i],c[i])
get_result(ckt)
#u1 = np.array([[0,1],[1,0]]) # Pauli-X
#u2 = np.array([[1,1],[1,-1]])/math.sqrt(2.0) # Hadamard
#u2 = np.array([[1,1],[1,-1]])/math.sqrt(2.0)
#u= np.kron(u1,u1)
#u= np.kron(u,u1)
#u = unitary()
#u= np.kron(u,u2)
#u= np.kron(u,u2)
#u = np.array([[0,0,0,0,0,0,0,1],[0,0,0,0,0,0,1,0],[0,0,0,0,0,1,0,0],[0,0,0,0,1,0,0,0],[0,0,0,1,0,0,0,0],[0,0,1,0,0,0,0,0],[0,1,0,0,0,0,0,0],[1,0,0,0,0,0,0,0]])
#u = np.identity(16)
#for i in range(16):
# u[i][i]=0
# u[i][15-i]=1
#print(u)
#kk = np.array([[1],[0],[0],[0],[0],[0],[0],[0]])
#print(np.matmul(u,kk))
#synth(u,8,3)
# test .....................2018
#Vk,V_tilde,ntv_cols = get_Vk(u,8,8) # all the two-level matrices
#for V in range(len(Vk)):
# print(np.round(Vk[V],decimals=2),"\n")
# print(np.round(V_tilde[V],decimals=2),"\n")
# print("gcodes-->",ntv_cols[V][0],ntv_cols[V][1])
#print(np.allclose(np.identity(8),Vk[len(Vk)-1]))
|
https://github.com/victor-onofre/Quantum_Algorithms
|
victor-onofre
|
import numpy as np
from qiskit import QuantumCircuit as QC
from qiskit import execute
from qiskit import IBMQ, BasicAer
from qiskit.providers.ibmq import least_busy
from qiskit.tools.jupyter import *
provider = IBMQ.load_account()
from qiskit.visualization import plot_histogram
def oracle(case, n):
##creating an oracle
oracle_qc = QC(n+1)
if case=="balanced":
for i in range(n):
oracle_qc.cx(i,n)
if case=="constant":
pass
##converting circuit to a indivsual gate
oracle_gate = oracle_qc.to_gate()
oracle_gate.name = "Oracle"
return oracle_gate
def dj_algo(n, case="random"):
dj_crc = QC(n+1,n)
for i in range(n):
dj_crc.h(i)
dj_crc.x(n)
dj_crc.h(n)
if case=="random":
rnd = np.random.randint(2)
if rnd == 0:
case = "constant"
else:
case = "balanced"
dj_oracle = oracle(case, n)
dj_crc.append(dj_oracle, range(n+1))
for i in range(n):
dj_crc.h(i)
dj_crc.measure(i,i)
return dj_crc
n = 3
dj_crc = dj_algo(n)
dj_crc.draw('mpl')
#simulating
backend=BasicAer.get_backend('qasm_simulator')
shots = 1024
dj_circuit = dj_algo(n, "balanced")
results = execute(dj_circuit, backend=backend, shots=shots).result()
answer = results.get_counts()
plot_histogram(answer)
#running on real quantum computer
backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= (n+1) and
not x.configuration().simulator and x.status().operational == True))
print("Using least busy backend: ", backend)
%qiskit_job_watcher
dj_circuit = dj_algo(n, "balanced")
job = execute(dj_circuit, backend=backend, shots=shots, optimization_level=3)
result = job.result()
answer = result.get_counts()
plot_histogram(answer)
|
https://github.com/victor-onofre/Quantum_Algorithms
|
victor-onofre
|
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer, IBMQ, BasicAer
from qiskit.visualization import plot_bloch_multivector,plot_bloch_vector, plot_histogram
from qiskit.quantum_info import Statevector
import numpy as np
import matplotlib
backend = BasicAer.get_backend('qasm_simulator')
shots = 1024
style = {'backgroundcolor': 'lightyellow'} # Style of the circuits
qreg1 = QuantumRegister(2) # The quantum register of the qubits, in this case 2 qubits
register1 = ClassicalRegister(1)
qc = QuantumCircuit(qreg1, register1)
#qc.x(0)
qc.x(1)
qc.barrier()
qc.draw(output='mpl', style=style)
qc.h(0)
qc.h(1)
qc.barrier()
qc.draw(output='mpl', style=style)
qc.cx(0,1)
qc.barrier()
qc.draw(output='mpl', style=style)
qc.h(0)
qc.draw(output='mpl', style=style)
qc.measure(qreg1[0],register1)
qc.draw(output='mpl', style=style)
results = execute(qc, backend=backend, shots=shots).result()
answer = results.get_counts()
plot_histogram(answer)
def oracleBalance1(qcir):
qcir.cx(0,1)
qcir.barrier()
return qcir
def oracleBalance2(qcir):
qcir.x(1)
qcir.cx(0,1)
qcir.barrier()
return qcir
def oracleConstant1(qcir):
qcir.x(1)
qcir.barrier()
return qcir
def oracleConstant2(qcir):
qcir.barrier()
return qcir
def deutsch(oracle):
Qreg = QuantumRegister(2)
Creg = ClassicalRegister(1)
qcirc = QuantumCircuit(Qreg, Creg)
qcirc.x(1)
qcirc.h(0)
qcirc.h(1)
qcirc.barrier()
qcirc = oracle(qcirc)
qcirc.h(0)
qcirc.barrier()
qcirc.measure(Qreg[0],Creg)
return qcirc
resultBalanced1 = deutsch(oracleBalance1)
resultBalanced1.draw(output='mpl', style=style)
resultsB1 = execute(resultBalanced1, backend=backend, shots=shots).result()
answerB1 = resultsB1.get_counts()
plot_histogram(answerB1)
resultBalanced2 = deutsch(oracleBalance1)
resultBalanced2.draw(output='mpl', style=style)
resultsB2 = execute(resultBalanced2, backend=backend, shots=shots).result()
answerB2 = resultsB2.get_counts()
plot_histogram(answerB2)
resultConstant1 = deutsch(oracleConstant1)
resultConstant1.draw(output='mpl', style=style)
resultsC1= execute(resultConstant1, backend=backend, shots=shots).result()
answerC1 = resultsC1.get_counts()
plot_histogram(answerC1)
resultConstant2 = deutsch(oracleConstant2)
resultConstant2.draw(output='mpl', style=style)
resultsC2= execute(resultConstant2, backend=backend, shots=shots).result()
answerC2 = resultsC2.get_counts()
plot_histogram(answerC2)
|
https://github.com/victor-onofre/Quantum_Algorithms
|
victor-onofre
|
import numpy as np
import networkx as nx
import matplotlib.pyplot as plt
from scipy.optimize import minimize
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer
style = {'backgroundcolor': 'lightyellow'} # Style of the drawing of the quantum circuit
Graph_Example_1 = nx.Graph()
Graph_Example_1.add_edges_from([[1,2],[2,3],[1,3]])
nx.draw(Graph_Example_1,with_labels=True,font_weight='bold')
nx.draw(Graph_Example_1,node_color = ['b','b','r'])
Graph_Example_2 = nx.Graph()
Graph_Example_2.add_edges_from([[1,2],[1,3],[4,2],[4,3]])
nx.draw(Graph_Example_2,with_labels=True,font_weight='bold')
nx.draw(Graph_Example_2,node_color = ['r','b','b','r'])
Graph_Example_3 = nx.Graph()
Graph_Example_3.add_edges_from([[1,4],[1,2],[2,5],[4,5],[5,3],[2,3]])
nx.draw(Graph_Example_3,with_labels=True,font_weight='bold')
nx.draw(Graph_Example_3,node_color = ['r','b','b','r','b'])
Graph = nx.Graph()
Graph.add_edges_from([[0,1],[0,3],[3,4],[1,4],[1,2],[4,2]])
nx.draw(Graph,with_labels=True)
Graph.edges()
N = Graph.number_of_nodes() # The number of nodes in the graph
qc = QuantumCircuit(N,N) # Quantum circuit with N qubits and N classical register
gamma = np.pi/8 # parameter gamma for the cost function (maxcut hamiltonian)
#Apply the operator to each edge
for i, j in Graph.edges():
qc.cx(i,j)
qc.rz(2*gamma, j)
qc.cx(i,j)
qc.barrier()
qc.draw(output='mpl', style=style) # Draw the quantum circuit
beta = np.pi/8 # parameter for the mixer hamiltonian
for n in Graph.nodes():
qc.rx(2*beta, n)
# measure the result
qc.barrier(range(N))
qc.measure(range(N), range(N))
qc.draw(output='mpl', style=style,fold= 35)
def qaoa_circuit(G, theta,p):
r"""
############################################
# Compute the QAOA circuit for the graph G
#
# |psi(theta) > = |psi(beta,gamma) > = e^{-i*beta_p*B} e^{-i*gamma_p*C}... e^{-i*beta_1*B} e^{-i*gamma_1*C} H^{otimes n}|0>
#
# where C is the Maxcut hamiltonian, B is the mixer hamiltonian.
#
# G: graph
# theta: parameters,first half is betas, second half is gammas
# p: number of QAOA steps
# return: The QAOA circuit
###########################################
"""
beta = theta[:p] #Parameters beta for the mixer hamiltonian
gamma = theta[p:]#Parameters gamma for the maxcut hamiltonian
N = G.number_of_nodes()#Number of nodes of the graph G
qc = QuantumCircuit(N,N)# Quantum circuit wiht N qubits and N classical register
qc.h(range(N))# Apply the Hadamard gate to all the qubits
# Apply p operators
for k in range(p):
for i, j in G.edges(): #Representation of the maxcut hamiltonian
qc.cx(i,j)
qc.rz(2*gamma[k], j)
qc.cx(i,j)
qc.barrier()
for n in G.nodes(): # Representation of the mixer hamiltonian
qc.rx(2*beta[k], n)
# Measurement in all the qubits
qc.barrier(range(N))
qc.measure(range(N), range(N))
return qc #Returns the quantum circuit
# p is the number of QAOA alternating operators
p = 1
theta = np.array([np.pi/8,np.pi/8])
circuit = qaoa_circuit(Graph, theta,p)
circuit.draw(output='mpl', style=style,fold= 35) # Draw the quantum circuit
#Qiskit uses the least significant bit in the bistring, we need to invert this string
def invert_counts(counts):
r"""
############################################
# Inverted the binary string
#
# counts: The result of running the quantum circuit
# return: The results with binary string inverted
###########################################
"""
inv_counts = {}
for k, v in counts.items():
inv_counts[k[::-1]] = v
return inv_counts
def maxcut_objective_function(x,G):
r"""
############################################
# Compute the maxcut objective function for the binary string x and graph G
#
# G: graph
# x: binary string
# return: The cost of the binary string x
###########################################
"""
cut = 0
for i, j in G.edges():
if x[i] != x[j]:
cut -= 1# the edge is cut
return cut # Sum of all the edges that are cut
def function_to_minimize(G,p):
r"""
############################################
# Define the function to minimize given the graph G and the number of parameters
#
# G: graph
# p: number of parameters
# return: The function to minimize
###########################################
"""
backend = Aer.get_backend('qasm_simulator')
def f(theta):
r"""
############################################
# Function that gives the energy for parameters theta
#
# theta: parameters
# return: Energy
###########################################
"""
qc = qaoa_circuit(G,theta,p) # Gives the circuit of QAOA fot a graph G, parameters theta and p operators
counts = execute(qc, backend, seed_simulator=10).result().get_counts()# Run the circuit and get the results using the backedn "qasm_simulator"
E = 0 # Initial energy
total_counts = 0 # Initial counts
#Qiskit uses the least significant bit in the bistring, we need to invert this string
InvertedCounts = invert_counts(counts) #Inverted the binary string
# meas is the binary string measure
# meas_count is the number of times that the binary string has been measure
for meas, meas_count in InvertedCounts.items():
objective_function = maxcut_objective_function(meas, G)#Compute the maxcut objetive function fot the binary string meas
E += objective_function*meas_count # Define the energy as the value of the objective functions times the counts of that measure
total_counts += meas_count # The total number of measures in the system
return E/total_counts # Returns the energy given the parameters theta
return f
p = 5 # p is the number of QAOA alternating operators
objective_function = function_to_minimize(Graph, p)
x0=np.random.randn(10)#Initial parameters
minim_solution = minimize(objective_function, x0) # Minimization of scalar function of one or more variable from scipy
minim_solution
optimal_theta = minim_solution['x'] # The optimal parameters to use
optimal_theta
backend = Aer.get_backend('qasm_simulator')
qc = qaoa_circuit(Graph, optimal_theta,p) # Define the quantum circuit with the optimal parameters
counts = invert_counts(execute(qc, backend).result().get_counts()) # Get the results
#energies = {bs: maxcut_objective_function(bs, Graph) for bs, _ in counts.items()}
#energies_sorted = {bs: en for bs, en in sorted(energies.items(), key=lambda item: item[1])}
#print(energies_sorted)
#print({bs: counts[bs] for bs, energy in energies_sorted.items()})
# Compute the maxcut objective function for the optimal parameters
results = []
for x in counts.keys():
results.append([maxcut_objective_function(x,Graph),x])
# Get the best solution given the results of the maxcut objective function
best_cut, best_solution = min(results)
print(f"Best string: {best_solution} with cut: {-best_cut}")
# Define the colors of the nodes for the best solution
colors = ['r' if best_solution[node] == '0' else 'b' for node in Graph]
nx.draw(Graph,node_color = colors)
def solution_max_cut(G):
r"""
############################################
# Compute the solution for the maxcut problem given a graph G
#
# G: graph
# return:The draw of the best solution with two colors. Print the solution in the binary string form and the number of cuts
###############
"""
p = 5 # p is the number of QAOA alternating operators
objective_function = function_to_minimize(G, p)
x0=np.random.randn(10)#Initial parameters
new_parameters = minimize(objective_function, x0) # Minimization of scalar function of one or more variable from scipy
optimal_theta = new_parameters['x']# The optimal parameters to use
qc = qaoa_circuit(G, optimal_theta,p) # Define the quantum circuit with the optimal parameters
counts = invert_counts(execute(qc, backend).result().get_counts()) # Get the results
# Compute the maxcut objective function for the optimal parameters
results = []
for x in counts.keys():
results.append([maxcut_objective_function(x,G),x])
best_cut, best_solution = min(results) # Get the best solution given the results of the maxcut objective function
colors = ['r' if best_solution[node] == '0' else 'b' for node in G] # Define the colors of the nodes for the best solution
return nx.draw(G,node_color = colors),print(f"Best string: {best_solution} with cut: {-best_cut}")
Graph1 = nx.Graph()
Graph1.add_edges_from([[0,1],[0,2],[2,1]])
nx.draw(Graph1,with_labels=True)
solution_max_cut(Graph1)
graph2 = nx.random_regular_graph(3, 4, seed=1234)
nx.draw(graph2) #drawing the graph
plt.show() #plotting the graph
solution_max_cut(graph2)
graph3 = nx.random_regular_graph(3, 12, seed=1234)
nx.draw(graph3) #drawing the graph
plt.show() #plotting the graph
solution_max_cut(graph3)
|
https://github.com/victor-onofre/Quantum_Algorithms
|
victor-onofre
|
from qiskit import IBMQ, Aer
from qiskit.providers.ibmq import least_busy
from qiskit import QuantumCircuit, transpile, assemble
from qiskit.tools.monitor import job_monitor
import matplotlib as mpl
# import basic plot tools
from qiskit.visualization import plot_histogram, plot_bloch_multivector
import numpy as np
from numpy import pi
qft_circuit = QuantumCircuit(3)
qft_circuit.clear()
#input state= 5
qft_circuit.x(0)
qft_circuit.x(2)
qft_circuit.h(0)
qft_circuit.cp(pi/2,0,1)
qft_circuit.cp(pi/4,0,2)
qft_circuit.h(1)
qft_circuit.cp(pi/2,1,2)
qft_circuit.h(2)
#qft_circuit.swap(0,2)
qft_circuit.draw('mpl')
#output is the bloch sphere representation in the fourier basis
sim = Aer.get_backend("aer_simulator")
qft_circuit_init = qft_circuit.copy()
qft_circuit_init.save_statevector()
statevector = sim.run(qft_circuit_init).result().get_statevector()
plot_bloch_multivector(statevector)
IBMQ.save_account('')
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q')
backend = least_busy(provider.backends(filters=lambda b: b.configuration().n_qubits >= 2 and not b.configuration().simulator and b.status().operational==True))
print(backend)
t_qc = transpile(qft_circuit, backend, optimization_level=3)#transpile=assembling the circuit and everything
job = backend.run(t_qc)#backend means device
job_monitor(job)
|
https://github.com/victor-onofre/Quantum_Algorithms
|
victor-onofre
|
from qiskit import ClassicalRegister , QuantumCircuit, QuantumRegister
import numpy as np
qr = QuantumRegister(2)
cr = ClassicalRegister(3) #For tree classicals bites
qc = QuantumCircuit(qr , cr)
qc.h(qr[0]) #auxiliary qubit
qc.x(qr[1]) # eigenvector
#qc.cp((3/2)*np.pi , qr[0] , qr[1])
qc.cp(3*np.pi , qr[0] , qr[1])
qc.h(qr[0])
qc.measure(qr[0] , cr[0]) # this is the controlled-U^(2^n-1) operator for determine phi_n
qc.draw("mpl")
qc.reset(qr[0])
qc.h(qr[0])
# la valeur du bit du poids le plus faible est dans cr[0].
#Si cr[0] = 1 on enléve le bit de poids le plus faible en fesant la rotation alpha_2
#et on continu le bit n-1 devient le bit le bit de poids le plus faible
#si cr[0] est à 0 alors on peut appliquer directement la matrice unitaire associé sans avoir
#à faire de rotation inverse alpha_k
with qc.if_test((cr[0] , 1)) as else_:
qc.p(-np.pi/2 , qr[0])
#qc.cp((3/8)*np.pi , qr[0] ,qr[1])
qc.cp((3/2)*np.pi , qr[0] ,qr[1])
qc.h(qr[0]) # For make measure in X basis {|0> , |1>}
qc.measure(qr[0] , cr[1])
qc.draw("mpl")
qc.reset(qr[0])
qc.h(qr[0])
# la valeur du bit du poids le plus faible est dans cr[0].
#Si cr[0] = 1 on enléve le bit de poids le plus faible en fesant la rotation alpha_2
#et on continu le bit n-1 devient le bit le bit de poids le plus faible
#si cr[0] est à 0 alors on peut appliquer directement la matrice unitaire associé sans avoir
#à faire de rotation inverse alpha_k
with qc.if_test((cr[1] , 1)) as else_:
qc.p(-(3/4)*np.pi , qr[0])
qc.cp((3/4)*np.pi , qr[0] ,qr[1])
qc.h(qr[0]) # For make measure in X basis {|0> , |1>}
qc.measure(qr[0] , cr[2])
qc.draw("mpl")
from qiskit_aer import AerSimulator
sim = AerSimulator()
job = sim.run(qc, shots=1000)
result = job.result()
counts = result.get_counts()
counts
import qiskit.tools.jupyter
%qiskit_version_table
|
https://github.com/victor-onofre/Quantum_Algorithms
|
victor-onofre
|
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer, IBMQ, BasicAer
import math
from qiskit.visualization import plot_histogram
backend = BasicAer.get_backend('statevector_simulator')
from wordcloud import WordCloud
import numpy as np
import pandas as pd # primary data structure library
import matplotlib.pyplot as plt
reg = QuantumRegister(8, name='reg') # The quantum register of the qubits, in this case 8 qubits
reg_c = ClassicalRegister(8, name='regc') # Where the measurements of the qubits will be saved
qc = QuantumCircuit(reg, reg_c)
qc.h(reg) # Apply Hadamard gate to put it into a superposition of 0 and 1 all the qubits
qc.measure(reg, reg_c) # read the result as a digital bit
job = execute(qc, backend) # Execute the circuit in the statevector_simulator
result = job.result()
outputstate = result.get_statevector(qc, decimals=5)
counts = result.get_counts(qc)
#print(outputstate)
qc.draw()
state, value = list(counts.items())[0] # key is de state of the system after the measuremnt, for example '11100001'
state
number = int(state, 2) # The state is converted into a number
ASCII_Character = chr(number) # The number in ASCII character
print('The random number is:',number)
print('The random ASCII character:',ASCII_Character)
def Quantum_random_number_and_ASCII_Character_generator(n):
reg = QuantumRegister(n, name='reg') # The quantum register of the n qubits
reg_c = ClassicalRegister(n, name='regc')# Where the measurements of the qubits will be saved
qc = QuantumCircuit(reg, reg_c)
qc.h(reg) # put it into a superposition of 0 and 1
qc.measure(reg, reg_c) # read the result as a digital bit
job = execute(qc, backend)
result = job.result()
counts = result.get_counts(qc)
key, value = list(counts.items())[0]
number = int(key, 2)
ASCII_Character = chr(number)
return ASCII_Character, number
Quantum_random_number_and_ASCII_Character_generator(8)[0] # Resturns the ASCII Character
Quantum_random_number_and_ASCII_Character_generator(8)[1] # Resturns the Random number
L = []
num = []
counter = []
for x in range(800):
string = Quantum_random_number_and_ASCII_Character_generator(8)[0] # ASCII_Character
number = Quantum_random_number_and_ASCII_Character_generator(8)[1] # Random_number
L.append(string) # Save the ASCII_Character in a the list "L"
num.append(number) # Save the Random_number in a the list "number"
counter.append(x)
# Convert the list to a dataframe
df1 = pd.DataFrame(counter, columns=['Counter'])
df2 = pd.DataFrame(L, columns=['Random_Character'])
df3 = pd.DataFrame(num, columns=['Random_Number'])
#Join the results in a dataframe
re = df1.join(df2)
Quantum_Random = re.join(df3)
Quantum_Random.head()
Quantum_Random.plot(x='Counter', y='Random_Number', figsize=(25,6.5), xlabel='Iteration', ylabel='Randon Number', legend = False, grid = True, fontsize = 14)
Quantum_Random['Random_Number'].describe()
#generate the word cloud
wordcloud = WordCloud(background_color='white').generate(' '.join(Quantum_Random['Random_Character']))
# display the word cloud
fig = plt.figure()
fig.set_figwidth(14)
fig.set_figheight(18)
plt.imshow(wordcloud, interpolation='bilinear')
plt.axis('off')
plt.show()
|
https://github.com/victor-onofre/Quantum_Algorithms
|
victor-onofre
|
import cirq
import numpy as np
from qiskit import QuantumCircuit, execute, Aer
import seaborn as sns
import matplotlib.pyplot as plt
plt.rcParams['figure.figsize'] = (15,10)
q0, q1, q2 = [cirq.LineQubit(i) for i in range(3)]
circuit = cirq.Circuit()
#entagling the 2 quibits in different laboratories
#and preparing the qubit to send
circuit.append(cirq.H(q0))
circuit.append(cirq.H(q1))
circuit.append(cirq.CNOT(q1, q2))
#entangling the qubit we want to send to the one in the first laboratory
circuit.append(cirq.CNOT(q0, q1))
circuit.append(cirq.H(q0))
#measurements
circuit.append(cirq.measure(q0, q1))
#last transformations to obtain the qubit information
circuit.append(cirq.CNOT(q1, q2))
circuit.append(cirq.CZ(q0, q2))
#measure of the qubit in the receiving laboratory along z axis
circuit.append(cirq.measure(q2, key = 'Z'))
circuit
#starting simulation
sim = cirq.Simulator()
results = sim.run(circuit, repetitions=100)
sns.histplot(results.measurements['Z'], discrete = True)
100 - np.count_nonzero(results.measurements['Z']), np.count_nonzero(results.measurements['Z'])
#in qiskit the qubits are integrated in the circuit
qc = QuantumCircuit(3, 1)
#entangling
qc.h(0)
qc.h(1)
qc.cx(1, 2)
qc.cx(0, 1)
#setting for measurment
qc.h(0)
qc.measure([0,1], [0,0])
#transformation to obtain qubit sent
qc.cx(1, 2)
qc.cz(0, 2)
qc.measure(2, 0)
print(qc)
#simulation
simulator = Aer.get_backend('qasm_simulator')
job = execute(qc, simulator, shots=100)
res = job.result().get_counts(qc)
plt.bar(res.keys(), res.values())
res
|
https://github.com/victor-onofre/Quantum_Algorithms
|
victor-onofre
|
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer, IBMQ, BasicAer
from qiskit.visualization import plot_histogram
from qiskit.quantum_info import Statevector
import numpy as np
import matplotlib
style = {'backgroundcolor': 'lightyellow'} # Style of the circuits
backend = BasicAer.get_backend('qasm_simulator')
shots = 1024
qreg = QuantumRegister(6)
register1 = ClassicalRegister(5)
qc = QuantumCircuit(qreg, register1 )
qc.x(5)
qc.barrier()
qc.draw(output='mpl', style=style)
qc.h(0)
qc.h(1)
qc.h(2)
qc.h(3)
qc.h(4)
qc.h(5)
qc.barrier()
qc.draw(output='mpl', style=style)
qc.cx(0,5)
qc.cx(1,5)
qc.cx(4,5)
qc.barrier()
qc.draw(output='mpl', style=style)
qc.h(0)
qc.h(1)
qc.h(2)
qc.h(3)
qc.h(4)
qc.h(5)
qc.barrier()
qc.draw(output='mpl', style=style)
qc.measure(0, register1[0])
qc.measure(1, register1[1])
qc.measure(2, register1[2])
qc.measure(3, register1[3])
qc.measure(4, register1[4])
qc.draw(output='mpl', style=style)
results = execute(qc, backend=backend, shots=shots).result()
answer = results.get_counts()
plot_histogram(answer)
|
https://github.com/victor-onofre/Quantum_Algorithms
|
victor-onofre
|
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer, IBMQ, BasicAer
from qiskit.visualization import plot_bloch_multivector,plot_bloch_vector, plot_histogram, plot_state_qsphere
from qiskit.quantum_info import Statevector, partial_trace
import random
import numpy as np
import matplotlib
backend_statevector = BasicAer.get_backend('statevector_simulator')# This backend executes a single shot of a Qiskit QuantumCircuit and returns the final quantum statevector of the simulation.
style = {'backgroundcolor': 'lightyellow'} # Style of the circuits
backend_qasm = BasicAer.get_backend('qasm_simulator')# This backend is designed to mimic an actual device.
#It executes a Qiskit QuantumCircuit and returns a count dictionary containing the final values of any classical registers in the circuit.
shots = 1024 #Number of individual shots
qreg = QuantumRegister(2)
registerBell = ClassicalRegister(2)
qBell = QuantumCircuit(qreg,registerBell )
qBell.h(0)
qBell.cx(0,1)
qBell.draw(output='mpl', style=style)
out_vectorBell = execute(qBell, backend_statevector).result().get_statevector()
plot_state_qsphere(out_vectorBell)
qBell.measure(qreg[0],registerBell [0])
qBell.measure(qreg[1],registerBell [1])
qBell.draw(output='mpl', style=style)
results = execute(qBell, backend=backend_qasm, shots=shots).result()
answer = results.get_counts()
plot_histogram(answer)
def gate_errorX():
############################################################
# This function will return ['X'] with a probability 0.2 #
# ['Z'] with a probability 0.2 #
# and ['I'] with a probability 0.6 #
##########################################################
random_gate = random.choices(population= ['Z', 'X', 'I'],weights=[0.2,0.2, 0.6],k=1)
return(random_gate)
def noise(qcirc):
if gate_errorX() == ['X']:
### Bit-flip in the qubit 0 #####
qcirc.x(0)
elif gate_errorX() == ['Z']:
### phase-flip in the qubit 0 #####
qcirc.z(0)
else:
qcirc.i(0)
if gate_errorX() == ['X']:
### Bit-flip in the qubit 1 #####
qcirc.x(1)
elif gate_errorX() == ['Z']:
### phase-flip in the qubit 0 #####
qcirc.z(1)
else:
qcirc.i(1)
return qcirc
qregNoise = QuantumRegister(2)
registerBellNoise = ClassicalRegister(2)
qBellNoise = QuantumCircuit(qregNoise,registerBellNoise )
qBellNoise.h(0)
qBellNoise.barrier()
noise(qBellNoise)
#qBellNoise.z(0)
qBellNoise.barrier()
qBellNoise.cx(0,1)
qBellNoise.draw(output='mpl', style=style)
out_vectorBellNoise = execute(qBellNoise, backend_statevector).result().get_statevector()
plot_state_qsphere(out_vectorBellNoise)
plot_state_qsphere(out_vectorBell)
qBellNoise.measure(qregNoise[0],registerBellNoise[0])
qBellNoise.measure(qregNoise[1],registerBellNoise[1])
qBellNoise.draw(output='mpl', style=style)
resultsNoise = execute(qBellNoise, backend=backend_qasm, shots=shots).result()
answerNoise = resultsNoise.get_counts()
plot_histogram(answerNoise)
qreg_X1_Noise = QuantumRegister(2)
registerBell_X1_Noise = ClassicalRegister(2)
qBell_X1_Noise = QuantumCircuit(qreg_X1_Noise,registerBell_X1_Noise )
qBell_X1_Noise.h(0)
qBell_X1_Noise.barrier()
#noise(qBellNoise)
qBell_X1_Noise.x(1)
qBell_X1_Noise.barrier()
qBell_X1_Noise.cx(0,1)
qBell_X1_Noise.draw(output='mpl', style=style)
out_vectorBell_X1_Noise = execute(qBell_X1_Noise, backend_statevector).result().get_statevector()
plot_state_qsphere(out_vectorBell_X1_Noise)
Qreg1 = QuantumRegister(1)
Qreg2 = QuantumRegister(2)
qc_bit_flip = QuantumCircuit(Qreg1,Qreg2)
state_to_protect = [np.sqrt(0.2),np.sqrt(0.8)]
qc_bit_flip.initialize(state_to_protect,0) # Apply initialisation operation to the 0th qubit
qc_bit_flip.barrier()
Initial_state = Statevector.from_instruction(qc_bit_flip)
plot_bloch_multivector(Initial_state, title='Initial state')
qc_bit_flip.cx(0,1)
qc_bit_flip.cx(0,2)
qc_bit_flip.draw(output='mpl', style=style)
qc_bit_flip.barrier()
qc_bit_flip.x(0)
qc_bit_flip.barrier()
qc_bit_flip.cx(0,2)
qc_bit_flip.cx(0,1)
qc_bit_flip.barrier()
qc_bit_flip.ccx(2,1,0)
qc_bit_flip.draw(output='mpl', style=style)
out_vector = execute(qc_bit_flip, backend_statevector).result().get_statevector()
plot_bloch_multivector(out_vector, title='Final state')
plot_bloch_multivector(Initial_state, title='Initial state')
qregister1 = QuantumRegister(1)
qregister2 = QuantumRegister(2)
cregister = ClassicalRegister(2, 'c')
qc_bit_flip_measurements = QuantumCircuit(qregister1,qregister2,cregister)
qc_bit_flip_measurements.initialize(state_to_protect,0) # Apply initialisation operation to the 0th qubit
Initial_state1 = Statevector.from_instruction(qc_bit_flip_measurements)
plot_bloch_multivector(Initial_state1, title='Initial state')
### Perfmoing the encoding #####
qc_bit_flip_measurements.barrier()
qc_bit_flip_measurements.cx(0,1)
qc_bit_flip_measurements.cx(0,2)
### Apply some noise #####
qc_bit_flip_measurements.barrier()
#noise(qc)
qc_bit_flip_measurements.x(0)
### Aplying the inverse of the encoding procedure ###
qc_bit_flip_measurements.barrier()
qc_bit_flip_measurements.cx(0,2)
qc_bit_flip_measurements.cx(0,1)
qc_bit_flip_measurements.barrier()
qc_bit_flip_measurements.measure(qregister2,cregister)
qc_bit_flip_measurements.x(0).c_if(cregister, 3)
qc_bit_flip_measurements.draw(output='mpl', style=style)
out_vector1 = execute(qc_bit_flip_measurements, backend_statevector).result().get_statevector()
plot_bloch_multivector(out_vector1, title='Final state')
plot_bloch_multivector(Initial_state1, title='Initial state')
qEncoding = QuantumRegister(3)
qAncillas = QuantumRegister(2, 'ancilla')
AncillasRegister = ClassicalRegister(2, 'c')
qc_bit_flip_ancillas_measuremnts = QuantumCircuit(qEncoding,qAncillas,AncillasRegister)
qc_bit_flip_ancillas_measuremnts.initialize(state_to_protect,0) # Apply initialisation operation to the 0th qubit
Initial_state2 = Statevector.from_instruction(qc_bit_flip_ancillas_measuremnts)
plot_bloch_multivector(Initial_state2, title='Initial state')
### Perfmoing the encoding #####
qc_bit_flip_ancillas_measuremnts.barrier()
qc_bit_flip_ancillas_measuremnts.cx(0,1)
qc_bit_flip_ancillas_measuremnts.cx(0,2)
### Apply some noise #####
qc_bit_flip_ancillas_measuremnts.barrier()
#noise(qc)
qc_bit_flip_ancillas_measuremnts.x(0)
qc_bit_flip_ancillas_measuremnts.barrier()
qc_bit_flip_ancillas_measuremnts.cx(0,4)
qc_bit_flip_ancillas_measuremnts.cx(1,4)
qc_bit_flip_ancillas_measuremnts.barrier()
qc_bit_flip_ancillas_measuremnts.cx(1,3)
qc_bit_flip_ancillas_measuremnts.cx(2,3)
qc_bit_flip_ancillas_measuremnts.barrier()
qc_bit_flip_ancillas_measuremnts.measure(qAncillas,AncillasRegister)
qc_bit_flip_ancillas_measuremnts.x(0).c_if(AncillasRegister, 2)
qc_bit_flip_ancillas_measuremnts.x(1).c_if(AncillasRegister, 3)
qc_bit_flip_ancillas_measuremnts.x(2).c_if(AncillasRegister, 1)
qc_bit_flip_ancillas_measuremnts.barrier()
qc_bit_flip_ancillas_measuremnts.cx(0,2)
qc_bit_flip_ancillas_measuremnts.cx(0,1)
qc_bit_flip_ancillas_measuremnts.draw(output='mpl', style=style)
out_vector2 = execute(qc_bit_flip_ancillas_measuremnts,backend_statevector).result().get_statevector()
plot_bloch_multivector(out_vector2, title='Final state')
plot_bloch_multivector(Initial_state2, title='Initial state')
qregister_to_protect = QuantumRegister(1)
qregister = QuantumRegister(2)
creg = ClassicalRegister(2, 'c')
qc_phase_flip = QuantumCircuit(qregister_to_protect,qregister,creg)
qc_phase_flip.initialize(state_to_protect,0) # Apply initialisation operation to the 0th qubit
Initial_state3 = Statevector.from_instruction(qc_phase_flip)
plot_bloch_multivector(Initial_state3, title='Initial state')
### Perfmoing the encoding #####
qc_phase_flip.barrier()
qc_phase_flip.cx(0,1)
qc_phase_flip.cx(0,2)
### Apply thje hadamard gates #####
qc_phase_flip.barrier()
qc_phase_flip.h(0)
qc_phase_flip.h(1)
qc_phase_flip.h(2)
### Apply some noise #####
qc_phase_flip.barrier()
#noise(qc)
qc_phase_flip.z(0)
qc_phase_flip.barrier()
### Apply thje hadamard gates #####
qc_phase_flip.h(0)
qc_phase_flip.h(1)
qc_phase_flip.h(2)
### Aplying the inverse of the encoding procedure ###
qc_phase_flip.barrier()
qc_phase_flip.cx(0,2)
qc_phase_flip.cx(0,1)
qc_phase_flip.barrier()
qc_phase_flip.measure(qregister,creg)
qc_phase_flip.x(0).c_if(cregister, 3)
qc_phase_flip.draw(output='mpl', style=style)
out_vector4 = execute(qc_phase_flip, backend_statevector).result().get_statevector()
plot_bloch_multivector(out_vector4)
plot_bloch_multivector(Initial_state3, title='Initial state')
qregA = QuantumRegister(1)
qr1 = QuantumRegister(2)
qregB = QuantumRegister(1)
qr2 = QuantumRegister(2)
qregC = QuantumRegister(1)
qr3 = QuantumRegister(2)
r1 = ClassicalRegister(2, 'c1')
r2 = ClassicalRegister(2, 'c2')
r3 = ClassicalRegister(2, 'c3')
registerBC = ClassicalRegister(2, 'c')
qc_shor_code = QuantumCircuit(qregA, qr1,qregB, qr2,qregC,qr3,r1,r2,r3,registerBC)
qc_shor_code.initialize(state_to_protect,0) # Apply initialisation operation to the 0th qubit
qc_shor_code.barrier()
Initial_state4 = Statevector.from_instruction(qc_shor_code)
plot_bloch_multivector(Initial_state4, title='Initial state')
qc_shor_code.cx(0,3)
qc_shor_code.cx(0,6)
qc_shor_code.h(0)
qc_shor_code.h(3)
qc_shor_code.h(6)
qc_shor_code.barrier()
qc_shor_code.cx(0,1)
qc_shor_code.cx(0,2)
qc_shor_code.cx(3,4)
qc_shor_code.cx(3,5)
qc_shor_code.cx(6,7)
qc_shor_code.cx(6,8)
qc_shor_code.draw(output='mpl', style=style)
### Apply some gate error, in this case X y Z gate ###
qc_shor_code.barrier()
qc_shor_code.x(0)
qc_shor_code.z(6)
## This is the saame as the bit-flip code with measurements (Part 3.2) repeated 3 times ##
qc_shor_code.barrier()
qc_shor_code.cx(0,2)
qc_shor_code.cx(0,1)
qc_shor_code.cx(3,5)
qc_shor_code.cx(3,4)
qc_shor_code.cx(6,8)
qc_shor_code.cx(6,7)
qc_shor_code.barrier()
qc_shor_code.measure(qr1,r1)
qc_shor_code.measure(qr2,r2)
qc_shor_code.measure(qr3,r3)
qc_shor_code.x(qregA).c_if(r1, 3)
qc_shor_code.x(qregB).c_if(r2, 3)
qc_shor_code.x(qregC).c_if(r3, 3)
### Aplying the inverse of the encoding procedure ###
qc_shor_code.barrier()
qc_shor_code.h(0)
qc_shor_code.h(3)
qc_shor_code.h(6)
qc_shor_code.cx(0,6)
qc_shor_code.cx(0,3)
qc_shor_code.measure(qregB,registerBC[0])
qc_shor_code.measure(qregC,registerBC[1])
qc_shor_code.x(qregA).c_if(registerBC, 3)
qc_shor_code.draw(output='mpl', style=style, fold= 30)
out_vector5 = execute(qc_shor_code,backend_statevector).result().get_statevector()
plot_bloch_multivector(out_vector5)
reduced_state_shor_code = partial_trace(out_vector5 , [1,2,3,4,5,6,7,8])
plot_bloch_multivector(reduced_state_shor_code)
plot_bloch_multivector(Initial_state4, title='Initial state')
reduced_intial_state_shor_code = partial_trace(Initial_state4 , [1,2,3,4,5,6,7,8])
plot_bloch_multivector(reduced_intial_state_shor_code)
def shor_encoding(qc_shor_encode):
## Encoding for the shor code ##
################################
qc_shor_encode.cx(0,3)
qc_shor_encode.cx(0,6)
qc_shor_encode.h(0)
qc_shor_encode.h(3)
qc_shor_encode.h(6)
qc_shor_encode.barrier()
qc_shor_encode.cx(0,1)
qc_shor_encode.cx(0,2)
qc_shor_encode.cx(3,4)
qc_shor_encode.cx(3,5)
qc_shor_encode.cx(6,7)
qc_shor_encode.cx(6,8)
qc_shor_encode.barrier()
return(qc_shor_encode)
def shor_correct(qc_shor_code_correct,qCorrect_regA, qCorrect_r1,qCorrect_regB, qCorrect_r2,qCorrect_regC,qCorrect_r3,rCorrect1,rCorrect2,rCorrect3,registerCorrectBC ):
## Correction of the error in the shor code ##
##############################################
qc_shor_code_correct.barrier()
qc_shor_code_correct.cx(0,2)
qc_shor_code_correct.cx(0,1)
qc_shor_code_correct.cx(3,5)
qc_shor_code_correct.cx(3,4)
qc_shor_code_correct.cx(6,8)
qc_shor_code_correct.cx(6,7)
qc_shor_code_correct.barrier()
qc_shor_code_correct.measure(qCorrect_r1,rCorrect1)
qc_shor_code_correct.measure(qCorrect_r2,rCorrect2)
qc_shor_code_correct.measure(qCorrect_r3,rCorrect3)
qc_shor_code_correct.x(qCorrect_regA).c_if(rCorrect1, 3)
qc_shor_code_correct.x(qCorrect_regB).c_if(rCorrect2, 3)
qc_shor_code_correct.x(qCorrect_regC).c_if(rCorrect3, 3)
qc_shor_code_correct.barrier()
qc_shor_code_correct.h(0)
qc_shor_code_correct.h(3)
qc_shor_code_correct.h(6)
qc_shor_code_correct.cx(0,6)
qc_shor_code_correct.cx(0,3)
qc_shor_code_correct.measure(qCorrect_regB,registerCorrectBC[0])
qc_shor_code_correct.measure(qCorrect_regC,registerCorrectBC[1])
qc_shor_code_correct.x(qCorrect_regA).c_if(registerCorrectBC, 3)
return(qc_shor_code_correct)
### Ciruit to encode the state for the bit-flip code ####
q_Encoding_bit_flip_reg1 = QuantumRegister(1)
q_Encoding_bit_flip_reg2 = QuantumRegister(2)
qc_Encoding_bit_flip = QuantumCircuit(Qreg1,Qreg2)
qc_Encoding_bit_flip.cx(0,1)
qc_Encoding_bit_flip.cx(0,2)
### Ciruit to correct the state for the bit-flip code ####
qBit_flip_correct_register1 = QuantumRegister(1)
qBit_flip_correct_register2 = QuantumRegister(2)
cBit_flip_correct_register = ClassicalRegister(2, 'c')
qcBit_flip_correct = QuantumCircuit(qBit_flip_correct_register1,qBit_flip_correct_register2,cBit_flip_correct_register)
qcBit_flip_correct.barrier()
qcBit_flip_correct.cx(0,2)
qcBit_flip_correct.cx(0,1)
qcBit_flip_correct.barrier()
qcBit_flip_correct.measure(qBit_flip_correct_register2,cBit_flip_correct_register)
qcBit_flip_correct.x(0).c_if(cBit_flip_correct_register, 3)
qcBit_flip_correct.barrier()
q_To_Protect1 = QuantumRegister(1, name = 'state_to_protect1')
qCorrect_r1 = QuantumRegister(2)
qCorrect_regB = QuantumRegister(1)
qCorrect_r2 = QuantumRegister(2)
qCorrect_regC = QuantumRegister(1)
qCorrect_r3 = QuantumRegister(2)
rCorrect1 = ClassicalRegister(2, 'c1')
rCorrect2 = ClassicalRegister(2, 'c2')
rCorrect3 = ClassicalRegister(2, 'c3')
registerCorrectBC = ClassicalRegister(2, 'c')
q_To_Protect2 = QuantumRegister(1, name = 'state_to_protect2')
qregister_test2 = QuantumRegister(2)
qbell_test = QuantumCircuit(q_To_Protect1, qCorrect_r1,qCorrect_regB, qCorrect_r2,qCorrect_regC,qCorrect_r3,rCorrect1,rCorrect2,rCorrect3,registerCorrectBC, q_To_Protect2, qregister_test2)
qbell_test.h(0)
qbell_test.barrier()
qbell_test.draw(output='mpl', style=style)
shor_encoding(qbell_test)
new_qc1 = qbell_test.compose(qc_Encoding_bit_flip,[9,10,11])
new_qc1.draw(output='mpl', style=style)
new_qc1.barrier()
new_qc1.x(0)
new_qc1.z(9)
new_qc2 = new_qc1.compose(qcBit_flip_correct,[9,10,11])
shor_correct(new_qc2,q_To_Protect1, qCorrect_r1,qCorrect_regB, qCorrect_r2,qCorrect_regC,qCorrect_r3,rCorrect1,rCorrect2,rCorrect3,registerCorrectBC)
new_qc2.barrier()
new_qc2.cx(0,9)
new_qc2.draw(output='mpl', style=style, fold= 42)
out_vector8 = execute(new_qc2,backend_statevector).result().get_statevector()
reduced_state1 = partial_trace(out_vector8 , [1,2,3,4,5,6,7,8,10,11])
plot_state_qsphere(reduced_state1)
q_To_Protect1_ZX = QuantumRegister(1, name = 'state_to_protect1')
qCorrect_r1_ZX = QuantumRegister(2)
qCorrect_regB_ZX = QuantumRegister(1)
qCorrect_r2_ZX = QuantumRegister(2)
qCorrect_regC_ZX = QuantumRegister(1)
qCorrect_r3_ZX = QuantumRegister(2)
rCorrect1_ZX = ClassicalRegister(2, 'c1')
rCorrect2_ZX = ClassicalRegister(2, 'c2')
rCorrect3_ZX = ClassicalRegister(2, 'c3')
registerCorrectBC_ZX = ClassicalRegister(2, 'c')
q_To_Protect2_ZX = QuantumRegister(1, name = 'state_to_protect2')
qregister_test2_ZX = QuantumRegister(2)
qbell_test_ZX = QuantumCircuit(q_To_Protect1_ZX, qCorrect_r1_ZX,qCorrect_regB_ZX, qCorrect_r2_ZX,qCorrect_regC_ZX,qCorrect_r3_ZX,rCorrect1_ZX,rCorrect2_ZX,rCorrect3_ZX,registerCorrectBC_ZX, q_To_Protect2_ZX, qregister_test2_ZX)
qbell_test_ZX.h(0)
qbell_test_ZX.barrier()
shor_encoding(qbell_test_ZX)
new_qc1_ZX = qbell_test_ZX.compose(qc_Encoding_bit_flip,[9,10,11])
#### Error gates ######
new_qc1_ZX.barrier()
new_qc1_ZX.z(0)
new_qc1_ZX.x(9)
new_qc2_ZX = new_qc1_ZX.compose(qcBit_flip_correct,[9,10,11])
shor_correct(new_qc2_ZX,q_To_Protect1_ZX , qCorrect_r1_ZX ,qCorrect_regB_ZX, qCorrect_r2_ZX,qCorrect_regC_ZX,qCorrect_r3_ZX,rCorrect1_ZX,rCorrect2_ZX,rCorrect3_ZX,registerCorrectBC_ZX)
new_qc2_ZX.barrier()
new_qc2_ZX.cx(0,9)
new_qc2_ZX.draw(output='mpl', style=style, fold= 42)
out_vector8 = execute(new_qc2,backend_statevector).result().get_statevector()
reduced_state1 = partial_trace(out_vector8 , [1,2,3,4,5,6,7,8,10,11])
plot_state_qsphere(reduced_state1)
q_To_Protect1_YX = QuantumRegister(1, name = 'state_to_protect1')
qCorrect_r1_YX = QuantumRegister(2)
qCorrect_regB_YX = QuantumRegister(1)
qCorrect_r2_YX = QuantumRegister(2)
qCorrect_regC_YX = QuantumRegister(1)
qCorrect_r3_YX = QuantumRegister(2)
rCorrect1_YX = ClassicalRegister(2, 'c1')
rCorrect2_YX = ClassicalRegister(2, 'c2')
rCorrect3_YX = ClassicalRegister(2, 'c3')
registerCorrectBC_YX = ClassicalRegister(2, 'c')
q_To_Protect2_YX = QuantumRegister(1, name = 'state_to_protect2')
qregister_test2_YX = QuantumRegister(2)
qbell_test_YX = QuantumCircuit(q_To_Protect1_YX, qCorrect_r1_YX,qCorrect_regB_YX, qCorrect_r2_YX,qCorrect_regC_YX,qCorrect_r3_YX,rCorrect1_YX,rCorrect2_YX,rCorrect3_YX,registerCorrectBC_YX, q_To_Protect2_YX, qregister_test2_YX)
qbell_test_YX.h(0)
qbell_test_YX.barrier()
qbell_test_YX.draw(output='mpl', style=style)
shor_encoding(qbell_test_YX)
new_qc1_YX = qbell_test_YX.compose(qc_Encoding_bit_flip,[9,10,11])
#### Error gates ######
new_qc1_YX.barrier()
new_qc1_YX.y(0)
new_qc1_YX.x(9)
new_qc2_YX = new_qc1_YX.compose(qcBit_flip_correct,[9,10,11])
shor_correct(new_qc2_YX,q_To_Protect1_YX , qCorrect_r1_YX ,qCorrect_regB_YX, qCorrect_r2_YX,qCorrect_regC_YX,qCorrect_r3_YX,rCorrect1_YX,rCorrect2_YX,rCorrect3_YX,registerCorrectBC_YX)
new_qc2_YX.barrier()
new_qc2_YX.cx(0,9)
new_qc2_YX.draw(output='mpl', style=style, fold= 42)
out_vector9 = execute(new_qc2_YX,backend_statevector).result().get_statevector()
reduced_state2 = partial_trace(out_vector9 , [1,2,3,4,5,6,7,8,10,11])
plot_state_qsphere(reduced_state2)
def random_error_gate(qcirc):
if gate_errorX() == ['X']:
### Bit-flip in the qubit 0 #####
qcirc.x(0)
elif gate_errorX() == ['Z']:
### phase-flip in the qubit 0 #####
qcirc.z(0)
else:
qcirc.i(0)
if gate_errorX() == ['X']:
### Bit-flip in the qubit 9 #####
qcirc.x(9)
elif gate_errorX() == ['Z']:
### phase-flip in the qubit 9 #####
qcirc.z(9)
else:
qcirc.i(9)
return qcirc
q_To_Protect1_Random = QuantumRegister(1, name = 'state_to_protect1')
qCorrect_r1_Random = QuantumRegister(2)
qCorrect_regB_Random = QuantumRegister(1)
qCorrect_r2_Random = QuantumRegister(2)
qCorrect_regC_Random = QuantumRegister(1)
qCorrect_r3_Random = QuantumRegister(2)
rCorrect1_Random = ClassicalRegister(2, 'c1')
rCorrect2_Random = ClassicalRegister(2, 'c2')
rCorrect3_Random = ClassicalRegister(2, 'c3')
registerCorrectBC_Random = ClassicalRegister(2, 'c')
q_To_Protect2_Random = QuantumRegister(1, name = 'state_to_protect2')
qregister_test2_Random = QuantumRegister(2)
qbell_test_Random = QuantumCircuit(q_To_Protect1_Random, qCorrect_r1_Random,qCorrect_regB_Random, qCorrect_r2_Random,qCorrect_regC_Random,qCorrect_r3_Random,rCorrect1_Random,rCorrect2_Random,rCorrect3_Random,registerCorrectBC_Random, q_To_Protect2_Random, qregister_test2_Random)
qbell_test_Random.h(0)
qbell_test_Random.barrier()
shor_encoding(qbell_test_Random)
new_qc1_Random = qbell_test_Random.compose(qc_Encoding_bit_flip,[9,10,11])
#### Error gates ######
new_qc1_Random.barrier()
random_error_gate(new_qc1_Random)
################################
new_qc2_Random = new_qc1_Random.compose(qcBit_flip_correct,[9,10,11])
shor_correct(new_qc2_Random,q_To_Protect1_Random , qCorrect_r1_Random ,qCorrect_regB_Random, qCorrect_r2_Random,qCorrect_regC_Random,qCorrect_r3_Random,rCorrect1_Random,rCorrect2_Random,rCorrect3_Random,registerCorrectBC_Random)
new_qc2_Random.barrier()
new_qc2_Random.cx(0,9)
new_qc2_Random.draw(output='mpl', style=style, fold= 42)
out_vector10 = execute(new_qc2_Random,backend_statevector).result().get_statevector()
reduced_state3 = partial_trace(out_vector10 , [1,2,3,4,5,6,7,8,10,11])
plot_state_qsphere(reduced_state3)
|
https://github.com/victor-onofre/Quantum_Algorithms
|
victor-onofre
|
import qutip as qt # I use QuTip for the tensor and trace function
import numpy as np
H = qt.Qobj(np.matrix([[1.0 , 0.0 , 0.0 , 0.0 ]
,[0.0 , 0.0 ,-1.0 , 0.0 ]
,[0.0 ,-1.0 , 0.0 , 0.0 ]
,[0.0 , 0.0 , 0.0 , 1.0 ]]))
H
Id = qt.qeye(2); Sx = qt.sigmax(); Sy = qt.sigmay(); Sz = qt.sigmaz();
Pauli = [Id,Sx,Sy,Sz]
PauliLabels = ['Id' , 'Sx' , 'Sy' , 'Sz']
aij = 0;
for i in range(4):
for j in range(4):
PauliTensor = qt.Qobj(qt.tensor(Pauli[i], Pauli[j]).data.toarray(),dims=[[4],[4]]) # Tensor product of the pauli matrices (sigma_i (tensor) sigma_j), dims[[4],[4]] equal to dimens of H
aij = 0.25*( (PauliTensor*H ).tr()) #Elements of the descomposition
label1 = PauliLabels[i] #Label i to print
label2 = PauliLabels[j] #Label j to print
if aij!= 0:
print(aij, '*', label1, '(tensor)', label2 ) # Print the descomposition of the matrix
Id_tensor_Id = qt.tensor(Pauli[0], Pauli[0])
sx_tensor_sx = qt.tensor(Pauli[1], Pauli[1])
sy_tensor_sy = qt.tensor(Pauli[2], Pauli[2])
sz_tensor_sz = qt.tensor(Pauli[3], Pauli[3])
H_descomposition = 0.5*Id_tensor_Id - 0.5*sx_tensor_sx - 0.5*sy_tensor_sy + 0.5*sz_tensor_sz
H_descomposition_Dim = qt.Qobj(H_descomposition.data.toarray(),dims=[[4],[4]])
H_descomposition_Dim
from qiskit import QuantumCircuit, Aer, execute
from qiskit.visualization import plot_histogram
import matplotlib.pyplot as plt
def ansatz(circuit,angle):
circuit.h(0); circuit.id(1) #Apply (H \otimes I) |00>
circuit.cx(0,1) #Apply (CX)
circuit.rx(angle, 0); circuit.id(1) #Apply (Rx \otimes I)
return circuit
ansatzCircuit = QuantumCircuit(2)
ansatzCircuit = ansatz(ansatzCircuit,np.pi/4)
ansatzCircuit.draw()
def zz_meas(angle):
qc = QuantumCircuit(2) # qc is the quantum register of the qubits, in this case 2 qubits
qc = ansatz(qc,angle)
qc.measure_all()
return qc
zz = zz_meas(np.pi/4)
zz.draw()
def yy_meas(angle):
qc = QuantumCircuit(2) # qc is the quantum register of the qubits, in this case 2 qubits
qc = ansatz(qc,angle)
qc.barrier()
qc.h(0); qc.h(1) #Apply (H \otimes H) |00>
qc.sdg(0); qc.sdg(1) #Apply (S^{\dagger} \otimes S^{\dagger})
qc.measure_all()
return qc
yy = yy_meas(np.pi/4)
yy.draw()
def xx_meas(angle):
qc = QuantumCircuit(2) # qc is the quantum register of the qubits, in this case 2 qubits
qc = ansatz(qc,angle)
qc.barrier()
qc.h(0); qc.h(1) #Apply (H \otimes H) |00>
qc.measure_all()
return qc
xx = xx_meas(np.pi/4)
xx.draw()
def expectation(qcGiven):
simulator = Aer.get_backend('qasm_simulator') #Simulator for the measures
result = execute(qcGiven, backend = simulator, shots=10000).result() # Execute the quantum circuit (qcGiven) 10000 times
counts = result.get_counts(qcGiven) #Count the results
# 'if' for the times that there are not measure in the state [3]
if '00' not in counts:
counts['00'] = 0
if '01' not in counts:
counts['01'] = 0
if '10' not in counts:
counts['10'] = 0
if '11' not in counts:
counts['11'] = 0
total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10']
zzCounts = counts['00'] + counts['11'] - counts['01'] - counts['10']
zzCounts = zzCounts / total_counts
#plot_histogram(counts)
return zzCounts
E = []; # List where the estimations of the eigenvalue will be stored
anglelist = np.linspace(0.0,2*np.pi,200) # Parameter \theta for the minimization
def Eigenvalue_Approx(xx,yy,zz):
xx_value = expectation(xx)
yy_value = expectation(yy)
zz_value = expectation(zz)
EigenValue = 0.5 - (0.5)*xx_value - (0.5)*yy_value + (0.5)*zz_value # Estimate the expectation value of the matriz H
return EigenValue
for theta in anglelist:
xx = xx_meas(theta)
yy = yy_meas(theta)
zz = zz_meas(theta)
E.append(Eigenvalue_Approx(xx,yy,zz))
plt.figure(figsize = (10,4))
plt.plot(anglelist,E , linewidth=5)
plt.grid()
plt.xlabel(r'$\theta$', fontsize = 22)
plt.ylabel(r'$<{\psi(\theta)} | H |{\psi(\theta)} >$' , fontsize = 20)
plt.yticks(fontsize = 16)
plt.xticks([0.0, np.pi/4, np.pi/2, 3*np.pi/4 , np.pi, 5*np.pi/4 , 3*np.pi/2, 7*np.pi/4 , 2*np.pi],
[r'$0$', r'$\pi/4$', r'$\pi/2$', r'$3\pi/4$', r'$\pi$', r'$5\pi/4$', r'$3\pi/2$' , r'$7\pi/4$', r'$2\pi$' ], fontsize = 16)
plt.show()
MimimumEigenvalue = np.amin(E)
print('The estimated minimum eigenvalue of the matrix H from VQE algorithm is: {}'.format(MimimumEigenvalue))
evalsH, eketsH =H.eigenstates()
MimimumEigenvalue_Exact = np.amin(evalsH)
print('The exact minimum eigenvalue of the matrix H is: {}'.format(MimimumEigenvalue_Exact))
evalsH
evalsH[0]
|
https://github.com/victor-onofre/Quantum_Algorithms
|
victor-onofre
|
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer, IBMQ, BasicAer
import math
from qiskit.visualization import plot_histogram
backend = BasicAer.get_backend('statevector_simulator')
from wordcloud import WordCloud
import numpy as np
import pandas as pd # primary data structure library
import matplotlib.pyplot as plt
reg = QuantumRegister(8, name='reg') # The quantum register of the qubits, in this case 8 qubits
reg_c = ClassicalRegister(8, name='regc') # Where the measurements of the qubits will be saved
qc = QuantumCircuit(reg, reg_c)
qc.h(reg) # Apply Hadamard gate to put it into a superposition of 0 and 1 all the qubits
qc.measure(reg, reg_c) # read the result as a digital bit
job = execute(qc, backend) # Execute the circuit in the statevector_simulator
result = job.result()
outputstate = result.get_statevector(qc, decimals=5)
counts = result.get_counts(qc)
#print(outputstate)
qc.draw()
state, value = list(counts.items())[0] # key is de state of the system after the measuremnt, for example '11100001'
state
number = int(state, 2) # The state is converted into a number
ASCII_Character = chr(number) # The number in ASCII character
print('The random number is:',number)
print('The random ASCII character:',ASCII_Character)
def Quantum_random_number_and_ASCII_Character_generator(n):
reg = QuantumRegister(n, name='reg') # The quantum register of the n qubits
reg_c = ClassicalRegister(n, name='regc')# Where the measurements of the qubits will be saved
qc = QuantumCircuit(reg, reg_c)
qc.h(reg) # put it into a superposition of 0 and 1
qc.measure(reg, reg_c) # read the result as a digital bit
job = execute(qc, backend)
result = job.result()
counts = result.get_counts(qc)
key, value = list(counts.items())[0]
number = int(key, 2)
ASCII_Character = chr(number)
return ASCII_Character, number
Quantum_random_number_and_ASCII_Character_generator(8)[0] # Resturns the ASCII Character
Quantum_random_number_and_ASCII_Character_generator(8)[1] # Resturns the Random number
L = []
num = []
counter = []
for x in range(800):
string = Quantum_random_number_and_ASCII_Character_generator(8)[0] # ASCII_Character
number = Quantum_random_number_and_ASCII_Character_generator(8)[1] # Random_number
L.append(string) # Save the ASCII_Character in a the list "L"
num.append(number) # Save the Random_number in a the list "number"
counter.append(x)
# Convert the list to a dataframe
df1 = pd.DataFrame(counter, columns=['Counter'])
df2 = pd.DataFrame(L, columns=['Random_Character'])
df3 = pd.DataFrame(num, columns=['Random_Number'])
#Join the results in a dataframe
re = df1.join(df2)
Quantum_Random = re.join(df3)
Quantum_Random.head()
Quantum_Random.plot(x='Counter', y='Random_Number', figsize=(25,6.5), xlabel='Iteration', ylabel='Randon Number', legend = False, grid = True, fontsize = 14)
Quantum_Random['Random_Number'].describe()
#generate the word cloud
wordcloud = WordCloud(background_color='white').generate(' '.join(Quantum_Random['Random_Character']))
# display the word cloud
fig = plt.figure()
fig.set_figwidth(14)
fig.set_figheight(18)
plt.imshow(wordcloud, interpolation='bilinear')
plt.axis('off')
plt.show()
|
https://github.com/abhilash1910/EuroPython-21-QuantumDeepLearning
|
abhilash1910
|
!pip install pennylane
%load_ext tensorboard
import pennylane as qml
from pennylane import numpy as np
from pennylane.templates import RandomLayers
import tensorflow as tf
from tensorflow import keras
import matplotlib.pyplot as plt
import os
from datetime import datetime
%tensorboard --logdir logs/scalars/
tensorboard_callback = keras.callbacks.TensorBoard(
log_dir= "logs/scalars/" + datetime.now().strftime("%Y%m%d-%H%M%S"),
histogram_freq=0,
write_graph=True,
write_grads=True
)
n_epochs = 30 # Number of optimization epochs
n_layers = 1 # Number of random layers
n_train = 50 # Size of the train dataset
n_test = 30 # Size of the test dataset
SAVE_PATH = "quanvolution/" # Data saving folder
PREPROCESS = True # If False, skip quantum processing and load data from SAVE_PATH
np.random.seed(0) # Seed for NumPy random number generator
tf.random.set_seed(0) # Seed for TensorFlow random number generator
mnist_dataset = keras.datasets.mnist
(train_images, train_labels), (test_images, test_labels) = mnist_dataset.load_data()
# Reduce dataset size
train_images = train_images[:n_train]
train_labels = train_labels[:n_train]
test_images = test_images[:n_test]
test_labels = test_labels[:n_test]
# Normalize pixel values within 0 and 1
train_images = train_images / 255
test_images = test_images / 255
# Add extra dimension for convolution channels
train_images = np.array(train_images[..., tf.newaxis], requires_grad=False)
test_images = np.array(test_images[..., tf.newaxis], requires_grad=False)
dev = qml.device("default.qubit", wires=4)
# Random circuit parameters
rand_params = np.random.uniform(high=2 * np.pi, size=(n_layers, 4))
@qml.qnode(dev)
def circuit(phi):
# Encoding of 4 classical input values
for j in range(4):
qml.RY(np.pi * phi[j], wires=j)
# Random quantum circuit
RandomLayers(rand_params, wires=list(range(4)))
# Measurement producing 4 classical output values
return [qml.expval(qml.PauliZ(j)) for j in range(4)]
def quanv(image):
"""Convolves the input image with many applications of the same quantum circuit."""
out = np.zeros((14, 14, 4))
# Loop over the coordinates of the top-left pixel of 2X2 squares
for j in range(0, 28, 2):
for k in range(0, 28, 2):
# Process a squared 2x2 region of the image with a quantum circuit
q_results = circuit(
[
image[j, k, 0],
image[j, k + 1, 0],
image[j + 1, k, 0],
image[j + 1, k + 1, 0]
]
)
# Assign expectation values to different channels of the output pixel (j/2, k/2)
for c in range(4):
out[j // 2, k // 2, c] = q_results[c]
return out
if PREPROCESS == True:
q_train_images = []
print("Quantum pre-processing of train images:")
for idx, img in enumerate(train_images):
print("{}/{} ".format(idx + 1, n_train), end="\r")
q_train_images.append(quanv(img))
q_train_images = np.asarray(q_train_images)
q_test_images = []
print("\nQuantum pre-processing of test images:")
for idx, img in enumerate(test_images):
print("{}/{} ".format(idx + 1, n_test), end="\r")
q_test_images.append(quanv(img))
q_test_images = np.asarray(q_test_images)
# Save pre-processed images
if (os.path.exists(SAVE_PATH))==False:
os.makedirs(SAVE_PATH)
np.save(SAVE_PATH + "q_train_images.npy", q_train_images)
np.save(SAVE_PATH + "q_test_images.npy", q_test_images)
# Load pre-processed images
q_train_images = np.load(SAVE_PATH + "q_train_images.npy")
q_test_images = np.load(SAVE_PATH + "q_test_images.npy")
n_samples = 4
n_channels = 4
def plotter():
fig, axes = plt.subplots(1 + n_channels, n_samples, figsize=(10, 10))
for k in range(n_samples):
axes[0, 0].set_ylabel("Input")
if k != 0:
axes[0, k].yaxis.set_visible(False)
axes[0, k].imshow(train_images[k, :, :, 0], cmap="gray")
# Plot all output channels
for c in range(n_channels):
axes[c + 1, 0].set_ylabel("Output [ch. {}]".format(c))
if k != 0:
axes[c, k].yaxis.set_visible(False)
axes[c + 1, k].imshow(q_train_images[k, :, :, c], cmap="gray")
plt.tight_layout()
plt.show()
plotter()
def Model():
"""Initializes and returns a custom Keras model
which is ready to be trained."""
model = keras.models.Sequential([
keras.layers.Conv2D(32,(3,3),activation='relu'),
keras.layers.Flatten(),
keras.layers.Dense(12),
keras.layers.Dense(10, activation="softmax")
])
model.compile(
optimizer='adam',
loss="sparse_categorical_crossentropy",
metrics=["accuracy"],
)
return model
q_model = Model()
q_history = q_model.fit(
q_train_images,
train_labels,
validation_data=(q_test_images, test_labels),
batch_size=4,
epochs=n_epochs,
verbose=2,callbacks=[tensorboard_callback]
)
c_model = Model()
c_history = c_model.fit(
train_images,
train_labels,
validation_data=(test_images, test_labels),
batch_size=4,
epochs=n_epochs,
verbose=2,callbacks=[tensorboard_callback]
)
print(q_model.summary())
print(c_model.summary())
def plot_model(model,filename):
tf.keras.utils.plot_model(model, to_file=filename, show_shapes=False, show_dtype=False,show_layer_names=True, rankdir='TB', expand_nested=False, dpi=96)
plot_model(q_model,'QConv.png')
plot_model(c_model,'CConv.png')
|
https://github.com/abhilash1910/EuroPython-21-QuantumDeepLearning
|
abhilash1910
|
!pip install pennylane
# example of training a gan on mnist
from numpy import expand_dims
from numpy import zeros
from numpy import ones
from numpy import vstack
from numpy.random import randn
from numpy.random import randint
import tensorflow as tf
from keras.datasets.mnist import load_data
from keras.optimizers import Adam
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import Reshape
from keras.layers import Flatten
from keras.layers import Conv2D
from keras.layers import Conv2DTranspose
from keras.layers import LeakyReLU
from keras.layers import Dropout
from matplotlib import pyplot
import pennylane as qml
import numpy as np
num_wires=5
dev = qml.device('default.qubit', wires=5)
# variables
phi = [np.pi] * 12
for i in range(len(phi)):
phi[i] = phi[i] / np.random.randint(2, 12)
num_epochs = 30
eps = 1
initial_generator_weights = np.array([np.pi] + [0] * 44) + np.random.normal(scale=eps, size=(45,))
initial_discriminator_weights = np.random.normal(scale=eps, size=(35,))
generator_weights = tf.Variable(initial_generator_weights)
discriminator_weights = tf.Variable(initial_discriminator_weights)
opt = tf.keras.optimizers.Adam(0.4)
def real_data(phi, **kwargs):
# phi is a list with length 12
qml.Hadamard(wires=0)
qml.CNOT(wires=[0,1])
qml.RX(phi[0], wires=0)
qml.RY(phi[1], wires=0)
qml.RZ(phi[2], wires=0)
qml.RX(phi[3], wires=0)
qml.RY(phi[4], wires=0)
qml.RZ(phi[5], wires=0)
qml.CNOT(wires=[0, 1])
qml.RX(phi[6], wires=1)
qml.RY(phi[7], wires=1)
qml.RZ(phi[8], wires=1)
qml.RX(phi[9], wires=1)
qml.RY(phi[10], wires=1)
qml.RZ(phi[11], wires=1)
# the discriminator acts on wires 0, 1, and 4
def discriminator_layer(w, **kwargs):
qml.RX(w[0], wires=0)
qml.RX(w[1], wires=1)
qml.RX(w[2], wires=4)
qml.RZ(w[3], wires=0)
qml.RZ(w[4], wires=1)
qml.RZ(w[5], wires=4)
qml.MultiRZ(w[6], wires=[0, 1])
qml.MultiRZ(w[7], wires=[1, 4])
def discriminator(w, **kwargs):
qml.Hadamard(wires=0)
qml.CNOT(wires=[0,1])
discriminator_layer(w[:8])
discriminator_layer(w[8:16])
discriminator_layer(w[16:32])
qml.RX(w[32], wires=4)
qml.RY(w[33], wires=4)
qml.RZ(w[34], wires=4)
def generator_layer(w):
qml.RX(w[0], wires=0)
qml.RX(w[1], wires=1)
qml.RX(w[2], wires=2)
qml.RX(w[3], wires=3)
qml.RZ(w[4], wires=0)
qml.RZ(w[5], wires=1)
qml.RZ(w[6], wires=2)
qml.RZ(w[7], wires=3)
qml.MultiRZ(w[8], wires=[0, 1])
qml.MultiRZ(w[9], wires=[2, 3])
qml.MultiRZ(w[10], wires=[1, 2])
def generator(w, **kwargs):
qml.Hadamard(wires=0)
qml.CNOT(wires=[0,1])
generator_layer(w[:11])
generator_layer(w[11:22])
generator_layer(w[22:33]) # includes w[22], doesnt include w[33]
qml.RX(w[33], wires=0)
qml.RY(w[34], wires=0)
qml.RZ(w[35], wires=0)
qml.RX(w[36], wires=1)
qml.RY(w[37], wires=1)
qml.RZ(w[38], wires=1)
qml.CNOT(wires=[0, 1])
qml.RX(w[39], wires=0)
qml.RY(w[40], wires=0)
qml.RZ(w[41], wires=0)
qml.RX(w[42], wires=1)
qml.RY(w[43], wires=1)
qml.RZ(w[44], wires=1)
@qml.qnode(dev, interface='tf')
def real_discriminator(phi, discriminator_weights):
real_data(phi)
discriminator(discriminator_weights)
return qml.expval(qml.PauliZ(4))
@qml.qnode(dev, interface='tf')
def generator_discriminator(generator_weights, discriminator_weights):
generator(generator_weights)
discriminator(discriminator_weights)
return qml.expval(qml.PauliZ(4))
def probability_real_real(discriminator_weights):
# probability of guessing real data as real
discriminator_output = real_discriminator(phi, discriminator_weights) # the output of the discriminator classifying the data as real
probability_real_real = (discriminator_output + 1) / 2
return probability_real_real
def probability_fake_real(generator_weights, discriminator_weights):
# probability of guessing real fake as real
# incorrect classification
discriminator_output = generator_discriminator(generator_weights, discriminator_weights)
probability_fake_real = (discriminator_output + 1) / 2
return probability_fake_real
def discriminator_cost(discriminator_weights):
accuracy = probability_real_real(discriminator_weights) - probability_fake_real(generator_weights, discriminator_weights)
# accuracy = correct classification - incorrect classification
cost = -accuracy
return cost
def generator_cost(generator_weights):
accuracy = probability_fake_real(generator_weights, discriminator_weights)
# accuracy = probability that the generator fools the discriminator
cost = -accuracy
return cost
def train_discriminator():
for epoch in range(num_epochs):
cost = lambda: discriminator_cost(discriminator_weights)
# you need lambda because discriminator weights is a tensorflow object
opt.minimize(cost, discriminator_weights)
if epoch % 5 == 0:
cost_val = discriminator_cost(discriminator_weights).numpy()
print('Epoch {}/{}, Cost: {}, Probability class real as real: {}'.format(epoch, num_epochs, cost_val, probability_real_real(discriminator_weights).numpy()))
if epoch == num_epochs - 1:
print('\n')
def train_generator():
for epoch in range(num_epochs):
cost = lambda: generator_cost(generator_weights)
opt.minimize(cost, generator_weights)
if epoch % 5 == 0:
cost_val = generator_cost(generator_weights).numpy()
print('Epoch {}/{}, Cost: {}, Probability class fake as real: {}'.format(epoch, num_epochs, cost_val, probability_fake_real(generator_weights, discriminator_weights).numpy()))
if epoch == num_epochs - 1:
print('\n')
train_discriminator()
train_generator()
|
https://github.com/abhilash1910/EuroPython-21-QuantumDeepLearning
|
abhilash1910
|
!pip install pennylane
!pip install qiskit
import pennylane as qml
from pennylane.templates import AmplitudeEmbedding,BasisEmbedding,AngleEmbedding
import tensorflow as tf
from tensorflow import keras
device = qml.device('default.qubit', wires=2)
@qml.qnode(device)
def amplitude_circuit(inputs=None):
AmplitudeEmbedding(features=inputs, wires=range(2),normalize=True,pad_with=0.)
return qml.expval(qml.PauliZ(0))
@qml.qnode(device)
def basis_circuit(inputs=None):
BasisEmbedding(features=inputs, wires=range(2))
return qml.expval(qml.PauliZ(0))
@qml.qnode(device)
def angle_circuit(inputs=None):
AngleEmbedding(features=inputs, wires=range(2))
return qml.expval(qml.PauliZ(0))
inputs=[0.05,0.43]
z_a=amplitude_circuit(inputs)
z_an=angle_circuit(inputs)
print(f"Amplitude Embeddings: {z_a}")
print(f"Amplitude Embeddings: {z_an}")
from qiskit.visualization import plot_bloch_vector
%matplotlib inline
rot_1=[0,0,z_a]
rot_2=[0,0,z_an]
print("Bloch sphere for Amplitude Embedding")
plot_bloch_vector([rot_1], title="Bloch Sphere")
print("Bloch sphere for Angle Embedding")
plot_bloch_vector([rot_2], title="Bloch Sphere")
print("For Basis Embeddings, we need to encode n binary features to a basis state of n qubits.")
input_basis=[1,0]
z_b=basis_circuit(input_basis)
print(z_b)
print("Bloch sphere for Basis Embedding")
plot_bloch_vector([0,0,z_b], title="Bloch Sphere")
import tensorflow as tf
from tensorflow import keras
import os
from datetime import datetime
(x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data()
assert x_train.shape == (60000, 28, 28)
assert x_test.shape == (10000, 28, 28)
assert y_train.shape == (60000,)
assert y_test.shape == (10000,)
%load_ext tensorboard
%tensorboard --logdir logs/scalars/
tensorboard_callback = keras.callbacks.TensorBoard(
log_dir= "logs/scalars/" + datetime.now().strftime("%Y%m%d-%H%M%S"),
histogram_freq=0,
write_graph=True,
write_grads=True
)
'''Cerate 2 qubit node circuit with angle embedding and entangled layers'''
n_qubits = 2
@qml.qnode(device)
def qnode(inputs, weights):
qml.templates.AngleEmbedding(inputs, wires=range(n_qubits))
qml.templates.BasicEntanglerLayers(weights, wires=range(n_qubits))
return [qml.expval(qml.PauliZ(wires=i)) for i in range(n_qubits)]
def create_CQC_model(x_train,y_train,x_test,y_test):
'''Convert the q node circuit into a keras layer with a weight mapping'''
n_layers = 6
weight_shapes = {"weights": (n_layers, n_qubits)}
qlayer = qml.qnn.KerasLayer(qnode, weight_shapes, output_dim=n_qubits)
'''Initial layers for flattening the Image inputs and compress the features to pass it through the 2-bit node '''
clayer_0 = tf.keras.layers.Flatten(input_shape=(28,28))
clayer_1=tf.keras.layers.Dense(2)
'''Terminal layer with softmax activation for classification'''
clayer_2 = tf.keras.layers.Dense(10, activation="softmax")
model = tf.keras.models.Sequential([clayer_0,clayer_1,qlayer, clayer_2])
opt = tf.keras.optimizers.SGD(learning_rate=0.2)
model.compile(opt, loss="mae", metrics=["accuracy"])
model.fit(x_train,y_train,batch_size=128,epochs=10,verbose=2,validation_data=(x_test,y_test),callbacks=[tensorboard_callback])
model.summary()
'''Testing circuit on a small batch '''
x_train_n,y_train_n,x_test_n,y_test_n=x_train[:1000],y_train[:1000],x_test[:1000],y_test[:1000]
create_CQC_model(x_train_n,y_train_n,x_test_n,y_test_n)
import random
%load_ext tensorboard
%tensorboard --logdir logs/scalars/
tensorboard_callback = keras.callbacks.TensorBoard(
log_dir= "logs/scalars/" + datetime.now().strftime("%Y%m%d-%H%M%S"),
histogram_freq=0,
write_graph=True,
write_grads=True
)
n_qubits = 9
n_layer_steps = 3
n_layers_to_add = 2
batch_size = 128
epochs = 5
device = qml.device("default.qubit", wires=n_qubits)
def random_gates(n_qubits):
gates = [qml.RX, qml.RY, qml.RZ]
chosen_gates = []
for i in range(n_qubits):
chosen_gate = random.choice(gates)
chosen_gates.append(chosen_gate)
return chosen_gates
def apply_layer(gates, weights):
for i in range(n_qubits):
gates[i](weights[i], wires = i)
for i in range(n_qubits-1):
qml.CZ(wires=[i, i+1])
def apply_frozen_layers(frozen_layer_gates, frozen_layer_weights):
for i in range(len(frozen_layer_gates)):
apply_layer(frozen_layer_gates[i], frozen_layer_weights[i])
@qml.qnode(device,interface='tf')
def qnode(inputs,weights):
layer_gates = []
layer_weights = []
AngleEmbedding(inputs, wires=range(n_qubits))
# Apply frozen layers
new_gates = [random_gates(n_qubits) for i in range(n_layers_to_add)]
apply_frozen_layers(layer_gates, layer_weights)
# Apply layers with trainable parameters
for i in range(n_layers_to_add):
apply_layer(new_gates[i], weights[i])
# Expectation value of the last qubit
return [qml.expval(qml.PauliZ(wires=i)) for i in range(n_qubits)]
def create_CQC_frozen_model(x_train,y_train):
'''Convert the q node circuit into a keras layer with a weight mapping'''
# n_layers_to_add = 10
# Define shape of the weights
weight_shapes = {"weights": (n_layers_to_add, n_qubits)}
qlayer = qml.qnn.KerasLayer(qnode, weight_shapes,output_dim=n_qubits)
'''Initial layers for flattening the Image inputs and compress the features to pass it through the 2-bit node '''
clayer_0 = tf.keras.layers.Flatten(input_shape=(28,28))
clayer_1=tf.keras.layers.Dense(2)
'''Terminal layer with softmax activation for classification'''
clayer_2 = tf.keras.layers.Dense(2, activation="sigmoid")
model = tf.keras.models.Sequential([clayer_0,clayer_1,qlayer, clayer_2])
opt = tf.keras.optimizers.SGD(learning_rate=0.2)
model.compile(opt, loss="mae", metrics=["accuracy"])
print(model.summary())
model.fit(x_train,y_train,batch_size=128,epochs=10,verbose=2,callbacks=[tensorboard_callback])
model.summary()
'''Testing circuit on a small batch '''
#x_train_n,y_train_n,x_test_n,y_test_n=x_train[:1000],y_train[:1000],x_test[:1000],y_test[:1000]
create_CQC_frozen_model(modif_x_train,modif_y_train)
import numpy as np
import tensorflow as tf
from tensorflow import keras
import os
from datetime import datetime
(x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data()
assert x_train.shape == (60000, 28, 28)
assert x_test.shape == (10000, 28, 28)
assert y_train.shape == (60000,)
assert y_test.shape == (10000,)
modif_x_train=[]
modif_y_train=[]
for i in range(len(y_train)):
if y_train[i]==4:
modif_y_train.append(0)
modif_x_train.append(x_train[i])
elif y_train[i]==8:
modif_y_train.append(0)
modif_x_train.append(x_train[i])
modif_x_train,modif_y_train=np.asarray(modif_x_train),np.asarray(modif_y_train)
modif_x_train.shape,modif_y_train.shape,y_train.shape,x_train.shape
|
https://github.com/abhilash1910/EuroPython-21-QuantumDeepLearning
|
abhilash1910
|
!pip install qiskit
!pip install pennylane
import pennylane as qml
from pennylane import numpy as np
#Create a basic default Quantum circuit
#First , create a device to use the qubits
def create_device():
return qml.device("default.qubit",wires=1)
dev=create_device()
#Create an instance of Qnode() class which takes as parameters: the device name
@qml.qnode(dev)
def create_circuit(inputs):
qml.RX(inputs[0],wires=0)
qml.RY(inputs[1],wires=0)
#qml.CNOT(wires=[0,1])
return qml.expval(qml.PauliZ(0))#,qml.expval(qml.PauliZ(1))
d_circuit=qml.grad(create_circuit,argnum=0)
#Create a cost function to optimize
def cost_function(x):
return create_circuit(x)
#Creating an optimizer for gradient descent
def optimize(inputs):
grad_list=[]
opt=qml.AdagradOptimizer(stepsize=0.6,eps=1e-8)
steps=100
for i in range(steps):
inputs=opt.step(cost_function,inputs)
if (i + 1) % 5 == 0:
print("Cost after step {:5d}: {: .7f}".format(i + 1, cost_function(inputs)))
grad_list.append(cost_function(inputs))
print("Optimized rotation angles: {}".format(inputs))
return inputs,grad_list
inp=[0.011,0.012]
print("Cost Function values")
print(create_circuit(inp))
print(cost_function(inp))
print("Computing Adagrad Gradients")
inputs = np.array([0.011, 0.012])
angles,point=optimize(inputs)
print("Finalized gradients")
print(point[-1])
from qiskit.visualization import plot_bloch_vector
%matplotlib inline
rot_x=[0,0,point[-1]]
plot_bloch_vector(rot_x, title="Bloch Sphere")
dev = qml.device('default.qubit.tf', wires=["a","b"])
@qml.qnode(dev)
def dual_circuit(a):
qml.Hadamard("a")
qml.RX(a[0], wires=["a"])
qml.RY(a[1],wires=["b"])
return qml.expval(qml.PauliZ(0) @ qml.PauliZ(1))
def cost_fun(x):
return dual_circuit(x)
def plotter(circuit):
return qml.draw(circuit)
print("Input states to the Circuit")
inputs=[0.011,0.012]
print("Results after convergence")
results=optimize(inputs)
print("Drawing the circuit")
drawer=plotter(dual_circuit)
print(drawer(inputs))
|
https://github.com/abhilash1910/EuroPython-21-QuantumDeepLearning
|
abhilash1910
|
!pip install pennylane
!pip install qiskit
import pennylane as qml
from pennylane import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
device=qml.device("default.qubit",wires=2)
@qml.qnode(device,interface='tf')
def create_circuit(inputs):
qml.RX(inputs[0],wires=0)
qml.RY(inputs[1],wires=1)
qml.CNOT(wires=[0, 1])
return qml.expval(qml.PauliZ(0))
# return qml.expval(qml.PauliZ(0)@qml.PauliZ(1))
@tf.function
def cost_function(x,step):
val=-(-1)**(step//100)
#delta=tf.abs(tf.square(create_circuit(x)-val))
delta= tf.reduce_mean(tf.square(create_circuit(x)-val))
return delta
def initialize_tensor(angle_1,angle_2):
tensors=[]
phi=tf.Variable(angle_1)
theta=tf.Variable(angle_2)
tensors.append(phi)
tensors.append(theta)
return tensors
def optimize_circuit(tensors,steps):
g0,g1,g2,g3=[],[],[],[]
opt = tf.keras.optimizers.SGD(learning_rate=0.1)
for i in range(steps):
with tf.GradientTape() as tape:
loss=cost_function(tensors,i)
grads=tape.gradient(loss,tensors)
opt.apply_gradients(zip(grads, tensors))
g0.append(grads[0].numpy()[0])
g1.append(grads[0].numpy()[1])
g2.append(grads[1].numpy()[0])
g3.append(grads[1].numpy()[1])
if (i+1)%5==0:
print(f"Gradients after {i} iterations:")
print(f"Gradient 1:{grads[0]} ,Gradient 2:{grads[1]} For the provided input tensor")
plt.plot(g0)
#plt.plot(g1)
plt.plot(g2)
#plt.plot(g3)
plt.show()
return g0,g1,g2,g3
phi=[0.05,0.87]
theta=[0.43,0.034]
tf_tensors=initialize_tensor(phi,theta)
conj_angles=[phi,theta]
#create_circuit(conj_angles)
steps=200
g0,g1,g2,g3=optimize_circuit(tf_tensors,steps)
from qiskit.visualization import plot_bloch_vector
%matplotlib inline
final_anglex=g0[-1]
final_angley=g1[-1]
final_anglex1=g2[-1]
final_angley1=g3[-1]
rot_1=[final_anglex,final_angley,0]
rot_2=[final_anglex1,final_angley1,0]
plot_bloch_vector([rot_1], title="Bloch Sphere")
|
https://github.com/abhilash1910/EuroPython-21-QuantumDeepLearning
|
abhilash1910
|
# This cell is added by sphinx-gallery
# It can be customized to whatever you like
%matplotlib inline
!pip install pennylane
import pennylane as qml
from matplotlib import pyplot as plt
import numpy as np
import scipy
import networkx as nx
import copy
qubit_number = 4
qubits = range(qubit_number)
ising_graph = nx.cycle_graph(qubit_number)
print(f"Edges: {ising_graph.edges}")
nx.draw(ising_graph)
target_weights = [0.56, 1.24, 1.67, -0.79]
target_bias = [-1.44, -1.43, 1.18, -0.93]
def create_hamiltonian_matrix(n_qubits, graph, weights, bias):
full_matrix = np.zeros((2 ** n_qubits, 2 ** n_qubits))
# Creates the interaction component of the Hamiltonian
for i, edge in enumerate(graph.edges):
interaction_term = 1
for qubit in range(0, n_qubits):
if qubit in edge:
interaction_term = np.kron(interaction_term, qml.PauliZ.matrix)
else:
interaction_term = np.kron(interaction_term, np.identity(2))
full_matrix += weights[i] * interaction_term
# Creates the bias components of the matrix
for i in range(0, n_qubits):
z_term = x_term = 1
for j in range(0, n_qubits):
if j == i:
z_term = np.kron(z_term, qml.PauliZ.matrix)
x_term = np.kron(x_term, qml.PauliX.matrix)
else:
z_term = np.kron(z_term, np.identity(2))
x_term = np.kron(x_term, np.identity(2))
full_matrix += bias[i] * z_term + x_term
return full_matrix
# Prints a visual representation of the Hamiltonian matrix
ham_matrix = create_hamiltonian_matrix(qubit_number, ising_graph, target_weights, target_bias)
plt.matshow(ham_matrix, cmap="hot")
plt.show()
low_energy_state = [
(-0.054661080280306085 + 0.016713907320174026j),
(0.12290003656489545 - 0.03758500591109822j),
(0.3649337966440005 - 0.11158863596657455j),
(-0.8205175732627094 + 0.25093231967092877j),
(0.010369790825776609 - 0.0031706387262686003j),
(-0.02331544978544721 + 0.007129899300113728j),
(-0.06923183949694546 + 0.0211684344103713j),
(0.15566094863283836 - 0.04760201916285508j),
(0.014520590919500158 - 0.004441887836078486j),
(-0.032648113364535575 + 0.009988590222879195j),
(-0.09694382811137187 + 0.02965579457620536j),
(0.21796861485652747 - 0.06668776658411019j),
(-0.0027547112135013247 + 0.0008426289322652901j),
(0.006193695872468649 - 0.0018948418969390599j),
(0.018391279795405405 - 0.005625722994009138j),
(-0.041350974715649635 + 0.012650711602265649j),
]
res = np.vdot(low_energy_state, (ham_matrix @ low_energy_state))
energy_exp = np.real_if_close(res)
print(f"Energy Expectation: {energy_exp}")
ground_state_energy = np.real_if_close(min(np.linalg.eig(ham_matrix)[0]))
print(f"Ground State Energy: {ground_state_energy}")
def state_evolve(hamiltonian, qubits, time):
U = scipy.linalg.expm(-1j * hamiltonian * time)
qml.QubitUnitary(U, wires=qubits)
def qgrnn_layer(weights, bias, qubits, graph, trotter_step):
# Applies a layer of RZZ gates (based on a graph)
for i, edge in enumerate(graph.edges):
qml.MultiRZ(2 * weights[i] * trotter_step, wires=(edge[0], edge[1]))
# Applies a layer of RZ gates
for i, qubit in enumerate(qubits):
qml.RZ(2 * bias[i] * trotter_step, wires=qubit)
# Applies a layer of RX gates
for qubit in qubits:
qml.RX(2 * trotter_step, wires=qubit)
def swap_test(control, register1, register2):
qml.Hadamard(wires=control)
for reg1_qubit, reg2_qubit in zip(register1, register2):
qml.CSWAP(wires=(control, reg1_qubit, reg2_qubit))
qml.Hadamard(wires=control)
# Defines some fixed values
reg1 = tuple(range(qubit_number)) # First qubit register
reg2 = tuple(range(qubit_number, 2 * qubit_number)) # Second qubit register
control = 2 * qubit_number # Index of control qubit
trotter_step = 0.01 # Trotter step size
# Defines the interaction graph for the new qubit system
new_ising_graph = nx.complete_graph(reg2)
print(f"Edges: {new_ising_graph.edges}")
nx.draw(new_ising_graph)
def qgrnn(weights, bias, time=None):
# Prepares the low energy state in the two registers
qml.QubitStateVector(np.kron(low_energy_state, low_energy_state), wires=reg1 + reg2)
# Evolves the first qubit register with the time-evolution circuit to
# prepare a piece of quantum data
state_evolve(ham_matrix, reg1, time)
# Applies the QGRNN layers to the second qubit register
depth = time / trotter_step # P = t/Delta
for _ in range(0, int(depth)):
qgrnn_layer(weights, bias, reg2, new_ising_graph, trotter_step)
# Applies the SWAP test between the registers
swap_test(control, reg1, reg2)
# Returns the results of the SWAP test
return qml.expval(qml.PauliZ(control))
N = 15 # The number of pieces of quantum data that are used for each step
max_time = 0.1 # The maximum value of time that can be used for quantum data
rng = np.random.default_rng(seed=42)
def cost_function(weight_params, bias_params):
# Randomly samples times at which the QGRNN runs
times_sampled = rng.random(size=N) * max_time
# Cycles through each of the sampled times and calculates the cost
total_cost = 0
for dt in times_sampled:
result = qgrnn_qnode(weight_params, bias_params, time=dt)
total_cost += -1 * result
return total_cost / N
# Defines the new device
qgrnn_dev = qml.device("default.qubit", wires=2 * qubit_number + 1)
# Defines the new QNode
qgrnn_qnode = qml.QNode(qgrnn, qgrnn_dev)
steps = 20
optimizer = qml.AdamOptimizer(stepsize=0.5)
weights = rng.random(size=len(new_ising_graph.edges)) - 0.5
bias = rng.random(size=qubit_number) - 0.5
initial_weights = copy.copy(weights)
initial_bias = copy.copy(bias)
for i in range(0, steps):
(weights, bias), cost = optimizer.step_and_cost(cost_function, weights, bias)
# Prints the value of the cost function
if i % 5 == 0:
print(f"Cost at Step {i}: {cost}")
print(f"Weights at Step {i}: {weights}")
print(f"Bias at Step {i}: {bias}")
print("---------------------------------------------")
new_ham_matrix = create_hamiltonian_matrix(
qubit_number, nx.complete_graph(qubit_number), weights, bias
)
init_ham = create_hamiltonian_matrix(
qubit_number, nx.complete_graph(qubit_number), initial_weights, initial_bias
)
fig, axes = plt.subplots(nrows=1, ncols=3, figsize=(6, 6))
axes[0].matshow(ham_matrix, vmin=-7, vmax=7, cmap="hot")
axes[0].set_title("Target", y=1.13)
axes[1].matshow(init_ham, vmin=-7, vmax=7, cmap="hot")
axes[1].set_title("Initial", y=1.13)
axes[2].matshow(new_ham_matrix, vmin=-7, vmax=7, cmap="hot")
axes[2].set_title("Learned", y=1.13)
plt.subplots_adjust(wspace=0.3, hspace=0.3)
plt.show()
# We first pick out the weights of edges (1, 3) and (2, 0)
# and then remove them from the list of target parameters
weights_noedge = []
weights_edge = []
for ii, edge in enumerate(new_ising_graph.edges):
if (edge[0] - qubit_number, edge[1] - qubit_number) in ising_graph.edges:
weights_edge.append(weights[ii])
else:
weights_noedge.append(weights[ii])
print("Target parameters Learned parameters")
print("Weights")
print("-" * 41)
for ii_target, ii_learned in zip(target_weights, weights_edge):
print(f"{ii_target : <20}|{ii_learned : >20}")
print("\nBias")
print("-"*41)
for ii_target, ii_learned in zip(target_bias, bias):
print(f"{ii_target : <20}|{ii_learned : >20}")
print(f"\nNon-Existing Edge Parameters: {[val.unwrap() for val in weights_noedge]}")
|
https://github.com/abhilash1910/EuroPython-21-QuantumDeepLearning
|
abhilash1910
|
!apt-get install -y xvfb python-opengl > /dev/null 2>&1
!pip install gym pyvirtualdisplay > /dev/null 2>&1
!pip install pennylane
!pip install pyvirtualdisplay
#PPO-A2C for CartPole
import gym
import numpy as np
import tensorflow as tf
from tensorflow import keras
from datetime import datetime
from keras.models import Sequential
from keras.layers import Dense, Reshape, Flatten
from keras.optimizers import Adam
from keras.layers.convolutional import Convolution2D
import matplotlib.pyplot as plt
from IPython import display as ipythondisplay
from pyvirtualdisplay import Display
from keras import backend as k
import pennylane as qml
from pennylane.templates import AmplitudeEmbedding,BasisEmbedding,AngleEmbedding
import random
%load_ext tensorboard
%tensorboard --logdir logs/scalars/
log_dir= "logs/scalars/" + datetime.now().strftime("%Y%m%d-%H%M%S")
tensorboard_callback = keras.callbacks.TensorBoard(
log_dir= "logs/scalars/" + datetime.now().strftime("%Y%m%d-%H%M%S"),
histogram_freq=0,
write_graph=True,
write_grads=True
)
train_names = ['train_loss']
display = Display(visible=0, size=(400, 300))
display.start()
n_qubits = 9
n_layer_steps = 3
n_layers_to_add = 2
batch_size = 128
epochs = 5
device = qml.device("default.qubit", wires=n_qubits)
def random_gates(n_qubits):
gates = [qml.RX, qml.RY, qml.RZ]
chosen_gates = []
for i in range(n_qubits):
chosen_gate = random.choice(gates)
chosen_gates.append(chosen_gate)
return chosen_gates
def apply_layer(gates, weights):
for i in range(n_qubits):
gates[i](weights[i], wires = i)
for i in range(n_qubits-1):
qml.CZ(wires=[i, i+1])
def apply_frozen_layers(frozen_layer_gates, frozen_layer_weights):
for i in range(len(frozen_layer_gates)):
apply_layer(frozen_layer_gates[i], frozen_layer_weights[i])
@qml.qnode(device,interface='tf')
def qnode(inputs,weights):
layer_gates = []
layer_weights = []
AngleEmbedding(inputs, wires=range(n_qubits))
# Apply frozen layers
new_gates = [random_gates(n_qubits) for i in range(n_layers_to_add)]
apply_frozen_layers(layer_gates, layer_weights)
# Apply layers with trainable parameters
for i in range(n_layers_to_add):
apply_layer(new_gates[i], weights[i])
# Expectation value of the last qubit
return [qml.expval(qml.PauliZ(wires=i)) for i in range(n_qubits)]
def write_log(callback, names, logs, batch_no):
writer = tf.summary.create_file_writer(log_dir)
with writer.as_default():
for step in range(batch_no):
tf.summary.scalar(names[0], logs, step=step)
writer.flush()
# summary = tf.Summary()
# summary_value = summary.value.add()
# summary_value.simple_value = logs
# summary_value.tag = names
# callback.writer.add_summary(summary, batch_no)
# callback.writer.flush()
class PPOAgent:
def __init__(self,state_size,action_size):
self.state_size=state_size
self.action_size=action_size
self.gamma=0.99
self.learning_rate=0.001
self.states=[]
self.rewards=[]
self.labels=[]
self.prob=[]
self.Actor=self.build_actor_model()
self.Critic=self.build_critic_model()
self.Critic.summary()
def build_actor_model(self):
logdir= "logs/scalars/" + datetime.now().strftime("%Y%m%d-%H%M%S")
tensorboard_callback=keras.callbacks.TensorBoard(log_dir=logdir)
weight_shapes = {"weights": (n_layers_to_add, n_qubits)}
qlayer = qml.qnn.KerasLayer(qnode, weight_shapes,output_dim=n_qubits)
clayer_0= tf.keras.layers.Dense(64,input_dim=self.state_size,activation='relu',kernel_initializer='glorot_uniform')
clayer_1= tf.keras.layers.Dense(9,activation='relu',kernel_initializer='glorot_uniform')
clayer_2= tf.keras.layers.Dense(64,activation='relu',kernel_initializer='glorot_uniform')
clayer_3= tf.keras.layers.Dense(self.action_size,activation='softmax')
Actor = tf.keras.models.Sequential([clayer_0,clayer_1,qlayer, clayer_2,clayer_3])
def trpo_ppo_clip_loss(y_true,y_pred):
entropy=2e-5
clip_loss=0.2
old_log= k.sum(y_true)
print(old_log)
pred_log=k.sum(y_pred)
print(pred_log)
r=pred_log/(old_log + 1e-9)
advantage=pred_log-old_log
p1=r*advantage
p2=k.clip(r,min_value=1-clip_loss,max_value=1+clip_loss)*advantage
prob=1e-2
loss=-k.mean(k.minimum(p1,p2) + entropy*(-(prob*k.log(prob+1e-10))))
return loss
def trpo_ppo_penalty_loss(y_true,y_pred):
entropy=2e-5
clip_loss=0.2
old_log= k.sum(y_true)
print(old_log)
pred_log=k.sum(y_pred)
print(pred_log)
r=pred_log/(old_log + 1e-9)
kl_divergence= k.sum(old_log* k.log(old_log/pred_log))
advantage=kl_divergence
p1=r*advantage
p2=k.clip(r,min_value=1-clip_loss,max_value=1+clip_loss)*advantage
prob=1e-2
loss=-k.mean(k.minimum(p1,p2) + entropy*(-(prob*k.log(prob+1e-10))))
return loss
Actor.compile(optimizer=Adam(learning_rate=self.learning_rate),loss=trpo_ppo_penalty_loss)
return Actor
def build_critic_model(self):
logdir= "logs/scalars/" + datetime.now().strftime("%Y%m%d-%H%M%S")
tensorboard_callback=keras.callbacks.TensorBoard(log_dir=logdir)
Critic=Sequential()
Critic.add(Dense(64,input_dim=self.state_size,activation='relu',kernel_initializer='glorot_uniform'))
Critic.add(Dense(64,activation='relu',kernel_initializer='glorot_uniform'))
Critic.add(Dense(self.action_size,activation='softmax'))
Critic.compile(optimizer=Adam(learning_rate=self.learning_rate),loss='categorical_crossentropy')
return Critic
def memory(self,state,action,prob,reward):
y=np.zeros([self.action_size])
y[action]=1
self.labels.append(np.array(y).astype('float32'))
self.states.append(state)
self.rewards.append(reward)
def act(self,state):
state=state.reshape([1,state.shape[0]])
probs=self.Critic.predict(state,batch_size=1).flatten()
self.prob.append(probs)
action=np.random.choice(self.action_size,1,p=probs)[0]
return action,probs
def discount_rewards(self, rewards):
discounted_rewards = np.zeros_like(rewards)
running_sum = 0
for t in reversed(range(len(rewards))):
if rewards[t] != 0:
running_add = 0
running_add = running_add * self.gamma + rewards[t]
discounted_rewards[t] = running_add
return discounted_rewards
def train(self,batch_no):
labels=np.vstack(self.labels)
rewards=np.vstack(self.rewards)
rewards=self.discount_rewards(rewards)
rewards=(rewards-np.mean(rewards))/np.std(rewards)
labels*=-rewards
x=np.squeeze(np.vstack([self.states]))
y=np.squeeze(np.vstack([self.labels]))
tensorboard_callback.set_model(self.Actor)
logs_actor=self.Actor.train_on_batch(x,y)
logs_critic=self.Critic.train_on_batch(x,y)
write_log(tensorboard_callback, train_names, logs_actor, batch_no)
self.states,self.probs,self.labels,self.rewards=[],[],[],[]
def load_model(self,name):
self.Actor.load_weights(name)
self.Critic.load_weights(name)
def save_model(self,name):
self.Actor.save_weights(name)
self.Critic.save_weights(name)
self.Critic.save_weights(name)
if __name__=="__main__":
env=gym.make('CartPole-v0')
state=env.reset()
score=0
episode=0
state_size=env.observation_space.shape[0]
action_size=env.action_space.n
agent=PPOAgent(state_size,action_size)
j=0
while j is not 2000:
screen = env.render(mode='rgb_array')
action,prob=agent.act(state)
state_1,reward,done,_=env.step(action)
score+=reward
agent.memory(state,action,prob,reward)
state=state_1
plt.imshow(screen)
ipythondisplay.clear_output(wait=True)
ipythondisplay.display(plt.gcf())
if done:
j+=1
agent.rewards[-1]=score
agent.train(j)
print("Episode: %d - Score: %f."%(j,score))
score=0.0
state=env.reset()
env.close()
|
https://github.com/JavaFXpert/think2020
|
JavaFXpert
|
%matplotlib inline
# Importing standard Qiskit libraries and configuring account
from qiskit import QuantumCircuit, execute, Aer, IBMQ
from qiskit.compiler import transpile, assemble
from qiskit.tools.jupyter import *
from qiskit.visualization import *
# Loading your IBM Q account(s)
provider = IBMQ.load_account()
# Create a quantum circuit containing three quantum bits, and three classical bits to hold measurement results.
# REPLACE THIS WITH CODE
# REPLACE THIS WITH CODE
def answer(result):
for key in result.keys():
state = key
print('The Quantum 8-ball says:')
if state == '000':
print('It is certain.')
elif state == '001':
print('Without a doubt.')
elif state == '010':
print('Yes - definitely.')
elif state == '011':
print('Most likely.')
elif state == '100':
print("Don't count on it.")
elif state == '101':
print('My reply is no.')
elif state == '110':
print('Very doubtful.')
else:
print('Concentrate and ask again.')
job = execute(qc, backend=Aer.get_backend('qasm_simulator'), shots=1)
counts = job.result().get_counts(qc)
answer(counts)
from qiskit.quantum_info import Statevector
# REPLACE THIS WITH CODE THAT USES THE from_instruction()
# AND sample_counts() METHODS OF THE Statevector class
|
https://github.com/JavaFXpert/think2020
|
JavaFXpert
|
%matplotlib inline
# Importing standard Qiskit libraries and configuring account
from qiskit import QuantumCircuit, execute, Aer, IBMQ
from qiskit.compiler import transpile, assemble
from qiskit.tools.jupyter import *
from qiskit.visualization import *
# Loading your IBM Q account(s)
provider = IBMQ.load_account()
# Create a quantum circuit containing three quantum bits, and three classical bits to hold measurement results.
qc = QuantumCircuit(3, 3)
qc.h(0)
qc.h(1)
qc.h(2)
qc.measure(range(3),range(3))
qc.draw()
def answer(result):
for key in result.keys():
state = key
print('The Quantum 8-ball says:')
if state == '000':
print('It is certain.')
elif state == '001':
print('Without a doubt.')
elif state == '010':
print('Yes - definitely.')
elif state == '011':
print('Most likely.')
elif state == '100':
print("Don't count on it.")
elif state == '101':
print('My reply is no.')
elif state == '110':
print('Very doubtful.')
else:
print('Concentrate and ask again.')
job = execute(qc, backend=Aer.get_backend('qasm_simulator'), shots=1)
counts = job.result().get_counts(qc)
answer(counts)
from qiskit.quantum_info import Statevector
qc = QuantumCircuit(3)
qc.h(0)
qc.h(1)
qc.h(2)
sv = Statevector.from_instruction(qc)
counts = sv.sample_counts(shots = 1)
answer(counts)
|
https://github.com/sergiogh/qpirates-qiskit-notebooks
|
sergiogh
|
from qiskit.aqua.algorithms import NumPyMinimumEigensolver
from qiskit.optimization.algorithms import GroverOptimizer, MinimumEigenOptimizer
from qiskit.optimization.problems import QuadraticProgram
from qiskit import BasicAer
from docplex.mp.model import Model
backend = BasicAer.get_backend('statevector_simulator')
model = Model()
x0 = model.binary_var(name='x0')
x1 = model.binary_var(name='x1')
x2 = model.binary_var(name='x2')
model.minimize(-x0+2*x1-3*x2-2*x0*x2-1*x1*x2)
qp = QuadraticProgram()
qp.from_docplex(model)
print(qp.export_as_lp_string())
grover_optimizer = GroverOptimizer(6, num_iterations=10, quantum_instance=backend)
results = grover_optimizer.solve(qp)
print("x={}".format(results.x))
print("fval={}".format(results.fval))
import matplotlib.pyplot as plt
import matplotlib.axes as axes
%matplotlib inline
import numpy as np
import networkx as nx
from qiskit.aqua import QuantumInstance
from qiskit.optimization.applications.ising import max_cut, tsp
from qiskit.optimization.converters import IsingToQuadraticProgram
n = 4
num_qubits = n ** 2
ins = tsp.random_tsp(n, seed=123)
G = nx.Graph()
G.add_nodes_from(np.arange(0, n, 1))
colors = ['r' for node in G.nodes()]
pos = {k: v for k, v in enumerate(ins.coord)}
default_axes = plt.axes(frameon=True)
nx.draw_networkx(G, node_color=colors, node_size=600, alpha=.8, ax=default_axes, pos=pos)
print('distance\n', ins.w)
qubitOp, offset = tsp.get_operator(ins)
print('Offset:', offset)
print('Ising Hamiltonian:')
print(qubitOp.print_details())
qp = QuadraticProgram()
qp.from_ising(qubitOp, offset, linear=True)
qp.to_docplex().prettyprint()
grover_optimizer = GroverOptimizer(6, num_iterations=10, quantum_instance=backend)
results = grover_optimizer.solve(qp)
print("x={}".format(results.x))
print("fval={}".format(results.fval))
# Test with classical EigenOptimizer
from qiskit.aqua.algorithms import NumPyMinimumEigensolver
from qiskit.optimization.algorithms import MinimumEigenOptimizer
exact_solver = MinimumEigenOptimizer(NumPyMinimumEigensolver())
exact_result = exact_solver.solve(qp)`
print("x={}".format(exact_result.x))
print("fval={}".format(exact_result.fval))
|
https://github.com/sergiogh/qpirates-qiskit-notebooks
|
sergiogh
|
import numpy as np
from qiskit import BasicAer
from qiskit.visualization import plot_histogram
from qiskit.aqua import QuantumInstance
from qiskit.aqua.algorithms import Grover
from qiskit.aqua.components.oracles import LogicalExpressionOracle, TruthTableOracle
"""
Examples:
c This is an example DIMACS CNF file with 3 satisfying assignments: 1 -2 3, -1 -2 -3, 1 2 -3.
p cnf 3 5
-1 -2 -3 0
1 -2 3 0
1 2 -3 0
1 -2 -3 0
-1 2 3 0
(¬𝑥1∨¬𝑥2∨¬𝑥3)∧(𝑥1∨¬𝑥2∨𝑥3)∧(𝑥1∨𝑥2∨¬𝑥3)∧(𝑥1∨¬𝑥2∨¬𝑥3)∧(¬𝑥1∨𝑥2∨𝑥3)
"""
input_3sat = '''
c example DIMACS-CNF 3-SAT
p cnf 3 5
-1 -2 -3 0
1 -2 3 0
1 2 -3 0
1 -2 -3 0
-1 2 3 0
'''
oracle = LogicalExpressionOracle(input_3sat)
oracle.circuit.draw('mpl')
grover = Grover(oracle)
backend = BasicAer.get_backend('qasm_simulator')
quantum_instance = QuantumInstance(backend, shots=1024)
result = grover.run(quantum_instance)
print(result['result'])
## Non deterministic solutions, could be [1,-2,3], [-1, -2, -3], [1,2,-3]
plot_histogram(result['measurement'])
## REAL DEVICE LIMITATIONS
from qiskit import IBMQ
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q')
backend = provider.get_backend('ibmq_16_melbourne')
from qiskit.compiler import transpile
# transpile the circuit for ibmq_16_melbourne
grover_compiled = transpile(result['circuit'], backend=backend, optimization_level=3)
print('gates = ', grover_compiled.count_ops())
print('depth = ', grover_compiled.depth())
grover_compiled.draw('mpl')
from qiskit import execute
from qiskit.tools.monitor import job_monitor
job_exp = execute(grover_compiled, shots=1024, backend=backend)
job_monitor(job_exp)
# Get the results from the computation
results = job_exp.result()
answer = results.get_counts(grover_compiled)
plot_histogram(answer)
# Too much noise!
|
https://github.com/sergiogh/qpirates-qiskit-notebooks
|
sergiogh
|
from qiskit import QuantumRegister, ClassicalRegister, BasicAer
import numpy as np
import matplotlib.pyplot as plt
from qiskit import QuantumCircuit, execute,IBMQ
from qiskit.tools.monitor import job_monitor
from qiskit.circuit.library import NormalDistribution,UniformDistribution,LogNormalDistribution
from kaleidoscope import qsphere, probability_distribution
#provider = IBMQ.load_account()
#backend = provider.get_backend('ibmq_qasm_simulator')
backend = BasicAer.get_backend('qasm_simulator')
qubits = 5
q = QuantumRegister(qubits,'q')
c = ClassicalRegister(qubits,'c')
print("\n Normal Distribution")
print("-----------------")
circuit = QuantumCircuit(q,c)
normal = NormalDistribution(num_qubits = qubits, mu=0, sigma=0.1, bounds=([-1,1]))
circuit.append(normal, list(range(qubits)))
circuit.measure(q,c)
job = execute(circuit, backend, shots=8192)
job_monitor(job)
counts = job.result().get_counts()
print(counts)
sortedcounts = []
sortedkeys = sorted(counts)
for i in sortedkeys:
for j in counts:
if(i == j):
sortedcounts.append(counts.get(j))
plt.suptitle('Normal Distribution')
plt.plot(sortedcounts)
plt.show()
probability_distribution(counts)
circuit.decompose().decompose().draw('mpl')
print("\n Uniform Distribution")
print("-----------------")
circuit = QuantumCircuit(q,c)
uniform = UniformDistribution(num_qubits = qubits)
circuit.append(uniform, list(range(qubits)))
circuit.measure(q,c)
job = execute(circuit, backend, shots=8192)
job_monitor(job)
counts = job.result().get_counts()
print(counts)
sortedcounts = []
sortedkeys = sorted(counts)
for i in sortedkeys:
for j in counts:
if(i == j):
sortedcounts.append(counts.get(j))
plt.suptitle('Uniform Distribution')
plt.plot(sortedcounts)
plt.show()
probability_distribution(counts)
circuit.decompose().draw('mpl')
print("\n Log-Normal Distribution")
print("-----------------")
circuit = QuantumCircuit(q,c)
lognorm = LogNormalDistribution(num_qubits = qubits, mu=0.5, sigma=0.05, bounds=([0,4]))
circuit.append(lognorm, list(range(qubits)))
circuit.measure(q,c)
job = execute(circuit, backend, shots=8192)
job_monitor(job)
counts = job.result().get_counts()
print(counts)
sortedcounts = []
sortedkeys = sorted(counts)
for i in sortedkeys:
for j in counts:
if(i == j):
sortedcounts.append(counts.get(j))
plt.suptitle('Log-Normal Distribution')
plt.plot(sortedcounts)
plt.show()
probability_distribution(counts)
from qiskit.finance.applications import GaussianConditionalIndependenceModel as GCI
print("\n Gaussian Conditional Independence Distribution")
print("-----------------")
# set problem parameters
n_z = qubits
z_max = qubits
#p_zeros = [0.15, 0.25, 0.09, 0.05, 0.01]
#rhos = [0.1, 0.05, 0.04, 0.03, 0.01]
p_zeros = [0.15, 0.25]
rhos = [0.1, 0.05]
circuit = GCI(n_z, z_max, p_zeros, rhos)
circuit.measure_all()
job = execute(circuit, backend, shots=8192)
job_monitor(job)
counts = job.result().get_counts()
print(counts)
sortedcounts = []
sortedkeys = sorted(counts)
for i in sortedkeys:
for j in counts:
if(i == j):
sortedcounts.append(counts.get(j))
plt.suptitle('Log-Normal Distribution')
plt.plot(sortedcounts)
plt.show()
probability_distribution(counts)
from qiskit.aqua.algorithms import AmplitudeEstimation
estimation_qubits = 4
ae_lognormal = AmplitudeEstimation(estimation_qubits, state_preparation=lognorm)
ae_uniform = AmplitudeEstimation(estimation_qubits, state_preparation=uniform)
ae_normal = AmplitudeEstimation(estimation_qubits, state_preparation=normal)
result_lognormal = ae_lognormal.run(quantum_instance=BasicAer.get_backend('qasm_simulator'))
result_uniform = ae_uniform.run(quantum_instance=BasicAer.get_backend('qasm_simulator'))
result_normal = ae_normal.run(quantum_instance=BasicAer.get_backend('qasm_simulator'))
# plot estimated values
plt.bar(result_uniform['mapped_a_samples'], result_uniform['probabilities'], width=0.5/len(result_uniform['probabilities']))
plt.bar(result_lognormal['mapped_a_samples'], result_lognormal['probabilities'], width=0.5/len(result_lognormal['probabilities']))
#plt.bar(result_normal['mapped_a_samples'], result_normal['probabilities'], width=0.5/len(result_normal['probabilities']))
plt.xticks([0, 0.25, 0.5, 0.75, 1], size=15)
plt.yticks([0, 0.25, 0.5, 0.75, 1], size=15)
plt.title('Estimated Values', size=15)
plt.ylabel('Probability', size=15)
plt.ylim((0,1))
plt.grid()
plt.show()
print(result_lognormal)
print(result_uniform)
print(result_normal)
estimation_qubits = 7
ae_lognormal = AmplitudeEstimation(estimation_qubits, state_preparation=lognorm)
result_lognormal = ae_lognormal.run(quantum_instance=BasicAer.get_backend('qasm_simulator'))
plt.bar(result_lognormal['mapped_a_samples'], result_lognormal['probabilities'], width=0.5/len(result_lognormal['probabilities']))
plt.title('Estimated Values', size=15)
plt.ylabel('Probability', size=15)
plt.ylim((0,1))
plt.grid()
|
https://github.com/sergiogh/qpirates-qiskit-notebooks
|
sergiogh
|
import pennylane as qml
from pennylane import numpy as np
graph = [(0, 1), (0, 3), (1, 2), (2, 3), (3, 4), (1, 4), (4, 5)]
n_wires = len(graph)
# unitary operator U_B with parameter beta
def U_B(beta):
for wire in range(n_wires):
qml.RX(2 * beta, wires=wire)
# unitary operator U_C with parameter gamma
def U_C(gamma):
for edge in graph:
wire1 = edge[0]
wire2 = edge[1]
qml.CNOT(wires=[wire1, wire2])
qml.RZ(gamma, wires=wire2)
qml.CNOT(wires=[wire1, wire2])
def comp_basis_measurement(wires):
n_wires = len(wires)
return qml.Hermitian(np.diag(range(2 ** n_wires)), wires=wires)
dev = qml.device("default.qubit", wires=n_wires, analytic=True, shots=1)
pauli_z = [[1, 0], [0, -1]]
pauli_z_2 = np.kron(pauli_z, pauli_z)
@qml.qnode(dev)
def circuit(gammas, betas, edge=None, n_layers=1):
# apply Hadamards to get the n qubit |+> state
for wire in range(n_wires):
qml.Hadamard(wires=wire)
# p instances of unitary operators
for i in range(n_layers):
U_C(gammas[i])
U_B(betas[i])
if edge is None:
# measurement phase
return qml.sample(comp_basis_measurement(range(n_wires)))
# during the optimization phase we are evaluating a term
# in the objective using expval
return qml.expval(qml.Hermitian(pauli_z_2, wires=edge))
def qaoa_maxcut(n_layers=1):
print("\np={:d}".format(n_layers))
# initialize the parameters near zero
init_params = 0.01 * np.random.rand(2, n_layers)
# minimize the negative of the objective function
def objective(params):
gammas = params[0]
betas = params[1]
neg_obj = 0
for edge in graph:
# objective for the MaxCut problem
neg_obj -= 0.5 * (1 - circuit(gammas, betas, edge=edge, n_layers=n_layers))
return neg_obj
# initialize optimizer: Adagrad works well empirically
opt = qml.AdagradOptimizer(stepsize=0.5)
# optimize parameters in objective
params = init_params
steps = 30
for i in range(steps):
params = opt.step(objective, params)
if (i + 1) % 5 == 0:
print("Objective after step {:5d}: {: .7f}".format(i + 1, -objective(params)))
# sample measured bitstrings 100 times
bit_strings = []
n_samples = 100
for i in range(0, n_samples):
bit_strings.append(int(circuit(params[0], params[1], edge=None, n_layers=n_layers)))
# print optimal parameters and most frequently sampled bitstring
counts = np.bincount(np.array(bit_strings))
most_freq_bit_string = np.argmax(counts)
print("Optimized (gamma, beta) vectors:\n{}".format(params[:, :n_layers]))
print("Most frequently sampled bit string is: {:04b}".format(most_freq_bit_string))
return -objective(params), bit_strings
# perform qaoa on our graph with p=1,2 and
# keep the bitstring sample lists
bitstrings1 = qaoa_maxcut(n_layers=1)[1]
bitstrings2 = qaoa_maxcut(n_layers=2)[1]
bitstrings3 = qaoa_maxcut(n_layers=3)[1]
import matplotlib.pyplot as plt
xticks = range(0, 16)
xtick_labels = list(map(lambda x: format(x, "08b"), xticks))
bins = np.arange(0, 17) - 0.5
fig, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(10, 4))
plt.subplot(1, 3, 1)
plt.title("n_layers=1")
plt.xlabel("bitstrings")
plt.ylabel("freq.")
plt.xticks(xticks, xtick_labels, rotation="vertical")
plt.hist(bitstrings1, bins=bins)
plt.subplot(1, 3, 2)
plt.title("n_layers=2")
plt.xlabel("bitstrings")
plt.ylabel("freq.")
plt.xticks(xticks, xtick_labels, rotation="vertical")
plt.hist(bitstrings2, bins=bins)
plt.subplot(1, 3, 3)
plt.title("n_layers=3")
plt.xlabel("bitstrings")
plt.ylabel("freq.")
plt.xticks(xticks, xtick_labels, rotation="vertical")
plt.hist(bitstrings3, bins=bins)
plt.tight_layout()
plt.show()
|
https://github.com/sergiogh/qpirates-qiskit-notebooks
|
sergiogh
|
# importing Qiskit
from qiskit import IBMQ, Aer
from qiskit import QuantumCircuit, execute
jokes = [
"I also have a wavefunction joke but I'm afraid that it will collapse",
"I have a unique quantum joke because I am pretty sure it cannot be cloned.",
"I have a joke about quantum physics, but nobody gets it - not even me.",
"I have a quantum computing joke, but it may have decohered.",
"I could tell an entanglement joke, but you already know the second half.",
"I have a quantum computing joke, but it may and may not be more funny than a classical computing joke.",
"I have a quantum diamond joke but it has a defect.",
"I have a quantum entanglement joke, but finding a witness to it is NP-hard.",
"I have a quantum computing opinion, but it's just a projection.",
"All quantum computing jokes are so entangling",
"I have a quantum computing joke, but it’s too nisqué.",
"I have a joke about quantum computing, but I’ll tell you when it’s less noisy.",
"I'll probably have a quantum computing joke about 30 years from now.",
"I won't tell my joke about Quantum Computing, it's a bit cold.",
"I have a joke about quantum computing, but it’s not yet error corrected.",
"I have a quantum computing joke. Once built it is going to profoundly change the way we do humor.",
"It has come to the University’s attention that people really like science jokes. We aim to form a committee in the next 2-3 months made up of selected candidates that will come up with our own, school-approved joke. Please be patient and be on the lookout for our correspondence.",
"There’s a 50/50 chance I have a quantum joke.",
"I have a quantum computing joke, but it will take you at least from 5 to 15 years to get it."
]
qubits = len(bin(len(jokes))[2:])
print("Jokes: %s, Need %s Qubits" % (len(jokes), qubits))
qc = QuantumCircuit(qubits)
qc.h(range(qubits))
# TODO: Interfere or remove additional states not in the length of
# the solution. I.e. If 8 strings, max binary rep is 1000
qc.measure_all()
qc.draw('mpl')
# Clasically it will be easier to just repeat the simulation if we get an out of bounds result :)
while True:
backend = Aer.get_backend('qasm_simulator')
job = execute(qc, backend, shots=1 )
result = job.result().get_counts()
joke = int(list(result)[0],2)
if (joke - 1 < len(jokes)):
break
print(jokes[joke-1])
|
https://github.com/sergiogh/qpirates-qiskit-notebooks
|
sergiogh
|
#initialization
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
import math
# importing Qiskit
from qiskit import IBMQ, Aer
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute
# import basic plot tools
from qiskit.visualization import plot_histogram
from qiskit.circuit.library import QFT
def qft_dagger(circ, qubits, n):
circ.append(QFT(n).inverse(), qubits)
# Add UROTx based on CU1 gates
def apply_crot(circ, control_qubit, target_qubit, theta, exponent):
circ.cu1(2*math.pi*theta*exponent, control_qubit, target_qubit)
def prepare_circuit(n, theta):
qpe = QuantumCircuit(n+1,n)
qpe.x(n)
qpe.h(range(n))
for x in range(n):
exponent = 2**(n-x-1)
apply_crot(qpe, x, n, theta, exponent)
qpe.barrier()
qft_dagger(qpe, range(n), n)
qpe.barrier()
for i in range(n):
qpe.measure(i,i)
return qpe
# The idea is that we are able to estimate theta (the angle) thanks to the QFT Dagger.
# The more qubits we apply on top, the more accuracy we get. Take a look
import operator
backend = Aer.get_backend('qasm_simulator')
shots = 2048
theta = 0.24125
for qubits in range(2, 15):
circuit = prepare_circuit(qubits, theta)
results = execute(circuit, backend=backend, shots=shots).result()
counts = results.get_counts(circuit)
highest_probability_outcome = max(counts.items(), key=operator.itemgetter(1))[0][::-1]
measured_theta = int(highest_probability_outcome, 2)/2**qubits
print("Using %d qubits with theta = %.6f, measured_theta = %.6f." % (qubits, theta, measured_theta))
## Look at the lovely circuit
circuit.draw('text')
|
https://github.com/sergiogh/qpirates-qiskit-notebooks
|
sergiogh
|
import numpy as np
from qiskit import IBMQ, QuantumCircuit, ClassicalRegister, QuantumRegister, execute
from qiskit.tools.visualization import plot_histogram, plot_state_city
from qiskit import Aer, IBMQ
def increment_gate(qc, q, qcoin):
qc.ccx(qcoin, q[0], q[1])
qc.cx(qcoin, q[0])
return qc
def decrement_gate(qc, q, qcoin):
qc.x(q)
qc.x(qcoin)
increment_gate(qc, q, qcoin)
qc.x(qcoin)
qc.x(q)
return qc
n = 2
qnodes = QuantumRegister(n,'qc')
qcoin = QuantumRegister(1,'qcoin')
cnodes = ClassicalRegister(n,'cr')
qc = QuantumCircuit(qnodes, qcoin, cnodes)
# Apply Coin
qc.h(qcoin[0])
# Initial state
qc.x(0)
increment_gate(qc, qnodes, qcoin)
decrement_gate(qc, qnodes, qcoin)
qc.measure(qnodes, cnodes)
qc.draw('mpl')
# Single Shot, just to test!
import matplotlib as mpl
backend = Aer.get_backend("qasm_simulator")
result = execute(qc, backend=backend).result()
plot_histogram(result.get_counts())
# Here goes the magic
n = 2
qnodes = QuantumRegister(n,'qc')
qcoin = QuantumRegister(1,'qcoin')
cnodes = ClassicalRegister(n,'cr')
qc = QuantumCircuit(qnodes, qcoin, cnodes)
steps = 51
def runQWC(qc, steps):
for i in range(steps):
qc.h(qcoin[0])
increment_gate(qc, qnodes, qcoin)
decrement_gate(qc, qnodes, qcoin)
qc.measure(qnodes, cnodes)
return qc
qc = runQWC(qc, steps)
backend = Aer.get_backend("qasm_simulator")
result = execute(qc, backend=backend).result()
plot_histogram(result.get_counts())
|
https://github.com/sergiogh/qpirates-qiskit-notebooks
|
sergiogh
|
from qiskit.quantum_info import Operator
from qiskit import QuantumCircuit
import numpy as np
def phase_oracle(n, solutions, name = 'Oracle'):
qc = QuantumCircuit(n, name=name)
oracle_matrix = np.identity(2**n)
for solution in solutions:
oracle_matrix[solution, solution] = -1
qc.unitary(Operator(oracle_matrix), range(n))
return qc
def diffuser(n):
qc = QuantumCircuit(n, name='Diffuser')
qc.h(range(n))
qc.append(phase_oracle(n, [0]), range(n))
qc.h(range(n))
return qc
def Grover(n, solutions):
qc = QuantumCircuit(n, n)
r = int(np.floor(np.pi/4*np.sqrt(2**n/len(solutions))))
print(f'{n} qubits, basis states {solutions} marked, {r} rounds')
qc.h(range(n))
for _ in range(r):
qc.append(phase_oracle(n, solutions), range(n))
qc.append(diffuser(n), range(n))
qc.measure(range(n), range(n))
return qc
circuit = Grover(8, [1, 42, 120, 199, 250])
circuit.draw(output='text')
from qiskit import Aer, execute
simulator = Aer.get_backend('qasm_simulator')
counts = execute(circuit, backend=simulator).result().get_counts(circuit)
from qiskit.visualization import plot_histogram
plot_histogram(counts)
|
https://github.com/sergiogh/qpirates-qiskit-notebooks
|
sergiogh
|
import math
import matplotlib.pyplot as plt
%matplotlib inline
class TSP:
def __init__(self):
self.flat_mat = flat_mat
self.n = 0
self.melhor_dist = 1e11
self.pontos = []
self.melhores_pontos = []
def busca_exaustiva(self, flat_mat, n, ite):
if ite == n:
dist = 0
for j in range(1, n):
dist += flat_mat[self.pontos[j-1] * n + self.pontos[j]]
dist += flat_mat[self.pontos[n-1] * n + self.pontos[0]]
if dist < self.melhor_dist:
self.melhor_dist = dist
self.melhores_pontos = self.pontos[:]
return
for i in range(n):
if self.pontos[i] == -1:
self.pontos[i] = ite
self.busca_exaustiva(flat_mat, n, ite + 1)
self.pontos[i] = -1
def dist_mat(self):
x = []
y = []
flat_mat = [] #matriz 1 dimensao contendo todas as distancias possiveis entre os pontos para facilitar cálculo.
while True:
try:
temp = input("Digite a coordenada x y: ").split()
x.append(float(temp[0]))
y.append(float(temp[1]))
except:
break
for i in range(len(x)):
for j in range(len(y)):
flat_mat.append(math.sqrt((x[i] - x[j])**2 + (y[i] - y[j])**2))
return flat_mat, x, y
def get_results(self):
self.flat_mat, x, _ = self.dist_mat()
self.n = len(x)
self.pontos = [-1]*self.n
self.pontos[0] = 0
self.busca_exaustiva(self.flat_mat, self.n, 1)
return self.melhor_dist, self.melhores_pontos
Tsp = TSP()
distancia, pontos = Tsp.get_results()
print("Melhor distancia encontrada: ", distancia)
print("Melhor caminho encontrado: ", pontos)
#plota gráfico
def connectpoints(x,y,p1,p2):
x1, x2 = x[p1], x[p2]
y1, y2 = y[p1], y[p2]
plt.plot([x1,x2],[y1,y2],'ro-')
for i in range(1, len(pontos)):
connectpoints(x,y,pontos[i-1],pontos[i])
connectpoints(x,y,pontos[len(x)-1],pontos[0])
plt.title("Percurso")
plt.show()
%%time
%%cmd
python TSP.py < in-1.txt
type out-1.txt
python TSP.py < in-2.txt
type out-2.txt
python TSP.py < in-3.txt
type out-3.txt
python TSP.py < in-4.txt
type out-4.txt
from qiskit import IBMQ
import numpy as np
#IBMQ.save_account('seu-tokenIBMQ-para-rodar-localmente')
IBMQ.load_account()
from qiskit import Aer
from qiskit.tools.visualization import plot_histogram
from qiskit.circuit.library import TwoLocal
from qiskit.optimization.applications.ising import max_cut, tsp
from qiskit.aqua.algorithms import VQE, NumPyMinimumEigensolver
from qiskit.aqua.components.optimizers import SPSA
from qiskit.aqua import aqua_globals
from qiskit.aqua import QuantumInstance
from qiskit.optimization.applications.ising.common import sample_most_likely
from qiskit.optimization.algorithms import MinimumEigenOptimizer
from qiskit.optimization.problems import QuadraticProgram
import logging
from qiskit.aqua import set_qiskit_aqua_logging
#Preparando os dados segundo os imputs do usuario para serem resolvidos pelo qiskit max 4 pontos por limitação de qubits
coord = []
flat_mat, x, y = TSP().dist_mat()
dist_mat = np.array(flat_mat).reshape(len(x),len(x))
for i, j in zip(x, y):
coord.append([i,j])
ins = tsp.TspData('TSP_Q', dim=len(x), coord=np.array(coord), w=dist_mat)
qubitOp, offset = tsp.get_operator(ins)
print('Offset:', offset)
print('Ising Hamiltonian:')
print(qubitOp.print_details())
#Usando o numpyMinimumEigensolver como o solver do problema para resolver de forma quantica
ee = NumPyMinimumEigensolver(qubitOp)
result = ee.run()
print('energy:', result.eigenvalue.real)
print('tsp objective:', result.eigenvalue.real + offset)
x_Q = sample_most_likely(result.eigenstate)
print('feasible:', tsp.tsp_feasible(x_Q))
z = tsp.get_tsp_solution(x_Q)
print('solution:', z)
print('solution objective:', tsp.tsp_value(z, ins.w))
for i in range(1, len(z)):
connectpoints(x,y,z[i-1],z[i])
connectpoints(x,y,z[len(x)-1],z[0])
plt.title("Percurso")
plt.show()
#instanciando o simulador ou o computador real importante lembrar que nao ira funcionar para mais de 4 pontos pelo numero de qubits disponibilizados pela IBM que sao apenas 16 para o simulador qasm e 15 para a maquina quantica
provider = IBMQ.get_provider(hub = 'ibm-q')
device = provider.get_backend('ibmq_16_melbourne')
aqua_globals.random_seed = np.random.default_rng(123)
seed = 10598
backend = Aer.get_backend('qasm_simulator')
#descomentar essa linha caso queira rodar na maquina real
#backend = device
quantum_instance = QuantumInstance(backend, seed_simulator=seed, seed_transpiler=seed)
#rodando no simulador quantico
spsa = SPSA(maxiter=10)
ry = TwoLocal(qubitOp.num_qubits, 'ry', 'cz', reps=5, entanglement='linear')
vqe = VQE(qubitOp, ry, spsa, quantum_instance=quantum_instance)
result = vqe.run(quantum_instance)
print('energy:', result.eigenvalue.real)
print('time:', result.optimizer_time)
x = sample_most_likely(result.eigenstate)
print('feasible:', tsp.tsp_feasible(x_Q))
z = tsp.get_tsp_solution(x_Q)
print('solution:', z)
print('solution objective:', tsp.tsp_value(z, ins.w))
|
https://github.com/sergiogh/qpirates-qiskit-notebooks
|
sergiogh
|
# Playing with models
from qiskit.aqua.algorithms import VQC
from qiskit.aqua.components.optimizers import SPSA
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
from qiskit.ml.datasets import ad_hoc_data, wine
# Data to play with
# ad_hoc_data - returns ad hoc dataset - ad_hoc_data(training_size, test_size, n, gap, plot_data=False)
# sample_ad_hoc_data - returns sample ad hoc data
# breast_cancer - returns breast cancer dataset
# digits - returns digits dataset
# gaussian - returns gaussian dataset
# iris - returns iris dataset
# wine - returns wine dataset - wine(training_size, test_size, n, plot_data=False)
_, training_data, test_data, _ = ad_hoc_data(10, 10, 2, 0.2)
markers = ['o', '^']
plt.figure(figsize=(12,6))
plt.title('Training (full) and test (hollow) data')
for marker, (label, data) in zip(markers, training_data.items()):
plt.scatter(data[:,0], data[:,1], color='tab:blue', label=label, s=60, marker=marker)
for marker, (label, data) in zip(markers, test_data.items()):
plt.scatter(data[:,0], data[:,1], facecolor='', edgecolor='tab:blue', s=60, marker=marker)
plt.legend(loc='best');
_, wine_training_data, wine_data, _ = wine(20, 20, 3)
markers = ['o', '^']
plt.figure(figsize=(12,6))
plt.title('Training (full) and test (hollow) data')
for marker, (label, data) in zip(markers, wine_training_data.items()):
plt.scatter(data[:,0], data[:,1], color='tab:blue', label=label, s=60, marker=marker)
for marker, (label, data) in zip(markers, wine_data.items()):
plt.scatter(data[:,0], data[:,1], facecolor='', edgecolor='tab:blue', s=60, marker=marker)
plt.legend(loc='best');
# Choose which trainint data
test_data = wine_data
training_data = wine_training_data
from qiskit.circuit.library.data_preparation import ZZFeatureMap # can also drop .data_preparation
data_preparation = ZZFeatureMap(2)
data_preparation.draw(output='mpl')
from qiskit.circuit.library.n_local import RealAmplitudes # can also drop .n_local
classifier = RealAmplitudes(2)
classifier.draw(output='mpl')
optimizer = SPSA(max_trials=200)
vqc = VQC(optimizer, data_preparation, classifier, training_data)
from qiskit import Aer
from qiskit.aqua import QuantumInstance
backend = Aer.get_backend('qasm_simulator')
result = vqc.run(backend)
print('Loss:', result['training_loss'])
points_a = test_data['A']
points_b = test_data['B']
_, predicted_a = vqc.predict(points_a)
_, predicted_b = vqc.predict(points_b)
print('Score:', sum(predicted_a == 0) + sum(predicted_b == 1), '/', (len(predicted_a) + len(predicted_b)))
plt.figure(figsize=(12,6))
plt.title('Correctly predicted')
plt.scatter(points_a[:,0], points_a[:,1], s=60, marker='o',
color=['tab:green' if label == 0 else 'tab:red' for label in predicted_a])
plt.scatter(points_b[:,0], points_b[:,1], s=60, marker='^',
color=['tab:green' if label == 1 else 'tab:red' for label in predicted_b])
for marker, (label, data) in zip(markers, training_data.items()):
plt.scatter(data[:,0], data[:,1], color='tab:blue', label=label, s=60, marker=marker)
train = mpatches.Patch(color='tab:blue', label='training data')
correct = mpatches.Patch(color='tab:green', label='correctly labeled')
wrong = mpatches.Patch(color='tab:red', label='wrongly labeled')
plt.legend(handles=[train, correct, wrong])
|
https://github.com/sergiogh/qpirates-qiskit-notebooks
|
sergiogh
|
import networkx as nx
import numpy as np
from qiskit import Aer
from qiskit.aqua import aqua_globals, QuantumInstance
from qiskit.aqua.algorithms import QAOA, VQE, NumPyMinimumEigensolver
from qiskit.aqua.components.optimizers import SPSA, COBYLA
from qiskit.optimization.applications.ising.common import sample_most_likely
from qiskit.optimization.applications.ising import tsp
from qiskit.optimization.converters import IsingToQuadraticProgram
from qiskit.optimization.problems import QuadraticProgram
from qiskit.optimization.algorithms import MinimumEigenOptimizer, RecursiveMinimumEigenOptimizer
from qiskit.circuit.library import TwoLocal
def get_graph(nodes):
G = nx.Graph()
G.add_nodes_from(np.arange(0, nodes, 1))
# Create random positions in the graph. Distance will be calculated from positions
# Note: Dwave and other solvers require a complete graph
for i in range(nodes):
G.nodes[i]['pos'] = (np.random.uniform(0, 10), np.random.uniform(0, 10))
elist = set()
for i in range(nodes):
for t in range(i + 1,nodes):
y1=G.nodes[i]['pos'][1]
x1=G.nodes[i]['pos'][0]
y2=G.nodes[t]['pos'][1]
x2=G.nodes[t]['pos'][0]
dist = np.sqrt(((x2-x1)**2)+((y2-y1)**2))
_tuple = (i, t, dist)
elist.add(_tuple)
# tuple is (i,j,weight) where (i,j) is the edge
G.add_weighted_edges_from(elist)
return G
def get_cost_matrix(G, nodes):
w = np.zeros([nodes,nodes])
for i in range(nodes):
for j in range(nodes):
temp = G.get_edge_data(i,j,default=0)
if temp != 0:
w[i,j] = temp['weight']
return w
def calculate_cost(cost_matrix, solution):
cost = 0
for i in range(len(solution)):
a = i % len(solution)
b = (i + 1) % len(solution)
cost += cost_matrix[solution[a]][solution[b]]
return cost
nodes = 3
starting_node = 0
####
G = get_graph(nodes)
cost_matrix = get_cost_matrix(G, nodes)
G.nodes[0]['pos']
coords = []
for node in G.nodes:
coords.append(G.nodes[node]['pos'])
print(G.nodes[node]['pos'])
tsp_instance = tsp.TspData(name = "TSP", dim = len(G.nodes), coord = coords, w = cost_matrix)
qubitOp, offset = tsp.get_operator(tsp_instance)
#print(qubitOp.print_details())
print("Qubits: ",qubitOp.num_qubits)
qp = QuadraticProgram()
qp.from_ising(qubitOp, offset, linear=True)
qp.to_docplex().prettyprint()
backend = Aer.get_backend('qasm_simulator')
quantum_instance = QuantumInstance(backend)
optimizer = SPSA(maxiter=400)
#optimizer = COBYLA(maxiter=100, rhobeg=2, tol=0.5, disp=True)
ry = TwoLocal(qubitOp.num_qubits, 'ry', 'cx', reps=3, entanglement='full')
vqe = VQE(operator=qubitOp, optimizer=optimizer, quantum_instance=quantum_instance)
result = vqe.run(quantum_instance)
print(result)
x = sample_most_likely(result.eigenstate)
print(x)
print(tsp.tsp_feasible(x))
if(tsp.tsp_feasible(x)):
z = tsp.get_tsp_solution(x)
print('solution with VQE:', z)
else:
print('No solution found with VQE and such parameters')
npes = NumPyMinimumEigensolver(qubitOp)
result_classical = npes.run()
x = sample_most_likely(result_classical.eigenstate)
print(x)
if(tsp.tsp_feasible(x)):
z = tsp.get_tsp_solution(x)
print('solution Numpy classical solver:', z)
else:
print('No solution found with Classical Eigensolver')
## Try now with the optimizer and the Recursive Optimizer
backend = quantum_instance = Aer.get_backend('qasm_simulator')
optimizer = COBYLA(maxiter=200, rhobeg=3, tol=1.5, disp=True)
# MinimumEigenSolvers
qaoa_mes = QAOA(quantum_instance = backend, optimizer=optimizer)
vqe_mes = VQE(quantum_instance=backend, optimizer=optimizer, operator=qubitOp)
exact_mes = NumPyMinimumEigensolver()
# Optimizers
qaoa = MinimumEigenOptimizer(qaoa_mes) # using QAOA
vqe = MinimumEigenOptimizer(vqe_mes) # using QAOA
exact = MinimumEigenOptimizer(exact_mes) # using the exact classical numpy minimum eigen solver
# We can try using VQE or QAOA for the minimum eigen optimizer and compare results
rqaoa = RecursiveMinimumEigenOptimizer(min_eigen_optimizer=vqe, min_num_vars=1, min_num_vars_optimizer=exact)
#rqaoa = RecursiveMinimumEigenOptimizer(min_eigen_optimizer=qaoa, min_num_vars=1, min_num_vars_optimizer=exact)
exact_result = exact.solve(qp)
print("Result Exact QP: ",exact_result.x)
if(tsp.tsp_feasible(exact_result.x)):
print(tsp.get_tsp_solution(exact_result.x))
qaoa_result = qaoa.solve(qp)
print("Result QAOA with QP: ",qaoa_result.x)
if(tsp.tsp_feasible(qaoa_result.x)):
print(tsp.get_tsp_solution(qaoa_result.x))
vqe_result = vqe.solve(qp)
print("Result VQE with QP: ",vqe_result.x)
if(tsp.tsp_feasible(vqe_result.x)):
print(tsp.get_tsp_solution(vqe_result.x))
rqaoa_result = rqaoa.solve(qp)
print("Result RQAOA (withVQE) QP: ",rqaoa_result.x)
if(tsp.tsp_feasible(rqaoa_result.x)):
print(tsp.get_tsp_solution(rqaoa_result.x))
# Compare with using VQE directly without optimizer. That is why we send qubit operator to the MES
result = vqe_mes.run(quantum_instance)
x = sample_most_likely(result_classical.eigenstate)
print("Result VQE with Operator: ",x)
if(tsp.tsp_feasible(x)):
print(tsp.get_tsp_solution(x))
|
https://github.com/sergiogh/qpirates-qiskit-notebooks
|
sergiogh
|
import numpy as np
from qiskit import QuantumCircuit, execute, Aer
from qiskit.quantum_info import Statevector
import kaleidoscope.qiskit
from kaleidoscope import qsphere, probability_distribution
# import basic plot tools
from qiskit.visualization import plot_histogram, plot_state_qsphere
# A Circuit is something as simple as a Qubit with a 0 or a 1.
qc = QuantumCircuit(1)
state = Statevector.from_instruction(qc)
qsphere(state)
# Or a 1
qc.x(0)
state = Statevector.from_instruction(qc)
qsphere(state)
# Now we simulate 3 Qubits
qc = QuantumCircuit(3)
qc.h(range(3))
qc.cz(0,1)
state = Statevector.from_instruction(qc)
qsphere(state)
qc.draw()
# Representing 5 Qubits
qc2 = QuantumCircuit(5)
qc2.h(range(4))
qc2.x(4)
qc2.h(4)
#qc2.barrier()
# "Mark" |11011>
qc2.x(2)
qc2.mct([0,1,2,3], 4)
qc2.x(2)
# "Mark" |11110>
#qc2.x(0)
#qc2.mct([0,1,2,3], 4)
#qc2.x(0)
qc2.h(4)
#qc2.barrier()
qc2.draw('mpl')
statevector = Statevector.from_instruction(qc2)
qsphere(statevector)
qc2.measure_all()
backend = Aer.get_backend("qasm_simulator")
result = execute(qc2, backend=backend, shots=1000).result()
probability_distribution(result.get_counts(qc2))
# Very simple circuit explanation
qc3 = QuantumCircuit(3)
# 1: No Gates
qc3.i(range(3))
# 2: Some Gates
#qc3.x(0)
#qc3.x(1)
# 3: X on all gates
#qc3.x(range(3))
# 4: Superposition
#qc3.x(range(3))
# 5: With some X as well
#qc3.h(range(3))
qc3.draw('mpl')
statevector = Statevector.from_instruction(qc3)
qsphere(statevector)
qc3.measure_all()
backend = Aer.get_backend("qasm_simulator")
result = execute(qc3, backend=backend, shots=1000).result()
probability_distribution(result.get_counts(qc3))
### NEW CIRCUIT WITH 3 QUBITS
### SOLUTIONS: 101 AND 110
def phase_oracle(circuit):
circuit.cz(0, 2)
circuit.cz(1, 2)
def diffuser(circuit):
"""Apply inversion about the average step of Grover's algorithm."""
qubits = circuit.qubits
nqubits = len(qubits)
for q in range(nqubits):
circuit.h(q)
circuit.x(q)
# Do controlled-Z
circuit.h(2)
circuit.ccx(0,1,2)
circuit.h(2)
for q in range(nqubits):
circuit.x(q)
circuit.h(q)
## First we create superposition
n = 3
grover_circuit = QuantumCircuit(n)
grover_circuit.h(range(n))
grover_circuit.barrier()
grover_circuit.draw(output="mpl")
statevector = Statevector.from_instruction(grover_circuit)
qsphere(statevector)
# The Quantum Computer "marks" the solutions
phase_oracle(grover_circuit)
grover_circuit.draw(output="mpl")
statevector = Statevector.from_instruction(grover_circuit)
qsphere(statevector)
# User interference to keep only the solution states
grover_circuit.barrier()
diffuser(grover_circuit)
grover_circuit.draw(output="mpl")
statevector = Statevector.from_instruction(grover_circuit)
qsphere(statevector)
grover_circuit.measure_all()
backend = Aer.get_backend('qasm_simulator')
results = execute(grover_circuit, backend=backend, shots=1000).result()
probability_distribution(results.get_counts(grover_circuit))
|
https://github.com/sergiogh/qpirates-qiskit-notebooks
|
sergiogh
|
from sklearn.datasets import make_blobs
# example dataset
features, labels = make_blobs(n_samples=20, n_features=2, centers=2, random_state=3, shuffle=True)
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import MinMaxScaler
features = MinMaxScaler(feature_range=(0, np.pi)).fit_transform(features)
train_features, test_features, train_labels, test_labels = train_test_split(
features, labels, train_size=15, shuffle=False
)
# number of qubits is equal to the number of features
num_qubits = 2
# number of steps performed during the training procedure
tau = 100
# regularization parameter
C = 1000
from qiskit import BasicAer
from qiskit.circuit.library import ZFeatureMap
from qiskit.utils import QuantumInstance, algorithm_globals
from qiskit_machine_learning.kernels import QuantumKernel
algorithm_globals.random_seed = 12345
pegasos_backend = QuantumInstance(
BasicAer.get_backend("statevector_simulator"),
seed_simulator=algorithm_globals.random_seed,
seed_transpiler=algorithm_globals.random_seed,
)
feature_map = ZFeatureMap(feature_dimension=num_qubits, reps=1)
qkernel = QuantumKernel(feature_map=feature_map, quantum_instance=pegasos_backend)
from qiskit_machine_learning.algorithms import PegasosQSVC
pegasos_qsvc = PegasosQSVC(quantum_kernel=qkernel, C=C, num_steps=tau)
# training
pegasos_qsvc.fit(train_features, train_labels)
# testing
pegasos_score = pegasos_qsvc.score(test_features, test_labels)
print(f"PegasosQSVC classification test score: {pegasos_score}")
grid_step = 0.2
margin = 0.2
grid_x, grid_y = np.meshgrid(
np.arange(-margin, np.pi + margin, grid_step), np.arange(-margin, np.pi + margin, grid_step)
)
meshgrid_features = np.column_stack((grid_x.ravel(), grid_y.ravel()))
meshgrid_colors = pegasos_qsvc.predict(meshgrid_features)
import matplotlib.pyplot as plt
plt.figure(figsize=(5, 5))
meshgrid_colors = meshgrid_colors.reshape(grid_x.shape)
plt.pcolormesh(grid_x, grid_y, meshgrid_colors, cmap="RdBu", shading="auto")
plt.scatter(
train_features[:, 0][train_labels == 0],
train_features[:, 1][train_labels == 0],
marker="s",
facecolors="w",
edgecolors="r",
label="A train",
)
plt.scatter(
train_features[:, 0][train_labels == 1],
train_features[:, 1][train_labels == 1],
marker="o",
facecolors="w",
edgecolors="b",
label="B train",
)
plt.scatter(
test_features[:, 0][test_labels == 0],
test_features[:, 1][test_labels == 0],
marker="s",
facecolors="r",
edgecolors="r",
label="A test",
)
plt.scatter(
test_features[:, 0][test_labels == 1],
test_features[:, 1][test_labels == 1],
marker="o",
facecolors="b",
edgecolors="b",
label="B test",
)
plt.legend(bbox_to_anchor=(1.05, 1), loc="upper left", borderaxespad=0.0)
plt.title("Pegasos Classification")
plt.show()
|
https://github.com/sergiogh/qpirates-qiskit-notebooks
|
sergiogh
|
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit import execute
from qiskit import Aer
from qiskit.aqua.utils import split_dataset_to_data_and_labels
from qiskit.tools.visualization import plot_bloch_multivector
from qiskit.aqua import QuantumInstance
from qiskit.aqua.algorithms import QSVM
from qiskit.circuit.library import ZZFeatureMap
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import sklearn
from sklearn.svm import SVC
from sklearn import preprocessing
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler, MinMaxScaler
from sklearn.decomposition import PCA
Titanic_DF = pd.read_csv('titanic.csv')
Titanic_DF = Titanic_DF.drop(['PassengerId','Name','Cabin','Ticket'],axis=1)
lb_make = preprocessing.LabelEncoder()
Titanic_DF['Sex'] = lb_make.fit_transform(Titanic_DF['Sex'])
Titanic_DF['Embarked'] = lb_make.fit_transform(Titanic_DF['Embarked'])
le_name_mapping = dict(zip(lb_make.classes_, lb_make.transform(lb_make.classes_)))
pd.DataFrame(Titanic_DF).fillna(inplace=True, method='backfill')
FeatureNames = [x for x in list(Titanic_DF.columns) if x not in ['Name','Survived']]
Data = Titanic_DF[FeatureNames].values
Labels = Titanic_DF['Survived'].values
Titanic_DF.info()
Titanic_DF
feature_dim=2
class_labels = [r'0', r'1']
sample_train, sample_test, label_train, label_test = train_test_split(Data, Labels, test_size=0.3, random_state=12)
std_scale = StandardScaler().fit(sample_train, label_train)
sample_train = std_scale.transform(sample_train)
sample_test = std_scale.transform(sample_test)
pca = PCA(n_components=feature_dim).fit(sample_train)
sample_train = pca.transform(sample_train)
sample_test = pca.transform(sample_test)
samples = np.append(sample_train, sample_test, axis=0)
minmax_scale = MinMaxScaler((-1, 1)).fit(samples)
sample_train = minmax_scale.transform(sample_train)
sample_test = minmax_scale.transform(sample_test)
sample_test
def QuantumFormat(sample_train, sample_test, label_train, label_test, training_size, test_size, class_labels):
training_input = {key: (sample_train[label_train == k, :])[:training_size] for k, key in enumerate(class_labels)}
test_input = {key: (sample_test[label_test == k, :])[:test_size] for k, key in enumerate(class_labels)}
return training_input, test_input
training_input, test_input = QuantumFormat(sample_train, sample_test, label_train, label_test, 10, 10, class_labels)
datapoints, class_to_label = split_dataset_to_data_and_labels(test_input)
training_input, test_input
# QSVM
feature_map = ZZFeatureMap(feature_dimension=feature_dim, reps=2, entanglement='linear')
qsvm = QSVM(feature_map, training_input, test_input, None)
backend = Aer.get_backend('qasm_simulator')
quantum_instance = QuantumInstance(backend, shots=1024)
result = qsvm.run(quantum_instance)
print("kernel matrix during the training:")
kernel_matrix = result['kernel_matrix_training']
img = plt.imshow(np.asmatrix(kernel_matrix),interpolation='nearest',origin='upper',cmap='bone_r')
plt.show()
# Classical SVM
svc = SVC(probability=True, gamma='auto')
svc.fit(sample_train, label_train)
kernel_matrix2=sklearn.metrics.pairwise.rbf_kernel(sample_train, sample_train)
img = plt.imshow(np.asmatrix(kernel_matrix2[0:10,0:10]),interpolation='nearest',origin='upper',cmap='bone_r')
plt.show()
# Error Rate
label_predict=svc.predict(sample_test)
print('Error rate: ' + str(sum(label_predict==label_test)/len(label_predict)))
|
https://github.com/sergiogh/qpirates-qiskit-notebooks
|
sergiogh
|
# Playing with models
from qiskit.aqua.algorithms import VQC
from qiskit.aqua.components.optimizers import SPSA
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
from qiskit.ml.datasets import ad_hoc_data, wine
# Data to play with
# ad_hoc_data - returns ad hoc dataset - ad_hoc_data(training_size, test_size, n, gap, plot_data=False)
# sample_ad_hoc_data - returns sample ad hoc data
# breast_cancer - returns breast cancer dataset
# digits - returns digits dataset
# gaussian - returns gaussian dataset
# iris - returns iris dataset
# wine - returns wine dataset - wine(training_size, test_size, n, plot_data=False)
_, training_data, test_data, _ = ad_hoc_data(10, 10, 2, 0.2)
markers = ['o', '^']
plt.figure(figsize=(12,6))
plt.title('Training (full) and test (hollow) data')
for marker, (label, data) in zip(markers, training_data.items()):
plt.scatter(data[:,0], data[:,1], color='tab:blue', label=label, s=60, marker=marker)
for marker, (label, data) in zip(markers, test_data.items()):
plt.scatter(data[:,0], data[:,1], facecolor='', edgecolor='tab:blue', s=60, marker=marker)
plt.legend(loc='best');
_, wine_training_data, wine_data, _ = wine(20, 20, 3)
markers = ['o', '^']
plt.figure(figsize=(12,6))
plt.title('Training (full) and test (hollow) data')
for marker, (label, data) in zip(markers, wine_training_data.items()):
plt.scatter(data[:,0], data[:,1], color='tab:blue', label=label, s=60, marker=marker)
for marker, (label, data) in zip(markers, wine_data.items()):
plt.scatter(data[:,0], data[:,1], facecolor='', edgecolor='tab:blue', s=60, marker=marker)
plt.legend(loc='best');
# Choose which trainint data
test_data = wine_data
training_data = wine_training_data
from qiskit.circuit.library.data_preparation import ZZFeatureMap # can also drop .data_preparation
data_preparation = ZZFeatureMap(2)
data_preparation.draw(output='mpl')
from qiskit.circuit.library.n_local import RealAmplitudes # can also drop .n_local
classifier = RealAmplitudes(2)
classifier.draw(output='mpl')
optimizer = SPSA(max_trials=200)
vqc = VQC(optimizer, data_preparation, classifier, training_data)
from qiskit import Aer
from qiskit.aqua import QuantumInstance
backend = Aer.get_backend('qasm_simulator')
result = vqc.run(backend)
print('Loss:', result['training_loss'])
points_a = test_data['A']
points_b = test_data['B']
_, predicted_a = vqc.predict(points_a)
_, predicted_b = vqc.predict(points_b)
print('Score:', sum(predicted_a == 0) + sum(predicted_b == 1), '/', (len(predicted_a) + len(predicted_b)))
plt.figure(figsize=(12,6))
plt.title('Correctly predicted')
plt.scatter(points_a[:,0], points_a[:,1], s=60, marker='o',
color=['tab:green' if label == 0 else 'tab:red' for label in predicted_a])
plt.scatter(points_b[:,0], points_b[:,1], s=60, marker='^',
color=['tab:green' if label == 1 else 'tab:red' for label in predicted_b])
for marker, (label, data) in zip(markers, training_data.items()):
plt.scatter(data[:,0], data[:,1], color='tab:blue', label=label, s=60, marker=marker)
train = mpatches.Patch(color='tab:blue', label='training data')
correct = mpatches.Patch(color='tab:green', label='correctly labeled')
wrong = mpatches.Patch(color='tab:red', label='wrongly labeled')
plt.legend(handles=[train, correct, wrong])
|
https://github.com/sergiogh/qpirates-qiskit-notebooks
|
sergiogh
|
# Dependencies and initial configuration
%pylab inline
from qiskit import ClassicalRegister, QuantumRegister, QuantumCircuit
from qiskit import execute, Aer
from qiskit.tools.visualization import plot_histogram
from ipywidgets import interact
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
from qiskit.circuit.library.standard_gates import HGate, IGate, XGate
def MoveA1(move_A1): global moveA1; moveA1=move_A1;
def MoveB1(move_B1): global moveB1; moveB1=move_B1;
def MoveA2(move_A2): global moveA2; moveA2=move_A2;
def who_wins(counts):
if len(counts)==1 :
print('The winner is', 'A' if ("0" in counts) else 'B')
if ("0" in counts):
img = mpimg.imread('card.jpg')
else:
img = mpimg.imread('card_reverse.jpg')
imgplot = plt.imshow(img)
plt.axis('off')
plt.show()
else:
count0=counts["0"]
count1=counts["1"]
print('The coin is in superposition of |0⟩ and |1⟩')
print('A wins with probability', "%.1f%%" % (100.*count0/(count0+count1)))
print('B wins with probability', "%.1f%%" % (100.*count1/(count0+count1)))
return()
def build_circuit():
q = QuantumRegister(1, name="coin") # create a quantum register with one qubit
c = ClassicalRegister(1)
qc = QuantumCircuit(q, c) # creates the quantum circuit
h = HGate(label='MAGIC')
i = IGate(label='Do Nothing')
x = XGate(label='Flip')
# 1. move of A
if moveA1 == 0 : qc.append(i, [0]) #qc.i(q[0])
elif moveA1 == 1 : qc.append(x, [0]) #qc.x(q[0])
elif moveA1 == 2 : qc.append(h, [0]) #.h(q[0])
# 1. move of B
if moveB1 == 0 : qc.append(i, [0])
elif moveB1 == 1 : qc.append(x, [0])
# 2. move of A
if moveA2 == 0 : qc.append(i, [0])
elif moveA2 == 1 : qc.append(x, [0])
elif moveA2 == 2 : qc.append(h, [0])
qc.measure(q, c) # Measure the qubits
return qc
interact(MoveA1, move_A1={'Not Flip':0,'Flip':1});
interact(MoveB1, move_B1={'Not Flip':0,'Flip':1});
interact(MoveA2, move_A2={'Not Flip':0,'Flip':1});
# The Quantum Circuit
qc = build_circuit()
qc.draw('mpl')
# execute the quantum circiut (coin moves) and identify the winner
backend = Aer.get_backend('qasm_simulator') # define the backend
job = execute(qc, backend, shots=200) # run the job simulation
result = job.result() # grab the result
counts = result.get_counts(qc) # results for the number of runs
#print(counts); # print the results of the runs
who_wins(counts); # celebrate the winner
interact(MoveB1, move_B1={'Not Flip':0,'Flip':1});
# Quantum Computer uses Superposition! (2 is a "Hadamard Gate")
MoveA1(2)
MoveA2(2)
qc = build_circuit()
qc.draw('mpl')
# execute the quantum circiut (coin moves) and identify the winner
backend = Aer.get_backend('qasm_simulator') # define the backend
job = execute(qc, backend, shots=200) # run the job simulation
result = job.result() # grab the result
counts = result.get_counts(qc) # results for the number of runs
print(counts); # print the results of the runs
who_wins(counts); # celebrate the winner
plot_histogram(counts) # Visualise the results
from qiskit.providers.aer.noise import NoiseModel, thermal_relaxation_error
noise_model = NoiseModel()
T1 = 0.001
T2 = 0.002
error = 0.001
thermal_error = thermal_relaxation_error(T1, T2, error)
noise_model.add_quantum_error(thermal_error, "MAGIC", [0])
job = execute(qc, backend, shots=200, noise_model=noise_model) # run the job simulation
result = job.result() # grab the result
counts = result.get_counts(qc) # results for the number of runs
print(counts); # print the results of the runs
who_wins(counts); # celebrate the winner
plot_histogram(counts) # Visualise the results
|
https://github.com/FerjaniMY/Quantum_Steganography
|
FerjaniMY
|
from qiskit import *
import numpy as np
import matplotlib.pyplot as plt
from qiskit.visualization import plot_histogram
# Creating registers with n qubits
n =7 # for a local backend n can go as up as 23, after that it raises a Memory Error
qr = QuantumRegister(n, name='qr')
cr = ClassicalRegister(n, name='cr')
qc = QuantumCircuit(qr, cr, name='QC')
"""
qr2 = QuantumRegister(n, name='qr')
cr2= ClassicalRegister(n, name='cr')
qc2 = QuantumCircuit(qr2, cr2, name='QC')
for i in range(n):
qc2.h(i)
qc2.measure(qr2,cr2)
qc2.draw(output='mpl')
simulator = Aer.get_backend('qasm_simulator')
execute(qc2, backend = simulator)
result = execute(qc2, backend = simulator).result()
k=list(result.get_counts(qc2))[0]
print(k)
"""
# Generate a random number in the range of available qubits [0,65536))
alice_key = np.random.randint(0,2**n)# we can remplace it by a key from a quantum key generator
alice_key = np.binary_repr(alice_key,n)
print(alice_key)
for i in range(len(alice_key)):
if alice_key[i]=='1':
qc.x(qr[i])
B=[]
for i in range(len(alice_key)):
if 0.5 < np.random.random():
qc.h(qr[i])
B.append("H")
else:
B.append("S")
pass
qc.barrier()
print("Alice Basis",B)
%config InlineBackend.figure_format = 'svg'
qc.draw(output='mpl')
C=[]
for i in range(len(alice_key)):
if 0.5 < np.random.random():
qc.h(qr[i])
C.append("H")
else:
C.append("S")
qc.barrier()
for i in range(len(alice_key)):
qc.measure(qr[i],cr[i])
print("Bob Basis",C)
qc.draw(output='mpl')
simulator = Aer.get_backend('qasm_simulator')
execute(qc, backend = simulator)
result = execute(qc, backend = simulator).result()
print("Bob key :",list(result.get_counts(qc))[0])
print("Bob Basis",C)
print("Alice key :",alice_key)
print("Alice Basis :",B)
def sifted_key(A_basis,B_basis,key):
correct_basis=[]
sifted_key=''
for i in range(len(A_basis)):
if A_basis[i]==B_basis[i]:
correct_basis.append(i)
sifted_key+=key[i]
else:
pass
return sifted_key,correct_basis
a=sifted_key(B,C,alice_key)
print("sifted key",a[0])
print("Basis",a[1])
BB84_key=a[0]
def wordToBV(s) :
#convert text to binar
a_byte_array = bytearray(s, "utf8")
byte_list = []
for byte in a_byte_array:
binary_representation = bin(byte)
byte_list.append(binary_representation[9-n:])
#chop off the "0b" at the beginning. can also truncate the binary to fit on a device with N qubits
#binary has 2 extra digits for "0b", so it starts at 9 for our 7 bit operation.
print(byte_list)
circuit_array = []
length = len(byte_list)
for i in range(length):
s = byte_list[i]
#do all this stuff for every letter
# We need a circuit with n qubits, plus one ancilla qubit
# Also need n classical bits to write the output to
bv_circuit = QuantumCircuit(n+1, n)
# put ancilla in state |->
bv_circuit.h(n)
bv_circuit.z(n)
# Apply Hadamard gates before querying the oracle
for i in range(n):
bv_circuit.h(i)
# Apply barrier
bv_circuit.barrier()
# Apply the inner-product oracle
s = s[::-1] # reverse s to fit qiskit's qubit ordering
for q in range(n):
if s[q] == '0':
bv_circuit.i(q)
else:
bv_circuit.cx(q, n)
# Apply barrier
bv_circuit.barrier()
#Apply Hadamard gates after querying the oracle
for i in range(n):
bv_circuit.h(i)
# Measurement
for i in range(n):
bv_circuit.measure(i, i)
circuit_array.append(bv_circuit)
return circuit_array
circuit_to_run = wordToBV('Qiskit')#Secret Msg
circuit_to_run[0].draw(output='mpl')
backend = BasicAer.get_backend('qasm_simulator')
shots = 4096
results = execute(circuit_to_run[::-1], backend=backend, shots=shots).result()
answer = results.get_counts()
plot_histogram(answer)
def encrypt(BB84_key, letter):
"""Calculates XOR"""
b = int(BB84_key, 2)
x = ord(letter)
return format(b ^ x, "b")
def stega_encoder(LM, carrier_msg):
"""Encodes LM bits message into carrier_msg"""
message = ""
size = len(LM[0])
i = 0
for j, bitstring in enumerate(LM):
for k, digit in enumerate(bitstring):
while (not carrier_msg[i].isalpha()):
message += carrier_msg[i]
i += 1
if digit == "1":
letter = carrier_msg[i].upper()
message += letter
else:
message += carrier_msg[i]
i += 1
if i < len(carrier_msg):
message += carrier_msg[i:]
return message
def stega_decoder(new_carrier_msg, BB84_key):
"""Decodes secret message from new_carrier_msg"""
b = int(BB84_key, 2)
message = ""
bitstring = ""
for char in new_carrier_msg:
if char.isalpha():
if char.isupper():
bitstring += "1"
else:
bitstring += "0"
if len(bitstring) == 7:
x = int(bitstring, 2)
message += chr(b ^ x)
bitstring = ""
return message
a = chr(1110100)
str(a)
encrypt(BB84_key,'q')
secret_msg='qiskit'
L=[]
for c in secret_msg:
L.append(encrypt(BB84_key,c))
carrier_msg='aaaa aaa aaa aaaa aaaaaaa aaaaaaa aaaaaaa aaabaaa'
new_carrier_msg=stega_encoder(L, carrier_msg)
new_carrier_msg
stega_decoder(new_carrier_msg, BB84_key)
|
https://github.com/carstenblank/dc-qiskit-stochastics
|
carstenblank
|
from hmmlearn import hmm
samples = 10*[[0], [1], [1], [1], [1], [2], [2], [0], [1], [1], [1], [0], [2]]
model = hmm.MultinomialHMM(n_components=4)
model.fit(samples)
model.emissionprob_
model.transmat_
|
https://github.com/carstenblank/dc-qiskit-stochastics
|
carstenblank
|
# Copyright 2018-2022 Carsten Blank
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import logging
from datetime import datetime
from typing import List, Union, Optional, Callable
import numpy as np
import qiskit
import scipy
from qiskit.circuit import Parameter
from qiskit.providers.ibmq import IBMQBackend
from qiskit.transpiler import PassManager
from scipy import sparse
from dc_quantum_scheduling import PreparedExperiment
from . import get_default_pass_manager
from .dsp_common import apply_level, apply_initial, x_measurement, y_measurement
from .dsp_independent import index_independent_prep
from .dsp_util import create_qobj, extract_evaluations
from .qiskit_util import qasm_simulator
LOG = logging.getLogger(__name__)
class DiscreteStochasticProcess(object):
realizations: np.array
probabilities: np.array
initial_value: float
def __init__(self, initial_value: float, probabilities: np.ndarray, realizations: np.ndarray):
self.initial_value = initial_value
self.probabilities = probabilities
self.realizations = realizations
@staticmethod
def _get_circuit_name(scaling: float) -> str:
return f'dsp_simulation({scaling})'
@staticmethod
def _get_circuit_name_cos(scaling: float) -> str:
return f'{DiscreteStochasticProcess._get_circuit_name(scaling)}_cosine'
@staticmethod
def _get_circuit_name_sin(scaling: float) -> str:
return f'{DiscreteStochasticProcess._get_circuit_name(scaling)}_sine'
def _proposition_one_circuit(self, scaling: Parameter, level_func=None, index_state_prep=None, with_barrier=False, **kwargs):
# per default we use the standard Moettoennen level function
level_func = apply_level if level_func is None else level_func
# per default we use the independent index state preparation (also Moettoennen)
index_state_prep = index_independent_prep if index_state_prep is None else index_state_prep
LOG.debug(f"Data: initial value={self.initial_value}, "
f"probabilities={list(self.probabilities)}, realizations={list(self.realizations)},"
f"applied function={level_func.__name__}.")
qc = qiskit.QuantumCircuit()
LOG.debug(f"Initializing with {self.initial_value} and scaling {scaling}.")
init_qc = apply_initial(self.initial_value, scaling)
qc.extend(init_qc)
if with_barrier:
qc.barrier()
for level, (p, r) in enumerate(zip(self.probabilities, self.realizations)):
LOG.debug(f"Adding level {level}: {p} with {r} and scaling {scaling}.")
qc_index = index_state_prep(level, p, **kwargs)
qc_level_l = level_func(level, r, scaling, **kwargs)
qc.extend(qc_index)
if with_barrier:
qc.barrier()
qc.extend(qc_level_l)
if with_barrier:
qc.barrier()
return qc
def expval_cos_circuit(self, scaling: Parameter, level_func=None, index_state_prep=None, **kwargs):
LOG.info(f'Cosine Circuit generation with scaling {scaling} and level_func={level_func}')
qc = self._proposition_one_circuit(scaling, level_func, index_state_prep, **kwargs)
qc.extend(x_measurement())
qc.name = f'{qc.name}_cosine'
LOG.debug(f"Circuit:\n{qc.draw(output='text', fold=-1)}")
return qc
def expval_sin_circuit(self, scaling: Parameter, level_func=None, index_state_prep=None, **kwargs):
LOG.info(f'Sine Circuit generation with scaling {scaling} and level_func={level_func}')
qc = self._proposition_one_circuit(scaling, level_func, index_state_prep, **kwargs)
qc.extend(y_measurement())
qc.name = f'{qc.name}_sine'
LOG.debug(f"Circuit:\n{qc.draw(output='text', fold=-1)}")
return qc
def characteristic_function(self, evaluations: Union[List[float], np.ndarray, scipy.sparse.dok_matrix],
external_id: Optional[str] = None, level_func=None, pm: Optional[PassManager] = None,
transpiler_target_backend: Optional[Callable[[], IBMQBackend]] = None,
other_arguments: dict = None) -> PreparedExperiment:
other_arguments = {} if other_arguments is None else other_arguments
backend = transpiler_target_backend() if transpiler_target_backend is not None else qasm_simulator()
if external_id is None:
tags = other_arguments.get('tags', [])
external_id = datetime.now().strftime('%Y%m%d-%H%M%S') + f"-{type(self).__name__}-{'-'.join(tags)}"
scaling_v: Parameter = Parameter('v')
qc_cos_param: qiskit.QuantumCircuit = self.expval_cos_circuit(scaling_v, level_func, **other_arguments)
qc_sin_param: qiskit.QuantumCircuit = self.expval_sin_circuit(scaling_v, level_func, **other_arguments)
pre_pm = None
if pm is None:
LOG.info('No PassManager given, trying to attain one.')
pre_pm, pm = get_default_pass_manager(
transpiler_target_backend=backend,
other_arguments=other_arguments
)
qobj_list = create_qobj(qc_cos_param, qc_sin_param, scaling_v, evaluations=evaluations,
pass_manager=pm, pre_pass_manager=pre_pm, qobj_id=external_id,
other_arguments=other_arguments,
transpiler_target_backend=backend)
prepared_experiment = PreparedExperiment(
external_id=external_id,
tags=other_arguments.get('tags', []),
arguments=evaluations,
parameters={
'initial_value': self.initial_value,
'probabilities': self.probabilities,
'realizations': self.realizations,
'pass_manager': pm.passes(),
'qc_cos': qc_cos_param,
'qc_sin': qc_sin_param,
**other_arguments
},
qobj_list=qobj_list,
callback=extract_evaluations,
transpiler_backend=backend
)
return prepared_experiment
|
https://github.com/carstenblank/dc-qiskit-stochastics
|
carstenblank
|
# Copyright 2018-2022 Carsten Blank
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import logging
import numpy as np
import qiskit
from dc_qiskit_algorithms import UniformRotationGate
from qiskit.circuit import Parameter
from qiskit.circuit.library import U1Gate
from scipy import sparse
LOG = logging.getLogger(__name__)
def apply_initial(value: float, scaling_factor: Parameter) -> qiskit.QuantumCircuit:
"""
This function initializes the circuit using Proposition 1 of the paper:
First we need a Hadamard and then we rotate by the value * scaling factor * 2
with the R_z rotation.
:param value: The initial value
:param scaling_factor: The scaling factor to be used when computing the characteristic function
:return: The initial quantum circuit with the data system only
"""
qc = qiskit.QuantumCircuit(name='initial_rotation')
qreg_data = qiskit.QuantumRegister(1, 'data')
qc.add_register(qreg_data)
# BY Proposition 1 we need to start in a superposition state
qc.h(qreg_data)
# Then the initial rotation
# qc.append(RZGate(2*scaling_factor * value), qreg_data)
qc.u1(scaling_factor * value, qreg_data)
return qc
def apply_level(level: int, realizations: np.array, scaling_factor: Parameter, with_debug_circuit: bool = False, **kwargs) -> qiskit.QuantumCircuit:
k, = realizations.shape
qubits_k = int(np.ceil(np.log2(k)))
qc = qiskit.QuantumCircuit(name=f'level_{level}')
qreg_index = qiskit.QuantumRegister(qubits_k, f'level_{level}')
qreg_data = qiskit.QuantumRegister(1, 'data')
qc.add_register(qreg_index)
qc.add_register(qreg_data)
alpha = sparse.dok_matrix([realizations]).transpose()
if with_debug_circuit:
LOG.debug(f"Will add a controlled rotations with u1({scaling_factor} * {realizations})")
for (i, j), angle in alpha.items():
qc.append(
U1Gate(1.0 * scaling_factor * angle).control(num_ctrl_qubits=qubits_k, ctrl_state=int(i)),
list(qreg_index) + list(qreg_data)
)
else:
LOG.debug(f"Will add a uniform rotation gate with u1({scaling_factor} * {realizations})")
qc.append(UniformRotationGate(lambda theta: U1Gate(scaling_factor * theta), alpha), list(qreg_index) + list(qreg_data))
return qc
def apply_level_two_realizations(level: int, realizations: np.array, scaling_factor: Parameter, **kwargs) -> qiskit.QuantumCircuit:
k, = realizations.shape
assert k == 2
qubits_k = int(np.ceil(np.log2(k)))
qc = qiskit.QuantumCircuit(name=f'level_{level}')
qreg_index = qiskit.QuantumRegister(qubits_k, f'level_{level}')
qreg_data = qiskit.QuantumRegister(1, 'data')
qc.add_register(qreg_index)
qc.add_register(qreg_data)
x_l1 = realizations[0]
x_l2 = realizations[1]
qc.cu1(theta=scaling_factor * x_l2, control_qubit=qreg_index, target_qubit=qreg_data)
qc.x(qreg_index)
qc.cu1(theta=scaling_factor * x_l1, control_qubit=qreg_index, target_qubit=qreg_data)
qc.x(qreg_index)
return qc
def x_measurement() -> qiskit.QuantumCircuit:
qc = qiskit.QuantumCircuit(name='initial_rotation')
qreg_data = qiskit.QuantumRegister(1, 'data')
creg_data = qiskit.ClassicalRegister(1, 'output')
qc.add_register(qreg_data)
qc.add_register(creg_data)
qc.h(qreg_data)
qc.measure(qreg_data, creg_data)
return qc
def y_measurement() -> qiskit.QuantumCircuit:
qc = qiskit.QuantumCircuit(name='initial_rotation')
qreg_data = qiskit.QuantumRegister(1, 'data')
creg_data = qiskit.ClassicalRegister(1, 'output')
qc.add_register(qreg_data)
qc.add_register(creg_data)
qc.z(qreg_data)
qc.s(qreg_data)
qc.h(qreg_data)
qc.measure(qreg_data, creg_data)
return qc
|
https://github.com/carstenblank/dc-qiskit-stochastics
|
carstenblank
|
# Copyright 2018-2022 Carsten Blank
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import logging
from typing import List, Union
import numpy as np
import qiskit
import scipy
from dc_qiskit_algorithms.MöttönenStatePreparation import get_alpha_y
from qiskit.circuit import Parameter
from scipy import sparse
from .benchmark import brute_force_correlated_walk, monte_carlo_correlated_walk
from .discrete_stochastic_process import DiscreteStochasticProcess
LOG = logging.getLogger(__name__)
def index_binary_correlated_walk(level: int, level_p: np.ndarray, **kwargs) -> qiskit.QuantumCircuit:
probs = []
probs.append([np.sqrt(level_p[0]), np.sqrt(1 - level_p[0])])
probs.append([np.sqrt(1 - level_p[1]), np.sqrt(level_p[1])])
qc = qiskit.QuantumCircuit(name='index_state_prep')
qreg = qiskit.QuantumRegister(1, f'level_{level}')
qc.add_register(qreg)
if level == 0:
vector = sparse.dok_matrix([probs[0]]).transpose()
alpha = get_alpha_y(vector, 1, 1)
qc.ry(alpha[0, 0], qreg)
else:
previous_level_qreg = qiskit.QuantumRegister(1, f'level_{level - 1}')
qc.add_register(previous_level_qreg)
# Activating the 1 path
vector = sparse.dok_matrix([probs[1]]).transpose()
alpha = get_alpha_y(vector, 1, 1)
qc.cry(alpha[0, 0], previous_level_qreg, qreg)
# Activating the 0 path
vector = sparse.dok_matrix([probs[0]]).transpose()
alpha = get_alpha_y(vector, 1, 1)
qc.x(previous_level_qreg)
qc.cry(alpha[0, 0], previous_level_qreg, qreg)
qc.x(previous_level_qreg)
return qc
def benchmark_brute_force(probabilities,
realizations,
evaluations: Union[List[float], np.ndarray, scipy.sparse.dok_matrix],
func=None) -> np.ndarray:
logging.basicConfig(format=logging.BASIC_FORMAT)
output: List[complex] = []
for e in list(evaluations):
c_func_eval = brute_force_correlated_walk(
probabilities=probabilities,
realizations=realizations,
initial_value=0.0,
scaling=e,
func=lambda x: np.exp(1.0j * x) if func is None else func
)
output.append(c_func_eval)
return np.asarray(output)
def benchmark_monte_carlo(
probabilities,
realizations,
evaluations: Union[List[float], np.ndarray, scipy.sparse.dok_matrix],
initial_value: float = 0.0,
samples: int = 100,
func=None) -> np.ndarray:
c_func_eval = monte_carlo_correlated_walk(
probabilities=probabilities,
realizations=realizations,
initial_value=initial_value,
samples=samples,
scaling=evaluations,
func=lambda v: np.exp(1.0j * v) if func is None else func
)
return np.asarray(c_func_eval)
class CorrelatedWalk(DiscreteStochasticProcess):
def __init__(self, initial_value: float, probabilities: np.ndarray, realizations: np.ndarray):
assert probabilities.shape == realizations.shape
super().__init__(initial_value, probabilities, realizations)
def _proposition_one_circuit(self, scaling: Parameter, level_func=None, index_state_prep=None, **kwargs):
index_state_prep = index_binary_correlated_walk if index_state_prep is None else index_state_prep
return super(CorrelatedWalk, self)._proposition_one_circuit(scaling, level_func, index_state_prep, **kwargs)
def benchmark(self, evaluations: Union[List[float], np.ndarray, scipy.sparse.dok_matrix],
func=None, samples: int = 100) -> np.ndarray:
return benchmark_monte_carlo(
probabilities=self.probabilities,
realizations=self.realizations,
evaluations=evaluations,
initial_value=self.initial_value,
samples=samples,
func=func
)
|
https://github.com/carstenblank/dc-qiskit-stochastics
|
carstenblank
|
# Copyright 2018-2022 Carsten Blank
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import logging
import numpy as np
import qiskit
from dc_qiskit_algorithms import MöttönenStatePreparationGate
from dc_qiskit_algorithms.MöttönenStatePreparation import get_alpha_y
from scipy import sparse
LOG = logging.getLogger(__name__)
def index_independent_prep(level: int, probabilities: np.ndarray, **kwargs) -> qiskit.QuantumCircuit:
"""
The function adds an index register of appropriate size and uses the state preparation by Möttönen et al.
> Möttönen, Mikko, et al. "Transformation of quantum states using uniformly controlled rotations."
> Quantum Information & Computation 5.6 (2005): 467-473.
:param level: The level for register naming purposes
:param probabilities: the probabilities for this level
:return: the quantum circuit with the state preparation for the index
"""
k = probabilities.shape
qubits_k = int(np.ceil(np.log2(k)))
qc = qiskit.QuantumCircuit(name='index_state_prep')
assert np.sum(probabilities) == 1
qreg = qiskit.QuantumRegister(qubits_k, f'level_{level}')
qc.add_register(qreg)
# Möttönen State-prep with row
qc.append(MöttönenStatePreparationGate(list(np.sqrt(probabilities))), qreg)
return qc
def index_independent_prep_two(level: int, probabilities: np.ndarray, **kwargs) -> qiskit.QuantumCircuit:
assert probabilities.shape == (2,)
qc = qiskit.QuantumCircuit(name='index_state_prep')
assert np.sum(probabilities) == 1
qreg = qiskit.QuantumRegister(1, f'level_{level}')
qc.add_register(qreg)
vector = sparse.dok_matrix([probabilities]).transpose()
alpha = get_alpha_y(vector, 1, 1)
qc.ry(alpha[0, 0], qreg)
return qc
|
https://github.com/carstenblank/dc-qiskit-stochastics
|
carstenblank
|
# Copyright 2018-2022 Carsten Blank
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import logging
from typing import Tuple
import numpy as np
import qiskit
from qiskit.circuit import Parameter
from dc_qiskit_algorithms import MöttönenStatePreparationGate
from dc_qiskit_algorithms import ControlledStatePreparationGate
from scipy import sparse
from .discrete_stochastic_process import DiscreteStochasticProcess
from .dsp_common import apply_level
LOG = logging.getLogger(__name__)
def _index_prep_level_0(probabilities: np.ndarray, **kwargs) -> qiskit.QuantumCircuit:
"""
The function adds an index register of appropriate size and uses the state preparation by Möttönen et al.
> Möttönen, Mikko, et al. "Transformation of quantum states using uniformly controlled rotations."
> Quantum Information & Computation 5.6 (2005): 467-473.
:param level: The level for register naming purposes
:param probabilities: the probabilities for this level
:return: the quantum circuit with the state preparation for the index
"""
_, m = probabilities.shape
qubits_target = int(np.ceil(np.log2(m)))
# check if we have a probability density
assert probabilities.shape[0] == 1
assert np.linalg.norm(np.sum(probabilities) - 1) < 1e-6, "The vector's entries must sum to 1"
qc = qiskit.QuantumCircuit(name='index_state_prep')
qreg_current = qiskit.QuantumRegister(qubits_target, f'level_0')
qc.add_register(qreg_current)
# Möttönen State-prep with row
amplitudes = np.sqrt(probabilities)
vector = sparse.dok_matrix(amplitudes).transpose()
gate = MöttönenStatePreparationGate(vector, neglect_absolute_value=False)
qc.append(gate, list(qreg_current), [])
return qc
def _index_prep(level: int, probabilities: np.ndarray, with_debug_circuit: bool = False, **kwargs) -> qiskit.QuantumCircuit:
"""
The function adds an index register of appropriate size and uses the state preparation by Möttönen et al.
> Möttönen, Mikko, et al. "Transformation of quantum states using uniformly controlled rotations."
> Quantum Information & Computation 5.6 (2005): 467-473.
:param level: The level for register naming purposes
:param probabilities: the probabilities for this level
:return: the quantum circuit with the state preparation for the index
"""
assert level > 0, "This call is only for the level 1, and beyond."
n, m = probabilities.shape
qubits_source = int(np.ceil(np.log2(n)))
qubits_target = int(np.ceil(np.log2(m)))
# check if we have a stochastic matrix
# assert np.linalg.norm(np.sum(probabilities, axis=0) - 1) < 1e-6, "The probability matrix must be a stochastic matrix"
assert np.linalg.norm(np.sum(probabilities, axis=1) - 1) < 1e-6, "The probability matrix must be a stochastic matrix"
qc = qiskit.QuantumCircuit(name='index_state_prep')
qreg_last = qiskit.QuantumRegister(qubits_source, f'level_{level - 1}')
qreg_current = qiskit.QuantumRegister(qubits_target, f'level_{level}')
qc.add_register(qreg_last)
qc.add_register(qreg_current)
# Möttönen State-prep with row
amplitudes = probabilities ** 0.5
matrix = sparse.dok_matrix(amplitudes)
gate = ControlledStatePreparationGate(matrix)
if with_debug_circuit:
from qiskit import QuantumCircuit
qc_def: QuantumCircuit = gate.definition
qc = qc.compose(qc_def, qubits=list(qreg_last) + list(qreg_current))
else:
qc.append(gate, list(qreg_last) + list(qreg_current), [])
return qc
def _index(level, probabilities, **kwargs):
# Deliver the index register which encodes the joint probability of realizations
# Given the initial value, select the row that is encoding the first step
level_probabilities = np.asarray(probabilities)
if level == 0:
return _index_prep_level_0(level_probabilities, **kwargs)
else:
return _index_prep(level, level_probabilities, **kwargs)
def _level(level, realizations, scaling, **kwargs):
# Deliver the index register which encodes the joint probability of realizations
# Given the initial value, select the row that is encoding the first step
return apply_level(level, realizations, scaling, **kwargs)
class StateMachineDSP(DiscreteStochasticProcess):
def __init__(self, initial_value: float, probabilities: np.ndarray, realizations: np.ndarray):
# FIXME: this is wrong, find assertions that reflect this situation
# assert probabilities.shape == realizations.shape
_probabilities = np.asarray([np.asarray(p) for p in probabilities])
_realizations = np.asarray([np.asarray(r) for r in realizations])
super().__init__(initial_value, _probabilities, _realizations)
last_target_states = -1
for step in range(self.length):
source_states, target_states = self.number_of_states(step)
if last_target_states != -1:
assert source_states == last_target_states
last_target_states = target_states
@property
def length(self):
return self.probabilities.shape[0]
def number_of_states(self, step: int) -> Tuple[int, ...]:
return np.asarray(self.probabilities[step]).shape
def get_level_transition_matrix(self, level: int) -> np.ndarray:
return self.probabilities[level]
def _proposition_one_circuit(self, scaling: Parameter, level_func=None, index_state_prep=None, **kwargs):
index_state_prep = _index if index_state_prep is None else index_state_prep
level_func = _level if level_func is None else level_func
return super(StateMachineDSP, self)._proposition_one_circuit(scaling, level_func, index_state_prep, **kwargs)
#
# def benchmark(self, evaluations: Union[List[float], np.ndarray, scipy.sparse.dok_matrix],
# func=None, samples: int = 100) -> Union[NDArray[complex], np.ndarray]:
# return benchmark_monte_carlo(
# probabilities=self.probabilities,
# realizations=self.realizations,
# evaluations=evaluations,
# initial_value=self.initial_value,
# samples=samples,
# func=func
# )
|
https://github.com/carstenblank/dc-qiskit-stochastics
|
carstenblank
|
# Copyright 2018-2022 Carsten Blank
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import bisect
import logging
from multiprocessing import Pool
from numpy.random import random
import sys
from typing import List, Union, Optional, Dict, Tuple
import numpy as np
import qiskit
from qiskit import QuantumCircuit
from qiskit.circuit import Parameter
from qiskit.providers.backend import BackendV1
from qiskit.providers.ibmq import IBMQBackend
from qiskit.providers.models import QasmBackendConfiguration
from qiskit.qobj import Qobj
from qiskit.result import Result
from qiskit.transpiler import PassManager
from qiskit.utils.mitigation import CompleteMeasFitter
from . import qobj_mapping
from dc_quantum_scheduling import FinishedExperiment
LOG = logging.getLogger(__name__)
def _bind(qc, parameter, v):
return qc.bind_parameters({parameter: v})
def create_qobj(qc_cos: QuantumCircuit, qc_sin: QuantumCircuit,
parameter: Parameter, evaluations: np.ndarray,
qobj_id: str, pass_manager: PassManager,
other_arguments: dict,
transpiler_target_backend: Union[BackendV1, IBMQBackend],
pre_pass_manager: Optional[PassManager] = None) -> List[Qobj]:
LOG.info(f'Transpiling {len(evaluations)} cosine and {len(evaluations)} sine circuits with id={qobj_id}.')
# We have the same number of circuits for the cosine and sine experiments
other_arguments = {} if other_arguments is None else other_arguments
if pre_pass_manager:
LOG.info(f'Pre running cicuits...')
qc_cos = pre_pass_manager.run(qc_cos)
qc_sin = pre_pass_manager.run(qc_sin)
LOG.info(f'Main run of cicuits...')
qc_transpiled_cos_param = pass_manager.run(qc_cos)
qc_transpiled_sin_param = pass_manager.run(qc_sin)
with Pool() as pool:
circuits_cos = pool.starmap(_bind, [(qc_transpiled_cos_param, parameter, v) for v in evaluations])
circuits_sin = pool.starmap(_bind, [(qc_transpiled_sin_param, parameter, v) for v in evaluations])
# circuits_cos = [qc_transpiled_cos_param.bind_parameters({parameter: v}) for v in evaluations]
# circuits_sin = [qc_transpiled_sin_param.bind_parameters({parameter: v}) for v in evaluations]
config: QasmBackendConfiguration = transpiler_target_backend.configuration()
max_shots = config.max_shots
max_experiments = config.max_experiments if hasattr(config, 'max_experiments') else sys.maxsize
shots = other_arguments.get('shots', max_shots)
other_arguments['shots'] = shots
mapping_matrix: np.array = qobj_mapping(shots, max_shots, max_experiments, 2*len(evaluations))
shots_per_experiment = int(shots / mapping_matrix.shape[1])
LOG.debug(mapping_matrix)
number_of_qobj: int = np.max(mapping_matrix) + 1
LOG.info(f'For #{len(evaluations)} evaluations each {shots} on the device {transpiler_target_backend.name()} '
f'with max shots {max_shots} and max no. of experiments per Qobj {max_experiments} '
f'there are #{number_of_qobj} of Qobj needed. Assembling the circuits now.')
all_circuits = list(zip(circuits_cos, circuits_sin))
qobj_list: List[Qobj] = []
circuit_list: List[List[QuantumCircuit]] = [[] for i in range(number_of_qobj)]
for row_no, (ccos, csin) in enumerate(all_circuits):
# cosine
indices = mapping_matrix[2 * row_no]
for i, qobj_id in enumerate(indices):
qobj_circuits = circuit_list[qobj_id]
qobj_circuits.append(ccos)
# sine
indices = mapping_matrix[2 * row_no + 1]
for i, qobj_id in enumerate(indices):
qobj_circuits = circuit_list[qobj_id]
qobj_circuits.append(csin)
LOG.info(f'Assembled circuits, now building a list of Qobj.')
for i, cc in enumerate(circuit_list):
qobj_id_i = f'{qobj_id}--{i}'
LOG.info(f'Assembling circuits for Qobj #{i} with shots {shots_per_experiment} and id {qobj_id_i}.')
qobj = qiskit.compiler.assemble(cc,
shots=shots_per_experiment,
max_credits=shots_per_experiment * 5,
qobj_id=qobj_id_i)
qobj_list.append(qobj)
return qobj_list
def get_row_colums_of_qobj_index(qobj_index: int, mapping: np.array):
indices: List[Tuple[int, int]] = []
for row_no, row in enumerate(mapping):
for column_no, entry in enumerate(row):
if entry == qobj_index:
indices.append((row_no, column_no))
if entry > qobj_index:
break
return indices
def _get_expval_proposition_one(counts: Dict[str, int]):
return (counts.get('0', 0) - counts.get('1', 0)) / (counts.get('0', 0) + counts.get('1', 0))
def extract_evaluations(finished_experiment: FinishedExperiment, meas_fitter: Optional[CompleteMeasFitter] = None) -> np.ndarray:
backend: BackendV1 = finished_experiment.transpiler_backend
config: QasmBackendConfiguration = backend.configuration()
max_shots = config.max_shots
max_experiments = config.max_experiments if hasattr(config, 'max_experiments') else sys.maxsize
shots = finished_experiment.parameters.get('shots', max_shots)
mapping_matrix = qobj_mapping(shots, max_shots, max_experiments, 2*len(finished_experiment.arguments))
number_of_qobj: int = np.max(mapping_matrix) + 1
counts_cos: List[Dict[str, int]] = [{'0': 0, '1': 0} for a in finished_experiment.arguments]
counts_sin: List[Dict[str, int]] = [{'0': 0, '1': 0} for a in finished_experiment.arguments]
for qobj_index in range(number_of_qobj):
indices = get_row_colums_of_qobj_index(qobj_index, mapping_matrix)
result: Result = finished_experiment.to_result(qobj_index)
measured_qubits = [e.instructions[-1].qubits for e in finished_experiment.qobj_list[qobj_index].experiments]
def mitigate_counts(counts: Dict[str, int], q_no: List[int]):
if meas_fitter is not None:
# build a fitter from the subset
meas_fitter_sub = meas_fitter.subset_fitter(qubit_sublist=q_no)
# Get the filter object
meas_filter = meas_fitter_sub.filter
# Results with mitigation
mitigated_counts = meas_filter.apply(counts, method='pseudo_inverse')
return mitigated_counts
else:
return counts
count: Dict[str, int]
for count, (row_no, _), measured_q_no in zip(result.get_counts(), indices, measured_qubits):
count = mitigate_counts(count, measured_q_no)
if row_no % 2 == 1:
argument_no = int((row_no - 1) / 2)
counts = counts_sin
else:
argument_no = int(row_no / 2)
counts = counts_cos
old_counts = counts[argument_no]
counts[argument_no]['0'] = old_counts.get('0', 0) + count.get('0', 0)
counts[argument_no]['1'] = old_counts.get('1', 0) + count.get('1', 0)
cosine_expvals = [_get_expval_proposition_one(c) for c in counts_cos]
sine_expvals = [_get_expval_proposition_one(c) for c in counts_sin]
return np.asarray([cos + 1.0j * sin for cos, sin in zip(cosine_expvals, sine_expvals)])
def cdf(weights):
"""
From https://stackoverflow.com/questions/4113307/pythonic-way-to-select-list-elements-with-different-probability
:param weights:
:return:
"""
total = sum(weights)
result = []
cumsum = 0
for w in weights:
cumsum += w
result.append(cumsum / total)
return result
def choice(population, weights, size=None):
"""
From https://stackoverflow.com/questions/4113307/pythonic-way-to-select-list-elements-with-different-probability
:param population:
:param weights:
:return:
Args:
size:
"""
assert len(population) == len(weights)
cdf_vals = cdf(weights)
x = random(size=size)
if not size:
x = [x]
for e in x:
idx = bisect.bisect(cdf_vals, e)
yield population[idx]
|
https://github.com/carstenblank/dc-qiskit-stochastics
|
carstenblank
|
# Copyright 2018-2022 Carsten Blank
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import logging
from typing import Optional, Dict, Any, Union
import numpy as np
import qiskit
from dc_qiskit_algorithms import UniformRotationGate, QuantumFourierTransformGate
from dc_qiskit_algorithms.MöttönenStatePreparation import get_alpha_y
from dc_qiskit_algorithms.Qft import get_theta
from hmmlearn import hmm
from hmmlearn.hmm import MultinomialHMM
from qiskit import QuantumRegister, QuantumCircuit
from qiskit.circuit import Gate, Parameter
from qiskit.circuit.library import RYGate, CU1Gate
from scipy import sparse
LOG = logging.basicConfig(format=logging.BASIC_FORMAT)
class DraperAdder(Gate):
num_qubits_a: int
num_qubits_b: int
def __init__(self, num_qubits_a: int, num_qubits_b: int, label: Optional[str] = None) -> None:
super().__init__("draper", num_qubits_a + num_qubits_b, [], label)
self.num_qubits_a = num_qubits_a
self.num_qubits_b = num_qubits_b
def _define(self):
a = QuantumRegister(self.num_qubits_a, "a")
b = QuantumRegister(self.num_qubits_b, "b")
qc = QuantumCircuit(a, b, name=self.name)
qc.append(QuantumFourierTransformGate(len(a)), a, [])
for b_index in reversed(range(len(b))):
theta_index = 1
for a_index in reversed(range(b_index + 1)):
qc.append(CU1Gate(get_theta(theta_index)), [b[b_index], a[a_index]], [])
theta_index += 1
qc.append(QuantumFourierTransformGate(len(a)).inverse(), a, [])
self.definition = qc
class RYGateSpecial(object):
scaling: Parameter
def __init__(self, scaling: Parameter):
self.scaling = scaling
def gate(self):
return lambda phi: RYGate(self.scaling * (-phi))
# class MultinomialHmmSpecial(MultinomialHMM):
#
# def __init__(self, n_components=1, startprob_prior=1.0, transmat_prior=1.0, algorithm="viterbi", random_state=None,
# n_iter=10, tol=1e-2, verbose=False, params="ste", init_params="ste"):
# super().__init__(n_components, startprob_prior, transmat_prior, algorithm, random_state, n_iter, tol, verbose,
# params, init_params)
#
# def emitted_symbol(self, state):
# return self.emissionprob_[state, :].argmax()
#
# def _generate_sample_from_state(self, state, random_state=None):
# most_likely_emmission = self.emitted_symbol(state)
# return [most_likely_emmission]
class HiddenMarkovModelAlternative(object):
emitted_symbols_map: Dict[int, float]
accumulator_register: QuantumRegister
state_register: QuantumRegister
number_of_qubits: int
number_of_states: int
model: hmm.MultinomialHMM
def __init__(self, model: hmm.MultinomialHMM, emitted_symbols_map: Optional[Dict[int, float]] = None) -> None:
self.emitted_symbols_map = emitted_symbols_map or {}
self.model = model
self.number_of_states = self.model.n_components * self.model.n_features
self.number_of_qubits = int(np.ceil(np.log2(self.number_of_states)))
self.state_register = QuantumRegister(size=self.number_of_qubits, name='state')
self.accumulator_register = QuantumRegister(size=1, name='accumulator')
def _create_index(self, level: int, scaling: Parameter):
angles = {}
for k in range(1, self.number_of_qubits + 1):
size_of_vector = 2 ** (2 * self.number_of_qubits - k)
vector = sparse.dok_matrix((size_of_vector, 1))
angles[k] = vector
transition_matrix: np.ndarray = self.model.transmat_
for state in range(self.number_of_states):
transitions: np.ndarray = transition_matrix[state]
a = sparse.dok_matrix([transitions]).transpose()
for k in range(1, self.number_of_qubits + 1):
resulting_angles = angles[k]
alpha_vector = get_alpha_y(a, self.number_of_qubits, k)
offset = state * 2 ** (self.number_of_qubits - k)
for key, alpha in alpha_vector.items():
resulting_angles[offset + key[0], key[1]] = alpha
level_register = QuantumRegister(size=self.number_of_qubits, name=f'level_{level}')
qc: QuantumCircuit = QuantumCircuit(self.state_register, level_register, name=f'circuit_level_{level}')
for k in range(1, self.number_of_qubits + 1):
alpha_angles = angles[k]
control = list(self.state_register) + list(level_register)[0:self.number_of_qubits - k]
target = level_register[self.number_of_qubits - k]
# FIXME: scaling must be adjusted too!
qc.append(UniformRotationGate(gate=RYGateSpecial(scaling).gate(), alpha=alpha_angles), control + [target], [])
return qc
def _create_accumulator_circuit(self, level: int, scaling: Parameter):
angles: sparse.dok_matrix = sparse.dok_matrix((2**(2*self.number_of_qubits), 1))
for state in range(self.number_of_states):
for transition in range(self.number_of_states):
index = state + transition * self.number_of_states
# The emitted symbol that occurs when going from state to state + transition!
target_state = (state + transition) % self.model.n_components
emitted_symbol = 0 # TODO: do
angles[index, 0] = self.emitted_symbols_map.get(emitted_symbol, emitted_symbol)
level_register = QuantumRegister(size=self.number_of_qubits, name=f'level_{level}')
qc: QuantumCircuit = QuantumCircuit(self.state_register, level_register, self.accumulator_register,
name=f'circuit_accumulator_{level}')
control = list(self.state_register) + list(level_register)
target = list(self.accumulator_register)[0]
# FIXME: scaling must be adjusted too!
qc.append(
UniformRotationGate(gate=RYGateSpecial(scaling).gate(), alpha=angles), control + [target], []
)
return qc
def _create_adder(self, level: int):
level_register = QuantumRegister(size=self.number_of_qubits, name=f'level_{level}')
qc: QuantumCircuit = QuantumCircuit(self.state_register, level_register,
name=f'circuit_adder_{level}')
control = list(self.state_register) + list(level_register)
if self.number_of_qubits == 1:
qc.cx(level_register, self.state_register)
else:
qc.append(
DraperAdder(num_qubits_a=self.number_of_qubits, num_qubits_b=self.number_of_qubits), control, []
)
return qc
if __name__ == "__main__":
samples = 10*[[0], [1], [1], [1], [1], [2], [2], [0], [1], [1], [1], [0], [2]]
model = hmm.MultinomialHMM(n_components=4)
model.fit(samples)
samples = model.sample(10)
q_model = HiddenMarkovModel(model)
qc: QuantumCircuit = QuantumCircuit(name='hmm_circuit')
scaling_v: Parameter = Parameter('v')
steps = 3
for level in range(1, steps + 1):
level_qc = q_model._create_index(level, scaling_v)
qc.extend(level_qc)
# qc.barrier()
acc_qc = q_model._create_accumulator_circuit(level, scaling_v)
qc.extend(acc_qc)
# qc.barrier()
update_state_qc = q_model._create_adder(level)
qc.extend(update_state_qc)
qc.barrier()
print(qc.draw(fold=-1))
transpiled_qc = qiskit.transpile(
qc,
optimization_level=3,
basis_gates=[
'u1', 'u2', 'u3', 'cx', 'id',
# 'cu1', 'h'
]
)
print(transpiled_qc.draw(fold=-1))
print(transpiled_qc.depth(), transpiled_qc.width())
|
https://github.com/carstenblank/dc-qiskit-stochastics
|
carstenblank
|
# Copyright 2018-2022 Carsten Blank
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import logging
import sys
from typing import List, Optional
import numpy as np
import qiskit
from qiskit import QuantumCircuit
from qiskit.providers.models import QasmBackendConfiguration
from qiskit.qobj import Qobj
from qiskit.transpiler import PassManager
from dc_quantum_scheduling import PreparedExperiment, FinishedExperiment
from qiskit.utils.mitigation import CompleteMeasFitter, complete_meas_cal
from . import qobj_mapping, get_default_pass_manager
LOG = logging.getLogger(__name__)
def create_qobj(circuits: List[QuantumCircuit], pass_manager: PassManager, qobj_id, other_arguments, transpiler_target_backend):
circuits_assembled = [pass_manager.run(qc) for qc in circuits]
config: QasmBackendConfiguration = transpiler_target_backend.configuration()
max_shots = config.max_shots
max_experiments = config.max_experiments if hasattr(config, 'max_experiments') else sys.maxsize
shots = other_arguments.get('shots', max_shots)
other_arguments['shots'] = shots
mapping_matrix: np.array = qobj_mapping(shots, max_shots, max_experiments, len(circuits_assembled))
shots_per_experiment = int(shots / mapping_matrix.shape[1])
LOG.debug(mapping_matrix)
number_of_qobj: int = np.max(mapping_matrix) + 1
LOG.info(f'For #{len(circuits_assembled)} evaluations each {shots} on the device {transpiler_target_backend.name()} '
f'with max shots {max_shots} and max no. of experiments per Qobj {max_experiments} '
f'there are #{number_of_qobj} of Qobj needed. Assembling the circuits now.')
qobj_list: List[Qobj] = []
circuit_list: List[List[QuantumCircuit]] = [[] for i in range(number_of_qobj)]
for row_no, qc in enumerate(circuits_assembled):
indices = mapping_matrix[row_no]
for i, qobj_id in enumerate(indices):
qobj_circuits = circuit_list[qobj_id]
qobj_circuits.append(qc)
LOG.info(f'Assembled circuits, now building a list of Qobj.')
for i, cc in enumerate(circuit_list):
qobj_id_i = f'{qobj_id}--{i}'
LOG.info(f'Assembling circuits for Qobj #{i} with shots {shots_per_experiment} and id {qobj_id_i}.')
qobj = qiskit.compiler.assemble(cc,
shots=shots_per_experiment,
max_credits=shots_per_experiment * 5,
qobj_id=qobj_id_i)
qobj_list.append(qobj)
return qobj_list
def interpret_output(finished_experiment: FinishedExperiment,
meas_fitter: Optional[CompleteMeasFitter] = None) -> CompleteMeasFitter:
if meas_fitter is not None:
return meas_fitter
qubit_list = finished_experiment.parameters['qubit_list']
state_labels = finished_experiment.parameters['state_labels']
# Get results
cal_results = []
for qobj_index in range(len(finished_experiment.qobj_list)):
r = finished_experiment.to_result(qobj_index)
cal_results.append(r)
# Calculate the calibration matrix with the noise model
return CompleteMeasFitter(cal_results, state_labels, qubit_list=qubit_list, circlabel='mcal')
def create_error_mitigation_experiment(exp: PreparedExperiment) -> PreparedExperiment:
# def calculate_error_mitigation_matrix(self, backend: Optional[Union[IBMQBackend, AerBackend]] = None):
# Get the measured qubits
measured_qubits = set([e.instructions[-1].qubits[0] for q in exp.qobj_list for e in q.experiments])
LOG.info(f'Qubits measured are {measured_qubits}')
# Generate the calibration circuits
qr = qiskit.QuantumRegister(exp.transpiler_backend.configuration().n_qubits)
qubit_list = list(measured_qubits)
meas_calibs, state_labels = complete_meas_cal(qubit_list=qubit_list, qr=qr, circlabel='mcal')
_, pm = get_default_pass_manager(exp.transpiler_backend, exp.parameters)
external_id = f'{exp.external_id}-error_mitigation'
qobj_list = create_qobj(meas_calibs,
pass_manager=pm,
qobj_id=external_id,
other_arguments=exp.parameters,
transpiler_target_backend=exp.transpiler_backend
)
return PreparedExperiment(
external_id=f'{exp.external_id}-error_mitigation',
tags=exp.tags + ['error mitigation'],
qobj_list=qobj_list,
arguments=[],
transpiler_backend=exp.transpiler_backend,
parameters={
'qubit_list': qubit_list,
'state_labels': state_labels,
**exp.parameters,
},
callback=interpret_output
)
|
https://github.com/carstenblank/dc-qiskit-stochastics
|
carstenblank
|
# Copyright 2018-2022 Carsten Blank
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import logging
from typing import Optional, Dict, Any, Union
import numpy as np
import qiskit
from dc_qiskit_algorithms import UniformRotationGate, QuantumFourierTransformGate
from dc_qiskit_algorithms.MöttönenStatePreparation import get_alpha_y
from dc_qiskit_algorithms.Qft import get_theta
from hmmlearn import hmm
from hmmlearn.hmm import MultinomialHMM
from qiskit import QuantumRegister, QuantumCircuit
from qiskit.circuit import Gate, Parameter
from qiskit.circuit.library import RYGate, CU1Gate
from scipy import sparse
LOG = logging.basicConfig(format=logging.BASIC_FORMAT)
class DraperAdder(Gate):
num_qubits_a: int
num_qubits_b: int
def __init__(self, num_qubits_a: int, num_qubits_b: int, label: Optional[str] = None) -> None:
super().__init__("draper", num_qubits_a + num_qubits_b, [], label)
self.num_qubits_a = num_qubits_a
self.num_qubits_b = num_qubits_b
def _define(self):
a = QuantumRegister(self.num_qubits_a, "a")
b = QuantumRegister(self.num_qubits_b, "b")
qc = QuantumCircuit(a, b, name=self.name)
qc.append(QuantumFourierTransformGate(len(a)), a, [])
for b_index in reversed(range(len(b))):
theta_index = 1
for a_index in reversed(range(b_index + 1)):
qc.append(CU1Gate(get_theta(theta_index)), [b[b_index], a[a_index]], [])
theta_index += 1
qc.append(QuantumFourierTransformGate(len(a)).inverse(), a, [])
self.definition = qc
class RYGateSpecial(object):
scaling: Parameter
def __init__(self, scaling: Parameter):
self.scaling = scaling
def gate(self):
return lambda phi: RYGate(self.scaling * (-phi))
class MultinomialHmmSpecial(MultinomialHMM):
def __init__(self, n_components=1, startprob_prior=1.0, transmat_prior=1.0, algorithm="viterbi", random_state=None,
n_iter=10, tol=1e-2, verbose=False, params="ste", init_params="ste"):
super().__init__(n_components, startprob_prior, transmat_prior, algorithm, random_state, n_iter, tol, verbose,
params, init_params)
def emitted_symbol(self, state):
return self.emissionprob_[state, :].argmax()
def _generate_sample_from_state(self, state, random_state=None):
most_likely_emmission = self.emitted_symbol(state)
return [most_likely_emmission]
class HiddenMarkovModel(object):
emitted_symbols_map: Dict[int, float]
accumulator_register: QuantumRegister
state_register: QuantumRegister
number_of_state_qubits: int
number_of_level_qubits: int
model: MultinomialHmmSpecial
def __init__(self, model: MultinomialHmmSpecial, emitted_symbols_map: Optional[Dict[int, float]] = None) -> None:
self.emitted_symbols_map = emitted_symbols_map or {}
self.model = model
self.number_of_state_qubits = int(np.ceil(np.log2(model.n_components)))
self.number_of_level_qubits = int(np.ceil(np.log2(model.n_features)))
self.state_register = QuantumRegister(size=self.number_of_state_qubits, name='state')
self.accumulator_register = QuantumRegister(size=1, name='accumulator')
def _create_index(self, level: int, scaling: Parameter):
angles = {}
for k in range(1, self.number_of_state_qubits + 1):
size_of_vector = 2 ** (2 * self.number_of_state_qubits - k)
vector = sparse.dok_matrix((size_of_vector, 1))
angles[k] = vector
transition_matrix: np.ndarray = self.model.transmat_
for state in range(self.model.n_components):
transitions: np.ndarray = transition_matrix[state]
a = sparse.dok_matrix([transitions]).transpose()
for k in range(1, self.number_of_state_qubits + 1):
resulting_angles = angles[k]
alpha_vector = get_alpha_y(a, self.number_of_state_qubits, k)
offset = state * 2 ** (self.number_of_state_qubits - k)
for key, alpha in alpha_vector.items():
resulting_angles[offset + key[0], key[1]] = alpha
level_register = QuantumRegister(size=self.number_of_state_qubits, name=f'level_{level}')
qc: QuantumCircuit = QuantumCircuit(self.state_register, level_register, name=f'circuit_level_{level}')
for k in range(1, self.number_of_state_qubits + 1):
alpha_angles = angles[k]
control = list(self.state_register) + list(level_register)[0:self.number_of_state_qubits - k]
target = level_register[self.number_of_state_qubits - k]
# FIXME: scaling must be adjusted too!
qc.append(UniformRotationGate(gate=RYGateSpecial(scaling).gate(), alpha=alpha_angles), control + [target], [])
return qc
def _create_accumulator_circuit(self, level: int, scaling: Parameter):
angles: sparse.dok_matrix = sparse.dok_matrix((2 ** (2 * self.number_of_state_qubits), 1))
for state in range(self.model.n_components):
for transition in range(self.model.n_components):
index = state + transition * self.model.n_components
# The emitted symbol that occurs when going from state to state + transition!
target_state = (state + transition) % self.model.n_components
# The problem with the HMM is that it associates to a state a random variable
# FIXME: for epsilon-machines this is a state/target-state pair!
emitted_symbol = self.model.emitted_symbol(target_state)
angles[index, 0] = self.emitted_symbols_map.get(emitted_symbol, emitted_symbol)
level_register = QuantumRegister(size=self.number_of_state_qubits, name=f'level_{level}')
qc: QuantumCircuit = QuantumCircuit(self.state_register, level_register, self.accumulator_register,
name=f'circuit_accumulator_{level}')
control = list(self.state_register) + list(level_register)
target = list(self.accumulator_register)[0]
# FIXME: scaling must be adjusted too!
qc.append(
UniformRotationGate(gate=RYGateSpecial(scaling).gate(), alpha=angles), control + [target], []
)
return qc
def _create_adder(self, level: int):
level_register = QuantumRegister(size=self.number_of_state_qubits, name=f'level_{level}')
qc: QuantumCircuit = QuantumCircuit(self.state_register, level_register,
name=f'circuit_adder_{level}')
control = list(self.state_register) + list(level_register)
if self.number_of_state_qubits == 1:
qc.cx(level_register, self.state_register)
else:
qc.append(
DraperAdder(num_qubits_a=self.number_of_state_qubits, num_qubits_b=self.number_of_state_qubits), control, []
)
return qc
if __name__ == "__main__":
samples = 10*[[0], [1], [1], [1], [1], [2], [2], [0], [1], [1], [1], [0], [2]]
model = hmm.MultinomialHMM(n_components=4)
model.fit(samples)
samples = model.sample(10)
q_model = HiddenMarkovModel(model)
qc: QuantumCircuit = QuantumCircuit(name='hmm_circuit')
scaling_v: Parameter = Parameter('v')
steps = 3
for level in range(1, steps + 1):
level_qc = q_model._create_index(level, scaling_v)
qc.extend(level_qc)
# qc.barrier()
acc_qc = q_model._create_accumulator_circuit(level, scaling_v)
qc.extend(acc_qc)
# qc.barrier()
update_state_qc = q_model._create_adder(level)
qc.extend(update_state_qc)
qc.barrier()
print(qc.draw(fold=-1))
transpiled_qc = qiskit.transpile(
qc,
optimization_level=3,
basis_gates=[
'u1', 'u2', 'u3', 'cx', 'id',
# 'cu1', 'h'
]
)
print(transpiled_qc.draw(fold=-1))
print(transpiled_qc.depth(), transpiled_qc.width())
|
https://github.com/carstenblank/dc-qiskit-stochastics
|
carstenblank
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
# pylint: disable=wrong-import-order
"""Main Qiskit public functionality."""
import pkgutil
# First, check for required Python and API version
from . import util
# qiskit errors operator
from .exceptions import QiskitError
# The main qiskit operators
from qiskit.circuit import ClassicalRegister
from qiskit.circuit import QuantumRegister
from qiskit.circuit import QuantumCircuit
# pylint: disable=redefined-builtin
from qiskit.tools.compiler import compile # TODO remove after 0.8
from qiskit.execute import execute
# The qiskit.extensions.x imports needs to be placed here due to the
# mechanism for adding gates dynamically.
import qiskit.extensions
import qiskit.circuit.measure
import qiskit.circuit.reset
# Allow extending this namespace. Please note that currently this line needs
# to be placed *before* the wrapper imports or any non-import code AND *before*
# importing the package you want to allow extensions for (in this case `backends`).
__path__ = pkgutil.extend_path(__path__, __name__)
# Please note these are global instances, not modules.
from qiskit.providers.basicaer import BasicAer
# Try to import the Aer provider if installed.
try:
from qiskit.providers.aer import Aer
except ImportError:
pass
# Try to import the IBMQ provider if installed.
try:
from qiskit.providers.ibmq import IBMQ
except ImportError:
pass
from .version import __version__
from .version import __qiskit_version__
|
https://github.com/carstenblank/dc-qiskit-stochastics
|
carstenblank
|
# Copyright 2018-2022 Carsten Blank
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import logging
import re
import unittest
from typing import List, Optional
import numpy as np
import qiskit
import qiskit.result
from ddt import ddt, data as test_data, unpack
import dsp_data
import dc_qiskit_stochastics.benchmark as benchmark
from dc_qiskit_stochastics.dsp_common import apply_initial, x_measurement, y_measurement
from dc_qiskit_stochastics.dsp_independent import index_independent_prep
logging.basicConfig(format=logging.BASIC_FORMAT, level='DEBUG')
LOG = logging.getLogger(__name__)
@ddt
class QiskitDspCircuitTests(unittest.TestCase):
@staticmethod
def report_progress(job_id: str, job_status: qiskit.providers.JobStatus, job: qiskit.providers.JobV1):
LOG.info(f'Processing {job_id} with status {job_status}...')
def assert_statevector(self, probabilities: np.ndarray, realizations: np.ndarray,
scaling: float, initial_value: float,job: qiskit.providers.JobV1,
measurement: Optional[str] = None):
LOG.info(f'Asserting {job.job_id()} with status {job.status()}...')
if job.status() == qiskit.providers.JobStatus.DONE:
result: qiskit.result.Result = job.result()
vector = result.get_statevector()
# Gather facts from the probabilities about the number k (realizations)
# and the number of qubits to encode a this number
k = len(probabilities[0, :])
index_register_size = int(np.ceil(np.log2(k)))
# The bits show the string length of bits to encode the Hilbert space of the state vector (dimension of it)
bits = int(np.log2(len(vector)))
# First assertion: the bits to encode the dimension of the state vector must be
# divisible by the index register size if the data bit is removed
self.assertTrue((bits - 1) % index_register_size == 0, msg='Bit length of state vector must be 1 data bit + l level index.')
# If the last assertion passed, the divisor os the number of levels, so it must be equal
levels = (bits - 1) / index_register_size
self.assertTrue(levels == len(probabilities), msg='Bit length of state vector must show the correct number of levels.')
# Save the resulting expected vector to compare later. We do this because we want to
# get the full information first, before we fail the test
expected_vector: List[complex] = []
phase_diff_list: List[float] = []
for index, value in enumerate(vector):
basis_state_bits = "{0:b}".format(index).zfill(bits) # [::-1]
data_state = int(basis_state_bits[-1], 2)
values: List[str] = re.findall(''.join(index_register_size*['.']), basis_state_bits[:-1])
values: List[int] = [int(v, 2) for v in values]
LOG.debug(f'Found the extraction indices to be {values}.')
all_probs = probabilities[np.arange(len(probabilities)), values]
LOG.debug(f'Found the extraction probabilities to be {all_probs}.')
all_reals = realizations[np.arange(len(realizations)), values]
LOG.debug(f'Found the extraction realizations to be {all_reals}.')
p = 1 / np.sqrt(2) * np.prod(np.sqrt(all_probs))
x = np.sum(all_reals)
if measurement is None:
expected_value: complex = p * np.exp(
1.0j * scaling * (initial_value + x) if data_state == 1 else 0.0
)
elif measurement == 'sigma_x':
expected_value: complex = p * np.exp(
(-1.0)**(1 - data_state) * 1.0j * scaling * (initial_value + x)
)
elif measurement == 'sigma_y':
expected_value: complex = p * np.exp(
(-1.0)**(1 - data_state) * 1.0j * (np.pi/2 + scaling * (initial_value + x))
)
else:
self.fail("If a measurement is given, it must either 'sigma_x' or 'sigma_y'.")
expected_vector.append(expected_value)
# As quantum mechanics is neglecting a global phase, we need to find the phase difference.
# If later we find that all phase differences are the same, we have a global phase
# and need to adjust for it.
phase_diff = np.angle(expected_value) - np.angle(value)
phase_diff_list.append(phase_diff if phase_diff > 10e-6 else phase_diff + 2 * np.pi)
LOG.info(f'Basis: {basis_state_bits} (data/indices: {data_state}/{values}), '
f'Expected: {np.abs(expected_value):.4f} * e^{np.angle(expected_value):.4f}, '
f'Actual: {np.abs(value):.4f} * e^{np.angle(value):.4f}')
# First we check by pairwise comparison, if we have phase differences all within a small
# delta, if so, we have found a global phase difference.
LOG.info(f"Phase differences: {phase_diff_list}")
[self.assertAlmostEqual(x, y, delta=10e-3, msg='Phase Differences have to negligible.')
for i, x in enumerate(phase_diff_list)
for j, y in enumerate(phase_diff_list) if i != j]
# Checking the equality of expect vs. actual values with the global phase taken into account.
LOG.info(f"Checking of state vector is as expected (modulo phase shift of): {phase_diff_list[0]}")
for expected, actual in zip(expected_vector, vector):
actual_phase_shifted = actual * np.exp(1.0j * phase_diff_list[0])
LOG.debug(f'Expected: {np.abs(expected):.4f} * e^{np.angle(expected):.4f}, '
f'Actual: {np.abs(actual_phase_shifted):.4f} * e^{np.angle(actual_phase_shifted):.4f}')
self.assertAlmostEqual(expected.real, actual_phase_shifted.real, delta=10e-3)
self.assertAlmostEqual(expected.imag, actual_phase_shifted.imag, delta=10e-3)
return expected_vector
else:
self.fail("The job is not done. Cannot assert correctness.")
@test_data(*dsp_data.testing_data)
@unpack
def test_create_circuit(self, scaling: float, initial_value: float, probabilities: np.ndarray,
realizations: np.ndarray, apply_func):
LOG.info(f"Data: scaling={scaling}, initial value={initial_value}, "
f"probabilities={list(probabilities)}, realizations={list(realizations)},"
f"applied function={apply_func.__name__}.")
qc = qiskit.QuantumCircuit(name='dsp_simulation')
LOG.info(f"Initializing with {initial_value} and scaling {scaling}.")
init_qc = apply_initial(initial_value, scaling)
qc.extend(init_qc)
for level, (p, r) in enumerate(zip(probabilities, realizations)):
LOG.info(f"Adding level {level}: {p} with {r} and scaling {scaling}.")
qc_index = index_independent_prep(level, p)
qc_level_l = apply_func(level, r, scaling)
qc.extend(qc_index)
qc.extend(qc_level_l)
LOG.info(f"Circuit:\n{qc.draw(output='text', fold=-1)}")
qc_compiled = qiskit.transpile(qc, optimization_level=3,basis_gates=['id', 'u1', 'u2', 'u3', 'cx'])
LOG.info(f"Circuit:\n{qc_compiled.draw(output='text', fold=-1)}")
backend: qiskit.providers.aer.StatevectorSimulator = qiskit.Aer.get_backend('statevector_simulator')
job: qiskit.providers.aer.AerJob = qiskit.execute(qc_compiled, backend)
job.wait_for_final_state(callback=QiskitDspCircuitTests.report_progress, wait=1)
self.assert_statevector(probabilities, realizations, scaling, initial_value, job)
@test_data(*dsp_data.testing_data)
@unpack
def test_calculate_x_measurement_cos(self, scaling: float, initial_value: float, probabilities: np.ndarray,
realizations: np.ndarray, apply_func):
LOG.info(f"Data: scaling={scaling}, initial value={initial_value}, "
f"probabilities={list(probabilities)}, realizations={list(realizations)},"
f"applied function={apply_func.__name__}.")
qc = qiskit.QuantumCircuit(name='dsp_simulation')
LOG.info(f"Initializing with {initial_value} and scaling {scaling}.")
init_qc = apply_initial(initial_value, scaling)
qc.extend(init_qc)
for level, (p, r) in enumerate(zip(probabilities, realizations)):
LOG.info(f"Adding level {level}: {p} with {r} and scaling {scaling}.")
qc_index = index_independent_prep(level, p)
qc_level_l = apply_func(level, r, scaling)
qc.extend(qc_index)
qc.extend(qc_level_l)
qc.extend(x_measurement())
LOG.info(f"Circuit:\n{qc.draw(output='text', fold=-1)}")
qc_compiled = qiskit.transpile(qc, optimization_level=3,basis_gates=['id', 'u1', 'u2', 'u3', 'cx'])
LOG.info(f"Circuit:\n{qc_compiled.draw(output='text', fold=-1)}")
backend: qiskit.providers.aer.StatevectorSimulator = qiskit.Aer.get_backend('qasm_simulator')
job: qiskit.providers.aer.AerJob = qiskit.execute(qc_compiled, backend, shots=2**16)
job.wait_for_final_state(callback=QiskitDspCircuitTests.report_progress, wait=1)
expected_cos = benchmark.brute_force_rw_ind(probabilities, realizations, initial_value, scaling, np.cos)
result: qiskit.result.Result = job.result()
counts = result.get_counts()
p: float = (counts.get('0', 0) - counts.get('1', 0)) / (counts.get('0', 0) + counts.get('1', 0))
LOG.info(f"Assertion: expected={expected_cos}, actual={p}, diff={np.abs(expected_cos - p)}")
self.assertAlmostEqual(expected_cos, p, delta=10e-3)
@test_data(*dsp_data.testing_data)
@unpack
def test_calculate_y_measurement_sin(self, scaling: float, initial_value: float, probabilities: np.ndarray,
realizations: np.ndarray, apply_func):
LOG.info(f"Data: scaling={scaling}, initial value={initial_value}, "
f"probabilities={list(probabilities)}, realizations={list(realizations)},"
f"applied function={apply_func.__name__}.")
qc = qiskit.QuantumCircuit(name='dsp_simulation')
LOG.info(f"Initializing with {initial_value} and scaling {scaling}.")
init_qc = apply_initial(initial_value, scaling)
qc.extend(init_qc)
for level, (p, r) in enumerate(zip(probabilities, realizations)):
LOG.info(f"Adding level {level}: {p} with {r} and scaling {scaling}.")
qc_index = index_independent_prep(level, p)
qc_level_l = apply_func(level, r, scaling)
qc.extend(qc_index)
qc.extend(qc_level_l)
qc.extend(y_measurement())
LOG.info(f"Circuit:\n{qc.draw(output='text', fold=-1)}")
qc_compiled = qiskit.transpile(qc, optimization_level=3,basis_gates=['id', 'u1', 'u2', 'u3', 'cx'])
LOG.info(f"Circuit:\n{qc_compiled.draw(output='text', fold=-1)}")
backend: qiskit.providers.aer.StatevectorSimulator = qiskit.Aer.get_backend('qasm_simulator')
job: qiskit.providers.aer.AerJob = qiskit.execute(qc_compiled, backend, shots=2**16)
job.wait_for_final_state(callback=QiskitDspCircuitTests.report_progress, wait=1)
expected_cos = benchmark.brute_force_rw_ind(probabilities, realizations, initial_value, scaling, np.sin)
result: qiskit.result.Result = job.result()
counts = result.get_counts()
p: float = (counts.get('0', 0) - counts.get('1', 0)) / (counts.get('0', 0) + counts.get('1', 0))
LOG.info(f"Assertion: expected={expected_cos}, actual={p}, diff={np.abs(expected_cos - p)}")
self.assertAlmostEqual(expected_cos, p, delta=10e-3)
|
https://github.com/carstenblank/dc-qiskit-stochastics
|
carstenblank
|
# Copyright 2018-2022 Carsten Blank
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import logging
import unittest
from typing import Optional
import matplotlib.pyplot as plt
import numpy as np
import qiskit
from qiskit.circuit import Parameter
from dc_qiskit_stochastics.benchmark import char_func_asian_option, char_func_asian_option_sm
from dc_qiskit_stochastics.dsp_state_machine import StateMachineDSP
from dc_qiskit_stochastics.simulation.asian_option import AsianOptionPricing, StateMachineDescription
from dc_quantum_scheduling import processor
from dc_quantum_scheduling.models import PreparedExperiment, RunningExperiment, FinishedExperiment
from dsp_data import testing_data_state_machine
logging.basicConfig(format=f'%(asctime)s::{logging.BASIC_FORMAT}', level='ERROR')
LOG = logging.getLogger(__name__)
class StateMachineTest(unittest.TestCase):
def test_init_success(self):
data = {
'initial_value': 0,
'probabilities': np.asarray([
[
[0.1, 0.6]
],
[
[0.1, 0.6, 0.3],
[0.5, 0.3, 0.1]
],
[
[0.1, 0.6],
[0.5, 0.3],
[0.1, 0.1]
]
]),
'realizations': np.asarray([
[
[1, 1]
],
[
[1, 1, 1],
[1, 1, 1]
],
[
[1, 1],
[1, 1],
[1, 1]
]
])
}
try:
StateMachineDSP(data['initial_value'], data['probabilities'], data['realizations'])
except AssertionError:
self.fail()
def test_init_fail(self):
data = {
'initial_value': 0,
'probabilities': np.asarray([
[
[0.1, 0.6]
],
[
[0.1, 0.6, 0.3],
[0.5, 0.3, 0.1],
[0.5, 0.3, 0.1]
],
[
[0.1, 0.6],
[0.5, 0.3],
[0.1, 0.1]
]
]),
'realizations': np.asarray([
[
[1, 1]
],
[
[1, 1, 1],
[1, 1, 1],
[1, 1, 1]
],
[
[1, 1],
[1, 1],
[1, 1]
]
])
}
try:
StateMachineDSP(data['initial_value'], data['probabilities'], data['realizations'])
except AssertionError:
return
self.fail()
def test_full(self):
for i, data in enumerate(testing_data_state_machine):
print(f'Test on data {i}.')
process = StateMachineDSP(data['initial_value'], data['probabilities'], data['realizations'])
qc = process._proposition_one_circuit(Parameter('v'))
qc_t = qiskit.transpile(
qc, basis_gates=['uni_rot_rx', 'uni_rot_ry', 'uni_rot_rz', 'uni_rot_rx_dg', 'uni_rot_ry_dg',
'uni_rot_rz_dg', 'uni_rot_u1', 'uni_rot_u1_dg', 'h', 'u1']
)
print(qc_t.draw(fold=-1))
qc_t = qiskit.transpile(qc, basis_gates=['u1', 'u2', 'u3', 'cx'], optimization_level=3)
print(qc_t.draw(fold=-1))
print(f'Depth of final circuit: {qc_t.depth()}')
def test_log_normal(self):
log_normal_data = {
'risk_free_interest': 0.02,
'volatility': 0.05,
'start_value': 80,
'time_steps': np.asarray([5]),
'discretization': 2**4
}
s0 = log_normal_data['start_value']
sigma = log_normal_data['volatility']
mu = log_normal_data['risk_free_interest']
time_steps = log_normal_data['time_steps']
discretization = log_normal_data['discretization']
asian_option_model = AsianOptionPricing(s0, sigma, mu, time_steps, discretization)
data = asian_option_model.get_state_machine_model()
v = np.linspace(-0.3, 0.3, num=400)
# TODO: test the benchmark separately with this:
# # As this is just the lognormal distribution, we can directly brute-force compute the outcome.
# phi_v_sim = []
# for entry in v:
# summands = data.probabilities[0] * np.exp(1.0j * entry * data.realizations)
# summed = np.sum(summands)
# phi_v_sim.append(summed)
# phi_v_sim = np.asarray(phi_v_sim)
phi_v_sim = char_func_asian_option_sm(v, asian_option_model)
# The quantum approach is created here
state_machine = StateMachineDSP(data.initial_value, data.probabilities, data.realizations)
pre_exp: PreparedExperiment = state_machine.characteristic_function(
evaluations=v, other_arguments={'shots': 2000, 'with_barrier': True}
)
print(pre_exp.parameters['qc_cos'].draw(fold=-1))
run_exp: RunningExperiment = processor.execute_simulation(pre_exp)
fin_exp: Optional[FinishedExperiment] = run_exp.wait()
phi_v_qc = fin_exp.get_output()
# The MC benchmark computation
phi_v = char_func_asian_option(
asian_option_model.mu,
asian_option_model.sigma,
asian_option_model.s0,
asian_option_model.time_steps,
samples=2000,
evaluations=v
)
# TODO: remove if not needed
# s = sigma * np.sqrt(delta_t)
# mu_tilde = (mu - 0.5 * sigma ** 2) * delta_t + np.log(s0)
# phi_v_benchmark_m = np.asarray(
# [(1.0j * v) ** n / factorial(n) * np.exp(n * mu_tilde + 0.5 * n**2 * s**2) for n in range(1000)]
# )
# phi_v = np.sum(phi_v_benchmark_m, axis=0, where=~np.isnan(phi_v_benchmark_m))
# Plotting party
plt.plot(v, np.real(phi_v_sim), color='gray', alpha=0.7, label='QC-TH')
plt.scatter(x=v, y=np.real(phi_v_qc), color='blue', alpha=1.0, label='QC', marker='.')
plt.plot(v, np.real(phi_v), color='black', label='MC')
plt.axvline(x=0, color='purple')
plt.title(f'StateMachineTest.test_log_normal\nReal part (cosine) at {time_steps}')
plt.ylim((-1.1, 1.1))
plt.legend()
plt.show()
plt.plot(v, np.imag(phi_v_sim), color='gray', alpha=0.7, label='QC-TH')
plt.scatter(x=v, y=np.imag(phi_v_qc), color='blue', alpha=0.7, label='QC', marker='.')
plt.plot(v, np.imag(phi_v), color='black', label='MC')
plt.axvline(x=0, color='purple')
plt.title(f'StateMachineTest.test_log_normal\nImaginary part (sine) at {time_steps}')
plt.ylim((-1.1, 1.1))
plt.legend()
plt.show()
def test_asian_option(self):
log_normal_data = {
'risk_free_interest': 0.02,
'volatility': 0.05,
'start_value': 80,
'time_steps': np.asarray([5, 10]),
'discretization': 2**4
}
s0 = log_normal_data['start_value']
sigma = log_normal_data['volatility']
mu = log_normal_data['risk_free_interest']
time_steps = log_normal_data['time_steps']
discretization = log_normal_data['discretization']
asian_option_model = AsianOptionPricing(s0, sigma, mu, time_steps, discretization)
data: StateMachineDescription = asian_option_model.get_state_machine_model()
v = np.linspace(-0.3, 0.3, num=400)
# The brute force calculation using the state machine description
phi_v_sim = char_func_asian_option_sm(v, asian_option_model)
# The quantum approach is created here
state_machine = StateMachineDSP(data.initial_value, data.probabilities, data.realizations)
pre_exp: PreparedExperiment = state_machine.characteristic_function(
evaluations=v, other_arguments={'shots': 2000, 'with_barrier': True}
)
print(qiskit.transpile(pre_exp.parameters['qc_cos']).draw(fold=-1))
run_exp: RunningExperiment = processor.execute_simulation(pre_exp)
fin_exp: Optional[FinishedExperiment] = run_exp.wait()
phi_v_qc = fin_exp.get_output()
# The MC benchmark computation
phi_v = char_func_asian_option(
asian_option_model.mu,
asian_option_model.sigma,
asian_option_model.s0,
asian_option_model.time_steps,
samples=2000,
evaluations=v
)
# Plotting party
plt.plot(v, np.real(phi_v_sim), color='gray', alpha=0.7, label='QC-TH')
plt.scatter(x=v, y=np.real(phi_v_qc), color='blue', alpha=1.0, label='QC', marker='.')
plt.plot(v, np.real(phi_v), color='black', label='MC')
plt.axvline(x=0, color='purple')
plt.title(f'StateMachineTest.test_asian_option\nReal part (cosine) at {time_steps}')
plt.ylim((-1.1, 1.1))
plt.legend()
plt.show()
plt.plot(v, np.imag(phi_v_sim), color='gray', alpha=0.7, label='QC-TH')
plt.scatter(x=v, y=np.imag(phi_v_qc), color='blue', alpha=0.7, label='QC', marker='.')
plt.plot(v, np.imag(phi_v), color='black', label='MC')
plt.axvline(x=0, color='purple')
plt.title(f'StateMachineTest.test_asian_option\nImaginary part (sine) at {time_steps}')
plt.ylim((-1.1, 1.1))
plt.legend()
plt.show()
|
https://github.com/renatawong/classical-shadow-vqe
|
renatawong
|
# Installation of the requirements
#!python -m pip install -r requirements.txt
'''
(C) Renata Wong 2023
Qiskit code for testing fidelity of derandomised classical shadow on the ground state energy of molecules.
Procedure:
1. Derandomize the molecule-in-question's Hamiltonian.
2. Choose a variational ansatz with initial parameters selected at random.
3. Apply the derandomized Hamiltonian as basis change operators to the ansatz.
4. Measure the ansatz in the Pauli Z basis and store the results as a shadow.
5. Obtain the expectation value of the molecular Hamiltonian from the shadow.
6. Optimize for minimum Hamiltonian expectation value.
7. Feed the calculated angles/parameters back to the ansatz.
8. Repeat steps 3-7 till the optimization is completed.
9. Output the minimized expectation value of the molecular Hamiltonian and the mean-square-root-error.
Note: Below we perform calculations on the molecular Hamiltonian of H_2.
To perform calculations on other molecules, you will need to specify their geometry, charge and spin
to replace the values in the driver.
Note: predicting_quantum_properties module comes from https://github.com/hsinyuan-huang/predicting-quantum-properties
'''
from qiskit import QuantumCircuit, execute
from qiskit_aer import QasmSimulator
from qiskit_nature.units import DistanceUnit
from qiskit_nature.second_q.drivers import PySCFDriver
from qiskit_nature.second_q.mappers import BravyiKitaevMapper
from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver
from qiskit_nature.second_q.algorithms import GroundStateEigensolver
from qiskit.circuit.library import EfficientSU2
from qiskit.algorithms.optimizers import SLSQP, COBYLA, SPSA
import time
import numpy as np
from functools import partial
import matplotlib.pyplot as plt
from collections import Counter
from predicting_quantum_properties.prediction_shadow import estimate_exp
from modified_derandomization import modified_derandomized_classical_shadow
# handle deprecation issues
import qiskit_nature
qiskit_nature.settings.use_pauli_sum_op = False
import h5py
H5PY_DEFAULT_READONLY=1
# classically obtained ground state energy
EXPECTED_EIGENVALUE = -1.86
# specifying the geometry of the molecule in question
driver = PySCFDriver(
atom="H 0 0 0; H 0 0 0.735",
basis="sto3g",
charge=0,
spin=0,
unit=DistanceUnit.ANGSTROM,
)
problem = driver.run()
hamiltonian = problem.hamiltonian
# electronic Hamiltonian of the system
second_q_op = hamiltonian.second_q_op()
# The Bravyi-Kitaev repserentation of the Fermionic Hamiltonian
mapper = BravyiKitaevMapper()
bkencoded_hamiltonian = mapper.map(second_q_op)
print(bkencoded_hamiltonian)
def process_hamiltonian(hamiltonian, derandomize = False):
hamiltonian_observables = []
hamiltonian_coefficients = []
for observable in hamiltonian.paulis:
op_list = []
for op_index, pauli_op in enumerate(observable):
pauli_op = str(pauli_op)
if pauli_op == 'I' or pauli_op == 'X' or pauli_op == 'Y' or pauli_op == 'Z':
op_list.append((pauli_op, op_index))
hamiltonian_observables.append(op_list)
hamiltonian_coefficients = hamiltonian.coeffs.real
system_size = len(hamiltonian_observables[0])
# removing all occurrences of Pauli-I, for all-Pauli-I there is an empty list left
# these observables are needed for estimate_exp()
observables_xyze = []
for observable in hamiltonian_observables:
XYZE = []
for pauli in observable:
if pauli[0] != 'I':
XYZE.append(pauli)
observables_xyze.append(XYZE)
# derandomisation procedure requires that coefficients are non-negative
if derandomize == True:
absolute_coefficients = [abs(coeffcient) for coeffcient in hamiltonian_coefficients]
# removing the empty list as well
# these observables are needed for derandomisation procedure
observables_xyz = []
for idx, observable in enumerate(observables_xyze):
if observable:
observables_xyz.append(observable)
else:
absolute_coefficients.pop(idx)
return system_size, observables_xyze, observables_xyz, hamiltonian_coefficients, absolute_coefficients
return system_size, observables_xyze, hamiltonian_coefficients
# process the Hamiltonian to obtain properly formatted data
hamiltonian_data = process_hamiltonian(bkencoded_hamiltonian, derandomize = True)
system_size, observables_xyze, observables_xyz, hamiltonian_coefficients, absolute_coefficients = hamiltonian_data
#print('HAMILTONIAN\n', observables_xyze)
'''
VARIATIONAL ANSATZ
Note that for molecules other than H_2 you may need to specify a different number of reps.
'''
reps = 1
ansatz = EfficientSU2(system_size, su2_gates=['rx', 'ry'], entanglement='circular', reps=reps, skip_final_rotation_layer=False)
ansatz.decompose().draw('mpl')
'''
COST FUNCTION
'''
def basis_change_circuit(pauli_op):
# Generating circuit with just the basis change operators
#
# pauli_op: n-qubit Pauli operator
basis_change = QuantumCircuit(ansatz.num_qubits, ansatz.num_qubits)
for idx, op in enumerate(pauli_op):
if op == 'X':
basis_change.h(idx)
elif op == 'Y':
basis_change.h(idx)
basis_change.p(-np.pi/2, idx)
return basis_change
def min_cost():
return min(cost_history)
def log_cost(cost):
global cost_history
cost_history.append(cost)
def objective_function(operators, params):
backend = QasmSimulator(method='statevector', shots=1)
pauli_op_dict = Counter(tuple(x) for x in operators)
shadow = []
for pauli_op in pauli_op_dict:
qc = ansatz.bind_parameters(params)
qc = qc.compose(basis_change_circuit(pauli_op))
qc.measure(reversed(range(system_size)), range(system_size))
result = execute(qc, backend, shots=pauli_op_dict[pauli_op]).result()
counts = result.get_counts()
# generate a separate circuit for each basis change Pauli operator
output_str = list(list(counts.keys())[list(counts.values()).index(1)])
output = [int(i) for i in output_str]
eigenvals = [x+1 if x == 0 else x-2 for x in output]
snapshot = [(op, eigenval) for op, eigenval in zip(pauli_op, eigenvals)]
shadow.append(snapshot)
cost = 0.0
for term, weight in zip(observables_xyze, hamiltonian_coefficients):
sum_product, match_count = estimate_exp(shadow, term)
if match_count != 0:
exp_val = sum_product / match_count
cost += weight * exp_val
log_cost(cost)
return cost
'''
RUNNING EXPERIMENTS
'''
start_time = time.time()
rmse_errors = []
print('NUMBER OF OPERATORS | DERANDOMISED OPERATORS | AVERAGE RMSE ERROR\n')
measurement_range = [50, 100, 200, 600, 1000, 1600]
for num_operators in measurement_range:
derandomized_hamiltonian = modified_derandomized_classical_shadow(observables_xyz, num_operators,
system_size, weight=absolute_coefficients)
tuples = (tuple(pauli) for pauli in derandomized_hamiltonian)
counts = Counter(tuples)
optimizer = SPSA(maxiter=2000)
cost_function = partial(objective_function, derandomized_hamiltonian)
expectation_values = []
num_experiments = 5
for iteration in range(num_experiments):
cost_history = []
params = np.random.rand(ansatz.num_parameters)
result = optimizer.minimize(fun=cost_function, x0=params)
minimal_cost = min_cost()
expectation_values.append(minimal_cost)
print("EXPERIMENT {}: GROUND STATE ENERGY FOUND = {}".format(iteration, minimal_cost))
rmse_derandomised_cs = np.sqrt(np.sum([(expectation_values[i] - EXPECTED_EIGENVALUE)**2
for i in range(num_experiments)])/num_experiments)
rmse_errors.append(rmse_derandomised_cs)
print('{} | {} | {}'.format(num_operators, counts, rmse_derandomised_cs))
elapsed_time = time.time() - start_time
print("Execution time = ", time.strftime("%H:%M:%S", time.gmtime(elapsed_time)))
points = measurement_range
num_points = len(measurement_range)
plt.plot([i for i in points], [rmse_errors[i] for i in range(num_points)], 'r', label='SPSA(maxiter=2000)')
plt.xlabel('Number of measurements')
plt.ylabel('Average RMSE error')
plt.legend(loc=1)
'''
Above we have assumed a particular ground state energy for the molecule of interest.
Below we corroborate this assumption using a classical minimum eigensolver on our Hamiltonian.
'''
converter = BravyiKitaevMapper()
numpy_solver = NumPyMinimumEigensolver()
calc = GroundStateEigensolver(converter, numpy_solver)
res = calc.solve(problem)
print('Electronic ground state energy:\n', res)
|
https://github.com/renatawong/classical-shadow-vqe
|
renatawong
|
# Installation of the requirements
#!python -m pip install -r requirements.txt
'''
(C) Renata Wong 2023
Qiskit code for testing fidelity of derandomised classical shadow on the ground state energy of molecules.
This notebook implements an optimization: since the derandomized Hamiltonian may contan very few terms,
instead of generating a quantum circuit for each and measuring once, we generate a single circuit and specify
a shot number that matches the number of occurrences of a derandomized operator. This speeds up the computation
significantly.
Procedure:
1. Derandomize the molecule-in-question's Hamiltonian.
2. Choose a variational ansatz with initial parameters selected at random.
3. Apply the derandomized Hamiltonian as basis change operators to the ansatz.
4. Measure the ansatz in the Pauli Z basis and store the results as a shadow.
5. Obtain the expectation value of the molecular Hamiltonian from the shadow.
6. Optimize for minimum Hamiltonian expectation value.
7. Feed the calculated angles/parameters back to the ansatz.
8. Repeat steps 3-7 till the optimization is completed.
9. Output the minimized expectation value of the molecular Hamiltonian and the mean-square-root-error.
Note: Below we perform calculations on the molecular Hamiltonian of H_2.
To perform calculations on other molecules, you will need to specify their geometry, charge and spin
to replace the values in the driver.
'''
from qiskit import QuantumCircuit, execute
from qiskit_aer import QasmSimulator
from qiskit_nature.units import DistanceUnit
from qiskit_nature.second_q.drivers import PySCFDriver
from qiskit_nature.second_q.mappers import BravyiKitaevMapper
from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver
from qiskit_nature.second_q.algorithms import GroundStateEigensolver
from qiskit.circuit.library import EfficientSU2
from qiskit.algorithms.optimizers import SLSQP, COBYLA, SPSA
import time
import numpy as np
from functools import partial
import matplotlib.pyplot as plt
from collections import Counter
from predicting_quantum_properties.prediction_shadow import estimate_exp
from modified_derandomization import modified_derandomized_classical_shadow
# handle deprecation issues
import qiskit_nature
qiskit_nature.settings.use_pauli_sum_op = False
import h5py
H5PY_DEFAULT_READONLY=1
# classically obtained ground state energy
EXPECTED_EIGENVALUE = -1.86
# specifying the geometry of the molecule in question
driver = PySCFDriver(
atom="H 0 0 0; H 0 0 0.735",
basis="sto3g",
charge=0,
spin=0,
unit=DistanceUnit.ANGSTROM,
)
problem = driver.run()
hamiltonian = problem.hamiltonian
# electronic Hamiltonian of the system
second_q_op = hamiltonian.second_q_op()
# The Bravyi-Kitaev repserentation of the Fermionic Hamiltonian
mapper = BravyiKitaevMapper()
bkencoded_hamiltonian = mapper.map(second_q_op)
print(bkencoded_hamiltonian)
def process_hamiltonian(hamiltonian, derandomize = False):
hamiltonian_observables = []
hamiltonian_coefficients = []
for observable in hamiltonian.paulis:
op_list = []
for op_index, pauli_op in enumerate(observable):
pauli_op = str(pauli_op)
if pauli_op == 'I' or pauli_op == 'X' or pauli_op == 'Y' or pauli_op == 'Z':
op_list.append((pauli_op, op_index))
hamiltonian_observables.append(op_list)
hamiltonian_coefficients = hamiltonian.coeffs.real
system_size = len(hamiltonian_observables[0])
# removing all occurrences of Pauli-I, for all-Pauli-I there is an empty list left
# these observables are needed for estimate_exp()
observables_xyze = []
for observable in hamiltonian_observables:
XYZE = []
for pauli in observable:
if pauli[0] != 'I':
XYZE.append(pauli)
observables_xyze.append(XYZE)
# derandomisation procedure requires that coefficients are non-negative
if derandomize == True:
absolute_coefficients = [abs(coeffcient) for coeffcient in hamiltonian_coefficients]
# removing the empty list as well
# these observables are needed for derandomisation procedure
observables_xyz = []
for idx, observable in enumerate(observables_xyze):
if observable:
observables_xyz.append(observable)
else:
absolute_coefficients.pop(idx)
return system_size, observables_xyze, observables_xyz, hamiltonian_coefficients, absolute_coefficients
return system_size, observables_xyze, hamiltonian_coefficients
# process the Hamiltonian to obtain properly formatted data
hamiltonian_data = process_hamiltonian(bkencoded_hamiltonian, derandomize = True)
system_size, observables_xyze, observables_xyz, hamiltonian_coefficients, absolute_coefficients = hamiltonian_data
#print('HAMILTONIAN\n', observables_xyze)
'''
VARIATIONAL ANSATZ
Note that for molecules other than H_2 you may need to specify a different number of reps.
'''
reps = 1
ansatz = EfficientSU2(system_size, su2_gates=['rx', 'ry'], entanglement='circular', reps=reps, skip_final_rotation_layer=False)
ansatz.decompose().draw('mpl')
'''
COST FUNCTION
'''
def basis_change_circuit(pauli_op):
# Generating circuit with just the basis change operators
#
# pauli_op: n-qubit Pauli operator
basis_change = QuantumCircuit(ansatz.num_qubits, ansatz.num_qubits)
for idx, op in enumerate(pauli_op):
if op == 'X':
basis_change.h(idx)
elif op == 'Y':
basis_change.h(idx)
basis_change.p(-np.pi/2, idx)
return basis_change
def min_cost():
return min(cost_history)
def log_cost(cost):
global cost_history
cost_history.append(cost)
def objective_function(operators, params):
backend = QasmSimulator(method='statevector', shots=1)
pauli_op_dict = Counter(tuple(x) for x in operators)
shadow = []
for pauli_op in pauli_op_dict:
qc = ansatz.bind_parameters(params)
qc = qc.compose(basis_change_circuit(pauli_op))
qc.measure(reversed(range(system_size)), range(system_size))
result = execute(qc, backend, shots=pauli_op_dict[pauli_op]).result()
counts = result.get_counts()
for count in counts:
for _ in range(counts[count]): # number of repeated measurement values
output_str = list(count)
output = [int(i) for i in output_str]
eigenvals = [x+1 if x == 0 else x-2 for x in output]
snapshot = [(op, eigenval) for op, eigenval in zip(pauli_op, eigenvals)]
shadow.append(snapshot)
cost = 0.0
for term, weight in zip(observables_xyze, hamiltonian_coefficients):
sum_product, match_count = estimate_exp(shadow, term)
if match_count != 0:
exp_val = sum_product / match_count
cost += weight * exp_val
log_cost(cost)
return cost
'''
RUNNING EXPERIMENTS
'''
start_time = time.time()
rmse_errors = []
print('NUMBER OF OPERATORS | DERANDOMISED OPERATORS | AVERAGE RMSE ERROR\n')
measurement_range = [50, 100, 200, 600, 1000, 1600]
for num_operators in measurement_range:
derandomized_hamiltonian = modified_derandomized_classical_shadow(observables_xyz, num_operators,
system_size, weight=absolute_coefficients)
tuples = (tuple(pauli) for pauli in derandomized_hamiltonian)
counts = Counter(tuples)
optimizer = SPSA(maxiter=2000)
cost_function = partial(objective_function, derandomized_hamiltonian)
expectation_values = []
num_experiments = 3
for iteration in range(num_experiments):
cost_history = []
params = np.random.rand(ansatz.num_parameters)
result = optimizer.minimize(fun=cost_function, x0=params)
minimal_cost = min_cost()
expectation_values.append(minimal_cost)
print("EXPERIMENT {}: GROUND STATE ENERGY FOUND = {}".format(iteration, minimal_cost))
rmse_derandomised_cs = np.sqrt(np.sum([(expectation_values[i] - EXPECTED_EIGENVALUE)**2
for i in range(num_experiments)])/num_experiments)
rmse_errors.append(rmse_derandomised_cs)
print('{} | {} | {}'.format(num_operators, counts, rmse_derandomised_cs))
elapsed_time = time.time() - start_time
print("Execution time = ", time.strftime("%H:%M:%S", time.gmtime(elapsed_time)))
points = measurement_range
num_points = len(measurement_range)
plt.plot([i for i in points], [rmse_errors[i] for i in range(num_points)], 'r', label='SPSA(maxiter=2000)')
plt.xlabel('Number of measurements')
plt.ylabel('Average RMSE error')
plt.legend(loc=1)
|
https://github.com/renatawong/classical-shadow-vqe
|
renatawong
|
# Installation of the requirements
#!python -m pip install -r requirements.txt
'''
(C) Renata Wong 2023
Qiskit code for testing fidelity of randomised classical shadow on the ground state energy of molecules.
Procedure:
1. Choose a variational ansatz with initial parameters selected at random.
2. Generate a set of random basis change operators.
3. Apply the random operators to change bases in the ansatz.
4. Measure the ansatz in the Pauli Z basis and store the results as a shadow.
5. Obtain the expectation value of the molecular Hamiltonian from the shadow.
6. Optimize for minimum Hamiltonian expectation value.
7. Feed the calculated angles/parameters back to the ansatz.
8. Repeat steps 3-7 till the optimization is completed.
9. Output the minimized expectation value of the molecular Hamiltonian and the mean-square-root-error.
Note: Below we perform calculations on the molecular Hamiltonian of H_2.
To perform calculations on other molecules, you will need to specify their geometry, charge and spin
to replace the values in the driver.
Note: predicting_quantum_properties module comes from https://github.com/hsinyuan-huang/predicting-quantum-properties
'''
from qiskit import QuantumCircuit, execute
from qiskit_aer import QasmSimulator
from qiskit_nature.units import DistanceUnit
from qiskit_nature.second_q.drivers import PySCFDriver
from qiskit_nature.second_q.mappers import BravyiKitaevMapper
from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver
from qiskit_nature.second_q.algorithms import GroundStateEigensolver
from qiskit.circuit.library import EfficientSU2
from qiskit.algorithms.optimizers import SLSQP, COBYLA, SPSA
import time
import numpy as np
from functools import partial
import matplotlib.pyplot as plt
from collections import Counter
from predicting_quantum_properties.data_acquisition_shadow import randomized_classical_shadow
from predicting_quantum_properties.prediction_shadow import estimate_exp
# handle deprecation issues
import qiskit_nature
qiskit_nature.settings.use_pauli_sum_op = False
import h5py
H5PY_DEFAULT_READONLY=1
# classically obtained ground state energy
EXPECTED_EIGENVALUE = -1.86
# specifying the geometry of the molecule in question
driver = PySCFDriver(
atom="H 0 0 0; H 0 0 0.735",
basis="sto3g",
charge=0,
spin=0,
unit=DistanceUnit.ANGSTROM,
)
problem = driver.run()
hamiltonian = problem.hamiltonian
# electronic Hamiltonian of the system
second_q_op = hamiltonian.second_q_op()
# The Bravyi-Kitaev repserentation of the Fermionic Hamiltonian
mapper = BravyiKitaevMapper()
bkencoded_hamiltonian = mapper.map(second_q_op)
print(bkencoded_hamiltonian)
def process_hamiltonian(hamiltonian, derandomize = False):
hamiltonian_observables = []
hamiltonian_coefficients = []
for observable in hamiltonian.paulis:
op_list = []
for op_index, pauli_op in enumerate(observable):
pauli_op = str(pauli_op)
if pauli_op == 'I' or pauli_op == 'X' or pauli_op == 'Y' or pauli_op == 'Z':
op_list.append((pauli_op, op_index))
hamiltonian_observables.append(op_list)
hamiltonian_coefficients = hamiltonian.coeffs.real
system_size = len(hamiltonian_observables[0])
# removing all occurrences of Pauli-I, for all-Pauli-I there is an empty list left
# these observables are needed for estimate_exp()
observables_xyze = []
for observable in hamiltonian_observables:
XYZE = []
for pauli in observable:
if pauli[0] != 'I':
XYZE.append(pauli)
observables_xyze.append(XYZE)
# derandomisation procedure requires that coefficients are non-negative
if derandomize == True:
absolute_coefficients = [abs(coeffcient) for coeffcient in hamiltonian_coefficients]
# removing the empty list as well
# these observables are needed for derandomisation procedure
observables_xyz = []
for idx, observable in enumerate(observables_xyze):
if observable:
observables_xyz.append(observable)
else:
absolute_coefficients.pop(idx)
return system_size, observables_xyze, observables_xyz, hamiltonian_coefficients, absolute_coefficients
return system_size, observables_xyze, hamiltonian_coefficients
# process the Hamiltonian to obtain properly formatted data
hamiltonian_data = process_hamiltonian(bkencoded_hamiltonian, derandomize = False)
system_size, observables_xyze, hamiltonian_coefficients = hamiltonian_data
#print('HAMILTONIAN\n', observables_xyze)
'''
VARIATIONAL ANSATZ
Note that for molecules other than H_2 you may need to specify a different number of reps.
'''
reps = 1
ansatz = EfficientSU2(system_size, su2_gates=['rx', 'ry'], entanglement='circular', reps=reps, skip_final_rotation_layer=False)
ansatz.decompose().draw('mpl')
'''
COST FUNCTION
'''
def basis_change_circuit(pauli_op):
# Generating circuit with just the basis change operators
#
# pauli_op: n-qubit Pauli operator
basis_change = QuantumCircuit(ansatz.num_qubits, ansatz.num_qubits)
for idx, op in enumerate(pauli_op):
if op == 'X':
basis_change.h(idx)
elif op == 'Y':
basis_change.h(idx)
basis_change.p(-np.pi/2, idx)
return basis_change
def min_cost():
return min(cost_history)
def log_cost(cost):
global cost_history
cost_history.append(cost)
def objective_function(operators, params):
backend = QasmSimulator(method='statevector', shots=1)
pauli_op_dict = Counter(tuple(x) for x in operators)
shadow = []
for pauli_op in pauli_op_dict:
qc = ansatz.bind_parameters(params)
qc = qc.compose(basis_change_circuit(pauli_op))
qc.measure(reversed(range(system_size)), range(system_size))
result = execute(qc, backend, shots=pauli_op_dict[pauli_op]).result()
counts = result.get_counts()
# generate a separate circuit for each basis change Pauli operator
output_str = list(list(counts.keys())[list(counts.values()).index(1)])
output = [int(i) for i in output_str]
eigenvals = [x+1 if x == 0 else x-2 for x in output]
snapshot = [(op, eigenval) for op, eigenval in zip(pauli_op, eigenvals)]
shadow.append(snapshot)
cost = 0.0
for term, weight in zip(observables_xyze, hamiltonian_coefficients):
sum_product, match_count = estimate_exp(shadow, term)
if match_count != 0:
exp_val = sum_product / match_count
cost += weight * exp_val
log_cost(cost)
return cost
'''
RUNNING EXPERIMENTS
'''
start_time = time.time()
rmse_errors = []
print('NUMBER OF OPERATORS | RANDOMISED OPERATORS | AVERAGE RMSE ERROR\n')
measurement_range = [50, 100, 200, 600, 1000, 1600]
for num_operators in measurement_range:
basis_change = randomized_classical_shadow(num_operators, system_size)
tuples = (tuple(pauli) for pauli in basis_change)
counts = Counter(tuples)
optimizer = SPSA(maxiter=2000)
cost_function = partial(objective_function, basis_change)
expectation_values = []
num_experiments = 5
for iteration in range(num_experiments):
cost_history = []
params = np.random.rand(ansatz.num_parameters)
result = optimizer.minimize(fun=cost_function, x0=params)
minimal_cost = min_cost()
expectation_values.append(minimal_cost)
print("EXPERIMENT {}: GROUND STATE ENERGY FOUND = {}".format(iteration, minimal_cost))
rmse_randomised_cs = np.sqrt(np.sum([(expectation_values[i] - EXPECTED_EIGENVALUE)**2
for i in range(num_experiments)])/num_experiments)
rmse_errors.append(rmse_randomised_cs)
print('{} | {} | {}'.format(num_operators, counts, rmse_randomised_cs))
elapsed_time = time.time() - start_time
print("Execution time = ", time.strftime("%H:%M:%S", time.gmtime(elapsed_time)))
points = measurement_range
num_points = len(measurement_range)
plt.plot([i for i in points], [rmse_errors[i] for i in range(num_points)], 'r', label='SPSA(maxiter=2000)')
plt.xlabel('Number of measurements')
plt.ylabel('Average RMSE error')
plt.legend(loc=1)
|
https://github.com/renatawong/classical-shadow-vqe
|
renatawong
|
# Installation of the requirements
#!python -m pip install -r requirements.txt
'''
(C) Renata Wong 2023
Qiskit code for testing fidelity of randomised classical shadow on the ground state energy of molecules.
Procedure:
1. Choose a variational ansatz with initial parameters selected at random.
2. Generate a set of random basis change operators.
3. Apply the random operators to change bases in the ansatz.
4. Measure the ansatz in the Pauli Z basis and store the results as a shadow.
5. Obtain the expectation value of the molecular Hamiltonian from the shadow.
6. Optimize for minimum Hamiltonian expectation value.
7. Feed the calculated angles/parameters back to the ansatz.
8. Repeat steps 3-7 till the optimization is completed.
9. Output the minimized expectation value of the molecular Hamiltonian and the mean-square-root-error.
Note: Below we perform calculations on the molecular Hamiltonian of H_2.
To perform calculations on other molecules, you will need to specify their geometry, charge and spin
to replace the values in the driver.
Note: predicting_quantum_properties module comes from https://github.com/hsinyuan-huang/predicting-quantum-properties
'''
from qiskit import QuantumCircuit, execute
from qiskit_aer import QasmSimulator
from qiskit_nature.units import DistanceUnit
from qiskit_nature.second_q.drivers import PySCFDriver
from qiskit_nature.second_q.mappers import BravyiKitaevMapper
from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver
from qiskit_nature.second_q.algorithms import GroundStateEigensolver
from qiskit.circuit.library import EfficientSU2
from qiskit.algorithms.optimizers import SLSQP, COBYLA, SPSA
import time
import numpy as np
from functools import partial
import matplotlib.pyplot as plt
from collections import Counter
from predicting_quantum_properties.data_acquisition_shadow import randomized_classical_shadow
from predicting_quantum_properties.prediction_shadow import estimate_exp
# handle deprecation issues
import qiskit_nature
qiskit_nature.settings.use_pauli_sum_op = False
import h5py
H5PY_DEFAULT_READONLY=1
# classically obtained ground state energy
EXPECTED_EIGENVALUE = -1.86
# specifying the geometry of the molecule in question
driver = PySCFDriver(
atom="H 0 0 0; H 0 0 0.735",
basis="sto3g",
charge=0,
spin=0,
unit=DistanceUnit.ANGSTROM,
)
problem = driver.run()
hamiltonian = problem.hamiltonian
# electronic Hamiltonian of the system
second_q_op = hamiltonian.second_q_op()
# The Bravyi-Kitaev repserentation of the Fermionic Hamiltonian
mapper = BravyiKitaevMapper()
bkencoded_hamiltonian = mapper.map(second_q_op)
print(bkencoded_hamiltonian)
def process_hamiltonian(hamiltonian, derandomize = False):
hamiltonian_observables = []
hamiltonian_coefficients = []
for observable in hamiltonian.paulis:
op_list = []
for op_index, pauli_op in enumerate(observable):
pauli_op = str(pauli_op)
if pauli_op == 'I' or pauli_op == 'X' or pauli_op == 'Y' or pauli_op == 'Z':
op_list.append((pauli_op, op_index))
hamiltonian_observables.append(op_list)
hamiltonian_coefficients = hamiltonian.coeffs.real
system_size = len(hamiltonian_observables[0])
# removing all occurrences of Pauli-I, for all-Pauli-I there is an empty list left
# these observables are needed for estimate_exp()
observables_xyze = []
for observable in hamiltonian_observables:
XYZE = []
for pauli in observable:
if pauli[0] != 'I':
XYZE.append(pauli)
observables_xyze.append(XYZE)
# derandomisation procedure requires that coefficients are non-negative
if derandomize == True:
absolute_coefficients = [abs(coeffcient) for coeffcient in hamiltonian_coefficients]
# removing the empty list as well
# these observables are needed for derandomisation procedure
observables_xyz = []
for idx, observable in enumerate(observables_xyze):
if observable:
observables_xyz.append(observable)
else:
absolute_coefficients.pop(idx)
return system_size, observables_xyze, observables_xyz, hamiltonian_coefficients, absolute_coefficients
return system_size, observables_xyze, hamiltonian_coefficients
# process the Hamiltonian to obtain properly formatted data
hamiltonian_data = process_hamiltonian(bkencoded_hamiltonian, derandomize = False)
system_size, observables_xyze, hamiltonian_coefficients = hamiltonian_data
#print('HAMILTONIAN\n', observables_xyze)
'''
VARIATIONAL ANSATZ
Note that for molecules other than H_2 you may need to specify a different number of reps.
'''
reps = 1
ansatz = EfficientSU2(system_size, su2_gates=['rx', 'ry'], entanglement='circular', reps=reps, skip_final_rotation_layer=False)
ansatz.decompose().draw('mpl')
'''
COST FUNCTION
'''
def basis_change_circuit(pauli_op):
# Generating circuit with just the basis change operators
#
# pauli_op: n-qubit Pauli operator
basis_change = QuantumCircuit(ansatz.num_qubits, ansatz.num_qubits)
for idx, op in enumerate(pauli_op):
if op == 'X':
basis_change.h(idx)
elif op == 'Y':
basis_change.h(idx)
basis_change.p(-np.pi/2, idx)
return basis_change
def min_cost():
return min(cost_history)
def log_cost(cost):
global cost_history
cost_history.append(cost)
def objective_function(operators, params):
backend = QasmSimulator(method='statevector', shots=1)
pauli_op_dict = Counter(tuple(x) for x in operators)
shadow = []
for pauli_op in pauli_op_dict:
qc = ansatz.bind_parameters(params)
qc = qc.compose(basis_change_circuit(pauli_op))
qc.measure(reversed(range(system_size)), range(system_size))
result = execute(qc, backend, shots=pauli_op_dict[pauli_op]).result()
counts = result.get_counts()
for count in counts:
for _ in range(counts[count]): # number of repeated measurement values
output_str = list(count)
output = [int(i) for i in output_str]
eigenvals = [x+1 if x == 0 else x-2 for x in output]
snapshot = [(op, eigenval) for op, eigenval in zip(pauli_op, eigenvals)]
shadow.append(snapshot)
cost = 0.0
for term, weight in zip(observables_xyze, hamiltonian_coefficients):
sum_product, match_count = estimate_exp(shadow, term)
if match_count != 0:
exp_val = sum_product / match_count
cost += weight * exp_val
log_cost(cost)
return cost
'''
RUNNING EXPERIMENTS
'''
start_time = time.time()
rmse_errors = []
print('NUMBER OF OPERATORS | RANDOMISED OPERATORS | AVERAGE RMSE ERROR\n')
measurement_range = [50, 100, 200, 600, 1000, 1600]
for num_operators in measurement_range:
basis_change = randomized_classical_shadow(num_operators, system_size)
tuples = (tuple(pauli) for pauli in basis_change)
counts = Counter(tuples)
optimizer = SPSA(maxiter=2000)
cost_function = partial(objective_function, basis_change)
expectation_values = []
num_experiments = 5
for iteration in range(num_experiments):
cost_history = []
params = np.random.rand(ansatz.num_parameters)
result = optimizer.minimize(fun=cost_function, x0=params)
minimal_cost = min_cost()
expectation_values.append(minimal_cost)
print("EXPERIMENT {}: GROUND STATE ENERGY FOUND = {}".format(iteration, minimal_cost))
rmse_randomised_cs = np.sqrt(np.sum([(expectation_values[i] - EXPECTED_EIGENVALUE)**2
for i in range(num_experiments)])/num_experiments)
rmse_errors.append(rmse_randomised_cs)
print('{} | {} | {}'.format(num_operators, counts, rmse_randomised_cs))
elapsed_time = time.time() - start_time
print("Execution time = ", time.strftime("%H:%M:%S", time.gmtime(elapsed_time)))
points = measurement_range
num_points = len(measurement_range)
plt.plot([i for i in points], [rmse_errors[i] for i in range(num_points)], 'r', label='SPSA(maxiter=2000)')
plt.xlabel('Number of measurements')
plt.ylabel('Average RMSE error')
plt.legend(loc=1)
|
https://github.com/renatawong/classical-shadow-vqe
|
renatawong
|
'''
(C) 2023 Renata Wong
Electronic structure problem with classical shadows, as presented in https://arxiv.org/abs/2103.07510
This code uses Qiskit as platform.
The shadow is constructed based on derandomized Hamiltonian.
The molecules tested are: H2 (6-31s basis), LiH (sto3g basis), BeH2 (sto3g), H2O (sto3g), and NH3 (sto3g).
The coordinates for NH3 were taken from 'Algorithms for Computer Detection of Symmetry Elementsin Molecular Systems'.
'''
import time
import numpy as np
from collections import Counter
import matplotlib.pyplot as plt
from qiskit import QuantumCircuit, execute
from qiskit_aer.primitives import Estimator as AerEstimator
from qiskit_aer import QasmSimulator
from qiskit.quantum_info import SparsePauliOp
from qiskit_nature.units import DistanceUnit
from qiskit_nature.second_q.drivers import PySCFDriver
from qiskit_nature.second_q.algorithms import GroundStateEigensolver
from qiskit_nature.second_q.mappers import BravyiKitaevMapper, JordanWignerMapper, ParityMapper
from qiskit_nature.second_q.circuit.library import UCCSD, HartreeFock
from qiskit_nature.second_q.algorithms import VQEUCCFactory
from qiskit.algorithms.minimum_eigensolvers import VQE
from qiskit.algorithms.optimizers import SLSQP, COBYLA, SPSA
# Estimator primitive is based on the Statevector construct = algebraic simulation
from qiskit.primitives import Estimator
from qiskit.utils import algorithm_globals
from modified_derandomization import modified_derandomized_classical_shadow
from predicting_quantum_properties.data_acquisition_shadow import derandomized_classical_shadow
from predicting_quantum_properties.prediction_shadow import estimate_exp
import qiskit_nature
qiskit_nature.settings.use_pauli_sum_op = False
import h5py
H5PY_DEFAULT_READONLY=1
'''
DEFINING DRIVERS FOR THE MOLECULES
'''
H2_driver = PySCFDriver(
atom="H 0 0 0; H 0 0 0.735",
basis="6-31g",
charge=0,
spin=0,
unit=DistanceUnit.ANGSTROM,
)
LiH_driver = PySCFDriver(
atom="Li 0 0 0; H 0 0 1.599",
basis="sto3g",
charge=0,
spin=0,
unit=DistanceUnit.ANGSTROM,
)
BeH2_driver = PySCFDriver(
atom="Be 0 0 0; H 0 0 1.3264; H 0 0 -1.3264",
basis="sto3g",
charge=0,
spin=0,
unit=DistanceUnit.ANGSTROM,
)
H2O_driver = PySCFDriver(
atom="O 0.0 0.0 0.0; H 0.757 0.586 0.0; H -0.757 0.586 0.0",
basis="sto3g",
charge=0,
spin=0,
unit=DistanceUnit.ANGSTROM,
)
NH3_driver = PySCFDriver(
atom="N 0 0 0; H 0 0 1.008000; H 0.950353 0 -0.336000; H -0.475176 -0.823029 -0.336000",
basis="sto3g",
charge=0,
spin=0,
unit=DistanceUnit.ANGSTROM,
)
'''
FORMATTING HAMILTONIAN
'''
def process_hamiltonian(hamiltonian, derandomize = False):
hamiltonian_observables = []
hamiltonian_coefficients = []
for observable in hamiltonian.paulis:
op_list = []
for op_index, pauli_op in enumerate(observable):
pauli_op = str(pauli_op)
if pauli_op == 'I' or pauli_op == 'X' or pauli_op == 'Y' or pauli_op == 'Z':
op_list.append((pauli_op, op_index))
hamiltonian_observables.append(op_list)
hamiltonian_coefficients = hamiltonian.coeffs.real
system_size = len(hamiltonian_observables[0])
# removing all occurrences of Pauli-I, for all-Pauli-I there is an empty list left
# these observables are needed for estimate_exp()
observables_xyze = []
for observable in hamiltonian_observables:
XYZE = []
for pauli in observable:
if pauli[0] != 'I':
XYZE.append(pauli)
observables_xyze.append(XYZE)
# derandomisation procedure requires that coefficients are non-negative
if derandomize == True:
absolute_coefficients = [abs(coeffcient) for coeffcient in hamiltonian_coefficients]
# removing the empty list as well
# these observables are needed for derandomisation procedure
observables_xyz = []
for idx, observable in enumerate(observables_xyze):
if observable:
observables_xyz.append(observable)
else:
absolute_coefficients.pop(idx)
return system_size, observables_xyze, observables_xyz, hamiltonian_coefficients, absolute_coefficients
return system_size, observables_xyze, hamiltonian_coefficients
'''
COST FUNCTION AND HELPER FUNCTIONS
'''
def basis_change_circuit(pauli_op):
# Generating circuit with just the basis change operators
#
# pauli_op: n-qubit Pauli operator
basis_change = QuantumCircuit(ansatz.num_qubits, ansatz.num_qubits)
for idx, op in enumerate(pauli_op):
if op == 'X':
basis_change.h(idx)
if op == 'Y':
basis_change.h(idx)
basis_change.p(-np.pi/2, idx)
return basis_change
def ground_state_energy_from_shadow(operators, params):
backend = QasmSimulator(method='statevector', shots=1)
pauli_op_dict = Counter(tuple(x) for x in operators)
shadow = []
for pauli_op in pauli_op_dict:
qc = ansatz.bind_parameters(params)
qc = qc.compose(basis_change_circuit(pauli_op))
qc.measure(reversed(range(system_size)), range(system_size))
result = execute(qc, backend, shots=pauli_op_dict[pauli_op]).result()
counts = result.get_counts() # given in order q0 q1 ... qn-1 after register reversal in qc.measure
for count in counts:
for _ in range(counts[count]): # number of repeated measurement values
output_str = list(count)
output = [int(i) for i in output_str]
eigenvals = [x+1 if x == 0 else x-2 for x in output]
snapshot = [(op, eigenval) for op, eigenval in zip(pauli_op, eigenvals)]
shadow.append(snapshot)
expectation_value = 0.0
for term, weight in zip(observables_xyze, hamiltonian_coefficients):
sum_product, match_count = estimate_exp(shadow, term)
if match_count != 0:
expectation_value += (weight * sum_product / match_count)
return expectation_value
'''
EXPERIMENTS
'''
start_time = time.time()
all_molecules_rmse_errors = []
# CALCULATING FERMIONIC HAMILTONIAN AND CONVERTING TO QUBIT HAMILTONIAN
MOLECULES = ['BeH2']
for molecule in MOLECULES:
rmse_errors = []
if molecule == 'H2':
problem = H2_driver.run()
if molecule == 'LiH':
problem = LiH_driver.run()
if molecule == 'BeH2':
problem = BeH2_driver.run()
if molecule == 'H2O':
problem = H2O_driver.run()
if molecule == 'NH3':
problem = NH3_driver.run()
hamiltonian = problem.hamiltonian
second_q_op = hamiltonian.second_q_op()
bk_mapper = BravyiKitaevMapper() #(num_particles=problem.num_particles) #BravyiKitaevMapper()
bkencoded_hamiltonian = bk_mapper.map(second_q_op)
#print('Qubit Hamiltonian in Bravyi-Kitaev encoding', bkencoded_hamiltonian)
# process the Hamiltonian to obtain properly formatted data
hamiltonian_data = process_hamiltonian(bkencoded_hamiltonian, derandomize = True)
system_size, observables_xyze, observables_xyz, hamiltonian_coefficients, absolute_coefficients = hamiltonian_data
'''
VARIATIONAL ANSATZ
'''
ansatz = UCCSD(
problem.num_spatial_orbitals,
problem.num_particles,
bk_mapper,
initial_state=HartreeFock(
problem.num_spatial_orbitals,
problem.num_particles,
bk_mapper,
),
)
'''
Running VQE on the Hamiltonian obtained from PySCFDriver using Statevector simulator (Estimator primitive)
'''
#estimator = Estimator()
# If shots = None, it calculates the exact expectation values. Otherwise, it samples from normal distributions
# with standard errors as standard deviations using normal distribution approximation.
#estimator.set_options(shots = None)
#estimator = AerEstimator()
#estimator.set_options(approximation=False, shots=None)
#vqe_solver = VQE(estimator, ansatz, SLSQP())
vqe_solver = VQE(Estimator(), ansatz, SLSQP())
vqe_solver.initial_point = np.zeros(ansatz.num_parameters)
calc = GroundStateEigensolver(bk_mapper, vqe_solver)
result = calc.solve(problem)
print(result.raw_result)
#print('NUMBER OF OPERATORS | DERANDOMISED OPERATORS | AVERAGE RMSE ERROR\n')
measurement_range = [50, 250, 500, 750, 1000, 1250, 1500, 1750]
for num_operators in measurement_range:
derandomized_hamiltonian = derandomized_classical_shadow(observables_xyz, 50,
system_size, weight=absolute_coefficients)
tuples = (tuple(pauli) for pauli in derandomized_hamiltonian)
counts = Counter(tuples)
print('Original derandomized Hamiltonian', counts)
# derandomized classical shadow will usually either undergenerate or overgenerate derandomized operators
# adjusting for this issue:
while sum(counts.values()) != num_operators:
for key, value in zip(counts.keys(), counts.values()):
sum_counts = sum(counts.values())
if sum_counts == num_operators:
break
if sum_counts < num_operators:
# generate additional operators from the existing ones by increasing the number of counts
counts[key] += 1
if sum_counts > num_operators:
# remove the element with highest count
max_element_key = [k for k, v in counts.items() if v == max(counts.values())][0]
counts[max_element_key] -= 1
print('Size-adjusted derandomized Hamiltonian', counts)
# translate the Counter to a set of derandomized operators
new_derandomized_hamiltonian = []
for key, value in counts.items():
for _ in range(value):
new_derandomized_hamiltonian.append(list(key))
#print('Size-adjusted derandomized Hamiltonian', new_derandomized_hamiltonian)
expectation_values = []
num_experiments = 10
for iteration in range(num_experiments):
expectation_value = ground_state_energy_from_shadow(new_derandomized_hamiltonian, result.raw_result.optimal_point)
expectation_values.append(expectation_value)
print("EXPERIMENT {}: GROUND STATE ENERGY FOUND = {}".format(iteration, expectation_value))
rmse_derandomised_cs = np.sqrt(np.sum([(expectation_values[i] - result.raw_result.optimal_value)**2
for i in range(num_experiments)])/num_experiments)
rmse_errors.append(rmse_derandomised_cs)
print('{} | {} | {}'.format(num_operators, counts, rmse_derandomised_cs))
all_molecules_rmse_errors.append(rmse_errors)
elapsed_time = time.time() - start_time
print("Execution time = ", time.strftime("%H:%M:%S", time.gmtime(elapsed_time)))
import matplotlib.pyplot as plt
points = measurement_range
num_points = len(points)
plt.plot([i for i in points], [rmse_errors[i] for i in range(num_points)], 'r', label='derandomized classical shadow')
plt.xlabel('Number of measurements')
plt.ylabel('Average RMSE error')
plt.legend(loc=1)
|
https://github.com/renatawong/classical-shadow-vqe
|
renatawong
|
'''
(C) 2023 Renata Wong
Electronic structure problem with classical shadows, as presented in https://arxiv.org/abs/2103.07510
This code uses Qiskit as platform.
The shadow is constructed based on derandomized Hamiltonian.
The molecules tested are: H2 (6-31s basis), LiH (sto3g basis), BeH2 (sto3g), H2O (sto3g), and NH3 (sto3g).
The coordinates for NH3 were taken from 'Algorithms for Computer Detection of Symmetry Elementsin Molecular Systems'.
'''
import time
import numpy as np
from collections import Counter
import matplotlib.pyplot as plt
from qiskit import QuantumCircuit, execute
from qiskit_aer.primitives import Estimator as AerEstimator
from qiskit_aer import QasmSimulator
from qiskit.quantum_info import SparsePauliOp
from qiskit_nature.units import DistanceUnit
from qiskit_nature.second_q.drivers import PySCFDriver
from qiskit_nature.second_q.algorithms import GroundStateEigensolver
from qiskit_nature.second_q.mappers import BravyiKitaevMapper, JordanWignerMapper, ParityMapper
from qiskit_nature.second_q.circuit.library import UCCSD, HartreeFock
from qiskit_nature.second_q.algorithms import VQEUCCFactory
from qiskit.algorithms.minimum_eigensolvers import VQE
from qiskit.algorithms.optimizers import SLSQP, COBYLA, SPSA
# Estimator primitive is based on the Statevector construct = algebraic simulation
from qiskit.primitives import Estimator
from qiskit.utils import algorithm_globals
from modified_derandomization import modified_derandomized_classical_shadow
from predicting_quantum_properties.data_acquisition_shadow import derandomized_classical_shadow
from predicting_quantum_properties.prediction_shadow import estimate_exp
import qiskit_nature
qiskit_nature.settings.use_pauli_sum_op = False
import h5py
H5PY_DEFAULT_READONLY=1
'''
DEFINING DRIVERS FOR THE MOLECULES
'''
H2_driver = PySCFDriver(
atom="H 0 0 0; H 0 0 0.735",
basis="6-31g",
charge=0,
spin=0,
unit=DistanceUnit.ANGSTROM,
)
LiH_driver = PySCFDriver(
atom="Li 0 0 0; H 0 0 1.599",
basis="sto3g",
charge=0,
spin=0,
unit=DistanceUnit.ANGSTROM,
)
BeH2_driver = PySCFDriver(
atom="Be 0 0 0; H 0 0 1.3264; H 0 0 -1.3264",
basis="sto3g",
charge=0,
spin=0,
unit=DistanceUnit.ANGSTROM,
)
H2O_driver = PySCFDriver(
atom="O 0.0 0.0 0.0; H 0.757 0.586 0.0; H -0.757 0.586 0.0",
basis="sto3g",
charge=0,
spin=0,
unit=DistanceUnit.ANGSTROM,
)
NH3_driver = PySCFDriver(
atom="N 0 0 0; H 0 0 1.008000; H 0.950353 0 -0.336000; H -0.475176 -0.823029 -0.336000",
basis="sto3g",
charge=0,
spin=0,
unit=DistanceUnit.ANGSTROM,
)
'''
FORMATTING HAMILTONIAN
'''
def process_hamiltonian(hamiltonian, derandomize = False):
hamiltonian_observables = []
hamiltonian_coefficients = []
for observable in hamiltonian.paulis:
op_list = []
for op_index, pauli_op in enumerate(observable):
pauli_op = str(pauli_op)
if pauli_op == 'I' or pauli_op == 'X' or pauli_op == 'Y' or pauli_op == 'Z':
op_list.append((pauli_op, op_index))
hamiltonian_observables.append(op_list)
hamiltonian_coefficients = hamiltonian.coeffs.real
system_size = len(hamiltonian_observables[0])
# removing all occurrences of Pauli-I, for all-Pauli-I there is an empty list left
# these observables are needed for estimate_exp()
observables_xyze = []
for observable in hamiltonian_observables:
XYZE = []
for pauli in observable:
if pauli[0] != 'I':
XYZE.append(pauli)
observables_xyze.append(XYZE)
# derandomisation procedure requires that coefficients are non-negative
if derandomize == True:
absolute_coefficients = [abs(coeffcient) for coeffcient in hamiltonian_coefficients]
# removing the empty list as well
# these observables are needed for derandomisation procedure
observables_xyz = []
for idx, observable in enumerate(observables_xyze):
if observable:
observables_xyz.append(observable)
else:
absolute_coefficients.pop(idx)
return system_size, observables_xyze, observables_xyz, hamiltonian_coefficients, absolute_coefficients
return system_size, observables_xyze, hamiltonian_coefficients
'''
COST FUNCTION AND HELPER FUNCTIONS
'''
def basis_change_circuit(pauli_op):
# Generating circuit with just the basis change operators
#
# pauli_op: n-qubit Pauli operator
basis_change = QuantumCircuit(ansatz.num_qubits, ansatz.num_qubits)
for idx, op in enumerate(pauli_op):
if op == 'X':
basis_change.h(idx)
if op == 'Y':
basis_change.h(idx)
basis_change.p(-np.pi/2, idx)
return basis_change
def ground_state_energy_from_shadow(operators, params):
backend = QasmSimulator(method='statevector', shots=1)
pauli_op_dict = Counter(tuple(x) for x in operators)
shadow = []
for pauli_op in pauli_op_dict:
qc = ansatz.bind_parameters(params)
qc = qc.compose(basis_change_circuit(pauli_op))
qc.measure(reversed(range(system_size)), range(system_size))
result = execute(qc, backend, shots=pauli_op_dict[pauli_op]).result()
counts = result.get_counts() # given in order q0 q1 ... qn-1 after register reversal in qc.measure
for count in counts:
for _ in range(counts[count]): # number of repeated measurement values
output_str = list(count)
output = [int(i) for i in output_str]
eigenvals = [x+1 if x == 0 else x-2 for x in output]
snapshot = [(op, eigenval) for op, eigenval in zip(pauli_op, eigenvals)]
shadow.append(snapshot)
expectation_value = 0.0
for term, weight in zip(observables_xyze, hamiltonian_coefficients):
sum_product, match_count = estimate_exp(shadow, term)
if match_count != 0:
expectation_value += (weight * sum_product / match_count)
return expectation_value
'''
EXPERIMENTS
'''
start_time = time.time()
all_molecules_rmse_errors = []
# CALCULATING FERMIONIC HAMILTONIAN AND CONVERTING TO QUBIT HAMILTONIAN
MOLECULES = ['H2']
for molecule in MOLECULES:
rmse_errors = []
if molecule == 'H2':
problem = H2_driver.run()
if molecule == 'LiH':
problem = LiH_driver.run()
if molecule == 'BeH2':
problem = BeH2_driver.run()
if molecule == 'H2O':
problem = H2O_driver.run()
if molecule == 'NH3':
problem = NH3_driver.run()
hamiltonian = problem.hamiltonian
second_q_op = hamiltonian.second_q_op()
bk_mapper = BravyiKitaevMapper() #(num_particles=problem.num_particles) #BravyiKitaevMapper()
bkencoded_hamiltonian = bk_mapper.map(second_q_op)
#print('Qubit Hamiltonian in Bravyi-Kitaev encoding', bkencoded_hamiltonian)
# process the Hamiltonian to obtain properly formatted data
hamiltonian_data = process_hamiltonian(bkencoded_hamiltonian, derandomize = True)
system_size, observables_xyze, observables_xyz, hamiltonian_coefficients, absolute_coefficients = hamiltonian_data
'''
VARIATIONAL ANSATZ
'''
ansatz = UCCSD(
problem.num_spatial_orbitals,
problem.num_particles,
bk_mapper,
initial_state=HartreeFock(
problem.num_spatial_orbitals,
problem.num_particles,
bk_mapper,
),
)
'''
Running VQE on the Hamiltonian obtained from PySCFDriver using Statevector simulator (Estimator primitive)
'''
#estimator = Estimator()
# If shots = None, it calculates the exact expectation values. Otherwise, it samples from normal distributions
# with standard errors as standard deviations using normal distribution approximation.
#estimator.set_options(shots = None)
#estimator = AerEstimator()
#estimator.set_options(approximation=False, shots=None)
#vqe_solver = VQE(estimator, ansatz, SLSQP())
vqe_solver = VQE(Estimator(), ansatz, SLSQP())
vqe_solver.initial_point = np.zeros(ansatz.num_parameters)
calc = GroundStateEigensolver(bk_mapper, vqe_solver)
result = calc.solve(problem)
print(result.raw_result)
#print('NUMBER OF OPERATORS | DERANDOMISED OPERATORS | AVERAGE RMSE ERROR\n')
measurement_range = [50, 250, 500, 750, 1000, 1250, 1500, 1750]
for num_operators in measurement_range:
derandomized_hamiltonian = derandomized_classical_shadow(observables_xyz, 50,
system_size, weight=absolute_coefficients)
tuples = (tuple(pauli) for pauli in derandomized_hamiltonian)
counts = Counter(tuples)
print('Original derandomized Hamiltonian', counts)
# derandomized classical shadow will usually either undergenerate or overgenerate derandomized operators
# adjusting for this issue:
while sum(counts.values()) != num_operators:
for key, value in zip(counts.keys(), counts.values()):
sum_counts = sum(counts.values())
if sum_counts == num_operators:
break
if sum_counts < num_operators:
# generate additional operators from the existing ones by increasing the number of counts
counts[key] += 1
if sum_counts > num_operators:
# remove the element with highest count
max_element_key = [k for k, v in counts.items() if v == max(counts.values())][0]
counts[max_element_key] -= 1
print('Size-adjusted derandomized Hamiltonian', counts)
# translate the Counter to a set of derandomized operators
new_derandomized_hamiltonian = []
for key, value in counts.items():
for _ in range(value):
new_derandomized_hamiltonian.append(list(key))
#print('Size-adjusted derandomized Hamiltonian', new_derandomized_hamiltonian)
expectation_values = []
num_experiments = 10
for iteration in range(num_experiments):
expectation_value = ground_state_energy_from_shadow(new_derandomized_hamiltonian, result.raw_result.optimal_point)
expectation_values.append(expectation_value)
print("EXPERIMENT {}: GROUND STATE ENERGY FOUND = {}".format(iteration, expectation_value))
rmse_derandomised_cs = np.sqrt(np.sum([(expectation_values[i] - result.raw_result.optimal_value)**2
for i in range(num_experiments)])/num_experiments)
rmse_errors.append(rmse_derandomised_cs)
print('{} | {} | {}'.format(num_operators, counts, rmse_derandomised_cs))
all_molecules_rmse_errors.append(rmse_errors)
elapsed_time = time.time() - start_time
print("Execution time = ", time.strftime("%H:%M:%S", time.gmtime(elapsed_time)))
import matplotlib.pyplot as plt
points = [50, 250, 500, 750, 1000, 1250, 1500, 1750]
num_points = len(points)
rmse_errors = [0.1069869635064184, 0.07725001066018326, 0.05225116371481676, 0.042165636875291464,
0.051653435360326294, 0.03145057406737202, 0.03650841505283894, 0.03864886899799828]
plt.plot([i for i in points], [rmse_errors[i] for i in range(num_points)], 'r', label='derandomized classical shadow')
plt.xlabel('Number of measurements')
plt.ylabel('Average RMSE error')
plt.legend(loc=1)
|
https://github.com/renatawong/classical-shadow-vqe
|
renatawong
|
'''
(C) 2023 Renata Wong
Electronic structure problem with classical shadows, as presented in https://arxiv.org/abs/2103.07510
This code uses Qiskit as platform.
The shadow is constructed based on derandomized Hamiltonian.
The molecules tested are: H2 (6-31s basis), LiH (sto3g basis), BeH2 (sto3g), H2O (sto3g), and NH3 (sto3g).
The coordinates for NH3 were taken from 'Algorithms for Computer Detection of Symmetry Elementsin Molecular Systems'.
'''
import time
import numpy as np
from collections import Counter
import matplotlib.pyplot as plt
from qiskit import QuantumCircuit, execute
from qiskit_aer.primitives import Estimator as AerEstimator
from qiskit_aer import QasmSimulator
from qiskit.quantum_info import SparsePauliOp
from qiskit_nature.units import DistanceUnit
from qiskit_nature.second_q.drivers import PySCFDriver
from qiskit_nature.second_q.algorithms import GroundStateEigensolver
from qiskit_nature.second_q.mappers import BravyiKitaevMapper, JordanWignerMapper, ParityMapper
from qiskit_nature.second_q.circuit.library import UCCSD, HartreeFock
from qiskit_nature.second_q.algorithms import VQEUCCFactory
from qiskit.algorithms.minimum_eigensolvers import VQE
from qiskit.algorithms.optimizers import SLSQP, COBYLA, SPSA
# Estimator primitive is based on the Statevector construct = algebraic simulation
from qiskit.primitives import Estimator
from qiskit.utils import algorithm_globals
from modified_derandomization import modified_derandomized_classical_shadow
from predicting_quantum_properties.data_acquisition_shadow import derandomized_classical_shadow
from predicting_quantum_properties.prediction_shadow import estimate_exp
import qiskit_nature
qiskit_nature.settings.use_pauli_sum_op = False
import h5py
H5PY_DEFAULT_READONLY=1
'''
DEFINING DRIVERS FOR THE MOLECULES
'''
H2_driver = PySCFDriver(
atom="H 0 0 0; H 0 0 0.735",
basis="6-31g",
charge=0,
spin=0,
unit=DistanceUnit.ANGSTROM,
)
LiH_driver = PySCFDriver(
atom="Li 0 0 0; H 0 0 1.599",
basis="sto3g",
charge=0,
spin=0,
unit=DistanceUnit.ANGSTROM,
)
BeH2_driver = PySCFDriver(
atom="Be 0 0 0; H 0 0 1.3264; H 0 0 -1.3264",
basis="sto3g",
charge=0,
spin=0,
unit=DistanceUnit.ANGSTROM,
)
H2O_driver = PySCFDriver(
atom="O 0.0 0.0 0.0; H 0.757 0.586 0.0; H -0.757 0.586 0.0",
basis="sto3g",
charge=0,
spin=0,
unit=DistanceUnit.ANGSTROM,
)
NH3_driver = PySCFDriver(
atom="N 0 0 0; H 0 0 1.008000; H 0.950353 0 -0.336000; H -0.475176 -0.823029 -0.336000",
basis="sto3g",
charge=0,
spin=0,
unit=DistanceUnit.ANGSTROM,
)
'''
FORMATTING HAMILTONIAN
'''
def process_hamiltonian(hamiltonian, derandomize = False):
hamiltonian_observables = []
hamiltonian_coefficients = []
for observable in hamiltonian.paulis:
op_list = []
for op_index, pauli_op in enumerate(observable):
pauli_op = str(pauli_op)
if pauli_op == 'I' or pauli_op == 'X' or pauli_op == 'Y' or pauli_op == 'Z':
op_list.append((pauli_op, op_index))
hamiltonian_observables.append(op_list)
hamiltonian_coefficients = hamiltonian.coeffs.real
system_size = len(hamiltonian_observables[0])
# removing all occurrences of Pauli-I, for all-Pauli-I there is an empty list left
# these observables are needed for estimate_exp()
observables_xyze = []
for observable in hamiltonian_observables:
XYZE = []
for pauli in observable:
if pauli[0] != 'I':
XYZE.append(pauli)
observables_xyze.append(XYZE)
# derandomisation procedure requires that coefficients are non-negative
if derandomize == True:
absolute_coefficients = [abs(coeffcient) for coeffcient in hamiltonian_coefficients]
# removing the empty list as well
# these observables are needed for derandomisation procedure
observables_xyz = []
for idx, observable in enumerate(observables_xyze):
if observable:
observables_xyz.append(observable)
else:
absolute_coefficients.pop(idx)
return system_size, observables_xyze, observables_xyz, hamiltonian_coefficients, absolute_coefficients
return system_size, observables_xyze, hamiltonian_coefficients
'''
COST FUNCTION AND HELPER FUNCTIONS
'''
def basis_change_circuit(pauli_op):
# Generating circuit with just the basis change operators
#
# pauli_op: n-qubit Pauli operator
basis_change = QuantumCircuit(ansatz.num_qubits, ansatz.num_qubits)
for idx, op in enumerate(pauli_op):
if op == 'X':
basis_change.h(idx)
if op == 'Y':
basis_change.h(idx)
basis_change.p(-np.pi/2, idx)
return basis_change
def ground_state_energy_from_shadow(operators, params):
backend = QasmSimulator(method='statevector', shots=1)
pauli_op_dict = Counter(tuple(x) for x in operators)
shadow = []
for pauli_op in pauli_op_dict:
qc = ansatz.bind_parameters(params)
qc = qc.compose(basis_change_circuit(pauli_op))
qc.measure(reversed(range(system_size)), range(system_size))
result = execute(qc, backend, shots=pauli_op_dict[pauli_op]).result()
counts = result.get_counts() # given in order q0 q1 ... qn-1 after register reversal in qc.measure
for count in counts:
for _ in range(counts[count]): # number of repeated measurement values
output_str = list(count)
output = [int(i) for i in output_str]
eigenvals = [x+1 if x == 0 else x-2 for x in output]
snapshot = [(op, eigenval) for op, eigenval in zip(pauli_op, eigenvals)]
shadow.append(snapshot)
expectation_value = 0.0
for term, weight in zip(observables_xyze, hamiltonian_coefficients):
sum_product, match_count = estimate_exp(shadow, term)
if match_count != 0:
expectation_value += (weight * sum_product / match_count)
return expectation_value
'''
EXPERIMENTS
'''
start_time = time.time()
all_molecules_rmse_errors = []
# CALCULATING FERMIONIC HAMILTONIAN AND CONVERTING TO QUBIT HAMILTONIAN
MOLECULES = ['H2O']
for molecule in MOLECULES:
rmse_errors = []
if molecule == 'H2':
problem = H2_driver.run()
if molecule == 'LiH':
problem = LiH_driver.run()
if molecule == 'BeH2':
problem = BeH2_driver.run()
if molecule == 'H2O':
problem = H2O_driver.run()
if molecule == 'NH3':
problem = NH3_driver.run()
hamiltonian = problem.hamiltonian
second_q_op = hamiltonian.second_q_op()
bk_mapper = BravyiKitaevMapper()
bkencoded_hamiltonian = bk_mapper.map(second_q_op)
#print('Qubit Hamiltonian in Bravyi-Kitaev encoding', bkencoded_hamiltonian)
# process the Hamiltonian to obtain properly formatted data
hamiltonian_data = process_hamiltonian(bkencoded_hamiltonian, derandomize = True)
system_size, observables_xyze, observables_xyz, hamiltonian_coefficients, absolute_coefficients = hamiltonian_data
'''
VARIATIONAL ANSATZ
'''
ansatz = UCCSD(
problem.num_spatial_orbitals,
problem.num_particles,
bk_mapper,
initial_state=HartreeFock(
problem.num_spatial_orbitals,
problem.num_particles,
bk_mapper,
),
)
'''
Running VQE on the Hamiltonian obtained from PySCFDriver using Statevector simulator (Estimator primitive)
'''
#estimator = Estimator()
# If shots = None, it calculates the exact expectation values. Otherwise, it samples from normal distributions
# with standard errors as standard deviations using normal distribution approximation.
#estimator.set_options(shots = None)
#estimator = AerEstimator()
#estimator.set_options(approximation=True, shots=None)
vqe_solver = VQE(Estimator(), ansatz, SLSQP())
vqe_solver.initial_point = np.zeros(ansatz.num_parameters)
calc = GroundStateEigensolver(bk_mapper, vqe_solver)
result = calc.solve(problem)
print(result.raw_result)
#print('NUMBER OF OPERATORS | DERANDOMISED OPERATORS | AVERAGE RMSE ERROR\n')
measurement_range = [50, 250, 500, 750, 1000, 1250, 1500, 1750]
for num_operators in measurement_range:
derandomized_hamiltonian = derandomized_classical_shadow(observables_xyz, 50,
system_size, weight=absolute_coefficients)
tuples = (tuple(pauli) for pauli in derandomized_hamiltonian)
counts = Counter(tuples)
print('Original derandomized Hamiltonian', counts)
# derandomized classical shadow will usually either undergenerate or overgenerate derandomized operators
# adjusting for this issue:
while sum(counts.values()) != num_operators:
for key, value in zip(counts.keys(), counts.values()):
sum_counts = sum(counts.values())
if sum_counts == num_operators:
break
if sum_counts < num_operators:
# generate additional operators from the existing ones by increasing the number of counts
counts[key] += 1
if sum_counts > num_operators:
# remove the element with highest count
max_element_key = [k for k, v in counts.items() if v == max(counts.values())][0]
counts[max_element_key] -= 1
print('Size-adjusted derandomized Hamiltonian', counts)
# translate the Counter to a set of derandomized operators
new_derandomized_hamiltonian = []
for key, value in counts.items():
for _ in range(value):
new_derandomized_hamiltonian.append(list(key))
#print('Size-adjusted derandomized Hamiltonian', new_derandomized_hamiltonian)
expectation_values = []
num_experiments = 10
for iteration in range(num_experiments):
expectation_value = ground_state_energy_from_shadow(new_derandomized_hamiltonian, result.raw_result.optimal_point)
expectation_values.append(expectation_value)
print("EXPERIMENT {}: GROUND STATE ENERGY FOUND = {}".format(iteration, expectation_value))
rmse_derandomised_cs = np.sqrt(np.sum([(expectation_values[i] - result.raw_result.optimal_value)**2
for i in range(num_experiments)])/num_experiments)
rmse_errors.append(rmse_derandomised_cs)
print('{} | {} | {}'.format(num_operators, counts, rmse_derandomised_cs))
all_molecules_rmse_errors.append(rmse_errors)
elapsed_time = time.time() - start_time
print("Execution time = ", time.strftime("%H:%M:%S", time.gmtime(elapsed_time)))
import matplotlib.pyplot as plt
points = measurement_range
num_points = len(points)
plt.plot([i for i in points], [rmse_errors[i] for i in range(num_points)], 'r', label='derandomized classical shadow')
plt.xlabel('Number of measurements')
plt.ylabel('Average RMSE error')
plt.legend(loc=1)
|
https://github.com/renatawong/classical-shadow-vqe
|
renatawong
|
'''
(C) 2023 Renata Wong
Electronic structure problem with classical shadows, as presented in https://arxiv.org/abs/2103.07510
This code uses Qiskit as platform.
The shadow is constructed based on derandomized Hamiltonian.
The molecules tested are: H2 (6-31s basis), LiH (sto3g basis), BeH2 (sto3g), H2O (sto3g), and NH3 (sto3g).
The coordinates for NH3 were taken from 'Algorithms for Computer Detection of Symmetry Elementsin Molecular Systems'.
'''
import time
import numpy as np
from collections import Counter
import matplotlib.pyplot as plt
from qiskit import QuantumCircuit, execute
from qiskit_aer.primitives import Estimator as AerEstimator
from qiskit_aer import QasmSimulator
from qiskit.quantum_info import SparsePauliOp
from qiskit_nature.units import DistanceUnit
from qiskit_nature.second_q.drivers import PySCFDriver
from qiskit_nature.second_q.algorithms import GroundStateEigensolver
from qiskit_nature.second_q.mappers import BravyiKitaevMapper, JordanWignerMapper, ParityMapper
from qiskit_nature.second_q.circuit.library import UCCSD, HartreeFock
from qiskit_nature.second_q.algorithms import VQEUCCFactory
from qiskit.algorithms.minimum_eigensolvers import VQE
from qiskit.algorithms.optimizers import SLSQP, COBYLA, SPSA
# Estimator primitive is based on the Statevector construct = algebraic simulation
from qiskit.primitives import Estimator
from qiskit.utils import algorithm_globals
from modified_derandomization import modified_derandomized_classical_shadow
from predicting_quantum_properties.data_acquisition_shadow import derandomized_classical_shadow
from predicting_quantum_properties.prediction_shadow import estimate_exp
import qiskit_nature
qiskit_nature.settings.use_pauli_sum_op = False
import h5py
H5PY_DEFAULT_READONLY=1
'''
DEFINING DRIVERS FOR THE MOLECULES
'''
H2_driver = PySCFDriver(
atom="H 0 0 0; H 0 0 0.735",
basis="6-31g",
charge=0,
spin=0,
unit=DistanceUnit.ANGSTROM,
)
LiH_driver = PySCFDriver(
atom="Li 0 0 0; H 0 0 1.599",
basis="sto3g",
charge=0,
spin=0,
unit=DistanceUnit.ANGSTROM,
)
BeH2_driver = PySCFDriver(
atom="Be 0 0 0; H 0 0 1.3264; H 0 0 -1.3264",
basis="sto3g",
charge=0,
spin=0,
unit=DistanceUnit.ANGSTROM,
)
H2O_driver = PySCFDriver(
atom="O 0.0 0.0 0.0; H 0.757 0.586 0.0; H -0.757 0.586 0.0",
basis="sto3g",
charge=0,
spin=0,
unit=DistanceUnit.ANGSTROM,
)
NH3_driver = PySCFDriver(
atom="N 0 0 0; H 0 0 1.008000; H 0.950353 0 -0.336000; H -0.475176 -0.823029 -0.336000",
basis="sto3g",
charge=0,
spin=0,
unit=DistanceUnit.ANGSTROM,
)
'''
FORMATTING HAMILTONIAN
'''
def process_hamiltonian(hamiltonian, derandomize = False):
hamiltonian_observables = []
hamiltonian_coefficients = []
for observable in hamiltonian.paulis:
op_list = []
for op_index, pauli_op in enumerate(observable):
pauli_op = str(pauli_op)
if pauli_op == 'I' or pauli_op == 'X' or pauli_op == 'Y' or pauli_op == 'Z':
op_list.append((pauli_op, op_index))
hamiltonian_observables.append(op_list)
hamiltonian_coefficients = hamiltonian.coeffs.real
system_size = len(hamiltonian_observables[0])
# removing all occurrences of Pauli-I, for all-Pauli-I there is an empty list left
# these observables are needed for estimate_exp()
observables_xyze = []
for observable in hamiltonian_observables:
XYZE = []
for pauli in observable:
if pauli[0] != 'I':
XYZE.append(pauli)
observables_xyze.append(XYZE)
# derandomisation procedure requires that coefficients are non-negative
if derandomize == True:
absolute_coefficients = [abs(coeffcient) for coeffcient in hamiltonian_coefficients]
# removing the empty list as well
# these observables are needed for derandomisation procedure
observables_xyz = []
for idx, observable in enumerate(observables_xyze):
if observable:
observables_xyz.append(observable)
else:
absolute_coefficients.pop(idx)
return system_size, observables_xyze, observables_xyz, hamiltonian_coefficients, absolute_coefficients
return system_size, observables_xyze, hamiltonian_coefficients
'''
COST FUNCTION AND HELPER FUNCTIONS
'''
def basis_change_circuit(pauli_op):
# Generating circuit with just the basis change operators
#
# pauli_op: n-qubit Pauli operator
basis_change = QuantumCircuit(ansatz.num_qubits, ansatz.num_qubits)
for idx, op in enumerate(pauli_op):
if op == 'X':
basis_change.h(idx)
if op == 'Y':
basis_change.h(idx)
basis_change.p(-np.pi/2, idx)
return basis_change
def ground_state_energy_from_shadow(operators, params):
backend = QasmSimulator(method='statevector', shots=1)
pauli_op_dict = Counter(tuple(x) for x in operators)
shadow = []
for pauli_op in pauli_op_dict:
qc = ansatz.bind_parameters(params)
qc = qc.compose(basis_change_circuit(pauli_op))
qc.measure(reversed(range(system_size)), range(system_size))
result = execute(qc, backend, shots=pauli_op_dict[pauli_op]).result()
counts = result.get_counts() # given in order q0 q1 ... qn-1 after register reversal in qc.measure
for count in counts:
for _ in range(counts[count]): # number of repeated measurement values
output_str = list(count)
output = [int(i) for i in output_str]
eigenvals = [x+1 if x == 0 else x-2 for x in output]
snapshot = [(op, eigenval) for op, eigenval in zip(pauli_op, eigenvals)]
shadow.append(snapshot)
expectation_value = 0.0
for term, weight in zip(observables_xyze, hamiltonian_coefficients):
sum_product, match_count = estimate_exp(shadow, term)
if match_count != 0:
expectation_value += (weight * sum_product / match_count)
return expectation_value
'''
EXPERIMENTS
'''
start_time = time.time()
all_molecules_rmse_errors = []
# CALCULATING FERMIONIC HAMILTONIAN AND CONVERTING TO QUBIT HAMILTONIAN
MOLECULES = ['LiH']
for molecule in MOLECULES:
rmse_errors = []
if molecule == 'H2':
problem = H2_driver.run()
if molecule == 'LiH':
problem = LiH_driver.run()
if molecule == 'BeH2':
problem = BeH2_driver.run()
if molecule == 'H2O':
problem = H2O_driver.run()
if molecule == 'NH3':
problem = NH3_driver.run()
hamiltonian = problem.hamiltonian
second_q_op = hamiltonian.second_q_op()
bk_mapper = BravyiKitaevMapper() #(num_particles=problem.num_particles) #BravyiKitaevMapper()
bkencoded_hamiltonian = bk_mapper.map(second_q_op)
#print('Qubit Hamiltonian in Bravyi-Kitaev encoding', bkencoded_hamiltonian)
# process the Hamiltonian to obtain properly formatted data
hamiltonian_data = process_hamiltonian(bkencoded_hamiltonian, derandomize = True)
system_size, observables_xyze, observables_xyz, hamiltonian_coefficients, absolute_coefficients = hamiltonian_data
'''
VARIATIONAL ANSATZ
'''
ansatz = UCCSD(
problem.num_spatial_orbitals,
problem.num_particles,
bk_mapper,
initial_state=HartreeFock(
problem.num_spatial_orbitals,
problem.num_particles,
bk_mapper,
),
)
'''
Running VQE on the Hamiltonian obtained from PySCFDriver using Statevector simulator (Estimator primitive)
'''
#estimator = Estimator()
# If shots = None, it calculates the exact expectation values. Otherwise, it samples from normal distributions
# with standard errors as standard deviations using normal distribution approximation.
#estimator.set_options(shots = None)
#estimator = AerEstimator()
#estimator.set_options(approximation=False, shots=None)
#vqe_solver = VQE(estimator, ansatz, SLSQP())
vqe_solver = VQE(Estimator(), ansatz, SLSQP())
vqe_solver.initial_point = np.zeros(ansatz.num_parameters)
calc = GroundStateEigensolver(bk_mapper, vqe_solver)
result = calc.solve(problem)
print(result.raw_result)
#print('NUMBER OF OPERATORS | DERANDOMISED OPERATORS | AVERAGE RMSE ERROR\n')
measurement_range = [50, 250, 500, 750, 1000, 1250, 1500, 1750]
for num_operators in measurement_range:
derandomized_hamiltonian = derandomized_classical_shadow(observables_xyz, 50,
system_size, weight=absolute_coefficients)
tuples = (tuple(pauli) for pauli in derandomized_hamiltonian)
counts = Counter(tuples)
print('Original derandomized Hamiltonian', counts)
# derandomized classical shadow will usually either undergenerate or overgenerate derandomized operators
# adjusting for this issue:
while sum(counts.values()) != num_operators:
for key, value in zip(counts.keys(), counts.values()):
sum_counts = sum(counts.values())
if sum_counts == num_operators:
break
if sum_counts < num_operators:
# generate additional operators from the existing ones by increasing the number of counts
counts[key] += 1
if sum_counts > num_operators:
# remove the element with highest count
max_element_key = [k for k, v in counts.items() if v == max(counts.values())][0]
counts[max_element_key] -= 1
print('Size-adjusted derandomized Hamiltonian', counts)
# translate the Counter to a set of derandomized operators
new_derandomized_hamiltonian = []
for key, value in counts.items():
for _ in range(value):
new_derandomized_hamiltonian.append(list(key))
#print('Size-adjusted derandomized Hamiltonian', new_derandomized_hamiltonian)
expectation_values = []
num_experiments = 10
for iteration in range(num_experiments):
expectation_value = ground_state_energy_from_shadow(new_derandomized_hamiltonian, result.raw_result.optimal_point)
expectation_values.append(expectation_value)
print("EXPERIMENT {}: GROUND STATE ENERGY FOUND = {}".format(iteration, expectation_value))
rmse_derandomised_cs = np.sqrt(np.sum([(expectation_values[i] - result.raw_result.optimal_value)**2
for i in range(num_experiments)])/num_experiments)
rmse_errors.append(rmse_derandomised_cs)
print('{} | {} | {}'.format(num_operators, counts, rmse_derandomised_cs))
all_molecules_rmse_errors.append(rmse_errors)
elapsed_time = time.time() - start_time
print("Execution time = ", time.strftime("%H:%M:%S", time.gmtime(elapsed_time)))
import matplotlib.pyplot as plt
points = measurement_range
num_points = len(points)
plt.plot([i for i in points], [rmse_errors[i] for i in range(num_points)], 'r', label='derandomized classical shadow')
plt.xlabel('Number of measurements')
plt.ylabel('Average RMSE error')
plt.legend(loc=1)
|
https://github.com/renatawong/classical-shadow-vqe
|
renatawong
|
'''
(C) 2023 Renata Wong
Electronic structure problem with classical shadows, as presented in https://arxiv.org/abs/2103.07510
This code uses Qiskit as platform.
The shadow is constructed based on derandomized Hamiltonian.
The molecules tested are: H2 (6-31s basis), LiH (sto3g basis), BeH2 (sto3g), H2O (sto3g), and NH3 (sto3g).
The coordinates for NH3 were taken from 'Algorithms for Computer Detection of Symmetry Elementsin Molecular Systems'.
'''
import time
import numpy as np
from collections import Counter
import matplotlib.pyplot as plt
from qiskit import QuantumCircuit, execute
from qiskit_aer.primitives import Estimator as AerEstimator
from qiskit_aer import QasmSimulator
from qiskit.quantum_info import SparsePauliOp
from qiskit_nature.units import DistanceUnit
from qiskit_nature.second_q.drivers import PySCFDriver
from qiskit_nature.second_q.algorithms import GroundStateEigensolver
from qiskit_nature.second_q.mappers import BravyiKitaevMapper, JordanWignerMapper, ParityMapper
from qiskit_nature.second_q.circuit.library import UCCSD, HartreeFock
from qiskit_nature.second_q.algorithms import VQEUCCFactory
from qiskit.algorithms.minimum_eigensolvers import VQE
from qiskit.algorithms.optimizers import SLSQP, COBYLA, SPSA
# Estimator primitive is based on the Statevector construct = algebraic simulation
from qiskit.primitives import Estimator
from qiskit.utils import algorithm_globals
from modified_derandomization import modified_derandomized_classical_shadow
from predicting_quantum_properties.data_acquisition_shadow import derandomized_classical_shadow
from predicting_quantum_properties.prediction_shadow import estimate_exp
import qiskit_nature
qiskit_nature.settings.use_pauli_sum_op = False
import h5py
H5PY_DEFAULT_READONLY=1
'''
DEFINING DRIVERS FOR THE MOLECULES
'''
H2_driver = PySCFDriver(
atom="H 0 0 0; H 0 0 0.735",
basis="6-31g",
charge=0,
spin=0,
unit=DistanceUnit.ANGSTROM,
)
LiH_driver = PySCFDriver(
atom="Li 0 0 0; H 0 0 1.599",
basis="sto3g",
charge=0,
spin=0,
unit=DistanceUnit.ANGSTROM,
)
BeH2_driver = PySCFDriver(
atom="Be 0 0 0; H 0 0 1.3264; H 0 0 -1.3264",
basis="sto3g",
charge=0,
spin=0,
unit=DistanceUnit.ANGSTROM,
)
H2O_driver = PySCFDriver(
atom="O 0.0 0.0 0.0; H 0.757 0.586 0.0; H -0.757 0.586 0.0",
basis="sto3g",
charge=0,
spin=0,
unit=DistanceUnit.ANGSTROM,
)
NH3_driver = PySCFDriver(
atom="N 0 0 0; H 0 0 1.008000; H 0.950353 0 -0.336000; H -0.475176 -0.823029 -0.336000",
basis="sto3g",
charge=0,
spin=0,
unit=DistanceUnit.ANGSTROM,
)
'''
FORMATTING HAMILTONIAN
'''
def process_hamiltonian(hamiltonian, derandomize = False):
hamiltonian_observables = []
hamiltonian_coefficients = []
for observable in hamiltonian.paulis:
op_list = []
for op_index, pauli_op in enumerate(observable):
pauli_op = str(pauli_op)
if pauli_op == 'I' or pauli_op == 'X' or pauli_op == 'Y' or pauli_op == 'Z':
op_list.append((pauli_op, op_index))
hamiltonian_observables.append(op_list)
hamiltonian_coefficients = hamiltonian.coeffs.real
system_size = len(hamiltonian_observables[0])
# removing all occurrences of Pauli-I, for all-Pauli-I there is an empty list left
# these observables are needed for estimate_exp()
observables_xyze = []
for observable in hamiltonian_observables:
XYZE = []
for pauli in observable:
if pauli[0] != 'I':
XYZE.append(pauli)
observables_xyze.append(XYZE)
# derandomisation procedure requires that coefficients are non-negative
if derandomize == True:
absolute_coefficients = [abs(coeffcient) for coeffcient in hamiltonian_coefficients]
# removing the empty list as well
# these observables are needed for derandomisation procedure
observables_xyz = []
for idx, observable in enumerate(observables_xyze):
if observable:
observables_xyz.append(observable)
else:
absolute_coefficients.pop(idx)
return system_size, observables_xyze, observables_xyz, hamiltonian_coefficients, absolute_coefficients
return system_size, observables_xyze, hamiltonian_coefficients
'''
COST FUNCTION AND HELPER FUNCTIONS
'''
def basis_change_circuit(pauli_op):
# Generating circuit with just the basis change operators
#
# pauli_op: n-qubit Pauli operator
basis_change = QuantumCircuit(ansatz.num_qubits, ansatz.num_qubits)
for idx, op in enumerate(pauli_op):
if op == 'X':
basis_change.h(idx)
if op == 'Y':
basis_change.h(idx)
basis_change.p(-np.pi/2, idx)
return basis_change
def ground_state_energy_from_shadow(operators, params):
backend = QasmSimulator(method='statevector', shots=1)
pauli_op_dict = Counter(tuple(x) for x in operators)
shadow = []
for pauli_op in pauli_op_dict:
qc = ansatz.bind_parameters(params)
qc = qc.compose(basis_change_circuit(pauli_op))
qc.measure(reversed(range(system_size)), range(system_size))
result = execute(qc, backend, shots=pauli_op_dict[pauli_op]).result()
counts = result.get_counts() # given in order q0 q1 ... qn-1 after register reversal in qc.measure
for count in counts:
for _ in range(counts[count]): # number of repeated measurement values
output_str = list(count)
output = [int(i) for i in output_str]
eigenvals = [x+1 if x == 0 else x-2 for x in output]
snapshot = [(op, eigenval) for op, eigenval in zip(pauli_op, eigenvals)]
shadow.append(snapshot)
expectation_value = 0.0
for term, weight in zip(observables_xyze, hamiltonian_coefficients):
sum_product, match_count = estimate_exp(shadow, term)
if match_count != 0:
expectation_value += (weight * sum_product / match_count)
return expectation_value
'''
EXPERIMENTS
'''
start_time = time.time()
all_molecules_rmse_errors = []
# CALCULATING FERMIONIC HAMILTONIAN AND CONVERTING TO QUBIT HAMILTONIAN
MOLECULES = ['NH3']
for molecule in MOLECULES:
rmse_errors = []
if molecule == 'H2':
problem = H2_driver.run()
if molecule == 'LiH':
problem = LiH_driver.run()
if molecule == 'BeH2':
problem = BeH2_driver.run()
if molecule == 'H2O':
problem = H2O_driver.run()
if molecule == 'NH3':
problem = NH3_driver.run()
hamiltonian = problem.hamiltonian
second_q_op = hamiltonian.second_q_op()
bk_mapper = BravyiKitaevMapper() #ParityMapper(num_particles=problem.num_particles) #BravyiKitaevMapper()
bkencoded_hamiltonian = bk_mapper.map(second_q_op)
#print('Qubit Hamiltonian in Bravyi-Kitaev encoding', bkencoded_hamiltonian)
# process the Hamiltonian to obtain properly formatted data
hamiltonian_data = process_hamiltonian(bkencoded_hamiltonian, derandomize = True)
system_size, observables_xyze, observables_xyz, hamiltonian_coefficients, absolute_coefficients = hamiltonian_data
'''
VARIATIONAL ANSATZ
'''
ansatz = UCCSD(
problem.num_spatial_orbitals,
problem.num_particles,
bk_mapper,
initial_state=HartreeFock(
problem.num_spatial_orbitals,
problem.num_particles,
bk_mapper,
),
)
'''
Running VQE on the Hamiltonian obtained from PySCFDriver using Statevector simulator (Estimator primitive)
'''
#estimator = Estimator()
# If shots = None, it calculates the exact expectation values. Otherwise, it samples from normal distributions
# with standard errors as standard deviations using normal distribution approximation.
#estimator.set_options(shots = None)
#estimator = AerEstimator()
#estimator.set_options(approximation=True, shots=None)
vqe_solver = VQE(Estimator(), ansatz, SLSQP())
vqe_solver.initial_point = np.zeros(ansatz.num_parameters)
calc = GroundStateEigensolver(bk_mapper, vqe_solver)
result = calc.solve(problem)
print(result.raw_result)
#print('NUMBER OF OPERATORS | DERANDOMISED OPERATORS | AVERAGE RMSE ERROR\n')
measurement_range = [50, 250, 500, 750, 1000, 1250, 1500, 1750]
for num_operators in measurement_range:
derandomized_hamiltonian = derandomized_classical_shadow(observables_xyz, 50,
system_size, weight=absolute_coefficients)
tuples = (tuple(pauli) for pauli in derandomized_hamiltonian)
counts = Counter(tuples)
print('Original derandomized Hamiltonian', counts)
# derandomized classical shadow will usually either undergenerate or overgenerate derandomized operators
# adjusting for this issue:
while sum(counts.values()) != num_operators:
for key, value in zip(counts.keys(), counts.values()):
sum_counts = sum(counts.values())
if sum_counts == num_operators:
break
if sum_counts < num_operators:
# generate additional operators from the existing ones by increasing the number of counts
counts[key] += 1
if sum_counts > num_operators:
# remove the element with highest count
max_element_key = [k for k, v in counts.items() if v == max(counts.values())][0]
counts[max_element_key] -= 1
print('Size-adjusted derandomized Hamiltonian', counts)
# translate the Counter to a set of derandomized operators
new_derandomized_hamiltonian = []
for key, value in counts.items():
for _ in range(value):
new_derandomized_hamiltonian.append(list(key))
#print('Size-adjusted derandomized Hamiltonian', new_derandomized_hamiltonian)
expectation_values = []
num_experiments = 10
for iteration in range(num_experiments):
expectation_value = ground_state_energy_from_shadow(new_derandomized_hamiltonian, result.raw_result.optimal_point)
expectation_values.append(expectation_value)
print("EXPERIMENT {}: GROUND STATE ENERGY FOUND = {}".format(iteration, expectation_value))
rmse_derandomised_cs = np.sqrt(np.sum([(expectation_values[i] - result.raw_result.optimal_value)**2
for i in range(num_experiments)])/num_experiments)
rmse_errors.append(rmse_derandomised_cs)
print('{} | {} | {}'.format(num_operators, counts, rmse_derandomised_cs))
all_molecules_rmse_errors.append(rmse_errors)
elapsed_time = time.time() - start_time
print("Execution time = ", time.strftime("%H:%M:%S", time.gmtime(elapsed_time)))
import matplotlib.pyplot as plt
points = measurement_range
num_points = len(points)
plt.plot([i for i in points], [rmse_errors[i] for i in range(num_points)], 'r', label='derandomized classical shadow')
plt.xlabel('Number of measurements')
plt.ylabel('Average RMSE error')
plt.legend(loc=1)
|
https://github.com/renatawong/classical-shadow-vqe
|
renatawong
|
'''
(C) 2023 Renata Wong
Electronic structure problem with classical shadows, as presented in https://arxiv.org/abs/2103.07510
This code uses Qiskit as platform.
The molecule tested is H2.
The shadow is constructed based on derandomized Hamiltonian.
'''
import time
import numpy as np
from collections import Counter
import matplotlib.pyplot as plt
from qiskit import QuantumCircuit, execute
from qiskit_aer import QasmSimulator
from qiskit.quantum_info import SparsePauliOp
from qiskit_nature.units import DistanceUnit
from qiskit_nature.second_q.drivers import PySCFDriver
from qiskit_nature.second_q.algorithms import GroundStateEigensolver
from qiskit_nature.second_q.mappers import BravyiKitaevMapper, JordanWignerMapper, ParityMapper
from qiskit.circuit.library import TwoLocal, RealAmplitudes
from qiskit.algorithms.minimum_eigensolvers import VQE
from qiskit_nature.second_q.circuit.library import UCCSD
from qiskit_nature.second_q.algorithms import VQEUCCFactory
from qiskit.algorithms.optimizers import SLSQP, COBYLA, SPSA
# Estimator primitive is based on the Statevector construct = algebraic simulation
from qiskit.primitives import Estimator
from qiskit.utils import algorithm_globals
from modified_derandomization import modified_derandomized_classical_shadow
from predicting_quantum_properties.data_acquisition_shadow import derandomized_classical_shadow
from predicting_quantum_properties.prediction_shadow import estimate_exp
import qiskit_nature
qiskit_nature.settings.use_pauli_sum_op = False
import h5py
H5PY_DEFAULT_READONLY=1
driver = PySCFDriver(
atom="H 0 0 0; H 0 0 0.735",
basis="6-31g",
charge=0,
spin=0,
unit=DistanceUnit.ANGSTROM,
)
problem = driver.run()
hamiltonian = problem.hamiltonian
second_q_op = hamiltonian.second_q_op()
bk_mapper = BravyiKitaevMapper()
bkencoded_hamiltonian = bk_mapper.map(second_q_op)
print(bkencoded_hamiltonian)
def process_hamiltonian(hamiltonian, derandomize = False):
"""
For use in derandomization and as input in the function estimate_exp, the Hamiltonian needs to be
reformatted from SparsePauliOp to a list of the form [[(X/Y/Z, position), (X/Y/Z, position)], [...], ...]
For derandomization, the all-identity Hamiltonian term is removed.
For use in estimating expectation values, the all-identity Hamiltonian term is retained as the empty
list [].
hamiltonian:
the problem's qubit Hamiltonian of type SparsePauliOp
derandomize:
if True: return the Hamiltonian formatted for derandomization as well as for use in calculating
the expectation value
if False: return the Hamiltonian formatted for calculating the expectation value only
"""
hamiltonian_observables = []
hamiltonian_coefficients = []
for observable in hamiltonian.paulis:
op_list = []
for op_index, pauli_op in enumerate(observable):
pauli_op = str(pauli_op)
if pauli_op == 'I' or pauli_op == 'X' or pauli_op == 'Y' or pauli_op == 'Z':
op_list.append((pauli_op, op_index))
hamiltonian_observables.append(op_list)
hamiltonian_coefficients = hamiltonian.coeffs.real
system_size = len(hamiltonian_observables[0])
# removing all occurrences of Pauli-I, for all-Pauli-I there is an empty list left
# these observables are needed for estimate_exp()
observables_xyze = []
for observable in hamiltonian_observables:
XYZE = []
for pauli in observable:
if pauli[0] != 'I':
XYZE.append(pauli)
observables_xyze.append(XYZE)
# derandomisation procedure requires that coefficients are non-negative
if derandomize == True:
absolute_coefficients = [abs(coeffcient) for coeffcient in hamiltonian_coefficients]
# removing the empty list as well
# these observables are needed for derandomisation procedure
observables_xyz = []
for idx, observable in enumerate(observables_xyze):
if observable:
observables_xyz.append(observable)
else:
absolute_coefficients.pop(idx)
return system_size, observables_xyze, observables_xyz, hamiltonian_coefficients, absolute_coefficients
return system_size, observables_xyze, hamiltonian_coefficients
# process the Hamiltonian to obtain properly formatted data
hamiltonian_data = process_hamiltonian(bkencoded_hamiltonian, derandomize = True)
system_size, observables_xyze, observables_xyz, hamiltonian_coefficients, absolute_coefficients = hamiltonian_data
#print('HAMILTONIAN\n', observables_xyze)
def basis_change_circuit(pauli_op):
"""
Generating circuit with just the basis change operators.
pauli_op:
n-qubit Pauli operator that indicates the change of basis
"""
basis_change = QuantumCircuit(ansatz.num_qubits, ansatz.num_qubits)
for idx, op in enumerate(pauli_op):
if op == 'X':
basis_change.h(idx)
if op == 'Y':
basis_change.h(idx)
basis_change.p(-np.pi/2, idx)
return basis_change
def ground_state_energy_from_shadow(operators, params):
"""
Calculate the ground state energy from a shadow represeantation of performed measurements.
operators:
the derandomized Hamiltonian
params:
set of optimal parameters, obtained from VQE run, to be used in the ansatz for shadow generation
"""
backend = QasmSimulator(method='statevector', shots=1)
pauli_op_dict = Counter(tuple(x) for x in operators)
shadow = []
for pauli_op in pauli_op_dict:
qc = ansatz.bind_parameters(params)
qc = qc.compose(basis_change_circuit(pauli_op))
qc.measure(reversed(range(system_size)), range(system_size))
result = execute(qc, backend, shots=pauli_op_dict[pauli_op]).result()
counts = result.get_counts() # given in order q0 q1 ... qn-1 after register reversal in qc.measure
for count in counts:
for _ in range(counts[count]): # number of repeated measurement values
output_str = list(count)
output = [int(i) for i in output_str]
eigenvals = [x+1 if x == 0 else x-2 for x in output]
snapshot = [(op, eigenval) for op, eigenval in zip(pauli_op, eigenvals)]
shadow.append(snapshot)
expectation_value = 0.0
for term, weight in zip(observables_xyze, hamiltonian_coefficients):
sum_product, match_count = estimate_exp(shadow, term)
if match_count != 0:
expectation_value += (weight * sum_product / match_count)
return expectation_value
ansatz = RealAmplitudes(num_qubits=system_size, reps=8, entanglement='linear')
ansatz.decompose().draw('mpl')
'''
Running VQE on the Hamiltonian obtained from PySCFDriver using Statevector simulator (Estimator primitive)
'''
estimator = Estimator()
# If shots = None, it calculates the exact expectation values. Otherwise, it samples from normal distributions
# with standard errors as standard deviations using normal distribution approximation.
estimator.set_options(shots = None)
vqe_solver = VQE(estimator, ansatz, SLSQP(maxiter=2000))
calc = GroundStateEigensolver(bk_mapper, vqe_solver)
result = calc.solve(problem)
print(result.raw_result)
'''
EXPERIMENTS
'''
start_time = time.time()
rmse_errors = []
print('NUMBER OF OPERATORS | DERANDOMISED OPERATORS | AVERAGE RMSE ERROR\n')
measurement_range = [50, 250, 500, 750, 1000, 1250, 1500, 1750]
for num_operators in measurement_range:
derandomized_hamiltonian = modified_derandomized_classical_shadow(observables_xyz, num_operators,
system_size, weight=absolute_coefficients)
tuples = (tuple(pauli) for pauli in derandomized_hamiltonian)
counts = Counter(tuples)
expectation_values = []
num_experiments = 10
for iteration in range(num_experiments):
expectation_value = ground_state_energy_from_shadow(derandomized_hamiltonian, result.raw_result.optimal_point)
expectation_values.append(expectation_value)
print("EXPERIMENT {}: GROUND STATE ENERGY FOUND = {}".format(iteration, expectation_value))
rmse_derandomised_cs = np.sqrt(np.sum([(expectation_values[i] - result.raw_result.optimal_value)**2
for i in range(num_experiments)])/num_experiments)
rmse_errors.append(rmse_derandomised_cs)
print('{} | {} | {}'.format(num_operators, counts, rmse_derandomised_cs))
elapsed_time = time.time() - start_time
print("Execution time = ", time.strftime("%H:%M:%S", time.gmtime(elapsed_time)))
points = measurement_range
num_points = len(measurement_range)
plt.plot([i for i in points], [rmse_errors[i] for i in range(num_points)], 'r', label='derandomized classical shadow')
plt.xlabel('Number of measurements')
plt.ylabel('Average RMSE error')
plt.legend(loc=1)
'''
ESTIMATE THE HAMILTONIAN ON OPTIMAL PARAMETERS
'''
qc = ansatz.bind_parameters(result.raw_result.optimal_point)
job_ham = estimator.run(qc, bkencoded_hamiltonian)
result_h = job_ham.result()
print(f">>> Expectation value of the Hamiltonian: {result_h.values[0]}")
expectation_values = []
for index, term in enumerate(bkencoded_hamiltonian.paulis):
job = estimator.run(qc, term)
#print(f">>> Job ID: {job.job_id()}")
#print(f">>> Job Status: {job.status()}")
result2 = job.result()
#print(f">>> {result2}")
expval = result2.values[0]
expectation_values.append(expval)
print(" > Expectation value of {} with coeff {}: {}".format(term, bkencoded_hamiltonian.coeffs.real[index], expval))
total_expval = 0.0
for index, expval in enumerate(expectation_values):
total_expval += expval * bkencoded_hamiltonian.coeffs.real[index]
print('>>> Total expectation value from summing up expectation values of all terms', total_expval)
|
https://github.com/renatawong/classical-shadow-vqe
|
renatawong
|
'''
(C) 2023 Renata Wong
Electronic structure problem with classical shadows, as presented in https://arxiv.org/abs/2103.07510
This code uses Qiskit as platform.
The shadow is constructed based on derandomized Hamiltonian.
The molecules tested are: H2 (6-31s basis), LiH (sto3g basis), BeH2 (sto3g), H2O (sto3g), and NH3 (sto3g).
The coordinates for NH3 were taken from 'Algorithms for Computer Detection of Symmetry Elementsin Molecular Systems'.
'''
import time
import numpy as np
from collections import Counter
import matplotlib.pyplot as plt
from qiskit import QuantumCircuit, execute
from qiskit_aer import QasmSimulator
from qiskit.quantum_info import SparsePauliOp
from qiskit_nature.units import DistanceUnit
from qiskit_nature.second_q.drivers import PySCFDriver
from qiskit_nature.second_q.algorithms import GroundStateEigensolver
from qiskit_nature.second_q.mappers import BravyiKitaevMapper, JordanWignerMapper, ParityMapper
from qiskit_nature.second_q.circuit.library import UCCSD, HartreeFock
from qiskit_nature.second_q.algorithms import VQEUCCFactory
from qiskit.algorithms.minimum_eigensolvers import VQE
from qiskit.algorithms.optimizers import SLSQP, COBYLA, SPSA
# Estimator primitive is based on the Statevector construct = algebraic simulation
from qiskit.primitives import Estimator
from qiskit.utils import algorithm_globals
from modified_derandomization import modified_derandomized_classical_shadow
from predicting_quantum_properties.data_acquisition_shadow import derandomized_classical_shadow
from predicting_quantum_properties.prediction_shadow import estimate_exp
import qiskit_nature
qiskit_nature.settings.use_pauli_sum_op = False
import h5py
H5PY_DEFAULT_READONLY=1
'''
DEFINING DRIVERS FOR THE MOLECULES
'''
H2_driver = PySCFDriver(
atom="H 0 0 0; H 0 0 0.735",
basis="6-31g",
charge=0,
spin=0,
unit=DistanceUnit.ANGSTROM,
)
LiH_driver = PySCFDriver(
atom="Li 0 0 0.5; H 0 0 0",
basis="sto3g",
charge=0,
spin=0,
unit=DistanceUnit.ANGSTROM,
)
BeH2_driver = PySCFDriver(
atom="Be 0 0 0; H 0 0 1.3264; H 0 0 -1.3264",
basis="sto3g",
charge=0,
spin=0,
unit=DistanceUnit.ANGSTROM,
)
H2O_driver = PySCFDriver(
atom="O 0.0 0.0 0.0; H 0.757 0.586 0.0; H -0.757 0.586 0.0",
basis="sto3g",
charge=0,
spin=0,
unit=DistanceUnit.ANGSTROM,
)
NH3_driver = PySCFDriver(
atom="N 0 0 0; H 0 0 1.008000; H 0.950353 0 -0.336000; H -0.475176 -0.823029 -0.336000",
basis="sto3g",
charge=0,
spin=0,
unit=DistanceUnit.ANGSTROM,
)
'''
FORMATTING HAMILTONIAN
'''
def process_hamiltonian(hamiltonian, derandomize = False):
hamiltonian_observables = []
hamiltonian_coefficients = []
for observable in hamiltonian.paulis:
op_list = []
for op_index, pauli_op in enumerate(observable):
pauli_op = str(pauli_op)
if pauli_op == 'I' or pauli_op == 'X' or pauli_op == 'Y' or pauli_op == 'Z':
op_list.append((pauli_op, op_index))
hamiltonian_observables.append(op_list)
hamiltonian_coefficients = hamiltonian.coeffs.real
system_size = len(hamiltonian_observables[0])
# removing all occurrences of Pauli-I, for all-Pauli-I there is an empty list left
# these observables are needed for estimate_exp()
observables_xyze = []
for observable in hamiltonian_observables:
XYZE = []
for pauli in observable:
if pauli[0] != 'I':
XYZE.append(pauli)
observables_xyze.append(XYZE)
# derandomisation procedure requires that coefficients are non-negative
if derandomize == True:
absolute_coefficients = [abs(coeffcient) for coeffcient in hamiltonian_coefficients]
# removing the empty list as well
# these observables are needed for derandomisation procedure
observables_xyz = []
for idx, observable in enumerate(observables_xyze):
if observable:
observables_xyz.append(observable)
else:
absolute_coefficients.pop(idx)
return system_size, observables_xyze, observables_xyz, hamiltonian_coefficients, absolute_coefficients
return system_size, observables_xyze, hamiltonian_coefficients
'''
COST FUNCTION AND HELPER FUNCTIONS
'''
def basis_change_circuit(pauli_op):
# Generating circuit with just the basis change operators
#
# pauli_op: n-qubit Pauli operator
basis_change = QuantumCircuit(ansatz.num_qubits, ansatz.num_qubits)
for idx, op in enumerate(pauli_op):
if op == 'X':
basis_change.h(idx)
if op == 'Y':
basis_change.h(idx)
basis_change.p(-np.pi/2, idx)
return basis_change
def ground_state_energy_from_shadow(operators, params):
backend = QasmSimulator(method='statevector', shots=1)
pauli_op_dict = Counter(tuple(x) for x in operators)
shadow = []
for pauli_op in pauli_op_dict:
qc = ansatz.bind_parameters(params)
qc = qc.compose(basis_change_circuit(pauli_op))
qc.measure(reversed(range(system_size)), range(system_size))
result = execute(qc, backend, shots=pauli_op_dict[pauli_op]).result()
counts = result.get_counts() # given in order q0 q1 ... qn-1 after register reversal in qc.measure
for count in counts:
for _ in range(counts[count]): # number of repeated measurement values
output_str = list(count)
output = [int(i) for i in output_str]
eigenvals = [x+1 if x == 0 else x-2 for x in output]
snapshot = [(op, eigenval) for op, eigenval in zip(pauli_op, eigenvals)]
shadow.append(snapshot)
expectation_value = 0.0
for term, weight in zip(observables_xyze, hamiltonian_coefficients):
sum_product, match_count = estimate_exp(shadow, term)
if match_count != 0:
expectation_value += (weight * sum_product / match_count)
return expectation_value
'''
EXPERIMENTS
'''
start_time = time.time()
rmse_errors = []
# CALCULATING FERMIONIC HAMILTONIAN AND CONVERTING TO QUBIT HAMILTONIAN
MOLECULES = ['H2', 'LiH', 'BeH2', 'H2O', 'NH3']
for molecule in MOLECULES:
if molecule == 'H2':
problem = H2_driver.run()
if molecule == 'LiH':
problem = LiH_driver.run()
if molecule == 'BeH2':
problem = BeH2_driver.run()
if molecule == 'H2O':
problem = H2O_driver.run()
if molecule == 'NH3':
problem = NH3_driver.run()
hamiltonian = problem.hamiltonian
second_q_op = hamiltonian.second_q_op()
bk_mapper = BravyiKitaevMapper()
bkencoded_hamiltonian = bk_mapper.map(second_q_op)
#print('Qubit Hamiltonian in Bravyi-Kitaev encoding', bkencoded_hamiltonian)
# process the Hamiltonian to obtain properly formatted data
hamiltonian_data = process_hamiltonian(bkencoded_hamiltonian, derandomize = True)
system_size, observables_xyze, observables_xyz, hamiltonian_coefficients, absolute_coefficients = hamiltonian_data
'''
VARIATIONAL ANSATZ
'''
ansatz = UCCSD(
problem.num_spatial_orbitals,
problem.num_particles,
bk_mapper,
initial_state=HartreeFock(
problem.num_spatial_orbitals,
problem.num_particles,
bk_mapper,
),
)
'''
Running VQE on the Hamiltonian obtained from PySCFDriver using Statevector simulator (Estimator primitive)
'''
#estimator = Estimator()
# If shots = None, it calculates the exact expectation values. Otherwise, it samples from normal distributions
# with standard errors as standard deviations using normal distribution approximation.
#estimator.set_options(shots = None)
vqe_solver = VQE(Estimator(), ansatz, SLSQP())
vqe_solver.initial_point = np.zeros(ansatz.num_parameters)
calc = GroundStateEigensolver(bk_mapper, vqe_solver)
result = calc.solve(problem)
print(result.raw_result)
#print('NUMBER OF OPERATORS | DERANDOMISED OPERATORS | AVERAGE RMSE ERROR\n')
measurement_range = [50, 250, 500, 750, 1000, 1250, 1500, 1750]
for num_operators in measurement_range:
derandomized_hamiltonian = modified_derandomized_classical_shadow(observables_xyz, num_operators,
system_size, weight=absolute_coefficients)
tuples = (tuple(pauli) for pauli in derandomized_hamiltonian)
counts = Counter(tuples)
expectation_values = []
num_experiments = 10
for iteration in range(num_experiments):
expectation_value = ground_state_energy_from_shadow(derandomized_hamiltonian, result.raw_result.optimal_point)
expectation_values.append(expectation_value)
print("EXPERIMENT {}: GROUND STATE ENERGY FOUND = {}".format(iteration, expectation_value))
rmse_derandomised_cs = np.sqrt(np.sum([(expectation_values[i] - result.raw_result.optimal_value)**2
for i in range(num_experiments)])/num_experiments)
rmse_errors.append(rmse_derandomised_cs)
print('{} | {} | {}'.format(num_operators, counts, rmse_derandomised_cs))
points = measurement_range
num_points = len(measurement_range)
plt.plot([i for i in points], [rmse_errors[i] for i in range(num_points)], 'r', label=molecule)
plt.xlabel('Number of measurements')
plt.ylabel('Average RMSE error')
plt.legend(loc=1)
elapsed_time = time.time() - start_time
print("Execution time = ", time.strftime("%H:%M:%S", time.gmtime(elapsed_time)))
|
https://github.com/renatawong/classical-shadow-vqe
|
renatawong
|
'''
(C) 2023 Renata Wong
Electronic structure problem with classical shadows, as presented in https://arxiv.org/abs/2103.07510
This code uses Qiskit as platform.
The shadow is constructed based on derandomized Hamiltonian.
The molecules tested are: H2 (6-31s basis), LiH (sto3g basis), BeH2 (sto3g), H2O (sto3g), and NH3 (sto3g).
The coordinates for NH3 were taken from 'Algorithms for Computer Detection of Symmetry Elementsin Molecular Systems'.
'''
import time
import numpy as np
from collections import Counter
import matplotlib.pyplot as plt
from qiskit import QuantumCircuit, execute
from qiskit_aer import QasmSimulator
from qiskit.quantum_info import SparsePauliOp
from qiskit_nature.units import DistanceUnit
from qiskit_nature.second_q.drivers import PySCFDriver
from qiskit_nature.second_q.algorithms import GroundStateEigensolver
from qiskit_nature.second_q.mappers import BravyiKitaevMapper, JordanWignerMapper, ParityMapper
from qiskit_nature.second_q.circuit.library import UCCSD, HartreeFock
from qiskit_nature.second_q.algorithms import VQEUCCFactory
from qiskit.algorithms.minimum_eigensolvers import VQE
from qiskit.algorithms.optimizers import SLSQP, COBYLA, SPSA
# Estimator primitive is based on the Statevector construct = algebraic simulation
from qiskit.primitives import Estimator
from qiskit.utils import algorithm_globals
from modified_derandomization import modified_derandomized_classical_shadow
from predicting_quantum_properties.data_acquisition_shadow import derandomized_classical_shadow
from predicting_quantum_properties.prediction_shadow import estimate_exp
import qiskit_nature
qiskit_nature.settings.use_pauli_sum_op = False
import h5py
H5PY_DEFAULT_READONLY=1
'''
DEFINING DRIVERS FOR THE MOLECULES
'''
H2_driver = PySCFDriver(
atom="H 0 0 0; H 0 0 0.735",
basis="6-31g",
charge=0,
spin=0,
unit=DistanceUnit.ANGSTROM,
)
LiH_driver = PySCFDriver(
atom="Li 0 0 0.5; H 0 0 0",
basis="sto3g",
charge=0,
spin=0,
unit=DistanceUnit.ANGSTROM,
)
BeH2_driver = PySCFDriver(
atom="Be 0 0 0; H 0 0 1.3264; H 0 0 -1.3264",
basis="sto3g",
charge=0,
spin=0,
unit=DistanceUnit.ANGSTROM,
)
H2O_driver = PySCFDriver(
atom="O 0.0 0.0 0.0; H 0.757 0.586 0.0; H -0.757 0.586 0.0",
basis="sto3g",
charge=0,
spin=0,
unit=DistanceUnit.ANGSTROM,
)
NH3_driver = PySCFDriver(
atom="N 0 0 0; H 0 0 1.008000; H 0.950353 0 -0.336000; H -0.475176 -0.823029 -0.336000",
basis="sto3g",
charge=0,
spin=0,
unit=DistanceUnit.ANGSTROM,
)
'''
FORMATTING HAMILTONIAN
'''
def process_hamiltonian(hamiltonian, derandomize = False):
hamiltonian_observables = []
hamiltonian_coefficients = []
for observable in hamiltonian.paulis:
op_list = []
for op_index, pauli_op in enumerate(observable):
pauli_op = str(pauli_op)
if pauli_op == 'I' or pauli_op == 'X' or pauli_op == 'Y' or pauli_op == 'Z':
op_list.append((pauli_op, op_index))
hamiltonian_observables.append(op_list)
hamiltonian_coefficients = hamiltonian.coeffs.real
system_size = len(hamiltonian_observables[0])
# removing all occurrences of Pauli-I, for all-Pauli-I there is an empty list left
# these observables are needed for estimate_exp()
observables_xyze = []
for observable in hamiltonian_observables:
XYZE = []
for pauli in observable:
if pauli[0] != 'I':
XYZE.append(pauli)
observables_xyze.append(XYZE)
# derandomisation procedure requires that coefficients are non-negative
if derandomize == True:
absolute_coefficients = [abs(coeffcient) for coeffcient in hamiltonian_coefficients]
# removing the empty list as well
# these observables are needed for derandomisation procedure
observables_xyz = []
for idx, observable in enumerate(observables_xyze):
if observable:
observables_xyz.append(observable)
else:
absolute_coefficients.pop(idx)
return system_size, observables_xyze, observables_xyz, hamiltonian_coefficients, absolute_coefficients
return system_size, observables_xyze, hamiltonian_coefficients
'''
COST FUNCTION AND HELPER FUNCTIONS
'''
def basis_change_circuit(pauli_op):
# Generating circuit with just the basis change operators
#
# pauli_op: n-qubit Pauli operator
basis_change = QuantumCircuit(ansatz.num_qubits, ansatz.num_qubits)
for idx, op in enumerate(pauli_op):
if op == 'X':
basis_change.h(idx)
if op == 'Y':
basis_change.h(idx)
basis_change.p(-np.pi/2, idx)
return basis_change
def ground_state_energy_from_shadow(operators, params):
backend = QasmSimulator(method='statevector', shots=1)
pauli_op_dict = Counter(tuple(x) for x in operators)
shadow = []
for pauli_op in pauli_op_dict:
qc = ansatz.bind_parameters(params)
qc = qc.compose(basis_change_circuit(pauli_op))
qc.measure(reversed(range(system_size)), range(system_size))
result = execute(qc, backend, shots=pauli_op_dict[pauli_op]).result()
counts = result.get_counts() # given in order q0 q1 ... qn-1 after register reversal in qc.measure
for count in counts:
for _ in range(counts[count]): # number of repeated measurement values
output_str = list(count)
output = [int(i) for i in output_str]
eigenvals = [x+1 if x == 0 else x-2 for x in output]
snapshot = [(op, eigenval) for op, eigenval in zip(pauli_op, eigenvals)]
shadow.append(snapshot)
expectation_value = 0.0
for term, weight in zip(observables_xyze, hamiltonian_coefficients):
sum_product, match_count = estimate_exp(shadow, term)
if match_count != 0:
expectation_value += (weight * sum_product / match_count)
return expectation_value
'''
EXPERIMENTS
'''
start_time = time.time()
all_molecules_rmse_errors = []
# CALCULATING FERMIONIC HAMILTONIAN AND CONVERTING TO QUBIT HAMILTONIAN
MOLECULES = ['H2', 'LiH', 'BeH2', 'H2O', 'NH3']
for molecule in MOLECULES:
rmse_errors = []
if molecule == 'H2':
problem = H2_driver.run()
if molecule == 'LiH':
problem = LiH_driver.run()
if molecule == 'BeH2':
problem = BeH2_driver.run()
if molecule == 'H2O':
problem = H2O_driver.run()
if molecule == 'NH3':
problem = NH3_driver.run()
hamiltonian = problem.hamiltonian
second_q_op = hamiltonian.second_q_op()
bk_mapper = BravyiKitaevMapper()
bkencoded_hamiltonian = bk_mapper.map(second_q_op)
#print('Qubit Hamiltonian in Bravyi-Kitaev encoding', bkencoded_hamiltonian)
# process the Hamiltonian to obtain properly formatted data
hamiltonian_data = process_hamiltonian(bkencoded_hamiltonian, derandomize = True)
system_size, observables_xyze, observables_xyz, hamiltonian_coefficients, absolute_coefficients = hamiltonian_data
'''
VARIATIONAL ANSATZ
'''
ansatz = UCCSD(
problem.num_spatial_orbitals,
problem.num_particles,
bk_mapper,
initial_state=HartreeFock(
problem.num_spatial_orbitals,
problem.num_particles,
bk_mapper,
),
)
'''
Running VQE on the Hamiltonian obtained from PySCFDriver using Statevector simulator (Estimator primitive)
'''
#estimator = Estimator()
# If shots = None, it calculates the exact expectation values. Otherwise, it samples from normal distributions
# with standard errors as standard deviations using normal distribution approximation.
#estimator.set_options(shots = None)
vqe_solver = VQE(Estimator(), ansatz, SLSQP())
vqe_solver.initial_point = np.zeros(ansatz.num_parameters)
calc = GroundStateEigensolver(bk_mapper, vqe_solver)
result = calc.solve(problem)
print(result.raw_result)
#print('NUMBER OF OPERATORS | DERANDOMISED OPERATORS | AVERAGE RMSE ERROR\n')
measurement_range = [50]#, 250, 500, 750, 1000, 1250, 1500, 1750]
molecules_avg_rmse = []
for num_operators in measurement_range:
derandomized_hamiltonian = derandomized_classical_shadow(observables_xyz, num_operators,
system_size, weight=absolute_coefficients)
tuples = (tuple(pauli) for pauli in derandomized_hamiltonian)
counts = Counter(tuples)
# derandomized classical shadow will usually either undergenerate or overgenerate derandomized operators
# Therefore, a modification may be necessary.
expectation_values = []
num_experiments = 1
for iteration in range(num_experiments):
expectation_value = ground_state_energy_from_shadow(derandomized_hamiltonian, result.raw_result.optimal_point)
expectation_values.append(expectation_value)
print("EXPERIMENT {}: GROUND STATE ENERGY FOUND = {}".format(iteration, expectation_value))
rmse_derandomised_cs = np.sqrt(np.sum([(expectation_values[i] - result.raw_result.optimal_value)**2
for i in range(num_experiments)])/num_experiments)
rmse_errors.append(rmse_derandomised_cs)
print('{} | {} | {}'.format(num_operators, counts, rmse_derandomised_cs))
all_molecules_rmse_errors.append(rmse_errors)
elapsed_time = time.time() - start_time
print("Execution time = ", time.strftime("%H:%M:%S", time.gmtime(elapsed_time)))
print(all_molecules_rmse_errors)
|
https://github.com/renatawong/classical-shadow-vqe
|
renatawong
|
'''
(C) 2023 Renata Wong
Electronic structure problem with classical shadows, as presented in https://arxiv.org/abs/2103.07510
This code uses Qiskit as platform.
The shadow is constructed based on derandomized Hamiltonian.
The molecules tested are: H2 (6-31s basis), LiH (sto3g basis), BeH2 (sto3g), H2O (sto3g), and NH3 (sto3g).
The coordinates for NH3 were taken from 'Algorithms for Computer Detection of Symmetry Elementsin Molecular Systems'.
'''
import time
import numpy as np
from collections import Counter
import matplotlib.pyplot as plt
from qiskit import QuantumCircuit, execute
from qiskit_aer import QasmSimulator
from qiskit.quantum_info import SparsePauliOp
from qiskit_nature.units import DistanceUnit
from qiskit_nature.second_q.drivers import PySCFDriver
from qiskit_nature.second_q.algorithms import GroundStateEigensolver
from qiskit_nature.second_q.mappers import BravyiKitaevMapper, JordanWignerMapper, ParityMapper
from qiskit_nature.second_q.circuit.library import UCCSD, HartreeFock
from qiskit_nature.second_q.algorithms import VQEUCCFactory
from qiskit.algorithms.minimum_eigensolvers import VQE
from qiskit.algorithms.optimizers import SLSQP, COBYLA, SPSA
# Estimator primitive is based on the Statevector construct = algebraic simulation
from qiskit.primitives import Estimator
from qiskit.utils import algorithm_globals
from modified_derandomization import modified_derandomized_classical_shadow
from predicting_quantum_properties.data_acquisition_shadow import derandomized_classical_shadow
from predicting_quantum_properties.prediction_shadow import estimate_exp
import qiskit_nature
qiskit_nature.settings.use_pauli_sum_op = False
import h5py
H5PY_DEFAULT_READONLY=1
'''
DEFINING DRIVERS FOR THE MOLECULES
'''
H2_driver = PySCFDriver(
atom="H 0 0 0; H 0 0 0.735",
basis="6-31g",
charge=0,
spin=0,
unit=DistanceUnit.ANGSTROM,
)
LiH_driver = PySCFDriver(
atom="Li 0 0 0.5; H 0 0 0",
basis="sto3g",
charge=0,
spin=0,
unit=DistanceUnit.ANGSTROM,
)
BeH2_driver = PySCFDriver(
atom="Be 0 0 0; H 0 0 1.3264; H 0 0 -1.3264",
basis="sto3g",
charge=0,
spin=0,
unit=DistanceUnit.ANGSTROM,
)
H2O_driver = PySCFDriver(
atom="O 0.0 0.0 0.0; H 0.757 0.586 0.0; H -0.757 0.586 0.0",
basis="sto3g",
charge=0,
spin=0,
unit=DistanceUnit.ANGSTROM,
)
NH3_driver = PySCFDriver(
atom="N 0 0 0; H 0 0 1.008000; H 0.950353 0 -0.336000; H -0.475176 -0.823029 -0.336000",
basis="sto3g",
charge=0,
spin=0,
unit=DistanceUnit.ANGSTROM,
)
'''
FORMATTING HAMILTONIAN
'''
def process_hamiltonian(hamiltonian, derandomize = False):
hamiltonian_observables = []
hamiltonian_coefficients = []
for observable in hamiltonian.paulis:
op_list = []
for op_index, pauli_op in enumerate(observable):
pauli_op = str(pauli_op)
if pauli_op == 'I' or pauli_op == 'X' or pauli_op == 'Y' or pauli_op == 'Z':
op_list.append((pauli_op, op_index))
hamiltonian_observables.append(op_list)
hamiltonian_coefficients = hamiltonian.coeffs.real
system_size = len(hamiltonian_observables[0])
# removing all occurrences of Pauli-I, for all-Pauli-I there is an empty list left
# these observables are needed for estimate_exp()
observables_xyze = []
for observable in hamiltonian_observables:
XYZE = []
for pauli in observable:
if pauli[0] != 'I':
XYZE.append(pauli)
observables_xyze.append(XYZE)
# derandomisation procedure requires that coefficients are non-negative
if derandomize == True:
absolute_coefficients = [abs(coeffcient) for coeffcient in hamiltonian_coefficients]
# removing the empty list as well
# these observables are needed for derandomisation procedure
observables_xyz = []
for idx, observable in enumerate(observables_xyze):
if observable:
observables_xyz.append(observable)
else:
absolute_coefficients.pop(idx)
return system_size, observables_xyze, observables_xyz, hamiltonian_coefficients, absolute_coefficients
return system_size, observables_xyze, hamiltonian_coefficients
'''
COST FUNCTION AND HELPER FUNCTIONS
'''
def basis_change_circuit(pauli_op):
# Generating circuit with just the basis change operators
#
# pauli_op: n-qubit Pauli operator
basis_change = QuantumCircuit(ansatz.num_qubits, ansatz.num_qubits)
for idx, op in enumerate(pauli_op):
if op == 'X':
basis_change.h(idx)
if op == 'Y':
basis_change.h(idx)
basis_change.p(-np.pi/2, idx)
return basis_change
def ground_state_energy_from_shadow(operators, params):
backend = QasmSimulator(method='statevector', shots=1)
pauli_op_dict = Counter(tuple(x) for x in operators)
shadow = []
for pauli_op in pauli_op_dict:
qc = ansatz.bind_parameters(params)
qc = qc.compose(basis_change_circuit(pauli_op))
qc.measure(reversed(range(system_size)), range(system_size))
result = execute(qc, backend, shots=pauli_op_dict[pauli_op]).result()
counts = result.get_counts() # given in order q0 q1 ... qn-1 after register reversal in qc.measure
for count in counts:
for _ in range(counts[count]): # number of repeated measurement values
output_str = list(count)
output = [int(i) for i in output_str]
eigenvals = [x+1 if x == 0 else x-2 for x in output]
snapshot = [(op, eigenval) for op, eigenval in zip(pauli_op, eigenvals)]
shadow.append(snapshot)
expectation_value = 0.0
for term, weight in zip(observables_xyze, hamiltonian_coefficients):
sum_product, match_count = estimate_exp(shadow, term)
if match_count != 0:
expectation_value += (weight * sum_product / match_count)
return expectation_value
'''
EXPERIMENTS
'''
start_time = time.time()
all_molecules_rmse_errors = []
# CALCULATING FERMIONIC HAMILTONIAN AND CONVERTING TO QUBIT HAMILTONIAN
MOLECULES = ['H2', 'LiH', 'BeH2', 'H2O', 'NH3']
for molecule in MOLECULES:
rmse_errors = []
if molecule == 'H2':
problem = H2_driver.run()
if molecule == 'LiH':
problem = LiH_driver.run()
if molecule == 'BeH2':
problem = BeH2_driver.run()
if molecule == 'H2O':
problem = H2O_driver.run()
if molecule == 'NH3':
problem = NH3_driver.run()
hamiltonian = problem.hamiltonian
second_q_op = hamiltonian.second_q_op()
bk_mapper = BravyiKitaevMapper()
bkencoded_hamiltonian = bk_mapper.map(second_q_op)
#print('Qubit Hamiltonian in Bravyi-Kitaev encoding', bkencoded_hamiltonian)
# process the Hamiltonian to obtain properly formatted data
hamiltonian_data = process_hamiltonian(bkencoded_hamiltonian, derandomize = True)
system_size, observables_xyze, observables_xyz, hamiltonian_coefficients, absolute_coefficients = hamiltonian_data
'''
VARIATIONAL ANSATZ
'''
ansatz = UCCSD(
problem.num_spatial_orbitals,
problem.num_particles,
bk_mapper,
initial_state=HartreeFock(
problem.num_spatial_orbitals,
problem.num_particles,
bk_mapper,
),
)
'''
Running VQE on the Hamiltonian obtained from PySCFDriver using Statevector simulator (Estimator primitive)
'''
#estimator = Estimator()
# If shots = None, it calculates the exact expectation values. Otherwise, it samples from normal distributions
# with standard errors as standard deviations using normal distribution approximation.
#estimator.set_options(shots = None)
vqe_solver = VQE(Estimator(), ansatz, SLSQP())
vqe_solver.initial_point = np.zeros(ansatz.num_parameters)
calc = GroundStateEigensolver(bk_mapper, vqe_solver)
result = calc.solve(problem)
print(result.raw_result)
#print('NUMBER OF OPERATORS | DERANDOMISED OPERATORS | AVERAGE RMSE ERROR\n')
measurement_range = [50, 250, 500, 750, 1000, 1250, 1500, 1750]
for num_operators in measurement_range:
derandomized_hamiltonian = derandomized_classical_shadow(observables_xyz, num_operators,
system_size, weight=absolute_coefficients)
tuples = (tuple(pauli) for pauli in derandomized_hamiltonian)
counts = Counter(tuples)
print('Original derandomized Hamiltonian', counts)
# derandomized classical shadow will usually either undergenerate or overgenerate derandomized operators
# adjusting for this issue:
while sum(counts.values()) != num_operators:
for key, value in zip(counts.keys(), counts.values()):
sum_counts = sum(counts.values())
if sum_counts == num_operators:
break
if sum_counts < num_operators:
# generate additional operators from the existing ones by increasing the number of counts
counts[key] += 1
if sum_counts > num_operators:
# remove the element with highest count
max_element_key = [k for k, v in counts.items() if v == max(counts.values())][0]
counts[max_element_key] -= 1
#print('Size-adjusted derandomized Hamiltonian', counts)
# translate the Counter to a set of derandomized operators
new_derandomized_hamiltonian = []
for key, value in counts.items():
for _ in range(value):
new_derandomized_hamiltonian.append(list(key))
#print('Size-adjusted derandomized Hamiltonian', new_derandomized_hamiltonian)
expectation_values = []
num_experiments = 10
for iteration in range(num_experiments):
expectation_value = ground_state_energy_from_shadow(new_derandomized_hamiltonian, result.raw_result.optimal_point)
expectation_values.append(expectation_value)
print("EXPERIMENT {}: GROUND STATE ENERGY FOUND = {}".format(iteration, expectation_value))
rmse_derandomised_cs = np.sqrt(np.sum([(expectation_values[i] - result.raw_result.optimal_value)**2
for i in range(num_experiments)])/num_experiments)
rmse_errors.append(rmse_derandomised_cs)
print('{} | {} | {}'.format(num_operators, counts, rmse_derandomised_cs))
all_molecules_rmse_errors.append(rmse_errors)
elapsed_time = time.time() - start_time
print("Execution time = ", time.strftime("%H:%M:%S", time.gmtime(elapsed_time)))
print(all_molecules_rmse_errors)
# all_molecules_rmse_errors contains a list of lists of errors
'''
points = measurement_range
num_points = len(measurement_range)
for molecule, index in zip(molecules, enumerate(all_molecules_rmse_errors)):
plt.plot([i for i in points], [all_molecules_rmse_errors[index][i] for i in range(num_points)], 'r', label=molecule)
plt.xlabel('Number of measurements')
plt.ylabel('Average RMSE error')
plt.legend(loc=1)
'''
|
https://github.com/renatawong/classical-shadow-vqe
|
renatawong
|
'''
(C) 2023 Renata Wong
Electronic structure problem with classical shadows, as presented in https://arxiv.org/abs/2103.07510
This code uses Qiskit as platform.
The molecule tested is H2.
The shadow is vanilla, i.e. uses randomized basis change operations.
'''
import time
import numpy as np
from collections import Counter
import matplotlib.pyplot as plt
from qiskit import QuantumCircuit, execute
from qiskit_aer import QasmSimulator
from qiskit.quantum_info import SparsePauliOp
from qiskit_nature.units import DistanceUnit
from qiskit_nature.second_q.drivers import PySCFDriver
from qiskit_nature.second_q.algorithms import GroundStateEigensolver
from qiskit_nature.second_q.mappers import BravyiKitaevMapper
from qiskit.circuit.library import TwoLocal
from qiskit.algorithms.minimum_eigensolvers import VQE
from qiskit.algorithms.optimizers import SLSQP, COBYLA, SPSA
# Estimator primitive is based on the Statevector construct = algebraic simulation
from qiskit.primitives import Estimator
from qiskit.utils import algorithm_globals
from predicting_quantum_properties.data_acquisition_shadow import randomized_classical_shadow
from predicting_quantum_properties.prediction_shadow import estimate_exp
# taking care of deprecation issues
import qiskit_nature
qiskit_nature.settings.use_pauli_sum_op = False
import h5py
H5PY_DEFAULT_READONLY=1
driver = PySCFDriver(
atom="H 0 0 0; H 0 0 0.735",
basis="6-31g",
charge=0,
spin=0,
unit=DistanceUnit.ANGSTROM,
)
problem = driver.run()
hamiltonian = problem.hamiltonian
second_q_op = hamiltonian.second_q_op()
mapper = BravyiKitaevMapper()
bkencoded_hamiltonian = mapper.map(second_q_op)
print(bkencoded_hamiltonian)
def process_hamiltonian(hamiltonian, derandomize = False):
hamiltonian_observables = []
hamiltonian_coefficients = []
for observable in hamiltonian.paulis:
op_list = []
for op_index, pauli_op in enumerate(observable):
pauli_op = str(pauli_op)
if pauli_op == 'I' or pauli_op == 'X' or pauli_op == 'Y' or pauli_op == 'Z':
op_list.append((pauli_op, op_index))
hamiltonian_observables.append(op_list)
hamiltonian_coefficients = hamiltonian.coeffs.real
system_size = len(hamiltonian_observables[0])
# removing all occurrences of Pauli-I, for all-Pauli-I there is an empty list left
# these observables are needed for estimate_exp()
observables_xyze = []
for observable in hamiltonian_observables:
XYZE = []
for pauli in observable:
if pauli[0] != 'I':
XYZE.append(pauli)
observables_xyze.append(XYZE)
# derandomisation procedure requires that coefficients are non-negative
if derandomize == True:
absolute_coefficients = [abs(coeffcient) for coeffcient in hamiltonian_coefficients]
# removing the empty list as well
# these observables are needed for derandomisation procedure
observables_xyz = []
for idx, observable in enumerate(observables_xyze):
if observable:
observables_xyz.append(observable)
else:
absolute_coefficients.pop(idx)
return system_size, observables_xyze, observables_xyz, hamiltonian_coefficients, absolute_coefficients
return system_size, observables_xyze, hamiltonian_coefficients
# process the Hamiltonian to obtain properly formatted data
hamiltonian_data = process_hamiltonian(bkencoded_hamiltonian, derandomize = False)
system_size, observables_xyze, hamiltonian_coefficients = hamiltonian_data
#print('HAMILTONIAN\n', observables_xyze)
'''
VARIATIONAL ANSATZ
Note that for molecules other than H_2 you may need to specify a different number of reps.
'''
reps = 5
ansatz = TwoLocal(num_qubits=system_size, reps=reps, rotation_blocks=['ry', 'rz'],
entanglement_blocks='cz', skip_final_rotation_layer=False)
ansatz.decompose().draw('mpl')
def basis_change_circuit(pauli_op):
# Generating circuit with just the basis change operators
#
# pauli_op: n-qubit Pauli operator
basis_change = QuantumCircuit(ansatz.num_qubits, ansatz.num_qubits)
for idx, op in enumerate(pauli_op):
if op == 'X':
basis_change.h(idx)
if op == 'Y':
basis_change.h(idx)
basis_change.p(-np.pi/2, idx)
return basis_change
def ground_state_energy_from_shadow(operators, params):
backend = QasmSimulator(method='statevector', shots=1)
pauli_op_dict = Counter(tuple(x) for x in operators)
shadow = []
for pauli_op in pauli_op_dict:
qc = ansatz.bind_parameters(params)
qc = qc.compose(basis_change_circuit(pauli_op))
qc.measure(reversed(range(system_size)), range(system_size))
result = execute(qc, backend, shots=pauli_op_dict[pauli_op]).result()
counts = result.get_counts() # given in order q0 q1 ... qn-1 after register reversal in qc.measure
for count in counts:
for _ in range(counts[count]): # number of repeated measurement values
output_str = list(count)
output = [int(i) for i in output_str]
eigenvals = [x+1 if x == 0 else x-2 for x in output]
snapshot = [(op, eigenval) for op, eigenval in zip(pauli_op, eigenvals)]
shadow.append(snapshot)
expectation_value = 0.0
for term, weight in zip(observables_xyze, hamiltonian_coefficients):
sum_product, match_count = estimate_exp(shadow, term)
if match_count != 0:
expectation_value += (weight * sum_product / match_count)
return expectation_value
'''
Running VQE on the Hamiltonian obtained from PySCFDriver using Statevector simulator (Estimator primitive)
'''
estimator = Estimator()
# If shots = None, it calculates the exact expectation values. Otherwise, it samples from normal distributions
# with standard errors as standard deviations using normal distribution approximation.
estimator.set_options(shots = None)
vqe_solver = VQE(estimator, ansatz, SPSA(maxiter=3000))
calc = GroundStateEigensolver(mapper, vqe_solver)
result = calc.solve(problem)
print(result.raw_result)
'''
EXPERIMENTS
'''
start_time = time.time()
rmse_errors = []
print('NUMBER OF RANDOM OPERATORS | AVERAGE RMSE ERROR\n')
measurement_range = [50, 250, 500, 750, 1000, 1250, 1500, 1750]
for num_operators in measurement_range:
randomized_basis_change = randomized_classical_shadow(num_operators, system_size)
tuples = (tuple(pauli) for pauli in randomized_basis_change)
counts = Counter(tuples)
expectation_values = []
num_experiments = 10
for iteration in range(num_experiments):
expectation_value = ground_state_energy_from_shadow(randomized_basis_change, result.raw_result.optimal_point)
expectation_values.append(expectation_value)
print("EXPERIMENT {}: GROUND STATE ENERGY FOUND = {}".format(iteration, expectation_value))
rmse_randomised_cs = np.sqrt(np.sum([(expectation_values[i] - result.raw_result.optimal_value)**2
for i in range(num_experiments)])/num_experiments)
rmse_errors.append(rmse_randomised_cs)
print('{} | {}'.format(num_operators, rmse_randomised_cs))
elapsed_time = time.time() - start_time
print("Execution time = ", time.strftime("%H:%M:%S", time.gmtime(elapsed_time)))
points = measurement_range
num_points = len(measurement_range)
plt.plot([i for i in points], [rmse_errors[i] for i in range(num_points)], 'r', label='randomized classical shadow')
plt.xlabel('Number of measurements')
plt.ylabel('Average RMSE error')
plt.legend(loc=1)
|
https://github.com/renatawong/classical-shadow-vqe
|
renatawong
|
'''
CALCULATING NUMBER OF MEASUREMENTS NEEDED AGAINST AN ERROR RATE
Example: H2 molecule in sto3g basis
'''
import numpy as np
from qiskit_nature.units import DistanceUnit
from qiskit_nature.second_q.drivers import PySCFDriver
from qiskit_nature.second_q.mappers import BravyiKitaevMapper
# specifying the geometry of the molecule in question
driver = PySCFDriver(
atom="H 0 0 0; H 0 0 0.735",
basis="sto3g",
charge=0,
spin=0,
unit=DistanceUnit.ANGSTROM,
)
problem = driver.run()
hamiltonian = problem.hamiltonian
# electronic Hamiltonian of the system
second_q_op = hamiltonian.second_q_op()
# The Bravyi-Kitaev representation of the Fermionic Hamiltonian
mapper = BravyiKitaevMapper()
bkencoded_hamiltonian = mapper.map(second_q_op)
print(bkencoded_hamiltonian)
def shadow_bound(error, observables, failure_rate=0.01):
"""
Method taken from: https://pennylane.ai/qml/demos/tutorial_classical_shadows
Calculate the shadow bound for the Pauli measurement scheme.
Implements Eq. (S13) from https://arxiv.org/pdf/2002.08953.pdf
Args:
error (float): The error on the estimator.
observables (list) : List of matrices corresponding to the observables we intend to
measure.
failure_rate (float): Rate of failure for the bound to hold.
Returns:
An integer that gives the number of samples required to satisfy the shadow bound and
the chunk size required attaining the specified failure rate.
"""
M = len(observables)
K = 2 * np.log(2 * M / failure_rate)
shadow_norm = (
lambda op: np.linalg.norm(
op - np.trace(op) / 2 ** int(np.log2(op.shape[0])), ord=np.inf
)
** 2
)
N = 34 * max(shadow_norm(o) for o in observables) / error ** 2
return int(np.ceil(N * K)), int(K)
matrix_observables = [obs.to_matrix().real for obs in bkencoded_hamiltonian]
num_measurements, chunk_size = shadow_bound(error=2e-1, observables=matrix_observables, failure_rate=0.01)
print('Number of measurements (error=2e-1):', num_measurements)
|
https://github.com/TendTo/Quantum-random-walk-simulation
|
TendTo
|
import numpy as np
import networkx as nx
from networkx import hypercube_graph
from networkx.drawing.nx_agraph import graphviz_layout
import matplotlib.pyplot as plt
from typing import Callable
from qiskit import QuantumCircuit, Aer, QuantumRegister, ClassicalRegister, transpile
from qiskit.quantum_info import Operator
from qiskit.tools.visualization import plot_histogram, plot_bloch_vector
from qiskit_aer import AerSimulator
from numpy import pi
coords = [1, np.pi / 2, 0] # [Radius, Theta, Phi]
plot_bloch_vector(coords, coord_type="spherical")
qc = QuantumCircuit(2)
qc.h(0)
qc.x(1)
qc.x(0)
qc.y(1)
qc.h(0)
qc.draw("mpl", initial_state=True)
qc = QuantumCircuit(2)
qc.x(0)
qc.cx(0, 1)
qc.x(0)
qc.draw("mpl", initial_state=True)
pos = {1: [0.75, 1.0], 2: [0.75, 0.15], 3: [0.5, -0.5], 4: [1.0, -0.5]}
U = [
[0.1, 0.2, 0.6, 0.1],
[0.4, 0.3, 0.2, 0.1],
[0.4, 0.2, 0.1, 0.3],
[0.1, 0.0, 0.1, 0.8],
]
G = nx.DiGraph(directed=True)
for i in range(1, 5):
G.add_node(i)
for j in range(1, 5):
G.add_edge(i, j, weight=U[i - 1][j - 1])
nx.draw(G, pos=pos, with_labels=True)
nx.draw_networkx_edge_labels(
G, pos=pos, edge_labels=nx.get_edge_attributes(G, "weight")
)
plt.show()
n_steps = 50 # Number of steps the walker will take
pr = 0.5 # Probability of the walker stepping to the right
initial_position = 0 # Initial position of our walker
def random_walk(pr: float, n_steps: int, initial_pos: int) -> int:
"""Run a random walk with N steps and a probability of stepping to the right of pr.
Args:
pr: probability of stepping to the right
N: number of steps
i: initial position
Returns:
The final position of the walker
"""
position = initial_pos
for _ in range(n_steps):
coin_flip = list(
np.random.choice(2, 1, p=[1 - pr, pr])
) # Flips our weighted coin
position += 2 * coin_flip[0] - 1 # Moves the walker according to the coin flip
return position
print(f"The walker is located at: x = {random_walk(pr, n_steps, initial_position)}")
def dist(n_runs: int, n_steps: int):
"""Plot the distribution of the random walk.
Args:
runs: number of runs
N: number of steps
"""
positions = range(-1 * n_steps, n_steps + 1)
instances = [0 for _ in range(-1 * n_steps, n_steps + 1)]
for _ in range(n_runs):
result = random_walk(pr, n_steps, initial_position)
instances[positions.index(result)] += 1
plt.bar(positions, [n / n_runs for n in instances])
plt.show()
dist(10000, n_steps)
# Number of qubits
n = 3
# Initial state
initial_state = np.array([1] + [0] * (2**n - 1))
assert initial_state.size == 2**n
# Hadamard gate
hadamard_gate_base = 1 / np.sqrt(2) * np.array([[1, 1], [1, -1]])
hadamard_gate = hadamard_gate_base
for i in range(n - 1):
hadamard_gate = np.kron(hadamard_gate, hadamard_gate_base)
# Grover's gate
grover_gate = np.full((2**n, 2**n), 1 / 2 ** (n - 1)) - np.eye(2**n)
# Apply gates
hadamard_res = np.dot(initial_state, hadamard_gate)
hadamard_res = np.square(hadamard_res)
grover_res = np.dot(initial_state, grover_gate)
grover_res = np.square(grover_res)
# Plot results
fig, axes = plt.subplots(2)
plt.suptitle("Hadamard vs Grover gates (|000>)")
for ax, res in zip(axes, [hadamard_res, grover_res]):
ax.set_ylabel("Probability")
ax.set_ylim(0, 1)
ax.bar(tuple(bin(i)[2:].zfill(n) for i in range(res.size)), res)
plt.show()
n_walker_qubits = 4 # The number of qubits used to represent the position of the walker
def coined_walk_circuit(
n_walker_qubits: int,
) -> tuple[QuantumCircuit, QuantumRegister, QuantumRegister, ClassicalRegister]:
"""Create a quantum circuit for the quantum walk.
Args:
n_walker_qubits: number of qubits used to represent the position of the walker
Returns:
a tuple containing the circuit, the walker qubits, the coin qubits and the classical register to store the output
"""
walker_r = QuantumRegister(n_walker_qubits, name="w")
coin_r = QuantumRegister(1, name="c") # The coin requires only one qubit
classic_r = ClassicalRegister(n_walker_qubits, name="output")
qc = QuantumCircuit(walker_r, coin_r, classic_r)
return qc, walker_r, coin_r, classic_r
qc, _, _, _ = coined_walk_circuit(n_walker_qubits)
qc.draw(output="mpl", initial_state=True)
initial_position = 2 ** (
n_walker_qubits - 1
) # The initial position of the walker is the middle of all possible positions
initial_coin_value = 1 # The initial value of the coin is 0
def initialize_coined_walk_circuit(
qc: QuantumCircuit,
walker_r: QuantumRegister,
coin_r: QuantumRegister,
initial_position: int,
initial_coin_value: int,
) -> QuantumCircuit:
"""Initialize the circuit with the initial position of the walker and the initial value of the coin.
Args:
qc: the quantum circuit
walker_r: the quantum register containing the walker's position qubits
coin_r: the quantum register containing the coin qubit
initial_position: the initial position of the walker
initial_coin_value: the initial value of the coin
Returns:
the initialized quantum circuit
"""
if initial_coin_value == 1:
qc.x(coin_r)
for i in range(n_walker_qubits):
if initial_position & (1 << i):
qc.x(walker_r[n_walker_qubits - i - 1])
qc.barrier()
return qc
qc, walker_r, coin_r, _ = coined_walk_circuit(n_walker_qubits)
qc = initialize_coined_walk_circuit(
qc, walker_r, coin_r, initial_position, initial_coin_value
)
qc.draw(output="mpl", initial_state=True)
def coined_walk_step(
qc: QuantumCircuit, walker_r: QuantumRegister, coin_r: QuantumRegister
) -> QuantumCircuit:
"""Single step of the quantum walk.
Args:
qc: quantum circuit
walker_r: the quantum register containing the walker's position qubits
coin_r: the quantum register containing the coin qubit
Returns:
quantum circuit with an added walk step
"""
# "Flip" the coin vector
qc.h(coin_r)
# Implement the Addition Operator
for i in reversed(range(len(walker_r))):
# Qubits with less significant bits than the current one
controls = [walker_r[v] for v in range(len(walker_r) - 1, i, -1)]
controls.append(coin_r) # The coin qubit is also used as a control
qc.mcx(controls, walker_r[i]) # Multi-controlled X gate
if i != 0:
qc.x(walker_r[i]) # Flip the qubit
# Switch the coin vector
qc.x(coin_r)
# Implement the Subtraction Operator
for i in range(len(walker_r)):
if i != 0:
qc.x(walker_r[i]) # Reverse the flip
# Qubits with less significant bits than the current one
controls = [walker_r[v] for v in range(len(walker_r) - 1, i, -1)]
controls.append(coin_r) # The coin qubit is also used as a control
qc.mcx(controls, walker_r[i]) # Multi-controlled X gate
# Revert the switch of the coin vector
qc.x(coin_r)
return qc
qc, walker_r, coin_r, _ = coined_walk_circuit(n_walker_qubits)
qc = coined_walk_step(qc, walker_r, coin_r)
qc.draw(output="mpl", initial_state=True)
n_steps = 5 # The number of steps of the quantum walk
def coined_walk(
n_walker_qubits: int,
n_steps: int,
initial_position: int,
initial_coin_value: int,
init_func: Callable,
) -> QuantumCircuit:
"""Create a quantum circuit for the quantum walk.
Args:
n_walker_qubits: number of qubits used to represent the position of the walker
n_steps: number of steps of the quantum walk
initial_position: initial position of the walker
initial_coin_value: initial value of the coin
init_func: function used to initialize the circuit
Returns:
quantum circuit for the quantum walk
"""
qc, walker_r, coin_r, classic_r = coined_walk_circuit(n_walker_qubits)
qc = init_func(qc, walker_r, coin_r, initial_position, initial_coin_value)
for i in range(n_steps):
step_gate = coined_walk_step(QuantumCircuit(walker_r, coin_r), walker_r, coin_r)
qc.append(step_gate.to_gate(label=f"Step #{i + 1}"), walker_r[:] + coin_r[:])
qc.barrier()
qc.measure(walker_r, reversed(classic_r))
return qc
qc = coined_walk(
n_walker_qubits,
n_steps,
initial_position,
initial_coin_value,
initialize_coined_walk_circuit,
)
qc.draw(output="mpl", initial_state=True)
n_walker_qubits = 6 # The number of qubits used to represent the position of the walker
n_steps = 30 # The number of steps of the quantum walk
initial_position = 2 ** (
n_walker_qubits - 1
) # The initial position of the walker is the middle of all possible positions
initial_coin_value = 0 # The initial value of the coin is 0
n_runs = 5000 # The number of runs of the quantum circuit
qc = coined_walk(
n_walker_qubits,
n_steps,
initial_position,
initial_coin_value,
initialize_coined_walk_circuit,
)
def plot_results(qc: QuantumCircuit, n_runs: int, title: str):
"""Plot the results of the quantum walk.
Args:
qc: quantum circuit for the quantum walk
n_runs: number of runs of the quantum circuit
Returns:
histogram of the results of the quantum walk
"""
simulator: AerSimulator = Aer.get_backend("aer_simulator")
transpiled_qc = transpile(qc, simulator)
results = simulator.run(transpiled_qc, shots=n_runs).result()
counts = results.get_counts(transpiled_qc)
counts = {int(k, 2): v for k, v in counts.items()}
return plot_histogram(counts, title=title)
plot_results(qc, n_runs, "Quantum Coined Walk")
def initialize_balance_coined_walk_circuit(
qc: QuantumCircuit,
walker_r: QuantumRegister,
coin_r: QuantumRegister,
initial_position: int,
initial_coin_value: int,
) -> QuantumCircuit:
"""Initialize the circuit with the initial position of the walker and the initial value of the coin.
Set the coin qubit to |+> and apply the S gate to it to make sure that the coin operator keeps being balanced.
Args:
qc: the quantum circuit
walker_r: the quantum register containing the walker's position qubits
coin_r: the quantum register containing the coin qubit
initial_position: the initial position of the walker
initial_coin_value: the initial value of the coin
Returns:
the initialized quantum circuit
"""
if initial_coin_value == 1:
qc.x(coin_r)
qc.h(coin_r)
qc.s(coin_r)
for i in range(n_walker_qubits):
if initial_position & (1 << i):
qc.x(walker_r[n_walker_qubits - i - 1])
qc.barrier()
return qc
qc, walker_r, coin_r, _ = coined_walk_circuit(n_walker_qubits)
qc = initialize_balance_coined_walk_circuit(
qc, walker_r, coin_r, initial_position, initial_coin_value
)
qc.draw(output="mpl", initial_state=True)
n_walker_qubits = 6 # The number of qubits used to represent the position of the walker
n_steps = 30 # The number of steps of the quantum walk
initial_position = 2 ** (
n_walker_qubits - 1
) # The initial position of the walker is the middle of all possible positions
initial_coin_value = 0 # The initial value of the coin is 0
n_runs = 5000 # The number of runs of the quantum circuit
qc = coined_walk(
n_walker_qubits,
n_steps,
initial_position,
initial_coin_value,
initialize_balance_coined_walk_circuit,
)
plot_results(qc, n_runs, "Balanced Quantum Coined Walk")
n = 3 # Number of qubits
G = hypercube_graph(n) # Create hypercube graph
# Draw graph
nx.draw(
G,
with_labels=True,
pos=graphviz_layout(G, prog="dot"),
node_color="#dddddd",
node_size=2500,
)
plt.show()
n = 2 # Dimension of the hypercube
def graph_walk_circuit(
n: int,
) -> tuple[QuantumCircuit, QuantumRegister, QuantumRegister, ClassicalRegister]:
"""Create a quantum circuit for the graph walk.
Args:
n: number of qubits used to represent the position of the walker
Returns:
quantum circuit for the graph walk, walker register, coin register, and output register
"""
walker_r = QuantumRegister(2**n, name="w")
coin_r = QuantumRegister(n, name="c")
classic_r = ClassicalRegister(2**n, name="output")
qc = QuantumCircuit(walker_r, coin_r, classic_r)
return qc, walker_r, coin_r, classic_r
qc, _, _, _ = graph_walk_circuit(n)
qc.draw(output="mpl", initial_state=True)
n = 2 # Dimension of the hypercube
def grover_coin(coin_r: QuantumRegister) -> Operator:
matrix_size = 2 ** len(coin_r)
grover_matrix = np.full((matrix_size, matrix_size), 2 / matrix_size) - np.eye(
matrix_size
)
return Operator(grover_matrix)
coin_r = QuantumRegister(n, name="c")
qc = QuantumCircuit(coin_r)
gc = grover_coin(coin_r)
qc.unitary(gc, coin_r[:], label="Grover Coin")
qc.draw(output="mpl", initial_state=True)
n = 2 # Dimension of the hypercube
def shift_operator(
walker_r: QuantumRegister, coin_r: QuantumRegister
) -> QuantumCircuit:
"""Create a quantum circuit for the shift operator.
Args:
walker_r: the quantum register containing the walker's position qubits
coin_r: the quantum register containing the coin qubit
Returns:
quantum circuit for the shift operator
"""
qc = QuantumCircuit(walker_r, coin_r)
for i in reversed(range(len(walker_r))):
qc.mcx(coin_r, walker_r[i])
qc.x(coin_r[-1])
for j in range(1, len(coin_r)):
if i & ((1 << j) - 1) == 0:
qc.x(coin_r[-(j + 1)])
return qc
qc, walker_r, coin_r, _ = graph_walk_circuit(n)
qc = shift_operator(walker_r, coin_r)
qc.draw(output="mpl", initial_state=True)
n = 2 # Dimension of the hypercube
def graph_walk_step(
walker_r: QuantumRegister, coin_r: QuantumRegister
) -> QuantumCircuit:
"""Create a quantum circuit for one step of the graph walk.
Args:
walker_r: the quantum register containing the walker's position qubits
coin_r: the quantum register containing the coin qubit
Returns:
quantum circuit for one step of the graph walk
"""
shift = shift_operator(walker_r, coin_r)
gc = grover_coin(coin_r)
walk_step = QuantumCircuit(walker_r, coin_r)
walk_step.unitary(gc, coin_r, label="Grover Coin")
walk_step.compose(shift, inplace=True)
return walk_step
walk_step = graph_walk_step(walker_r, coin_r)
walk_step.draw(output="mpl", initial_state=True)
n = 2 # Dimension of the hypercube
n_steps = 3 # Number of steps of the quantum walk
def graph_walk(
n: int,
n_steps: int,
) -> QuantumCircuit:
"""Create a quantum circuit for the quantum walk over a graph.
Args:
n: dimension of the hypercube
n_steps: number of steps of the quantum walk
initial_position: initial position of the walker
initial_coin_value: initial value of the coin
Returns:
quantum circuit for the quantum walk over a graph
"""
qc, walker_r, coin_r, classic_r = graph_walk_circuit(n)
for i in range(n_steps):
step_gate = graph_walk_step(walker_r, coin_r).to_gate(label=f"Step #{i + 1}")
qc.append(step_gate, walker_r[:] + coin_r[:])
qc.barrier()
qc.measure(walker_r, reversed(classic_r))
return qc
qc = graph_walk(n, n_steps)
qc.draw(output="mpl", initial_state=True)
n = 2 # Dimension of the hypercube
n_steps = 30 # Number of steps of the quantum walk
n_runs = 5000 # Number of runs of the quantum circuit
qc = graph_walk(n, n_steps)
plot_results(qc, n_runs, "Quantum Walk on a Hypercube")
|
https://github.com/deveshq/Qiskit-Fall-Fest
|
deveshq
|
# Importing standard Qiskit libraries
from qiskit import QuantumCircuit, transpile, Aer, IBMQ, execute
from qiskit.tools.jupyter import *
from qiskit.visualization import *
from qiskit.providers.aer import QasmSimulator
from numpy import pi
from qiskit.circuit import Parameter, ParameterVector
import numpy as np
from numpy import pi, sin, cos, exp
import cmath
degree = 1
scaling = 1
coeffs = [0.15 + 0.15j]*degree
coeff0 = 0.1
#Generate a Fourier series.
def function(x):
res = coeff0
for i,c in enumerate(coeffs):
exponent = complex(0, scaling*(i+1)*x)
conj_c = np.conjugate(c)
res += c * np.exp(exponent) + conj_c * np.exp(-exponent)
return np.real(res)
#Original data points
x = np.linspace(-6,6,70)
y_0 = np.array([function(x_) for x_ in x])
from qiskit.circuit.library import TwoLocal
from qiskit.opflow import CircuitStateFn, CircuitOp
import matplotlib.pyplot as plt
n = 2
qc = QuantumCircuit(n)
num_parameters = 8
#Data encoding circuit
def M(cir, x):
for w in range(n):
cir.rx(scaling*x, w)
return cir
#Trainable circuit block (Defining the ansatz)
def U(theta):
encode = TwoLocal(num_qubits = 2, reps = 1, rotation_blocks=['ry','rz'],
entanglement_blocks='cx', entanglement='full', insert_barriers=True)
return encode.assign_parameters(theta)
#Defining the Quantum Model. Here we are mapping the data to the fourier series.
def Quantum_model(cir, weights, x=None):
weights = weights.reshape(2,num_parameters)
cir = cir.compose(U(weights[0]))
cir = cir.compose(M(cir, x))
cir = cir.compose(U(weights[1]))
cir = CircuitStateFn(cir)
weights = weights.reshape(1,2*num_parameters)
circuit = QuantumCircuit(2)
circuit.z(0)
op = CircuitOp(circuit)
return (cir.adjoint().compose(op).compose(cir).eval().real)*scaling
scaling = 1
weight = 2*np.pi*np.random.random(size = (1,2*num_parameters))
random_y = [Quantum_model(qc, weight, x = x_) for x_ in x]
plt.plot(x,random_y, c='blue')
plt.plot(x,y_0, c = 'red')
plt.show()
def square_loss(targets, predictions):
s = 0
for t, p in zip(targets, predictions):
s = s + (t - p) ** 2
loss = s / 2*len(targets)
return loss
def cost(weights):
y = y_0
predictions = [Quantum_model(qc,weights, x=x_) for x_ in x]
return square_loss(y, predictions)
import scipy.optimize as op
weight2 = op.fmin(lambda w: cost(w), weight, xtol=0.0001, ftol=0.0001, maxiter=100,
maxfun=None, full_output=0, disp=1, retall=0, callback=None)
new_weights = np.array(weight2)
trained_y = [Quantum_model(qc, new_weights, x = x_) for x_ in x]
plt.plot(x, trained_y, c='blue')
plt.plot(x,y_0, c = 'red')
plt.show()
#Computes the first 2*K+1 Fourier coefficients of a 2*pi periodic function.
def fourier_coefficients(f, K):
n_coeffs = 2*K+1
t = np.linspace(0, 2*np.pi, n_coeffs, endpoint=False)
y = np.fft.rfft(f(t)) / t.size
return y
n_coeffs = len(new_weights)
n_samples = 100
coeffs = []
def f(x):
return np.array([Quantum_model(qc, new_weights, x=i) for i in x])
coeffs_sample = fourier_coefficients(f, n_coeffs)
coeffs.append(coeffs_sample)
coeffs = np.array(coeffs)
coeffs_real = np.real(coeffs)
coeffs_imag = np.imag(coeffs)
n_coeffs = len(coeffs_real[0])
fig, ax = plt.subplots(1, n_coeffs, figsize=(15,4))
for idx, ax_ in enumerate(ax):
ax_.set_title(r"$c_{}$".format(idx))
ax_.scatter(coeffs_real[:, idx], coeffs_imag[:, idx], s=35, facecolor='white', edgecolor='red')
ax_.set_aspect("equal")
ax_.set_ylim(-1, 1)
ax_.set_xlim(-1, 1)
plt.tight_layout(pad=0.5)
plt.show()
|
https://github.com/SunilBoopalan/quantum-chess-Qiskit
|
SunilBoopalan
|
from chess import *
SquareSet(BB_DIAG_ATTACKS[36][BB_DIAG_MASKS[36] & BB_RANKS[6]])
SquareSet(BB_SQUARES[0] | BB_SQUARES[1])
3423421312222322111 & 222
board = Board()
board.turn = True
Nf3 = chess.Move.from_uci("g1f3")
Ng5 = chess.Move.from_uci("f3g5")
# board.push(Nf3)
board.push(Nf3)
board.push(Ng5)
chess.Piece.from_symbol('P')
board
em_board = Board(fen = None)
|
https://github.com/SunilBoopalan/quantum-chess-Qiskit
|
SunilBoopalan
|
import qiskit
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit import Aer, execute
from qiskit.quantum_info.operators import Operator
from qiskit.extensions import UnitaryGate, Initialize
from qiskit import IBMQ
import math
backend = Aer.get_backend('qasm_simulator')
class quantum_obj:
def __init__(self, pos, piece):
self.piece = piece
self.qnum = { '0': [pos, 1] }
self.ent = []
def split(self, i_add, pos1, pos2):
## i_pos = self.qnum[i_add][0]
self.qnum[i_add + '0'] = ["", 0]
self.qnum[i_add + '1'] = ["", 0]
self.qnum[i_add + '0'][0] = pos1
self.qnum[i_add + '1'][0] = pos2
self.qnum[i_add + '0'][1] = self.qnum[i_add][1]/2.0 #probability of split piece is half of original piece
self.qnum[i_add + '1'][1] = self.qnum[i_add][1]/2.0
del self.qnum[i_add]
def entangle_oneblock(self, i_add, pos1, obj, obj_add):
# return quantumobj, pos of quantumobj from in_bw_pieces
'''
1 2 3
a | P Q _
b | _ _ _
c | _ _ _
a1 to a3
If Q is classical, move cannot be made.
If Q is not classical, P and Q get entangled.
Let P[P at a1] = x
Let P[Q at a2] = y
After the move,
P[P at a3] = x * (1 - y)
P[P at a1] = x * y
'''
prob_blocked_piece = self.qnum[i_add][1]
prob_blocking_piece = obj.qnum[obj_add][1]
x = prob_blocked_piece
y = prob_blocking_piece
a = x*y # prob_not_moved = prob_blocked*prob_blocking
b = x*(1-y) # prob_moved = prob_blocked_piece*(1-prob_blocking_piece)
self.qnum[i_add + '0'] = ["", 0]
self.qnum[i_add + '1'] = ["", 0]
self.qnum[i_add + '0'][0] = self.qnum[i_add][0]
self.qnum[i_add + '1'][0] = pos1
self.qnum[i_add + '0'][1] = a
self.qnum[i_add + '1'][1] = b
del self.qnum[i_add]
last_state = obj_add[:-1] + str(int(not(int(obj_add[-1]))))
obj.ent += [(self, i_add+'1', obj_add), (self, i_add+'0', last_state)] # make sure that obj is quantumobj while calling!
self.ent += [(obj, obj_add, i_add+'1'), (obj, last_state, i_add+'0')]
def entangle_twoblock(self, i_add, pos1, pos2, obj1, obj1_add, obj2, obj2_add): #change pos parameter to address
# Applicable when
# - both positions are blocked, so entanglement with 2 pieces
# obj1 is blocking pos1 and obj2 is blocking pos2
# return quantumobj, pos of quantumobj from in_bw_pieces
'''
1 2 3
a | P Y R
b | X _ _
c | Q _ _
a1 to split (c1, a3)
If both Q and R are classical, no move.
Else, weighted split.
Let P[P at a1] = x
Let P[Y at a2] = y
Let P[X at b1] = z
After the move,
P[P at a1] = x * P[both Q and R are there] = x*y*z
P[P at a3] = x * ( P[Q not at a2, R at b1] + 0.5 * P[Q, R not there] ) = x*(1-y)*z + 0.5*x*(1-y)*(1-z)
P[P at c1] = x * ( P[Q at a2, R not at b1] + 0.5 * P[Q, R not there] ) = x*y*(1-z) + 0.5*x*(1-y)*(1-z)
#check
Total prob = xyz + xz - xyz + xy - xyz + x - xy - xz + xyz
= x
# These hold up even if P, Q, R are classical
'''
'''
1. ob1 there, ob2 there - not possible (0)
2. ob1 there, ob2 not there - p(ob1)
3. ob1 not there, ob2 there - p(ob2)
4. ob1 not there, ob2 not there - (1-p(ob1))(1-p(ob2))
at pos1 when ob1 not there - c3 + 0.5*c4
at pos2 when ob2 not there - c2 + 0.5*c4
at ipos when ob1, ob2 there - c1
'''
prob_i_pos = self.qnum[i_add][1]
prob_ob1 = obj1.qnum[obj1_add][1]
prob_ob2 = obj2.qnum[obj2_add][1]
if obj1 == obj2:
prob_pos1 = prob_i_pos*prob_ob2 + 0.5*prob_i_pos*(1 - prob_ob1 - prob_ob2)
prob_pos2 = prob_i_pos*prob_ob1 + 0.5*prob_i_pos*(1 - prob_ob1 - prob_ob2)
self.qnum[i_add + '0'] = ["", 0]
self.qnum[i_add + '1'] = ["", 0]
self.qnum[i_add + '0'][0] = pos1
self.qnum[i_add + '0'][1] = prob_pos1
self.qnum[i_add + '1'][0] = pos2
self.qnum[i_add + '1'][1] = prob_pos2
last_state1 = obj1_add[:-1] + str(int(not(int(obj1_add[-1]))))
last_state2 = obj2_add[:-1] + str(int(not(int(obj2_add[-1]))))
obj1.ent += [(self, i_add+'0', obj1_add), (self, i_add+'1', last_state1)] # obj1 cannot coexist with i_add+'0'
obj2.ent += [(self, i_add+'1', obj2_add), (self, i_add+'0', last_state2)] # obj2 cannot coexist with i_add+'1'
self.ent += [(obj1, obj1_add, i_add+'0'), (obj1, last_state1, i_add+'1'), (obj2, obj2_add, i_add+'1'), (obj2, last_state2, i_add+'0')]
else:
prob_unmoved = prob_i_pos*prob_ob1*prob_ob2
prob_pos1 = prob_i_pos*(1-prob_ob1)*prob_ob2 + 0.5*prob_i_pos*(1-prob_ob1)*(1-prob_ob2)
prob_pos2 = prob_i_pos*prob_ob1*(1-prob_ob2) + 0.5*prob_i_pos*(1-prob_ob1)*(1-prob_ob2)
# a(bc+c-bc+b-bc+1-b-c+bc) = a
self.qnum[i_add + '00'] = ["", 0]
self.qnum[i_add + '01'] = ["", 0]
self.qnum[i_add + '10'] = ["", 0]
self.qnum[i_add + '00'][0] = self.qnum[i_add][0]
self.qnum[i_add + '01'][0] = pos1
self.qnum[i_add + '10'][0] = pos2
self.qnum[i_add + '00'][1] = prob_unmoved
self.qnum[i_add + '01'][1] = prob_pos1
self.qnum[i_add + '10'][1] = prob_pos2
last_state1 = obj1_add[:-1] + str(int(not(int(obj1_add[-1]))))
last_state2 = obj2_add[:-1] + str(int(not(int(obj2_add[-1]))))
obj1.ent += [(self, i_add+'01', obj1_add), (self, i_add+'00', last_state1)] # obj1 cannot coexist with i_add+'01'
obj2.ent += [(self, i_add+'10', obj2_add), (self, i_add+'00', last_state2)] # obj2 cannot coexist with i_add+'10'
self.ent += [(obj1, obj1_add, i_add+'01'), (obj1, last_state1, i_add+'00'), (obj2, obj2_add, i_add+'10'), (obj2, last_state2, i_add+'00')]
del self.qnum[i_add]
# classical cases matter here
'''
Scaling up probabilities:
A - 0.5 - found to not exist
B - 0.25 --> (after killing A) 0.5 = 0.25/(0.25+0.25) = B/(B+C)
C - 0.25 --> (after killing A) 0.5
'''
def detangle(self, add, obj):
probs = 0
all_states = list(self.qnum.keys())
for i in all_states:
if i.startswith(add):
print('delete', i)
del self.qnum[i]
else:
probs += self.qnum[i][1]
for i in self.qnum:
self.qnum[i][1] /= probs
# for i in range(len(self.ent)):
# # nested entanglement to be handled here
# if self.ent[i][0] == obj:
# self.ent.remove(self.ent[i])
# 2block fixage
# peek at nested entanglement (>2 degrees of ent across >2 pieces)
def meas(self):
'''
1 2 3
a | X Q Y
b | R _ _
c | Z _ W
PIECE1
P(b2, 0) - 1
P.split(a2, b1)
# final
Q(a2, 00) - 0.5
R(b1, 01) - 0.5
PIECE2
W(c3, 00) - 1/2
X(a1, 01) - 1/2
X.split(a3, c1)
# final
W(c3, 00) - 1/2
X(a1, 0100) - 1/8
Y(a3, 0101) - 3/16
Z(c1, 0110) - 3/16
PIECE2 is killer
How to measure?
Cannot pad 00 with zeroes, last 2 qubits can be anything (don't care condition)
0000 - 1/4*1/2
0001 - 1/4*1/2
0010 - 1/4*1/2
0011 - 1/4*1/2
0100 - 1/8
0101 - 3/16
0110 - 3/16
0111 - 0
1 2 3 4
0 1 1/2 9/16 9/16
1 0 1/2 7/16 7/16
'''
level = 0
for i in self.qnum:
if len(i) > level:
level = len(i)
# probs = [(0,0)]*level
# for i in self.qnum:
# for j in range(0, len(i)):
# if self.qnum[j][0] == '0':
# probs[j][0] += 1
# else:
# probs[j][1] += 1
# all_add = self.qnum.keys()
# n = len(all_add)
# for i in range(0, n):
# if all_add[i]
## print(level)
'''
states:
000
001
010
011
100
101
110
111
poss_states:
00
01
11
100
101
'''
params = [0+0.j]*(2**(level-1))
states = [bin(i)[2:].zfill(level-1) for i in range(0, 2**(level-1))]
poss_states = list(self.qnum.keys())
poss_states = [poss_states[i][1:] for i in range(0, len(poss_states))]
for i in range(0, len(poss_states)):
if(len(poss_states[i]) < level):
index = states.index(poss_states[i] + '0'*(level - 1 - len(poss_states[i])))
params[index] = self.qnum['0'+poss_states[i]][1]**0.5 + 0.j
#Initializing:
qr = QuantumRegister(level-1)
cr = ClassicalRegister(level-1)
ckt = QuantumCircuit(qr, cr)
ckt.initialize(params, [qr[i] for i in range(level-1)])
# init_gate = Initialize(params)
# init_gate.label = "init"
# ckt.append(init_gate, [i for i in range(level-1)])
ckt.measure_all()
## print(ckt)
job = execute(ckt, backend, shots = 1)
res = job.result()
# print(res.get_counts())
final_state = list(res.get_counts().keys())[0][:(level-1)]
## print(final_state)
## print(all_add)
while(True):
if(final_state in poss_states):
break
final_state = final_state[:-1]
final_state = '0' + final_state
print('Final state of piece2 : ', final_state)
## detangle
print("Piece2 ent list : ", self.ent)
for i in range(len(self.ent)):
if final_state.startswith(self.ent[i][2]):
print("Piece1 ent list : ", self.ent[i][0].ent)
print("Entangled guy's states : ", self.ent[i][0].qnum)
self.ent[i][0].detangle(self.ent[i][1], self)
print("Entangled guy's states : ", self.ent[i][0].qnum)
final_pos = self.qnum[final_state][0]
self.qnum.clear()
self.ent.clear()
self.qnum['0'] = [final_pos, 1]
print("States of piece2 after measuring : ", self.qnum)
# Test cases
# '''
# 1 2 3
# a | _ _ Q
# b | P R _
# c | _ S _
# P - 00 (0.5)
# Q - 010 (0.25)
# R - 0110 (0.125)
# S - 0111 (0.125)
# '''
# piece1 = quantum_obj("a2")
# piece1.split("0", "b1", "b2")
# piece1.split("01", "a3", "c1")
# piece1.split("011", "b2", "c2")
# '''
# 1 2 3
# a | Z _ Q
# b | P R _
# c | X S Y
# P - 00 (0.5)
# Q - 010 (0.25)
# R - 0110 (0.125)
# S - 0111 (0.125)
# X - 000 (1/16 = 0.0625) [ignore X since obj1==obj2 for this test case]
# Y - 00 (0.5 + 0.5*(1-0.5-0.125) = 0.6875)
# Z - 01 (0.125 + 0.5*(1-0.5-0.125) = 0.3125)
# piece1.ent - [piece2, "0", "00"]
# piece2.ent - [piece1, "00", "0"]
# '''
# piece2 = quantum_obj("c1")
# piece2.entangle_twoblock("0", "c3", "a1", piece1, "0111", piece1, "00")
# piece2.meas()
# '''
# to-do
# - restore old addresses after detangle (reduce level)
# - ent_twoblock obj1 = obj2 case: prob (both being there) = 0 [done]
# - integrate with main code
# '''
|
https://github.com/RedHatParichay/qiskit-lancasterleipzig-2023
|
RedHatParichay
|
## Blank Code Cell
## Use only if you need to install the grader and/or Qiskit
## If you are running this notebook in the IBM Quantum Lab - you can ignore this cell
!pip install qiskit
!pip install 'qc-grader[qiskit] @ git+https://github.com/qiskit-community/Quantum-Challenge-Grader.git'
event = "Qiskit Fall Fest"
## Write your code below here. Delete the current information and replace it with your own ##
## Make sure to write your information between the quotation marks!
name = "Brian"
age = "33"
school = "UConn"
## Now press the "Run" button in the toolbar above, or press Shift + Enter while you're active in this cell
## You do not need to write any code in this cell. Simply run this cell to see your information in a sentence. ##
print(f'My name is {name}, I am {age} years old, and I attend {school}.')
## Run this cell to make sure your grader is setup correctly
%set_env QC_GRADE_ONLY=true
%set_env QC_GRADING_ENDPOINT=https://qac-grading.quantum-computing.ibm.com
from qiskit import QuantumCircuit
# Create quantum circuit with 3 qubits and 3 classical bits
# (we'll explain why we need the classical bits later)
qc = QuantumCircuit(3,3)
# return a drawing of the circuit
qc.draw()
## You don't need to write any new code in this cell, just run it
from qiskit import QuantumCircuit
qc = QuantumCircuit(3,3)
# measure all the qubits
qc.measure([0,1,2], [0,1,2])
qc.draw(output="mpl")
from qiskit.providers.aer import AerSimulator
# make a new simulator object
sim = AerSimulator()
job = sim.run(qc) # run the experiment
result = job.result() # get the results
result.get_counts() # interpret the results as a "counts" dictionary
from qiskit import QuantumCircuit
from qiskit.providers.aer import AerSimulator
## Write your code below here ##
## Do not modify the code under this line ##
qc.draw()
sim = AerSimulator() # make a new simulator object
job = sim.run(qc) # run the experiment
result = job.result() # get the results
answer1 = result.get_counts()
# Grader Cell: Run this to submit your answer
from qc_grader.challenges.fall_fest23 import grade_ex1a
grade_ex1a(answer1)
from qiskit import QuantumCircuit
qc = QuantumCircuit(2)
# We start by flipping the first qubit, which is qubit 0, using an X gate
qc.x(0)
# Next we add an H gate on qubit 0, putting this qubit in superposition.
qc.h(0)
# Finally we add a CX (CNOT) gate on qubit 0 and qubit 1
# This entangles the two qubits together
qc.cx(0, 1)
qc.draw(output="mpl")
from qiskit import QuantumCircuit
qc = QuantumCircuit(2, 2)
## Write your code below here ##
## Do not modify the code under this line ##
answer2 = qc
qc.draw(output="mpl")
# Grader Cell: Run this to submit your answer
from qc_grader.challenges.fall_fest23 import grade_ex1b
grade_ex1b(answer2)
|
https://github.com/RedHatParichay/qiskit-lancasterleipzig-2023
|
RedHatParichay
|
## Blank Code Cell
## Use only if you need to install the grader and/or Qiskit
## If you are running this notebook in the IBM Quantum Lab - you can ignore this cell
!pip install qiskit
!pip install 'qc-grader[qiskit] @ git+https://github.com/qiskit-community/Quantum-Challenge-Grader.git'
## Run this cell to make sure your grader is setup correctly
%set_env QC_GRADE_ONLY=true
%set_env QC_GRADING_ENDPOINT=https://qac-grading.quantum-computing.ibm.com
from qiskit import QuantumCircuit
qc = QuantumCircuit(3, 3)
## Write your code below this line ##
## Do not change the code below here ##
answer1 = qc
qc.draw()
# Grader Cell: Run this to submit your answer
from qc_grader.challenges.fall_fest23 import grade_ex2a
grade_ex2a(answer1)
from qiskit import QuantumCircuit
qc = QuantumCircuit(3, 3)
qc.barrier(0, 1, 2)
## Write your code below this line ##
## Do not change the code below this line ##
answer2 = qc
qc.draw()
# Grader Cell: Run this to submit your answer
from qc_grader.challenges.fall_fest23 import grade_ex2b
grade_ex2b(answer2)
answer3: bool
## Quiz: evaluate the results and decide if the following statement is True or False
q0 = 1
q1 = 0
q2 = 1
## Based on this, is it TRUE or FALSE that the Guard on the left is a liar?
## Assign your answer, either True or False, to answer3 below
answer3 =
from qc_grader.challenges.fall_fest23 import grade_ex2c
grade_ex2c(answer3)
## Quiz: Fill in the correct numbers to make the following statement true:
## The treasure is on the right, and the Guard on the left is the liar
q0 =
q1 =
q2 =
## HINT - Remember that Qiskit uses little-endian ordering
answer4 = [q0, q1, q2]
# Grader Cell: Run this to submit your answer
from qc_grader.challenges.fall_fest23 import grade_ex2d
grade_ex2d(answer4)
from qiskit import QuantumCircuit
qc = QuantumCircuit(3)
## in the code below, fill in the missing gates. Run the cell to see a drawing of the current circuit ##
qc.h(0)
qc.barrier(0, 1, 2)
qc.x(2)
qc.cx(2, 0)
qc.barrier(0, 1, 2)
qc.cx(2, 1)
qc.x(0)
## Do not change any of the code below this line ##
answer5 = qc
qc.draw(output="mpl")
# Grader Cell: Run this to submit your answer
from qc_grader.challenges.fall_fest23 import grade_ex2e
grade_ex2e(answer5)
from qiskit import QuantumCircuit, Aer, transpile
from qiskit.visualization import plot_histogram
## This is the full version of the circuit. Run it to see the results ##
quantCirc = QuantumCircuit(3)
quantCirc.h(0), quantCirc.h(2), quantCirc.cx(0, 1), quantCirc.barrier(0, 1, 2), quantCirc.cx(2, 1), quantCirc.x(2), quantCirc.cx(2, 0), quantCirc.x(2)
quantCirc.barrier(0, 1, 2), quantCirc.swap(0, 1), quantCirc.x(1), quantCirc.cx(2, 1), quantCirc.x(0), quantCirc.x(2), quantCirc.cx(2, 0), quantCirc.x(2)
# Execute the circuit and draw the histogram
measured_qc = quantCirc.measure_all(inplace=False)
backend = Aer.get_backend('qasm_simulator') # the device to run on
result = backend.run(transpile(measured_qc, backend), shots=1000).result()
counts = result.get_counts(measured_qc)
plot_histogram(counts)
from qiskit.primitives import Sampler
from qiskit.visualization import plot_distribution
sampler = Sampler()
result = sampler.run(measured_qc, shots=1000).result()
probs = result.quasi_dists[0].binary_probabilities()
plot_distribution(probs)
|
https://github.com/RedHatParichay/qiskit-lancasterleipzig-2023
|
RedHatParichay
|
## Blank Code Cell
## Use only if you need to install the grader and/or Qiskit
## If you are running this notebook in the IBM Quantum Lab - you can ignore this cell
!pip install qiskit
!pip install 'qc-grader[qiskit] @ git+https://github.com/qiskit-community/Quantum-Challenge-Grader.git'
## Run this cell to make sure your grader is setup correctly
%set_env QC_GRADE_ONLY=true
%set_env QC_GRADING_ENDPOINT=https://qac-grading.quantum-computing.ibm.com
from qiskit import QuantumCircuit
from qiskit.circuit import QuantumRegister, ClassicalRegister
qr = QuantumRegister(1)
cr = ClassicalRegister(2)
qc = QuantumCircuit(qr, cr)
# unpack the qubit and classical bits from the registers
(q0,) = qr
b0, b1 = cr
# apply Hadamard
qc.h(q0)
# measure
qc.measure(q0, b0)
# begin if test block. the contents of the block are executed if b0 == 1
with qc.if_test((b0, 1)):
# if the condition is satisfied (b0 == 1), then flip the bit back to 0
qc.x(q0)
# finally, measure q0 again
qc.measure(q0, b1)
qc.draw(output="mpl", idle_wires=False)
from qiskit_aer import AerSimulator
# initialize the simulator
backend_sim = AerSimulator()
# run the circuit
reset_sim_job = backend_sim.run(qc)
# get the results
reset_sim_result = reset_sim_job.result()
# retrieve the bitstring counts
reset_sim_counts = reset_sim_result.get_counts()
print(f"Counts: {reset_sim_counts}")
from qiskit.visualization import *
# plot histogram
plot_histogram(reset_sim_counts)
qr = QuantumRegister(2)
cr = ClassicalRegister(2)
qc = QuantumCircuit(qr, cr)
q0, q1 = qr
b0, b1 = cr
qc.h(q0)
qc.measure(q0, b0)
## Write your code below this line ##
## Do not change the code below this line ##
qc.measure(q1, b1)
qc.draw(output="mpl", idle_wires=False)
backend_sim = AerSimulator()
job_1 = backend_sim.run(qc)
result_1 = job_1.result()
counts_1 = result_1.get_counts()
print(f"Counts: {counts_1}")
# Grader Cell: Run this to submit your answer
from qc_grader.challenges.fall_fest23 import grade_ex3b
grade_ex3b(qc)
controls = QuantumRegister(2, name="control")
target = QuantumRegister(1, name="target")
mid_measure = ClassicalRegister(2, name="mid")
final_measure = ClassicalRegister(1, name="final")
base = QuantumCircuit(controls, target, mid_measure, final_measure)
def trial(
circuit: QuantumCircuit,
target: QuantumRegister,
controls: QuantumRegister,
measures: ClassicalRegister,
):
"""Probabilistically perform Rx(theta) on the target, where cos(theta) = 3/5."""
## Write your code below this line, making sure it's indented to where this comment begins from ##
## Do not change the code below this line ##
qc = base.copy_empty_like()
trial(qc, target, controls, mid_measure)
qc.draw("mpl", cregbundle=False)
# Grader Cell: Run this to submit your answer
from qc_grader.challenges.fall_fest23 import grade_ex3c
grade_ex3c(qc)
def reset_controls(
circuit: QuantumCircuit, controls: QuantumRegister, measures: ClassicalRegister
):
"""Reset the control qubits if they are in |1>."""
## Write your code below this line, making sure it's indented to where this comment begins from ##
## Do not change the code below this line ##
qc = base.copy_empty_like()
trial(qc, target, controls, mid_measure)
reset_controls(qc, controls, mid_measure)
qc.measure(controls, mid_measure)
qc.draw("mpl", cregbundle=False)
# Grader Cell: Run this to submit your answer
from qc_grader.challenges.fall_fest23 import grade_ex3d
grade_ex3d(qc)
# Set the maximum number of trials
max_trials = 2
# Create a clean circuit with the same structure (bits, registers, etc) as the initial base we set up.
circuit = base.copy_empty_like()
# The first trial does not need to reset its inputs, since the controls are guaranteed to start in the |0> state.
trial(circuit, target, controls, mid_measure)
# Manually add the rest of the trials. In the future, we will be able to use a dynamic `while` loop to do this, but for now,
# we statically add each loop iteration with a manual condition check on each one.
# This involves more classical synchronizations than the while loop, but will suffice for now.
for _ in range(max_trials - 1):
reset_controls(circuit, controls, mid_measure)
with circuit.if_test((mid_measure, 0b00)) as else_:
# This is the success path, but Qiskit can't directly
# represent a negative condition yet, so we have an
# empty `true` block in order to use the `else` branch.
pass
with else_:
## Write your code below this line, making sure it's indented to where this comment begins from ##
## Do not change the code below this line ##
# We need to measure the control qubits again to ensure we get their final results; this is a hardware limitation.
circuit.measure(controls, mid_measure)
# Finally, let's measure our target, to check that we're getting the rotation we desired.
circuit.measure(target, final_measure)
circuit.draw("mpl", cregbundle=False)
# Grader Cell: Run this to submit your answer
from qc_grader.challenges.fall_fest23 import grade_ex3e
grade_ex3e(circuit)
sim = AerSimulator()
job = sim.run(circuit, shots=1000)
result = job.result()
counts = result.get_counts()
plot_histogram(counts)
|
https://github.com/JavaFXpert/qiskit-plotting-app
|
JavaFXpert
|
# Do the necessary import for our program
%matplotlib inline
from qiskit import *
from qiskit.aqua.algorithms import Grover
from qiskit.aqua.components.oracles import LogicalExpressionOracle
from qiskit.tools.visualization import plot_histogram
import ipywidgets as widgets
import matplotlib.pyplot as plt
from IPython.display import clear_output
SHOW_CIRCUIT = True
def create_expanded_button(description, button_style):
return widgets.Button(description=description, button_style=button_style,
layout=widgets.Layout(height='auto', width='5%'))
header_button = create_expanded_button('Header', 'success')
left_button = create_expanded_button('Left', 'info')
center_button = create_expanded_button('Center', 'warning')
right_button = create_expanded_button('Right', 'info')
footer_button = create_expanded_button('Footer', 'success')
app_ui = widgets.AppLayout(header=None,
left_sidebar=None,
center=center_button,
right_sidebar=None,
footer=None)
display(app_ui)
log_expr_widget = widgets.Text(
value='',
description='Logical expression:',
disabled=True
)
out1 = widgets.Output()
out2 = widgets.Output()
rel_matrix = None
names = ["A", "B", "C", "D"]
num_names = len(names)
REL_NONE = ""
REL_GOOD = "good"
REL_BAD = "bad"
# Compute logical expression from dropdowns
def compute_log_expr():
log_expr_str = ""
good_rel_exist = False
bad_rel_exist = False
for col_num in range(num_names + 1):
for row_num in range(num_names + 1):
if col_num > row_num and row_num > 0:
if rel_matrix[col_num][row_num].value == 1: #1 is good
good_rel_exist = True
break
if good_rel_exist:
log_expr_str = "("
for col_idx in range(num_names + 1):
for row_idx in range(num_names + 1):
if col_idx > row_idx and row_idx > 0:
if rel_matrix[col_idx][row_idx].value == 1: #1 is good
log_expr_str += "("
log_expr_str += rel_matrix[0][row_idx].value
log_expr_str += " & "
log_expr_str += rel_matrix[col_idx][0].value
log_expr_str += ")|"
if log_expr_str[-1] == '|':
log_expr_str = log_expr_str[:-1]
log_expr_str += ")"
for col_num in range(num_names + 1):
for row_num in range(num_names + 1):
if col_num > row_num and row_num > 0:
if rel_matrix[col_num][row_num].value == 2: #2 is bad
bad_rel_exist = True
break
if bad_rel_exist:
if good_rel_exist:
log_expr_str += "&"
bad_log_expr_str = "("
for col_idx in range(num_names + 1):
for row_idx in range(num_names + 1):
if col_idx > row_idx and row_idx > 0:
if rel_matrix[col_idx][row_idx].value == 2: #2 is bad
bad_log_expr_str += "~("
bad_log_expr_str += rel_matrix[0][row_idx].value
bad_log_expr_str += " & "
bad_log_expr_str += rel_matrix[col_idx][0].value
bad_log_expr_str += ")&"
if bad_log_expr_str[-1] == '&':
bad_log_expr_str = bad_log_expr_str[:-1]
bad_log_expr_str += ")"
log_expr_str += bad_log_expr_str
log_expr_widget.value = log_expr_str
#def handle_log_expr_text_entered(text_widget):
def handle_log_expr_text_entered(some_widget):
with out1:
clear_output()
compute_log_expr()
algorithm = Grover(LogicalExpressionOracle(log_expr_widget.value))
# Run the algorithm on a QASM simulator, printing the most frequently occurring result
qasm_simulator_backend = BasicAer.get_backend('qasm_simulator')
qasm_simulator_result = algorithm.run(qasm_simulator_backend)
if SHOW_CIRCUIT:
circuit = qasm_simulator_result['circuit']
with out1:
display(plot_histogram(qasm_simulator_result['measurement']))
if SHOW_CIRCUIT:
with out2:
clear_output()
display(circuit.draw(output='mpl'))
log_expr_button = widgets.Button(
description = "Run",
)
# Relationship model for the grid
def compute_rel_matrix_entry(col_num, row_num):
entry = None
if col_num == 0:
if row_num > 0:
entry = widgets.Label(value=names[row_num - 1])
else:
entry = widgets.Label(value='')
elif row_num == 0:
entry = widgets.Label(value=names[col_num - 1])
elif col_num < row_num:
entry = widgets.Dropdown(
options=[('', 0), (REL_GOOD, 1), (REL_BAD, 2)],
value=0,
layout=widgets.Layout(width='auto', height='auto')
)
else:
entry = widgets.Label(value='')
return entry
rel_matrix = [[compute_rel_matrix_entry(i, j) for i in range(num_names + 1)] for j in range(num_names + 1)]
for col_num in range(num_names + 1):
for row_num in range(num_names + 1):
if col_num > row_num and row_num > 0:
rel_matrix[col_num][row_num].observe(handle_log_expr_text_entered, names='value')
# Make Grid with name headings and dropdown relationships
rel_gridbox = widgets.GridBox(children=[rel_matrix[col_idx][row_idx] for row_idx in [0, 1, 2, 3] for col_idx in [0, 2, 3, 4]],
layout=widgets.Layout(
width='100%',
grid_template_columns='70px ' * len(names),
grid_template_rows='30px ' * len(names),
grid_gap='10px 10px')
)
tab = widgets.Tab(children = [out1, out2], layout=widgets.Layout(height='auto', width='auto'))
tab.set_title(0, 'Probabilities')
if SHOW_CIRCUIT:
tab.set_title(1, 'Circuit')
app_header = widgets.Label(value = "Grover Search Party")
center_pane = widgets.VBox([app_header, rel_gridbox, widgets.VBox([log_expr_widget, tab])])
app_ui.center = center_pane
|
https://github.com/JavaFXpert/qiskit-plotting-app
|
JavaFXpert
|
from qiskit import *
from qiskit.visualization import plot_histogram
from qiskit.tools.monitor import job_monitor
# quantum circuit to make a Bell state
bell = QuantumCircuit(2, 2)
bell.h(0)
bell.cx(0, 1)
meas = QuantumCircuit(2, 2)
meas.measure([0,1], [0,1])
# execute the quantum circuit
backend = BasicAer.get_backend('qasm_simulator') # the device to run on
circ = bell+meas
result = execute(circ, backend, shots=1000).result()
counts = result.get_counts(circ)
print(counts)
plot_histogram(counts)
|
https://github.com/IffTech/UCLA-Qiskit-Intro
|
IffTech
|
# You'll always start off any Quantum circuit with...QuantumCircuit
from qiskit import QuantumCircuit
# Every quantum circuit has some number of quantum registers and classical registers that you get to define in advance
# You can either pass one integer in to denote a fixed number of quantum registers
# OR you can pass in two numbers, the first being the # of quantum registers and the second being the number of classical registers
qc = QuantumCircuit(5) # creates empty circuit with 5 quantum registers
qc = QuantumCircuit(3,1) # creates empty circuit with 3 quantum registers, 1 classical register
# For this part of the workshop, we'll start simple with a one-qubit circuit and gradually work towards
# larger qubit circuits
qc = QuantumCircuit(1,1)
# A blank circuit isn't really useful to us so lets add some gates!
# There are two ways to add gates, the easier way is to do it like so:
## Apply an X gate to qubit 0 (the only qubit in this circuit)
qc.x(0)
## Or to .append() them to the circuit
## The [0] tells qiskit to apply the gate to the 0th qubit (the first).
from qiskit.circuit.library import XGate
qc.append(XGate(), [0])
# to see the circuit, we can just use the .draw() method
qc.draw()
# Notice how despite two different methods for adding gates, we still see the same gate!
# For a "shinier" representation of our circuit, we can tell Qiskit to leverage matplotlib
qc.draw(output='mpl')
# Awesome! Your first quantum circuit!
# Before we actually run this on something, lets perform some "sanity checks"
# We know that applying two pauli operators back to back should return the qubit to its original state (it essentially undoes itself)
# So we expect the unitary matrix to be the identity.
# We can access this information like so
# Credit to Chistopher J. Wood, lead Qiskit Aer developer: https://quantumcomputing.stackexchange.com/a/14283
from qiskit.quantum_info import Operator
op = Operator(qc)
op.data
# We can also see what happens to a qubit initialized to |0> when it goes through the unitary
from qiskit.quantum_info import Statevector
# .from_instruction automatically defaults to |0>
state_vec = Statevector.from_instruction(qc)
state_vec.data
# so we remain in the |0> state
# But a circuit that just ends up being an identity matrix is pretty boring. Why don't we make things more fun with our old friend the
# Hadamard gate?
# Lets create a new circuit and apply it:
qc = QuantumCircuit(1, 1)
qc.h(0)
qc.draw(output='mpl')
# Now lets see what the unitary is
Operator(qc).data
# And lets see what happens when we send in a qubit with |0>
state_vec = Statevector.from_instruction(qc)
state_vec.data
# Sometimes it's nice to visualize the states themselves
# We can always pull out our trusty bloch sphere for one qubit states:
# You'll see in a bit why it's called "plot_bloch_multivector"
# There IS a single plot_bloch_vector but it requires you to convert your state vector into
# cartesian/polar coordinates, which is a lot of unnecessary overhead for what we want to do
from qiskit.visualization import plot_bloch_multivector
plot_bloch_multivector(state_vec)
# This allows you to view the density matrix formulation,
# you can see the real and imaginary components of the density matrix
from qiskit.visualization import plot_state_city
plot_state_city(state_vec)
# now lets actually "run" our circuit
# In real world quantum computation, we know the only way to get useful information out of the quantum algorithm is to perform
# a measurement, which collapses the qubit state to one of two values.
# Let's go ahead and add a measurement to our circuit, telling Qiskit to store the result in the classical register
qc.measure(0,0)
qc.draw(output='mpl')
# You can either run your circuit on an ACTUAL quantum computer
# (which means you'll have to create an IBM Q account) or
# most of the time, you can run in on a simulator (which is what we'll do here).
from qiskit.providers.aer import AerSimulator
# There's a wide variety of simulators you can select, see: https://qiskit.org/documentation/stubs/qiskit.providers.aer.AerSimulator.html#qiskit.providers.aer.AerSimulator
# For the majority of purposes, statevector will do fine
backend = AerSimulator(method='statevector')
# shots defines how many times your circuit should run
job = backend.run(qc, shots=1024)
# Every time you run a circuit on a backend (real or simulated) you'll get a "Job"
# that you can then access results from
result = job.result()
# Here's the counts on each type of measurement
result.get_counts()
# we can also plot the probabilities via histogram
from qiskit.visualization import plot_histogram
plot_histogram(result.get_counts())
# You can also save the state of the quantum circuit AFTER running it on the simulators
# Let's add the following to our quantum circuit
qc.save_state() # <- you can save the statevector after running the experiment and view it later
job = backend.run(qc, shots=1024)
result = job.result()
result.get_statevector()
# not really that interesting
qc = QuantumCircuit(1,1)
qc.h(0)
# note that we can place the save state at an intermediate point as well!
qc.save_state()
qc.measure(0,0)
job = backend.run(qc, shots=1024)
result = job.result()
result.get_statevector()
# So far we've always started in |0>
# What if we want to start in some other initial state, like |1> or (|0> + |1>)/sqrt(2)?
# Qiskit lets us do that with ease!
# for a basis state we can do the following
qc = QuantumCircuit(1) # just for demonstration purposes, we don't need to create a classical register here
qc.initialize('1')
qc.draw(output='mpl')
# we can check it's |1> through the following:
Statevector.from_instruction(qc)
# For a non 0/1 basis state, (some kind of superposition perhaps) we can do the following
from numpy import sqrt
qc = QuantumCircuit(1) # just for demonstration purposes, we don't need to create a classical register here
qc.initialize([1j/sqrt(2), 1/sqrt(2)])
qc.draw(output='mpl')
Statevector.from_instruction(qc)
# You may want to build your own gates from matrices at some point
# Qiskit makes this a cinch with UnitaryGate
import numpy as np
custom_gate_matrix = np.eye(2) # 2x2 identity matrix
qc = QuantumCircuit(1)
from qiskit.extensions import UnitaryGate
custom_gate = UnitaryGate(custom_gate_matrix, label="Gate Name Here")
qc.append(custom_gate, [0])
qc.draw(output='mpl')
# The X, Y, and Z gates are all based on the Pauli matrices and are known for making rotations of pi radians around the bloch sphere
# on each respective axis.
# What if I want to rotate some fractional amount instead of pi?
# Each X,Y,Z gate has a version capable of accepting an argument theta that allows you to explicitly define the amount of rotation
# desired on any axis
qc = QuantumCircuit(1)
import numpy as np
qc.rx(np.pi/3, 0)
qc.draw(output='mpl')
state_vec = Statevector.from_instruction(qc)
plot_bloch_multivector(state_vec)
qc = QuantumCircuit(1)
import numpy as np
qc.ry(np.pi/3, 0)
qc.draw(output='mpl')
state_vec = Statevector.from_instruction(qc)
plot_bloch_multivector(state_vec)
qc = QuantumCircuit(1)
import numpy as np
qc.rz(np.pi/3, 0)
qc.draw(output='mpl')
state_vec = Statevector.from_instruction(qc)
plot_bloch_multivector(state_vec)
# We can create a two-qubit circuit
qc = QuantumCircuit(2,2)
# Single qubit gates can be applied as usual
qc.z(0)
qc.x(1)
# You can also apply two-qubit gates like so, with the first integer denoting the "control" qubit
# and the second denoting the target
qc.cx(0,1)
qc.draw(output='mpl')
# lets see what the statevector result looks like
state_vec = Statevector.from_instruction(qc)
state_vec
# The current state is separable and can be visualized with TWO bloch spheres
plot_bloch_multivector(state_vec)
# the statecity plot should also work
plot_state_city(state_vec)
# We can still obtain the unitary
Operator(qc).data
# And the syntax for running simulations does not change as well
## Let's add a measurement to the last operators
## For multiple measurements you can use the "measure_all" method
## If you declared the circuit with no quantum registers, like
## QuantumCircuit(2), measure_all will create classical registers automatically.
## If you declared something like QuantumCircuit(2,2) and classical reigsters ALREADY exist
## then you can invoke it with .measure_all(add_bits=False), otherwise, it'll continue to create
## extra classical registers which you don't need
qc.measure_all(add_bits=False)
qc.draw(output='mpl')
backend = AerSimulator(method='statevector')
job = backend.run(qc, shots=1024)
result = job.result()
plot_histogram(result.get_counts())
# You can still save the intermediate statevector as well
qc = QuantumCircuit(2,2)
# Single qubit gates can be applied as usual
qc.z(0)
qc.x(1)
qc.cx(0,1)
qc.save_statevector()
qc.measure_all(add_bits=False)
qc.draw(output='mpl')
backend = AerSimulator(method='statevector')
job = backend.run(qc, shots=1024)
result = job.result()
result.get_statevector()
# You can choose one qubit to initalize to a custom state:
qc = QuantumCircuit(2,2)
# Set qubit 0 to be in equal superposition
qc.initialize([1/sqrt(2), 1/sqrt(2)], 0)
qc.draw(output='mpl')
# You can also set the entire system to be in a certain state
qc = QuantumCircuit(2,2)
# Set the system to be in a Bell State, note that I don't have to state the qubits being targeted
# (Although in Qiskit examples, they'll usually be explicit with which qubits were selected)
qc.initialize([1/sqrt(2), 0, 0, 1/sqrt(2)])
qc.draw(output='mpl')
# For initalizations where you just want to pick between starting with |0> or |1> you can do the following:
qc = QuantumCircuit(2,2)
# Keep in mind this sets the SECOND qubit to 1, and the FIRST qubit to 0
qc.initialize("10")
qc.draw(output='mpl')
Statevector.from_instruction(qc)
# You can also just pass in an integer
qc = QuantumCircuit(2,2)
# Set qubit 0 to be in equal superposition
qc.initialize(3)
qc.draw(output='mpl')
Statevector.from_instruction(qc)
# create a quantum circuit to play around with
qc = QuantumCircuit(2)
# We create a custom gate
custom_gate = UnitaryGate(np.eye(2), label="Identity")
# Then we get the controlled version, with 1 qubit for control and the qubit in question needing to be in the |1> state to turn on
# the gate
controlled_custom_gate = custom_gate.control(num_ctrl_qubits=1, label="Controlled Identity")
# Add the gate
# The [0,1] here tells qiskit we want qubit 0 to be control, qubit 1 to be the target
qc.append(controlled_custom_gate, [0,1])
qc.draw(output='mpl')
# Note we can pass in ctrl_state as an integer OR as a string of 1s and 0s
controlled_custom_gate = custom_gate.control(num_ctrl_qubits=1, ctrl_state=0, label="Controlled Identity")
qc.append(controlled_custom_gate, [0,1])
qc.draw(output='mpl')
## When an entangled state is created, by definition it is NON-SEPERABLE
## (you cannot split the vector that constitutes it into two separate vectors).
## This does put a wrench into visualization but only partly.
## Observe the following Bell state generating circuit
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0,1)
qc.draw(output='mpl')
# We get the statevector
state_vec = Statevector.from_instruction(qc)
# and try to visualize it...
plot_bloch_multivector(state_vec)
# BEHOLD! You don't get anything
# This is generally the case whenever you run into entanglement, Qiskit will fail to properly display seperate bloch spheres (because it's impossible!)
# You may also still get "something" but the vector is shorter or significantly longer than what it should be (visually)
# However, the Density Matrix can give you more information....
# But we still have one way of seeing things, the state city diagram
plot_state_city(state_vec)
## You can actually figure out if a system has some degree of entanglment by using the trace and reducing the degrees of freedom to individual qubits
## Credit to "Quantum Mechanic" on Stack Overflow https://quantumcomputing.stackexchange.com/questions/17580/how-to-calculate-the-amount-of-entanglement-for-each-qubit-in-a-quantum-computer
# We can define even larger circuits...
qc = QuantumCircuit(5,5)
# apply some single qubit gates
qc.rz(np.pi/8, 1)
qc.z(0)
qc.y(3)
qc.x(2)
# apply a CCX or Toffoli gate with 0 and 1 as control qubits, 2 as the target qubit
qc.ccx(0,1,2)
# apply a controlled swap gate
qc.cswap(2,3,4)
qc.draw(output='mpl')
# lets see what the statevector result looks like
state_vec = Statevector.from_instruction(qc)
state_vec
# can still see what the unitary matrix looks like
unitary_mat = Operator(qc)
unitary_mat
# Should be able to visualize all the qubits too!
plot_bloch_multivector(state_vec)
# Should be able to visualize all the qubits too!
plot_state_city(state_vec)
# Rules for simulation remain the same
## Add measurement gets
qc.measure_all(add_bits=False)
job = backend.run(qc, shots=1024)
result = job.result()
plot_histogram(result.get_counts())
# We can still initialize our circuits to custom states
qc = QuantumCircuit(5,5)
qc.initialize(4) # initialized to |00100>
qc.draw(output='mpl')
Statevector.from_instruction(qc)
# Now that we have all these extra qubits, we can do some pretty crazy stuff with defining controlled gates.
# For example, lets say we want a controlled X gate that only applies when the control qubits have the state "0011"
# In such a case we can just piggyback off of the fact that Qiskit already has an X gate and build up from it
from qiskit.circuit.library import XGate
# keep in mind that the ordering is flipped for qubits in qiskit!
custom_controlled_X = XGate().control(num_ctrl_qubits=4, ctrl_state="0011", label="Crazy Controlled X")
qc = QuantumCircuit(5)
qc.append(custom_controlled_X, [0,1,2,3,4])
qc.draw(output='mpl')
# Let's test the circuit.
# We expect that for any other initialized state, nothing should happen and the initialied state stays as is
qc = QuantumCircuit(5)
qc.initialize(0)
qc.append(custom_controlled_X, [0,1,2,3,4])
Statevector.from_instruction(qc)
plot_bloch_multivector(Statevector.from_instruction(qc))
# ...and if we set the initial state right then the gate gets applied
qc = QuantumCircuit(5)
qc.initialize("00011")
qc.append(custom_controlled_X, [0,1,2,3,4])
Statevector.from_instruction(qc)
plot_bloch_multivector(Statevector(qc))
# Note that we flipped qubit 4, the one we wanted to target!
# Sometimes you'll find that it's easier when building custom gates to go ahead and build it out in a separate circuit and then treat
# that circuit as a whole gate entirely (kind of like when you write a large computer program and you call multiple functions,
# or when you have a long essay with lots of individual paragraphs you work on)
# We can do that like so (taken from https://qiskit.org/documentation/tutorials/circuits_advanced/01_advanced_circuits.html#Composite-Gates
# slightly modified for this tutorial)
sub_circ = QuantumCircuit(2, name='sub_circ')
sub_circ.h(0)
# theta is set to 1, with control qubit 0 and target 1
sub_circ.crz(1,0,1)
# A barrier is usually used as a way to explicitly split up certain parts of the circuit for visual purposes
# in most tutorials, although it actually has a role in telling the transpiler not to optimize
# "The barrier acts as a directive for circuit compilation to separate pieces of a circuit so that any optimizations or
# This only comes into play when using the transpile or execute functions in Qiskit (execute includes a transpile step)."
# re-writes are constrained to only act between barriers (and if there are no barriers they act on the whole circuit). - Christopher J. Wood, Lead Developer for Qiskit Aer
sub_circ.barrier()
sub_circ.id(1)
# The U gate takes several parameters and is a kind of universal gate capable of performing a rotation in ANY direction
sub_circ.u(1,2,-2,0)
sub_circ.draw(output='mpl')
# Convert to a gate and stick it into an arbitrary place in the bigger circuit
sub_inst = sub_circ.to_instruction()
qc = QuantumCircuit(3)
qc.h(0)
qc.cx(0,1)
qc.cx(1,2)
qc.append(sub_inst, [1,2])
qc.draw(output='mpl')
# register naming code obtained from:
# https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate
# credits to Ali Javadi for their answer
# label our qubits
# Note that you can also explicitly declare your Quantum and Classical Registers as separate entities and then
# initialize a QuantumCircuit with them, although QuantumCircuit(n,m) will do just fine as well if you don't care much for register labeling
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
n = 3
function_inputs = QuantumRegister(n, "x")
target = QuantumRegister(1, "f(x)")
# store our results here
classical_registers = ClassicalRegister(3)
circuit = QuantumCircuit(function_inputs, target, classical_registers)
# Initialization phase
# apply Hadamards to three qubits
circuit.h(0)
circuit.h(1)
circuit.h(2)
# Get the last hadamard in the kickback position
circuit.x(3)
circuit.h(3)
circuit.draw(output="mpl")
# visualize the current state after execution
plot_bloch_multivector(Statevector.from_instruction(circuit))
circuit.barrier()
circuit.draw(output='mpl')
# Create an Oracle
# In this case, we want to solve for (x0 AND x1 AND x2)
# Note that when the circuit actually gets run on hardware, the gate actually gets
# broken down into smaller gates (so this one may get broken down in CCX gates, and even further
# to CX and other single qubit gates) that are native to the hardware (the hardware
# may only support
# a certain subset of gates, although that subset is capable of generating any other
# gate's operations
# Inspiration for Oracle from: https://cnot.io/quantum_algorithms/grover/grovers_algorithm.html
# as well as Ryan LaRose's QuIC Seminar notes on Grover's Algorithm:
# https://www.ryanlarose.com/uploads/1/1/5/8/115879647/grover.pdf
circuit.mcx([0,1,2],3)
circuit.draw(output="mpl")
# oracle complete, put the barrier down
circuit.barrier()
circuit.draw(output="mpl")
# Oracle implementation taken from Eric Li (https://you.stonybrook.edu/qcomputing/2018/07/18/2-3-qubit-grovers-algorithm/)
# and Martin Vesely (https://quantumcomputing.stackexchange.com/questions/9531/grover-diffusion-operator-for-a-3-qubit-system)
for i in range(3):
circuit.h(i)
# 2|0><0| - I
for i in range(3):
circuit.x(i)
circuit.h(2)
circuit.mcx([0,1],2)
circuit.h(2)
for i in range(3):
circuit.x(i)
for i in range(3):
circuit.h(i)
circuit.barrier()
circuit.draw(output="mpl")
# get results
# .measure_all fails here because there isn't an equal number of classical regsiters, so we have to resort to the next best thing
# circuit.measure_all(add_bits=False)
# Need to explicitly declare which quantum bit gets measured to which classical bit
circuit.measure([0,1,2],[0,1,2])
backend = AerSimulator(method='statevector')
job = backend.run(circuit, shots=1024)
result = job.result()
plot_histogram(result.get_counts())
# Create a custom gate representing the oracle
from qiskit.circuit.library import MCXGate
oracle = MCXGate(num_ctrl_qubits=3, label="oracle", ctrl_state="111")
# create a custom gate representing the diffusion operator
grover_op_circ = QuantumCircuit(3, name="Grover's Operator")
for i in range(3):
grover_op_circ.h(i)
# 2|0><0| - I
for i in range(3):
grover_op_circ.x(i)
grover_op_circ.h(2)
grover_op_circ.mcx([0,1],2)
grover_op_circ.h(2)
for i in range(3):
grover_op_circ.x(i)
for i in range(3):
grover_op_circ.h(i)
# Now rebuild the original circuit using our newly defined custom gates
n = 3
function_inputs = QuantumRegister(n, "x")
target = QuantumRegister(1, "f(x)")
# store our results here
classical_registers = ClassicalRegister(3)
qc = QuantumCircuit(function_inputs, target, classical_registers)
# apply Hadamards to three qubits
qc.h(0)
qc.h(1)
qc.h(2)
# Get the last hadamard in the kickback position
qc.x(3)
qc.h(3)
qc.barrier()
qc.append(oracle, [0,1,2,3])
qc.barrier()
qc.append(grover_op_circ.decompose(), [0,1,2])
qc.draw(output='mpl')
# now we apply the same things again
qc.barrier()
qc.append(oracle, [0,1,2,3])
qc.barrier()
qc.append(grover_op_circ.to_instruction(), [0,1,2])
qc.draw(output='mpl')
# Now let's see how the results hold up
qc.measure([0,1,2],[0,1,2])
backend = AerSimulator(method='statevector')
job = backend.run(qc.decompose(), shots=1024)
result = job.result()
plot_histogram(result.get_counts())
qc.draw(output='mpl')
# Create Sqrt iSWAP gate
from qiskit.circuit.library import ZGate
# Obtained from: https://github.com/quantumlib/Cirq/blob/a22269dfe41b0da78243bbd210a915d26cc7d25f/cirq-core/cirq/ops/swap_gates.py#L166
sqrt_iSWAP_circ = QuantumCircuit(2, name="sqrt(iSWAP)")
sqrt_iSWAP_circ.cx(0,1)
sqrt_iSWAP_circ.h(0)
sqrt_iSWAP_circ.cx(1,0)
sqrt_iSWAP_circ.append(ZGate().power(0.25), [0])
sqrt_iSWAP_circ.cx(1,0)
sqrt_iSWAP_circ.append(ZGate().power(-0.25), [0])
sqrt_iSWAP_circ.h(0)
sqrt_iSWAP_circ.cx(0,1)
sqrt_iSWAP_circ.draw(output='mpl')
# Create the full IonQ supported Given's Rotation
from qiskit.circuit import Parameter
import numpy as np
# You can create a Parameter that you later bind values to during execution
theta = Parameter('θ')
givens_circ = QuantumCircuit(2, name="Givens Rotation")
givens_circ.append(sqrt_iSWAP_circ.to_instruction(), [0,1])
givens_circ.rz(-theta, 0)
givens_circ.rz(theta + np.pi, 1)
givens_circ.append(sqrt_iSWAP_circ.to_instruction(), [0,1])
givens_circ.rz(np.pi, 1)
givens_circ.draw(output='mpl')
print(givens_circ.parameters)
# Full simulation
qc = QuantumCircuit(2)
# Initialize the circuit to be a full, even superpositon (equivalent of putting two hadamards)
full_superposition = [1/np.sqrt(4)] * 4
qc.initialize(full_superposition)
qc.append(givens_circ.bind_parameters({theta: np.pi/3}).to_instruction(), [0,1])
qc.draw(output='mpl')
# hmmm, close but not quite right
np.round(Statevector.from_instruction(qc).data.reshape(4,1), 3)
# taken from https://medium.com/mdr-inc/checking-the-unitary-matrix-of-the-quantum-circuit-on-qiskit-5968c6019a45
# All credit to Yuchiro Minato
from qiskit import Aer, execute
# The Unitary simulator only works with circuits that have NO MEASUREMENT GATES
# but allows you to get the unitary representing the matrix.
# Operator() fails to work if your circuit contains a custom initialization value
backend = Aer.get_backend('unitary_simulator')
job = execute(qc, backend)
result = job.result()
print(result.get_unitary(qc, decimals=3))
# This unitary comes from the correct implementation from: https://github.com/QC-at-Davis/GroveFold/blob/feature/vectoradditionfrombiomoleculesusingbiopython/src/scripts/IonQ-Givens-Cirq-Simulation.ipynb
# (literally copied and pasted here, then converted back into a matrix)
x =np.array([[-1. -1.34015774e-16j, 0. +0.00000000e+00j,
0. +0.00000000e+00j, 0. -3.72797834e-17j],
[ 0. +0.00000000e+00j, -0.5 -5.88784672e-17j,
0.8660254+1.17756934e-16j, 0. +0.00000000e+00j],
[ 0. +0.00000000e+00j, -0.8660254+5.88784672e-17j,
-0.5 +1.96261557e-16j, 0. +0.00000000e+00j],
[ 0. -2.29934717e-17j, 0. -0.00000000e+00j,
0. -0.00000000e+00j, -1. +3.51298275e-16j]])
# Note certain entries seem to be flipped...
np.round(x, 3)
y = np.array([1/sqrt(4)] * 4).reshape(4, 1)
x @ y
|
https://github.com/Antonio297/Qiskit_Algoritmo_Cuantico
|
Antonio297
|
### Original articles:
###
### (1) "Improving the Sequence Alignment Method by Quantum Multi-Pattern Recognition"
### Konstantinos Prousalis & Nikos Konofaos
### Published in: SETN '18 Proceedings of the 10th Hellenic Conference on Artificial Intelligence, Article No. 50
### Patras, Greece, July 09 - 12, 2018
###
### (2) "Quantum Pattern Recognition with Probability of 100%"
### Rigui Zhou & Qiulin Ding
### Published in: International Journal of Theoretical Physics, Springer
### Received: 3 August 2007, Accepted: 11 September 2007, Published online: 4 October 2007
###
### (3) "Initializing the amplitude distribution of a quantum state"
### Dan Ventura & Tony Martinez
### Revised 2nd November 1999
## Importing libraries
%matplotlib inline
import qiskit
from qiskit import IBMQ
from qiskit import Aer
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, QiskitError
from qiskit.quantum_info.operators import Operator
from qiskit.tools.visualization import circuit_drawer
from qiskit.tools.visualization import plot_histogram
from qiskit.tools.visualization import plot_state_city
from qiskit.providers.aer import noise
import random
from math import *
import math
import matplotlib
import numpy as np
## Initializing global variables
# Quantum register is organized like the following:
# |t, x, g, c, a>, with (t+x) having n qubits (index+pattern), g having (n-1) qubits and c having 2 qubits
# Also, ancilla qubits (a) as support for mct gate
genome_file = open("Cromosoma 1-Covid 19.txt", "r") #select the data source
seq_x = genome_file.read()
genome_file.close()
seq_x = seq_x[0:200] #changes the number of characters you want to read from the file
seq_y = "TTCT" #string to compare (endonuclease recognition sequence)
Q_t = ceil(log2(len(seq_x)))
Q_x = len(seq_y)
Q_g = Q_t + Q_x - 1
Q_c = 2
Q_anc = 1
total_qubits = Q_t + Q_x + Q_g + Q_c + Q_anc
## Initialization of IBM QX
IBMQ.enable_account('My Token')
provider = IBMQ.get_provider()
# Pick an available backend
# If this isn't available pick a backend whose name containes '_qasm_simulator' from the output above
backend = provider.get_backend('ibmq_qasm_simulator')
# Uncomment if you want to use local simulator
#backend= Aer.get_backend('qasm_simulator')
## Functions for recurrence dot matrix
def delta(x, y):
return 0 if x == y else 1
def M(seq1, seq2, i, j, k):
return sum(delta(x, y) for x, y in zip(seq1[i : i+k],seq2[j : j+k]))
def makeMatrix(seq1, seq2, k):
n = len(seq1)
m = len(seq2)
return [[M(seq1, seq2, i, j, k) for j in range(m - k + 1)] for i in range(n - k + 1)]
def plotMatrix(M, t, seq1, seq2, nonblank = chr(0x25A0), blank = ' '):
print(' |' + seq2)
print('-' * (2 + len(seq2)))
for label, row in zip(seq1, M):
line = ''.join(nonblank if s < t else blank for s in row)
print(label + '|' + line)
return
def convertMatrix(M):
for i in range(0, len(M)):
for j in range(0, len(M[i])):
if M[i][j] == 0:
M[i][j] = 1
elif M[i][j] == 1:
M[i][j] = 0
return M
def dotplot(seq1, seq2, k = 1, t = 1):
if len(seq1) > len(seq2):
raise Exception("Vertical sequence cannot be longer than horizontal sequence!")
M = makeMatrix(seq1, seq2, k)
plotMatrix(M, t, seq1, seq2)
M = convertMatrix(M)
return M
def getAllDiagonalsFromMatrix(M):
D = np.array([])
d_size = -1
for i in range(0, len(M[0])):
d = np.diag(M, k=i)
if d_size == -1:
d_size = len(d)
D = d
elif d_size > len(d):
z = np.zeros((1, (d_size-len(d))), dtype=int)
d = np.append(d, z)
D = np.vstack((D, d))
else:
D = np.vstack((D, d))
return D
def convertBinArrayToStr(array):
string = ""
for bin_digit in array:
if bin_digit == 0:
string = string + '0'
elif bin_digit == 1:
string = string + '1'
return string
## Functions for Quantum Pattern Recognition
def generateInitialState(qc, qr, dot_matrix):
D = getAllDiagonalsFromMatrix(dot_matrix)
m = len(D)
print("Size of Learning Set: {}".format(len(D)))
idx = 0
for d in D:
print("{}->{}: {}".format(idx, format(idx,'0'+str(Q_t)+'b'), d))
idx = idx + 1
z_values = convertBinArrayToStr(np.zeros(Q_t+Q_x))
ancilla_qubits = []
for qi in range(0, Q_anc):
ancilla_qubits.append(qr[Q_t + Q_x + Q_g + Q_c + qi])
for p in range(m, 0, -1):
bin_diagonal = convertBinArrayToStr(D[len(D)-p])
index = format((len(D)-p), '0' + str(Q_t) + 'b')
instance = index + bin_diagonal
#print("Instance #{}, z={}".format(p, instance))
for j in range(1, Q_t + Q_x + 1):
if z_values[j-1] != instance[j-1]:
#print("F_0 #{} Applied to circuit with ctrl={} and target={}".format(j, Q_t+Q_x+Q_g+Q_c-1,j-1))
qc.x(qr[Q_t+Q_x+Q_g+Q_c-1])
qc.cx(qr[Q_t+Q_x+Q_g+Q_c-1], qr[j-1])
qc.x(qr[Q_t+Q_x+Q_g+Q_c-1])
z_values = instance
#print("F_0 Applied to circuit with ctrl={} and arget={}".format(Q_t+Q_x+Q_g+Q_c-1, Q_t+Q_x+Q_g+Q_c-2))
qc.x(qr[Q_t+Q_x+Q_g+Q_c-1])
qc.cx(qr[Q_t+Q_x+Q_g+Q_c-1], qr[Q_t+Q_x+Q_g+Q_c-2])
qc.x(qr[Q_t+Q_x+Q_g+Q_c-1])
#print("S_{},{} Applied to circuit with ctrl={} and arget={}".format(1, p, Q_t+Q_x+Q_g+Q_c-2, Q_t+Q_x+Q_g+Q_c-1))
theta = 2*np.arcsin(1/sqrt(p))
qc.cry(theta, qr[Q_t+Q_x+Q_g+Q_c-2], qr[Q_t+Q_x+Q_g+Q_c-1])
if instance[0]=='0' and instance[1]=='0':
#print("A_00 #1 Applied to circuit with ctrl={},{} and target={}".format(0, 1, Q_t+Q_x))
qc.x(qr[0])
qc.x(qr[1])
qc.mct([qr[0], qr[1]], qr[Q_t+Q_x], ancilla_qubits)
qc.x(qr[1])
qc.x(qr[0])
elif instance[0]=='0' and instance[1]=='1':
#print("A_01 #1 Applied to circuit with ctrl={},{} and target={}".format(0, 1, Q_t+Q_x))
qc.x(qr[0])
qc.mct([qr[0], qr[1]], qr[Q_t+Q_x], ancilla_qubits)
qc.x(qr[0])
elif instance[0]=='1' and instance[1]=='0':
#print("A_10 #1 Applied to circuit with ctrl={},{} and target={}".format(0, 1, Q_t+Q_x))
qc.x(qr[1])
qc.mct([qr[0], qr[1]], qr[Q_t+Q_x], ancilla_qubits)
qc.x(qr[1])
elif instance[0]=='1' and instance[1]=='1':
#print("A_11 #1 Applied to circuit with ctrl={},{} and target={}".format(0, 1, Q_t+Q_x))
qc.mct([qr[0], qr[1]], qr[Q_t+Q_x], ancilla_qubits)
for k in range(3, Q_t+Q_x+1):
if instance[k-1]=='0':
#print("A_01 #{} Applied to circuit with ctrl={},{} and target={}".format(k-1, k-1, Q_t+Q_x+k-3, Q_t+Q_x+k-2))
qc.x(qr[k-1])
qc.mct([qr[k-1], qr[Q_t+Q_x+k-3]], qr[Q_t+Q_x+k-2], ancilla_qubits)
qc.x(qr[k-1])
elif instance[k-1]=='1':
#print("A_11 #{} Applied to circuit with ctrl={},{} and target={}".format(k-1, k-1, Q_t+Q_x+k-3, Q_t+Q_x+k-2))
qc.mct([qr[k-1], qr[Q_t+Q_x+k-3]], qr[Q_t+Q_x+k-2], ancilla_qubits)
#print("F_1 Applied to circuit with ctrl={} and target={}".format(Q_t+Q_x+Q_g-1, Q_t+Q_x+Q_g))
qc.cx(qr[Q_t+Q_x+Q_g-1], qr[Q_t+Q_x+Q_g])
for k in range(Q_t+Q_x, 2, -1):
if instance[k-1]=='0':
#print("A_01 #{} Applied to circuit with ctrl={},{} and target={}".format(k-1, k-1, Q_t+Q_x+k-3, Q_t+Q_x+k-2))
qc.x(qr[k-1])
qc.mct([qr[k-1], qr[Q_t+Q_x+k-3]], qr[Q_t+Q_x+k-2], ancilla_qubits)
qc.x(qr[k-1])
elif instance[k-1]=='1':
#print("A_11 #{} Applied to circuit with ctrl={},{} and target={}".format(k-1, k-1, Q_t+Q_x+k-3, Q_t+Q_x+k-2))
qc.mct([qr[k-1], qr[Q_t+Q_x+k-3]], qr[Q_t+Q_x+k-2], ancilla_qubits)
if instance[0]=='0' and instance[1]=='0':
#print("A_00 #1 Applied to circuit with ctrl={},{} and target={}".format(0, 1, Q_t+Q_x))
qc.x(qr[0])
qc.x(qr[1])
qc.mct([qr[0], qr[1]], qr[Q_t+Q_x], ancilla_qubits)
qc.x(qr[1])
qc.x(qr[0])
elif instance[0]=='0' and instance[1]=='1':
#print("A_01 #1 Applied to circuit with ctrl={},{} and target={}".format(0, 1, Q_t+Q_x))
qc.x(qr[0])
qc.mct([qr[0], qr[1]], qr[Q_t+Q_x], ancilla_qubits)
qc.x(qr[0])
elif instance[0]=='1' and instance[1]=='0':
#print("A_10 #1 Applied to circuit with ctrl={},{} and target={}".format(0, 1, Q_t+Q_x))
qc.x(qr[1])
qc.mct([qr[0], qr[1]], qr[Q_t+Q_x], ancilla_qubits)
qc.x(qr[1])
elif instance[0]=='1' and instance[1]=='1':
#print("A_11 #1 Applied to circuit with ctrl={},{} and target={}".format(0, 1, Q_t+Q_x))
qc.mct([qr[0], qr[1]], qr[Q_t+Q_x], ancilla_qubits)
#print("F Applied to circuit at qubit={}".format(Q_t+Q_x+Q_g+Q_c-1))
qc.x(qr[Q_t+Q_x+Q_g+Q_c-1])
return
def getIndices(mySet):
indices = []
for i in range(0, len(mySet)):
tmp = ""
for j in range(0, len(mySet[i])):
tmp = tmp + str(int(mySet[i][j]))
indices.append(int(tmp, 2))
return indices
def oracle(query_set):
I = np.identity(2**Q_x)
b_sum = np.zeros((2**Q_x, 2**Q_x))
indices = getIndices(query_set)
for i in indices:
vs = np.zeros((1, 2**Q_x))
for j in range(0, 2**Q_x):
if j == i:
vs[0][j] = 1
b_sum = b_sum + np.dot(np.conjugate(np.transpose(vs)), vs)
U = I - (1-1j)*b_sum
return U
def inversionAboutMean(dot_matrix):
I = np.identity(2**(Q_t+Q_x))
b_sum = np.zeros((2**(Q_t+Q_x), 1))
D = getAllDiagonalsFromMatrix(dot_matrix)
mySet = np.empty([len(D), Q_t+Q_x])
for i in range(0, len(D)):
bin_arr = np.concatenate((convertIntToBinArray(i, Q_t), D[i]))
mySet[i] = bin_arr
indices = getIndices(mySet)
for i in indices:
vs = np.zeros((2**(Q_t+Q_x), 1))
for j in range(0, 2**(Q_t+Q_x)):
if j == i:
vs[j][0] = 1
b_sum = b_sum + vs
phi_zero = (1/sqrt(len(D))) * b_sum
phi_mtrx = np.dot(phi_zero, np.conjugate(np.transpose(phi_zero)))
U = (1 + 1j) * phi_mtrx - 1j * I
return U
def convertIntToBinArray(j, dim):
if not isinstance(j, int):
raise Exception("Number of bits must be an integer!")
elif (j == 0 or j == 1) and dim < 1:
raise Exception("More bits needed to convert j in binary!")
elif j > 1 and dim <= log2(j):
raise Exception("More bits needed to convert j in binary!")
bin_arr = np.array([], dtype=int)
j_bin = format(int(j), '0' + str(dim) + 'b')
for k in j_bin:
if k == '1':
bin_arr = np.append(bin_arr, 1)
elif k == '0':
bin_arr = np.append(bin_arr, 0)
return bin_arr
def QPR(dot_matrix):
qr = qiskit.QuantumRegister(total_qubits)
cr = qiskit.ClassicalRegister(Q_t)
qc = qiskit.QuantumCircuit(qr, cr)
print("Total number of qubits: {}".format(total_qubits))
print("Size of t register: {}".format(Q_t))
print("Size of x register: {}".format(Q_x))
print("Size of g register: {}".format(Q_g))
print("Size of c register: {}".format(Q_c))
print("Number of ancilla qubits: {}".format(Q_anc))
# A query set is manually defined
query_set = np.array([[1,1,1],
[0,1,1],
[1,1,0],
[1,0,1]])
O_mtrx = oracle(query_set)
U_phi_mtrx = inversionAboutMean(dot_matrix)
O = Operator(O_mtrx)
U_phi = Operator(U_phi_mtrx)
O_qubits = []
for qi in range(Q_x-1, -1, -1):
O_qubits.append(Q_t + qi)
U_phi_qubits = []
for qi in range(Q_t+Q_x-1, -1, -1):
U_phi_qubits.append(qi)
generateInitialState(qc, qr, dot_matrix)
#simulateStateVector(qc)
T = round((math.pi/4)*sqrt(len(dot_matrix[0])/len(query_set)))
it = 0
for i in range(0, T):
print("Grover Iteration #{}".format(it+1))
qc.unitary(O, O_qubits, label='O')
#simulateStateVector(qc)
#qc.unitary(U_phi, U_phi_qubits, label='U_phi')
#simulateStateVector(qc)
it = it + 1
print("Grover's algorithm had {} iterations.".format(int(it)))
finalGroverMeasurement(qc, qr, cr)
return qc
def simulateStateVector(qc):
result = qiskit.execute(qc, backend=Aer.get_backend('statevector_simulator')).result()
state = result.get_statevector(qc)
print("Number of states in vector: {}".format(len(state)))
it = 0
for item in state:
bin_str = format(it, '0'+str(total_qubits)+'b')
bin_str_rev = bin_str[len(bin_str)::-1]
if (item.real != 0 or item.imag != 0):
print("{}->{}: {}".format(it, bin_str_rev[Q_t:Q_t+Q_x], item))
it = it + 1
return
# Final measurement
def finalGroverMeasurement(qc, qr, cr):
for qi in range(0, Q_t):
qc.measure(qr[qi], cr[qi])
return
## Main function
if __name__ == '__main__':
# Printing some data for testing
M = dotplot(seq_y, seq_x)
qc = QPR(M)
print("Circuit depth: {}".format(qc.depth()))
# Total number of gates
print("Number of gates: {}".format(len(qc.data)))
gate_num = 1
for item in qc.data:
qb_list = ""
for qb in item[1]:
qb_list = qb_list + str(qb.index) + ", "
qb_list = qb_list[:len(qb_list)-2]
print("#{}: {}, {}".format(gate_num, item[0].name, qb_list))
gate_num = gate_num + 1
# Drawing circuit
qc.draw()
# Showing histogram
# BE CAREFUL!
# Qiskit uses a LSB ordering, meaning the first qubit is all the way to the right!
# For example, a state of |01> would mean the first qubit is 1 and the second qubit is 0!
sim = qiskit.execute(qc, backend=backend, shots=1024)
result = sim.result()
final=result.get_counts(qc)
print(final)
plot_histogram(final)
|
https://github.com/Antonio297/Qiskit_Algoritmo_Cuantico
|
Antonio297
|
### Quantum indexed Bidirectional Associative Memory by A. Sarkar, Z. Al-Ars, C. G. Almudever, K. Bertels
### Repository reference: https://gitlab.com/prince-ph0en1x/QaGs (by A. Sarkar)
## Importing libraries
%matplotlib inline
import qiskit
from qiskit import IBMQ
from qiskit import Aer
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, QiskitError
from qiskit.quantum_info.operators import Operator
from qiskit.tools.visualization import circuit_drawer
from qiskit.tools.visualization import plot_histogram
from qiskit.providers.aer import noise
from qiskit.providers.aer.noise import NoiseModel, errors
import random
from math import *
import os
import re
import sys
import math
import matplotlib.pyplot as plt
import numpy as np
## Defining some auxiliary functions
def hamming_distance(str1, str2):
count = sum(c1 != c2 for c1, c2 in zip(str1, str2))
return count
def convertToNumEncoding(genome_str):
bin_str = ""
for i in range(0, len(genome_str)):
if genome_str[i] == 'A':
bin_str = bin_str + "0"
elif genome_str[i] == 'C':
bin_str = bin_str + "1"
elif genome_str[i] == 'G':
bin_str = bin_str + "2"
elif genome_str[i] == 'T':
bin_str = bin_str + "3"
return bin_str
def convertReadToBin(read):
bin_read = ""
for i in range(0, len(read)):
if read[i] == '0':
bin_read = bin_read + "00"
elif read[i] == '1':
bin_read = bin_read + "01"
elif read[i] == '2':
bin_read = bin_read + "10"
elif read[i] == '3':
bin_read = bin_read + "11"
return bin_read
## Initializing global variables
# Alphabet set {0, 1, 2, 3} := {A, C, G, T} for DNA Nucleotide bases
AS = {'00', '01', '10', '11'}
A = len(AS)
################# Default Test #################
# Reference Genome: "AATTGTCTAGGCGACC"
#w = "0033231302212011"
#N = len(w)
# Short Read: "CA"
#p = "10"
# Distributed query around zero Hamming distance
#pb = "0000"
################################################
############## Test on HIV genome ##############
genome_file = open("HIVgenome.txt", "r") #select the data source
w = genome_file.read()
genome_file.close()
w = convertToNumEncoding(w)
w = w[0:128] #changes the number of characters you want to read from the file
N = len(w)
# Short read: "TCT" #Try with chains of three
p = "313"
# Distributed query around zero Hamming distance
pb = "000000"
################################################
# Short Read size
M = len(p)
# Number of qubits to encode one character
Q_A = ceil(log2(A))
# Number of data qubits
Q_D = Q_A * M
# Tag Qubits
Q_T = ceil(log2(N-M))
#print('valor Q_T:',Q_T)
# Ancilla Qubits
Q_anc = 8
# Ancilla qubits ids
anc = []
for qi in range(0, Q_anc):
anc.append(Q_D + Q_T + qi)
total_qubits = Q_D + Q_T + Q_anc
## Inizializing Oracle O Matrix
gamma = 0.25
SS = 2**Q_D
bp = np.empty([1, SS])
for i in range(0, SS):
i_binary = format(i, '0'+str(Q_D)+'b')
hd = hamming_distance(i_binary, pb)
bp[0][i] = sqrt((gamma**hd)*((1 - gamma)**(Q_D - hd)))
BO = np.identity(SS) - 2*np.dot(np.conjugate(np.transpose(bp)), bp)
orc = Operator(BO)
qbsp = []
for qi in range (0, Q_D):
qbsp.append(Q_T+qi)
qbsp.reverse()
## Initialization of IBM QX
IBMQ.enable_account('My Token')
provider = IBMQ.get_provider()
# Pick an available backend
# If this isn't available pick a backend whose name containes '_qasm_simulator' from the output above
backend = provider.get_backend('ibmq_qasm_simulator')
# Uncomment if you want to use local simulator
#backend= Aer.get_backend('qasm_simulator')
## Defining functions
def QIBAM():
print('Reference genome:', w)
print('Chosen pattern for testing:', p)
print('Total number of qubits:', total_qubits)
print('Number of ancilla qubits:', Q_anc)
qr = qiskit.QuantumRegister(total_qubits)
cr = qiskit.ClassicalRegister(Q_T)
qc = qiskit.QuantumCircuit(qr, cr)
# Initialise
generateInitialState(qc, qr)
# Transform to Hamming distance
evolveToHammingDistances(qc, qr)
# Oracle call
oracle(qc)
# Inversion about mean
inversionAboutMean(qc, qr)
it = 0
for r in range(0, 2):
# Oracle call
oracle(qc)
# Inversion about mean
inversionAboutMean(qc, qr)
it = it + 1
print("Grover's algorithm had {} iterations.".format(int(it)))
# Measurement
finalGroverMeasurement(qc, qr, cr)
return qc
# Initialization as suggested by L. C. L. Hollenberg
def generateInitialState(qc, qr):
for qi in range(0, Q_T):
qc.h(qr[qi])
control_qubits = []
for ci in range(0,Q_T):
control_qubits.append(qr[ci])
ancilla_qubits = []
for qi in anc:
ancilla_qubits.append(qr[qi])
for qi in range(0, N - M + 1):
qis = format(qi, '0' + str(Q_T) + 'b')
for qisi in range(0, Q_T):
if qis[qisi] == '0':
qc.x(qr[qisi])
wMi = w[qi:qi + M]
print("Tag: {} - Data: {} - Hamming distance: {}".format(qis, wMi, hamming_distance(convertReadToBin(wMi), convertReadToBin(p))))
for wisi in range(0, M):
wisia = format(int(wMi[wisi]), '0' + str(Q_A) + 'b')
for wisiai in range(0, Q_A):
if wisia[wisiai] == '1':
qc.mct(control_qubits, qr[Q_T + wisi * Q_A + wisiai], ancilla_qubits)
for qisi in range(0, Q_T):
if qis[qisi] == '0':
qc.x(qr[qisi])
wMi = p
for qi in range(N - M + 1, 2**Q_T):
qis = format(qi, '0' + str(Q_T) + 'b')
for qisi in range(0, Q_T):
if qis[qisi] == '0':
qc.x(qr[qisi])
for wisi in range(0, M):
wisia = format(int(wMi[wisi]), '0' + str(Q_A) + 'b')
for wisiai in range(0, Q_A):
if wisia[wisiai] == '0':
qc.mct(control_qubits, qr[Q_T + wisi * Q_A + wisiai], ancilla_qubits)
for qisi in range(0, Q_T):
if qis[qisi] == '0':
qc.x(qr[qisi])
return
# Calculate Hamming Distance
def evolveToHammingDistances(qc, qr):
for pi in range(0, M):
ppi = format(int(p[pi]), '0' + str(Q_A) + 'b')
for ppii in range(0, Q_A):
if ppi[ppii] == '1':
qc.x(qr[Q_T + pi * Q_A + ppii])
return
# Oracle to mark zero Hamming distance
def oracle(qc):
qc.unitary(orc, qbsp, label='orc')
return
# Inversion about mean
def inversionAboutMean(qc, qr):
for si in range(0, Q_D + Q_T):
qc.h(qr[si])
qc.x(qr[si])
control_qubits = []
for sj in range(0, Q_D + Q_T - 1):
control_qubits.append(qr[sj])
ancilla_qubits = []
for qi in anc:
ancilla_qubits.append(qr[qi])
qc.h(qr[Q_D + Q_T - 1])
qc.mct(control_qubits, qr[Q_D + Q_T - 1], ancilla_qubits)
qc.h(qr[Q_D + Q_T - 1])
for si in range(0,Q_D + Q_T):
qc.x(qr[si])
qc.h(qr[si])
return
# Oracle to mark Memory States
def markStoredStates(qc, qr):
control_qubits = []
for qsi in range(0, Q_T + Q_D - 1):
control_qubits.append(qr[qsi])
ancilla_qubits = []
for qi in anc:
ancilla_qubits.append(qr[qi])
for qi in range(0, N - M + 1):
qis = format(qi, '0' + str(Q_T) + 'b')
wMi = w[qi:qi + M]
wt = qis
for wisi in range(0, M):
hd = int(format(int(wMi[wisi]), '0'+str(Q_A)+'b'), 2) ^ int(format(int(p[wisi]), '0'+str(Q_A)+'b'), 2)
wisia = format(hd, '0' + str(Q_A) + 'b')
wt = wt + wisia
for qisi in range(0, Q_T + Q_D):
if wt[qisi] == '0':
qc.x(qr[qisi])
qc.h(qr[Q_D + Q_T - 1])
qc.mct(control_qubits, qr[Q_D + Q_T - 1], ancilla_qubits)
qc.h(qr[Q_D + Q_T - 1])
if wt[qisi] == '0':
qc.x(qr[qisi])
return
# Final measurement
def finalGroverMeasurement(qc, qr, cr):
for qi in range(0, Q_T):
qc.measure(qr[qi], cr[qi])
return
## Main function
if __name__ == '__main__':
# Printing some data for testing
qc = QIBAM()
print("Circuit depth: {}".format(qc.depth()))
# Total number of gates
print("Number of gates: {}".format(len(qc.data)))
gate_num = 1
for item in qc.data:
qb_list = ''
for qb in item[1]:
qb_list = qb_list + str(qb.index) + ', '
qb_list = qb_list[:len(qb_list)-2]
print("#{}: {}, {}".format(gate_num, item[0].name, qb_list))
gate_num = gate_num + 1
# Drawing circuit
# qc.draw()
# Showing histogram
# BE CAREFUL!
# Qiskit uses a LSB ordering, meaning the first qubit is all the way to the right!
# For example, a state of |01> would mean the first qubit is 1 and the second qubit is 0!
sim = qiskit.execute(qc, backend=backend, shots=8192)
result = sim.result()
final=result.get_counts(qc)
print(final)
plot_histogram(final)
|
https://github.com/idriss-hamadi/Qiskit-Quantaum-codes-
|
idriss-hamadi
|
# Importing standard Qiskit libraries
from qiskit import QuantumCircuit, transpile
from qiskit.tools.jupyter import *
from qiskit.visualization import *
from ibm_quantum_widgets import *
from qiskit_aer import AerSimulator
# qiskit-ibmq-provider has been deprecated.
# Please see the Migration Guides in https://ibm.biz/provider_migration_guide for more detail.
from qiskit_ibm_runtime import QiskitRuntimeService, Sampler, Estimator, Session, Options
# Loading your IBM Quantum account(s)
service = QiskitRuntimeService(channel="ibm_quantum")
# Invoke a primitive inside a session. For more details see https://qiskit.org/documentation/partners/qiskit_ibm_runtime/tutorials.html
# with Session(backend=service.backend("ibmq_qasm_simulator")):
# result = Sampler().run(circuits).result()
from qiskit import * #importing libraries we need
from qiskit.tools.visualization import plot_bloch_multivector
from qiskit.visualization import plot_histogram
%matplotlib inline
import math
Aer.backends() #seeing all the availibe simulators
def run_on_simulators(circuit): #defining a function to run on two simulators
statevector = execute(circuit, backend=Aer.get_backend('statevector_simulator'))
result = statevector.result()
vec = result.get_statevector()
QubitsNumber = circuit.num_qubits
circuit.measure([i for i in range(QubitsNumber)], [i for i in range(QubitsNumber)])
Qass = execute(circuit, backend=Aer.get_backend('qasm_simulator'), shots=1024).result()
count = Qass.get_counts()
return vec, count
circuit = QuantumCircuit(2,2)
statevec, counts = run_on_simulators(circuit)
plot_bloch_multivector(statevec)
plot_histogram([counts])
circuit = QuantumCircuit(2,2)
circuit.h(0)
circuit.cx(0,1)
statevec, counts = run_on_simulators(circuit)
plot_bloch_multivector(statevec)
plot_histogram([counts])
circuit = QuantumCircuit(2,2)
circuit.rx(math.pi/4, 0)
circuit.rx(math.pi / 2, 1)
statevec, counts = run_on_simulators(circuit)
plot_bloch_multivector(statevec)
plot_histogram([counts])
circuit = QuantumCircuit(2,2)
circuit.ry(math.pi/4, 0)
circuit.ry(math.pi / 2, 1)
statevec, counts = run_on_simulators(circuit)
plot_bloch_multivector(statevec)
plot_histogram([counts])
circuit.h(0)
statevec, counts = run_on_simulators(circuit)
plot_bloch_multivector(statevec)
plot_histogram([counts])
circuit.h(0)
circuit.h(1)
statevec, counts = run_on_simulators(circuit)
plot_bloch_multivector(statevec)
plot_histogram([counts])
statevec, counts = run_on_simulators(circuit)
plot_bloch_multivector(statevec)
plot_histogram([counts])
|
https://github.com/idriss-hamadi/Qiskit-Quantaum-codes-
|
idriss-hamadi
|
from qiskit import * #qiskit framework
# Quantum_Register=QuantumRegister(2)
# classical_Register=ClassicalRegister(2)
# circut=QuantumCircuit(Quantum_Register,classical_Register) #those 3 lines are the same as the next line
circut=QuantumCircuit(2,2)
circut.draw(output='mpl') #drawing function
circut.h(0) #handmard function
circut.cx(0,1) #Cnot function
circut.measure([0,1],[0,1]) #measuring between the qubits and calssical bits
circut.draw(output='mpl') #drawing
simulator=Aer.get_backend('qasm_simulator') #using simulator of quantaum comuter called qasm
resault=execute(circut,backend=simulator).result() #storing the resault of computation
from qiskit.visualization import plot_histogram #importing function of ploting histogram
plot_histogram(resault.get_counts()) #plot
from qiskit import *
# IBMQ.save_account(open("token.txt","r").read()) #signing in using my token in my txt file
IBMQ.load_account() #lading account
provider=IBMQ.get_provider("ibm-q")
quantaum_computer=provider.get_backend('ibmq_quito')
import qiskit.tools.jupyter
%qiskit_job_watcher
job =execute(circut,backend=quantaum_computer)
from qiskit.tools.monitor import job_monitor
job_monitor(job)
quantaum_resault=job.result()
plot_histogram(quantaum_resault.get_counts(circut))
%qiskit_disable_job_watcher
|
https://github.com/idriss-hamadi/Qiskit-Quantaum-codes-
|
idriss-hamadi
|
# Importing standard Qiskit libraries
from qiskit import QuantumCircuit, transpile
from qiskit.tools.jupyter import *
from qiskit.visualization import *
from ibm_quantum_widgets import *
from qiskit_aer import AerSimulator
# qiskit-ibmq-provider has been deprecated.
# Please see the Migration Guides in https://ibm.biz/provider_migration_guide for more detail.
from qiskit_ibm_runtime import QiskitRuntimeService, Sampler, Estimator, Session, Options
# Loading your IBM Quantum account(s)
service = QiskitRuntimeService(channel="ibm_quantum")
# Invoke a primitive inside a session. For more details see https://qiskit.org/documentation/partners/qiskit_ibm_runtime/tutorials.html
# with Session(backend=service.backend("ibmq_qasm_simulator")):
# result = Sampler().run(circuits).result()
from qiskit import *
IBMQ.save_account(open("token.txt","r").read()) #signing in using my token in my txt file
IBMQ.load_account() #lading account
Aer.backends() #show simulators each is special
provider=IBMQ.get_provider("ibm-q") #show all the actual quantaum computers and simulators that are avaliable
provider.backends()
for backend in provider.backends(): #show properties
print(backend.properties())
i=0 #code to see if it is simulator or not and how many pending jobs are there
for backend in provider.backends():
i+=1
try:
qubit_count=len(backend.properties().qubits)
except:
qubit_count="simulated"
if(qubit_count=="simulated"):
print(f"{i}-{backend.name()} : there is {backend.status().pending_jobs} waiting jobs in the queue and it is a simulator")
else:
print(f"{i}-{backend.name()} : there is {backend.status().pending_jobs} waiting jobs in the queue and it has {qubit_count} qubits")
|
https://github.com/dlyongemallo/qiskit-zx-transpiler
|
dlyongemallo
|
from qiskit.circuit import QuantumCircuit
from qiskit.converters import circuit_to_dag
from qiskit.visualization import dag_drawer
import numpy as np
# Taken from https://github.com/Quantomatic/pyzx/blob/master/circuits/Fast/mod5_4_before
qc = QuantumCircuit(5)
qc.x(4)
qc.h(4)
qc.ccz(0, 3, 4)
qc.ccz(2, 3, 4)
qc.h(4)
qc.cx(3, 4)
qc.h(4)
qc.ccz(1, 2, 4)
qc.h(4)
qc.cx(2, 4)
qc.h(4)
qc.ccz(0, 1, 4)
qc.h(4)
qc.cx(1, 4)
qc.cx(0, 4)
qc.draw(output='mpl', style='clifford')
dag = circuit_to_dag(qc)
dag_drawer(dag)
from qiskit.transpiler import PassManager
from zxpass import ZXPass
zxpass = ZXPass()
pass_manager = PassManager(zxpass)
zx_qc = pass_manager.run(qc)
zx_qc.draw(output='mpl', style='clifford')
from qiskit import transpile
opt_qc = transpile(qc, basis_gates=['u3', 'cx'], optimization_level=3)
opt_qc.draw(output='mpl', style='clifford')
from qiskit.quantum_info import Statevector
print("original circuit depth: ", qc.depth())
print("transpiled circuit depth: ", opt_qc.depth())
print("PyZX circuit depth: ", zx_qc.depth())
print(Statevector.from_instruction(qc).equiv(Statevector.from_instruction(zx_qc)))
|
https://github.com/dlyongemallo/qiskit-zx-transpiler
|
dlyongemallo
|
import sys; sys.path.append('..')
from qiskit import transpile
from qiskit.circuit import QuantumCircuit
from qiskit.transpiler import PassManager
from qiskit.qasm2 import dumps
from qiskit.qasm3 import dumps as dumps3
import pyzx as zx
from zxpass import ZXPass
pass_manager = PassManager(ZXPass())
# Select the benchmark circuit to examine.
subdir = "medium"
circuit_name = "qft_n18"
# Output the original circuit.
with open(f"QASMBench/{subdir}/{circuit_name}/{circuit_name}.qasm", "r") as file:
qasm_str = file.read()
print(f"Benchmark circuit: {circuit_name}")
qc = QuantumCircuit.from_qasm_str(qasm_str)
# qc.draw(output = "mpl")
# Output the ZX diagram for the original circuit.
g = zx.Circuit.from_qasm(qasm_str).to_graph()
zx.draw(g)
# Output the circuit produced by Qiskit optimisation.
opt_qc = transpile(qc, basis_gates=['u3', 'cx'], optimization_level=3)
# opt_qc.draw(output = "mpl")
# Output the ZX diagram for the Qiskit-optimised circuit.
opt_g = zx.Circuit.from_qasm(dumps3(opt_qc)).to_graph()
zx.draw(opt_g)
# Output the ZX-optimised circuit.
zx_qc = pass_manager.run(qc)
# zx_qc.draw(output = "mpl")
# Re-create the graph from the circuit.
zx_g = zx.Circuit.from_qasm(dumps(zx_qc)).to_graph()
zx.draw(zx_g)
|
https://github.com/dlyongemallo/qiskit-zx-transpiler
|
dlyongemallo
|
# ZX transpiler pass for Qiskit
# Copyright (C) 2023 David Yonge-Mallo
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
if __name__ == '__main__':
import sys
sys.path.append('..')
from qiskit import transpile
from qiskit.circuit import QuantumCircuit
from qiskit.transpiler import PassManager
from typing import Dict, List, Tuple
import matplotlib.pyplot as plt # type: ignore
from zxpass import ZXPass
pass_manager = PassManager(ZXPass())
def _benchmark(subdir: str, circuit_name: str, as_plugin: bool = False) -> Tuple[float, float, float]:
print(f"Circuit name: {circuit_name}")
qc = QuantumCircuit.from_qasm_file(f"QASMBench/{subdir}/{circuit_name}/{circuit_name}.qasm")
opt_qc = transpile(qc, basis_gates=['u3', 'cx'], optimization_level=3)
if as_plugin:
zx_qc = transpile(qc, optimization_method="zxpass", optimization_level=3)
else:
zx_qc = pass_manager.run(qc)
print(f"Size - original: {qc.size()}, "
f"optimized: {opt_qc.size()} ({qc.size() / opt_qc.size():.2f}), "
f"zx: {zx_qc.size()} ({qc.size() / zx_qc.size():.2f})")
print(f"Depth - original: {qc.depth()}, "
f"optimized: {opt_qc.depth()} ({qc.depth() / opt_qc.depth():.2f}), "
f"zx: {zx_qc.depth()} ({qc.depth() / zx_qc.depth():.2f})")
print(f"Number of non-local gates - original: {qc.num_nonlocal_gates()}, ", end="")
if qc.num_nonlocal_gates() != 0:
print(f"optimized: {opt_qc.num_nonlocal_gates()}, zx: {zx_qc.num_nonlocal_gates()}, "
f"ratio: {opt_qc.num_nonlocal_gates() / zx_qc.num_nonlocal_gates():.2f}")
else:
print("optimized: 0, zx: 0")
print()
return (qc.depth() / opt_qc.depth(),
qc.depth() / zx_qc.depth(),
qc.num_nonlocal_gates() / zx_qc.num_nonlocal_gates() if zx_qc.num_nonlocal_gates() != 0 else 0)
def _save_plot(title: str, plot_index: List[str], data: Dict[str, List[float]], ylabel: str) -> None:
width = 0.35
fig, ax = plt.subplots()
ax.set_title(title)
ax.set_ylabel(ylabel)
x = range(len(plot_index))
ax.bar(x, data['qiskit'], width, label='qiskit')
ax.bar([i + width for i in x], data['pyzx'], width, label='pyzx')
ax.set_xticks([i + width / 2 for i in x])
ax.set_xticklabels(plot_index, rotation=90)
ax.legend()
plt.tight_layout()
plt.savefig(f"{title.replace(' ', '_')}.png")
def run_benchmarks() -> None:
# List of circuits to benchmark, based on: https://github.com/Qiskit/qiskit/issues/4990#issuecomment-1157858632
small_benchmarks = ['wstate_n3', 'linearsolver_n3', 'fredkin_n3', 'dnn_n2', 'qrng_n4', 'adder_n4', 'deutsch_n2',
'cat_state_n4', 'basis_trotter_n4', 'qec_en_n5', 'toffoli_n3', 'grover_n2', 'hs4_n4', 'qaoa_n3',
'teleportation_n3', 'lpn_n5', 'vqe_uccsd_n4', 'quantumwalks_n2', 'variational_n4', 'qft_n4',
'iswap_n2', 'bell_n4', 'basis_change_n3', 'vqe_uccsd_n6', 'ising_n10', 'simon_n6', 'qpe_n9',
'qaoa_n6', 'bb84_n8', 'vqe_uccsd_n8', 'adder_n10', 'dnn_n8']
medium_benchmarks = ['bv_n14', 'multiplier_n15', 'sat_n11', 'qft_n18']
depth_ratio: Dict[str, List[float]] = {'qiskit': [], 'pyzx': []}
num_nonlocal_ratio: Dict[str, List[float]] = {'qiskit': [], 'pyzx': []}
plot_index = []
for benchmark in small_benchmarks:
qiskit_depth, zx_depth, non_local_ratio = _benchmark('small', benchmark)
depth_ratio['pyzx'].append(zx_depth)
depth_ratio['qiskit'].append(qiskit_depth)
num_nonlocal_ratio['pyzx'].append(non_local_ratio)
num_nonlocal_ratio['qiskit'].append(1 if non_local_ratio != 0 else 0)
plot_index.append(benchmark)
for benchmark in medium_benchmarks:
qiskit_depth, zx_depth, non_local_ratio = _benchmark('medium', benchmark)
depth_ratio['pyzx'].append(zx_depth)
depth_ratio['qiskit'].append(qiskit_depth)
num_nonlocal_ratio['pyzx'].append(non_local_ratio)
num_nonlocal_ratio['qiskit'].append(1 if non_local_ratio != 0 else 0)
plot_index.append(benchmark)
_save_plot('Depth compression ratio', plot_index, depth_ratio, 'depth_ratio')
_save_plot('Ratio of non-local gates', plot_index, num_nonlocal_ratio, 'num_nonlocal_ratio')
if __name__ == '__main__':
run_benchmarks()
|
https://github.com/dlyongemallo/qiskit-zx-transpiler
|
dlyongemallo
|
# ZX transpiler pass for Qiskit
# Copyright (C) 2023 David Yonge-Mallo
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for Qiskit ZX transpiler."""
from typing import Callable, Optional
import pyzx as zx
import numpy as np
from qiskit.circuit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit.quantum_info import Statevector
from qiskit.transpiler import PassManager
from qiskit.circuit.random import random_circuit
import qiskit.converters
from zxpass import ZXPass
def _run_zxpass(qc: QuantumCircuit, optimize: Optional[Callable[[zx.Circuit], zx.Circuit]] = None) -> bool:
zxpass = ZXPass(optimize)
pass_manager = PassManager(zxpass)
zx_qc = pass_manager.run(qc)
return Statevector.from_instruction(qc).equiv(Statevector.from_instruction(zx_qc))
def test_basic_circuit() -> None:
"""Test a basic circuit.
Taken from https://github.com/Quantomatic/pyzx/blob/master/circuits/Fast/mod5_4_before
"""
qc = QuantumCircuit(5)
qc.x(4)
qc.h(4)
qc.ccz(0, 3, 4)
qc.ccz(2, 3, 4)
qc.h(4)
qc.cx(3, 4)
qc.h(4)
qc.ccz(1, 2, 4)
qc.h(4)
qc.cx(2, 4)
qc.h(4)
qc.ccz(0, 1, 4)
qc.h(4)
qc.cx(1, 4)
qc.cx(0, 4)
assert _run_zxpass(qc)
def test_custom_optimize() -> None:
"""Test custom optimize method.
"""
qc = QuantumCircuit(4)
qc.h(0)
qc.h(1)
qc.h(2)
qc.h(3)
qc.cx(0, 1)
qc.cx(1, 2)
qc.cx(2, 3)
qc.cx(3, 0)
def optimize(circ: zx.Circuit) -> zx.Circuit:
# Any function that takes a zx.Circuit and returns a zx.Circuit will do.
return circ.to_basic_gates()
assert _run_zxpass(qc, optimize)
def test_measurement() -> None:
"""Test a circuit with a measurement.
"""
q = QuantumRegister(1, 'q')
c = ClassicalRegister(1, 'c')
qc = QuantumCircuit(q, c)
qc.h(q[0])
qc.measure(q[0], c[0])
qc.h(q[0])
dag = qiskit.converters.circuit_to_dag(qc)
zxpass = ZXPass()
circuits_and_nodes = zxpass._dag_to_circuits_and_nodes(dag) # pylint: disable=protected-access
assert len(circuits_and_nodes) == 3
assert circuits_and_nodes[1] == dag.op_nodes()[1]
def test_conditional_gate() -> None:
"""Test a circuit with a conditional gate.
"""
q = QuantumRegister(1, 'q')
c = ClassicalRegister(1, 'c')
qc = QuantumCircuit(q, c)
qc.h(q[0]).c_if(c, 0)
assert _run_zxpass(qc)
def test_unitary() -> None:
"""Test a circuit with a unitary gate.
"""
matrix = [[0, 0, 0, 1],
[0, 0, 1, 0],
[1, 0, 0, 0],
[0, 1, 0, 0]]
qc = QuantumCircuit(2)
qc.unitary(matrix, [0, 1])
assert _run_zxpass(qc)
def test_pyzx_issue_102() -> None:
"""Regression test for PyZX issue #102.
This tests for a bug which prevented an earlier attempt at a Qiskit ZX transpiler pass from working.
See: https://github.com/Quantomatic/pyzx/issues/102
"""
qc = QuantumCircuit(4)
qc.ccx(2, 1, 0)
qc.ccz(0, 1, 2)
qc.h(1)
qc.ccx(1, 2, 3)
qc.t(1)
qc.ccz(0, 1, 2)
qc.h(1)
qc.t(0)
qc.ccz(2, 1, 0)
qc.s(1)
qc.ccx(2, 1, 0)
qc.crz(0.2*np.pi, 0, 1)
qc.rz(0.8*np.pi, 1)
qc.cry(0.4*np.pi, 2, 1)
qc.crx(0.02*np.pi, 2, 0)
assert _run_zxpass(qc)
def test_random_circuits() -> None:
"""Test random circuits.
"""
for _ in range(20):
num_qubits = np.random.randint(4, 9)
depth = np.random.randint(10, 21)
qc = random_circuit(num_qubits, depth)
assert _run_zxpass(qc)
|
https://github.com/bawejagb/Quantum_Computing
|
bawejagb
|
#Import Libraries
from qiskit import QuantumCircuit, transpile, Aer, assemble
from qiskit.providers.aer import QasmSimulator
from qiskit.visualization import plot_bloch_multivector, plot_histogram
from qiskit.visualization import array_to_latex, plot_state_qsphere
# Use Aer's qasm_simulator
simulator = QasmSimulator()
# Create a Quantum Circuit acting on the q register
circuit = QuantumCircuit(2, 2)
# Add a H gate on qubit 0
circuit.h(0)
# Add a CX (CNOT) gate on control qubit 0 and target qubit 1
circuit.cx(0, 1)
# Draw the circuit
circuit.draw(output='mpl')
# Let's get the result:
svsim=Aer.get_backend('aer_simulator')
circuit.save_statevector()
qobj = assemble(circuit)
result = svsim.run(qobj).result()
# Print the statevector neatly:
final_state = result.get_statevector()
array_to_latex(final_state, prefix="\\text{Statevector = }")
#Plot Sphere
plot_state_qsphere(final_state)
# Map the quantum measurement to the classical bits
circuit.measure([0,1], [0,1])
# Draw the circuit
circuit.draw(output='mpl')
# compile the circuit down to low-level QASM instructions
compiled_circuit = transpile(circuit, simulator)
# Execute the circuit on the qasm simulator
job = simulator.run(compiled_circuit, shots=1000)
# Grab results from the job
result = job.result()
# Returns counts
counts = result.get_counts(compiled_circuit)
print("\nTotal count for 00 and 11 are:",counts)
#Plot histogram of result
plot_histogram(counts)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.