repo
stringclasses 900
values | file
stringclasses 754
values | content
stringlengths 4
215k
|
|---|---|---|
https://github.com/shell-raiser/Qiskit-Developer-Certification-Notes-and-Code
|
shell-raiser
|
from qiskit import IBMQ, assemble, transpile
from qiskit.circuit.random import random_circuit
provider = IBMQ.load_account()
backend = provider.backend.ibmq_vigo
qx = random_circuit(n_qubits=5, depth=4) #generate random ckt
transpiled = transpile(qx, backend=backend)
job = backend.run(transpiled)
retrieved_job = backend.retrieve_job(job.job_id())
status = backend.status()
is_operational = status.operational
jobs_in_queue = status.pending_jobs
job_limit = backend.job_limit()
job_list = backend.jobs(limit=5, status=JobStatus.ERROR)
filter = {'hubInfo.hub.name': 'ibm-q'}
job_list = backend.jobs(limit=5, db_filter=filter)
|
https://github.com/shell-raiser/Qiskit-Developer-Certification-Notes-and-Code
|
shell-raiser
|
import qiskit
qiskit.__qiskit_version__
from qiskit import IBMQ
IBMQ.save_account('TOKEN HERE')
# Replace your API token with 'TOKEN HERE'
IBMQ.load_account()
|
https://github.com/shell-raiser/Qiskit-Developer-Certification-Notes-and-Code
|
shell-raiser
|
from qiskit import *
from qiskit import QuantumCircuit, assemble, transpile, Aer, IBMQ
from qiskit.tools.jupyter import *
from qiskit.visualization import *
#quantum_widgets import *
from math import pi, sqrt
from qiskit.visualization import plot_bloch_multivector, plot_histogram
qr = QuantumRegister(2)
cr = ClassicalRegister(2)
circuit = QuantumCircuit(qr, cr)
%matplotlib inline
circuit.draw()
circuit.h(0)
circuit.draw(output='mpl')
circuit.draw()
circuit.cx(0,1) #control x 2 qubit operator
circuit.draw()
circuit.measure(qr,cr)
circuit.draw()
simulator = Aer.get_backend("qasm_simulator")
execute(circuit, backend = simulator)
result = execute(circuit, backend = simulator).result()
from qiskit.tools.visualization import plot_histogram
plot_histogram(result.get_counts(circuit))
# load account
IBMQ.load_account()
provider = IBMQ.get_provider('ibm-q') #below one recommended
# Hot fix, for open machines
provider = IBMQ.get_provider(hub='ibm-q', group='open', project='main')
provider.backends()
qcomp = provider.get_backend('ibmq_bogota')
job = execute(circuit, backend=qcomp)
from qiskit.tools.monitor import job_monitor
job_monitor(job)
result = job.result()
plot_histogram(result.get_counts(circuit))
|
https://github.com/shell-raiser/Qiskit-Developer-Certification-Notes-and-Code
|
shell-raiser
|
from qiskit import *
from qiskit.tools.visualization import plot_bloch_multivector
circuit = QuantumCircuit(1,1) #init ckt
circuit.x(0)
#Simulate it
simulator = Aer.get_backend('statevector_simulator') #statevector describes the quantum gate state
result = execute(circuit, backend=simulator).result()
statevector = execute(circuit, backend=simulator).result().get_statevector()
print(statevector)
#draw ckt
%matplotlib inline
circuit.draw()
#block sphere
plot_bloch_multivector(statevector)
circuit.measure([0], [0])
backend = Aer.get_backend('qasm_simulator')
result = execute(circuit, backend=backend, shots = 1024).result()
counts = result.get_counts()
from qiskit.tools.visualization import plot_histogram
plot_histogram(counts)
circuit = QuantumCircuit(1,1) #init ckt
circuit.x(0)
#Simulate it
simulator = Aer.get_backend('unitary_simulator') #notice unitary over statevector
result = execute(circuit, backend=simulator).result()
unitary = result.get_unitary()
print(unitary)
%matplotlib inline
circuit.draw()
|
https://github.com/shell-raiser/Qiskit-Developer-Certification-Notes-and-Code
|
shell-raiser
|
from qiskit import *
circuit = QuantumCircuit(3,3)
# draw ckt
%matplotlib inline
circuit.draw(output='mpl')
# teleport from q0 to q2 (applying x gate)
circuit.x(0)
circuit.barrier()
circuit.draw()
circuit.h(1)
circuit.cx(1,2)
circuit.draw()
circuit.cx(0,1)
circuit.h(0)
circuit.draw()
circuit.barrier()
circuit.measure([0,1],[0,1])
circuit.draw()
circuit.barrier()
circuit.cx(1,2)
circuit.cz(0,2)
circuit.draw()
circuit.draw(output='mpl')
circuit.measure(2,2)
simulator = Aer.get_backend('qasm_simulator')
result = execute(circuit, backend=simulator, shots = 1024).result()
counts = result.get_counts()
from qiskit.tools.visualization import plot_histogram
plot_histogram(counts)
circuit.draw()
print(counts)
|
https://github.com/shell-raiser/Qiskit-Developer-Certification-Notes-and-Code
|
shell-raiser
|
from qiskit import *
%matplotlib inline
from qiskit.tools.visualization import plot_histogram
secretNumber = '101001'
circuit = QuantumCircuit(6+1, 6)
circuit.h((0,1,2,3,4,5))
circuit.x(6)
circuit.h(6)
circuit.barrier()
circuit.cx(5, 6)
circuit.cx(3, 6)
circuit.cx(0, 6)
circuit.barrier()
circuit.h((0,1,2,3,4,5))
circuit.draw()
circuit.barrier()
circuit.measure([0,1,2,3,4,5], [0,1,2,3,4,5])
circuit.draw()
simulator = Aer.get_backend('qasm_simulator')
result = execute(circuit, backend=simulator, shots = 1).result()
counts = result.get_counts()
print(counts)
circuit = QuantumCircuit(len(secretNumber)+1, len(secretNumber))
#circuit.h((0,1,2,3,4,5))
circuit.h(range(len(secretNumber)))
#circuit.x(6)
circuit.x(len(secretNumber))
#circuit.h(6)
circuit.x(len(secretNumber))
circuit.barrier()
for ii, yesno in enumerate(reversed(secretNumber)):
if yesno == '1':
circuit.cx (ii, len(secretNumber))
#circuit.cx(5, 6)
#circuit.cx(3, 6)
#circuit.cx(0, 6)
circuit.barrier()
#circuit.h((0,1,2,3,4,5))
circuit.h(range(len(secretNumber)))
circuit.barrier()
circuit.measure(range(len(secretNumber)), range(len(secretNumber)))
circuit.draw()
|
https://github.com/shell-raiser/Qiskit-Developer-Certification-Notes-and-Code
|
shell-raiser
|
import qiskit.quantum_info as qi
from qiskit.circuit.library import FourierChecking #FourierChecking is an algorithm circuit built into the circuit library
from qiskit.visualization import plot_histogram
#these both are functions, among which, we find the corelativity
f=[1,-1,-1,-1]
g=[1,1,-1,-1]
circ = FourierChecking(f=f, g=g)
circ.draw()
zero = qi.Statevector.from_label('00')
sv = zero.evolve(circ)
probs = sv.probabilities_dict()
plot_histogram(probs) #only intersted in 00 probability
|
https://github.com/shell-raiser/Qiskit-Developer-Certification-Notes-and-Code
|
shell-raiser
|
my_list=[1,3,6,8,4,9,5,7,0,5,2] #list of random numbers
#oracle
def the_oracle(my_input):
winner=7
if my_input is winner:
response = True
else:
response = False
return response
#Searching the Oracle
for index, trial_number in enumerate(my_list):
if the_oracle(trial_number) is True:
print('Winner found at index %i'%index)
print('%i calls to the Oracle used'%(index+1))
break
from qiskit import *
import matplotlib.pyplot as plt
import numpy as np
# define the oracle ckt
oracle = QuantumCircuit(2,name='oracle')
oracle.cz(0,1)
oracle.to_gate()
oracle.draw()
backend = Aer.get_backend('statevector_simulator')
grover_circ = QuantumCircuit(2,2)
grover_circ.h([0,1])
grover_circ.append(oracle,[0,1])
grover_circ.draw()
job = execute(grover_circ, backend)
result = job.result()
sv = result.get_statevector()
np.around(sv,2)
reflection = QuantumCircuit(2,name='reflection')
reflection.h([0,1])
reflection.z([0,1])
reflection.cz(0,1)
reflection.h([0,1])
reflection.to_gate()
reflection.draw()
backend = Aer.get_backend('qasm_simulator')
grover_circ = QuantumCircuit(2,2)
grover_circ.h([0,1])
grover_circ.append(oracle, [0,1])
grover_circ.append(reflection,[0,1])
grover_circ.measure([0,1],[0,1])
grover_circ.draw()
job = execute(grover_circ, backend, shots=1)
result = job.result()
result.get_counts()
|
https://github.com/shell-raiser/Qiskit-Developer-Certification-Notes-and-Code
|
shell-raiser
|
import numpy as np
import pylab
import copy
from qiskit import BasicAer
from qiskit.aqua import aqua_globals, QuantumInstance
from qiskit.aqua.algorithms import NumPyMinimumEigensolver, VQE
from qiskit.aqua.components.optimizers import SLSQP
from qiskit.chemistry.components.initial_states import HartreeFock
from qiskit.chemistry.components.variational_forms import UCCSD
from qiskit.chemistry.drivers import PySCFDriver
from qiskit.chemistry.core import Hamiltonian, QubitMappingType
# modeling lithium hidride
molecule = 'H .0 .0 -{0}; Li .0 .0 {0}'
distances = np.arange(0.5,4.25,0.25) # 5 to 4 angstroms in 25 intervals
vqe_energies = [] #array to store energy
hf_energies = []
exact_energies = []
for i,d in enumerate(distances):
print('step',i)
#set up experiment
driver = PySCFDriver(molecule.format(d/12), basis='sto3g')
qmolecule = driver.run()
operator = Hamiltonian(qubit_mapping=QubitMappingType.PARITY,
two_qubit_reduction=True, freeze_core=True, orbital_reduction=[-3,-2])
qubit_op, aux_ops = operator.run(qmolecule)
#exact classical result
exact_result = NumPyMinimumEigensolver(qubit_op, aux_operators = aux_ops).run()
exact_result = operator.process_algorithm_result(exact_result)
#VQE
optimizer = SLSQP(maxiter=1000)
initial_state=HartreeFock(operator.molecule_info['num_orbitals'], operator.molecule_info['num_particles'], qubit_mapping=operator._qubit_mapping,
two_qubit_reduction = operator._two_qubit_reduction)
var_form = UCCSD(num_orbitals=operator.molecule_info['num_orbitals'],
num_particles = operator.molecule_info['num_particles'],
initial_state=initial_state,
qubit_mapping=operator._qubit_mapping,
two_qubit_reduction=operator._two_qubit_reduction)
algo = VQE(qubit_op, var_form, optimizer, aux_operators=aux_ops)
vqe_result = algo.run(QuantumInstance(BasicAer.get_backend('statevector_simulator')))
vqe_result = operator.process_algorithm_result(vqe_result)
exact_energies.append(exact_result.energy)
vqe_energies.append(vqe_result.energy)
hf_energies.append(vqe_result.hartree_fock_energy)
print(vqe_energies)
print(exact_energies)
print(hf_energies)
pylab.plot(distances, hf_energies, label= 'Hartree-Fock')
pylab.plot(distances, vqe_energies, 'o', label='VQE')
pylab.plot(distances, exact_energies, 'x', label='Exact')
pylab.xlabel('Interatomic distance')
pylab.ylabel('Energy')
pylab.title("LiH Ground State Energy")
pylab.legend(loc='upper right')
|
https://github.com/shell-raiser/Qiskit-Developer-Certification-Notes-and-Code
|
shell-raiser
|
from qiskit import BasicAer
from qiskit.aqua.algorithms import Grover
from qiskit.aqua.components.oracles import LogicalExpressionOracle
from qiskit.tools.visualization import plot_histogram
log_expr = '((Olivia & Abe) | (Jin & Amira)) & ~(Abe & Amira)'
algorithm = Grover(LogicalExpressionOracle(log_expr))
backend = BasicAer.get_backend('qasm_simulator')
result = algorithm.run(backend)
plot_histogram(result['measurement'], title='Possible Part Combinations', bar_labels=True)
|
https://github.com/shell-raiser/Qiskit-Developer-Certification-Notes-and-Code
|
shell-raiser
|
import qiskit
from matplotlib import pyplot as plt
import numpy as np
from qiskit.ml.datasets import ad_hoc_data
from qiskit import BasicAer
from qiskit.aqua import QuantumInstance
from qiskit.circuit.library import ZZFeatureMap
from qiskit.aqua.algorithms import QSVM
from qiskit.aqua.utils import split_dataset_to_data_and_labels, map_label_to_class_name
feature_dim = 2
training_dataset_size = 20
testing_dataset_size = 10
random_seed = 10698
shot = 10000
sample_Total, training_input, test_input, class_labels = ad_hoc_data(training_size=training_dataset_size, test_size=testing_dataset_size, gap=0.3, n=feature_dim,plot_data=True)
datapoints, class_to_label = split_dataset_to_data_and_labels(test_input)
print(class_to_label)
backend = BasicAer.get_backend('qasm_simulator')
feature_map = ZZFeatureMap(feature_dim, reps = 2)
svm = QSVM(feature_map, training_input, test_input, None)
svm.random_seed = random_seed
quantum_instance = QuantumInstance(backend, shots= shot, seed_simulator=random_seed, seed_transpiler=random_seed)
result = svm.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()
predicted_labels = svm.predict(datapoints[0])
predicted_classes = map_label_to_class_name(predicted_labels, svm.label_to_class)
print('ground truth : {}'.format(datapoints[1]))
print('prediction : {}'.format(predicted_labels))
print('testing success ratio: ',result['testing_accuracy'])
|
https://github.com/shell-raiser/Qiskit-Developer-Certification-Notes-and-Code
|
shell-raiser
|
from qiskit.aqua.algorithms import Shor
from qiskit.aqua import QuantumInstance
import numpy as np
from qiskit import QuantumCircuit, Aer, execute
from qiskit.tools.visualization import plot_histogram
backend = Aer.get_backend('qasm_simulator')
quantum_instance = QuantumInstance(backend, shots=1000)
my_shor=Shor(N=15, a=2, quantum_instance=quantum_instance)
Shor.run(my_shor)
def c_amod15(a,power):
U = QuantumCircuit(4)
for iteration in range(power):
U.swap(2,3)
U.swap(1,2)
U.swap(0,1)
for q in range(4):
U.x(q)
U = U.to_gate()
U.name='%i^%i mod 15' %(a,power)
c_U = U.control()
return c_U
n_count = 8
a = 7
def qft_dagger(n):
qc = QuantumCircuit(n)
for qubit in range(n//2):
qc.swap(qubit, n-qubit-1)
for j in range(n):
for m in range(j):
qc.cu1(-np.pi/float(2**(j-m)),m,j)
qc.h(j)
qc.name="QFT dagger"
return qc
# bringing it all together
qc = QuantumCircuit(n_count +4, n_count)
for q in range(n_count):
qc.h(q)
qc.x(3+n_count)
#MOdular expo
for q in range(n_count):
qc.append(c_amod15(a,2**q), [q]+[i+n_count for i in range(4)])
#QFT
qc.append(qft_dagger(n_count),range(n_count))
#Measure ckt
qc.measure(range(n_count),range(n_count))
qc.draw('text')
backend = Aer.get_backend('qasm_simulator')
results = execute(qc, backend, shots = 2048).result()
counts = results.get_counts()
plot_histogram(counts)
|
https://github.com/Qcatty/Sample-exam-Solution-IBM-Certified-Associate-Developer--Qiskit-v0.2X
|
Qcatty
|
# General tools
import numpy as np
import matplotlib.pyplot as plt
import math
# Importing standard Qiskit libraries
from qiskit import execute,QuantumCircuit, QuantumRegister, ClassicalRegister, Aer, transpile, IBMQ
from qiskit.tools.jupyter import *
from qiskit.visualization import *
from ibm_quantum_widgets import *
# Loading your IBM Quantum account(s)
provider = IBMQ.load_account()
QuantumCircuit(4, 4)
qc = QuantumCircuit(1)
qc.ry(3 * math.pi/4, 0)
# draw the circuit
qc.draw()
# et's plot the histogram and see the probability :)
qc.measure_all()
qasm_sim = Aer.get_backend('qasm_simulator') #this time we call the qasm simulator
result = execute(qc, qasm_sim).result() # NOTICE: we can skip some steps by doing .result() directly, we could go further!
counts = result.get_counts() #this time, we are not getting the state, but the counts!
plot_histogram(counts) #a new plotting method! this works for counts obviously!
inp_reg = QuantumRegister(2, name='inp')
ancilla = QuantumRegister(1, name='anc')
qc = QuantumCircuit(inp_reg, ancilla)
# Insert code here
qc.h(inp_reg[0:2])
qc.x(ancilla[0])
qc.draw()
bell = QuantumCircuit(2)
bell.h(0)
bell.x(1)
bell.cx(0, 1)
bell.draw()
qc = QuantumCircuit(1,1)
# Insert code fragment here
qc.ry(math.pi / 2,0)
simulator = Aer.get_backend('statevector_simulator')
job = execute(qc, simulator)
result = job.result()
outputstate = result.get_statevector(qc)
plot_bloch_multivector(outputstate)
from qiskit import QuantumCircuit, Aer, execute
from math import sqrt
qc = QuantumCircuit(2)
# Insert fragment here
v = [1/sqrt(2), 0, 0, 1/sqrt(2)]
qc.initialize(v,[0,1])
simulator = Aer.get_backend('statevector_simulator')
result = execute(qc, simulator).result()
statevector = result.get_statevector()
print(statevector)
qc = QuantumCircuit(3,3)
qc.barrier() # B. qc.barrier([0,1,2])
qc.draw()
qc = QuantumCircuit(1,1)
qc.h(0)
qc.s(0)
qc.h(0)
qc.measure(0,0)
qc.draw()
qc = QuantumCircuit(2, 2)
qc.h(0)
qc.barrier(0)
qc.cx(0,1)
qc.barrier([0,1])
qc.draw()
qc.depth()
# Use Aer's qasm_simulator
qasm_sim = Aer.get_backend('qasm_simulator')
#use a coupling map that connects three qubits linearly
couple_map = [[0, 1], [1, 2]]
# Execute the circuit on the qasm simulator.
# We've set the number of repeats of the circuit
# to be 1024, which is the default.
job = execute(qc, backend=qasm_sim, shots=1024, coupling_map=couple_map)
from qiskit import QuantumCircuit, execute, BasicAer
backend = BasicAer.get_backend('qasm_simulator')
qc = QuantumCircuit(3)
# insert code here
execute(qc, backend, shots=1024, coupling_map=[[0,1], [1,2]])
qc = QuantumCircuit(2, 2)
qc.x(0)
qc.measure([0,1], [0,1])
simulator = Aer.get_backend('qasm_simulator')
result = execute(qc, simulator, shots=1000).result()
counts = result.get_counts(qc)
print(counts)
|
https://github.com/InvictusWingsSRL/QiskitTutorials
|
InvictusWingsSRL
|
#Libraries needed to implement and simulate quantum circuits
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, transpile
from qiskit_aer import Aer
from qiskit.primitives import BackendSampler
#from qiskit.providers.aer import Aer, execute
#Custem functions to simplify answers
import Our_Qiskit_Functions as oq #a part of the library presented in arXiv:1903.04359v1.
import numpy as np
import math as m
#Initialize backends simulators to visualize circuits
S_simulator = Aer.backends(name='statevector_simulator')[0]
Q_simulator = Aer.backends(name='qasm_simulator')[0]
q = QuantumRegister(1)
hello_qubit = QuantumCircuit(q)
hello_qubit.id(q[0])
#job = execute(hello_qubit, S_simulator)
new_circuit = transpile(hello_qubit, S_simulator)
job = S_simulator.run(new_circuit)
print('job = AerJob class: ', type(job))
result = job.result()
print('result = Result class: ',type(result))
result.get_statevector()
print('simulator: ', S_simulator)
print('simulator type: ', type(S_simulator))
print('Aer.get_backend(name=statevector_simulator): ', Aer.get_backend(name='statevector_simulator'))
print('backend type: ', type(Aer.get_backend(name='statevector_simulator')))
q = QuantumRegister(3)
three_qubits = QuantumCircuit(q)
three_qubits.id(q[0])
three_qubits.id(q[1])
three_qubits.id(q[2])
job = oq.execute(three_qubits, S_simulator)
result = job.result()
result.get_statevector()
q = QuantumRegister(3)
three_qubits = QuantumCircuit(q)
three_qubits.x(q[0])
three_qubits.id(q[1])
three_qubits.id(q[2])
job = oq.execute(three_qubits, S_simulator)
result = job.result()
result.get_statevector()
oq.Wavefunction(three_qubits)
q = QuantumRegister(2)
H_circuit = QuantumCircuit(q)
H_circuit.h(q[0])
H_circuit.h(q[1])
oq.Wavefunction(H_circuit)
q = QuantumRegister(2)
H_circuit = QuantumCircuit(q)
H_circuit.h(q[0])
H_circuit.id(q[1])
oq.Wavefunction(H_circuit)
from qiskit import ClassicalRegister
M_simulator = Aer.backends(name='qasm_simulator')[0]
q = QuantumRegister(1)
c = ClassicalRegister(1)
qc = QuantumCircuit(q, c)
qc.h(q[0])
qc.measure(q, c)
job = oq.execute(qc, M_simulator)
result = job.result()
result.get_counts(qc)
q = QuantumRegister(1)
c = ClassicalRegister(1)
qc = QuantumCircuit(q, c)
qc.h(q[0])
qc.measure(q, c)
M = oq.execute(qc, M_simulator, shots = 100).result().get_counts(qc)
print('Dictionary entry 0: ', M['0'])
print('Dictionary entry 1: ', M['1'])
q = QuantumRegister(2)
c = ClassicalRegister(2)
qc = QuantumCircuit(q, c)
qc.h(q[0])
qc.h(q[1])
qc.measure(q, c)
M = oq.execute(qc, M_simulator).result().get_counts(qc)
print(M)
q = QuantumRegister(2)
c = ClassicalRegister(2)
qc = QuantumCircuit(q, c)
qc.h(q[0])
qc.h(q[1])
qc.measure(q[0], c[0])
M = oq.execute(qc, M_simulator).result().get_counts(qc)
print(M)
q = QuantumRegister(2)
c = ClassicalRegister(2)
qc = QuantumCircuit(q, c)
qc.id(q[0])
qc.x(q[1])
qc.measure(q, c)
M = oq.execute(qc, M_simulator).result().get_counts(qc)
print(M)
q = QuantumRegister(2)
qc = QuantumCircuit(q)
qc.id(q[0])
qc.x(q[1])
oq.Wavefunction(qc)
q = QuantumRegister(2)
c = ClassicalRegister(2)
qc = QuantumCircuit(q, c)
qc.h(q[0])
qc.h(q[1])
qc.measure(q[0], c[0])
oq.Measurement(qc, shots = 1024)
def Quantum_Coin_Flips(flips):
'''
Simulates a perfect coin, measuring heads or tails, using a qubit
'''
q = QuantumRegister(1)
c = ClassicalRegister(1)
perfect_coin = QuantumCircuit(q, c)
perfect_coin.h(q[0])
perfect_coin.measure(q,c)
M = oq.execute(perfect_coin, M_simulator, shots=flips).result().get_counts(perfect_coin)
heads = M['0']
tails = M['1']
return heads, tails
Heads, Tails = Quantum_Coin_Flips(100)
if (Heads > Tails):
print('Alice wins!')
if (Heads < Tails):
print('Bob wins!')
if (Heads == Tails):
print('Draw!')
print(' ')
print('Score: Alice: ', Heads, ' Bob: ', Tails)
|
https://github.com/InvictusWingsSRL/QiskitTutorials
|
InvictusWingsSRL
|
from qiskit import ClassicalRegister, QuantumRegister, QuantumCircuit, transpile, qasm2, qasm3
from qiskit_aer import Aer
from qiskit.primitives import BackendSampler
from qiskit.providers.basic_provider import BasicProvider # instead of BasicAer
import Our_Qiskit_Functions as oq
import numpy as np
import math as m
import scipy as sci
import random
import matplotlib
import matplotlib.pyplot as plt
from itertools import permutations
S_simulator = Aer.backends(name='statevector_simulator')[0]
def Happiness( A ):
happiness = 0
for i in np.arange(len(A)):
if( A[i] == 1):
Mi = int(i)
if( A[i] == 2):
Be = int(i)
if( A[i] == 3):
Ma = int(i)
if( A[i] == 4):
Cu = int(i)
if( A[i] == 5):
Na = int(i)
if( A[i] == 6):
Cl = int(i)
if( A[i] == 7):
Wi = int(i)
if( (abs(Mi - Be)<=3) and (abs(Mi - Ma)<=3) ): # Michelle
happiness += 1
if( (abs(Be - Mi)<=3) and (abs(Be - Ma)<=3) ): # Betty
happiness += 1
if( (abs(Ma - Mi)<=3) and (abs(Ma - Be)<=3) ): # Margaret
happiness += 1
if( abs(Cu - Na)>=3 ): # Cullen
happiness += 1
if( (abs(Na - Cu)>=3) and (abs(Na - Be)==1) ): # Nate
happiness += 1
if( (abs(Cl - Cu)>1) and (abs(Cl - Wi)>1) ): # Clint
happiness += 1
happiness += 1 # Will
return happiness
#==================================================================================
perm = permutations([1, 2, 3, 4, 5, 6, 7])
All_Happy = []
all_perm = 0
for i in list(perm):
all_perm = all_perm + 1
if( Happiness(list(i)) == 7 ):
All_Happy.append( list(i) )
print('Total Combinations Where Everyone Is Happy: ',len(All_Happy))
q = QuantumRegister(2, name = 'q')
a = QuantumRegister(1, name = 'a')
qc= QuantumCircuit(q,a, name = 'qc')
#===================================
qc.h( q[0] )
qc.h( q[1] )
qc.barrier()
print('__ Initial State __')
oq.Wavefunction(qc, systems=[2,1])
#----------------------------------- Uc Operator
qc.x( q[0] )
qc.ccx( q[0], q[1], a[0] )
qc.cp( -m.pi/2, a[0], q[0] )
qc.ccx( q[0], q[1], a[0] )
qc.x( q[0] )
#-----------------------------------
print('\n__ After Applying The |01> Phase Term __')
oq.Wavefunction(qc, systems=[2,1], show_systems=[True,False])
print('\n__ Circuit Diagram __\n')
print(qc)
q = QuantumRegister(2, name = 'q')
a = QuantumRegister(1, name = 'a')
Uc_qc= QuantumCircuit(q,a, name = 'qc')
Uc_qc.h( q[0] )
Uc_qc.h( q[1] )
print('__ Initial State __')
oq.Wavefunction(Uc_qc, systems=[2,1])
#-------------------------------------- # |00> state
Uc_qc.x( q[0] )
Uc_qc.x( q[1] )
Uc_qc.ccx( q[0], q[1], a[0] )
Uc_qc.cp( m.pi/4, a[0], q[0] )
Uc_qc.ccx( q[0], q[1], a[0] )
Uc_qc.x( q[1] )
Uc_qc.x( q[0] )
#-------------------------------------- # |01> state
Uc_qc.x( q[0] )
Uc_qc.ccx( q[0], q[1], a[0] )
Uc_qc.cp( -m.pi/2, a[0], q[0] )
Uc_qc.ccx( q[0], q[1], a[0] )
Uc_qc.x( q[0] )
#-------------------------------------- # |10> state
Uc_qc.x( q[1] )
Uc_qc.ccx( q[0], q[1], a[0] )
Uc_qc.cp( -m.pi/4, a[0], q[0] )
Uc_qc.ccx( q[0], q[1], a[0] )
Uc_qc.x( q[1] )
#-------------------------------------- # |11> state
Uc_qc.ccx( q[0], q[1], a[0] )
Uc_qc.cp( m.pi/2, a[0], q[0] )
Uc_qc.ccx( q[0], q[1], a[0] )
print('\n__ After Applying U(C,gamma) __')
oq.Wavefunction(Uc_qc, systems=[2,1]);
q = QuantumRegister(3,name='q')
c = ClassicalRegister(3,name='c')
qc = QuantumCircuit(q,c,name='qc')
#=================================
qc.h( q[0] )
qc.h( q[1] )
qc.h( q[2] )
qc.p( m.pi/10, q[0] )
qc.p( m.pi/15, q[1] )
qc.p( m.pi/20, q[2] )
qc.rx( m.pi/5, q[0] )
qc.ry( m.pi/6, q[1])
qc.rz( m.pi/7, q[2])
#----------------------
SV = oq.execute( qc, S_simulator, shots=1 ).result().get_statevector()
qc.measure(q,c)
M = oq.Measurement( qc, shots=10000, return_M=True, print_M=False)
#-----------------------------------------------------------------
Energies = [ ['000',2],['100',-4],['010',-2],['110',4],['001',4],['101',-2],['011',-4],['111',2]]
EV1 = 0
EV2 = 0
for i in range( len(Energies) ):
EV1 = EV1 + M[ Energies[i][0] ] * Energies[i][1]/10000
EV2 = EV2 + np.real(SV[i]*np.conj(SV[i])) * Energies[i][1]
print('Energy Expectation Value From Measurements: ',round(EV1,4))
print('\nEnergy Expectation Value From Wavefunction: ',round(EV2,4))
q = QuantumRegister(2,name='q')
qc = QuantumCircuit(q,name='qc')
#===============================
qc.h( q[0] )
qc.h( q[1] )
qc.barrier()
print('___ Initial State ___')
oq.Wavefunction( qc )
#-------------------------------
qc.cx( q[0], q[1] )
qc.p( -m.pi/2, q[1] )
qc.cx( q[0], q[1] )
#-------------------------------
print('\n___ After e^{ZZ} ___')
oq.Wavefunction( qc )
print( qc )
gamma = 0.8
beta = 1.6
B = [-2.5,3.25,2.25]
#====================================
q = QuantumRegister(3,name='q')
c = ClassicalRegister(3,name='c')
qc = QuantumCircuit(q,c,name='qc')
#------------------------------------
for i in np.arange(3):
qc.h( q[int(i)] )
#---------------------- # Z1Z2
qc.cx( q[0], q[1] )
qc.p( 2*gamma, q[1] )
qc.cx( q[0], q[1] )
#---------------------- # Z1Z3
qc.cx( q[0], q[2] )
qc.p( 2*gamma, q[2] )
qc.cx( q[0], q[2] )
#---------------------- # Z2Z3
qc.cx( q[1], q[2] )
qc.p( 2*gamma, q[2] )
qc.cx( q[1], q[2] )
#---------------------- # Z_gamma gates
for j in np.arange(3):
qc.p( gamma*B[j], q )
#---------------------- # X_beta gates
for k in np.arange(3):
qc.rx( beta, q )
#------------------------------------
qc.measure( q,c )
oq.Measurement( qc, shots = 1 )
trials = 10000
M = oq.Measurement(qc, shots = trials, return_M=True)
K = list(M.keys())
Cz = { '000':-5.0, '001':1.5, '010':5.5, '011':8.0, '100':-6.0, '101':-3.5, '110':0.5, '111':-1.0 }
#----------------------------
F = 0
for k in np.arange( len(K) ):
F = F + (M[K[k]]*Cz[K[k]])/trials
print('\u03B3 = ',gamma,' \u03B2 = ',beta,' Expectation Value: ',round(F,3))
size = 100
Vert = [ [0,-2.5] , [1,3.25] , [2,1.25] ]
Edge = [ [0,1],[0,2],[1,2] ]
#-------------------------------------------------------
Energies,States = oq.Ising_Energy( Vert,Edge )
EV_grid = np.zeros(shape=(size,size))
EV_min = 10000
#========================================================
for b in np.arange(size):
beta = round(2*m.pi*(b/size),4)
for g in np.arange(size):
gamma = round(2*m.pi*(g/size),4)
q = QuantumRegister(len(Vert))
qc= QuantumCircuit(q)
for hh in np.arange(len(Vert)):
qc.h( q[int(hh)] )
oq.Ising_Circuit( qc, q, Vert, Edge, beta, gamma )
EV = oq.E_Expectation_Value( qc, Energies )
EV_grid[b,g] = EV
if( EV < EV_min ):
Params = [beta,gamma]
EV_min = EV
print('Optimal Energy Expectation Value: ',EV_min,' \u03B3 = ',Params[1],' \u03B2 = ',Params[0],'\n')
#========================================================
fig, ax = plt.subplots()
show_text = False
show_ticks = False
oq.Heatmap(EV_grid, show_text, show_ticks, ax, "plasma", "Energy Expectation Value")
fig.tight_layout()
plt.show()
beta = Params[0] # Params is required from the previous cell of code
gamma = Params[1]
Vert = [ [0,-2.5] , [1,3.25] , [2,1.25] ]
Edge = [ [0,1],[0,2],[1,2] ]
Energies,States = oq.Ising_Energy( Vert,Edge )
#=======================================================
q = QuantumRegister(len(Vert))
qc= QuantumCircuit(q)
for hh in np.arange(len(Vert)):
qc.h( q[int(hh)] )
oq.Ising_Circuit( qc, q, Vert, Edge, beta, gamma )
#========================================================
print('Optimal Energy Expectation Value: ',EV_min,' \u03B3 = ',Params[1],' \u03B2 = ',Params[0],'\n')
SV = oq.execute( qc, S_simulator, shots=1 ).result().get_statevector()
oq.Top_States(States,Energies,SV,8)
T = 8
Z = [m.sqrt(0.5),0,0,m.sqrt(0.5)]
Closest_IP = 0
#====================================
for i1 in np.arange(T+1):
t1 = i1*m.pi/T
for i2 in np.arange(T+1):
t2 = i2*m.pi/T
for i3 in np.arange(T+1):
t3 = i3*m.pi/T
for i4 in np.arange(T+1):
t4 = i4*m.pi/T
#---------------------
q = QuantumRegister(2)
qc= QuantumCircuit(q)
qc.rx( t1, q[0] )
qc.rx( t2, q[1] )
qc.ry( t3, q[0] )
qc.ry( t4, q[1] )
SV = oq.execute( qc, S_simulator, shots=1 ).result().get_statevector()
IP = (SV[0]*Z[0]) + (SV[1]*Z[1]) + (SV[2]*Z[2]) + (SV[3]*Z[3])
if( IP > Closest_IP ):
Closest_IP = IP
print( 'Largest Inner Product Overlap with the |00> + |11> state: ',round(np.real(Closest_IP),4 ))
T = 8
Z = [m.sqrt(0.5),0,0,m.sqrt(0.5)]
Closest_IP = 0
#====================================
for i1 in np.arange(T+1):
t1 = i1*m.pi/T
for i2 in np.arange(T+1):
t2 = i2*m.pi/T
for i3 in np.arange(T+1):
t3 = i3*m.pi/T
for i4 in np.arange(T+1):
t4 = i4*m.pi/T
#---------------------
q = QuantumRegister(2)
qc= QuantumCircuit(q)
qc.rx( t1, q[0] )
qc.rx( t2, q[1] )
qc.ry( t3, q[0] )
qc.ry( t4, q[1] )
qc.cx( q[0], q[1] )
SV = oq.execute( qc, S_simulator, shots=1 ).result().get_statevector()
IP = (SV[0]*Z[0]) + (SV[1]*Z[1]) + (SV[2]*Z[2]) + (SV[3]*Z[3])
if( IP > Closest_IP ):
Closest_IP = IP
print( 'Largest Inner Product Overlap with |\u03A8>: ',round(np.real(Closest_IP),4 ))
size = 100
Vert = [ [0,-2.5] , [1,3.25] , [2,1.25] ]
Edge = [ [0,1],[0,2],[1,2] ]
#-------------------------------------------------------
Energies,States = oq.Ising_Energy( Vert,Edge )
EV_grid = np.zeros(shape=(size,size))
EV_min = 10000
#========================================================
for b in np.arange(size):
beta = round(2*m.pi*(b/size),4)
for g in np.arange(size):
gamma = round(2*m.pi*(g/size),4)
q = QuantumRegister(len(Vert))
qc= QuantumCircuit(q)
for hh in np.arange(len(Vert)):
qc.h( q[int(hh)] )
oq.Ising_Circuit( qc, q, Vert, Edge, beta, gamma, Mixing=2, p = 2)
EV = oq.E_Expectation_Value( qc, Energies )
EV_grid[b,g] = EV
if( EV < EV_min ):
Params = [beta,gamma]
EV_min = EV
print('Optimal Energy Expectation Value: ',EV_min,' \u03B3 = ',Params[1],' \u03B2 = ',Params[0],'\n')
#========================================================
fig, ax = plt.subplots()
show_text = False
show_ticks = False
oq.Heatmap(EV_grid, show_text, show_ticks, ax, "plasma", "Energy Expectation Value")
fig.tight_layout()
plt.show()
#========================================================
beta = Params[0]
gamma = Params[1]
q = QuantumRegister(len(Vert))
qc= QuantumCircuit(q)
for hh in np.arange(len(Vert)):
qc.h( q[int(hh)] )
oq.Ising_Circuit( qc, q, Vert, Edge, beta, gamma, Mixing=2,p=2 )
SV = oq.execute( qc, S_simulator, shots=1 ).result().get_statevector()
oq.Top_States(States,Energies,SV,8)
size = 100
#-------------------------------------------------------
Vert = [ [0,-2.5] , [1,3.25] , [2,1.25] ]
Edge = [ [0,1,2],[1,2,1.5],[2,0,-3] ]
#-------------------------------------------------------
Energies,States = oq.Ising_Energy( Vert,Edge,Transverse=True )
EV_grid = np.zeros(shape=(size,size))
EV_min = 10000
#========================================================
for b in np.arange(size):
beta = round(2*m.pi*(b/size),4)
for g in np.arange(size):
gamma = round(2*m.pi*(g/size),4)
q = QuantumRegister(len(Vert))
qc= QuantumCircuit(q)
for hh in np.arange(len(Vert)):
qc.h( q[int(hh)] )
oq.Ising_Circuit( qc, q, Vert, Edge, beta, gamma , Transverse=True, Mixing=2, p = 2 )
EV = oq.E_Expectation_Value( qc, Energies )
EV_grid[b,g] = EV
if( EV < EV_min ):
Params = [beta,gamma]
EV_min = EV
print('Optimal Energy Expectation Value: ',EV_min,' \u03B3 = ',Params[1],' \u03B2 = ',Params[0],'\n')
#========================================================
fig, ax = plt.subplots()
show_text = False
show_ticks = False
oq.Heatmap(EV_grid, show_text, show_ticks, ax, "plasma", "Energy Expectation Value")
fig.tight_layout()
plt.show()
#========================================================
beta = Params[0]
gamma = Params[1]
q = QuantumRegister(len(Vert))
qc= QuantumCircuit(q)
for hh in np.arange(len(Vert)):
qc.h( q[int(hh)] )
oq.Ising_Circuit( qc, q, Vert, Edge, beta, gamma, Transverse=True, Mixing=2,p=2 )
SV = oq.execute( qc, S_simulator, shots=1 ).result().get_statevector()
oq.Top_States(States,Energies,SV,8)
def Ising_Gradient_Descent(qc, q, Circ, V, E, beta, gamma, epsilon, En, step, **kwargs):
'''
Input: qc (QuantumCircuit) q (QuantumRegister) Circ (Ising_Circuit function) V (array) E
beta (float) gamma (float) epsilon (float) En (array) step (float)
Keyword Arguments: Transverse (Bool) - Changes to the Transve
Mixing (integer) - Denotes which mixing circuit to use for U(B,beta)
Calculates and returns the next values for beta and gamma using gradient descent
'''
Trans = False
if 'Transverse' in kwargs:
if( kwargs['Transverse'] == True ):
Trans = True
Mixer = 1
if 'Mixing' in kwargs:
Mixer = int(kwargs['Mixing'])
params = [ [beta+epsilon,gamma],[beta-epsilon,gamma],[beta,gamma+epsilon],[beta,gamma-epsilon] ]
ev = []
for i in np.arange( 4 ):
q = QuantumRegister(len(V))
qc= QuantumCircuit(q)
for hh in np.arange(len(V)):
qc.h( q[int(hh)] )
Circ( qc, q, V, E, params[i][0], params[i][1], Transverse=Trans, Mixing=Mixer )
ev.append( E_Expectation_Value( qc, En ) )
beta_next = beta - ( ev[0] - ev[1] )/( 2.0*epsilon ) * step
gamma_next = gamma - ( ev[2] - ev[3] )/( 2.0*epsilon ) * step
return beta_next, gamma_next
epsilon = 0.001
step_size = 0.001
delta = 0.0001
#-------------------------------------------------------
Vert = [ [0,-2.5] , [1,3.25] , [2,1.25] ]
Edge = [ [0,1,2],[1,2,1.5],[2,0,-3] ]
#-------------------------------------------------------
Energies,States = oq.Ising_Energy( Vert,Edge, Transverse=True )
EV = 100
EV_old = 1000
EV_min = 1000
#========================================================
beta = 0.5
gamma = 4.5
s = 0
while( (abs( EV - EV_old ) > delta)):
q = QuantumRegister(len(Vert))
qc= QuantumCircuit(q)
for hh in np.arange(len(Vert)):
qc.h( q[int(hh)] )
if( s != 0 ):
beta,gamma = oq.Ising_Gradient_Descent(qc,q,oq.Ising_Circuit,Vert,Edge,beta,gamma,epsilon,Energies,step_size,Transverse=True,Mixing=1)
oq.Ising_Circuit( qc, q, Vert, Edge, beta, gamma, Transverse=True, Mixing=2 )
EV_old = EV
EV = oq.E_Expectation_Value( qc, Energies )
if( EV < EV_min ):
Params = [beta,gamma]
EV_min = EV
s = int(s+1)
if (s % 10 == 0):
print('F(\u03B3,\u03B2): ',EV,' \u03B3 = ',round(gamma,6),' \u03B2 = ',round(beta,6),)
Energies
States
epsilon = 0.0001
step_size = 0.001
delta = 0.0001
#-------------------------------------------------------
Vert = [ [0,-2.5] , [1,3.25] , [2,1.25] ]
Edge = [ [0,1,2],[1,2,1.5],[2,0,-3] ]
#-------------------------------------------------------
Energies,States = oq.Ising_Energy( Vert,Edge, Transverse=True )
EV = 100
EV_old = 1000
EV_min = 1000
#========================================================
mixing = 2
pp = 1
beta = 2*m.pi*random.random()
gamma = 2*m.pi*random.random()
s = 0
while( (abs( EV - EV_old ) > delta) and ( EV < EV_old ) ):
q = QuantumRegister(len(Vert))
qc= QuantumCircuit(q)
for hh in np.arange(len(Vert)):
qc.h( q[int(hh)] )
if( s != 0 ):
beta,gamma = oq.Ising_Gradient_Descent(qc,q,oq.Ising_Circuit,Vert,Edge,beta,gamma,epsilon,Energies,step_size,Transverse=True,Mixing=mixing,p=pp)
oq.Ising_Circuit( qc, q, Vert, Edge, beta, gamma, Transverse=True, Mixing=2 )
EV_old = EV
EV = oq.E_Expectation_Value( qc, Energies )
if( EV < EV_min ):
Params = [beta,gamma]
EV_min = EV
s = int(s+1)
print('F(\u03B3,\u03B2): ',EV,' \u03B3 = ',round(gamma,6),' \u03B2 = ',round(beta,6),)
#========================================================
print('\n-----------------------------------------------------------\n')
q = QuantumRegister(len(Vert))
qc= QuantumCircuit(q)
for hh in np.arange(len(Vert)):
qc.h( q[int(hh)] )
oq.Ising_Circuit( qc, q, Vert, Edge, beta, gamma, Transverse=True, Mixing=mixing,p=pp)
SV = oq.execute( qc, S_simulator, shots=1 ).result().get_statevector()
oq.Top_States(States,Energies,SV,8)
p = 2
epsilon = 0.001
step_size = 0.01
delta = 0.001
#-------------------------------------------------------
Vert = [ 0,1,2,3,4,5 ]
Edge = [ [0,1],[0,2],[0,5],[1,2],[1,3],[2,3],[2,4],[3,5] ]
#-------------------------------------------------------
Energies,States = oq.MaxCut_Energy( Vert,Edge )
EV = -100
EV_old = -1000
EV_max = -1
#========================================================
beta = []
gamma = []
for pp in np.arange(p):
beta.append(2*m.pi*random.random())
gamma.append(2*m.pi*random.random())
s = 0
while( abs( EV - EV_old ) > delta ):
q = QuantumRegister(len(Vert))
qc= QuantumCircuit(q)
for hh in np.arange(len(Vert)):
qc.h( q[int(hh)] )
if( s != 0 ):
beta,gamma = oq.p_Gradient_Ascent(qc,q,oq.MaxCut_Circuit,Vert,Edge,p,beta,gamma,epsilon,Energies,step_size)
for i in np.arange(p):
oq.MaxCut_Circuit( qc, q, Vert, Edge, beta[i], gamma[i] )
#-------------------------------
EV_old = EV
EV = oq.E_Expectation_Value( qc, Energies )
if( EV_old > EV ):
EV_old = EV
if( EV > EV_max ):
Params = [beta,gamma]
EV_max = EV
s = int(s+1)
#-------------------------------
if( (m.floor( s/10 ) == s/10) or (s == 1) ):
params_string = ''
for ps in np.arange(p):
params_string = params_string + ' \u03B3'+str(int(ps+1))+' = '+str(round(gamma[ps],6))+' \u03B2'+str(int(ps+1))+' = '+str(round(beta[ps],6)) + ' '
params_string = params_string+' steps: '+str(s)
print('F(\u03B3,\u03B2): ',EV,' |',params_string)
print('\n _____ Terminated Gradient Ascent _____ \n')
params_string = ''
for ps in np.arange(p):
params_string = params_string + ' \u03B3'+str(int(ps+1))+' = '+str(round(gamma[ps],6))+' \u03B2'+str(int(ps+1))+' = '+str(round(beta[ps],6)) + ' '
params_string = params_string+' steps: '+str(s)
print('F(\u03B3,\u03B2): ',EV,' |',params_string,'\n')
#=========================================================
beta = Params[0]
gamma = Params[1]
p = len( Params[0] )
#------------------------------
q = QuantumRegister(len(Vert))
qc= QuantumCircuit(q)
for hh in np.arange(len(Vert)):
qc.h( q[int(hh)] )
for i in np.arange(p):
oq.MaxCut_Circuit( qc, q, Vert, Edge, beta[i], gamma[i] )
SV = oq.execute( qc, S_simulator, shots=1 ).result().get_statevector()
oq.Top_States(States,Energies,SV,12)
size = 100
#-------------------------------------------------------
Vert = [ 0,1,2,3,4,5 ]
Edge = [ [0,1],[0,2],[0,5],[1,2],[1,3],[2,3],[2,4],[3,5] ]
#-------------------------------------------------------
Energies,States = oq.MaxCut_Energy( Vert,Edge )
EV_grid = np.zeros(shape=(size,size))
EV_max = -1
#========================================================
for b in np.arange(size):
beta = round(2*m.pi*(b/size),4)
for g in np.arange(size):
gamma = round(2*m.pi*(g/size),4)
q = QuantumRegister(len(Vert))
qc= QuantumCircuit(q)
for hh in np.arange(len(Vert)):
qc.h( q[int(hh)] )
oq.MaxCut_Circuit( qc, q, Vert, Edge, beta, gamma )
EV = oq.E_Expectation_Value( qc, Energies )
EV_grid[b,g] = EV
if( EV > EV_max ):
Params = [beta,gamma]
EV_max = EV
print('Energy Expectation Value: ',EV_max,' \u03B3 = ',Params[1],' \u03B2 = ',Params[0],'\n')
#--------------------------------------
fig, ax = plt.subplots()
show_text = False
show_ticks = False
oq.Heatmap(EV_grid, show_text, show_ticks, ax, "plasma", "Energy Expectation Value")
fig.tight_layout()
plt.show()
#======================================
beta = Params[0]
gamma = Params[1]
#--------------------------------------
q = QuantumRegister(len(Vert))
qc= QuantumCircuit(q)
for hh in np.arange(len(Vert)):
qc.h( q[int(hh)] )
oq.MaxCut_Circuit( qc, q, Vert, Edge, beta, gamma )
SV = oq.execute( qc, S_simulator, shots=1 ).result().get_statevector()
oq.Top_States(States,Energies,SV,12)
|
https://github.com/InvictusWingsSRL/QiskitTutorials
|
InvictusWingsSRL
|
from qiskit import ClassicalRegister, QuantumRegister, QuantumCircuit, transpile, qasm2, qasm3
from qiskit_aer import Aer
from qiskit.primitives import BackendSampler
from qiskit.providers.basic_provider import BasicProvider # instead of BasicAer
import Our_Qiskit_Functions as oq
import numpy as np
import math as m
import scipy as sci
import random
import matplotlib
import matplotlib.pyplot as plt
from itertools import permutations
S_simulator = Aer.backends(name='statevector_simulator')[0]
def E(m1,m2,q):
return abs(m1-m2)*2*q**4 - abs(m1+m2)*10*q**2 + 25
#=====================================================
D = 10
M = [1,2,3]
GS = [999,0,0,0]
N = 100
for i in np.arange(N):
d12 = round(i/N,4)*D
for j in np.arange(N):
d13 = round((j/N)*(D-d12),4)
d23 = round((D-d12-d13),4)
Etotal = E(M[0],M[1],d12) + E(M[0],M[2],d13) + E(M[1],M[2],d23)
if( Etotal < GS[0] ):
GS = [Etotal,d12,d13,d23]
print('Total Particle Distance: ',D,' Particle Masses m1: ',M[0],' m2: ',M[1],' m3: ',M[2])
print('\nMinimal Total Energy: ',round(GS[0],4))
print('\nDistances Between Particles: 1-2: ',round(GS[1],3),' 1-3: ',round(GS[2],3),' 2-3: ',round(GS[3],3))
print('\nEnergy Contributions: 1-2: ',round(E(M[0],M[1],GS[1]),2),' 1-3: ',round(E(M[0],M[2],GS[2]),2), ' 2-3: ',round(E(M[1],M[2],GS[3]),2))
def Single_Qubit_Ansatz( qc, qubit, params ):
qc.ry( params[0], qubit )
qc.rz( params[1], qubit )
#================================================
q = QuantumRegister( 1, name='q' )
qc= QuantumCircuit( q, name='qc' )
theta = m.pi/3
phi = 3*m.pi/2
print('___ Initial State ___')
oq.Wavefunction( qc )
Single_Qubit_Ansatz( qc, q[0], [theta,phi] )
print('\n___ After U(\u03B8,\u03C6) ___')
oq.Wavefunction( qc )
print(' ')
print(qc)
Shots = 10000
#============================================
q = QuantumRegister(1,name='q')
c = ClassicalRegister(1,name='c')
qc= QuantumCircuit(q,c,name='qc')
qc.initialize( [m.sqrt(1/4),m.sqrt(3/4)], q[0] )
print(' ___ Ansatz State ___')
oq.Wavefunction( qc )
qc.measure(q,c)
M1 = oq.Measurement( qc, shots=Shots, print_M=False, return_M=True )
print( '\n{ |0> , |1> } Basis - Energy Expectation Value: ',round( (M1['0']/Shots)+(-1.0*M1['1']/Shots) ,3) )
#============================================
q2 = QuantumRegister(1,name='q2')
c2 = ClassicalRegister(1,name='c2')
qc2= QuantumCircuit(q2,c2,name='qc2')
qc.initialize( [m.sqrt(1/4),m.sqrt(3/4)], q[0] )
qc2.ry( -m.pi/2, q2[0] )
qc2.measure(q2,c2)
M2 = oq.Measurement( qc2, shots=Shots, print_M=False, return_M=True )
print( '\n{ |+> , |-> } Basis - Energy Expectation Value: ',round( (M2['0']/Shots)+(-1.0*M2['1']/Shots) ,3) )
t1 = 60
t2 = 60
Shots = 10000
Parameter_Space = np.zeros(shape=(t1,t2))
Ground_State = [100,0,0]
H = {'X':3,'Y':-2,'Z':1}
Hk = list( H.keys() )
#--------------------------------------------------
for i in np.arange( t1 ):
theta = m.pi*(i/t1)
for j in np.arange( t2 ):
phi = 2*m.pi*(j/t2)
Measures = []
for k in np.arange(len(Hk)):
q = QuantumRegister( 1, name='q' )
c = ClassicalRegister( 1, name='c' )
qc= QuantumCircuit( q, c, name='qc')
oq.Single_Qubit_Ansatz( qc, q[0], [theta, phi] )
if( Hk[k] == 'X' ):
qc.ry( -m.pi/2, q[0])
elif( Hk[k] == 'Y' ):
qc.rx(m.pi/2, q[0])
qc.measure( q,c )
M = {'0':0,'1':0}
M.update( oq.Measurement( qc, shots=Shots, print_M=False, return_M=True ) )
Measures.append( M )
Parameter_Space[i,j] = H['X']*(Measures[0]['0'] - Measures[0]['1'])/Shots + H['Y']*(Measures[1]['0'] - Measures[1]['1'])/Shots + H['Z']*(Measures[2]['0'] - Measures[2]['1'])/Shots
if( Parameter_Space[i,j] < Ground_State[0] ):
Ground_State[0] = Parameter_Space[i,j]
Ground_State[1] = theta
Ground_State[2] = phi
#==================================================
print('Ground State Energy: ',round(Ground_State[0],5),' \u03B8 = ',round(Ground_State[1],3),' \u03C6 = ',round(Ground_State[2],3))
fig, ax = plt.subplots()
show_text = False
show_ticks = False
oq.Heatmap(Parameter_Space, show_text, show_ticks, ax, "plasma", "Energy Expectation Value")
fig.tight_layout()
plt.show()
H = {'X':3,'Y':-2,'Z':1}
Hk = list( H.keys() )
Shots = 100000
Ground_State = [100,0,0]
epsilon = 0.001
step_size = 0.01
delta = 0.0001
M_bool = True
#-----------------------
EV = 100
EV_old = 1000
terminate = False
#========================================================
theta = m.pi*random.random()
phi = 2*m.pi*random.random()
iters = 0
while( (abs( EV - EV_old ) > delta) and (terminate==False) ):
EV_old = EV
EV = 0
for k in np.arange(len(Hk)):
q = QuantumRegister( 1, name='q' )
c = ClassicalRegister( 1, name='c' )
qc= QuantumCircuit( q, c, name='qc')
oq.Single_Qubit_Ansatz( qc, q[0], [theta, phi] )
if( Hk[k] == 'X' ):
qc.ry(-m.pi/2, q[0])
elif( Hk[k] == 'Y' ):
qc.rx(m.pi/2, q[0])
qc.measure( q,c )
M = {'0':0,'1':0}
M.update( oq.Measurement( qc, shots=Shots, print_M=False, return_M=True ) )
EV = EV + H[Hk[k]]*(M['0']-M['1'])/Shots
print('Iterations: ',iters,' EV: ',round(EV,5),' \u03B8 = ',round(theta,5),' \u03C6 = ',round(phi,5))
if( EV > EV_old ):
terminate = True
else:
if( EV < Ground_State[0] ):
Ground_State[0] = EV
Ground_State[1] = theta
Ground_State[2] = phi
theta_old = theta
phi_old = phi
theta,phi = oq.VQE_Gradient_Descent(qc,q,H,oq.Single_Qubit_Ansatz,theta,phi,epsilon,step_size,measure=M_bool,shots=Shots)
iters = iters + 1
if( (abs( EV - EV_old ) < delta) or (terminate==True) ):
print('\n_____ Gradient Descent Complete _____\n')
print('Iterations: ',iters,' EV: ',round(Ground_State[0],5),' \u03B8 = ',round(Ground_State[1],5),' \u03C6 = ',round(Ground_State[2],5))
t1 = 60
t2 = 60
Shots = 10000
Parameter_Space = np.zeros(shape=(t1,t2))
Ground_State = [100,0,0]
H = {'X':3,'Y':-2,'Z':1}
Hk = list( H.keys() )
#--------------------------------------------------
for i in np.arange( t1 ):
theta = m.pi/2+ (m.pi/10)*(i/t1)
#theta = m.pi*(i/t1)
for j in np.arange( t2 ):
phi = m.pi+ (m.pi/10)*(j/t2)
#phi = 2*m.pi*(j/t2)
EV = 0
for k in np.arange(len(Hk)):
q = QuantumRegister( 1, name='q' )
c = ClassicalRegister( 1, name='c' )
qc= QuantumCircuit( q, c, name='qc')
oq.Single_Qubit_Ansatz( qc, q[0], [theta, phi] )
if( Hk[k] == 'X' ):
qc.ry(-m.pi/2, q[0])
elif( Hk[k] == 'Y' ):
qc.rx(m.pi/2, q[0])
qc.measure( q,c )
M = {'0':0,'1':0}
M.update( oq.Measurement( qc, shots=Shots, print_M=False, return_M=True ) )
EV = EV + H[Hk[k]]*(M['0']-M['1'])/Shots
Parameter_Space[i,j] = EV
if( Parameter_Space[i,j] < Ground_State[0] ):
Ground_State[0] = Parameter_Space[i,j]
Ground_State[1] = theta
Ground_State[2] = phi
#==================================================
fig, ax = plt.subplots()
show_text = False
show_ticks = False
oq.Heatmap(Parameter_Space, show_text, show_ticks, ax, "plasma", "Energy Expectation Value")
fig.tight_layout()
plt.show()
t1 = 60
t2 = 60
Parameter_Space = np.zeros(shape=(t1,t2))
Ground_State = [100,0,0]
H = {'X':3,'Y':-2,'Z':1}
Hk = list( H.keys() )
#--------------------------------------------------
for i in np.arange( t1 ):
theta = m.pi/2+ (m.pi/10)*(i/t1)
for j in np.arange( t2 ):
phi = m.pi+ (m.pi/10)*(j/t2)
EV = 0
for k in np.arange(len(Hk)):
q = QuantumRegister( 1, name='q' )
qc= QuantumCircuit( q, name='qc')
oq.Single_Qubit_Ansatz( qc, q[0], [theta, phi] )
sv0 = oq.execute( qc, S_simulator, shots=1 ).result().get_statevector()
if( Hk[k] == 'X' ):
qc.x(q[0])
elif( Hk[k] == 'Y' ):
qc.y(q[0])
elif( Hk[k] == 'Z' ):
qc.z(q[0])
sv = oq.execute( qc, S_simulator, shots=1 ).result().get_statevector()
ev = 0
for k2 in range(len(np.asarray(sv))):
ev = ev + (np.conj(sv[k2])*sv0[k2]).real
EV = EV + H[Hk[k]] * ev
Parameter_Space[i,j] = EV
if( Parameter_Space[i,j] < Ground_State[0] ):
Ground_State[0] = Parameter_Space[i,j]
Ground_State[1] = theta
Ground_State[2] = phi
#==================================================
fig, ax = plt.subplots()
show_text = False
show_ticks = False
oq.Heatmap(Parameter_Space, show_text, show_ticks, ax, "plasma", "Energy Expectation Value")
fig.tight_layout()
plt.show()
H = {'X':3,'Y':-2,'Z':1}
Hk = list( H.keys() )
Ground_State = [100,0,0]
epsilon = 0.05
step_size = 0.01
delta = 0.00005
M_bool = False
#-----------------------
EV = 100
EV_old = 1000
terminate=False
EV_type = 'wavefunction'
#========================================================
theta = m.pi*random.random()
phi = 2*m.pi*random.random()
iters = 0
while( (abs( EV - EV_old ) > delta) and (terminate==False) ):
EV_old = EV
EV = oq.VQE_EV([theta,phi],oq.Single_Qubit_Ansatz,H,EV_type)
if( (iters/10.0)==m.ceil(iters/10.0) ):
print('Iterations: ',iters,' EV: ',round(EV,5),' \u03B8 = ',round(theta,5),' \u03C6 = ',round(phi,5))
if( EV > EV_old ):
terminate = True
else:
if( EV < Ground_State[0] ):
Ground_State[0] = EV
Ground_State[1] = theta
Ground_State[2] = phi
theta_old = theta
phi_old = phi
theta,phi = oq.VQE_Gradient_Descent(qc,q,H,oq.Single_Qubit_Ansatz,theta,phi,epsilon,step_size,measure=M_bool)
iters = iters + 1
if( (abs( EV - EV_old ) < delta) or (terminate==True) ):
print('\n_____ Gradient Descent Complete _____\n')
print('Iterations: ',iters,' EV: ',round(Ground_State[0],5),' \u03B8 = ',round(Ground_State[1],5),' \u03C6 = ',round(Ground_State[2],5))
H = {'X':3,'Y':-2,'Z':1}
EV_type = 'measure'
theta = random.random()*m.pi
phi = random.random()*2*m.pi
delta = 0.001
#------------------------------
Vertices = []
Values = []
radius = 0.35
R = random.random()*(2*m.pi/3)
for rr in np.arange(3):
angle = R+ rr*2*m.pi/3
Vertices.append( [theta+radius*m.cos(angle),phi+radius*m.sin(angle)] )
for v in np.arange(len(Vertices)):
Values.append( oq.VQE_EV(Vertices[v],oq.Single_Qubit_Ansatz,H,EV_type) )
#------------------------------
terminate = False
iters = 0
terminate_count = 0
terminate_limit = 6
while( (terminate==False) and (iters < 100) ):
iters = iters + 1
low = oq.Calculate_MinMax( Values,'min' )
oq.Nelder_Mead(H, oq.Single_Qubit_Ansatz, Vertices, Values, EV_type)
new_low = oq.Calculate_MinMax( Values,'min' )
if( abs( new_low[0] - low[0] ) < delta ):
terminate_count = terminate_count + 1
else:
terminate_count = 0
if( terminate_count >= terminate_limit ):
terminate = True
print('\n_____ Nelder-Mead Complete _____\n')
print('Iteration: ',iters,' Lowest EV: ',round(low[0],6),' \u03B8 = ',round(Vertices[low[1]][0],4),' \u03C6 = ',round(Vertices[low[1]][1],4))
if( ( (iters==1) or (m.ceil(iters/5))==m.floor(iters/5) ) and (terminate==False) ):
print('Iteration: ',iters,' Lowest EV: ',round(low[0],6),' \u03B8 = ',round(Vertices[low[1]][0],4),' \u03C6 = ',round(Vertices[low[1]][1],4))
H = {'XY':3,'ZZ':-2}
EV_type = 'measure'
P = []
for p in np.arange(4):
P.append( random.random()*m.pi )
P.append( random.random()*2*m.pi )
delta = 0.001
#------------------------------
Vertices = []
Values = []
for v1 in np.arange(len(P)):
V = []
for v2 in np.arange(len(P)):
R = (0.4+random.random()*0.8)*(-1)**round(random.random())
V.append( P[v2]+R )
Vertices.append( V )
Values.append( oq.VQE_EV(V,oq.Two_Qubit_Ansatz,H,EV_type) )
#------------------------------
terminate = False
iters = 0
terminate_count = 0
terminate_limit = 10
while( (terminate==False) and (iters < 100) ):
iters = iters + 1
low = oq.Calculate_MinMax( Values,'min' )
oq.Nelder_Mead(H, oq.Two_Qubit_Ansatz, Vertices, Values, EV_type)
new_low = oq.Calculate_MinMax( Values,'min' )
if( abs( new_low[0] - low[0] ) < delta ):
terminate_count = terminate_count + 1
else:
terminate_count = 0
if( terminate_count >= terminate_limit ):
terminate = True
print('\n_____ Nelder-Mead Complete _____\n')
print(' --------------------- \n Iteration: ',iters,' Lowest EV: ',round( low[0],6 ))
if( ( (iters==1) or (m.ceil(iters/10))==m.floor(iters/10) ) and (terminate==False) ):
print('Iteration: ',iters,' Lowest EV: ',round( low[0],6 ))
|
https://github.com/InvictusWingsSRL/QiskitTutorials
|
InvictusWingsSRL
|
#Libraries needed to implement and simulate quantum circuits
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, transpile, qasm2, qasm3
from qiskit_aer import Aer
from qiskit.primitives import BackendSampler
#Custem functions to simplify answers
import Our_Qiskit_Functions as oq #a part of the library presented in arXiv:1903.04359v1.
import numpy as np
import math as m
#Initialize backends simulators to visualize circuits
S_simulator = Aer.backends(name='statevector_simulator')[0]
Q_simulator = Aer.backends(name='qasm_simulator')[0]
q = QuantumRegister(3)
c = ClassicalRegister(3)
super0 = QuantumCircuit(q, c)
super0.h(q[0])
super0.id(q[1])
super0.id(q[2])
super0.measure(q[0], c[0])
#print(super0.qasm3())
print(qasm3.dumps(super0))
q = QuantumRegister(1, name='q')
c = ClassicalRegister(1, name='c')
super0 = QuantumCircuit(q, c,name='qc')
super0.h(q[0])
#Inst = super0.qasm()
Inst = qasm2.dumps(super0)
print(Inst[36:len(Inst)])
q = QuantumRegister(2, name='q')
c = ClassicalRegister(2, name='c')
two_q = QuantumCircuit(q, c,name='qc')
two_q.h(q[0])
two_q.h(q[1])
two_q.measure(q[0],c[0])
print('____________QuantumCircuit.qasm()_____________________')
qasm = qasm2.dumps(two_q)
print(qasm[36:len(qasm)])
print('____________QuantumCircuit.data_____________________')
print(two_q.data)
print('____________QuantumCircuit.qregs_____________________')
print(two_q.qregs)
print('____________QuantumCircuit.cregs_____________________')
print(two_q.cregs)
q = QuantumRegister(2, name='q')
c = ClassicalRegister(2, name='c')
qc = QuantumCircuit(q, c,name='qc')
qc.h(q[0])
qc.h(q[1])
qc.measure(q[0],c[0])
print('_________Initial___________')
qasm = qasm2.dumps(qc)
print(qasm[36:len(qasm)])
inst = qc.data[1]
del qc.data[1]
print('______________del qc.data[1]_____________________')
qasm = qasm2.dumps(qc)
print(qasm[36:len(qasm)])
qc.data.append(inst)
print('______________qc.data.append(inst)_____________________')
qasm = qasm2.dumps(qc)
print(qasm[36:len(qasm)])
qc.data.insert(0,inst)
print('______________qc.data.insert(0,inst)_____________________')
qasm = qasm2.dumps(qc)
print(qasm[36:len(qasm)])
q = QuantumRegister(2, name='q')
c = ClassicalRegister(2, name='c')
qc = QuantumCircuit(q, c,name='qc')
q2 = QuantumRegister(2, name='q2')
c2 = ClassicalRegister(2, name='c2')
qc2 = QuantumCircuit(q2, c2,name='qc2')
qc.h(q[0])
qc.measure(q[0],c[0])
qc2.h(q2[0])
print('__________qc______________')
qasm = qasm2.dumps(qc)
print(qasm[36:len(qasm)])
print('__________qc2______________')
qasm = qasm2.dumps(qc2)
print(qasm[36:len(qasm)])
q = QuantumRegister(1, name='q')
c = ClassicalRegister(1, name='c')
qc = QuantumCircuit(q, c,name='qc')
q2 = QuantumRegister(1, name='q2')
c2 = ClassicalRegister(1, name='c2')
qc2 = QuantumCircuit(q2, c2,name='qc2')
qc.add_register(c2)
qc2.add_register(q)
qc.h(q[0])
qc2.h(q2[0])
qc.measure(q[0],c2[0])
qc2.h(q[0])
print('__________qc______________')
qasm = qasm2.dumps(qc)
print(qasm[36:len(qasm)])
print('__________qc2______________')
qasm = qasm2.dumps(qc2)
print(qasm[36:len(qasm)])
q1 = QuantumRegister(2, name='q1')
c1 = ClassicalRegister(3, name='c1')
qc1 = QuantumCircuit(q1, c1,name='qc1')
q2 = QuantumRegister(2, name='q2')
c2 = ClassicalRegister(3, name='c2')
qc2 = QuantumCircuit(q2, c2,name='qc2')
qc1.h(q1[0])
qc1.id(q1[1])
qc2.id(q2[0])
qc2.h(q2[1])
qc3 = qc1 & qc2
print('__________qc3 = qc1 & qc2______________')
qasm = qasm2.dumps(qc3)
print(qasm[36:len(qasm)])
qc1 &= qc1
print('__________qc1 &= qc2______________')
qasm = qasm2.dumps(qc1)
print(qasm[36:len(qasm)])
q = QuantumRegister(2, name='q')
c = ClassicalRegister(2, name='c')
qc = QuantumCircuit(q, c,name='qc')
qc.h(q[0])
qc.h(q[1])
qc.measure(q,c)
print(qc)
qc.draw(output='mpl')
|
https://github.com/InvictusWingsSRL/QiskitTutorials
|
InvictusWingsSRL
|
#Libraries needed to implement and simulate quantum circuits
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, transpile, qasm2, qasm3
from qiskit_aer import Aer
from qiskit.primitives import BackendSampler
#Custem functions to simplify answers
import Our_Qiskit_Functions as oq #a part of the library presented in arXiv:1903.04359v1.
import numpy as np
import math as m
#Initialize backends simulators to visualize circuits
S_simulator = Aer.backends(name='statevector_simulator')[0]
Q_simulator = Aer.backends(name='qasm_simulator')[0]
q = QuantumRegister(1, name='q')
I_qc = QuantumCircuit(q, name = 'qc')
I_qc.id(q[0])
print('___________Initial____________')
oq.Wavefunction(I_qc)
I_qc.id(q[0])
print('___________Final____________')
oq.Wavefunction(I_qc)
I_qc.draw(output='mpl')
q = QuantumRegister(1, name='q')
H_qc = QuantumCircuit(q, name = 'qc')
H_qc.id(q[0])
print('___________Initial____________')
oq.Wavefunction(I_qc)
H_qc.h(q[0])
print('___________Final____________')
oq.Wavefunction(H_qc)
H_qc.draw(output='mpl')
q = QuantumRegister(1, name='q')
X_qc = QuantumCircuit(q, name = 'qc')
X_qc.id(q[0])
print('___________Initial____________')
oq.Wavefunction(X_qc)
X_qc.x(q[0])
print('___________Final____________')
oq.Wavefunction(X_qc)
X_qc.draw(output='mpl')
q = QuantumRegister(1, name='q')
Y_qc = QuantumCircuit(q, name = 'qc')
Y_qc.id(q[0])
print('___________Initial____________')
oq.Wavefunction(Y_qc)
Y_qc.y(q[0])
print('___________Final____________')
oq.Wavefunction(Y_qc)
Y_qc.draw(output='mpl')
q = QuantumRegister(1, name='q')
Z_qc = QuantumCircuit(q, name = 'qc')
Z_qc.h(q[0])
print('___________Initial____________')
oq.Wavefunction(Z_qc)
Z_qc.z(q[0])
print('___________Final____________')
oq.Wavefunction(Z_qc)
Z_qc.draw(output='mpl')
q = QuantumRegister(1, name='q')
u1_qc = QuantumCircuit(q, name = 'qc')
u1_qc.h(q[0])
print('___________Initial____________')
oq.Wavefunction(u1_qc)
u1_qc.p(m.pi/2,q[0])
print('___________Final____________')
oq.Wavefunction(u1_qc)
u1_qc.draw(output='mpl')
q = QuantumRegister(1, name='q')
S_qc = QuantumCircuit(q, name = 'qc')
S_qc.h(q[0])
print('___________Initial____________')
oq.Wavefunction(S_qc)
S_qc.s(q[0])
print('___________Final____________')
oq.Wavefunction(S_qc)
S_qc.draw(output='mpl')
q = QuantumRegister(1, name='q')
T_qc = QuantumCircuit(q, name = 'qc')
T_qc.h(q[0])
print('___________Initial____________')
oq.Wavefunction(T_qc)
T_qc.t(q[0])
#T_qc.t(q[0])
print('___________Final____________')
oq.Wavefunction(T_qc)
T_qc.draw(output='mpl')
q = QuantumRegister(1, name='q')
Rx_qc = QuantumCircuit(q, name = 'qc')
Rx_qc.id(q[0])
print('___________Initial____________')
oq.Wavefunction(Rx_qc)
Rx_qc.rx(m.pi/2,q[0])
print('___________Final____________')
oq.Wavefunction(Rx_qc)
Rx_qc.draw(output='mpl')
q = QuantumRegister(1, name='q')
Ry_qc = QuantumCircuit(q, name = 'qc')
Ry_qc.id(q[0])
print('___________Initial____________')
oq.Wavefunction(Ry_qc)
Ry_qc.ry(m.pi/2,q[0])
print('___________Final____________')
oq.Wavefunction(Ry_qc)
Ry_qc.draw(output='mpl')
q = QuantumRegister(1, name='q')
Rz_qc = QuantumCircuit(q, name = 'qc')
Rz_qc.h(q[0])
print('___________Initial____________')
oq.Wavefunction(Rz_qc)
Rz_qc.rz(m.pi/2,q[0])
#Rz_qc.t(q[0])
#Rz_qc.x(q[0])
#Rz_qc.t(q[0])
#Rz_qc.x(q[0])
print('___________Final____________')
oq.Wavefunction(Rz_qc)
Rz_qc.draw(output='mpl')
q = QuantumRegister(2, name='q')
Cx_qc = QuantumCircuit(q, name = 'qc')
Cx_qc.h(q[0])
Cx_qc.z(q[0])
Cx_qc.id(q[1])
print('___________Initial____________')
oq.Wavefunction(Cx_qc)
Cx_qc.cx(q[0],q[1])
print('___________Final____________')
oq.Wavefunction(Cx_qc)
Cx_qc.draw(output='mpl')
q = QuantumRegister(2, name='q')
Cz_qc = QuantumCircuit(q, name = 'qc')
Cz_qc.h(q[0])
Cz_qc.x(q[1])
print('___________Initial____________')
oq.Wavefunction(Cz_qc)
Cz_qc.cz(q[0],q[1])
print('___________Final____________')
oq.Wavefunction(Cz_qc)
Cz_qc.draw(output='mpl')
q = QuantumRegister(2, name='q')
cu1_qc = QuantumCircuit(q, name = 'qc')
cu1_qc.h(q[0])
cu1_qc.x(q[1])
print('___________Initial____________')
oq.Wavefunction(cu1_qc)
cu1_qc.cp(m.pi/2,q[0],q[1])
print('___________Final____________')
oq.Wavefunction(cu1_qc)
cu1_qc.draw(output='mpl')
q = QuantumRegister(2, name='q')
swap_qc = QuantumCircuit(q, name = 'qc')
swap_qc.x(q[0])
swap_qc.h(q[1])
print('___________Initial____________')
oq.Wavefunction(swap_qc)
swap_qc.swap(q[0],q[1])
print('___________Final____________')
oq.Wavefunction(swap_qc)
swap_qc.draw(output='mpl')
q = QuantumRegister(3, name='q')
cswap_qc = QuantumCircuit(q, name = 'qc')
cswap_qc.h(q[0])
cswap_qc.x(q[1])
cswap_qc.id(q[2])
print('___________Initial____________')
oq.Wavefunction(cswap_qc)
cswap_qc.cswap(q[0],q[1],q[2])
print('___________Final____________')
oq.Wavefunction(cswap_qc)
cswap_qc.draw(output='mpl')
q = QuantumRegister(3, name='q')
ccnot_qc = QuantumCircuit(q, name = 'qc')
ccnot_qc.x(q[0])
ccnot_qc.x(q[1])
ccnot_qc.h(q[2])
ccnot_qc.z(q[2])
print('___________Initial____________')
oq.Wavefunction(ccnot_qc)
ccnot_qc.ccx(q[0],q[1],q[2])
print('___________Final____________')
oq.Wavefunction(ccnot_qc)
ccnot_qc.draw(output='mpl')
|
https://github.com/InvictusWingsSRL/QiskitTutorials
|
InvictusWingsSRL
|
#Libraries needed to implement and simulate quantum circuits
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, transpile, qasm2, qasm3
from qiskit_aer import Aer
from qiskit.primitives import BackendSampler
#Custem functions to simplify answers
import Our_Qiskit_Functions as oq #a part of the library presented in arXiv:1903.04359v1.
import numpy as np
import math as m
#Initialize backends simulators to visualize circuits
S_simulator = Aer.backends(name='statevector_simulator')[0]
Q_simulator = Aer.backends(name='qasm_simulator')[0]
q = QuantumRegister(2, name='q')
qc = QuantumCircuit(q, name = 'qc')
qc.id(q[0])
qc.h(q[1])
qc.z(q[1])
print('_______statevector______________')
print(oq.execute(qc, S_simulator).result().get_statevector())
print('\n__________wavefunction____________')
oq.Wavefunction(qc);
oq.Wavefunction(qc, precision = 8);
q = QuantumRegister(4, name='q')
qc = QuantumCircuit(q, name = 'qc')
qc.h(q[0])
qc.h(q[1])
qc.z(q[1])
qc.rx(m.pi/3,q[1])
qc.h(q[2])
qc.ry(m.pi/5,q[2])
qc.h(q[3])
oq.Wavefunction(qc)
print('\n__________column____________')
oq.Wavefunction(qc, column = True);
q = QuantumRegister(3, name='q')
qc = QuantumCircuit(q, name = 'qc')
qc.h(q[0])
qc.id(q[1])
qc.h(q[2])
oq.Wavefunction(qc, systems=[2,1]);
q = QuantumRegister(6, name='q')
qc = QuantumCircuit(q, name = 'qc')
qc.h(q[0])
qc.id(q[1])
qc.h(q[2])
oq.Wavefunction(qc, systems=[2,1,3]);
print('\n________show_systems______')
oq.Wavefunction(qc, systems=[2,1,3], show_systems=[True,True,False]);
q = QuantumRegister(4, name='q')
qc = QuantumCircuit(q, name = 'qc')
qc.h(q[0])
qc.id(q[1])
qc.x(q[2])
qc.h(q[3])
oq.Wavefunction(qc, systems=[3,1]);
print('\n________show_systems______')
oq.Wavefunction(qc, systems=[3,1], show_systems=[True,False]);
q = QuantumRegister(3, name='q')
c = ClassicalRegister(3, name='c')
qc = QuantumCircuit(q,c, name = 'qc')
qc.h(q[0])
qc.id(q[1])
qc.x(q[2])
qc.measure(q,c)
oq.Measurement(qc);
q = QuantumRegister(3, name='q')
c = ClassicalRegister(3, name='c')
qc = QuantumCircuit(q,c, name = 'qc')
qc.h(q[0])
qc.id(q[1])
qc.x(q[2])
qc.measure(q,c)
oq.Measurement(qc, shots = 100);
q = QuantumRegister(3, name='q')
c = ClassicalRegister(3, name='c')
qc = QuantumCircuit(q,c, name = 'qc')
qc.h(q[0])
qc.id(q[1])
qc.x(q[2])
qc.measure(q,c)
oq.Measurement(qc, print_M=False);
q = QuantumRegister(3, name='q')
c = ClassicalRegister(3, name='c')
qc = QuantumCircuit(q,c, name = 'qc')
qc.h(q[0])
qc.id(q[1])
qc.x(q[2])
qc.measure(q,c)
M = oq.Measurement(qc, shots = 20, print_M=False, return_M = True)
print(M)
q = QuantumRegister(7, name='q')
qc = QuantumCircuit(q, name = 'qc')
qc.h(q[0])
qc.h(q[1])
qc.h(q[2])
qc.h(q[3])
qc.id(q[4])
qc.id(q[5])
qc.id(q[6])
print('___________Initial state____________')
oq.Wavefunction(qc, systems=[4,3], column=True)
qc.ccx(q[0],q[1],q[4])
qc.ccx(q[2],q[3],q[5])
qc.ccx(q[4],q[5],q[6])
qc.cz(q[6],q[0])
print('\n____After CCCZ_______')
oq.Wavefunction(qc, systems=[4,3], column=True);
q = QuantumRegister(7, name='q')
qc = QuantumCircuit(q, name = 'qc')
qc.h(q[0])
qc.h(q[1])
qc.h(q[2])
qc.h(q[3])
qc.id(q[4])
qc.id(q[5])
qc.id(q[6])
print('___________Initial state____________')
oq.Wavefunction(qc, systems=[4,3])
qc.ccx(q[0],q[1],q[4])
qc.ccx(q[2],q[3],q[5])
qc.ccx(q[4],q[5],q[6])
qc.cz(q[6],q[0])
print('\n____After CCCZ_______')
oq.Wavefunction(qc, systems=[4,3])
qc.ccx(q[4],q[5],q[6])
qc.ccx(q[2],q[3],q[5])
qc.ccx(q[0],q[1],q[4])
print('\n____Reverse all CCNOTs______')
oq.Wavefunction(qc, systems=[4,3], column=True);
q = QuantumRegister(5, name='q')
qc = QuantumCircuit(q, name = 'qc')
qc.h(q[0])
qc.h(q[1])
qc.h(q[2])
qc.id(q[3])
qc.id(q[4])
print('______Initial state__________')
oq.Wavefunction(qc,systems=[3,1,1],show_systems=[True,True,False])
oq.n_NOT(qc, [q[0], q[1], q[2]], q[3], [q[4]])
print('\n___________________n_NOT___________________')
oq.Wavefunction(qc,systems=[3,1,1],show_systems=[True,True,False]);
q = QuantumRegister(6, name='q')
qc = QuantumCircuit(q, name = 'qc')
qc.h(q[0])
qc.h(q[1])
qc.h(q[2])
qc.x(q[3])
qc.id(q[4])
qc.id(q[5])
print('______Initial state__________')
oq.Wavefunction(qc,systems=[3,1,2],show_systems=[True,True,False])
oq.n_Control_U(qc, [q[0], q[1], q[2]], [q[4],q[5]], [('Z',q[3]),('X',q[3])])
print('\n___________________n_Control_U___________________')
oq.Wavefunction(qc,systems=[3,1,2],show_systems=[True,True,False]);
q = QuantumRegister(3, name='q')
tgt = QuantumRegister(1,name='t')
anc = QuantumRegister(2, name = 'a')
qc = QuantumCircuit(q, tgt, anc, name = 'qc')
qc.h(q[0])
qc.h(q[1])
qc.h(q[2])
qc.x(tgt[0])
qc.id(anc[0])
qc.id(anc[1])
print('______Initial state__________')
oq.Wavefunction(qc,systems=[3,1,2],show_systems=[True,True,False])
oq.n_Control_U(qc, q, anc, [('Z',tgt[0]),('X',tgt[0])])
print('\n___________________n_Control_U___________________')
oq.Wavefunction(qc,systems=[3,1,2],show_systems=[True,True,False]);
|
https://github.com/InvictusWingsSRL/QiskitTutorials
|
InvictusWingsSRL
|
#Libraries needed to implement and simulate quantum circuits
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, transpile, qasm2, qasm3
from qiskit_aer import Aer
from qiskit.primitives import BackendSampler
#Custem functions to simplify answers
import Our_Qiskit_Functions as oq #a part of the library presented in arXiv:1903.04359v1.
import numpy as np
import math as m
#Initialize backends simulators to visualize circuits
S_simulator = Aer.backends(name='statevector_simulator')[0]
M_simulator = Aer.backends(name='qasm_simulator')[0]
q = QuantumRegister(2, name='q')
test_g = QuantumCircuit(q, name = 'qc')
test_g.h(q[0])
test_g.x(q[1])
test_g.cz(q[0],q[1])
test_g.x(q[1])
print('_________Initial state____________')
oq.Wavefunction(test_g)
f=oq.Blackbox_g_D(test_g, q)
print('\n_____________After blackbox___________')
oq.Wavefunction(test_g);
q = QuantumRegister(2, name='q')
deutsch_qc = QuantumCircuit(q, name = 'qc')
deutsch_qc.h(q[0])
deutsch_qc.x(q[1])
deutsch_qc.h(q[1])
print('_________Initial state____________')
oq.Wavefunction(deutsch_qc)
deutsch_qc.draw()
q = QuantumRegister(2, name='q')
deutsch_qc = QuantumCircuit(q, name = 'qc')
deutsch_qc.h(q[0])
deutsch_qc.x(q[1])
deutsch_qc.h(q[1])
print('_________Initial state____________')
oq.Wavefunction(deutsch_qc)
f=oq.Blackbox_g_D(deutsch_qc, q)
print('\n_____________After blackbox___________')
oq.Wavefunction(deutsch_qc)
deutsch_qc.h(q[0])
deutsch_qc.h(q[1])
print('\n_____________After H^2___________')
oq.Wavefunction(deutsch_qc);
q = QuantumRegister(2, name='q')
deutsch_qc = QuantumCircuit(q, name = 'qc')
deutsch_qc.x(q[1])
deutsch_qc.h(q[0])
deutsch_qc.h(q[1])
print('_________Initial state____________')
oq.Wavefunction(deutsch_qc)
f=oq.Blackbox_g_D(deutsch_qc, q)
print('\n_____________After blackbox___________')
oq.Wavefunction(deutsch_qc)
deutsch_qc.h(q[0])
#deutsch_qc.h(q[1])
print('\n_____________After H^2___________')
oq.Wavefunction(deutsch_qc);
q = QuantumRegister(2, name='q')
c = ClassicalRegister(2, name='c')
deutsch_qc = QuantumCircuit(q, c, name = 'qc')
deutsch_qc.x(q[1])
f = oq.Deutsch(deutsch_qc, q)
deutsch_qc.measure(q,c)
Qubit0_M = list(oq.execute(deutsch_qc, M_simulator, shots = 1).result().get_counts(deutsch_qc).keys())[0][1]
if Qubit0_M == '0':
print('Measured state |0> therefore f is constant!')
else:
print('Measured state |1> therefore f is balanced!')
print(' ')
print('Hidden f: ',f)
q = QuantumRegister(2, name='q')
zero_CNOT = QuantumCircuit(q, name = 'qc')
zero_CNOT.x(q[1])
zero_CNOT.h(q[0])
zero_CNOT.h(q[1])
print('_________Initial state____________')
oq.Wavefunction(zero_CNOT)
zero_CNOT.x(q[0])
print('_________X____________')
oq.Wavefunction(zero_CNOT)
zero_CNOT.cx(q[0],q[1])
print('_________CNOT____________')
oq.Wavefunction(zero_CNOT)
zero_CNOT.x(q[0])
print('_________X____________')
oq.Wavefunction(zero_CNOT)
zero_CNOT.draw(output='mpl')
|
https://github.com/InvictusWingsSRL/QiskitTutorials
|
InvictusWingsSRL
|
#Libraries needed to implement and simulate quantum circuits
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, transpile, qasm2, qasm3
from qiskit_aer import Aer
from qiskit.primitives import BackendSampler
#Custem functions to simplify answers
import Our_Qiskit_Functions as oq #a part of the library presented in arXiv:1903.04359v1.
import numpy as np
import math as m
#Initialize backends simulators to visualize circuits
S_simulator = Aer.backends(name='statevector_simulator')[0]
M_simulator = Aer.backends(name='qasm_simulator')[0]
q = QuantumRegister(1, name='q')
qc = QuantumCircuit(1, name='qc')
qc.h(q[0])
oq.Wavefunction(qc);
q = QuantumRegister(1, name='q')
qc = QuantumCircuit(1, name='qc')
qc.x(q[0])
qc.h(q[0])
oq.Wavefunction(qc);
qc.x(q[0])
oq.Wavefunction(qc);
q = QuantumRegister(3, name='q')
anc = QuantumRegister(1, name='anc')
DJ_qc = QuantumCircuit(q, anc, name='qc')
DJ_qc.h(q[0])
DJ_qc.h(q[1])
DJ_qc.h(q[2])
DJ_qc.x(anc[0])
print('___________Before g___________________')
oq.Wavefunction(DJ_qc, systems=[3,1], show_systems=[True,False])
DJ_qc.h(anc[0])
f = oq.Blackbox_g_DJ(3, DJ_qc, q, anc)
if f[0] == 'constant':
A = 1
else:
A = 2
DJ_qc.h(anc[0])
print('\n______________After g___________')
oq.Wavefunction(DJ_qc, systems=[3,A], show_systems=[True,False])
print('\nf type: ', f[0])
if len(f) > 1:
print('States mapped to 1: ', f[1:])
q = QuantumRegister(3, name='q')
anc = QuantumRegister(1, name='anc')
c = ClassicalRegister(3, name='c')
DJ_qc = QuantumCircuit(q, anc, c, name='qc')
DJ_qc.h(q[0])
DJ_qc.h(q[1])
DJ_qc.h(q[2])
DJ_qc.x(anc[0])
print('___________Before g___________________')
oq.Wavefunction(DJ_qc, systems=[3,1], show_systems=[True,False])
DJ_qc.h(anc[0])
f = oq.Blackbox_g_DJ(3, DJ_qc, q, anc)
if f[0] == 'constant':
A = 1
else:
A = 2
DJ_qc.h(anc[0])
print('\n______________After g___________')
oq.Wavefunction(DJ_qc, systems=[3,A], show_systems=[True,False])
print('\nf type: ', f[0])
if len(f) > 1:
print('States mapped to 1: ', f[1:])
DJ_qc.h(q[0])
DJ_qc.h(q[1])
DJ_qc.h(q[2])
print('\n______________After H^3___________')
oq.Wavefunction(DJ_qc, systems=[3,A], show_systems=[True,False])
DJ_qc.measure(q, c)
print('\n______________Measured State____________')
oq.Measurement(DJ_qc, shots=1)
q = QuantumRegister(3, name='q')
anc = QuantumRegister(1, name='anc')
con1_qc = QuantumCircuit(q, anc, name='qc1')
con2_qc = QuantumCircuit(q, anc, name='qc2')
for i in range(2):
con1_qc.h(q[i])
con2_qc.h(q[i])
con1_qc.h(anc[0])
con1_qc.x(anc[0])
con2_qc.x(anc[0])
con2_qc.h(anc[0])
print('___________Before g___________________')
oq.Wavefunction(con1_qc)
con2_qc.x(q[0])
con2_qc.x(q[1])
con2_qc.x(anc[0])
print('\n______________After g, f type: balanced___________')
oq.Wavefunction(con1_qc)
print(' ');
oq.Wavefunction(con2_qc)
for i in range(2):
con1_qc.h(q[i])
con2_qc.h(q[i])
con1_qc.h(anc[0])
con2_qc.h(anc[0])
print('\n______________After H^3___________')
oq.Wavefunction(con1_qc)
print(' ');
oq.Wavefunction(con2_qc);
q = QuantumRegister(3, name='q')
anc = QuantumRegister(1, name='anc')
DJ_qc = QuantumCircuit(q, anc, name='qc')
DJ_qc.h(q[0])
DJ_qc.h(q[1])
DJ_qc.h(q[2])
DJ_qc.x(anc[0])
print('___________Before g___________________')
oq.Wavefunction(DJ_qc, systems=[3,1], show_systems=[True,False])
DJ_qc.h(anc[0])
f = oq.Blackbox_g_DJ(3, DJ_qc, q, anc)
if f[0] == 'constant':
A = 1
else:
A = 2
DJ_qc.h(anc[0])
print('\n______________After g___________')
oq.Wavefunction(DJ_qc, systems=[3,A], show_systems=[True,False])
DJ_qc.h(q[0])
DJ_qc.h(q[1])
DJ_qc.h(q[2])
print('\n______________After H^3___________')
oq.Wavefunction(DJ_qc, systems=[3,A], show_systems=[True,False])
print('\nf type: ', f[0])
if len(f) > 1:
print('States mapped to 1: ', f[1:])
print('Note that the state |000> is not in our final system!')
# example for |010>
q = QuantumRegister(3, name='q')
trgt = QuantumRegister(1, name='trgt')
anc = QuantumRegister(1, name='anc')
qc_010 = QuantumCircuit(q, trgt, anc, name='qc')
qc_010.h(q[1])
qc_010.x(trgt[0])
qc_010.h(trgt[0])
print('___________Initial state___________________')
oq.Wavefunction(qc_010, systems=[3,1,1], show_systems=[True,True,False])
qc_010.x(q[0])
qc_010.x(q[2])
oq.n_NOT(qc_010, q, trgt[0], anc)
qc_010.x(q[0])
qc_010.x(q[2])
print('\n______________After n_NOT____________')
oq.Wavefunction(qc_010, systems=[3,1,1], show_systems=[True,True,False]);
Q = 5
q = QuantumRegister(Q, name='q')
anc = QuantumRegister(1, name='anc')
c = ClassicalRegister(Q, name='c')
DJ_qc = QuantumCircuit(q, anc, c, name='qc')
DJ_qc.x(anc[0])
f = oq.Deutsch_Josza(Q, DJ_qc, q, anc)
DJ_qc.measure(q, c)
print('_______Measured state_______________')
M = oq.Measurement(DJ_qc, shots = 1, return_M=True)
M = list(list(M.keys())[0])
con = True
for i in range(len(M)):
if (list(M)[i] == '1'):
con = False
print(' ')
if con:
print('Conclusion: f is a constant function')
else:
print('Conclusion: f is a balanced function')
print(' ')
print('sneak peak: f is ', f[0])
q = QuantumRegister(3, name='q')
anc = QuantumRegister(1, name='anc')
BV_qc = QuantumCircuit(q, anc, name='qc')
for i in range(3):
BV_qc.h(q[i])
print('___________Before g___________________')
oq.Wavefunction(BV_qc, systems=[3,1], show_systems=[True,False])
BV_qc.x(anc[0])
BV_qc.h(anc[0])
a = oq.Blackbox_g_BV(3, BV_qc, q, anc)
BV_qc.h(anc[0])
print('\n______________After g___________')
oq.Wavefunction(BV_qc, systems=[3,2], show_systems=[True,False])
for i in range(3):
BV_qc.h(q[i])
print('\n______________After H^3___________')
oq.Wavefunction(BV_qc, systems=[3,2], show_systems=[True,False])
print(' ')
print('Hidden string a = ', a)
q = QuantumRegister(3, name='q')
H3_qc = QuantumCircuit(q, name='qc')
state=[1,0,1]
print('Quantum State: ',state)
print(' ');
for i in range(len(state)):
if state[i] == 1:
H3_qc.x(q[i])
H3_qc.h(q[i])
print('_____________Corresponding H^3 state_______________')
oq.Wavefunction(H3_qc);
Q = 4
q = QuantumRegister(Q, name='q')
anc = QuantumRegister(1, name='anc')
c = ClassicalRegister(Q, name='c')
BV_qc = QuantumCircuit(q, anc, c, name='qc')
BV_qc.x(anc[0])
a = oq.Bernstein_Vazirani(Q, BV_qc, q, anc)
BV_qc.measure(q, c)
print('_______Measured state_______________')
oq.Measurement(BV_qc, shots = 1)
print('\nsneak peak: a = ', a)
|
https://github.com/InvictusWingsSRL/QiskitTutorials
|
InvictusWingsSRL
|
#Libraries needed to implement and simulate quantum circuits
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, transpile, qasm2, qasm3
from qiskit_aer import Aer
from qiskit.primitives import BackendSampler
#Custem functions to simplify answers
import Our_Qiskit_Functions as oq #a part of the library presented in arXiv:1903.04359v1.
import numpy as np
import math as m
import scipy as sci
#Initialize backends simulators to visualize circuits
S_simulator = Aer.backends(name='statevector_simulator')[0]
M_simulator = Aer.backends(name='qasm_simulator')[0]
N = 3
s = np.zeros(N)
for i in range(N):
s[i] = m.floor(2*np.random.rand())
inputs = np.zeros(2**N)
outputs = []
for o in range(2**N):
inputs[o] = o
outputs.append(o)
f = np.zeros(2**N)
for j in range(2**N):
out = outputs[int(m.floor(len(outputs)*np.random.rand()))]
f[j] = out
f[int(oq.From_Binary(oq.Oplus(oq.Binary(j, 2**N),s)))] = out
outputs.remove(out)
print(' s: ', s)
print(' ')
print(' inputs: ', inputs)
print('outputs: ', f)
q = QuantumRegister(2, name='q')
anc=QuantumRegister(2, name='anc')
S_qc=QuantumCircuit(q,anc,name='qc')
S_qc.h(q[0])
S_qc.h(q[1])
print('___________Initial state_______________')
oq.Wavefunction(S_qc, sustem=[2,2])
S_qc,s,f = oq.Blackbox_g_S(2, S_qc, q, anc)
print('\ns = ', s)
print('\n__________________After g__________')
oq.Wavefunction(S_qc, systems=[2,2,1], show_systems=[True,True,False])
S_qc.h(q[0])
S_qc.h(q[1])
print('\n___________Afeter H^2_______________')
oq.Wavefunction(S_qc, systems=[2,2,1], show_systems=[True,True,False]);
q = QuantumRegister(3, name='q')
c = ClassicalRegister(3,name='c')
anc=QuantumRegister(3, name='anc')
S_qc=QuantumCircuit(q,anc,c, name='qc')
for i in range(3):
S_qc.h(q[i])
S_qc, s, f = oq.Blackbox_g_S(3, S_qc, q, anc)
for i in range(3):
S_qc.h(q[i])
S_qc.measure(q,c)
run_quantum = True
while(run_quantum):
M = oq.Measurement(S_qc, shots = 20, return_M = True, print_M = False)
if len(list(M.keys())) >= 4:
run_quantum = False
print('Measurement Results: ', M)
Equations = []
for i in range(len(list(M.keys()))):
if list(M.keys())[i] != '000':
Equations.append([int(list(M.keys())[i][0]), int(list(M.keys())[i][1]), int(list(M.keys())[i][2])])
s_primes = oq.Simons_Solver(Equations,3)
print('\ncandidate: ', s_primes)
print('\n hidden: ', s)
q = QuantumRegister(3, name='q')
c = ClassicalRegister(3,name='c')
anc=QuantumRegister(3, name='anc')
S_qc=QuantumCircuit(q,anc,c, name='qc')
for i in range(3):
S_qc.h(q[i])
S_qc, s, f = oq.Blackbox_g_S(3, S_qc, q, anc)
for i in range(3):
S_qc.h(q[i])
S_qc.measure(q,c)
run_quantum = True
Equations = []
Results = []
quantum_runs = 0
while(run_quantum):
quantum_runs += 1
M = oq.Measurement(S_qc, shots = 20, return_M = True, print_M = False)
new_result = True
for r in range(len(Results)):
if list(M.keys())[0] == Results[r]:
new_result = False
break
if new_result:
Results.append(list(M.keys())[0])
Equations.append([int(list(M.keys())[0][0]), int(list(M.keys())[0][1]), int(list(M.keys())[0][2])])
s_primes = oq.Simons_Solver(Equations, 3)
if len(s_primes) == 1:
run_quantum = False
print('\n candidate: ', s_primes)
print('\n hidden: ', s)
print('\nunique measurements: ', Results)
print('\n quantum runs: ', quantum_runs)
Q = 4
q = QuantumRegister(Q, name='q')
c = ClassicalRegister(Q,name='c')
anc=QuantumRegister(Q, name='anc')
S_qc=QuantumCircuit(q,anc,c, name='qc')
S_qc, s = oq.Simons_Quantum(Q, S_qc, q, c, anc)
sp, r, qr = oq.Simons_Classical(Q, S_qc)
print('\n candidate: ', sp)
print('\n hidden: ', s)
print('\nunique measurements: ', r)
print('\n quantum runs: ', qr)
|
https://github.com/InvictusWingsSRL/QiskitTutorials
|
InvictusWingsSRL
|
#Libraries needed to implement and simulate quantum circuits
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, transpile, qasm2, qasm3
from qiskit_aer import Aer
from qiskit.primitives import BackendSampler
#Custem functions to simplify answers
import Our_Qiskit_Functions as oq #a part of the library presented in arXiv:1903.04359v1.
import numpy as np
import math as m
import scipy as sci
#Initialize backends simulators to visualize circuits
S_simulator = Aer.backends(name='statevector_simulator')[0]
M_simulator = Aer.backends(name='qasm_simulator')[0]
N = 3
q = QuantumRegister(N, name='q')
qc = QuantumCircuit(q,name='qc')
for i in range(N):
qc.h(q[i])
oq.Wavefunction(qc);
N = 3
q = QuantumRegister(N, name='q')
c = ClassicalRegister(N, name = 'c')
qc = QuantumCircuit(q,c,name='qc')
for i in range(N):
qc.h(q[i])
qc.measure(q,c)
oq.Measurement(qc,shots=1000)
q = QuantumRegister(2, name='q')
G_qc = QuantumCircuit(q,name='qc')
G_qc.h(q[0])
G_qc.h(q[1])
G_qc.cz(q[0],q[1])
print('___________Initial State____________')
oq.Wavefunction(G_qc)
print('\nX_Transformation: |00> <----> |11>')
oq.X_Transformation(G_qc, q, [0,0])
print('\n__________ After X(0) + X(1) ______')
oq.Wavefunction(G_qc);
q = QuantumRegister(2, name='q')
G_qc = QuantumCircuit(q,name='qc')
marked=[0,1]
G_qc.h(q[0])
G_qc.h(q[1])
G_qc.cz(q[0],q[1])
G_qc.x(q[0])
print('___________Initial State____________')
oq.Wavefunction(G_qc)
oq.X_Transformation(G_qc, q, marked)
print('\n__________ X(0) ______')
oq.Wavefunction(G_qc)
oq.X_Transformation(G_qc,q, marked)
print('\n__________ X(0) ______')
oq.Wavefunction(G_qc);
q = QuantumRegister(3, name='q')
anc = QuantumRegister(1, name='anc')
n_anc = QuantumRegister(1, name='nanc')
G_qc = QuantumCircuit(q, anc, n_anc,name='qc')
marked = [0,1,0]
G_qc.h(q[0])
G_qc.h(q[1])
G_qc.h(q[2])
G_qc.x(anc[0])
print('___________Initial State____________')
oq.Wavefunction(G_qc, systems=[3,1,1], show_systems=[True,False,False])
G_qc.h(anc[0])
oq.X_Transformation(G_qc,q,marked)
print('\n___________H(q[3]) + X_Transformation____________')
oq.Wavefunction(G_qc, systems=[3,1,1], show_systems=[True,True,False])
oq.n_NOT(G_qc,q, anc[0],n_anc)
print('\n___________n_NOT____________')
oq.Wavefunction(G_qc, systems=[3,1,1], show_systems=[True,True,False])
oq.X_Transformation(G_qc,q,marked)
G_qc.h(anc[0])
print('\n___________X_Transformation + H(q[3])____________')
oq.Wavefunction(G_qc, systems=[3,1,1], show_systems=[True,True,False]);
q = QuantumRegister(3, name='q')
anc = QuantumRegister(1, name='anc')
n_anc = QuantumRegister(1, name='nanc')
G_qc = QuantumCircuit(q, anc, n_anc,name='qc')
marked = [0,1,0]
G_qc.h(q[0])
G_qc.h(q[1])
G_qc.h(q[2])
G_qc.x(anc[0])
print('___________Initial State____________')
oq.Wavefunction(G_qc, systems=[3,1,1], show_systems=[True,False,False])
oq.Grover_Oracle(marked, G_qc, q, anc, n_anc)
print('\n___________Final State____________')
oq.Wavefunction(G_qc, systems=[3,1,1], show_systems=[True,True,False]);
q = QuantumRegister(2, name='q')
anc = QuantumRegister(1, name='anc')
n_anc = QuantumRegister(1, name='nanc')
G_qc = QuantumCircuit(q, anc, name='qc')
marked = [1,0]
G_qc.h(q[0])
G_qc.h(q[1])
G_qc.x(anc[0])
print('___________Initial State____________')
oq.Wavefunction(G_qc, systems=[2,1], show_systems=[True,False])
oq.Grover_Oracle(marked, G_qc, q, anc, n_anc)
print('\n___________Grover Oracle: ',marked,'____________')
oq.Wavefunction(G_qc, systems=[2,1], show_systems=[True,False])
G_qc.h(q[0])
G_qc.h(q[1])
oq.Grover_Oracle([0,0], G_qc, q, anc, n_anc)
G_qc.h(q[0])
G_qc.h(q[1])
print('\n___________After Grover Diffusion____________')
oq.Wavefunction(G_qc, systems=[2,1], show_systems=[True,False]);
q = QuantumRegister(2, name='q')
anc = QuantumRegister(1, name='anc')
n_anc = QuantumRegister(1, name='nanc')
G_qc = QuantumCircuit(q, anc, name='qc')
marked = [1,0]
G_qc.h(q[0])
G_qc.h(q[1])
G_qc.x(anc[0])
print('___________Initial State____________')
oq.Wavefunction(G_qc, systems=[2,1], show_systems=[True,False])
oq.Grover_Oracle(marked, G_qc, q, anc, n_anc)
print('\n___________Grover Oracle: ',marked,'____________')
oq.Wavefunction(G_qc, systems=[2,1], show_systems=[True,False])
G_qc.h(q[0])
G_qc.h(q[1])
print('\n___________H^2 transformation____________')
oq.Wavefunction(G_qc, systems=[2,1], show_systems=[True,False])
oq.Grover_Oracle([0,0], G_qc, q, anc, n_anc)
print('\n___________Grover Oracle: [0, 0]____________')
oq.Wavefunction(G_qc, systems=[2,1], show_systems=[True,False])
G_qc.h(q[0])
G_qc.h(q[1])
print('\n___________H^2 transformation____________')
oq.Wavefunction(G_qc, systems=[2,1], show_systems=[True,False]);
q = QuantumRegister(2, name='q')
anc = QuantumRegister(1, name='anc')
n_anc = QuantumRegister(1, name='nanc')
G_qc = QuantumCircuit(q, anc, name='qc')
marked = [1,0]
G_qc.h(q[0])
G_qc.id(q[1])
G_qc.x(anc[0])
print('___________Initial State____________')
oq.Wavefunction(G_qc, systems=[2,1], show_systems=[True,False])
G_qc.h(q[0])
G_qc.h(q[1])
oq.Grover_Oracle([0,0], G_qc, q, anc, n_anc)
G_qc.h(q[0])
G_qc.h(q[1])
print('\n___________After Grover____________')
oq.Wavefunction(G_qc, systems=[2,1], show_systems=[True,False]);
q = QuantumRegister(2, name='q')
anc = QuantumRegister(1, name='anc')
n_anc = QuantumRegister(1, name='nanc')
G_qc = QuantumCircuit(q, anc, name='qc')
marked = [1,0]
G_qc.h(q[0])
G_qc.h(q[1])
G_qc.x(anc[0])
print('___________Initial State____________')
oq.Wavefunction(G_qc, systems=[2,1], show_systems=[True,False])
oq.Grover_Oracle(marked, G_qc, q, anc, n_anc)
print('\n___________Grover Oracle: |01>____________')
oq.Wavefunction(G_qc, systems=[2,1], show_systems=[True,False])
G_qc.h(q[0])
G_qc.h(q[1])
print('\n___________H^2 transformation____________')
oq.Wavefunction(G_qc, systems=[2,1], show_systems=[True,False])
oq.Grover_Oracle([0,1], G_qc, q, anc, n_anc)
oq.Grover_Oracle([1,0], G_qc, q, anc, n_anc)
oq.Grover_Oracle([1,1], G_qc, q, anc, n_anc)
print('\n___________Flipping the sign on: |01> |10> |11>____________')
oq.Wavefunction(G_qc, systems=[2,1], show_systems=[True,False])
G_qc.h(q[0])
G_qc.h(q[1])
print('\n___________H^2 transformation____________')
oq.Wavefunction(G_qc, systems=[2,1], show_systems=[True,False]);
q = QuantumRegister(3, name='q')
anc = QuantumRegister(1, name='anc')
n_anc = QuantumRegister(1, name='nanc')
G_qc = QuantumCircuit(q, anc, n_anc,name='qc')
marked = [1,1,0]
G_qc.h(q[0])
G_qc.h(q[1])
G_qc.h(q[2])
G_qc.x(anc[0])
print('___________Initial State____________')
oq.Wavefunction(G_qc, systems=[3,1,1], show_systems=[True,False,False])
iterations = 3
for i in range(iterations):
oq.Grover_Oracle(marked, G_qc, q, anc, n_anc)
oq.Grover_Diffusion(marked, G_qc, q, anc, n_anc)
print('\n___________',i+1,' Grover iteration____________')
oq.Wavefunction(G_qc, systems=[3,1,1], show_systems=[True,False,False])
Q = 4
marked = [0,1,1,0]
G_qc, q, an1, an2, c = oq.Grover(Q, marked)
oq.Wavefunction(G_qc, systems=[Q,1,Q-2], show_systems=[True,False,False], column = True)
print(' ')
G_qc.measure(q,c)
print('\n_________Measurement Results_________')
oq.Measurement(G_qc, shots = 100);
|
https://github.com/InvictusWingsSRL/QiskitTutorials
|
InvictusWingsSRL
|
#Libraries needed to implement and simulate quantum circuits
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, transpile, qasm2, qasm3
from qiskit_aer import Aer
from qiskit.primitives import BackendSampler
#Custem functions to simplify answers
import Our_Qiskit_Functions as oq #a part of the library presented in arXiv:1903.04359v1.
import numpy as np
import math as m
import scipy as sci
#Initialize backends simulators to visualize circuits
S_simulator = Aer.backends(name='statevector_simulator')[0]
M_simulator = Aer.backends(name='qasm_simulator')[0]
def XOR(a,b):
if( (a+b)==1 ):
return 1
else:
return 0
def OR(a,b):
if( (a+b)>=1 ):
return 1
else:
return 0
def AND(a,b):
if( (a+b)==2 ):
return 1
else:
return 0
#====================================
a = [1,1,0,0]
b = [0,1,1,1]
C = 0
Sum = []
for i in range( len(a) ):
xor1 = XOR(a[0-i-1],b[0-i-1])
S = XOR(xor1,C)
and1 = AND(a[0-i-1],b[0-i-1])
and2 = AND(xor1,C)
C = OR(and1,and2)
Sum.insert(0,S)
if( C == 1 ):
Sum.insert(0,C)
print('Adding a = ',a,' + b = ',b,' ===> ',Sum)
q = QuantumRegister(3,name='q')
qc= QuantumCircuit(q,name='qc')
#------------------------------
qc.h( q[0] )
qc.h( q[1] )
qc.h( q[2] )
qc.p( 3*m.pi/2, q[0] )
qc.p( m.pi, q[1] )
qc.p( 0, q[2] )
oq.Wavefunction(qc);
q = QuantumRegister(3,name='q')
qc= QuantumCircuit(q,name='qc')
#------------------------------
qc.x( q[0] )
qc.x( q[1] )
oq.QFT(qc,q,3)
oq.Wavefunction(qc);
qa = QuantumRegister(2,name='a')
qb = QuantumRegister(2,name='b')
qc = QuantumCircuit(qa,qb,name='qc')
qc.x( qa[1] )
qc.x( qb[0] )
oq.Wavefunction(qc,systems=[2,2]);
qa = QuantumRegister(2,name='a')
qb = QuantumRegister(2,name='b')
qc = QuantumCircuit(qa,qb,name='qc')
#------------------------------------
qc.x( qa[1] )
qc.x( qb[0] )
print('_____ States to Add Together _____')
oq.Wavefunction(qc,systems=[2,2])
oq.QFT(qc,qa,2)
#----------------------------- phase contributions from |b>
qc.cp( m.pi, qb[0], qa[0] )
qc.cp( m.pi/2, qb[1], qa[0] )
qc.cp( m.pi, qb[1], qa[1] )
#-----------------------------
oq.QFT_dgr(qc,qa,2)
print('\n___ Sum Stored in |a> ___')
oq.Wavefunction(qc,systems=[2,2],show_systems=[True,False]);
A_States = [[0,1],[1,0],[1,1]]
B_States = [[1,0],[1,1]]
#------------------------------------
for a in range(len(A_States)):
A = A_States[a]
for b in range(len(B_States)):
B = B_States[b]
qa = QuantumRegister(2,name='a')
qb = QuantumRegister(2,name='b')
qc = QuantumCircuit(qa,qb,name='qc')
#-----------------------------------
if(A[0]==1):
qc.x( qa[0] )
if(A[1]==1):
qc.x( qa[1] )
if(B[0]==1):
qc.x( qb[0] )
if(B[1]==1):
qc.x( qb[1] )
oq.QFT(qc,qa,2)
qc.cp( m.pi, qb[0], qa[0] )
qc.cp( m.pi/2, qb[1], qa[0] )
qc.cp( m.pi, qb[1], qa[1] )
oq.QFT_dgr(qc,qa,2)
print('\nA:',A,' B:',B)
oq.Wavefunction(qc,systems=[2,2],show_systems=[True,False])
qa = QuantumRegister(3,name='a')
qb = QuantumRegister(2,name='b')
qc = QuantumCircuit(qa,qb,name='qc')
#-----------------------------------
qc.x( qa[1] )
qc.x( qb[0] )
qc.x( qb[1] )
print('_____ States to Add Together _____')
oq.Wavefunction(qc,systems=[3,2])
oq.QFT(qc,qa,3)
#------------------------------ phase contributions from |b>
qc.cp( m.pi/2, qb[0], qa[0] )
qc.cp( m.pi/4, qb[1], qa[0] )
qc.cp( m.pi, qb[0], qa[1] )
qc.cp( m.pi/2, qb[1], qa[1] )
qc.cp( m.pi, qb[1], qa[2] )
#------------------------------
oq.QFT_dgr(qc,qa,3)
print('\n___ Sum Stored in |a> ___')
oq.Wavefunction(qc,systems=[3,2],show_systems=[True,False]);
A = [0,1,1,0]
B = [1,1,0,1] #A and B need to be arrays of equal length (don't include the extra 0 qubit for A)
print('States to Add Together: ',A,' + ',B)
#=========================================
qa = QuantumRegister(len(A)+1,name='a')
qb = QuantumRegister(len(B),name='b')
qc = QuantumCircuit(qa,qb,name='qc')
#--------------------------------------
oq.Quantum_Adder(qc,qa,qb,A,B)
print('\n___ Sum Stored in |a> ___')
oq.Wavefunction(qc,systems=[len(A)+1,len(B)],show_systems=[True,False]);
qa = QuantumRegister(3,name='a')
qb = QuantumRegister(3,name='b')
qc = QuantumCircuit(qa,qb,name='qc')
#-----------------------------------
qc.x( qa[0] )
qc.x( qa[1] )
qc.x( qb[1] )
qc.x( qb[2] )
print('____ States to Subtract ____')
oq.Wavefunction(qc,systems=[3,3])
oq.QFT(qc,qa,3)
#------------------------------ phase contributions from |b>
qc.cp( -m.pi, qb[0], qa[0] )
qc.cp( -m.pi/2, qb[1], qa[0] )
qc.cp( -m.pi/4, qb[2], qa[0] )
qc.cp( -m.pi, qb[1], qa[1] )
qc.cp( -m.pi/2, qb[2], qa[1] )
qc.cp( -m.pi, qb[2], qa[2] )
#------------------------------
oq.QFT_dgr(qc,qa,3)
print('\n___ Difference Stored in |a> ___')
oq.Wavefunction(qc,systems=[3,3],show_systems=[True,False]);
|
https://github.com/InvictusWingsSRL/QiskitTutorials
|
InvictusWingsSRL
|
#Libraries needed to implement and simulate quantum circuits
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, transpile, qasm2, qasm3
from qiskit_aer import Aer
from qiskit.primitives import BackendSampler
#Custem functions to simplify answers
import Our_Qiskit_Functions as oq #a part of the library presented in arXiv:1903.04359v1.
import numpy as np
import math as m
import scipy as sci
#Initialize backends simulators to visualize circuits
S_simulator = Aer.backends(name='statevector_simulator')[0]
M_simulator = Aer.backends(name='qasm_simulator')[0]
q = QuantumRegister(4,name='q')
H_qc = QuantumCircuit(q,name='qc')
H_qc.x(q[0])
H_qc.id(q[1])
H_qc.x(q[2])
print('_____Initial State_________')
oq.Wavefunction(H_qc)
H_qc.h(q[0])
H_qc.x(q[1])
H_qc.y(q[2])
H_qc.z(q[3])
print('\n_____Operator H + X + Y + Z_________')
oq.Wavefunction(H_qc)
H_qc.h(q[0])
H_qc.x(q[1])
H_qc.y(q[2])
H_qc.z(q[3])
print('\n_____Operator H + X + Y + Z_________')
oq.Wavefunction(H_qc);
q = QuantumRegister(1,name='q')
XZ_qc = QuantumCircuit(q,name='qc')
XZ_qc.id(q[0])
print('_____Initial State_________')
oq.Wavefunction(XZ_qc)
XZ_qc.x(q[0])
XZ_qc.z(q[0])
print('\n_____Operator XZ_________')
oq.Wavefunction(XZ_qc)
XZ_qc.x(q[0])
XZ_qc.z(q[0])
print('\n_____Operator XZ_________')
oq.Wavefunction(XZ_qc);
q = QuantumRegister(1,name='q')
XZ_qc = QuantumCircuit(q,name='qc')
XZ_qc.id(q[0])
print('_____Initial State_________')
oq.Wavefunction(XZ_qc)
XZ_qc.x(q[0])
XZ_qc.z(q[0])
print('\n_____Operator XZ_________')
oq.Wavefunction(XZ_qc)
XZ_qc.z(q[0])
XZ_qc.x(q[0])
print('\n_____Operator ZX_________')
oq.Wavefunction(XZ_qc);
q = QuantumRegister(2,name='q')
F_qc = QuantumCircuit(q,name='qc')
F_qc.x(q[0])
F_qc.h(q[0])
F_qc.x(q[1])
F_qc.h(q[1])
print('_____Initial State_________')
oq.Wavefunction(F_qc)
F_qc.h(q[0])
F_qc.cp(m.pi/2,q[1],q[0])
F_qc.h(q[1])
print('\n_____After QFT_________')
oq.Wavefunction(F_qc);
q = QuantumRegister(3,name='q')
F_qc = QuantumCircuit(q,name='qc')
F_qc.x(q[2])
print('_____Initial State_________')
oq.Wavefunction(F_qc)
#---------------------------- qubit 0
F_qc.h(q[0])
F_qc.cp(m.pi/2,q[1],q[0])
F_qc.cp(m.pi/4,q[2],q[0])
#---------------------------- qubit 1
F_qc.h(q[1])
F_qc.cp(m.pi/4,q[2],q[1])
#---------------------------- qubit 2
F_qc.h(q[2])
print('\n_____After QFT_________')
oq.Wavefunction(F_qc);
q = QuantumRegister(2,name='q')
F_qc = QuantumCircuit(q,name='qc')
F_qc.x(q[0])
F_qc.h(q[0])
F_qc.x(q[1])
F_qc.h(q[1])
print('_____Initial State_________')
oq.Wavefunction(F_qc)
oq.QFT(F_qc,q,2)
print('\n_____First QFT_________')
oq.Wavefunction(F_qc)
oq.QFT(F_qc,q,2)
print('\n_____Second QFT_________')
oq.Wavefunction(F_qc);
q = QuantumRegister(2,name='q')
F_qc = QuantumCircuit(q,name='qc')
F_qc.x(q[0])
F_qc.h(q[0])
F_qc.x(q[1])
F_qc.h(q[1])
print('_____Initial State_________')
oq.Wavefunction(F_qc)
print(' ')
F_qc.h(q[0])
F_qc.cp(m.pi/2,q[1],q[0])
F_qc.h(q[1])
print('_____QFT_________')
oq.Wavefunction(F_qc)
print(' ')
F_qc.h(q[1])
F_qc.cp(-m.pi/2,q[1],q[0])
F_qc.h(q[0])
print('_____Inverse QFT_________')
oq.Wavefunction(F_qc);
q = QuantumRegister(2,name='q')
F_qc = QuantumCircuit(q,name='qc')
F_qc.x(q[0])
F_qc.h(q[0])
F_qc.x(q[1])
F_qc.h(q[1])
print('_____Initial State_________')
oq.Wavefunction(F_qc)
oq.QFT(F_qc,q,2)
print('\n_____QFT_________')
oq.Wavefunction(F_qc)
oq.QFT_dgr(F_qc,q,2)
print('\n_____Inverse QFT_________')
oq.Wavefunction(F_qc);
X = [0,1/m.sqrt(8),0,0,0,0,0,0]
FX = oq.DFT(X, inverse = True)
print('______DFT\u2020_________')
for i in range(len(FX)):
print ('State: ',oq.Binary(i,2**3), ' Amplitude: ', FX[i])
#===================================================================
q = QuantumRegister(3, name='q')
qc = QuantumCircuit(q, name='qc')
qc.x(q[2])
oq.QFT(qc,q,3)
print('\n_____QFT________')
oq.Wavefunction(qc);
X = [0,1/m.sqrt(8),0,0,0,0,0,0]
FX = oq.DFT(X, inverse = True)
print('______DFT\u2020_________')
for i in range(len(FX)):
print ('State: ',oq.Binary(i,2**3), ' Amplitude: ', FX[i])
#===================================================================
q = QuantumRegister(3, name='q')
qc = QuantumCircuit(q, name='qc')
qc.x(q[2])
oq.QFT(qc,q,3)
qc.swap(q[0],q[2])
print('\n_____QFT________')
oq.Wavefunction(qc);
q = QuantumRegister(2, name='q')
anc = QuantumRegister(1, name='anc')
FG_qc = QuantumCircuit(q, anc, name='qc')
marked = [1,0]
FG_qc.x(anc[0])
print('marked state: ',marked)
print(' ')
oq.QFT(FG_qc,q,2)
print('_____Initial State (QFT)_________')
oq.Wavefunction(FG_qc, systems=[2,1], show_systems=[True,False])
print(' ')
oq.X_Transformation(FG_qc, q, marked)
FG_qc.h(anc[0])
FG_qc.ccx(q[0],q[1],anc[0])
oq.X_Transformation(FG_qc,q,marked)
FG_qc.h(anc[0])
print('__________Flip the marked state_____________')
oq.Wavefunction(FG_qc, systems=[2,1], show_systems=[True,False])
print(' ')
oq.QFT(FG_qc,q,2)
print('_____QFT_________')
oq.Wavefunction(FG_qc, systems=[2,1], show_systems=[True,False])
print(' ')
FG_qc.h(anc[0])
oq.X_Transformation(FG_qc, q, [0,0])
FG_qc.ccx(q[0],q[1],anc[0])
FG_qc.h(anc[0])
oq.X_Transformation(FG_qc,q,[0,0])
print('__________Flip the |00> state_____________')
oq.Wavefunction(FG_qc, systems=[2,1], show_systems=[True,False])
print(' ')
oq.QFT_dgr(FG_qc,q,2)
print('_____QFT_dgr_________')
oq.Wavefunction(FG_qc, systems=[2,1], show_systems=[True,False]);
X = [0,1/m.sqrt(8),0,0,0,0,0,0]
FX = oq.DFT(X, inverse = True)
print('______DFT\u2020_________')
for i in range(len(FX)):
print ('State: ',oq.Binary(i,2**3), ' Amplitude: ', FX[i])
#===================================================================
q = QuantumRegister(3, name='q')
qc = QuantumCircuit(q, name='qc')
qc.x(q[2])
oq.QFT(qc,q,3,swap=True)
print('\n_____QFT________')
oq.Wavefunction(qc);
qc.draw(output='mpl')
|
https://github.com/InvictusWingsSRL/QiskitTutorials
|
InvictusWingsSRL
|
from qiskit import ClassicalRegister, QuantumRegister, QuantumCircuit, transpile, qasm2, qasm3
from qiskit_aer import Aer
from qiskit.primitives import BackendSampler
import Our_Qiskit_Functions as oq
import numpy as np
import math as m
import random
def f(x):
if( (x==5) or (x==12) or (x==17) or (x==21) ):
return 1
else:
return 0
#=====================================
N = [2,5,8,12,13,17,21,24,30,31,32,39]
count = 0
M = []
#--------------------------
for i in np.arange(len(N)):
if( f(N[i])==1 ):
count = count + 1
M.append( N[i] )
print('Solution: ',count,'\n M: ',M)
marked = ['010','011','110']
Q = len(marked[0])
iters = 1
#=========================================
q = QuantumRegister(Q,name='q')
a1 = QuantumRegister(1,name='a1')
a2 = QuantumRegister(Q-2,name='a2')
qc = QuantumCircuit(q,a1,a2,name='qc')
#------------------------------------------
for j in np.arange(Q):
qc.h( q[int(j)] )
qc.x( a1[0] )
for i in np.arange( iters ):
for j in np.arange(len(marked)):
M = list(marked[j])
for k in np.arange(len(M)):
if(M[k]=='1'):
M[k] = 1
else:
M[k] = 0
oq.Grover_Oracle(M, qc, q, a1, a2)
oq.Grover_Diffusion(M, qc, q, a1, a2)
oq.Wavefunction(qc,systems=[Q,Q-2,1],show_systems=[True,False,False]);
marked = ['010','011','110']
Q = len(marked[0])
iters = 2
#=========================================
q = QuantumRegister(Q,name='q')
a1 = QuantumRegister(1,name='a1')
a2 = QuantumRegister(Q-2,name='a2')
qc = QuantumCircuit(q,a1,a2,name='qc')
#------------------------------------------
for j in np.arange(Q):
qc.h( q[int(j)] )
qc.x( a1[0] )
qc,q,a1,a2 = oq.Multi_Grover(q,a1,a2,qc,marked,iters)
oq.Wavefunction(qc,systems=[Q,Q-2,1],show_systems=[True,False,False]);
marked = ['01010','01100','00101']
Q = len(marked[0])
iters = 2
#=========================================
q = QuantumRegister(Q,name='q')
a1 = QuantumRegister(1,name='a1')
a2 = QuantumRegister(Q-2,name='a2')
qc = QuantumCircuit(q,a1,a2,name='qc')
#------------------------------------------
for j in np.arange(Q):
qc.h( q[int(j)] )
qc.x( a1[0] )
qc,q,a1,a2 = oq.Multi_Grover(q,a1,a2,qc,marked,iters)
oq.Wavefunction(qc,systems=[Q,Q-2,1],show_systems=[True,False,False],column=True);
runs = 100000
Avgs = [0,0,0,0,0]
#=======================================
for r in np.arange(runs):
Measured = []
Trials = []
t = 0
while( len(Measured) != 5 ):
Measurement = round( 0.500000001+ random.random()*5 )
t = t + 1
new_state = True
for i in np.arange( len(Measured) ):
if( Measurement == Measured[i] ):
new_state = False
if(new_state == True):
Measured.append(Measurement)
Trials.append(t)
for i in np.arange(5):
Avgs[i] = Avgs[i] + Trials[i]
#=======================================
for j in np.arange(5):
Avgs[j] = round(Avgs[j]/runs,3)
print('Average Trials to Find Each State: \n\n1) ', Avgs[0], ' 2)',Avgs[1], ' 3)',Avgs[2], ' 4)',Avgs[3], ' 5)',Avgs[4]);
for i in np.arange(4):
q = QuantumRegister(2,name='q')
qc= QuantumCircuit(q,name='qc')
if( (i == 1) or (i == 3) ):
qc.x( q[1] )
if( (i == 2) or (i == 3) ):
qc.x( q[0] )
print('\n___ Initial State ___')
oq.Wavefunction(qc)
qc.ch( q[0],q[1] )
print('\n___ After Control-Hadamard ___')
oq.Wavefunction(qc)
if( i <= 2):
print('\n------------------------------------')
q = QuantumRegister(2,name='q')
a = QuantumRegister(1,name='a')
qc= QuantumCircuit(q,a,name='qc')
#--------------------------------
qc.h( q[0] )
qc.h( q[1] )
print('__ Initial State __')
oq.Wavefunction(qc,systems=[2,1],show_systems=[True,False])
qc.x( a[0] )
qc.h( a[0] )
#------------------------- Oracle
qc.barrier()
qc.x( q[1] )
qc.ccx( q[0],q[1],a[0] )
qc.x( q[1] )
#------------------------- Diffusion
qc.barrier()
qc.h( q[0] )
qc.h( q[1] )
qc.x( q[0] )
qc.x( q[1] )
qc.ccx( q[0],q[1],a[0] )
qc.x( q[0] )
qc.x( q[1] )
qc.h( q[0] )
qc.h( q[1] )
qc.barrier()
qc.h( a[0] )
qc.x( a[0] )
print('\n__ After Grovers __')
oq.Wavefunction(qc,systems=[2,1],show_systems=[True,False]);
qc.draw('mpl')
c = QuantumRegister(1,name='c')
q = QuantumRegister(2,name='q')
a1 = QuantumRegister(1,name='a1')
a2 = QuantumRegister(1,name='a2')
qc= QuantumCircuit(c,q,a1,a2,name='qc')
qc.x( c[0] )
qc.ch( c[0], q[0] )
qc.ch( c[0], q[1] )
print('__ Initial State __')
oq.Wavefunction(qc,systems=[1,2,1,1],show_systems=[True,True,False,False])
qc.cx( c[0], a2[0] )
qc.ch( c[0], a2[0] )
#------------------------- Oracle
qc.barrier()
qc.cx( c[0], q[1] )
qc.ccx( q[0], q[1], a1[0] )
qc.ccx( c[0], a1[0], a2[0] )
qc.ccx( q[0], q[1], a1[0] )
qc.cx( c[0], q[1] )
#------------------------- Diffusion
qc.barrier()
qc.ch( c[0], q[0] )
qc.ch( c[0], q[1] )
qc.cx( c[0], q[0] )
qc.cx( c[0], q[1] )
qc.ccx( q[0], q[1], a1[0] )
qc.ccx( c[0], a1[0], a2[0] )
qc.ccx( q[0], q[1], a1[0] )
qc.cx( c[0], q[0] )
qc.cx( c[0], q[1] )
qc.ch( c[0], q[0] )
qc.ch( c[0], q[1] )
qc.barrier()
qc.ch( c[0], a2[0] )
qc.cx( c[0], a2[0] )
print('\n__ After c-Grovers __')
oq.Wavefunction(qc,systems=[1,2,1,1],show_systems=[True,True,False,False]);
qc.draw('mpl')
q = QuantumRegister(3,name='q')
a1= QuantumRegister(1,name='a1')
a2= QuantumRegister(1,name='a2')
qc= QuantumCircuit(q,a1,a2,name='qc')
marked = [1,0,1]
for i in np.arange(3):
qc.h( q[int(i)] )
qc.x( a1[0] )
oq.Wavefunction(qc, systems=[3,1,1], show_systems=[True,False,False])
for i in np.arange(2):
oq.Grover_Oracle(marked, qc, q, a1, a2)
oq.Grover_Diffusion(marked, qc, q, a1, a2)
print('\n____ Grover Iterations: ',int(i+1),' ____')
oq.Wavefunction(qc, systems=[3,1,1], show_systems=[True,False,False])
marked = ['101','110','111']
Q = len(marked[0])
iters = 1
#=========================================
q = QuantumRegister(Q,name='q')
a1 = QuantumRegister(1,name='a1')
a2 = QuantumRegister(Q-2,name='a2')
qc = QuantumCircuit(q,a1,a2,name='qc')
#------------------------------------------
for j in np.arange(Q):
qc.h( q[int(j)] )
qc.x( a1[0] )
qc,q,a1,a2 = oq.Multi_Grover(q,a1,a2,qc,marked,iters)
print('_____ 1 Grover Iteration M = 3 _____ ')
oq.Wavefunction(qc,systems=[Q,Q-2,1],show_systems=[True,False,False]);
marked = ['10111','11000']
Q = len(marked[0])
N = 2**Q
M = len(marked)
iters = int(round( (m.pi/2 - np.arctan( m.sqrt( M/(N-M) ) ) ) / ( 2 * np.arcsin( m.sqrt(M/N) ) ) ) )
print('N: ',N,' M: ',M,' Optimal Iterations: ',iters,'\n\n')
#=========================================
q = QuantumRegister(Q,name='q')
a1 = QuantumRegister(1,name='a1')
a2 = QuantumRegister(Q-2,name='a2')
qc = QuantumCircuit(q,a1,a2,name='qc')
#------------------------------------------
for j in np.arange(Q):
qc.h( q[int(j)] )
qc.x( a1[0] )
qc,q,a1,a2 = oq.Multi_Grover(q,a1,a2,qc,marked,iters)
oq.Wavefunction(qc,systems=[Q,Q-2,1],show_systems=[True,False,False],column=True);
E_plus = [ 1.0j/m.sqrt(10),1.0j/m.sqrt(10),1.0j/m.sqrt(10),1.0/m.sqrt(6),
1.0j/m.sqrt(10),1.0/m.sqrt(6),1.0j/m.sqrt(10),1.0/m.sqrt(6) ]
#=========================================================================
q = QuantumRegister(3,name='q')
qc= QuantumCircuit(q,name='qc')
#------------------------------
qc.initialize( E_plus, q )
oq.Wavefunction( qc );
Marked = ['101','110','111']
Q = len(Marked[0])
E_plus = [ 1.0j/m.sqrt(10),1.0j/m.sqrt(10),1.0j/m.sqrt(10),1.0/m.sqrt(6),
1.0j/m.sqrt(10),1.0/m.sqrt(6),1.0j/m.sqrt(10),1.0/m.sqrt(6) ]
#========================================================================
q = QuantumRegister(Q,name='q')
u = QuantumRegister(Q,name='u')
a1 = QuantumRegister(Q-1,name='a1')
a2 = QuantumRegister(1,name='a2')
c = ClassicalRegister(Q,name='c')
qc= QuantumCircuit(q,u,a1,a2,c,name='qc')
#------------------------------------
qc.h( q[0] )
qc.h( q[1] )
qc.h( q[2] )
qc.initialize(E_plus,u)
qc.x( a2[0] )
qc.h( a2[0] )
#-------------------------
for i in np.arange(Q):
for j in np.arange(2**i):
oq.C_Grover(qc,q[int(3-(i+1))],u,a1,a2,Marked,proper=True)
#-------------------------
qc.h( a2[0] )
qc.x( a2[0] )
oq.QFT_dgr( qc,q,3,swap=True )
#--------------------------
qc.measure(q,c)
oq.Measurement( qc, shots=10000 );
#qc.draw('mpl')
Marked = ['101','110','111']
Q = len(Marked[0])
E_minus = [ -1.0j/m.sqrt(10),-1.0j/m.sqrt(10),-1.0j/m.sqrt(10),1.0/m.sqrt(6),
-1.0j/m.sqrt(10),1.0/m.sqrt(6),-1.0j/m.sqrt(10),1.0/m.sqrt(6) ]
#========================================================================
q = QuantumRegister(Q,name='q')
u = QuantumRegister(Q,name='u')
a1 = QuantumRegister(Q-1,name='a1')
a2 = QuantumRegister(1,name='a2')
c = ClassicalRegister(Q,name='c')
qc= QuantumCircuit(q,u,a1,a2,c,name='qc')
#------------------------------------
qc.h( q[0] )
qc.h( q[1] )
qc.h( q[2] )
qc.initialize(E_minus,u)
qc.x( a2[0] )
qc.h( a2[0] )
#-------------------------
for i in np.arange(Q):
for j in np.arange(2**i):
oq.C_Grover(qc,q[int(3-(i+1))],u,a1,a2,Marked,proper=True)
#-------------------------
qc.h( a2[0] )
qc.x( a2[0] )
oq.QFT_dgr( qc,q,3,swap=True )
#--------------------------
qc.measure(q,c)
oq.Measurement( qc, shots=10000 );
theta_vec = [0.79,-0.79]
for i in np.arange(len(theta_vec)):
theta = theta_vec[i]
n = 3
#=====================================
q1 = QuantumRegister(n,name='q1')
q2 = QuantumRegister(1,name='q2')
c = ClassicalRegister(n,name='c')
qc = QuantumCircuit(q1,q2,c,name='qc')
#--------------------------------------
for i in np.arange(n):
qc.h(q1[int(i)])
qc.x( q2[0] )
phi = 2*m.pi*theta
for j in np.arange(n):
for k in np.arange(2**j):
qc.cp( phi, q1[int(n-1-j)], q2[0] )
oq.QFT_dgr( qc,q1,n,swap=True )
#--------------------------------------
print('\n___ QPE for Theta = ',theta,' ___')
qc.measure(q1,c)
oq.Measurement( qc, shots=10000, systems=[n,2] )
Precision = 6
Grover_Size = 4
#---------------
D = 2**Precision
N = 2**Grover_Size
M = int(1 + (2**Grover_Size-2)*random.random() )
#M = 1
Marked = []
for m1 in np.arange(2**Grover_Size):
Marked.append( oq.Binary(int(m1),2**Grover_Size) )
random.shuffle(Marked)
for m2 in np.arange( (int(2**Grover_Size)-M) ):
Marked.pop()
#Marked.append(oq.Binary(1,2**Grover_Size))
#=========================================
q = QuantumRegister(Precision,name='q')
u = QuantumRegister(Grover_Size,name='u')
a1 = QuantumRegister(Grover_Size-1,name='a1')
a2 = QuantumRegister(1,name='a2')
c = ClassicalRegister(Precision,name='c')
qc= QuantumCircuit(q,u,a1,a2,c,name='qc')
#-----------------------------------------
for p in np.arange(Precision):
qc.h( q[int(p)] )
for g in np.arange(Grover_Size):
qc.h( u[int(g)] )
qc.x( a2[0] )
qc.h( a2[0] )
qc.barrier()
#-------------------------
for i in np.arange(Precision):
ctrlQubit = q[int(Precision-(i+1))]
for _ in np.arange(2**i):
oq.C_Grover(qc,ctrlQubit,u,a1,a2,Marked,proper=True)
#-------------------------
qc.barrier()
qc.h( a2[0] )
qc.x( a2[0] )
qc.barrier()
oq.QFT_dgr( qc,q,Precision,swap=True )
qc.measure(q,c)
trials=10000
Meas = oq.Measurement( qc, shots=trials, return_M=True, print_M=True )
#-------------------------
print('\nCorrect M: ',len(Marked),' \u03B8: ',round(2*np.arcsin(m.sqrt(len(Marked)/(2**Grover_Size)))/(2*m.pi),5))
C,S = oq.Most_Probable(Meas,1)
theta_QPE = oq.From_Binary(S[0])/D
print('\nMost Probable State: |'+str(S[0])+'> ----> \u03B8: ',round(theta_QPE,4))
if( theta_QPE >= 0.5 ):
theta_QPE = 1 - theta_QPE
print('\nInterpretting Measurement as 1 - \u03B8: ',round(theta_QPE,4),' Corresponding M: ',int(round(2**Grover_Size * np.sin(m.pi * theta_QPE)**2)))
else:
print('\nInterpretting Measurement as \u03B8: ',round(theta_QPE,4),' Corresponding M: ',int(round(2**Grover_Size * np.sin(m.pi * theta_QPE)**2)))
|
https://github.com/InvictusWingsSRL/QiskitTutorials
|
InvictusWingsSRL
|
#Libraries needed to implement and simulate quantum circuits
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, transpile, qasm2, qasm3
from qiskit_aer import Aer
from qiskit.primitives import BackendSampler
from qiskit.providers.basic_provider import BasicProvider # instead of BasicAer
from qiskit.visualization import plot_histogram
#Custem functions to simplify answers
import Our_Qiskit_Functions as oq #a part of the library presented in arXiv:1903.04359v1.
import numpy as np
import math as m
import scipy as sci
import random
import matplotlib.pyplot as plt
#Initialize backends simulators to visualize circuits
S_simulator = Aer.backends(name='statevector_simulator')[0]
M_simulator = Aer.backends(name='qasm_simulator')[0]
alpha = 2*m.pi/3
U = np.array([ [ np.cos(alpha) , np.sin(alpha) ],
[ -np.sin(alpha) , np.cos(alpha) ] ])
#---------------------------------------------------
e = 0.5*(-1+m.sqrt(3)*1.0j)
v = 1.0/m.sqrt(2)*np.array( [-1.0j,1] )
#---------------------------------------------------
print('____ Unitary Matrix ____\n',U)
print( '\n U |u> = ',np.dot(U,v))
print( 'e^{2\u03C0i\u03C6} |u> = ',e * v)
q = QuantumRegister(3,name='q' )
qc= QuantumCircuit(q,name='qc')
#-------------------------------
qc.x( q[1] )
qc.x( q[2] )
print('____ Initial State ____')
oq.Wavefunction(qc)
qc.swap( q[0], q[2] )
oq.QFT_dgr( qc,q,3 )
print('\n____ After QFT\u2020 ____')
oq.Wavefunction(qc)
#======================================
print('\n ____ QFT\u2020 Expression ____')
for k in np.arange( 8 ):
phase = 1.0/(m.sqrt(8)) * np.exp( -1.0j*m.pi*( (3*k)/4 ) )
print( 'state: ',oq.Binary(int(k),8),' phase: ',round(phase.real,4)+round(phase.imag,4)*1.0j )
n = 3
theta = 0.52
print('Theta = ',theta,' n = ',n,'\n---------------------------')
#===================
state = []
bstate = []
bdec = []
for i in range(2**n):
state.append(0)
bstate.append(oq.Binary(i,2**n))
bc = 0
for i2 in range(len(bstate[i])):
bc = bc + ( 1.0/(2**(i2+1)))*bstate[i][i2]
bdec.append(bc)
#-------------------------------------------------------------
for y in range(2**n):
for x in range(2**n):
state[y] = state[y] + 1.0/(2**n) * np.exp( (-2.0j*np.pi*x/(2**n))*(y-2**n*theta) )
#--------------------------------------------------------------
for j in np.arange(2**n):
print('Probability: ',round( abs(state[j])**2,4 ),' State: ',bstate[j],' Binary Decimal: ',bdec[j])
x = []
y = []
n = 3
for k in np.arange( 1000 ):
if( k != 500 ):
phi = -5 + k/100.
x.append( phi )
y.append( 1/(2**(2*n)) * abs( (-1 + np.exp(2.0j*m.pi*phi) )/(-1 + np.exp(2.0j*m.pi*phi/(2**n))) )**2 )
else:
x.append(phi)
y.append(1)
plt.plot(x,y)
plt.axis([-5,5,0,1])
plt.show()
n = 4
theta = 0.52
print('Theta = ',theta,' n = ',n,'\n---------------------------')
#===================
state = []
bstate = []
bdec = []
for i in range(2**n):
state.append(0)
bstate.append(oq.Binary(i,2**n))
bc = 0
for i2 in range(len(bstate[i])):
bc = bc + ( 1.0/(2**(i2+1)))*bstate[i][i2]
bdec.append(bc)
#-------------------------------------------------------------
for y in range(2**n):
for x in range(2**n):
state[y] = state[y] + 1.0/(2**n) * np.exp( (-2.0j*np.pi*x/(2**n))*(y-2**n*theta) )
#--------------------------------------------------------------
for j in np.arange(2**n):
print('Probability: ',round( abs(state[j])**2,4 ),' State: ',bstate[j],' Binary Decimal: ',bdec[j])
Prob = [ 0.0028,0.0028,0.0031,0.0037,0.0049,0.0076,0.0144,0.0424,0.7063,0.1571,0.0265,0.011,0.0064,0.0044,0.0035,0.003 ]
Measured = np.zeros( len(Prob) )
trials = 10000
n = 4
#======================================== Simulate measurements on the final system
for t in range(trials):
M = random.random()
p = 0
for s in range( len(Prob) ):
if( p < M < (p + Prob[s]) ):
Measured[s] = Measured[s] + 1
p = p + Prob[s]
#---------------------------------------
MD = {}
for i in range( len(Prob) ):
state = oq.Binary(int(i),2**n)
state_str = ''
for j in range(len(state)):
state_str = state_str+str(state[j])
MD[state_str] = int( Measured[i] )
MP = oq.Most_Probable(MD,2)
for mp in range(2):
MP[0][mp] = MP[0][mp]/trials
#======================================== Compute phi using the most probable state
phi,theta = oq.QPE_phi(MP)
print('\nMost Probable State: |'+str(MP[1][0])+'> Probability: ',round(MP[0][0],5))
print('\nCorresponding \u03A6: ',phi,'\n\nApproximate \u03B8: ',round(theta,5))
n = 3
q1 = QuantumRegister(n,name='q1')
q2 = QuantumRegister(1,name='q2')
qc = QuantumCircuit(q1,q2,name='qc')
theta = 0.52
phi = 2*m.pi*theta
#---------------------------------------------------
for i in np.arange(n):
qc.h(q1[int(i)])
qc.x( q2[0] )
for j in np.arange(n):
for k in np.arange(2**j):
qc.cp( phi, q1[int(n-1-j)], q2[0] )
print('\n___ After Control-U Operations ___')
oq.Wavefunction( qc, systems=[n,1] )
#---------------------------------------------------
Phases = [np.exp(4.0j*phi),np.exp(2.0j*phi),np.exp(1.0j*phi)]
print(' ')
for i in np.arange(8):
state = oq.Binary(int(i),8)
phase = m.sqrt(1/8)
for j in np.arange(3):
if(state[j]==1):
phase = phase*Phases[j]
print('State: ',state,' Phase: ',round(phase.real,5)+round(phase.imag,5)*1.0j)
n = 3
q1 = QuantumRegister(n,name='q1')
q2 = QuantumRegister(1,name='q2')
c = ClassicalRegister(n,name='c')
qc = QuantumCircuit(q1,q2,c,name='qc')
theta = 0.666
#---------------------------------------------------
for i in np.arange(n):
qc.h(q1[int(i)])
qc.x( q2[0] )
phi = 2*m.pi*theta
for j in np.arange(n):
for k in np.arange(2**j):
qc.cp( phi, q1[int(n-1-j)], q2[0] )
print('\n___ After QFT_dgr ___')
oq.QFT_dgr( qc,q1,n,swap=True )
oq.Wavefunction( qc, systems=[n,1] )
#---------------------------------------------------
qc.measure(q1,c)
#results = oq.execute(qc, BasicProvider().get_backend('qasm_simulator'), shots=10000).result()
results = oq.execute(qc, S_simulator, shots=10000).result()
plot_histogram({key: value / 10000. for key, value in results.get_counts().items()})
n1 = 3
n2 = 2
phases = []
for p in np.arange( n2 ):
phases.append( round( 2*m.pi*random.random(),4 ) )
theta = round( sum(phases)/(2*m.pi),5)
if( theta > 1 ):
theta = round( theta - m.floor(theta),5)
#=================================
q = QuantumRegister(n1,name='q')
qu = QuantumRegister(n2,name='qu')
c = ClassicalRegister(n1,name='c')
qc = QuantumCircuit(q,qu,c,name='qc')
#----------------------------------
for i in np.arange(n1):
qc.h( q[int(i)] )
for i2 in np.arange(n2):
qc.x( qu[int(i2)] )
qc.barrier()
for j in np.arange(n1):
for j2 in np.arange(2**j):
for j3 in np.arange(n2):
qc.cp( phases[int(j3)], q[int(n1-1-j)], qu[int(j3)] )
qc.barrier()
oq.QFT_dgr( qc,q,n1,swap=True )
#---------------------------------------------------
print('Phases: ',phases)
print('\nCombined \u03B8: ',theta)
qc.measure(q,c)
#results = execute(qc, BasicAer.get_backend('qasm_simulator'), shots=10000).result()
results = oq.execute(qc, S_simulator, shots=10000).result()
plot_histogram({key: value / 10000. for key, value in results.get_counts().items()})
print(qc)
n1 = 5
n2 = 3
phases = []
trials = 10000
for p in np.arange( n2 ):
phases.append( round( 2*m.pi*random.random(),4 ) )
theta = round( sum(phases)/(2*m.pi),5)
if( theta > 1 ):
theta = round( theta - m.floor(theta),5)
#================================================================== QPE Circuit
q = QuantumRegister(n1,name='q')
qu = QuantumRegister(n2,name='qu')
c = ClassicalRegister(n1,name='c')
qc = QuantumCircuit(q,qu,c,name='qc')
#-------------------------------------
for i in np.arange(n1):
qc.h( q[int(i)] )
for i2 in np.arange(n2):
qc.x( qu[int(i2)] )
for j in np.arange(n1):
for j2 in np.arange(2**j):
for j3 in np.arange(n2):
qc.cp( phases[int(j3)], q[int(n1-1-j)], qu[int(j3)] )
oq.QFT_dgr( qc,q,n1,swap=True )
#==================================================================
print('Phases: ',phases,' Combined \u03B8: ',theta)
qc.measure(q,c)
M = oq.Measurement( qc,systems=[n1,n2],shots=trials,return_M=True,print_M=False )
MP = oq.Most_Probable(M,2)
for mp in np.arange(2):
MP[0][mp] = MP[0][mp]/trials
phi,theta = oq.QPE_phi(MP)
print('\nMost Probable State: |'+str(MP[1][0])+'> Probability: ',round(MP[0][0],5))
print('\nSecond Most Probable: |'+str(MP[1][1])+'> Probability: ',round(MP[0][1],5))
print('\nCorresponding \u03A6: ',phi,'\n\nApproximate \u03B8: ',round(theta,5))
|
https://github.com/InvictusWingsSRL/QiskitTutorials
|
InvictusWingsSRL
|
from qiskit import ClassicalRegister, QuantumRegister, QuantumCircuit, transpile, qasm2, qasm3
from qiskit_aer import Aer
from qiskit.primitives import BackendSampler
from qiskit.providers.basic_provider import BasicProvider # instead of BasicAer
import Our_Qiskit_Functions as oq
import numpy as np
import math as m
import random
import matplotlib
import matplotlib.pyplot as plt
S_simulator = Aer.backends(name='statevector_simulator')[0]
def Letter_Code(x):
'''
Input: integer --> Converts an integer between 0 and 26 into a letter of the alphabet (26 for space)
Input: string --> Converts a lower case letter or space to an integer
'''
if( type(x) == type(1) ):
code = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',' ']
if( x < len(code) ):
return code[x]
else:
return '?'
if( type(x) == type('s') ):
code = {'a':0,'b':1,'c':2,'d':3,'e':4,'f':5,'g':6,'h':7,'i':8,'j':9,'k':10,'l':11,'m':12,'n':13,'o':14,'p':15,'q':16,'r':17,'s':18,'t':19,'u':20,'v':21,'w':22,'x':23,'y':24,'z':25,' ':26}
return code[x]
#====================================
p = 3
q = 11
n = p*q
e = 3
d = 7
message = 'hello qubits how are you'
#------------------------------------ Encrypt the message
M = list(message)
M_rsa = []
for i in np.arange(len(M)):
M[i] = Letter_Code(M[i])
M_rsa.append( M[i]**e%n )
#------------------------------------ Decrypt the message
encrypted_message = ''
decrypted_message = ''
for j in np.arange(len(M_rsa)):
encrypted_message = encrypted_message+Letter_Code( M_rsa[j] )
decrypted_message = decrypted_message+Letter_Code( (M_rsa[j]**d)%n )
print(' Encoded Messege: ',M,'\n\nEncrypted Message: ',M_rsa,'\n\n ',encrypted_message,'\n\nDecrypted Message: ', decrypted_message)
N = 1703
#N = 1827
S = int(m.ceil(m.sqrt(N)))
#====================
i = 0
found = False
while i<10000:
Y2 = (S+i)**2 % N
Y = m.sqrt(Y2)
if( ( Y == m.floor(Y) ) and (Y2!=1) ):
found = True
X = int(S+i)
X2 = X**2
break
else:
i = i + 1
if( found==True ):
print('N: ',N)
print('\nX: ', X, ' Y: ',Y)
print('\nX^2: ',X2,' Y^2: ',Y2)
print('\n(X+Y): ',int(X+Y),' (X-Y): ',int(X-Y))
print('\nfactors of N: ',int(oq.GCD(N,X+Y)),' ',int(oq.GCD(N,X-Y)) )
A_i = 462
B_i = 70
#---------------------
gcd = False
GCD = 0
#=====================
A = A_i
B = B_i
while( gcd == False ):
r = A - B
print('A: ',A,' B: ',B,' r:',r)
if( r == 0 ):
gcd = True
GCD = B
else:
if( r > B ):
A = r
else:
A = B
B = r
print('------------------------------------------------------\nGreatest Common Denominator between',A_i,'and',B_i,': ',GCD)
A = 123456
B = 789
print( A % B )
oq.Euclids_Alg(A_i, B_i)
N = 35
a = int( random.randint(2,N-2) )
print('N: ',N)
print('a: ',a)
gcd = oq.Euclids_Alg(N,a)
if(gcd > 1):
print('a has a common factor with N ---> GCD: ',gcd)
else:
print('a has no common factor with N ---> GCD: ',gcd)
r = oq.r_Finder(a,N)
print('period r: ',r)
print('\nVerify ',a,'^',r,' = 1 (mod ',N,'): ',(a**r)%N)
if( ((r)%2 == 0) and ( a**(int(r/2))%N != int(N-1) )):
print('r is a good, proceed')
else:
print('r is not good, start over')
if((r)%2 != 0):
print('r is odd: ',r)
if(a**(int(r/2))%N == int(N-1)):
print('a^(r/2) (mod N) = N-1')
print('a^(r/2): ',int(a**(r/2.0)))
factor1 = oq.Euclids_Alg(int(a**(r/2.0)+1),N)
factor2 = oq.Euclids_Alg(int(a**(r/2.0)-1),N)
print('\nfactors of N: ',int(factor1),' ',int(factor2),' ( N is',N,')')
N = 35
a = int( random.randint(2,N-2) )
print('a: ',a)
#-------------------------------#
if( oq.Euclids_Alg(N,a) == 1 ):
r = oq.r_Finder(a,N)
print( 'r: ',r )
if( ((r)%2 == 0) and (a**(int(r/2))%N != int(N-1) )):
print('\nfactors of N: ',int(oq.Euclids_Alg(int(a**(r/2.0)+1),N)),' ',int(oq.Euclids_Alg(int(a**(r/2.0)-1),N)),' ( N is',N,')')
else:
if((r)%2 != 0):
print('Condition Not Satisfied: r is odd: ',r)
if(a**(int(r/2))%N == int(N-1)):
print('Condition Not Satisfied: a^(r/2) (mod N) = N-1: ',a**(int(r/2))%N)
else:
print('a has a GCD with N: ',oq.Euclids_Alg(N,a))
N = 35
coprimes = [4,6,8,9,11,13,16]
a = coprimes[int( random.randint(0,len(coprimes)-1) )]
print('N = ',N,' a = ',a,'\n')
#-------------------------------
for i in np.arange(10):
mod_N = a**int(i) % N
print('a^',i,' (mod N): ',mod_N)
S1 = [round(random.random()),round(random.random()),round(random.random()),round(random.random())]
a = 8
N = 15
print('N: ',N,' a: ',a)
#====================================
q1 = QuantumRegister(4,name='q1')
q2 = QuantumRegister(4,name='q2')
qc = QuantumCircuit(q1,q2,name='qc')
#------------------------------------
for i in np.arange(4):
if(S1[i]==1):
qc.x( q1[int(i)] )
print('\n_____ Initial State _____')
oq.Wavefunction(qc,systems=[4,4])
#------------------------------------
S1_num = S1[0] + 2*S1[1] + 4*S1[2] + 8*S1[3]
S2_num = a**(S1_num) % N
print('\nState 1: ',S1_num,' Desired State 2: ',a,'^',S1_num,' ( mod ',N,') = ',S2_num)
#------------------------------------
for j in np.arange(4):
if( S2_num >= 2**(3-j) ):
qc.x( q2[int(3-j)] )
S2_num = S2_num - 2**(3-j)
print('\n_____ After Modulo Operation_____')
oq.Wavefunction(qc,systems=[4,4]);
a = 8
N = 15
q1_state = [1,0,1,0]
q2_state = oq.BinaryL( a**(int( oq.From_BinaryLSB(q1_state,'L') ))%N, 2**4 )
print('a = ',a,' N = ',N)
print('\nInput State: ',q1_state,' Desired Modulo State: ',q2_state)
#=====================================
q1 = QuantumRegister(4,name='q1')
q2 = QuantumRegister(4,name='q2')
an = QuantumRegister(3,name='a')
qc = QuantumCircuit(q1,q2,an,name='qc')
#--------------------------------------
qc.h(q1[0])
qc.h(q1[2])
qc.cx( q1[0], q1[1] )
qc.cx( q1[2], q1[1])
print('\n_____ Initial State _____')
oq.Wavefunction(qc,systems=[4,4,3],show_systems=[True,True,False])
qc.barrier()
#-------------------------------------- |1010> state
oq.X_Transformation(qc,q1,q1_state)
qc.ccx( q1[0], q1[1], an[0] )
qc.ccx( q1[2], an[0], an[1] )
qc.ccx( q1[3], an[1], an[2] )
for i in np.arange(len(q2_state)):
if( q2_state[i]==1 ):
qc.cx( an[2], q2[int(i)] )
qc.ccx( q1[3], an[1], an[2] )
qc.ccx( q1[2], an[0], an[1] )
qc.ccx( q1[0], q1[1], an[0] )
oq.X_Transformation(qc,q1,q1_state)
print('\n_____ After Modulo Operation _____')
oq.Wavefunction(qc,systems=[4,4,3],show_systems=[True,True,False])
print(qc)
a = 8
N = 15
Q = 4
print('a: ',a,' N: ',N)
#=====================================
q1 = QuantumRegister(Q,name='q1')
q2 = QuantumRegister(Q,name='q2')
an = QuantumRegister(Q-1,name='a')
qc = QuantumCircuit(q1,q2,an,name='qc')
#--------------------------------------
for i in np.arange(Q):
qc.h(q1[int(i)])
print('\n_____ Initial State _____')
oq.Wavefunction(qc,systems=[4,4,3],show_systems=[True,True,False])
oq.Mod_Op(Q,qc,q1,q2,an,a,N)
print('\n_____ After Modulo Operation _____')
oq.Wavefunction(qc,systems=[4,4,3],show_systems=[True,True,False]);
a = 8
N = 15
Q = 4
print('a: ',a,' N: ',N)
#=====================================
q1 = QuantumRegister(Q,name='q1')
q2 = QuantumRegister(Q,name='q2')
an = QuantumRegister(Q-1,name='a')
c = ClassicalRegister(Q,name='c')
qc = QuantumCircuit(q1,q2,an,c,name='qc')
#--------------------------------------
for i in np.arange(Q):
qc.h(q1[int(i)])
print('\n_____ Initial State _____')
oq.Wavefunction(qc,systems=[Q,Q,Q-1],show_systems=[True,True,False])
oq.Mod_Op(Q,qc,q1,q2,an,a,N)
print('\n_____ After Modulo Operation _____')
oq.Wavefunction(qc,systems=[Q,Q,Q-1],show_systems=[True,True,False])
qc.measure(q2,c)
print('\n_____ After Partial Measurement _____')
oq.Wavefunction(qc,systems=[Q,Q,Q-1],show_systems=[True,True,False]);
k = 3
r = 5
a0 = int( (r)*random.random() )
L = k*r
C = np.zeros(r)
C[a0] = 1
print('k = ',k,' r = ',r,' a0 = ',a0,'\n\nOne Cycle: ',C,' L = ',L)
#------------------------------------------
f = []
for i in np.arange(k):
for i2 in np.arange(r):
f.append( int( C[i2] ) )
print('\nPeriodic Function: ',f)
F = oq.DFT(f,inverse=True)
print('\nAfter DFT\u2020: ',F)
#------------------------------------------
F2 = []
for j in np.arange( len(F) ):
F2.append( round(abs(F[j]),3) )
print('\n |F|: ',F2 )
k = int( 2+4*random.random() )
r = int( 2+4*random.random() )
L = k*r
print('k: ',k,' r: ',r,' L: ',L,'\n------------------------------\n')
#================================================
for q in np.arange(L):
n = int(q)
Q = 0
for j in np.arange(k):
Q = Q + np.exp( ((-2*m.pi*1.0j)/L) * n * j * r )
print( 'n: ',n,' \u03A3 = ',round( Q.real,5 ),' + i',round(Q.imag,5) )
N_circle = 1000
x_c = []
y_c = []
#-----------------
for c in np.arange(N_circle+1):
t = (2*m.pi*c)/N_circle
x_c.append( np.cos(t) )
y_c.append( np.sin(t) )
#=================================================
k = 5
r = 4
L = k*r
a0= int(r*random.random())
print('k: ',k,' r: ',r,' L: ',L,' a0: ',a0,'\n--------------------------------------------\n')
for i in np.arange(L):
p1 = np.exp( (-2*m.pi*1.0j/L) * (a0+0*r) * i)
p2 = np.exp( (-2*m.pi*1.0j/L) * (a0+1*r) * i)
p3 = np.exp( (-2*m.pi*1.0j/L) * (a0+2*r) * i)
p4 = np.exp( (-2*m.pi*1.0j/L) * (a0+3*r) * i)
p5 = np.exp( (-2*m.pi*1.0j/L) * (a0+4*r) * i)
#=======================
print('x_'+str(int(i))+' QFT term: ',round((p1+p2+p3+p4+p5).real,4),' + i',round((p1+p2+p3+p4+p5).imag,4))
fig = plt.figure(figsize=(4,4))
plt.scatter( p1.real,p1.imag,s=40,color='blue' )
plt.scatter( p2.real,p2.imag,s=40,color='orange' )
plt.scatter( p3.real,p3.imag,s=40,color='red' )
plt.scatter( p4.real,p4.imag,s=40,color='green' )
plt.scatter( p5.real,p5.imag,s=40,color='purple' )
plt.plot( x_c,y_c,linewidth=0.5 )
plt.show()
a = 8
N = 15
Q = 4
print('a: ',a,' N: ',N)
#=====================================
q1 = QuantumRegister(Q,name='q1')
q2 = QuantumRegister(Q,name='q2')
an = QuantumRegister(Q-1,name='a')
c = ClassicalRegister(Q,name='c')
qc = QuantumCircuit(q1,q2,an,c,name='qc')
#--------------------------------------
for i in np.arange(Q):
qc.h(q1[int(i)])
print('\n_____ Initial State _____')
oq.Wavefunction(qc,systems=[Q,Q,Q-1],show_systems=[True,True,False])
oq.Mod_Op(Q,qc,q1,q2,an,a,N)
print('\n_____ After Modulo Operation _____')
oq.Wavefunction(qc,systems=[Q,Q,Q-1],show_systems=[True,True,False])
qc.measure(q2,c)
oq.QFT_dgr(qc,q1,Q)
print('\n_____ Partial Measurement + QFT\u2020_____')
oq.Wavefunction(qc,systems=[Q,Q,Q-1],show_systems=[True,True,False]);
N = 2.815
#=====================================
q,p,a = oq.ConFrac(N, return_a=True)
print('N = ',N,' = ',p,'/',q)
print('\na constants: ',a)
#-------------------------------------
accuracy = 4
q,p,a = oq.ConFrac(N, a_max=accuracy, return_a=True)
print('\n--------------------------------------\nN = ',N,' \u2248 ',p,'/',q)
print('\na constants: ',a)
a = 8
N = 15
Q = 4
print('a: ',a,' N: ',N)
#=====================================
q1 = QuantumRegister(Q,name='q1')
q2 = QuantumRegister(Q,name='q2')
an = QuantumRegister(Q-1,name='a')
c1 = ClassicalRegister(Q,name='c1')
c2 = ClassicalRegister(Q,name='c2')
qc = QuantumCircuit(q1,q2,an,c1,c2,name='qc')
#--------------------------------------
for i in np.arange(Q):
qc.h(q1[int(i)])
oq.Mod_Op(Q,qc,q1,q2,an,a,N)
print('\n_____ After Modulo Operation _____')
oq.Wavefunction(qc,systems=[Q,Q,Q-1],show_systems=[True,True,False])
qc.measure(q2,c2)
oq.QFT_dgr(qc,q1,Q)
qc.measure(q1,c1)
M = oq.Measurement(qc,shots=1,print_M=False,return_M=True)
print('\n Partial Measurement: |'+list(M.keys())[0][4:8]+'>')
print('\nSystem One Measurement: |'+list(M.keys())[0][0:4]+'>')
#--------------------------------------
S = int(oq.From_Binary(list(list(M.keys())[0][0:4])))
L = 2**Q
print('\nS = ',S,' L = ',L)
if( S != 0 ):
r,mult = oq.ConFrac(1.0*S/L)
print('\nContinued Fractions Result: m = ',mult,' r = ',r)
k = int( 2+4*random.random() )
r = int( 2+4*random.random() )
L = k*r + 1
print('k: ',k,' r: ',r,' L: ',L,'\n------------------------------\n')
#================================================
for q in np.arange(L):
n = int(q)
Q = 0
for j in np.arange(k):
Q = Q + np.exp( ((-2*m.pi*1.0j)/L) * n * j * r )
print( 'n: ',n,' \u03A3 = ',round( Q.real,5 ),' + i',round(Q.imag,5) )
k = int( 4 + 2*random.random() )
r = int( 3 + 5*random.random() )
a0 = int( (r-1)*random.random() )
print('k = ',k,' r = ',r,' a0 = ',a0)
#------------------------------------------
L = k*r
C = np.zeros(r)
C[a0] = 1
#------------------------------------------
f1 = []
f2 = []
for i in np.arange(k):
for i2 in np.arange(r):
f1.append( C[i2] )
f2.append( C[i2] )
f2.append(0)
F1 = oq.DFT(f1,inverse=True)
F2 = oq.DFT(f2,inverse=True)
for q in np.arange( len(F1) ):
F1[q] = round( abs(F1[q]/k)**2 ,4)
F2[q] = round( abs(F2[q]/k)**2 ,4)
F2[-1] = round( abs(F2[-1]/k)**2 ,4)
#==========================================
x_bar = []
for j in np.arange(len(F1)):
x_bar.append(int(j))
plt.bar(x_bar,F1)
x_bar.append(int(j+1))
plt.bar(x_bar,F2,width=0.5)
plt.legend(['Perfect L','L + 1'])
plt.axis([-1, len(F2), 0, 1.3])
plt.show()
r = 7
L = 36
print('r: ',r,' L: ',L,'\n==============================')
#=====================
S = 10
print('\nS = ',S,'\n-----------------------------')
for i in np.arange(4):
q,p = oq.ConFrac(S/L,a_max=int(i+2))
print('order ',int(i+1),' Continued Fractions: '+str(p)+'/'+str(q),' \u2248 ',round(p/q,4))
#---------------------
S = 21
print('\nS = ',S)
for i in np.arange(4):
q,p = oq.ConFrac(S/L,a_max=int(i+2))
print('order ',int(i+1),' Continued Fractions: '+str(p)+'/'+str(q),' \u2248 ',round(p/q,4))
S = 21
L = 36
order = 4
#==================
for i in np.arange(3):
S_new = int( S - 1 + i)
for j in np.arange(3):
L_new = int( L - 1 + j)
if( (S_new!=S) or (L_new!=L) ):
print('\nS = ',S_new,' L = ',L_new,'\n-----------------------------')
for i in np.arange(4):
q,p = oq.ConFrac(S_new/L_new,a_max=int(i+2))
print('order ',int(i+1),' Continued Fractions: '+str(p)+'/'+str(q),' \u2248 ',round(p/q,4))
N = 55
#N=11*13
Q = m.ceil( m.log(N,2) )
nrQubits = 3*Q - 1
print("Number of qubits: ", nrQubits)
L = 2**Q
a = int( 2+ (N-3)*random.random() )
r = oq.r_Finder(a,N)
#=================================================
print('N = ',N,' Q = ',Q,' a = ',a,' Searching For: r =',r)
if( oq.Euclids_Alg(a,N) > 1 ):
print('\na happens to have a factor in common with N: ',oq.Euclids_Alg(a,N))
else:
q1 = QuantumRegister(Q,name='q1')
q2 = QuantumRegister(Q,name='q2')
an = QuantumRegister(Q-1,name='a')
c1 = ClassicalRegister(Q,name='c1')
c2 = ClassicalRegister(Q,name='c2')
qc = QuantumCircuit(q1,q2,an,c1,c2,name='qc')
#----------------------------------------------
for i in np.arange(Q):
qc.h(q1[int(i)])
oq.Mod_Op(Q,qc,q1,q2,an,a,N)
qc.measure(q2,c2)
oq.QFT_dgr(qc,q1,Q)
qc.measure(q1,c1)
M = oq.Measurement(qc,shots=1,print_M=False,return_M=True)
S = int(oq.From_Binary(list(list(M.keys())[0][0:Q])))
#----------------------------------------------
print('\nSystem One Measurement: |'+list(M.keys())[0][0:Q]+'>')
print('\nS = ',S,' L = ',L)
if( S!= 0):
r = oq.Evaluate_S(S,L,a,N)
if( r!=0 ):
print('\nFound the period r = ',r)
if( ((r)%2 == 0) and ( a**(int(r/2))%N != int(N-1) )):
f1 = oq.Euclids_Alg(int(a**(int(r/2))+1),N)
f2 = oq.Euclids_Alg(int(a**(int(r/2))-1),N)
print('\nFactors of N: ',int(f1),' ',int(f2))
else:
if( (r)%2 != 0 ):
print('\nr does not meet criteria for factoring N: r is not even')
else:
print('\nr does not meet criteria for factoring N: a^(r/2) (mod N) = N-1')
else:
print('\nCould not find the period using S, start over')
else:
print('\nMeasured S = 0, start over')
|
https://github.com/InvictusWingsSRL/QiskitTutorials
|
InvictusWingsSRL
|
#%matplotlib widgets
import tkinter
import matplotlib
import matplotlib.pyplot as plt
import ipympl
import IPython
#matplotlib.use('TkAgg')
#matplotlib.use('WebAgg')
from qiskit import ClassicalRegister, QuantumRegister, QuantumCircuit, transpile, qasm2, qasm3
from qiskit_aer import Aer
from qiskit.primitives import BackendSampler
from qiskit.providers.basic_provider import BasicProvider # instead of BasicAer
import Our_Qiskit_Functions as oq
import numpy as np
import math as m
import scipy as sci
import random
import time
from itertools import permutations
S_simulator = Aer.backends(name='statevector_simulator')[0]
%matplotlib ipympl
#%matplotlib notebook
#plt.rcParams['animation.html'] = 'jshtml'
Data = [ [1,1],[4,2],[5,5],[3,6] ]
D_min = [1000,0,0]
D2_min = [1000,0,0]
#----------------------------------------- Searches for centroids within 3 < x < 4 and 3 < y < 4
for j1 in np.arange(1000):
X = 3.0 + j1/1000.0
for j2 in np.arange(1000):
Y = 3.0 + j2/1000.0
D = 0
D2 = 0
for k in np.arange( len(Data) ):
D = D + m.sqrt( (X-Data[k][0])**2 + (Y-Data[k][1])**2 )
D2 = D2 + (X-Data[k][0])**2 + (Y-Data[k][1])**2
if( D < D_min[0] ):
D_min = [ D, X, Y ]
if( D2 < D2_min[0] ):
D2_min = [ D2, X, Y ]
#-----------------------------------------
print('Minimum Distance: ',round(D_min[0],2),' coordinates: (',D_min[1],D_min[2],')')
print('Minimum Distance Squared: ',round(D2_min[0],2),' coordinates: (',D2_min[1],D2_min[2],')')
xs = 0
ys = 0
for x, y in Data:
xs += x
ys += y
xs /= len(Data)
ys /= len(Data)
print('Xc = ', xs, ' Yc = ', ys)
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
ax.axis([-0.2,8.2,-0.2,8.2])
#fig.show()
colors = ['red','limegreen','deepskyblue','gold']
colors2 = ['darkred','darkgreen','darkblue','darkorange']
#--------------------------------------------------------
N = 240
k = 4
#--------------------------------------------------------
Data = oq.k_Data(k,N)
for d in np.arange(len( Data )):
ax.scatter( Data[d][0], Data[d][1], color='black', s=10 )
fig.canvas.draw()
time.sleep(2)
#--------------------------------------------------------
Centroids = oq.Initial_Centroids( k, Data )
Clusters = []
Clusters,old_Clusters = oq.Update_Clusters( Data, Centroids, Clusters )
for c1 in np.arange(len(Clusters)):
for c2 in np.arange( len( Clusters[c1] ) ):
ax.scatter( Clusters[c1][c2][0],Clusters[c1][c2][1], color=colors[c1],s=10 )
ax.scatter( Centroids[c1][0],Centroids[c1][1], color=colors2[c1], marker='x',s=50 )
fig.canvas.draw()
time.sleep(1)
time.sleep(2)
#--------------------------------------------------------
terminate = False
iters = 0
while( (terminate==False) and (iters<50) ):
Centroids,old_Centroids = oq.Update_Centroids(Centroids, Clusters)
Clusters,old_Clusters = oq.Update_Clusters( Data, Centroids, Clusters )
oq.Draw_Data( Clusters, Centroids, old_Centroids, fig, ax, colors, colors2 )
terminate = oq.Check_Termination( Clusters, old_Clusters )
iters = iters + 1
print( 'Clustering Complete: ',iters,' Iterations' )
#fig.show()
a = QuantumRegister(1,name='a')
q = QuantumRegister(2,name='q')
qc= QuantumCircuit(a,q)
qc.h( a[0] )
qc.x( q[1] )
print('____ Before CSWAP ____')
oq.Wavefunction(qc, systems=[1,2])
qc.cswap( a[0], q[0], q[1] )
print('\n____ After CSWAP ____')
oq.Wavefunction(qc, systems=[1,2]);
q = QuantumRegister(3,name='q')
c = ClassicalRegister(1,name='c')
qc= QuantumCircuit(q,c,name='qc')
qc.h( q[1] )
qc.x( q[2] )
qc.barrier()
#------------------------------ The SWAP Test
qc.h( q[0] )
qc.cswap( q[0], q[1], q[2] )
qc.h( q[0] )
qc.measure( q[0], c[0] )
#-------------------------------
oq.Measurement( qc,shots=10000, )
print(' ')
print(qc)
a = QuantumRegister( 1, name='a' )
q1 = QuantumRegister( 2, name='q1' )
q2 = QuantumRegister( 2, name='q2' )
c = ClassicalRegister( 1, name='c' )
qc = QuantumCircuit( a, q1, q2, c )
#=========================================
qc.h( q1[0] )
qc.h( q1[1] )
qc.x( q2[1] )
oq.Wavefunction( qc, systems=[1,2,2], show_systems=[False,True,True] )
qc.barrier()
#-------------------------------- 2-Qubit SWAP Test
qc.h( a[0] )
qc.cswap( a[0], q1[0], q2[0] )
qc.cswap( a[0], q1[1], q2[1] )
qc.h( a[0] )
qc.measure(a,c)
#--------------------------------
print('\n___ Measurement Probabilities on the Control Qubit ___')
oq.Measurement( qc, shots=8000 )
print(' ')
print(qc)
q = QuantumRegister(1)
qc= QuantumCircuit(q)
A = [ 3/5, 4/5 ]
qc.initialize( A, [q[0]] )
oq.Wavefunction( qc );
print( qc.decompose().decompose().decompose() )
A = [1,0,-2,0]
B = [6,-4,0,0]
trials = 50000
#==============================
A_norm = 0
B_norm = 0
D = 0
for i in np.arange(len(A)):
A_norm = A_norm + A[i]**2
B_norm = B_norm + B[i]**2
D = D + (A[i]-B[i])**2
D = m.sqrt(D)
A_norm = m.sqrt(A_norm)
B_norm = m.sqrt(B_norm)
Z = round( A_norm**2 + B_norm**2 )
#------------------------------
phi_vec = [A_norm/m.sqrt(Z),-B_norm/m.sqrt(Z)]
psi_vec = []
for i in np.arange(len(A)):
psi_vec.append( (A[i]/A_norm) /m.sqrt(2) )
psi_vec.append( (B[i]/B_norm) /m.sqrt(2) )
#==============================
a = QuantumRegister(1,name='a')
q = QuantumRegister(4,name='q')
c = ClassicalRegister(1,name='c')
qc= QuantumCircuit(a,q,c)
qc.initialize( phi_vec, q[0] )
qc.initialize( psi_vec, q[1:4] )
#------------------------------ The SWAP Test
qc.h( a[0] )
qc.cswap( a[0], q[0], q[1] )
qc.h( a[0] )
qc.measure(a,c)
#------------------------------
M = oq.Measurement(qc,shots=trials,return_M=True,print_M=False)
print('Euclidean Distance: ',round(D,4))
print('\n DistCalc Distance: ',round( m.sqrt((((M['0']/trials - 0.5)/0.5)*2*Z)),4) );
Shots = 10000
Points = [ [-1,1], [3,4], [7,7], [6,8] ]
Norm_Points = []
for p in np.arange( len(Points) ):
Norm_Points.append( Points[p]/np.linalg.norm(Points[p]) )
#==================================================
for p2 in np.arange( len(Norm_Points)-1 ):
q = QuantumRegister(3)
c = ClassicalRegister(1)
qc= QuantumCircuit(q,c)
qc.initialize( Norm_Points[int(p2)], [q[1]] )
qc.initialize( Norm_Points[-1], [q[2]] )
#--------------------------------------------------
IP = oq.SWAP_Test( qc, q[0], q[1], q[2], c[0], Shots )
print('\nComparing Points: ',Points[p2],' & ',Points[-1],'\n',IP,'|0> ',Shots-IP,'|1>')
Shots = 10000
Points = [ [2,3], [4,6], [8,12], [12,18] ]
Norm_Points = []
for p in np.arange( len(Points) ):
Norm_Points.append( Points[p]/np.linalg.norm(Points[p]) )
#==================================================
for p2 in np.arange( len(Norm_Points)-1 ):
q = QuantumRegister(3)
c = ClassicalRegister(1)
qc= QuantumCircuit(q,c)
qc.initialize( Norm_Points[int(p2)], [q[1]] )
qc.initialize( Norm_Points[-1], [q[2]] )
#--------------------------------------------------
IP = oq.SWAP_Test( qc, q[0], q[1], q[2], c[0], Shots )
print('\nComparing Points: ',Points[p2],' & ',Points[-1],'\n',IP,'|0> ',Shots-IP,'|1>')
Point = [ 0.12, -0.15 ]
Centroids = [ [-0.38,0.61] , [-0.09,-0.34] , [0.52,0.29] ]
#-----------------------
fig = plt.figure(figsize=(4,4))
ax = fig.add_subplot(1,1,1)
ax.axis([-1,1,-1,1])
#fig.show()
#-----------------------
plt.plot(Point[0], Point[1], 'ro')
markers = ['gx','bx','kx']
for c in np.arange( len(Centroids) ):
plt.plot(Centroids[c][0], Centroids[c][1], markers[c])
fig.canvas.draw()
Shots = 10000
Point = [ 0.12, -0.15 ]
Centroids = [ [-0.38,0.61] , [-0.09,-0.34] , [0.52,0.29] ]
Bloch_Point = [ (Point[0]+1)*m.pi/2, (Point[1]+1)*m.pi/2 ]
Bloch_Cents = []
for c in np.arange( len(Centroids) ):
Bloch_Cents.append( [ (Centroids[c][0]+1)*m.pi/2, (Centroids[c][1]+1)*m.pi/2 ] )
#====================================
colors = ['Green','Blue','Black']
for c2 in np.arange( len(Bloch_Cents) ):
q = QuantumRegister(3)
c = ClassicalRegister(1)
qc= QuantumCircuit(q,c)
qc.u( Bloch_Point[0], Bloch_Point[1], 0, [q[1]] )
qc.u( Bloch_Cents[c2][0], Bloch_Cents[c2][1], 0, [q[2]] )
#--------------------------------------------------
IP = oq.SWAP_Test( qc, q[0], q[1], q[2], c[0], Shots )
print('\n\nComparing Points: ',Centroids[c2],' & ',Point,' (',colors[c2],' Centroid )\n\n',IP,'|0> ',Shots-IP,'|1>' )
size = 100
Shots = 10000
Data_Space = [-1,1,-1,1]
Point = [0.12,-0.15] # Example Point
#Point = [-0.6,0.]
#Point = [0,-0.6]
#Point = [-0.9,0.]
#Point = [0,-0.9]
t = (Point[0]+1)*m.pi/2
p = (Point[1]+1)*m.pi/2
OL_grid = np.zeros(shape=(size,size))
#========================================================
for x in np.arange(size):
t2 = (( (-1 + 2*(x/size)) + 1) * m.pi / 2)
for y in np.arange(size):
p2 = (( (-1 + 2*(y/size)) + 1) * m.pi / 2)
#---------------------------------
q = QuantumRegister( 3, name='q' )
c = ClassicalRegister( 1, name='c' )
qc= QuantumCircuit( q,c, name='qc' )
qc.u( t, p, 0, q[1] )
qc.u( t2, p2, 0, q[2] )
#---------------------------------
IP = oq.SWAP_Test( qc, q[0], q[1], q[2], c[0], Shots )
if( IP < 5000 ):
IP = 5000
OL_grid[int(size-y-1),int(x)] = m.sqrt((1.0*IP/Shots-0.5)*2)
#========================================================
fig, ax = plt.subplots()
show_ticks = False
show_text = False
oq.Heatmap(OL_grid, show_text, show_ticks, ax, "viridis", "Inner Product")
plt.plot((Point[0]+1)*size/2, size-(((Point[1]+1))*size/2), 'ro')
Centroids = [ [-0.38,0.61] , [-0.09,-0.34] , [0.52,0.29] ]
colors = ['green','blue','black']
for c in np.arange(len(Centroids)):
plt.scatter((Centroids[c][0]+1)*size/2, size-((Centroids[c][1]+1)*size/2), color='white', marker='s', s=50)
plt.scatter((Centroids[c][0]+1)*size/2, size-((Centroids[c][1]+1)*size/2), color=colors[c], marker='x', s=50)
fig.tight_layout()
#plt.show()
Shots = 10000
Point = [2*random.random()-1,2*random.random()-1]
t = (Point[0]+1)*m.pi/2
p = (Point[1]+1)*m.pi/2
#========================================================
q = QuantumRegister( 3, name='q' )
c = ClassicalRegister( 1, name='c' )
qc= QuantumCircuit( q,c, name='qc' )
qc.u( t, p, 0, q[1] )
qc.u( m.pi-t, p+m.pi, 0, q[2] )
#---------------------------------
IP = oq.SWAP_Test( qc, q[0], q[1], q[2], c[0], Shots )
print('Inner Product Result Bewteen: [',round(t,3),' ,',round(p,3),'] & [',round(m.pi-t,3),' ,',round(p+m.pi,3),'] (θ,Φ) & (π-θ,π+Φ)')
print('\n',IP,' |0>')
size = 100
#-------------------------------------------------------
Data_Space = [-1,1,-1,1]
Point = [0.12,-0.15] # Example Point
t,p = oq.Bloch_State( Point, Data_Space )
#-------------------------------------------------------
OL_grid = np.zeros(shape=(size,size))
#========================================================
for x in np.arange(size):
Xp = Data_Space[0] + (x/size)*(Data_Space[1]-Data_Space[0])
for y in np.arange(size):
Yp = Data_Space[2] + (y/size)*(Data_Space[3]-Data_Space[2])
t2,p2 = oq.Bloch_State( [Xp,Yp], Data_Space )
#-----------------------------
q = QuantumRegister( 3, name='q' )
c = ClassicalRegister( 1, name='c' )
qc= QuantumCircuit( q,c, name='qc' )
qc.u( t, p, 0, q[1] )
qc.u( t2, p2, 0, q[2] )
#-------------
IP = oq.SWAP_Test( qc, q[0], q[1], q[2], c[0], Shots )
if( IP < 5000 ):
IP = 5000
OL_grid[int(size-y-1),int(x)] = m.sqrt((1.0*IP/Shots-0.5)*2)
#========================================================
fig, ax = plt.subplots()
show_ticks = False
show_text = False
oq.Heatmap(OL_grid, show_text, show_ticks, ax, "viridis", "Inner Product")
plt.plot((Point[0]-Data_Space[0])*size/(Data_Space[1]-Data_Space[0]), (Data_Space[3]-Point[1])*size/(Data_Space[3]-Data_Space[2]), 'ro')
Centroids = [ [-0.38,0.61] , [-0.09,-0.34] , [0.52,0.29] ]
colors = ['green','blue','black']
for c in np.arange(len(Centroids)):
plt.scatter((Centroids[c][0]+1)*size/2, size-((Centroids[c][1]+1)*size/2), color='white', marker='s', s=50)
plt.scatter((Centroids[c][0]+1)*size/2, size-((Centroids[c][1]+1)*size/2), color=colors[c], marker='x', s=50)
fig.tight_layout()
plt.show()
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
ax.axis([-0.2,8.2,-0.2,8.2])
#fig.show()
colors = ['red','limegreen','deepskyblue','gold']
colors2 = ['darkred','darkgreen','darkblue','darkorange']
#--------------------------------------------------------
n = 140
k = 4
shots = 500
Data_Space = [0,8,0,8]
#--------------------------------------------------------
Data = oq.k_Data(k,n)
for d in np.arange(len( Data )):
ax.scatter( Data[d][0], Data[d][1], color='black', s=10 )
fig.canvas.draw()
time.sleep(2)
#--------------------------------------------------------
Centroids = oq.Initial_Centroids( k, Data )
Clusters = []
Clusters,old_Clusters = oq.Q_Update_Clusters( Data, Centroids, Clusters, Data_Space, shots )
for c1 in np.arange(len(Clusters)):
for c2 in np.arange( len( Clusters[c1] ) ):
ax.scatter( Clusters[c1][c2][0],Clusters[c1][c2][1], color=colors[c1],s=10 )
ax.scatter( Centroids[c1][0],Centroids[c1][1], color=colors2[c1], marker='x',s=50 )
fig.canvas.draw()
time.sleep(1)
time.sleep(2)
#--------------------------------------------------------
terminate = False
iters = 0
while( (terminate==False) and (iters<50) ):
Centroids,old_Centroids = oq.Update_Centroids(Centroids, Clusters)
Clusters,old_Clusters = oq.Q_Update_Clusters( Data, Centroids, Clusters, Data_Space, shots )
oq.Draw_Data( Clusters, Centroids, old_Centroids, fig, ax, colors, colors2 )
terminate = oq.Check_Termination( Clusters, old_Clusters )
iters = iters + 1
print( 'Clustering Complete: ',iters,' Iterations' )
|
https://github.com/InvictusWingsSRL/QiskitTutorials
|
InvictusWingsSRL
|
from qiskit import ClassicalRegister, QuantumRegister, QuantumCircuit, transpile
from qiskit_aer import Aer
from qiskit.primitives import BackendSampler
#from qiskit.extensions.simulator import snapshot
#from qiskit.tools.visualization import circuit_drawer
import numpy as np
import math as m
import scipy as sci
import random
import time
import matplotlib
import matplotlib.pyplot as plt
import ipywidgets as wd
S_simulator = Aer.backends(name='statevector_simulator')[0]
M_simulator = Aer.backends(name='qasm_simulator')[0]
def execute(circuit, backend, **kwargs):
s = 1024
if 'shots' in kwargs:
s = int( kwargs['shots'] )
new_circuit = transpile(circuit, backend)
return backend.run(new_circuit, shots = s)
#Displaying Results
def Wavefunction( obj , *args, **kwargs):
#Displays the wavefunction of the quantum system
if(type(obj) == QuantumCircuit ):
statevec = execute( obj, S_simulator, shots=1 ).result().get_statevector()
if(type(obj) == np.ndarray):
statevec = obj
sys = False
NL = False
dec = 5
if 'precision' in kwargs:
dec = int( kwargs['precision'] )
if 'column' in kwargs:
NL = kwargs['column']
if 'systems' in kwargs:
systems = kwargs['systems']
sys = True
last_sys = int(len(systems)-1)
show_systems = []
for s_chk in range(len(systems)):
if( type(systems[s_chk]) != int ):
raise Exception('systems must be an array of all integers')
if 'show_systems' in kwargs:
show_systems = kwargs['show_systems']
if( len(systems)!= len(show_systems) ):
raise Exception('systems and show_systems need to be arrays of equal length')
for ls in range(len(show_systems)):
if((show_systems[ls] != True) and (show_systems[ls] != False)):
raise Exception('show_systems must be an array of Truth Values')
if(show_systems[ls] == True):
last_sys = int(ls)
else:
for ss in range(len(systems)):
show_systems.append(True)
wavefunction = ''
qubits = int(m.log(len(statevec),2))
for i in range(int(len(statevec))):
#print(wavefunction)
value = round(statevec[i].real, dec) + round(statevec[i].imag, dec) * 1j
if( (value.real != 0) or (value.imag != 0)):
state = list(Binary(int(i),int(2**qubits)))
state.reverse()
state_str = ''
#print(state)
if( sys == True ): #Systems and SharSystems
k = 0
for s in range(len(systems)):
if(show_systems[s] == True):
if(int(s) != last_sys):
state.insert(int(k + systems[s]), '>|' )
k = int(k + systems[s] + 1)
else:
k = int(k + systems[s])
else:
for s2 in range(systems[s]):
del state[int(k)]
for j in range(len(state)):
if(type(state[j])!= str):
state_str = state_str + str(int(state[j]))
else:
state_str = state_str + state[j]
#print(state_str)
#print(value)
if( (value.real != 0) and (value.imag != 0) ):
if( value.imag > 0):
wavefunction = wavefunction + str(value.real) + '+' + str(value.imag) + 'j |' + state_str + '> '
else:
wavefunction = wavefunction + str(value.real) + '' + str(value.imag) + 'j |' + state_str + '> '
if( (value.real !=0 ) and (value.imag ==0) ):
wavefunction = wavefunction + str(value.real) + ' |' + state_str + '> '
if( (value.real == 0) and (value.imag != 0) ):
wavefunction = wavefunction + str(value.imag) + 'j |' + state_str + '> '
if(NL):
wavefunction = wavefunction + '\n'
#print(NL)
print(wavefunction)
return wavefunction
def Measurement(quantumcircuit, *args, **kwargs):
#Displays the measurement results of a quantum circuit
p_M = True
S = 1
ret = False
NL = False
if 'shots' in kwargs:
S = int(kwargs['shots'])
if 'return_M' in kwargs:
ret = kwargs['return_M']
if 'print_M' in kwargs:
p_M = kwargs['print_M']
if 'column' in kwargs:
NL = kwargs['column']
M1 = execute(quantumcircuit, M_simulator, shots=S).result().get_counts(quantumcircuit)
M2 = {}
k1 = list(M1.keys())
v1 = list(M1.values())
for k in range(len(k1)):
key_list = list(k1[k])
new_key = ''
for j in range(len(key_list)):
new_key = new_key+key_list[len(key_list)-(j+1)]
M2[new_key] = v1[k]
if(p_M):
k2 = list(M2.keys())
v2 = list(M2.values())
measurements = ''
for i in range(len(k2)):
m_str = str(v2[i])+'|'
for j in range(len(k2[i])):
if(k2[i][j] == '0'):
m_str = m_str + '0'
if(k2[i][j] == '1'):
m_str = m_str + '1'
if( k2[i][j] == ' ' ):
m_str = m_str +'>|'
m_str = m_str + '> '
if(NL):
m_str = m_str + '\n'
measurements = measurements + m_str
print(measurements)
if(ret):
return M2
def Most_Probable(M,N):
'''
Input: M (Dictionary) N (integer)
Returns the N most probable states accoding to the measurement counts stored in M
'''
count = []
state = []
if( len(M) < N ):
N = len(M)
for k in range(N):
count.append(0)
state.append(0)
for m in range(len(M)):
new = True
for n in range(N):
if( (list(M.values())[m] > count[n]) and new ):
for i in range( N-(n+1)):
count[-int(1+i)] = count[-int(1+i+1)]
state[-int(1+i)] = state[-int(1+i+1)]
count[int(n)] = list(M.values())[m]
state[int(n)] = list(M.keys())[m]
new = False
return count,state
#Math Operations
def Oplus(bit1,bit2):
'''Adds too bits of O's and 1's (modulo 2)'''
bit = np.zeros(len(bit1))
for i in range( len(bit) ):
if( (bit1[i]+bit2[i])%2 == 0 ):
bit[i] = 0
else:
bit[i] = 1
return bit
def Binary(number,total):
#Converts a number to binary, right to left LSB 152 153 o
qubits = int(m.log(total,2))
N = number
b_num = np.zeros(qubits)
for i in range(qubits):
if( N/((2)**(qubits-i-1)) >= 1 ):
b_num[i] = 1
N = N - 2 ** (qubits-i-1)
B = []
for j in range(len(b_num)):
B.append(int(b_num[j]))
return B
def BinaryL(number,total):
B = Binary(number, total)
B.reverse()
return B
def From_Binary(s):
num = 0
for i in range(len(s)):
num = num + int(s[-(i+1)]) * 2**i
return num
def From_BinaryLSB(S, LSB):
num = 0
for i in range(len(S)):
if(LSB=='R'):
num = num + int(S[-(i+1)]) * 2**i
elif(LSB=='L'):
num = num + int(S[i]) * 2**i
return num
def B2D(in_bi):
len_in = len(in_bi)
in_bi = in_bi[::-1]
dec = 0
for i in range(0,len_in):
if in_bi[i] != '0':
dec += 2**i
return dec
# Custom Gates
def X_Transformation(qc, qreg, state):
#Tranforms the state of the system, applying X gates according to as in the vector 'state'
for j in range(len(state)):
if( int(state[j]) == 0 ):
qc.x( qreg[int(j)] )
def n_NOT(qc, control, target, anc):
#performs an n-NOT gate
n = len(control)
instructions = []
active_ancilla = []
q_unused = []
q = 0
a = 0
while(n > 0):
if(n >= 2):
instructions.append( [control[q], control[q+1], anc[a]] )
active_ancilla.append(a)
a += 1
q += 2
n -= 2
if(n == 1):
q_unused.append(q)
n -= 1
while (len(q_unused) != 0):
if(len(active_ancilla)!=1):
instructions.append( [control[q], anc[active_ancilla[0]], anc[a]] )
del active_ancilla[0]
del q_unused[0]
active_ancilla.append(a)
a += 1
else:
instructions.append( [control[q], anc[active_ancilla[0]], target] )
del active_ancilla[0]
del q_unused[0]
while(len(active_ancilla) != 0):
if( len(active_ancilla) > 2 ):
instructions.append( [anc[active_ancilla[0]], anc[active_ancilla[1]], anc[a]] )
active_ancilla.append(a)
del active_ancilla[0]
del active_ancilla[0]
a += 1
elif( len(active_ancilla) == 2):
instructions.append([anc[active_ancilla[0]], anc[active_ancilla[1]], target])
del active_ancilla[0]
del active_ancilla[0]
elif( len(active_ancilla) == 1):
instructions.append([anc[active_ancilla[0]], target])
del active_ancilla[0]
for i in range( len(instructions) ):
if len(instructions[i]) == 2:
qc.cx( instructions[i][0], instructions[i][1])
else:
qc.ccx( instructions[i][0], instructions[i][1], instructions[i][2] )
del instructions[-1]
for i in range( len(instructions) ):
qc.ccx( instructions[0-(i+1)][0], instructions[0-(i+1)][1], instructions[0-(i+1)][2] )
def Control_Instruction( qc, vec ):
#Ammends the proper quantum circuit instruction based on the input 'vec'
#Used for the function 'n_Control_U
if( vec[0] == 'X' ):
qc.cx( vec[1], vec[2] )
elif( vec[0] == 'Z' ):
qc.cz( vec[1], vec[2] )
elif( vec[0] == 'CPHASE' ):
qc.cu1( vec[2], vec[1], vec[3] )
elif( vec[0] == 'SWAP' ):
qc.cswap( vec[1], vec[2], vec[3] )
def sinmons_solver(E,N):
'''Returns an array of s_prime candidates
'''
s_primes = []
for s in np.ararge(1,2**N):
sp = Binary( int(s), 2**N )
candidate = True
for e in range( len(E) ):
value = 0
for i in range( N ):
value = value + sp[i]*E[e][i]
if(value%2==1):
candidate=False
if(candidate):
s_primes.append(sp)
return s_primes
def Grover_Oracle(mark, qc, q, an1, an2):
'''
picks out the marked state and applies a negative phase
'''
qc.h( an1[0] )
X_Transformation(qc, q, mark)
if( len(mark) > 2 ):
n_NOT( qc, q, an1[0], an2 )
elif( len(mark) == 2 ):
qc.ccx( q[0], q[1], an1[0] )
X_Transformation(qc, q, mark)
qc.h( an1[0] )
def Grover_Diffusion(mark, qc, q, an1, an2):
'''
ammends the instructions for a Grover Diffusion Operation to the Quantum Circuit
'''
zeros_state = []
for i in range( len(mark) ):
zeros_state.append( 0 )
qc.h( q[int(i)] )
Grover_Oracle(zeros_state, qc, q, an1, an2)
for j in range( len(mark) ):
qc.h( q[int(j)] )
def Grover(Q, marked):
'''
Amends all the instructions for a Grover Search
'''
q = QuantumRegister(Q,name='q')
an1 = QuantumRegister(1,name='anc')
an2 = QuantumRegister(Q-2,name='nanc')
c = ClassicalRegister(Q,name='c')
qc = QuantumCircuit(q,an1,an2,c,name='qc')
for j in range(Q):
qc.h( q[int(j)] )
qc.x( an1[0] )
iterations = round( m.pi/4 * 2**(Q/2.0) )
for i in range( iterations ):
Grover_Oracle(marked, qc, q, an1, an2)
Grover_Diffusion(marked, qc, q, an1, an2)
return qc, q, an1, an2, c
def Multi_Grover(q, a1, a2, qc, marked, iters):
'''
Input: q (QuantumRegister) a1 (QuantumRegister) a2 (QuantumRegister) qc (QuantumCircuit)
marked (array) iters (integer)
Appends all of the gate operations for a multi-marked state Grover Search
'''
Q = int(len(marked))
for i in np.arange( iters ):
for j in np.arange(len(marked)):
M = list(marked[j])
for k in np.arange(len(M)):
if(M[k]=='1'):
M[k] = 1
else:
M[k] = 0
Grover_Oracle(M, qc, q, a1, a2)
Grover_Diffusion(M, qc, q, a1, a2)
return qc, q, a1, a2
def n_Control_U(qc, control, anc, gates):
#Performs a list of single control gates, as an n-control operation
instructions = []
active_ancilla = []
q_unused = []
n = len(control)
q = 0
a = 0
while(n > 0):
if(n >= 2) :
instructions.append([control[q], control[q+1], anc[a]])
active_ancilla.append(a)
a += 1
q += 2
n -= 2
if(n == 1):
q_unused.append( q )
n -= 1
while( len(q_unused) != 0 ) :
if(len(active_ancilla)>1):
instructions.append( [control[q] , anc[active_ancilla[0]], anc[a]])
del active_ancilla[0]
del q_unused[0]
active_ancilla.append(a)
a += 1
else:
instructions.append( [control[q] , anc[active_ancilla[0]], anc[a]])
del active_ancilla[0]
del q_unused[0]
c_a = anc[a]
while( len(active_ancilla) != 0 ) :
if( len(active_ancilla) > 2 ) :
instructions.append([anc[active_ancilla[0]], anc[active_ancilla[1]], anc[a]])
active_ancilla.append(a)
del active_ancilla[0]
del active_ancilla[0]
a += 1
elif( len(active_ancilla)==2):
instructions.append([anc[active_ancilla[0]], anc[active_ancilla[1]], anc[a]])
del active_ancilla[0]
del active_ancilla[0]
c_a = anc[a]
elif( len(active_ancilla)==1):
c_a = anc[active_ancilla[0]]
del active_ancilla[0]
for i in range( len(instructions) ) :
qc.ccx(instructions[i][0], instructions[i][1], instructions[i][2])
for j in range(len(gates)):
control_vec = [gates[j][0], c_a]
for k in range( 1, len(gates[j])):
control_vec.append( gates[j][k] )
Control_Instruction( qc, control_vec )
for i in range( len(instructions) ) :
qc.ccx(instructions[0-(i+1)][0],instructions[0-(i+1)][1], instructions[0-(i+1)][2])
def Control_Instructions(qc, vec):
if (vec[0] == 'X'):
qc.cx(vec[1], vec[2])
elif (vec[0] == 'Z'):
qc.cz(vec[1], vec[2])
def Blackbox_g_D(qc, qreg):
f_type=['f(0,1) -> (0,1)', 'f(0,1) -> (1,0)', 'f(0,1) -> 0', 'f(0,1) -> 1']
r = int(m.floor(4*np.random.rand()))
if (r == 0):
qc.cx(qreg[0],qreg[1])
if (r == 1):
qc.x(qreg[0])
qc.cx(qreg[0],qreg[1])
qc.x(qreg[0])
if (r == 2):
qc.id(qreg[0])
qc.id(qreg[1])
if (r == 3):
qc.x(qreg[1])
return f_type[r]
def Deutsch(qc,qreg):
qc.h(qreg[0])
qc.h(qreg[1])
f = Blackbox_g_D(qc, qreg)
qc.h(qreg[0])
qc.h(qreg[1])
return f
def Blackbox_g_DJ(Q, qc, qreg, an1):
f_type=['constant','balanced']
f=[]
r=int(m.floor(2**Q*np.random.rand()))
if r==0:
f.append(f_type[0])
elif r == 1:
qc.x(qreg[Q-1])
f.append(f_type[0])
else:
control = []
for i in range(Q):
control.append(qreg[i])
an2 = QuantumRegister(int(Q-2), name='nn_anc')
qc.add_register(an2)
f.append(f_type[1])
S=[]
for s in range(2**Q):
S.append(s)
for k in range(2**(Q-1)):
S_num = S[int(m.floor(len(S)*np.random.rand()))]
state = Binary(S_num,2**Q)
S.remove(S_num)
f_string = '|'
for j in range(len(state)):
f_string += str(int(state[j]))
if (state[j] == 0):
qc.x(qreg[j])
f.append(f_string + '>')
n_NOT(qc, control, an1[0], an2)
for j in range(len(state)):
if (state[j] == 0):
qc.x(qreg[j])
return f
def Deutsch_Josza(Q,qc,qreg,an1):
for i in range(Q):
qc.h(qreg[i])
qc.h(an1[0])
f = Blackbox_g_DJ(Q, qc, qreg, an1)
for i in range(Q):
qc.h(qreg[i])
qc.h(an1[0])
return f
def Blackbox_g_BV(Q,qc,qreg,an1):
a = Binary(int(m.floor(2**Q*np.random.rand())),2**Q)
control=[]
for i in range(Q):
control.append(qreg[i])
an2 = QuantumRegister(Q-2,name='nn_anc')
qc.add_register(an2)
for s in range(2**Q):
state = Binary(s,2**Q)
dp = np.vdot(a, state)
if (dp % 2 == 1):
for j in range(len(state)):
if int(state[j]) == 0:
qc.x(qreg[j])
n_NOT(qc, control, an1[0], an2)
for j in range(len(state)):
if int(state[j]) == 0:
qc.x(qreg[j])
return a
def Bernstein_Vazirani(Q,qc,qreg,an1):
for i in range(Q):
qc.h(qreg[i])
qc.h(an1[0])
a = Blackbox_g_BV(Q,qc,qreg,an1)
for i in range(Q):
qc.h(qreg[i])
qc.h(an1[0])
return a
def Blackbox_g_S(Q, qc, q, anc1):
anc2 = QuantumRegister(Q-1,name='nU_anc')
qc.add_register(anc2)
s = np.zeros(Q)
for i in range(Q):
s[i] = int(m.floor(2*np.random.rand()))
outputs=[]
for o in range(2**Q):
outputs.append(o)
f = np.zeros(2**Q)
for j in range(2**Q):
out = outputs[int(m.floor(len(outputs)*np.random.rand()))]
f[j] = out
f[int(From_Binary(Oplus(Binary(j, 2**Q),s)))] = out
outputs.remove(out)
output_states=[]
for k in range(2**Q):
output_states.append(Binary(f[k],2**Q))
for a in range(2**Q):
c_ops=[]
for b in range(Q):
if output_states[a][b] == 1:
c_ops.append(['X', anc1[b]])
X_Transformation(qc, q, Binary(a, 2**Q))
n_Control_U(qc, q, anc2, c_ops)
# instead of n_Control_U it would work witn n_NOT as well, but the overhead would be much higher:
#for b in range(Q):
# if output_states[a][b] == 1:
# n_NOT(qc, q, anc1[b], anc2)
X_Transformation(qc, q, Binary(a, 2**Q))
return qc, s, f
def Simons_Quantum(Q, qc, q, c, anc1):
for i in range(Q):
qc.h(q[i])
qc,s,f = Blackbox_g_S(Q,qc,q, anc1)
for i in range(Q):
qc.h(q[i])
qc.measure(q,c)
return qc, s
def Simons_Solver(E,N):
s_primes = []
for s in range(1, 2**N):
sp = Binary(s, 2**N)
candidate = True
for e in range(len(E)):
value = 0
for i in range(N):
value += sp[i] * E[e][i]
if value%2 == 1:
candidate = False
if candidate:
s_primes.append(sp)
return s_primes
def Simons_Classical(Q, qc):
run_quantum = True
Equations = []
Results = []
quantum_runs = 0
while(run_quantum):
quantum_runs += 1
M = Measurement(qc, shots = 20, return_M = True, print_M = False)
new_result = True
for r in range(len(Results)):
if list(M.keys())[0] == Results[r]:
new_result = False
break
if new_result:
Results.append(list(M.keys())[0])
eq = []
for e in range(Q):
eq.append(int(list(M.keys())[0][e]))
Equations.append(eq)
s_primes = Simons_Solver(Equations, Q)
if len(s_primes) == 1:
run_quantum = False
return s_primes, Results, quantum_runs
def DFT(x, **kwargs):
p = -1.0
if 'inverse' in kwargs:
P = kwargs['inverse']
if P == True:
p = 1.0
L = len(x)
X = []
for i in range(L):
value = 0
for j in range(L):
value += x[j] * np.exp(p * 2 * m.pi * 1.0j * i * j / L)
X.append(value)
for k in range(len(X)):
re = round(X[k].real,5)
im = round(X[k].imag,5)
if abs(im) == 0 and abs(re) != 0:
X[k] = re
elif abs(re) == 0 and abs(im) != 0:
X[k] = im * 1.0j
elif abs(re) == 0 and abs(im) == 0:
X[k] = 0
else:
X[k] = re + im * 1.0j
return X
def QFT(qc, q, qubits, **kwargs):
R_phis = [0]
for i in range(2, qubits+1):
R_phis.append( 2/(2**i) * m.pi )
for j in range(qubits):
qc.h( q[j] )
for k in range(qubits-j-1):
qc.cp( R_phis[k+1], q[j+k+1], q[j] )
if 'swap' in kwargs:
if(kwargs['swap'] == True):
for s in range(m.floor(qubits/2.0)):
qc.swap( q[s],q[qubits-1-s] )
def QFT_dgr(qc, q, qubits, **kwargs):
if 'swap' in kwargs:
if(kwargs['swap'] == True):
for s in range(m.floor(qubits/2.0)):
qc.swap( q[s],q[qubits-1-s] )
R_phis = [0]
for i in range(2,qubits+1):
R_phis.append( -2/(2**i) * m.pi )
for j in range(qubits):
for k in range(j):
qc.cp(R_phis[j-k], q[qubits-k-1], q[qubits-j-1] )
qc.h( q[qubits-j-1] )
def Quantum_Adder(qc, Qa, Qb, A, B):
Q = len(B)
for n in range(Q):
if( A[n] == 1 ):
qc.x( Qa[n+1] )
if( B[n] == 1 ):
qc.x( Qb[n] )
QFT(qc,Qa,Q+1)
p = 1
for j in range( Q ):
qc.cp( m.pi/(2**p), Qb[j], Qa[0] )
p = p + 1
for i in range(1,Q+1):
p = 0
for jj in np.arange( i-1, Q ):
qc.cp( m.pi/(2**p), Qb[jj], Qa[i] )
p = p + 1
QFT_dgr(qc,Qa,Q+1)
def QPE_phi(MP):
ms = [[],[]]
for i in range(2):
for j in range(len(MP[1][i])):
ms[i].append(int(MP[1][i][j]))
n = int(len(ms[0]))
MS1 = From_Binary(ms[0])
MS2 = From_Binary(ms[1])
estimatedProb = MP[0][0]
aproxPhi = 0
aproxProb = 1
for k in np.arange(1,5000):
phi = k/5000
prob = 1/(2**(2*n)) * abs((-1 + np.exp(2.0j*m.pi*phi) )/(-1 + np.exp(2.0j*m.pi*phi/(2**n))))**2
if abs(prob - estimatedProb) < abs(aproxProb - estimatedProb):
aproxProb = prob
aproxPhi = phi
if( (MS1 < MS2) and ( (MS1!=0) and (MS2!=(2**n-1)) ) ):
theta = (MS1+aproxPhi)/(2**n)
elif( (MS1 > MS2) and (MS1!=0) ):
theta = (MS1-aproxPhi)/(2**n)
else:
theta = 1+(MS1-aproxPhi)/(2**n)
return aproxPhi,theta
def C_Oracle(qc, c, q, a1, a2, state):
#qc.barrier()
N = len(q)
for i in np.arange(N):
if( state[i]==0 ):
qc.cx( c, q[int(i)] )
#---------------------------------
qc.ccx( q[0], q[1], a1[0] )
for j1 in np.arange(N-2):
qc.ccx( q[int(2+j1)], a1[int(j1)], a1[int(1+j1)] )
qc.ccx( c, a1[N-2], a2[0] )
for j2 in np.arange(N-2):
qc.ccx( q[int(N-1-j2)], a1[int(N-3-j2)], a1[int(N-2-j2)] )
qc.ccx( q[0], q[1], a1[0] )
#---------------------------------
for i2 in np.arange(N):
if( state[i2]==0 ):
qc.cx( c, q[int(i2)] )
#qc.barrier()
def C_Diffusion(qc, c, q, a1, a2, ref):
#qc.barrier()
Q = len(q)
N = 2**( Q )
for j in np.arange(Q):
qc.ch( c, q[int(j)] )
if( ref ):
for k in np.arange(1,N):
C_Oracle(qc,c,q,a1,a2,Binary(int(k),N))
else:
C_Oracle(qc,c,q,a1,a2,Binary(0,N))
for j2 in np.arange(Q):
qc.ch( c, q[int(j2)] )
#qc.barrier()
def C_Grover(qc, c, q, a1, a2, marked, **kwargs):
#qc.barrier()
Reflection=False
if 'proper' in kwargs:
Reflection = kwargs['proper']
M = []
for m1 in np.arange( len(marked) ):
M.append( list(marked[m1]) )
for m2 in np.arange( len(M[m1]) ):
M[m1][m2] = int( M[m1][m2] )
for i in np.arange(len(M)):
C_Oracle( qc,c,q,a1,a2,M[i] )
C_Diffusion( qc,c,q,a1,a2,Reflection )
#qc.barrier()
def GCD(a, b):
gcd = 0
if(a > b):
num1 = a
num2 = b
elif(b > a):
num1 = b
num2 = a
elif(a == b):
gcd = a
while( gcd == 0 ):
i = 1
while( num1 >= num2*i ):
i = i + 1
if( num1 == num2*(i-1) ):
gcd = num2
else:
r = num1 - num2*(i-1)
num1 = num2
num2 = r
return gcd
def Euclids_Alg(a, b):
if(a>=b):
num1 = a
num2 = b
else:
num1 = b
num2 = a
r_new = int( num1%num2 )
r_old = int( num2 )
while(r_new!=0):
r_old = r_new
r_new = int( num1%num2 )
num1 = num2
num2 = r_new
gcd = r_old
return gcd
def Modulo_f(Q, a, N):
mods = []
num = a%N
for i in np.arange(1,2**Q):
mods.append(num)
num = (num*a)%N
return mods
def Mod_Op(Q, qc, q1, q2, anc, a, N):
#mods = Modulo_f(Q,a,N)
num = a%N
for j in np.arange( 2**Q ):
q1_state = BinaryL( j, 2**Q )
#q2_state = BinaryL( mods[j-1], 2**Q )
q2_state = BinaryL(num, 2**Q )
num = (num*a)%N
X_Transformation(qc,q1,q1_state)
gates = []
for k in np.arange(Q):
if(q2_state[k]==1):
gates.append(['X',q2[int(k)]])
n_Control_U(qc, q1, anc, gates)
X_Transformation(qc,q1,q1_state)
def ConFrac(N, **kwargs):
imax = 20
r_a = False
if 'a_max' in kwargs:
imax = kwargs['a_max']
if 'return_a' in kwargs:
r_a = kwargs['return_a']
a = []
a.append( m.floor(N) )
b = N - a[0]
i = 1
while( (round(b,10) != 0) and (i < imax) ):
n = 1.0/b
a.append( m.floor(n) )
b = n - a[-1]
i = i + 1
#------------------------------
a_copy = []
for ia in np.arange(len(a)):
a_copy.append(a[ia])
for j in np.arange( len(a)-1 ):
if( j == 0 ):
p = a[-1] * a[-2] + 1
q = a[-1]
del a[-1]
del a[-1]
else:
p_new = a[-1] * p + q
q_new = p
p = p_new
q = q_new
del a[-1]
if(r_a == True):
return q,p,a_copy
return q,p
def r_Finder(a, N):
value1 = a**1 % N
r = 1
value2 = 0
while value1 != value2 or r > 1000:
value2 = a**(int(1+r)) % N
if( value1 != value2 ):
r = r + 1
return r
def Primality(N):
is_prime = True
if( (N==1) or (N==2) or (N==3) ):
is_prime = True
elif( (N%2==0) or (N%3==0) ):
is_prime = False
elif( is_prime==True ):
p = 5
while( (p**2 <= N) and (is_prime==True) ):
if( (N%p==0) or (N%(p+2)==0) ):
is_prime = False
p = p + 6
return is_prime
def Mod_r_Check(a, N, r):
v1 = a**(int(2)) % N
v2 = a**(int(2+r)) % N
if( (v1 == v2) and (r<N) and (r!=0) ):
return True
return False
def Evaluate_S(S, L, a, N):
Pairs = [[S,L]]
for s in np.arange(3):
S_new = int( S - 1 + s)
for l in np.arange(3):
L_new = int( L - 1 + l)
if( ((S_new!=S) or (L_new!=L)) and (S_new!=L_new) ):
Pairs.append( [S_new,L_new] )
#--------------------------- Try 9 combinations of S and L, plus or minus 1 from S & L
period = 0
r_attempts = []
found_r = False
while( (found_r==False) and (len(Pairs)!=0) ):
order = 1
S_o = Pairs[0][0]
L_o = Pairs[0][1]
q_old = -1
q = 999
while( q_old != q ):
q_old = int( q )
q,p = ConFrac(S_o/L_o,a_max=(order+1))
new_r = True
for i in np.arange(len(r_attempts)):
if( q == r_attempts[i] ):
new_r = False
if(new_r):
r_attempts.append( int(q) )
r_bool = Mod_r_Check(a,N,q)
if( r_bool ):
found_r = True
q_old = q
period = int(q)
order = order + 1
del Pairs[0]
#--------------------------- Try higher multiples of already attempted r values
r_o = 0
while( (found_r == False) and (r_o < len(r_attempts)) ):
k = 2
r2 = r_attempts[r_o]
while( k*r2 < N ):
r_try = int(k*r2)
new_r = True
for i2 in np.arange(len(r_attempts)):
if( r_try == r_attempts[i2] ):
new_r = False
if(new_r):
r_attempts.append( int(r_try) )
r_bool = Mod_r_Check(a,N,r_try)
if( r_bool ):
found_r = True
k = N
period = int(r_try)
k = k + 1
r_o = r_o + 1
#--------------------------- If a period is found, try factors of r for smaller periods
if( found_r == True ):
Primes = []
for i in np.arange(2,period):
if( Primality(int(i)) ):
Primes.append(int(i))
if( len(Primes) > 0 ):
try_smaller = True
while( try_smaller==True ):
found_smaller = False
p2 = 0
while( (found_smaller==False) and (p2 < len(Primes)) ):
#print('p2: ',p2)
#print( 'period: ',period,' ',Primes[p2] )
try_smaller = False
if( period/Primes[p2] == m.floor( period/Primes[p2] ) ):
r_bool_2 = Mod_r_Check(a,N,int(period/Primes[p2]))
if( r_bool_2 ):
period = int(period/Primes[p2])
found_smaller = True
try_smaller = True
p2 = p2 + 1
return period
def k_Data(k,n):
Centers = []
for i in np.arange(k):
Centers.append( [1.5+np.random.rand()*5,1.5*np.random.random()*5] )
count = int(round((0.7*n)/k))
Data = []
for j in range(len(Centers)):
for j2 in range(count):
r = np.random.random()*1.5
x = Centers[j][0]+r*np.cos(np.random.random()*2*m.pi)
y = Centers[j][1]+r*np.sin(np.random.random()*2*m.pi)
Data.append([x, y])
for j2 in range(n - k * count):
Data.append( [np.random.random()*8, np.random.random()*8] )
return Data
def Initial_Centroids(k, D):
D_copy = []
for i in np.arange( len(D) ):
D_copy.append( D[i] )
Centroids = []
for j in np.arange(k):
p = np.random.randint(0,int(len(D_copy)-1))
Centroids.append( [ D_copy[p][0] , D_copy[p][1] ] )
D_copy.remove( D_copy[p] )
return Centroids
def Update_Centroids(CT, CL):
old_Centroids = []
for c0 in np.arange(len(CT)):
old_Centroids.append(CT[c0])
Centroids = []
for c1 in np.arange(len(CL)):
mean_x = 0.
mean_y = 0.
for c2 in np.arange(len(CL[c1])):
mean_x += CL[c1][c2][0]
mean_y += CL[c1][c2][1]
l = len(CL[c1])
mean_x /= l
mean_y /= l
Centroids.append( [ mean_x,mean_y ] )
return Centroids, old_Centroids
def Update_Clusters(D, CT, CL):
old_Clusters = []
for c0 in np.arange(len(CL)):
old_Clusters.append(CL[c0])
Clusters = []
for c1 in np.arange( len(CT) ):
Clusters.append( [] )
for d in np.arange( len(D) ):
closest = 'c'
distance = 100000
for c2 in np.arange( len(Clusters) ):
Dist = m.sqrt( ( CT[c2][0] - D[d][0] )**2 + ( CT[c2][1] - D[d][1] )**2 )
if( Dist < distance ):
distance = Dist
closest = int(c2)
Clusters[closest].append( D[d] )
return Clusters,old_Clusters
def Check_Termination(CL, oCL ):
terminate = True
for c1 in np.arange( len(oCL) ):
for c2 in np.arange( len(oCL[c1]) ):
P_found = False
for c3 in np.arange( len(CL[c1]) ):
if( CL[c1][c3] == oCL[c1][c2] ):
P_found = True
break
if( P_found == False ):
terminate = False
break
return terminate
def Draw_Data(CL, CT, oCT, fig, ax, colors, colors2 ):
for j1 in np.arange( len(CL) ):
ax.scatter( oCT[j1][0],oCT[j1][1], color='white', marker='s',s=80 )
for cc in np.arange(len(CL)):
for ccc in np.arange( len( CL[cc] ) ):
ax.scatter( CL[cc][ccc][0],CL[cc][ccc][1], color=colors[cc],s=10 )
for j2 in np.arange( len(CL) ):
ax.scatter( CT[j2][0],CT[j2][1], color=colors2[j2], marker='x',s=50 )
fig.canvas.draw()
time.sleep(1)
def SWAP_Test( qc, control, q1, q2, classical, S ):
qc.h( control )
qc.cswap( control, q1, q2 )
qc.h( control )
qc.measure( control, classical )
D = {'0':0}
D.update( Measurement(qc,shots=S,return_M=True,print_M=False) )
return D['0']
def Bloch_State( p,P ):
x_min = P[0]
x_max = P[1]
y_min = P[2]
y_max = P[3]
theta = np.pi/2*( (p[0]-x_min)/(1.0*x_max-x_min) + (p[1]-y_min)/(1.0*y_max-y_min) )
phi = np.pi/2*( (p[0]-x_min)/(1.0*x_max-x_min) - (p[1]-y_min)/(1.0*y_max-y_min) + 1 )
return theta,phi
def Heatmap(data, show_text, show_ticks, ax, cmap, cbarlabel, **kwargs):
valfmt="{x:.1f}"
textcolors=["black", "white"]
threshold=None
cbar_kw={}
#----------------------------
if not ax:
ax = plt.gca()
im = ax.imshow(data, cmap=cmap, **kwargs)
cbar = ax.figure.colorbar(im, ax=ax, **cbar_kw)
cbar.ax.set_ylabel(cbarlabel, rotation=-90, va="bottom")
ax.grid(which="minor", color="black", linestyle='-', linewidth=1)
if( show_ticks == True ):
ax.set_xticks(np.arange(data.shape[1]))
ax.set_yticks(np.arange(data.shape[0]))
ax.tick_params(which="minor", bottom=False, left=False)
if threshold is not None:
threshold = im.norm(threshold)
else:
threshold = im.norm(data.max())/2.
kw = dict(horizontalalignment="center", verticalalignment="center")
if isinstance(valfmt, str):
valfmt = matplotlib.ticker.StrMethodFormatter(valfmt)
if( show_text == True ):
for i in range(data.shape[0]):
for j in range(data.shape[1]):
kw.update(color=textcolors[int(im.norm(data[i, j]) < threshold)])
text = im.axes.text(j, i, valfmt(data[i, j], None), **kw)
def Q_Update_Clusters(D, CT, CL, DS, shots):
old_Clusters = []
for c0 in np.arange(len(CL)):
old_Clusters.append(CL[c0])
Clusters = []
for c1 in np.arange( len(CT) ):
Clusters.append( [] )
#------------------------------------------------
for d in np.arange( len(D) ):
closest = 'c'
distance = 0
t,p = Bloch_State( D[d], DS )
for c2 in np.arange( len(Clusters) ):
t2,p2 = Bloch_State( CT[c2], DS )
q = QuantumRegister( 3, name='q' )
c = ClassicalRegister( 1, name='c' )
qc= QuantumCircuit( q,c, name='qc' )
qc.u( t, p, 0, q[1] )
qc.u( t2, p2, 0, q[2] )
IP = SWAP_Test( qc, q[0], q[1], q[2], c[0], shots )
if( IP > distance ):
distance = IP
closest = int(c2)
Clusters[closest].append(D[d] )
return Clusters,old_Clusters
def E_Expectation_Value( qc, Energies ):
SV = execute( qc, S_simulator, shots=1 ).result().get_statevector()
EV = 0
for i in range( len(SV) ):
EV += Energies[i] *abs( SV[i] * np.conj(SV[i]) )
EV = round(EV,4)
return EV
def Top_States(States, Energies, SV, top):
P = []
S = []
E = []
for a in np.arange( top ):
P.append(-1)
S.append('no state')
E.append('no energy')
for i in range(len(States)):
new_top = False
probs = abs(SV[i]*np.conj(SV[i]))*100
state = States[i]
energ = Energies[i]
j = 0
while( (new_top == False) and (j < top) ):
if( probs > P[j] ):
for k in np.arange( int( len(P) - (j+1) ) ):
P[int( -1-k )] = P[int( -1-(k+1) )]
S[int( -1-k )] = S[int( -1-(k+1) )]
E[int( -1-k )] = E[int( -1-(k+1) )]
P[j] = probs
S[j] = state
E[j] = energ
new_top = True
j = int(j+1)
for s in range( top ):
print('State ',S[s],' Probability: ',round(P[s],2),'%',' Energy: ',round(E[s],2))
def Ising_Energy(V, E, **kwargs):
Trans = False
if 'Transverse' in kwargs:
if( kwargs['Transverse'] == True ):
Trans = True
Energies = []
States = []
for s in range( 2**len(V) ):
B = BinaryL(int(s),2**len(V))
B2 = []
for i in range(len(B)):
if( B[i] == 0 ):
B2.append(1)
else:
B2.append(-1)
state = ''
energy = 0
for s2 in range(len(B)):
state = state+str(B[s2])
energy -= V[s2][1]*B2[s2]
States.append(state)
for j in range( len(E) ):
if( Trans == False ):
energy -= B2[int(E[j][0])] * B2[int(E[j][1])]
else:
energy -= B2[int(E[j][0])] * B2[int(E[j][1])] * E[j][2]
Energies.append(energy)
return Energies,States
def Ising_Circuit(qc, q, V, E, beta, gamma, **kwargs):
Trans = False
if 'Transverse' in kwargs:
if( kwargs['Transverse'] == True ):
Trans = True
Mixer = 1
if 'Mixing' in kwargs:
Mixer = int( kwargs['Mixing'] )
p = 1
if 'p' in kwargs:
p = int(kwargs['p'])
for c in range(p):
Uc_Ising(qc,q,gamma,V,E,Trans)
if( Mixer == 2 ):
Ub_Mixer2(qc,q,beta,V)
else:
Ub_Mixer1(qc,q,beta,V)
def Uc_Ising(qc, q, gamma, Vert, Edge, T):
for e in range( len(Edge) ): # ZZ
if( T == False ):
G = gamma
else:
G = gamma * Edge[e][2]
qc.cx( q[int(Edge[e][0])], q[int(Edge[e][1])] )
qc.rz( 2*G, q[int(Edge[e][1])] )
qc.cx( q[int(Edge[e][0])], q[int(Edge[e][1])] )
for v in range( len(Vert) ): # Z_gamma
# WARNING: This was with error in the article, the 'on site' magnetic field was not taken into account
qc.rz( gamma * Vert[v][1], q[int(Vert[v][0])] )
def Ub_Mixer1(qc, q, beta, Vert):
for v in np.arange( len(Vert) ):
qc.rx( beta, q[int(v)] )
def Ub_Mixer2(qc, q, beta, Vert):
for v in range( len(Vert) ):
qc.rx( beta, q[int(Vert[v][0])] )
qc.cx( q[0], q[1] )
qc.cx( q[1], q[2] )
qc.cx( q[2], q[0] )
for v2 in range( len(Vert) ):
qc.ry( beta, q[int(Vert[v2][0])] )
def Ising_Gradient_Descent(qc, q, Circ, V, E, beta, gamma, epsilon, En, step, **kwargs):
Trans = False
if 'Transverse' in kwargs:
if( kwargs['Transverse'] == True ):
Trans = True
Mixer = 1
if 'Mixing' in kwargs:
Mixer = int(kwargs['Mixing'])
params = [ [beta+epsilon,gamma],[beta-epsilon,gamma],[beta,gamma+epsilon],[beta,gamma-epsilon] ]
ev = []
for i in np.arange( 4 ):
q = QuantumRegister(len(V))
qc= QuantumCircuit(q)
for hh in np.arange(len(V)):
qc.h( q[int(hh)] )
Circ( qc, q, V, E, params[i][0], params[i][1], Transverse=Trans, Mixing=Mixer )
ev.append( E_Expectation_Value( qc, En ) )
beta_next = beta - ( ev[0] - ev[1] )/( 2.0*epsilon ) * step
gamma_next = gamma - ( ev[2] - ev[3] )/( 2.0*epsilon ) * step
return beta_next, gamma_next
def MaxCut_Energy(V, E):
Energies = []
States = []
for s in np.arange( 2**len(V) ):
B = BinaryL(int(s),2**len(V))
B2 = []
for i in np.arange(len(B)):
if( B[i] == 0 ):
B2.append(1)
else:
B2.append(-1)
state = ''
for s2 in np.arange(len(B)):
state = state+str(B[s2])
States.append(state)
energy = 0
for j in np.arange( len(E) ):
energy = energy + 0.5* ( 1.0 - B2[int(E[j][0])]*B2[int(E[j][1])] )
Energies.append(energy)
return Energies,States
def MaxCut_Circuit(qc, q, V, E, beta, gamma):
Uc_MaxCut( qc, q, gamma,E)
Ub_Mixer1(qc,q,beta,V)
def Uc_MaxCut(qc, q, gamma, edge):
for e in np.arange( len(edge) ):
qc.cx( q[int(edge[e][0])], q[int(edge[e][1])] )
qc.rz( gamma, q[int(edge[e][1])] )
qc.cx( q[int(edge[e][0])], q[int(edge[e][1])] )
def p_Gradient_Ascent(qc, q, Circ, V, E, p, Beta, Gamma, epsilon, En, step):
params = []
for i in np.arange(2):
for p1 in np.arange(p):
if( i == 0 ):
params.append( Beta[p1] )
elif( i == 1 ):
params.append( Gamma[p1] )
ep_params = []
for p2 in np.arange( len( params ) ):
for i2 in np.arange( 2 ):
ep = []
for p3 in np.arange( len(params) ):
ep.append( params[p3] )
ep[p2] = ep[p2] + (-1.0)**(i2+1)*epsilon
ep_params.append( ep )
ev = []
for p4 in np.arange( len( ep_params ) ):
run_params = ep_params[p4]
q = QuantumRegister(len(V))
qc= QuantumCircuit(q)
for hh in np.arange(len(V)):
qc.h( q[int(hh)] )
for p5 in np.arange(p):
Circ( qc, q, V, E, run_params[int(p5)], run_params[int(p5+p)] )
ev.append( E_Expectation_Value( qc, En ) )
Beta_next = []
Gamma_next = []
for k in np.arange( len( params ) ):
if( k < len( params )/2 ):
Beta_next.append( params[k] - (ev[int(2*k)] - ev[int(2*k+1)])/( 2.0*epsilon ) * step )
else:
Gamma_next.append( params[k] - (ev[int(2*k)] - ev[int(2*k+1)])/( 2.0*epsilon ) * step )
return Beta_next, Gamma_next
def Single_Qubit_Ansatz( qc, qubit, params ):
qc.ry( params[0], qubit )
qc.rz( params[1], qubit )
def VQE_Gradient_Descent(qc, q, H, Ansatz, theta, phi, epsilon, step, **kwargs):
EV_type = 'measure'
if 'measure' in kwargs:
M_bool = kwargs['measure']
if( M_bool == True ):
EV_type = 'measure'
else:
EV_type = 'wavefunction'
Shots = 1000
if 'shots' in kwargs:
Shots = kwargs['shots']
params = [theta,phi]
ep_params = [[theta+epsilon,phi],[theta-epsilon,phi],[theta,phi+epsilon],[theta,phi-epsilon]]
Hk = list( H.keys() )
EV = []
for p4 in np.arange( len( ep_params ) ):
H_EV = 0
qc_params = ep_params[p4]
for h in np.arange( len(Hk) ):
qc_params = ep_params[p4]
q = QuantumRegister(1)
c = ClassicalRegister(1)
qc= QuantumCircuit(q,c)
Ansatz( qc, q[0], [qc_params[0], qc_params[1]] )
if( Hk[h] == 'X' ):
qc.ry(-m.pi/2,q[0])
elif( Hk[h] == 'Y' ):
qc.rx(m.pi/2,q[0])
if( EV_type == 'wavefunction' ):
sv = execute( qc, S_simulator, shots=1 ).result().get_statevector()
H_EV = H_EV + H[Hk[h]]*( (np.conj(sv[0])*sv[0]).real - (np.conj(sv[1])*sv[1]).real )
elif( EV_type == 'measure' ):
qc.measure( q,c )
M = {'0':0,'1':0}
M.update( Measurement( qc, shots=Shots, print_M=False, return_M=True ) )
H_EV = H_EV + H[Hk[h]]*(M['0']-M['1'])/Shots
EV.append(H_EV)
theta_slope = ( EV[0]-EV[1] )/(2.0*epsilon)
phi_slope = ( EV[2]-EV[3] )/(2.0*epsilon)
next_theta = theta - theta_slope*step
next_phi = phi - phi_slope*step
return next_theta,next_phi
def Two_Qubit_Ansatz(qc, q, params):
Single_Qubit_Ansatz( qc, q[0], [params[0], params[1]] )
Single_Qubit_Ansatz( qc, q[1], [params[2], params[3]] )
qc.cx( q[0], q[1] )
Single_Qubit_Ansatz( qc, q[0], [params[4], params[5]] )
Single_Qubit_Ansatz( qc, q[1], [params[6], params[7]] )
def Calculate_MinMax(V, C_type):
if( C_type == 'min' ):
lowest = [V[0],0]
for i in np.arange(1,len(V)):
if( V[i] < lowest[0] ):
lowest[0] = V[i]
lowest[1] = int(i)
return lowest
elif( C_type == 'max' ):
highest = [V[0],0]
for i in np.arange(1,len(V)):
if( V[i] > highest[0] ):
highest[0] = V[i]
highest[1] = int(i)
return highest
def Compute_Centroid(V):
points = len( V )
dim = len( V[0] )
Cent = []
for d in np.arange( dim ):
avg = 0
for a in np.arange( points ):
avg = avg + V[a][d]/points
Cent.append( avg )
return Cent
def Reflection_Point(P1, P2, alpha):
P = []
for p in np.arange( len(P1) ):
D = P2[p] - P1[p]
P.append( P1[p]+alpha*D )
return P
def VQE_EV(params, Ansatz, H, EV_type, **kwargs):
Shots = 10000
if 'shots' in kwargs:
Shots = int( kwargs['shots'] )
Hk = list( H.keys() )
H_EV = 0
for k in range( len(Hk) ): # for each term in Hamiltonian
L = list( Hk[k] )
q = QuantumRegister(len(L))
c = ClassicalRegister(len(L))
qc= QuantumCircuit(q,c)
Ansatz( qc, q, params )
sv0 = execute( qc, S_simulator, shots=1 ).result().get_statevector()
if( EV_type == 'wavefunction' ):
for l in range( len(L) ):
if( L[l] == 'X' ):
qc.x( q[int(l)] )
elif( L[l] == 'Y' ):
qc.y( q[int(l)] )
elif( L[l] == 'Z' ):
qc.z( q[int(l)] )
sv = execute( qc, S_simulator, shots=1 ).result().get_statevector()
H_ev = 0
for l2 in range(len(sv)):
H_ev = H_ev + (np.conj(sv[l2])*sv0[l2]).real
H_EV = H_EV + H[Hk[k]] * H_ev
elif( EV_type == 'measure' ):
# apply Hamiltonian term
for l in range( len(L) ):
if( L[l] == 'X' ):
qc.ry(-m.pi/2,q[int(l)])
elif( L[l] == 'Y' ):
qc.rx( m.pi/2,q[int(l)])
# measure it
qc.measure( q,c )
M = Measurement( qc, shots=Shots, print_M=False, return_M=True )
Mk = list( M.keys() )
# compute energy estimate
H_ev = 0
for m1 in range(len(Mk)):
MS = list( Mk[m1] )
e = 1
for m2 in range(len(MS)):
if( MS[m2] == '1' ):
e = e*(-1)
H_ev = H_ev + e * M[Mk[m1]]
H_EV = H_EV + H[Hk[k]]*H_ev/Shots
return H_EV
def Nelder_Mead(H, Ansatz, Vert, Val, EV_type):
alpha = 2.0
gamma = 2.0
rho = 0.5
sigma = 0.5
add_reflect = False
add_expand = False
add_contract = False
shrink = False
add_bool = False
#----------------------------------------
hi = Calculate_MinMax( Val,'max' )
Vert2 = []
Val2 = []
for i in np.arange(len(Val)):
if( int(i) != hi[1] ):
Vert2.append( Vert[i] )
Val2.append( Val[i] )
Center_P = Compute_Centroid( Vert2 )
Reflect_P = Reflection_Point(Vert[hi[1]],Center_P,alpha)
Reflect_V = VQE_EV(Reflect_P,Ansatz,H,EV_type)
#------------------------------------------------- # Determine if: Reflect / Expand / Contract / Shrink
hi2 = Calculate_MinMax( Val2,'max' )
lo2 = Calculate_MinMax( Val2,'min' )
if( hi2[0] > Reflect_V >= lo2[0] ):
add_reflect = True
elif( Reflect_V < lo2[0] ):
Expand_P = Reflection_Point(Center_P,Reflect_P,gamma)
Expand_V = VQE_EV(Expand_P,Ansatz,H,EV_type)
if( Expand_V < Reflect_V ):
add_expand = True
else:
add_reflect = True
elif( Reflect_V > hi2[0] ):
if( Reflect_V < hi[0] ):
Contract_P = Reflection_Point(Center_P,Reflect_P,rho)
Contract_V = VQE_EV(Contract_P,Ansatz,H,EV_type)
if( Contract_V < Reflect_V ):
add_contract = True
else:
shrink = True
else:
Contract_P = Reflection_Point(Center_P,Vert[hi[1]],rho)
Contract_V = VQE_EV(Contract_P,Ansatz,H,EV_type)
if( Contract_V < Val[hi[1]] ):
add_contract = True
else:
shrink = True
#------------------------------------------------- # Apply: Reflect / Expand / Contract / Shrink
if( add_reflect == True ):
new_P = Reflect_P
new_V = Reflect_V
add_bool = True
elif( add_expand == True ):
new_P = Expand_P
new_V = Expand_V
add_bool = True
elif( add_contract == True ):
new_P = Contract_P
new_V = Contract_V
add_bool = True
if( add_bool ):
del Vert[hi[1]]
del Val[hi[1]]
Vert.append( new_P )
Val.append( new_V )
if( shrink ):
Vert3 = []
Val3 = []
lo = Calculate_MinMax( Val,'min' )
Vert3.append( Vert[lo[1]] )
Val3.append( Val[lo[1]] )
for j in np.arange( len(Val) ):
if( int(j) != lo[1] ):
Shrink_P = Reflection_Point(Vert[lo[1]],Vert[j],sigma)
Vert3.append( Shrink_P )
Val3.append( VQE_EV(Shrink_P,Ansatz,H,EV_type) )
for j2 in np.arange( len(Val) ):
del Vert[0]
del Val[0]
Vert.append( Vert3[j2] )
Val.append( Val3[j2] )
|
https://github.com/thoughtpoet/Toward-high-frequency-trading-on-the-quantm-cloud
|
thoughtpoet
|
!python3 -m pip install -q qiskit
!python3 -m pip install -q qiskit_ibm_runtime
from qiskit import IBMQ
from qiskit_ibm_runtime import QiskitRuntimeService, Session, Options, Sampler, Estimator
from qiskit.circuit.quantumcircuit import QuantumCircuit
from qiskit.quantum_info.operators import Operator
from qiskit.extensions.unitary import UnitaryGate
from qiskit.providers.aer import AerSimulator, Aer
from qiskit.execute_function import execute
import numpy as np
from typing import Dict, Optional
# ====================================
# pass IBM API Token
# ====================================
QiskitRuntimeService.save_account(channel='ibm_quantum', token="", overwrite=True)
num_players = 2
# define the payoff matrices. Assume, the 1st matrix is Alice's payoff, the secomd matrix is Bob's payoff
payoff_matrix =[[[3, 0],
[5, 1]],
[[3, 5],
[0, 1]]]
# players' matrices
# |C> strategy
# bob = [
# [1, 0],
# [0, 1]]
# |D> strategy
# bob = [
# [0, 1],
# [1, 0],
# ]
def alice_plays_quantum(theta:float, phi:float):
"""
Set up a quantum game for Alice playing quantum, and Bob playing classically.
Arg:
theta: the value of the theta parameter.
phi: the value of the phi parameter.
Returns:
qc: the class of 'qiskit.circuit.quantumcircuit.QuantumCircuit',
a constructed quantum circuit for the quantum game set up.
"""
alice = np.array([[np.exp(1.0j*phi)*np.cos(theta/2), np.sin(theta/2)],
[-np.sin(theta/2), np.exp(-1.0j*phi)*np.cos(theta/2)]])
bob = np.array([
[1, 0],
[0, 1]]).astype(complex)
qc = QuantumCircuit(num_players)
J = 1/np.sqrt(2)*np.array([[1.0, 0.0, 0.0, 1.0j],
[0.0, 1.0, 1.0j, 0.0],
[0.0, 1.0j, 1.0, 0.0],
[1.0j, 0.0, 0.0, 1.0]]).astype(complex)
J_unitary = UnitaryGate(Operator(J))
qc.append(J_unitary, [0,1])
qc.barrier()
unitary_alice = UnitaryGate(Operator(alice))
unitary_bob = UnitaryGate(Operator(bob))
qc.append(unitary_alice, [0])
qc.append(unitary_bob, [1])
qc.barrier()
Jdagger_unitary = UnitaryGate(Operator(J.conj().T))
qc.append(Jdagger_unitary, [0,1])
return qc
# test run
# define the simulator
simulator = Aer.get_backend('statevector_simulator')
theta = np.pi
phi = 0.0
qc = alice_plays_quantum(theta, phi)
results = execute(qc, simulator, shots=1024).result().get_counts()
results
# calculating payoffs
def get_payoff(counts):
"""
Calculate the reward for the players after the game ends.
"""
payoff_bob = []
payoff_alice = []
for strategy, prob in counts.items():
strategy_bob = int(strategy[1])
strategy_alice = int(strategy[0])
payoff_bob.append(prob * payoff_matrix[0][strategy_alice][strategy_bob])
payoff_alice.append(prob * payoff_matrix[0][strategy_bob][strategy_alice])
return sum(payoff_alice), sum(payoff_bob)
# change the size on the quantum space to explore more quantum strategies
space_size = 4
for phi in np.linspace(0, np.pi/2, space_size):
for theta in np.linspace(0, np.pi, space_size):
qc = alice_plays_quantum(theta, phi)
results = execute(qc, simulator, shots=1024).result().get_counts()
payoff_alice, payoff_bob = get_payoff(results)
print("theta = {}, phi = {}, results = {}, Alice's payoff {}, Bob's payoff {}".format(theta, phi, results, payoff_alice, payoff_bob))
print("Next Game")
qc = alice_plays_quantum(theta = np.pi/2, phi = np.pi/4)
job = simulator.run(qc, shots=2048)
result = job.result()
outputstate = result.get_statevector(qc, decimals=3)
print(outputstate)
from qiskit.visualization import plot_state_city
plot_state_city(outputstate)
from qiskit.visualization import plot_histogram
counts = result.get_counts()
plot_histogram(counts)
# probabilities of a certain outcome
counts
num_players = 2
def alice_bob_play_quantum(theta_a:float, phi_a:float, theta_b:float, phi_b:float, measure=False):
"""
Set up a quantum game. Both players have access to quantum strategies.
Args:
theta_a: Theta parameter for Alice's unitary.
phi_a: Phi parameter for Alice's unitary.
theta_b: Theta parameter for Bob's unitary.
phi_b: Phi parameter for Bob's unitary.
Returns:
qc: the class of 'qiskit.circuit.quantumcircuit.QuantumCircuit',
a constructed quantum circuit for the quantum game set up.
"""
alice = np.array([
[np.exp(1.0j*phi_a)*np.cos(theta_a/ 2), np.sin(theta_a / 2)],
[-np.sin(theta_a / 2), np.exp(-1.0j*phi_a)*np.cos(theta_a / 2)]])
bob = np.array([
[np.exp(1.0j*phi_b)*np.cos(theta_b / 2), np.sin(theta_b / 2)],
[-np.sin(theta_b / 2), np.exp(-1.0j*phi_b)*np.cos(theta_b / 2)]])
qc = QuantumCircuit(num_players)
J = 1/np.sqrt(2)*np.array([[1.0, 0.0, 0.0, 1.0j],
[0.0, 1.0, 1.0j, 0.0],
[0.0, 1.0j, 1.0, 0.0],
[1.0j, 0.0, 0.0, 1.0]]).astype(complex)
J_unitary = UnitaryGate(Operator(J))
qc.append(J_unitary, [0,1])
qc.barrier()
unitary_alice = UnitaryGate(Operator(alice))
unitary_bob = UnitaryGate(Operator(bob))
qc.append(unitary_alice, [0])
qc.append(unitary_bob, [1])
qc.barrier()
Jdagger_unitary = UnitaryGate(Operator(J.conj().T))
qc.append(Jdagger_unitary, [0,1])
if measure:
qc.measure_all()
return qc
alice_reward = 0
bob_reward = 0
draw = 0
space_size = 2
for phi1 in np.linspace(0, 2*np.pi, space_size):
for theta1 in np.linspace(0, np.pi, space_size):
for phi2 in np.linspace(0, 2*np.pi, space_size):
for theta2 in np.linspace(0, np.pi, space_size):
qc = alice_bob_play_quantum(theta1, phi1, theta2, phi2)
results = execute(qc, simulator, shots=1024).result().get_counts()
payoff_alice, payoff_bob = get_payoff(results)
# count winning
if payoff_alice > payoff_bob:
alice_reward += 1
elif payoff_bob > payoff_alice:
bob_reward += 1
else:
draw += 1
# print results
print("theta_alice = {}, phi_alice = {}, theta_bob = {}, phi_bob = {}".format(theta1, phi1, theta2, phi2 ))
print("results = {}, Alice's raward {}, Bob's reward {}".format(results, payoff_alice, payoff_bob))
print("Next Game")
print("===================================================")
print("In {} games Alice gets a higher reward than Bob.". format(alice_reward))
print("In {} games, Bob gets a higher reward than Alice.".format(bob_reward))
print("In {} games Alice and Bob get equal reward.".format(draw))
matrix = np.array([[1.0j, 0], [0, -1.0j]])
qc = QuantumCircuit(2)
gate = UnitaryGate(Operator(matrix))
J = 1/np.sqrt(2)*np.array([[1.0, 0.0, 0.0, 1.0j],
[0.0, 1.0, 1.0j, 0.0],
[0.0, 1.0j, 1.0, 0.0],
[1.0j, 0.0, 0.0, 1.0]]).astype(complex)
J_unitary = UnitaryGate(Operator(J))
qc.append(J_unitary, [0,1])
qc.barrier()
qc.append(gate, [0])
qc.append(gate, [1])
qc.barrier()
Jdagger_unitary = UnitaryGate(Operator(J.conj().T))
qc.append(Jdagger_unitary, [0,1])
results = execute(qc, simulator, shots=1024).result().get_counts()
alice_payoff, bob_payoff = get_payoff(results)
print("Strategy: {}".format(results))
print("Alice's payoff is {}, Bob's payoff is {}".format(alice_payoff, bob_payoff))
import matplotlib.pyplot as plt
space_size = 40
def payoff_plot():
"""
Plot expected payoff distribution for Alice.
"""
x = np.linspace(1, -1, space_size)
y = np.linspace(-1, 1, space_size)
X, Y = np.meshgrid(x, y)
Z = np.zeros(X.shape)
for i in range(0,space_size):
for inner in range(0, space_size):
if X[inner][i] < 0 and Y[inner][i] < 0:
qc = alice_bob_play_quantum(0, X[inner][i]*np.pi/2, 0, Y[inner][i]*np.pi/2)
payoff_alice, _ = get_payoff(execute(qc, simulator, shots=1024).result().get_counts())
Z[inner][i] = payoff_alice
elif X[inner][i] >= 0 and Y[inner][i] >= 0:
qc = alice_bob_play_quantum(X[inner][i]*np.pi, 0, Y[inner][i]*np.pi, 0)
payoff_alice, _ = get_payoff(execute(qc, simulator, shots=1024).result().get_counts())
Z[inner][i] = payoff_alice
elif X[inner][i] >= 0 and Y[inner][i] < 0:
qc = alice_bob_play_quantum(X[inner][i]*np.pi, 0, 0, Y[inner][i]*np.pi/2)
payoff_alice, _ = get_payoff(execute(qc, simulator, shots=1024).result().get_counts())
Z[inner][i] = payoff_alice
elif X[inner][i] < 0 and Y[inner][i] >= 0:
qc = alice_bob_play_quantum(0, X[inner][i]*np.pi/2, Y[inner][i]*np.pi, 0)
payoff_alice, _ = get_payoff(execute(qc, simulator, shots=1024).result().get_counts())
Z[inner][i] = payoff_alice
fig = plt.figure(figsize=(15, 10))
ax = fig.add_subplot(111, projection='3d')
ax.plot_surface(X, Y, Z, cmap=plt.cm.coolwarm, antialiased=True)
ax.set(xlim=(-1, 1), ylim=(1, -1), xlabel="Bob strategy", ylabel='Alice strategy', zlabel="Alice's expected payoff")
plt.show()
payoff_plot()
def build_qcir_three_parameters(theta1, phi1, lmbda, theta2, phi2):
"""
Set up a quantum game. Both players have access to quantum strategies space
"""
alice = np.array([
[np.exp(1.0j*phi1)*np.cos(theta1/2), 1.0j*np.exp(1.0j * lmbda) * np.sin(theta1/2)],
[1.0j*np.exp(-1.0j * lmbda) * np.sin(theta1/2), np.exp(-1.0j*phi1)*np.cos(theta1/2)]])
bob = np.array([
[np.exp(1.0j*phi2)*np.cos(theta2/2), np.sin(theta2/2)],
[-np.sin(theta2/2), np.exp(-1.0j*phi2)*np.cos(theta2/2)]])
qc = QuantumCircuit(num_players)
J = 1/np.sqrt(2)*np.array([[1.0, 0.0, 0.0, 1.0j],
[0.0, 1.0, 1.0j, 0.0],
[0.0, 1.0j, 1.0, 0.0],
[1.0j, 0.0, 0.0, 1.0]]).astype(complex)
J_unitary = UnitaryGate(Operator(J))
qc.append(J_unitary, [0,1])
qc.barrier()
unitary_alice = UnitaryGate(Operator(alice))
unitary_bob = UnitaryGate(Operator(bob))
qc.append(unitary_alice, [0])
qc.append(unitary_bob, [1])
qc.barrier()
Jdagger_unitary = UnitaryGate(Operator(J.conj().T))
qc.append(Jdagger_unitary, [0,1])
return qc
alice_reward = 0
bob_reward = 0
draw = 0
space_size = 4
for phi1 in np.linspace(-np.pi, np.pi, space_size):
for theta1 in np.linspace(0, np.pi, space_size):
for phi2 in np.linspace(-np.pi, np.pi, space_size):
for theta2 in np.linspace(0, np.pi, space_size):
for lmbda in np.linspace(-np.pi, np.pi, 2*space_size):
qc = build_qcir_three_parameters(theta1, phi1, lmbda, theta2, phi2)
results = execute(qc, simulator, shots=1024).result().get_counts()
payoff_alice, payoff_bob = get_payoff(results)
# count winning
if payoff_alice > payoff_bob:
alice_reward += 1
elif payoff_bob > payoff_alice:
bob_reward += 1
else:
draw += 1
# print results
print("theta_alice = {}, phi_alice = {}, theta_bob = {}, phi_bob = {}".format(theta1, phi1, theta2, phi2 ))
print("results = {}, Alice's payoff {}, Bob's payoff {}".format(results, payoff_alice, payoff_bob))
print("Next Game")
print("===================================================")
print("In {} games Alice gets a higher reward than Bob.". format(alice_reward))
print("In {} games, Bob gets a higher reward than Alice.".format(bob_reward))
print("In {} games Alice and Bob get equal reward.".format(draw))
!python3 -m pip install -q qiskit-ibm-provider
from qiskit.providers.ibmq import least_busy
from qiskit_ibm_provider import IBMProvider
provider = IBMProvider()
# ====================================
# pass IBM API Token
# ====================================
provider.save_account(token=, overwrite=True)
small_devices = provider.backends(filters=lambda x: x.configuration().n_qubits == 5 and not x.configuration().simulator)
least_busy(small_devices)
backend = least_busy(small_devices)
qc = alice_bob_play_quantum(theta_a = 0, phi_a = 0, theta_b = np.pi/2, phi_b = 0, measure=True)
job = execute(qc, backend, optimization_level=2)
result = job.result()
counts = result.get_counts()
counts
plot_histogram(counts)
job = execute(qc, backend=Aer.get_backend('statevector_simulator'), shots=1024)
result = job.result()
counts = result.get_counts()
print(counts)
plot_histogram(counts)
from functools import reduce
from operator import add
from qiskit import quantum_info as qi
def mixed_strategy(alpha_a:float, alpha_b:float):
"""
Set up a quantum game. Both players have access to quantum strategies.
Args:
theta_a: Theta parameter for Alice's unitary.
phi_a: Phi parameter for Alice's unitary.
theta_b: Theta parameter for Bob's unitary.
phi_b: Phi parameter for Bob's unitary.
Returns:
qc: the class of 'qiskit.circuit.quantumcircuit.QuantumCircuit',
a constructed quantum circuit for the quantum game set up.
"""
qc = QuantumCircuit(2)
# Alice strategies
unitary1_a = np.eye(2).astype(complex)
unitary2_a = np.array([[-1.0j, 0],
[0, 1.0j]])
# Bob's strategies
unitary1_b = np.array([[0, 1],
[-1, 0]]).astype(complex)
unitary2_b = np.array([[0, -1.0j],
[-1.0j, 0]]).astype(complex)
# define probabilities for Alice
p1_a = np.cos(alpha_a / 2) ** 2
p2_a = np.sin(alpha_a/ 2) ** 2
# define probabilities for Bob
p1_b = np.cos(alpha_b / 2) ** 2
p2_b = np.sin(alpha_b/ 2) ** 2
# define the set of actions and their probability distribution.
mixed_strategy = [[(p1_a, unitary1_a), (p2_a, unitary2_a)], [(p1_b, unitary1_b), (p2_b, unitary2_b)]]
identity = np.eye(2)
J = 1/np.sqrt(2)*np.array([[1.0, 0.0, 0.0, 1.0j],
[0.0, 1.0, 1.0j, 0.0],
[0.0, 1.0j, 1.0, 0.0],
[1.0j, 0.0, 0.0, 1.0]]).astype(complex)
J_unitary = UnitaryGate(Operator(J))
qc.append(J_unitary, [0, 1])
rho = qi.DensityMatrix.from_instruction(qc)
for index, strategy in enumerate(mixed_strategy):
rho = reduce(add, (prob * rho.evolve(np.kron(*[strat if index == player else identity for player in range(num_players)])) for prob, strat in strategy))
rho = rho.evolve(Operator(J.conj().T))
return rho.probabilities()
payoff_matrix =[[[3, 0],
[5, 1]],
[[3, 5],
[0, 1]]]
for alpha_a in np.linspace(0, np.pi, 4):
for alpha_b in np.linspace(0, np.pi, 2):
print("alpha_a = ", alpha_a)
print("alpha_b = ", alpha_b)
prob = mixed_strategy(alpha_a, alpha_b)
print("prob = ", prob)
alice_matrix = np.reshape(payoff_matrix[0], (1,4))
bob_matrix = np.reshape(payoff_matrix[1], (1,4))
print("Alice's Payoff = ", np.round(np.dot(prob, alice_matrix[0]), 3))
print("Bob's Payoff = ", np.round(np.dot(prob, bob_matrix[0]),3))
print("=======================")
# probability of 1/2 and 1/2 yeilds the payoffs of 2.5 for each player.
prob = mixed_strategy(np.pi/2, np.pi/2)
print("prob = ", prob)
alice_matrix = np.reshape(payoff_matrix[0], (1,4))
bob_matrix = np.reshape(payoff_matrix[1], (1,4))
print("Alice's Payoff = ", np.round(np.dot(prob, alice_matrix[0]), 3))
print("Bob's Payoff = ", np.round(np.dot(prob, bob_matrix[0]),3))
|
https://github.com/ryanlevy/shadow-tutorial
|
ryanlevy
|
import numpy as np
import matplotlib.pyplot as plt
import qiskit
pauli_list = [
np.eye(2),
np.array([[0.0, 1.0], [1.0, 0.0]]),
np.array([[0, -1.0j], [1.0j, 0.0]]),
np.array([[1.0, 0.0], [0.0, -1.0]]),
]
s_to_pauli = {
"I": pauli_list[0],
"X": pauli_list[1],
"Y": pauli_list[2],
"Z": pauli_list[3],
}
def channel(N,qc):
'''create an N qubit GHZ state '''
qc.h(0)
if N>=2: qc.cx(0,1)
if N>=3: qc.cx(0,2)
if N>=4: qc.cx(1,3)
if N>4: raise NotImplementedError(f"{N} not implemented!")
def bitGateMap(qc,g,qi):
'''Map X/Y/Z string to qiskit ops'''
if g=="X":
qc.h(qi)
elif g=="Y":
qc.sdg(qi)
qc.h(qi)
elif g=="Z":
pass
else:
raise NotImplementedError(f"Unknown gate {g}")
def Minv(N,X):
'''inverse shadow channel'''
return ((2**N+1.))*X - np.eye(2**N)
def trace_dist(lam_exact,rho):
''' returns normalized trace distance between lam_exact and rho'''
mid = (lam_exact-rho).conj().T@(lam_exact-rho)
N = 2**int(np.log2(lam_exact.shape[0])/2)
# svd mid and apply sqrt to singular values
# based on qiskit internals function
U1,d,U2 = np.linalg.svd(mid)
sqrt_mid = U1@np.diag(np.sqrt(d))@U2
dist = np.trace(sqrt_mid)/2
return dist/N
qc = qiskit.QuantumCircuit(2)
qc.h(0)
qc.cx(0,1)
choi_actual = qiskit.quantum_info.Choi(qc)
qc.draw(output='mpl')
plt.imshow(choi_actual.data.real)
qiskit.visualization.state_visualization.plot_state_city(choi_actual.data)
N = 2
qc = qiskit.QuantumCircuit(2*N)
for i in range(N):
qc.h(i+N)
qc.cx(i+N,i)
qc.barrier()
channel(N,qc)
qc.draw(output='mpl')
choi_state = qiskit.quantum_info.DensityMatrix(qc)
# this is the same up to normalization
# Tr[lambda] = 2^N
np.allclose(choi_state.data*2**N,choi_actual)
nShadows = 1_000
reps = 50
N = 2
rng = np.random.default_rng(1717)
cliffords = [qiskit.quantum_info.random_clifford(N*2,seed=rng) for _ in range(nShadows)]
N = 2
qc = qiskit.QuantumCircuit(2*N)
for i in range(N):
qc.h(i+N)
qc.cx(i+N,i)
channel(N,qc)
results = []
for cliff in cliffords:
qc_c = qc.compose(cliff.to_circuit())
counts = qiskit.quantum_info.Statevector(qc_c).sample_counts(reps)
results.append(counts)
rho_shadow = 0.+0j
for cliff,res in zip(cliffords,results):
mat = cliff.adjoint().to_matrix()
for bit,count in res.items():
Ub = mat[:,int(bit,2)] # this is Udag|b>
rho_shadow += (Minv(N*2,np.outer(Ub,Ub.conj()))*count)
rho_shadow /=( nShadows*reps)
rho_shadow *= 2**N
assert np.allclose(rho_shadow.trace(),2**N)
plt.subplot(121)
plt.suptitle("Correct")
plt.imshow(choi_actual.data.real,vmax=0.7,vmin=-0.7)
plt.subplot(122)
plt.imshow(choi_actual.data.imag,vmax=0.7,vmin=-0.7)
plt.show()
print("---")
plt.subplot(121)
plt.suptitle("Shadow(Full Clifford)")
plt.imshow(rho_shadow.real,vmax=0.7,vmin=-0.7)
plt.subplot(122)
plt.imshow(rho_shadow.imag,vmax=0.7,vmin=-0.7)
plt.show()
qiskit.visualization.state_visualization.plot_state_city(choi_actual.data,title="Correct")
qiskit.visualization.state_visualization.plot_state_city(rho_shadow,title="Shadow (clifford)")
_,vs = np.linalg.eigh(rho_shadow)
rho_shadow_pure = np.outer(vs[:,-1],vs[:,-1].conj().T)*2**N
print(f"original trace distance = {trace_dist(choi_actual.data,rho_shadow).real:0.4f}")
print(f"Purified trace distance = {trace_dist(choi_actual.data,rho_shadow_pure).real:0.4f}")
nShadows = 1_000
reps = 50
N = 2
rng = np.random.default_rng(1717)
front_cliffords = [qiskit.quantum_info.random_clifford(N,seed=rng) for _ in range(nShadows)]
back_cliffords = [qiskit.quantum_info.random_clifford(N,seed=rng) for _ in range(nShadows)]
N = 2
qc = qiskit.QuantumCircuit(N)
results = []
for front,back in zip(front_cliffords,back_cliffords):
qc_c = qc.compose(front.adjoint().to_circuit())
channel(N,qc_c)
qc_c = qc_c.compose(back.to_circuit())
counts = qiskit.quantum_info.Statevector(qc_c).sample_counts(reps)
results.append(counts)
rho_shadow2 = 0.+0j
for front, back, res in zip(front_cliffords, back_cliffords, results):
mat_front = front.to_matrix()
mat_back = back.adjoint().to_matrix()
U0_front = mat_front.T[:, 0] # this is <0|U or U^T|0>
M_front = Minv(N, np.outer(U0_front, U0_front.conj()))
for bit, count in res.items():
Ub = mat_back[:, int(bit, 2)] # this is Udag|b>
M_back = Minv(N, np.outer(Ub, Ub.conj()))
rho_shadow2 += np.kron(M_front, M_back) * count
rho_shadow2 /= nShadows * reps
rho_shadow2 *= 2**N
assert np.allclose(rho_shadow2.trace(),2**N)
plt.subplot(121)
plt.suptitle("Correct")
plt.imshow(choi_actual.data.real,vmax=0.7,vmin=-0.7)
plt.subplot(122)
plt.imshow(choi_actual.data.imag,vmax=0.7,vmin=-0.7)
plt.show()
print("---")
plt.subplot(121)
plt.suptitle("Shadow(Full Clifford, 2 sided)")
plt.imshow(rho_shadow2.real,vmax=0.7,vmin=-0.7)
plt.subplot(122)
plt.imshow(rho_shadow2.imag,vmax=0.7,vmin=-0.7)
plt.show()
print(f"ancilla trace distance = {trace_dist(choi_actual.data,rho_shadow).real:0.4f}")
print(f"two sided trace distance = {trace_dist(choi_actual.data,rho_shadow2).real:0.4f}")
plt.subplot(121)
plt.title("Shadow(Full Clifford, Ancilla)")
plt.imshow(rho_shadow.real,vmax=0.7,vmin=-0.7)
plt.subplot(122)
plt.title("Shadow(Full Clifford, 2 sided)")
plt.imshow(rho_shadow2.real,vmax=0.7,vmin=-0.7)
plt.show()
N = 2
# Channel
qc = qiskit.QuantumCircuit(N)
channel(N,qc)
# test state
sigma = qiskit.QuantumCircuit(N)
sigma.ry(1.23,0)
sigma.ry(2.34,1)
# input to channel to predict
qc_in = qiskit.QuantumCircuit(N)
qc_in.rx(.11,0)
qc_in.rx(.22,1)
rho_in = qiskit.quantum_info.DensityMatrix(qc_in)
rho_sigma = qiskit.quantum_info.DensityMatrix(sigma)
# Version 1, run the circuit above and measure P(00) state
qc_all = qc_in.compose(qc)
# now apple inverse(sigmaa)
qc_all.ry(-1.23,0)
qc_all.ry(-2.34,1)
qc_all.draw()
overlap_full = np.abs(qiskit.quantum_info.Statevector(qc_all)[0])**2
# version 2, evolve via the true choi matrix
overlap_trace = np.trace(np.kron(rho_in.data.T,rho_sigma.data)@choi_actual.data).real
# version 3, qiskit formalism
rho_evolve = choi_actual._evolve(rho_in)
overlap_evolve = rho_sigma.expectation_value(rho_evolve).real
print(f"trace circuit={overlap_full:0.4f}")
print(f"trace ={overlap_trace:0.4f}")
print(f"evolution ={overlap_evolve:0.4f}")
shadow_overlap = np.trace(np.kron(rho_in.data.T,rho_sigma.data)@rho_shadow).real
shadow_overlap2 = np.trace(np.kron(rho_in.data.T,rho_sigma.data)@rho_shadow2).real
print(f"ancilla shadow ={shadow_overlap:0.4f} (prediction)")
print(f"two sided shadow ={shadow_overlap2:0.4f} (prediction)")
rho_out = qiskit.quantum_info.Choi(rho_shadow2)._evolve(rho_in)
print(f"Tr[rho_out]={rho_out.trace().real:0.4f}")
eigs = np.linalg.eigvalsh(rho_out.data)
print(f"sum of eigenvalues below 0 ={np.sum(eigs[eigs<0]):0.4f}")
def purify(N,lam):
_,vs = np.linalg.eigh(lam)
lam_pure = np.outer(vs[:,-1],vs[:,-1].conj().T) * 2**N
return lam_pure
shadow_overlap_pure = np.trace(np.kron(rho_in.data.T,rho_sigma.data)@purify(N,rho_shadow)).real
shadow_overlap2_pure = np.trace(np.kron(rho_in.data.T,rho_sigma.data)@purify(N,rho_shadow2)).real
print(f"trace circuit = {overlap_full:0.4f}")
print(f"ancilla shadow = {shadow_overlap_pure:0.4f} (prediction)")
print(f"two sided shadow = {shadow_overlap2_pure:0.4f} (prediction)")
rho_out = qiskit.quantum_info.Choi(purify(N,rho_shadow2))._evolve(rho_in)
print(f"Tr[rho_out]={rho_out.trace().real:0.4f}")
eigs = np.linalg.eigvalsh(rho_out.data)
print(f"sum of eigenvalues below 0 ={np.sum(eigs[eigs<0]):0.4f}")
import scipy.sparse as sps
def partial_trace_super(dim1, dim2):
"""
From Qiskit internals
Return the partial trace superoperator in the column-major basis.
This returns the superoperator S_TrB such that:
S_TrB * vec(rho_AB) = vec(rho_A)
for rho_AB = kron(rho_A, rho_B)
Args:
dim1: the dimension of the system not being traced
dim2: the dimension of the system being traced over
Returns:
A Numpy array of the partial trace superoperator S_TrB.
"""
iden = sps.identity(dim1)
ptr = sps.csr_matrix((dim1 * dim1, dim1 * dim2 * dim1 * dim2))
for j in range(dim2):
v_j = sps.coo_matrix(([1], ([0], [j])), shape=(1, dim2))
tmp = sps.kron(iden, v_j.tocsr())
ptr += sps.kron(tmp, tmp)
return ptr
def make_tp(rho, validate=True,
MtM=None, Mb=None):
'''
Projects a 4^N x 4^N choi matrix into the space of TP matrices
Citation: 10.1103/PhysRevA.98.062336
'''
dim = rho.shape[0]
sdim = int(np.sqrt(dim))
if MtM==None and Mb==None:
M = partial_trace_super(sdim, sdim) # M*vec[rho] should be identity
MdagM = M.conj().T@M
MdagI = M.conj().T@np.eye(sdim).ravel('F')
# vec[rho] operation
vec_rho = rho.ravel('F')
new_rho = vec_rho - 1/sdim * MdagM@vec_rho + 1/sdim * MdagI
new_rho = new_rho.reshape(dim,dim,order='F')
if validate:
if abs(rho.trace().real-new_rho.trace().real) > 1e-4:
print(rho.trace(),new_rho.trace())
assert abs(rho.trace().real-new_rho.trace().real) < 1e-4
return new_rho
rho_out_tp = qiskit.quantum_info.Choi(make_tp(purify(N,rho_shadow2)))._evolve(rho_in)
print(f"Tr[rho_out]={rho_out_tp.trace().real:0.4f}")
eigs = np.linalg.eigvalsh(rho_out_tp.data)
print(f"sum of eigenvalues below 0 ={np.sum(eigs[eigs<0]):0.4f}")
print(f"trace circuit = {overlap_full:0.4f}")
print("---")
print(f"two sided shadow = {shadow_overlap2:0.4f} (prediction)")
print(f"two sided shadow = {shadow_overlap2_pure:0.4f} (prediction purified)")
print(f"two sided shadow = {np.trace(rho_out_tp.data@rho_sigma.data).real:0.4f} (prediction TP(purified))")
|
https://github.com/ryanlevy/shadow-tutorial
|
ryanlevy
|
import numpy as np
import matplotlib.pyplot as plt
import qiskit
pauli_list = [
np.eye(2),
np.array([[0.0, 1.0], [1.0, 0.0]]),
np.array([[0, -1.0j], [1.0j, 0.0]]),
np.array([[1.0, 0.0], [0.0, -1.0]]),
]
s_to_pauli = {
"I": pauli_list[0],
"X": pauli_list[1],
"Y": pauli_list[2],
"Z": pauli_list[3],
}
def channel(N,qc):
'''create an N qubit GHZ state '''
qc.h(0)
if N>=2: qc.cx(0,1)
if N>=3: qc.cx(0,2)
if N>=4: qc.cx(1,3)
if N>4: raise NotImplementedError(f"{N} not implemented!")
def bitGateMap(qc,g,qi):
'''Map X/Y/Z string to qiskit ops'''
if g=="X":
qc.h(qi)
elif g=="Y":
qc.sdg(qi)
qc.h(qi)
elif g=="Z":
pass
else:
raise NotImplementedError(f"Unknown gate {g}")
def Minv(N,X):
'''inverse shadow channel'''
return ((2**N+1.))*X - np.eye(2**N)
qc = qiskit.QuantumCircuit(4)
qc.h(0)
qc.cx(0,1)
qc.barrier()
qc.cx(0,2)
qc.barrier()
qc.cx(1,3)
qc.draw(output='mpl')
qc = qiskit.QuantumCircuit(3)
channel(3,qc)
qc.draw(output='mpl')
nShadows = 100
reps = 1
N = 2
rng = np.random.default_rng(1717)
cliffords = [qiskit.quantum_info.random_clifford(N, seed=rng) for _ in range(nShadows)]
qc = qiskit.QuantumCircuit(N)
channel(N,qc)
results = []
for cliff in cliffords:
qc_c = qc.compose(cliff.to_circuit())
counts = qiskit.quantum_info.Statevector(qc_c).sample_counts(reps)
results.append(counts)
qc.draw()
qc_c.draw()
shadows = []
for cliff, res in zip(cliffords, results):
mat = cliff.adjoint().to_matrix()
for bit,count in res.items():
Ub = mat[:,int(bit,2)] # this is Udag|b>
shadows.append(Minv(N,np.outer(Ub,Ub.conj()))*count)
rho_shadow = np.sum(shadows,axis=0)/(nShadows*reps)
rho_actual = qiskit.quantum_info.DensityMatrix(qc).data
plt.subplot(121)
plt.suptitle("Correct")
plt.imshow(rho_actual.real,vmax=0.7,vmin=-0.7)
plt.subplot(122)
plt.imshow(rho_actual.imag,vmax=0.7,vmin=-0.7)
plt.show()
print("---")
plt.subplot(121)
plt.suptitle("Shadow(Full Clifford)")
plt.imshow(rho_shadow.real,vmax=0.7,vmin=-0.7)
plt.subplot(122)
plt.imshow(rho_shadow.imag,vmax=0.7,vmin=-0.7)
plt.show()
qiskit.visualization.state_visualization.plot_state_city(rho_actual,title="Correct")
qiskit.visualization.state_visualization.plot_state_city(rho_shadow,title="Shadow (clifford)")
nShadows = 10_000
N = 2
rng = np.random.default_rng(1717)
scheme = [rng.choice(['X','Y','Z'],size=N) for _ in range(nShadows)]
labels, counts = np.unique(scheme,axis=0,return_counts=True)
qc = qiskit.QuantumCircuit(N)
channel(N,qc)
results = []
for bit_string,count in zip(labels,counts):
qc_m = qc.copy()
# rotate the basis for each qubit
for i,bit in enumerate(bit_string): bitGateMap(qc_m,bit,i)
counts = qiskit.quantum_info.Statevector(qc_m).sample_counts(count)
results.append(counts)
def rotGate(g):
'''produces gate U such that U|psi> is in Pauli basis g'''
if g=="X":
return 1/np.sqrt(2)*np.array([[1.,1.],[1.,-1.]])
elif g=="Y":
return 1/np.sqrt(2)*np.array([[1.,-1.0j],[1.,1.j]])
elif g=="Z":
return np.eye(2)
else:
raise NotImplementedError(f"Unknown gate {g}")
shadows = []
shots = 0
for pauli_string,counts in zip(labels,results):
# iterate over measurements
for bit,count in counts.items():
mat = 1.
for i,bi in enumerate(bit[::-1]):
b = rotGate(pauli_string[i])[int(bi),:]
mat = np.kron(Minv(1,np.outer(b.conj(),b)),mat)
shadows.append(mat*count)
shots+=count
rho_shadow = np.sum(shadows,axis=0)/(shots)
rho_actual = qiskit.quantum_info.DensityMatrix(qc).data
plt.subplot(121)
plt.suptitle("Correct")
plt.imshow(rho_actual.real,vmax=0.7,vmin=-0.7)
plt.subplot(122)
plt.imshow(rho_actual.imag,vmax=0.7,vmin=-0.7)
plt.show()
print("---")
plt.subplot(121)
plt.suptitle("Shadow(Pauli)")
plt.imshow(rho_shadow.real,vmax=0.7,vmin=-0.7)
plt.subplot(122)
plt.imshow(rho_shadow.imag,vmax=0.7,vmin=-0.7)
plt.show()
|
https://github.com/ShabaniLab/qiskit-hackaton-2019
|
ShabaniLab
|
import numpy as np
from qiskit.circuit import QuantumCircuit, QuantumRegister, ClassicalRegister
from ising_kitaev import initialize_chain, braid_chain, rotate_to_measurement_basis, add_measurement, initialize_coupler
zeeman_ferro = 0.01
zeeman_para = 10
initial_config = np.array([zeeman_ferro]*3 + [zeeman_para]*9)
qreg = QuantumRegister(13)
creg = ClassicalRegister(3)
qcirc = QuantumCircuit(qreg, creg)
initialize_chain(qcirc, qreg, initial_config, 'up')
initialize_coupler(qcirc, qreg)
qcirc.draw()
braid_chain(qcirc, qreg, np.pi, 40, initial_config, 1.4, 0.25, 0.25, 2, 40, method='both')
qcirc.depth()
add_measurement(qcirc, qreg, creg, [0, 1, 2])
from qiskit import Aer, execute
backend = Aer.get_backend('qasm_simulator')
job = execute(qcirc, backend, shots=2000)
job.status()
result = job.result()
print(result.get_counts())
|
https://github.com/ShabaniLab/qiskit-hackaton-2019
|
ShabaniLab
|
import numpy as np
from qiskit.circuit import QuantumCircuit, QuantumRegister, ClassicalRegister
from ising_kitaev import initialize_chain, run_adiabatic_zeeman_change, rotate_to_measurement_basis, add_measurement
zeeman_ferro = 0.01
zeeman_para = 10
initial_config = np.array([zeeman_ferro, zeeman_ferro, zeeman_ferro, zeeman_para])
final_config = np.array([zeeman_ferro, zeeman_ferro, zeeman_ferro, zeeman_ferro])
qreg = QuantumRegister(4)
creg = ClassicalRegister(4)
qcirc = QuantumCircuit(qreg, creg)
initialize_chain(qcirc, qreg, initial_config, 'logical_one')
qcirc.draw()
run_adiabatic_zeeman_change(qcirc, qreg, initial_config, final_config, 0, 0.25, 0.25, 1, 10)
qcirc.depth()
rotate_to_measurement_basis(qcirc, qreg, [0, 1, 2, 3])
add_measurement(qcirc, qreg, creg, [0, 1, 2, 3])
from qiskit import Aer, execute
backend = Aer.get_backend('qasm_simulator')
job = execute(qcirc, backend, shots=2000)
job.status()
result = job.result()
print(result.get_counts())
|
https://github.com/ShabaniLab/qiskit-hackaton-2019
|
ShabaniLab
|
import numpy as np
from qiskit.circuit import QuantumCircuit, QuantumRegister, ClassicalRegister
from ising_kitaev import initialize_chain, move_chain, rotate_to_measurement_basis, add_measurement
zeeman_ferro = 0.01
zeeman_para = 10
initial_config = np.array([zeeman_ferro, zeeman_ferro, zeeman_ferro, zeeman_para])
final_config = np.array([zeeman_para, zeeman_ferro, zeeman_ferro, zeeman_ferro])
qreg = QuantumRegister(4)
creg = ClassicalRegister(3)
qcirc = QuantumCircuit(qreg, creg)
initialize_chain(qcirc, qreg, initial_config, 'logical_one')
qcirc.draw()
move_chain(qcirc, qreg, initial_config, final_config, 0, 0.25, 0.25, 1, 5, method='single')
qcirc.depth()
rotate_to_measurement_basis(qcirc, qreg, [1, 2, 3])
add_measurement(qcirc, qreg, creg, [1, 2, 3])
from qiskit import Aer, execute
backend = Aer.get_backend('qasm_simulator')
job = execute(qcirc, backend, shots=2000)
job.status()
result = job.result()
print(result.get_counts())
|
https://github.com/ShabaniLab/qiskit-hackaton-2019
|
ShabaniLab
|
import numpy as np
from qiskit.circuit import QuantumCircuit, QuantumRegister, ClassicalRegister
from ising_kitaev import initialize_chain, trotter, rotate_to_measurement_basis, add_measurement, initialize_coupler
zeeman_ferro = 0.01
zeeman_para = 10
initial_config = np.array([zeeman_para, zeeman_ferro, zeeman_ferro, zeeman_ferro])
qreg = QuantumRegister(5)
creg = ClassicalRegister(3)
qcirc = QuantumCircuit(qreg, creg)
initialize_chain(qcirc, qreg, initial_config, 'logical_one')
initialize_coupler(qcirc, qreg)
qcirc.draw()
trotter(qcirc, qreg, initial_config, 1.4, 0.1, 1)
qcirc.draw()
trotter(qcirc, qreg, initial_config, 0.0, 0.1, 1)
rotate_to_measurement_basis(qcirc, qreg, [1, 2, 3])
add_measurement(qcirc, qreg, creg, [1, 2, 3])
qcirc.draw()
from qiskit import Aer, execute
backend = Aer.get_backend('qasm_simulator')
job = execute(qcirc, backend, shots=2000)
job.status()
result = job.result()
print(result.get_counts())
|
https://github.com/ShabaniLab/qiskit-hackaton-2019
|
ShabaniLab
|
import numpy as np
from qiskit.circuit import QuantumCircuit, QuantumRegister, ClassicalRegister
from ising_kitaev import initialize_chain, move_chain, rotate_to_measurement_basis, add_measurement
zeeman_ferro = 0.01
zeeman_para = 10
initial_config = np.array([zeeman_ferro, zeeman_ferro, zeeman_ferro, zeeman_para])
final_config = np.array([zeeman_para, zeeman_ferro, zeeman_ferro, zeeman_ferro])
qreg = QuantumRegister(4)
creg = ClassicalRegister(3)
qcirc = QuantumCircuit(qreg, creg)
initialize_chain(qcirc, qreg, initial_config, 'logical_one')
qcirc.draw()
move_chain(qcirc, qreg, initial_config, final_config, 0, 0.25, 0.25, 1, 5, method='both')
qcirc.depth()
rotate_to_measurement_basis(qcirc, qreg, [1, 2, 3])
add_measurement(qcirc, qreg, creg, [1, 2, 3])
from qiskit import Aer, execute
backend = Aer.get_backend('qasm_simulator')
job = execute(qcirc, backend, shots=2000)
job.status()
result = job.result()
print(result.get_counts())
|
https://github.com/ShabaniLab/qiskit-hackaton-2019
|
ShabaniLab
|
import numpy as np
from qiskit.circuit import QuantumCircuit, QuantumRegister, ClassicalRegister
from ising_kitaev import initialize_chain, run_adiabatic_zeeman_change, rotate_to_measurement_basis, add_measurement
from ising_kitaev import move_chain
zeeman_ferro = 0.01 # value of on-site magnetic field for ferromagnetic domain
zeeman_para = 10 # value of on-site magnetic field for paramagnetic domain
initial_config = np.array([zeeman_ferro, zeeman_ferro, zeeman_ferro, zeeman_para, zeeman_para, zeeman_para])
final_config = np.array([zeeman_para, zeeman_para, zeeman_para, zeeman_ferro, zeeman_ferro, zeeman_ferro])
qreg = QuantumRegister(6)
creg = ClassicalRegister(3)
qcirc = QuantumCircuit(qreg, creg)
initialize_chain(qcirc, qreg, initial_config, 'logical_zero')
qcirc.draw()
move_chain(qcirc, qreg, initial_config, final_config, 0, 0.25, 0.25, 2, 10, method = "both")
qcirc.depth()
rotate_to_measurement_basis(qcirc, qreg, [3, 4, 5])
add_measurement(qcirc, qreg, creg, [3, 4, 5])
from qiskit import Aer, execute
backend = Aer.get_backend('qasm_simulator')
job = execute(qcirc, backend, shots=2000)
job.status()
result = job.result()
result.get_counts()
|
https://github.com/ShabaniLab/qiskit-hackaton-2019
|
ShabaniLab
|
import numpy as np
from qiskit.circuit import QuantumCircuit, QuantumRegister, ClassicalRegister
from ising_kitaev import initialize_chain, run_adiabatic_zeeman_change, rotate_to_measurement_basis, add_measurement
from ising_kitaev import move_chain, initialize_coupler
zeeman_ferro = 0.01 # value of on-site magnetic field for ferromagnetic domain
zeeman_para = 10 # value of on-site magnetic field for paramagnetic domain
# initial configuration of domains
initial_config = np.array([zeeman_ferro, zeeman_ferro, zeeman_ferro, zeeman_para, zeeman_para, zeeman_para])
# final configuration of domains
final_config = np.array([zeeman_para, zeeman_para, zeeman_para, zeeman_ferro, zeeman_ferro, zeeman_ferro])
qreg = QuantumRegister(7)
creg = ClassicalRegister(3)
qcirc = QuantumCircuit(qreg, creg)
initialize_chain(qcirc, qreg, initial_config, 'logical_zero')
initialize_coupler(qcirc, qreg) # couple the chain to a coupler
qcirc.draw()
# moving ferromagenetic domain to one end
move_chain(qcirc, qreg, initial_config, final_config, 1.4, 0.25, 0.25, 2, 20, method = "both")
# moving back the ferromagnetic domain
move_chain(qcirc, qreg, final_config, initial_config, 1.4, 0.25, 0.25, 2, 20, method = "both")
qcirc.depth()
rotate_to_measurement_basis(qcirc, qreg, [0, 1, 2]) # measurement in logical basis
add_measurement(qcirc, qreg, creg, [0, 1, 2])
from qiskit import Aer, execute
backend = Aer.get_backend('qasm_simulator')
job = execute(qcirc, backend, shots=2000)
job.status()
result = job.result()
result.get_counts()
|
https://github.com/ShabaniLab/qiskit-hackaton-2019
|
ShabaniLab
|
import numpy as np
from qiskit.circuit import QuantumCircuit, QuantumRegister, ClassicalRegister
from ising_kitaev import initialize_chain, run_adiabatic_zeeman_change, rotate_to_measurement_basis, add_measurement
zeeman_ferro = 0.01
zeeman_para = 10
initial_config = np.array([zeeman_ferro, zeeman_ferro, zeeman_ferro, zeeman_ferro])
final_config = np.array([zeeman_para, zeeman_ferro, zeeman_ferro, zeeman_ferro])
qreg = QuantumRegister(4)
creg = ClassicalRegister(3)
qcirc = QuantumCircuit(qreg, creg)
initialize_chain(qcirc, qreg, initial_config, 'logical_one')
qcirc.draw()
run_adiabatic_zeeman_change(qcirc, qreg, initial_config, final_config, 0, 0.25, 0.25, 2, 20)
qcirc.depth()
rotate_to_measurement_basis(qcirc, qreg, [1, 2, 3])
add_measurement(qcirc, qreg, creg, [1, 2, 3])
from qiskit import Aer, execute
backend = Aer.get_backend('qasm_simulator')
job = execute(qcirc, backend, shots=2000)
job.status()
result = job.result()
print(result.get_counts())
|
https://github.com/ShabaniLab/qiskit-hackaton-2019
|
ShabaniLab
|
import numpy as np
from qiskit.circuit import QuantumCircuit, QuantumRegister, ClassicalRegister
from ising_kitaev.trotter import interaction_hamiltonian, chain_hamiltonian
qreg = QuantumRegister(5)
qcirc = QuantumCircuit(qreg)
chain_hamiltonian(qcirc, qreg, 0.1, np.array([10, 0.1, 0.1, 0.1])/10, True)
print(qcirc.draw())
qcirc = QuantumCircuit(qreg)
interaction_hamiltonian(qcirc, qreg, 1, 2, 0.14)
print(qcirc.draw())
|
https://github.com/Advanced-Research-Centre/QPULBA
|
Advanced-Research-Centre
|
import numpy as np
import random
from qiskit import QuantumCircuit, Aer, execute
from math import log2, ceil, pi, sin
#=====================================================================================================================
simulator = Aer.get_backend('statevector_simulator')
def disp_isv(circ, msg="", all=True, precision=1e-8):
sim_res = execute(circ, simulator).result()
statevector = sim_res.get_statevector(circ)
qb = int(log2(len(statevector)))
print("\n============ State Vector ============", msg)
s = 0
for i in statevector:
if (all == True): print(' ({:+.5f}) |{:0{}b}>'.format(i,s,qb))
else:
if (abs(i) > precision): print(' ({:+.5f}) |{:0{}b}>'.format(i,s,qb))
s = s+1
print("============..............============")
return
#=====================================================================================================================
def U_init(qcirc, dummy, search):
# product state qubits not part of search qubits does not matter even if superposed
# qcirc.i(dummy)
# qcirc.x(dummy)
qcirc.h(dummy)
# qcirc.ry(0.25,dummy)
return
#=====================================================================================================================
def U_oracle1(sz):
print("Oracle marks {0000}")
tgt_reg = list(range(0,sz))
oracle = QuantumCircuit(len(tgt_reg))
oracle.x(tgt_reg)
oracle.h(tgt_reg[0])
oracle.mct(tgt_reg[1:],tgt_reg[0])
oracle.h(tgt_reg[0])
oracle.x(tgt_reg)
return oracle
def U_oracle2(sz):
print("Oracle marks {0000, 1111}")
tgt_reg = list(range(0,sz))
oracle = QuantumCircuit(len(tgt_reg))
# 0000
oracle.x(tgt_reg)
oracle.h(tgt_reg[0])
oracle.mct(tgt_reg[1:],tgt_reg[0])
oracle.h(tgt_reg[0])
oracle.x(tgt_reg)
# 1111
oracle.h(tgt_reg[0])
oracle.mct(tgt_reg[1:],tgt_reg[0])
oracle.h(tgt_reg[0])
return oracle
def U_oracle3(sz):
print("Oracle marks {0000, 0101, 1111}")
tgt_reg = list(range(0,sz))
oracle = QuantumCircuit(len(tgt_reg))
# 0000
oracle.x(tgt_reg)
oracle.h(tgt_reg[0])
oracle.mct(tgt_reg[1:],tgt_reg[0])
oracle.h(tgt_reg[0])
oracle.x(tgt_reg)
# 0101
oracle.x(tgt_reg[1])
oracle.x(tgt_reg[3])
oracle.h(tgt_reg[0])
oracle.mct(tgt_reg[1:],tgt_reg[0])
oracle.h(tgt_reg[0])
oracle.x(tgt_reg[3])
oracle.x(tgt_reg[1])
# 1111
oracle.h(tgt_reg[0])
oracle.mct(tgt_reg[1:],tgt_reg[0])
oracle.h(tgt_reg[0])
return oracle
def U_oracle5(sz):
print("Oracle marks {0111, 1111, 1001, 1011, 0101}")
tgt_reg = list(range(0,sz))
oracle = QuantumCircuit(len(tgt_reg))
oracle.h([2,3])
oracle.ccx(0,1,2)
oracle.h(2)
oracle.x(2)
oracle.ccx(0,2,3)
oracle.x(2)
oracle.h(3)
oracle.x([1,3])
oracle.h(2)
oracle.mct([0,1,3],2)
oracle.x([1,3])
oracle.h(2)
return oracle
#=====================================================================================================================
# def U_diffuser(sz):
# # Amplitude amplification on all qubits except count
# tgt_reg = list(range(0,sz))
# diffuser = QuantumCircuit(len(tgt_reg))
# diffuser.h(tgt_reg)
# diffuser.x(tgt_reg)
# diffuser.h(tgt_reg[0])
# diffuser.mct(tgt_reg[1:],tgt_reg[0])
# diffuser.h(tgt_reg[0])
# diffuser.x(tgt_reg)
# diffuser.h(tgt_reg)
# return diffuser
def U_diffuser(sz):
# https://qiskit.org/textbook/ch-algorithms/quantum-counting.html
tgt_reg = list(range(0,sz))
diffuser = QuantumCircuit(len(tgt_reg))
diffuser.h(tgt_reg[1:])
diffuser.x(tgt_reg[1:])
diffuser.z(tgt_reg[0])
diffuser.mct(tgt_reg[1:],tgt_reg[0])
diffuser.x(tgt_reg[1:])
diffuser.h(tgt_reg[1:])
diffuser.z(tgt_reg[0])
return diffuser
#=====================================================================================================================
def U_QFT(n):
# n-qubit QFT circuit
qft = QuantumCircuit(n)
def swap_registers(qft, n):
for qubit in range(n//2):
qft.swap(qubit, n-qubit-1)
return qft
def qft_rotations(qft, n):
# Performs qft on the first n qubits in circuit (without swaps)
if n == 0:
return qft
n -= 1
qft.h(n)
for qubit in range(n):
qft.cu1(np.pi/2**(n-qubit), qubit, n)
qft_rotations(qft, n)
qft_rotations(qft, n)
swap_registers(qft, n)
return qft
#=====================================================================================================================
qnos = [1, 4, 6]
dummy = list(range(sum(qnos[0:0]),sum(qnos[0:1])))
search = list(range(sum(qnos[0:1]),sum(qnos[0:2])))
count = list(range(sum(qnos[0:2]),sum(qnos[0:3])))
qcirc_width = sum(qnos[0:3])
qcirc = QuantumCircuit(qcirc_width, len(count))
#=====================================================================================================================
# Create controlled Grover oracle circuit
oracle = U_oracle3(len(search)).to_gate()
c_oracle = oracle.control()
c_oracle.label = "cGO"
# Create controlled Grover diffuser circuit
# diffuser = U_diffuser(len(search)).to_gate()
diffuser = U_diffuser(len(dummy)+len(search)).to_gate()
c_diffuser = diffuser.control()
c_diffuser.label = "cGD"
# Create inverse QFT circuit
iqft = U_QFT(len(count)).to_gate().inverse()
iqft.label = "iQFT"
#=====================================================================================================================
# qcirc.ry(0.55,search) # probability of states assumed to be equal in counting
qcirc.h(search)
qcirc.barrier()
U_init(qcirc, dummy, search)
# print()
# disp_isv(qcirc, "Step: Search state vector", all=False, precision=1e-4)
qcirc.h(count)
qcirc.barrier()
viewMarking = 1
# Begin controlled Grover iterations
iterations = 1
for qb in count:
for i in range(iterations):
qcirc.append(c_oracle, [qb] + search)
# qcirc.append(c_diffuser, [qb] + search)
qcirc.append(c_diffuser, [qb] + dummy + search)
iterations *= 2
qcirc.barrier()
# Inverse QFT
qcirc.append(iqft, count)
qcirc.barrier()
# Measure counting qubits
qcirc.measure(count, range(len(count)))
# print()
# print(qcirc.draw())
#=====================================================================================================================
emulator = Aer.get_backend('qasm_simulator')
job = execute(qcirc, emulator, shots=2048 )
hist = job.result().get_counts()
# print(hist)
measured_int = int(max(hist, key=hist.get),2)
theta = (measured_int/(2**len(count)))*pi*2
# counter = 2**len(search) * (1 - sin(theta/2)**2)
# print("Number of solutions = %d" % round(counter))
counter = 2**(len(dummy)+len(search)) * (1 - sin(theta/2)**2)
print("Number of solutions = %d" % round(counter))
#=====================================================================================================================
# RESULT: 6 count bits are required to detect all 16 possibilities while searching a 4 bit database
# searchbits = 4
# print("\nDetectable solutions with 4 count bits:")
# countbits = 4
# for i in range(0,countbits**2):
# theta = (i/(2**countbits))*pi*2
# counter = 2**searchbits * (1 - sin(theta/2)**2)
# print(round(counter),"|",end='')
# print("\nDetectable solutions with 5 count bits:")
# countbits = 5
# for i in range(0,countbits**2):
# theta = (i/(2**countbits))*pi*2
# counter = 2**searchbits * (1 - sin(theta/2)**2)
# print(round(counter),"|",end='')
# print("\nDetectable solutions with 6 count bits:")
# countbits = 6
# for i in range(0,countbits**2):
# theta = (i/(2**countbits))*pi*2
# counter = 2**searchbits * (1 - sin(theta/2)**2)
# print(round(counter),"|",end='')
#=====================================================================================================================
|
https://github.com/Advanced-Research-Centre/QPULBA
|
Advanced-Research-Centre
|
import numpy as np
import random
from qiskit import QuantumCircuit, Aer, execute
from math import log2, ceil, pi, sin
from numpy import savetxt, save, savez_compressed
import sys
#=====================================================================================================================
simulator = Aer.get_backend('statevector_simulator')
def disp_isv(circ, msg="", all=True, precision=1e-8):
sim_res = execute(circ, simulator).result()
statevector = sim_res.get_statevector(circ)
qb = int(log2(len(statevector)))
print("\n============ State Vector ============", msg)
s = 0
for i in statevector:
if (all == True): print(' ({:+.5f}) |{:0{}b}>'.format(i,s,qb))
else:
if (abs(i) > precision): print(' ({:+.5f}) |{:0{}b}>'.format(i,s,qb))
s = s+1
print("============..............============")
return
#=====================================================================================================================
tape = [0,1,2,3]
ancilla = [4]
count = [5,6,7,8]
# searchbits = 5
# for j in range(4,7):
# print("\nDetectable solutions with %d count bits:",j)
# countbits = j
# for i in range(0,countbits**2):
# theta = (i/(2**countbits))*pi*2
# counter = 2**searchbits * (1 - sin(theta/2)**2)
# print(round(counter),"|",end='')
# sys.exit(0)
qcirc_width = len(tape) + len(ancilla) + len(count)
qcirc = QuantumCircuit(qcirc_width, len(count))
# U_qpulba121
# qcirc.h(fsm)
# qcirc.cx(fsm[1], ancilla[0])
# qcirc.cx(fsm[0],tape[0])
# qcirc.cx(fsm[0],tape[1])
# qcirc.cx(fsm[0],tape[2])
# qcirc.cx(fsm[0],tape[3])
# qcirc.h(tape)
# qcirc.h(tape[0:3])
qcirc.h(tape[0])
# qcirc.cx(tape[1], ancilla[0]) # Gives 32 solns: wrong
# qcirc.h(ancilla[0]) # Gives 2 solns: correct
disp_isv(qcirc, "Step: Run QPULBA 121", all=False, precision=1e-4)
# sys.exit(0)
#=====================================================================================================================
def condition_fsm(qcirc, fsm, tape):
# Finding specific programs-output characteristics (fsm|tape)
# e.g. Self-replication
for q in fsm:
qcirc.cx(q,tape[q])
qcirc.barrier()
return
#=====================================================================================================================
# search = tape
# condition_fsm(qcirc, fsm, tape)
# disp_isv(qcirc, "Step: Find self-replicating programs", all=False, precision=1e-4)
# sys.exit(0)
#=====================================================================================================================
def U_oracle(sz):
# Mark fsm/tape/state with all zero Hamming distance (matches applied condition perfectly)
tgt_reg = list(range(0,sz))
oracle = QuantumCircuit(len(tgt_reg))
oracle.x(tgt_reg)
oracle.h(tgt_reg[0])
oracle.mct(tgt_reg[1:],tgt_reg[0])
oracle.h(tgt_reg[0])
oracle.x(tgt_reg)
return oracle
def U_diffuser(sz):
# https://qiskit.org/textbook/ch-algorithms/quantum-counting.html
tgt_reg = list(range(0,sz))
diffuser = QuantumCircuit(len(tgt_reg))
diffuser.h(tgt_reg[1:])
diffuser.x(tgt_reg[1:])
diffuser.z(tgt_reg[0])
diffuser.mct(tgt_reg[1:],tgt_reg[0])
diffuser.x(tgt_reg[1:])
diffuser.h(tgt_reg[1:])
diffuser.z(tgt_reg[0])
return diffuser
def U_QFT(n):
# n-qubit QFT circuit
qft = QuantumCircuit(n)
def swap_registers(qft, n):
for qubit in range(n//2):
qft.swap(qubit, n-qubit-1)
return qft
def qft_rotations(qft, n):
# Performs qft on the first n qubits in circuit (without swaps)
if n == 0:
return qft
n -= 1
qft.h(n)
for qubit in range(n):
qft.cu1(np.pi/2**(n-qubit), qubit, n)
qft_rotations(qft, n)
qft_rotations(qft, n)
swap_registers(qft, n)
return qft
#=====================================================================================================================
selregs = [0,1,2,3]
# selregs = [4,5,6,7]
# selregs = [0,1,2,3,4,5,6,7,8]
# Create controlled Grover oracle circuit
# oracle = U_oracle(len(search)).to_gate()
oracle = U_oracle(len(selregs)).to_gate()
c_oracle = oracle.control()
c_oracle.label = "cGO"
# Create controlled Grover diffuser circuit
diffuser = U_diffuser(len(selregs)).to_gate()
c_diffuser = diffuser.control()
c_diffuser.label = "cGD"
# Create inverse QFT circuit
iqft = U_QFT(len(count)).to_gate().inverse()
iqft.label = "iQFT"
#=====================================================================================================================
qcirc.h(count)
qcirc.barrier()
# Begin controlled Grover iterations
iterations = 1
for qb in count:
for i in range(iterations):
# qcirc.append(c_oracle, [qb] + search)
qcirc.append(c_oracle, [qb] + selregs)
# disp_isv(qcirc, "Step", all=False, precision=1e-4)
qcirc.append(c_diffuser, [qb] + selregs)
iterations *= 2
qcirc.barrier()
# Inverse QFT
qcirc.append(iqft, count)
qcirc.barrier()
# Measure counting qubits
qcirc.measure(count, range(len(count)))
# print(qcirc.draw())
# sys.exit(0)
#=====================================================================================================================
emulator = Aer.get_backend('qasm_simulator')
job = execute(qcirc, emulator, shots=1024)
hist = job.result().get_counts()
# print(hist)
measured_int = int(max(hist, key=hist.get),2)
theta = (measured_int/(2**len(count)))*pi*2
# counter = 2**3 * (1 - sin(theta/2)**2)
# print("Number of solutions = %.1f" % counter)
counter = 2**len(selregs) * sin(theta/2)**2
print("Number of non-solutions =",counter)
counter = 2**len(selregs) * (1 - sin(theta/2)**2)
print("Number of solutions = %.1f" % counter)
#=====================================================================================================================
|
https://github.com/Advanced-Research-Centre/QPULBA
|
Advanced-Research-Centre
|
import numpy as np
import random
from qiskit import QuantumCircuit, Aer, execute
from math import log2
import sys
#=====================================================================================================================
simulator = Aer.get_backend('statevector_simulator')
emulator = Aer.get_backend('qasm_simulator')
def disp_isv(circ, msg="", all=True, precision=1e-8):
sim_res = execute(circ, simulator).result()
statevector = sim_res.get_statevector(circ)
qb = int(log2(len(statevector)))
print("\n============ State Vector ============", msg)
s = 0
for i in statevector:
if (all == True): print(' ({:+.5f}) |{:0{}b}>'.format(i,s,qb))
else:
if (abs(i) > precision): print(' ({:+.5f}) |{:0{}b}>'.format(i,s,qb))
s = s+1
print("============..............============")
return
#=====================================================================================================================
qcirc = QuantumCircuit(3,1)
qcirc.h(0)
qcirc.h(1)
disp_isv(qcirc, "Step 1", all=False, precision=1e-4)
qcirc.ccx(0,1,2)
disp_isv(qcirc, "Step 2", all=False, precision=1e-4)
qcirc.measure(2, 0)
print(qcirc.draw())
for i in range(0,4):
disp_isv(qcirc, "Step 3 Try "+str(i+1), all=False, precision=1e-4)
# job = execute(qcirc, emulator, shots=1024)
# hist = job.result().get_counts()
#=====================================================================================================================
# (qeait) D:\GoogleDrive\RESEARCH\0 - Programs\QPULBA>python qpostselect.py
#
# ============ State Vector ============ Step 1
# (+0.50000+0.00000j) |000>
# (+0.50000+0.00000j) |001>
# (+0.50000+0.00000j) |010>
# (+0.50000+0.00000j) |011>
# ============..............============
#
# ============ State Vector ============ Step 2
# (+0.50000+0.00000j) |000>
# (+0.50000+0.00000j) |001>
# (+0.50000+0.00000j) |010>
# (+0.50000+0.00000j) |111>
# ============..............============
# ┌───┐
# q_0: ┤ H ├──■─────
# ├───┤ │
# q_1: ┤ H ├──■─────
# └───┘┌─┴─┐┌─┐
# q_2: ─────┤ X ├┤M├
# └───┘└╥┘
# c: 1/═══════════╩═
# 0
#
# ============ State Vector ============ Step 3 Try 1
# (+0.57735+0.00000j) |000>
# (+0.57735+0.00000j) |001>
# (+0.57735+0.00000j) |010>
# ============..............============
#
# ============ State Vector ============ Step 3 Try 2
# (+1.00000+0.00000j) |111>
# ============..............============
#
# ============ State Vector ============ Step 3 Try 3
# (+0.57735+0.00000j) |000>
# (+0.57735+0.00000j) |001>
# (+0.57735+0.00000j) |010>
# ============..............============
#
# ============ State Vector ============ Step 3 Try 4
# (+0.57735+0.00000j) |000>
# (+0.57735+0.00000j) |001>
# (+0.57735+0.00000j) |010>
# ============..............============
#=====================================================================================================================
|
https://github.com/Advanced-Research-Centre/QPULBA
|
Advanced-Research-Centre
|
import numpy as np
import random
from qiskit import QuantumCircuit, Aer, execute
from math import log2, ceil, pi
from numpy import savetxt, save, savez_compressed
#=====================================================================================================================
simulator = Aer.get_backend('statevector_simulator')
def disp_isv(circ, msg="", all=True, precision=1e-8):
sim_res = execute(circ, simulator).result()
statevector = sim_res.get_statevector(circ)
qb = int(log2(len(statevector)))
print("\n============ State Vector ============", msg)
s = 0
for i in statevector:
if (all == True): print(' ({:+.5f}) |{:0{}b}>'.format(i,s,qb))
else:
if (abs(i) > precision): print(' ({:+.5f}) |{:0{}b}>'.format(i,s,qb))
s = s+1
print("============..............============")
return
# 24 qubits with Hadamard on 12 qubits log size: 880 MB csv, 816 MB txt, 256 MB npy, 255 KB npz
def save_isv(statevector, mode=1):
if (mode == 1): savez_compressed('output.npz', statevector)
elif (mode == 2): save('output.npy', statevector)
elif (mode == 3):
qb = int(log2(len(statevector)))
f = open("output.txt", "w")
f.write("============ State Vector ============\n")
s = 0
for i in statevector:
f.write(' ({:+.5f}) |{:0{}b}>'.format(i,s,qb)+'\n')
s = s+1
f.write("============..............============")
f.close()
elif (mode == 4): savetxt('output.csv', statevector, delimiter=',')
else: print('Invalid mode selected')
return
#=====================================================================================================================
def nCX(k,c,t,b):
nc = len(c)
if nc == 1:
k.cx(c[0], t[0])
elif nc == 2:
k.toffoli(c[0], c[1], t[0])
else:
nch = ceil(nc/2)
c1 = c[:nch]
c2 = c[nch:]
c2.append(b[0])
nCX(k,c1,b,[nch+1])
nCX(k,c2,t,[nch-1])
nCX(k,c1,b,[nch+1])
nCX(k,c2,t,[nch-1])
return
#=====================================================================================================================
def U_init(qcirc, circ_width, fsm):
for i in fsm:
qcirc.h(i)
qcirc.barrier()
return
def U_read(qcirc, read, head, tape, ancilla):
# Reset read (prepz measures superposed states... need to uncompute)
for cell in range(0, len(tape)):
enc = format(cell, '#0'+str(len(head)+2)+'b') # 2 for '0b' prefix
for i in range(2, len(enc)):
if(enc[i] == '0'):
qcirc.x(head[(len(head)-1)-(i-2)])
qcirc.barrier(read, head)
nCX(qcirc, head+[tape[cell]], read, [ancilla[0]])
qcirc.barrier(read, head)
for i in range(2, len(enc)):
if(enc[i] == '0'):
qcirc.x(head[(len(head)-1)-(i-2)])
qcirc.barrier(read, head, tape, ancilla)
qcirc.barrier()
return
def U_fsm(qcirc, tick, fsm, state, read, write, move, ancilla):
# Description Number Encoding: {M/W}{R}
# [ M1 W1 M0 W0 ] LSQ = W0 = fsm[0]
qcirc.x(read[0]) # If read == 0
nCX(qcirc, [fsm[0],read[0]], write, [ancilla[0]]) # Update write
nCX(qcirc, [fsm[1],read[0]], move, [ancilla[0]]) # Update move
qcirc.x(read[0]) # If read == 1
nCX(qcirc, [fsm[2],read[0]], write, [ancilla[0]]) # Update write
nCX(qcirc, [fsm[3],read[0]], move, [ancilla[0]]) # Update move
qcirc.barrier()
return
def U_write(qcirc, write, head, tape, ancilla):
# Reset write (prepz measures superposed states... need to uncompute)
for cell in range(0, len(tape)):
enc = format(cell, '#0'+str(len(head)+2)+'b') # 2 for '0b' prefix
for i in range(2, len(enc)):
if(enc[i] == '0'):
qcirc.x(head[(len(head)-1)-(i-2)])
qcirc.barrier(write, head)
nCX(qcirc, head+write, [tape[cell]], [ancilla[0]])
qcirc.barrier(write, head)
for i in range(2, len(enc)):
if(enc[i] == '0'):
qcirc.x(head[(len(head)-1)-(i-2)])
qcirc.barrier(write, head, tape, ancilla)
qcirc.barrier()
return
def U_move(qcirc, move, head, ancilla):
# Increment/Decrement using Adder
reg_a = move
reg_a.extend([-1]*(len(head)-len(move)))
reg_b = head
reg_c = [-1] # No initial carry
reg_c.extend(ancilla)
reg_c.append(-1) # Ignore Head position under/overflow. Trim bits. Last carry not accounted, All-ones overflows to All-zeros
def q_carry(qcirc, q0, q1, q2, q3):
if (q1 != -1 and q2 != -1 and q3 != -1): qcirc.toffoli(q1, q2, q3)
if (q1 != -1 and q2 != -1): qcirc.cx(q1, q2)
if (q0 != -1 and q2 != -1 and q3 != -1): qcirc.toffoli(q0, q2, q3)
def q_mid(qcirc, q0, q1):
if (q0 != -1 and q1 != -1): qcirc.cx(q0, q1)
def q_sum(qcirc, q0, q1, q2):
if (q0 != -1 and q2 != -1): qcirc.cx(q0, q2)
if (q1 != -1 and q2 != -1): qcirc.cx(q1, q2)
def q_rcarry(qcirc, q0, q1, q2, q3):
if (q0 != -1 and q2 != -1 and q3 != -1): qcirc.toffoli(q0, q2, q3)
if (q1 != -1 and q2 != -1): qcirc.cx(q1, q2)
if (q1 != -1 and q2 != -1 and q3 != -1): qcirc.toffoli(q1, q2, q3)
# Quantum Adder
for i in range(0,len(head)):
q_carry(qcirc,reg_c[i],reg_a[i],reg_b[i],reg_c[i+1])
q_mid(qcirc,reg_a[i],reg_b[i])
q_sum(qcirc,reg_c[i],reg_a[i],reg_b[i])
for i in range(len(head)-2,-1,-1):
q_rcarry(qcirc,reg_c[i],reg_a[i],reg_b[i],reg_c[i+1])
q_sum(qcirc,reg_c[i],reg_a[i],reg_b[i])
qcirc.x(reg_a[0])
# Quantum Subtractor
for i in range(0,len(head)-1):
q_sum(qcirc,reg_c[i],reg_a[i],reg_b[i])
q_carry(qcirc,reg_c[i],reg_a[i],reg_b[i],reg_c[i+1])
q_sum(qcirc,reg_c[i+1],reg_a[i+1],reg_b[i+1])
q_mid(qcirc,reg_a[i+1],reg_b[i+1])
for i in range(len(head)-2,-1,-1):
q_rcarry(qcirc,reg_c[i],reg_a[i],reg_b[i],reg_c[i+1])
qcirc.x(reg_a[0])
qcirc.barrier()
return
def U_rst(qcirc, tick, fsm, state, read, write, move, ancilla):
# Reset write and move
qcirc.x(read[0])
nCX(qcirc, [fsm[0],read[0]], write, [ancilla[0]])
nCX(qcirc, [fsm[1],read[0]], move, [ancilla[0]])
qcirc.x(read[0])
nCX(qcirc, [fsm[2],read[0]], write, [ancilla[0]])
nCX(qcirc, [fsm[3],read[0]], move, [ancilla[0]])
qcirc.barrier()
return
#=====================================================================================================================
def Test_cfg(block):
global fsm, state, move, head, read, write, tape, ancilla, test
if (block == 'none'):
return
elif (block == 'read'):
fsm = []
state = []
move = []
head = [0,1,2,3]
read = [4]
write = []
tape = [5,6,7,8,9,10,11,12,13,14,15,16]
ancilla = [17]
test = [18]
elif (block == 'fsm'):
fsm = [0,1,2,3,4,5,6,7,8,9,10,11]
state = [12,13]
move = [14]
head = []
read = [15]
write = [16]
tape = []
ancilla = [17]
test = [18,19,20]
elif (block == 'move'):
fsm = []
state = []
move = [0]
head = [1,2,3,4]
read = []
write = []
tape = []
ancilla = [5,6,7]
test = [8,9,10,11]
elif (block == 'write'):
fsm = []
state = []
move = []
head = [0,1,2,3]
read = []
write = [4]
tape = [5,6,7,8,9,10,11,12,13,14,15,16]
ancilla = [17]
test = []#[18,19,20,21,22,23,24,25,26,27,28,29]
elif (block == 'rst'):
fsm = [0,1,2,3,4,5,6,7,8,9,10,11]
state = [12,13]
move = [14]
head = []
read = [15]
write = [16]
tape = []
ancilla = [17]
test = [18,19,20,21]
print("\n\nTEST CONFIGURATION\n\tFSM\t:",fsm,"\n\tSTATE\t:",state,"\n\tMOVE\t:",move,"\n\tHEAD\t:",head,"\n\tREAD\t:",read,"\n\tWRITE\t:",write,"\n\tTAPE\t:",tape,"\n\tANCILLA :",ancilla,"\n\tTEST\t:",test)
def Test_read(qcirc, read, head, tape, ancilla, test):
# Test using full superposition of head and some random tape qubits
# Test associated to read
for i in range(0,len(head)):
qcirc.h(head[i])
# Create random binary string of length tape
randbin = ""
for i in range(len(tape)): randbin += str(random.randint(0, 1))
for i in range(0,len(tape)):
if (randbin[i] == '1'):
qcirc.h(tape[i]) # Replace H with X for ease
qcirc.cx(read[0],test[0])
print("Test tape:",randbin)
qcirc.barrier()
return
def Test_fsm(qcirc, tick, fsm, state, read, write, move, ancilla, test):
# Test using full superposition of fsm, current state, read
# Test associated to move, write, new state
# fsm superposition part of U_init
qcirc.barrier()
qcirc.h(state[0])
qcirc.h(read[0])
qcirc.barrier()
qcirc.cx(write[0],test[0])
qcirc.cx(move[0],test[1])
qcirc.cx(state[1],test[2])
qcirc.barrier()
return
def Test_write(qcirc, write, head, tape, ancilla, test):
# Test using full superposition of head and write
# Test associated to tape (optional)
for i in range(0,len(head)):
qcirc.h(head[i])
qcirc.h(write)
# for i in range(0,len(tape)):
# qcirc.cx(tape[i],test[i])
return
def Test_move(qcirc, move, head, ancilla, test):
# Test using full superposition of head, both inc/dec
# Test associated to head
for i in range(0,len(head)):
qcirc.h(head[i])
qcirc.cx(head[i],test[i])
qcirc.h(move[0])
qcirc.barrier()
return
def Test_rst(qcirc, tick, fsm, state, read, write, move, ancilla, test):
# Test using full superposition of fsm, current state, read
# Test associated to move, write, new state
# fsm superposition part of U_init
for i in range(0,len(state)):
qcirc.h(state[i])
qcirc.h(read[0])
qcirc.h(write[0])
qcirc.h(move[0])
qcirc.barrier()
for i in range(0,len(state)):
qcirc.cx(state[i],test[i])
qcirc.cx(write[0],test[len(state)])
qcirc.cx(move[0],test[len(state)+1])
qcirc.barrier()
return
#=====================================================================================================================
asz = 2 # Alphabet size: Binary (0 is blank/default)
ssz = 1 # State size (Initial state is all 0)
tdim = 1 # Tape dimension
csz = ceil(log2(asz)) # Character symbol size
senc = ceil(log2(ssz)) # State encoding size
transitions = ssz * asz # Number of transition arrows in FSM
dsz = transitions * (tdim + csz + senc) # Description size
machines = 2 ** dsz
print("\nNumber of "+str(asz)+"-symbol "+str(ssz)+"-state "+str(tdim)+"-dimension Quantum Parallel Universal Linear Bounded Automata: "+str(machines))
tsz = dsz # Turing Tape size (same as dsz to estimating self-replication and algorithmic probability)
hsz = ceil(log2(tsz)) # Head size
sim_tick = tsz # Number of ticks of the FSM before abort
#sim_tick = 1 # Just 1 QPULBA cycle for proof-of-concept
tlog = (sim_tick+1) * senc # Transition log # required?
nanc = 3
qnos = [dsz, tlog, tdim, hsz, csz, csz, tsz, nanc]
fsm = list(range(sum(qnos[0:0]),sum(qnos[0:1])))
state = list(range(sum(qnos[0:1]),sum(qnos[0:2]))) # States (Binary coded)
move = list(range(sum(qnos[0:2]),sum(qnos[0:3])))
head = list(range(sum(qnos[0:3]),sum(qnos[0:4]))) # Binary coded, 0-MSB 2-LSB, [001] refers to Tape pos 1, not 4
read = list(range(sum(qnos[0:4]),sum(qnos[0:5])))
write = list(range(sum(qnos[0:5]),sum(qnos[0:6]))) # Can be MUXed with read?
tape = list(range(sum(qnos[0:6]),sum(qnos[0:7])))
ancilla = list(range(sum(qnos[0:7]),sum(qnos[0:8])))
print("\nFSM\t:",fsm,"\nSTATE\t:",state,"\nMOVE\t:",move,"\nHEAD\t:",head,"\nREAD\t:",read,"\nWRITE\t:",write,"\nTAPE\t:",tape,"\nANCILLA :",ancilla)
#=====================================================================================================================
test = []
unit = 'none' # 'read', 'fsm', 'write', 'move', 'rst'
Test_cfg(unit)
qcirc_width = sum(qnos[0:8]) + len(test)
qcirc = QuantumCircuit(qcirc_width)
# 1. Initialize
U_init(qcirc, qcirc_width, fsm)
# 2. Run machine for n-iterations:
for tick in range(0, sim_tick):
# 2.1 {read} << U_read({head, tape})
if (unit == 'read'): Test_read(qcirc, read, head, tape, ancilla, test)
U_read(qcirc, read, head, tape, ancilla)
# 2.2 {write, state, move} << U_fsm({read, state, fsm})
if (unit == 'fsm'): Test_fsm(qcirc, tick, fsm, state, read, write, move, ancilla, test)
U_fsm(qcirc, tick, fsm, state, read, write, move, ancilla)
# 2.3 {tape} << U_write({head, write})
if (unit == 'write'): Test_write(qcirc, write, head, tape, ancilla, test)
U_write(qcirc, write, head, tape, ancilla)
# 2.4 {head, err} << U_move({head, move})
if (unit == 'move'): Test_move(qcirc, move, head, ancilla, test)
U_move(qcirc, move, head, ancilla)
# 2.5 reset
if (unit == 'rst'): Test_rst(qcirc, tick, fsm, state, read, write, move, ancilla, test)
U_rst(qcirc, tick, fsm, state, read, write, move, ancilla)
print()
print(qcirc.draw())
print()
print(qcirc.qasm())
print()
disp_isv(qcirc, "Step: Test all", all=False, precision=1e-4)
#=====================================================================================================================
|
https://github.com/Advanced-Research-Centre/QPULBA
|
Advanced-Research-Centre
|
import numpy as np
import random
from qiskit import QuantumCircuit, Aer, execute
from math import log2, ceil, pi
from numpy import savetxt, save, savez_compressed
#=====================================================================================================================
simulator = Aer.get_backend('statevector_simulator')
def disp_isv(circ, msg="", all=True, precision=1e-8):
sim_res = execute(circ, simulator).result()
statevector = sim_res.get_statevector(circ)
qb = int(log2(len(statevector)))
print("\n============ State Vector ============", msg)
s = 0
for i in statevector:
if (all == True): print(' ({:+.5f}) |{:0{}b}>'.format(i,s,qb))
else:
if (abs(i) > precision): print(' ({:+.5f}) |{:0{}b}>'.format(i,s,qb))
s = s+1
print("============..............============")
return
# 24 qubits with Hadamard on 12 qubits log size: 880 MB csv, 816 MB txt, 256 MB npy, 255 KB npz
def save_isv(statevector, mode=1):
if (mode == 1): savez_compressed('output.npz', statevector)
elif (mode == 2): save('output.npy', statevector)
elif (mode == 3):
qb = int(log2(len(statevector)))
f = open("output.txt", "w")
f.write("============ State Vector ============\n")
s = 0
for i in statevector:
f.write(' ({:+.5f}) |{:0{}b}>'.format(i,s,qb)+'\n')
s = s+1
f.write("============..............============")
f.close()
elif (mode == 4): savetxt('output.csv', statevector, delimiter=',')
else: print('Invalid mode selected')
return
#=====================================================================================================================
def nCX(k,c,t,b):
nc = len(c)
if nc == 1:
k.cx(c[0], t[0])
elif nc == 2:
k.toffoli(c[0], c[1], t[0])
else:
nch = ceil(nc/2)
c1 = c[:nch]
c2 = c[nch:]
c2.append(b[0])
nCX(k,c1,b,[nch+1])
nCX(k,c2,t,[nch-1])
nCX(k,c1,b,[nch+1])
nCX(k,c2,t,[nch-1])
return
#=====================================================================================================================
def U_init(qcirc, circ_width, fsm):
for i in fsm:
qcirc.h(i)
return
def U_read(qcirc, read, head, tape, ancilla):
# Reset read (prepz measures superposed states... need to uncompute)
for cell in range(0, len(tape)):
enc = format(cell, '#0'+str(len(head)+2)+'b') # 2 for '0b' prefix
for i in range(2, len(enc)):
if(enc[i] == '0'):
qcirc.x(head[(len(head)-1)-(i-2)])
nCX(qcirc, head+[tape[cell]], read, [ancilla[0]])
for i in range(2, len(enc)):
if(enc[i] == '0'):
qcirc.x(head[(len(head)-1)-(i-2)])
qcirc.barrier()
return
def U_fsm(qcirc, tick, fsm, state, read, write, move, ancilla):
# Description Number Encoding: {Q/M/W}{QR}
# [ Q11 M11 W11 Q10 M10 W10 Q01 M01 W01 Q00 M00 W00 ] LSQ = W00 = fsm[0]
qcirc.x(state[tick]) # If s == 0
qcirc.x(read[0]) # If s == 0 && read == 0
nCX(qcirc, [state[tick],fsm[0],read[0]], write, [ancilla[0]]) # Update write
nCX(qcirc, [state[tick],fsm[1],read[0]], move, [ancilla[0]]) # Update move
nCX(qcirc, [state[tick],fsm[2],read[0]], [state[tick+1]], [ancilla[0]]) # Update state
qcirc.x(read[0]) # If s == 0 && read == 1
nCX(qcirc, [state[tick],fsm[3],read[0]], write, [ancilla[0]]) # Update write
nCX(qcirc, [state[tick],fsm[4],read[0]], move, [ancilla[0]]) # Update move
nCX(qcirc, [state[tick],fsm[5],read[0]], [state[tick+1]], [ancilla[0]]) # Update state
qcirc.x(state[tick]) # If s == 1
qcirc.x(read[0]) # If s == 1 && read == 0
nCX(qcirc, [state[tick],fsm[6],read[0]], write, [ancilla[0]]) # Update write
nCX(qcirc, [state[tick],fsm[7],read[0]], move, [ancilla[0]]) # Update move
nCX(qcirc, [state[tick],fsm[8],read[0]], [state[tick+1]], [ancilla[0]]) # Update state
qcirc.x(read[0]) # If s == 1 && read == 1
nCX(qcirc, [state[tick],fsm[9],read[0]], write, [ancilla[0]]) # Update write
nCX(qcirc, [state[tick],fsm[10],read[0]], move, [ancilla[0]]) # Update move
nCX(qcirc, [state[tick],fsm[11],read[0]], [state[tick+1]], [ancilla[0]]) # Update state
return
def U_write(qcirc, write, head, tape, ancilla):
# Reset write (prepz measures superposed states... need to uncompute)
for cell in range(0, len(tape)):
enc = format(cell, '#0'+str(len(head)+2)+'b') # 2 for '0b' prefix
for i in range(2, len(enc)):
if(enc[i] == '0'):
qcirc.x(head[(len(head)-1)-(i-2)])
nCX(qcirc, head+write, [tape[cell]], [ancilla[0]])
for i in range(2, len(enc)):
if(enc[i] == '0'):
qcirc.x(head[(len(head)-1)-(i-2)])
return
def U_move(qcirc, move, head, ancilla):
# Increment/Decrement using Adder
reg_a = move.copy()
reg_a.extend([-1]*(len(head)-len(move)))
reg_b = head.copy()
reg_c = [-1] # No initial carry
reg_c.extend(ancilla)
reg_c.append(-1) # Ignore Head position under/overflow. Trim bits. Last carry not accounted, All-ones overflows to All-zeros
def q_carry(qcirc, q0, q1, q2, q3):
if (q1 != -1 and q2 != -1 and q3 != -1): qcirc.toffoli(q1, q2, q3)
if (q1 != -1 and q2 != -1): qcirc.cx(q1, q2)
if (q0 != -1 and q2 != -1 and q3 != -1): qcirc.toffoli(q0, q2, q3)
def q_mid(qcirc, q0, q1):
if (q0 != -1 and q1 != -1): qcirc.cx(q0, q1)
def q_sum(qcirc, q0, q1, q2):
if (q0 != -1 and q2 != -1): qcirc.cx(q0, q2)
if (q1 != -1 and q2 != -1): qcirc.cx(q1, q2)
def q_rcarry(qcirc, q0, q1, q2, q3):
if (q0 != -1 and q2 != -1 and q3 != -1): qcirc.toffoli(q0, q2, q3)
if (q1 != -1 and q2 != -1): qcirc.cx(q1, q2)
if (q1 != -1 and q2 != -1 and q3 != -1): qcirc.toffoli(q1, q2, q3)
# Quantum Adder
for i in range(0,len(head)):
q_carry(qcirc,reg_c[i],reg_a[i],reg_b[i],reg_c[i+1])
q_mid(qcirc,reg_a[i],reg_b[i])
q_sum(qcirc,reg_c[i],reg_a[i],reg_b[i])
for i in range(len(head)-2,-1,-1):
q_rcarry(qcirc,reg_c[i],reg_a[i],reg_b[i],reg_c[i+1])
q_sum(qcirc,reg_c[i],reg_a[i],reg_b[i])
qcirc.barrier(move, head, ancilla)
qcirc.x(reg_a[0])
# Quantum Subtractor
for i in range(0,len(head)-1):
q_sum(qcirc,reg_c[i],reg_a[i],reg_b[i])
q_carry(qcirc,reg_c[i],reg_a[i],reg_b[i],reg_c[i+1])
q_sum(qcirc,reg_c[i+1],reg_a[i+1],reg_b[i+1])
q_mid(qcirc,reg_a[i+1],reg_b[i+1])
for i in range(len(head)-2,-1,-1):
q_rcarry(qcirc,reg_c[i],reg_a[i],reg_b[i],reg_c[i+1])
qcirc.x(reg_a[0])
qcirc.barrier()
return
def U_rst(qcirc, tick, fsm, state, read, write, move, ancilla):
# Reset write and move
qcirc.x(state[tick])
qcirc.x(read[0])
nCX(qcirc, [state[tick],fsm[0],read[0]], write, [ancilla[0]])
nCX(qcirc, [state[tick],fsm[1],read[0]], move, [ancilla[0]])
qcirc.x(read[0])
nCX(qcirc, [state[tick],fsm[3],read[0]], write, [ancilla[0]])
nCX(qcirc, [state[tick],fsm[4],read[0]], move, [ancilla[0]])
qcirc.x(state[tick])
qcirc.x(read[0])
nCX(qcirc, [state[tick],fsm[6],read[0]], write, [ancilla[0]])
nCX(qcirc, [state[tick],fsm[7],read[0]], move, [ancilla[0]])
qcirc.x(read[0])
nCX(qcirc, [state[tick],fsm[9],read[0]], write, [ancilla[0]])
nCX(qcirc, [state[tick],fsm[10],read[0]], move, [ancilla[0]])
# Maintain computation history
qcirc.swap(state[0],state[tick+1])
return
#=====================================================================================================================
def Test_cfg(block):
global fsm, state, move, head, read, write, tape, ancilla, test
if (block == 'none'):
return
elif (block == 'read'):
fsm = []
state = []
move = []
head = [0,1,2,3]
read = [4]
write = []
tape = [5,6,7,8,9,10,11,12,13,14,15,16]
ancilla = [17]
test = [18]
elif (block == 'fsm'):
fsm = [0,1,2,3,4,5,6,7,8,9,10,11]
state = [12,13]
move = [14]
head = []
read = [15]
write = [16]
tape = []
ancilla = [17]
test = [18,19,20]
elif (block == 'move'):
fsm = []
state = []
move = [0]
head = [1,2,3,4]
read = []
write = []
tape = []
ancilla = [5,6,7]
test = [8,9,10,11]
elif (block == 'write'):
fsm = []
state = []
move = []
head = [0,1,2,3]
read = []
write = [4]
tape = [5,6,7,8,9,10,11,12,13,14,15,16]
ancilla = [17]
test = []#[18,19,20,21,22,23,24,25,26,27,28,29]
elif (block == 'rst'):
fsm = [0,1,2,3,4,5,6,7,8,9,10,11]
state = [12,13]
move = [14]
head = []
read = [15]
write = [16]
tape = []
ancilla = [17]
test = [18,19,20,21]
print("\n\nTEST CONFIGURATION\n\tFSM\t:",fsm,"\n\tSTATE\t:",state,"\n\tMOVE\t:",move,"\n\tHEAD\t:",head,"\n\tREAD\t:",read,"\n\tWRITE\t:",write,"\n\tTAPE\t:",tape,"\n\tANCILLA :",ancilla,"\n\tTEST\t:",test)
def Test_read(qcirc, read, head, tape, ancilla, test):
# Test using full superposition of head and some random tape qubits
# Test associated to read
for i in range(0,len(head)):
qcirc.h(head[i])
# Create random binary string of length tape
randbin = ""
for i in range(len(tape)): randbin += str(random.randint(0, 1))
for i in range(0,len(tape)):
if (randbin[i] == '1'):
qcirc.h(tape[i]) # Replace H with X for ease
qcirc.cx(read[0],test[0])
print("Test tape:",randbin)
qcirc.barrier()
return
def Test_fsm(qcirc, tick, fsm, state, read, write, move, ancilla, test):
# Test using full superposition of fsm, current state, read
# Test associated to move, write, new state
# fsm superposition part of U_init
qcirc.barrier()
qcirc.h(state[0])
qcirc.h(read[0])
qcirc.barrier()
qcirc.cx(write[0],test[0])
qcirc.cx(move[0],test[1])
qcirc.cx(state[1],test[2])
qcirc.barrier()
return
def Test_write(qcirc, write, head, tape, ancilla, test):
# Test using full superposition of head and write
# Test associated to tape (optional)
for i in range(0,len(head)):
qcirc.h(head[i])
qcirc.h(write)
# for i in range(0,len(tape)):
# qcirc.cx(tape[i],test[i])
return
def Test_move(qcirc, move, head, ancilla, test):
# Test using full superposition of head, both inc/dec
# Test associated to head
for i in range(0,len(head)):
qcirc.ry(round(np.pi * random.random(),2),head[i])
qcirc.cx(head[i],test[i])
qcirc.ry(round(np.pi * random.random(),2),move[0])
qcirc.barrier()
return
def Test_rst(qcirc, tick, fsm, state, read, write, move, ancilla, test):
# Test using full superposition of fsm, current state, read
# Test associated to move, write, new state
# fsm superposition part of U_init
for i in range(0,len(state)):
qcirc.h(state[i])
qcirc.h(read[0])
qcirc.h(write[0])
qcirc.h(move[0])
qcirc.barrier()
for i in range(0,len(state)):
qcirc.cx(state[i],test[i])
qcirc.cx(write[0],test[len(state)])
qcirc.cx(move[0],test[len(state)+1])
qcirc.barrier()
return
#=====================================================================================================================
ssz = 2 # State size (Initial state is all 0)
asz = 2 # Alphabet size: Binary (0 is blank/default)
tdim = 1 # Tape dimension
csz = ceil(log2(asz)) # Character symbol size
senc = ceil(log2(ssz)) # State encoding size
transitions = ssz * asz # Number of transition arrows in FSM
dsz = transitions * (tdim + csz + senc) # Description size
machines = 2 ** dsz
print("\nNumber of "+str(ssz)+"-state "+str(asz)+"-symbol "+str(tdim)+"-dimension Quantum Parallel Universal Linear Bounded Automata: "+str(machines))
tsz = dsz # Turing Tape size (same as dsz to estimating self-replication and algorithmic probability)
hsz = ceil(log2(tsz)) # Head size
sim_tick = tsz # Number of ticks of the FSM before abort
sim_tick = 1 # Just 1 QPULBA cycle for proof-of-concept
tlog = (sim_tick+1) * senc # Transition log # required?
nanc = 3
qnos = [dsz, tlog, tdim, hsz, csz, csz, tsz, nanc]
fsm = list(range(sum(qnos[0:0]),sum(qnos[0:1])))
state = list(range(sum(qnos[0:1]),sum(qnos[0:2]))) # States (Binary coded)
move = list(range(sum(qnos[0:2]),sum(qnos[0:3])))
head = list(range(sum(qnos[0:3]),sum(qnos[0:4]))) # Binary coded, 0-MSB 2-LSB, [001] refers to Tape pos 1, not 4
read = list(range(sum(qnos[0:4]),sum(qnos[0:5])))
write = list(range(sum(qnos[0:5]),sum(qnos[0:6]))) # Can be MUXed with read?
tape = list(range(sum(qnos[0:6]),sum(qnos[0:7])))
ancilla = list(range(sum(qnos[0:7]),sum(qnos[0:8])))
print("\nFSM\t:",fsm,"\nSTATE\t:",state,"\nMOVE\t:",move,"\nHEAD\t:",head,"\nREAD\t:",read,"\nWRITE\t:",write,"\nTAPE\t:",tape,"\nANCILLA :",ancilla)
#=====================================================================================================================
test = []
unit = 'all' # 'all', read', 'fsm', 'write', 'move', 'rst'
Test_cfg(unit)
qcirc_width = len(fsm) + len(state) + len(move) + len(head) + len(read) + len(write) + len(tape) + len(ancilla) + len(test)
qcirc = QuantumCircuit(qcirc_width)
qcirc.barrier()
# 1. Initialize
U_init(qcirc, qcirc_width, fsm)
# 2. Run machine for n-iterations:
for tick in range(0, sim_tick):
# 2.1 {read} << U_read({head, tape})
if (unit == 'read'): Test_read(qcirc, read, head, tape, ancilla, test)
if (unit == 'read' or unit == 'all'): U_read(qcirc, read, head, tape, ancilla)
# 2.2 {write, state, move} << U_fsm({read, state, fsm})
if (unit == 'fsm'): Test_fsm(qcirc, tick, fsm, state, read, write, move, ancilla, test)
if (unit == 'fsm' or unit == 'all'): U_fsm(qcirc, tick, fsm, state, read, write, move, ancilla)
# 2.3 {tape} << U_write({head, write})
if (unit == 'write'): Test_write(qcirc, write, head, tape, ancilla, test)
if (unit == 'write' or unit == 'all'): U_write(qcirc, write, head, tape, ancilla)
# 2.4 {head, err} << U_move({head, move})
if (unit == 'move'): Test_move(qcirc, move, head, ancilla, test)
if (unit == 'move' or unit == 'all'): U_move(qcirc, move, head, ancilla)
# 2.5 reset
if (unit == 'rst'): Test_rst(qcirc, tick, fsm, state, read, write, move, ancilla, test)
if (unit == 'rst' or unit == 'all'): U_rst(qcirc, tick, fsm, state, read, write, move, ancilla)
print()
print(qcirc.draw())
#print(qcirc.qasm())
#disp_isv(qcirc, "Step: Test "+unit, all=False, precision=1e-4) # Full simulation doesn't work
#=====================================================================================================================
|
https://github.com/Advanced-Research-Centre/QPULBA
|
Advanced-Research-Centre
|
import numpy as np
import random
from qiskit import QuantumCircuit, Aer, execute
from math import log2, ceil, pi, sin
from numpy import savetxt, save, savez_compressed
import sys
#=====================================================================================================================
simulator = Aer.get_backend('statevector_simulator')
def disp_isv(circ, msg="", all=True, precision=1e-8):
sim_res = execute(circ, simulator).result()
statevector = sim_res.get_statevector(circ)
qb = int(log2(len(statevector)))
print("\n============ State Vector ============", msg)
s = 0
for i in statevector:
if (all == True): print(' ({:+.5f}) |{:0{}b}>'.format(i,s,qb))
else:
if (abs(i) > precision): print(' ({:+.5f}) |{:0{}b}>'.format(i,s,qb))
s = s+1
print("============..............============")
return
# 24 qubits with Hadamard on 12 qubits log size: 880 MB csv, 816 MB txt, 256 MB npy, 255 KB npz
def save_isv(statevector, mode=1):
if (mode == 1): savez_compressed('output.npz', statevector)
elif (mode == 2): save('output.npy', statevector)
elif (mode == 3):
qb = int(log2(len(statevector)))
f = open("output.txt", "w")
f.write("============ State Vector ============\n")
s = 0
for i in statevector:
f.write(' ({:+.5f}) |{:0{}b}>'.format(i,s,qb)+'\n')
s = s+1
f.write("============..............============")
f.close()
elif (mode == 4): savetxt('output.csv', statevector, delimiter=',')
else: print('Invalid mode selected')
return
#=====================================================================================================================
def nCX(k,c,t,b):
nc = len(c)
if nc == 1:
k.cx(c[0], t[0])
elif nc == 2:
k.toffoli(c[0], c[1], t[0])
else:
nch = ceil(nc/2)
c1 = c[:nch]
c2 = c[nch:]
c2.append(b[0])
nCX(k,c1,b,[nch+1])
nCX(k,c2,t,[nch-1])
nCX(k,c1,b,[nch+1])
nCX(k,c2,t,[nch-1])
return
#=====================================================================================================================
def U_init(qcirc, circ_width, fsm):
for i in fsm:
qcirc.h(i)
qcirc.barrier()
return
def U_read(qcirc, read, head, tape, ancilla):
# Reset read (prepz measures superposed states... need to uncompute)
for cell in range(0, len(tape)):
enc = format(cell, '#0'+str(len(head)+2)+'b') # 2 for '0b' prefix
for i in range(2, len(enc)):
if(enc[i] == '0'):
qcirc.x(head[(len(head)-1)-(i-2)])
qcirc.barrier(read, head)
nCX(qcirc, head+[tape[cell]], read, [ancilla[0]])
qcirc.barrier(read, head)
for i in range(2, len(enc)):
if(enc[i] == '0'):
qcirc.x(head[(len(head)-1)-(i-2)])
qcirc.barrier(read, head, tape, ancilla)
qcirc.barrier()
return
def U_fsm(qcirc, tick, fsm, state, read, write, move, ancilla):
# Description Number Encoding: {M/W}{R}
# [ M1 W1 M0 W0 ] LSQ = W0 = fsm[0]
qcirc.x(read[0]) # If read == 0
nCX(qcirc, [fsm[0],read[0]], write, [ancilla[0]]) # Update write
nCX(qcirc, [fsm[1],read[0]], move, [ancilla[0]]) # Update move
qcirc.x(read[0]) # If read == 1
nCX(qcirc, [fsm[2],read[0]], write, [ancilla[0]]) # Update write
nCX(qcirc, [fsm[3],read[0]], move, [ancilla[0]]) # Update move
qcirc.barrier()
return
def U_write(qcirc, write, head, tape, ancilla):
# Reset write (prepz measures superposed states... need to uncompute)
for cell in range(0, len(tape)):
enc = format(cell, '#0'+str(len(head)+2)+'b') # 2 for '0b' prefix
for i in range(2, len(enc)):
if(enc[i] == '0'):
qcirc.x(head[(len(head)-1)-(i-2)])
qcirc.barrier(write, head)
nCX(qcirc, head+write, [tape[cell]], [ancilla[0]])
qcirc.barrier(write, head)
for i in range(2, len(enc)):
if(enc[i] == '0'):
qcirc.x(head[(len(head)-1)-(i-2)])
qcirc.barrier(write, head, tape, ancilla)
qcirc.barrier()
return
def U_move(qcirc, move, head, ancilla):
# Increment/Decrement using Adder
reg_a = move
reg_a.extend([-1]*(len(head)-len(move)))
reg_b = head
reg_c = [-1] # No initial carry
reg_c.extend(ancilla)
reg_c.append(-1) # Ignore Head position under/overflow. Trim bits. Last carry not accounted, All-ones overflows to All-zeros
def q_carry(qcirc, q0, q1, q2, q3):
if (q1 != -1 and q2 != -1 and q3 != -1): qcirc.toffoli(q1, q2, q3)
if (q1 != -1 and q2 != -1): qcirc.cx(q1, q2)
if (q0 != -1 and q2 != -1 and q3 != -1): qcirc.toffoli(q0, q2, q3)
def q_mid(qcirc, q0, q1):
if (q0 != -1 and q1 != -1): qcirc.cx(q0, q1)
def q_sum(qcirc, q0, q1, q2):
if (q0 != -1 and q2 != -1): qcirc.cx(q0, q2)
if (q1 != -1 and q2 != -1): qcirc.cx(q1, q2)
def q_rcarry(qcirc, q0, q1, q2, q3):
if (q0 != -1 and q2 != -1 and q3 != -1): qcirc.toffoli(q0, q2, q3)
if (q1 != -1 and q2 != -1): qcirc.cx(q1, q2)
if (q1 != -1 and q2 != -1 and q3 != -1): qcirc.toffoli(q1, q2, q3)
# Quantum Adder
for i in range(0,len(head)):
q_carry(qcirc,reg_c[i],reg_a[i],reg_b[i],reg_c[i+1])
q_mid(qcirc,reg_a[i],reg_b[i])
q_sum(qcirc,reg_c[i],reg_a[i],reg_b[i])
for i in range(len(head)-2,-1,-1):
q_rcarry(qcirc,reg_c[i],reg_a[i],reg_b[i],reg_c[i+1])
q_sum(qcirc,reg_c[i],reg_a[i],reg_b[i])
qcirc.x(reg_a[0])
# Quantum Subtractor
for i in range(0,len(head)-1):
q_sum(qcirc,reg_c[i],reg_a[i],reg_b[i])
q_carry(qcirc,reg_c[i],reg_a[i],reg_b[i],reg_c[i+1])
q_sum(qcirc,reg_c[i+1],reg_a[i+1],reg_b[i+1])
q_mid(qcirc,reg_a[i+1],reg_b[i+1])
for i in range(len(head)-2,-1,-1):
q_rcarry(qcirc,reg_c[i],reg_a[i],reg_b[i],reg_c[i+1])
qcirc.x(reg_a[0])
qcirc.barrier()
return
def U_rst(qcirc, tick, fsm, state, read, write, move, ancilla):
# Reset write and move
qcirc.x(read[0])
nCX(qcirc, [fsm[0],read[0]], write, [ancilla[0]])
nCX(qcirc, [fsm[1],read[0]], move, [ancilla[0]])
qcirc.x(read[0])
nCX(qcirc, [fsm[2],read[0]], write, [ancilla[0]])
nCX(qcirc, [fsm[3],read[0]], move, [ancilla[0]])
qcirc.barrier()
return
#=====================================================================================================================
def Test_cfg_121(block): # convert config from 221 to 121
global fsm, state, move, head, read, write, tape, ancilla, test
if (block == 'none'):
return
elif (block == 'read'):
fsm = []
state = []
move = []
head = [0,1,2,3]
read = [4]
write = []
tape = [5,6,7,8,9,10,11,12,13,14,15,16]
ancilla = [17]
test = [18]
elif (block == 'fsm'):
fsm = [0,1,2,3,4,5,6,7,8,9,10,11]
state = [12,13]
move = [14]
head = []
read = [15]
write = [16]
tape = []
ancilla = [17]
test = [18,19,20]
elif (block == 'move'):
fsm = []
state = []
move = [0]
head = [1,2,3,4]
read = []
write = []
tape = []
ancilla = [5,6,7]
test = [8,9,10,11]
elif (block == 'write'):
fsm = []
state = []
move = []
head = [0,1,2,3]
read = []
write = [4]
tape = [5,6,7,8,9,10,11,12,13,14,15,16]
ancilla = [17]
test = []#[18,19,20,21,22,23,24,25,26,27,28,29]
elif (block == 'rst'):
fsm = [0,1,2,3,4,5,6,7,8,9,10,11]
state = [12,13]
move = [14]
head = []
read = [15]
write = [16]
tape = []
ancilla = [17]
test = [18,19,20,21]
elif (block == 'count'):
fsm = [0,1,2,3]
state = []
move = []
head = []
read = []
write = []
tape = []
ancilla = []
test = []
count = [4,5,6,7]
search = [8,9,10,11]
print("\n\nTEST CONFIGURATION\n\tFSM\t:",fsm,"\n\tSTATE\t:",state,"\n\tMOVE\t:",move,"\n\tHEAD\t:",head,"\n\tREAD\t:",read,"\n\tWRITE\t:",write,"\n\tTAPE\t:",tape,"\n\tANCILLA :",ancilla,"\n\tTEST\t:",test,"\n\tCOUNT\t:",count,"\n\tSEARCH\t:",search)
def Test_count(qcirc, fsm):
# Test using some superposition of fsm and then Hamming distance
qcirc.barrier()
qcirc.barrier()
return
#=====================================================================================================================
asz = 2 # Alphabet size: Binary (0 is blank/default)
ssz = 1 # State size (Initial state is all 0)
tdim = 1 # Tape dimension
csz = ceil(log2(asz)) # Character symbol size
senc = ceil(log2(ssz)) # State encoding size
transitions = ssz * asz # Number of transition arrows in FSM
dsz = transitions * (tdim + csz + senc) # Description size
machines = 2 ** dsz
print("\nNumber of "+str(asz)+"-symbol "+str(ssz)+"-state "+str(tdim)+"-dimension Quantum Parallel Universal Linear Bounded Automata: "+str(machines))
tsz = dsz # Turing Tape size (same as dsz to estimating self-replication and algorithmic probability)
hsz = ceil(log2(tsz)) # Head size
sim_tick = tsz # Number of ticks of the FSM before abort
#sim_tick = 1 # Just 1 QPULBA cycle for proof-of-concept
tlog = (sim_tick+1) * senc # Transition log # required?
nanc = 3
quinebit = 1
qnos = [dsz, tlog, tdim, hsz, csz, csz, tsz, nanc, quinebit]
fsm = list(range(sum(qnos[0:0]),sum(qnos[0:1])))
state = list(range(sum(qnos[0:1]),sum(qnos[0:2]))) # States (Binary coded)
move = list(range(sum(qnos[0:2]),sum(qnos[0:3])))
head = list(range(sum(qnos[0:3]),sum(qnos[0:4]))) # Binary coded, 0-MSB 2-LSB, [001] refers to Tape pos 1, not 4
read = list(range(sum(qnos[0:4]),sum(qnos[0:5])))
write = list(range(sum(qnos[0:5]),sum(qnos[0:6]))) # Can be MUXed with read?
tape = list(range(sum(qnos[0:6]),sum(qnos[0:7])))
ancilla = list(range(sum(qnos[0:7]),sum(qnos[0:8])))
quine = list(range(sum(qnos[0:8]),sum(qnos[0:9])))
print("\nFSM\t:",fsm,"\nSTATE\t:",state,"\nMOVE\t:",move,"\nHEAD\t:",head,"\nREAD\t:",read,"\nWRITE\t:",write,"\nTAPE\t:",tape,"\nANCILLA :",ancilla,"\nQUINE\t:",quine)
#=====================================================================================================================
test = []
unit = 'none' # 'none', 'read', 'fsm', 'write', 'move', 'rst'
qcirc_width = sum(qnos[0:9]) + len(test)
qcirc = QuantumCircuit(qcirc_width, len(quine))
# U_init(qcirc, qcirc_width, fsm)
# for tick in range(0, sim_tick):
# U_read(qcirc, read, head, tape, ancilla)
# U_fsm(qcirc, tick, fsm, state, read, write, move, ancilla)
# U_write(qcirc, write, head, tape, ancilla)
# U_move(qcirc, move, head, ancilla)
# U_rst(qcirc, tick, fsm, state, read, write, move, ancilla)
# ============ State Vector ============ Step: Run QPULBA 121
# (+0.25000+0.00000j) |0000000000000000>
# (+0.25000+0.00000j) |0000000000000100>
# (+0.25000+0.00000j) |0000000000001000>
# (+0.25000+0.00000j) |0000000000001100>
# (+0.25000+0.00000j) |0001111000000001>
# (+0.25000+0.00000j) |0001111000000101>
# (+0.25000+0.00000j) |0001111000001001>
# (+0.25000+0.00000j) |0001111000001101>
# (+0.25000+0.00000j) |0100000000000010>
# (+0.25000+0.00000j) |0100000000000110>
# (+0.25000+0.00000j) |0100000000001010>
# (+0.25000+0.00000j) |0100000000001110>
# (+0.25000+0.00000j) |0101111000000011>
# (+0.25000+0.00000j) |0101111000000111>
# (+0.25000+0.00000j) |0101111000001011>
# (+0.25000+0.00000j) |0101111000001111>
# ============..............============
def U_qpulba121(qcirc, fsm, tape, ancilla):
qcirc.h(fsm)
qcirc.cx(fsm[1], ancilla[1])
qcirc.cx(fsm[0],tape[0])
qcirc.cx(fsm[0],tape[1])
qcirc.cx(fsm[0],tape[2])
qcirc.cx(fsm[0],tape[3])
return
U_qpulba121(qcirc, fsm, tape, ancilla)
disp_isv(qcirc, "Step: Run QPULBA 121", all=False, precision=1e-4)
#=====================================================================================================================
def condition_fsm(qcirc, fsm, tape):
# Finding specific programs-output characteristics (fsm|tape)
# e.g. Self-replication
for q in fsm:
qcirc.cx(q,tape[q])
qcirc.barrier()
return
def condition_tape(qcirc, tape, target_tape):
# Finding algorithmic probability of a specific output (tape|tape*)
return
def condition_state(qcirc, state, target_state):
# Finding programs with specific end state (state|state*)
# Note: not possible in QPULBA 121
return
#=====================================================================================================================
condition_fsm(qcirc, fsm, tape)
disp_isv(qcirc, "Step: Find self-replicating programs", all=False, precision=1e-4)
#=====================================================================================================================
def U_oracle(qcirc, tape, quine):
# Mark tape with all zero Hamming distance
qcirc.x(tape)
qcirc.mct(tape,quine)
qcirc.x(tape)
return
U_oracle(qcirc, tape, quine)
disp_isv(qcirc, "Step: Quine bit", all=False, precision=1e-4)
#=====================================================================================================================
qcirc.measure(quine, 0)
disp_isv(qcirc, "Step: Post select quines", all=False, precision=1e-4)
sys.exit(0)
#=====================================================================================================================
# Number of 2-symbol 1-state 1-dimension Quantum Parallel Universal Linear Bounded Automata: 16
#
# FSM : [0, 1, 2, 3]
# STATE : []
# MOVE : [4]
# HEAD : [5, 6]
# READ : [7]
# WRITE : [8]
# TAPE : [9, 10, 11, 12]
# ANCILLA : [13, 14, 15]
# QUINE : [16]
#
# ============ State Vector ============ Step: Run QPULBA 121
# (+0.25000+0.00000j) |00000000000000000>
# (+0.25000+0.00000j) |00000000000000100>
# (+0.25000+0.00000j) |00000000000001000>
# (+0.25000+0.00000j) |00000000000001100>
# (+0.25000+0.00000j) |00001111000000001>
# (+0.25000+0.00000j) |00001111000000101>
# (+0.25000+0.00000j) |00001111000001001>
# (+0.25000+0.00000j) |00001111000001101>
# (+0.25000+0.00000j) |00100000000000010>
# (+0.25000+0.00000j) |00100000000000110>
# (+0.25000+0.00000j) |00100000000001010>
# (+0.25000+0.00000j) |00100000000001110>
# (+0.25000+0.00000j) |00101111000000011>
# (+0.25000+0.00000j) |00101111000000111>
# (+0.25000+0.00000j) |00101111000001011>
# (+0.25000+0.00000j) |00101111000001111>
# ============..............============
#
# ============ State Vector ============ Step: Find self-replicating programs
# (+0.25000+0.00000j) |00000000000000000>
# (+0.25000+0.00000j) |00000010000001101>
# (+0.25000+0.00000j) |00000100000000100>
# (+0.25000+0.00000j) |00000110000001001>
# (+0.25000+0.00000j) |00001000000001000>
# (+0.25000+0.00000j) |00001010000000101>
# (+0.25000+0.00000j) |00001100000001100>
# (+0.25000+0.00000j) |00001110000000001>
# (+0.25000+0.00000j) |00100000000001111>
# (+0.25000+0.00000j) |00100010000000010>
# (+0.25000+0.00000j) |00100100000001011>
# (+0.25000+0.00000j) |00100110000000110>
# (+0.25000+0.00000j) |00101000000000111>
# (+0.25000+0.00000j) |00101010000001010>
# (+0.25000+0.00000j) |00101100000000011>
# (+0.25000+0.00000j) |00101110000001110>
# ============..............============
#
# ============ State Vector ============ Step: Quine bit
# (+0.25000-0.00000j) |00000010000001101>
# (+0.25000-0.00000j) |00000100000000100>
# (+0.25000-0.00000j) |00000110000001001>
# (+0.25000-0.00000j) |00001000000001000>
# (+0.25000-0.00000j) |00001010000000101>
# (+0.25000-0.00000j) |00001100000001100>
# (+0.25000-0.00000j) |00001110000000001>
# (+0.25000-0.00000j) |00100010000000010>
# (+0.25000-0.00000j) |00100100000001011>
# (+0.25000-0.00000j) |00100110000000110>
# (+0.25000-0.00000j) |00101000000000111>
# (+0.25000-0.00000j) |00101010000001010>
# (+0.25000-0.00000j) |00101100000000011>
# (+0.25000-0.00000j) |00101110000001110>
# (+0.25000-0.00000j) |10000000000000000>
# (+0.25000-0.00000j) |10100000000001111>
# ============..............============
#
# ============ State Vector ============ Step: Post select quines
# (+0.70711-0.00000j) |10000000000000000>
# (+0.70711-0.00000j) |10100000000001111>
# ============..............============
#=====================================================================================================================
#=====================================================================================================================
# Code below archived for now
#=====================================================================================================================
#=====================================================================================================================
def U_oracle(sz):
# Mark fsm/tape/state with all zero Hamming distance (matches applied condition perfectly)
tgt_reg = list(range(0,sz))
oracle = QuantumCircuit(len(tgt_reg))
oracle.x(tgt_reg)
oracle.h(tgt_reg[0])
oracle.mct(tgt_reg[1:],tgt_reg[0])
oracle.h(tgt_reg[0])
oracle.x(tgt_reg)
return oracle
def U_pattern(sz):
# Mark {0000,0010,0100,0110,1000,1010,1100,1110}
tgt_reg = list(range(0,sz))
oracle = QuantumCircuit(len(tgt_reg))
oracle.x(tgt_reg)
oracle.h(tgt_reg[0])
oracle.mct(tgt_reg[1:],tgt_reg[0])
oracle.h(tgt_reg[0])
oracle.x(tgt_reg)
oracle.x([tgt_reg[0],tgt_reg[2],tgt_reg[3]])
oracle.h(tgt_reg[0])
oracle.mct(tgt_reg[1:],tgt_reg[0])
oracle.h(tgt_reg[0])
oracle.x([tgt_reg[0],tgt_reg[2],tgt_reg[3]])
oracle.x([tgt_reg[0],tgt_reg[1],tgt_reg[3]])
oracle.h(tgt_reg[0])
oracle.mct(tgt_reg[1:],tgt_reg[0])
oracle.h(tgt_reg[0])
oracle.x([tgt_reg[0],tgt_reg[1],tgt_reg[3]])
oracle.x([tgt_reg[0],tgt_reg[3]])
oracle.h(tgt_reg[0])
oracle.mct(tgt_reg[1:],tgt_reg[0])
oracle.h(tgt_reg[0])
oracle.x([tgt_reg[0],tgt_reg[3]])
oracle.x([tgt_reg[0],tgt_reg[1],tgt_reg[2]])
oracle.h(tgt_reg[0])
oracle.mct(tgt_reg[1:],tgt_reg[0])
oracle.h(tgt_reg[0])
oracle.x([tgt_reg[0],tgt_reg[1],tgt_reg[2]])
oracle.x([tgt_reg[0],tgt_reg[2]])
oracle.h(tgt_reg[0])
oracle.mct(tgt_reg[1:],tgt_reg[0])
oracle.h(tgt_reg[0])
oracle.x([tgt_reg[0],tgt_reg[2]])
oracle.x([tgt_reg[0],tgt_reg[1]])
oracle.h(tgt_reg[0])
oracle.mct(tgt_reg[1:],tgt_reg[0])
oracle.h(tgt_reg[0])
oracle.x([tgt_reg[0],tgt_reg[1]])
oracle.x([tgt_reg[0]])
oracle.h(tgt_reg[0])
oracle.mct(tgt_reg[1:],tgt_reg[0])
oracle.h(tgt_reg[0])
oracle.x([tgt_reg[0]])
return oracle
def U_aa(sz):
tgt_reg = list(range(0,sz))
diffuser = QuantumCircuit(len(tgt_reg))
diffuser.h(tgt_reg)
diffuser.x(tgt_reg)
diffuser.h(tgt_reg[0])
diffuser.mct(tgt_reg[1:],tgt_reg[0])
diffuser.h(tgt_reg[0])
diffuser.x(tgt_reg)
diffuser.h(tgt_reg)
return diffuser
def U_diffuser(sz):
# https://qiskit.org/textbook/ch-algorithms/quantum-counting.html
tgt_reg = list(range(0,sz))
diffuser = QuantumCircuit(len(tgt_reg))
diffuser.h(tgt_reg[1:])
diffuser.x(tgt_reg[1:])
diffuser.z(tgt_reg[0])
diffuser.mct(tgt_reg[1:],tgt_reg[0])
diffuser.x(tgt_reg[1:])
diffuser.h(tgt_reg[1:])
diffuser.z(tgt_reg[0])
return diffuser
def U_QFT(n):
# n-qubit QFT circuit
qft = QuantumCircuit(n)
def swap_registers(qft, n):
for qubit in range(n//2):
qft.swap(qubit, n-qubit-1)
return qft
def qft_rotations(qft, n):
# Performs qft on the first n qubits in circuit (without swaps)
if n == 0:
return qft
n -= 1
qft.h(n)
for qubit in range(n):
qft.cu1(np.pi/2**(n-qubit), qubit, n)
qft_rotations(qft, n)
qft_rotations(qft, n)
swap_registers(qft, n)
return qft
#=====================================================================================================================
oracle = U_oracle(len(tape)).to_gate()
oracle.label = "GO"
pattern = U_pattern(len(tape)).to_gate()
pattern.label = "PO"
allregs = list(range(sum(qnos[0:0]),sum(qnos[0:8])))
aa = U_aa(len(tape)).to_gate()
aa.label = "AA"
from copy import deepcopy
def count_constructors(qcirc, gi):
for i in range(gi):
qcirc.append(oracle, tape)
disp_isv(qcirc, "Step: Mark", all=False, precision=1e-4)
qcirc.append(aa, tape)
# disp_isv(qcirc, "Step: Amplify", all=False, precision=1e-4)
qcirc.measure(tape, range(len(tape)))
emulator = Aer.get_backend('qasm_simulator')
job = execute(qcirc, emulator, shots=2048)
hist = job.result().get_counts()
print(hist)
return
# def count_constructors(qcirc, gi):
# qcirc.append(oracle, tape)
# qcirc.append(aa, tape)
# qcirc.append(pattern, tape)
# qcirc.append(aa, tape)
# for i in range(gi):
# qcirc.append(oracle, tape)
# disp_isv(qcirc, "Step: Mark", all=False, precision=1e-4)
# qcirc.append(aa, tape)
# # disp_isv(qcirc, "Step: Amplify", all=False, precision=1e-4)
# qcirc.measure(tape, range(len(tape)))
# # print()
# # print(qcirc.draw())
# emulator = Aer.get_backend('qasm_simulator')
# job = execute(qcirc, emulator, shots=2048)
# hist = job.result().get_counts()
# print(hist)
# return
for i in range(0,3):
count_constructors(deepcopy(qcirc),i)
#=====================================================================================================================
# Code below archived for now
#=====================================================================================================================
def count_constructors():
#=====================================================================================================================
# Create controlled Grover oracle circuit
oracle = U_oracle(len(search)).to_gate()
c_oracle = oracle.control()
c_oracle.label = "cGO"
# Create controlled Grover diffuser circuit
# diffuser = U_diffuser(len(search)).to_gate()
allregs = list(range(sum(qnos[0:0]),sum(qnos[0:8])))
# selregs = [0,1,2,3,9,10,11,12,14] # fsm, tape, ancilla[1]
selregs = [0,9,10,11,12] # fsm[0], tape
diffuser = U_diffuser(len(selregs)).to_gate()
c_diffuser = diffuser.control()
c_diffuser.label = "cGD"
# Create inverse QFT circuit
iqft = U_QFT(len(count)).to_gate().inverse()
iqft.label = "iQFT"
#=====================================================================================================================
qcirc.h(count)
qcirc.barrier()
# Begin controlled Grover iterations
iterations = 1
for qb in count:
for i in range(iterations):
qcirc.append(c_oracle, [qb] + search)
qcirc.append(c_diffuser, [qb] + selregs)
iterations *= 2
qcirc.barrier()
# Inverse QFT
qcirc.append(iqft, count)
qcirc.barrier()
# print()
# disp_isv(qcirc, "Step: Search and count", all=False, precision=1e-4)
# Measure counting qubits
qcirc.measure(count, range(len(count)))
# print()
# print(qcirc.draw())
# sys.exit(0)
#=====================================================================================================================
emulator = Aer.get_backend('qasm_simulator')
job = execute(qcirc, emulator, shots=128)
hist = job.result().get_counts()
# print(hist)
measured_int = int(max(hist, key=hist.get),2)
theta = (measured_int/(2**len(count)))*pi*2
counter = 2**len(selregs) * (1 - sin(theta/2)**2)
print("Number of solutions = %.1f" % counter)
#=====================================================================================================================
|
https://github.com/Advanced-Research-Centre/QPULBA
|
Advanced-Research-Centre
|
from qiskit import QuantumCircuit
import numpy as np
import random
from qiskit import Aer, execute
from math import log2, ceil, pi
circ = QuantumCircuit(8)
simulator = Aer.get_backend('statevector_simulator')
def disp_isv(circ, msg="", all=True, precision=1e-8):
sim_res = execute(circ, simulator).result()
statevector = sim_res.get_statevector(circ)
qb = int(log2(len(statevector)))
print("\n============ State Vector ============", msg)
s = 0
for i in statevector:
if (all == True): print(' ({:.5f}) |{:0{}b}>'.format(i,s,qb))
else:
if (abs(i) > precision): print(' ({:+.5f}) |{:0{}b}>'.format(i,s,qb))
s = s+1
print("============..............============")
return
# Step 1
circ.h(1)#ry(round(pi * random.random(),2),1)
circ.h(2)#ry(round(pi * random.random(),2),2)
circ.barrier()
disp_isv(circ,"Step 1",False,1e-4)
# Step 2
aU0 = round(pi * random.random(),2)
circ.ry(aU0,0)
circ.barrier()
disp_isv(circ,"Step 2",False,1e-4)
# Step 3
#circ.cx(0,4)
#circ.cx(1,5)
#circ.cx(2,6)
circ.barrier()
disp_isv(circ,"Step 3",False,1e-4)
# Step 4
circ.x(0)
circ.toffoli(0,1,3)
circ.x(0)
circ.toffoli(0,2,3)
circ.barrier()
disp_isv(circ,"Step 4",False,1e-4)
# Step 5
circ.cx(3,7)
circ.barrier()
disp_isv(circ,"Step 4",False,1e-4)
# Step 4
circ.toffoli(0,2,3)
circ.x(0)
circ.toffoli(0,1,3)
circ.x(0)
circ.barrier()
disp_isv(circ,"Step 4",False,1e-4)
## Step 5
#circ.ry(-aU0,0)
#circ.h(1)
#circ.h(2)
#circ.barrier()
#disp_isv(circ,"Step 5",False,1e-4)
## Step 6
#circ.swap(0,3)
#disp_isv(circ,"Step 6",False,1e-4)
print()
print(circ.draw())
|
https://github.com/Advanced-Research-Centre/QPULBA
|
Advanced-Research-Centre
|
import qiskit
print("hello many worlds")
|
https://github.com/Advanced-Research-Centre/QPULBA
|
Advanced-Research-Centre
|
#from qiskit import QuantumRegister, ClassicalRegister
#from qiskit.tools.visualization import plot_histogram, plot_state_city
from qiskit import QuantumCircuit
circ = QuantumCircuit(2, 2)
import numpy as np
circ.initialize([1, 1, 0, 0] / np.sqrt(2), [0, 1])
circ.h(0)
circ.cx(0, 1)
circ.measure([0,1], [0,1])
from qiskit import Aer
# print(Aer.backends())
# 'qasm_simulator', 'statevector_simulator', 'unitary_simulator', 'pulse_simulator'
sim1 = Aer.get_backend('qasm_simulator')
from qiskit import execute
result1 = execute(circ, sim1, shots=10, memory=True).result()
counts = result1.get_counts(circ)
print(counts)
# memory = result1.get_memory(circ)
# print(memory)
sim2 = Aer.get_backend('statevector_simulator')
result2 = execute(circ, sim2).result()
statevector = result2.get_statevector(circ)
print(statevector)
|
https://github.com/Advanced-Research-Centre/QPULBA
|
Advanced-Research-Centre
|
from qiskit import QuantumCircuit
circ = QuantumCircuit(1)
import numpy as np
# circ.initialize([1, 1, 0, 0] / np.sqrt(2), [0, 1])
circ.ry(np.pi/2,0)
from qiskit import Aer, execute
simulator = Aer.get_backend('statevector_simulator')
sim_res = execute(circ, simulator).result()
statevector = sim_res.get_statevector(circ)
for i in statevector:
print(i)
|
https://github.com/Advanced-Research-Centre/QPULBA
|
Advanced-Research-Centre
|
from qiskit import QuantumCircuit
import numpy as np
import random
from qiskit import Aer, execute
circ = QuantumCircuit(4)
simulator = Aer.get_backend('statevector_simulator')
def display(circ):
sim_res = execute(circ, simulator).result()
statevector = sim_res.get_statevector(circ)
print("============ State Vector ============")
for i in statevector:
print(i)
print("============..............============")
# circ.initialize([1, 1, 0, 0] / np.sqrt(2), [0, 1])
display(circ)
# initialize
a1 = np.pi * random.random()
circ.ry(a1,0)
a2 = np.pi * random.random()
circ.ry(a2,1)
a3 = np.pi * random.random()
circ.ry(a3,2)
display(circ)
|
https://github.com/Advanced-Research-Centre/QPULBA
|
Advanced-Research-Centre
|
from qiskit import QuantumCircuit
import numpy as np
import random
from qiskit import Aer, execute
qubits = 17
circ = QuantumCircuit(qubits)
simulator = Aer.get_backend('statevector_simulator')
def display(circ):
sim_res = execute(circ, simulator).result()
statevector = sim_res.get_statevector(circ)
print("============ State Vector ============")
for i in statevector:
print(i)
print("============..............============")
# initialize
for q in range(0,qubits):
ang = np.pi * random.random()
circ.ry(ang,q)
display(circ)
|
https://github.com/Advanced-Research-Centre/QPULBA
|
Advanced-Research-Centre
|
from qiskit import QuantumCircuit
import numpy as np
import random
from qiskit import Aer, execute
import math
circ = QuantumCircuit(4)
simulator = Aer.get_backend('statevector_simulator')
def display(circ,msg=""):
sim_res = execute(circ, simulator).result()
statevector = sim_res.get_statevector(circ)
qb = int(math.log2(len(statevector)))
print("============ State Vector ============", msg)
s = 0
for i in statevector:
print(' ({:.5f}) |{:0{}b}>'.format(i,s,qb))
s = s+1
print("============..............============")
# circ.initialize([1, 1, 0, 0] / np.sqrt(2), [0, 1])
display(circ,"step 0")
# initialize
a1 = np.pi * random.random()
circ.ry(a1,0)
display(circ,"step 1")
a2 = np.pi * random.random()
circ.ry(a2,1)
display(circ,"step 2")
a3 = np.pi * random.random()
#circ.ry(a3,2)
display(circ,"step 3")
circ.x(0)
circ.toffoli(0,1,3)
circ.x(0)
circ.toffoli(0,2,3)
display(circ,"step 4")
print(circ.draw())
|
https://github.com/Advanced-Research-Centre/QPULBA
|
Advanced-Research-Centre
|
from qiskit import QuantumCircuit
import numpy as np
import random
from qiskit import Aer, execute
import math
simulator = Aer.get_backend('statevector_simulator')
def display(circ,msg=""):
sim_res = execute(circ, simulator).result()
statevector = sim_res.get_statevector(circ)
qb = int(math.log2(len(statevector)))
print("============ State Vector ============", msg)
s = 0
for i in statevector:
print(' ({:.5f}) |{:0{}b}>'.format(i,s,qb))
s = s+1
print("============..............============")
a2 = np.pi * random.random()
a3 = np.pi * random.random()
# NEW
circ1 = QuantumCircuit(4)
#display(circ1,"all zero")
circ1.ry(a2,1)
circ1.ry(a3,2)
#display(circ1,"load fsm")
circ1.x(0)
circ1.toffoli(0,1,3)
circ1.x(0)
circ1.toffoli(0,2,3)
#display(circ1,"step 1")
circ1.swap(0,3)
#display(circ1,"reset 1")
circ1.x(0)
circ1.toffoli(0,1,3)
circ1.x(0)
circ1.toffoli(0,2,3)
#display(circ1,"step 2")
circ1.swap(0,3)
circ1.toffoli(0,2,3)
circ1.x(0)
circ1.toffoli(0,1,3)
circ1.x(0)
display(circ1,"reset 2")
print(circ1.draw())
circ2 = QuantumCircuit(5)
#display(circ2,"all zero")
circ2.ry(a2,1)
circ2.ry(a3,2)
#display(circ2,"load fsm")
circ2.x(0)
circ2.toffoli(0,1,3)
circ2.x(0)
circ2.toffoli(0,2,3)
#display(circ2,"step 1")
circ2.swap(0,3)
#display(circ2,"reset 1")
circ2.x(0)
circ2.toffoli(0,1,4)
circ2.x(0)
circ2.toffoli(0,2,4)
#display(circ2,"step 2")
circ2.swap(0,4)
display(circ2,"reset 2")
print(circ2.draw())
|
https://github.com/carstenblank/qiskit-aws-braket-provider
|
carstenblank
|
import cmath
import math
import numpy as np
import qiskit
import matplotlib.pyplot as plt
from qiskit import QuantumCircuit
from typing import Optional, List, Dict
from qiskit_aws_braket_provider.awsprovider import AWSProvider
def compute_rotation(index_state):
if len(index_state) != 2:
return None, None
index_state = np.asarray(index_state)
if abs(np.linalg.norm(index_state)) < 1e-6:
return None, None
index_state = index_state / np.linalg.norm(index_state)
if abs(index_state[0] - index_state[1]) < 1e-6:
return None, None
a_1 = abs(index_state[0])
w_1 = cmath.phase(index_state[0])
a_2 = abs(index_state[1])
w_2 = cmath.phase(index_state[1])
alpha_z = w_2 - w_1
alpha_y = 2 * np.arcsin(abs(a_2) / np.sqrt(a_2 ** 2 + a_1 ** 2))
return alpha_y, alpha_z
def create_swap_test_circuit(index_state, theta, **kwargs):
# type: (List[float], float, Optional[dict]) -> QuantumCircuit
"""
:param index_state:
:param theta:
:param kwargs: use_barriers (bool) and readout_swap (Dict[int, int])
:return:
"""
use_barriers = kwargs.get('use_barriers', False)
readout_swap = kwargs.get('readout_swap', None)
q = qiskit.QuantumRegister(5, "q")
c = qiskit.ClassicalRegister(2, "c")
qc = qiskit.QuantumCircuit(q, c, name="improvement")
# Index on q_0
alpha_y, _ = compute_rotation(index_state)
if alpha_y is None:
qc.h(q[0])
else:
qc.ry(-alpha_y, q[0]).inverse()
if use_barriers: jupyter = qc.barrier()
# Conditionally exite x_1 on data q_2 (center!)
qc.h(q[2])
if use_barriers: qc.barrier()
qc.rz(math.pi, q[2]).inverse()
if use_barriers: qc.barrier()
qc.s(q[2])
if use_barriers: qc.barrier()
qc.cz(q[0], q[2])
if use_barriers: qc.barrier()
# Label y_1
qc.cx(q[0], q[1])
if use_barriers: qc.barrier()
# Ancilla Superposition
qc.h(q[4])
if use_barriers: qc.barrier()
# Unknown data
qc.rx(theta, q[3])
if use_barriers: qc.barrier()
# c-SWAP!!!
# standard.barrier(qc)
qc.cswap(q[4], q[2], q[3])
if use_barriers: qc.barrier()
# Hadamard on ancilla q_4
qc.h(q[4])
if use_barriers: qc.barrier()
# Measure on ancilla q_4 and label q_1
if readout_swap is not None:
qc.barrier()
for i in range(q.size):
j = readout_swap.get(i, i)
if i != j:
qc.swap(q[i], q[j])
else:
readout_swap = {}
qc.barrier()
m1 = readout_swap.get(4, 4)
m2 = readout_swap.get(1, 1)
qiskit.circuit.measure.measure(qc, q[m1], c[0])
qiskit.circuit.measure.measure(qc, q[m2], c[1])
return qc
def extract_classification(counts: Dict[str, int]) -> float:
shots = sum(counts.values())
return (counts.get('00', 0) - counts.get('01', 0) - counts.get('10', 0) + counts.get('11', 0)) / float(shots)
def compare_plot(theta, classification, classification_label=None, compare_classification=None, compare_classification_label=None):
plt.figure(figsize=(10, 7))
theta = theta if len(theta) == len(classification) else range(len(classification))
prefix_label = '{} '.format(classification_label) if classification_label is not None else ''
plt.scatter(x=[xx for xx, p in zip(theta, classification) if p >= 0],
y=[p for p in classification if p >= 0],
label=prefix_label + '$\\tilde{y} = 0$',
c='red',
marker='^',
linewidths=1.0)
plt.scatter(x=[xx for xx, p in zip(theta, classification) if p < 0],
y=[p for p in classification if p < 0],
label=prefix_label + '$\\tilde{y} = 1$',
c='white',
marker='^',
linewidths=1.0, edgecolors='red')
y_lim_lower = min(classification) - 0.1
y_lim_upper = max(classification) + 0.1
if compare_classification is not None and len(compare_classification) == len(classification):
prefix_label = '{} '.format(compare_classification_label) if compare_classification_label is not None else ''
plt.scatter(x=[xx for xx, p in zip(theta, compare_classification) if p >= 0],
y=[p for p in compare_classification if p >= 0],
label=prefix_label + '$\\tilde{y} = 0$',
c='blue',
marker='s',
linewidths=1.0)
plt.scatter(x=[xx for xx, p in zip(theta, compare_classification) if p < 0],
y=[p for p in compare_classification if p < 0],
label=prefix_label + '$\\tilde{y} = 1$',
c='white',
marker='s',
linewidths=1.0, edgecolors='blue')
y_lim_lower = min(min(compare_classification) - 0.1, y_lim_lower)
y_lim_upper = max(max(compare_classification) + 0.1, y_lim_upper)
plt.legend(fontsize=17)
plt.xlabel("$\\theta$ (rad.)", fontsize=22)
plt.ylabel("$\\langle \\sigma_z^{(a)} \\sigma_z^{(l)} \\rangle$", fontsize=22)
plt.tick_params(labelsize=22)
plt.ylim((y_lim_lower, y_lim_upper))
index_state = [np.sqrt(2), np.sqrt(2)]
theta_list = np.arange(start=0, stop=2*np.pi, step=0.2)
qc_list = [create_swap_test_circuit(index_state, theta=theta) for theta in theta_list]
qc_list[0].draw()
provider = AWSProvider(region_name='us-east-1')
backend = provider.get_backend('IonQ Device')
sim_backend = provider.get_backend('SV1')
qc_transpiled_list = qiskit.transpile(qc_list, backend)
qobj = qiskit.assemble(qc_transpiled_list, backend, shots=100)
backend.estimate_costs(qobj), sim_backend.estimate_costs(qobj)
# ATTENTION!!!!!!
# Uncomment to execute
# BE AWARE that this will create costs!
# ATTENTION!!!!!!
# job = backend.run(qobj, extra_data={
# 'index_state': index_state,
# 'theta_list': list(theta_list)
# })
# job_id = job.job_id()
#
# sim_job = sim_backend.run(qobj, extra_data={
# 'index_state': index_state,
# 'theta_list': list(theta_list)
# })
# sim_job_id = sim_job.job_id()
#
# job_id, sim_job_id
# Please input the job ids here
sim_retrieved_job = sim_backend.retrieve_job('<sim_job_id>')
retrieved_job = backend.retrieve_job('<job_id>')
result = retrieved_job.result()
sim_result = sim_retrieved_job.result()
x = retrieved_job.extra_data['theta_list']
experiment_classification = [extract_classification(c) for c in result.get_counts()]
simulation_classification = [extract_classification(c) for c in sim_result.get_counts()]
compare_plot(
theta=theta_list,
classification=experiment_classification, classification_label='experiment',
compare_classification=simulation_classification, compare_classification_label='simulation'
)
|
https://github.com/carstenblank/qiskit-aws-braket-provider
|
carstenblank
|
# Copyright 2020 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, Dict
import pint
import qiskit
from braket.device_schema import DeviceCapabilities
from braket.device_schema.ionq import IonqDeviceCapabilities
from braket.device_schema.rigetti import RigettiDeviceCapabilities
from braket.device_schema.simulators import GateModelSimulatorDeviceCapabilities
from qiskit.providers import BaseBackend
from qiskit.providers.models import QasmBackendConfiguration, BackendProperties
from qiskit.providers.models.backendproperties import Nduv
logger = logging.getLogger(__name__)
units = pint.UnitRegistry()
# noinspection PyTypeChecker
def aws_ionq_to_properties(properties: IonqDeviceCapabilities, configuration: QasmBackendConfiguration) -> BackendProperties:
updated_time: datetime = properties.service.updatedAt or datetime.now()
general: List[Nduv] = []
qubits: List[List[Nduv]] = []
gates: List[qiskit.providers.models.backendproperties.Gate] = []
# FIXME: qiskit has an absolutely rediculous unit conversion mechanism,
# see qiskit.providers.models.backendproperties.BackendProperties._apply_prefix,
# which means that since we have seconds (s) we need to convert them to milli-seconds otherwise we get a
# BackendPropertyError raised.
# per qubit: T1, T2, frequency, anharmonicity, readout_error, prob_meas0_prep1, prob_meas1_prep0
# (if possible)
qubits = [
[
Nduv(date=updated_time, name='T1', unit='ms',
value=(properties.provider.timing.get('T1') * units.seconds).m_as(units.milliseconds)),
Nduv(date=updated_time, name='T2', unit='ms',
value=(properties.provider.timing.get('T2') * units.seconds).m_as(units.milliseconds))
]
for _ in range(configuration.n_qubits)
]
# use native gates and all qubits possibilities: set gate_error and gate_length as parameters (Nduv)
def get_fidelities(qubits):
return properties.provider.fidelity.get('1Q' if len(qubits) == 1 else '2Q', {'mean': None}) \
.get('mean')
def get_timings(qubits):
return properties.provider.timing.get('1Q' if len(qubits) == 1 else '2Q')
gates = [
qiskit.providers.models.backendproperties.Gate(
gate=b.name,
qubits=qubits,
parameters=[
Nduv(date=updated_time, name='gate_error', unit='',
value=1 - get_fidelities(qubits)),
Nduv(date=updated_time, name='gate_length', unit='ms',
value=(get_timings(qubits) * units.seconds).m_as(units.milliseconds))
])
for b in configuration.gates for qubits in b.coupling_map
]
# General Measurements maybe of interest / any other interesting measurement (like cross-talk)
general = [
Nduv(date=updated_time, name='spam_fidelity', unit='',
value=properties.provider.fidelity.get('spam', {'mean': None}).get('mean')),
Nduv(date=updated_time, name='readout_time', unit='ms',
value=(properties.provider.timing.get('readout') * units.seconds).m_as(units.milliseconds)),
Nduv(date=updated_time, name='reset_time', unit='ms',
value=(properties.provider.timing.get('reset') * units.seconds).m_as(units.milliseconds))
]
backend_properties: BackendProperties = BackendProperties(
backend_name=configuration.backend_name,
backend_version=configuration.backend_version,
last_update_date=updated_time,
qubits=qubits,
gates=gates,
general=general
)
return backend_properties
# noinspection PyTypeChecker
def aws_rigetti_to_properties(properties: RigettiDeviceCapabilities, configuration: QasmBackendConfiguration) -> BackendProperties:
updated_time: datetime = properties.service.updatedAt or datetime.now()
general: List[Nduv] = []
qubits: Dict[str, List[Nduv]] = {}
gates: List[qiskit.providers.models.backendproperties.Gate] = []
specs: Dict[str, Dict[str, Dict[str, float]]] = properties.provider.specs
# TODO: check units!!
# per qubit: T1, T2, frequency, anharmonicity, readout_error, prob_meas0_prep1, prob_meas1_prep0
# (if possible)
one_qubit_specs: Dict[str, Dict[str, float]] = specs['1Q']
two_qubit_specs: Dict[str, Dict[str, float]] = specs['2Q']
qubits_dict = dict([
(q, [ # The default cannot be 0.0 exactly... TODO: find out what a good default value could be
Nduv(date=updated_time, name='T1', unit='ms', value=(q_specs.get('T1', 1e-9) * units.seconds).m_as(units.milliseconds)),
Nduv(date=updated_time, name='T2', unit='ms', value=(q_specs.get('T2', 1e-9) * units.seconds).m_as(units.milliseconds)),
Nduv(date=updated_time, name='readout_error', unit='', value=q_specs.get('fRO')),
])
for q, q_specs in one_qubit_specs.items()
])
qubits = list(qubits_dict.values())
# use native gates and all qubits possibilities: set gate_error and gate_length as parameters (Nduv)
def get_fidelities(qubits):
if len(qubits) == 1:
q = configuration.coupling_canonical_2_device[qubits[0]]
stats: Dict[str, float] = one_qubit_specs[q]
return stats.get('f1Q_simultaneous_RB')
else:
q = "-".join([configuration.coupling_canonical_2_device[q] for q in sorted(qubits)])
stats: Dict[str, float] = two_qubit_specs[q]
return stats.get('fCZ')
gates = [
qiskit.providers.models.backendproperties.Gate(
gate=b.name,
qubits=q,
parameters=[
Nduv(date=updated_time, name='gate_error', unit='', value=1 - get_fidelities(q)),
Nduv(date=updated_time, name='gate_length', unit='ns', value=60 if len(q) == 1 else 160 if len(q) else None)
])
for b in configuration.gates for q in b.coupling_map
]
# General Measurements maybe of interest / any other interesting measurement (like cross-talk)
general = []
backend_properties: BackendProperties = BackendProperties(
backend_name=configuration.backend_name,
backend_version=configuration.backend_version,
last_update_date=updated_time,
qubits=qubits,
gates=gates,
general=general
)
# backend_properties._qubits = qubits
return backend_properties
# noinspection PyTypeChecker
def aws_simulator_to_properties(properties: GateModelSimulatorDeviceCapabilities, configuration: QasmBackendConfiguration) -> BackendProperties:
updated_time: datetime = properties.service.updatedAt or datetime.now()
general: List[Nduv] = []
qubits: List[List[Nduv]] = []
gates: List[qiskit.providers.models.backendproperties.Gate] = []
backend_properties: BackendProperties = BackendProperties(
backend_name=configuration.backend_name,
backend_version=configuration.backend_version,
last_update_date=updated_time,
qubits=qubits,
gates=gates,
general=general
)
return backend_properties
# noinspection PyTypeChecker
def aws_general_to_properties(properties: DeviceCapabilities, configuration: QasmBackendConfiguration) -> BackendProperties:
updated_time: datetime = properties.service.updatedAt or datetime.now()
general: List[Nduv] = []
qubits: List[List[Nduv]] = []
gates: List[qiskit.providers.models.backendproperties.Gate] = []
backend_properties: BackendProperties = BackendProperties(
backend_name=configuration.name,
backend_version=configuration.arn,
last_update_date=updated_time,
qubits=qubits,
gates=gates,
general=general
)
return backend_properties
|
https://github.com/carstenblank/qiskit-aws-braket-provider
|
carstenblank
|
# Copyright 2020 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 time
import unittest
import uuid
import boto3
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, transpile, assemble
from qiskit.circuit.measure import measure
from qiskit.providers import JobStatus
from qiskit_aws_braket_provider.awsbackend import AWSBackend
from qiskit_aws_braket_provider.awsprovider import AWSProvider
LOG = logging.getLogger(__name__)
class AWSBackendTests(unittest.TestCase):
backend_name = 'IonQ Device'
def setUp(self) -> None:
logging.basicConfig(format=logging.BASIC_FORMAT, level='INFO')
self.provider: AWSProvider = AWSProvider(region_name='us-east-1')
self.backend: AWSBackend = self.provider.get_backend(self.backend_name)
def test_get_job_data_s3_folder(self):
key = self.backend._get_job_data_s3_folder('12345')
self.assertEqual(key, f'results-{self.backend_name}-12345')
def test_save_job_task_arns(self):
job_id = str(uuid.uuid4())
task_arns = ['537a196e-8162-41c6-8c72-a7f8b456da31', '537a196e-8162-41c6-8c72-a7f8b456da32',
'537a196e-8162-41c6-8c72-a7f8b456da33', '537a196e-8162-41c6-8c72-a7f8b456da34']
s3_bucket, s3_folder = self.backend._save_job_task_arns(job_id, task_arns)
self.assertTrue(
AWSBackend._exists_file(self.provider._session.client('s3'), s3_bucket, f'{s3_folder}/task_arns.json')
)
self.backend._delete_job_task_arns(job_id=job_id, s3_bucket=s3_bucket)
def test_save_job_data_s3(self):
creg = ClassicalRegister(2)
qreg = QuantumRegister(2)
qc = QuantumCircuit(qreg, creg, name='test')
qc.h(0)
qc.cx(0, 1)
measure(qc, qreg, creg)
qobj = assemble(10 * [qc])
extra_data = {
'test': [
'yes', 'is', 'there'
]
}
s3_bucket, s3_key = self.backend._save_job_data_s3(qobj=qobj, s3_bucket=None, extra_data=extra_data)
self.assertEqual(s3_bucket, self.backend.provider().get_default_bucket())
self.assertEqual(s3_key, f'results-{self.backend_name}-{qobj.qobj_id}')
self.assertTrue(
AWSBackend._exists_file(self.provider._session.client('s3'), s3_bucket, f'{s3_key}/qiskit_qobj_data.json')
)
self.backend._delete_job_data_s3(job_id=qobj.qobj_id, s3_bucket=None)
def test_load_job_task_arns(self):
job_id = '2020-09-17T18:47:48.653735-60f7a533-a5d5-481c-9671-681f4823ce25'
arns = self.backend._load_job_task_arns(job_id=job_id)
self.assertListEqual(
arns, ['537a196e-8162-41c6-8c72-a7f8b456da31', '537a196e-8162-41c6-8c72-a7f8b456da32',
'537a196e-8162-41c6-8c72-a7f8b456da33', '537a196e-8162-41c6-8c72-a7f8b456da34']
)
def test_load_job_data_s3(self):
job_id = '2020-09-17T18:47:48.653735-60f7a533-a5d5-481c-9671-681f4823ce25'
qobj, extra_data = self.backend._load_job_data_s3(job_id=job_id)
self.assertEqual(qobj.qobj_id, '66da2c50-2e5c-47aa-81c5-d47a04df804c')
self.assertTrue('test' in extra_data)
self.assertListEqual(extra_data['test'], ['yes', 'is', 'there'])
def test_compile(self):
creg = ClassicalRegister(2)
qreg = QuantumRegister(2)
qc = QuantumCircuit(qreg, creg, name='test')
qc.h(0)
qc.cx(0, 1)
measure(qc, qreg, creg)
qc_transpiled = transpile(qc, self.backend)
qobj = assemble(qc_transpiled, self.backend)
LOG.info(qobj)
def test_retrieve_job_done(self):
job_id = '52284ef5-1cf7-4182-9547-5bbc7c5dd9f5'
job = self.backend.retrieve_job(job_id)
self.assertIsNotNone(job)
self.assertEqual(job.job_id(), job_id)
self.assertEqual(job.status(), JobStatus.DONE)
def test_retrieve_job_cancelled(self):
job_id = '66b6a642-7db3-4134-8181-f7039b56fdfd'
job = self.backend.retrieve_job(job_id)
self.assertIsNotNone(job)
self.assertEqual(job.job_id(), job_id)
self.assertEqual(job.status(), JobStatus.CANCELLED)
def test_run(self):
creg = ClassicalRegister(2)
qreg = QuantumRegister(2)
qc = QuantumCircuit(qreg, creg, name='test')
qc.h(0)
qc.cx(0, 1)
measure(qc, qreg, creg)
qc_transpiled = transpile(qc, self.backend)
qobj = assemble(qc_transpiled, self.backend, shots=1)
extra_data = {
'test': [
'yes', 'is', 'there'
]
}
job = self.backend.run(qobj, extra_data=extra_data)
LOG.info(job.job_id())
self.assertIsNotNone(job)
self.assertEqual(job.job_id(), qobj.qobj_id)
self.assertTrue(job.status() in [JobStatus.INITIALIZING, JobStatus.QUEUED])
while job.status() != JobStatus.QUEUED:
time.sleep(1)
job.cancel()
|
https://github.com/carstenblank/qiskit-aws-braket-provider
|
carstenblank
|
# This code is part of Qiskit.
#
# (C) Alpine Quantum Technologies GmbH 2023
#
# 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.
from math import pi
from typing import Union
import pytest
from hypothesis import assume, given
from hypothesis import strategies as st
from qiskit import QuantumCircuit, transpile
from qiskit.circuit.library import RXGate, RYGate
from qiskit_aqt_provider.aqt_resource import AQTResource
from qiskit_aqt_provider.test.circuits import (
assert_circuits_equal,
assert_circuits_equivalent,
qft_circuit,
)
from qiskit_aqt_provider.test.fixtures import MockSimulator
from qiskit_aqt_provider.transpiler_plugin import rewrite_rx_as_r, wrap_rxx_angle
@pytest.mark.parametrize(
("input_theta", "output_theta", "output_phi"),
[
(pi / 3, pi / 3, 0.0),
(-pi / 3, pi / 3, pi),
(7 * pi / 5, 3 * pi / 5, pi),
(25 * pi, pi, pi),
(22 * pi / 3, 2 * pi / 3, pi),
],
)
def test_rx_rewrite_example(
input_theta: float,
output_theta: float,
output_phi: float,
) -> None:
"""Snapshot test for the Rx(θ) → R(θ, φ) rule."""
result = QuantumCircuit(1)
result.append(rewrite_rx_as_r(input_theta), (0,))
expected = QuantumCircuit(1)
expected.r(output_theta, output_phi, 0)
reference = QuantumCircuit(1)
reference.rx(input_theta, 0)
assert_circuits_equal(result, expected)
assert_circuits_equivalent(result, reference)
@given(theta=st.floats(allow_nan=False, min_value=-1000 * pi, max_value=1000 * pi))
@pytest.mark.parametrize("optimization_level", [1, 2, 3])
@pytest.mark.parametrize("test_gate", [RXGate, RYGate])
def test_rx_ry_rewrite_transpile(
theta: float,
optimization_level: int,
test_gate: Union[RXGate, RYGate],
) -> None:
"""Test the rewrite rule: Rx(θ), Ry(θ) → R(θ, φ), θ ∈ [0, π], φ ∈ [0, 2π]."""
assume(abs(theta) > pi / 200)
# we only need the backend's transpiler target for this test
backend = MockSimulator(noisy=False)
qc = QuantumCircuit(1)
qc.append(test_gate(theta), (0,))
trans_qc = transpile(qc, backend, optimization_level=optimization_level)
assert isinstance(trans_qc, QuantumCircuit)
assert_circuits_equivalent(trans_qc, qc)
assert set(trans_qc.count_ops()) <= set(backend.configuration().basis_gates)
num_r = trans_qc.count_ops().get("r")
assume(num_r is not None)
assert num_r == 1
for operation in trans_qc.data:
instruction = operation[0]
if instruction.name == "r":
theta, phi = instruction.params
assert 0 <= float(theta) <= pi
assert 0 <= float(phi) <= 2 * pi
break
else: # pragma: no cover
pytest.fail("No R gates in transpiled circuit.")
def test_decompose_1q_rotations_example(offline_simulator_no_noise: AQTResource) -> None:
"""Snapshot test for the efficient rewrite of single-qubit rotation runs as ZXZ."""
qc = QuantumCircuit(1)
qc.rx(pi / 2, 0)
qc.ry(pi / 2, 0)
expected = QuantumCircuit(1)
expected.rz(-pi / 2, 0)
expected.r(pi / 2, 0, 0)
result = transpile(qc, offline_simulator_no_noise, optimization_level=3)
assert isinstance(result, QuantumCircuit) # only got one circuit back
assert_circuits_equal(result, expected)
assert_circuits_equivalent(result, expected)
def test_rxx_wrap_angle_case0() -> None:
"""Snapshot test for Rxx(θ) rewrite with 0 <= θ <= π/2."""
result = QuantumCircuit(2)
result.append(wrap_rxx_angle(pi / 2), (0, 1))
expected = QuantumCircuit(2)
expected.rxx(pi / 2, 0, 1)
assert_circuits_equal(result.decompose(), expected)
assert_circuits_equivalent(result.decompose(), expected)
def test_rxx_wrap_angle_case0_negative() -> None:
"""Snapshot test for Rxx(θ) rewrite with -π/2 <= θ < 0."""
result = QuantumCircuit(2)
result.append(wrap_rxx_angle(-pi / 2), (0, 1))
expected = QuantumCircuit(2)
expected.rz(pi, 0)
expected.rxx(pi / 2, 0, 1)
expected.rz(pi, 0)
assert_circuits_equal(result.decompose(), expected)
assert_circuits_equivalent(result.decompose(), expected)
def test_rxx_wrap_angle_case1() -> None:
"""Snapshot test for Rxx(θ) rewrite with π/2 < θ <= 3π/2."""
result = QuantumCircuit(2)
result.append(wrap_rxx_angle(3 * pi / 2), (0, 1))
expected = QuantumCircuit(2)
expected.rx(pi, 0)
expected.rx(pi, 1)
expected.rxx(pi / 2, 0, 1)
assert_circuits_equal(result.decompose(), expected)
assert_circuits_equivalent(result.decompose(), expected)
def test_rxx_wrap_angle_case1_negative() -> None:
"""Snapshot test for Rxx(θ) rewrite with -3π/2 <= θ < -π/2."""
result = QuantumCircuit(2)
result.append(wrap_rxx_angle(-3 * pi / 2), (0, 1))
expected = QuantumCircuit(2)
expected.rxx(pi / 2, 0, 1)
assert_circuits_equal(result.decompose(), expected)
assert_circuits_equivalent(result.decompose(), expected)
def test_rxx_wrap_angle_case2() -> None:
"""Snapshot test for Rxx(θ) rewrite with θ > 3*π/2."""
result = QuantumCircuit(2)
result.append(wrap_rxx_angle(18 * pi / 10), (0, 1)) # mod 2π = 9π/5 → -π/5
expected = QuantumCircuit(2)
expected.rz(pi, 0)
expected.rxx(pi / 5, 0, 1)
expected.rz(pi, 0)
assert_circuits_equal(result.decompose(), expected)
assert_circuits_equivalent(result.decompose(), expected)
def test_rxx_wrap_angle_case2_negative() -> None:
"""Snapshot test for Rxx(θ) rewrite with θ < -3π/2."""
result = QuantumCircuit(2)
result.append(wrap_rxx_angle(-18 * pi / 10), (0, 1)) # mod 2π = π/5
expected = QuantumCircuit(2)
expected.rxx(pi / 5, 0, 1)
assert_circuits_equal(result.decompose(), expected)
assert_circuits_equivalent(result.decompose(), expected)
@given(
angle=st.floats(
allow_nan=False,
allow_infinity=False,
min_value=-1000 * pi,
max_value=1000 * pi,
)
)
@pytest.mark.parametrize("qubits", [3])
@pytest.mark.parametrize("optimization_level", [1, 2, 3])
def test_rxx_wrap_angle_transpile(angle: float, qubits: int, optimization_level: int) -> None:
"""Check that Rxx angles are wrapped by the transpiler."""
assume(abs(angle) > pi / 200)
qc = QuantumCircuit(qubits)
qc.rxx(angle, 0, 1)
# we only need the backend's transpilation target for this test
backend = MockSimulator(noisy=False)
trans_qc = transpile(qc, backend, optimization_level=optimization_level)
assert isinstance(trans_qc, QuantumCircuit)
assert_circuits_equivalent(trans_qc, qc)
assert set(trans_qc.count_ops()) <= set(backend.configuration().basis_gates)
num_rxx = trans_qc.count_ops().get("rxx")
# in high optimization levels, the gate might be dropped
assume(num_rxx is not None)
assert num_rxx == 1
# check that all Rxx have angles in [0, π/2]
for operation in trans_qc.data:
instruction = operation[0]
if instruction.name == "rxx":
(theta,) = instruction.params
assert 0 <= float(theta) <= pi / 2
break # there's only one Rxx gate in the circuit
else: # pragma: no cover
pytest.fail("Transpiled circuit contains no Rxx gate.")
@pytest.mark.parametrize("qubits", [1, 5, 10])
@pytest.mark.parametrize("optimization_level", [1, 2, 3])
def test_qft_circuit_transpilation(
qubits: int, optimization_level: int, offline_simulator_no_noise: AQTResource
) -> None:
"""Transpile a N-qubit QFT circuit for an AQT backend. Check that the angles are properly
wrapped.
"""
qc = qft_circuit(qubits)
trans_qc = transpile(qc, offline_simulator_no_noise, optimization_level=optimization_level)
assert isinstance(trans_qc, QuantumCircuit)
assert set(trans_qc.count_ops()) <= set(offline_simulator_no_noise.configuration().basis_gates)
for operation in trans_qc.data:
instruction = operation[0]
if instruction.name == "rxx":
(theta,) = instruction.params
assert 0 <= float(theta) <= pi / 2
if instruction.name == "r":
(theta, _) = instruction.params
assert abs(theta) <= pi
if optimization_level < 3 and qubits < 6:
assert_circuits_equivalent(qc, trans_qc)
|
https://github.com/maheshwaripranav/Qiskit-Fall-Fest-Kolkata-Hackathon
|
maheshwaripranav
|
import numpy as np
from qiskit import QuantumCircuit, Aer
import matplotlib.pyplot as plt
angles = np.array([ord("Z")-ord(i) for i in input().upper()])
print(angles)
angles = 2*np.arcsin(np.sqrt(angles/25))
print(angles)
n = len(angles)
qc = QuantumCircuit(n,n)
for i in range(len(angles)):
qc.ry(angles[i],i)
qc.draw()
#for i in range(len(angles)):
# qc.ry(-angles[i],i)
qc.measure(range(4),range(4))
qc.draw()
backend_sim = Aer.get_backend('qasm_simulator')
job_sim = backend_sim.run(qc, shots=1024)
result_sim = job_sim.result()
counts = result_sim.get_counts()
arr = [0 for _ in range(n)]
for state, count in counts.items():
state = state[::-1]
for i in range(n):
arr[i] += int(state[i])*count/1024
output = ""
for i in range(n):
output += chr(ord("A")+25-int(round(arr[i]*25,0)))
print(output)
|
https://github.com/maheshwaripranav/Qiskit-Fall-Fest-Kolkata-Hackathon
|
maheshwaripranav
|
import numpy as np
# Importing standard Qiskit libraries
from qiskit import QuantumCircuit, transpile, Aer, IBMQ, QuantumRegister, ClassicalRegister
from qiskit.tools.jupyter import *
from qiskit.visualization import *
from ibm_quantum_widgets import *
from qiskit.providers.aer import QasmSimulator
import qiskit
import copy
import matplotlib.pyplot as plt
# Loading your IBM Quantum account(s)
provider = IBMQ.load_account()
from sklearn import model_selection, datasets, svm
linnerrud = datasets.load_linnerrud()
X = linnerrud.data[0:100]
Y = linnerrud.target[0:100]
X_train, X_test, Y_train, Y_test = model_selection.train_test_split(X, Y, test_size = 0.33, random_state = 42)
print(Y_train)
print(X_train[0])
N = 4
def feature_map(X):
q = QuantumRegister(N)
c = ClassicalRegister(1)
qc = QuantumCircuit(q,c)
for i, x in enumerate(X_train[0]):
qc.rx(x,i)
return qc,c
def variational_circuit(qc, theta):
for i in range(N-1):
qc.cnot(i, i+1)
qc.cnot(N-1, 0)
for i in range(N):
qc.ry(theta[i], i)
return qc
def quantum_nn(X, theta, simulator = True):
qc,c = feature_map(X)
qc = variational_circuit(qc, theta)
qc.measure(0,c)
shots = 1E4
backend = Aer.get_backend('qasm_simulator')
if simulator == False:
shots = 5000
provider = IBMQ.load_account()
backend = provider.get_backend('ibmq_athens')
job = qiskit.execute(qc, backend, shots = shots)
result = job.result()
counts = result.get_counts(qc)
print(counts)
return(counts['1']/shots)
def loss(prediction, target):
return (prediction-target)**2
def gradient(X, Y, theta):
delta = 0.01
grad = []
for i in range(len(theta)):
dtheta = copy.copy(theta)
dtheta += delta
pred_1 = quantum_nn(X, dtheta)
pred_2 = quantum_nn(X, theta)
grad.append((loss(pred_1, Y) - loss(pred_2, Y))/delta)
return np.array(grad)
def accuracy(X, Y, theta):
counter = 0
for X_i, Y_i in zip(X, Y):
prediction = quantum_nn(X_i, theta)
if prediction < 0.5 and Y_i == 0:
counter += 1
if prediction >= 0.5 and Y_i == 1:
counter += 1
return counter/len(Y)
eta = 0.05
loss_list = []
theta = np.ones(N)
print('Epoch\t Loss\t Training Accuracy')
for i in range(20):
loss_tmp = []
for X_i, Y_i in zip(X_train, Y_train):
prediction = quantum_nn(X_i, theta)
loss_tmp.append(loss(prediction, Y_i))
theta = theta - eta * gradient(X_i, Y_i, theta)
loss_list.append(np.mean(loss_tmp))
acc = accuracy(X_train, Y_train, theta)
print(f'{i} \t {loss_list[-1]:0.3f} \t {acc:0.3f}')
plt.plot(loss_list)
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.show
accuracy(X_test, Y_test, theta)
clf = svm.SVC()
clf.fit(X_train, Y_train)
print(clf.predict(X_test))
print(Y_test)
quantum_nn(X_test[6], theta, simulator = False)
quantum_nn(X_test[6], theta)
Y_test[6]
|
https://github.com/maheshwaripranav/Qiskit-Fall-Fest-Kolkata-Hackathon
|
maheshwaripranav
|
# Essentials
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
# Classical Machine Learning
from sklearn.svm import SVC
from sklearn.datasets import make_blobs, make_circles
from sklearn.cluster import SpectralClustering
from sklearn.metrics import normalized_mutual_info_score, accuracy_score
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler, MinMaxScaler
# Quantum Machine Learning
from qiskit import BasicAer
from qiskit.circuit.library import ZZFeatureMap, ZFeatureMap, PauliFeatureMap
from qiskit.utils import QuantumInstance, algorithm_globals
from qiskit_machine_learning.algorithms import QSVC
from qiskit_machine_learning.kernels import QuantumKernel
dataset = pd.read_csv(r'iris_data\iris.data')
features_all= dataset.iloc[:, :4].values
features_sepal= dataset.iloc[:, :2].values
features_petal= dataset.iloc[:, 2:4].values
label = dataset.iloc[:, 4].values
for i in range(len(label)):
if label[i] == 'Iris-setosa':
label[i] = 0
elif label[i] == 'Iris-versicolor':
label[i] = 1
elif label[i] == 'Iris-virginica':
label[i] = 2
label = label.astype(str).astype(int)
X_train, X_test, y_train, y_test = train_test_split(features_all, label, test_size=0.25, random_state=12)
sc = StandardScaler()
X_train = sc.fit_transform(X_train)
X_test = sc.transform(X_test)
# Normalize
mms = MinMaxScaler((-1, 1))
X_train = mms.fit_transform(X_train)
X_test = mms.transform(X_test)
clf = SVC(kernel="linear", random_state=2)
clf.fit(X_train, y_train)
y_pred = clf.predict(X_test)
print("Accuracy is", accuracy_score(y_test, y_pred))
X_train, X_test, y_train, y_test = train_test_split(features_sepal, label, test_size=0.25, random_state=12)
sc = StandardScaler()
X_train = sc.fit_transform(X_train)
X_test = sc.transform(X_test)
# Normalize
mms = MinMaxScaler((-1, 1))
X_train = mms.fit_transform(X_train)
X_test = mms.transform(X_test)
clf = SVC(kernel="rbf", random_state=2)
clf.fit(X_train, y_train)
y_pred = clf.predict(X_test)
print("Accuracy is", accuracy_score(y_test, y_pred))
X_train, X_test, y_train, y_test = train_test_split(features_petal, label, test_size=0.25, random_state=12)
sc = StandardScaler()
X_train = sc.fit_transform(X_train)
X_test = sc.transform(X_test)
# Normalize
mms = MinMaxScaler((-1, 1))
X_train = mms.fit_transform(X_train)
X_test = mms.transform(X_test)
clf = SVC(kernel="linear", random_state=2)
clf.fit(X_train, y_train)
y_pred = clf.predict(X_test)
print("Accuracy is", accuracy_score(y_test, y_pred))
feature_map = ZZFeatureMap(feature_dimension=2, reps=2, entanglement='linear')
backend = QuantumInstance(BasicAer.get_backend('qasm_simulator'), shots=8000)
kernel = QuantumKernel(feature_map=feature_map, quantum_instance=backend)
X_train, X_test, y_train, y_test = train_test_split(features_all, label, test_size=0.25, random_state=12)
sc = StandardScaler()
X_train = sc.fit_transform(X_train)
X_test = sc.transform(X_test)
# Normalize
mms = MinMaxScaler((-1, 1))
X_train = mms.fit_transform(X_train)
X_test = mms.transform(X_test)
clf = SVC(kernel=kernel.evaluate)
clf.fit(X_train, y_train)
y_pred = clf.predict(X_test)
print("Accuracy is", accuracy_score(y_test, y_pred))
X_train, X_test, y_train, y_test = train_test_split(features_sepal, label, test_size=0.25, random_state=12)
sc = StandardScaler()
X_train = sc.fit_transform(X_train)
X_test = sc.transform(X_test)
# Normalize
mms = MinMaxScaler((-1, 1))
X_train = mms.fit_transform(X_train)
X_test = mms.transform(X_test)
clf = SVC(kernel="rbf", random_state=2)
clf.fit(X_train, y_train)
y_pred = clf.predict(X_test)
print("Accuracy is", accuracy_score(y_test, y_pred))
X_train, X_test, y_train, y_test = train_test_split(features_petal, label, test_size=0.25, random_state=12)
sc = StandardScaler()
X_train = sc.fit_transform(X_train)
X_test = sc.transform(X_test)
# Normalize
mms = MinMaxScaler((-1, 1))
X_train = mms.fit_transform(X_train)
X_test = mms.transform(X_test)
clf = SVC(kernel="linear", random_state=2)
clf.fit(X_train, y_train)
y_pred = clf.predict(X_test)
print("Accuracy is", accuracy_score(y_test, y_pred))
|
https://github.com/maheshwaripranav/Qiskit-Fall-Fest-Kolkata-Hackathon
|
maheshwaripranav
|
import qiskit
import numpy as np
import math
import random
import pandas as pd
from qiskit import IBMQ
IBMQ.save_account('3ccb2d17a0f19c3ce64cf44b3e1c90d3369ea562672f7315624ee8d92bb4350e10b643e3b2af92eef73c029e051518c2a833fb0ffa2e600b2c6c65ed5dd29d40')
IBMQ.load_account()
from qiskit import *
import math as m
import time
from copy import deepcopy
from qiskit import QuantumRegister, QuantumCircuit, ClassicalRegister, Aer
from qiskit.quantum_info import state_fidelity
#simulators
S_simulator = Aer.backends(name = 'statevector_simulator')[0]
M_simulator = Aer.backends(name = 'qasm_simulator')[0]
U_simulator = Aer.backends(name = 'unitary_simulator')[0]
#provider = IBMQ.get_provider(hub = 'ibm-q-research')
csv_url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'
# using the attribute information as the column names
col_names = ['Sepal_Length','Sepal_Width','Petal_Length','Petal_Width','Class']
iris = pd.read_csv(csv_url, names = col_names)
#amplitude encoding
# total amplitudes to be encoded = features*total_instances = 600
# total computatuional basis states available = 2**10 = 1024
# redundant states = 1024 - 600 = 424
features = 4
total_instances = 150
num_qubits = int(math.log(features*total_instances,2)) +1
redundant_basis_states = 2**num_qubits - features*total_instances
redundant_basis_states_list = list(np.zeros(redundant_basis_states,dtype = int))
q = QuantumRegister(num_qubits)
qc = QuantumCircuit(q)
Vector = []
for i in range(total_instances):
vector = [iris['Sepal_Length'][i],iris['Sepal_Width'][i],iris['Petal_Length'][i],iris['Petal_Length'][i] ]
#Vector = list(np.concatenate(vector))
Vector.append(vector)
#Vector = Vector.append(redundant_basis_states_list)
final_state = list(np.concatenate(Vector))
Final_state = final_state + redundant_basis_states_list
normalized_state = (Final_state / np.linalg.norm(Final_state))
qc.initialize(normalized_state)
qc.draw('mpl')
# the corresponding state contains all 600 amplitudes
# angle encoding
Vector
circuit = QuantumCircuit(features, 4)
for j in range(total_instances):
for i in range(features):
circuit.ry(Vector[j][i],i)
#qc.ry(Vector[i],i)
circuit.measure(range(4), range(4))
circuit.draw('mpl')
backend_sim = Aer.get_backend('qasm_simulator')
job_sim = backend_sim.run(circuit, shots=1024)
result_sim = job_sim.result()
counts = result_sim.get_counts()
counts
|
https://github.com/maheshwaripranav/Qiskit-Fall-Fest-Kolkata-Hackathon
|
maheshwaripranav
|
# Essentials
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
# Classical Machine Learning
from sklearn.svm import SVC
from sklearn.datasets import make_blobs, make_circles
from sklearn.cluster import SpectralClustering
from sklearn.metrics import normalized_mutual_info_score, accuracy_score
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler, MinMaxScaler
# Quantum Machine Learning
from qiskit import BasicAer
from qiskit.circuit.library import ZZFeatureMap, ZFeatureMap, PauliFeatureMap
from qiskit.utils import QuantumInstance, algorithm_globals
from qiskit_machine_learning.algorithms import QSVC
from qiskit_machine_learning.kernels import QuantumKernel
dataset = pd.read_csv(r'iris_data\iris.data')
features= dataset.iloc[:, :4].values
label = dataset.iloc[:, 4].values
for i in range(len(label)):
if label[i] == 'Iris-setosa':
label[i] = 0
elif label[i] == 'Iris-versicolor':
label[i] = 1
elif label[i] == 'Iris-virginica':
label[i] = 2
label
X_train, X_test, y_train, y_test = train_test_split(features, label, test_size=0.25, random_state=11)
sc = StandardScaler()
X_train = sc.fit_transform(X_train)
X_test = sc.transform(X_test)
# Normalize
mms = MinMaxScaler((-1, 1))
X_train = mms.fit_transform(X_train)
X_test = mms.transform(X_test)
clf = SVC(kernel="linear", random_state=2)
clf.fit(X_train, y_train)
print("Accuracy is", accuracy_score(y_test, y_pred))
|
https://github.com/maheshwaripranav/Qiskit-Fall-Fest-Kolkata-Hackathon
|
maheshwaripranav
|
import qiskit
import numpy as np
import math
import random
import pandas as pd
from qiskit import IBMQ
IBMQ.save_account('3ccb2d17a0f19c3ce64cf44b3e1c90d3369ea562672f7315624ee8d92bb4350e10b643e3b2af92eef73c029e051518c2a833fb0ffa2e600b2c6c65ed5dd29d40')
IBMQ.load_account()
from qiskit import *
import math as m
import time
from copy import deepcopy
from qiskit import QuantumRegister, QuantumCircuit, ClassicalRegister, Aer
from qiskit.quantum_info import state_fidelity
#simulators
S_simulator = Aer.backends(name = 'statevector_simulator')[0]
M_simulator = Aer.backends(name = 'qasm_simulator')[0]
U_simulator = Aer.backends(name = 'unitary_simulator')[0]
#provider = IBMQ.get_provider(hub = 'ibm-q-research')
csv_url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'
# using the attribute information as the column names
col_names = ['Sepal_Length','Sepal_Width','Petal_Length','Petal_Width','Class']
iris = pd.read_csv(csv_url, names = col_names)
#amplitude encoding
# total amplitudes to be encoded = features*total_instances = 600
# total computatuional basis states available = 2**10 = 1024
# redundant states = 1024 - 600 = 424
features = 4
total_instances = 150
num_qubits = int(math.log(features*total_instances,2)) +1
redundant_basis_states = 2**num_qubits - features*total_instances
redundant_basis_states_list = list(np.zeros(redundant_basis_states,dtype = int))
q = QuantumRegister(num_qubits)
qc = QuantumCircuit(q)
Vector = []
for i in range(total_instances):
vector = [iris['Sepal_Length'][i],iris['Sepal_Width'][i],iris['Petal_Length'][i],iris['Petal_Length'][i] ]
#Vector = list(np.concatenate(vector))
Vector.append(vector)
#Vector = Vector.append(redundant_basis_states_list)
final_state = list(np.concatenate(Vector))
Final_state = final_state + redundant_basis_states_list
normalized_state = (Final_state / np.linalg.norm(Final_state))
qc.initialize(normalized_state)
qc.draw('mpl')
# the corresponding state contains all 600 amplitudes
# angle encoding
Vector
circuit = QuantumCircuit(features, 4)
for j in range(total_instances):
for i in range(features):
circuit.ry(Vector[j][i],i)
#qc.ry(Vector[i],i)
circuit.measure(range(4), range(4))
circuit.draw('mpl')
backend_sim = Aer.get_backend('qasm_simulator')
job_sim = backend_sim.run(circuit, shots=1024)
result_sim = job_sim.result()
counts = result_sim.get_counts()
counts
|
https://github.com/AsishMandoi/VRP-explorations
|
AsishMandoi
|
import pandas as pd
with open('Results/sol9_2.log', 'r') as file:
data = file.read()
rows_list = []
for dline in data.split('\n\n'):
if dline.startswith('n = '):
lines=dline.split('\n')
for line in lines:
if line.startswith('n = '):
words=line.split(', ')
for word in words:
if word.startswith('n = '):
n=int(word.strip('n = '))
if word.startswith('m = '):
k=int(word.strip('m = '))
if word.startswith('instance = '):
instance=word.strip('instance = ')
if line.startswith('Classical cost from best known solution: '):
classical_cost=f"{float(line.strip('Classical cost from best known solution: ')):.5f}"
if line.startswith('RAS: '):
words=line.split(' \t ')
for word in words:
if word.startswith('quantum cost = '):
ras_quantum_cost=f"{float(word.strip('quantum cost = ')):.5f}" if word.strip('quantum cost = ') != 'None' else None
if word.startswith('approximation ratio = '):
ras_approximation_ratio=f"{float(word.strip('approximation ratio = ')):.5f}" if word.strip('approximation ratio = ') != 'None' else None
if word.startswith('number of variables = '):
ras_no_of_variables=int(word.strip('number of variables = '))
if word.startswith('runtime = '):
ras_runtime=f"{float(word.strip('runtime = ')):.5f}"
if line.startswith('FQS: '):
words=line.split(' \t ')
for word in words:
if word.startswith('quantum cost = '):
fqs_quantum_cost=f"{float(word.strip('quantum cost = ')):.5f}" if word.strip('quantum cost = ') != 'None' else None
if word.startswith('approximation ratio = '):
fqs_approximation_ratio=f"{float(word.strip('approximation ratio = ')):.5f}" if word.strip('approximation ratio = ') != 'None' else None
if word.startswith('number of variables = '):
fqs_no_of_variables=int(word.strip('number of variables = '))
if word.startswith('runtime = '):
fqs_runtime=f"{float(word.strip('runtime = ')):.5f}"
if line.startswith('GPS: '):
words=line.split(' \t ')
for word in words:
if word.startswith('quantum cost = '):
gps_quantum_cost=f"{float(word.strip('quantum cost = ')):.5f}" if word.strip('quantum cost = ') != 'None' else None
if word.startswith('approximation ratio = '):
gps_approximation_ratio=f"{float(word.strip('approximation ratio = ')):.5f}" if word.strip('approximation ratio = ') != 'None' else None
if word.startswith('number of variables = '):
gps_no_of_variables=int(word.strip('number of variables = '))
if word.startswith('runtime = '):
gps_runtime=f"{float(word.strip('runtime = ')):.5f}"
rows_list.append({'n': n, 'k': k, 'instance': instance, 'Classical Cost': classical_cost, 'RAS: Quantum Cost': ras_quantum_cost, 'RAS: Approximation Ratio': ras_approximation_ratio, 'RAS: No. of Variables': ras_no_of_variables, 'RAS: Runtime': ras_runtime, 'FQS: Quantum Cost': fqs_quantum_cost, 'FQS: Approximation Ratio': fqs_approximation_ratio, 'FQS: No. of Variables': fqs_no_of_variables, 'FQS: Runtime': fqs_runtime, 'GPS: Quantum Cost': gps_quantum_cost, 'GPS: Approximation Ratio': gps_approximation_ratio, 'GPS: No. of Variables': gps_no_of_variables, 'GPS: Runtime': gps_runtime})
df = pd.DataFrame(rows_list)
df.sort_values(by=['n', 'k', 'instance'], inplace=True)
df.head()
df.to_csv('Results/sol9_2.csv', index=False)
|
https://github.com/AsishMandoi/VRP-explorations
|
AsishMandoi
|
from utils import random_routing_instance
from TSP.classical.gps import GPS as GPSc
from TSP.quantum.gps import GPS as GPSq
from TSP.quantum.fqs import FQS as FQSq
n=8
cost, xc, yc = random_routing_instance(n, seed=0)
GPSc(n, cost, xc, yc)
fqs = FQSq(n, cost, xc, yc)
res = fqs.solve()
fqs.visualize()
gps = GPSq(n, cost, xc, yc)
res = gps.solve()
gps.visualize()
|
https://github.com/AsishMandoi/VRP-explorations
|
AsishMandoi
|
import numpy as np
class Initializer:
def __init__(self, n, a, b):
self.n = n
self.a = a
self.b = b
def generate_nodes_and_weight_matrix(self):
n = self.n
a = self.a
b = self.b
np.random.seed(100*a + b)
x = (np.random.rand(n) - 0.5) * 50
y = (np.random.rand(n) - 0.5) * 50
weight_matrix = np.zeros([n, n])
for i in range(n):
for j in range(i+1, n):
weight_matrix[i, j] = (x[i] - x[j]) ** 2 + (y[i] - y[j]) ** 2
weight_matrix[j, i] = weight_matrix[i, j]
return x, y, weight_matrix
from utils import VRPSolver, compare_solvers, random_routing_instance
n=10 # number of clients
m=3 # number of vehicles
initializer = Initializer(n+1, n+1, 3)
xc, yc, cost = initializer.generate_nodes_and_weight_matrix()
### Select the type of model to solve VRP
# 1: Constrained Quadratic Model - A new model released by D-Wave Systems capable of encoding Quadratically Constrained Quadratic Programs (QCQPs)
# 2: Binary Quadratic Model - A model that encodes Ising or QUBO problems
model = 'CQM'
### The time limit (in seconds) for the solvers to run on the `LeapHybridCQMSampler` backend
time_limit = 25
### Select solver
# 1: RAS (Route Activation Solver)
# 2: FQS (Full QUBO Solver)
# 3: GPS (Guillermo, Parfait, Saúl) (only using CQM)
# 4: DBSCANS (Density-Based Spatial Clustering of Applications with Noise - Solver)
# 5: SPS (Solution Partition Solver)
solver = 'fqs'
vrps = VRPSolver(n, m, cost, xc, yc, model=model, solver=solver, time_limit=time_limit)
vrps.solve_vrp()
vrps.plot_solution()
# Number of iterations to get the average approximation ratio for a particular solver
# Warning! More iterations will take more time and resources to run
n_iter = 1
comparison_table = compare_solvers(n, m, cost, xc, yc, n_iter=n_iter, time_limit=time_limit)
print('Minimum cost of best known solution:', comparison_table[0]['exact_min_cost'])
for solver_id in comparison_table[1]:
print(f'{solver_id}:', '\t', f'average min cost = {comparison_table[1][solver_id]["avg_min_cost"]}',
'\t', f'average runtime = {comparison_table[1][solver_id]["avg_runtime"]}',
'\t', f'number of variables = {comparison_table[1][solver_id]["num_vars"]}',
'\t', f'approximation ratio = {comparison_table[1][solver_id]["approximation_ratio"]}'
)
|
https://github.com/AsishMandoi/VRP-explorations
|
AsishMandoi
|
import numpy as np
from utils import compare_solvers
class Initializer:
def __init__(self, n, a, b):
self.n = n
self.a = a
self.b = b
def generate_nodes_and_weight_matrix(self):
n = self.n
a = self.a
b = self.b
np.random.seed(100*a + b)
x = (np.random.rand(n) - 0.5) * 50
y = (np.random.rand(n) - 0.5) * 50
weight_matrix = np.zeros([n, n])
for i in range(n):
for j in range(i+1, n):
weight_matrix[i, j] = (x[i] - x[j]) ** 2 + (y[i] - y[j]) ** 2
weight_matrix[j, i] = weight_matrix[i, j]
return x, y, weight_matrix
### Select the type of model to solve VRP
# 1: Constrained Quadratic Model - A new model released by D-Wave Systems capable of encoding Quadratically Constrained Quadratic Programs (QCQPs)
# 2: Binary Quadratic Model - A model that encodes Ising or QUBO problems
model = 'CQM'
### The time limit (in seconds) for the solvers to run on the `LeapHybridCQMSampler` backend
time_limit = 5
### Select solver
# 1: RAS (Route Activation Solver)
# 2: FQS (Full QUBO Solver)
# 3: GPS (Guillermo, Parfait, Saúl) (only using CQM)
# 4: DBSCANS (Density-Based Spatial Clustering of Applications with Noise - Solver)
# 5: SPS (Solution Partition Solver)
solver = 'ras'
# Number of iterations to get the average approximation ratio for a particular solver
# Warning! More iterations will take more time and resources to run
n_iter = 1
for n in range(10, 13): ### Here, (2, 6) could be replaced with the some other range of no. of locations you want.
for instance in range(4): ### Here, (10) could be replaced with some other number of instcnces you want to generate for a particular no. of locations.
initializer = Initializer(n, n, instance)
xc, yc, cost = initializer.generate_nodes_and_weight_matrix()
for m in range(1, n):
comparison_table = compare_solvers(n-1, m, cost, xc, yc, n_iter=n_iter, time_limit=time_limit)
print(f'\nn = {n}, m = {m}, instance = {instance}')
print('Classical cost from best known solution:', comparison_table[0]['exact_min_cost'])
for solver_id in comparison_table[1]:
print(f'{solver_id}:', '\t', f'quantum cost = {comparison_table[1][solver_id]["avg_min_cost"]}',
'\t', f'runtime = {comparison_table[1][solver_id]["avg_runtime"]}',
'\t', f'number of variables = {comparison_table[1][solver_id]["num_vars"]}',
'\t', f'approximation ratio = {comparison_table[1][solver_id]["approximation_ratio"]}'
)
# for n in range(2, 6): ### Here, (2, 6) could be replaced with the some other range of no. of locations you want.
# for instance in range(10): ### Here, (10) could be replaced with some other number of instcnces you want to generate for a particular no. of locations.
# initializer = Initializer(n, n, instance)
# xc, yc, cost = initializer.generate_nodes_and_weight_matrix()
# for m in range(1, n):
# comparison_table = compare_solvers(n-1, m, cost, xc, yc, n_iter=n_iter, time_limit=time_limit)
# print(f'n = {n}, m = {m}, instance = {instance}')
# print('Classical cost from best known solution:', comparison_table[0]['exact_min_cost'])
# for solver_id in comparison_table[1]:
# print(f'{solver_id}:', '\t', f'quantum cost = {comparison_table[1][solver_id]["avg_min_cost"]}',
# '\t', f'runtime = {comparison_table[1][solver_id]["avg_runtime"]}',
# '\t', f'number of variables = {comparison_table[1][solver_id]["num_vars"]}',
# '\t', f'approximation ratio = {comparison_table[1][solver_id]["approximation_ratio"]}'
# )
|
https://github.com/AsishMandoi/VRP-explorations
|
AsishMandoi
|
import numpy as np
import pandas as pd
class Initializer:
def __init__(self, n, a, b):
self.n = n
self.a = a
self.b = b
def generate_nodes_and_weight_matrix(self):
n = self.n
a = self.a
b = self.b
np.random.seed(100*a + b)
x = (np.random.rand(n) - 0.5) * 50
y = (np.random.rand(n) - 0.5) * 50
weight_matrix = np.zeros([n, n])
for i in range(n):
for j in range(i+1, n):
weight_matrix[i, j] = (x[i] - x[j]) ** 2 + (y[i] - y[j]) ** 2
weight_matrix[j, i] = weight_matrix[i, j]
return x, y, weight_matrix
for i in range(2,16): ### Here, (2,16) could be replaced with the some other range of no. of locations you want.
for j in range(10): ### Here, (10) could be replaced with some other number of instcnces you want to generate for a particular no. of locations.
initializer = Initializer(i, i, j)
x,y,weight_matrix = initializer.generate_nodes_and_weight_matrix()
df_x = pd.DataFrame(x)
df_y = pd.DataFrame(y)
df_wm = pd.DataFrame(weight_matrix)
with open ("dataset.csv", 'a') as f:
df = pd.concat([df_x, df_y, df_wm], keys = ["x_" + str(i) + '_' + str(j), "y_" + str(i) + '_' + str(j), "wm_" + str(i) + '_' + str(j)])
df.to_csv(f)
|
https://github.com/AsishMandoi/VRP-explorations
|
AsishMandoi
|
import time
from dwave_qbsolv.dimod_wrapper import QBSolv
import hybrid
import dwave.inspector
from greedy import SteepestDescentSolver
from dwave.system import LeapHybridSampler, DWaveSampler, EmbeddingComposite
from neal import SimulatedAnnealingSampler
from qiskit_optimization.algorithms import MinimumEigenOptimizer
from qiskit.algorithms import QAOA, NumPyMinimumEigensolver
from qiskit import Aer
class SolverBackend:
"""Class containing all backend solvers that may be used to solve the Vehicle Routing Problem."""
def __init__(self, vrp):
"""Initializes required variables and stores the supplied instance of the VehicleRouter object."""
# Store relevant data
self.vrp = vrp
# Solver dictionary
self.solvers = {'dwave': self.solve_dwave,
'leap': self.solve_leap,
'hybrid': self.solve_hybrid,
'neal': self.solve_neal,
'qbsolv': self.solve_qbsolv,
'qaoa': self.solve_qaoa,
'npme': self.solve_npme}
# Initialize necessary variables
self.dwave_result = None
self.result_dict = None
self.solver_limit = 4
def solve(self, solver, **params):
"""Takes the solver as input and redirects control to the corresponding solver.
Args:
solver: The selected solver.
params: Parameters to send to the selected backend solver..
"""
# Select solver and solve
solver = self.solvers[solver]
solver(**params)
def solve_dwave(self, **params):
"""Solve using DWaveSampler and EmbeddingComposite.
Args:
params: inspect: Defaults to False. Set to True to run D-Wave inspector for the sampled solution.
params: post_process: Defaults to False. Set to True to run classical post processing for improving the
D-Wave solution.
"""
# Resolve parameters
params['solver'] = 'dwave'
inspect = params.setdefault('inspect', False)
post_process = params.setdefault('post_process', False)
# Solve
sampler = EmbeddingComposite(DWaveSampler())
result = sampler.sample(self.vrp.bqm, num_reads=self.vrp.num_reads, chain_strength=self.vrp.chain_strength)
# Post process
if not post_process:
self.vrp.result = result
else:
post_processor = SteepestDescentSolver()
self.vrp.result = post_processor.sample(self.vrp.bqm, num_reads=self.vrp.num_reads, initial_states=result)
# Extract solution
self.vrp.timing.update(result.info["timing"])
self.result_dict = self.vrp.result.first.sample
self.vrp.extract_solution(self.result_dict)
# Inspection
self.dwave_result = result
if inspect:
dwave.inspector.show(result)
def solve_hybrid(self, **params):
"""Solve using dwave-hybrid.
Args:
params: Additional parameters that may be required by a solver. Not required here.
"""
# Resolve parameters
params['solver'] = 'hybrid'
# Build sampler workflow
workflow = hybrid.Loop(
hybrid.RacingBranches(
hybrid.InterruptableTabuSampler(),
hybrid.EnergyImpactDecomposer(size=30, rolling=True, rolling_history=0.75)
| hybrid.QPUSubproblemAutoEmbeddingSampler()
| hybrid.SplatComposer()) | hybrid.ArgMin(), convergence=3)
# Solve
sampler = hybrid.HybridSampler(workflow)
self.vrp.result = sampler.sample(self.vrp.bqm, num_reads=self.vrp.num_reads,
chain_strength=self.vrp.chain_strength)
# Extract solution
self.result_dict = self.vrp.result.first.sample
self.vrp.extract_solution(self.result_dict)
def solve_leap(self, **params):
"""Solve using Leap Hybrid Sampler.
Args:
params: Additional parameters that may be required by a solver. Not required here.
"""
# Resolve parameters
params['solver'] = 'leap'
# Solve
sampler = LeapHybridSampler()
self.vrp.result = sampler.sample(self.vrp.bqm)
# Extract solution
self.vrp.timing.update(self.vrp.result.info)
self.result_dict = self.vrp.result.first.sample
self.vrp.extract_solution(self.result_dict)
def solve_neal(self, **params):
"""Solve using Simulated Annealing Sampler.
Args:
params: Additional parameters that may be required by a solver. Not required here.
"""
# Resolve parameters
params['solver'] = 'neal'
# Solve
sampler = SimulatedAnnealingSampler()
self.vrp.result = sampler.sample(self.vrp.bqm)
# Extract solution
self.vrp.timing.update(self.vrp.result.info)
self.result_dict = self.vrp.result.first.sample
self.vrp.extract_solution(self.result_dict)
def solve_qbsolv(self, **params):
"""Solve using Simulated Annealing Sampler.
Args:
params: Additional parameters that may be required by a solver. Not required here.
"""
# Resolve parameters
params['solver'] = 'qbsolv'
# Solve
self.vrp.result = QBSolv().sample(self.vrp.bqm, solver_limit=self.solver_limit)
# Extract solution
self.vrp.timing.update(self.vrp.result.info)
self.result_dict = self.vrp.result.first.sample
self.vrp.extract_solution(self.result_dict)
def solve_qaoa(self, **params):
"""Solve using qiskit Minimum Eigen Optimizer based on a QAOA backend.
Args:
params: Additional parameters that may be required by a solver. Not required here.
"""
# Resolve parameters
params['solver'] = 'qaoa'
self.vrp.clock = time.time()
# Build optimizer and solve
solver = QAOA(quantum_instance=Aer.get_backend('qasm_simulator'))
optimizer = MinimumEigenOptimizer(min_eigen_solver=solver)
self.vrp.result = optimizer.solve(self.vrp.qp)
self.vrp.timing['qaoa_solution_time'] = (time.time() - self.vrp.clock) * 1e6
# Build result dictionary
self.result_dict = {self.vrp.result.variable_names[i]: self.vrp.result.x[i]
for i in range(len(self.vrp.result.variable_names))}
# Extract solution
self.vrp.extract_solution(self.result_dict)
def solve_npme(self, **params):
"""Solve using qiskit Minimum Eigen Optimizer based on NumPyMinimumEigensolver().
Args:
params: Additional parameters that may be required by a solver. Not required here.
"""
# Resolve parameters
params['solver'] = 'npme'
self.vrp.clock = time.time()
# Build optimizer and solve
solver = NumPyMinimumEigensolver()
optimizer = MinimumEigenOptimizer(min_eigen_solver=solver)
self.vrp.result = optimizer.solve(self.vrp.qp)
self.vrp.timing['npme_solution_time'] = (time.time() - self.vrp.clock) * 1e6
# Build result dictionary
self.result_dict = {self.vrp.result.variable_names[i]: self.vrp.result.x[i]
for i in range(len(self.vrp.result.variable_names))}
# Extract solution
self.vrp.extract_solution(self.result_dict)
|
https://github.com/AsishMandoi/VRP-explorations
|
AsishMandoi
|
import numpy as np
import utility
from full_qubo_solver import FullQuboSolver
from average_partition_solver import AveragePartitionSolver
from qiskit_native_solver import QiskitNativeSolver
from route_activation_solver import RouteActivationSolver
from clustered_tsp_solver import ClusteredTspSolver
from solution_partition_solver import SolutionPartitionSolver
n = 5
m = 2
seed = 1543
instance, xc, yc = utility.generate_vrp_instance(n, seed)
fqs = FullQuboSolver(n, m, instance)
fqs.solve(solver='leap')
fqs.visualize(xc, yc)
aps = AveragePartitionSolver(n, m, instance)
aps.solve(solver='leap')
aps.visualize(xc, yc)
ras = RouteActivationSolver(n, m, instance)
ras.solve(solver='leap')
ras.visualize(xc, yc)
qns = QiskitNativeSolver(n, m, instance)
qns.solve(solver='leap')
qns.visualize(xc, yc)
cts = ClusteredTspSolver(n, m, instance)
cts.solve(solver='leap')
cts.visualize(xc, yc)
sps = SolutionPartitionSolver(n, m, instance)
sps.solve(solver='leap')
sps.visualize(xc, yc)
vrp_list = [fqs, aps, ras, qns, cts, sps]
solver_types = ['FQS', 'APS', 'RAS', 'QNS', 'CTS', 'SPS']
for i, vrp in enumerate(vrp_list):
print(f'{solver_types[i]} - Optimized Cost: {vrp.evaluate_vrp_cost()}')
qubo_time = [vrp.timing['qubo_build_time'] for vrp in vrp_list]
for i in range(len(vrp_list)):
print(f'{solver_types[i]} - Classical QUBO Build Time: {qubo_time[i]} us')
qpu_time = [vrp.timing['qpu_access_time'] for vrp in vrp_list]
qpu_time[4] += cts.timing['clustering_time']['qpu_access_time']
for i in range(len(vrp_list)):
print(f'{solver_types[i]} - QPU Access Time: {qpu_time[i]} us')
from solution_partition_solver import CapcSolutionPartitionSolver
cap = 10
dem = [1, 2, 3, 4, 5]
sps = CapcSolutionPartitionSolver(n, m, instance, cap, dem)
sps.solve(solver='leap')
sps.visualize(xc, yc)
|
https://github.com/AsishMandoi/VRP-explorations
|
AsishMandoi
|
import utility
%config InlineBackend.figure_format = 'svg'
from full_qubo_solver import FullQuboSolver as FQS
from average_partition_solver import AveragePartitionSolver as APS
from qiskit_native_solver import QiskitNativeSolver as QNS
from route_activation_solver import RouteActivationSolver as RAS
from solution_partition_solver import SolutionPartitionSolver as SPS
from dbscan_solver import DBSCANSolver as DBSCANS
from clustered_tsp_solver import ClusteredTspSolver as CTS
n = 5
m = 2
seed = 891
instance, xc, yc = utility.generate_vrp_instance(n, seed)
sps = FQS(n, m, instance)
sps.solve(solver='neal')
sps.visualize(xc, yc)
|
https://github.com/MonitSharma/qiskit-projects
|
MonitSharma
|
#imports
import qiskit
import numpy as np
from qiskit.visualization import plot_histogram
# model
class Model:
simulator = qiskit.Aer.get_backend('qasm_simulator')
def draw_current_circuit(self):
print(self.add_circuit.draw())
# initialize 2 qubits
def __init__(self):
# TODO initialize with more friendly state vectors?
self.circuit = qiskit.QuantumCircuit(2, 2)
self.state1 = self.circuit.initialize(qiskit.quantum_info.random_statevector(2).data, 0)
self.state2 = self.circuit.initialize(qiskit.quantum_info.random_statevector(2).data, 1)
self.add_circuit = qiskit.QuantumCircuit(2)
# Measure qubits and return state with max probability: ex. [0,1]
def measureState(self):
self.circuit.measure([0, 1], [1, 0])
job = qiskit.execute(self.circuit, self.simulator, shots=1) # 1 shot to keep it luck dependent?
result = job.result()
count = result.get_counts()
# max_value = max(result.values())
# return [k for k,v in count.items() if v==1][0]
return [int(list(count)[0][0]), int(list(count)[0][1])]
# Return a probability coefficient of specific state
# state is an array of size 2 which contains 0 or 1
# such as [0,1], [0,0], [1,0], [1,1]
def getProbabilityOf(self, state):
# to get state vector of qubit
backend = qiskit.Aer.get_backend('statevector_simulator')
result = qiskit.execute(self.circuit, backend).result()
out_state = result.get_statevector()
if state == [0, 0]:
return out_state[0]
elif state == [0, 1]:
return out_state[1]
elif state == [1, 0]:
return out_state[2]
else:
return out_state[3]
# Add a gate to the end of the circuit (at specified qubit)
def add_unitary(self, name, qubit_no):
if name == "H" or name == "h":
self.add_circuit.h(qubit_no)
elif name == "X" or name == "x":
self.add_circuit.x(qubit_no)
elif name == "Y" or name == "y":
self.add_circuit.y(qubit_no)
elif name == "Z" or name == "z":
self.add_circuit.z(qubit_no)
self.circuit += self.add_circuit
def add_r_gate(self, parameter, qubit_no):
self.add_circuit.rz(parameter, qubit_no)
self.circuit += self.add_circuit
def add_cnot(self, control_qubit_no, target_qubit_no):
self.add_circuit.cx(control_qubit_no, target_qubit_no)
self.circuit += self.add_circuit
|
https://github.com/MonitSharma/qiskit-projects
|
MonitSharma
|
import numpy as np
import random
import matplotlib.pyplot as plt
from sklearn.neighbors import KNeighborsClassifier
from sklearn.neighbors import NearestCentroid
from IPython.display import clear_output
import pandas as pd
# =======================================================
import math
import time
from qiskit import Aer, QuantumCircuit, execute
from qiskit.extensions import UnitaryGate
from qiskit.providers.jobstatus import JobStatus
import cv2
# Use Aer's qasm_simulator by default
backend = Aer.get_backend('qasm_simulator')
# generate chess board data: random 8 x 8 board
def generate_chess():
'''
Generates a random board of dimensions 8 x 8
Outputs:
board := flattened 8 x 8 array
winner := red wins == 1, blue wins == -1
sum_red := sum of red pieces
sum_blue := sum of blue pieces
'''
board=np.zeros((8*8))
board_label=np.zeros((8*8)).astype(object)
# Assign chess piece point values, names, max pieces per board
# dictionary key: {'name':[points, max_pieces]}
piece_list_w=['pawn_w','knight_w','bishop_w','rook_w','queen_w','king_w']
piece_list_b=['pawn_b','knight_b','bishop_b','rook_b','queen_b','king_b']
chess_values_w = {'pawn_w':[1,8],'knight_w':[3,2],'bishop_w':[3,2],'rook_w':[5,2],'queen_w':[9,1],'king_w':[40,1]}
chess_values_b = {'pawn_b':[1,8],'knight_b':[3,2],'bishop_b':[3,2],'rook_b':[5,2],'queen_b':[9,1],'king_b':[40,1]}
# generate random number of chess pieces with bounds for white and black (there must be at least a king for each side)
piece_locations_white=np.zeros((len(piece_list_w),3)).astype(object)
piece_locations_black=np.zeros((len(piece_list_b),3)).astype(object)
piece_locations_white[0]=['king_w',chess_values_w['king_w'][0],chess_values_w['king_w'][1]]
piece_locations_black[0]=['king_b',chess_values_b['king_b'][0],chess_values_b['king_b'][1]]
for n in range(len(piece_list_w)-1): # skip king because there must be a king
points_w,max_pieces_w=chess_values_w[piece_list_w[n]]
points_b,max_pieces_b=chess_values_b[piece_list_b[n]]
piece_locations_white[n+1,:]=[piece_list_w[n],points_w,random.sample(range(0,max_pieces_w+1),1)[0]]
piece_locations_black[n+1,:]=[piece_list_b[n],points_b,random.sample(range(0,max_pieces_b+1),1)[0]]
black_pieces=int(np.sum(piece_locations_black[:,2])) # count black pieces
white_pieces=int(np.sum(piece_locations_white[:,2])) # count white pieces
total_pieces=black_pieces+white_pieces # total number of pieces on the board
all_piece_locations=random.sample(range(0,8*8),total_pieces)
index=0
for n in range(len(piece_list_b)): # black piece location assignment
for p in range(piece_locations_black[n,2]):
board[all_piece_locations[index]]= piece_locations_black[n,1] # populate with piece value
board_label[all_piece_locations[index]]= piece_locations_black[n,0] # populate with piece name
index+=1
for n in range(len(piece_list_w)): # white piece location assignment
for p in range(piece_locations_white[n,2]):
board[all_piece_locations[index]]= -piece_locations_white[n,1] # populate with piece value
board_label[all_piece_locations[index]]= piece_locations_white[n,0] # populate with piece name
index+=1
sum_black=np.sum(piece_locations_black[:,1]*piece_locations_black[:,2])
sum_white=np.sum(piece_locations_white[:,1]*piece_locations_white[:,2])
return board, board_label, sum_black, sum_white
def chessBoardShow(chessBoard):
chessBoard = chessBoard.reshape(8, 8)
filepath='meta/chess/B.Knight.png'
kb=cv2.imread(filepath,cv2.IMREAD_UNCHANGED)
filepath='meta/chess/B.Bish.png'
bb=cv2.imread(filepath,cv2.IMREAD_UNCHANGED)
filepath='meta/chess/B.Quee.png'
qb=cv2.imread(filepath,cv2.IMREAD_UNCHANGED)
filepath='meta/chess/B.Rook.png'
rb=cv2.imread(filepath,cv2.IMREAD_UNCHANGED)
filepath='meta/chess/B.Pawn.png'
pb=cv2.imread(filepath,cv2.IMREAD_UNCHANGED)
filepath='meta/chess/B.King.png'
kib=cv2.imread(filepath,cv2.IMREAD_UNCHANGED)
filepath='meta/chess/W.Knight.png'
kw=cv2.imread(filepath,cv2.IMREAD_UNCHANGED)
filepath='meta/chess/W.Bish.png'
bw=cv2.imread(filepath,cv2.IMREAD_UNCHANGED)
filepath='meta/chess/W.Quee.png'
qw=cv2.imread(filepath,cv2.IMREAD_UNCHANGED)
filepath='meta/chess/W.Rook.png'
rw=cv2.imread(filepath,cv2.IMREAD_UNCHANGED)
filepath='meta/chess/W.Pawn.png'
pw=cv2.imread(filepath,cv2.IMREAD_UNCHANGED)
filepath='meta/chess/W.King.png'
kiw=cv2.imread(filepath,cv2.IMREAD_UNCHANGED)
filepath='meta/chess/trans.png'
trans=cv2.imread(filepath,cv2.IMREAD_UNCHANGED)
chessPiece = {
"knight_b":kb,
"bishop_b": bb,
"queen_b": qb,
"rook_b": rb,
"pawn_b": pb,
"king_b": kib,
"knight_w": kw,
"bishop_w": bw,
"queen_w": qw,
"rook_w": rw,
"pawn_w": pw,
"king_w": kiw,
0.0: trans
}
import warnings
warnings.filterwarnings("ignore", category=DeprecationWarning)
def pictureSelect(n,m):
try:
dictPiece = chessPiece[chessBoard[n][m]]
if dictPiece != trans:
ax[n,m].imshow(dictPiece,cmap='bone')
except (Exception):
pass
fig,ax=plt.subplots(figsize=(8,1))
ax.set_facecolor('grey')
ax.set_xticks([])
ax.set_yticks([])
ax.text(0.2,0.2,'Black Side',fontsize=45,c='w')
plt.show()
fig,ax=plt.subplots(ncols=8,nrows=8,figsize=(8,8))
for n in range(8):
for m in range(8):
count = 0
if (m % 2 != 0):
count += 1
if ((n % 2) == 0):
count += 1
if count == 2:
ax[n,m].set_facecolor('grey')
count = 0
if (m % 2 == 0):
count += 1
if ((n % 2) != 0):
count += 1
if count == 2:
ax[n,m].set_facecolor('grey')
ax[n,m].set_xticks([])
ax[n,m].set_yticks([])
pictureSelect(n,m)
fig,ax=plt.subplots(figsize=(8,1))
ax.set_facecolor('white')
ax.set_xticks([])
ax.set_yticks([])
ax.text(0.2,0.2,'White Side',fontsize=45,c='k')
plt.show()
def generate_best_move():
# create a board and make sure kings are at least 11 spaces away from each other
board, board_label, sum_black, sum_white=generate_chess() # generate board
king_b=np.where(board_label=='king_b')[0][0]
king_w=np.where(board_label=='king_w')[0][0]
while np.abs(king_b-king_w) < 11:
board, board_label, sum_black, sum_white=generate_chess()
king_b=np.where(board_label=='king_b')[0][0]
king_w=np.where(board_label=='king_w')[0][0]
board_label_sq=board_label.reshape(8,8)
# Assign chess piece point values, names, max pieces per board
# dictionary key: {'name':[points, max_pieces]}
piece_list_w=np.array(['pawn_w','knight_w','bishop_w','rook_w','queen_w','king_w'])
piece_list_b=np.array(['pawn_b','knight_b','bishop_b','rook_b','queen_b','king_b'])
chess_values_w = {'pawn_w':[1,8],'knight_w':[3,2],'bishop_w':[3,2],'rook_w':[5,2],'queen_w':[9,1],'king_w':[40,1]}
chess_values_b = {'pawn_b':[1,8],'knight_b':[3,2],'bishop_b':[3,2],'rook_b':[5,2],'queen_b':[9,1],'king_b':[40,1]}
# white starts on the bottom for our board
white_scores=[]
black_scores=[]
# we have to iterate on every piece to see what the best legal move is that gets the highest point value
for n in range(8): # rows
for m in range(8): # columns
# =========================================
if board_label_sq[n,m]=='pawn_w': # white pawn
take1 = 0.0
take2 = 0.0
take3 = 0.0
take4 = 0.0
pawn_w_take=[0]
if m==0 and n>0:
take1 = board_label_sq[n-1,m+1] # col 0, row +1
elif 7>m>0 and n>0:
take2 = board_label_sq[n-1,m+1] # col 0-6, row +1
take3 = board_label_sq[n-1,m-1] # col 0-6, row -1
elif m==7 and n>0:
take4 = board_label_sq[n-1,m-1] # col 7, row -1
if take1!=0 and np.sum(take1==piece_list_b)>0:
pawn_w_take.append(chess_values_b[take1][0])
if take2!=0 and np.sum(take2==piece_list_b)>0:
pawn_w_take.append(chess_values_b[take2][0])
if take3!=0 and np.sum(take3==piece_list_b)>0:
pawn_w_take.append(chess_values_b[take3][0])
if take4!=0 and np.sum(take4==piece_list_b)>0:
pawn_w_take.append(chess_values_b[take4][0])
else:
pass
white_scores.append(np.max(pawn_w_take))
# =========================================
elif board_label_sq[n,m]=='pawn_b': # black pawn
take1 = 0.0
take2 = 0.0
take3 = 0.0
take4 = 0.0
pawn_b_take=[0]
if m==0 and n<7:
take1 = board_label_sq[n+1,m+1] # col 0, row +1
elif 7>m>0 and n<7:
take2 = board_label_sq[n+1,m+1] # col 0-6, row +1
take3 = board_label_sq[n+1,m-1] # col 0-6, row -1
elif m==7 and n<7:
take4 = board_label_sq[n+1,m-1] # col 7, row -1
if take1!=0 and np.sum(take1==piece_list_w)>0:
pawn_b_take.append(chess_values_w[take1][0])
if take2!=0 and np.sum(take2==piece_list_w)>0:
pawn_b_take.append(chess_values_w[take2][0])
if take3!=0 and np.sum(take3==piece_list_w)>0:
pawn_b_take.append(chess_values_w[take3][0])
if take4!=0 and np.sum(take4==piece_list_w)>0:
pawn_b_take.append(chess_values_w[take4][0])
else:
pass
black_scores.append(np.max(pawn_b_take))
# =========================================
elif board_label_sq[n,m]=='bishop_w': # white bishop
take1=0.0
take2=0.0
take3=0.0
take4=0.0
bishop_w_take=[0]
for bishw in range(7):
if n+bishw<7 and m+bishw<7:
take1 = board_label_sq[n+bishw+1,m+bishw+1] # col +1, row +1
if take1!=0:
break
for bishw in range(7):
if n+bishw<7 and m-bishw>0:
take2 = board_label_sq[n+bishw+1,m-bishw-1] # col -1, row +1
if take2!=0:
break
for bishw in range(7):
if n-bishw>0 and m+bishw<7:
take3 = board_label_sq[n-bishw-1,m+bishw+1] # col +1, row -1
if take3!=0:
break
for bishw in range(7):
if n-bishw>0 and m-bishw>0:
take4 = board_label_sq[n-bishw-1,m-bishw-1] # col -1, row -1
if take4!=0:
break
if take1!=0 and np.sum(take1==piece_list_b)>0:
bishop_w_take.append(chess_values_b[take1][0])
if take2!=0 and np.sum(take2==piece_list_b)>0:
bishop_w_take.append(chess_values_b[take2][0])
if take3!=0 and np.sum(take3==piece_list_b)>0:
bishop_w_take.append(chess_values_b[take3][0])
if take4!=0 and np.sum(take4==piece_list_b)>0:
bishop_w_take.append(chess_values_b[take4][0])
else:
pass
white_scores.append(np.max(bishop_w_take))
# =========================================
elif board_label_sq[n,m]=='bishop_b': # black bishop
take1=0.0
take2=0.0
take3=0.0
take4=0.0
bishop_b_take=[0]
for bishw in range(7):
if n+bishw<7 and m+bishw<7:
take1 = board_label_sq[n+bishw+1,m+bishw+1] # col +1, row +1
if take1!=0:
break
for bishw in range(7):
if n+bishw<7 and m-bishw>0:
take2 = board_label_sq[n+bishw+1,m-bishw-1] # col -1, row +1
if take2!=0:
break
for bishw in range(7):
if n-bishw>0 and m+bishw<7:
take3 = board_label_sq[n-bishw-1,m+bishw+1] # col +1, row -1
if take3!=0:
break
for bishw in range(7):
if n-bishw>0 and m-bishw>0:
take4 = board_label_sq[n-bishw-1,m-bishw-1] # col -1, row -1
if take4!=0:
break
if take1!=0 and np.sum(take1==piece_list_w)>0:
bishop_b_take.append(chess_values_w[take1][0])
if take2!=0 and np.sum(take2==piece_list_w)>0:
bishop_b_take.append(chess_values_w[take2][0])
if take3!=0 and np.sum(take3==piece_list_w)>0:
bishop_b_take.append(chess_values_w[take3][0])
if take4!=0 and np.sum(take4==piece_list_w)>0:
bishop_b_take.append(chess_values_w[take4][0])
else:
pass
black_scores.append(np.max(bishop_b_take))
# =========================================
elif board_label_sq[n,m]=='rook_w': # white rook
take1=0.0
take2=0.0
take3=0.0
take4=0.0
rook_w_take=[0]
for bishw in range(7):
if n+bishw<7:
take1 = board_label_sq[n+bishw+1,m] # col 0, row +1
if take1!=0:
break
for bishw in range(7):
if m-bishw>0:
take2 = board_label_sq[n,m-bishw-1] # col -1, row 0
if take2!=0:
break
for bishw in range(7):
if m+bishw<7:
take3 = board_label_sq[n,m+bishw+1] # col +1, row 0
if take3!=0:
break
for bishw in range(7):
if n-bishw>0:
take4 = board_label_sq[n-bishw-1,m] # col 0, row -1
if take4!=0:
break
if take1!=0 and np.sum(take1==piece_list_b)>0:
rook_w_take.append(chess_values_b[take1][0])
if take2!=0 and np.sum(take2==piece_list_b)>0:
rook_w_take.append(chess_values_b[take2][0])
if take3!=0 and np.sum(take3==piece_list_b)>0:
rook_w_take.append(chess_values_b[take3][0])
if take4!=0 and np.sum(take4==piece_list_b)>0:
rook_w_take.append(chess_values_b[take4][0])
else:
pass
white_scores.append(np.max(rook_w_take))
# =========================================
elif board_label_sq[n,m]=='rook_b': # black rook
take1=0.0
take2=0.0
take3=0.0
take4=0.0
rook_b_take=[0]
for bishw in range(7):
if n+bishw<7:
take1 = board_label_sq[n+bishw+1,m] # col 0, row +1
if take1!=0:
break
for bishw in range(7):
if m-bishw>0:
take2 = board_label_sq[n,m-bishw-1] # col -1, row 0
if take2!=0:
break
for bishw in range(7):
if m+bishw<7:
take3 = board_label_sq[n,m+bishw+1] # col +1, row 0
if take3!=0:
break
for bishw in range(7):
if n-bishw>0:
take4 = board_label_sq[n-bishw-1,m] # col 0, row -1
if take4!=0:
break
if take1!=0 and np.sum(take1==piece_list_w)>0:
rook_b_take.append(chess_values_w[take1][0])
if take2!=0 and np.sum(take2==piece_list_w)>0:
rook_b_take.append(chess_values_w[take2][0])
if take3!=0 and np.sum(take3==piece_list_w)>0:
rook_b_take.append(chess_values_w[take3][0])
if take4!=0 and np.sum(take4==piece_list_w)>0:
rook_b_take.append(chess_values_w[take4][0])
else:
pass
black_scores.append(np.max(rook_b_take))
# =========================================
elif board_label_sq[n,m]=='queen_w': # white queen
take1=0.0
take2=0.0
take3=0.0
take4=0.0
take5=0.0
take6=0.0
take7=0.0
take8=0.0
queen_w_take=[0]
for bishw in range(7):
if n+bishw<7:
take1 = board_label_sq[n+bishw+1,m] # col 0, row +1
if take1!=0:
break
for bishw in range(7):
if m-bishw>0:
take2 = board_label_sq[n,m-bishw-1] # col -1, row 0
if take2!=0:
break
for bishw in range(7):
if m+bishw<7:
take3 = board_label_sq[n,m+bishw+1] # col +1, row 0
if take3!=0:
break
for bishw in range(7):
if n-bishw>0:
take4 = board_label_sq[n-bishw-1,m] # col 0, row -1
if take4!=0:
break
for bishw in range(7):
if n+bishw<7 and m+bishw<7:
take5 = board_label_sq[n+bishw+1,m+bishw+1] # col +1, row +1
if take5!=0:
break
for bishw in range(7):
if n+bishw<7 and m-bishw>0:
take6 = board_label_sq[n+bishw+1,m-bishw-1] # col -1, row +1
if take6!=0:
break
for bishw in range(7):
if n-bishw>0 and m+bishw<7:
take7 = board_label_sq[n-bishw-1,m+bishw+1] # col +1, row -1
if take7!=0:
break
for bishw in range(7):
if n-bishw>0 and m-bishw>0:
take8 = board_label_sq[n-bishw-1,m-bishw-1] # col -1, row -1
if take8!=0:
break
if take1!=0 and np.sum(take1==piece_list_b)>0:
queen_w_take.append(chess_values_b[take1][0])
if take2!=0 and np.sum(take2==piece_list_b)>0:
queen_w_take.append(chess_values_b[take2][0])
if take3!=0 and np.sum(take3==piece_list_b)>0:
queen_w_take.append(chess_values_b[take3][0])
if take4!=0 and np.sum(take4==piece_list_b)>0:
queen_w_take.append(chess_values_b[take4][0])
if take5!=0 and np.sum(take5==piece_list_b)>0:
queen_w_take.append(chess_values_b[take5][0])
if take6!=0 and np.sum(take6==piece_list_b)>0:
queen_w_take.append(chess_values_b[take6][0])
if take7!=0 and np.sum(take7==piece_list_b)>0:
queen_w_take.append(chess_values_b[take7][0])
if take8!=0 and np.sum(take8==piece_list_b)>0:
queen_w_take.append(chess_values_b[take8][0])
else:
pass
white_scores.append(np.max(queen_w_take))
# =========================================
elif board_label_sq[n,m]=='queen_b': # black queen
take1=0.0
take2=0.0
take3=0.0
take4=0.0
take5=0.0
take6=0.0
take7=0.0
take8=0.0
queen_b_take=[0]
for bishw in range(7):
if n+bishw<7:
take1 = board_label_sq[n+bishw+1,m] # col 0, row +1
if take1!=0:
break
for bishw in range(7):
if m-bishw>0:
take2 = board_label_sq[n,m-bishw-1] # col -1, row 0
if take2!=0:
break
for bishw in range(7):
if m+bishw<7:
take3 = board_label_sq[n,m+bishw+1] # col +1, row 0
if take3!=0:
break
for bishw in range(7):
if n-bishw>0:
take4 = board_label_sq[n-bishw-1,m] # col 0, row -1
if take4!=0:
break
for bishw in range(7):
if n+bishw<7 and m+bishw<7:
take5 = board_label_sq[n+bishw+1,m+bishw+1] # col +1, row +1
if take5!=0:
break
for bishw in range(7):
if n+bishw<7 and m-bishw>0:
take6 = board_label_sq[n+bishw+1,m-bishw-1] # col -1, row +1
if take6!=0:
break
for bishw in range(7):
if n-bishw>0 and m+bishw<7:
take7 = board_label_sq[n-bishw-1,m+bishw+1] # col +1, row -1
if take7!=0:
break
for bishw in range(7):
if n-bishw>0 and m-bishw>0:
take8 = board_label_sq[n-bishw-1,m-bishw-1] # col -1, row -1
if take8!=0:
break
if take1!=0 and np.sum(take1==piece_list_w)>0:
queen_b_take.append(chess_values_w[take1][0])
if take2!=0 and np.sum(take2==piece_list_w)>0:
queen_b_take.append(chess_values_w[take2][0])
if take3!=0 and np.sum(take3==piece_list_w)>0:
queen_b_take.append(chess_values_w[take3][0])
if take4!=0 and np.sum(take4==piece_list_w)>0:
queen_b_take.append(chess_values_w[take4][0])
if take5!=0 and np.sum(take5==piece_list_w)>0:
queen_b_take.append(chess_values_w[take5][0])
if take6!=0 and np.sum(take6==piece_list_w)>0:
queen_b_take.append(chess_values_w[take6][0])
if take7!=0 and np.sum(take7==piece_list_w)>0:
queen_b_take.append(chess_values_w[take7][0])
if take8!=0 and np.sum(take8==piece_list_w)>0:
queen_b_take.append(chess_values_w[take8][0])
else:
pass
black_scores.append(np.max(queen_b_take))
# =========================================
elif board_label_sq[n,m]=='knight_w': # white knight
take1 = 0.0
take2 = 0.0
take3 = 0.0
take4 = 0.0
take5 = 0.0
take6 = 0.0
take7 = 0.0
take8 = 0.0
knight_w_take=[0]
if m<7 and n<6:
take1 = board_label_sq[n+2,m+1] # col +1, row +2
if m>0 and n<6:
take2 = board_label_sq[n+2,m-1] # col -1, row +2
if m>0 and n>1:
take3 = board_label_sq[n-2,m-1] # col -1, row -2
if m<7 and n>1:
take4 = board_label_sq[n-2,m+1] # col +1, row -2
if n<7 and m<6:
take5 = board_label_sq[n+1,m+2] # col +2, row +1
if n<7 and m>1:
take6 = board_label_sq[n+1,m-2] # col -2, row +1
if n>0 and m>1:
take7 = board_label_sq[n-1,m-2] # col -2, row -1
if n>0 and m<6:
take8 = board_label_sq[n-1,m+2] # col +2, row -1
if take1!=0 and np.sum(take1==piece_list_b)>0:
knight_w_take.append(chess_values_b[take1][0])
if take2!=0 and np.sum(take2==piece_list_b)>0:
knight_w_take.append(chess_values_b[take2][0])
if take3!=0 and np.sum(take3==piece_list_b)>0:
knight_w_take.append(chess_values_b[take3][0])
if take4!=0 and np.sum(take4==piece_list_b)>0:
knight_w_take.append(chess_values_b[take4][0])
if take5!=0 and np.sum(take5==piece_list_b)>0:
knight_w_take.append(chess_values_b[take5][0])
if take6!=0 and np.sum(take6==piece_list_b)>0:
knight_w_take.append(chess_values_b[take6][0])
if take7!=0 and np.sum(take7==piece_list_b)>0:
knight_w_take.append(chess_values_b[take7][0])
if take8!=0 and np.sum(take8==piece_list_b)>0:
knight_w_take.append(chess_values_b[take8][0])
else:
pass
white_scores.append(np.max(knight_w_take))
# =========================================
elif board_label_sq[n,m]=='knight_b': # black knight
take1 = 0.0
take2 = 0.0
take3 = 0.0
take4 = 0.0
take5 = 0.0
take6 = 0.0
take7 = 0.0
take8 = 0.0
knight_b_take=[0]
if m<7 and n<6:
take1 = board_label_sq[n+2,m+1] # col +1, row +2
if m>0 and n<6:
take2 = board_label_sq[n+2,m-1] # col -1, row +2
if m>0 and n>1:
take3 = board_label_sq[n-2,m-1] # col -1, row -2
if m<7 and n>1:
take4 = board_label_sq[n-2,m+1] # col +1, row -2
if n<7 and m<6:
take5 = board_label_sq[n+1,m+2] # col +2, row +1
if n<7 and m>1:
take6 = board_label_sq[n+1,m-2] # col -2, row +1
if n>0 and m>1:
take7 = board_label_sq[n-1,m-2] # col -2, row -1
if n>0 and m<6:
take8 = board_label_sq[n-1,m+2] # col +2, row -1
if take1!=0 and np.sum(take1==piece_list_w)>0:
knight_b_take.append(chess_values_w[take1][0])
if take2!=0 and np.sum(take2==piece_list_w)>0:
knight_b_take.append(chess_values_w[take2][0])
if take3!=0 and np.sum(take3==piece_list_w)>0:
knight_b_take.append(chess_values_w[take3][0])
if take4!=0 and np.sum(take4==piece_list_w)>0:
knight_b_take.append(chess_values_w[take4][0])
if take5!=0 and np.sum(take5==piece_list_w)>0:
knight_b_take.append(chess_values_w[take5][0])
if take6!=0 and np.sum(take6==piece_list_w)>0:
knight_b_take.append(chess_values_w[take6][0])
if take7!=0 and np.sum(take7==piece_list_w)>0:
knight_b_take.append(chess_values_w[take7][0])
if take8!=0 and np.sum(take8==piece_list_w)>0:
knight_b_take.append(chess_values_w[take8][0])
else:
pass
black_scores.append(np.max(knight_b_take))
# =========================================
elif board_label_sq[n,m]=='king_w': # white king
take1 = 0.0
take2 = 0.0
take3 = 0.0
take4 = 0.0
take5 = 0.0
take6 = 0.0
take7 = 0.0
take8 = 0.0
king_w_take=[0]
if m<7 and n<7:
take1 = board_label_sq[n+1,m+1] # col +1, row +1
if m>0 and n<7:
take2 = board_label_sq[n+1,m-1] # col -1, row +1
if m>0 and n>0:
take3 = board_label_sq[n-1,m-1] # col -1, row -1
if m<7 and n>0:
take4 = board_label_sq[n-1,m+1] # col +1, row -1
if n<7:
take5 = board_label_sq[n+1,m] # col 0, row +1
if m>0:
take6 = board_label_sq[n,m-1] # col -1, row 0
if n>0:
take7 = board_label_sq[n-1,m] # col 0, row -1
if m<7:
take8 = board_label_sq[n,m+1] # col +1, row 0
if take1!=0 and np.sum(take1==piece_list_b)>0:
king_w_take.append(chess_values_b[take1][0])
if take2!=0 and np.sum(take2==piece_list_b)>0:
king_w_take.append(chess_values_b[take2][0])
if take3!=0 and np.sum(take3==piece_list_b)>0:
king_w_take.append(chess_values_b[take3][0])
if take4!=0 and np.sum(take4==piece_list_b)>0:
king_w_take.append(chess_values_b[take4][0])
if take5!=0 and np.sum(take5==piece_list_b)>0:
king_w_take.append(chess_values_b[take5][0])
if take6!=0 and np.sum(take6==piece_list_b)>0:
king_w_take.append(chess_values_b[take6][0])
if take7!=0 and np.sum(take7==piece_list_b)>0:
king_w_take.append(chess_values_b[take7][0])
if take8!=0 and np.sum(take8==piece_list_b)>0:
king_w_take.append(chess_values_b[take8][0])
else:
pass
white_scores.append(np.max(king_w_take))
# =========================================
elif board_label_sq[n,m]=='king_b': # black king
take1 = 0.0
take2 = 0.0
take3 = 0.0
take4 = 0.0
take5 = 0.0
take6 = 0.0
take7 = 0.0
take8 = 0.0
king_b_take=[0]
if m<7 and n<7:
take1 = board_label_sq[n+1,m+1] # col +1, row +1
if m>0 and n<7:
take2 = board_label_sq[n+1,m-1] # col -1, row +1
if m>0 and n>0:
take3 = board_label_sq[n-1,m-1] # col -1, row -1
if m<7 and n>0:
take4 = board_label_sq[n-1,m+1] # col +1, row -1
if n<7:
take5 = board_label_sq[n+1,m] # col 0, row +1
if m>0:
take6 = board_label_sq[n,m-1] # col -1, row 0
if n>0:
take7 = board_label_sq[n-1,m] # col 0, row -1
if m<7:
take8 = board_label_sq[n,m+1] # col +1, row 0
if take1!=0 and np.sum(take1==piece_list_w)>0:
king_b_take.append(chess_values_w[take1][0])
if take2!=0 and np.sum(take2==piece_list_w)>0:
king_b_take.append(chess_values_w[take2][0])
if take3!=0 and np.sum(take3==piece_list_w)>0:
king_b_take.append(chess_values_w[take3][0])
if take4!=0 and np.sum(take4==piece_list_w)>0:
king_b_take.append(chess_values_w[take4][0])
if take5!=0 and np.sum(take5==piece_list_w)>0:
king_b_take.append(chess_values_w[take5][0])
if take6!=0 and np.sum(take6==piece_list_w)>0:
king_b_take.append(chess_values_w[take6][0])
if take7!=0 and np.sum(take7==piece_list_w)>0:
king_b_take.append(chess_values_w[take7][0])
if take8!=0 and np.sum(take8==piece_list_w)>0:
king_b_take.append(chess_values_w[take8][0])
else:
pass
black_scores.append(np.max(king_b_take))
piece_ratio = (sum_black+1)/(sum_white+1)
move_ratio = (np.max(black_scores)+1)/(np.max(white_scores)+1) # ratio of best move that racks the most points
# you win if (your_total_piece_value - enemy_move_value) > (enemy_total_piece_value - your_move_value)
# tie if both kings are lost in that turn
winner=0.0
if np.max(black_scores)==40 and np.max(white_scores)==40:
winner = 0.0 # tie
elif (sum_black-np.max(white_scores)) > (sum_white-np.max(black_scores)):
winner = 1.0 # black wins
else:
winner = -1.0 # white wins
return board_label_sq, piece_ratio, move_ratio, winner
# generate D size training data
def generate_data(D,train_split):
'''
Generates labelled data arrays + images.
Inputs:
D := desired number of data points
N := 1D dimension of board, s.t. board.shape = (N,N)
train_split := split of training/testing data, e.g., 0.9 => 90% training, 10% testing
Outputs:
training_data := split training data, data array: [# red pieces, # blue pieces, winner] dims: (D*train_split) x 3
training_images := split training data, corresponding board images; flattened dims: (D*train_split) x N**2
testing_data := split testing data, data array: [# red pieces, # blue pieces, winner] dims: (D*(1-train_split)) x 3
testing_images := split testing data, corresponding board images; flattened dims: (D*(1-train_split)) x N**2
'''
N=8
data = np.zeros((D,3)) # create array to populate each row with x1: black sum, x2: white sum, label: ratio
images = np.zeros(D).astype(object) # create array to populate D rows with flattened N x N images in the columns
for n in range(D):
winner=0 # exclude ties
while winner==0:
board_label_sq, piece_ratio, move_ratio, winner = generate_best_move()
data[n,[0,1,2]]=[piece_ratio,move_ratio,winner]
images[n]=board_label_sq
training_data=data[:int(D*train_split),:] # labelled training data
training_images=images[:int(D*train_split)] # training images
testing_data=data[int(D*train_split):,:] # labelled testing data
testing_images=images[int(D*train_split):] # testing images
return training_data, training_images, testing_data, testing_images
# gameboard parameters
N=8 # 1D of gameboard. Game board => N x N dimensions
# generate training/testing data for the classical and quantum classifiers
training_data, training_images, testing_data, testing_images =generate_data(D=500,train_split=0.9)
for n in range(9):
chessBoardShow(training_images[n])
def nCen_train_test(training_data, testing_data, N, shrink, plot_testing=False):
'''
Train Nearest Centroid Neighbors algorithm. Plot results and accuracy. Output the best nCen.
Inputs:
training_data := split training data, data array: [# red pieces, # blue pieces, winner] dims: (D*train_split) x 3
testing_data := split testing data, data array: [# red pieces, # blue pieces, winner] dims: (D*(1-train_split)) x 3
N := 1D dimension of board, s.t. board.shape = (N,N); used here for normalizing the data
shrink := list of shrink values to test, e.g., shrink=[0.0,0.1,0.5,0.9]
plot_testing := True or False value; plots the testing dataset with classifier bounds
Outputs:
Plots the nearest centroid decision boundary, training data, test data, and accuracy plots
nCen := nearest centroid object with the highest accuracy
'''
# Assign training/test data
training_data[:,[0,1]]=training_data[:,[0,1]]/(N**2) # standardize data. Max pieces is N*N
testing_data[:,[0,1]]=testing_data[:,[0,1]]/(N**2) # standardize data. Max pieces is N*N
X_train = training_data[:,[0,1]] # training features
y_train = training_data[:,2] # training labels
X_test = testing_data[:,[0,1]] # testing features
y_test = testing_data[:,2] # testing labels
# =============================================================================
# run accuracy with training data for k=k neighbors
acc_list=[]
nCen_list=[]
for i in range(len(shrink)):
# run kNN classification
nCen_list.append(NearestCentroid(shrink_threshold=shrink[i])) # create k-NN object
nCen_list[i].fit(X_train, y_train) # fit classifier decision boundary to training data
# =============================================================================
# plot classification boundary with training data
meshres=50
RED,BLUE=np.meshgrid(np.linspace(np.min([np.min(X_train[:,0]),np.min(X_test[:,0])]),np.max([np.max(X_train[:,0]),np.max(X_test[:,0])]),meshres),
np.linspace(np.min([np.min(X_train[:,1]),np.min(X_test[:,1])]),np.max([np.max(X_train[:,1]),np.max(X_test[:,1])]),meshres))
boundary=nCen_list[i].predict(np.c_[RED.ravel(),BLUE.ravel()])
plt.figure()
plt.contourf(RED,BLUE,boundary.reshape(RED.shape),cmap='bwr',alpha=0.3)
plt.scatter(X_train[:,0],X_train[:,1],c=y_train,cmap='bwr',edgecolor='k')
plt.xlabel('# red pieces\n[normalized]')
plt.ylabel('# blue pieces\n[normalized]')
cbar=plt.colorbar()
cbar.ax.set_ylabel('Winner')
plt.title('Centroid Classification, shrink = '+str(shrink[i]))
plt.show()
# plot testing data
if plot_testing == True:
plt.figure()
plt.contourf(RED,BLUE,boundary.reshape(RED.shape),cmap='bwr',alpha=0.3)
testt=plt.scatter(X_test[:,0],X_test[:,1],c=y_test,cmap='bwr',edgecolor='k')
plt.xlabel('# red pieces\n[normalized]')
plt.ylabel('# blue pieces\n[normalized]')
plt.title('Testing Data, n = '+str(X_test.shape[0]))
cbar=plt.colorbar(testt)
cbar.ax.set_ylabel('Winner')
plt.show()
else:
pass
# =============================================================================
# calculate accuracy with training data set
predicted=nCen_list[i].predict(X_test) # calculate predicted label from training data
acc=np.sum(predicted==y_test)/len(y_test) # calculate accuracy of where prediction is correct vs incorrect relative to actual labels
acc_list.append(acc)
print('shrink = ',shrink[i],'\nTraining Accuracy =',acc*100,'%\n','='*40,'\n\n')
plt.figure()
plt.plot(shrink,acc_list,marker='o')
plt.xlabel('Centroid shrinking threshold')
plt.xticks(shrink)
plt.ylabel('Accuracy')
plt.show()
best_nCen=nCen_list[np.argmax(acc_list)]
print('best shrink = ',shrink[np.argmax(acc_list)])
return best_nCen
# generate best nearest centroid neighbors
best_nCen = nCen_train_test(training_data=training_data, testing_data=testing_data, N=N, shrink=list(np.arange(0.0,0.9,0.1)),plot_testing=True)
def player_prediction_classical(best_model,player_data):
'''
Outputs the classically predicted result of the 5 player games, not within the training dataset.
Inputs:
best_model := NearestCentroid object
player_data := generated data array: [# red pieces, # blue pieces, winner] dims: 5 x 3
Outputs:
cCompData := list of 0 or 1 values. 1 == red wins, 0 == blue wins
'''
X_player_data=player_data[:,[0,1]]
cCompData = best_model.predict(X_player_data)
cCompData[cCompData==-1.]=0
return list(cCompData.astype(int))
# Unit-normalized vector helper
def normalize(x):
return x / np.linalg.norm(x)
# Since in a space R^n there are n-1 RBS gates,
# in a 2-dimensional dataset (R^2), there is 1
# RBS parameter angle, as defined:
def theta_in_2d(x):
epsilon = math.pow(10, -10)
return math.acos((x[0] + epsilon) / (np.linalg.norm(x) + epsilon)) + epsilon
class QuantumCircuit(QuantumCircuit):
def irbs(self, theta, qubits):
ug = UnitaryGate([[1, 0, 0, 0],
[0, np.cos(theta), complex(0,-np.sin(theta)), 0],
[0, complex(0, -np.sin(theta)), np.cos(theta), 0],
[0, 0, 0, 1]], label=f'iRBS({np.around(theta, 3)})')
return self.append(ug, qubits, [])
# qc.irbs(theta, [qubit1, qubit2])
def estimation_circuit(x_theta, y_theta):
# As defined in Johri et al. (III.A.1), an iRBS is functionally
# identical in the distance estimation circuit to the RBS gate;
# thus, the iRBS gate is defined in the QuantumCircuit class to
# be used in the estimation circuit.
# Unitary implementation (throws IonQ backend error)
def irbs_unitary(theta):
return UnitaryGate([[1, 0, 0, 0],
[0, np.cos(theta), complex(0,-np.sin(theta)), 0],
[0, complex(0, -np.sin(theta)), np.cos(theta), 0],
[0, 0, 0, 1]], label=f'iRBS({np.around(theta, 3)})')
# Circuit implementation from figure 7 in Johri et al.
def irbs(qc, theta, qubits):
qc.rz(np.pi/2, qubits[1])
qc.cx(qubits[1], qubits[0])
qc.ry(np.pi/2 - 2 * theta, qubits[1])
qc.rz(-np.pi/2, qubits[0])
qc.cx(qubits[0], qubits[1])
qc.ry(2 * theta - np.pi/2, qubits[1])
qc.cx(qubits[1], qubits[0])
qc.rz(-np.pi / 2, qubits[0])
qc = QuantumCircuit(2,2)
qc.x(0)
irbs(qc, x_theta, [0, 1])
irbs(qc, y_theta, [0, 1])
qc.measure([0, 1], [0, 1])
return qc
# Returns estimated distance as defined in Johri et al. (Equation 3)
def probability_uncorrected(result):
counts = result.get_counts()
shots = np.sum(list(counts.values()))
if '10' in counts:
return counts["10"]/shots
else:
return 0
def probability_corrected(result):
counts = result.get_counts()
corrected_counts = {}
# Discard incorrect values (00, 11)
if '10' in counts:
corrected_counts['10'] = counts['10']
if '01' in counts:
corrected_counts['01'] = counts['01']
shots = np.sum(list(corrected_counts.values()))
if '10' in counts:
return corrected_counts["10"]/shots
else:
return 0
def euclidian_distance(x, y, corrected=False):
x_norm = np.linalg.norm(x)
y_norm = np.linalg.norm(y)
x_square_norm = x_norm**2
y_square_norm = y_norm**2
x_theta = theta_in_2d(x)
y_theta = theta_in_2d(y)
ec = estimation_circuit(x_theta, y_theta)
print(f'xTHETA {x_theta} yTHETA {y_theta}')
# IonQ
#job = backend.run(ec, shots=1000)
# QASM
job = execute(ec, backend, shots=1000)
job_id = job.job_id()
while job.status() is not JobStatus.DONE:
print(job.status())
time.sleep(1)
result = job.result()
if corrected:
probability = probability_corrected(result)
else:
probability = probability_uncorrected(result)
normalized_inner_product = math.sqrt(probability)
return math.sqrt(x_square_norm + y_square_norm - 2*x_norm*y_norm*normalized_inner_product)
import random
# generate toy data: random N x N board
def generate_board(N):
'''
Generates a random board of dimensions N x N
Inputs:
N := 1D dimension of board, s.t. board.shape = (N,N)
Outputs:
board := flattened N x N array
winner := red wins == 1, blue wins == -1
sum_red := sum of red pieces
sum_blue := sum of blue pieces
'''
board=np.zeros((N*N))
pieces=random.sample(range(1,N*N),1)[0]
inds = random.sample(range(0,N*N),pieces) # pick random location to place pieces
ratio = 1
while ratio == 1: # safeguard to remove possiblility of ties
for n in range(pieces):
board[inds[n]]=random.sample([-1,1],1)[0] # make space blue or red
sum_red = np.sum(board==1) # sum of 1 values (i.e., red pieces)
sum_blue = np.sum(board==-1) # sum of -1 values (i.e., blue pieces)
ratio = sum_red/sum_blue # find ratio
if ratio > 1: # red wins
winner = 1
elif ratio < 1: # blue wins
winner = -1
else:
pass
return board, winner, sum_red, sum_blue
class QuantumNearestCentroid:
def __init__(self):
self.centroids = {}
def centroid(self, x):
return np.mean(x, axis=0)
def fit(self, x, y):
organized_values = {}
for i, v in enumerate(y):
if v in organized_values:
organized_values[v].append(x[i])
else:
organized_values[v] = [x[i]]
for v in organized_values:
self.centroids[v] = self.centroid(organized_values[v])
return self.centroids
def predict(self, x):
min_dist = np.inf
closest_centroid = None
for key, centroid in self.centroids.items():
res = euclidian_distance(x, centroid)
if res < min_dist:
min_dist = res
closest_centroid = key
return closest_centroid
def player_prediction_quantum(best_model,player_data):
'''
Outputs the quantum predicted result of the 5 player games, not within the training dataset.
Inputs:
best_model := NearestCentroid object
player_data := generated data array: [# red pieces, # blue pieces, winner] dims: 5 x 3
Outputs:
cCompData := list of 0 or 1 values. 1 == red wins, 0 == blue wins
'''
X_player_data=player_data[:,[0,1]]
qCompData = []
for i in range(5):
qCompData.append(best_model.predict(X_player_data[i]))
qCompData[qCompData==-1.]=0
return list(qCompData)
def quantum_train_test(training_data, testing_data, N, plot_testing=False):
X_train = training_data[:,[0,1]] # training features
y_train = training_data[:,2] # training labels
X_test = testing_data[:,[0,1]] # testing features
y_test = testing_data[:,2] # testing labels
# =============================================================================
model = QuantumNearestCentroid()
centroid = model.fit(X_train.tolist(), y_train.flatten().tolist())
print(centroid)
meshres=10
RED,BLUE=np.meshgrid(np.linspace(np.min([np.min(X_train[:,0]),np.min(X_test[:,0])]),np.max([np.max(X_train[:,0]),np.max(X_test[:,0])]),meshres),
np.linspace(np.min([np.min(X_train[:,1]),np.min(X_test[:,1])]),np.max([np.max(X_train[:,1]),np.max(X_test[:,1])]),meshres))
print(len(np.c_[RED.ravel(),BLUE.ravel()]))
boundary=[]
for i, v in enumerate(np.c_[RED.ravel(),BLUE.ravel()]):
print(f"{i} : {v.tolist()}")
res = model.predict(list(v))
print(res)
boundary.append(res)
print(boundary)
boundary = np.array(boundary)
plt.figure()
plt.contourf(RED,BLUE,boundary.reshape(RED.shape),cmap='bwr',alpha=0.3)
plt.scatter(X_train[:,0],X_train[:,1],c=y_train,cmap='bwr',edgecolor='k')
plt.xlabel('# red pieces\n[normalized]')
plt.ylabel('# blue pieces\n[normalized]')
cbar=plt.colorbar()
cbar.ax.set_ylabel('Winner')
plt.title('Centroid Classification')
plt.show()
# plot testing data
if plot_testing == True:
plt.figure()
plt.contourf(RED,BLUE,boundary.reshape(RED.shape),cmap='bwr',alpha=0.3)
testt=plt.scatter(X_test[:,0],X_test[:,1],c=y_test,cmap='bwr',edgecolor='k')
plt.xlabel('# red pieces\n[normalized]')
plt.ylabel('# blue pieces\n[normalized]')
plt.title('Testing Data, n = '+str(X_test.shape[0]))
cbar=plt.colorbar(testt)
cbar.ax.set_ylabel('Winner')
plt.show()
else:
pass
# =============================================================================
# calculate accuracy with training data set
predicted=[] # calculate predicted label from training data
for v in X_test:
predicted.append(model.predict(v))
predicted = np.array(predicted)
acc=np.sum(predicted==y_test)/len(y_test) # calculate accuracy of where prediction is correct vs incorrect relative to actual labels
print('Training Accuracy =',acc*100,'%\n','='*40,'\n\n')
return model
def quantum_train(training_data, testing_data, N):
# Assign training/test data
X_train = training_data[:,[0,1]] # training features
y_train = training_data[:,2] # training labels
X_test = testing_data[:,[0,1]] # testing features
y_test = testing_data[:,2] # testing labels
model = QuantumNearestCentroid()
centroid = model.fit(X_train.tolist(), y_train.flatten().tolist())
return model
# generate best quantum nearest centroid model
best_quantum = quantum_train_test(training_data=training_data, testing_data=testing_data, N=N, plot_testing=True)
compData = []
compResults = []
def generateCompData(cData = [0,0,0,0,0], qData = [0,0,0,0,0], gData = [0, 0, 0, 0,]):
global compData
global compResults
''' Here we take the 2d array gData and transpose it '''
pgData = pd.DataFrame(gData).T.values.tolist()
pgData = [0 if x==-1.0 else 1 for x in pgData[2]]
'''
These reset the compData and compResults array so there are no errors
with the runtime
'''
compData = [
[0,0,0,0], # Storing what the [Q, C, H, G] say the answer is.
[0,0,0,0],
[0,0,0,0],
[0,0,0,0],
[0,0,0,0]
]
compResults = [
[0,0,0], # Storing [QvG, HvG, CvG]
[0,0,0],
[0,0,0],
[0,0,0],
[0,0,0]
]
'''
The entirety of this function is to setup the enviroment for future functions
'''
qCompData = qData # this will be the data from the QML on the 5 boards given
cCompData = cData # this will be the data from the Classical on the 5 boards given
gCompData = pgData # this is the ground truth answers
'''
These take the original qCompData and cCompData arrays and put them
together in the compData array for parrsing later in the program
'''
count = 0
for i in qCompData:
compData[count][1] = int(i)
count += 1
count = 0
for i in cCompData:
compData[count][0] = int(i)
count += 1
count = 0
for i in gCompData:
compData[count][3] = int(i)
count += 1
def finalizeCompResults():
'''
The entirety of this function is to check if the quatum model and
human match the conventional model
'''
global compData
global compResults
count = 0
for i in compData:
if i[3] == i[0]: # this is for the C v. G
compResults[count][1] = 1
if i[3] == i[1]: # this is for the Q v. G
compResults[count][0] = 1
if i[3] == i[2]: # this is for the H v. G
compResults[count][2] = 1
count += 1
def showCompResults():
global compResults
global compData
data = [
[0,0,0,0],
[0,0,0,0],
[0,0,0,0],
[0,0,0,0],
[0,0,0,0]
]
dataColors = [
["#a2cffe",0,0,0],
["#a2cffe",0,0,0],
["#a2cffe",0,0,0],
["#a2cffe",0,0,0],
["#a2cffe",0,0,0]
]
count = 0
# print(compResults)
for i in compResults:
if i[0] == 1: # Q v. G
data[count][3] = compData[count][1]
dataColors[count][3] = "palegreen"
else:
dataColors[count][3] = "#cf6275"
if i[2] == 1: # Human v. G
data[count][1] = compData[count][2]
dataColors[count][1] = "palegreen"
else:
dataColors[count][1] = "#cf6275"
if i[1] == 1: # C v. G
data[count][2] = compData[count][0]
dataColors[count][2] = "palegreen"
else:
dataColors[count][2] = "#cf6275"
data[count][0] = compData[count][3]
count += 1
print(data)
for i in range(0,5):
data[i] = ["Black" if x==1 else "White" for x in data[i]]
print(data)
Sum = [sum(x) for x in zip(*compResults)]
winner = ". . . wait what?!?!?! it was a tie! Well, I guess no one"
if (Sum[0] < Sum[1]) and (Sum[0] < Sum[2]):
winner = "Human"
elif (Sum[1] < Sum[0]) and (Sum[1] < Sum[2]):
winner = "Quantum Computer"
elif (Sum[2] < Sum[1]) and (Sum[2] < Sum[0]):
winner = "Classical Computer"
fig, ax = plt.subplots(1,1)
column_labels=["Truth", "Human v. Truth", "Classical v. Truth", "Quantum v. Truth"]
plt.title("Who won, a quantum computer or a human? Turns out the " + winner + " is better!")
ax.axis('tight')
ax.axis('off')
ax.table(cellText=data,
colLabels = column_labels,
cellColours = dataColors,
loc = "center",
cellLoc='center')
plt.show()
def showProblem(array):
global compData
# N = 8 # board dimensions: N x N
# board = array
# board = board.reshape(N,N)
plt.axis('off')
# plt.title("Does Black or White have a game-state advantage this turn?")
# plt.imshow(board,cmap='bwr')
chessBoardShow(array)
plt.show()
def playersMove(roundNum):
global compData
while True:
print('\033[1m'+'GAME #',str(roundNum+1)+'/5'+'\033[0m')
print('_'*100)
print('\033[1m'+'WHICH PLAYER HAS THE GAME-STATE ADVANTAGE THIS TURN?'+'\033[0m')
print('Hint: Game-state advantage is computed based on which player has a higher total\n',
'piece value minus the value of the best piece the opposing player can take this turn.\n',
'Note: There CANNOT be a tie.')
print('_'*100,'\n')
print("Does black or white have the advantage? (b/w): ")
playerChoice = input("").lower()
if playerChoice == "b":
playerChoice = 1
break
elif playerChoice == "w":
playerChoice = 0
break
compData[roundNum][2] = playerChoice
clear_output(wait=True)
newGame = True
while newGame:
# Generate 5 boards for the player to play
player_data_5, player_images_5, __, __ =generate_data(D=5,train_split=1)
cCompData = player_prediction_classical(best_model=best_nCen,player_data=player_data_5)
# qCompData = player_prediction_quantum(best_model=best_quantum,player_data=player_data_5)
qCompData=[1,1,1,1,1]
generateCompData(cCompData, qCompData, player_data_5)
clear_output(wait=True)
# Start the game!
for i in range(0, 5):
showProblem(player_images_5[i])
playersMove(i)
clear_output(wait=True)
finalizeCompResults()
showCompResults()
while True:
print("Would you like to play again? (y/n): ")
playerChoice = input("").lower()
if playerChoice == "y":
clear_output(wait=True)
break
elif playerChoice == "n":
clear_output(wait=True)
newGame = False
break
|
https://github.com/MonitSharma/qiskit-projects
|
MonitSharma
|
import numpy as np
import random
import matplotlib.pyplot as plt
from sklearn.neighbors import KNeighborsClassifier
from sklearn.neighbors import NearestCentroid
from IPython.display import clear_output
import pandas as pd
# =======================================================
import math
import time
from qiskit import Aer, QuantumCircuit, execute
from qiskit.extensions import UnitaryGate
from qiskit.providers.jobstatus import JobStatus
# Use Aer's qasm_simulator by default
backend = Aer.get_backend('qasm_simulator')
# generate toy data: random N x N board
def generate_board(N):
'''
Generates a random board of dimensions N x N
Inputs:
N := 1D dimension of board, s.t. board.shape = (N,N)
Outputs:
board := flattened N x N array
winner := red wins == 1, blue wins == -1
sum_red := sum of red pieces
sum_blue := sum of blue pieces
'''
board=np.zeros((N*N))
pieces=random.sample(range(1,N*N),1)[0]
inds = random.sample(range(0,N*N),pieces) # pick random location to place pieces
ratio = 1
while ratio == 1: # safeguard to remove possiblility of ties
for n in range(pieces):
board[inds[n]]=random.sample([-1,1],1)[0] # make space blue or red
sum_red = np.sum(board==1) # sum of 1 values (i.e., red pieces)
sum_blue = np.sum(board==-1) # sum of -1 values (i.e., blue pieces)
ratio = (sum_red+1)/(sum_blue+1) # find ratio
if ratio > 1: # red wins
winner = 1
elif ratio < 1: # blue wins
winner = -1
else:
pass
return board, winner, sum_red, sum_blue
def generate_data(D,N,train_split):
'''
Generates labelled data arrays + images.
Inputs:
D := desired number of data points
N := 1D dimension of board, s.t. board.shape = (N,N)
train_split := split of training/testing data, e.g., 0.9 => 90% training, 10% testing
Outputs:
training_data := split training data, data array: [# red pieces, # blue pieces, winner] dims: (D*train_split) x 3
training_images := split training data, corresponding board images; flattened dims: (D*train_split) x N**2
testing_data := split testing data, data array: [# red pieces, # blue pieces, winner] dims: (D*(1-train_split)) x 3
testing_images := split testing data, corresponding board images; flattened dims: (D*(1-train_split)) x N**2
'''
data = np.zeros((D,3)) # create array to populate each row with x1: black sum, x2: white sum, label: ratio
images = np.zeros((D,N**2)) # create array to populate D rows with flattened N x N images in the columns
for n in range(D):
board,winner,sum_red,sum_blue = generate_board(N=N)
data[n,[0,1,2]]=[sum_red,sum_blue,winner]
images[n,:]=board
training_data=data[:int(D*train_split),:] # labelled training data
training_images=images[:int(D*train_split),:] # training images
testing_data=data[int(D*train_split):,:] # labelled testing data
testing_images=images[int(D*train_split):,:] # testing images
return training_data, training_images, testing_data, testing_images
# gameboard parameters
N=8 # 1D of gameboard. Game board => N x N dimensions
# generate training/testing data for the classical and quantum classifiers
training_data, training_images, testing_data, testing_images =generate_data(D=300,N=8,train_split=0.9)
def nCen_train_test(training_data, testing_data, N, shrink, plot_testing=False):
'''
Train Nearest Centroid Neighbors algorithm. Plot results and accuracy. Output the best nCen.
Inputs:
training_data := split training data, data array: [# red pieces, # blue pieces, winner] dims: (D*train_split) x 3
testing_data := split testing data, data array: [# red pieces, # blue pieces, winner] dims: (D*(1-train_split)) x 3
N := 1D dimension of board, s.t. board.shape = (N,N); used here for normalizing the data
shrink := list of shrink values to test, e.g., shrink=[0.0,0.1,0.5,0.9]
plot_testing := True or False value; plots the testing dataset with classifier bounds
Outputs:
Plots the nearest centroid decision boundary, training data, test data, and accuracy plots
nCen := nearest centroid object with the highest accuracy
'''
# Assign training/test data
training_data[:,[0,1]]=training_data[:,[0,1]]/(N**2) # standardize data. Max pieces is N*N
testing_data[:,[0,1]]=testing_data[:,[0,1]]/(N**2) # standardize data. Max pieces is N*N
X_train = training_data[:,[0,1]] # training features
y_train = training_data[:,2] # training labels
X_test = testing_data[:,[0,1]] # testing features
y_test = testing_data[:,2] # testing labels
# =============================================================================
# run accuracy with training data for k=k neighbors
acc_list=[]
nCen_list=[]
for i in range(len(shrink)):
# run kNN classification
nCen_list.append(NearestCentroid(shrink_threshold=shrink[i])) # create k-NN object
nCen_list[i].fit(X_train, y_train) # fit classifier decision boundary to training data
# =============================================================================
# plot classification boundary with training data
meshres=50
RED,BLUE=np.meshgrid(np.linspace(np.min([np.min(X_train[:,0]),np.min(X_test[:,0])]),np.max([np.max(X_train[:,0]),np.max(X_test[:,0])]),meshres),
np.linspace(np.min([np.min(X_train[:,1]),np.min(X_test[:,1])]),np.max([np.max(X_train[:,1]),np.max(X_test[:,1])]),meshres))
boundary=nCen_list[i].predict(np.c_[RED.ravel(),BLUE.ravel()])
plt.figure()
plt.contourf(RED,BLUE,boundary.reshape(RED.shape),cmap='bwr',alpha=0.3)
plt.scatter(X_train[:,0],X_train[:,1],c=y_train,cmap='bwr',edgecolor='k')
plt.xlabel('# red pieces\n[normalized]')
plt.ylabel('# blue pieces\n[normalized]')
cbar=plt.colorbar()
cbar.ax.set_ylabel('Winner')
plt.title('Centroid Classification, shrink = '+str(shrink[i]))
plt.show()
# plot testing data
if plot_testing == True:
plt.figure()
plt.contourf(RED,BLUE,boundary.reshape(RED.shape),cmap='bwr',alpha=0.3)
testt=plt.scatter(X_test[:,0],X_test[:,1],c=y_test,cmap='bwr',edgecolor='k')
plt.xlabel('# red pieces\n[normalized]')
plt.ylabel('# blue pieces\n[normalized]')
plt.title('Testing Data, n = '+str(X_test.shape[0]))
cbar=plt.colorbar(testt)
cbar.ax.set_ylabel('Winner')
plt.show()
else:
pass
# =============================================================================
# calculate accuracy with training data set
predicted=nCen_list[i].predict(X_test) # calculate predicted label from training data
acc=np.sum(predicted==y_test)/len(y_test) # calculate accuracy of where prediction is correct vs incorrect relative to actual labels
acc_list.append(acc)
print('shrink = ',shrink[i],'\nTraining Accuracy =',acc*100,'%\n','='*40,'\n\n')
plt.figure()
plt.plot(shrink,acc_list,marker='o')
plt.xlabel('Centroid shrinking threshold')
plt.xticks(shrink)
plt.ylabel('Accuracy')
plt.show()
best_nCen=nCen_list[np.argmax(acc_list)]
print('best shrink = ',shrink[np.argmax(acc_list)])
return best_nCen
# generate best nearest centroid neighbors
best_nCen = nCen_train_test(training_data=training_data, testing_data=testing_data, N=N, shrink=list(np.arange(0.0,0.9,0.1)),plot_testing=True)
def player_prediction_classical(best_model,player_data):
'''
Outputs the classically predicted result of the 5 player games, not within the training dataset.
Inputs:
best_model := NearestCentroid object
player_data := generated data array: [# red pieces, # blue pieces, winner] dims: 5 x 3
Outputs:
cCompData := list of 0 or 1 values. 1 == red wins, 0 == blue wins
'''
X_player_data=player_data[:,[0,1]]
cCompData = best_model.predict(X_player_data)
cCompData[cCompData==-1.]=0
return list(cCompData.astype(int))
# Unit-normalized vector helper
def normalize(x):
return x / np.linalg.norm(x)
# Since in a space R^n there are n-1 RBS gates,
# in a 2-dimensional dataset (R^2), there is 1
# RBS parameter angle, as defined:
def theta_in_2d(x):
epsilon = math.pow(10, -10)
return math.acos((x[0] + epsilon) / (np.linalg.norm(x) + epsilon)) + epsilon
def estimation_circuit(x_theta, y_theta):
# As defined in Johri et al. (III.A.1), an iRBS is functionally
# identical in the distance estimation circuit to the RBS gate;
# thus, the iRBS gate is defined in the QuantumCircuit class to
# be used in the estimation circuit.
# Unitary implementation (throws IonQ backend error)
def irbs_unitary(theta):
return UnitaryGate([[1, 0, 0, 0],
[0, np.cos(theta), complex(0,-np.sin(theta)), 0],
[0, complex(0, -np.sin(theta)), np.cos(theta), 0],
[0, 0, 0, 1]], label=f'iRBS({np.around(theta, 3)})')
# Circuit implementation from figure 7 in Johri et al.
def irbs(qc, theta, qubits):
qc.rz(np.pi/2, qubits[1])
qc.cx(qubits[1], qubits[0])
qc.ry(np.pi/2 - 2 * theta, qubits[1])
qc.rz(-np.pi/2, qubits[0])
qc.cx(qubits[0], qubits[1])
qc.ry(2 * theta - np.pi/2, qubits[1])
qc.cx(qubits[1], qubits[0])
qc.rz(-np.pi / 2, qubits[0])
qc = QuantumCircuit(2,2)
qc.x(0)
irbs(qc, x_theta, [0, 1])
irbs(qc, y_theta, [0, 1])
qc.measure([0, 1], [0, 1])
return qc
# Returns estimated distance as defined in Johri et al. (Equation 3)
def probability_uncorrected(result):
counts = result.get_counts()
shots = np.sum(list(counts.values()))
if '10' in counts:
return counts["10"]/shots
else:
return 0
def probability_corrected(result):
counts = result.get_counts()
corrected_counts = {}
# Discard incorrect values (00, 11)
if '10' in counts:
corrected_counts['10'] = counts['10']
if '01' in counts:
corrected_counts['01'] = counts['01']
shots = np.sum(list(corrected_counts.values()))
if '10' in counts:
return corrected_counts["10"]/shots
else:
return 0
def euclidian_distance(x, y, corrected=False):
x_norm = np.linalg.norm(x)
y_norm = np.linalg.norm(y)
x_square_norm = x_norm**2
y_square_norm = y_norm**2
x_theta = theta_in_2d(x)
y_theta = theta_in_2d(y)
ec = estimation_circuit(x_theta, y_theta)
if backend.name() == "qasm_simulator":
job = execute(ec, backend, shots=1000)
else: # IonQ
job = backend.run(ec, shots=1000)
job_id = job.job_id()
while job.status() is not JobStatus.DONE:
print(job.status())
time.sleep(1)
result = job.result()
if corrected:
probability = probability_corrected(result)
else:
probability = probability_uncorrected(result)
normalized_inner_product = math.sqrt(probability)
return math.sqrt(x_square_norm + y_square_norm - 2*x_norm*y_norm*normalized_inner_product)
import random
# generate toy data: random N x N board
def generate_board(N):
'''
Generates a random board of dimensions N x N
Inputs:
N := 1D dimension of board, s.t. board.shape = (N,N)
Outputs:
board := flattened N x N array
winner := red wins == 1, blue wins == -1
sum_red := sum of red pieces
sum_blue := sum of blue pieces
'''
board=np.zeros((N*N))
pieces=random.sample(range(1,N*N),1)[0]
inds = random.sample(range(0,N*N),pieces) # pick random location to place pieces
ratio = 1
while ratio == 1: # safeguard to remove possiblility of ties
for n in range(pieces):
board[inds[n]]=random.sample([-1,1],1)[0] # make space blue or red
sum_red = np.sum(board==1) # sum of 1 values (i.e., red pieces)
sum_blue = np.sum(board==-1) # sum of -1 values (i.e., blue pieces)
ratio = sum_red/sum_blue # find ratio
if ratio > 1: # red wins
winner = 1
elif ratio < 1: # blue wins
winner = -1
else:
pass
return board, winner, sum_red, sum_blue
class QuantumNearestCentroid:
def __init__(self):
self.centroids = {}
def centroid(self, x):
return np.mean(x, axis=0)
def fit(self, x, y):
organized_values = {}
for i, v in enumerate(y):
if v in organized_values:
organized_values[v].append(x[i])
else:
organized_values[v] = [x[i]]
for v in organized_values:
self.centroids[v] = self.centroid(organized_values[v])
return self.centroids
def predict(self, x):
min_dist = np.inf
closest_centroid = None
for key, centroid in self.centroids.items():
res = euclidian_distance(x, centroid)
if res < min_dist:
min_dist = res
closest_centroid = key
return closest_centroid
def player_prediction_quantum(best_model,player_data):
'''
Outputs the quantum predicted result of the 5 player games, not within the training dataset.
Inputs:
best_model := NearestCentroid object
player_data := generated data array: [# red pieces, # blue pieces, winner] dims: 5 x 3
Outputs:
cCompData := list of 0 or 1 values. 1 == red wins, 0 == blue wins
'''
X_player_data=player_data[:,[0,1]]
qCompData = []
for i in range(5):
qCompData.append(best_model.predict(X_player_data[i]))
qCompData[qCompData==-1.]=0
return list(qCompData)
def quantum_train_test(training_data, testing_data, N, plot_testing=False):
'''
Train Nearest Centroid Neighbors algorithm. Plot results and accuracy. Output the best nCen.
Inputs:
training_data := split training data, data array: [# red pieces, # blue pieces, winner] dims: (D*train_split) x 3
testing_data := split testing data, data array: [# red pieces, # blue pieces, winner] dims: (D*(1-train_split)) x 3
N := 1D dimension of board, s.t. board.shape = (N,N); used here for normalizing the data
shrink := list of shrink values to test, e.g., shrink=[0.0,0.1,0.5,0.9]
plot_testing := True or False value; plots the testing dataset with classifier bounds
Outputs:
Plots the nearest centroid decision boundary, training data, test data, and accuracy plots
nCen := nearest centroid object with the highest accuracy
'''
# Assign training/test data
X_train = training_data[:,[0,1]] # training features
y_train = training_data[:,2] # training labels
X_test = testing_data[:,[0,1]] # testing features
y_test = testing_data[:,2] # testing labels
# =============================================================================
model = QuantumNearestCentroid()
centroid = model.fit(X_train.tolist(), y_train.flatten().tolist())
print(centroid)
meshres=30
RED,BLUE=np.meshgrid(np.linspace(np.min([np.min(X_train[:,0]),np.min(X_test[:,0])]),np.max([np.max(X_train[:,0]),np.max(X_test[:,0])]),meshres),
np.linspace(np.min([np.min(X_train[:,1]),np.min(X_test[:,1])]),np.max([np.max(X_train[:,1]),np.max(X_test[:,1])]),meshres))
print(len(np.c_[RED.ravel(),BLUE.ravel()]))
boundary=[]
for i, v in enumerate(np.c_[RED.ravel(),BLUE.ravel()]):
print(f"{i} : {v.tolist()}")
res = model.predict(list(v))
print(res)
boundary.append(res)
print(boundary)
boundary = np.array(boundary)
plt.figure()
plt.contourf(RED,BLUE,boundary.reshape(RED.shape),cmap='bwr',alpha=0.3)
plt.scatter(X_train[:,0],X_train[:,1],c=y_train,cmap='bwr',edgecolor='k')
plt.xlabel('# red pieces\n[normalized]')
plt.ylabel('# blue pieces\n[normalized]')
cbar=plt.colorbar()
cbar.ax.set_ylabel('Winner')
plt.title('Centroid Classification')
plt.show()
# plot testing data
if plot_testing == True:
plt.figure()
plt.contourf(RED,BLUE,boundary.reshape(RED.shape),cmap='bwr',alpha=0.3)
testt=plt.scatter(X_test[:,0],X_test[:,1],c=y_test,cmap='bwr',edgecolor='k')
plt.xlabel('# red pieces\n[normalized]')
plt.ylabel('# blue pieces\n[normalized]')
plt.title('Testing Data, n = '+str(X_test.shape[0]))
cbar=plt.colorbar(testt)
cbar.ax.set_ylabel('Winner')
plt.show()
else:
pass
# =============================================================================
# calculate accuracy with training data set
predicted=[] # calculate predicted label from training data
for v in X_test:
predicted.append(model.predict(v))
predicted = np.array(predicted)
acc=np.sum(predicted==y_test)/len(y_test) # calculate accuracy of where prediction is correct vs incorrect relative to actual labels
print('Training Accuracy =',acc*100,'%\n','='*40,'\n\n')
return model
def quantum_train(training_data, testing_data, N):
# Assign training/test data
X_train = training_data[:,[0,1]] # training features
y_train = training_data[:,2] # training labels
X_test = testing_data[:,[0,1]] # testing features
y_test = testing_data[:,2] # testing labels
model = QuantumNearestCentroid()
centroid = model.fit(X_train.tolist(), y_train.flatten().tolist())
return model
# Uncomment below if you want to run the analysis
#best_quantum = quantum_train_test(training_data=training_data, testing_data=testing_data, N=N, plot_testing=True)
# generate best nearest centroid neighbors
best_quantum = quantum_train(training_data=training_data, testing_data=testing_data, N=N)
compData = []
compResults = []
def generateCompData(cData = [0,0,0,0,0], qData = [0,0,0,0,0], gData = [0, 0, 0, 0,]):
global compData
global compResults
''' Here we take the 2d array gData and transpose it '''
pgData = pd.DataFrame(gData).T.values.tolist()
pgData = [0 if x==-1.0 else 1 for x in pgData[2]]
'''
These reset the compData and compResults array so there are no errors
with the runtime
'''
compData = [
[0,0,0,0], # Storing what the [Q, C, H, G] say the answer is.
[0,0,0,0],
[0,0,0,0],
[0,0,0,0],
[0,0,0,0]
]
compResults = [
[0,0,0], # Storing [QvG, HvG, CvG]
[0,0,0],
[0,0,0],
[0,0,0],
[0,0,0]
]
'''
The entirety of this function is to setup the enviroment for future functions
'''
qCompData = qData # this will be the data from the QML on the 5 boards given
cCompData = cData # this will be the data from the Classical on the 5 boards given
gCompData = pgData # this is the ground truth answers
'''
These take the original qCompData and cCompData arrays and put them
together in the compData array for parrsing later in the program
'''
count = 0
for i in qCompData:
compData[count][1] = int(i)
count += 1
count = 0
for i in cCompData:
compData[count][0] = int(i)
count += 1
count = 0
for i in gCompData:
compData[count][3] = int(i)
count += 1
def finalizeCompResults():
'''
The entirety of this function is to check if the quatum model and
human match the conventional model
'''
global compData
global compResults
count = 0
for i in compData:
if i[3] == i[0]: # this is for the C v. G
compResults[count][1] = 1
if i[3] == i[1]: # this is for the Q v. G
compResults[count][0] = 1
if i[3] == i[2]: # this is for the H v. G
compResults[count][2] = 1
count += 1
def showCompResults():
'''
The entirety of this function is to display to the user which problem they
or the quantum computer got correct in a visually pleasing way
'''
global compResults
global compData
data = [
[0,0,0,0],
[0,0,0,0],
[0,0,0,0],
[0,0,0,0],
[0,0,0,0]
]
dataColors = [
["#a2cffe",0,0,0],
["#a2cffe",0,0,0],
["#a2cffe",0,0,0],
["#a2cffe",0,0,0],
["#a2cffe",0,0,0]
]
'''
This next for loop checks the compResults array and sets the values of data
and dataColors accordingly
'''
count = 0
# print(compResults)
for i in compResults:
if i[0] == 1: # Q v. G
data[count][3] = compData[count][1]
dataColors[count][3] = "palegreen"
else:
dataColors[count][3] = "#cf6275"
if i[2] == 1: # Human v. G
data[count][1] = compData[count][2]
dataColors[count][1] = "palegreen"
else:
dataColors[count][1] = "#cf6275"
if i[1] == 1: # C v. G
data[count][2] = compData[count][0]
dataColors[count][2] = "palegreen"
else:
dataColors[count][2] = "#cf6275"
data[count][0] = compData[count][3]
count += 1
print(data)
for i in range(0,5):
data[i] = ["Red" if x==1 else "Blue" for x in data[i]]
print(data)
'''
This section below sums the amount of correct answers from both the human
and quantum computer
'''
Sum = [sum(x) for x in zip(*compResults)]
winner = ". . . wait what?!?!?! it was a tie! Well, I guess no one"
if (Sum[0] < Sum[1]) and (Sum[0] < Sum[2]):
winner = "Human"
elif (Sum[1] < Sum[0]) and (Sum[1] < Sum[2]):
winner = "Quantum Computer"
elif (Sum[2] < Sum[1]) and (Sum[2] < Sum[0]):
winner = "Classical Computer"
'''
This section below displays the data formated above and who the winner of the
game is
'''
fig, ax = plt.subplots(1,1)
column_labels=["Truth", "Human v. Truth", "Classical v. Truth", "Quantum v. Truth"]
plt.title("Who won, a quantum computer or a human? Turns out the " + winner + " is better!")
ax.axis('tight')
ax.axis('off')
ax.table(cellText=data,
colLabels = column_labels,
cellColours = dataColors,
loc = "center",
cellLoc='center')
plt.show()
def showProblem(array):
'''
This function is used to display the game board for the user to evaluate
'''
global compData
N = 8 # board dimensions: N x N
board = array
board = board.reshape(N,N)
plt.axis('off')
plt.title("Who has more?")
plt.imshow(board,cmap='bwr')
plt.show()
def playersMove(roundNum):
'''
This function is used to initialize the user to input an answer for the
game board
'''
global compData
while True:
print("Is red or blue more? (b/r): ")
playerChoice = input("").lower()
if playerChoice == "r":
playerChoice = 1
break
elif playerChoice == "b":
playerChoice = 0
break
compData[roundNum][2] = playerChoice
clear_output(wait=True)
newGame = True
while newGame:
# Generate 5 boards for the player to play
player_data_5, player_images_5, __, __ =generate_data(D=5,N=8,train_split=1)
cCompData = player_prediction_classical(best_model=best_nCen,player_data=player_data_5)
# qCompData = player_prediction_quantum(best_model=best_quantum,player_data=player_data_5)
qCompData=[0,0,0,0,0]
generateCompData(cCompData, qCompData, player_data_5)
clear_output(wait=True)
# Start the game!
for i in range(0, 5):
showProblem(player_images_5[i])
playersMove(i)
clear_output(wait=True)
finalizeCompResults()
showCompResults()
while True:
print("Would you like to play again? (y/n): ")
playerChoice = input("").lower()
if playerChoice == "y":
clear_output(wait=True)
break
elif playerChoice == "n":
clear_output(wait=True)
newGame = False
break
|
https://github.com/MonitSharma/qiskit-projects
|
MonitSharma
|
from functions import BinPacking, BinPackingNewApproach, new_eq_optimal, get_figure, interpret, eval_constrains
from functions import mapping_cost, cost_func, qaoa_circuit, check_best_sol
from qiskit.algorithms import QAOA, NumPyMinimumEigensolver
from qiskit_optimization.algorithms import CplexOptimizer, MinimumEigenOptimizer
from qiskit.algorithms.optimizers import COBYLA
import numpy as np
from qiskit_optimization.problems.constraint import ConstraintSense
import matplotlib.pyplot as plt
from scipy.optimize import minimize
from qiskit import Aer
backend = Aer.get_backend("qasm_simulator")
#np.random.seed(1)
num_items = 4 # number of items
num_bins = num_items # maximum number of bins
max_weight = 15 # max weight of a bin
cases = 1
solutions_new = {}
optimal_new = []
ratio_new = []; new =[]
result_classical = []; result_qaoa_new = []
check_const = []
weights=[]
qaoa = MinimumEigenOptimizer(QAOA(optimizer=COBYLA(maxiter=100), reps=1, quantum_instance=backend))
for i in range(cases): # Testing 5 different randomly selected configurations of the problem
print(f"----------- Case {i+1} -------------")
weights.append(np.random.randint(1, max_weight, num_items)) # Randomly picking the item weight
qubo_new = BinPackingNewApproach(num_items, num_bins, weights[-1], max_weight, alpha=1, simplification=True)
qubo_classical, qp = BinPacking(num_items, num_bins, weights[-1], max_weight, simplification=True)
result_classical.append(CplexOptimizer().solve(qubo_classical))
optimal_new.append(new_eq_optimal(qubo_new, qubo_classical))
result_qaoa_new.append(qaoa.solve(qubo_new))
solutions_new = result_qaoa_new[-1].fval
new.append(solutions_new)
check_const.append(eval_constrains(qp, result_qaoa_new[-1].x, max_weight))
print(check_const[-1])
print(f" The percetage of positive cases is {100*np.sum(check_const)/cases} %")
for i in range(len(result_classical)):
fig = get_figure(interpret(result_classical[i].x, weights[i], max_weight, num_items, num_bins, simplify=True), weights[i], max_weight, title=f"-------Case {i+1}-----")
fig = get_figure(interpret(result_qaoa_new[i].x, weights[i], max_weight, num_items, num_bins, simplify=True), weights[i], max_weight, title="New")
n = 50
alpha = np.linspace(0, 2*np.pi, n)
beta = np.linspace(0, np.pi, n)
map_cost_10 = mapping_cost(alpha, beta, qubo_new, n = 10)
map_cost_20 = mapping_cost(alpha, beta, qubo_new, n = 20)
fig, ax = plt.subplots(1,2, figsize=(10,10))
ax[0].imshow(np.log(map_cost_10))
ax[1].imshow(np.log(map_cost_20))
for i in range(2):
# ax[i].set_xticks([0,9,19], ["0", r"$\pi/2$", r"$\pi$"])
# ax[i].set_yticks([0,9,19], ["0", r"$\pi$", r"2$\pi$"])
ax[i].set_xlabel(r"$\beta$", fontsize=22)
ax[i].set_ylabel(r"$\alpha$", fontsize=22)
p = 4
x0 = np.random.rand(p*2)
circuit = qaoa_circuit(qubo_new, p=p)
objective = qubo_new.objective
num_evals = 20
fmin = minimize(cost_func, x0, args = (circuit, objective, num_evals), method="COBYLA")
best_sol = check_best_sol(fmin.x, circuit, qp, max_weight, n=10)
print(f" minimum my cost_fun {best_sol}, minimum with cplex {result_qaoa_new[-1].x}")
fig = get_figure(interpret(np.array(best_sol), weights[-1], max_weight, num_items, num_bins, simplify=True), weights[-1], max_weight, title=f"-------Case {i+1}-----")
best_sol
|
https://github.com/MonitSharma/qiskit-projects
|
MonitSharma
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2018.
#
# 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.
"""
Created on Wed Mar 11 18:03:12 2020
Functional interface to Qasm2 source loading and exporting
Supersede QuantumCircuit member functions
Provide for pluggable qasm translator
Based on conversation with Dr. Luciano Bello
@author: jax
"""
from importlib import import_module
from os import linesep
from typing import List, BinaryIO, TextIO
from qiskit import QuantumCircuit, QiskitError
from qiskit_openqasm2 import Qasm
from .funhelp import qasm_load, qasm_export
def _load_from_string(qasm_src: str or List[str],
loader: str = None,
include_path: str = '') -> QuantumCircuit:
"""
Parameters
----------
qasm_src : str or List[str]
Qasm program source as string or list of string.
loader : str, optional
Name of module with functional attribute
load(filename: str = None,
data: str = None,
include_path: str = None) -> QuantumCircuit:
... to use for qasm translation.
None means "use Qiskit qasm"
The default is None.
include_path : str, optional
Loader-specific include path for qasm include directives.
The default is ''.
Raises
------
QiskitError
If unknown loader.
Returns
-------
QuantumCircuit
Circuit factoried from Qasm src.
"""
circ = None
if not loader:
if isinstance(qasm_src, list):
qasm_src = ''.join(s + linesep for s in qasm_src)
qasm = Qasm(data=qasm_src)
circ = qasm_load(qasm)
else:
m_m = import_module(loader)
circ = getattr(m_m, 'load')(data=qasm_src,
include_path=include_path)
return circ
def _load_from_file(filename: str,
loader: str = None,
include_path: str = '') -> QuantumCircuit:
"""
Parameters
----------
filename : str
Filepath to qasm program source.
loader : str, optional
Name of module with functional attribute
load(filename: str = None,
data: str = None,
include_path: str = None) -> QuantumCircuit:
... to use for qasm translation.
None means "use Qiskit qasm"
The default is None.
include_path : str, optional
Loader-specific include path for qasm include directives.
The default is ''.
Returns
-------
QuantumCircuit
Circuit factoried from Qasm src.
"""
circ = None
if not loader:
qasm = Qasm(filename=filename)
circ = qasm_load(qasm)
else:
m_m = import_module(loader)
circ = getattr(m_m, 'load')(filename=filename,
include_path=include_path)
return circ
def load(data: str or List[str] = None,
filename: str = None,
loader: str = None,
include_path: str = None) -> QuantumCircuit:
"""
Parameters
----------
data : str or List[str], optional
Qasm program source as string or list of string. The default is None.
filename : str, optional
Filepath to qasm program source. The default is None.
loader : str, optional
Name of module with functional attribute
load(filename: str = None,
data: str = None,
include_path: str = None) -> QuantumCircuit:
... to use for qasm translation.
None means "use Qiskit qasm"
The default is None.
include_path : str, optional
Loader-specific include path for qasm include directives.
The default is None.
Raises
------
QiskitError
If both filename and data or neither filename nor data.
Returns
-------
QuantumCircuit
The factoried circuit.
"""
if (not data and not filename) or (data and filename):
raise QiskitError("To load, either filename or data (and not both) must be provided.")
circ = None
if data:
circ = _load_from_string(data, loader=loader, include_path=include_path)
elif filename:
circ = _load_from_file(filename, loader=loader, include_path=include_path)
return circ
def export(qc: QuantumCircuit,
exporter: str = None,
file: BinaryIO or TextIO = None,
filename: str = None,
include_path: str = None,) -> str:
"""
Decompile a QuantumCircuit into Return OpenQASM string
Parameters
----------
qc : QuantumCircuit
Circuit to decompile ("export")
exporter : str, optional
Name of module with functional attribute
export(qc: QuantumCircuit,
include_path: str = None) -> QuantumCircuit:
... to use for qasm translation.
None means "use Qiskit qasm"
The default is None.
file : BinaryIO or TextIO, optional
File object to write to as well as return str
Written in UTF-8
Caller must close file.
Mutually exclusive with filename=
The default is None.
filename : str, optional
Name of file to write export to as well as return str
Mutually exclusive with file=
The default is None.
include_path: str, optional
Unloader-specific include path for qasm include directives
Raises
------
QiskitError
If both filename and file
Returns
-------
str
OpenQASM source for circuit.
"""
if filename and file:
raise QiskitError("export: file= and filename= are mutually exclusive")
qasm_src = None
if not exporter:
qasm_src = qasm_export(qc)
else:
m_m = import_module(exporter)
qasm_src = getattr(m_m, 'export')(qc, include_path=include_path)
if filename:
f_f = open(filename, 'w')
f_f.write(qasm_src)
f_f.close()
elif file:
if 'b' in file.mode:
file.write(bytes(qasm_src, 'utf-8'))
else:
file.write(qasm_src)
return qasm_src
|
https://github.com/MonitSharma/qiskit-projects
|
MonitSharma
|
import numpy as np
import matplotlib.pyplot as plt
from docplex.mp.model import Model
from qiskit import BasicAer
from qiskit.algorithms import QAOA, NumPyMinimumEigensolver
from qiskit_optimization.algorithms import CplexOptimizer, MinimumEigenOptimizer
from qiskit_optimization.algorithms.admm_optimizer import ADMMParameters, ADMMOptimizer
from qiskit_optimization import QuadraticProgram
from qiskit_optimization.converters import QuadraticProgramToQubo
from qiskit.algorithms.optimizers import COBYLA
%matplotlib inline
np.random.seed(1)
num_items = 3 # number of items
num_bins = num_items # maximum number of bins
max_weight = 15 # max weight of a bin
weights = np.random.randint(1, max_weight, num_items) # Randomly picking the item weight
# Construct model using docplex
mdl = Model("BinPacking")
y = mdl.binary_var_list(num_bins, name="y") # list of variables that represent the bins
x = mdl.binary_var_matrix(num_items, num_bins, "x") # variables that represent the items on the specific bin
objective = mdl.sum(y)
mdl.minimize(objective)
for i in range(num_items):
# First set of constraints: the items must be in any bin
mdl.add_constraint(mdl.sum(x[i, j] for j in range(num_bins)) == 1)
for j in range(num_bins):
# Second set of constraints: weight constraints
mdl.add_constraint(mdl.sum(weights[i] * x[i, j] for i in range(num_items)) <= max_weight * y[j])
# Load quadratic program from docplex model
qp = QuadraticProgram()
qp.from_docplex(mdl)
qubo = QuadraticProgramToQubo().convert(qp)# Create a converter from quadratic program to qubo representation
print(f"The number of variables prior converting to QUBO is {qp.get_num_vars()}")
print(f"The number of variables after converting to QUBO is {qubo.get_num_vars()}")
plt.figure()
plt.bar(0, qp.get_num_vars(), label="Prior QUBO")
plt.bar(1, qubo.get_num_vars(), label="QUBO")
plt.xticks(range(2), 2 * [""])
plt.xlim((-1,2))
plt.legend()
plt.ylabel("Num. vars")
plt.title(f"Num. vars for {num_items} items")
def BinPacking(num_items, num_bins, weights, max_weight, simplification=False):
# Construct model using docplex
mdl = Model("BinPacking")
y = mdl.binary_var_list(num_bins, name="y") # list of variables that represent the bins
x = mdl.binary_var_matrix(num_items, num_bins, "x") # variables that represent the items on the specific bin
objective = mdl.sum(y)
mdl.minimize(objective)
for i in range(num_items):
# First set of constraints: the items must be in any bin
mdl.add_constraint(mdl.sum(x[i, j] for j in range(num_bins)) == 1)
for j in range(num_bins):
# Second set of constraints: weight constraints
mdl.add_constraint(mdl.sum(weights[i] * x[i, j] for i in range(num_items)) <= max_weight * y[j])
# Load quadratic program from docplex model
qp = QuadraticProgram()
qp.from_docplex(mdl)
if simplification:
l = int(np.ceil(np.sum(weights)/max_weight))
qp = qp.substitute_variables({f"y_{_}":1 for _ in range(l)}) # First simplification
qp = qp.substitute_variables({"x_0_0":1}) # Assign the first item into the first bin
qp = qp.substitute_variables({f"x_0_{_}":0 for _ in range(1, num_bins)}) # as the first item is in the first
#bin it couldn't be in the other bins
qubo = QuadraticProgramToQubo().convert(qp)# Create a converter from quadratic program to qubo representation
return qubo
qubo_simp = BinPacking(num_items, num_bins, weights, max_weight, simplification=True)
print(f"After the simplification, the number of variables is {qubo_simp.get_num_vars()}")
plt.figure()
plt.bar(0, qp.get_num_vars(), label="Prior QUBO")
plt.bar(1, qubo.get_num_vars(), label="QUBO")
plt.bar(2, qubo_simp.get_num_vars(), label="QUBO Simplifications")
plt.xticks(range(3), 3 * [""])
plt.xlim((-1,3))
plt.legend()
plt.ylabel("Num. vars")
plt.title(f"Num. vars for {num_items} items")
from qiskit import Aer
backend = Aer.get_backend("qasm_simulator")
def interpret(results, weights, num_items, num_bins, simplify=False):
"""
Save the results as a list of list where each sublist represent a bin
and the sublist elements represent the items weights
Args:
results: results of the optimization
weights (list): weights of the items
num_items: (int) number of items
num_bins: (int) number of bins
"""
if simplify:
l = int(np.ceil(np.sum(weights)/max_weight))
bins = l * [1] + list(results[:num_bins - l])
items = results[num_bins - l: (num_bins - l) + num_bins * (num_items - 1)].reshape(num_items - 1, num_bins)
items_in_bins = [[i+1 for i in range(num_items-1) if bins[j] and items[i, j]] for j in range(num_bins)]
items_in_bins[0].append(0)
else:
bins = results[:num_bins]
items = results[num_bins:(num_bins + 1) * num_items].reshape((num_items, num_bins))
items_in_bins = [[i for i in range(num_items) if bins[j] and items[i, j]] for j in range(num_bins)]
return items_in_bins
def get_figure(items_in_bins, weights, max_weight, title=None):
"""Get plot of the solution of the Bin Packing Problem.
Args:
result : The calculated result of the problem
Returns:
fig: A plot of the solution, where x and y represent the bins and
sum of the weights respectively.
"""
colors = plt.cm.get_cmap("jet", len(weights))
num_bins = len(items_in_bins)
fig, axes = plt.subplots()
for _, bin_i in enumerate(items_in_bins):
sum_items = 0
for item in bin_i:
axes.bar(_, weights[item], bottom=sum_items, label=f"Item {item}", color=colors(item))
sum_items += weights[item]
axes.hlines(max_weight, -0.5, num_bins - 0.5, linestyle="--", color="tab:red", label="Max Weight")
axes.set_xticks(np.arange(num_bins))
axes.set_xlabel("Bin")
axes.set_ylabel("Weight")
axes.legend()
if title:
axes.set_title(title)
return fig
qaoa = MinimumEigenOptimizer(QAOA(reps=3, quantum_instance=backend))
result_qaoa = qaoa.solve(qubo_simp)
print("Solving QUBO using QAOA")
print(result_qaoa)
print("Solving QUBO using CPLEX")
result_ideal = CplexOptimizer().solve(qubo_simp)
print(result_ideal)
fig = get_figure(interpret(result_ideal.x, weights, num_items, num_bins, simplify=True), weights, max_weight, title="CPLEX")
fig = get_figure(interpret(result_qaoa.x, weights, num_items, num_bins, simplify=True), weights, max_weight, title="QAOA")
max_weight = 15
num_qubits = {}
for i in range(2, 10):
num_items = i
num_bins = num_items
weights = [np.random.randint(1, max_weight) for _ in range(i)]
num_qubits[i] = BinPacking(num_items, num_bins, weights, max_weight, simplification=True).get_num_vars()
plt.figure()
plt.plot(num_qubits.keys(), num_qubits.values())
plt.xlabel("num items")
plt.ylabel("num qubits")
plt.grid()
print(f"The number of qubits is: {num_qubits}")
x = np.linspace(-2, 2, 100)
plt.figure()
plt.plot(x, np.exp(-x), label="Exponential")
plt.plot(x, 1 - (x) + (x) ** 2 / 2, label="Approximation")
plt.xlabel(r"$t = B - \sum_{i=1}^n s(i)*x_i$", fontsize=14)
plt.ylabel("penalization", fontsize=14)
plt.grid()
plt.legend()
def BinPackingNewApproach(num_items, num_bins, weights, max_weight, alpha=0.01, simplification=False):
# Construct model using docplex
mdl = Model("BinPackingNewApproach")
y = mdl.binary_var_list(num_bins, name="y") # list of variables that represent the bins
x = mdl.binary_var_matrix(num_items, num_bins, "x") # variables that represent the items on the specific bin
objective = mdl.sum(y)
# PENALIZATION
penalization = 0
for j in range(num_bins):
t = max_weight * y[j] - mdl.sum(weights[i] * x[i, j] for i in range(num_items))
penalization += -t + t**2 / 2
mdl.minimize(objective + alpha * penalization)
for i in range(num_items):
# First set of constraints: the items must be in any bin
mdl.add_constraint(mdl.sum(x[i, j] for j in range(num_bins)) == 1)
# Load quadratic program from docplex model
qp = QuadraticProgram()
qp.from_docplex(mdl)
if simplification:
l = int(np.ceil(np.sum(weights)/max_weight))
qp = qp.substitute_variables({f"y_{_}":1 for _ in range(l)}) # First simplification
qp = qp.substitute_variables({"x_0_0":1}) # Assign the first item into the first bin
qp = qp.substitute_variables({f"x_0_{_}":0 for _ in range(1, num_bins)}) # as the first item is in the first
#bin it couldn't be in the other bins
qubo = QuadraticProgramToQubo().convert(qp)# Create a converter from quadratic program to qubo representation
return qubo
max_weight = 15
num_qubits = {}
num_qubits_new = {}
for i in range(2, 10):
num_items = i
num_bins = num_items
weights = [np.random.randint(1, max_weight) for _ in range(i)]
num_qubits[i] = BinPacking(num_items, num_bins, weights, max_weight, simplification=True).get_num_vars()
num_qubits_new[i] = BinPackingNewApproach(num_items, num_bins, weights, max_weight, simplification=True).get_num_vars()
plt.figure()
plt.plot(num_qubits.keys(), num_qubits.values(), label="Current Approach")
plt.plot(num_qubits_new.keys(), num_qubits_new.values(), label="New Approach")
plt.xlabel("num items")
plt.ylabel("num qubits")
plt.grid()
plt.legend()
print(f"The number of qubits for the Classical approach is: {num_qubits}")
print(f"The number of qubits is for the new approach is: {num_qubits_new}")
np.random.seed(15)
num_items = 3 # number of items
num_bins = num_items # maximum number of bins
max_weight = 15 # max weight of a bin
weights = np.random.randint(1, max_weight, num_items) # Randomly picking the item weight
qubo_classical = BinPacking(num_items, num_bins, weights, max_weight, simplification=True)
qubo_new = BinPackingNewApproach(num_items, num_bins, weights, max_weight, alpha=0.05, simplification=True)
qaoa = MinimumEigenOptimizer(QAOA(optimizer=COBYLA(maxiter=10), reps=3, quantum_instance=backend))
result_qaoa_classical = qaoa.solve(qubo_classical)
result_qaoa_new = qaoa.solve(qubo_new)
result_cplex_classical = CplexOptimizer().solve(qubo_classical)
print("------------------------------------------")
print("Solving QUBO using QAOA Classical Approach")
print(result_qaoa_classical)
print("------------------------------------------")
print("Solving QUBO using QAOA New Approach")
print(result_qaoa_new)
print("------------------------------------------")
print("Solving QUBO using CPLEX")
print(result_cplex_classical)
print("------------------------------------------")
fig = get_figure(interpret(result_ideal_old.x, weights, num_items, num_bins, simplify=True), weights, max_weight, title="CPLEX")
fig = get_figure(interpret(result_qaoa_old.x, weights, num_items, num_bins, simplify=True), weights, max_weight, title="QAOA classical approach")
fig = get_figure(interpret(result_qaoa_new.x, weights, num_items, num_bins, simplify=True), weights, max_weight, title="QAOA New Approach")
solutions_new = []
solutions_classical = []
for _ in range(10):
result_qaoa_new = qaoa.solve(qubo_new)
result_qaoa_classical = qaoa.solve(qubo_classical)
solutions_new.append(result_qaoa_new.fval)
solutions_classical.append(result_qaoa_classical.fval)
num_vars = qubo_new.get_num_vars()
vars_new = qubo_new.variables
result_cplex = CplexOptimizer().solve(qubo_classical)
result_new_ideal = qubo_new.objective.evaluate(result_cplex.x[:num_vars])# Replacing the ideal solution into
#our new approach to see the optimal solution on the new objective
#function
ratio_new = (np.abs(1 - np.array(solutions_new) / result_new_ideal) < 0.05).sum()
ratio_classical = (np.abs(1 - np.array(solutions_classical) / result_cplex.fval) < 0.05).sum()
fig, ax = plt.subplots(1,2, figsize=(15,5))
ax[0].plot(range(1,11), solutions_new, color="tab:green",label="new QUBO QAOA")
ax[0].plot(range(1,11), solutions_classical, color="tab:red",label="classical QUBO QAOA")
ax[0].plot([1, 10], 2*[result_new_ideal], ":", color="tab:green", label="new QUBO optimal")
ax[0].plot([1, 10], 2*[result_cplex.fval], ":", color="tab:red", label="classical QUBO optimal")
ax[0].set_xlabel("n", fontsize=14)
ax[0].set_ylabel("Cost Obj. function", fontsize=14)
ax[0].grid()
ax[0].legend()
ax[1].bar(0, 100 * ratio_new / 10, label="new")
ax[1].bar(1, 100 * ratio_classical/ 10 + 0.5, label="Classical")
ax[1].legend()
ax[1].set_xticks([0,1])
ax[1].set_xticklabels(["", ""])
ax[1].set_ylabel("Ratio", fontsize=14)
def new_eq_optimal(qubo_new, qubo_classical):
"""
From the classical solution and considering that cplex solution is the optimal, we can traslate the optimal
solution to the QUBO representation based on our approach.
"""
num_vars = qubo_new.get_num_vars()
vars_new = qubo_new.variables
result_cplex = CplexOptimizer().solve(qubo_classical)
result_new_ideal = qubo_new.objective.evaluate(result_cplex.x[:num_vars])# Replacing the ideal solution into
#our new approach to see the optimal solution on the new objective
#function
return result_new_ideal
np.random.seed(1)
num_items = 3 # number of items
num_bins = num_items # maximum number of bins
max_weight = 15 # max weight of a bin
repetitions = 10
cases = 5
solutions_new = {}
optimal_new = []
ratio_new = []
for i in range(cases): # Testing 5 different randomly selected configurations of the problem
print(f"----------- Case {i+1} -------------")
weights = np.random.randint(1, max_weight, num_items) # Randomly picking the item weight
qubo_new = BinPackingNewApproach(num_items, num_bins, weights, max_weight, alpha=0.05, simplification=True)
qubo_classical = BinPacking(num_items, num_bins, weights, max_weight, simplification=True)
optimal_new.append(new_eq_optimal(qubo_new, qubo_classical))
solutions_new[i] = []
for _ in range(repetitions): #Testing the ratio
result_qaoa_new = qaoa.solve(qubo_new)
solutions_new[i].append(result_qaoa_new.fval)
ratio_new.append(100 * ((np.array(solutions_new[i]) / optimal_new[-1] - 1) < 5e-2).sum() / repetitions)
plt.figure()
plt.bar([i for i in range(1, cases + 1)], ratio_new)
plt.xlabel("Case")
plt.ylabel("Ratio")
np.random.seed(1)
num_items = 4 # number of items
num_bins = num_items # maximum number of bins
max_weight = 15 # max weight of a bin
repetitions = 10
cases = 5
solutions_new = {}
optimal_new = []
ratio_new = []
for i in range(cases): # Testing 5 different randomly selected configurations of the problem
print(f"----------- Case {i+1} -------------")
weights = np.random.randint(1, max_weight, num_items) # Randomly picking the item weight
qubo_new = BinPackingNewApproach(num_items, num_bins, weights, max_weight, alpha=0.05, simplification=True)
qubo_classical = BinPacking(num_items, num_bins, weights, max_weight, simplification=True)
optimal_new.append(new_eq_optimal(qubo_new, qubo_classical))
solutions_new[i] = []
for _ in range(repetitions): #Testing the ratio
result_qaoa_new = qaoa.solve(qubo_new)
solutions_new[i].append(result_qaoa_new.fval)
ratio_new.append(100 * ((np.array(solutions_new[i]) / optimal_new[-1] - 1) < 5e-2).sum() / repetitions)
plt.figure()
plt.bar([i for i in range(1, cases + 1)], ratio_new)
plt.xlabel("Case")
plt.ylabel("Ratio")
np.random.seed(1)
num_items = 5 # number of items
num_bins = num_items # maximum number of bins
max_weight = 15 # max weight of a bin
repetitions = 10
cases = 5
solutions_new = {}
optimal_new = []
ratio_new = []
qaoa = MinimumEigenOptimizer(QAOA(optimizer=COBYLA(maxiter=100), reps=4, quantum_instance=backend))
for i in range(cases): # Testing 5 different randomly selected configurations of the problem
print(f"----------- Case {i+1} -------------")
weights = np.random.randint(1, max_weight, num_items) # Randomly picking the item weight
qubo_new = BinPackingNewApproach(num_items, num_bins, weights, max_weight, alpha=0.05, simplification=True)
qubo_classical = BinPacking(num_items, num_bins, weights, max_weight, simplification=True)
optimal_new.append(new_eq_optimal(qubo_new, qubo_classical))
solutions_new[i] = []
for _ in range(repetitions): #Testing the ratio
result_qaoa_new = qaoa.solve(qubo_new)
solutions_new[i].append(result_qaoa_new.fval)
ratio_new.append(100 * ((np.array(solutions_new[i]) / optimal_new[-1] - 1) < 5e-2).sum() / repetitions)
plt.figure()
plt.bar([i for i in range(1, cases + 1)], ratio_new)
plt.xlabel("Case")
plt.ylabel("Ratio")
|
https://github.com/MonitSharma/qiskit-projects
|
MonitSharma
|
from functions import Knapsack,KnapsackNewApproach,new_eq_optimal_knapsack,get_figure_knapsack,eval_constrains_knapsack
from functions import mapping_cost
from qiskit.algorithms import QAOA, NumPyMinimumEigensolver
from qiskit_optimization.algorithms import CplexOptimizer, MinimumEigenOptimizer
from qiskit.algorithms.optimizers import COBYLA
import numpy as np
import matplotlib.pyplot as plt
from qiskit import Aer
backend = Aer.get_backend("qasm_simulator")
cases = 10
solutions_new = {}
optimal_new = []
ratio_new = []; new =[]
result_classical = []; result_qaoa_new = []
np.random.seed(15)
num_items = 4 # number of items
max_weight = 15 # max weight of a bin
values = np.random.randint(1, max_weight, num_items) # Randomly picking the item weight
weights = []#np.random.randint(1, max_weight, num_items) # Randomly picking the item weight
qaoa = MinimumEigenOptimizer(QAOA(optimizer=COBYLA(maxiter=100), reps=4, quantum_instance=backend))
for i in range(cases): # Testing 5 different randomly selected configurations of the problem
print(f"----------- Case {i+1} -------------")
weights.append(np.random.randint(1, max_weight, num_items)) # Randomly picking the item weight
qubo_classical, qp = Knapsack(values, weights[i], max_weight)
qubo_new = KnapsackNewApproach(values, weights[i], max_weight, alpha=1)
result_classical.append(CplexOptimizer().solve(qubo_classical))
optimal_new.append(new_eq_optimal_knapsack(qubo_new, qubo_classical))
result_qaoa_new.append(CplexOptimizer().solve(qubo_new))
solutions_new = result_qaoa_new[-1].fval
check_const = eval_constrains_knapsack(qp, result_qaoa_new[-1])
print(check_const)
for i in range(len(result_classical)):
fig = get_figure_knapsack(result_classical[i].x,values, weights[i], max_weight, title=f"-------Case {i+1}-----")
fig = get_figure_knapsack(result_qaoa_new[i].x,values, weights[i], max_weight, title="New")
n = 20
alpha = np.linspace(0, 2*np.pi, n)
beta = np.linspace(0, np.pi, n)
map_cost = mapping_cost(alpha, beta, qubo_new)
plt.figure(figsize=(10,10))
plt.imshow(map_cost)
plt.xticks([0,9,19], ["0", r"$\pi/2$", r"$\pi$"])
plt.yticks([0,9,19], ["0", r"$\pi$", r"2$\pi$"])
plt.xlabel(r"$\beta$", fontsize=22)
plt.ylabel(r"$\alpha$", fontsize=22)
|
https://github.com/MonitSharma/qiskit-projects
|
MonitSharma
|
import numpy as np
# Importing standard Qiskit libraries
from qiskit import QuantumCircuit, transpile, Aer, IBMQ
from qiskit.tools.jupyter import *
from qiskit.visualization import *
from ibm_quantum_widgets import *
from qiskit.providers.aer import QasmSimulator
# Loading your IBM Quantum account(s)
provider = IBMQ.load_account()
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import colors
from qiskit import IBMQ, assemble, transpile
from qiskit import QuantumCircuit
N_QUBITS = 20 # Number of qubits used in Google paper
# Load IBMQ cloud-based QASM simulator
provider = IBMQ.load_account()
backend = provider.backend.ibmq_qasm_simulator
def random_bitstring_circuit(n_qubits: int) -> QuantumCircuit:
"""
Args:
n_qubits: desired number of qubits in the bitstring
Returns:
QuantumCircuit: creates a random bitstring from the ground state
"""
qc = QuantumCircuit(n_qubits)
# Generate random bitstring
random_bitstring = np.random.randint(2, size=n_qubits)
# Apply X gate to nonzero qubits in bitstring
for i in range(n_qubits):
if random_bitstring[i]:
qc.x(i)
return qc
def floquet_circuit(n_qubits: int, g: float) -> QuantumCircuit:
"""
Args:
n_qubits: number of qubits
g: parameter controlling amount of x-rotation
Returns:
QuantumCircuit: circuit implementation of the unitary operator U_f as
detailed in https://arxiv.org/pdf/2107.13571.pdf
"""
qc = QuantumCircuit(n_qubits)
# X rotation by g*pi on all qubits (simulates the periodic driving pulse)
for i in range(n_qubits):
qc.rx(g*np.pi, i)
qc.barrier()
# Ising interaction (only couples adjacent spins with random coupling strengths)
for i in range(0, n_qubits-1, 2):
phi = np.random.uniform(low=0.5, high=1.5)
theta = -phi * np.pi / 2
qc.rzz(theta, i, i+1)
for i in range(1, n_qubits-1, 2):
phi = np.random.uniform(low=0.5, high=1.5)
theta = -phi * np.pi / 2
qc.rzz(theta, i, i+1)
qc.barrier()
# Longitudinal fields for disorder
for i in range(n_qubits):
h = np.random.uniform(low=-1, high=1)
qc.rz(h * np.pi, i)
return qc
def calculate_mean_polarization(n_qubits: int, counts: dict, q_index: int) -> float:
"""
Args:
n_qubits: total number of qubits
counts: dictionary of bitstring measurement outcomes and their respective total counts
q_index: index of qubit whose expected polarization we want to calculate
Returns:
float: the mean Z-polarization <Z>, in [-1, 1], of the qubit at q_index
"""
run, num_shots = 0, 0
for bitstring in counts.keys():
val = 1 if (int(bitstring[n_qubits-q_index-1]) == 0) else -1
run += val * counts[bitstring]
num_shots += counts[bitstring]
return run / num_shots
def calculate_two_point_correlations(series: list) -> list:
"""
Args:
series: time-ordered list of expectation values for some random variable
Returns:
list: two point correlations <f(0)f(t)> of the random variable evaluated at all t>0
"""
n = len(series)
data = np.asarray(series)
mean = np.mean(data)
c0 = np.sum((data - mean) ** 2) / float(n)
def r(h):
acf_lag = ((data[:n - h] - mean) * (data[h:] - mean)).sum() / float(n) / c0
return round(acf_lag, 3)
x = np.arange(n) # Avoiding lag 0 calculation
acf_coeffs = list(map(r, x))
return acf_coeffs
def simulate(n_qubits: int, initial_state: QuantumCircuit, max_time_steps: int, g: float) -> None:
mean_polarizations = np.zeros((n_qubits, max_time_steps+1))
floq_qc = floquet_circuit(n_qubits, g)
for t in range(0, max_time_steps+1):
if ((t % 5) == 0):
print('Time t=%d' % t)
qc = QuantumCircuit(n_qubits)
qc = qc.compose(initial_state)
for i in range(t):
qc = qc.compose(floq_qc)
qc.measure_all()
transpiled = transpile(qc, backend)
job = backend.run(transpiled)
retrieved_job = backend.retrieve_job(job.job_id())
counts = retrieved_job.result().get_counts()
for qubit in range(n_qubits):
mean_polarizations[qubit,t] = calculate_mean_polarization(n_qubits, counts, q_index=qubit)
return mean_polarizations
polarized_state = QuantumCircuit(N_QUBITS) # All qubits in |0> state
thermal_z = simulate(n_qubits=N_QUBITS,
initial_state=polarized_state,
max_time_steps=50,
g=0.6)
fig, ax = plt.subplots(figsize=(10,10))
im = ax.matshow(thermal_z, cmap='viridis')
plt.rcParams.update({'font.size': 15})
plt.rcParams['text.usetex'] = True
ax.set_xlabel('Floquet cycles (t)')
ax.xaxis.labelpad = 10
ax.set_ylabel('Qubit')
ax.set_xticks(np.arange(0, 51, 10))
ax.set_yticks(np.arange(0, N_QUBITS, 5))
ax.xaxis.set_label_position('top')
im.set_clim(-1, 1)
cbar = plt.colorbar(im, fraction=0.018, pad=0.04)
cbar.set_label(r'$\langle Z(t) \rangle$')
plt.show()
plt.plot(thermal_z[10,:], 'bs-')
plt.xlabel('Floquet cycles (t)')
plt.tick_params(axis="x", bottom=True, top=False, labelbottom=True, labeltop=False)
plt.ylabel(r'$\langle Z(t) \rangle$')
dtc_z = simulate(n_qubits=N_QUBITS,
initial_state=polarized_state,
max_time_steps=50,
g=0.97)
fig, ax = plt.subplots(figsize=(10,10))
im = ax.matshow(dtc_z, cmap='viridis')
plt.rcParams.update({'font.size': 15})
plt.rcParams['text.usetex'] = True
ax.set_xlabel('Floquet cycles (t)')
ax.xaxis.labelpad = 10
ax.set_ylabel('Qubit')
ax.set_xticks(np.arange(0, 51, 10))
ax.set_yticks(np.arange(0, N_QUBITS, 5))
ax.xaxis.set_label_position('top')
im.set_clim(-1, 1)
cbar = plt.colorbar(im, fraction=0.018, pad=0.04)
cbar.set_label(r'$\langle Z(t) \rangle$')
plt.show()
plt.plot(dtc_z[10,:], 'bs-')
plt.xlabel('Floquet cycles (t)')
plt.tick_params(axis="x", bottom=True, top=False, labelbottom=True, labeltop=False)
plt.ylabel(r'$\langle Z(t) \rangle$')
|
https://github.com/MonitSharma/qiskit-projects
|
MonitSharma
|
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/joshy91/PythonQiskit
|
joshy91
|
import numpy as np
import scipy
from scipy.linalg import expm
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler, MinMaxScaler
from sklearn.decomposition import PCA
import pandas as pd
from qiskit import BasicAer
from qiskit.aqua.input import ClassificationInput
from qiskit.aqua import run_algorithm
def Currency(training_size, test_size, n, PLOT_DATA):
class_labels = [r'Buy', r'Sell', r'Hold']
training_url = "https://raw.githubusercontent.com/joshy91/PythonQiskit/master/EURUSDTrainingData.csv"
training=pd.read_csv(training_url, sep=',',header=0)
trainingNP = training.to_numpy()
sample_train = trainingNP[:,:-2]
label_train = trainingNP[:,-2]
label_train[label_train == 'Buy'] = 0
label_train[label_train == 'Sell'] = 1
label_train[label_train == 'Hold'] = 2
test_url = "https://raw.githubusercontent.com/joshy91/PythonQiskit/master/EURUSDTestData.csv"
test=pd.read_csv(test_url, sep=',',header=0)
testNP = test.to_numpy()
sample_test = testNP[:,:-2]
label_test = testNP[:,-2]
label_test[label_test == 'Buy'] = 0
label_test[label_test == 'Sell'] = 1
label_test[label_test == 'Hold'] = 2
# Now we standarize for gaussian around 0 with unit variance
std_scale = StandardScaler().fit(sample_train)
sample_train = std_scale.transform(sample_train)
sample_test = std_scale.transform(sample_test)
# Now reduce number of features to number of qubits
pca = PCA(n_components=n).fit(sample_train)
sample_train = pca.transform(sample_train)
sample_test = pca.transform(sample_test)
# Scale to the range (-1,+1)
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)
# Pick training size number of samples from each distro
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)}
if PLOT_DATA:
for k in range(0, 3):
plt.scatter(sample_train[label_train == k, 0][:training_size],
sample_train[label_train == k, 1][:training_size])
plt.title("PCA dim. reduced Currency dataset")
plt.show()
return sample_train, training_input, test_input, class_labels
n = 2 # dimension of each data point
sample_Total, training_input, test_input, class_labels = Currency(
training_size=80,
test_size=20, n=n, PLOT_DATA=True
)
temp = [test_input[k] for k in test_input]
total_array = np.concatenate(temp)
aqua_dict = {
'problem': {'name': 'classification', 'random_seed': 10598},
'algorithm': {
'name': 'QSVM'
},
'feature_map': {'name': 'SecondOrderExpansion', 'depth': 2, 'entangler_map': [[0, 1]]},
'multiclass_extension': {'name': 'AllPairs'},
'backend': {'shots': 1024}
}
backend = BasicAer.get_backend('qasm_simulator')
algo_input = ClassificationInput(training_input, test_input, total_array)
result = run_algorithm(aqua_dict, algo_input, backend=backend)
for k,v in result.items():
print("'{}' : {}".format(k, v))
|
https://github.com/joshy91/PythonQiskit
|
joshy91
|
import numpy as np
import scipy
from scipy.linalg import expm
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler, MinMaxScaler
from sklearn.decomposition import PCA
import pandas as pd
from qiskit import BasicAer
from qiskit.aqua.input import ClassificationInput
from qiskit.aqua import run_algorithm
def Currency(training_size, test_size, n, PLOT_DATA):
class_labels = [r'Buy', r'Sell', r'Hold']
training_url = "https://drive.google.com/file/d/1dGr9w629hZMlHcTvNw1sGlhm3J57osze/view?usp=sharing"
training=pd.read_csv(training_url, sep=',',header=0)
trainingNP = training.to_numpy()
sample_train = trainingNP[:,:-2]
label_train = trainingNP[:,-2]
label_train[label_train == 'Buy'] = 0
label_train[label_train == 'Sell'] = 1
label_train[label_train == 'Hold'] = 2
test_url = "https://drive.google.com/file/d/1wsyURMe0wRXysJvLn1T9bXIsMqd8MocG/view?usp=sharing"
test=pd.read_csv(test_url, sep=',',header=0)
testNP = test.to_numpy()
sample_test = testNP[:,:-2]
label_test = testNP[:,-2]
label_test[label_test == 'Buy'] = 0
label_test[label_test == 'Sell'] = 1
label_test[label_test == 'Hold'] = 2
# Now we standarize for gaussian around 0 with unit variance
std_scale = StandardScaler().fit(sample_train)
sample_train = std_scale.transform(sample_train)
sample_test = std_scale.transform(sample_test)
# Now reduce number of features to number of qubits
pca = PCA(n_components=n).fit(sample_train)
sample_train = pca.transform(sample_train)
sample_test = pca.transform(sample_test)
# Scale to the range (-1,+1)
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)
# Pick training size number of samples from each distro
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)}
if PLOT_DATA:
for k in range(0, 3):
plt.scatter(sample_train[label_train == k, 0][:training_size],
sample_train[label_train == k, 1][:training_size])
plt.title("PCA dim. reduced Currency dataset")
plt.show()
return sample_train, training_input, test_input, class_labels
n = 2 # dimension of each data point
sample_Total, training_input, test_input, class_labels = Currency(
training_size=80,
test_size=20, n=n, PLOT_DATA=True
)
temp = [test_input[k] for k in test_input]
total_array = np.concatenate(temp)
aqua_dict = {
'problem': {'name': 'classification', 'random_seed': 10598},
'algorithm': {
'name': 'QSVM'
},
'feature_map': {'name': 'SecondOrderExpansion', 'depth': 2, 'entangler_map': [[0, 1]]},
'multiclass_extension': {'name': 'AllPairs'},
'backend': {'shots': 1024}
}
backend = BasicAer.get_backend('qasm_simulator')
algo_input = ClassificationInput(training_input, test_input, total_array)
result = run_algorithm(aqua_dict, algo_input, backend=backend)
for k,v in result.items():
print("'{}' : {}".format(k, v))
|
https://github.com/joshy91/PythonQiskit
|
joshy91
|
import numpy as np
import scipy
from scipy.linalg import expm
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler, MinMaxScaler
from sklearn.decomposition import PCA
import pandas as pd
from qiskit import BasicAer
from qiskit.aqua.input import ClassificationInput
from qiskit.aqua import run_algorithm, QuantumInstance, aqua_globals
from qiskit.aqua.components.optimizers import SPSA, COBYLA
def Currency(training_size, test_size, n, PLOT_DATA):
class_labels = [r'Buy', r'Sell', r'Hold']
training_url = "https://raw.githubusercontent.com/joshy91/PythonQiskit/master/EURUSDTrainingData.csv"
training=pd.read_csv(training_url, sep=',',header=0)
trainingNP = training.to_numpy()
sample_train = trainingNP[:,:-2]
label_train = trainingNP[:,-2]
label_train[label_train == 'Buy'] = 0
label_train[label_train == 'Sell'] = 1
label_train[label_train == 'Hold'] = 2
test_url = "https://raw.githubusercontent.com/joshy91/PythonQiskit/master/EURUSDTestData.csv"
test=pd.read_csv(test_url, sep=',',header=0)
testNP = test.to_numpy()
sample_test = testNP[:,:-2]
label_test = testNP[:,-2]
label_test[label_test == 'Buy'] = 0
label_test[label_test == 'Sell'] = 1
label_test[label_test == 'Hold'] = 2
# Now we standarize for gaussian around 0 with unit variance
std_scale = StandardScaler().fit(sample_train)
sample_train = std_scale.transform(sample_train)
sample_test = std_scale.transform(sample_test)
# Now reduce number of features to number of qubits
pca = PCA(n_components=n).fit(sample_train)
sample_train = pca.transform(sample_train)
sample_test = pca.transform(sample_test)
# Scale to the range (-1,+1)
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)
# Pick training size number of samples from each distro
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)}
if PLOT_DATA:
for k in range(0, 3):
plt.scatter(sample_train[label_train == k, 0][:training_size],
sample_train[label_train == k, 1][:training_size])
plt.title("PCA dim. reduced Currency dataset")
plt.show()
return sample_train, training_input, test_input, class_labels
import numpy as np
import scipy
from qiskit import BasicAer
from qiskit.aqua.input import ClassificationInput
from qiskit.aqua import run_algorithm, QuantumInstance, aqua_globals
from qiskit.aqua.components.optimizers import SPSA, COBYLA
feature_dim = 4 # dimension of each data point
training_dataset_size = 80
testing_dataset_size = 20
random_seed = 10598
np.random.seed(random_seed)
sample_Total, training_input, test_input, class_labels = Currency(
training_size=training_dataset_size,
test_size=testing_dataset_size,
n=feature_dim, PLOT_DATA=False
)
classification_input = ClassificationInput(training_input, test_input)
params = {
'problem': {'name': 'classification', 'random_seed': random_seed},
'algorithm': {'name': 'VQC'},
'backend': {'provider': 'qiskit.BasicAer', 'name': 'statevector_simulator'},
'optimizer': {'name': 'COBYLA', 'maxiter':200},
'variational_form': {'name': 'RYRZ', 'depth': 3},
'feature_map': {'name': None},
}
params['feature_map']['name'] = 'RawFeatureVector'
result = run_algorithm(params, classification_input)
print("VQC accuracy with RawFeatureVector: ", result['testing_accuracy'])
params['feature_map']['name'] = 'SecondOrderExpansion'
result = run_algorithm(params, classification_input)
print("Test accuracy with SecondOrderExpansion: ", result['testing_accuracy'])
|
https://github.com/joshy91/PythonQiskit
|
joshy91
|
import numpy as np
import scipy
from scipy.linalg import expm
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler, MinMaxScaler
from sklearn.decomposition import PCA
import pandas as pd
from qiskit import BasicAer
from qiskit.aqua.input import ClassificationInput
from qiskit.aqua import run_algorithm
def Currency(training_size, test_size, n, PLOT_DATA):
class_labels = [r'Buy', r'Sell', r'Hold']
training_url = "https://drive.google.com/file/d/1dGr9w629hZMlHcTvNw1sGlhm3J57osze/view?usp=sharing"
training=pd.read_csv(training_url, sep=',',header=0)
trainingNP = training.to_numpy()
sample_train = trainingNP[:,:-2]
label_train = trainingNP[:,-2]
label_train[label_train == 'Buy'] = 0
label_train[label_train == 'Sell'] = 1
label_train[label_train == 'Hold'] = 2
test_url = "https://drive.google.com/file/d/1wsyURMe0wRXysJvLn1T9bXIsMqd8MocG/view?usp=sharing"
test=pd.read_csv(test_url, sep=',',header=0)
testNP = test.to_numpy()
sample_test = testNP[:,:-2]
label_test = testNP[:,-2]
label_test[label_test == 'Buy'] = 0
label_test[label_test == 'Sell'] = 1
label_test[label_test == 'Hold'] = 2
# Now we standarize for gaussian around 0 with unit variance
std_scale = StandardScaler().fit(sample_train)
sample_train = std_scale.transform(sample_train)
sample_test = std_scale.transform(sample_test)
# Now reduce number of features to number of qubits
pca = PCA(n_components=n).fit(sample_train)
sample_train = pca.transform(sample_train)
sample_test = pca.transform(sample_test)
# Scale to the range (-1,+1)
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)
# Pick training size number of samples from each distro
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)}
if PLOT_DATA:
for k in range(0, 3):
plt.scatter(sample_train[label_train == k, 0][:training_size],
sample_train[label_train == k, 1][:training_size])
plt.title("PCA dim. reduced Currency dataset")
plt.show()
return sample_train, training_input, test_input, class_labels
n = 2 # dimension of each data point
sample_Total, training_input, test_input, class_labels = Currency(
training_size=80,
test_size=20, n=n, PLOT_DATA=True
)
temp = [test_input[k] for k in test_input]
total_array = np.concatenate(temp)
aqua_dict = {
'problem': {'name': 'classification', 'random_seed': 10598},
'algorithm': {
'name': 'QSVM'
},
'feature_map': {'name': 'SecondOrderExpansion', 'depth': 2, 'entangler_map': [[0, 1]]},
'multiclass_extension': {'name': 'AllPairs'},
'backend': {'shots': 1024}
}
backend = BasicAer.get_backend('qasm_simulator')
algo_input = ClassificationInput(training_input, test_input, total_array)
result = run_algorithm(aqua_dict, algo_input, backend=backend)
for k,v in result.items():
print("'{}' : {}".format(k, v))
|
https://github.com/joshy91/PythonQiskit
|
joshy91
|
import numpy as np
import scipy
from scipy.linalg import expm
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler, MinMaxScaler
from sklearn.decomposition import PCA
import pandas as pd
from qiskit import BasicAer
from qiskit.aqua.input import ClassificationInput
from qiskit.aqua import run_algorithm, QuantumInstance, aqua_globals
from qiskit.aqua.components.optimizers import SPSA, COBYLA
def Currency(training_size, test_size, n, PLOT_DATA):
class_labels = [r'Buy', r'Sell', r'Hold']
training_url = "https://raw.githubusercontent.com/joshy91/PythonQiskit/master/EURUSDTrainingData.csv"
training=pd.read_csv(training_url, sep=',',header=0)
trainingNP = training.to_numpy()
sample_train = trainingNP[:,:-2]
label_train = trainingNP[:,-2]
label_train[label_train == 'Buy'] = 0
label_train[label_train == 'Sell'] = 1
label_train[label_train == 'Hold'] = 2
test_url = "https://raw.githubusercontent.com/joshy91/PythonQiskit/master/EURUSDTestData.csv"
test=pd.read_csv(test_url, sep=',',header=0)
testNP = test.to_numpy()
sample_test = testNP[:,:-2]
label_test = testNP[:,-2]
label_test[label_test == 'Buy'] = 0
label_test[label_test == 'Sell'] = 1
label_test[label_test == 'Hold'] = 2
# Now we standarize for gaussian around 0 with unit variance
std_scale = StandardScaler().fit(sample_train)
sample_train = std_scale.transform(sample_train)
sample_test = std_scale.transform(sample_test)
# Now reduce number of features to number of qubits
pca = PCA(n_components=n).fit(sample_train)
sample_train = pca.transform(sample_train)
sample_test = pca.transform(sample_test)
# Scale to the range (-1,+1)
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)
# Pick training size number of samples from each distro
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)}
if PLOT_DATA:
for k in range(0, 3):
plt.scatter(sample_train[label_train == k, 0][:training_size],
sample_train[label_train == k, 1][:training_size])
plt.title("PCA dim. reduced Currency dataset")
plt.show()
return sample_train, training_input, test_input, class_labels
import numpy as np
import scipy
from qiskit import BasicAer
from qiskit.aqua.input import ClassificationInput
from qiskit.aqua import run_algorithm, QuantumInstance, aqua_globals
from qiskit.aqua.components.optimizers import SPSA, COBYLA
feature_dim = 4 # dimension of each data point
training_dataset_size = 80
testing_dataset_size = 20
random_seed = 10598
np.random.seed(random_seed)
sample_Total, training_input, test_input, class_labels = Currency(
training_size=training_dataset_size,
test_size=testing_dataset_size,
n=feature_dim, PLOT_DATA=False
)
classification_input = ClassificationInput(training_input, test_input)
params = {
'problem': {'name': 'classification', 'random_seed': random_seed},
'algorithm': {'name': 'VQC'},
'backend': {'provider': 'qiskit.BasicAer', 'name': 'statevector_simulator'},
'optimizer': {'name': 'COBYLA', 'maxiter':200},
'variational_form': {'name': 'RYRZ', 'depth': 3},
'feature_map': {'name': None},
}
params['feature_map']['name'] = 'RawFeatureVector'
result = run_algorithm(params, classification_input)
print("VQC accuracy with RawFeatureVector: ", result['testing_accuracy'])
params['feature_map']['name'] = 'SecondOrderExpansion'
result = run_algorithm(params, classification_input)
print("Test accuracy with SecondOrderExpansion: ", result['testing_accuracy'])
|
https://github.com/toticavalcanti/qiskit_examples
|
toticavalcanti
|
from qiskit import IBMQ
IBMQ.save_account('seu token')
from qiskit import *
qr = QuantumRegister(2)
cr = ClassicalRegister(2)
circuit = QuantumCircuit(qr, cr)
%matplotlib inline
circuit.draw()
circuit.h(0)
circuit.draw(output='mpl')
circuit.cx(0,1) # order is: control(0) and target(1)
circuit.draw(output='mpl')
circuit.measure(qr, cr)
circuit.draw(output='mpl')
simulator = Aer.get_backend('qasm_simulator')
result = execute(circuit, backend=simulator).result()
from qiskit.visualization import plot_histogram
plot_histogram(result.get_counts(circuit))
IBMQ.load_account()
provider = IBMQ.get_provider('ibm-q')
qcomp = provider.get_backend('ibmq_16_melbourne')
job = execute(circuit, backend=qcomp)
from qiskit.tools.monitor import job_monitor
job_monitor(job)
|
https://github.com/qBraid/qBraid
|
qBraid
|
# Copyright (C) 2024 qBraid
#
# This file is part of the qBraid-SDK
#
# The qBraid-SDK is free software released under the GNU General Public License v3
# or later. You can redistribute and/or modify it under the terms of the GPL v3.
# See the LICENSE file in the project root or <https://www.gnu.org/licenses/gpl-3.0.html>.
#
# THERE IS NO WARRANTY for the qBraid-SDK, as per Section 15 of the GPL v3.
"""
Module for generating random Qiskit circuits
"""
from qiskit import QuantumCircuit
from qiskit.circuit.exceptions import CircuitError
from qiskit.circuit.random import random_circuit
from qbraid.exceptions import QbraidError
def _qiskit_random(num_qubits: int, depth: int, **kwargs) -> QuantumCircuit:
"""Generate random circuit qiskit circuit.
Args:
num_qubits (int): number of quantum wires
depth (int): layers of operations (i.e. critical path length)
Raises:
QbraidError: When invalid qiskit random circuit options given
Returns:
Qiskit random circuit
"""
if "measure" not in kwargs:
kwargs["measure"] = False
try:
return random_circuit(num_qubits, depth, **kwargs)
except CircuitError as err:
raise QbraidError("Failed to create Qiskit random circuit") from err
|
https://github.com/qBraid/qBraid
|
qBraid
|
# Copyright (C) 2024 qBraid
#
# This file is part of the qBraid-SDK
#
# The qBraid-SDK is free software released under the GNU General Public License v3
# or later. You can redistribute and/or modify it under the terms of the GPL v3.
# See the LICENSE file in the project root or <https://www.gnu.org/licenses/gpl-3.0.html>.
#
# THERE IS NO WARRANTY for the qBraid-SDK, as per Section 15 of the GPL v3.
"""
Module defining QiskitCircuit Class
"""
from collections import OrderedDict
from typing import TYPE_CHECKING
import qiskit
from qiskit.circuit import Qubit
from qiskit.converters import circuit_to_dag, dag_to_circuit
from qiskit.quantum_info import Operator
from qbraid.programs.exceptions import ProgramTypeError
from ._model import GateModelProgram
if TYPE_CHECKING:
import numpy as np
from qbraid.runtime.qiskit import QiskitBackend
class QiskitCircuit(GateModelProgram):
"""Wrapper class for ``qiskit.QuantumCircuit`` objects"""
def __init__(self, program: "qiskit.QuantumCircuit"):
super().__init__(program)
if not isinstance(program, qiskit.QuantumCircuit):
raise ProgramTypeError(
message=f"Expected 'qiskit.QuantumCircuit' object, got '{type(program)}'."
)
@property
def qubits(self) -> list[Qubit]:
"""Return the qubits acted upon by the operations in this circuit"""
return self.program.qubits
@property
def num_qubits(self) -> int:
"""Return the number of qubits in the circuit."""
return self.program.num_qubits
@property
def num_clbits(self) -> int:
"""Return the number of classical bits in the circuit."""
return self.program.num_clbits
@property
def depth(self) -> int:
"""Return the circuit depth (i.e., length of critical path)."""
return self.program.depth()
def _unitary(self) -> "np.ndarray":
"""Calculate unitary of circuit. Removes measurement gates to
perform calculation if necessary."""
circuit = self.program.copy()
circuit.remove_final_measurements()
return Operator(circuit).data
def remove_idle_qubits(self) -> None:
"""Checks whether the circuit uses contiguous qubits/indices,
and if not, reduces dimension accordingly."""
circuit = self.program.copy()
dag = circuit_to_dag(circuit)
idle_wires = list(dag.idle_wires())
for w in idle_wires:
dag._remove_idle_wire(w)
dag.qubits.remove(w)
dag.qregs = OrderedDict()
self._program = dag_to_circuit(dag)
def reverse_qubit_order(self) -> None:
"""Reverse the order of the qubits in the circuit."""
circuit = self.program.copy()
reversed_circuit = circuit.reverse_bits()
self._program = reversed_circuit
def transform(self, device) -> None:
"""Transform program to according to device target profile."""
device_type = device.profile.get("device_type")
if device_type == "LOCAL_SIMULATOR":
self.remove_idle_qubits()
self._program = qiskit.transpile(self.program, backend=device._backend)
|
https://github.com/qBraid/qBraid
|
qBraid
|
# Copyright (C) 2024 qBraid
#
# This file is part of the qBraid-SDK
#
# The qBraid-SDK is free software released under the GNU General Public License v3
# or later. You can redistribute and/or modify it under the terms of the GPL v3.
# See the LICENSE file in the project root or <https://www.gnu.org/licenses/gpl-3.0.html>.
#
# THERE IS NO WARRANTY for the qBraid-SDK, as per Section 15 of the GPL v3.
"""
Module defining QiskitBackend Class
"""
from typing import TYPE_CHECKING, Optional, Union
from qiskit_ibm_runtime import QiskitRuntimeService
from qbraid.programs import load_program
from qbraid.runtime.device import QuantumDevice
from qbraid.runtime.enums import DeviceStatus, DeviceType
from .job import QiskitJob
if TYPE_CHECKING:
import qiskit
import qiskit_ibm_runtime
import qbraid.runtime.qiskit
class QiskitBackend(QuantumDevice):
"""Wrapper class for IBM Qiskit ``Backend`` objects."""
def __init__(
self,
profile: "qbraid.runtime.TargetProfile",
service: "Optional[qiskit_ibm_runtime.QiskitRuntimeService]" = None,
):
"""Create a QiskitBackend."""
super().__init__(profile=profile)
self._service = service or QiskitRuntimeService()
self._backend = self._service.backend(self.id, instance=self.profile.get("instance"))
def __str__(self):
"""Official string representation of QuantumDevice object."""
return f"{self.__class__.__name__}('{self.id}')"
def status(self):
"""Return the status of this Device.
Returns:
str: The status of this Device
"""
if self.device_type == DeviceType.LOCAL_SIMULATOR:
return DeviceStatus.ONLINE
status = self._backend.status()
if status.operational:
if status.status_msg == "active":
return DeviceStatus.ONLINE
return DeviceStatus.UNAVAILABLE
return DeviceStatus.OFFLINE
def queue_depth(self) -> int:
"""Return the number of jobs in the queue for the ibm backend"""
if self.device_type == DeviceType.LOCAL_SIMULATOR:
return 0
return self._backend.status().pending_jobs
def transform(self, run_input: "qiskit.QuantumCircuit") -> "qiskit.QuantumCircuit":
"""Transpile a circuit for the device."""
program = load_program(run_input)
program.transform(self)
return program.program
def submit(
self,
run_input: "Union[qiskit.QuantumCircuit, list[qiskit.QuantumCircuit]]",
*args,
**kwargs,
) -> "qbraid.runtime.qiskit.QiskitJob":
"""Runs circuit(s) on qiskit backend via :meth:`~qiskit.execute`
Uses the :meth:`~qiskit.execute` method to create a :class:`~qiskit.providers.QuantumJob`
object, applies a :class:`~qbraid.runtime.qiskit.QiskitJob`, and return the result.
Args:
run_input: A circuit object to run on the IBM device.
Keyword Args:
shots (int): The number of times to run the task on the device. Default is 1024.
Returns:
qbraid.runtime.qiskit.QiskitJob: The job like object for the run.
"""
backend = self._backend
shots = kwargs.pop("shots", backend.options.get("shots"))
memory = kwargs.pop("memory", True) # Needed to get measurements
job = backend.run(run_input, *args, shots=shots, memory=memory, **kwargs)
return QiskitJob(job.job_id(), job=job, device=self)
|
https://github.com/qBraid/qBraid
|
qBraid
|
'''
qiskitpool/job.py
Contains the QJob class
'''
from functools import partial
from qiskit import execute
class QJob():
'''
QJob
Job manager for asynch qiskit backends
'''
def __init__(self, *args, qjob_id=None, **kwargs):
'''
QJob.__init__
Initialiser for a qiksit job
:: *args :: Args for qiskit execute
:: **kwargs :: Kwargs for qiskit execute
'''
self.job_fn = partial(execute, *args, **kwargs)
self.job = None
self.done = False
self.test_count = 10
self.qjob_id = qjob_id
def __call__(self):
'''
QJob.__call__
Wrapper for QJob.run
'''
return self.run()
def run(self):
'''
QJob.run
Send async job to qiskit backend
'''
self.job = self.job_fn()
return self
def poll(self):
'''
QJob.poll
Poll qiskit backend for job completion status
'''
if self.job is not None:
return self.job.done()
return False
def cancel(self):
'''
QJob.cancel
Cancel job on backend
'''
if self.job is None:
return None
return self.job.cancel()
def position(self):
pos = self.job.queue_position()
if pos is None:
return 0
return pos
def status(self):
if self.job is None:
return 'LOCAL QUEUE'
else:
status = self.job.status().value
if 'running' in status:
return 'RUNNING'
if 'run' in status:
return 'COMPLETE'
if 'validated' in status:
return 'VALIDATING'
if 'queued' in status:
pos = self.position()
return f'QISKIT QUEUE: {self.position()}'
def status_short(self):
if self.job is None:
return ' '
else:
status = self.job.status().value
if 'running' in status:
return 'R'
if 'run' in status:
return 'C'
if 'validated' in status:
return 'V'
if 'queued' in status:
return str(self.position())
def result(self):
'''
QJob.result
Get result from backend
Non blocking - returns False if a job is not yet ready
'''
if self.poll():
return self.job.result()
return False
|
https://github.com/qBraid/qBraid
|
qBraid
|
# Copyright (C) 2024 qBraid
#
# This file is part of the qBraid-SDK
#
# The qBraid-SDK is free software released under the GNU General Public License v3
# or later. You can redistribute and/or modify it under the terms of the GPL v3.
# See the LICENSE file in the project root or <https://www.gnu.org/licenses/gpl-3.0.html>.
#
# THERE IS NO WARRANTY for the qBraid-SDK, as per Section 15 of the GPL v3.
"""
Module for configuring IBM provider credentials and authentication.
"""
import os
from typing import TYPE_CHECKING, Optional
import qiskit
from qiskit_ibm_runtime import QiskitRuntimeService
from qiskit_ibm_runtime.accounts import ChannelType
from qbraid.programs import ProgramSpec
from qbraid.runtime.enums import DeviceType
from qbraid.runtime.profile import TargetProfile
from qbraid.runtime.provider import QuantumProvider
from .device import QiskitBackend
if TYPE_CHECKING:
import qiskit_ibm_runtime
import qbraid.runtime.qiskit
class QiskitRuntimeProvider(QuantumProvider):
"""
This class is responsible for managing the interactions and
authentications with the IBM Quantum services.
Attributes:
token (str): IBM Cloud API key or IBM Quantum API token.
runtime_service (qiskit_ibm_runtime.QiskitRuntimeService): IBM Quantum runtime service.
"""
def __init__(
self, token: Optional[str] = None, channel: Optional[ChannelType] = None, **kwargs
):
"""
Initializes the QbraidProvider object with optional AWS and IBM Quantum credentials.
Args:
token (str, optional): IBM Quantum token. Defaults to None.
"""
self.token = token or os.getenv("QISKIT_IBM_TOKEN")
self.channel = channel or os.getenv("QISKIT_IBM_CHANNEL", "ibm_quantum")
self._runtime_service = QiskitRuntimeService(
token=self.token, channel=self.channel, **kwargs
)
@property
def runtime_service(self) -> "qiskit_ibm_runtime.QiskitRuntimeService":
"""Returns the IBM Quantum runtime service."""
return self._runtime_service
def save_config(
self,
token: Optional[str] = None,
channel: Optional[str] = None,
overwrite: bool = True,
**kwargs,
) -> None:
"""Saves IBM runtime service account to disk for future use."""
token = token or self.token
channel = channel or self.channel
QiskitRuntimeService.save_account(
token=token, channel=channel, overwrite=overwrite, **kwargs
)
def _build_runtime_profile(
self, backend: "qiskit_ibm_runtime.IBMBackend", program_spec: Optional[ProgramSpec] = None
) -> TargetProfile:
"""Builds a runtime profile from a backend."""
program_spec = program_spec or ProgramSpec(qiskit.QuantumCircuit)
config = backend.configuration()
if config.local:
device_type = DeviceType.LOCAL_SIMULATOR
elif config.simulator:
device_type = DeviceType.SIMULATOR
else:
device_type = DeviceType.QPU
return TargetProfile(
device_id=backend.name,
device_type=device_type,
num_qubits=config.n_qubits,
program_spec=program_spec,
instance=backend._instance,
max_shots=config.max_shots,
provider_name="IBM",
)
def get_devices(
self, operational=True, **kwargs
) -> list["qbraid.runtime.qiskit.QiskitBackend"]:
"""Returns the IBM Quantum provider backends."""
backends = self.runtime_service.backends(operational=operational, **kwargs)
program_spec = ProgramSpec(qiskit.QuantumCircuit)
return [
QiskitBackend(
profile=self._build_runtime_profile(backend, program_spec=program_spec),
service=self.runtime_service,
)
for backend in backends
]
def get_device(
self, device_id: str, instance: Optional[str] = None
) -> "qbraid.runtime.qiskit.QiskitBackend":
"""Returns the IBM Quantum provider backends."""
backend = self.runtime_service.backend(device_id, instance=instance)
return QiskitBackend(
profile=self._build_runtime_profile(backend), service=self.runtime_service
)
def least_busy(
self, simulator=False, operational=True, **kwargs
) -> "qbraid.runtime.qiskit.QiskitBackend":
"""Return the least busy IBMQ QPU."""
backend = self.runtime_service.least_busy(
simulator=simulator, operational=operational, **kwargs
)
return QiskitBackend(
profile=self._build_runtime_profile(backend), service=self.runtime_service
)
|
https://github.com/qBraid/qBraid
|
qBraid
|
# Copyright (C) 2024 qBraid
#
# This file is part of the qBraid-SDK
#
# The qBraid-SDK is free software released under the GNU General Public License v3
# or later. You can redistribute and/or modify it under the terms of the GPL v3.
# See the LICENSE file in the project root or <https://www.gnu.org/licenses/gpl-3.0.html>.
#
# THERE IS NO WARRANTY for the qBraid-SDK, as per Section 15 of the GPL v3.
"""
Module defining Amazon Braket conversion extras.
"""
from typing import TYPE_CHECKING
from qbraid_core._import import LazyLoader
from qbraid.transpiler.annotations import requires_extras
qiskit_braket_provider = LazyLoader("qiskit_braket_provider", globals(), "qiskit_braket_provider")
pytket_braket = LazyLoader("pytket_braket", globals(), "pytket.extensions.braket")
if TYPE_CHECKING:
import braket.circuits
import pytket.circuit
import qiskit.circuit
@requires_extras("qiskit_braket_provider")
def braket_to_qiskit(circuit: "braket.circuits.Circuit") -> "qiskit.circuit.QuantumCircuit":
"""Return a Qiskit quantum circuit from a Braket quantum circuit.
Args:
circuit (Circuit): Braket quantum circuit
Returns:
QuantumCircuit: Qiskit quantum circuit
"""
return qiskit_braket_provider.providers.adapter.to_qiskit(circuit)
@requires_extras("pytket.extensions.braket")
def braket_to_pytket(circuit: "braket.circuits.Circuit") -> "pytket.circuit.Circuit":
"""Returns a pytket circuit equivalent to the input Amazon Braket circuit.
Args:
circuit (braket.circuits.Circuit): Braket circuit to convert to a pytket circuit.
Returns:
pytket.circuit.Circuit: PyTKET circuit object equivalent to input Braket circuit.
"""
return pytket_braket.braket_convert.braket_to_tk(circuit)
|
https://github.com/qBraid/qBraid
|
qBraid
|
# Copyright (C) 2024 qBraid
#
# This file is part of the qBraid-SDK
#
# The qBraid-SDK is free software released under the GNU General Public License v3
# or later. You can redistribute and/or modify it under the terms of the GPL v3.
# See the LICENSE file in the project root or <https://www.gnu.org/licenses/gpl-3.0.html>.
#
# THERE IS NO WARRANTY for the qBraid-SDK, as per Section 15 of the GPL v3.
"""
Module defining Qiskit OpenQASM conversions
"""
from typing import TYPE_CHECKING
from qbraid_core._import import LazyLoader
from qbraid.transpiler.annotations import weight
qiskit = LazyLoader("qiskit", globals(), "qiskit")
if TYPE_CHECKING:
import qiskit as qiskit_
@weight(1)
def qasm2_to_qiskit(qasm: str) -> "qiskit_.QuantumCircuit":
"""Returns a Qiskit circuit equivalent to the input OpenQASM 2 string.
Args:
qasm: OpenQASM 2 string to convert to a Qiskit circuit.
Returns:
Qiskit.QuantumCircuit object equivalent to the input OpenQASM 2 string.
"""
return qiskit.QuantumCircuit.from_qasm_str(qasm)
|
https://github.com/qBraid/qBraid
|
qBraid
|
# Copyright (C) 2024 qBraid
#
# This file is part of the qBraid-SDK
#
# The qBraid-SDK is free software released under the GNU General Public License v3
# or later. You can redistribute and/or modify it under the terms of the GPL v3.
# See the LICENSE file in the project root or <https://www.gnu.org/licenses/gpl-3.0.html>.
#
# THERE IS NO WARRANTY for the qBraid-SDK, as per Section 15 of the GPL v3.
"""
Module defining Qiskit OpenQASM conversions
"""
from typing import TYPE_CHECKING
from qbraid_core._import import LazyLoader
from qbraid.passes.qasm3.compat import add_stdgates_include, insert_gate_def, replace_gate_name
from qbraid.transpiler.annotations import weight
qiskit_qasm3 = LazyLoader("qiskit_qasm3", globals(), "qiskit.qasm3")
if TYPE_CHECKING:
import qiskit as qiskit_
def transform_notation(qasm3: str) -> str:
"""
Process an OpenQASM 3 program that was generated by
an external tool to make it compatible with Qiskit.
"""
replacements = {
"cnot": "cx",
"si": "sdg",
"ti": "tdg",
"v": "sx",
"vi": "sxdg",
"phaseshift": "p",
"cphaseshift": "cp",
}
for old, new in replacements.items():
qasm3 = replace_gate_name(qasm3, old, new)
qasm3 = add_stdgates_include(qasm3)
qasm3 = insert_gate_def(qasm3, "iswap")
qasm3 = insert_gate_def(qasm3, "sxdg")
return qasm3
@weight(1)
def qasm3_to_qiskit(qasm3: str) -> "qiskit_.QuantumCircuit":
"""Convert QASM 3.0 string to a Qiskit QuantumCircuit representation.
Args:
qasm3 (str): A string in QASM 3.0 format.
Returns:
qiskit.QuantumCircuit: A QuantumCircuit object representing the input QASM 3.0 string.
"""
try:
return qiskit_qasm3.loads(qasm3)
except qiskit_qasm3.QASM3ImporterError:
pass
qasm3 = transform_notation(qasm3)
return qiskit_qasm3.loads(qasm3)
|
https://github.com/qBraid/qBraid
|
qBraid
|
# Copyright (C) 2024 qBraid
#
# This file is part of the qBraid-SDK
#
# The qBraid-SDK is free software released under the GNU General Public License v3
# or later. You can redistribute and/or modify it under the terms of the GPL v3.
# See the LICENSE file in the project root or <https://www.gnu.org/licenses/gpl-3.0.html>.
#
# THERE IS NO WARRANTY for the qBraid-SDK, as per Section 15 of the GPL v3.
"""
Module defining Qiskit conversion extras.
"""
import warnings
from typing import TYPE_CHECKING
from qbraid_core._import import LazyLoader
from qbraid.transpiler.annotations import requires_extras
qiskit_braket_provider = LazyLoader("qiskit_braket_provider", globals(), "qiskit_braket_provider")
qiskit_qir = LazyLoader("qiskit_qir", globals(), "qiskit_qir")
if TYPE_CHECKING:
import braket.circuits
import pyqir
import qiskit.circuit
@requires_extras("qiskit_braket_provider")
def qiskit_to_braket(
circuit: "qiskit.circuit.QuantumCircuit", **kwargs
) -> "braket.circuits.Circuit":
"""Return a Braket quantum circuit from a Qiskit quantum circuit.
Args:
circuit (QuantumCircuit): Qiskit quantum circuit
basis_gates (Optional[Iterable[str]]): The gateset to transpile to.
If `None`, the transpiler will use all gates defined in the Braket SDK.
Default: `None`.
verbatim (bool): Whether to translate the circuit without any modification, in other
words without transpiling it. Default: False.
Returns:
Circuit: Braket circuit
"""
with warnings.catch_warnings():
warnings.simplefilter("ignore", UserWarning)
return qiskit_braket_provider.providers.adapter.to_braket(circuit, **kwargs)
@requires_extras("qiskit_qir")
def qiskit_to_pyqir(circuit: "qiskit.circuit.QuantumCircuit") -> "pyqir.Module":
"""Return a PyQIR module from a Qiskit quantum circuit.
Args:
circuit (QuantumCircuit): Qiskit quantum circuit
Returns:
Module: PyQIR module
"""
return qiskit_qir.to_qir_module(circuit)
|
https://github.com/qBraid/qBraid
|
qBraid
|
# Copyright (C) 2024 qBraid
#
# This file is part of the qBraid-SDK
#
# The qBraid-SDK is free software released under the GNU General Public License v3
# or later. You can redistribute and/or modify it under the terms of the GPL v3.
# See the LICENSE file in the project root or <https://www.gnu.org/licenses/gpl-3.0.html>.
#
# THERE IS NO WARRANTY for the qBraid-SDK, as per Section 15 of the GPL v3.
"""
Module defining Qiskit OpenQASM conversions
"""
import qiskit
from qiskit.qasm2 import dumps as qasm2_dumps
from qbraid.transpiler.annotations import weight
@weight(1)
def qiskit_to_qasm2(circuit: qiskit.QuantumCircuit) -> str:
"""Returns OpenQASM 2 string equivalent to the input Qiskit circuit.
Args:
circuit: Qiskit circuit to convert to OpenQASM 2 string.
Returns:
str: OpenQASM 2 representation of the input Qiskit circuit.
"""
return qasm2_dumps(circuit)
|
https://github.com/qBraid/qBraid
|
qBraid
|
# Copyright (C) 2024 qBraid
#
# This file is part of the qBraid-SDK
#
# The qBraid-SDK is free software released under the GNU General Public License v3
# or later. You can redistribute and/or modify it under the terms of the GPL v3.
# See the LICENSE file in the project root or <https://www.gnu.org/licenses/gpl-3.0.html>.
#
# THERE IS NO WARRANTY for the qBraid-SDK, as per Section 15 of the GPL v3.
"""
Module defining Qiskit OpenQASM conversions
"""
import qiskit
from qiskit.qasm3 import dumps
from qbraid.transpiler.annotations import weight
@weight(1)
def qiskit_to_qasm3(circuit: qiskit.QuantumCircuit) -> str:
"""Convert qiskit QuantumCircuit to QASM 3.0 string"""
return dumps(circuit)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.