repo
stringclasses 885
values | file
stringclasses 741
values | content
stringlengths 4
215k
|
|---|---|---|
https://github.com/AbdulahAmer/PHYS-31415-Summer-2021
|
AbdulahAmer
|
for i in range(100): # I define my dummy variable and my range that I will iterate over
print(i, end=',') # I do my thing which is printing whatever the dummy variable is
# the end =',' is added so that the output gets printed more compactly! super optional.
i=0 # with while loops we need to give our dummy variable a value since it is not looking for i in something like a range
while i<100: # while i is less than 100 we iterate through the loop
print(i, end=',') # we do our thing and print our dummy variable i
i=i+1 # we add 1 to i each time we loop through, this is ESSENTIAL to while loops, without this i would always
# EQUAL 0 and the loop would NEVER end!
# create a string to test against another
string_1 = "I Love Physics"
string_2 = 'i love physics'
if string_1 == string_2:
print('These strings are the same')
# create a string to test against another
string_1 = "I Love Physics"
string_2 = 'i love physics'
if string_1 == string_2:
print('These strings are the same')
else:
print('These strings are NOT the same')
# using a for loop
for i in range(101):
print(i, end=',')
if i == 100:
print('we counted until 100!')
# using a while loop
i=0 # starting point for our loop
while i <= 100:
print(i, end=',')
if i == 100:
print('we counted until 100!')
i+=1
|
https://github.com/GabrielPontolillo/Quantum_Algorithm_Implementations
|
GabrielPontolillo
|
import warnings
from qiskit import QuantumRegister, ClassicalRegister
from qiskit import QuantumCircuit, execute, Aer, transpile
from qiskit.tools.monitor import job_monitor
from qiskit.circuit.library import QFT
from qiskit.visualization import plot_histogram, plot_bloch_multivector
warnings.filterwarnings("ignore", category=DeprecationWarning)
import numpy as np
pi = np.pi
def flip_endian(dict):
newdict = {}
for key in list(dict):
newdict[key[::-1]] = dict.pop(key)
return newdict
def qft_rotations(circuit, n):
#if qubit amount is 0, then do nothing and return
if n == 0:
#set it to measure the x axis
#set_measure_x(circuit, 4)
#circuit.measure_all()
return circuit
n -= 1
circuit.h(n)
for qubit in range(n):
circuit.cp(pi/2**(n-qubit), qubit, n)
return qft_rotations(circuit, n)
def qft_rotations_not_inplace(n):
circuit = QuantumCircuit(n)
#if qubit amount is 0, then do nothing and return
if n == 0:
#set it to measure the x axis
#set_measure_x(circuit, 4)
#circuit.measure_all()
return circuit
n -= 1
circuit.h(n)
for qubit in range(n):
circuit.cp(pi/2**(n-qubit), qubit, n)
return qft_rotations(circuit, n)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.dagcircuit import DAGCircuit
from qiskit.converters import circuit_to_dag
from qiskit.visualization import dag_drawer
q = QuantumRegister(3, 'q')
c = ClassicalRegister(3, 'c')
circ = QuantumCircuit(q, c)
circ.h(q[0])
circ.cx(q[0], q[1])
circ.measure(q[0], c[0])
circ.rz(0.5, q[1]).c_if(c, 2)
dag = circuit_to_dag(circ)
dag_drawer(dag)
|
https://github.com/MuhammadMiqdadKhan/Solution-of-IBM-s-Global-Quantum-Challenge-2020
|
MuhammadMiqdadKhan
|
from may4_challenge.ex4 import get_unitary
U = get_unitary()
from may4_challenge.ex4 import get_unitary
from qiskit import QuantumCircuit, transpile, execute, BasicAer, extensions
from qiskit.visualization import *
from qiskit import QuantumCircuit
from may4_challenge.ex4 import check_circuit, submit_circuit
import numpy as np
import sklearn as sk
import scipy as scipy
from scipy import linalg
from qiskit.visualization import plot_state_city
from qiskit.compiler import transpile
from qiskit import Aer,execute,QuantumRegister
from math import pi
from qiskit import transpile
import scipy
import numpy as np
from qiskit import QuantumCircuit
from may4_challenge.ex4 import check_circuit, submit_circuit
#U = get_unitary()
#pi = 3.141
#print(U)
#print("U has shape", U.shape)
#H = scipy.linalg.hadamard(16)/4
#U = np.dot(H, U)
#U = np.dot(U, H)
#qc = QuantumCircuit(4)
#print(pi)
#qc.u3(pi/2,0,pi,0)
#qc.u3(pi/2,0,pi,1)
#qc.u3(pi/2,0,pi,2)
#qc.u3(pi/2,0,pi,3)
#qc.isometry(U,[0,1,2,3],[])
#qc.u3(pi/2,0,pi,0)
#qc.u3(pi/2,0,pi,1)
#qc.u3(pi/2,0,pi,2)
#qc.u3(pi/2,0,pi,3)
#qc = transpile(qc, basis_gates = ['u3', 'cx'], seed_transpiler=0, optimization_level=2)
#print('gates = ', qc.count_ops())
#print('depth = ', qc.depth()
from scipy.linalg import hadamard
H = hadamard(16, dtype=complex)/4
U = np.dot(H, U)
U = np.dot(U, H)
qc = QuantumCircuit(4)
qc.u3(pi/2,0,pi,range(4))
qc.isometry(U,[0,1,2,3],[])
qc.u3(pi/2,0,pi,range(4))
qc = transpile(qc, basis_gates = ['u3', 'cx'], seed_transpiler=5, optimization_level=2)
##### check your quantum circuit by running the next line
check_circuit(qc)
from may4_challenge.ex4 import submit_circuit
submit_circuit(qc)
|
https://github.com/quantum-tokyo/qiskit-handson
|
quantum-tokyo
|
import math
import numpy as np
import matplotlib.pyplot as plt
#from fractions import Fraction
from quantum_computer_math_guide_trigonometric_intro_exercise_answer import *
ans1 = 1/2 # こちらに値を書いてください
print(check_answer_exercise(ans1,"ans1"))
ans2 = 0# こちらに値を書いてください。
print(check_answer_exercise(ans2,"ans2"))
ans3 = 1# こちらに値を書いてください。
print(check_answer_exercise(ans3,"ans3"))
ans4 = 1/2 # こちらに値を書いてください。
print(check_answer_exercise(ans4,"ans4"))
ans5 = 0 # こちらに値を書いてください。
print(check_answer_exercise(ans5,"ans5"))
ans6 = -1/2 # こちらに値を書いてください。
print(check_answer_exercise(ans6,"ans6"))
ans7 = -1 # こちらに値を書いてください。
print(check_answer_exercise(ans7,"ans7"))
ans8 = -1# こちらに値を書いてください。
print(check_answer_exercise(ans8,"ans8"))
ans9 = -1/2# こちらに値を書いてください。
print(check_answer_exercise(ans9,"ans9"))
ans10 = 0 # こちらに値を書いてください。
print(check_answer_exercise(ans10,"ans10"))
ans11 = 1 # こちらに値を書いてください。
print(check_answer_exercise(ans11,"ans11"))
ans12 = 45 # こちらに値を書いてください(「°」は省略してください。)
print(check_answer_exercise(ans12,"ans12"))
ans13 = 60 # こちらに値を書いてください(「°」は省略してください。)
print(check_answer_exercise(ans13,"ans13"))
ans14 = 45 # こちらに値を書いてください(「°」は省略してください。)
print(check_answer_exercise(ans14,"ans14"))
ans15 = 1 # こちらに値を書いてください
print(check_answer_exercise(ans15,"ans15"))
ans16 = 1 # こちらに値を書いてください
print(check_answer_exercise(ans16,"ans16"))
ans1_deg = math.sin(math.radians(30)) # こちらに度数法の計算式を書いてください。
ans1_rad = math.sin(np.pi*(1/6)) # こちらに弧度法の計算式を書いてください。
print("ans1 =", round(ans1,3)," : ans1_deg = ", round(ans1_deg,3)," : ans1_rad = ", round(ans1_rad,3))
ans2_deg = math.cos(math.radians(90)) # 度数法
ans2_rad = math.cos(np.pi*(1/2)) # 弧度法
print("ans2 =", round(ans2,3)," : ans2_deg = ", round(ans2_deg,3)," : ans2_rad = ", round(ans2_rad,3))
ans3_deg = math.tan(math.radians(45)) # 度数法
ans3_rad = math.tan(np.pi*(1/4)) # 弧度法
print("ans3 =", round(ans3,3)," : ans3_deg = ", round(ans3_deg,3)," : ans3_rad = ", round(ans3_rad,3))
ans4_deg = math.cos(math.radians(60)) # 度数法
ans4_rad = math.cos(np.pi*(1/3)) # 弧度法
print("ans4 =", round(ans4,3)," : ans4_deg = ", round(ans4_deg,3)," : ans4_rad = ", round(ans4_rad,3))
ans5_deg = math.sin(math.radians(0)) # 度数法
ans5_rad = math.sin(np.pi*(0)) # 弧度法
print("ans5 =", round(ans5,3)," : ans5_deg = ", round(ans5_deg,3)," : ans5_rad = ", round(ans5_rad,3))
ans6_deg = math.cos(math.radians(120)) # 度数法
ans6_rad = math.cos(np.pi*(2/3)) # 弧度法
print("ans6 =", round(ans6,3)," : ans6_deg = ", round(ans6_deg,3)," : ans6_rad = ", round(ans6_rad,3))
ans7_deg = math.tan(math.radians(135)) # 度数法
ans7_rad = math.tan(np.pi*(3/4)) # 弧度法
print("ans7 =", round(ans7,3)," : ans7_deg = ", round(ans7_deg,3)," : ans7_rad = ", round(ans7_rad,3))
ans8_deg = math.cos(math.radians(180)) # 度数法
ans8_rad = math.cos(np.pi*(1)) # 弧度法
print("ans8 =", round(ans8,3)," : ans8_deg = ", round(ans8_deg,3)," : ans8_rad = ", round(ans8_rad,3))
ans9_deg = math.sin(math.radians(-30)) # 度数法
ans9_rad = math.sin(np.pi*(-1/6)) # 弧度法
print("ans9 =", round(ans9,3)," : ans9_deg = ", round(ans9_deg,3)," : ans9_rad = ", round(ans9_rad,3))
ans10_deg = math.cos(math.radians(-90)) # 度数法
ans10_rad = math.cos(np.pi*(-1/2)) # 弧度法
print("ans10 =", round(ans10,3)," : ans10_deg = ", round(ans10_deg,3)," : ans10_rad = ", round(ans10_rad,3))
ans11_deg = math.sin(math.radians(450)) # 度数法
ans11_rad = math.sin(np.pi*(5/2)) # 弧度法
print("ans11 =", round(ans11,3)," : ans11_deg = ", round(ans11_deg,3)," : ans11_rad = ", round(ans11_rad,3))
ans12_deg = math.degrees(math.asin(1/math.sqrt(2))) # 度数法
print("ans12 =", round(ans12,3)," : ans12_deg = ", round(ans12_deg,3))
ans13_deg = math.degrees(math.acos(1/2)) # 度数法
print("ans13 =", round(ans13,3)," : ans13_deg = ", round(ans13_deg,3))
ans14_deg = math.degrees(math.atan(1)) # 度数法
print("ans14 =", round(ans14,3)," : ans14_deg = ", round(ans14_deg,3))
ans15_deg = math.sin(math.radians(30))**2 + math.cos(math.radians(30))**2 # 度数法
ans15_rad = (math.sin(np.pi*(1/2)))**2+(math.cos(np.pi*(1/2)))**2 # 弧度法
print("ans15 =", round(ans15,3)," : ans15_deg = ", round(ans15_deg,3)," : ans15_rad = ", round(ans15_rad,3))
ans16_deg = math.sin(math.radians(-45))**2 + math.cos(math.radians(-45))**2 # 度数法
ans16_rad = (math.sin(np.pi*(-1/4)))**2+(math.cos(np.pi*(-1/4)))**2 # 弧度法
print("ans16 =", round(ans16,3)," : ans16_deg = ", round(ans16_deg,3)," : ans16_rad = ", round(ans16_rad,3))
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-np.pi, np.pi)
plt.plot(x, np.sin(x), color='b', label='sin') # color = 'r': red, 'g': green
plt.xlim(-np.pi, np.pi)
plt.ylim(-1.5, 1.5)
plt.axhline(0, ls='-', c='b', lw=0.5)
plt.axvline(0, ls='-', c='b', lw=0.5)
plt.legend()
plt.xlabel('x')
plt.ylabel('y')
plt.title('Graphs')
plt.show()
x = np.linspace(-np.pi, np.pi)
plt.plot(x, np.cos(x), color='r', label='cos')
plt.xlim(-np.pi, np.pi)
plt.ylim(-1.5, 1.5)
plt.axhline(0, ls='-', c='b', lw=0.5)
plt.axvline(0, ls='-', c='b', lw=0.5)
plt.legend()
plt.xlabel('x')
plt.ylabel('y')
plt.title('Graphs')
plt.show()
x = np.linspace(-np.pi, np.pi)
plt.plot(x, np.sin(x), color='b', label='sin')
plt.plot(x, np.cos(x), color='r', label='cos')
plt.xlim(-np.pi, np.pi)
plt.ylim(-1.5, 1.5)
plt.axhline(0, ls='-', c='b', lw=0.5)
plt.axvline(0, ls='-', c='b', lw=0.5)
plt.legend()
plt.xlabel('x')
plt.ylabel('y')
plt.title('Graphs')
plt.show()
x = np.linspace(-2*np.pi, 2*np.pi)
plt.plot(x, np.tan(x), color='r', label='tan')
plt.xlim(-2*np.pi, 2*np.pi)
plt.ylim(-1.5, 1.5)
plt.axhline(0, ls='-', c='b', lw=0.5)
plt.axvline(0, ls='-', c='b', lw=0.5)
plt.legend()
plt.xlabel('x')
plt.ylabel('y')
plt.title('Graphs')
plt.show()
class GraphClass:
# x_start:x軸の最小値
# x_end:x軸の最大値
# x_start、x_endは表示する関数のデフォルトの定義域
# y_start:y軸の最小値
# y_end:y軸の最大値
def __init__(self, x_start, x_end, y_start , y_end):
self.x_start = x_start
self.x_end = x_end
self.y_start = y_start
self.y_end = y_end
self.x = np.linspace(x_start,x_end)
self.plt = plt
# オーバーライドする。自分が表示したいグラフを定義する
def setGraph(self):
pass
# グラフを表示する
def displayGraph(self):
self.setGraph()
self.__setBasicConfig()
self.plt.show()
# sinグラフを表示する
def displaySin(self):
self.plt.plot(self.x, np.sin(self.x), color='b', label='sin')
self.__setBasicConfig()
self.plt.show()
# cosグラフを表示する
def displayCos(self):
self.plt.plot(self.x, np.cos(self.x), color='r', label='cos')
self.__setBasicConfig()
self.plt.show()
# tanグラフを表示する
def displayTan(self):
self.plt.plot(self.x, np.tan(self.x), color='y', label='tan')
self.__setBasicConfig()
self.plt.show()
# 基本的な設定
def __setBasicConfig(self):
self.plt.xlim(self.x_start, self.x_end)
self.plt.ylim(self.y_start, self.y_end)
self.plt.gca().set_aspect('equal', adjustable='box')
self.plt.axhline(0, ls='-', c='b', lw=0.5)
self.plt.axvline(0, ls='-', c='b', lw=0.5)
self.plt.xticks(rotation=45)
self.plt.legend()
self.plt.xlabel('x')
self.plt.ylabel('y')
self.plt.title('Graphs')
# 自分のクラスを定義する 以下はサンプル
class MyGraphClass(GraphClass):
def __init__(self, x_start, x_end, y_start , y_end):
super().__init__(x_start, x_end, y_start , y_end)
# オーバーライドする
def setGraph(self):
#sin
self.plt.plot(self.x, 2*np.sin(self.x), color='b', label='sin')
#cos
self.plt.plot(self.x, np.cos(self.x), color='g', label='cos')
#単位円 デフォルトとは異なる定義域にする。
r=1
x = np.linspace(-r, r)
self.plt.plot(x, np.sqrt(r ** 2 - x ** 2), color='r', label='x^2+y^2')
self.plt.plot(x, -np.sqrt(r ** 2 - x ** 2), color='r', label='x^2+y^2')
# 点を入れる
self.plt.plot(np.cos(math.radians(30)), np.sin(math.radians(30)), marker='X', markersize=20)
#tan
#self.plt.plot(self.x, np.tan(self.x), color='y', label='tan')
#exp
#self.plt.plot(self.x, np.exp(self.x), color='m', label='exp')
myGraphClass = MyGraphClass(-1,1,-1,1)
myGraphClass.displayGraph()
#myGraphClass.displaySin()
#myGraphClass.displayCos()
#myGraphClass.displayTan()
|
https://github.com/ShabaniLab/qiskit-hackaton-2019
|
ShabaniLab
|
import numpy as np
from qiskit.circuit import QuantumCircuit, QuantumRegister, ClassicalRegister
from ising_kitaev import initialize_chain, run_adiabatic_zeeman_change, rotate_to_measurement_basis, add_measurement
zeeman_ferro = 0.01
zeeman_para = 10
initial_config = np.array([zeeman_ferro, zeeman_ferro, zeeman_ferro, zeeman_para])
final_config = np.array([zeeman_ferro, zeeman_ferro, zeeman_ferro, zeeman_ferro])
qreg = QuantumRegister(4)
creg = ClassicalRegister(4)
qcirc = QuantumCircuit(qreg, creg)
initialize_chain(qcirc, qreg, initial_config, 'logical_one')
qcirc.draw()
run_adiabatic_zeeman_change(qcirc, qreg, initial_config, final_config, 0, 0.25, 0.25, 1, 10)
qcirc.depth()
rotate_to_measurement_basis(qcirc, qreg, [0, 1, 2, 3])
add_measurement(qcirc, qreg, creg, [0, 1, 2, 3])
from qiskit import Aer, execute
backend = Aer.get_backend('qasm_simulator')
job = execute(qcirc, backend, shots=2000)
job.status()
result = job.result()
print(result.get_counts())
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit_nature.second_q.drivers import PySCFDriver
driver = PySCFDriver()
problem = driver.run()
print(problem)
from qiskit_nature.second_q.problems import ElectronicBasis
driver.run_pyscf()
problem = driver.to_problem(basis=ElectronicBasis.MO, include_dipole=True)
print(problem.basis)
ao_problem = driver.to_problem(basis=ElectronicBasis.AO)
print(ao_problem.basis)
from qiskit_nature.second_q.formats.qcschema_translator import qcschema_to_problem
qcschema = driver.to_qcschema()
ao_problem = qcschema_to_problem(qcschema, basis=ElectronicBasis.AO)
from qiskit_nature.second_q.formats.qcschema_translator import get_ao_to_mo_from_qcschema
basis_transformer = get_ao_to_mo_from_qcschema(qcschema)
mo_problem = basis_transformer.transform(ao_problem)
print(mo_problem.basis)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/victor-onofre/Quantum_Algorithms
|
victor-onofre
|
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer, IBMQ, BasicAer
from qiskit.visualization import plot_histogram
from qiskit.quantum_info import Statevector
import numpy as np
import matplotlib
style = {'backgroundcolor': 'lightyellow'} # Style of the circuits
backend = BasicAer.get_backend('qasm_simulator')
shots = 1024
qreg = QuantumRegister(6)
register1 = ClassicalRegister(5)
qc = QuantumCircuit(qreg, register1 )
qc.x(5)
qc.barrier()
qc.draw(output='mpl', style=style)
qc.h(0)
qc.h(1)
qc.h(2)
qc.h(3)
qc.h(4)
qc.h(5)
qc.barrier()
qc.draw(output='mpl', style=style)
qc.cx(0,5)
qc.cx(1,5)
qc.cx(4,5)
qc.barrier()
qc.draw(output='mpl', style=style)
qc.h(0)
qc.h(1)
qc.h(2)
qc.h(3)
qc.h(4)
qc.h(5)
qc.barrier()
qc.draw(output='mpl', style=style)
qc.measure(0, register1[0])
qc.measure(1, register1[1])
qc.measure(2, register1[2])
qc.measure(3, register1[3])
qc.measure(4, register1[4])
qc.draw(output='mpl', style=style)
results = execute(qc, backend=backend, shots=shots).result()
answer = results.get_counts()
plot_histogram(answer)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import numpy as np
from qiskit import QuantumCircuit
# Create a Quantum Circuit acting on a quantum register of three qubits
circ = QuantumCircuit(3)
# Add a H gate on qubit 0, putting this qubit in superposition.
circ.h(0)
# Add a CX (CNOT) gate on control qubit 0 and target qubit 1, putting
# the qubits in a Bell state.
circ.cx(0, 1)
# Add a CX (CNOT) gate on control qubit 0 and target qubit 2, putting
# the qubits in a GHZ state.
circ.cx(0, 2)
circ.draw('mpl')
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(circ)
#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')
state.draw('hinton')
from qiskit.quantum_info import Operator
U = Operator(circ)
# Show the results
U.data
# Create a Quantum Circuit
meas = QuantumCircuit(3, 3)
meas.barrier(range(3))
# map the quantum measurement to the classical bits
meas.measure(range(3), range(3))
# The Qiskit circuit object supports composition.
# Here the meas has to be first and front=True (putting it before)
# as compose must put a smaller circuit into a larger one.
qc = meas.compose(circ, range(3), front=True)
#drawing the circuit
qc.draw('mpl')
# Adding the transpiler to reduce the circuit to QASM instructions
# supported by the backend
from qiskit import transpile
# Use AerSimulator
from qiskit_aer import AerSimulator
backend = AerSimulator()
# First we have to transpile the quantum circuit
# to the low-level QASM instructions used by the
# backend
qc_compiled = transpile(qc, backend)
# Execute the circuit on the qasm simulator.
# We've set the number of repeats of the circuit
# to be 1024, which is the default.
job_sim = backend.run(qc_compiled, shots=1024)
# Grab the results from the job.
result_sim = job_sim.result()
counts = result_sim.get_counts(qc_compiled)
print(counts)
from qiskit.visualization import plot_histogram
plot_histogram(counts)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
import numpy as np
import pylab
from qiskit_chemistry import QiskitChemistry
# Input dictionary to configure Qiskit Chemistry for the chemistry problem.
qiskit_chemistry_dict = {
'driver': {'name': 'PYQUANTE'},
'PYQUANTE': {'atoms': '', 'basis': 'sto3g'},
'operator': {'name': 'hamiltonian', 'qubit_mapping': 'jordan_wigner',
'two_qubit_reduction': False},
'algorithm': {'name': ''},
'optimizer': {'name': 'COBYLA', 'maxiter': 10000 },
'variational_form': {'name': 'UCCSD'},
'initial_state': {'name': 'HartreeFock'}
}
molecule = 'H .0 .0 -{0}; H .0 .0 {0}'
algorithms = ['VQE', 'ExactEigensolver']
start = 0.5 # Start distance
by = 0.5 # How much to increase distance by
steps = 20 # Number of steps to increase by
energies = np.empty([len(algorithms), steps+1])
hf_energies = np.empty(steps+1)
distances = np.empty(steps+1)
eval_counts = np.empty(steps+1)
print('Processing step __', end='')
for i in range(steps+1):
print('\b\b{:2d}'.format(i), end='', flush=True)
d = start + i*by/steps
qiskit_chemistry_dict['PYQUANTE']['atoms'] = molecule.format(d/2)
for j in range(len(algorithms)):
qiskit_chemistry_dict['algorithm']['name'] = algorithms[j]
solver = QiskitChemistry()
result = solver.run(qiskit_chemistry_dict)
energies[j][i] = result['energy']
hf_energies[i] = result['hf_energy']
if algorithms[j] == 'VQE':
eval_counts[i] = result['algorithm_retvals']['eval_count']
distances[i] = d
print(' --- complete')
print('Distances: ', distances)
print('Energies:', energies)
print('Hartree-Fock energies:', hf_energies)
print('VQE num evaluations:', eval_counts)
pylab.plot(distances, hf_energies, label='Hartree-Fock')
for j in range(len(algorithms)):
pylab.plot(distances, energies[j], label=algorithms[j])
pylab.xlabel('Interatomic distance')
pylab.ylabel('Energy')
pylab.title('H2 Ground State Energy')
pylab.legend(loc='upper right')
pylab.plot(distances, np.subtract(hf_energies, energies[1]), label='Hartree-Fock')
pylab.plot(distances, np.subtract(energies[0], energies[1]), label='VQE')
pylab.xlabel('Interatomic distance')
pylab.ylabel('Energy')
pylab.title('Energy difference from ExactEigensolver')
pylab.legend(loc='upper left')
pylab.plot(distances, eval_counts, '-o', color=[0.8500, 0.3250, 0.0980], label='VQE')
pylab.xlabel('Interatomic distance')
pylab.ylabel('Evaluations')
pylab.title('VQE number of evaluations')
pylab.legend(loc='upper left')
|
https://github.com/brhn-4/CMSC457
|
brhn-4
|
from qiskit import QuantumRegister, ClassicalRegister
from qiskit import QuantumCircuit, execute
from qiskit import Aer
import numpy as np
import sys
N=int(sys.argv[1])
filename = sys.argv[2]
backend = Aer.get_backend('unitary_simulator')
def GHZ(n):
if n<=0:
return None
circ = QuantumCircuit(n)
# Put your code below
# ----------------------------
circ.h(0)
for x in range(1,n):
circ.cx(x-1,x)
# ----------------------------
return circ
circuit = GHZ(N)
job = execute(circuit, backend, shots=8192)
result = job.result()
array = result.get_unitary(circuit,3)
np.savetxt(filename, array, delimiter=",", fmt = "%0.3f")
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
from qiskit.transpiler.passes import RemoveBarriers
circuit = QuantumCircuit(1)
circuit.x(0)
circuit.barrier()
circuit.h(0)
circuit = RemoveBarriers()(circuit)
circuit.draw('mpl')
|
https://github.com/swe-train/qiskit__qiskit
|
swe-train
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Piecewise polynomial Chebyshev approximation to a given f(x)."""
from __future__ import annotations
from typing import Callable
import numpy as np
from numpy.polynomial.chebyshev import Chebyshev
from qiskit.circuit import QuantumRegister, AncillaRegister
from qiskit.circuit.library.blueprintcircuit import BlueprintCircuit
from qiskit.circuit.exceptions import CircuitError
from .piecewise_polynomial_pauli_rotations import PiecewisePolynomialPauliRotations
class PiecewiseChebyshev(BlueprintCircuit):
r"""Piecewise Chebyshev approximation to an input function.
For a given function :math:`f(x)` and degree :math:`d`, this class implements a piecewise
polynomial Chebyshev approximation on :math:`n` qubits to :math:`f(x)` on the given intervals.
All the polynomials in the approximation are of degree :math:`d`.
The values of the parameters are calculated according to [1] and see [2] for a more
detailed explanation of the circuit construction and how it acts on the qubits.
Examples:
.. plot::
:include-source:
import numpy as np
from qiskit import QuantumCircuit
from qiskit.circuit.library.arithmetic.piecewise_chebyshev import PiecewiseChebyshev
f_x, degree, breakpoints, num_state_qubits = lambda x: np.arcsin(1 / x), 2, [2, 4], 2
pw_approximation = PiecewiseChebyshev(f_x, degree, breakpoints, num_state_qubits)
pw_approximation._build()
qc = QuantumCircuit(pw_approximation.num_qubits)
qc.h(list(range(num_state_qubits)))
qc.append(pw_approximation.to_instruction(), qc.qubits)
qc.draw(output='mpl')
References:
[1]: Haener, T., Roetteler, M., & Svore, K. M. (2018).
Optimizing Quantum Circuits for Arithmetic.
`arXiv:1805.12445 <http://arxiv.org/abs/1805.12445>`_
[2]: Carrera Vazquez, A., Hiptmair, H., & Woerner, S. (2022).
Enhancing the Quantum Linear Systems Algorithm Using Richardson Extrapolation.
`ACM Transactions on Quantum Computing 3, 1, Article 2 <https://doi.org/10.1145/3490631>`_
"""
def __init__(
self,
f_x: float | Callable[[int], float],
degree: int | None = None,
breakpoints: list[int] | None = None,
num_state_qubits: int | None = None,
name: str = "pw_cheb",
) -> None:
r"""
Args:
f_x: the function to be approximated. Constant functions should be specified
as f_x = constant.
degree: the degree of the polynomials.
Defaults to ``1``.
breakpoints: the breakpoints to define the piecewise-linear function.
Defaults to the full interval.
num_state_qubits: number of qubits representing the state.
name: The name of the circuit object.
"""
super().__init__(name=name)
# define internal parameters
self._num_state_qubits = None
# Store parameters
self._f_x = f_x
self._degree = degree if degree is not None else 1
self._breakpoints = breakpoints if breakpoints is not None else [0]
self._polynomials: list[list[float]] | None = None
self.num_state_qubits = num_state_qubits
def _check_configuration(self, raise_on_failure: bool = True) -> bool:
"""Check if the current configuration is valid."""
valid = True
if self._f_x is None:
valid = False
if raise_on_failure:
raise AttributeError("The function to be approximated has not been set.")
if self._degree is None:
valid = False
if raise_on_failure:
raise AttributeError("The degree of the polynomials has not been set.")
if self._breakpoints is None:
valid = False
if raise_on_failure:
raise AttributeError("The breakpoints have not been set.")
if self.num_state_qubits is None:
valid = False
if raise_on_failure:
raise AttributeError("The number of qubits has not been set.")
if self.num_qubits < self.num_state_qubits + 1:
valid = False
if raise_on_failure:
raise CircuitError(
"Not enough qubits in the circuit, need at least "
"{}.".format(self.num_state_qubits + 1)
)
return valid
@property
def f_x(self) -> float | Callable[[int], float]:
"""The function to be approximated.
Returns:
The function to be approximated.
"""
return self._f_x
@f_x.setter
def f_x(self, f_x: float | Callable[[int], float] | None) -> None:
"""Set the function to be approximated.
Note that this may change the underlying quantum register, if the number of state qubits
changes.
Args:
f_x: The new function to be approximated.
"""
if self._f_x is None or f_x != self._f_x:
self._invalidate()
self._f_x = f_x
self._reset_registers(self.num_state_qubits)
@property
def degree(self) -> int:
"""The degree of the polynomials.
Returns:
The degree of the polynomials.
"""
return self._degree
@degree.setter
def degree(self, degree: int | None) -> None:
"""Set the error tolerance.
Note that this may change the underlying quantum register, if the number of state qubits
changes.
Args:
degree: The new degree.
"""
if self._degree is None or degree != self._degree:
self._invalidate()
self._degree = degree
self._reset_registers(self.num_state_qubits)
@property
def breakpoints(self) -> list[int]:
"""The breakpoints for the piecewise approximation.
Returns:
The breakpoints for the piecewise approximation.
"""
breakpoints = self._breakpoints
# it the state qubits are set ensure that the breakpoints match beginning and end
if self.num_state_qubits is not None:
num_states = 2**self.num_state_qubits
# If the last breakpoint is < num_states, add the identity polynomial
if breakpoints[-1] < num_states:
breakpoints = breakpoints + [num_states]
# If the first breakpoint is > 0, add the identity polynomial
if breakpoints[0] > 0:
breakpoints = [0] + breakpoints
return breakpoints
@breakpoints.setter
def breakpoints(self, breakpoints: list[int] | None) -> None:
"""Set the breakpoints for the piecewise approximation.
Note that this may change the underlying quantum register, if the number of state qubits
changes.
Args:
breakpoints: The new breakpoints for the piecewise approximation.
"""
if self._breakpoints is None or breakpoints != self._breakpoints:
self._invalidate()
self._breakpoints = breakpoints if breakpoints is not None else [0]
self._reset_registers(self.num_state_qubits)
@property
def polynomials(self) -> list[list[float]]:
"""The polynomials for the piecewise approximation.
Returns:
The polynomials for the piecewise approximation.
Raises:
TypeError: If the input function is not in the correct format.
"""
if self.num_state_qubits is None:
return [[]]
# note this must be the private attribute since we handle missing breakpoints at
# 0 and 2 ^ num_qubits here (e.g. if the function we approximate is not defined at 0
# and the user takes that into account we just add an identity)
breakpoints = self._breakpoints
# Need to take into account the case in which no breakpoints were provided in first place
if breakpoints == [0]:
breakpoints = [0, 2**self.num_state_qubits]
num_intervals = len(breakpoints)
# Calculate the polynomials
polynomials = []
for i in range(0, num_intervals - 1):
# Calculate the polynomial approximating the function on the current interval
try:
# If the function is constant don't call Chebyshev (not necessary and gives errors)
if isinstance(self.f_x, (float, int)):
# Append directly to list of polynomials
polynomials.append([self.f_x])
else:
poly = Chebyshev.interpolate(
self.f_x, self.degree, domain=[breakpoints[i], breakpoints[i + 1]]
)
# Convert polynomial to the standard basis and rescale it for the rotation gates
poly = 2 * poly.convert(kind=np.polynomial.Polynomial).coef
# Convert to list and append
polynomials.append(poly.tolist())
except ValueError as err:
raise TypeError(
" <lambda>() missing 1 required positional argument: '"
+ self.f_x.__code__.co_varnames[0]
+ "'."
+ " Constant functions should be specified as 'f_x = constant'."
) from err
# If the last breakpoint is < 2 ** num_qubits, add the identity polynomial
if breakpoints[-1] < 2**self.num_state_qubits:
polynomials = polynomials + [[2 * np.arcsin(1)]]
# If the first breakpoint is > 0, add the identity polynomial
if breakpoints[0] > 0:
polynomials = [[2 * np.arcsin(1)]] + polynomials
return polynomials
@polynomials.setter
def polynomials(self, polynomials: list[list[float]] | None) -> None:
"""Set the polynomials for the piecewise approximation.
Note that this may change the underlying quantum register, if the number of state qubits
changes.
Args:
polynomials: The new breakpoints for the piecewise approximation.
"""
if self._polynomials is None or polynomials != self._polynomials:
self._invalidate()
self._polynomials = polynomials
self._reset_registers(self.num_state_qubits)
@property
def num_state_qubits(self) -> int:
r"""The number of state qubits representing the state :math:`|x\rangle`.
Returns:
The number of state qubits.
"""
return self._num_state_qubits
@num_state_qubits.setter
def num_state_qubits(self, num_state_qubits: int | None) -> None:
"""Set the number of state qubits.
Note that this may change the underlying quantum register, if the number of state qubits
changes.
Args:
num_state_qubits: The new number of qubits.
"""
if self._num_state_qubits is None or num_state_qubits != self._num_state_qubits:
self._invalidate()
self._num_state_qubits = num_state_qubits
# Set breakpoints if they haven't been set
if num_state_qubits is not None and self._breakpoints is None:
self.breakpoints = [0, 2**num_state_qubits]
self._reset_registers(num_state_qubits)
def _reset_registers(self, num_state_qubits: int | None) -> None:
"""Reset the registers."""
self.qregs = []
if num_state_qubits is not None:
qr_state = QuantumRegister(num_state_qubits, "state")
qr_target = QuantumRegister(1, "target")
self.qregs = [qr_state, qr_target]
num_ancillas = num_state_qubits
if num_ancillas > 0:
qr_ancilla = AncillaRegister(num_ancillas)
self.add_register(qr_ancilla)
def _build(self):
"""Build the circuit if not already build. The operation is considered successful
when q_objective is :math:`|1>`"""
if self._is_built:
return
super()._build()
poly_r = PiecewisePolynomialPauliRotations(
self.num_state_qubits, self.breakpoints, self.polynomials, name=self.name
)
# qr_state = self.qubits[: self.num_state_qubits]
# qr_target = [self.qubits[self.num_state_qubits]]
# qr_ancillas = self.qubits[self.num_state_qubits + 1 :]
# Apply polynomial approximation
self.append(poly_r.to_gate(), self.qubits)
|
https://github.com/0tt3r/QuaC-qiskit
|
0tt3r
|
# -*- coding: utf-8 -*-
"""This module contains objective functions for optimizing noise models.
"""
from typing import List
import numpy as np
from qiskit import QuantumCircuit, execute
from qiskit.result import Result
from quac_qiskit.stat import kl_dist_smoothing, discrete_one_samp_ks, get_vec_angle
from quac_qiskit.format import counts_to_list
from quac_qiskit.models import QuacNoiseModel
def kl_div_sum(circuits: List[QuantumCircuit], simulation_result: Result, reference_result: Result) -> float:
"""Given a set of test circuits and a Qiskit Result object for a simulation and hardware, the sum of
K-L divergence between circuit result distributions for each circuit is computed
:param circuits: a list of QuantumCircuit objects
:param simulation_result: a Qiskit Result object
:param reference_result: a Qiskit Result object
:return: a float representing the total K-L divergence between distributions of all circuits
"""
total_kl_div = 0
for circuit in circuits:
simulation_counts = np.array(counts_to_list(simulation_result.get_counts(circuit)))
simulation_dist = simulation_counts / simulation_counts.sum() # normalize if using counts simulator
reference_counts = np.array(counts_to_list(reference_result.get_counts(circuit)))
reference_dist = reference_counts / reference_counts.sum() # normalize if using counts simulator
total_kl_div += kl_dist_smoothing(reference_dist, simulation_dist, 1e-5)
return total_kl_div
def ks_div_sum(circuits: List[QuantumCircuit], simulation_result: Result, reference_result: Result) -> float:
"""Given a set of test circuits and a Qiskit Result object for a simulation and hardware, the sum of
K-S distance between circuit result distributions for each circuit is computed
:param circuits: a list of QuantumCircuit objects
:param simulation_result: a Qiskit Result object
:param reference_result: a Qiskit Result object
:return: a float representing the total K-S distance between distributions of all circuits
"""
total_ks_div = 0
for circuit in circuits:
simulation_counts = np.array(counts_to_list(simulation_result.get_counts(circuit)))
simulation_dist = simulation_counts / simulation_counts.sum() # normalize if using counts simulator
reference_counts = np.array(counts_to_list(reference_result.get_counts(circuit)))
reference_dist = reference_counts / reference_counts.sum() # normalize if using counts simulator
total_ks_div += discrete_one_samp_ks(reference_dist, simulation_dist, 8000)[0]
return total_ks_div
def angle_div_sum(circuits: List[QuantumCircuit], simulation_result: Result, reference_result: Result) -> float:
"""Given a set of test circuits and a Qiskit Result object for a simulation and hardware, the sum of
angle distance between circuit result distributions for each circuit is computed
:param circuits: a list of QuantumCircuit objects
:param simulation_result: a Qiskit Result object
:param reference_result: a Qiskit Result object
:return: a float representing the total angle distance between distributions of all circuits
"""
total_angle_div = 0
for ind, circuit in enumerate(circuits):
simulation_counts = np.array(counts_to_list(simulation_result.get_counts(circuit)))
simulation_dist = simulation_counts / simulation_counts.sum() # normalize if using counts simulator
reference_counts = np.array(counts_to_list(reference_result.get_counts(circuit)))
reference_dist = reference_counts / reference_counts.sum() # normalize if using counts simulator
total_angle_div += get_vec_angle(reference_dist, simulation_dist)
return total_angle_div
def kl_objective_function(noise_model_array: np.array, *args):
"""An objective function to be minimized based on K-L divergence
:param noise_model_array: a Numpy array generated via QuacNoiseModel.to_array()
:param args: QuantumCircuit objects run, the simulator to run on, and the hardware results
:return: a float representing the "loss" over the set of circuits
"""
circuits, backend, reference_result = args
noise_model = QuacNoiseModel.from_array(noise_model_array, backend.configuration().n_qubits)
simulation_result = execute(circuits, backend, shots=1, quac_noise_model=noise_model).result()
return kl_div_sum(circuits, simulation_result, reference_result)
def ks_objective_function(noise_model_array: np.array, *args):
"""An objective function to be minimized based on K-S distance
:param noise_model_array: a Numpy array generated via QuacNoiseModel.to_array()
:param args: QuantumCircuit objects run, the simulator to run on, and the hardware results
:return: a float representing the "loss" over the set of circuits
"""
circuits, backend, reference_result = args
noise_model = QuacNoiseModel.from_array(noise_model_array, backend.configuration().n_qubits)
simulation_result = execute(circuits, backend, shots=1, quac_noise_model=noise_model).result()
return ks_div_sum(circuits, simulation_result, reference_result)
def angle_objective_function(noise_model_array: np.array, *args):
"""An objective function to be minimized based on angle divergence
:param noise_model_array: a Numpy array generated via QuacNoiseModel.to_array()
:param args: QuantumCircuit objects run, the simulator to run on, and the hardware results
:return: a float representing the "loss" over the set of circuits
"""
circuits, backend, reference_result = args
noise_model = QuacNoiseModel.from_array(noise_model_array, backend.configuration().n_qubits)
simulation_result = execute(circuits, backend, shots=1, quac_noise_model=noise_model).result()
return angle_div_sum(circuits, simulation_result, reference_result)
|
https://github.com/sakthianand7/Bernstein_Vazirani_Algorithm
|
sakthianand7
|
from qiskit import *
from qiskit.tools.visualization import plot_histogram
%matplotlib inline
secretnumber = '11100011'
circuit = QuantumCircuit(len(secretnumber)+1,len(secretnumber))
circuit.h(range(len(secretnumber)))
circuit.x(len(secretnumber))
circuit.h(len(secretnumber))
circuit.barrier()
for ii, yesno in enumerate(reversed(secretnumber)):
if yesno == '1':
circuit.cx(ii,len(secretnumber))
circuit.barrier()
circuit.h(range(len(secretnumber)))
circuit.barrier()
circuit.measure(range(len(secretnumber)),range(len(secretnumber)))
circuit.draw(output = 'mpl')
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit_nature.mappers.second_quantization import LogarithmicMapper
mapper = LogarithmicMapper(2)
from qiskit_nature.second_q.mappers import LogarithmicMapper
mapper = LogarithmicMapper(2)
from qiskit_nature.second_q.mappers import LogarithmicMapper
mapper = LogarithmicMapper(padding=2)
from qiskit_nature.circuit.library import HartreeFock
from qiskit_nature.converters.second_quantization import QubitConverter
from qiskit_nature.mappers.second_quantization import JordanWignerMapper
converter = QubitConverter(JordanWignerMapper())
init_state = HartreeFock(num_spin_orbitals=6, num_particles=(2, 1), qubit_converter=converter)
print(init_state.draw())
from qiskit_nature.second_q.circuit.library import HartreeFock
from qiskit_nature.second_q.mappers import JordanWignerMapper, QubitConverter
converter = QubitConverter(JordanWignerMapper())
init_state = HartreeFock(num_spatial_orbitals=3, num_particles=(2, 1), qubit_converter=converter)
print(init_state.draw())
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/BOBO1997/osp_solutions
|
BOBO1997
|
import numpy as np
import matplotlib.pyplot as plt
import itertools
from pprint import pprint
# plt.rcParams.update({'font.size': 16}) # enlarge matplotlib fonts
import pickle
import time
import datetime
# Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z)
from qiskit.opflow import Zero, One, I, X, Y, Z
from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer
from qiskit.tools.monitor import job_monitor
from qiskit.circuit import Parameter
from qiskit.transpiler.passes import RemoveBarriers
# Import QREM package
from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter
from qiskit.ignis.mitigation import expectation_value
# Import mitiq for zne
import mitiq
# Import state tomography modules
from qiskit.ignis.verification.tomography import state_tomography_circuits
from qiskit.quantum_info import state_fidelity
import sys
import importlib
sys.path.append("./")
import circuit_utils, zne_utils, tomography_utils, sgs_algorithm
importlib.reload(circuit_utils)
importlib.reload(zne_utils)
importlib.reload(tomography_utils)
importlib.reload(sgs_algorithm)
from circuit_utils import *
from zne_utils import *
from tomography_utils import *
from sgs_algorithm import *
# Combine subcircuits into a single multiqubit gate representing a single trotter step
num_qubits = 3
# The final time of the state evolution
target_time = np.pi
# Parameterize variable t to be evaluated at t=pi later
dt = Parameter('t')
# Convert custom quantum circuit into a gate
trot_gate = trotter_gate(dt)
# initial layout
initial_layout = [5,3,1]
# Number of trotter steps
num_steps = 100
print("trotter step: ", num_steps)
# Initialize quantum circuit for 3 qubits
qr = QuantumRegister(num_qubits, name="q")
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>)
make_initial_state(qc, "110") # DO NOT MODIFY (|q_5,q_3,q_1> = |110>)
subspace_encoder_init110(qc, targets=[0, 1, 2]) # encode
trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian
subspace_decoder(qc, targets=[0,1,2]) # decode
# Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time
t1 = time.perf_counter()
qc = qc.bind_parameters({dt: target_time / num_steps})
t2 = time.perf_counter()
print("created qc,", t2 - t1, "s")
# Generate state tomography circuits to evaluate fidelity of simulation
t1 = time.perf_counter()
st_qcs = state_tomography_circuits(qc, [0, 1, 2][::-1]) #! state tomography requires === BIG ENDIAN ===
t2 = time.perf_counter()
print("created st_qcs (length:", len(st_qcs), "),", t2 - t1, "s")
# remove barriers
t1 = time.perf_counter()
st_qcs = [RemoveBarriers()(qc) for qc in st_qcs]
t2 = time.perf_counter()
print("removed barriers from st_qcs,", t2 - t1, "s")
# optimize circuit
t1 = time.perf_counter()
t3_st_qcs = transpile(st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"])
t2 = time.perf_counter()
print("created t3_st_qcs (length:", len(t3_st_qcs), "),", t2 - t1, "s")
t3_st_qcs[0].draw("mpl")
# zne wrapping
t1 = time.perf_counter()
zne_qcs = zne_wrapper(t3_st_qcs)
t2 = time.perf_counter()
print("created zne_qcs (length:", len(zne_qcs), "),", t2 - t1, "s")
t1 = time.perf_counter()
zne_qcs = transpile(zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"])
t2 = time.perf_counter()
print("decomposed zne_qcs into basis gates (length:", len(zne_qcs), "),", t2 - t1, "s")
t1 = time.perf_counter()
t3_zne_qcs = transpile(zne_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"])
t2 = time.perf_counter()
print("optimized zne_qcs -> create t3_zne_qcs (length:", len(t3_zne_qcs), "),", t2 - t1, "s")
t1 = time.perf_counter()
t3_zne_qcs = transpile(t3_zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout)
t2 = time.perf_counter()
print("fit the t3_zne_qcs to the initial layoit (length:", len(t3_zne_qcs), "),", t2 - t1, "s")
t3_zne_qcs[-3].draw("mpl")
from qiskit.test.mock import FakeJakarta
# backend = FakeJakarta()
# backend = Aer.get_backend("qasm_simulator")
IBMQ.load_account()
# provider = IBMQ.get_provider(hub='ibm-q-utokyo', group='internal', project='hirashi-jst')
provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22')
print("provider:", provider)
backend = provider.get_backend("ibmq_jakarta")
# QREM
shots = 1 << 13
qr = QuantumRegister(num_qubits)
meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal')
cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout = initial_layout)
print('Job ID', cal_job.job_id())
shots = 1 << 13
reps = 8 # unused
jobs = []
for _ in range(reps):
job = execute(t3_zne_qcs, backend, shots=shots, optimization_level = 0) # 毎回チェック: ここちゃんと変えた?
print('Job ID', job.job_id())
jobs.append(job)
dt_now = datetime.datetime.now()
print(dt_now)
import pickle
with open("jobs_jakarta_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f:
pickle.dump({"jobs": jobs, "cal_job": cal_job}, f)
with open("job_ids_jakarta_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f:
pickle.dump({"job_ids": [job.job_id() for job in jobs], "cal_job_id": cal_job.job_id()}, f)
with open("properties_jakarta" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f:
pickle.dump(backend.properties(), f)
cal_results = cal_job.result()
meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal')
mit_results = meas_fitter.filter.apply(job.result())
zne_expvals = zne_decoder(num_qubits, mit_results)
target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!!
rho = expvals_to_valid_rho(num_qubits, zne_expvals)
fidelity = state_fidelity(rho, target_state)
print(fidelity)
|
https://github.com/lkcoredo/qiskitWorkshop
|
lkcoredo
|
from qiskit import *
from qiskit.tools.visualization import plot_bloch_multivector
circuit = QuantumCircuit(1,1)
circuit.x(0)
simulator = Aer.get_backend('statevector_simulator')
execute(circuit, backend = simulator).result()
circuit.draw(output='mpl')
circuit.measure([0], [0])
backend = Aer.get_backend('qasm_simulator')
execute(circuit, backend = backend, shots = 1024).result()
result = execute(circuit, backend = simulator).result()
counts = result.get_counts()
statevector = result.get_statevector()
print(statevector)
%matplotlib inline
circuit.draw(output='mpl')
plot_bloch_multivector(statevector)
circuit.measure([0], [0])
backend = Aer.get_backend('qasm_simulator')
execute(circuit, backend = backend, shots = 1024).result()
counts = result.get_counts()
from qiskit.tools.visualization import plot_histogram
plot_histogram(counts)
circuit.draw(output='mpl')
circuit.draw(output='mpl')
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import IBMQ
IBMQ.load_account()
provider = IBMQ.get_provider(hub="ibm-q", group="open", project="main")
program_id = "qaoa"
qaoa_program = provider.runtime.program(program_id)
print(f"Program name: {qaoa_program.name}, Program id: {qaoa_program.program_id}")
print(qaoa_program.parameters())
import numpy as np
from qiskit.tools import job_monitor
from qiskit.opflow import PauliSumOp, Z, I
from qiskit.algorithms.optimizers import SPSA
# Define the cost operator to run.
op = (
(Z ^ Z ^ I ^ I ^ I)
- (I ^ I ^ Z ^ Z ^ I)
+ (I ^ I ^ Z ^ I ^ Z)
- (Z ^ I ^ Z ^ I ^ I)
- (I ^ Z ^ Z ^ I ^ I)
+ (I ^ Z ^ I ^ Z ^ I)
+ (I ^ I ^ I ^ Z ^ Z)
)
# SPSA helps deal with noisy environments.
optimizer = SPSA(maxiter=100)
# We will run a depth two QAOA.
reps = 2
# The initial point for the optimization, chosen at random.
initial_point = np.random.random(2 * reps)
# The backend that will run the programm.
options = {"backend_name": "ibmq_qasm_simulator"}
# The inputs of the program as described above.
runtime_inputs = {
"operator": op,
"reps": reps,
"optimizer": optimizer,
"initial_point": initial_point,
"shots": 2**13,
# Set to True when running on real backends to reduce circuit
# depth by leveraging swap strategies. If False the
# given optimization_level (default is 1) will be used.
"use_swap_strategies": False,
# Set to True when optimizing sparse problems.
"use_initial_mapping": False,
# Set to true when using echoed-cross-resonance hardware.
"use_pulse_efficient": False,
}
job = provider.runtime.run(
program_id=program_id,
options=options,
inputs=runtime_inputs,
)
job_monitor(job)
print(f"Job id: {job.job_id()}")
print(f"Job status: {job.status()}")
result = job.result()
from collections import defaultdict
def op_adj_mat(op: PauliSumOp) -> np.array:
"""Extract the adjacency matrix from the op."""
adj_mat = np.zeros((op.num_qubits, op.num_qubits))
for pauli, coeff in op.primitive.to_list():
idx = tuple([i for i, c in enumerate(pauli[::-1]) if c == "Z"]) # index of Z
adj_mat[idx[0], idx[1]], adj_mat[idx[1], idx[0]] = np.real(coeff), np.real(coeff)
return adj_mat
def get_cost(bit_str: str, adj_mat: np.array) -> float:
"""Return the cut value of the bit string."""
n, x = len(bit_str), [int(bit) for bit in bit_str[::-1]]
cost = 0
for i in range(n):
for j in range(n):
cost += adj_mat[i, j] * x[i] * (1 - x[j])
return cost
def get_cut_distribution(result) -> dict:
"""Extract the cut distribution from the result.
Returns:
A dict of cut value: probability.
"""
adj_mat = op_adj_mat(PauliSumOp.from_list(result["inputs"]["operator"]))
state_results = []
for bit_str, amp in result["eigenstate"].items():
state_results.append((bit_str, get_cost(bit_str, adj_mat), amp**2 * 100))
vals = defaultdict(int)
for res in state_results:
vals[res[1]] += res[2]
return dict(vals)
import matplotlib.pyplot as plt
cut_vals = get_cut_distribution(result)
fig, axs = plt.subplots(1, 2, figsize=(14, 5))
axs[0].plot(result["optimizer_history"]["energy"])
axs[1].bar(list(cut_vals.keys()), list(cut_vals.values()))
axs[0].set_xlabel("Energy evaluation number")
axs[0].set_ylabel("Energy")
axs[1].set_xlabel("Cut value")
axs[1].set_ylabel("Probability")
from qiskit_optimization.runtime import QAOAClient
from qiskit_optimization.algorithms import MinimumEigenOptimizer
from qiskit_optimization import QuadraticProgram
qubo = QuadraticProgram()
qubo.binary_var("x")
qubo.binary_var("y")
qubo.binary_var("z")
qubo.minimize(linear=[1, -2, 3], quadratic={("x", "y"): 1, ("x", "z"): -1, ("y", "z"): 2})
print(qubo.prettyprint())
qaoa_mes = QAOAClient(
provider=provider, backend=provider.get_backend("ibmq_qasm_simulator"), reps=2, alpha=0.75
)
qaoa = MinimumEigenOptimizer(qaoa_mes)
result = qaoa.solve(qubo)
print(result.prettyprint())
from qiskit.transpiler import PassManager
from qiskit.circuit.library.standard_gates.equivalence_library import (
StandardEquivalenceLibrary as std_eqlib,
)
from qiskit.transpiler.passes import (
Collect2qBlocks,
ConsolidateBlocks,
UnrollCustomDefinitions,
BasisTranslator,
Optimize1qGatesDecomposition,
)
from qiskit.transpiler.passes.calibration.builders import RZXCalibrationBuilderNoEcho
from qiskit.transpiler.passes.optimization.echo_rzx_weyl_decomposition import (
EchoRZXWeylDecomposition,
)
from qiskit.test.mock import FakeBelem
backend = FakeBelem()
inst_map = backend.defaults().instruction_schedule_map
channel_map = backend.configuration().qubit_channel_mapping
rzx_basis = ["rzx", "rz", "x", "sx"]
pulse_efficient = PassManager(
[
# Consolidate consecutive two-qubit operations.
Collect2qBlocks(),
ConsolidateBlocks(basis_gates=["rz", "sx", "x", "rxx"]),
# Rewrite circuit in terms of Weyl-decomposed echoed RZX gates.
EchoRZXWeylDecomposition(backend.defaults().instruction_schedule_map),
# Attach scaled CR pulse schedules to the RZX gates.
RZXCalibrationBuilderNoEcho(
instruction_schedule_map=inst_map, qubit_channel_mapping=channel_map
),
# Simplify single-qubit gates.
UnrollCustomDefinitions(std_eqlib, rzx_basis),
BasisTranslator(std_eqlib, rzx_basis),
Optimize1qGatesDecomposition(rzx_basis),
]
)
from qiskit import QuantumCircuit
circ = QuantumCircuit(3)
circ.h([0, 1, 2])
circ.rzx(0.5, 0, 1)
circ.swap(0, 1)
circ.cx(2, 1)
circ.rz(0.4, 1)
circ.cx(2, 1)
circ.rx(1.23, 2)
circ.cx(2, 1)
circ.draw("mpl")
pulse_efficient.run(circ).draw("mpl", fold=False)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
q = QuantumRegister(1)
c = ClassicalRegister(1)
qc = QuantumCircuit(q, c)
qc.h(q)
qc.measure(q, c)
qc.draw(output='mpl', style={'backgroundcolor': '#EEEEEE'})
|
https://github.com/quantumyatra/quantum_computing
|
quantumyatra
|
%matplotlib inline
# Importing standard Qiskit libraries and configuring account
from qiskit import QuantumCircuit,QuantumRegister,ClassicalRegister, execute, Aer, IBMQ
from qiskit.compiler import transpile, assemble
from qiskit.tools.jupyter import *
from qiskit.visualization import *
num_qubits = 2;
num_bits = 2;
bell = QuantumCircuit(2,2)
bell.h(0)
bell.cx(0, 1)
bell.measure([0,1], [0,1])
bell.draw(output='mpl')
simulator = Aer.get_backend('qasm_simulator')
result = execute(bell, simulator).result()
counts = result.get_counts(bell)
plot_histogram(counts, title='Bell-State counts')
num_qubits = 2;
num_bits = 2;
bell = QuantumCircuit(2,2)
bell.h(0)
bell.cx(0, 1)
bell.h(1)
bell.cx(0, 1)
bell.measure([0,1], [0,1])
bell.draw(output='mpl')
simulator = Aer.get_backend('qasm_simulator')
result = execute(bell, simulator).result()
counts = result.get_counts(bell)
plot_histogram(counts, title='Bell-State counts')
n =3
q = QuantumRegister(n)
c = ClassicalRegister(n)
circ = QuantumCircuit(q,c)
circ.h(q[0])
circ.cx(q[0], q[1])
circ.h(q[1])
circ.cx(q[1], q[2])
circ.h(q[2])
circ.measure(q,c)
# Change the background color in mpl
style = {'backgroundcolor': 'lightgreen'}
circ.draw(output='mpl', style = style)
simulator = Aer.get_backend('qasm_simulator')
result = execute(circ, simulator).result()
counts = result.get_counts(circ)
plot_histogram(counts, title='Bell-State counts')
|
https://github.com/DEBARGHYA4469/quantum-compiler
|
DEBARGHYA4469
|
#THIS PROGRAM IS MODIFIED FROM THE DJ ALGORITHM PRESENT IN QISKIT TUTORIAL WHERE I FEEL THAT THE NOTION OF TAKING THE RANDOM BALANCED
#FUNCTION IS QUITE ABSTRACT AND DIFFICULT TO GRASP FOR A BEGINNER.SO I ADDED SOME PIECE OF CODE FOR PRINTING THE RANDOM FUNCTION
#AND PROVE THERE IS A DETERMINISTIC WAY OF DERIVING A BALANCED FUNCTION BY SEEDING A RANDOM NUMBER!!
from connection import *
import numpy as np
import random
import matplotlib.pyplot as plt
from qiskit import QuantumCircuit,ClassicalRegister,QuantumRegister,QuantumJob
from qiskit import available_backends,execute,register,get_backend
from qiskit.tools.visualization import plot_histogram,circuit_drawer
backend = get_qc() # get the quantum computer with least jobs queued up
def flip_x(arr,binlength,l):
if(l == 0):
newstr = ""
for b in range(binlength):newstr = newstr + str(arr[b])
print("f(",newstr,")=1")
else:
for pv in range(2):
acopy = []
for i in range(binlength): acopy.append(arr[i])
for k in range(binlength):
if(acopy[k] == -1):
acopy[k] = pv
break
flip_x(acopy,binlength,l-1)
def mark_ones(j,shift,pos_ones,arr):
for i in range(j):
arr[pos_ones[shift+i]] = 1
return arr
def rec_util(j,binlength,pos_ones,shift):
if(shift+j-1 >= len(pos_ones)):
return
arr = []
for i in range(binlength): arr.append(-1)
arr = mark_ones(j,shift,pos_ones,arr)
flip_x(arr,binlength,binlength-j)
rec_util(j,binlength,pos_ones,shift+1)
def ones_in_binary(r): # Decimal to binary conversion
num = r
bry = 0
m = []
j = 0
f=1
while(num>0):
bry = bry + (num%2)*f
if(num%2 == 1):
m.append(j)
num = num//2
f=f*10
j=j+1
for i in range(len(m)):
m[i] = j -1- m[i]
pos_ones = []
for i in range(len(m)):
pos_ones.append(m[len(m)-i-1])
print(pos_ones)
return pos_ones,j
def print_fx(r,n):
j=1
pos_ones,binlength = ones_in_binary(r)#position of the ones and total length of binary string
binlength = n
while(j <= len(pos_ones)): #only odd results in flip by CNOT
shift = 0 # to traverse the pos_ones
rec_util(j,binlength,pos_ones,shift)
j=j+2
print("\n................DEUTSCH JOZSA ALGORITHM....................\n")
print("\nInput the size of the domain of the function..\n")
n = int(input())
print("\nInput 0 if you want a constant function,1 otherwise\n")
oracle_Type = int(input()) # constant or balanced
if(oracle_Type == 0): # constant function
print("What is the constant value 0/1 ?")
oracle_val = int(input())
else:
print("The function is balanced...Generating a random f(x)")
fx_generator = np.random.randint(1,2**n) # this variable creates the quantum circuit of the f(x)
print("\nYour Balanced Function is .........................")
print(fx_generator)
print_fx(fx_generator,n) # print the function
print("\nn Rest all values are 0s")
print("\nTHIS FUNCTION WILL REMAIN HIDDEN AND ONLY BE QUERIED TO ITS EQUIVALENT QUANTUM CIRCUIT")
#Print the quantum circuit for your random balanced oracle
file = open("oracle.qasm","a") # append mode
file.write("\n")
# Interfacing with quantum computer
qr = QuantumRegister(n+1) # query string
cr = ClassicalRegister(n) # first register
circuitName = "Deutsch_Joszsa"
djCircuit = QuantumCircuit(qr,cr)
for i in range(n+1):
file.write(" qubit q"+str(i)+"\n")
#superposition of all input queries by hadamard transform
for i in range(n):
file.write(" h q"+str(i)+"\n")
djCircuit.h(qr[i])
#FLip the second register and apply hadamard
djCircuit.x(qr[n])
file.write(" X q"+str(n)+"\n")
djCircuit.h(qr[n])
file.write(" h q"+str(n)+"\n")
djCircuit.barrier()
# IMPLEMENTING THE ORACLE BUT ITS VALUES ARE HIDDEN
if(oracle_Type == 0): # if constant
if(oracle_val==1):
djCircuit.x(qr[n])
file.write(" X q"+str(n)+"\n")
else:
djCircuit.iden(qr[n])
else:
for i in range(n):
if(fx_generator & (1 << i)):
djCircuit.cx(qr[i],qr[n])
file.write(" cnot q"+str(i)+",q"+str(n)+"\n")
djCircuit.barrier()
#apply hadamard after querying the oracle
for i in range(n):
djCircuit.h(qr[i])
file.write(" h q"+str(i)+"\n")
#measurements
for i in range(n):
djCircuit.measure(qr[i],cr[i])
file.write(" measure q"+str(i)+"\n")
#circuit_drawer(djCircuit)
file.close()
#backend = "local_qasm_simulator" #FOR local testing...
shots = 1000
job = execute(djCircuit,backend=backend,shots=shots)
results=job.result()
answer = results.get_counts()
plot_histogram(answer)
|
https://github.com/AbdulahAmer/PHYS-31415-Summer-2021
|
AbdulahAmer
|
from qiskit import * # this means that from the qiskit package
# import ALL functionality(*)
# we also want to see our results in insightful ways through graphs!
from qiskit.visualization import * # bloch sphere graphs, bar graphs for measurements
# We also need to import the simulators that we will use to make measurements
S_simulator=Aer.backends(name='statevector_simulator')[0] # allows you to simulate statevectors
M_simulator=Aer.backends(name='qasm_simulator')[0] # allows you to simulate measurements
# X gate on |0>
# make the circuit with one qubit and one classical bit
qc=QuantumCircuit(1,1)
# print out initial state to confirm that something happens when we use our gate!
initial_state=execute(qc, S_simulator).result().get_statevector()
print('Initial state: ', initial_state)
# use the x gate on the first qubit
qc.x(0)
# print out results!
state_after_gate= execute(qc, S_simulator).result().get_statevector()
print('state after X gate: ', state_after_gate)
# X gate on |1>
# make the circuit with one qubit and one classical bit
qc=QuantumCircuit(1,1)
# Initialize circuit to |1>
one = [0,1]
qc.initialize(one, 0)
# print out initial state to confirm that something happens when we use our gate!
initial_state=execute(qc, S_simulator).result().get_statevector()
print('Initial state: ', initial_state)
# use the x gate on the first qubit
qc.x(0)
# print out results!
state_after_gate= execute(qc, S_simulator).result().get_statevector()
print('state after X gate: ', state_after_gate)
# Y gate on |0>
# make the circuit with one qubit and one classical bit
qc=QuantumCircuit(1,1)
# print out initial state to confirm that something happens when we use our gate!
initial_state=execute(qc, S_simulator).result().get_statevector()
print('Initial state: ', initial_state)
# use the x gate on the first qubit
qc.y(0)
# print out results!
state_after_gate= execute(qc, S_simulator).result().get_statevector()
print('state after X gate: ', state_after_gate)
# Y gate on |1>
# make the circuit with one qubit and one classical bit
qc=QuantumCircuit(1,1)
# Initialize circuit to |1>
one = [0,1]
qc.initialize(one, 0)
# print out initial state to confirm that something happens when we use our gate!
initial_state=execute(qc, S_simulator).result().get_statevector()
print('Initial state: ', initial_state)
# use the x gate on the first qubit
qc.y(0)
# print out results!
state_after_gate= execute(qc, S_simulator).result().get_statevector()
print('state after X gate: ', state_after_gate)
# Z gate on |0>
# make the circuit with one qubit and one classical bit
qc=QuantumCircuit(1,1)
# print out initial state to confirm that something happens when we use our gate!
initial_state=execute(qc, S_simulator).result().get_statevector()
print('Initial state: ', initial_state)
# use the x gate on the first qubit
qc.z(0)
# print out results!
state_after_gate= execute(qc, S_simulator).result().get_statevector()
print('state after Z gate: ', state_after_gate)
# Z gate on |1>
# make the circuit with one qubit and one classical bit
qc=QuantumCircuit(1,1)
# Initialize circuit to |1>
one = [0,1]
qc.initialize(one, 0)
# print out initial state to confirm that something happens when we use our gate!
initial_state=execute(qc, S_simulator).result().get_statevector()
print('Initial state: ', initial_state)
# use the x gate on the first qubit
qc.z(0)
# print out results!
state_after_gate= execute(qc, S_simulator).result().get_statevector()
print('state after Z gate: ', state_after_gate)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from sklearn.datasets import make_blobs
# example dataset
features, labels = make_blobs(n_samples=20, n_features=2, centers=2, random_state=3, shuffle=True)
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import MinMaxScaler
features = MinMaxScaler(feature_range=(0, np.pi)).fit_transform(features)
train_features, test_features, train_labels, test_labels = train_test_split(
features, labels, train_size=15, shuffle=False
)
# number of qubits is equal to the number of features
num_qubits = 2
# number of steps performed during the training procedure
tau = 100
# regularization parameter
C = 1000
from qiskit import BasicAer
from qiskit.circuit.library import ZFeatureMap
from qiskit.utils import algorithm_globals
from qiskit_machine_learning.kernels import FidelityQuantumKernel
algorithm_globals.random_seed = 12345
feature_map = ZFeatureMap(feature_dimension=num_qubits, reps=1)
qkernel = FidelityQuantumKernel(feature_map=feature_map)
from qiskit_machine_learning.algorithms import PegasosQSVC
pegasos_qsvc = PegasosQSVC(quantum_kernel=qkernel, C=C, num_steps=tau)
# training
pegasos_qsvc.fit(train_features, train_labels)
# testing
pegasos_score = pegasos_qsvc.score(test_features, test_labels)
print(f"PegasosQSVC classification test score: {pegasos_score}")
grid_step = 0.2
margin = 0.2
grid_x, grid_y = np.meshgrid(
np.arange(-margin, np.pi + margin, grid_step), np.arange(-margin, np.pi + margin, grid_step)
)
meshgrid_features = np.column_stack((grid_x.ravel(), grid_y.ravel()))
meshgrid_colors = pegasos_qsvc.predict(meshgrid_features)
import matplotlib.pyplot as plt
plt.figure(figsize=(5, 5))
meshgrid_colors = meshgrid_colors.reshape(grid_x.shape)
plt.pcolormesh(grid_x, grid_y, meshgrid_colors, cmap="RdBu", shading="auto")
plt.scatter(
train_features[:, 0][train_labels == 0],
train_features[:, 1][train_labels == 0],
marker="s",
facecolors="w",
edgecolors="r",
label="A train",
)
plt.scatter(
train_features[:, 0][train_labels == 1],
train_features[:, 1][train_labels == 1],
marker="o",
facecolors="w",
edgecolors="b",
label="B train",
)
plt.scatter(
test_features[:, 0][test_labels == 0],
test_features[:, 1][test_labels == 0],
marker="s",
facecolors="r",
edgecolors="r",
label="A test",
)
plt.scatter(
test_features[:, 0][test_labels == 1],
test_features[:, 1][test_labels == 1],
marker="o",
facecolors="b",
edgecolors="b",
label="B test",
)
plt.legend(bbox_to_anchor=(1.05, 1), loc="upper left", borderaxespad=0.0)
plt.title("Pegasos Classification")
plt.show()
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/AkshayPatil347/Grover-s-Code
|
AkshayPatil347
|
from qiskit import QuantumCircuit, Aer, execute
from qiskit.visualization import plot_histogram
from numpy import random
color_codes = [0,1,2,3,4,5,6,7]
random.shuffle(color_codes)
database = {}
for i in range(8):
database[i] = color_codes[i]
desired_color_code = 2
DB = QuantumCircuit(7)
def DB_function(QC, color_code):
if color_code == 7:
QC.mcx([0,1,2],3)
QC.mcx([0,1,2],4)
QC.mcx([0,1,2],5)
elif color_code == 6:
QC.mcx([0,1,2],3)
QC.mcx([0,1,2],4)
elif color_code == 5:
QC.mcx([0,1,2],3)
QC.mcx([0,1,2],5)
elif color_code == 4:
QC.mcx([0,1,2],3)
elif color_code == 3:
QC.mcx([0,1,2],4)
QC.mcx([0,1,2],5)
elif color_code == 2:
QC.mcx([0,1,2],4)
elif color_code == 1:
QC.mcx([0,1,2],5)
#for when index = 0 = 000
DB.x(0)
DB.x(1)
DB.x(2)
DB_function(DB, database[0])
DB.x(0)
DB.x(1)
DB.x(2)
#for when index = 1 = 001
DB.x(0)
DB.x(1)
DB_function(DB, database[1])
DB.x(0)
DB.x(1)
#for when index = 2 = 010
DB.x(0)
DB.x(2)
DB_function(DB, database[2])
DB.x(0)
DB.x(2)
#for when index = 3 = 011
DB.x(0)
DB_function(DB, database[3])
DB.x(0)
#for when index = 4 = 100
DB.x(1)
DB.x(2)
DB_function(DB, database[4])
DB.x(1)
DB.x(2)
#for when index = 5 = 101
DB.x(1)
DB_function(DB, database[5])
DB.x(1)
#for when index = 6 = 110
DB.x(2)
DB_function(DB, database[6])
DB.x(2)
#for when index = 7 = 111
DB_function(DB, database[7])
DB.draw()
MG = QuantumCircuit(7)
if desired_color_code == 0:
MG.x(3)
MG.x(4)
MG.x(5)
MG.mcx([3,4,5],6)
MG.x(3)
MG.x(4)
MG.x(5)
elif desired_color_code == 1:
MG.x(3)
MG.x(4)
MG.mcx([3,4,5],6)
MG.x(3)
MG.x(4)
elif desired_color_code == 2:
MG.x(3)
MG.x(5)
MG.mcx([3,4,5],6)
MG.x(3)
MG.x(5)
elif desired_color_code == 3:
MG.x(3)
MG.mcx([3,4,5],6)
MG.x(3)
elif desired_color_code == 4:
MG.x(4)
MG.x(5)
MG.mcx([3,4,5],6)
MG.x(4)
MG.x(5)
elif desired_color_code == 5:
MG.x(4)
MG.mcx([3,4,5],6)
MG.x(4)
elif desired_color_code == 6:
MG.x(4)
MG.mcx([3,4,5],6)
MG.x(4)
elif desired_color_code == 7:
MG.mcx([3,4,5],6)
MG.draw()
oracle = QuantumCircuit(7)
oracle = oracle + DB + MG + DB
oracle.draw()
phase = QuantumCircuit(7)
phase.x(0)
phase.x(1)
phase.x(2)
phase.h(2)
phase.ccx(0,1,2)
phase.h(2)
phase.x(0)
phase.x(1)
phase.x(2)
phase.draw()
Grover = QuantumCircuit(7)
Grover = Grover + oracle
Grover.h(0)
Grover.h(1)
Grover.h(2)
Grover = Grover + phase
Grover.h(0)
Grover.h(1)
Grover.h(2)
Grover = Grover + Grover
Grover.draw()
circuit = QuantumCircuit(7,3)
circuit.x(6)
circuit.h(0)
circuit.h(1)
circuit.h(2)
circuit.h(6)
circuit = circuit + Grover
circuit.measure(0,2)
circuit.measure(1,1)
circuit.measure(2,0)
sim = Aer.get_backend ('qasm_simulator')
results = execute(circuit,sim,shots = 1000)
counts = results.result().get_counts()
def mitigated_results(backend,circuit,results,results_sim):
# Import the required classes
from qiskit.providers.aer.noise import NoiseModel
from qiskit.ignis.mitigation.measurement import (complete_meas_cal,CompleteMeasFitter)
# Get noise model for backend
noise_model = NoiseModel.from_backend(backend)
# Create the measurement fitter
qr = QuantumRegister(circuit.num_qubits)
meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal')
job = execute(meas_calibs,
backend=Aer.get_backend('qasm_simulator'),
shots=1000, noise_model=noise_model)
cal_results = job.result()
meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal')
print(meas_fitter.cal_matrix)
# Get the filter object
meas_filter = meas_fitter.filter
# Results with mitigation
mitigated_results = meas_filter.apply(results)
mitigated_counts = mitigated_results.get_counts(0)
return(mitigated_counts)
plot_histogram( mitigated_counts)
plot_histogram(counts)
from qiskit import IBMQ, BasicAer
from qiskit.providers.ibmq import least_busy
from qiskit import QuantumCircuit,transpile,execute
from qiskit.tools.jupyter import *
import qiskit
# Qiskit quantum circuits libraries
# prepare your circuit to run
from qiskit import IBMQ
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q-education', group='iisc-bangalore-1', project = 'm-tech-quantum-t')
device = provider.get_backend('ibmq_casablanca')
from qiskit.tools.monitor import job_monitor
from qiskit import transpile, assemble
def transpile_circuit(circuit,backend):
trans_circ = transpile(circuit, backend)
display(trans_circ.draw(output="mpl"))
transpiled_grover_circuit = transpile(circuit, device, optimization_level=3)
print("Circuit data\n\nDepth: ",transpiled_grover_circuit.depth(),"\
nWidth: ",transpiled_grover_circuit.width(),"\nSize: ",transpiled_grover_circuit.
size())
job = device.run(transpiled_grover_circuit)
job_monitor(job, interval=2)
results = job.result()
answer = results.get_counts(circuit)
plot_histogram(answer)
transpiled_grover_circuit.draw()
|
https://github.com/BOBO1997/osp_solutions
|
BOBO1997
|
import numpy as np
import matplotlib.pyplot as plt
import itertools
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
from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer
from qiskit.providers.aer import QasmSimulator
from qiskit.tools.monitor import job_monitor
from qiskit.circuit import Parameter
from qiskit.transpiler.passes import RemoveBarriers
backend = Aer.get_backend("qasm_simulator")
def make_initial_state(qc, initial_state):
"""
logical qubit index
little endian
"""
for i, state in enumerate(initial_state):
if state == "1":
qc.x(i)
def subspace_encoder(qc, targets):
"""
naive method, can be optimized for init state |110>
little endian
"""
n = qc.num_qubits
qc.cx(targets[0],targets[1])
qc.cx(targets[2],targets[1])
qc.cx(targets[1],targets[2])
qc.cx(targets[0],targets[1])
qc.cx(targets[1],targets[0])
def subspace_encoder_init110(qc, targets):
"""
optimized encoder for init state |110>
endian: |q_0, q_1, q_2> (little endian)
encode |110> to |0>|10>
"""
n = qc.num_qubits
qc.x(targets[0])
def subspace_decoder(qc, targets):
"""
naive method
little endian
"""
n = qc.num_qubits
qc.cx(targets[1],targets[0])
qc.cx(targets[0],targets[1])
qc.cx(targets[1],targets[2])
qc.cx(targets[2],targets[1])
qc.cx(targets[0],targets[1])
# Combine subcircuits into a single multiqubit gate representing a single trotter step
num_qubits = 3
# initial layout
initial_layout = [5,3,1]
qr = QuantumRegister(num_qubits, name="lq")
qc = QuantumCircuit(qr)
qc.x([1])
qc.barrier()
subspace_encoder(qc, targets=[0, 1, 2]) # encode
qc.measure_all()
t3_qc = transpile(qc, optimization_level=3, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout)
t3_qc.draw("mpl")
execute(qc, backend).result().get_counts()
|
https://github.com/jaykomarraju/Quantum-Optimization-for-Solar-Farm
|
jaykomarraju
|
import numpy as np
import networkx as nx
from qiskit import Aer
from qiskit.algorithms import QAOA, NumPyMinimumEigensolver
from qiskit.algorithms.optimizers import COBYLA
from qiskit.utils import QuantumInstance
from qiskit_optimization import QuadraticProgram
from qiskit_optimization.algorithms import MinimumEigenOptimizer
num_time_slots = 24
# Define the QUBO problem
qubo = QuadraticProgram()
# Add binary variables for charging (c) and discharging (d) states
for t in range(num_time_slots):
qubo.binary_var(f'c_{t}')
qubo.binary_var(f'd_{t}')
# Define the objective function
# (In practice, you need to calculate Jij and hi based on the solar farm data)
Jij = np.random.rand(num_time_slots, num_time_slots) * 0.5
hi_c = -1 + np.random.rand(num_time_slots)
hi_d = 1 - np.random.rand(num_time_slots)
# Set linear and quadratic terms of the objective function
linear_terms = {}
quadratic_terms = {}
for t in range(num_time_slots):
linear_terms[f'c_{t}'] = hi_c[t]
linear_terms[f'd_{t}'] = hi_d[t]
for s in range(num_time_slots):
if t != s:
quadratic_terms[(f'c_{t}', f'c_{s}')] = Jij[t, s]
quadratic_terms[(f'd_{t}', f'd_{s}')] = Jij[t, s]
qubo.minimize(linear=linear_terms, quadratic=quadratic_terms)
# Set up the quantum instance
backend = Aer.get_backend('qasm_simulator')
quantum_instance = QuantumInstance(backend, seed_simulator=42, seed_transpiler=42, shots=10000)
# Set up the QAOA algorithm and optimizer
optimizer = COBYLA(maxiter=500)
qaoa = QAOA(optimizer=optimizer, reps=5, quantum_instance=quantum_instance)
# Set up the minimum eigen optimizer
min_eig_optimizer = MinimumEigenOptimizer(qaoa)
# Solve the problem
result = min_eig_optimizer.solve(qubo)
print("QAOA result:", result)
# Solve the problem using a classical solver (NumPyMinimumEigensolver)
exact_solver = MinimumEigenOptimizer(NumPyMinimumEigensolver())
exact_result = exact_solver.solve(qubo)
print("Classical result:", exact_result)
|
https://github.com/rodneyosodo/variational-quantum-classifier-on-heartattack
|
rodneyosodo
|
from qiskit.ml.datasets import *
from qiskit import QuantumCircuit
from qiskit.aqua.components.optimizers import COBYLA, ADAM, SPSA, SLSQP, POWELL, L_BFGS_B, TNC, AQGD
from qiskit.circuit.library import ZZFeatureMap, RealAmplitudes
from qiskit.quantum_info import Statevector
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.preprocessing import MinMaxScaler
from sklearn.model_selection import train_test_split
from sklearn.utils import shuffle
import warnings
warnings.filterwarnings("ignore")
%matplotlib inline
# constants
n = 4
RANDOM_STATE = 42
LR = 1e-3
class_labels = ['yes', 'no']
def normalizeData(DATA_PATH = "../../Data/Processed/winedata.csv"):
"""
Normalizes the data
"""
# Reads the data
data = pd.read_csv(DATA_PATH)
data = shuffle(data, random_state=RANDOM_STATE)
X, Y = data[['alcohol', 'flavanoids', 'color_intensity', 'proline']].values, data['target'].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=RANDOM_STATE)
return X_train, X_test, Y_train, Y_test
X_train, X_test, Y_train, Y_test = normalizeData()
sv = Statevector.from_label('0' * n)
feature_map = ZZFeatureMap(n, reps=1)
var_form = RealAmplitudes(n, reps=1)
circuit = feature_map.combine(var_form)
circuit.draw(output='mpl')
def get_data_dict(params, x):
parameters = {}
for i, p in enumerate(feature_map.ordered_parameters):
parameters[p] = x[i]
for i, p in enumerate(var_form.ordered_parameters):
parameters[p] = params[i]
return parameters
def assign_label(bit_string, class_labels):
hamming_weight = sum([int(k) for k in list(bit_string)])
is_odd_parity = hamming_weight & 1
if is_odd_parity:
return class_labels[1]
else:
return class_labels[0]
def return_probabilities(counts, class_labels):
shots = sum(counts.values())
result = {class_labels[0]: 0,
class_labels[1]: 0}
for key, item in counts.items():
label = assign_label(key, class_labels)
result[label] += counts[key]/shots
return result
def classify(x_list, params, class_labels):
qc_list = []
for x in x_list:
circ_ = circuit.assign_parameters(get_data_dict(params, x))
qc = sv.evolve(circ_)
qc_list += [qc]
probs = []
for qc in qc_list:
counts = qc.to_counts()
prob = return_probabilities(counts, class_labels)
probs += [prob]
return probs
def mse_cost(probs, expected_label):
p = probs.get(expected_label)
actual, pred = np.array(1), np.array(p)
return np.square(np.subtract(actual,pred)).mean()
cost_list = []
def cost_function(X, Y, class_labels, params, shots=100, print_value=False):
# 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 += [class_labels[0]]
elif label == 1:
training_labels += [class_labels[1]]
probs = classify(training_samples, params, class_labels)
# evaluate costs for all classified samples
for i, prob in enumerate(probs):
cost += mse_cost(prob, training_labels[i])
cost /= len(training_samples)
# print resulting objective function
if print_value:
print('%.4f' % cost)
# return objective value
cost_list.append(cost)
return cost
cost_list = []
optimizer = SPSA(maxiter=100)
# define objective function for training
objective_function = lambda params: cost_function(X_train, Y_train, class_labels, params, print_value=True)
# randomly initialize the parameters
np.random.seed(RANDOM_STATE)
init_params = 2*np.pi*np.random.rand(n*(1)*2)
# train classifier
opt_params, value, _ = optimizer.optimize(len(init_params), objective_function, initial_point=init_params)
# print results
print()
print('opt_params:', opt_params)
print('opt_value: ', value)
fig = plt.figure()
plt.plot(range(0,len(cost_list),1), cost_list)
plt.xlabel('Steps')
plt.ylabel('Cost value')
plt.title("ADAM Cost value against steps")
plt.show()
def test_model(X, Y, class_labels, params):
accuracy = 0
training_labels = []
training_samples = []
for sample in X:
training_samples += [sample]
probs = classify(training_samples, params, class_labels)
for i, prob in enumerate(probs):
if (prob.get('yes') >= prob.get('no')) and (Y_test[i] == 0):
accuracy += 1
elif (prob.get('no') >= prob.get('yes')) and (Y_test[i] == 1):
accuracy += 1
accuracy /= len(Y_test)
print("Test accuracy: {}\n".format(accuracy))
test_model(X_test, Y_test, class_labels, opt_params)
|
https://github.com/COFAlumni-USB/qiskit-fall-2022
|
COFAlumni-USB
|
import numpy as np
import math
import qiskit as qiskit
from numpy import sqrt
from random import randint
from qiskit import *
from qiskit import Aer, QuantumCircuit, IBMQ, execute, quantum_info, transpile
from qiskit.visualization import plot_state_city, plot_bloch_multivector
from qiskit.visualization import plot_histogram
from qiskit.tools import job_monitor
from qiskit.providers.fake_provider import FakeOpenPulse2Q, FakeOpenPulse3Q, FakeManila, FakeValencia, FakeHanoi
from qiskit import pulse, transpile
from qiskit.pulse.library import Gaussian
#Compuertas personalizadas
from qiskit.circuit import Gate
from qiskit import QiskitError
#informacion
import qiskit.tools.jupyter
provider = IBMQ.load_account()
belem = provider.get_backend('ibmq_belem')
print('se ha ejecutado correctamente')
def SoQ_Grover_0(qc, x_qubit_0,x_qubit_1,y_qubit):
qc.ccx(x_qubit_0,x_qubit_1,y_qubit)
return qc
def SoQ_Grover_1(qc, x_qubit_0,x_qubit_1,y_qubit):
qc.x(x_qubit_0)
qc.ccx(x_qubit_0,x_qubit_1,y_qubit)
qc.x(x_qubit_0)
return qc
def SoQ_Grover_2(qc, x_qubit_0,x_qubit_1,y_qubit):
qc.x(x_qubit_1)
qc.ccx(x_qubit_0,x_qubit_1,y_qubit)
qc.x(x_qubit_1)
return qc
def SoQ_Grover_3(qc, x_qubit_0,x_qubit_1,y_qubit):
qc.x(x_qubit_0)
qc.x(x_qubit_1)
qc.ccx(x_qubit_0,x_qubit_1,y_qubit)
qc.x(x_qubit_0)
qc.x(x_qubit_1)
return qc
def random_oracle(qc, x_qubit_0,x_qubit_1,y_qubit):
rand=randint(0,3)
if rand==3:
SoQ_Grover_0(qc, x_qubit_0,x_qubit_1,y_qubit)
elif rand==2:
SoQ_Grover_1(qc, x_qubit_0,x_qubit_1,y_qubit)
elif rand==1:
SoQ_Grover_2(qc, x_qubit_0,x_qubit_1,y_qubit)
else:
SoQ_Grover_3(qc, x_qubit_0,x_qubit_1,y_qubit)
return qc
def Grover_Iteration(qc, x_qubit_0,x_qubit_1):
qc.h(range(2))
qc.x(range(2))
qc.h(x_qubit_1)
qc.cx(x_qubit_0,x_qubit_1)
qc.h(x_qubit_1)
qc.x(range(2))
qc.h(range(2))
return qc
print('se ha ejecutado correctamente')
#Simulador de prueba FakeManila
backend = FakeManila()
x_register=2
y_register=1
measure_register=2
y_position=x_register+y_register-1
circ = QuantumCircuit(x_register+y_register,measure_register)
circ.x(y_position)
circ.barrier()
circ.h(range(x_register+y_register))
circ.barrier()
random_oracle(circ, 0,1,2)
circ.barrier()
Grover_Iteration(circ, 0,1)
circ.measure(range(x_register),range(measure_register))
circ.draw('mpl')
result = execute(circ, backend=FakeManila()).result();
job = backend.run(circ)
counts = job.result().get_counts()
plot_histogram(counts)
backend = FakeManila();
with pulse.build(backend, name='hadamard') as h_q0:
pulse.play(Gaussian(duration=100, amp=0.1, sigma=3), pulse.drive_channel(0))
h_q0.draw()
backend = FakeManila();
with pulse.build(backend, name='hadamard') as h_q0: #el 'h_q0 es invariable y puede ser nombrado de cualquier forma solo identifica'
pulse.play(Gaussian(duration=100, amp=0.1, sigma=33.33), pulse.drive_channel(0))
h_q0.draw()
circ.add_calibration( 'h', [0], h_q0)
circ.add_calibration( 'x', [0], h_q0)
circ.add_calibration( 'cx',[0], h_q0)
circ.add_calibration( 'sx',[0], h_q0)
circ.add_calibration( 'id',[0], h_q0)
circ.add_calibration( 'rz',[0], h_q0)
circ.add_calibration( 'reset',[0], h_q0)
backend = FakeManila()
circ1 = transpile(circ, backend)
print(backend.configuration().basis_gates)
circ1.draw('mpl', idle_wires=False)
result = execute(circ1, backend=FakeManila()).result();
job = backend.run(circ1)
counts = job.result().get_counts()
plot_histogram(counts)
def SoQ_Grover_0(qc, x_qubit_0,x_qubit_1,y_qubit):
qc.ccx(x_qubit_0,x_qubit_1,y_qubit)
return qc
def SoQ_Grover_1(qc, x_qubit_0,x_qubit_1,y_qubit):
qc.x(x_qubit_0)
qc.ccx(x_qubit_0,x_qubit_1,y_qubit)
qc.x(x_qubit_0)
return qc
def SoQ_Grover_2(qc, x_qubit_0,x_qubit_1,y_qubit):
qc.x(x_qubit_1)
qc.ccx(x_qubit_0,x_qubit_1,y_qubit)
qc.x(x_qubit_1)
return qc
def SoQ_Grover_3(qc, x_qubit_0,x_qubit_1,y_qubit):
qc.x(x_qubit_0)
qc.x(x_qubit_1)
qc.ccx(x_qubit_0,x_qubit_1,y_qubit)
qc.x(x_qubit_0)
qc.x(x_qubit_1)
return qc
def random_oracle(qc, x_qubit_0,x_qubit_1,y_qubit):
rand=randint(0,3)
if rand==3:
SoQ_Grover_0(qc, x_qubit_0,x_qubit_1,y_qubit)
elif rand==2:
SoQ_Grover_1(qc, x_qubit_0,x_qubit_1,y_qubit)
elif rand==1:
SoQ_Grover_2(qc, x_qubit_0,x_qubit_1,y_qubit)
else:
SoQ_Grover_3(qc, x_qubit_0,x_qubit_1,y_qubit)
return qc
def Grover_Iteration(qc, x_qubit_0,x_qubit_1):
qc.h(range(2))
qc.x(range(2))
qc.h(x_qubit_1)
qc.cx(x_qubit_0,x_qubit_1)
qc.h(x_qubit_1)
qc.x(range(2))
qc.h(range(2))
return qc
print('se ha ejecutado correctamente')
#Simulador de prueba FakeOpenPulse3Q
backend = FakeOpenPulse3Q()
x_register=2
y_register=1
measure_register=2
y_position=x_register+y_register-1
circ = QuantumCircuit(x_register+y_register,measure_register)
circ.x(y_position)
circ.barrier()
circ.h(range(x_register+y_register))
circ.barrier()
random_oracle(circ, 0,1,2)
circ.barrier()
Grover_Iteration(circ, 0,1)
circ.measure(range(x_register),range(measure_register))
circ.draw('mpl')
result = execute(circ, backend=FakeOpenPulse3Q()).result();
job = backend.run(circ)
counts = job.result().get_counts()
plot_histogram(counts)
backend = FakeOpenPulse3Q();
with pulse.build(backend, name='hadamard') as h_q1:
pulse.play(Gaussian(duration=100, amp=0.1, sigma=3), pulse.drive_channel(0))
h_q1.draw()
backend = FakeOpenPulse3Q();
with pulse.build(backend, name='hadamard') as h_q1: #el 'h_q1 es invariable y puede ser nombrado de cualquier forma solo identifica'
pulse.play(Gaussian(duration=100, amp=0.1, sigma=33.33), pulse.drive_channel(0))
h_q1.draw()
circ.add_calibration( 'h', [0], h_q1)
circ.add_calibration( 'x', [0], h_q1)
circ.add_calibration( 'cx',[0], h_q1)
circ.add_calibration( 'sx',[0], h_q1)
circ.add_calibration( 'id',[0], h_q1)
circ.add_calibration( 'rz',[0], h_q1)
circ.add_calibration( 'reset',[0], h_q1)
backend = FakeOpenPulse3Q()
circ2 = transpile(circ, backend)
print(backend.configuration().basis_gates)
circ2.draw('mpl', idle_wires=False)
result = execute(circ2, backend=FakeManila()).result();
job = backend.run(circ2)
counts = job.result().get_counts()
plot_histogram(counts)
def SoQ_Grover_0(qc, x_qubit_0,x_qubit_1,y_qubit):
qc.ccx(x_qubit_0,x_qubit_1,y_qubit)
return qc
def SoQ_Grover_1(qc, x_qubit_0,x_qubit_1,y_qubit):
qc.x(x_qubit_0)
qc.ccx(x_qubit_0,x_qubit_1,y_qubit)
qc.x(x_qubit_0)
return qc
def SoQ_Grover_2(qc, x_qubit_0,x_qubit_1,y_qubit):
qc.x(x_qubit_1)
qc.ccx(x_qubit_0,x_qubit_1,y_qubit)
qc.x(x_qubit_1)
return qc
def SoQ_Grover_3(qc, x_qubit_0,x_qubit_1,y_qubit):
qc.x(x_qubit_0)
qc.x(x_qubit_1)
qc.ccx(x_qubit_0,x_qubit_1,y_qubit)
qc.x(x_qubit_0)
qc.x(x_qubit_1)
return qc
def random_oracle(qc, x_qubit_0,x_qubit_1,y_qubit):
rand=randint(0,3)
if rand==3:
SoQ_Grover_0(qc, x_qubit_0,x_qubit_1,y_qubit)
elif rand==2:
SoQ_Grover_1(qc, x_qubit_0,x_qubit_1,y_qubit)
elif rand==1:
SoQ_Grover_2(qc, x_qubit_0,x_qubit_1,y_qubit)
else:
SoQ_Grover_3(qc, x_qubit_0,x_qubit_1,y_qubit)
return qc
def Grover_Iteration(qc, x_qubit_0,x_qubit_1):
qc.h(range(2))
qc.x(range(2))
qc.h(x_qubit_1)
qc.cx(x_qubit_0,x_qubit_1)
qc.h(x_qubit_1)
qc.x(range(2))
qc.h(range(2))
return qc
print('se ha ejecutado correctamente')
#Simulador de prueba FakeManila
backend = FakeManila()
x_register=2
y_register=1
measure_register=2
y_position=x_register+y_register-1
circ = QuantumCircuit(x_register+y_register,measure_register)
circ.x(y_position)
circ.barrier()
circ.h(range(x_register+y_register))
circ.barrier()
random_oracle(circ, 0,1,2)
circ.barrier()
Grover_Iteration(circ, 0,1)
circ.measure(range(x_register),range(measure_register))
circ.draw('mpl')
result = execute(circ, backend=FakeManila()).result();
job = backend.run(circ)
counts = job.result().get_counts()
plot_histogram(counts)
backend = FakeManila();
with pulse.build(backend, name='hadamard') as h_q0:
pulse.play(Gaussian(duration=100, amp=0.1, sigma=3), pulse.drive_channel(0))
h_q0.draw()
backend = FakeManila();
with pulse.build(backend, name='hadamard') as h_q0:
pulse.play(Gaussian(duration=100, amp=0.1, sigma=10), pulse.drive_channel(0))
h_q0.draw()
circ.add_calibration( 'h', [0], h_q0)
circ.add_calibration( 'x', [0], h_q0)
circ.add_calibration( 'cx',[0], h_q0)
circ.add_calibration( 'sx',[0], h_q0)
circ.add_calibration( 'id',[0], h_q0)
circ.add_calibration( 'rz',[0], h_q0)
circ.add_calibration( 'reset',[0], h_q0)
backend = FakeManila()
circ1 = transpile(circ, backend)
print(backend.configuration().basis_gates)
circ1.draw('mpl', idle_wires=False)
result = execute(circ1, backend=FakeManila()).result();
job = backend.run(circ1)
counts = job.result().get_counts()
plot_histogram(counts)
def SoQ_Grover_0(qc, x_qubit_0,x_qubit_1,y_qubit):
qc.ccx(x_qubit_0,x_qubit_1,y_qubit)
return qc
def SoQ_Grover_1(qc, x_qubit_0,x_qubit_1,y_qubit):
qc.x(x_qubit_0)
qc.ccx(x_qubit_0,x_qubit_1,y_qubit)
qc.x(x_qubit_0)
return qc
def SoQ_Grover_2(qc, x_qubit_0,x_qubit_1,y_qubit):
qc.x(x_qubit_1)
qc.ccx(x_qubit_0,x_qubit_1,y_qubit)
qc.x(x_qubit_1)
return qc
def SoQ_Grover_3(qc, x_qubit_0,x_qubit_1,y_qubit):
qc.x(x_qubit_0)
qc.x(x_qubit_1)
qc.ccx(x_qubit_0,x_qubit_1,y_qubit)
qc.x(x_qubit_0)
qc.x(x_qubit_1)
return qc
def random_oracle(qc, x_qubit_0,x_qubit_1,y_qubit):
rand=randint(0,3)
if rand==3:
SoQ_Grover_0(qc, x_qubit_0,x_qubit_1,y_qubit)
elif rand==2:
SoQ_Grover_1(qc, x_qubit_0,x_qubit_1,y_qubit)
elif rand==1:
SoQ_Grover_2(qc, x_qubit_0,x_qubit_1,y_qubit)
else:
SoQ_Grover_3(qc, x_qubit_0,x_qubit_1,y_qubit)
return qc
def Grover_Iteration(qc, x_qubit_0,x_qubit_1):
qc.h(range(2))
qc.x(range(2))
qc.h(x_qubit_1)
qc.cx(x_qubit_0,x_qubit_1)
qc.h(x_qubit_1)
qc.x(range(2))
qc.h(range(2))
return qc
print('se ha ejecutado correctamente')
#Simulador de prueba FakeOpenPulse3Q
backend = FakeOpenPulse3Q()
x_register=2
y_register=1
measure_register=2
y_position=x_register+y_register-1
circ = QuantumCircuit(x_register+y_register,measure_register)
circ.x(y_position)
circ.barrier()
circ.h(range(x_register+y_register))
circ.barrier()
random_oracle(circ, 0,1,2)
circ.barrier()
Grover_Iteration(circ, 0,1)
circ.measure(range(x_register),range(measure_register))
circ.draw('mpl')
result = execute(circ, backend=FakeOpenPulse3Q()).result();
job = backend.run(circ)
counts = job.result().get_counts()
plot_histogram(counts)
backend = FakeOpenPulse3Q();
with pulse.build(backend, name='hadamard') as h_q1:
pulse.play(Gaussian(duration=100, amp=0.1, sigma=3), pulse.drive_channel(0))
h_q1.draw()
backend = FakeOpenPulse3Q();
with pulse.build(backend, name='hadamard') as h_q1:
pulse.play(Gaussian(duration=100, amp=0.1, sigma=10), pulse.drive_channel(0))
h_q1.draw()
circ.add_calibration( 'h', [0], h_q1)
circ.add_calibration( 'x', [0], h_q1)
circ.add_calibration( 'cx',[0], h_q1)
circ.add_calibration( 'sx',[0], h_q1)
circ.add_calibration( 'id',[0], h_q1)
circ.add_calibration( 'rz',[0], h_q1)
circ.add_calibration( 'reset',[0], h_q1)
backend = FakeOpenPulse3Q()
circ2 = transpile(circ, backend)
print(backend.configuration().basis_gates)
circ2.draw('mpl', idle_wires=False)
result = execute(circ2, backend=FakeOpenPulse3Q()).result();
job = backend.run(circ2)
counts = job.result().get_counts()
plot_histogram(counts)
def SoQ_Grover_0(qc, x_qubit_0,x_qubit_1,y_qubit):
qc.ccx(x_qubit_0,x_qubit_1,y_qubit)
return qc
def SoQ_Grover_1(qc, x_qubit_0,x_qubit_1,y_qubit):
qc.x(x_qubit_0)
qc.ccx(x_qubit_0,x_qubit_1,y_qubit)
qc.x(x_qubit_0)
return qc
def SoQ_Grover_2(qc, x_qubit_0,x_qubit_1,y_qubit):
qc.x(x_qubit_1)
qc.ccx(x_qubit_0,x_qubit_1,y_qubit)
qc.x(x_qubit_1)
return qc
def SoQ_Grover_3(qc, x_qubit_0,x_qubit_1,y_qubit):
qc.x(x_qubit_0)
qc.x(x_qubit_1)
qc.ccx(x_qubit_0,x_qubit_1,y_qubit)
qc.x(x_qubit_0)
qc.x(x_qubit_1)
return qc
def random_oracle(qc, x_qubit_0,x_qubit_1,y_qubit):
rand=randint(0,3)
if rand==3:
SoQ_Grover_0(qc, x_qubit_0,x_qubit_1,y_qubit)
elif rand==2:
SoQ_Grover_1(qc, x_qubit_0,x_qubit_1,y_qubit)
elif rand==1:
SoQ_Grover_2(qc, x_qubit_0,x_qubit_1,y_qubit)
else:
SoQ_Grover_3(qc, x_qubit_0,x_qubit_1,y_qubit)
return qc
def Grover_Iteration(qc, x_qubit_0,x_qubit_1):
qc.h(range(2))
qc.x(range(2))
qc.h(x_qubit_1)
qc.cx(x_qubit_0,x_qubit_1)
qc.h(x_qubit_1)
qc.x(range(2))
qc.h(range(2))
return qc
print('se ha ejecutado correctamente')
#Simulador de prueba FakeManila
backend = FakeManila()
x_register=2
y_register=1
measure_register=2
y_position=x_register+y_register-1
circ = QuantumCircuit(x_register+y_register,measure_register)
circ.x(y_position)
circ.barrier()
circ.h(range(x_register+y_register))
circ.barrier()
random_oracle(circ, 0,1,2)
circ.barrier()
Grover_Iteration(circ, 0,1)
circ.measure(range(x_register),range(measure_register))
circ.draw('mpl')
result = execute(circ, backend=FakeManila()).result();
job = backend.run(circ)
counts = job.result().get_counts()
plot_histogram(counts)
backend = FakeManila();
with pulse.build(backend, name='hadamard') as h_q0:
pulse.play(Gaussian(duration=100, amp=0.1, sigma=3), pulse.drive_channel(0))
h_q0.draw()
backend = FakeManila();
with pulse.build(backend, name='hadamard') as h_q0:
pulse.play(Gaussian(duration=100, amp=0.1, sigma=5), pulse.drive_channel(0))
h_q0.draw()
circ.add_calibration( 'h', [0], h_q0)
circ.add_calibration( 'x', [0], h_q0)
circ.add_calibration( 'cx',[0], h_q0)
circ.add_calibration( 'sx',[0], h_q0)
circ.add_calibration( 'id',[0], h_q0)
circ.add_calibration( 'rz',[0], h_q0)
circ.add_calibration( 'reset',[0], h_q0)
backend = FakeManila()
circ1 = transpile(circ, backend)
print(backend.configuration().basis_gates)
circ1.draw('mpl', idle_wires=False)
result = execute(circ1, backend=FakeManila()).result();
job = backend.run(circ1)
counts = job.result().get_counts()
plot_histogram(counts)
def SoQ_Grover_0(qc, x_qubit_0,x_qubit_1,y_qubit):
qc.ccx(x_qubit_0,x_qubit_1,y_qubit)
return qc
def SoQ_Grover_1(qc, x_qubit_0,x_qubit_1,y_qubit):
qc.x(x_qubit_0)
qc.ccx(x_qubit_0,x_qubit_1,y_qubit)
qc.x(x_qubit_0)
return qc
def SoQ_Grover_2(qc, x_qubit_0,x_qubit_1,y_qubit):
qc.x(x_qubit_1)
qc.ccx(x_qubit_0,x_qubit_1,y_qubit)
qc.x(x_qubit_1)
return qc
def SoQ_Grover_3(qc, x_qubit_0,x_qubit_1,y_qubit):
qc.x(x_qubit_0)
qc.x(x_qubit_1)
qc.ccx(x_qubit_0,x_qubit_1,y_qubit)
qc.x(x_qubit_0)
qc.x(x_qubit_1)
return qc
def random_oracle(qc, x_qubit_0,x_qubit_1,y_qubit):
rand=randint(0,3)
if rand==3:
SoQ_Grover_0(qc, x_qubit_0,x_qubit_1,y_qubit)
elif rand==2:
SoQ_Grover_1(qc, x_qubit_0,x_qubit_1,y_qubit)
elif rand==1:
SoQ_Grover_2(qc, x_qubit_0,x_qubit_1,y_qubit)
else:
SoQ_Grover_3(qc, x_qubit_0,x_qubit_1,y_qubit)
return qc
def Grover_Iteration(qc, x_qubit_0,x_qubit_1):
qc.h(range(2))
qc.x(range(2))
qc.h(x_qubit_1)
qc.cx(x_qubit_0,x_qubit_1)
qc.h(x_qubit_1)
qc.x(range(2))
qc.h(range(2))
return qc
print('se ha ejecutado correctamente')
#Simulador de prueba FakeOpenPulse3Q
backend = FakeOpenPulse3Q()
x_register=2
y_register=1
measure_register=2
y_position=x_register+y_register-1
circ = QuantumCircuit(x_register+y_register,measure_register)
circ.x(y_position)
circ.barrier()
circ.h(range(x_register+y_register))
circ.barrier()
random_oracle(circ, 0,1,2)
circ.barrier()
Grover_Iteration(circ, 0,1)
circ.measure(range(x_register),range(measure_register))
circ.draw('mpl')
result = execute(circ, backend=FakeOpenPulse3Q()).result();
job = backend.run(circ)
counts = job.result().get_counts()
plot_histogram(counts)
backend = FakeOpenPulse3Q();
with pulse.build(backend, name='hadamard') as h_q1:
pulse.play(Gaussian(duration=100, amp=0.1, sigma=3), pulse.drive_channel(0))
h_q1.draw()
backend = FakeOpenPulse3Q();
with pulse.build(backend, name='hadamard') as h_q1:
pulse.play(Gaussian(duration=100, amp=0.1, sigma=5), pulse.drive_channel(0))
h_q1.draw()
circ.add_calibration( 'h', [0], h_q1)
circ.add_calibration( 'x', [0], h_q1)
circ.add_calibration( 'cx',[0], h_q1)
circ.add_calibration( 'sx',[0], h_q1)
circ.add_calibration( 'id',[0], h_q1)
circ.add_calibration( 'rz',[0], h_q1)
circ.add_calibration( 'reset',[0], h_q1)
backend = FakeOpenPulse3Q()
circ2 = transpile(circ, backend)
print(backend.configuration().basis_gates)
circ2.draw('mpl', idle_wires=False)
result = execute(circ2, backend=FakeOpenPulse3Q()).result();
job = backend.run(circ2)
counts = job.result().get_counts()
plot_histogram(counts)
|
https://github.com/Keerthiraj-Nagaraj/IBM-quantum-challenge-2020
|
Keerthiraj-Nagaraj
|
from IPython.display import Image, display
Image("ryoko.png", width="70")
Image('asteroids_example.png')
Image('asteroids_beam_example.png')
Image('false_asteroids_example.png')
Image('asteroids_example.png')
problem_set = \
[[['0', '2'], ['1', '0'], ['1', '2'], ['1', '3'], ['2', '0'], ['3', '3']],
[['0', '0'], ['0', '1'], ['1', '2'], ['2', '2'], ['3', '0'], ['3', '3']],
[['0', '0'], ['1', '1'], ['1', '3'], ['2', '0'], ['3', '2'], ['3', '3']],
[['0', '0'], ['0', '1'], ['1', '1'], ['1', '3'], ['3', '2'], ['3', '3']],
[['0', '2'], ['1', '0'], ['1', '3'], ['2', '0'], ['3', '2'], ['3', '3']],
[['1', '1'], ['1', '2'], ['2', '0'], ['2', '1'], ['3', '1'], ['3', '3']],
[['0', '2'], ['0', '3'], ['1', '2'], ['2', '0'], ['2', '1'], ['3', '3']],
[['0', '0'], ['0', '3'], ['1', '2'], ['2', '2'], ['2', '3'], ['3', '0']],
[['0', '3'], ['1', '1'], ['1', '2'], ['2', '0'], ['2', '1'], ['3', '3']],
[['0', '0'], ['0', '1'], ['1', '3'], ['2', '1'], ['2', '3'], ['3', '0']],
[['0', '1'], ['0', '3'], ['1', '2'], ['1', '3'], ['2', '0'], ['3', '2']],
[['0', '0'], ['1', '3'], ['2', '0'], ['2', '1'], ['2', '3'], ['3', '1']],
[['0', '1'], ['0', '2'], ['1', '0'], ['1', '2'], ['2', '2'], ['2', '3']],
[['0', '3'], ['1', '0'], ['1', '3'], ['2', '1'], ['2', '2'], ['3', '0']],
[['0', '2'], ['0', '3'], ['1', '2'], ['2', '3'], ['3', '0'], ['3', '1']],
[['0', '1'], ['1', '0'], ['1', '2'], ['2', '2'], ['3', '0'], ['3', '1']]]
import numpy as np
# import qiskit libraries
from qiskit import IBMQ, Aer,QuantumRegister, ClassicalRegister, QuantumCircuit, execute
from qiskit.tools.jupyter import *
from qiskit.circuit.library import OR as or_gate
provider = IBMQ.load_account()
#import functions to plot
from qiskit.visualization import plot_histogram
def week3_ans_func(problem_set):
##### build your quantum circuit here
##### In addition, please make it a function that can solve the problem even with different inputs (problem_set). We do validation with different inputs.
def qRAM(qc,add,data, auxiliary, problem_set):
problem_set_mapping_dict = {'0' : {'0': 0, '1': 1, '2': 2, '3':3},
'1' : {'0': 4, '1': 5, '2': 6, '3':7},
'2' : {'0': 8, '1': 9, '2': 10, '3':11},
'3' : {'0': 12, '1': 13, '2': 14, '3':15}}
for ind in range(len(data)):
binary = f'{ind:04b}'
if(binary[0] == '0'):
qc.x(add[0])
if(binary[1] == '0'):
qc.x(add[1])
if(binary[2] == '0'):
qc.x(add[2])
if(binary[3] == '0'):
qc.x(add[3])
for i, edg in enumerate(problem_set[ind]):
qc.ch(add[0],auxiliary[0])
qc.cz(add[1],auxiliary[0])
qc.ch(add[0], auxiliary[0])
#qc.ccx(add[0], add[1], auxiliary[0])
qc.ch(add[2],auxiliary[1])
qc.cz(add[3],auxiliary[1])
qc.ch(add[2], auxiliary[1])
#qc.ccx(add[2], add[3], auxiliary[1])
qc.ch(auxiliary[0],auxiliary[2])
qc.cz(auxiliary[1],auxiliary[2])
qc.ch(auxiliary[0],auxiliary[2])
#qc.ccx(auxiliary[0], auxiliary[1], auxiliary[2])
qc.cx(auxiliary[2], data[problem_set_mapping_dict[edg[0]][edg[1]]])
qc.ch(auxiliary[0],auxiliary[2])
qc.cz(auxiliary[1],auxiliary[2])
qc.ch(auxiliary[0],auxiliary[2])
qc.ch(add[2],auxiliary[1])
qc.cz(add[3],auxiliary[1])
qc.ch(add[2], auxiliary[1])
qc.ch(add[0],auxiliary[0])
qc.cz(add[1],auxiliary[0])
qc.ch(add[0], auxiliary[0])
if(binary[0] == '0'):
qc.x(add[0])
if(binary[1] == '0'):
qc.x(add[1])
if(binary[2] == '0'):
qc.x(add[2])
if(binary[3] == '0'):
qc.x(add[3])
qc.barrier()
def diffuser(nqubits):
qc_diff = QuantumCircuit(nqubits)
for qubit in range(nqubits):
qc_diff.h(qubit)
for qubit in range(nqubits):
qc_diff.x(qubit)
qc_diff.h(nqubits-1)
qc_diff.mct(list(range(nqubits-1)), nqubits-1) # multi-controlled-toffoli
qc_diff.h(nqubits-1)
for qubit in range(nqubits):
qc_diff.x(qubit)
for qubit in range(nqubits):
qc_diff.h(qubit)
U_f0 = qc_diff.to_gate()
U_f0.name = "V"
return U_f0
def add_row_counters(qc, data, auxiliary):
row_mat = [[0, 1, 2, 3],
[4, 5, 6, 7],
[8, 9, 10, 11],
[12, 13, 14, 15]]
for i, curr_row in enumerate(row_mat):
flag_list = [0] * len(data)
for curr_flag_index in range(len(data)):
if curr_flag_index in curr_row:
flag_list[curr_flag_index] = 1
qc.append(or_gate(len(data), flag_list, mcx_mode='noancilla'), [*data, auxiliary[i]])
def add_column_counters(qc, data, auxiliary):
col_mat = [[0, 4, 8, 12],
[1, 5, 9, 13],
[2, 6, 10, 14],
[3, 7, 11, 15]]
for i, curr_col in enumerate(col_mat):
flag_list = [0] * len(data)
for curr_flag_index in range(len(data)):
if curr_flag_index in curr_col:
flag_list[curr_flag_index] = 1
qc.append(or_gate(len(data), flag_list, mcx_mode='noancilla'), [*data, auxiliary[i]])
def add_lone_counters(qc, data, auxiliary, count_out):
lone_mat = [[0, 1, 2, 3, 4, 8, 12],
[1, 0, 2, 3, 5, 9, 13],
[2, 0, 1, 3, 6, 10, 14],
[3, 0, 1, 2, 7, 11, 15],
[4, 5, 6, 7, 0, 8, 12],
[5, 4, 6, 7, 1, 9, 13],
[6, 4, 5, 7, 2, 10, 14],
[7, 4, 5, 6, 3, 11, 15],
[8, 9, 10, 11, 0, 4, 12],
[9, 8, 10, 11, 1, 5, 13],
[10, 8, 9, 11, 2, 6, 14],
[11, 8, 9, 10, 3, 7, 15],
[12, 13, 14, 15, 0, 4, 8],
[13, 12, 14, 15, 1, 5, 9],
[14, 12, 13, 15, 2, 6, 10],
[15, 12, 13, 14, 3, 7, 11]]
qc.barrier()
#curr_lone_row = [0, 1, 2, 3, 4, 8, 12]
for curr_lone_row in lone_mat:
n = len(curr_lone_row)
for j in range(1,n):
qc.x(data[curr_lone_row[j]])
qc.ch(data[curr_lone_row[0]], auxiliary[0])
qc.cz(data[curr_lone_row[1]], auxiliary[0])
qc.ch(data[curr_lone_row[0]],auxiliary[0])
#qc.ccx(data[curr_lone_row[0]], data[curr_lone_row[1]], auxiliary[0])
qc.ch(data[curr_lone_row[2]],auxiliary[1])
qc.cz(data[curr_lone_row[3]],auxiliary[1])
qc.ch(data[curr_lone_row[2]],auxiliary[1])
#qc.ccx(data[curr_lone_row[2]], data[curr_lone_row[3]], auxiliary[1])
qc.ch(auxiliary[0],auxiliary[2])
qc.cz(auxiliary[1],auxiliary[2])
qc.ch(auxiliary[0],auxiliary[2])
#qc.ccx(auxiliary[0], auxiliary[1], auxiliary[2])
qc.ch(data[curr_lone_row[0]],auxiliary[0])
qc.cz(data[curr_lone_row[1]],auxiliary[0])
qc.ch(data[curr_lone_row[0]],auxiliary[0])
#qc.ccx(data[curr_lone_row[0]], data[curr_lone_row[1]], auxiliary[0])
qc.ch(data[curr_lone_row[4]],auxiliary[0])
qc.cz(data[curr_lone_row[5]],auxiliary[0])
qc.ch(data[curr_lone_row[4]],auxiliary[0])
#qc.ccx(data[curr_lone_row[4]], data[curr_lone_row[5]], auxiliary[0])
qc.ch(auxiliary[0],auxiliary[3])
qc.cz(auxiliary[2],auxiliary[3])
qc.ch(auxiliary[0],auxiliary[3])
#qc.ccx(auxiliary[0], auxiliary[2], auxiliary[3])
#------------------------------------------------------------------------------------------------------------------------
#qc.ch(data[curr_lone_row[6]], count_out[2])
#qc.cz(auxiliary[3],count_out[2])
#qc.ch(data[curr_lone_row[2]],count_out[2])
qc.ccx(data[curr_lone_row[6]], auxiliary[3], count_out[2]) #this CCX is important to avoid
#unnecessary addition of relative phase
#------------------------------------------------------------------------------------------------------------------------
qc.ch(auxiliary[0],auxiliary[3])
qc.cz(auxiliary[2],auxiliary[3])
qc.ch(auxiliary[0],auxiliary[3])
qc.ch(data[curr_lone_row[4]],auxiliary[0])
qc.cz(data[curr_lone_row[5]],auxiliary[0])
qc.ch(data[curr_lone_row[4]],auxiliary[0])
qc.ch(data[curr_lone_row[0]],auxiliary[0])
qc.cz(data[curr_lone_row[1]],auxiliary[0])
qc.ch(data[curr_lone_row[0]],auxiliary[0])
qc.ch(auxiliary[0],auxiliary[2])
qc.cz(auxiliary[1],auxiliary[2])
qc.ch(auxiliary[0],auxiliary[2])
qc.ch(data[curr_lone_row[2]],auxiliary[1])
qc.cz(data[curr_lone_row[3]],auxiliary[1])
qc.ch(data[curr_lone_row[2]],auxiliary[1])
qc.ch(data[curr_lone_row[0]], auxiliary[0])
qc.cz(data[curr_lone_row[1]], auxiliary[0])
qc.ch(data[curr_lone_row[0]],auxiliary[0])
for j in range(1,n):
qc.x(data[curr_lone_row[j]])
qc.barrier
def u3a(data, auxiliary,oracle, count_out):
qc_1 = QuantumCircuit(data, auxiliary,oracle, count_out)
#Oracle -----------------------------------------------
#Adding Row counters to check if each row has at least 1 asteroid and then flipping a count_out bit if all rows has at least one asteroid
add_row_counters(qc_1, data, auxiliary) #compute
qc_1.mct([auxiliary[0], auxiliary[1], auxiliary[2], auxiliary[3]], count_out[0], mode = 'noancilla')
add_row_counters(qc_1, data, auxiliary) #uncompute
#Adding column counters to check if each column has at least 1 asteroid and then flipping a count_out bit if all columns has at least one asteroid
add_column_counters(qc_1, data, auxiliary) #compute
qc_1.mct([auxiliary[0], auxiliary[1], auxiliary[2], auxiliary[3]], count_out[1], mode = 'noancilla')
add_column_counters(qc_1, data, auxiliary) #uncompute
#qc_1.barrier()
#lone asteroid counter circuit to add
add_lone_counters(qc_1, data, auxiliary, count_out)
return qc_1
def u3a_dagger(data, auxiliary, oracle, count_out):
qc_1 = QuantumCircuit(data, auxiliary,oracle, count_out)
#Oracle -----------------------------------------------
#Adding Row counters to check if each row has at least 1 asteroid and then flipping a count_out bit if all rows has at least one asteroid
add_row_counters(qc_1, data, auxiliary) #compute
qc_1.mct([auxiliary[0], auxiliary[1], auxiliary[2], auxiliary[3]], count_out[0], mode = 'noancilla')
add_row_counters(qc_1, data, auxiliary) #uncompute
#Adding column counters to check if each column has at least 1 asteroid and then flipping a count_out bit if all columns has at least one asteroid
add_column_counters(qc_1, data, auxiliary) #compute
qc_1.mct([auxiliary[0], auxiliary[1], auxiliary[2], auxiliary[3]], count_out[1], mode = 'noancilla')
add_column_counters(qc_1, data, auxiliary) #uncompute
#qc_1.barrier()
#lone asteroid counter circuit to add
add_lone_counters(qc_1, data, auxiliary, count_out)
qc_2 = qc_1.inverse()
return qc_2
add = QuantumRegister(4, name = 'address')
data = QuantumRegister(16, name = 'data')
auxiliary = QuantumRegister(4, name = 'auxiliary')
count_out = QuantumRegister(3, name = 'counter_outputs')
oracle = QuantumRegister(1, name = 'oracle')
cbits = ClassicalRegister(4, name = 'solution')
qc = QuantumCircuit(add, data, auxiliary,oracle, count_out, cbits)
qc.x(oracle)
qc.h(oracle)
qc.h(add)
qc.barrier()
#Add qRAM
qRAM(qc,add,data, auxiliary, problem_set) #compute
qc.barrier()
# counters
qc.extend(u3a(data, auxiliary,oracle, count_out))
qc.barrier()
# Phase flipping oracle
#qc.cx(auxiliary[6], oracle)
qc.mct([count_out[0], count_out[1], count_out[2]], oracle, mode = 'noancilla')
# -------------------------------------------------------
# counters - dagger
qc.extend(u3a_dagger(data, auxiliary,oracle, count_out))
qc.barrier()
#qRAM
qc.barrier()
qRAM(qc,add,data, auxiliary, problem_set) #uncompute
qc.barrier()
#diffuser
qc.append(diffuser(4), add)
qc.barrier()
#measure
qc.measure(add[0], cbits[0])
qc.measure(add[1], cbits[1])
qc.measure(add[2], cbits[2])
qc.measure(add[3], cbits[3])
return qc
# Submission code
from qc_grader import grade_ex3, prepare_ex3, submit_ex3
# Execute your circuit with following prepare_ex3() function.
# The prepare_ex3() function works like the execute() function with only QuantumCircuit as an argument.
job = prepare_ex3(week3_ans_func)
result = job.result()
counts = result.get_counts()
original_problem_set_counts = counts[0]
original_problem_set_counts
# The bit string with the highest number of observations is treated as the solution.
# Check your answer by executing following code.
# The quantum cost of the QuantumCircuit is obtained as the score. The lower the cost, the better.
grade_ex3(job)
# Submit your results by executing following code. You can submit as many times as you like during the period.
submit_ex3(job)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, execute
from qiskit.providers.fake_provider import FakeVigoV2
from qiskit.visualization import plot_gate_map
backend = FakeVigoV2()
plot_gate_map(backend)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
# useful additional packages
import matplotlib.pyplot as plt
import numpy as np
import networkx as nx
from qiskit_aer import Aer
from qiskit.tools.visualization import plot_histogram
from qiskit.circuit.library import TwoLocal
from qiskit_optimization.applications import Maxcut, Tsp
from qiskit.algorithms.minimum_eigensolvers import SamplingVQE, NumPyMinimumEigensolver
from qiskit.algorithms.optimizers import SPSA
from qiskit.utils import algorithm_globals
from qiskit.primitives import Sampler
from qiskit_optimization.algorithms import MinimumEigenOptimizer
# Generating a graph of 4 nodes
n = 4 # Number of nodes in graph
G = nx.Graph()
G.add_nodes_from(np.arange(0, n, 1))
elist = [(0, 1, 1.0), (0, 2, 1.0), (0, 3, 1.0), (1, 2, 1.0), (2, 3, 1.0)]
# tuple is (i,j,weight) where (i,j) is the edge
G.add_weighted_edges_from(elist)
colors = ["r" for node in G.nodes()]
pos = nx.spring_layout(G)
def draw_graph(G, colors, pos):
default_axes = plt.axes(frameon=True)
nx.draw_networkx(G, node_color=colors, node_size=600, alpha=0.8, ax=default_axes, pos=pos)
edge_labels = nx.get_edge_attributes(G, "weight")
nx.draw_networkx_edge_labels(G, pos=pos, edge_labels=edge_labels)
draw_graph(G, colors, pos)
# Computing the weight matrix from the random graph
w = np.zeros([n, n])
for i in range(n):
for j in range(n):
temp = G.get_edge_data(i, j, default=0)
if temp != 0:
w[i, j] = temp["weight"]
print(w)
best_cost_brute = 0
for b in range(2**n):
x = [int(t) for t in reversed(list(bin(b)[2:].zfill(n)))]
cost = 0
for i in range(n):
for j in range(n):
cost = cost + w[i, j] * x[i] * (1 - x[j])
if best_cost_brute < cost:
best_cost_brute = cost
xbest_brute = x
print("case = " + str(x) + " cost = " + str(cost))
colors = ["r" if xbest_brute[i] == 0 else "c" for i in range(n)]
draw_graph(G, colors, pos)
print("\nBest solution = " + str(xbest_brute) + " cost = " + str(best_cost_brute))
max_cut = Maxcut(w)
qp = max_cut.to_quadratic_program()
print(qp.prettyprint())
qubitOp, offset = qp.to_ising()
print("Offset:", offset)
print("Ising Hamiltonian:")
print(str(qubitOp))
# solving Quadratic Program using exact classical eigensolver
exact = MinimumEigenOptimizer(NumPyMinimumEigensolver())
result = exact.solve(qp)
print(result.prettyprint())
# Making the Hamiltonian in its full form and getting the lowest eigenvalue and eigenvector
ee = NumPyMinimumEigensolver()
result = ee.compute_minimum_eigenvalue(qubitOp)
x = max_cut.sample_most_likely(result.eigenstate)
print("energy:", result.eigenvalue.real)
print("max-cut objective:", result.eigenvalue.real + offset)
print("solution:", x)
print("solution objective:", qp.objective.evaluate(x))
colors = ["r" if x[i] == 0 else "c" for i in range(n)]
draw_graph(G, colors, pos)
algorithm_globals.random_seed = 123
seed = 10598
# construct SamplingVQE
optimizer = SPSA(maxiter=300)
ry = TwoLocal(qubitOp.num_qubits, "ry", "cz", reps=5, entanglement="linear")
vqe = SamplingVQE(sampler=Sampler(), ansatz=ry, optimizer=optimizer)
# run SamplingVQE
result = vqe.compute_minimum_eigenvalue(qubitOp)
# print results
x = max_cut.sample_most_likely(result.eigenstate)
print("energy:", result.eigenvalue.real)
print("time:", result.optimizer_time)
print("max-cut objective:", result.eigenvalue.real + offset)
print("solution:", x)
print("solution objective:", qp.objective.evaluate(x))
# plot results
colors = ["r" if x[i] == 0 else "c" for i in range(n)]
draw_graph(G, colors, pos)
# create minimum eigen optimizer based on SamplingVQE
vqe_optimizer = MinimumEigenOptimizer(vqe)
# solve quadratic program
result = vqe_optimizer.solve(qp)
print(result.prettyprint())
colors = ["r" if result.x[i] == 0 else "c" for i in range(n)]
draw_graph(G, colors, pos)
# Generating a graph of 3 nodes
n = 3
num_qubits = n**2
tsp = Tsp.create_random_instance(n, seed=123)
adj_matrix = nx.to_numpy_array(tsp.graph)
print("distance\n", adj_matrix)
colors = ["r" for node in tsp.graph.nodes]
pos = [tsp.graph.nodes[node]["pos"] for node in tsp.graph.nodes]
draw_graph(tsp.graph, colors, pos)
from itertools import permutations
def brute_force_tsp(w, N):
a = list(permutations(range(1, N)))
last_best_distance = 1e10
for i in a:
distance = 0
pre_j = 0
for j in i:
distance = distance + w[j, pre_j]
pre_j = j
distance = distance + w[pre_j, 0]
order = (0,) + i
if distance < last_best_distance:
best_order = order
last_best_distance = distance
print("order = " + str(order) + " Distance = " + str(distance))
return last_best_distance, best_order
best_distance, best_order = brute_force_tsp(adj_matrix, n)
print(
"Best order from brute force = "
+ str(best_order)
+ " with total distance = "
+ str(best_distance)
)
def draw_tsp_solution(G, order, colors, pos):
G2 = nx.DiGraph()
G2.add_nodes_from(G)
n = len(order)
for i in range(n):
j = (i + 1) % n
G2.add_edge(order[i], order[j], weight=G[order[i]][order[j]]["weight"])
default_axes = plt.axes(frameon=True)
nx.draw_networkx(
G2, node_color=colors, edge_color="b", node_size=600, alpha=0.8, ax=default_axes, pos=pos
)
edge_labels = nx.get_edge_attributes(G2, "weight")
nx.draw_networkx_edge_labels(G2, pos, font_color="b", edge_labels=edge_labels)
draw_tsp_solution(tsp.graph, best_order, colors, pos)
qp = tsp.to_quadratic_program()
print(qp.prettyprint())
from qiskit_optimization.converters import QuadraticProgramToQubo
qp2qubo = QuadraticProgramToQubo()
qubo = qp2qubo.convert(qp)
qubitOp, offset = qubo.to_ising()
print("Offset:", offset)
print("Ising Hamiltonian:")
print(str(qubitOp))
result = exact.solve(qubo)
print(result.prettyprint())
# Making the Hamiltonian in its full form and getting the lowest eigenvalue and eigenvector
ee = NumPyMinimumEigensolver()
result = ee.compute_minimum_eigenvalue(qubitOp)
print("energy:", result.eigenvalue.real)
print("tsp objective:", result.eigenvalue.real + offset)
x = tsp.sample_most_likely(result.eigenstate)
print("feasible:", qubo.is_feasible(x))
z = tsp.interpret(x)
print("solution:", z)
print("solution objective:", tsp.tsp_value(z, adj_matrix))
draw_tsp_solution(tsp.graph, z, colors, pos)
algorithm_globals.random_seed = 123
seed = 10598
optimizer = SPSA(maxiter=300)
ry = TwoLocal(qubitOp.num_qubits, "ry", "cz", reps=5, entanglement="linear")
vqe = SamplingVQE(sampler=Sampler(), ansatz=ry, optimizer=optimizer)
result = vqe.compute_minimum_eigenvalue(qubitOp)
print("energy:", result.eigenvalue.real)
print("time:", result.optimizer_time)
x = tsp.sample_most_likely(result.eigenstate)
print("feasible:", qubo.is_feasible(x))
z = tsp.interpret(x)
print("solution:", z)
print("solution objective:", tsp.tsp_value(z, adj_matrix))
draw_tsp_solution(tsp.graph, z, colors, pos)
algorithm_globals.random_seed = 123
seed = 10598
# create minimum eigen optimizer based on SamplingVQE
vqe_optimizer = MinimumEigenOptimizer(vqe)
# solve quadratic program
result = vqe_optimizer.solve(qp)
print(result.prettyprint())
z = tsp.interpret(x)
print("solution:", z)
print("solution objective:", tsp.tsp_value(z, adj_matrix))
draw_tsp_solution(tsp.graph, z, colors, pos)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/Qiskit/qiskit-transpiler-service
|
Qiskit
|
# -*- coding: utf-8 -*-
# (C) Copyright 2024 IBM. All Rights Reserved.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Unit-testing clifford_ai"""
from qiskit import QuantumCircuit
from qiskit.transpiler import PassManager
from qiskit_transpiler_service.ai.collection import CollectCliffords
from qiskit_transpiler_service.ai.synthesis import AICliffordSynthesis
def test_clifford_function(random_circuit_transpiled, backend):
ai_optimize_lf = PassManager(
[
CollectCliffords(),
AICliffordSynthesis(backend_name=backend),
]
)
ai_optimized_circuit = ai_optimize_lf.run(random_circuit_transpiled)
assert isinstance(ai_optimized_circuit, QuantumCircuit)
def test_clifford_wrong_backend(random_circuit_transpiled, caplog):
ai_optimize_lf = PassManager(
[
CollectCliffords(),
AICliffordSynthesis(backend_name="wrong_backend"),
]
)
ai_optimized_circuit = ai_optimize_lf.run(random_circuit_transpiled)
assert "couldn't synthesize the circuit" in caplog.text
assert "Keeping the original circuit" in caplog.text
assert isinstance(ai_optimized_circuit, QuantumCircuit)
|
https://github.com/swe-train/qiskit__qiskit
|
swe-train
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test the SabreLayout pass"""
import unittest
from qiskit import QuantumRegister, QuantumCircuit
from qiskit.transpiler import CouplingMap
from qiskit.transpiler.passes import SabreLayout
from qiskit.transpiler.exceptions import TranspilerError
from qiskit.converters import circuit_to_dag
from qiskit.test import QiskitTestCase
from qiskit.compiler.transpiler import transpile
from qiskit.providers.fake_provider import FakeAlmaden, FakeAlmadenV2
from qiskit.providers.fake_provider import FakeKolkata
from qiskit.providers.fake_provider import FakeMontreal
class TestSabreLayout(QiskitTestCase):
"""Tests the SabreLayout pass"""
def setUp(self):
super().setUp()
self.cmap20 = FakeAlmaden().configuration().coupling_map
def test_5q_circuit_20q_coupling(self):
"""Test finds layout for 5q circuit on 20q device."""
# ┌───┐
# q_0: ──■───────┤ X ├───────────────
# │ └─┬─┘┌───┐
# q_1: ──┼────■────┼──┤ X ├───────■──
# ┌─┴─┐ │ │ ├───┤┌───┐┌─┴─┐
# q_2: ┤ X ├──┼────┼──┤ X ├┤ X ├┤ X ├
# └───┘┌─┴─┐ │ └───┘└─┬─┘└───┘
# q_3: ─────┤ X ├──■─────────┼───────
# └───┘ │
# q_4: ──────────────────────■───────
qr = QuantumRegister(5, "q")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[2])
circuit.cx(qr[1], qr[3])
circuit.cx(qr[3], qr[0])
circuit.x(qr[2])
circuit.cx(qr[4], qr[2])
circuit.x(qr[1])
circuit.cx(qr[1], qr[2])
dag = circuit_to_dag(circuit)
pass_ = SabreLayout(CouplingMap(self.cmap20), seed=0, swap_trials=32, layout_trials=32)
pass_.run(dag)
layout = pass_.property_set["layout"]
self.assertEqual([layout[q] for q in circuit.qubits], [18, 11, 13, 12, 14])
def test_6q_circuit_20q_coupling(self):
"""Test finds layout for 6q circuit on 20q device."""
# ┌───┐┌───┐┌───┐┌───┐┌───┐
# q0_0: ┤ X ├┤ X ├┤ X ├┤ X ├┤ X ├
# └─┬─┘└─┬─┘└─┬─┘└─┬─┘└─┬─┘
# q0_1: ──┼────■────┼────┼────┼──
# │ ┌───┐ │ │ │
# q0_2: ──┼──┤ X ├──┼────■────┼──
# │ └───┘ │ │
# q1_0: ──■─────────┼─────────┼──
# ┌───┐ │ │
# q1_1: ─────┤ X ├──┼─────────■──
# └───┘ │
# q1_2: ────────────■────────────
qr0 = QuantumRegister(3, "q0")
qr1 = QuantumRegister(3, "q1")
circuit = QuantumCircuit(qr0, qr1)
circuit.cx(qr1[0], qr0[0])
circuit.cx(qr0[1], qr0[0])
circuit.cx(qr1[2], qr0[0])
circuit.x(qr0[2])
circuit.cx(qr0[2], qr0[0])
circuit.x(qr1[1])
circuit.cx(qr1[1], qr0[0])
dag = circuit_to_dag(circuit)
pass_ = SabreLayout(CouplingMap(self.cmap20), seed=0, swap_trials=32, layout_trials=32)
pass_.run(dag)
layout = pass_.property_set["layout"]
self.assertEqual([layout[q] for q in circuit.qubits], [7, 8, 12, 6, 11, 13])
def test_6q_circuit_20q_coupling_with_target(self):
"""Test finds layout for 6q circuit on 20q device."""
# ┌───┐┌───┐┌───┐┌───┐┌───┐
# q0_0: ┤ X ├┤ X ├┤ X ├┤ X ├┤ X ├
# └─┬─┘└─┬─┘└─┬─┘└─┬─┘└─┬─┘
# q0_1: ──┼────■────┼────┼────┼──
# │ ┌───┐ │ │ │
# q0_2: ──┼──┤ X ├──┼────■────┼──
# │ └───┘ │ │
# q1_0: ──■─────────┼─────────┼──
# ┌───┐ │ │
# q1_1: ─────┤ X ├──┼─────────■──
# └───┘ │
# q1_2: ────────────■────────────
qr0 = QuantumRegister(3, "q0")
qr1 = QuantumRegister(3, "q1")
circuit = QuantumCircuit(qr0, qr1)
circuit.cx(qr1[0], qr0[0])
circuit.cx(qr0[1], qr0[0])
circuit.cx(qr1[2], qr0[0])
circuit.x(qr0[2])
circuit.cx(qr0[2], qr0[0])
circuit.x(qr1[1])
circuit.cx(qr1[1], qr0[0])
dag = circuit_to_dag(circuit)
target = FakeAlmadenV2().target
pass_ = SabreLayout(target, seed=0, swap_trials=32, layout_trials=32)
pass_.run(dag)
layout = pass_.property_set["layout"]
self.assertEqual([layout[q] for q in circuit.qubits], [7, 8, 12, 6, 11, 13])
def test_layout_with_classical_bits(self):
"""Test sabre layout with classical bits recreate from issue #8635."""
qc = QuantumCircuit.from_qasm_str(
"""
OPENQASM 2.0;
include "qelib1.inc";
qreg q4833[1];
qreg q4834[6];
qreg q4835[7];
creg c982[2];
creg c983[2];
creg c984[2];
rzz(0) q4833[0],q4834[4];
cu(0,-6.1035156e-05,0,1e-05) q4834[1],q4835[2];
swap q4834[0],q4834[2];
cu(-1.1920929e-07,0,-0.33333333,0) q4833[0],q4834[2];
ccx q4835[2],q4834[5],q4835[4];
measure q4835[4] -> c984[0];
ccx q4835[2],q4835[5],q4833[0];
measure q4835[5] -> c984[1];
measure q4834[0] -> c982[1];
u(10*pi,0,1.9) q4834[5];
measure q4834[3] -> c984[1];
measure q4835[0] -> c982[0];
rz(0) q4835[1];
"""
)
res = transpile(qc, FakeKolkata(), layout_method="sabre", seed_transpiler=1234)
self.assertIsInstance(res, QuantumCircuit)
layout = res._layout.initial_layout
self.assertEqual(
[layout[q] for q in qc.qubits], [13, 10, 11, 12, 17, 14, 22, 26, 5, 16, 25, 19, 7, 8]
)
# pylint: disable=line-too-long
def test_layout_many_search_trials(self):
"""Test recreate failure from randomized testing that overflowed."""
qc = QuantumCircuit.from_qasm_str(
"""
OPENQASM 2.0;
include "qelib1.inc";
qreg q18585[14];
creg c1423[5];
creg c1424[4];
creg c1425[3];
barrier q18585[4],q18585[5],q18585[12],q18585[1];
cz q18585[11],q18585[3];
cswap q18585[8],q18585[10],q18585[6];
u(-2.00001,6.1035156e-05,-1.9) q18585[2];
barrier q18585[3],q18585[6],q18585[5],q18585[8],q18585[10],q18585[9],q18585[11],q18585[2],q18585[12],q18585[7],q18585[13],q18585[4],q18585[0],q18585[1];
cp(0) q18585[2],q18585[4];
cu(-0.99999,0,0,0) q18585[7],q18585[1];
cu(0,0,0,2.1507119) q18585[6],q18585[3];
barrier q18585[13],q18585[0],q18585[12],q18585[3],q18585[2],q18585[10];
ry(-1.1044662) q18585[13];
barrier q18585[13];
id q18585[12];
barrier q18585[12],q18585[6];
cu(-1.9,1.9,-1.5,0) q18585[10],q18585[0];
barrier q18585[13];
id q18585[8];
barrier q18585[12];
barrier q18585[12],q18585[1],q18585[9];
sdg q18585[2];
rz(-10*pi) q18585[6];
u(0,27.566433,1.9) q18585[1];
barrier q18585[12],q18585[11],q18585[9],q18585[4],q18585[7],q18585[0],q18585[13],q18585[3];
cu(-0.99999,-5.9604645e-08,-0.5,2.00001) q18585[3],q18585[13];
rx(-5.9604645e-08) q18585[7];
p(1.1) q18585[13];
barrier q18585[12],q18585[13],q18585[10],q18585[9],q18585[7],q18585[4];
z q18585[10];
measure q18585[7] -> c1423[2];
barrier q18585[0],q18585[3],q18585[7],q18585[4],q18585[1],q18585[8],q18585[6],q18585[11],q18585[5];
barrier q18585[5],q18585[2],q18585[8],q18585[3],q18585[6];
"""
)
res = transpile(
qc,
FakeMontreal(),
layout_method="sabre",
routing_method="stochastic",
seed_transpiler=12345,
)
self.assertIsInstance(res, QuantumCircuit)
layout = res._layout.initial_layout
self.assertEqual(
[layout[q] for q in qc.qubits], [7, 19, 14, 18, 10, 6, 12, 16, 13, 20, 15, 21, 1, 17]
)
class TestDisjointDeviceSabreLayout(QiskitTestCase):
"""Test SabreLayout with a disjoint coupling map."""
def setUp(self):
super().setUp()
self.dual_grid_cmap = CouplingMap(
[[0, 1], [0, 2], [1, 3], [2, 3], [4, 5], [4, 6], [5, 7], [5, 8]]
)
def test_dual_ghz(self):
"""Test a basic example with 2 circuit components and 2 cmap components."""
qc = QuantumCircuit(8, name="double dhz")
qc.h(0)
qc.cz(0, 1)
qc.cz(0, 2)
qc.h(3)
qc.cx(3, 4)
qc.cx(3, 5)
qc.cx(3, 6)
qc.cx(3, 7)
layout_routing_pass = SabreLayout(
self.dual_grid_cmap, seed=123456, swap_trials=1, layout_trials=1
)
layout_routing_pass(qc)
layout = layout_routing_pass.property_set["layout"]
self.assertEqual([layout[q] for q in qc.qubits], [3, 1, 2, 5, 4, 6, 7, 8])
def test_dual_ghz_with_wide_barrier(self):
"""Test a basic example with 2 circuit components and 2 cmap components."""
qc = QuantumCircuit(8, name="double dhz")
qc.h(0)
qc.cz(0, 1)
qc.cz(0, 2)
qc.h(3)
qc.cx(3, 4)
qc.cx(3, 5)
qc.cx(3, 6)
qc.cx(3, 7)
qc.measure_all()
layout_routing_pass = SabreLayout(
self.dual_grid_cmap, seed=123456, swap_trials=1, layout_trials=1
)
layout_routing_pass(qc)
layout = layout_routing_pass.property_set["layout"]
self.assertEqual([layout[q] for q in qc.qubits], [3, 1, 2, 5, 4, 6, 7, 8])
def test_dual_ghz_with_intermediate_barriers(self):
"""Test dual ghz circuit with intermediate barriers local to each componennt."""
qc = QuantumCircuit(8, name="double dhz")
qc.h(0)
qc.cz(0, 1)
qc.cz(0, 2)
qc.barrier(0, 1, 2)
qc.h(3)
qc.cx(3, 4)
qc.cx(3, 5)
qc.barrier(4, 5, 6)
qc.cx(3, 6)
qc.cx(3, 7)
qc.measure_all()
layout_routing_pass = SabreLayout(
self.dual_grid_cmap, seed=123456, swap_trials=1, layout_trials=1
)
layout_routing_pass(qc)
layout = layout_routing_pass.property_set["layout"]
self.assertEqual([layout[q] for q in qc.qubits], [3, 1, 2, 5, 4, 6, 7, 8])
def test_dual_ghz_with_intermediate_spanning_barriers(self):
"""Test dual ghz circuit with barrier in the middle across components."""
qc = QuantumCircuit(8, name="double dhz")
qc.h(0)
qc.cz(0, 1)
qc.cz(0, 2)
qc.barrier(0, 1, 2, 4, 5)
qc.h(3)
qc.cx(3, 4)
qc.cx(3, 5)
qc.cx(3, 6)
qc.cx(3, 7)
qc.measure_all()
layout_routing_pass = SabreLayout(
self.dual_grid_cmap, seed=123456, swap_trials=1, layout_trials=1
)
layout_routing_pass(qc)
layout = layout_routing_pass.property_set["layout"]
self.assertEqual([layout[q] for q in qc.qubits], [3, 1, 2, 5, 4, 6, 7, 8])
def test_too_large_components(self):
"""Assert trying to run a circuit with too large a connected component raises."""
qc = QuantumCircuit(8)
qc.h(0)
for i in range(1, 6):
qc.cx(0, i)
qc.h(7)
qc.cx(7, 6)
layout_routing_pass = SabreLayout(
self.dual_grid_cmap, seed=123456, swap_trials=1, layout_trials=1
)
with self.assertRaises(TranspilerError):
layout_routing_pass(qc)
if __name__ == "__main__":
unittest.main()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
from qiskit.quantum_info import Statevector
from qiskit.visualization import plot_state_qsphere
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
state = Statevector(qc)
plot_state_qsphere(state)
|
https://github.com/YPadawan/qiskit-hackathon
|
YPadawan
|
import numpy as np
# Importing necessary quantum computing library (QISKIT)
import qiskit
from qiskit import QuantumCircuit, QuantumRegister
from qiskit.visualization import *
# Source:https://www.tensorflow.org/quantum/tutorials/qcnn
def cluster_state(qr):
"""Returns a cluster state of the qubits in the quantum register `qr`
Parameters
----------
qr: (QuantumRegister)
Qiskit quantum register
Returns
-------
qc: (QuantumCircuit)
Qiskit quantum circuit with the cluster state
"""
qc = QuantumCircuit(qr) # Creating a QuantumRegister
# Applying a Hadamard gate to qubits
for i, _ in enumerate(qr):
qc.h(i)
for this_bit, next_bit in zip(qr, qr[1:] + [qr[0]]):
c = this_bit.index
t = next_bit.index
qc.cz(c, t)
return qc
qc_cs = cluster_state(QuantumRegister(4))
qc_cs.draw('mpl')
# https://www.tensorflow.org/quantum/tutorials/qcnn
# This function is a readaptation of the tensorflow tutorial using qiskit and pytorch instead
# WARNING: I believe the function is working, but it looks like it is not possible to convert quantum gates
# and quantum circuits to pytorch tensors.
# I don't think there is an equivalent of tfq.convert_to_tensor yet.
# For the moment the function only returns a tuple of lists for train and test excitations.
def generate_data(qubits):
"""Generate training and testing data.
Parameters
----------
qubits: (Qiskit QuantumRegister)
Quantum register containing qubits to pass to the Quantum circuit
Returns
--------
train_excitations: (list)
list of excited qubits for training
train_labels: (array)
numpy array containing the labels corresponding to the train set
test_excitations: (list)
list of excited qubits to use as a testing set
test_labels: (array)
numpy array containing the labels of the test set
N.B. train_excitations and test_excitations should be a PyTorch tensor
"""
n_rounds = 20 # Produces n_rounds * n_qubits datapoints.
excitations = []
labels = []
for n in range(n_rounds):
for bit in qubits:
rng = np.random.uniform(-np.pi, np.pi)
# Creating a quantum circuit with qiskit
excitations.append(QuantumCircuit(bit.register).rx(rng, bit.register))
#excitations.append(cirq.Circuit(cirq.rx(rng)(bit))) / cirq to check if it's correct
labels.append(1 if (-np.pi / 2) <= rng <= (np.pi / 2) else -1)
split_ind = int(len(excitations) * 0.7)
train_excitations = excitations[:split_ind]
test_excitations = excitations[split_ind:]
train_labels = labels[:split_ind]
test_labels = labels[split_ind:]
return train_excitations, np.array(train_labels), \
test_excitations, np.array(test_labels)
qr = QuantumRegister(2)
train_excitations, train_labels, test_excitations, test_labels = generate_data(qr)
# Source of the function: https://www.tensorflow.org/quantum/tutorials/qcnn
# The function has been re-adapted for qiskit use
from qiskit.circuit import Parameter
def one_qubit_unitary(bit, rotation=('1', '2', '3')):
"""Make a circuit enacting a rotation of the bloch sphere about the X,
Y and Z axis, that depends on the values in `symbols`.
Parameters
-----------
bit: (QuantumRegister (qubit))
qubit to rotate
rotation: (tuple)
tuple containing the three rotation values of rotation operators for respectively, x, y and z
Returns
-------
Rotated qubit, one qubit unitary matrix
"""
x, y, z = rotation
qc = QuantumCircuit(bit)
qc.rx(Parameter(x), 0)
qc.ry(Parameter(y), 0)
qc.rz(Parameter(z), 0)
return qc
one_qubit_unitary(1, ("e1", "e2", "e3")).draw()
# Function still needs some rechecking but it might be correct.
# replace symbols later, still having an issue with symbols
def two_qubit_unitary(bits,
rotations={"q1": ("x1", "y1", "z1"),
"q2": ('x2', 'y2', 'z2'),
"rzyx":("t1", "t2", "t3")}):
"""Make a qiskit circuit that creates an arbitrary two qubit unitary.
Parameters
----------
bits: (QuantumRegister)
Qiskit quantum register which we want to pass to the circuit
rotations: (dictionary)
dictionary containing the rotation parameters for both qubits and x, y, z axis
Returns
-------
big_qc: (QuantumCircuit)
Qiskit quantum circuit representing two-qubit unitary matrix (to be confirmed)
"""
rot1 = rotations["q1"]
rot2 = rotations["q2"]
sub_circ1 = one_qubit_unitary(1, rot1)
sub_circ2 = one_qubit_unitary(1, rot2)
qr = bits
big_qc = QuantumCircuit(qr)
big_qc.append(sub_circ1.to_instruction(), [qr[0]])
big_qc.append(sub_circ2.to_instruction(), [qr[1]])
zz, yy, xx = rotations["rzyx"]
big_qc.rzz(Parameter(zz), 0, 1)
big_qc.ryy(Parameter(yy), 0, 1)
big_qc.rxx(Parameter(xx), 0, 1)
big_qc.append(sub_circ1.to_instruction(), [qr[0]])
big_qc.append(sub_circ2.to_instruction(), [qr[1]])
return big_qc
two_qubit_unitary(QuantumRegister(2)).decompose().draw('mpl')
# source: https://www.tensorflow.org/quantum/tutorials/qcnn
def two_qubit_pool(source_qubit, sink_qubit,
rotations={"q1":("x1", "y1", "z1"),
"q2": ("x2", "y2", "z2"),
"invq":("-x2", "-y2", "-z2")}): # add symbols later
"""Make a Qiskit circuit to do a parameterized 'pooling' operation, which
attempts to reduce entanglement down from two qubits to just one.
Parameters
---------
source_qubit: (QuantumRegister)
source qubit that will be the control qubit before sinking
sink_qubit: (QuantumRegister)
sink_qubit that will be the target qubit of the CNOT gate and that is supposed to be inversed
Returns
------
pool_circuit: (QuantumCircuit)
Qiskit quantum circuit making the pooling operation
"""
rot1 = rotations["q1"]
rot2 = rotations["q2"]
sink_basis_selector = one_qubit_unitary(sink_qubit, rot1)
source_basis_selector = one_qubit_unitary(source_qubit, rot2)
qr = QuantumRegister(2)
pool_circuit = QuantumCircuit(qr)
pool_circuit.append(sink_basis_selector.to_instruction(), [qr[0]])
pool_circuit.append(source_basis_selector.to_instruction(), [qr[1]])
pool_circuit.cnot(control_qubit=0, target_qubit=1)
# add sink_basis selector I don't know what is being done
inv_rot = rotations["invq"]
inv_sink_basis_selector = one_qubit_unitary(source_qubit, inv_rot)
pool_circuit.append(inv_sink_basis_selector.to_instruction(), [qr[1]])
return pool_circuit
two_qubit_pool(QuantumRegister(1), QuantumRegister(1)).decompose().draw('mpl')
def quantum_conv_circuit(bits): # Take care of rotations later
"""Quantum Convolution Layer
Parameters
----------
bits: (QuantumRegister)
Qiskit quantum register that will be used in the quantum circuit
Returns
-------
qc: (QuantumCircuit)
Qiskit circuit with the cascade of `two_qubit_unitary` applied
to all pairs of qubits in `bits`
"""
qc = QuantumCircuit(bits)
# The xyz variable below is meant as a workaround to parameter implementation and replacement
xyz = ("x", "y", "z")
k = 0 # variable to increment in order
for first, second in zip(bits[0::2], bits[1::2]):
i = first.index
j = second.index
### Creating parameters to avoid duplicate names because they raises a Circuit Error ###
k+=1
q1_val = tuple([r + str(k) for r in xyz])
q2_val = tuple([r + str(k + 1) for r in xyz])
rzyx = tuple([t + str(k) for t in ("theta", "beta", "gamma")])
k+=1
rotations = {"q1": q1_val, "q2":q2_val, "rzyx":rzyx}
qc.append(two_qubit_unitary(QuantumRegister(2), rotations).to_instruction(), [bits[i], bits[j]])
### Second loop for the second two_qubit unitary
abc = ("a", "b", "c")
p = 0
for first, second in zip(bits[1::2], bits[2::2] + [bits[0]]):
i = first.index
j = second.index
### Creating parameters to avoid duplicate names because they raises a Circuit Error ###
p+=1
q1_val = tuple([r + str(p) for r in abc])
q2_val = tuple([r + str(p + 1) for r in abc])
rzyx = tuple([t + str(p) for t in ("mu", "nu", "eps")])
p+=1
rotations = {"q1": q1_val, "q2":q2_val, "rzyx":rzyx}
qc.append(two_qubit_unitary(QuantumRegister(2), rotations).to_instruction(), [bits[i], bits[j]])
return qc
quantum_conv_circuit(QuantumRegister(8)).decompose().draw('mpl')
def quantum_pool_circuit(bits):
"""A layer that specifies a quantum pooling operation.
A Quantum pool tries to learn to pool the relevant information from two
qubits onto 1.
Parameters
----------
bits: (QuantumRegister)
Qiskit quantum register
Returns
-------
circuit: (QuantumCircuit)
Qiskit quantum circuit with the pooled qubits
"""
circuit = QuantumCircuit(bits) # instantiating of the quantum circuit
# The xyz variable below is mean't as a workaround to parameter implementation and replacement
xyz = ("x", "y", "z")
k = 0 # variable to increment in order
assert len(bits) % 2==0, "The number of qubits in the register should be even"
split = len(bits) // 2 # taking half of the quantum register's length
for source, sink in zip(bits[:split], bits[split:]):
i = source.index # getting source qubit index
j = sink.index # sink qubit index
### Creating parameters to avoid duplicate names because they raises a Circuit Error ###
k+=1
q1_val = tuple([r + str(k) for r in xyz])
invq_val = tuple(["-" + r + str(k) for r in xyz])
q2_val = tuple([r + str(k + 1) for r in xyz])
k+=1 # k is incremented twice because q2_val takes the value (k + 1) at k round
tqb = two_qubit_pool(QuantumRegister(1), QuantumRegister(1),
{"q1": q1_val, "q2":q2_val, "invq":invq_val})
circuit.append(tqb.to_instruction(),
[bits[i], bits[j]])
return circuit
test_bits = QuantumRegister(8)
quantum_pool_circuit(test_bits).decompose().draw('mpl')
|
https://github.com/madmen2/QASM
|
madmen2
|
# Do the necessary imports
import numpy as np
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, BasicAer, IBMQ
from qiskit.visualization import plot_histogram, plot_bloch_multivector
### Creating 3 qubit and 2 classical bits in each separate register
qr = QuantumRegister(3)
crz = ClassicalRegister(1)
crx = ClassicalRegister(1)
teleportation_circuit = QuantumCircuit(qr, crz, crx)
### A third party eve helps to create an entangled state
def create_bell_pair(qc, a, b):
qc.h(a)
qc.cx(a, b)
create_bell_pair(teleportation_circuit, 1, 2)
teleportation_circuit.draw()
def alice_gates(qc, a, b):
qc.cx(a, b)
qc.h(a)
teleportation_circuit.barrier()
alice_gates(teleportation_circuit, 0, 1)
teleportation_circuit.draw()
def measure_and_send(qc, a, b):
qc.barrier()
qc.measure(a,0)
qc.measure(b,1)
teleportation_circuit.barrier()
measure_and_send(teleportation_circuit, 0, 1)
teleportation_circuit.draw()
def bob_gates(qc, qubit, crz, crx):
qc.x(qubit).c_if(crx, 1)
qc.z(qubit).c_if(crz, 1)
teleportation_circuit.barrier()
bob_gates(teleportation_circuit, 2, crz, crx)
teleportation_circuit.draw()
from qiskit.extensions import Initialize
import math
qc = QuantumCircuit(1)
initial_state = [0,1]
init_gate = Initialize(initial_state)
# qc.append(initialize_qubit, [0])
qr = QuantumRegister(3) # Protocol uses 3 qubits
crz = ClassicalRegister(1) # and 2 classical registers
crx = ClassicalRegister(1)
qc = QuantumCircuit(qr, crz, crx)
# First, let's initialise Alice's q0
qc.append(init_gate, [0])
qc.barrier()
# Now begins the teleportation protocol
create_bell_pair(qc, 1, 2)
qc.barrier()
# Send q1 to Alice and q2 to Bob
alice_gates(qc, 0, 1)
# Alice then sends her classical bits to Bob
measure_and_send(qc, 0, 1)
# Bob decodes qubits
bob_gates(qc, 2, crz, crx)
qc.draw()
backend = BasicAer.get_backend('statevector_simulator')
out_vector = execute(qc, backend).result().get_statevector()
plot_bloch_multivector(out_vector)
inverse_init_gate = init_gate.gates_to_uncompute()
qc.append(inverse_init_gate, [2])
qc.draw()
cr_result = ClassicalRegister(1)
qc.add_register(cr_result)
qc.measure(2,2)
qc.draw()
backend = BasicAer.get_backend('qasm_simulator')
counts = execute(qc, backend, shots=1024).result().get_counts()
plot_histogram(counts)
def bob_gates(qc, a, b, c):
qc.cz(a, c)
qc.cx(b, c)
qc = QuantumCircuit(3,1)
# First, let's initialise Alice's q0
qc.append(init_gate, [0])
qc.barrier()
# Now begins the teleportation protocol
create_bell_pair(qc, 1, 2)
qc.barrier()
# Send q1 to Alice and q2 to Bob
alice_gates(qc, 0, 1)
qc.barrier()
# Alice sends classical bits to Bob
bob_gates(qc, 0, 1, 2)
# We undo the initialisation process
qc.append(inverse_init_gate, [2])
# See the results, we only care about the state of qubit 2
qc.measure(2,0)
# View the results:
qc.draw()
from qiskit import IBMQ
IBMQ.save_account('### IMB TOKEN ')
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q')
provider.backends()
from qiskit.providers.ibmq import least_busy
backend = least_busy(provider.backends(filters=lambda b: b.configuration().n_qubits >= 3 and
not b.configuration().simulator and b.status().operational==True))
job_exp = execute(qc, backend=backend, shots=8192)
exp_result = job_exp.result()
exp_measurement_result = exp_result.get_counts(qc)
print(exp_measurement_result)
plot_histogram(exp_measurement_result)
error_rate_percent = sum([exp_measurement_result[result] for result in exp_measurement_result.keys() if result[0]=='1']) \
* 100./ sum(list(exp_measurement_result.values()))
print("The experimental error rate : ", error_rate_percent, "%")
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import numpy as np
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.circuit.library import QFT
def create_qpe_circuit(theta, num_qubits):
'''Creates a QPE circuit given theta and num_qubits.'''
# Step 1: Create a circuit with two quantum registers and one classical register.
first = QuantumRegister(size=num_qubits, name='first') # the first register for phase estimation
second = QuantumRegister(size=1, name='second') # the second register for storing eigenvector |psi>
classical = ClassicalRegister(size=num_qubits, name='readout') # classical register for readout
qpe_circuit = QuantumCircuit(first, second, classical)
# Step 2: Initialize the qubits.
# All qubits are initialized in |0> by default, no extra code is needed to initialize the first register.
qpe_circuit.x(second) # Initialize the second register with state |psi>, which is |1> in this example.
# Step 3: Create superposition in the first register.
qpe_circuit.barrier() # Add barriers to separate each step of the algorithm for better visualization.
qpe_circuit.h(first)
# Step 4: Apply a controlled-U^(2^j) black box.
qpe_circuit.barrier()
for j in range(num_qubits):
qpe_circuit.cp(theta*2*np.pi*(2**j), j, num_qubits) # Theta doesn't contain the 2 pi factor.
# Step 5: Apply an inverse QFT to the first register.
qpe_circuit.barrier()
qpe_circuit.compose(QFT(num_qubits, inverse=True), inplace=True)
# Step 6: Measure the first register.
qpe_circuit.barrier()
qpe_circuit.measure(first, classical)
return qpe_circuit
num_qubits = 4
qpe_circuit_fixed_phase = create_qpe_circuit(1/2, num_qubits) # Create a QPE circuit with fixed theta=1/2.
qpe_circuit_fixed_phase.draw('mpl')
from qiskit.circuit import Parameter
theta = Parameter('theta') # Create a parameter `theta` whose values can be assigned later.
qpe_circuit_parameterized = create_qpe_circuit(theta, num_qubits)
qpe_circuit_parameterized.draw('mpl')
number_of_phases = 21
phases = np.linspace(0, 2, number_of_phases)
individual_phases = [[ph] for ph in phases] # Phases need to be expressed as a list of lists.
from qiskit_ibm_runtime import QiskitRuntimeService
service = QiskitRuntimeService()
backend = "ibmq_qasm_simulator" # use the simulator
from qiskit_ibm_runtime import Sampler, Session
with Session(service=service, backend=backend):
results = Sampler().run(
[qpe_circuit_parameterized]*len(individual_phases),
parameter_values=individual_phases
).result()
from qiskit.tools.visualization import plot_histogram
idx = 6
plot_histogram(results.quasi_dists[idx].binary_probabilities(), legend=[f'$\\theta$={phases[idx]:.3f}'])
def most_likely_bitstring(results_dict):
'''Finds the most likely outcome bit string from a result dictionary.'''
return max(results_dict, key=results_dict.get)
def find_neighbors(bitstring):
'''Finds the neighbors of a bit string.
Example:
For bit string '1010', this function returns ('1001', '1011')
'''
if bitstring == len(bitstring)*'0':
neighbor_left = len(bitstring)*'1'
else:
neighbor_left = format((int(bitstring,2)-1), '0%sb'%len(bitstring))
if bitstring == len(bitstring)*'1':
neighbor_right = len(bitstring)*'0'
else:
neighbor_right = format((int(bitstring,2)+1), '0%sb'%len(bitstring))
return (neighbor_left, neighbor_right)
def estimate_phase(results_dict):
'''Estimates the phase from a result dictionary of a QPE circuit.'''
# Find the most likely outcome bit string N1 and its neighbors.
num_1_key = most_likely_bitstring(results_dict)
neighbor_left, neighbor_right = find_neighbors(num_1_key)
# Get probabilities of N1 and its neighbors.
num_1_prob = results_dict.get(num_1_key)
neighbor_left_prob = results_dict.get(neighbor_left)
neighbor_right_prob = results_dict.get(neighbor_right)
# Find the second most likely outcome N2 and its probability P2 among the neighbors.
if neighbor_left_prob is None:
# neighbor_left doesn't exist
if neighbor_right_prob is None:
# both neighbors don't exist, N2 is N1
num_2_key = num_1_key
num_2_prob = num_1_prob
else:
# If only neighbor_left doesn't exist, N2 is neighbor_right.
num_2_key = neighbor_right
num_2_prob = neighbor_right_prob
elif neighbor_right_prob is None:
# If only neighbor_right doesn't exist, N2 is neighbor_left.
num_2_key = neighbor_left
num_2_prob = neighbor_left_prob
elif neighbor_left_prob > neighbor_right_prob:
# Both neighbors exist and neighbor_left has higher probability, so N2 is neighbor_left.
num_2_key = neighbor_left
num_2_prob = neighbor_left_prob
else:
# Both neighbors exist and neighbor_right has higher probability, so N2 is neighor_right.
num_2_key = neighbor_right
num_2_prob = neighbor_right_prob
# Calculate the estimated phases for N1 and N2.
num_qubits = len(num_1_key)
num_1_phase = (int(num_1_key, 2) / 2**num_qubits)
num_2_phase = (int(num_2_key, 2) / 2**num_qubits)
# Calculate the weighted average phase from N1 and N2.
phase_estimated = (num_1_phase * num_1_prob + num_2_phase * num_2_prob) / (num_1_prob + num_2_prob)
return phase_estimated
qpe_solutions = []
for idx, result_dict in enumerate(results.quasi_dists):
qpe_solutions.append(estimate_phase(result_dict.binary_probabilities()))
ideal_solutions = np.append(
phases[:(number_of_phases-1)//2], # first period
np.subtract(phases[(number_of_phases-1)//2:-1], 1) # second period
)
ideal_solutions = np.append(ideal_solutions, np.subtract(phases[-1], 2)) # starting point of the third period
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(10, 6))
plt.plot(phases, ideal_solutions, '--', label='Ideal solutions')
plt.plot(phases, qpe_solutions, 'o', label='QPE solutions')
plt.title('Quantum Phase Estimation Algorithm')
plt.xlabel('Input Phase')
plt.ylabel('Output Phase')
plt.legend()
import qiskit_ibm_runtime
qiskit_ibm_runtime.version.get_version_info()
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
# If you introduce a list with less colors than bars, the color of the bars will
# alternate following the sequence from the list.
import numpy as np
from qiskit.quantum_info import DensityMatrix
from qiskit import QuantumCircuit
from qiskit.visualization import plot_state_paulivec
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
qc = QuantumCircuit(2)
qc.h([0, 1])
qc.cz(0, 1)
qc.ry(np.pi/3, 0)
qc.rx(np.pi/5, 1)
matrix = DensityMatrix(qc)
plot_state_paulivec(matrix, color=['crimson', 'midnightblue', 'seagreen'])
|
https://github.com/ryanlevy/shadow-tutorial
|
ryanlevy
|
import numpy as np
import matplotlib.pyplot as plt
import qiskit
pauli_list = [
np.eye(2),
np.array([[0.0, 1.0], [1.0, 0.0]]),
np.array([[0, -1.0j], [1.0j, 0.0]]),
np.array([[1.0, 0.0], [0.0, -1.0]]),
]
s_to_pauli = {
"I": pauli_list[0],
"X": pauli_list[1],
"Y": pauli_list[2],
"Z": pauli_list[3],
}
def channel(N,qc):
'''create an N qubit GHZ state '''
qc.h(0)
if N>=2: qc.cx(0,1)
if N>=3: qc.cx(0,2)
if N>=4: qc.cx(1,3)
if N>4: raise NotImplementedError(f"{N} not implemented!")
def bitGateMap(qc,g,qi):
'''Map X/Y/Z string to qiskit ops'''
if g=="X":
qc.h(qi)
elif g=="Y":
qc.sdg(qi)
qc.h(qi)
elif g=="Z":
pass
else:
raise NotImplementedError(f"Unknown gate {g}")
def Minv(N,X):
'''inverse shadow channel'''
return ((2**N+1.))*X - np.eye(2**N)
qc = qiskit.QuantumCircuit(4)
qc.h(0)
qc.cx(0,1)
qc.barrier()
qc.cx(0,2)
qc.barrier()
qc.cx(1,3)
qc.draw(output='mpl')
qc = qiskit.QuantumCircuit(3)
channel(3,qc)
qc.draw(output='mpl')
nShadows = 100
reps = 1
N = 2
rng = np.random.default_rng(1717)
cliffords = [qiskit.quantum_info.random_clifford(N, seed=rng) for _ in range(nShadows)]
qc = qiskit.QuantumCircuit(N)
channel(N,qc)
results = []
for cliff in cliffords:
qc_c = qc.compose(cliff.to_circuit())
counts = qiskit.quantum_info.Statevector(qc_c).sample_counts(reps)
results.append(counts)
qc.draw()
qc_c.draw()
shadows = []
for cliff, res in zip(cliffords, results):
mat = cliff.adjoint().to_matrix()
for bit,count in res.items():
Ub = mat[:,int(bit,2)] # this is Udag|b>
shadows.append(Minv(N,np.outer(Ub,Ub.conj()))*count)
rho_shadow = np.sum(shadows,axis=0)/(nShadows*reps)
rho_actual = qiskit.quantum_info.DensityMatrix(qc).data
plt.subplot(121)
plt.suptitle("Correct")
plt.imshow(rho_actual.real,vmax=0.7,vmin=-0.7)
plt.subplot(122)
plt.imshow(rho_actual.imag,vmax=0.7,vmin=-0.7)
plt.show()
print("---")
plt.subplot(121)
plt.suptitle("Shadow(Full Clifford)")
plt.imshow(rho_shadow.real,vmax=0.7,vmin=-0.7)
plt.subplot(122)
plt.imshow(rho_shadow.imag,vmax=0.7,vmin=-0.7)
plt.show()
qiskit.visualization.state_visualization.plot_state_city(rho_actual,title="Correct")
qiskit.visualization.state_visualization.plot_state_city(rho_shadow,title="Shadow (clifford)")
nShadows = 10_000
N = 2
rng = np.random.default_rng(1717)
scheme = [rng.choice(['X','Y','Z'],size=N) for _ in range(nShadows)]
labels, counts = np.unique(scheme,axis=0,return_counts=True)
qc = qiskit.QuantumCircuit(N)
channel(N,qc)
results = []
for bit_string,count in zip(labels,counts):
qc_m = qc.copy()
# rotate the basis for each qubit
for i,bit in enumerate(bit_string): bitGateMap(qc_m,bit,i)
counts = qiskit.quantum_info.Statevector(qc_m).sample_counts(count)
results.append(counts)
def rotGate(g):
'''produces gate U such that U|psi> is in Pauli basis g'''
if g=="X":
return 1/np.sqrt(2)*np.array([[1.,1.],[1.,-1.]])
elif g=="Y":
return 1/np.sqrt(2)*np.array([[1.,-1.0j],[1.,1.j]])
elif g=="Z":
return np.eye(2)
else:
raise NotImplementedError(f"Unknown gate {g}")
shadows = []
shots = 0
for pauli_string,counts in zip(labels,results):
# iterate over measurements
for bit,count in counts.items():
mat = 1.
for i,bi in enumerate(bit[::-1]):
b = rotGate(pauli_string[i])[int(bi),:]
mat = np.kron(Minv(1,np.outer(b.conj(),b)),mat)
shadows.append(mat*count)
shots+=count
rho_shadow = np.sum(shadows,axis=0)/(shots)
rho_actual = qiskit.quantum_info.DensityMatrix(qc).data
plt.subplot(121)
plt.suptitle("Correct")
plt.imshow(rho_actual.real,vmax=0.7,vmin=-0.7)
plt.subplot(122)
plt.imshow(rho_actual.imag,vmax=0.7,vmin=-0.7)
plt.show()
print("---")
plt.subplot(121)
plt.suptitle("Shadow(Pauli)")
plt.imshow(rho_shadow.real,vmax=0.7,vmin=-0.7)
plt.subplot(122)
plt.imshow(rho_shadow.imag,vmax=0.7,vmin=-0.7)
plt.show()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import pulse
d0 = pulse.DriveChannel(0)
x90 = pulse.Gaussian(10, 0.1, 3)
x180 = pulse.Gaussian(10, 0.2, 3)
with pulse.build() as hahn_echo:
with pulse.align_equispaced(duration=100):
pulse.play(x90, d0)
pulse.play(x180, d0)
pulse.play(x90, d0)
hahn_echo.draw()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit_nature.second_q.drivers import PySCFDriver
from qiskit_nature.second_q.problems import ElectronicBasis
driver = PySCFDriver()
driver.run_pyscf()
ao_problem = driver.to_problem(basis=ElectronicBasis.AO)
print(ao_problem.basis)
ao_hamil = ao_problem.hamiltonian
print(ao_hamil.electronic_integrals.alpha)
from qiskit_nature.second_q.formats.qcschema_translator import get_ao_to_mo_from_qcschema
qcschema = driver.to_qcschema()
basis_transformer = get_ao_to_mo_from_qcschema(qcschema)
print(basis_transformer.initial_basis)
print(basis_transformer.final_basis)
mo_problem = basis_transformer.transform(ao_problem)
print(mo_problem.basis)
mo_hamil = mo_problem.hamiltonian
print(mo_hamil.electronic_integrals.alpha)
import numpy as np
from qiskit_nature.second_q.operators import ElectronicIntegrals
from qiskit_nature.second_q.problems import ElectronicBasis
from qiskit_nature.second_q.transformers import BasisTransformer
ao2mo_alpha = np.random.random((2, 2))
ao2mo_beta = np.random.random((2, 2))
basis_transformer = BasisTransformer(
ElectronicBasis.AO,
ElectronicBasis.MO,
ElectronicIntegrals.from_raw_integrals(ao2mo_alpha, h1_b=ao2mo_beta),
)
from qiskit_nature.second_q.drivers import PySCFDriver
driver = PySCFDriver(atom="Li 0 0 0; H 0 0 1.5")
full_problem = driver.run()
print(full_problem.molecule)
print(full_problem.num_particles)
print(full_problem.num_spatial_orbitals)
from qiskit_nature.second_q.transformers import FreezeCoreTransformer
fc_transformer = FreezeCoreTransformer()
fc_problem = fc_transformer.transform(full_problem)
print(fc_problem.num_particles)
print(fc_problem.num_spatial_orbitals)
print(fc_problem.hamiltonian.constants)
fc_transformer = FreezeCoreTransformer(remove_orbitals=[4, 5])
fc_problem = fc_transformer.transform(full_problem)
print(fc_problem.num_particles)
print(fc_problem.num_spatial_orbitals)
from qiskit_nature.second_q.drivers import PySCFDriver
driver = PySCFDriver(atom="Li 0 0 0; H 0 0 1.5")
full_problem = driver.run()
print(full_problem.num_particles)
print(full_problem.num_spatial_orbitals)
from qiskit_nature.second_q.transformers import ActiveSpaceTransformer
as_transformer = ActiveSpaceTransformer(2, 2)
as_problem = as_transformer.transform(full_problem)
print(as_problem.num_particles)
print(as_problem.num_spatial_orbitals)
print(as_problem.hamiltonian.electronic_integrals.alpha)
as_transformer = ActiveSpaceTransformer(2, 2, active_orbitals=[0, 4])
as_problem = as_transformer.transform(full_problem)
print(as_problem.num_particles)
print(as_problem.num_spatial_orbitals)
print(as_problem.hamiltonian.electronic_integrals.alpha)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/mingweii/My-Qiskit-codes
|
mingweii
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
#Import essential packages
import matplotlib.pyplot as plt
import matplotlib.axes as axes
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
%matplotlib inline
import numpy as np
import networkx as nx
from qiskit import Aer, IBMQ
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, transpile, assemble
from qiskit.providers.ibmq import least_busy
from qiskit.tools.monitor import job_monitor
from qiskit.visualization import plot_histogram
from qiskit.optimization.applications.ising import max_cut
from qiskit.optimization.applications.ising.common import sample_most_likely
# setup aqua logging
#import logging
#from qiskit.aqua import set_qiskit_aqua_logging
# set_qiskit_aqua_logging(logging.DEBUG) # choose INFO, DEBUG to see the log
# Generating a random graph with n nodes
n = 12
V = range(n)#np.arange(0,n,1)
E=[]
edge_bool=np.random.randint(2,size=n*(n-1)) #generate a sequence of boolen numbers for all possible edges
W=np.zeros([n,n])
idx=0
for i in range(n):
for j in range(i):
temp=np.random.randint(2)
if temp==1:
E.append((i,j,1.0))
W[i,j]=1
W[j,i]=1
#if edge_bool[idx]: # if the edge_bool is 1, then add an edge between i and j vertices with a weight 1.0.
idx+=1
G = nx.Graph()# Generate a graph
G.add_nodes_from(V) # Add the nodes
G.add_weighted_edges_from(E) # Add the edges from E
# Generate plot of the Graph
colors = ['r' for node in G.nodes()]
pos = nx.spring_layout(G)
def draw_graph(G, colors, pos):
default_axes = plt.axes(frameon=True)
nx.draw_networkx(G, node_color=colors, node_size=600, alpha=1, ax=default_axes, pos=pos)
#edge_labels = nx.get_edge_attributes(G, 'weight')
#nx.draw_networkx_edge_labels(G, pos=pos, edge_labels=edge_labels)
draw_graph(G, colors, pos)
#nx.draw_networkx(G, node_color=colors, node_size=600, alpha=1, ax=default_axes, pos=pos)
print(W)
best_cost_brute = 0
for b in range(2**n):
x = [int(t) for t in reversed(list(bin(b)[2:].zfill(n)))]
cost = 0
for i in range(n):
for j in range(n):
cost = cost + W[i,j]*x[i]*(1-x[j])
if best_cost_brute < cost:
best_cost_brute = cost
xbest_brute = x
#print('case = ' + str(x)+ ' cost = ' + str(cost))
colors = ['c' if xbest_brute[i] == 0 else 'r' for i in range(n)]
draw_graph(G, colors, pos)
print('\nBest solution = ' + str(xbest_brute) + ' cost = ' + str(best_cost_brute))
# Evaluate the function
step_size = 0.001;
a_gamma = np.arange(0, np.pi, step_size)
a_beta = np.arange(0, np.pi, step_size)
a_gamma, a_beta = np.meshgrid(a_gamma,a_beta)
F1 = 3-(np.sin(2*a_beta)**2*np.sin(2*a_gamma)**2-0.5*np.sin(4*a_beta)*np.sin(4*a_gamma))*(1+np.cos(4*a_gamma)**2)
# Grid search for the minimizing variables
result = np.where(F1 == np.amax(F1))
a = list(zip(result[0],result[1]))[0]
gamma = a[0]*step_size;
beta = a[1]*step_size;
#The smallest parameters and the expectation can be extracted
print('\n --- OPTIMAL PARAMETERS --- \n')
print('The maximal expectation value is: M1 = %.03f' % np.amax(F1))
print('This is attained for gamma = %.03f and beta = %.03f' % (gamma,beta))
# prepare the quantum and classical resisters
QAOA = QuantumCircuit(len(V), len(V))
# apply the layer of Hadamard gates to all qubits
QAOA.h(range(len(V)))
QAOA.barrier()
# apply the Ising type gates with angle gamma along the edges in E
for edge in E:
k = edge[0]
l = edge[1]
QAOA.cp(-2*gamma, k, l)
QAOA.p(gamma, k)
QAOA.p(gamma, l)
# then apply the single qubit X rotations with angle beta to all qubits
QAOA.barrier()
QAOA.rx(2*beta, range(len(V)))
# Finally measure the result in the computational basis
QAOA.barrier()
QAOA.measure(range(len(V)),range(len(V)))
### draw the circuit for comparison
QAOA.draw(output='mpl')
# Compute the value of the cost function
def cost_function_C(x,G):
E = G.edges()
if( len(x) != len(G.nodes())):
return np.nan
C = 0;
for index in E:
e1 = index[0]
e2 = index[1]
w=1.0
C = C + w*x[e1]*(1-x[e2]) + w*x[e2]*(1-x[e1])
return C
# run on local simulator
backend = Aer.get_backend("qasm_simulator")
shots = 200000
TQAOA = transpile(QAOA, backend)
qobj = assemble(TQAOA)
QAOA_results = backend.run(qobj).result()
plot_histogram(QAOA_results.get_counts(),figsize = (12,6),bar_labels = False)
# Evaluate the data from the simulator
counts = QAOA_results.get_counts()
avr_C = 0
max_C = [0,0]
hist = {}
for k in range(len(G.edges())+1):
hist[str(k)] = hist.get(str(k),0)
for sample in list(counts.keys()):
# use sampled bit string x to compute C(x)
x = [int(num) for num in list(sample)]
tmp_eng = cost_function_C(x,G)
# compute the expectation value and energy distribution
avr_C = avr_C + counts[sample]*tmp_eng
hist[str(round(tmp_eng))] = hist.get(str(round(tmp_eng)),0) + counts[sample]
# save best bit string
if( max_C[1] < tmp_eng):
max_C[0] = sample
max_C[1] = tmp_eng
M1_sampled = avr_C/shots
""
print('\n --- SIMULATION RESULTS ---\n')
print('The sampled mean value is M1_sampled = %.02f while the true value is M1 = %.02f \n' % (M1_sampled,np.amax(F1)))
print('The approximate solution is x* = %s with C(x*) = %d \n' % (max_C[0],max_C[1]))
print('The cost function is distributed as: \n')
plot_histogram(hist,figsize = (8,6),bar_labels = False)
colors = ['r' if max_C[0][i] == '0' else 'c' for i in range(n)]
draw_graph(G, colors, pos)
# Use the IBMQ essex device
provider = IBMQ.load_account()
large_enough_devices = provider.backends(filters=lambda x: x.configuration().n_qubits >= n and
not x.configuration().simulator)
backend = least_busy(large_enough_devices)
shots = 8192
TQAOA = transpile(QAOA, backend)
qobj = assemble(TQAOA, shots=shots)
job_exp = backend.run(qobj)
job_monitor(job_exp)
exp_results = job_exp.result()
plot_histogram(exp_results.get_counts(),figsize = (10,8),bar_labels = False)
# Evaluate the data from the experiment
counts_exp = exp_results.get_counts()
avr_C_exp = 0
max_C_exp = [0,0]
hist_exp = {}
for k in range(len(G.edges())+1):
hist_exp[str(k)] = hist_exp.get(str(k),0)
for sample in list(counts_exp.keys()):
# use sampled bit string x to compute C(x)
x = [int(num) for num in list(sample)]
tmp_eng = cost_function_C(x,G)
# compute the expectation value and energy distribution
avr_C_exp = avr_C_exp + counts_exp[sample]*tmp_eng
hist_exp[str(round(tmp_eng))] = hist_exp.get(str(round(tmp_eng)),0) + counts_exp[sample]
# save best bit string
if( max_C_exp[1] < tmp_eng):
max_C_exp[0] = sample
max_C_exp[1] = tmp_eng
M1_sampled_exp = avr_C_exp/shots
print('\n --- EXPERIMENTAL RESULTS ---\n')
print('The sampled mean value is M1_sampled = %.02f while the true value is M1 = %.02f \n' % (M1_sampled_exp,np.amax(F1)))
print('The approximate solution is x* = %s with C(x*) = %d \n' % (max_C_exp[0],max_C_exp[1]))
print('The cost function is distributed as: \n')
plot_histogram(hist_exp,figsize = (8,6),bar_labels = False)
colors = ['c' if max_C_exp[0][i] == '0' else 'r' for i in range(n)]
draw_graph(G, colors, pos)
from qiskit import Aer
from qiskit.optimization.applications.ising import max_cut
from qiskit.aqua.algorithms import QAOA as QAOAlib
from qiskit.aqua.components.optimizers import ADAM
from qiskit.aqua import aqua_globals
from qiskit.aqua import QuantumInstance
from qiskit.optimization.applications.ising.common import sample_most_likely
qubitOp, offset = max_cut.get_operator(W)
aqua_globals.random_seed = np.random.default_rng(123)
seed = 10598
backend = Aer.get_backend('statevector_simulator')
quantum_instance = QuantumInstance(backend, seed_simulator=seed, seed_transpiler=seed)
adam = ADAM(maxiter=500)
qaoa=QAOAlib(operator=qubitOp,optimizer=adam,p=1,quantum_instance=quantum_instance)
result=qaoa.run(quantum_instance)
# print results
x = sample_most_likely(result.eigenstate)
print('energy:', result.eigenvalue.real)
print('time:', result.optimizer_time)
print('max-cut objective:', result.eigenvalue.real + offset)
print('solution:', max_cut.get_graph_solution(x))
print('solution objective:', max_cut.max_cut_value(x, W))
# plot results
colors = ['r' if max_cut.get_graph_solution(x)[i] == 0 else 'c' for i in range(n)]
draw_graph(G, colors, pos)
|
https://github.com/infiniteregrets/QiskitBot
|
infiniteregrets
|
import discord
from discord.ext import commands
import asyncio
import subprocess
import logging
import re
logger = logging.getLogger(__name__)
class DocInfo(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command(name = 'docs')
async def docs(self, ctx, *, arg):
if re.match('^`[A-Za-z]{1,20}`$', arg):
out = subprocess.run( f'echo "from qiskit import *\nhelp({arg[1:-1]})" | python3',
shell = True, text = True, capture_output = True)
if out.returncode == 0:
embed = discord.Embed(title = f'Info on {arg}',
description = f'```py{out.stdout}```')
await ctx.send(embed = embed)
else:
embed = discord.Embed(title = 'Error',
description = 'Try again with a correct class or function name and with a limit of 20 characters.')
await ctx.send(embed = embed)
def setup(bot):
bot.add_cog(DocInfo(bot))
|
https://github.com/swe-train/qiskit__qiskit
|
swe-train
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Randomized tests of quantum synthesis."""
import unittest
from test.python.quantum_info.test_synthesis import CheckDecompositions
from hypothesis import given, strategies, settings
import numpy as np
from qiskit import execute
from qiskit.circuit import QuantumCircuit, QuantumRegister
from qiskit.extensions import UnitaryGate
from qiskit.providers.basicaer import UnitarySimulatorPy
from qiskit.quantum_info.random import random_unitary
from qiskit.quantum_info.synthesis.two_qubit_decompose import (
two_qubit_cnot_decompose,
TwoQubitBasisDecomposer,
Ud,
)
class TestSynthesis(CheckDecompositions):
"""Test synthesis"""
seed = strategies.integers(min_value=0, max_value=2**32 - 1)
rotation = strategies.floats(min_value=-np.pi * 10, max_value=np.pi * 10)
@given(seed)
def test_1q_random(self, seed):
"""Checks one qubit decompositions"""
unitary = random_unitary(2, seed=seed)
self.check_one_qubit_euler_angles(unitary)
self.check_one_qubit_euler_angles(unitary, "U3")
self.check_one_qubit_euler_angles(unitary, "U1X")
self.check_one_qubit_euler_angles(unitary, "PSX")
self.check_one_qubit_euler_angles(unitary, "ZSX")
self.check_one_qubit_euler_angles(unitary, "ZYZ")
self.check_one_qubit_euler_angles(unitary, "ZXZ")
self.check_one_qubit_euler_angles(unitary, "XYX")
self.check_one_qubit_euler_angles(unitary, "RR")
@settings(deadline=None)
@given(seed)
def test_2q_random(self, seed):
"""Checks two qubit decompositions"""
unitary = random_unitary(4, seed=seed)
self.check_exact_decomposition(unitary.data, two_qubit_cnot_decompose)
@given(strategies.tuples(*[seed] * 5))
def test_exact_supercontrolled_decompose_random(self, seeds):
"""Exact decomposition for random supercontrolled basis and random target"""
k1 = np.kron(random_unitary(2, seed=seeds[0]).data, random_unitary(2, seed=seeds[1]).data)
k2 = np.kron(random_unitary(2, seed=seeds[2]).data, random_unitary(2, seed=seeds[3]).data)
basis_unitary = k1 @ Ud(np.pi / 4, 0, 0) @ k2
decomposer = TwoQubitBasisDecomposer(UnitaryGate(basis_unitary))
self.check_exact_decomposition(random_unitary(4, seed=seeds[4]).data, decomposer)
@given(strategies.tuples(*[rotation] * 6), seed)
def test_cx_equivalence_0cx_random(self, rnd, seed):
"""Check random circuits with 0 cx gates locally equivalent to identity."""
qr = QuantumRegister(2, name="q")
qc = QuantumCircuit(qr)
qc.u(rnd[0], rnd[1], rnd[2], qr[0])
qc.u(rnd[3], rnd[4], rnd[5], qr[1])
sim = UnitarySimulatorPy()
unitary = execute(qc, sim, seed_simulator=seed).result().get_unitary()
self.assertEqual(two_qubit_cnot_decompose.num_basis_gates(unitary), 0)
@given(strategies.tuples(*[rotation] * 12), seed)
def test_cx_equivalence_1cx_random(self, rnd, seed):
"""Check random circuits with 1 cx gates locally equivalent to a cx."""
qr = QuantumRegister(2, name="q")
qc = QuantumCircuit(qr)
qc.u(rnd[0], rnd[1], rnd[2], qr[0])
qc.u(rnd[3], rnd[4], rnd[5], qr[1])
qc.cx(qr[1], qr[0])
qc.u(rnd[6], rnd[7], rnd[8], qr[0])
qc.u(rnd[9], rnd[10], rnd[11], qr[1])
sim = UnitarySimulatorPy()
unitary = execute(qc, sim, seed_simulator=seed).result().get_unitary()
self.assertEqual(two_qubit_cnot_decompose.num_basis_gates(unitary), 1)
@given(strategies.tuples(*[rotation] * 18), seed)
def test_cx_equivalence_2cx_random(self, rnd, seed):
"""Check random circuits with 2 cx gates locally equivalent to some circuit with 2 cx."""
qr = QuantumRegister(2, name="q")
qc = QuantumCircuit(qr)
qc.u(rnd[0], rnd[1], rnd[2], qr[0])
qc.u(rnd[3], rnd[4], rnd[5], qr[1])
qc.cx(qr[1], qr[0])
qc.u(rnd[6], rnd[7], rnd[8], qr[0])
qc.u(rnd[9], rnd[10], rnd[11], qr[1])
qc.cx(qr[0], qr[1])
qc.u(rnd[12], rnd[13], rnd[14], qr[0])
qc.u(rnd[15], rnd[16], rnd[17], qr[1])
sim = UnitarySimulatorPy()
unitary = execute(qc, sim, seed_simulator=seed).result().get_unitary()
self.assertEqual(two_qubit_cnot_decompose.num_basis_gates(unitary), 2)
@given(strategies.tuples(*[rotation] * 24), seed)
def test_cx_equivalence_3cx_random(self, rnd, seed):
"""Check random circuits with 3 cx gates are outside the 0, 1, and 2 qubit regions."""
qr = QuantumRegister(2, name="q")
qc = QuantumCircuit(qr)
qc.u(rnd[0], rnd[1], rnd[2], qr[0])
qc.u(rnd[3], rnd[4], rnd[5], qr[1])
qc.cx(qr[1], qr[0])
qc.u(rnd[6], rnd[7], rnd[8], qr[0])
qc.u(rnd[9], rnd[10], rnd[11], qr[1])
qc.cx(qr[0], qr[1])
qc.u(rnd[12], rnd[13], rnd[14], qr[0])
qc.u(rnd[15], rnd[16], rnd[17], qr[1])
qc.cx(qr[1], qr[0])
qc.u(rnd[18], rnd[19], rnd[20], qr[0])
qc.u(rnd[21], rnd[22], rnd[23], qr[1])
sim = UnitarySimulatorPy()
unitary = execute(qc, sim, seed_simulator=seed).result().get_unitary()
self.assertEqual(two_qubit_cnot_decompose.num_basis_gates(unitary), 3)
if __name__ == "__main__":
unittest.main()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
from qiskit.quantum_info import Statevector
from qiskit.visualization import plot_state_qsphere
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
state = Statevector(qc)
plot_state_qsphere(state)
|
https://github.com/alpine-quantum-technologies/qiskit-aqt-provider-rc
|
alpine-quantum-technologies
|
from qiskit import *
from oracle_generation import generate_oracle
get_bin = lambda x, n: format(x, 'b').zfill(n)
def gen_circuits(min,max,size):
circuits = []
secrets = []
ORACLE_SIZE = size
for i in range(min,max+1):
cur_str = get_bin(i,ORACLE_SIZE-1)
(circuit, secret) = generate_oracle(ORACLE_SIZE,False,3,cur_str)
circuits.append(circuit)
secrets.append(secret)
return (circuits, secrets)
|
https://github.com/peiyong-addwater/Hackathon-QNLP
|
peiyong-addwater
|
import collections
import pickle
from tqdm.notebook import tqdm
import warnings
warnings.filterwarnings("ignore")
import os
from random import shuffle
import re
import spacy
from discopy.tensor import Tensor
from discopy import Word
from discopy.rigid import Functor
import seaborn as sns
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from numpy import random, unique
from lambeq import AtomicType, IQPAnsatz, remove_cups, NumpyModel, spiders_reader
from lambeq import BobcatParser, TreeReader, cups_reader, DepCCGParser
from lambeq import Dataset
from lambeq import QuantumTrainer, SPSAOptimizer
from lambeq import TketModel
from lambeq import SpacyTokeniser
from pytket.extensions.qiskit import AerBackend
from nltk.tokenize import sent_tokenize, word_tokenize
from nltk.corpus import stopwords
from nltk.stem import WordNetLemmatizer, PorterStemmer
from nltk import pos_tag, ne_chunk
from nltk.chunk import tree2conlltags
import seaborn as sns
import matplotlib.pyplot as plt
from collections import Counter
import nltk
nltk.download('stopwords')
nltk.download('punkt')
nltk.download('wordnet')
nltk.download('averaged_perceptron_tagger')
nltk.download('maxent_ne_chunker')
nltk.download('words')
nltk.download('omw-1.4')
pd.set_option('display.width', 1000)
pd.options.display.max_colwidth=80
print(os.getcwd())
warnings.filterwarnings("ignore")
os.environ["TOKENIZERS_PARALLELISM"] = "false"
spacy.load('en_core_web_sm')
TOTAL_DATA_RATIO = 0.1 # only use part of the data
MAX_LENGTH = 10 # only use short tweets
def get_sent_length(sent):
if type(sent) is not str:
return 9999999999999
word_list = sent.split(" ")
return len(word_list)
columns = ["Id","Entity","Target","Text"]
data = pd.read_csv(os.path.join(os.getcwd(),"data/twitter_training.csv"), names=columns,header=None)
#data = data.sample(frac=1).reset_index(drop=True)
data_val = pd.read_csv(os.path.join(os.getcwd(), "data/twitter_validation.csv"), names=columns,header=None)
#data_val = data.sample(frac=1).reset_index(drop=True)
df_train = data[["Text","Target"]]
df_train = df_train.loc[(df_train["Target"]=='Positive') | (df_train["Target"]=='Negative') & (df_train["Text"]!=np.nan)&(df_train["Text"].map(get_sent_length)<=MAX_LENGTH)]
df_train= df_train.drop_duplicates()
df_val = data_val[['Text', 'Target']]
df_val = df_val.loc[(df_val['Target'] == 'Positive') | (df_val['Target'] == 'Negative') & (df_val["Text"]!=np.nan)&(df_val["Text"].map(get_sent_length)<=MAX_LENGTH)]
text_cleaning_re = "@\S+|https?:\S+|http?:\S|[^A-Za-z0-9]+"
emoji_pattern = re.compile("["
u"\U0001F600-\U0001F64F" # emoticons
u"\U0001F300-\U0001F5FF" # symbols & pictographs
u"\U0001F680-\U0001F6FF" # transport & map symbols
u"\U0001F1E0-\U0001F1FF" # flags (iOS)
"]+", flags=re.UNICODE)
def preprocess(text):
text = re.sub(text_cleaning_re, ' ', str(text).lower()).strip()
without_emoji = emoji_pattern.sub(r'', text)
tokens = word_tokenize(str(without_emoji).replace("'", "").lower())
# Remove Puncs
without_punc = [w for w in tokens if w.isalpha()]
# Lemmatize
text_len = [WordNetLemmatizer().lemmatize(t) for t in without_punc]
# Stem
text_cleaned = [PorterStemmer().stem(w) for w in text_len]
return " ".join(text_cleaned)
df_train["Text"]= df_train["Text"].str.replace("im","i am")
df_train["Text"]= df_train["Text"].str.replace("i'm","i am")
df_train["Text"]= df_train["Text"].str.replace("I'm","i am")
df_train["Text"]= df_train["Text"].str.replace("it's","it is")
df_train["Text"]= df_train["Text"].str.replace("you're","you are")
df_train["Text"]= df_train["Text"].str.replace("hasn't","has not")
df_train["Text"]= df_train["Text"].str.replace("haven't","have not")
df_train["Text"]= df_train["Text"].str.replace("don't","do not")
df_train["Text"]= df_train["Text"].str.replace("doesn't","does not")
df_train["Text"]= df_train["Text"].str.replace("won't","will not")
df_train["Text"]= df_train["Text"].str.replace("shouldn't","should not")
df_train["Text"]= df_train["Text"].str.replace("can't","can not")
df_train["Text"]= df_train["Text"].str.replace("couldn't","could not")
df_val["Text"] = df_val["Text"].str.replace("im","i am")
df_val["Text"] = df_val["Text"].str.replace("i'm","i am")
df_val["Text"] = df_val["Text"].str.replace("I'm","i am")
df_val["Text"]= df_val["Text"].str.replace("it's","it is")
df_val["Text"]= df_val["Text"].str.replace("you're","you are")
df_val["Text"]= df_val["Text"].str.replace("hasn't","has not")
df_val["Text"]= df_val["Text"].str.replace("haven't","have not")
df_val["Text"] = df_val["Text"].str.replace("don't","do not")
df_val["Text"] = df_val["Text"].str.replace("doesn't","does not")
df_val["Text"] = df_val["Text"].str.replace("won't","will not")
df_val["Text"] = df_val["Text"].str.replace("shouldn't","should not")
df_val["Text"] = df_val["Text"].str.replace("can't","can not")
df_val["Text"] = df_val["Text"].str.replace("couldn't","could not")
df_train["Text"] = df_train["Text"].apply(preprocess)
df_val["Text"] = df_val["Text"].apply(preprocess)
df_train = df_train.dropna()
df_val = df_val.dropna()
# Positive sentiment to [0,1], negative sentiment to [1,0]
sentiment_train = []
sentiment_val = []
for i in df_train["Target"]:
if i == "Positive":
sentiment_train.append([0,1])
else:
sentiment_train.append([1,0])
df_train["Sentiment"] = sentiment_train
for i in df_val["Target"]:
if i == "Positive":
sentiment_val.append([0,1])
else:
sentiment_val.append([1,0])
df_val["Sentiment"] = sentiment_val
df_train.info()
df_val.info()
df_train.head()
df_val.head()
sns.countplot(x = "Target", data = df_train)
sns.countplot(x = "Target", data = df_val)
train_data_all, train_label_all, train_target_all = df_train["Text"].tolist(), df_train["Sentiment"].tolist(), df_train['Target'].tolist()
dev_data, dev_labels, dev_target = df_val["Text"].tolist(), df_val["Sentiment"].tolist(), df_val['Target'].tolist()
data = train_data_all+dev_data
labels = train_label_all+dev_labels
targets = train_target_all+dev_target
pairs = []
for c in zip(labels, data, targets):
if len(c[1]) > 0:
pairs.append(c)
random.seed(0)
random.shuffle(pairs)
N_EXAMPLES = len(pairs)
print("Total: {}".format(N_EXAMPLES))
parser = BobcatParser(verbose='text')
new_data = []
new_label = []
new_target = []
i = 0 # positive
j = 0 # negative
for label, sent, target in tqdm(pairs):
try:
diag = parser.sentence2diagram(sent)
except:
pass
else:
sent_length = len(sent.split(" "))
if i>round(N_EXAMPLES*TOTAL_DATA_RATIO)//2 and j>round(N_EXAMPLES*TOTAL_DATA_RATIO)//2:
break
if target == "Positive" and i<=round(N_EXAMPLES*TOTAL_DATA_RATIO)//2:
new_data.append(sent)
new_label.append(label)
new_target.append(target)
i = i + 1
if target == 'Negative' and j<=round(N_EXAMPLES*TOTAL_DATA_RATIO)//2:
new_data.append(sent)
new_label.append(label)
new_target.append(target)
j = j + 1
cleaned_qnlp_data = {"data":new_data, "label":new_label, "target":new_target}
pickle.dump(cleaned_qnlp_data, open("cleaned_qnlp_data_stem_lematize.pkl", "wb" ))
def get_sent_length(sent):
if type(sent) is not str:
return 9999999999999
word_list = sent.split(" ")
return len(word_list)
columns = ["Id","Entity","Target","Text"]
data = pd.read_csv(os.path.join(os.getcwd(),"data/twitter_training.csv"), names=columns,header=None)
#data = data.sample(frac=1).reset_index(drop=True)
data_val = pd.read_csv(os.path.join(os.getcwd(), "data/twitter_validation.csv"), names=columns,header=None)
#data_val = data.sample(frac=1).reset_index(drop=True)
df_train = data[["Text","Target"]]
df_train = df_train.loc[(df_train["Target"]=='Positive') | (df_train["Target"]=='Negative') & (df_train["Text"]!=np.nan)&(df_train["Text"].map(get_sent_length)<=MAX_LENGTH)]
df_train= df_train.drop_duplicates()
df_val = data_val[['Text', 'Target']]
df_val = df_val.loc[(df_val['Target'] == 'Positive') | (df_val['Target'] == 'Negative') & (df_val["Text"]!=np.nan)&(df_val["Text"].map(get_sent_length)<=MAX_LENGTH)]
text_cleaning_re = "@\S+|https?:\S+|http?:\S|[^A-Za-z0-9]+"
emoji_pattern = re.compile("["
u"\U0001F600-\U0001F64F" # emoticons
u"\U0001F300-\U0001F5FF" # symbols & pictographs
u"\U0001F680-\U0001F6FF" # transport & map symbols
u"\U0001F1E0-\U0001F1FF" # flags (iOS)
"]+", flags=re.UNICODE)
def preprocess(text):
text = re.sub(text_cleaning_re, ' ', str(text).lower()).strip()
without_emoji = emoji_pattern.sub(r'', text)
tokens = word_tokenize(str(without_emoji).replace("'", "").lower())
# Remove Puncs
without_punc = [w for w in tokens if w.isalpha()]
text_len = [WordNetLemmatizer().lemmatize(t) for t in without_punc]
return " ".join(text_len)
df_train["Text"]= df_train["Text"].str.replace("im","i am")
df_train["Text"]= df_train["Text"].str.replace("i'm","i am")
df_train["Text"]= df_train["Text"].str.replace("I'm","i am")
df_train["Text"]= df_train["Text"].str.replace("it's","it is")
df_train["Text"]= df_train["Text"].str.replace("you're","you are")
df_train["Text"]= df_train["Text"].str.replace("hasn't","has not")
df_train["Text"]= df_train["Text"].str.replace("haven't","have not")
df_train["Text"]= df_train["Text"].str.replace("don't","do not")
df_train["Text"]= df_train["Text"].str.replace("doesn't","does not")
df_train["Text"]= df_train["Text"].str.replace("won't","will not")
df_train["Text"]= df_train["Text"].str.replace("shouldn't","should not")
df_train["Text"]= df_train["Text"].str.replace("can't","can not")
df_train["Text"]= df_train["Text"].str.replace("couldn't","could not")
df_val["Text"] = df_val["Text"].str.replace("im","i am")
df_val["Text"] = df_val["Text"].str.replace("i'm","i am")
df_val["Text"] = df_val["Text"].str.replace("I'm","i am")
df_val["Text"]= df_val["Text"].str.replace("it's","it is")
df_val["Text"]= df_val["Text"].str.replace("you're","you are")
df_val["Text"]= df_val["Text"].str.replace("hasn't","has not")
df_val["Text"]= df_val["Text"].str.replace("haven't","have not")
df_val["Text"] = df_val["Text"].str.replace("don't","do not")
df_val["Text"] = df_val["Text"].str.replace("doesn't","does not")
df_val["Text"] = df_val["Text"].str.replace("won't","will not")
df_val["Text"] = df_val["Text"].str.replace("shouldn't","should not")
df_val["Text"] = df_val["Text"].str.replace("can't","can not")
df_val["Text"] = df_val["Text"].str.replace("couldn't","could not")
df_train["Text"] = df_train["Text"].apply(preprocess)
df_val["Text"] = df_val["Text"].apply(preprocess)
df_train = df_train.dropna()
df_val = df_val.dropna()
# Positive sentiment to [0,1], negative sentiment to [1,0]
sentiment_train = []
sentiment_val = []
for i in df_train["Target"]:
if i == "Positive":
sentiment_train.append([0,1])
else:
sentiment_train.append([1,0])
df_train["Sentiment"] = sentiment_train
for i in df_val["Target"]:
if i == "Positive":
sentiment_val.append([0,1])
else:
sentiment_val.append([1,0])
df_val["Sentiment"] = sentiment_val
train_data_all, train_label_all, train_target_all = df_train["Text"].tolist(), df_train["Sentiment"].tolist(), df_train['Target'].tolist()
dev_data, dev_labels, dev_target = df_val["Text"].tolist(), df_val["Sentiment"].tolist(), df_val['Target'].tolist()
data = train_data_all+dev_data
labels = train_label_all+dev_labels
targets = train_target_all+dev_target
pairs = []
for c in zip(labels, data, targets):
if len(c[1]) > 0:
pairs.append(c)
random.seed(0)
random.shuffle(pairs)
N_EXAMPLES = len(pairs)
print("Total: {}".format(N_EXAMPLES))
new_data = []
new_label = []
new_target = []
i = 0 # positive
j = 0 # negative
parser = BobcatParser(verbose='text')
for label, sent, target in tqdm(pairs):
try:
diag = parser.sentence2diagram(sent)
except:
pass
else:
sent_length = len(sent.split(" "))
if i>round(N_EXAMPLES*TOTAL_DATA_RATIO)//2 and j>round(N_EXAMPLES*TOTAL_DATA_RATIO)//2:
break
if target == "Positive" and i<=round(N_EXAMPLES*TOTAL_DATA_RATIO)//2:
new_data.append(sent)
new_label.append(label)
new_target.append(target)
i = i + 1
if target == 'Negative' and j<=round(N_EXAMPLES*TOTAL_DATA_RATIO)//2:
new_data.append(sent)
new_label.append(label)
new_target.append(target)
j = j + 1
cleaned_qnlp_data = {"data":new_data, "label":new_label, "target":new_target}
pickle.dump(cleaned_qnlp_data, open("cleaned_qnlp_data_lematize.pkl", "wb" ))
def get_sent_length(sent):
if type(sent) is not str:
return 9999999999999
word_list = sent.split(" ")
return len(word_list)
columns = ["Id","Entity","Target","Text"]
data = pd.read_csv(os.path.join(os.getcwd(),"data/twitter_training.csv"), names=columns,header=None)
#data = data.sample(frac=1).reset_index(drop=True)
data_val = pd.read_csv(os.path.join(os.getcwd(), "data/twitter_validation.csv"), names=columns,header=None)
#data_val = data.sample(frac=1).reset_index(drop=True)
df_train = data[["Text","Target"]]
df_train = df_train.loc[(df_train["Target"]=='Positive') | (df_train["Target"]=='Negative') & (df_train["Text"]!=np.nan)&(df_train["Text"].map(get_sent_length)<=MAX_LENGTH)]
df_train= df_train.drop_duplicates()
df_val = data_val[['Text', 'Target']]
df_val = df_val.loc[(df_val['Target'] == 'Positive') | (df_val['Target'] == 'Negative') & (df_val["Text"]!=np.nan)&(df_val["Text"].map(get_sent_length)<=MAX_LENGTH)]
text_cleaning_re = "@\S+|https?:\S+|http?:\S|[^A-Za-z0-9]+"
emoji_pattern = re.compile("["
u"\U0001F600-\U0001F64F" # emoticons
u"\U0001F300-\U0001F5FF" # symbols & pictographs
u"\U0001F680-\U0001F6FF" # transport & map symbols
u"\U0001F1E0-\U0001F1FF" # flags (iOS)
"]+", flags=re.UNICODE)
def preprocess(text):
text = re.sub(text_cleaning_re, ' ', str(text).lower()).strip()
without_emoji = emoji_pattern.sub(r'', text)
tokens = word_tokenize(str(without_emoji).replace("'", "").lower())
# Remove Puncs
without_punc = [w for w in tokens if w.isalpha()]
# text_len = [WordNetLemmatizer().lemmatize(t) for t in without_punc]
return " ".join(without_punc)
df_train["Text"]= df_train["Text"].str.replace("im","i am")
df_train["Text"]= df_train["Text"].str.replace("i'm","i am")
df_train["Text"]= df_train["Text"].str.replace("I'm","i am")
df_train["Text"]= df_train["Text"].str.replace("it's","it is")
df_train["Text"]= df_train["Text"].str.replace("you're","you are")
df_train["Text"]= df_train["Text"].str.replace("hasn't","has not")
df_train["Text"]= df_train["Text"].str.replace("haven't","have not")
df_train["Text"]= df_train["Text"].str.replace("don't","do not")
df_train["Text"]= df_train["Text"].str.replace("doesn't","does not")
df_train["Text"]= df_train["Text"].str.replace("won't","will not")
df_train["Text"]= df_train["Text"].str.replace("shouldn't","should not")
df_train["Text"]= df_train["Text"].str.replace("can't","can not")
df_train["Text"]= df_train["Text"].str.replace("couldn't","could not")
df_val["Text"] = df_val["Text"].str.replace("im","i am")
df_val["Text"] = df_val["Text"].str.replace("i'm","i am")
df_val["Text"] = df_val["Text"].str.replace("I'm","i am")
df_val["Text"]= df_val["Text"].str.replace("it's","it is")
df_val["Text"]= df_val["Text"].str.replace("you're","you are")
df_val["Text"]= df_val["Text"].str.replace("hasn't","has not")
df_val["Text"]= df_val["Text"].str.replace("haven't","have not")
df_val["Text"] = df_val["Text"].str.replace("don't","do not")
df_val["Text"] = df_val["Text"].str.replace("doesn't","does not")
df_val["Text"] = df_val["Text"].str.replace("won't","will not")
df_val["Text"] = df_val["Text"].str.replace("shouldn't","should not")
df_val["Text"] = df_val["Text"].str.replace("can't","can not")
df_val["Text"] = df_val["Text"].str.replace("couldn't","could not")
df_train["Text"] = df_train["Text"].apply(preprocess)
df_val["Text"] = df_val["Text"].apply(preprocess)
df_train = df_train.dropna()
df_val = df_val.dropna()
# Positive sentiment to [0,1], negative sentiment to [1,0]
sentiment_train = []
sentiment_val = []
for i in df_train["Target"]:
if i == "Positive":
sentiment_train.append([0,1])
else:
sentiment_train.append([1,0])
df_train["Sentiment"] = sentiment_train
for i in df_val["Target"]:
if i == "Positive":
sentiment_val.append([0,1])
else:
sentiment_val.append([1,0])
df_val["Sentiment"] = sentiment_val
train_data_all, train_label_all, train_target_all = df_train["Text"].tolist(), df_train["Sentiment"].tolist(), df_train['Target'].tolist()
dev_data, dev_labels, dev_target = df_val["Text"].tolist(), df_val["Sentiment"].tolist(), df_val['Target'].tolist()
data = train_data_all+dev_data
labels = train_label_all+dev_labels
targets = train_target_all+dev_target
pairs = []
for c in zip(labels, data, targets):
if len(c[1]) > 0:
pairs.append(c)
random.seed(0)
random.shuffle(pairs)
N_EXAMPLES = len(pairs)
print("Total: {}".format(N_EXAMPLES))
new_data = []
new_label = []
new_target = []
i = 0 # positive
j = 0 # negative
parser = BobcatParser(verbose='text')
for label, sent, target in tqdm(pairs):
try:
diag = parser.sentence2diagram(sent)
except:
pass
else:
sent_length = len(sent.split(" "))
if i>round(N_EXAMPLES*TOTAL_DATA_RATIO)//2 and j>round(N_EXAMPLES*TOTAL_DATA_RATIO)//2:
break
if target == "Positive" and i<=round(N_EXAMPLES*TOTAL_DATA_RATIO)//2:
new_data.append(sent)
new_label.append(label)
new_target.append(target)
i = i + 1
if target == 'Negative' and j<=round(N_EXAMPLES*TOTAL_DATA_RATIO)//2:
new_data.append(sent)
new_label.append(label)
new_target.append(target)
j = j + 1
cleaned_qnlp_data = {"data":new_data, "label":new_label, "target":new_target}
pickle.dump(cleaned_qnlp_data, open("cleaned_qnlp_data.pkl", "wb" ))
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
# useful additional packages
import matplotlib.pyplot as plt
import numpy as np
import networkx as nx
from qiskit_aer import Aer
from qiskit.tools.visualization import plot_histogram
from qiskit.circuit.library import TwoLocal
from qiskit_optimization.applications import Maxcut, Tsp
from qiskit.algorithms.minimum_eigensolvers import SamplingVQE, NumPyMinimumEigensolver
from qiskit.algorithms.optimizers import SPSA
from qiskit.utils import algorithm_globals
from qiskit.primitives import Sampler
from qiskit_optimization.algorithms import MinimumEigenOptimizer
# Generating a graph of 4 nodes
n = 4 # Number of nodes in graph
G = nx.Graph()
G.add_nodes_from(np.arange(0, n, 1))
elist = [(0, 1, 1.0), (0, 2, 1.0), (0, 3, 1.0), (1, 2, 1.0), (2, 3, 1.0)]
# tuple is (i,j,weight) where (i,j) is the edge
G.add_weighted_edges_from(elist)
colors = ["r" for node in G.nodes()]
pos = nx.spring_layout(G)
def draw_graph(G, colors, pos):
default_axes = plt.axes(frameon=True)
nx.draw_networkx(G, node_color=colors, node_size=600, alpha=0.8, ax=default_axes, pos=pos)
edge_labels = nx.get_edge_attributes(G, "weight")
nx.draw_networkx_edge_labels(G, pos=pos, edge_labels=edge_labels)
draw_graph(G, colors, pos)
# Computing the weight matrix from the random graph
w = np.zeros([n, n])
for i in range(n):
for j in range(n):
temp = G.get_edge_data(i, j, default=0)
if temp != 0:
w[i, j] = temp["weight"]
print(w)
best_cost_brute = 0
for b in range(2**n):
x = [int(t) for t in reversed(list(bin(b)[2:].zfill(n)))]
cost = 0
for i in range(n):
for j in range(n):
cost = cost + w[i, j] * x[i] * (1 - x[j])
if best_cost_brute < cost:
best_cost_brute = cost
xbest_brute = x
print("case = " + str(x) + " cost = " + str(cost))
colors = ["r" if xbest_brute[i] == 0 else "c" for i in range(n)]
draw_graph(G, colors, pos)
print("\nBest solution = " + str(xbest_brute) + " cost = " + str(best_cost_brute))
max_cut = Maxcut(w)
qp = max_cut.to_quadratic_program()
print(qp.prettyprint())
qubitOp, offset = qp.to_ising()
print("Offset:", offset)
print("Ising Hamiltonian:")
print(str(qubitOp))
# solving Quadratic Program using exact classical eigensolver
exact = MinimumEigenOptimizer(NumPyMinimumEigensolver())
result = exact.solve(qp)
print(result.prettyprint())
# Making the Hamiltonian in its full form and getting the lowest eigenvalue and eigenvector
ee = NumPyMinimumEigensolver()
result = ee.compute_minimum_eigenvalue(qubitOp)
x = max_cut.sample_most_likely(result.eigenstate)
print("energy:", result.eigenvalue.real)
print("max-cut objective:", result.eigenvalue.real + offset)
print("solution:", x)
print("solution objective:", qp.objective.evaluate(x))
colors = ["r" if x[i] == 0 else "c" for i in range(n)]
draw_graph(G, colors, pos)
algorithm_globals.random_seed = 123
seed = 10598
# construct SamplingVQE
optimizer = SPSA(maxiter=300)
ry = TwoLocal(qubitOp.num_qubits, "ry", "cz", reps=5, entanglement="linear")
vqe = SamplingVQE(sampler=Sampler(), ansatz=ry, optimizer=optimizer)
# run SamplingVQE
result = vqe.compute_minimum_eigenvalue(qubitOp)
# print results
x = max_cut.sample_most_likely(result.eigenstate)
print("energy:", result.eigenvalue.real)
print("time:", result.optimizer_time)
print("max-cut objective:", result.eigenvalue.real + offset)
print("solution:", x)
print("solution objective:", qp.objective.evaluate(x))
# plot results
colors = ["r" if x[i] == 0 else "c" for i in range(n)]
draw_graph(G, colors, pos)
# create minimum eigen optimizer based on SamplingVQE
vqe_optimizer = MinimumEigenOptimizer(vqe)
# solve quadratic program
result = vqe_optimizer.solve(qp)
print(result.prettyprint())
colors = ["r" if result.x[i] == 0 else "c" for i in range(n)]
draw_graph(G, colors, pos)
# Generating a graph of 3 nodes
n = 3
num_qubits = n**2
tsp = Tsp.create_random_instance(n, seed=123)
adj_matrix = nx.to_numpy_array(tsp.graph)
print("distance\n", adj_matrix)
colors = ["r" for node in tsp.graph.nodes]
pos = [tsp.graph.nodes[node]["pos"] for node in tsp.graph.nodes]
draw_graph(tsp.graph, colors, pos)
from itertools import permutations
def brute_force_tsp(w, N):
a = list(permutations(range(1, N)))
last_best_distance = 1e10
for i in a:
distance = 0
pre_j = 0
for j in i:
distance = distance + w[j, pre_j]
pre_j = j
distance = distance + w[pre_j, 0]
order = (0,) + i
if distance < last_best_distance:
best_order = order
last_best_distance = distance
print("order = " + str(order) + " Distance = " + str(distance))
return last_best_distance, best_order
best_distance, best_order = brute_force_tsp(adj_matrix, n)
print(
"Best order from brute force = "
+ str(best_order)
+ " with total distance = "
+ str(best_distance)
)
def draw_tsp_solution(G, order, colors, pos):
G2 = nx.DiGraph()
G2.add_nodes_from(G)
n = len(order)
for i in range(n):
j = (i + 1) % n
G2.add_edge(order[i], order[j], weight=G[order[i]][order[j]]["weight"])
default_axes = plt.axes(frameon=True)
nx.draw_networkx(
G2, node_color=colors, edge_color="b", node_size=600, alpha=0.8, ax=default_axes, pos=pos
)
edge_labels = nx.get_edge_attributes(G2, "weight")
nx.draw_networkx_edge_labels(G2, pos, font_color="b", edge_labels=edge_labels)
draw_tsp_solution(tsp.graph, best_order, colors, pos)
qp = tsp.to_quadratic_program()
print(qp.prettyprint())
from qiskit_optimization.converters import QuadraticProgramToQubo
qp2qubo = QuadraticProgramToQubo()
qubo = qp2qubo.convert(qp)
qubitOp, offset = qubo.to_ising()
print("Offset:", offset)
print("Ising Hamiltonian:")
print(str(qubitOp))
result = exact.solve(qubo)
print(result.prettyprint())
# Making the Hamiltonian in its full form and getting the lowest eigenvalue and eigenvector
ee = NumPyMinimumEigensolver()
result = ee.compute_minimum_eigenvalue(qubitOp)
print("energy:", result.eigenvalue.real)
print("tsp objective:", result.eigenvalue.real + offset)
x = tsp.sample_most_likely(result.eigenstate)
print("feasible:", qubo.is_feasible(x))
z = tsp.interpret(x)
print("solution:", z)
print("solution objective:", tsp.tsp_value(z, adj_matrix))
draw_tsp_solution(tsp.graph, z, colors, pos)
algorithm_globals.random_seed = 123
seed = 10598
optimizer = SPSA(maxiter=300)
ry = TwoLocal(qubitOp.num_qubits, "ry", "cz", reps=5, entanglement="linear")
vqe = SamplingVQE(sampler=Sampler(), ansatz=ry, optimizer=optimizer)
result = vqe.compute_minimum_eigenvalue(qubitOp)
print("energy:", result.eigenvalue.real)
print("time:", result.optimizer_time)
x = tsp.sample_most_likely(result.eigenstate)
print("feasible:", qubo.is_feasible(x))
z = tsp.interpret(x)
print("solution:", z)
print("solution objective:", tsp.tsp_value(z, adj_matrix))
draw_tsp_solution(tsp.graph, z, colors, pos)
algorithm_globals.random_seed = 123
seed = 10598
# create minimum eigen optimizer based on SamplingVQE
vqe_optimizer = MinimumEigenOptimizer(vqe)
# solve quadratic program
result = vqe_optimizer.solve(qp)
print(result.prettyprint())
z = tsp.interpret(x)
print("solution:", z)
print("solution objective:", tsp.tsp_value(z, adj_matrix))
draw_tsp_solution(tsp.graph, z, colors, pos)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/1chooo/Quantum-Oracle
|
1chooo
|
from qiskit import execute
from qiskit.providers.aer import AerSimulator
from qiskit.visualization import plot_histogram
from qiskit import QuantumCircuit, execute
from qiskit.quantum_info import Statevector
qc = QuantumCircuit(8, 8)
sv = Statevector.from_label("11011000")
qc.initialize(sv, range(8))
qc.cx(0, 1)
qc.cx(2, 3)
qc.cx(4, 5)
qc.cx(6, 7)
qc.measure(range(8), range(8))
qc.draw("mpl")
sim = AerSimulator()
job = execute(qc, backend=sim, shots=1000)
result = job.result()
counts = result.get_counts(qc)
print("Counts: ", counts)
plot_histogram(counts)
|
https://github.com/ttlion/ShorAlgQiskit
|
ttlion
|
"""
This is the final implementation of Shor's Algorithm using the circuit presented in section 2.3 of the report about the second
simplification introduced by the base paper used.
The circuit is general, so, in a good computer that can support simulations infinite qubits, it can factorize any number N. The only limitation
is the capacity of the computer when running in local simulator and the limits on the IBM simulator (in the number of qubits and in the number
of QASM instructions the simulations can have when sent to IBM simulator).
The user may try N=21, which is an example that runs perfectly fine even just in local simulator because, as in explained in report, this circuit,
because implements the QFT sequentially, uses less qubits then when using a "normal"n QFT.
"""
""" Imports from qiskit"""
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit import execute, IBMQ
from qiskit import BasicAer
import sys
""" Imports to Python functions """
import math
import array
import fractions
import numpy as np
import time
""" Local Imports """
from cfunctions import check_if_power, get_value_a
from cfunctions import get_factors
from qfunctions import create_QFT, create_inverse_QFT
from qfunctions import getAngle, cMULTmodN
""" Main program """
if __name__ == '__main__':
""" Ask for analysis number N """
N = int(input('Please insert integer number N: '))
print('input number was: {0}\n'.format(N))
""" Check if N==1 or N==0"""
if N==1 or N==0:
print('Please put an N different from 0 and from 1')
exit()
""" Check if N is even """
if (N%2)==0:
print('N is even, so does not make sense!')
exit()
""" Check if N can be put in N=p^q, p>1, q>=2 """
""" Try all numbers for p: from 2 to sqrt(N) """
if check_if_power(N)==True:
exit()
print('Not an easy case, using the quantum circuit is necessary\n')
""" To login to IBM Q experience the following functions should be called """
"""
IBMQ.delete_accounts()
IBMQ.save_account('insert token here')
IBMQ.load_accounts()"""
""" Get an integer a that is coprime with N """
a = get_value_a(N)
""" If user wants to force some values, can do that here, please make sure to update print and that N and a are coprime"""
"""print('Forcing N=15 and a=4 because its the fastest case, please read top of source file for more info')
N=15
a=2"""
""" Get n value used in Shor's algorithm, to know how many qubits are used """
n = math.ceil(math.log(N,2))
print('Total number of qubits used: {0}\n'.format(2*n+3))
ts = time.time()
""" Create quantum and classical registers """
"""auxilliary quantum register used in addition and multiplication"""
aux = QuantumRegister(n+2)
"""single qubit where the sequential QFT is performed"""
up_reg = QuantumRegister(1)
"""quantum register where the multiplications are made"""
down_reg = QuantumRegister(n)
"""classical register where the measured values of the sequential QFT are stored"""
up_classic = ClassicalRegister(2*n)
"""classical bit used to reset the state of the top qubit to 0 if the previous measurement was 1"""
c_aux = ClassicalRegister(1)
""" Create Quantum Circuit """
circuit = QuantumCircuit(down_reg , up_reg , aux, up_classic, c_aux)
""" Initialize down register to 1"""
circuit.x(down_reg[0])
""" Cycle to create the Sequential QFT, measuring qubits and applying the right gates according to measurements """
for i in range(0, 2*n):
"""reset the top qubit to 0 if the previous measurement was 1"""
circuit.x(up_reg).c_if(c_aux, 1)
circuit.h(up_reg)
cMULTmodN(circuit, up_reg[0], down_reg, aux, a**(2**(2*n-1-i)), N, n)
"""cycle through all possible values of the classical register and apply the corresponding conditional phase shift"""
for j in range(0, 2**i):
"""the phase shift is applied if the value of the classical register matches j exactly"""
circuit.u1(getAngle(j, i), up_reg[0]).c_if(up_classic, j)
circuit.h(up_reg)
circuit.measure(up_reg[0], up_classic[i])
circuit.measure(up_reg[0], c_aux[0])
""" show results of circuit creation """
create_time = round(time.time()-ts, 3)
#if n < 8: print(circuit)
print(f"... circuit creation time = {create_time}")
ts = time.time()
""" Select how many times the circuit runs"""
number_shots=int(input('Number of times to run the circuit: '))
if number_shots < 1:
print('Please run the circuit at least one time...')
exit()
""" Print info to user """
print('Executing the circuit {0} times for N={1} and a={2}\n'.format(number_shots,N,a))
""" Simulate the created Quantum Circuit """
simulation = execute(circuit, backend=BasicAer.get_backend('qasm_simulator'),shots=number_shots)
""" to run on IBM, use backend=IBMQ.get_backend('ibmq_qasm_simulator') in execute() function """
""" to run locally, use backend=BasicAer.get_backend('qasm_simulator') in execute() function """
""" Get the results of the simulation in proper structure """
sim_result=simulation.result()
counts_result = sim_result.get_counts(circuit)
""" show execution time """
exec_time = round(time.time()-ts, 3)
print(f"... circuit execute time = {exec_time}")
""" Print info to user from the simulation results """
print('Printing the various results followed by how many times they happened (out of the {} cases):\n'.format(number_shots))
i=0
while i < len(counts_result):
print('Result \"{0}\" happened {1} times out of {2}'.format(list(sim_result.get_counts().keys())[i],list(sim_result.get_counts().values())[i],number_shots))
i=i+1
""" An empty print just to have a good display in terminal """
print(' ')
""" Initialize this variable """
prob_success=0
""" For each simulation result, print proper info to user and try to calculate the factors of N"""
i=0
while i < len(counts_result):
""" Get the x_value from the final state qubits """
all_registers_output = list(sim_result.get_counts().keys())[i]
output_desired = all_registers_output.split(" ")[1]
x_value = int(output_desired, 2)
prob_this_result = 100 * ( int( list(sim_result.get_counts().values())[i] ) ) / (number_shots)
print("------> Analysing result {0}. This result happened in {1:.4f} % of all cases\n".format(output_desired,prob_this_result))
""" Print the final x_value to user """
print('In decimal, x_final value for this result is: {0}\n'.format(x_value))
""" Get the factors using the x value obtained """
success = get_factors(int(x_value),int(2*n),int(N),int(a))
if success==True:
prob_success = prob_success + prob_this_result
i=i+1
print("\nUsing a={0}, found the factors of N={1} in {2:.4f} % of the cases\n".format(a,N,prob_success))
|
https://github.com/Qiskit/feedback
|
Qiskit
|
from qiskit import __qiskit_version__
print(__qiskit_version__)
from qiskit.tools.jupyter import *
%qiskit_version_table
from qiskit import __version__
print(__version__)
from qiskit.version import get_version_info
|
https://github.com/rubenandrebarreiro/ibm-qiskit-global-summer-school-2023
|
rubenandrebarreiro
|
# required import of libraries and modules
# import quantum circuit from IBM's Qiskit circuit module
from qiskit.circuit import QuantumCircuit
# import estimator and sample
# from IBM's Qiskit primitives module
from qiskit.primitives import Estimator, Sampler
# import Sparse Pauli operator
# from IBM's Qiskit quantum information module
from qiskit.quantum_info import SparsePauliOp
# import histogram plotting
# from IBM's Qiskit visualization module
from qiskit.visualization import plot_histogram
# import numpy
import numpy as np
# import plotting from Matplotlib's pyplot module
import matplotlib.pyplot as plt
# OPTIONAL: use the dark background style
# for the plotting from Matplotlib's pyplot module
plt.style.use("dark_background")
# create an excited state |1>
# create a quantum circuit for one qubit
# and to implement an excited state |1>
qc_1 = QuantumCircuit(1)
# apply a Pauli-X (bit flip / not) gate to
# the quantum circuit, on the 1st qubit
qc_1.x(0)
# draw the quantum circuit implementing
# the excited state |1>
qc_1.draw("mpl")
# create quantum superposition state |+>
# create a quantum circuit for one qubit
# and to implement a quantum superposition state |+>
qc_plus = QuantumCircuit(1)
# apply a Hadamard gate to
# the quantum circuit, on the 1st qubit
qc_plus.h(0)
# draw the quantum circuit implementing
# the quantum superposition state |+>
qc_plus.draw("mpl")
# measure all the qubits of
# the quantum circuit implementing
# an excited state |1>
qc_1.measure_all()
# measure all the qubits of
# the quantum circuit implementing
# a quantum superposition state |+>
qc_plus.measure_all()
# create a Sampler object
sampler = Sampler()
# create a job for the quantum circuit implementing
# an excited state |1>, running the Sampler
job_1 = sampler.run(qc_1)
# create a job for the quantum circuit implementing
# a quantum superposition state |+>, running the Sampler
job_plus = sampler.run(qc_plus)
# retrieve the quasi-distribution of
# the job for the quantum circuit
# implementing an excited state |1>
quasi_dists_ket_1 = job_1.result().quasi_dists
# fix the legend issue for
# the quasi-distribution of the outcome 0
quasi_dists_ket_1[0][0] = 1e-20
# show the quasi-distribution of
# the job for the quantum circuit
# implementing an excited state |1>
quasi_dists_ket_1
# retrieve the quasi-distribution of
# the job for the quantum circuit implementing
# a quantum superposition state |+>
quasi_dists_ket_plus = job_plus.result().quasi_dists
# show the quasi-distribution of
# the job for the quantum circuit
# implementing a quantum superposition state |+>
quasi_dists_ket_plus
# create the legend for the two quantum states
# created before, namely the excited state |1> and
# the quantum superposition state |+>
legend = ["Excited State", "Plus State"]
# plot the histogram for the quasi-distributions
# for the two quantum states created before,
# namely the excited state |1> and
# the quantum superposition state |+>
plot_histogram( [ quasi_dists_ket_1[0], quasi_dists_ket_plus[0] ],
legend=legend, title="Measurement Results\n" )
# remove all the qubits' measurements of
# the quantum circuit implementing
# an excited state |1>
qc_1.remove_final_measurements()
# remove all the qubits' measurements of
# the quantum circuit implementing
# a quantum superposition state |+>
qc_plus.remove_final_measurements()
# prepare the 1st qubit of the quantum circuit
# implementing an excited state |1>,
# for the X-Basis measurement,
# applying a Hadamard gate
qc_1.h(0)
# prepare the 1st qubit of the quantum circuit
# implementing a quantum superposition state |+>,
# for the X-Basis measurement,
# applying a Hadamard gate
qc_plus.h(0)
# measure all the qubits of
# the quantum circuit implementing
# an excited state |1>
qc_1.measure_all()
# measure all the qubits of
# the quantum circuit implementing
# a quantum superposition state |+>
qc_plus.measure_all()
# create a Sampler object
sampler = Sampler()
# create a job for the quantum circuit implementing
# an excited state |1>, running the Sampler
job_1 = sampler.run(qc_1)
# create a job for the quantum circuit implementing
# a quantum superposition state |+>, running the Sampler
job_plus = sampler.run(qc_plus)
# retrieve the quasi-distribution of
# the job for the quantum circuit
# implementing an excited state |1>,
# measured in the X-Basis
quasi_dists_ket_1 = job_1.result().quasi_dists
# show the quasi-distribution of
# the job for the quantum circuit
# implementing an excited state |1>,
# measured in the X-Basis
quasi_dists_ket_1
# retrieve the quasi-distribution of
# the job for the quantum circuit
# implementing a quantum superposition state |+>,
# measured in the X-Basis
quasi_dists_ket_plus = job_plus.result().quasi_dists
# fix the legend issue for
# the quasi-distribution of the outcome 1
quasi_dists_ket_plus[0][1] = 1e-20
# show the quasi-distribution of
# the job for the quantum circuit
# implementing a quantum superposition state |+>,
# measured in the X-Basis
quasi_dists_ket_plus
# plot the histogram for the quasi-distributions
# for the two quantum states created before,
# namely the excited state |1> and
# the quantum superposition state |+>,
# measured in the X-Basis
plot_histogram( [ quasi_dists_ket_1[0], quasi_dists_ket_plus[0] ],
legend=legend, title="Measurement Results\n" )
# create a quantum circuit for one qubit
# and to implement an excited state |1>
qc2_1 = QuantumCircuit(1)
# apply a Pauli-X (bit flip / not) gate to
# the quantum circuit, on the 1st qubit
qc2_1.x(0)
# create a quantum circuit for one qubit
# and to implement a quantum superposition state |+>
qc2_plus = QuantumCircuit(1)
# apply a Hadamard gate to
# the quantum circuit, on the 1st qubit
qc2_plus.h(0)
# create a list for the observables for
# the Sparse Pauli-Z and Pauli-X operators
obsvs = list( SparsePauliOp( [ "Z", "X" ] ) )
# crate an Estimator object
estimator = Estimator()
# create a job for the quantum circuit implementing
# an excited state |1>, running the Estimator
job2_1 = estimator.run( [ qc2_1 ] * len(obsvs), observables=obsvs )
# create a job for the quantum circuit implementing
# a quantum superposition state |+>, running the Estimator
job2_plus = estimator.run( [ qc2_plus ] * len(obsvs), observables=obsvs )
# show the results of the job ran by
# the Estimator created before,
# that was ran on the excited state |1>
job2_1.result()
# print a table with results (and eigenvalues) for
# the quantum states created before and measured in the bases set before
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]}')
# import the Sparse Pauli operator from
# the IBM's Qiskit quantum information module
from qiskit.quantum_info import SparsePauliOp
# For Alice: A = Z ; a = X
# For Bob: B = Z ; b = X
# create the Sparse Pauli operator ZZ, for <AB>
ZZ = SparsePauliOp.from_list( [ ( "ZZ", 1 ) ] )
# create the Sparse Pauli operator ZX, for <Ab>
ZX = SparsePauliOp.from_list( [ ( "ZX", 1 ) ] )
# create the Sparse Pauli operator XZ, for <aB>
XZ = SparsePauliOp.from_list( [ ( "XZ", 1 ) ] )
# create the Sparse Pauli operator XX, for <ab>
XX = SparsePauliOp.from_list( [ ( "XX", 1 ) ] )
# create the list of required
# operators ZZ, ZX, XZ, and XX
ops = [ ZZ, ZX, XZ, XX ]
# there are two possible CHSH witnesses
# create operator for CHSH witness <CHSH_1>
# <CHSH_1> = <ZZ> - <ZX> + <XZ> + <XX> (=)
# (=) <CHSH_1> = <AB> - <Ab> + <aB> + <ab>
#obsv = ops[0] - ops[1] + ops[2] + ops[3]
# create operator for CHSH witness <CHSH_2>
# <CHSH_2> = <ZZ> + <ZX> - <XZ> + <XX> (=)
# (=) <CHSH_2> = <AB> + <Ab> - <aB> + <ab>
obsv = ( ops[0] + ops[1] - ops[2] + ops[3] )
# import the grader for the exercise 1 of the lab 2
from qc_grader.challenges.qgss_2023 import grade_lab2_ex1
# grade the exercise 1 of the lab 2
grade_lab2_ex1( obsv )
# import the parameter from
# the IBM's Qiskit circuit module
from qiskit.circuit import Parameter
# create a parameter for the theta angle
theta = Parameter("θ")
# create a quantum circuit for two qubits
# and to implement a parametrized quantum entangled pair
qc = QuantumCircuit(2)
# apply a Hadamard gate to
# the quantum circuit, on the 1st qubit
qc.h(0)
# apply a CX/CNOT gate to
# the quantum circuit,
# with control on 1st qubit
# and target on 2nd qubit
qc.cx(0, 1)
# apply a RY (Rotation-Y) gate to
# the quantum circuit, on the 1st qubit,
# with the theta angle defined before
qc.ry(theta, 0)
# draw the quantum circuit implementing
# a parametrized quantum entangled pair
qc.draw("mpl")
# create a parameterization of theta angles that
# will violate the CHSH inequality
# number of theta angles to violate the CHSH inequality
number_of_phases = 20
# for the 1st CHSH witness
# <CHSH_1> = <ZZ> - <ZX> + <XZ> + <XX> (=)
# (=) <CHSH_1> = <AB> - <Ab> + <aB> + <ab>
#phases_chsh_1_1 = np.linspace(0.5 * np.pi, np.pi, number_of_phases)
#phases_chsh_1_2 = np.linspace(1.5 * np.pi, 2 * np.pi, number_of_phases)
# create the two lists of theta angles that
# violate the CHSH inequality
#angles_chsh_1_1 = [[ph] for ph in phases_chsh_1_1]
#angles_chsh_1_2 = [[ph] for ph in phases_chsh_1_2]
# merge the two lists of theta angles that
# violate the CHSH inequality, for the final result
#angles = angles_chsh_1_1 + angles_chsh_1_2
# for the 2nd CHSH witness
# <CHSH_2> = <ZZ> + <ZX> - <XZ> + <XX> (=)
# (=) <CHSH_2> = <AB> + <Ab> - <aB> + <ab>
phases_chsh_2_1 = np.linspace( 0, ( 0.5 * np.pi ), number_of_phases )
phases_chsh_2_2 = np.linspace( ( 1 * np.pi ) , ( 1.5 * np.pi ), number_of_phases )
# create the two lists of theta angles that
# violate the CHSH inequality
angles_chsh_2_1 = [ [ph] for ph in phases_chsh_2_1 ]
angles_chsh_2_2 = [ [ph] for ph in phases_chsh_2_2 ]
# merge the two lists of theta angles that
# violate the CHSH inequality, for the final result
angles = angles_chsh_2_1 + angles_chsh_2_2
# crate an Estimator object
estimator = Estimator()
# create a job for the quantum circuit implementing
# a parametrized quantum entangled pair,
# varying the elements in the list of
# theta angles defined before
job = estimator.run( [qc] * len(angles),
observables=[obsv] * len(angles),
parameter_values=angles )
# retrieve the expectation values
# from the results of the job ran by
# the Estimator created before,
# that was ran on the parametrized
# quantum entangled pair
exps = job.result().values
# plot the angles theta parametrized from the list built before
plt.plot( angles, exps, marker='x', ls='-', color="green" )
# plot the two classical bounds that violates the CHSH inequality
plt.plot( angles, [2]*len(angles), ls="--", color="red", label="Classical Bound" )
plt.plot( angles, [-2]*len(angles), ls="--", color="red" )
# add the X-axis label to the plot built before
plt.xlabel("angle (rad)")
# add the Y-axis label to the plot built before
plt.ylabel("CHSH Witness")
# add the title to the plot built before
plt.title("CHSH Witnesses\n")
# add the legend to the plot built before
plt.legend(loc=4)
# import the grader for the exercise 2 of the lab 2
from qc_grader.challenges.qgss_2023 import grade_lab2_ex2
# grade the exercise 2 of the lab 2
grade_lab2_ex2( obsv, angles )
# import the classical and quantum registers
# from the IBM's Qiksit circuit module
from qiskit.circuit import ClassicalRegister, QuantumRegister
# create a parameter for the theta angle
theta = Parameter("θ")
# create a quantum register for one qubit
# and to implement a parametrized quantum operation
qr = QuantumRegister(1, "q")
# create a quantum circuit with
# the quantum register created before
qc = QuantumCircuit(qr)
# apply a RY (Rotation-Y) gate to
# the quantum circuit, on the 1st qubit,
# with the theta angle defined before
qc.ry(theta, 0)
# draw the quantum circuit implementing
# a parametrized quantum operation
qc.draw("mpl")
# create a copy of the quantum circuit defined before
# to initialize the quantum circuit implementing
# a parametrized quantum teleportation
tele_qc = qc.copy()
# create a quantum register with two qubits
# for the Bell State to be shared on
# the parametrized quantum teleportation
bell = QuantumRegister(2, "Bell")
# create a classical register with two qubits
# for Alice's part on the parametrized
# quantum teleportation
alice = ClassicalRegister(2, "Alice")
# create a classical register with one qubit
# for Bob's part on the parametrized
# quantum teleportation
bob = ClassicalRegister(1, "Bob")
# add all the quantum and classical registers
# created before to the quantum circuit implementing
# a parametrized quantum teleportation
tele_qc.add_register(bell, alice, bob)
# draw the quantum circuit implementing
# the 1st step of a parametrized
# quantum teleportation
tele_qc.draw("mpl")
# add a barrier to the quantum circuit implementing
# a parametrized quantum teleportation
tele_qc.barrier()
# create Bell state with the other two qubits,
# in the quantum register defined before
# for that purpose
# apply a Hadamard gate to
# the quantum circuit, on the 2nd qubit
tele_qc.h(1)
# apply a CX/CNOT gate to
# the quantum circuit,
# with control on 2nd qubit
# and target on 3rd qubit
tele_qc.cx(1, 2)
# add a barrier to the quantum circuit implementing
# a parametrized quantum teleportation
tele_qc.barrier()
# draw the quantum circuit implementing
# the 2nd step of a parametrized
# quantum teleportation
tele_qc.draw("mpl")
# operations for Alice perform on her qubits
# during the parametrized quantum teleportation
# apply a CX/CNOT gate to
# the quantum circuit,
# with control on 1sr qubit
# and target on 2nd qubit
tele_qc.cx(0, 1)
# apply a Hadamard gate to
# the quantum circuit, on the 1st qubit
tele_qc.h(0)
# add a barrier to the quantum circuit implementing
# a parametrized quantum teleportation
tele_qc.barrier()
# draw the quantum circuit implementing
# the 3rd step of a parametrized
# quantum teleportation
tele_qc.draw("mpl")
# measurements performed by Alice on
# the qubit q and on her part of the Bell State,
# performing the entanglement swapping
tele_qc.measure( [ qr[0], bell[0] ], alice )
# draw the quantum circuit implementing
# the 4th step of a parametrized
# quantum teleportation
tele_qc.draw("mpl")
# create a copy of the quantum circuit defined before
# to initialize the quantum circuit implementing
# a parametrized quantum teleportation,
# and to be graded with dynamic operations
graded_qc = tele_qc.copy()
##############################
# add gates to graded_qc here
# Bob, who already has the qubit teleported,
# applies the following gates depending on
# the state of the classical bits:
# 00 -> Do nothing
# 01 -> Apply X gate
# 10 -> Apply Z gate
# 11 -> Apply ZX gate
# apply the Pauli-X (bit flip / not) gate on
# the 2nd qubit of the Bell state if
# the Alice's 2nd classical bit is 1
graded_qc.x( bell[1] ).c_if( alice[1], 1 )
# apply the Pauli-Z (phase flip) gate on
# the 2nd qubit of the Bell state if
# the Alice's 1st classical bit is 1
graded_qc.z( bell[1] ).c_if( alice[0], 1 )
##############################
# draw the quantum circuit implementing
# the parametrized quantum teleportation, to be graded
graded_qc.draw("mpl")
# add a barrier to the quantum circuit implementing
# a parametrized quantum teleportation, to be graded
graded_qc.barrier()
# measure the 2nd qubit of the Bell state to
# the Bob's classical register
graded_qc.measure( bell[1], bob )
# draw the quantum circuit implementing
# a parametrized quantum teleportation, to be graded
graded_qc.draw("mpl")
# import the grader for the exercise 3 of the lab 2
from qc_grader.challenges.qgss_2023 import grade_lab2_ex3
# grade the exercise 3 of the lab 2
grade_lab2_ex3( graded_qc, theta, 5 * ( np.pi / 7 ) )
# impor the Sampler from the IBM's Qiskit
# Aer primitives module
from qiskit_aer.primitives import Sampler
# define the pretended theta angle
angle = 5 * ( np.pi / 7 )
# create a Sampler object
sampler = Sampler()
# measure all the qubits on the quantum circuit
# implementing a parametrized quantum teleportation
qc.measure_all()
# create a job for the quantum circuit implementing
# a parametrized quantum teleportation,
# with a static quantum circuit and
# with the theta angle defined before
job_static = sampler.run( qc.bind_parameters({theta: angle}) )
# create a job for the quantum circuit implementing
# a parametrized quantum teleportation,
# with a dynamic quantum circuit and
# with the theta angle defined before
job_dynamic = sampler.run( graded_qc.bind_parameters({theta: angle}) )
# print the measurement distributions of the qubits from
# the parametrized quantum teleportation, with a static quantum circuit
print( f"Original Dists.: {job_static.result().quasi_dists[0].binary_probabilities()}" )
# print the measurement distributions of the qubits from
# the parametrized quantum teleportation, with a dynamic quantum circuit
print( f"Teleported Dists.: {job_dynamic.result().quasi_dists[0].binary_probabilities()}" )
# import the counts marginalization from
# the IBM's Qiskit result module
from qiskit.result import marginal_counts
# marginalize counts from the quasi-distributitions
# obtained from the parametrized quantum teleportation
tele_counts = marginal_counts( job_dynamic.result().quasi_dists[0]
.binary_probabilities(), [2] )
# create the legend for the two quantum states
# created before, namely the original quantum state to
# be teleported and the quantum state which was indeed teleported
legend = [ "Original State", "Teleported State" ]
# plot the histogram for the quasi-distributions
# for the two quantum states created before,
# namely the original quantum state to be teleported
# and the quantum state which was indeed teleported
plot_histogram( [ job_static.result().quasi_dists[0]
.binary_probabilities(), tele_counts ],
legend=legend, title="Measurement Results\n" )
# import the grader for the exercise 4 of the lab 2
from qc_grader.challenges.qgss_2023 import grade_lab2_ex4
# grade the exercise 4 of the lab 2
grade_lab2_ex4( tele_counts, job_dynamic.result() )
# 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/hritiksauw199/Optimized-Shor-Algorithm-for-factoring
|
hritiksauw199
|
import matplotlib.pyplot as plt
import numpy as np
from qiskit import QuantumCircuit, Aer, transpile, assemble
from qiskit.visualization import plot_histogram
from math import gcd
from numpy.random import randint
import pandas as pd
from fractions import Fraction
print("Imports Successful")
def c_amod15(a, power):
"""Controlled multiplication by a mod 15"""
if a not in [2,7,8,11,13]:
raise ValueError("'a' must be 2,7,8,11 or 13")
U = QuantumCircuit(4) p
for iteration in range(power):
if a in [2,13]:
U.swap(0,1)
U.swap(1,2)
U.swap(2,3)
if a in [7,8]:
U.swap(2,3)
U.swap(1,2)
U.swap(0,1)
if a == 11:
U.swap(1,3)
U.swap(0,2)
if a in [7,11,13]:
for q in range(4):
U.x(q)
U = U.to_gate()
U.name = "%i^%i mod 15" % (a, power)
c_U = U.control()
return c_U
def qft_dagger(n):
"""n-qubit QFTdagger the first n qubits in circ"""
qc = QuantumCircuit(n)
# Don't forget the Swaps!
for qubit in range(n//2):
qc.swap(qubit, n-qubit-1)
for j in range(n):
for m in range(j):
qc.cp(-np.pi/float(2**(j-m)), m, j)
qc.h(j)
qc.name = "QFT†"
return qc
# Specify variables
n_count = 8 # number of counting qubits
a = 7
# Create QuantumCircuit with n_count counting qubits
# plus 4 qubits for U to act on
qc = QuantumCircuit(n_count + 4, n_count)
# Initialize counting qubits
# in state |+>
for q in range(n_count):
qc.h(q)
# And auxiliary register in state |1>
qc.x(3+n_count)
# Do controlled-U operations
for q in range(n_count):
qc.append(c_amod15(a, 2**q), # second one is power of 2
[q] + [i+n_count for i in range(4)]) # i+n_count will be 0+8, 1+8, 2+8, 3+8 where n_count = 8
# Do inverse-QFT
qc.append(qft_dagger(n_count), range(n_count))
# Measure circuit
qc.measure(range(n_count), range(n_count))
qc.draw(fold=-1) # -1 means 'do not fold'
aer_sim = Aer.get_backend('aer_simulator')
t_qc = transpile(qc, aer_sim)
qobj = assemble(t_qc)
results = aer_sim.run(qobj).result()
counts = results.get_counts()
plot_histogram(counts)
rows, measured_phases = [], []
for output in counts:
decimal = int(output, 2) # Convert (base 2) string to decimal
phase = decimal/(2**n_count) # Find corresponding eigenvalue
measured_phases.append(phase)
# Add these values to the rows in our table:
rows.append([f"{output}(bin) = {decimal:>3}(dec)",
f"{decimal}/{2**n_count} = {phase:.2f}"])
# Print the rows in a table
headers=["Register Output", "Phase"]
df = pd.DataFrame(rows, columns=headers)
print(df)
rows = []
for phase in measured_phases:
frac = Fraction(phase).limit_denominator(15)
rows.append([phase, f"{frac.numerator}/{frac.denominator}", frac.denominator])
# Print as a table
headers=["Phase", "Fraction", "Guess for r"]
df = pd.DataFrame(rows, columns=headers)
print(df)
def qpe_amod15(a):
n_count = 8
qc = QuantumCircuit(4+n_count, n_count)
for q in range(n_count):
qc.h(q) # Initialize counting qubits in state |+>
qc.x(3+n_count) # And auxiliary register in state |1>
for q in range(n_count): # Do controlled-U operations
qc.append(c_amod15(a, 2**q),
[q] + [i+n_count for i in range(4)])
qc.append(qft_dagger(n_count), range(n_count)) # Do inverse-QFT
qc.measure(range(n_count), range(n_count))
# Simulate Results
aer_sim = Aer.get_backend('aer_simulator')
# Setting memory=True below allows us to see a list of each sequential reading
t_qc = transpile(qc, aer_sim)
qobj = assemble(t_qc, shots=1)
result = aer_sim.run(qobj, memory=True).result()
readings = result.get_memory()
print("Register Reading: " + readings[0])
phase = int(readings[0],2)/(2**n_count)
print("Corresponding Phase: %f" % phase)
return phase
N = 15
a = 7
factor_found = False
attempt = 0
while not factor_found:
attempt += 1
print("\nAttempt %i:" % attempt)
phase = qpe_amod15(a) # Phase = s/r
frac = Fraction(phase).limit_denominator(N) # Denominator should (hopefully!) tell us r
r = frac.denominator
print("Result: r = %i" % r)
if phase != 0:
# Guesses for factors are gcd(x^{r/2} ±1 , 15)
guesses = [gcd(a**(r//2)-1, N), gcd(a**(r//2)+1, N)]
print("Guessed Factors: %i and %i" % (guesses[0], guesses[1]))
for guess in guesses:
if guess not in [1,N] and (N % guess) == 0: # Check to see if guess is a factor
print("*** Non-trivial factor found: %i ***" % guess)
factor_found = True
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
# load necessary Runtime libraries
from qiskit_ibm_runtime import QiskitRuntimeService, Sampler, Session
backend = "ibmq_qasm_simulator" # use the simulator
from qiskit.circuit import Parameter
from qiskit.opflow import I, X, Z
mu = Parameter('$\\mu$')
ham_pauli = mu * X
cc = Parameter('$c$')
ww = Parameter('$\\omega$')
ham_res = -(1/2)*ww*(I^Z) + cc*(X^X) + (ham_pauli^I)
tt = Parameter('$t$')
U_ham = (tt*ham_res).exp_i()
from qiskit import transpile
from qiskit.circuit import ClassicalRegister
from qiskit.opflow import PauliTrotterEvolution, Suzuki
import numpy as np
num_trot_steps = 5
total_time = 10
cr = ClassicalRegister(1, 'c')
spec_op = PauliTrotterEvolution(trotter_mode=Suzuki(order=2, reps=num_trot_steps)).convert(U_ham)
spec_circ = spec_op.to_circuit()
spec_circ_t = transpile(spec_circ, basis_gates=['sx', 'rz', 'cx'])
spec_circ_t.add_register(cr)
spec_circ_t.measure(0, cr[0])
spec_circ_t.draw('mpl')
# fixed Parameters
fixed_params = {
cc: 0.3,
mu: 0.7,
tt: total_time
}
# Parameter value for single circuit
param_keys = list(spec_circ_t.parameters)
# run through all the ww values to create a List of Lists of Parameter value
num_pts = 101
wvals = np.linspace(-2, 2, num_pts)
param_vals = []
for wval in wvals:
all_params = {**fixed_params, **{ww: wval}}
param_vals.append([all_params[key] for key in param_keys])
with Session(backend=backend):
sampler = Sampler()
job = sampler.run(
circuits=[spec_circ_t]*num_pts,
parameter_values=param_vals,
shots=1e5
)
result = job.result()
Zexps = []
for dist in result.quasi_dists:
if 1 in dist:
Zexps.append(1 - 2*dist[1])
else:
Zexps.append(1)
from qiskit.opflow import PauliExpectation, Zero
param_bind = {
cc: 0.3,
mu: 0.7,
tt: total_time
}
init_state = Zero^2
obsv = I^Z
Zexp_exact = (U_ham @ init_state).adjoint() @ obsv @ (U_ham @ init_state)
diag_meas_op = PauliExpectation().convert(Zexp_exact)
Zexact_values = []
for w_set in wvals:
param_bind[ww] = w_set
Zexact_values.append(np.real(diag_meas_op.bind_parameters(param_bind).eval()))
import matplotlib.pyplot as plt
plt.style.use('dark_background')
fig, ax = plt.subplots(dpi=100)
ax.plot([-param_bind[mu], -param_bind[mu]], [0, 1], ls='--', color='purple')
ax.plot([param_bind[mu], param_bind[mu]], [0, 1], ls='--', color='purple')
ax.plot(wvals, Zexact_values, label='Exact')
ax.plot(wvals, Zexps, label=f"{backend}")
ax.set_xlabel(r'$\omega$ (arb)')
ax.set_ylabel(r'$\langle Z \rangle$ Expectation')
ax.legend()
import qiskit_ibm_runtime
qiskit_ibm_runtime.version.get_version_info()
from qiskit.tools.jupyter import *
%qiskit_version_table
|
https://github.com/108mk/Quantum_Algorithms_and_Qiskit
|
108mk
|
import qiskit
qiskit.__qiskit_version__
#initialization
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
# importing Qiskit
from qiskit import IBMQ, BasicAer
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute
from qiskit.compiler import transpile
from qiskit.tools.monitor import job_monitor
# import basic plot tools
from qiskit.tools.visualization import plot_histogram
# Load our saved IBMQ accounts.
IBMQ.load_account()
nQubits = 14 # number of physical qubits
a = 101 # the hidden integer whose bitstring is 1100101
# make sure that a can be represented with nQubits
a = a % 2**(nQubits)
# Creating registers
# qubits for querying the oracle and finding the hidden integer
qr = QuantumRegister(nQubits)
# for recording the measurement on qr
cr = ClassicalRegister(nQubits)
circuitName = "BernsteinVazirani"
bvCircuit = QuantumCircuit(qr, cr)
# Apply Hadamard gates before querying the oracle
for i in range(nQubits):
bvCircuit.h(qr[i])
# Apply barrier so that it is not optimized by the compiler
bvCircuit.barrier()
# Apply the inner-product oracle
for i in range(nQubits):
if (a & (1 << i)):
bvCircuit.z(qr[i])
else:
bvCircuit.iden(qr[i])
# Apply barrier
bvCircuit.barrier()
#Apply Hadamard gates after querying the oracle
for i in range(nQubits):
bvCircuit.h(qr[i])
# Measurement
bvCircuit.barrier(qr)
bvCircuit.measure(qr, cr)
bvCircuit.draw(output='mpl')
# use local simulator
backend = BasicAer.get_backend('qasm_simulator')
shots = 1000
results = execute(bvCircuit, backend=backend, shots=shots).result()
answer = results.get_counts()
plot_histogram(answer)
backend = IBMQ.get_backend('ibmq_16_melbourne')
shots = 1000
bvCompiled = transpile(bvCircuit, backend=backend, optimization_level=1)
job_exp = execute(bvCircuit, backend=backend, shots=shots)
job_monitor(job_exp)
results = job_exp.result()
answer = results.get_counts(bvCircuit)
threshold = int(0.01 * shots) #the threshold of plotting significant measurements
filteredAnswer = {k: v for k,v in answer.items() if v >= threshold} #filter the answer for better view of plots
removedCounts = np.sum([ v for k,v in answer.items() if v < threshold ]) #number of counts removed
filteredAnswer['other_bitstrings'] = removedCounts #the removed counts is assigned to a new index
plot_histogram(filteredAnswer)
print(filteredAnswer)
|
https://github.com/quantumyatra/quantum_computing
|
quantumyatra
|
import numpy as np
import pylab as plt
from qiskit import QuantumCircuit, execute, Aer, IBMQ
from qiskit.visualization import plot_histogram, plot_bloch_multivector
qpe = QuantumCircuit(4,3)
qpe.x(3)
qpe.draw('mpl')
#Apply Hadamard gate to all the quits
for q in range(3):
qpe.h(q)
qpe.draw('mpl')
repetitions = 1
for q in range(3):
for i in range(repetitions):
qpe.cu1(np.pi/4., q, 3) # controlled U gate : for T gate angle = pi/4
repetitions *= 2
qpe.draw('mpl')
from qiskit.circuit.library import QFT
def qft_dagger(qc, n):
"""n-qubit QFTdagger the first n qubits in the circuit qc"""
for q in range(n//2):
qc.swap(q, n-q-1)
for j in range(n):
for m in range(j):
qc.cu1(-np.pi/(float(2**(j-m))), m, j)
qc.h(j)
def qft_dagger2(qc, n):
"""n-qubit QFTdagger the first n qubits in the circuit qc"""
### WRITE YOUR CODE BETWEEN THESE LINES - START
gate = QFT(n, inverse=True, do_swaps=True )
qc.append(gate, range(n))
### WRITE YOUR CODE BETWEEN THESE LINES - END
# measure the counting register
qpe.barrier()
qft_dagger(qpe, 3)
qpe.barrier()
for n in range(3):
qpe.measure(n,n)
qpe.draw('mpl')
backend = Aer.get_backend('qasm_simulator')
shots = 2048
results = execute(qpe, backend=backend, shots=shots).result()
answer = results.get_counts()
plot_histogram(answer)
def bin2decimal(binary_str):
if '1' not in binary_str:
return 0
else:
binary = int(binary_str.lstrip('0'))
binary1 = binary
decimal, i = 0, 0
while(binary != 0):
dec = binary % 10
decimal = decimal + dec * pow(2, i)
binary = binary//10
i += 1
return decimal
bin2decimal('001010')
def QPE(N=3):
qc = QuantumCircuit(N+1, N)
qc.x(N)
#Apply Hadamard gate to all the quits
for q in range(N):
qc.h(q)
#Next we perform the controlled unitary operations
repetitions = 1
for q in range(N):
for i in range(repetitions):
qc.cu1(np.pi/4., q, N) # controlled U gate, angle is pi/4 for T gate
repetitions *=2
# measure the counting register
qc.barrier()
qft_dagger(qc, N)
qc.barrier()
for n in range(N):
qc.measure(n,n)
# execute the circuit
backend = Aer.get_backend('qasm_simulator')
Nshots = 2048
results = execute(qc, backend=backend, shots=Nshots).result()
counts = results.get_counts()
for binary in counts:
dec = bin2decimal(binary)
phase = dec/(2**N)
print ('binary:', binary,', decimal:', dec, 'Count ratio:', counts[binary]/Nshots)
print ('phase:', phase)
return counts
#print (counts)
counts = QPE(4)
print (counts)
plot_histogram(counts)
def getting_more_precision(N=3):
qc = QuantumCircuit(N+1, N)
# Prepare our eigenstate |psi>:
qc.x(N)
#Apply Hadamard gate to all the quits
for q in range(N):
qc.h(q)
#controlled-U operations
angle = 2*np.pi/3.
repetitions = 1
for q in range(N):
for i in range(repetitions):
qc.cu1(angle, q, N) # controlled U gate
repetitions *=2
# measure the counting register
qc.barrier()
qft_dagger(qc, N)
qc.barrier()
for n in range(N):
qc.measure(n,n)
# execute the circuit
backend = Aer.get_backend('qasm_simulator')
Nshots = 2048
results = execute(qc, backend=backend, shots=Nshots).result()
counts = results.get_counts()
return counts
def calcPhase(counts, Nqubit):
kL = list(counts.items())
vL = list(counts.values())
maxval1 = max(vL); (k1,v1) = kL[vL.index(maxval1)]; vL.remove(maxval1)
maxval2 = max(vL); (k2,v2) = kL[vL.index(maxval2)];
k1_dec = bin2decimal(k1)
k2_dec = bin2decimal(k2)
phase1 = k1_dec/(2**Nqubit)
phase2 = k2_dec/(2**Nqubit)
print ('the phase lies between [',phase1, ',', phase2, ']')
N=5
counts = getting_more_precision(N)
print (counts)
calcPhase(counts, N)
plot_histogram(counts)
#'11010': 1385
26/32
print ( 6/8, 4/8)
d = {'001': 60, '011': 1397, '010': 358}
list(d.keys())[0]
|
https://github.com/Bikramaditya0154/Quantum-Simulation-of-the-ground-states-of-Li-and-Li-2-using-Variational-Quantum-EIgensolver
|
Bikramaditya0154
|
from qiskit import Aer
from qiskit_nature.drivers import UnitsType, Molecule
from qiskit_nature.drivers.second_quantization import (
ElectronicStructureDriverType,
ElectronicStructureMoleculeDriver,
)
from qiskit_nature.problems.second_quantization import ElectronicStructureProblem
from qiskit_nature.converters.second_quantization import QubitConverter
from qiskit_nature.mappers.second_quantization import JordanWignerMapper
molecule = Molecule(
geometry=[["Li", [0.0, 0.0, 0.0]]], charge=1, multiplicity=1
)
driver = ElectronicStructureMoleculeDriver(
molecule, basis="sto3g", driver_type=ElectronicStructureDriverType.PYSCF
)
es_problem = ElectronicStructureProblem(driver)
qubit_converter = QubitConverter(JordanWignerMapper())
from qiskit.providers.aer import StatevectorSimulator
from qiskit import Aer
from qiskit.utils import QuantumInstance
from qiskit_nature.algorithms import VQEUCCFactory
quantum_instance = QuantumInstance(backend=Aer.get_backend("aer_simulator_statevector"))
vqe_solver = VQEUCCFactory(quantum_instance=quantum_instance)
from qiskit.algorithms import VQE
from qiskit.circuit.library import TwoLocal
tl_circuit = TwoLocal(
rotation_blocks=["h", "rx"],
entanglement_blocks="cz",
entanglement="full",
reps=2,
parameter_prefix="y",
)
another_solver = VQE(
ansatz=tl_circuit,
quantum_instance=QuantumInstance(Aer.get_backend("aer_simulator_statevector")),
)
from qiskit_nature.algorithms import GroundStateEigensolver
calc = GroundStateEigensolver(qubit_converter, vqe_solver)
res = calc.solve(es_problem)
print(res)
|
https://github.com/1chooo/Quantum-Oracle
|
1chooo
|
#Program 3.1a Apply X-gate to qubit
from qiskit import QuantumCircuit
qc = QuantumCircuit(2)
qc.x(1)
qc.draw('mpl')
#Program 3.1b Show Bloch sphere of qubit w/wo X-gate
from qiskit.quantum_info import Statevector
state = Statevector.from_instruction(qc)
state.draw('bloch')
#Program 3.2a Measure state of qubit w/o X-gate
from qiskit import QuantumCircuit,execute
from qiskit.providers.aer import AerSimulator
from qiskit.visualization import plot_histogram
import math
qc = QuantumCircuit(1,1)
qc.initialize([math.sqrt(1/3), math.sqrt(2/3)],0)
qc.measure([0],[0])
print(qc)
sim=AerSimulator()
job=execute(qc, backend=sim, shots=1000)
result=job.result()
counts=result.get_counts(qc)
print("Counts:",counts)
plot_histogram(counts)
#Program 3.2b Measure state of qubit w/ X-gate
from qiskit import QuantumCircuit,execute
from qiskit.providers.aer import AerSimulator
from qiskit.visualization import plot_histogram
import math
qc = QuantumCircuit(1,1)
qc.initialize([math.sqrt(1/3), math.sqrt(2/3)],0)
qc.x(0)
qc.measure([0],[0])
print(qc)
sim=AerSimulator()
job=execute(qc, backend=sim, shots=1000)
result=job.result()
counts=result.get_counts(qc)
print("Counts:",counts)
plot_histogram(counts)
#Program 3.3a Apply X-gate and H-gate to qubit
from qiskit import QuantumCircuit
import math
qc = QuantumCircuit(4)
qc.initialize([1/math.sqrt(2), 1/math.sqrt(2)],0)
qc.initialize([1/math.sqrt(2), -1/math.sqrt(2)],1)
qc.h(2)
qc.x(3)
qc.h(3)
qc.draw('mpl')
#Program 3.3b Show Bloch sphere of qubit w/ X-gate and H-gate
from qiskit.quantum_info import Statevector
state = Statevector.from_instruction(qc)
state.draw('bloch')
#Program 3.4 Measure state of qubit w/ H-gate
from qiskit import QuantumCircuit,execute
from qiskit.providers.aer import AerSimulator
from qiskit.visualization import plot_histogram
qc = QuantumCircuit(1,1)
qc.h(0)
qc.measure([0],[0])
print("This is |+>:")
print(qc)
sim=AerSimulator()
job=execute(qc, backend=sim, shots=1000)
result=job.result()
counts=result.get_counts(qc)
print("Counts:",counts)
plot_histogram(counts)
#Program 3.5 Measure state of qubit w/ X-gate and H-gate
from qiskit import QuantumCircuit,execute
from qiskit.providers.aer import AerSimulator
from qiskit.visualization import plot_histogram
qc = QuantumCircuit(1,1)
qc.x(0)
qc.h(0)
qc.measure([0],[0])
print("This is |->:")
print(qc)
sim=AerSimulator()
job=execute(qc, backend=sim, shots=1000)
result=job.result()
counts=result.get_counts(qc)
print("Counts:",counts)
plot_histogram(counts)
#Program 3.6 Measure state of qubit w/ H-gate
from qiskit import QuantumCircuit,execute
from qiskit.providers.aer import AerSimulator
from qiskit.visualization import plot_histogram
qc = QuantumCircuit(2,2)
qc.h(0)
qc.h(1)
qc.measure([0,1],[0,1])
print("This is |++>:")
print(qc)
sim=AerSimulator()
job=execute(qc, backend=sim, shots=1000)
result=job.result()
counts=result.get_counts(qc)
print("Counts:",counts)
plot_histogram(counts)
#Program 3.7a Apply X-, Y-, and Z-gate to qubit
from qiskit import QuantumCircuit
qc = QuantumCircuit(3)
qc.x(0)
qc.y(1)
qc.z(2)
qc.draw('mpl')
#Program 3.7b Show Bloch sphere of qubit w/ X-, Y-, and Z-gate
from qiskit.quantum_info import Statevector
state = Statevector.from_instruction(qc)
state.draw('bloch')
#Program 3.8a Apply RX-, RY-, and RZ-gate to qubit
from qiskit import QuantumCircuit
import math
qc = QuantumCircuit(3)
qc.rx(math.pi/2, 0)
qc.ry(math.pi/2, 1)
qc.rz(math.pi/2, 2)
qc.draw('mpl')
#Program 3.8b Show Bloch sphere of qubit w/ RX-, RY-, and RZ-gate
from qiskit.quantum_info import Statevector
state = Statevector.from_instruction(qc)
state.draw('bloch')
#Program 3.9a Apply RX-, P-, S-, T-gate to qubit
from qiskit import QuantumCircuit
import math
qc = QuantumCircuit(4)
qc.rx(math.pi/2, [0,1,2,3])
qc.p(math.pi/8, 1)
qc.s(2)
qc.t(3)
qc.draw('mpl')
#Program 3.9b Show Bloch sphere of qubit w/ RX-, P-, S-, and T-gate
from qiskit.quantum_info import Statevector
state = Statevector.from_instruction(qc)
state.draw('bloch')
#Program 3.10a Apply RX-, I-, and U-gate to qubit
from qiskit import QuantumCircuit
import math
qc = QuantumCircuit(4)
qc.rx(math.pi/2, [0,1,2,3])
qc.i(1)
qc.u(math.pi/2, 0, math.pi, 2)
qc.u(0,0, math.pi/4, 3)
qc.draw('mpl')
#Program 3.10b Show Bloch sphere of qubit w/ RX-, I-, and U-gate
from qiskit.quantum_info import Statevector
state = Statevector.from_instruction(qc)
state.draw('bloch')
|
https://github.com/magn5452/QiskitQaoa
|
magn5452
|
from qiskit import Aer
from qiskit.algorithms import QAOA
from qiskit.algorithms.optimizers import COBYLA
from qiskit.providers.aer import QasmSimulator, StatevectorSimulator
from VehicleRouting.framework.factory.QaoaMinimumEigenSolverFactory import QAOAMinimumEigenSolverFactory
class StandardQaoaMinimumEigenSolverFactory(QAOAMinimumEigenSolverFactory):
def create_qaoa(self):
precision = 12
classical_optimization_method = COBYLA()
#backend = StatevectorSimulator(precision='single')
backend = QasmSimulator()
return QAOA(optimizer=classical_optimization_method, reps=precision, quantum_instance=backend)
|
https://github.com/yh08037/quantum-neural-network
|
yh08037
|
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
import torch
from torch.autograd import Function
from torchvision import datasets, transforms
import torch.optim as optim
import torch.nn as nn
import torch.nn.functional as F
# from torchsummary import summary
import qiskit
from qiskit.visualization import *
from qiskit.circuit.random import random_circuit
from itertools import combinations
if torch.cuda.is_available():
DEVICE = torch.device('cuda')
else:
DEVICE = torch.device('cpu')
print('Using PyTorch version:', torch.__version__, ' Device:', DEVICE)
print('cuda index:', torch.cuda.current_device())
print('GPU 이름:', torch.cuda.get_device_name())
BATCH_SIZE = 256
EPOCHS = 10 # Number of optimization epochs
n_layers = 1 # Number of random layers
n_train = 50 # Size of the train dataset
n_test = 30 # Size of the test dataset
SAVE_PATH = "quanvolution/" # Data saving folder
PREPROCESS = True # If False, skip quantum processing and load data from SAVE_PATH
seed = 47
np.random.seed(seed) # Seed for NumPy random number generator
torch.manual_seed(seed) # Seed for TensorFlow random number generator
train_dataset = datasets.MNIST(root = "./data",
train = True,
download = True,
transform = transforms.ToTensor())
test_dataset = datasets.MNIST(root = "./data",
train = False,
transform = transforms.ToTensor())
train_loader = torch.utils.data.DataLoader(dataset = train_dataset,
batch_size = BATCH_SIZE,
shuffle = True)
test_loader = torch.utils.data.DataLoader(dataset = test_dataset,
batch_size = BATCH_SIZE,
shuffle = False)
for (X_train, y_train) in train_loader:
print('X_train:', X_train.size(), 'type:', X_train.type())
print('y_train:', y_train.size(), 'type:', y_train.type())
break
pltsize = 1
plt.figure(figsize=(10 * pltsize, pltsize))
for i in range(10):
plt.subplot(1, 10, i + 1)
plt.axis('off')
plt.imshow(X_train[i, :, :, :].numpy().reshape(28, 28), cmap = "gray_r")
plt.title('Class: ' + str(y_train[i].item()))
class QuanvCircuit:
"""
This class defines filter circuit of Quanvolution layer
"""
def __init__(self, kernel_size, backend, shots, threshold):
# --- Circuit definition start ---
self.n_qubits = kernel_size ** 2
self._circuit = qiskit.QuantumCircuit(self.n_qubits)
self.theta = [qiskit.circuit.Parameter('theta{}'.format(i)) for i in range(self.n_qubits)]
for i in range(self.n_qubits):
self._circuit.rx(self.theta[i], i)
self._circuit.barrier()
self._circuit += random_circuit(self.n_qubits, 2)
self._circuit.measure_all()
# ---- Circuit definition end ----
self.backend = backend
self.shots = shots
self.threshold = threshold
def run(self, data):
# data shape: tensor (1, 5, 5)
# val > self.threshold : |1> - rx(pi)
# val <= self.threshold : |0> - rx(0)
# reshape input data
# [1, kernel_size, kernel_size] -> [1, self.n_qubits]
data = torch.reshape(data, (1, self.n_qubits))
# encoding data to parameters
thetas = []
for dat in data:
theta = []
for val in dat:
if val > self.threshold:
theta.append(np.pi)
else:
theta.append(0)
thetas.append(theta)
param_dict = dict()
for theta in thetas:
for i in range(self.n_qubits):
param_dict[self.theta[i]] = theta[i]
param_binds = [param_dict]
# execute random quantum circuit
job = qiskit.execute(self._circuit,
self.backend,
shots = self.shots,
parameter_binds = param_binds)
result = job.result().get_counts(self._circuit)
# decoding the result
counts = 0
for key, val in result.items():
cnt = sum([int(char) for char in key])
counts += cnt * val
# Compute probabilities for each state
probabilities = counts / (self.shots * self.n_qubits)
# probabilities = counts / self.shots
return probabilities
backend = qiskit.Aer.get_backend('qasm_simulator')
filter_size = 2
circ = QuanvCircuit(filter_size, backend, 100, 127)
data = torch.tensor([[0, 200], [100, 255]])
print(data.size())
print(circ.run(data))
circ._circuit.draw(output='mpl')
# def quanv_feed(image):
# """
# Convolves the input image with many applications
# of the same quantum circuit.
# In the standard language of CNN, this would correspond to
# a convolution with a 5×5 kernel and a stride equal to 1.
# """
# out = np.zeros((24, 24, 25))
# # Loop over the coordinates of the top-left pixel of 5X5 squares
# for j in range(24):
# for k in range(24):
# # Process a squared 5x5 region of the image with a quantum circuit
# circuit_input = []
# for a in range(5):
# for b in range(5):
# circuit_input.append(image[j + a, k + b, 0])
# q_results = circuit(circuit_input)
# # Assign expectation values to different channels of the output pixel (j/2, k/2)
# for c in range(25):
# out[24, 24, c] = q_results[c]
# return out
class QuanvFunction(Function):
""" Quanv function definition """
@staticmethod
def forward(ctx, inputs, in_channels, out_channels, kernel_size, quantum_circuits, shift):
""" Forward pass computation """
# input shape : (-1, 1, 28, 28)
# otuput shape : (-1, 6, 24, 24)
ctx.in_channels = in_channels
ctx.out_channels = out_channels
ctx.kernel_size = kernel_size
ctx.quantum_circuits = quantum_circuits
ctx.shift = shift
_, _, len_x, len_y = inputs.size()
len_x = len_x - kernel_size + 1
len_y = len_y - kernel_size + 1
features = []
for input in inputs:
feature = []
for circuit in quantum_circuits:
xys = []
for x in range(len_x):
ys = []
for y in range(len_y):
data = input[0, x:x+kernel_size, y:y+kernel_size]
ys.append(circuit.run(data))
xys.append(ys)
feature.append(xys)
features.append(feature)
result = torch.tensor(features)
ctx.save_for_backward(inputs, result)
return result
@staticmethod
def backward(ctx, grad_output): # 확인 필요(검증 x)
""" Backward pass computation """
input, expectation_z = ctx.saved_tensors
input_list = np.array(input.tolist())
shift_right = input_list + np.ones(input_list.shape) * ctx.shift
shift_left = input_list - np.ones(input_list.shape) * ctx.shift
gradients = []
for i in range(len(input_list)):
expectation_right = ctx.quantum_circuit.run(shift_right[i])
expectation_left = ctx.quantum_circuit.run(shift_left[i])
gradient = torch.tensor([expectation_right]) - torch.tensor([expectation_left])
gradients.append(gradient)
gradients = np.array([gradients]).T
return torch.tensor([gradients]).float() * grad_output.float(), None, None
class Quanv(nn.Module):
""" Quanvolution(Quantum convolution) layer definition """
def __init__(self, in_channels, out_channels, kernel_size,
backend=qiskit.Aer.get_backend('qasm_simulator'),
shots=100, shift=np.pi/2):
super(Quanv, self).__init__()
self.quantum_circuits = [QuanvCircuit(kernel_size=kernel_size,
backend=backend, shots=shots, threshold=127)
for i in range(out_channels)]
self.in_channels = in_channels
self.out_channels = out_channels
self.kernel_size = kernel_size
self.shift = shift
def forward(self, inputs):
return QuanvFunction.apply(inputs, self.in_channels, self.out_channels, self.kernel_size,
self.quantum_circuits, self.shift)
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.quanv = Quanv(1, 6, kernel_size=5)
self.conv = nn.Conv2d(6, 16, kernel_size=5)
self.dropout = nn.Dropout2d()
self.fc1 = nn.Linear(256, 64)
self.fc2 = nn.Linear(64, 10)
def forward(self, x):
x = F.relu(self.quanv(x))
x = F.max_pool2d(x, 2)
x = F.relu(self.conv(x))
x = F.max_pool2d(x, 2)
x = self.dropout(x)
x = torch.flatten(x, start_dim=1)
x = F.relu(self.fc1(x))
x = self.fc2(x)
return F.softmax(x)
model = Net()
optimizer = optim.Adam(model.parameters(), lr=0.001)
loss_func = nn.CrossEntropyLoss()
epochs = 20
loss_list = []
model.train()
for epoch in range(epochs):
total_loss = []
for batch_idx, (data, target) in enumerate(train_loader):
optimizer.zero_grad()
# Forward pass
output = model(data)
# Calculating loss
loss = loss_func(output, target)
# Backward pass
loss.backward()
# Optimize the weights
optimizer.step()
total_loss.append(loss.item())
loss_list.append(sum(total_loss)/len(total_loss))
print('Training [{:.0f}%]\tLoss: {:.4f}'.format(
100. * (epoch + 1) / epochs, loss_list[-1]))
model.eval()
with torch.no_grad():
correct = 0
for batch_idx, (data, target) in enumerate(test_loader):
data = data.cuda()
target = target.cuda()
output = model(data).cuda()
pred = output.argmax(dim=1, keepdim=True)
correct += pred.eq(target.view_as(pred)).sum().item()
loss = loss_func(output, target)
total_loss.append(loss.item())
print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format(
sum(total_loss) / len(total_loss),
correct / len(test_loader) * 100 / batch_size)
)
|
https://github.com/ashishpatel26/IBM-Quantum-Challenge-Fall-2021
|
ashishpatel26
|
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/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
q = QuantumRegister(1)
c = ClassicalRegister(1)
qc = QuantumCircuit(q, c)
qc.h(q)
qc.measure(q, c)
qc.draw(output='mpl', style={'backgroundcolor': '#EEEEEE'})
|
https://github.com/PacktPublishing/Quantum-Computing-in-Practice-with-Qiskit-and-IBM-Quantum-Experience
|
PacktPublishing
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created Nov 2020
@author: hassi
"""
from qiskit import IBMQ, QuantumCircuit, execute
from qiskit.tools.monitor import job_monitor
from qiskit.visualization import plot_histogram
from IPython.core.display import display
print("Ch 5: Comparing backends")
print("------------------------")
print("Getting provider...")
if not IBMQ.active_account():
IBMQ.load_account()
provider = IBMQ.get_provider()
# Cceate a Bell circuit
qc = QuantumCircuit(2,2)
qc.h(0)
qc.cx(0,1)
qc.measure([0,1],[0,1])
print("\nQuantum circuit:")
print(qc)
# Get all available and operational backends.
backends = provider.backends(filters=lambda b: b.configuration().n_qubits > 1 and b.status().operational)
print("\nAvailable backends:", backends)
# Run the program on all backends and create a counts dictionary with the results from the executions.
counts = {}
for n in range(0, len(backends)):
print('Run on:', backends[n])
job = execute(qc, backends[n], shots=1000)
job_monitor(job)
result = job.result()
counts[backends[n].name()] = result.get_counts(qc)
#Display the data that we want to plot.
print("\nRaw results:", counts)
#Optionally define the histogram colors.
colors = ['green','darkgreen','red','darkred', 'orange','yellow','blue','darkblue','purple']
#Plot the counts dictionary values in a histogram, using the counts dictionary keys as legend.
display(plot_histogram(list(counts.values()), title = "Bell results on all available backends", legend=list(counts), color = colors[0:len(backends)], bar_labels = True))
|
https://github.com/cjsproject/qiskit_learning
|
cjsproject
|
%matplotlib inline
# 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 os import environ
# Grab env var
token = environ.get('ibmq_token')
# Loading your IBM Q account(s)
account = IBMQ.save_account(token, overwrite=True)
provider = IBMQ.load_account()
provider.backends()
from qiskit.providers.ibmq import least_busy
large_enough_devices = provider.backends(filters=lambda x: x.configuration().n_qubits > 3 and not x.configuration().simulator)
backend = least_busy(large_enough_devices)
print("The best backend is " + backend.name())
# quasm_sim not necessary
#simulator = Aer.get_backend('qasm_simulator')
from qiskit.tools.monitor import job_monitor
# circuit with 2 qubits, 2 cbits
circuit = QuantumCircuit(2, 2)
# hadamard on A
circuit.h(0)
# CNOT on B controlled by A
circuit.cx(0 , 1)
circuit.measure([0, 1], [0, 1])
job = execute(circuit, backend, shots=1000)
job_monitor(job)
results = job.result()
counts = results.get_counts(circuit)
print(f"total count for 0 and 1 are: {counts}")
circuit.draw()
plot_histogram(counts)
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
import numpy as np
import json
from qiskit import Aer
from qiskit_aqua import run_algorithm
from qiskit_aqua.input import EnergyInput
from qiskit_aqua.translators.ising import exactcover
from qiskit_aqua.algorithms import ExactEigensolver
input_file = 'sample.exactcover'
with open(input_file) as f:
list_of_subsets = json.load(f)
print(list_of_subsets)
qubitOp, offset = exactcover.get_exactcover_qubitops(list_of_subsets)
algo_input = EnergyInput(qubitOp)
def brute_force():
# brute-force way: try every possible assignment!
has_sol = False
def bitfield(n, L):
result = np.binary_repr(n, L)
return [int(digit) for digit in result] # [2:] to chop off the "0b" part
L = len(list_of_subsets)
max = 2**L
for i in range(max):
cur = bitfield(i, L)
cur_v = exactcover.check_solution_satisfiability(cur, list_of_subsets)
if cur_v:
has_sol = True
break
return has_sol, cur
has_sol, cur = brute_force()
if has_sol:
print("solution is", cur)
else:
print("no solution is found")
params = {
'problem': {'name': 'ising'},
'algorithm': {'name': 'ExactEigensolver'}
}
result = run_algorithm(params, algo_input)
x = exactcover.sample_most_likely(len(list_of_subsets), result['eigvecs'][0])
ising_sol = exactcover.get_solution(x)
np.testing.assert_array_equal(ising_sol, [0, 1, 1, 0])
if exactcover.check_solution_satisfiability(ising_sol, list_of_subsets):
print("solution is", ising_sol)
else:
print("no solution is found")
algo = ExactEigensolver(algo_input.qubit_op, k=1, aux_operators=[])
result = algo.run()
x = exactcover.sample_most_likely(len(list_of_subsets), result['eigvecs'][0])
ising_sol = exactcover.get_solution(x)
np.testing.assert_array_equal(ising_sol, [0, 1, 1, 0])
if exactcover.check_solution_satisfiability(ising_sol, list_of_subsets):
print("solution is", ising_sol)
else:
print("no solution is found")
algorithm_cfg = {
'name': 'VQE',
'operator_mode': 'matrix'
}
optimizer_cfg = {
'name': 'COBYLA'
}
var_form_cfg = {
'name': 'RYRZ',
'depth': 5
}
params = {
'problem': {'name': 'ising', 'random_seed': 10598},
'algorithm': algorithm_cfg,
'optimizer': optimizer_cfg,
'variational_form': var_form_cfg
}
backend = Aer.get_backend('statevector_simulator')
result = run_algorithm(params, algo_input, backend=backend)
x = exactcover.sample_most_likely(len(list_of_subsets), result['eigvecs'][0])
ising_sol = exactcover.get_solution(x)
if exactcover.check_solution_satisfiability(ising_sol, list_of_subsets):
print("solution is", ising_sol)
else:
print("no solution is found")
|
https://github.com/qiskit-community/qiskit-jku-provider
|
qiskit-community
|
# -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
# pylint: disable=unused-import
# pylint: disable=redefined-builtin
"""Test Qiskit's QuantumCircuit class for multiple registers."""
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit import execute
from qiskit.quantum_info import state_fidelity, basis_state
from qiskit.test import QiskitTestCase
from qiskit_jku_provider import QasmSimulator
class TestCircuitMultiRegs(QiskitTestCase):
"""QuantumCircuit Qasm tests."""
def test_circuit_multi(self):
"""Test circuit multi regs declared at start.
"""
qreg0 = QuantumRegister(2, 'q0')
creg0 = ClassicalRegister(2, 'c0')
qreg1 = QuantumRegister(2, 'q1')
creg1 = ClassicalRegister(2, 'c1')
circ = QuantumCircuit(qreg0, qreg1)
circ.x(qreg0[1])
circ.x(qreg1[0])
meas = QuantumCircuit(qreg0, qreg1, creg0, creg1)
meas.measure(qreg0, creg0)
meas.measure(qreg1, creg1)
qc = circ + meas
backend_sim = QasmSimulator(silent=True)
result = execute(qc, backend_sim, seed_transpiler=34342).result()
counts = result.get_counts(qc)
target = {'01 10': 1024}
result = execute(circ, backend_sim, seed_transpiler=3438).result()
state = result.get_statevector(circ)
self.assertEqual(counts, target)
self.assertAlmostEqual(state_fidelity(basis_state('0110', 4), state), 1.0, places=7)
|
https://github.com/qiskit-community/qiskit-qcgpu-provider
|
qiskit-community
|
from qiskit_aqua import run_algorithm
from qiskit_qcgpu_provider import QCGPUProvider
sat_cnf = """
c Example DIMACS 3-sat
p cnf 3 5
-1 -2 -3 0
1 -2 3 0
1 2 -3 0
1 -2 -3 0
-1 2 3 0
"""
params = {
"problem": { "name": "search" },
"algorithm": { "name": "Grover" },
"oracle": { "name": "SAT", "cnf": sat_cnf },
"backend": { "name": "qasm_simulator" }
}
backend = QCGPUProvider().get_backend('qasm_simulator')
%time result_qiskit = run_algorithm(params)
%time result = run_algorithm(params, backend=backend)
print(result["result"])
|
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/swe-train/qiskit__qiskit
|
swe-train
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2022, 2023.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Tests for Sampler."""
import unittest
import numpy as np
from qiskit import QuantumCircuit
from qiskit.circuit import Parameter
from qiskit.circuit.library import RealAmplitudes
from qiskit.exceptions import QiskitError
from qiskit.extensions.unitary import UnitaryGate
from qiskit.primitives import Sampler, SamplerResult
from qiskit.providers import JobStatus, JobV1
from qiskit.test import QiskitTestCase
class TestSampler(QiskitTestCase):
"""Test Sampler"""
def setUp(self):
super().setUp()
hadamard = QuantumCircuit(1, 1, name="Hadamard")
hadamard.h(0)
hadamard.measure(0, 0)
bell = QuantumCircuit(2, name="Bell")
bell.h(0)
bell.cx(0, 1)
bell.measure_all()
self._circuit = [hadamard, bell]
self._target = [
{0: 0.5, 1: 0.5},
{0: 0.5, 3: 0.5, 1: 0, 2: 0},
]
self._pqc = RealAmplitudes(num_qubits=2, reps=2)
self._pqc.measure_all()
self._pqc2 = RealAmplitudes(num_qubits=2, reps=3)
self._pqc2.measure_all()
self._pqc_params = [[0.0] * 6, [1.0] * 6]
self._pqc_target = [{0: 1}, {0: 0.0148, 1: 0.3449, 2: 0.0531, 3: 0.5872}]
self._theta = [
[0, 1, 1, 2, 3, 5],
[1, 2, 3, 4, 5, 6],
[0, 1, 2, 3, 4, 5, 6, 7],
]
def _generate_circuits_target(self, indices):
if isinstance(indices, list):
circuits = [self._circuit[j] for j in indices]
target = [self._target[j] for j in indices]
else:
raise ValueError(f"invalid index {indices}")
return circuits, target
def _generate_params_target(self, indices):
if isinstance(indices, int):
params = self._pqc_params[indices]
target = self._pqc_target[indices]
elif isinstance(indices, list):
params = [self._pqc_params[j] for j in indices]
target = [self._pqc_target[j] for j in indices]
else:
raise ValueError(f"invalid index {indices}")
return params, target
def _compare_probs(self, prob, target):
if not isinstance(prob, list):
prob = [prob]
if not isinstance(target, list):
target = [target]
self.assertEqual(len(prob), len(target))
for p, targ in zip(prob, target):
for key, t_val in targ.items():
if key in p:
self.assertAlmostEqual(p[key], t_val, places=1)
else:
self.assertAlmostEqual(t_val, 0, places=1)
def test_sampler_run(self):
"""Test Sampler.run()."""
bell = self._circuit[1]
sampler = Sampler()
job = sampler.run(circuits=[bell])
self.assertIsInstance(job, JobV1)
result = job.result()
self.assertIsInstance(result, SamplerResult)
# print([q.binary_probabilities() for q in result.quasi_dists])
self._compare_probs(result.quasi_dists, self._target[1])
def test_sample_run_multiple_circuits(self):
"""Test Sampler.run() with multiple circuits."""
# executes three Bell circuits
# Argument `parameters` is optional.
bell = self._circuit[1]
sampler = Sampler()
result = sampler.run([bell, bell, bell]).result()
# print([q.binary_probabilities() for q in result.quasi_dists])
self._compare_probs(result.quasi_dists[0], self._target[1])
self._compare_probs(result.quasi_dists[1], self._target[1])
self._compare_probs(result.quasi_dists[2], self._target[1])
def test_sampler_run_with_parameterized_circuits(self):
"""Test Sampler.run() with parameterized circuits."""
# parameterized circuit
pqc = self._pqc
pqc2 = self._pqc2
theta1, theta2, theta3 = self._theta
sampler = Sampler()
result = sampler.run([pqc, pqc, pqc2], [theta1, theta2, theta3]).result()
# result of pqc(theta1)
prob1 = {
"00": 0.1309248462975777,
"01": 0.3608720796028448,
"10": 0.09324865232050054,
"11": 0.41495442177907715,
}
self.assertDictAlmostEqual(result.quasi_dists[0].binary_probabilities(), prob1)
# result of pqc(theta2)
prob2 = {
"00": 0.06282290651933871,
"01": 0.02877144385576705,
"10": 0.606654494132085,
"11": 0.3017511554928094,
}
self.assertDictAlmostEqual(result.quasi_dists[1].binary_probabilities(), prob2)
# result of pqc2(theta3)
prob3 = {
"00": 0.1880263994380416,
"01": 0.6881971261189544,
"10": 0.09326232720582443,
"11": 0.030514147237179892,
}
self.assertDictAlmostEqual(result.quasi_dists[2].binary_probabilities(), prob3)
def test_run_1qubit(self):
"""test for 1-qubit cases"""
qc = QuantumCircuit(1)
qc.measure_all()
qc2 = QuantumCircuit(1)
qc2.x(0)
qc2.measure_all()
sampler = Sampler()
result = sampler.run([qc, qc2]).result()
self.assertIsInstance(result, SamplerResult)
self.assertEqual(len(result.quasi_dists), 2)
for i in range(2):
keys, values = zip(*sorted(result.quasi_dists[i].items()))
self.assertTupleEqual(keys, (i,))
np.testing.assert_allclose(values, [1])
def test_run_2qubit(self):
"""test for 2-qubit cases"""
qc0 = QuantumCircuit(2)
qc0.measure_all()
qc1 = QuantumCircuit(2)
qc1.x(0)
qc1.measure_all()
qc2 = QuantumCircuit(2)
qc2.x(1)
qc2.measure_all()
qc3 = QuantumCircuit(2)
qc3.x([0, 1])
qc3.measure_all()
sampler = Sampler()
result = sampler.run([qc0, qc1, qc2, qc3]).result()
self.assertIsInstance(result, SamplerResult)
self.assertEqual(len(result.quasi_dists), 4)
for i in range(4):
keys, values = zip(*sorted(result.quasi_dists[i].items()))
self.assertTupleEqual(keys, (i,))
np.testing.assert_allclose(values, [1])
def test_run_single_circuit(self):
"""Test for single circuit case."""
sampler = Sampler()
with self.subTest("No parameter"):
circuit = self._circuit[1]
target = self._target[1]
param_vals = [None, [], [[]], np.array([]), np.array([[]])]
for val in param_vals:
with self.subTest(f"{circuit.name} w/ {val}"):
result = sampler.run(circuit, val).result()
self._compare_probs(result.quasi_dists, target)
self.assertEqual(len(result.metadata), 1)
with self.subTest("One parameter"):
circuit = QuantumCircuit(1, 1, name="X gate")
param = Parameter("x")
circuit.ry(param, 0)
circuit.measure(0, 0)
target = [{1: 1}]
param_vals = [
[np.pi],
[[np.pi]],
np.array([np.pi]),
np.array([[np.pi]]),
[np.array([np.pi])],
]
for val in param_vals:
with self.subTest(f"{circuit.name} w/ {val}"):
result = sampler.run(circuit, val).result()
self._compare_probs(result.quasi_dists, target)
self.assertEqual(len(result.metadata), 1)
with self.subTest("More than one parameter"):
circuit = self._pqc
target = [self._pqc_target[0]]
param_vals = [
self._pqc_params[0],
[self._pqc_params[0]],
np.array(self._pqc_params[0]),
np.array([self._pqc_params[0]]),
[np.array(self._pqc_params[0])],
]
for val in param_vals:
with self.subTest(f"{circuit.name} w/ {val}"):
result = sampler.run(circuit, val).result()
self._compare_probs(result.quasi_dists, target)
self.assertEqual(len(result.metadata), 1)
def test_run_reverse_meas_order(self):
"""test for sampler with reverse measurement order"""
x = Parameter("x")
y = Parameter("y")
qc = QuantumCircuit(3, 3)
qc.rx(x, 0)
qc.rx(y, 1)
qc.x(2)
qc.measure(0, 2)
qc.measure(1, 1)
qc.measure(2, 0)
sampler = Sampler()
result = sampler.run([qc] * 2, [[0, 0], [np.pi / 2, 0]]).result()
self.assertIsInstance(result, SamplerResult)
self.assertEqual(len(result.quasi_dists), 2)
# qc({x: 0, y: 0})
keys, values = zip(*sorted(result.quasi_dists[0].items()))
self.assertTupleEqual(keys, (1,))
np.testing.assert_allclose(values, [1])
# qc({x: pi/2, y: 0})
keys, values = zip(*sorted(result.quasi_dists[1].items()))
self.assertTupleEqual(keys, (1, 5))
np.testing.assert_allclose(values, [0.5, 0.5])
def test_run_errors(self):
"""Test for errors with run method"""
qc1 = QuantumCircuit(1)
qc1.measure_all()
qc2 = RealAmplitudes(num_qubits=1, reps=1)
qc2.measure_all()
qc3 = QuantumCircuit(1)
qc4 = QuantumCircuit(1, 1)
sampler = Sampler()
with self.subTest("set parameter values to a non-parameterized circuit"):
with self.assertRaises(ValueError):
_ = sampler.run([qc1], [[1e2]])
with self.subTest("missing all parameter values for a parameterized circuit"):
with self.assertRaises(ValueError):
_ = sampler.run([qc2], [[]])
with self.subTest("missing some parameter values for a parameterized circuit"):
with self.assertRaises(ValueError):
_ = sampler.run([qc2], [[1e2]])
with self.subTest("too many parameter values for a parameterized circuit"):
with self.assertRaises(ValueError):
_ = sampler.run([qc2], [[1e2]] * 100)
with self.subTest("no classical bits"):
with self.assertRaises(ValueError):
_ = sampler.run([qc3], [[]])
with self.subTest("no measurement"):
with self.assertRaises(QiskitError):
# The following raises QiskitError because this check is located in
# `Sampler._preprocess_circuit`
_ = sampler.run([qc4], [[]])
def test_run_empty_parameter(self):
"""Test for empty parameter"""
n = 5
qc = QuantumCircuit(n, n - 1)
qc.measure(range(n - 1), range(n - 1))
sampler = Sampler()
with self.subTest("one circuit"):
result = sampler.run([qc], shots=1000).result()
self.assertEqual(len(result.quasi_dists), 1)
for q_d in result.quasi_dists:
quasi_dist = {k: v for k, v in q_d.items() if v != 0.0}
self.assertDictEqual(quasi_dist, {0: 1.0})
self.assertEqual(len(result.metadata), 1)
with self.subTest("two circuits"):
result = sampler.run([qc, qc], shots=1000).result()
self.assertEqual(len(result.quasi_dists), 2)
for q_d in result.quasi_dists:
quasi_dist = {k: v for k, v in q_d.items() if v != 0.0}
self.assertDictEqual(quasi_dist, {0: 1.0})
self.assertEqual(len(result.metadata), 2)
def test_run_numpy_params(self):
"""Test for numpy array as parameter values"""
qc = RealAmplitudes(num_qubits=2, reps=2)
qc.measure_all()
k = 5
params_array = np.random.rand(k, qc.num_parameters)
params_list = params_array.tolist()
params_list_array = list(params_array)
sampler = Sampler()
target = sampler.run([qc] * k, params_list).result()
with self.subTest("ndarrary"):
result = sampler.run([qc] * k, params_array).result()
self.assertEqual(len(result.metadata), k)
for i in range(k):
self.assertDictEqual(result.quasi_dists[i], target.quasi_dists[i])
with self.subTest("list of ndarray"):
result = sampler.run([qc] * k, params_list_array).result()
self.assertEqual(len(result.metadata), k)
for i in range(k):
self.assertDictEqual(result.quasi_dists[i], target.quasi_dists[i])
def test_run_with_shots_option(self):
"""test with shots option."""
params, target = self._generate_params_target([1])
sampler = Sampler()
result = sampler.run(
circuits=[self._pqc], parameter_values=params, shots=1024, seed=15
).result()
self._compare_probs(result.quasi_dists, target)
def test_run_with_shots_option_none(self):
"""test with shots=None option. Seed is ignored then."""
sampler = Sampler()
result_42 = sampler.run(
[self._pqc], parameter_values=[[0, 1, 1, 2, 3, 5]], shots=None, seed=42
).result()
result_15 = sampler.run(
[self._pqc], parameter_values=[[0, 1, 1, 2, 3, 5]], shots=None, seed=15
).result()
self.assertDictAlmostEqual(result_42.quasi_dists, result_15.quasi_dists)
def test_run_shots_result_size(self):
"""test with shots option to validate the result size"""
n = 10
shots = 100
qc = QuantumCircuit(n)
qc.h(range(n))
qc.measure_all()
sampler = Sampler()
result = sampler.run(qc, [], shots=shots, seed=42).result()
self.assertEqual(len(result.quasi_dists), 1)
self.assertLessEqual(len(result.quasi_dists[0]), shots)
self.assertAlmostEqual(sum(result.quasi_dists[0].values()), 1.0)
def test_primitive_job_status_done(self):
"""test primitive job's status"""
bell = self._circuit[1]
sampler = Sampler()
job = sampler.run(circuits=[bell])
_ = job.result()
self.assertEqual(job.status(), JobStatus.DONE)
def test_options(self):
"""Test for options"""
with self.subTest("init"):
sampler = Sampler(options={"shots": 3000})
self.assertEqual(sampler.options.get("shots"), 3000)
with self.subTest("set_options"):
sampler.set_options(shots=1024, seed=15)
self.assertEqual(sampler.options.get("shots"), 1024)
self.assertEqual(sampler.options.get("seed"), 15)
with self.subTest("run"):
params, target = self._generate_params_target([1])
result = sampler.run([self._pqc], parameter_values=params).result()
self._compare_probs(result.quasi_dists, target)
self.assertEqual(result.quasi_dists[0].shots, 1024)
def test_circuit_with_unitary(self):
"""Test for circuit with unitary gate."""
gate = UnitaryGate(np.eye(2))
circuit = QuantumCircuit(1)
circuit.append(gate, [0])
circuit.measure_all()
sampler = Sampler()
sampler_result = sampler.run([circuit]).result()
self.assertDictAlmostEqual(sampler_result.quasi_dists[0], {0: 1, 1: 0})
if __name__ == "__main__":
unittest.main()
|
https://github.com/acfilok96/Quantum-Computation
|
acfilok96
|
import qiskit
from qiskit import *
print(qiskit.__version__)
%matplotlib inline
from qiskit.tools.visualization import plot_histogram
from qiskit.providers.aer import QasmSimulator
# use Aer's qasm_simulator
simulator = QasmSimulator()
# create quantum circute acting on the q register
circuit = QuantumCircuit(2,2)
# add a H gate on qubit 0
circuit.h(0)
# add a cx (CNOT) gate on control qubit 0 and target qubit 1
circuit.cx(0,1)
# map the quantum measurement to the classical bits
circuit.measure([0,1],[0,1])
# compile the circuit down to low-level QASM instructions
# supported by the backend (not needed for simple circuits)
compiled_circuit = transpile(circuit, simulator)
# execute the circuit on the qasm simulator
job = simulator.run(compiled_circuit, shots=1024)
# grad results from the job
result = job.result()
# return counts
counts = result.get_counts(compiled_circuit)
print('total count for 00 and 11 are: ',counts)
# draw circuit
circuit.draw(output='mpl')
# plot histogram
plot_histogram(counts)
from qiskit.circuit import QuantumCircuit, Parameter
from qiskit.providers.aer import AerSimulator
backend = AerSimulator()
circuit = QuantumCircuit(2)
theta = Parameter('theta')
circuit.rx(234, 0)
circuit.draw(output='mpl')
backend = AerSimulator()
circuit = QuantumCircuit(2)
# theta = Parameter('theta')
circuit.rx(20, 0)
circuit.x(0)
circuit.h(1)
result = execute(circuit, backend=backend, shots=1024).result()
# counts=result.get_counts()
# print(counts)
circuit.draw(output='mpl')
|
https://github.com/minnukota381/Quantum-Computing-Qiskit
|
minnukota381
|
from qiskit import *
from qiskit.visualization import plot_bloch_multivector, visualize_transition, plot_histogram
# Create a quantum circuit with 2 qubits
# The default initial state of qubits will be |0> or [1,0]
B2 = QuantumCircuit(2)
B2.x(0)
B2.h(0)
B2.x(1)
B2.cx(0,1)
B2.draw('mpl')
#Get the backend for the circuit to display unitary matrix
backend = Aer.get_backend('unitary_simulator')
#execute the circuit using the backend
out = execute(B2,backend).result().get_unitary()
#import qiskit_textbook and display the combined unitary matrix
from qiskit_textbook.tools import array_to_latex
array_to_latex(out, pretext = "\\text{UnitaryMatrix} = ")
#Get the backend for the circuit (simulator or realtime system)
backend = Aer.get_backend('statevector_simulator')
#execute the circuit using the backend
out = execute(B2,backend).result().get_statevector()
#import qiskit_textbook and display the statevector
#from qiskit_textbook.tools import array_to_latex
array_to_latex(out, pretext = "\\text{Statevector} = ")
#plot the result as a bloch sphere visualization
plot_bloch_multivector(out)
#execute the circuit and get the plain result
out = execute(B2,backend).result()
#getting the count of the result
counts = out.get_counts()
#plotting the histogram
plot_histogram(counts)
|
https://github.com/Pitt-JonesLab/slam_decomposition
|
Pitt-JonesLab
|
# Follow this tutorial
# https://qucontrol.github.io/krotov/v1.2.1/notebooks/07_example_PE.html#Optimization
# 1. we aren't considering virtual z-gates, we could use state-to-state functional but was getting errors
# 2. simulated annealing learning rate?
# 3. not every 1Q variance has a solution, find subset that do, particular for CX and SWAP decomp targets
# 4. we see that when the solution is 1Q gates are off, the optimizer still struggles to find that solution with high fidelity
# 5. getting errors when turning on local variance in objective function
# 6. !!!! we think cnot with phase =0 doesn't change its coordinate - maybe it works with smushing?
import logging
logger = logging.getLogger()
logger.setLevel(logging.ERROR)
%matplotlib widget
import numpy as np
import qutip
import numpy as np
import scipy
import matplotlib
import matplotlib.pylab as plt
import krotov
from IPython.display import display
import weylchamber as wc
from weylchamber.visualize import WeylChamber
from weylchamber.coordinates import from_magic
gc, gg = (np.pi / 2, 0 * np.pi / 4)
T = 1.0 # final time
nt = 100
u0 = 2 * np.pi
tlist = np.linspace(0, T, nt)
def eps0(t, args):
return u0 * krotov.shapes.flattop(
t, t_start=0, t_stop=T, t_rise=(T / 20), t_fall=(T / 20), func="sinsq"
)
def eps1(t, args):
return u0 * krotov.shapes.flattop(
t, t_start=0, t_stop=T, t_rise=(T / 20), t_fall=(T / 20), func="sinsq"
)
def plot_pulse(pulse, tlist):
fig, ax = plt.subplots()
if callable(pulse):
pulse = np.array([pulse(t, args=None) for t in tlist])
ax.plot(tlist, pulse)
ax.set_xlabel("time")
ax.set_ylabel("pulse amplitude")
plt.show(fig)
def hamiltonian(phi_c, phi_g, gc, gg, gx0, gy0):
"""Two qubit Hamiltonian"""
a = qutip.operators.create(N=2)
I2 = qutip.operators.identity(2)
A = qutip.tensor(a, I2)
B = qutip.tensor(I2, a)
# # local qubit Hamiltonians
# Hq1 = 0.5 * w1 * np.diag([-1, 1])
# Hq2 = 0.5 * w2 * np.diag([-1, 1])
# # lift Hamiltonians to joint system operators
# H0 = np.kron(Hq1, np.identity(2)) + np.kron(np.identity(2), Hq2)
# construct Hamiltonian
Ha = A + A.dag()
Hb = B + B.dag()
H_c = np.exp(1j * phi_c) * A * B.dag() + np.exp(-1j * phi_c) * A.dag() * B
H_g = np.exp(1j * phi_g) * A * B + np.exp(-1j * phi_g) * A.dag() * B.dag()
H1 = gc * H_c + gg * H_g
# convert Hamiltonians to QuTiP objects
# H0 = qutip.Qobj(H0)
H1 = qutip.Qobj(H1)
Ha = qutip.Qobj(Ha)
Hb = qutip.Qobj(Hb)
# H1 = qutip.Qobj(H1)
# H2 = qutip.Qobj(H2)
# return [H0, [H1, eps0]]
# reshaping from [[2],[2]] to [4,4]
H1 = qutip.Qobj(H1.data, dims=[[4], [4]])
Ha = qutip.Qobj(Ha.data, dims=[[4], [4]])
Hb = qutip.Qobj(Hb.data, dims=[[4], [4]])
return [H1, [Ha, eps0], [Hb, eps1]] # renamed to eps1 to avoid dictionary key clash
H = hamiltonian(phi_c=0, phi_g=0, gc=gc, gg=gg, gx0=0, gy0=0)
# H = qutip.Qobj(H[0].data,dims=[[4],[4]])
# def hamiltonian(w1=w1, w2=w2, J=J, la=la, u0=u0):
# """Two qubit Hamiltonian
# Args:
# w1 (float): energy separation of the first qubit levels
# w2 (float): energy separation of the second qubit levels
# J (float): effective coupling between both qubits
# la (float): factor that pulse coupling strength differs for second qubit
# u0 (float): constant amplitude of the driving field
# """
# # local qubit Hamiltonians
# Hq1 = 0.5 * w1 * np.diag([-1, 1])
# Hq2 = 0.5 * w2 * np.diag([-1, 1])
# # lift Hamiltonians to joint system operators
# H0 = np.kron(Hq1, np.identity(2)) + np.kron(np.identity(2), Hq2)
# # define the interaction Hamiltonian
# sig_x = np.array([[0, 1], [1, 0]])
# sig_y = np.array([[0, -1j], [1j, 0]])
# Hint = 2 * J * (np.kron(sig_x, sig_x) + np.kron(sig_y, sig_y))
# H0 = H0 + Hint
# # define the drive Hamiltonian
# H1 = np.kron(np.array([[0, 1], [1, 0]]), np.identity(2)) + la * np.kron(
# np.identity(2), np.array([[0, 1], [1, 0]])
# )
# # convert Hamiltonians to QuTiP objects
# H0 = qutip.Qobj(H0)
# H1 = qutip.Qobj(H1)
# return [H0, [H1, eps0]]
# H = hamiltonian(w1=w1, w2=w2, J=J, la=la, u0=u0)
psi_00 = qutip.Qobj(np.kron(np.array([1, 0]), np.array([1, 0])))
psi_01 = qutip.Qobj(np.kron(np.array([1, 0]), np.array([0, 1])))
psi_10 = qutip.Qobj(np.kron(np.array([0, 1]), np.array([1, 0])))
psi_11 = qutip.Qobj(np.kron(np.array([0, 1]), np.array([0, 1])))
basis_states = [psi_00, psi_01, psi_10, psi_11]
proj_00 = qutip.ket2dm(psi_00)
proj_01 = qutip.ket2dm(psi_01)
proj_10 = qutip.ket2dm(psi_10)
proj_11 = qutip.ket2dm(psi_11)
from qiskit import QuantumCircuit
from slam.utils.gates.custom_gates import (
ConversionGainGate,
CanonicalGate,
BerkeleyGate,
)
from qiskit.quantum_info import Operator, random_unitary
from qiskit.extensions import UnitaryGate
from qiskit.circuit.library import SwapGate, CPhaseGate
# from slam.sampler import GateSample
# qc = QuantumCircuit(2)
# # qc.append(random_unitary(2), [0])
# # qc.append(random_unitary(2), [1])
# g = ConversionGainGate(0, 0, gc, gg, t_el=1.0)
# qc.append(g, [0,1])
# qc.append(random_unitary(2), [0])
# qc.append(random_unitary(2), [1])
# # qc.rx(-np.pi/2, 0)
# # qc.rx(-np.pi/2, 1)
# qc.draw('mpl');
# gate_data = Operator(qc).data
# qc = QuantumCircuit(2)
# qc.append(BerkeleyGate(), [0,1])
# qc.append(random_unitary(2), [0])
# qc.append(random_unitary(2), [1])
# gate_data = Operator(qc).data
gate_data = CanonicalGate(np.pi / 4, np.pi / 8, np.pi / 8).to_matrix()
gate_data = CanonicalGate(6 * np.pi / 8, 0, 0).to_matrix()
gate_data = CPhaseGate(theta=1.5 * np.pi).inverse().to_matrix()
# from smush_sqiswap.ipynb
gate_data = np.array(
[
[
-9.46073893e-01 - 3.23950901e-01j,
7.52727300e-06 + 1.48322966e-05j,
2.94187599e-05 + 7.74408998e-06j,
4.19924316e-05 - 1.55821066e-05j,
],
[
-2.36262549e-05 - 3.80524888e-05j,
-1.76803539e-05 - 8.38430158e-06j,
9.31614726e-06 - 1.53352949e-05j,
-9.46063756e-01 - 3.23980505e-01j,
],
[
-2.79905333e-05 - 1.19149014e-05j,
-4.85744092e-05 - 3.82839177e-07j,
-9.46062499e-01 - 3.23984174e-01j,
2.04261036e-06 - 1.78273925e-05j,
],
[
-1.50375118e-05 + 7.10662866e-06j,
-9.46068103e-01 - 3.23967809e-01j,
3.86126018e-05 + 2.94739471e-05j,
1.91084645e-05 + 4.21392507e-06j,
],
]
)
# gate_data = SwapGate().to_matrix()
# sampler = GateSample(UnitaryGate(gate_data))
from slam.utils.visualize import unitary_to_weyl, c1c2c3
c1c2c3(gate_data)
unitary_to_weyl(gate_data);
objectives = krotov.gate_objectives(
basis_states=basis_states, gate=gate_data, H=H, local_invariants=0
) # XXX local_invariants flag just doesnt work!
class sigma(krotov.second_order.Sigma):
def __init__(self, A, epsA=0):
self.A = A
self.epsA = epsA
def __call__(self, t):
ϵ, A = self.epsA, self.A
return -max(ϵ, 2 * A + ϵ)
def refresh(
self,
forward_states,
forward_states0,
chi_states,
chi_norms,
optimized_pulses,
guess_pulses,
objectives,
result,
):
try:
Delta_J_T = result.info_vals[-1][0] - result.info_vals[-2][0]
except IndexError: # first iteration
Delta_J_T = 0
self.A = krotov.second_order.numerical_estimate_A(
forward_states, forward_states0, chi_states, chi_norms, Delta_J_T
)
def S(t):
"""Shape function for the field update"""
return krotov.shapes.flattop(
t, t_start=0, t_stop=T, t_rise=T / 20, t_fall=T / 20, func="sinsq"
)
# def check_PE(result):
# # extract F_PE from (F_PE, [c1, c2, c3])
# F_PE = result.info_vals[-1][0]
# if F_PE <= 0:
# return "achieved perfect entangler"
# else:
# return None
from krotov.functionals import chis_hs, J_T_hs, J_T_wc
# from krotov.functionals import chis_ss, J_T_ss
# from krotov.functionals import chis_re, J_T_re
from weylchamber import make_LI_krotov_chi_constructor, J_T_LI
from krotov.convergence import check_monotonic_error, value_below, Or
from krotov.info_hooks import print_table, chain
# learning_rate = .01 # (reversed rules) bigger is smaller learning rate
# pulse_options = {H[1][1]: dict(lambda_a=learning_rate, update_shape=S), H[2][1]: dict(lambda_a=learning_rate, update_shape=S)}
from weylchamber import make_PE_krotov_chi_constructor, make_PE_krotov_chi_constructor
class simulated_annealer:
def __init__(self):
self.prev_optimized = None
self.opt_result = None
self.save_optimized = None
self.coordinate_list = []
self.iters = 0
def train(self):
for i, learning_rate in enumerate(
[0.1, 0.25, 0.5, 0.75, 1, 2, 3]
): # (reversed rules) bigger is smaller learning rate
print("learning rate: ", learning_rate)
pulse_options = {
H[1][1]: dict(lambda_a=learning_rate, update_shape=S),
H[2][1]: dict(lambda_a=learning_rate, update_shape=S),
}
self.opt_result = krotov.optimize_pulses(
objectives,
pulse_options=pulse_options,
tlist=tlist,
propagator=krotov.propagators.expm,
# chi_constructor=make_PE_krotov_chi_constructor(basis_states),
chi_constructor=chis_hs,
# info_hook=chain(self.save_coordinate, print_table(J_T=J_T_wc), self.save_iteration),
info_hook=chain(
self.save_coordinate, print_table(J_T=J_T_hs), self.save_iteration
),
# info_hook=chain(self.save_coordinate, self.save_iteration),
# check_convergence=value_below(1e-10, name='J_T'),
check_convergence=Or(
value_below(1e-10, name="J_T"), check_monotonic_error
),
iter_stop=40 * i,
continue_from=self.opt_result,
sigma=sigma(A=0.0),
# modify_params_after_iter = {'lambda_a': 1} not sure how to use this exactly
# norm= lambda state: np.linalg.norm(state)
# skip_initial_forward_propagation=True,
)
# truncate opt_result, if convergence was reached because broke monotonicity
if "Loss of monotonic convergence" in self.opt_result.message:
# remove the faulty iteration
print("removing faulty iteration")
# self.delete_iteration()
def save_coordinate(self, **args):
basis = [objectives[i].initial_state for i in [0, 1, 2, 3]]
states = [args["fw_states_T"][i] for i in [0, 1, 2, 3]]
U = wc.gates.gate(basis, states)
O = gate_data
c1, c2, c3 = wc.coordinates.c1c2c3(U)
# print(f'c1: {c1}, c2: {c2}, c3: {c3}')
self.coordinate_list.append([c1, c2, c3])
dist = J_T_LI(O, U)
# print iters and dist
print(f"iters: {self.iters}, dist: {dist}")
# return dist
def delete_iteration(self):
self.opt_result.iters[-1] = self.opt_result.iters[-2]
self.opt_result.iter_seconds[-1] = self.opt_result.iter_seconds[-2]
self.opt_result.info_vals[-1] = self.opt_result.info_vals[-2]
self.opt_result.tau_vals[-1] = self.opt_result.tau_vals[-2]
if self.prev_optimized is None:
raise ValueError("No previous optimized pulses to revert to")
self.opt_result.optimized_controls = self.prev_optimized
pass
def save_iteration(self, **args):
# deepcopy to avoid overwriting
import copy
if self.save_optimized is not None:
self.prev_optimized = self.save_optimized
self.save_optimized = copy.deepcopy(args["optimized_pulses"])
self.iters += 1
sa = simulated_annealer()
sa.train()
opt_result = sa.opt_result
print(opt_result)
# w = WeylChamber()
# c1c2c3 = [sa.coordinate_list[i] for i in range(len(opt_result.iters))]
# for i in range(len(opt_result.iters)):
# w.add_point(c1c2c3[i][0], c1c2c3[i][1], c1c2c3[i][2])
# w.plot()
from slam.utils.visualize import coordinate_2dlist_weyl
coordinate_2dlist_weyl(sa.coordinate_list, c=range(len(sa.coordinate_list)));
plot_pulse(opt_result.optimized_controls[1], tlist)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import numpy as np
from qiskit import QuantumCircuit
from qiskit.circuit.library.arithmetic.piecewise_chebyshev import PiecewiseChebyshev
f_x, degree, breakpoints, num_state_qubits = lambda x: np.arcsin(1 / x), 2, [2, 4], 2
pw_approximation = PiecewiseChebyshev(f_x, degree, breakpoints, num_state_qubits)
pw_approximation._build()
qc = QuantumCircuit(pw_approximation.num_qubits)
qc.h(list(range(num_state_qubits)))
qc.append(pw_approximation.to_instruction(), qc.qubits)
qc.draw(output='mpl')
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
qc = QuantumCircuit(12)
for idx in range(5):
qc.h(idx)
qc.cx(idx, idx+5)
qc.cx(1, 7)
qc.x(8)
qc.cx(1, 9)
qc.x(7)
qc.cx(1, 11)
qc.swap(6, 11)
qc.swap(6, 9)
qc.swap(6, 10)
qc.x(6)
qc.draw('mpl')
|
https://github.com/2lambda123/Qiskit-qiskit
|
2lambda123
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2018.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""
A two-ways dict to represent a layout.
Layout is the relation between virtual (qu)bits and physical (qu)bits.
Virtual (qu)bits are tuples, e.g. `(QuantumRegister(3, 'qr'), 2)` or simply `qr[2]`.
Physical (qu)bits are integers.
"""
from __future__ import annotations
from typing import List
from dataclasses import dataclass
from qiskit import circuit
from qiskit.circuit.quantumregister import Qubit, QuantumRegister
from qiskit.transpiler.exceptions import LayoutError
from qiskit.converters import isinstanceint
class Layout:
"""Two-ways dict to represent a Layout."""
__slots__ = ("_regs", "_p2v", "_v2p")
def __init__(self, input_dict=None):
"""construct a Layout from a bijective dictionary, mapping
virtual qubits to physical qubits"""
self._regs = []
self._p2v = {}
self._v2p = {}
if input_dict is not None:
if not isinstance(input_dict, dict):
raise LayoutError("Layout constructor takes a dict")
self.from_dict(input_dict)
def __repr__(self):
"""Representation of a Layout"""
str_list = []
for key, val in self._p2v.items():
str_list.append(f"{key}: {val},")
if str_list:
str_list[-1] = str_list[-1][:-1]
return "Layout({\n" + "\n".join(str_list) + "\n})"
def from_dict(self, input_dict):
"""Populates a Layout from a dictionary.
The dictionary must be a bijective mapping between
virtual qubits (tuple) and physical qubits (int).
Args:
input_dict (dict):
e.g.::
{(QuantumRegister(3, 'qr'), 0): 0,
(QuantumRegister(3, 'qr'), 1): 1,
(QuantumRegister(3, 'qr'), 2): 2}
Can be written more concisely as follows:
* virtual to physical::
{qr[0]: 0,
qr[1]: 1,
qr[2]: 2}
* physical to virtual::
{0: qr[0],
1: qr[1],
2: qr[2]}
"""
for key, value in input_dict.items():
virtual, physical = Layout.order_based_on_type(key, value)
self._p2v[physical] = virtual
if virtual is None:
continue
self._v2p[virtual] = physical
@staticmethod
def order_based_on_type(value1, value2):
"""decides which one is physical/virtual based on the type. Returns (virtual, physical)"""
if isinstanceint(value1) and isinstance(value2, (Qubit, type(None))):
physical = int(value1)
virtual = value2
elif isinstanceint(value2) and isinstance(value1, (Qubit, type(None))):
physical = int(value2)
virtual = value1
else:
raise LayoutError(
"The map (%s -> %s) has to be a (Bit -> integer)"
" or the other way around." % (type(value1), type(value2))
)
return virtual, physical
def __getitem__(self, item):
if item in self._p2v:
return self._p2v[item]
if item in self._v2p:
return self._v2p[item]
raise KeyError(f"The item {item} does not exist in the Layout")
def __contains__(self, item):
return item in self._p2v or item in self._v2p
def __setitem__(self, key, value):
virtual, physical = Layout.order_based_on_type(key, value)
self._set_type_checked_item(virtual, physical)
def _set_type_checked_item(self, virtual, physical):
old = self._v2p.pop(virtual, None)
self._p2v.pop(old, None)
old = self._p2v.pop(physical, None)
self._v2p.pop(old, None)
self._p2v[physical] = virtual
if virtual is not None:
self._v2p[virtual] = physical
def __delitem__(self, key):
if isinstance(key, int):
del self._v2p[self._p2v[key]]
del self._p2v[key]
elif isinstance(key, Qubit):
del self._p2v[self._v2p[key]]
del self._v2p[key]
else:
raise LayoutError(
"The key to remove should be of the form"
" Qubit or integer) and %s was provided" % (type(key),)
)
def __len__(self):
return len(self._p2v)
def __eq__(self, other):
if isinstance(other, Layout):
return self._p2v == other._p2v and self._v2p == other._v2p
return False
def copy(self):
"""Returns a copy of a Layout instance."""
layout_copy = type(self)()
layout_copy._regs = self._regs.copy()
layout_copy._p2v = self._p2v.copy()
layout_copy._v2p = self._v2p.copy()
return layout_copy
def add(self, virtual_bit, physical_bit=None):
"""
Adds a map element between `bit` and `physical_bit`. If `physical_bit` is not
defined, `bit` will be mapped to a new physical bit.
Args:
virtual_bit (tuple): A (qu)bit. For example, (QuantumRegister(3, 'qr'), 2).
physical_bit (int): A physical bit. For example, 3.
"""
if physical_bit is None:
if len(self._p2v) == 0:
physical_bit = 0
else:
max_physical = max(self._p2v)
# Fill any gaps in the existing bits
for physical_candidate in range(max_physical):
if physical_candidate not in self._p2v:
physical_bit = physical_candidate
break
# If there are no free bits in the allocated physical bits add new ones
else:
physical_bit = max_physical + 1
self[virtual_bit] = physical_bit
def add_register(self, reg):
"""Adds at the end physical_qubits that map each bit in reg.
Args:
reg (Register): A (qu)bit Register. For example, QuantumRegister(3, 'qr').
"""
self._regs.append(reg)
for bit in reg:
if bit not in self:
self.add(bit)
def get_registers(self):
"""
Returns the registers in the layout [QuantumRegister(2, 'qr0'), QuantumRegister(3, 'qr1')]
Returns:
Set: A set of Registers in the layout
"""
return set(self._regs)
def get_virtual_bits(self):
"""
Returns the dictionary where the keys are virtual (qu)bits and the
values are physical (qu)bits.
"""
return self._v2p
def get_physical_bits(self):
"""
Returns the dictionary where the keys are physical (qu)bits and the
values are virtual (qu)bits.
"""
return self._p2v
def swap(self, left, right):
"""Swaps the map between left and right.
Args:
left (tuple or int): Item to swap with right.
right (tuple or int): Item to swap with left.
Raises:
LayoutError: If left and right have not the same type.
"""
if type(left) is not type(right):
raise LayoutError("The method swap only works with elements of the same type.")
temp = self[left]
self[left] = self[right]
self[right] = temp
def combine_into_edge_map(self, another_layout):
"""Combines self and another_layout into an "edge map".
For example::
self another_layout resulting edge map
qr_1 -> 0 0 <- q_2 qr_1 -> q_2
qr_2 -> 2 2 <- q_1 qr_2 -> q_1
qr_3 -> 3 3 <- q_0 qr_3 -> q_0
The edge map is used to compose dags via, for example, compose.
Args:
another_layout (Layout): The other layout to combine.
Returns:
dict: A "edge map".
Raises:
LayoutError: another_layout can be bigger than self, but not smaller.
Otherwise, raises.
"""
edge_map = {}
for virtual, physical in self._v2p.items():
if physical not in another_layout._p2v:
raise LayoutError(
"The wire_map_from_layouts() method does not support when the"
" other layout (another_layout) is smaller."
)
edge_map[virtual] = another_layout[physical]
return edge_map
def reorder_bits(self, bits) -> list[int]:
"""Given an ordered list of bits, reorder them according to this layout.
The list of bits must exactly match the virtual bits in this layout.
Args:
bits (list[Bit]): the bits to reorder.
Returns:
List: ordered bits.
"""
order = [0] * len(bits)
# the i-th bit is now sitting in position j
for i, v in enumerate(bits):
j = self[v]
order[i] = j
return order
@staticmethod
def generate_trivial_layout(*regs):
"""Creates a trivial ("one-to-one") Layout with the registers and qubits in `regs`.
Args:
*regs (Registers, Qubits): registers and qubits to include in the layout.
Returns:
Layout: A layout with all the `regs` in the given order.
"""
layout = Layout()
for reg in regs:
if isinstance(reg, QuantumRegister):
layout.add_register(reg)
else:
layout.add(reg)
return layout
@staticmethod
def from_intlist(int_list, *qregs):
"""Converts a list of integers to a Layout
mapping virtual qubits (index of the list) to
physical qubits (the list values).
Args:
int_list (list): A list of integers.
*qregs (QuantumRegisters): The quantum registers to apply
the layout to.
Returns:
Layout: The corresponding Layout object.
Raises:
LayoutError: Invalid input layout.
"""
if not all(isinstanceint(i) for i in int_list):
raise LayoutError("Expected a list of ints")
if len(int_list) != len(set(int_list)):
raise LayoutError("Duplicate values not permitted; Layout is bijective.")
num_qubits = sum(reg.size for reg in qregs)
# Check if list is too short to cover all qubits
if len(int_list) != num_qubits:
raise LayoutError(
f"Integer list length ({len(int_list)}) must equal number of qubits "
f"in circuit ({num_qubits}): {int_list}."
)
out = Layout()
main_idx = 0
for qreg in qregs:
for idx in range(qreg.size):
out[qreg[idx]] = int_list[main_idx]
main_idx += 1
out.add_register(qreg)
if main_idx != len(int_list):
for int_item in int_list[main_idx:]:
out[int_item] = None
return out
@staticmethod
def from_qubit_list(qubit_list, *qregs):
"""
Populates a Layout from a list containing virtual
qubits, Qubit or None.
Args:
qubit_list (list):
e.g.: [qr[0], None, qr[2], qr[3]]
*qregs (QuantumRegisters): The quantum registers to apply
the layout to.
Returns:
Layout: the corresponding Layout object
Raises:
LayoutError: If the elements are not Qubit or None
"""
out = Layout()
for physical, virtual in enumerate(qubit_list):
if virtual is None:
continue
if isinstance(virtual, Qubit):
if virtual in out._v2p:
raise LayoutError("Duplicate values not permitted; Layout is bijective.")
out[virtual] = physical
else:
raise LayoutError("The list should contain elements of the Bits or NoneTypes")
for qreg in qregs:
out.add_register(qreg)
return out
def compose(self, other: Layout, qubits: List[Qubit]) -> Layout:
"""Compose this layout with another layout.
If this layout represents a mapping from the P-qubits to the positions of the Q-qubits,
and the other layout represents a mapping from the Q-qubits to the positions of
the R-qubits, then the composed layout represents a mapping from the P-qubits to the
positions of the R-qubits.
Args:
other: The existing :class:`.Layout` to compose this :class:`.Layout` with.
qubits: A list of :class:`.Qubit` objects over which ``other`` is defined,
used to establish the correspondence between the positions of the ``other``
qubits and the actual qubits.
Returns:
A new layout object the represents this layout composed with the ``other`` layout.
"""
other_v2p = other.get_virtual_bits()
return Layout({virt: other_v2p[qubits[phys]] for virt, phys in self._v2p.items()})
def inverse(self, source_qubits: List[Qubit], target_qubits: List[Qubit]):
"""Finds the inverse of this layout.
This is possible when the layout is a bijective mapping, however the input
and the output qubits may be different (in particular, this layout may be
the mapping from the extended-with-ancillas virtual qubits to physical qubits).
Thus, if this layout represents a mapping from the P-qubits to the positions
of the Q-qubits, the inverse layout represents a mapping from the Q-qubits
to the positions of the P-qubits.
Args:
source_qubits: A list of :class:`.Qubit` objects representing the domain
of the layout.
target_qubits: A list of :class:`.Qubit` objects representing the image
of the layout.
Returns:
A new layout object the represents the inverse of this layout.
"""
source_qubit_to_position = {q: p for p, q in enumerate(source_qubits)}
return Layout(
{
target_qubits[pos_phys]: source_qubit_to_position[virt]
for virt, pos_phys in self._v2p.items()
}
)
def to_permutation(self, qubits: List[Qubit]):
"""Creates a permutation corresponding to this layout.
This is possible when the layout is a bijective mapping with the same
source and target qubits (for instance, a "final_layout" corresponds
to a permutation of the physical circuit qubits). If this layout is
a mapping from qubits to their new positions, the resulting permutation
describes which qubits occupy the positions 0, 1, 2, etc. after
applying the permutation.
For example, suppose that the list of qubits is ``[qr_0, qr_1, qr_2]``,
and the layout maps ``qr_0`` to ``2``, ``qr_1`` to ``0``, and
``qr_2`` to ``1``. In terms of positions in ``qubits``, this maps ``0``
to ``2``, ``1`` to ``0`` and ``2`` to ``1``, with the corresponding
permutation being ``[1, 2, 0]``.
"""
perm = [None] * len(qubits)
for i, q in enumerate(qubits):
pos = self._v2p[q]
perm[pos] = i
return perm
@dataclass
class TranspileLayout:
r"""Layout attributes for the output circuit from transpiler.
The :mod:`~qiskit.transpiler` is unitary-preserving up to the "initial layout"
and "final layout" permutations. The initial layout permutation is caused by
setting and applying the initial layout during the :ref:`layout_stage`.
The final layout permutation is caused by :class:`~.SwapGate` insertion during
the :ref:`routing_stage`. This class provides an interface to reason about these
permutations using a variety of helper methods.
During the layout stage, the transpiler can potentially remap the order of the
qubits in the circuit as it fits the circuit to the target backend. For example,
let the input circuit be:
.. plot:
:include-source:
from qiskit.circuit import QuantumCircuit, QuantumRegister
qr = QuantumRegister(3, name="MyReg")
qc = QuantumCircuit(qr)
qc.h(0)
qc.cx(0, 1)
qc.cx(0, 2)
qc.draw("mpl")
Suppose that during the layout stage the transpiler reorders the qubits to be:
.. plot:
:include-source:
from qiskit import QuantumCircuit
qc = QuantumCircuit(3)
qc.h(2)
qc.cx(2, 1)
qc.cx(2, 0)
qc.draw("mpl")
Then the output of the :meth:`.initial_virtual_layout` method is
equivalent to::
Layout({
qr[0]: 2,
qr[1]: 1,
qr[2]: 0,
})
(it is also this attribute in the :meth:`.QuantumCircuit.draw` and
:func:`.circuit_drawer` which is used to display the mapping of qubits to
positions in circuit visualizations post-transpilation).
Building on the above example, suppose that during the routing stage
the transpiler needs to insert swap gates, and the output circuit
becomes:
.. plot:
:include-source:
from qiskit import QuantumCircuit
qc = QuantumCircuit(3)
qc.h(2)
qc.cx(2, 1)
qc.swap(0, 1)
qc.cx(2, 1)
qc.draw("mpl")
Then the output of the :meth:`routing_permutation` method is::
[1, 0, 2]
which maps positions of qubits before routing to their final positions
after routing.
There are three public attributes associated with the class, however these
are mostly provided for backwards compatibility and represent the internal
state from the transpiler. They are defined as:
* :attr:`initial_layout` - This attribute is used to model the
permutation caused by the :ref:`layout_stage`. It is a
:class:`~.Layout` object that maps the input :class:`~.QuantumCircuit`\s
:class:`~.circuit.Qubit` objects to the position in the output
:class:`.QuantumCircuit.qubits` list.
* :attr:`input_qubit_mapping` - This attribute is used to retain
input ordering of the original :class:`~.QuantumCircuit` object. It
maps the virtual :class:`~.circuit.Qubit` object from the original circuit
(and :attr:`initial_layout`) to its corresponding position in
:attr:`.QuantumCircuit.qubits` in the original circuit. This
is needed when computing the permutation of the :class:`Operator` of
the circuit (and used by :meth:`.Operator.from_circuit`).
* :attr:`final_layout` - This attribute is used to model the
permutation caused by the :ref:`routing_stage`. It is a
:class:`~.Layout` object that maps the output circuit's qubits from
:class:`.QuantumCircuit.qubits` in the output circuit to their final
positions after routing. Importantly, this only represents the
permutation caused by inserting :class:`~.SwapGate`\s into
the :class:`~.QuantumCircuit` during the :ref:`routing_stage`.
It is **not** a mapping from the original input circuit's position
to the final position at the end of the transpiled circuit.
If you need this, you can use the :meth:`.final_index_layout` to generate this.
If :attr:`final_layout` is set to ``None``, this indicates that routing was not
run, and can be considered equivalent to a trivial layout with the qubits from
the output circuit's :attr:`~.QuantumCircuit.qubits` list.
"""
initial_layout: Layout
input_qubit_mapping: dict[circuit.Qubit, int]
final_layout: Layout | None = None
_input_qubit_count: int | None = None
_output_qubit_list: List[Qubit] | None = None
def initial_virtual_layout(self, filter_ancillas: bool = False) -> Layout:
"""Return a :class:`.Layout` object for the initial layout.
This returns a mapping of virtual :class:`~.circuit.Qubit` objects in the input
circuit to the positions of the physical qubits selected during layout.
This is analogous to the :attr:`.initial_layout` attribute.
Args:
filter_ancillas: If set to ``True`` only qubits in the input circuit
will be in the returned layout. Any ancilla qubits added to the
output circuit will be filtered from the returned object.
Returns:
A layout object mapping the input circuit's :class:`~.circuit.Qubit`
objects to the positions of the selected physical qubits.
"""
if not filter_ancillas:
return self.initial_layout
return Layout(
{
k: v
for k, v in self.initial_layout.get_virtual_bits().items()
if self.input_qubit_mapping[k] < self._input_qubit_count
}
)
def initial_index_layout(self, filter_ancillas: bool = False) -> List[int]:
"""Generate an initial layout as an array of integers.
Args:
filter_ancillas: If set to ``True`` any ancilla qubits added
to the transpiler will not be included in the output.
Return:
A layout array that maps a position in the array to its new position in the output
circuit.
"""
virtual_map = self.initial_layout.get_virtual_bits()
if filter_ancillas:
output = [None] * self._input_qubit_count
else:
output = [None] * len(virtual_map)
for index, (virt, phys) in enumerate(virtual_map.items()):
if filter_ancillas and index >= self._input_qubit_count:
break
pos = self.input_qubit_mapping[virt]
output[pos] = phys
return output
def routing_permutation(self) -> List[int]:
"""Generate a final layout as an array of integers.
If there is no :attr:`.final_layout` attribute present then that indicates
there was no output permutation caused by routing or other transpiler
transforms. In this case the function will return a list of ``[0, 1, 2, .., n]``.
Returns:
A layout array that maps a position in the array to its new position in the output
circuit.
"""
if self.final_layout is None:
return list(range(len(self._output_qubit_list)))
virtual_map = self.final_layout.get_virtual_bits()
return [virtual_map[virt] for virt in self._output_qubit_list]
def final_index_layout(self, filter_ancillas: bool = True) -> List[int]:
"""Generate the final layout as an array of integers.
This method will generate an array of final positions for each qubit in the input circuit.
For example, if you had an input circuit like::
qc = QuantumCircuit(3)
qc.h(0)
qc.cx(0, 1)
qc.cx(0, 2)
and the output from the transpiler was::
tqc = QuantumCircuit(3)
tqc.h(2)
tqc.cx(2, 1)
tqc.swap(0, 1)
tqc.cx(2, 1)
then the :meth:`.final_index_layout` method returns::
[2, 0, 1]
This can be seen as follows. Qubit 0 in the original circuit is mapped to qubit 2
in the output circuit during the layout stage, which is mapped to qubit 2 during the
routing stage. Qubit 1 in the original circuit is mapped to qubit 1 in the output
circuit during the layout stage, which is mapped to qubit 0 during the routing
stage. Qubit 2 in the original circuit is mapped to qubit 0 in the output circuit
during the layout stage, which is mapped to qubit 1 during the routing stage.
The output list length will be as wide as the input circuit's number of qubits,
as the output list from this method is for tracking the permutation of qubits in the
original circuit caused by the transpiler.
Args:
filter_ancillas: If set to ``False`` any ancillas allocated in the output circuit will be
included in the layout.
Returns:
A list of final positions for each input circuit qubit.
"""
if self._input_qubit_count is None:
# TODO: After there is a way to differentiate the ancilla qubits added by the transpiler
# don't use the ancilla name anymore.See #10817 for discussion on this.
num_source_qubits = len(
[
x
for x in self.input_qubit_mapping
if getattr(x, "_register", "").startswith("ancilla")
]
)
else:
num_source_qubits = self._input_qubit_count
if self._output_qubit_list is None:
circuit_qubits = list(self.final_layout.get_virtual_bits())
else:
circuit_qubits = self._output_qubit_list
pos_to_virt = {v: k for k, v in self.input_qubit_mapping.items()}
qubit_indices = []
if filter_ancillas:
num_qubits = num_source_qubits
else:
num_qubits = len(self._output_qubit_list)
for index in range(num_qubits):
qubit_idx = self.initial_layout[pos_to_virt[index]]
if self.final_layout is not None:
qubit_idx = self.final_layout[circuit_qubits[qubit_idx]]
qubit_indices.append(qubit_idx)
return qubit_indices
def final_virtual_layout(self, filter_ancillas: bool = True) -> Layout:
"""Generate the final layout as a :class:`.Layout` object.
This method will generate an array of final positions for each qubit in the input circuit.
For example, if you had an input circuit like::
qc = QuantumCircuit(3)
qc.h(0)
qc.cx(0, 1)
qc.cx(0, 2)
and the output from the transpiler was::
tqc = QuantumCircuit(3)
tqc.h(2)
tqc.cx(2, 1)
tqc.swap(0, 1)
tqc.cx(2, 1)
then the return from this function would be a layout object::
Layout({
qc.qubits[0]: 2,
qc.qubits[1]: 0,
qc.qubits[2]: 1,
})
This can be seen as follows. Qubit 0 in the original circuit is mapped to qubit 2
in the output circuit during the layout stage, which is mapped to qubit 2 during the
routing stage. Qubit 1 in the original circuit is mapped to qubit 1 in the output
circuit during the layout stage, which is mapped to qubit 0 during the routing
stage. Qubit 2 in the original circuit is mapped to qubit 0 in the output circuit
during the layout stage, which is mapped to qubit 1 during the routing stage.
The output list length will be as wide as the input circuit's number of qubits,
as the output list from this method is for tracking the permutation of qubits in the
original circuit caused by the transpiler.
Args:
filter_ancillas: If set to ``False`` any ancillas allocated in the output circuit will be
included in the layout.
Returns:
A layout object mapping to the final positions for each qubit.
"""
res = self.final_index_layout(filter_ancillas=filter_ancillas)
pos_to_virt = {v: k for k, v in self.input_qubit_mapping.items()}
return Layout({pos_to_virt[index]: phys for index, phys in enumerate(res)})
|
https://github.com/quantumyatra/quantum_computing
|
quantumyatra
|
import numpy as np
import pylab as plt
from qiskit import QuantumCircuit, execute, Aer, IBMQ
from qiskit.visualization import plot_histogram, plot_bloch_multivector
damage = 0 # damage to the enemy
def attack(damage):
damage = min ( (damage +1/3.), 1 )
return damage
damage = attack(damage)
print (damage)
%matplotlib inline
def plot_satevector(qc):
backend_sv = Aer.get_backend('statevector_simulator')
sv = execute(qc, backend=backend_sv).result().get_statevector()
fig = plot_bloch_multivector(sv)
return fig
qcc = QuantumCircuit(1,1)
qcc.x(0)
fig = plot_satevector(qcc)
fig
damage_qc = QuantumCircuit(1,1)
def attack(damage_qc):
damage_qc.rx(np.pi/3,0)
fig = plot_satevector(damage_qc)
fig
return fig
meas = QuantumCircuit(1,1)
meas.measure(0,0)
fig = attack(damage_qc)
fig
#qc = damage_qc+meas
#counts = execute(qc, Aer.get_backend('qasm_simulator'), shots=1000).result().get_counts()
#print(counts)
#qc.draw('mpl')
def get_damage(damage_qc):
meas = QuantumCircuit(1,1)
meas.measure(0,0)
attack(damage_qc)
Nshots=1000
counts = execute(damage_qc+meas, backend=Aer.get_backend('qasm_simulator'), shots=Nshots).result().get_counts()
damage = counts['1']/Nshots
return damage
damage_qc = QuantumCircuit(1,1)
damage = get_damage(damage_qc)
print(damage)
#damage = attack(damage_qc)
#get_damage(damage)
#damage_qc.draw()
meas = QuantumCircuit(1,1)
meas.measure(0,0)
damage_qc = attack(damage_qc)
qc = damage_qc+meas
counts = execute(qc, Aer.get_backend('qasm_simulator'), shots=1000).result().get_counts()
print(counts)
qc.draw()
#some tests
qc = QuantumCircuit(1,1)
backend = Aer.get_backend('qasm_simulator')
counts = execute(qc, backend=Aer.get_backend('qasm_simulator'), shots=1000).result().get_counts()
counts
!git clone https://github.com/quantumjim/jupyter-widget-game-engine/
!mv jupyter-widget-game-engine/jupyter_widget_engine.py jupyter_widget_engine.py
!mv jupyter-widget-game-engine/jupyter_widget_game.ipynb jupyter_widget_game.ipynb
!rm -r jupyter-widget-game-engine
from jupyter_widget_engine import jupyter_widget_engine
L = 8
def start(engine):
pass
def next_frame(engine):
pass
engine = jupyter_widget_engine(start, next_frame, L=L)
def get_terrain(x,y):
return 'grass'
L = 8
def start(engine):
engine.get_terrain = get_terrain
engine.next_frame(engine)
def next_frame(engine):
for x in range(L):
for y in range(L):
#terrain = engine.get_terrain(x,y)
if engine.get_terrain(x,y) == 'grass':
engine.screen[x,y].button_style = 'success'
engine = jupyter_widget_engine(start, next_frame, L=L)
def get_terrain(x,y):
qc = QuantumCircuit(1,1) # make a circuit
# perform rotations, whose angles depend on x and y
qc.rx( (np.pi/16)*(x+y) ,0)
qc.rx( (np.pi/16)*(x-y) ,0)
# calculate probability for outcome 1
qc.measure(0,0)
counts = execute(qc, Aer.get_backend('qasm_simulator'), shots=1000).result().get_counts()
if '1' in counts:
h = counts['1']/1000
else:
h = 0
# return terrain depending on this probability
# the chosen values here are fairly arbitrarily
if h<0.3:
terrain = 'sea'
elif h<0.7:
terrain = 'sand'
else:
terrain = 'grass'
return terrain
L = 8
def start(engine):
engine.get_terrain = get_terrain
engine.next_frame(engine)
def next_frame(engine):
for x in range(L):
for y in range(L):
terrain = engine.get_terrain(x,y)
if terrain == 'grass':
engine.screen[x,y].button_style = 'success'
elif terrain == 'sand':
engine.screen[x,y].button_style = 'warning'
else:
engine.screen[x,y].button_style = 'info'
engine = jupyter_widget_engine(start, next_frame, L=L)
L = 8
def start(engine):
engine.get_terrain = get_terrain
engine.p_x = 4
engine.p_y = 4
engine.next_frame(engine)
def next_frame(engine):
if engine.controller['up'].value:
engine.p_y -= 1
if engine.controller['down'].value:
engine.p_y += 1
if engine.controller['left'].value:
engine.p_x -= 1
if engine.controller['right'].value:
engine.p_x += 1
s_x = np.floor(engine.p_x/L)
s_y = np.floor(engine.p_y/L)
for x in range(L):
for y in range(L):
terrain = engine.get_terrain(L*s_x+x,L*s_y+y)
if terrain == 'grass':
engine.screen[x,y].button_style = 'success'
elif terrain == 'sand':
engine.screen[x,y].button_style = 'warning'
else:
engine.screen[x,y].button_style = 'info'
engine.screen[engine.p_x%L, engine.p_y%L].button_style = 'danger'
engine = jupyter_widget_engine(start, next_frame, L=L)
|
https://github.com/taalexander/IEEE-Quantum-Week-2021
|
taalexander
|
import os
from typing import Any, List, Dict, Union
import numpy as np
import matplotlib.pyplot as plt
from qiskit import IBMQ, Aer, QuantumCircuit, QuantumRegister, ClassicalRegister, transpile, execute
from qiskit.tools.visualization import plot_histogram
from qiskit.result import marginal_counts
import qiskit.tools.jupyter
from run_openqasm3 import run_openqasm3
%matplotlib inline
import warnings
warnings.filterwarnings("ignore")
pi = np.pi
backend_sim = Aer.get_backend('aer_simulator')
hub = 'ibm-q-community'
group = 'ieee-session'
project = 'event-2021'
backend_name = 'ibm_perth'
IBMQ.load_account()
provider = IBMQ.get_provider(hub=hub, group=group, project=project)
backend_real = provider.get_backend(backend_name)
basis_gates = backend_real.configuration().basis_gates
import qiskit.tools.jupyter
backend_real
from qiskit import qasm3
def dump_qasm3(circuit, backend=backend_real):
return qasm3.Exporter(includes=[], basis_gates=basis_gates+["reset"], disable_constants=True).dumps(circuit)
q = QuantumRegister(1,'q')
c = ClassicalRegister(1,'c')
qc = QuantumCircuit(q, c)
qc.h(0)
qc.measure(0,0)
qc.x(0).c_if(c, 0)
qc.draw(output='mpl')
q = QuantumRegister(3,'q')
c = ClassicalRegister(3,'c')
qc = QuantumCircuit(q, c)
qc.h(q[0])
qc.h(q[1])
qc.h(q[2])
qc.barrier()
qc.measure(q,c)
qc.draw('mpl')
print(bin(3))
print(bin(7))
q = QuantumRegister(3,'q')
c = ClassicalRegister(3,'c')
qc = QuantumCircuit(q, c)
qc.h(0)
qc.h(1)
qc.h(2)
qc.barrier()
qc.measure(q,c)
qc.x(2).c_if(c, 3) # for the 011 case
qc.x(2).c_if(c, 7) # for the 111 case
qc.draw(output='mpl')
qubits = [5, 6]
def reset_conditional(qc, q, reset_reg):
qc.barrier(q)
qc.measure(q, reset_reg)
qc.x(q).c_if(reset_reg, 1)
qc.barrier(q)
def reset_conditional(qc, q, reset_reg):
qc.barrier(q)
qc.measure(q, reset_reg)
qc.x(q).c_if(reset_reg, 1)
qc.barrier(q)
qr = QuantumRegister(2)
reset_reg0 = ClassicalRegister(1, "reset_reg0")
reset_reg1 = ClassicalRegister(1, "reset_reg1")
cr0 = ClassicalRegister(1, "reset_result0")
cr1 = ClassicalRegister(1, "reset_result1")
qc_reset = QuantumCircuit(qr, reset_reg0, reset_reg1, cr0, cr1)
reset_conditional(qc_reset, qr[0], reset_reg0)
reset_conditional(qc_reset, qr[1], reset_reg1)
qc_reset.measure(0, cr0)
qc_reset.measure(1, cr1)
qc_reset = transpile(qc_reset, backend_real, initial_layout=qubits)
qc_reset.draw(output="mpl")
# Hint use qiskit.result.marginal_counts to remove the first three classical register results
# from your counts
def pad_counts(counts):
new_counts = {}
for k, v in counts.items():
if len(k) < 4:
for _ in range(4-len(k)):
k = "0"+k
new_counts[k] = v
return new_counts
def remove_reset_results(counts):
return marginal_counts(pad_counts(counts), indices=[0, 1])
reset_job = run_openqasm3(qc_reset, backend_real, verbose=False)
print(f"Reset job id: {reset_job.job_id()}")
reset_result = reset_job.result()
reset_counts = remove_reset_results(reset_result.get_counts(0))
print(f"The results of your reset circuit are {reset_counts}")
assert reset_counts["00"] > 700
def init(qc, qr):
"""Implement a qubit initialization using three rounds of qubit reset."""
qc.barrier(qr)
qc.reset(qr)
qc.reset(qr)
qc.reset(qr)
qc.barrier(qr)
qr = QuantumRegister(2)
cr0 = ClassicalRegister(1, "reset_result0")
cr1 = ClassicalRegister(1, "reset_result1")
qc_init = QuantumCircuit(qr, cr0, cr1)
init(qc_init, qr)
qc_init.measure(0, cr0)
qc_init.measure(1, cr1)
qc_init = transpile(qc_init, backend_real, initial_layout=qubits)
qc_init.draw(output="mpl")
init_job = run_openqasm3(qc_init, backend_real, verbose=False)
print(f"Qubit init job id: {init_job.job_id()}")
init_result = init_job.result()
init_counts = init_result.get_counts()
print(f"The results of your reset circuit are {init_counts}")
assert init_counts["0 0"] > 900
delta_counts = init_counts["0 0"] - reset_counts["00"]
print(f"With the initialization circuit we prepared the ground state {delta_counts} more times than in the reset circuit.""")
nq = 2
m = 2
qr = QuantumRegister(2,'q')
c0 = ClassicalRegister(1,'c0')
c1 = ClassicalRegister(1, 'c1')
qc_S = QuantumCircuit(qr, c0, c1)
def init_ipe_circuit(qc):
"""Initialize the qubits in your IPE circuit."""
init(qc, [0, 1])
init_ipe_circuit(qc_S)
qc_S.draw(output="mpl")
def initialize_eigenstate(qc):
"""Initialize the eigenstate and prepare our ancilla qubit"""
qc.h(0)
qc.x(1)
initialize_eigenstate(qc_S)
qc_S.draw('mpl')
theta = 1 * np.pi / 2
cu_circ = QuantumCircuit(2)
cu_circ.cp(theta,0,1)
cu_circ.draw('mpl')
for _ in range(2**(m-1)):
qc_S.cp(theta,0,1)
qc_S.draw('mpl')
def x_measurement(qc, qubit, cbit):
"""Measure 'qubit' in the X-basis, and store the result in 'cbit'"""
qc.h(qubit)
qc.measure(qubit, cbit)
x_measurement(qc_S, qr[0], c0)
qc_S.draw('mpl')
def reset_auxiliary(qc):
qc.reset(0)
qc.h(0)
reset_auxiliary(qc_S)
qc_S.draw('mpl')
qc_S.p(-np.pi/2,0).c_if(c0, 1)
qc_S.draw('mpl')
## 2^t c-U operations (with t=m-2)
for _ in range(2**(m-2)):
qc_S.cp(theta,0,1)
x_measurement(qc_S, qr[0], c1)
qc_S.draw('mpl')
count = execute(qc_S, backend_sim).result().get_counts()
count
count0 = remove_reset_results(execute(qc_S, backend_sim).result().get_counts())
key_new = [str(int(key,2)/2**m) for key in list(count0.keys())]
count1 = dict(zip(key_new, count0.values()))
fig, ax = plt.subplots(1,2)
plot_histogram(count0, ax=ax[0])
plot_histogram(count1, ax=ax[1])
plt.tight_layout()
qc_S_backend = transpile(qc_S, backend_real, initial_layout=qubits, optimization_level=3)
qc_S_backend.draw(output="mpl")
real_ipe_job = run_openqasm3(qc_S_backend, backend_real, verbose=False)
print(f"IPE job id: {real_ipe_job.job_id()}")
real_counts0 = remove_reset_results(real_ipe_job.result().get_counts())
real_key_new = [str(int(key,2)/2**m) for key in list(real_counts0.keys())]
real_counts1 = dict(zip(real_key_new, real_counts0.values()))
fig, ax = plt.subplots(1,2)
plot_histogram(real_counts0, ax=ax[0])
plot_histogram(real_counts1, ax=ax[1])
plt.tight_layout()
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/a24l/IBM_Qiskit_QGSS
|
a24l
|
!pip install -U -r resources/requirements.txt
from IPython.display import clear_output
clear_output()
from qiskit import QuantumCircuit
mycircuit = QuantumCircuit(1)
mycircuit.draw('mpl')
from qiskit.quantum_info import Statevector
sv = Statevector.from_label('0')
sv
sv.data
new_sv = sv.evolve(mycircuit)
new_sv
from qiskit.quantum_info import state_fidelity
state_fidelity(sv, new_sv)
from qiskit.visualization import plot_state_qsphere
plot_state_qsphere(sv.data)
mycircuit = QuantumCircuit(1)
mycircuit.x(0)
mycircuit.draw('mpl')
sv = Statevector.from_label('0')
new_sv = sv.evolve(mycircuit)
new_sv
state_fidelity(new_sv, sv)
plot_state_qsphere(new_sv.data)
sv = Statevector.from_label('0')
mycircuit = QuantumCircuit(1)
mycircuit.h(0)
mycircuit.draw('mpl')
new_sv = sv.evolve(mycircuit)
print(new_sv)
plot_state_qsphere(new_sv.data)
sv = Statevector.from_label('1')
mycircuit = QuantumCircuit(1)
mycircuit.h(0)
new_sv = sv.evolve(mycircuit)
print(new_sv)
plot_state_qsphere(new_sv.data)
from resources.qiskit_textbook.widgets import gate_demo
gate_demo(qsphere=True)
sv = Statevector.from_label('00')
plot_state_qsphere(sv.data)
mycircuit = QuantumCircuit(2)
mycircuit.h(0)
mycircuit.cx(0,1)
mycircuit.draw('mpl')
new_sv = sv.evolve(mycircuit)
print(new_sv)
plot_state_qsphere(new_sv.data)
counts = new_sv.sample_counts(shots=1000)
from qiskit.visualization import plot_histogram
plot_histogram(counts)
Tri3=QuantumCircuit(2,2)
Tri3.x(1)
Tri3.h(0)
Tri3.cx(0, 1)
Tri3.draw()
tri3_sv = sv.evolve(Tri3)
print(tri3_sv)
plot_state_qsphere(tri3_sv.data)
counts1 = tri3_sv.sample_counts(shots=1000)
from qiskit.visualization import plot_histogram
plot_histogram(counts1)
#create the above bell state
Sing = QuantumCircuit(2, 2)
#make the gates
Sing.x(1)
Sing.h(0)
Sing.z(0)
Sing.z(1)
Sing.cx(0,1)
Sing.draw()
#print out the statevector
sing_sv = sv.evolve(Sing)
print(sing_sv)
#plot the statevector on qshere
plot_state_qsphere(sing_sv.data)
mycircuit = QuantumCircuit(2, 2)
mycircuit.h(0)
mycircuit.cx(0,1)
mycircuit.measure([0,1], [0,1])
mycircuit.draw('mpl')
from qiskit import Aer, execute
simulator = Aer.get_backend('qasm_simulator')
result = execute(mycircuit, simulator, shots=10000).result()
counts = result.get_counts(mycircuit)
plot_histogram(counts)
def initialize_qubit(given_circuit, qubit_index):
import numpy as np
### WRITE YOUR CODE BETWEEN THESE LINES - START
initial_state = [np.sqrt(0.70)+0.j,np.sqrt(0.30)+0.j]
### WRITE YOUR CODE BETWEEN THESE LINES - END
given_circuit.initialize(initial_state, 0)
return given_circuit
def entangle_qubits(given_circuit, qubit_Alice, qubit_Bob):
### WRITE YOUR CODE BETWEEN THESE LINES - START
given_circuit.h(qubit_Alice)
given_circuit.cx(qubit_Alice,qubit_Bob)
### WRITE YOUR CODE BETWEEN THESE LINES - END
return given_circuit
def bell_meas_Alice_qubits(given_circuit, qubit1_Alice, qubit2_Alice, clbit1_Alice, clbit2_Alice):
### WRITE YOUR CODE BETWEEN THESE LINES - START
given_circuit.cx(qubit1_Alice,qubit2_Alice)
given_circuit.h(qubit1_Alice)
given_circuit.measure(qubit1_Alice,clbit1_Alice)
given_circuit.measure(qubit2_Alice,clbit2_Alice)
### WRITE YOUR CODE BETWEEN THESE LINES - END
return given_circuit
def controlled_ops_Bob_qubit(given_circuit, qubit_Bob, clbit1_Alice, clbit2_Alice):
### WRITE YOUR CODE BETWEEN THESE LINES - START
given_circuit.x(qubit_Bob).c_if(clbit2_Alice, 1)
given_circuit.z(qubit_Bob).c_if(clbit1_Alice, 1)
### WRITE YOUR CODE BETWEEN THESE LINES - END
return given_circuit
### imports
from qiskit import QuantumRegister, ClassicalRegister
### set up the qubits and classical bits
all_qubits_Alice = QuantumRegister(2)
all_qubits_Bob = QuantumRegister(1)
creg1_Alice = ClassicalRegister(1)
creg2_Alice = ClassicalRegister(1)
### quantum teleportation circuit here
# Initialize
mycircuit = QuantumCircuit(all_qubits_Alice, all_qubits_Bob, creg1_Alice, creg2_Alice)
initialize_qubit(mycircuit, 0)
mycircuit.barrier()
# Entangle
entangle_qubits(mycircuit, 1, 2)
mycircuit.barrier()
# Do a Bell measurement
bell_meas_Alice_qubits(mycircuit, all_qubits_Alice[0], all_qubits_Alice[1], creg1_Alice, creg2_Alice)
mycircuit.barrier()
# Apply classically controlled quantum gates
controlled_ops_Bob_qubit(mycircuit, all_qubits_Bob[0], creg1_Alice, creg2_Alice)
### Look at the complete circuit
mycircuit.draw()
|
https://github.com/samuraigab/Quantum-Basic-Algorithms
|
samuraigab
|
'''
Quantum Phase Estimation
Por Samuraí Brito
Data:02072021
'''
import numpy as np
# Importing standard Qiskit libraries
from qiskit import QuantumCircuit, transpile, Aer, IBMQ, execute
from qiskit.tools.jupyter import *
from qiskit.visualization import *
from ibm_quantum_widgets import *
# Loading your IBM Quantum account(s)
# provider = IBMQ.load_account()
# provider = IBMQ.get_provider(hub='ibm-q-research', group='inter-inst-phys-1', project='main')
from qiskit.circuit.library import QFT
n = 4
qft = QFT(num_qubits = n, name = 'QFT')
qft.draw('mpl')
#Creating 101 state
qft_circ = QuantumCircuit(n,n)
qft_circ.x(0)
qft_circ.x(2)
qft_circ.draw()
sim_backend = Aer.get_backend('statevector_simulator')
state = execute(qft_circ, sim_backend).result().get_statevector()
# #get results
# results = job.result()
# state = results.get_statevector()
plot_bloch_multivector(state)
#appending QFT subroutine
qft_circ.append(qft,range(n))
qft_circ.save_statevector()
qft_circ.draw()
#Run in a simulator
sim_backend = Aer.get_backend('statevector_simulator')
state = execute(qft_circ, sim_backend).result().get_statevector()
plot_bloch_multivector(state)
iqft = QFT(n, inverse=True, name = 'iQFT')
iqft.draw()
#apply inverse QFT
qft_circ.append(iqft, range(n))
qft_circ.measure(range(n), range(n))
qft_circ.draw()
sim_backend = Aer.get_backend('statevector_simulator')
state = execute(qft_circ, sim_backend, shots = 10000000).result().get_statevector()
plot_bloch_multivector(state)
sim_backend = Aer.get_backend('qasm_simulator')
state = execute(qft_circ, sim_backend).result().get_counts()
plot_histogram(state)
def qft(qc,n):
for i in range(n):
qc.h(n-i-1)
# qc.barrier()
# display(qc.draw('mpl'))
for j in range(n-i-1):
qc.cp(np.pi/(2**(n-i-j-1)), n-i-1,j)
qc.barrier()
for qubit in range(n//2):
qc.swap(qubit, n-qubit-1)
return qc
# display(qc.draw('mpl'))
n = 4
qc = QuantumCircuit(n)
qc = qft(qc,n)
qc.draw('mpl')
qc = QuantumCircuit(n)
def inverse_qft(qc, n):
"""Does the inverse QFT on the first n qubits in circuit"""
# First we create a QFT circuit of the correct size:
qft_circ = qft(QuantumCircuit(n), n)
# Then we take the inverse of this circuit
invqft_circ = qft_circ.inverse()
# And add it to the first n qubits in our existing circuit
qc.append(invqft_circ, qc.qubits[:n])
return qc
n = 4
qc = QuantumCircuit(n)
qc = inverse_qft(qc,n).decompose()
qc.draw('mpl')
import numpy as np
from qiskit.extensions import *
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer, IBMQ
from qiskit.compiler import transpile, assemble
from qiskit.tools.jupyter import *
from qiskit.visualization import *
from ibm_quantum_widgets import *
import numpy as np
import random
from scipy.linalg import expm
from qiskit.circuit.add_control import add_control
n = 10
Id = np.eye(2)
theta = 0.15
U = expm(2*1j*np.pi*theta*Id)
u = UnitaryGate(U,label='U')
u = add_control(operation=u, num_ctrl_qubits=1,ctrl_state=1, label = 'U')
print('Expected phase:', theta)
def qpe(n, u):
qc = QuantumCircuit(n + 1,n)
for i in range(n):
qc.h(i)
qc.x(n)
for i in range(n):
for j in range(2**i):
qc.append(u, [i, n])
qc.draw()
#------------------- QFT dag ----------------------
qft_circ = qft(QuantumCircuit(n), n)
invqft_circ = qft_circ.inverse()
qc.append(invqft_circ, qc.qubits[:n])
qc.measure(range(n),range(n))
return qc
qc = qpe(n,u)
display(qc.draw('mpl'))
shots = 10000
backend = Aer.get_backend('qasm_simulator')
result = execute(qc,backend, shots=shots).result().get_counts()
states = sorted([[result[i]/shots, i] for i in result], reverse=True)
res = [int(i[1],2) for i in states]
if len(res) > 1 and states[1][0] > 0.1:
print('The phase is between:', res[0]/2**n, res[1]/2**n)
else:
print('The phase is:', res[0]/2**n)
print('Integer number:', res[:2])
plot_histogram(result, figsize = (22,6))
# for i in range(n):
# qc.cp()
|
https://github.com/carstenblank/dc-qiskit-stochastics
|
carstenblank
|
# Copyright 2018-2022 Carsten Blank
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import logging
import unittest
from typing import Optional
import matplotlib.pyplot as plt
import numpy as np
import qiskit
from qiskit.circuit import Parameter
from dc_qiskit_stochastics.benchmark import char_func_asian_option, char_func_asian_option_sm
from dc_qiskit_stochastics.dsp_state_machine import StateMachineDSP
from dc_qiskit_stochastics.simulation.asian_option import AsianOptionPricing, StateMachineDescription
from dc_quantum_scheduling import processor
from dc_quantum_scheduling.models import PreparedExperiment, RunningExperiment, FinishedExperiment
from dsp_data import testing_data_state_machine
logging.basicConfig(format=f'%(asctime)s::{logging.BASIC_FORMAT}', level='ERROR')
LOG = logging.getLogger(__name__)
class StateMachineTest(unittest.TestCase):
def test_init_success(self):
data = {
'initial_value': 0,
'probabilities': np.asarray([
[
[0.1, 0.6]
],
[
[0.1, 0.6, 0.3],
[0.5, 0.3, 0.1]
],
[
[0.1, 0.6],
[0.5, 0.3],
[0.1, 0.1]
]
]),
'realizations': np.asarray([
[
[1, 1]
],
[
[1, 1, 1],
[1, 1, 1]
],
[
[1, 1],
[1, 1],
[1, 1]
]
])
}
try:
StateMachineDSP(data['initial_value'], data['probabilities'], data['realizations'])
except AssertionError:
self.fail()
def test_init_fail(self):
data = {
'initial_value': 0,
'probabilities': np.asarray([
[
[0.1, 0.6]
],
[
[0.1, 0.6, 0.3],
[0.5, 0.3, 0.1],
[0.5, 0.3, 0.1]
],
[
[0.1, 0.6],
[0.5, 0.3],
[0.1, 0.1]
]
]),
'realizations': np.asarray([
[
[1, 1]
],
[
[1, 1, 1],
[1, 1, 1],
[1, 1, 1]
],
[
[1, 1],
[1, 1],
[1, 1]
]
])
}
try:
StateMachineDSP(data['initial_value'], data['probabilities'], data['realizations'])
except AssertionError:
return
self.fail()
def test_full(self):
for i, data in enumerate(testing_data_state_machine):
print(f'Test on data {i}.')
process = StateMachineDSP(data['initial_value'], data['probabilities'], data['realizations'])
qc = process._proposition_one_circuit(Parameter('v'))
qc_t = qiskit.transpile(
qc, basis_gates=['uni_rot_rx', 'uni_rot_ry', 'uni_rot_rz', 'uni_rot_rx_dg', 'uni_rot_ry_dg',
'uni_rot_rz_dg', 'uni_rot_u1', 'uni_rot_u1_dg', 'h', 'u1']
)
print(qc_t.draw(fold=-1))
qc_t = qiskit.transpile(qc, basis_gates=['u1', 'u2', 'u3', 'cx'], optimization_level=3)
print(qc_t.draw(fold=-1))
print(f'Depth of final circuit: {qc_t.depth()}')
def test_log_normal(self):
log_normal_data = {
'risk_free_interest': 0.02,
'volatility': 0.05,
'start_value': 80,
'time_steps': np.asarray([5]),
'discretization': 2**4
}
s0 = log_normal_data['start_value']
sigma = log_normal_data['volatility']
mu = log_normal_data['risk_free_interest']
time_steps = log_normal_data['time_steps']
discretization = log_normal_data['discretization']
asian_option_model = AsianOptionPricing(s0, sigma, mu, time_steps, discretization)
data = asian_option_model.get_state_machine_model()
v = np.linspace(-0.3, 0.3, num=400)
# TODO: test the benchmark separately with this:
# # As this is just the lognormal distribution, we can directly brute-force compute the outcome.
# phi_v_sim = []
# for entry in v:
# summands = data.probabilities[0] * np.exp(1.0j * entry * data.realizations)
# summed = np.sum(summands)
# phi_v_sim.append(summed)
# phi_v_sim = np.asarray(phi_v_sim)
phi_v_sim = char_func_asian_option_sm(v, asian_option_model)
# The quantum approach is created here
state_machine = StateMachineDSP(data.initial_value, data.probabilities, data.realizations)
pre_exp: PreparedExperiment = state_machine.characteristic_function(
evaluations=v, other_arguments={'shots': 2000, 'with_barrier': True}
)
print(pre_exp.parameters['qc_cos'].draw(fold=-1))
run_exp: RunningExperiment = processor.execute_simulation(pre_exp)
fin_exp: Optional[FinishedExperiment] = run_exp.wait()
phi_v_qc = fin_exp.get_output()
# The MC benchmark computation
phi_v = char_func_asian_option(
asian_option_model.mu,
asian_option_model.sigma,
asian_option_model.s0,
asian_option_model.time_steps,
samples=2000,
evaluations=v
)
# TODO: remove if not needed
# s = sigma * np.sqrt(delta_t)
# mu_tilde = (mu - 0.5 * sigma ** 2) * delta_t + np.log(s0)
# phi_v_benchmark_m = np.asarray(
# [(1.0j * v) ** n / factorial(n) * np.exp(n * mu_tilde + 0.5 * n**2 * s**2) for n in range(1000)]
# )
# phi_v = np.sum(phi_v_benchmark_m, axis=0, where=~np.isnan(phi_v_benchmark_m))
# Plotting party
plt.plot(v, np.real(phi_v_sim), color='gray', alpha=0.7, label='QC-TH')
plt.scatter(x=v, y=np.real(phi_v_qc), color='blue', alpha=1.0, label='QC', marker='.')
plt.plot(v, np.real(phi_v), color='black', label='MC')
plt.axvline(x=0, color='purple')
plt.title(f'StateMachineTest.test_log_normal\nReal part (cosine) at {time_steps}')
plt.ylim((-1.1, 1.1))
plt.legend()
plt.show()
plt.plot(v, np.imag(phi_v_sim), color='gray', alpha=0.7, label='QC-TH')
plt.scatter(x=v, y=np.imag(phi_v_qc), color='blue', alpha=0.7, label='QC', marker='.')
plt.plot(v, np.imag(phi_v), color='black', label='MC')
plt.axvline(x=0, color='purple')
plt.title(f'StateMachineTest.test_log_normal\nImaginary part (sine) at {time_steps}')
plt.ylim((-1.1, 1.1))
plt.legend()
plt.show()
def test_asian_option(self):
log_normal_data = {
'risk_free_interest': 0.02,
'volatility': 0.05,
'start_value': 80,
'time_steps': np.asarray([5, 10]),
'discretization': 2**4
}
s0 = log_normal_data['start_value']
sigma = log_normal_data['volatility']
mu = log_normal_data['risk_free_interest']
time_steps = log_normal_data['time_steps']
discretization = log_normal_data['discretization']
asian_option_model = AsianOptionPricing(s0, sigma, mu, time_steps, discretization)
data: StateMachineDescription = asian_option_model.get_state_machine_model()
v = np.linspace(-0.3, 0.3, num=400)
# The brute force calculation using the state machine description
phi_v_sim = char_func_asian_option_sm(v, asian_option_model)
# The quantum approach is created here
state_machine = StateMachineDSP(data.initial_value, data.probabilities, data.realizations)
pre_exp: PreparedExperiment = state_machine.characteristic_function(
evaluations=v, other_arguments={'shots': 2000, 'with_barrier': True}
)
print(qiskit.transpile(pre_exp.parameters['qc_cos']).draw(fold=-1))
run_exp: RunningExperiment = processor.execute_simulation(pre_exp)
fin_exp: Optional[FinishedExperiment] = run_exp.wait()
phi_v_qc = fin_exp.get_output()
# The MC benchmark computation
phi_v = char_func_asian_option(
asian_option_model.mu,
asian_option_model.sigma,
asian_option_model.s0,
asian_option_model.time_steps,
samples=2000,
evaluations=v
)
# Plotting party
plt.plot(v, np.real(phi_v_sim), color='gray', alpha=0.7, label='QC-TH')
plt.scatter(x=v, y=np.real(phi_v_qc), color='blue', alpha=1.0, label='QC', marker='.')
plt.plot(v, np.real(phi_v), color='black', label='MC')
plt.axvline(x=0, color='purple')
plt.title(f'StateMachineTest.test_asian_option\nReal part (cosine) at {time_steps}')
plt.ylim((-1.1, 1.1))
plt.legend()
plt.show()
plt.plot(v, np.imag(phi_v_sim), color='gray', alpha=0.7, label='QC-TH')
plt.scatter(x=v, y=np.imag(phi_v_qc), color='blue', alpha=0.7, label='QC', marker='.')
plt.plot(v, np.imag(phi_v), color='black', label='MC')
plt.axvline(x=0, color='purple')
plt.title(f'StateMachineTest.test_asian_option\nImaginary part (sine) at {time_steps}')
plt.ylim((-1.1, 1.1))
plt.legend()
plt.show()
|
https://github.com/Naphann/Solving-TSP-Grover
|
Naphann
|
#initialization
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
# importing Qiskit
from qiskit import IBMQ, BasicAer, Aer
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
provider = IBMQ.load_account()
#functions
# def OR(a, b, k):
# # enter qubit numbers here
# """ function does the equivalent of a classical OR between nodes a and b and stores the result in k """
# qc.barrier(q)
# qc.cx(q[a], q[k])
# qc.barrier(q)
# qc.x(q[a])
# qc.barrier(q)
# qc.ccx(q[a], q[b], q[k])
# qc.barrier(q)
# qc.x(q[a])
# qc.barrier(q)
def OR(qubit_1, qubit_2, k):
# enter qubit numbers here
""" function does the equivalent of a classical OR between qubit numbers a and b and stores the result in qubit number k """
qc.barrier(q)
qc.x(q[qubit_1])
qc.x(q[qubit_2])
qc.barrier(q)
qc.ccx(q[qubit_1], q[qubit_2], q[k])
qc.x(q[k])
qc.barrier(q)
qc.x(q[qubit_1])
qc.x(q[qubit_2])
qc.barrier(q)
def are_not_equal(a_0, b_0, k):
# enter node numbers here. For example, a is node 0, b is node 1 and c is node 2
""" function outputs 1 if nodes a and b are not the same. Node numbering starts from 0
as in the problem statement. k is the qubit number where the output is XOR-ed. qubit
numbering also starts from 0 """
qc.barrier(q)
qc.cx(q[2*a_0], q[2*b_0])
qc.cx(q[(2*a_0) + 1], q[(2*b_0) + 1])
OR(2*b_0, (2*b_0)+1, k)
qc.cx(q[2*a_0], q[2*b_0])
qc.cx(q[(2*a_0) + 1], q[(2*b_0) + 1])
qc.barrier(q)
# number of nodes
def initialize_oracle_part():
qc.h(q[0:6])
qc.barrier(q)
are_not_equal(0, 1, 6) # node a and b are not equal
are_not_equal(0, 2, 7)
are_not_equal(1, 2, 8)
qc.barrier(q)
qc.mct([q[6], q[7], q[8]], q[10],[q[9]]) # answer is stored in 10. please keep 9 a clean qubit, it's used as ancilla here
qc.barrier(q)
are_not_equal(0, 1, 6) # node a and b are not equal
are_not_equal(0, 2, 7)
are_not_equal(1, 2, 8)
def diffusion():
qc.h(q[0:6])
qc.x(q[0:6])
qc.h(q[5])
qc.barrier()
qc.mct([q[0], q[1], q[2], q[3], q[4]], q[5], [q[11], q[12], q[13]])
qc.barrier()
qc.h(q[5])
qc.x(q[0:6])
qc.h(q[0:6])
def grover(iter):
for i in range(iter):
initialize_oracle_part()
diffusion()
qubit_num = 20 # max is 32 if you're using the simulator
q = QuantumRegister(qubit_num)
c = ClassicalRegister(14)
qc = QuantumCircuit(q, c)
qc.x(q[10])
qc.h(q[10])
grover(2)
qc.measure(q[0:6], c[0:6])
qc.draw()
# running and getting results
backend = Aer.get_backend('qasm_simulator')
job = execute(qc, backend, shots=1000)
# backend = provider.get_backend('ibmq_qasm_simulator')
# job = execute(qc, backend=backend, shots=8000, seed_simulator=12345, backend_options={"fusion_enable":True})
result = job.result()
count = result.get_counts()
print(count)
#sort count
count_sorted = sorted(count.items(), key=lambda x:x[1], reverse=True)
# collect answers with Top 9 probability
ans_list = count_sorted[0:9]
print(ans_list)
|
https://github.com/swe-train/qiskit__qiskit
|
swe-train
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test registerless QuantumCircuit and Gates on wires"""
import numpy
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.circuit import Qubit, Clbit, AncillaQubit
from qiskit.circuit.exceptions import CircuitError
from qiskit.test import QiskitTestCase
class TestRegisterlessCircuit(QiskitTestCase):
"""Test registerless QuantumCircuit."""
def test_circuit_constructor_qwires(self):
"""Create a QuantumCircuit directly with quantum wires"""
circuit = QuantumCircuit(2)
expected = QuantumCircuit(QuantumRegister(2, "q"))
self.assertEqual(circuit, expected)
def test_circuit_constructor_wires_wrong(self):
"""Create a registerless QuantumCircuit wrongly"""
self.assertRaises(CircuitError, QuantumCircuit, 1, 2, 3) # QuantumCircuit(1, 2, 3)
def test_circuit_constructor_wires_wrong_mix(self):
"""Create an almost-registerless QuantumCircuit"""
# QuantumCircuit(1, ClassicalRegister(2))
self.assertRaises(CircuitError, QuantumCircuit, 1, ClassicalRegister(2))
class TestAddingBitsWithoutRegisters(QiskitTestCase):
"""Test adding Bit instances outside of Registers."""
def test_circuit_constructor_on_bits(self):
"""Verify we can add bits directly to a circuit."""
qubits = [Qubit(), Qubit()]
clbits = [Clbit()]
ancillas = [AncillaQubit(), AncillaQubit()]
qc = QuantumCircuit(qubits, clbits, ancillas)
self.assertEqual(qc.qubits, qubits + ancillas)
self.assertEqual(qc.clbits, clbits)
self.assertEqual(qc.ancillas, ancillas)
self.assertEqual(qc.qregs, [])
self.assertEqual(qc.cregs, [])
def test_circuit_constructor_on_invalid_bits(self):
"""Verify we raise if passed not a Bit."""
with self.assertRaisesRegex(CircuitError, "Expected an instance of"):
_ = QuantumCircuit([3.14])
def test_raise_if_bits_already_present(self):
"""Verify we raise when attempting to add a Bit already in the circuit."""
qubits = [Qubit()]
with self.assertRaisesRegex(CircuitError, "bits found already"):
_ = QuantumCircuit(qubits, qubits)
qc = QuantumCircuit(qubits)
with self.assertRaisesRegex(CircuitError, "bits found already"):
qc.add_bits(qubits)
qr = QuantumRegister(1, "qr")
qc = QuantumCircuit(qr)
with self.assertRaisesRegex(CircuitError, "bits found already"):
qc.add_bits(qr[:])
def test_addding_individual_bit(self):
"""Verify we can add a single bit to a circuit."""
qr = QuantumRegister(3, "qr")
qc = QuantumCircuit(qr)
new_bit = Qubit()
qc.add_bits([new_bit])
self.assertEqual(qc.qubits, list(qr) + [new_bit])
self.assertEqual(qc.qregs, [qr])
def test_inserted_ancilla_bits_are_added_to_qubits(self):
"""Verify AncillaQubits added via .add_bits are added to .qubits."""
anc = AncillaQubit()
qb = Qubit()
qc = QuantumCircuit()
qc.add_bits([anc, qb])
self.assertEqual(qc.qubits, [anc, qb])
class TestGatesOnWires(QiskitTestCase):
"""Test gates on wires."""
def test_circuit_single_wire_h(self):
"""Test circuit on wire (H gate)."""
qreg = QuantumRegister(2)
circuit = QuantumCircuit(qreg)
circuit.h(1)
expected = QuantumCircuit(qreg)
expected.h(qreg[1])
self.assertEqual(circuit, expected)
def test_circuit_two_wire_cx(self):
"""Test circuit two wires (CX gate)."""
qreg = QuantumRegister(2)
expected = QuantumCircuit(qreg)
expected.cx(qreg[0], qreg[1])
circuit = QuantumCircuit(qreg)
circuit.cx(0, 1)
self.assertEqual(circuit, expected)
def test_circuit_single_wire_measure(self):
"""Test circuit on wire (measure gate)."""
qreg = QuantumRegister(2)
creg = ClassicalRegister(2)
circuit = QuantumCircuit(qreg, creg)
circuit.measure(1, 1)
expected = QuantumCircuit(qreg, creg)
expected.measure(qreg[1], creg[1])
self.assertEqual(circuit, expected)
def test_circuit_multi_qregs_h(self):
"""Test circuit multi qregs and wires (H gate)."""
qreg0 = QuantumRegister(2)
qreg1 = QuantumRegister(2)
circuit = QuantumCircuit(qreg0, qreg1)
circuit.h(0)
circuit.h(2)
expected = QuantumCircuit(qreg0, qreg1)
expected.h(qreg0[0])
expected.h(qreg1[0])
self.assertEqual(circuit, expected)
def test_circuit_multi_qreg_cregs_measure(self):
"""Test circuit multi qregs/cregs and wires (measure)."""
qreg0 = QuantumRegister(2)
creg0 = ClassicalRegister(2)
qreg1 = QuantumRegister(2)
creg1 = ClassicalRegister(2)
circuit = QuantumCircuit(qreg0, qreg1, creg0, creg1)
circuit.measure(0, 2)
circuit.measure(2, 1)
expected = QuantumCircuit(qreg0, qreg1, creg0, creg1)
expected.measure(qreg0[0], creg1[0])
expected.measure(qreg1[0], creg0[1])
self.assertEqual(circuit, expected)
def test_circuit_barrier(self):
"""Test barrier on wires."""
qreg01 = QuantumRegister(2)
qreg23 = QuantumRegister(2)
circuit = QuantumCircuit(qreg01, qreg23)
circuit.barrier(0)
circuit.barrier(2)
expected = QuantumCircuit(qreg01, qreg23)
expected.barrier(qreg01[0])
expected.barrier(qreg23[0])
self.assertEqual(circuit, expected)
def test_circuit_conditional(self):
"""Test conditional on wires."""
qreg = QuantumRegister(2)
creg = ClassicalRegister(4)
circuit = QuantumCircuit(qreg, creg)
circuit.h(0).c_if(creg, 3)
expected = QuantumCircuit(qreg, creg)
expected.h(qreg[0]).c_if(creg, 3)
self.assertEqual(circuit, expected)
def test_circuit_qwire_out_of_range(self):
"""Fail if quantum wire is out of range."""
qreg = QuantumRegister(2)
circuit = QuantumCircuit(qreg)
self.assertRaises(CircuitError, circuit.h, 99) # circuit.h(99)
def test_circuit_cwire_out_of_range(self):
"""Fail if classical wire is out of range."""
qreg = QuantumRegister(2)
creg = ClassicalRegister(2)
circuit = QuantumCircuit(qreg, creg)
self.assertRaises(CircuitError, circuit.measure, 1, 99) # circuit.measure(1, 99)
def test_circuit_initialize(self):
"""Test initialize on wires."""
init_vector = [0.5, 0.5, 0.5, 0.5]
qreg01 = QuantumRegister(2)
qreg23 = QuantumRegister(2)
circuit = QuantumCircuit(qreg01, qreg23)
circuit.initialize(init_vector, [0, 2])
expected = QuantumCircuit(qreg01, qreg23)
expected.initialize(init_vector, [qreg01[0], qreg23[0]])
self.assertEqual(circuit, expected)
def test_circuit_initialize_single_qubit(self):
"""Test initialize on single qubit."""
init_vector = [numpy.sqrt(0.5), numpy.sqrt(0.5)]
qreg = QuantumRegister(2)
circuit = QuantumCircuit(qreg)
circuit.initialize(init_vector, qreg[0])
expected = QuantumCircuit(qreg)
expected.initialize(init_vector, [qreg[0]])
self.assertEqual(circuit, expected)
def test_mixed_register_and_registerless_indexing(self):
"""Test indexing if circuit contains bits in and out of registers."""
bits = [Qubit(), Qubit()]
qreg = QuantumRegister(3, "q")
circuit = QuantumCircuit(bits, qreg)
for i in range(len(circuit.qubits)):
circuit.rz(i, i)
expected_qubit_order = bits + qreg[:]
expected_circuit = QuantumCircuit(bits, qreg)
for i in range(len(expected_circuit.qubits)):
expected_circuit.rz(i, expected_qubit_order[i])
self.assertEqual(circuit.data, expected_circuit.data)
class TestGatesOnWireRange(QiskitTestCase):
"""Test gates on wire range."""
def test_wire_range(self):
"""Test gate wire range"""
qreg = QuantumRegister(4)
circuit = QuantumCircuit(qreg)
circuit.h(range(0, 2))
expected = QuantumCircuit(qreg)
expected.h(qreg[0:2])
self.assertEqual(circuit, expected)
def test_circuit_multi_qregs_h(self):
"""Test circuit multi qregs in range of wires (H gate)."""
qreg0 = QuantumRegister(2)
qreg1 = QuantumRegister(2)
circuit = QuantumCircuit(qreg0, qreg1)
circuit.h(range(0, 3))
expected = QuantumCircuit(qreg0, qreg1)
expected.h(qreg0[0])
expected.h(qreg0[1])
expected.h(qreg1[0])
self.assertEqual(circuit, expected)
def test_circuit_multi_qreg_cregs_measure(self):
"""Test circuit multi qregs in range of wires (measure)."""
qreg0 = QuantumRegister(2)
creg0 = ClassicalRegister(2)
qreg1 = QuantumRegister(2)
creg1 = ClassicalRegister(2)
circuit = QuantumCircuit(qreg0, qreg1, creg0, creg1)
circuit.measure(range(1, 3), range(0, 4, 2))
expected = QuantumCircuit(qreg0, qreg1, creg0, creg1)
expected.measure(qreg0[1], creg0[0])
expected.measure(qreg1[0], creg1[0])
self.assertEqual(circuit, expected)
def test_circuit_barrier(self):
"""Test barrier on range of wires with multi regs."""
qreg01 = QuantumRegister(2)
qreg23 = QuantumRegister(2)
circuit = QuantumCircuit(qreg01, qreg23)
circuit.barrier(range(0, 3))
expected = QuantumCircuit(qreg01, qreg23)
expected.barrier(qreg01[0], qreg01[1], qreg23[0])
self.assertEqual(circuit, expected)
def test_circuit_initialize(self):
"""Test initialize on wires."""
init_vector = [0.5, 0.5, 0.5, 0.5]
qreg01 = QuantumRegister(2)
qreg23 = QuantumRegister(2)
circuit = QuantumCircuit(qreg01, qreg23)
circuit.initialize(init_vector, range(1, 3))
expected = QuantumCircuit(qreg01, qreg23)
expected.initialize(init_vector, [qreg01[1], qreg23[0]])
self.assertEqual(circuit, expected)
def test_circuit_conditional(self):
"""Test conditional on wires."""
qreg0 = QuantumRegister(2)
qreg1 = QuantumRegister(2)
creg = ClassicalRegister(2)
circuit = QuantumCircuit(qreg0, qreg1, creg)
circuit.h(range(1, 3)).c_if(creg, 3)
expected = QuantumCircuit(qreg0, qreg1, creg)
expected.h(qreg0[1]).c_if(creg, 3)
expected.h(qreg1[0]).c_if(creg, 3)
self.assertEqual(circuit, expected)
def test_circuit_qwire_out_of_range(self):
"""Fail if quantum wire is out of range."""
qreg = QuantumRegister(2)
circuit = QuantumCircuit(qreg)
self.assertRaises(CircuitError, circuit.h, range(9, 99)) # circuit.h(range(9,99))
def test_circuit_cwire_out_of_range(self):
"""Fail if classical wire is out of range."""
qreg = QuantumRegister(2)
creg = ClassicalRegister(2)
circuit = QuantumCircuit(qreg, creg)
# circuit.measure(1, range(9,99))
self.assertRaises(CircuitError, circuit.measure, 1, range(9, 99))
class TestGatesOnWireSlice(QiskitTestCase):
"""Test gates on wire slice."""
def test_wire_slice(self):
"""Test gate wire slice"""
qreg = QuantumRegister(4)
circuit = QuantumCircuit(qreg)
circuit.h(slice(0, 2))
expected = QuantumCircuit(qreg)
expected.h(qreg[0:2])
self.assertEqual(circuit, expected)
def test_wire_list(self):
"""Test gate wire list of integers"""
qreg = QuantumRegister(4)
circuit = QuantumCircuit(qreg)
circuit.h([0, 1])
expected = QuantumCircuit(qreg)
expected.h(qreg[0:2])
self.assertEqual(circuit, expected)
def test_wire_np_int(self):
"""Test gate wire with numpy int"""
numpy_int = numpy.dtype("int").type(2)
qreg = QuantumRegister(4)
circuit = QuantumCircuit(qreg)
circuit.h(numpy_int)
expected = QuantumCircuit(qreg)
expected.h(qreg[2])
self.assertEqual(circuit, expected)
def test_wire_np_1d_array(self):
"""Test gate wire with numpy array (one-dimensional)"""
numpy_arr = numpy.array([0, 1])
qreg = QuantumRegister(4)
circuit = QuantumCircuit(qreg)
circuit.h(numpy_arr)
expected = QuantumCircuit(qreg)
expected.h(qreg[0])
expected.h(qreg[1])
self.assertEqual(circuit, expected)
def test_circuit_multi_qregs_h(self):
"""Test circuit multi qregs in slices of wires (H gate)."""
qreg0 = QuantumRegister(2)
qreg1 = QuantumRegister(2)
circuit = QuantumCircuit(qreg0, qreg1)
circuit.h(slice(0, 3))
expected = QuantumCircuit(qreg0, qreg1)
expected.h(qreg0[0])
expected.h(qreg0[1])
expected.h(qreg1[0])
self.assertEqual(circuit, expected)
def test_circuit_multi_qreg_cregs_measure(self):
"""Test circuit multi qregs in slices of wires (measure)."""
qreg0 = QuantumRegister(2)
creg0 = ClassicalRegister(2)
qreg1 = QuantumRegister(2)
creg1 = ClassicalRegister(2)
circuit = QuantumCircuit(qreg0, qreg1, creg0, creg1)
circuit.measure(slice(1, 3), slice(0, 4, 2))
expected = QuantumCircuit(qreg0, qreg1, creg0, creg1)
expected.measure(qreg0[1], creg0[0])
expected.measure(qreg1[0], creg1[0])
self.assertEqual(circuit, expected)
def test_circuit_barrier(self):
"""Test barrier on slice of wires with multi regs."""
qreg01 = QuantumRegister(2)
qreg23 = QuantumRegister(2)
circuit = QuantumCircuit(qreg01, qreg23)
circuit.barrier(slice(0, 3))
expected = QuantumCircuit(qreg01, qreg23)
expected.barrier([qreg01[0], qreg01[1], qreg23[0]])
self.assertEqual(circuit, expected)
def test_circuit_initialize(self):
"""Test initialize on wires."""
init_vector = [0.5, 0.5, 0.5, 0.5]
qreg01 = QuantumRegister(2)
qreg23 = QuantumRegister(2)
circuit = QuantumCircuit(qreg01, qreg23)
circuit.initialize(init_vector, slice(1, 3))
expected = QuantumCircuit(qreg01, qreg23)
expected.initialize(init_vector, [qreg01[1], qreg23[0]])
self.assertEqual(circuit, expected)
def test_circuit_conditional(self):
"""Test conditional on wires."""
qreg0 = QuantumRegister(2)
qreg1 = QuantumRegister(2)
creg = ClassicalRegister(2)
circuit = QuantumCircuit(qreg0, qreg1, creg)
circuit.h(slice(1, 3)).c_if(creg, 3)
expected = QuantumCircuit(qreg0, qreg1, creg)
expected.h(qreg0[1]).c_if(creg, 3)
expected.h(qreg1[0]).c_if(creg, 3)
self.assertEqual(circuit, expected)
def test_circuit_qwire_out_of_range(self):
"""Fail if quantum wire is out of range."""
qreg = QuantumRegister(2)
circuit = QuantumCircuit(qreg)
self.assertRaises(CircuitError, circuit.h, slice(9, 99)) # circuit.h(slice(9,99))
def test_circuit_cwire_out_of_range(self):
"""Fail if classical wire is out of range."""
qreg = QuantumRegister(2)
creg = ClassicalRegister(2)
circuit = QuantumCircuit(qreg, creg)
# circuit.measure(1, slice(9,99))
self.assertRaises(CircuitError, circuit.measure, 1, slice(9, 99))
def test_wire_np_2d_array(self):
"""Test gate wire with numpy array (two-dimensional). Raises."""
numpy_arr = numpy.array([[0, 1], [2, 3]])
qreg = QuantumRegister(4)
circuit = QuantumCircuit(qreg)
self.assertRaises(CircuitError, circuit.h, numpy_arr) # circuit.h(numpy_arr)
class TestBitConditional(QiskitTestCase):
"""Test gates with single bit conditionals."""
def test_bit_conditional_single_gate(self):
"""Test circuit with a single gate conditioned on a bit."""
qreg = QuantumRegister(1)
creg = ClassicalRegister(2)
circuit = QuantumCircuit(qreg, creg)
circuit.h(0).c_if(0, True)
expected = QuantumCircuit(qreg, creg)
expected.h(qreg[0]).c_if(creg[0], True)
self.assertEqual(circuit, expected)
def test_bit_conditional_multiple_gates(self):
"""Test circuit with multiple gates conditioned on individual bits."""
qreg = QuantumRegister(2)
creg = ClassicalRegister(2)
creg1 = ClassicalRegister(1)
circuit = QuantumCircuit(qreg, creg, creg1)
circuit.h(0).c_if(0, True)
circuit.h(1).c_if(1, False)
circuit.cx(1, 0).c_if(2, True)
expected = QuantumCircuit(qreg, creg, creg1)
expected.h(qreg[0]).c_if(creg[0], True)
expected.h(qreg[1]).c_if(creg[1], False)
expected.cx(qreg[1], qreg[0]).c_if(creg1[0], True)
self.assertEqual(circuit, expected)
|
https://github.com/steffencruz/FockWits
|
steffencruz
|
from CVCircuit import CVCircuit
import numpy as np
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from ops import Interferometer
def gbs(z, U, n_qubits_per_mode=2, n_qumodes=4):
qr = QuantumRegister(n_qubits_per_mode*n_qumodes)
cr = ClassicalRegister(n_qubits_per_mode*n_qumodes)
circuit = QuantumCircuit(qr, cr)
cv_circuit = CVCircuit(circuit, qr, n_qubits_per_mode)
interferometer = Interferometer(U)
for n in range(4):
cv_circuit.SGate(z, n)
for n, m, theta, phi, N in interferometer.BS1:
if np.round(phi, 13) != 0:
cv_circuit.RGate(phi, n)
if np.round(theta, 13) != 0:
cv_circuit.BSGate(theta, [n, m])
for n, expphi in enumerate(interferometer.R):
if np.round(expphi, 13) != 1.0:
q = log(expphi).imag
cv_circuit.RGate(q, n)
for n, m, theta, phi, N in reversed(interferometer.BS2):
if np.round(theta, 13) != 0:
cv_circuit.BSgate(-theta, [n, m])
if np.round(phi, 13) != 0:
cv_circuit.RGate(-phi, n)
result = []
for i in range(4):
result.append(cv_circuit.Measure(i))
return result
if __name__ == '__main__':
U = np.array([
[0.219546940711 - 0.256534554457j, 0.611076853957 + 0.524178937791j,
-0.102700187435 + 0.474478834685j, -0.027250232925 + 0.03729094623j],
[0.451281863394 + 0.602582912475j, 0.456952590016 + 0.01230749109j,
0.131625867435 - 0.450417744715j, 0.035283194078 - 0.053244267184j],
[0.038710094355 + 0.492715562066j, -0.019212744068 - 0.321842852355j,
-0.240776471286 + 0.524432833034j, -0.458388143039 + 0.329633367819j],
[-0.156619083736 + 0.224568570065j, 0.109992223305 - 0.163750223027j,
-0.421179844245 + 0.183644837982j, 0.818769184612 + 0.068015658737j]
])
"""print(TiUs)
print(TUs)
print(phis)"""
gbs(1, U)
|
https://github.com/Qiskit-Extensions/circuit-knitting-toolbox
|
Qiskit-Extensions
|
from qiskit.circuit.library import EfficientSU2
qc = EfficientSU2(4, entanglement="linear", reps=2).decompose()
qc.assign_parameters([0.4] * len(qc.parameters), inplace=True)
qc.draw("mpl", scale=0.8)
from qiskit.quantum_info import SparsePauliOp
observable = SparsePauliOp(["ZZII", "IZZI", "-IIZZ", "XIXI", "ZIZZ", "IXIX"])
from circuit_knitting.cutting import partition_problem
partitioned_problem = partition_problem(
circuit=qc, partition_labels="AABB", observables=observable.paulis
)
subcircuits = partitioned_problem.subcircuits
subobservables = partitioned_problem.subobservables
bases = partitioned_problem.bases
subobservables
subcircuits["A"].draw("mpl", scale=0.8)
subcircuits["B"].draw("mpl", scale=0.8)
import numpy as np
print(f"Sampling overhead: {np.prod([basis.overhead for basis in bases])}")
from circuit_knitting.cutting import generate_cutting_experiments
subexperiments, coefficients = generate_cutting_experiments(
circuits=subcircuits, observables=subobservables, num_samples=np.inf
)
from qiskit_ibm_runtime.fake_provider import FakeManilaV2
backend = FakeManilaV2()
from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager
# Transpile the subexperiments to ISA circuits
pass_manager = generate_preset_pass_manager(optimization_level=1, backend=backend)
isa_subexperiments = {
label: pass_manager.run(partition_subexpts)
for label, partition_subexpts in subexperiments.items()
}
from qiskit_ibm_runtime import SamplerV2, Batch
# Submit each partition's subexperiments to the Qiskit Runtime Sampler
# primitive, in a single batch so that the jobs will run back-to-back.
with Batch(backend=backend) as batch:
sampler = SamplerV2(mode=batch)
jobs = {
label: sampler.run(subsystem_subexpts, shots=2**12)
for label, subsystem_subexpts in isa_subexperiments.items()
}
# Retrieve results
results = {label: job.result() for label, job in jobs.items()}
from circuit_knitting.cutting import reconstruct_expectation_values
# Get expectation values for each observable term
reconstructed_expvals = reconstruct_expectation_values(
results,
coefficients,
subobservables,
)
# Reconstruct final expectation value
final_expval = np.dot(reconstructed_expvals, observable.coeffs)
from qiskit_aer.primitives import EstimatorV2
estimator = EstimatorV2()
exact_expval = estimator.run([(qc, observable)]).result()[0].data.evs
print(f"Reconstructed expectation value: {np.real(np.round(final_expval, 8))}")
print(f"Exact expectation value: {np.round(exact_expval, 8)}")
print(f"Error in estimation: {np.real(np.round(final_expval-exact_expval, 8))}")
print(
f"Relative error in estimation: {np.real(np.round((final_expval-exact_expval) / exact_expval, 8))}"
)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
qr = QuantumRegister(3, 'q')
anc = QuantumRegister(1, 'ancilla')
cr = ClassicalRegister(3, 'c')
qc = QuantumCircuit(qr, anc, cr)
qc.x(anc[0])
qc.h(anc[0])
qc.h(qr[0:3])
qc.cx(qr[0:3], anc[0])
qc.h(qr[0:3])
qc.barrier(qr)
qc.measure(qr, cr)
qc.draw('mpl')
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import IBMQ, transpile
from qiskit import QuantumCircuit
from qiskit_aer import AerSimulator
from qiskit.tools.visualization import plot_histogram
from qiskit.providers.fake_provider import FakeVigo
device_backend = FakeVigo()
# Construct quantum circuit
circ = QuantumCircuit(3, 3)
circ.h(0)
circ.cx(0, 1)
circ.cx(1, 2)
circ.measure([0, 1, 2], [0, 1, 2])
sim_ideal = AerSimulator()
# Execute and get counts
result = sim_ideal.run(transpile(circ, sim_ideal)).result()
counts = result.get_counts(0)
plot_histogram(counts, title='Ideal counts for 3-qubit GHZ state')
sim_vigo = AerSimulator.from_backend(device_backend)
# Transpile the circuit for the noisy basis gates
tcirc = transpile(circ, sim_vigo)
# Execute noisy simulation and get counts
result_noise = sim_vigo.run(tcirc).result()
counts_noise = result_noise.get_counts(0)
plot_histogram(counts_noise,
title="Counts for 3-qubit GHZ state with device noise model")
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import matplotlib.pyplot as plt
import numpy as np
from IPython.display import clear_output
from qiskit import QuantumCircuit
from qiskit.algorithms.optimizers import COBYLA, L_BFGS_B
from qiskit.circuit import Parameter
from qiskit.circuit.library import RealAmplitudes, ZZFeatureMap
from qiskit.utils import algorithm_globals
from qiskit_machine_learning.algorithms.classifiers import NeuralNetworkClassifier, VQC
from qiskit_machine_learning.algorithms.regressors import NeuralNetworkRegressor, VQR
from qiskit_machine_learning.neural_networks import SamplerQNN, EstimatorQNN
algorithm_globals.random_seed = 42
num_inputs = 2
num_samples = 20
X = 2 * algorithm_globals.random.random([num_samples, num_inputs]) - 1
y01 = 1 * (np.sum(X, axis=1) >= 0) # in { 0, 1}
y = 2 * y01 - 1 # in {-1, +1}
y_one_hot = np.zeros((num_samples, 2))
for i in range(num_samples):
y_one_hot[i, y01[i]] = 1
for x, y_target in zip(X, y):
if y_target == 1:
plt.plot(x[0], x[1], "bo")
else:
plt.plot(x[0], x[1], "go")
plt.plot([-1, 1], [1, -1], "--", color="black")
plt.show()
# construct QNN
qc = QuantumCircuit(2)
feature_map = ZZFeatureMap(2)
ansatz = RealAmplitudes(2)
qc.compose(feature_map, inplace=True)
qc.compose(ansatz, inplace=True)
qc.draw(output="mpl")
estimator_qnn = EstimatorQNN(
circuit=qc, input_params=feature_map.parameters, weight_params=ansatz.parameters
)
# QNN maps inputs to [-1, +1]
estimator_qnn.forward(X[0, :], algorithm_globals.random.random(estimator_qnn.num_weights))
# callback function that draws a live plot when the .fit() method is called
def callback_graph(weights, obj_func_eval):
clear_output(wait=True)
objective_func_vals.append(obj_func_eval)
plt.title("Objective function value against iteration")
plt.xlabel("Iteration")
plt.ylabel("Objective function value")
plt.plot(range(len(objective_func_vals)), objective_func_vals)
plt.show()
# construct neural network classifier
estimator_classifier = NeuralNetworkClassifier(
estimator_qnn, optimizer=COBYLA(maxiter=60), callback=callback_graph
)
# create empty array for callback to store evaluations of the objective function
objective_func_vals = []
plt.rcParams["figure.figsize"] = (12, 6)
# fit classifier to data
estimator_classifier.fit(X, y)
# return to default figsize
plt.rcParams["figure.figsize"] = (6, 4)
# score classifier
estimator_classifier.score(X, y)
# evaluate data points
y_predict = estimator_classifier.predict(X)
# plot results
# red == wrongly classified
for x, y_target, y_p in zip(X, y, y_predict):
if y_target == 1:
plt.plot(x[0], x[1], "bo")
else:
plt.plot(x[0], x[1], "go")
if y_target != y_p:
plt.scatter(x[0], x[1], s=200, facecolors="none", edgecolors="r", linewidths=2)
plt.plot([-1, 1], [1, -1], "--", color="black")
plt.show()
estimator_classifier.weights
# construct feature map
feature_map = ZZFeatureMap(num_inputs)
# construct ansatz
ansatz = RealAmplitudes(num_inputs, reps=1)
# construct quantum circuit
qc = QuantumCircuit(num_inputs)
qc.append(feature_map, range(num_inputs))
qc.append(ansatz, range(num_inputs))
qc.decompose().draw(output="mpl")
# parity maps bitstrings to 0 or 1
def parity(x):
return "{:b}".format(x).count("1") % 2
output_shape = 2 # corresponds to the number of classes, possible outcomes of the (parity) mapping.
# construct QNN
sampler_qnn = SamplerQNN(
circuit=qc,
input_params=feature_map.parameters,
weight_params=ansatz.parameters,
interpret=parity,
output_shape=output_shape,
)
# construct classifier
sampler_classifier = NeuralNetworkClassifier(
neural_network=sampler_qnn, optimizer=COBYLA(maxiter=30), callback=callback_graph
)
# create empty array for callback to store evaluations of the objective function
objective_func_vals = []
plt.rcParams["figure.figsize"] = (12, 6)
# fit classifier to data
sampler_classifier.fit(X, y01)
# return to default figsize
plt.rcParams["figure.figsize"] = (6, 4)
# score classifier
sampler_classifier.score(X, y01)
# evaluate data points
y_predict = sampler_classifier.predict(X)
# plot results
# red == wrongly classified
for x, y_target, y_p in zip(X, y01, y_predict):
if y_target == 1:
plt.plot(x[0], x[1], "bo")
else:
plt.plot(x[0], x[1], "go")
if y_target != y_p:
plt.scatter(x[0], x[1], s=200, facecolors="none", edgecolors="r", linewidths=2)
plt.plot([-1, 1], [1, -1], "--", color="black")
plt.show()
sampler_classifier.weights
# construct feature map, ansatz, and optimizer
feature_map = ZZFeatureMap(num_inputs)
ansatz = RealAmplitudes(num_inputs, reps=1)
# construct variational quantum classifier
vqc = VQC(
feature_map=feature_map,
ansatz=ansatz,
loss="cross_entropy",
optimizer=COBYLA(maxiter=30),
callback=callback_graph,
)
# create empty array for callback to store evaluations of the objective function
objective_func_vals = []
plt.rcParams["figure.figsize"] = (12, 6)
# fit classifier to data
vqc.fit(X, y_one_hot)
# return to default figsize
plt.rcParams["figure.figsize"] = (6, 4)
# score classifier
vqc.score(X, y_one_hot)
# evaluate data points
y_predict = vqc.predict(X)
# plot results
# red == wrongly classified
for x, y_target, y_p in zip(X, y_one_hot, y_predict):
if y_target[0] == 1:
plt.plot(x[0], x[1], "bo")
else:
plt.plot(x[0], x[1], "go")
if not np.all(y_target == y_p):
plt.scatter(x[0], x[1], s=200, facecolors="none", edgecolors="r", linewidths=2)
plt.plot([-1, 1], [1, -1], "--", color="black")
plt.show()
from sklearn.datasets import make_classification
from sklearn.preprocessing import MinMaxScaler
X, y = make_classification(
n_samples=10,
n_features=2,
n_classes=3,
n_redundant=0,
n_clusters_per_class=1,
class_sep=2.0,
random_state=algorithm_globals.random_seed,
)
X = MinMaxScaler().fit_transform(X)
plt.scatter(X[:, 0], X[:, 1], c=y)
y_cat = np.empty(y.shape, dtype=str)
y_cat[y == 0] = "A"
y_cat[y == 1] = "B"
y_cat[y == 2] = "C"
print(y_cat)
vqc = VQC(
num_qubits=2,
optimizer=COBYLA(maxiter=30),
callback=callback_graph,
)
# create empty array for callback to store evaluations of the objective function
objective_func_vals = []
plt.rcParams["figure.figsize"] = (12, 6)
# fit classifier to data
vqc.fit(X, y_cat)
# return to default figsize
plt.rcParams["figure.figsize"] = (6, 4)
# score classifier
vqc.score(X, y_cat)
predict = vqc.predict(X)
print(f"Predicted labels: {predict}")
print(f"Ground truth: {y_cat}")
num_samples = 20
eps = 0.2
lb, ub = -np.pi, np.pi
X_ = np.linspace(lb, ub, num=50).reshape(50, 1)
f = lambda x: np.sin(x)
X = (ub - lb) * algorithm_globals.random.random([num_samples, 1]) + lb
y = f(X[:, 0]) + eps * (2 * algorithm_globals.random.random(num_samples) - 1)
plt.plot(X_, f(X_), "r--")
plt.plot(X, y, "bo")
plt.show()
# construct simple feature map
param_x = Parameter("x")
feature_map = QuantumCircuit(1, name="fm")
feature_map.ry(param_x, 0)
# construct simple ansatz
param_y = Parameter("y")
ansatz = QuantumCircuit(1, name="vf")
ansatz.ry(param_y, 0)
# construct a circuit
qc = QuantumCircuit(1)
qc.compose(feature_map, inplace=True)
qc.compose(ansatz, inplace=True)
# construct QNN
regression_estimator_qnn = EstimatorQNN(
circuit=qc, input_params=feature_map.parameters, weight_params=ansatz.parameters
)
# construct the regressor from the neural network
regressor = NeuralNetworkRegressor(
neural_network=regression_estimator_qnn,
loss="squared_error",
optimizer=L_BFGS_B(maxiter=5),
callback=callback_graph,
)
# create empty array for callback to store evaluations of the objective function
objective_func_vals = []
plt.rcParams["figure.figsize"] = (12, 6)
# fit to data
regressor.fit(X, y)
# return to default figsize
plt.rcParams["figure.figsize"] = (6, 4)
# score the result
regressor.score(X, y)
# plot target function
plt.plot(X_, f(X_), "r--")
# plot data
plt.plot(X, y, "bo")
# plot fitted line
y_ = regressor.predict(X_)
plt.plot(X_, y_, "g-")
plt.show()
regressor.weights
vqr = VQR(
feature_map=feature_map,
ansatz=ansatz,
optimizer=L_BFGS_B(maxiter=5),
callback=callback_graph,
)
# create empty array for callback to store evaluations of the objective function
objective_func_vals = []
plt.rcParams["figure.figsize"] = (12, 6)
# fit regressor
vqr.fit(X, y)
# return to default figsize
plt.rcParams["figure.figsize"] = (6, 4)
# score result
vqr.score(X, y)
# plot target function
plt.plot(X_, f(X_), "r--")
# plot data
plt.plot(X, y, "bo")
# plot fitted line
y_ = vqr.predict(X_)
plt.plot(X_, y_, "g-")
plt.show()
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/GroenteLepel/qiskit-quantum-knn
|
GroenteLepel
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
# pylint: disable=wrong-import-order
"""Main Qiskit public functionality."""
import pkgutil
# First, check for required Python and API version
from . import util
# qiskit errors operator
from .exceptions import QiskitError
# The main qiskit operators
from qiskit.circuit import ClassicalRegister
from qiskit.circuit import QuantumRegister
from qiskit.circuit import QuantumCircuit
# pylint: disable=redefined-builtin
from qiskit.tools.compiler import compile # TODO remove after 0.8
from qiskit.execute import execute
# The qiskit.extensions.x imports needs to be placed here due to the
# mechanism for adding gates dynamically.
import qiskit.extensions
import qiskit.circuit.measure
import qiskit.circuit.reset
# Allow extending this namespace. Please note that currently this line needs
# to be placed *before* the wrapper imports or any non-import code AND *before*
# importing the package you want to allow extensions for (in this case `backends`).
__path__ = pkgutil.extend_path(__path__, __name__)
# Please note these are global instances, not modules.
from qiskit.providers.basicaer import BasicAer
# Try to import the Aer provider if installed.
try:
from qiskit.providers.aer import Aer
except ImportError:
pass
# Try to import the IBMQ provider if installed.
try:
from qiskit.providers.ibmq import IBMQ
except ImportError:
pass
from .version import __version__
from .version import __qiskit_version__
|
https://github.com/zapatacomputing/qe-qiskit
|
zapatacomputing
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2018.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Utils for using with Qiskit unit tests."""
import logging
import os
import unittest
from enum import Enum
from qiskit import __path__ as qiskit_path
class Path(Enum):
"""Helper with paths commonly used during the tests."""
# Main SDK path: qiskit/
SDK = qiskit_path[0]
# test.python path: qiskit/test/python/
TEST = os.path.normpath(os.path.join(SDK, '..', 'test', 'python'))
# Examples path: examples/
EXAMPLES = os.path.normpath(os.path.join(SDK, '..', 'examples'))
# Schemas path: qiskit/schemas
SCHEMAS = os.path.normpath(os.path.join(SDK, 'schemas'))
# VCR cassettes path: qiskit/test/cassettes/
CASSETTES = os.path.normpath(os.path.join(TEST, '..', 'cassettes'))
# Sample QASMs path: qiskit/test/python/qasm
QASMS = os.path.normpath(os.path.join(TEST, 'qasm'))
def setup_test_logging(logger, log_level, filename):
"""Set logging to file and stdout for a logger.
Args:
logger (Logger): logger object to be updated.
log_level (str): logging level.
filename (str): name of the output file.
"""
# Set up formatter.
log_fmt = ('{}.%(funcName)s:%(levelname)s:%(asctime)s:'
' %(message)s'.format(logger.name))
formatter = logging.Formatter(log_fmt)
# Set up the file handler.
file_handler = logging.FileHandler(filename)
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)
# Set the logging level from the environment variable, defaulting
# to INFO if it is not a valid level.
level = logging._nameToLevel.get(log_level, logging.INFO)
logger.setLevel(level)
class _AssertNoLogsContext(unittest.case._AssertLogsContext):
"""A context manager used to implement TestCase.assertNoLogs()."""
# pylint: disable=inconsistent-return-statements
def __exit__(self, exc_type, exc_value, tb):
"""
This is a modified version of TestCase._AssertLogsContext.__exit__(...)
"""
self.logger.handlers = self.old_handlers
self.logger.propagate = self.old_propagate
self.logger.setLevel(self.old_level)
if exc_type is not None:
# let unexpected exceptions pass through
return False
if self.watcher.records:
msg = 'logs of level {} or higher triggered on {}:\n'.format(
logging.getLevelName(self.level), self.logger.name)
for record in self.watcher.records:
msg += 'logger %s %s:%i: %s\n' % (record.name, record.pathname,
record.lineno,
record.getMessage())
self._raiseFailure(msg)
|
https://github.com/2lambda123/Qiskit-qiskit
|
2lambda123
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Tests for layouts of timeline drawer."""
import qiskit
from qiskit.test import QiskitTestCase
from qiskit.visualization.timeline import layouts
class TestBitArrange(QiskitTestCase):
"""Tests for layout.bit_arrange."""
def setUp(self) -> None:
"""Setup."""
super().setUp()
qregs = qiskit.QuantumRegister(3)
cregs = qiskit.ClassicalRegister(3)
self.regs = list(qregs) + list(cregs)
def test_qreg_creg_ascending(self):
"""Test qreg_creg_ascending layout function."""
sorted_regs = layouts.qreg_creg_ascending(self.regs)
ref_regs = [
self.regs[0],
self.regs[1],
self.regs[2],
self.regs[3],
self.regs[4],
self.regs[5],
]
self.assertListEqual(sorted_regs, ref_regs)
def test_qreg_creg_descending(self):
"""Test qreg_creg_descending layout function."""
sorted_regs = layouts.qreg_creg_descending(self.regs)
ref_regs = [
self.regs[2],
self.regs[1],
self.regs[0],
self.regs[5],
self.regs[4],
self.regs[3],
]
self.assertListEqual(sorted_regs, ref_regs)
class TestAxisMap(QiskitTestCase):
"""Tests for layout.time_axis_map."""
def test_time_map_in_dt(self):
"""Test time_map_in_dt layout function."""
axis_config = layouts.time_map_in_dt(time_window=(-100, 500))
self.assertEqual(axis_config.window, (-100, 500))
self.assertEqual(axis_config.label, "System cycle time (dt)")
ref_map = {0: "0", 100: "100", 200: "200", 300: "300", 400: "400", 500: "500"}
self.assertDictEqual(axis_config.axis_map, ref_map)
|
https://github.com/PabloMartinezAngerosa/QAOA-uniform-convergence
|
PabloMartinezAngerosa
|
from tsp_qaoa import test_solution
from qiskit.visualization import plot_histogram
import networkx as nx
import numpy as np
import json
import csv
# Array of JSON Objects
header = ['p', 'state', 'probability', 'mean']
length_p = 10
with open('qaoa_multiple_p.csv', 'w', encoding='UTF8') as f:
writer = csv.writer(f)
# write the header
writer.writerow(header)
first_p = False
for p in range(length_p):
p = p+1
if first_p == False:
job_2, G, UNIFORM_CONVERGENCE_SAMPLE = test_solution(p=p)
first_p = True
else:
job_2, G, UNIFORM_CONVERGENCE_SAMPLE = test_solution(grafo=G, p=p)
# Sort the JSON data based on the value of the brand key
UNIFORM_CONVERGENCE_SAMPLE.sort(key=lambda x: x["mean"])
mean = UNIFORM_CONVERGENCE_SAMPLE[0]["mean"]
print(mean)
state = 0
for probability in UNIFORM_CONVERGENCE_SAMPLE[0]["probabilities"]:
state += 1
writer.writerow([p,state, probability,mean])
|
https://github.com/indian-institute-of-science-qc/qiskit-aakash
|
indian-institute-of-science-qc
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2018.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""
Example showing how to use Qiskit at level 2 (advanced).
This example shows how an advanced user interacts with Terra.
It builds some circuits and transpiles them with the pass_manager.
"""
import pprint, time
# Import the Qiskit modules
from qiskit import IBMQ, BasicAer
from qiskit import QiskitError
from qiskit.circuit import QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit.extensions import SwapGate
from qiskit.compiler import assemble
from qiskit.providers.ibmq import least_busy
from qiskit.tools.monitor import job_monitor
from qiskit.transpiler import PassManager
from qiskit.transpiler import CouplingMap
from qiskit.transpiler.passes import Unroller
from qiskit.transpiler.passes import FullAncillaAllocation
from qiskit.transpiler.passes import EnlargeWithAncilla
from qiskit.transpiler.passes import TrivialLayout
from qiskit.transpiler.passes import Decompose
from qiskit.transpiler.passes import CXDirection
from qiskit.transpiler.passes import LookaheadSwap
try:
IBMQ.load_accounts()
except:
print("""WARNING: There's no connection with the API for remote backends.
Have you initialized a file with your personal token?
For now, there's only access to local simulator backends...""")
try:
qubit_reg = QuantumRegister(4, name='q')
clbit_reg = ClassicalRegister(4, name='c')
# Making first circuit: superpositions
qc1 = QuantumCircuit(qubit_reg, clbit_reg, name="bell")
qc1.h(qubit_reg[0])
qc1.cx(qubit_reg[0], qubit_reg[1])
qc1.measure(qubit_reg, clbit_reg)
# Making another circuit: GHZ State
qc2 = QuantumCircuit(qubit_reg, clbit_reg, name="superposition")
qc2.h(qubit_reg)
qc2.cx(qubit_reg[0], qubit_reg[1])
qc2.cx(qubit_reg[0], qubit_reg[2])
qc2.cx(qubit_reg[0], qubit_reg[3])
qc2.measure(qubit_reg, clbit_reg)
# Setting up the backend
print("(Aer Backends)")
for backend in BasicAer.backends():
print(backend.status())
qasm_simulator = BasicAer.get_backend('qasm_simulator')
# Compile and run the circuit on a real device backend
# See a list of available remote backends
print("\n(IBMQ Backends)")
for backend in IBMQ.backends():
print(backend.status())
try:
# select least busy available device and execute.
least_busy_device = least_busy(IBMQ.backends(simulator=False))
except:
print("All devices are currently unavailable.")
print("Running on current least busy device: ", least_busy_device)
# making a pass manager to compile the circuits
coupling_map = CouplingMap(least_busy_device.configuration().coupling_map)
print("coupling map: ", coupling_map)
pm = PassManager()
pm.append(TrivialLayout(coupling_map))
pm.append(FullAncillaAllocation(coupling_map))
pm.append(EnlargeWithAncilla())
pm.append(LookaheadSwap(coupling_map))
pm.append(Decompose(SwapGate))
pm.append(CXDirection(coupling_map))
pm.append(Unroller(['u1', 'u2', 'u3', 'id', 'cx']))
qc1_new = pm.run(qc1)
qc2_new = pm.run(qc2)
print("Bell circuit before passes:")
print(qc1.draw())
print("Bell circuit after passes:")
print(qc1_new.draw())
print("Superposition circuit before passes:")
print(qc2.draw())
print("Superposition circuit after passes:")
print(qc2_new.draw())
# Assemble the two circuits into a runnable qobj
qobj = assemble([qc1_new, qc2_new], shots=1000)
# Running qobj on the simulator
print("Running on simulator:")
sim_job = qasm_simulator.run(qobj)
# Getting the result
sim_result=sim_job.result()
# Show the results
print(sim_result.get_counts(qc1))
print(sim_result.get_counts(qc2))
# Running the job.
print("Running on device:")
exp_job = least_busy_device.run(qobj)
job_monitor(exp_job)
exp_result = exp_job.result()
# Show the results
print(exp_result.get_counts(qc1))
print(exp_result.get_counts(qc2))
except QiskitError as ex:
print('There was an error in the circuit!. Error = {}'.format(ex))
|
https://github.com/ritamsarmah/cs239
|
ritamsarmah
|
from qiskit import QuantumCircuit
from QCLG_lvl3.oracles.secret_number_oracle import SecretNUmberOracle
class BernsteinVazirani:
@classmethod
def bernstein_vazirani(cls, random_binary, eval_mode: bool) -> QuantumCircuit:
# Construct secret number oracle
secret_number_oracle = SecretNUmberOracle.create_secret_number_oracle(random_binary=random_binary, eval_mode=eval_mode)
num_of_qubits = secret_number_oracle.num_qubits
# Construct circuit according to the length of the number
dj_circuit = QuantumCircuit(num_of_qubits, num_of_qubits - 1)
dj_circuit_before_oracle = QuantumCircuit(num_of_qubits, num_of_qubits - 1)
# Apply H-gates
for qubit in range(num_of_qubits - 1):
dj_circuit_before_oracle.h(qubit)
# Put output qubit in state |->
dj_circuit_before_oracle.x(num_of_qubits - 1)
dj_circuit_before_oracle.h(num_of_qubits - 1)
dj_circuit += dj_circuit_before_oracle
# Add oracle
dj_circuit += secret_number_oracle
dj_circuit_after_oracle = QuantumCircuit(num_of_qubits, num_of_qubits - 1)
# Repeat H-gates
for qubit in range(num_of_qubits - 1):
dj_circuit_after_oracle.h(qubit)
dj_circuit_after_oracle.barrier()
# Measure
for i in range(num_of_qubits - 1):
dj_circuit_after_oracle.measure(i, i)
dj_circuit += dj_circuit_after_oracle
if not eval_mode:
print("Circuit before the oracle\n")
print(QuantumCircuit.draw(dj_circuit_before_oracle))
print("Circuit after the oracle\n")
print(QuantumCircuit.draw(dj_circuit_after_oracle))
print(dj_circuit)
return dj_circuit
|
https://github.com/2lambda123/Qiskit-qiskit
|
2lambda123
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Tests LogicNetwork.Tweedledum2Qiskit converter."""
import unittest
from qiskit.utils.optionals import HAS_TWEEDLEDUM
from qiskit.test import QiskitTestCase
from qiskit import QuantumCircuit, QuantumRegister
from qiskit.circuit.library.standard_gates import XGate
if HAS_TWEEDLEDUM:
# pylint: disable=import-error
from qiskit.circuit.classicalfunction.utils import tweedledum2qiskit
from tweedledum.ir import Circuit
from tweedledum.operators import X
@unittest.skipUnless(HAS_TWEEDLEDUM, "Tweedledum is required for these tests.")
class TestTweedledum2Qiskit(QiskitTestCase):
"""Tests qiskit.transpiler.classicalfunction.utils.tweedledum2qiskit function."""
def test_x(self):
"""Single uncontrolled X"""
tweedledum_circuit = Circuit()
tweedledum_circuit.apply_operator(X(), [tweedledum_circuit.create_qubit()])
circuit = tweedledum2qiskit(tweedledum_circuit)
expected = QuantumCircuit(1)
expected.x(0)
self.assertEqual(circuit, expected)
def test_cx_0_1(self):
"""CX(0, 1)"""
tweedledum_circuit = Circuit()
qubits = []
qubits.append(tweedledum_circuit.create_qubit())
qubits.append(tweedledum_circuit.create_qubit())
tweedledum_circuit.apply_operator(X(), [qubits[0], qubits[1]])
circuit = tweedledum2qiskit(tweedledum_circuit)
expected = QuantumCircuit(2)
expected.append(XGate().control(1, ctrl_state="1"), [0, 1])
self.assertEqual(circuit, expected)
def test_cx_1_0(self):
"""CX(1, 0)"""
tweedledum_circuit = Circuit()
qubits = []
qubits.append(tweedledum_circuit.create_qubit())
qubits.append(tweedledum_circuit.create_qubit())
tweedledum_circuit.apply_operator(X(), [qubits[1], qubits[0]])
circuit = tweedledum2qiskit(tweedledum_circuit)
expected = QuantumCircuit(2)
expected.append(XGate().control(1, ctrl_state="1"), [1, 0])
self.assertEqual(expected, circuit)
def test_cx_qreg(self):
"""CX(0, 1) with qregs parameter"""
tweedledum_circuit = Circuit()
qubits = []
qubits.append(tweedledum_circuit.create_qubit())
qubits.append(tweedledum_circuit.create_qubit())
tweedledum_circuit.apply_operator(X(), [qubits[1], qubits[0]])
qr = QuantumRegister(2, "qr")
circuit = tweedledum2qiskit(tweedledum_circuit, qregs=[qr])
expected = QuantumCircuit(qr)
expected.append(XGate().control(1, ctrl_state="1"), [qr[1], qr[0]])
self.assertEqual(expected, circuit)
|
https://github.com/Pitt-JonesLab/slam_decomposition
|
Pitt-JonesLab
|
from inspect import signature
from itertools import cycle
from qiskit import QuantumCircuit
from qiskit.circuit import Parameter
from qiskit.circuit.library.standard_gates import *
from qiskit.quantum_info import Operator
from slam.utils.data_utils import filename_encode
from slam.utils.gates.custom_gates import *
"""
Defines the variational object passed to the optimizer
#TODO: this should extend Qiskit's NLocal class
"""
"""TemplateV2 working on implementing the continuous 2Q search
1. Change base_gate to be a class instead of already initialzied object
2. Eliminate monodromy things (I don't know how it could be used)
Wait actually, what if before we try decomp, we look at the shortest gates that make the monodromy span valid
I'll leave this as a TODO for now because it still breaks for 3Q+ and that's what I want working first
3. Define a cost of the circuit using the Q-params, should be the circuit fidelity which can be used with decomposition fidelity to find total f
"""
from slam.basis_abc import VariationalTemplate
class CircuitTemplateV2(VariationalTemplate):
def __init__(
self,
n_qubits=2,
base_gates=[RiSwapGate],
edge_params=[[(0, 1)]],
no_exterior_1q=False,
use_polytopes=False,
maximum_span_guess=5,
preseed=False,
vz_only=False,
param_vec_expand=None,
):
"""Initalizes a qiskit.quantumCircuit object with unbound 1Q gate
parameters."""
hash = str(n_qubits) + str(base_gates) + str(edge_params) + str(no_exterior_1q)
self.filename = filename_encode(hash)
self.n_qubits = n_qubits
self.no_exterior_1q = no_exterior_1q
# for smushing gate exps
self.param_vec_expand = param_vec_expand
if self.param_vec_expand is not None:
assert len(base_gates) == 1 # too complicated otherwise :)
self.vz_only = vz_only
self.gate_2q_base = cycle(base_gates)
# each gate gets its on cycler
self.gate_2q_edges = cycle(
[cycle(edge_params_el) for edge_params_el in edge_params]
)
self.gen_1q_params = self._param_iter()
# XXX
self.bounds = {} # dict key is each parameter
self.bounds_list = [] # list puts in order for scipy.optimze()
self.constraint_func = None # cost function constraint for optimize()
self.using_bounds = False
self.using_constraints = False # bound or constraint
# define a range to see how many times we should extend the circuit while in optimization search
self.spanning_range = None
if not use_polytopes:
self.spanning_range = range(1, maximum_span_guess + 1)
self.coverage = None # only precomputed in mixedbasis class
super().__init__(preseed=preseed, use_polytopes=use_polytopes)
self._reset()
# deprecated feature
self.trotter = False
def get_spanning_range(self, target_u):
if not self.use_polytopes:
return self.spanning_range
else:
# call monodromy polytope helper
# import put here so files that don't use monodromy can still import this file
from slam.utils.polytopes.polytope_wrap import monodromy_range_from_target
return monodromy_range_from_target(self, target_u)
def reconstruct(self, ret):
"""Reconstructs the circuit from the optimization result."""
self.build(ret.cycles)
print("Cost:", self.circuit_cost(Xk=ret.Xk))
return self.assign_Xk(ret.Xk)
def circuit_cost(self, Xk):
# NOTE: this doesn't necessarily correlate to a fidelity measure
# for now, consider to just be an abstract score used in constraint building
# fidelity = 1.0
cost = 0
qc = self.assign_Xk(Xk)
# assuming there is only 1 critical path, need to iterate through gates
# want to take the product of fidelities
# for now just hardcode this until we settle on a better way
for gate in qc:
c = 0.0
if gate[0].name == "riswap":
a = gate[0].params[0]
c = RiSwapGate(a).cost() # fidelity
elif gate[0].name in ["3QGate", "VSWAP", "ΔSWAP"]:
# cast ParameterExpression to list(float)
# XXX I believe the gate.params doesn't preserve the order so splatting is not correct
# raise ValueError("BROKEN!")
a = [float(el) for el in gate[0].params]
c = CirculatorSNAILGate(*a).cost()
# elif gate[0].name in ["2QSmushGate"]:
# # fidelity = fidelity * c:
# a = [float(el) for el in gate[0].params]
# c = ConversionGainSmushGate(*a).cost()
elif gate[0].name in ["2QGate", "2QSmushGate"]:
# fidelity = fidelity * c:
a = [float(el) for el in gate[0].params]
c = ConversionGainGate(a[0], a[1], a[2], a[3], a[-1]).cost()
# raise ValueError("BROKEN!")
cost += c
return cost
def circuit_fidelity(self, Xk):
fidelity = 1.0
qc = self.assign_Xk(Xk)
# assuming there is only 1 critical path, need to iterate through gates
# want to take the product of fidelities
# for now just hardcode this until we settle on a better way
for gate in qc:
c = 1.0
if gate[0].name == "riswap":
a = gate[0].params[0]
c = RiSwapGate(a).cost() # fidelity
fidelity = fidelity * c
return fidelity
def eval(self, Xk):
"""Returns an Operator after binding parameter array to template."""
return Operator(self.assign_Xk(Xk)).data
# TODO: modify this so the Q-params have a smaller range
def parameter_guess(self, t=0):
"""Returns a np array of random values for each parameter."""
# parent checking is to handle preseeding
parent = super().parameter_guess(t)
if parent is not None:
return parent
random_list = []
# set defaults
# default_bound = (-2*np.pi, 2*np.pi)
default_bound = (-4 * np.pi, 4 * np.pi)
dict_response_default = default_bound
self.bounds_list = (
[]
) # sequence of (min,max) for each element in X passed to scipy optimze
for parameter in self.circuit.parameters:
cbound = self.bounds.get(parameter.name, dict_response_default)
self.bounds_list.append(cbound)
if cbound is None:
cbound = default_bound
random_list.append(np.random.uniform(cbound[0], cbound[1], 1)[0])
if not self.using_bounds:
self.bounds_list = None # remove so optimizer can use BFGS
return random_list
# return np.random.random(len(self.circuit.parameters))* 2 * np.pi
def add_bound(self, parameter_name, max=None, min=None):
self.bounds[parameter_name] = (min, max)
# con_funs is passed to scipy optimizer
# quick iteration because I don't have a better way
p_index = -1
for index, p in enumerate(self.circuit.parameters):
if p.name == parameter_name:
p_index = index
break
if p_index == -1:
raise ValueError("Parameter Name not found")
# self.con_funs.append({'type:ineq', 'fun':lambda x: max-x[p_index]})
# self.con_funs.append({'type:ineq','fun':lambda x: x[p_index] - min})
# flag for safety, can't rebuilt or messes with ordering
self.using_bounds = True
return
def set_constraint(self, param_max_cost):
# set a constraint that the current basis can't have a cost more than param
# of the form C_j(x) >= 0
self.constraint_func = {
"type": "ineq",
"fun": lambda x: param_max_cost - self.circuit_cost(x),
}
self.using_constraints = True
def remove_constraint(self):
self.constraint_func = None
self.using_constraints = False
def assign_Xk(self, Xk):
return self.circuit.assign_parameters(
{parameter: i for parameter, i in zip(self.circuit.parameters, Xk)}
)
def _reset(self):
"""Return template to a 0 cycle."""
self.cycles = 0
self.circuit = QuantumCircuit(self.n_qubits)
self.gen_1q_params = self._param_iter() # reset p labels
self.gen_2q_params = self._param_iter2() # second counter for 2Q gates
def build(self, n_repetitions):
# if self.using_constraints:
# raise ValueError("Can't build after setting constraints")
self._reset()
if n_repetitions <= 0:
raise ValueError()
if self.trotter:
pass
# n_repetitions = int(1 / next(self.gate_2q_params))
for i in range(n_repetitions):
self._build_cycle(initial=(i == 0), final=(i == n_repetitions - 1))
def _param_iter(self):
index = 0
while True:
# Check if Parameter already created, then return reference to that variable
def _filter_param(param):
return param.name == f"P{index}"
res = list(filter(_filter_param, self.circuit.parameters))
if len(res) == 0:
yield Parameter(f"P{index}")
else:
yield res[0]
index += 1
if self.trotter:
index %= 3 * self.n_qubits
def _param_iter2(self):
index = 0
while True:
# Check if Parameter already created, then return reference to that variable
def _filter_param(param):
return param.name == f"Q{index}"
res = list(filter(_filter_param, self.circuit.parameters))
if len(res) == 0:
yield Parameter(f"Q{index}")
else:
yield res[0]
index += 1
def _build_cycle(self, initial=False, final=False):
"""Extends template by next nonlocal gate."""
if initial and not self.no_exterior_1q:
# before build by extend, add first pair of 1Qs
for qubit in range(self.n_qubits):
if self.vz_only:
self.circuit.rz(
*[next(self.gen_1q_params) for _ in range(1)], qubit
)
else:
self.circuit.u(*[next(self.gen_1q_params) for _ in range(3)], qubit)
#
gate = next(self.gate_2q_base)
edge = next(
next(self.gate_2q_edges)
) # call cycle twice to increment gate then edge
# inspect to find how many parameters our gate requires
# now using self.param_vec_expand to handle when parameter is a vector
num2qparams = len(
signature(gate).parameters
) # is +1 because of self, but goes away in range()
if self.param_vec_expand is not None:
num2qparams = sum(self.param_vec_expand)
gate_instance = gate(*[next(self.gen_2q_params) for _ in range(num2qparams)])
self.circuit.append(gate_instance, edge)
if not (final and self.no_exterior_1q):
for qubit in edge:
if self.vz_only:
self.circuit.rz(
*[next(self.gen_1q_params) for _ in range(1)], qubit
)
else:
self.circuit.u(*[next(self.gen_1q_params) for _ in range(3)], qubit)
self.cycles += 1
"""this might be deprecated, if I want to use gate costs, should be factored in with circuit polytopes already
for now, instead just use the mixedbasis instead"""
# class CustomCostCircuitTemplate(CircuitTemplate):
#
# #assigns a cost value to each repeated call to build()
# def __init__(self, base_gates=[CustomCostGate]) -> None:
# logging.warning("deprecated, use mixedorderbasis with cost assigned to cirucit polytopes")
# for gate in base_gates:
# if not isinstance(gate, CustomCostGate):
# raise ValueError("Gates must have a defined cost")
# self.cost = {0:0}
# super().__init__(n_qubits=2, base_gates=base_gates, edge_params=[(0,1)], no_exterior_1q=False,use_polytopes=True, preseed=True)
# def _build_cycle(self, initial=False, final=False):
# """Extends template by next nonlocal gate
# add modification which saves cost to dict"""
# if initial and not self.no_exterior_1q:
# # before build by extend, add first pair of 1Qs
# for qubit in range(self.n_qubits):
# self.circuit.u(*[next(self.gen_1q_params) for _ in range(3)], qubit)
# edge = next(self.gate_2q_edges)
# gate = next(self.gate_2q_base)
# self.circuit.append(gate, edge)
# if not (final and self.no_exterior_1q):
# for qubit in edge:
# self.circuit.u(*[next(self.gen_1q_params) for _ in range(3)], qubit)
# self.cycles += 1
# self.cost[self.cycles] = self.cost[self.cycles-1] + gate.cost
# def unit_cost(self, cycles):
# if not cycles in self.cost.keys():
# self.build(cycles)
# return self.cost[cycles]
|
https://github.com/usamisaori/Grover
|
usamisaori
|
import math
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
from matplotlib.pyplot import arrow
from mpl_toolkits.axisartist.axislines import SubplotZero
from matplotlib.patches import Arc
%matplotlib inline
import warnings
warnings.filterwarnings('ignore')
def get_line_plot(angle, *, linewidth=1, linestyle="-", color="black"):
angle = math.radians(angle)
return Line2D([0, math.cos(angle) * 0.92], [0, math.sin(angle) * 0.92],
linewidth=linewidth, linestyle=linestyle, color=color)
def get_angle_plot(line1, line2, *, offset=1, color=None, origin=(0, 0),
len_x_axis = 1, len_y_axis = 1):
l1xy = line1.get_xydata()
# Angle between line1 and x-axis
y1 = l1xy[1][1] - l1xy[0][1]
x1 = l1xy[1][0] - l1xy[0][0]
slope1 = y1 / float(x1)
# Allows you to use this in different quadrants
angle1 = math.degrees(math.atan2(y1, x1))
l2xy = line2.get_xydata()
# Angle between line2 and x-axis
y2 = l2xy[1][1] - l2xy[0][1]
x2 = l2xy[1][0] - l2xy[0][0]
slope2 = y2 / float(x2)
angle2 = math.degrees(math.atan2(y2, x2))
theta1 = min(angle1, angle2)
theta2 = max(angle1, angle2)
angle = theta2 - theta1
if angle > 180:
angle = 360 - angle
theta1 = 360 + theta1
if theta1 > theta2:
theta1, theta2 = theta2, theta1
if color is None:
color = line1.get_color() # Uses the color of line 1 if color parameter is not passed.
return Arc(origin, len_x_axis*offset, len_y_axis*offset, 0,
theta1, theta2, color=color,
label = r'${:.4}^\circ$'.format(float(angle)))
def get_angle_text(angle_plot):
angle = angle_plot.get_label()
# angle = r'${:.4}^\circ$'.format(angle) # Display angle upto 2 decimal places
# Get the vertices of the angle arc
vertices = angle_plot.get_verts()
# Get the midpoint of the arc extremes
x_width = (vertices[0][0] + vertices[-1][0]) / 2.0
y_width = (vertices[0][1] + vertices[-1][1]) / 2.0
separation_radius = max(x_width / 2.0, y_width / 2.0)
return [x_width + separation_radius, y_width + separation_radius, angle]
class AnglePoltter:
def __init__(self):
self.lines = []
self.arcs = []
self.angles = []
def add_line(self, angle, *, linewidth=1, linestyle="-", color="black"):
line = get_line_plot(angle, linewidth=linewidth, linestyle=linestyle, color=color)
self.lines.append(
[
line.get_xdata()[0], line.get_ydata()[0], line.get_xdata()[1], line.get_ydata()[1],
linewidth, linestyle, color
]
)
return line
def add_angle(self, line1, line2, *, text=False, **kwargs):
angle = get_angle_plot(line1, line2, **kwargs)
self.arcs.append(angle)
if text:
self.angles.append(get_angle_text(angle))
def plot(self, *, title, fontsize=18):
fig = plt.figure()
ax = SubplotZero(fig, 1, 1, 1)
# draw a circle
theta = np.linspace(0, 2 * np.pi, 200)
x = np.cos(theta)
y = np.sin(theta)
ax.plot(x, y, color="#CCCCCC", linewidth=1.5)
fig.add_subplot(ax)
for direction in ["left", "right", "bottom", "top"]:
# hides borders
ax.axis[direction].set_visible(False)
for direction in ["xzero", "yzero"]:
# adds arrows at the ends of each axis
ax.axis[direction].set_axisline_style('-|>')
# adds X and Y-axis from the origin
ax.axis[direction].set_visible(True)
for line in self.lines:
if line[4] != 0:
ax.arrow(line[0], line[1], line[2], line[3],
head_width=0.06, head_length=0.06,
linewidth=line[4], linestyle=line[5], color=line[6])
for arc in self.arcs:
ax.add_patch(arc)
for angle in self.angles:
ax.text(*angle)
if title != None:
fig.suptitle(title, fontsize=fontsize)
plt.axis([-1.8, 1.8, -1.35, 1.35])
plt.grid()
plt.legend()
return ax
plotter = AnglePoltter()
# draw lines
x = plotter.add_line(0, linewidth=0)
line_1 = plotter.add_line(30, linewidth=1.5, color="#FF6666")
# draw angles
plotter.add_angle(line_1, x, offset=0.5, text=True)
ax = plotter.plot(title="Initial state")
plotter = AnglePoltter()
# draw lines
x = plotter.add_line(0, linewidth=0)
line_1 = plotter.add_line(30, linewidth=1.5, linestyle="-.", color="#6666CC")
line_2 = plotter.add_line(330, linewidth=1.5, color="#FF6666")
# draw angles
plotter.add_angle(line_1, x, offset=0.4)
plotter.add_angle(line_2, x, offset=0.4)
ax = plotter.plot(title="After applying Oracle")
x = math.cos(math.radians(30))
y = math.sin(math.radians(30))
ax.add_line(Line2D([x, x], [-y, y], linewidth=1.5, linestyle="--", color="#CCCCCC"))
plotter = AnglePoltter()
# draw lines
x = plotter.add_line(0, linewidth=0)
line_1 = plotter.add_line(30, linewidth=1.5, linestyle="-.", color="#6666CC")
line_2 = plotter.add_line(330, linewidth=1.5, linestyle="-.", color="#99CC33")
line_3 = plotter.add_line(90, linewidth=1.5, color="#FF6666")
# draw angles
plotter.add_angle(line_1, x, offset=0.4)
plotter.add_angle(line_2, x, offset=0.4)
plotter.add_angle(line_3, line_1, offset=0.6)
ax = plotter.plot(title="After one Grover iteration")
x = math.cos(math.radians(30))
y = math.sin(math.radians(30))
ax.add_line(Line2D([x, x], [-y, y], linewidth=1.5, linestyle="--", color="#CCCCCC"))
ax.add_line(Line2D([x, 0], [-y, 1], linewidth=1.5, linestyle="--", color="#CCCCCC"))
ax.add_line(Line2D([-x * 1.2, 0], [-y * 1.2, 0], linewidth=1.5, linestyle="--", color="#CCCCCC"))
ax.add_line(Line2D([x, x * 1.2], [y, y * 1.2], linewidth=1.5, linestyle="--", color="#CCCCCC"))
plotter = AnglePoltter()
# draw lines
x = plotter.add_line(0, linewidth=0)
line_1 = plotter.add_line(30, linewidth=1.5, linestyle="-.", color="#6666CC")
line_2 = plotter.add_line(330, linewidth=1.5, linestyle="-.", color="#99CC33")
line_3 = plotter.add_line(90, linewidth=1.5, color="#99CCFF")
line_4 = plotter.add_line(-90, linewidth=1.5, color="#FF6666")
# draw angles
plotter.add_angle(line_1, x, offset=0.4)
plotter.add_angle(line_2, x, offset=0.4)
plotter.add_angle(line_3, line_1, offset=0.6)
plotter.add_angle(line_4, x, offset=0.8)
ax = plotter.plot(title="Apply Oracle(second iteration)")
x = math.cos(math.radians(30))
y = math.sin(math.radians(30))
ax.add_line(Line2D([x, x], [-y, y], linewidth=1.5, linestyle="--", color="#CCCCCC"))
ax.add_line(Line2D([x, 0], [-y, 1], linewidth=1.5, linestyle="--", color="#CCCCCC"))
ax.add_line(Line2D([-x * 1.2, 0], [-y * 1.2, 0], linewidth=1.5, linestyle="--", color="#CCCCCC"))
ax.add_line(Line2D([x, x * 1.2], [y, y * 1.2], linewidth=1.5, linestyle="--", color="#CCCCCC"))
plotter = AnglePoltter()
# draw lines
x = plotter.add_line(0, linewidth=0)
line_1 = plotter.add_line(30, linewidth=1.5, linestyle="-.", color="#6666CC")
line_2 = plotter.add_line(330, linewidth=1.5, linestyle="-.", color="#99CC33")
line_3 = plotter.add_line(90, linewidth=1.5, color="#99CCFF")
line_4 = plotter.add_line(-90, linewidth=1.5, color="#FF9900")
line_5 = plotter.add_line(150, linewidth=1.5, color="#FF6666")
# draw angles
plotter.add_angle(line_1, x, offset=0.4)
plotter.add_angle(line_2, x, offset=0.4)
plotter.add_angle(line_3, line_1, offset=0.6)
plotter.add_angle(line_4, x, offset=0.8)
plotter.add_angle(line_5, line_3, offset=0.6)
ax = plotter.plot(title="Apply Oracle(second iteration)")
x = math.cos(math.radians(30))
y = math.sin(math.radians(30))
ax.add_line(Line2D([x, x], [-y, y], linewidth=1.5, linestyle="--", color="#CCCCCC"))
ax.add_line(Line2D([x, 0], [-y, 1], linewidth=1.5, linestyle="--", color="#CCCCCC"))
ax.add_line(Line2D([-x, 0], [y, -1], linewidth=1.5, linestyle="--", color="#CCCCCC"))
ax.add_line(Line2D([-x * 1.2, 0], [-y * 1.2, 0], linewidth=1.5, linestyle="--", color="#CCCCCC"))
ax.add_line(Line2D([x, x * 1.2], [y, y * 1.2], linewidth=1.5, linestyle="--", color="#CCCCCC"))
theta = math.degrees(math.asin(1/(8 ** 0.5)))
plotter = AnglePoltter()
# draw lines
x = plotter.add_line(0, linewidth=0)
line_1 = plotter.add_line(theta, linewidth=1.5, color="#FF6666")
# draw angles
plotter.add_angle(line_1, x, offset=0.5, text=True)
ax = plotter.plot(title="Initial state")
plotter = AnglePoltter()
# draw lines
x = plotter.add_line(0, linewidth=0)
line_1 = plotter.add_line(theta, linewidth=1.5, linestyle="-.", color="#6666CC")
line_2 = plotter.add_line(-theta, linewidth=1.5, color="#FF6666")
# draw angles
plotter.add_angle(line_1, x, offset=0.4)
plotter.add_angle(line_2, x, offset=0.4)
ax = plotter.plot(title="After applying Oracle")
x = math.cos(math.radians(theta))
y = math.sin(math.radians(theta))
ax.add_line(Line2D([x, x], [-y, y], linewidth=1.5, linestyle="--", color="#CCCCCC"))
plotter = AnglePoltter()
# draw lines
x = plotter.add_line(0, linewidth=0)
line_1 = plotter.add_line(theta, linewidth=1.5, linestyle="-.", color="#6666CC")
line_2 = plotter.add_line(-theta, linewidth=1.5, linestyle="-.", color="#99CC33")
line_3 = plotter.add_line(3 * theta, linewidth=1.5, color="#FF6666")
# draw angles
plotter.add_angle(line_1, x, offset=0.4)
plotter.add_angle(line_2, x, offset=0.4)
plotter.add_angle(line_3, line_1, offset=0.6)
ax = plotter.plot(title="After one Grover iteration")
x = math.cos(math.radians(theta))
y = math.sin(math.radians(theta))
x2 = math.cos(math.radians(3 * theta))
y2 = math.sin(math.radians(3 * theta))
ax.add_line(Line2D([x, x], [-y, y], linewidth=1.5, linestyle="--", color="#CCCCCC"))
ax.add_line(Line2D([x, x2], [-y, y2], linewidth=1.5, linestyle="--", color="#CCCCCC"))
ax.add_line(Line2D([-x * 1.2, 0], [-y * 1.2, 0], linewidth=1.5, linestyle="--", color="#CCCCCC"))
ax.add_line(Line2D([x, x * 1.2], [y, y * 1.2], linewidth=1.5, linestyle="--", color="#CCCCCC"))
plotter = AnglePoltter()
# draw lines
x = plotter.add_line(0, linewidth=0)
line_1 = plotter.add_line(theta, linewidth=1.5, linestyle="-.", color="#6666CC")
line_2 = plotter.add_line(-theta, linewidth=1.5, linestyle="-.", color="#99CC33")
line_3 = plotter.add_line(3 * theta, linewidth=1.5, color="#99CCFF")
line_4 = plotter.add_line(5 * theta, linewidth=1.5, color="#FF6666")
# draw angles
plotter.add_angle(line_1, x, offset=0.4)
plotter.add_angle(line_2, x, offset=0.4)
plotter.add_angle(line_3, line_1, offset=0.6)
plotter.add_angle(line_4, line_3, offset=0.6)
ax = plotter.plot(title="After two Grover iteration")
x = math.cos(math.radians(theta))
y = math.sin(math.radians(theta))
x2 = math.cos(math.radians(3 * theta))
y2 = math.sin(math.radians(3 * theta))
ax.add_line(Line2D([x, x], [-y, y], linewidth=1.5, linestyle="--", color="#CCCCCC"))
ax.add_line(Line2D([x, x2], [-y, y2], linewidth=1.5, linestyle="--", color="#CCCCCC"))
ax.add_line(Line2D([-x * 1.2, 0], [-y * 1.2, 0], linewidth=1.5, linestyle="--", color="#CCCCCC"))
ax.add_line(Line2D([x, x * 1.2], [y, y * 1.2], linewidth=1.5, linestyle="--", color="#CCCCCC"))
plotter = AnglePoltter()
# draw lines
x = plotter.add_line(0, linewidth=0)
line_1 = plotter.add_line(theta, linewidth=1.5, linestyle="-.", color="#6666CC")
line_2 = plotter.add_line(-theta, linewidth=1.5, linestyle="-.", color="#99CC33")
line_3 = plotter.add_line(3 * theta, linewidth=1.5, color="#99CCFF")
line_4 = plotter.add_line(5 * theta, linewidth=1.5, color="#FF9900")
line_5 = plotter.add_line(7 * theta, linewidth=1.5, color="#FF6666")
# draw angles
plotter.add_angle(line_1, x, offset=0.4)
plotter.add_angle(line_2, x, offset=0.4)
plotter.add_angle(line_3, line_1, offset=0.6)
plotter.add_angle(line_4, line_3, offset=0.6)
plotter.add_angle(line_5, line_4, offset=0.6)
ax = plotter.plot(title="After two Grover iteration")
x = math.cos(math.radians(theta))
y = math.sin(math.radians(theta))
x2 = math.cos(math.radians(3 * theta))
y2 = math.sin(math.radians(3 * theta))
ax.add_line(Line2D([x, x], [-y, y], linewidth=1.5, linestyle="--", color="#CCCCCC"))
ax.add_line(Line2D([x, x2], [-y, y2], linewidth=1.5, linestyle="--", color="#CCCCCC"))
ax.add_line(Line2D([-x * 1.2, 0], [-y * 1.2, 0], linewidth=1.5, linestyle="--", color="#CCCCCC"))
ax.add_line(Line2D([x, x * 1.2], [y, y * 1.2], linewidth=1.5, linestyle="--", color="#CCCCCC"))
plotter = AnglePoltter()
# draw lines
x = plotter.add_line(0, linewidth=0)
line_1 = plotter.add_line(45, linewidth=1.5, color="#FF6666")
# draw angles
plotter.add_angle(line_1, x, offset=0.5, text=True)
ax = plotter.plot(title="Initial state")
plotter = AnglePoltter()
# draw lines
x = plotter.add_line(0, linewidth=0)
line_1 = plotter.add_line(45, linewidth=1.5, linestyle="-.", color="#99CC33")
line_2 = plotter.add_line(-45, linewidth=1.5, color="#FF6666")
# draw angles
plotter.add_angle(line_1, x, offset=0.4)
plotter.add_angle(line_2, x, offset=0.4)
ax = plotter.plot(title="After applying Oracle")
x = math.cos(math.radians(45))
y = math.sin(math.radians(45))
ax.add_line(Line2D([x, x], [-y, y], linewidth=1.5, linestyle="--", color="#CCCCCC"))
plotter = AnglePoltter()
# draw lines
x = plotter.add_line(0, linewidth=0)
line_1 = plotter.add_line(45, linewidth=1.5, linestyle="-.", color="#99CC33")
line_2 = plotter.add_line(-45, linewidth=1.5, linestyle="-.", color="#99CCFF")
line_3 = plotter.add_line(3 * 45, linewidth=1.5, color="#FF6666")
# draw angles
plotter.add_angle(line_1, x, offset=0.4)
plotter.add_angle(line_2, x, offset=0.4)
plotter.add_angle(line_3, line_1, offset=0.6)
ax = plotter.plot(title="After one Grover iteration")
x = math.cos(math.radians(45))
y = math.sin(math.radians(45))
x2 = math.cos(math.radians(3 * 45))
y2 = math.sin(math.radians(3 * 45))
ax.add_line(Line2D([x, x], [-y, y], linewidth=1.5, linestyle="--", color="#CCCCCC"))
ax.add_line(Line2D([-x * 1.2, 0], [-y * 1.2, 0], linewidth=1.5, linestyle="--", color="#CCCCCC"))
ax.add_line(Line2D([x, x * 1.2], [y, y * 1.2], linewidth=1.5, linestyle="--", color="#CCCCCC"))
plotter = AnglePoltter()
# draw lines
x = plotter.add_line(0, linewidth=0)
line_1 = plotter.add_line(45, linewidth=1.5, linestyle="-.", color="#99CC33")
line_2 = plotter.add_line(-45, linewidth=1.5, linestyle="-.", color="#99CCFF")
line_3 = plotter.add_line(3 * 45, linewidth=1.5, color="#FF9900")
line_4 = plotter.add_line(5 * 45, linewidth=1.5, color="#FF6666")
# draw angles
plotter.add_angle(line_1, x, offset=0.4)
plotter.add_angle(line_2, x, offset=0.4)
plotter.add_angle(line_3, line_1, offset=0.6)
plotter.add_angle(line_4, line_3, offset=0.6)
ax = plotter.plot(title="After two Grover iteration")
x = math.cos(math.radians(45))
y = math.sin(math.radians(45))
ax.add_line(Line2D([x, x], [-y, y], linewidth=1.5, linestyle="--", color="#CCCCCC"))
plotter = AnglePoltter()
# draw lines
x = plotter.add_line(0, linewidth=0)
line_s = plotter.add_line(40, linewidth=2, color="#6666CC")
line_phi = plotter.add_line(25, linewidth=1.5, color="#FF6666")
# draw angles
plotter.add_angle(line_s, x, offset=0.6)
plotter.add_angle(line_phi, x, offset=0.4)
plotter.plot(title="Grover reflections - initial state")
plotter = AnglePoltter()
# draw lines
x = plotter.add_line(0, linewidth=0)
line_s = plotter.add_line(40, linewidth=2, color="#6666CC")
line_phi = plotter.add_line(25, linewidth=1.5, linestyle=":", color="#99CC33")
line_O_phi = plotter.add_line(335, linewidth=1.5, color="#FF6666")
# draw angles
plotter.add_angle(line_s, x, offset=0.6)
plotter.add_angle(line_phi, x, offset=0.4)
plotter.add_angle(line_O_phi, x, offset=0.4)
ax = plotter.plot(title="Grover reflections - reflection 1")
x = math.cos(math.radians(25))
y = math.sin(math.radians(25))
ax.add_line(Line2D([x, x], [-y, y], linewidth=1.5, linestyle="--", color="#CCCCCC"))
plotter = AnglePoltter()
# draw lines
x = plotter.add_line(0, linewidth=0)
line_s = plotter.add_line(40, linewidth=2, color="#6666CC")
line_phi = plotter.add_line(25, linewidth=1.5, linestyle=":", color="#99CC33")
line_O_phi = plotter.add_line(335, linewidth=1.5, linestyle=":", color="#99CCFF")
line_RO_phi = plotter.add_line(285, linewidth=1.5, color="#FF6666")
# draw angles
plotter.add_angle(line_s, x, offset=0.8)
plotter.add_angle(line_phi, x, offset=0.6)
plotter.add_angle(line_O_phi, x, offset=0.6)
plotter.add_angle(line_RO_phi, x, offset=0.4)
ax = plotter.plot(title="Grover reflections - reflection 2")
x1 = math.cos(math.radians(25))
y1 = math.sin(math.radians(25))
ax.add_line(Line2D([x1, x1], [-y1, y1], linewidth=1.5, linestyle="--", color="#CCCCCC"))
x2 = math.cos(math.radians(-75))
y2 = math.sin(math.radians(-75))
ax.add_line(Line2D([x1, x2], [-y1, y2], linewidth=1.5, linestyle="--", color="#CCCCCC"))
x3 = math.cos(math.radians(130)) * 1.5
y3 = math.sin(math.radians(130)) * 1.5
ax.add_line(Line2D([x3, -x3], [y3, -y3], linewidth=1.5, linestyle="--", color="#CCCCCC"))
plotter = AnglePoltter()
# draw lines
x = plotter.add_line(0, linewidth=0)
line_s = plotter.add_line(40, linewidth=2, color="#6666CC")
line_phi = plotter.add_line(25, linewidth=1.5, linestyle=":", color="#99CC33")
line_O_phi = plotter.add_line(335, linewidth=1.5, linestyle=":", color="#99CCFF")
line_RO_phi = plotter.add_line(285, linewidth=1.5, linestyle=":", color="#FF9900")
line_mRO_phi = plotter.add_line(105, linewidth=1.5, color="#FF6666")
# draw angles
plotter.add_angle(line_s, x, offset=0.8)
plotter.add_angle(line_phi, x, offset=0.6)
plotter.add_angle(line_O_phi, x, offset=0.6)
plotter.add_angle(line_RO_phi, x, offset=0.4)
plotter.add_angle(line_mRO_phi, line_phi, offset=1)
ax = plotter.plot(title="Grover reflections - reflection3")
x1 = math.cos(math.radians(25))
y1 = math.sin(math.radians(25))
ax.add_line(Line2D([x1, x1], [-y1, y1], linewidth=1.5, linestyle="--", color="#CCCCCC"))
x2 = math.cos(math.radians(-75))
y2 = math.sin(math.radians(-75))
ax.add_line(Line2D([x1, x2], [-y1, y2], linewidth=1.5, linestyle="--", color="#CCCCCC"))
x3 = math.cos(math.radians(130)) * 1.5
y3 = math.sin(math.radians(130)) * 1.5
ax.add_line(Line2D([x3, -x3], [y3, -y3], linewidth=1.5, linestyle="--", color="#CCCCCC"))
plotter = AnglePoltter()
# draw lines
x = plotter.add_line(0, linewidth=0)
line_1 = plotter.add_line(45, linewidth=1.5, color="#FF6666")
# draw angles
plotter.add_angle(line_1, x, offset=0.5, text=True)
ax = plotter.plot(title="Initial state")
plotter = AnglePoltter()
# draw lines
x = plotter.add_line(0, linewidth=0)
line_1 = plotter.add_line(45, linewidth=1.5, linestyle="-.", color="#99CCFF")
line_2 = plotter.add_line(-2, linewidth=1.5, color="#FF6666")
# draw angles
plotter.add_angle(line_1, x, offset=0.4)
plotter.add_angle(line_2, x, offset=0.4)
ax = plotter.plot(title="After applying Oracle")
plotter = AnglePoltter()
# draw lines
x = plotter.add_line(0, linewidth=0)
line_1 = plotter.add_line(45, linewidth=1.5, linestyle="-.", color="#99CCFF")
line_2 = plotter.add_line(-2, linewidth=1.5, linestyle="-.", color="#FF9900")
line_3 = plotter.add_line(92, linewidth=1.5, color="#FF6666")
# draw angles
plotter.add_angle(line_1, x, offset=0.4)
plotter.add_angle(line_2, x, offset=0.4)
plotter.add_angle(line_3, line_1, offset=0.6)
ax = plotter.plot(title="After one Grover iteration")
plotter = AnglePoltter()
# draw lines
x = plotter.add_line(0, linewidth=0)
line_1 = plotter.add_line(45, linewidth=1.5, color="#FF6666")
# draw angles
plotter.add_angle(line_1, x, offset=0.5, text=True)
ax = plotter.plot(title="Initial state")
plotter = AnglePoltter()
# draw lines
x = plotter.add_line(0, linewidth=0)
line_1 = plotter.add_line(45, linewidth=1.5, linestyle="-.", color="#99CCFF")
line_2 = plotter.add_line(40, linewidth=1.5, color="#FF6666")
# draw angles
plotter.add_angle(line_1, x, offset=0.4)
plotter.add_angle(line_2, x, offset=0.4)
ax = plotter.plot(title="After applying Oracle")
plotter = AnglePoltter()
# draw lines
x = plotter.add_line(0, linewidth=0)
line_1 = plotter.add_line(45, linewidth=1.5, linestyle="-.", color="#99CCFF")
line_2 = plotter.add_line(40, linewidth=1.5, linestyle="-.", color="#FF9900")
line_3 = plotter.add_line(50, linewidth=1.5, color="#FF6666")
# draw angles
plotter.add_angle(line_1, x, offset=0.4)
plotter.add_angle(line_2, x, offset=0.4)
plotter.add_angle(line_3, line_1, offset=0.6)
ax = plotter.plot(title="After one Grover iteration")
|
https://github.com/TheGupta2012/QickStart-Challenges
|
TheGupta2012
|
## Enter Team ID
import os
os.environ["TEAMID"] = "Excalibur"
def get_min_swaps_line(N, controls, targets, connectivity_map):
min_swaps = []
### You code goes here
length=len(controls)
for i in range(length):
if(targets[i] in connectivity_map[controls[i]]):
min_swaps.append(0)
else:
min_swaps.append(abs(targets[i]-controls[i])-1)
### your code goes here
return min_swaps
def test_function_1():
controls = [1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5]
targets = [2,3,4,5,1,3,4,5,1,2,4,5,1,2,3,5,1,2,3,4]
connectivity_map = {
1 : [2],
2 : [1,3],
3 : [2,4],
4 : [3,5],
5 : [4]
}
N = 5
min_swaps = get_min_swaps_line(N, controls, targets, connectivity_map)
return min_swaps
test_function_1()
from grader.graders.problem_2.grader import grader1
grader1.evaluate(get_min_swaps_line)
import sys
def get_min_swaps_graph(N, M, controls, targets, connectivity_map):
min_swaps = []
### You code goes here
length=len(controls)
for i in range(length):
if(targets[i] in connectivity_map[controls[i]]):
min_swaps.append(0)
else:
u=controls[i]
v=targets[i]
visited=[]
distance=[]
q=[]
for i in range(N):
visited.append(0)
distance.append(sys.maxsize)
for k in connectivity_map[u]:
distance[k-1]=1
distance[u-1]=0
q.append(u)
visited[u-1]=1
while(q):
x=q.pop(0)
templist=connectivity_map[x]
length2=len(templist)
for j in range(length2):
if(visited[templist[j]-1]==1):
continue
if((distance[x-1]+1)<distance[templist[j]-1]):
distance[templist[j]-1]=distance[x-1]+1
q.append(templist[j])
visited[templist[j]-1]=1
if(distance[v-1]==sys.maxsize):
min_swaps.append(-1)
continue
min_swaps.append(distance[v-1]-1)
### your code goes here
return min_swaps
def test_function_2():
controls = [1, 2]
targets = [2, 5]
connectivity_map = {
1 : [2],
2 : [1,3],
3 : [2,4,5],
4 : [3],
5 : [3]
}
N = 5
M = 4
min_swaps = get_min_swaps_graph(N, M, controls, targets, connectivity_map)
return min_swaps
test_function_2()
from grader.graders.problem_2.grader import grader2
grader2.evaluate(get_min_swaps_graph)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, transpile, schedule
from qiskit.visualization.pulse_v2 import draw, IQXDebugging
from qiskit.providers.fake_provider import FakeBoeblingen
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
qc.measure_all()
qc = transpile(qc, FakeBoeblingen(), layout_method='trivial')
sched = schedule(qc, FakeBoeblingen())
draw(sched, style=IQXDebugging(), backend=FakeBoeblingen())
|
https://github.com/Tojarieh97/VQE
|
Tojarieh97
|
import nbimporter
from typing import Dict, Tuple, List
import numpy as np
from tqdm import tqdm
QUBITS_NUM = 4
N = 16
K = 4
NUM_SHOTS = 1024
NUM_ITERATIONS = 50
w_vector = np.asarray([4,3,2,1])
from qiskit import Aer
from qiskit.utils import QuantumInstance, algorithm_globals
seed = 50
algorithm_globals.random_seed = seed
simulator_backend = Aer.get_backend('qasm_simulator')
from scipy.optimize import minimize
from utiles import *
input_states = get_first_k_eigenvectors_from_n_computational_basis(K, N)
from ansatz_circuit_item2 import get_full_variational_quantum_circuit
init_circuit_params = {
"thetas": np.random.uniform(low=0, high=2*np.pi, size=8),
"phis": np.random.uniform(low=0, high=2*np.pi, size=4),
"D1": 2,
"D2": 8
}
def prepare_circuit_params(thetas) -> Dict:
return {
"thetas": thetas[4:],
"phis": thetas[:4],
"D1": 2,
"D2": 8
}
def get_ansatz_state(circuit_params, input_state):
circuit_params_with_input_state = {**circuit_params, "input_state": input_state}
return get_full_variational_quantum_circuit(**circuit_params_with_input_state)
def transfrom_hamiltonian_into_pauli_strings(hamiltonian) -> List:
pauli_operators = hamiltonian.to_pauli_op().settings['oplist']
pauli_coeffs = list(map(lambda pauli_operator: pauli_operator.coeff, pauli_operators))
pauli_strings = list(map(lambda pauli_operator: pauli_operator.primitive, pauli_operators))
return pauli_coeffs, pauli_strings
from qiskit.circuit.library.standard_gates import HGate, SGate
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
reducing_to_pauli_z_mapping = {
'I': 'I',
'Z': 'Z',
'X': 'Z',
'Y': 'Z'
}
def reduce_pauli_matrixes_into_sigma_z(pauli_string) -> str:
reduced_pauli_string = ""
for matrix_index in range(QUBITS_NUM):
pauli_matrix = str(pauli_string[matrix_index])
reduced_pauli_matrix = reducing_to_pauli_z_mapping[pauli_matrix]
reduced_pauli_string = reduced_pauli_matrix + reduced_pauli_string
return reduced_pauli_string
def add_layer_of_gates_for_reducing_paulis_to_sigma_z(pauli_string, quantum_circuit):
quantum_registers = QuantumRegister(QUBITS_NUM, name="qubit")
additional_circuit_layer = QuantumCircuit(quantum_registers)
for quantum_register_index, pauli_matrix in enumerate(pauli_string):
if pauli_matrix == "X":
additional_circuit_layer.append(HGate(), [quantum_registers[quantum_register_index]])
if pauli_string == "Y":
additional_circuit_layer.append(HGate(), [quantum_registers[quantum_register_index]])
additional_circuit_layer.append(SGate(), [quantum_registers[quantum_register_index]])
extended_quantum_circuit = quantum_circuit.compose(additional_circuit_layer)
return extended_quantum_circuit
def get_probability_distribution(counts: Dict) -> Dict:
proba_distribution = {state: (count / NUM_SHOTS) for state, count in counts.items()}
return proba_distribution
def calculate_probabilities_of_measurments_in_computational_basis(quantum_state_circuit) -> Dict:
quantum_state_circuit.measure_all()
transpiled_quantum_state_circuit = transpile(quantum_state_circuit, simulator_backend)
Qobj = assemble(transpiled_quantum_state_circuit)
result = simulator_backend.run(Qobj).result()
counts = result.get_counts(quantum_state_circuit)
return get_probability_distribution(counts)
def sort_probas_dict_by_qubits_string_keys(proba_distribution: Dict) -> Dict:
return dict(sorted(proba_distribution.items()))
def reset_power_of_minus_1(power_of_minus_1):
power_of_minus_1 = 0
return power_of_minus_1
def convert_pauli_string_into_str(pauli_string) -> str:
return str(pauli_string)
def calculate_expectation_value_of_pauli_string_by_measurments_probas(pauli_string, ansatz_circuit):
pauli_string_expectation_value = 0
power_of_minus_1 = 0
pauli_string_str = convert_pauli_string_into_str(pauli_string)
extended_ansatz_circuit = add_layer_of_gates_for_reducing_paulis_to_sigma_z(pauli_string_str, ansatz_circuit)
probas_distribution = calculate_probabilities_of_measurments_in_computational_basis(extended_ansatz_circuit)
reduced_pauli_string = reduce_pauli_matrixes_into_sigma_z(pauli_string)
sorted_probas_distribuition = sort_probas_dict_by_qubits_string_keys(probas_distribution)
for qubits_string, proba in sorted_probas_distribuition.items():
for string_index in range(QUBITS_NUM):
if(str(qubits_string[string_index])=="1" and str(pauli_string[string_index])=="Z"):
power_of_minus_1 += 1
pauli_string_expectation_value += pow(-1, power_of_minus_1)*proba
power_of_minus_1 = reset_power_of_minus_1(power_of_minus_1)
return pauli_string_expectation_value
def get_expectation_value(ansatz_circuit, pauli_coeffs, pauli_strings):
total_expection_value = 0
for pauli_coeff, pauli_string in zip(pauli_coeffs, pauli_strings):
total_expection_value += pauli_coeff*calculate_expectation_value_of_pauli_string_by_measurments_probas(
pauli_string, ansatz_circuit)
return total_expection_value
from qiskit import assemble, transpile
def cost_function(thetas, hamiltonian):
L_w = 0
circuit_params = prepare_circuit_params(thetas)
computational_eigenvectors = get_first_k_eigenvectors_from_n_computational_basis(K, N)
pauli_coeffs, pauli_strings = transfrom_hamiltonian_into_pauli_strings(LiH_molecule_4_qubits)
for j in tqdm(range(K)):
ansatz_state = get_ansatz_state(circuit_params, computational_eigenvectors[j])
approximated_energy = get_expectation_value(ansatz_state, pauli_coeffs, pauli_strings)
insert_approximated_energy_to_list_of_all_approximated_energies(
approximated_energies_dict["approximated_eneriges_"+str(j)], approximated_energy)
L_w += w_vector[j]*approximated_energy
return L_w
def get_optimal_thetas_of_ansatz_circuit_for_hamiltonian(hamiltonian):
initial_thetas = np.random.uniform(low=0, high=360, size=12)
optimizer_result = minimize(
cost_function,
x0=initial_thetas,
args=(hamiltonian),
method="COBYLA",
options={"maxiter":NUM_ITERATIONS})
optimal_thetas = prepare_circuit_params(optimizer_result.x)
return optimal_thetas
def get_approximated_k_eigenvalues_of_hamiltonian(hamiltonian):
approximated_k_eigenvalues = []
optimal_thetas = get_optimal_thetas_of_ansatz_circuit_for_hamiltonian(hamiltonian)
computational_eigenvectors = get_first_k_eigenvectors_from_n_computational_basis(K, N)
pauli_coeffs, pauli_strings = transfrom_hamiltonian_into_pauli_strings(hamiltonian)
for eigenvalue_index, eigenvector in enumerate(computational_eigenvectors):
optimal_ansatz_state = get_ansatz_state(optimal_thetas, eigenvector)
approximated_eigenvalue = get_expectation_value(optimal_ansatz_state, pauli_coeffs, pauli_strings)
approximated_k_eigenvalues.append(approximated_eigenvalue)
return approximated_k_eigenvalues
from numpy import linalg as LA
from statistics import mean
def get_mean_approximation_error(exact_k_eigenvalues, approximated_k_eigenvalues):
approximated_errors = []
for exact_eigenvalue, approximated_eigenvalue in zip(exact_k_eigenvalues, approximated_k_eigenvalues):
approximated_errors.append(abs(abs(exact_eigenvalue)-abs(approximated_eigenvalue))/abs(exact_eigenvalue))
return mean(approximated_errors)
def get_exact_k_eigenvalues_of_hamiltonian(hamiltonian, k):
eigenvalues = LA.eig(hamiltonian.to_matrix())[0]
return sorted(eigenvalues)[:k]
def compare_exact_and_approximated_eigenvectors(hamiltonian, approximated_k_eigenvalues):
exact_k_eigenvalues = get_exact_k_eigenvalues_of_hamiltonian(hamiltonian, K)
print("Exact K Eigenvalues:")
print(exact_k_eigenvalues)
print("\nApproximated K Eigenvalues:")
print(sorted(approximated_k_eigenvalues))
print("\nMean Approximation error:")
print(get_mean_approximation_error(exact_k_eigenvalues, sorted(approximated_k_eigenvalues)))
approximated_energies_dict = { "approximated_eneriges_0": [],
"approximated_eneriges_1":[],
"approximated_eneriges_2": [],
"approximated_eneriges_3": []}
def initialize_approximated_energies_dict():
return { "approximated_eneriges_0": [],
"approximated_eneriges_1":[],
"approximated_eneriges_2": [],
"approximated_eneriges_3": []}
def insert_approximated_energy_to_list_of_all_approximated_energies(approximated_energies_list, energy):
approximated_energies_list.append(energy)
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
def plot_convergence_of_optimization_process(approximated_energies, hamiltonian, margin=0.02):
plt.title("convergence of optimization process to the exact eigenvalue")
plt.margins(0,margin)
base_colors_list = list(mcolors.BASE_COLORS.keys())
exact_k_eigenvalues = get_exact_k_eigenvalues_of_hamiltonian(hamiltonian, K)
print(exact_k_eigenvalues)
for energy_level, eigenvalue in enumerate(exact_k_eigenvalues):
energy_level_name = "E_{0}".format(str(energy_level))
plt.axhline(y = eigenvalue,
color = base_colors_list[energy_level],
linestyle = 'dotted', label=energy_level_name)
plt.plot(approximated_energies["approximated_eneriges_{0}".format(str(energy_level))],
color = base_colors_list[energy_level],
label="Weighted_SSVQE({0})".format(energy_level_name))
# plt.plot(approximated_energies["approximated_eneriges_0"])
# plt.plot(approximated_energies["approximated_eneriges_1"])
# plt.plot(approximated_energies["approximated_eneriges_2"])
# plt.plot(approximated_energies["approximated_eneriges_3"])
plt.xlabel("# of iterations")
plt.ylabel("Energy")
plt.legend(loc='center left', bbox_to_anchor=(1, 0.5))
def plot_fidelity():
plt.plot(LiH_approximated_energies)
plt.xlabel("# of iterations")
plt.ylabel("Energy")
from qiskit.opflow import X, Z, Y, I, H, S
LiH_molecule_4_qubits = -7.49894690201071*(I^I^I^I) + \
-0.0029329964409502266*(X^X^Y^Y) + \
0.0029329964409502266*(X^Y^Y^X) + \
0.01291078027311749*(X^Z^X^I) + \
-0.0013743761078958677*(X^Z^X^Z) + \
0.011536413200774975*(X^I^X^I) + \
0.0029329964409502266*(Y^X^X^Y) + \
-0.0029329964409502266*(Y^Y^X^X) + \
0.01291078027311749*(Y^Z^Y^I) + \
-0.0013743761078958677*(Y^Z^Y^Z) + \
0.011536413200774975*(Y^I^Y^I) + \
0.16199475388004184*(Z^I^I^I) + \
0.011536413200774975*(Z^X^Z^X) + \
0.011536413200774975*(Z^Y^Z^Y) + \
0.12444770133137588*(Z^Z^I^I) + \
0.054130445793298836*(Z^I^Z^I) + \
0.05706344223424907*(Z^I^I^Z) + \
0.012910780273117487*(I^X^Z^X) + \
-0.0013743761078958677*(I^X^I^X) + \
0.012910780273117487*(I^Y^Z^Y) + \
-0.0013743761078958677*(I^Y^I^Y) + \
0.16199475388004186*(I^Z^I^I) + \
0.05706344223424907*(I^Z^Z^I) + \
0.054130445793298836*(I^Z^I^Z) + \
-0.013243698330265966*(I^I^Z^I) + \
0.08479609543670981*(I^I^Z^Z) + \
-0.013243698330265952*(I^I^I^Z)
%%time
LiH_approximated_k_eigenvalues = get_approximated_k_eigenvalues_of_hamiltonian(LiH_molecule_4_qubits)
compare_exact_and_approximated_eigenvectors(LiH_molecule_4_qubits, LiH_approximated_k_eigenvalues)
print(approximated_energies_dict)
approximated_energies_dict = initialize_approximated_energies_dict()
LiH_approximated_energies = {'approximated_eneriges_0': [-7.443763256904104, -7.4002130802981165, -7.402247491880844, -7.470848596022202, -7.45320004578142, -7.2037442823809394, -7.606622032604259, -7.432350599744895, -7.432495103535102, -7.141159809219269, -7.34603922757036, -7.476135398795488, -7.280043003574207, -7.4614181224914295, -7.407924717612185, -7.461586578652535, -7.525445976535891, -7.422114431402694, -7.401649526037618, -7.488021953946464, -7.47896570893905, -7.462685937161847, -7.454120832230556, -7.436292572707697, -7.480688115871342, -7.515063846777348, -7.477177021961932, -7.391244710949009, -7.471217858315684, -7.503242588552382, -7.471439257727218, -7.44505573833778, -7.418285185624123, -7.466695823049642, -7.4771052531993325, -7.4637738318283535, -7.520776558858023, -7.526230791574609, -7.533608947411593, -7.503004948009757, -7.519724331102011, -7.493384913528219, -7.485478644775202, -7.516510223399673, -7.503475090881356, -7.494010354458551, -7.510090310795372, -7.526632388070386, -7.492160858734219, -7.5090846022988345], 'approximated_eneriges_1': [-7.611160770738447, -7.612537039823402, -7.5628667736575075, -7.627321643310454, -7.602218901158253, -7.669321267055824, -7.112869137843162, -7.529831878035033, -7.492031424566759, -7.546144927687019, -7.5380518543846815, -7.619806507952486, -7.536960192278364, -7.430594135829916, -7.558781662996708, -7.620192075334588, -7.500080654402885, -7.5874392595184466, -7.60518715593763, -7.587653509223957, -7.612775269021471, -7.6068484660945295, -7.599678769877363, -7.589714279771383, -7.60619548365883, -7.51735676728312, -7.612125836144872, -7.6014638647121675, -7.5899647846917055, -7.5976032888517775, -7.597212073112908, -7.558188737021209, -7.601200874808052, -7.607713345897209, -7.607499093171809, -7.599792654361252, -7.5596730670773855, -7.573728870000363, -7.546383632358012, -7.583001966857374, -7.5523102781572735, -7.560199542695961, -7.588780755315564, -7.566078651167328, -7.5879779290873905, -7.551861316141719, -7.573269260993632, -7.5817304433034804, -7.579569386092089, -7.570120795581553], 'approximated_eneriges_2': [-7.470829844981112, -7.470523575311227, -7.437547474097366, -7.489185208098881, -7.490140854087586, -7.406399694105737, -7.590301545017305, -7.541698353920802, -7.3691554663088015, -7.5191215141999335, -7.5115133084041545, -7.479635969058671, -7.567154091041735, -7.50831667284109, -7.404328307409327, -7.5010681837274165, -7.4650688490182455, -7.472575860441914, -7.402811603611692, -7.488550998068402, -7.488801074870055, -7.487994212250475, -7.515666333417201, -7.544214178703916, -7.510926968697341, -7.5173523503867195, -7.516193644717367, -7.53534000298624, -7.523519316290358, -7.455126696410415, -7.491381392393936, -7.504298259865865, -7.554652346024801, -7.523103712442472, -7.4955202720183, -7.517862423002627, -7.519654460714506, -7.518381698117194, -7.505702129067322, -7.504489391632537, -7.513392952340638, -7.5270772264781485, -7.519299542624053, -7.516485116618228, -7.50529569871512, -7.523333441799501, -7.499747575849092, -7.512325163721414, -7.52439763900249, -7.516395718429318], 'approximated_eneriges_3': [-7.32849500423405, -7.391564768264744, -7.474600394267608, -7.364808119047038, -7.381820772708144, -7.738911447566172, -7.758703374786833, -7.337171319897428, -7.381997666733045, -7.7142353175373115, -7.553174001897375, -7.381334761150993, -7.432289783474271, -7.368363081328347, -7.3468625031342345, -7.361828638208896, -7.480664471801326, -7.400110228803251, -7.3144431418222435, -7.368928231722106, -7.364078865897079, -7.373915189743662, -7.364944693985124, -7.3659051775080195, -7.361913922683342, -7.393984696256876, -7.358970234887909, -7.374457680841522, -7.380263158291077, -7.334590298526401, -7.362071851140452, -7.386812482151001, -7.350540699194575, -7.371636446671611, -7.367436744048734, -7.364018994060641, -7.366669879511723, -7.352155755509138, -7.36382240372502, -7.361211381137372, -7.395275852423786, -7.356090854960467, -7.385525123953955, -7.369782537122054, -7.388817786814771, -7.378669588844872, -7.38373310976381, -7.353810063874061, -7.387305671775982, -7.39466794423844]}
plot_convergence_of_optimization_process(LiH_approximated_energies, LiH_molecule_4_qubits, margin=0.02)
H2_molecule_Hamiltonian_4_qubits = -0.8105479805373279 * (I^I^I^I) \
+ 0.1721839326191554 * (I^I^I^Z) \
- 0.22575349222402372 * (I^I^Z^I) \
+ 0.17218393261915543 * (I^Z^I^I) \
- 0.2257534922240237 * (Z^I^I^I) \
+ 0.12091263261776627 * (I^I^Z^Z) \
+ 0.16892753870087907 * (I^Z^I^Z) \
+ 0.045232799946057826 * (Y^Y^Y^Y) \
+ 0.045232799946057826 * (X^X^Y^Y) \
+ 0.045232799946057826 * (Y^Y^X^X) \
+ 0.045232799946057826 * (X^X^X^X) \
+ 0.1661454325638241 * (Z^I^I^Z) \
+ 0.1661454325638241 * (I^Z^Z^I) \
+ 0.17464343068300453 * (Z^I^Z^I) \
+ 0.12091263261776627 * (Z^Z^I^I)
%%time
H2_approximated_k_eigenvalues = get_approximated_k_eigenvalues_of_hamiltonian(H2_molecule_Hamiltonian_4_qubits)
compare_exact_and_approximated_eigenvectors(H2_molecule_Hamiltonian_4_qubits, H2_approximated_k_eigenvalues)
print(approximated_energies_dict)
approximated_energies_dict = initialize_approximated_energies_dict()
H2_approximated_energies = {'approximated_eneriges_0': [-7.6847981551656215, -7.69669203350899, -7.695360282155182, -7.678547396735197, -7.682475520277694, -7.6665142799074735, -7.628511929237866, -7.727019079759623, -7.674672621892967, -7.782410750059304, -7.782640995023298, -7.774731391845236, -7.820098880570926, -7.644963955279764, -7.765933104421869, -7.689259899346986, -7.75838188322518, -7.7617232185924685, -7.6749058485455, -7.7606516385721775, -7.628823093333026, -7.778442627599486, -7.745777242153594, -7.753227986202937, -7.784556444100247, -7.756083187584806, -7.714476381527707, -7.780522704585265, -7.776979399600117, -7.782311933837449, -7.7842922352561335, -7.7870034099757515, -7.778992899075237, -7.787348917202359, -7.781744204782898, -7.789211430733308, -7.7871397501264985, -7.784088445887376, -7.793805473659068, -7.79346880686618, -7.786308107923922, -7.7925468325707765, -7.793338173915457, -7.78652494500572, -7.790090500177619, -7.792533180308775, -7.7962537918904715, -7.78963405481515, -7.786085398062213, -7.7891853374630635], 'approximated_eneriges_1': [-7.674684523604055, -7.680764074432957, -7.684992567218362, -7.683800571677806, -7.680390184089667, -7.721622516127985, -7.295633734656554, -7.7311487161990256, -7.678587133102517, -7.662425555106433, -7.669138289334058, -7.6673461427248775, -7.626942993490443, -7.538153577774583, -7.662429920440635, -7.619523577002202, -7.614356108241046, -7.658931116094572, -7.761466767269052, -7.64876243086473, -7.575843530150479, -7.675840508678627, -7.587039305802285, -7.66134535231588, -7.659686693231967, -7.6135464123687475, -7.651463803918251, -7.634151979073155, -7.665419894321144, -7.653707767256248, -7.659251797898335, -7.658200706731602, -7.671972673195233, -7.66434999274741, -7.663813235960182, -7.666611902147287, -7.667328389333765, -7.658213410128788, -7.663109239237157, -7.669688709053952, -7.669483352101843, -7.666970692695458, -7.67011145442623, -7.66774490260206, -7.66767261347493, -7.671932371682364, -7.671697879258323, -7.664936996622855, -7.665002841620933, -7.668432858833779], 'approximated_eneriges_2': [-7.216994389513745, -7.162295345496143, -7.340953879090269, -7.354575085834582, -7.25564377642011, -7.148940094695811, -7.524402673550271, -7.354347811404502, -7.25889495057094, -7.643589020627088, -7.644947961476648, -7.625158816558789, -7.620703327132717, -7.45620769838637, -7.630870366832682, -7.575290709380177, -7.596165182631779, -7.637811242834557, -7.170274298321406, -7.641715648367393, -7.601007658607277, -7.599962246378673, -7.554443833932802, -7.635475447591654, -7.64486017630937, -7.626536753201153, -7.6322795435642625, -7.610659904945782, -7.642214540537407, -7.630361126826373, -7.645346880047898, -7.6443043653096305, -7.616965316828286, -7.644233130202644, -7.64564265540827, -7.648497631150577, -7.647931469579165, -7.645272451577426, -7.650160805708954, -7.64876250969817, -7.646823091092999, -7.645297203651874, -7.641287946379679, -7.648284082427012, -7.6468976982996475, -7.6442778318847076, -7.649731833380351, -7.647619040578347, -7.648140904559129, -7.647936421498813], 'approximated_eneriges_3': [-7.202290172665147, -7.136542775453234, -7.32557094169548, -7.3304047498628275, -7.250215528560754, -7.530121383747615, -7.674756284215522, -7.3437821085023725, -7.25926128948872, -7.043725550448698, -7.048032766005656, -7.062091983030029, -7.015079505078198, -7.130094283026538, -7.023198238540297, -6.894206716999318, -6.948244787472701, -7.045666589563991, -7.516441009890359, -7.043138953607762, -7.164113379397319, -7.083629601908816, -6.994407404756581, -7.024569950050662, -7.042675844714379, -7.071398804304009, -7.030579249445848, -6.970942611477129, -7.0452067433138, -7.009655723846796, -7.0465525569622045, -7.041138823294234, -7.0758293298141, -7.037825997609188, -7.042134113140199, -7.045247103049186, -7.04832718431786, -7.060394271726066, -7.041607839469861, -7.04191968859915, -7.038852427210924, -7.034303963384438, -7.046001232407491, -7.0401609547447235, -7.040921144894931, -7.04670117664207, -7.043097516559149, -7.038106821967233, -7.045959853355035, -7.042930913127023]}
plot_convergence_of_optimization_process(H2_approximated_energies, H2_molecule_Hamiltonian_4_qubits,margin=0.01)
transverse_ising_4_qubits = 0.0 * (I^I^I^I) \
+ 0.8398088405253477 * (X^I^I^I) \
+ 0.7989496312070936 * (I^X^I^I) \
+ 0.38189710487113193 * (Z^Z^I^I) \
+ 0.057753122422666725 * (I^I^X^I) \
+ 0.5633292636970458 * (Z^I^Z^I) \
+ 0.3152740621483513 * (I^Z^Z^I) \
+ 0.07209487981989715 * (I^I^I^X) \
+ 0.17892334004292654 * (Z^I^I^Z) \
+ 0.2273896497668042 * (I^Z^I^Z) \
+ 0.09762902934216211 * (I^I^Z^Z)
%%time
TI_approximated_k_eigenvalues = get_approximated_k_eigenvalues_of_hamiltonian(transverse_ising_4_qubits)
compare_exact_and_approximated_eigenvectors(transverse_ising_4_qubits, TI_approximated_k_eigenvalues)
print(approximated_energies_dict)
approximated_energies_dict = initialize_approximated_energies_dict()
TI_approximated_energies = {'approximated_eneriges_0': [-7.589752024122858, -7.613360553742977, -7.6190283377699295, -7.606452381315795, -7.623841264856606, -7.494521829539001, -7.646521400209204, -7.497441846730476, -7.679252378794595, -7.568306667439035, -7.635326747625471, -7.581974996633829, -7.6029476683468165, -7.629264364655602, -7.622068391999914, -7.639909424564434, -7.658080921293223, -7.6610216888186935, -7.654527411413256, -7.66008477955216, -7.7547150031040335, -7.7564360961248395, -7.7211692300067325, -7.740308604020784, -7.600566578864045, -7.745346804765525, -7.7462796221068615, -7.751641127972047, -7.731226373852388, -7.759764904228919, -7.738323394248081, -7.75008559994191, -7.776677950424584, -7.753426121197687, -7.782341273752688, -7.779205848396213, -7.748582934815819, -7.770913423670053, -7.762781290918378, -7.757243053876988, -7.771747073785976, -7.77460241775567, -7.768169945808579, -7.775293924988296, -7.777833875967182, -7.772874566073456, -7.770639259052609, -7.780183175053531, -7.770198633263086, -7.772715721535181], 'approximated_eneriges_1': [-7.479491405676765, -7.511836148005719, -7.386839072151142, -7.482910503302419, -7.45350504578557, -7.717645422348506, -7.557130209537956, -7.585292224236378, -7.601455267806437, -7.6053728445146245, -7.652940774863644, -7.495571799306382, -7.498805036929139, -7.665075417141012, -7.564424290629817, -7.649242137492966, -7.63973609380236, -7.662321437170673, -7.6197253632972295, -7.619795999950689, -7.77220111836819, -7.7560901206803, -7.733399518265041, -7.731248976846906, -7.5715275315884965, -7.707440626139587, -7.707393893999951, -7.7348112389201, -7.6963929548826515, -7.7303082911355006, -7.716146462527111, -7.726011057644771, -7.754736352832551, -7.7244308215718, -7.755435989771994, -7.740311979126285, -7.75802286075666, -7.74587377621213, -7.7511355458410875, -7.7524697184268225, -7.752276487330399, -7.752209127687969, -7.745506448113101, -7.763323596450217, -7.753689897688524, -7.761008277453863, -7.742591039142208, -7.750704035603405, -7.754889646373152, -7.762317652046046], 'approximated_eneriges_2': [-7.429773687068325, -7.456290835401122, -7.5244382722139695, -7.449488807771006, -7.475902887301357, -7.323710694006624, -7.382629223743793, -7.319565894330178, -7.37324196562631, -7.4655637009696845, -7.292361426064088, -7.305355248566785, -7.349061659711274, -7.423506442892262, -7.487123730123055, -7.419043739762055, -7.4468612412996995, -7.429270866973703, -7.449287078710123, -7.488601777023326, -7.338899993772503, -7.3479680423849905, -7.4752168162071655, -7.499949509399753, -7.438503219564106, -7.490451691757577, -7.478437506558136, -7.500437702418609, -7.500581801475034, -7.499075900701008, -7.502121265617482, -7.491113049098129, -7.518867376724795, -7.626022727858267, -7.528977849213658, -7.51704786926269, -7.341426863319758, -7.492808200100214, -7.491951333497299, -7.513636940451013, -7.517112352002725, -7.519479170352952, -7.532633970484797, -7.531363773844777, -7.533977320554524, -7.527126270896771, -7.527817041278419, -7.526558961818585, -7.533610800208856, -7.53189647381379], 'approximated_eneriges_3': [-7.491338578949814, -7.5365715669859465, -7.532419245094768, -7.536703941979599, -7.547853449746403, -7.624626489025748, -7.534978590313114, -7.508989186601839, -7.445225566309921, -7.443181538165437, -7.482755392167175, -7.491627334989187, -7.448561403824932, -7.450744878426274, -7.3527159389057335, -7.429044714148724, -7.453107440745492, -7.43199903518407, -7.426905138160319, -7.471734210770166, -7.394515983381335, -7.402658524799258, -7.382535100794421, -7.3287228122787855, -7.4052951836113845, -7.3303577854783635, -7.339337904181725, -7.340771690542788, -7.340357772707655, -7.316555819042501, -7.333550487910194, -7.313936474027675, -7.31041466499232, -7.227826572283069, -7.263505884929646, -7.299661733764759, -7.4931242665258, -7.314755252756475, -7.3482236593292924, -7.29989242094733, -7.3017643952015465, -7.296684067035896, -7.284748556671026, -7.276492262521696, -7.272782406124991, -7.295223632281355, -7.3008113357190965, -7.27265620287829, -7.284622446048762, -7.278514057888236]}
plot_convergence_of_optimization_process(TI_approximated_energies, transverse_ising_4_qubits, )
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.