repo
stringclasses 900
values | file
stringclasses 754
values | content
stringlengths 4
215k
|
|---|---|---|
https://github.com/MonitSharma/Qiskit-Summer-School-and-Quantum-Challenges
|
MonitSharma
|
from qiskit_optimization.algorithms import MinimumEigenOptimizer
from qiskit import Aer
from qiskit.utils import algorithm_globals, QuantumInstance
from qiskit.algorithms import QAOA, NumPyMinimumEigensolver
import numpy as np
val = [5,6,7,8,9]
wt = [4,5,6,7,8]
W = 18
def dp(W, wt, val, n):
k = [[0 for x in range(W + 1)] for x in range(n + 1)]
for i in range(n + 1):
for w in range(W + 1):
if i == 0 or w == 0:
k[i][w] = 0
elif wt[i-1] <= w:
k[i][w] = max(val[i-1] + k[i-1][w-wt[i-1]], k[i-1][w])
else:
k[i][w] = k[i-1][w]
picks=[0 for x in range(n)]
volume=W
for i in range(n,-1,-1):
if (k[i][volume]>k[i-1][volume]):
picks[i-1]=1
volume -= wt[i-1]
return k[n][W],picks
n = len(val)
print("optimal value:", dp(W, wt, val, n)[0])
print('\n index of the chosen items:')
for i in range(n):
if dp(W, wt, val, n)[1][i]:
print(i,end=' ')
# import packages necessary for application classes.
from qiskit_optimization.applications import Knapsack
def knapsack_quadratic_program():
# Put values, weights and max_weight parameter for the Knapsack()
##############################
# Provide your code here
prob = Knapsack(val, wt, W)
#
##############################
# to_quadratic_program generates a corresponding QuadraticProgram of the instance of the knapsack problem.
kqp = prob.to_quadratic_program()
return prob, kqp
prob,quadratic_program=knapsack_quadratic_program()
quadratic_program
# Numpy Eigensolver
meo = MinimumEigenOptimizer(min_eigen_solver=NumPyMinimumEigensolver())
result = meo.solve(quadratic_program)
print('result:\n', result)
print('\n index of the chosen items:', prob.interpret(result))
# QAOA
seed = 123
algorithm_globals.random_seed = seed
qins = QuantumInstance(backend=Aer.get_backend('qasm_simulator'), shots=1000, seed_simulator=seed, seed_transpiler=seed)
meo = MinimumEigenOptimizer(min_eigen_solver=QAOA(reps=1, quantum_instance=qins))
result = meo.solve(quadratic_program)
print('result:\n', result)
print('\n index of the chosen items:', prob.interpret(result))
# Check your answer and submit using the following code
from qc_grader import grade_ex4a
grade_ex4a(quadratic_program)
L1 = [5,3,3,6,9,7,1]
L2 = [8,4,5,12,10,11,2]
C1 = [1,1,2,1,1,1,2]
C2 = [3,2,3,2,4,3,3]
C_max = 16
def knapsack_argument(L1, L2, C1, C2, C_max):
##############################
# Provide your code here
values = [j-i for i,j in zip(L1,L2)]
weights = [j-i for i,j in zip(C1,C2)]
max_weight = max([i+j for i,j in zip(L1, L2)])
#
##############################
return values, weights, max_weight
values, weights, max_weight = knapsack_argument(L1, L2, C1, C2, C_max)
print(values, weights, max_weight)
prob = Knapsack(values = values, weights = weights, max_weight = max_weight)
qp = prob.to_quadratic_program()
qp
# Check your answer and submit using the following code
from qc_grader import grade_ex4b
grade_ex4b(knapsack_argument)
# QAOA
seed = 123
algorithm_globals.random_seed = seed
qins = QuantumInstance(backend=Aer.get_backend('qasm_simulator'), shots=1000, seed_simulator=seed, seed_transpiler=seed)
meo = MinimumEigenOptimizer(min_eigen_solver=QAOA(reps=1, quantum_instance=qins))
result = meo.solve(qp)
print('result:', result.x)
item = np.array(result.x)
revenue=0
for i in range(len(item)):
if item[i]==0:
revenue+=L1[i]
else:
revenue+=L2[i]
print('total revenue:', revenue)
instance_examples = [
{
'L1': [3, 7, 3, 4, 2, 6, 2, 2, 4, 6, 6],
'L2': [7, 8, 7, 6, 6, 9, 6, 7, 6, 7, 7],
'C1': [2, 2, 2, 3, 2, 4, 2, 2, 2, 2, 2],
'C2': [4, 3, 3, 4, 4, 5, 3, 4, 4, 3, 4],
'C_max': 33
},
{
'L1': [4, 2, 2, 3, 5, 3, 6, 3, 8, 3, 2],
'L2': [6, 5, 8, 5, 6, 6, 9, 7, 9, 5, 8],
'C1': [3, 3, 2, 3, 4, 2, 2, 3, 4, 2, 2],
'C2': [4, 4, 3, 5, 5, 3, 4, 5, 5, 3, 5],
'C_max': 38
},
{
'L1': [5, 4, 3, 3, 3, 7, 6, 4, 3, 5, 3],
'L2': [9, 7, 5, 5, 7, 8, 8, 7, 5, 7, 9],
'C1': [2, 2, 4, 2, 3, 4, 2, 2, 2, 2, 2],
'C2': [3, 4, 5, 4, 4, 5, 3, 3, 5, 3, 5],
'C_max': 35
}
]
from typing import List, Union
import math
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, assemble
from qiskit.compiler import transpile
from qiskit.circuit import Gate
from qiskit.circuit.library.standard_gates import *
from qiskit.circuit.library import QFT
def phase_return(index_qubits: int, gamma: float, L1: list, L2: list, to_gate=True) -> Union[Gate, QuantumCircuit]:
qr_index = QuantumRegister(index_qubits, "index")
qc = QuantumCircuit(qr_index)
##############################
### U_1(gamma * (lambda2 - lambda1)) for each qubit ###
# Provide your code here
##############################
return qc.to_gate(label=" phase return ") if to_gate else qc
def subroutine_add_const(data_qubits: int, const: int, to_gate=True) -> Union[Gate, QuantumCircuit]:
qc = QuantumCircuit(data_qubits)
##############################
### Phase Rotation ###
# Provide your code here
##############################
return qc.to_gate(label=" [+"+str(const)+"] ") if to_gate else qc
def const_adder(data_qubits: int, const: int, to_gate=True) -> Union[Gate, QuantumCircuit]:
qr_data = QuantumRegister(data_qubits, "data")
qc = QuantumCircuit(qr_data)
##############################
### QFT ###
# Provide your code here
##############################
##############################
### Phase Rotation ###
# Use `subroutine_add_const`
##############################
##############################
### IQFT ###
# Provide your code here
##############################
return qc.to_gate(label=" [ +" + str(const) + "] ") if to_gate else qc
def cost_calculation(index_qubits: int, data_qubits: int, list1: list, list2: list, to_gate = True) -> Union[Gate, QuantumCircuit]:
qr_index = QuantumRegister(index_qubits, "index")
qr_data = QuantumRegister(data_qubits, "data")
qc = QuantumCircuit(qr_index, qr_data)
for i, (val1, val2) in enumerate(zip(list1, list2)):
##############################
### Add val2 using const_adder controlled by i-th index register (set to 1) ###
# Provide your code here
##############################
qc.x(qr_index[i])
##############################
### Add val1 using const_adder controlled by i-th index register (set to 0) ###
# Provide your code here
##############################
qc.x(qr_index[i])
return qc.to_gate(label=" Cost Calculation ") if to_gate else qc
def constraint_testing(data_qubits: int, C_max: int, to_gate = True) -> Union[Gate, QuantumCircuit]:
qr_data = QuantumRegister(data_qubits, "data")
qr_f = QuantumRegister(1, "flag")
qc = QuantumCircuit(qr_data, qr_f)
##############################
### Set the flag register for indices with costs larger than C_max ###
# Provide your code here
##############################
return qc.to_gate(label=" Constraint Testing ") if to_gate else qc
def penalty_dephasing(data_qubits: int, alpha: float, gamma: float, to_gate = True) -> Union[Gate, QuantumCircuit]:
qr_data = QuantumRegister(data_qubits, "data")
qr_f = QuantumRegister(1, "flag")
qc = QuantumCircuit(qr_data, qr_f)
##############################
### Phase Rotation ###
# Provide your code here
##############################
return qc.to_gate(label=" Penalty Dephasing ") if to_gate else qc
def reinitialization(index_qubits: int, data_qubits: int, C1: list, C2: list, C_max: int, to_gate = True) -> Union[Gate, QuantumCircuit]:
qr_index = QuantumRegister(index_qubits, "index")
qr_data = QuantumRegister(data_qubits, "data")
qr_f = QuantumRegister(1, "flag")
qc = QuantumCircuit(qr_index, qr_data, qr_f)
##############################
### Reinitialization Circuit ###
# Provide your code here
##############################
return qc.to_gate(label=" Reinitialization ") if to_gate else qc
def mixing_operator(index_qubits: int, beta: float, to_gate = True) -> Union[Gate, QuantumCircuit]:
qr_index = QuantumRegister(index_qubits, "index")
qc = QuantumCircuit(qr_index)
##############################
### Mixing Operator ###
# Provide your code here
##############################
return qc.to_gate(label=" Mixing Operator ") if to_gate else qc
def solver_function(L1: list, L2: list, C1: list, C2: list, C_max: int) -> QuantumCircuit:
# the number of qubits representing answers
index_qubits = len(L1)
# the maximum possible total cost
max_c = sum([max(l0, l1) for l0, l1 in zip(C1, C2)])
# the number of qubits representing data values can be defined using the maximum possible total cost as follows:
data_qubits = math.ceil(math.log(max_c, 2)) + 1 if not max_c & (max_c - 1) == 0 else math.ceil(math.log(max_c, 2)) + 2
### Phase Operator ###
# return part
def phase_return():
##############################
### TODO ###
### Paste your code from above cells here ###
##############################
# penalty part
def subroutine_add_const():
##############################
### TODO ###
### Paste your code from above cells here ###
##############################
# penalty part
def const_adder():
##############################
### TODO ###
### Paste your code from above cells here ###
##############################
# penalty part
def cost_calculation():
##############################
### TODO ###
### Paste your code from above cells here ###
##############################
# penalty part
def constraint_testing():
##############################
### TODO ###
### Paste your code from above cells here ###
##############################
# penalty part
def penalty_dephasing():
##############################
### TODO ###
### Paste your code from above cells here ###
##############################
# penalty part
def reinitialization():
##############################
### TODO ###
### Paste your code from above cells here ###
##############################
### Mixing Operator ###
def mixing_operator():
##############################
### TODO ###
### Paste your code from above cells here ###
##############################
qr_index = QuantumRegister(index_qubits, "index") # index register
qr_data = QuantumRegister(data_qubits, "data") # data register
qr_f = QuantumRegister(1, "flag") # flag register
cr_index = ClassicalRegister(index_qubits, "c_index") # classical register storing the measurement result of index register
qc = QuantumCircuit(qr_index, qr_data, qr_f, cr_index)
### initialize the index register with uniform superposition state ###
qc.h(qr_index)
### DO NOT CHANGE THE CODE BELOW
p = 5
alpha = 1
for i in range(p):
### set fixed parameters for each round ###
beta = 1 - (i + 1) / p
gamma = (i + 1) / p
### return part ###
qc.append(phase_return(index_qubits, gamma, L1, L2), qr_index)
### step 1: cost calculation ###
qc.append(cost_calculation(index_qubits, data_qubits, C1, C2), qr_index[:] + qr_data[:])
### step 2: Constraint testing ###
qc.append(constraint_testing(data_qubits, C_max), qr_data[:] + qr_f[:])
### step 3: penalty dephasing ###
qc.append(penalty_dephasing(data_qubits, alpha, gamma), qr_data[:] + qr_f[:])
### step 4: reinitialization ###
qc.append(reinitialization(index_qubits, data_qubits, C1, C2, C_max), qr_index[:] + qr_data[:] + qr_f[:])
### mixing operator ###
qc.append(mixing_operator(index_qubits, beta), qr_index)
### measure the index ###
### since the default measurement outcome is shown in big endian, it is necessary to reverse the classical bits in order to unify the endian ###
qc.measure(qr_index, cr_index[::-1])
return qc
# Execute your circuit with following prepare_ex4c() function.
# The prepare_ex4c() function works like the execute() function with only QuantumCircuit as an argument.
from qc_grader import prepare_ex4c
job = prepare_ex4c(solver_function)
result = job.result()
# Check your answer and submit using the following code
from qc_grader import grade_ex4c
grade_ex4c(job)
|
https://github.com/MonitSharma/Qiskit-Summer-School-and-Quantum-Challenges
|
MonitSharma
|
from qiskit import *
from qiskit.visualization import plot_histogram
import numpy as np
def NOT(inp):
"""An NOT gate.
Parameters:
inp (str): Input, encoded in qubit 0.
Returns:
QuantumCircuit: Output NOT circuit.
str: Output value measured from qubit 0.
"""
qc = QuantumCircuit(1, 1) # A quantum circuit with a single qubit and a single classical bit
qc.reset(0)
# We encode '0' as the qubit state |0⟩, and '1' as |1⟩
# Since the qubit is initially |0⟩, we don't need to do anything for an input of '0'
# For an input of '1', we do an x to rotate the |0⟩ to |1⟩
if inp=='1':
qc.x(0)
# barrier between input state and gate operation
qc.barrier()
# Now we've encoded the input, we can do a NOT on it using x
qc.x(0)
#barrier between gate operation and measurement
qc.barrier()
# Finally, we extract the |0⟩/|1⟩ output of the qubit and encode it in the bit c[0]
qc.measure(0,0)
qc.draw()
# We'll run the program on a simulator
backend = Aer.get_backend('qasm_simulator')
# Since the output will be deterministic, we can use just a single shot to get it
job = backend.run(qc, shots=1, memory=True)
output = job.result().get_memory()[0]
return qc, output
## Test the function
for inp in ['0', '1']:
qc, out = NOT(inp)
print('NOT with input',inp,'gives output',out)
display(qc.draw())
print('\n')
def XOR(inp1,inp2):
"""An XOR gate.
Parameters:
inpt1 (str): Input 1, encoded in qubit 0.
inpt2 (str): Input 2, encoded in qubit 1.
Returns:
QuantumCircuit: Output XOR circuit.
str: Output value measured from qubit 1.
"""
qc = QuantumCircuit(2, 1)
qc.reset(range(2))
if inp1=='1':
qc.x(0)
if inp2=='1':
qc.x(1)
# barrier between input state and gate operation
qc.barrier()
# this is where your program for quantum XOR gate goes
qc.cx(0, 1)
# barrier between input state and gate operation
qc.barrier()
qc.measure(1,0) # output from qubit 1 is measured
#We'll run the program on a simulator
backend = Aer.get_backend('qasm_simulator')
#Since the output will be deterministic, we can use just a single shot to get it
job = backend.run(qc, shots=1, memory=True)
output = job.result().get_memory()[0]
return qc, output
## Test the function
for inp1 in ['0', '1']:
for inp2 in ['0', '1']:
qc, output = XOR(inp1, inp2)
print('XOR with inputs',inp1,inp2,'gives output',output)
display(qc.draw())
print('\n')
def AND(inp1,inp2):
"""An AND gate.
Parameters:
inpt1 (str): Input 1, encoded in qubit 0.
inpt2 (str): Input 2, encoded in qubit 1.
Returns:
QuantumCircuit: Output XOR circuit.
str: Output value measured from qubit 2.
"""
qc = QuantumCircuit(3, 1)
qc.reset(range(2))
if inp1=='1':
qc.x(0)
if inp2=='1':
qc.x(1)
qc.barrier()
# this is where your program for quantum AND gate goes
qc.ccx(0,1,2)
qc.barrier()
qc.measure(2, 0) # output from qubit 2 is measured
# We'll run the program on a simulator
backend = Aer.get_backend('qasm_simulator')
# Since the output will be deterministic, we can use just a single shot to get it
job = backend.run(qc, shots=1, memory=True)
output = job.result().get_memory()[0]
return qc, output
## Test the function
for inp1 in ['0', '1']:
for inp2 in ['0', '1']:
qc, output = AND(inp1, inp2)
print('AND with inputs',inp1,inp2,'gives output',output)
display(qc.draw())
print('\n')
def NAND(inp1,inp2):
"""An NAND gate.
Parameters:
inpt1 (str): Input 1, encoded in qubit 0.
inpt2 (str): Input 2, encoded in qubit 1.
Returns:
QuantumCircuit: Output NAND circuit.
str: Output value measured from qubit 2.
"""
qc = QuantumCircuit(3, 1)
qc.reset(range(3))
if inp1=='1':
qc.x(0)
if inp2=='1':
qc.x(1)
qc.barrier()
# this is where your program for quantum NAND gate goes
qc.ccx(0,1,2)
if inp=='1':
qc.x(2)
qc.barrier()
qc.measure(2, 0) # output from qubit 2 is measured
# We'll run the program on a simulator
backend = Aer.get_backend('aer_simulator')
# Since the output will be deterministic, we can use just a single shot to get it
job = backend.run(qc,shots=1,memory=True)
output = job.result().get_memory()[0]
return qc, output
## Test the function
for inp1 in ['0', '1']:
for inp2 in ['0', '1']:
qc, output = NAND(inp1, inp2)
print('NAND with inputs',inp1,inp2,'gives output',output)
display(qc.draw())
print('\n')
def OR(inp1,inp2):
"""An OR gate.
Parameters:
inpt1 (str): Input 1, encoded in qubit 0.
inpt2 (str): Input 2, encoded in qubit 1.
Returns:
QuantumCircuit: Output XOR circuit.
str: Output value measured from qubit 2.
"""
qc = QuantumCircuit(3, 1)
qc.reset(range(3))
if inp1=='1':
qc.x(0)
if inp2=='1':
qc.x(1)
qc.barrier()
# this is where your program for quantum OR gate goes
qc.cx(0, 2)
qc.cx(1, 2)
qc.barrier()
qc.measure(2, 0) # output from qubit 2 is measured
# We'll run the program on a simulator
backend = Aer.get_backend('aer_simulator')
# Since the output will be deterministic, we can use just a single shot to get it
job = backend.run(qc,shots=1,memory=True)
output = job.result().get_memory()[0]
return qc, output
## Test the function
for inp1 in ['0', '1']:
for inp2 in ['0', '1']:
qc, output = OR(inp1, inp2)
print('OR with inputs',inp1,inp2,'gives output',output)
display(qc.draw())
print('\n')
from qiskit import IBMQ
#IBMQ.save_account("a68a35747d4eccd1d58f275e637909987c789ce5c0edd8a4f43014672bf0301b54b28b1b5f44ba8ff87500777429e1e4ceb79621a6ba248d6cca6bca0e233d23", overwrite=True)
IBMQ.load_account()
IBMQ.providers()
provider = IBMQ.get_provider('ibm-q')
provider.backends()
import qiskit.tools.jupyter
# run this cell
backend = provider.get_backend('ibmq_quito')
qc_and = QuantumCircuit(3)
qc_and.ccx(0,1,2)
print('AND gate')
display(qc_and.draw())
print('\n\nTranspiled AND gate with all the required connectivity')
qc_and.decompose().draw()
from qiskit.tools.monitor import job_monitor
# run the cell to define AND gate for real quantum system
def AND(inp1, inp2, backend, layout):
qc = QuantumCircuit(3, 1)
qc.reset(range(3))
if inp1=='1':
qc.x(0)
if inp2=='1':
qc.x(1)
qc.barrier()
qc.ccx(0, 1, 2)
qc.barrier()
qc.measure(2, 0)
qc_trans = transpile(qc, backend, initial_layout=layout, optimization_level=3)
job = backend.run(qc_trans, shots=8192)
print(job.job_id())
job_monitor(job)
output = job.result().get_counts()
return qc_trans, output
backend
layout = [0, 1, 2]
output_all = []
qc_trans_all = []
prob_all = []
worst = 1
best = 0
for input1 in ['0','1']:
for input2 in ['0','1']:
qc_trans, output = AND(input1, input2, backend, layout)
output_all.append(output)
qc_trans_all.append(qc_trans)
prob = output[str(int( input1=='1' and input2=='1' ))]/8192
prob_all.append(prob)
print('\nProbability of correct answer for inputs',input1,input2)
print('{:.2f}'.format(prob) )
print('---------------------------------')
worst = min(worst,prob)
best = max(best, prob)
print('')
print('\nThe highest of these probabilities was {:.2f}'.format(best))
print('The lowest of these probabilities was {:.2f}'.format(worst))
print('Transpiled AND gate circuit for ibmq_vigo with input 0 0')
print('\nThe circuit depth : {}'.format (qc_trans_all[0].depth()))
print('# of nonlocal gates : {}'.format (qc_trans_all[0].num_nonlocal_gates()))
print('Probability of correct answer : {:.2f}'.format(prob_all[0]) )
qc_trans_all[0].draw()
print('Transpiled AND gate circuit for ibmq_vigo with input 0 1')
print('\nThe circuit depth : {}'.format (qc_trans_all[1].depth()))
print('# of nonlocal gates : {}'.format (qc_trans_all[1].num_nonlocal_gates()))
print('Probability of correct answer : {:.2f}'.format(prob_all[1]) )
qc_trans_all[1].draw()
print('Transpiled AND gate circuit for ibmq_vigo with input 1 0')
print('\nThe circuit depth : {}'.format (qc_trans_all[2].depth()))
print('# of nonlocal gates : {}'.format (qc_trans_all[2].num_nonlocal_gates()))
print('Probability of correct answer : {:.2f}'.format(prob_all[2]) )
qc_trans_all[2].draw()
print('Transpiled AND gate circuit for ibmq_vigo with input 1 1')
print('\nThe circuit depth : {}'.format (qc_trans_all[3].depth()))
print('# of nonlocal gates : {}'.format (qc_trans_all[3].num_nonlocal_gates()))
print('Probability of correct answer : {:.2f}'.format(prob_all[3]) )
qc_trans_all[3].draw()
|
https://github.com/MonitSharma/Qiskit-Summer-School-and-Quantum-Challenges
|
MonitSharma
|
import numpy as np
# Importing standard Qiskit libraries
from qiskit import QuantumCircuit, transpile, Aer, execute
from qiskit.tools.jupyter import *
from qiskit.visualization import *
from qiskit.providers.aer import QasmSimulator
backend = Aer.get_backend('statevector_simulator')
qc1 = QuantumCircuit(4)
# perform gate operations on individual qubits
qc1.x(0)
qc1.y(1)
qc1.z(2)
qc1.s(3)
# Draw circuit
qc1.draw()
# Plot blochshere
out1 = execute(qc1,backend).result().get_statevector()
plot_bloch_multivector(out1)
qc2 = QuantumCircuit(4)
# initialize qubits
qc2.x(range(4))
# perform gate operations on individual qubits
qc2.x(0)
qc2.y(1)
qc2.z(2)
qc2.s(3)
# Draw circuit
qc2.draw()
# Plot blochshere
out2 = execute(qc2,backend).result().get_statevector()
plot_bloch_multivector(out2)
qc3 = QuantumCircuit(4)
# initialize qubits
qc3.h(range(4))
# perform gate operations on individual qubits
qc3.x(0)
qc3.y(1)
qc3.z(2)
qc3.s(3)
# Draw circuit
qc3.draw()
# Plot blochshere
out3 = execute(qc3,backend).result().get_statevector()
plot_bloch_multivector(out3)
qc4 = QuantumCircuit(4)
# initialize qubits
qc4.x(range(4))
qc4.h(range(4))
# perform gate operations on individual qubits
qc4.x(0)
qc4.y(1)
qc4.z(2)
qc4.s(3)
# Draw circuit
qc4.draw()
# Plot blochshere
out4 = execute(qc4,backend).result().get_statevector()
plot_bloch_multivector(out4)
qc5 = QuantumCircuit(4)
# initialize qubits
qc5.h(range(4))
qc5.s(range(4))
# perform gate operations on individual qubits
qc5.x(0)
qc5.y(1)
qc5.z(2)
qc5.s(3)
# Draw circuit
qc5.draw()
# Plot blochshere
out5 = execute(qc5,backend).result().get_statevector()
plot_bloch_multivector(out5)
qc6 = QuantumCircuit(4)
# initialize qubits
qc6.x(range(4))
qc6.h(range(4))
qc6.s(range(4))
# perform gate operations on individual qubits
qc6.x(0)
qc6.y(1)
qc6.z(2)
qc6.s(3)
# Draw circuit
qc6.draw()
# Plot blochshere
out6 = execute(qc6,backend).result().get_statevector()
plot_bloch_multivector(out6)
import qiskit
qiskit.__qiskit_version__
|
https://github.com/MonitSharma/Qiskit-Summer-School-and-Quantum-Challenges
|
MonitSharma
|
from qiskit import *
import numpy as np
from numpy import linalg as la
from qiskit.tools.monitor import job_monitor
import qiskit.tools.jupyter
qc = QuantumCircuit(1)
#### your code goes here
# z measurement of qubit 0
measure_z = QuantumCircuit(1,1)
measure_z.measure(0,0)
# x measurement of qubit 0
measure_x = QuantumCircuit(1,1)
# your code goes here
# y measurement of qubit 0
measure_y = QuantumCircuit(1,1)
# your code goes here
shots = 2**14 # number of samples used for statistics
sim = Aer.get_backend('qasm_simulator')
bloch_vector_measure = []
for measure_circuit in [measure_x, measure_y, measure_z]:
# run the circuit with a the selected measurement and get the number of samples that output each bit value
counts = execute(qc+measure_circuit, sim, shots=shots).result().get_counts()
# calculate the probabilities for each bit value
probs = {}
for output in ['0','1']:
if output in counts:
probs[output] = counts[output]/shots
else:
probs[output] = 0
bloch_vector_measure.append( probs['0'] - probs['1'] )
# normalizing the bloch sphere vector
bloch_vector = bloch_vector_measure/la.norm(bloch_vector_measure)
print('The bloch sphere coordinates are [{0:4.3f}, {1:4.3f}, {2:4.3f}]'
.format(*bloch_vector))
from kaleidoscope.interactive import bloch_sphere
bloch_sphere(bloch_vector, vectors_annotation=True)
from qiskit.visualization import plot_bloch_vector
plot_bloch_vector( bloch_vector )
# circuit for the state Tri1
Tri1 = QuantumCircuit(2)
# your code goes here
# circuit for the state Tri2
Tri2 = QuantumCircuit(2)
# your code goes here
# circuit for the state Tri3
Tri3 = QuantumCircuit(2)
# your code goes here
# circuit for the state Sing
Sing = QuantumCircuit(2)
# your code goes here
# <ZZ>
measure_ZZ = QuantumCircuit(2)
measure_ZZ.measure_all()
# <XX>
measure_XX = QuantumCircuit(2)
# your code goes here
# <YY>
measure_YY = QuantumCircuit(2)
# your code goes here
shots = 2**14 # number of samples used for statistics
A = 1.47e-6 #unit of A is eV
E_sim = []
for state_init in [Tri1,Tri2,Tri3,Sing]:
Energy_meas = []
for measure_circuit in [measure_XX, measure_YY, measure_ZZ]:
# run the circuit with a the selected measurement and get the number of samples that output each bit value
qc = state_init+measure_circuit
counts = execute(qc, sim, shots=shots).result().get_counts()
# calculate the probabilities for each computational basis
probs = {}
for output in ['00','01', '10', '11']:
if output in counts:
probs[output] = counts[output]/shots
else:
probs[output] = 0
Energy_meas.append( probs['00'] - probs['01'] - probs['10'] + probs['11'] )
E_sim.append(A * np.sum(np.array(Energy_meas)))
# Run this cell to print out your results
print('Energy expection value of the state Tri1 : {:.3e} eV'.format(E_sim[0]))
print('Energy expection value of the state Tri2 : {:.3e} eV'.format(E_sim[1]))
print('Energy expection value of the state Tri3 : {:.3e} eV'.format(E_sim[2]))
print('Energy expection value of the state Sing : {:.3e} eV'.format(E_sim[3]))
# reduced plank constant in (eV) and the speed of light(cgs units)
hbar, c = 4.1357e-15, 3e10
# energy difference between the triplets and singlet
E_del = abs(E_sim[0] - E_sim[3])
# frequency associated with the energy difference
f = E_del/hbar
# convert frequency to wavelength in (cm)
wavelength = c/f
print('The wavelength of the radiation from the transition\
in the hyperfine structure is : {:.1f} cm'.format(wavelength))
provider = IBMQ.load_account()
backend = provider.get_backend('ibmq_athens')
# run this cell to get the backend information through the widget
backend
# assign your choice for the initial layout to the list variable `initial_layout`.
initial_layout =
qc_all = [state_init+measure_circuit for state_init in [Tri1,Tri2,Tri3,Sing]
for measure_circuit in [measure_XX, measure_YY, measure_ZZ] ]
shots = 8192
job = execute(qc_all, backend, initial_layout=initial_layout, optimization_level=3, shots=shots)
print(job.job_id())
job_monitor(job)
# getting the results of your job
results = job.result()
## To access the results of the completed job
#results = backend.retrieve_job('job_id').result()
def Energy(results, shots):
"""Compute the energy levels of the hydrogen ground state.
Parameters:
results (obj): results, results from executing the circuits for measuring a hamiltonian.
shots (int): shots, number of shots used for the circuit execution.
Returns:
Energy (list): energy values of the four different hydrogen ground states
"""
E = []
A = 1.47e-6
for ind_state in range(4):
Energy_meas = []
for ind_comp in range(3):
counts = results.get_counts(ind_state*3+ind_comp)
# calculate the probabilities for each computational basis
probs = {}
for output in ['00','01', '10', '11']:
if output in counts:
probs[output] = counts[output]/shots
else:
probs[output] = 0
Energy_meas.append( probs['00'] - probs['01'] - probs['10'] + probs['11'] )
E.append(A * np.sum(np.array(Energy_meas)))
return E
E = Energy(results, shots)
print('Energy expection value of the state Tri1 : {:.3e} eV'.format(E[0]))
print('Energy expection value of the state Tri2 : {:.3e} eV'.format(E[1]))
print('Energy expection value of the state Tri3 : {:.3e} eV'.format(E[2]))
print('Energy expection value of the state Sing : {:.3e} eV'.format(E[3]))
from qiskit.ignis.mitigation.measurement import *
# your code to create the circuits, meas_calibs, goes here
meas_calibs, state_labels =
# execute meas_calibs on your choice of the backend
job = execute(meas_calibs, backend, shots = shots)
print(job.job_id())
job_monitor(job)
cal_results = job.result()
## To access the results of the completed job
#cal_results = backend.retrieve_job('job_id').result()
# your code to obtain the measurement filter object, 'meas_filter', goes here
results_new = meas_filter.apply(results)
E_new = Energy(results_new, shots)
print('Energy expection value of the state Tri1 : {:.3e} eV'.format(E_new[0]))
print('Energy expection value of the state Tri2 : {:.3e} eV'.format(E_new[1]))
print('Energy expection value of the state Tri3 : {:.3e} eV'.format(E_new[2]))
print('Energy expection value of the state Sing : {:.3e} eV'.format(E_new[3]))
# results for the energy estimation from the simulation,
# execution on a quantum system without error mitigation and
# with error mitigation in numpy array format
Energy_exact, Energy_exp_orig, Energy_exp_new = np.array(E_sim), np.array(E), np.array(E_new)
# Calculate the relative errors of the energy values without error mitigation
# and assign to the numpy array variable `Err_rel_orig` of size 4
Err_rel_orig =
# Calculate the relative errors of the energy values with error mitigation
# and assign to the numpy array variable `Err_rel_new` of size 4
Err_rel_new =
np.set_printoptions(precision=3)
print('The relative errors of the energy values for four bell basis\
without measurement error mitigation : {}'.format(Err_rel_orig))
np.set_printoptions(precision=3)
print('The relative errors of the energy values for four bell basis\
with measurement error mitigation : {}'.format(Err_rel_new))
|
https://github.com/MonitSharma/Qiskit-Summer-School-and-Quantum-Challenges
|
MonitSharma
|
# Importing standard Qiskit libraries
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit import Aer, assemble
from qiskit.visualization import plot_histogram, plot_bloch_multivector, plot_state_qsphere, plot_state_city, plot_state_paulivec, plot_state_hinton
# Ignore warnings
import warnings
warnings.filterwarnings('ignore')
# Define backend
sim = Aer.get_backend('aer_simulator')
def createBellStates(inp1, inp2):
qc = QuantumCircuit(2)
qc.reset(range(2))
if inp1=='1':
qc.x(0)
if inp2=='1':
qc.x(1)
qc.barrier()
qc.h(0)
qc.cx(0,1)
qc.save_statevector()
qobj = assemble(qc)
result = sim.run(qobj).result()
state = result.get_statevector()
return qc, state, result
print('Note: Since these qubits are in entangled state, their state cannot be written as two separate qubit states. This also means that we lose information when we try to plot our state on separate Bloch spheres as seen below.\n')
inp1 = 0
inp2 = 1
qc, state, result = createBellStates(inp1, inp2)
display(plot_bloch_multivector(state))
# Uncomment below code in order to explore other states
#for inp2 in ['0', '1']:
#for inp1 in ['0', '1']:
#qc, state, result = createBellStates(inp1, inp2)
#print('For inputs',inp2,inp1,'Representation of Entangled States are:')
# Uncomment any of the below functions to visualize the resulting quantum states
# Draw the quantum circuit
#display(qc.draw())
# Plot states on QSphere
#display(plot_state_qsphere(state))
# Plot states on Bloch Multivector
#display(plot_bloch_multivector(state))
# Plot histogram
#display(plot_histogram(result.get_counts()))
# Plot state matrix like a city
#display(plot_state_city(state))
# Represent state matix using Pauli operators as the basis
#display(plot_state_paulivec(state))
# Plot state matrix as Hinton representation
#display(plot_state_hinton(state))
#print('\n')'''
from qiskit import IBMQ, execute
from qiskit.providers.ibmq import least_busy
from qiskit.tools import job_monitor
# Loading your IBM Quantum account(s)
provider = IBMQ.load_account()
backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 2
and not x.configuration().simulator
and x.status().operational==True))
def createBSRealDevice(inp1, inp2):
qr = QuantumRegister(2)
cr = ClassicalRegister(2)
qc = QuantumCircuit(qr, cr)
qc.reset(range(2))
if inp1 == 1:
qc.x(0)
if inp2 == 1:
qc.x(1)
qc.barrier()
qc.h(0)
qc.cx(0,1)
qc.measure(qr, cr)
job = execute(qc, backend=backend, shots=100)
job_monitor(job)
result = job.result()
return qc, result
inp1 = 0
inp2 = 0
print('For inputs',inp2,inp1,'Representation of Entangled States are,')
#first results
qc, first_result = createBSRealDevice(inp1, inp2)
first_counts = first_result.get_counts()
# Draw the quantum circuit
display(qc.draw())
#second results
qc, second_result = createBSRealDevice(inp1, inp2)
second_counts = second_result.get_counts()
# Plot results on histogram with legend
legend = ['First execution', 'Second execution']
plot_histogram([first_counts, second_counts], legend=legend)
def ghzCircuit(inp1, inp2, inp3):
qc = QuantumCircuit(3)
qc.reset(range(3))
if inp1 == 1:
qc.x(0)
if inp2 == 1:
qc.x(1)
if inp3 == 1:
qc.x(2)
qc.barrier()
qc.h(0)
qc.cx(0,1)
qc.cx(0,2)
qc.save_statevector()
qobj = assemble(qc)
result = sim.run(qobj).result()
state = result.get_statevector()
return qc, state, result
print('Note: Since these qubits are in entangled state, their state cannot be written as two separate qubit states. This also means that we lose information when we try to plot our state on separate Bloch spheres as seen below.\n')
inp1 = 0
inp2 = 1
inp3 = 1
qc, state, result = ghzCircuit(inp1, inp2, inp3)
display(plot_bloch_multivector(state))
# Uncomment below code in order to explore other states
#for inp3 in ['0','1']:
#for inp2 in ['0','1']:
#for inp1 in ['0','1']:
#qc, state, result = ghzCircuit(inp1, inp2, inp3)
#print('For inputs',inp3,inp2,inp1,'Representation of GHZ States are:')
# Uncomment any of the below functions to visualize the resulting quantum states
# Draw the quantum circuit
#display(qc.draw())
# Plot states on QSphere
#display(plot_state_qsphere(state))
# Plot states on Bloch Multivector
#display(plot_bloch_multivector(state))
# Plot histogram
#display(plot_histogram(result.get_counts()))
# Plot state matrix like a city
#display(plot_state_city(state))
# Represent state matix using Pauli operators as the basis
#display(plot_state_paulivec(state))
# Plot state matrix as Hinton representation
#display(plot_state_hinton(state))
#print('\n')
def ghz5QCircuit(inp1, inp2, inp3, inp4, inp5):
qc = QuantumCircuit(5)
#qc.reset(range(5))
if inp1 == 1:
qc.x(0)
if inp2 == 1:
qc.x(1)
if inp3 == 1:
qc.x(2)
if inp4 == 1:
qc.x(3)
if inp5 == 1:
qc.x(4)
qc.barrier()
qc.h(0)
qc.cx(0,1)
qc.cx(0,2)
qc.cx(0,3)
qc.cx(0,4)
qc.save_statevector()
qobj = assemble(qc)
result = sim.run(qobj).result()
state = result.get_statevector()
return qc, state, result
# Explore GHZ States for input 00010. Note: the input has been stated in little-endian format.
inp1 = 0
inp2 = 1
inp3 = 0
inp4 = 0
inp5 = 0
qc, state, result = ghz5QCircuit(inp1, inp2, inp3, inp4, inp5)
print('For inputs',inp5,inp4,inp3,inp2,inp1,'Representation of GHZ States are:')
display(plot_state_qsphere(state))
print('\n')
# Explore GHZ States for input 11001. Note: the input has been stated in little-endian format.
inp1 = 1
inp2 = 0
inp3 = 0
inp4 = 1
inp5 = 1
qc, state, result = ghz5QCircuit(inp1, inp2, inp3, inp4, inp5)
print('For inputs',inp5,inp4,inp3,inp2,inp1,'Representation of GHZ States are:')
display(plot_state_qsphere(state))
print('\n')
# Explore GHZ States for input 01010. Note: the input has been stated in little-endian format.
inp1 = 0
inp2 = 1
inp3 = 0
inp4 = 1
inp5 = 0
qc, state, result = ghz5QCircuit(inp1, inp2, inp3, inp4, inp5)
print('For inputs',inp5,inp4,inp3,inp2,inp1,'Representation of GHZ States are:')
display(plot_state_qsphere(state))
print('\n')
# Uncomment below code in order to explore other states
#for inp5 in ['0','1']:
#for inp4 in ['0','1']:
#for inp3 in ['0','1']:
#for inp2 in ['0','1']:
#for inp1 in ['0','1']:
#qc, state, result = ghz5QCircuit(inp1, inp2, inp3, inp4, inp5)
#print('For inputs',inp5,inp4,inp3,inp2,inp1,'Representation of GHZ States are:')
# Uncomment any of the below functions to visualize the resulting quantum states
# Draw the quantum circuit
#display(qc.draw())
# Plot states on QSphere
#display(plot_state_qsphere(state))
# Plot states on Bloch Multivector
#display(plot_bloch_multivector(state))
# Plot histogram
#display(plot_histogram(result.get_counts()))
# Plot state matrix like a city
#display(plot_state_city(state))
# Represent state matix using Pauli operators as the basis
#display(plot_state_paulivec(state))
# Plot state matrix as Hinton representation
#display(plot_state_hinton(state))
#print('\n')
backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 5
and not x.configuration().simulator
and x.status().operational==True))
def create5QGHZRealDevice(inp1, inp2, inp3, inp4, inp5):
qr = QuantumRegister(5)
cr = ClassicalRegister(5)
qc = QuantumCircuit(qr, cr)
qc.reset(range(5))
if inp1=='1':
qc.x(0)
if inp2=='1':
qc.x(1)
if inp3=='1':
qc.x(1)
if inp4=='1':
qc.x(1)
if inp5=='1':
qc.x(1)
qc.barrier()
qc.h(0)
qc.cx(0,1)
qc.cx(0,2)
qc.cx(0,3)
qc.cx(0,4)
qc.measure(qr, cr)
job = execute(qc, backend=backend, shots=1000)
job_monitor(job)
result = job.result()
return qc, result
inp1 = 0
inp2 = 0
inp3 = 0
inp4 = 0
inp5 = 0
#first results
qc, first_result = create5QGHZRealDevice(inp1, inp2, inp3, inp4, inp5)
first_counts = first_result.get_counts()
# Draw the quantum circuit
display(qc.draw())
#second results
qc, second_result = create5QGHZRealDevice(inp1, inp2, inp3, inp4, inp5)
second_counts = second_result.get_counts()
print('For inputs',inp5,inp4,inp3,inp2,inp1,'Representation of GHZ circuit states are,')
# Plot results on histogram with legend
legend = ['First execution', 'Second execution']
plot_histogram([first_counts, second_counts], legend=legend)
import qiskit
qiskit.__qiskit_version__
|
https://github.com/MonitSharma/Qiskit-Summer-School-and-Quantum-Challenges
|
MonitSharma
|
# Importing standard Qiskit libraries
from qiskit import QuantumCircuit, execute, Aer, IBMQ
from qiskit.compiler import transpile, assemble
from qiskit.tools.jupyter import *
from qiskit.visualization import *
from ibm_quantum_widgets import *
# useful to have pi
import math
pi=math.pi
# Loading your IBM Q account(s)
provider = IBMQ.load_account()
device = provider.get_backend('ibmq_5_yorktown')
qc=QuantumCircuit(3)
qc.ccx(0,1,2)
new_circuit = transpile(qc,backend=device)
new_circuit.draw(output='mpl')
qc = QuantumCircuit(3)
theta = pi # Theta can be anything (pi chosen arbitrarily)
# qc.h(2) gets replaced with
qc.rz(pi/2, 2)
qc.sx(2)
qc.rz(pi/2, 2)
#already basic gate
qc.cx(1,2)
# qc.tdg(2) gets replaced with
qc.rz(7*pi/4, 2)
#already basic gate
qc.cx(0,2)
# qc.t(2) gets replaced with
qc.rz(pi/4, 2)
#Already a basic gate
qc.cx(1,2)
# qc.tdg(2) gets replaced with
qc.rz(7*pi/4, 2)
#already a basic gate
qc.cx(0,2)
# qc.t(1) gets replaced with
qc.rz(pi/4, 1)
# qc.t(2) gets replaced with
qc.rz(pi/4, 2)
# qc.h(2) gets replaced with
qc.rz(pi/2, 2)
qc.sx(2)
qc.rz(pi/2, 2)
#Already a basic gate
qc.cx(0,1)
# qc.t(0) gets replaced with
qc.rz(pi/4, 0)
# qc.tdg(1) gets replaced with
qc.rz(pi/4, 1)
#already a basic gate
qc.cx(0,1)
qc.draw()
|
https://github.com/MonitSharma/Qiskit-Summer-School-and-Quantum-Challenges
|
MonitSharma
|
from qiskit import QuantumCircuit
from qiskit import QuantumRegister, QuantumCircuit
c = QuantumRegister(1, 'control')
t = QuantumRegister(2, 'target')
cu = QuantumCircuit(c, t, name="Controlled 13^x mod 35")
# Your code goes here
# easy (non-optimal) solution:
cu.ccx(c, t[0], t[1])
cu.cx(c, t[0])
# end solution
cu.draw()
c = QuantumRegister(1, 'control')
t = QuantumRegister(2, 'target')
cu2 = QuantumCircuit(c, t)
# Your code here
# Non-optimal solution:
cu2 = cu.compose(cu)
# end solution
cu2.draw()
c = QuantumRegister(1, 'control')
t = QuantumRegister(2, 'target')
cu4 = QuantumCircuit(c, t)
# Your code here
# VERY bad solution (to be removed):
cu4 = cu2.compose(cu2)
# end solution
cu4.draw()
cqr = QuantumRegister(3, 'control')
tqr = QuantumRegister(2, 'target')
cux = QuantumCircuit(cqr, tqr)
solutions = [cu, cu2, cu4]
for i in range(3):
cux = cux.compose(solutions[i], [cqr[i], tqr[0], tqr[1]])
cux.draw()
# To be removed before the challenge
from qiskit.circuit.library import QFT
from qiskit import transpile
import numpy as np
cqr = QuantumRegister(3, 'control')
tqr = QuantumRegister(2, 'target')
cux2 = QuantumCircuit(cqr, tqr)
cux2.append(QFT(2, do_swaps=False), [3, 4])
cux2.cz(0, 3)
cux2.cp(np.pi/2, 0, 4)
cux2.cz(1, 4)
cux2.append(QFT(2, inverse=True, do_swaps=False), [3, 4])
display(cux2.draw())
t_cux2 = transpile(cux2, basis_gates=['u','cx'], optimization_level=3)
display(t_cux2.draw())
t_cux2.count_ops()['cx']
from qiskit.circuit.library import QFT
from qiskit import ClassicalRegister
cr = ClassicalRegister(3)
shor_circuit = QuantumCircuit(cqr, tqr, cr)
shor_circuit.h(cqr)
shor_circuit.compose(cux2, inplace=True)
shor_circuit.append(QFT(3, inverse=True, do_swaps=True), cqr)
shor_circuit.measure(cqr, cr)
shor_circuit.draw()
from qiskit.test.mock import FakeAthens
from qiskit import assemble
from qiskit.visualization import plot_histogram
# we can do some more transpiling to squeeze out extra performance, but this isn't necessary
from qiskit.transpiler import PassManager
from qiskit.transpiler.passes import HoareOptimizer
athens = FakeAthens()
tqc = transpile(shor_circuit, athens, optimization_level=3)
pm = PassManager(HoareOptimizer())
tqc = pm.run(tqc)
counts = athens.run(assemble(tqc)).result().get_counts()
plot_histogram(counts)
|
https://github.com/MonitSharma/Qiskit-Summer-School-and-Quantum-Challenges
|
MonitSharma
|
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, Aer, assemble, transpile
import qiskit.tools.jupyter
from qiskit.test.mock import FakeTokyo
code = QuantumRegister(5,'code')
syn = QuantumRegister(4,'syn')
out = ClassicalRegister(4,'output')
backend = FakeTokyo()
error_qubits = [0,4]
# qc_syn
qc_syn = QuantumCircuit(code,syn,out)
# left ZZZ
qc_syn.cx(code[0],syn[1])
qc_syn.cx(code[2],syn[1])
qc_syn.cx(code[3],syn[1])
qc_syn.barrier()
# right ZZZ
qc_syn.cx(code[2],syn[2])
qc_syn.cx(code[4],syn[2])
qc_syn.cx(code[1],syn[0]) #
qc_syn.cx(syn[0],syn[2]) #
qc_syn.cx(code[1],syn[0]) #
qc_syn.barrier()
# top XXX
qc_syn.h(syn[0])
qc_syn.cx(syn[0],code[0])
qc_syn.cx(syn[0],code[1])
qc_syn.cx(syn[0],code[2])
qc_syn.h(syn[0])
qc_syn.barrier()
# bottom XXX
qc_syn.h(syn[3])
qc_syn.cx(syn[3],code[2])
qc_syn.cx(syn[3],code[3])
qc_syn.cx(syn[3],code[4])
qc_syn.h(syn[3])
qc_syn.barrier()
# measure the auxilliary qubits
qc_syn.measure(syn,out)
# qc_init
qc_init = QuantumCircuit(code,syn,out)
qc_init.h(syn[0])
qc_init.cx(syn[0],code[0])
qc_init.cx(syn[0],code[1])
qc_init.cx(syn[0],code[2])
qc_init.cx(code[2],syn[0])
qc_init.h(syn[3])
qc_init.cx(syn[3],code[2])
qc_init.cx(syn[3],code[3])
qc_init.cx(syn[3],code[4])
qc_init.cx(code[4],syn[3])
qc_init.barrier()
# initial layout
initial_layout = [0,2,6,10,12,1,5,7,11]
# qc_syn
qc_syn = QuantumCircuit(code,syn,out)
# left ZZZ
qc_syn.cx(code[0],syn[1])
qc_syn.cx(code[2],syn[1])
qc_syn.cx(code[3],syn[1])
qc_syn.barrier()
# right ZZZ
qc_syn.cx(code[2],syn[2])
qc_syn.cx(code[4],syn[2])
qc_syn.cx(code[1],syn[0])
qc_syn.cx(syn[0],syn[2])
qc_syn.cx(code[1],syn[0])
qc_syn.barrier()
# top XXX
qc_syn.h(syn[0])
qc_syn.cx(syn[0],code[0])
qc_syn.cx(syn[0],code[1])
qc_syn.cx(syn[0],code[2])
qc_syn.h(syn[0])
qc_syn.barrier()
# bottom XXX
qc_syn.h(syn[3])
qc_syn.cx(syn[3],code[2])
qc_syn.cx(syn[3],code[3])
qc_syn.cx(syn[3],code[4])
qc_syn.h(syn[3])
qc_syn.barrier()
# measure the auxilliary qubits
qc_syn.measure(syn,out)
# qc_init
qc_init = QuantumCircuit(code,syn,out)
# initial layout
initial_layout = [0,2,6,10,12,1,5,7,11]
# qc_syn
qc_syn = QuantumCircuit(code,syn,out)
qc_syn.measure(syn,out)
# qc_init
qc_init = QuantumCircuit(code,syn,out)
qc_init.h(syn[0])
qc_init.cx(syn[0],code[0])
qc_init.cx(syn[0],code[1])
qc_init.cx(syn[0],code[2])
qc_init.cx(code[2],syn[0])
qc_init.h(syn[3])
qc_init.cx(syn[3],code[2])
qc_init.cx(syn[3],code[3])
qc_init.cx(syn[3],code[4])
qc_init.cx(code[4],syn[3])
qc_init.barrier()
# initial layout
initial_layout = [0,2,6,10,12,1,5,7,11]
# qc_syn
qc_syn = QuantumCircuit(code,syn,out)
# left ZZZ
qc_syn.cx(code[0],syn[1])
qc_syn.cx(code[2],syn[1])
qc_syn.cx(code[3],syn[1])
qc_syn.barrier()
# right ZZZ
qc_syn.cx(code[2],syn[2])
qc_syn.cx(code[4],syn[2])
qc_syn.cx(code[1],syn[2])
qc_syn.barrier()
# top XXX
qc_syn.h(syn[0])
qc_syn.cx(syn[0],code[0])
qc_syn.cx(syn[0],code[1])
qc_syn.cx(syn[0],code[2])
qc_syn.h(syn[0])
qc_syn.barrier()
# bottom XXX
qc_syn.h(syn[3])
qc_syn.cx(syn[3],code[2])
qc_syn.cx(syn[3],code[3])
qc_syn.cx(syn[3],code[4])
qc_syn.h(syn[3])
qc_syn.barrier()
# measure the auxilliary qubits
qc_syn.measure(syn,out)
# qc_init
qc_init = QuantumCircuit(code,syn,out)
qc_init.h(code[0])
qc_init.cx(code[0],code[1])
qc_init.cx(code[0],code[2])
qc_init.h(code[3])
qc_init.cx(code[3],code[2])
qc_init.cx(code[3],code[4])
qc_init.barrier()
# initial layout
initial_layout = list(range(9))
|
https://github.com/MonitSharma/Qiskit-Summer-School-and-Quantum-Challenges
|
MonitSharma
|
# Import helper module from local folder
import sys
import os
sys.path.append(os.getcwd())
from resources import helper
# Numerical and plotting tools
import numpy as np
import matplotlib.pyplot as plt
# Import SI unit conversion factors
from resources.helper import GHz, MHz, kHz, us, ns
# Importing standard Qiskit libraries
from qiskit import IBMQ
from qiskit.tools.jupyter import *
# Loading your IBM Quantum account
IBMQ.load_account()
# IBMQ.providers() # see a list of providers you have access to
# Get the special provider assigned to you using information from the output above
hub_name = 'iqc2021-1' # e.g. 'iqc2021-1'
group_name = 'challenge-159' # e.g. 'challenge-1'
project_name = 'ex4' # Your project name should be 'ex4'
provider = IBMQ.get_provider(hub=hub_name, group=group_name, project=project_name)
# Get `ibmq_jakarta` backend from the provider
backend_name = 'ibmq_jakarta'
backend = provider.get_backend(backend_name)
backend # See details of the `ibmq_jakarta` quantum system
from qiskit import pulse
from qiskit.pulse import Play, Schedule, DriveChannel
# Please use qubit 0 throughout the notebook
qubit = 0
backend_config = backend.configuration()
exc_chans = helper.get_exc_chans(globals())
dt = backend_config.dt
print(f"Sampling time: {dt*1e9} ns")
backend_defaults = backend.defaults()
center_frequency = backend_defaults.qubit_freq_est
inst_sched_map = backend_defaults.instruction_schedule_map
inst_sched_map.instructions
# Retrieve calibrated measurement pulse from backend
meas = inst_sched_map.get('measure', qubits=[qubit])
meas.exclude(channels=exc_chans).draw(time_range=[0,1000])
from qiskit.pulse import DriveChannel, Gaussian
# The same spec pulse for both 01 and 12 spec
drive_amp = 0.25
drive_duration = inst_sched_map.get('x', qubits=[qubit]).duration
# Calibrated backend pulse use advanced DRAG pulse to reduce leakage to the |2> state.
# Here we will use simple Gaussian pulse
drive_sigma = drive_duration // 4 # DRAG pulses typically 4*sigma long.
spec_pulse = Gaussian(duration=drive_duration, amp=drive_amp,
sigma=drive_sigma, name=f"Spec drive amplitude = {drive_amp}")
# Construct an np array of the frequencies for our experiment
spec_freqs_GHz = helper.get_spec01_freqs(center_frequency, qubit)
# Create the base schedule
# Start with drive pulse acting on the drive channel
spec01_scheds = []
for freq in spec_freqs_GHz:
with pulse.build(name="Spec Pulse at %.3f GHz" % freq) as spec01_sched:
with pulse.align_sequential():
# Pay close attention to this part to solve the problem at the end
pulse.set_frequency(freq*GHz, DriveChannel(qubit))
pulse.play(spec_pulse, DriveChannel(qubit))
pulse.call(meas)
spec01_scheds.append(spec01_sched)
# Draw spec01 schedule
spec01_scheds[-1].exclude(channels=exc_chans).draw(time_range=[0,1000])
from qiskit.tools.monitor import job_monitor
# Run the job on a real backend
spec01_job = backend.run(spec01_scheds, job_name="Spec 01", **helper.job_params)
print(spec01_job.job_id())
job_monitor(spec01_job)
# If the queuing time is too long, you can save the job id
# And retrieve the job after it's done
# Replace 'JOB_ID' with the the your job id and uncomment to line below
#spec01_job = backend.retrieve_job('JOB_ID')
from resources.helper import SpecFitter
amp_guess = 5e6
f01_guess = 5
B = 1
C = 0
fit_guess = [amp_guess, f01_guess, B, C]
fit = SpecFitter(spec01_job.result(), spec_freqs_GHz, qubits=[qubit], fit_p0=fit_guess)
fit.plot(0, series='z')
f01 = fit.spec_freq(0, series='z')
print("Spec01 frequency is %.6f GHz" % f01)
# Retrieve qubit frequency from backend properties
f01_calibrated = backend.properties().frequency(qubit) / GHz
f01_error = abs(f01-f01_calibrated) * 1000 # error in MHz
print("Qubit frequency error is %.6f MHz" % f01_error)
max_rabi_amp = 0.75
rabi_amps = helper.get_rabi_amps(max_rabi_amp)
rabi_scheds = []
for ridx, amp in enumerate(rabi_amps):
with pulse.build(name="rabisched_%d_0" % ridx) as sched: # '0' corresponds to Rabi
with pulse.align_sequential():
pulse.set_frequency(f01*GHz, DriveChannel(qubit))
rabi_pulse = Gaussian(duration=drive_duration, amp=amp, \
sigma=drive_sigma, name=f"Rabi drive amplitude = {amp}")
pulse.play(rabi_pulse, DriveChannel(qubit))
pulse.call(meas)
rabi_scheds.append(sched)
# Draw rabi schedule
rabi_scheds[-1].exclude(channels=exc_chans).draw(time_range=[0,1000])
# Run the job on a real device
rabi_job = backend.run(rabi_scheds, job_name="Rabi", **helper.job_params)
print(rabi_job.job_id())
job_monitor(rabi_job)
# If the queuing time is too long, you can save the job id
# And retrieve the job after it's done
# Replace 'JOB_ID' with the the your job id and uncomment to line below
#rabi_job = backend.retrieve_job('JOB_ID')
from qiskit.ignis.characterization.calibrations.fitters import RabiFitter
amp_guess = 5e7
fRabi_guess = 2
phi_guess = 0.5
c_guess = 0
fit_guess = [amp_guess, fRabi_guess, phi_guess, c_guess]
fit = RabiFitter(rabi_job.result(), rabi_amps, qubits=[qubit], fit_p0=fit_guess)
fit.plot(qind=0, series='0')
x180_amp = fit.pi_amplitude()
print("Pi amplitude is %.3f" % x180_amp)
# Define pi pulse
x_pulse = Gaussian(duration=drive_duration,
amp=x180_amp,
sigma=drive_sigma,
name='x_pulse')
def build_spec12_pulse_schedule(freq, anharm_guess_GHz):
with pulse.build(name="Spec Pulse at %.3f GHz" % (freq+anharm_guess_GHz)) as spec12_schedule:
with pulse.align_sequential():
# WRITE YOUR CODE BETWEEN THESE LINES - START
# X Pulse
pulse.set_frequency(f01*GHz, DriveChannel(qubit))
pulse.play(x_pulse, DriveChannel(qubit))
# 0-2 Spec Pulse
pulse.set_frequency((freq+anharm_guess_GHz)*GHz, DriveChannel(qubit))
pulse.play(spec_pulse, DriveChannel(qubit))
pulse.call(meas)
# WRITE YOUR CODE BETWEEN THESE LINES - END
return spec12_schedule
anharmonicity_guess_GHz = -0.3 # your anharmonicity guess
freqs_GHz = helper.get_spec12_freqs(f01, qubit)
# Now vary the sideband frequency for each spec pulse
spec12_scheds = []
for freq in freqs_GHz:
spec12_scheds.append(build_spec12_pulse_schedule(freq, anharmonicity_guess_GHz))
# Draw spec12 schedule
spec12_scheds[-1].exclude(channels=exc_chans).draw(time_range=[0,1000])
spec12_scheds[1].exclude(channels=exc_chans).draw(time_range=[0,1000])
# Run the job on a real device
spec12_job = backend.run(spec12_scheds, job_name="Spec 12", **helper.job_params)
print(spec12_job.job_id())
job_monitor(spec12_job)
# If the queuing time is too long, you can save the job id
# And retrieve the job after it's done
# Replace 'JOB_ID' with the the your job id and uncomment to line below
#spec12_job = backend.retrieve_job('JOB_ID')
amp_guess = 2e7
f12_guess = f01 - 0.3
B = .1
C = 0
fit_guess = [amp_guess, f12_guess, B, C]
fit = SpecFitter(spec12_job.result(), freqs_GHz+anharmonicity_guess_GHz, qubits=[qubit], fit_p0=fit_guess)
fit.plot(0, series='z')
f12 = fit.spec_freq(0, series='z')
print("Spec12 frequency is %.6f GHz" % f12)
# Check your answer using following code
from qc_grader import grade_ex4
grade_ex4(f12,qubit,backend_name)
# Submit your answer. You can re-submit at any time.
from qc_grader import submit_ex4
submit_ex4(f12,qubit,backend_name)
Ec = f01 - f12
Ej = (2*f01-f12)**2/(8*(f01-f12))
print(f"Ej/Ec: {Ej/Ec:.2f}") # This value is typically ~ 30
|
https://github.com/MonitSharma/Qiskit-Summer-School-and-Quantum-Challenges
|
MonitSharma
|
# Classical HF computation
from qiskit_nature.drivers import PySCFDriver
molecule = "H .0 .0 .0; H .0 .0 0.739"
driver = PySCFDriver(atom=molecule)
qmolecule = driver.run()
n_el = qmolecule.num_alpha + qmolecule.num_beta
n_mo = qmolecule.num_molecular_orbitals
n_so = 2 * qmolecule.num_molecular_orbitals
n_q = n_so
e_nn = qmolecule.nuclear_repulsion_energy
print("1. Number of electrons: {}".format(n_el))
print("2. Number of molecular orbitals: {}".format(n_mo))
print("3. Number of spin-orbitals: {}".format(n_so))
print("4. Number of qubits: {}".format(n_q))
print("5. Nuclear repulsion energy: {}".format(e_nn))
# Generate the second-quantized operators
from qiskit_nature.problems.second_quantization.electronic import ElectronicStructureProblem
problem = ElectronicStructureProblem(driver)
second_q_ops = problem.second_q_ops()
main_op = second_q_ops[0]
from qiskit_nature.mappers.second_quantization import ParityMapper, BravyiKitaevMapper, JordanWignerMapper
from qiskit_nature.converters.second_quantization.qubit_converter import QubitConverter
# Setup the qubit converter
mapper_type = 'JordanWignerMapper'
if mapper_type == 'ParityMapper':
mapper = ParityMapper()
elif mapper_type == 'JordanWignerMapper':
mapper = JordanWignerMapper()
elif mapper_type == 'BravyiKitaevMapper':
mapper = BravyiKitaevMapper()
converter = QubitConverter(mapper=mapper, two_qubit_reduction=False)
# Exact solution
from qiskit_nature.algorithms.ground_state_solvers.minimum_eigensolver_factories import NumPyMinimumEigensolverFactory
from qiskit_nature.algorithms.ground_state_solvers import GroundStateEigensolver
import numpy as np
def exact_diagonalizer(problem, converter):
solver = NumPyMinimumEigensolverFactory()
calc = GroundStateEigensolver(converter, solver)
result = calc.solve(problem)
return result
result_exact = exact_diagonalizer(problem, converter)
exact_energy = np.real(result_exact.eigenenergies[0])
print("Exact electronic energy", exact_energy)
print(result_exact)
# The fermionic operators are mapped to qubit operators
num_particles = (problem.molecule_data_transformed.num_alpha,
problem.molecule_data_transformed.num_beta)
qubit_op = converter.convert(main_op, num_particles=num_particles)
from qiskit_nature.circuit.library import HartreeFock
num_particles = (problem.molecule_data_transformed.num_alpha,
problem.molecule_data_transformed.num_beta)
num_spin_orbitals = 2 * problem.molecule_data_transformed.num_molecular_orbitals
init_state = HartreeFock(num_spin_orbitals, num_particles, converter)
print(init_state)
from qiskit.circuit.library import TwoLocal
from qiskit_nature.circuit.library import UCCSD, PUCCD, SUCCD
from qiskit.circuit import Parameter, QuantumCircuit
# Choose the ansatz
ansatz_type = "TwoLocal"
# Parameters for q-UCC antatze
num_particles = (problem.molecule_data_transformed.num_alpha,
problem.molecule_data_transformed.num_beta)
num_spin_orbitals = 2 * problem.molecule_data_transformed.num_molecular_orbitals
# Put arguments for twolocal
if ansatz_type == "TwoLocal":
# Single qubit rotations that are placed on all qubits with independent parameters
rotation_blocks = ['ry']
# Entangling gates
entanglement_blocks = 'cx'
# How the qubits are entangled
entanglement = 'linear'
# Repetitions of rotation_blocks + entanglement_blocks with independent parameters
repetitions = 1
# Skip the final rotation_blocks layer
skip_final_rotation_layer = False
ansatz = TwoLocal(qubit_op.num_qubits, rotation_blocks, entanglement_blocks, reps=repetitions,
entanglement=entanglement, skip_final_rotation_layer=skip_final_rotation_layer)
# Add the initial state
ansatz.compose(init_state, front=True, inplace=True)
elif ansatz_type == "UCCSD":
ansatz = UCCSD(converter,num_particles,num_spin_orbitals,initial_state = init_state)
elif ansatz_type == "PUCCD":
ansatz = PUCCD(converter,num_particles,num_spin_orbitals,initial_state = init_state)
elif ansatz_type == "SUCCD":
ansatz = SUCCD(converter,num_particles,num_spin_orbitals,initial_state = init_state)
elif ansatz_type == "Custom":
num_qubits = qubit_op.num_qubits
qc = QuantumCircuit(num_qubits)
param_count = 1
for i in range(num_qubits):
theta = Parameter(f"ry_angle{param_count}" )
qc.ry(theta, i)
param_count += 1
qc.cx(0,1)
qc.cx(1,2)
qc.cx(2,3)
for i in range(num_qubits):
theta = Parameter(f"ry_angle{param_count}")
qc.ry(theta, i)
param_count += 1
ansatz = qc
ansatz.compose(init_state, front=True, inplace=True)
print(ansatz)
# Backend
from qiskit import Aer
backend = Aer.get_backend('statevector_simulator')
# Classical optimizer
from qiskit.algorithms.optimizers import COBYLA, L_BFGS_B, SPSA, SLSQP
optimizer_type = 'COBYLA'
# You may want to tune the parameters
# of each optimizer, here the defaults are used
if optimizer_type == 'COBYLA':
optimizer = COBYLA(maxiter=500)
elif optimizer_type == 'L_BFGS_B':
optimizer = L_BFGS_B(maxfun=500)
elif optimizer_type == 'SPSA':
optimizer = SPSA(maxiter=500)
elif optimizer_type == 'SLSQP':
optimizer = SLSQP(maxiter=500)
# Run VQE
from qiskit.algorithms import VQE
from IPython.display import display, clear_output
# Print and save the data in lists
def callback(eval_count, parameters, mean, std):
# Overwrites the same line when printing
display("Evaluation: {}, Energy: {}, Std: {}".format(eval_count, mean, std))
clear_output(wait=True)
counts.append(eval_count)
values.append(mean)
params.append(parameters)
deviation.append(std)
counts = []
values = []
params = []
deviation = []
# Set initial parameters of the ansatz
# We choose a fixed small displacement
# So all participants start from similar starting point
try:
initial_point = [0.01] * len(ansatz.ordered_parameters)
except:
initial_point = [0.01] * ansatz.num_parameters
algorithm = VQE(ansatz,
optimizer=optimizer,
quantum_instance=backend,
callback=callback,
initial_point=initial_point)
result = algorithm.compute_minimum_eigenvalue(qubit_op)
print(result)
# Store results in a dictionary
from qiskit.transpiler import PassManager
from qiskit.transpiler.passes import Unroller
# Unroller transpile your circuit into CNOTs and U gates
pass_ = Unroller(['u', 'cx'])
pm = PassManager(pass_)
ansatz_tp = pm.run(ansatz)
cnots = ansatz_tp.count_ops()['cx']
score = cnots
accuracy_threshold = 4.0 # in mHa
energy = result.optimal_value
if ansatz_type == "TwoLocal":
result_dict = {
'optimizer': optimizer.__class__.__name__,
'mapping': converter.mapper.__class__.__name__,
'ansatz': ansatz.__class__.__name__,
'rotation blocks': rotation_blocks,
'entanglement_blocks': entanglement_blocks,
'entanglement': entanglement,
'repetitions': repetitions,
'skip_final_rotation_layer': skip_final_rotation_layer,
'energy (Ha)': energy,
'error (mHa)': (energy-exact_energy)*1000,
'pass': (energy-exact_energy)*1000 <= accuracy_threshold,
'# of parameters': len(result.optimal_point),
'final parameters': result.optimal_point,
'# of evaluations': result.optimizer_evals,
'optimizer time': result.optimizer_time,
'# of qubits': int(qubit_op.num_qubits),
'# of CNOTs': cnots,
'score': score}
else:
result_dict = {
'optimizer': optimizer.__class__.__name__,
'mapping': converter.mapper.__class__.__name__,
'ansatz': ansatz.__class__.__name__,
'rotation blocks': None,
'entanglement_blocks': None,
'entanglement': None,
'repetitions': None,
'skip_final_rotation_layer': None,
'energy (Ha)': energy,
'error (mHa)': (energy-exact_energy)*1000,
'pass': (energy-exact_energy)*1000 <= accuracy_threshold,
'# of parameters': len(result.optimal_point),
'final parameters': result.optimal_point,
'# of evaluations': result.optimizer_evals,
'optimizer time': result.optimizer_time,
'# of qubits': int(qubit_op.num_qubits),
'# of CNOTs': cnots,
'score': score}
# Plot the results
import matplotlib.pyplot as plt
fig, ax = plt.subplots(1, 1)
ax.set_xlabel('Iterations')
ax.set_ylabel('Energy')
ax.grid()
fig.text(0.7, 0.75, f'Energy: {result.optimal_value:.3f}\nScore: {score:.0f}')
plt.title(f"{result_dict['optimizer']}-{result_dict['mapping']}\n{result_dict['ansatz']}")
ax.plot(counts, values)
ax.axhline(exact_energy, linestyle='--')
fig_title = f"\
{result_dict['optimizer']}-\
{result_dict['mapping']}-\
{result_dict['ansatz']}-\
Energy({result_dict['energy (Ha)']:.3f})-\
Score({result_dict['score']:.0f})\
.png"
fig.savefig(fig_title, dpi=300)
# Display and save the data
import pandas as pd
import os.path
filename = 'results_h2.csv'
if os.path.isfile(filename):
result_df = pd.read_csv(filename)
result_df = result_df.append([result_dict])
else:
result_df = pd.DataFrame.from_dict([result_dict])
result_df.to_csv(filename)
result_df[['optimizer','ansatz', '# of qubits', '# of parameters','rotation blocks', 'entanglement_blocks',
'entanglement', 'repetitions', 'error (mHa)', 'pass', 'score']]
from qiskit_nature.drivers import PySCFDriver
molecule = 'Li 0.0 0.0 0.0; H 0.0 0.0 1.5474'
driver = PySCFDriver(atom=molecule)
qmolecule = driver.run()
n_el = qmolecule.num_alpha + qmolecule.num_beta
n_mo = qmolecule.num_molecular_orbitals
n_so = 2 * qmolecule.num_molecular_orbitals
n_q = n_so
e_nn = qmolecule.nuclear_repulsion_energy
print("Number of electrons: {}".format(n_el))
print("Number of molecular orbitals: {}".format(n_mo))
print("Number of spin-orbitals: {}".format(n_so))
print("Number of qubits: {}".format(n_q))
print("Nuclear repulsion energy: {}".format(e_nn))
# Generate the second-quantized operators
from qiskit_nature.problems.second_quantization.electronic import ElectronicStructureProblem
problem = ElectronicStructureProblem(driver)
second_q_ops = problem.second_q_ops()
main_op = second_q_ops[0]
from qiskit_nature.mappers.second_quantization import ParityMapper, BravyiKitaevMapper, JordanWignerMapper
from qiskit_nature.converters.second_quantization.qubit_converter import QubitConverter
# Setup the qubit converter
mapper_type = 'JordanWignerMapper'
if mapper_type == 'ParityMapper':
mapper = ParityMapper()
elif mapper_type == 'JordanWignerMapper':
mapper = JordanWignerMapper()
elif mapper_type == 'BravyiKitaevMapper':
mapper = BravyiKitaevMapper()
converter = QubitConverter(mapper=mapper, two_qubit_reduction=False)
# Exact solution
from qiskit_nature.algorithms.ground_state_solvers.minimum_eigensolver_factories import NumPyMinimumEigensolverFactory
from qiskit_nature.algorithms.ground_state_solvers import GroundStateEigensolver
import numpy as np
def exact_diagonalizer(problem, converter):
solver = NumPyMinimumEigensolverFactory()
calc = GroundStateEigensolver(converter, solver)
result = calc.solve(problem)
return result
result_exact = exact_diagonalizer(problem, converter)
exact_energy = np.real(result_exact.eigenenergies[0])
print("Exact electronic energy", exact_energy)
print(result_exact)
from qiskit_nature.problems.second_quantization.electronic import ElectronicStructureProblem
from qiskit_nature.transformers import FreezeCoreTransformer
freezeCoreTransformer = FreezeCoreTransformer(True)
problem = ElectronicStructureProblem(driver, q_molecule_transformers=[freezeCoreTransformer])
# Generate the second-quantized operators
second_q_ops = problem.second_q_ops()
# Hamiltonian
main_op = second_q_ops[0]
from qiskit_nature.mappers.second_quantization import ParityMapper
from qiskit_nature.converters.second_quantization.qubit_converter import QubitConverter
# Setup the mapper and qubit converter
mapper_type = 'ParityMapper'
mapper = ParityMapper()
converter = QubitConverter(mapper=mapper, two_qubit_reduction=True)
# The fermionic operators are mapped to qubit operators
num_particles = (problem.molecule_data_transformed.num_alpha,
problem.molecule_data_transformed.num_beta)
symmetries = True
if symmetries:
num_particles = (problem.molecule_data_transformed.num_alpha,
problem.molecule_data_transformed.num_beta)
converter = QubitConverter(mapper, two_qubit_reduction=True, z2symmetry_reduction="auto")
qubit_op = converter.convert(
main_op,
num_particles,
sector_locator=problem.symmetry_sector_locator,
)
else:
converter = QubitConverter(mapper=mapper, two_qubit_reduction=True)
qubit_op = converter.convert(main_op, num_particles=num_particles)
print("Number of qubits: ", qubit_op.num_qubits)
result_exact = exact_diagonalizer(problem, converter)
exact_energy = np.real(result_exact.eigenenergies[0])
print("Exact electronic energy", exact_energy)
print(result_exact)
from qiskit_nature.problems.second_quantization.electronic import ElectronicStructureProblem
from qiskit_nature.transformers import FreezeCoreTransformer
# Eliminate the MOs 3 and 4 that correspond to 2px and 2py in addition to freezen the core electrons
freezeCoreTransformer = FreezeCoreTransformer(True,[3,4])
problem = ElectronicStructureProblem(driver, q_molecule_transformers=[freezeCoreTransformer])
# Generate the second-quantized operators
second_q_ops = problem.second_q_ops()
# Hamiltonian
main_op = second_q_ops[0]
from qiskit_nature.mappers.second_quantization import ParityMapper
from qiskit_nature.converters.second_quantization.qubit_converter import QubitConverter
# Setup the mapper and qubit converter
mapper_type = 'ParityMapper'
mapper = ParityMapper()
converter = QubitConverter(mapper=mapper, two_qubit_reduction=True)
# The fermionic operators are mapped to qubit operators
num_particles = (problem.molecule_data_transformed.num_alpha,
problem.molecule_data_transformed.num_beta)
symmetries = False
if symmetries:
num_particles = (problem.molecule_data_transformed.num_alpha,
problem.molecule_data_transformed.num_beta)
converter = QubitConverter(mapper, two_qubit_reduction=True, z2symmetry_reduction="auto")
qubit_op = converter.convert(
main_op,
num_particles,
sector_locator=problem.symmetry_sector_locator,
)
else:
converter = QubitConverter(mapper=mapper, two_qubit_reduction=True)
qubit_op = converter.convert(main_op, num_particles=num_particles)
print("Number of qubits: ", qubit_op.num_qubits)
result_exact = exact_diagonalizer(problem, converter)
exact_energy = np.real(result_exact.eigenenergies[0])
print("Exact electronic energy", exact_energy)
from qiskit_nature.circuit.library import HartreeFock
num_particles = (problem.molecule_data_transformed.num_alpha,
problem.molecule_data_transformed.num_beta)
num_spin_orbitals = 2 * problem.molecule_data_transformed.num_molecular_orbitals
init_state = HartreeFock(num_spin_orbitals, num_particles, converter)
init_state.draw()
# ansatz 1
num_qubits = qubit_op.num_qubits
qc = QuantumCircuit(num_qubits)
param_count = 1
for i in range(num_qubits):
theta = Parameter(f"ry_angle{param_count}" )
qc.ry(theta, i)
param_count += 1
qc.cx(0,1)
qc.cx(1,2)
qc.cx(2,3)
for i in range(num_qubits):
theta = Parameter(f"ry_angle{param_count}")
qc.ry(theta, i)
param_count += 1
ansatz = qc
ansatz.compose(init_state, front=True, inplace=True)
ansatz.draw()
# ansatz 2
# num_qubits = qubit_op.num_qubits
# qc = QuantumCircuit(num_qubits)
# param_count = 1
# for i in range(num_qubits):
# theta = Parameter(f"ry_angle{param_count}" )
# theta2 = Parameter(f"rz_angle{param_count}" )
# qc.ry(theta, i)
# qc.rz(theta2, i)
# param_count += 1
# qc.cx(2,3)
# qc.cx(0,2)
# qc.cx(1,3)
# for i in range(num_qubits):
# theta = Parameter(f"ry_angle{param_count}")
# theta2 = Parameter(f"rz_angle{param_count}" )
# qc.ry(theta, i)
# qc.rz(theta2, i)
# param_count += 1
# ansatz = qc
# ansatz.compose(init_state, front=True, inplace=True)
# ansatz.draw()
from qiskit import Aer
backend = Aer.get_backend('statevector_simulator')
from qiskit.algorithms.optimizers import SLSQP
optimizer_type = 'SLSQP'
optimizer = SLSQP(maxiter=1000)
from qiskit.algorithms import VQE
from IPython.display import display, clear_output
# Print and save the data in lists
def callback(eval_count, parameters, mean, std):
# Overwrites the same line when printing
display("Evaluation: {}, Energy: {}, Std: {}".format(eval_count, mean, std))
clear_output(wait=True)
counts.append(eval_count)
values.append(mean)
params.append(parameters)
deviation.append(std)
counts = []
values = []
params = []
deviation = []
# Set initial parameters of the ansatz
# We choose a fixed small displacement
# So all participants start from similar starting point
try:
initial_point = [0.01] * len(ansatz.ordered_parameters)
except:
initial_point = [0.01] * ansatz.num_parameters
algorithm = VQE(ansatz,
optimizer=optimizer,
quantum_instance=backend,
callback=callback,
initial_point=initial_point)
result = algorithm.compute_minimum_eigenvalue(qubit_op)
print(result)
# Store results in a dictionary
from qiskit.transpiler import PassManager
from qiskit.transpiler.passes import Unroller
# Unroller transpile your circuit into CNOTs and U gates
pass_ = Unroller(['u', 'cx'])
pm = PassManager(pass_)
ansatz_tp = pm.run(ansatz)
cnots = ansatz_tp.count_ops()['cx']
score = cnots
accuracy_threshold = 4.0 # in mHa
energy = result.optimal_value
if ansatz_type == "TwoLocal":
result_dict = {
'optimizer': optimizer.__class__.__name__,
'mapping': converter.mapper.__class__.__name__,
'ansatz': ansatz.__class__.__name__,
'rotation blocks': rotation_blocks,
'entanglement_blocks': entanglement_blocks,
'entanglement': entanglement,
'repetitions': repetitions,
'skip_final_rotation_layer': skip_final_rotation_layer,
'energy (Ha)': energy,
'error (mHa)': (energy-exact_energy)*1000,
'pass': (energy-exact_energy)*1000 <= accuracy_threshold,
'# of parameters': len(result.optimal_point),
'final parameters': result.optimal_point,
'# of evaluations': result.optimizer_evals,
'optimizer time': result.optimizer_time,
'# of qubits': int(qubit_op.num_qubits),
'# of CNOTs': cnots,
'score': score}
else:
result_dict = {
'optimizer': optimizer.__class__.__name__,
'mapping': converter.mapper.__class__.__name__,
'ansatz': ansatz.__class__.__name__,
'rotation blocks': None,
'entanglement_blocks': None,
'entanglement': None,
'repetitions': None,
'skip_final_rotation_layer': None,
'energy (Ha)': energy,
'error (mHa)': (energy-exact_energy)*1000,
'pass': (energy-exact_energy)*1000 <= accuracy_threshold,
'# of parameters': len(result.optimal_point),
'final parameters': result.optimal_point,
'# of evaluations': result.optimizer_evals,
'optimizer time': result.optimizer_time,
'# of qubits': int(qubit_op.num_qubits),
'# of CNOTs': cnots,
'score': score}
# Plot the results
import matplotlib.pyplot as plt
fig, ax = plt.subplots(1, 1)
ax.set_xlabel('Iterations')
ax.set_ylabel('Energy')
ax.grid()
fig.text(0.7, 0.75, f'Energy: {result.optimal_value:.3f}\nScore: {score:.0f}')
plt.title(f"{result_dict['optimizer']}-{result_dict['mapping']}\n{result_dict['ansatz']}")
ax.plot(counts, values)
ax.axhline(exact_energy, linestyle='--')
fig_title = f"\
{result_dict['optimizer']}-\
{result_dict['mapping']}-\
{result_dict['ansatz']}-\
Energy({result_dict['energy (Ha)']:.3f})-\
Score({result_dict['score']:.0f})\
.png"
fig.savefig(fig_title, dpi=300)
# Display and save the data
import pandas as pd
import os.path
filename = 'results_lih.csv'
if os.path.isfile(filename):
result_df = pd.read_csv(filename)
result_df = result_df.append([result_dict])
else:
result_df = pd.DataFrame.from_dict([result_dict])
result_df.to_csv(filename)
result_df[['optimizer','ansatz', '# of qubits', 'error (mHa)', 'pass', 'score']]
|
https://github.com/MonitSharma/Qiskit-Summer-School-and-Quantum-Challenges
|
MonitSharma
|
import numpy as np
import pandas as pd
import itertools
import cma
import os
import sys
import argparse
import pickle
import random
import re
from pprint import pprint
import qiskit
from qiskit import *
from qiskit import Aer
from qiskit import IBMQ
from qiskit.providers.aer.noise.noise_model import NoiseModel
from qiskit.test.mock import *
from qiskit.providers.aer import AerSimulator, QasmSimulator
from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter
import mitiq
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q-utokyo', group='internal', project='hirashi-jst')
provider = IBMQ.get_provider(hub='', group='internal', project='hirashi-jst')
print("provider:", provider)
L = 3
p = 2
dt = 1.0
tf = 20
shots = 8192
def TwirlCircuit(circ: str) -> QuantumCircuit:
"""
そのまま使う: 修正は後回し
"""
#! qasm ベタ書き
def apply_pauli(num: int, qb: int) -> str:
if (num == 0):
return f'id q[{qb}];\n'
elif (num == 1):
return f'x q[{qb}];\n'
elif (num == 2):
return f'y q[{qb}];\n'
else:
return f'z q[{qb}];\n'
paulis = [(i,j) for i in range(0,4) for j in range(0,4)]
paulis.remove((0,0))
paulis_map = [(0, 1), (3, 2), (3, 3), (1, 1), (1, 0), (2, 3), (2, 2), (2, 1), (2, 0), (1, 3), (1, 2), (3, 0), (3, 1), (0, 2), (0, 3)]
new_circ = ''
ops = circ.qasm().splitlines(True) #! 生のqasmコードを持ってきてる: オペレータに分解
for op in ops:
if (op[:2] == 'cx'): # can add for cz, etc.
num = random.randrange(len(paulis)) #! permute paulis
qbs = re.findall('q\[(.)\]', op)
new_circ += apply_pauli(paulis[num][0], qbs[0])
new_circ += apply_pauli(paulis[num][1], qbs[1])
new_circ += op
new_circ += apply_pauli(paulis_map[num][0], qbs[0])
new_circ += apply_pauli(paulis_map[num][1], qbs[1])
else:
new_circ += op
return qiskit.circuit.QuantumCircuit.from_qasm_str(new_circ)
# とりあえずOK
def evolve(alpha: float, q0: Union[int, QuantumRegister], q1: Union[int, QuantumRegister]) -> QuantumCircuit:
"""
The implementation of Fig. 4 in https://arxiv.org/abs/2112.12654
"""
qc = QuantumCircuit(2)
qc.rz(-np.pi / 2, q1)
qc.cnot(q1, q0)
qc.rz(alpha - np.pi / 2, q0)
qc.ry(np.pi / 2 - alpha, q1)
qc.cnot(q0, q1)
qc.ry(alpha - np.pi / 2, q1)
qc.cnot(q1, q0)
qc.rz(np.pi / 2, q0)
return qc
# とりあえずOK
def make_ansatz_circuit(num_qubits: int, ansatz_depth: int, parameters: np.array) -> QuantumCircuit:
"""
Prepare ansatz circuit
code reference: https://gitlab.com/QANED/heis_dynamics
method reference: https://arxiv.org/abs/1906.06343
== AnsatzCircuit(param, p) -> QuantumCircuit
Args:
parameters: 1d array (for 2d parameters on circuit)
"""
qc = QuantumCircuit(num_qubits)
for l in range(ansatz_depth):
if num_qubits & 1:
for i in range(0, num_qubits, 2): # linear condition
qc.compose(evolve(parameters[l * ansatz_depth + i] / 4), [i, i + 1], inplace = True) #! we do not have to divide the angle by 4
for i in range(1, num_qubits - 1, 2): # linear condition
# ! we do not have to divide the angle by 4
qc.compose(evolve(parameters[l * ansatz_depth + i] / 4), [i, i + 1], inplace=True)
else:
for i in range(0, num_qubits - 1, 2): # linear condition
# ! we do not have to divide the angle by 4
qc.compose(evolve(parameters[l * ansatz_depth + i]), [i, i + 1], inplace=True)
for i in range(1, num_qubits - 1, 2): # linear condition
# ! we do not have to divide the angle by 4
qc.compose(evolve(parameters[l * ansatz_depth + i]), [i, i + 1], inplace=True)
return qc
# とりあえずOK
def make_trotter_circuit(num_qubits: int, time_interval: float) -> QuantumCircuit:
"""
Prepare Trotter circuit
code reference: https://gitlab.com/QANED/heis_dynamics
method reference: https://arxiv.org/abs/1906.06343
== TrotterEvolveCircuit(dt, nt, init) -> QuantumCircuit
"""
qc = QuantumCircuit(num_qubits)
for n in range(trotter_steps): #! time_interval の符号に注意
if num_qubits & 1:
for i in range(0, num_qubits, 2): # linear condition
qc.compose(evolve(time_interval / 4), [i, i + 1], inplace = True) #! we do not have to divide the angle by 4
for i in range(1, num_qubits - 1, 2): # linear condition
qc.compose(evolve(time_interval / 4), [i, i + 1], inplace = True) # ! we do not have to divide the angle by 4
else:
for i in range(0, num_qubits - 1, 2): # linear condition
qc.compose(evolve(time_interval / 4), [i, i + 1], inplace = True) #! we do not have to divide the angle by 4
for i in range(1, num_qubits - 1, 2): # linear condition
qc.compose(evolve(time_interval / 4), [i, i + 1], inplace = True) # ! we do not have to divide the angle by 4
return qc
#TODO VTCとは別実装?→ no, 同じ実装に。
def SimulateAndReorder(circ):
"""
#! execution wrapper
Executes a circuit using the statevector simulator and reorders basis to match with standard
"""
backend = Aer.get_backend('statevector_simulator')
return execute(circ.reverse_bits(), backend).result().get_statevector()
def Simulate(circ):
"""
#! execution wrapper
Executes a circuit using the statevector simulator. Doesn't reorder -- which is needed for intermediate steps in the VTC
"""
backend = Aer.get_backend('statevector_simulator')
return execute(circ, backend).result().get_statevector()
#TODO
def LoschmidtEchoExecutor(circuits, backend, shots, filter):
"""
#! 回路を実行
Returns the expectation value to be mitigated.
:param circuit: Circuit to run. #! ここでのcircuitsは
:param backend: backend to run the circuit on
:param shots: Number of times to execute the circuit to compute the expectation value.
:param fitter: measurement error mitigator
"""
# circuits = [TwirlCircuit(circ) for circ in circuits]
scale_factors = [1.0, 2.0, 3.0] #! ZNEのノイズスケーリングパラメタ
folded_circuits = [] #! ZNE用の回路
for circuit in circuits:
folded_circuits.append([mitiq.zne.scaling.fold_gates_at_random(circuit, scale) for scale in scale_factors]) #! ここでmitiqを使用
folded_circuits = list(itertools.chain(*folded_circuits)) #! folded_circuitsを平坦化
folded_circuits = [TwirlCircuit(circ) for circ in folded_circuits] #! 後からPauli Twirlingを施す!
print("length of circuit in job", len(folded_circuits))
#! jobを投げる
job = qiskit.execute(
experiments=folded_circuits,
backend=backend,
optimization_level=0,
shots=shots
)
print("casted job")
#! fidelity測定用(VTCをしないなら、ここはtomographyで良い)
c = ['1','1','0'] #! これをpermutationする
# c = [str((1 + (-1)**(i+1)) // 2) for i in range(L)]
c = ''.join(c)[::-1] #! endianを反転 (big endianへ)
res = job.result()
if (filter is not None): #! QREM
res = filter.apply(res)
print("retrieved job")
all_counts = [job.result().get_counts(i) for i in range(len(folded_circuits))]
expectation_values = []
for counts in all_counts:
total_allowed_shots = [counts.get(''.join(p)) for p in set(itertools.permutations(c))] #! ここでcをpermutationしている
total_allowed_shots = sum([0 if x is None else x for x in total_allowed_shots])
if counts.get(c) is None:
expectation_values.append(0)
else:
expectation_values.append(counts.get(c)/total_allowed_shots)
# expectation_values = [counts.get(c) / shots for counts in all_counts]
zero_noise_values = []
if isinstance(backend, qiskit.providers.aer.backends.qasm_simulator.QasmSimulator): # exact_sim
for i in range(len(circuits)):
zero_noise_values.append(np.mean(expectation_values[i*len(scale_factors):(i+1)*len(scale_factors)]))
else: #device_sim, real_device
fac = mitiq.zne.inference.LinearFactory(scale_factors)
for i in range(len(circuits)):
zero_noise_values.append(fac.extrapolate(scale_factors,
expectation_values[i*len(scale_factors):(i+1)*len(scale_factors)]))
print("zero_noise_values")
pprint(zero_noise_values)
print()
return zero_noise_values
#TODO
def LoschmidtEchoCircuit(params, U_v, U_trot, init, p):
"""
#! 回路を作成
Cost function using the Loschmidt Echo. Just using statevectors currently -- can rewrite using shots
:param params: parameters new variational circuit that represents U_trot U_v | init >. Need dagger for cost function
:param U_v: variational circuit that stores the state before the trotter step
:param U_trot: trotter step
:param init: initial state
:param p: number of ansatz steps
"""
U_v_prime = AnsatzCircuit(params, p)
circ = init + U_v + U_trot + U_v_prime.inverse()
circ.measure_all()
return circ
def LoschmidtEcho(params, U_v, U_trot, init, p, backend, shots, filter):
"""
#! 実行パート
"""
circs = []
for param in params:
circs.append(LoschmidtEchoCircuit(param, U_v, U_trot, init, p)) #! 回路を作成
print("length of circuits without zne:", len(circs))
res = LoschmidtEchoExecutor(circs, backend, shots, filter) #! 回路を実行
return abs(1 - np.array(res))
def LoschmidtEchoExact(params, U_v, U_trot, init, p):
"""
#! unused function
"""
U_v_prime = AnsatzCircuit(params, p)
circ = init + U_v + U_trot + U_v_prime.inverse()
circ_vec = Simulate(circ)
init_vec = Simulate(init)
return 1 - abs(np.conj(circ_vec) @ init_vec)**2
def CMAES(U_v, U_trot, init, p, backend, shots, filter):
"""
#! 実行 + 最適化パート
"""
init_params = np.random.uniform(0, 2*np.pi, (L-1)*p)
es = cma.CMAEvolutionStrategy(init_params, np.pi/2)
es.opts.set({'ftarget':5e-3, 'maxiter':1000})
# es = pickle.load(open(f'./results_{L}/optimizer_dump', 'rb'))
while not es.stop(): #! 最適化パート
# solutions = es.ask(25) # ! 25 = number of returned solutions
solutions = es.ask(10)
print("solutions")
pprint(solutions)
es.tell(solutions, LoschmidtEcho(solutions, U_v, U_trot, init, p, backend, shots, filter)) #! 実行パート
# es.tell(solutions, LoschmidtEchoExact(solutions, U_v, U_trot, init, p)) #! 実行パート
es.disp()
open(f'./results_{L}/optimizer_dump', 'wb').write(es.pickle_dumps())
return es.result_pretty()
def VTC(tf, dt, p, init, backend, shots, filter):
"""
#! tf: 総経過時間
#! dt: trotter step size: 時間間隔
#! p: ansatzのステップ数
"""
VTCParamList = [np.zeros((L-1)*p)] #! デフォルトのパラメタ(初期値)
VTCStepList = [SimulateAndReorder(init.copy())] #! type: List[Statevector]
# TrotterFixStepList = [init]
TimeStep = [0]
if (os.path.exists(f'./results_{L}/VTD_params_{tf}_{L}_{p}_{dt}_{shots}.csv')): #! 2巡目からこっち
VTCParamList = pd.read_csv(f'./results_{L}/VTD_params_{tf}_{L}_{p}_{dt}_{shots}.csv', index_col=0)
VTCStepList = pd.read_csv(f'./results_{L}/VTD_results_{tf}_{L}_{p}_{dt}_{shots}.csv', index_col=0)
temp = VTCParamList.iloc[-1]
print(temp, "th time interval")
U_v = AnsatzCircuit(temp, p)
else: #! 最初はこっちに入る
VTCParamList = pd.DataFrame(np.array(VTCParamList), index=np.array(TimeStep))
VTCStepList = pd.DataFrame(np.array(VTCStepList), index=np.array(TimeStep))
print("0 th time interval")
print()
U_v = QuantumCircuit(L)
ts = VTCParamList.index
#! 時間間隔
U_trot = TrotterEvolveCircuit(dt, p, QuantumCircuit(L)) #! Trotter分解のunitaryを作る
print()
print("start CMAES")
print()
res = CMAES(U_v, U_trot, init, p, backend, shots, filter) #! ここでプロセスを実行!!!!
print()
print("res")
pprint(res)
#! 新しいループ結果を追加し、tsを更新
res = res.xbest # ! best solution evaluated
print("res.xbest")
pprint(res)
VTCParamList.loc[ts[-1]+(dt*p)] = np.array(res)
VTCStepList.loc[ts[-1]+(dt*p)] = np.array(SimulateAndReorder(init + AnsatzCircuit(res, p)))
ts = VTCParamList.index
# VTCParamList = pd.DataFrame(np.array(VTCParamList), index=np.array(TimeStep))
# VTCStepList = pd.DataFrame(np.array(VTCStepList), index=np.array(TimeStep))
#! csvファイルを更新
VTCParamList.to_csv(f'./results_{L}/VTD_params_{tf}_{L}_{p}_{dt}_{shots}.csv')
VTCStepList.to_csv(f'./results_{L}/VTD_results_{tf}_{L}_{p}_{dt}_{shots}.csv')
if (ts[-1] >= tf):
return
else:
print("next step")
VTC(tf, dt, p, init, backend, shots, filter)
#! ここからQREM回路
qr = QuantumRegister(L)
meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal')
# device_backend = FakeJakarta()
# device_sim = AerSimulator.from_backend(device_backend)
real_device = provider.get_backend('ibmq_jakarta')
noise_model = NoiseModel.from_backend(real_device)
device_sim = QasmSimulator(method='statevector', noise_model=noise_model)
exact_sim = Aer.get_backend('qasm_simulator') # QasmSimulator(method='statevector')
t_qc = transpile(meas_calibs)
qobj = assemble(t_qc, shots=8192)
# cal_results = real_device.run(qobj, shots=8192).result()
cal_results = device_sim.run(qobj, shots=8192).result()
meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal')
print("qrem done")
# np.around(meas_fitter.cal_matrix, decimals=2)
init = QuantumCircuit(L)
# c = [str((1 + (-1)**(i+1)) // 2) for i in range(L)]
c = ['1','1','0'] #! なぜinitial stateが110なの??????? もしかしてopen science prizeを意識???
#! けどループでこのプログラムが実行されるたびにここが|110>だとおかしくないか?
for q in range(len(c)):
if (c[q] == '1'):
init.x(q)
#! ここまでQREM回路
nt = int(np.ceil(tf / (dt * p)))
# f = open(f'./results_{L}/logging.txt', 'a')
# sys.stdout = f
#! tf: シミュレーションの(経過)時間
#! dt: trotter分解のステップ数
#! p: ansatzのステップ数 (論文中のL)
# VTC(tf, dt, p, init, real_device, shots, meas_fitter.filter) #! mainの処理
print("vtc start!!!! \n\n\n")
VTC(tf, dt, p, init, device_sim, shots, meas_fitter.filter) #! mainの処理
# f.close()
|
https://github.com/MonitSharma/Qiskit-Summer-School-and-Quantum-Challenges
|
MonitSharma
|
import numpy as np
import matplotlib.pyplot as plt
from copy import deepcopy
# Importing standard Qiskit libraries
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, transpile, Aer, IBMQ, execute
from qiskit.tools.jupyter import *
from qiskit.visualization import *
from qiskit.providers.aer import QasmSimulator
from tqdm.notebook import tqdm
from qiskit.providers.aer import QasmSimulator
from qiskit.tools.monitor import job_monitor
from qiskit.circuit import Parameter
import qiskit.quantum_info as qi
from qc_grader.challenges.spring_2022.helpers import generate_XX, generate_YY, generate_disordered_tb_instruction
# Suppress warnings
import warnings
warnings.filterwarnings('ignore')
import pylatexenc
import IPython
t = Parameter('t')
XX = generate_XX(t)
YY = generate_YY(t)
from scipy.special import jv
t_test = 20
r = np.linspace(-50,50,101)
gaussian = np.exp(-r**2/t_test) / np.sum(np.exp(-r**2/t_test))
bessel = np.abs(jv(r,2*t_test))**2 / np.sum(np.abs(jv(r,2*t_test))**2)
plt.figure(facecolor='white')
plt.plot(r, gaussian, label=r'Gaussian function')
plt.plot(r, bessel, label=r'Bessel function')
plt.xlabel('Position')
plt.ylabel('Probability density')
plt.legend()
plt.show()
num_qubits = 5 ## DO NOT EDIT
Trot_tb_qr = QuantumRegister(num_qubits)
Trot_tb_qc = QuantumCircuit(Trot_tb_qr, name='Trot')
###EDIT CODE BELOW
for j in [0,2]:
Trot_tb_qc.append(YY, [Trot_tb_qr[j], Trot_tb_qr[j+1]])
Trot_tb_qc.append(XX, [Trot_tb_qr[j], Trot_tb_qr[j+1]])
for i in [1,3]:
Trot_tb_qc.append(YY, [Trot_tb_qr[i], Trot_tb_qr[i+1]])
Trot_tb_qc.append(XX, [Trot_tb_qr[i], Trot_tb_qr[i+1]])
###DO NOT EDIT BELOW
Trot_tb_gate = Trot_tb_qc.to_instruction()
Trot_tb_qc.draw(output='mpl')
## Grade and submit your solution
from qc_grader.challenges.spring_2022 import grade_ex2a
grade_ex2a(Trot_tb_qc)
delta_t=0.15 # DO NOT EDIT
time_steps=np.arange(1,20,1) # DO NOT EDIT
circuits=[]
for n_steps in time_steps:
qr = QuantumRegister(num_qubits)
cr = ClassicalRegister(num_qubits)
qc = QuantumCircuit(qr,cr)
###EDIT CODE BELOW
qc.x([0])
###DO NOT EDIT BELOW
for _ in range(n_steps):
qc.append(Trot_tb_gate, [i for i in range(num_qubits)])
qc = qc.bind_parameters({t: delta_t})
circuits.append(qc)
from qiskit import transpile
# Use Aer's statevector simulator
from qiskit import Aer
# Run the quantum circuit on a statevector simulator backend
backend_sim = Aer.get_backend('statevector_simulator')
probability_density=[]
for circ in tqdm(circuits):
transpiled_circ=transpile(circ, backend_sim, optimization_level=3)
job_sim = backend_sim.run(transpiled_circ)
# Grab the results from the job.
result_sim = job_sim.result()
outputstate = result_sim.get_statevector(transpiled_circ, decimals=5)
ps=[]
###EDIT CODE BELOW (Extract the probability of finding the excitation on each qubit)
probs=[]
for i in range(num_qubits):
prob=outputstate.probabilities([i]) # type(..) >> list
probs.append(prob)
for elem in probs:
excited=elem[1]
ps.append(excited)
###DO NOT EDIT BELOW
probability_density.append(ps)
probability_density=np.array(probability_density)
plt.figure(figsize=(3,5), facecolor='white')
plt.pcolormesh(np.arange(0,num_qubits,1), time_steps*delta_t, probability_density)
plt.xlabel('Qubit index')
plt.ylabel('Time (1/J)')
## Grade and submit your solution
from qc_grader.challenges.spring_2022 import grade_ex2b
grade_ex2b(probability_density)
from qiskit.tools.monitor import job_monitor
from qiskit import IBMQ
# Loading your IBM Quantum account
IBMQ.load_account()
IBMQ.providers() # see a list of providers you have access to
# Get the special provider assigned to you using information from the output above
hub_name = 'qc-spring-22-4' # e.g. 'qc-spring-22-1'
group_name = 'group-2' # e.g. 'group-2'
project_name = 'recrrGhzxg3VULGQS' # e.g. 'recPdHH04wfWiNHjG'
provider = IBMQ.get_provider(hub=hub_name, group=group_name, project=project_name)
# Get `ibm_nairobi` backend from the provider
backend_name = 'ibm_nairobi'
backend = provider.get_backend(backend_name)
backend # See details of the `ibm_nairobi` quantum system
initial_layout=[0 , 1 , 3 , 5 , 4]
hardware_transpiled_circuits=[]
for circ in circuits:
hardware_circ=deepcopy(circ)
hardware_circ.barrier()
hardware_circ.measure(range(num_qubits), range(num_qubits))
hardware_transpiled_circuits.append(transpile(hardware_circ, backend, initial_layout=initial_layout, optimization_level=3))
shots=1024
job = execute(hardware_transpiled_circuits, backend=backend, shots=shots)
job_monitor(job)
print('Job ID', job.job_id())
qc = QuantumCircuit(5,1)
qc.x([0])
qc.measure(0,0) # Measuring only qubit 0 (q_0) and storing the measurement result in classical bit (a.k.a register) 0.
jobs = execute(qc,backend,shots=1024) # Sending job to ibm_nairobi.
counts = jobs.result().get_counts(qc)
probs = {key:value/shots for key, value in counts.items()}
print(qc)
print(counts)
print(probs)
experiment_results=backend.retrieve_job('629c26b701885c41f6f358c2').result()
i=0
for output in experiment_results.get_counts(): # Doing a for through each measurement (each new experiment).
print(f'output: {type(output)}\n')
print(output, '\n')
#print(output.keys()) # Type >> <class 'dict_keys'>
print(f"Number of Basis states/prob. amp.: {len(output)}.\n")
i+=1
if i == 2:
break
type(experiment_results.get_counts()), len(experiment_results.get_counts())
# There are 19 dictionaries. Each dict. corresponds to an average measurement trial.
for output in experiment_results.get_counts():
for key, value in output.items():
print(key, value)
print('')
print(output.keys())
break
Z = np.random.rand(2, 2)
Z
Z.shape, len(Z)
plt.pcolormesh(Z)
Z.tolist()
plt.pcolormesh(Z.tolist())
experiment_results=job.result()
#experiment_results=backend.retrieve_job('629c26b701885c41f6f358c2').result()
probability_density_exp=[]
for output in experiment_results.get_counts():
ps=[]
###EDIT CODE BELOW (Extract the probability of finding the excitation on each qubit)
for key in ['00001', '00010', '00100', '01000', '10000']:
try:
count=float(output.get(key))
prob=(count/shots)
except:
prob=0
ps.append(prob)
###DO NOT EDIT BELOW
probability_density_exp.append(ps)
plt.figure(figsize=(3,5), facecolor='white')
plt.pcolormesh(np.arange(0,num_qubits,1), time_steps*delta_t, probability_density_exp)
plt.xlabel('Qubit index')
plt.ylabel('Time (1/J)')
beta=(np.sqrt(5)-1)/2 # DO NOT EDIT
AA_patern=np.cos(2*np.pi*beta*np.arange(num_qubits)) # DO NOT EDIT
plt.plot(np.linspace(-0.5,4.5,101), np.cos(2*np.pi*beta*np.linspace(-0.5,4.5,101)), '--')
plt.plot(np.arange(num_qubits), AA_patern, 'o', label=r'$\epsilon_i$')
plt.xlabel('Position')
plt.ylabel('Energy')
plt.legend()
plt.title('Aubry-Andre potential')
plt.show()
Trot_qr_disorder = QuantumRegister(num_qubits)
Trot_qc_disorder = QuantumCircuit(Trot_qr_disorder, name='Trot disorder')
Trot_qc_disorder.append(Trot_tb_gate,[0,1,2,3,4])
deltas=[Parameter('delta_{:d}'.format(idx)) for idx in range(num_qubits)]
###EDIT CODE BELOW (add a parametric disorder to each qubit)
for i in range(0, num_qubits):
Trot_qc_disorder.rz(2*deltas[i]*t,i) # (angles, qubits).
###DO NOT EDIT BELOW
# Convert custom quantum circuit into a gate
Trot_disorder_gate = Trot_qc_disorder.to_instruction()
Trot_qc_disorder.draw(output='mpl')
delta_t=0.15
time_steps=np.arange(1,20,1)
W=2 # DO NOT EDIT
disorders=W*AA_patern # DO NOT EDIT
disorder_circuits=[]
for n_steps in time_steps:
qr = QuantumRegister(num_qubits)
cr = ClassicalRegister(num_qubits)
qc = QuantumCircuit(qr, cr)
qc.x(0)
for _ in range(n_steps):
qc.append(Trot_disorder_gate, [i for i in range(num_qubits)])
qc = qc.bind_parameters({t: delta_t})
qc = qc.bind_parameters({deltas[idx]: disorders[idx] for idx in range(num_qubits)})
disorder_circuits.append(qc)
from qiskit import transpile
# Use Aer's statevector simulator
from qiskit import Aer
# Run the quantum circuit on a statevector simulator backend
backend_sim = Aer.get_backend('statevector_simulator')
probability_density_localization=[]
for circ in tqdm(disorder_circuits):
transpiled_circ=transpile(circ, backend_sim, optimization_level=3)
job_sim = backend_sim.run(transpiled_circ)
# Grab the results from the job.
result_sim = job_sim.result()
outputstate = result_sim.get_statevector(transpiled_circ, decimals=5)
ps=[]
###EDIT CODE BELOW (Extract the probability of finding the excitation on each qubit)
probs=[]
for i in range(num_qubits):
prob=outputstate.probabilities([i]) # type(..) >> list
probs.append(prob)
for elem in probs:
excited=elem[1]
ps.append(excited)
###DO NOT EDIT BELOW
probability_density_localization.append(ps)
probability_density_localization=np.array(probability_density_localization)
plt.figure(figsize=(3,5), facecolor='white')
plt.pcolormesh(np.arange(0,num_qubits,1), time_steps*delta_t ,probability_density_localization)
plt.xlabel('Qubit index')
plt.ylabel('Time (1/J)')
## Grade and submit your solution
from qc_grader.challenges.spring_2022 import grade_ex2c
grade_ex2c(probability_density_localization)
from qiskit.tools.monitor import job_monitor
provider = IBMQ.load_account()
provider = IBMQ.get_provider(hub='qc-spring-22-4', group='group-2', project='recrrGhzxg3VULGQS')
backend = provider.get_backend('ibm_nairobi')
initial_layout=[0 , 1 , 3 , 5 , 4]
hardware_transpiled_circuits_disordered=[]
for circ in disorder_circuits:
hardware_circ=deepcopy(circ)
hardware_circ.barrier()
hardware_circ.measure(range(num_qubits), range(num_qubits))
hardware_transpiled_circuits_disordered.append(transpile(hardware_circ, backend, initial_layout=initial_layout, optimization_level=3))
shots=1024
job_disorder = execute(hardware_transpiled_circuits_disordered, backend=backend, shots=shots)
job_monitor(job_disorder)
print('Job ID', job_disorder.job_id())
disorder_experiment_results=job_disorder.result()
#disorder_experiment_results=backend.retrieve_job('6290b7ce4bb9753402efaa20').result()
disorder_probability_density_exp=[]
for output in disorder_experiment_results.get_counts():
ps=[]
###EDIT CODE BELOW (Extract the probability of finding the excitation on each qubit)
for key in ['00001', '00010', '00100', '01000', '10000']:
try:
count=float(output.get(key))
prob=(count/shots)
except:
prob=0
ps.append(prob)
###DO NOT EDIT BELOW
disorder_probability_density_exp.append(ps)
plt.figure(figsize=(3,5), facecolor='white')
plt.pcolormesh(np.arange(0,num_qubits,1), time_steps*delta_t, disorder_probability_density_exp)
plt.xlabel('Qubit index')
plt.ylabel('Time (1/J)')
|
https://github.com/MonitSharma/Qiskit-Summer-School-and-Quantum-Challenges
|
MonitSharma
|
import numpy as np
import matplotlib.pyplot as plt
# Importing standard Qiskit libraries
from qiskit import QuantumCircuit, QuantumRegister, transpile, Aer, IBMQ, execute
from qiskit.tools.jupyter import *
from qiskit.visualization import *
from qiskit.providers.aer import QasmSimulator
from tqdm.notebook import tqdm
from qiskit.providers.aer import QasmSimulator
from qiskit.tools.monitor import job_monitor
from qiskit.circuit import Parameter
import qiskit.quantum_info as qi
from qc_grader.challenges.spring_2022.helpers import generate_disordered_tb_instruction
# Suppress warnings
import warnings
warnings.filterwarnings('ignore')
import pylatexenc
import IPython
pop = [1,0]
Ne=0 # Sum of even populations.
No=0 # Sum of odd populations.
for j in range(0, len(pop), 2):
Ne += pop[j]
for j in range(1, len(pop), 2):
No += pop[j]
I = (Ne-No)/(Ne+No)
print(f"Ne={Ne}, No={No}, I={I}")
def get_imbalance(state):
###EDIT CODE BELOW
### HINT: MAKE SURE TO SKIP CALCULATING IMBALANCE OF THE |00...0> STATE
imbalance_val=0
def get_basis(i):
num_qubits = int(np.log2(len(state.probabilities())))
basis = []
for i in list(f'{i:0{num_qubits}b}'):
basis.append(int(i))
return basis # A list such as [1,0,0,0]
def imbalance(basis):
Ne=0 # Sum of even populations.
No=0 # Sum of odd populations.
for j in range(0, len(basis), 2):
Ne += basis[j]
for j in range(1, len(basis), 2):
No += basis[j]
return (Ne-No)/(Ne+No)
pop = state.probabilities() # List of probabilities of the state |\psi> for measuring all qubits.
for i in range(1, len(pop)): # Skipping i=0 corresponding to the |00...0> basis.
basis = get_basis(i)
prob_amp = pop[i] # float
imbalance_val += imbalance(basis)*prob_amp
###DO NOT EDIT BELOW
return imbalance_val
st1 = qi.Statevector.from_label('0111') # -1/3
st2 = np.sqrt(2/3)*qi.Statevector.from_label('0111') + np.sqrt(1/3)*qi.Statevector.from_label('1011') # -1/9
st3 = (qi.Statevector.from_label('1000')+qi.Statevector.from_label('1001'))*(1/np.sqrt(2)) # 0.5
for i in [st1, st2, st3]:
print(get_imbalance(i))
## Grade and submit your solution
from qc_grader.challenges.spring_2022 import grade_ex3a
grade_ex3a(get_imbalance)
bell_state = qi.Statevector(np.array([0,1,1,0])/np.sqrt(2))
rho_0 = qi.partial_trace(bell_state,[1]) # We trace out qubit 1
rho_1 = qi.partial_trace(bell_state,[0]) # We trace out qubit 0
print('QB0 vn entropy: ', qi.entropy(rho_0, base=np.exp(1)))
print('QB1 vn entropy: ', qi.entropy(rho_1, base=np.exp(1)))
t = Parameter('t')
num_qubits=12
deltas=[Parameter('delta_{:d}'.format(idx)) for idx in range(num_qubits)]
disorder_trot_step=generate_disordered_tb_instruction(t, deltas, num_qubits)
# Here we define the disorder pattern
beta=(np.sqrt(5)-1)/2 # DO NOT EDIT
AA_pattern=np.cos(2*np.pi*beta*np.arange(num_qubits)) # DO NOT EDIT
delta_t=0.1
time_steps=np.arange(0,21,2)
circuits={}
Ws=[1,4,10]
for W in Ws:
disorders=W*AA_pattern
circuits[W]=[]
for n_steps in time_steps:
qr = QuantumRegister(num_qubits)
qc = QuantumCircuit(qr)
###EDIT CODE BELOW
qc.x([0,4,8])
###DO NOT EDIT BELOW
for _ in range(n_steps):
qc.append(disorder_trot_step, [i for i in range(num_qubits)])
if n_steps!=0:
qc = qc.bind_parameters({t: delta_t})
qc = qc.bind_parameters({deltas[idx]: disorders[idx] for idx in range(num_qubits)})
circuits[W].append(qc)
from qiskit import transpile
# Use Aer's statevector simulator
from qiskit import Aer
# Run the quantum circuit on a statevector simulator backend
backend_sim = Aer.get_backend('statevector_simulator')
probability_densities={}
state_vector_imbalances={}
vn_entropies={}
for W in tqdm(Ws):
probability_densities[W]=[]
state_vector_imbalances[W]=[]
vn_entropies[W]=[]
for circ in circuits[W]:
transpiled_circ=transpile(circ, backend_sim, optimization_level=3)
job_sim = backend_sim.run(transpiled_circ)
# Grab the results from the job.
result_sim = job_sim.result()
outputstate = result_sim.get_statevector(transpiled_circ, decimals=6)
ps=[]
for idx in range(num_qubits):
ps.append(np.abs(qi.partial_trace(outputstate,[i for i in range(num_qubits) if i!=idx]))[1,1]**2)
entropy=0
### EDIT CODE BELOW (extract the density matrix of qubit 0 by tracing out all other qubits)
rho0=qi.partial_trace(outputstate, [i for i in range(num_qubits) if i!=0]) # trace out qubit 0.
entropy=qi.entropy(rho0, base=np.exp(1))
###DO NOT EDIT BELOW
imbalance=get_imbalance(outputstate)
### EDIT CODE BELOW
###DO NOT EDIT BELOW
vn_entropies[W].append(entropy)
probability_densities[W].append(ps)
state_vector_imbalances[W].append(imbalance)
fig, axs = plt.subplots(1,3,figsize=(15,5), facecolor='white', sharey=True)
for i,W in enumerate(Ws):
ax=axs[i]
ax.pcolormesh(np.arange(0,num_qubits,1), time_steps*delta_t ,probability_densities[W])
ax.set_xlabel('Qubit index')
ax.set_xticks(np.arange(1,num_qubits+1,1))
axs[0].set_ylabel('Time (1/J)')
plt.show()
for W in Ws:
plt.plot(time_steps*delta_t,vn_entropies[W], '--o', label='W={:d}'.format(W))
plt.xlabel(r'Time (1/J)')
plt.ylabel(r'$\mathcal{S}_{\rm vn}(\rho_0)$')
plt.legend()
plt.show()
## Grade and submit your solution
from qc_grader.challenges.spring_2022 import grade_ex3b
grade_ex3b(vn_entropies)
for W in Ws:
plt.plot(time_steps*delta_t,state_vector_imbalances[W], '--o', label='W={:d}'.format(W))
plt.xlabel(r'Time (1/J)')
plt.ylabel(r'$\mathcal{I}$')
plt.legend()
plt.show()
## Grade and submit your solution
from qc_grader.challenges.spring_2022 import grade_ex3c
grade_ex3c(state_vector_imbalances)
|
https://github.com/MonitSharma/Qiskit-Summer-School-and-Quantum-Challenges
|
MonitSharma
|
from qiskit_nature.drivers import Molecule
from qiskit_nature.drivers.second_quantization import ElectronicStructureMoleculeDriver, ElectronicStructureDriverType
molecule = Molecule(
# coordinates are given in Angstrom
geometry=[
["O", [0.0, 0.0, 0.0]],
["H", [0.758602, 0.0, 0.504284]],
["H", [0.758602, 0.0, -0.504284]]
],
multiplicity=1, # = 2*spin + 1
charge=0,
)
driver = ElectronicStructureMoleculeDriver(
molecule=molecule,
basis="sto3g",
driver_type=ElectronicStructureDriverType.PYSCF,
)
properties = driver.run()
print(properties)
print(properties.get_property("ParticleNumber"))
#print(properties.get_property("ElectronicEnergy"))
properties.get_property("ElectronicEnergy").nuclear_repulsion_energy
# WRITE YOUR CODE BETWEEN THESE LINES - START
num_alpha_electrons = 5
num_beta_electrons = 5
num_spin_orbitals = 14
nuclear_rep_energy = properties.get_property("ElectronicEnergy").nuclear_repulsion_energy
# WRITE YOUR CODE BETWEEN THESE LINES - END
from qc_grader.challenges.spring_2022 import grade_ex4a
grade_ex4a(
num_alpha_electrons=num_alpha_electrons,
num_beta_electrons=num_beta_electrons,
num_spin_orbitals=num_spin_orbitals,
nuclear_rep_energy=nuclear_rep_energy
)
from qiskit_nature.transformers.second_quantization.electronic import ActiveSpaceTransformer
# Check the occupation of the spin orbitals
PN_property = properties.get_property("ParticleNumber")
print(PN_property)
# Define the active space around the Fermi level
# (selected automatically around the HOMO and LUMO, ordered by energy)
transformer = ActiveSpaceTransformer(
num_electrons=2, #how many electrons we have in our active space
num_molecular_orbitals=2, #how many orbitals we have in our active space
)
# We can hand-pick the MOs to be included in the AS
# (in case they are not exactly around the Fermi level)
# transformer = ActiveSpaceTransformer(
# num_electrons=2, #how many electrons we have in our active space
# num_molecular_orbitals=2, #how many orbitals we have in our active space
# active_orbitals=[4,7], #We are specifically choosing MO number 4 (occupied with two electrons) and 7 (empty)
# )
from qiskit_nature.problems.second_quantization.electronic import ElectronicStructureProblem
problem = ElectronicStructureProblem(driver, [transformer])
second_q_ops = problem.second_q_ops() # this calls driver.run() internally
hamiltonian = second_q_ops[0]
print(hamiltonian)
from qiskit_nature.operators.second_quantization import FermionicOp
# WRITE YOUR CODE BETWEEN THESE LINES - START
op = (0.5j* FermionicOp('-_0 +_1')) + (2.0* FermionicOp('-_0 +_2'))
# list of valid tuples to initialize the FermionicOp
list_operator = op.to_list('sparse')
# positive integer that represents the length of registers
num_register_length = 3
list_operator
# WRITE YOUR CODE BETWEEN THESE LINES - END
(FermionicOp('+_1 -_0')).to_list() == (FermionicOp('+_1')@FermionicOp('-_0')).to_list()
(0.5j* FermionicOp("+_1 -_0", 4, "dense")).to_list() == (0.5j* FermionicOp("+_1", 4, "dense")@FermionicOp("-_0", 4, "dense")).to_list()
from qc_grader.challenges.spring_2022 import grade_ex4b
grade_ex4b(list_operator, num_register_length)
from qiskit_nature.mappers.second_quantization import ParityMapper, BravyiKitaevMapper, JordanWignerMapper
from qiskit_nature.converters.second_quantization import QubitConverter
# Setup the mapper and qubit converter
mapper_type = 'JordanWignerMapper'
if mapper_type == 'ParityMapper':
mapper = ParityMapper()
elif mapper_type == 'JordanWignerMapper':
mapper = JordanWignerMapper()
elif mapper_type == 'BravyiKitaevMapper':
mapper = BravyiKitaevMapper()
converter = QubitConverter(mapper)
qubit_op = converter.convert(hamiltonian)
print(qubit_op)
from qiskit_nature.circuit.library import HartreeFock
particle_number = problem.grouped_property_transformed.get_property("ParticleNumber")
num_spin_orbitals = particle_number.num_spin_orbitals
num_particles = particle_number.num_particles
init_state = HartreeFock(num_spin_orbitals, num_particles, converter)
print(init_state)
from qiskit.circuit.library import TwoLocal
from qiskit_nature.circuit.library import UCCSD, PUCCD, SUCCD
# Choose the ansatz
ansatz_type = "UCCSD"
# Put arguments for twolocal
if ansatz_type == "TwoLocal":
# Single qubit rotations that are placed on all qubits with independent parameters
rotation_blocks = ['ry', 'rz']
# Entangling gates
entanglement_blocks = 'cz'
# How the qubits are entangled
entanglement = 'full'
# Repetitions of rotation_blocks + entanglement_blocks with independent parameters
repetitions = 1
# Skip the final rotation_blocks layer
skip_final_rotation_layer = True
ansatz = TwoLocal(qubit_op.num_qubits, rotation_blocks, entanglement_blocks, reps=repetitions,
entanglement=entanglement, skip_final_rotation_layer=skip_final_rotation_layer)
# Add the initial state
ansatz.compose(init_state, front=True, inplace=True)
elif ansatz_type == "UCCSD":
ansatz = UCCSD(converter,num_particles,num_spin_orbitals,initial_state = init_state)
elif ansatz_type == "PUCCD":
ansatz = PUCCD(converter,num_particles,num_spin_orbitals,initial_state = init_state)
elif ansatz_type == "SUCCD":
ansatz = SUCCD(converter,num_particles,num_spin_orbitals,initial_state = init_state)
elif ansatz_type == "Custom":
# Example of how to write your own circuit
from qiskit.circuit import Parameter, QuantumCircuit, QuantumRegister
# Define the variational parameter
theta = Parameter('a')
n = qubit_op.num_qubits
# Make an empty quantum circuit
qc = QuantumCircuit(qubit_op.num_qubits)
qubit_label = 0
# Place a Hadamard gate
qc.h(qubit_label)
# Place a CNOT ladder
for i in range(n-1):
qc.cx(i, i+1)
# Visual separator
qc.barrier()
# rz rotations on all qubits
qc.rz(theta, range(n))
ansatz = qc
ansatz.compose(init_state, front=True, inplace=True)
print(ansatz.decompose())
from qiskit import Aer
backend = Aer.get_backend('statevector_simulator')
from qiskit.algorithms.optimizers import COBYLA, L_BFGS_B, SPSA, SLSQP
optimizer_type = 'L_BFGS_B'
# You may want to tune the parameters
# of each optimizer, here the defaults are used
if optimizer_type == 'COBYLA':
optimizer = COBYLA(maxiter=500)
elif optimizer_type == 'L_BFGS_B':
optimizer = L_BFGS_B(maxfun=500)
elif optimizer_type == 'SPSA':
optimizer = SPSA(maxiter=500)
elif optimizer_type == 'SLSQP':
optimizer = SLSQP(maxiter=500)
from qiskit_nature.algorithms.ground_state_solvers.minimum_eigensolver_factories import NumPyMinimumEigensolverFactory
from qiskit_nature.algorithms.ground_state_solvers import GroundStateEigensolver
import numpy as np
def exact_diagonalizer(problem, converter):
solver = NumPyMinimumEigensolverFactory()
calc = GroundStateEigensolver(converter, solver)
result = calc.solve(problem)
return result
result_exact = exact_diagonalizer(problem, converter)
exact_energy = np.real(result_exact.eigenenergies[0])
print("Exact electronic energy", exact_energy)
print(result_exact)
# The targeted electronic energy for H2 is -1.85336 Ha
# Check with your VQE result.
from qiskit.algorithms import VQE
from IPython.display import display, clear_output
# Print and save the data in lists
def callback(eval_count, parameters, mean, std):
# Overwrites the same line when printing
display("Evaluation: {}, Energy: {}, Std: {}".format(eval_count, mean, std))
clear_output(wait=True)
counts.append(eval_count)
values.append(mean)
params.append(parameters)
deviation.append(std)
counts = []
values = []
params = []
deviation = []
# Set initial parameters of the ansatz
# We choose a fixed small displacement
# So all participants start from similar starting point
try:
initial_point = [0.01] * len(ansatz.ordered_parameters)
except:
initial_point = [0.01] * ansatz.num_parameters
algorithm = VQE(ansatz,
optimizer=optimizer,
quantum_instance=backend,
callback=callback,
initial_point=initial_point)
result = algorithm.compute_minimum_eigenvalue(qubit_op)
print(result)
# Store results in a dictionary
from qiskit.transpiler import PassManager
from qiskit.transpiler.passes import Unroller
# Unroller transpile your circuit into CNOTs and U gates
pass_ = Unroller(['u', 'cx'])
pm = PassManager(pass_)
ansatz_tp = pm.run(ansatz)
cnots = ansatz_tp.count_ops()['cx']
energy = result.optimal_value
if ansatz_type == "TwoLocal":
result_dict = {
'optimizer': optimizer.__class__.__name__,
'mapping': converter.mapper.__class__.__name__,
'ansatz': ansatz.__class__.__name__,
'rotation blocks': rotation_blocks,
'entanglement_blocks': entanglement_blocks,
'entanglement': entanglement,
'repetitions': repetitions,
'skip_final_rotation_layer': skip_final_rotation_layer,
'energy (Ha)': energy,
'error (mHa)': (energy-exact_energy)*1000,
'# of parameters': len(result.optimal_point),
'final parameters': result.optimal_point,
'# of evaluations': result.cost_function_evals,
'# of qubits': int(qubit_op.num_qubits),
'# of CNOTs': cnots}
else:
result_dict = {
'optimizer': optimizer.__class__.__name__,
'mapping': converter.mapper.__class__.__name__,
'ansatz': ansatz.__class__.__name__,
'rotation blocks': None,
'entanglement_blocks': None,
'entanglement': None,
'repetitions': None,
'skip_final_rotation_layer': None,
'energy (Ha)': energy,
'error (mHa)': (energy-exact_energy)*1000,
'# of parameters': len(result.optimal_point),
'final parameters': result.optimal_point,
'# of evaluations': result.cost_function_evals,
'# of qubits': int(qubit_op.num_qubits),
'# of CNOTs': cnots}
# Plot the results
import matplotlib.pyplot as plt
fig, ax = plt.subplots(1, 1)
ax.set_xlabel('Iterations')
ax.set_ylabel('Energy')
ax.grid()
fig.text(0.7, 0.75, f'Energy: {result.optimal_value:.3f}')
plt.title(f"{result_dict['optimizer']}-{result_dict['mapping']}\n{result_dict['ansatz']}")
ax.plot(counts, values)
ax.axhline(exact_energy, linestyle='--')
fig_title = f"\
{result_dict['optimizer']}-\
{result_dict['mapping']}-\
{result_dict['ansatz']}-\
Energy({result_dict['energy (Ha)']:.3f}).png"
fig.savefig(fig_title, dpi=300)
# Display and save the data
import pandas as pd
import os.path
filename = 'results_h2o.csv'
if os.path.isfile(filename):
result_df = pd.read_csv(filename)
result_df = result_df.append([result_dict])
else:
result_df = pd.DataFrame.from_dict([result_dict])
result_df.to_csv(filename)
result_df[['optimizer','ansatz', 'rotation blocks', 'entanglement_blocks',
'entanglement', 'repetitions', '# of qubits', '# of parameters', '# of CNOTs', '# of evaluations', 'error (mHa)']]
from qiskit import Aer
from qiskit.utils import QuantumInstance
from qiskit_nature.algorithms import GroundStateEigensolver, QEOM, VQEUCCFactory
# This first part sets the ground state solver
# see more about this part in the ground state calculation tutorial
quantum_instance = QuantumInstance(Aer.get_backend("aer_simulator_statevector"))
solver = VQEUCCFactory(quantum_instance)
gsc = GroundStateEigensolver(converter, solver)
# The qEOM algorithm is simply instantiated with the chosen ground state solver
qeom_excited_states_calculation = QEOM(gsc, "sd")
qeom_results = qeom_excited_states_calculation.solve(problem)
print(qeom_results)
# WRITE YOUR CODE BETWEEN THESE LINES - START
# WRITE YOUR CODE BETWEEN THESE LINES - END
|
https://github.com/MonitSharma/Qiskit-Summer-School-and-Quantum-Challenges
|
MonitSharma
|
import numpy as np
import sympy as sym
from sympy import exp # Symbolic exponentiation.
from scipy.linalg import expm # Numerical exponentiation.
from sympy.physics.quantum import TensorProduct, OuterProduct
from qiskit import Aer, QuantumRegister, QuantumCircuit, assemble, execute
from qiskit.quantum_info import Statevector
from qiskit.circuit import Parameter
from qiskit.opflow import I, X, Y, Z
import pylatexenc # Required to use 'MatplotlibDrawer'.
'''1-qubit gates SU(2):'''
sigma0 = np.identity(2) # Matrix of the identity gate.
sigma1 = np.array([[0,1],[1,0]], dtype=(np.float32)) # Matrix of the Pauli-X gate that performs a Pi radian rotation around the x-axis.
sigma2 = np.array([[0,-1j],[1j,0]], dtype=(np.complex64)) # Matrix of the Pauli-Y gate = iXZ.
sigma3 = np.array([[1,0],[0,-1]], dtype=(np.float32)) # Matrix of the Pauli-Z gate = P(pi).
had = (1/np.sqrt(2))*np.array([[1,1],[1,-1]]) # Matrix of the Hadamard gate that performs a Pi radian rotation around an axis between the x and z axes.
phase = np.array([[1,0],[0,1j]]) # Matrix of the Phase gate S = P(pi/2) = square-root of Pauli-Z.
'''2-qubit gates SU(4):'''
XX = np.kron(sigma1,sigma1) # Matrix of the XX gate.
YY = np.kron(sigma2,sigma2) # Matrix of the YY gate.
'''Array dimensions:'''
sigma0.shape, sigma1.shape, sigma2.shape, sigma3.shape, had.shape, phase.shape, XX.shape, YY.shape
# Circuit for the ZZ(t) gate:
'''
from qiskit import QuantumCircuit
from qiskit.circuit import Parameter
'''
t = Parameter('t')
qc = QuantumCircuit(2, name='ZZ')
qc.cnot(0,1) # CX^{01}.
qc.rz(2 * t, 1) # R_z(2t).
qc.cnot(0,1) # CX^{01}.
qc.draw(output='mpl') # '!pip install pylatexenc' library is required to use 'MatplotlibDrawer'.
# Circuit for the XX(t) gate:
'''
from qiskit import QuantumCircuit
from qiskit.circuit import Parameter
'''
t = Parameter('t')
qc = QuantumCircuit(2, name='XX')
qc.h([0,1])
qc.cx(0, 1)
qc.rz(2 * t, 1)
qc.cx(0, 1)
qc.h([0,1])
qc.draw(output='mpl')
# Equivalent circuit for the XX(t) gate:
qc = QuantumCircuit(2, name='XX')
qc.ry(np.pi/2,[0,1])
qc.cnot(0,1)
qc.rz(2 * t, 1)
qc.cnot(0,1)
qc.ry(-np.pi/2,[0,1])
qc.draw(output='mpl')
# Circuit for the YY(t) gate:
'''
from qiskit import QuantumCircuit
from qiskit.circuit import Parameter
'''
t = Parameter('t')
qr = QuantumRegister(2)
qc = QuantumCircuit(qr, name='YY')
qc.sdg([0,1])
qc.h([0,1])
qc.cx(0, 1)
qc.rz(2 * t, 1)
qc.cx(0, 1)
qc.h([0,1])
qc.s([0,1])
qc.draw(output='mpl')
# Equivalent circuit for the YY(t) gate:
qr = QuantumRegister(2)
qc = QuantumCircuit(qr, name='YY')
qc.rx(np.pi/2,[0,1])
qc.cnot(0,1)
qc.rz(2 * t, 1)
qc.cnot(0,1)
qc.rx(-np.pi/2,[0,1])
qc.draw(output='mpl')
t = Parameter('t')
qr = QuantumRegister(2)
ZZ_qc = QuantumCircuit(qr, name='ZZ')
ZZ_qc.cnot(0,1)
ZZ_qc.rz(2 * t, 1)
ZZ_qc.cnot(0,1)
ZZg = ZZ_qc.to_instruction()
XX_qc = QuantumCircuit(qr, name='XX')
XX_qc.h([0,1])
XX_qc.append(ZZg, [0,1])
XX_qc.h([0,1])
XXg = XX_qc.to_instruction()
YY_qc = QuantumCircuit(qr, name='YY')
YY_qc.sdg([0,1])
YY_qc.h([0,1])
YY_qc.append(ZZg, [0,1])
YY_qc.h([0,1])
YY_qc.s([0,1])
YYg = YY_qc.to_instruction()
num_qubits = 3
Trot_qr = QuantumRegister(num_qubits)
Trot_qc = QuantumCircuit(Trot_qr, name='Trot')
for i in range(0, num_qubits - 1):
Trot_qc.append(YYg, [Trot_qr[i], Trot_qr[i+1]])
Trot_qc.append(XXg, [Trot_qr[i], Trot_qr[i+1]])
Trot_gate = Trot_qc.to_instruction()
Trot_qc.draw(output='mpl')
XXI = np.kron(XX, sigma0)
YYI = np.kron(YY, sigma0)
(expm(-1j*(XXI+YYI)).round(6) == (expm(-1j*XXI)@expm(-1j*YYI)).round(6)).all()
((expm(-1j*XXI)@expm(-1j*YYI)).round(6) == (expm(-1j*YYI)@expm(-1j*XXI)).round(6)).all()
'''Return should be >>> False.'''
YYI = np.kron(YY, sigma0)
IXX = np.kron(sigma0, XX)
(expm(-1j*(YYI+IXX)).round(6) == (expm(-1j*YYI)@expm(-1j*IXX)).round(6)).all()
from qiskit.opflow import I, X, Y, Z
H1 = (X^X^I)+(Y^Y^I)
(H1.exp_i().to_matrix().round(7) == ((X^X^I).exp_i()@(Y^Y^I).exp_i()).to_matrix().round(7)).all()
'''Return should be >>> False.'''
H2 = (Y^Y^I)+(I^X^X)
(H2.exp_i().to_matrix().round(3) == ((Y^Y^I).exp_i()@(I^X^X).exp_i()).to_matrix().round(3)).all()
|
https://github.com/MonitSharma/Qiskit-Summer-School-and-Quantum-Challenges
|
MonitSharma
|
from qiskit import *
from qiskit.visualization import plot_histogram
import numpy as np
def NOT(inp):
"""An NOT gate.
Parameters:
inp (str): Input, encoded in qubit 0.
Returns:
QuantumCircuit: Output NOT circuit.
str: Output value measured from qubit 0.
"""
qc = QuantumCircuit(1, 1) # A quantum circuit with a single qubit and a single classical bit
qc.reset(0)
# We encode '0' as the qubit state |0⟩, and '1' as |1⟩
# Since the qubit is initially |0⟩, we don't need to do anything for an input of '0'
# For an input of '1', we do an x to rotate the |0⟩ to |1⟩
if inp=='1':
qc.x(0)
# barrier between input state and gate operation
qc.barrier()
# Now we've encoded the input, we can do a NOT on it using x
qc.x(0)
#barrier between gate operation and measurement
qc.barrier()
# Finally, we extract the |0⟩/|1⟩ output of the qubit and encode it in the bit c[0]
qc.measure(0,0)
qc.draw()
# We'll run the program on a simulator
backend = Aer.get_backend('qasm_simulator')
# Since the output will be deterministic, we can use just a single shot to get it
job = backend.run(qc, shots=1, memory=True)
output = job.result().get_memory()[0]
return qc, output
## Test the function
for inp in ['0', '1']:
qc, out = NOT(inp)
print('NOT with input',inp,'gives output',out)
display(qc.draw())
print('\n')
def XOR(inp1,inp2):
"""An XOR gate.
Parameters:
inpt1 (str): Input 1, encoded in qubit 0.
inpt2 (str): Input 2, encoded in qubit 1.
Returns:
QuantumCircuit: Output XOR circuit.
str: Output value measured from qubit 1.
"""
qc = QuantumCircuit(2, 1)
qc.reset(range(2))
if inp1=='1':
qc.x(0)
if inp2=='1':
qc.x(1)
# barrier between input state and gate operation
qc.barrier()
# this is where your program for quantum XOR gate goes
qc.cx(0, 1)
# barrier between input state and gate operation
qc.barrier()
qc.measure(1,0) # output from qubit 1 is measured
#We'll run the program on a simulator
backend = Aer.get_backend('qasm_simulator')
#Since the output will be deterministic, we can use just a single shot to get it
job = backend.run(qc, shots=1, memory=True)
output = job.result().get_memory()[0]
return qc, output
## Test the function
for inp1 in ['0', '1']:
for inp2 in ['0', '1']:
qc, output = XOR(inp1, inp2)
print('XOR with inputs',inp1,inp2,'gives output',output)
display(qc.draw())
print('\n')
def AND(inp1,inp2):
"""An AND gate.
Parameters:
inpt1 (str): Input 1, encoded in qubit 0.
inpt2 (str): Input 2, encoded in qubit 1.
Returns:
QuantumCircuit: Output XOR circuit.
str: Output value measured from qubit 2.
"""
qc = QuantumCircuit(3, 1)
qc.reset(range(2))
if inp1=='1':
qc.x(0)
if inp2=='1':
qc.x(1)
qc.barrier()
# this is where your program for quantum AND gate goes
qc.ccx(0,1,2)
qc.barrier()
qc.measure(2, 0) # output from qubit 2 is measured
# We'll run the program on a simulator
backend = Aer.get_backend('qasm_simulator')
# Since the output will be deterministic, we can use just a single shot to get it
job = backend.run(qc, shots=1, memory=True)
output = job.result().get_memory()[0]
return qc, output
## Test the function
for inp1 in ['0', '1']:
for inp2 in ['0', '1']:
qc, output = AND(inp1, inp2)
print('AND with inputs',inp1,inp2,'gives output',output)
display(qc.draw())
print('\n')
def NAND(inp1,inp2):
"""An NAND gate.
Parameters:
inpt1 (str): Input 1, encoded in qubit 0.
inpt2 (str): Input 2, encoded in qubit 1.
Returns:
QuantumCircuit: Output NAND circuit.
str: Output value measured from qubit 2.
"""
qc = QuantumCircuit(3, 1)
qc.reset(range(3))
if inp1=='1':
qc.x(0)
if inp2=='1':
qc.x(1)
qc.barrier()
# this is where your program for quantum NAND gate goes
qc.ccx(0,1,2)
if inp=='1':
qc.x(2)
qc.barrier()
qc.measure(2, 0) # output from qubit 2 is measured
# We'll run the program on a simulator
backend = Aer.get_backend('aer_simulator')
# Since the output will be deterministic, we can use just a single shot to get it
job = backend.run(qc,shots=1,memory=True)
output = job.result().get_memory()[0]
return qc, output
## Test the function
for inp1 in ['0', '1']:
for inp2 in ['0', '1']:
qc, output = NAND(inp1, inp2)
print('NAND with inputs',inp1,inp2,'gives output',output)
display(qc.draw())
print('\n')
def OR(inp1,inp2):
"""An OR gate.
Parameters:
inpt1 (str): Input 1, encoded in qubit 0.
inpt2 (str): Input 2, encoded in qubit 1.
Returns:
QuantumCircuit: Output XOR circuit.
str: Output value measured from qubit 2.
"""
qc = QuantumCircuit(3, 1)
qc.reset(range(3))
if inp1=='1':
qc.x(0)
if inp2=='1':
qc.x(1)
qc.barrier()
# this is where your program for quantum OR gate goes
qc.cx(0, 2)
qc.cx(1, 2)
qc.barrier()
qc.measure(2, 0) # output from qubit 2 is measured
# We'll run the program on a simulator
backend = Aer.get_backend('aer_simulator')
# Since the output will be deterministic, we can use just a single shot to get it
job = backend.run(qc,shots=1,memory=True)
output = job.result().get_memory()[0]
return qc, output
## Test the function
for inp1 in ['0', '1']:
for inp2 in ['0', '1']:
qc, output = OR(inp1, inp2)
print('OR with inputs',inp1,inp2,'gives output',output)
display(qc.draw())
print('\n')
from qiskit import IBMQ
#IBMQ.save_account("a68a35747d4eccd1d58f275e637909987c789ce5c0edd8a4f43014672bf0301b54b28b1b5f44ba8ff87500777429e1e4ceb79621a6ba248d6cca6bca0e233d23", overwrite=True)
IBMQ.load_account()
IBMQ.providers()
provider = IBMQ.get_provider('ibm-q')
provider.backends()
import qiskit.tools.jupyter
# run this cell
backend = provider.get_backend('ibmq_quito')
qc_and = QuantumCircuit(3)
qc_and.ccx(0,1,2)
print('AND gate')
display(qc_and.draw())
print('\n\nTranspiled AND gate with all the required connectivity')
qc_and.decompose().draw()
from qiskit.tools.monitor import job_monitor
# run the cell to define AND gate for real quantum system
def AND(inp1, inp2, backend, layout):
qc = QuantumCircuit(3, 1)
qc.reset(range(3))
if inp1=='1':
qc.x(0)
if inp2=='1':
qc.x(1)
qc.barrier()
qc.ccx(0, 1, 2)
qc.barrier()
qc.measure(2, 0)
qc_trans = transpile(qc, backend, initial_layout=layout, optimization_level=3)
job = backend.run(qc_trans, shots=8192)
print(job.job_id())
job_monitor(job)
output = job.result().get_counts()
return qc_trans, output
backend
layout = [0, 1, 2]
output_all = []
qc_trans_all = []
prob_all = []
worst = 1
best = 0
for input1 in ['0','1']:
for input2 in ['0','1']:
qc_trans, output = AND(input1, input2, backend, layout)
output_all.append(output)
qc_trans_all.append(qc_trans)
prob = output[str(int( input1=='1' and input2=='1' ))]/8192
prob_all.append(prob)
print('\nProbability of correct answer for inputs',input1,input2)
print('{:.2f}'.format(prob) )
print('---------------------------------')
worst = min(worst,prob)
best = max(best, prob)
print('')
print('\nThe highest of these probabilities was {:.2f}'.format(best))
print('The lowest of these probabilities was {:.2f}'.format(worst))
print('Transpiled AND gate circuit for ibmq_vigo with input 0 0')
print('\nThe circuit depth : {}'.format (qc_trans_all[0].depth()))
print('# of nonlocal gates : {}'.format (qc_trans_all[0].num_nonlocal_gates()))
print('Probability of correct answer : {:.2f}'.format(prob_all[0]) )
qc_trans_all[0].draw()
print('Transpiled AND gate circuit for ibmq_vigo with input 0 1')
print('\nThe circuit depth : {}'.format (qc_trans_all[1].depth()))
print('# of nonlocal gates : {}'.format (qc_trans_all[1].num_nonlocal_gates()))
print('Probability of correct answer : {:.2f}'.format(prob_all[1]) )
qc_trans_all[1].draw()
print('Transpiled AND gate circuit for ibmq_vigo with input 1 0')
print('\nThe circuit depth : {}'.format (qc_trans_all[2].depth()))
print('# of nonlocal gates : {}'.format (qc_trans_all[2].num_nonlocal_gates()))
print('Probability of correct answer : {:.2f}'.format(prob_all[2]) )
qc_trans_all[2].draw()
print('Transpiled AND gate circuit for ibmq_vigo with input 1 1')
print('\nThe circuit depth : {}'.format (qc_trans_all[3].depth()))
print('# of nonlocal gates : {}'.format (qc_trans_all[3].num_nonlocal_gates()))
print('Probability of correct answer : {:.2f}'.format(prob_all[3]) )
qc_trans_all[3].draw()
|
https://github.com/MonitSharma/Qiskit-Summer-School-and-Quantum-Challenges
|
MonitSharma
|
import numpy as np
# Importing standard Qiskit libraries
from qiskit import QuantumCircuit, transpile, Aer, execute
from qiskit.tools.jupyter import *
from qiskit.visualization import *
from qiskit.providers.aer import QasmSimulator
backend = Aer.get_backend('statevector_simulator')
qc1 = QuantumCircuit(4)
# perform gate operations on individual qubits
qc1.x(0)
qc1.y(1)
qc1.z(2)
qc1.s(3)
# Draw circuit
qc1.draw()
# Plot blochshere
out1 = execute(qc1,backend).result().get_statevector()
plot_bloch_multivector(out1)
qc2 = QuantumCircuit(4)
# initialize qubits
qc2.x(range(4))
# perform gate operations on individual qubits
qc2.x(0)
qc2.y(1)
qc2.z(2)
qc2.s(3)
# Draw circuit
qc2.draw()
# Plot blochshere
out2 = execute(qc2,backend).result().get_statevector()
plot_bloch_multivector(out2)
qc3 = QuantumCircuit(4)
# initialize qubits
qc3.h(range(4))
# perform gate operations on individual qubits
qc3.x(0)
qc3.y(1)
qc3.z(2)
qc3.s(3)
# Draw circuit
qc3.draw()
# Plot blochshere
out3 = execute(qc3,backend).result().get_statevector()
plot_bloch_multivector(out3)
qc4 = QuantumCircuit(4)
# initialize qubits
qc4.x(range(4))
qc4.h(range(4))
# perform gate operations on individual qubits
qc4.x(0)
qc4.y(1)
qc4.z(2)
qc4.s(3)
# Draw circuit
qc4.draw()
# Plot blochshere
out4 = execute(qc4,backend).result().get_statevector()
plot_bloch_multivector(out4)
qc5 = QuantumCircuit(4)
# initialize qubits
qc5.h(range(4))
qc5.s(range(4))
# perform gate operations on individual qubits
qc5.x(0)
qc5.y(1)
qc5.z(2)
qc5.s(3)
# Draw circuit
qc5.draw()
# Plot blochshere
out5 = execute(qc5,backend).result().get_statevector()
plot_bloch_multivector(out5)
qc6 = QuantumCircuit(4)
# initialize qubits
qc6.x(range(4))
qc6.h(range(4))
qc6.s(range(4))
# perform gate operations on individual qubits
qc6.x(0)
qc6.y(1)
qc6.z(2)
qc6.s(3)
# Draw circuit
qc6.draw()
# Plot blochshere
out6 = execute(qc6,backend).result().get_statevector()
plot_bloch_multivector(out6)
import qiskit
qiskit.__qiskit_version__
|
https://github.com/MonitSharma/Qiskit-Summer-School-and-Quantum-Challenges
|
MonitSharma
|
from qiskit import *
import numpy as np
from numpy import linalg as la
from qiskit.tools.monitor import job_monitor
import qiskit.tools.jupyter
qc = QuantumCircuit(1)
#### your code goes here
# z measurement of qubit 0
measure_z = QuantumCircuit(1,1)
measure_z.measure(0,0)
# x measurement of qubit 0
measure_x = QuantumCircuit(1,1)
# your code goes here
# y measurement of qubit 0
measure_y = QuantumCircuit(1,1)
# your code goes here
shots = 2**14 # number of samples used for statistics
sim = Aer.get_backend('qasm_simulator')
bloch_vector_measure = []
for measure_circuit in [measure_x, measure_y, measure_z]:
# run the circuit with a the selected measurement and get the number of samples that output each bit value
counts = execute(qc+measure_circuit, sim, shots=shots).result().get_counts()
# calculate the probabilities for each bit value
probs = {}
for output in ['0','1']:
if output in counts:
probs[output] = counts[output]/shots
else:
probs[output] = 0
bloch_vector_measure.append( probs['0'] - probs['1'] )
# normalizing the bloch sphere vector
bloch_vector = bloch_vector_measure/la.norm(bloch_vector_measure)
print('The bloch sphere coordinates are [{0:4.3f}, {1:4.3f}, {2:4.3f}]'
.format(*bloch_vector))
from kaleidoscope.interactive import bloch_sphere
bloch_sphere(bloch_vector, vectors_annotation=True)
from qiskit.visualization import plot_bloch_vector
plot_bloch_vector( bloch_vector )
# circuit for the state Tri1
Tri1 = QuantumCircuit(2)
# your code goes here
# circuit for the state Tri2
Tri2 = QuantumCircuit(2)
# your code goes here
# circuit for the state Tri3
Tri3 = QuantumCircuit(2)
# your code goes here
# circuit for the state Sing
Sing = QuantumCircuit(2)
# your code goes here
# <ZZ>
measure_ZZ = QuantumCircuit(2)
measure_ZZ.measure_all()
# <XX>
measure_XX = QuantumCircuit(2)
# your code goes here
# <YY>
measure_YY = QuantumCircuit(2)
# your code goes here
shots = 2**14 # number of samples used for statistics
A = 1.47e-6 #unit of A is eV
E_sim = []
for state_init in [Tri1,Tri2,Tri3,Sing]:
Energy_meas = []
for measure_circuit in [measure_XX, measure_YY, measure_ZZ]:
# run the circuit with a the selected measurement and get the number of samples that output each bit value
qc = state_init+measure_circuit
counts = execute(qc, sim, shots=shots).result().get_counts()
# calculate the probabilities for each computational basis
probs = {}
for output in ['00','01', '10', '11']:
if output in counts:
probs[output] = counts[output]/shots
else:
probs[output] = 0
Energy_meas.append( probs['00'] - probs['01'] - probs['10'] + probs['11'] )
E_sim.append(A * np.sum(np.array(Energy_meas)))
# Run this cell to print out your results
print('Energy expection value of the state Tri1 : {:.3e} eV'.format(E_sim[0]))
print('Energy expection value of the state Tri2 : {:.3e} eV'.format(E_sim[1]))
print('Energy expection value of the state Tri3 : {:.3e} eV'.format(E_sim[2]))
print('Energy expection value of the state Sing : {:.3e} eV'.format(E_sim[3]))
# reduced plank constant in (eV) and the speed of light(cgs units)
hbar, c = 4.1357e-15, 3e10
# energy difference between the triplets and singlet
E_del = abs(E_sim[0] - E_sim[3])
# frequency associated with the energy difference
f = E_del/hbar
# convert frequency to wavelength in (cm)
wavelength = c/f
print('The wavelength of the radiation from the transition\
in the hyperfine structure is : {:.1f} cm'.format(wavelength))
provider = IBMQ.load_account()
backend = provider.get_backend('ibmq_athens')
# run this cell to get the backend information through the widget
backend
# assign your choice for the initial layout to the list variable `initial_layout`.
initial_layout =
qc_all = [state_init+measure_circuit for state_init in [Tri1,Tri2,Tri3,Sing]
for measure_circuit in [measure_XX, measure_YY, measure_ZZ] ]
shots = 8192
job = execute(qc_all, backend, initial_layout=initial_layout, optimization_level=3, shots=shots)
print(job.job_id())
job_monitor(job)
# getting the results of your job
results = job.result()
## To access the results of the completed job
#results = backend.retrieve_job('job_id').result()
def Energy(results, shots):
"""Compute the energy levels of the hydrogen ground state.
Parameters:
results (obj): results, results from executing the circuits for measuring a hamiltonian.
shots (int): shots, number of shots used for the circuit execution.
Returns:
Energy (list): energy values of the four different hydrogen ground states
"""
E = []
A = 1.47e-6
for ind_state in range(4):
Energy_meas = []
for ind_comp in range(3):
counts = results.get_counts(ind_state*3+ind_comp)
# calculate the probabilities for each computational basis
probs = {}
for output in ['00','01', '10', '11']:
if output in counts:
probs[output] = counts[output]/shots
else:
probs[output] = 0
Energy_meas.append( probs['00'] - probs['01'] - probs['10'] + probs['11'] )
E.append(A * np.sum(np.array(Energy_meas)))
return E
E = Energy(results, shots)
print('Energy expection value of the state Tri1 : {:.3e} eV'.format(E[0]))
print('Energy expection value of the state Tri2 : {:.3e} eV'.format(E[1]))
print('Energy expection value of the state Tri3 : {:.3e} eV'.format(E[2]))
print('Energy expection value of the state Sing : {:.3e} eV'.format(E[3]))
from qiskit.ignis.mitigation.measurement import *
# your code to create the circuits, meas_calibs, goes here
meas_calibs, state_labels =
# execute meas_calibs on your choice of the backend
job = execute(meas_calibs, backend, shots = shots)
print(job.job_id())
job_monitor(job)
cal_results = job.result()
## To access the results of the completed job
#cal_results = backend.retrieve_job('job_id').result()
# your code to obtain the measurement filter object, 'meas_filter', goes here
results_new = meas_filter.apply(results)
E_new = Energy(results_new, shots)
print('Energy expection value of the state Tri1 : {:.3e} eV'.format(E_new[0]))
print('Energy expection value of the state Tri2 : {:.3e} eV'.format(E_new[1]))
print('Energy expection value of the state Tri3 : {:.3e} eV'.format(E_new[2]))
print('Energy expection value of the state Sing : {:.3e} eV'.format(E_new[3]))
# results for the energy estimation from the simulation,
# execution on a quantum system without error mitigation and
# with error mitigation in numpy array format
Energy_exact, Energy_exp_orig, Energy_exp_new = np.array(E_sim), np.array(E), np.array(E_new)
# Calculate the relative errors of the energy values without error mitigation
# and assign to the numpy array variable `Err_rel_orig` of size 4
Err_rel_orig =
# Calculate the relative errors of the energy values with error mitigation
# and assign to the numpy array variable `Err_rel_new` of size 4
Err_rel_new =
np.set_printoptions(precision=3)
print('The relative errors of the energy values for four bell basis\
without measurement error mitigation : {}'.format(Err_rel_orig))
np.set_printoptions(precision=3)
print('The relative errors of the energy values for four bell basis\
with measurement error mitigation : {}'.format(Err_rel_new))
|
https://github.com/MonitSharma/Qiskit-Summer-School-and-Quantum-Challenges
|
MonitSharma
|
# Importing standard Qiskit libraries
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit import Aer, assemble
from qiskit.visualization import plot_histogram, plot_bloch_multivector, plot_state_qsphere, plot_state_city, plot_state_paulivec, plot_state_hinton
# Ignore warnings
import warnings
warnings.filterwarnings('ignore')
# Define backend
sim = Aer.get_backend('aer_simulator')
def createBellStates(inp1, inp2):
qc = QuantumCircuit(2)
qc.reset(range(2))
if inp1=='1':
qc.x(0)
if inp2=='1':
qc.x(1)
qc.barrier()
qc.h(0)
qc.cx(0,1)
qc.save_statevector()
qobj = assemble(qc)
result = sim.run(qobj).result()
state = result.get_statevector()
return qc, state, result
print('Note: Since these qubits are in entangled state, their state cannot be written as two separate qubit states. This also means that we lose information when we try to plot our state on separate Bloch spheres as seen below.\n')
inp1 = 0
inp2 = 1
qc, state, result = createBellStates(inp1, inp2)
display(plot_bloch_multivector(state))
# Uncomment below code in order to explore other states
#for inp2 in ['0', '1']:
#for inp1 in ['0', '1']:
#qc, state, result = createBellStates(inp1, inp2)
#print('For inputs',inp2,inp1,'Representation of Entangled States are:')
# Uncomment any of the below functions to visualize the resulting quantum states
# Draw the quantum circuit
#display(qc.draw())
# Plot states on QSphere
#display(plot_state_qsphere(state))
# Plot states on Bloch Multivector
#display(plot_bloch_multivector(state))
# Plot histogram
#display(plot_histogram(result.get_counts()))
# Plot state matrix like a city
#display(plot_state_city(state))
# Represent state matix using Pauli operators as the basis
#display(plot_state_paulivec(state))
# Plot state matrix as Hinton representation
#display(plot_state_hinton(state))
#print('\n')'''
from qiskit import IBMQ, execute
from qiskit.providers.ibmq import least_busy
from qiskit.tools import job_monitor
# Loading your IBM Quantum account(s)
provider = IBMQ.load_account()
backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 2
and not x.configuration().simulator
and x.status().operational==True))
def createBSRealDevice(inp1, inp2):
qr = QuantumRegister(2)
cr = ClassicalRegister(2)
qc = QuantumCircuit(qr, cr)
qc.reset(range(2))
if inp1 == 1:
qc.x(0)
if inp2 == 1:
qc.x(1)
qc.barrier()
qc.h(0)
qc.cx(0,1)
qc.measure(qr, cr)
job = execute(qc, backend=backend, shots=100)
job_monitor(job)
result = job.result()
return qc, result
inp1 = 0
inp2 = 0
print('For inputs',inp2,inp1,'Representation of Entangled States are,')
#first results
qc, first_result = createBSRealDevice(inp1, inp2)
first_counts = first_result.get_counts()
# Draw the quantum circuit
display(qc.draw())
#second results
qc, second_result = createBSRealDevice(inp1, inp2)
second_counts = second_result.get_counts()
# Plot results on histogram with legend
legend = ['First execution', 'Second execution']
plot_histogram([first_counts, second_counts], legend=legend)
def ghzCircuit(inp1, inp2, inp3):
qc = QuantumCircuit(3)
qc.reset(range(3))
if inp1 == 1:
qc.x(0)
if inp2 == 1:
qc.x(1)
if inp3 == 1:
qc.x(2)
qc.barrier()
qc.h(0)
qc.cx(0,1)
qc.cx(0,2)
qc.save_statevector()
qobj = assemble(qc)
result = sim.run(qobj).result()
state = result.get_statevector()
return qc, state, result
print('Note: Since these qubits are in entangled state, their state cannot be written as two separate qubit states. This also means that we lose information when we try to plot our state on separate Bloch spheres as seen below.\n')
inp1 = 0
inp2 = 1
inp3 = 1
qc, state, result = ghzCircuit(inp1, inp2, inp3)
display(plot_bloch_multivector(state))
# Uncomment below code in order to explore other states
#for inp3 in ['0','1']:
#for inp2 in ['0','1']:
#for inp1 in ['0','1']:
#qc, state, result = ghzCircuit(inp1, inp2, inp3)
#print('For inputs',inp3,inp2,inp1,'Representation of GHZ States are:')
# Uncomment any of the below functions to visualize the resulting quantum states
# Draw the quantum circuit
#display(qc.draw())
# Plot states on QSphere
#display(plot_state_qsphere(state))
# Plot states on Bloch Multivector
#display(plot_bloch_multivector(state))
# Plot histogram
#display(plot_histogram(result.get_counts()))
# Plot state matrix like a city
#display(plot_state_city(state))
# Represent state matix using Pauli operators as the basis
#display(plot_state_paulivec(state))
# Plot state matrix as Hinton representation
#display(plot_state_hinton(state))
#print('\n')
def ghz5QCircuit(inp1, inp2, inp3, inp4, inp5):
qc = QuantumCircuit(5)
#qc.reset(range(5))
if inp1 == 1:
qc.x(0)
if inp2 == 1:
qc.x(1)
if inp3 == 1:
qc.x(2)
if inp4 == 1:
qc.x(3)
if inp5 == 1:
qc.x(4)
qc.barrier()
qc.h(0)
qc.cx(0,1)
qc.cx(0,2)
qc.cx(0,3)
qc.cx(0,4)
qc.save_statevector()
qobj = assemble(qc)
result = sim.run(qobj).result()
state = result.get_statevector()
return qc, state, result
# Explore GHZ States for input 00010. Note: the input has been stated in little-endian format.
inp1 = 0
inp2 = 1
inp3 = 0
inp4 = 0
inp5 = 0
qc, state, result = ghz5QCircuit(inp1, inp2, inp3, inp4, inp5)
print('For inputs',inp5,inp4,inp3,inp2,inp1,'Representation of GHZ States are:')
display(plot_state_qsphere(state))
print('\n')
# Explore GHZ States for input 11001. Note: the input has been stated in little-endian format.
inp1 = 1
inp2 = 0
inp3 = 0
inp4 = 1
inp5 = 1
qc, state, result = ghz5QCircuit(inp1, inp2, inp3, inp4, inp5)
print('For inputs',inp5,inp4,inp3,inp2,inp1,'Representation of GHZ States are:')
display(plot_state_qsphere(state))
print('\n')
# Explore GHZ States for input 01010. Note: the input has been stated in little-endian format.
inp1 = 0
inp2 = 1
inp3 = 0
inp4 = 1
inp5 = 0
qc, state, result = ghz5QCircuit(inp1, inp2, inp3, inp4, inp5)
print('For inputs',inp5,inp4,inp3,inp2,inp1,'Representation of GHZ States are:')
display(plot_state_qsphere(state))
print('\n')
# Uncomment below code in order to explore other states
#for inp5 in ['0','1']:
#for inp4 in ['0','1']:
#for inp3 in ['0','1']:
#for inp2 in ['0','1']:
#for inp1 in ['0','1']:
#qc, state, result = ghz5QCircuit(inp1, inp2, inp3, inp4, inp5)
#print('For inputs',inp5,inp4,inp3,inp2,inp1,'Representation of GHZ States are:')
# Uncomment any of the below functions to visualize the resulting quantum states
# Draw the quantum circuit
#display(qc.draw())
# Plot states on QSphere
#display(plot_state_qsphere(state))
# Plot states on Bloch Multivector
#display(plot_bloch_multivector(state))
# Plot histogram
#display(plot_histogram(result.get_counts()))
# Plot state matrix like a city
#display(plot_state_city(state))
# Represent state matix using Pauli operators as the basis
#display(plot_state_paulivec(state))
# Plot state matrix as Hinton representation
#display(plot_state_hinton(state))
#print('\n')
backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 5
and not x.configuration().simulator
and x.status().operational==True))
def create5QGHZRealDevice(inp1, inp2, inp3, inp4, inp5):
qr = QuantumRegister(5)
cr = ClassicalRegister(5)
qc = QuantumCircuit(qr, cr)
qc.reset(range(5))
if inp1=='1':
qc.x(0)
if inp2=='1':
qc.x(1)
if inp3=='1':
qc.x(1)
if inp4=='1':
qc.x(1)
if inp5=='1':
qc.x(1)
qc.barrier()
qc.h(0)
qc.cx(0,1)
qc.cx(0,2)
qc.cx(0,3)
qc.cx(0,4)
qc.measure(qr, cr)
job = execute(qc, backend=backend, shots=1000)
job_monitor(job)
result = job.result()
return qc, result
inp1 = 0
inp2 = 0
inp3 = 0
inp4 = 0
inp5 = 0
#first results
qc, first_result = create5QGHZRealDevice(inp1, inp2, inp3, inp4, inp5)
first_counts = first_result.get_counts()
# Draw the quantum circuit
display(qc.draw())
#second results
qc, second_result = create5QGHZRealDevice(inp1, inp2, inp3, inp4, inp5)
second_counts = second_result.get_counts()
print('For inputs',inp5,inp4,inp3,inp2,inp1,'Representation of GHZ circuit states are,')
# Plot results on histogram with legend
legend = ['First execution', 'Second execution']
plot_histogram([first_counts, second_counts], legend=legend)
import qiskit
qiskit.__qiskit_version__
|
https://github.com/MonitSharma/Qiskit-Summer-School-and-Quantum-Challenges
|
MonitSharma
|
from qiskit import QuantumCircuit, QuantumRegister
from qiskit.quantum_info import SparsePauliOp
def heisenberg_hamiltonian(
length: int, jx: float = 1.0, jy: float = 0.0, jz: float = 0.0
) -> SparsePauliOp:
terms = []
for i in range(length - 1):
if jx:
terms.append(("XX", [i, i + 1], jx))
if jy:
terms.append(("YY", [i, i + 1], jy))
if jz:
terms.append(("ZZ", [i, i + 1], jz))
return SparsePauliOp.from_sparse_list(terms, num_qubits=length)
def state_prep_circuit(num_qubits: int, layers: int = 1) -> QuantumCircuit:
qubits = QuantumRegister(num_qubits, name="q")
circuit = QuantumCircuit(qubits)
circuit.h(qubits)
for _ in range(layers):
for i in range(0, num_qubits - 1, 2):
circuit.cx(qubits[i], qubits[i + 1])
circuit.ry(0.1, qubits)
for i in range(1, num_qubits - 1, 2):
circuit.cx(qubits[i], qubits[i + 1])
circuit.ry(0.1, qubits)
return circuit
length = 5
hamiltonian = heisenberg_hamiltonian(length, 1.0, 1.0)
circuit = state_prep_circuit(length, layers=2)
print(hamiltonian)
circuit.draw("mpl")
from qiskit_aer.primitives import Estimator
estimator = Estimator(approximation=True)
job = estimator.run(circuit, hamiltonian, shots=None)
result = job.result()
exact_value = result.values[0]
print(f"Exact energy: {exact_value}")
from qiskit_ibm_runtime import QiskitRuntimeService
hub = "ibm-q-internal"
group = "deployed"
project = "default"
service = QiskitRuntimeService(instance=f"{hub}/{group}/{project}")
from qiskit_ibm_runtime import Estimator, Options, Session
from qiskit.transpiler import CouplingMap
backend = service.get_backend("simulator_statevector")
# set simulation options
simulator = {
"basis_gates": ["id", "rz", "sx", "cx", "reset"],
"coupling_map": list(CouplingMap.from_line(length + 1)),
}
shots = 10000
import math
options = Options(
simulator=simulator,
resilience_level=0,
)
with Session(service=service, backend=backend):
estimator = Estimator(options=options)
job = estimator.run(circuit, hamiltonian, shots=shots)
result = job.result()
experiment_value = result.values[0]
error = abs(experiment_value - exact_value)
variance = result.metadata[0]["variance"]
std = math.sqrt(variance / shots)
print(f"Estimated energy: {experiment_value}")
print(f"Energy error: {error}")
print(f"Variance: {variance}")
print(f"Standard error: {std}")
from qiskit_aer.noise import NoiseModel, ReadoutError
noise_model = NoiseModel()
##### your code here #####
# P(A|B) = [P(A|0), P(A|1)] = [ 1 - q0_01, q0_01 ] = [ 0.8, 0.2 ]
q0_10 = 0.5
q0_01 = 0.2
qn_10 = 0.05
qn_01 = 0.02
re_l = [ReadoutError(
[
[1 - q0_01, q0_01],
[q0_10, 1 - q0_10],
]
)]
n_qubits = 6
for _ in range(n_qubits - 1):
re_l.append(ReadoutError(
[
[1 - qn_01, qn_01],
[qn_10, 1 - qn_10],
]
))
for q in range(n_qubits):
noise_model.add_readout_error(re_l[q], (q, ))
print(noise_model.to_dict())
# Submit your answer
from qc_grader.challenges.qgss_2023 import grade_lab5_ex1
grade_lab5_ex1(noise_model)
options = Options(
simulator=dict(noise_model=noise_model, **simulator),
resilience_level=0,
transpilation=dict(initial_layout=list(range(length))),
)
with Session(service=service, backend=backend):
estimator = Estimator(options=options)
job = estimator.run(circuit, hamiltonian, shots=shots)
result = job.result()
experiment_value = result.values[0]
error = abs(experiment_value - exact_value)
variance = result.metadata[0]["variance"]
std = math.sqrt(variance / shots)
print(f"Estimated energy: {experiment_value}")
print(f"Energy error: {error}")
print(f"Variance: {variance}")
print(f"Standard error: {std}")
options = Options(
simulator=dict(noise_model=noise_model, **simulator),
resilience_level=0,
transpilation=dict(initial_layout=list(range(1, length + 1))),
)
with Session(service=service, backend=backend):
estimator = Estimator(options=options)
job = estimator.run(circuit, hamiltonian, shots=shots)
result = job.result()
experiment_value = result.values[0]
error = abs(experiment_value - exact_value)
variance = result.metadata[0]["variance"]
std = math.sqrt(variance / shots)
print(f"Estimated energy: {experiment_value}")
print(f"Energy error: {error}")
print(f"Variance: {variance}")
print(f"Standard error: {std}")
options = Options(
simulator=dict(noise_model=noise_model, **simulator),
resilience_level=1,
transpilation=dict(initial_layout=list(range(1, length + 1))),
)
with Session(service=service, backend=backend):
estimator = Estimator(options=options)
job = estimator.run(circuit, hamiltonian, shots=shots)
result = job.result()
experiment_value = result.values[0]
error = abs(experiment_value - exact_value)
variance = result.metadata[0]["variance"]
std = math.sqrt(variance / shots)
print(f"Estimated energy: {experiment_value}")
print(f"Energy error: {error}")
print(f"Variance: {variance}")
print(f"Standard error: {std}")
new_shots: int
##### your code here #####
new_shots = 20000
# Submit your answer
from qc_grader.challenges.qgss_2023 import grade_lab5_ex2
grade_lab5_ex2(new_shots)
from qiskit_aer.noise import depolarizing_error
noise_model = NoiseModel()
##### your code here #####
error = depolarizing_error(0.01, 2)
noise_model.add_all_qubit_quantum_error(error, ['cx'])
print(noise_model)
# Submit your answer
from qc_grader.challenges.qgss_2023 import grade_lab5_ex3
grade_lab5_ex3(noise_model)
options = Options(
simulator=dict(noise_model=noise_model, **simulator),
resilience_level=1,
)
with Session(service=service, backend=backend):
estimator = Estimator(options=options)
job = estimator.run(circuit, hamiltonian, shots=shots)
result = job.result()
experiment_value = result.values[0]
error = abs(experiment_value - exact_value)
variance = result.metadata[0]["variance"]
std = math.sqrt(variance / shots)
print(f"Estimated energy: {experiment_value}")
print(f"Energy error: {error}")
print(f"Variance: {variance}")
print(f"Standard error: {std}")
options = Options(
simulator=dict(noise_model=noise_model, **simulator),
resilience_level=2,
)
with Session(service=service, backend=backend):
estimator = Estimator(options=options)
job = estimator.run(circuit, hamiltonian, shots=shots)
result = job.result()
experiment_value = result.values[0]
error = abs(experiment_value - exact_value)
variances = result.metadata[0]["zne"]["noise_amplification"]["variance"]
print(f"Estimated energy: {experiment_value}")
print(f"Energy error: {error}")
print(f"Variances: {variances}")
|
https://github.com/MonitSharma/Qiskit-Summer-School-and-Quantum-Challenges
|
MonitSharma
|
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams.update({'font.size': 16}) # enlarge matplotlib fonts
# Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z)
from qiskit.opflow import Zero, One, I, X, Y, Z
# Suppress warnings
import warnings
warnings.filterwarnings('ignore')
# Returns the matrix representation of the XXX Heisenberg model for 3 spin-1/2 particles in a line
def H_heis3():
# Interactions (I is the identity matrix; X, Y, and Z are Pauli matricies; ^ is a tensor product)
XXs = (I^X^X) + (X^X^I)
YYs = (I^Y^Y) + (Y^Y^I)
ZZs = (I^Z^Z) + (Z^Z^I)
# Sum interactions
H = XXs + YYs + ZZs
# Return Hamiltonian
return H
# Returns the matrix representation of U_heis3(t) for a given time t assuming an XXX Heisenberg Hamiltonian for 3 spins-1/2 particles in a line
def U_heis3(t):
# Compute XXX Hamiltonian for 3 spins in a line
H = H_heis3()
# Return the exponential of -i multipled by time t multipled by the 3 spin XXX Heisenberg Hamilonian
return (t * H).exp_i()
# Define array of time points
ts = np.linspace(0, np.pi, 100)
# Define initial state |110>
initial_state = One^One^Zero
# Compute probability of remaining in |110> state over the array of time points
# ~initial_state gives the bra of the initial state (<110|)
# @ is short hand for matrix multiplication
# U_heis3(t) is the unitary time evolution at time t
# t needs to be wrapped with float(t) to avoid a bug
# (...).eval() returns the inner product <110|U_heis3(t)|110>
# np.abs(...)**2 is the modulus squared of the innner product which is the expectation value, or probability, of remaining in |110>
probs_110 = [np.abs((~initial_state @ U_heis3(float(t)) @ initial_state).eval())**2 for t in ts]
# Plot evolution of |110>
plt.plot(ts, probs_110)
plt.xlabel('time')
plt.ylabel(r'probability of state $|110\rangle$')
plt.title(r'Evolution of state $|110\rangle$ under $H_{Heis3}$')
plt.grid()
plt.show()
# Importing standard Qiskit modules
from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile
from qiskit.providers.aer import QasmSimulator
from qiskit.tools.monitor import job_monitor
from qiskit.circuit import Parameter
# Import state tomography modules
from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter
from qiskit.quantum_info import state_fidelity
# suppress warnings
import warnings
warnings.filterwarnings('ignore')
# load IBMQ Account data
# IBMQ.save_account(TOKEN) # replace TOKEN with your API token string (https://quantum-computing.ibm.com/lab/docs/iql/manage/account/ibmq)
provider = IBMQ.load_account()
# Get backend for experiment
provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22')
jakarta = provider.get_backend('ibmq_jakarta')
# properties = jakarta.properties()
# Simulated backend based on ibmq_jakarta's device noise profile
sim_noisy_jakarta = QasmSimulator.from_backend(provider.get_backend('ibmq_jakarta'))
# Noiseless simulated backend
sim = QasmSimulator()
# Parameterize variable t to be evaluated at t=pi later
t = Parameter('t')
# Build a subcircuit for XX(t) two-qubit gate
XX_qr = QuantumRegister(2)
XX_qc = QuantumCircuit(XX_qr, name='XX')
XX_qc.ry(np.pi/2,[0,1])
XX_qc.cnot(0,1)
XX_qc.rz(2 * t, 1)
XX_qc.cnot(0,1)
XX_qc.ry(-np.pi/2,[0,1])
# Convert custom quantum circuit into a gate
XX = XX_qc.to_instruction()
# Build a subcircuit for YY(t) two-qubit gate
YY_qr = QuantumRegister(2)
YY_qc = QuantumCircuit(YY_qr, name='YY')
YY_qc.rx(np.pi/2,[0,1])
YY_qc.cnot(0,1)
YY_qc.rz(2 * t, 1)
YY_qc.cnot(0,1)
YY_qc.rx(-np.pi/2,[0,1])
# Convert custom quantum circuit into a gate
YY = YY_qc.to_instruction()
# Build a subcircuit for ZZ(t) two-qubit gate
ZZ_qr = QuantumRegister(2)
ZZ_qc = QuantumCircuit(ZZ_qr, name='ZZ')
ZZ_qc.cnot(0,1)
ZZ_qc.rz(2 * t, 1)
ZZ_qc.cnot(0,1)
# Convert custom quantum circuit into a gate
ZZ = ZZ_qc.to_instruction()
# Combine subcircuits into a single multiqubit gate representing a single trotter step
num_qubits = 3
Trot_qr = QuantumRegister(num_qubits)
Trot_qc = QuantumCircuit(Trot_qr, name='Trot')
for i in range(0, num_qubits - 1):
Trot_qc.append(ZZ, [Trot_qr[i], Trot_qr[i+1]])
Trot_qc.append(YY, [Trot_qr[i], Trot_qr[i+1]])
Trot_qc.append(XX, [Trot_qr[i], Trot_qr[i+1]])
# Convert custom quantum circuit into a gate
Trot_gate = Trot_qc.to_instruction()
# The final time of the state evolution
target_time = np.pi
# Number of trotter steps
trotter_steps = 4 ### CAN BE >= 4
# Initialize quantum circuit for 3 qubits
qr = QuantumRegister(7)
qc = QuantumCircuit(qr)
# Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>)
qc.x([3,5]) # DO NOT MODIFY (|q_5,q_3,q_1> = |110>)
# Simulate time evolution under H_heis3 Hamiltonian
for _ in range(trotter_steps):
qc.append(Trot_gate, [qr[1], qr[3], qr[5]])
# Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time
qc = qc.bind_parameters({t: target_time/trotter_steps})
# Generate state tomography circuits to evaluate fidelity of simulation
st_qcs = state_tomography_circuits(qc, [qr[1], qr[3], qr[5]])
# Display circuit for confirmation
# st_qcs[-1].decompose().draw() # view decomposition of trotter gates
st_qcs[-1].draw() # only view trotter gates
shots = 8192
reps = 8
backend = sim_noisy_jakarta
# reps = 8
# backend = jakarta
jobs = []
for _ in range(reps):
# execute
job = execute(st_qcs, backend, shots=shots)
print('Job ID', job.job_id())
jobs.append(job)
for job in jobs:
job_monitor(job)
try:
if job.error_message() is not None:
print(job.error_message())
except:
pass
# Compute the state tomography based on the st_qcs quantum circuits and the results from those ciricuits
def state_tomo(result, st_qcs):
# The expected final state; necessary to determine state tomography fidelity
target_state = (One^One^Zero).to_matrix() # DO NOT MODIFY (|q_5,q_3,q_1> = |110>)
# Fit state tomography results
tomo_fitter = StateTomographyFitter(result, st_qcs)
rho_fit = tomo_fitter.fit(method='lstsq')
# Compute fidelity
fid = state_fidelity(rho_fit, target_state)
return fid
# Compute tomography fidelities for each repetition
fids = []
for job in jobs:
fid = state_tomo(job.result(), st_qcs)
fids.append(fid)
print('state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(fids), np.std(fids)))
import qiskit.tools.jupyter
%qiskit_version_table
|
https://github.com/MonitSharma/Qiskit-Summer-School-and-Quantum-Challenges
|
MonitSharma
|
from qiskit_nature.drivers import Molecule
from qiskit_nature.drivers.second_quantization import ElectronicStructureMoleculeDriver, ElectronicStructureDriverType
molecule = Molecule(
# coordinates are given in Angstrom
geometry=[
["O", [0.0, 0.0, 0.0]],
["H", [0.758602, 0.0, 0.504284]],
["H", [0.758602, 0.0, -0.504284]]
],
multiplicity=1, # = 2*spin + 1
charge=0,
)
driver = ElectronicStructureMoleculeDriver(
molecule=molecule,
basis="sto3g",
driver_type=ElectronicStructureDriverType.PYSCF,
)
properties = driver.run()
# WRITE YOUR CODE BETWEEN THESE LINES - START
num_alpha_electrons =
num_beta_electrons =
num_spin_orbitals =
nuclear_rep_energy =
# WRITE YOUR CODE BETWEEN THESE LINES - END
from qc_grader.challenges.spring_2022 import grade_ex4a
grade_ex4a(
num_alpha_electrons=num_alpha_electrons,
num_beta_electrons=num_beta_electrons,
num_spin_orbitals=num_spin_orbitals,
nuclear_rep_energy=nuclear_rep_energy
)
from qiskit_nature.transformers.second_quantization.electronic import ActiveSpaceTransformer
# Check the occupation of the spin orbitals
PN_property = properties.get_property("ParticleNumber")
print(PN_property)
# Define the active space around the Fermi level
# (selected automatically around the HOMO and LUMO, ordered by energy)
transformer = ActiveSpaceTransformer(
num_electrons=2, #how many electrons we have in our active space
num_molecular_orbitals=2, #how many orbitals we have in our active space
)
# We can hand-pick the MOs to be included in the AS
# (in case they are not exactly around the Fermi level)
# transformer = ActiveSpaceTransformer(
# num_electrons=2, #how many electrons we have in our active space
# num_molecular_orbitals=2, #how many orbitals we have in our active space
# active_orbitals=[4,7], #We are specifically choosing MO number 4 (occupied with two electrons) and 7 (empty)
# )
from qiskit_nature.problems.second_quantization.electronic import ElectronicStructureProblem
problem = ElectronicStructureProblem(driver, [transformer])
second_q_ops = problem.second_q_ops() # this calls driver.run() internally
hamiltonian = second_q_ops[0]
print(hamiltonian)
from qiskit_nature.operators.second_quantization import FermionicOp
# WRITE YOUR CODE BETWEEN THESE LINES - START
# list of valid tuples to initialize the FermionicOp
list_operator =
# positive integer that represents the length of registers
num_register_length =
# WRITE YOUR CODE BETWEEN THESE LINES - END
from qc_grader.challenges.spring_2022 import grade_ex4b
grade_ex4b(list_operator, num_register_length)
from qiskit_nature.mappers.second_quantization import ParityMapper, BravyiKitaevMapper, JordanWignerMapper
from qiskit_nature.converters.second_quantization import QubitConverter
# Setup the mapper and qubit converter
mapper_type = 'JordanWignerMapper'
if mapper_type == 'ParityMapper':
mapper = ParityMapper()
elif mapper_type == 'JordanWignerMapper':
mapper = JordanWignerMapper()
elif mapper_type == 'BravyiKitaevMapper':
mapper = BravyiKitaevMapper()
converter = QubitConverter(mapper)
qubit_op = converter.convert(hamiltonian)
print(qubit_op)
from qiskit_nature.circuit.library import HartreeFock
particle_number = problem.grouped_property_transformed.get_property("ParticleNumber")
num_spin_orbitals = particle_number.num_spin_orbitals
num_particles = particle_number.num_particles
init_state = HartreeFock(num_spin_orbitals, num_particles, converter)
print(init_state)
from qiskit.circuit.library import TwoLocal
from qiskit_nature.circuit.library import UCCSD, PUCCD, SUCCD
# Choose the ansatz
ansatz_type = "UCCSD"
# Put arguments for twolocal
if ansatz_type == "TwoLocal":
# Single qubit rotations that are placed on all qubits with independent parameters
rotation_blocks = ['ry', 'rz']
# Entangling gates
entanglement_blocks = 'cz'
# How the qubits are entangled
entanglement = 'full'
# Repetitions of rotation_blocks + entanglement_blocks with independent parameters
repetitions = 1
# Skip the final rotation_blocks layer
skip_final_rotation_layer = True
ansatz = TwoLocal(qubit_op.num_qubits, rotation_blocks, entanglement_blocks, reps=repetitions,
entanglement=entanglement, skip_final_rotation_layer=skip_final_rotation_layer)
# Add the initial state
ansatz.compose(init_state, front=True, inplace=True)
elif ansatz_type == "UCCSD":
ansatz = UCCSD(converter,num_particles,num_spin_orbitals,initial_state = init_state)
elif ansatz_type == "PUCCD":
ansatz = PUCCD(converter,num_particles,num_spin_orbitals,initial_state = init_state)
elif ansatz_type == "SUCCD":
ansatz = SUCCD(converter,num_particles,num_spin_orbitals,initial_state = init_state)
elif ansatz_type == "Custom":
# Example of how to write your own circuit
from qiskit.circuit import Parameter, QuantumCircuit, QuantumRegister
# Define the variational parameter
theta = Parameter('a')
n = qubit_op.num_qubits
# Make an empty quantum circuit
qc = QuantumCircuit(qubit_op.num_qubits)
qubit_label = 0
# Place a Hadamard gate
qc.h(qubit_label)
# Place a CNOT ladder
for i in range(n-1):
qc.cx(i, i+1)
# Visual separator
qc.barrier()
# rz rotations on all qubits
qc.rz(theta, range(n))
ansatz = qc
ansatz.compose(init_state, front=True, inplace=True)
print(ansatz.decompose())
from qiskit import Aer
backend = Aer.get_backend('statevector_simulator')
from qiskit.algorithms.optimizers import COBYLA, L_BFGS_B, SPSA, SLSQP
optimizer_type = 'L_BFGS_B'
# You may want to tune the parameters
# of each optimizer, here the defaults are used
if optimizer_type == 'COBYLA':
optimizer = COBYLA(maxiter=500)
elif optimizer_type == 'L_BFGS_B':
optimizer = L_BFGS_B(maxfun=500)
elif optimizer_type == 'SPSA':
optimizer = SPSA(maxiter=500)
elif optimizer_type == 'SLSQP':
optimizer = SLSQP(maxiter=500)
from qiskit_nature.algorithms.ground_state_solvers.minimum_eigensolver_factories import NumPyMinimumEigensolverFactory
from qiskit_nature.algorithms.ground_state_solvers import GroundStateEigensolver
import numpy as np
def exact_diagonalizer(problem, converter):
solver = NumPyMinimumEigensolverFactory()
calc = GroundStateEigensolver(converter, solver)
result = calc.solve(problem)
return result
result_exact = exact_diagonalizer(problem, converter)
exact_energy = np.real(result_exact.eigenenergies[0])
print("Exact electronic energy", exact_energy)
print(result_exact)
# The targeted electronic energy for H2 is -1.85336 Ha
# Check with your VQE result.
from qiskit.algorithms import VQE
from IPython.display import display, clear_output
# Print and save the data in lists
def callback(eval_count, parameters, mean, std):
# Overwrites the same line when printing
display("Evaluation: {}, Energy: {}, Std: {}".format(eval_count, mean, std))
clear_output(wait=True)
counts.append(eval_count)
values.append(mean)
params.append(parameters)
deviation.append(std)
counts = []
values = []
params = []
deviation = []
# Set initial parameters of the ansatz
# We choose a fixed small displacement
# So all participants start from similar starting point
try:
initial_point = [0.01] * len(ansatz.ordered_parameters)
except:
initial_point = [0.01] * ansatz.num_parameters
algorithm = VQE(ansatz,
optimizer=optimizer,
quantum_instance=backend,
callback=callback,
initial_point=initial_point)
result = algorithm.compute_minimum_eigenvalue(qubit_op)
print(result)
# Store results in a dictionary
from qiskit.transpiler import PassManager
from qiskit.transpiler.passes import Unroller
# Unroller transpile your circuit into CNOTs and U gates
pass_ = Unroller(['u', 'cx'])
pm = PassManager(pass_)
ansatz_tp = pm.run(ansatz)
cnots = ansatz_tp.count_ops()['cx']
energy = result.optimal_value
if ansatz_type == "TwoLocal":
result_dict = {
'optimizer': optimizer.__class__.__name__,
'mapping': converter.mapper.__class__.__name__,
'ansatz': ansatz.__class__.__name__,
'rotation blocks': rotation_blocks,
'entanglement_blocks': entanglement_blocks,
'entanglement': entanglement,
'repetitions': repetitions,
'skip_final_rotation_layer': skip_final_rotation_layer,
'energy (Ha)': energy,
'error (mHa)': (energy-exact_energy)*1000,
'# of parameters': len(result.optimal_point),
'final parameters': result.optimal_point,
'# of evaluations': result.cost_function_evals,
'# of qubits': int(qubit_op.num_qubits),
'# of CNOTs': cnots}
else:
result_dict = {
'optimizer': optimizer.__class__.__name__,
'mapping': converter.mapper.__class__.__name__,
'ansatz': ansatz.__class__.__name__,
'rotation blocks': None,
'entanglement_blocks': None,
'entanglement': None,
'repetitions': None,
'skip_final_rotation_layer': None,
'energy (Ha)': energy,
'error (mHa)': (energy-exact_energy)*1000,
'# of parameters': len(result.optimal_point),
'final parameters': result.optimal_point,
'# of evaluations': result.cost_function_evals,
'# of qubits': int(qubit_op.num_qubits),
'# of CNOTs': cnots}
# Plot the results
import matplotlib.pyplot as plt
fig, ax = plt.subplots(1, 1)
ax.set_xlabel('Iterations')
ax.set_ylabel('Energy')
ax.grid()
fig.text(0.7, 0.75, f'Energy: {result.optimal_value:.3f}')
plt.title(f"{result_dict['optimizer']}-{result_dict['mapping']}\n{result_dict['ansatz']}")
ax.plot(counts, values)
ax.axhline(exact_energy, linestyle='--')
fig_title = f"\
{result_dict['optimizer']}-\
{result_dict['mapping']}-\
{result_dict['ansatz']}-\
Energy({result_dict['energy (Ha)']:.3f}).png"
fig.savefig(fig_title, dpi=300)
# Display and save the data
import pandas as pd
import os.path
filename = 'results_h2o.csv'
if os.path.isfile(filename):
result_df = pd.read_csv(filename)
result_df = result_df.append([result_dict])
else:
result_df = pd.DataFrame.from_dict([result_dict])
result_df.to_csv(filename)
result_df[['optimizer','ansatz', 'rotation blocks', 'entanglement_blocks',
'entanglement', 'repetitions', '# of qubits', '# of parameters', '# of CNOTs', '# of evaluations', 'error (mHa)']]
from qiskit import Aer
from qiskit.utils import QuantumInstance
from qiskit_nature.algorithms import GroundStateEigensolver, QEOM, VQEUCCFactory
# This first part sets the ground state solver
# see more about this part in the ground state calculation tutorial
quantum_instance = QuantumInstance(Aer.get_backend("aer_simulator_statevector"))
solver = VQEUCCFactory(quantum_instance)
gsc = GroundStateEigensolver(converter, solver)
# The qEOM algorithm is simply instantiated with the chosen ground state solver
qeom_excited_states_calculation = QEOM(gsc, "sd")
qeom_results = qeom_excited_states_calculation.solve(problem)
print(qeom_results)
# WRITE YOUR CODE BETWEEN THESE LINES - START
# WRITE YOUR CODE BETWEEN THESE LINES - END
|
https://github.com/MonitSharma/Qiskit-Summer-School-and-Quantum-Challenges
|
MonitSharma
|
!pip install -U -r grading_tools/requirements.txt
from IPython.display import clear_output
clear_output()
import numpy as np; pi = np.pi
from qiskit import QuantumCircuit, Aer, execute
from qiskit.visualization import plot_histogram
from copy import deepcopy as make_copy
def prepare_hets_circuit(depth, angle1, angle2):
hets_circ = QuantumCircuit(depth)
hets_circ.ry(angle1, 0)
hets_circ.rz(angle1, 0)
hets_circ.ry(angle1, 1)
hets_circ.rz(angle1, 1)
for ii in range(depth):
hets_circ.cx(0,1)
hets_circ.ry(angle2,0)
hets_circ.rz(angle2,0)
hets_circ.ry(angle2,1)
hets_circ.rz(angle2,1)
return hets_circ
hets_circuit = prepare_hets_circuit(2, pi/2, pi/2)
hets_circuit.draw()
def measure_zz_circuit(given_circuit):
zz_meas = make_copy(given_circuit)
zz_meas.measure_all()
return zz_meas
zz_meas = measure_zz_circuit(hets_circuit)
zz_meas.draw()
simulator = Aer.get_backend('qasm_simulator')
result = execute(zz_meas, backend = simulator, shots=10000).result()
counts = result.get_counts(zz_meas)
plot_histogram(counts)
def measure_zz(given_circuit, num_shots = 10000):
zz_meas = measure_zz_circuit(given_circuit)
result = execute(zz_meas, backend = simulator, shots = num_shots).result()
counts = result.get_counts(zz_meas)
if '00' not in counts:
counts['00'] = 0
if '01' not in counts:
counts['01'] = 0
if '10' not in counts:
counts['10'] = 0
if '11' not in counts:
counts['11'] = 0
total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10']
zz = counts['00'] + counts['11'] - counts['01'] - counts['10']
zz = zz / total_counts
return zz
zz = measure_zz(hets_circuit)
print("<ZZ> =", str(zz))
def measure_zi(given_circuit, num_shots = 10000):
zz_meas = measure_zz_circuit(given_circuit)
result = execute(zz_meas, backend = simulator, shots = num_shots).result()
counts = result.get_counts(zz_meas)
if '00' not in counts:
counts['00'] = 0
if '01' not in counts:
counts['01'] = 0
if '10' not in counts:
counts['10'] = 0
if '11' not in counts:
counts['11'] = 0
total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10']
zi = counts['00'] - counts['11'] + counts['01'] - counts['10']
zi = zi / total_counts
return zi
def measure_iz(given_circuit, num_shots = 10000):
zz_meas = measure_zz_circuit(given_circuit)
result = execute(zz_meas, backend = simulator, shots = num_shots).result()
counts = result.get_counts(zz_meas)
if '00' not in counts:
counts['00'] = 0
if '01' not in counts:
counts['01'] = 0
if '10' not in counts:
counts['10'] = 0
if '11' not in counts:
counts['11'] = 0
total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10']
iz = counts['00'] - counts['11'] - counts['01'] + counts['10']
iz = iz / total_counts
return iz
zi = measure_zi(hets_circuit)
print("<ZI> =", str(zi))
iz = measure_iz(hets_circuit)
print("<IZ> =", str(iz))
def measure_xx_circuit(given_circuit):
xx_meas = make_copy(given_circuit)
### WRITE YOUR CODE BETWEEN THESE LINES - START
xx_meas.h(0)
xx_meas.h(1)
xx_meas.measure_all()
### WRITE YOUR CODE BETWEEN THESE LINES - END
return xx_meas
xx_meas = measure_xx_circuit(hets_circuit)
xx_meas.draw()
def measure_xx(given_circuit, num_shots = 10000):
xx_meas = measure_xx_circuit(given_circuit)
result = execute(xx_meas, backend = simulator, shots = num_shots).result()
counts = result.get_counts(xx_meas)
if '00' not in counts:
counts['00'] = 0
if '01' not in counts:
counts['01'] = 0
if '10' not in counts:
counts['10'] = 0
if '11' not in counts:
counts['11'] = 0
total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10']
xx = counts['00'] + counts['11'] - counts['01'] - counts['10']
xx = xx / total_counts
return xx
xx = measure_xx(hets_circuit)
print("<XX> =", str(xx))
def get_energy(given_circuit, num_shots = 10000):
zz = measure_zz(given_circuit, num_shots = num_shots)
iz = measure_iz(given_circuit, num_shots = num_shots)
zi = measure_zi(given_circuit, num_shots = num_shots)
xx = measure_xx(given_circuit, num_shots = num_shots)
energy = (-1.0523732)*1 + (0.39793742)*iz + (-0.3979374)*zi + (-0.0112801)*zz + (0.18093119)*xx
return energy
energy = get_energy(hets_circuit)
print("The energy of the trial state is", str(energy))
hets_circuit_plus = None
hets_circuit_minus = None
### WRITE YOUR CODE BETWEEN THESE LINES - START
hets_circuit_plus = prepare_hets_circuit(2, pi/2 + 0.1*pi/2, pi/2)
hets_circuit_minus = prepare_hets_circuit(2, pi/2 - 0.1*pi/2, pi/2)
### WRITE YOUR CODE BETWEEN THESE LINES - END
energy_plus = get_energy(hets_circuit_plus, num_shots=100000)
energy_minus = get_energy(hets_circuit_minus, num_shots=100000)
print(energy_plus, energy_minus)
name = 'Pon Rahul M'
email = 'ponrahul.21it@licet.ac.in'
### Do not change the lines below
from grading_tools import grade
grade(answer=measure_xx_circuit(hets_circuit), name=name, email=email, labid='lab9', exerciseid='ex1')
grade(answer=hets_circuit_plus, name=name, email=email, labid='lab9', exerciseid='ex2')
grade(answer=hets_circuit_minus, name=name, email=email, labid='lab9', exerciseid='ex3')
energy_plus_100, energy_plus_1000, energy_plus_10000 = 0, 0, 0
energy_minus_100, energy_minus_1000, energy_minus_10000 = 0, 0, 0
### WRITE YOUR CODE BETWEEN THESE LINES - START
energy_plus_100 = get_energy(hets_circuit_plus, num_shots = 100)
energy_minus_100 = get_energy(hets_circuit_minus, num_shots = 100)
energy_plus_1000 = get_energy(hets_circuit_plus, num_shots = 1000)
energy_minus_1000 = get_energy(hets_circuit_minus, num_shots = 1000)
energy_plus_10000 = get_energy(hets_circuit_plus, num_shots = 10000)
energy_minus_10000 = get_energy(hets_circuit_minus, num_shots = 10000)
### WRITE YOUR CODE BETWEEN THESE LINES - END
print(energy_plus_100, energy_minus_100, "difference = ", energy_minus_100 - energy_plus_100)
print(energy_plus_1000, energy_minus_1000, "difference = ", energy_minus_1000 - energy_plus_1000)
print(energy_plus_10000, energy_minus_10000, "difference = ", energy_minus_10000 - energy_plus_10000)
### WRITE YOUR CODE BETWEEN THESE LINES - START
I = np.array([
[1, 0],
[0, 1]
])
X = np.array([
[0, 1],
[1, 0]
])
Z = np.array([
[1, 0],
[0, -1]
])
h2_hamiltonian = (-1.0523732) * np.kron(I, I) + \
(0.39793742) * np.kron(I, Z) + \
(-0.3979374) * np.kron(Z, I) + \
(-0.0112801) * np.kron(Z, Z) + \
(0.18093119) * np.kron(X, X)
from numpy import linalg as LA
eigenvalues, eigenvectors = LA.eig(h2_hamiltonian)
for ii, eigenvalue in enumerate(eigenvalues):
print(f"Eigenvector {eigenvectors[:,ii]} has energy {eigenvalue}")
exact_eigenvector = eigenvectors[:,np.argmin(eigenvalues)]
exact_eigenvalue = np.min(eigenvalues)
print()
print("Minimum energy is", exact_eigenvalue)
### WRITE YOUR CODE BETWEEN THESE LINES - END
|
https://github.com/MonitSharma/Qiskit-Summer-School-and-Quantum-Challenges
|
MonitSharma
|
!pip install -U -r grading_tools/requirements.txt
from IPython.display import clear_output
clear_output()
import numpy as np; pi = np.pi
from qiskit import QuantumCircuit, Aer, execute
from qiskit.visualization import plot_histogram
from copy import deepcopy as make_copy
def prepare_hets_circuit(depth, angle1, angle2):
hets_circ = QuantumCircuit(depth)
hets_circ.ry(angle1, 0)
hets_circ.rz(angle1, 0)
hets_circ.ry(angle1, 1)
hets_circ.rz(angle1, 1)
for ii in range(depth):
hets_circ.cx(0,1)
hets_circ.ry(angle2,0)
hets_circ.rz(angle2,0)
hets_circ.ry(angle2,1)
hets_circ.rz(angle2,1)
return hets_circ
hets_circuit = prepare_hets_circuit(2, pi/2, pi/2)
hets_circuit.draw()
def measure_zz_circuit(given_circuit):
zz_meas = make_copy(given_circuit)
zz_meas.measure_all()
return zz_meas
zz_meas = measure_zz_circuit(hets_circuit)
zz_meas.draw()
simulator = Aer.get_backend('qasm_simulator')
result = execute(zz_meas, backend = simulator, shots=10000).result()
counts = result.get_counts(zz_meas)
plot_histogram(counts)
def measure_zz(given_circuit, num_shots = 10000):
zz_meas = measure_zz_circuit(given_circuit)
result = execute(zz_meas, backend = simulator, shots = num_shots).result()
counts = result.get_counts(zz_meas)
if '00' not in counts:
counts['00'] = 0
if '01' not in counts:
counts['01'] = 0
if '10' not in counts:
counts['10'] = 0
if '11' not in counts:
counts['11'] = 0
total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10']
zz = counts['00'] + counts['11'] - counts['01'] - counts['10']
zz = zz / total_counts
return zz
zz = measure_zz(hets_circuit)
print("<ZZ> =", str(zz))
def measure_zi(given_circuit, num_shots = 10000):
zz_meas = measure_zz_circuit(given_circuit)
result = execute(zz_meas, backend = simulator, shots = num_shots).result()
counts = result.get_counts(zz_meas)
if '00' not in counts:
counts['00'] = 0
if '01' not in counts:
counts['01'] = 0
if '10' not in counts:
counts['10'] = 0
if '11' not in counts:
counts['11'] = 0
total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10']
zi = counts['00'] - counts['11'] + counts['01'] - counts['10']
zi = zi / total_counts
return zi
def measure_iz(given_circuit, num_shots = 10000):
zz_meas = measure_zz_circuit(given_circuit)
result = execute(zz_meas, backend = simulator, shots = num_shots).result()
counts = result.get_counts(zz_meas)
if '00' not in counts:
counts['00'] = 0
if '01' not in counts:
counts['01'] = 0
if '10' not in counts:
counts['10'] = 0
if '11' not in counts:
counts['11'] = 0
total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10']
iz = counts['00'] - counts['11'] - counts['01'] + counts['10']
iz = iz / total_counts
return iz
zi = measure_zi(hets_circuit)
print("<ZI> =", str(zi))
iz = measure_iz(hets_circuit)
print("<IZ> =", str(iz))
def measure_xx_circuit(given_circuit):
xx_meas = make_copy(given_circuit)
### WRITE YOUR CODE BETWEEN THESE LINES - START
xx_meas.h(0)
xx_meas.h(1)
xx_meas.measure_all()
### WRITE YOUR CODE BETWEEN THESE LINES - END
return xx_meas
xx_meas = measure_xx_circuit(hets_circuit)
xx_meas.draw()
def measure_xx(given_circuit, num_shots = 10000):
xx_meas = measure_xx_circuit(given_circuit)
result = execute(xx_meas, backend = simulator, shots = num_shots).result()
counts = result.get_counts(xx_meas)
if '00' not in counts:
counts['00'] = 0
if '01' not in counts:
counts['01'] = 0
if '10' not in counts:
counts['10'] = 0
if '11' not in counts:
counts['11'] = 0
total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10']
xx = counts['00'] + counts['11'] - counts['01'] - counts['10']
xx = xx / total_counts
return xx
xx = measure_xx(hets_circuit)
print("<XX> =", str(xx))
def get_energy(given_circuit, num_shots = 10000):
zz = measure_zz(given_circuit, num_shots = num_shots)
iz = measure_iz(given_circuit, num_shots = num_shots)
zi = measure_zi(given_circuit, num_shots = num_shots)
xx = measure_xx(given_circuit, num_shots = num_shots)
energy = (-1.0523732)*1 + (0.39793742)*iz + (-0.3979374)*zi + (-0.0112801)*zz + (0.18093119)*xx
return energy
energy = get_energy(hets_circuit)
print("The energy of the trial state is", str(energy))
hets_circuit_plus = None
hets_circuit_minus = None
### WRITE YOUR CODE BETWEEN THESE LINES - START
hets_circuit_plus = prepare_hets_circuit(2, pi/2 + 0.1*pi/2, pi/2)
hets_circuit_minus = prepare_hets_circuit(2, pi/2 - 0.1*pi/2, pi/2)
### WRITE YOUR CODE BETWEEN THESE LINES - END
energy_plus = get_energy(hets_circuit_plus, num_shots=100000)
energy_minus = get_energy(hets_circuit_minus, num_shots=100000)
print(energy_plus, energy_minus)
name = 'Pon Rahul M'
email = 'ponrahul.21it@licet.ac.in'
### Do not change the lines below
from grading_tools import grade
grade(answer=measure_xx_circuit(hets_circuit), name=name, email=email, labid='lab9', exerciseid='ex1')
grade(answer=hets_circuit_plus, name=name, email=email, labid='lab9', exerciseid='ex2')
grade(answer=hets_circuit_minus, name=name, email=email, labid='lab9', exerciseid='ex3')
energy_plus_100, energy_plus_1000, energy_plus_10000 = 0, 0, 0
energy_minus_100, energy_minus_1000, energy_minus_10000 = 0, 0, 0
### WRITE YOUR CODE BETWEEN THESE LINES - START
energy_plus_100 = get_energy(hets_circuit_plus, num_shots = 100)
energy_minus_100 = get_energy(hets_circuit_minus, num_shots = 100)
energy_plus_1000 = get_energy(hets_circuit_plus, num_shots = 1000)
energy_minus_1000 = get_energy(hets_circuit_minus, num_shots = 1000)
energy_plus_10000 = get_energy(hets_circuit_plus, num_shots = 10000)
energy_minus_10000 = get_energy(hets_circuit_minus, num_shots = 10000)
### WRITE YOUR CODE BETWEEN THESE LINES - END
print(energy_plus_100, energy_minus_100, "difference = ", energy_minus_100 - energy_plus_100)
print(energy_plus_1000, energy_minus_1000, "difference = ", energy_minus_1000 - energy_plus_1000)
print(energy_plus_10000, energy_minus_10000, "difference = ", energy_minus_10000 - energy_plus_10000)
### WRITE YOUR CODE BETWEEN THESE LINES - START
I = np.array([
[1, 0],
[0, 1]
])
X = np.array([
[0, 1],
[1, 0]
])
Z = np.array([
[1, 0],
[0, -1]
])
h2_hamiltonian = (-1.0523732) * np.kron(I, I) + \
(0.39793742) * np.kron(I, Z) + \
(-0.3979374) * np.kron(Z, I) + \
(-0.0112801) * np.kron(Z, Z) + \
(0.18093119) * np.kron(X, X)
from numpy import linalg as LA
eigenvalues, eigenvectors = LA.eig(h2_hamiltonian)
for ii, eigenvalue in enumerate(eigenvalues):
print(f"Eigenvector {eigenvectors[:,ii]} has energy {eigenvalue}")
exact_eigenvector = eigenvectors[:,np.argmin(eigenvalues)]
exact_eigenvalue = np.min(eigenvalues)
print()
print("Minimum energy is", exact_eigenvalue)
### WRITE YOUR CODE BETWEEN THESE LINES - END
|
https://github.com/MonitSharma/Qiskit-Summer-School-and-Quantum-Challenges
|
MonitSharma
|
!pip install -U -r grading_tools/requirements.txt
from IPython.display import clear_output
clear_output()
import numpy as np; pi = np.pi
from qiskit import QuantumCircuit, Aer, execute
from qiskit.visualization import plot_histogram
from copy import deepcopy as make_copy
def prepare_hets_circuit(depth, angle1, angle2):
hets_circ = QuantumCircuit(depth)
hets_circ.ry(angle1, 0)
hets_circ.rz(angle1, 0)
hets_circ.ry(angle1, 1)
hets_circ.rz(angle1, 1)
for ii in range(depth):
hets_circ.cx(0,1)
hets_circ.ry(angle2,0)
hets_circ.rz(angle2,0)
hets_circ.ry(angle2,1)
hets_circ.rz(angle2,1)
return hets_circ
hets_circuit = prepare_hets_circuit(2, pi/2, pi/2)
hets_circuit.draw()
def measure_zz_circuit(given_circuit):
zz_meas = make_copy(given_circuit)
zz_meas.measure_all()
return zz_meas
zz_meas = measure_zz_circuit(hets_circuit)
zz_meas.draw()
simulator = Aer.get_backend('qasm_simulator')
result = execute(zz_meas, backend = simulator, shots=10000).result()
counts = result.get_counts(zz_meas)
plot_histogram(counts)
def measure_zz(given_circuit, num_shots = 10000):
zz_meas = measure_zz_circuit(given_circuit)
result = execute(zz_meas, backend = simulator, shots = num_shots).result()
counts = result.get_counts(zz_meas)
if '00' not in counts:
counts['00'] = 0
if '01' not in counts:
counts['01'] = 0
if '10' not in counts:
counts['10'] = 0
if '11' not in counts:
counts['11'] = 0
total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10']
zz = counts['00'] + counts['11'] - counts['01'] - counts['10']
zz = zz / total_counts
return zz
zz = measure_zz(hets_circuit)
print("<ZZ> =", str(zz))
def measure_zi(given_circuit, num_shots = 10000):
zz_meas = measure_zz_circuit(given_circuit)
result = execute(zz_meas, backend = simulator, shots = num_shots).result()
counts = result.get_counts(zz_meas)
if '00' not in counts:
counts['00'] = 0
if '01' not in counts:
counts['01'] = 0
if '10' not in counts:
counts['10'] = 0
if '11' not in counts:
counts['11'] = 0
total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10']
zi = counts['00'] - counts['11'] + counts['01'] - counts['10']
zi = zi / total_counts
return zi
def measure_iz(given_circuit, num_shots = 10000):
zz_meas = measure_zz_circuit(given_circuit)
result = execute(zz_meas, backend = simulator, shots = num_shots).result()
counts = result.get_counts(zz_meas)
if '00' not in counts:
counts['00'] = 0
if '01' not in counts:
counts['01'] = 0
if '10' not in counts:
counts['10'] = 0
if '11' not in counts:
counts['11'] = 0
total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10']
iz = counts['00'] - counts['11'] - counts['01'] + counts['10']
iz = iz / total_counts
return iz
zi = measure_zi(hets_circuit)
print("<ZI> =", str(zi))
iz = measure_iz(hets_circuit)
print("<IZ> =", str(iz))
def measure_xx_circuit(given_circuit):
xx_meas = make_copy(given_circuit)
### WRITE YOUR CODE BETWEEN THESE LINES - START
xx_meas.h(0)
xx_meas.h(1)
xx_meas.measure_all()
### WRITE YOUR CODE BETWEEN THESE LINES - END
return xx_meas
xx_meas = measure_xx_circuit(hets_circuit)
xx_meas.draw()
def measure_xx(given_circuit, num_shots = 10000):
xx_meas = measure_xx_circuit(given_circuit)
result = execute(xx_meas, backend = simulator, shots = num_shots).result()
counts = result.get_counts(xx_meas)
if '00' not in counts:
counts['00'] = 0
if '01' not in counts:
counts['01'] = 0
if '10' not in counts:
counts['10'] = 0
if '11' not in counts:
counts['11'] = 0
total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10']
xx = counts['00'] + counts['11'] - counts['01'] - counts['10']
xx = xx / total_counts
return xx
xx = measure_xx(hets_circuit)
print("<XX> =", str(xx))
def get_energy(given_circuit, num_shots = 10000):
zz = measure_zz(given_circuit, num_shots = num_shots)
iz = measure_iz(given_circuit, num_shots = num_shots)
zi = measure_zi(given_circuit, num_shots = num_shots)
xx = measure_xx(given_circuit, num_shots = num_shots)
energy = (-1.0523732)*1 + (0.39793742)*iz + (-0.3979374)*zi + (-0.0112801)*zz + (0.18093119)*xx
return energy
energy = get_energy(hets_circuit)
print("The energy of the trial state is", str(energy))
hets_circuit_plus = None
hets_circuit_minus = None
### WRITE YOUR CODE BETWEEN THESE LINES - START
hets_circuit_plus = prepare_hets_circuit(2, pi/2 + 0.1*pi/2, pi/2)
hets_circuit_minus = prepare_hets_circuit(2, pi/2 - 0.1*pi/2, pi/2)
### WRITE YOUR CODE BETWEEN THESE LINES - END
energy_plus = get_energy(hets_circuit_plus, num_shots=100000)
energy_minus = get_energy(hets_circuit_minus, num_shots=100000)
print(energy_plus, energy_minus)
name = 'Pon Rahul M'
email = 'ponrahul.21it@licet.ac.in'
### Do not change the lines below
from grading_tools import grade
grade(answer=measure_xx_circuit(hets_circuit), name=name, email=email, labid='lab9', exerciseid='ex1')
grade(answer=hets_circuit_plus, name=name, email=email, labid='lab9', exerciseid='ex2')
grade(answer=hets_circuit_minus, name=name, email=email, labid='lab9', exerciseid='ex3')
energy_plus_100, energy_plus_1000, energy_plus_10000 = 0, 0, 0
energy_minus_100, energy_minus_1000, energy_minus_10000 = 0, 0, 0
### WRITE YOUR CODE BETWEEN THESE LINES - START
energy_plus_100 = get_energy(hets_circuit_plus, num_shots = 100)
energy_minus_100 = get_energy(hets_circuit_minus, num_shots = 100)
energy_plus_1000 = get_energy(hets_circuit_plus, num_shots = 1000)
energy_minus_1000 = get_energy(hets_circuit_minus, num_shots = 1000)
energy_plus_10000 = get_energy(hets_circuit_plus, num_shots = 10000)
energy_minus_10000 = get_energy(hets_circuit_minus, num_shots = 10000)
### WRITE YOUR CODE BETWEEN THESE LINES - END
print(energy_plus_100, energy_minus_100, "difference = ", energy_minus_100 - energy_plus_100)
print(energy_plus_1000, energy_minus_1000, "difference = ", energy_minus_1000 - energy_plus_1000)
print(energy_plus_10000, energy_minus_10000, "difference = ", energy_minus_10000 - energy_plus_10000)
### WRITE YOUR CODE BETWEEN THESE LINES - START
I = np.array([
[1, 0],
[0, 1]
])
X = np.array([
[0, 1],
[1, 0]
])
Z = np.array([
[1, 0],
[0, -1]
])
h2_hamiltonian = (-1.0523732) * np.kron(I, I) + \
(0.39793742) * np.kron(I, Z) + \
(-0.3979374) * np.kron(Z, I) + \
(-0.0112801) * np.kron(Z, Z) + \
(0.18093119) * np.kron(X, X)
from numpy import linalg as LA
eigenvalues, eigenvectors = LA.eig(h2_hamiltonian)
for ii, eigenvalue in enumerate(eigenvalues):
print(f"Eigenvector {eigenvectors[:,ii]} has energy {eigenvalue}")
exact_eigenvector = eigenvectors[:,np.argmin(eigenvalues)]
exact_eigenvalue = np.min(eigenvalues)
print()
print("Minimum energy is", exact_eigenvalue)
### WRITE YOUR CODE BETWEEN THESE LINES - END
|
https://github.com/MonitSharma/Qiskit-Summer-School-and-Quantum-Challenges
|
MonitSharma
|
!pip install -U -r grading_tools/requirements.txt
from IPython.display import clear_output
clear_output()
import numpy as np; pi = np.pi
from qiskit import QuantumCircuit, Aer, execute
from qiskit.visualization import plot_histogram
from copy import deepcopy as make_copy
def prepare_hets_circuit(depth, angle1, angle2):
hets_circ = QuantumCircuit(depth)
hets_circ.ry(angle1, 0)
hets_circ.rz(angle1, 0)
hets_circ.ry(angle1, 1)
hets_circ.rz(angle1, 1)
for ii in range(depth):
hets_circ.cx(0,1)
hets_circ.ry(angle2,0)
hets_circ.rz(angle2,0)
hets_circ.ry(angle2,1)
hets_circ.rz(angle2,1)
return hets_circ
hets_circuit = prepare_hets_circuit(2, pi/2, pi/2)
hets_circuit.draw()
def measure_zz_circuit(given_circuit):
zz_meas = make_copy(given_circuit)
zz_meas.measure_all()
return zz_meas
zz_meas = measure_zz_circuit(hets_circuit)
zz_meas.draw()
simulator = Aer.get_backend('qasm_simulator')
result = execute(zz_meas, backend = simulator, shots=10000).result()
counts = result.get_counts(zz_meas)
plot_histogram(counts)
def measure_zz(given_circuit, num_shots = 10000):
zz_meas = measure_zz_circuit(given_circuit)
result = execute(zz_meas, backend = simulator, shots = num_shots).result()
counts = result.get_counts(zz_meas)
if '00' not in counts:
counts['00'] = 0
if '01' not in counts:
counts['01'] = 0
if '10' not in counts:
counts['10'] = 0
if '11' not in counts:
counts['11'] = 0
total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10']
zz = counts['00'] + counts['11'] - counts['01'] - counts['10']
zz = zz / total_counts
return zz
zz = measure_zz(hets_circuit)
print("<ZZ> =", str(zz))
def measure_zi(given_circuit, num_shots = 10000):
zz_meas = measure_zz_circuit(given_circuit)
result = execute(zz_meas, backend = simulator, shots = num_shots).result()
counts = result.get_counts(zz_meas)
if '00' not in counts:
counts['00'] = 0
if '01' not in counts:
counts['01'] = 0
if '10' not in counts:
counts['10'] = 0
if '11' not in counts:
counts['11'] = 0
total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10']
zi = counts['00'] - counts['11'] + counts['01'] - counts['10']
zi = zi / total_counts
return zi
def measure_iz(given_circuit, num_shots = 10000):
zz_meas = measure_zz_circuit(given_circuit)
result = execute(zz_meas, backend = simulator, shots = num_shots).result()
counts = result.get_counts(zz_meas)
if '00' not in counts:
counts['00'] = 0
if '01' not in counts:
counts['01'] = 0
if '10' not in counts:
counts['10'] = 0
if '11' not in counts:
counts['11'] = 0
total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10']
iz = counts['00'] - counts['11'] - counts['01'] + counts['10']
iz = iz / total_counts
return iz
zi = measure_zi(hets_circuit)
print("<ZI> =", str(zi))
iz = measure_iz(hets_circuit)
print("<IZ> =", str(iz))
def measure_xx_circuit(given_circuit):
xx_meas = make_copy(given_circuit)
### WRITE YOUR CODE BETWEEN THESE LINES - START
xx_meas.h(0)
xx_meas.h(1)
xx_meas.measure_all()
### WRITE YOUR CODE BETWEEN THESE LINES - END
return xx_meas
xx_meas = measure_xx_circuit(hets_circuit)
xx_meas.draw()
def measure_xx(given_circuit, num_shots = 10000):
xx_meas = measure_xx_circuit(given_circuit)
result = execute(xx_meas, backend = simulator, shots = num_shots).result()
counts = result.get_counts(xx_meas)
if '00' not in counts:
counts['00'] = 0
if '01' not in counts:
counts['01'] = 0
if '10' not in counts:
counts['10'] = 0
if '11' not in counts:
counts['11'] = 0
total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10']
xx = counts['00'] + counts['11'] - counts['01'] - counts['10']
xx = xx / total_counts
return xx
xx = measure_xx(hets_circuit)
print("<XX> =", str(xx))
def get_energy(given_circuit, num_shots = 10000):
zz = measure_zz(given_circuit, num_shots = num_shots)
iz = measure_iz(given_circuit, num_shots = num_shots)
zi = measure_zi(given_circuit, num_shots = num_shots)
xx = measure_xx(given_circuit, num_shots = num_shots)
energy = (-1.0523732)*1 + (0.39793742)*iz + (-0.3979374)*zi + (-0.0112801)*zz + (0.18093119)*xx
return energy
energy = get_energy(hets_circuit)
print("The energy of the trial state is", str(energy))
hets_circuit_plus = None
hets_circuit_minus = None
### WRITE YOUR CODE BETWEEN THESE LINES - START
hets_circuit_plus = prepare_hets_circuit(2, pi/2 + 0.1*pi/2, pi/2)
hets_circuit_minus = prepare_hets_circuit(2, pi/2 - 0.1*pi/2, pi/2)
### WRITE YOUR CODE BETWEEN THESE LINES - END
energy_plus = get_energy(hets_circuit_plus, num_shots=100000)
energy_minus = get_energy(hets_circuit_minus, num_shots=100000)
print(energy_plus, energy_minus)
name = 'Pon Rahul M'
email = 'ponrahul.21it@licet.ac.in'
### Do not change the lines below
from grading_tools import grade
grade(answer=measure_xx_circuit(hets_circuit), name=name, email=email, labid='lab9', exerciseid='ex1')
grade(answer=hets_circuit_plus, name=name, email=email, labid='lab9', exerciseid='ex2')
grade(answer=hets_circuit_minus, name=name, email=email, labid='lab9', exerciseid='ex3')
energy_plus_100, energy_plus_1000, energy_plus_10000 = 0, 0, 0
energy_minus_100, energy_minus_1000, energy_minus_10000 = 0, 0, 0
### WRITE YOUR CODE BETWEEN THESE LINES - START
energy_plus_100 = get_energy(hets_circuit_plus, num_shots = 100)
energy_minus_100 = get_energy(hets_circuit_minus, num_shots = 100)
energy_plus_1000 = get_energy(hets_circuit_plus, num_shots = 1000)
energy_minus_1000 = get_energy(hets_circuit_minus, num_shots = 1000)
energy_plus_10000 = get_energy(hets_circuit_plus, num_shots = 10000)
energy_minus_10000 = get_energy(hets_circuit_minus, num_shots = 10000)
### WRITE YOUR CODE BETWEEN THESE LINES - END
print(energy_plus_100, energy_minus_100, "difference = ", energy_minus_100 - energy_plus_100)
print(energy_plus_1000, energy_minus_1000, "difference = ", energy_minus_1000 - energy_plus_1000)
print(energy_plus_10000, energy_minus_10000, "difference = ", energy_minus_10000 - energy_plus_10000)
### WRITE YOUR CODE BETWEEN THESE LINES - START
I = np.array([
[1, 0],
[0, 1]
])
X = np.array([
[0, 1],
[1, 0]
])
Z = np.array([
[1, 0],
[0, -1]
])
h2_hamiltonian = (-1.0523732) * np.kron(I, I) + \
(0.39793742) * np.kron(I, Z) + \
(-0.3979374) * np.kron(Z, I) + \
(-0.0112801) * np.kron(Z, Z) + \
(0.18093119) * np.kron(X, X)
from numpy import linalg as LA
eigenvalues, eigenvectors = LA.eig(h2_hamiltonian)
for ii, eigenvalue in enumerate(eigenvalues):
print(f"Eigenvector {eigenvectors[:,ii]} has energy {eigenvalue}")
exact_eigenvector = eigenvectors[:,np.argmin(eigenvalues)]
exact_eigenvalue = np.min(eigenvalues)
print()
print("Minimum energy is", exact_eigenvalue)
### WRITE YOUR CODE BETWEEN THESE LINES - END
|
https://github.com/MonitSharma/Qiskit-Summer-School-and-Quantum-Challenges
|
MonitSharma
|
!pip install -U -r grading_tools/requirements.txt
from IPython.display import clear_output
clear_output()
import numpy as np; pi = np.pi
from qiskit import QuantumCircuit, Aer, execute
from qiskit.visualization import plot_histogram
from copy import deepcopy as make_copy
def prepare_hets_circuit(depth, angle1, angle2):
hets_circ = QuantumCircuit(depth)
hets_circ.ry(angle1, 0)
hets_circ.rz(angle1, 0)
hets_circ.ry(angle1, 1)
hets_circ.rz(angle1, 1)
for ii in range(depth):
hets_circ.cx(0,1)
hets_circ.ry(angle2,0)
hets_circ.rz(angle2,0)
hets_circ.ry(angle2,1)
hets_circ.rz(angle2,1)
return hets_circ
hets_circuit = prepare_hets_circuit(2, pi/2, pi/2)
hets_circuit.draw()
def measure_zz_circuit(given_circuit):
zz_meas = make_copy(given_circuit)
zz_meas.measure_all()
return zz_meas
zz_meas = measure_zz_circuit(hets_circuit)
zz_meas.draw()
simulator = Aer.get_backend('qasm_simulator')
result = execute(zz_meas, backend = simulator, shots=10000).result()
counts = result.get_counts(zz_meas)
plot_histogram(counts)
def measure_zz(given_circuit, num_shots = 10000):
zz_meas = measure_zz_circuit(given_circuit)
result = execute(zz_meas, backend = simulator, shots = num_shots).result()
counts = result.get_counts(zz_meas)
if '00' not in counts:
counts['00'] = 0
if '01' not in counts:
counts['01'] = 0
if '10' not in counts:
counts['10'] = 0
if '11' not in counts:
counts['11'] = 0
total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10']
zz = counts['00'] + counts['11'] - counts['01'] - counts['10']
zz = zz / total_counts
return zz
zz = measure_zz(hets_circuit)
print("<ZZ> =", str(zz))
def measure_zi(given_circuit, num_shots = 10000):
zz_meas = measure_zz_circuit(given_circuit)
result = execute(zz_meas, backend = simulator, shots = num_shots).result()
counts = result.get_counts(zz_meas)
if '00' not in counts:
counts['00'] = 0
if '01' not in counts:
counts['01'] = 0
if '10' not in counts:
counts['10'] = 0
if '11' not in counts:
counts['11'] = 0
total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10']
zi = counts['00'] - counts['11'] + counts['01'] - counts['10']
zi = zi / total_counts
return zi
def measure_iz(given_circuit, num_shots = 10000):
zz_meas = measure_zz_circuit(given_circuit)
result = execute(zz_meas, backend = simulator, shots = num_shots).result()
counts = result.get_counts(zz_meas)
if '00' not in counts:
counts['00'] = 0
if '01' not in counts:
counts['01'] = 0
if '10' not in counts:
counts['10'] = 0
if '11' not in counts:
counts['11'] = 0
total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10']
iz = counts['00'] - counts['11'] - counts['01'] + counts['10']
iz = iz / total_counts
return iz
zi = measure_zi(hets_circuit)
print("<ZI> =", str(zi))
iz = measure_iz(hets_circuit)
print("<IZ> =", str(iz))
def measure_xx_circuit(given_circuit):
xx_meas = make_copy(given_circuit)
### WRITE YOUR CODE BETWEEN THESE LINES - START
xx_meas.h(0)
xx_meas.h(1)
xx_meas.measure_all()
### WRITE YOUR CODE BETWEEN THESE LINES - END
return xx_meas
xx_meas = measure_xx_circuit(hets_circuit)
xx_meas.draw()
def measure_xx(given_circuit, num_shots = 10000):
xx_meas = measure_xx_circuit(given_circuit)
result = execute(xx_meas, backend = simulator, shots = num_shots).result()
counts = result.get_counts(xx_meas)
if '00' not in counts:
counts['00'] = 0
if '01' not in counts:
counts['01'] = 0
if '10' not in counts:
counts['10'] = 0
if '11' not in counts:
counts['11'] = 0
total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10']
xx = counts['00'] + counts['11'] - counts['01'] - counts['10']
xx = xx / total_counts
return xx
xx = measure_xx(hets_circuit)
print("<XX> =", str(xx))
def get_energy(given_circuit, num_shots = 10000):
zz = measure_zz(given_circuit, num_shots = num_shots)
iz = measure_iz(given_circuit, num_shots = num_shots)
zi = measure_zi(given_circuit, num_shots = num_shots)
xx = measure_xx(given_circuit, num_shots = num_shots)
energy = (-1.0523732)*1 + (0.39793742)*iz + (-0.3979374)*zi + (-0.0112801)*zz + (0.18093119)*xx
return energy
energy = get_energy(hets_circuit)
print("The energy of the trial state is", str(energy))
hets_circuit_plus = None
hets_circuit_minus = None
### WRITE YOUR CODE BETWEEN THESE LINES - START
hets_circuit_plus = prepare_hets_circuit(2, pi/2 + 0.1*pi/2, pi/2)
hets_circuit_minus = prepare_hets_circuit(2, pi/2 - 0.1*pi/2, pi/2)
### WRITE YOUR CODE BETWEEN THESE LINES - END
energy_plus = get_energy(hets_circuit_plus, num_shots=100000)
energy_minus = get_energy(hets_circuit_minus, num_shots=100000)
print(energy_plus, energy_minus)
name = 'Pon Rahul M'
email = 'ponrahul.21it@licet.ac.in'
### Do not change the lines below
from grading_tools import grade
grade(answer=measure_xx_circuit(hets_circuit), name=name, email=email, labid='lab9', exerciseid='ex1')
grade(answer=hets_circuit_plus, name=name, email=email, labid='lab9', exerciseid='ex2')
grade(answer=hets_circuit_minus, name=name, email=email, labid='lab9', exerciseid='ex3')
energy_plus_100, energy_plus_1000, energy_plus_10000 = 0, 0, 0
energy_minus_100, energy_minus_1000, energy_minus_10000 = 0, 0, 0
### WRITE YOUR CODE BETWEEN THESE LINES - START
energy_plus_100 = get_energy(hets_circuit_plus, num_shots = 100)
energy_minus_100 = get_energy(hets_circuit_minus, num_shots = 100)
energy_plus_1000 = get_energy(hets_circuit_plus, num_shots = 1000)
energy_minus_1000 = get_energy(hets_circuit_minus, num_shots = 1000)
energy_plus_10000 = get_energy(hets_circuit_plus, num_shots = 10000)
energy_minus_10000 = get_energy(hets_circuit_minus, num_shots = 10000)
### WRITE YOUR CODE BETWEEN THESE LINES - END
print(energy_plus_100, energy_minus_100, "difference = ", energy_minus_100 - energy_plus_100)
print(energy_plus_1000, energy_minus_1000, "difference = ", energy_minus_1000 - energy_plus_1000)
print(energy_plus_10000, energy_minus_10000, "difference = ", energy_minus_10000 - energy_plus_10000)
### WRITE YOUR CODE BETWEEN THESE LINES - START
I = np.array([
[1, 0],
[0, 1]
])
X = np.array([
[0, 1],
[1, 0]
])
Z = np.array([
[1, 0],
[0, -1]
])
h2_hamiltonian = (-1.0523732) * np.kron(I, I) + \
(0.39793742) * np.kron(I, Z) + \
(-0.3979374) * np.kron(Z, I) + \
(-0.0112801) * np.kron(Z, Z) + \
(0.18093119) * np.kron(X, X)
from numpy import linalg as LA
eigenvalues, eigenvectors = LA.eig(h2_hamiltonian)
for ii, eigenvalue in enumerate(eigenvalues):
print(f"Eigenvector {eigenvectors[:,ii]} has energy {eigenvalue}")
exact_eigenvector = eigenvectors[:,np.argmin(eigenvalues)]
exact_eigenvalue = np.min(eigenvalues)
print()
print("Minimum energy is", exact_eigenvalue)
### WRITE YOUR CODE BETWEEN THESE LINES - END
|
https://github.com/MonitSharma/Qiskit-Summer-School-and-Quantum-Challenges
|
MonitSharma
|
!pip install -U -r grading_tools/requirements.txt
from IPython.display import clear_output
clear_output()
import numpy as np; pi = np.pi
from qiskit import QuantumCircuit, Aer, execute
from qiskit.visualization import plot_histogram
from copy import deepcopy as make_copy
def prepare_hets_circuit(depth, angle1, angle2):
hets_circ = QuantumCircuit(depth)
hets_circ.ry(angle1, 0)
hets_circ.rz(angle1, 0)
hets_circ.ry(angle1, 1)
hets_circ.rz(angle1, 1)
for ii in range(depth):
hets_circ.cx(0,1)
hets_circ.ry(angle2,0)
hets_circ.rz(angle2,0)
hets_circ.ry(angle2,1)
hets_circ.rz(angle2,1)
return hets_circ
hets_circuit = prepare_hets_circuit(2, pi/2, pi/2)
hets_circuit.draw()
def measure_zz_circuit(given_circuit):
zz_meas = make_copy(given_circuit)
zz_meas.measure_all()
return zz_meas
zz_meas = measure_zz_circuit(hets_circuit)
zz_meas.draw()
simulator = Aer.get_backend('qasm_simulator')
result = execute(zz_meas, backend = simulator, shots=10000).result()
counts = result.get_counts(zz_meas)
plot_histogram(counts)
def measure_zz(given_circuit, num_shots = 10000):
zz_meas = measure_zz_circuit(given_circuit)
result = execute(zz_meas, backend = simulator, shots = num_shots).result()
counts = result.get_counts(zz_meas)
if '00' not in counts:
counts['00'] = 0
if '01' not in counts:
counts['01'] = 0
if '10' not in counts:
counts['10'] = 0
if '11' not in counts:
counts['11'] = 0
total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10']
zz = counts['00'] + counts['11'] - counts['01'] - counts['10']
zz = zz / total_counts
return zz
zz = measure_zz(hets_circuit)
print("<ZZ> =", str(zz))
def measure_zi(given_circuit, num_shots = 10000):
zz_meas = measure_zz_circuit(given_circuit)
result = execute(zz_meas, backend = simulator, shots = num_shots).result()
counts = result.get_counts(zz_meas)
if '00' not in counts:
counts['00'] = 0
if '01' not in counts:
counts['01'] = 0
if '10' not in counts:
counts['10'] = 0
if '11' not in counts:
counts['11'] = 0
total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10']
zi = counts['00'] - counts['11'] + counts['01'] - counts['10']
zi = zi / total_counts
return zi
def measure_iz(given_circuit, num_shots = 10000):
zz_meas = measure_zz_circuit(given_circuit)
result = execute(zz_meas, backend = simulator, shots = num_shots).result()
counts = result.get_counts(zz_meas)
if '00' not in counts:
counts['00'] = 0
if '01' not in counts:
counts['01'] = 0
if '10' not in counts:
counts['10'] = 0
if '11' not in counts:
counts['11'] = 0
total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10']
iz = counts['00'] - counts['11'] - counts['01'] + counts['10']
iz = iz / total_counts
return iz
zi = measure_zi(hets_circuit)
print("<ZI> =", str(zi))
iz = measure_iz(hets_circuit)
print("<IZ> =", str(iz))
def measure_xx_circuit(given_circuit):
xx_meas = make_copy(given_circuit)
### WRITE YOUR CODE BETWEEN THESE LINES - START
xx_meas.h(0)
xx_meas.h(1)
xx_meas.measure_all()
### WRITE YOUR CODE BETWEEN THESE LINES - END
return xx_meas
xx_meas = measure_xx_circuit(hets_circuit)
xx_meas.draw()
def measure_xx(given_circuit, num_shots = 10000):
xx_meas = measure_xx_circuit(given_circuit)
result = execute(xx_meas, backend = simulator, shots = num_shots).result()
counts = result.get_counts(xx_meas)
if '00' not in counts:
counts['00'] = 0
if '01' not in counts:
counts['01'] = 0
if '10' not in counts:
counts['10'] = 0
if '11' not in counts:
counts['11'] = 0
total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10']
xx = counts['00'] + counts['11'] - counts['01'] - counts['10']
xx = xx / total_counts
return xx
xx = measure_xx(hets_circuit)
print("<XX> =", str(xx))
def get_energy(given_circuit, num_shots = 10000):
zz = measure_zz(given_circuit, num_shots = num_shots)
iz = measure_iz(given_circuit, num_shots = num_shots)
zi = measure_zi(given_circuit, num_shots = num_shots)
xx = measure_xx(given_circuit, num_shots = num_shots)
energy = (-1.0523732)*1 + (0.39793742)*iz + (-0.3979374)*zi + (-0.0112801)*zz + (0.18093119)*xx
return energy
energy = get_energy(hets_circuit)
print("The energy of the trial state is", str(energy))
hets_circuit_plus = None
hets_circuit_minus = None
### WRITE YOUR CODE BETWEEN THESE LINES - START
hets_circuit_plus = prepare_hets_circuit(2, pi/2 + 0.1*pi/2, pi/2)
hets_circuit_minus = prepare_hets_circuit(2, pi/2 - 0.1*pi/2, pi/2)
### WRITE YOUR CODE BETWEEN THESE LINES - END
energy_plus = get_energy(hets_circuit_plus, num_shots=100000)
energy_minus = get_energy(hets_circuit_minus, num_shots=100000)
print(energy_plus, energy_minus)
name = 'Pon Rahul M'
email = 'ponrahul.21it@licet.ac.in'
### Do not change the lines below
from grading_tools import grade
grade(answer=measure_xx_circuit(hets_circuit), name=name, email=email, labid='lab9', exerciseid='ex1')
grade(answer=hets_circuit_plus, name=name, email=email, labid='lab9', exerciseid='ex2')
grade(answer=hets_circuit_minus, name=name, email=email, labid='lab9', exerciseid='ex3')
energy_plus_100, energy_plus_1000, energy_plus_10000 = 0, 0, 0
energy_minus_100, energy_minus_1000, energy_minus_10000 = 0, 0, 0
### WRITE YOUR CODE BETWEEN THESE LINES - START
energy_plus_100 = get_energy(hets_circuit_plus, num_shots = 100)
energy_minus_100 = get_energy(hets_circuit_minus, num_shots = 100)
energy_plus_1000 = get_energy(hets_circuit_plus, num_shots = 1000)
energy_minus_1000 = get_energy(hets_circuit_minus, num_shots = 1000)
energy_plus_10000 = get_energy(hets_circuit_plus, num_shots = 10000)
energy_minus_10000 = get_energy(hets_circuit_minus, num_shots = 10000)
### WRITE YOUR CODE BETWEEN THESE LINES - END
print(energy_plus_100, energy_minus_100, "difference = ", energy_minus_100 - energy_plus_100)
print(energy_plus_1000, energy_minus_1000, "difference = ", energy_minus_1000 - energy_plus_1000)
print(energy_plus_10000, energy_minus_10000, "difference = ", energy_minus_10000 - energy_plus_10000)
### WRITE YOUR CODE BETWEEN THESE LINES - START
I = np.array([
[1, 0],
[0, 1]
])
X = np.array([
[0, 1],
[1, 0]
])
Z = np.array([
[1, 0],
[0, -1]
])
h2_hamiltonian = (-1.0523732) * np.kron(I, I) + \
(0.39793742) * np.kron(I, Z) + \
(-0.3979374) * np.kron(Z, I) + \
(-0.0112801) * np.kron(Z, Z) + \
(0.18093119) * np.kron(X, X)
from numpy import linalg as LA
eigenvalues, eigenvectors = LA.eig(h2_hamiltonian)
for ii, eigenvalue in enumerate(eigenvalues):
print(f"Eigenvector {eigenvectors[:,ii]} has energy {eigenvalue}")
exact_eigenvector = eigenvectors[:,np.argmin(eigenvalues)]
exact_eigenvalue = np.min(eigenvalues)
print()
print("Minimum energy is", exact_eigenvalue)
### WRITE YOUR CODE BETWEEN THESE LINES - END
|
https://github.com/MonitSharma/Qiskit-Summer-School-and-Quantum-Challenges
|
MonitSharma
|
from qiskit.quantum_info import Statevector
from qiskit.visualization import plot_bloch_multivector
excited = Statevector.from_int(1, 2)
plot_bloch_multivector(excited.data)
from qiskit.tools.jupyter import *
from qiskit import IBMQ
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q', group='open', project='main')
backend = provider.get_backend('ibmq_armonk')
backend_config = backend.configuration()
assert backend_config.open_pulse, "Backend doesn't support Pulse"
dt = backend_config.dt
print(f"Sampling time: {dt*1e9} ns")
backend_defaults = backend.defaults()
import numpy as np
# unit conversion factors -> all backend properties returned in SI (Hz, sec, etc)
GHz = 1.0e9 # Gigahertz
MHz = 1.0e6 # Megahertz
us = 1.0e-6 # Microseconds
ns = 1.0e-9 # Nanoseconds
# We will find the qubit frequency for the following qubit.
qubit = 0
# The Rabi sweep will be at the given qubit frequency.
center_frequency_Hz = backend_defaults.qubit_freq_est[qubit] # The default frequency is given in Hz
# warning: this will change in a future release
print(f"Qubit {qubit} has an estimated frequency of {center_frequency_Hz / GHz} GHz.")
from qiskit import pulse, assemble # This is where we access all of our Pulse features!
from qiskit.pulse import Play
from qiskit.pulse import pulse_lib # This Pulse module helps us build sampled pulses for common pulse shapes
### Collect the necessary channels
drive_chan = pulse.DriveChannel(qubit)
meas_chan = pulse.MeasureChannel(qubit)
acq_chan = pulse.AcquireChannel(qubit)
inst_sched_map = backend_defaults.instruction_schedule_map
measure = inst_sched_map.get('measure', qubits=[0])
# Rabi experiment parameters
# Drive amplitude values to iterate over: 50 amplitudes evenly spaced from 0 to 0.75
num_rabi_points = 50
drive_amp_min = 0
drive_amp_max = 0.75
drive_amps = np.linspace(drive_amp_min, drive_amp_max, num_rabi_points)
# drive waveforms mush be in units of 16
drive_sigma = 80 # in dt
drive_samples = 8*drive_sigma # in dt
# Build the Rabi experiments:
# A drive pulse at the qubit frequency, followed by a measurement,
# where we vary the drive amplitude each time.
rabi_schedules = []
for drive_amp in drive_amps:
rabi_pulse = pulse_lib.gaussian(duration=drive_samples, amp=drive_amp,
sigma=drive_sigma, name=f"Rabi drive amplitude = {drive_amp}")
this_schedule = pulse.Schedule(name=f"Rabi drive amplitude = {drive_amp}")
this_schedule += Play(rabi_pulse, drive_chan)
# The left shift `<<` is special syntax meaning to shift the start time of the schedule by some duration
this_schedule += measure << this_schedule.duration
rabi_schedules.append(this_schedule)
rabi_schedules[-1].draw(label=True, scaling=1.0)
# assemble the schedules into a Qobj
num_shots_per_point = 1024
rabi_experiment_program = assemble(rabi_schedules,
backend=backend,
meas_level=1,
meas_return='avg',
shots=num_shots_per_point,
schedule_los=[{drive_chan: center_frequency_Hz}]
* num_rabi_points)
# RUN the job on a real device
#job = backend.run(rabi_experiment_program)
#print(job.job_id())
#from qiskit.tools.monitor import job_monitor
#job_monitor(job)
# OR retreive result from previous run
job = backend.retrieve_job("5ef3bf17dc3044001186c011")
rabi_results = job.result()
import matplotlib.pyplot as plt
plt.style.use('dark_background')
scale_factor = 1e-14
# center data around 0
def baseline_remove(values):
return np.array(values) - np.mean(values)
rabi_values = []
for i in range(num_rabi_points):
# Get the results for `qubit` from the ith experiment
rabi_values.append(rabi_results.get_memory(i)[qubit]*scale_factor)
rabi_values = np.real(baseline_remove(rabi_values))
plt.xlabel("Drive amp [a.u.]")
plt.ylabel("Measured signal [a.u.]")
plt.scatter(drive_amps, rabi_values, color='white') # plot real part of Rabi values
plt.show()
from scipy.optimize import curve_fit
def fit_function(x_values, y_values, function, init_params):
fitparams, conv = curve_fit(function, x_values, y_values, init_params)
y_fit = function(x_values, *fitparams)
return fitparams, y_fit
fit_params, y_fit = fit_function(drive_amps,
rabi_values,
lambda x, A, B, drive_period, phi: (A*np.cos(2*np.pi*x/drive_period - phi) + B),
[10, 0.1, 0.6, 0])
plt.scatter(drive_amps, rabi_values, color='white')
plt.plot(drive_amps, y_fit, color='red')
drive_period = fit_params[2] # get period of rabi oscillation
plt.axvline(drive_period/2, color='red', linestyle='--')
plt.axvline(drive_period, color='red', linestyle='--')
plt.annotate("", xy=(drive_period, 0), xytext=(drive_period/2,0), arrowprops=dict(arrowstyle="<->", color='red'))
plt.xlabel("Drive amp [a.u.]", fontsize=15)
plt.ylabel("Measured signal [a.u.]", fontsize=15)
plt.show()
pi_amp = abs(drive_period / 2)
print(f"Pi Amplitude = {pi_amp}")
# Drive parameters
# The drive amplitude for pi/2 is simply half the amplitude of the pi pulse
drive_amp = pi_amp / 2
# x_90 is a concise way to say pi_over_2; i.e., an X rotation of 90 degrees
x90_pulse = pulse_lib.gaussian(duration=drive_samples,
amp=drive_amp,
sigma=drive_sigma,
name='x90_pulse')
# Ramsey experiment parameters
time_max_us = 1.8
time_step_us = 0.025
times_us = np.arange(0.1, time_max_us, time_step_us)
# Convert to units of dt
delay_times_dt = times_us * us / dt
# create schedules for Ramsey experiment
ramsey_schedules = []
for delay in delay_times_dt:
this_schedule = pulse.Schedule(name=f"Ramsey delay = {delay * dt / us} us")
this_schedule += Play(x90_pulse, drive_chan)
this_schedule += Play(x90_pulse, drive_chan) << this_schedule.duration + int(delay)
this_schedule += measure << this_schedule.duration
ramsey_schedules.append(this_schedule)
ramsey_schedules[-1].draw(label=True, scaling=1.0)
# Execution settings
num_shots = 256
detuning_MHz = 2
ramsey_frequency = round(center_frequency_Hz + detuning_MHz * MHz, 6) # need ramsey freq in Hz
ramsey_program = assemble(ramsey_schedules,
backend=backend,
meas_level=1,
meas_return='avg',
shots=num_shots,
schedule_los=[{drive_chan: ramsey_frequency}]*len(ramsey_schedules)
)
# RUN the job on a real device
#job = backend.run(ramsey_experiment_program)
#print(job.job_id())
#from qiskit.tools.monitor import job_monitor
#job_monitor(job)
# OR retreive job from previous run
job = backend.retrieve_job('5ef3ed3a84b1b70012374317')
ramsey_results = job.result()
ramsey_values = []
for i in range(len(times_us)):
ramsey_values.append(ramsey_results.get_memory(i)[qubit]*scale_factor)
fit_params, y_fit = fit_function(times_us, np.real(ramsey_values),
lambda x, A, del_f_MHz, C, B: (
A * np.cos(2*np.pi*del_f_MHz*x - C) + B
),
[5, 1./0.4, 0, 0.25]
)
# Off-resonance component
_, del_f_MHz, _, _, = fit_params # freq is MHz since times in us
plt.scatter(times_us, np.real(ramsey_values), color='white')
plt.plot(times_us, y_fit, color='red', label=f"df = {del_f_MHz:.2f} MHz")
plt.xlim(0, np.max(times_us))
plt.xlabel('Delay between X90 pulses [$\mu$s]', fontsize=15)
plt.ylabel('Measured Signal [a.u.]', fontsize=15)
plt.title('Ramsey Experiment', fontsize=15)
plt.legend()
plt.show()
|
https://github.com/MonitSharma/Qiskit-Summer-School-and-Quantum-Challenges
|
MonitSharma
|
!pip install -U -r grading_tools/requirements.txt
from IPython.display import clear_output
clear_output()
# our backend is the Pulse Simulator
from resources import helper
from qiskit.providers.aer import PulseSimulator
backend_sim = PulseSimulator()
# sample duration for pulse instructions
dt = 1e-9
# create the model
duffing_model = helper.get_transmon(dt)
# get qubit frequency from Duffing model
qubit_lo_freq = duffing_model.hamiltonian.get_qubit_lo_from_drift()
import numpy as np
# visualization tools
import matplotlib.pyplot as plt
plt.style.use('dark_background')
# unit conversion factors -> all backend properties returned in SI (Hz, sec, etc)
GHz = 1.0e9 # Gigahertz
MHz = 1.0e6 # Megahertz
kHz = 1.0e3 # kilohertz
us = 1.0e-6 # microseconds
ns = 1.0e-9 # nanoseconds
from qiskit import pulse
from qiskit.pulse import Play, Acquire
from qiskit.pulse.pulse_lib import GaussianSquare
# qubit to be used throughout the notebook
qubit = 0
### Collect the necessary channels
drive_chan = pulse.DriveChannel(qubit)
meas_chan = pulse.MeasureChannel(qubit)
acq_chan = pulse.AcquireChannel(qubit)
# Construct a measurement schedule and add it to an InstructionScheduleMap
meas_samples = 1200
meas_pulse = GaussianSquare(duration=meas_samples, amp=0.025, sigma=4, width=1150)
measure_sched = Play(meas_pulse, meas_chan) | Acquire(meas_samples, acq_chan, pulse.MemorySlot(qubit))
inst_map = pulse.InstructionScheduleMap()
inst_map.add('measure', [qubit], measure_sched)
# save the measurement/acquire pulse for later
measure = inst_map.get('measure', qubits=[qubit])
from qiskit.pulse import pulse_lib
# the same spect pulse used in every schedule
drive_amp = 0.9
drive_sigma = 16
drive_duration = 128
spec_pulse = pulse_lib.gaussian(duration=drive_duration, amp=drive_amp,
sigma=drive_sigma, name=f"Spec drive amplitude = {drive_amp}")
# Construct an np array of the frequencies for our experiment
spec_freqs_GHz = np.arange(5.0, 5.2, 0.005)
# Create the base schedule
# Start with drive pulse acting on the drive channel
spec_schedules = []
for freq in spec_freqs_GHz:
sb_spec_pulse = helper.apply_sideband(spec_pulse, qubit_lo_freq[0]-freq*GHz, dt)
spec_schedule = pulse.Schedule(name='SB Frequency = {}'.format(freq))
spec_schedule += Play(sb_spec_pulse, drive_chan)
# The left shift `<<` is special syntax meaning to shift the start time of the schedule by some duration
spec_schedule += measure << spec_schedule.duration
spec_schedules.append(spec_schedule)
spec_schedules[0].draw()
from qiskit import assemble
# assemble the schedules into a Qobj
spec01_qobj = assemble(**helper.get_params('spec01', globals()))
# run the simulation
spec01_result = backend_sim.run(spec01_qobj, duffing_model).result()
# retrieve the data from the experiment
spec01_values = helper.get_values_from_result(spec01_result, qubit)
fit_params, y_fit = helper.fit_lorentzian(spec_freqs_GHz, spec01_values, [5, 5, 1, 0])
f01 = fit_params[1]
plt.scatter(spec_freqs_GHz, np.real(spec01_values), color='white') # plot real part of sweep values
plt.plot(spec_freqs_GHz, y_fit, color='red')
plt.xlim([min(spec_freqs_GHz), max(spec_freqs_GHz)])
plt.xlabel("Frequency [GHz]")
plt.ylabel("Measured Signal [a.u.]")
plt.show()
print("01 Spectroscopy yields %f GHz"%f01)
x180_amp = 0.629070 #from lab 6 Rabi experiment
x_pulse = pulse_lib.gaussian(duration=drive_duration,
amp=x180_amp,
sigma=drive_sigma,
name='x_pulse')
anharmonicity_guess_GHz = -0.3
def build_spec12_pulse_schedule(freq):
sb12_spec_pulse = helper.apply_sideband(spec_pulse, (freq + anharmonicity_guess_GHz)*GHz, dt)
### create a 12 spectroscopy pulse schedule spec12_schedule (already done)
### play an x pulse on the drive channel
### play sidebanded spec pulse on the drive channel
### add measurement pulse to schedule
spec12_schedule = pulse.Schedule()
### WRITE YOUR CODE BETWEEN THESE LINES - START
spec12_schedule += Play(x_pulse, drive_chan)
spec12_schedule += Play(sb12_spec_pulse, drive_chan)
spec12_schedule += measure << spec12_schedule.duration
### WRITE YOUR CODE BETWEEN THESE LINES - STOP
return spec12_schedule
sb_freqs_GHz = np.arange(-.1, .1, 0.005) # sweep +/- 100 MHz around guess
# now vary the sideband frequency for each spec pulse
spec_schedules = []
for freq in sb_freqs_GHz:
spec_schedules.append(build_spec12_pulse_schedule(freq))
spec_schedules[0].draw()
# assemble the schedules into a Qobj
spec12_qobj = assemble(**helper.get_params('spec12', globals()))
answer1 = spec12_qobj
# run the simulation
spec12_result = backend_sim.run(spec12_qobj, duffing_model).result()
# retrieve the data from the experiment
spec12_values = helper.get_values_from_result(spec12_result, qubit)
anharm_offset = qubit_lo_freq[0]/GHz + anharmonicity_guess_GHz
fit_params, y_fit = helper.fit_lorentzian(anharm_offset + sb_freqs_GHz, spec12_values, [5, 4.5, .1, 3])
f12 = fit_params[1]
plt.scatter(anharm_offset + sb_freqs_GHz, np.real(spec12_values), color='white') # plot real part of sweep values
plt.plot(anharm_offset + sb_freqs_GHz, y_fit, color='red')
plt.xlim([anharm_offset + min(sb_freqs_GHz), anharm_offset + max(sb_freqs_GHz)])
plt.xlabel("Frequency [GHz]")
plt.ylabel("Measured Signal [a.u.]")
plt.show()
print("12 Spectroscopy yields %f GHz"%f12)
print("Measured transmon anharmonicity is %f MHz"%((f12-f01)*GHz/MHz))
from IPython.display import display, Javascript;display(Javascript('IPython.notebook.save_checkpoint();'));
from grading_tools import send_code;send_code('ex1.ipynb')
|
https://github.com/MonitSharma/Qiskit-Summer-School-and-Quantum-Challenges
|
MonitSharma
|
# import SymPy and define symbols
import sympy as sp
sp.init_printing(use_unicode=True)
wr = sp.Symbol('\omega_r') # resonator frequency
wq = sp.Symbol('\omega_q') # qubit frequency
g = sp.Symbol('g', real=True) # vacuum Rabi coupling
Delta = sp.Symbol('Delta', real=True) # wr - wq; defined later
# import operator relations and define them
from sympy.physics.quantum.boson import BosonOp
a = BosonOp('a') # resonator photon annihilation operator
from sympy.physics.quantum import pauli, Dagger, Commutator
from sympy.physics.quantum.operatorordering import normal_ordered_form
# Pauli matrices
sx = pauli.SigmaX()
sy = pauli.SigmaY()
sz = pauli.SigmaZ()
# qubit raising and lowering operators
splus = pauli.SigmaPlus()
sminus = pauli.SigmaMinus()
# define J-C Hamiltonian in terms of diagonal and non-block diagonal terms
H0 = wr*Dagger(a)*a - (1/2)*wq*sz;
H1 = 0
H2 = g*(Dagger(a)*sminus + a*splus);
HJC = H0 + H1 + H2; HJC # print
# using the above method for finding the ansatz
eta = Commutator(H0, H2); eta
pauli.qsimplify_pauli(normal_ordered_form(eta.doit().expand()))
A = sp.Symbol('A')
B = sp.Symbol('B')
eta = A * Dagger(a) * sminus - B * a * splus;
pauli.qsimplify_pauli(normal_ordered_form(Commutator(H0, eta).doit().expand()))
H2
S1 = eta.subs(A, g/Delta)
S1 = S1.subs(B, g/Delta); S1.factor()
Heff = H0 + H1 + 0.5*pauli.qsimplify_pauli(normal_ordered_form(Commutator(H2, S1).doit().expand())).simplify(); Heff
from qiskit.tools.jupyter import *
from qiskit import IBMQ
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q', group='open', project='main')
backend = provider.get_backend('ibmq_armonk')
backend_config = backend.configuration()
assert backend_config.open_pulse, "Backend doesn't support Pulse"
dt = backend_config.dt
print(f"Sampling time: {dt*1e9} ns")
backend_defaults = backend.defaults()
import numpy as np
# unit conversion factors -> all backend properties returned in SI (Hz, sec, etc)
GHz = 1.0e9 # Gigahertz
MHz = 1.0e6 # Megahertz
kHz = 1.0e3
us = 1.0e-6 # Microseconds
ns = 1.0e-9 # Nanoseconds
# We will find the qubit frequency for the following qubit.
qubit = 0
# The sweep will be centered around the estimated qubit frequency.
center_frequency_Hz = backend_defaults.qubit_freq_est[qubit] # The default frequency is given in Hz
# warning: this will change in a future release
print(f"Qubit {qubit} has an estimated frequency of {center_frequency_Hz / GHz} GHz.")
# scale factor to remove factors of 10 from the data
scale_factor = 1e-14
# We will sweep 40 MHz around the estimated frequency
frequency_span_Hz = 40 * MHz
# in steps of 1 MHz.
frequency_step_Hz = 1 * MHz
# We will sweep 20 MHz above and 20 MHz below the estimated frequency
frequency_min = center_frequency_Hz - frequency_span_Hz / 2
frequency_max = center_frequency_Hz + frequency_span_Hz / 2
# Construct an np array of the frequencies for our experiment
frequencies_GHz = np.arange(frequency_min / GHz,
frequency_max / GHz,
frequency_step_Hz / GHz)
print(f"The sweep will go from {frequency_min / GHz} GHz to {frequency_max / GHz} GHz \
in steps of {frequency_step_Hz / MHz} MHz.")
from qiskit import pulse # This is where we access all of our Pulse features!
inst_sched_map = backend_defaults.instruction_schedule_map
measure = inst_sched_map.get('measure', qubits=[qubit])
x_pulse = inst_sched_map.get('x', qubits=[qubit])
### Collect the necessary channels
drive_chan = pulse.DriveChannel(qubit)
meas_chan = pulse.MeasureChannel(qubit)
acq_chan = pulse.AcquireChannel(qubit)
# Create the base schedule
# Start with drive pulse acting on the drive channel
schedule = pulse.Schedule(name='Frequency sweep')
schedule += x_pulse
# The left shift `<<` is special syntax meaning to shift the start time of the schedule by some duration
schedule += measure << schedule.duration
# Create the frequency settings for the sweep (MUST BE IN HZ)
frequencies_Hz = frequencies_GHz*GHz
schedule_frequencies = [{drive_chan: freq} for freq in frequencies_Hz]
schedule.draw(label=True, scaling=0.8)
from qiskit import assemble
frequency_sweep_program = assemble(schedule,
backend=backend,
meas_level=1,
meas_return='avg',
shots=1024,
schedule_los=schedule_frequencies)
# RUN the job on a real device
#job = backend.run(rabi_experiment_program)
#print(job.job_id())
#from qiskit.tools.monitor import job_monitor
#job_monitor(job)
# OR retreive result from previous run
job = backend.retrieve_job('5ef3b081fbc24b001275b03b')
frequency_sweep_results = job.result()
import matplotlib.pyplot as plt
plt.style.use('dark_background')
sweep_values = []
for i in range(len(frequency_sweep_results.results)):
# Get the results from the ith experiment
res = frequency_sweep_results.get_memory(i)*scale_factor
# Get the results for `qubit` from this experiment
sweep_values.append(res[qubit])
plt.scatter(frequencies_GHz, np.real(sweep_values), color='white') # plot real part of sweep values
plt.xlim([min(frequencies_GHz), max(frequencies_GHz)])
plt.xlabel("Frequency [GHz]")
plt.ylabel("Measured signal [a.u.]")
plt.show()
from scipy.optimize import curve_fit
def fit_function(x_values, y_values, function, init_params):
fitparams, conv = curve_fit(function, x_values, y_values, init_params)
y_fit = function(x_values, *fitparams)
return fitparams, y_fit
fit_params, y_fit = fit_function(frequencies_GHz,
np.real(sweep_values),
lambda x, A, q_freq, B, C: (A / np.pi) * (B / ((x - q_freq)**2 + B**2)) + C,
[5, 4.975, 1, 3] # initial parameters for curve_fit
)
plt.scatter(frequencies_GHz, np.real(sweep_values), color='white')
plt.plot(frequencies_GHz, y_fit, color='red')
plt.xlim([min(frequencies_GHz), max(frequencies_GHz)])
plt.xlabel("Frequency [GHz]")
plt.ylabel("Measured Signal [a.u.]")
plt.show()
# Create the schedules for 0 and 1
schedule_0 = pulse.Schedule(name='0')
schedule_0 += measure
schedule_1 = pulse.Schedule(name='1')
schedule_1 += x_pulse
schedule_1 += measure << schedule_1.duration
schedule_0.draw()
schedule_1.draw()
frequency_span_Hz = 320 * kHz
frequency_step_Hz = 8 * kHz
center_frequency_Hz = backend_defaults.meas_freq_est[qubit]
print(f"Qubit {qubit} has an estimated readout frequency of {center_frequency_Hz / GHz} GHz.")
frequency_min = center_frequency_Hz - frequency_span_Hz / 2
frequency_max = center_frequency_Hz + frequency_span_Hz / 2
frequencies_GHz = np.arange(frequency_min / GHz,
frequency_max / GHz,
frequency_step_Hz / GHz)
print(f"The sweep will go from {frequency_min / GHz} GHz to {frequency_max / GHz} GHz\
in steps of {frequency_step_Hz / MHz} MHz.")
num_shots_per_frequency = 2048
frequencies_Hz = frequencies_GHz*GHz
schedule_los = [{meas_chan: freq} for freq in frequencies_Hz]
cavity_sweep_0 = assemble(schedule_0,
backend=backend,
meas_level=1,
meas_return='avg',
shots=num_shots_per_frequency,
schedule_los=schedule_los)
cavity_sweep_1 = assemble(schedule_1,
backend=backend,
meas_level=1,
meas_return='avg',
shots=num_shots_per_frequency,
schedule_los=schedule_los)
# RUN the job on a real device
#job_0 = backend.run(cavity_sweep_0)
#job_monitor(job_0)
#job_0.error_message()
#job_1 = backend.run(cavity_sweep_1)
#job_monitor(job_1)
#job_1.error_message()
# OR retreive result from previous run
job_0 = backend.retrieve_job('5efa5b447c0d6800137fff1c')
job_1 = backend.retrieve_job('5efa6b2720eee10013be46b4')
cavity_sweep_0_results = job_0.result()
cavity_sweep_1_results = job_1.result()
scale_factor = 1e-14
sweep_values_0 = []
for i in range(len(cavity_sweep_0_results.results)):
res_0 = cavity_sweep_0_results.get_memory(i)*scale_factor
sweep_values_0.append(res_0[qubit])
sweep_values_1 = []
for i in range(len(cavity_sweep_1_results.results)):
res_1 = cavity_sweep_1_results.get_memory(i)*scale_factor
sweep_values_1.append(res_1[qubit])
plotx = frequencies_Hz/kHz
ploty_0 = np.abs(sweep_values_0)
ploty_1 = np.abs(sweep_values_1)
plt.plot(plotx, ploty_0, color='blue', marker='.') # plot real part of sweep values
plt.plot(plotx, ploty_1, color='red', marker='.') # plot real part of sweep values
plt.legend([r'$\vert0\rangle$', r'$\vert1\rangle$'])
plt.grid()
plt.xlabel("Frequency [kHz]")
plt.ylabel("Measured signal [a.u.]")
plt.yscale('log')
plt.show()
|
https://github.com/MonitSharma/Qiskit-Summer-School-and-Quantum-Challenges
|
MonitSharma
|
!pip install -U -r grading_tools/requirements.txt
from IPython.display import clear_output
clear_output()
import numpy as np; pi = np.pi
from qiskit import QuantumCircuit, Aer, execute
from qiskit.visualization import plot_histogram
from copy import deepcopy as make_copy
def prepare_hets_circuit(depth, angle1, angle2):
hets_circ = QuantumCircuit(depth)
hets_circ.ry(angle1, 0)
hets_circ.rz(angle1, 0)
hets_circ.ry(angle1, 1)
hets_circ.rz(angle1, 1)
for ii in range(depth):
hets_circ.cx(0,1)
hets_circ.ry(angle2,0)
hets_circ.rz(angle2,0)
hets_circ.ry(angle2,1)
hets_circ.rz(angle2,1)
return hets_circ
hets_circuit = prepare_hets_circuit(2, pi/2, pi/2)
hets_circuit.draw()
def measure_zz_circuit(given_circuit):
zz_meas = make_copy(given_circuit)
zz_meas.measure_all()
return zz_meas
zz_meas = measure_zz_circuit(hets_circuit)
zz_meas.draw()
simulator = Aer.get_backend('qasm_simulator')
result = execute(zz_meas, backend = simulator, shots=10000).result()
counts = result.get_counts(zz_meas)
plot_histogram(counts)
def measure_zz(given_circuit, num_shots = 10000):
zz_meas = measure_zz_circuit(given_circuit)
result = execute(zz_meas, backend = simulator, shots = num_shots).result()
counts = result.get_counts(zz_meas)
if '00' not in counts:
counts['00'] = 0
if '01' not in counts:
counts['01'] = 0
if '10' not in counts:
counts['10'] = 0
if '11' not in counts:
counts['11'] = 0
total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10']
zz = counts['00'] + counts['11'] - counts['01'] - counts['10']
zz = zz / total_counts
return zz
zz = measure_zz(hets_circuit)
print("<ZZ> =", str(zz))
def measure_zi(given_circuit, num_shots = 10000):
zz_meas = measure_zz_circuit(given_circuit)
result = execute(zz_meas, backend = simulator, shots = num_shots).result()
counts = result.get_counts(zz_meas)
if '00' not in counts:
counts['00'] = 0
if '01' not in counts:
counts['01'] = 0
if '10' not in counts:
counts['10'] = 0
if '11' not in counts:
counts['11'] = 0
total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10']
zi = counts['00'] - counts['11'] + counts['01'] - counts['10']
zi = zi / total_counts
return zi
def measure_iz(given_circuit, num_shots = 10000):
zz_meas = measure_zz_circuit(given_circuit)
result = execute(zz_meas, backend = simulator, shots = num_shots).result()
counts = result.get_counts(zz_meas)
if '00' not in counts:
counts['00'] = 0
if '01' not in counts:
counts['01'] = 0
if '10' not in counts:
counts['10'] = 0
if '11' not in counts:
counts['11'] = 0
total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10']
iz = counts['00'] - counts['11'] - counts['01'] + counts['10']
iz = iz / total_counts
return iz
zi = measure_zi(hets_circuit)
print("<ZI> =", str(zi))
iz = measure_iz(hets_circuit)
print("<IZ> =", str(iz))
def measure_xx_circuit(given_circuit):
xx_meas = make_copy(given_circuit)
### WRITE YOUR CODE BETWEEN THESE LINES - START
xx_meas.h(0)
xx_meas.h(1)
xx_meas.measure_all()
### WRITE YOUR CODE BETWEEN THESE LINES - END
return xx_meas
xx_meas = measure_xx_circuit(hets_circuit)
xx_meas.draw()
def measure_xx(given_circuit, num_shots = 10000):
xx_meas = measure_xx_circuit(given_circuit)
result = execute(xx_meas, backend = simulator, shots = num_shots).result()
counts = result.get_counts(xx_meas)
if '00' not in counts:
counts['00'] = 0
if '01' not in counts:
counts['01'] = 0
if '10' not in counts:
counts['10'] = 0
if '11' not in counts:
counts['11'] = 0
total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10']
xx = counts['00'] + counts['11'] - counts['01'] - counts['10']
xx = xx / total_counts
return xx
xx = measure_xx(hets_circuit)
print("<XX> =", str(xx))
def get_energy(given_circuit, num_shots = 10000):
zz = measure_zz(given_circuit, num_shots = num_shots)
iz = measure_iz(given_circuit, num_shots = num_shots)
zi = measure_zi(given_circuit, num_shots = num_shots)
xx = measure_xx(given_circuit, num_shots = num_shots)
energy = (-1.0523732)*1 + (0.39793742)*iz + (-0.3979374)*zi + (-0.0112801)*zz + (0.18093119)*xx
return energy
energy = get_energy(hets_circuit)
print("The energy of the trial state is", str(energy))
hets_circuit_plus = None
hets_circuit_minus = None
### WRITE YOUR CODE BETWEEN THESE LINES - START
hets_circuit_plus = prepare_hets_circuit(2, pi/2 + 0.1*pi/2, pi/2)
hets_circuit_minus = prepare_hets_circuit(2, pi/2 - 0.1*pi/2, pi/2)
### WRITE YOUR CODE BETWEEN THESE LINES - END
energy_plus = get_energy(hets_circuit_plus, num_shots=100000)
energy_minus = get_energy(hets_circuit_minus, num_shots=100000)
print(energy_plus, energy_minus)
name = 'Pon Rahul M'
email = 'ponrahul.21it@licet.ac.in'
### Do not change the lines below
from grading_tools import grade
grade(answer=measure_xx_circuit(hets_circuit), name=name, email=email, labid='lab9', exerciseid='ex1')
grade(answer=hets_circuit_plus, name=name, email=email, labid='lab9', exerciseid='ex2')
grade(answer=hets_circuit_minus, name=name, email=email, labid='lab9', exerciseid='ex3')
energy_plus_100, energy_plus_1000, energy_plus_10000 = 0, 0, 0
energy_minus_100, energy_minus_1000, energy_minus_10000 = 0, 0, 0
### WRITE YOUR CODE BETWEEN THESE LINES - START
energy_plus_100 = get_energy(hets_circuit_plus, num_shots = 100)
energy_minus_100 = get_energy(hets_circuit_minus, num_shots = 100)
energy_plus_1000 = get_energy(hets_circuit_plus, num_shots = 1000)
energy_minus_1000 = get_energy(hets_circuit_minus, num_shots = 1000)
energy_plus_10000 = get_energy(hets_circuit_plus, num_shots = 10000)
energy_minus_10000 = get_energy(hets_circuit_minus, num_shots = 10000)
### WRITE YOUR CODE BETWEEN THESE LINES - END
print(energy_plus_100, energy_minus_100, "difference = ", energy_minus_100 - energy_plus_100)
print(energy_plus_1000, energy_minus_1000, "difference = ", energy_minus_1000 - energy_plus_1000)
print(energy_plus_10000, energy_minus_10000, "difference = ", energy_minus_10000 - energy_plus_10000)
### WRITE YOUR CODE BETWEEN THESE LINES - START
I = np.array([
[1, 0],
[0, 1]
])
X = np.array([
[0, 1],
[1, 0]
])
Z = np.array([
[1, 0],
[0, -1]
])
h2_hamiltonian = (-1.0523732) * np.kron(I, I) + \
(0.39793742) * np.kron(I, Z) + \
(-0.3979374) * np.kron(Z, I) + \
(-0.0112801) * np.kron(Z, Z) + \
(0.18093119) * np.kron(X, X)
from numpy import linalg as LA
eigenvalues, eigenvectors = LA.eig(h2_hamiltonian)
for ii, eigenvalue in enumerate(eigenvalues):
print(f"Eigenvector {eigenvectors[:,ii]} has energy {eigenvalue}")
exact_eigenvector = eigenvectors[:,np.argmin(eigenvalues)]
exact_eigenvalue = np.min(eigenvalues)
print()
print("Minimum energy is", exact_eigenvalue)
### WRITE YOUR CODE BETWEEN THESE LINES - END
|
https://github.com/MonitSharma/Qiskit-Summer-School-and-Quantum-Challenges
|
MonitSharma
|
import numpy as np
# Importing standard Qiskit libraries
from qiskit import QuantumCircuit, transpile, assemble, Aer, IBMQ, execute
from qiskit.quantum_info import Statevector
from qiskit.visualization import plot_bloch_multivector, plot_histogram
from qiskit_textbook.problems import dj_problem_oracle
def lab1_ex1():
qc = QuantumCircuit(1)
#
#
# FILL YOUR CODE IN HERE
#
#
qc.x(0)
return qc
state = Statevector.from_instruction(lab1_ex1())
plot_bloch_multivector(state)
from qc_grader import grade_lab1_ex1
# Note that the grading function is expecting a quantum circuit without measurements
grade_lab1_ex1(lab1_ex1())
def lab1_ex2():
qc = QuantumCircuit(1)
#
#
# FILL YOUR CODE IN HERE
#
#
qc.h(0)
return qc
state = Statevector.from_instruction(lab1_ex2())
plot_bloch_multivector(state)
from qc_grader import grade_lab1_ex2
# Note that the grading function is expecting a quantum circuit without measurements
grade_lab1_ex2(lab1_ex2())
def lab1_ex3():
qc = QuantumCircuit(1)
#
#
# FILL YOUR CODE IN HERE
#
#
qc.x(0)
qc.h(0)
return qc
state = Statevector.from_instruction(lab1_ex3())
plot_bloch_multivector(state)
from qc_grader import grade_lab1_ex3
# Note that the grading function is expecting a quantum circuit without measurements
grade_lab1_ex3(lab1_ex3())
def lab1_ex4():
qc = QuantumCircuit(1)
#
#
# FILL YOUR CODE IN HERE
#
#
qc.h(0)
qc.sdg(0)
return qc
state = Statevector.from_instruction(lab1_ex4())
plot_bloch_multivector(state)
from qc_grader import grade_lab1_ex4
# Note that the grading function is expecting a quantum circuit without measurements
grade_lab1_ex4(lab1_ex4())
def lab1_ex5():
qc = QuantumCircuit(2,2) # this time, we not only want two qubits, but also two classical bits for the measurement
#
#
# FILL YOUR CODE IN HERE
#
#
qc.h(0)
qc.cx(0,1)
qc.x(0)
return qc
qc = lab1_ex5()
qc.draw() # we draw the circuit
from qc_grader import grade_lab1_ex5
# Note that the grading function is expecting a quantum circuit without measurements
grade_lab1_ex5(lab1_ex5())
qc.measure(0, 0) # we perform a measurement on qubit q_0 and store the information on the classical bit c_0
qc.measure(1, 1) # we perform a measurement on qubit q_1 and store the information on the classical bit c_1
backend = Aer.get_backend('qasm_simulator') # we choose the simulator as our backend
counts = execute(qc, backend, shots = 1000).result().get_counts() # we run the simulation and get the counts
plot_histogram(counts) # let us plot a histogram to see the possible outcomes and corresponding probabilities
def lab1_ex6():
#
#
# FILL YOUR CODE IN HERE
#
#
qc = QuantumCircuit(3,3)
qc.h(0)
qc.cx(0,1)
qc.cx(1,2)
qc.y(1)
return qc
qc = lab1_ex6()
qc.draw() # we draw the circuit
from qc_grader import grade_lab1_ex6
# Note that the grading function is expecting a quantum circuit without measurements
grade_lab1_ex6(lab1_ex6())
oraclenr = 4 # determines the oracle (can range from 1 to 5)
oracle = dj_problem_oracle(oraclenr) # gives one out of 5 oracles
oracle.name = "DJ-Oracle"
def dj_classical(n, input_str):
# build a quantum circuit with n qubits and 1 classical readout bit
dj_circuit = QuantumCircuit(n+1,1)
# Prepare the initial state corresponding to your input bit string
for i in range(n):
if input_str[i] == '1':
dj_circuit.x(i)
# append oracle
dj_circuit.append(oracle, range(n+1))
# measure the fourth qubit
dj_circuit.measure(n,0)
return dj_circuit
n = 4 # number of qubits
input_str = '1111'
dj_circuit = dj_classical(n, input_str)
dj_circuit.draw() # draw the circuit
input_str = '1111'
dj_circuit = dj_classical(n, input_str)
qasm_sim = Aer.get_backend('qasm_simulator')
transpiled_dj_circuit = transpile(dj_circuit, qasm_sim)
qobj = assemble(transpiled_dj_circuit, qasm_sim)
results = qasm_sim.run(qobj).result()
answer = results.get_counts()
plot_histogram(answer)
def lab1_ex7():
min_nr_inputs = 2
max_nr_inputs = 9
return [min_nr_inputs, max_nr_inputs]
from qc_grader import grade_lab1_ex7
# Note that the grading function is expecting a list of two integers
grade_lab1_ex7(lab1_ex7())
n=4
def psi_0(n):
qc = QuantumCircuit(n+1,n)
# Build the state (|00000> - |10000>)/sqrt(2)
#
#
# FILL YOUR CODE IN HERE
#
#
qc.x(4)
qc.h(4)
return qc
dj_circuit = psi_0(n)
dj_circuit.draw()
def psi_1(n):
# obtain the |psi_0> = |00001> state
qc = psi_0(n)
# create the superposition state |psi_1>
#
#
qc.h(0)
qc.h(1)
qc.h(2)
qc.h(3)
#
#
qc.barrier()
return qc
dj_circuit = psi_1(n)
dj_circuit.draw()
def psi_2(oracle,n):
# circuit to obtain psi_1
qc = psi_1(n)
# append the oracle
qc.append(oracle, range(n+1))
return qc
dj_circuit = psi_2(oracle, n)
dj_circuit.draw()
def lab1_ex8(oracle, n): # note that this exercise also depends on the code in the functions psi_0 (In [24]) and psi_1 (In [25])
qc = psi_2(oracle, n)
# apply n-fold hadamard gate
#
#
# FILL YOUR CODE IN HERE
#
#
qc.h(0)
qc.h(1)
qc.h(2)
qc.h(3)
# add the measurement by connecting qubits to classical bits
#
#
qc.measure(0,0)
qc.measure(1,1)
qc.measure(2,2)
qc.measure(3,3)
#
#
return qc
dj_circuit = lab1_ex8(oracle, n)
dj_circuit.draw()
from qc_grader import grade_lab1_ex8
# Note that the grading function is expecting a quantum circuit with measurements
grade_lab1_ex8(lab1_ex8(dj_problem_oracle(4),n))
qasm_sim = Aer.get_backend('qasm_simulator')
transpiled_dj_circuit = transpile(dj_circuit, qasm_sim)
qobj = assemble(transpiled_dj_circuit)
results = qasm_sim.run(qobj).result()
answer = results.get_counts()
plot_histogram(answer)
|
https://github.com/MonitSharma/Qiskit-Summer-School-and-Quantum-Challenges
|
MonitSharma
|
import networkx as nx
import numpy as np
import plotly.graph_objects as go
import matplotlib as mpl
import pandas as pd
from IPython.display import clear_output
from plotly.subplots import make_subplots
from matplotlib import pyplot as plt
from qiskit import Aer
from qiskit import QuantumCircuit
from qiskit.visualization import plot_state_city
from qiskit.algorithms.optimizers import COBYLA, SLSQP, ADAM
from time import time
from copy import copy
from typing import List
from qc_grader.graph_util import display_maxcut_widget, QAOA_widget, graphs
mpl.rcParams['figure.dpi'] = 300
from qiskit.circuit import Parameter, ParameterVector
#Parameters are initialized with a simple string identifier
parameter_0 = Parameter('θ[0]')
parameter_1 = Parameter('θ[1]')
circuit = QuantumCircuit(1)
#We can then pass the initialized parameters as the rotation angle argument to the Rx and Ry gates
circuit.ry(theta = parameter_0, qubit = 0)
circuit.rx(theta = parameter_1, qubit = 0)
circuit.draw('mpl')
parameter = Parameter('θ')
circuit = QuantumCircuit(1)
circuit.ry(theta = parameter, qubit = 0)
circuit.rx(theta = parameter, qubit = 0)
circuit.draw('mpl')
#Set the number of layers and qubits
n=3
num_layers = 2
#ParameterVectors are initialized with a string identifier and an integer specifying the vector length
parameters = ParameterVector('θ', n*(num_layers+1))
circuit = QuantumCircuit(n, n)
for layer in range(num_layers):
#Appending the parameterized Ry gates using parameters from the vector constructed above
for i in range(n):
circuit.ry(parameters[n*layer+i], i)
circuit.barrier()
#Appending the entangling CNOT gates
for i in range(n):
for j in range(i):
circuit.cx(j,i)
circuit.barrier()
#Appending one additional layer of parameterized Ry gates
for i in range(n):
circuit.ry(parameters[n*num_layers+i], i)
circuit.barrier()
circuit.draw('mpl')
print(circuit.parameters)
#Create parameter dictionary with random values to bind
param_dict = {parameter: np.random.random() for parameter in parameters}
print(param_dict)
#Assign parameters using the assign_parameters method
bound_circuit = circuit.assign_parameters(parameters = param_dict)
bound_circuit.draw('mpl')
new_parameters = ParameterVector('Ψ',9)
new_circuit = circuit.assign_parameters(parameters = [k*new_parameters[i] for k in range(9)])
new_circuit.draw('mpl')
#Run the circuit with assigned parameters on Aer's statevector simulator
simulator = Aer.get_backend('statevector_simulator')
result = simulator.run(bound_circuit).result()
statevector = result.get_statevector(bound_circuit)
plot_state_city(statevector)
#The following line produces an error when run because 'circuit' still contains non-assigned parameters
#result = simulator.run(circuit).result()
for key in graphs.keys():
print(key)
graph = nx.Graph()
#Add nodes and edges
graph.add_nodes_from(np.arange(0,6,1))
edges = [(0,1,2.0),(0,2,3.0),(0,3,2.0),(0,4,4.0),(0,5,1.0),(1,2,4.0),(1,3,1.0),(1,4,1.0),(1,5,3.0),(2,4,2.0),(2,5,3.0),(3,4,5.0),(3,5,1.0)]
graph.add_weighted_edges_from(edges)
graphs['custom'] = graph
#Display widget
display_maxcut_widget(graphs['custom'])
def maxcut_cost_fn(graph: nx.Graph, bitstring: List[int]) -> float:
"""
Computes the maxcut cost function value for a given graph and cut represented by some bitstring
Args:
graph: The graph to compute cut values for
bitstring: A list of integer values '0' or '1' specifying a cut of the graph
Returns:
The value of the cut
"""
#Get the weight matrix of the graph
weight_matrix = nx.adjacency_matrix(graph).toarray()
size = weight_matrix.shape[0]
value = 0.
#INSERT YOUR CODE TO COMPUTE THE CUT VALUE HERE
for i in range(size):
for j in range(size):
value+= weight_matrix[i,j]*bitstring[i]*(1-bitstring[j])
return value
def plot_maxcut_histogram(graph: nx.Graph) -> None:
"""
Plots a bar diagram with the values for all possible cuts of a given graph.
Args:
graph: The graph to compute cut values for
"""
num_vars = graph.number_of_nodes()
#Create list of bitstrings and corresponding cut values
bitstrings = ['{:b}'.format(i).rjust(num_vars, '0')[::-1] for i in range(2**num_vars)]
values = [maxcut_cost_fn(graph = graph, bitstring = [int(x) for x in bitstring]) for bitstring in bitstrings]
#Sort both lists by largest cut value
values, bitstrings = zip(*sorted(zip(values, bitstrings)))
#Plot bar diagram
bar_plot = go.Bar(x = bitstrings, y = values, marker=dict(color=values, colorscale = 'plasma', colorbar=dict(title='Cut Value')))
fig = go.Figure(data=bar_plot, layout = dict(xaxis=dict(type = 'category'), width = 1500, height = 600))
fig.show()
plot_maxcut_histogram(graph = graphs['custom'])
from qc_grader import grade_lab2_ex1
bitstring = [1, 0, 1, 1, 0, 0] #DEFINE THE CORRECT MAXCUT BITSTRING HERE
# Note that the grading function is expecting a list of integers '0' and '1'
grade_lab2_ex1(bitstring)
from qiskit_optimization import QuadraticProgram
quadratic_program = QuadraticProgram('sample_problem')
print(quadratic_program.export_as_lp_string())
quadratic_program.binary_var(name = 'x_0')
quadratic_program.integer_var(name = 'x_1')
quadratic_program.continuous_var(name = 'x_2', lowerbound = -2.5, upperbound = 1.8)
quadratic = [[0,1,2],[3,4,5],[0,1,2]]
linear = [10,20,30]
quadratic_program.minimize(quadratic = quadratic, linear = linear, constant = -5)
print(quadratic_program.export_as_lp_string())
def quadratic_program_from_graph(graph: nx.Graph) -> QuadraticProgram:
"""Constructs a quadratic program from a given graph for a MaxCut problem instance.
Args:
graph: Underlying graph of the problem.
Returns:
QuadraticProgram
"""
#Get weight matrix of graph
weight_matrix = nx.adjacency_matrix(graph)
shape = weight_matrix.shape
size = shape[0]
#Build qubo matrix Q from weight matrix W
qubo_matrix = np.zeros((size, size))
qubo_vector = np.zeros(size)
for i in range(size):
for j in range(size):
qubo_matrix[i, j] -= weight_matrix[i, j]
for i in range(size):
for j in range(size):
qubo_vector[i] += weight_matrix[i,j]
#INSERT YOUR CODE HERE
quadratic_program=QuadraticProgram('sample_problem')
for i in range(size):
quadratic_program.binary_var(name='x_{}'.format(i))
quadratic_program.maximize(quadratic =qubo_matrix, linear = qubo_vector)
return quadratic_program
quadratic_program = quadratic_program_from_graph(graphs['custom'])
print(quadratic_program.export_as_lp_string())
from qc_grader import grade_lab2_ex2
# Note that the grading function is expecting a quadratic program
grade_lab2_ex2(quadratic_program)
def qaoa_circuit(qubo: QuadraticProgram, p: int = 1):
"""
Given a QUBO instance and the number of layers p, constructs the corresponding parameterized QAOA circuit with p layers.
Args:
qubo: The quadratic program instance
p: The number of layers in the QAOA circuit
Returns:
The parameterized QAOA circuit
"""
size = len(qubo.variables)
qubo_matrix = qubo.objective.quadratic.to_array(symmetric=True)
qubo_linearity = qubo.objective.linear.to_array()
#Prepare the quantum and classical registers
qaoa_circuit = QuantumCircuit(size,size)
#Apply the initial layer of Hadamard gates to all qubits
qaoa_circuit.h(range(size))
#Create the parameters to be used in the circuit
gammas = ParameterVector('gamma', p)
betas = ParameterVector('beta', p)
#Outer loop to create each layer
for i in range(p):
#Apply R_Z rotational gates from cost layer
#INSERT YOUR CODE HERE
for j in range(size):
qubo_matrix_sum_of_col = 0
for k in range(size):
qubo_matrix_sum_of_col+= qubo_matrix[j][k]
qaoa_circuit.rz(gammas[i]*(qubo_linearity[j]+qubo_matrix_sum_of_col),j)
#Apply R_ZZ rotational gates for entangled qubit rotations from cost layer
#INSERT YOUR CODE HERE
for j in range(size):
for k in range(size):
if j!=k:
qaoa_circuit.rzz(gammas[i]*qubo_matrix[j][k]*0.5,j,k)
# Apply single qubit X - rotations with angle 2*beta_i to all qubits
#INSERT YOUR CODE HERE
for j in range(size):
qaoa_circuit.rx(2*betas[i],j)
return qaoa_circuit
quadratic_program = quadratic_program_from_graph(graphs['custom'])
custom_circuit = qaoa_circuit(qubo = quadratic_program)
test = custom_circuit.assign_parameters(parameters=[1.0]*len(custom_circuit.parameters))
from qc_grader import grade_lab2_ex3
# Note that the grading function is expecting a quantum circuit
grade_lab2_ex3(test)
from qiskit.algorithms import QAOA
from qiskit_optimization.algorithms import MinimumEigenOptimizer
backend = Aer.get_backend('statevector_simulator')
qaoa = QAOA(optimizer = ADAM(), quantum_instance = backend, reps=1, initial_point = [0.1,0.1])
eigen_optimizer = MinimumEigenOptimizer(min_eigen_solver = qaoa)
quadratic_program = quadratic_program_from_graph(graphs['custom'])
result = eigen_optimizer.solve(quadratic_program)
print(result)
def plot_samples(samples):
"""
Plots a bar diagram for the samples of a quantum algorithm
Args:
samples
"""
#Sort samples by probability
samples = sorted(samples, key = lambda x: x.probability)
#Get list of probabilities, function values and bitstrings
probabilities = [sample.probability for sample in samples]
values = [sample.fval for sample in samples]
bitstrings = [''.join([str(int(i)) for i in sample.x]) for sample in samples]
#Plot bar diagram
sample_plot = go.Bar(x = bitstrings, y = probabilities, marker=dict(color=values, colorscale = 'plasma',colorbar=dict(title='Function Value')))
fig = go.Figure(
data=sample_plot,
layout = dict(
xaxis=dict(
type = 'category'
)
)
)
fig.show()
plot_samples(result.samples)
graph_name = 'custom'
quadratic_program = quadratic_program_from_graph(graph=graphs[graph_name])
trajectory={'beta_0':[], 'gamma_0':[], 'energy':[]}
offset = 1/4*quadratic_program.objective.quadratic.to_array(symmetric = True).sum() + 1/2*quadratic_program.objective.linear.to_array().sum()
def callback(eval_count, params, mean, std_dev):
trajectory['beta_0'].append(params[1])
trajectory['gamma_0'].append(params[0])
trajectory['energy'].append(-mean + offset)
optimizers = {
'cobyla': COBYLA(),
'slsqp': SLSQP(),
'adam': ADAM()
}
qaoa = QAOA(optimizer = optimizers['cobyla'], quantum_instance = backend, reps=1, initial_point = [6.2,1.8],callback = callback)
eigen_optimizer = MinimumEigenOptimizer(min_eigen_solver = qaoa)
result = eigen_optimizer.solve(quadratic_program)
fig = QAOA_widget(landscape_file=f'./resources/energy_landscapes/{graph_name}.csv', trajectory = trajectory, samples = result.samples)
fig.show()
graph_name = 'custom'
quadratic_program = quadratic_program_from_graph(graphs[graph_name])
#Create callback to record total number of evaluations
max_evals = 0
def callback(eval_count, params, mean, std_dev):
global max_evals
max_evals = eval_count
#Create empty lists to track values
energies = []
runtimes = []
num_evals=[]
#Run QAOA for different values of p
for p in range(1,10):
print(f'Evaluating for p = {p}...')
qaoa = QAOA(optimizer = optimizers['cobyla'], quantum_instance = backend, reps=p, callback=callback)
eigen_optimizer = MinimumEigenOptimizer(min_eigen_solver = qaoa)
start = time()
result = eigen_optimizer.solve(quadratic_program)
runtimes.append(time()-start)
num_evals.append(max_evals)
#Calculate energy of final state from samples
avg_value = 0.
for sample in result.samples:
avg_value += sample.probability*sample.fval
energies.append(avg_value)
#Create and display plots
energy_plot = go.Scatter(x = list(range(1,10)), y =energies, marker=dict(color=energies, colorscale = 'plasma'))
runtime_plot = go.Scatter(x = list(range(1,10)), y =runtimes, marker=dict(color=runtimes, colorscale = 'plasma'))
num_evals_plot = go.Scatter(x = list(range(1,10)), y =num_evals, marker=dict(color=num_evals, colorscale = 'plasma'))
fig = make_subplots(rows = 1, cols = 3, subplot_titles = ['Energy value', 'Runtime', 'Number of evaluations'])
fig.update_layout(width=1800,height=600, showlegend=False)
fig.add_trace(energy_plot, row=1, col=1)
fig.add_trace(runtime_plot, row=1, col=2)
fig.add_trace(num_evals_plot, row=1, col=3)
clear_output()
fig.show()
def plot_qaoa_energy_landscape(graph: nx.Graph, cvar: float = None):
num_shots = 1000
seed = 42
simulator = Aer.get_backend('qasm_simulator')
simulator.set_options(seed_simulator = 42)
#Generate circuit
circuit = qaoa_circuit(qubo = quadratic_program_from_graph(graph), p=1)
circuit.measure(range(graph.number_of_nodes()),range(graph.number_of_nodes()))
#Create dictionary with precomputed cut values for all bitstrings
cut_values = {}
size = graph.number_of_nodes()
for i in range(2**size):
bitstr = '{:b}'.format(i).rjust(size, '0')[::-1]
x = [int(bit) for bit in bitstr]
cut_values[bitstr] = maxcut_cost_fn(graph, x)
#Perform grid search over all parameters
data_points = []
max_energy = None
for beta in np.linspace(0,np.pi, 50):
for gamma in np.linspace(0, 4*np.pi, 50):
bound_circuit = circuit.assign_parameters([beta, gamma])
result = simulator.run(bound_circuit, shots = num_shots).result()
statevector = result.get_counts(bound_circuit)
energy = 0
measured_cuts = []
for bitstring, count in statevector.items():
measured_cuts = measured_cuts + [cut_values[bitstring]]*count
if cvar is None:
#Calculate the mean of all cut values
energy = sum(measured_cuts)/num_shots
else:
#raise NotImplementedError()
#INSERT YOUR CODE HERE
measured_cuts = sorted(measured_cuts, reverse = True)
for w in range(int(cvar*num_shots)):
energy += measured_cuts[w]/int((cvar*num_shots))
#Update optimal parameters
if max_energy is None or energy > max_energy:
max_energy = energy
optimum = {'beta': beta, 'gamma': gamma, 'energy': energy}
#Update data
data_points.append({'beta': beta, 'gamma': gamma, 'energy': energy})
#Create and display surface plot from data_points
df = pd.DataFrame(data_points)
df = df.pivot(index='beta', columns='gamma', values='energy')
matrix = df.to_numpy()
beta_values = df.index.tolist()
gamma_values = df.columns.tolist()
surface_plot = go.Surface(
x=gamma_values,
y=beta_values,
z=matrix,
coloraxis = 'coloraxis'
)
fig = go.Figure(data = surface_plot)
fig.show()
#Return optimum
return optimum
graph = graphs['custom']
optimal_parameters = plot_qaoa_energy_landscape(graph = graph)
print('Optimal parameters:')
print(optimal_parameters)
optimal_parameters = plot_qaoa_energy_landscape(graph = graph, cvar = 0.2)
print(optimal_parameters)
from qc_grader import grade_lab2_ex4
# Note that the grading function is expecting a python dictionary
# with the entries 'beta', 'gamma' and 'energy'
grade_lab2_ex4(optimal_parameters)
|
https://github.com/MonitSharma/Qiskit-Summer-School-and-Quantum-Challenges
|
MonitSharma
|
# General Imports
import numpy as np
# Visualisation Imports
import matplotlib.pyplot as plt
# Scikit Imports
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler, MinMaxScaler
# Qiskit Imports
from qiskit import Aer, execute
from qiskit.circuit import QuantumCircuit, Parameter, ParameterVector
from qiskit.circuit.library import PauliFeatureMap, ZFeatureMap, ZZFeatureMap
from qiskit.circuit.library import TwoLocal, NLocal, RealAmplitudes, EfficientSU2
from qiskit.circuit.library import HGate, RXGate, RYGate, RZGate, CXGate, CRXGate, CRZGate
from qiskit_machine_learning.kernels import QuantumKernel
# Load digits dataset
digits = datasets.load_digits(n_class=2)
# Plot example '0' and '1'
fig, axs = plt.subplots(1, 2, figsize=(6,3))
axs[0].set_axis_off()
axs[0].imshow(digits.images[0], cmap=plt.cm.gray_r, interpolation='nearest')
axs[1].set_axis_off()
axs[1].imshow(digits.images[1], cmap=plt.cm.gray_r, interpolation='nearest')
plt.show()
# Split dataset
sample_train, sample_test, label_train, label_test = train_test_split(
digits.data, digits.target, test_size=0.2, random_state=22)
# Reduce dimensions
n_dim = 4
pca = PCA(n_components=n_dim).fit(sample_train)
sample_train = pca.transform(sample_train)
sample_test = pca.transform(sample_test)
# Normalise
std_scale = StandardScaler().fit(sample_train)
sample_train = std_scale.transform(sample_train)
sample_test = std_scale.transform(sample_test)
# Scale
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)
# Select
train_size = 100
sample_train = sample_train[:train_size]
label_train = label_train[:train_size]
test_size = 20
sample_test = sample_test[:test_size]
label_test = label_test[:test_size]
print(sample_train[0], label_train[0])
print(sample_test[0], label_test[0])
# 3 features, depth 2
map_z = ZFeatureMap(feature_dimension=3, reps=2)
map_z.draw('mpl')
# 3 features, depth 1
map_zz = ZZFeatureMap(feature_dimension=3, reps=1)
map_zz.draw('mpl')
# 3 features, depth 1, linear entanglement
map_zz = ZZFeatureMap(feature_dimension=3, reps=1, entanglement='linear')
map_zz.draw('mpl')
# 3 features, depth 1, circular entanglement
map_zz = ZZFeatureMap(feature_dimension=3, reps=1, entanglement='circular')
map_zz.draw('mpl')
# 3 features, depth 1
map_pauli = PauliFeatureMap(feature_dimension=3, reps=1, paulis = ['X', 'Y', 'ZZ'])
map_pauli.draw('mpl')
def custom_data_map_func(x):
coeff = x[0] if len(x) == 1 else reduce(lambda m, n: m * n, np.sin(np.pi - x))
return coeff
map_customdatamap = PauliFeatureMap(feature_dimension=3, reps=1, paulis=['Z','ZZ'],
data_map_func=custom_data_map_func)
#map_customdatamap.draw() # qiskit isn't able to draw the circuit with np.sin in the custom data map
twolocal = TwoLocal(num_qubits=3, reps=2, rotation_blocks=['ry','rz'],
entanglement_blocks='cx', entanglement='circular', insert_barriers=True)
twolocal.draw('mpl')
twolocaln = NLocal(num_qubits=3, reps=2,
rotation_blocks=[RYGate(Parameter('a')), RZGate(Parameter('a'))],
entanglement_blocks=CXGate(),
entanglement='circular', insert_barriers=True)
twolocaln.draw('mpl')
# rotation block:
rot = QuantumCircuit(2)
params = ParameterVector('r', 2)
rot.ry(params[0], 0)
rot.rz(params[1], 1)
# entanglement block:
ent = QuantumCircuit(4)
params = ParameterVector('e', 3)
ent.crx(params[0], 0, 1)
ent.crx(params[1], 1, 2)
ent.crx(params[2], 2, 3)
nlocal = NLocal(num_qubits=6, rotation_blocks=rot, entanglement_blocks=ent,
entanglement='linear', insert_barriers=True)
nlocal.draw('mpl')
qubits = 3
repeats = 2
x = ParameterVector('x', length=qubits)
var_custom = QuantumCircuit(qubits)
for _ in range(repeats):
for i in range(qubits):
var_custom.rx(x[i], i)
for i in range(qubits):
for j in range(i + 1, qubits):
var_custom.cx(i, j)
var_custom.p(x[i] * x[j], j)
var_custom.cx(i, j)
var_custom.barrier()
var_custom.draw('mpl')
print(sample_train[0])
encode_map = ZZFeatureMap(feature_dimension=4, reps=2, entanglement='linear', insert_barriers=True)
encode_circuit = encode_map.bind_parameters(sample_train[0])
encode_circuit.draw(output='mpl')
x = [-0.1,0.2]
# YOUR CODE HERE
encode_map_x =ZZFeatureMap(feature_dimension=2, reps=4)
ex1_circuit =encode_map_x.bind_parameters(x)
ex1_circuit.draw(output='mpl')
from qc_grader import grade_lab3_ex1
# Note that the grading function is expecting a quantum circuit
grade_lab3_ex1(ex1_circuit)
zz_map = ZZFeatureMap(feature_dimension=4, reps=2, entanglement='linear', insert_barriers=True)
zz_kernel = QuantumKernel(feature_map=zz_map, quantum_instance=Aer.get_backend('statevector_simulator'))
print(sample_train[0])
print(sample_train[1])
zz_circuit = zz_kernel.construct_circuit(sample_train[0], sample_train[1])
zz_circuit.decompose().decompose().draw(output='mpl')
backend = Aer.get_backend('qasm_simulator')
job = execute(zz_circuit, backend, shots=8192,
seed_simulator=1024, seed_transpiler=1024)
counts = job.result().get_counts(zz_circuit)
counts['0000']/sum(counts.values())
matrix_train = zz_kernel.evaluate(x_vec=sample_train)
matrix_test = zz_kernel.evaluate(x_vec=sample_test, y_vec=sample_train)
fig, axs = plt.subplots(1, 2, figsize=(10, 5))
axs[0].imshow(np.asmatrix(matrix_train),
interpolation='nearest', origin='upper', cmap='Blues')
axs[0].set_title("training kernel matrix")
axs[1].imshow(np.asmatrix(matrix_test),
interpolation='nearest', origin='upper', cmap='Reds')
axs[1].set_title("testing kernel matrix")
plt.show()
x = [-0.1,0.2]
y = [0.4,-0.6]
# YOUR CODE HERE
encode_map_x2 = ZZFeatureMap(feature_dimension=2, reps=4)
zz_kernel_x2 =QuantumKernel(feature_map=encode_map_x2,quantum_instance=Aer.get_backend('statevector_simulator'))
zz_circuit_x2 =zz_kernel_x2.construct_circuit(x,y)
backend =Aer.get_backend('qasm_simulator')
job = execute(zz_circuit_x2,backend,shots=8192,
seed_simulator=1024, seed_transpiler=1024)
counts_x2 = job.result().get_counts(zz_circuit_x2)
amplitude= counts_x2['00']/sum(counts_x2.values())
from qc_grader import grade_lab3_ex2
# Note that the grading function is expecting a floating point number
grade_lab3_ex2(amplitude)
zzpc_svc = SVC(kernel='precomputed')
zzpc_svc.fit(matrix_train, label_train)
zzpc_score = zzpc_svc.score(matrix_test, label_test)
print(f'Precomputed kernel classification test score: {zzpc_score}')
zzcb_svc = SVC(kernel=zz_kernel.evaluate)
zzcb_svc.fit(sample_train, label_train)
zzcb_score = zzcb_svc.score(sample_test, label_test)
print(f'Callable kernel classification test score: {zzcb_score}')
classical_kernels = ['linear', 'poly', 'rbf', 'sigmoid']
for kernel in classical_kernels:
classical_svc = SVC(kernel=kernel)
classical_svc.fit(sample_train, label_train)
classical_score = classical_svc.score(sample_test, label_test)
print('%s kernel classification test score: %0.2f' % (kernel, classical_score))
|
https://github.com/MonitSharma/Qiskit-Summer-School-and-Quantum-Challenges
|
MonitSharma
|
from qiskit.circuit.library import RealAmplitudes
ansatz = RealAmplitudes(num_qubits=2, reps=1, entanglement='linear')
ansatz.draw('mpl', style='iqx')
from qiskit.opflow import Z, I
hamiltonian = Z ^ Z
from qiskit.opflow import StateFn
expectation = StateFn(hamiltonian, is_measurement=True) @ StateFn(ansatz)
import numpy as np
point = np.random.random(ansatz.num_parameters)
index = 2
from qiskit import Aer
from qiskit.utils import QuantumInstance
backend = Aer.get_backend('qasm_simulator')
q_instance = QuantumInstance(backend, shots = 8192, seed_simulator = 2718, seed_transpiler = 2718)
from qiskit.circuit import QuantumCircuit
from qiskit.opflow import Z, X
H = X ^ X
U = QuantumCircuit(2)
U.h(0)
U.cx(0, 1)
# YOUR CODE HERE
expectation = StateFn(hamiltonian, is_measurement=True) @ StateFn(U)
matmult_result =expectation.eval()
from qc_grader import grade_lab4_ex1
# Note that the grading function is expecting a complex number
grade_lab4_ex1(matmult_result)
from qiskit.opflow import CircuitSampler, PauliExpectation
sampler = CircuitSampler(q_instance)
# YOUR CODE HERE
sampler = CircuitSampler(q_instance) # q_instance is the QuantumInstance from the beginning of the notebook
expectation = StateFn(hamiltonian, is_measurement=True) @ StateFn(U)
in_pauli_basis = PauliExpectation().convert(expectation)
shots_result = sampler.convert(in_pauli_basis).eval()
from qc_grader import grade_lab4_ex2
# Note that the grading function is expecting a complex number
grade_lab4_ex2(shots_result)
from qiskit.opflow import PauliExpectation, CircuitSampler
expectation = StateFn(hamiltonian, is_measurement=True) @ StateFn(ansatz)
in_pauli_basis = PauliExpectation().convert(expectation)
sampler = CircuitSampler(q_instance)
def evaluate_expectation(x):
value_dict = dict(zip(ansatz.parameters, x))
result = sampler.convert(in_pauli_basis, params=value_dict).eval()
return np.real(result)
eps = 0.2
e_i = np.identity(point.size)[:, index] # identity vector with a 1 at index ``index``, otherwise 0
plus = point + eps * e_i
minus = point - eps * e_i
finite_difference = (evaluate_expectation(plus) - evaluate_expectation(minus)) / (2 * eps)
print(finite_difference)
from qiskit.opflow import Gradient
expectation = StateFn(hamiltonian, is_measurement=True) @ StateFn(ansatz)
shifter = Gradient('fin_diff', analytic=False, epsilon=eps)
grad = shifter.convert(expectation, params=ansatz.parameters[index])
print(grad)
value_dict = dict(zip(ansatz.parameters, point))
sampler.convert(grad, value_dict).eval().real
eps = np.pi / 2
e_i = np.identity(point.size)[:, index] # identity vector with a 1 at index ``index``, otherwise 0
plus = point + eps * e_i
minus = point - eps * e_i
finite_difference = (evaluate_expectation(plus) - evaluate_expectation(minus)) / 2
print(finite_difference)
expectation = StateFn(hamiltonian, is_measurement=True) @ StateFn(ansatz)
shifter = Gradient() # parameter-shift rule is the default
grad = shifter.convert(expectation, params=ansatz.parameters[index])
sampler.convert(grad, value_dict).eval().real
expectation = StateFn(hamiltonian, is_measurement=True) @ StateFn(ansatz)
shifter = Gradient('lin_comb') # parameter-shift rule is the default
grad = shifter.convert(expectation, params=ansatz.parameters[index])
sampler.convert(grad, value_dict).eval().real
# initial_point = np.random.random(ansatz.num_parameters)
initial_point = np.array([0.43253681, 0.09507794, 0.42805949, 0.34210341])
expectation = StateFn(hamiltonian, is_measurement=True).compose(StateFn(ansatz))
gradient = Gradient().convert(expectation)
gradient_in_pauli_basis = PauliExpectation().convert(gradient)
sampler = CircuitSampler(q_instance)
def evaluate_gradient(x):
value_dict = dict(zip(ansatz.parameters, x))
result = sampler.convert(gradient_in_pauli_basis, params=value_dict).eval() # add parameters in here!
return np.real(result)
# Note: The GradientDescent class will be released with Qiskit 0.28.0 and can then be imported as:
# from qiskit.algorithms.optimizers import GradientDescent
from qc_grader.gradient_descent import GradientDescent
gd_loss = []
def gd_callback(nfevs, x, fx, stepsize):
gd_loss.append(fx)
gd = GradientDescent(maxiter=300, learning_rate=0.01, callback=gd_callback)
x_opt, fx_opt, nfevs = gd.optimize(initial_point.size, # number of parameters
evaluate_expectation, # function to minimize
gradient_function=evaluate_gradient, # function to evaluate the gradient
initial_point=initial_point) # initial point
import matplotlib
import matplotlib.pyplot as plt
matplotlib.rcParams['font.size'] = 14
plt.figure(figsize=(12, 6))
plt.plot(gd_loss, label='vanilla gradient descent')
plt.axhline(-1, ls='--', c='tab:red', label='target')
plt.ylabel('loss')
plt.xlabel('iterations')
plt.legend();
from qiskit.opflow import NaturalGradient
expectation = StateFn(hamiltonian, is_measurement=True).compose(StateFn(ansatz))
natural_gradient = NaturalGradient(regularization='ridge').convert(expectation)
natural_gradient_in_pauli_basis = PauliExpectation().convert(natural_gradient)
sampler = CircuitSampler(q_instance, caching="all")
def evaluate_natural_gradient(x):
value_dict = dict(zip(ansatz.parameters, x))
result = sampler.convert(natural_gradient, params=value_dict).eval()
return np.real(result)
print('Vanilla gradient:', evaluate_gradient(initial_point))
print('Natural gradient:', evaluate_natural_gradient(initial_point))
qng_loss = []
def qng_callback(nfevs, x, fx, stepsize):
qng_loss.append(fx)
qng = GradientDescent(maxiter=300, learning_rate=0.01, callback=qng_callback)
x_opt, fx_opt, nfevs = qng.optimize(initial_point.size,
evaluate_expectation,
gradient_function=evaluate_natural_gradient,
initial_point=initial_point)
def plot_loss():
plt.figure(figsize=(12, 6))
plt.plot(gd_loss, 'tab:blue', label='vanilla gradient descent')
plt.plot(qng_loss, 'tab:green', label='quantum natural gradient')
plt.axhline(-1, c='tab:red', ls='--', label='target')
plt.ylabel('loss')
plt.xlabel('iterations')
plt.legend()
plot_loss()
from qc_grader.spsa import SPSA
spsa_loss = []
def spsa_callback(nfev, x, fx, stepsize, accepted):
spsa_loss.append(fx)
spsa = SPSA(maxiter=300, learning_rate=0.01, perturbation=0.01, callback=spsa_callback)
x_opt, fx_opt, nfevs = spsa.optimize(initial_point.size,
evaluate_expectation,
initial_point=initial_point)
def plot_loss():
plt.figure(figsize=(12, 6))
plt.plot(gd_loss, 'tab:blue', label='vanilla gradient descent')
plt.plot(qng_loss, 'tab:green', label='quantum natural gradient')
plt.plot(spsa_loss, 'tab:blue', ls='--', label='SPSA')
plt.axhline(-1, c='tab:red', ls='--', label='target')
plt.ylabel('loss')
plt.xlabel('iterations')
plt.legend()
plot_loss()
# Note: The QNSPSA class will be released with Qiskit 0.28.0 and can then be imported as:
# from qiskit.algorithms.optimizers import QNSPSA
from qc_grader.qnspsa import QNSPSA
qnspsa_loss = []
def qnspsa_callback(nfev, x, fx, stepsize, accepted):
qnspsa_loss.append(fx)
fidelity = QNSPSA.get_fidelity(ansatz, q_instance, expectation=PauliExpectation())
qnspsa = QNSPSA(fidelity, maxiter=300, learning_rate=0.01, perturbation=0.01, callback=qnspsa_callback)
x_opt, fx_opt, nfevs = qnspsa.optimize(initial_point.size,
evaluate_expectation,
initial_point=initial_point)
def plot_loss():
plt.figure(figsize=(12, 6))
plt.plot(gd_loss, 'tab:blue', label='vanilla gradient descent')
plt.plot(qng_loss, 'tab:green', label='quantum natural gradient')
plt.plot(spsa_loss, 'tab:blue', ls='--', label='SPSA')
plt.plot(qnspsa_loss, 'tab:green', ls='--', label='QN-SPSA')
plt.axhline(-1, c='tab:red', ls='--', label='target')
plt.ylabel('loss')
plt.xlabel('iterations')
plt.legend()
plot_loss()
autospsa_loss = []
def autospsa_callback(nfev, x, fx, stepsize, accepted):
autospsa_loss.append(fx)
autospsa = SPSA(maxiter=300, learning_rate=None, perturbation=None, callback=autospsa_callback)
x_opt, fx_opt, nfevs = autospsa.optimize(initial_point.size,
evaluate_expectation,
initial_point=initial_point)
def plot_loss():
plt.figure(figsize=(12, 6))
plt.plot(gd_loss, 'tab:blue', label='vanilla gradient descent')
plt.plot(qng_loss, 'tab:green', label='quantum natural gradient')
plt.plot(spsa_loss, 'tab:blue', ls='--', label='SPSA')
plt.plot(qnspsa_loss, 'tab:green', ls='--', label='QN-SPSA')
plt.plot(autospsa_loss, 'tab:red', label='Powerlaw SPSA')
plt.axhline(-1, c='tab:red', ls='--', label='target')
plt.ylabel('loss')
plt.xlabel('iterations')
plt.legend()
plot_loss()
H_tfi = -(Z^Z^I)-(I^Z^Z)-(X^I^I)-(I^X^I)-(I^I^X)
from qc_grader import grade_lab4_ex3
# Note that the grading function is expecting a Hamiltonian
grade_lab4_ex3(H_tfi)
from qiskit.circuit.library import EfficientSU2
efficient_su2 = EfficientSU2(3, entanglement="linear", reps=2)
tfi_sampler = CircuitSampler(q_instance)
def evaluate_tfi(parameters):
exp = StateFn(H_tfi, is_measurement=True).compose(StateFn(efficient_su2))
value_dict = dict(zip(efficient_su2.parameters, parameters))
result = tfi_sampler.convert(PauliExpectation().convert(exp), params=value_dict).eval()
return np.real(result)
# target energy
tfi_target = -3.4939592074349326
# initial point for reproducibility
tfi_init = np.array([0.95667807, 0.06192812, 0.47615196, 0.83809827, 0.89022282,
0.27140831, 0.9540853 , 0.41374024, 0.92595507, 0.76150126,
0.8701938 , 0.05096063, 0.25476016, 0.71807858, 0.85661325,
0.48311132, 0.43623886, 0.6371297 ])
tfi_result = SPSA(maxiter=300, learning_rate=None, perturbation=None)
tfi_result = tfi_result.optimize(tfi_init.size, evaluate_tfi, initial_point=tfi_init)
tfi_minimum = tfi_result[1]
print("Error:", np.abs(tfi_result[1] - tfi_target))
from qc_grader import grade_lab4_ex4
# Note that the grading function is expecting a floating point number
grade_lab4_ex4(tfi_minimum)
from qiskit_machine_learning.datasets import ad_hoc_data
training_features, training_labels, test_features, test_labels = ad_hoc_data(
training_size=20, test_size=10, n=2, one_hot=False, gap=0.5
)
# the training labels are in {0, 1} but we'll use {-1, 1} as class labels!
training_labels = 2 * training_labels - 1
test_labels = 2 * test_labels - 1
def plot_sampled_data():
from matplotlib.patches import Patch
from matplotlib.lines import Line2D
import matplotlib.pyplot as plt
plt.figure(figsize=(12,6))
for feature, label in zip(training_features, training_labels):
marker = 'o'
color = 'tab:green' if label == -1 else 'tab:blue'
plt.scatter(feature[0], feature[1], marker=marker, s=100, color=color)
for feature, label in zip(test_features, test_labels):
marker = 's'
plt.scatter(feature[0], feature[1], marker=marker, s=100, facecolor='none', edgecolor='k')
legend_elements = [
Line2D([0], [0], marker='o', c='w', mfc='tab:green', label='A', ms=15),
Line2D([0], [0], marker='o', c='w', mfc='tab:blue', label='B', ms=15),
Line2D([0], [0], marker='s', c='w', mfc='none', mec='k', label='test features', ms=10)
]
plt.legend(handles=legend_elements, bbox_to_anchor=(1, 0.6))
plt.title('Training & test data')
plt.xlabel('$x$')
plt.ylabel('$y$')
plot_sampled_data()
from qiskit.circuit.library import ZZFeatureMap
dim = 2
feature_map = ZZFeatureMap(dim, reps=1) # let's keep it simple!
feature_map.draw('mpl', style='iqx')
ansatz = RealAmplitudes(num_qubits=dim, entanglement='linear', reps=1) # also simple here!
ansatz.draw('mpl', style='iqx')
circuit = feature_map.compose(ansatz)
circuit.draw('mpl', style='iqx')
hamiltonian = Z ^ Z # global Z operators
gd_qnn_loss = []
def gd_qnn_callback(*args):
gd_qnn_loss.append(args[2])
gd = GradientDescent(maxiter=100, learning_rate=0.01, callback=gd_qnn_callback)
from qiskit_machine_learning.neural_networks import OpflowQNN
qnn_expectation = StateFn(hamiltonian, is_measurement=True) @ StateFn(circuit)
qnn = OpflowQNN(qnn_expectation,
input_params=list(feature_map.parameters),
weight_params=list(ansatz.parameters),
exp_val=PauliExpectation(),
gradient=Gradient(), # <-- Parameter-Shift gradients
quantum_instance=q_instance)
from qiskit_machine_learning.algorithms import NeuralNetworkClassifier
#initial_point = np.array([0.2, 0.1, 0.3, 0.4])
classifier = NeuralNetworkClassifier(qnn, optimizer=gd)
classifier.fit(training_features, training_labels);
predicted = classifier.predict(test_features)
def plot_predicted():
from matplotlib.lines import Line2D
plt.figure(figsize=(12, 6))
for feature, label in zip(training_features, training_labels):
marker = 'o'
color = 'tab:green' if label == -1 else 'tab:blue'
plt.scatter(feature[0], feature[1], marker=marker, s=100, color=color)
for feature, label, pred in zip(test_features, test_labels, predicted):
marker = 's'
color = 'tab:green' if pred == -1 else 'tab:blue'
if label != pred: # mark wrongly classified
plt.scatter(feature[0], feature[1], marker='o', s=500, linewidths=2.5,
facecolor='none', edgecolor='tab:red')
plt.scatter(feature[0], feature[1], marker=marker, s=100, color=color)
legend_elements = [
Line2D([0], [0], marker='o', c='w', mfc='tab:green', label='A', ms=15),
Line2D([0], [0], marker='o', c='w', mfc='tab:blue', label='B', ms=15),
Line2D([0], [0], marker='s', c='w', mfc='tab:green', label='predict A', ms=10),
Line2D([0], [0], marker='s', c='w', mfc='tab:blue', label='predict B', ms=10),
Line2D([0], [0], marker='o', c='w', mfc='none', mec='tab:red', label='wrongly classified', mew=2, ms=15)
]
plt.legend(handles=legend_elements, bbox_to_anchor=(1, 0.7))
plt.title('Training & test data')
plt.xlabel('$x$')
plt.ylabel('$y$')
plot_predicted()
qng_qnn_loss = []
def qng_qnn_callback(*args):
qng_qnn_loss.append(args[2])
gd = GradientDescent(maxiter=100, learning_rate=0.01, callback=qng_qnn_callback)
qnn = OpflowQNN(qnn_expectation,
input_params=list(feature_map.parameters),
weight_params=list(ansatz.parameters),
gradient=NaturalGradient(regularization='ridge'), # <-- using Natural Gradients!
quantum_instance=q_instance)
classifier = NeuralNetworkClassifier(qnn, optimizer=gd)#, initial_point=initial_point)
classifier.fit(training_features, training_labels);
def plot_losses():
plt.figure(figsize=(12, 6))
plt.plot(gd_qnn_loss, 'tab:blue', marker='o', label='vanilla gradients')
plt.plot(qng_qnn_loss, 'tab:green', marker='o', label='natural gradients')
plt.xlabel('iterations')
plt.ylabel('loss')
plt.legend(loc='best')
plot_losses()
from qiskit.opflow import I
def sample_gradients(num_qubits, reps, local=False):
"""Sample the gradient of our model for ``num_qubits`` qubits and ``reps`` repetitions.
We sample 100 times for random parameters and compute the gradient of the first RY rotation gate.
"""
index = num_qubits - 1
# you can also exchange this for a local operator and observe the same!
if local:
operator = Z ^ Z ^ (I ^ (num_qubits - 2))
else:
operator = Z ^ num_qubits
# real amplitudes ansatz
ansatz = RealAmplitudes(num_qubits, entanglement='linear', reps=reps)
# construct Gradient we want to evaluate for different values
expectation = StateFn(operator, is_measurement=True).compose(StateFn(ansatz))
grad = Gradient().convert(expectation, params=ansatz.parameters[index])
# evaluate for 100 different, random parameter values
num_points = 100
grads = []
for _ in range(num_points):
# points are uniformly chosen from [0, pi]
point = np.random.uniform(0, np.pi, ansatz.num_parameters)
value_dict = dict(zip(ansatz.parameters, point))
grads.append(sampler.convert(grad, value_dict).eval())
return grads
num_qubits = list(range(2, 13))
reps = num_qubits # number of layers = numbers of qubits
gradients = [sample_gradients(n, r) for n, r in zip(num_qubits, reps)]
fit = np.polyfit(num_qubits, np.log(np.var(gradients, axis=1)), deg=1)
x = np.linspace(num_qubits[0], num_qubits[-1], 200)
plt.figure(figsize=(12, 6))
plt.semilogy(num_qubits, np.var(gradients, axis=1), 'o-', label='measured variance')
plt.semilogy(x, np.exp(fit[0] * x + fit[1]), 'r--', label=f'exponential fit w/ {fit[0]:.2f}')
plt.xlabel('number of qubits')
plt.ylabel(r'$\mathrm{Var}[\partial_{\theta 1} \langle E(\theta) \rangle]$')
plt.legend(loc='best');
from qiskit.opflow import NaturalGradient
def sample_natural_gradients(num_qubits, reps):
index = num_qubits - 1
operator = Z ^ num_qubits
ansatz = RealAmplitudes(num_qubits, entanglement='linear', reps=reps)
expectation = StateFn(operator, is_measurement=True).compose(StateFn(ansatz))
grad = # TODO: ``grad`` should be the natural gradient for the parameter at index ``index``.
# Hint: Check the ``sample_gradients`` function, this one is almost the same.
grad = NaturalGradient().convert(expectation, params=ansatz.parameters[index])
num_points = 100
grads = []
for _ in range(num_points):
point = np.random.uniform(0, np.pi, ansatz.num_parameters)
value_dict = dict(zip(ansatz.parameters, point))
grads.append(sampler.convert(grad, value_dict).eval())
return grads
num_qubits = list(range(2, 13))
reps = num_qubits # number of layers = numbers of qubits
natural_gradients = [sample_natural_gradients(n, r) for n, r in zip(num_qubits, reps)]
fit = np.polyfit(num_qubits, np.log(np.var(natural_gradients, axis=1)), deg=1)
x = np.linspace(num_qubits[0], num_qubits[-1], 200)
plt.figure(figsize=(12, 6))
plt.semilogy(num_qubits, np.var(gradients, axis=1), 'o-', label='vanilla gradients')
plt.semilogy(num_qubits, np.var(natural_gradients, axis=1), 's-', label='natural gradients')
plt.semilogy(x, np.exp(fit[0] * x + fit[1]), 'r--', label=f'exponential fit w/ {float(fit[0]):.2f}')
plt.xlabel('number of qubits')
plt.ylabel(r'$\mathrm{Var}[\partial_{\theta 1} \langle E(\theta) \rangle]$')
plt.legend(loc='best');
num_qubits = list(range(2, 13))
fixed_depth_global_gradients = [sample_gradients(n, 1) for n in num_qubits]
fit = np.polyfit(num_qubits, np.log(np.var(fixed_depth_global_gradients, axis=1)), deg=1)
x = np.linspace(num_qubits[0], num_qubits[-1], 200)
plt.figure(figsize=(12, 6))
plt.semilogy(num_qubits, np.var(gradients, axis=1), 'o-', label='global cost, linear depth')
plt.semilogy(num_qubits, np.var(fixed_depth_global_gradients, axis=1), 'o-', label='global cost, constant depth')
plt.semilogy(x, np.exp(fit[0] * x + fit[1]), 'r--', label=f'exponential fit w/ {fit[0]:.2f}')
plt.xlabel('number of qubits')
plt.ylabel(r'$\mathrm{Var}[\partial_{\theta 1} \langle E(\theta) \rangle]$')
plt.legend(loc='best');
num_qubits = list(range(2, 13))
linear_depth_local_gradients = [sample_gradients(n, n, local=True) for n in num_qubits]
fit = np.polyfit(num_qubits, np.log(np.var(linear_depth_local_gradients, axis=1)), deg=1)
x = np.linspace(num_qubits[0], num_qubits[-1], 200)
plt.figure(figsize=(12, 6))
plt.semilogy(num_qubits, np.var(gradients, axis=1), 'o-', label='global cost, linear depth')
plt.semilogy(num_qubits, np.var(fixed_depth_global_gradients, axis=1), 'o-', label='global cost, constant depth')
plt.semilogy(num_qubits, np.var(linear_depth_local_gradients, axis=1), 'o-', label='local cost, linear depth')
plt.semilogy(x, np.exp(fit[0] * x + fit[1]), 'r--', label=f'exponential fit w/ {fit[0]:.2f}')
plt.xlabel('number of qubits')
plt.ylabel(r'$\mathrm{Var}[\partial_{\theta 1} \langle E(\theta) \rangle]$')
plt.legend(loc='best');
num_qubits = list(range(2, 13))
fixed_depth_local_gradients = [sample_gradients(n, 1, local=True) for n in num_qubits]
fit = np.polyfit(num_qubits, np.log(np.var(fixed_depth_local_gradients, axis=1)), deg=1)
x = np.linspace(num_qubits[0], num_qubits[-1], 200)
plt.figure(figsize=(12, 6))
plt.semilogy(num_qubits, np.var(gradients, axis=1), 'o-', label='global cost, linear depth')
plt.semilogy(num_qubits, np.var(fixed_depth_global_gradients, axis=1), 'o-', label='global cost, constant depth')
plt.semilogy(num_qubits, np.var(linear_depth_local_gradients, axis=1), 'o-', label='local cost, linear depth')
plt.semilogy(num_qubits, np.var(fixed_depth_local_gradients, axis=1), 'o-', label='local cost, constant depth')
plt.semilogy(x, np.exp(fit[0] * x + fit[1]), 'r--', label=f'exponential fit w/ {fit[0]:.2f}')
plt.xlabel('number of qubits')
plt.ylabel(r'$\mathrm{Var}[\partial_{\theta 1} \langle E(\theta) \rangle]$')
plt.legend(loc='best');
num_qubits = 6
operator = Z ^ Z ^ (I ^ (num_qubits - 4))
def minimize(circuit, optimizer):
initial_point = np.random.random(circuit.num_parameters)
exp = StateFn(operator, is_measurement=True) @ StateFn(circuit)
grad = Gradient().convert(exp)
# pauli basis
exp = PauliExpectation().convert(exp)
grad = PauliExpectation().convert(grad)
sampler = CircuitSampler(q_instance, caching="all")
def loss(x):
values_dict = dict(zip(circuit.parameters, x))
return np.real(sampler.convert(exp, values_dict).eval())
def gradient(x):
values_dict = dict(zip(circuit.parameters, x))
return np.real(sampler.convert(grad, values_dict).eval())
return optimizer.optimize(circuit.num_parameters, loss, gradient, initial_point=initial_point)
circuit = RealAmplitudes(4, reps=1, entanglement='linear')
circuit.draw('mpl', style='iqx')
circuit.reps = 5
circuit.draw('mpl', style='iqx')
def layerwise_training(ansatz, max_num_layers, optimizer):
optimal_parameters = []
fopt = None
for reps in range(1, max_num_layers):
ansatz.reps = reps
# bind already optimized parameters
values_dict = dict(zip(ansatz.parameters, optimal_parameters))
partially_bound = ansatz.bind_parameters(values_dict)
xopt, fopt, _ = minimize(partially_bound, optimizer)
print('Circuit depth:', ansatz.depth(), 'best value:', fopt)
optimal_parameters += list(xopt)
return fopt, optimal_parameters
ansatz = RealAmplitudes(4, entanglement='linear')
optimizer = GradientDescent(maxiter=50)
np.random.seed(12)
fopt, optimal_parameters = layerwise_training(ansatz, 4, optimizer)
|
https://github.com/MonitSharma/Qiskit-Summer-School-and-Quantum-Challenges
|
MonitSharma
|
# General tools
import numpy as np
import matplotlib.pyplot as plt
# Qiskit Circuit Functions
from qiskit import execute,QuantumCircuit, QuantumRegister, ClassicalRegister, Aer, transpile
import qiskit.quantum_info as qi
# Tomography functions
from qiskit.ignis.verification.tomography import process_tomography_circuits, ProcessTomographyFitter
from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter
import warnings
warnings.filterwarnings('ignore')
target = QuantumCircuit(2)
#target = # YOUR CODE HERE
target.h(0)
target.h(1)
target.rx(np.pi/2,0)
target.rx(np.pi/2,1)
target.cx(0,1)
target.p(np.pi,1)
target.cx(0,1)
target_unitary = qi.Operator(target)
target.draw('mpl')
from qc_grader import grade_lab5_ex1
# Note that the grading function is expecting a quantum circuit with no measurements
grade_lab5_ex1(target)
simulator = Aer.get_backend('qasm_simulator')
qpt_circs = process_tomography_circuits(target,measured_qubits=[0,1])# YOUR CODE HERE
qpt_job = execute(qpt_circs,simulator,seed_simulator=3145,seed_transpiler=3145,shots=8192)
qpt_result = qpt_job.result()
# YOUR CODE HERE
qpt_tomo= ProcessTomographyFitter(qpt_result,qpt_circs)
Choi_qpt= qpt_tomo.fit(method='lstsq')
fidelity = qi.average_gate_fidelity(Choi_qpt,target_unitary)
from qc_grader import grade_lab5_ex2
# Note that the grading function is expecting a floating point number
grade_lab5_ex2(fidelity)
# T1 and T2 values for qubits 0-3
T1s = [15000, 19000, 22000, 14000]
T2s = [30000, 25000, 18000, 28000]
# Instruction times (in nanoseconds)
time_u1 = 0 # virtual gate
time_u2 = 50 # (single X90 pulse)
time_u3 = 100 # (two X90 pulses)
time_cx = 300
time_reset = 1000 # 1 microsecond
time_measure = 1000 # 1 microsecond
from qiskit.providers.aer.noise import thermal_relaxation_error
from qiskit.providers.aer.noise import NoiseModel
# QuantumError objects
errors_reset = [thermal_relaxation_error(t1, t2, time_reset)
for t1, t2 in zip(T1s, T2s)]
errors_measure = [thermal_relaxation_error(t1, t2, time_measure)
for t1, t2 in zip(T1s, T2s)]
errors_u1 = [thermal_relaxation_error(t1, t2, time_u1)
for t1, t2 in zip(T1s, T2s)]
errors_u2 = [thermal_relaxation_error(t1, t2, time_u2)
for t1, t2 in zip(T1s, T2s)]
errors_u3 = [thermal_relaxation_error(t1, t2, time_u3)
for t1, t2 in zip(T1s, T2s)]
errors_cx = [[thermal_relaxation_error(t1a, t2a, time_cx).expand(
thermal_relaxation_error(t1b, t2b, time_cx))
for t1a, t2a in zip(T1s, T2s)]
for t1b, t2b in zip(T1s, T2s)]
# Add errors to noise model
noise_thermal = NoiseModel()
for j in range(4):
noise_thermal.add_quantum_error(errors_measure[j],'measure',[j])
noise_thermal.add_quantum_error(errors_reset[j],'reset',[j])
noise_thermal.add_quantum_error(errors_u3[j],'u3',[j])
noise_thermal.add_quantum_error(errors_u2[j],'u2',[j])
noise_thermal.add_quantum_error(errors_u1[j],'u1',[j])
for k in range(4):
noise_thermal.add_quantum_error(errors_cx[j][k],'cx',[j,k])
# YOUR CODE HERE
from qc_grader import grade_lab5_ex3
# Note that the grading function is expecting a NoiseModel
grade_lab5_ex3(noise_thermal)
np.random.seed(0)
noise_qpt_circs = process_tomography_circuits(target,measured_qubits=[0,1])# YOUR CODE HERE
noise_qpt_job = execute(noise_qpt_circs,simulator,seed_simulator=3145,seed_transpiler=3145,shots=8192,noise_model=noise_thermal)
noise_qpt_result = noise_qpt_job.result()
# YOUR CODE HERE
noise_qpt_tomo= ProcessTomographyFitter(noise_qpt_result,noise_qpt_circs)
noise_Choi_qpt= noise_qpt_tomo.fit(method='lstsq')
fidelity = qi.average_gate_fidelity(noise_Choi_qpt,target_unitary)
from qc_grader import grade_lab5_ex4
# Note that the grading function is expecting a floating point number
grade_lab5_ex4(fidelity)
np.random.seed(0)
# YOUR CODE HERE
#qr = QuantumRegister(2)
qubit_list = [0,1]
meas_calibs, state_labels = complete_meas_cal(qubit_list=qubit_list)
meas_calibs_job = execute(meas_calibs,simulator,seed_simulator=3145,seed_transpiler=3145,shots=8192,noise_model=noise_thermal)
cal_results = meas_calibs_job.result()
meas_fitter = CompleteMeasFitter(cal_results, state_labels, qubit_list=qubit_list)
Cal_result = meas_fitter.filter.apply(noise_qpt_result)
# YOUR CODE HERE
Cal_qpt_tomo= ProcessTomographyFitter(Cal_result,noise_qpt_circs)
Cal_Choi_qpt= Cal_qpt_tomo.fit(method='lstsq')
fidelity = qi.average_gate_fidelity(Cal_Choi_qpt,target_unitary)
from qc_grader import grade_lab5_ex5
# Note that the grading function is expecting a floating point number
grade_lab5_ex5(fidelity)
|
https://github.com/MonitSharma/Qiskit-Summer-School-and-Quantum-Challenges
|
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()
# Qiskit module
from qiskit import QuantumCircuit
import qiskit.circuit.library as circuit_library
import qiskit.quantum_info as qi
import qiskit.ignis.mitigation as mit
# Qiskit tools for noisy simulation
from qiskit.providers.aer import QasmSimulator
from qiskit.providers.aer.noise import NoiseModel
from qiskit.providers.aer.utils import insert_noise
# Qiskit tools for running and monitoring jobs
from qiskit import execute
from qiskit.tools.monitor import job_monitor
# Other imports
import numpy as np
# Suppress warnings
import warnings
warnings.filterwarnings('ignore')
num_qubits = 7
# adjacency matrix for `ibmq_casablanca`
adjmat = [
[0, 1, 0, 0, 0, 0, 0],
[1, 0, 1, 1, 0, 0, 0],
[0, 1, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 1, 0],
[0, 0, 0, 0, 0, 1, 0],
[0, 0, 0, 1, 1, 0, 1],
[0, 0, 0, 0, 0, 1, 0]]
def create_graph_state():
graph_state_circuit = circuit_library.GraphState(adjmat)
return graph_state_circuit
# the graph state can be created using Qiskit's circuit library
state_circuit = create_graph_state()
state_circuit.draw()
def compute_stabilizer_group(circuit):
"""Compute the stabilizer group for stabilizer circuit."""
state = qi.Statevector.from_instruction(circuit)
labels = []
for i in qi.pauli_basis(state.num_qubits):
val = round(qi.state_fidelity(i.to_matrix()[0], state, validate=False))
if val != 0:
label = i.to_labels()[0]
if val == 1:
label = '+' + label
else:
label = '-' + label
labels.append(label)
return labels
def stabilizer_coeff_pauli(stabilizer):
"""Return the 1 or -1 coeff and Pauli label."""
coeff = 1
pauli = coeff
if stabilizer[0] == '-':
coeff = -1
if stabilizer[0] in ['+', '-']:
pauli = stabilizer[1:]
else:
pauli = stabilizer
return coeff, pauli
def stabilizer_measure_circuit(stabilizer, initial_circuit=None):
"""Return a stabilizer measurement circuits.
Args:
stabilizer (str): a stabilizer string
initial_circuit (QuantumCircuit): Optional, the initial circuit.
Returns:
QuantumCircuit: the circuit with stabilizer measurements.
"""
_, pauli = stabilizer_coeff_pauli(stabilizer)
if initial_circuit is None:
circ = QuantumCircuit(len(pauli))
else:
circ = initial_circuit.copy()
for i, s in enumerate(reversed(pauli)):
if s == 'X':
circ.h(i)
if s == 'Y':
circ.sdg(i)
circ.h(i)
circ.measure_all()
return circ
## Compute the stabilizers for this graph state
generators = qi.Clifford(state_circuit).stabilizer.pauli.to_labels()
stabilizers = compute_stabilizer_group(state_circuit)
print('Stabilizers:', stabilizers)
print('Generators:', generators)
## Append the stabilizer measurements to the graph state circuit
stabilizer_circuits = [stabilizer_measure_circuit(stab, state_circuit)
for stab in stabilizers]
stabilizer_circuits[0].draw()
labels = ['0000000', '0000011', '0000101',
'0001001', '0001010', '0001100',
'0010001', '0010010', '0010100', '0011000',
'0100001', '0100010', '0100100', '0101000', '0110000',
'1000001', '1000010', '1000100', '1001000', '1010000', '1100000',
'1111111']
meas_cal_circuits, metadata = mit.expval_meas_mitigator_circuits(num_qubits, labels=labels)
[meas_cal_circuits_full, state_labels] = mit.complete_meas_cal(range(num_qubits))
#backend = QasmSimulator.from_backend(provider.get_backend('ibmq_casablanca'))
IBMQ.load_account() # Load account from disk
IBMQ.providers()
from qiskit import IBMQ, assemble, transpile
from qiskit.circuit.random import random_circuit
backend = provider.backend.ibmq_qasm_simulator
reps = 10
all_jobs = []
all_jobs_mit = []
for ii in range(reps):
# Run QPT on backend
shots = 8192
il = [0,1,2,3,4,5,6]
job_backend = execute(stabilizer_circuits, backend, shots=shots, initial_layout=il)
job_mit_backend = execute(meas_cal_circuits, backend, shots=shots, initial_layout=il)
print('Job IDs ({}/{}): \n measurement calibration: {}\n stabilizer measurements: {}'.format(
ii+1, reps, job_mit_backend.job_id(), job_backend.job_id()))
all_jobs.append(job_backend)
all_jobs_mit.append(job_mit_backend)
for job in all_jobs:
job_monitor(job)
try:
if job.error_message() is not None:
print(job.error_message())
except:
pass
result_backend = []
result_mit_backend = []
for job in all_jobs:
# Retrieve results (this may take a while depending on the queue)
result_backend.append(job.result())
for job in all_jobs_mit:
result_mit_backend.append(job.result())
def stabilizer_measure_diagonal(stabilizer):
"""Return the diagonal vector for a stabilizer measurement.
Args:
stabilizer (str): a stabilizer string
Returns:
np.ndarray: the diagonal for measurement in the stabilizer basis.
"""
coeff, pauli = stabilizer_coeff_pauli(stabilizer)
diag = np.array([1])
for s in reversed(pauli):
if s == 'I':
tmp = np.array([1, 1])
else:
tmp = np.array([1, -1])
diag = np.kron(tmp, diag)
return coeff * diag
def stabilizer_fidelity(expvals, stddevs=None):
"""Compute stabilizer state fidelity from stabilizer expvals."""
mean = np.mean(expvals)
if stddevs is None:
return mean
stddev = np.sqrt(np.sum(stddevs ** 2))
return mean, stddev
def stabilizer_expvals(result, stabilizers, meas_mitigator=None):
"""Compute expectation values from stabilizer measurement results."""
### YOUR CODE GOES HERE -- START
expvals = []
stddevs = []
for i, stab in enumerate(stabilizers):
expval, stddev = mit.expectation_value(
result.get_counts(i),
diagonal=stabilizer_measure_diagonal(stab),
meas_mitigator=meas_mitigator)
expvals.append(expval)
stddevs.append(stddev)
return np.array(expvals), np.array(stddevs)
## Mitigate the stabilizer expectation values
F_nomit_backend = []
F_mit_backend = []
for ii in range(reps):
# Unmitigated Expectation Values
expvals_nomit_b, stddevs_nomit_b = stabilizer_expvals(
result_backend[ii], stabilizers)
# Fit measurement error mitigators
mitigator_backend = mit.ExpvalMeasMitigatorFitter(result_mit_backend[ii], metadata).fit()
# Measurement error mitigated expectation values
expvals_mit_b, stddevs_mit_b = stabilizer_expvals(
result_backend[ii], stabilizers, meas_mitigator=mitigator_backend)
# save the fidelities for this iteration
F_nomit_backend.append(stabilizer_fidelity(expvals_nomit_b, stddevs_nomit_b)[0])
F_mit_backend.append(stabilizer_fidelity(expvals_mit_b, stddevs_mit_b)[0])
## The final results
print('Graph-state fidelity estimates')
print('\nNo mitigation')
print('F({}) = {:.3f} \u00B1 {:.3f}'.format(properties.backend_name, np.mean(F_nomit_backend), np.std(F_nomit_backend)))
print('\nCTMP error mitigation')
print('F({}) = {:.3f} \u00B1 {:.3f}'.format(properties.backend_name, np.mean(F_mit_backend), np.std(F_mit_backend)))
|
https://github.com/MonitSharma/Qiskit-Summer-School-and-Quantum-Challenges
|
MonitSharma
|
import numpy as np
# Importing standard Qiskit libraries
from qiskit import QuantumCircuit, transpile, assemble, Aer, IBMQ, execute
from qiskit.quantum_info import Statevector
from qiskit.visualization import plot_bloch_multivector, plot_histogram
from qiskit_textbook.problems import dj_problem_oracle
def lab1_ex1():
qc = QuantumCircuit(1)
#
#
# FILL YOUR CODE IN HERE
#
#
qc.x(0)
return qc
state = Statevector.from_instruction(lab1_ex1())
plot_bloch_multivector(state)
from qc_grader import grade_lab1_ex1
# Note that the grading function is expecting a quantum circuit without measurements
grade_lab1_ex1(lab1_ex1())
def lab1_ex2():
qc = QuantumCircuit(1)
#
#
# FILL YOUR CODE IN HERE
#
#
qc.h(0)
return qc
state = Statevector.from_instruction(lab1_ex2())
plot_bloch_multivector(state)
from qc_grader import grade_lab1_ex2
# Note that the grading function is expecting a quantum circuit without measurements
grade_lab1_ex2(lab1_ex2())
def lab1_ex3():
qc = QuantumCircuit(1)
#
#
# FILL YOUR CODE IN HERE
#
#
qc.x(0)
qc.h(0)
return qc
state = Statevector.from_instruction(lab1_ex3())
plot_bloch_multivector(state)
from qc_grader import grade_lab1_ex3
# Note that the grading function is expecting a quantum circuit without measurements
grade_lab1_ex3(lab1_ex3())
def lab1_ex4():
qc = QuantumCircuit(1)
#
#
# FILL YOUR CODE IN HERE
#
#
qc.h(0)
qc.sdg(0)
return qc
state = Statevector.from_instruction(lab1_ex4())
plot_bloch_multivector(state)
from qc_grader import grade_lab1_ex4
# Note that the grading function is expecting a quantum circuit without measurements
grade_lab1_ex4(lab1_ex4())
def lab1_ex5():
qc = QuantumCircuit(2,2) # this time, we not only want two qubits, but also two classical bits for the measurement
#
#
# FILL YOUR CODE IN HERE
#
#
qc.h(0)
qc.cx(0,1)
qc.x(0)
return qc
qc = lab1_ex5()
qc.draw() # we draw the circuit
from qc_grader import grade_lab1_ex5
# Note that the grading function is expecting a quantum circuit without measurements
grade_lab1_ex5(lab1_ex5())
qc.measure(0, 0) # we perform a measurement on qubit q_0 and store the information on the classical bit c_0
qc.measure(1, 1) # we perform a measurement on qubit q_1 and store the information on the classical bit c_1
backend = Aer.get_backend('qasm_simulator') # we choose the simulator as our backend
counts = execute(qc, backend, shots = 1000).result().get_counts() # we run the simulation and get the counts
plot_histogram(counts) # let us plot a histogram to see the possible outcomes and corresponding probabilities
def lab1_ex6():
#
#
# FILL YOUR CODE IN HERE
#
#
qc = QuantumCircuit(3,3)
qc.h(0)
qc.cx(0,1)
qc.cx(1,2)
qc.y(1)
return qc
qc = lab1_ex6()
qc.draw() # we draw the circuit
from qc_grader import grade_lab1_ex6
# Note that the grading function is expecting a quantum circuit without measurements
grade_lab1_ex6(lab1_ex6())
oraclenr = 4 # determines the oracle (can range from 1 to 5)
oracle = dj_problem_oracle(oraclenr) # gives one out of 5 oracles
oracle.name = "DJ-Oracle"
def dj_classical(n, input_str):
# build a quantum circuit with n qubits and 1 classical readout bit
dj_circuit = QuantumCircuit(n+1,1)
# Prepare the initial state corresponding to your input bit string
for i in range(n):
if input_str[i] == '1':
dj_circuit.x(i)
# append oracle
dj_circuit.append(oracle, range(n+1))
# measure the fourth qubit
dj_circuit.measure(n,0)
return dj_circuit
n = 4 # number of qubits
input_str = '1111'
dj_circuit = dj_classical(n, input_str)
dj_circuit.draw() # draw the circuit
input_str = '1111'
dj_circuit = dj_classical(n, input_str)
qasm_sim = Aer.get_backend('qasm_simulator')
transpiled_dj_circuit = transpile(dj_circuit, qasm_sim)
qobj = assemble(transpiled_dj_circuit, qasm_sim)
results = qasm_sim.run(qobj).result()
answer = results.get_counts()
plot_histogram(answer)
def lab1_ex7():
min_nr_inputs = 2
max_nr_inputs = 9
return [min_nr_inputs, max_nr_inputs]
from qc_grader import grade_lab1_ex7
# Note that the grading function is expecting a list of two integers
grade_lab1_ex7(lab1_ex7())
n=4
def psi_0(n):
qc = QuantumCircuit(n+1,n)
# Build the state (|00000> - |10000>)/sqrt(2)
#
#
# FILL YOUR CODE IN HERE
#
#
qc.x(4)
qc.h(4)
return qc
dj_circuit = psi_0(n)
dj_circuit.draw()
def psi_1(n):
# obtain the |psi_0> = |00001> state
qc = psi_0(n)
# create the superposition state |psi_1>
#
#
qc.h(0)
qc.h(1)
qc.h(2)
qc.h(3)
#
#
qc.barrier()
return qc
dj_circuit = psi_1(n)
dj_circuit.draw()
def psi_2(oracle,n):
# circuit to obtain psi_1
qc = psi_1(n)
# append the oracle
qc.append(oracle, range(n+1))
return qc
dj_circuit = psi_2(oracle, n)
dj_circuit.draw()
def lab1_ex8(oracle, n): # note that this exercise also depends on the code in the functions psi_0 (In [24]) and psi_1 (In [25])
qc = psi_2(oracle, n)
# apply n-fold hadamard gate
#
#
# FILL YOUR CODE IN HERE
#
#
qc.h(0)
qc.h(1)
qc.h(2)
qc.h(3)
# add the measurement by connecting qubits to classical bits
#
#
qc.measure(0,0)
qc.measure(1,1)
qc.measure(2,2)
qc.measure(3,3)
#
#
return qc
dj_circuit = lab1_ex8(oracle, n)
dj_circuit.draw()
from qc_grader import grade_lab1_ex8
# Note that the grading function is expecting a quantum circuit with measurements
grade_lab1_ex8(lab1_ex8(dj_problem_oracle(4),n))
qasm_sim = Aer.get_backend('qasm_simulator')
transpiled_dj_circuit = transpile(dj_circuit, qasm_sim)
qobj = assemble(transpiled_dj_circuit)
results = qasm_sim.run(qobj).result()
answer = results.get_counts()
plot_histogram(answer)
|
https://github.com/MonitSharma/Qiskit-Summer-School-and-Quantum-Challenges
|
MonitSharma
|
import networkx as nx
import numpy as np
import plotly.graph_objects as go
import matplotlib as mpl
import pandas as pd
from IPython.display import clear_output
from plotly.subplots import make_subplots
from matplotlib import pyplot as plt
from qiskit import Aer
from qiskit import QuantumCircuit
from qiskit.visualization import plot_state_city
from qiskit.algorithms.optimizers import COBYLA, SLSQP, ADAM
from time import time
from copy import copy
from typing import List
from qc_grader.graph_util import display_maxcut_widget, QAOA_widget, graphs
mpl.rcParams['figure.dpi'] = 300
from qiskit.circuit import Parameter, ParameterVector
#Parameters are initialized with a simple string identifier
parameter_0 = Parameter('θ[0]')
parameter_1 = Parameter('θ[1]')
circuit = QuantumCircuit(1)
#We can then pass the initialized parameters as the rotation angle argument to the Rx and Ry gates
circuit.ry(theta = parameter_0, qubit = 0)
circuit.rx(theta = parameter_1, qubit = 0)
circuit.draw('mpl')
parameter = Parameter('θ')
circuit = QuantumCircuit(1)
circuit.ry(theta = parameter, qubit = 0)
circuit.rx(theta = parameter, qubit = 0)
circuit.draw('mpl')
#Set the number of layers and qubits
n=3
num_layers = 2
#ParameterVectors are initialized with a string identifier and an integer specifying the vector length
parameters = ParameterVector('θ', n*(num_layers+1))
circuit = QuantumCircuit(n, n)
for layer in range(num_layers):
#Appending the parameterized Ry gates using parameters from the vector constructed above
for i in range(n):
circuit.ry(parameters[n*layer+i], i)
circuit.barrier()
#Appending the entangling CNOT gates
for i in range(n):
for j in range(i):
circuit.cx(j,i)
circuit.barrier()
#Appending one additional layer of parameterized Ry gates
for i in range(n):
circuit.ry(parameters[n*num_layers+i], i)
circuit.barrier()
circuit.draw('mpl')
print(circuit.parameters)
#Create parameter dictionary with random values to bind
param_dict = {parameter: np.random.random() for parameter in parameters}
print(param_dict)
#Assign parameters using the assign_parameters method
bound_circuit = circuit.assign_parameters(parameters = param_dict)
bound_circuit.draw('mpl')
new_parameters = ParameterVector('Ψ',9)
new_circuit = circuit.assign_parameters(parameters = [k*new_parameters[i] for k in range(9)])
new_circuit.draw('mpl')
#Run the circuit with assigned parameters on Aer's statevector simulator
simulator = Aer.get_backend('statevector_simulator')
result = simulator.run(bound_circuit).result()
statevector = result.get_statevector(bound_circuit)
plot_state_city(statevector)
#The following line produces an error when run because 'circuit' still contains non-assigned parameters
#result = simulator.run(circuit).result()
for key in graphs.keys():
print(key)
graph = nx.Graph()
#Add nodes and edges
graph.add_nodes_from(np.arange(0,6,1))
edges = [(0,1,2.0),(0,2,3.0),(0,3,2.0),(0,4,4.0),(0,5,1.0),(1,2,4.0),(1,3,1.0),(1,4,1.0),(1,5,3.0),(2,4,2.0),(2,5,3.0),(3,4,5.0),(3,5,1.0)]
graph.add_weighted_edges_from(edges)
graphs['custom'] = graph
#Display widget
display_maxcut_widget(graphs['custom'])
def maxcut_cost_fn(graph: nx.Graph, bitstring: List[int]) -> float:
"""
Computes the maxcut cost function value for a given graph and cut represented by some bitstring
Args:
graph: The graph to compute cut values for
bitstring: A list of integer values '0' or '1' specifying a cut of the graph
Returns:
The value of the cut
"""
#Get the weight matrix of the graph
weight_matrix = nx.adjacency_matrix(graph).toarray()
size = weight_matrix.shape[0]
value = 0.
#INSERT YOUR CODE TO COMPUTE THE CUT VALUE HERE
for i in range(size):
for j in range(size):
value+= weight_matrix[i,j]*bitstring[i]*(1-bitstring[j])
return value
def plot_maxcut_histogram(graph: nx.Graph) -> None:
"""
Plots a bar diagram with the values for all possible cuts of a given graph.
Args:
graph: The graph to compute cut values for
"""
num_vars = graph.number_of_nodes()
#Create list of bitstrings and corresponding cut values
bitstrings = ['{:b}'.format(i).rjust(num_vars, '0')[::-1] for i in range(2**num_vars)]
values = [maxcut_cost_fn(graph = graph, bitstring = [int(x) for x in bitstring]) for bitstring in bitstrings]
#Sort both lists by largest cut value
values, bitstrings = zip(*sorted(zip(values, bitstrings)))
#Plot bar diagram
bar_plot = go.Bar(x = bitstrings, y = values, marker=dict(color=values, colorscale = 'plasma', colorbar=dict(title='Cut Value')))
fig = go.Figure(data=bar_plot, layout = dict(xaxis=dict(type = 'category'), width = 1500, height = 600))
fig.show()
plot_maxcut_histogram(graph = graphs['custom'])
from qc_grader import grade_lab2_ex1
bitstring = [1, 0, 1, 1, 0, 0] #DEFINE THE CORRECT MAXCUT BITSTRING HERE
# Note that the grading function is expecting a list of integers '0' and '1'
grade_lab2_ex1(bitstring)
from qiskit_optimization import QuadraticProgram
quadratic_program = QuadraticProgram('sample_problem')
print(quadratic_program.export_as_lp_string())
quadratic_program.binary_var(name = 'x_0')
quadratic_program.integer_var(name = 'x_1')
quadratic_program.continuous_var(name = 'x_2', lowerbound = -2.5, upperbound = 1.8)
quadratic = [[0,1,2],[3,4,5],[0,1,2]]
linear = [10,20,30]
quadratic_program.minimize(quadratic = quadratic, linear = linear, constant = -5)
print(quadratic_program.export_as_lp_string())
def quadratic_program_from_graph(graph: nx.Graph) -> QuadraticProgram:
"""Constructs a quadratic program from a given graph for a MaxCut problem instance.
Args:
graph: Underlying graph of the problem.
Returns:
QuadraticProgram
"""
#Get weight matrix of graph
weight_matrix = nx.adjacency_matrix(graph)
shape = weight_matrix.shape
size = shape[0]
#Build qubo matrix Q from weight matrix W
qubo_matrix = np.zeros((size, size))
qubo_vector = np.zeros(size)
for i in range(size):
for j in range(size):
qubo_matrix[i, j] -= weight_matrix[i, j]
for i in range(size):
for j in range(size):
qubo_vector[i] += weight_matrix[i,j]
#INSERT YOUR CODE HERE
quadratic_program=QuadraticProgram('sample_problem')
for i in range(size):
quadratic_program.binary_var(name='x_{}'.format(i))
quadratic_program.maximize(quadratic =qubo_matrix, linear = qubo_vector)
return quadratic_program
quadratic_program = quadratic_program_from_graph(graphs['custom'])
print(quadratic_program.export_as_lp_string())
from qc_grader import grade_lab2_ex2
# Note that the grading function is expecting a quadratic program
grade_lab2_ex2(quadratic_program)
def qaoa_circuit(qubo: QuadraticProgram, p: int = 1):
"""
Given a QUBO instance and the number of layers p, constructs the corresponding parameterized QAOA circuit with p layers.
Args:
qubo: The quadratic program instance
p: The number of layers in the QAOA circuit
Returns:
The parameterized QAOA circuit
"""
size = len(qubo.variables)
qubo_matrix = qubo.objective.quadratic.to_array(symmetric=True)
qubo_linearity = qubo.objective.linear.to_array()
#Prepare the quantum and classical registers
qaoa_circuit = QuantumCircuit(size,size)
#Apply the initial layer of Hadamard gates to all qubits
qaoa_circuit.h(range(size))
#Create the parameters to be used in the circuit
gammas = ParameterVector('gamma', p)
betas = ParameterVector('beta', p)
#Outer loop to create each layer
for i in range(p):
#Apply R_Z rotational gates from cost layer
#INSERT YOUR CODE HERE
for j in range(size):
qubo_matrix_sum_of_col = 0
for k in range(size):
qubo_matrix_sum_of_col+= qubo_matrix[j][k]
qaoa_circuit.rz(gammas[i]*(qubo_linearity[j]+qubo_matrix_sum_of_col),j)
#Apply R_ZZ rotational gates for entangled qubit rotations from cost layer
#INSERT YOUR CODE HERE
for j in range(size):
for k in range(size):
if j!=k:
qaoa_circuit.rzz(gammas[i]*qubo_matrix[j][k]*0.5,j,k)
# Apply single qubit X - rotations with angle 2*beta_i to all qubits
#INSERT YOUR CODE HERE
for j in range(size):
qaoa_circuit.rx(2*betas[i],j)
return qaoa_circuit
quadratic_program = quadratic_program_from_graph(graphs['custom'])
custom_circuit = qaoa_circuit(qubo = quadratic_program)
test = custom_circuit.assign_parameters(parameters=[1.0]*len(custom_circuit.parameters))
from qc_grader import grade_lab2_ex3
# Note that the grading function is expecting a quantum circuit
grade_lab2_ex3(test)
from qiskit.algorithms import QAOA
from qiskit_optimization.algorithms import MinimumEigenOptimizer
backend = Aer.get_backend('statevector_simulator')
qaoa = QAOA(optimizer = ADAM(), quantum_instance = backend, reps=1, initial_point = [0.1,0.1])
eigen_optimizer = MinimumEigenOptimizer(min_eigen_solver = qaoa)
quadratic_program = quadratic_program_from_graph(graphs['custom'])
result = eigen_optimizer.solve(quadratic_program)
print(result)
def plot_samples(samples):
"""
Plots a bar diagram for the samples of a quantum algorithm
Args:
samples
"""
#Sort samples by probability
samples = sorted(samples, key = lambda x: x.probability)
#Get list of probabilities, function values and bitstrings
probabilities = [sample.probability for sample in samples]
values = [sample.fval for sample in samples]
bitstrings = [''.join([str(int(i)) for i in sample.x]) for sample in samples]
#Plot bar diagram
sample_plot = go.Bar(x = bitstrings, y = probabilities, marker=dict(color=values, colorscale = 'plasma',colorbar=dict(title='Function Value')))
fig = go.Figure(
data=sample_plot,
layout = dict(
xaxis=dict(
type = 'category'
)
)
)
fig.show()
plot_samples(result.samples)
graph_name = 'custom'
quadratic_program = quadratic_program_from_graph(graph=graphs[graph_name])
trajectory={'beta_0':[], 'gamma_0':[], 'energy':[]}
offset = 1/4*quadratic_program.objective.quadratic.to_array(symmetric = True).sum() + 1/2*quadratic_program.objective.linear.to_array().sum()
def callback(eval_count, params, mean, std_dev):
trajectory['beta_0'].append(params[1])
trajectory['gamma_0'].append(params[0])
trajectory['energy'].append(-mean + offset)
optimizers = {
'cobyla': COBYLA(),
'slsqp': SLSQP(),
'adam': ADAM()
}
qaoa = QAOA(optimizer = optimizers['cobyla'], quantum_instance = backend, reps=1, initial_point = [6.2,1.8],callback = callback)
eigen_optimizer = MinimumEigenOptimizer(min_eigen_solver = qaoa)
result = eigen_optimizer.solve(quadratic_program)
fig = QAOA_widget(landscape_file=f'./resources/energy_landscapes/{graph_name}.csv', trajectory = trajectory, samples = result.samples)
fig.show()
graph_name = 'custom'
quadratic_program = quadratic_program_from_graph(graphs[graph_name])
#Create callback to record total number of evaluations
max_evals = 0
def callback(eval_count, params, mean, std_dev):
global max_evals
max_evals = eval_count
#Create empty lists to track values
energies = []
runtimes = []
num_evals=[]
#Run QAOA for different values of p
for p in range(1,10):
print(f'Evaluating for p = {p}...')
qaoa = QAOA(optimizer = optimizers['cobyla'], quantum_instance = backend, reps=p, callback=callback)
eigen_optimizer = MinimumEigenOptimizer(min_eigen_solver = qaoa)
start = time()
result = eigen_optimizer.solve(quadratic_program)
runtimes.append(time()-start)
num_evals.append(max_evals)
#Calculate energy of final state from samples
avg_value = 0.
for sample in result.samples:
avg_value += sample.probability*sample.fval
energies.append(avg_value)
#Create and display plots
energy_plot = go.Scatter(x = list(range(1,10)), y =energies, marker=dict(color=energies, colorscale = 'plasma'))
runtime_plot = go.Scatter(x = list(range(1,10)), y =runtimes, marker=dict(color=runtimes, colorscale = 'plasma'))
num_evals_plot = go.Scatter(x = list(range(1,10)), y =num_evals, marker=dict(color=num_evals, colorscale = 'plasma'))
fig = make_subplots(rows = 1, cols = 3, subplot_titles = ['Energy value', 'Runtime', 'Number of evaluations'])
fig.update_layout(width=1800,height=600, showlegend=False)
fig.add_trace(energy_plot, row=1, col=1)
fig.add_trace(runtime_plot, row=1, col=2)
fig.add_trace(num_evals_plot, row=1, col=3)
clear_output()
fig.show()
def plot_qaoa_energy_landscape(graph: nx.Graph, cvar: float = None):
num_shots = 1000
seed = 42
simulator = Aer.get_backend('qasm_simulator')
simulator.set_options(seed_simulator = 42)
#Generate circuit
circuit = qaoa_circuit(qubo = quadratic_program_from_graph(graph), p=1)
circuit.measure(range(graph.number_of_nodes()),range(graph.number_of_nodes()))
#Create dictionary with precomputed cut values for all bitstrings
cut_values = {}
size = graph.number_of_nodes()
for i in range(2**size):
bitstr = '{:b}'.format(i).rjust(size, '0')[::-1]
x = [int(bit) for bit in bitstr]
cut_values[bitstr] = maxcut_cost_fn(graph, x)
#Perform grid search over all parameters
data_points = []
max_energy = None
for beta in np.linspace(0,np.pi, 50):
for gamma in np.linspace(0, 4*np.pi, 50):
bound_circuit = circuit.assign_parameters([beta, gamma])
result = simulator.run(bound_circuit, shots = num_shots).result()
statevector = result.get_counts(bound_circuit)
energy = 0
measured_cuts = []
for bitstring, count in statevector.items():
measured_cuts = measured_cuts + [cut_values[bitstring]]*count
if cvar is None:
#Calculate the mean of all cut values
energy = sum(measured_cuts)/num_shots
else:
#raise NotImplementedError()
#INSERT YOUR CODE HERE
measured_cuts = sorted(measured_cuts, reverse = True)
for w in range(int(cvar*num_shots)):
energy += measured_cuts[w]/int((cvar*num_shots))
#Update optimal parameters
if max_energy is None or energy > max_energy:
max_energy = energy
optimum = {'beta': beta, 'gamma': gamma, 'energy': energy}
#Update data
data_points.append({'beta': beta, 'gamma': gamma, 'energy': energy})
#Create and display surface plot from data_points
df = pd.DataFrame(data_points)
df = df.pivot(index='beta', columns='gamma', values='energy')
matrix = df.to_numpy()
beta_values = df.index.tolist()
gamma_values = df.columns.tolist()
surface_plot = go.Surface(
x=gamma_values,
y=beta_values,
z=matrix,
coloraxis = 'coloraxis'
)
fig = go.Figure(data = surface_plot)
fig.show()
#Return optimum
return optimum
graph = graphs['custom']
optimal_parameters = plot_qaoa_energy_landscape(graph = graph)
print('Optimal parameters:')
print(optimal_parameters)
optimal_parameters = plot_qaoa_energy_landscape(graph = graph, cvar = 0.2)
print(optimal_parameters)
from qc_grader import grade_lab2_ex4
# Note that the grading function is expecting a python dictionary
# with the entries 'beta', 'gamma' and 'energy'
grade_lab2_ex4(optimal_parameters)
|
https://github.com/MonitSharma/Qiskit-Summer-School-and-Quantum-Challenges
|
MonitSharma
|
# General Imports
import numpy as np
# Visualisation Imports
import matplotlib.pyplot as plt
# Scikit Imports
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler, MinMaxScaler
# Qiskit Imports
from qiskit import Aer, execute
from qiskit.circuit import QuantumCircuit, Parameter, ParameterVector
from qiskit.circuit.library import PauliFeatureMap, ZFeatureMap, ZZFeatureMap
from qiskit.circuit.library import TwoLocal, NLocal, RealAmplitudes, EfficientSU2
from qiskit.circuit.library import HGate, RXGate, RYGate, RZGate, CXGate, CRXGate, CRZGate
from qiskit_machine_learning.kernels import QuantumKernel
# Load digits dataset
digits = datasets.load_digits(n_class=2)
# Plot example '0' and '1'
fig, axs = plt.subplots(1, 2, figsize=(6,3))
axs[0].set_axis_off()
axs[0].imshow(digits.images[0], cmap=plt.cm.gray_r, interpolation='nearest')
axs[1].set_axis_off()
axs[1].imshow(digits.images[1], cmap=plt.cm.gray_r, interpolation='nearest')
plt.show()
# Split dataset
sample_train, sample_test, label_train, label_test = train_test_split(
digits.data, digits.target, test_size=0.2, random_state=22)
# Reduce dimensions
n_dim = 4
pca = PCA(n_components=n_dim).fit(sample_train)
sample_train = pca.transform(sample_train)
sample_test = pca.transform(sample_test)
# Normalise
std_scale = StandardScaler().fit(sample_train)
sample_train = std_scale.transform(sample_train)
sample_test = std_scale.transform(sample_test)
# Scale
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)
# Select
train_size = 100
sample_train = sample_train[:train_size]
label_train = label_train[:train_size]
test_size = 20
sample_test = sample_test[:test_size]
label_test = label_test[:test_size]
print(sample_train[0], label_train[0])
print(sample_test[0], label_test[0])
# 3 features, depth 2
map_z = ZFeatureMap(feature_dimension=3, reps=2)
map_z.draw('mpl')
# 3 features, depth 1
map_zz = ZZFeatureMap(feature_dimension=3, reps=1)
map_zz.draw('mpl')
# 3 features, depth 1, linear entanglement
map_zz = ZZFeatureMap(feature_dimension=3, reps=1, entanglement='linear')
map_zz.draw('mpl')
# 3 features, depth 1, circular entanglement
map_zz = ZZFeatureMap(feature_dimension=3, reps=1, entanglement='circular')
map_zz.draw('mpl')
# 3 features, depth 1
map_pauli = PauliFeatureMap(feature_dimension=3, reps=1, paulis = ['X', 'Y', 'ZZ'])
map_pauli.draw('mpl')
def custom_data_map_func(x):
coeff = x[0] if len(x) == 1 else reduce(lambda m, n: m * n, np.sin(np.pi - x))
return coeff
map_customdatamap = PauliFeatureMap(feature_dimension=3, reps=1, paulis=['Z','ZZ'],
data_map_func=custom_data_map_func)
#map_customdatamap.draw() # qiskit isn't able to draw the circuit with np.sin in the custom data map
twolocal = TwoLocal(num_qubits=3, reps=2, rotation_blocks=['ry','rz'],
entanglement_blocks='cx', entanglement='circular', insert_barriers=True)
twolocal.draw('mpl')
twolocaln = NLocal(num_qubits=3, reps=2,
rotation_blocks=[RYGate(Parameter('a')), RZGate(Parameter('a'))],
entanglement_blocks=CXGate(),
entanglement='circular', insert_barriers=True)
twolocaln.draw('mpl')
# rotation block:
rot = QuantumCircuit(2)
params = ParameterVector('r', 2)
rot.ry(params[0], 0)
rot.rz(params[1], 1)
# entanglement block:
ent = QuantumCircuit(4)
params = ParameterVector('e', 3)
ent.crx(params[0], 0, 1)
ent.crx(params[1], 1, 2)
ent.crx(params[2], 2, 3)
nlocal = NLocal(num_qubits=6, rotation_blocks=rot, entanglement_blocks=ent,
entanglement='linear', insert_barriers=True)
nlocal.draw('mpl')
qubits = 3
repeats = 2
x = ParameterVector('x', length=qubits)
var_custom = QuantumCircuit(qubits)
for _ in range(repeats):
for i in range(qubits):
var_custom.rx(x[i], i)
for i in range(qubits):
for j in range(i + 1, qubits):
var_custom.cx(i, j)
var_custom.p(x[i] * x[j], j)
var_custom.cx(i, j)
var_custom.barrier()
var_custom.draw('mpl')
print(sample_train[0])
encode_map = ZZFeatureMap(feature_dimension=4, reps=2, entanglement='linear', insert_barriers=True)
encode_circuit = encode_map.bind_parameters(sample_train[0])
encode_circuit.draw(output='mpl')
x = [-0.1,0.2]
# YOUR CODE HERE
encode_map_x =ZZFeatureMap(feature_dimension=2, reps=4)
ex1_circuit =encode_map_x.bind_parameters(x)
ex1_circuit.draw(output='mpl')
from qc_grader import grade_lab3_ex1
# Note that the grading function is expecting a quantum circuit
grade_lab3_ex1(ex1_circuit)
zz_map = ZZFeatureMap(feature_dimension=4, reps=2, entanglement='linear', insert_barriers=True)
zz_kernel = QuantumKernel(feature_map=zz_map, quantum_instance=Aer.get_backend('statevector_simulator'))
print(sample_train[0])
print(sample_train[1])
zz_circuit = zz_kernel.construct_circuit(sample_train[0], sample_train[1])
zz_circuit.decompose().decompose().draw(output='mpl')
backend = Aer.get_backend('qasm_simulator')
job = execute(zz_circuit, backend, shots=8192,
seed_simulator=1024, seed_transpiler=1024)
counts = job.result().get_counts(zz_circuit)
counts['0000']/sum(counts.values())
matrix_train = zz_kernel.evaluate(x_vec=sample_train)
matrix_test = zz_kernel.evaluate(x_vec=sample_test, y_vec=sample_train)
fig, axs = plt.subplots(1, 2, figsize=(10, 5))
axs[0].imshow(np.asmatrix(matrix_train),
interpolation='nearest', origin='upper', cmap='Blues')
axs[0].set_title("training kernel matrix")
axs[1].imshow(np.asmatrix(matrix_test),
interpolation='nearest', origin='upper', cmap='Reds')
axs[1].set_title("testing kernel matrix")
plt.show()
x = [-0.1,0.2]
y = [0.4,-0.6]
# YOUR CODE HERE
encode_map_x2 = ZZFeatureMap(feature_dimension=2, reps=4)
zz_kernel_x2 =QuantumKernel(feature_map=encode_map_x2,quantum_instance=Aer.get_backend('statevector_simulator'))
zz_circuit_x2 =zz_kernel_x2.construct_circuit(x,y)
backend =Aer.get_backend('qasm_simulator')
job = execute(zz_circuit_x2,backend,shots=8192,
seed_simulator=1024, seed_transpiler=1024)
counts_x2 = job.result().get_counts(zz_circuit_x2)
amplitude= counts_x2['00']/sum(counts_x2.values())
from qc_grader import grade_lab3_ex2
# Note that the grading function is expecting a floating point number
grade_lab3_ex2(amplitude)
zzpc_svc = SVC(kernel='precomputed')
zzpc_svc.fit(matrix_train, label_train)
zzpc_score = zzpc_svc.score(matrix_test, label_test)
print(f'Precomputed kernel classification test score: {zzpc_score}')
zzcb_svc = SVC(kernel=zz_kernel.evaluate)
zzcb_svc.fit(sample_train, label_train)
zzcb_score = zzcb_svc.score(sample_test, label_test)
print(f'Callable kernel classification test score: {zzcb_score}')
classical_kernels = ['linear', 'poly', 'rbf', 'sigmoid']
for kernel in classical_kernels:
classical_svc = SVC(kernel=kernel)
classical_svc.fit(sample_train, label_train)
classical_score = classical_svc.score(sample_test, label_test)
print('%s kernel classification test score: %0.2f' % (kernel, classical_score))
|
https://github.com/MonitSharma/Qiskit-Summer-School-and-Quantum-Challenges
|
MonitSharma
|
from qiskit.circuit.library import RealAmplitudes
ansatz = RealAmplitudes(num_qubits=2, reps=1, entanglement='linear')
ansatz.draw('mpl', style='iqx')
from qiskit.opflow import Z, I
hamiltonian = Z ^ Z
from qiskit.opflow import StateFn
expectation = StateFn(hamiltonian, is_measurement=True) @ StateFn(ansatz)
import numpy as np
point = np.random.random(ansatz.num_parameters)
index = 2
from qiskit import Aer
from qiskit.utils import QuantumInstance
backend = Aer.get_backend('qasm_simulator')
q_instance = QuantumInstance(backend, shots = 8192, seed_simulator = 2718, seed_transpiler = 2718)
from qiskit.circuit import QuantumCircuit
from qiskit.opflow import Z, X
H = X ^ X
U = QuantumCircuit(2)
U.h(0)
U.cx(0, 1)
# YOUR CODE HERE
expectation = StateFn(hamiltonian, is_measurement=True) @ StateFn(U)
matmult_result =expectation.eval()
from qc_grader import grade_lab4_ex1
# Note that the grading function is expecting a complex number
grade_lab4_ex1(matmult_result)
from qiskit.opflow import CircuitSampler, PauliExpectation
sampler = CircuitSampler(q_instance)
# YOUR CODE HERE
sampler = CircuitSampler(q_instance) # q_instance is the QuantumInstance from the beginning of the notebook
expectation = StateFn(hamiltonian, is_measurement=True) @ StateFn(U)
in_pauli_basis = PauliExpectation().convert(expectation)
shots_result = sampler.convert(in_pauli_basis).eval()
from qc_grader import grade_lab4_ex2
# Note that the grading function is expecting a complex number
grade_lab4_ex2(shots_result)
from qiskit.opflow import PauliExpectation, CircuitSampler
expectation = StateFn(hamiltonian, is_measurement=True) @ StateFn(ansatz)
in_pauli_basis = PauliExpectation().convert(expectation)
sampler = CircuitSampler(q_instance)
def evaluate_expectation(x):
value_dict = dict(zip(ansatz.parameters, x))
result = sampler.convert(in_pauli_basis, params=value_dict).eval()
return np.real(result)
eps = 0.2
e_i = np.identity(point.size)[:, index] # identity vector with a 1 at index ``index``, otherwise 0
plus = point + eps * e_i
minus = point - eps * e_i
finite_difference = (evaluate_expectation(plus) - evaluate_expectation(minus)) / (2 * eps)
print(finite_difference)
from qiskit.opflow import Gradient
expectation = StateFn(hamiltonian, is_measurement=True) @ StateFn(ansatz)
shifter = Gradient('fin_diff', analytic=False, epsilon=eps)
grad = shifter.convert(expectation, params=ansatz.parameters[index])
print(grad)
value_dict = dict(zip(ansatz.parameters, point))
sampler.convert(grad, value_dict).eval().real
eps = np.pi / 2
e_i = np.identity(point.size)[:, index] # identity vector with a 1 at index ``index``, otherwise 0
plus = point + eps * e_i
minus = point - eps * e_i
finite_difference = (evaluate_expectation(plus) - evaluate_expectation(minus)) / 2
print(finite_difference)
expectation = StateFn(hamiltonian, is_measurement=True) @ StateFn(ansatz)
shifter = Gradient() # parameter-shift rule is the default
grad = shifter.convert(expectation, params=ansatz.parameters[index])
sampler.convert(grad, value_dict).eval().real
expectation = StateFn(hamiltonian, is_measurement=True) @ StateFn(ansatz)
shifter = Gradient('lin_comb') # parameter-shift rule is the default
grad = shifter.convert(expectation, params=ansatz.parameters[index])
sampler.convert(grad, value_dict).eval().real
# initial_point = np.random.random(ansatz.num_parameters)
initial_point = np.array([0.43253681, 0.09507794, 0.42805949, 0.34210341])
expectation = StateFn(hamiltonian, is_measurement=True).compose(StateFn(ansatz))
gradient = Gradient().convert(expectation)
gradient_in_pauli_basis = PauliExpectation().convert(gradient)
sampler = CircuitSampler(q_instance)
def evaluate_gradient(x):
value_dict = dict(zip(ansatz.parameters, x))
result = sampler.convert(gradient_in_pauli_basis, params=value_dict).eval() # add parameters in here!
return np.real(result)
# Note: The GradientDescent class will be released with Qiskit 0.28.0 and can then be imported as:
# from qiskit.algorithms.optimizers import GradientDescent
from qc_grader.gradient_descent import GradientDescent
gd_loss = []
def gd_callback(nfevs, x, fx, stepsize):
gd_loss.append(fx)
gd = GradientDescent(maxiter=300, learning_rate=0.01, callback=gd_callback)
x_opt, fx_opt, nfevs = gd.optimize(initial_point.size, # number of parameters
evaluate_expectation, # function to minimize
gradient_function=evaluate_gradient, # function to evaluate the gradient
initial_point=initial_point) # initial point
import matplotlib
import matplotlib.pyplot as plt
matplotlib.rcParams['font.size'] = 14
plt.figure(figsize=(12, 6))
plt.plot(gd_loss, label='vanilla gradient descent')
plt.axhline(-1, ls='--', c='tab:red', label='target')
plt.ylabel('loss')
plt.xlabel('iterations')
plt.legend();
from qiskit.opflow import NaturalGradient
expectation = StateFn(hamiltonian, is_measurement=True).compose(StateFn(ansatz))
natural_gradient = NaturalGradient(regularization='ridge').convert(expectation)
natural_gradient_in_pauli_basis = PauliExpectation().convert(natural_gradient)
sampler = CircuitSampler(q_instance, caching="all")
def evaluate_natural_gradient(x):
value_dict = dict(zip(ansatz.parameters, x))
result = sampler.convert(natural_gradient, params=value_dict).eval()
return np.real(result)
print('Vanilla gradient:', evaluate_gradient(initial_point))
print('Natural gradient:', evaluate_natural_gradient(initial_point))
qng_loss = []
def qng_callback(nfevs, x, fx, stepsize):
qng_loss.append(fx)
qng = GradientDescent(maxiter=300, learning_rate=0.01, callback=qng_callback)
x_opt, fx_opt, nfevs = qng.optimize(initial_point.size,
evaluate_expectation,
gradient_function=evaluate_natural_gradient,
initial_point=initial_point)
def plot_loss():
plt.figure(figsize=(12, 6))
plt.plot(gd_loss, 'tab:blue', label='vanilla gradient descent')
plt.plot(qng_loss, 'tab:green', label='quantum natural gradient')
plt.axhline(-1, c='tab:red', ls='--', label='target')
plt.ylabel('loss')
plt.xlabel('iterations')
plt.legend()
plot_loss()
from qc_grader.spsa import SPSA
spsa_loss = []
def spsa_callback(nfev, x, fx, stepsize, accepted):
spsa_loss.append(fx)
spsa = SPSA(maxiter=300, learning_rate=0.01, perturbation=0.01, callback=spsa_callback)
x_opt, fx_opt, nfevs = spsa.optimize(initial_point.size,
evaluate_expectation,
initial_point=initial_point)
def plot_loss():
plt.figure(figsize=(12, 6))
plt.plot(gd_loss, 'tab:blue', label='vanilla gradient descent')
plt.plot(qng_loss, 'tab:green', label='quantum natural gradient')
plt.plot(spsa_loss, 'tab:blue', ls='--', label='SPSA')
plt.axhline(-1, c='tab:red', ls='--', label='target')
plt.ylabel('loss')
plt.xlabel('iterations')
plt.legend()
plot_loss()
# Note: The QNSPSA class will be released with Qiskit 0.28.0 and can then be imported as:
# from qiskit.algorithms.optimizers import QNSPSA
from qc_grader.qnspsa import QNSPSA
qnspsa_loss = []
def qnspsa_callback(nfev, x, fx, stepsize, accepted):
qnspsa_loss.append(fx)
fidelity = QNSPSA.get_fidelity(ansatz, q_instance, expectation=PauliExpectation())
qnspsa = QNSPSA(fidelity, maxiter=300, learning_rate=0.01, perturbation=0.01, callback=qnspsa_callback)
x_opt, fx_opt, nfevs = qnspsa.optimize(initial_point.size,
evaluate_expectation,
initial_point=initial_point)
def plot_loss():
plt.figure(figsize=(12, 6))
plt.plot(gd_loss, 'tab:blue', label='vanilla gradient descent')
plt.plot(qng_loss, 'tab:green', label='quantum natural gradient')
plt.plot(spsa_loss, 'tab:blue', ls='--', label='SPSA')
plt.plot(qnspsa_loss, 'tab:green', ls='--', label='QN-SPSA')
plt.axhline(-1, c='tab:red', ls='--', label='target')
plt.ylabel('loss')
plt.xlabel('iterations')
plt.legend()
plot_loss()
autospsa_loss = []
def autospsa_callback(nfev, x, fx, stepsize, accepted):
autospsa_loss.append(fx)
autospsa = SPSA(maxiter=300, learning_rate=None, perturbation=None, callback=autospsa_callback)
x_opt, fx_opt, nfevs = autospsa.optimize(initial_point.size,
evaluate_expectation,
initial_point=initial_point)
def plot_loss():
plt.figure(figsize=(12, 6))
plt.plot(gd_loss, 'tab:blue', label='vanilla gradient descent')
plt.plot(qng_loss, 'tab:green', label='quantum natural gradient')
plt.plot(spsa_loss, 'tab:blue', ls='--', label='SPSA')
plt.plot(qnspsa_loss, 'tab:green', ls='--', label='QN-SPSA')
plt.plot(autospsa_loss, 'tab:red', label='Powerlaw SPSA')
plt.axhline(-1, c='tab:red', ls='--', label='target')
plt.ylabel('loss')
plt.xlabel('iterations')
plt.legend()
plot_loss()
H_tfi = -(Z^Z^I)-(I^Z^Z)-(X^I^I)-(I^X^I)-(I^I^X)
from qc_grader import grade_lab4_ex3
# Note that the grading function is expecting a Hamiltonian
grade_lab4_ex3(H_tfi)
from qiskit.circuit.library import EfficientSU2
efficient_su2 = EfficientSU2(3, entanglement="linear", reps=2)
tfi_sampler = CircuitSampler(q_instance)
def evaluate_tfi(parameters):
exp = StateFn(H_tfi, is_measurement=True).compose(StateFn(efficient_su2))
value_dict = dict(zip(efficient_su2.parameters, parameters))
result = tfi_sampler.convert(PauliExpectation().convert(exp), params=value_dict).eval()
return np.real(result)
# target energy
tfi_target = -3.4939592074349326
# initial point for reproducibility
tfi_init = np.array([0.95667807, 0.06192812, 0.47615196, 0.83809827, 0.89022282,
0.27140831, 0.9540853 , 0.41374024, 0.92595507, 0.76150126,
0.8701938 , 0.05096063, 0.25476016, 0.71807858, 0.85661325,
0.48311132, 0.43623886, 0.6371297 ])
tfi_result = SPSA(maxiter=300, learning_rate=None, perturbation=None)
tfi_result = tfi_result.optimize(tfi_init.size, evaluate_tfi, initial_point=tfi_init)
tfi_minimum = tfi_result[1]
print("Error:", np.abs(tfi_result[1] - tfi_target))
from qc_grader import grade_lab4_ex4
# Note that the grading function is expecting a floating point number
grade_lab4_ex4(tfi_minimum)
from qiskit_machine_learning.datasets import ad_hoc_data
training_features, training_labels, test_features, test_labels = ad_hoc_data(
training_size=20, test_size=10, n=2, one_hot=False, gap=0.5
)
# the training labels are in {0, 1} but we'll use {-1, 1} as class labels!
training_labels = 2 * training_labels - 1
test_labels = 2 * test_labels - 1
def plot_sampled_data():
from matplotlib.patches import Patch
from matplotlib.lines import Line2D
import matplotlib.pyplot as plt
plt.figure(figsize=(12,6))
for feature, label in zip(training_features, training_labels):
marker = 'o'
color = 'tab:green' if label == -1 else 'tab:blue'
plt.scatter(feature[0], feature[1], marker=marker, s=100, color=color)
for feature, label in zip(test_features, test_labels):
marker = 's'
plt.scatter(feature[0], feature[1], marker=marker, s=100, facecolor='none', edgecolor='k')
legend_elements = [
Line2D([0], [0], marker='o', c='w', mfc='tab:green', label='A', ms=15),
Line2D([0], [0], marker='o', c='w', mfc='tab:blue', label='B', ms=15),
Line2D([0], [0], marker='s', c='w', mfc='none', mec='k', label='test features', ms=10)
]
plt.legend(handles=legend_elements, bbox_to_anchor=(1, 0.6))
plt.title('Training & test data')
plt.xlabel('$x$')
plt.ylabel('$y$')
plot_sampled_data()
from qiskit.circuit.library import ZZFeatureMap
dim = 2
feature_map = ZZFeatureMap(dim, reps=1) # let's keep it simple!
feature_map.draw('mpl', style='iqx')
ansatz = RealAmplitudes(num_qubits=dim, entanglement='linear', reps=1) # also simple here!
ansatz.draw('mpl', style='iqx')
circuit = feature_map.compose(ansatz)
circuit.draw('mpl', style='iqx')
hamiltonian = Z ^ Z # global Z operators
gd_qnn_loss = []
def gd_qnn_callback(*args):
gd_qnn_loss.append(args[2])
gd = GradientDescent(maxiter=100, learning_rate=0.01, callback=gd_qnn_callback)
from qiskit_machine_learning.neural_networks import OpflowQNN
qnn_expectation = StateFn(hamiltonian, is_measurement=True) @ StateFn(circuit)
qnn = OpflowQNN(qnn_expectation,
input_params=list(feature_map.parameters),
weight_params=list(ansatz.parameters),
exp_val=PauliExpectation(),
gradient=Gradient(), # <-- Parameter-Shift gradients
quantum_instance=q_instance)
from qiskit_machine_learning.algorithms import NeuralNetworkClassifier
#initial_point = np.array([0.2, 0.1, 0.3, 0.4])
classifier = NeuralNetworkClassifier(qnn, optimizer=gd)
classifier.fit(training_features, training_labels);
predicted = classifier.predict(test_features)
def plot_predicted():
from matplotlib.lines import Line2D
plt.figure(figsize=(12, 6))
for feature, label in zip(training_features, training_labels):
marker = 'o'
color = 'tab:green' if label == -1 else 'tab:blue'
plt.scatter(feature[0], feature[1], marker=marker, s=100, color=color)
for feature, label, pred in zip(test_features, test_labels, predicted):
marker = 's'
color = 'tab:green' if pred == -1 else 'tab:blue'
if label != pred: # mark wrongly classified
plt.scatter(feature[0], feature[1], marker='o', s=500, linewidths=2.5,
facecolor='none', edgecolor='tab:red')
plt.scatter(feature[0], feature[1], marker=marker, s=100, color=color)
legend_elements = [
Line2D([0], [0], marker='o', c='w', mfc='tab:green', label='A', ms=15),
Line2D([0], [0], marker='o', c='w', mfc='tab:blue', label='B', ms=15),
Line2D([0], [0], marker='s', c='w', mfc='tab:green', label='predict A', ms=10),
Line2D([0], [0], marker='s', c='w', mfc='tab:blue', label='predict B', ms=10),
Line2D([0], [0], marker='o', c='w', mfc='none', mec='tab:red', label='wrongly classified', mew=2, ms=15)
]
plt.legend(handles=legend_elements, bbox_to_anchor=(1, 0.7))
plt.title('Training & test data')
plt.xlabel('$x$')
plt.ylabel('$y$')
plot_predicted()
qng_qnn_loss = []
def qng_qnn_callback(*args):
qng_qnn_loss.append(args[2])
gd = GradientDescent(maxiter=100, learning_rate=0.01, callback=qng_qnn_callback)
qnn = OpflowQNN(qnn_expectation,
input_params=list(feature_map.parameters),
weight_params=list(ansatz.parameters),
gradient=NaturalGradient(regularization='ridge'), # <-- using Natural Gradients!
quantum_instance=q_instance)
classifier = NeuralNetworkClassifier(qnn, optimizer=gd)#, initial_point=initial_point)
classifier.fit(training_features, training_labels);
def plot_losses():
plt.figure(figsize=(12, 6))
plt.plot(gd_qnn_loss, 'tab:blue', marker='o', label='vanilla gradients')
plt.plot(qng_qnn_loss, 'tab:green', marker='o', label='natural gradients')
plt.xlabel('iterations')
plt.ylabel('loss')
plt.legend(loc='best')
plot_losses()
from qiskit.opflow import I
def sample_gradients(num_qubits, reps, local=False):
"""Sample the gradient of our model for ``num_qubits`` qubits and ``reps`` repetitions.
We sample 100 times for random parameters and compute the gradient of the first RY rotation gate.
"""
index = num_qubits - 1
# you can also exchange this for a local operator and observe the same!
if local:
operator = Z ^ Z ^ (I ^ (num_qubits - 2))
else:
operator = Z ^ num_qubits
# real amplitudes ansatz
ansatz = RealAmplitudes(num_qubits, entanglement='linear', reps=reps)
# construct Gradient we want to evaluate for different values
expectation = StateFn(operator, is_measurement=True).compose(StateFn(ansatz))
grad = Gradient().convert(expectation, params=ansatz.parameters[index])
# evaluate for 100 different, random parameter values
num_points = 100
grads = []
for _ in range(num_points):
# points are uniformly chosen from [0, pi]
point = np.random.uniform(0, np.pi, ansatz.num_parameters)
value_dict = dict(zip(ansatz.parameters, point))
grads.append(sampler.convert(grad, value_dict).eval())
return grads
num_qubits = list(range(2, 13))
reps = num_qubits # number of layers = numbers of qubits
gradients = [sample_gradients(n, r) for n, r in zip(num_qubits, reps)]
fit = np.polyfit(num_qubits, np.log(np.var(gradients, axis=1)), deg=1)
x = np.linspace(num_qubits[0], num_qubits[-1], 200)
plt.figure(figsize=(12, 6))
plt.semilogy(num_qubits, np.var(gradients, axis=1), 'o-', label='measured variance')
plt.semilogy(x, np.exp(fit[0] * x + fit[1]), 'r--', label=f'exponential fit w/ {fit[0]:.2f}')
plt.xlabel('number of qubits')
plt.ylabel(r'$\mathrm{Var}[\partial_{\theta 1} \langle E(\theta) \rangle]$')
plt.legend(loc='best');
from qiskit.opflow import NaturalGradient
def sample_natural_gradients(num_qubits, reps):
index = num_qubits - 1
operator = Z ^ num_qubits
ansatz = RealAmplitudes(num_qubits, entanglement='linear', reps=reps)
expectation = StateFn(operator, is_measurement=True).compose(StateFn(ansatz))
grad = # TODO: ``grad`` should be the natural gradient for the parameter at index ``index``.
# Hint: Check the ``sample_gradients`` function, this one is almost the same.
grad = NaturalGradient().convert(expectation, params=ansatz.parameters[index])
num_points = 100
grads = []
for _ in range(num_points):
point = np.random.uniform(0, np.pi, ansatz.num_parameters)
value_dict = dict(zip(ansatz.parameters, point))
grads.append(sampler.convert(grad, value_dict).eval())
return grads
num_qubits = list(range(2, 13))
reps = num_qubits # number of layers = numbers of qubits
natural_gradients = [sample_natural_gradients(n, r) for n, r in zip(num_qubits, reps)]
fit = np.polyfit(num_qubits, np.log(np.var(natural_gradients, axis=1)), deg=1)
x = np.linspace(num_qubits[0], num_qubits[-1], 200)
plt.figure(figsize=(12, 6))
plt.semilogy(num_qubits, np.var(gradients, axis=1), 'o-', label='vanilla gradients')
plt.semilogy(num_qubits, np.var(natural_gradients, axis=1), 's-', label='natural gradients')
plt.semilogy(x, np.exp(fit[0] * x + fit[1]), 'r--', label=f'exponential fit w/ {float(fit[0]):.2f}')
plt.xlabel('number of qubits')
plt.ylabel(r'$\mathrm{Var}[\partial_{\theta 1} \langle E(\theta) \rangle]$')
plt.legend(loc='best');
num_qubits = list(range(2, 13))
fixed_depth_global_gradients = [sample_gradients(n, 1) for n in num_qubits]
fit = np.polyfit(num_qubits, np.log(np.var(fixed_depth_global_gradients, axis=1)), deg=1)
x = np.linspace(num_qubits[0], num_qubits[-1], 200)
plt.figure(figsize=(12, 6))
plt.semilogy(num_qubits, np.var(gradients, axis=1), 'o-', label='global cost, linear depth')
plt.semilogy(num_qubits, np.var(fixed_depth_global_gradients, axis=1), 'o-', label='global cost, constant depth')
plt.semilogy(x, np.exp(fit[0] * x + fit[1]), 'r--', label=f'exponential fit w/ {fit[0]:.2f}')
plt.xlabel('number of qubits')
plt.ylabel(r'$\mathrm{Var}[\partial_{\theta 1} \langle E(\theta) \rangle]$')
plt.legend(loc='best');
num_qubits = list(range(2, 13))
linear_depth_local_gradients = [sample_gradients(n, n, local=True) for n in num_qubits]
fit = np.polyfit(num_qubits, np.log(np.var(linear_depth_local_gradients, axis=1)), deg=1)
x = np.linspace(num_qubits[0], num_qubits[-1], 200)
plt.figure(figsize=(12, 6))
plt.semilogy(num_qubits, np.var(gradients, axis=1), 'o-', label='global cost, linear depth')
plt.semilogy(num_qubits, np.var(fixed_depth_global_gradients, axis=1), 'o-', label='global cost, constant depth')
plt.semilogy(num_qubits, np.var(linear_depth_local_gradients, axis=1), 'o-', label='local cost, linear depth')
plt.semilogy(x, np.exp(fit[0] * x + fit[1]), 'r--', label=f'exponential fit w/ {fit[0]:.2f}')
plt.xlabel('number of qubits')
plt.ylabel(r'$\mathrm{Var}[\partial_{\theta 1} \langle E(\theta) \rangle]$')
plt.legend(loc='best');
num_qubits = list(range(2, 13))
fixed_depth_local_gradients = [sample_gradients(n, 1, local=True) for n in num_qubits]
fit = np.polyfit(num_qubits, np.log(np.var(fixed_depth_local_gradients, axis=1)), deg=1)
x = np.linspace(num_qubits[0], num_qubits[-1], 200)
plt.figure(figsize=(12, 6))
plt.semilogy(num_qubits, np.var(gradients, axis=1), 'o-', label='global cost, linear depth')
plt.semilogy(num_qubits, np.var(fixed_depth_global_gradients, axis=1), 'o-', label='global cost, constant depth')
plt.semilogy(num_qubits, np.var(linear_depth_local_gradients, axis=1), 'o-', label='local cost, linear depth')
plt.semilogy(num_qubits, np.var(fixed_depth_local_gradients, axis=1), 'o-', label='local cost, constant depth')
plt.semilogy(x, np.exp(fit[0] * x + fit[1]), 'r--', label=f'exponential fit w/ {fit[0]:.2f}')
plt.xlabel('number of qubits')
plt.ylabel(r'$\mathrm{Var}[\partial_{\theta 1} \langle E(\theta) \rangle]$')
plt.legend(loc='best');
num_qubits = 6
operator = Z ^ Z ^ (I ^ (num_qubits - 4))
def minimize(circuit, optimizer):
initial_point = np.random.random(circuit.num_parameters)
exp = StateFn(operator, is_measurement=True) @ StateFn(circuit)
grad = Gradient().convert(exp)
# pauli basis
exp = PauliExpectation().convert(exp)
grad = PauliExpectation().convert(grad)
sampler = CircuitSampler(q_instance, caching="all")
def loss(x):
values_dict = dict(zip(circuit.parameters, x))
return np.real(sampler.convert(exp, values_dict).eval())
def gradient(x):
values_dict = dict(zip(circuit.parameters, x))
return np.real(sampler.convert(grad, values_dict).eval())
return optimizer.optimize(circuit.num_parameters, loss, gradient, initial_point=initial_point)
circuit = RealAmplitudes(4, reps=1, entanglement='linear')
circuit.draw('mpl', style='iqx')
circuit.reps = 5
circuit.draw('mpl', style='iqx')
def layerwise_training(ansatz, max_num_layers, optimizer):
optimal_parameters = []
fopt = None
for reps in range(1, max_num_layers):
ansatz.reps = reps
# bind already optimized parameters
values_dict = dict(zip(ansatz.parameters, optimal_parameters))
partially_bound = ansatz.bind_parameters(values_dict)
xopt, fopt, _ = minimize(partially_bound, optimizer)
print('Circuit depth:', ansatz.depth(), 'best value:', fopt)
optimal_parameters += list(xopt)
return fopt, optimal_parameters
ansatz = RealAmplitudes(4, entanglement='linear')
optimizer = GradientDescent(maxiter=50)
np.random.seed(12)
fopt, optimal_parameters = layerwise_training(ansatz, 4, optimizer)
|
https://github.com/MonitSharma/Qiskit-Summer-School-and-Quantum-Challenges
|
MonitSharma
|
# required imports:
from qiskit.visualization import array_to_latex
from qiskit.quantum_info import Statevector, random_statevector
from qiskit.quantum_info.operators import Operator, Pauli
from qiskit import QuantumCircuit
from qiskit.circuit.library import HGate, CXGate
import numpy as np
ket0 = [[1],[0]]
array_to_latex(ket0)
bra0 = [1,0]
array_to_latex(bra0)
ket1 = [[0], [1]]
bra1 = [0, 1]
from qc_grader.challenges.qgss_2023 import grade_lab1_ex1
grade_lab1_ex1([ket1, bra1])
sv_bra0 = Statevector(bra0)
sv_bra0
sv_bra0.draw('latex')
sv_eq = Statevector([1/2, 3/4, 4/5, 6/8])
sv_eq.draw('latex')
sv_eq.is_valid()
sv_valid = Statevector([1/2, 1/2, 1/2, 1/2])
from qc_grader.challenges.qgss_2023 import grade_lab1_ex2
grade_lab1_ex2(sv_valid)
op_bra0 = Operator(bra0)
op_bra0
op_ket0 = Operator(ket0)
op_bra0.tensor(op_ket0)
braket = np.dot(op_bra0,op_ket0)
array_to_latex(braket)
ketbra = np.outer(ket0,bra0)
array_to_latex(ketbra)
braket = np.dot(op_bra0,op_ket0)
array_to_latex(braket)
bra1ket0 = [0]
bra0ket1 = [0]
bra1ket1 = [1]
ket1bra0 = [[0, 0], [1, 0]]
ket0bra1 = [[0, 1], [0, 0]]
ket1bra1 = [[0, 0], [0, 1]]
from qc_grader.challenges.qgss_2023 import grade_lab1_ex3
grade_lab1_ex3([bra1ket0, bra0ket1, bra1ket1, ket1bra0, ket0bra1, ket1bra1])
answer = ['a']
from qc_grader.challenges.qgss_2023 import grade_lab1_ex4
grade_lab1_ex4(answer)
m1 = Operator([[1,1],[0,0]])
array_to_latex(m1)
m3 = Operator([[0,1],[1,0]])
array_to_latex(m3)
array_to_latex(m1@ket0)
m2 = Operator([[1, 0], [0, 1]])
m4 = Operator([[0, 0], [1, 1]])
from qc_grader.challenges.qgss_2023 import grade_lab1_ex5
grade_lab1_ex5([m2, m4])
cnot = CXGate()
array_to_latex(cnot)
m3.is_unitary()
random = Operator(np.array([[ 0.50778085-0.44607116j, -0.1523741 +0.14128434j, 0.44607116+0.50778085j,
-0.14128434-0.1523741j ],
[ 0.16855994+0.12151822j, 0.55868196+0.38038841j, -0.12151822+0.16855994j,
-0.38038841+0.55868196j],
[ 0.50778085-0.44607116j, -0.1523741 +0.14128434j, -0.44607116-0.50778085j,
0.14128434+0.1523741j ],
[ 0.16855994+0.12151822j, 0.55868196+0.38038841j, 0.12151822-0.16855994j,
0.38038841-0.55868196j]]))
random.is_unitary()
non_unitary_op = Operator(np.array([0,1,2,3]))
from qc_grader.challenges.qgss_2023 import grade_lab1_ex6
grade_lab1_ex6(non_unitary_op)
pauli_x = Pauli('X')
array_to_latex(pauli_x)
pauli_y = Pauli('Y')
array_to_latex(pauli_y)
pauli_z = Pauli('Z')
array_to_latex(pauli_z)
op_x = Operator(pauli_x)
op_x
op_new = np.dot(op_x,ket0)
array_to_latex(op_new)
result = [[0.+0.j], [-1.+0.j]]
from qc_grader.challenges.qgss_2023 import grade_lab1_ex7
grade_lab1_ex7(result)
hadamard = HGate()
array_to_latex(hadamard)
hop = Operator(hadamard)
hop.is_unitary()
bell = QuantumCircuit(2)
bell.h(0) # apply an H gate to the circuit
bell.cx(0,1) # apply a CNOT gate to the circuit
bell.draw(output="mpl")
bell_op = Operator(bell)
array_to_latex(bell_op)
ghz = QuantumCircuit(3)
##############################
# add gates to your circuit here
ghz.h(0)
ghz.cx(0, 1)
ghz.cx(1, 2)
##############################
ghz.draw(output='mpl')
from qc_grader.challenges.qgss_2023 import grade_lab1_ex8
grade_lab1_ex8(ghz)
plus_state = Statevector.from_label("+")
plus_state.draw('latex')
plus_state
plus_state.probabilities_dict()
# run this cell multiple times to show collapsing into one state or the other
res = plus_state.measure()
res
qc = QuantumCircuit(1,1)
qc.h(0)
qc.measure(0, 0)
qc.draw(output="mpl")
sv_bell = Statevector([np.sqrt(1/2), 0, 0, np.sqrt(1/2)])
sv_bell.draw('latex')
sv_bell.probabilities_dict()
sv_psi_plus = Statevector([0, np.sqrt(1/2), np.sqrt(1/2), 0])
prob_psi_plus = {'01': 0.5000000000000001, '10': 0.5000000000000001}
sv_psi_minus = Statevector([0, np.sqrt(1/2), -np.sqrt(1/2), 0])
prob_psi_minus = {'01': 0.5000000000000001, '10': 0.5000000000000001}
sv_phi_minus = Statevector([np.sqrt(1/2), 0, 0, -np.sqrt(1/2)])
prob_phi_minus = {'00': 0.5000000000000001, '11': 0.5000000000000001}
from qc_grader.challenges.qgss_2023 import grade_lab1_ex9
grade_lab1_ex9([prob_psi_plus, prob_psi_minus, prob_phi_minus])
qft = QuantumCircuit(2)
##############################
# add gates to your circuit here
qft.h(1)
qft.cp(np.pi/2, 0, 1)
qft.h(0)
qft.swap(0, 1)
##############################
qft.draw(output='mpl')
from qc_grader.challenges.qgss_2023 import grade_lab1_ex10
grade_lab1_ex10(qft)
U = Operator(qft)
array_to_latex(U)
|
https://github.com/MonitSharma/Qiskit-Summer-School-and-Quantum-Challenges
|
MonitSharma
|
%set_env QC_GRADE_ONLY=true
from qiskit.circuit import QuantumCircuit
from qiskit.primitives import Estimator, Sampler
from qiskit.quantum_info import SparsePauliOp
from qiskit.visualization import plot_histogram
import numpy as np
import matplotlib.pyplot as plt
plt.style.use('dark_background') # optional
# create excited |1> state
qc_1 = QuantumCircuit(1)
qc_1.x(0)
qc_1.draw('mpl')
# create superposition |+> state
qc_plus = QuantumCircuit(1)
qc_plus.h(0)
qc_plus.draw('mpl')
qc_1.measure_all()
qc_plus.measure_all()
sampler = Sampler()
job_1 = sampler.run(qc_1)
job_plus = sampler.run(qc_plus)
job_1.result().quasi_dists
job_plus.result().quasi_dists
legend = ["Excited State", "Plus State"] # TODO: Excited State does not appear
plot_histogram([job_1.result().quasi_dists[0], job_plus.result().quasi_dists[0]], legend=legend)
qc_1.remove_final_measurements()
qc_plus.remove_final_measurements()
# rotate into the X-basis
qc_1.h(0)
qc_plus.h(0)
qc_1.measure_all()
qc_plus.measure_all()
sampler = Sampler()
job_1 = sampler.run(qc_1)
job_plus = sampler.run(qc_plus)
plot_histogram([job_1.result().quasi_dists[0], job_plus.result().quasi_dists[0]], legend=legend)
qc2_1 = QuantumCircuit(1)
qc2_1.x(0)
qc2_plus = QuantumCircuit(1)
qc2_plus.h(0)
obsvs = list(SparsePauliOp(['Z', 'X']))
estimator = Estimator()
job2_1 = estimator.run([qc2_1]*len(obsvs), observables=obsvs)
job2_plus = estimator.run([qc2_plus]*len(obsvs), observables=obsvs)
job2_1.result()
# TODO: make this into module that outputs a nice table
print(f' | <Z> | <X> ')
print(f'----|------------------')
print(f'|1> | {job2_1.result().values[0]} | {job2_1.result().values[1]}')
print(f'|+> | {job2_plus.result().values[0]} | {job2_plus.result().values[1]}')
# this is a correct answer:
obsv = SparsePauliOp('X').tensor(SparsePauliOp(['X', 'Z'], coeffs=[1, -1])) + SparsePauliOp('Z').tensor(SparsePauliOp(['X', 'Z'], coeffs=[1, 1]))
from qc_grader.challenges.qgss_2023 import grade_lab2_ex1
grade_lab2_ex1(obsv)
from qiskit.circuit import Parameter
theta = Parameter('θ')
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
qc.ry(theta, 0)
qc.draw('mpl')
# this is a correct answer
num_params = 21
angles=[[angle] for angle in np.linspace(-np.pi, np.pi, num_params)]
estimator = Estimator()
job = estimator.run([qc]*len(angles), observables=[obsv]*len(angles), parameter_values=angles)
exps = job.result().values
plt.plot(angles, exps, marker='x', ls='-', color='green')
plt.plot(angles, [2]*len(angles), ls='--', color='red', label='Classical Bound')
plt.plot(angles, [-2]*len(angles), ls='--', color='red')
plt.xlabel('angle (rad)')
plt.ylabel('CHSH Witness')
plt.legend(loc=4)
from qc_grader.challenges.qgss_2023 import grade_lab2_ex2
grade_lab2_ex2(obsv, angles)
from qiskit.circuit import ClassicalRegister, QuantumRegister
theta = Parameter('θ')
qr = QuantumRegister(1, 'q')
qc = QuantumCircuit(qr)
qc.ry(theta, 0)
qc.draw('mpl')
tele_qc = qc.copy()
bell = QuantumRegister(2, 'Bell')
alice = ClassicalRegister(2, 'Alice')
bob = ClassicalRegister(1, 'Bob')
tele_qc.add_register(bell, alice, bob)
tele_qc.draw('mpl')
# create Bell state with other two qubits
tele_qc.barrier()
tele_qc.h(1)
tele_qc.cx(1, 2)
tele_qc.barrier()
tele_qc.draw('mpl')
# alice operates on her qubits
tele_qc.cx(0, 1)
tele_qc.h(0)
tele_qc.barrier()
tele_qc.draw('mpl')
tele_qc.measure([qr[0], bell[0]], alice)
tele_qc.draw('mpl')
# either pairs are correct
# tele_qc.x(2).c_if(alice[1], 1)
# tele_qc.z(2).c_if(alice[0], 1)
with tele_qc.if_test((alice[1], 1)):
tele_qc.x(2)
with tele_qc.if_test((alice[0], 1)):
tele_qc.z(2)
tele_qc.draw('mpl')
tele_qc.barrier()
tele_qc.measure(bell[1], bob)
tele_qc.draw('mpl')
from qc_grader.challenges.qgss_2023 import grade_lab2_ex3
grade_lab2_ex3(tele_qc, theta, 5*np.pi/7)
from qiskit_aer.primitives import Sampler
angle = 5*np.pi/7
sampler = Sampler()
qc.measure_all()
job_static = sampler.run(qc.bind_parameters({theta: angle}))
job_dynamic = sampler.run(tele_qc.bind_parameters({theta: angle}))
print(f"Original Dists: {job_static.result().quasi_dists[0].binary_probabilities()}")
print(f"Teleported Dists: {job_dynamic.result().quasi_dists[0].binary_probabilities()}")
from qiskit.result import marginal_counts
# this is correct
tele_counts = marginal_counts(job_dynamic.result().quasi_dists[0].binary_probabilities(), indices=[2])
legend = ['Original State', 'Teleported State']
plot_histogram([job_static.result().quasi_dists[0].binary_probabilities(), tele_counts], legend=legend)
from qc_grader.challenges.qgss_2023 import grade_lab2_ex4
grade_lab2_ex4(tele_counts, job_dynamic.result().quasi_dists[0])
import qiskit.tools.jupyter
%qiskit_version_table
|
https://github.com/MonitSharma/Qiskit-Summer-School-and-Quantum-Challenges
|
MonitSharma
|
# upgrade/update pip library
!pip install --upgrade pip
# install the last official version of the grader from IBM's Qiskit Community
!pip install git+https://github.com/qiskit-community/Quantum-Challenge-Grader.git@main
# import the quantum circuit, Aer,
# and execute instruction
# from the IBM' Qiskit library
from qiskit import QuantumCircuit, Aer, execute
# import the numpy library
import numpy as np
# import the plot histogram function
# from the IBM's Qiskit Visualization module
from qiskit.visualization import plot_histogram
# import the plotting from
# the Matplotlib's Pyplot module
import matplotlib.pyplot as plt
# import the GCD (Greatest Common Divisor)
# from the built-in mathematics module
from math import gcd
# define the function to genera the quantum circuit
# for the Quantum Fourier Transform (QFT) on n qubits
def qft(n):
# creates a quantum circuit with n qubits,
# implementing the Quantum Fourier Transform (QFT)
circuit = QuantumCircuit(n)
# define the function to perform the Swap gates
# on the quantum registers of the quantum circuit
# for the Quantum Fourier Transform (QFT) on n qubits
def swap_registers( circuit, n ):
# for a number of iterations equal to half of
# the number of qubits used on the quantum circuit
# for the Quantum Fourier Transform (QFT)
for qubit in range( n // 2 ):
# apply the Swap gate between the kth qubit and
# the (n - k)th qubit on the quantum register defined before
circuit.swap( qubit, ( n - qubit - 1 ) )
# return the quantum circuit with the Swap gates
# applied on the n qubits of the quantum register,
# to implement the Quantum Fourier Transform (QFT)
return circuit
# define the function to perform the Controlled-Phase gates
# on the quantum registers of the quantum circuit
# for the Quantum Fourier Transform (QFT) on n qubits
# (it is applied to the first n qubits,
# and without the Swap gates performed)
def qft_rotations( circuit, n ):
# if it is the last opposite iteration
if n == 0:
# return with the Controlled-Phase gates
# on the quantum registers of the quantum circuit
# for the Quantum Fourier Transform (QFT) on n qubits
# (it is applied to the first n qubits,
# and without the Swap gates performed)
return circuit
# iterates on the opposite direction,
# setting a new nth iteration
n -= 1
# apply the Hadamard gate to the kth qubit,
# on the quantum register defined before,
# and iterating on the opposite direction
circuit.h(n)
# for the remaining qubits to consider
# i the kth opposite iteration
for qubit in range(n):
# apply the Controlled-Phase gate for
# the theta angle equal to (pi / 2)^(n - k),
# with control on the nth qubit and target on the kth qubit
circuit.cp( ( np.pi / 2 )**( n - qubit ), qubit, n )
# call this fuction recursively for
# the next opposite iteration
qft_rotations( circuit, n )
# perform the Controlled-Phase gates
# on the quantum registers of the quantum circuit
# for the Quantum Fourier Transform (QFT) on n qubits
# (it is applied to the first n qubits,
# and without the Swap gates performed)
qft_rotations( circuit, n )
# perform the Swap gates on the quantum registers of
# the quantum circuit for the Quantum Fourier Transform (QFT) on n qubits
swap_registers( circuit, n )
# return the quantum circuit with n qubits,
# implementing the Quantum Fourier Transform (QFT)
return circuit
# define the function to genera the quantum circuit
# for the Inverse Quantum Fourier Transform (IQFT) on n qubits
def qft_dagger( circuit, n ):
# note: do not forget to apply again the Swap gates
# to peform its inverse operation
# for a number of iterations equal to half of
# the number of qubits used on the quantum circuit
# for the Inverse Quantum Fourier Transform (IQFT)
for qubit in range( n // 2 ):
# apply the Swap gate between the kth qubit and
# the (n - k)th qubit on the quantum register defined before
circuit.swap( qubit, ( n - qubit - 1 ) )
# for each number of qubits of the quantum register defined before,
# to consider in the current jth iteration
for j in range(n):
# for each mth qubit of the quantum register defined before,
# to consider in the current iteration
for m in range(j):
# apply the Controlled-Phase gate for
# the theta angle equal to -pi / ( 2^( j - m ) ),
# with control on the mth qubit and target on the jth qubit
qc.cp( -np.pi / float( 2**( j - m ) ), m, j )
# apply the Hadamard gate to the jth qubit
# on the quantum register defined before
qc.h(j)
# define the size n of the quantum register to
# store the phase information
phase_register_size = 4
# create a quantum circuit with a quantum register
# with n qubits and a classical register with n bits,
# to implement the Quantum Phase Estimation (QPE) for n = 4 qubits
qpe4 = QuantumCircuit( ( phase_register_size + 1 ),
phase_register_size )
####################################################
#### insert your code here ####
# define the function to perform the Quantum Hadamard Transform on
# the n qubits of the quantum register of the quantum circuit
# implementing the Quantum Phase Estimation (QPE)
def apply_quantum_hadamard_transform( circuit, n ):
# for each qubit of the quantum register of the quantum circuit
# implementing the Quantum Phase Estimation (QPE) for n qubits
for qubit_idx in range(n):
# apply the Hadamard gate to the current ith qubit
circuit.h(qubit_idx)
# define the function to perform the Controlled-Phase gates on
# the n qubits of the quantum register of the quantum circuit
# implementing the Quantum Phase Estimation (QPE),
# as part of the Quantum Fourier Transform (QFT)
def apply_controlled_phases( theta, circuit, n ):
# for each ith step according to
# the number of n qubits used
for step in range(n):
# compute the iteration parameter t
# as a power of 2, according to the current step
t = 2**step
# for each iteration according to
# the iteration parameter t
for _ in range(t):
# apply the Controlled-Phase gate for the theta angle,
# with control on the ith qubit and target on the last qubit
circuit.cp( theta, step, n )
# define the function to perform the Swap gates on
# the n qubits of the quantum register of the quantum circuit
# implementing the Quantum Phase Estimation (QPE),
# as part of the Quantum Fourier Transform (QFT)
def apply_swaps( circuit, n ):
# for a number of iterations equal to half of
# the number of phase counting qubits used
# on the resepective quantum circuit
# for the Quantum Fourier Transform (QFT)
for qubit_idx in range( phase_register_size // 2 ):
# apply the Swap gate between the kth qubit and
# the (n - k)th qubit on the quantum register defined before
circuit.swap( qubit_idx, ( n - qubit_idx - 1 ) )
# define the function to perform
# the Inverse Quantum Fourier Transform (IQFT) on
# the n qubits of the quantum register of the quantum circuit
# implementing the Quantum Phase Estimation (QPE)
def apply_quantum_fourier_transform_inverse( circuit, n ):
# for each qubit on the quantum register
for j in range(n):
# for each additional mth qubit ranging to
# the current jth qubit being iterated before
for m in range(j):
# apply the Controlled-Phase gate for
# the theta angle equal to -pi / ( 2^( j - m ) ),
# with control on the mth qubit and target on the jth qubit
circuit.cp( -np.pi / float( 2**( j - m ) ), m, j )
# apply the Hadamard gate to the jth qubit (system's qubit)
circuit.h(j)
# define the function to perform a measurement of
# all the n qubits on the quantum register of a quantum circuit,
# and storing the classical outcomes on the n bits of
# the classical register of that same quantum circuit
def measure_all_qubits(circuit, n):
# for each pair of qubits and bits
for j in range(n):
# measure the current qubit on the quantum register,
# and stores the classical outcome obtained
# in the current bit on the classical register
circuit.measure(j, j)
# define the function to perform the Quantum Phase Estimation (QPE)
# according to a theta angle given, on a quantum circuit of n qubits
def quantum_phase_estimation( theta, circuit, n ):
# perform the Quantum Hadamard Transform on
# the n qubits of the quantum register of
# the quantum circuit implementing
# the Quantum Phase Estimation (QPE)
apply_quantum_hadamard_transform( circuit, n )
# apply the Pauli-X gate to the last qubit on
# the quantum register of the quantum circuit of
# the Quantum Phase Estimation (QPE)
circuit.x(n)
# apply a barrier to the quantum circuit of
# the Quantum Phase Estimation (QPE)
circuit.barrier()
# perform the Controlled-Phase gates on
# the n qubits of the quantum register of the quantum circuit
# implementing the Quantum Phase Estimation (QPE),
# as part of the Quantum Fourier Transform (QFT)
apply_controlled_phases( theta, circuit, n )
# apply a barrier to the quantum circuit of
# the Quantum Phase Estimation (QPE)
circuit.barrier()
# perform the Swap gates on the n qubits of
# the quantum register of the quantum circuit
# implementing the Quantum Phase Estimation (QPE),
# as part of the Quantum Fourier Transform (QFT)
apply_swaps( circuit, n )
# apply a barrier to the quantum circuit of
# the Quantum Phase Estimation (QPE)
circuit.barrier()
# perform the Inverse Quantum Fourier Transform (IQFT) on
# the n qubits of the quantum register of the quantum circuit
# implementing the Quantum Phase Estimation (QPE)
apply_quantum_fourier_transform_inverse( circuit, n )
# apply a barrier to the quantum circuit of
# the Quantum Phase Estimation (QPE)
circuit.barrier()
# perform a measurement of all the n qubits on
# the quantum register of the quantum circuit of
# the Quantum Phase Estimation (QPE) and storing
# the classical outcomes on the n bits of
# the classical register of that same quantum circuit
measure_all_qubits( circuit, n )
####################################################
# define the theta angle to be equal to (2 * pi) / 3
theta = ( 2 * np.pi ) / 3
# perform the Quantum Phase Estimation (QPE)
# according to the theta angle defined,
# on the quantum circuit of n qubits defined before
quantum_phase_estimation( theta, qpe4, phase_register_size )
# draw the quantum circuit implementing
# the Quantum Phase Estimation (QPE) defined before
qpe4.draw("mpl")
# run this cell to simulate 'qpe4' and
# to plot the histogram of the result
# create the Aer Simulator object
sim = Aer.get_backend("aer_simulator")
# define the number of shots
shots = 20000
# execute the simulation for the Quantum Phase Estimation (QPE),
# with n = 4 counting qubits, and retrieve
# the result counts of this quantum simulation
count_qpe4 = execute( qpe4, sim, shots=shots ).result().get_counts()
# plot the histogram of the result counts of the quantum simulation
# for the Quantum Phase Estimation (QPE), with n = 4 counting qubits
plot_histogram( count_qpe4, figsize=(9,5) )
# submit your answer
# import the grader for the exercise 1 of the lab 3
from qc_grader.challenges.qgss_2023 import grade_lab3_ex1
# grade the exercise 1 of the lab 3
grade_lab3_ex1( count_qpe4 )
# process the result count data to determine accuracy of
# the estimated phase and grab the highest probability measurement
# define the maximum number of counts which will be obtained
max_binary_counts = 0
# define the maximum binary value which will be obtained
max_binary_val = ""
# for each count obtained from the quantum simulation of
# the Quantum Phase Estimation (QPE)
for key, item in count_qpe4.items():
# if the current number of counts is greater than
# the current maximum number of counts obtained
if item > max_binary_counts:
# update the maximum number of counts obtained
max_binary_counts = item
# update the maximum binary value obtained
max_binary_val = key
#########################################
#### your function to convert a binary ####
#### string to a decimal number goes here ####
# define the function to convert
# a binary string to a decimal number
def bin_to_decimal( binary_string ):
# return a binary string
# converted to a decimal number
return int( binary_string, 2 )
# calculate the estimated phase obtained
# from the quantum simulation of
# the Quantum Phase Estimation (QPE)
estimated_phase = ( bin_to_decimal(max_binary_val) / 2**phase_register_size )
# calculate the phase accuracy
# which can be obtained from
# the quantum simulation of
# the Quantum Phase Estimation (QPE)
# with the quantum circuit defined before,
# inverse of the highest power of 2
# (i.e. smallest decimal) this quantum circuit can estimate
phase_accuracy_window = 2**( -phase_register_size )
# submit your answer
# import the grader for the exercise 2 of the lab 3
from qc_grader.challenges.qgss_2023 import grade_lab3_ex2
# grade the exercise 2 of the lab 3
grade_lab3_ex2( [ estimated_phase, phase_accuracy_window ] )
# import the IBM's Provider from
# the Qiskit's IBM Provider module
from qiskit_ibm_provider import IBMProvider
# import the transpile function from
# the IBM's Qikist Compiler module
from qiskit.compiler import transpile
# create an IBM's Provider object
provider = IBMProvider()
# define the hub for the IBM's Provider
hub = "summer-school-6"
# define the group for the IBM's Provider
group = "group-3"
# define the project for the IBM's Provider
project = "7048813929"
# define the backend's name for the IBM's Provider
backend_name = "ibmq_manila"
# retrieve the backend from the IBM's Provider
backend = provider.get_backend( backend_name, instance=f"{hub}/{group}/{project}" )
##########################################
#### your code goes here ####
# define the initial maximum quantum circuit depth obtained
max_depth = 1e-20
# define the initial minimum quantum circuit depth obtained
min_depth = 1e20
# define the number of trials to transpile/optimize
# the quantum circuit for the Quantum Phase Estimation (QPE)
num_trials = 10
# for each trial to transpile/optimize the quantum circuit
# for the Quantum Phase Estimation (QPE)
for _ in range(num_trials):
# transpile/optimize the quantum circuit
# for the Quantum Phase Estimation (QPE),
# for the current considering trial
transpiled_qpe4 = transpile( qpe4, backend, optimization_level=3 )
# retrieve the quantum circuit depth of
# the transpiled/optimized quantum circuit
# for the Quantum Phase Estimation (QPE)
transpiled_qpe4_depth = transpiled_qpe4.depth()
# if the quantum circuit depth of
# the transpiled/optimized quantum circuit
# for the Quantum Phase Estimation (QPE)
# is greater than the current maximum
# quantum circuit depth obtained
if transpiled_qpe4_depth > max_depth:
# update the maximum quantum circuit depth
# obtained with the current quantum circuit depth
max_depth = transpiled_qpe4_depth
# update the quantum circuit with the maximum depth
# with the current quantum circuit transpiled/optimized
max_depth_qpe = transpiled_qpe4
# if the quantum circuit depth of
# the transpiled/optimized quantum circuit
# for the Quantum Phase Estimation (QPE)
# is lower than the current minimum
# quantum circuit depth obtained
if transpiled_qpe4_depth < min_depth:
# update the minimum quantum circuit depth
# obtained with the current quantum circuit depth
min_depth = transpiled_qpe4_depth
# update the quantum circuit with the minimum depth
# with the current quantum circuit transpiled/optimized
min_depth_qpe = transpiled_qpe4
##########################################
# submit your answer
# import the grader for the exercise 3 of the lab 3
from qc_grader.challenges.qgss_2023 import grade_lab3_ex3
# grade the exercise 3 of the lab 3
grade_lab3_ex3( [ max_depth_qpe, min_depth_qpe ] )
# define the number of shots
#shots = 2000
# OPTIONAL: run the minimum depth quantum circuit for
# the Quantum Phase Estimation (QPE)
# execute and retrieve the job for the simulation
# for the Quantum Phase Estimation (QPE),
# with n = 4 counting qubits, and retrieve
# the result counts of this quantum simulation,
# using the minimum quantum circuit depth
#job_min_qpe4 = backend.run( min_depth_qpe, sim, shots=shots )
# print the id of the job of the simulation
# for the Quantum Phase Estimation (QPE),
# with n = 4 counting qubits, and retrieve
# the result counts of this quantum simulation,
# using the minimum quantum circuit depth
#print( job_min_qpe4.job_id() )
# gather the result counts data
# execute the simulation for the Quantum Phase Estimation (QPE),
# with n = 4 counting qubits, and retrieve
# the result counts of this quantum simulation,
# using the minimum quantum circuit depth
#count_min_qpe4 = job_min_qpe4.result().get_counts()
# plot the histogram of the result counts of the quantum simulation
# for the Quantum Phase Estimation (QPE), with n = 4 counting qubits,
# and using the minimum quantum circuit depth
#plot_histogram( count_min_qpe4, figsize=(9,5) )
# OPTIONAL: run the maximum depth quantum circuit for
# the Quantum Phase Estimation (QPE)
# execute and retrieve the job for the simulation
# for the Quantum Phase Estimation (QPE),
# with n = 4 counting qubits, and retrieve
# the result counts of this quantum simulation,
# using the maximum quantum circuit depth
#job_max_qpe4 = backend.run( max_depth_qpe, sim, shots=shots )
# print the id of the job of the simulation
# for the Quantum Phase Estimation (QPE),
# with n = 4 counting qubits, and retrieve
# the result counts of this quantum simulation,
# using the maximum quantum circuit depth
#print( job_max_qpe4.job_id() )
# gather the result counts data
# execute the simulation for the Quantum Phase Estimation (QPE),
# with n = 4 counting qubits, and retrieve
# the result counts of this quantum simulation,
# using the maximum quantum circuit depth
#count_max_qpe4 = job_max_qpe4.result().get_counts()
# plot the histogram of the result counts of the quantum simulation
# for the Quantum Phase Estimation (QPE), with n = 4 counting qubits,
# and using the maximum quantum circuit depth
#plot_histogram( count_max_qpe4, figsize=(9,5) )
# define the function to perform the Quantum Hadamard Transform on
# the n qubits of the quantum register of the quantum circuit
# implementing the Quantum Phase Estimation (QPE)
def apply_quantum_hadamard_transform( circuit, n ):
# for each qubit of the quantum register of the quantum circuit
# implementing the Quantum Phase Estimation (QPE) for n qubits
for qubit_idx in range(n):
# apply the Hadamard gate to the current ith qubit
circuit.h(qubit_idx)
# define the function to perform the Controlled-Phase gates on
# the n qubits of the quantum register of the quantum circuit
# implementing the Quantum Phase Estimation (QPE),
# as part of the Quantum Fourier Transform (QFT)
def apply_controlled_phases( theta, circuit, n ):
# for each ith step according to
# the number of n qubits used
for step in range(n):
# compute the iteration parameter t
# as a power of 2, according to the current step
t = 2**step
# for each iteration according to
# the iteration parameter t
for _ in range(t):
# apply the Controlled-Phase gate for the theta angle,
# with control on the ith qubit and target on the last qubit
circuit.cp( theta, step, n )
# define the function to perform the Swap gates on
# the n qubits of the quantum register of the quantum circuit
# implementing the Quantum Phase Estimation (QPE),
# as part of the Quantum Fourier Transform (QFT)
def apply_swaps( circuit, n ):
# for a number of iterations equal to half of
# the number of phase counting qubits used
# on the resepective quantum circuit
# for the Quantum Fourier Transform (QFT)
for qubit_idx in range( phase_register_size // 2 ):
# apply the Swap gate between the kth qubit and
# the (n - k)th qubit on the quantum register defined before
circuit.swap( qubit_idx, ( n - qubit_idx - 1 ) )
# define the function to perform
# the Inverse Quantum Fourier Transform (IQFT) on
# the n qubits of the quantum register of the quantum circuit
# implementing the Quantum Phase Estimation (QPE)
def apply_quantum_fourier_transform_inverse( circuit, n ):
# for each jth qubit on the quantum register
for j in range(n):
# for each additional mth qubit ranging to
# the current jth qubit being iterated before
for m in range(j):
# apply the Controlled-Phase gate for
# the theta angle equal to -pi / ( 2^( j - m ) ),
# with control on the mth qubit and target on the jth qubit
circuit.cp( -np.pi / float( 2**( j - m ) ), m, j )
# apply the Hadamard gate to the jth qubit
circuit.h(j)
# define the function to perform a measurement of
# all the n qubits on the quantum register of a quantum circuit,
# and storing the classical outcomes on the n bits of
# the classical register of that same quantum circuit
def measure_all_qubits( circuit, n ):
# for each pair of qubits and bits
for j in range(n):
# measure the current qubit on the quantum register,
# and stores the classical outcome obtained
# in the current bit on the classical register
circuit.measure(j, j)
# define the function to create a quantum circuit,
# implementing the Quantum Phase Estimation (QPE) on (n + 1) qubits
def qpe_circuit(register_size):
#########################################
#### your code goes here ####
# define the theta phase angle to estimate
theta = 1/7
# create the quantum circuit with a quantum register with (n + 1) qubits
# and a classical register with n bits, intended to implement
# the Quantum Phase Estimation (QPE) on n qubits
qpe = QuantumCircuit( ( register_size + 1 ), register_size )
# perform the Quantum Hadamard Transform on
# the n qubits of the quantum register of
# the quantum circuit implementing
# the Quantum Phase Estimation (QPE)
apply_quantum_hadamard_transform( qpe, register_size )
# apply the Pauli-X gate to the last qubit on
# the quantum register of the quantum circuit of
# the Quantum Phase Estimation (QPE)
qpe.x(register_size)
# apply a barrier to the quantum circuit of
# the Quantum Phase Estimation (QPE)
qpe.barrier()
# perform the Controlled-Phase gates on
# the n qubits of the quantum register of the quantum circuit
# implementing the Quantum Phase Estimation (QPE),
# as part of the Quantum Fourier Transform (QFT)
apply_controlled_phases( theta, qpe, register_size )
# apply a barrier to the quantum circuit of
# the Quantum Phase Estimation (QPE)
qpe.barrier()
# perform the Swap gates on the n qubits of
# the quantum register of the quantum circuit
# implementing the Quantum Phase Estimation (QPE),
# as part of the Quantum Fourier Transform (QFT)
apply_swaps( qpe, register_size )
# apply a barrier to the quantum circuit of
# the Quantum Phase Estimation (QPE)
qpe.barrier()
# perform the Inverse Quantum Fourier Transform (IQFT) on
# the n qubits of the quantum register of the quantum circuit
# implementing the Quantum Phase Estimation (QPE)
apply_quantum_fourier_transform_inverse( qpe, register_size )
# apply a barrier to the quantum circuit of
# the Quantum Phase Estimation (QPE)
qpe.barrier()
# perform a measurement of all the n qubits on
# the quantum register of the quantum circuit of
# the Quantum Phase Estimation (QPE) and storing
# the classical outcomes on the n bits of
# the classical register of that same quantum circuit
measure_all_qubits( qpe, register_size )
# return the quantum circuit, implementing
# the Quantum Phase Estimation (QPE) on n qubits
return qpe
#########################################
# run this cell to simulate 'qpe' and
# to plot the histogram of the result
# define several quantum register sizes
# equal to n, allowing to vary them
#reg_size = 4
reg_size = 5
#reg_size = 6
#reg_size = 7
#reg_size = 8
# create a quantum circuit for
# the Quantum Phase Estimation (QPE),
# given the quantum register defined before,
# with n counting qubits
qpe_check = qpe_circuit( reg_size )
# create the Aer Simulator object
sim = Aer.get_backend("aer_simulator")
# define the number of shots
shots = 10000
# execute the simulation for the Quantum Phase Estimation (QPE),
# with n counting qubits, and retrieve its result counts
count_qpe = execute( qpe_check, sim, shots=shots ).result().get_counts()
# plot the histogram of the result counts of the quantum simulation
# for the Quantum Phase Estimation (QPE), with n counting qubits
plot_histogram( count_qpe, figsize=(9,5) )
# process the result count data to determine accuracy of
# the estimated phase and grab the highest probability measurement
# define the maximum number of counts which will be obtained
max_binary_counts = 0
# define the maximum binary value which will be obtained
max_binary_val = ""
# for each count obtained from the quantum simulation of
# the Quantum Phase Estimation (QPE)
for key, item in count_qpe.items():
# if the current number of counts is greater than
# the current maximum number of counts obtained
if item > max_binary_counts:
# update the maximum number of counts obtained
max_binary_counts = item
# update the maximum binary value obtained
max_binary_val = key
#########################################
#### your function to convert a binary ####
#### string to a decimal number goes here ####
# define the function to convert
# a binary string to a decimal number
def bin_to_decimal( binary_string ):
# return a binary string
# converted to a decimal number
return int( binary_string, 2 )
# calculate the estimated phase obtained
# from the quantum simulation of
# the Quantum Phase Estimation (QPE)
estimated_phase = ( bin_to_decimal(max_binary_val) / 2**reg_size )
# print the estimated phase obtained
# from the quantum simulation of
# the Quantum Phase Estimation (QPE)
print("Estimated Phase:", estimated_phase)
# calculate the phase accuracy
# which can be obtained from
# the quantum simulation of
# the Quantum Phase Estimation (QPE)
# with the quantum circuit defined before,
# inverse of the highest power of 2
# (i.e. smallest decimal) this quantum circuit can estimate
phase_accuracy_window = 2**( -reg_size )
# print the phase accuracy
# which can be obtained from
# the quantum simulation of
# the Quantum Phase Estimation (QPE)
# with the quantum circuit defined before,
# inverse of the highest power of 2
# (i.e. smallest decimal) this quantum circuit can estimate
print("Phase Accuracy Window:", phase_accuracy_window)
# define the theta phase angle,
# which was pretended to be estimated
theta = 1 / 7
# compute the accuracy of the estimated phase,
# as the distance between the estimated phase
# and the theta phase angle, which was pretended to be estimated
accuracy_estimated_phase = abs( theta - estimated_phase )
# print the accuracy of the estimated phase,
# as the distance between the estimated phase
# and the theta phase angle, which was pretended to be estimated
print("Accuracy of the Estimated Phase:", accuracy_estimated_phase)
### put your answer here ###
# to estimate accurately the phase information to be within 2^(-6)
# we need n + 1 = 6 (=) n = 5 qubits to store the phase information
required_register_size = 5
### submit your answer ###
# import the grader for the exercise 4 of the lab 3
from qc_grader.challenges.qgss_2023 import grade_lab3_ex4
# grade the exercise 4 of the lab 3
grade_lab3_ex4( required_register_size )
# create 7 mod 15 unitary operator
# for a quantum circuit
N = 15
# define the number of m qubits required
# for the 7 mod 15 operator to be executed
m = int( np.ceil( np.log2( N ) ) )
# create the quantum circuit with
# a quantum register of m qubits
# to implement the 7 mod 15 unitary operator
U_qc = QuantumCircuit( m )
# apply the Pauli-X gate to all the m qubits of
# the quantum register of the quantum circuit
# implementing the 7 mod 15 unitary operator
U_qc.x( range(m) )
# apply the Swap gate between the 2nd qubit and
# the 3rd qubit on the quantum register of
# the quantum circuit implementing
# the 7 mod 15 unitary operator
U_qc.swap(1, 2)
# apply the Swap gate between the 3rd qubit and
# the 4th qubit on the quantum register of
# the quantum circuit implementing
# the 7 mod 15 unitary operator
U_qc.swap(2, 3)
# apply the Swap gate between the 1st qubit and
# the 4th qubit on the quantum register of
# the quantum circuit implementing
# the 7 mod 15 unitary operator
U_qc.swap(0, 3)
# convert the quantum circuit implementing
# the 7 mod 15 unitary operator to
# a quantum unitary gate
U = U_qc.to_gate()
# define the name of the 7 mod 15
# unitary operator created before
U.name ="{}Mod{}".format(7, N)
# your code goes here
# print the number of qubits
print("Num. qubits: m =", m);
# define the quantum circuits for the inputs
# |1> = |0001>, |2> = |0010>, and |5> = |0101>
#########################################
# create the a quantum circuit with m qubits,
# for the input state |1> = |0001>
qcirc_input_1 = QuantumCircuit(m)
# apply the Pauli-X gate to
# the 1st qubit of the quantum register of
# the quantum circuit defined before
qcirc_input_1.x(0)
# apply the U gate to all
# the m qubits of the quantum register of
# the quantum circuit defined before
qcirc_input_1.append( U, range(m) )
# measure all the m qubits of
# the quantum register of
# the quantum circuit defined before
qcirc_input_1.measure_all()
#########################################
# create the a quantum circuit with m qubits,
# for input state |2> = |0010>
qcirc_input_2 = QuantumCircuit(m)
# apply the Pauli-X gate to
# the 2nd qubit of the quantum register of
# the quantum circuit defined before
qcirc_input_2.x(1)
# apply the U gate to all
# the m qubits of the quantum register of
# the quantum circuit defined before
qcirc_input_2.append( U, range(m) )
# measure all the m qubits of
# the quantum register of
# the quantum circuit defined before
qcirc_input_2.measure_all()
#########################################
# create the a quantum circuit with m qubits,
# for input state |5> = |0101>
qcirc_input_5 = QuantumCircuit(m)
# apply the Pauli-X gate to
# the 1st qubit of the quantum register of
# the quantum circuit defined before
qcirc_input_5.x(0)
# apply the Pauli-X gate to
# the 3rd qubit of the quantum register of
# the quantum circuit defined before
qcirc_input_5.x(2)
# apply the U gate to all
# the m qubits of the quantum register of
# the quantum circuit defined before
qcirc_input_5.append( U, range(m) )
# measure all the m qubits of
# the quantum register of
# the quantum circuit defined before
qcirc_input_5.measure_all()
#########################################
# run this cell to simulate 'qcirc' and to plot the histogram of the result
# create the Aer Simulator object
sim = Aer.get_backend("aer_simulator")
# define the number of shots
shots = 20000
# save the count data for the input state |1> = |0001>
input_1 = execute(qcirc_input_1, sim, shots=shots).result().get_counts()
# save the count data for the input state |2> = |0010>
input_2 = execute(qcirc_input_2, sim, shots=shots).result().get_counts()
# save the count data for the input state |5> = |0101>
input_5 = execute(qcirc_input_5, sim, shots=shots).result().get_counts()
# submit your answer
# import the grader for the exercise 5 of the lab 3
from qc_grader.challenges.qgss_2023 import grade_lab3_ex5
# grade the exercise 5 of the lab 3
grade_lab3_ex5( [ input_1, input_2, input_5 ] )
# create an unitary quantum circuit
# with a quantum register of m qubits
unitary_circ = QuantumCircuit(m)
#### your code goes here ####
# for each iteration in a range of 2^2 = 4
for _ in range( 2**2 ):
# apply the U gate on all
# the m qubits on the quantum register
unitary_circ.append( U, range(m) )
# create a Unitary Simulator object
sim = Aer.get_backend("unitary_simulator")
# execute the quantum simulation of
# an unitary quantum circuit with
# a quantum register of m qubits,
# defined before, retrieving its unitary operator
unitary = execute( unitary_circ, sim ).result().get_unitary()
# submit your answer
# import the grader for the exercise 6 of the lab 3
from qc_grader.challenges.qgss_2023 import grade_lab3_ex6
# grade the exercise 6 of the lab 3
grade_lab3_ex6( unitary, unitary_circ )
# define the function to built a 2^k-Controlled-U gate object,
# which repeats the action of the operator U, 2^k times
def cU_multi(k):
# define the size n of the system's quantum register
sys_register_size = 4
# create the quantum circuit with n qubits on
# the system's quantum register, to build
# a 2^k-Controlled-U gate object
circ = QuantumCircuit( sys_register_size )
# for each iteration ranging until 2^k
for _ in range(2**k):
# apply the U gate to all the n qubits on
# the system's quantum register of
# the quantum circuit to represent
# the 2^k-Controlled-U gate
circ.append(U, range(sys_register_size))
# convert the operator resulting from the construction of
# the quantum circuit defined before, to a quantum gate
U_multi = circ.to_gate()
# define the name of the 2^k-Controlled-U gate,
# as being a "7 Mod 15 gate"
U_multi.name = "7Mod15_[2^{}]".format(k)
# set this 2^k-Controlled-U gate as multi-qubit gate,
# depending on a given control qubit
cU_multi = U_multi.control()
# return the 2^k-Controlled-U gate object,
# which repeats the action of the operator U, 2^k times
return cU_multi
# define the size m of the quantum register
# for the phase counting of the qubits
phase_register_size = 8
# define the size n of the quantum register
# for the successive applications of
# the 2^k-Controlled-U gate defined before
cu_register_size = 4
# create the Quantum Circuit needed to run
# with m = 8 qubits for the phase counting
# and with n = 4 qubits for the successive
# applications of the 2^k-Controlled-U gate
# defined before, to implement the Shor's Algorithm
# for Factoring, based on Quantum Phase Estimation (QPE)
shor_qpe = QuantumCircuit( ( phase_register_size + cu_register_size ),
phase_register_size )
# perform the Quantum Hadamard Transform on
# the m qubits for the phase counting of
# the quantum register of the quantum circuit
# implementing the Shor's Algorithm for Factoring,
# based on Quantum Phase Estimation (QPE)
apply_quantum_hadamard_transform( shor_qpe, phase_register_size )
# apply the Pauli-X gate to the last qubit on
# the quantum register of the quantum circuit to
# implement the Shor's Algorithm for Factoring,
# based on Quantum Phase Estimation (QPE)
shor_qpe.x( phase_register_size )
# apply a barrier to the quantum circuit to
# implement the Shor's Algorithm for Factoring,
# based on Quantum Phase Estimation (QPE)
shor_qpe.barrier()
# for each kth qubit on the quantum register
# for the phase counting of the qubits
for k in range( phase_register_size ):
# retrieve the 2^k-Controlled-U gate object,
# which repeats the action of the operator U,
# 2^k times, defined before
cU = cU_multi(k)
# apply the 2^k-Controlled-U gate object,
# which repeats the action of the operator U,
# 2^k times, defined before, for the kth iteration,
# to the quantum circuit to implement
# the Shor's Algorithm for Factoring,
# based on Quantum Phase Estimation (QPE)
shor_qpe.append( cU, [k] + list( range( phase_register_size,
( phase_register_size + cu_register_size ) ) ) )
# apply a barrier to the quantum circuit to
# implement the Shor's Algorithm for Factoring,
# based on Quantum Phase Estimation (QPE)
shor_qpe.barrier()
# perform the Swap gates on the n qubits of
# the quantum register of the quantum circuit
# implementing the Quantum Phase Estimation (QPE),
# as part of the Quantum Fourier Transform (QFT),
# required to build the quantum circuit to implement
# the Shor's Algorithm for Factoring,
# based on Quantum Phase Estimation (QPE)
apply_swaps(shor_qpe, phase_register_size)
# apply a barrier to the quantum circuit to
# implement the Shor's Algorithm for Factoring,
# based on Quantum Phase Estimation (QPE)
shor_qpe.barrier()
# perform the Inverse Quantum Fourier Transform (IQFT) on
# the m qubits for the phase counting of
# the quantum register of the quantum circuit
# implementing the Shor's Algorithm for Factoring,
# based on Quantum Phase Estimation (QPE)
apply_quantum_fourier_transform_inverse( shor_qpe, phase_register_size )
# apply a barrier to the quantum circuit to
# implement the Shor's Algorithm for Factoring,
# based on Quantum Phase Estimation (QPE)
shor_qpe.barrier()
# perform a measurement of all
# the m qubits for the phase counting of
# the quantum register of the quantum circuit
# implementing the Shor's Algorithm for Factoring,
# based on Quantum Phase Estimation (QPE)
shor_qpe.measure( range( phase_register_size ),
range( phase_register_size ) )
# draw the quantum circuit implementing
# the quantum circuit to
# implement the Shor's Algorithm for Factoring,
# based on Quantum Phase Estimation (QPE)
shor_qpe.draw("mpl")
# run this cell to simulate 'shor_qpe' and
# to plot the histogram of the results
# create an Aer Simulator object
sim = Aer.get_backend("aer_simulator")
# define the number of shots
shots = 20000
# execute the quantum simulation for
# the quantum circuit for the Shor's Algorithm,
# based on Quantum Phase Estimation (QPE),
# with n phase counting qubits, and retrieve
# the result counts of this quantum simulation
shor_qpe_counts = execute(shor_qpe, sim, shots=shots).result().get_counts()
# plot the histogram of the result counts of the quantum simulation
# for the quantum circuit for the Shor's Algorithm, based on
# Quantum Phase Estimation (QPE), with n phase counting qubits
plot_histogram( shor_qpe_counts, figsize=(9,5) )
# submit your answer
# import the grader for the exercise 7 of the lab 3
from qc_grader.challenges.qgss_2023 import grade_lab3_ex7
# grade the exercise 7 of the lab 3
grade_lab3_ex7( shor_qpe_counts )
# import the Fraction object
# from the built-in fractions module
from fractions import Fraction
# print the number '0.666',
# as an unlimited Fraction object
print( "Unlimited Fraction(0.666):",
Fraction(0.666), '\n')
# print the number '0.666',
# as a limited Fraction object
# with the denominator of 15
print( "Limited Fraction(0.666), with a max. denominator of 15:",
Fraction(0.666).limit_denominator(15) )
# create a list with the estimated phases of the result counts
# obtained from the execution of the quantum simulation
# for the Quantum Phase Estimation (QPE), with n counting qubits
estimated_phases = [ bin_to_decimal(binary_val) / 2**phase_register_size
for binary_val in shor_qpe_counts ]
# print the list with the estimated phases of the result counts
# obtained from the execution of the quantum simulation
# for the Quantum Phase Estimation (QPE), with n counting qubits
print( "Estimated Phases:", estimated_phases )
# create a list of with the estimated phases of the result counts
# obtained from the execution of the quantum simulation
# for the Quantum Phase Estimation (QPE), with n counting qubits,
# represented as Fraction objects with the format s/r
shor_qpe_fractions = [ Fraction(estimated_phase).limit_denominator(15)
for estimated_phase in estimated_phases ]
# print the list of with the estimated phases of the result counts
# obtained from the execution of the quantum simulation
# for the Quantum Phase Estimation (QPE), with n counting qubits,
# represented as Fraction objects with the format s/r
print( "Estimated Fractions:", shor_qpe_fractions )
# submit your answer
# import the grader for the exercise 8 of the lab 3
from qc_grader.challenges.qgss_2023 import grade_lab3_ex8
# grade the exercise 8 of the lab 3
grade_lab3_ex8( shor_qpe_fractions )
# define the function to create and execute
# the Shor's Algorithm for Factoring,
# based on Quantum Phase Estimation (QPE),
# with k phase counting qubits
def shor_qpe(k):
# define the co-prime a
a = 7
# define the number N to factor
N = 15
# compute the number m of
# additional qubits required
m = int( np.ceil( np.log2(N) ) )
#################################################
# step 1. Begin a while loop until a nontrivial guess is found
#### your code goes here ####
# define the boolean flag to determine
# if a non trivial guess was found, initially as False
non_trivial_guess_found = False
# while no trivial factor guess was found,
# execute the while loop
while( not non_trivial_guess_found ):
#################################################
# step 2a. construct a QPE quantum circuit
# with m phase counting qubits to guess
# the phase phi = s/r, using the function
# cU_multi() defined before
#### your code goes here ####
# create a quantum circuit for
# the Shor's Algorithm for Factoring,
# based on Quantum Phase Estimation (QPE),
# with k phase counting qubits,
# and additional m qubits for
# the successive applications of
# the 2^k-Controlled-U gate defined before
qc = QuantumCircuit( ( k + m ), k)
# perform the Quantum Hadamard Transform on
# the k phase counting qubits of the respective
# quantum register of the quantum circuit
# for the Shor's Algorithm for Factoring,
# based on Quantum Phase Estimation (QPE)
apply_quantum_hadamard_transform( qc, k )
# apply a Pauli-X gate to the last
# phase counting qubit of the respective
# quantum register of the quantum circuit
# for the Shor's Algorithm for Factoring,
# based on Quantum Phase Estimation (QPE)
qc.x(k)
# apply a barrier to the quantum circuit for
# the Shor's Algorithm for Factoring,
# based on Quantum Phase Estimation (QPE),
# with k phase counting qubits,
# and additional m qubits for
# the successive applications of
# the 2^k-Controlled-U gate defined before
qc.barrier()
# for each kth qubit on the quantum register
# for the phase counting of the qubits
for k_i in range(k):
# retrieve the 2^k-Controlled-U gate object,
# which repeats the action of the operator U,
# 2^k times, defined before
cU = cU_multi(k_i)
# apply the 2^k-Controlled-U gate object,
# which repeats the action of the operator U,
# 2^k times, defined before, for the kth iteration,
# to the quantum circuit for the Shor's Algorithm
# for Factoring, based on Quantum Phase Estimation (QPE),
# with k phase counting qubits, and additional m qubits
# for the successive applications of
# the 2^k-Controlled-U gate defined before
qc.append( cU, [k_i] + list( range( k, ( k + m ) ) ) )
# apply a barrier to the quantum circuit for
# the Shor's Algorithm for Factoring,
# based on Quantum Phase Estimation (QPE),
# with k phase counting qubits,
# and additional m qubits for
# the successive applications of
# the 2^k-Controlled-U gate defined before
qc.barrier()
# perform the Swap gates on the k
# phase counting qubits of the respective
# quantum register of the quantum circuit
# for the Shor's Algorithm for Factoring,
# based on Quantum Phase Estimation (QPE),
# as part of the Quantum Fourier Transform (QFT)
apply_swaps( qc, k )
# apply a barrier to the quantum circuit for
# the Shor's Algorithm for Factoring,
# based on Quantum Phase Estimation (QPE),
# with k phase counting qubits,
# and additional m qubits for
# the successive applications of
# the 2^k-Controlled-U gate defined before
qc.barrier()
# perform the Inverse Quantum Fourier Transform (IQFT) on
# the k phase counting qubits of the respective
# quantum register of the quantum circuit
# for the Shor's Algorithm for Factoring,
# based on Quantum Phase Estimation (QPE)
apply_quantum_fourier_transform_inverse( qc, k )
# apply a barrier to the quantum circuit for
# the Shor's Algorithm for Factoring,
# based on Quantum Phase Estimation (QPE),
# with k phase counting qubits,
# and additional m qubits for
# the successive applications of
# the 2^k-Controlled-U gate defined before
qc.barrier()
# perform a measurement of all
# the k phase counting qubits of the respective
# quantum register of the quantum circuit
# for the Shor's Algorithm for Factoring,
# based on Quantum Phase Estimation (QPE)
qc.measure( range(k), range(k) )
#################################################
# step 2b. run the QPE quantum circuit with a single shot,
# record the results and convert the estimated phase
# bitstring to a decimal format
#### your code goes here ####
# create an Aer Simulator object
sim = Aer.get_backend("aer_simulator")
# define the number of shots
shots = 1
# execute the simulation for the Quantum Phase Estimation (QPE),
# with n counting qubits, and retrieve the result counts
# obtained from this quantum simulation
shor_qpe_counts = execute( qc, sim, shots=shots ).result().get_counts()
# plot the histogram of the result counts of the quantum simulation
# for the Quantum Phase Estimation (QPE), with n counting qubits
plot_histogram( shor_qpe_counts, figsize=(9,5) )
# compute the estimated phases from the result counts
# obtained from the quantum simulation of the quantum circuit
# implementing the Shor's Algorithm for Factoring,
# based on Quantum Phase Estimation (QPE)
estimated_phases = [ bin_to_decimal( binary_val ) / 2**k
for binary_val in shor_qpe_counts ]
#################################################
# step 3. use the Fraction object to find the guess for r
#### your code goes here ####
# convert the estimated phase to a fraction s/r format
fraction_s_r = [ Fraction(estimated_phase).limit_denominator(N)
for estimated_phase in estimated_phases ][0]
# retrieve the numerator s and the denominator r
# from the estimated phase represented as a fraction
s, r = fraction_s_r.numerator, fraction_s_r.denominator
#################################################
# step 4. now that r has been found, use the built-in
# greatest common divisor function to determine
# the guesses for a factor of N
# build the list of guesses for possible non-trivial factors of N
guesses = [ gcd( a**( r // 2 ) - 1, N ),
gcd( a**( r // 2 ) + 1, N ) ]
#################################################
# step 5. for each guess in guesses, check if
# at least one is a non-trivial factor,
# i.e., ( ( guess != 1 ) or ( guess != N ) )
# and ( N % guess == 0 )
#### your code goes here ####
# for each of the guesses computed before
for guess in guesses:
# if the current guess is not a trivial factor
if ( ( ( guess != 1 ) or ( guess != N ) )
and ( N % guess == 0 ) ):
# update the boolean flag to determine
# if a non trivial guess was found, as True
non_trivial_guess_found = True
# break the current for loop
break
#################################################
# step 6. if a non-trivial factor is found return
# the list 'guesses', otherwise
# continue the while loop
# return the list of the guesses,
# containing a non-trivial factor of N
return guesses
#################################################
# submit your circuit
# import the grader for the exercise 9 of the lab 3
from qc_grader.challenges.qgss_2023 import grade_lab3_ex9
# grade the exercise 9 of the lab 3
grade_lab3_ex9( shor_qpe )
# import the IBM's Qiskit Jupyter Tools
import qiskit.tools.jupyter
# show the table of the IBM's Qiskit version
%qiskit_version_table
|
https://github.com/MonitSharma/Qiskit-Summer-School-and-Quantum-Challenges
|
MonitSharma
|
from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister
import numpy as np
def step_1_circuit(qr: QuantumRegister, cr: ClassicalRegister) -> QuantumCircuit:
# qr is a quantum register with 2 qubits
# cr is a classical register with 2 bits
qc = QuantumCircuit(qr, cr)
####### your code goes here #######
##1 Initialization
q0, q1 = qr
# apply Hadamard on the auxiliary qubit
qc.h(q0)
# put the system qubit into the |1> state
qc.x(q1)
##2 Apply control-U operator as many times as needed to get the least significant phase bit
# controlled-S is equivalent to CPhase with angle pi / 2
s_angle = np.pi / 2
# we want to apply controlled-S 2^k times
k = 1
# calculate the angle of CPhase corresponding to 2^k applications of controlled-S
cphase_angle = s_angle * 2**k
# apply the controlled phase gate
qc.cp(cphase_angle, q0, q1)
##3 Measure the auxiliary qubit in x-basis into the first classical bit
# apply Hadamard to change to the X basis
qc.h(q0)
# measure the auxiliary qubit into the first classical bit
c0, _ = cr
qc.measure(q0, c0)
return qc
qr = QuantumRegister(2, "q")
cr = ClassicalRegister(2, "c")
qc = QuantumCircuit(qr, cr)
qc = step_1_circuit(qr, cr)
qc.draw("mpl")
# Submit your circuit
from qc_grader.challenges.qgss_2023 import grade_lab4_ex1
grade_lab4_ex1(qc)
def step_2_circuit(qr: QuantumRegister, cr: ClassicalRegister) -> QuantumCircuit:
# qr is a quantum register with 2 qubits
# cr is a classical register with 2 bits
# begin with the circuit from Step 1
qc = step_1_circuit(qr, cr)
####### your code goes here #######
##1 Reset and re-initialize the auxiliary qubit
q0, q1 = qr
# reset the auxiliary qubit
qc.reset(q0)
# apply Hadamard on the auxiiliary qubit
qc.h(q0)
##2 Apply phase correction conditioned on the first classical bit
c0, c1 = cr
with qc.if_test((c0, 1)):
qc.p(-np.pi / 2, q0)
##3 Apply control-U operator as many times as needed to get the next phase bit
# controlled-S is equivalent to CPhase with angle pi / 2
s_angle = np.pi / 2
# we want to apply controlled-S 2^k times
k = 0
# calculate the angle of CPhase corresponding to 2^k applications of controlled-S
cphase_angle = s_angle * 2**k
# apply the controlled phase gate
qc.cp(cphase_angle, q0, q1)
##4 Measure the auxiliary qubit in x-basis into the second classical bit
# apply Hadamard to change to the X basis
qc.h(q0)
# measure the auxiliary qubit into the first classical bit
qc.measure(q0, c1)
return qc
qr = QuantumRegister(2, "q")
cr = ClassicalRegister(2, "c")
qc = QuantumCircuit(qr, cr)
qc = step_2_circuit(qr, cr)
qc.draw("mpl")
# Submit your circuit
from qc_grader.challenges.qgss_2023 import grade_lab4_ex2
grade_lab4_ex2(qc)
from qiskit_aer import AerSimulator
sim = AerSimulator()
job = sim.run(qc, shots=1000)
result = job.result()
counts = result.get_counts()
counts
from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister
import numpy as np
def t_gate_ipe_circuit(qr: QuantumRegister, cr: ClassicalRegister) -> QuantumCircuit:
# qr is a quantum register with 2 qubits
# cr is a classical register with 3 bits
qc = QuantumCircuit(qr, cr)
####### your code goes here #######
# Initialization
q0, q1 = qr
qc.h(q0)
qc.x(q1)
# Apply control-U operator as many times as needed to get the least significant phase bit
t_angle = np.pi / 4
k = 2
cphase_angle = t_angle * 2**k
qc.cp(cphase_angle, q0, q1)
# Measure the auxiliary qubit in x-basis into the first classical bit
qc.h(q0)
c0, c1, c2 = cr
qc.measure(q0, c0)
# Reset and re-initialize the auxiliary qubit
qc.reset(q0)
qc.h(q0)
# Apply phase correction conditioned on the first classical bit
with qc.if_test((c0, 1)):
qc.p(-np.pi / 2, q0)
# Apply control-U operator as many times as needed to get the next phase bit
k = 1
cphase_angle = t_angle * 2**k
qc.cp(cphase_angle, q0, q1)
# Measure the auxiliary qubit in x-basis into the second classical bit
qc.h(q0)
qc.measure(q0, c1)
# Reset and re-initialize the auxiliary qubit
qc.reset(q0)
qc.h(q0)
# Apply phase correction conditioned on the first and second classical bits
with qc.if_test((c0, 1)):
qc.p(-np.pi / 4, q0)
with qc.if_test((c1, 1)):
qc.p(-np.pi / 2, q0)
# Apply control-U operator as many times as needed to get the next phase bit
k = 0
cphase_angle = t_angle * 2**k
qc.cp(cphase_angle, q0, q1)
# Measure the auxiliary qubit in x-basis into the third classical bit
qc.h(q0)
qc.measure(q0, c2)
return qc
qr = QuantumRegister(2, "q")
cr = ClassicalRegister(3, "c")
qc = QuantumCircuit(qr, cr)
qc = t_gate_ipe_circuit(qr, cr)
qc.draw("mpl")
from qiskit_aer import AerSimulator
sim = AerSimulator()
job = sim.run(qc, shots=1000)
result = job.result()
counts = result.get_counts()
counts
# Submit your circuit
from qc_grader.challenges.qgss_2023 import grade_lab4_ex3
grade_lab4_ex3(qc)
from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister
import numpy as np
def u_circuit(qr: QuantumRegister, cr: ClassicalRegister) -> QuantumCircuit:
# qr is a quantum register with 2 qubits
# cr is a classical register with 2 bits
qc = QuantumCircuit(qr, cr)
# Initialization
q0, q1 = qr
qc.h(q0)
qc.x(q1)
# Apply control-U operator as many times as needed to get the least significant phase bit
u_angle = 2 * np.pi / 3
k = 1
cphase_angle = u_angle * 2**k
qc.cp(cphase_angle, q0, q1)
# Measure the auxiliary qubit in x-basis into the first classical bit
qc.h(q0)
c0, c1 = cr
qc.measure(q0, c0)
# Reset and re-initialize the auxiliary qubit
qc.reset(q0)
qc.h(q0)
# Apply phase correction conditioned on the first classical bit
with qc.if_test((c0, 1)):
qc.p(-np.pi / 2, q0)
# Apply control-U operator as many times as needed to get the next phase bit
k = 0
cphase_angle = u_angle * 2**k
qc.cp(cphase_angle, q0, q1)
# Measure the auxiliary qubit in x-basis into the second classical bit
qc.h(q0)
qc.measure(q0, c1)
return qc
qr = QuantumRegister(2, "q")
cr = ClassicalRegister(2, "c")
qc = QuantumCircuit(qr, cr)
qc = u_circuit(qr, cr)
qc.draw("mpl")
from qiskit_aer import AerSimulator
sim = AerSimulator()
job = sim.run(qc, shots=1000)
result = job.result()
counts = result.get_counts()
print(counts)
success_probability = counts["01"] / counts.shots()
print(f"Success probability: {success_probability}")
from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister
import numpy as np
def u_circuit(qr: QuantumRegister, cr: ClassicalRegister) -> QuantumCircuit:
# qr is a quantum register with 2 qubits
# cr is a classical register with 1 bits
qc = QuantumCircuit(qr, cr)
# Initialization
q0, q1 = qr
qc.h(q0)
qc.x(q1)
# Apply control-U operator as many times as needed to get the least significant phase bit
u_angle = 2 * np.pi / 3
k = 1
cphase_angle = u_angle * 2**k
qc.cp(cphase_angle, q0, q1)
# Measure the auxiliary qubit in x-basis
qc.h(q0)
(c0,) = cr
qc.measure(q0, c0)
return qc
qr = QuantumRegister(2, "q")
cr = ClassicalRegister(1, "c")
qc = QuantumCircuit(qr, cr)
qc = u_circuit(qr, cr)
qc.draw("mpl")
job = sim.run(qc, shots=15)
result = job.result()
counts = result.get_counts()
print(counts)
step1_bit: int
####### your code goes here #######
step1_bit = 1 if counts["1"] > counts["0"] else 0
print(step1_bit)
# Submit your result
from qc_grader.challenges.qgss_2023 import grade_lab4_ex4
grade_lab4_ex4(step1_bit)
from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister
import numpy as np
def u_circuit(qr: QuantumRegister, cr: ClassicalRegister) -> QuantumCircuit:
# qr is a quantum register with 2 qubits
# cr is a classical register with 2 bits
qc = QuantumCircuit(qr, cr)
####### your code goes here #######
# Initialization
q0, q1 = qr
if step1_bit:
qc.x(q0)
qc.x(q1)
# Measure the auxiliary qubit
c0, c1 = cr
qc.measure(q0, c0)
# Reset and re-initialize the auxiliary qubit
qc.reset(q0)
qc.h(q0)
# Apply phase correction conditioned on the first classical bit
with qc.if_test((c0, 1)):
qc.p(-np.pi / 2, q0)
# Apply control-U operator as many times as needed to get the next phase bit
u_angle = 2 * np.pi / 3
k = 0
cphase_angle = u_angle * 2**k
qc.cp(cphase_angle, q0, q1)
# Measure the auxiliary qubit in x-basis into the second classical bit
qc.h(q0)
qc.measure(q0, c1)
return qc
qr = QuantumRegister(2, "q")
cr = ClassicalRegister(2, "c")
qc = QuantumCircuit(qr, cr)
qc = u_circuit(qr, cr)
qc.draw("mpl")
# Submit your result
from qc_grader.challenges.qgss_2023 import grade_lab4_ex5
grade_lab4_ex5(qc)
from qiskit_aer import AerSimulator
sim = AerSimulator()
job = sim.run(qc, shots=1000)
result = job.result()
counts = result.get_counts()
print(counts)
success_probability = counts["01"] / counts.shots()
print(f"Success probability: {success_probability}")
from qiskit.circuit import Gate
def iterative_phase_estimation(
qr: QuantumRegister,
cr: ClassicalRegister,
controlled_unitaries: list[Gate],
state_prep: Gate,
) -> QuantumCircuit:
qc = QuantumCircuit(qr, cr)
####### your code goes here #######
auxiliary_qubit = qr[0]
system_qubits = qr[1:]
qc.append(state_prep, system_qubits)
for i in range(len(cr)):
k = len(cr) - 1 - i
qc.reset(auxiliary_qubit)
qc.h(auxiliary_qubit)
for j in range(i):
with qc.if_test((cr[j], 1)):
qc.p(-np.pi / 2 ** (i - j), auxiliary_qubit)
qc.append(controlled_unitaries[k], qr)
qc.h(auxiliary_qubit)
qc.measure(auxiliary_qubit, cr[i])
return qc
from qiskit.circuit.library import CPhaseGate, XGate
qr = QuantumRegister(2, "q")
cr = ClassicalRegister(2, "c")
s_angle = np.pi / 2
controlled_unitaries = [CPhaseGate(s_angle * 2**k) for k in range(2)]
qc = iterative_phase_estimation(qr, cr, controlled_unitaries, XGate())
sim = AerSimulator()
job = sim.run(qc, shots=1000)
result = job.result()
counts = result.get_counts()
counts
from qiskit_ibm_provider import IBMProvider
provider = IBMProvider()
hub = "YOUR_HUB"
group = "YOUR_GROUP"
project = "YOUR_PROJECT"
backend_name = "ibmq_manila"
backend = provider.get_backend(backend_name, instance=f"{hub}/{group}/{project}")
from qiskit import transpile
qr = QuantumRegister(2, "q")
cr = ClassicalRegister(2, "c")
qc = QuantumCircuit(qr, cr)
qc = step_2_circuit(qr, cr)
qc_transpiled = transpile(qc, backend)
job = backend.run(qc_transpiled, shots=1000, dynamic=True)
job_id = job.job_id()
print(job_id)
retrieve_job = provider.retrieve_job(job_id)
retrieve_job.status()
from qiskit.tools.visualization import plot_histogram
counts = retrieve_job.result().get_counts()
plot_histogram(counts)
|
https://github.com/MonitSharma/Qiskit-Summer-School-and-Quantum-Challenges
|
MonitSharma
|
from qiskit import QuantumCircuit, QuantumRegister
from qiskit.quantum_info import SparsePauliOp
def heisenberg_hamiltonian(
length: int, jx: float = 1.0, jy: float = 0.0, jz: float = 0.0
) -> SparsePauliOp:
terms = []
for i in range(length - 1):
if jx:
terms.append(("XX", [i, i + 1], jx))
if jy:
terms.append(("YY", [i, i + 1], jy))
if jz:
terms.append(("ZZ", [i, i + 1], jz))
return SparsePauliOp.from_sparse_list(terms, num_qubits=length)
def state_prep_circuit(num_qubits: int, layers: int = 1) -> QuantumCircuit:
qubits = QuantumRegister(num_qubits, name="q")
circuit = QuantumCircuit(qubits)
circuit.h(qubits)
for _ in range(layers):
for i in range(0, num_qubits - 1, 2):
circuit.cx(qubits[i], qubits[i + 1])
circuit.ry(0.1, qubits)
for i in range(1, num_qubits - 1, 2):
circuit.cx(qubits[i], qubits[i + 1])
circuit.ry(0.1, qubits)
return circuit
length = 5
hamiltonian = heisenberg_hamiltonian(length, 1.0, 1.0)
circuit = state_prep_circuit(length, layers=2)
print(hamiltonian)
circuit.draw("mpl")
from qiskit_aer.primitives import Estimator
estimator = Estimator(approximation=True)
job = estimator.run(circuit, hamiltonian, shots=None)
result = job.result()
exact_value = result.values[0]
print(f"Exact energy: {exact_value}")
from qiskit_ibm_runtime import QiskitRuntimeService
hub = "ibm-q-internal"
group = "deployed"
project = "default"
service = QiskitRuntimeService(instance=f"{hub}/{group}/{project}")
from qiskit_ibm_runtime import Estimator, Options, Session
from qiskit.transpiler import CouplingMap
backend = service.get_backend("simulator_statevector")
# set simulation options
simulator = {
"basis_gates": ["id", "rz", "sx", "cx", "reset"],
"coupling_map": list(CouplingMap.from_line(length + 1)),
}
shots = 10000
import math
options = Options(
simulator=simulator,
resilience_level=0,
)
with Session(service=service, backend=backend):
estimator = Estimator(options=options)
job = estimator.run(circuit, hamiltonian, shots=shots)
result = job.result()
experiment_value = result.values[0]
error = abs(experiment_value - exact_value)
variance = result.metadata[0]["variance"]
std = math.sqrt(variance / shots)
print(f"Estimated energy: {experiment_value}")
print(f"Energy error: {error}")
print(f"Variance: {variance}")
print(f"Standard error: {std}")
from qiskit_aer.noise import NoiseModel, ReadoutError
noise_model = NoiseModel()
##### your code here #####
# add modest readout error on all qubits
p0given1 = 0.05
p1given0 = 0.02
readout_error = ReadoutError(
[
[1 - p1given0, p1given0],
[p0given1, 1 - p0given1],
]
)
noise_model.add_all_qubit_readout_error(readout_error)
# add really bad readout error on qubit 0
p0given1 = 0.5
p1given0 = 0.2
readout_error = ReadoutError(
[
[1 - p1given0, p1given0],
[p0given1, 1 - p0given1],
]
)
noise_model.add_readout_error(readout_error, [0])
print(noise_model)
# Submit your answer
from qc_grader.challenges.qgss_2023 import grade_lab5_ex1
grade_lab5_ex1(noise_model)
options = Options(
simulator=dict(noise_model=noise_model, **simulator),
resilience_level=0,
transpilation=dict(initial_layout=list(range(length))),
)
with Session(service=service, backend=backend):
estimator = Estimator(options=options)
job = estimator.run(circuit, hamiltonian, shots=shots)
result = job.result()
experiment_value = result.values[0]
error = abs(experiment_value - exact_value)
variance = result.metadata[0]["variance"]
std = math.sqrt(variance / shots)
print(f"Estimated energy: {experiment_value}")
print(f"Energy error: {error}")
print(f"Variance: {variance}")
print(f"Standard error: {std}")
options = Options(
simulator=dict(noise_model=noise_model, **simulator),
resilience_level=0,
transpilation=dict(initial_layout=list(range(1, length + 1))),
)
with Session(service=service, backend=backend):
estimator = Estimator(options=options)
job = estimator.run(circuit, hamiltonian, shots=shots)
result = job.result()
experiment_value = result.values[0]
error = abs(experiment_value - exact_value)
variance = result.metadata[0]["variance"]
std = math.sqrt(variance / shots)
print(f"Estimated energy: {experiment_value}")
print(f"Energy error: {error}")
print(f"Variance: {variance}")
print(f"Standard error: {std}")
options = Options(
simulator=dict(noise_model=noise_model, **simulator),
resilience_level=1,
transpilation=dict(initial_layout=list(range(1, length + 1))),
)
with Session(service=service, backend=backend):
estimator = Estimator(options=options)
job = estimator.run(circuit, hamiltonian, shots=shots)
result = job.result()
experiment_value = result.values[0]
error = abs(experiment_value - exact_value)
variance = result.metadata[0]["variance"]
std = math.sqrt(variance / shots)
print(f"Estimated energy: {experiment_value}")
print(f"Energy error: {error}")
print(f"Variance: {variance}")
print(f"Standard error: {std}")
new_shots: int
##### your code here #####
new_shots = 20000
# Submit your answer
from qc_grader.challenges.qgss_2023 import grade_lab5_ex2
grade_lab5_ex2(new_shots)
from qiskit_aer.noise import depolarizing_error
noise_model = NoiseModel()
##### your code here #####
noise_model.add_all_qubit_quantum_error(depolarizing_error(0.01, 2), ["cx"])
print(noise_model)
# Submit your answer
from qc_grader.challenges.qgss_2023 import grade_lab5_ex3
grade_lab5_ex3(noise_model)
options = Options(
simulator=dict(noise_model=noise_model, **simulator),
resilience_level=1,
)
with Session(service=service, backend=backend):
estimator = Estimator(options=options)
job = estimator.run(circuit, hamiltonian, shots=shots)
result = job.result()
experiment_value = result.values[0]
error = abs(experiment_value - exact_value)
variance = result.metadata[0]["variance"]
std = math.sqrt(variance / shots)
print(f"Estimated energy: {experiment_value}")
print(f"Energy error: {error}")
print(f"Variance: {variance}")
print(f"Standard error: {std}")
options = Options(
simulator=dict(noise_model=noise_model, **simulator),
resilience_level=2,
)
with Session(service=service, backend=backend):
estimator = Estimator(options=options)
job = estimator.run(circuit, hamiltonian, shots=shots)
result = job.result()
experiment_value = result.values[0]
error = abs(experiment_value - exact_value)
variances = result.metadata[0]["zne"]["noise_amplification"]["variance"]
print(f"Estimated energy: {experiment_value}")
print(f"Energy error: {error}")
print(f"Variances: {variances}")
from qiskit_aer.noise import depolarizing_error, amplitude_damping_error
noise_model = NoiseModel()
##### your code here #####
noise_model.add_all_qubit_quantum_error(amplitude_damping_error(0.01).tensor(amplitude_damping_error(0.05)), ["cx"])
print(noise_model)
options = Options(
simulator=dict(noise_model=noise_model, **simulator),
resilience_level=1,
)
with Session(service=service, backend=backend):
estimator = Estimator(options=options)
job = estimator.run(circuit, hamiltonian, shots=shots)
result = job.result()
experiment_value = result.values[0]
error = abs(experiment_value - exact_value)
variance = result.metadata[0]["variance"]
std = math.sqrt(variance / shots)
print(f"Estimated energy: {experiment_value}")
print(f"Energy error: {error}")
print(f"Variance: {variance}")
print(f"Standard error: {std}")
options = Options(
simulator=dict(noise_model=noise_model, **simulator),
resilience_level=2,
)
with Session(service=service, backend=backend):
estimator = Estimator(options=options)
job = estimator.run(circuit, hamiltonian, shots=shots)
result = job.result()
experiment_value = result.values[0]
error = abs(experiment_value - exact_value)
variances = result.metadata[0]["zne"]["noise_amplification"]["variance"]
print(f"Estimated energy: {experiment_value}")
print(f"Energy error: {error}")
print(f"Variances: {variances}")
|
https://github.com/MonitSharma/Learn-Quantum-Machine-Learning
|
MonitSharma
|
import pennylane as qml
import jax
from jax import numpy as np
jax.config.update("jax_platform_name", "cpu")
dev = qml.device('default.qubit', wires=2)
x = np.array([0.1, 0.2, 0.3])
@qml.qnode(dev, diff_method="adjoint")
def circuit(a):
qml.RX(a[0], wires=0)
qml.CNOT(wires=(0,1))
qml.RY(a[1], wires=1)
qml.RZ(a[2], wires=1)
return qml.expval(qml.PauliX(wires=1))
n_gates = 4
n_params = 3
ops = [
qml.RX(x[0], wires=0),
qml.CNOT(wires=(0,1)),
qml.RY(x[1], wires=1),
qml.RZ(x[2], wires=1)
]
M = qml.PauliX(wires=1)
from pennylane.devices.qubit import create_initial_state, apply_operation
state = create_initial_state((0, 1))
for op in ops:
state = apply_operation(op, state)
print(state)
bra = apply_operation(M, state)
ket = state
M_expval = np.vdot(bra, ket)
print("vdot : ", M_expval)
print("QNode : ", circuit(x))
bra_n = create_initial_state((0, 1))
for op in ops:
bra_n = apply_operation(op, bra_n)
bra_n = apply_operation(M, bra_n)
bra_n = apply_operation(qml.adjoint(ops[-1]), bra_n)
ket_n = create_initial_state((0, 1))
for op in ops[:-1]: # don't apply last operation
ket_n = apply_operation(op, ket_n)
M_expval_n = np.vdot(bra_n, ket_n)
print(M_expval_n)
bra_n_v2 = apply_operation(M, state)
ket_n_v2 = state
adj_op = qml.adjoint(ops[-1])
bra_n_v2 = apply_operation(adj_op, bra_n_v2)
ket_n_v2 = apply_operation(adj_op, ket_n_v2)
M_expval_n_v2 = np.vdot(bra_n_v2, ket_n_v2)
print(M_expval_n_v2)
bra_loop = apply_operation(M, state)
ket_loop = state
for op in reversed(ops):
adj_op = qml.adjoint(op)
bra_loop = apply_operation(adj_op, bra_loop)
ket_loop = apply_operation(adj_op, ket_loop)
print(np.vdot(bra_loop, ket_loop))
grad_op0 = qml.operation.operation_derivative(ops[0])
print(grad_op0)
bra = apply_operation(M, state)
ket = state
grads = []
for op in reversed(ops):
adj_op = qml.adjoint(op)
ket = apply_operation(adj_op, ket)
# Calculating the derivative
if op.num_params != 0:
dU = qml.operation.operation_derivative(op)
ket_temp = apply_operation(qml.QubitUnitary(dU, op.wires), ket)
dM = 2 * np.real(np.vdot(bra, ket_temp))
grads.append(dM)
bra = apply_operation(adj_op, bra)
# Finally reverse the order of the gradients
# since we calculated them in reverse
grads = grads[::-1]
print("our calculation: ", [float(grad) for grad in grads])
grad_compare = jax.grad(circuit)(x)
print("comparison: ", grad_compare)
dev_lightning = qml.device('lightning.qubit', wires=2)
@qml.qnode(dev_lightning, diff_method="adjoint")
def circuit_adjoint(a):
qml.RX(a[0], wires=0)
qml.CNOT(wires=(0,1))
qml.RY(a[1], wires=1)
qml.RZ(a[2], wires=1)
return qml.expval(M)
print(jax.grad(circuit_adjoint)(x))
|
https://github.com/MonitSharma/Learn-Quantum-Machine-Learning
|
MonitSharma
|
import numpy as np
n_samples = 100
p_1 = 0.2
x_data = np.random.binomial(1, p_1, (n_samples,))
print(x_data)
frequency_of_zeros, frequency_of_ones = 0, 0
for x in x_data:
if x:
frequency_of_ones += 1/n_samples
else:
frequency_of_zeros += 1/n_samples
print(frequency_of_ones+frequency_of_zeros)
import matplotlib.pyplot as plt
%matplotlib inline
p_0 = np.linspace(0, 1, 100)
p_1 = 1-p_0
fig, ax = plt.subplots()
ax.set_xlim(-1.2, 1.2)
ax.set_ylim(-1.2, 1.2)
ax.spines['left'].set_position('center')
ax.spines['bottom'].set_position('center')
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.set_xlabel("$p_0$")
ax.xaxis.set_label_coords(1.0, 0.5)
ax.set_ylabel("$p_1$")
ax.yaxis.set_label_coords(0.5, 1.0)
plt.plot(p_0, p_1)
p = np.array([[0.8], [0.2]])
np.linalg.norm(p, ord=1)
Π_0 = np.array([[1, 0], [0, 0]])
np.linalg.norm(Π_0 @ p, ord=1)
Π_1 = np.array([[0, 0], [0, 1]])
np.linalg.norm(Π_1 @ p, ord=1)
p = np.array([[.5], [.5]])
M = np.array([[0.7, 0.6], [0.3, 0.4]])
np.linalg.norm(M @ p, ord=1)
ϵ = 10e-10
p_0 = np.linspace(ϵ, 1-ϵ, 100)
p_1 = 1-p_0
H = -(p_0*np.log2(p_0) + p_1*np.log2(p_1))
fig, ax = plt.subplots()
ax.set_xlim(0, 1)
ax.set_ylim(0, -np.log2(0.5))
ax.set_xlabel("$p_0$")
ax.set_ylabel("$H$")
plt.plot(p_0, H)
plt.axvline(x=0.5, color='k', linestyle='--')
# %pip install qiskit
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit_aer import AerSimulator
from qiskit.visualization import plot_histogram, plot_bloch_multivector
from qiskit.primitives import BackendEstimator, BackendSampler
import numpy as np
π = np.pi
backend = AerSimulator(method='statevector')
q = QuantumRegister(1)
c = ClassicalRegister(1)
circuit = QuantumCircuit(q, c)
circuit.measure(q, c)
circuit.draw(output='mpl')
sampler = BackendSampler(backend=backend)
result = sampler.run(circuit).result()
print(result.quasi_dists[0])
# get the statevcector
from qiskit.quantum_info import Statevector
q = QuantumRegister(1)
c = ClassicalRegister(1)
circuit = QuantumCircuit(q, c)
state = Statevector.from_instruction(circuit)
print(state)
plot_bloch_multivector(state)
circuit = QuantumCircuit(q, c)
circuit.ry(π/2, q[0])
circuit.measure(q, c)
circuit.draw(output='mpl')
job = sampler.run(circuit)
result = job.result()
print(result.quasi_dists[0])
plot_histogram(result.quasi_dists[0])
circuit = QuantumCircuit(q, c)
circuit.ry(π/2, q[0])
# get statevector
state = Statevector.from_instruction(circuit)
print(state)
plot_bloch_multivector(state)
circuit = QuantumCircuit(q, c)
circuit.x(q[0])
circuit.ry(π/2, q[0])
# get statevector
state = Statevector.from_instruction(circuit)
print(state)
plot_bloch_multivector(state)
circuit.measure(q, c)
job = sampler.run(circuit)
result = job.result()
print(result.quasi_dists[0])
plot_histogram(result.quasi_dists[0])
circuit = QuantumCircuit(q, c)
circuit.ry(π/2, q[0])
circuit.ry(π/2, q[0])
circuit.measure(q, c)
job = sampler.run(circuit)
result = job.result()
print(result.quasi_dists[0])
plot_histogram(result.quasi_dists[0])
q0 = np.array([[1], [0]])
q1 = np.array([[1], [0]])
np.kron(q0, q1)
q = QuantumRegister(2)
c = ClassicalRegister(2)
circuit = QuantumCircuit(q, c)
circuit.h(q[0])
circuit.cx(q[0], q[1])
circuit.measure(q, c)
job = sampler.run(circuit)
result = job.result()
print(result.quasi_dists[0])
plot_histogram(result.quasi_dists[0])
|
https://github.com/MonitSharma/Learn-Quantum-Machine-Learning
|
MonitSharma
|
import pennylane as qml
from pennylane import numpy as np
from pennylane.optimize import AdamOptimizer, GradientDescentOptimizer
import matplotlib.pyplot as plt
# Set a random seed
np.random.seed(42)
# Make a dataset of points inside and outside of a circle
def circle(samples, center=[0.0, 0.0], radius=np.sqrt(2 / np.pi)):
"""
Generates a dataset of points with 1/0 labels inside a given radius.
Args:
samples (int): number of samples to generate
center (tuple): center of the circle
radius (float: radius of the circle
Returns:
Xvals (array[tuple]): coordinates of points
yvals (array[int]): classification labels
"""
Xvals, yvals = [], []
for i in range(samples):
x = 2 * (np.random.rand(2)) - 1
y = 0
if np.linalg.norm(x - center) < radius:
y = 1
Xvals.append(x)
yvals.append(y)
return np.array(Xvals, requires_grad=False), np.array(yvals, requires_grad=False)
def plot_data(x, y, fig=None, ax=None):
"""
Plot data with red/blue values for a binary classification.
Args:
x (array[tuple]): array of data points as tuples
y (array[int]): array of data points as tuples
"""
if fig == None:
fig, ax = plt.subplots(1, 1, figsize=(5, 5))
reds = y == 0
blues = y == 1
ax.scatter(x[reds, 0], x[reds, 1], c="red", s=20, edgecolor="k")
ax.scatter(x[blues, 0], x[blues, 1], c="blue", s=20, edgecolor="k")
ax.set_xlabel("$x_1$")
ax.set_ylabel("$x_2$")
Xdata, ydata = circle(500)
fig, ax = plt.subplots(1, 1, figsize=(4, 4))
plot_data(Xdata, ydata, fig=fig, ax=ax)
plt.show()
# Define output labels as quantum state vectors
def density_matrix(state):
"""Calculates the density matrix representation of a state.
Args:
state (array[complex]): array representing a quantum state vector
Returns:
dm: (array[complex]): array representing the density matrix
"""
return state * np.conj(state).T
label_0 = [[1], [0]]
label_1 = [[0], [1]]
state_labels = np.array([label_0, label_1], requires_grad=False)
dev = qml.device("default.qubit", wires=1)
# Install any pennylane-plugin to run on some particular backend
@qml.qnode(dev)
def qcircuit(params, x, y):
"""A variational quantum circuit representing the Universal classifier.
Args:
params (array[float]): array of parameters
x (array[float]): single input vector
y (array[float]): single output state density matrix
Returns:
float: fidelity between output state and input
"""
for p in params:
qml.Rot(*x, wires=0)
qml.Rot(*p, wires=0)
return qml.expval(qml.Hermitian(y, wires=[0]))
def cost(params, x, y, state_labels=None):
"""Cost function to be minimized.
Args:
params (array[float]): array of parameters
x (array[float]): 2-d array of input vectors
y (array[float]): 1-d array of targets
state_labels (array[float]): array of state representations for labels
Returns:
float: loss value to be minimized
"""
# Compute prediction for each input in data batch
loss = 0.0
dm_labels = [density_matrix(s) for s in state_labels]
for i in range(len(x)):
f = qcircuit(params, x[i], dm_labels[y[i]])
loss = loss + (1 - f) ** 2
return loss / len(x)
def test(params, x, y, state_labels=None):
"""
Tests on a given set of data.
Args:
params (array[float]): array of parameters
x (array[float]): 2-d array of input vectors
y (array[float]): 1-d array of targets
state_labels (array[float]): 1-d array of state representations for labels
Returns:
predicted (array([int]): predicted labels for test data
output_states (array[float]): output quantum states from the circuit
"""
fidelity_values = []
dm_labels = [density_matrix(s) for s in state_labels]
predicted = []
for i in range(len(x)):
fidel_function = lambda y: qcircuit(params, x[i], y)
fidelities = [fidel_function(dm) for dm in dm_labels]
best_fidel = np.argmax(fidelities)
predicted.append(best_fidel)
fidelity_values.append(fidelities)
return np.array(predicted), np.array(fidelity_values)
def accuracy_score(y_true, y_pred):
"""Accuracy score.
Args:
y_true (array[float]): 1-d array of targets
y_predicted (array[float]): 1-d array of predictions
state_labels (array[float]): 1-d array of state representations for labels
Returns:
score (float): the fraction of correctly classified samples
"""
score = y_true == y_pred
return score.sum() / len(y_true)
def iterate_minibatches(inputs, targets, batch_size):
"""
A generator for batches of the input data
Args:
inputs (array[float]): input data
targets (array[float]): targets
Returns:
inputs (array[float]): one batch of input data of length `batch_size`
targets (array[float]): one batch of targets of length `batch_size`
"""
for start_idx in range(0, inputs.shape[0] - batch_size + 1, batch_size):
idxs = slice(start_idx, start_idx + batch_size)
yield inputs[idxs], targets[idxs]
# Generate training and test data
num_training = 200
num_test = 2000
Xdata, y_train = circle(num_training)
X_train = np.hstack((Xdata, np.zeros((Xdata.shape[0], 1), requires_grad=False)))
Xtest, y_test = circle(num_test)
X_test = np.hstack((Xtest, np.zeros((Xtest.shape[0], 1), requires_grad=False)))
# Train using Adam optimizer and evaluate the classifier
num_layers = 3
learning_rate = 0.6
epochs = 10
batch_size = 32
opt = AdamOptimizer(learning_rate, beta1=0.9, beta2=0.999)
# initialize random weights
params = np.random.uniform(size=(num_layers, 3), requires_grad=True)
predicted_train, fidel_train = test(params, X_train, y_train, state_labels)
accuracy_train = accuracy_score(y_train, predicted_train)
predicted_test, fidel_test = test(params, X_test, y_test, state_labels)
accuracy_test = accuracy_score(y_test, predicted_test)
# save predictions with random weights for comparison
initial_predictions = predicted_test
loss = cost(params, X_test, y_test, state_labels)
print(
"Epoch: {:2d} | Cost: {:3f} | Train accuracy: {:3f} | Test Accuracy: {:3f}".format(
0, loss, accuracy_train, accuracy_test
)
)
for it in range(epochs):
for Xbatch, ybatch in iterate_minibatches(X_train, y_train, batch_size=batch_size):
params, _, _, _ = opt.step(cost, params, Xbatch, ybatch, state_labels)
predicted_train, fidel_train = test(params, X_train, y_train, state_labels)
accuracy_train = accuracy_score(y_train, predicted_train)
loss = cost(params, X_train, y_train, state_labels)
predicted_test, fidel_test = test(params, X_test, y_test, state_labels)
accuracy_test = accuracy_score(y_test, predicted_test)
res = [it + 1, loss, accuracy_train, accuracy_test]
print(
"Epoch: {:2d} | Loss: {:3f} | Train accuracy: {:3f} | Test accuracy: {:3f}".format(
*res
)
)
print(
"Cost: {:3f} | Train accuracy {:3f} | Test Accuracy : {:3f}".format(
loss, accuracy_train, accuracy_test
)
)
print("Learned weights")
for i in range(num_layers):
print("Layer {}: {}".format(i, params[i]))
fig, axes = plt.subplots(1, 3, figsize=(10, 3))
plot_data(X_test, initial_predictions, fig, axes[0])
plot_data(X_test, predicted_test, fig, axes[1])
plot_data(X_test, y_test, fig, axes[2])
axes[0].set_title("Predictions with random weights")
axes[1].set_title("Predictions after training")
axes[2].set_title("True test data")
plt.tight_layout()
plt.show()
|
https://github.com/MonitSharma/Learn-Quantum-Machine-Learning
|
MonitSharma
|
import numpy as np
X = np.array([[0, 1], [1, 0]])
print("XX^dagger")
print(X @ X.T.conj())
print("X^daggerX")
print(X.T.conj() @ X)
print("The norm of the state |0> before applying X")
zero_ket = np.array([[1], [0]])
print(np.linalg.norm(zero_ket))
print("The norm of the state after applying X")
print(np.linalg.norm(X @ zero_ket))
import numpy as np
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit_aer import AerSimulator
from qiskit.quantum_info import Statevector
np.set_printoptions(precision=3, suppress=True)
backend_statevector = AerSimulator(method='statevector')
q = QuantumRegister(1)
c = ClassicalRegister(1)
circuit = QuantumCircuit(q, c)
circuit.x(q[0])
circuit.x(q[0])
# get the statevector
state = Statevector.from_instruction(circuit)
print(state.data)
def mixed_state(pure_state, visibility):
density_matrix = pure_state @ pure_state.T.conj()
maximally_mixed_state = np.eye(4)/2**2
return visibility*density_matrix + (1-visibility)*maximally_mixed_state
ϕ = np.array([[1],[0],[0],[1]])/np.sqrt(2)
print("Maximum visibility is a pure state:")
print(mixed_state(ϕ, 1.0))
print("The state is still entangled with visibility 0.8:")
print(mixed_state(ϕ, 0.8))
print("Entanglement is lost by 0.6:")
print(mixed_state(ϕ, 0.6))
print("Barely any coherence remains by 0.2:")
print(mixed_state(ϕ, 0.2))
import matplotlib.pyplot as plt
temperatures = [.5, 5, 2000]
energies = np.linspace(0, 20, 100)
fig, ax = plt.subplots()
for i, T in enumerate(temperatures):
probabilities = np.exp(-energies/T)
Z = probabilities.sum()
probabilities /= Z
ax.plot(energies, probabilities, linewidth=3, label = "$T_" + str(i+1)+"$")
ax.set_xlim(0, 20)
ax.set_ylim(0, 1.2*probabilities.max())
ax.set_xticks([])
ax.set_yticks([])
ax.set_xlabel('Energy')
ax.set_ylabel('Probability')
ax.legend()
|
https://github.com/MonitSharma/Learn-Quantum-Machine-Learning
|
MonitSharma
|
from PIL import Image
import numpy as np
import matplotlib.pyplot as plt
cut=128
img = Image.open('nasa_image.jpg').convert('L')
plt.imshow(img)
img = np.asarray(img.getdata()).reshape((2463,2895))
for i in range(2463//cut):
for j in range(2895//cut):
cutimg = img[i*cut:(i+1)*cut]
cutimg = cutimg[:,list(range(j*cut,(j+1)*cut))]
plt.imsave('result/{} {}.jpg'.format(i,j), cutimg ,cmap='gray')
for i in range(2463//cut):
for j in range(2895//cut):
img16 = Image.open('result/{} {}.jpg'.format(i,j)).resize((16,16)).convert('L')
img16 = np.asarray(img16.getdata()).reshape((16,16))
img16 = Image.open('result/{} {}.jpg'.format(5,1)).resize((16,16)).convert('L')
plt.imshow(img16, cmap='gray')
img16 = np.asarray(img16.getdata(), dtype=np.float64).reshape((16,16))
import random
import numpy as np
import matplotlib.pyplot as plt
import sys
sys.path.append('../PyFiles') # where the Helper files are saved
# Pull in the helper files.
from ImageRead import * # the helper files we created to read Images
from QNN import * # the helper file that creates the QNN
target_o = [1 for i in range(25)]+[0 for i in range(25)]
pathY=r'../dataset/Original/galaxy/'
pathN=r'../dataset/Original/No-galaxy/'
nameN=''
nameY=''
inputY=[imageResize(callImage(i+1,pathY,nameY),16) for i in range(25)]
inputN=[imageResize(callImage(i+1,pathN,nameN),16) for i in range(25)]
input_combine = inputY+inputN
np.random.seed(0)
idx=np.array([int(i) for i in range(50)]).flatten()
np.random.shuffle(idx)
dataInput = list(input_combine[i] for i in idx )
dataTarget = list( imageBinarize(input_combine[i]) for i in idx )
data_target_o=list( target_o[i] for i in idx )
n_samples_show = 10
fig, axes = plt.subplots(nrows=2, ncols=n_samples_show, figsize=(20, 6))
for i in range(n_samples_show):
axes[0,i].imshow(dataInput[i], cmap='gray')
axes[0,i].set_xticks([])
axes[0,i].set_yticks([])
axes[1,i].imshow(dataInput[i+5], cmap='gray')
axes[1,i].set_xticks([])
axes[1,i].set_yticks([])
from qiskit.circuit.parameter import Parameter
from qiskit_machine_learning.neural_networks import CircuitQNN
from qiskit_machine_learning.connectors import TorchConnector
from qiskit.utils import QuantumInstance
from torch.nn import Linear, CrossEntropyLoss, MSELoss
from torch.optim import LBFGS, SGD,Adam
qi = QuantumInstance(Aer.get_backend('statevector_simulator'))
from qiskit.circuit.library import RealAmplitudes, ZZFeatureMap
from qiskit_machine_learning.algorithms.classifiers import NeuralNetworkClassifier, VQC
from qiskit.algorithms.optimizers import COBYLA, L_BFGS_B
# Model for LBFGS
# Combining the circuit together with CircuitQNN
np.random.seed(3)
nqubits=6
num_inputs=256
qc = QuantumCircuit(nqubits)
# Encoding
param_x=[];
for i in range(num_inputs):
param_x.append(Parameter('x'+str(i)))
for i in range(8):
param_x.append(np.pi/2)
feature_map = encoding(qc,param_x,22)
# Optimzing circuit PQC
param_y=[];
for i in range(nqubits*2):
param_y.append(Parameter('θ'+str(i)))
ansatz=circuit15(qc,param_y)
qc.append(feature_map, range(nqubits))
qc.append(ansatz, range(nqubits))
qnn2 = CircuitQNN(qc, input_params=feature_map.parameters, weight_params=ansatz.parameters,
interpret=parity, output_shape=2, quantum_instance=qi)
initial_weights = 0.1*(2*np.random.rand(qnn2.num_weights) - 1)
# define optimizer and loss function
model2 = TorchConnector(qnn2, initial_weights)
optimizer = LBFGS(model2.parameters(),lr=0.05)
f_loss = CrossEntropyLoss()
X= [normlaizeData(dataInput[i].flatten()) for i in range(50)]
y01= [data_target_o[i] for i in range(50)]
from torch import Tensor
# traning model accuracy
y_predict = []
for x in X:
output = model2(Tensor(x))
y_predict += [np.argmax(output.detach().numpy())]
print('Accuracy:', sum(y_predict == np.array(y01))/len(np.array(y01)))
# define optimizer and loss function
model2 = TorchConnector(qnn2, initial_weights)
optimizer = LBFGS(model2.parameters(),lr=0.05)
f_loss = CrossEntropyLoss()
X= [normlaizeData(dataInput[i].flatten()) for i in range(50)]
y01= [data_target_o[i] for i in range(50)]
from torch import Tensor
# start training
model2.train() # set model to training mode
# define objective function
def closure():
optimizer.zero_grad() # initialize gradient
loss = 0.0 # initialize loss
for x, y_target in zip(X, y01): # evaluate batch loss
output = model2(Tensor(x)).reshape(1, 2) # forward pass
loss += f_loss(output, Tensor([y_target]).long())
loss.backward() # backward pass
print(loss.item()) # print loss
return loss
# run optimizer
optimizer.step(closure)
optimizer.step(closure)
# traning model accuracy
y_predict = []
for x in X:
output = model2(Tensor(x))
y_predict += [np.argmax(output.detach().numpy())]
print('Accuracy:', sum(y_predict == np.array(y01))/len(np.array(y01)))
# define optimizer and loss function
from torch import Tensor
model2 = TorchConnector(qnn2, initial_weights)
optimizer = LBFGS(model2.parameters(),lr=0.06)
f_loss = CrossEntropyLoss()
X= [normlaizeData(dataInput[i].flatten()) for i in range(50)]
y01= [data_target_o[i] for i in range(50)]
y_predict = []
for x in X:
output = model2(Tensor(x))
y_predict += [np.argmax(output.detach().numpy())]
print('Accuracy:', sum(y_predict == np.array(y01))/len(np.array(y01)))
from torch import Tensor
# start training
model2.train() # set model to training mode
# define objective function
def closure():
optimizer.zero_grad() # initialize gradient
loss = 0.0 # initialize loss
for x, y_target in zip(X, y01): # evaluate batch loss
output = model2(Tensor(x)).reshape(1, 2) # forward pass
loss += f_loss(output, Tensor([y_target]).long())
loss.backward() # backward pass
print(loss.item()) # print loss
return loss
# run optimizer
optimizer.step(closure)
optimizer.step(closure)
# traning model accuracy
y_predict = []
for x in X:
output = model2(Tensor(x))
y_predict += [np.argmax(output.detach().numpy())]
print('Accuracy:', sum(y_predict == np.array(y01))/len(np.array(y01)))
# define optimizer and loss function
from torch import Tensor
model2 = TorchConnector(qnn2, initial_weights)
optimizer = LBFGS(model2.parameters(),lr=0.07)
f_loss = CrossEntropyLoss()
X= [normlaizeData(dataInput[i].flatten()) for i in range(50)]
y01= [data_target_o[i] for i in range(50)]
y_predict = []
for x in X:
output = model2(Tensor(x))
y_predict += [np.argmax(output.detach().numpy())]
print('Accuracy:', sum(y_predict == np.array(y01))/len(np.array(y01)))
from torch import Tensor
# start training
model2.train() # set model to training mode
# define objective function
def closure():
optimizer.zero_grad() # initialize gradient
loss = 0.0 # initialize loss
for x, y_target in zip(X, y01): # evaluate batch loss
output = model2(Tensor(x)).reshape(1, 2) # forward pass
loss += f_loss(output, Tensor([y_target]).long())
loss.backward() # backward pass
print(loss.item()) # print loss
return loss
# run optimizer
optimizer.step(closure)
optimizer.step(closure)
# traning model accuracy
y_predict = []
for x in X:
output = model2(Tensor(x))
y_predict += [np.argmax(output.detach().numpy())]
print('Accuracy:', sum(y_predict == np.array(y01))/len(np.array(y01)))
target_o = [1 for i in range(25)]+[0 for i in range(25)]
pathY=r'../dataset/Original/galaxy1/'
pathN=r'../dataset/Original/no-galaxy1/'
nameN=''
nameY=''
inputY=[imageResize(callImage(i+1,pathY,nameY),16) for i in range(25)]
inputN=[imageResize(callImage(i+1,pathN,nameN),16) for i in range(25)]
input_combine = inputY+inputN
np.random.seed(0)
idx=np.array([int(i) for i in range(50)]).flatten()
np.random.shuffle(idx)
dataInput = list(input_combine[i] for i in idx )
dataTarget = list( imageBinarize(input_combine[i]) for i in idx )
data_target_o=list( target_o[i] for i in idx )
Xtest= [normlaizeData(dataInput[i].flatten()) for i in range(25)]
y01test= [data_target_o[i] for i in range(25)]
Xtest1= [normlaizeData(dataInput[i].flatten()) for i in range(50)]
y01test1= [data_target_o[i] for i in range(50)]
y_predict = []
for x in Xtest:
output = model2(Tensor(x))
y_predict += [np.argmax(output.detach().numpy())]
print('Accuracy25data:', sum(y_predict == np.array(y01test))/len(np.array(y01test)))
y_predict1 = []
for x in Xtest1:
output = model2(Tensor(x))
y_predict1 += [np.argmax(output.detach().numpy())]
print('Accuracy50data:', sum(y_predict1 == np.array(y01test1))/len(np.array(y01test1)))
|
https://github.com/MonitSharma/Learn-Quantum-Machine-Learning
|
MonitSharma
|
import pennylane as qml
from pennylane import numpy as np
dev_gaussian = qml.device("default.gaussian", wires=1)
@qml.qnode(dev_gaussian)
def mean_photon_gaussian(mag_alpha, phase_alpha, phi):
qml.Displacement(mag_alpha, phase_alpha, wires=0)
qml.Rotation(phi, wires=0)
return qml.expval(qml.NumberOperator(0))
def cost(params):
return (mean_photon_gaussian(params[0], params[1], params[2]) - 1.0) ** 2
init_params = np.array([0.015, 0.02, 0.005], requires_grad=True)
print(cost(init_params))
# initialise the optimizer
opt = qml.GradientDescentOptimizer(stepsize=0.1)
# set the number of steps
steps = 20
# set the initial parameter values
params = init_params
for i in range(steps):
# update the circuit parameters
params = opt.step(cost, params)
print("Cost after step {:5d}: {:8f}".format(i + 1, cost(params)))
print("Optimized mag_alpha:{:8f}".format(params[0]))
print("Optimized phase_alpha:{:8f}".format(params[1]))
print("Optimized phi:{:8f}".format(params[2]))
|
https://github.com/MonitSharma/Learn-Quantum-Machine-Learning
|
MonitSharma
|
import pennylane as qml
from pennylane import numpy as np
dev_fock = qml.device("strawberryfields.fock", wires=2, cutoff_dim=2)
@qml.qnode(dev_fock, diff_method="parameter-shift")
def photon_redirection(params):
qml.FockState(1, wires=0)
qml.Beamsplitter(params[0], params[1], wires=[0, 1])
return qml.expval(qml.NumberOperator(1))
def cost(params):
return -photon_redirection(params)
init_params = np.array([0.01, 0.01], requires_grad=True)
print(cost(init_params))
dphoton_redirection = qml.grad(photon_redirection, argnum=0)
print(dphoton_redirection([0.0, 0.0]))
# initialise the optimizer
opt = qml.GradientDescentOptimizer(stepsize=0.4)
# set the number of steps
steps = 100
# set the initial parameter values
params = init_params
for i in range(steps):
# update the circuit parameters
params = opt.step(cost, params)
if (i + 1) % 5 == 0:
print("Cost after step {:5d}: {: .7f}".format(i + 1, cost(params)))
print("Optimized rotation angles: {}".format(params))
# create the devices
dev_qubit = qml.device("default.qubit", wires=1)
dev_fock = qml.device("strawberryfields.fock", wires=2, cutoff_dim=10)
@qml.qnode(dev_qubit)
def qubit_rotation(phi1, phi2):
"""Qubit rotation QNode"""
qml.RX(phi1, wires=0)
qml.RY(phi2, wires=0)
return qml.expval(qml.PauliZ(0))
@qml.qnode(dev_fock, diff_method="parameter-shift")
def photon_redirection(params):
"""The photon redirection QNode"""
qml.FockState(1, wires=0)
qml.Beamsplitter(params[0], params[1], wires=[0, 1])
return qml.expval(qml.NumberOperator(1))
def squared_difference(x, y):
"""Classical node to compute the squared
difference between two inputs"""
return np.abs(x - y) ** 2
def cost(params, phi1=0.5, phi2=0.1):
"""Returns the squared difference between
the photon-redirection and qubit-rotation QNodes, for
fixed values of the qubit rotation angles phi1 and phi2"""
qubit_result = qubit_rotation(phi1, phi2)
photon_result = photon_redirection(params)
return squared_difference(qubit_result, photon_result)
# initialise the optimizer
opt = qml.GradientDescentOptimizer(stepsize=0.4)
# set the number of steps
steps = 100
# set the initial parameter values
params = np.array([0.01, 0.01], requires_grad=True)
for i in range(steps):
# update the circuit parameters
params = opt.step(cost, params)
if (i + 1) % 5 == 0:
print("Cost after step {:5d}: {: .7f}".format(i + 1, cost(params)))
print("Optimized rotation angles: {}".format(params))
result = [1.20671364, 0.01]
print(photon_redirection(result))
print(qubit_rotation(0.5, 0.1))
|
https://github.com/MonitSharma/Learn-Quantum-Machine-Learning
|
MonitSharma
|
%pip install qiskit
from qiskit import ClassicalRegister, QuantumRegister, QuantumCircuit
from qiskit_aer import AerSimulator
from qiskit.primitives import BackendEstimator, BackendSampler
import numpy as np
np.set_printoptions(precision=3, suppress=True)
backend = AerSimulator(method='automatic')
q = QuantumRegister(1)
c = ClassicalRegister(1)
circuit = QuantumCircuit(q, c)
circuit.measure(q[0], c[0])
circuit.draw(output='mpl')
sampler = BackendSampler(backend)
job = sampler.run(circuit, options={'shots': 1})
result = job.result()
print("Counts",result.quasi_dists[0])
backend = AerSimulator(method='statevector')
from qiskit.quantum_info import Statevector
circuit = QuantumCircuit(q, c)
circuit.id(q[0])
# get the statevcector
state = Statevector.from_instruction(circuit)
print(state)
circuit.draw(output='mpl')
from qiskit.visualization import plot_bloch_multivector
print("Initial state")
plot_bloch_multivector(state)
circuit.h(q[0])
circuit.draw(output='mpl')
state = Statevector.from_instruction(circuit)
print("After a Hadamard gate")
plot_bloch_multivector(state)
from qiskit.visualization import plot_histogram
circuit.measure(q[0], c[0])
job = sampler.run(circuit, options={'shots': 1024})
result = job.result()
print("Initial state statistics")
plot_histogram(result.quasi_dists[0])
|
https://github.com/MonitSharma/Learn-Quantum-Machine-Learning
|
MonitSharma
|
import pennylane as qml
H = qml.Hamiltonian(
[1, 1, 0.5],
[qml.PauliX(0), qml.PauliZ(1), qml.PauliX(0) @ qml.PauliX(1)]
)
print(H)
dev = qml.device('default.qubit', wires=2)
t = 1
n = 2
@qml.qnode(dev)
def circuit():
qml.ApproxTimeEvolution(H, t, n)
return [qml.expval(qml.PauliZ(i)) for i in range(2)]
print(qml.draw(circuit, expansion_strategy='device')())
def circ(theta):
qml.RX(theta, wires=0)
qml.Hadamard(wires=1)
qml.CNOT(wires=[0, 1])
@qml.qnode(dev)
def circuit(param):
circ(param)
return [qml.expval(qml.PauliZ(i)) for i in range(2)]
print(qml.draw(circuit)(0.5))
@qml.qnode(dev)
def circuit(params, **kwargs):
qml.layer(circ, 3, params)
return [qml.expval(qml.PauliZ(i)) for i in range(2)]
print(qml.draw(circuit)([0.3, 0.4, 0.5]))
from pennylane import qaoa
from pennylane import numpy as np
from matplotlib import pyplot as plt
import networkx as nx
edges = [(0, 1), (1, 2), (2, 0), (2, 3)]
graph = nx.Graph(edges)
nx.draw(graph, with_labels=True)
plt.show()
cost_h, mixer_h = qaoa.min_vertex_cover(graph, constrained=False)
print("Cost Hamiltonian", cost_h)
print("Mixer Hamiltonian", mixer_h)
def qaoa_layer(gamma, alpha):
qaoa.cost_layer(gamma, cost_h)
qaoa.mixer_layer(alpha, mixer_h)
wires = range(4)
depth = 2
def circuit(params, **kwargs):
for w in wires:
qml.Hadamard(wires=w)
qml.layer(qaoa_layer, depth, params[0], params[1])
!pip install pennylane-qulacs["cpu"]
dev = qml.device("qulacs.simulator", wires=wires)
@qml.qnode(dev)
def cost_function(params):
circuit(params)
return qml.expval(cost_h)
optimizer = qml.GradientDescentOptimizer()
steps = 70
params = np.array([[0.5, 0.5], [0.5, 0.5]], requires_grad=True)
for i in range(steps):
params = optimizer.step(cost_function, params)
print("Optimal Parameters")
print(params)
@qml.qnode(dev)
def probability_circuit(gamma, alpha):
circuit([gamma, alpha])
return qml.probs(wires=wires)
probs = probability_circuit(params[0], params[1])
plt.style.use("seaborn")
plt.bar(range(2 ** len(wires)), probs)
plt.show()
reward_h = qaoa.edge_driver(nx.Graph([(0, 2)]), ['11'])
new_cost_h = cost_h + 2 * reward_h
def qaoa_layer(gamma, alpha):
qaoa.cost_layer(gamma, new_cost_h)
qaoa.mixer_layer(alpha, mixer_h)
def circuit(params, **kwargs):
for w in wires:
qml.Hadamard(wires=w)
qml.layer(qaoa_layer, depth, params[0], params[1])
@qml.qnode(dev)
def cost_function(params):
circuit(params)
return qml.expval(new_cost_h)
params = np.array([[0.5, 0.5], [0.5, 0.5]], requires_grad=True)
for i in range(steps):
params = optimizer.step(cost_function, params)
print("Optimal Parameters")
print(params)
@qml.qnode(dev)
def probability_circuit(gamma, alpha):
circuit([gamma, alpha])
return qml.probs(wires=wires)
probs = probability_circuit(params[0], params[1])
plt.style.use("seaborn")
plt.bar(range(2 ** len(wires)), probs)
plt.show()
|
https://github.com/MonitSharma/Learn-Quantum-Machine-Learning
|
MonitSharma
|
import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline
np.set_printoptions(precision=3, suppress=True)
if(1j**2==-1):
print("Complex Number")
else:
print("Not a Complex Number")
x = 3.5 + 2.1j
print("Type of x:" , type(x))
print("Real part of x:", x.real)
print("Imaginary part of x:", x.imag)
def plot_complex(a):
for x in range(len(a)):
plt.plot([0,a[x].real], [0,a[x].imag], 'r-o')
plt.axhline(y=0, color='k')
plt.axvline(x=0, color='k')
plt.ylabel('Imaginary')
plt.xlabel('Real')
limit = np.max(np.ceil(np.absolute(a)))
plt.xlim((-limit,limit))
plt.ylim((-limit,limit))
plt.show()
plot_complex([x])
abs(x)
r = abs(x)
φ = np.arctan2(x.imag, x.real)
z = r*np.exp(1j*φ)
z == x
print(x.conjugate())
plot_complex([x.conjugate()])
a = np.array([[1+2j], [2+2j]])
a
a.T.conj()
b = np.array([[0.1], [2j]])
b.T.conj() @ a
c = np.array([[1], [0]])
d = np.array([[0], [1]])
c.T.conj() @ d
print("The square of the l2 norm of a:", np.linalg.norm(a)**2)
print("The same thing calculated as an inner product:", a.T.conj() @ a)
sum(a != 0), sum(c != 0)
np.linalg.norm(a, ord=1)
np.kron(c, d)
A = np.array([[1+2j, 2], [1j, 3+4j]])
A
A.T.conj()
A @ a
a @ a.T.conj()
λs, eigenvectors = np.linalg.eig(A)
np.all(A == A.T.conj())
B = a @ a.T.conj()
np.all(B == B.T.conj())
|
https://github.com/MonitSharma/Learn-Quantum-Machine-Learning
|
MonitSharma
|
import numpy as np
zero_ket = np.array([[1], [0]])
print("|0> ket:\n", zero_ket)
print("<0| bra:\n", zero_ket.T.conj())
zero_ket.T.conj() @ zero_ket
one_ket = np.array([[0], [1]])
zero_ket.T.conj() @ one_ket
zero_ket @ zero_ket.T.conj()
ψ = np.array([[1], [0]])/np.sqrt(2)
Π_0 = zero_ket @ zero_ket.T.conj()
ψ.T.conj() @ Π_0 @ ψ
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit_aer import AerSimulator
from qiskit.visualization import plot_histogram
from qiskit.primitives import BackendEstimator, BackendSampler
backend = AerSimulator()
sampler = BackendSampler(backend)
q = QuantumRegister(1)
c = ClassicalRegister(1)
circuit = QuantumCircuit(q, c)
circuit.h(q[0])
circuit.measure(q, c)
job = sampler.run(circuit, shots=100)
result = job.result()
counts = result.quasi_dists[0]
plot_histogram(counts)
ψ = np.array([[np.sqrt(2)/2], [np.sqrt(2)/2]])
Π_0 = zero_ket @ zero_ket.T.conj()
probability_0 = ψ.T.conj() @ Π_0 @ ψ
Π_0 @ ψ/np.sqrt(probability_0)
c = ClassicalRegister(2)
circuit = QuantumCircuit(q, c)
circuit.h(q[0])
circuit.measure(q[0], c[0])
circuit.measure(q[0], c[1])
job = sampler.run(circuit, shots=100)
result = job.result()
counts = result.quasi_dists[0]
plot_histogram(counts)
q = QuantumRegister(2)
c = ClassicalRegister(2)
circuit = QuantumCircuit(q, c)
circuit.h(q[0])
circuit.measure(q, c)
job = sampler.run(circuit, shots=100)
result = job.result()
counts = result.quasi_dists[0]
plot_histogram(counts)
q = QuantumRegister(2)
c = ClassicalRegister(2)
circuit = QuantumCircuit(q, c)
circuit.h(q[0])
circuit.cx(q[0], q[1])
circuit.measure(q, c)
job = sampler.run(circuit, shots=100)
result = job.result()
counts = result.quasi_dists[0]
plot_histogram(counts)
ψ = np.array([[1], [1]])/np.sqrt(2)
ρ = ψ @ ψ.T.conj()
Π_0 = zero_ket @ zero_ket.T.conj()
np.trace(Π_0 @ ρ)
probability_0 = np.trace(Π_0 @ ρ)
Π_0 @ ρ @ Π_0/probability_0
zero_ket = np.array([[1], [0]])
one_ket = np.array([[0], [1]])
ψ = (zero_ket + one_ket)/np.sqrt(2)
print("Density matrix of the equal superposition")
print(ψ @ ψ.T.conj())
print("Density matrix of the equally mixed state of |0><0| and |1><1|")
print((zero_ket @ zero_ket.T.conj()+one_ket @ one_ket.T.conj())/2)
|
https://github.com/MonitSharma/Learn-Quantum-Machine-Learning
|
MonitSharma
|
import pennylane as qml
from pennylane import numpy as np
dev = qml.device('default.mixed', wires = 2)
@qml.qnode(dev)
def circuit():
qml.Hadamard(wires = 0)
qml.CNOT(wires = [0,1])
return qml.expval(qml.PauliZ(0) @ qml.PauliZ(1))
print(f"QNode output = {circuit() :.4f}")
print(f"Output state is = \n{np.real(dev.state)}")
@qml.qnode(dev)
def bitflip_circuit(p):
qml.Hadamard(wires=0)
qml.CNOT(wires=[0, 1])
qml.BitFlip(p, wires=0)
qml.BitFlip(p, wires=1)
return qml.expval(qml.PauliZ(0) @ qml.PauliZ(1))
ps = [0.001, 0.01, 0.1, 0.2]
for p in ps:
print(f"QNode output for bit flip probability {p} is {bitflip_circuit(p):.4f}")
print(f"Output state for bit flip probability {p} is \n{np.real(dev.state)}")
@qml.qnode(dev)
def depolarizing_circuit(p):
qml.Hadamard(wires=0)
qml.CNOT(wires=[0, 1])
qml.DepolarizingChannel(p, wires=0)
qml.DepolarizingChannel(p, wires=1)
return qml.expval(qml.PauliZ(0) @ qml.PauliZ(1))
ps = [0.001, 0.01, 0.1, 0.2]
for p in ps:
print(f"QNode output for depolarizing probability {p} is {depolarizing_circuit(p):.4f}")
ev = np.tensor(0.7781, requires_grad=False) # observed expectation value
def sigmoid(x):
return 1/(1+np.exp(-x))
@qml.qnode(dev)
def damping_circuit(x):
qml.Hadamard(wires=0)
qml.CNOT(wires=[0, 1])
qml.AmplitudeDamping(sigmoid(x), wires=0) # p = sigmoid(x)
qml.AmplitudeDamping(sigmoid(x), wires=1)
return qml.expval(qml.PauliZ(0) @ qml.PauliZ(1))
def cost(x, target):
return (damping_circuit(x) - target)**2
opt = qml.GradientDescentOptimizer(stepsize=10)
steps = 35
x = np.tensor(0.0, requires_grad=True)
for i in range(steps):
(x, ev), cost_val = opt.step_and_cost(cost, x, ev)
if i % 5 == 0 or i == steps - 1:
print(f"Step: {i} Cost: {cost_val}")
print(f"QNode output after optimization = {damping_circuit(x):.4f}")
print(f"Experimental expectation value = {ev}")
print(f"Optimized noise parameter p = {sigmoid(x.take(0)):.4f}")
|
https://github.com/MonitSharma/Learn-Quantum-Machine-Learning
|
MonitSharma
|
import pennylane as qml
from pennylane import numpy as np
from matplotlib import pyplot as plt
# set the random seed
np.random.seed(42)
# create a device to execute the circuit on
dev = qml.device("default.qubit", wires=3)
@qml.qnode(dev, diff_method="parameter-shift")
def circuit(params):
qml.RX(params[0], wires=0)
qml.RY(params[1], wires=1)
qml.RZ(params[2], wires=2)
qml.broadcast(qml.CNOT, wires=[0, 1, 2], pattern="ring")
qml.RX(params[3], wires=0)
qml.RY(params[4], wires=1)
qml.RZ(params[5], wires=2)
qml.broadcast(qml.CNOT, wires=[0, 1, 2], pattern="ring")
return qml.expval(qml.PauliY(0) @ qml.PauliZ(2))
# initial parameters
params = np.random.random([6], requires_grad=True)
print("Parameters:", params)
print("Expectation value:", circuit(params))
fig, ax = qml.draw_mpl(circuit, decimals=2)(params)
plt.show()
def parameter_shift_term(qnode, params, i):
shifted = params.copy()
shifted[i] += np.pi/2
forward = qnode(shifted) # forward evaluation
shifted[i] -= np.pi
backward = qnode(shifted) # backward evaluation
return 0.5 * (forward - backward)
# gradient with respect to the first parameter
print(parameter_shift_term(circuit, params, 0))
def parameter_shift(qnode, params):
gradients = np.zeros([len(params)])
for i in range(len(params)):
gradients[i] = parameter_shift_term(qnode, params, i)
return gradients
print(parameter_shift(circuit, params))
grad_function = qml.grad(circuit)
print(grad_function(params)[0])
print(qml.gradients.param_shift(circuit)(params))
dev = qml.device("default.qubit", wires=4)
@qml.qnode(dev, diff_method="parameter-shift")
def circuit(params):
qml.StronglyEntanglingLayers(params, wires=[0, 1, 2, 3])
return qml.expval(qml.PauliZ(0) @ qml.PauliZ(1) @ qml.PauliZ(2) @ qml.PauliZ(3))
# initialize circuit parameters
param_shape = qml.StronglyEntanglingLayers.shape(n_wires=4, n_layers=15)
params = np.random.normal(scale=0.1, size=param_shape, requires_grad=True)
print(params.size)
print(circuit(params))
import timeit
reps = 3
num = 10
times = timeit.repeat("circuit(params)", globals=globals(), number=num, repeat=reps)
forward_time = min(times) / num
print(f"Forward pass (best of {reps}): {forward_time} sec per loop")
# create the gradient function
grad_fn = qml.grad(circuit)
times = timeit.repeat("grad_fn(params)", globals=globals(), number=num, repeat=reps)
backward_time = min(times) / num
print(f"Gradient computation (best of {reps}): {backward_time} sec per loop")
print(2 * forward_time * params.size)
dev = qml.device("default.qubit", wires=4)
@qml.qnode(dev, diff_method="backprop")
def circuit(params):
qml.StronglyEntanglingLayers(params, wires=[0, 1, 2, 3])
return qml.expval(qml.PauliZ(0) @ qml.PauliZ(1) @ qml.PauliZ(2) @ qml.PauliZ(3))
# initialize circuit parameters
param_shape = qml.StronglyEntanglingLayers.shape(n_wires=4, n_layers=15)
params = np.random.normal(scale=0.1, size=param_shape, requires_grad=True)
print(circuit(params))
import timeit
reps = 3
num = 10
times = timeit.repeat("circuit(params)", globals=globals(), number=num, repeat=reps)
forward_time = min(times) / num
print(f"Forward pass (best of {reps}): {forward_time} sec per loop")
times = timeit.repeat("qml.grad(circuit)(params)", globals=globals(), number=num, repeat=reps)
backward_time = min(times) / num
print(f"Backward pass (best of {reps}): {backward_time} sec per loop")
dev = qml.device("default.qubit", wires=4)
def circuit(params):
qml.StronglyEntanglingLayers(params, wires=[0, 1, 2, 3])
return qml.expval(qml.PauliZ(0) @ qml.PauliZ(1) @ qml.PauliZ(2) @ qml.PauliZ(3))
reps = 2
num = 3
forward_shift = []
gradient_shift = []
forward_backprop = []
gradient_backprop = []
for depth in range(0, 21):
param_shape = qml.StronglyEntanglingLayers.shape(n_wires=4, n_layers=depth)
params = np.random.normal(scale=0.1, size=param_shape, requires_grad=True)
num_params = params.size
# forward pass timing
# ===================
qnode_shift = qml.QNode(circuit, dev, diff_method="parameter-shift")
qnode_backprop = qml.QNode(circuit, dev, diff_method="backprop")
# parameter-shift
t = timeit.repeat("qnode_shift(params)", globals=globals(), number=num, repeat=reps)
forward_shift.append([num_params, min(t) / num])
# backprop
t = timeit.repeat("qnode_backprop(params)", globals=globals(), number=num, repeat=reps)
forward_backprop.append([num_params, min(t) / num])
if num_params == 0:
continue
# Gradient timing
# ===============
qnode_shift = qml.QNode(circuit, dev, diff_method="parameter-shift")
qnode_backprop = qml.QNode(circuit, dev, diff_method="backprop")
# parameter-shift
t = timeit.repeat("qml.grad(qnode_shift)(params)", globals=globals(), number=num, repeat=reps)
gradient_shift.append([num_params, min(t) / num])
# backprop
t = timeit.repeat("qml.grad(qnode_backprop)(params)", globals=globals(), number=num, repeat=reps)
gradient_backprop.append([num_params, min(t) / num])
gradient_shift = np.array(gradient_shift).T
gradient_backprop = np.array(gradient_backprop).T
forward_shift = np.array(forward_shift).T
forward_backprop = np.array(forward_backprop).T
plt.style.use("bmh")
fig, ax = plt.subplots(1, 1, figsize=(6, 4))
ax.plot(*gradient_shift, '.-', label="Parameter-shift")
ax.plot(*gradient_backprop, '.-', label="Backprop")
ax.set_ylabel("Time (s)")
ax.set_xlabel("Number of parameters")
ax.legend()
plt.show()
gradient_shift[1] /= forward_shift[1, 1:]
gradient_backprop[1] /= forward_backprop[1, 1:]
fig, ax = plt.subplots(1, 1, figsize=(6, 4))
ax.plot(*gradient_shift, '.-', label="Parameter-shift")
ax.plot(*gradient_backprop, '.-', label="Backprop")
# perform a least squares regression to determine the linear best fit/gradient
# for the normalized time vs. number of parameters
x = gradient_shift[0]
m_shift, c_shift = np.polyfit(*gradient_shift, deg=1)
m_back, c_back = np.polyfit(*gradient_backprop, deg=1)
ax.plot(x, m_shift * x + c_shift, '--', label=f"{m_shift:.2f}p{c_shift:+.2f}")
ax.plot(x, m_back * x + c_back, '--', label=f"{m_back:.2f}p{c_back:+.2f}")
ax.set_ylabel("Normalized time")
ax.set_xlabel("Number of parameters")
ax.set_xscale("log")
ax.set_yscale("log")
ax.legend()
plt.show()
|
https://github.com/MonitSharma/Learn-Quantum-Machine-Learning
|
MonitSharma
|
import matplotlib.pyplot as plt
import pennylane as qml
from pennylane import numpy as np
np.random.seed(135)
def square_loss(targets, predictions):
loss = 0
for t, p in zip(targets, predictions):
loss += (t - p) ** 2
loss = loss / len(targets)
return 0.5*loss
degree = 1 # since we are using a single qubit model it would be better to keep it to 1
scaling = 1 # scaling factor for the data
coeffs = [0.15 + 0.15j]*degree # coefficient of the non-zero frequencies
coeff0 = 0.1 # coefficient of zero frequency
def target_function(x):
"""
Generate a truncated Fourier series, where the data gets re-scaled
"""
res = coeff0
for idx, coeff in enumerate(coeffs):
exponent = np.complex128(scaling * (idx + 1) * x * 1j)
conj_coeff = np.conjugate(coeff)
res += coeff * np.exp(exponent) + conj_coeff * np.exp(-exponent)
return np.real(res)
x = np.linspace(-6, 6, 70, requires_grad=False)
target_y = np.array([target_function(x_) for x_ in x], requires_grad=False)
plt.plot(x, target_y, c='black')
plt.scatter(x, target_y, facecolor='white', edgecolor='black')
plt.ylim(-1, 1)
plt.show();
scaling = 1
dev = qml.device('default.qubit', wires =1)
def S(x):
"""Data encodng circuit block"""
qml.RX(scaling * x, wires = 0)
def W(theta):
"""Trainable circuit block"""
qml.Rot(theta[0], theta[1], theta[2], wires=0)
@qml.qnode(dev)
def serial_quantum_model(weights,x):
for theta in weights[:-1]:
W(theta)
S(x)
# (L+1)'th unitary
W(weights[-1])
return qml.expval(qml.PauliZ(wires=0))
r = 1 # number of times the encoding gets repeated (here equal to the number of layers)
weights = 2 * np.pi * np.random.random(size=(r+1, 3), requires_grad=True) # some random initial weights
x = np.linspace(-6, 6, 70, requires_grad=False)
random_quantum_model_y = [serial_quantum_model(weights, x_) for x_ in x]
plt.plot(x, random_quantum_model_y, c='blue')
plt.ylim(-1,1)
plt.show()
print(qml.draw(serial_quantum_model)(weights, x[-1]))
def cost(weights, x, y):
predictions = [serial_quantum_model(weights, x_) for x_ in x]
return square_loss(y, predictions)
max_steps = 50
opt = qml.AdamOptimizer(0.3)
batch_size = 25
cst = [cost(weights, x, target_y)] # initial cost
for step in range(max_steps):
# Select batch of data
batch_index = np.random.randint(0, len(x), (batch_size,))
x_batch = x[batch_index]
y_batch = target_y[batch_index]
# Update the weights by one optimizer step
weights, _, _ = opt.step(cost, weights, x_batch, y_batch)
# Save, and possibly print, the current cost
c = cost(weights, x, target_y)
cst.append(c)
if (step + 1) % 10 == 0:
print("Cost at step {0:3}: {1}".format(step + 1, c))
predictions = [serial_quantum_model(weights, x_) for x_ in x]
plt.plot(x, target_y, c='black')
plt.scatter(x, target_y, facecolor='white', edgecolor='black')
plt.plot(x, predictions, c='blue')
plt.ylim(-1,1)
plt.show();
plt.plot(range(len(cst)), cst)
plt.ylabel("Cost")
plt.xlabel("Step")
plt.ylim(0, 0.23)
plt.show();
from pennylane.templates import StronglyEntanglingLayers
n_ansatz_layers = 2
n_qubits = 3
dev = qml.device('default.qubit', wires=4)
@qml.qnode(dev)
def ansatz(weights):
StronglyEntanglingLayers(weights, wires=range(n_qubits))
return qml.expval(qml.Identity(wires=0))
weights_ansatz = 2 * np.pi * np.random.random(size=(n_ansatz_layers, n_qubits, 3))
print(qml.draw(ansatz, expansion_strategy="device")(weights_ansatz))
scaling = 1
r = 3
dev = qml.device('default.qubit', wires=r)
def S(x):
"""Data-encoding circuit block."""
for w in range(r):
qml.RX(scaling * x, wires=w)
def W(theta):
"""Trainable circuit block."""
StronglyEntanglingLayers(theta, wires=range(r))
@qml.qnode(dev)
def parallel_quantum_model(weights, x):
W(weights[0])
S(x)
W(weights[1])
return qml.expval(qml.PauliZ(wires=0))
trainable_block_layers = 3
weights = 2 * np.pi * np.random.random(size=(2, trainable_block_layers, r, 3), requires_grad=True)
x = np.linspace(-6, 6, 70, requires_grad=False)
random_quantum_model_y = [parallel_quantum_model(weights, x_) for x_ in x]
plt.plot(x, random_quantum_model_y, c='blue')
plt.ylim(-1,1)
plt.show();
def cost(weights, x, y):
predictions = [parallel_quantum_model(weights, x_) for x_ in x]
return square_loss(y, predictions)
max_steps = 50
opt = qml.AdamOptimizer(0.3)
batch_size = 25
cst = [cost(weights, x, target_y)] # initial cost
for step in range(max_steps):
# select batch of data
batch_index = np.random.randint(0, len(x), (batch_size,))
x_batch = x[batch_index]
y_batch = target_y[batch_index]
# update the weights by one optimizer step
weights, _, _ = opt.step(cost, weights, x_batch, y_batch)
# save, and possibly print, the current cost
c = cost(weights, x, target_y)
cst.append(c)
if (step + 1) % 10 == 0:
print("Cost at step {0:3}: {1}".format(step + 1, c))
predictions = [parallel_quantum_model(weights, x_) for x_ in x]
plt.plot(x, target_y, c='black')
plt.scatter(x, target_y, facecolor='white', edgecolor='black')
plt.plot(x, predictions, c='blue')
plt.ylim(-1,1)
plt.show();
plt.plot(range(len(cst)), cst)
plt.ylabel("Cost")
plt.xlabel("Step")
plt.show();
def fourier_coefficients(f, K):
"""
Computes the first 2*K+1 Fourier coefficients of a 2*pi periodic function.
"""
n_coeffs = 2 * K + 1
t = np.linspace(0, 2 * np.pi, n_coeffs, endpoint=False)
y = np.fft.rfft(f(t)) / t.size
return y
from pennylane.templates import BasicEntanglerLayers
scaling = 1
n_qubits = 4
dev = qml.device('default.qubit', wires=n_qubits)
def S(x):
"""Data encoding circuit block."""
for w in range(n_qubits):
qml.RX(scaling * x, wires=w)
def W(theta):
"""Trainable circuit block."""
BasicEntanglerLayers(theta, wires=range(n_qubits))
@qml.qnode(dev)
def quantum_model(weights, x):
W(weights[0])
S(x)
W(weights[1])
return qml.expval(qml.PauliZ(wires=0))
n_ansatz_layers = 1
def random_weights():
return 2 * np.pi * np.random.random(size=(2, n_ansatz_layers, n_qubits))
n_coeffs = 5
n_samples = 100
coeffs = []
for i in range(n_samples):
weights = random_weights()
def f(x):
return np.array([quantum_model(weights, x_) for x_ in x])
coeffs_sample = fourier_coefficients(f, n_coeffs)
coeffs.append(coeffs_sample)
coeffs = np.array(coeffs)
coeffs_real = np.real(coeffs)
coeffs_imag = np.imag(coeffs)
n_coeffs = len(coeffs_real[0])
fig, ax = plt.subplots(1, n_coeffs, figsize=(15, 4))
for idx, ax_ in enumerate(ax):
ax_.set_title(r"$c_{}$".format(idx))
ax_.scatter(coeffs_real[:, idx], coeffs_imag[:, idx], s=20,
facecolor='white', edgecolor='red')
ax_.set_aspect("equal")
ax_.set_ylim(-1, 1)
ax_.set_xlim(-1, 1)
plt.tight_layout(pad=0.5)
plt.show();
var = 2
n_ansatz_layers = 1
dev_cv = qml.device('default.gaussian', wires=1)
def S(x):
qml.Rotation(x, wires=0)
def W(theta):
"""Trainable circuit block."""
for r_ in range(n_ansatz_layers):
qml.Displacement(theta[0], theta[1], wires=0)
qml.Squeezing(theta[2], theta[3], wires=0)
@qml.qnode(dev_cv)
def quantum_model(weights, x):
W(weights[0])
S(x)
W(weights[1])
return qml.expval(qml.X(wires=0))
def random_weights():
return np.random.normal(size=(2, 5 * n_ansatz_layers), loc=0, scale=var)
n_coeffs = 5
n_samples = 100
coeffs = []
for i in range(n_samples):
weights = random_weights()
def f(x):
return np.array([quantum_model(weights, x_) for x_ in x])
coeffs_sample = fourier_coefficients(f, n_coeffs)
coeffs.append(coeffs_sample)
coeffs = np.array(coeffs)
coeffs_real = np.real(coeffs)
coeffs_imag = np.imag(coeffs)
n_coeffs = len(coeffs_real[0])
fig, ax = plt.subplots(1, n_coeffs, figsize=(15, 4))
for idx, ax_ in enumerate(ax):
ax_.set_title(r"$c_{}$".format(idx))
ax_.scatter(coeffs_real[:, idx], coeffs_imag[:, idx], s=20,
facecolor='white', edgecolor='red')
ax_.set_aspect("equal")
ax_.set_ylim(-1, 1)
ax_.set_xlim(-1, 1)
plt.tight_layout(pad=0.5)
plt.show();
|
https://github.com/MonitSharma/Learn-Quantum-Machine-Learning
|
MonitSharma
|
import pennylane as qml
from pennylane import numpy as np
dev1 = qml.device("default.qubit", wires=1)
@qml.qnode(dev1)
def circuit(params):
qml.RX(params[0], wires=0)
qml.RY(params[1], wires=0)
return qml.expval(qml.PauliZ(0))
print(circuit([0.54,0.12]))
dcircuit = qml.grad(circuit, argnum = 0)
print(dcircuit([0.54,0.12]))
@qml.qnode(dev1)
def circuit2(phi1, phi2):
qml.RX(phi1, wires=0)
qml.RY(phi2, wires=0)
return qml.expval(qml.PauliZ(0))
dcircuit = qml.grad(circuit2, argnum=[0, 1])
print(dcircuit(0.54, 0.12))
def cost(x):
return circuit(x)
init_params = np.array([0.011, 0.012], requires_grad=True)
print(cost(init_params))
# initialise the optimizer
opt = qml.GradientDescentOptimizer(stepsize=0.4)
# set the number of steps
steps = 100
# set the initial parameter values
params = init_params
for i in range(steps):
# update the circuit parameters
params = opt.step(cost, params)
if (i + 1) % 5 == 0:
print("Cost after step {:5d}: {: .7f}".format(i + 1, cost(params)))
print("Optimized rotation angles: {}".format(params))
|
https://github.com/MonitSharma/Learn-Quantum-Machine-Learning
|
MonitSharma
|
!pip install amazon-braket-pennylane-plugin
my_bucket = "amazon-braket-Your-Bucket-Name" # the name of the bucket, keep the 'amazon-braket-' prefix and then include the bucket name
my_prefix = "Your-Folder-Name" # the name of the folder in the bucket
s3_folder = (my_bucket, my_prefix)
device_arn = "arn:aws:braket:::device/quantum-simulator/amazon/sv1"
import pennylane as qml
from pennylane import numpy as np
n_wires = 25
dev_remote = qml.device(
"braket.aws.qubit",
device_arn=device_arn,
wires=n_wires,
s3_destination_folder=s3_folder,
parallel=True,
)
dev_local = qml.device("default.qubit", wires=n_wires)
def circuit(params):
for i in range(n_wires):
qml.RX(params[i], wires=i)
for i in range(n_wires):
qml.CNOT(wires=[i, (i + 1) % n_wires])
# Measure all qubits to make sure all's good with Braket
observables = [qml.PauliZ(n_wires - 1)] + [qml.Identity(i) for i in range(n_wires - 1)]
return qml.expval(qml.operation.Tensor(*observables))
qnode_remote = qml.QNode(circuit, dev_remote)
qnode_local = qml.QNode(circuit, dev_local)
import time
params = np.random.random(n_wires)
t_0_remote = time.time()
qnode_remote(params)
t_1_remote = time.time()
t_0_local = time.time()
qnode_local(params)
t_1_local = time.time()
print("Execution time on remote device (seconds):", t_1_remote - t_0_remote)
print("Execution time on local device (seconds):", t_1_local - t_0_local)
d_qnode_remote = qml.grad(qnode_remote)
t_0_remote_grad = time.time()
d_qnode_remote(params)
t_1_remote_grad = time.time()
print("Gradient calculation time on remote device (seconds):", t_1_remote_grad - t_0_remote_grad)
d_qnode_local = qml.grad(qnode_local)
t_0_local_grad = time.time()
d_qnode_local(params)
t_1_local_grad = time.time()
print("Gradient calculation time on local device (seconds):", t_1_local_grad - t_0_local_grad)
import networkx as nx
nodes = n_wires = 20
edges = 60
seed = 1967
g = nx.gnm_random_graph(nodes, edges, seed=seed)
positions = nx.spring_layout(g, seed=seed)
nx.draw(g, with_labels=True, pos=positions)
dev = qml.device(
"braket.aws.qubit",
device_arn=device_arn,
wires=n_wires,
s3_destination_folder=s3_folder,
parallel=True,
max_parallel=20,
poll_timeout_seconds=30,
)
cost_h, mixer_h = qml.qaoa.maxcut(g)
n_layers = 2
def qaoa_layer(gamma, alpha):
qml.qaoa.cost_layer(gamma, cost_h)
qml.qaoa.mixer_layer(alpha, mixer_h)
def circuit(params, **kwargs):
for i in range(n_wires): # Prepare an equal superposition over all qubits
qml.Hadamard(wires=i)
qml.layer(qaoa_layer, n_layers, params[0], params[1])
return qml.expval(cost_h)
cost_function = qml.QNode(circuit, dev)
optimizer = qml.AdagradOptimizer(stepsize=0.1)
import time
np.random.seed(1967)
params = 0.01 * np.random.uniform(size=[2, n_layers], requires_grad=True)
iterations = 10
for i in range(iterations):
t0 = time.time()
params, cost_before = optimizer.step_and_cost(cost_function, params)
t1 = time.time()
if i == 0:
print("Initial cost:", cost_before)
else:
print(f"Cost at step {i}:", cost_before)
print(f"Completed iteration {i + 1}")
print(f"Time to complete iteration: {t1 - t0} seconds")
print(f"Cost at step {iterations}:", cost_function(params))
np.save("params.npy", params)
print("Parameters saved to params.npy")
|
https://github.com/MonitSharma/Learn-Quantum-Machine-Learning
|
MonitSharma
|
import pennylane as qml
from pennylane import numpy as np
from pennylane.optimize import NesterovMomentumOptimizer
dev = qml.device("default.qubit", wires=4)
def layer(W):
qml.Rot(W[0, 0], W[0, 1], W[0, 2], wires=0)
qml.Rot(W[1, 0], W[1, 1], W[1, 2], wires=1)
qml.Rot(W[2, 0], W[2, 1], W[2, 2], wires=2)
qml.Rot(W[3, 0], W[3, 1], W[3, 2], wires=3)
qml.CNOT(wires=[0, 1])
qml.CNOT(wires=[1, 2])
qml.CNOT(wires=[2, 3])
qml.CNOT(wires=[3, 0])
def statepreparation(x):
qml.BasisState(x, wires=[0, 1, 2, 3])
@qml.qnode(dev)
def circuit(weights, x):
statepreparation(x)
for W in weights:
layer(W)
return qml.expval(qml.PauliZ(0))
def variational_classifier(weights, bias, x):
return circuit(weights, x) + bias
def square_loss(labels, predictions):
loss = 0
for l, p in zip(labels, predictions):
loss = loss + (l - p) ** 2
loss = loss / len(labels)
return loss
def accuracy(labels, predictions):
loss = 0
for l, p in zip(labels, predictions):
if abs(l - p) < 1e-5:
loss = loss + 1
loss = loss / len(labels)
return loss
def cost(weights, bias, X, Y):
predictions = [variational_classifier(weights, bias, x) for x in X]
return square_loss(Y, predictions)
data = np.loadtxt("variational/data/parity.txt")
X = np.array(data[:, :-1], requires_grad=False)
Y = np.array(data[:, -1], requires_grad=False)
Y = Y * 2 - np.ones(len(Y)) # shift label from {0, 1} to {-1, 1}
for i in range(5):
print("X = {}, Y = {: d}".format(X[i], int(Y[i])))
print("...")
np.random.seed(0)
num_qubits = 4
num_layers = 2
weights_init = 0.01 * np.random.randn(num_layers, num_qubits, 3, requires_grad=True)
bias_init = np.array(0.0, requires_grad=True)
print(weights_init, bias_init)
opt = NesterovMomentumOptimizer(0.5)
batch_size = 5
weights = weights_init
bias = bias_init
for it in range(25):
# Update the weights by one optimizer step
batch_index = np.random.randint(0, len(X), (batch_size,))
X_batch = X[batch_index]
Y_batch = Y[batch_index]
weights, bias, _, _ = opt.step(cost, weights, bias, X_batch, Y_batch)
# Compute accuracy
predictions = [np.sign(variational_classifier(weights, bias, x)) for x in X]
acc = accuracy(Y, predictions)
print(
"Iter: {:5d} | Cost: {:0.7f} | Accuracy: {:0.7f} ".format(
it + 1, cost(weights, bias, X, Y), acc
)
)
dev = qml.device("default.qubit", wires=2)
def get_angles(x):
beta0 = 2 * np.arcsin(np.sqrt(x[1] ** 2) / np.sqrt(x[0] ** 2 + x[1] ** 2 + 1e-12))
beta1 = 2 * np.arcsin(np.sqrt(x[3] ** 2) / np.sqrt(x[2] ** 2 + x[3] ** 2 + 1e-12))
beta2 = 2 * np.arcsin(
np.sqrt(x[2] ** 2 + x[3] ** 2)
/ np.sqrt(x[0] ** 2 + x[1] ** 2 + x[2] ** 2 + x[3] ** 2)
)
return np.array([beta2, -beta1 / 2, beta1 / 2, -beta0 / 2, beta0 / 2])
def statepreparation(a):
qml.RY(a[0], wires=0)
qml.CNOT(wires=[0, 1])
qml.RY(a[1], wires=1)
qml.CNOT(wires=[0, 1])
qml.RY(a[2], wires=1)
qml.PauliX(wires=0)
qml.CNOT(wires=[0, 1])
qml.RY(a[3], wires=1)
qml.CNOT(wires=[0, 1])
qml.RY(a[4], wires=1)
qml.PauliX(wires=0)
x = np.array([0.53896774, 0.79503606, 0.27826503, 0.0], requires_grad=False)
ang = get_angles(x)
@qml.qnode(dev)
def test(angles):
statepreparation(angles)
return qml.expval(qml.PauliZ(0))
test(ang)
print("x : ", x)
print("angles : ", ang)
print("amplitude vector: ", np.real(dev.state))
def layer(W):
qml.Rot(W[0, 0], W[0, 1], W[0, 2], wires=0)
qml.Rot(W[1, 0], W[1, 1], W[1, 2], wires=1)
qml.CNOT(wires=[0, 1])
@qml.qnode(dev)
def circuit(weights, angles):
statepreparation(angles)
for W in weights:
layer(W)
return qml.expval(qml.PauliZ(0))
def variational_classifier(weights, bias, angles):
return circuit(weights, angles) + bias
def cost(weights, bias, features, labels):
predictions = [variational_classifier(weights, bias, f) for f in features]
return square_loss(labels, predictions)
data = np.loadtxt("variational/data/iris.txt")
X = data[:, 0:2]
print("First X sample (original) :", X[0])
# pad the vectors to size 2^2 with constant values
padding = 0.3 * np.ones((len(X), 1))
X_pad = np.c_[np.c_[X, padding], np.zeros((len(X), 1))]
print("First X sample (padded) :", X_pad[0])
# normalize each input
normalization = np.sqrt(np.sum(X_pad ** 2, -1))
X_norm = (X_pad.T / normalization).T
print("First X sample (normalized):", X_norm[0])
# angles for state preparation are new features
features = np.array([get_angles(x) for x in X_norm], requires_grad=False)
print("First features sample :", features[0])
Y = data[:, -1]
import matplotlib.pyplot as plt
plt.figure()
plt.scatter(X[:, 0][Y == 1], X[:, 1][Y == 1], c="b", marker="o", edgecolors="k")
plt.scatter(X[:, 0][Y == -1], X[:, 1][Y == -1], c="r", marker="o", edgecolors="k")
plt.title("Original data")
plt.show()
plt.figure()
dim1 = 0
dim2 = 1
plt.scatter(
X_norm[:, dim1][Y == 1], X_norm[:, dim2][Y == 1], c="b", marker="o", edgecolors="k"
)
plt.scatter(
X_norm[:, dim1][Y == -1], X_norm[:, dim2][Y == -1], c="r", marker="o", edgecolors="k"
)
plt.title("Padded and normalised data (dims {} and {})".format(dim1, dim2))
plt.show()
plt.figure()
dim1 = 0
dim2 = 3
plt.scatter(
features[:, dim1][Y == 1], features[:, dim2][Y == 1], c="b", marker="o", edgecolors="k"
)
plt.scatter(
features[:, dim1][Y == -1], features[:, dim2][Y == -1], c="r", marker="o", edgecolors="k"
)
plt.title("Feature vectors (dims {} and {})".format(dim1, dim2))
plt.show()
np.random.seed(0)
num_data = len(Y)
num_train = int(0.75 * num_data)
index = np.random.permutation(range(num_data))
feats_train = features[index[:num_train]]
Y_train = Y[index[:num_train]]
feats_val = features[index[num_train:]]
Y_val = Y[index[num_train:]]
# We need these later for plotting
X_train = X[index[:num_train]]
X_val = X[index[num_train:]]
num_qubits = 2
num_layers = 6
weights_init = 0.01 * np.random.randn(num_layers, num_qubits, 3, requires_grad=True)
bias_init = np.array(0.0, requires_grad=True)
opt = NesterovMomentumOptimizer(0.01)
batch_size = 5
# train the variational classifier
weights = weights_init
bias = bias_init
for it in range(60):
# Update the weights by one optimizer step
batch_index = np.random.randint(0, num_train, (batch_size,))
feats_train_batch = feats_train[batch_index]
Y_train_batch = Y_train[batch_index]
weights, bias, _, _ = opt.step(cost, weights, bias, feats_train_batch, Y_train_batch)
# Compute predictions on train and validation set
predictions_train = [np.sign(variational_classifier(weights, bias, f)) for f in feats_train]
predictions_val = [np.sign(variational_classifier(weights, bias, f)) for f in feats_val]
# Compute accuracy on train and validation set
acc_train = accuracy(Y_train, predictions_train)
acc_val = accuracy(Y_val, predictions_val)
print(
"Iter: {:5d} | Cost: {:0.7f} | Acc train: {:0.7f} | Acc validation: {:0.7f} "
"".format(it + 1, cost(weights, bias, features, Y), acc_train, acc_val)
)
plt.figure()
cm = plt.cm.RdBu
# make data for decision regions
xx, yy = np.meshgrid(np.linspace(0.0, 1.5, 20), np.linspace(0.0, 1.5, 20))
X_grid = [np.array([x, y]) for x, y in zip(xx.flatten(), yy.flatten())]
# preprocess grid points like data inputs above
padding = 0.3 * np.ones((len(X_grid), 1))
X_grid = np.c_[np.c_[X_grid, padding], np.zeros((len(X_grid), 1))] # pad each input
normalization = np.sqrt(np.sum(X_grid ** 2, -1))
X_grid = (X_grid.T / normalization).T # normalize each input
features_grid = np.array(
[get_angles(x) for x in X_grid]
) # angles for state preparation are new features
predictions_grid = [variational_classifier(weights, bias, f) for f in features_grid]
Z = np.reshape(predictions_grid, xx.shape)
# plot decision regions
cnt = plt.contourf(
xx, yy, Z, levels=np.arange(-1, 1.1, 0.1), cmap=cm, alpha=0.8, extend="both"
)
plt.contour(
xx, yy, Z, levels=[0.0], colors=("black",), linestyles=("--",), linewidths=(0.8,)
)
plt.colorbar(cnt, ticks=[-1, 0, 1])
# plot data
plt.scatter(
X_train[:, 0][Y_train == 1],
X_train[:, 1][Y_train == 1],
c="b",
marker="o",
edgecolors="k",
label="class 1 train",
)
plt.scatter(
X_val[:, 0][Y_val == 1],
X_val[:, 1][Y_val == 1],
c="b",
marker="^",
edgecolors="k",
label="class 1 validation",
)
plt.scatter(
X_train[:, 0][Y_train == -1],
X_train[:, 1][Y_train == -1],
c="r",
marker="o",
edgecolors="k",
label="class -1 train",
)
plt.scatter(
X_val[:, 0][Y_val == -1],
X_val[:, 1][Y_val == -1],
c="r",
marker="^",
edgecolors="k",
label="class -1 validation",
)
plt.legend()
plt.show()
|
https://github.com/fiasqo-io/quantumcircuit_gym
|
fiasqo-io
|
import gym
import gym_quantcircuit
import numpy as np
env = gym.make('quantcircuit-v0')
num_qubits = 3
test_goal_state = [0j] * (2**num_qubits - 1) + [1+0j]
env.var_init(num_qubits,
unitary=False,
gate_group='pauli',
connectivity='fully_connected',
goal_state=test_goal_state)
env.render()
env.plot_connectivity_graph()
action = env.sample()
env.gate_list[action]
env.step(action)
env.render()
for _ in range(5):
env.step(env.sample())
env.render()
env.reset()
env.render()
# Environment must be created before this step
custom_gate_group = [
env.qcircuit.x,
env.qcircuit.h,
env.qcircuit.t
]
env.set_gate_group('custom',custom_gate_group)
env.gate_list = env._create_gates()
env.gate_list
# Nearest neighbour
nnenv = gym.make('quantcircuit-v0')
nnenv.var_init(5,connectivity='nearest_neighbour')
nnenv.plot_connectivity_graph()
# Fully Connected
fc_env = gym.make('quantcircuit-v0')
fc_env.var_init(5,connectivity='fully_connected')
fc_env.plot_connectivity_graph()
# IBM - limited to 5, 14 or 20 qubits (these are the only current physical architectures)
ibm_env = gym.make('quantcircuit-v0')
ibm_env.var_init(5,connectivity='ibm')
ibm_env.plot_connectivity_graph()
# Custom
custom_conn = np.array([[1,1,1,0],[1,1,1,0],[1,1,1,1],[0,0,1,1]])
custom_env = gym.make('quantcircuit-v0')
custom_env.var_init(4,connectivity='custom',custom_connectivity=custom_conn)
custom_env.plot_connectivity_graph()
num_gates = 2
curriculum, tracker = env.make_curriculum(num_gates)
curriculum
tracker
|
https://github.com/fiasqo-io/quantumcircuit_gym
|
fiasqo-io
|
import itertools as it
import gym
from gym import error, spaces, utils
from gym.utils import seeding
import qiskit
from qiskit import QuantumRegister, QuantumCircuit, execute, Aer
from qutip import qeye, basis, Qobj, fidelity, hadamard_transform, qubit_states, tracedist
import numpy as np
import matplotlib.pyplot as plt
import networkx as nx
class QuantCircuitEnv(gym.Env):
"""
A quantum circuit implementation using the Qiskit library, containing methods to construct
and simulate quantum circuits designed to perform specific operations. Mainly for use in
Reinforcement Learning with an agent choosing and learning actions for a specific goal.
"""
def __init__(self):
pass
def var_init(self,
num_qubits,
unitary=False,
gate_group='pauli',
connectivity='nearest_neighbour',
goal_state=None,
goal_unitary=None,
custom_gates=None,
custom_connectivity=None):
"""
Initialises the Quantum Circuit Environment object with arguments since gym.make can't
do so.
Args:
num_qubits (int): number of qubits in the desired circuit
unitary (bool): if True sets environment to use unitary matrices,
otherwise uses statevectors
gate_group (str): string to define the gate group used,
options include 'pauli','clifford' and 'IQP'
goal_state (list): list of complex values defining goal statevector,
must have 2**num_qubits values
goal_unitary (np.array): goal unitary matrix,
must have shape (2**num_qubits, 2**num_qubits)
custom_gates (list): list of gate functions to use in the circuit
custom_connectivity (np.array): a NxN binary matrix where N is the number of qubits,
with entry [i,j] = 1 when qubit i is physically
connected to qubit j.
Return:
None
"""
# Define whether using unitaries or statevectors
try:
self.is_unitary = bool(unitary)
except ValueError:
print('Please use a boolean value for "unitary".')
# Set number of qubits in circuit, and dimensionality
try:
self.num_qubits = int(num_qubits)
except ValueError:
print('Please use an integer value for number of qubits.')
self.dimension = 2**self.num_qubits
# Initialise qiskit circuit object
self.q_reg = QuantumRegister(self.num_qubits)
self.qcircuit = QuantumCircuit(self.q_reg)
# Initialise current/goal statevectors
self.current_state = [1+0j] + [0+0j]*(self.dimension - 1)
# concatenate real and imaginary parts of statevector into one array
self.comp_state = np.append(np.real(self.current_state), np.imag(self.current_state))
if goal_state is None:
self.goal_state = [1+0j]+[0+0j]*(self.dimension-1)
else:
assert len(goal_state) == self.dimension, 'Goal state is not correct length.'
self.goal_state = goal_state
self.comp_goal = np.append(np.real(self.goal_state), np.imag(self.goal_state))
# Initialise unitaries
if self.is_unitary:
self.current_unitary = qeye(self.dimension).full()
if goal_unitary is None:
self.goal_unitary = qeye(self.dimension).full()
else:
assert np.asarray(goal_unitary).shape == (self.dimension, self.dimension), ('Goal '
'unitary is not correct shape.')
self.goal_unitary = goal_unitary
# Define gate group used
self.gate_group = gate_group
self.set_gate_group(gate_group, custom_gates)
# Initialise qubit connectivity
self.define_connectivity(connectivity, custom_connectivity)
# Initialise gate list
self.gate_list = self._create_gates()
# Initialise other various values
self.basis_state = basis(self.dimension)
self.gate_count = 1
self.action_space_n = len(self.gate_list)
self.num_actions = self.num_qubits*6
self.EPS = 1e-10
self.has_run = False
def step(self, action):
"""
Takes a single step (action) inside the environment
Args:
action (int): index of the action in self.gate_list generated by self._create_gates -
containing all combinations of legal qubit/gate combinations
Return:
diff (np.array): difference between current and goal state
reward (float): reward gained from taking the specified action
done (bool): True if agent has reached the goal, False otherwise
measures (dict): dictionary containing the measure used to determine reward
"""
if not self.has_run:
self.set_gate_group(self.gate_group)
self.gate_list = self._create_gates()
self.has_run = True
assert action in range(self.action_space_n), 'Not a valid action.'
# Initialize done variable
done = False
# Extra reward for using identities instead of other gates - may not be needed?
extra = 0
# Keep track of number of gates used
self.gate_count += 1
# Check if multi-qubit gate - self.gate_list[action][0] is a tuple of the qubits
if len(self.gate_list[action][0]) > 1:
# Apply gate to circuit - the second arg of the tuple is the gate function
self.gate_list[action][1](self.q_reg[self.gate_list[action][0][0]],
self.q_reg[self.gate_list[action][0][1]])
else:
# Do the same but for single qubit gates
self.gate_list[action][1](self.q_reg[self.gate_list[action][0][0]])
# Unitary case
if self.is_unitary:
self.job = execute(self.qcircuit,
backend=qiskit.BasicAer.get_backend('unitary_simulator'))
self.current_unitary = self.job.result().get_unitary(self.qcircuit)
diff = np.asarray(self.goal_unitary-self.current_unitary).flatten()
diff = np.append(np.real(diff), np.imag(diff))
# Statevector case
else:
self.job = execute(self.qcircuit,
backend=qiskit.BasicAer.get_backend('statevector_simulator'))
self.current_state = self.job.result().get_statevector(self.qcircuit)
self.comp_state = np.append(np.real(self.current_state), np.imag(self.current_state))
diff = self.comp_goal - self.comp_state
reward = 0
# Reward inversely proportional to number of gates used if fidelity is hit
if round(self.fidelity(), 3) == 1:
reward = 50*(1/(self.gate_count+1))
done = True
return diff, reward, done, {'fidelity': round(self.fidelity(), 3)}
def reset(self):
"""
Resets the circuit to empty and any relevant variables to their initial state
Return:
diff (list): real and imaginary parts of the current reset quantum state/unitary
"""
self.qcircuit = QuantumCircuit(self.q_reg)
self.current_state = [1+0j]+[0+0j]*(2**self.num_qubits-1)
self.current_unitary = qeye(2**self.num_qubits).full()
self.comp_state = np.append(np.real(self.current_state), np.imag(self.current_state))
self.gate_count = 0
self.has_run = False
if self.is_unitary:
diff = np.asarray(self.goal_unitary-self.current_unitary).flatten()
diff = np.append(np.real(diff), np.imag(diff))
else:
diff = self.comp_goal - self.comp_state
return diff
def render(self):
"""
Return:
text drawing of the current circuit represented by the QuantumCircuit object
"""
return self.qcircuit.draw()
def define_goal(self, goal_state):
"""
Defines goal statevector or unitary matrix for the circuit.
Args:
goal_state (list): flattened statevector or unitary matrix
Return:
None
"""
if self.is_unitary:
self.goal_unitary = goal_state
elif not self.is_unitary:
assert len(goal_state) == len(self.current_state)
self.goal_state = goal_state
self.comp_goal = np.append(np.real(goal_state), np.imag(goal_state))
def sample(self):
"""
Return:
action (int): a specific action in the circuit environment action space
"""
action = np.random.randint(0, self.action_space_n)
return action
def fidelity(self):
"""
Calculates fidelity of current and goal state/unitary.
Return:
fid (float): fidelity measure
"""
if self.is_unitary:
assert self.current_unitary.shape == self.goal_unitary.shape
fid = fidelity(Qobj(self.current_unitary)*self.basis_state,
Qobj(self.goal_unitary)*self.basis_state)
else:
assert len(self.current_state) == len(self.goal_state)
fid = fidelity(Qobj([self.current_state]), Qobj([self.goal_state]))
return fid
def set_gate_group(self, gate_group, custom_gates=None):
"""
Defines the gate group to be used within the enviroment
Args:
gate_group (str): name of the gate group used
custom_gates (dict): A set of custom gates may be defined using a dictionary,
the form looks like{"gate_name":gate_function}
Returns:
None
"""
gate_group = gate_group.lower()
if gate_group == 'clifford':
# Clifford group uses cnot, phase gate and hadamard
self.gate_group_list = [
self.qcircuit.iden,
self.qcircuit.cx,
self.qcircuit.h,
self.qcircuit.s,
self.qcircuit.t
]
elif gate_group == 'pauli':
self.gate_group_list = [
self.qcircuit.iden,
self.qcircuit.h,
self.qcircuit.x,
self.qcircuit.z,
self.qcircuit.cx
]
elif gate_group == 'IQP':
self.gate_group_list = [
self.qcircuit.iden,
self.qcircuit.t,
(2, self.c_s_gate)
]
# Sets up the circuit with initial hadamard gates,
# as is necessary for circuits with the IQP format
temp_state = (hadamard_transform(self.num_qubits)*
qubit_states(self.num_qubits)).full()
self.qcircuit.initialize(temp_state.flatten(),
[self.q_reg[i] for i in range(self.num_qubits)])
elif gate_group == 'custom':
assert custom_gates is not None, 'custom_gates is not defined.'
self.gate_group_list = custom_gates
else:
raise "%s gate_group not defined!"%gate_group
def _create_gates(self):
"""
Create a list of gate/qubit tuples that contains all possible combinations
given a defined qubit connectivity.
Return:
gate_list (list): list of tuples of all qubit/gate combinations
"""
gate_list = []
for gates in self.gate_group_list:
if isinstance(gates, tuple):
gate_qubits = gates[0]
gates = gates[1]
else:
# Qiskit defines the gate function as 'iden',
# but in the descriptions of a circuit object calls the identity 'id'
# changed to make valid key for the dictionary
if gates.__name__ == 'iden':
name = 'id'
else:
name = gates.__name__
gate_qubits = self.qcircuit.definitions[str(name)]['n_bits']
# Check if multi-qubit gate (currently max is 2 qubits)
if gate_qubits > 1:
for qubits_t in range(self.num_qubits):
for qubits_c in range(self.num_qubits):
# Check for connectivity, and don't allow connection with self
if self.connectivity[qubits_t, qubits_c] == 1 and qubits_t != qubits_c:
gate_list.append(((qubits_t, qubits_c), gates))
else:
# Assumption made that these are single-qubit gates
for i in range(self.num_qubits):
gate_list.append(((i, ), gates))
return gate_list
def define_connectivity(self, connectivity, custom_matrix=None):
"""
Creates a binary matrix that describes the connections between qubits
Args:
connectivity (str): string representation of connectivity format
custom_matrix (np.array): binary array with index pairs denoting a connection between
those two qubits i.e. (i,j) = 1 if qubit i is connected to
qubit j. This is a one way mapping, if two way connectivity is
desired the array must be symmetric about the diagonal.
Return:
None
"""
connectivity_matrix = np.identity(self.num_qubits)
connectivity = connectivity.lower()
assert connectivity in ['nearest_neighbour', 'fully_connected', 'custom', 'ibm']
if connectivity == 'nearest_neighbour':
for i in range(self.num_qubits-1):
connectivity_matrix[i, i+1] = 1
connectivity_matrix[i+1, i] = 1
# Connects extremities
connectivity_matrix[0, self.num_qubits-1] == 1
connectivity_matrix[self.num_qubits-1, 0] == 1
elif connectivity == 'fully_connected':
#fully conencted mean every conenction is allowable
connectivity_matrix = np.ones((self.num_qubits, self.num_qubits))
elif connectivity == "custom":
assert np.asarray(custom_matrix).shape == ((self.num_qubits, self.num_qubits),
"Dimension mismatch!")
connectivity_matrix = custom_matrix
elif connectivity == "ibm":
assert self.num_qubits in [5, 14, 20]
# Based on IBMQ 5 Tenerife and IBMQ 5 Yorktown
if self.num_qubits == 5:
connectivity_matrix = np.array([[0, 1, 1, 0, 0],
[1, 0, 1, 0, 0],
[1, 1, 0, 1, 1],
[0, 0, 1, 0, 1],
[0, 0, 1, 1, 0]])
# Based on IBMQ 14 Melbourne
elif self.num_qubits == 14:
connectivity_matrix = np.zeros((14, 14))
for i in range(14):
for j in range(14):
if i + j == 14:
connectivity_matrix[(i, j)] = 1
for i in range(13):
if i != 6:
connectivity_matrix[(i, i+1)] = 1
# Based on IBMQ 20 Tokyo
elif self.num_qubits == 20:
connectivity_matrix = np.zeros((20, 20))
for k in [0, 5, 10, 15]:
for j in range(k, k+4):
connectivity_matrix[(j, j+1)] = 1
for k in range(5):
connectivity_matrix[(k, k+5)] = 1
connectivity_matrix[(k+5, k+10)] = 1
connectivity_matrix[(k+10, k+15)] = 1
for k in [1, 3, 5, 7, 11, 13]:
connectivity_matrix[(k, k+6)] = 1
for k in [2, 4, 6, 8, 12, 14]:
connectivity_matrix[(k, k+4)] = 1
self.connectivity = connectivity_matrix
def plot_connectivity_graph(self):
"""
Draws a graph of nodes and edges that represents the physical connectivity of the qubits.
Graph will not be completely symmetric and will not be an exact replica of the framework,
but will provide an accurate visual representation of the connections between qubits.
Returns:
None
"""
graph = nx.Graph()
graph.add_nodes_from([i for i in range(self.num_qubits)])
for i in range(self.num_qubits):
for j in range(self.num_qubits):
if self.connectivity[(i, j)] == 1:
graph.add_edge(i, j)
nx.draw(graph, with_labels=True, font_weight='bold')
plt.show()
def trace_norm(self):
"""
Calculates trace norms of density state of matrix - to use this as a metric,
take the difference (p_0 - p_1) and return the value of the trace distance
Return:
dist (float): trace distance of difference between density matrices
"""
current = Qobj(self.current_state)
goal = Qobj(self.goal_state)
density_1 = current*current.dag()
density_2 = goal*goal.dag()
dist = tracedist(density_1, density_2)
return dist
def c_s_gate(self, target, control):
"""
Creates custom composite gate from defined qiskit gates that is contained in the IQP group
Args:
target (int): index of the target qubit
control (int): index of the control qubit
Return:
None
"""
# We need to create a controlled-S gate using simple gates from qiskit,
# this can be done using cnots and T gates + T_dag
self.qcircuit.cx(control, target)
self.qcircuit.tdg(target)
self.qcircuit.cx(control, target)
self.qcircuit.t(target)
self.qcircuit.t(control)
def make_curriculum(self, num_gates, loop_list=None):
"""
Designs curriculum for agent which gradually increases goal difficulty.
Args:
num_gates (int): max number of gates for a circuit in the curriculum
loop_list (list): A list of times you want to loop each curriculum stage
Return:
curriculum (list): list of goal unitaries/statevectors for the agent to target
tracker (array): array of how many goals found in each section
"""
if not loop_list is None:
assert len(loop_list) == num_gates, ('List of number of loops for each gate'
'must have length num_gates')
loop_num = 0
gate_group_n = len(self.gate_group_list)
curriculum, state_check, tracker = ([], [], [])
self.gate_list = self._create_gates()
num_moves = len(self.gate_list)
moves = np.linspace(0, num_moves-1, num_moves)
for j in range(0, num_gates):
max_gates = j+1
curriculum_sect = []
if max_gates < 4:
all_moves = [p for p in it.product(moves, repeat=max_gates)]
else:
all_moves = np.zeros(5000)
for k in range(0, len(all_moves)):
self.reset()
self.set_gate_group(self.gate_group)
l = 0
move_set = all_moves[k]
while l != max_gates:
if max_gates >= 4:
#randomly search combinations
i = np.random.randint(0, num_moves)
else:
#move through every combination
i = move_set[l]
self.gate_list = self._create_gates()
tple = self.gate_list[int(i)]
if len(tple[0]) > 1:
tple[1](self.q_reg[tple[0][0]], self.q_reg[tple[0][1]])
else:
tple[1](self.q_reg[tple[0][0]])
l += 1
else:
job2 = execute(self.qcircuit,
backend=qiskit.BasicAer.get_backend('statevector_simulator'))
state_to_check = job2.result().get_statevector(self.qcircuit)
for i in range(len(state_to_check.real)):
state_to_check.real[i] = np.round(state_to_check.real[i], 4)
state_to_check.imag[i] = np.round(state_to_check.imag[i], 4)
if self.is_unitary:
job = execute(self.qcircuit,
backend=qiskit.BasicAer.get_backend('unitary_simulator'))
current_state = job.result().get_unitary(self.qcircuit)
for i in range(len(current_state.real)):
for j in range(len(current_state[0].real)):
current_state.real[i][j] = np.round(current_state.real[i][j], 4)
current_state.imag[i][j] = np.round(current_state.imag[i][j], 4)
else:
current_state = state_to_check
if len(state_check) >= 1:
if (any(np.equal(state_check, state_to_check).all(1)) or
any(np.equal(state_check, -state_to_check).all(1))):
pass
else:
curriculum_sect.append(current_state)
state_check.append(state_to_check)
else:
curriculum_sect.append(current_state)
state_check.append(state_to_check)
tracker.append(len(curriculum_sect))
if loop_list is None:
loop = 1
else:
loop = loop_list[loop_num]
curriculum += curriculum_sect*loop
loop_num += 1
for i in range(len(curriculum)):
curriculum[i] = np.ndarray.tolist(curriculum[i])
return curriculum, tracker
|
https://github.com/UST-QuAntiL/qiskit-service
|
UST-QuAntiL
|
# ******************************************************************************
# Copyright (c) 2020-2021 University of Stuttgart
#
# See the NOTICE file(s) distributed with this work for additional
# information regarding copyright ownership.
#
# 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.
# ******************************************************************************
from qiskit_braket_provider import AWSBraketProvider
from braket.aws.aws_session import AwsSession
import boto3
from qiskit.providers.jobstatus import JOB_FINAL_STATES
from qiskit import QiskitError
def get_qpu(access_key, secret_access_key, qpu_name, region='eu-west-2'):
boto_session = boto3.Session(
aws_access_key_id=access_key,
aws_secret_access_key=secret_access_key,
region_name=region,
)
session = AwsSession(boto_session)
provider = AWSBraketProvider()
backend = provider.get_backend(qpu_name, aws_session=session)
return backend
def execute_job(transpiled_circuit, shots, backend):
"""Generate qObject from transpiled circuit and execute it. Return result."""
try:
job = backend.run(transpiled_circuit, shots=shots)
job_status = job.status()
while job_status not in JOB_FINAL_STATES:
print("The job is still running")
job_status = job.status()
job_result = job.result()
print("\nJob result:")
print(job_result)
job_result_dict = job_result.to_dict()
print(job_result_dict)
try:
statevector = job_result.get_statevector()
print("\nState vector:")
print(statevector)
except QiskitError:
statevector = None
print("No statevector available!")
try:
counts = job_result.get_counts()
print("\nCounts:")
print(counts)
except QiskitError:
counts = None
print("No counts available!")
try:
unitary = job_result.get_unitary()
print("\nUnitary:")
print(unitary)
except QiskitError:
unitary = None
print("No unitary available!")
return {'job_result_raw': job_result_dict, 'statevector': statevector, 'counts': counts, 'unitary': unitary}
except Exception:
return None
|
https://github.com/UST-QuAntiL/qiskit-service
|
UST-QuAntiL
|
#!/usr/bin/env python
# coding: utf-8
from qiskit import QuantumCircuit
from qiskit.aqua.components.optimizers import COBYLA, ADAM, SPSA
from qiskit.circuit.library import ZZFeatureMap, RealAmplitudes, ZFeatureMap, PauliFeatureMap
from qiskit.quantum_info import Statevector
import numpy as np
import pandas as pd
from sklearn.preprocessing import MinMaxScaler
from sklearn.model_selection import train_test_split
from sklearn.utils import shuffle
import csv
import warnings
warnings.filterwarnings("ignore")
class Benchmark:
"""
Benchmarking different optimizers, featuremaps and depth of variational circuits
"""
def __init__(self, optimizer, variational_depth, feature_map, X_train, X_test, Y_train, Y_test):
"""
Initial function
:param optimizer: The optimizer to benchmark
:param variational_depth: The depth of the variational circuit
:param feature_map: The featuremap that encodes data
:param X_train: The x data for training
:param X_test: The x data for testing
:param Y_train: The y data for training
:param Y_test: The y data for testing
"""
self.optimizer = optimizer
self.variational_depth = variational_depth
self.feature_map = feature_map
self.no_qubit = 4
self.random_state = 42
self.class_labels = ['yes', 'no']
self.circuit = None
self.var_form = RealAmplitudes(self.no_qubit, reps=self.variational_depth)
self.sv = Statevector.from_label('0' * self.no_qubit)
self.X_train, self.X_test, self.Y_train, self.Y_test = X_train, X_test, Y_train, Y_test
self.cost_list = []
def prepare_circuit(self):
"""
Prepares the circuit. Combines an encoding circuit, feature map, to a variational circuit, RealAmplitudes
:return:
"""
self.circuit = self.feature_map.combine(self.var_form)
# circuit.draw(output='mpl')
def get_data_dict(self, params, x):
"""
Assign the params to the variational circuit and the data to the featuremap
:param params: Parameter for training the variational circuit
:param x: The data
:return parameters:
"""
parameters = {}
for i, p in enumerate(self.feature_map.ordered_parameters):
parameters[p] = x[i]
for i, p in enumerate(self.var_form.ordered_parameters):
parameters[p] = params[i]
return parameters
def assign_label(self, bit_string):
"""
Based on the output from measurements assign no if it odd parity and yes if it is even parity
:param bit_string: The bit string eg 00100
:return class_label: Yes or No
"""
hamming_weight = sum([int(k) for k in list(bit_string)])
is_odd_parity = hamming_weight & 1
if is_odd_parity:
return self.class_labels[1]
else:
return self.class_labels[0]
def return_probabilities(self, counts):
"""
Calculates the probabilities of the class label after assigning the label from the bit string measured
as output
:type counts: dict
:param counts: The counts from the measurement of the quantum circuit
:return result: The probability of each class
"""
shots = sum(counts.values())
result = {self.class_labels[0]: 0, self.class_labels[1]: 0}
for key, item in counts.items():
label = self.assign_label(key)
result[label] += counts[key] / shots
return result
def classify(self, x_list, params):
"""
Assigns the x and params to the quantum circuit the runs a measurement to return the probabilities
of each class
:type params: List
:type x_list: List
:param x_list: The x data
:param params: Parameters for optimizing the variational circuit
:return probs: The probabilities
"""
qc_list = []
for x in x_list:
circ_ = self.circuit.assign_parameters(self.get_data_dict(params, x))
qc = self.sv.evolve(circ_)
qc_list += [qc]
probs = []
for qc in qc_list:
counts = qc.to_counts()
prob = self.return_probabilities(counts)
probs += [prob]
return probs
@staticmethod
def mse_cost(probs, expected_label):
"""
Calculates the mean squared error from the expected values and calculated values
:type expected_label: List
:type probs: List
:param probs: The expected values
:param expected_label: The real values
:return mse: The mean squared error
"""
p = probs.get(expected_label)
actual, pred = np.array(1), np.array(p)
mse = np.square(np.subtract(actual, pred)).mean()
return mse
def cost_function(self, X, Y, params, print_value=False):
"""
This is the cost function and returns cost for optimization
:type print_value: Boolean
:type params: List
:type Y: List
:type X: List
:param X: The x data
:param Y: The label
:param params: The parameters
:param print_value: If you want values to be printed
:return cost:
"""
# map training input to list of labels and list of samples
cost = 0
training_labels = []
training_samples = []
for sample in X:
training_samples += [sample]
for label in Y:
if label == 0:
training_labels += [self.class_labels[0]]
elif label == 1:
training_labels += [self.class_labels[1]]
probs = self.classify(training_samples, params)
# evaluate costs for all classified samples
for i, prob in enumerate(probs):
cost += self.mse_cost(prob, training_labels[i])
cost /= len(training_samples)
# print resulting objective function
if print_value:
print('%.4f' % cost)
# return objective value
self.cost_list.append(cost)
return cost
def test_model(self, X, Y, params):
"""
Test the model based on x test and y test
:type params: List
:type Y: List
:type X: List
:param X: The x test set
:param Y: The y test set
:param params: The parameters
:return:
"""
accuracy = 0
training_samples = []
for sample in X:
training_samples += [sample]
probs = self.classify(training_samples, params)
for i, prob in enumerate(probs):
if (prob.get('yes') >= prob.get('no')) and (Y[i] == 0):
accuracy += 1
elif (prob.get('no') >= prob.get('yes')) and (Y[i] == 1):
accuracy += 1
accuracy /= len(Y)
print("Test accuracy: {}".format(accuracy))
def run(self):
"""
Runs the whole code
1. Prepares the circuit
2. define the objective function
3. Initialize the paramters
4. Optimize the paramters by training the classifier
:return:
"""
self.prepare_circuit()
# define objective function for training
objective_function = lambda params: self.cost_function(self.X_train, self.Y_train, params, print_value=False)
# randomly initialize the parameters
np.random.seed(self.random_state)
init_params = 2 * np.pi * np.random.rand(self.no_qubit * self.variational_depth * 2)
# train classifier
opt_params, value, _ = self.optimizer.optimize(len(init_params), objective_function, initial_point=init_params)
# print results
# print()
# print('opt_params:', opt_params)
# print('opt_value: ', value)
self.test_model(self.X_test, self.Y_test, opt_params)
def get_cost_list(self):
"""
Return the cost list
:return cost list:
"""
return self.cost_list
def normalize_data(dataPath="../../Data/Processed/heartdata.csv"):
"""
Normalizes the data
:return X_train, X_test, Y_train, Y_test:
"""
# Reads the data
data = pd.read_csv(dataPath)
data = shuffle(data, random_state=42)
X, Y = data[['sex', 'cp', 'exang', 'oldpeak']].values, data['num'].values
# normalize the data
scaler = MinMaxScaler(feature_range=(-2 * np.pi, 2 * np.pi))
X = scaler.fit_transform(X)
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.3, random_state=42)
return X_train, X_test, Y_train, Y_test
def main():
data = {}
feature_maps = ['ZZFeatureMap(4, reps=1)', 'ZZFeatureMap(4, reps=2)', 'ZZFeatureMap(4, reps=4)',
'ZFeatureMap(4, reps=1)', 'ZFeatureMap(4, reps=2)', 'ZFeatureMap(4, reps=4)',
'PauliFeatureMap(4, reps=1)', 'PauliFeatureMap(4, reps=2)', 'PauliFeatureMap(4, reps=4)']
optimizers = ["COBYLA(maxiter=50)", "SPSA(max_trials=50)", "ADAM(maxiter=50)"]
x_train, x_test, y_train, y_test = normalize_data()
for fe in feature_maps:
for i in [1, 3, 5]:
for opt in optimizers:
print("FE: {}\tDepth: {}\tOpt: {}".format(fe, i, opt))
test_benchmark = Benchmark(optimizer=eval(opt), variational_depth=i, feature_map=eval(fe), X_train=x_train, X_test=x_test, Y_train=y_train, Y_test=y_test)
test_benchmark.run()
data_list = "{} {} vdepth {}".format(fe, opt, i)
data[data_list] = test_benchmark.get_cost_list()
w = csv.writer(open("../../Data/Processed/heartcosts.csv", "w"))
for key, val in data.items():
w.writerow([key, val])
if __name__ == "__main__":
main()
|
https://github.com/UST-QuAntiL/qiskit-service
|
UST-QuAntiL
|
# ******************************************************************************
# Copyright (c) 2020-2024 University of Stuttgart
#
# See the NOTICE file(s) distributed with this work for additional
# information regarding copyright ownership.
#
# 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.
# ******************************************************************************
from time import sleep
from qiskit import QiskitError, QuantumRegister, execute, Aer
from qiskit.compiler import assemble
from qiskit.providers.exceptions import JobError, JobTimeoutError
from qiskit.providers.ibmq import IBMQ
from qiskit.providers.jobstatus import JOB_FINAL_STATES
from qiskit.utils.mitigation import CompleteMeasFitter, complete_meas_cal
def get_qpu(token, qpu_name, url='https://auth.quantum-computing.ibm.com/api', hub='ibm-q', group='open',
project='main'):
"""Load account from token. Get backend."""
try:
IBMQ.disable_account()
except:
pass
provider = IBMQ.enable_account(token=token, url=url, hub=hub, group=group, project=project)
if 'simulator' in qpu_name:
backend = Aer.get_backend('aer_simulator')
else:
backend = provider.get_backend(qpu_name)
return backend
def delete_token():
"""Delete account."""
IBMQ.delete_account()
def execute_job(transpiled_circuits, shots, backend, noise_model):
"""Generate qObject from transpiled circuit and execute it. Return result."""
try:
job = backend.run(assemble(transpiled_circuits, shots=shots), noise_model=noise_model)
job_status = job.status()
while job_status not in JOB_FINAL_STATES:
print("The job is still running")
job_status = job.status()
job_result = job.result()
print("\nJob result:")
print(job_result)
job_result_dict = job_result.to_dict()
print(job_result_dict)
try:
statevector = job_result.get_statevector()
print("\nState vector:")
print(statevector)
except QiskitError:
statevector = None
print("No statevector available!")
try:
counts = job_result.get_counts()
print("\nCounts:")
print(counts)
except QiskitError:
counts = None
print("No counts available!")
try:
unitary = job_result.get_unitary()
print("\nUnitary:")
print(unitary)
except QiskitError:
unitary = None
print("No unitary available!")
return {'job_result_raw': job_result_dict, 'statevector': statevector, 'counts': counts, 'unitary': unitary}
except (JobError, JobTimeoutError):
return None
def get_meas_fitter(token, qpu_name, shots):
"""Execute the calibration circuits on the given backend and calculate resulting matrix."""
print("Starting calculation of calibration matrix for QPU: ", qpu_name)
backend = get_qpu(token, qpu_name)
# Generate a calibration circuit for each state
qr = QuantumRegister(len(backend.properties().qubits))
meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal')
# Execute each calibration circuit and store results
print('Executing ' + str(len(meas_calibs)) + ' circuits to create calibration matrix...')
cal_results = []
for circuit in meas_calibs:
print('Executing circuit ' + circuit.name)
cal_results.append(execute_calibration_circuit(circuit, shots, backend))
# Generate calibration matrix out of measurement results
meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal')
return meas_fitter.filter
def execute_calibration_circuit(circuit, shots, backend):
"""Execute a calibration circuit on the specified backend"""
job = execute(circuit, backend=backend, shots=shots)
job_status = job.status()
while job_status not in JOB_FINAL_STATES:
print('The execution is still running')
sleep(20)
job_status = job.status()
return job.result()
|
https://github.com/UST-QuAntiL/qiskit-service
|
UST-QuAntiL
|
# ******************************************************************************
# Copyright (c) 2020-2021 University of Stuttgart
#
# See the NOTICE file(s) distributed with this work for additional
# information regarding copyright ownership.
#
# 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 os
import shutil
import sys
import tempfile
import urllib.parse
from http.client import HTTPResponse
from importlib import reload
from urllib import request, error
import qiskit
from flask import abort
from app import app
def prepare_code_from_data(data, input_params):
"""Get implementation code from data. Set input parameters into implementation. Return circuit."""
temp_dir = tempfile.mkdtemp()
with open(os.path.join(temp_dir, "__init__.py"), "w") as f:
f.write("")
with open(os.path.join(temp_dir, "downloaded_code.py"), "w") as f:
f.write(data)
sys.path.append(temp_dir)
try:
import downloaded_code
# deletes every attribute from downloaded_code, except __name__, because importlib.reload
# doesn't reset the module's global variables
for attr in dir(downloaded_code):
if attr != "__name__":
delattr(downloaded_code, attr)
reload(downloaded_code)
if 'get_circuit' in dir(downloaded_code):
circuit = downloaded_code.get_circuit(**input_params)
elif 'qc' in dir(downloaded_code):
circuit = downloaded_code.qc
finally:
sys.path.remove(temp_dir)
shutil.rmtree(temp_dir, ignore_errors=True)
if not circuit:
raise ValueError
return circuit
def prepare_code_from_url(url, input_params, bearer_token: str = "", post_processing=False):
"""Get implementation code from URL. Set input parameters into implementation. Return circuit."""
try:
impl = _download_code(url, bearer_token)
except (error.HTTPError, error.URLError):
return None
if not post_processing:
circuit = prepare_code_from_data(impl, input_params)
return circuit
else:
result = prepare_post_processing_code_from_data(impl, input_params)
return result
def prepare_code_from_qasm(qasm):
return qiskit.QuantumCircuit.from_qasm_str(qasm)
def prepare_code_from_qasm_url(url, bearer_token: str = ""):
"""Get implementation code from URL. Set input parameters into implementation. Return circuit."""
try:
impl = _download_code(url, bearer_token)
except (error.HTTPError, error.URLError):
return None
return prepare_code_from_qasm(impl)
def prepare_post_processing_code_from_data(data, input_params):
"""Get implementation code from data. Set input parameters into implementation. Return circuit."""
temp_dir = tempfile.mkdtemp()
with open(os.path.join(temp_dir, "__init__.py"), "w") as f:
f.write("")
with open(os.path.join(temp_dir, "downloaded_code.py"), "w") as f:
f.write(data)
sys.path.append(temp_dir)
try:
import downloaded_code
# deletes every attribute from downloaded_code, except __name__, because importlib.reload
# doesn't reset the module's global variables
for attr in dir(downloaded_code):
if attr != "__name__":
delattr(downloaded_code, attr)
reload(downloaded_code)
if 'post_processing' in dir(downloaded_code):
result = downloaded_code.post_processing(**input_params)
finally:
sys.path.remove(temp_dir)
shutil.rmtree(temp_dir, ignore_errors=True)
if not result:
raise ValueError
return result
def _download_code(url: str, bearer_token: str = "") -> str:
req = request.Request(url)
if urllib.parse.urlparse(url).netloc == "platform.planqk.de":
if bearer_token == "":
app.logger.error("No bearer token specified, download from the PlanQK platform will fail.")
abort(401)
elif bearer_token.startswith("Bearer"):
app.logger.error("The bearer token MUST NOT start with \"Bearer\".")
abort(401)
req.add_header("Authorization", "Bearer " + bearer_token)
try:
res: HTTPResponse = request.urlopen(req)
except Exception as e:
app.logger.error("Could not open url: " + str(e))
if str(e).find("401") != -1:
abort(401)
if res.getcode() == 200 and urllib.parse.urlparse(url).netloc == "platform.planqk.de":
app.logger.info("Request to platform.planqk.de was executed successfully.")
if res.getcode() == 401:
abort(401)
return res.read().decode("utf-8")
|
https://github.com/UST-QuAntiL/qiskit-service
|
UST-QuAntiL
|
# ******************************************************************************
# Copyright (c) 2023 University of Stuttgart
#
# See the NOTICE file(s) distributed with this work for additional
# information regarding copyright ownership.
#
# 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.
# ******************************************************************************
from qiskit import QiskitError
from qiskit.providers.jobstatus import JOB_FINAL_STATES
from qiskit_ionq import IonQProvider
def get_qpu(token, qpu_name):
provider = IonQProvider(token)
if "simulator" not in qpu_name:
qpu_name = qpu_name.replace(" ", "-").lower()
ionq_signature = "ionq_qpu."
qpu_name = ionq_signature + qpu_name
return provider.get_backend(qpu_name)
def execute_job(transpiled_circuit, shots, backend):
"""Generate qObject from transpiled circuit and execute it. Return result."""
try:
job = backend.run(transpiled_circuit, shots=shots)
job_status = job.status()
while job_status not in JOB_FINAL_STATES:
print("The job is still running")
job_status = job.status()
job_result = job.result()
print("\nJob result:")
print(job_result)
job_result_dict = job_result.to_dict()
print(job_result_dict)
try:
statevector = job_result.get_statevector()
print("\nState vector:")
print(statevector)
except QiskitError:
statevector = None
print("No statevector available!")
try:
counts = job_result.get_counts()
print("\nCounts:")
print(counts)
except QiskitError:
counts = None
print("No counts available!")
try:
unitary = job_result.get_unitary()
print("\nUnitary:")
print(unitary)
except QiskitError:
unitary = None
print("No unitary available!")
return {'job_result_raw': job_result_dict, 'statevector': statevector, 'counts': counts, 'unitary': unitary}
except Exception:
return None
|
https://github.com/UST-QuAntiL/qiskit-service
|
UST-QuAntiL
|
# ******************************************************************************
# Copyright (c) 2024 University of Stuttgart
#
# See the NOTICE file(s) distributed with this work for additional
# information regarding copyright ownership.
#
# 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 base64
import json
from flask import jsonify, abort, request
from qiskit import transpile
from qiskit.providers.ibmq import IBMQAccountError
from qiskit.transpiler.exceptions import TranspilerError
from app import app, benchmarking, aws_handler, ibmq_handler, implementation_handler, db, parameters, circuit_analysis, \
analysis, ionq_handler
from app.benchmark_model import Benchmark
from app.generated_circuit_model import Generated_Circuit
from app.qpu_metrics import generate_deterministic_uuid, get_all_qpus_and_metrics_as_json_str
from app.result_model import Result
@app.route('/qiskit-service/api/v1.0/generate-circuit', methods=['POST'])
def generate_circuit():
if not request.json:
abort(400)
impl_language = request.json.get('impl-language', '')
impl_url = request.json.get('impl-url', "")
input_params = request.json.get('input-params', "")
bearer_token = request.json.get("bearer-token", "")
impl_data = ''
if input_params:
input_params = parameters.ParameterDictionary(input_params)
if impl_url is not None and impl_url != "":
impl_url = request.json['impl-url']
elif 'impl-data' in request.json:
impl_data = base64.b64decode(request.json.get('impl-data').encode()).decode()
else:
abort(400)
job = app.implementation_queue.enqueue('app.tasks.generate', impl_url=impl_url, impl_data=impl_data,
impl_language=impl_language, input_params=input_params,
bearer_token=bearer_token)
result = Generated_Circuit(id=job.get_id())
db.session.add(result)
db.session.commit()
app.logger.info('Returning HTTP response to client...')
content_location = '/qiskit-service/api/v1.0/generated-circuits/' + result.id
response = jsonify({'Location': content_location})
response.status_code = 202
response.headers['Location'] = content_location
response.autocorrect_location_header = True
return response
@app.route('/qiskit-service/api/v1.0/generated-circuits/<generated_circuit_id>', methods=['GET'])
def get_generated_circuit(generated_circuit_id):
"""Return result when it is available."""
generated_circuit = Generated_Circuit.query.get(generated_circuit_id)
if generated_circuit.complete:
input_params_dict = json.loads(generated_circuit.input_params)
return jsonify(
{'id': generated_circuit.id, 'complete': generated_circuit.complete, 'input_params': input_params_dict,
'generated-circuit': generated_circuit.generated_circuit,
'original-depth': generated_circuit.original_depth, 'original-width': generated_circuit.original_width,
'original-total-number-of-operations': generated_circuit.original_total_number_of_operations,
'original-number-of-multi-qubit-gates': generated_circuit.original_number_of_multi_qubit_gates,
'original-number-of-measurement-operations': generated_circuit.original_number_of_measurement_operations,
'original-number-of-single-qubit-gates': generated_circuit.original_number_of_single_qubit_gates,
'original-multi-qubit-gate-depth': generated_circuit.original_multi_qubit_gate_depth}), 200
else:
return jsonify({'id': generated_circuit.id, 'complete': generated_circuit.complete}), 200
@app.route('/qiskit-service/api/v1.0/transpile', methods=['POST'])
def transpile_circuit():
"""Get implementation from URL. Pass input into implementation. Generate and transpile circuit
and return depth and width."""
if not request.json or not 'qpu-name' in request.json:
abort(400)
# Default value is ibmq for services that do not support multiple providers and expect the IBMQ provider
provider = request.json.get('provider', 'ibmq')
qpu_name = request.json['qpu-name']
impl_language = request.json.get('impl-language', '')
input_params = request.json.get('input-params', "")
impl_url = request.json.get('impl-url', "")
bearer_token = request.json.get("bearer-token", "")
if input_params:
input_params = parameters.ParameterDictionary(input_params)
if provider == 'ibmq' or provider == 'ionq':
if 'token' in input_params:
token = input_params['token']
elif 'token' in request.json:
token = request.json.get('token')
else:
abort(400)
elif provider == 'aws':
if 'aws-access-key-id' in input_params and 'aws-secret-access-key' in input_params:
aws_access_key_id = input_params['aws-access-key-id']
aws_secret_access_key = input_params['aws-secret-access-key']
elif 'aws-access-key-id' in request.json and 'aws-secret-access-key' in request.json:
aws_access_key_id = request.json.get('aws-access-key-id')
aws_secret_access_key = request.json.get('aws-secret-access-key')
else:
abort(400)
if impl_url is not None and impl_url != "":
impl_url = request.json['impl-url']
if impl_language.lower() == 'openqasm':
short_impl_name = 'no name'
circuit = implementation_handler.prepare_code_from_qasm_url(impl_url, bearer_token)
else:
short_impl_name = "untitled"
try:
circuit = implementation_handler.prepare_code_from_url(impl_url, input_params, bearer_token)
except ValueError:
abort(400)
elif 'impl-data' in request.json:
impl_data = base64.b64decode(request.json.get('impl-data').encode()).decode()
short_impl_name = 'no short name'
if impl_language.lower() == 'openqasm':
circuit = implementation_handler.prepare_code_from_qasm(impl_data)
else:
try:
circuit = implementation_handler.prepare_code_from_data(impl_data, input_params)
except ValueError:
abort(400)
elif 'qasm-string' in request.json:
short_impl_name = 'no short name'
app.logger.info(request.json.get('qasm-string'))
circuit = implementation_handler.prepare_code_from_qasm(request.json.get('qasm-string'))
else:
abort(400)
try:
non_transpiled_depth_old = 0
non_transpiled_depth = circuit.depth()
while non_transpiled_depth_old < non_transpiled_depth:
non_transpiled_depth_old = non_transpiled_depth
circuit = circuit.decompose()
non_transpiled_depth = circuit.depth()
non_transpiled_width = circuit_analysis.get_width_of_circuit(circuit)
non_transpiled_total_number_of_operations = circuit.size()
non_transpiled_number_of_multi_qubit_gates = circuit.num_nonlocal_gates()
non_transpiled_number_of_measurement_operations = circuit_analysis.get_number_of_measurement_operations(circuit)
non_transpiled_number_of_single_qubit_gates = non_transpiled_total_number_of_operations - non_transpiled_number_of_multi_qubit_gates - non_transpiled_number_of_measurement_operations
non_transpiled_multi_qubit_gate_depth, non_transpiled_circuit = circuit_analysis.get_multi_qubit_gate_depth(
circuit.copy())
print(f"Non transpiled width {non_transpiled_width} & non transpiled depth {non_transpiled_depth}")
if not circuit:
app.logger.warn(f"{short_impl_name} not found.")
abort(404)
except Exception as e:
app.logger.info(f"Transpile {short_impl_name} for {qpu_name}: {str(e)}")
return jsonify({'error': str(e)}), 200
backend = None
credentials = {}
if provider == 'ibmq':
if 'url' in input_params:
credentials['url'] = input_params['url']
if 'hub' in input_params:
credentials['hub'] = input_params['hub']
if 'group' in input_params:
credentials['group'] = input_params['group']
if 'project' in input_params:
credentials['project'] = input_params['project']
backend = ibmq_handler.get_qpu(token, qpu_name, **credentials)
elif provider == 'ionq':
backend = ionq_handler.get_qpu(token, qpu_name)
elif provider == 'aws':
if 'region' in input_params:
credentials['region'] = input_params['region']
backend = aws_handler.get_qpu(access_key=aws_access_key_id, secret_access_key=aws_secret_access_key,
qpu_name=qpu_name, **credentials)
if not backend:
app.logger.warn(f"{qpu_name} not found.")
abort(404)
try:
if provider == 'aws':
transpiled_circuit = transpile(circuit, backend=backend)
else:
transpiled_circuit = transpile(circuit, backend=backend, optimization_level=3)
width = circuit_analysis.get_width_of_circuit(transpiled_circuit)
depth = transpiled_circuit.depth()
total_number_of_operations = transpiled_circuit.size()
number_of_multi_qubit_gates = transpiled_circuit.num_nonlocal_gates()
number_of_measurement_operations = circuit_analysis.get_number_of_measurement_operations(transpiled_circuit)
number_of_single_qubit_gates = total_number_of_operations - number_of_multi_qubit_gates - number_of_measurement_operations
multi_qubit_gate_depth, transpiled_circuit = circuit_analysis.get_multi_qubit_gate_depth(transpiled_circuit)
except TranspilerError:
app.logger.info(f"Transpile {short_impl_name} for {qpu_name}: too many qubits required")
return jsonify({'error': 'too many qubits required'}), 200
app.logger.info(f"Transpile {short_impl_name} for {qpu_name}: w={width}, "
f"d={depth}, "
f"multi qubit gate depth={multi_qubit_gate_depth}, "
f"total number of operations={total_number_of_operations}, "
f"number of single qubit gates={number_of_single_qubit_gates}, "
f"number of multi qubit gates={number_of_multi_qubit_gates}, "
f"number of measurement operations={number_of_measurement_operations}")
return jsonify({'original-depth': non_transpiled_depth, 'original-width': non_transpiled_width,
'original-total-number-of-operations': non_transpiled_total_number_of_operations,
'original-number-of-multi-qubit-gates': non_transpiled_number_of_multi_qubit_gates,
'original-number-of-measurement-operations': non_transpiled_number_of_measurement_operations,
'original-number-of-single-qubit-gates': non_transpiled_number_of_single_qubit_gates,
'original-multi-qubit-gate-depth': non_transpiled_multi_qubit_gate_depth, 'depth': depth,
'multi-qubit-gate-depth': multi_qubit_gate_depth, 'width': width,
'total-number-of-operations': total_number_of_operations,
'number-of-single-qubit-gates': number_of_single_qubit_gates,
'number-of-multi-qubit-gates': number_of_multi_qubit_gates,
'number-of-measurement-operations': number_of_measurement_operations,
'transpiled-qasm': transpiled_circuit.qasm()}), 200
@app.route('/qiskit-service/api/v1.0/analyze-original-circuit', methods=['POST'])
def analyze_original_circuit():
if not request.json:
abort(400)
impl_language = request.json.get('impl-language', '')
impl_url = request.json.get('impl-url', "")
input_params = request.json.get('input-params', "")
bearer_token = request.json.get("bearer-token", "")
if input_params:
input_params = parameters.ParameterDictionary(input_params)
if impl_url is not None and impl_url != "":
impl_url = request.json['impl-url']
if impl_language.lower() == 'openqasm':
short_impl_name = 'no name'
circuit = implementation_handler.prepare_code_from_qasm_url(impl_url, bearer_token)
else:
short_impl_name = "untitled"
try:
circuit = implementation_handler.prepare_code_from_url(impl_url, input_params, bearer_token)
except ValueError:
abort(400)
elif 'impl-data' in request.json:
impl_data = base64.b64decode(request.json.get('impl-data').encode()).decode()
short_impl_name = 'no short name'
if impl_language.lower() == 'openqasm':
circuit = implementation_handler.prepare_code_from_qasm(impl_data)
else:
try:
circuit = implementation_handler.prepare_code_from_data(impl_data, input_params)
except ValueError:
abort(400)
elif 'qasm-string' in request.json:
short_impl_name = 'no short name'
app.logger.info(request.json.get('qasm-string'))
circuit = implementation_handler.prepare_code_from_qasm(request.json.get('qasm-string'))
else:
abort(400)
try:
non_transpiled_depth_old = 0
non_transpiled_depth = circuit.depth()
while non_transpiled_depth_old < non_transpiled_depth:
non_transpiled_depth_old = non_transpiled_depth
circuit = circuit.decompose()
non_transpiled_depth = circuit.depth()
non_transpiled_width = circuit_analysis.get_width_of_circuit(circuit)
non_transpiled_total_number_of_operations = circuit.size()
non_transpiled_number_of_multi_qubit_gates = circuit.num_nonlocal_gates()
non_transpiled_number_of_measurement_operations = circuit_analysis.get_number_of_measurement_operations(circuit)
non_transpiled_number_of_single_qubit_gates = non_transpiled_total_number_of_operations - non_transpiled_number_of_multi_qubit_gates - non_transpiled_number_of_measurement_operations
non_transpiled_multi_qubit_gate_depth, non_transpiled_circuit = circuit_analysis.get_multi_qubit_gate_depth(
circuit)
print(f"Non transpiled width {non_transpiled_width} & non transpiled depth {non_transpiled_depth}")
if not circuit:
app.logger.warn(f"{short_impl_name} not found.")
abort(404)
except Exception as e:
return jsonify({'error': str(e)}), 200
return jsonify({'original-depth': non_transpiled_depth, 'original-width': non_transpiled_width,
'original-total-number-of-operations': non_transpiled_total_number_of_operations,
'original-number-of-multi-qubit-gates': non_transpiled_number_of_multi_qubit_gates,
'original-number-of-measurement-operations': non_transpiled_number_of_measurement_operations,
'original-number-of-single-qubit-gates': non_transpiled_number_of_single_qubit_gates,
'original-multi-qubit-gate-depth': non_transpiled_multi_qubit_gate_depth}), 200
@app.route('/qiskit-service/api/v1.0/execute', methods=['POST'])
def execute_circuit():
"""Put execution jobs in queue. Return location of the later results."""
if not request.json or not 'qpu-name' in request.json:
abort(400)
# Default value is ibmq for services that do not support multiple providers and expect the IBMQ provider
provider = request.json.get('provider', 'ibmq')
correlation_id = request.json.get('correlation-id', None)
qpu_name = request.json['qpu-name']
impl_language = request.json.get('impl-language', '')
impl_url = request.json.get('impl-url')
if type(impl_url) is str:
impl_url = [impl_url]
impl_data = request.json.get('impl-data')
if type(impl_data) is str:
impl_data = [impl_data]
qasm_string = request.json.get('qasm-string')
if type(qasm_string) is str:
qasm_string = [qasm_string]
transpiled_qasm = request.json.get('transpiled-qasm')
if type(transpiled_qasm) is str:
transpiled_qasm = [transpiled_qasm]
bearer_token = request.json.get("bearer-token", "")
input_params = request.json.get('input-params', "")
noise_model = request.json.get("noise-model")
only_measurement_errors = request.json.get("only-measurement-errors")
optimization_level = request.json.get('transpilation-optimization-level', 3)
if input_params:
input_params = parameters.ParameterDictionary(input_params)
token = ''
aws_access_key_id = ''
aws_secret_access_key = ''
if provider == 'ibmq' or provider == 'ionq':
if 'token' in input_params:
token = input_params['token']
elif 'token' in request.json:
token = request.json.get('token')
else:
abort(400)
elif provider == 'aws':
if 'aws-access-key-id' in input_params and 'aws-secret-access-key' in input_params:
aws_access_key_id = input_params['aws-access-key-id']
aws_secret_access_key = input_params['aws-secret-access-key']
elif 'aws-access-key-id' in request.json and 'aws-secret-access-key' in request.json:
aws_access_key_id = request.json.get('aws-access-key-id')
aws_secret_access_key = request.json.get('aws-secret-access-key')
else:
abort(400)
# Check parameters required for using premium accounts, de.imbq and reservations
credentials = {}
if provider == 'ibmq':
if 'url' in input_params:
credentials['url'] = input_params['url']
if 'hub' in input_params:
credentials['hub'] = input_params['hub']
if 'group' in input_params:
credentials['group'] = input_params['group']
if 'project' in input_params:
credentials['project'] = input_params['project']
elif provider == 'aws':
if 'region' in input_params:
credentials['region'] = input_params['region']
shots = request.json.get('shots', 1024)
job = app.execute_queue.enqueue('app.tasks.execute', correlation_id=correlation_id, provider=provider,
impl_url=impl_url, impl_data=impl_data, impl_language=impl_language,
transpiled_qasm=transpiled_qasm, qpu_name=qpu_name, token=token,
access_key_aws=aws_access_key_id, secret_access_key_aws=aws_secret_access_key,
input_params=input_params, noise_model=noise_model,
only_measurement_errors=only_measurement_errors,
optimization_level=optimization_level, shots=shots, bearer_token=bearer_token,
qasm_string=qasm_string, **credentials)
result = Result(id=job.get_id(), backend=qpu_name, shots=shots)
db.session.add(result)
db.session.commit()
app.logger.info('Returning HTTP response to client...')
content_location = '/qiskit-service/api/v1.0/results/' + result.id
response = jsonify({'Location': content_location})
response.status_code = 202
response.headers['Location'] = content_location
response.autocorrect_location_header = True
return response
@app.route('/qiskit-service/api/v1.0/calculate-calibration-matrix', methods=['POST'])
def calculate_calibration_matrix():
"""Put calibration matrix calculation job in queue. Return location of the later result."""
if not request.json or not 'qpu-name' in request.json or not 'token' in request.json:
abort(400)
qpu_name = request.json['qpu-name']
token = request.json['token']
shots = request.json.get('shots', 8192)
job = app.execute_queue.enqueue('app.tasks.calculate_calibration_matrix', qpu_name=qpu_name, token=token,
shots=shots)
result = Result(id=job.get_id())
db.session.add(result)
db.session.commit()
app.logger.info('Returning HTTP response to client...')
content_location = '/qiskit-service/api/v1.0/results/' + result.id
response = jsonify({'Location': content_location})
response.status_code = 202
response.headers['Location'] = content_location
response.autocorrect_location_header = True
return response
@app.route('/qiskit-service/api/v1.0/calc-wd/<qpu_name>', methods=['GET'])
def calc_wd(qpu_name):
"""calculates wd-value of a given Quantum Computer based on the clifford data in your database and returns it"""
wd = benchmarking.calc_wd(qpu_name)
return jsonify(wd)
# TODO: after Qiskit ignis is deprecated, the generation of Clifford gate circuits has to be adapted
@app.route('/qiskit-service/api/v1.0/randomize', methods=['POST'])
def randomize():
# """Create randomized circuits of given properties to run benchmarks and return locations to their results"""
# if not request.json:
# abort(400)
#
# qpu_name = request.json['qpu-name']
# num_of_qubits = request.json['number-of-qubits']
# min_depth_of_circuit = request.json['min-depth-of-circuit']
# max_depth_of_circuit = request.json['max-depth-of-circuit']
# num_of_circuits = request.json['number-of-circuits']
# clifford = request.json.get('clifford', False)
# shots = request.json.get('shots', 1024)
# token = request.json['token']
#
# locations = benchmarking.randomize(qpu_name=qpu_name, num_of_qubits=num_of_qubits, shots=shots,
# min_depth_of_circuit=min_depth_of_circuit,
# max_depth_of_circuit=max_depth_of_circuit, num_of_circuits=num_of_circuits,
# clifford=clifford, token=token)
#
# return jsonify(locations)
return jsonify(0)
@app.route('/qiskit-service/api/v1.0/results/<result_id>', methods=['GET'])
def get_result(result_id):
"""Return result when it is available."""
result = Result.query.get(result_id)
if result.complete:
result_dict = json.loads(result.result)
if result.post_processing_result:
post_processing_result_dict = json.loads(result.post_processing_result)
return jsonify(
{'id': result.id, 'complete': result.complete, 'result': result_dict, 'backend': result.backend,
'shots': result.shots, 'generated-circuit-id': result.generated_circuit_id,
'post-processing-result': post_processing_result_dict}), 200
else:
return jsonify(
{'id': result.id, 'complete': result.complete, 'result': result_dict, 'backend': result.backend,
'shots': result.shots}), 200
else:
return jsonify({'id': result.id, 'complete': result.complete}), 200
@app.route('/qiskit-service/api/v1.0/benchmarks/<benchmark_id>', methods=['GET'])
def get_benchmark(benchmark_id):
"""Return summary of benchmark when it is available. Includes result of both simulator and quantum computer if
available """
benchmark_sim = None
benchmark_real = None
# get the simulator's and quantum computer's result from the db
i = 1 # for testing simulator can be benchmarked
for benchmark in Benchmark.query.filter(Benchmark.benchmark_id == benchmark_id):
if benchmark.backend == 'ibmq_qasm_simulator' and i > 0:
benchmark_sim = benchmark
i = i - 1
else:
benchmark_real = benchmark
# check which backend has finished execution and adapt response to that
if (benchmark_sim is not None) and (benchmark_real is not None):
if benchmark_sim.complete and benchmark_real.complete:
if benchmark_sim.result == "" or benchmark_real.result == "":
# one backend failed during the execution
return json.dumps({'error': 'execution failed'})
# both backends finished execution
return jsonify({'id': int(benchmark_id), 'benchmarking-complete': True,
'histogram-intersection': analysis.calc_intersection(
json.loads(benchmark_sim.counts).copy(), json.loads(benchmark_real.counts).copy(),
benchmark_real.shots),
'perc-error': analysis.calc_percentage_error(json.loads(benchmark_sim.counts),
json.loads(benchmark_real.counts)),
'correlation': analysis.calc_correlation(json.loads(benchmark_sim.counts).copy(),
json.loads(benchmark_real.counts).copy(),
benchmark_real.shots),
'chi-square': analysis.calc_chi_square_distance(json.loads(benchmark_sim.counts).copy(),
json.loads(benchmark_real.counts).copy()),
'benchmarking-results': [get_benchmark_body(benchmark_backend=benchmark_sim),
get_benchmark_body(benchmark_backend=benchmark_real)]}), 200
elif benchmark_sim.complete and not benchmark_real.complete:
if benchmark_sim.result == "":
# execution on simulator failed
return json.dumps({'error': 'execution failed'})
# simulator finished execution, quantum computer not yet
return jsonify({'id': int(benchmark_id), 'benchmarking-complete': False,
'benchmarking-results': [get_benchmark_body(benchmark_backend=benchmark_sim),
{'result-id': benchmark_real.id,
'complete': benchmark_real.complete}]}), 200
elif not benchmark_sim.complete and benchmark_real.complete:
if benchmark_real.result == "":
# execution on quantum computer failed
return json.dumps({'error': 'execution failed'})
# quantum computer finished execution, simulator not yet
return jsonify({'id': int(benchmark_id), 'benchmarking-complete': False, 'benchmarking-results': [
{'result-id': benchmark_sim.id, 'complete': benchmark_sim.complete},
get_benchmark_body(benchmark_backend=benchmark_real)]}), 200
else:
# both backends did not finish execution yet
return jsonify({'id': int(benchmark_id), 'benchmarking-complete': False, 'benchmarking-results': [
{'result-id': benchmark_sim.id, 'complete': benchmark_sim.complete},
{'result-id': benchmark_real.id, 'complete': benchmark_real.complete}]}), 200
else:
abort(404)
@app.route('/qiskit-service/api/v1.0/providers', methods=['GET'])
def get_providers():
"""Return available providers."""
return jsonify({"_embedded": {"providerDtoes": [
{"id": str(generate_deterministic_uuid("ibmq", "provider")), "name": "ibmq",
"offeringURL": "https://quantum-computing.ibm.com/", },
{"id": str(generate_deterministic_uuid("aws", "provider")), "name": "aws",
"offeringURL": "https://aws.amazon.com/braket/", }]}}), 200
@app.route('/qiskit-service/api/v1.0/providers/<provider_id>/qpus', methods=['GET'])
def get_qpus_and_metrics_of_provider(provider_id: str):
"""Return qpus and metrics of the specified provider."""
if 'token' not in request.headers:
return jsonify({"message": "Error: token missing in request"}), 401
token = request.headers.get('token')
if provider_id == str(generate_deterministic_uuid("ibmq", "provider")):
try:
return get_all_qpus_and_metrics_as_json_str(token), 200
except IBMQAccountError:
return jsonify({"message": "the provided token is wrong"}), 401
else:
return jsonify({"message": "Error: unknown provider ID."}), 400
@app.route('/qiskit-service/api/v1.0/analysis', methods=['GET'])
def get_analysis():
"""Return analysis of all benchmarks saved in the database"""
return jsonify(benchmarking.analyse())
@app.route('/qiskit-service/api/v1.0/analysis/<qpu_name>', methods=['GET'])
def get_analysis_qpu(qpu_name):
"""Return analysis of all benchmarks from a specific quantum computer saved in the database"""
benchmarks = Benchmark.query.all()
list = []
for i in range(0, len(benchmarks), 2):
if (benchmarks[i].complete and benchmarks[i + 1].complete) and (
benchmarks[i].benchmark_id == benchmarks[i + 1].benchmark_id) and (
benchmarks[i].result != "" and benchmarks[i + 1].result != "") and (
benchmarks[i + 1].backend == qpu_name):
counts_sim = json.loads(benchmarks[i].counts)
counts_real = json.loads(benchmarks[i + 1].counts)
shots = benchmarks[i + 1].shots
perc_error = analysis.calc_percentage_error(counts_sim, counts_real)
correlation = analysis.calc_correlation(counts_sim.copy(), counts_real.copy(), shots)
chi_square = analysis.calc_chi_square_distance(counts_sim.copy(), counts_real.copy())
intersection = analysis.calc_intersection(counts_sim.copy(), counts_real.copy(), shots)
list.append({'benchmark-' + str(benchmarks[i].benchmark_id): {
'benchmark-location': '/qiskit-service/api/v1.0/benchmarks/' + str(benchmarks[i].benchmark_id),
'counts-sim': counts_sim, 'counts-real': counts_real, 'percentage-error': perc_error,
'chi-square': chi_square, 'correlation': correlation, 'histogram-intersection': intersection}})
return jsonify(list)
@app.route('/qiskit-service/api/v1.0/version', methods=['GET'])
def version():
return jsonify({'version': '1.0'})
def get_benchmark_body(benchmark_backend):
return {'result-id': benchmark_backend.id,
'result-location': '/qiskit-service/api/v1.0/results/' + benchmark_backend.id,
'backend': benchmark_backend.backend, 'counts': json.loads(benchmark_backend.counts),
'original-depth': benchmark_backend.original_depth, 'original-width': benchmark_backend.original_width,
'original-number-of-multi-qubit-gates': benchmark_backend.original_number_of_multi_qubit_gates,
'transpiled-depth': benchmark_backend.transpiled_depth,
'transpiled-width': benchmark_backend.transpiled_width,
'transpiled-number-of-multi-qubit-gates': benchmark_backend.transpiled_number_of_multi_qubit_gates,
'clifford': benchmark_backend.clifford, 'benchmark-id': benchmark_backend.benchmark_id,
'complete': benchmark_backend.complete, 'shots': benchmark_backend.shots}
|
https://github.com/UST-QuAntiL/qiskit-service
|
UST-QuAntiL
|
# ******************************************************************************
# Copyright (c) 2020-2021 University of Stuttgart
#
# See the NOTICE file(s) distributed with this work for additional
# information regarding copyright ownership.
#
# 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 base64
import datetime
import json
from qiskit import transpile, QuantumCircuit, Aer
from qiskit.transpiler.exceptions import TranspilerError
from qiskit.utils.measurement_error_mitigation import get_measured_qubits
from qiskit_aer.noise import NoiseModel
from rq import get_current_job
from app import implementation_handler, aws_handler, ibmq_handler, db, app, ionq_handler, circuit_analysis
from app.NumpyEncoder import NumpyEncoder
from app.benchmark_model import Benchmark
from app.generated_circuit_model import Generated_Circuit
from app.result_model import Result
def generate(impl_url, impl_data, impl_language, input_params, bearer_token):
app.logger.info("Starting generate task...")
job = get_current_job()
generated_circuit_code = None
if impl_url:
generated_circuit_code = implementation_handler.prepare_code_from_url(impl_url, input_params, bearer_token)
elif impl_data:
generated_circuit_code = implementation_handler.prepare_code_from_data(impl_data, input_params)
else:
generated_circuit_object = Generated_Circuit.query.get(job.get_id())
generated_circuit_object.generated_circuit = json.dumps({'error': 'generating circuit failed'})
generated_circuit_object.complete = True
db.session.commit()
if generated_circuit_code:
non_transpiled_depth_old = 0
generated_circuit_object = Generated_Circuit.query.get(job.get_id())
generated_circuit_object.generated_circuit = generated_circuit_code.qasm()
non_transpiled_depth = generated_circuit_code.depth()
while non_transpiled_depth_old < non_transpiled_depth:
non_transpiled_depth_old = non_transpiled_depth
generated_circuit_code = generated_circuit_code.decompose()
non_transpiled_depth = generated_circuit_code.depth()
generated_circuit_object.original_depth = non_transpiled_depth
generated_circuit_object.original_width = circuit_analysis.get_width_of_circuit(generated_circuit_code)
generated_circuit_object.original_total_number_of_operations = generated_circuit_code.size()
generated_circuit_object.original_number_of_multi_qubit_gates = generated_circuit_code.num_nonlocal_gates()
generated_circuit_object.original_number_of_measurement_operations = circuit_analysis.get_number_of_measurement_operations(
generated_circuit_code)
generated_circuit_object.original_number_of_single_qubit_gates = generated_circuit_object.original_total_number_of_operations - generated_circuit_object.original_number_of_multi_qubit_gates - generated_circuit_object.original_number_of_measurement_operations
generated_circuit_object.original_multi_qubit_gate_depth, non_transpiled_circuit = circuit_analysis.get_multi_qubit_gate_depth(
generated_circuit_code)
generated_circuit_object.input_params = json.dumps(input_params)
app.logger.info(f"Received input params for circuit generation: {generated_circuit_object.input_params}")
generated_circuit_object.complete = True
db.session.commit()
def execute(correlation_id, provider, impl_url, impl_data, impl_language, transpiled_qasm, input_params, token,
access_key_aws, secret_access_key_aws, qpu_name, optimization_level, noise_model, only_measurement_errors,
shots, bearer_token, qasm_string, **kwargs):
"""Create database entry for result. Get implementation code, prepare it, and execute it. Save result in db"""
app.logger.info("Starting execute task...")
job = get_current_job()
if provider == 'ibmq':
backend = ibmq_handler.get_qpu(token, qpu_name, **kwargs)
elif provider == 'ionq':
backend = ionq_handler.get_qpu(token, qpu_name)
elif provider == 'aws':
backend = aws_handler.get_qpu(access_key=access_key_aws, secret_access_key=secret_access_key_aws,
qpu_name=qpu_name, **kwargs)
if not backend:
result = Result.query.get(job.get_id())
result.result = json.dumps({'error': 'qpu-name or token wrong'})
result.complete = True
db.session.commit()
app.logger.info('Preparing implementation...')
if transpiled_qasm:
transpiled_circuits = [QuantumCircuit.from_qasm_str(qasm) for qasm in transpiled_qasm]
else:
if qasm_string:
circuits = [implementation_handler.prepare_code_from_qasm(qasm) for qasm in qasm_string]
elif impl_url and not correlation_id:
if impl_language.lower() == 'openqasm':
# list of circuits
circuits = [implementation_handler.prepare_code_from_qasm_url(url, bearer_token) for url in impl_url]
else:
circuits = [implementation_handler.prepare_code_from_url(url, input_params, bearer_token) for url in
impl_url]
elif impl_data:
impl_data = [base64.b64decode(data.encode()).decode() for data in impl_data]
if impl_language.lower() == 'openqasm':
circuits = [implementation_handler.prepare_code_from_qasm(data) for data in impl_data]
else:
circuits = [implementation_handler.prepare_code_from_data(data, input_params) for data in impl_data]
if not circuits:
result = Result.query.get(job.get_id())
result.result = json.dumps({'error': 'URL not found'})
result.complete = True
db.session.commit()
app.logger.info('Start transpiling...')
if noise_model and provider == 'ibmq':
noisy_qpu = ibmq_handler.get_qpu(token, noise_model, **kwargs)
noise_model = NoiseModel.from_backend(noisy_qpu)
properties = noisy_qpu.properties()
configuration = noisy_qpu.configuration()
coupling_map = configuration.coupling_map
basis_gates = noise_model.basis_gates
try:
transpiled_circuits = transpile(circuits, noisy_qpu)
except TranspilerError:
result = Result.query.get(job.get_id())
result.result = json.dumps({'error': 'too many qubits required'})
result.complete = True
db.session.commit()
measurement_qubits = get_measurement_qubits_from_transpiled_circuit(transpiled_circuits)
if only_measurement_errors:
ro_noise_model = NoiseModel()
for k, v in noise_model._local_readout_errors.items():
ro_noise_model.add_readout_error(v, k)
noise_model = ro_noise_model
backend = Aer.get_backend('aer_simulator')
else:
try:
transpiled_circuits = transpile(circuits, backend=backend, optimization_level=optimization_level)
except TranspilerError:
result = Result.query.get(job.get_id())
result.result = json.dumps({'error': 'too many qubits required'})
result.complete = True
db.session.commit()
app.logger.info('Start executing...')
if provider == 'aws' and not noise_model:
# Note: AWS cannot handle such a noise model
job_result = aws_handler.execute_job(transpiled_circuits, shots, backend)
elif provider == 'ionq' and not noise_model:
job_result = ionq_handler.execute_job(transpiled_circuits, shots, backend)
else:
# If we need a noise model, we have to use IBM Q
job_result = ibmq_handler.execute_job(transpiled_circuits, shots, backend, noise_model)
if job_result:
result = Result.query.get(job.get_id())
result.result = json.dumps(job_result['counts'])
# check if implementation contains post processing of execution results that has to be executed
if correlation_id and (impl_url or impl_data):
result.generated_circuit_id = correlation_id
# prepare input data containing execution results and initial input params for generating the circuit
generated_circuit = Generated_Circuit.query.get(correlation_id)
input_params_for_post_processing = json.loads(generated_circuit.input_params)
input_params_for_post_processing['counts'] = job_result['counts']
if impl_url:
post_p_result = implementation_handler.prepare_code_from_url(url=impl_url[0],
input_params=input_params_for_post_processing,
bearer_token=bearer_token,
post_processing=True)
elif impl_data:
post_p_result = implementation_handler.prepare_post_processing_code_from_data(data=impl_data[0],
input_params=input_params_for_post_processing)
result.post_processing_result = json.loads(post_p_result)
result.complete = True
db.session.commit()
else:
result = Result.query.get(job.get_id())
result.result = json.dumps({'error': 'execution failed'})
result.complete = True
db.session.commit()
def get_measurement_qubits_from_transpiled_circuit(transpiled_circuit):
qubit_index, qubit_mappings = get_measured_qubits([transpiled_circuit])
measurement_qubits = [int(i) for i in list(qubit_mappings.keys())[0].split("_")]
return measurement_qubits
def convert_into_suitable_format(object):
"""Enables the serialization of the unserializable datetime.datetime format"""
if isinstance(object, datetime.datetime):
return object.__str__()
def execute_benchmark(transpiled_qasm, token, qpu_name, shots):
"""Create database entry for result and benchmark. Get implementation code, prepare it, and execute it. Save
result in db """
job = get_current_job()
backend = ibmq_handler.get_qpu(token, qpu_name)
if not backend:
result = Result.query.get(job.get_id())
result.result = json.dumps({'error': 'qpu-name or token wrong'})
result.complete = True
db.session.commit()
app.logger.info('Preparing implementation...')
transpiled_circuit = QuantumCircuit.from_qasm_str(transpiled_qasm)
app.logger.info('Start executing...')
job_result = ibmq_handler.execute_job(transpiled_circuit, shots, backend, None)
if job_result:
# once the job is finished save results in db
result = Result.query.get(job.get_id())
result.result = json.dumps(job_result, default=convert_into_suitable_format)
result.complete = True
benchmark = Benchmark.query.get(job.get_id())
benchmark.result = json.dumps(job_result, default=convert_into_suitable_format)
benchmark.counts = json.dumps(job_result['counts'])
benchmark.complete = True
db.session.commit()
else:
result = Result.query.get(job.get_id())
result.result = json.dumps({'error': 'execution failed'})
result.complete = True
benchmark = Benchmark.query.get(job.get_id())
benchmark.complete = True
db.session.commit()
def calculate_calibration_matrix(token, qpu_name, shots):
"""Calculate the current calibration matrix for the given QPU and save the result in db"""
job = get_current_job()
backend = ibmq_handler.get_qpu(token, qpu_name)
if backend:
job_result = ibmq_handler.get_meas_fitter(token, qpu_name, shots)
if job_result:
result = Result.query.get(job.get_id())
result.result = json.dumps({'matrix': job_result.cal_matrix}, cls=NumpyEncoder)
result.complete = True
db.session.commit()
else:
result = Result.query.get(job.get_id())
result.result = json.dumps({'error': 'matrix calculation failed'})
result.complete = True
db.session.commit()
else:
result = Result.query.get(job.get_id())
result.result = json.dumps({'error': 'qpu-name or token wrong'})
result.complete = True
db.session.commit()
|
https://github.com/UST-QuAntiL/qiskit-service
|
UST-QuAntiL
|
# ******************************************************************************
# Copyright (c) 2021 University of Stuttgart
#
# See the NOTICE file(s) distributed with this work for additional
# information regarding copyright ownership.
#
# 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 unittest
import os
from app.config import basedir
from app import app, db
import qiskit
class TranspileTestCase(unittest.TestCase):
def setUp(self):
# setup environment variables for testing
app.config['TESTING'] = True
app.config['WTF_CSRF_ENABLED'] = False
app.config['SQLALCHEMY_DATABASE_URI'] = "sqlite:///" + os.path.join(basedir, 'test.db')
self.client = app.test_client()
db.create_all()
def tearDown(self):
db.session.remove()
db.drop_all()
def test_version(self):
response = self.client.get('/qiskit-service/api/v1.0/version')
self.assertEqual(response.status_code, 200)
json_data = response.get_json()
self.assertTrue("version" in json_data)
self.assertEqual(json_data['version'], "1.0")
@unittest.skip("Has to be adapted as the benchmarking via Qiskit ignis is deprecated")
def test_randomize_full_request(self):
# prepare the request
request = {
'qpu-name': 'ibmq_qasm_simulator',
'number-of-qubits': 1,
'min-depth-of-circuit': 1,
'max-depth-of-circuit': 1,
'number-of-circuits': 1,
'clifford': False,
'shots': 1024,
'token': os.environ["QISKIT_TOKEN"]
}
# send the request
response = self.client.post('/qiskit-service/api/v1.0/randomize', json=request)
self.assertEqual(response.status_code, 200)
json_data = response.get_json()
self.assertEqual(1, len(json_data))
self.assertEqual(3, len(json_data[0]))
print(json_data[0])
self.assertIn("result-benchmark", json_data[0])
self.assertIn("result-simulator", json_data[0])
self.assertIn("result-real-backend", json_data[0])
@unittest.skip("Has to be adapted as the benchmarking via Qiskit ignis is deprecated")
def test_randomize_no_shots_request(self):
# prepare the request
request = {
'qpu-name': 'ibmq_qasm_simulator',
'number-of-qubits': 1,
'min-depth-of-circuit': 1,
'max-depth-of-circuit': 1,
'number-of-circuits': 1,
'clifford': False,
'token': os.environ["QISKIT_TOKEN"]
}
# send the request
response = self.client.post('/qiskit-service/api/v1.0/randomize', json=request)
self.assertEqual(response.status_code, 200)
json_data = response.get_json()
self.assertEqual(1, len(json_data))
self.assertEqual(3, len(json_data[0]))
self.assertIn("result-benchmark", json_data[0])
self.assertIn("result-simulator", json_data[0])
self.assertIn("result-real-backend", json_data[0])
@unittest.skip("Has to be adapted as the benchmarking via Qiskit ignis is deprecated")
def test_randomize_no_clifford_request(self):
# prepare the request
request = {
'qpu-name': 'ibmq_qasm_simulator',
'number-of-qubits': 1,
'min-depth-of-circuit': 1,
'max-depth-of-circuit': 1,
'number-of-circuits': 1,
'token': os.environ["QISKIT_TOKEN"]
}
# send the request
response = self.client.post('/qiskit-service/api/v1.0/randomize', json=request)
self.assertEqual(response.status_code, 200)
json_data = response.get_json()
self.assertEqual(1, len(json_data))
self.assertEqual(3, len(json_data[0]))
self.assertIn("result-benchmark", json_data[0])
self.assertIn("result-simulator", json_data[0])
self.assertIn("result-real-backend", json_data[0])
@unittest.skip("Has to be adapted as the benchmarking via Qiskit ignis is deprecated")
def test_randomize_clifford_full_request(self):
# prepare the request
request = {
'qpu-name': 'ibmq_qasm_simulator',
'number-of-qubits': 1,
'min-depth-of-circuit': 1,
'max-depth-of-circuit': 1,
'number-of-circuits': 1,
'clifford': True,
'token': os.environ["QISKIT_TOKEN"]
}
# send the request
response = self.client.post('/qiskit-service/api/v1.0/randomize', json=request)
self.assertEqual(response.status_code, 200)
json_data = response.get_json()
self.assertEqual(1, len(json_data))
self.assertEqual(3, len(json_data[0]))
self.assertIn("result-benchmark", json_data[0])
self.assertIn("result-simulator", json_data[0])
self.assertIn("result-real-backend", json_data[0])
if __name__ == "__main__":
unittest.main()
|
https://github.com/UST-QuAntiL/qiskit-service
|
UST-QuAntiL
|
# ******************************************************************************
# Copyright (c) 2020-2021 University of Stuttgart
#
# See the NOTICE file(s) distributed with this work for additional
# information regarding copyright ownership.
#
# 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 unittest
import os
from app.config import basedir
from app import app, db
import qiskit
import base64
from qiskit.circuit.random import random_circuit
class TranspileTestCase(unittest.TestCase):
def setUp(self):
# setup environment variables for testing
app.config['TESTING'] = True
app.config['WTF_CSRF_ENABLED'] = False
app.config['SQLALCHEMY_DATABASE_URI'] = "sqlite:///" + os.path.join(basedir, 'test.db')
self.client = app.test_client()
db.create_all()
def tearDown(self):
db.session.remove()
db.drop_all()
def test_version(self):
response = self.client.get('/qiskit-service/api/v1.0/version')
self.assertEqual(response.status_code, 200)
json_data = response.get_json()
self.assertTrue("version" in json_data)
self.assertEqual(json_data['version'], "1.0")
def test_transpile_hadamard_simulator_url(self):
# prepare the request
request = {
'impl-url': "https://raw.githubusercontent.com/PlanQK/qiskit-service/master/test/data/hadamard.py",
'impl-language': 'Qiskit',
'qpu-name': "ibmq_qasm_simulator",
'input-params': {},
'token': os.environ["QISKIT_TOKEN"]
}
# send the request
response = self.client.post('/qiskit-service/api/v1.0/transpile',
json=request)
self.assertEqual(response.status_code, 200)
json_data = response.get_json()
self.assertIn("width", json_data)
self.assertIn("depth", json_data)
self.assertIsNotNone(json_data['depth'])
self.assertIsNotNone(json_data['width'])
self.assertIn('transpiled-qasm', json_data)
self.assertIn("total-number-of-operations", json_data)
self.assertIn("number-of-multi-qubit-gates", json_data)
self.assertIn("multi-qubit-gate-depth", json_data)
self.assertIsNotNone(json_data["total-number-of-operations"])
self.assertEqual(json_data["number-of-multi-qubit-gates"], 0)
self.assertEqual(json_data["multi-qubit-gate-depth"], 0)
self.assertIsNotNone(json_data.get('transpiled-qasm'))
r = self.client.post('/qiskit-service/api/v1.0/execute', json=request)
self.assertEqual(r.status_code, 202)
print(r.headers.get("Location"))
def test_transpile_hadamard_simulator_file(self):
# prepare the request
file_path = (os.path.dirname(__file__)) + '/data/hadamard.py'
with open(file_path, 'rb') as f:
impl_data = base64.b64encode(f.read()).decode()
request = {
'impl-data': impl_data,
'impl-language': 'Qiskit',
'qpu-name': "ibmq_qasm_simulator",
'input-params': {},
'token': os.environ["QISKIT_TOKEN"]
}
# send the request
response = self.client.post('/qiskit-service/api/v1.0/transpile',
json=request)
self.assertEqual(response.status_code, 200)
json_data = response.get_json()
self.assertIn("width", json_data)
self.assertIn("depth", json_data)
self.assertIsNotNone(json_data['depth'])
self.assertIsNotNone(json_data['width'])
self.assertIn('transpiled-qasm', json_data)
self.assertIn("total-number-of-operations", json_data)
self.assertIn("number-of-multi-qubit-gates", json_data)
self.assertIn("multi-qubit-gate-depth", json_data)
self.assertIsNotNone(json_data["total-number-of-operations"])
self.assertIsNotNone(json_data["number-of-multi-qubit-gates"])
self.assertIsNotNone(json_data["multi-qubit-gate-depth"])
self.assertIsNotNone(json_data.get('transpiled-qasm'))
r = self.client.post('/qiskit-service/api/v1.0/execute', json=request)
self.assertEqual(r.status_code, 202)
print(r.headers.get("Location"))
def test_transpile_circuit_sim_file(self):
# prepare the request
file_path = (os.path.dirname(__file__))+'/data/pattern0-3_1_2nCliffs10seed2.qasm'
with open(file_path, 'rb') as f:
impl_data = base64.b64encode(f.read()).decode()
request = {
'impl-data': impl_data,
'impl-language': 'openqasm',
'qpu-name': "ibmq_qasm_simulator",
'input-params': {},
'token': os.environ.get("QISKIT_TOKEN", "")
}
# send the request
response = self.client.post('/qiskit-service/api/v1.0/transpile',
json=request)
self.assertEqual(response.status_code, 200)
json_data = response.get_json()
self.assertIn("width", json_data)
self.assertIn("depth", json_data)
self.assertIsNotNone(json_data['depth'])
self.assertIsNotNone(json_data['width'])
self.assertIn('transpiled-qasm', json_data)
self.assertIn("total-number-of-operations", json_data)
self.assertIn("number-of-multi-qubit-gates", json_data)
self.assertIn("multi-qubit-gate-depth", json_data)
self.assertIsNotNone(json_data["total-number-of-operations"])
self.assertIsNotNone(json_data["number-of-multi-qubit-gates"])
self.assertIsNotNone(json_data["multi-qubit-gate-depth"])
self.assertIsNotNone(json_data.get('transpiled-qasm'))
r = self.client.post('/qiskit-service/api/v1.0/execute', json=request)
self.assertEqual(r.status_code, 202)
print(r.headers.get("Location"))
def test_transpile_shor_sim_url_qasm(self):
# prepare the request
request = {
'impl-url': 'https://quantum-circuit.com/api/get/circuit/KzG7MxH6hpBpM9pCt?format=qasm',
'impl-language': 'OpenQASM',
'qpu-name': "ibmq_qasm_simulator",
'input-params': {},
'token': os.environ["QISKIT_TOKEN"]
}
# send the request
response = self.client.post('/qiskit-service/api/v1.0/transpile',
json=request)
self.assertEqual(response.status_code, 200)
json_data = response.get_json()
self.assertIn("width", json_data)
self.assertIn("depth", json_data)
self.assertIsNotNone(json_data['depth'])
self.assertIsNotNone(json_data['width'])
self.assertIn('transpiled-qasm', json_data)
self.assertIn("total-number-of-operations", json_data)
self.assertIn("number-of-multi-qubit-gates", json_data)
self.assertIn("multi-qubit-gate-depth", json_data)
self.assertIsNotNone(json_data["total-number-of-operations"])
self.assertIsNotNone(json_data["number-of-multi-qubit-gates"])
self.assertIsNotNone(json_data["multi-qubit-gate-depth"])
self.assertIsNotNone(json_data.get('transpiled-qasm'))
r = self.client.post('/qiskit-service/api/v1.0/execute', json=request)
self.assertEqual(r.status_code, 202)
print(r.headers.get("Location"))
"""
def test_transpile_file_qasm_aws(self):
circuit = random_circuit(5, 3, seed=42)
circuit = circuit.qasm()
impl_data = base64.b64encode(circuit.encode()).decode()
# prepare the request
request = {
'impl-data': impl_data,
'impl-language': 'OpenQASM',
'provider': 'aws',
'qpu-name': "Aria 2",
'input-params': {},
'aws_access_key_id': os.environ.get("QISKIT_AWS_TOKEN", ""),
'aws_secret_access_key': os.environ.get("QISKIT_AWS_SECRET", "")
}
# send the request
response = self.client.post('/qiskit-service/api/v1.0/transpile',
json=request)
self.assertEqual(response.status_code, 200)
json_data = response.get_json()
self.assertIn("width", json_data)
self.assertIn("depth", json_data)
self.assertIsNotNone(json_data['depth'])
self.assertIsNotNone(json_data['width'])
self.assertIn('transpiled-qasm', json_data)
self.assertIn("total-number-of-operations", json_data)
self.assertIn("number-of-multi-qubit-gates", json_data)
self.assertIn("multi-qubit-gate-depth", json_data)
self.assertIsNotNone(json_data["total-number-of-operations"])
self.assertIsNotNone(json_data["number-of-multi-qubit-gates"])
self.assertIsNotNone(json_data["multi-qubit-gate-depth"])
self.assertIsNotNone(json_data.get('transpiled-qasm'))
"""
def test_transpile_circuit_sim_file_qasm(self):
# prepare the request
file_path = (os.path.dirname(__file__))+'/data/pattern0-3_1_2nCliffs10seed2.qasm'
with open(file_path, 'rb') as f:
impl_data = base64.b64encode(f.read()).decode()
request = {
'impl-data': impl_data,
'impl-language': 'OpenQASM',
'qpu-name': "ibmq_qasm_simulator",
'input-params': {},
'token': os.environ["QISKIT_TOKEN"]
}
# send the request
response = self.client.post('/qiskit-service/api/v1.0/transpile',
json=request)
self.assertEqual(response.status_code, 200)
json_data = response.get_json()
self.assertIn("width", json_data)
self.assertIn("depth", json_data)
self.assertIsNotNone(json_data['depth'])
self.assertIsNotNone(json_data['width'])
self.assertIn('transpiled-qasm', json_data)
self.assertIn("total-number-of-operations", json_data)
self.assertIn("number-of-multi-qubit-gates", json_data)
self.assertIn("multi-qubit-gate-depth", json_data)
self.assertIsNotNone(json_data["total-number-of-operations"])
self.assertIsNotNone(json_data["number-of-multi-qubit-gates"])
self.assertIsNotNone(json_data["multi-qubit-gate-depth"])
self.assertIsNotNone(json_data.get('transpiled-qasm'))
r = self.client.post('/qiskit-service/api/v1.0/execute', json=request)
self.assertEqual(r.status_code, 202)
print(r.headers.get("Location"))
# def test_transpile_shor_simulator(self):
# # this test is deprecated, as Shor is no longer natively supported by newer versions of Qiskit
# # prepare the request
# request = {
# 'impl-url': "https://raw.githubusercontent.com/PlanQK/qiskit-service/master/test/data/shor_general_qiskit.py",
# 'qpu-name': "ibmq_qasm_simulator",
# 'input-params': {
# 'N': {
# 'rawValue': "9",
# 'type': 'Integer'
# }
# },
# 'token': os.environ["QISKIT_TOKEN"]
# }
#
# # send the request
# response = self.client.post('/qiskit-service/api/v1.0/transpile',
# json=request)
#
# self.assertEqual(response.status_code, 200)
# json_data = response.get_json()
# self.assertIn("width", json_data)
# self.assertIn("depth", json_data)
# self.assertIsNotNone(json_data['depth'])
# self.assertIsNotNone(json_data['width'])
# self.assertIn('transpiled-qasm', json_data)
# self.assertIn("total-number-of-operations", json_data)
# self.assertIn("number-of-multi-qubit-gates", json_data)
# self.assertIn("multi-qubit-gate-depth", json_data)
# self.assertIsNotNone(json_data["total-number-of-operations"])
# self.assertIsNotNone(json_data["number-of-multi-qubit-gates"])
# self.assertIsNotNone(json_data["multi-qubit-gate-depth"])
# self.assertIsNotNone(json_data.get('transpiled-qasm'))
#
# r = self.client.post('/qiskit-service/api/v1.0/execute', json=request)
# self.assertEqual(r.status_code, 202)
# print(r.headers.get("Location"))
# def test_transpile_shor_nairobi(self):
# # this test is deprecated, as Shor is no longer natively supported by newer versions of Qiskit
# # prepare the request
# request = {
# 'impl-url': "https://raw.githubusercontent.com/PlanQK/qiskit-service/master/test/data/shor_general_qiskit.py",
# 'qpu-name': "ibm_nairobi",
# 'input-params': {
# 'N': {
# 'rawValue': "9",
# 'type': 'Integer'
# }
# },
# 'token': os.environ["QISKIT_TOKEN"]
# }
#
# # send the request
# response = self.client.post('/qiskit-service/api/v1.0/transpile',
# json=request)
#
# self.assertEqual(response.status_code, 200)
# json_data = response.get_json()
# self.assertIn("error", json_data)
# self.assertIn("too many qubits", json_data['error'])
@unittest.skip("PlanQK access token required")
def test_transpile_shor_simulator_planqk_url(self):
# prepare the request
request = {
'impl-url': "https://platform.planqk.de/qc-catalog/algorithms/e7413acf-c25e-4de8-ab78-75bfc836a839/implementations/1207510f-9007-48b3-93b8-ea51359c0ced/files/1d827208-1976-487e-819b-64df6e990bf3/content",
'impl-language': 'Qiskit',
'qpu-name': "ibmq_qasm_simulator",
'input-params': {},
'token': os.environ["QISKIT_TOKEN"],
"bearer-token": os.environ["BEARER_TOKEN"]
}
# send the request
response = self.client.post('/qiskit-service/api/v1.0/transpile',
json=request)
self.assertEqual(response.status_code, 200)
json_data = response.get_json()
self.assertIn("width", json_data)
self.assertIn("depth", json_data)
self.assertIsNotNone(json_data['depth'])
self.assertIsNotNone(json_data['width'])
self.assertIn('transpiled-qasm', json_data)
self.assertIn("total-number-of-operations", json_data)
self.assertIn("number-of-multi-qubit-gates", json_data)
self.assertIn("multi-qubit-gate-depth", json_data)
self.assertIsNotNone(json_data["total-number-of-operations"])
self.assertIsNotNone(json_data["number-of-multi-qubit-gates"])
self.assertIsNotNone(json_data["multi-qubit-gate-depth"])
self.assertIsNotNone(json_data.get('transpiled-qasm'))
r = self.client.post('/qiskit-service/api/v1.0/execute', json=request)
self.assertEqual(r.status_code, 202)
print(r.headers.get("Location"))
def test_batch_execution(self):
# Build a thousand circuits.
circs = []
for _ in range(1000):
circs.append(random_circuit(num_qubits=5, depth=4, measure=True).qasm())
request = {
'impl-qasm': circs,
'impl-language': 'Qiskit',
'qpu-name': "ibmq_qasm_simulator",
'input-params': {},
'token': os.environ["QISKIT_TOKEN"]
}
# send the request
r = self.client.post('/qiskit-service/api/v1.0/execute', json=request)
self.assertEqual(r.status_code, 202)
json_data = r.get_json()
self.assertIsNotNone("result", json_data)
print(r.headers.get("Location"))
@unittest.skip("Perth QPU currently not available")
def test_noisy_simulator(self):
token = os.environ["QISKIT_TOKEN"]
request = {
'impl-qasm': "OPENQASM 2.0; include \"qelib1.inc\";qreg q[4];creg c[4];x q[0]; x q[2];barrier q;h q[0];cu1(pi/2) q[1],q[0];h q[1];cu1(pi/4) q[2],q[0];cu1(pi/2) q[2],q[1];h q[2];cu1(pi/8) q[3],q[0];cu1(pi/4) q[3],q[1];cu1(pi/2) q[3],q[2];h q[3];measure q -> c;",
'impl-language': 'Qiskit',
'qpu-name': "aer_qasm_simulator",
'input-params': {},
"noise_model": "ibm_perth",
'token': token
}
response = self.client.post('/qiskit-service/api/v1.0/execute', json=request)
self.assertEqual(response.status_code, 202)
print(response.get_json())
@unittest.skip("Perth QPU currently not available")
def test_noisy_de_simulator(self):
token = os.environ["QISKIT_TOKEN"]
request = {
'impl-qasm': "OPENQASM 2.0; include \"qelib1.inc\";qreg q[4];creg c[4];x q[0]; x q[2];barrier q;h q[0];cu1(pi/2) q[1],q[0];h q[1];cu1(pi/4) q[2],q[0];cu1(pi/2) q[2],q[1];h q[2];cu1(pi/8) q[3],q[0];cu1(pi/4) q[3],q[1];cu1(pi/2) q[3],q[2];h q[3];measure q -> c;",
'impl-language': 'Qiskit',
'qpu-name': "aer_qasm_simulator",
'input-params': {},
"noise_model": "ibm_perth",
"only-measurement-errors": "True",
'token': token
}
response = self.client.post('/qiskit-service/api/v1.0/execute', json=request)
self.assertEqual(response.status_code, 202)
print(response.get_json())
if __name__ == "__main__":
unittest.main()
|
https://github.com/UST-QuAntiL/qiskit-service
|
UST-QuAntiL
|
import qiskit
def get_circuit(**kwargs):
reg = qiskit.QuantumRegister(1, "q")
circuit = qiskit.QuantumCircuit(reg)
circuit.h(reg)
circuit.measure_all()
return circuit
if __name__ == "__main__":
c = get_circuit()
print(c)
|
https://github.com/UST-QuAntiL/qiskit-service
|
UST-QuAntiL
|
from qiskit import QuantumRegister, ClassicalRegister
from qiskit import QuantumCircuit
qc = QuantumCircuit()
q = QuantumRegister(5, 'q')
c = ClassicalRegister(3, 'c')
qc.add_register(q)
qc.add_register(c)
qc.h(q[0])
qc.h(q[1])
qc.h(q[2])
qc.h(q[1])
qc.cx(q[2], q[3])
qc.cu1(0, q[1], q[0])
qc.cx(q[2], q[4])
qc.h(q[0])
qc.cu1(0, q[1], q[2])
qc.cu1(0, q[0], q[2])
qc.h(q[2])
qc.measure(q[0], c[0])
qc.measure(q[1], c[1])
qc.measure(q[2], c[2])
|
https://github.com/IvanIsCoding/Quantum
|
IvanIsCoding
|
# initialization
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
# importing Qiskit
from qiskit import IBMQ, BasicAer
from qiskit.providers.ibmq import least_busy
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute
# import basic plot tools
from qiskit.tools.visualization import plot_histogram
nQubits = 2 # number of physical qubits used to represent s
s = 3 # the hidden integer
# make sure that a can be represented with nqubits
s = s % 2**(nQubits)
# Creating registers
# qubits for querying the oracle and finding the hidden integer
qr = QuantumRegister(nQubits)
# bits for recording the measurement on qr
cr = ClassicalRegister(nQubits)
bvCircuit = QuantumCircuit(qr, cr)
barriers = True
# Apply Hadamard gates before querying the oracle
for i in range(nQubits):
bvCircuit.h(qr[i])
# Apply barrier
if barriers:
bvCircuit.barrier()
# Apply the inner-product oracle
for i in range(nQubits):
if (s & (1 << i)):
bvCircuit.z(qr[i])
else:
bvCircuit.iden(qr[i])
# Apply barrier
if barriers:
bvCircuit.barrier()
#Apply Hadamard gates after querying the oracle
for i in range(nQubits):
bvCircuit.h(qr[i])
# Apply barrier
if barriers:
bvCircuit.barrier()
# Measurement
bvCircuit.measure(qr, cr)
bvCircuit.draw(output='mpl')
# use local simulator
backend = BasicAer.get_backend('qasm_simulator')
shots = 1024
results = execute(bvCircuit, backend=backend, shots=shots).result()
answer = results.get_counts()
plot_histogram(answer)
# Load our saved IBMQ accounts and get the least busy backend device with less than or equal to 5 qubits
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q')
provider.backends()
backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits <= 5 and
not x.configuration().simulator and x.status().operational==True))
print("least busy backend: ", backend)
# Run our circuit on the least busy backend. Monitor the execution of the job in the queue
from qiskit.tools.monitor import job_monitor
shots = 1024
job = execute(bvCircuit, backend=backend, shots=shots)
job_monitor(job, interval = 2)
# Get the results from the computation
results = job.result()
answer = results.get_counts()
plot_histogram(answer)
import qiskit
qiskit.__qiskit_version__
|
https://github.com/IvanIsCoding/Quantum
|
IvanIsCoding
|
# initialization
import numpy as np
# importing Qiskit
from qiskit import IBMQ, Aer
from qiskit.providers.ibmq import least_busy
from qiskit import QuantumCircuit, transpile
# import basic plot tools
from qiskit.visualization import plot_histogram
# set the length of the n-bit input string.
n = 3
# set the length of the n-bit input string.
n = 3
const_oracle = QuantumCircuit(n+1)
output = np.random.randint(2)
if output == 1:
const_oracle.x(n)
const_oracle.draw()
balanced_oracle = QuantumCircuit(n+1)
b_str = "101"
balanced_oracle = QuantumCircuit(n+1)
b_str = "101"
# Place X-gates
for qubit in range(len(b_str)):
if b_str[qubit] == '1':
balanced_oracle.x(qubit)
balanced_oracle.draw()
balanced_oracle = QuantumCircuit(n+1)
b_str = "101"
# Place X-gates
for qubit in range(len(b_str)):
if b_str[qubit] == '1':
balanced_oracle.x(qubit)
# Use barrier as divider
balanced_oracle.barrier()
# Controlled-NOT gates
for qubit in range(n):
balanced_oracle.cx(qubit, n)
balanced_oracle.barrier()
balanced_oracle.draw()
balanced_oracle = QuantumCircuit(n+1)
b_str = "101"
# Place X-gates
for qubit in range(len(b_str)):
if b_str[qubit] == '1':
balanced_oracle.x(qubit)
# Use barrier as divider
balanced_oracle.barrier()
# Controlled-NOT gates
for qubit in range(n):
balanced_oracle.cx(qubit, n)
balanced_oracle.barrier()
# Place X-gates
for qubit in range(len(b_str)):
if b_str[qubit] == '1':
balanced_oracle.x(qubit)
# Show oracle
balanced_oracle.draw()
dj_circuit = QuantumCircuit(n+1, n)
# Apply H-gates
for qubit in range(n):
dj_circuit.h(qubit)
# Put qubit in state |->
dj_circuit.x(n)
dj_circuit.h(n)
dj_circuit.draw()
dj_circuit = QuantumCircuit(n+1, n)
# Apply H-gates
for qubit in range(n):
dj_circuit.h(qubit)
# Put qubit in state |->
dj_circuit.x(n)
dj_circuit.h(n)
# Add oracle
dj_circuit = dj_circuit.compose(balanced_oracle)
dj_circuit.draw()
dj_circuit = QuantumCircuit(n+1, n)
# Apply H-gates
for qubit in range(n):
dj_circuit.h(qubit)
# Put qubit in state |->
dj_circuit.x(n)
dj_circuit.h(n)
# Add oracle
dj_circuit = dj_circuit.compose(balanced_oracle)
# Repeat H-gates
for qubit in range(n):
dj_circuit.h(qubit)
dj_circuit.barrier()
# Measure
for i in range(n):
dj_circuit.measure(i, i)
# Display circuit
dj_circuit.draw()
# use local simulator
aer_sim = Aer.get_backend('aer_simulator')
results = aer_sim.run(dj_circuit).result()
answer = results.get_counts()
plot_histogram(answer)
# ...we have a 0% chance of measuring 000.
assert answer.get('000', 0) == 0
def dj_oracle(case, n):
# We need to make a QuantumCircuit object to return
# This circuit has n+1 qubits: the size of the input,
# plus one output qubit
oracle_qc = QuantumCircuit(n+1)
# First, let's deal with the case in which oracle is balanced
if case == "balanced":
# First generate a random number that tells us which CNOTs to
# wrap in X-gates:
b = np.random.randint(1,2**n)
# Next, format 'b' as a binary string of length 'n', padded with zeros:
b_str = format(b, '0'+str(n)+'b')
# Next, we place the first X-gates. Each digit in our binary string
# corresponds to a qubit, if the digit is 0, we do nothing, if it's 1
# we apply an X-gate to that qubit:
for qubit in range(len(b_str)):
if b_str[qubit] == '1':
oracle_qc.x(qubit)
# Do the controlled-NOT gates for each qubit, using the output qubit
# as the target:
for qubit in range(n):
oracle_qc.cx(qubit, n)
# Next, place the final X-gates
for qubit in range(len(b_str)):
if b_str[qubit] == '1':
oracle_qc.x(qubit)
# Case in which oracle is constant
if case == "constant":
# First decide what the fixed output of the oracle will be
# (either always 0 or always 1)
output = np.random.randint(2)
if output == 1:
oracle_qc.x(n)
oracle_gate = oracle_qc.to_gate()
oracle_gate.name = "Oracle" # To show when we display the circuit
return oracle_gate
def dj_algorithm(oracle, n):
dj_circuit = QuantumCircuit(n+1, n)
# Set up the output qubit:
dj_circuit.x(n)
dj_circuit.h(n)
# And set up the input register:
for qubit in range(n):
dj_circuit.h(qubit)
# Let's append the oracle gate to our circuit:
dj_circuit.append(oracle, range(n+1))
# Finally, perform the H-gates again and measure:
for qubit in range(n):
dj_circuit.h(qubit)
for i in range(n):
dj_circuit.measure(i, i)
return dj_circuit
n = 4
oracle_gate = dj_oracle('balanced', n)
dj_circuit = dj_algorithm(oracle_gate, n)
dj_circuit.draw()
transpiled_dj_circuit = transpile(dj_circuit, aer_sim)
results = aer_sim.run(transpiled_dj_circuit).result()
answer = results.get_counts()
plot_histogram(answer)
# Load our saved IBMQ accounts and get the least busy backend device with greater than or equal to (n+1) qubits
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q')
backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= (n+1) and
not x.configuration().simulator and x.status().operational==True))
print("least busy backend: ", backend)
# Run our circuit on the least busy backend. Monitor the execution of the job in the queue
from qiskit.tools.monitor import job_monitor
transpiled_dj_circuit = transpile(dj_circuit, backend, optimization_level=3)
job = backend.run(transpiled_dj_circuit)
job_monitor(job, interval=2)
# Get the results of the computation
results = job.result()
answer = results.get_counts()
plot_histogram(answer)
# ...the most likely result is 1111.
assert max(answer, key=answer.get) == '1111'
from qiskit_textbook.problems import dj_problem_oracle
oracle = dj_problem_oracle(1)
import qiskit.tools.jupyter
%qiskit_version_table
|
https://github.com/IvanIsCoding/Quantum
|
IvanIsCoding
|
# initialization
import numpy as np
# importing Qiskit
from qiskit import IBMQ, Aer
from qiskit import QuantumCircuit, transpile
# import basic plot tools
from qiskit.visualization import plot_histogram
# set the length of the n-bit input string.
n = 3
# Constant Oracle
const_oracle = QuantumCircuit(n+1)
# Random output
output = np.random.randint(2)
if output == 1:
const_oracle.x(n)
const_oracle.draw()
# Balanced Oracle
balanced_oracle = QuantumCircuit(n+1)
# Binary string length
b_str = "101"
# For each qubit in our circuit
# we place an X-gate if the corresponding digit in b_str is 1
# or do nothing if the digit is 0
balanced_oracle = QuantumCircuit(n+1)
b_str = "101"
# Place X-gates
for qubit in range(len(b_str)):
if b_str[qubit] == '1':
balanced_oracle.x(qubit)
balanced_oracle.draw()
# Creating the controlled-NOT gates
# using each input qubit as a control
# and the output as a target
balanced_oracle = QuantumCircuit(n+1)
b_str = "101"
# Place X-gates
for qubit in range(len(b_str)):
if b_str[qubit] == '1':
balanced_oracle.x(qubit)
# Use barrier as divider
balanced_oracle.barrier()
# Controlled-NOT gates
for qubit in range(n):
balanced_oracle.cx(qubit, n)
balanced_oracle.barrier()
# Wrapping the controls in X-gates
# Place X-gates
for qubit in range(len(b_str)):
if b_str[qubit] == '1':
balanced_oracle.x(qubit)
# Show oracle
balanced_oracle.draw()
dj_circuit = QuantumCircuit(n+1, n)
# Apply H-gates
for qubit in range(n):
dj_circuit.h(qubit)
# Put qubit in state |->
dj_circuit.x(n)
dj_circuit.h(n)
# Add oracle
dj_circuit = dj_circuit.compose(balanced_oracle)
# Repeat H-gates
for qubit in range(n):
dj_circuit.h(qubit)
dj_circuit.barrier()
# Measure
for i in range(n):
dj_circuit.measure(i, i)
# Display circuit
dj_circuit.draw()
# Viewing the output
# use local simulator
aer_sim = Aer.get_backend('aer_simulator')
results = aer_sim.run(dj_circuit).result()
answer = results.get_counts()
plot_histogram(answer)
|
https://github.com/IvanIsCoding/Quantum
|
IvanIsCoding
|
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()
from qiskit.circuit.library.standard_gates import XGate, HGate
from operator import *
n = 3
N = 8 #2**n
index_colour_table = {}
colour_hash_map = {}
index_colour_table = {'000':"yellow", '001':"red", '010':"blue", '011':"red", '100':"green", '101':"blue", '110':"orange", '111':"red"}
colour_hash_map = {"yellow":'100', "red":'011', "blue":'000', "green":'001', "orange":'010'}
def database_oracle(index_colour_table, colour_hash_map):
circ_database = QuantumCircuit(n + n)
for i in range(N):
circ_data = QuantumCircuit(n)
idx = bin(i)[2:].zfill(n) # removing the "0b" prefix appended by the bin() funtion
colour = index_colour_table[idx]
colour_hash = colour_hash_map[colour][::-1]
for j in range(n):
if colour_hash[j] == '1':
circ_data.x(j)
# qiskit maps the rightmost bit as the 0th qubit -> qn, ..., q0
# we therefore reverse the index string -> q0, ..., qn
data_gate = circ_data.to_gate(label=colour).control(num_ctrl_qubits=n, ctrl_state=idx, label="index-"+colour)
circ_database.append(data_gate, list(range(n+n)))
return circ_database
# drawing the database oracle circuit
print("Database Encoding")
database_oracle(index_colour_table, colour_hash_map).draw()
circ_data = QuantumCircuit(n)
m = 4
idx = bin(m)[2:].zfill(n) # removing the "0b" prefix appended by the bin() funtion
colour = index_colour_table[idx]
colour_hash = colour_hash_map[colour][::-1]
for j in range(n):
if colour_hash[j] == '1':
circ_data.x(j)
print("Internal colour encoding for the colour green (as an example)");
circ_data.draw()
def oracle_grover(database, data_entry):
circ_grover = QuantumCircuit(n + n + 1)
circ_grover.append(database, list(range(n+n)))
target_reflection_gate = XGate().control(num_ctrl_qubits=n, ctrl_state=colour_hash_map[data_entry], label="Reflection of " + "\"" + data_entry + "\" Target")
# control() missing 1 required positional argument: 'self' .... if only 'XGate' used instead of 'XGate()'
# The “missing 1 required positional argument: 'self'” error is raised when you do not instantiate an object of a class before calling a class method. This error is also raised when you incorrectly instantiate a class.
circ_grover.append(target_reflection_gate, list(range(n, n+n+1)))
circ_grover.append(database, list(range(n+n)))
return circ_grover
print("Grover Oracle (target example: orange)")
oracle_grover(database_oracle(index_colour_table, colour_hash_map).to_gate(label="Database Encoding"), "orange").decompose().draw()
def mcz_gate(num_qubits):
num_controls = num_qubits - 1
mcz_gate = QuantumCircuit(num_qubits)
target_mcz = QuantumCircuit(1)
target_mcz.z(0)
target_mcz = target_mcz.to_gate(label="Z_Gate").control(num_ctrl_qubits=num_controls, ctrl_state=None, label="MCZ")
mcz_gate.append(target_mcz, list(range(num_qubits)))
return mcz_gate.reverse_bits()
print("Multi-controlled Z (MCZ) Gate")
mcz_gate(n).decompose().draw()
def diffusion_operator(num_qubits):
circ_diffusion = QuantumCircuit(num_qubits)
qubits_list = list(range(num_qubits))
# Layer of H^n gates
circ_diffusion.h(qubits_list)
# Layer of X^n gates
circ_diffusion.x(qubits_list)
# Layer of Multi-controlled Z (MCZ) Gate
circ_diffusion = circ_diffusion.compose(mcz_gate(num_qubits), qubits_list)
# Layer of X^n gates
circ_diffusion.x(qubits_list)
# Layer of H^n gates
circ_diffusion.h(qubits_list)
return circ_diffusion
print("Diffusion Circuit")
diffusion_operator(n).draw()
# Putting it all together ... !!!
item = "green"
print("Searching for the index of the colour", item)
circuit = QuantumCircuit(n + n + 1, n)
circuit.x(n + n)
circuit.barrier()
circuit.h(list(range(n)))
circuit.h(n+n)
circuit.barrier()
unitary_oracle = oracle_grover(database_oracle(index_colour_table, colour_hash_map).to_gate(label="Database Encoding"), item).to_gate(label="Oracle Operator")
unitary_diffuser = diffusion_operator(n).to_gate(label="Diffusion Operator")
M = countOf(index_colour_table.values(), item)
Q = int(np.pi * np.sqrt(N/M) / 4)
for i in range(Q):
circuit.append(unitary_oracle, list(range(n + n + 1)))
circuit.append(unitary_diffuser, list(range(n)))
circuit.barrier()
circuit.measure(list(range(n)), list(range(n)))
circuit.draw()
backend_sim = Aer.get_backend('qasm_simulator')
job_sim = backend_sim.run(transpile(circuit, backend_sim), shots=1024)
result_sim = job_sim.result()
counts = result_sim.get_counts(circuit)
if M==1:
print("Index of the colour", item, "is the index with most probable outcome")
else:
print("Indices of the colour", item, "are the indices the most probable outcomes")
from qiskit.visualization import plot_histogram
plot_histogram(counts)
|
https://github.com/IvanIsCoding/Quantum
|
IvanIsCoding
|
from math import gcd, log
from random import randint
def is_prime(N):
"""Returns if N is prime or not. Notice that this is not optimal,
there is faster primality testing algorithms e.g. Miller-Rabin
"""
if N == 2:
return True # only even prime
if N % 2 == 0 or N <= 1:
return False # even numbers and 1 are not prime
for i in range(3, N, 2): # only try odd candidates
if i*i > N:
break # we only need to check up to sqrt(N)
if N % i == 0:
return False # found a factor
return True
def find_power_k(N):
"""Returns the smallest k > 1 such that N**(1/k) is an integer,
or 1 if there is no such k.
"""
upper_bound = int(log(N)/log(3))
for k in range(2, upper_bound + 1):
p = int(N**(1/k))
if p**k == N:
return k
return 1
def order_finding(a, N):
"""Returns the smallest r such that a^r = 1 mod N
Notice that this is a naive classic implementation and is
exponentially slower than the quantum version invented by Peter Shor.
"""
i = 1
a_i = a % N
while a_i != 1:
i += 1
a_i = (a_i * a) % N
return i
order_finding(2, 15)
def shor_algorithm(N):
"""Returns a pair of integers (P, Q) such that PQ = N for integer N"""
if N % 2 == 0: # even case
return (N//2, 2)
if is_prime(N): # prime case
return (N, 1) # N is primes, factors cannot be found
if find_power_k(N) > 1: # prime power case
P = int(N**(1/find_power_k(N))) # we find a k such that N**(1/k) is an integer
Q = N//P
return (P, Q)
# Now we can assume that the criteria for Shor's algorithm is met
while True:
# Non-deterministic, we will try multiple values for a
a = randint(2, N-1) # pick random a
if gcd(a, N) != 1: # Lucky case: a and N are not coprime!
P = gcd(a, N) # gcd yields a non-trivial factor
Q = N//P
return (P, Q)
r = order_finding(a, N) # quantum subroutine of the code
if r % 2 == 0:
continue
P = gcd(a**(r//2) - 1, N)
if P != 1:
Q = N//P # gcd yielded non trivial factor
return (P, Q)
N = 10013
P, Q = shor_algorithm(N)
print(
"Shor's algorithm found {} = {} x {} which is {}!".format(N, P, Q, ["incorrect", "correct"][P*Q==N])
)
S, T = shor_algorithm(Q)
print(
"Shor's algorithm found {} = {} x {} which is {} again!".format(Q, S, T, ["incorrect", "correct"][S*T==Q])
)
|
https://github.com/IvanIsCoding/Quantum
|
IvanIsCoding
|
from qiskit import *
from qiskit.visualization import plot_histogram
simulator = Aer.get_backend("qasm_simulator")
circuit = QuantumCircuit(1, 1)
circuit.measure(0, 0)
circuit.draw(output="mpl")
job = execute(circuit, backend=simulator, shots=2**15)
result = job.result()
counts = result.get_counts()
print(counts)
plot_histogram(counts)
circuit = QuantumCircuit(1, 1)
circuit.x(0)
circuit.measure(0, 0)
circuit.draw(output="mpl")
counts = execute(circuit, backend=simulator, shots=2**15).result().get_counts()
plot_histogram(counts)
circuit = QuantumCircuit(1, 1)
circuit.h(0)
circuit.measure(0, 0)
circuit.draw(output="mpl")
counts = execute(circuit, backend=simulator, shots=2**15).result().get_counts()
plot_histogram(counts)
# Circuit to generate -|0>
circuit = QuantumCircuit(1, 1)
circuit.x(0)
circuit.z(0)
circuit.x(0)
circuit.measure(0, 0)
circuit.draw(output="mpl")
counts = execute(circuit, backend=simulator, shots=2**15).result().get_counts()
plot_histogram(counts)
# Circuit to generate i|0>
circuit = QuantumCircuit(1, 1)
circuit.x(0)
circuit.y(0)
circuit.measure(0, 0)
circuit.draw(output="mpl")
counts = execute(circuit, backend=simulator, shots=2**15).result().get_counts()
plot_histogram(counts)
|
https://github.com/IvanIsCoding/Quantum
|
IvanIsCoding
|
%matplotlib inline
from qiskit import *
from qiskit.visualization import plot_histogram
circuit = QuantumCircuit(2)
circuit.x(0)
circuit.z(1)
circuit.draw(output="mpl")
unitary_simulator = Aer.get_backend("unitary_simulator")
unitary = execute(circuit, backend=unitary_simulator).result().get_unitary()
print(unitary)
circuit = QuantumCircuit(2)
circuit.h(0)
circuit.x(1)
circuit.cx(0, 1)
circuit.draw(output="mpl")
state_simulator = Aer.get_backend("statevector_simulator")
state_vector = execute(circuit, backend=state_simulator).result().get_statevector()
print(state_vector)
circuit = QuantumCircuit(2)
circuit.h(0)
circuit.h(1)
circuit.cz(0, 1)
circuit.draw(output="mpl")
state_vector = execute(circuit, backend=state_simulator).result().get_statevector()
print(state_vector)
circuit = QuantumCircuit(3, 3)
circuit.h([0, 1])
circuit.ccx(0, 1, 2)
circuit.measure([0, 1, 2], [0, 1, 2])
circuit.draw(output="mpl")
simulator = Aer.get_backend("qasm_simulator")
counts = execute(circuit, backend=simulator, shots=2**16).result().get_counts()
plot_histogram(counts)
circuit = QuantumCircuit(3, 3)
circuit.x(0)
circuit.cx(0, 1)
circuit.ccx(0, 1, 2)
circuit.ccx(0, 1, 2)
circuit.cx(0, 1)
circuit.x(0)
circuit.measure([0, 1, 2], [0, 1, 2])
circuit.draw(output="mpl")
counts = execute(circuit, backend=simulator, shots=2**16).result().get_counts()
plot_histogram(counts)
|
https://github.com/IvanIsCoding/Quantum
|
IvanIsCoding
|
%matplotlib inline
from qiskit import *
# The following code is for nicer display of the matrices
from IPython.display import display, Markdown
def format_float(x):
if x % 1 == 0:
return int(x)
else:
return x
def format_imaginary(z):
if abs(z.imag) < 1e-15:
return "{}".format(format_float(z.real))
elif abs(z.real) < 1e-15:
if z.imag == 1:
return "i"
elif z.imag == -1:
return "-i"
return "{}i".format(format_float(z.imag))
if z.imag > 0:
return "{} + {}i".format(z.real, abs(z.imag))
else:
return "{} - {}i".format(z.real, abs(z.imag))
def display_matrix(gate, gate_name="U"):
a00 = format_imaginary(gate[0][0])
a01 = format_imaginary(gate[0][1])
a10 = format_imaginary(gate[1][0])
a11 = format_imaginary(gate[1][1])
ans = r"${} = \begin{{bmatrix}} {} & {} \\ {} & {}\end{{bmatrix}}$".format(gate_name,a00, a01, a10, a11)
return Markdown(ans)
simulator = Aer.get_backend("unitary_simulator")
circuit = QuantumCircuit(1)
circuit.draw(output="mpl")
job = execute(circuit, backend=simulator)
result = job.result()
unitary = result.get_unitary()
print(unitary)
circuit = QuantumCircuit(1)
circuit.x(0)
circuit.draw(output="mpl")
unitary = execute(circuit, backend=simulator).result().get_unitary()
display(
display_matrix(unitary, "X")
)
circuit = QuantumCircuit(1)
circuit.x(0)
circuit.h(0)
circuit.draw(output="mpl")
unitary = execute(circuit, backend=simulator).result().get_unitary()
display(
display_matrix(unitary)
)
circuit = QuantumCircuit(1)
circuit.h(0)
circuit.z(0)
circuit.draw(output="mpl")
unitary = execute(circuit, backend=simulator).result().get_unitary()
display(
display_matrix(unitary)
)
circuit = QuantumCircuit(1)
circuit.z(0)
circuit.h(0)
circuit.draw(output="mpl")
unitary = execute(circuit, backend=simulator).result().get_unitary()
display(
display_matrix(unitary)
)
circuit = QuantumCircuit(1)
circuit.y(0)
circuit.draw(output="mpl")
unitary = execute(circuit, backend=simulator).result().get_unitary()
display(
display_matrix(unitary, "Y")
)
circuit = QuantumCircuit(1)
circuit.y(0)
circuit.y(0)
circuit.draw(output="mpl")
unitary = execute(circuit, backend=simulator).result().get_unitary()
display(
display_matrix(unitary, "U")
)
circuit = QuantumCircuit(1)
circuit.s(0)
circuit.s(0)
circuit.draw(output="mpl")
unitary = execute(circuit, backend=simulator).result().get_unitary()
display(
display_matrix(unitary, "U")
)
circuit = QuantumCircuit(1)
circuit.s(0)
circuit.sdg(0) # sdg = s dagger
circuit.draw(output="mpl")
unitary = execute(circuit, backend=simulator).result().get_unitary()
display(
display_matrix(unitary, "U")
)
circuit = QuantumCircuit(1)
circuit.s(0)
#circuit.sdg(0)
circuit.s(0)
circuit.s(0)
circuit.s(0)
circuit.draw(output="mpl")
unitary = execute(circuit, backend=simulator).result().get_unitary()
display(
display_matrix(unitary, "U")
)
|
https://github.com/IvanIsCoding/Quantum
|
IvanIsCoding
|
from qiskit import QuantumCircuit
from qiskit.quantum_info import Statevector
# Create a Quantum Circuit acting on the q register
circuit = QuantumCircuit(1)
# print the statevector
print(f"Initial Statevector: {Statevector.from_instruction(circuit).data}\n\n")
# Add an X gate followed by a H gate to put the qubit in |-> state
circuit.x(0)
circuit.h(0)
print("After putting the qubit in |-> state\n\n")
# print the statevector
print("Final Statevector: ", Statevector.from_instruction(circuit).data)
import numpy as np
from qiskit import QuantumCircuit, QuantumRegister
from qiskit.quantum_info import Statevector
# Create a Quantum Register with 3 qubits
q = QuantumRegister(3)
# Create a Quantum Circuit acting on the q register to demonstrate the GHZ state
circuit = QuantumCircuit(q)
# Add a H gate on qubit 0, putting this qubit in superposition.
circuit.h(q[0])
# Add a CX (CNOT) gate on control qubit 0 and target qubit 1
circuit.cx(q[0], q[1])
# Add a CX (CNOT) gate on control qubit 0 and target qubit 2
circuit.cx(q[0], q[2])
from qiskit.quantum_info import Statevector
# Set the intial state of the simulator to the ground state using from_int
state = Statevector.from_int(0, 2**3)
# Evolve the state by the quantum circuit
state = state.evolve(circuit)
#draw using latex
state.draw('latex')
from qiskit.visualization import array_to_latex
#Alternative way of representing in latex
array_to_latex(state)
state.draw('qsphere')
|
https://github.com/IvanIsCoding/Quantum
|
IvanIsCoding
|
%matplotlib inline
from qiskit import *
circuit = QuantumCircuit(5, 2)
# Steps to change qubits to 1 for test purposes
_ = circuit.x(0)
_ = circuit.x(1)
_ = circuit.x(2)
_ = circuit.barrier()
_ = circuit.ccx(0, 1, 3)
circuit.draw(output="mpl")
_ = circuit.ccx(2, 3, 4)
circuit.draw(output="mpl")
_ = circuit.ccx(0, 1, 3)
circuit.draw(output="mpl")
# Measure (x^y^z) and working qubuit in classical bit
_ = circuit.barrier()
_ = circuit.measure(4, 0)
_ = circuit.measure(3, 1)
circuit.draw(output="mpl")
# Simulate
simulator = Aer.get_backend("qasm_simulator")
job = execute(circuit, backend=simulator, shots=1024)
result = job.result()
counts = result.get_counts()
# Plot results
visualization.plot_histogram(counts)
|
https://github.com/IvanIsCoding/Quantum
|
IvanIsCoding
|
# Superdense Coding
%matplotlib inline
from qiskit import *
# Step 0: Prepare the Bell State
bell_circuit = QuantumCircuit(2, 2)
bell_circuit.h(0)
bell_circuit.cx(0, 1)
bell_circuit.barrier()
bell_circuit.draw(output="mpl")
# Step 1: Prepare Alice circuits depending on b0b1
# Case 00: the circuit has no gates
alice_00 = QuantumCircuit(2, 2)
alice_00.barrier()
alice_00.draw(output="mpl")
# Case 01: the circuit has the X gate
alice_01 = QuantumCircuit(2, 2)
alice_01.x(0)
alice_01.barrier()
alice_01.draw(output="mpl")
# Case 10: the circuit has the Z gate
alice_10 = QuantumCircuit(2, 2)
alice_10.z(0)
alice_10.barrier()
alice_10.draw(output="mpl")
# Case 11: the circuit has the X gate and then Z gate
alice_11 = QuantumCircuit(2, 2)
alice_11.x(0)
alice_11.z(0)
alice_11.barrier()
alice_11.draw(output="mpl")
# Step 2: Apply the inverted entanglement circuit, and then measure
invert_circuit = QuantumCircuit(2, 2)
invert_circuit.cx(0, 1)
invert_circuit.h(0)
invert_circuit.barrier()
invert_circuit.measure([0, 1], [1, 0]) # Qiskit measures are always reversed, b1b0 not b0b1
invert_circuit.draw(output="mpl")
# When merged, the whole circuit looks like
(bell_circuit + alice_11 + invert_circuit).draw(output="mpl")
# Now we simulate each outcome, to do so we create an auxiliary function that runs it
def simulate_circuit(prep, encoding, decoding):
"""Returns the counts of the circuit that is combination of the three circuits"""
circuit = prep + encoding + decoding
simulator = Aer.get_backend("qasm_simulator")
job = execute(circuit, simulator, shots = 2**16)
result = job.result()
count = result.get_counts()
return count
# For 00
count_00 = simulate_circuit(bell_circuit, alice_00, invert_circuit)
visualization.plot_histogram(count_00)
# For 01
count_01 = simulate_circuit(bell_circuit, alice_01, invert_circuit)
visualization.plot_histogram(count_01)
# For 10
count_10 = simulate_circuit(bell_circuit, alice_10, invert_circuit)
visualization.plot_histogram(count_10)
# For 11
count_11 = simulate_circuit(bell_circuit, alice_11, invert_circuit)
visualization.plot_histogram(count_11)
# The results match our predictions!
# For purposes of reproducibility, the Qiskit version is
qiskit.__qiskit_version__
|
https://github.com/IvanIsCoding/Quantum
|
IvanIsCoding
|
# Do the necessary imports
import numpy as np
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit import IBMQ, Aer, transpile, assemble
from qiskit.visualization import plot_histogram, plot_bloch_multivector, array_to_latex
from qiskit.extensions import Initialize
from qiskit.ignis.verification import marginal_counts
from qiskit.quantum_info import random_statevector
# Loading your IBM Quantum account(s)
provider = IBMQ.load_account()
## SETUP
# Protocol uses 3 qubits and 2 classical bits in 2 different registers
qr = QuantumRegister(3, name="q") # Protocol uses 3 qubits
crz = ClassicalRegister(1, name="crz") # and 2 classical bits
crx = ClassicalRegister(1, name="crx") # in 2 different registers
teleportation_circuit = QuantumCircuit(qr, crz, crx)
def create_bell_pair(qc, a, b):
qc.h(a)
qc.cx(a,b)
qr = QuantumRegister(3, name="q")
crz, crx = ClassicalRegister(1, name="crz"), ClassicalRegister(1, name="crx")
teleportation_circuit = QuantumCircuit(qr, crz, crx)
create_bell_pair(teleportation_circuit, 1, 2)
teleportation_circuit.draw()
def alice_gates(qc, psi, a):
qc.cx(psi, a)
qc.h(psi)
qr = QuantumRegister(3, name="q")
crz, crx = ClassicalRegister(1, name="crz"), ClassicalRegister(1, name="crx")
teleportation_circuit = QuantumCircuit(qr, crz, crx)
## STEP 1
create_bell_pair(teleportation_circuit, 1, 2)
## STEP 2
teleportation_circuit.barrier() # Use barrier to separate steps
alice_gates(teleportation_circuit, 0, 1)
teleportation_circuit.draw()
def measure_and_send(qc, a, b):
"""Measures qubits a & b and 'sends' the results to Bob"""
qc.barrier()
qc.measure(a,0)
qc.measure(b,1)
qr = QuantumRegister(3, name="q")
crz, crx = ClassicalRegister(1, name="crz"), ClassicalRegister(1, name="crx")
teleportation_circuit = QuantumCircuit(qr, crz, crx)
create_bell_pair(teleportation_circuit, 1, 2)
teleportation_circuit.barrier() # Use barrier to separate steps
alice_gates(teleportation_circuit, 0, 1)
measure_and_send(teleportation_circuit, 0 ,1)
teleportation_circuit.draw()
def bob_gates(qc, qubit, crz, crx):
qc.x(qubit).c_if(crx, 1) # Apply gates if the registers
qc.z(qubit).c_if(crz, 1) # are in the state '1'
qr = QuantumRegister(3, name="q")
crz, crx = ClassicalRegister(1, name="crz"), ClassicalRegister(1, name="crx")
teleportation_circuit = QuantumCircuit(qr, crz, crx)
## STEP 1
create_bell_pair(teleportation_circuit, 1, 2)
## STEP 2
teleportation_circuit.barrier() # Use barrier to separate steps
alice_gates(teleportation_circuit, 0, 1)
## STEP 3
measure_and_send(teleportation_circuit, 0, 1)
## STEP 4
teleportation_circuit.barrier() # Use barrier to separate steps
bob_gates(teleportation_circuit, 2, crz, crx)
teleportation_circuit.draw()
# Create random 1-qubit state
psi = random_statevector(2)
# Display it nicely
display(array_to_latex(psi, prefix="|\\psi\\rangle ="))
# Show it on a Bloch sphere
plot_bloch_multivector(psi)
init_gate = Initialize(psi)
init_gate.label = "init"
## SETUP
qr = QuantumRegister(3, name="q") # Protocol uses 3 qubits
crz = ClassicalRegister(1, name="crz") # and 2 classical registers
crx = ClassicalRegister(1, name="crx")
qc = QuantumCircuit(qr, crz, crx)
## STEP 0
# First, let's initialize Alice's q0
qc.append(init_gate, [0])
qc.barrier()
## STEP 1
# Now begins the teleportation protocol
create_bell_pair(qc, 1, 2)
qc.barrier()
## STEP 2
# Send q1 to Alice and q2 to Bob
alice_gates(qc, 0, 1)
## STEP 3
# Alice then sends her classical bits to Bob
measure_and_send(qc, 0, 1)
## STEP 4
# Bob decodes qubits
bob_gates(qc, 2, crz, crx)
# Display the circuit
qc.draw()
sim = Aer.get_backend('aer_simulator')
qc.save_statevector()
out_vector = sim.run(qc).result().get_statevector()
plot_bloch_multivector(out_vector)
|
https://github.com/rohitgit1/Quantum-Computing-Summer-School
|
rohitgit1
|
!pip install -U -r grading_tools/requirements.txt
from IPython.display import clear_output
clear_output()
import numpy as np; pi = np.pi
from qiskit import QuantumCircuit, Aer, execute
from qiskit.visualization import plot_histogram
from copy import deepcopy as make_copy
def prepare_hets_circuit(depth, angle1, angle2):
hets_circ = QuantumCircuit(depth)
hets_circ.ry(angle1, 0)
hets_circ.rz(angle1, 0)
hets_circ.ry(angle1, 1)
hets_circ.rz(angle1, 1)
for ii in range(depth):
hets_circ.cx(0,1)
hets_circ.ry(angle2,0)
hets_circ.rz(angle2,0)
hets_circ.ry(angle2,1)
hets_circ.rz(angle2,1)
return hets_circ
hets_circuit = prepare_hets_circuit(2, pi/2, pi/2)
hets_circuit.draw()
def measure_zz_circuit(given_circuit):
zz_meas = make_copy(given_circuit)
zz_meas.measure_all()
return zz_meas
zz_meas = measure_zz_circuit(hets_circuit)
zz_meas.draw()
simulator = Aer.get_backend('qasm_simulator')
result = execute(zz_meas, backend = simulator, shots=10000).result()
counts = result.get_counts(zz_meas)
plot_histogram(counts)
def measure_zz(given_circuit, num_shots = 10000):
zz_meas = measure_zz_circuit(given_circuit)
result = execute(zz_meas, backend = simulator, shots = num_shots).result()
counts = result.get_counts(zz_meas)
if '00' not in counts:
counts['00'] = 0
if '01' not in counts:
counts['01'] = 0
if '10' not in counts:
counts['10'] = 0
if '11' not in counts:
counts['11'] = 0
total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10']
zz = counts['00'] + counts['11'] - counts['01'] - counts['10']
zz = zz / total_counts
return zz
zz = measure_zz(hets_circuit)
print("<ZZ> =", str(zz))
def measure_zi(given_circuit, num_shots = 10000):
zz_meas = measure_zz_circuit(given_circuit)
result = execute(zz_meas, backend = simulator, shots = num_shots).result()
counts = result.get_counts(zz_meas)
if '00' not in counts:
counts['00'] = 0
if '01' not in counts:
counts['01'] = 0
if '10' not in counts:
counts['10'] = 0
if '11' not in counts:
counts['11'] = 0
total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10']
zi = counts['00'] - counts['11'] + counts['01'] - counts['10']
zi = zi / total_counts
return zi
def measure_iz(given_circuit, num_shots = 10000):
zz_meas = measure_zz_circuit(given_circuit)
result = execute(zz_meas, backend = simulator, shots = num_shots).result()
counts = result.get_counts(zz_meas)
if '00' not in counts:
counts['00'] = 0
if '01' not in counts:
counts['01'] = 0
if '10' not in counts:
counts['10'] = 0
if '11' not in counts:
counts['11'] = 0
total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10']
iz = counts['00'] - counts['11'] - counts['01'] + counts['10']
iz = iz / total_counts
return iz
zi = measure_zi(hets_circuit)
print("<ZI> =", str(zi))
iz = measure_iz(hets_circuit)
print("<IZ> =", str(iz))
def measure_xx_circuit(given_circuit):
xx_meas = make_copy(given_circuit)
### WRITE YOUR CODE BETWEEN THESE LINES - START
xx_meas.h(0)
xx_meas.h(1)
xx_meas.measure_all()
### WRITE YOUR CODE BETWEEN THESE LINES - END
return xx_meas
xx_meas = measure_xx_circuit(hets_circuit)
xx_meas.draw()
def measure_xx(given_circuit, num_shots = 10000):
xx_meas = measure_xx_circuit(given_circuit)
result = execute(xx_meas, backend = simulator, shots = num_shots).result()
counts = result.get_counts(xx_meas)
if '00' not in counts:
counts['00'] = 0
if '01' not in counts:
counts['01'] = 0
if '10' not in counts:
counts['10'] = 0
if '11' not in counts:
counts['11'] = 0
total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10']
xx = counts['00'] + counts['11'] - counts['01'] - counts['10']
xx = xx / total_counts
return xx
xx = measure_xx(hets_circuit)
print("<XX> =", str(xx))
def get_energy(given_circuit, num_shots = 10000):
zz = measure_zz(given_circuit, num_shots = num_shots)
iz = measure_iz(given_circuit, num_shots = num_shots)
zi = measure_zi(given_circuit, num_shots = num_shots)
xx = measure_xx(given_circuit, num_shots = num_shots)
energy = (-1.0523732)*1 + (0.39793742)*iz + (-0.3979374)*zi + (-0.0112801)*zz + (0.18093119)*xx
return energy
energy = get_energy(hets_circuit)
print("The energy of the trial state is", str(energy))
hets_circuit_plus = None
hets_circuit_minus = None
### WRITE YOUR CODE BETWEEN THESE LINES - START
hets_circuit_plus = prepare_hets_circuit(2, pi/2 + 0.1*pi/2, pi/2)
hets_circuit_minus = prepare_hets_circuit(2, pi/2 - 0.1*pi/2, pi/2)
### WRITE YOUR CODE BETWEEN THESE LINES - END
energy_plus = get_energy(hets_circuit_plus, num_shots=100000)
energy_minus = get_energy(hets_circuit_minus, num_shots=100000)
print(energy_plus, energy_minus)
name = 'Pon Rahul M'
email = 'ponrahul.21it@licet.ac.in'
### Do not change the lines below
from grading_tools import grade
grade(answer=measure_xx_circuit(hets_circuit), name=name, email=email, labid='lab9', exerciseid='ex1')
grade(answer=hets_circuit_plus, name=name, email=email, labid='lab9', exerciseid='ex2')
grade(answer=hets_circuit_minus, name=name, email=email, labid='lab9', exerciseid='ex3')
energy_plus_100, energy_plus_1000, energy_plus_10000 = 0, 0, 0
energy_minus_100, energy_minus_1000, energy_minus_10000 = 0, 0, 0
### WRITE YOUR CODE BETWEEN THESE LINES - START
energy_plus_100 = get_energy(hets_circuit_plus, num_shots = 100)
energy_minus_100 = get_energy(hets_circuit_minus, num_shots = 100)
energy_plus_1000 = get_energy(hets_circuit_plus, num_shots = 1000)
energy_minus_1000 = get_energy(hets_circuit_minus, num_shots = 1000)
energy_plus_10000 = get_energy(hets_circuit_plus, num_shots = 10000)
energy_minus_10000 = get_energy(hets_circuit_minus, num_shots = 10000)
### WRITE YOUR CODE BETWEEN THESE LINES - END
print(energy_plus_100, energy_minus_100, "difference = ", energy_minus_100 - energy_plus_100)
print(energy_plus_1000, energy_minus_1000, "difference = ", energy_minus_1000 - energy_plus_1000)
print(energy_plus_10000, energy_minus_10000, "difference = ", energy_minus_10000 - energy_plus_10000)
### WRITE YOUR CODE BETWEEN THESE LINES - START
I = np.array([
[1, 0],
[0, 1]
])
X = np.array([
[0, 1],
[1, 0]
])
Z = np.array([
[1, 0],
[0, -1]
])
h2_hamiltonian = (-1.0523732) * np.kron(I, I) + \
(0.39793742) * np.kron(I, Z) + \
(-0.3979374) * np.kron(Z, I) + \
(-0.0112801) * np.kron(Z, Z) + \
(0.18093119) * np.kron(X, X)
from numpy import linalg as LA
eigenvalues, eigenvectors = LA.eig(h2_hamiltonian)
for ii, eigenvalue in enumerate(eigenvalues):
print(f"Eigenvector {eigenvectors[:,ii]} has energy {eigenvalue}")
exact_eigenvector = eigenvectors[:,np.argmin(eigenvalues)]
exact_eigenvalue = np.min(eigenvalues)
print()
print("Minimum energy is", exact_eigenvalue)
### WRITE YOUR CODE BETWEEN THESE LINES - END
|
https://github.com/rohitgit1/Quantum-Computing-Summer-School
|
rohitgit1
|
!pip install -U -r grading_tools/requirements.txt
from IPython.display import clear_output
clear_output()
import numpy as np; pi = np.pi
from qiskit import QuantumCircuit, Aer, execute
from qiskit.visualization import plot_histogram
from copy import deepcopy as make_copy
def prepare_hets_circuit(depth, angle1, angle2):
hets_circ = QuantumCircuit(depth)
hets_circ.ry(angle1, 0)
hets_circ.rz(angle1, 0)
hets_circ.ry(angle1, 1)
hets_circ.rz(angle1, 1)
for ii in range(depth):
hets_circ.cx(0,1)
hets_circ.ry(angle2,0)
hets_circ.rz(angle2,0)
hets_circ.ry(angle2,1)
hets_circ.rz(angle2,1)
return hets_circ
hets_circuit = prepare_hets_circuit(2, pi/2, pi/2)
hets_circuit.draw()
def measure_zz_circuit(given_circuit):
zz_meas = make_copy(given_circuit)
zz_meas.measure_all()
return zz_meas
zz_meas = measure_zz_circuit(hets_circuit)
zz_meas.draw()
simulator = Aer.get_backend('qasm_simulator')
result = execute(zz_meas, backend = simulator, shots=10000).result()
counts = result.get_counts(zz_meas)
plot_histogram(counts)
def measure_zz(given_circuit, num_shots = 10000):
zz_meas = measure_zz_circuit(given_circuit)
result = execute(zz_meas, backend = simulator, shots = num_shots).result()
counts = result.get_counts(zz_meas)
if '00' not in counts:
counts['00'] = 0
if '01' not in counts:
counts['01'] = 0
if '10' not in counts:
counts['10'] = 0
if '11' not in counts:
counts['11'] = 0
total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10']
zz = counts['00'] + counts['11'] - counts['01'] - counts['10']
zz = zz / total_counts
return zz
zz = measure_zz(hets_circuit)
print("<ZZ> =", str(zz))
def measure_zi(given_circuit, num_shots = 10000):
zz_meas = measure_zz_circuit(given_circuit)
result = execute(zz_meas, backend = simulator, shots = num_shots).result()
counts = result.get_counts(zz_meas)
if '00' not in counts:
counts['00'] = 0
if '01' not in counts:
counts['01'] = 0
if '10' not in counts:
counts['10'] = 0
if '11' not in counts:
counts['11'] = 0
total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10']
zi = counts['00'] - counts['11'] + counts['01'] - counts['10']
zi = zi / total_counts
return zi
def measure_iz(given_circuit, num_shots = 10000):
zz_meas = measure_zz_circuit(given_circuit)
result = execute(zz_meas, backend = simulator, shots = num_shots).result()
counts = result.get_counts(zz_meas)
if '00' not in counts:
counts['00'] = 0
if '01' not in counts:
counts['01'] = 0
if '10' not in counts:
counts['10'] = 0
if '11' not in counts:
counts['11'] = 0
total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10']
iz = counts['00'] - counts['11'] - counts['01'] + counts['10']
iz = iz / total_counts
return iz
zi = measure_zi(hets_circuit)
print("<ZI> =", str(zi))
iz = measure_iz(hets_circuit)
print("<IZ> =", str(iz))
def measure_xx_circuit(given_circuit):
xx_meas = make_copy(given_circuit)
### WRITE YOUR CODE BETWEEN THESE LINES - START
xx_meas.h(0)
xx_meas.h(1)
xx_meas.measure_all()
### WRITE YOUR CODE BETWEEN THESE LINES - END
return xx_meas
xx_meas = measure_xx_circuit(hets_circuit)
xx_meas.draw()
def measure_xx(given_circuit, num_shots = 10000):
xx_meas = measure_xx_circuit(given_circuit)
result = execute(xx_meas, backend = simulator, shots = num_shots).result()
counts = result.get_counts(xx_meas)
if '00' not in counts:
counts['00'] = 0
if '01' not in counts:
counts['01'] = 0
if '10' not in counts:
counts['10'] = 0
if '11' not in counts:
counts['11'] = 0
total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10']
xx = counts['00'] + counts['11'] - counts['01'] - counts['10']
xx = xx / total_counts
return xx
xx = measure_xx(hets_circuit)
print("<XX> =", str(xx))
def get_energy(given_circuit, num_shots = 10000):
zz = measure_zz(given_circuit, num_shots = num_shots)
iz = measure_iz(given_circuit, num_shots = num_shots)
zi = measure_zi(given_circuit, num_shots = num_shots)
xx = measure_xx(given_circuit, num_shots = num_shots)
energy = (-1.0523732)*1 + (0.39793742)*iz + (-0.3979374)*zi + (-0.0112801)*zz + (0.18093119)*xx
return energy
energy = get_energy(hets_circuit)
print("The energy of the trial state is", str(energy))
hets_circuit_plus = None
hets_circuit_minus = None
### WRITE YOUR CODE BETWEEN THESE LINES - START
hets_circuit_plus = prepare_hets_circuit(2, pi/2 + 0.1*pi/2, pi/2)
hets_circuit_minus = prepare_hets_circuit(2, pi/2 - 0.1*pi/2, pi/2)
### WRITE YOUR CODE BETWEEN THESE LINES - END
energy_plus = get_energy(hets_circuit_plus, num_shots=100000)
energy_minus = get_energy(hets_circuit_minus, num_shots=100000)
print(energy_plus, energy_minus)
name = 'Pon Rahul M'
email = 'ponrahul.21it@licet.ac.in'
### Do not change the lines below
from grading_tools import grade
grade(answer=measure_xx_circuit(hets_circuit), name=name, email=email, labid='lab9', exerciseid='ex1')
grade(answer=hets_circuit_plus, name=name, email=email, labid='lab9', exerciseid='ex2')
grade(answer=hets_circuit_minus, name=name, email=email, labid='lab9', exerciseid='ex3')
energy_plus_100, energy_plus_1000, energy_plus_10000 = 0, 0, 0
energy_minus_100, energy_minus_1000, energy_minus_10000 = 0, 0, 0
### WRITE YOUR CODE BETWEEN THESE LINES - START
energy_plus_100 = get_energy(hets_circuit_plus, num_shots = 100)
energy_minus_100 = get_energy(hets_circuit_minus, num_shots = 100)
energy_plus_1000 = get_energy(hets_circuit_plus, num_shots = 1000)
energy_minus_1000 = get_energy(hets_circuit_minus, num_shots = 1000)
energy_plus_10000 = get_energy(hets_circuit_plus, num_shots = 10000)
energy_minus_10000 = get_energy(hets_circuit_minus, num_shots = 10000)
### WRITE YOUR CODE BETWEEN THESE LINES - END
print(energy_plus_100, energy_minus_100, "difference = ", energy_minus_100 - energy_plus_100)
print(energy_plus_1000, energy_minus_1000, "difference = ", energy_minus_1000 - energy_plus_1000)
print(energy_plus_10000, energy_minus_10000, "difference = ", energy_minus_10000 - energy_plus_10000)
### WRITE YOUR CODE BETWEEN THESE LINES - START
I = np.array([
[1, 0],
[0, 1]
])
X = np.array([
[0, 1],
[1, 0]
])
Z = np.array([
[1, 0],
[0, -1]
])
h2_hamiltonian = (-1.0523732) * np.kron(I, I) + \
(0.39793742) * np.kron(I, Z) + \
(-0.3979374) * np.kron(Z, I) + \
(-0.0112801) * np.kron(Z, Z) + \
(0.18093119) * np.kron(X, X)
from numpy import linalg as LA
eigenvalues, eigenvectors = LA.eig(h2_hamiltonian)
for ii, eigenvalue in enumerate(eigenvalues):
print(f"Eigenvector {eigenvectors[:,ii]} has energy {eigenvalue}")
exact_eigenvector = eigenvectors[:,np.argmin(eigenvalues)]
exact_eigenvalue = np.min(eigenvalues)
print()
print("Minimum energy is", exact_eigenvalue)
### WRITE YOUR CODE BETWEEN THESE LINES - END
|
https://github.com/rohitgit1/Quantum-Computing-Summer-School
|
rohitgit1
|
!pip install -U -r grading_tools/requirements.txt
from IPython.display import clear_output
clear_output()
import numpy as np; pi = np.pi
from qiskit import QuantumCircuit, Aer, execute
from qiskit.visualization import plot_histogram
from copy import deepcopy as make_copy
def prepare_hets_circuit(depth, angle1, angle2):
hets_circ = QuantumCircuit(depth)
hets_circ.ry(angle1, 0)
hets_circ.rz(angle1, 0)
hets_circ.ry(angle1, 1)
hets_circ.rz(angle1, 1)
for ii in range(depth):
hets_circ.cx(0,1)
hets_circ.ry(angle2,0)
hets_circ.rz(angle2,0)
hets_circ.ry(angle2,1)
hets_circ.rz(angle2,1)
return hets_circ
hets_circuit = prepare_hets_circuit(2, pi/2, pi/2)
hets_circuit.draw()
def measure_zz_circuit(given_circuit):
zz_meas = make_copy(given_circuit)
zz_meas.measure_all()
return zz_meas
zz_meas = measure_zz_circuit(hets_circuit)
zz_meas.draw()
simulator = Aer.get_backend('qasm_simulator')
result = execute(zz_meas, backend = simulator, shots=10000).result()
counts = result.get_counts(zz_meas)
plot_histogram(counts)
def measure_zz(given_circuit, num_shots = 10000):
zz_meas = measure_zz_circuit(given_circuit)
result = execute(zz_meas, backend = simulator, shots = num_shots).result()
counts = result.get_counts(zz_meas)
if '00' not in counts:
counts['00'] = 0
if '01' not in counts:
counts['01'] = 0
if '10' not in counts:
counts['10'] = 0
if '11' not in counts:
counts['11'] = 0
total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10']
zz = counts['00'] + counts['11'] - counts['01'] - counts['10']
zz = zz / total_counts
return zz
zz = measure_zz(hets_circuit)
print("<ZZ> =", str(zz))
def measure_zi(given_circuit, num_shots = 10000):
zz_meas = measure_zz_circuit(given_circuit)
result = execute(zz_meas, backend = simulator, shots = num_shots).result()
counts = result.get_counts(zz_meas)
if '00' not in counts:
counts['00'] = 0
if '01' not in counts:
counts['01'] = 0
if '10' not in counts:
counts['10'] = 0
if '11' not in counts:
counts['11'] = 0
total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10']
zi = counts['00'] - counts['11'] + counts['01'] - counts['10']
zi = zi / total_counts
return zi
def measure_iz(given_circuit, num_shots = 10000):
zz_meas = measure_zz_circuit(given_circuit)
result = execute(zz_meas, backend = simulator, shots = num_shots).result()
counts = result.get_counts(zz_meas)
if '00' not in counts:
counts['00'] = 0
if '01' not in counts:
counts['01'] = 0
if '10' not in counts:
counts['10'] = 0
if '11' not in counts:
counts['11'] = 0
total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10']
iz = counts['00'] - counts['11'] - counts['01'] + counts['10']
iz = iz / total_counts
return iz
zi = measure_zi(hets_circuit)
print("<ZI> =", str(zi))
iz = measure_iz(hets_circuit)
print("<IZ> =", str(iz))
def measure_xx_circuit(given_circuit):
xx_meas = make_copy(given_circuit)
### WRITE YOUR CODE BETWEEN THESE LINES - START
xx_meas.h(0)
xx_meas.h(1)
xx_meas.measure_all()
### WRITE YOUR CODE BETWEEN THESE LINES - END
return xx_meas
xx_meas = measure_xx_circuit(hets_circuit)
xx_meas.draw()
def measure_xx(given_circuit, num_shots = 10000):
xx_meas = measure_xx_circuit(given_circuit)
result = execute(xx_meas, backend = simulator, shots = num_shots).result()
counts = result.get_counts(xx_meas)
if '00' not in counts:
counts['00'] = 0
if '01' not in counts:
counts['01'] = 0
if '10' not in counts:
counts['10'] = 0
if '11' not in counts:
counts['11'] = 0
total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10']
xx = counts['00'] + counts['11'] - counts['01'] - counts['10']
xx = xx / total_counts
return xx
xx = measure_xx(hets_circuit)
print("<XX> =", str(xx))
def get_energy(given_circuit, num_shots = 10000):
zz = measure_zz(given_circuit, num_shots = num_shots)
iz = measure_iz(given_circuit, num_shots = num_shots)
zi = measure_zi(given_circuit, num_shots = num_shots)
xx = measure_xx(given_circuit, num_shots = num_shots)
energy = (-1.0523732)*1 + (0.39793742)*iz + (-0.3979374)*zi + (-0.0112801)*zz + (0.18093119)*xx
return energy
energy = get_energy(hets_circuit)
print("The energy of the trial state is", str(energy))
hets_circuit_plus = None
hets_circuit_minus = None
### WRITE YOUR CODE BETWEEN THESE LINES - START
hets_circuit_plus = prepare_hets_circuit(2, pi/2 + 0.1*pi/2, pi/2)
hets_circuit_minus = prepare_hets_circuit(2, pi/2 - 0.1*pi/2, pi/2)
### WRITE YOUR CODE BETWEEN THESE LINES - END
energy_plus = get_energy(hets_circuit_plus, num_shots=100000)
energy_minus = get_energy(hets_circuit_minus, num_shots=100000)
print(energy_plus, energy_minus)
name = 'Pon Rahul M'
email = 'ponrahul.21it@licet.ac.in'
### Do not change the lines below
from grading_tools import grade
grade(answer=measure_xx_circuit(hets_circuit), name=name, email=email, labid='lab9', exerciseid='ex1')
grade(answer=hets_circuit_plus, name=name, email=email, labid='lab9', exerciseid='ex2')
grade(answer=hets_circuit_minus, name=name, email=email, labid='lab9', exerciseid='ex3')
energy_plus_100, energy_plus_1000, energy_plus_10000 = 0, 0, 0
energy_minus_100, energy_minus_1000, energy_minus_10000 = 0, 0, 0
### WRITE YOUR CODE BETWEEN THESE LINES - START
energy_plus_100 = get_energy(hets_circuit_plus, num_shots = 100)
energy_minus_100 = get_energy(hets_circuit_minus, num_shots = 100)
energy_plus_1000 = get_energy(hets_circuit_plus, num_shots = 1000)
energy_minus_1000 = get_energy(hets_circuit_minus, num_shots = 1000)
energy_plus_10000 = get_energy(hets_circuit_plus, num_shots = 10000)
energy_minus_10000 = get_energy(hets_circuit_minus, num_shots = 10000)
### WRITE YOUR CODE BETWEEN THESE LINES - END
print(energy_plus_100, energy_minus_100, "difference = ", energy_minus_100 - energy_plus_100)
print(energy_plus_1000, energy_minus_1000, "difference = ", energy_minus_1000 - energy_plus_1000)
print(energy_plus_10000, energy_minus_10000, "difference = ", energy_minus_10000 - energy_plus_10000)
### WRITE YOUR CODE BETWEEN THESE LINES - START
I = np.array([
[1, 0],
[0, 1]
])
X = np.array([
[0, 1],
[1, 0]
])
Z = np.array([
[1, 0],
[0, -1]
])
h2_hamiltonian = (-1.0523732) * np.kron(I, I) + \
(0.39793742) * np.kron(I, Z) + \
(-0.3979374) * np.kron(Z, I) + \
(-0.0112801) * np.kron(Z, Z) + \
(0.18093119) * np.kron(X, X)
from numpy import linalg as LA
eigenvalues, eigenvectors = LA.eig(h2_hamiltonian)
for ii, eigenvalue in enumerate(eigenvalues):
print(f"Eigenvector {eigenvectors[:,ii]} has energy {eigenvalue}")
exact_eigenvector = eigenvectors[:,np.argmin(eigenvalues)]
exact_eigenvalue = np.min(eigenvalues)
print()
print("Minimum energy is", exact_eigenvalue)
### WRITE YOUR CODE BETWEEN THESE LINES - END
|
https://github.com/rohitgit1/Quantum-Computing-Summer-School
|
rohitgit1
|
!pip install -U -r grading_tools/requirements.txt
from IPython.display import clear_output
clear_output()
import numpy as np; pi = np.pi
from qiskit import QuantumCircuit, Aer, execute
from qiskit.visualization import plot_histogram
from copy import deepcopy as make_copy
def prepare_hets_circuit(depth, angle1, angle2):
hets_circ = QuantumCircuit(depth)
hets_circ.ry(angle1, 0)
hets_circ.rz(angle1, 0)
hets_circ.ry(angle1, 1)
hets_circ.rz(angle1, 1)
for ii in range(depth):
hets_circ.cx(0,1)
hets_circ.ry(angle2,0)
hets_circ.rz(angle2,0)
hets_circ.ry(angle2,1)
hets_circ.rz(angle2,1)
return hets_circ
hets_circuit = prepare_hets_circuit(2, pi/2, pi/2)
hets_circuit.draw()
def measure_zz_circuit(given_circuit):
zz_meas = make_copy(given_circuit)
zz_meas.measure_all()
return zz_meas
zz_meas = measure_zz_circuit(hets_circuit)
zz_meas.draw()
simulator = Aer.get_backend('qasm_simulator')
result = execute(zz_meas, backend = simulator, shots=10000).result()
counts = result.get_counts(zz_meas)
plot_histogram(counts)
def measure_zz(given_circuit, num_shots = 10000):
zz_meas = measure_zz_circuit(given_circuit)
result = execute(zz_meas, backend = simulator, shots = num_shots).result()
counts = result.get_counts(zz_meas)
if '00' not in counts:
counts['00'] = 0
if '01' not in counts:
counts['01'] = 0
if '10' not in counts:
counts['10'] = 0
if '11' not in counts:
counts['11'] = 0
total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10']
zz = counts['00'] + counts['11'] - counts['01'] - counts['10']
zz = zz / total_counts
return zz
zz = measure_zz(hets_circuit)
print("<ZZ> =", str(zz))
def measure_zi(given_circuit, num_shots = 10000):
zz_meas = measure_zz_circuit(given_circuit)
result = execute(zz_meas, backend = simulator, shots = num_shots).result()
counts = result.get_counts(zz_meas)
if '00' not in counts:
counts['00'] = 0
if '01' not in counts:
counts['01'] = 0
if '10' not in counts:
counts['10'] = 0
if '11' not in counts:
counts['11'] = 0
total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10']
zi = counts['00'] - counts['11'] + counts['01'] - counts['10']
zi = zi / total_counts
return zi
def measure_iz(given_circuit, num_shots = 10000):
zz_meas = measure_zz_circuit(given_circuit)
result = execute(zz_meas, backend = simulator, shots = num_shots).result()
counts = result.get_counts(zz_meas)
if '00' not in counts:
counts['00'] = 0
if '01' not in counts:
counts['01'] = 0
if '10' not in counts:
counts['10'] = 0
if '11' not in counts:
counts['11'] = 0
total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10']
iz = counts['00'] - counts['11'] - counts['01'] + counts['10']
iz = iz / total_counts
return iz
zi = measure_zi(hets_circuit)
print("<ZI> =", str(zi))
iz = measure_iz(hets_circuit)
print("<IZ> =", str(iz))
def measure_xx_circuit(given_circuit):
xx_meas = make_copy(given_circuit)
### WRITE YOUR CODE BETWEEN THESE LINES - START
xx_meas.h(0)
xx_meas.h(1)
xx_meas.measure_all()
### WRITE YOUR CODE BETWEEN THESE LINES - END
return xx_meas
xx_meas = measure_xx_circuit(hets_circuit)
xx_meas.draw()
def measure_xx(given_circuit, num_shots = 10000):
xx_meas = measure_xx_circuit(given_circuit)
result = execute(xx_meas, backend = simulator, shots = num_shots).result()
counts = result.get_counts(xx_meas)
if '00' not in counts:
counts['00'] = 0
if '01' not in counts:
counts['01'] = 0
if '10' not in counts:
counts['10'] = 0
if '11' not in counts:
counts['11'] = 0
total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10']
xx = counts['00'] + counts['11'] - counts['01'] - counts['10']
xx = xx / total_counts
return xx
xx = measure_xx(hets_circuit)
print("<XX> =", str(xx))
def get_energy(given_circuit, num_shots = 10000):
zz = measure_zz(given_circuit, num_shots = num_shots)
iz = measure_iz(given_circuit, num_shots = num_shots)
zi = measure_zi(given_circuit, num_shots = num_shots)
xx = measure_xx(given_circuit, num_shots = num_shots)
energy = (-1.0523732)*1 + (0.39793742)*iz + (-0.3979374)*zi + (-0.0112801)*zz + (0.18093119)*xx
return energy
energy = get_energy(hets_circuit)
print("The energy of the trial state is", str(energy))
hets_circuit_plus = None
hets_circuit_minus = None
### WRITE YOUR CODE BETWEEN THESE LINES - START
hets_circuit_plus = prepare_hets_circuit(2, pi/2 + 0.1*pi/2, pi/2)
hets_circuit_minus = prepare_hets_circuit(2, pi/2 - 0.1*pi/2, pi/2)
### WRITE YOUR CODE BETWEEN THESE LINES - END
energy_plus = get_energy(hets_circuit_plus, num_shots=100000)
energy_minus = get_energy(hets_circuit_minus, num_shots=100000)
print(energy_plus, energy_minus)
name = 'Pon Rahul M'
email = 'ponrahul.21it@licet.ac.in'
### Do not change the lines below
from grading_tools import grade
grade(answer=measure_xx_circuit(hets_circuit), name=name, email=email, labid='lab9', exerciseid='ex1')
grade(answer=hets_circuit_plus, name=name, email=email, labid='lab9', exerciseid='ex2')
grade(answer=hets_circuit_minus, name=name, email=email, labid='lab9', exerciseid='ex3')
energy_plus_100, energy_plus_1000, energy_plus_10000 = 0, 0, 0
energy_minus_100, energy_minus_1000, energy_minus_10000 = 0, 0, 0
### WRITE YOUR CODE BETWEEN THESE LINES - START
energy_plus_100 = get_energy(hets_circuit_plus, num_shots = 100)
energy_minus_100 = get_energy(hets_circuit_minus, num_shots = 100)
energy_plus_1000 = get_energy(hets_circuit_plus, num_shots = 1000)
energy_minus_1000 = get_energy(hets_circuit_minus, num_shots = 1000)
energy_plus_10000 = get_energy(hets_circuit_plus, num_shots = 10000)
energy_minus_10000 = get_energy(hets_circuit_minus, num_shots = 10000)
### WRITE YOUR CODE BETWEEN THESE LINES - END
print(energy_plus_100, energy_minus_100, "difference = ", energy_minus_100 - energy_plus_100)
print(energy_plus_1000, energy_minus_1000, "difference = ", energy_minus_1000 - energy_plus_1000)
print(energy_plus_10000, energy_minus_10000, "difference = ", energy_minus_10000 - energy_plus_10000)
### WRITE YOUR CODE BETWEEN THESE LINES - START
I = np.array([
[1, 0],
[0, 1]
])
X = np.array([
[0, 1],
[1, 0]
])
Z = np.array([
[1, 0],
[0, -1]
])
h2_hamiltonian = (-1.0523732) * np.kron(I, I) + \
(0.39793742) * np.kron(I, Z) + \
(-0.3979374) * np.kron(Z, I) + \
(-0.0112801) * np.kron(Z, Z) + \
(0.18093119) * np.kron(X, X)
from numpy import linalg as LA
eigenvalues, eigenvectors = LA.eig(h2_hamiltonian)
for ii, eigenvalue in enumerate(eigenvalues):
print(f"Eigenvector {eigenvectors[:,ii]} has energy {eigenvalue}")
exact_eigenvector = eigenvectors[:,np.argmin(eigenvalues)]
exact_eigenvalue = np.min(eigenvalues)
print()
print("Minimum energy is", exact_eigenvalue)
### WRITE YOUR CODE BETWEEN THESE LINES - END
|
https://github.com/rohitgit1/Quantum-Computing-Summer-School
|
rohitgit1
|
!pip install -U -r grading_tools/requirements.txt
from IPython.display import clear_output
clear_output()
import numpy as np; pi = np.pi
from qiskit import QuantumCircuit, Aer, execute
from qiskit.visualization import plot_histogram
from copy import deepcopy as make_copy
def prepare_hets_circuit(depth, angle1, angle2):
hets_circ = QuantumCircuit(depth)
hets_circ.ry(angle1, 0)
hets_circ.rz(angle1, 0)
hets_circ.ry(angle1, 1)
hets_circ.rz(angle1, 1)
for ii in range(depth):
hets_circ.cx(0,1)
hets_circ.ry(angle2,0)
hets_circ.rz(angle2,0)
hets_circ.ry(angle2,1)
hets_circ.rz(angle2,1)
return hets_circ
hets_circuit = prepare_hets_circuit(2, pi/2, pi/2)
hets_circuit.draw()
def measure_zz_circuit(given_circuit):
zz_meas = make_copy(given_circuit)
zz_meas.measure_all()
return zz_meas
zz_meas = measure_zz_circuit(hets_circuit)
zz_meas.draw()
simulator = Aer.get_backend('qasm_simulator')
result = execute(zz_meas, backend = simulator, shots=10000).result()
counts = result.get_counts(zz_meas)
plot_histogram(counts)
def measure_zz(given_circuit, num_shots = 10000):
zz_meas = measure_zz_circuit(given_circuit)
result = execute(zz_meas, backend = simulator, shots = num_shots).result()
counts = result.get_counts(zz_meas)
if '00' not in counts:
counts['00'] = 0
if '01' not in counts:
counts['01'] = 0
if '10' not in counts:
counts['10'] = 0
if '11' not in counts:
counts['11'] = 0
total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10']
zz = counts['00'] + counts['11'] - counts['01'] - counts['10']
zz = zz / total_counts
return zz
zz = measure_zz(hets_circuit)
print("<ZZ> =", str(zz))
def measure_zi(given_circuit, num_shots = 10000):
zz_meas = measure_zz_circuit(given_circuit)
result = execute(zz_meas, backend = simulator, shots = num_shots).result()
counts = result.get_counts(zz_meas)
if '00' not in counts:
counts['00'] = 0
if '01' not in counts:
counts['01'] = 0
if '10' not in counts:
counts['10'] = 0
if '11' not in counts:
counts['11'] = 0
total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10']
zi = counts['00'] - counts['11'] + counts['01'] - counts['10']
zi = zi / total_counts
return zi
def measure_iz(given_circuit, num_shots = 10000):
zz_meas = measure_zz_circuit(given_circuit)
result = execute(zz_meas, backend = simulator, shots = num_shots).result()
counts = result.get_counts(zz_meas)
if '00' not in counts:
counts['00'] = 0
if '01' not in counts:
counts['01'] = 0
if '10' not in counts:
counts['10'] = 0
if '11' not in counts:
counts['11'] = 0
total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10']
iz = counts['00'] - counts['11'] - counts['01'] + counts['10']
iz = iz / total_counts
return iz
zi = measure_zi(hets_circuit)
print("<ZI> =", str(zi))
iz = measure_iz(hets_circuit)
print("<IZ> =", str(iz))
def measure_xx_circuit(given_circuit):
xx_meas = make_copy(given_circuit)
### WRITE YOUR CODE BETWEEN THESE LINES - START
xx_meas.h(0)
xx_meas.h(1)
xx_meas.measure_all()
### WRITE YOUR CODE BETWEEN THESE LINES - END
return xx_meas
xx_meas = measure_xx_circuit(hets_circuit)
xx_meas.draw()
def measure_xx(given_circuit, num_shots = 10000):
xx_meas = measure_xx_circuit(given_circuit)
result = execute(xx_meas, backend = simulator, shots = num_shots).result()
counts = result.get_counts(xx_meas)
if '00' not in counts:
counts['00'] = 0
if '01' not in counts:
counts['01'] = 0
if '10' not in counts:
counts['10'] = 0
if '11' not in counts:
counts['11'] = 0
total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10']
xx = counts['00'] + counts['11'] - counts['01'] - counts['10']
xx = xx / total_counts
return xx
xx = measure_xx(hets_circuit)
print("<XX> =", str(xx))
def get_energy(given_circuit, num_shots = 10000):
zz = measure_zz(given_circuit, num_shots = num_shots)
iz = measure_iz(given_circuit, num_shots = num_shots)
zi = measure_zi(given_circuit, num_shots = num_shots)
xx = measure_xx(given_circuit, num_shots = num_shots)
energy = (-1.0523732)*1 + (0.39793742)*iz + (-0.3979374)*zi + (-0.0112801)*zz + (0.18093119)*xx
return energy
energy = get_energy(hets_circuit)
print("The energy of the trial state is", str(energy))
hets_circuit_plus = None
hets_circuit_minus = None
### WRITE YOUR CODE BETWEEN THESE LINES - START
hets_circuit_plus = prepare_hets_circuit(2, pi/2 + 0.1*pi/2, pi/2)
hets_circuit_minus = prepare_hets_circuit(2, pi/2 - 0.1*pi/2, pi/2)
### WRITE YOUR CODE BETWEEN THESE LINES - END
energy_plus = get_energy(hets_circuit_plus, num_shots=100000)
energy_minus = get_energy(hets_circuit_minus, num_shots=100000)
print(energy_plus, energy_minus)
name = 'Pon Rahul M'
email = 'ponrahul.21it@licet.ac.in'
### Do not change the lines below
from grading_tools import grade
grade(answer=measure_xx_circuit(hets_circuit), name=name, email=email, labid='lab9', exerciseid='ex1')
grade(answer=hets_circuit_plus, name=name, email=email, labid='lab9', exerciseid='ex2')
grade(answer=hets_circuit_minus, name=name, email=email, labid='lab9', exerciseid='ex3')
energy_plus_100, energy_plus_1000, energy_plus_10000 = 0, 0, 0
energy_minus_100, energy_minus_1000, energy_minus_10000 = 0, 0, 0
### WRITE YOUR CODE BETWEEN THESE LINES - START
energy_plus_100 = get_energy(hets_circuit_plus, num_shots = 100)
energy_minus_100 = get_energy(hets_circuit_minus, num_shots = 100)
energy_plus_1000 = get_energy(hets_circuit_plus, num_shots = 1000)
energy_minus_1000 = get_energy(hets_circuit_minus, num_shots = 1000)
energy_plus_10000 = get_energy(hets_circuit_plus, num_shots = 10000)
energy_minus_10000 = get_energy(hets_circuit_minus, num_shots = 10000)
### WRITE YOUR CODE BETWEEN THESE LINES - END
print(energy_plus_100, energy_minus_100, "difference = ", energy_minus_100 - energy_plus_100)
print(energy_plus_1000, energy_minus_1000, "difference = ", energy_minus_1000 - energy_plus_1000)
print(energy_plus_10000, energy_minus_10000, "difference = ", energy_minus_10000 - energy_plus_10000)
### WRITE YOUR CODE BETWEEN THESE LINES - START
I = np.array([
[1, 0],
[0, 1]
])
X = np.array([
[0, 1],
[1, 0]
])
Z = np.array([
[1, 0],
[0, -1]
])
h2_hamiltonian = (-1.0523732) * np.kron(I, I) + \
(0.39793742) * np.kron(I, Z) + \
(-0.3979374) * np.kron(Z, I) + \
(-0.0112801) * np.kron(Z, Z) + \
(0.18093119) * np.kron(X, X)
from numpy import linalg as LA
eigenvalues, eigenvectors = LA.eig(h2_hamiltonian)
for ii, eigenvalue in enumerate(eigenvalues):
print(f"Eigenvector {eigenvectors[:,ii]} has energy {eigenvalue}")
exact_eigenvector = eigenvectors[:,np.argmin(eigenvalues)]
exact_eigenvalue = np.min(eigenvalues)
print()
print("Minimum energy is", exact_eigenvalue)
### WRITE YOUR CODE BETWEEN THESE LINES - END
|
https://github.com/rohitgit1/Quantum-Computing-Summer-School
|
rohitgit1
|
!pip install -U -r grading_tools/requirements.txt
from IPython.display import clear_output
clear_output()
import numpy as np; pi = np.pi
from qiskit import QuantumCircuit, Aer, execute
from qiskit.visualization import plot_histogram
from copy import deepcopy as make_copy
def prepare_hets_circuit(depth, angle1, angle2):
hets_circ = QuantumCircuit(depth)
hets_circ.ry(angle1, 0)
hets_circ.rz(angle1, 0)
hets_circ.ry(angle1, 1)
hets_circ.rz(angle1, 1)
for ii in range(depth):
hets_circ.cx(0,1)
hets_circ.ry(angle2,0)
hets_circ.rz(angle2,0)
hets_circ.ry(angle2,1)
hets_circ.rz(angle2,1)
return hets_circ
hets_circuit = prepare_hets_circuit(2, pi/2, pi/2)
hets_circuit.draw()
def measure_zz_circuit(given_circuit):
zz_meas = make_copy(given_circuit)
zz_meas.measure_all()
return zz_meas
zz_meas = measure_zz_circuit(hets_circuit)
zz_meas.draw()
simulator = Aer.get_backend('qasm_simulator')
result = execute(zz_meas, backend = simulator, shots=10000).result()
counts = result.get_counts(zz_meas)
plot_histogram(counts)
def measure_zz(given_circuit, num_shots = 10000):
zz_meas = measure_zz_circuit(given_circuit)
result = execute(zz_meas, backend = simulator, shots = num_shots).result()
counts = result.get_counts(zz_meas)
if '00' not in counts:
counts['00'] = 0
if '01' not in counts:
counts['01'] = 0
if '10' not in counts:
counts['10'] = 0
if '11' not in counts:
counts['11'] = 0
total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10']
zz = counts['00'] + counts['11'] - counts['01'] - counts['10']
zz = zz / total_counts
return zz
zz = measure_zz(hets_circuit)
print("<ZZ> =", str(zz))
def measure_zi(given_circuit, num_shots = 10000):
zz_meas = measure_zz_circuit(given_circuit)
result = execute(zz_meas, backend = simulator, shots = num_shots).result()
counts = result.get_counts(zz_meas)
if '00' not in counts:
counts['00'] = 0
if '01' not in counts:
counts['01'] = 0
if '10' not in counts:
counts['10'] = 0
if '11' not in counts:
counts['11'] = 0
total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10']
zi = counts['00'] - counts['11'] + counts['01'] - counts['10']
zi = zi / total_counts
return zi
def measure_iz(given_circuit, num_shots = 10000):
zz_meas = measure_zz_circuit(given_circuit)
result = execute(zz_meas, backend = simulator, shots = num_shots).result()
counts = result.get_counts(zz_meas)
if '00' not in counts:
counts['00'] = 0
if '01' not in counts:
counts['01'] = 0
if '10' not in counts:
counts['10'] = 0
if '11' not in counts:
counts['11'] = 0
total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10']
iz = counts['00'] - counts['11'] - counts['01'] + counts['10']
iz = iz / total_counts
return iz
zi = measure_zi(hets_circuit)
print("<ZI> =", str(zi))
iz = measure_iz(hets_circuit)
print("<IZ> =", str(iz))
def measure_xx_circuit(given_circuit):
xx_meas = make_copy(given_circuit)
### WRITE YOUR CODE BETWEEN THESE LINES - START
xx_meas.h(0)
xx_meas.h(1)
xx_meas.measure_all()
### WRITE YOUR CODE BETWEEN THESE LINES - END
return xx_meas
xx_meas = measure_xx_circuit(hets_circuit)
xx_meas.draw()
def measure_xx(given_circuit, num_shots = 10000):
xx_meas = measure_xx_circuit(given_circuit)
result = execute(xx_meas, backend = simulator, shots = num_shots).result()
counts = result.get_counts(xx_meas)
if '00' not in counts:
counts['00'] = 0
if '01' not in counts:
counts['01'] = 0
if '10' not in counts:
counts['10'] = 0
if '11' not in counts:
counts['11'] = 0
total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10']
xx = counts['00'] + counts['11'] - counts['01'] - counts['10']
xx = xx / total_counts
return xx
xx = measure_xx(hets_circuit)
print("<XX> =", str(xx))
def get_energy(given_circuit, num_shots = 10000):
zz = measure_zz(given_circuit, num_shots = num_shots)
iz = measure_iz(given_circuit, num_shots = num_shots)
zi = measure_zi(given_circuit, num_shots = num_shots)
xx = measure_xx(given_circuit, num_shots = num_shots)
energy = (-1.0523732)*1 + (0.39793742)*iz + (-0.3979374)*zi + (-0.0112801)*zz + (0.18093119)*xx
return energy
energy = get_energy(hets_circuit)
print("The energy of the trial state is", str(energy))
hets_circuit_plus = None
hets_circuit_minus = None
### WRITE YOUR CODE BETWEEN THESE LINES - START
hets_circuit_plus = prepare_hets_circuit(2, pi/2 + 0.1*pi/2, pi/2)
hets_circuit_minus = prepare_hets_circuit(2, pi/2 - 0.1*pi/2, pi/2)
### WRITE YOUR CODE BETWEEN THESE LINES - END
energy_plus = get_energy(hets_circuit_plus, num_shots=100000)
energy_minus = get_energy(hets_circuit_minus, num_shots=100000)
print(energy_plus, energy_minus)
name = 'Pon Rahul M'
email = 'ponrahul.21it@licet.ac.in'
### Do not change the lines below
from grading_tools import grade
grade(answer=measure_xx_circuit(hets_circuit), name=name, email=email, labid='lab9', exerciseid='ex1')
grade(answer=hets_circuit_plus, name=name, email=email, labid='lab9', exerciseid='ex2')
grade(answer=hets_circuit_minus, name=name, email=email, labid='lab9', exerciseid='ex3')
energy_plus_100, energy_plus_1000, energy_plus_10000 = 0, 0, 0
energy_minus_100, energy_minus_1000, energy_minus_10000 = 0, 0, 0
### WRITE YOUR CODE BETWEEN THESE LINES - START
energy_plus_100 = get_energy(hets_circuit_plus, num_shots = 100)
energy_minus_100 = get_energy(hets_circuit_minus, num_shots = 100)
energy_plus_1000 = get_energy(hets_circuit_plus, num_shots = 1000)
energy_minus_1000 = get_energy(hets_circuit_minus, num_shots = 1000)
energy_plus_10000 = get_energy(hets_circuit_plus, num_shots = 10000)
energy_minus_10000 = get_energy(hets_circuit_minus, num_shots = 10000)
### WRITE YOUR CODE BETWEEN THESE LINES - END
print(energy_plus_100, energy_minus_100, "difference = ", energy_minus_100 - energy_plus_100)
print(energy_plus_1000, energy_minus_1000, "difference = ", energy_minus_1000 - energy_plus_1000)
print(energy_plus_10000, energy_minus_10000, "difference = ", energy_minus_10000 - energy_plus_10000)
### WRITE YOUR CODE BETWEEN THESE LINES - START
I = np.array([
[1, 0],
[0, 1]
])
X = np.array([
[0, 1],
[1, 0]
])
Z = np.array([
[1, 0],
[0, -1]
])
h2_hamiltonian = (-1.0523732) * np.kron(I, I) + \
(0.39793742) * np.kron(I, Z) + \
(-0.3979374) * np.kron(Z, I) + \
(-0.0112801) * np.kron(Z, Z) + \
(0.18093119) * np.kron(X, X)
from numpy import linalg as LA
eigenvalues, eigenvectors = LA.eig(h2_hamiltonian)
for ii, eigenvalue in enumerate(eigenvalues):
print(f"Eigenvector {eigenvectors[:,ii]} has energy {eigenvalue}")
exact_eigenvector = eigenvectors[:,np.argmin(eigenvalues)]
exact_eigenvalue = np.min(eigenvalues)
print()
print("Minimum energy is", exact_eigenvalue)
### WRITE YOUR CODE BETWEEN THESE LINES - END
|
https://github.com/rohitgit1/Quantum-Computing-Summer-School
|
rohitgit1
|
from qiskit.quantum_info import Statevector
from qiskit.visualization import plot_bloch_multivector
excited = Statevector.from_int(1, 2)
plot_bloch_multivector(excited.data)
from qiskit.tools.jupyter import *
from qiskit import IBMQ
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q', group='open', project='main')
backend = provider.get_backend('ibmq_armonk')
backend_config = backend.configuration()
assert backend_config.open_pulse, "Backend doesn't support Pulse"
dt = backend_config.dt
print(f"Sampling time: {dt*1e9} ns")
backend_defaults = backend.defaults()
import numpy as np
# unit conversion factors -> all backend properties returned in SI (Hz, sec, etc)
GHz = 1.0e9 # Gigahertz
MHz = 1.0e6 # Megahertz
us = 1.0e-6 # Microseconds
ns = 1.0e-9 # Nanoseconds
# We will find the qubit frequency for the following qubit.
qubit = 0
# The Rabi sweep will be at the given qubit frequency.
center_frequency_Hz = backend_defaults.qubit_freq_est[qubit] # The default frequency is given in Hz
# warning: this will change in a future release
print(f"Qubit {qubit} has an estimated frequency of {center_frequency_Hz / GHz} GHz.")
from qiskit import pulse, assemble # This is where we access all of our Pulse features!
from qiskit.pulse import Play
from qiskit.pulse import pulse_lib # This Pulse module helps us build sampled pulses for common pulse shapes
### Collect the necessary channels
drive_chan = pulse.DriveChannel(qubit)
meas_chan = pulse.MeasureChannel(qubit)
acq_chan = pulse.AcquireChannel(qubit)
inst_sched_map = backend_defaults.instruction_schedule_map
measure = inst_sched_map.get('measure', qubits=[0])
# Rabi experiment parameters
# Drive amplitude values to iterate over: 50 amplitudes evenly spaced from 0 to 0.75
num_rabi_points = 50
drive_amp_min = 0
drive_amp_max = 0.75
drive_amps = np.linspace(drive_amp_min, drive_amp_max, num_rabi_points)
# drive waveforms mush be in units of 16
drive_sigma = 80 # in dt
drive_samples = 8*drive_sigma # in dt
# Build the Rabi experiments:
# A drive pulse at the qubit frequency, followed by a measurement,
# where we vary the drive amplitude each time.
rabi_schedules = []
for drive_amp in drive_amps:
rabi_pulse = pulse_lib.gaussian(duration=drive_samples, amp=drive_amp,
sigma=drive_sigma, name=f"Rabi drive amplitude = {drive_amp}")
this_schedule = pulse.Schedule(name=f"Rabi drive amplitude = {drive_amp}")
this_schedule += Play(rabi_pulse, drive_chan)
# The left shift `<<` is special syntax meaning to shift the start time of the schedule by some duration
this_schedule += measure << this_schedule.duration
rabi_schedules.append(this_schedule)
rabi_schedules[-1].draw(label=True, scaling=1.0)
# assemble the schedules into a Qobj
num_shots_per_point = 1024
rabi_experiment_program = assemble(rabi_schedules,
backend=backend,
meas_level=1,
meas_return='avg',
shots=num_shots_per_point,
schedule_los=[{drive_chan: center_frequency_Hz}]
* num_rabi_points)
# RUN the job on a real device
#job = backend.run(rabi_experiment_program)
#print(job.job_id())
#from qiskit.tools.monitor import job_monitor
#job_monitor(job)
# OR retreive result from previous run
job = backend.retrieve_job("5ef3bf17dc3044001186c011")
rabi_results = job.result()
import matplotlib.pyplot as plt
plt.style.use('dark_background')
scale_factor = 1e-14
# center data around 0
def baseline_remove(values):
return np.array(values) - np.mean(values)
rabi_values = []
for i in range(num_rabi_points):
# Get the results for `qubit` from the ith experiment
rabi_values.append(rabi_results.get_memory(i)[qubit]*scale_factor)
rabi_values = np.real(baseline_remove(rabi_values))
plt.xlabel("Drive amp [a.u.]")
plt.ylabel("Measured signal [a.u.]")
plt.scatter(drive_amps, rabi_values, color='white') # plot real part of Rabi values
plt.show()
from scipy.optimize import curve_fit
def fit_function(x_values, y_values, function, init_params):
fitparams, conv = curve_fit(function, x_values, y_values, init_params)
y_fit = function(x_values, *fitparams)
return fitparams, y_fit
fit_params, y_fit = fit_function(drive_amps,
rabi_values,
lambda x, A, B, drive_period, phi: (A*np.cos(2*np.pi*x/drive_period - phi) + B),
[10, 0.1, 0.6, 0])
plt.scatter(drive_amps, rabi_values, color='white')
plt.plot(drive_amps, y_fit, color='red')
drive_period = fit_params[2] # get period of rabi oscillation
plt.axvline(drive_period/2, color='red', linestyle='--')
plt.axvline(drive_period, color='red', linestyle='--')
plt.annotate("", xy=(drive_period, 0), xytext=(drive_period/2,0), arrowprops=dict(arrowstyle="<->", color='red'))
plt.xlabel("Drive amp [a.u.]", fontsize=15)
plt.ylabel("Measured signal [a.u.]", fontsize=15)
plt.show()
pi_amp = abs(drive_period / 2)
print(f"Pi Amplitude = {pi_amp}")
# Drive parameters
# The drive amplitude for pi/2 is simply half the amplitude of the pi pulse
drive_amp = pi_amp / 2
# x_90 is a concise way to say pi_over_2; i.e., an X rotation of 90 degrees
x90_pulse = pulse_lib.gaussian(duration=drive_samples,
amp=drive_amp,
sigma=drive_sigma,
name='x90_pulse')
# Ramsey experiment parameters
time_max_us = 1.8
time_step_us = 0.025
times_us = np.arange(0.1, time_max_us, time_step_us)
# Convert to units of dt
delay_times_dt = times_us * us / dt
# create schedules for Ramsey experiment
ramsey_schedules = []
for delay in delay_times_dt:
this_schedule = pulse.Schedule(name=f"Ramsey delay = {delay * dt / us} us")
this_schedule += Play(x90_pulse, drive_chan)
this_schedule += Play(x90_pulse, drive_chan) << this_schedule.duration + int(delay)
this_schedule += measure << this_schedule.duration
ramsey_schedules.append(this_schedule)
ramsey_schedules[-1].draw(label=True, scaling=1.0)
# Execution settings
num_shots = 256
detuning_MHz = 2
ramsey_frequency = round(center_frequency_Hz + detuning_MHz * MHz, 6) # need ramsey freq in Hz
ramsey_program = assemble(ramsey_schedules,
backend=backend,
meas_level=1,
meas_return='avg',
shots=num_shots,
schedule_los=[{drive_chan: ramsey_frequency}]*len(ramsey_schedules)
)
# RUN the job on a real device
#job = backend.run(ramsey_experiment_program)
#print(job.job_id())
#from qiskit.tools.monitor import job_monitor
#job_monitor(job)
# OR retreive job from previous run
job = backend.retrieve_job('5ef3ed3a84b1b70012374317')
ramsey_results = job.result()
ramsey_values = []
for i in range(len(times_us)):
ramsey_values.append(ramsey_results.get_memory(i)[qubit]*scale_factor)
fit_params, y_fit = fit_function(times_us, np.real(ramsey_values),
lambda x, A, del_f_MHz, C, B: (
A * np.cos(2*np.pi*del_f_MHz*x - C) + B
),
[5, 1./0.4, 0, 0.25]
)
# Off-resonance component
_, del_f_MHz, _, _, = fit_params # freq is MHz since times in us
plt.scatter(times_us, np.real(ramsey_values), color='white')
plt.plot(times_us, y_fit, color='red', label=f"df = {del_f_MHz:.2f} MHz")
plt.xlim(0, np.max(times_us))
plt.xlabel('Delay between X90 pulses [$\mu$s]', fontsize=15)
plt.ylabel('Measured Signal [a.u.]', fontsize=15)
plt.title('Ramsey Experiment', fontsize=15)
plt.legend()
plt.show()
|
https://github.com/rohitgit1/Quantum-Computing-Summer-School
|
rohitgit1
|
!pip install -U -r grading_tools/requirements.txt
from IPython.display import clear_output
clear_output()
# our backend is the Pulse Simulator
from resources import helper
from qiskit.providers.aer import PulseSimulator
backend_sim = PulseSimulator()
# sample duration for pulse instructions
dt = 1e-9
# create the model
duffing_model = helper.get_transmon(dt)
# get qubit frequency from Duffing model
qubit_lo_freq = duffing_model.hamiltonian.get_qubit_lo_from_drift()
import numpy as np
# visualization tools
import matplotlib.pyplot as plt
plt.style.use('dark_background')
# unit conversion factors -> all backend properties returned in SI (Hz, sec, etc)
GHz = 1.0e9 # Gigahertz
MHz = 1.0e6 # Megahertz
kHz = 1.0e3 # kilohertz
us = 1.0e-6 # microseconds
ns = 1.0e-9 # nanoseconds
from qiskit import pulse
from qiskit.pulse import Play, Acquire
from qiskit.pulse.pulse_lib import GaussianSquare
# qubit to be used throughout the notebook
qubit = 0
### Collect the necessary channels
drive_chan = pulse.DriveChannel(qubit)
meas_chan = pulse.MeasureChannel(qubit)
acq_chan = pulse.AcquireChannel(qubit)
# Construct a measurement schedule and add it to an InstructionScheduleMap
meas_samples = 1200
meas_pulse = GaussianSquare(duration=meas_samples, amp=0.025, sigma=4, width=1150)
measure_sched = Play(meas_pulse, meas_chan) | Acquire(meas_samples, acq_chan, pulse.MemorySlot(qubit))
inst_map = pulse.InstructionScheduleMap()
inst_map.add('measure', [qubit], measure_sched)
# save the measurement/acquire pulse for later
measure = inst_map.get('measure', qubits=[qubit])
from qiskit.pulse import pulse_lib
# the same spect pulse used in every schedule
drive_amp = 0.9
drive_sigma = 16
drive_duration = 128
spec_pulse = pulse_lib.gaussian(duration=drive_duration, amp=drive_amp,
sigma=drive_sigma, name=f"Spec drive amplitude = {drive_amp}")
# Construct an np array of the frequencies for our experiment
spec_freqs_GHz = np.arange(5.0, 5.2, 0.005)
# Create the base schedule
# Start with drive pulse acting on the drive channel
spec_schedules = []
for freq in spec_freqs_GHz:
sb_spec_pulse = helper.apply_sideband(spec_pulse, qubit_lo_freq[0]-freq*GHz, dt)
spec_schedule = pulse.Schedule(name='SB Frequency = {}'.format(freq))
spec_schedule += Play(sb_spec_pulse, drive_chan)
# The left shift `<<` is special syntax meaning to shift the start time of the schedule by some duration
spec_schedule += measure << spec_schedule.duration
spec_schedules.append(spec_schedule)
spec_schedules[0].draw()
from qiskit import assemble
# assemble the schedules into a Qobj
spec01_qobj = assemble(**helper.get_params('spec01', globals()))
# run the simulation
spec01_result = backend_sim.run(spec01_qobj, duffing_model).result()
# retrieve the data from the experiment
spec01_values = helper.get_values_from_result(spec01_result, qubit)
fit_params, y_fit = helper.fit_lorentzian(spec_freqs_GHz, spec01_values, [5, 5, 1, 0])
f01 = fit_params[1]
plt.scatter(spec_freqs_GHz, np.real(spec01_values), color='white') # plot real part of sweep values
plt.plot(spec_freqs_GHz, y_fit, color='red')
plt.xlim([min(spec_freqs_GHz), max(spec_freqs_GHz)])
plt.xlabel("Frequency [GHz]")
plt.ylabel("Measured Signal [a.u.]")
plt.show()
print("01 Spectroscopy yields %f GHz"%f01)
x180_amp = 0.629070 #from lab 6 Rabi experiment
x_pulse = pulse_lib.gaussian(duration=drive_duration,
amp=x180_amp,
sigma=drive_sigma,
name='x_pulse')
anharmonicity_guess_GHz = -0.3
def build_spec12_pulse_schedule(freq):
sb12_spec_pulse = helper.apply_sideband(spec_pulse, (freq + anharmonicity_guess_GHz)*GHz, dt)
### create a 12 spectroscopy pulse schedule spec12_schedule (already done)
### play an x pulse on the drive channel
### play sidebanded spec pulse on the drive channel
### add measurement pulse to schedule
spec12_schedule = pulse.Schedule()
### WRITE YOUR CODE BETWEEN THESE LINES - START
spec12_schedule += Play(x_pulse, drive_chan)
spec12_schedule += Play(sb12_spec_pulse, drive_chan)
spec12_schedule += measure << spec12_schedule.duration
### WRITE YOUR CODE BETWEEN THESE LINES - STOP
return spec12_schedule
sb_freqs_GHz = np.arange(-.1, .1, 0.005) # sweep +/- 100 MHz around guess
# now vary the sideband frequency for each spec pulse
spec_schedules = []
for freq in sb_freqs_GHz:
spec_schedules.append(build_spec12_pulse_schedule(freq))
spec_schedules[0].draw()
# assemble the schedules into a Qobj
spec12_qobj = assemble(**helper.get_params('spec12', globals()))
answer1 = spec12_qobj
# run the simulation
spec12_result = backend_sim.run(spec12_qobj, duffing_model).result()
# retrieve the data from the experiment
spec12_values = helper.get_values_from_result(spec12_result, qubit)
anharm_offset = qubit_lo_freq[0]/GHz + anharmonicity_guess_GHz
fit_params, y_fit = helper.fit_lorentzian(anharm_offset + sb_freqs_GHz, spec12_values, [5, 4.5, .1, 3])
f12 = fit_params[1]
plt.scatter(anharm_offset + sb_freqs_GHz, np.real(spec12_values), color='white') # plot real part of sweep values
plt.plot(anharm_offset + sb_freqs_GHz, y_fit, color='red')
plt.xlim([anharm_offset + min(sb_freqs_GHz), anharm_offset + max(sb_freqs_GHz)])
plt.xlabel("Frequency [GHz]")
plt.ylabel("Measured Signal [a.u.]")
plt.show()
print("12 Spectroscopy yields %f GHz"%f12)
print("Measured transmon anharmonicity is %f MHz"%((f12-f01)*GHz/MHz))
from IPython.display import display, Javascript;display(Javascript('IPython.notebook.save_checkpoint();'));
from grading_tools import send_code;send_code('ex1.ipynb')
|
https://github.com/rohitgit1/Quantum-Computing-Summer-School
|
rohitgit1
|
# import SymPy and define symbols
import sympy as sp
sp.init_printing(use_unicode=True)
wr = sp.Symbol('\omega_r') # resonator frequency
wq = sp.Symbol('\omega_q') # qubit frequency
g = sp.Symbol('g', real=True) # vacuum Rabi coupling
Delta = sp.Symbol('Delta', real=True) # wr - wq; defined later
# import operator relations and define them
from sympy.physics.quantum.boson import BosonOp
a = BosonOp('a') # resonator photon annihilation operator
from sympy.physics.quantum import pauli, Dagger, Commutator
from sympy.physics.quantum.operatorordering import normal_ordered_form
# Pauli matrices
sx = pauli.SigmaX()
sy = pauli.SigmaY()
sz = pauli.SigmaZ()
# qubit raising and lowering operators
splus = pauli.SigmaPlus()
sminus = pauli.SigmaMinus()
# define J-C Hamiltonian in terms of diagonal and non-block diagonal terms
H0 = wr*Dagger(a)*a - (1/2)*wq*sz;
H1 = 0
H2 = g*(Dagger(a)*sminus + a*splus);
HJC = H0 + H1 + H2; HJC # print
# using the above method for finding the ansatz
eta = Commutator(H0, H2); eta
pauli.qsimplify_pauli(normal_ordered_form(eta.doit().expand()))
A = sp.Symbol('A')
B = sp.Symbol('B')
eta = A * Dagger(a) * sminus - B * a * splus;
pauli.qsimplify_pauli(normal_ordered_form(Commutator(H0, eta).doit().expand()))
H2
S1 = eta.subs(A, g/Delta)
S1 = S1.subs(B, g/Delta); S1.factor()
Heff = H0 + H1 + 0.5*pauli.qsimplify_pauli(normal_ordered_form(Commutator(H2, S1).doit().expand())).simplify(); Heff
from qiskit.tools.jupyter import *
from qiskit import IBMQ
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q', group='open', project='main')
backend = provider.get_backend('ibmq_armonk')
backend_config = backend.configuration()
assert backend_config.open_pulse, "Backend doesn't support Pulse"
dt = backend_config.dt
print(f"Sampling time: {dt*1e9} ns")
backend_defaults = backend.defaults()
import numpy as np
# unit conversion factors -> all backend properties returned in SI (Hz, sec, etc)
GHz = 1.0e9 # Gigahertz
MHz = 1.0e6 # Megahertz
kHz = 1.0e3
us = 1.0e-6 # Microseconds
ns = 1.0e-9 # Nanoseconds
# We will find the qubit frequency for the following qubit.
qubit = 0
# The sweep will be centered around the estimated qubit frequency.
center_frequency_Hz = backend_defaults.qubit_freq_est[qubit] # The default frequency is given in Hz
# warning: this will change in a future release
print(f"Qubit {qubit} has an estimated frequency of {center_frequency_Hz / GHz} GHz.")
# scale factor to remove factors of 10 from the data
scale_factor = 1e-14
# We will sweep 40 MHz around the estimated frequency
frequency_span_Hz = 40 * MHz
# in steps of 1 MHz.
frequency_step_Hz = 1 * MHz
# We will sweep 20 MHz above and 20 MHz below the estimated frequency
frequency_min = center_frequency_Hz - frequency_span_Hz / 2
frequency_max = center_frequency_Hz + frequency_span_Hz / 2
# Construct an np array of the frequencies for our experiment
frequencies_GHz = np.arange(frequency_min / GHz,
frequency_max / GHz,
frequency_step_Hz / GHz)
print(f"The sweep will go from {frequency_min / GHz} GHz to {frequency_max / GHz} GHz \
in steps of {frequency_step_Hz / MHz} MHz.")
from qiskit import pulse # This is where we access all of our Pulse features!
inst_sched_map = backend_defaults.instruction_schedule_map
measure = inst_sched_map.get('measure', qubits=[qubit])
x_pulse = inst_sched_map.get('x', qubits=[qubit])
### Collect the necessary channels
drive_chan = pulse.DriveChannel(qubit)
meas_chan = pulse.MeasureChannel(qubit)
acq_chan = pulse.AcquireChannel(qubit)
# Create the base schedule
# Start with drive pulse acting on the drive channel
schedule = pulse.Schedule(name='Frequency sweep')
schedule += x_pulse
# The left shift `<<` is special syntax meaning to shift the start time of the schedule by some duration
schedule += measure << schedule.duration
# Create the frequency settings for the sweep (MUST BE IN HZ)
frequencies_Hz = frequencies_GHz*GHz
schedule_frequencies = [{drive_chan: freq} for freq in frequencies_Hz]
schedule.draw(label=True, scaling=0.8)
from qiskit import assemble
frequency_sweep_program = assemble(schedule,
backend=backend,
meas_level=1,
meas_return='avg',
shots=1024,
schedule_los=schedule_frequencies)
# RUN the job on a real device
#job = backend.run(rabi_experiment_program)
#print(job.job_id())
#from qiskit.tools.monitor import job_monitor
#job_monitor(job)
# OR retreive result from previous run
job = backend.retrieve_job('5ef3b081fbc24b001275b03b')
frequency_sweep_results = job.result()
import matplotlib.pyplot as plt
plt.style.use('dark_background')
sweep_values = []
for i in range(len(frequency_sweep_results.results)):
# Get the results from the ith experiment
res = frequency_sweep_results.get_memory(i)*scale_factor
# Get the results for `qubit` from this experiment
sweep_values.append(res[qubit])
plt.scatter(frequencies_GHz, np.real(sweep_values), color='white') # plot real part of sweep values
plt.xlim([min(frequencies_GHz), max(frequencies_GHz)])
plt.xlabel("Frequency [GHz]")
plt.ylabel("Measured signal [a.u.]")
plt.show()
from scipy.optimize import curve_fit
def fit_function(x_values, y_values, function, init_params):
fitparams, conv = curve_fit(function, x_values, y_values, init_params)
y_fit = function(x_values, *fitparams)
return fitparams, y_fit
fit_params, y_fit = fit_function(frequencies_GHz,
np.real(sweep_values),
lambda x, A, q_freq, B, C: (A / np.pi) * (B / ((x - q_freq)**2 + B**2)) + C,
[5, 4.975, 1, 3] # initial parameters for curve_fit
)
plt.scatter(frequencies_GHz, np.real(sweep_values), color='white')
plt.plot(frequencies_GHz, y_fit, color='red')
plt.xlim([min(frequencies_GHz), max(frequencies_GHz)])
plt.xlabel("Frequency [GHz]")
plt.ylabel("Measured Signal [a.u.]")
plt.show()
# Create the schedules for 0 and 1
schedule_0 = pulse.Schedule(name='0')
schedule_0 += measure
schedule_1 = pulse.Schedule(name='1')
schedule_1 += x_pulse
schedule_1 += measure << schedule_1.duration
schedule_0.draw()
schedule_1.draw()
frequency_span_Hz = 320 * kHz
frequency_step_Hz = 8 * kHz
center_frequency_Hz = backend_defaults.meas_freq_est[qubit]
print(f"Qubit {qubit} has an estimated readout frequency of {center_frequency_Hz / GHz} GHz.")
frequency_min = center_frequency_Hz - frequency_span_Hz / 2
frequency_max = center_frequency_Hz + frequency_span_Hz / 2
frequencies_GHz = np.arange(frequency_min / GHz,
frequency_max / GHz,
frequency_step_Hz / GHz)
print(f"The sweep will go from {frequency_min / GHz} GHz to {frequency_max / GHz} GHz\
in steps of {frequency_step_Hz / MHz} MHz.")
num_shots_per_frequency = 2048
frequencies_Hz = frequencies_GHz*GHz
schedule_los = [{meas_chan: freq} for freq in frequencies_Hz]
cavity_sweep_0 = assemble(schedule_0,
backend=backend,
meas_level=1,
meas_return='avg',
shots=num_shots_per_frequency,
schedule_los=schedule_los)
cavity_sweep_1 = assemble(schedule_1,
backend=backend,
meas_level=1,
meas_return='avg',
shots=num_shots_per_frequency,
schedule_los=schedule_los)
# RUN the job on a real device
#job_0 = backend.run(cavity_sweep_0)
#job_monitor(job_0)
#job_0.error_message()
#job_1 = backend.run(cavity_sweep_1)
#job_monitor(job_1)
#job_1.error_message()
# OR retreive result from previous run
job_0 = backend.retrieve_job('5efa5b447c0d6800137fff1c')
job_1 = backend.retrieve_job('5efa6b2720eee10013be46b4')
cavity_sweep_0_results = job_0.result()
cavity_sweep_1_results = job_1.result()
scale_factor = 1e-14
sweep_values_0 = []
for i in range(len(cavity_sweep_0_results.results)):
res_0 = cavity_sweep_0_results.get_memory(i)*scale_factor
sweep_values_0.append(res_0[qubit])
sweep_values_1 = []
for i in range(len(cavity_sweep_1_results.results)):
res_1 = cavity_sweep_1_results.get_memory(i)*scale_factor
sweep_values_1.append(res_1[qubit])
plotx = frequencies_Hz/kHz
ploty_0 = np.abs(sweep_values_0)
ploty_1 = np.abs(sweep_values_1)
plt.plot(plotx, ploty_0, color='blue', marker='.') # plot real part of sweep values
plt.plot(plotx, ploty_1, color='red', marker='.') # plot real part of sweep values
plt.legend([r'$\vert0\rangle$', r'$\vert1\rangle$'])
plt.grid()
plt.xlabel("Frequency [kHz]")
plt.ylabel("Measured signal [a.u.]")
plt.yscale('log')
plt.show()
|
https://github.com/rohitgit1/Quantum-Computing-Summer-School
|
rohitgit1
|
!pip install -U -r grading_tools/requirements.txt
from IPython.display import clear_output
clear_output()
import numpy as np; pi = np.pi
from qiskit import QuantumCircuit, Aer, execute
from qiskit.visualization import plot_histogram
from copy import deepcopy as make_copy
def prepare_hets_circuit(depth, angle1, angle2):
hets_circ = QuantumCircuit(depth)
hets_circ.ry(angle1, 0)
hets_circ.rz(angle1, 0)
hets_circ.ry(angle1, 1)
hets_circ.rz(angle1, 1)
for ii in range(depth):
hets_circ.cx(0,1)
hets_circ.ry(angle2,0)
hets_circ.rz(angle2,0)
hets_circ.ry(angle2,1)
hets_circ.rz(angle2,1)
return hets_circ
hets_circuit = prepare_hets_circuit(2, pi/2, pi/2)
hets_circuit.draw()
def measure_zz_circuit(given_circuit):
zz_meas = make_copy(given_circuit)
zz_meas.measure_all()
return zz_meas
zz_meas = measure_zz_circuit(hets_circuit)
zz_meas.draw()
simulator = Aer.get_backend('qasm_simulator')
result = execute(zz_meas, backend = simulator, shots=10000).result()
counts = result.get_counts(zz_meas)
plot_histogram(counts)
def measure_zz(given_circuit, num_shots = 10000):
zz_meas = measure_zz_circuit(given_circuit)
result = execute(zz_meas, backend = simulator, shots = num_shots).result()
counts = result.get_counts(zz_meas)
if '00' not in counts:
counts['00'] = 0
if '01' not in counts:
counts['01'] = 0
if '10' not in counts:
counts['10'] = 0
if '11' not in counts:
counts['11'] = 0
total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10']
zz = counts['00'] + counts['11'] - counts['01'] - counts['10']
zz = zz / total_counts
return zz
zz = measure_zz(hets_circuit)
print("<ZZ> =", str(zz))
def measure_zi(given_circuit, num_shots = 10000):
zz_meas = measure_zz_circuit(given_circuit)
result = execute(zz_meas, backend = simulator, shots = num_shots).result()
counts = result.get_counts(zz_meas)
if '00' not in counts:
counts['00'] = 0
if '01' not in counts:
counts['01'] = 0
if '10' not in counts:
counts['10'] = 0
if '11' not in counts:
counts['11'] = 0
total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10']
zi = counts['00'] - counts['11'] + counts['01'] - counts['10']
zi = zi / total_counts
return zi
def measure_iz(given_circuit, num_shots = 10000):
zz_meas = measure_zz_circuit(given_circuit)
result = execute(zz_meas, backend = simulator, shots = num_shots).result()
counts = result.get_counts(zz_meas)
if '00' not in counts:
counts['00'] = 0
if '01' not in counts:
counts['01'] = 0
if '10' not in counts:
counts['10'] = 0
if '11' not in counts:
counts['11'] = 0
total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10']
iz = counts['00'] - counts['11'] - counts['01'] + counts['10']
iz = iz / total_counts
return iz
zi = measure_zi(hets_circuit)
print("<ZI> =", str(zi))
iz = measure_iz(hets_circuit)
print("<IZ> =", str(iz))
def measure_xx_circuit(given_circuit):
xx_meas = make_copy(given_circuit)
### WRITE YOUR CODE BETWEEN THESE LINES - START
xx_meas.h(0)
xx_meas.h(1)
xx_meas.measure_all()
### WRITE YOUR CODE BETWEEN THESE LINES - END
return xx_meas
xx_meas = measure_xx_circuit(hets_circuit)
xx_meas.draw()
def measure_xx(given_circuit, num_shots = 10000):
xx_meas = measure_xx_circuit(given_circuit)
result = execute(xx_meas, backend = simulator, shots = num_shots).result()
counts = result.get_counts(xx_meas)
if '00' not in counts:
counts['00'] = 0
if '01' not in counts:
counts['01'] = 0
if '10' not in counts:
counts['10'] = 0
if '11' not in counts:
counts['11'] = 0
total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10']
xx = counts['00'] + counts['11'] - counts['01'] - counts['10']
xx = xx / total_counts
return xx
xx = measure_xx(hets_circuit)
print("<XX> =", str(xx))
def get_energy(given_circuit, num_shots = 10000):
zz = measure_zz(given_circuit, num_shots = num_shots)
iz = measure_iz(given_circuit, num_shots = num_shots)
zi = measure_zi(given_circuit, num_shots = num_shots)
xx = measure_xx(given_circuit, num_shots = num_shots)
energy = (-1.0523732)*1 + (0.39793742)*iz + (-0.3979374)*zi + (-0.0112801)*zz + (0.18093119)*xx
return energy
energy = get_energy(hets_circuit)
print("The energy of the trial state is", str(energy))
hets_circuit_plus = None
hets_circuit_minus = None
### WRITE YOUR CODE BETWEEN THESE LINES - START
hets_circuit_plus = prepare_hets_circuit(2, pi/2 + 0.1*pi/2, pi/2)
hets_circuit_minus = prepare_hets_circuit(2, pi/2 - 0.1*pi/2, pi/2)
### WRITE YOUR CODE BETWEEN THESE LINES - END
energy_plus = get_energy(hets_circuit_plus, num_shots=100000)
energy_minus = get_energy(hets_circuit_minus, num_shots=100000)
print(energy_plus, energy_minus)
name = 'Pon Rahul M'
email = 'ponrahul.21it@licet.ac.in'
### Do not change the lines below
from grading_tools import grade
grade(answer=measure_xx_circuit(hets_circuit), name=name, email=email, labid='lab9', exerciseid='ex1')
grade(answer=hets_circuit_plus, name=name, email=email, labid='lab9', exerciseid='ex2')
grade(answer=hets_circuit_minus, name=name, email=email, labid='lab9', exerciseid='ex3')
energy_plus_100, energy_plus_1000, energy_plus_10000 = 0, 0, 0
energy_minus_100, energy_minus_1000, energy_minus_10000 = 0, 0, 0
### WRITE YOUR CODE BETWEEN THESE LINES - START
energy_plus_100 = get_energy(hets_circuit_plus, num_shots = 100)
energy_minus_100 = get_energy(hets_circuit_minus, num_shots = 100)
energy_plus_1000 = get_energy(hets_circuit_plus, num_shots = 1000)
energy_minus_1000 = get_energy(hets_circuit_minus, num_shots = 1000)
energy_plus_10000 = get_energy(hets_circuit_plus, num_shots = 10000)
energy_minus_10000 = get_energy(hets_circuit_minus, num_shots = 10000)
### WRITE YOUR CODE BETWEEN THESE LINES - END
print(energy_plus_100, energy_minus_100, "difference = ", energy_minus_100 - energy_plus_100)
print(energy_plus_1000, energy_minus_1000, "difference = ", energy_minus_1000 - energy_plus_1000)
print(energy_plus_10000, energy_minus_10000, "difference = ", energy_minus_10000 - energy_plus_10000)
### WRITE YOUR CODE BETWEEN THESE LINES - START
I = np.array([
[1, 0],
[0, 1]
])
X = np.array([
[0, 1],
[1, 0]
])
Z = np.array([
[1, 0],
[0, -1]
])
h2_hamiltonian = (-1.0523732) * np.kron(I, I) + \
(0.39793742) * np.kron(I, Z) + \
(-0.3979374) * np.kron(Z, I) + \
(-0.0112801) * np.kron(Z, Z) + \
(0.18093119) * np.kron(X, X)
from numpy import linalg as LA
eigenvalues, eigenvectors = LA.eig(h2_hamiltonian)
for ii, eigenvalue in enumerate(eigenvalues):
print(f"Eigenvector {eigenvectors[:,ii]} has energy {eigenvalue}")
exact_eigenvector = eigenvectors[:,np.argmin(eigenvalues)]
exact_eigenvalue = np.min(eigenvalues)
print()
print("Minimum energy is", exact_eigenvalue)
### WRITE YOUR CODE BETWEEN THESE LINES - END
|
https://github.com/rodneyosodo/variational-quantum-classifier-on-heartattack
|
rodneyosodo
|
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import pandas_profiling as pp
%matplotlib inline
# Constants
DATA_PATH = "../../Data/Raw/data.csv"
PP_PATH = "../../Output/Figures/pandasProfile.html"
CLEAN_DATA_PATH = "../../Data/Processed/data.csv"
data = pd.read_csv(DATA_PATH)
data.shape
data.columns
data.head(7)
data.info()
data.describe()
def check_unique(df):
""""
Checks the unique value in each column
:param df: The dataframe
"""
for col in df.columns:
unique = df[col].unique()
print("Column: {} has {} unique values\n".format(col, unique))
check_unique(data)
data['num '].value_counts()
fig = plt.figure()
sns.countplot(x="num ", data=data, palette="gist_rainbow_r")
plt.xlabel("Heart disease (0 = have, 1 = don't)")
plt.title("Target distribution")
plt.show()
fig.savefig("../../Output/Figures/targetdist.png", )
sns.countplot(x='sex', data=data, palette="mako_r")
plt.xlabel("Sex (0 = female, 1= male)")
plt.title("Age distribution")
plt.savefig("../../Output/Figures/agedist.png", format="png")
pd.crosstab(data['age'], data['num ']).plot(kind="bar",figsize=(20,6))
plt.title('Heart Disease Frequency for Ages')
plt.xlabel('Age')
plt.ylabel('Frequency')
plt.savefig('../../Output/Figures/heartDiseaseAndAges.png')
plt.figure(figsize=(15,8))
ax = sns.boxplot(data=data, orient="v", palette="Set2")
plt.title("Box plots")
plt.savefig("../../Output/Figures/boxplot.png")
sns.pairplot(data, diag_kind="kde")
plt.title("Pair plots")
plt.savefig("../../Output/Figures/pairplot.png")
data = data.rename(columns={'num ':'num'})
def fix_missing_values(df):
""""
Changes ? in the data to be np.Nan
:param df: The dataframe
:return df: Fixed dataframe
"""
cols = df.columns
for col in cols:
for i in range(len(df[col])):
if df[col][i] == '?':
df[col][i] = np.NaN
return df
data = fix_missing_values(data)
data.info()
def change_dtype(df):
""""
Changes the data type from object to float64
:param df: The dataframe
:return df: Fixed dataframe
"""
cols = df.columns
for col in cols:
if df[col].dtype == 'O':
df[col] = df[col].astype("float64")
return df
data = change_dtype(data)
def fix_missing_values(df):
def delete_missing_values(df):
"""
Deletes the column with Null values which are less than half of its values
"""
df = df[['age', 'sex', 'cp', 'trestbps', 'chol', 'fbs', 'restecg', 'thalach','exang', 'oldpeak', 'num']]
return df
def fill_with_mean(df):
"""
Fills the NaN values with the mean value of the column
"""
cols = ['trestbps', 'chol', 'thalach']
for col in cols:
df[col].fillna(value=df[col].mean(), inplace=True)
return df
def fill_with_mode(df):
"""
Fills the NaN values with the mode value of the column
"""
cols =['fbs', 'restecg', 'exang']
for col in cols:
df[col].fillna(value=df[col].mode()[0], inplace=True)
return df
df = delete_missing_values(df)
df = fill_with_mean(df)
df = fill_with_mode(df)
return df
data = fix_missing_values(data)
data.duplicated().sum()
data.drop_duplicates(inplace=True)
data.drop('num', axis=1).corrwith(data['num']).plot(kind='bar', grid=True, figsize=(12, 8), title="Correlation with target")
plt.savefig("../../Output/Figures/correlation.png")
pp.ProfileReport(df=data, dark_mode=True, explorative=True)
pp.ProfileReport(df=data, dark_mode=True, explorative=True).to_file(PP_PATH)
data.to_csv(CLEAN_DATA_PATH, index=False)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.