repo
stringclasses 885
values | file
stringclasses 741
values | content
stringlengths 4
215k
|
|---|---|---|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import pulse
from qiskit.providers.fake_provider import FakeArmonk
backend = FakeArmonk()
with pulse.build(backend) as drive_sched:
d0 = pulse.drive_channel(0)
a0 = pulse.acquire_channel(0)
pulse.play(pulse.library.Constant(10, 1.0), d0)
pulse.delay(20, d0)
pulse.shift_phase(3.14/2, d0)
pulse.set_phase(3.14, d0)
pulse.shift_frequency(1e7, d0)
pulse.set_frequency(5e9, d0)
with pulse.build() as temp_sched:
pulse.play(pulse.library.Gaussian(20, 1.0, 3.0), d0)
pulse.play(pulse.library.Gaussian(20, -1.0, 3.0), d0)
pulse.call(temp_sched)
pulse.acquire(30, a0, pulse.MemorySlot(0))
drive_sched.draw()
|
https://github.com/animeshnanda1/my_QAOA_qiskit
|
animeshnanda1
|
import qiskit
qiskit.__qiskit_version__
# import warnings; warnings.filterwarnings("ignore")
import numpy as np
import networkx as nx
import matplotlib.pyplot as plt
from collections import defaultdict
from operator import itemgetter
from scipy.optimize import minimize
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer
from qiskit.visualization import plot_histogram
G = nx.Graph()
Lx=6
G.add_nodes_from([i for i in range(Lx)])
G.add_edges_from([[i,i+1] for i in range(Lx-1)])
G.add_edges_from([[Lx-1,0]])
options = {
'node_color': 'y',
'node_size': 1000,
'width': 3,
}
nx.draw(G, with_labels=True,pos=nx.circular_layout(G),**options)
print(list(G.edges()))
print(G.number_of_nodes())
def ham_rot(G,gamma):
L=G.number_of_nodes()
qc=QuantumCircuit(L,L)
for i,j in list(G.edges()):
qc.cx(i,j)
qc.rz(2*gamma,j)
qc.cx(i,j)
return qc
qc = ham_rot(G, np.pi/3)
print(G.edges())
qc.draw()
def x_field_rot(G, beta):
N = G.number_of_nodes()
qc = QuantumCircuit(N,N)
for n in G.nodes():
qc.rx(2*beta, n)
return qc
qc = x_field_rot(G, np.pi/3)
qc.draw()
def qaoa_circuit(G,beta,gamma):
assert(len(beta)==len(gamma))
layer=len(beta)
L=G.number_of_nodes()
qc=QuantumCircuit(L,L)
qc.h(range(L))
for k in range(layer):
qc=qc+ham_rot(G,gamma[k])
qc=qc+x_field_rot(G,beta[k])
qc.measure(range(L), range(L))
return qc
qc = qaoa_circuit(G,[np.pi/3], [np.pi/2])
qc.draw()
def invert_counts(counts):
return {k[::-1]:v for k, v in counts.items()}
backend = Aer.get_backend('qasm_simulator')
job = execute(qc, backend,shots=2048) # this is just a test run for the above circuit
result = job.result()
print(result.get_counts())
def ising_energy(x,G):
ener = 0
for i, j in G.edges():
if x[i] != x[j]:
# the edge is cut
ener += 1
elif x[i] == x[j]:
# the edge is cut
ener -= 1
return ener
ising_energy('010101', G),ising_energy('111110', G)
def compute_ising_energy(counts, G):
energy = 0
total_counts = 0
for meas, meas_count in counts.items(): # meas and meas_count are the state and freq
# print(type(meas),meas_count)
obj_for_meas = ising_energy(meas, G) # calling the state to compute the energy
energy += obj_for_meas * meas_count
total_counts += meas_count # energy is total energy of all the states
return energy / total_counts # total_counts is total number of sampling
compute_ising_energy(invert_counts(result.get_counts()), G)
invert_counts(result.get_counts());
# here p is the number of layer used for the optimize
def get_black_box_objective(G,p,list1):
backend = Aer.get_backend('qasm_simulator')
def f(theta):
# let's assume first half is betas, second half is gammas
# theta is a 2*p length array, first 'p' entries are gamma and rest are beta
beta = theta[:p]
gamma = theta[p:]
qc = qaoa_circuit(G,beta, gamma)
counts = execute(qc, backend,shots=1024, seed_simulator=100).result().get_counts()
# return the energy
ener=compute_ising_energy(invert_counts(counts), G)
list1.append(ener)
return ener, list1
return f
# p is the number of QAOA alternating operators
p = 5
energy_qasm=[]
obj = get_black_box_objective(G, p, energy_qasm)
init_point = np.array([0.81069872, 2.2067517 , 1.83830696, 2.15579759, 0.37060699,
2.42068091, 6.1575306 , 2.2453419 , 0.85060091, 3.137845 ])
# We are going to limit the number of iterations to 2500
res_sample = minimize(obj, init_point, method='COBYLA', options={'maxiter':2500, 'disp': True})
res_sample
# Once we have gotten the optimum beta and gamma we run the circuit again with the
optimal_theta = res_sample['x']
qc = qaoa_circuit(G, optimal_theta[:p], optimal_theta[p:])
counts = invert_counts(execute(qc, backend,shots=2048).result().get_counts())
counts
plot_histogram(counts,figsize=(12,4))
# get the best solution:
best_cut, best_solution = min([(ising_energy(x,G),x) for x in counts.keys()], key=itemgetter(0))
print(f"Best string: {best_solution} with cut: {-best_cut}")
# color the graph nodes by part
colors = ['c' if best_solution[node] == '0' else 'y' for node in G]
options = {
'node_size': 1000,
'width': 3,
}
nx.draw(G, with_labels=True,node_color = colors,pos=nx.circular_layout(G),**options)
len(energy_qasm);
def state_to_ampl_counts(vec, eps=1e-15):
"""Converts a statevector to a dictionary
of bitstrings and corresponding amplitudes
"""
qubit_dims = np.log2(vec.shape[0])
if qubit_dims % 1:
raise ValueError("Input vector is not a valid statevector for qubits.")
qubit_dims = int(qubit_dims)
counts = {}
str_format = '0{}b'.format(qubit_dims)
for kk in range(vec.shape[0]):
val = vec[kk]
if val.real**2+val.imag**2 > eps:
counts[format(kk, str_format)] = val
return counts
def compute_ising_energy_sv(sv, G):
"""Compute objective from statevector
For large number of qubits, this is slow.
"""
counts = state_to_ampl_counts(sv)
return sum(ising_energy(np.array([int(x) for x in k]), G) * (np.abs(v)**2) for k, v in counts.items())
def get_qaoa_circuit_sv(G, beta, gamma):
assert(len(beta) == len(gamma))
p = len(beta) # infering number of QAOA steps from the parameters passed
N = G.number_of_nodes()
qc = QuantumCircuit(N,N)
# first, apply a layer of Hadamards
qc.h(range(N))
# second, apply p alternating operators
for k in range(p):
qc=qc+ham_rot(G,gamma[k])
qc=qc+x_field_rot(G,beta[k])
# no measurement in the end!
return qc
def get_black_box_objective_sv(G,p,list1):
backend = Aer.get_backend('statevector_simulator')
def f(theta):
# let's assume first half is betas, second half is gammas
beta = theta[:p]
gamma = theta[p:]
qc = get_qaoa_circuit_sv(G,beta, gamma)
sv = execute(qc, backend).result().get_statevector() # the sv is np.array with complex entries
# return the energy
ener=compute_ising_energy_sv(sv, G)
list1.append(ener)
return ener, list1
return f
# p is the number of QAOA alternating operators
energy_sv=[]
obj = get_black_box_objective_sv(G, p, energy_sv)
init_point = np.array([0.81069872, 2.2067517 , 0.83830696, 2.15579759, 0.37060699,
2.42068091, 6.1575306 , 2.2453419 , 3.85060091, 6.137845 ])
p = len(init_point)//2
# We are going to limit the number of iterations to 2500
res_sv = minimize(obj, init_point, method='COBYLA', options={'maxiter':2500, 'disp': True})
res_sv
# Once we have gotten the optimum beta and gamma we run the circuit again with the
backend = Aer.get_backend('qasm_simulator')
optimal_theta = res_sv['x']
qc = qaoa_circuit(G, optimal_theta[:p], optimal_theta[p:])
counts = invert_counts(execute(qc, backend,shots=2048).result().get_counts())
counts
plot_histogram(counts,figsize=(8,4))
len(energy_sv);
ms=6
x_sv=np.arange(1,len(energy_sv)+1)
x_qasm=np.arange(1,len(energy_qasm)+1)
plt.figure(figsize=(7,6))
plt.plot(x_sv,energy_sv,'b-',markersize=ms,label='Statevector')
plt.plot(x_qasm,energy_qasm,'r--',markersize=ms,label='QASM')
plt.xlabel('Iterations',fontsize=16)
plt.ylabel('Energy',fontsize=16)
plt.xticks(fontsize=16)
plt.yticks(fontsize=16)
plt.legend(fontsize=16)
# plt.title('Plot of gap for different $t_2$, at $t_1=0$ ')
plt.grid()
plt.tight_layout()
# plt.yscale('log')
# plt.legend(loc='upper right',fontsize=16)
# plt.savefig('%s/gap_t2.pdf'%(loc), bbox_inches='tight')
plt.show()
print(f"Angles found with samples: beta={res_sample['x'][:p]}, gamma={res_sample['x'][p:]}")
print(f"Angles found with full state: beta={res_sv['x'][:p]}, gamma={res_sv['x'][p:]}")
|
https://github.com/acfilok96/Quantum-Computation
|
acfilok96
|
# Quantum Computation
import qiskit
print(qiskit.__version__)
import qiskit.quantum_info as qi
from qiskit.circuit.library import FourierChecking
from qiskit.visualization import plot_histogram
f = [1, -1, -1, -1]
g = [1, 1, -1, -1]
# How co-related fourier transform of function g to function f.
# we will check for probability '00', if p(f,g) >= 0.05, then,
# fourier transform of function g co-related to function f.
circ = FourierChecking(f=f,g=g)
circ.draw()
zero = qi.Statevector.from_label('00') # '00' or '01' or '10' or '11'
sv = zero.evolve(circ)
probs = sv.probabilities_dict()
plot_histogram(probs)
|
https://github.com/jonasmaziero/computacao_quantica_qiskit_sbf_2023
|
jonasmaziero
|
import math; import numpy as np; phmax = 4*math.pi; npt = 100; dth = phmax/npt; ph = np.arange(0,phmax+dth,dth)
from matplotlib import pyplot as plt; PrD0 = 0.5*(1+np.cos(ph)); plt.plot(ph,PrD0, label=r'$Pr(D_0)$')
PrD0 = 0.5*(1-np.cos(ph)); plt.plot(ph,PrD0, label=r'$Pr(D_1)$'); plt.legend(); plt.xlabel(r'$\phi$'); plt.show()
from sympy import Matrix, sqrt
S = Matrix([[1,0],[0,1j]]); H = (1/sqrt(2))*Matrix([[1,1],[1,-1]])
S*H*S
Y = Matrix([[0,-1j],[1j,0]]); Z = Matrix([[1,0],[0,-1]]); Y*Z
from qiskit import QuantumCircuit
def qc_df(): # divisor de feixes 50:50
qc = QuantumCircuit(1, name='DF')
qc.s(0)
qc.h(0)
qc.s(0)
return qc
qcdf = qc_df(); qcdf.draw('mpl')
def qc_espelhos():
qc = QuantumCircuit(1, name='E')
qc.z(0)
qc.y(0)
return qc
qce = qc_espelhos(); qce.draw('mpl')
def qc_imz(ph): # retorna o circuito quΓ’ntico para o IMZ (sem as medidas)
qc = QuantumCircuit(1, name='IMZ')
qcdf = qc_df(); qc.append(qcdf, [0])
qce = qc_espelhos(); qc.append(qce, [0])
qc.p(ph, [0])
qcdf = qc_df(); qc.append(qcdf, [0])
return qc
qcimz = qc_imz(0); qcimz.draw('mpl')
# SimulaΓ§Γ£o clΓ‘ssica
from qiskit import Aer, execute
simulator = Aer.get_backend('qasm_simulator')
nshots = 2**13
import numpy as np; import math
phmax = 2*math.pi
npe = 6
dth = phmax/npe
ph = np.arange(0,phmax+dth,dth)
PD0sim = np.zeros(len(ph))
for j in range(0,len(ph)):
qc = QuantumCircuit(1,1)
qcimz = qc_imz(ph[j])
qc.append(qcimz,[0])
qc.measure(0,0)
job = execute(qc, backend=simulator, shots=nshots)
counts = job.result().get_counts()
if '0' in counts:
PD0sim[j] = counts['0']/nshots
print(PD0sim)
npt = 100
dtht = phmax/npt
pht = np.arange(0,phmax+dtht,dtht)
PD0teo = 0.5*(1+np.cos(pht))
from matplotlib import pyplot as plt
plt.plot(pht,PD0teo, label=r'$Pr(D_0)_{teo}$')
plt.plot(ph,PD0sim, 'o', label=r'$Pr(D_0)_{sim}$')
plt.legend(); plt.xlabel(r'$\phi$')
plt.show()
import qiskit
qiskit.IBMQ.save_account('a221013b3d88dd070a495178c3f732ac683a494e5af4e641383f16d361e9fa7fa22af7f09cad3f88988a3e6e5621c7fe951d8ca6ff0c0371422b211ec0ae9709',
overwrite = True)
qiskit.IBMQ.load_account()
#provider = qiskit.IBMQ.get_provider(hub='ibm-q', group='open', project='main')
provider = qiskit.IBMQ.get_provider(hub='ibm-q-research-2', group='federal-uni-sant-1', project='main')
device = provider.get_backend('ibm_nairobi')
nshots = 2**13
import numpy as np; import math
phmax = 2*math.pi
npe = 6
dth = phmax/npe
ph = np.arange(0,phmax+dth,dth)
job_ids = []
for j in range(0,len(ph)):
qc = QuantumCircuit(1,1)
qcimz = qc_imz(ph[j])
qc.append(qcimz,[0])
qc.measure(0,0)
job = execute(qc, backend=device, shots=nshots)
jobid = job.job_id()
job_ids.append(jobid)
print(jobid)
f = open("jobs_ids_IMZ.txt", "w")
f.write(str(job_ids))
f.close()
device = provider.get_backend('ibm_nairobi')
f = open("jobs_ids_IMZ.txt","r")
list_ids_IMZ = f.read().replace("'","").replace(" ","").replace("[","").replace("]","").split(",")
f.close()
PD0exp = np.zeros(len(ph))
for j in range(0,len(ph)):
job = device.retrieve_job(list_ids_IMZ[j])
counts = job.result().get_counts()
if '0' in counts:
PD0exp[j] = counts['0']/nshots
print(PD0exp)
npt = 100; dtht = phmax/npt; pht = np.arange(0,phmax+dtht,dtht)
PD0teo = 0.5*(1+np.cos(pht))
from matplotlib import pyplot as plt
plt.plot(pht,PD0teo, label=r'$Pr(D_0)_{teo}$')
plt.plot(ph,PD0sim, 'o', label=r'$Pr(D_0)_{sim}$')
plt.plot(ph,PD0exp, '*', label=r'$Pr(D_0)_{exp}$')
plt.legend()
plt.xlabel(r'$\phi$')
plt.show()
Vsim = (np.max(PD0sim)-np.min(PD0sim))/(np.max(PD0sim)+np.min(PD0sim)); print('Vsim = ',Vsim)
Vexp = (np.max(PD0exp)-np.min(PD0exp))/(np.max(PD0exp)+np.min(PD0exp)); print('Vexp = ',Vexp)
from sympy import Matrix, eye; P0 = Matrix([[1,0],[0,0]]); P1 = Matrix([[0,0],[0,1]]); X = Matrix([[0,1],[1,0]])
from sympy.physics.quantum import TensorProduct as tp; tp(eye(2),P0) + tp(X,P1)
def qc_bbo():
from qiskit import QuantumCircuit
qc = QuantumCircuit(2, name='BBO')
qc.x(1)
qc.h(0)
qc.cx(0,1)
return qc
qcbbo = qc_bbo(); qcbbo.draw('mpl')
def qc_dfp():
from qiskit import QuantumCircuit
qc = QuantumCircuit(2, name='DFP')
qc.cz(0,1)
qc.cy(0,1)
return qc
qcdfp = qc_dfp()
qcdfp.draw('mpl')
def qc_pmo():
from qiskit import QuantumCircuit
qc = QuantumCircuit(2, name='PMO')
qc.cx(1,0)
return qc
qcpmo = qc_pmo()
qcpmo.draw('mpl')
def qc_imz_ic(ph): # nΓ£o consideramos o caminho do fΓ³ton A
from qiskit import QuantumCircuit
qc = QuantumCircuit(3, name='IMZIC')
qcbbo = qc_bbo(); qc.append(qcbbo, [0,1])
qcdfp = qc_dfp(); qc.append(qcdfp, [1,2])
qcpmo = qc_pmo(); qc.append(qcpmo, [1,2])
qce = qc_espelhos(); qc.append(qce, [2])
qc.p(ph, [2])
qcdf = qc_df(); qc.append(qcdf, [2])
return qc
qcimzic = qc_imz_ic(0); qcimzic.draw('mpl')
qcimzic.decompose().draw('mpl')
qcimzic.decompose().decompose().decompose().draw('mpl')
# SimulaΓ§Γ£o clΓ‘ssica
from qiskit import Aer, execute
simulator = Aer.get_backend('qasm_simulator')
nshots = 2**13
import numpy as np; import math
phmax = 2*math.pi
npe = 5
dth = phmax/npe
ph = np.arange(0,phmax+dth,dth)
PD0sim = np.zeros(len(ph))
for j in range(0,len(ph)):
qc = QuantumCircuit(3,2)
qcimzic = qc_imz_ic(ph[j])
qc.append(qcimzic,[0,1,2])
qc.measure([0,2],[0,1])
job = execute(qc, backend=simulator, shots=nshots)
counts = job.result().get_counts()
if '00' in counts:
PD0sim[j] = counts['00']/nshots
if '10' in counts:
PD0sim[j] += counts['10']/nshots
print(PD0sim)
qc.draw('mpl')
import numpy as np; import math
phmax = 2*math.pi; npt = 100; dpht = phmax/npt
pht = np.arange(0,phmax+dtht,dtht)
PD0teo = 0.5*np.ones(len(pht))
from matplotlib import pyplot as plt
plt.plot(pht,PD0teo, label=r'$Pr(D_0)_{teo}$')
plt.plot(ph,PD0sim, 'o', label=r'$Pr(D_0)_{sim}$')
plt.ylim(0,1); plt.legend()
plt.xlabel(r'$\phi$')
plt.show()
import qiskit
qiskit.IBMQ.save_account('e20d3045c7c23a3be753606794714e9b47d4331ec46a41b2281e2d601bae27b2b3c1baa0b5cb54f3282a8b5248e552b14c9c556699010660fb94b11d00ff1073',
overwrite = True)
qiskit.IBMQ.load_account()
#provider = qiskit.IBMQ.get_provider(hub='ibm-q', group='open', project='main')
provider = qiskit.IBMQ.get_provider(hub='ibm-q-research-2', group='federal-uni-sant-1', project='main')
device = provider.get_backend('ibm_nairobi')
nshots = 2**13
import numpy as np; import math
phmax=2*math.pi
npe=5
dth=phmax/npe
ph=np.arange(0,phmax+dth,dth)
job_ids=[]
for j in range(0,len(ph)):
qc = QuantumCircuit(3,2)
qcimzic = qc_imz_ic(ph[j])
qc.append(qcimzic,[0,1,2])
qc.measure([0,2],[0,1])
job = execute(qc, backend=device, shots=nshots)
jobid = job.job_id()
job_ids.append(jobid)
f = open("jobs_ids_IMZIC.txt", "w")
f.write(str(job_ids))
f.close()
print(job_ids)
f = open("jobs_ids_IMZIC.txt","r")
list_ids_IMZIC = f.read().replace("'","").replace(" ","").replace("[","").replace("]","").split(",")
f.close()
phmax = 2*math.pi
npe=5
dth = phmax/npe
ph = np.arange(0,phmax+dth,dth)
PD0exp = np.zeros(len(ph))
device = provider.get_backend('ibm_nairobi')
for j in range(0,len(ph)):
job = device.retrieve_job(list_ids_IMZIC[j])
counts = job.result().get_counts()
if '00' in counts:
PD0exp[j] = counts['00']/nshots
if '10' in counts:
PD0exp[j] += counts['10']/nshots
print(PD0exp)
import numpy as np; import math
phmax = 2*math.pi; npt = 100; dpht = phmax/npt
pht = np.arange(0,phmax+dtht,dtht)
PD0teo = 0.5*np.ones(len(pht))
from matplotlib import pyplot as plt
plt.plot(pht,PD0teo, label=r'$Pr(D_0)_{teo}$')
plt.plot(ph,PD0sim, 'o', label=r'$Pr(D_0)_{sim}$')
plt.plot(ph,PD0exp, '*', label=r'$Pr(D_0)_{exp}$')
plt.ylim(0,1); plt.legend(); plt.xlabel(r'$\phi$'); plt.show()
Vsim = (np.max(PD0sim)-np.min(PD0sim))/(np.max(PD0sim)+np.min(PD0sim)); print('Vsim = ',Vsim)
Vexp = (np.max(PD0exp)-np.min(PD0exp))/(np.max(PD0exp)+np.min(PD0exp)); print('Vexp = ',Vexp)
import numpy as np; import math; phmax = 2*math.pi; npt = 100; dpht = phmax/npt; pht = np.arange(0,phmax+dpht,dpht)
PD0teoA0 = 0.5*(1+np.cos(pht)); PD0teoA1 = 0.5*(1-np.cos(pht))
from matplotlib import pyplot as plt
plt.plot(pht,PD0teoA0, label=r'$Pr(D_0|A=0)_{teo}$'); plt.plot(pht,PD0teoA1, label=r'$Pr(D_0|A=1)_{teo}$')
plt.xlim(0,2*math.pi); plt.xlim(-0.1,phmax+0.1); plt.ylim(-0.01,1.01); plt.legend(); plt.xlabel(r'$\phi$'); plt.show()
def qc_pqo():
from qiskit import QuantumCircuit
qc = QuantumCircuit(1, name='PQO')
qc.h(0)
qc.s(0)
return qc
qcpqo = qc_pqo()
qcpqo.draw('mpl')
def qc_apagadorQ(ph):
from qiskit import QuantumCircuit
qc = QuantumCircuit(3)
qcimzic = qc_imz_ic(ph)
qc.append(qcimzic, [0,1,2])
qcpqo = qc_pqo()
qc.append(qcpqo, [0])
return qc
qcaq = qc_apagadorQ(0)
qcaq.decompose().draw('mpl')
# SimulaΓ§Γ£o clΓ‘ssica
from qiskit import Aer, execute; simulator = Aer.get_backend('qasm_simulator'); nshots = 2**13
import numpy as np; import math; phmax = 2*math.pi; npe = 6; dth = phmax/npe; ph = np.arange(0,phmax+dth,dth)
PA0sim = np.zeros(len(ph)); PA1sim = np.zeros(len(ph)); PD0A0sim = np.zeros(len(ph)); PD0A1sim = np.zeros(len(ph))
for j in range(0,len(ph)):
qc = QuantumCircuit(3,2)
qcaq = qc_apagadorQ(ph[j])
qc.append(qcaq,[0,1,2])
qc.measure([0,2],[0,1])
job = execute(qc, backend=simulator, shots=nshots)
counts = job.result().get_counts()
if '00' in counts:
PA0sim[j] = counts['00']/nshots
if '01' in counts:
PA0sim[j] += counts['01']/nshots
if '10' in counts:
PA1sim[j] = counts['10']/nshots
if '11' in counts:
PA1sim[j] += counts['11']/nshots
if PA0sim[j] != 0 and '00' in counts:
PD0A0sim[j] = (counts['00']/nshots)/PA0sim[j]
if PA1sim[j] != 0 and '10' in counts:
PD0A1sim[j] = (counts['10']/nshots)/PA1sim[j]
print(PD0A0sim, PD0A1sim)
import numpy as np; import math
phmax = 2*math.pi; npt = 100; dpht = phmax/npt; pht = np.arange(0,phmax+dpht,dpht)
PD0teoA0 = 0.5*(1+np.cos(pht)); PD0teoA1 = 0.5*(1-np.cos(pht))
from matplotlib import pyplot as plt
plt.plot(pht,PD0teoA0, label=r'$Pr(D_0|A=0)_{teo}$')
plt.plot(pht,PD0teoA1, label=r'$Pr(D_0|A=1)_{teo}$')
plt.plot(ph,PD0A0sim, 'o', label=r'$Pr(D_0|A=0)_{sim}$')
plt.plot(ph,PD0A1sim, 's', label=r'$Pr(D_0|A=1)_{sim}$')
plt.xlim(-0.1,2*math.pi+0.1); plt.ylim(-0.01,1.02); plt.legend(); plt.xlabel(r'$\phi$'); plt.show()
import qiskit
qiskit.IBMQ.save_account('dabd4674f7b3794f740813fec0c5478bfefdebb7d1dca9b7acd41e3f90ed2c8a8b80af26fb3236289fbfc70d0ea334829a836453ac46f96fee68abcb22495ef4',
overwrite = True)
qiskit.IBMQ.load_account()
#provider = qiskit.IBMQ.get_provider(hub='ibm-q', group='open', project='main')
provider = qiskit.IBMQ.get_provider(hub='ibm-q-research-2', group='federal-uni-sant-1', project='main')
device = provider.get_backend('ibm_nairobi')
nshots = 2**13
import numpy as np; import math
phmax=2*math.pi
npe=6
dth=phmax/npe
ph=np.arange(0,phmax+dth,dth)
job_ids=[]
for j in range(0,len(ph)):
qc = QuantumCircuit(3,2)
qcaq = qc_apagadorQ(ph[j])
qc.append(qcaq,[0,1,2])
qc.measure([0,2],[0,1])
job = execute(qc, backend=device, shots=nshots)
jobid = job.job_id()
job_ids.append(jobid)
print(jobid)
f = open("jobs_ids_apagador.txt", "w")
f.write(str(job_ids))
f.close()
f = open("jobs_ids_apagador.txt","r")
list_ids_apagador = f.read().replace("'","").replace(" ","").replace("[","").replace("]","").split(",")
f.close()
phmax = 2*math.pi; npe=6; dth = phmax/npe; ph = np.arange(0,phmax+dth,dth)
PD0A0exp = np.zeros(len(ph)); PD0A1exp = np.zeros(len(ph)); PA0exp = np.zeros(len(ph)); PA1exp = np.zeros(len(ph))
device = provider.get_backend('ibm_nairobi')
for j in range(0,len(ph)):
job = device.retrieve_job(list_ids_apagador[j])
counts = job.result().get_counts()
if '00' in counts:
PA0exp[j] = counts['00']/nshots
if '01' in counts:
PA0exp[j] += counts['01']/nshots
if '10' in counts:
PA1exp[j] = counts['10']/nshots
if '11' in counts:
PA1exp[j] += counts['11']/nshots
if PA0exp[j] != 0 and '00' in counts:
PD0A0exp[j] = (counts['00']/nshots)/PA0exp[j]
if PA1exp[j] != 0 and '10' in counts:
PD0A1exp[j] = (counts['10']/nshots)/PA1exp[j]
print(PD0A0exp,PD0A1exp)
import numpy as np; import math
phmax = 2*math.pi; npt = 100; dpht = phmax/npt
pht = np.arange(0,phmax+dpht,dpht)
PD0teoA0 = 0.5*(1+np.cos(pht)); PD0teoA1 = 0.5*(1-np.cos(pht))
from matplotlib import pyplot as plt
plt.plot(pht,PD0teoA0, label=r'$Pr(D_0|A=0)_{teo}$'); plt.plot(pht,PD0teoA1, label=r'$Pr(D_0|A=1)_{teo}$')
plt.plot(ph,PD0A0sim, 'o', label=r'$Pr(D_0|A=0)_{sim}$'); plt.plot(ph,PD0A1sim, 's', label=r'$Pr(D_0|A=1)_{sim}$')
plt.plot(ph,PD0A0exp, '*', label=r'$Pr(D_0|A=0)_{exp}$'); plt.plot(ph,PD0A1exp, '+', label=r'$Pr(D_0|A=1)_{exp}$')
plt.xlim(-0.1,2*math.pi+0.1); plt.ylim(-0.02,1.02); plt.legend(bbox_to_anchor=(1.4, 1.0),loc='upper right')
plt.xlabel(r'$\phi$'); plt.show()
VsimA0 = (np.max(PD0A0sim)-np.min(PD0A0sim))/(np.max(PD0A0sim)+np.min(PD0A0sim))
print('VsimA0 = ',VsimA0)
VsimA1 = (np.max(PD0A1sim)-np.min(PD0A1sim))/(np.max(PD0A1sim)+np.min(PD0A1sim))
print('VsimA1 = ',VsimA1)
VexpA0 = (np.max(PD0A0exp)-np.min(PD0A0exp))/(np.max(PD0A0exp)+np.min(PD0A0exp))
print('VexpA0 = ',VexpA0)
VexpA1 = (np.max(PD0A1exp)-np.min(PD0A1exp))/(np.max(PD0A1exp)+np.min(PD0A1exp))
print('VexpA1 = ',VexpA1)
import qiskit
qiskit.IBMQ.save_account('e20d3045c7c23a3be753606794714e9b47d4331ec46a41b2281e2d601bae27b2b3c1baa0b5cb54f3282a8b5248e552b14c9c556699010660fb94b11d00ff1073',
overwrite = True)
qiskit.IBMQ.load_account()
#provider = qiskit.IBMQ.get_provider(hub='ibm-q', group='open', project='main')
provider = qiskit.IBMQ.get_provider(hub='ibm-q-research-2', group='federal-uni-sant-1', project='main')
device = provider.get_backend('ibm_nairobi')
nshots = 2**13
from qiskit import QuantumRegister, execute
from qiskit.ignis.mitigation.measurement import complete_meas_cal
qr = QuantumRegister(3)
qubit_list = [0, 2]
meas_calibs, state_labels = complete_meas_cal(qubit_list = qubit_list, qr = qr)
job = execute(meas_calibs, backend=device, shots=nshots)
print(job.job_id())
from qiskit.ignis.mitigation.measurement import CompleteMeasFitter
job = device.retrieve_job('cmp2xzqyj8fg0080m0e0')
cal_results = job.result()
meas_fitter = CompleteMeasFitter(cal_results, state_labels)
f = open("jobs_ids_apagador.txt","r")
list_ids_apagador = f.read().replace("'","").replace(" ","").replace("[","").replace("]","").split(",")
f.close()
phmax = 2*math.pi; npe=6; dth = phmax/npe; ph = np.arange(0,phmax+dth,dth)
PD0A0exp_mit = np.zeros(len(ph)); PD0A1exp_mit = np.zeros(len(ph)); PA0exp_mit = np.zeros(len(ph)); PA1exp_mit = np.zeros(len(ph))
device = provider.get_backend('ibm_nairobi')
for j in range(0,len(ph)):
job = device.retrieve_job(list_ids_apagador[j])
mitigated_results = meas_fitter.filter.apply(job.result())
mitigated_counts = mitigated_results.get_counts()
if '00' in counts:
PA0exp_mit[j] = mitigated_counts['00']/nshots
if '01' in counts:
PA0exp_mit[j] += mitigated_counts['01']/nshots
if '10' in counts:
PA1exp_mit[j] = mitigated_counts['10']/nshots
if '11' in counts:
PA1exp_mit[j] += mitigated_counts['11']/nshots
if PA0exp_mit[j] != 0 and '00' in mitigated_counts:
PD0A0exp_mit[j] = (mitigated_counts['00']/nshots)/PA0exp[j]
if PA1exp[j] != 0 and '10' in mitigated_counts:
PD0A1exp_mit[j] = (mitigated_counts['10']/nshots)/PA1exp[j]
print(PD0A0exp_mit, PD0A1exp_mit)
import matplotlib; matplotlib.rcParams.update({'font.size':11}); plt.figure(figsize = (7,5), dpi = 100)
import numpy as np; import math; phmax = 2*math.pi; npt = 100; dpht = phmax/npt; pht = np.arange(0,phmax+dpht,dpht)
PD0teoA0 = 0.5*(1+np.cos(pht)); PD0teoA1 = 0.5*(1-np.cos(pht)); from matplotlib import pyplot as plt
plt.plot(pht,PD0teoA0, label=r'$Pr(D_0|A=0)_{teo}$'); plt.plot(pht,PD0teoA1, label=r'$Pr(D_0|A=1)_{teo}$')
plt.plot(ph,PD0A0sim, 'o', label=r'$Pr(D_0|A=0)_{sim}$'); plt.plot(ph,PD0A1sim, 's', label=r'$Pr(D_0|A=1)_{sim}$')
plt.plot(ph,PD0A0exp, '*', label=r'$Pr(D_0|A=0)_{exp}$'); plt.plot(ph,PD0A1exp, 'v', label=r'$Pr(D_0|A=1)_{exp}$')
plt.plot(ph,PD0A0exp_mit, '^', label=r'$Pr(D_0|A=0)_{expmit}$'); plt.plot(ph,PD0A1exp_mit, '+', label=r'$Pr(D_0|A=1)_{expmit}$')
plt.xlim(-0.1,2*math.pi+0.1); plt.ylim(-0.03,1.03); plt.legend(bbox_to_anchor=(1.4, 1.0),loc='upper right')
plt.xlabel(r'$\phi$'); plt.show()
VsimA0 = (np.max(PD0A0sim)-np.min(PD0A0sim))/(np.max(PD0A0sim)+np.min(PD0A0sim)); print('VsimA0 = ',VsimA0)
VsimA1 = (np.max(PD0A1sim)-np.min(PD0A1sim))/(np.max(PD0A1sim)+np.min(PD0A1sim)); print('VsimA1 = ',VsimA1)
VexpA0 = (np.max(PD0A0exp)-np.min(PD0A0exp))/(np.max(PD0A0exp)+np.min(PD0A0exp)); print('VexpA0 = ',VexpA0)
VexpA1 = (np.max(PD0A1exp)-np.min(PD0A1exp))/(np.max(PD0A1exp)+np.min(PD0A1exp)); print('VexpA1 = ',VexpA1)
VexpA0_mit = (np.max(PD0A0exp_mit)-np.min(PD0A0exp_mit))/(np.max(PD0A0exp_mit)+np.min(PD0A0exp_mit))
print('VexpA0_mit = ',VexpA0_mit)
VexpA1_mit = (np.max(PD0A1exp_mit)-np.min(PD0A1exp_mit))/(np.max(PD0A1exp_mit)+np.min(PD0A1exp_mit))
print('VexpA1_mit = ',VexpA1_mit)
import math; import numpy as np
al_max = math.pi/4; npt = 100; dalt = al_max/npt
alt = np.arange(0,al_max+dalt,dalt)
Vteo = np.sin(2*alt)
from matplotlib import pyplot as plt
plt.plot(alt,Vteo, label=r'$V_{teo}(A=0)$')
plt.xlim(-0.01,al_max+0.01); plt.ylim(-0.01,1.01)
plt.xlabel(r'$\alpha$'); plt.legend()
plt.show()
from qiskit import QuantumCircuit
def qc_Psi(al): # prepara o estado parcialmente emaranhado
qc = QuantumCircuit(2, name = r'$|\Psi\rangle$')
qc.u(2*al,0,0, 0)
qc.cx(0,1)
qc.z(0)
qc.x(1)
return qc
qcpsi = qc_Psi(0.1); qcpsi.draw('mpl')
# simulaΓ§Γ£o clΓ‘ssica
from qiskit import Aer, execute; simulator = Aer.get_backend('qasm_simulator'); nshots = 2**13
import math; import numpy as np
almax = math.pi/4; npa=2; dal = almax/npa; al = np.arange(0,almax+dal,dal)
phmax = 2*math.pi; npe=4; dph = phmax/npe; ph = np.arange(0,phmax+dph,dph); VA0sim = np.zeros(len(al))
for j in range(0,len(al)):
PD0A0sim = np.zeros(len(ph)); PA0sim = np.zeros(len(ph))
for k in range(0,len(ph)):
qc = QuantumCircuit(3,2)
qcpsi = qc_Psi(al[j]); qc.append(qcpsi, [0,1])
qcdfp = qc_dfp(); qc.append(qcdfp, [1,2]); qcpmo = qc_pmo(); qc.append(qcpmo, [1,2])
qce = qc_espelhos(); qc.append(qce, [2]); qc.p(ph[k], [2])
qcdf = qc_df(); qc.append(qcdf, [2]); qcpqo = qc_pqo(); qc.append(qcpqo, [0])
qc.measure([0,2],[0,1])
job = execute(qc, backend=simulator, shots=nshots); counts = job.result().get_counts()
if '00' in counts:
PA0sim[k] = counts['00']/nshots
if '01' in counts:
PA0sim[k] += counts['01']/nshots
if PA0sim[k] != 0:
if '00' in counts:
PD0A0sim[k] = (counts['00']/nshots)/PA0sim[k]
VA0sim[j] = (np.max(PD0A0sim)-np.min(PD0A0sim))/(np.max(PD0A0sim)+np.min(PD0A0sim))
VA0sim
PD0A0sim
qc.draw('mpl')
import math; import numpy as np
al_max = math.pi/4; npt = 100; dalt = al_max/npt; alt = np.arange(0,al_max+dalt,dalt)
Vteo = np.sin(2*alt)
from matplotlib import pyplot as plt
plt.plot(alt,Vteo, label=r'$V_{teo}(A=0)$')
plt.plot(al,VA0sim, 'o', label=r'$V_{sim}(A=0)$')
plt.xlim(-0.01,al_max+0.01); plt.ylim(-0.01,1.02); plt.xlabel(r'$\alpha$'); plt.legend()
plt.show()
# Experimento (simulaΓ§Γ£o quΓ’ntica)
from qiskit import execute; import math; import numpy as np
almax = math.pi/4; npa = 2; dal = almax/npa; al = np.arange(0,almax+dal,dal)
phmax = 2*math.pi; npe=4; dph = phmax/npe; ph = np.arange(0,phmax+dph,dph)
job_ids=[]
for j in range(0,len(al)):
for k in range(0,len(ph)):
qc = QuantumCircuit(3,2); qcpsi = qc_Psi(al[j]); qc.append(qcpsi, [0,1])
qcdfp = qc_dfp(); qc.append(qcdfp, [1,2]); qcpmo = qc_pmo(); qc.append(qcpmo, [1,2])
qce = qc_espelhos(); qc.append(qce, [2]); qc.p(ph[k], [2])
qcdf = qc_df(); qc.append(qcdf, [2]); qcpqo = qc_pqo(); qc.append(qcpqo, [0]); qc.measure([0,2],[0,1])
job = execute(qc, backend=device, shots=nshots); jobid = job.job_id(); job_ids.append(jobid); print(jobid)
f = open("jobs_ids_apagador_parcial.txt", "w"); f.write(str(job_ids)); f.close()
f = open("jobs_ids_apagador_parcial.txt","r")
list_ids_apagador_parcial = f.read().replace("'","").replace(" ","").replace("[","").replace("]","").split(",")
f.close()
import math; import numpy as np
almax = math.pi/4; npa=2; dal = almax/npa; al = np.arange(0,almax+dal,dal)
phmax = 2*math.pi; npe=4; dph = phmax/npe; ph = np.arange(0,phmax+dph,dph); VA0exp = np.zeros(len(al))
for j in range(0,len(al)):
PD0A0exp = np.zeros(len(ph)); PA0exp = np.zeros(len(ph))
for k in range(0,len(ph)):
job = device.retrieve_job(list_ids_apagador_parcial[(npe+1)*j+k])
counts = job.result().get_counts()
if '00' in counts:
PA0exp[k] = counts['00']/nshots
if '01' in counts:
PA0exp[k] += counts['01']/nshots
if PA0exp[k] != 0:
if '00' in counts:
PD0A0exp[k] = (counts['00']/nshots)/PA0exp[k]
VA0exp[j] = (np.max(PD0A0exp)-np.min(PD0A0exp))/(np.max(PD0A0exp)+np.min(PD0A0exp))
VA0exp
import math; import numpy as np
al_max = math.pi/4; npt = 100; dalt = al_max/npt; alt = np.arange(0,al_max+dalt,dalt); Vteo = np.sin(2*alt)
from matplotlib import pyplot as plt
plt.plot(alt,Vteo, label=r'$V_{teo}(A=0)$')
plt.plot(al,VA0sim, 'o', label=r'$V_{sim}(A=0)$')
plt.plot(al,VA0exp, '^', label=r'$V_{exp}(A=0)$')
plt.xlim(-0.01,al_max+0.01); plt.ylim(-0.01,1.02); plt.xlabel(r'$\alpha$'); plt.legend()
plt.show()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import numpy as np
import matplotlib.pyplot as plt
from IPython.display import display, clear_output
from qiskit.primitives import Estimator
from qiskit.algorithms.minimum_eigensolvers import VQE
from qiskit.algorithms.observables_evaluator import estimate_observables
from qiskit.algorithms.optimizers import COBYLA, SLSQP
from qiskit.circuit import QuantumCircuit, Parameter
from qiskit.circuit.library import TwoLocal
from qiskit.quantum_info import Pauli, SparsePauliOp
from qiskit.utils import algorithm_globals
from qiskit_nature.second_q.operators import FermionicOp
from qiskit_nature.second_q.mappers import JordanWignerMapper
def kronecker_delta_function(n: int, m: int) -> int:
"""An implementation of the Kronecker delta function.
Args:
n (int): The first integer argument.
m (int): The second integer argument.
Returns:
Returns 1 if n = m, else returns 0.
"""
return int(n == m)
def create_deuteron_hamiltonian(
N: int, hbar_omega: float = 7.0, V_0: float = -5.68658111
) -> SparsePauliOp:
"""Creates a version of the Deuteron Hamiltonian as a qubit operator.
Args:
N (int): An integer number that represents the dimension of the
basis.
hbar_omega (float, optional): The value of the product of hbar and omega. Defaults to 7.0.
V_0 (float, optional): The value of the potential energy. Defaults to -5.68658111.
Returns:
SparsePauliOp: The qubit-space Hamiltonian that represents the Deuteron.
"""
hamiltonian_terms = {}
for m in range(N):
for n in range(N):
label = "+_{} -_{}".format(str(n), str(m))
coefficient_kinect = (hbar_omega / 2) * (
(2 * n + 3 / 2) * kronecker_delta_function(n, m)
- np.sqrt(n * (n + (1 / 2))) * kronecker_delta_function(n, m + 1)
- np.sqrt((n + 1) * (n + (3 / 2)) * kronecker_delta_function(n, m - 1))
)
hamiltonian_terms[label] = coefficient_kinect
coefficient_potential = (
V_0 * kronecker_delta_function(n, 0) * kronecker_delta_function(n, m)
)
hamiltonian_terms[label] += coefficient_potential
hamiltonian = FermionicOp(hamiltonian_terms, num_spin_orbitals=N)
mapper = JordanWignerMapper()
qubit_hamiltonian = mapper.map(hamiltonian)
if not isinstance(qubit_hamiltonian, SparsePauliOp):
qubit_hamiltonian = qubit_hamiltonian.primitive
return qubit_hamiltonian
deuteron_hamiltonians = [create_deuteron_hamiltonian(i) for i in range(1, 5)]
for i, hamiltonian in enumerate(deuteron_hamiltonians):
print("Deuteron Hamiltonian: H_{}".format(i + 1))
print(hamiltonian)
print("\n")
theta = Parameter(r"$\theta$")
eta = Parameter(r"$\eta$")
wavefunction = QuantumCircuit(1)
wavefunction.ry(theta, 0)
wavefunction.draw("mpl")
wavefunction2 = QuantumCircuit(2)
wavefunction2.x(0)
wavefunction2.ry(theta, 1)
wavefunction2.cx(1, 0)
wavefunction2.draw("mpl")
wavefunction3 = QuantumCircuit(3)
wavefunction3.x(0)
wavefunction3.ry(eta, 1)
wavefunction3.ry(theta, 2)
wavefunction3.cx(2, 0)
wavefunction3.cx(0, 1)
wavefunction3.ry(-eta, 1)
wavefunction3.cx(0, 1)
wavefunction3.cx(1, 0)
wavefunction3.draw("mpl")
ansatz = [wavefunction, wavefunction2, wavefunction3]
reference_values = []
print("Exact binding energies calculated through numpy.linalg.eigh \n")
for i, hamiltonian in enumerate(deuteron_hamiltonians):
eigenvalues, eigenstates = np.linalg.eigh(hamiltonian.to_matrix())
reference_values.append(eigenvalues[0])
print("Exact binding energy for H_{}: {}".format(i + 1, eigenvalues[0]))
print(
"Results using Estimator for H_1, H_2 and H_3 with the ansatz given in the reference paper \n"
)
for i in range(3):
seed = 42
algorithm_globals.random_seed = seed
vqe = VQE(Estimator(), ansatz=ansatz[i], optimizer=SLSQP())
vqe_result = vqe.compute_minimum_eigenvalue(deuteron_hamiltonians[i])
binding_energy = vqe_result.optimal_value
print("Binding energy for H_{}: {} MeV".format(i + 1, binding_energy))
def callback(eval_count, parameters, mean, std):
# Overwrites the same line when printing
display("Evaluation: {}, Energy: {}, Std: {}".format(eval_count, mean, std))
clear_output(wait=True)
counts.append(eval_count)
values.append(mean)
params.append(parameters)
deviation.append(std)
plots = []
for i in range(3):
counts = []
values = []
params = []
deviation = []
seed = 42
algorithm_globals.random_seed = seed
vqe = VQE(Estimator(), ansatz=ansatz[i], optimizer=COBYLA(), callback=callback)
vqe_result = vqe.compute_minimum_eigenvalue(deuteron_hamiltonians[i])
plots.append([counts, values])
fig, ax = plt.subplots(nrows=3, ncols=1)
fig.set_size_inches((12, 12))
for i, plot in enumerate(plots):
ax[i].plot(plot[0], plot[1], "o-", label="COBYLA")
ax[i].axhline(
y=reference_values[i],
color="k",
linestyle="--",
label=f"Reference Value: {reference_values[i]}",
)
ax[i].legend()
ax[i].set_xlabel("Cost Function Evaluations", fontsize=15)
ax[i].set_ylabel(r"$\langle H_{} \rangle$ - Energy (MeV)".format(i + 1), fontsize=15)
plt.show()
twolocal_ansatzes = []
for i in range(1, 5):
ansatz = TwoLocal(
deuteron_hamiltonians[i - 1].num_qubits,
["rz", "ry"],
"cx",
entanglement="full",
reps=i,
initial_state=None,
)
twolocal_ansatzes.append(ansatz)
print("Results using Estimator for H_1, H_2, H_3 and H_4 with TwoLocal ansatz \n")
seed = 42
algorithm_globals.random_seed = seed
for i in range(4):
vqe = VQE(Estimator(), ansatz=twolocal_ansatzes[i], optimizer=SLSQP())
vqe_result = vqe.compute_minimum_eigenvalue(deuteron_hamiltonians[i])
binding_energy = vqe_result.optimal_value
print("Binding energy for H_{}:".format(i + 1), binding_energy, "MeV")
seed = 42
algorithm_globals.random_seed = seed
plots_tl = []
for i in range(4):
counts = []
values = []
params = []
deviation = []
vqe = VQE(
Estimator(),
ansatz=twolocal_ansatzes[i],
optimizer=SLSQP(),
callback=callback,
)
vqe_result = vqe.compute_minimum_eigenvalue(deuteron_hamiltonians[i])
plots_tl.append([counts, values])
fig, ax = plt.subplots(nrows=4, ncols=1)
fig.set_size_inches((15, 15))
for i, plot in enumerate(plots_tl):
ax[i].plot(plot[0], plot[1], "o-", label="COBYLA")
ax[i].axhline(
y=reference_values[i],
color="k",
linestyle="--",
label=f"Reference Value: {reference_values[i]}",
)
ax[i].legend()
ax[i].set_xlabel("Cost Function Evaluations", fontsize=15)
ax[i].set_ylabel(r"$\langle H_{} \rangle$ - Energy (MeV)".format(i + 1), fontsize=15)
plt.show()
def calculate_observables_exp_values(
quantum_circuit: QuantumCircuit, observables: list, angles: list
) -> list:
"""Calculate the expectation value of an observable given the quantum
circuit that represents the wavefunction and a list of parameters.
Args:
quantum_circuit (QuantumCircuit): A parameterized quantum circuit
that represents the wavefunction of the system.
observables (list): A list containing the observables that we want
to know the expectation values.
angles (list): A list with the values that will be used in the
'bind_parameters' method.
Returns:
list_exp_values (list): A list containing the expectation values
of the observables given as input.
"""
list_exp_values = []
for observable in observables:
exp_values = []
for angle in angles:
qc = quantum_circuit.bind_parameters({theta: angle})
result = estimate_observables(
Estimator(),
quantum_state=qc,
observables=[observable],
)
exp_values.append(result[0][0])
list_exp_values.append(exp_values)
return list_exp_values
angles = list(np.linspace(-np.pi, np.pi, 100))
observables = [
Pauli("IZ"),
Pauli("ZI"),
Pauli("XX"),
Pauli("YY"),
deuteron_hamiltonians[1],
]
h2_observables_exp_values = calculate_observables_exp_values(wavefunction2, observables, angles)
fig, ax = plt.subplots(nrows=2, ncols=1)
fig.set_size_inches((12, 12))
ax[0].plot(angles, h2_observables_exp_values[0], "o", label=r"$Z_0$")
ax[0].plot(angles, h2_observables_exp_values[1], "o", label=r"$Z_1$")
ax[0].plot(angles, h2_observables_exp_values[2], "o", label=r"$X_0X_1$")
ax[0].plot(angles, h2_observables_exp_values[3], "o", label=r"$Y_0Y_1$")
ax[0].axhline(
y=1,
color="k",
linestyle="--",
)
ax[0].axhline(y=-1, color="k", linestyle="--")
ax[0].legend()
ax[0].set_xlabel(r"Theta - $\theta$", fontsize=15)
ax[0].set_ylabel(r"$\langle O \rangle $ - Operator Expectation Value", fontsize=15)
ax[0].set_xticks(
[-np.pi, -np.pi / 2, 0, np.pi / 2, np.pi],
labels=[r"$-\pi$", r"$-\pi/2$", "0", r"$\pi/2$", r"$\pi$"],
)
ax[0].set_title(
r"Expectation value of the observables $Z_0$, $Z_1$, $X_0X_1$ and $Y_0Y_1$ when we vary $\theta$ in the ansatz.",
fontsize=15,
)
ax[1].plot(angles, h2_observables_exp_values[4], "o")
ax[1].axhline(
y=reference_values[1],
color="k",
linestyle="--",
label="Binding Energy: {} MeV".format(np.round(reference_values[1], 3)),
)
ax[1].legend()
ax[1].set_xlabel(r"Theta - $\theta$", fontsize=15)
ax[1].set_ylabel(r"$\langle H_2 \rangle $ - Energy (MeV)", fontsize=15)
ax[1].set_xticks(
[-np.pi, -np.pi / 2, 0, np.pi / 2, np.pi],
labels=[r"$-\pi$", r"$-\pi/2$", "0", r"$\pi/2$", r"$\pi$"],
)
ax[1].set_title(
r"Behavior of the expectation value of $H_2$ when we vary $\theta$ in the ansatz.", fontsize=15
)
plt.show()
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/swe-train/qiskit__qiskit
|
swe-train
|
# 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.
# pylint: disable=invalid-name
"""Tests for generator of timeline drawer."""
import qiskit
from qiskit.test import QiskitTestCase
from qiskit.visualization.timeline import generators, types, stylesheet
from qiskit.circuit import library, Delay
class TestGates(QiskitTestCase):
"""Tests for generator.gates."""
def setUp(self) -> None:
"""Setup."""
super().setUp()
self.qubit = list(qiskit.QuantumRegister(1))[0]
self.u1 = types.ScheduledGate(
t0=100, operand=library.U1Gate(0), duration=0, bits=[self.qubit], bit_position=0
)
self.u3 = types.ScheduledGate(
t0=100, operand=library.U3Gate(0, 0, 0), duration=20, bits=[self.qubit], bit_position=0
)
self.delay = types.ScheduledGate(
t0=100, operand=Delay(20), duration=20, bits=[self.qubit], bit_position=0
)
style = stylesheet.QiskitTimelineStyle()
self.formatter = style.formatter
def test_gen_sched_gate_with_finite_duration(self):
"""Test test_gen_sched_gate generator with finite duration gate."""
drawing_obj = generators.gen_sched_gate(self.u3, self.formatter)[0]
self.assertEqual(drawing_obj.data_type, str(types.BoxType.SCHED_GATE.value))
self.assertListEqual(list(drawing_obj.xvals), [100, 120])
self.assertListEqual(
list(drawing_obj.yvals),
[-0.5 * self.formatter["box_height.gate"], 0.5 * self.formatter["box_height.gate"]],
)
self.assertListEqual(drawing_obj.bits, [self.qubit])
ref_meta = {
"name": "u3",
"label": "n/a",
"bits": str(self.qubit.register.name),
"t0": 100,
"duration": 20,
"unitary": "[[1.+0.j 0.-0.j]\n [0.+0.j 1.+0.j]]",
"parameters": "0, 0, 0",
}
self.assertDictEqual(ref_meta, drawing_obj.meta)
ref_styles = {
"zorder": self.formatter["layer.gate"],
"facecolor": self.formatter["color.gates"]["u3"],
"alpha": self.formatter["alpha.gate"],
"linewidth": self.formatter["line_width.gate"],
}
self.assertDictEqual(ref_styles, drawing_obj.styles)
def test_gen_sched_gate_with_zero_duration(self):
"""Test test_gen_sched_gate generator with zero duration gate."""
drawing_obj = generators.gen_sched_gate(self.u1, self.formatter)[0]
self.assertEqual(drawing_obj.data_type, str(types.SymbolType.FRAME.value))
self.assertListEqual(list(drawing_obj.xvals), [100])
self.assertListEqual(list(drawing_obj.yvals), [0])
self.assertListEqual(drawing_obj.bits, [self.qubit])
self.assertEqual(drawing_obj.text, self.formatter["unicode_symbol.frame_change"])
self.assertEqual(drawing_obj.latex, self.formatter["latex_symbol.frame_change"])
ref_styles = {
"zorder": self.formatter["layer.frame_change"],
"color": self.formatter["color.gates"]["u1"],
"size": self.formatter["text_size.frame_change"],
"va": "center",
"ha": "center",
}
self.assertDictEqual(ref_styles, drawing_obj.styles)
def test_gen_sched_gate_with_delay(self):
"""Test test_gen_sched_gate generator with delay."""
drawing_obj = generators.gen_sched_gate(self.delay, self.formatter)[0]
self.assertEqual(drawing_obj.data_type, str(types.BoxType.DELAY.value))
def test_gen_full_gate_name_with_finite_duration(self):
"""Test gen_full_gate_name generator with finite duration gate."""
drawing_obj = generators.gen_full_gate_name(self.u3, self.formatter)[0]
self.assertEqual(drawing_obj.data_type, str(types.LabelType.GATE_NAME.value))
self.assertListEqual(list(drawing_obj.xvals), [110.0])
self.assertListEqual(list(drawing_obj.yvals), [0.0])
self.assertListEqual(drawing_obj.bits, [self.qubit])
self.assertEqual(drawing_obj.text, "u3(0.00, 0.00, 0.00)[20]")
ref_latex = "{name}(0.00, 0.00, 0.00)[20]".format(
name=self.formatter["latex_symbol.gates"]["u3"]
)
self.assertEqual(drawing_obj.latex, ref_latex)
ref_styles = {
"zorder": self.formatter["layer.gate_name"],
"color": self.formatter["color.gate_name"],
"size": self.formatter["text_size.gate_name"],
"va": "center",
"ha": "center",
}
self.assertDictEqual(ref_styles, drawing_obj.styles)
def test_gen_full_gate_name_with_zero_duration(self):
"""Test gen_full_gate_name generator with zero duration gate."""
drawing_obj = generators.gen_full_gate_name(self.u1, self.formatter)[0]
self.assertEqual(drawing_obj.data_type, str(types.LabelType.GATE_NAME.value))
self.assertListEqual(list(drawing_obj.xvals), [100.0])
self.assertListEqual(list(drawing_obj.yvals), [self.formatter["label_offset.frame_change"]])
self.assertListEqual(drawing_obj.bits, [self.qubit])
self.assertEqual(drawing_obj.text, "u1(0.00)")
ref_latex = "{name}(0.00)".format(name=self.formatter["latex_symbol.gates"]["u1"])
self.assertEqual(drawing_obj.latex, ref_latex)
ref_styles = {
"zorder": self.formatter["layer.gate_name"],
"color": self.formatter["color.gate_name"],
"size": self.formatter["text_size.gate_name"],
"va": "bottom",
"ha": "center",
}
self.assertDictEqual(ref_styles, drawing_obj.styles)
def test_gen_full_gate_name_with_delay(self):
"""Test gen_full_gate_name generator with delay."""
drawing_obj = generators.gen_full_gate_name(self.delay, self.formatter)[0]
self.assertEqual(drawing_obj.data_type, str(types.LabelType.DELAY.value))
def test_gen_short_gate_name_with_finite_duration(self):
"""Test gen_short_gate_name generator with finite duration gate."""
drawing_obj = generators.gen_short_gate_name(self.u3, self.formatter)[0]
self.assertEqual(drawing_obj.data_type, str(types.LabelType.GATE_NAME.value))
self.assertListEqual(list(drawing_obj.xvals), [110.0])
self.assertListEqual(list(drawing_obj.yvals), [0.0])
self.assertListEqual(drawing_obj.bits, [self.qubit])
self.assertEqual(drawing_obj.text, "u3")
ref_latex = "{name}".format(name=self.formatter["latex_symbol.gates"]["u3"])
self.assertEqual(drawing_obj.latex, ref_latex)
ref_styles = {
"zorder": self.formatter["layer.gate_name"],
"color": self.formatter["color.gate_name"],
"size": self.formatter["text_size.gate_name"],
"va": "center",
"ha": "center",
}
self.assertDictEqual(ref_styles, drawing_obj.styles)
def test_gen_short_gate_name_with_zero_duration(self):
"""Test gen_short_gate_name generator with zero duration gate."""
drawing_obj = generators.gen_short_gate_name(self.u1, self.formatter)[0]
self.assertEqual(drawing_obj.data_type, str(types.LabelType.GATE_NAME.value))
self.assertListEqual(list(drawing_obj.xvals), [100.0])
self.assertListEqual(list(drawing_obj.yvals), [self.formatter["label_offset.frame_change"]])
self.assertListEqual(drawing_obj.bits, [self.qubit])
self.assertEqual(drawing_obj.text, "u1")
ref_latex = "{name}".format(name=self.formatter["latex_symbol.gates"]["u1"])
self.assertEqual(drawing_obj.latex, ref_latex)
ref_styles = {
"zorder": self.formatter["layer.gate_name"],
"color": self.formatter["color.gate_name"],
"size": self.formatter["text_size.gate_name"],
"va": "bottom",
"ha": "center",
}
self.assertDictEqual(ref_styles, drawing_obj.styles)
def test_gen_short_gate_name_with_delay(self):
"""Test gen_short_gate_name generator with delay."""
drawing_obj = generators.gen_short_gate_name(self.delay, self.formatter)[0]
self.assertEqual(drawing_obj.data_type, str(types.LabelType.DELAY.value))
class TestTimeslot(QiskitTestCase):
"""Tests for generator.bits."""
def setUp(self) -> None:
"""Setup."""
super().setUp()
self.qubit = list(qiskit.QuantumRegister(1))[0]
style = stylesheet.QiskitTimelineStyle()
self.formatter = style.formatter
def test_gen_timeslot(self):
"""Test gen_timeslot generator."""
drawing_obj = generators.gen_timeslot(self.qubit, self.formatter)[0]
self.assertEqual(drawing_obj.data_type, str(types.BoxType.TIMELINE.value))
self.assertListEqual(
list(drawing_obj.xvals), [types.AbstractCoordinate.LEFT, types.AbstractCoordinate.RIGHT]
)
self.assertListEqual(
list(drawing_obj.yvals),
[
-0.5 * self.formatter["box_height.timeslot"],
0.5 * self.formatter["box_height.timeslot"],
],
)
self.assertListEqual(drawing_obj.bits, [self.qubit])
ref_styles = {
"zorder": self.formatter["layer.timeslot"],
"alpha": self.formatter["alpha.timeslot"],
"linewidth": self.formatter["line_width.timeslot"],
"facecolor": self.formatter["color.timeslot"],
}
self.assertDictEqual(ref_styles, drawing_obj.styles)
def test_gen_bit_name(self):
"""Test gen_bit_name generator."""
drawing_obj = generators.gen_bit_name(self.qubit, self.formatter)[0]
self.assertEqual(drawing_obj.data_type, str(types.LabelType.BIT_NAME.value))
self.assertListEqual(list(drawing_obj.xvals), [types.AbstractCoordinate.LEFT])
self.assertListEqual(list(drawing_obj.yvals), [0])
self.assertListEqual(drawing_obj.bits, [self.qubit])
self.assertEqual(drawing_obj.text, str(self.qubit.register.name))
ref_latex = r"{{\rm {register}}}_{{{index}}}".format(
register=self.qubit.register.prefix, index=self.qubit.index
)
self.assertEqual(drawing_obj.latex, ref_latex)
ref_styles = {
"zorder": self.formatter["layer.bit_name"],
"color": self.formatter["color.bit_name"],
"size": self.formatter["text_size.bit_name"],
"va": "center",
"ha": "right",
}
self.assertDictEqual(ref_styles, drawing_obj.styles)
class TestBarrier(QiskitTestCase):
"""Tests for generator.barriers."""
def setUp(self) -> None:
"""Setup."""
super().setUp()
self.qubits = list(qiskit.QuantumRegister(3))
self.barrier = types.Barrier(t0=100, bits=self.qubits, bit_position=1)
style = stylesheet.QiskitTimelineStyle()
self.formatter = style.formatter
def test_gen_barrier(self):
"""Test gen_barrier generator."""
drawing_obj = generators.gen_barrier(self.barrier, self.formatter)[0]
self.assertEqual(drawing_obj.data_type, str(types.LineType.BARRIER.value))
self.assertListEqual(list(drawing_obj.xvals), [100, 100])
self.assertListEqual(list(drawing_obj.yvals), [-0.5, 0.5])
self.assertListEqual(drawing_obj.bits, [self.qubits[1]])
ref_styles = {
"alpha": self.formatter["alpha.barrier"],
"zorder": self.formatter["layer.barrier"],
"linewidth": self.formatter["line_width.barrier"],
"linestyle": self.formatter["line_style.barrier"],
"color": self.formatter["color.barrier"],
}
self.assertDictEqual(ref_styles, drawing_obj.styles)
class TestGateLink(QiskitTestCase):
"""Tests for generator.gate_links."""
def setUp(self) -> None:
"""Setup."""
super().setUp()
self.qubits = list(qiskit.QuantumRegister(2))
self.gate_link = types.GateLink(t0=100, opname="cx", bits=self.qubits)
style = stylesheet.QiskitTimelineStyle()
self.formatter = style.formatter
def gen_bit_link(self):
"""Test gen_bit_link generator."""
drawing_obj = generators.gen_gate_link(self.gate_link, self.formatter)[0]
self.assertEqual(drawing_obj.data_type, str(types.LineType.GATE_LINK.value))
self.assertListEqual(list(drawing_obj.xvals), [100])
self.assertListEqual(list(drawing_obj.yvals), [0])
self.assertListEqual(drawing_obj.bits, self.qubits)
ref_styles = {
"alpha": self.formatter["alpha.bit_link"],
"zorder": self.formatter["layer.bit_link"],
"linewidth": self.formatter["line_width.bit_link"],
"linestyle": self.formatter["line_style.bit_link"],
"color": self.formatter["color.gates"]["cx"],
}
self.assertDictEqual(ref_styles, drawing_obj.styles)
|
https://github.com/scaleway/qiskit-scaleway
|
scaleway
|
# Copyright 2024 Scaleway
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from qiskit.visualization import plot_histogram
from qiskit import QuantumCircuit
from qiskit_scaleway import ScalewayProvider
provider = ScalewayProvider(
project_id="<your-scaleway-project-id>",
secret_key="<your-scaleway-secret-key>",
)
# Scaleway provides Qsim backend, whichs is compatible with Cirq SDK
backend = provider.get_backend("qsim_simulation_l40s")
# Define a quantum circuit that produces a 4-qubit GHZ state.
qc = QuantumCircuit(4)
qc.h(0)
qc.cx(0, 1)
qc.cx(0, 2)
qc.cx(0, 3)
qc.measure_all()
# Create a QPU's session with Qsim installed for a limited duration
session_id = backend.start_session(
deduplication_id="my-qsim-session-workshop", max_duration="2h"
)
# Create and send a job to the target session
qsim_job = backend.run(qc, shots=1000, session_id=session_id)
# Wait and get the Qiskit result
qiskit_result = qsim_job.result()
# Display the result
plot_histogram(qiskit_result.get_counts())
# Revoke manually the QPU's session if needed
# If not done, will be revoked automatically after 2 hours
backend.stop_session(session_id)
|
https://github.com/abbarreto/qiskit3
|
abbarreto
|
%run init.ipynb
c00,c01,c10,c11 = symbols('c_{00} c_{01} c_{10} c_{11}')
psiAB = Matrix([[c00],[c01],[c10],[c11]]); psiAB
rhoAB = psiAB*conjugate(psiAB.T); rhoAB
rhoA = ptraceB(2,2,rhoAB); rhoB = ptraceA(2,2,rhoAB)
rhoA, rhoB
pauli(3)*pauli(1)*pauli(3), pauli(3)*pauli(2)*pauli(3), comm(pauli(3),pauli(1)), comm(pauli(3),pauli(2))
%run init.ipynb
def pTraceL_num(dl, dr, rhoLR):
rhoR = np.zeros((dr, dr), dtype=complex)
for j in range(0, dr):
for k in range(j, dr):
for l in range(0, dl):
rhoR[j,k] += rhoLR[l*dr+j,l*dr+k]
if j != k:
rhoR[k,j] = np.conj(rhoR[j,k])
return rhoR
def pTraceR_num(dl, dr, rhoLR):
rhoL = np.zeros((dl, dl), dtype=complex)
for j in range(0, dl):
for k in range(j, dl):
for l in range(0, dr):
rhoL[j,k] += rhoLR[j*dr+l,k*dr+l]
if j != k:
rhoL[k,j] = np.conj(rhoL[j,k])
return rhoL
def coh_l1(rho):
d = rho.shape[0]; C = 0
for j in range(0,d-1):
for k in range(j+1,d):
C += np.abs(rho[j,k])
return 2*C
from numpy import linalg as LA
def Econc_(rho):
s2 = np.array([[0,-1j],[1j,0]])
R = rho@np.kron(s2,s2)@np.matrix.conjugate(rho)@np.kron(s2,s2)
w, v = LA.eig(R)
evm = max(abs(w[0]), abs(w[1]), abs(w[2]), abs(w[3]))
Ec = 2*math.sqrt(abs(evm)) - math.sqrt(abs(w[0])) - math.sqrt(abs(w[1]))\
- math.sqrt(abs(w[2])) - math.sqrt(abs(w[3]))
if Ec < 0.0:
Ec = 0.0
return Ec
import scipy.linalg.lapack as lapak
def Econc(rho):
s2 = np.array([[0,-1j],[1j,0]])
R = rho@np.kron(s2,s2)@np.matrix.conjugate(rho)@np.kron(s2,s2)
ev = lapak.zheevd(R)
evm = max(abs(ev[0][0]), abs(ev[0][1]), abs(ev[0][2]), abs(ev[0][3]))
Ec = 2*math.sqrt(abs(evm)) - math.sqrt(abs(ev[0][0])) - math.sqrt(abs(ev[0][1]))\
- math.sqrt(abs(ev[0][2])) - math.sqrt(abs(ev[0][3]))
if Ec < 0.0:
Ec = 0.0
return Ec
def concurrence_psi(rho):
rho_r = pTraceL_num(2,2,rho)
return math.sqrt(2*abs(1-np.matrix.trace(rho_r@rho_r)))
def predict_jb(rho):
return abs(rho[0,0]-rho[1,1])
import qiskit
from qiskit import *
nshots = 8192
IBMQ.load_account()
#provider= qiskit.IBMQ.get_provider(hub='ibm-q-research-2',group='federal-uni-sant-1',project='main')
provider = qiskit.IBMQ.get_provider(hub='ibm-q', group='open', project='main')
device = provider.get_backend('ibmq_manila')
simulator = Aer.get_backend('qasm_simulator')
from qiskit.tools.monitor import job_monitor
from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter
from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter
q_exp = np.arange(0,1.1,0.1); N = len(q_exp)
th_xi = np.zeros(N); th_xi = 2*np.arccos(np.sqrt(1-q_exp))
th_eta = np.zeros(N); th_eta = 2*np.arccos(np.sqrt(q_exp))
E_sim_10 = np.zeros(N); C_sim_0 = np.zeros(N); P_sim_0 = np.zeros(N)
jobs_ids = []
for j in range(0,N):
qr = QuantumRegister(5); qc = QuantumCircuit(qr)
# prepara xi
qc.u(th_xi[j],0,0,qr[1])
qc.cx(qr[1],qr[2])
qc.h([qr[1],qr[2]])
# prepara eta
qc.u(th_eta[j],0,0,qr[3])
qc.cx(qr[3],qr[4])
qc.h([qr[3],qr[4]])
# tomografia
qstc = state_tomography_circuits(qc, [qr[1],qr[2]])
job_sim = qiskit.execute(qstc, backend = simulator, shots=nshots)
qstf_sim = StateTomographyFitter(job_sim.result(), qstc)
rho_10_sim = qstf_sim.fit(method='lstsq')
E_sim_10[j] = concurrence_psi(rho_10_sim)
rho_0_sim = pTraceL_num(2, 2, rho_10_sim)
C_sim_0[j] = coh_l1(rho_0_sim)
P_sim_0[j] = predict_jb(rho_0_sim)
qc.draw(output='mpl')
q_exp = np.arange(0,1.1,0.1); N = len(q_exp)
th_xi = np.zeros(N); th_xi = 2*np.arccos(np.sqrt(1-q_exp))
th_eta = np.zeros(N); th_eta = 2*np.arccos(np.sqrt(q_exp))
jobs_ids = []
for j in range(0,N):
qr = QuantumRegister(5); qc = QuantumCircuit(qr)
# prepara xi
qc.u(th_xi[j],0,0,qr[1])
qc.cx(qr[1],qr[2])
qc.h([qr[1],qr[2]])
# prepara eta
qc.u(th_eta[j],0,0,qr[3])
qc.cx(qr[3],qr[4])
qc.h([qr[3],qr[4]])
# tomografia
qstc = state_tomography_circuits(qc, [qr[1],qr[2]])
job_exp = qiskit.execute(qstc, backend = device, shots=nshots)
jobs_ids.append(job_exp.job_id())
print(job_exp.job_id())
job_monitor(job_exp)
print(jobs_ids)
f = open("jobs_ids_ES_pre_bbm.txt", "w")
f.write(str(jobs_ids))
f.close()
f = open("jobs_ids_ES_pre_bbm.txt","r")
#jobs_ids_list = f.read()
list_ids = f.read().replace("'","").replace(" ","").replace("[","").replace("]","").split(",")
f.close()
list_ids[0]
print(list_ids)
print(jobs_ids_list)
len_ids = len('6368049443e1f0708afdaf73')
print(len_ids)
list_ids = []
for j in range(0,N):
s = 0
if j > 0:
s = 2
print(jobs_ids_list[(j*(len_ids+2+s)+2):(j+1)*(len_ids+2)+j*s])
list_ids.append(jobs_ids_list[(j*(len_ids+2+s)+2):(j+1)*(len_ids+2)+j*s])
list_ids[0]
q_exp = np.arange(0,1.1,0.1); N = len(q_exp)
E_exp_10 = np.zeros(N); C_exp_0 = np.zeros(N); P_exp_0 = np.zeros(N)
for j in range(0,N):
job = device.retrieve_job(list_ids[j])
qstf_exp = StateTomographyFitter(job.result(), qstc)
rho_10_exp = qstf_exp.fit(method='lstsq');
E_exp_10[j] = Econc_(rho_10_exp)
print(E_exp_10[j])
rho_0_exp = pTraceL_num(2, 2, rho_10_exp)
C_exp_0[j] = coh_l1(rho_0_exp)
P_exp[j] = predict_jb(rho_0_exp)
import matplotlib
matplotlib.rcParams.update({'font.size':11}); plt.figure(figsize = (7,5), dpi = 100)
q = np.arange(0,1.01,0.01)
Ei2 = 4*q*(1-q)
Ci2 = (2*q-1)**2
Pi2 = np.zeros(len(q))
Pm = 1-2*q*(1-q)
plt.plot(q, Ei2, '-', label=r'$E_{conc}(\xi_{AC})^2$')
plt.plot(q, Ci2, '--', label=r'$C_{l_1}(\xi_C)^2$')
plt.plot(q, Pi2, '-.', label=r'$P(\xi_C)^2$')
plt.plot(q, Ei2+Ci2, ':', label=r'$E_{conc}(\xi_{AC})^{2}+C_{l_{1}}(\xi_{C})^{2}+P(\xi_C)^2$')
plt.plot(q_exp, E_sim_10**2, 'X', label=r'$E_{conc}(\xi_{AC})^2_{sim}$')
plt.plot(q_exp, C_sim_0**2, 'h', label=r'$C_{l_1}(\xi_C)^2_{sim}$')
plt.plot(q_exp, P_sim_0**2, '>', label=r'$P(\xi_C)^2_{sim}$')
plt.plot(q_exp, E_sim_10**2+C_sim_0**2+P_sim_0**2, '*', label=r'$E_{conc}(\xi_{AC})^{2}_{sim}+C_{l_{1}}(\xi_{C})^{2}_{sim}+P(\xi_C)^2_{sim}$')
plt.plot(q_exp, E_exp_10**2, 's', label=r'$E_{conc}(\xi_{AC})^2_{exp}$')
plt.plot(q_exp, C_exp_0**2, 'o', label=r'$C_{l_1}(\xi_C)^2_{exp}$')
plt.plot(q_exp, P_exp_0**2, 'v', label=r'$P(\xi_C)^2_{exp}$')
plt.plot(q_exp, E_exp_10**2+C_exp_0**2+P_exp_0**2, 'd', label=r'$E_{conc}(\xi_{AC})^{2}_{exp}+C_{l_{1}}(\xi_{C})^{2}_{exp}+P(\xi_C)^2_{exp}$')
plt.legend(bbox_to_anchor=(1.75, 1.0), loc='upper right')
plt.xlabel(r'$q$')
plt.show()
# error mitigation
qr = QuantumRegister(5); qubit_list = [1,2]
meas_calibs, state_labels = complete_meas_cal(qubit_list = qubit_list, qr = qr)
job = qiskit.execute(meas_calibs, backend = device, shots = nshots)
print(job.job_id())
job_monitor(job)
job = device.retrieve_job('636d895d04e46a1feb6227a9')
meas_fitter = CompleteMeasFitter(job.result(), state_labels)
q_exp = np.arange(0,1.1,0.1); N = len(q_exp)
for j in range(0,N):
job = device.retrieve_job(list_ids[j])
mitigated_results = meas_fitter.filter.apply(job.result())
qstf_exp = StateTomographyFitter(mitigated_results, qstc)
rho_10_exp = qstf_exp.fit(method='lstsq');
E_exp_10[j] = Econc_(rho_10_exp)
print(E_exp_10[j])
rho_0_exp = pTraceL_num(2, 2, rho_10_exp)
C_exp_0[j] = coh_l1(rho_0_exp)
P_exp[j] = predict_jb(rho_0_exp)
import matplotlib
matplotlib.rcParams.update({'font.size':11}); plt.figure(figsize = (7,5), dpi = 100)
q = np.arange(0,1.01,0.01)
Ei2 = 4*q*(1-q)
Ci2 = (2*q-1)**2
Pi2 = np.zeros(len(q))
Pm = 1-2*q*(1-q)
plt.plot(q, Ei2, '-', label=r'$E_{conc}(\xi_{AC})^2$')
plt.plot(q, Ci2, '--', label=r'$C_{l_1}(\xi_C)^2$')
plt.plot(q, Pi2, '-.', label=r'$P(\xi_C)^2$')
plt.plot(q, Ei2+Ci2, ':', label=r'$E_{conc}(\xi_{AC})^{2}+C_{l_{1}}(\xi_{C})^{2}+P(\xi_C)^2$')
plt.plot(q_exp, E_sim_10**2, 'X', label=r'$E_{conc}(\xi_{AC})^2_{sim}$')
plt.plot(q_exp, C_sim_0**2, 'h', label=r'$C_{l_1}(\xi_C)^2_{sim}$')
plt.plot(q_exp, P_sim_0**2, '>', label=r'$P(\xi_C)^2_{sim}$')
plt.plot(q_exp, E_sim_10**2+C_sim_0**2+P_sim_0**2, '*', label=r'$E_{conc}(\xi_{AC})^{2}_{sim}+C_{l_{1}}(\xi_{C})^{2}_{sim}+P(\xi_C)^2_{sim}$')
plt.plot(q_exp, E_exp_10**2, '^', label=r'$E_{conc}(\xi_{AC})^2_{exp}$')
plt.plot(q_exp, C_exp_0**2, 'o', label=r'$C_{l_1}(\xi_C)^2_{exp}$')
plt.plot(q_exp, P_exp_0**2, '.', label=r'$P(\xi_C)^2_{exp}$')
plt.plot(q_exp, E_exp_10**2+C_exp_0**2+P_exp_0**2, 'd', label=r'$E_{conc}(\xi_{AC})^{2}_{exp}+C_{l_{1}}(\xi_{C})^{2}_{exp}+P(\xi_C)^2_{exp}$')
plt.legend(bbox_to_anchor=(1.75, 1.0), loc='upper right')
plt.xlabel(r'$q$')
plt.savefig('fig_Eswap_pre_bbm.pdf')
plt.show()
qc.draw(output='mpl')
def pTrace_3_num(rho_abc, da, db, dc):
rho_ac = np.zeros(da*dc*da*dc, dtype=complex).reshape(da*dc,da*dc)
for j in range(0,da):
for l in range(0,dc):
cj = j*dc+l
ccj = j*db*dc+l
for m in range(0,da):
for o in range(0,dc):
ck = m*dc+o
cck = m*db*dc+o
for k in range(0,db):
rho_ac[cj,ck] = rho_ac[cj,ck] + rho_abc[ccj+k*dc,cck+k*dc]
return rho_ac
import numpy as np
import math
# projetores para a pos-seleΓ§Γ£o
I2 = np.array([[1,0],[0,1]], dtype=complex)
P00 = np.kron(np.kron(I2,np.array([[1,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]],dtype=complex)), I2) # PhiP
P01 = np.kron(np.kron(I2,np.array([[0,0,0,0],[0,1,0,0],[0,0,0,0],[0,0,0,0]],dtype=complex)), I2) # PsiP
P10 = np.kron(np.kron(I2,np.array([[0,0,0,0],[0,0,0,0],[0,0,1,0],[0,0,0,0]],dtype=complex)), I2) # PhiM
P11 = np.kron(np.kron(I2,np.array([[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,1]],dtype=complex)), I2) # PsiM
#P00+P01+P10+P11
q_exp = np.arange(0,1.1,0.1); N = len(q_exp)
q_exp[0] = 0.03; q_exp[N-1] = 1-q_exp[0]
th_xi = np.zeros(N); th_xi = 2*np.arccos(np.sqrt(1-q_exp))
th_eta = np.zeros(N); th_eta = 2*np.arccos(np.sqrt(q_exp))
E_phiP_04_sim = np.zeros(N); E_psiM_04_sim = np.zeros(N)
E_psiP_04_sim = np.zeros(N); E_phiM_04_sim = np.zeros(N)
C2_sim = np.zeros(N)
for j in range(0,N):
qr = QuantumRegister(5); qc = QuantumCircuit(qr)
# prepara xi
qc.u(th_xi[j],0,0,qr[0])
qc.cx(qr[0],qr[1])
qc.h([qr[0],qr[1]])
# prepara eta
qc.u(th_eta[j],0,0,qr[3])
qc.cx(qr[3],qr[4])
qc.h([qr[3],qr[4]])
# BBM
qc.cx(qr[1],qr[3])
qc.h(qr[1])
# circuito para tomografia
qstc = state_tomography_circuits(qc, [qr[4],qr[3],qr[1],qr[0]])
# Simulacao
job_sim = qiskit.execute(qstc, backend = simulator, shots=nshots)
qstf_sim = StateTomographyFitter(job_sim.result(), qstc)
rho_4310_sim = qstf_sim.fit(method='lstsq')
# pos-selecao
rho_PhiP = P00@rho_4310_sim@P00
pr_phiP = np.real(np.trace(rho_PhiP))
rho_PhiP = (1/pr_phiP)*rho_PhiP
rho_PsiP = P01@rho_4310_sim@P01
pr_psiP = np.real(np.trace(rho_PsiP))
rho_PsiP = (1/pr_psiP)*rho_PsiP
rho_PhiM = P10@rho_4310_sim@P10
pr_phiM = np.real(np.trace(rho_PhiM))
rho_PhiM = (1/pr_phiM)*rho_PhiM
rho_PsiM = P11@rho_4310_sim@P11
pr_psiM = np.real(np.trace(rho_PsiM))
rho_PsiM = (1/pr_psiM)*rho_PsiM
# estados reduzidos
rho_PhiP_04 = pTrace_3_num(rho_PhiP,2,4,2)
rho_PsiP_04 = pTrace_3_num(rho_PsiP,2,4,2)
rho_PhiM_04 = pTrace_3_num(rho_PhiM,2,4,2)
rho_PsiM_04 = pTrace_3_num(rho_PsiM,2,4,2)
# emaranhamentos e probabilidades
E_phiP_04_sim[j] = Econc_(rho_PhiP_04)
E_phiM_04_sim[j] = Econc_(rho_PhiM_04)
E_psiP_04_sim[j] = Econc_(rho_PsiP_04)
E_psiM_04_sim[j] = Econc_(rho_PsiM_04)
C2_sim[j] = 1 - 2*(pr_phiP+pr_psiP)
provider = qiskit.IBMQ.get_provider(hub='ibm-q', group='open', project='main')
device = provider.get_backend('ibmq_manila')
q_exp = np.arange(0,1.1,0.1); N = len(q_exp)
q_exp[0] = 0.03; q_exp[N-1] = 1-q_exp[0]
th_xi = np.zeros(N); th_xi = 2*np.arccos(np.sqrt(1-q_exp))
th_eta = np.zeros(N); th_eta = 2*np.arccos(np.sqrt(q_exp))
#jobs_ids2 = []
for j in range(N-1,N):
qr = QuantumRegister(5); qc = QuantumCircuit(qr)
# prepara xi
qc.u(th_xi[j],0,0,qr[1])
qc.cx(qr[1],qr[2])
qc.h([qr[1],qr[2]])
# prepara eta
qc.u(th_eta[j],0,0,qr[3])
qc.cx(qr[3],qr[4])
qc.h([qr[3],qr[4]])
# BBM
qc.cx(qr[2],qr[3])
qc.h(qr[2])
# circuito para tomografia
qstc = state_tomography_circuits(qc, [qr[4],qr[3],qr[2],qr[1]])
# Experimento
job_exp = qiskit.execute(qstc, backend = device, shots=nshots)
#jobs_ids2.append(job_exp.job_id())
print(job_exp.job_id())
job_monitor(job_exp)
jobs_ids2.append('636e2c8910cc1925ad755b77')
qc.draw(output='mpl')
f = open("jobs_ids_ES_post_bbm.txt", "w")
f.write(str(jobs_ids2))
f.close()
f = open("jobs_ids_ES_post_bbm.txt","r")
list_ids2 = f.read().replace("'","").replace(" ","").replace("[","").replace("]","").split(",")
f.close()
print(list_ids2)
q_exp = np.arange(0,1.1,0.1); N = len(q_exp)
q_exp[0] = 0.03; q_exp[N-1] = 1-q_exp[0]
E_phiP_04_exp = np.zeros(N); E_psiM_04_exp = np.zeros(N)
E_psiP_04_exp = np.zeros(N); E_phiM_04_exp = np.zeros(N)
C2_exp = np.zeros(N)
for j in range(0,N):
job = device.retrieve_job(list_ids2[j])
qstf_exp = StateTomographyFitter(job.result(), qstc)
rho_4310_exp = qstf_exp.fit(method='lstsq')
# pos-selecao
rho_PhiP = P00@rho_4310_exp@P00
pr_phiP = np.real(np.trace(rho_PhiP))
rho_PhiP = (1/pr_phiP)*rho_PhiP
rho_PsiP = P01@rho_4310_exp@P01
pr_psiP = np.real(np.trace(rho_PsiP))
rho_PsiP = (1/pr_psiP)*rho_PsiP
rho_PhiM = P10@rho_4310_exp@P10
pr_phiM = np.real(np.trace(rho_PhiM))
rho_PhiM = (1/pr_phiM)*rho_PhiM
rho_PsiM = P11@rho_4310_exp@P11
pr_psiM = np.real(np.trace(rho_PsiM))
rho_PsiM = (1/pr_psiM)*rho_PsiM
# estados reduzidos
rho_PhiP_04 = pTrace_3_num(rho_PhiP,2,4,2)
rho_PsiP_04 = pTrace_3_num(rho_PsiP,2,4,2)
rho_PhiM_04 = pTrace_3_num(rho_PhiM,2,4,2)
rho_PsiM_04 = pTrace_3_num(rho_PsiM,2,4,2)
# emaranhamentos e probabilidades
E_phiP_04_exp[j] = Econc_(rho_PhiP_04)
E_phiM_04_exp[j] = Econc_(rho_PhiM_04)
E_psiP_04_exp[j] = Econc_(rho_PsiP_04)
E_psiM_04_exp[j] = Econc_(rho_PsiM_04)
C2_exp[j] = 1 - 2*(pr_phiP+pr_psiP)
print(C2_exp[j])
import matplotlib
from matplotlib import pyplot as plt
matplotlib.rcParams.update({'font.size':11}); plt.figure(figsize = (6,4), dpi = 100)
q = np.arange(0,1.01,0.01)
Ep = np.ones(len(q)); Em = (2*q*(1-q))/(1-2*q+2*q**2); C2 = 1-4*q*(1-q)
plt.plot(q, Ep, '-', label=r'$E(\hat{\phi}_+)=E(\hat{\psi}_+)$')
plt.plot(q, Em, '--', label=r'$E(\hat{\phi}_-)=E(\hat{\psi}_-)$')
plt.plot(q, C2, '-.', label=r'$1-2(Pr(\hat{\phi}_+)+Pr(\hat{\psi}_+))$')
plt.plot(q_exp, E_phiP_04_sim, 'o', label=r'$E(\hat{\phi}_+)_{sim}$')
plt.plot(q_exp, E_phiM_04_sim, '*', label=r'$E(\hat{\phi}_-)_{sim}$')
#plt.plot(q_exp, E_psiP_04_sim, 'X', label=r'$E(\hat{\psi}_+)_{sim}$')
#plt.plot(q_exp, E_psiM_04_sim, '.', label=r'$E(\hat{\psi}_-)_{sim}$')
plt.plot(q_exp, C2_sim, 'X', label=r'$1-2(Pr(\hat{\phi}_+)_{sim}+Pr(\hat{\psi}_+)_{sim})$')
plt.plot(q_exp, E_phiP_04_exp, '<', label=r'$E(\hat{\phi}_+)_{exp}$')
plt.plot(q_exp, E_phiM_04_exp, '>', label=r'$E(\hat{\phi}_-)_{exp}$')
#plt.plot(q_exp, E_psiP_04_exp, '^', label=r'$E(\hat{\psi}_+)_{exp}$')
#plt.plot(q_exp, E_psiM_04_exp, '.', label=r'$E(\hat{\psi}_-)_{exp}$')
plt.plot(q_exp, C2_exp, '^', label=r'$1-2(Pr(\hat{\phi}_+)_{exp}+Pr(\hat{\psi}_+)_{exp})$')
plt.xlabel(r'$q$')
plt.legend(bbox_to_anchor=(1.8, 1.0), loc='upper right')
plt.show()
# error mitigation
qr = QuantumRegister(5)#; qc = QuantumCircuit(qr)
qubit_list = [1,2,3,4]
meas_calibs, state_labels = complete_meas_cal(qubit_list = qubit_list, qr = qr)
job = qiskit.execute(meas_calibs, backend = device, shots = nshots)
print(job.job_id())
job_monitor(job)
job = device.retrieve_job('636e3407fb0a57272187586a')
meas_fitter = CompleteMeasFitter(job.result(), state_labels)
q_exp = np.arange(0,1.1,0.1); N = len(q_exp)
q_exp[0] = 0.03; q_exp[N-1] = 1-q_exp[0]
E_phiP_04_exp = np.zeros(N); E_psiM_04_exp = np.zeros(N)
E_psiP_04_exp = np.zeros(N); E_phiM_04_exp = np.zeros(N)
C2_exp = np.zeros(N)
for j in range(0,N):
job = device.retrieve_job(list_ids2[j])
mitigated_results = meas_fitter.filter.apply(job.result()) # error mitigation
qstf_exp = StateTomographyFitter(mitigated_results, qstc) # error mitigation
rho_4310_exp = qstf_exp.fit(method='lstsq')
# pos-selecao
rho_PhiP = P00@rho_4310_exp@P00
pr_phiP = np.real(np.trace(rho_PhiP))
rho_PhiP = (1/pr_phiP)*rho_PhiP
rho_PsiP = P01@rho_4310_exp@P01
pr_psiP = np.real(np.trace(rho_PsiP))
rho_PsiP = (1/pr_psiP)*rho_PsiP
rho_PhiM = P10@rho_4310_exp@P10
pr_phiM = np.real(np.trace(rho_PhiM))
rho_PhiM = (1/pr_phiM)*rho_PhiM
rho_PsiM = P11@rho_4310_exp@P11
pr_psiM = np.real(np.trace(rho_PsiM))
rho_PsiM = (1/pr_psiM)*rho_PsiM
# estados reduzidos
rho_PhiP_04 = pTrace_3_num(rho_PhiP,2,4,2)
rho_PsiP_04 = pTrace_3_num(rho_PsiP,2,4,2)
rho_PhiM_04 = pTrace_3_num(rho_PhiM,2,4,2)
rho_PsiM_04 = pTrace_3_num(rho_PsiM,2,4,2)
# emaranhamentos e probabilidades
E_phiP_04_exp[j] = Econc_(rho_PhiP_04)
E_phiM_04_exp[j] = Econc_(rho_PhiM_04)
E_psiP_04_exp[j] = Econc_(rho_PsiP_04)
E_psiM_04_exp[j] = Econc_(rho_PsiM_04)
C2_exp[j] = 1 - 2*(pr_phiP+pr_psiP)
print(C2_exp[j])
import matplotlib
from matplotlib import pyplot as plt
matplotlib.rcParams.update({'font.size':11}); plt.figure(figsize = (6,4), dpi = 100)
q = np.arange(0,1.01,0.01)
Ep = np.ones(len(q)); Em = (2*q*(1-q))/(1-2*q+2*q**2); C2 = 1-4*q*(1-q)
plt.plot(q, Ep, '-', label=r'$E(\hat{\phi}_+)=E(\hat{\psi}_+)$')
plt.plot(q, Em, '--', label=r'$E(\hat{\phi}_-)=E(\hat{\psi}_-)$')
plt.plot(q, C2, '-.', label=r'$1-2(Pr(\hat{\phi}_+)+Pr(\hat{\psi}_+))$')
plt.plot(q_exp, E_phiP_04_sim, 'o', label=r'$E(\hat{\phi}_+)_{sim}$')
plt.plot(q_exp, E_phiM_04_sim, '*', label=r'$E(\hat{\phi}_-)_{sim}$')
#plt.plot(q_exp, E_psiP_04_sim, 'X', label=r'$E(\hat{\psi}_+)_{sim}$')
#plt.plot(q_exp, E_psiM_04_sim, '.', label=r'$E(\hat{\psi}_-)_{sim}$')
plt.plot(q_exp, C2_sim, 'X', label=r'$1-2(Pr(\hat{\phi}_+)_{sim}+Pr(\hat{\psi}_+)_{sim})$')
plt.plot(q_exp, E_phiP_04_exp, '<', label=r'$E(\hat{\phi}_+)_{exp}$')
plt.plot(q_exp, E_phiM_04_exp, '>', label=r'$E(\hat{\phi}_-)_{exp}$')
#plt.plot(q_exp, E_psiP_04_exp, '^', label=r'$E(\hat{\psi}_+)_{exp}$')
#plt.plot(q_exp, E_psiM_04_exp, '.', label=r'$E(\hat{\psi}_-)_{exp}$')
plt.plot(q_exp, C2_exp, '^', label=r'$1-2(Pr(\hat{\phi}_+)_{exp}+Pr(\hat{\psi}_+)_{exp})$')
plt.xlabel(r'$q$')
plt.legend(bbox_to_anchor=(1.8, 1.0), loc='upper right')
plt.savefig('fig_Eswap_post_bbm.pdf')
plt.show()
C = np.arange(0,1.1,0.1);
E_PhiP = (1-C**2)/(1+C**2)
E_PhiM = np.ones(len(C))
plt.plot(C, E_PhiP, '*'); plt.plot(C, E_PhiM, '.')
plt.show()
from qiskit import *
qr = QuantumRegister(4);
%run init.ipynb
p,q = symbols('p q')
ket_xi = Matrix([[sqrt(p)],[sqrt((1-p)/2)],[sqrt((1-p)/2)],[0]])
ket_eta = Matrix([[sqrt(q)],[sqrt((1-q)/2)],[sqrt((1-q)/2)],[0]])
ket_xi, ket_eta
rho_xi = ket_xi*ket_xi.T
rho_eta = ket_eta*ket_eta.T
rho_xi, rho_eta
def ptraceA(da, db, rho):
rhoB = zeros(db,db)
for j in range(0, db):
for k in range(0, db):
for l in range(0, da):
rhoB[j,k] += rho[l*db+j,l*db+k]
return rhoB
def ptraceB(da, db, rho):
rhoA = zeros(da,da)
for j in range(0, da):
for k in range(0, da):
for l in range(0, db):
rhoA[j,k] += rho[j*db+l,k*db+l]
return rhoA
rho_xi_A = ptraceB(2,2,rho_xi); rho_xi_C = ptraceA(2,2,rho_xi)
rho_xi_A, rho_xi_C
rho_eta_Cp = ptraceB(2,2,rho_eta); rho_eta_B = ptraceA(2,2,rho_eta)
rho_eta_Cp, rho_eta_B
c00,c01,c10,c11 = symbols('c_{00} c_{01} c_{10} c_{11}')
d00,d01,d10,d11 = symbols('d_{00} d_{01} d_{10} d_{11}')
def two_qb_basis():
zz = Matrix([[1],[0],[0],[0]])
zu = Matrix([[0],[1],[0],[0]])
uz = Matrix([[0],[0],[1],[0]])
uu = Matrix([[0],[0],[0],[1]])
return zz,zu,uz,uu
zz,zu,uz,uu = two_qb_basis(); zz,zu,uz,uu
def psi_p(c00,c01,c10,c11,d00,d01,d10,d11):
zz,zu,uz,uu = two_qb_basis()
psi = (c00*d00+c01*d10)*zz + (c00*d01+c01*d11)*zu + (c10*d00+c11*d10)*uz + (c10*d01+c11*d11)*uu
return psi/sqrt(2)
def psi_m(c00,c01,c10,c11,d00,d01,d10,d11):
zz,zu,uz,uu = two_qb_basis()
psi = (c00*d00-c01*d10)*zz + (c00*d01-c01*d11)*zu + (c10*d00-c11*d10)*uz + (c10*d01-c11*d11)*uu
return psi/sqrt(2)
def phi_p(c00,c01,c10,c11,d00,d01,d10,d11):
zz,zu,uz,uu = two_qb_basis()
psi = (c00*d10+c01*d00)*zz + (c00*d11+c01*d01)*zu + (c10*d10+c11*d00)*uz + (c10*d11+c11*d01)*uu
return psi/sqrt(2)
def phi_m(c00,c01,c10,c11,d00,d01,d10,d11):
zz,zu,uz,uu = two_qb_basis()
psi = (c00*d10-c01*d00)*zz + (c00*d11-c01*d01)*zu + (c10*d10-c11*d00)*uz + (c10*d11-c11*d01)*uu
return psi/sqrt(2)
c00 = sqrt(p); c01 = sqrt((1-p)/2); c10 = sqrt((1-p)/2); c11 = 0
d00 = sqrt(q); d01 = sqrt((1-q)/2); d10 = sqrt((1-q)/2); d11 = 0
psip = psi_p(c00,c01,c10,c11,d00,d01,d10,d11);
psim = psi_m(c00,c01,c10,c11,d00,d01,d10,d11)
phip = phi_p(c00,c01,c10,c11,d00,d01,d10,d11);
phim = phi_m(c00,c01,c10,c11,d00,d01,d10,d11)
simplify(psip), simplify(psim), simplify(phip), simplify(phim)
psip_norm2 = psip.T*psip; simplify(psip_norm2)
psim_norm2 = psim.T*psim; simplify(psim_norm2)
phip_norm2 = phip.T*phip; simplify(phip_norm2)
phim_norm2 = phim.T*phim; simplify(phim_norm2)
|
https://github.com/arnavdas88/QuGlassyIsing
|
arnavdas88
|
!pip install qiskit
from qiskit.providers.aer import AerSimulator, QasmSimulator
from qiskit.algorithms import VQE
from qiskit.algorithms.optimizers import COBYLA
from qiskit.circuit.library import TwoLocal
# opflow is Qiskit's module for creating operators like yours
from qiskit import *
from qiskit.opflow import OperatorBase
from qiskit.opflow import Z, X, I # Pauli Z, X matrices and identity
import pylab
import matplotlib.pyplot as plt
import numpy as np
def store_intermediate_result(eval_count, parameters, mean, std):
counts.append(eval_count)
values.append(mean)
def get_gradient(values, counts):
rvalues = []
rcounts = []
for i in range(1, len(values)):
rvalues += [ (values[i - 1] - values[i]) ]
rcounts = [ i for i in range(len(rvalues)) ]
return rvalues, rcounts
def get_absolute(values):
return [ (v if v > 0 else -v) for v in values]
# J = 1.0
counts = []
values = []
H = (504.0 * I^I^I^I^I^I^I^Z) + (1008.0 * I^I^I^I^I^I^Z^I) + (2016.0 * I^I^I^I^I^Z^I^I) + (504.0 * I^I^I^I^Z^I^I^I) + (1143.7999999999997 * I^I^I^Z^I^I^I^I) + (2287.6 * I^I^Z^I^I^I^I^I) + (4575.200000000001 * I^Z^I^I^I^I^I^I) + (1143.7999999999997 * Z^I^I^I^I^I^I^I) + (98.0 * I^I^I^I^I^I^Z^Z) + (196.0 * I^I^I^I^I^Z^I^Z) + (392.0 * I^I^I^I^I^Z^Z^I) + (49.0 * I^I^I^I^Z^I^I^Z) + (98.0 * I^I^I^I^Z^I^Z^I) + (196.0 * I^I^I^I^Z^Z^I^I) + (93.1 * I^I^Z^Z^I^I^I^I) + (186.2 * I^Z^I^Z^I^I^I^I) + (372.4 * I^Z^Z^I^I^I^I^I) + (46.55 * Z^I^I^Z^I^I^I^I) + (93.1 * Z^I^Z^I^I^I^I^I) + (186.2 * Z^Z^I^I^I^I^I^I)
# you can swap this for a real quantum device and keep the rest of the code the same!
# backend = AerSimulator(method='matrix_product_state')
backend = QasmSimulator()
# COBYLA usually works well for small problems like this one
optimizer = COBYLA(maxiter=2000)
# EfficientSU2 is a standard heuristic chemistry ansatz from Qiskit's circuit library
ansatz = TwoLocal(num_qubits=8, rotation_blocks=['ry', 'rz'], entanglement_blocks=None, entanglement='full', reps=1, skip_unentangled_qubits=False, skip_final_rotation_layer=True)
# set the algorithm
vqe = VQE(ansatz, optimizer, quantum_instance=backend, callback=store_intermediate_result)
#run it with the Hamiltonian we defined above
result = vqe.compute_minimum_eigenvalue(H)
#print the result (it contains lot's of information)
print(result)
v1, c1 = get_gradient(values, counts)
plt.figure(figsize=(15,15))
plt.plot(c1,v1)
plt.xlabel('optimization step')
plt.ylabel('E')
plt.show()
counts = []
values = []
H = (504.0 * I^I^I^I^I^I^I^Z) + (1008.0 * I^I^I^I^I^I^Z^I) + (2016.0 * I^I^I^I^I^Z^I^I) + (504.0 * I^I^I^I^Z^I^I^I) + (1143.7999999999997 * I^I^I^Z^I^I^I^I) + (2287.6 * I^I^Z^I^I^I^I^I) + (4575.200000000001 * I^Z^I^I^I^I^I^I) + (1143.7999999999997 * Z^I^I^I^I^I^I^I) + (98.0 * I^I^I^I^I^I^Z^Z) + (196.0 * I^I^I^I^I^Z^I^Z) + (392.0 * I^I^I^I^I^Z^Z^I) + (49.0 * I^I^I^I^Z^I^I^Z) + (98.0 * I^I^I^I^Z^I^Z^I) + (196.0 * I^I^I^I^Z^Z^I^I) + (93.1 * I^I^Z^Z^I^I^I^I) + (186.2 * I^Z^I^Z^I^I^I^I) + (372.4 * I^Z^Z^I^I^I^I^I) + (46.55 * Z^I^I^Z^I^I^I^I) + (93.1 * Z^I^Z^I^I^I^I^I) + (186.2 * Z^Z^I^I^I^I^I^I)
# you can swap this for a real quantum device and keep the rest of the code the same!
# backend = AerSimulator(method='matrix_product_state')
backend = QasmSimulator()
# COBYLA usually works well for small problems like this one
optimizer = COBYLA(maxiter=2000)
# EfficientSU2 is a standard heuristic chemistry ansatz from Qiskit's circuit library
ansatz = TwoLocal(num_qubits=8, rotation_blocks=['ry', 'rz'], entanglement_blocks=None, entanglement='full', reps=1, skip_unentangled_qubits=False, skip_final_rotation_layer=True)
# set the algorithm
vqe = VQE(ansatz, optimizer, quantum_instance=backend, callback=store_intermediate_result)
#run it with the Hamiltonian we defined above
result = vqe.compute_minimum_eigenvalue(H)
#print the result (it contains lot's of information)
print(result)
v2, c2 = get_gradient(values, counts)
plt.figure(figsize=(15,15))
plt.plot(c2,v2)
plt.xlabel('optimization step')
plt.ylabel('E')
plt.show()
counts = []
values = []
H = (504.0 * I^I^I^I^I^I^I^Z) + (1008.0 * I^I^I^I^I^I^Z^I) + (2016.0 * I^I^I^I^I^Z^I^I) + (504.0 * I^I^I^I^Z^I^I^I) + (1143.7999999999997 * I^I^I^Z^I^I^I^I) + (2287.6 * I^I^Z^I^I^I^I^I) + (4575.200000000001 * I^Z^I^I^I^I^I^I) + (1143.7999999999997 * Z^I^I^I^I^I^I^I) + (98.0 * I^I^I^I^I^I^Z^Z)+(196.0 * I^I^I^I^I^Z^I^Z) + (392.0 * I^I^I^I^I^Z^Z^I) + (49.0 * I^I^I^I^Z^I^I^Z) + (98.0 * I^I^I^I^Z^I^Z^I) + (196.0 * I^I^I^I^Z^Z^I^I) + (93.1 * I^I^Z^Z^I^I^I^I) + (186.2 * I^Z^I^Z^I^I^I^I)+ (372.4 * I^Z^Z^I^I^I^I^I) + (46.55 * Z^I^I^Z^I^I^I^I) + (93.1 * Z^I^Z^I^I^I^I^I) + (186.2 * Z^Z^I^I^I^I^I^I)
# you can swap this for a real quantum device and keep the rest of the code the same!
# backend = AerSimulator(method='matrix_product_state')
backend = QasmSimulator()
# COBYLA usually works well for small problems like this one
optimizer = COBYLA(maxiter=2000)
# EfficientSU2 is a standard heuristic chemistry ansatz from Qiskit's circuit library
ansatz = TwoLocal(num_qubits=8, rotation_blocks=['ry', 'rz'], entanglement_blocks=None, entanglement='full', reps=1, skip_unentangled_qubits=False, skip_final_rotation_layer=True)
# set the algorithm
vqe = VQE(ansatz, optimizer, quantum_instance=backend, callback=store_intermediate_result)
#run it with the Hamiltonian we defined above
result = vqe.compute_minimum_eigenvalue(H)
#print the result (it contains lot's of information)
print(result)
v3, c3 = get_gradient(values, counts)
plt.figure(figsize=(15,15))
plt.plot(c3,v3)
plt.xlabel('optimization step')
plt.ylabel('E')
plt.show()
counts = []
values = []
H = (504.0 * I^I^I^I^I^I^I^Z) + (1008.0 * I^I^I^I^I^I^Z^I) + (2016.0 * I^I^I^I^I^Z^I^I) + (504.0 * I^I^I^I^Z^I^I^I) + (1143.7999999999997 * I^I^I^Z^I^I^I^I) + (2287.6 * I^I^Z^I^I^I^I^I) + (4575.200000000001 * I^Z^I^I^I^I^I^I) + (1143.7999999999997 * Z^I^I^I^I^I^I^I)+ (98.0 * I^I^I^I^I^I^Z^Z) + (196.0 * I^I^I^I^I^Z^I^Z) + (392.0 * I^I^I^I^I^Z^Z^I) + (49.0 * I^I^I^I^Z^I^I^Z)+ (98.0 * I^I^I^I^Z^I^Z^I)+ (196.0 * I^I^I^I^Z^Z^I^I) + (93.1 * I^I^Z^Z^I^I^I^I)+ (186.2 * I^Z^I^Z^I^I^I^I)+ (372.4 * I^Z^Z^I^I^I^I^I)+ (46.55 * Z^I^I^Z^I^I^I^I)+ (93.1 * Z^I^Z^I^I^I^I^I)+ (186.2 * Z^Z^I^I^I^I^I^I)
# you can swap this for a real quantum device and keep the rest of the code the same!
# backend = AerSimulator(method='matrix_product_state')
backend = QasmSimulator()
# COBYLA usually works well for small problems like this one
optimizer = COBYLA(maxiter=2000)
# EfficientSU2 is a standard heuristic chemistry ansatz from Qiskit's circuit library
ansatz = TwoLocal(num_qubits=8, rotation_blocks=['ry', 'rz'], entanglement_blocks=None, entanglement='full', reps=1, skip_unentangled_qubits=False, skip_final_rotation_layer=True)
# set the algorithm
vqe = VQE(ansatz, optimizer, quantum_instance=backend, callback=store_intermediate_result)
#run it with the Hamiltonian we defined above
result = vqe.compute_minimum_eigenvalue(H)
#print the result (it contains lot's of information)
print(result)
v4, c4 = get_gradient(values, counts)
plt.figure(figsize=(15,15))
plt.plot(c4,v4)
plt.xlabel('optimization step')
plt.ylabel('E')
plt.show()
# 2nd Order Der
v1, c1 = get_gradient(v1, c1)
v2, c2 = get_gradient(v2, c2)
v3, c3 = get_gradient(v3, c3)
v4, c4 = get_gradient(v4, c4)
v1 = get_absolute(v1)
v2 = get_absolute(v2)
v3 = get_absolute(v3)
v4 = get_absolute(v4)
plt.figure(figsize=(15,15))
plt.plot(c1,v1, label="R1")
plt.plot(c2,v2, label="R2")
plt.plot(c3,v3, label="R3")
plt.plot(c4,v4, label="R4")
plt.xlabel('comparison optimization step')
plt.ylabel('E')
plt.legend()
plt.show()
plt.figure(figsize=(15,15))
plt.plot(c1[:100],v1[:100], label="R1")
plt.plot(c2[:100],v2[:100], label="R2")
plt.plot(c3[:100],v3[:100], label="R3")
plt.plot(c4[:100],v4[:100], label="R4")
plt.xlabel('comparison optimization step')
plt.ylabel('E')
plt.legend()
plt.show()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit.circuit.library import MCXGate
gate = MCXGate(4)
from qiskit import QuantumCircuit
circuit = QuantumCircuit(5)
circuit.append(gate, [0, 1, 4, 2, 3])
circuit.draw('mpl')
|
https://github.com/apcarrik/qiskit-dev
|
apcarrik
|
import numpy as np
from qiskit import *
from matplotlib import pyplot
# Initialize quantum circuit with 3 qubits (and no classical bits)
circ = QuantumCircuit(3)
# Set circuit into 3-qubit GHZ state
circ.h(0)
circ.cx(0,1)
circ.cx(0,2)
# Visualize circuit
circ.draw('mpl')
pyplot.show()
### Simulating circuits with Qiskit Aer
from qiskit import Aer
backend = Aer.get_backend('statevector_simulator')
job = execute(circ, backend)
result = job.result()
outputstate = result.get_statevector(circ, decimals=3)
print(outputstate)
from qiskit.visualization import plot_state_city
plot_state_city(outputstate)
pyplot.show()
### Unitary Backend
backend = Aer.get_backend('unitary_simulator')
job = execute(circ, backend)
result = job.result()
print(result.get_unitary(circ, decimals=3))
### Open QASM Backend
# New circuit with classical bits
meas = QuantumCircuit(3,3)
meas.barrier(range(3))
meas.measure(range(3),range(3))
qc = circ + meas
qc.draw('mpl')
pyplot.show()
# Simulate
backend_sim = Aer.get_backend('qasm_simulator')
job_sim = execute(qc, backend_sim, shots=1024)
result_sim = job_sim.result()
counts = result_sim.get_counts(qc)
print(counts)
from qiskit.visualization import plot_histogram
plot_histogram(counts)
pyplot.show()
|
https://github.com/zapata-engineering/orquestra-qiskit
|
zapata-engineering
|
################################################################################
# Β© Copyright 2022 Zapata Computing Inc.
################################################################################
from typing import List, Optional
import numpy as np
from orquestra.quantum.api.wavefunction_simulator import BaseWavefunctionSimulator
from orquestra.quantum.circuits import Circuit
from orquestra.quantum.circuits.layouts import CircuitConnectivity
from orquestra.quantum.typing import StateVector
from orquestra.quantum.wavefunction import flip_amplitudes
from qiskit import QuantumCircuit, execute
from qiskit.transpiler import CouplingMap
from qiskit_aer.noise import NoiseModel
from orquestra.integrations.qiskit.conversions import export_to_qiskit
from orquestra.integrations.qiskit.runner._qiskit_runner import AnyQiskitBackend
class QiskitWavefunctionSimulator(BaseWavefunctionSimulator):
"""Wavefunction simulator using Qiskit backends.
Note that this simulator only works with backends that supports save_state
instruction.
"""
def __init__(
self,
qiskit_backend: AnyQiskitBackend,
noise_model: Optional[NoiseModel] = None,
device_connectivity: Optional[CircuitConnectivity] = None,
basis_gates: Optional[List[str]] = None,
optimization_level: int = 0,
seed: Optional[int] = None,
):
super().__init__()
self.seed = seed
self.backend = qiskit_backend
self.noise_model = noise_model
self.optimization_level = optimization_level
self.basis_gates = (
noise_model.basis_gates
if basis_gates is None and noise_model is not None
else basis_gates
)
self.device_connectivity = device_connectivity
def _get_wavefunction_from_native_circuit(
self, circuit: Circuit, initial_state: StateVector
):
qiskit_circuit = export_to_qiskit(circuit)
if not np.array_equal(initial_state, [1] + [0] * (2**circuit.n_qubits - 1)):
state_prep_circuit = QuantumCircuit(circuit.n_qubits)
state_prep_circuit.initialize(flip_amplitudes(initial_state))
qiskit_circuit = state_prep_circuit.compose(qiskit_circuit)
qiskit_circuit.save_state()
coupling_map = (
None
if self.device_connectivity is None
else CouplingMap(self.device_connectivity.connectivity)
)
job = execute(
qiskit_circuit,
self.backend,
noise_model=self.noise_model,
coupling_map=coupling_map,
basis_gates=self.basis_gates,
optimization_level=self.optimization_level,
seed_simulator=self.seed,
seed_transpiler=self.seed,
)
return flip_amplitudes(
job.result().get_statevector(qiskit_circuit, decimals=20).data
)
|
https://github.com/icarosadero/maxima_function_qiskit
|
icarosadero
|
%matplotlib inline
from qiskit import QuantumCircuit, execute, Aer, IBMQ, QuantumRegister
from qiskit.compiler import transpile, assemble
from qiskit.tools.jupyter import *
from qiskit.visualization import *
provider = IBMQ.load_account()
circ = QuantumCircuit(4,4)
#Preparation
circ.h(0)
circ.h(1)
#Oracle function
def oracle(circuit, mapping):
if mapping=="a":
"""
100x
010
101x
011
"""
circuit.cx(1,2)
circuit.x(2)
elif mapping=="b":
"""
100x
001
110x
011
"""
circuit.cx(0,2)
circuit.x(2)
elif mapping=="constant":
circuit.x(2)
oracle(circ,"b")
circ.barrier(range(4))
circ.x(2)
circ.ch(2,3)
circ.x(2)
circ.barrier(range(4))
circ.measure(range(4),range(4))
circ.draw("mpl")
nruns = 2048
backend_sim = Aer.get_backend('qasm_simulator')
job_sim = execute(circ, backend_sim, shots=nruns)
result_sim = job_sim.result()
counts = result_sim.get_counts(circ)
plot_histogram(counts)
dict(filter(lambda x: x[1]/nruns >= 0.2,counts.items()))
|
https://github.com/swe-train/qiskit__qiskit
|
swe-train
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 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.
# pylint: disable=invalid-name
"""Tests for error mitigation routines."""
import unittest
from collections import Counter
import numpy as np
from qiskit import QiskitError, QuantumCircuit
from qiskit.quantum_info import Statevector
from qiskit.quantum_info.operators.predicates import matrix_equal
from qiskit.result import (
CorrelatedReadoutMitigator,
Counts,
LocalReadoutMitigator,
)
from qiskit.result.mitigation.utils import (
counts_probability_vector,
expval_with_stddev,
stddev,
str2diag,
)
from qiskit.result.utils import marginal_counts
from qiskit.test import QiskitTestCase
from qiskit.providers.fake_provider import FakeYorktown
class TestReadoutMitigation(QiskitTestCase):
"""Tests for correlated and local readout mitigation."""
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.rng = np.random.default_rng(42)
@staticmethod
def compare_results(res1, res2):
"""Compare the results between two runs"""
res1_total_shots = sum(res1.values())
res2_total_shots = sum(res2.values())
keys = set(res1.keys()).union(set(res2.keys()))
total = 0
for key in keys:
val1 = res1.get(key, 0) / res1_total_shots
val2 = res2.get(key, 0) / res2_total_shots
total += abs(val1 - val2) ** 2
return total
@staticmethod
def mitigators(assignment_matrices, qubits=None):
"""Generates the mitigators to test for given assignment matrices"""
full_assignment_matrix = assignment_matrices[0]
for m in assignment_matrices[1:]:
full_assignment_matrix = np.kron(full_assignment_matrix, m)
CRM = CorrelatedReadoutMitigator(full_assignment_matrix, qubits)
LRM = LocalReadoutMitigator(assignment_matrices, qubits)
mitigators = [CRM, LRM]
return mitigators
@staticmethod
def simulate_circuit(circuit, assignment_matrix, num_qubits, shots=1024):
"""Simulates the given circuit under the given readout noise"""
probs = Statevector.from_instruction(circuit).probabilities()
noisy_probs = assignment_matrix @ probs
labels = [bin(a)[2:].zfill(num_qubits) for a in range(2**num_qubits)]
results = TestReadoutMitigation.rng.choice(labels, size=shots, p=noisy_probs)
return Counts(dict(Counter(results)))
@staticmethod
def ghz_3_circuit():
"""A 3-qubit circuit generating |000>+|111>"""
c = QuantumCircuit(3)
c.h(0)
c.cx(0, 1)
c.cx(1, 2)
return (c, "ghz_3_ciruit", 3)
@staticmethod
def first_qubit_h_3_circuit():
"""A 3-qubit circuit generating |000>+|001>"""
c = QuantumCircuit(3)
c.h(0)
return (c, "first_qubit_h_3_circuit", 3)
@staticmethod
def assignment_matrices():
"""A 3-qubit readout noise assignment matrices"""
return LocalReadoutMitigator(backend=FakeYorktown())._assignment_mats[0:3]
@staticmethod
def counts_data(circuit, assignment_matrices, shots=1024):
"""Generates count data for the noisy and noiseless versions of the circuit simulation"""
full_assignment_matrix = assignment_matrices[0]
for m in assignment_matrices[1:]:
full_assignment_matrix = np.kron(full_assignment_matrix, m)
num_qubits = len(assignment_matrices)
ideal_assignment_matrix = np.eye(2**num_qubits)
counts_ideal = TestReadoutMitigation.simulate_circuit(
circuit, ideal_assignment_matrix, num_qubits, shots
)
counts_noise = TestReadoutMitigation.simulate_circuit(
circuit, full_assignment_matrix, num_qubits, shots
)
probs_noise = {key: value / shots for key, value in counts_noise.items()}
return counts_ideal, counts_noise, probs_noise
def test_mitigation_improvement(self):
"""Test whether readout mitigation led to more accurate results"""
shots = 1024
assignment_matrices = self.assignment_matrices()
num_qubits = len(assignment_matrices)
mitigators = self.mitigators(assignment_matrices)
circuit, circuit_name, num_qubits = self.ghz_3_circuit()
counts_ideal, counts_noise, probs_noise = self.counts_data(
circuit, assignment_matrices, shots
)
unmitigated_error = self.compare_results(counts_ideal, counts_noise)
unmitigated_stddev = stddev(probs_noise, shots)
for mitigator in mitigators:
mitigated_quasi_probs = mitigator.quasi_probabilities(counts_noise)
mitigated_probs = (
mitigated_quasi_probs.nearest_probability_distribution().binary_probabilities(
num_bits=num_qubits
)
)
mitigated_error = self.compare_results(counts_ideal, mitigated_probs)
self.assertLess(
mitigated_error,
unmitigated_error * 0.8,
"Mitigator {} did not improve circuit {} measurements".format(
mitigator, circuit_name
),
)
mitigated_stddev_upper_bound = mitigated_quasi_probs._stddev_upper_bound
max_unmitigated_stddev = max(unmitigated_stddev.values())
self.assertGreaterEqual(
mitigated_stddev_upper_bound,
max_unmitigated_stddev,
"Mitigator {} on circuit {} gave stddev upper bound {} "
"while unmitigated stddev maximum is {}".format(
mitigator,
circuit_name,
mitigated_stddev_upper_bound,
max_unmitigated_stddev,
),
)
def test_expectation_improvement(self):
"""Test whether readout mitigation led to more accurate results
and that its standard deviation is increased"""
shots = 1024
assignment_matrices = self.assignment_matrices()
mitigators = self.mitigators(assignment_matrices)
num_qubits = len(assignment_matrices)
diagonals = []
diagonals.append("IZ0")
diagonals.append("101")
diagonals.append("IZZ")
qubit_index = {i: i for i in range(num_qubits)}
circuit, circuit_name, num_qubits = self.ghz_3_circuit()
counts_ideal, counts_noise, _ = self.counts_data(circuit, assignment_matrices, shots)
probs_ideal, _ = counts_probability_vector(counts_ideal, qubit_index=qubit_index)
probs_noise, _ = counts_probability_vector(counts_noise, qubit_index=qubit_index)
for diagonal in diagonals:
if isinstance(diagonal, str):
diagonal = str2diag(diagonal)
unmitigated_expectation, unmitigated_stddev = expval_with_stddev(
diagonal, probs_noise, shots=counts_noise.shots()
)
ideal_expectation = np.dot(probs_ideal, diagonal)
unmitigated_error = np.abs(ideal_expectation - unmitigated_expectation)
for mitigator in mitigators:
mitigated_expectation, mitigated_stddev = mitigator.expectation_value(
counts_noise, diagonal
)
mitigated_error = np.abs(ideal_expectation - mitigated_expectation)
self.assertLess(
mitigated_error,
unmitigated_error,
"Mitigator {} did not improve circuit {} expectation computation for diagonal {} "
"ideal: {}, unmitigated: {} mitigated: {}".format(
mitigator,
circuit_name,
diagonal,
ideal_expectation,
unmitigated_expectation,
mitigated_expectation,
),
)
self.assertGreaterEqual(
mitigated_stddev,
unmitigated_stddev,
"Mitigator {} did not increase circuit {} the standard deviation".format(
mitigator, circuit_name
),
)
def test_clbits_parameter(self):
"""Test whether the clbits parameter is handled correctly"""
shots = 10000
assignment_matrices = self.assignment_matrices()
mitigators = self.mitigators(assignment_matrices)
circuit, _, _ = self.first_qubit_h_3_circuit()
counts_ideal, counts_noise, _ = self.counts_data(circuit, assignment_matrices, shots)
counts_ideal_12 = marginal_counts(counts_ideal, [1, 2])
counts_ideal_02 = marginal_counts(counts_ideal, [0, 2])
for mitigator in mitigators:
mitigated_probs_12 = (
mitigator.quasi_probabilities(counts_noise, qubits=[1, 2], clbits=[1, 2])
.nearest_probability_distribution()
.binary_probabilities(num_bits=2)
)
mitigated_error = self.compare_results(counts_ideal_12, mitigated_probs_12)
self.assertLess(
mitigated_error,
0.001,
"Mitigator {} did not correctly marganalize for qubits 1,2".format(mitigator),
)
mitigated_probs_02 = (
mitigator.quasi_probabilities(counts_noise, qubits=[0, 2], clbits=[0, 2])
.nearest_probability_distribution()
.binary_probabilities(num_bits=2)
)
mitigated_error = self.compare_results(counts_ideal_02, mitigated_probs_02)
self.assertLess(
mitigated_error,
0.001,
"Mitigator {} did not correctly marganalize for qubits 0,2".format(mitigator),
)
def test_qubits_parameter(self):
"""Test whether the qubits parameter is handled correctly"""
shots = 10000
assignment_matrices = self.assignment_matrices()
mitigators = self.mitigators(assignment_matrices)
circuit, _, _ = self.first_qubit_h_3_circuit()
counts_ideal, counts_noise, _ = self.counts_data(circuit, assignment_matrices, shots)
counts_ideal_012 = counts_ideal
counts_ideal_210 = Counts({"000": counts_ideal["000"], "100": counts_ideal["001"]})
counts_ideal_102 = Counts({"000": counts_ideal["000"], "010": counts_ideal["001"]})
for mitigator in mitigators:
mitigated_probs_012 = (
mitigator.quasi_probabilities(counts_noise, qubits=[0, 1, 2])
.nearest_probability_distribution()
.binary_probabilities(num_bits=3)
)
mitigated_error = self.compare_results(counts_ideal_012, mitigated_probs_012)
self.assertLess(
mitigated_error,
0.001,
"Mitigator {} did not correctly handle qubit order 0, 1, 2".format(mitigator),
)
mitigated_probs_210 = (
mitigator.quasi_probabilities(counts_noise, qubits=[2, 1, 0])
.nearest_probability_distribution()
.binary_probabilities(num_bits=3)
)
mitigated_error = self.compare_results(counts_ideal_210, mitigated_probs_210)
self.assertLess(
mitigated_error,
0.001,
"Mitigator {} did not correctly handle qubit order 2, 1, 0".format(mitigator),
)
mitigated_probs_102 = (
mitigator.quasi_probabilities(counts_noise, qubits=[1, 0, 2])
.nearest_probability_distribution()
.binary_probabilities(num_bits=3)
)
mitigated_error = self.compare_results(counts_ideal_102, mitigated_probs_102)
self.assertLess(
mitigated_error,
0.001,
"Mitigator {} did not correctly handle qubit order 1, 0, 2".format(mitigator),
)
def test_repeated_qubits_parameter(self):
"""Tests the order of mitigated qubits."""
shots = 10000
assignment_matrices = self.assignment_matrices()
mitigators = self.mitigators(assignment_matrices, qubits=[0, 1, 2])
circuit, _, _ = self.first_qubit_h_3_circuit()
counts_ideal, counts_noise, _ = self.counts_data(circuit, assignment_matrices, shots)
counts_ideal_012 = counts_ideal
counts_ideal_210 = Counts({"000": counts_ideal["000"], "100": counts_ideal["001"]})
for mitigator in mitigators:
mitigated_probs_210 = (
mitigator.quasi_probabilities(counts_noise, qubits=[2, 1, 0])
.nearest_probability_distribution()
.binary_probabilities(num_bits=3)
)
mitigated_error = self.compare_results(counts_ideal_210, mitigated_probs_210)
self.assertLess(
mitigated_error,
0.001,
"Mitigator {} did not correctly handle qubit order 2,1,0".format(mitigator),
)
# checking qubit order 2,1,0 should not "overwrite" the default 0,1,2
mitigated_probs_012 = (
mitigator.quasi_probabilities(counts_noise)
.nearest_probability_distribution()
.binary_probabilities(num_bits=3)
)
mitigated_error = self.compare_results(counts_ideal_012, mitigated_probs_012)
self.assertLess(
mitigated_error,
0.001,
"Mitigator {} did not correctly handle qubit order 0,1,2 (the expected default)".format(
mitigator
),
)
def test_qubits_subset_parameter(self):
"""Tests mitigation on a subset of the initial set of qubits."""
shots = 10000
assignment_matrices = self.assignment_matrices()
mitigators = self.mitigators(assignment_matrices, qubits=[2, 4, 6])
circuit, _, _ = self.first_qubit_h_3_circuit()
counts_ideal, counts_noise, _ = self.counts_data(circuit, assignment_matrices, shots)
counts_ideal_2 = marginal_counts(counts_ideal, [0])
counts_ideal_6 = marginal_counts(counts_ideal, [2])
for mitigator in mitigators:
mitigated_probs_2 = (
mitigator.quasi_probabilities(counts_noise, qubits=[2])
.nearest_probability_distribution()
.binary_probabilities(num_bits=1)
)
mitigated_error = self.compare_results(counts_ideal_2, mitigated_probs_2)
self.assertLess(
mitigated_error,
0.001,
"Mitigator {} did not correctly handle qubit subset".format(mitigator),
)
mitigated_probs_6 = (
mitigator.quasi_probabilities(counts_noise, qubits=[6])
.nearest_probability_distribution()
.binary_probabilities(num_bits=1)
)
mitigated_error = self.compare_results(counts_ideal_6, mitigated_probs_6)
self.assertLess(
mitigated_error,
0.001,
"Mitigator {} did not correctly handle qubit subset".format(mitigator),
)
diagonal = str2diag("ZZ")
ideal_expectation = 0
mitigated_expectation, _ = mitigator.expectation_value(
counts_noise, diagonal, qubits=[2, 6]
)
mitigated_error = np.abs(ideal_expectation - mitigated_expectation)
self.assertLess(
mitigated_error,
0.1,
"Mitigator {} did not improve circuit expectation".format(mitigator),
)
def test_from_backend(self):
"""Test whether a local mitigator can be created directly from backend properties"""
backend = FakeYorktown()
num_qubits = len(backend.properties().qubits)
probs = TestReadoutMitigation.rng.random((num_qubits, 2))
for qubit_idx, qubit_prop in enumerate(backend.properties().qubits):
for prop in qubit_prop:
if prop.name == "prob_meas1_prep0":
prop.value = probs[qubit_idx][0]
if prop.name == "prob_meas0_prep1":
prop.value = probs[qubit_idx][1]
LRM_from_backend = LocalReadoutMitigator(backend=backend)
mats = []
for qubit_idx in range(num_qubits):
mat = np.array(
[
[1 - probs[qubit_idx][0], probs[qubit_idx][1]],
[probs[qubit_idx][0], 1 - probs[qubit_idx][1]],
]
)
mats.append(mat)
LRM_from_matrices = LocalReadoutMitigator(assignment_matrices=mats)
self.assertTrue(
matrix_equal(
LRM_from_backend.assignment_matrix(), LRM_from_matrices.assignment_matrix()
)
)
def test_error_handling(self):
"""Test that the assignment matrices are valid."""
bad_matrix_A = np.array([[-0.3, 1], [1.3, 0]]) # negative indices
bad_matrix_B = np.array([[0.2, 1], [0.7, 0]]) # columns not summing to 1
good_matrix_A = np.array([[0.2, 1], [0.8, 0]])
for bad_matrix in [bad_matrix_A, bad_matrix_B]:
with self.assertRaises(QiskitError) as cm:
CorrelatedReadoutMitigator(bad_matrix)
self.assertEqual(
cm.exception.message,
"Assignment matrix columns must be valid probability distributions",
)
with self.assertRaises(QiskitError) as cm:
amats = [good_matrix_A, bad_matrix_A]
LocalReadoutMitigator(amats)
self.assertEqual(
cm.exception.message,
"Assignment matrix columns must be valid probability distributions",
)
with self.assertRaises(QiskitError) as cm:
amats = [bad_matrix_B, good_matrix_A]
LocalReadoutMitigator(amats)
self.assertEqual(
cm.exception.message,
"Assignment matrix columns must be valid probability distributions",
)
def test_expectation_value_endian(self):
"""Test that endian for expval is little."""
mitigators = self.mitigators(self.assignment_matrices())
counts = Counts({"10": 3, "11": 24, "00": 74, "01": 923})
for mitigator in mitigators:
expval, _ = mitigator.expectation_value(counts, diagonal="IZ", qubits=[0, 1])
self.assertAlmostEqual(expval, -1.0, places=0)
def test_quasi_probabilities_shots_passing(self):
"""Test output of LocalReadoutMitigator.quasi_probabilities
We require the number of shots to be set in the output.
"""
mitigator = LocalReadoutMitigator([np.array([[0.9, 0.1], [0.1, 0.9]])], qubits=[0])
counts = Counts({"10": 3, "11": 24, "00": 74, "01": 923})
quasi_dist = mitigator.quasi_probabilities(counts)
self.assertEqual(quasi_dist.shots, sum(counts.values()))
# custom number of shots
quasi_dist = mitigator.quasi_probabilities(counts, shots=1025)
self.assertEqual(quasi_dist.shots, 1025)
class TestLocalReadoutMitigation(QiskitTestCase):
"""Tests specific to the local readout mitigator"""
def test_assignment_matrix(self):
"""Tests that the local mitigator generates the full assignment matrix correctly"""
qubits = [7, 2, 3]
assignment_matrices = LocalReadoutMitigator(backend=FakeYorktown())._assignment_mats[0:3]
expected_assignment_matrix = np.kron(
np.kron(assignment_matrices[2], assignment_matrices[1]), assignment_matrices[0]
)
expected_mitigation_matrix = np.linalg.inv(expected_assignment_matrix)
LRM = LocalReadoutMitigator(assignment_matrices, qubits)
self.assertTrue(matrix_equal(expected_mitigation_matrix, LRM.mitigation_matrix()))
self.assertTrue(matrix_equal(expected_assignment_matrix, LRM.assignment_matrix()))
if __name__ == "__main__":
unittest.main()
|
https://github.com/swe-train/qiskit__qiskit
|
swe-train
|
# 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.
"""
Drawing objects for timeline drawer.
Drawing objects play two important roles:
- Allowing unittests of visualization module. Usually it is hard for image files to be tested.
- Removing program parser from each plotter interface. We can easily add new plotter.
This module is based on the structure of matplotlib as it is the primary plotter
of the timeline drawer. However this interface is agnostic to the actual plotter.
Design concept
~~~~~~~~~~~~~~
When we think about dynamically updating drawings, it will be most efficient to
update only the changed properties of drawings rather than regenerating entirely from scratch.
Thus the core :py:class:`~qiskit.visualization.timeline.core.DrawerCanvas` generates
all possible drawings in the beginning and then the canvas instance manages
visibility of each drawing according to the end-user request.
Data key
~~~~~~~~
In the abstract class ``ElementaryData`` common attributes to represent a drawing are
specified. In addition, drawings have the `data_key` property that returns an
unique hash of the object for comparison.
This key is generated from a data type, the location of the drawing in the canvas,
and associated qubit or classical bit objects.
See py:mod:`qiskit.visualization.timeline.types` for detail on the data type.
If a data key cannot distinguish two independent objects, you need to add a new data type.
The data key may be used in the plotter interface to identify the object.
Drawing objects
~~~~~~~~~~~~~~~
To support not only `matplotlib` but also multiple plotters, those drawings should be
universal and designed without strong dependency on modules in `matplotlib`.
This means drawings that represent primitive geometries are preferred.
It should be noted that there will be no unittest for each plotter API, which takes
drawings and outputs image data, we should avoid adding a complicated geometry
that has a context of the scheduled circuit program.
For example, a two qubit scheduled gate may be drawn by two rectangles that represent
time occupation of two quantum registers during the gate along with a line connecting
these rectangles to identify the pair. This shape can be represented with
two box-type objects with one line-type object instead of defining a new object dedicated
to the two qubit gate. As many plotters don't support an API that visualizes such
a linked-box shape, if we introduce such complex drawings and write a
custom wrapper function on top of the existing API,
it could be difficult to prevent bugs with the CI tools due to lack of
the effective unittest for image data.
Link between gates
~~~~~~~~~~~~~~~~~~
The ``GateLinkData`` is the special subclass of drawing that represents
a link between bits. Usually objects are associated to the specific bit,
but ``GateLinkData`` can be associated with multiple bits to illustrate relationship
between quantum or classical bits during a gate operation.
"""
from abc import ABC
from enum import Enum
from typing import Optional, Dict, Any, List, Union
import numpy as np
from qiskit import circuit
from qiskit.visualization.timeline import types
from qiskit.visualization.exceptions import VisualizationError
class ElementaryData(ABC):
"""Base class of the scheduled circuit visualization object.
Note that drawings are mutable.
"""
__hash__ = None
def __init__(
self,
data_type: Union[str, Enum],
xvals: Union[np.ndarray, List[types.Coordinate]],
yvals: Union[np.ndarray, List[types.Coordinate]],
bits: Optional[Union[types.Bits, List[types.Bits]]] = None,
meta: Optional[Dict[str, Any]] = None,
styles: Optional[Dict[str, Any]] = None,
):
"""Create new drawing.
Args:
data_type: String representation of this drawing.
xvals: Series of horizontal coordinate that the object is drawn.
yvals: Series of vertical coordinate that the object is drawn.
bits: Qubit or Clbit object bound to this drawing.
meta: Meta data dictionary of the object.
styles: Style keyword args of the object. This conforms to `matplotlib`.
"""
if bits and isinstance(bits, (circuit.Qubit, circuit.Clbit)):
bits = [bits]
if isinstance(data_type, Enum):
data_type = data_type.value
self.data_type = str(data_type)
self.xvals = xvals
self.yvals = yvals
self.bits = bits
self.meta = meta
self.styles = styles
@property
def data_key(self):
"""Return unique hash of this object."""
return str(
hash(
(
self.__class__.__name__,
self.data_type,
tuple(self.bits),
tuple(self.xvals),
tuple(self.yvals),
)
)
)
def __repr__(self):
return f"{self.__class__.__name__}(type={self.data_type}, key={self.data_key})"
def __eq__(self, other):
return isinstance(other, self.__class__) and self.data_key == other.data_key
class LineData(ElementaryData):
"""Drawing object that represents line shape."""
def __init__(
self,
data_type: Union[str, Enum],
xvals: Union[np.ndarray, List[types.Coordinate]],
yvals: Union[np.ndarray, List[types.Coordinate]],
bit: types.Bits,
meta: Dict[str, Any] = None,
styles: Dict[str, Any] = None,
):
"""Create new line.
Args:
data_type: String representation of this drawing.
xvals: Series of horizontal coordinate that the object is drawn.
yvals: Series of vertical coordinate that the object is drawn.
bit: Bit associated to this object.
meta: Meta data dictionary of the object.
styles: Style keyword args of the object. This conforms to `matplotlib`.
"""
super().__init__(
data_type=data_type, xvals=xvals, yvals=yvals, bits=bit, meta=meta, styles=styles
)
class BoxData(ElementaryData):
"""Drawing object that represents box shape."""
def __init__(
self,
data_type: Union[str, Enum],
xvals: Union[np.ndarray, List[types.Coordinate]],
yvals: Union[np.ndarray, List[types.Coordinate]],
bit: types.Bits,
meta: Dict[str, Any] = None,
styles: Dict[str, Any] = None,
):
"""Create new box.
Args:
data_type: String representation of this drawing.
xvals: Left and right coordinate that the object is drawn.
yvals: Top and bottom coordinate that the object is drawn.
bit: Bit associated to this object.
meta: Meta data dictionary of the object.
styles: Style keyword args of the object. This conforms to `matplotlib`.
Raises:
VisualizationError: When number of data points are not equals to 2.
"""
if len(xvals) != 2 or len(yvals) != 2:
raise VisualizationError("Length of data points are not equals to 2.")
super().__init__(
data_type=data_type, xvals=xvals, yvals=yvals, bits=bit, meta=meta, styles=styles
)
class TextData(ElementaryData):
"""Drawing object that represents a text on canvas."""
def __init__(
self,
data_type: Union[str, Enum],
xval: types.Coordinate,
yval: types.Coordinate,
bit: types.Bits,
text: str,
latex: Optional[str] = None,
meta: Dict[str, Any] = None,
styles: Dict[str, Any] = None,
):
"""Create new text.
Args:
data_type: String representation of this drawing.
xval: Horizontal coordinate that the object is drawn.
yval: Vertical coordinate that the object is drawn.
bit: Bit associated to this object.
text: A string to draw on the canvas.
latex: If set this string is used instead of `text`.
meta: Meta data dictionary of the object.
styles: Style keyword args of the object. This conforms to `matplotlib`.
"""
self.text = text
self.latex = latex
super().__init__(
data_type=data_type, xvals=[xval], yvals=[yval], bits=bit, meta=meta, styles=styles
)
class GateLinkData(ElementaryData):
"""A special drawing data type that represents bit link of multi-bit gates.
Note this object takes multiple bits and dedicates them to the bit link.
This may appear as a line on the canvas.
"""
def __init__(
self, xval: types.Coordinate, bits: List[types.Bits], styles: Dict[str, Any] = None
):
"""Create new bit link.
Args:
xval: Horizontal coordinate that the object is drawn.
bits: Bit associated to this object.
styles: Style keyword args of the object. This conforms to `matplotlib`.
"""
super().__init__(
data_type=types.LineType.GATE_LINK,
xvals=[xval],
yvals=[0],
bits=bits,
meta=None,
styles=styles,
)
|
https://github.com/MiChaelinzo/Quantum-time-travel
|
MiChaelinzo
|
from qiskit.optimization.applications import Maxcut
from qiskit.aqua.algorithms import QAOA
from qiskit import Aer
# Define a graph representing your decision problem (example: Maxcut)
graph = generate_butterfly_graph(with_weights=True)
max_cut = Maxcut(graph)
qp = max_cut.to_quadratic_program()
# QAOA parameters
p = 2 # Number of layers
optimizer = COBYLA(maxiter=100)
# QAOA setup
qaoa = QAOA(optimizer, p=p, quantum_instance=Aer.get_backend('qasm_simulator'))
# Run QAOA
result = qaoa.solve(qp)
# Analyze the result (e.g., best solution and objective value)
print(result)
|
https://github.com/DaisukeIto-ynu/KosakaQ
|
DaisukeIto-ynu
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2018, 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.
"""
Simulator command to snapshot internal simulator representation.
"""
from warnings import warn
from qiskit import QuantumCircuit
from .snapshot import Snapshot
class SnapshotStatevector(Snapshot):
""" Snapshot instruction for statevector snapshot type """
def __init__(self, label, num_qubits=0):
"""Create a statevector state snapshot instruction.
Args:
label (str): the snapshot label.
num_qubits (int): the instruction barrier size [Default: 0].
Raises:
ExtensionError: if snapshot is invalid.
Additional Information:
This snapshot is always performed on all qubits in a circuit.
The number of qubits parameter specifies the size of the
instruction as a barrier and should be set to the number of
qubits in the circuit.
.. deprecated:: 0.9.0
This instruction has been deprecated and will be removed no earlier
than 3 months from the 0.9.0 release date. It has been superseded by the
:class:`qiskit.providers.aer.library.SaveStatevector` instruction.
"""
warn('The `SnapshotStatevector` instruction will be deprecated in the'
'future. It has been superseded by the `SaveStatevector`'
' instructions.', DeprecationWarning, stacklevel=2)
super().__init__(label, snapshot_type='statevector', num_qubits=num_qubits)
def snapshot_statevector(self, label):
"""Take a statevector snapshot of the simulator state.
Args:
label (str): a snapshot label to report the result.
Returns:
QuantumCircuit: with attached instruction.
Raises:
ExtensionError: if snapshot is invalid.
Additional Information:
This snapshot is always performed on all qubits in a circuit.
The number of qubits parameter specifies the size of the
instruction as a barrier and should be set to the number of
qubits in the circuit.
.. deprecated:: 0.9.0
This instruction has been deprecated and will be removed no earlier
than 3 months from the 0.9.0 release date. It has been superseded by the
:class:`qiskit.providers.aer.library.save_statevector` circuit
method.
"""
warn('The `snapshot_statevector` circuit method has been deprecated as of'
' qiskit-aer 0.9 and will be removed in a future release.'
' It has been superseded by the `save_statevector`'
' circuit method.', DeprecationWarning, stacklevel=2)
# Statevector snapshot acts as a barrier across all qubits in the
# circuit
snapshot_register = Snapshot.define_snapshot_register(self)
return self.append(
SnapshotStatevector(label, num_qubits=len(snapshot_register)),
snapshot_register)
QuantumCircuit.snapshot_statevector = snapshot_statevector
|
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
|
aryashah2k
|
# let's print all numbers between 0 and 9
for i in range(10): print(i)
# range(n) represents the list of all numbers from 0 to n-1
# i is the variable to take the values in the range(n) iteratively: 0, 1, ..., 9 in our example
# let's write the same code in two lines
for i in range(10): # do not forget to use colon
print(i)
# the second line is indented
# this means that the command in the second line will be executed inside the for-loop
# any other code executed inside the for-loop must be intented in the same way
#my_code_inside_for-loop_2 will come here
#my_code_inside_for-loop_3 will come here
#my_code_inside_for-loop_4 will come here
# now I am out of the scope of for-loop
#my_code_outside_for-loop_1 will come here
#my_code_outside_for-loop_2 will come here
# let's calculate the summation 1+2+...+10 by using a for-loop
# we use variable total for the total summation
total = 0
for i in range(11): # do not forget to use colon
total = total + i # total is increased by i in each iteration
# alternatively, the same assignment can shortly be written as total += i similarly to languages C, C++, Java, etc.
# now I am out of the scope of for-loop
# let's print the latest value of total
print(total)
# let's calculate the summation 10+12+14+...+44
# we create a list having all numbers in the summation
# for this purpose, this time we will use three parameters in range
total = 0
for j in range(10,45,2): # the range is defined between 10 and 44, and the value of j will be increased by 2 after each iteration
total += j # let's use the shortened version of total = total + j
print(total)
# let's calculate the summation 1+2+4+8+16+...+256
# remark that 256 = 2*2*...*2 (8 times)
total = 0
current_number = 1 # this value will be multiplied by 2 after each iteration
for k in range(9):
total = total + current_number # current_number is 1 at the beginning, and its value will be doubled after each iteration
current_number = 2 * current_number # let's double the value of the current_number for the next iteration
# short version of the same assignment: current_number *= 2 as in the languages C, C++, Java, etc.
# now I am out of the scope of for-loop
# let's print the latest value of total
print(total)
# instead of a range, we can directly use a list
for i in [1,10,100,1000,10000]:
print(i)
# instead of [...], we can also use (...)
# but this time it is a tuple, not a list (keep in your mind that the values in a tuple cannot be changed)
for i in (1,10,100,1000,10000):
print(i)
# let's create a range between 10 and 91 that contains the multiples of 7
for j in range(14,92,7):
# 14 is the first multiple of 7 greater than or equal to 10
# 91 should be in the range, and so we write 92
print(j)
# let's create a range between 11 and 22
for i in range(11,23):
print(i)
# we can also use variables in range
n = 5
for j in range(n,2*n):
print(j) # we will print all numbers in {n,n+1,n+2,...,2n-1}
# we can use a list of strings
for name in ("Asja","Balvis","Fyodor"):
print("Hello",name,":-)")
# any range can be converted to a list
L1 = list(range(10))
print(L1)
L2 = list(range(55,200,11))
print(L2)
#
# your solution is here
#
total1 = 0
total2 = 0
for i in range(3,52,3):
total1 = total1 + i
total2 += i # shorter form
print("The summation is",total1)
print("The summation is",total2)
#
# your solution is here
#
T = 0
current_number = 1
for i in range(9):
T = T + current_number
print("3 to",i,"is",current_number)
current_number = 3 * current_number
print("summation is",T)
# Python has also exponent operator: **
# we can also directly use it
T = 0
for i in range(9):
print("3 to",i,"is",3**i)
T = T + 3 ** i
print("summation is",T)
# let's calculate the summation 1+2+4+8+...+256 by using a while-loop
total = 0
i = 1
#while condition(s):
# your_code1
# your_code2
# your_code3
while i < 257: # this loop iterates as long as i is less than 257
total = total + i
i = i * 2 # i is doubled in each iteration, and so soon it will be greater than 256
print(total)
# remember that we calculated this summation as 511 before
L = [0,1,2,3,4,5,11] # this is a list containing 7 integer values
i = 0
while i in L: # this loop will be iterated as long as i is in L
print(i)
i = i + 1 # the value of i iteratively increased, and so soon it will hit a value not in the list L
# the loop is terminated after i is set to 6, because 6 is not in L
# let's use negation in the condition of while-loop
L = [10] # this list has a single element
i = 0
while i not in L: # this loop will be iterated as long as i is not equal to 10
print(i)
i = i+1 # the value of i will hit 10 after ten iterations
# let's rewrite the same loop by using a direct inequality
i = 0
while i != 10: # "!=" is used for "not equal to" operator
print(i)
i=i+1
# let's rewrite the same loop by using negation of equality
i = 0
while not (i == 10): # "==" is used for "equal to" operator
print(i)
i=i+1
# while-loop seems having more fun :-)
# but we should be more careful when writing the condition(s)!
# summation and n is zero at the beginning
S = 0
n = 0
while S < 1000: # this loop will stop after S exceeds 999 (S = 1000 or S > 1000)
n = n +1
S = S + n
# let's print n and S
print("n =",n," S =",S)
# three examples for the operator "less than or equal to"
#print (4 <= 5)
#print (5 <= 5)
#print (6 <= 5)
# you may comment out the above three lines and see the results by running this cell
#
# your solution is here
#
T = 0
n = 2 # this value iteratively will be first halved and then added to the summation T
how_many_terms = 0
while T<=1.99:
n = n/2 # half the value of n
print("n = ",n)
T = T + n # update the value of T
how_many_terms = how_many_terms + 1
print("T = ",T)
print("how many terms in the summation:",how_many_terms)
# our result says that there should be 8 terms in our summation
# let's calculate the summations of the first seven and eight terms, and verify our results
T7 = 0
n = 2 # this value iteratively will be first halved and then added to the summation
for i in range(7):
n = n/2
print("n =",n)
T7 = T7 + n
print("the summation of the first seven terms is",T7)
T8 = 0
n = 2 # this value iteratively will be first halved and then added to the summation
for i in range(8):
n = n/2
print("n =",n)
T8 = T8 + n
print("the summation of the first eight terms is",T8)
print("(the summation of the first seven terms is",T7,")")
# this is the code for including function randrange into our program
from random import randrange
# randrange(n) picks a number from the list [0,1,2,...,n-1] randomly
#r = randrange(100)
#print(r)
#
# your solution is here
#
from random import randrange
r = 0
attempt = 0
while r != 3: # the loop iterates as long as r is not equal to 3
r = randrange(10) # randomly pick a number
attempt = attempt + 1 # increase the number of attempts by 1
print (attempt,"->",r) # print the number of attempt and the randomly picked number
print("total number of attempt(s) is",attempt)
# here is a schematic example for double nested loops
#for i in range(10):
# your_code1
# your_code2
# while j != 7:
# your_code_3
# your_code_4
#
# your solution is here
#
# be aware of single and double indentions
number_of_execution = 2000 # change this with 200, 2000, 20000, 200000 and reexecute this cell
total_attempts = 0
from random import randrange
for i in range(number_of_execution): # the outer loop iterates number_of_execution times
r = 0
attempt = 0
while r != 3: # the while-loop iterates as long as r is not equal to 3
r = randrange(10) # randomly pick a number
attempt = attempt + 1 # increase the number of attempts by 1
# I am out of scope of while-loop
total_attempts = total_attempts + attempt # update the total number of attempts
# I am out of scope of for-loop
print(number_of_execution,"->",total_attempts/number_of_execution)
# let's use triple nested loops
for number_of_execution in [20,200,2000,20000,200000]: # we will use the same code by indenting all lines by one more level
total_attempts = 0
for i in range(number_of_execution): # the middle loop iterates number_of_execution times
r = 0
attempt = 0
while r != 3: # the while-loop iterates as long as r is not equal to 3
r = randrange(10) # randomly pick a number
attempt = attempt + 1 # increase the number of attempts by 1
# I am out of scope of while-loop
total_attempts = total_attempts + attempt # update the total number of attempts
# I am out of scope of for-loop
print(number_of_execution,"->",total_attempts/number_of_execution)
# you can include 2 million to the list, but you should WAIT for a while to see the result
# can your computer compete with exponential growth?
# if you think "yes", please try 20 million, 200 million, and so on
|
https://github.com/shantomborah/Quantum-Algorithms
|
shantomborah
|
import numpy as np
import matplotlib.pyplot as plt
from qiskit import QuantumCircuit, Aer, execute
from qiskit.circuit import ParameterVector
from qiskit.extensions import HamiltonianGate
from qiskit.visualization import plot_histogram
from qiskit.aqua.components.optimizers import COBYLA
class QAOA:
def __init__(self, clauses, p, num_shots=1024):
# Assign weights and clauses
if isinstance(clauses, dict):
self.clauses = list(clauses.values())
self.weights = list(clauses.keys())
else:
self.clauses = clauses
self.weights = [1] * len(clauses)
# Assign size parameters
self.m = len(self.clauses)
self.n = len(self.clauses[0])
self.p = p
# Assign auxiliary parameters
self.num_shots = num_shots
self.error = -1
# Create variational parameters
self.gamma = ParameterVector('gamma', length=p)
self.beta = ParameterVector('beta', length=p)
self.gamma_val = list(np.random.rand(p))
self.beta_val = list(np.random.rand(p))
# Create hamiltonians and variational circuit
self.C = np.diag([self.cost(z) for z in range(2 ** self.n)])
self.varckt = self.build_varckt()
self.optimize()
def cost(self, z):
# Convert to bitstr
if not isinstance(z, str):
z = format(z, '0' + str(self.n) + 'b')
z: str
# Evaluate C(z)
cost = 0
for i in range(self.m):
s = True
for j in range(self.n):
if self.clauses[i][j] != 'X' and self.clauses[i][j] != z[j]:
s = False
break
if s:
cost += self.weights[i]
# Return output
return cost
def expectation(self, beta=None, gamma=None):
# Resolve default values
if beta is None:
beta = self.beta_val
if gamma is None:
gamma = self.gamma_val
# Evaluate expectation value
circ = self.varckt.bind_parameters({self.beta: beta, self.gamma: gamma})
simulator = Aer.get_backend('qasm_simulator')
result = execute(circ, simulator, shots=self.num_shots).result()
counts = result.get_counts()
expval = sum([self.cost(z) * counts[z] / self.num_shots for z in counts.keys()])
return expval
def optimize(self):
# Define objective function
def objfunc(params):
return -self.expectation(beta=params[0:self.p], gamma=params[self.p:2*self.p])
# Optimize parameters
optimizer = COBYLA(maxiter=1000, tol=0.0001)
params = self.beta_val + self.gamma_val
ret = optimizer.optimize(num_vars=2*self.p, objective_function=objfunc, initial_point=params)
self.beta_val = ret[0][0:self.p]
self.gamma_val = ret[0][self.p:2*self.p]
self.error = ret[1]
return
def build_varckt(self):
# Build variational circuit
circ = QuantumCircuit(self.n)
circ.h(range(self.n))
for i in range(self.p):
eC = QuantumCircuit(self.n, name='$U(C,\\gamma_' + str(i + 1) + ')$')
eC.append(HamiltonianGate(self.C, self.gamma[i]), range(self.n))
eB = QuantumCircuit(self.n, name='$U(B,\\beta_' + str(i + 1) + ')$')
eB.rx(2*self.beta[i], range(self.n))
circ.append(eC.to_gate(), range(self.n))
circ.append(eB.to_gate(), range(self.n))
circ.measure_all()
return circ
def sample(self, shots=None, vis=False):
# Resolve defaults
if shots is None:
shots = self.num_shots
# Sample maximum cost value
circ = self.varckt.bind_parameters({self.beta: self.beta_val, self.gamma: self.gamma_val})
simulator = Aer.get_backend('qasm_simulator')
result = execute(circ, simulator, shots=shots).result()
counts = result.get_counts()
if vis:
plot_histogram(counts, title='Sample Output', bar_labels=False)
plt.subplots_adjust(left=0.15, right=0.85, top=0.9, bottom=0.15)
return max(counts, key=counts.get)
if __name__ == '__main__':
qaoa = QAOA(['10XX0', '11XXX'], 3)
print('Maximized Expectation Value: ' + str(qaoa.expectation()))
print('Sampled Output: ' + qaoa.sample())
qaoa.varckt.draw('mpl').suptitle('Variational Circuit', fontsize=16)
plt.show()
|
https://github.com/iqm-finland/qiskit-on-iqm
|
iqm-finland
|
# -*- 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/Aman-Agrawal01/Quantum-Computing-Qiskit-Tutorial
|
Aman-Agrawal01
|
from qiskit import *
from qiskit.tools.visualization import plot_histogram
%matplotlib inline
qr1 = QuantumRegister(size=2,name='numbers')
qr2 = QuantumRegister(size=1,name='answer-bit')
qr3 = QuantumRegister(size=1,name='carry-bit')
cr1 = ClassicalRegister(size=1,name='answer-cbit')
cr2 = ClassicalRegister(size=1,name='carry-cbit')
circuit = QuantumCircuit(qr1,qr2,qr3,cr1,cr2)
circuit.x(qr1)
circuit.barrier()
circuit.draw(output='mpl')
circuit.cx(control_qubit=qr1[0],target_qubit=qr2)
circuit.cx(control_qubit=qr1[1],target_qubit=qr2)
circuit.draw(output='mpl')
circuit.ccx(control_qubit1=qr1[0],control_qubit2=qr1[1],target_qubit=qr3)
circuit.barrier()
circuit.draw(output='mpl')
circuit.measure(qr2,cr1)
circuit.measure(qr3,cr2)
circuit.draw(output='mpl')
simulator = Aer.get_backend('qasm_simulator')
result = execute(circuit,backend=simulator).result()
plot_histogram(result.get_counts())
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import numpy as np
# Import Qiskit
from qiskit import QuantumCircuit
from qiskit import Aer, transpile
from qiskit.tools.visualization import plot_histogram, plot_state_city
import qiskit.quantum_info as qi
Aer.backends()
simulator = Aer.get_backend('aer_simulator')
# Create circuit
circ = QuantumCircuit(2)
circ.h(0)
circ.cx(0, 1)
circ.measure_all()
# Transpile for simulator
simulator = Aer.get_backend('aer_simulator')
circ = transpile(circ, simulator)
# Run and get counts
result = simulator.run(circ).result()
counts = result.get_counts(circ)
plot_histogram(counts, title='Bell-State counts')
# Run and get memory
result = simulator.run(circ, shots=10, memory=True).result()
memory = result.get_memory(circ)
print(memory)
# Increase shots to reduce sampling variance
shots = 10000
# Stabilizer simulation method
sim_stabilizer = Aer.get_backend('aer_simulator_stabilizer')
job_stabilizer = sim_stabilizer.run(circ, shots=shots)
counts_stabilizer = job_stabilizer.result().get_counts(0)
# Statevector simulation method
sim_statevector = Aer.get_backend('aer_simulator_statevector')
job_statevector = sim_statevector.run(circ, shots=shots)
counts_statevector = job_statevector.result().get_counts(0)
# Density Matrix simulation method
sim_density = Aer.get_backend('aer_simulator_density_matrix')
job_density = sim_density.run(circ, shots=shots)
counts_density = job_density.result().get_counts(0)
# Matrix Product State simulation method
sim_mps = Aer.get_backend('aer_simulator_matrix_product_state')
job_mps = sim_mps.run(circ, shots=shots)
counts_mps = job_mps.result().get_counts(0)
plot_histogram([counts_stabilizer, counts_statevector, counts_density, counts_mps],
title='Counts for different simulation methods',
legend=['stabilizer', 'statevector',
'density_matrix', 'matrix_product_state'])
from qiskit_aer import AerError
# Initialize a GPU backend
# Note that the cloud instance for tutorials does not have a GPU
# so this will raise an exception.
try:
simulator_gpu = Aer.get_backend('aer_simulator')
simulator_gpu.set_options(device='GPU')
except AerError as e:
print(e)
# Configure a single-precision statevector simulator backend
simulator = Aer.get_backend('aer_simulator_statevector')
simulator.set_options(precision='single')
# Run and get counts
result = simulator.run(circ).result()
counts = result.get_counts(circ)
print(counts)
# Construct quantum circuit without measure
circ = QuantumCircuit(2)
circ.h(0)
circ.cx(0, 1)
circ.save_statevector()
# Transpile for simulator
simulator = Aer.get_backend('aer_simulator')
circ = transpile(circ, simulator)
# Run and get statevector
result = simulator.run(circ).result()
statevector = result.get_statevector(circ)
plot_state_city(statevector, title='Bell state')
# Construct quantum circuit without measure
circ = QuantumCircuit(2)
circ.h(0)
circ.cx(0, 1)
circ.save_unitary()
# Transpile for simulator
simulator = Aer.get_backend('aer_simulator')
circ = transpile(circ, simulator)
# Run and get unitary
result = simulator.run(circ).result()
unitary = result.get_unitary(circ)
print("Circuit unitary:\n", np.asarray(unitary).round(5))
# Construct quantum circuit without measure
steps = 5
circ = QuantumCircuit(1)
for i in range(steps):
circ.save_statevector(label=f'psi_{i}')
circ.rx(i * np.pi / steps, 0)
circ.save_statevector(label=f'psi_{steps}')
# Transpile for simulator
simulator = Aer.get_backend('aer_simulator')
circ = transpile(circ, simulator)
# Run and get saved data
result = simulator.run(circ).result()
data = result.data(0)
data
# Generate a random statevector
num_qubits = 2
psi = qi.random_statevector(2 ** num_qubits, seed=100)
# Set initial state to generated statevector
circ = QuantumCircuit(num_qubits)
circ.set_statevector(psi)
circ.save_state()
# Transpile for simulator
simulator = Aer.get_backend('aer_simulator')
circ = transpile(circ, simulator)
# Run and get saved data
result = simulator.run(circ).result()
result.data(0)
# Use initilize instruction to set initial state
circ = QuantumCircuit(num_qubits)
circ.initialize(psi, range(num_qubits))
circ.save_state()
# Transpile for simulator
simulator = Aer.get_backend('aer_simulator')
circ = transpile(circ, simulator)
# Run and get result data
result = simulator.run(circ).result()
result.data(0)
num_qubits = 2
rho = qi.random_density_matrix(2 ** num_qubits, seed=100)
circ = QuantumCircuit(num_qubits)
circ.set_density_matrix(rho)
circ.save_state()
# Transpile for simulator
simulator = Aer.get_backend('aer_simulator')
circ = transpile(circ, simulator)
# Run and get saved data
result = simulator.run(circ).result()
result.data(0)
# Generate a random Clifford C
num_qubits = 2
stab = qi.random_clifford(num_qubits, seed=100)
# Set initial state to stabilizer state C|0>
circ = QuantumCircuit(num_qubits)
circ.set_stabilizer(stab)
circ.save_state()
# Transpile for simulator
simulator = Aer.get_backend('aer_simulator')
circ = transpile(circ, simulator)
# Run and get saved data
result = simulator.run(circ).result()
result.data(0)
# Generate a random unitary
num_qubits = 2
unitary = qi.random_unitary(2 ** num_qubits, seed=100)
# Set initial state to unitary
circ = QuantumCircuit(num_qubits)
circ.set_unitary(unitary)
circ.save_state()
# Transpile for simulator
simulator = Aer.get_backend('aer_simulator')
circ = transpile(circ, simulator)
# Run and get saved data
result = simulator.run(circ).result()
result.data(0)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/0tt3r/QuaC-qiskit
|
0tt3r
|
# -*- coding: utf-8 -*-
"""This example demonstrates the applying measurement error to a GHZ circuit in the
plugin. Additionally, the use of multiple classical registers is demonstrated.
"""
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute
from qiskit.visualization import plot_histogram
from quac_qiskit import Quac
from quac_qiskit.format import quac_time_qasm_transpiler
import matplotlib.pyplot as plt
if __name__ == '__main__':
# Note: measurement errors are included by setting the "meas" option to True
# Qubit P(0 | 1) P(1 | 0)
# 0 0.10799999999999998 0.024
# 1 0.039000000000000035 0.004
# 2 0.026 0.009000000000000008
# 3 0.03400000000000003 0.005
# 4 0.135 0.019
print(Quac.backends())
simulator = Quac.get_backend('fake_bogota_counts_simulator', t1=False, t2=False, meas=True, zz=True)
# Build the GhZ circuit over five qubits
quantum_register = QuantumRegister(4, "qreg")
classical_register1 = ClassicalRegister(2, "creg1")
classical_register2 = ClassicalRegister(2, "creg2")
ghz_circ = QuantumCircuit()
ghz_circ.add_register(quantum_register)
ghz_circ.add_register(classical_register1)
ghz_circ.add_register(classical_register2)
ghz_circ.h(0)
for qubit in range(1, 4):
ghz_circ.cx(qubit - 1, qubit)
ghz_circ.measure(quantum_register[0], classical_register1[0])
ghz_circ.measure(quantum_register[1], classical_register1[1])
ghz_circ.measure(quantum_register[2], classical_register2[0])
ghz_circ.measure(quantum_register[3], classical_register2[1])
quac_job = execute(ghz_circ, simulator, shots=1000)
# print(quac_job.status())
print(f"Frequency results: {quac_job.result().get_counts()}")
plot_histogram(quac_job.result().get_counts())
plt.title("GHZ States")
plt.show()
print("TIMEQASM of GHZ Circuit:")
print(quac_time_qasm_transpiler(ghz_circ, simulator))
|
https://github.com/HuangJunye/Qiskit-for-GameDev
|
HuangJunye
|
import sys
sys.path.append('/Users/kirais/Documents/GitHub/Qiskit-for-GameDev/pygame/')
from qgame import CircuitGridModel, CircuitGridNode, MeasurementsHistogram
from qgame import circuit_node_types as node_types
from qiskit import QuantumCircuit
circuit_grid_model = CircuitGridModel(4, 18)
circuit_grid_model.set_node(0, 0, CircuitGridNode(node_types.ID))
circuit = circuit_grid_model.compute_circuit()
print(circuit_grid_model)
cx_gate = CircuitGridNode(node_types.CX, 1, ctrl_a=0)
circuit_grid_model.set_node(1,1,cx_gate)
print(circuit_grid_model)
qasm_str = circuit_grid_model.create_qasm_for_circuit()
qasm_str = 'OPENQASM 2.0;include "qelib1.inc";qreg q[4];creg c[4];id q;id q[0];rx(pi) q[1];'
circuit = QuantumCircuit.from_qasm_str(qasm_str)
circuit.draw()
from qiskit import BasicAer, QuantumRegister, ClassicalRegister, QuantumCircuit, execute
backend_sim = BasicAer.get_backend('qasm_simulator')
qr = QuantumRegister(circuit.width(), 'q')
cr = ClassicalRegister(circuit.width(), 'c')
meas_circ = QuantumCircuit(qr, cr)
meas_circ.barrier(qr)
meas_circ.measure(qr, cr)
circuit.draw()
circuit.n_qubits
meas_circ.draw()
complete_circuit = circuit + meas_circ
|
https://github.com/SanNare/qiskit-notebooks
|
SanNare
|
from qiskit import QuantumCircuit
from qiskit.quantum_info import Statevector
from qiskit.tools.visualization import plot_bloch_multivector, plot_histogram
def logicalAnd(circuit,input_qubits,output_qubit):
circuit.mcx(input_qubits,output_qubit)
def logicalOr(circuit,input_qubits,output_qubit):
for i in input_qubits:
circuit.x(i)
circuit.x(output_qubit)
circuit.mcx(input_qubits,output_qubit)
for i in input_qubits:
circuit.x(i)
# circuit = QuantumCircuit(3)
# logicalAnd(circuit,[0,1],2)
# logicalOr(circuit,[0,1],2)
# %matplotlib inline
# circuit.draw('mpl')
#implementing the function xy + x'y'
circuit = QuantumCircuit(5,1)
#change input by commenting/uncommenting these two lines
circuit.x(0)
# circuit.x(1)
logicalAnd(circuit,[0,1],2)
circuit.x(0)
circuit.x(1)
logicalAnd(circuit,[0,1],3)
logicalOr(circuit,[2,3],4)
circuit.measure(4,0)
%matplotlib inline
circuit.draw(output = 'mpl')
#to run this, remove the classical register and measurement
sv = Statevector.from_label('11000')
nsv = sv.evolve(circuit)
plot_bloch_multivector(nsv.data)
from qiskit import Aer, execute
simulator = Aer.get_backend('qasm_simulator')
result = execute(circuit, simulator, shots=100).result()
counts = result.get_counts(circuit)
print(counts)
plot_histogram(counts)
#implementation of circuit for finding a boolean function in DNF
#encoding used: x + yz => [[1,0,0],[0,1,1]], xy'z + y'z' => [[1,-1,-1],[0,-1,-1]]
def DNF(minterms):
n = len(minterms[0])
m = len(minterms)
circuit = QuantumCircuit(n+m+1,1)
o = n
for t in minterms:
inp = []
for i in range(0,n):
if t[i] == -1:
circuit.x(i)
inp.append(i)
elif t[i] == 1:
inp.append(i)
logicalAnd(circuit,inp,o)
for i in range(0,n):
if t[i] == -1:
circuit.x(i)
o = o+1
logicalOr(circuit,list(range(n,n+m)),n+m)
circuit.measure(n+m,0)
return circuit
circuit = QuantumCircuit(6,1)
#comment/uncomment to modify input
circuit.x(0)
circuit.x(1)
#circuit.x(2)
circuit.append(DNF([[1,0,0],[0,-1,-1]]),[0,1,2,3,4,5],[0]) #f = x + y'z'
circuit.draw(output = 'text')
from qiskit import Aer, execute
simulator = Aer.get_backend('qasm_simulator')
result = execute(circuit, simulator, shots=100).result()
counts = result.get_counts(circuit)
print(counts)
plot_histogram(counts)
|
https://github.com/ctuning/ck-qiskit
|
ctuning
|
#--------------------------------------------------------------------------------------------------------------
# This module contains control unitaries that can be used while developing circuits on IBM QExperience
#--------------------------------------------------------------------------------------------------------------
#--------------------------------------------------------------------------------------------------------------
# Import necessary modules
#--------------------------------------------------------------------------------------------------------------
from qiskit import QuantumProgram
import Qconfig
import Basic_gates
# TODO make it more generalized
#--------------------------------------------------------------------------------------------------------------
# The control unitary for 2mod15 on 4 quantum qubits
# Input : Quantum program object, the Circuit name and the quantum register name, and the
# control bit number where the connections are supposed to be made
# Output : Quantum_program_object with the relevant connections
# Circuit implemented - CSwap(Q[3],Q[2])->CSwap(Q[2],Q[1])->CSwap(Q[1],Q[0])
#--------------------------------------------------------------------------------------------------------------
def C_2mod15(Quantum_program_object,Circuit_name,Quantum_register_name,Control_bit_number):
# Get the circuit and the quantum register by name
qc = Quantum_program_object.get_circuit(Circuit_name)
qr = Quantum_program_object.get_quantum_register(Quantum_register_name)
Control_bit_number = Control_bit_number
# Implement controlled swap on qr[3] and qr[2]
Basic_gates.CSWAP(Quantum_program_object,Circuit_name,Quantum_register_name,Control_bit_number,[3,2])
# Implement controlled swap on qr[2] and qr[1]
Basic_gates.CSWAP(Quantum_program_object,Circuit_name,Quantum_register_name,Control_bit_number,[2,1])
# Implement controlled swap on qr[1] and qr[0]
Basic_gates.CSWAP(Quantum_program_object,Circuit_name,Quantum_register_name,Control_bit_number,[1,0])
# Return the program object
return Quantum_program_object
#--------------------------------------------------------------------------------------------------------------
# The control unitary for 7mod15 on 4 quantum qubits
# Input : Quantum program object, the Circuit name and the quantum register name, and the
# control bit number where the connections are supposed to be made
# Output : Quantum_program_object with the relevant connections
# Circuit implemented - CSwap(Q[1],Q[0])->CSwap(Q[1],Q[2])->CSwap(Q[2],Q[3])->CX on all 4 qubits
#--------------------------------------------------------------------------------------------------------------
def C_7mod15(Quantum_program_object,Circuit_name,Quantum_register_name,Control_bit_number):
# Get the circuit and the quantum register by name
qc = Quantum_program_object.get_circuit(Circuit_name)
qr = Quantum_program_object.get_quantum_register(Quantum_register_name)
Control_bit_number = Control_bit_number
# Implement controlled swap on qr[1] and qr[0]
Basic_gates.CSWAP(Quantum_program_object,Circuit_name,Quantum_register_name,Control_bit_number,[1,0])
# Implement controlled swap on qr[2] and qr[1]
Basic_gates.CSWAP(Quantum_program_object,Circuit_name,Quantum_register_name,Control_bit_number,[2,1])
# Implement controlled swap on qr[3] and qr[2]
Basic_gates.CSWAP(Quantum_program_object,Circuit_name,Quantum_register_name,Control_bit_number,[3,2])
# Implement CX on all four qubits
qc.cx(Control_bit_number,qr[3])
qc.cx(Control_bit_number,qr[2])
qc.cx(Control_bit_number,qr[1])
qc.cx(Control_bit_number,qr[0])
# Return the program object
return Quantum_program_object
#--------------------------------------------------------------------------------------------------------------
# The control unitary for 8mod15 on 4 quantum qubits
# Input : Quantum program object, the Circuit name and the quantum register name, and the
# control bit number where the connections are supposed to be made
# Output : Quantum_program_object with the relevant connections
# Circuit implemented - CSwap(Q[1],Q[0])->CSwap(Q[1],Q[2])->CSwap(Q[2],Q[3])
#--------------------------------------------------------------------------------------------------------------
def C_8mod15(Quantum_program_object,Circuit_name,Quantum_register_name,Control_bit_number):
# Get the circuit and the quantum register by name
qc = Quantum_program_object.get_circuit(Circuit_name)
qr = Quantum_program_object.get_quantum_register(Quantum_register_name)
Control_bit_number = Control_bit_number
# Implement controlled swap on qr[1] and qr[0]
Basic_gates.CSWAP(Quantum_program_object,Circuit_name,Quantum_register_name,Control_bit_number,[1,0])
# Implement controlled swap on qr[2] and qr[1]
Basic_gates.CSWAP(Quantum_program_object,Circuit_name,Quantum_register_name,Control_bit_number,[2,1])
# Implement controlled swap on qr[3] and qr[2]
Basic_gates.CSWAP(Quantum_program_object,Circuit_name,Quantum_register_name,Control_bit_number,[3,2])
# Return the program object
return Quantum_program_object
#--------------------------------------------------------------------------------------------------------------
# The control unitary for 11mod15 on 4 quantum qubits
# Input : Quantum program object, the Circuit name and the quantum register name, and the
# control bit number where the connections are supposed to be made
# Output : Quantum_program_object with the relevant connections
# Circuit implemented - CSwap(Q[2],Q[0])->CSwap(Q[3],Q[1])->CX on all 4 qubits
#--------------------------------------------------------------------------------------------------------------
def C_11mod15(Quantum_program_object,Circuit_name,Quantum_register_name,Control_bit_number):
# Get the circuit and the quantum register by name
qc = Quantum_program_object.get_circuit(Circuit_name)
qr = Quantum_program_object.get_quantum_register(Quantum_register_name)
Control_bit_number = Control_bit_number
# Implement controlled swap on qr[2] and qr[0]
Basic_gates.CSWAP(Quantum_program_object,Circuit_name,Quantum_register_name,Control_bit_number,[2,0])
# Implement controlled swap on qr[3] and qr[1]
Basic_gates.CSWAP(Quantum_program_object,Circuit_name,Quantum_register_name,Control_bit_number,[3,1])
# Implement CX on all four qubits
qc.cx(Control_bit_number,qr[3])
qc.cx(Control_bit_number,qr[2])
qc.cx(Control_bit_number,qr[1])
qc.cx(Control_bit_number,qr[0])
# Return the program object
return Quantum_program_object
#--------------------------------------------------------------------------------------------------------------
# The control unitary for 13mod15 on 4 quantum qubits
# Input : Quantum program object, the Circuit name and the quantum register name, and the
# control bit number where the connections are supposed to be made
# Output : Quantum_program_object with the relevant connections
# Circuit implemented - CSwap(Q[3],Q[2])->CSwap(Q[2],Q[1])->CSwap(Q[1],Q[0])->CX on all 4 qubits
#--------------------------------------------------------------------------------------------------------------
def C_13mod15(Quantum_program_object,Circuit_name,Quantum_register_name,Control_bit_number):
# Get the circuit and the quantum register by name
qc = Quantum_program_object.get_circuit(Circuit_name)
qr = Quantum_program_object.get_quantum_register(Quantum_register_name)
Control_bit_number = Control_bit_number
# Implement controlled swap on qr[3] and qr[2]
Basic_gates.CSWAP(Quantum_program_object,Circuit_name,Quantum_register_name,Control_bit_number,[3,2])
# Implement controlled swap on qr[2] and qr[1]
Basic_gates.CSWAP(Quantum_program_object,Circuit_name,Quantum_register_name,Control_bit_number,[2,1])
# Implement controlled swap on qr[1] and qr[0]
Basic_gates.CSWAP(Quantum_program_object,Circuit_name,Quantum_register_name,Control_bit_number,[1,0])
# Implement CX on all four qubits
qc.cx(Control_bit_number,qr[3])
qc.cx(Control_bit_number,qr[2])
qc.cx(Control_bit_number,qr[1])
qc.cx(Control_bit_number,qr[0])
# Return the program object
return Quantum_program_object
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import execute, pulse
d0 = pulse.DriveChannel(0)
with pulse.build() as pulse_prog:
pulse.play(pulse.Constant(100, 1.0), d0)
pulse_prog.draw()
|
https://github.com/qiskit-community/qiskit-qcgpu-provider
|
qiskit-community
|
import matplotlib.pyplot as ply
%matplotlib inline
import networkx as nx
import numpy as np
from qiskit_aqua.translators.ising import tsp
from qiskit_aqua.input import EnergyInput
from qiskit_aqua import run_algorithm
from qiskit_qcgpu_provider import QCGPUProvider
locations = 3
problem = tsp.random_tsp(locations)
positions = {k: v for k, v in enumerate(problem.coord)}
G = nx.Graph()
G.add_nodes_from(np.arange(0, locations, 1))
nx.draw(G, with_labels=True, pos=positions)
best_distance, best_order = brute_force(problem.w, problem.dim)
draw(G, best_order, positions)
operator, offset = tsp.get_tsp_qubitops(problem)
algorithm_input = EnergyInput(operator)
algorithm_parameters = {
'problem': { 'name': 'ising', 'random_seed': 23 },
'algorithm': { 'name': 'VQE', 'operator_mode': 'matrix' },
'optimizer': { 'name': 'SPSA', 'max_trials':100 },
'variational_form': {'name': 'RY', 'depth': 5, 'entanglement': 'linear'}
}
backend = QCGPUProvider().get_backend('statevector_simulator')
%time result_qiskit = run_algorithm(algorithm_parameters, algorithm_input)
%time result = run_algorithm(algorithm_parameters, algorithm_input, backend=backend)
#print('tsp objective:', result['energy'] + offset)
x = tsp.sample_most_likely(result['eigvecs'][0])
print('feasible:', tsp.tsp_feasible(x))
z = tsp.get_tsp_solution(x)
print('solution:', z)
print('solution objective:', tsp.tsp_value(z, problem.w))
draw(G, z, positions)
# Utitlity Functions
def draw(G, order, positions):
G2 = G.copy()
n = len(order)
for i in range(n):
j = (i + 1) % n
G2.add_edge(order[i], order[j])
nx.draw(G2, pos=positions, with_labels=True)
# Classically solve the problem using a brute-force method
from itertools import permutations
def brute_force(weights, N):
a = list(permutations(range(1, N)))
best_distance = None
for i in a:
distance = 0
pre_j = 0
for j in i:
distance += weights[j, pre_j]
pre_j = j
distance += weights[pre_j, 0]
order = (0,) + i
if best_distance is None or distance < best_distance:
best_order = order
best_distance = distance
return best_distance, best_order
import warnings
warnings.filterwarnings('ignore')
|
https://github.com/quantum-kittens/quantum-computing-basics
|
quantum-kittens
|
from qiskit import *
from qiskit.visualization import plot_histogram
%config InlineBackend.figure_format = 'svg'
qc_ab = QuantumCircuit(6,6) #Create a quantum circuit with 6 qubits and 6 classical bits
##ENCODE BIT STRING
#The random bit sequence Alice needs to encode is: 100100, so the first and fourth qubits are flipped from |0> -> |1>
qc_ab.x(0) #The first qubit is indexed at 0, following Python being zero-indexed. From now on it'll be referred to as qubit 0 and so on.
qc_ab.x(3)
qc_ab.barrier()
##ALICE CHOOSES
#Alice randomly chooses to apply an X or an H.
#Note that since the state is already either a |0> or |1>, a Z essentially leaves the qubit state unchanged. But let's write it anyway, shall we?
qc_ab.h(0) # or qc.z(0) # switch these based on your own choice
qc_ab.z(1) # or qc.h(1)
qc_ab.z(2) # or qc.h(2)
qc_ab.h(3) # or qc.z(3)
qc_ab.z(4) # or qc.h(4)
qc_ab.h(5) # or qc.z(5)
qc_ab.barrier()
##BOB CHOOSES
#Alice sends the qubit sequence to Bob, and Bob randomly chooses measurements
qc_ab.h(0) # or qc.z(0) # switch these based on your own choice
qc_ab.z(1) # or qc.h(1)
qc_ab.h(2) # or qc.z(2)
qc_ab.h(3) # or qc.z(3)
qc_ab.z(4) # or qc.h(4)
qc_ab.z(5) # or qc.h(5)
qc_ab.barrier()
##PUBLICIZE CHOICES
#Alice and Bob publicize their choices and only retain those for which their choices match. In this case: qubits 0,1,3,4.
#Note: technically Bob performs the measurement BEFORE publicizing, but we're combining the two here since no one is actually communicating.
qc_ab.measure(0,0)
qc_ab.measure(1,1)
qc_ab.measure(3,3)
qc_ab.measure(4,4)
#qc_ab.measure(2,2) #come back to uncomment these to see what happens to the results after you've run this once
#qc_ab.measure(5,5)
qc_ab.draw(output='mpl') #let's see what this circuit looks like!
##EXECUTE
result = execute(qc_ab, Aer.get_backend('qasm_simulator')).result().get_counts() #We're only making use of the simulator. Refer to [2] to see how you can run this on a real quantum computer.
plot_histogram(result)
#Same situation but now with sneaky Eve
qc_aeb = QuantumCircuit(6,6) #Create a quantum circuit with 6 qubits and 6 classical bits
##ENCODE BIT STRING
qc_aeb.x(0)
qc_aeb.x(3)
qc_aeb.barrier()
##ALICE CHOOSES
qc_aeb.h(0)
qc_aeb.z(1)
qc_aeb.z(2)
qc_aeb.h(3)
qc_aeb.z(4)
qc_aeb.h(5)
qc_aeb.barrier()
##EVE CHOOSES
qc_aeb.h(0) #play around with these to see how many states with non-zero probabilities show up at the end for a fixed set of Alice's and Bob's choices
qc_aeb.z(1)
qc_aeb.h(2)
qc_aeb.h(3)
qc_aeb.z(4)
qc_aeb.z(5)
qc_aeb.barrier()
##BOB CHOOSES
qc_aeb.h(0)
qc_aeb.z(1)
qc_aeb.h(2)
qc_aeb.h(3)
qc_aeb.z(4)
qc_aeb.z(5)
qc_aeb.barrier()
##PUBLICIZE CHOICES
qc_aeb.measure(0,0)
qc_aeb.measure(1,1)
qc_aeb.measure(3,3)
qc_aeb.measure(4,4)
#qc_aeb.measure(2,2) #come back to uncomment these to see what happens to the results after you've run this once
#qc_aeb.measure(5,5)
qc_aeb.draw(output='mpl') #let's see what this circuit looks like!
##EXECUTE
result = execute(qc_aeb, Aer.get_backend('qasm_simulator')).result().get_counts()
plot_histogram(result)
|
https://github.com/ElePT/qiskit-algorithms-test
|
ElePT
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2018, 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.
"""Test the quantum amplitude estimation algorithm."""
import unittest
from test.python.algorithms import QiskitAlgorithmsTestCase
import numpy as np
from ddt import ddt, idata, data, unpack
from qiskit import QuantumRegister, QuantumCircuit, BasicAer
from qiskit.circuit.library import QFT, GroverOperator
from qiskit.utils import QuantumInstance
from qiskit_algorithms import (
AmplitudeEstimation,
MaximumLikelihoodAmplitudeEstimation,
IterativeAmplitudeEstimation,
FasterAmplitudeEstimation,
EstimationProblem,
)
from qiskit.quantum_info import Operator, Statevector
from qiskit.primitives import Sampler
class BernoulliStateIn(QuantumCircuit):
"""A circuit preparing sqrt(1 - p)|0> + sqrt(p)|1>."""
def __init__(self, probability):
super().__init__(1)
angle = 2 * np.arcsin(np.sqrt(probability))
self.ry(angle, 0)
class BernoulliGrover(QuantumCircuit):
"""The Grover operator corresponding to the Bernoulli A operator."""
def __init__(self, probability):
super().__init__(1, global_phase=np.pi)
self.angle = 2 * np.arcsin(np.sqrt(probability))
self.ry(2 * self.angle, 0)
def power(self, power, matrix_power=False):
if matrix_power:
return super().power(power, True)
powered = QuantumCircuit(1)
powered.ry(power * 2 * self.angle, 0)
return powered
class SineIntegral(QuantumCircuit):
r"""Construct the A operator to approximate the integral
\int_0^1 \sin^2(x) d x
with a specified number of qubits.
"""
def __init__(self, num_qubits):
qr_state = QuantumRegister(num_qubits, "state")
qr_objective = QuantumRegister(1, "obj")
super().__init__(qr_state, qr_objective)
# prepare 1/sqrt{2^n} sum_x |x>_n
self.h(qr_state)
# apply the sine/cosine term
self.ry(2 * 1 / 2 / 2**num_qubits, qr_objective[0])
for i, qubit in enumerate(qr_state):
self.cry(2 * 2**i / 2**num_qubits, qubit, qr_objective[0])
@ddt
class TestBernoulli(QiskitAlgorithmsTestCase):
"""Tests based on the Bernoulli A operator.
This class tests
* the estimation result
* the constructed circuits
"""
def setUp(self):
super().setUp()
with self.assertWarns(DeprecationWarning):
self._statevector = QuantumInstance(
backend=BasicAer.get_backend("statevector_simulator"),
seed_simulator=2,
seed_transpiler=2,
)
self._sampler = Sampler(options={"seed": 2})
def qasm(shots=100):
with self.assertWarns(DeprecationWarning):
qi = QuantumInstance(
backend=BasicAer.get_backend("qasm_simulator"),
shots=shots,
seed_simulator=2,
seed_transpiler=2,
)
return qi
self._qasm = qasm
def sampler_shots(shots=100):
return Sampler(options={"shots": shots, "seed": 2})
self._sampler_shots = sampler_shots
@idata(
[
[0.2, AmplitudeEstimation(2), {"estimation": 0.5, "mle": 0.2}],
[0.49, AmplitudeEstimation(3), {"estimation": 0.5, "mle": 0.49}],
[0.2, MaximumLikelihoodAmplitudeEstimation([0, 1, 2]), {"estimation": 0.2}],
[0.49, MaximumLikelihoodAmplitudeEstimation(3), {"estimation": 0.49}],
[0.2, IterativeAmplitudeEstimation(0.1, 0.1), {"estimation": 0.2}],
[0.49, IterativeAmplitudeEstimation(0.001, 0.01), {"estimation": 0.49}],
[0.2, FasterAmplitudeEstimation(0.1, 3, rescale=False), {"estimation": 0.2}],
[0.12, FasterAmplitudeEstimation(0.1, 2, rescale=False), {"estimation": 0.12}],
]
)
@unpack
def test_statevector(self, prob, qae, expect):
"""statevector test"""
problem = EstimationProblem(BernoulliStateIn(prob), 0, BernoulliGrover(prob))
with self.assertWarns(DeprecationWarning):
qae.quantum_instance = self._statevector
result = qae.estimate(problem)
self._statevector.reset_execution_results()
for key, value in expect.items():
self.assertAlmostEqual(
value, getattr(result, key), places=3, msg=f"estimate `{key}` failed"
)
@idata(
[
[0.2, AmplitudeEstimation(2), {"estimation": 0.5, "mle": 0.2}],
[0.49, AmplitudeEstimation(3), {"estimation": 0.5, "mle": 0.49}],
[0.2, MaximumLikelihoodAmplitudeEstimation([0, 1, 2]), {"estimation": 0.2}],
[0.49, MaximumLikelihoodAmplitudeEstimation(3), {"estimation": 0.49}],
[0.2, IterativeAmplitudeEstimation(0.1, 0.1), {"estimation": 0.2}],
[0.49, IterativeAmplitudeEstimation(0.001, 0.01), {"estimation": 0.49}],
[0.2, FasterAmplitudeEstimation(0.1, 3, rescale=False), {"estimation": 0.199}],
[0.12, FasterAmplitudeEstimation(0.1, 2, rescale=False), {"estimation": 0.12}],
]
)
@unpack
def test_sampler(self, prob, qae, expect):
"""sampler test"""
qae.sampler = self._sampler
problem = EstimationProblem(BernoulliStateIn(prob), 0, BernoulliGrover(prob))
result = qae.estimate(problem)
for key, value in expect.items():
self.assertAlmostEqual(
value, getattr(result, key), places=3, msg=f"estimate `{key}` failed"
)
@idata(
[
[0.2, 100, AmplitudeEstimation(4), {"estimation": 0.14644, "mle": 0.193888}],
[0.0, 1000, AmplitudeEstimation(2), {"estimation": 0.0, "mle": 0.0}],
[
0.2,
100,
MaximumLikelihoodAmplitudeEstimation([0, 1, 2, 4, 8]),
{"estimation": 0.199606},
],
[0.8, 10, IterativeAmplitudeEstimation(0.1, 0.05), {"estimation": 0.811711}],
[0.2, 1000, FasterAmplitudeEstimation(0.1, 3, rescale=False), {"estimation": 0.198640}],
[
0.12,
100,
FasterAmplitudeEstimation(0.01, 3, rescale=False),
{"estimation": 0.119037},
],
]
)
@unpack
def test_qasm(self, prob, shots, qae, expect):
"""qasm test"""
with self.assertWarns(DeprecationWarning):
qae.quantum_instance = self._qasm(shots)
problem = EstimationProblem(BernoulliStateIn(prob), [0], BernoulliGrover(prob))
result = qae.estimate(problem)
for key, value in expect.items():
self.assertAlmostEqual(
value, getattr(result, key), places=3, msg=f"estimate `{key}` failed"
)
@idata(
[
[0.2, 100, AmplitudeEstimation(4), {"estimation": 0.14644, "mle": 0.198783}],
[0.0, 1000, AmplitudeEstimation(2), {"estimation": 0.0, "mle": 0.0}],
[
0.2,
100,
MaximumLikelihoodAmplitudeEstimation([0, 1, 2, 4, 8]),
{"estimation": 0.200308},
],
[0.8, 10, IterativeAmplitudeEstimation(0.1, 0.05), {"estimation": 0.811711}],
[0.2, 1000, FasterAmplitudeEstimation(0.1, 3, rescale=False), {"estimation": 0.198640}],
[
0.12,
100,
FasterAmplitudeEstimation(0.01, 3, rescale=False),
{"estimation": 0.120017},
],
]
)
@unpack
def test_sampler_with_shots(self, prob, shots, qae, expect):
"""sampler with shots test"""
qae.sampler = self._sampler_shots(shots)
problem = EstimationProblem(BernoulliStateIn(prob), [0], BernoulliGrover(prob))
result = qae.estimate(problem)
for key, value in expect.items():
self.assertAlmostEqual(
value, getattr(result, key), places=3, msg=f"estimate `{key}` failed"
)
@data(True, False)
def test_qae_circuit(self, efficient_circuit):
"""Test circuits resulting from canonical amplitude estimation.
Build the circuit manually and from the algorithm and compare the resulting unitaries.
"""
prob = 0.5
problem = EstimationProblem(BernoulliStateIn(prob), objective_qubits=[0])
for m in [2, 5]:
qae = AmplitudeEstimation(m)
angle = 2 * np.arcsin(np.sqrt(prob))
# manually set up the inefficient AE circuit
qr_eval = QuantumRegister(m, "a")
qr_objective = QuantumRegister(1, "q")
circuit = QuantumCircuit(qr_eval, qr_objective)
# initial Hadamard gates
for i in range(m):
circuit.h(qr_eval[i])
# A operator
circuit.ry(angle, qr_objective)
if efficient_circuit:
qae.grover_operator = BernoulliGrover(prob)
for power in range(m):
circuit.cry(2 * 2**power * angle, qr_eval[power], qr_objective[0])
else:
oracle = QuantumCircuit(1)
oracle.z(0)
state_preparation = QuantumCircuit(1)
state_preparation.ry(angle, 0)
grover_op = GroverOperator(oracle, state_preparation)
for power in range(m):
circuit.compose(
grover_op.power(2**power).control(),
qubits=[qr_eval[power], qr_objective[0]],
inplace=True,
)
# fourier transform
iqft = QFT(m, do_swaps=False).inverse().reverse_bits()
circuit.append(iqft.to_instruction(), qr_eval)
actual_circuit = qae.construct_circuit(problem, measurement=False)
self.assertEqual(Operator(circuit), Operator(actual_circuit))
@data(True, False)
def test_iqae_circuits(self, efficient_circuit):
"""Test circuits resulting from iterative amplitude estimation.
Build the circuit manually and from the algorithm and compare the resulting unitaries.
"""
prob = 0.5
problem = EstimationProblem(BernoulliStateIn(prob), objective_qubits=[0])
for k in [2, 5]:
qae = IterativeAmplitudeEstimation(0.01, 0.05)
angle = 2 * np.arcsin(np.sqrt(prob))
# manually set up the inefficient AE circuit
q_objective = QuantumRegister(1, "q")
circuit = QuantumCircuit(q_objective)
# A operator
circuit.ry(angle, q_objective)
if efficient_circuit:
qae.grover_operator = BernoulliGrover(prob)
circuit.ry(2 * k * angle, q_objective[0])
else:
oracle = QuantumCircuit(1)
oracle.z(0)
state_preparation = QuantumCircuit(1)
state_preparation.ry(angle, 0)
grover_op = GroverOperator(oracle, state_preparation)
for _ in range(k):
circuit.compose(grover_op, inplace=True)
actual_circuit = qae.construct_circuit(problem, k, measurement=False)
self.assertEqual(Operator(circuit), Operator(actual_circuit))
@data(True, False)
def test_mlae_circuits(self, efficient_circuit):
"""Test the circuits constructed for MLAE"""
prob = 0.5
problem = EstimationProblem(BernoulliStateIn(prob), objective_qubits=[0])
for k in [2, 5]:
qae = MaximumLikelihoodAmplitudeEstimation(k)
angle = 2 * np.arcsin(np.sqrt(prob))
# compute all the circuits used for MLAE
circuits = []
# 0th power
q_objective = QuantumRegister(1, "q")
circuit = QuantumCircuit(q_objective)
circuit.ry(angle, q_objective)
circuits += [circuit]
# powers of 2
for power in range(k):
q_objective = QuantumRegister(1, "q")
circuit = QuantumCircuit(q_objective)
# A operator
circuit.ry(angle, q_objective)
# Q^(2^j) operator
if efficient_circuit:
qae.grover_operator = BernoulliGrover(prob)
circuit.ry(2 * 2**power * angle, q_objective[0])
else:
oracle = QuantumCircuit(1)
oracle.z(0)
state_preparation = QuantumCircuit(1)
state_preparation.ry(angle, 0)
grover_op = GroverOperator(oracle, state_preparation)
for _ in range(2**power):
circuit.compose(grover_op, inplace=True)
circuits += [circuit]
actual_circuits = qae.construct_circuits(problem, measurement=False)
for actual, expected in zip(actual_circuits, circuits):
self.assertEqual(Operator(actual), Operator(expected))
@ddt
class TestSineIntegral(QiskitAlgorithmsTestCase):
"""Tests based on the A operator to integrate sin^2(x).
This class tests
* the estimation result
* the confidence intervals
"""
def setUp(self):
super().setUp()
with self.assertWarns(DeprecationWarning):
self._statevector = QuantumInstance(
backend=BasicAer.get_backend("statevector_simulator"),
seed_simulator=123,
seed_transpiler=41,
)
self._sampler = Sampler(options={"seed": 123})
def qasm(shots=100):
with self.assertWarns(DeprecationWarning):
qi = QuantumInstance(
backend=BasicAer.get_backend("qasm_simulator"),
shots=shots,
seed_simulator=7192,
seed_transpiler=90000,
)
return qi
self._qasm = qasm
def sampler_shots(shots=100):
return Sampler(options={"shots": shots, "seed": 7192})
self._sampler_shots = sampler_shots
@idata(
[
[2, AmplitudeEstimation(2), {"estimation": 0.5, "mle": 0.270290}],
[4, MaximumLikelihoodAmplitudeEstimation(4), {"estimation": 0.272675}],
[3, IterativeAmplitudeEstimation(0.1, 0.1), {"estimation": 0.272082}],
[3, FasterAmplitudeEstimation(0.01, 1), {"estimation": 0.272082}],
]
)
@unpack
def test_statevector(self, n, qae, expect):
"""Statevector end-to-end test"""
# construct factories for A and Q
# qae.state_preparation = SineIntegral(n)
estimation_problem = EstimationProblem(SineIntegral(n), objective_qubits=[n])
with self.assertWarns(DeprecationWarning):
qae.quantum_instance = self._statevector
# result = qae.run(self._statevector)
result = qae.estimate(estimation_problem)
self._statevector.reset_execution_results()
for key, value in expect.items():
self.assertAlmostEqual(
value, getattr(result, key), places=3, msg=f"estimate `{key}` failed"
)
@idata(
[
[2, AmplitudeEstimation(2), {"estimation": 0.5, "mle": 0.2702}],
[4, MaximumLikelihoodAmplitudeEstimation(4), {"estimation": 0.2725}],
[3, IterativeAmplitudeEstimation(0.1, 0.1), {"estimation": 0.2721}],
[3, FasterAmplitudeEstimation(0.01, 1), {"estimation": 0.2792}],
]
)
@unpack
def test_sampler(self, n, qae, expect):
"""sampler end-to-end test"""
# construct factories for A and Q
# qae.state_preparation = SineIntegral(n)
qae.sampler = self._sampler
estimation_problem = EstimationProblem(SineIntegral(n), objective_qubits=[n])
result = qae.estimate(estimation_problem)
for key, value in expect.items():
self.assertAlmostEqual(
value, getattr(result, key), places=3, msg=f"estimate `{key}` failed"
)
@idata(
[
[4, 100, AmplitudeEstimation(2), {"estimation": 0.5, "mle": 0.281196}],
[3, 10, MaximumLikelihoodAmplitudeEstimation(2), {"estimation": 0.256878}],
[3, 1000, IterativeAmplitudeEstimation(0.01, 0.01), {"estimation": 0.271790}],
[3, 1000, FasterAmplitudeEstimation(0.1, 4), {"estimation": 0.274168}],
]
)
@unpack
def test_qasm(self, n, shots, qae, expect):
"""QASM simulator end-to-end test."""
estimation_problem = EstimationProblem(SineIntegral(n), objective_qubits=[n])
with self.assertWarns(DeprecationWarning):
qae.quantum_instance = self._qasm(shots)
result = qae.estimate(estimation_problem)
for key, value in expect.items():
self.assertAlmostEqual(
value, getattr(result, key), places=3, msg=f"estimate `{key}` failed"
)
@idata(
[
[4, 1000, AmplitudeEstimation(2), {"estimation": 0.5, "mle": 0.2636}],
[3, 10, MaximumLikelihoodAmplitudeEstimation(2), {"estimation": 0.2904}],
[3, 1000, IterativeAmplitudeEstimation(0.01, 0.01), {"estimation": 0.2706}],
[3, 1000, FasterAmplitudeEstimation(0.1, 4), {"estimation": 0.2764}],
]
)
@unpack
def test_sampler_with_shots(self, n, shots, qae, expect):
"""Sampler with shots end-to-end test."""
# construct factories for A and Q
qae.sampler = self._sampler_shots(shots)
estimation_problem = EstimationProblem(SineIntegral(n), objective_qubits=[n])
result = qae.estimate(estimation_problem)
for key, value in expect.items():
self.assertAlmostEqual(
value, getattr(result, key), places=3, msg=f"estimate `{key}` failed"
)
@idata(
[
[
AmplitudeEstimation(3),
"mle",
{
"likelihood_ratio": (0.2494734, 0.3003771),
"fisher": (0.2486176, 0.2999286),
"observed_fisher": (0.2484562, 0.3000900),
},
],
[
MaximumLikelihoodAmplitudeEstimation(3),
"estimation",
{
"likelihood_ratio": (0.2598794, 0.2798536),
"fisher": (0.2584889, 0.2797018),
"observed_fisher": (0.2659279, 0.2722627),
},
],
]
)
@unpack
def test_confidence_intervals(self, qae, key, expect):
"""End-to-end test for all confidence intervals."""
n = 3
estimation_problem = EstimationProblem(SineIntegral(n), objective_qubits=[n])
with self.assertWarns(DeprecationWarning):
qae.quantum_instance = self._statevector
# statevector simulator
result = qae.estimate(estimation_problem)
self._statevector.reset_execution_results()
methods = ["lr", "fi", "oi"] # short for likelihood_ratio, fisher, observed_fisher
alphas = [0.1, 0.00001, 0.9] # alpha shouldn't matter in statevector
for alpha, method in zip(alphas, methods):
confint = qae.compute_confidence_interval(result, alpha, method)
# confidence interval based on statevector should be empty, as we are sure of the result
self.assertAlmostEqual(confint[1] - confint[0], 0.0)
self.assertAlmostEqual(confint[0], getattr(result, key))
# qasm simulator
shots = 100
alpha = 0.01
with self.assertWarns(DeprecationWarning):
qae.quantum_instance = self._qasm(shots)
result = qae.estimate(estimation_problem)
for method, expected_confint in expect.items():
confint = qae.compute_confidence_interval(result, alpha, method)
np.testing.assert_array_almost_equal(confint, expected_confint)
self.assertTrue(confint[0] <= getattr(result, key) <= confint[1])
def test_iqae_confidence_intervals(self):
"""End-to-end test for the IQAE confidence interval."""
n = 3
expected_confint = (0.1984050, 0.3511015)
estimation_problem = EstimationProblem(SineIntegral(n), objective_qubits=[n])
with self.assertWarns(DeprecationWarning):
qae = IterativeAmplitudeEstimation(0.1, 0.01, quantum_instance=self._statevector)
# statevector simulator
result = qae.estimate(estimation_problem)
self._statevector.reset_execution_results()
confint = result.confidence_interval
# confidence interval based on statevector should be empty, as we are sure of the result
self.assertAlmostEqual(confint[1] - confint[0], 0.0)
self.assertAlmostEqual(confint[0], result.estimation)
# qasm simulator
shots = 100
with self.assertWarns(DeprecationWarning):
qae.quantum_instance = self._qasm(shots)
result = qae.estimate(estimation_problem)
confint = result.confidence_interval
np.testing.assert_array_almost_equal(confint, expected_confint)
self.assertTrue(confint[0] <= result.estimation <= confint[1])
class TestAmplitudeEstimation(QiskitAlgorithmsTestCase):
"""Specific tests for canonical AE."""
def test_warns_if_good_state_set(self):
"""Check AE warns if is_good_state is set."""
circuit = QuantumCircuit(1)
problem = EstimationProblem(circuit, objective_qubits=[0], is_good_state=lambda x: True)
qae = AmplitudeEstimation(num_eval_qubits=1, sampler=Sampler())
with self.assertWarns(Warning):
_ = qae.estimate(problem)
@ddt
class TestFasterAmplitudeEstimation(QiskitAlgorithmsTestCase):
"""Specific tests for Faster AE."""
def setUp(self):
super().setUp()
self._sampler = Sampler(options={"seed": 2})
def test_rescaling(self):
"""Test the rescaling."""
amplitude = 0.8
scaling = 0.25
circuit = QuantumCircuit(1)
circuit.ry(2 * np.arcsin(amplitude), 0)
problem = EstimationProblem(circuit, objective_qubits=[0])
rescaled = problem.rescale(scaling)
rescaled_amplitude = Statevector.from_instruction(rescaled.state_preparation).data[3]
self.assertAlmostEqual(scaling * amplitude, rescaled_amplitude)
def test_run_without_rescaling(self):
"""Run Faster AE without rescaling if the amplitude is in [0, 1/4]."""
# construct estimation problem
prob = 0.11
a_op = QuantumCircuit(1)
a_op.ry(2 * np.arcsin(np.sqrt(prob)), 0)
problem = EstimationProblem(a_op, objective_qubits=[0])
# construct algo without rescaling
backend = BasicAer.get_backend("statevector_simulator")
with self.assertWarns(DeprecationWarning):
fae = FasterAmplitudeEstimation(0.1, 1, rescale=False, quantum_instance=backend)
# run the algo
result = fae.estimate(problem)
# assert the result is correct
self.assertAlmostEqual(result.estimation, prob)
# assert no rescaling was used
theta = np.mean(result.theta_intervals[-1])
value_without_scaling = np.sin(theta) ** 2
self.assertAlmostEqual(result.estimation, value_without_scaling)
def test_sampler_run_without_rescaling(self):
"""Run Faster AE without rescaling if the amplitude is in [0, 1/4]."""
# construct estimation problem
prob = 0.11
a_op = QuantumCircuit(1)
a_op.ry(2 * np.arcsin(np.sqrt(prob)), 0)
problem = EstimationProblem(a_op, objective_qubits=[0])
# construct algo without rescaling
fae = FasterAmplitudeEstimation(0.1, 1, rescale=False, sampler=self._sampler)
# run the algo
result = fae.estimate(problem)
# assert the result is correct
self.assertAlmostEqual(result.estimation, prob, places=2)
# assert no rescaling was used
theta = np.mean(result.theta_intervals[-1])
value_without_scaling = np.sin(theta) ** 2
self.assertAlmostEqual(result.estimation, value_without_scaling)
def test_rescaling_with_custom_grover_raises(self):
"""Test that the rescaling option fails if a custom Grover operator is used."""
prob = 0.8
a_op = BernoulliStateIn(prob)
q_op = BernoulliGrover(prob)
problem = EstimationProblem(a_op, objective_qubits=[0], grover_operator=q_op)
# construct algo without rescaling
backend = BasicAer.get_backend("statevector_simulator")
with self.assertWarns(DeprecationWarning):
fae = FasterAmplitudeEstimation(0.1, 1, quantum_instance=backend)
# run the algo
with self.assertWarns(Warning):
_ = fae.estimate(problem)
@data(("statevector_simulator", 0.2), ("qasm_simulator", 0.199440))
@unpack
def test_good_state(self, backend_str, expect):
"""Test with a good state function."""
def is_good_state(bitstr):
return bitstr[1] == "1"
# construct the estimation problem where the second qubit is ignored
a_op = QuantumCircuit(2)
a_op.ry(2 * np.arcsin(np.sqrt(0.2)), 0)
# oracle only affects first qubit
oracle = QuantumCircuit(2)
oracle.z(0)
# reflect only on first qubit
q_op = GroverOperator(oracle, a_op, reflection_qubits=[0])
# but we measure both qubits (hence both are objective qubits)
problem = EstimationProblem(
a_op, objective_qubits=[0, 1], grover_operator=q_op, is_good_state=is_good_state
)
# construct algo
with self.assertWarns(DeprecationWarning):
backend = QuantumInstance(
BasicAer.get_backend(backend_str), seed_simulator=2, seed_transpiler=2
)
# cannot use rescaling with a custom grover operator
with self.assertWarns(DeprecationWarning):
fae = FasterAmplitudeEstimation(0.01, 5, rescale=False, quantum_instance=backend)
# run the algo
result = fae.estimate(problem)
# assert the result is correct
self.assertAlmostEqual(result.estimation, expect, places=5)
if __name__ == "__main__":
unittest.main()
|
https://github.com/maryrbarros2/QuantumAlgorithms_Qiskit
|
maryrbarros2
|
# initialization
import numpy as np
import matplotlib
# importing Qiskit
from qiskit.providers.ibmq import least_busy
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer, IBMQ, BasicAer, assemble, transpile
from qiskit.quantum_info import Statevector
# import basic plot tools
from qiskit.visualization import plot_bloch_multivector,plot_bloch_vector, plot_histogram
style = {'backgroundcolor': 'lightyellow'} # Style of the circuits
# set the length of the n-bit input string.
n = 3
# set the length of the n-bit input string.
n = 3
const_oracle = QuantumCircuit(n+1)
output = np.random.randint(2)
if output == 1:
const_oracle.x(n)
const_oracle.draw(output='mpl', style=style)
balanced_oracle = QuantumCircuit(n+1)
b_str = "101"
balanced_oracle = QuantumCircuit(n+1)
b_str = "101"
# Place X-gates
for qubit in range(len(b_str)):
if b_str[qubit] == '1':
balanced_oracle.x(qubit)
balanced_oracle.draw(output='mpl', style=style)
balanced_oracle = QuantumCircuit(n+1)
b_str = "101"
# Place X-gates
for qubit in range(len(b_str)):
if b_str[qubit] == '1':
balanced_oracle.x(qubit)
# Use barrier as divider
balanced_oracle.barrier()
# Controlled-NOT gates
for qubit in range(n):
balanced_oracle.cx(qubit, n)
balanced_oracle.barrier()
balanced_oracle.draw(output='mpl', style=style)
balanced_oracle = QuantumCircuit(n+1)
b_str = "101"
# Place X-gates
for qubit in range(len(b_str)):
if b_str[qubit] == '1':
balanced_oracle.x(qubit)
# Use barrier as divider
balanced_oracle.barrier()
# Controlled-NOT gates
for qubit in range(n):
balanced_oracle.cx(qubit, n)
balanced_oracle.barrier()
# Place X-gates
for qubit in range(len(b_str)):
if b_str[qubit] == '1':
balanced_oracle.x(qubit)
# Show oracle
balanced_oracle.draw(output='mpl', style=style)
dj_circuit = QuantumCircuit(n+1, n)
# Apply H-gates
for qubit in range(n):
dj_circuit.h(qubit)
# Put qubit in state |->
dj_circuit.x(n)
dj_circuit.h(n)
dj_circuit.draw(output='mpl', style=style)
dj_circuit = QuantumCircuit(n+1, n)
# Apply H-gates
for qubit in range(n):
dj_circuit.h(qubit)
# Put qubit in state |->
dj_circuit.x(n)
dj_circuit.h(n)
# Add oracle
dj_circuit += balanced_oracle
dj_circuit.draw(output='mpl', style=style)
dj_circuit = QuantumCircuit(n+1, n)
# Apply H-gates
for qubit in range(n):
dj_circuit.h(qubit)
# Put qubit in state |->
dj_circuit.x(n)
dj_circuit.h(n)
# Add oracle
dj_circuit += balanced_oracle
# Repeat H-gates
for qubit in range(n):
dj_circuit.h(qubit)
dj_circuit.barrier()
# Measure
for i in range(n):
dj_circuit.measure(i, i)
# Display circuit
dj_circuit.draw(output='mpl', style=style)
# use local simulator
aer_sim = Aer.get_backend('aer_simulator')
qobj = assemble(dj_circuit, aer_sim)
results = aer_sim.run(qobj).result()
answer = results.get_counts()
plot_histogram(answer)
def dj_oracle(case, n):
# We need to make a QuantumCircuit object to return
# This circuit has n+1 qubits: the size of the input,
# plus one output qubit
oracle_qc = QuantumCircuit(n+1)
# First, let's deal with the case in which oracle is balanced
if case == "balanced":
# First generate a random number that tells us which CNOTs to
# wrap in X-gates:
b = np.random.randint(1,2**n)
print(b)
print(str(n))
b=7
# Next, format 'b' as a binary string of length 'n', padded with zeros:
b_str = format(b, '0'+str(n)+'b')
print(b_str)
# Next, we place the first X-gates. Each digit in our binary string
# corresponds to a qubit, if the digit is 0, we do nothing, if it's 1
# we apply an X-gate to that qubit:
for qubit in range(len(b_str)):
if b_str[qubit] == '1':
oracle_qc.x(qubit)
# Do the controlled-NOT gates for each qubit, using the output qubit
# as the target:
for qubit in range(n):
oracle_qc.cx(qubit, n)
# Next, place the final X-gates
for qubit in range(len(b_str)):
if b_str[qubit] == '1':
oracle_qc.x(qubit)
# Case in which oracle is constant
if case == "constant":
# First decide what the fixed output of the oracle will be
# (either always 0 or always 1)
output = np.random.randint(2)
if output == 1:
oracle_qc.x(n)
oracle_gate = oracle_qc.to_gate()
oracle_gate.name = "Oracle" # To show when we display the circuit
return oracle_gate
def dj_algorithm(oracle, n):
dj_circuit = QuantumCircuit(n+1, n)
# Set up the output qubit:
dj_circuit.x(n)
dj_circuit.h(n)
# And set up the input register:
for qubit in range(n):
dj_circuit.h(qubit)
# Let's append the oracle gate to our circuit:
dj_circuit.append(oracle, range(n+1))
# Finally, perform the H-gates again and measure:
for qubit in range(n):
dj_circuit.h(qubit)
for i in range(n):
dj_circuit.measure(i, i)
return dj_circuit
n = 4
oracle_gate = dj_oracle('balanced', n)
dj_circuit = dj_algorithm(oracle_gate, n)
dj_circuit.draw(output='mpl', style=style)
transpiled_dj_circuit = transpile(dj_circuit, aer_sim)
qobj = assemble(transpiled_dj_circuit)
results = aer_sim.run(qobj).result()
answer = results.get_counts()
plot_histogram(answer)
|
https://github.com/arnavdas88/QuGlassyIsing
|
arnavdas88
|
!pip install qiskit
J = 4.0
B_x = 0.25
B_z = 1.5
import numpy as np
from qiskit.providers.aer import AerSimulator, QasmSimulator
from qiskit.algorithms.optimizers import COBYLA
from qiskit.circuit.library import TwoLocal
from qiskit.aqua.operators import *
from qiskit.aqua import set_qiskit_aqua_logging, QuantumInstance
from qiskit.aqua.algorithms import NumPyMinimumEigensolver, VQE, NumPyEigensolver
from qiskit.circuit import QuantumCircuit, ParameterVector
from qiskit.visualization import plot_histogram
Hamiltonian = J * (Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z^I)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^I^I^I^I^I^Z)+(I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^Z^Z)
- B_z * (( Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ Z )
) - B_x * ( ( X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ^ I ) + ( I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ I ^ X ))
ansatz = TwoLocal(num_qubits=36, rotation_blocks=['ry', 'rz'], entanglement_blocks=None, entanglement='full', reps=1, skip_unentangled_qubits=False, skip_final_rotation_layer=True)
print(ansatz)
backend = AerSimulator(method='matrix_product_state')
quantum_instance = QuantumInstance(backend,
shots = 8192,
initial_layout = None,
optimization_level = 3)
optimizer = COBYLA(maxiter=10000, tol=0.000000001)
vqe = VQE(Hamiltonian, ansatz, optimizer, include_custom = False)
print('We are using:', quantum_instance.backend)
vqe_result = vqe.run(quantum_instance)
print(vqe['result'])
plot_histogram(vqe_result['eigenstate'])
import pickle
filename = "2D_Ising_Model_CountsAF3.pkl"
a = {'vqe_result': vqe_result}
#This saves the data
with open(filename, 'wb') as handle:
pickle.dump(a, handle, protocol=pickle.HIGHEST_PROTOCOL)
# This loads the data
with open(filename, 'rb') as handle:
b = pickle.load(handle)
|
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
"""
print("Ch 7: Aer out of the box, a perfect quantum computer")
print("----------------------------------------------------")
# Import Qiskit
from qiskit import QuantumCircuit
from qiskit import Aer, IBMQ, execute
# Import visualization tools
from qiskit.tools.visualization import plot_histogram
from qiskit.tools.monitor import job_monitor
from IPython.core.display import display
# Load account
print("Getting provider...")
if not IBMQ.active_account():
IBMQ.load_account()
provider = IBMQ.get_provider()
# Enter number of SWAP gates to include with your circuit with (default 20)
user_input = input("Enter number of SWAP gates to use: ")
try:
n = int(user_input)
except ValueError:
n=10
n_gates=n
# Construct quantum circuit
circ = QuantumCircuit(2, 2)
circ.x(0)
while n >0:
circ.swap(0,1)
circ.barrier()
n=n-1
circ.measure([0,1], [0,1])
print("Circuit with",n_gates,"SWAP gates.\n")
display(circ.draw())
# Select the QasmSimulator from the Aer provider
simulator = Aer.get_backend('qasm_simulator')
# Execute and get counts
result = execute(circ, simulator, shots=simulator.configuration().max_shots).result()
counts = result.get_counts(circ)
display(plot_histogram(counts, title='Simulated counts for '+str(n_gates)+' SWAP gates.'))
print("Simulated SWAP counts:",counts)
input("Press enter to run on an IBM Q backend...\n")
# Import the least busy backend
from qiskit.providers.ibmq import least_busy
backend = least_busy(provider.backends(n_qubits=5, operational=True, simulator=False))
print("Least busy backend:",backend)
# Execute and get counts
job = execute(circ, backend, shots=backend.configuration().max_shots)
job_monitor(job)
nisq_result=job.result()
nisq_counts=nisq_result.get_counts(circ)
print("NISQ SWAP counts:",nisq_counts)
display(plot_histogram(nisq_counts, title='Counts for '+str(n_gates)+' SWAP gates on '+str(backend)))
input("Press enter to transpile the circuit...\n")
# Comparing the circuit with the transpiled circuit
from qiskit.compiler import transpile
trans_swap = transpile(circ, backend)
print(trans_swap)
print("Basis gates:",backend.configuration().basis_gates)
print("SWAP circuit depth:",circ.depth(),"gates")
print("Transpiled SWAP circuit depth:",trans_swap.depth(),"gates")
|
https://github.com/zeynepCankara/Introduction-Quantum-Programming
|
zeynepCankara
|
%run qlatvia.py
draw_qubit()
[x,y]=[1,0]
draw_quantum_state(x,y,"v0")
sqrttwo = 2**0.5
oversqrttwo = 1/sqrttwo
R = [ [oversqrttwo, -1*oversqrttwo], [oversqrttwo,oversqrttwo] ]
# function for rotation R
def rotate(px,py):
newx = R[0][0]*px + R[0][1]*py
newy = R[1][0]*px + R[1][1]*py
return [newx,newy]
# apply rotation R 7 times
for i in range(1,8):
[x,y] = rotate(x,y)
draw_quantum_state(x,y,"|v"+str(i)+">")
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
from math import pi
from random import randrange
# first qubit
qreg1 = QuantumRegister(1)
creg1 = ClassicalRegister(1)
mycircuit1 = QuantumCircuit(qreg1,creg1)
# second qubit
qreg2 = QuantumRegister(1)
creg2 = ClassicalRegister(1)
mycircuit2 = QuantumCircuit(qreg2,creg2)
# third qubit
qreg3 = QuantumRegister(1)
creg3 = ClassicalRegister(1)
mycircuit3 = QuantumCircuit(qreg3,creg3)
# randomly pick the angle of rotation
r = randrange(100)
theta = 2*pi*(r/100) # radians
print("the picked angle is",r*3.6,"degrees and",theta,"radians")
# rotate the first qubit
mycircuit1.ry(2*theta,qreg1[0])
# the different angles orthogonal to theta
theta1 = theta + pi/2
theta2 = theta - pi/2
# rotate the second and third qubits
mycircuit2.ry(2*theta1,qreg2[0])
mycircuit3.ry(2*theta2,qreg3[0])
# read the quantum state of the first qubit
job = execute(mycircuit1,Aer.get_backend('statevector_simulator'))
current_quantum_state=job.result().get_statevector(mycircuit1)
[x1,y1]=[current_quantum_state[0].real,current_quantum_state[1].real]
print("the first qubit:",x1,y1)
# read the quantum state of the second qubit
job = execute(mycircuit2,Aer.get_backend('statevector_simulator'))
current_quantum_state=job.result().get_statevector(mycircuit2)
[x2,y2]=[current_quantum_state[0].real,current_quantum_state[1].real]
print("the second qubit:",x2,y2)
# read the quantum state of the third qubit
job = execute(mycircuit3,Aer.get_backend('statevector_simulator'))
current_quantum_state=job.result().get_statevector(mycircuit3)
[x3,y3]=[current_quantum_state[0].real,current_quantum_state[1].real]
print("the third qubit:",x3,y3)
%run qlatvia.py
draw_qubit()
draw_quantum_state(x1,y1,"v0")
draw_quantum_state(x2,y2,"v1")
draw_quantum_state(x3,y3,"v2")
print("the dot product of |v0> and |v1> is",x1*x2+y1*y2)
print("the dot product of |v0> and |v2> is",x1*x3+y1*y3)
print("the dot product of |v1> and |v2> is",x2*x3+y2*y3)
# make a full rotation by theta + theta_prime
theta_prime = 2*pi - theta
# rotate all qubits with theta_prime
mycircuit1.ry(2*theta_prime,qreg1[0])
mycircuit2.ry(2*theta_prime,qreg2[0])
mycircuit3.ry(2*theta_prime,qreg3[0])
# measure all qubits
mycircuit1.measure(qreg1,creg1)
mycircuit2.measure(qreg2,creg2)
mycircuit3.measure(qreg3,creg3)
# draw the first circuit
mycircuit1.draw()
# draw the second circuit
mycircuit2.draw()
# draw the third circuit
mycircuit3.draw()
# execute the first circuit
job = execute(mycircuit1,Aer.get_backend('qasm_simulator'),shots=1000)
counts = job.result().get_counts(mycircuit1)
print(counts)
# execute the second circuit
job = execute(mycircuit2,Aer.get_backend('qasm_simulator'),shots=1000)
counts = job.result().get_counts(mycircuit2)
print(counts)
# execute the third circuit
job = execute(mycircuit3,Aer.get_backend('qasm_simulator'),shots=1000)
counts = job.result().get_counts(mycircuit3)
print(counts)
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
from math import pi, cos, sin
# first qubit
qreg = QuantumRegister(1)
creg = ClassicalRegister(1)
mycircuit = QuantumCircuit(qreg,creg)
theta=pi/4
for i in range(1,9):
total_theta = i*theta
mycircuit.ry(2*theta,qreg[0])
job = execute(mycircuit, Aer.get_backend('unitary_simulator'))
current_unitary = job.result().get_unitary(mycircuit, decimals=3)
print("after",i,"iteration(s):")
print(current_unitary[0][0].real,current_unitary[0][1].real)
print(current_unitary[1][0].real,current_unitary[1][1].real)
print("calculated by python:")
print(round(cos(total_theta),3),round(-sin(total_theta),3))
print(round(sin(total_theta),3),round(cos(total_theta),3))
print()
|
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
from qiskit.quantum_info import Statevector
qc = QuantumCircuit(2, 2)
sv = Statevector.from_label("10")
qc.initialize(sv, range(2))
qc.h(0)
qc.cx(0, 1)
qc.measure(range(2), range(2))
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/epelaaez/QuantumLibrary
|
epelaaez
|
import numpy as np
from qiskit import Aer
from qiskit.algorithms import Shor
import matplotlib.pyplot as plt
x = np.linspace(start=0, stop=29, num=30)
plt.plot(x, (3**x) % 20, 'x--', linewidth=1)
plt.xlabel('x', fontsize=10)
plt.ylabel('$3^x$ mod 20', fontsize=10)
plt.grid(visible=True)
plt.show()
backend = Aer.get_backend('qasm_simulator')
shors = Shor(backend)
qc = shors.construct_circuit(N=3, measurement=True)
qc.draw()
shors.factor(N=3).factors
qc = shors.construct_circuit(N=15, measurement=True)
qc.draw()
shors.factor(N=15).factors
qc = shors.construct_circuit(N=35, measurement=True)
print('Number of qubits:', qc.num_qubits, '\nGate operations:', qc.size(), '\nDepth:', qc.depth())
shors.factor(N=35).factors
|
https://github.com/RicardoBBS/ShorAlgo
|
RicardoBBS
|
import sys
import numpy as np
from matplotlib import pyplot as plt
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer, visualization
from random import randint
def to_binary(N,n_bit):
Nbin = np.zeros(n_bit, dtype=bool)
for i in range(1,n_bit+1):
bit_state = (N % (2**i) != 0)
if bit_state:
N -= 2**(i-1)
Nbin[n_bit-i] = bit_state
return Nbin
def modular_multiplication(qc,a,N):
"""
applies the unitary operator that implements
modular multiplication function x -> a*x(modN)
Only works for the particular case x -> 7*x(mod15)!
"""
for i in range(0,3):
qc.x(i)
qc.cx(2,1)
qc.cx(1,2)
qc.cx(2,1)
qc.cx(1,0)
qc.cx(0,1)
qc.cx(1,0)
qc.cx(3,0)
qc.cx(0,1)
qc.cx(1,0)
def quantum_period(a, N, n_bit):
# Quantum part
print(" Searching the period for N =", N, "and a =", a)
qr = QuantumRegister(n_bit)
cr = ClassicalRegister(n_bit)
qc = QuantumCircuit(qr,cr)
simulator = Aer.get_backend('qasm_simulator')
s0 = randint(1, N-1) # Chooses random int
sbin = to_binary(s0,n_bit) # Turns to binary
print("\n Starting at \n s =", s0, "=", "{0:b}".format(s0), "(bin)")
# Quantum register is initialized with s (in binary)
for i in range(0,n_bit):
if sbin[n_bit-i-1]:
qc.x(i)
s = s0
r=-1 # makes while loop run at least 2 times
# Applies modular multiplication transformation until we come back to initial number s
while s != s0 or r <= 0:
r+=1
# sets up circuit structure
qc.measure(qr, cr)
modular_multiplication(qc,a,N)
qc.draw('mpl')
# runs circuit and processes data
job = execute(qc,simulator, shots=10)
result_counts = job.result().get_counts(qc)
result_histogram_key = list(result_counts)[0] # https://qiskit.org/documentation/stubs/qiskit.result.Result.get_counts.html#qiskit.result.Result.get_counts
s = int(result_histogram_key, 2)
print(" ", result_counts)
plt.show()
print("\n Found period r =", r)
return r
if __name__ == '__main__':
a = 7
N = 15
n_bit=5
r = quantum_period(a, N, n_bit)
|
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.
r"""
.. _pulse_builder:
=============
Pulse Builder
=============
..
We actually want people to think of these functions as being defined within the ``qiskit.pulse``
namespace, not the submodule ``qiskit.pulse.builder``.
.. currentmodule: qiskit.pulse
Use the pulse builder DSL to write pulse programs with an imperative syntax.
.. warning::
The pulse builder interface is still in active development. It may have
breaking API changes without deprecation warnings in future releases until
otherwise indicated.
The pulse builder provides an imperative API for writing pulse programs
with less difficulty than the :class:`~qiskit.pulse.Schedule` API.
It contextually constructs a pulse schedule and then emits the schedule for
execution. For example, to play a series of pulses on channels is as simple as:
.. plot::
:include-source:
from qiskit import pulse
dc = pulse.DriveChannel
d0, d1, d2, d3, d4 = dc(0), dc(1), dc(2), dc(3), dc(4)
with pulse.build(name='pulse_programming_in') as pulse_prog:
pulse.play([1, 1, 1, 0, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1], d0)
pulse.play([1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0], d1)
pulse.play([1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0], d2)
pulse.play([1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0], d3)
pulse.play([1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 0, 1, 0], d4)
pulse_prog.draw()
To begin pulse programming we must first initialize our program builder
context with :func:`build`, after which we can begin adding program
statements. For example, below we write a simple program that :func:`play`\s
a pulse:
.. plot::
:include-source:
from qiskit import execute, pulse
d0 = pulse.DriveChannel(0)
with pulse.build() as pulse_prog:
pulse.play(pulse.Constant(100, 1.0), d0)
pulse_prog.draw()
The builder initializes a :class:`.pulse.Schedule`, ``pulse_prog``
and then begins to construct the program within the context. The output pulse
schedule will survive after the context is exited and can be executed like a
normal Qiskit schedule using ``qiskit.execute(pulse_prog, backend)``.
Pulse programming has a simple imperative style. This leaves the programmer
to worry about the raw experimental physics of pulse programming and not
constructing cumbersome data structures.
We can optionally pass a :class:`~qiskit.providers.Backend` to
:func:`build` to enable enhanced functionality. Below, we prepare a Bell state
by automatically compiling the required pulses from their gate-level
representations, while simultaneously applying a long decoupling pulse to a
neighboring qubit. We terminate the experiment with a measurement to observe the
state we prepared. This program which mixes circuits and pulses will be
automatically lowered to be run as a pulse program:
.. plot::
:include-source:
import math
from qiskit import pulse
from qiskit.providers.fake_provider import FakeOpenPulse3Q
# TODO: This example should use a real mock backend.
backend = FakeOpenPulse3Q()
d2 = pulse.DriveChannel(2)
with pulse.build(backend) as bell_prep:
pulse.u2(0, math.pi, 0)
pulse.cx(0, 1)
with pulse.build(backend) as decoupled_bell_prep_and_measure:
# We call our bell state preparation schedule constructed above.
with pulse.align_right():
pulse.call(bell_prep)
pulse.play(pulse.Constant(bell_prep.duration, 0.02), d2)
pulse.barrier(0, 1, 2)
registers = pulse.measure_all()
decoupled_bell_prep_and_measure.draw()
With the pulse builder we are able to blend programming on qubits and channels.
While the pulse schedule is based on instructions that operate on
channels, the pulse builder automatically handles the mapping from qubits to
channels for you.
In the example below we demonstrate some more features of the pulse builder:
.. code-block::
import math
from qiskit import pulse, QuantumCircuit
from qiskit.pulse import library
from qiskit.providers.fake_provider import FakeOpenPulse2Q
backend = FakeOpenPulse2Q()
with pulse.build(backend) as pulse_prog:
# Create a pulse.
gaussian_pulse = library.gaussian(10, 1.0, 2)
# Get the qubit's corresponding drive channel from the backend.
d0 = pulse.drive_channel(0)
d1 = pulse.drive_channel(1)
# Play a pulse at t=0.
pulse.play(gaussian_pulse, d0)
# Play another pulse directly after the previous pulse at t=10.
pulse.play(gaussian_pulse, d0)
# The default scheduling behavior is to schedule pulses in parallel
# across channels. For example, the statement below
# plays the same pulse on a different channel at t=0.
pulse.play(gaussian_pulse, d1)
# We also provide pulse scheduling alignment contexts.
# The default alignment context is align_left.
# The sequential context schedules pulse instructions sequentially in time.
# This context starts at t=10 due to earlier pulses above.
with pulse.align_sequential():
pulse.play(gaussian_pulse, d0)
# Play another pulse after at t=20.
pulse.play(gaussian_pulse, d1)
# We can also nest contexts as each instruction is
# contained in its local scheduling context.
# The output of a child context is a context-schedule
# with the internal instructions timing fixed relative to
# one another. This is schedule is then called in the parent context.
# Context starts at t=30.
with pulse.align_left():
# Start at t=30.
pulse.play(gaussian_pulse, d0)
# Start at t=30.
pulse.play(gaussian_pulse, d1)
# Context ends at t=40.
# Alignment context where all pulse instructions are
# aligned to the right, ie., as late as possible.
with pulse.align_right():
# Shift the phase of a pulse channel.
pulse.shift_phase(math.pi, d1)
# Starts at t=40.
pulse.delay(100, d0)
# Ends at t=140.
# Starts at t=130.
pulse.play(gaussian_pulse, d1)
# Ends at t=140.
# Acquire data for a qubit and store in a memory slot.
pulse.acquire(100, 0, pulse.MemorySlot(0))
# We also support a variety of macros for common operations.
# Measure all qubits.
pulse.measure_all()
# Delay on some qubits.
# This requires knowledge of which channels belong to which qubits.
# delay for 100 cycles on qubits 0 and 1.
pulse.delay_qubits(100, 0, 1)
# Call a quantum circuit. The pulse builder lazily constructs a quantum
# circuit which is then transpiled and scheduled before inserting into
# a pulse schedule.
# NOTE: Quantum register indices correspond to physical qubit indices.
qc = QuantumCircuit(2, 2)
qc.cx(0, 1)
pulse.call(qc)
# Calling a small set of standard gates and decomposing to pulses is
# also supported with more natural syntax.
pulse.u3(0, math.pi, 0, 0)
pulse.cx(0, 1)
# It is also be possible to call a preexisting schedule
tmp_sched = pulse.Schedule()
tmp_sched += pulse.Play(gaussian_pulse, d0)
pulse.call(tmp_sched)
# We also support:
# frequency instructions
pulse.set_frequency(5.0e9, d0)
# phase instructions
pulse.shift_phase(0.1, d0)
# offset contexts
with pulse.phase_offset(math.pi, d0):
pulse.play(gaussian_pulse, d0)
The above is just a small taste of what is possible with the builder. See the rest of the module
documentation for more information on its capabilities.
.. autofunction:: build
Channels
========
Methods to return the correct channels for the respective qubit indices.
.. code-block::
from qiskit import pulse
from qiskit.providers.fake_provider import FakeArmonk
backend = FakeArmonk()
with pulse.build(backend) as drive_sched:
d0 = pulse.drive_channel(0)
print(d0)
.. parsed-literal::
DriveChannel(0)
.. autofunction:: acquire_channel
.. autofunction:: control_channels
.. autofunction:: drive_channel
.. autofunction:: measure_channel
Instructions
============
Pulse instructions are available within the builder interface. Here's an example:
.. plot::
:include-source:
from qiskit import pulse
from qiskit.providers.fake_provider import FakeArmonk
backend = FakeArmonk()
with pulse.build(backend) as drive_sched:
d0 = pulse.drive_channel(0)
a0 = pulse.acquire_channel(0)
pulse.play(pulse.library.Constant(10, 1.0), d0)
pulse.delay(20, d0)
pulse.shift_phase(3.14/2, d0)
pulse.set_phase(3.14, d0)
pulse.shift_frequency(1e7, d0)
pulse.set_frequency(5e9, d0)
with pulse.build() as temp_sched:
pulse.play(pulse.library.Gaussian(20, 1.0, 3.0), d0)
pulse.play(pulse.library.Gaussian(20, -1.0, 3.0), d0)
pulse.call(temp_sched)
pulse.acquire(30, a0, pulse.MemorySlot(0))
drive_sched.draw()
.. autofunction:: acquire
.. autofunction:: barrier
.. autofunction:: call
.. autofunction:: delay
.. autofunction:: play
.. autofunction:: reference
.. autofunction:: set_frequency
.. autofunction:: set_phase
.. autofunction:: shift_frequency
.. autofunction:: shift_phase
.. autofunction:: snapshot
Contexts
========
Builder aware contexts that modify the construction of a pulse program. For
example an alignment context like :func:`align_right` may
be used to align all pulses as late as possible in a pulse program.
.. plot::
:include-source:
from qiskit import pulse
d0 = pulse.DriveChannel(0)
d1 = pulse.DriveChannel(1)
with pulse.build() as pulse_prog:
with pulse.align_right():
# this pulse will start at t=0
pulse.play(pulse.Constant(100, 1.0), d0)
# this pulse will start at t=80
pulse.play(pulse.Constant(20, 1.0), d1)
pulse_prog.draw()
.. autofunction:: align_equispaced
.. autofunction:: align_func
.. autofunction:: align_left
.. autofunction:: align_right
.. autofunction:: align_sequential
.. autofunction:: circuit_scheduler_settings
.. autofunction:: frequency_offset
.. autofunction:: phase_offset
.. autofunction:: transpiler_settings
Macros
======
Macros help you add more complex functionality to your pulse program.
.. code-block::
from qiskit import pulse
from qiskit.providers.fake_provider import FakeArmonk
backend = FakeArmonk()
with pulse.build(backend) as measure_sched:
mem_slot = pulse.measure(0)
print(mem_slot)
.. parsed-literal::
MemorySlot(0)
.. autofunction:: measure
.. autofunction:: measure_all
.. autofunction:: delay_qubits
Circuit Gates
=============
To use circuit level gates within your pulse program call a circuit
with :func:`call`.
.. warning::
These will be removed in future versions with the release of a circuit
builder interface in which it will be possible to calibrate a gate in
terms of pulses and use that gate in a circuit.
.. code-block::
import math
from qiskit import pulse
from qiskit.providers.fake_provider import FakeArmonk
backend = FakeArmonk()
with pulse.build(backend) as u3_sched:
pulse.u3(math.pi, 0, math.pi, 0)
.. autofunction:: cx
.. autofunction:: u1
.. autofunction:: u2
.. autofunction:: u3
.. autofunction:: x
Utilities
=========
The utility functions can be used to gather attributes about the backend and modify
how the program is built.
.. code-block::
from qiskit import pulse
from qiskit.providers.fake_provider import FakeArmonk
backend = FakeArmonk()
with pulse.build(backend) as u3_sched:
print('Number of qubits in backend: {}'.format(pulse.num_qubits()))
samples = 160
print('There are {} samples in {} seconds'.format(
samples, pulse.samples_to_seconds(160)))
seconds = 1e-6
print('There are {} seconds in {} samples.'.format(
seconds, pulse.seconds_to_samples(1e-6)))
.. parsed-literal::
Number of qubits in backend: 1
There are 160 samples in 3.5555555555555554e-08 seconds
There are 1e-06 seconds in 4500 samples.
.. autofunction:: active_backend
.. autofunction:: active_transpiler_settings
.. autofunction:: active_circuit_scheduler_settings
.. autofunction:: num_qubits
.. autofunction:: qubit_channels
.. autofunction:: samples_to_seconds
.. autofunction:: seconds_to_samples
"""
import collections
import contextvars
import functools
import itertools
import uuid
import warnings
from contextlib import contextmanager
from functools import singledispatchmethod
from typing import (
Any,
Callable,
ContextManager,
Dict,
Iterable,
List,
Mapping,
Optional,
Set,
Tuple,
TypeVar,
Union,
NewType,
)
import numpy as np
from qiskit import circuit
from qiskit.circuit.library import standard_gates as gates
from qiskit.circuit.parameterexpression import ParameterExpression, ParameterValueType
from qiskit.pulse import (
channels as chans,
configuration,
exceptions,
instructions,
macros,
library,
transforms,
)
from qiskit.providers.backend import BackendV2
from qiskit.pulse.instructions import directives
from qiskit.pulse.schedule import Schedule, ScheduleBlock
from qiskit.pulse.transforms.alignments import AlignmentKind
#: contextvars.ContextVar[BuilderContext]: active builder
BUILDER_CONTEXTVAR = contextvars.ContextVar("backend")
T = TypeVar("T")
StorageLocation = NewType("StorageLocation", Union[chans.MemorySlot, chans.RegisterSlot])
def _compile_lazy_circuit_before(function: Callable[..., T]) -> Callable[..., T]:
"""Decorator thats schedules and calls the lazily compiled circuit before
executing the decorated builder method."""
@functools.wraps(function)
def wrapper(self, *args, **kwargs):
self._compile_lazy_circuit()
return function(self, *args, **kwargs)
return wrapper
def _requires_backend(function: Callable[..., T]) -> Callable[..., T]:
"""Decorator a function to raise if it is called without a builder with a
set backend.
"""
@functools.wraps(function)
def wrapper(self, *args, **kwargs):
if self.backend is None:
raise exceptions.BackendNotSet(
'This function requires the builder to have a "backend" set.'
)
return function(self, *args, **kwargs)
return wrapper
class _PulseBuilder:
"""Builder context class."""
__alignment_kinds__ = {
"left": transforms.AlignLeft(),
"right": transforms.AlignRight(),
"sequential": transforms.AlignSequential(),
}
def __init__(
self,
backend=None,
block: Optional[ScheduleBlock] = None,
name: Optional[str] = None,
default_alignment: Union[str, AlignmentKind] = "left",
default_transpiler_settings: Mapping = None,
default_circuit_scheduler_settings: Mapping = None,
):
"""Initialize the builder context.
.. note::
At some point we may consider incorporating the builder into
the :class:`~qiskit.pulse.Schedule` class. However, the risk of
this is tying the user interface to the intermediate
representation. For now we avoid this at the cost of some code
duplication.
Args:
backend (Backend): Input backend to use in
builder. If not set certain functionality will be unavailable.
block: Initital ``ScheduleBlock`` to build on.
name: Name of pulse program to be built.
default_alignment: Default scheduling alignment for builder.
One of ``left``, ``right``, ``sequential`` or an instance of
:class:`~qiskit.pulse.transforms.alignments.AlignmentKind` subclass.
default_transpiler_settings: Default settings for the transpiler.
default_circuit_scheduler_settings: Default settings for the
circuit to pulse scheduler.
Raises:
PulseError: When invalid ``default_alignment`` or `block` is specified.
"""
#: Backend: Backend instance for context builder.
self._backend = backend
#: Union[None, ContextVar]: Token for this ``_PulseBuilder``'s ``ContextVar``.
self._backend_ctx_token = None
#: QuantumCircuit: Lazily constructed quantum circuit
self._lazy_circuit = None
#: Dict[str, Any]: Transpiler setting dictionary.
self._transpiler_settings = default_transpiler_settings or {}
#: Dict[str, Any]: Scheduler setting dictionary.
self._circuit_scheduler_settings = default_circuit_scheduler_settings or {}
#: List[ScheduleBlock]: Stack of context.
self._context_stack = []
#: str: Name of the output program
self._name = name
# Add root block if provided. Schedule will be built on top of this.
if block is not None:
if isinstance(block, ScheduleBlock):
root_block = block
elif isinstance(block, Schedule):
root_block = self._naive_typecast_schedule(block)
else:
raise exceptions.PulseError(
f"Input `block` type {block.__class__.__name__} is "
"not a valid format. Specify a pulse program."
)
self._context_stack.append(root_block)
# Set default alignment context
alignment = _PulseBuilder.__alignment_kinds__.get(default_alignment, default_alignment)
if not isinstance(alignment, AlignmentKind):
raise exceptions.PulseError(
f"Given `default_alignment` {repr(default_alignment)} is "
"not a valid transformation. Set one of "
f'{", ".join(_PulseBuilder.__alignment_kinds__.keys())}, '
"or set an instance of `AlignmentKind` subclass."
)
self.push_context(alignment)
def __enter__(self) -> ScheduleBlock:
"""Enter this builder context and yield either the supplied schedule
or the schedule created for the user.
Returns:
The schedule that the builder will build on.
"""
self._backend_ctx_token = BUILDER_CONTEXTVAR.set(self)
output = self._context_stack[0]
output._name = self._name or output.name
return output
@_compile_lazy_circuit_before
def __exit__(self, exc_type, exc_val, exc_tb):
"""Exit the builder context and compile the built pulse program."""
self.compile()
BUILDER_CONTEXTVAR.reset(self._backend_ctx_token)
@property
def backend(self):
"""Returns the builder backend if set.
Returns:
Optional[Backend]: The builder's backend.
"""
return self._backend
@_compile_lazy_circuit_before
def push_context(self, alignment: AlignmentKind):
"""Push new context to the stack."""
self._context_stack.append(ScheduleBlock(alignment_context=alignment))
@_compile_lazy_circuit_before
def pop_context(self) -> ScheduleBlock:
"""Pop the last context from the stack."""
if len(self._context_stack) == 1:
raise exceptions.PulseError("The root context cannot be popped out.")
return self._context_stack.pop()
def get_context(self) -> ScheduleBlock:
"""Get current context.
Notes:
New instruction can be added by `.append_subroutine` or `.append_instruction` method.
Use above methods rather than directly accessing to the current context.
"""
return self._context_stack[-1]
@property
@_requires_backend
def num_qubits(self):
"""Get the number of qubits in the backend."""
# backendV2
if isinstance(self.backend, BackendV2):
return self.backend.num_qubits
return self.backend.configuration().n_qubits
@property
def transpiler_settings(self) -> Mapping:
"""The builder's transpiler settings."""
return self._transpiler_settings
@transpiler_settings.setter
@_compile_lazy_circuit_before
def transpiler_settings(self, settings: Mapping):
self._compile_lazy_circuit()
self._transpiler_settings = settings
@property
def circuit_scheduler_settings(self) -> Mapping:
"""The builder's circuit to pulse scheduler settings."""
return self._circuit_scheduler_settings
@circuit_scheduler_settings.setter
@_compile_lazy_circuit_before
def circuit_scheduler_settings(self, settings: Mapping):
self._compile_lazy_circuit()
self._circuit_scheduler_settings = settings
@_compile_lazy_circuit_before
def compile(self) -> ScheduleBlock:
"""Compile and output the built pulse program."""
# Not much happens because we currently compile as we build.
# This should be offloaded to a true compilation module
# once we define a more sophisticated IR.
while len(self._context_stack) > 1:
current = self.pop_context()
self.append_subroutine(current)
return self._context_stack[0]
def _compile_lazy_circuit(self):
"""Call a context QuantumCircuit (lazy circuit) and append the output pulse schedule
to the builder's context schedule.
Note that the lazy circuit is not stored as a call instruction.
"""
if self._lazy_circuit:
lazy_circuit = self._lazy_circuit
# reset lazy circuit
self._lazy_circuit = self._new_circuit()
self.call_subroutine(self._compile_circuit(lazy_circuit))
def _compile_circuit(self, circ) -> Schedule:
"""Take a QuantumCircuit and output the pulse schedule associated with the circuit."""
from qiskit import compiler # pylint: disable=cyclic-import
transpiled_circuit = compiler.transpile(circ, self.backend, **self.transpiler_settings)
sched = compiler.schedule(
transpiled_circuit, self.backend, **self.circuit_scheduler_settings
)
return sched
def _new_circuit(self):
"""Create a new circuit for lazy circuit scheduling."""
return circuit.QuantumCircuit(self.num_qubits)
@_compile_lazy_circuit_before
def append_instruction(self, instruction: instructions.Instruction):
"""Add an instruction to the builder's context schedule.
Args:
instruction: Instruction to append.
"""
self._context_stack[-1].append(instruction)
def append_reference(self, name: str, *extra_keys: str):
"""Add external program as a :class:`~qiskit.pulse.instructions.Reference` instruction.
Args:
name: Name of subroutine.
extra_keys: Assistance keys to uniquely specify the subroutine.
"""
inst = instructions.Reference(name, *extra_keys)
self.append_instruction(inst)
@_compile_lazy_circuit_before
def append_subroutine(self, subroutine: Union[Schedule, ScheduleBlock]):
"""Append a :class:`ScheduleBlock` to the builder's context schedule.
This operation doesn't create a reference. Subroutine is directly
appended to current context schedule.
Args:
subroutine: ScheduleBlock to append to the current context block.
Raises:
PulseError: When subroutine is not Schedule nor ScheduleBlock.
"""
if not isinstance(subroutine, (ScheduleBlock, Schedule)):
raise exceptions.PulseError(
f"'{subroutine.__class__.__name__}' is not valid data format in the builder. "
"'Schedule' and 'ScheduleBlock' can be appended to the builder context."
)
if len(subroutine) == 0:
return
if isinstance(subroutine, Schedule):
subroutine = self._naive_typecast_schedule(subroutine)
self._context_stack[-1].append(subroutine)
@singledispatchmethod
def call_subroutine(
self,
subroutine: Union[circuit.QuantumCircuit, Schedule, ScheduleBlock],
name: Optional[str] = None,
value_dict: Optional[Dict[ParameterExpression, ParameterValueType]] = None,
**kw_params: ParameterValueType,
):
"""Call a schedule or circuit defined outside of the current scope.
The ``subroutine`` is appended to the context schedule as a call instruction.
This logic just generates a convenient program representation in the compiler.
Thus, this doesn't affect execution of inline subroutines.
See :class:`~pulse.instructions.Call` for more details.
Args:
subroutine: Target schedule or circuit to append to the current context.
name: Name of subroutine if defined.
value_dict: Parameter object and assigned value mapping. This is more precise way to
identify a parameter since mapping is managed with unique object id rather than
name. Especially there is any name collision in a parameter table.
kw_params: Parameter values to bind to the target subroutine
with string parameter names. If there are parameter name overlapping,
these parameters are updated with the same assigned value.
Raises:
PulseError:
- When input subroutine is not valid data format.
"""
raise exceptions.PulseError(
f"Subroutine type {subroutine.__class__.__name__} is "
"not valid data format. Call QuantumCircuit, "
"Schedule, or ScheduleBlock."
)
@call_subroutine.register
def _(
self,
target_block: ScheduleBlock,
name: Optional[str] = None,
value_dict: Optional[Dict[ParameterExpression, ParameterValueType]] = None,
**kw_params: ParameterValueType,
):
if len(target_block) == 0:
return
# Create local parameter assignment
local_assignment = {}
for param_name, value in kw_params.items():
params = target_block.get_parameters(param_name)
if not params:
raise exceptions.PulseError(
f"Parameter {param_name} is not defined in the target subroutine. "
f'{", ".join(map(str, target_block.parameters))} can be specified.'
)
for param in params:
local_assignment[param] = value
if value_dict:
if local_assignment.keys() & value_dict.keys():
warnings.warn(
"Some parameters provided by 'value_dict' conflict with one through "
"keyword arguments. Parameter values in the keyword arguments "
"are overridden by the dictionary values.",
UserWarning,
)
local_assignment.update(value_dict)
if local_assignment:
target_block = target_block.assign_parameters(local_assignment, inplace=False)
if name is None:
# Add unique string, not to accidentally override existing reference entry.
keys = (target_block.name, uuid.uuid4().hex)
else:
keys = (name,)
self.append_reference(*keys)
self.get_context().assign_references({keys: target_block}, inplace=True)
@call_subroutine.register
def _(
self,
target_schedule: Schedule,
name: Optional[str] = None,
value_dict: Optional[Dict[ParameterExpression, ParameterValueType]] = None,
**kw_params: ParameterValueType,
):
if len(target_schedule) == 0:
return
self.call_subroutine(
self._naive_typecast_schedule(target_schedule),
name=name,
value_dict=value_dict,
**kw_params,
)
@call_subroutine.register
def _(
self,
target_circuit: circuit.QuantumCircuit,
name: Optional[str] = None,
value_dict: Optional[Dict[ParameterExpression, ParameterValueType]] = None,
**kw_params: ParameterValueType,
):
if len(target_circuit) == 0:
return
self._compile_lazy_circuit()
self.call_subroutine(
self._compile_circuit(target_circuit),
name=name,
value_dict=value_dict,
**kw_params,
)
@_requires_backend
def call_gate(self, gate: circuit.Gate, qubits: Tuple[int, ...], lazy: bool = True):
"""Call the circuit ``gate`` in the pulse program.
The qubits are assumed to be defined on physical qubits.
If ``lazy == True`` this circuit will extend a lazily constructed
quantum circuit. When an operation occurs that breaks the underlying
circuit scheduling assumptions such as adding a pulse instruction or
changing the alignment context the circuit will be
transpiled and scheduled into pulses with the current active settings.
Args:
gate: Gate to call.
qubits: Qubits to call gate on.
lazy: If false the circuit will be transpiled and pulse scheduled
immediately. Otherwise, it will extend the active lazy circuit
as defined above.
"""
try:
iter(qubits)
except TypeError:
qubits = (qubits,)
if lazy:
self._call_gate(gate, qubits)
else:
self._compile_lazy_circuit()
self._call_gate(gate, qubits)
self._compile_lazy_circuit()
def _call_gate(self, gate, qargs):
if self._lazy_circuit is None:
self._lazy_circuit = self._new_circuit()
self._lazy_circuit.append(gate, qargs=qargs)
@staticmethod
def _naive_typecast_schedule(schedule: Schedule):
# Naively convert into ScheduleBlock
from qiskit.pulse.transforms import inline_subroutines, flatten, pad
preprocessed_schedule = inline_subroutines(flatten(schedule))
pad(preprocessed_schedule, inplace=True, pad_with=instructions.TimeBlockade)
# default to left alignment, namely ASAP scheduling
target_block = ScheduleBlock(name=schedule.name)
for _, inst in preprocessed_schedule.instructions:
target_block.append(inst, inplace=True)
return target_block
def get_dt(self):
"""Retrieve dt differently based on the type of Backend"""
if isinstance(self.backend, BackendV2):
return self.backend.dt
return self.backend.configuration().dt
def build(
backend=None,
schedule: Optional[ScheduleBlock] = None,
name: Optional[str] = None,
default_alignment: Optional[Union[str, AlignmentKind]] = "left",
default_transpiler_settings: Optional[Dict[str, Any]] = None,
default_circuit_scheduler_settings: Optional[Dict[str, Any]] = None,
) -> ContextManager[ScheduleBlock]:
"""Create a context manager for launching the imperative pulse builder DSL.
To enter a building context and starting building a pulse program:
.. code-block::
from qiskit import execute, pulse
from qiskit.providers.fake_provider import FakeOpenPulse2Q
backend = FakeOpenPulse2Q()
d0 = pulse.DriveChannel(0)
with pulse.build() as pulse_prog:
pulse.play(pulse.Constant(100, 0.5), d0)
While the output program ``pulse_prog`` cannot be executed as we are using
a mock backend. If a real backend is being used, executing the program is
done with:
.. code-block:: python
qiskit.execute(pulse_prog, backend)
Args:
backend (Backend): A Qiskit backend. If not supplied certain
builder functionality will be unavailable.
schedule: A pulse ``ScheduleBlock`` in which your pulse program will be built.
name: Name of pulse program to be built.
default_alignment: Default scheduling alignment for builder.
One of ``left``, ``right``, ``sequential`` or an alignment context.
default_transpiler_settings: Default settings for the transpiler.
default_circuit_scheduler_settings: Default settings for the
circuit to pulse scheduler.
Returns:
A new builder context which has the active builder initialized.
"""
return _PulseBuilder(
backend=backend,
block=schedule,
name=name,
default_alignment=default_alignment,
default_transpiler_settings=default_transpiler_settings,
default_circuit_scheduler_settings=default_circuit_scheduler_settings,
)
# Builder Utilities
def _active_builder() -> _PulseBuilder:
"""Get the active builder in the active context.
Returns:
The active active builder in this context.
Raises:
exceptions.NoActiveBuilder: If a pulse builder function is called
outside of a builder context.
"""
try:
return BUILDER_CONTEXTVAR.get()
except LookupError as ex:
raise exceptions.NoActiveBuilder(
"A Pulse builder function was called outside of "
"a builder context. Try calling within a builder "
'context, eg., "with pulse.build() as schedule: ...".'
) from ex
def active_backend():
"""Get the backend of the currently active builder context.
Returns:
Backend: The active backend in the currently active
builder context.
Raises:
exceptions.BackendNotSet: If the builder does not have a backend set.
"""
builder = _active_builder().backend
if builder is None:
raise exceptions.BackendNotSet(
'This function requires the active builder to have a "backend" set.'
)
return builder
def append_schedule(schedule: Union[Schedule, ScheduleBlock]):
"""Call a schedule by appending to the active builder's context block.
Args:
schedule: Schedule or ScheduleBlock to append.
"""
_active_builder().append_subroutine(schedule)
def append_instruction(instruction: instructions.Instruction):
"""Append an instruction to the active builder's context schedule.
Examples:
.. code-block::
from qiskit import pulse
d0 = pulse.DriveChannel(0)
with pulse.build() as pulse_prog:
pulse.builder.append_instruction(pulse.Delay(10, d0))
print(pulse_prog.instructions)
.. parsed-literal::
((0, Delay(10, DriveChannel(0))),)
"""
_active_builder().append_instruction(instruction)
def num_qubits() -> int:
"""Return number of qubits in the currently active backend.
Examples:
.. code-block::
from qiskit import pulse
from qiskit.providers.fake_provider import FakeOpenPulse2Q
backend = FakeOpenPulse2Q()
with pulse.build(backend):
print(pulse.num_qubits())
.. parsed-literal::
2
.. note:: Requires the active builder context to have a backend set.
"""
if isinstance(active_backend(), BackendV2):
return active_backend().num_qubits
return active_backend().configuration().n_qubits
def seconds_to_samples(seconds: Union[float, np.ndarray]) -> Union[int, np.ndarray]:
"""Obtain the number of samples that will elapse in ``seconds`` on the
active backend.
Rounds down.
Args:
seconds: Time in seconds to convert to samples.
Returns:
The number of samples for the time to elapse
"""
dt = _active_builder().get_dt()
if isinstance(seconds, np.ndarray):
return (seconds / dt).astype(int)
return int(seconds / dt)
def samples_to_seconds(samples: Union[int, np.ndarray]) -> Union[float, np.ndarray]:
"""Obtain the time in seconds that will elapse for the input number of
samples on the active backend.
Args:
samples: Number of samples to convert to time in seconds.
Returns:
The time that elapses in ``samples``.
"""
return samples * _active_builder().get_dt()
def qubit_channels(qubit: int) -> Set[chans.Channel]:
"""Returns the set of channels associated with a qubit.
Examples:
.. code-block::
from qiskit import pulse
from qiskit.providers.fake_provider import FakeOpenPulse2Q
backend = FakeOpenPulse2Q()
with pulse.build(backend):
print(pulse.qubit_channels(0))
.. parsed-literal::
{MeasureChannel(0), ControlChannel(0), DriveChannel(0), AcquireChannel(0), ControlChannel(1)}
.. note:: Requires the active builder context to have a backend set.
.. note:: A channel may still be associated with another qubit in this list
such as in the case where significant crosstalk exists.
"""
# implement as the inner function to avoid API change for a patch release in 0.24.2.
def get_qubit_channels_v2(backend: BackendV2, qubit: int):
r"""Return a list of channels which operate on the given ``qubit``.
Returns:
List of ``Channel``\s operated on my the given ``qubit``.
"""
channels = []
# add multi-qubit channels
for node_qubits in backend.coupling_map:
if qubit in node_qubits:
control_channel = backend.control_channel(node_qubits)
if control_channel:
channels.extend(control_channel)
# add single qubit channels
channels.append(backend.drive_channel(qubit))
channels.append(backend.measure_channel(qubit))
channels.append(backend.acquire_channel(qubit))
return channels
# backendV2
if isinstance(active_backend(), BackendV2):
return set(get_qubit_channels_v2(active_backend(), qubit))
return set(active_backend().configuration().get_qubit_channels(qubit))
def _qubits_to_channels(*channels_or_qubits: Union[int, chans.Channel]) -> Set[chans.Channel]:
"""Returns the unique channels of the input qubits."""
channels = set()
for channel_or_qubit in channels_or_qubits:
if isinstance(channel_or_qubit, int):
channels |= qubit_channels(channel_or_qubit)
elif isinstance(channel_or_qubit, chans.Channel):
channels.add(channel_or_qubit)
else:
raise exceptions.PulseError(
f'{channel_or_qubit} is not a "Channel" or qubit (integer).'
)
return channels
def active_transpiler_settings() -> Dict[str, Any]:
"""Return the current active builder context's transpiler settings.
Examples:
.. code-block::
from qiskit import pulse
from qiskit.providers.fake_provider import FakeOpenPulse2Q
backend = FakeOpenPulse2Q()
transpiler_settings = {'optimization_level': 3}
with pulse.build(backend,
default_transpiler_settings=transpiler_settings):
print(pulse.active_transpiler_settings())
.. parsed-literal::
{'optimization_level': 3}
"""
return dict(_active_builder().transpiler_settings)
def active_circuit_scheduler_settings() -> Dict[str, Any]:
"""Return the current active builder context's circuit scheduler settings.
Examples:
.. code-block::
from qiskit import pulse
from qiskit.providers.fake_provider import FakeOpenPulse2Q
backend = FakeOpenPulse2Q()
circuit_scheduler_settings = {'method': 'alap'}
with pulse.build(
backend,
default_circuit_scheduler_settings=circuit_scheduler_settings):
print(pulse.active_circuit_scheduler_settings())
.. parsed-literal::
{'method': 'alap'}
"""
return dict(_active_builder().circuit_scheduler_settings)
# Contexts
@contextmanager
def align_left() -> ContextManager[None]:
"""Left alignment pulse scheduling context.
Pulse instructions within this context are scheduled as early as possible
by shifting them left to the earliest available time.
Examples:
.. code-block::
from qiskit import pulse
d0 = pulse.DriveChannel(0)
d1 = pulse.DriveChannel(1)
with pulse.build() as pulse_prog:
with pulse.align_left():
# this pulse will start at t=0
pulse.play(pulse.Constant(100, 1.0), d0)
# this pulse will start at t=0
pulse.play(pulse.Constant(20, 1.0), d1)
pulse_prog = pulse.transforms.block_to_schedule(pulse_prog)
assert pulse_prog.ch_start_time(d0) == pulse_prog.ch_start_time(d1)
Yields:
None
"""
builder = _active_builder()
builder.push_context(transforms.AlignLeft())
try:
yield
finally:
current = builder.pop_context()
builder.append_subroutine(current)
@contextmanager
def align_right() -> AlignmentKind:
"""Right alignment pulse scheduling context.
Pulse instructions within this context are scheduled as late as possible
by shifting them right to the latest available time.
Examples:
.. code-block::
from qiskit import pulse
d0 = pulse.DriveChannel(0)
d1 = pulse.DriveChannel(1)
with pulse.build() as pulse_prog:
with pulse.align_right():
# this pulse will start at t=0
pulse.play(pulse.Constant(100, 1.0), d0)
# this pulse will start at t=80
pulse.play(pulse.Constant(20, 1.0), d1)
pulse_prog = pulse.transforms.block_to_schedule(pulse_prog)
assert pulse_prog.ch_stop_time(d0) == pulse_prog.ch_stop_time(d1)
Yields:
None
"""
builder = _active_builder()
builder.push_context(transforms.AlignRight())
try:
yield
finally:
current = builder.pop_context()
builder.append_subroutine(current)
@contextmanager
def align_sequential() -> AlignmentKind:
"""Sequential alignment pulse scheduling context.
Pulse instructions within this context are scheduled sequentially in time
such that no two instructions will be played at the same time.
Examples:
.. code-block::
from qiskit import pulse
d0 = pulse.DriveChannel(0)
d1 = pulse.DriveChannel(1)
with pulse.build() as pulse_prog:
with pulse.align_sequential():
# this pulse will start at t=0
pulse.play(pulse.Constant(100, 1.0), d0)
# this pulse will also start at t=100
pulse.play(pulse.Constant(20, 1.0), d1)
pulse_prog = pulse.transforms.block_to_schedule(pulse_prog)
assert pulse_prog.ch_stop_time(d0) == pulse_prog.ch_start_time(d1)
Yields:
None
"""
builder = _active_builder()
builder.push_context(transforms.AlignSequential())
try:
yield
finally:
current = builder.pop_context()
builder.append_subroutine(current)
@contextmanager
def align_equispaced(duration: Union[int, ParameterExpression]) -> AlignmentKind:
"""Equispaced alignment pulse scheduling context.
Pulse instructions within this context are scheduled with the same interval spacing such that
the total length of the context block is ``duration``.
If the total free ``duration`` cannot be evenly divided by the number of instructions
within the context, the modulo is split and then prepended and appended to
the returned schedule. Delay instructions are automatically inserted in between pulses.
This context is convenient to write a schedule for periodical dynamic decoupling or
the Hahn echo sequence.
Examples:
.. plot::
:include-source:
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()
Args:
duration: Duration of this context. This should be larger than the schedule duration.
Yields:
None
Notes:
The scheduling is performed for sub-schedules within the context rather than
channel-wise. If you want to apply the equispaced context for each channel,
you should use the context independently for channels.
"""
builder = _active_builder()
builder.push_context(transforms.AlignEquispaced(duration=duration))
try:
yield
finally:
current = builder.pop_context()
builder.append_subroutine(current)
@contextmanager
def align_func(
duration: Union[int, ParameterExpression], func: Callable[[int], float]
) -> AlignmentKind:
"""Callback defined alignment pulse scheduling context.
Pulse instructions within this context are scheduled at the location specified by
arbitrary callback function `position` that takes integer index and returns
the associated fractional location within [0, 1].
Delay instruction is automatically inserted in between pulses.
This context may be convenient to write a schedule of arbitrary dynamical decoupling
sequences such as Uhrig dynamical decoupling.
Examples:
.. plot::
:include-source:
import numpy as np
from qiskit import pulse
d0 = pulse.DriveChannel(0)
x90 = pulse.Gaussian(10, 0.1, 3)
x180 = pulse.Gaussian(10, 0.2, 3)
def udd10_pos(j):
return np.sin(np.pi*j/(2*10 + 2))**2
with pulse.build() as udd_sched:
pulse.play(x90, d0)
with pulse.align_func(duration=300, func=udd10_pos):
for _ in range(10):
pulse.play(x180, d0)
pulse.play(x90, d0)
udd_sched.draw()
Args:
duration: Duration of context. This should be larger than the schedule duration.
func: A function that takes an index of sub-schedule and returns the
fractional coordinate of of that sub-schedule.
The returned value should be defined within [0, 1].
The pulse index starts from 1.
Yields:
None
Notes:
The scheduling is performed for sub-schedules within the context rather than
channel-wise. If you want to apply the numerical context for each channel,
you need to apply the context independently to channels.
"""
builder = _active_builder()
builder.push_context(transforms.AlignFunc(duration=duration, func=func))
try:
yield
finally:
current = builder.pop_context()
builder.append_subroutine(current)
@contextmanager
def general_transforms(alignment_context: AlignmentKind) -> ContextManager[None]:
"""Arbitrary alignment transformation defined by a subclass instance of
:class:`~qiskit.pulse.transforms.alignments.AlignmentKind`.
Args:
alignment_context: Alignment context instance that defines schedule transformation.
Yields:
None
Raises:
PulseError: When input ``alignment_context`` is not ``AlignmentKind`` subclasses.
"""
if not isinstance(alignment_context, AlignmentKind):
raise exceptions.PulseError("Input alignment context is not `AlignmentKind` subclass.")
builder = _active_builder()
builder.push_context(alignment_context)
try:
yield
finally:
current = builder.pop_context()
builder.append_subroutine(current)
@contextmanager
def transpiler_settings(**settings) -> ContextManager[None]:
"""Set the currently active transpiler settings for this context.
Examples:
.. code-block::
from qiskit import pulse
from qiskit.providers.fake_provider import FakeOpenPulse2Q
backend = FakeOpenPulse2Q()
with pulse.build(backend):
print(pulse.active_transpiler_settings())
with pulse.transpiler_settings(optimization_level=3):
print(pulse.active_transpiler_settings())
.. parsed-literal::
{}
{'optimization_level': 3}
"""
builder = _active_builder()
curr_transpiler_settings = builder.transpiler_settings
builder.transpiler_settings = collections.ChainMap(settings, curr_transpiler_settings)
try:
yield
finally:
builder.transpiler_settings = curr_transpiler_settings
@contextmanager
def circuit_scheduler_settings(**settings) -> ContextManager[None]:
"""Set the currently active circuit scheduler settings for this context.
Examples:
.. code-block::
from qiskit import pulse
from qiskit.providers.fake_provider import FakeOpenPulse2Q
backend = FakeOpenPulse2Q()
with pulse.build(backend):
print(pulse.active_circuit_scheduler_settings())
with pulse.circuit_scheduler_settings(method='alap'):
print(pulse.active_circuit_scheduler_settings())
.. parsed-literal::
{}
{'method': 'alap'}
"""
builder = _active_builder()
curr_circuit_scheduler_settings = builder.circuit_scheduler_settings
builder.circuit_scheduler_settings = collections.ChainMap(
settings, curr_circuit_scheduler_settings
)
try:
yield
finally:
builder.circuit_scheduler_settings = curr_circuit_scheduler_settings
@contextmanager
def phase_offset(phase: float, *channels: chans.PulseChannel) -> ContextManager[None]:
"""Shift the phase of input channels on entry into context and undo on exit.
Examples:
.. code-block::
import math
from qiskit import pulse
d0 = pulse.DriveChannel(0)
with pulse.build() as pulse_prog:
with pulse.phase_offset(math.pi, d0):
pulse.play(pulse.Constant(10, 1.0), d0)
assert len(pulse_prog.instructions) == 3
Args:
phase: Amount of phase offset in radians.
channels: Channels to offset phase of.
Yields:
None
"""
for channel in channels:
shift_phase(phase, channel)
try:
yield
finally:
for channel in channels:
shift_phase(-phase, channel)
@contextmanager
def frequency_offset(
frequency: float, *channels: chans.PulseChannel, compensate_phase: bool = False
) -> ContextManager[None]:
"""Shift the frequency of inputs channels on entry into context and undo on exit.
Examples:
.. code-block:: python
:emphasize-lines: 7, 16
from qiskit import pulse
d0 = pulse.DriveChannel(0)
with pulse.build(backend) as pulse_prog:
# shift frequency by 1GHz
with pulse.frequency_offset(1e9, d0):
pulse.play(pulse.Constant(10, 1.0), d0)
assert len(pulse_prog.instructions) == 3
with pulse.build(backend) as pulse_prog:
# Shift frequency by 1GHz.
# Undo accumulated phase in the shifted frequency frame
# when exiting the context.
with pulse.frequency_offset(1e9, d0, compensate_phase=True):
pulse.play(pulse.Constant(10, 1.0), d0)
assert len(pulse_prog.instructions) == 4
Args:
frequency: Amount of frequency offset in Hz.
channels: Channels to offset frequency of.
compensate_phase: Compensate for accumulated phase accumulated with
respect to the channels' frame at its initial frequency.
Yields:
None
"""
builder = _active_builder()
# TODO: Need proper implementation of compensation. t0 may depend on the parent context.
# For example, the instruction position within the equispaced context depends on
# the current total number of instructions, thus adding more instruction after
# offset context may change the t0 when the parent context is transformed.
t0 = builder.get_context().duration
for channel in channels:
shift_frequency(frequency, channel)
try:
yield
finally:
if compensate_phase:
duration = builder.get_context().duration - t0
accumulated_phase = 2 * np.pi * ((duration * builder.get_dt() * frequency) % 1)
for channel in channels:
shift_phase(-accumulated_phase, channel)
for channel in channels:
shift_frequency(-frequency, channel)
# Channels
def drive_channel(qubit: int) -> chans.DriveChannel:
"""Return ``DriveChannel`` for ``qubit`` on the active builder backend.
Examples:
.. code-block::
from qiskit import pulse
from qiskit.providers.fake_provider import FakeOpenPulse2Q
backend = FakeOpenPulse2Q()
with pulse.build(backend):
assert pulse.drive_channel(0) == pulse.DriveChannel(0)
.. note:: Requires the active builder context to have a backend set.
"""
# backendV2
if isinstance(active_backend(), BackendV2):
return active_backend().drive_channel(qubit)
return active_backend().configuration().drive(qubit)
def measure_channel(qubit: int) -> chans.MeasureChannel:
"""Return ``MeasureChannel`` for ``qubit`` on the active builder backend.
Examples:
.. code-block::
from qiskit import pulse
from qiskit.providers.fake_provider import FakeOpenPulse2Q
backend = FakeOpenPulse2Q()
with pulse.build(backend):
assert pulse.measure_channel(0) == pulse.MeasureChannel(0)
.. note:: Requires the active builder context to have a backend set.
"""
# backendV2
if isinstance(active_backend(), BackendV2):
return active_backend().measure_channel(qubit)
return active_backend().configuration().measure(qubit)
def acquire_channel(qubit: int) -> chans.AcquireChannel:
"""Return ``AcquireChannel`` for ``qubit`` on the active builder backend.
Examples:
.. code-block::
from qiskit import pulse
from qiskit.providers.fake_provider import FakeOpenPulse2Q
backend = FakeOpenPulse2Q()
with pulse.build(backend):
assert pulse.acquire_channel(0) == pulse.AcquireChannel(0)
.. note:: Requires the active builder context to have a backend set.
"""
# backendV2
if isinstance(active_backend(), BackendV2):
return active_backend().acquire_channel(qubit)
return active_backend().configuration().acquire(qubit)
def control_channels(*qubits: Iterable[int]) -> List[chans.ControlChannel]:
"""Return ``ControlChannel`` for ``qubit`` on the active builder backend.
Return the secondary drive channel for the given qubit -- typically
utilized for controlling multi-qubit interactions.
Examples:
.. code-block::
from qiskit import pulse
from qiskit.providers.fake_provider import FakeOpenPulse2Q
backend = FakeOpenPulse2Q()
with pulse.build(backend):
assert pulse.control_channels(0, 1) == [pulse.ControlChannel(0)]
.. note:: Requires the active builder context to have a backend set.
Args:
qubits: Tuple or list of ordered qubits of the form
`(control_qubit, target_qubit)`.
Returns:
List of control channels associated with the supplied ordered list
of qubits.
"""
# backendV2
if isinstance(active_backend(), BackendV2):
return active_backend().control_channel(qubits)
return active_backend().configuration().control(qubits=qubits)
# Base Instructions
def delay(duration: int, channel: chans.Channel, name: Optional[str] = None):
"""Delay on a ``channel`` for a ``duration``.
Examples:
.. code-block::
from qiskit import pulse
d0 = pulse.DriveChannel(0)
with pulse.build() as pulse_prog:
pulse.delay(10, d0)
Args:
duration: Number of cycles to delay for on ``channel``.
channel: Channel to delay on.
name: Name of the instruction.
"""
append_instruction(instructions.Delay(duration, channel, name=name))
def play(
pulse: Union[library.Pulse, np.ndarray], channel: chans.PulseChannel, name: Optional[str] = None
):
"""Play a ``pulse`` on a ``channel``.
Examples:
.. code-block::
from qiskit import pulse
d0 = pulse.DriveChannel(0)
with pulse.build() as pulse_prog:
pulse.play(pulse.Constant(10, 1.0), d0)
Args:
pulse: Pulse to play.
channel: Channel to play pulse on.
name: Name of the pulse.
"""
if not isinstance(pulse, library.Pulse):
pulse = library.Waveform(pulse)
append_instruction(instructions.Play(pulse, channel, name=name))
def acquire(
duration: int,
qubit_or_channel: Union[int, chans.AcquireChannel],
register: StorageLocation,
**metadata: Union[configuration.Kernel, configuration.Discriminator],
):
"""Acquire for a ``duration`` on a ``channel`` and store the result
in a ``register``.
Examples:
.. code-block::
from qiskit import pulse
acq0 = pulse.AcquireChannel(0)
mem0 = pulse.MemorySlot(0)
with pulse.build() as pulse_prog:
pulse.acquire(100, acq0, mem0)
# measurement metadata
kernel = pulse.configuration.Kernel('linear_discriminator')
pulse.acquire(100, acq0, mem0, kernel=kernel)
.. note:: The type of data acquire will depend on the execution ``meas_level``.
Args:
duration: Duration to acquire data for
qubit_or_channel: Either the qubit to acquire data for or the specific
:class:`~qiskit.pulse.channels.AcquireChannel` to acquire on.
register: Location to store measured result.
metadata: Additional metadata for measurement. See
:class:`~qiskit.pulse.instructions.Acquire` for more information.
Raises:
exceptions.PulseError: If the register type is not supported.
"""
if isinstance(qubit_or_channel, int):
qubit_or_channel = chans.AcquireChannel(qubit_or_channel)
if isinstance(register, chans.MemorySlot):
append_instruction(
instructions.Acquire(duration, qubit_or_channel, mem_slot=register, **metadata)
)
elif isinstance(register, chans.RegisterSlot):
append_instruction(
instructions.Acquire(duration, qubit_or_channel, reg_slot=register, **metadata)
)
else:
raise exceptions.PulseError(f'Register of type: "{type(register)}" is not supported')
def set_frequency(frequency: float, channel: chans.PulseChannel, name: Optional[str] = None):
"""Set the ``frequency`` of a pulse ``channel``.
Examples:
.. code-block::
from qiskit import pulse
d0 = pulse.DriveChannel(0)
with pulse.build() as pulse_prog:
pulse.set_frequency(1e9, d0)
Args:
frequency: Frequency in Hz to set channel to.
channel: Channel to set frequency of.
name: Name of the instruction.
"""
append_instruction(instructions.SetFrequency(frequency, channel, name=name))
def shift_frequency(frequency: float, channel: chans.PulseChannel, name: Optional[str] = None):
"""Shift the ``frequency`` of a pulse ``channel``.
Examples:
.. code-block:: python
:emphasize-lines: 6
from qiskit import pulse
d0 = pulse.DriveChannel(0)
with pulse.build() as pulse_prog:
pulse.shift_frequency(1e9, d0)
Args:
frequency: Frequency in Hz to shift channel frequency by.
channel: Channel to shift frequency of.
name: Name of the instruction.
"""
append_instruction(instructions.ShiftFrequency(frequency, channel, name=name))
def set_phase(phase: float, channel: chans.PulseChannel, name: Optional[str] = None):
"""Set the ``phase`` of a pulse ``channel``.
Examples:
.. code-block:: python
:emphasize-lines: 8
import math
from qiskit import pulse
d0 = pulse.DriveChannel(0)
with pulse.build() as pulse_prog:
pulse.set_phase(math.pi, d0)
Args:
phase: Phase in radians to set channel carrier signal to.
channel: Channel to set phase of.
name: Name of the instruction.
"""
append_instruction(instructions.SetPhase(phase, channel, name=name))
def shift_phase(phase: float, channel: chans.PulseChannel, name: Optional[str] = None):
"""Shift the ``phase`` of a pulse ``channel``.
Examples:
.. code-block::
import math
from qiskit import pulse
d0 = pulse.DriveChannel(0)
with pulse.build() as pulse_prog:
pulse.shift_phase(math.pi, d0)
Args:
phase: Phase in radians to shift channel carrier signal by.
channel: Channel to shift phase of.
name: Name of the instruction.
"""
append_instruction(instructions.ShiftPhase(phase, channel, name))
def snapshot(label: str, snapshot_type: str = "statevector"):
"""Simulator snapshot.
Examples:
.. code-block::
from qiskit import pulse
with pulse.build() as pulse_prog:
pulse.snapshot('first', 'statevector')
Args:
label: Label for snapshot.
snapshot_type: Type of snapshot.
"""
append_instruction(instructions.Snapshot(label, snapshot_type=snapshot_type))
def call(
target: Optional[Union[circuit.QuantumCircuit, Schedule, ScheduleBlock]],
name: Optional[str] = None,
value_dict: Optional[Dict[ParameterValueType, ParameterValueType]] = None,
**kw_params: ParameterValueType,
):
"""Call the subroutine within the currently active builder context with arbitrary
parameters which will be assigned to the target program.
.. note::
If the ``target`` program is a :class:`.ScheduleBlock`, then a :class:`.Reference`
instruction will be created and appended to the current context.
The ``target`` program will be immediately assigned to the current scope as a subroutine.
If the ``target`` program is :class:`.Schedule`, it will be wrapped by the
:class:`.Call` instruction and appended to the current context to avoid
a mixed representation of :class:`.ScheduleBlock` and :class:`.Schedule`.
If the ``target`` program is a :class:`.QuantumCircuit` it will be scheduled
and the new :class:`.Schedule` will be added as a :class:`.Call` instruction.
Examples:
1. Calling a schedule block (recommended)
.. code-block::
from qiskit import circuit, pulse
from qiskit.providers.fake_provider import FakeBogotaV2
backend = FakeBogotaV2()
with pulse.build() as x_sched:
pulse.play(pulse.Gaussian(160, 0.1, 40), pulse.DriveChannel(0))
with pulse.build() as pulse_prog:
pulse.call(x_sched)
print(pulse_prog)
.. parsed-literal::
ScheduleBlock(
ScheduleBlock(
Play(
Gaussian(duration=160, amp=(0.1+0j), sigma=40),
DriveChannel(0)
),
name="block0",
transform=AlignLeft()
),
name="block1",
transform=AlignLeft()
)
The actual program is stored in the reference table attached to the schedule.
.. code-block::
print(pulse_prog.references)
.. parsed-literal::
ReferenceManager:
- ('block0', '634b3b50bd684e26a673af1fbd2d6c81'): ScheduleBlock(Play(Gaussian(...
In addition, you can call a parameterized target program with parameter assignment.
.. code-block::
amp = circuit.Parameter("amp")
with pulse.build() as subroutine:
pulse.play(pulse.Gaussian(160, amp, 40), pulse.DriveChannel(0))
with pulse.build() as pulse_prog:
pulse.call(subroutine, amp=0.1)
pulse.call(subroutine, amp=0.3)
print(pulse_prog)
.. parsed-literal::
ScheduleBlock(
ScheduleBlock(
Play(
Gaussian(duration=160, amp=(0.1+0j), sigma=40),
DriveChannel(0)
),
name="block2",
transform=AlignLeft()
),
ScheduleBlock(
Play(
Gaussian(duration=160, amp=(0.3+0j), sigma=40),
DriveChannel(0)
),
name="block2",
transform=AlignLeft()
),
name="block3",
transform=AlignLeft()
)
If there is a name collision between parameters, you can distinguish them by specifying
each parameter object in a python dictionary. For example,
.. code-block::
amp1 = circuit.Parameter('amp')
amp2 = circuit.Parameter('amp')
with pulse.build() as subroutine:
pulse.play(pulse.Gaussian(160, amp1, 40), pulse.DriveChannel(0))
pulse.play(pulse.Gaussian(160, amp2, 40), pulse.DriveChannel(1))
with pulse.build() as pulse_prog:
pulse.call(subroutine, value_dict={amp1: 0.1, amp2: 0.3})
print(pulse_prog)
.. parsed-literal::
ScheduleBlock(
ScheduleBlock(
Play(Gaussian(duration=160, amp=(0.1+0j), sigma=40), DriveChannel(0)),
Play(Gaussian(duration=160, amp=(0.3+0j), sigma=40), DriveChannel(1)),
name="block4",
transform=AlignLeft()
),
name="block5",
transform=AlignLeft()
)
2. Calling a schedule
.. code-block::
x_sched = backend.instruction_schedule_map.get("x", (0,))
with pulse.build(backend) as pulse_prog:
pulse.call(x_sched)
print(pulse_prog)
.. parsed-literal::
ScheduleBlock(
Call(
Schedule(
(
0,
Play(
Drag(
duration=160,
amp=(0.18989731546729305+0j),
sigma=40,
beta=-1.201258305015517,
name='drag_86a8'
),
DriveChannel(0),
name='drag_86a8'
)
),
name="x"
),
name='x'
),
name="block6",
transform=AlignLeft()
)
Currently, the backend calibrated gates are provided in the form of :class:`~.Schedule`.
The parameter assignment mechanism is available also for schedules.
However, the called schedule is not treated as a reference.
3. Calling a quantum circuit
.. code-block::
backend = FakeBogotaV2()
qc = circuit.QuantumCircuit(1)
qc.x(0)
with pulse.build(backend) as pulse_prog:
pulse.call(qc)
print(pulse_prog)
.. parsed-literal::
ScheduleBlock(
Call(
Schedule(
(
0,
Play(
Drag(
duration=160,
amp=(0.18989731546729305+0j),
sigma=40,
beta=-1.201258305015517,
name='drag_86a8'
),
DriveChannel(0),
name='drag_86a8'
)
),
name="circuit-87"
),
name='circuit-87'
),
name="block7",
transform=AlignLeft()
)
.. warning::
Calling a circuit from a schedule is not encouraged. Currently, the Qiskit execution model
is migrating toward the pulse gate model, where schedules are attached to
circuits through the :meth:`.QuantumCircuit.add_calibration` method.
Args:
target: Target circuit or pulse schedule to call.
name: Optional. A unique name of subroutine if defined. When the name is explicitly
provided, one cannot call different schedule blocks with the same name.
value_dict: Optional. Parameters assigned to the ``target`` program.
If this dictionary is provided, the ``target`` program is copied and
then stored in the main built schedule and its parameters are assigned to the given values.
This dictionary is keyed on :class:`~.Parameter` objects,
allowing parameter name collision to be avoided.
kw_params: Alternative way to provide parameters.
Since this is keyed on the string parameter name,
the parameters having the same name are all updated together.
If you want to avoid name collision, use ``value_dict`` with :class:`~.Parameter`
objects instead.
"""
_active_builder().call_subroutine(target, name, value_dict, **kw_params)
def reference(name: str, *extra_keys: str):
"""Refer to undefined subroutine by string keys.
A :class:`~qiskit.pulse.instructions.Reference` instruction is implicitly created
and a schedule can be separately registered to the reference at a later stage.
.. code-block:: python
from qiskit import pulse
with pulse.build() as main_prog:
pulse.reference("x_gate", "q0")
with pulse.build() as subroutine:
pulse.play(pulse.Gaussian(160, 0.1, 40), pulse.DriveChannel(0))
main_prog.assign_references(subroutine_dict={("x_gate", "q0"): subroutine})
Args:
name: Name of subroutine.
extra_keys: Helper keys to uniquely specify the subroutine.
"""
_active_builder().append_reference(name, *extra_keys)
# Directives
def barrier(*channels_or_qubits: Union[chans.Channel, int], name: Optional[str] = None):
"""Barrier directive for a set of channels and qubits.
This directive prevents the compiler from moving instructions across
the barrier. Consider the case where we want to enforce that one pulse
happens after another on separate channels, this can be done with:
.. code-block::
from qiskit import pulse
from qiskit.providers.fake_provider import FakeOpenPulse2Q
backend = FakeOpenPulse2Q()
d0 = pulse.DriveChannel(0)
d1 = pulse.DriveChannel(1)
with pulse.build(backend) as barrier_pulse_prog:
pulse.play(pulse.Constant(10, 1.0), d0)
pulse.barrier(d0, d1)
pulse.play(pulse.Constant(10, 1.0), d1)
Of course this could have been accomplished with:
.. code-block::
from qiskit.pulse import transforms
with pulse.build(backend) as aligned_pulse_prog:
with pulse.align_sequential():
pulse.play(pulse.Constant(10, 1.0), d0)
pulse.play(pulse.Constant(10, 1.0), d1)
barrier_pulse_prog = transforms.target_qobj_transform(barrier_pulse_prog)
aligned_pulse_prog = transforms.target_qobj_transform(aligned_pulse_prog)
assert barrier_pulse_prog == aligned_pulse_prog
The barrier allows the pulse compiler to take care of more advanced
scheduling alignment operations across channels. For example
in the case where we are calling an outside circuit or schedule and
want to align a pulse at the end of one call:
.. code-block::
import math
d0 = pulse.DriveChannel(0)
with pulse.build(backend) as pulse_prog:
with pulse.align_right():
pulse.x(1)
# Barrier qubit 1 and d0.
pulse.barrier(1, d0)
# Due to barrier this will play before the gate on qubit 1.
pulse.play(pulse.Constant(10, 1.0), d0)
# This will end at the same time as the pulse above due to
# the barrier.
pulse.x(1)
.. note:: Requires the active builder context to have a backend set if
qubits are barriered on.
Args:
channels_or_qubits: Channels or qubits to barrier.
name: Name for the barrier
"""
channels = _qubits_to_channels(*channels_or_qubits)
if len(channels) > 1:
append_instruction(directives.RelativeBarrier(*channels, name=name))
# Macros
def macro(func: Callable):
"""Wrap a Python function and activate the parent builder context at calling time.
This enables embedding Python functions as builder macros. This generates a new
:class:`pulse.Schedule` that is embedded in the parent builder context with
every call of the decorated macro function. The decorated macro function will
behave as if the function code was embedded inline in the parent builder context
after parameter substitution.
Examples:
.. plot::
:include-source:
from qiskit import pulse
@pulse.macro
def measure(qubit: int):
pulse.play(pulse.GaussianSquare(16384, 256, 15872), pulse.measure_channel(qubit))
mem_slot = pulse.MemorySlot(qubit)
pulse.acquire(16384, pulse.acquire_channel(qubit), mem_slot)
return mem_slot
with pulse.build(backend=backend) as sched:
mem_slot = measure(0)
print(f"Qubit measured into {mem_slot}")
sched.draw()
Args:
func: The Python function to enable as a builder macro. There are no
requirements on the signature of the function, any calls to pulse
builder methods will be added to builder context the wrapped function
is called from.
Returns:
Callable: The wrapped ``func``.
"""
func_name = getattr(func, "__name__", repr(func))
@functools.wraps(func)
def wrapper(*args, **kwargs):
_builder = _active_builder()
# activate the pulse builder before calling the function
with build(backend=_builder.backend, name=func_name) as built:
output = func(*args, **kwargs)
_builder.call_subroutine(built)
return output
return wrapper
def measure(
qubits: Union[List[int], int],
registers: Union[List[StorageLocation], StorageLocation] = None,
) -> Union[List[StorageLocation], StorageLocation]:
"""Measure a qubit within the currently active builder context.
At the pulse level a measurement is composed of both a stimulus pulse and
an acquisition instruction which tells the systems measurement unit to
acquire data and process it. We provide this measurement macro to automate
the process for you, but if desired full control is still available with
:func:`acquire` and :func:`play`.
To use the measurement it is as simple as specifying the qubit you wish to
measure:
.. code-block::
from qiskit import pulse
from qiskit.providers.fake_provider import FakeOpenPulse2Q
backend = FakeOpenPulse2Q()
qubit = 0
with pulse.build(backend) as pulse_prog:
# Do something to the qubit.
qubit_drive_chan = pulse.drive_channel(0)
pulse.play(pulse.Constant(100, 1.0), qubit_drive_chan)
# Measure the qubit.
reg = pulse.measure(qubit)
For now it is not possible to do much with the handle to ``reg`` but in the
future we will support using this handle to a result register to build
up ones program. It is also possible to supply this register:
.. code-block::
with pulse.build(backend) as pulse_prog:
pulse.play(pulse.Constant(100, 1.0), qubit_drive_chan)
# Measure the qubit.
mem0 = pulse.MemorySlot(0)
reg = pulse.measure(qubit, mem0)
assert reg == mem0
.. note:: Requires the active builder context to have a backend set.
Args:
qubits: Physical qubit to measure.
registers: Register to store result in. If not selected the current
behavior is to return the :class:`MemorySlot` with the same
index as ``qubit``. This register will be returned.
Returns:
The ``register`` the qubit measurement result will be stored in.
"""
backend = active_backend()
try:
qubits = list(qubits)
except TypeError:
qubits = [qubits]
if registers is None:
registers = [chans.MemorySlot(qubit) for qubit in qubits]
else:
try:
registers = list(registers)
except TypeError:
registers = [registers]
measure_sched = macros.measure(
qubits=qubits,
backend=backend,
qubit_mem_slots={qubit: register.index for qubit, register in zip(qubits, registers)},
)
# note this is not a subroutine.
# just a macro to automate combination of stimulus and acquisition.
# prepare unique reference name based on qubit and memory slot index.
qubits_repr = "&".join(map(str, qubits))
mslots_repr = "&".join((str(r.index) for r in registers))
_active_builder().call_subroutine(measure_sched, name=f"measure_{qubits_repr}..{mslots_repr}")
if len(qubits) == 1:
return registers[0]
else:
return registers
def measure_all() -> List[chans.MemorySlot]:
r"""Measure all qubits within the currently active builder context.
A simple macro function to measure all of the qubits in the device at the
same time. This is useful for handling device ``meas_map`` and single
measurement constraints.
Examples:
.. code-block::
from qiskit import pulse
from qiskit.providers.fake_provider import FakeOpenPulse2Q
backend = FakeOpenPulse2Q()
with pulse.build(backend) as pulse_prog:
# Measure all qubits and return associated registers.
regs = pulse.measure_all()
.. note::
Requires the active builder context to have a backend set.
Returns:
The ``register``\s the qubit measurement results will be stored in.
"""
backend = active_backend()
qubits = range(num_qubits())
registers = [chans.MemorySlot(qubit) for qubit in qubits]
measure_sched = macros.measure(
qubits=qubits,
backend=backend,
qubit_mem_slots={qubit: qubit for qubit in qubits},
)
# note this is not a subroutine.
# just a macro to automate combination of stimulus and acquisition.
_active_builder().call_subroutine(measure_sched, name="measure_all")
return registers
def delay_qubits(duration: int, *qubits: Union[int, Iterable[int]]):
r"""Insert delays on all of the :class:`channels.Channel`\s that correspond
to the input ``qubits`` at the same time.
Examples:
.. code-block::
from qiskit import pulse
from qiskit.providers.fake_provider import FakeOpenPulse3Q
backend = FakeOpenPulse3Q()
with pulse.build(backend) as pulse_prog:
# Delay for 100 cycles on qubits 0, 1 and 2.
regs = pulse.delay_qubits(100, 0, 1, 2)
.. note:: Requires the active builder context to have a backend set.
Args:
duration: Duration to delay for.
qubits: Physical qubits to delay on. Delays will be inserted based on
the channels returned by :func:`pulse.qubit_channels`.
"""
qubit_chans = set(itertools.chain.from_iterable(qubit_channels(qubit) for qubit in qubits))
with align_left():
for chan in qubit_chans:
delay(duration, chan)
# Gate instructions
def call_gate(gate: circuit.Gate, qubits: Tuple[int, ...], lazy: bool = True):
"""Call a gate and lazily schedule it to its corresponding
pulse instruction.
.. note::
Calling gates directly within the pulse builder namespace will be
deprecated in the future in favor of tight integration with a circuit
builder interface which is under development.
Examples:
.. code-block::
from qiskit import pulse
from qiskit.pulse import builder
from qiskit.circuit.library import standard_gates as gates
from qiskit.providers.fake_provider import FakeOpenPulse2Q
backend = FakeOpenPulse2Q()
with pulse.build(backend) as pulse_prog:
builder.call_gate(gates.CXGate(), (0, 1))
We can see the role of the transpiler in scheduling gates by optimizing
away two consecutive CNOT gates:
.. code-block::
with pulse.build(backend) as pulse_prog:
with pulse.transpiler_settings(optimization_level=3):
builder.call_gate(gates.CXGate(), (0, 1))
builder.call_gate(gates.CXGate(), (0, 1))
assert pulse_prog == pulse.Schedule()
.. note:: If multiple gates are called in a row they may be optimized by
the transpiler, depending on the
:func:`pulse.active_transpiler_settings``.
.. note:: Requires the active builder context to have a backend set.
Args:
gate: Circuit gate instance to call.
qubits: Qubits to call gate on.
lazy: If ``false`` the gate will be compiled immediately, otherwise
it will be added onto a lazily evaluated quantum circuit to be
compiled when the builder is forced to by a circuit assumption
being broken, such as the inclusion of a pulse instruction or
new alignment context.
"""
_active_builder().call_gate(gate, qubits, lazy=lazy)
def cx(control: int, target: int): # pylint: disable=invalid-name
"""Call a :class:`~qiskit.circuit.library.standard_gates.CXGate` on the
input physical qubits.
.. note::
Calling gates directly within the pulse builder namespace will be
deprecated in the future in favor of tight integration with a circuit
builder interface which is under development.
Examples:
.. code-block::
from qiskit import pulse
from qiskit.providers.fake_provider import FakeOpenPulse2Q
backend = FakeOpenPulse2Q()
with pulse.build(backend) as pulse_prog:
pulse.cx(0, 1)
"""
call_gate(gates.CXGate(), (control, target))
def u1(theta: float, qubit: int): # pylint: disable=invalid-name
"""Call a :class:`~qiskit.circuit.library.standard_gates.U1Gate` on the
input physical qubit.
.. note::
Calling gates directly within the pulse builder namespace will be
deprecated in the future in favor of tight integration with a circuit
builder interface which is under development.
Examples:
.. code-block::
import math
from qiskit import pulse
from qiskit.providers.fake_provider import FakeOpenPulse2Q
backend = FakeOpenPulse2Q()
with pulse.build(backend) as pulse_prog:
pulse.u1(math.pi, 1)
"""
call_gate(gates.U1Gate(theta), qubit)
def u2(phi: float, lam: float, qubit: int): # pylint: disable=invalid-name
"""Call a :class:`~qiskit.circuit.library.standard_gates.U2Gate` on the
input physical qubit.
.. note::
Calling gates directly within the pulse builder namespace will be
deprecated in the future in favor of tight integration with a circuit
builder interface which is under development.
Examples:
.. code-block::
import math
from qiskit import pulse
from qiskit.providers.fake_provider import FakeOpenPulse2Q
backend = FakeOpenPulse2Q()
with pulse.build(backend) as pulse_prog:
pulse.u2(0, math.pi, 1)
"""
call_gate(gates.U2Gate(phi, lam), qubit)
def u3(theta: float, phi: float, lam: float, qubit: int): # pylint: disable=invalid-name
"""Call a :class:`~qiskit.circuit.library.standard_gates.U3Gate` on the
input physical qubit.
.. note::
Calling gates directly within the pulse builder namespace will be
deprecated in the future in favor of tight integration with a circuit
builder interface which is under development.
Examples:
.. code-block::
import math
from qiskit import pulse
from qiskit.providers.fake_provider import FakeOpenPulse2Q
backend = FakeOpenPulse2Q()
with pulse.build(backend) as pulse_prog:
pulse.u3(math.pi, 0, math.pi, 1)
"""
call_gate(gates.U3Gate(theta, phi, lam), qubit)
def x(qubit: int):
"""Call a :class:`~qiskit.circuit.library.standard_gates.XGate` on the
input physical qubit.
.. note::
Calling gates directly within the pulse builder namespace will be
deprecated in the future in favor of tight integration with a circuit
builder interface which is under development.
Examples:
.. code-block::
from qiskit import pulse
from qiskit.providers.fake_provider import FakeOpenPulse2Q
backend = FakeOpenPulse2Q()
with pulse.build(backend) as pulse_prog:
pulse.x(0)
"""
call_gate(gates.XGate(), qubit)
|
https://github.com/maryrbarros2/QuantumAlgorithms_Qiskit
|
maryrbarros2
|
from qiskit import QuantumCircuit, assemble, Aer
from qiskit.visualization import plot_histogram, plot_bloch_vector
from math import sqrt, pi
qc = QuantumCircuit(1) #Quantum circuit with one qubit
initial_state = [0,1] # Define initial_state as |1>
qc.initialize(initial_state, 0) # Apply initialisation operation to the 0th qubit
qc.draw() # Let's view our circuit
sim = Aer.get_backend('aer_simulator') # Tell Qiskit how to simulate our circuit
qc.save_statevector() # Tell simulator to save statevector
qobj = assemble(qc) # Create a Qobj from the circuit for the simulator to run
result = sim.run(qobj).result() # Do the simulation and return the result
out_state = result.get_statevector()
print(out_state) # Display the output state vector
qc.measure_all()
qc.draw()
#instead of the statevector we will get the counts for the 0 and 1 results using .get_counts():
qobj = assemble(qc)
result = sim.run(qobj).result()
counts = result.get_counts()
plot_histogram(counts)
initial_state = [1/sqrt(2), 1j/sqrt(2)] # Define state |q_0>
qc = QuantumCircuit(1) # Must redefine qc
qc.initialize(initial_state, 0) # Initialize the 0th qubit in the state `initial_state`
qc.save_statevector() # Save statevector
qobj = assemble(qc) # # Create a Qobj from the circuit for the simulator to run
state = sim.run(qobj).result().get_statevector() # Execute the circuit
print(state)
results = sim.run(qobj).result().get_counts()
plot_histogram(results)
#State with 1/3 probability of measuring |0> and 2/3 of measuring |1>
initial_state2 = [1/sqrt(3), sqrt(2)/sqrt(3)] # Define state |q_0>
qc2 = QuantumCircuit(1) # Must redefine qc
qc2.initialize(initial_state2, 0) # Initialize the 0th qubit in the state `initial_state`
qc2.save_statevector() # Save statevector
qobj2 = assemble(qc2) # # Create a Qobj from the circuit for the simulator to run
state2 = sim.run(qobj2).result().get_statevector() # Execute the circuit
print(state)
results2 = sim.run(qobj2).result().get_counts()
plot_histogram(results2)
from qiskit_textbook.widgets import plot_bloch_vector_spherical
coords = [pi/2,0,1] # [Theta, Phi, Radius]
plot_bloch_vector_spherical(coords) # Bloch Vector with spherical coordinates
#Plotting \0>
coords = [0,1,1] # [Theta, Phi, Radius]
plot_bloch_vector_spherical(coords)
#Plotting \1>
coords = [pi,1,1] # [Theta, Phi, Radius]
plot_bloch_vector_spherical(coords)
from qiskit_textbook.widgets import bloch_calc
bloch_calc()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import ClassicalRegister, QuantumRegister, QuantumCircuit
qr = QuantumRegister(2)
cr = ClassicalRegister(2)
qc = QuantumCircuit(qr, cr)
qc.h(range(2))
qc.measure(range(2), range(2))
# apply x gate if the classical register has the value 2 (10 in binary)
qc.x(0).c_if(cr, 2)
# apply y gate if bit 0 is set to 1
qc.y(1).c_if(0, 1)
qc.draw('mpl')
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
# import all necessary objects and methods for quantum circuits
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
from qiskit.tools.visualization import matplotlib_circuit_drawer as drawer
# we use four pairs of two qubits in order to see all results at once
# the first pair -> qubits with indices 0 and 1
# the second pair -> qubits with indices 2 and 3
# the third pair -> qubits with indices 4 and 5
# the fourth pair -> qubits with indices 6 and 7
qreg = QuantumRegister(8)
creg = ClassicalRegister(8)
mycircuit = QuantumCircuit(qreg,creg)
# the first pair is already in |00>
# the second pair is set to be in |01>
mycircuit.x(qreg[3])
# the third pair is set to be in |10>
mycircuit.x(qreg[4])
# the fourth pair is set to be in |11>
mycircuit.x(qreg[6])
mycircuit.x(qreg[7])
# apply cx to each pair
for i in range(0,8,2): # i = 0,2,4,6
mycircuit.cx(qreg[i],qreg[i+1])
# measure the quantum register
mycircuit.measure(qreg,creg)
print("Everything looks fine, let's continue ...")
# draw the circuit
drawer(mycircuit)
# re-run this cell if you DO NOT see the circuit diagram
# execute the circuit 1000 times in the local simulator
job = execute(mycircuit,Aer.get_backend('qasm_simulator'),shots=1000)
counts = job.result().get_counts(mycircuit)
# print the reverse of the output
for outcome in counts:
reverse_outcome = ''
for i in outcome:
reverse_outcome = i + reverse_outcome
print(reverse_outcome,"is observed",counts[outcome],"times")
print()
print("let's also split into the pairs")
for i in range(0,8,2):
print(reverse_outcome[i:i+2])
# import all necessary objects and methods for quantum circuits
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
from qiskit.tools.visualization import matplotlib_circuit_drawer as drawer
# import randrange for random choices
from random import randrange
#
# your code is here
#
# import all necessary objects and methods for quantum circuits
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
from qiskit.tools.visualization import matplotlib_circuit_drawer as drawer
#
# your code is here
#
# import all necessary objects and methods for quantum circuits
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
from qiskit.tools.visualization import matplotlib_circuit_drawer as drawer
#
# your code is here
#
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
from qiskit.providers.fake_provider import FakeManilaV2
from qiskit import transpile
from qiskit.tools.visualization import plot_histogram
# Get a fake backend from the fake provider
backend = FakeManilaV2()
# Create a simple circuit
circuit = QuantumCircuit(3)
circuit.h(0)
circuit.cx(0,1)
circuit.cx(0,2)
circuit.measure_all()
circuit.draw('mpl')
# Transpile the ideal circuit to a circuit that can be directly executed by the backend
transpiled_circuit = transpile(circuit, backend)
transpiled_circuit.draw('mpl')
# Run the transpiled circuit using the simulated fake backend
job = backend.run(transpiled_circuit)
counts = job.result().get_counts()
plot_histogram(counts)
|
https://github.com/VoicuTomut/Qsiris-Quantum-Odyssey-and-Qiskit
|
VoicuTomut
|
import numpy as np
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.compiler import transpile
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
from project_qsiris.conversion_qiskit_qo import qiskit_to_odyssey, save_odyssey_puzzle
#Add here any Qiskit gates you'd like to be converted to Quantum Odyssey. What you see bellow is an example
#You can change the QuantumRegister between 1 to 5 qubits.
qreg_q = QuantumRegister(2,'q')
circuit = QuantumCircuit(qreg_q)
circuit.x(qreg_q[0])
circuit.y(qreg_q[1])
circuit.draw('mpl')
# This creates the QO puzzle out of your Qiskit circuit.
# You can save it in two ways: General (as an actual puzzle to be solved) or Editor (to just visualize it in QO).
puzzle = qiskit_to_odyssey(circuit, puzzle_type="General")
# The name of the puzzle (by default example_001). QO puzzles have extension .qpf
save_odyssey_puzzle(puzzle, 'example_001' )
#Step 1: Build the circuit in Qiskit
qreg_q = QuantumRegister(4,'q')
circuit = QuantumCircuit(qreg_q)
circuit.cx(qreg_q[1],qreg_q[2])
circuit.h(qreg_q[1])
circuit.z(qreg_q[3])
circuit.u(np.pi/7,np.pi/3,np.pi/5,qreg_q[0])
circuit.swap(qreg_q[0], qreg_q[3])
circuit.draw('mpl')
#Step 2: Transpile your Qiskit circuit to simple gates to conversion avoid problems
circuit = transpile(circuit, basis_gates=['id','u3', 'cx'], optimization_level=1, seed_transpiler=1)
circuit.draw(output='mpl')
#Step 3: Convert your circuit in dictionary that represents a QO puzzle.
puzzle=qiskit_to_odyssey(circuit, puzzle_type="General")
#Step 4: Save your puzzle
save_odyssey_puzzle(puzzle, 'example_002' )
circuit = QuantumCircuit(2,name='matchgate_2Q')
circuit.cx(0,1)
circuit.z(0)
circuit.cry(np.pi/7,1,0)
circuit.cx(0,1)
circuit.draw('mpl')
circuit = transpile(circuit, basis_gates=['id','u3', 'cx'], optimization_level=1, seed_transpiler=1)
circuit.draw(output='mpl')
puzzle = qiskit_to_odyssey(circuit)
save_odyssey_puzzle(puzzle, 'example_003' )
# Let's see here how the default example_003 puzzle file will look like in Quantum Odyssey
img_circuit = mpimg.imread('img/qiskit_circuit_to_QO.png')
img_circuit_gate = mpimg.imread('img/qo_circuit_as_1gate.png')
fig, ax = plt.subplots(1,2)
ax[0].imshow(img_circuit);
ax[1].imshow(img_circuit_gate);
ax[0].set_title('Circuit in QO')
#Quantum Odyssey allows compilation of any number of logic gates in a single custom gate (right side bellow=left)
ax[1].set_title('Circuit in QO as a gate')
#Here is how the QO puzzle file looks like, this is an example
puzzle
|
https://github.com/mahabubul-alam/QAOA-Compiler
|
mahabubul-alam
|
!python run.py -device_json examples/QC.json -circuit_json examples/QAOA_circ.json -config_json examples/Config.json -policy_compilation VIC -initial_layout_method vqp
!cat VIC_QAOA.qasm
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit.circuit.library import MCXGate
gate = MCXGate(4)
from qiskit import QuantumCircuit
circuit = QuantumCircuit(5)
circuit.append(gate, [0, 1, 4, 2, 3])
circuit.draw('mpl')
|
https://github.com/zapata-engineering/orquestra-qiskit
|
zapata-engineering
|
################################################################################
# Β© Copyright 2021-2022 Zapata Computing Inc.
################################################################################
import numpy as np
import pytest
import qiskit
import qiskit.circuit.random
import sympy
from orquestra.quantum.circuits import (
_builtin_gates,
_circuit,
_gates,
_wavefunction_operations,
)
from orquestra.integrations.qiskit.conversions import (
export_to_qiskit,
import_from_qiskit,
)
# --------- gates ---------
EQUIVALENT_NON_PARAMETRIC_GATES = [
(_builtin_gates.X, qiskit.circuit.library.XGate()),
(_builtin_gates.Y, qiskit.circuit.library.YGate()),
(_builtin_gates.Z, qiskit.circuit.library.ZGate()),
(_builtin_gates.H, qiskit.circuit.library.HGate()),
(_builtin_gates.I, qiskit.circuit.library.IGate()),
(_builtin_gates.S, qiskit.circuit.library.SGate()),
(_builtin_gates.SX, qiskit.circuit.library.SXGate()),
(_builtin_gates.T, qiskit.circuit.library.TGate()),
(_builtin_gates.CNOT, qiskit.circuit.library.CXGate()),
(_builtin_gates.CZ, qiskit.circuit.library.CZGate()),
(_builtin_gates.SWAP, qiskit.circuit.library.SwapGate()),
(_builtin_gates.ISWAP, qiskit.circuit.library.iSwapGate()),
(_builtin_gates.S.dagger, qiskit.circuit.library.SdgGate()),
(_builtin_gates.T.dagger, qiskit.circuit.library.TdgGate()),
]
EQUIVALENT_PARAMETRIC_GATES = [
(orquestra_cls(theta), qiskit_cls(theta))
for orquestra_cls, qiskit_cls in [
(_builtin_gates.RX, qiskit.circuit.library.RXGate),
(_builtin_gates.RY, qiskit.circuit.library.RYGate),
(_builtin_gates.RZ, qiskit.circuit.library.RZGate),
(_builtin_gates.PHASE, qiskit.circuit.library.PhaseGate),
(_builtin_gates.CPHASE, qiskit.circuit.library.CPhaseGate),
(_builtin_gates.XX, qiskit.circuit.library.RXXGate),
(_builtin_gates.YY, qiskit.circuit.library.RYYGate),
(_builtin_gates.ZZ, qiskit.circuit.library.RZZGate),
]
for theta in [0, -1, np.pi / 5, 2 * np.pi]
]
TWO_QUBIT_SWAP_MATRIX = np.array(
[
[1, 0, 0, 0],
[0, 0, 1, 0],
[0, 1, 0, 0],
[0, 0, 0, 1],
]
)
def _fix_qubit_ordering(qiskit_matrix):
"""Import qiskit matrix to Orquestra matrix convention.
Qiskit uses different qubit ordering than we do.
It causes multi-qubit matrices to look different on first sight."""
if len(qiskit_matrix) == 2:
return qiskit_matrix
if len(qiskit_matrix) == 4:
return TWO_QUBIT_SWAP_MATRIX @ qiskit_matrix @ TWO_QUBIT_SWAP_MATRIX
else:
raise ValueError(f"Unsupported matrix size: {len(qiskit_matrix)}")
class TestGateConversion:
@pytest.mark.parametrize(
"orquestra_gate,qiskit_gate",
[
*EQUIVALENT_NON_PARAMETRIC_GATES,
*EQUIVALENT_PARAMETRIC_GATES,
],
)
def test_matrices_are_equal(self, orquestra_gate, qiskit_gate):
orquestra_matrix = np.array(orquestra_gate.matrix).astype(np.complex128)
qiskit_matrix = _fix_qubit_ordering(qiskit_gate.to_matrix())
np.testing.assert_allclose(orquestra_matrix, qiskit_matrix)
class TestU3GateConversion:
@pytest.mark.parametrize(
"theta, phi, lambda_",
[
(0, 0, 0),
(0, np.pi / 5, 0),
(np.pi / 3, 0, 0),
(0, 0, np.pi / 7),
(42, -20, 30),
],
)
def test_matrices_are_equal_up_to_phase_factor(self, theta, phi, lambda_):
orquestra_matrix = np.array(
_builtin_gates.U3(theta, phi, lambda_).matrix
).astype(np.complex128)
qiskit_matrix = qiskit.circuit.library.U3Gate(theta, phi, lambda_).to_matrix()
np.testing.assert_allclose(orquestra_matrix, qiskit_matrix, atol=1e-7)
class TestCU3GateConversion:
@pytest.mark.parametrize(
"theta, phi, lambda_",
[
(0, 0, 0),
(0, np.pi / 5, 0),
(np.pi / 3, 0, 0),
(0, 0, np.pi / 7),
(42, -20, 30),
],
)
def test_matrices_are_equal_up_to_phase_factor(self, theta, phi, lambda_):
orquestra_matrix = np.array(
_builtin_gates.U3(theta, phi, lambda_).controlled(1)(0, 1).lifted_matrix(2)
).astype(np.complex128)
qiskit_matrix = (
qiskit.circuit.library.U3Gate(theta, phi, lambda_).control(1).to_matrix()
)
# Rearrange the qiskit matrix, such that it matches the endianness of orquestra
qiskit_matrix_reversed_control = _fix_qubit_ordering(qiskit_matrix)
np.testing.assert_allclose(
orquestra_matrix, qiskit_matrix_reversed_control, atol=1e-7
)
# --------- circuits ---------
# NOTE: In Qiskit, 0 is the most significant qubit,
# whereas in Orquestra, 0 is the least significant qubit.
# Thus, we need to flip the indices.
#
# See more at
# https://qiskit.org/documentation/tutorials/circuits/1_getting_started_with_qiskit.html#Visualize-Circuit
def _make_qiskit_circuit(n_qubits, commands, n_cbits=0):
qc = qiskit.QuantumCircuit(n_qubits, n_cbits)
for method_name, method_args in commands:
method = getattr(qc, method_name)
method(*method_args)
return qc
SYMPY_THETA = sympy.Symbol("theta")
SYMPY_GAMMA = sympy.Symbol("gamma")
SYMPY_LAMBDA = sympy.Symbol("lambda_")
SYMPY_PARAMETER_VECTOR = [sympy.Symbol("p[0]"), sympy.Symbol("p[1]")]
QISKIT_THETA = qiskit.circuit.Parameter("theta")
QISKIT_GAMMA = qiskit.circuit.Parameter("gamma")
QISKIT_LAMBDA = qiskit.circuit.Parameter("lambda_")
QISKIT_PARAMETER_VECTOR = qiskit.circuit.ParameterVector("p", 2)
EXAMPLE_PARAM_VALUES = {
"gamma": 0.3,
"theta": -5,
"lambda_": np.pi / 5,
"p[0]": -5,
"p[1]": 0.3,
}
EQUIVALENT_NON_PARAMETRIZED_CIRCUITS = [
(
_circuit.Circuit([], 3),
_make_qiskit_circuit(3, []),
),
(
_circuit.Circuit(
[
_builtin_gates.X(0),
_builtin_gates.Z(2),
],
6,
),
_make_qiskit_circuit(
6,
[
("x", (0,)),
("z", (2,)),
],
),
),
(
_circuit.Circuit(
[
_builtin_gates.T.dagger(0),
],
6,
),
_make_qiskit_circuit(
6,
[
("tdg", (0,)),
],
),
),
(
_circuit.Circuit(
[
_wavefunction_operations.ResetOperation(0),
],
6,
),
_make_qiskit_circuit(
6,
[
("reset", (0,)),
],
),
),
(
_circuit.Circuit(
[
_builtin_gates.X(0),
_wavefunction_operations.ResetOperation(0),
],
6,
),
_make_qiskit_circuit(
6,
[
("x", (0,)),
("reset", (0,)),
],
),
),
(
_circuit.Circuit(
[
_builtin_gates.CNOT(0, 1),
],
4,
),
_make_qiskit_circuit(
4,
[
("cnot", (0, 1)),
],
),
),
(
_circuit.Circuit(
[
_builtin_gates.RX(np.pi)(1),
],
4,
),
_make_qiskit_circuit(
4,
[
("rx", (np.pi, 1)),
],
),
),
(
_circuit.Circuit(
[_builtin_gates.SWAP.controlled(1)(2, 0, 3)],
5,
),
_make_qiskit_circuit(
5,
[
("append", (qiskit.circuit.library.SwapGate().control(1), [2, 0, 3])),
],
),
),
(
_circuit.Circuit(
[_builtin_gates.Y.controlled(2)(4, 5, 2)],
6,
),
_make_qiskit_circuit(
6,
[
("append", (qiskit.circuit.library.YGate().control(2), [4, 5, 2])),
],
),
),
(
_circuit.Circuit([_builtin_gates.U3(np.pi / 5, np.pi / 2, np.pi / 4)(2)]),
_make_qiskit_circuit(
3,
[
(
"append",
(
qiskit.circuit.library.U3Gate(np.pi / 5, np.pi / 2, np.pi / 4),
[2],
),
)
],
),
),
(
_circuit.Circuit(
[_builtin_gates.U3(np.pi / 5, np.pi / 2, np.pi / 4).controlled(1)(1, 2)]
),
_make_qiskit_circuit(
3,
[
(
"append",
(
qiskit.circuit.library.U3Gate(
np.pi / 5, np.pi / 2, np.pi / 4
).control(1),
[1, 2],
),
)
],
),
),
(
_circuit.Circuit([_builtin_gates.Delay(1)(0)]),
_make_qiskit_circuit(1, [("delay", (1, 0))]),
),
]
EQUIVALENT_PARAMETRIZED_CIRCUITS = [
(
_circuit.Circuit(
[
_builtin_gates.RX(SYMPY_THETA)(1),
],
4,
),
_make_qiskit_circuit(
4,
[
("rx", (QISKIT_THETA, 1)),
],
),
),
(
_circuit.Circuit(
[
_builtin_gates.RX(SYMPY_THETA * SYMPY_GAMMA)(1),
],
4,
),
_make_qiskit_circuit(
4,
[
("rx", (QISKIT_THETA * QISKIT_GAMMA, 1)),
],
),
),
(
_circuit.Circuit(
[_builtin_gates.U3(SYMPY_THETA, SYMPY_GAMMA, SYMPY_LAMBDA)(3)]
),
_make_qiskit_circuit(
4,
[
(
"append",
(
qiskit.circuit.library.U3Gate(
QISKIT_THETA, QISKIT_GAMMA, QISKIT_LAMBDA
),
[3],
),
)
],
),
),
(
_circuit.Circuit(
[
_builtin_gates.U3(SYMPY_THETA, SYMPY_GAMMA, SYMPY_LAMBDA).controlled(1)(
2, 3
)
]
),
_make_qiskit_circuit(
4,
[
(
"append",
(
qiskit.circuit.library.U3Gate(
QISKIT_THETA, QISKIT_GAMMA, QISKIT_LAMBDA
).control(1),
[2, 3],
),
)
],
),
),
(
_circuit.Circuit(
[
_builtin_gates.RX(
SYMPY_PARAMETER_VECTOR[0] * SYMPY_PARAMETER_VECTOR[1]
)(1),
],
4,
),
_make_qiskit_circuit(
4,
[
("rx", (QISKIT_PARAMETER_VECTOR[0] * QISKIT_PARAMETER_VECTOR[1], 1)),
],
),
),
]
UNITARY_GATE_DEF = _gates.CustomGateDefinition(
"unitary.33c11b461fe67e717e37ac34a568cd1c27a89013703bf5b84194f0732a33a26d",
sympy.Matrix([[0, 1], [1, 0]]),
tuple(),
)
CUSTOM_A2_GATE_DEF = _gates.CustomGateDefinition(
"custom.A2.33c11b461fe67e717e37ac34a568cd1c27a89013703bf5b84194f0732a33a26d",
sympy.Matrix([[0, 1], [1, 0]]),
tuple(),
)
EQUIVALENT_CUSTOM_GATE_CIRCUITS = [
(
_circuit.Circuit(
operations=[UNITARY_GATE_DEF()(1)],
n_qubits=4,
),
_make_qiskit_circuit(
4,
[
("unitary", (np.array([[0, 1], [1, 0]]), 1)),
],
),
),
(
_circuit.Circuit(
operations=[CUSTOM_A2_GATE_DEF()(3)],
n_qubits=5,
),
_make_qiskit_circuit(
5,
[
("unitary", (np.array([[0, 1], [1, 0]]), 3, "custom.A2")),
],
),
),
(
_circuit.Circuit(
operations=[UNITARY_GATE_DEF()(1), UNITARY_GATE_DEF()(1)],
n_qubits=4,
),
_make_qiskit_circuit(
4,
[
("unitary", (np.array([[0, 1], [1, 0]]), 1)),
("unitary", (np.array([[0, 1], [1, 0]]), 1)),
],
),
),
(
_circuit.Circuit(
operations=[
UNITARY_GATE_DEF()(1),
CUSTOM_A2_GATE_DEF()(1),
UNITARY_GATE_DEF()(0),
],
n_qubits=4,
),
_make_qiskit_circuit(
4,
[
("unitary", (np.array([[0, 1], [1, 0]]), 1)),
("unitary", (np.array([[0, 1], [1, 0]]), 1, "custom.A2")),
("unitary", (np.array([[0, 1], [1, 0]]), 0)),
],
),
),
]
UNSUPPORTED_CIRCUITS = [
_make_qiskit_circuit(1, [("measure", (0, 0))], n_cbits=1),
_make_qiskit_circuit(1, [("break_loop", ())]),
]
def _draw_qiskit_circuit(circuit):
return qiskit.visualization.circuit_drawer(circuit, output="text")
class TestExportingToQiskit:
@pytest.mark.parametrize(
"orquestra_circuit, qiskit_circuit", EQUIVALENT_NON_PARAMETRIZED_CIRCUITS
)
def test_exporting_circuit_gives_equivalent_circuit(
self, orquestra_circuit, qiskit_circuit
):
converted = export_to_qiskit(orquestra_circuit)
assert converted == qiskit_circuit, (
f"Converted circuit:\n{_draw_qiskit_circuit(converted)}\n isn't equal "
f"to\n{_draw_qiskit_circuit(qiskit_circuit)}"
)
@pytest.mark.parametrize(
"orquestra_circuit",
[
orquestra_circuit
for orquestra_circuit, _ in EQUIVALENT_PARAMETRIZED_CIRCUITS
],
)
def test_exporting_parametrized_circuit_doesnt_change_symbol_names(
self, orquestra_circuit
):
converted = export_to_qiskit(orquestra_circuit)
converted_names = sorted(map(str, converted.parameters))
initial_names = sorted(map(str, orquestra_circuit.free_symbols))
assert converted_names == initial_names
@pytest.mark.parametrize(
"orquestra_circuit, qiskit_circuit", EQUIVALENT_PARAMETRIZED_CIRCUITS
)
def test_exporting_and_binding_parametrized_circuit_results_in_equivalent_circuit(
self, orquestra_circuit, qiskit_circuit
):
# 1. Export
converted = export_to_qiskit(orquestra_circuit)
# 2. Bind params
converted_bound = converted.bind_parameters(
{param: EXAMPLE_PARAM_VALUES[str(param)] for param in converted.parameters}
)
# 3. Bind the ref
ref_bound = qiskit_circuit.bind_parameters(
{
param: EXAMPLE_PARAM_VALUES[str(param)]
for param in qiskit_circuit.parameters
}
)
assert converted_bound == ref_bound, (
f"Converted circuit:\n{_draw_qiskit_circuit(converted_bound)}\n isn't "
f"equal to\n{_draw_qiskit_circuit(ref_bound)}"
)
@pytest.mark.parametrize(
"orquestra_circuit, qiskit_circuit", EQUIVALENT_PARAMETRIZED_CIRCUITS
)
def test_binding_and_exporting_parametrized_circuit_results_in_equivalent_circuit(
self, orquestra_circuit, qiskit_circuit
):
# 1. Bind params
bound = orquestra_circuit.bind(
{
symbol: EXAMPLE_PARAM_VALUES[str(symbol)]
for symbol in orquestra_circuit.free_symbols
}
)
# 2. Export
bound_converted = export_to_qiskit(bound)
# 3. Bind the ref
ref_bound = qiskit_circuit.bind_parameters(
{
param: EXAMPLE_PARAM_VALUES[str(param)]
for param in qiskit_circuit.parameters
}
)
assert bound_converted == ref_bound, (
f"Converted circuit:\n{_draw_qiskit_circuit(bound_converted)}\n isn't "
f"equal to\n{_draw_qiskit_circuit(ref_bound)}"
)
@pytest.mark.parametrize(
"orquestra_circuit, qiskit_circuit", EQUIVALENT_CUSTOM_GATE_CIRCUITS
)
def test_exporting_circuit_with_custom_gates_gives_equivalent_operator(
self, orquestra_circuit, qiskit_circuit
):
exported = export_to_qiskit(orquestra_circuit)
# We can't compare the circuits directly, because the gate names can differ.
# Qiskit allows multiple gate operations with the same label. Orquestra doesn't
# allow that, so we append a matrix hash to the name.
assert qiskit.quantum_info.Operator(exported) == qiskit.quantum_info.Operator(
qiskit_circuit
)
class TestImportingFromQiskit:
@pytest.mark.parametrize(
"orquestra_circuit, qiskit_circuit", EQUIVALENT_NON_PARAMETRIZED_CIRCUITS
)
def test_importing_circuit_gives_equivalent_circuit(
self, orquestra_circuit, qiskit_circuit
):
imported = import_from_qiskit(qiskit_circuit)
assert imported == orquestra_circuit
@pytest.mark.parametrize(
"qiskit_circuit",
[q_circuit for _, q_circuit in EQUIVALENT_PARAMETRIZED_CIRCUITS],
)
def test_importing_parametrized_circuit_doesnt_change_symbol_names(
self, qiskit_circuit
):
imported = import_from_qiskit(qiskit_circuit)
assert sorted(map(str, imported.free_symbols)) == sorted(
map(str, qiskit_circuit.parameters)
)
@pytest.mark.parametrize(
"orquestra_circuit, qiskit_circuit", EQUIVALENT_PARAMETRIZED_CIRCUITS
)
def test_importing_and_binding_parametrized_circuit_results_in_equivalent_circuit(
self, orquestra_circuit, qiskit_circuit
):
# 1. Import
imported = import_from_qiskit(qiskit_circuit)
symbols_map = {
symbol: EXAMPLE_PARAM_VALUES[str(symbol)]
for symbol in imported.free_symbols
}
# 2. Bind params
imported_bound = imported.bind(symbols_map)
# 3. Bind the ref
ref_bound = orquestra_circuit.bind(symbols_map)
assert imported_bound == ref_bound
@pytest.mark.parametrize(
"orquestra_circuit, qiskit_circuit", EQUIVALENT_PARAMETRIZED_CIRCUITS
)
def test_binding_and_importing_parametrized_circuit_results_in_equivalent_circuit(
self, orquestra_circuit, qiskit_circuit
):
# 1. Bind params
bound = qiskit_circuit.bind_parameters(
{
param: EXAMPLE_PARAM_VALUES[str(param)]
for param in qiskit_circuit.parameters
}
)
# 2. Import
bound_imported = import_from_qiskit(bound)
# 3. Bind the ref
ref_bound = orquestra_circuit.bind(
{
symbol: EXAMPLE_PARAM_VALUES[str(symbol)]
for symbol in orquestra_circuit.free_symbols
}
)
assert bound_imported == ref_bound
@pytest.mark.parametrize(
"orquestra_circuit, qiskit_circuit", EQUIVALENT_CUSTOM_GATE_CIRCUITS
)
def test_importing_circuit_with_custom_gates_gives_equivalent_circuit(
self, orquestra_circuit, qiskit_circuit
):
imported = import_from_qiskit(qiskit_circuit)
assert imported == orquestra_circuit
@pytest.mark.parametrize("unsupported_circuit", UNSUPPORTED_CIRCUITS)
def test_operation_not_implemented(self, unsupported_circuit):
with pytest.raises(ValueError):
import_from_qiskit(unsupported_circuit)
|
https://github.com/qiskit-community/qiskit-cold-atom
|
qiskit-community
|
# 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.
"""Module to convert cold atom circuits to dictionaries that can be sent to backends."""
from typing import List, Union, Optional
from enum import Enum
from qiskit import QuantumCircuit
from qiskit.providers import BackendV1 as Backend
from qiskit_cold_atom.exceptions import QiskitColdAtomError
class WireOrder(str, Enum):
"""The possible wire orderings for cold atomic circuits.
For example, a sequential register [0, 1, 2, 3, 4, 5] with two species implies that wires 0, 1, 2
are of the same type while an interleaved ordering implies that wires 0, 2, and 4 are of the
same type.
"""
SEQUENTIAL = "sequential"
INTERLEAVED = "interleaved"
class CircuitTools:
"""A class to provide tooling for cold-atomic circuits.
Since all methods are class methods this class does not need to be instantiated. This
class groups tools for cold atomic circuits. It also makes clear the ordering of the
fermionic wires that qiskit works with.
"""
# Qiskit for fermions works with a sequential register definition. For fermionic
# modes with more than on species the circuits will have a corresponding number of
# sequential registers with the same length. For example, a three site system with two
# species will have two sequential registers with three wires each. Other packages may
# use an "interleaved" wire order.
__wire_order__ = WireOrder("sequential")
@classmethod
def validate_circuits(
cls,
circuits: Union[List[QuantumCircuit], QuantumCircuit],
backend: Backend,
shots: Optional[int] = None,
convert_wires: bool = True,
) -> None:
"""
Performs validity checks on circuits against the configuration of the backends. This checks
whether all applied instructions in the circuit are accepted by the backend and whether the
applied gates comply with their respective coupling maps.
Args:
circuits: The circuits that need to be run.
backend: The backend on which the circuit should be run.
shots: The number of shots for each circuit.
convert_wires: If True, the circuits are converted to the wiring convention of the backend.
Raises:
QiskitColdAtomError: If the maximum shot number specified by the backend is exceeded.
QiskitColdAtomError: If the backend does not support an instruction in the circuit.
QiskitColdAtomError: If the width of the circuit is too large.
QiskitColdAtomError: If the circuit has unbound parameters.
"""
if isinstance(circuits, QuantumCircuit):
circuits = [circuits]
# check for number of experiments allowed by the backend
if backend.configuration().max_experiments:
max_circuits = backend.configuration().max_experiments
if len(circuits) > max_circuits:
raise QiskitColdAtomError(
f"{backend.name()} allows for max. {max_circuits} different circuits; "
f"but {len(circuits)} circuits were given"
)
# check for number of individual shots allowed by the backend
if backend.configuration().max_shots and shots:
max_shots = backend.configuration().max_shots
if shots > max_shots:
raise QiskitColdAtomError(
f"{backend.name()} allows for max. {max_shots} shots per circuit; "
f"{shots} shots were requested"
)
config_dict = backend.configuration().to_dict()
for circuit in circuits:
try:
native_gates = {
gate.name: gate.coupling_map for gate in backend.configuration().gates
}
native_instructions = backend.configuration().supported_instructions
except NameError as name_error:
raise QiskitColdAtomError(
"backend needs to be initialized with config file first"
) from name_error
if circuit.num_qubits > backend.configuration().num_qubits:
raise QiskitColdAtomError(
f"{backend.name()} supports circuits with up to "
f"{backend.configuration().num_qubits} wires, but"
f"{circuit.num_qubits} wires were given."
)
# If num_species is specified by the backend, the wires describe different atomic species
# and the circuit's wire count must be a multiple of the number of species.
num_species = None
wire_order = None
if "num_species" in config_dict and convert_wires:
num_species = backend.configuration().num_species
if "wire_order" in config_dict:
wire_order = WireOrder(backend.configuration().wire_order)
else:
wire_order = cls.__wire_order__
if num_species > 1 and circuit.num_qubits % num_species:
raise QiskitColdAtomError(
f"{backend.name()} requires circuits to be submitted with a multiple of "
f"{num_species} wires, but {circuit.num_qubits} wires were given."
)
for inst in circuit.data:
# get the correct wire indices of the instruction with respect
# to the total index of the qubit objects in the circuit
wires = [circuit.qubits.index(qubit) for qubit in inst[1]]
for param in inst[0].params:
try:
float(param)
except TypeError as type_error:
raise QiskitColdAtomError(
"Cannot run circuit with unbound parameters."
) from type_error
# check if instruction is supported by the backend
name = inst[0].name
if name not in native_instructions:
raise QiskitColdAtomError(f"{backend.name()} does not support {name}")
# for the gates, check whether coupling map fits
if name in native_gates:
couplings = native_gates[name]
if num_species and convert_wires:
wires = cls.convert_wire_order(
wires,
convention_from=cls.__wire_order__,
convention_to=wire_order,
num_species=num_species,
num_sites=circuit.num_qubits // num_species,
sort=True,
)
if wires not in couplings:
raise QiskitColdAtomError(
f"coupling {wires} not supported for gate "
f"{name} on {backend.name()}; possible couplings: {couplings}"
)
@classmethod
def circuit_to_data(
cls, circuit: QuantumCircuit, backend: Backend, convert_wires: bool = True
) -> List[List]:
"""Convert the circuit to JSON serializable instructions.
Helper function that converts a QuantumCircuit into a list of symbolic
instructions as required by the Json format which is sent to the backend.
Args:
circuit: The quantum circuit for which to extract the instructions.
backend: The backend on which the circuit should be run.
convert_wires: If True, the circuits are converted to the wiring convention of the backend.
Returns:
A list of lists describing the instructions in the circuit. Each sublist
has three entries the name of the instruction, the wires that the instruction
applies to and the parameter values of the instruction.
"""
instructions = []
config_dict = backend.configuration().to_dict()
num_species = None
wire_order = None
if "num_species" in config_dict:
num_species = backend.configuration().num_species
if "wire_order" in config_dict:
wire_order = WireOrder(backend.configuration().wire_order)
else:
wire_order = cls.__wire_order__
for inst in circuit.data:
name = inst[0].name
wires = [circuit.qubits.index(qubit) for qubit in inst[1]]
if num_species and convert_wires:
wires = cls.convert_wire_order(
wires,
convention_from=cls.__wire_order__,
convention_to=wire_order,
num_species=num_species,
num_sites=circuit.num_qubits // num_species,
sort=True,
)
params = [float(param) for param in inst[0].params]
instructions.append([name, wires, params])
return instructions
@classmethod
def circuit_to_cold_atom(
cls,
circuits: Union[List[QuantumCircuit], QuantumCircuit],
backend: Backend,
shots: int = 60,
convert_wires: bool = True,
) -> dict:
"""
Converts a circuit to a JSon payload to be sent to a given backend.
Args:
circuits: The circuits that need to be run.
backend: The backend on which the circuit should be run.
shots: The number of shots for each circuit.
convert_wires: If True, the circuits are converted to the wiring convention of the backend.
Returns:
A list of dicts.
"""
if isinstance(circuits, QuantumCircuit):
circuits = [circuits]
# validate the circuits against the backend configuration
cls.validate_circuits(
circuits=circuits, backend=backend, shots=shots, convert_wires=convert_wires
)
if "wire_order" in backend.configuration().to_dict():
wire_order = WireOrder(backend.configuration().wire_order)
else:
wire_order = cls.__wire_order__
experiments = {}
for idx, circuit in enumerate(circuits):
experiments["experiment_%i" % idx] = {
"instructions": cls.circuit_to_data(
circuit, backend=backend, convert_wires=convert_wires
),
"shots": shots,
"num_wires": circuit.num_qubits,
"wire_order": wire_order,
}
return experiments
@classmethod
def convert_wire_order(
cls,
wires: List[int],
convention_from: WireOrder,
convention_to: WireOrder,
num_sites: int,
num_species: int,
sort: Optional[bool] = False,
) -> List[int]:
"""
Converts a list of wire indices onto which a gate acts from one convention to another.
Possible conventions are "sequential", where the first num_sites wires denote the
first species, the second num_sites wires denote the second species etc., and "interleaved",
where the first num_species wires denote the first site, the second num_species wires denote
the second site etc.
Args:
wires: Wires onto which a gate acts, e.g. [3, 4, 7, 8].
convention_from: The convention in which "wires" is given.
convention_to: The convention into which to convert.
num_sites: The total number of sites.
num_species: The number of different atomic species.
sort: If true, the returned list of indices is sorted in ascending order.
Raises:
QiskitColdAtomError: If the convention to and from is not supported.
Returns:
A list of wire indices following the convention_to.
"""
if (convention_to or convention_from) not in WireOrder:
raise QiskitColdAtomError(
f"Wire order conversion from {convention_from} to {convention_to}"
f" is not supported."
)
new_wires = None
if convention_from == convention_to:
new_wires = wires
if convention_from == WireOrder.SEQUENTIAL and convention_to == WireOrder.INTERLEAVED:
new_wires = [idx % num_sites * num_species + idx // num_sites for idx in wires]
elif convention_from == WireOrder.INTERLEAVED and convention_to == WireOrder.SEQUENTIAL:
new_wires = [idx % num_species * num_sites + idx // num_species for idx in wires]
if sort:
return sorted(new_wires)
else:
return new_wires
|
https://github.com/SaashaJoshi/IBM-Qiskit-Summer-School-2020
|
SaashaJoshi
|
!pip install -U -r grading_tools/requirements.txt
from IPython.display import clear_output
clear_output()
import numpy as np; pi = np.pi
from qiskit import QuantumCircuit, Aer, execute
from qiskit.visualization import plot_histogram
from copy import deepcopy as make_copy
def prepare_hets_circuit(depth, angle1, angle2):
hets_circ = QuantumCircuit(depth)
hets_circ.ry(angle1, 0)
hets_circ.rz(angle1, 0)
hets_circ.ry(angle1, 1)
hets_circ.rz(angle1, 1)
for ii in range(depth):
hets_circ.cx(0,1)
hets_circ.ry(angle2,0)
hets_circ.rz(angle2,0)
hets_circ.ry(angle2,1)
hets_circ.rz(angle2,1)
return hets_circ
hets_circuit = prepare_hets_circuit(2, pi/2, pi/2)
hets_circuit.draw()
def measure_zz_circuit(given_circuit):
zz_meas = make_copy(given_circuit)
zz_meas.measure_all()
return zz_meas
zz_meas = measure_zz_circuit(hets_circuit)
zz_meas.draw()
simulator = Aer.get_backend('qasm_simulator')
result = execute(zz_meas, backend = simulator, shots=10000).result()
counts = result.get_counts(zz_meas)
plot_histogram(counts)
def measure_zz(given_circuit, num_shots = 10000):
zz_meas = measure_zz_circuit(given_circuit)
result = execute(zz_meas, backend = simulator, shots = num_shots).result()
counts = result.get_counts(zz_meas)
if '00' not in counts:
counts['00'] = 0
if '01' not in counts:
counts['01'] = 0
if '10' not in counts:
counts['10'] = 0
if '11' not in counts:
counts['11'] = 0
total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10']
zz = counts['00'] + counts['11'] - counts['01'] - counts['10']
zz = zz / total_counts
return zz
zz = measure_zz(hets_circuit)
print("<ZZ> =", str(zz))
def measure_zi(given_circuit, num_shots = 10000):
zz_meas = measure_zz_circuit(given_circuit)
result = execute(zz_meas, backend = simulator, shots = num_shots).result()
counts = result.get_counts(zz_meas)
if '00' not in counts:
counts['00'] = 0
if '01' not in counts:
counts['01'] = 0
if '10' not in counts:
counts['10'] = 0
if '11' not in counts:
counts['11'] = 0
total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10']
zi = counts['00'] - counts['11'] + counts['01'] - counts['10']
zi = zi / total_counts
return zi
def measure_iz(given_circuit, num_shots = 10000):
zz_meas = measure_zz_circuit(given_circuit)
result = execute(zz_meas, backend = simulator, shots = num_shots).result()
counts = result.get_counts(zz_meas)
if '00' not in counts:
counts['00'] = 0
if '01' not in counts:
counts['01'] = 0
if '10' not in counts:
counts['10'] = 0
if '11' not in counts:
counts['11'] = 0
total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10']
iz = counts['00'] - counts['11'] - counts['01'] + counts['10']
iz = iz / total_counts
return iz
zi = measure_zi(hets_circuit)
print("<ZI> =", str(zi))
iz = measure_iz(hets_circuit)
print("<IZ> =", str(iz))
def measure_xx_circuit(given_circuit):
xx_meas = make_copy(given_circuit)
### WRITE YOUR CODE BETWEEN THESE LINES - START
xx_meas.h(0)
xx_meas.h(1)
xx_meas.measure_all()
### WRITE YOUR CODE BETWEEN THESE LINES - END
return xx_meas
xx_meas = measure_xx_circuit(hets_circuit)
xx_meas.draw()
def measure_xx(given_circuit, num_shots = 10000):
xx_meas = measure_xx_circuit(given_circuit)
result = execute(xx_meas, backend = simulator, shots = num_shots).result()
counts = result.get_counts(xx_meas)
if '00' not in counts:
counts['00'] = 0
if '01' not in counts:
counts['01'] = 0
if '10' not in counts:
counts['10'] = 0
if '11' not in counts:
counts['11'] = 0
total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10']
xx = counts['00'] + counts['11'] - counts['01'] - counts['10']
xx = xx / total_counts
return xx
xx = measure_xx(hets_circuit)
print("<XX> =", str(xx))
def get_energy(given_circuit, num_shots = 10000):
zz = measure_zz(given_circuit, num_shots = num_shots)
iz = measure_iz(given_circuit, num_shots = num_shots)
zi = measure_zi(given_circuit, num_shots = num_shots)
xx = measure_xx(given_circuit, num_shots = num_shots)
energy = (-1.0523732)*1 + (0.39793742)*iz + (-0.3979374)*zi + (-0.0112801)*zz + (0.18093119)*xx
return energy
energy = get_energy(hets_circuit)
print("The energy of the trial state is", str(energy))
hets_circuit_plus = None
hets_circuit_minus = None
### WRITE YOUR CODE BETWEEN THESE LINES - START
hets_circuit_plus = prepare_hets_circuit(2, pi/2 + 0.1*pi/2, pi/2)
hets_circuit_minus = prepare_hets_circuit(2, pi/2 - 0.1*pi/2, pi/2)
### WRITE YOUR CODE BETWEEN THESE LINES - END
energy_plus = get_energy(hets_circuit_plus, num_shots=100000)
energy_minus = get_energy(hets_circuit_minus, num_shots=100000)
print(energy_plus, energy_minus)
name = 'Pon Rahul M'
email = 'ponrahul.21it@licet.ac.in'
### Do not change the lines below
from grading_tools import grade
grade(answer=measure_xx_circuit(hets_circuit), name=name, email=email, labid='lab9', exerciseid='ex1')
grade(answer=hets_circuit_plus, name=name, email=email, labid='lab9', exerciseid='ex2')
grade(answer=hets_circuit_minus, name=name, email=email, labid='lab9', exerciseid='ex3')
energy_plus_100, energy_plus_1000, energy_plus_10000 = 0, 0, 0
energy_minus_100, energy_minus_1000, energy_minus_10000 = 0, 0, 0
### WRITE YOUR CODE BETWEEN THESE LINES - START
energy_plus_100 = get_energy(hets_circuit_plus, num_shots = 100)
energy_minus_100 = get_energy(hets_circuit_minus, num_shots = 100)
energy_plus_1000 = get_energy(hets_circuit_plus, num_shots = 1000)
energy_minus_1000 = get_energy(hets_circuit_minus, num_shots = 1000)
energy_plus_10000 = get_energy(hets_circuit_plus, num_shots = 10000)
energy_minus_10000 = get_energy(hets_circuit_minus, num_shots = 10000)
### WRITE YOUR CODE BETWEEN THESE LINES - END
print(energy_plus_100, energy_minus_100, "difference = ", energy_minus_100 - energy_plus_100)
print(energy_plus_1000, energy_minus_1000, "difference = ", energy_minus_1000 - energy_plus_1000)
print(energy_plus_10000, energy_minus_10000, "difference = ", energy_minus_10000 - energy_plus_10000)
### WRITE YOUR CODE BETWEEN THESE LINES - START
I = np.array([
[1, 0],
[0, 1]
])
X = np.array([
[0, 1],
[1, 0]
])
Z = np.array([
[1, 0],
[0, -1]
])
h2_hamiltonian = (-1.0523732) * np.kron(I, I) + \
(0.39793742) * np.kron(I, Z) + \
(-0.3979374) * np.kron(Z, I) + \
(-0.0112801) * np.kron(Z, Z) + \
(0.18093119) * np.kron(X, X)
from numpy import linalg as LA
eigenvalues, eigenvectors = LA.eig(h2_hamiltonian)
for ii, eigenvalue in enumerate(eigenvalues):
print(f"Eigenvector {eigenvectors[:,ii]} has energy {eigenvalue}")
exact_eigenvector = eigenvectors[:,np.argmin(eigenvalues)]
exact_eigenvalue = np.min(eigenvalues)
print()
print("Minimum energy is", exact_eigenvalue)
### WRITE YOUR CODE BETWEEN THESE LINES - END
|
https://github.com/2lambda123/Qiskit-qiskit
|
2lambda123
|
# 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.
"""
Instruction collection.
"""
from __future__ import annotations
from typing import Callable
from qiskit.circuit.exceptions import CircuitError
from .classicalregister import Clbit, ClassicalRegister
from .operation import Operation
from .quantumcircuitdata import CircuitInstruction
class InstructionSet:
"""Instruction collection, and their contexts."""
__slots__ = ("_instructions", "_requester")
def __init__( # pylint: disable=bad-docstring-quotes
self,
*,
resource_requester: Callable[..., ClassicalRegister | Clbit] | None = None,
):
"""New collection of instructions.
The context (``qargs`` and ``cargs`` that each instruction is attached to) is also stored
separately for each instruction.
Args:
resource_requester: A callable that takes in the classical resource used in the
condition, verifies that it is present in the attached circuit, resolves any indices
into concrete :obj:`.Clbit` instances, and returns the concrete resource. If this
is not given, specifying a condition with an index is forbidden, and all concrete
:obj:`.Clbit` and :obj:`.ClassicalRegister` resources will be assumed to be valid.
.. note::
The callback ``resource_requester`` is called once for each call to
:meth:`.c_if`, and assumes that a call implies that the resource will now be
used. It may throw an error if the resource is not valid for usage.
"""
self._instructions: list[CircuitInstruction] = []
self._requester = resource_requester
def __len__(self):
"""Return number of instructions in set"""
return len(self._instructions)
def __getitem__(self, i):
"""Return instruction at index"""
return self._instructions[i]
def add(self, instruction, qargs=None, cargs=None):
"""Add an instruction and its context (where it is attached)."""
if not isinstance(instruction, CircuitInstruction):
if not isinstance(instruction, Operation):
raise CircuitError("attempt to add non-Operation to InstructionSet")
if qargs is None or cargs is None:
raise CircuitError("missing qargs or cargs in old-style InstructionSet.add")
instruction = CircuitInstruction(instruction, tuple(qargs), tuple(cargs))
self._instructions.append(instruction)
def inverse(self):
"""Invert all instructions."""
for i, instruction in enumerate(self._instructions):
self._instructions[i] = instruction.replace(operation=instruction.operation.inverse())
return self
def c_if(self, classical: Clbit | ClassicalRegister | int, val: int) -> "InstructionSet":
"""Set a classical equality condition on all the instructions in this set between the
:obj:`.ClassicalRegister` or :obj:`.Clbit` ``classical`` and value ``val``.
.. note::
This is a setter method, not an additive one. Calling this multiple times will silently
override any previously set condition on any of the contained instructions; it does not
stack.
Args:
classical: the classical resource the equality condition should be on. If this is given
as an integer, it will be resolved into a :obj:`.Clbit` using the same conventions
as the circuit these instructions are attached to.
val: the value the classical resource should be equal to.
Returns:
This same instance of :obj:`.InstructionSet`, but now mutated to have the given equality
condition.
Raises:
CircuitError: if the passed classical resource is invalid, or otherwise not resolvable
to a concrete resource that these instructions are permitted to access.
Example:
.. plot::
:include-source:
from qiskit import ClassicalRegister, QuantumRegister, QuantumCircuit
qr = QuantumRegister(2)
cr = ClassicalRegister(2)
qc = QuantumCircuit(qr, cr)
qc.h(range(2))
qc.measure(range(2), range(2))
# apply x gate if the classical register has the value 2 (10 in binary)
qc.x(0).c_if(cr, 2)
# apply y gate if bit 0 is set to 1
qc.y(1).c_if(0, 1)
qc.draw('mpl')
"""
if self._requester is None and not isinstance(classical, (Clbit, ClassicalRegister)):
raise CircuitError(
"Cannot pass an index as a condition variable without specifying a requester"
" when creating this InstructionSet."
)
if self._requester is not None:
classical = self._requester(classical)
for instruction in self._instructions:
instruction.operation.c_if(classical, val)
return self
# Legacy support for properties. Added in Terra 0.21 to support the internal switch in
# `QuantumCircuit.data` from the 3-tuple to `CircuitInstruction`.
@property
def instructions(self):
"""Legacy getter for the instruction components of an instruction set. This does not
support mutation."""
return [instruction.operation for instruction in self._instructions]
@property
def qargs(self):
"""Legacy getter for the qargs components of an instruction set. This does not support
mutation."""
return [list(instruction.qubits) for instruction in self._instructions]
@property
def cargs(self):
"""Legacy getter for the cargs components of an instruction set. This does not support
mutation."""
return [list(instruction.clbits) for instruction in self._instructions]
|
https://github.com/filipecorrea/deutsch-jozsa
|
filipecorrea
|
import numpy as np
import qiskit
from qiskit import IBMQ, BasicAer
from qiskit.providers.ibmq import least_busy
from qiskit import QuantumCircuit, execute
from qiskit.visualization import plot_histogram
qiskit.__qiskit_version__
# set the length of the n-bit input string
n = 3
const_oracle = QuantumCircuit(n+1)
output = np.random.randint(2)
if output == 1:
const_oracle.x(n)
const_oracle.draw(output='mpl')
dj_circuit = QuantumCircuit(n+1, n)
# Apply H-gates
for qubit in range(n):
dj_circuit.h(qubit)
# Put qubit in state |->
dj_circuit.x(n)
dj_circuit.h(n)
dj_circuit.draw(output='mpl')
dj_circuit = QuantumCircuit(n+1, n)
# Apply H-gates
for qubit in range(n):
dj_circuit.h(qubit)
# Put qubit in state |->
dj_circuit.x(n)
dj_circuit.h(n)
# Add oracle
dj_circuit += const_oracle
dj_circuit.draw(output='mpl')
dj_circuit = QuantumCircuit(n+1, n)
# Apply H-gates
for qubit in range(n):
dj_circuit.h(qubit)
# Put qubit in state |->
dj_circuit.x(n)
dj_circuit.h(n)
# Add oracle
dj_circuit += const_oracle
# Repeat H-gates
for qubit in range(n):
dj_circuit.h(qubit)
dj_circuit.barrier()
# Measure
for i in range(n):
dj_circuit.measure(i, i)
# Display circuit
dj_circuit.draw(output='mpl')
# use local simulator
backend = BasicAer.get_backend('qasm_simulator')
shots = 1024
results = execute(dj_circuit, backend=backend, shots=shots).result()
answer = results.get_counts()
plot_histogram(answer)
|
https://github.com/2lambda123/Qiskit-qiskit
|
2lambda123
|
# 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 BasisTranslator pass"""
import os
from numpy import pi
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit import transpile
from qiskit.test import QiskitTestCase
from qiskit.circuit import Gate, Parameter, EquivalenceLibrary, Qubit, Clbit
from qiskit.circuit.library import (
U1Gate,
U2Gate,
U3Gate,
CU1Gate,
CU3Gate,
UGate,
RZGate,
XGate,
SXGate,
CXGate,
)
from qiskit.converters import circuit_to_dag, dag_to_circuit, circuit_to_instruction
from qiskit.exceptions import QiskitError
from qiskit.quantum_info import Operator
from qiskit.transpiler.target import Target, InstructionProperties
from qiskit.transpiler.exceptions import TranspilerError
from qiskit.transpiler.passes.basis import BasisTranslator, UnrollCustomDefinitions
from qiskit.circuit.library.standard_gates.equivalence_library import (
StandardEquivalenceLibrary as std_eqlib,
)
class OneQubitZeroParamGate(Gate):
"""Mock one qubit zero param gate."""
def __init__(self, name="1q0p"):
super().__init__(name, 1, [])
class OneQubitOneParamGate(Gate):
"""Mock one qubit one param gate."""
def __init__(self, theta, name="1q1p"):
super().__init__(name, 1, [theta])
class OneQubitOneParamPrimeGate(Gate):
"""Mock one qubit one param gate."""
def __init__(self, alpha):
super().__init__("1q1p_prime", 1, [alpha])
class OneQubitTwoParamGate(Gate):
"""Mock one qubit two param gate."""
def __init__(self, phi, lam, name="1q2p"):
super().__init__(name, 1, [phi, lam])
class TwoQubitZeroParamGate(Gate):
"""Mock one qubit zero param gate."""
def __init__(self, name="2q0p"):
super().__init__(name, 2, [])
class VariadicZeroParamGate(Gate):
"""Mock variadic zero param gate."""
def __init__(self, num_qubits, name="vq0p"):
super().__init__(name, num_qubits, [])
class TestBasisTranslator(QiskitTestCase):
"""Test the BasisTranslator pass."""
def test_circ_in_basis_no_op(self):
"""Verify we don't change a circuit already in the target basis."""
eq_lib = EquivalenceLibrary()
qc = QuantumCircuit(1)
qc.append(OneQubitZeroParamGate(), [0])
dag = circuit_to_dag(qc)
expected = circuit_to_dag(qc)
pass_ = BasisTranslator(eq_lib, ["1q0p"])
actual = pass_.run(dag)
self.assertEqual(actual, expected)
def test_raise_if_target_basis_unreachable(self):
"""Verify we raise if the circuit cannot be transformed to the target."""
eq_lib = EquivalenceLibrary()
qc = QuantumCircuit(1)
qc.append(OneQubitZeroParamGate(), [0])
dag = circuit_to_dag(qc)
pass_ = BasisTranslator(eq_lib, ["1q1p"])
with self.assertRaises(TranspilerError):
pass_.run(dag)
def test_single_substitution(self):
"""Verify we correctly unroll gates through a single equivalence."""
eq_lib = EquivalenceLibrary()
gate = OneQubitZeroParamGate()
equiv = QuantumCircuit(1)
equiv.append(OneQubitOneParamGate(pi), [0])
eq_lib.add_equivalence(gate, equiv)
qc = QuantumCircuit(1)
qc.append(OneQubitZeroParamGate(), [0])
dag = circuit_to_dag(qc)
expected = QuantumCircuit(1)
expected.append(OneQubitOneParamGate(pi), [0])
expected_dag = circuit_to_dag(expected)
pass_ = BasisTranslator(eq_lib, ["1q1p"])
actual = pass_.run(dag)
self.assertEqual(actual, expected_dag)
def test_double_substitution(self):
"""Verify we correctly unroll gates through multiple equivalences."""
eq_lib = EquivalenceLibrary()
gate = OneQubitZeroParamGate()
equiv = QuantumCircuit(1)
equiv.append(OneQubitOneParamGate(pi), [0])
eq_lib.add_equivalence(gate, equiv)
theta = Parameter("theta")
gate = OneQubitOneParamGate(theta)
equiv = QuantumCircuit(1)
equiv.append(OneQubitTwoParamGate(theta, pi / 2), [0])
eq_lib.add_equivalence(gate, equiv)
qc = QuantumCircuit(1)
qc.append(OneQubitZeroParamGate(), [0])
dag = circuit_to_dag(qc)
expected = QuantumCircuit(1)
expected.append(OneQubitTwoParamGate(pi, pi / 2), [0])
expected_dag = circuit_to_dag(expected)
pass_ = BasisTranslator(eq_lib, ["1q2p"])
actual = pass_.run(dag)
self.assertEqual(actual, expected_dag)
def test_single_substitution_with_global_phase(self):
"""Verify we correctly unroll gates through a single equivalence with global phase."""
eq_lib = EquivalenceLibrary()
gate = OneQubitZeroParamGate()
equiv = QuantumCircuit(1, global_phase=0.2)
equiv.append(OneQubitOneParamGate(pi), [0])
eq_lib.add_equivalence(gate, equiv)
qc = QuantumCircuit(1, global_phase=0.1)
qc.append(OneQubitZeroParamGate(), [0])
dag = circuit_to_dag(qc)
expected = QuantumCircuit(1, global_phase=0.1 + 0.2)
expected.append(OneQubitOneParamGate(pi), [0])
expected_dag = circuit_to_dag(expected)
pass_ = BasisTranslator(eq_lib, ["1q1p"])
actual = pass_.run(dag)
self.assertEqual(actual, expected_dag)
def test_single_two_gate_substitution_with_global_phase(self):
"""Verify we correctly unroll gates through a single equivalence with global phase."""
eq_lib = EquivalenceLibrary()
gate = OneQubitZeroParamGate()
equiv = QuantumCircuit(1, global_phase=0.2)
equiv.append(OneQubitOneParamGate(pi), [0])
equiv.append(OneQubitOneParamGate(pi), [0])
eq_lib.add_equivalence(gate, equiv)
qc = QuantumCircuit(1, global_phase=0.1)
qc.append(OneQubitZeroParamGate(), [0])
dag = circuit_to_dag(qc)
expected = QuantumCircuit(1, global_phase=0.1 + 0.2)
expected.append(OneQubitOneParamGate(pi), [0])
expected.append(OneQubitOneParamGate(pi), [0])
expected_dag = circuit_to_dag(expected)
pass_ = BasisTranslator(eq_lib, ["1q1p"])
actual = pass_.run(dag)
self.assertEqual(actual, expected_dag)
def test_two_substitutions_with_global_phase(self):
"""Verify we correctly unroll gates through a single equivalences with global phase."""
eq_lib = EquivalenceLibrary()
gate = OneQubitZeroParamGate()
equiv = QuantumCircuit(1, global_phase=0.2)
equiv.append(OneQubitOneParamGate(pi), [0])
eq_lib.add_equivalence(gate, equiv)
qc = QuantumCircuit(1, global_phase=0.1)
qc.append(OneQubitZeroParamGate(), [0])
qc.append(OneQubitZeroParamGate(), [0])
dag = circuit_to_dag(qc)
expected = QuantumCircuit(1, global_phase=0.1 + 2 * 0.2)
expected.append(OneQubitOneParamGate(pi), [0])
expected.append(OneQubitOneParamGate(pi), [0])
expected_dag = circuit_to_dag(expected)
pass_ = BasisTranslator(eq_lib, ["1q1p"])
actual = pass_.run(dag)
self.assertEqual(actual, expected_dag)
def test_two_single_two_gate_substitutions_with_global_phase(self):
"""Verify we correctly unroll gates through a single equivalence with global phase."""
eq_lib = EquivalenceLibrary()
gate = OneQubitZeroParamGate()
equiv = QuantumCircuit(1, global_phase=0.2)
equiv.append(OneQubitOneParamGate(pi), [0])
equiv.append(OneQubitOneParamGate(pi), [0])
eq_lib.add_equivalence(gate, equiv)
qc = QuantumCircuit(1, global_phase=0.1)
qc.append(OneQubitZeroParamGate(), [0])
qc.append(OneQubitZeroParamGate(), [0])
dag = circuit_to_dag(qc)
expected = QuantumCircuit(1, global_phase=0.1 + 2 * 0.2)
expected.append(OneQubitOneParamGate(pi), [0])
expected.append(OneQubitOneParamGate(pi), [0])
expected.append(OneQubitOneParamGate(pi), [0])
expected.append(OneQubitOneParamGate(pi), [0])
expected_dag = circuit_to_dag(expected)
pass_ = BasisTranslator(eq_lib, ["1q1p"])
actual = pass_.run(dag)
self.assertEqual(actual, expected_dag)
def test_double_substitution_with_global_phase(self):
"""Verify we correctly unroll gates through multiple equivalences with global phase."""
eq_lib = EquivalenceLibrary()
gate = OneQubitZeroParamGate()
equiv = QuantumCircuit(1, global_phase=0.2)
equiv.append(OneQubitOneParamGate(pi), [0])
eq_lib.add_equivalence(gate, equiv)
theta = Parameter("theta")
gate = OneQubitOneParamGate(theta)
equiv = QuantumCircuit(1, global_phase=0.4)
equiv.append(OneQubitTwoParamGate(theta, pi / 2), [0])
eq_lib.add_equivalence(gate, equiv)
qc = QuantumCircuit(1, global_phase=0.1)
qc.append(OneQubitZeroParamGate(), [0])
dag = circuit_to_dag(qc)
expected = QuantumCircuit(1, global_phase=0.1 + 0.2 + 0.4)
expected.append(OneQubitTwoParamGate(pi, pi / 2), [0])
expected_dag = circuit_to_dag(expected)
pass_ = BasisTranslator(eq_lib, ["1q2p"])
actual = pass_.run(dag)
self.assertEqual(actual, expected_dag)
def test_multiple_variadic(self):
"""Verify circuit with multiple instances of variadic gate."""
eq_lib = EquivalenceLibrary()
# e.g. MSGate
oneq_gate = VariadicZeroParamGate(1)
equiv = QuantumCircuit(1)
equiv.append(OneQubitZeroParamGate(), [0])
eq_lib.add_equivalence(oneq_gate, equiv)
twoq_gate = VariadicZeroParamGate(2)
equiv = QuantumCircuit(2)
equiv.append(TwoQubitZeroParamGate(), [0, 1])
eq_lib.add_equivalence(twoq_gate, equiv)
qc = QuantumCircuit(2)
qc.append(VariadicZeroParamGate(1), [0])
qc.append(VariadicZeroParamGate(2), [0, 1])
dag = circuit_to_dag(qc)
expected = QuantumCircuit(2)
expected.append(OneQubitZeroParamGate(), [0])
expected.append(TwoQubitZeroParamGate(), [0, 1])
expected_dag = circuit_to_dag(expected)
pass_ = BasisTranslator(eq_lib, ["1q0p", "2q0p"])
actual = pass_.run(dag)
self.assertEqual(actual, expected_dag)
def test_diamond_path(self):
"""Verify we find a path when there are multiple paths to the target basis."""
eq_lib = EquivalenceLibrary()
# Path 1: 1q0p -> 1q1p(pi) -> 1q2p(pi, pi/2)
gate = OneQubitZeroParamGate()
equiv = QuantumCircuit(1)
equiv.append(OneQubitOneParamGate(pi), [0])
eq_lib.add_equivalence(gate, equiv)
theta = Parameter("theta")
gate = OneQubitOneParamGate(theta)
equiv = QuantumCircuit(1)
equiv.append(OneQubitTwoParamGate(theta, pi / 2), [0])
eq_lib.add_equivalence(gate, equiv)
# Path 2: 1q0p -> 1q1p_prime(pi/2) -> 1q2p(2 * pi/2, pi/2)
gate = OneQubitZeroParamGate()
equiv = QuantumCircuit(1)
equiv.append(OneQubitOneParamPrimeGate(pi / 2), [0])
eq_lib.add_equivalence(gate, equiv)
alpha = Parameter("alpha")
gate = OneQubitOneParamPrimeGate(alpha)
equiv = QuantumCircuit(1)
equiv.append(OneQubitTwoParamGate(2 * alpha, pi / 2), [0])
eq_lib.add_equivalence(gate, equiv)
qc = QuantumCircuit(1)
qc.append(OneQubitZeroParamGate(), [0])
dag = circuit_to_dag(qc)
expected = QuantumCircuit(1)
expected.append(OneQubitTwoParamGate(pi, pi / 2), [0])
expected_dag = circuit_to_dag(expected)
pass_ = BasisTranslator(eq_lib, ["1q2p"])
actual = pass_.run(dag)
self.assertEqual(actual, expected_dag)
def test_if_else(self):
"""Test a simple if-else with parameters."""
qubits = [Qubit(), Qubit()]
clbits = [Clbit(), Clbit()]
alpha = Parameter("alpha")
beta = Parameter("beta")
gate = OneQubitOneParamGate(alpha)
equiv = QuantumCircuit([qubits[0]])
equiv.append(OneQubitZeroParamGate(name="1q0p_2"), [qubits[0]])
equiv.append(OneQubitOneParamGate(alpha, name="1q1p_2"), [qubits[0]])
eq_lib = EquivalenceLibrary()
eq_lib.add_equivalence(gate, equiv)
circ = QuantumCircuit(qubits, clbits)
circ.append(OneQubitOneParamGate(beta), [qubits[0]])
circ.measure(qubits[0], clbits[1])
with circ.if_test((clbits[1], 0)) as else_:
circ.append(OneQubitOneParamGate(alpha), [qubits[0]])
circ.append(TwoQubitZeroParamGate(), qubits)
with else_:
circ.append(TwoQubitZeroParamGate(), [qubits[1], qubits[0]])
dag = circuit_to_dag(circ)
dag_translated = BasisTranslator(eq_lib, ["if_else", "1q0p_2", "1q1p_2", "2q0p"]).run(dag)
expected = QuantumCircuit(qubits, clbits)
expected.append(OneQubitZeroParamGate(name="1q0p_2"), [qubits[0]])
expected.append(OneQubitOneParamGate(beta, name="1q1p_2"), [qubits[0]])
expected.measure(qubits[0], clbits[1])
with expected.if_test((clbits[1], 0)) as else_:
expected.append(OneQubitZeroParamGate(name="1q0p_2"), [qubits[0]])
expected.append(OneQubitOneParamGate(alpha, name="1q1p_2"), [qubits[0]])
expected.append(TwoQubitZeroParamGate(), qubits)
with else_:
expected.append(TwoQubitZeroParamGate(), [qubits[1], qubits[0]])
dag_expected = circuit_to_dag(expected)
self.assertEqual(dag_translated, dag_expected)
def test_nested_loop(self):
"""Test a simple if-else with parameters."""
qubits = [Qubit(), Qubit()]
clbits = [Clbit(), Clbit()]
cr = ClassicalRegister(bits=clbits)
index1 = Parameter("index1")
alpha = Parameter("alpha")
gate = OneQubitOneParamGate(alpha)
equiv = QuantumCircuit([qubits[0]])
equiv.append(OneQubitZeroParamGate(name="1q0p_2"), [qubits[0]])
equiv.append(OneQubitOneParamGate(alpha, name="1q1p_2"), [qubits[0]])
eq_lib = EquivalenceLibrary()
eq_lib.add_equivalence(gate, equiv)
circ = QuantumCircuit(qubits, cr)
with circ.for_loop(range(3), loop_parameter=index1) as ind:
with circ.while_loop((cr, 0)):
circ.append(OneQubitOneParamGate(alpha * ind), [qubits[0]])
dag = circuit_to_dag(circ)
dag_translated = BasisTranslator(
eq_lib, ["if_else", "for_loop", "while_loop", "1q0p_2", "1q1p_2"]
).run(dag)
expected = QuantumCircuit(qubits, cr)
with expected.for_loop(range(3), loop_parameter=index1) as ind:
with expected.while_loop((cr, 0)):
expected.append(OneQubitZeroParamGate(name="1q0p_2"), [qubits[0]])
expected.append(OneQubitOneParamGate(alpha * ind, name="1q1p_2"), [qubits[0]])
dag_expected = circuit_to_dag(expected)
self.assertEqual(dag_translated, dag_expected)
def test_different_bits(self):
"""Test that the basis translator correctly works when the inner blocks of control-flow
operations are not over the same bits as the outer blocks."""
base = QuantumCircuit([Qubit() for _ in [None] * 4], [Clbit()])
for_body = QuantumCircuit([Qubit(), Qubit()])
for_body.h(0)
for_body.cz(0, 1)
base.for_loop((1,), None, for_body, [1, 2], [])
while_body = QuantumCircuit([Qubit(), Qubit(), Clbit()])
while_body.cz(0, 1)
true_body = QuantumCircuit([Qubit(), Qubit(), Clbit()])
true_body.measure(0, 0)
true_body.while_loop((0, True), while_body, [0, 1], [0])
false_body = QuantumCircuit([Qubit(), Qubit(), Clbit()])
false_body.cz(0, 1)
base.if_else((0, True), true_body, false_body, [0, 3], [0])
basis = {"rz", "sx", "cx", "for_loop", "if_else", "while_loop", "measure"}
out = BasisTranslator(std_eqlib, basis).run(circuit_to_dag(base))
self.assertEqual(set(out.count_ops(recurse=True)), basis)
class TestUnrollerCompatability(QiskitTestCase):
"""Tests backward compatability with the Unroller pass.
Duplicate of TestUnroller from test.python.transpiler.test_unroller with
Unroller replaced by UnrollCustomDefinitions -> BasisTranslator.
"""
def test_basic_unroll(self):
"""Test decompose a single H into u2."""
qr = QuantumRegister(1, "qr")
circuit = QuantumCircuit(qr)
circuit.h(qr[0])
dag = circuit_to_dag(circuit)
pass_ = UnrollCustomDefinitions(std_eqlib, ["u2"])
dag = pass_.run(dag)
pass_ = BasisTranslator(std_eqlib, ["u2"])
unrolled_dag = pass_.run(dag)
op_nodes = unrolled_dag.op_nodes()
self.assertEqual(len(op_nodes), 1)
self.assertEqual(op_nodes[0].name, "u2")
def test_unroll_toffoli(self):
"""Test unroll toffoli on multi regs to h, t, tdg, cx."""
qr1 = QuantumRegister(2, "qr1")
qr2 = QuantumRegister(1, "qr2")
circuit = QuantumCircuit(qr1, qr2)
circuit.ccx(qr1[0], qr1[1], qr2[0])
dag = circuit_to_dag(circuit)
pass_ = UnrollCustomDefinitions(std_eqlib, ["h", "t", "tdg", "cx"])
dag = pass_.run(dag)
pass_ = BasisTranslator(std_eqlib, ["h", "t", "tdg", "cx"])
unrolled_dag = pass_.run(dag)
op_nodes = unrolled_dag.op_nodes()
self.assertEqual(len(op_nodes), 15)
for node in op_nodes:
self.assertIn(node.name, ["h", "t", "tdg", "cx"])
def test_unroll_1q_chain_conditional(self):
"""Test unroll chain of 1-qubit gates interrupted by conditional."""
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ βββββ βββββ Β»
# qr: β€ H ββ€ Tdg ββ€ Z ββ€ T ββ€ Ry(0.5) ββ€ Rz(0.3) ββ€ Rx(0.1) ββ€Mβββ€ X ββββ€ Y ββΒ»
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ₯β βββ₯ββ βββ₯ββ Β»
# β ββββ¨βββββββ¨βββΒ»
# cr: 1/βββββββββββββββββββββββββββββββββββββββββββββββββββββββ©ββ‘ 0x1 ββ‘ 0x1 βΒ»
# 0 ββββββββββββββΒ»
# Β« βββββ
# Β« qr: ββ€ Z ββ
# Β« βββ₯ββ
# Β« ββββ¨βββ
# Β«cr: 1/β‘ 0x1 β
# Β« βββββββ
qr = QuantumRegister(1, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.h(qr)
circuit.tdg(qr)
circuit.z(qr)
circuit.t(qr)
circuit.ry(0.5, qr)
circuit.rz(0.3, qr)
circuit.rx(0.1, qr)
circuit.measure(qr, cr)
circuit.x(qr).c_if(cr, 1)
circuit.y(qr).c_if(cr, 1)
circuit.z(qr).c_if(cr, 1)
dag = circuit_to_dag(circuit)
pass_ = UnrollCustomDefinitions(std_eqlib, ["u1", "u2", "u3"])
dag = pass_.run(dag)
pass_ = BasisTranslator(std_eqlib, ["u1", "u2", "u3"])
unrolled_dag = pass_.run(dag)
# Pick up -1 * 0.3 / 2 global phase for one RZ -> U1.
#
# global phase: 6.1332
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββΒ»
# qr: β€ U2(0,Ο) ββ€ U1(-Ο/4) ββ€ U1(Ο) ββ€ U1(Ο/4) ββ€ U3(0.5,0,0) ββ€ U1(0.3) βΒ»
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββΒ»
# cr: 1/βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββΒ»
# Β»
# Β« ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# Β« qr: β€ U3(0.1,-Ο/2,Ο/2) ββ€Mββ€ U3(Ο,0,Ο) ββ€ U3(Ο,Ο/2,Ο/2) ββ€ U1(Ο) β
# Β« ββββββββββββββββββββββ₯ββββββββ₯βββββββββββββββ₯βββββββββββββ₯ββββ
# Β« β ββββ¨βββ ββββ¨βββ ββββ¨βββ
# Β«cr: 1/ββββββββββββββββββββββ©βββββ‘ 0x1 ββββββββββ‘ 0x1 ββββββββ‘ 0x1 ββ
# Β« 0 βββββββ βββββββ βββββββ
ref_circuit = QuantumCircuit(qr, cr, global_phase=-0.3 / 2)
ref_circuit.append(U2Gate(0, pi), [qr[0]])
ref_circuit.append(U1Gate(-pi / 4), [qr[0]])
ref_circuit.append(U1Gate(pi), [qr[0]])
ref_circuit.append(U1Gate(pi / 4), [qr[0]])
ref_circuit.append(U3Gate(0.5, 0, 0), [qr[0]])
ref_circuit.append(U1Gate(0.3), [qr[0]])
ref_circuit.append(U3Gate(0.1, -pi / 2, pi / 2), [qr[0]])
ref_circuit.measure(qr[0], cr[0])
ref_circuit.append(U3Gate(pi, 0, pi), [qr[0]]).c_if(cr, 1)
ref_circuit.append(U3Gate(pi, pi / 2, pi / 2), [qr[0]]).c_if(cr, 1)
ref_circuit.append(U1Gate(pi), [qr[0]]).c_if(cr, 1)
ref_dag = circuit_to_dag(ref_circuit)
self.assertEqual(unrolled_dag, ref_dag)
def test_unroll_no_basis(self):
"""Test when a given gate has no decompositions."""
qr = QuantumRegister(1, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.h(qr)
dag = circuit_to_dag(circuit)
pass_ = UnrollCustomDefinitions(std_eqlib, [])
dag = pass_.run(dag)
pass_ = BasisTranslator(std_eqlib, [])
with self.assertRaises(QiskitError):
pass_.run(dag)
def test_unroll_all_instructions(self):
"""Test unrolling a circuit containing all standard instructions."""
qr = QuantumRegister(3, "qr")
cr = ClassicalRegister(3, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.crx(0.5, qr[1], qr[2])
circuit.cry(0.5, qr[1], qr[2])
circuit.ccx(qr[0], qr[1], qr[2])
circuit.ch(qr[0], qr[2])
circuit.crz(0.5, qr[1], qr[2])
circuit.cswap(qr[1], qr[0], qr[2])
circuit.append(CU1Gate(0.1), [qr[0], qr[2]])
circuit.append(CU3Gate(0.2, 0.1, 0.0), [qr[1], qr[2]])
circuit.cx(qr[1], qr[0])
circuit.cy(qr[1], qr[2])
circuit.cz(qr[2], qr[0])
circuit.h(qr[1])
circuit.i(qr[0])
circuit.rx(0.1, qr[0])
circuit.ry(0.2, qr[1])
circuit.rz(0.3, qr[2])
circuit.rzz(0.6, qr[1], qr[0])
circuit.s(qr[0])
circuit.sdg(qr[1])
circuit.swap(qr[1], qr[2])
circuit.t(qr[2])
circuit.tdg(qr[0])
circuit.append(U1Gate(0.1), [qr[1]])
circuit.append(U2Gate(0.2, -0.1), [qr[0]])
circuit.append(U3Gate(0.3, 0.0, -0.1), [qr[2]])
circuit.x(qr[2])
circuit.y(qr[1])
circuit.z(qr[0])
# circuit.snapshot('0')
# circuit.measure(qr, cr)
dag = circuit_to_dag(circuit)
pass_ = UnrollCustomDefinitions(std_eqlib, ["u3", "cx", "id"])
dag = pass_.run(dag)
pass_ = BasisTranslator(std_eqlib, ["u3", "cx", "id"])
unrolled_dag = pass_.run(dag)
ref_circuit = QuantumCircuit(qr, cr)
ref_circuit.append(U3Gate(0, 0, pi / 2), [qr[2]])
ref_circuit.cx(qr[1], qr[2])
ref_circuit.append(U3Gate(-0.25, 0, 0), [qr[2]])
ref_circuit.cx(qr[1], qr[2])
ref_circuit.append(U3Gate(0.25, -pi / 2, 0), [qr[2]])
ref_circuit.append(U3Gate(0.25, 0, 0), [qr[2]])
ref_circuit.cx(qr[1], qr[2])
ref_circuit.append(U3Gate(-0.25, 0, 0), [qr[2]])
ref_circuit.cx(qr[1], qr[2])
ref_circuit.append(U3Gate(pi / 2, 0, pi), [qr[2]])
ref_circuit.cx(qr[1], qr[2])
ref_circuit.append(U3Gate(0, 0, -pi / 4), [qr[2]])
ref_circuit.cx(qr[0], qr[2])
ref_circuit.append(U3Gate(0, 0, pi / 4), [qr[2]])
ref_circuit.cx(qr[1], qr[2])
ref_circuit.append(U3Gate(0, 0, pi / 4), [qr[1]])
ref_circuit.append(U3Gate(0, 0, -pi / 4), [qr[2]])
ref_circuit.cx(qr[0], qr[2])
ref_circuit.cx(qr[0], qr[1])
ref_circuit.append(U3Gate(0, 0, pi / 4), [qr[0]])
ref_circuit.append(U3Gate(0, 0, -pi / 4), [qr[1]])
ref_circuit.cx(qr[0], qr[1])
ref_circuit.append(U3Gate(0, 0, pi / 4), [qr[2]])
ref_circuit.append(U3Gate(pi / 2, 0, pi), [qr[2]])
ref_circuit.append(U3Gate(0, 0, pi / 2), [qr[2]])
ref_circuit.append(U3Gate(pi / 2, 0, pi), [qr[2]])
ref_circuit.append(U3Gate(0, 0, pi / 4), [qr[2]])
ref_circuit.cx(qr[0], qr[2])
ref_circuit.append(U3Gate(0, 0, -pi / 4), [qr[2]])
ref_circuit.append(U3Gate(pi / 2, 0, pi), [qr[2]])
ref_circuit.append(U3Gate(0, 0, -pi / 2), [qr[2]])
ref_circuit.append(U3Gate(0, 0, 0.25), [qr[2]])
ref_circuit.cx(qr[1], qr[2])
ref_circuit.append(U3Gate(0, 0, -0.25), [qr[2]])
ref_circuit.cx(qr[1], qr[2])
ref_circuit.cx(qr[2], qr[0])
ref_circuit.append(U3Gate(pi / 2, 0, pi), [qr[2]])
ref_circuit.cx(qr[0], qr[2])
ref_circuit.append(U3Gate(0, 0, -pi / 4), [qr[2]])
ref_circuit.cx(qr[1], qr[2])
ref_circuit.append(U3Gate(0, 0, pi / 4), [qr[2]])
ref_circuit.cx(qr[0], qr[2])
ref_circuit.append(U3Gate(0, 0, pi / 4), [qr[0]])
ref_circuit.append(U3Gate(0, 0, -pi / 4), [qr[2]])
ref_circuit.cx(qr[1], qr[2])
ref_circuit.cx(qr[1], qr[0])
ref_circuit.append(U3Gate(0, 0, -pi / 4), [qr[0]])
ref_circuit.append(U3Gate(0, 0, pi / 4), [qr[1]])
ref_circuit.cx(qr[1], qr[0])
ref_circuit.append(U3Gate(0, 0, 0.05), [qr[1]])
ref_circuit.append(U3Gate(0, 0, pi / 4), [qr[2]])
ref_circuit.append(U3Gate(pi / 2, 0, pi), [qr[2]])
ref_circuit.cx(qr[2], qr[0])
ref_circuit.append(U3Gate(0, 0, 0.05), [qr[0]])
ref_circuit.cx(qr[0], qr[2])
ref_circuit.append(U3Gate(0, 0, -0.05), [qr[2]])
ref_circuit.cx(qr[0], qr[2])
ref_circuit.append(U3Gate(0, 0, 0.05), [qr[2]])
ref_circuit.append(U3Gate(0, 0, -0.05), [qr[2]])
ref_circuit.cx(qr[1], qr[2])
ref_circuit.append(U3Gate(-0.1, 0, -0.05), [qr[2]])
ref_circuit.cx(qr[1], qr[2])
ref_circuit.cx(qr[1], qr[0])
ref_circuit.append(U3Gate(pi / 2, 0, pi), [qr[0]])
ref_circuit.append(U3Gate(0.1, 0.1, 0), [qr[2]])
ref_circuit.append(U3Gate(0, 0, -pi / 2), [qr[2]])
ref_circuit.cx(qr[1], qr[2])
ref_circuit.append(U3Gate(pi / 2, 0, pi), [qr[1]])
ref_circuit.append(U3Gate(0.2, 0, 0), [qr[1]])
ref_circuit.append(U3Gate(0, 0, pi / 2), [qr[2]])
ref_circuit.cx(qr[2], qr[0])
ref_circuit.append(U3Gate(pi / 2, 0, pi), [qr[0]])
ref_circuit.i(qr[0])
ref_circuit.append(U3Gate(0.1, -pi / 2, pi / 2), [qr[0]])
ref_circuit.cx(qr[1], qr[0])
ref_circuit.append(U3Gate(0, 0, 0.6), [qr[0]])
ref_circuit.cx(qr[1], qr[0])
ref_circuit.append(U3Gate(0, 0, pi / 2), [qr[0]])
ref_circuit.append(U3Gate(0, 0, -pi / 4), [qr[0]])
ref_circuit.append(U3Gate(pi / 2, 0.2, -0.1), [qr[0]])
ref_circuit.append(U3Gate(0, 0, pi), [qr[0]])
ref_circuit.append(U3Gate(0, 0, -pi / 2), [qr[1]])
ref_circuit.append(U3Gate(0, 0, 0.3), [qr[2]])
ref_circuit.cx(qr[1], qr[2])
ref_circuit.cx(qr[2], qr[1])
ref_circuit.cx(qr[1], qr[2])
ref_circuit.append(U3Gate(0, 0, 0.1), [qr[1]])
ref_circuit.append(U3Gate(pi, pi / 2, pi / 2), [qr[1]])
ref_circuit.append(U3Gate(0, 0, pi / 4), [qr[2]])
ref_circuit.append(U3Gate(0.3, 0.0, -0.1), [qr[2]])
ref_circuit.append(U3Gate(pi, 0, pi), [qr[2]])
# ref_circuit.snapshot('0')
# ref_circuit.measure(qr, cr)
# ref_dag = circuit_to_dag(ref_circuit)
self.assertTrue(Operator(dag_to_circuit(unrolled_dag)).equiv(ref_circuit))
def test_simple_unroll_parameterized_without_expressions(self):
"""Verify unrolling parameterized gates without expressions."""
qr = QuantumRegister(1)
qc = QuantumCircuit(qr)
theta = Parameter("theta")
qc.rz(theta, qr[0])
dag = circuit_to_dag(qc)
pass_ = UnrollCustomDefinitions(std_eqlib, ["u1", "cx"])
dag = pass_.run(dag)
unrolled_dag = BasisTranslator(std_eqlib, ["u1", "cx"]).run(dag)
expected = QuantumCircuit(qr, global_phase=-theta / 2)
expected.append(U1Gate(theta), [qr[0]])
self.assertEqual(circuit_to_dag(expected), unrolled_dag)
def test_simple_unroll_parameterized_with_expressions(self):
"""Verify unrolling parameterized gates with expressions."""
qr = QuantumRegister(1)
qc = QuantumCircuit(qr)
theta = Parameter("theta")
phi = Parameter("phi")
sum_ = theta + phi
qc.rz(sum_, qr[0])
dag = circuit_to_dag(qc)
pass_ = UnrollCustomDefinitions(std_eqlib, ["p", "cx"])
dag = pass_.run(dag)
unrolled_dag = BasisTranslator(std_eqlib, ["p", "cx"]).run(dag)
expected = QuantumCircuit(qr, global_phase=-sum_ / 2)
expected.p(sum_, qr[0])
self.assertEqual(circuit_to_dag(expected), unrolled_dag)
def test_definition_unroll_parameterized(self):
"""Verify that unrolling complex gates with parameters does not raise."""
qr = QuantumRegister(2)
qc = QuantumCircuit(qr)
theta = Parameter("theta")
qc.cp(theta, qr[1], qr[0])
qc.cp(theta * theta, qr[0], qr[1])
dag = circuit_to_dag(qc)
pass_ = UnrollCustomDefinitions(std_eqlib, ["p", "cx"])
dag = pass_.run(dag)
out_dag = BasisTranslator(std_eqlib, ["p", "cx"]).run(dag)
self.assertEqual(out_dag.count_ops(), {"p": 6, "cx": 4})
def test_unrolling_parameterized_composite_gates(self):
"""Verify unrolling circuits with parameterized composite gates."""
mock_sel = EquivalenceLibrary(base=std_eqlib)
qr1 = QuantumRegister(2)
subqc = QuantumCircuit(qr1)
theta = Parameter("theta")
subqc.rz(theta, qr1[0])
subqc.cx(qr1[0], qr1[1])
subqc.rz(theta, qr1[1])
# Expanding across register with shared parameter
qr2 = QuantumRegister(4)
qc = QuantumCircuit(qr2)
sub_instr = circuit_to_instruction(subqc, equivalence_library=mock_sel)
qc.append(sub_instr, [qr2[0], qr2[1]])
qc.append(sub_instr, [qr2[2], qr2[3]])
dag = circuit_to_dag(qc)
pass_ = UnrollCustomDefinitions(mock_sel, ["p", "cx"])
dag = pass_.run(dag)
out_dag = BasisTranslator(mock_sel, ["p", "cx"]).run(dag)
# Pick up -1 * theta / 2 global phase four twice (once for each RZ -> P
# in each of the two sub_instr instructions).
expected = QuantumCircuit(qr2, global_phase=-1 * 4 * theta / 2.0)
expected.p(theta, qr2[0])
expected.p(theta, qr2[2])
expected.cx(qr2[0], qr2[1])
expected.cx(qr2[2], qr2[3])
expected.p(theta, qr2[1])
expected.p(theta, qr2[3])
self.assertEqual(circuit_to_dag(expected), out_dag)
# Expanding across register with shared parameter
qc = QuantumCircuit(qr2)
phi = Parameter("phi")
gamma = Parameter("gamma")
sub_instr = circuit_to_instruction(subqc, {theta: phi}, mock_sel)
qc.append(sub_instr, [qr2[0], qr2[1]])
sub_instr = circuit_to_instruction(subqc, {theta: gamma}, mock_sel)
qc.append(sub_instr, [qr2[2], qr2[3]])
dag = circuit_to_dag(qc)
pass_ = UnrollCustomDefinitions(mock_sel, ["p", "cx"])
dag = pass_.run(dag)
out_dag = BasisTranslator(mock_sel, ["p", "cx"]).run(dag)
expected = QuantumCircuit(qr2, global_phase=-1 * (2 * phi + 2 * gamma) / 2.0)
expected.p(phi, qr2[0])
expected.p(gamma, qr2[2])
expected.cx(qr2[0], qr2[1])
expected.cx(qr2[2], qr2[3])
expected.p(phi, qr2[1])
expected.p(gamma, qr2[3])
self.assertEqual(circuit_to_dag(expected), out_dag)
class TestBasisExamples(QiskitTestCase):
"""Test example circuits targeting example bases over the StandardEquivalenceLibrary."""
def test_cx_bell_to_cz(self):
"""Verify we can translate a CX bell circuit to CZ,RX,RZ."""
bell = QuantumCircuit(2)
bell.h(0)
bell.cx(0, 1)
in_dag = circuit_to_dag(bell)
out_dag = BasisTranslator(std_eqlib, ["cz", "rx", "rz"]).run(in_dag)
self.assertTrue(set(out_dag.count_ops()).issubset(["cz", "rx", "rz"]))
self.assertEqual(Operator(bell), Operator(dag_to_circuit(out_dag)))
def test_cx_bell_to_iswap(self):
"""Verify we can translate a CX bell to iSwap,U3."""
bell = QuantumCircuit(2)
bell.h(0)
bell.cx(0, 1)
in_dag = circuit_to_dag(bell)
out_dag = BasisTranslator(std_eqlib, ["iswap", "u"]).run(in_dag)
self.assertTrue(set(out_dag.count_ops()).issubset(["iswap", "u"]))
self.assertEqual(Operator(bell), Operator(dag_to_circuit(out_dag)))
def test_cx_bell_to_ecr(self):
"""Verify we can translate a CX bell to ECR,U."""
bell = QuantumCircuit(2)
bell.h(0)
bell.cx(0, 1)
in_dag = circuit_to_dag(bell)
out_dag = BasisTranslator(std_eqlib, ["ecr", "u"]).run(in_dag)
# ββββββββββββββ βββββββββββββββββββββββββββββββββββ
# q_0: ββββ€ U(Ο/2,0,Ο) βββββ€ U(0,0,-Ο/2) ββ€0 ββ€ U(Ο,0,Ο) β
# ββββ΄βββββββββββββ΄βββββββββββββββββββ Ecr βββββββββββββ
# q_1: β€ U(-Ο/2,-Ο/2,Ο/2) βββββββββββββββββ€1 βββββββββββββ
# ββββββββββββββββββββ ββββββββ
qr = QuantumRegister(2, "q")
expected = QuantumCircuit(2)
expected.u(pi / 2, 0, pi, qr[0])
expected.u(0, 0, -pi / 2, qr[0])
expected.u(-pi / 2, -pi / 2, pi / 2, qr[1])
expected.ecr(0, 1)
expected.u(pi, 0, pi, qr[0])
expected_dag = circuit_to_dag(expected)
self.assertEqual(out_dag, expected_dag)
def test_cx_bell_to_cp(self):
"""Verify we can translate a CX bell to CP,U."""
bell = QuantumCircuit(2)
bell.h(0)
bell.cx(0, 1)
in_dag = circuit_to_dag(bell)
out_dag = BasisTranslator(std_eqlib, ["cp", "u"]).run(in_dag)
self.assertTrue(set(out_dag.count_ops()).issubset(["cp", "u"]))
self.assertEqual(Operator(bell), Operator(dag_to_circuit(out_dag)))
qr = QuantumRegister(2, "q")
expected = QuantumCircuit(qr)
expected.u(pi / 2, 0, pi, 0)
expected.u(pi / 2, 0, pi, 1)
expected.cp(pi, 0, 1)
expected.u(pi / 2, 0, pi, 1)
expected_dag = circuit_to_dag(expected)
self.assertEqual(out_dag, expected_dag)
def test_cx_bell_to_crz(self):
"""Verify we can translate a CX bell to CRZ,U."""
bell = QuantumCircuit(2)
bell.h(0)
bell.cx(0, 1)
in_dag = circuit_to_dag(bell)
out_dag = BasisTranslator(std_eqlib, ["crz", "u"]).run(in_dag)
self.assertTrue(set(out_dag.count_ops()).issubset(["crz", "u"]))
self.assertEqual(Operator(bell), Operator(dag_to_circuit(out_dag)))
qr = QuantumRegister(2, "q")
expected = QuantumCircuit(qr)
expected.u(pi / 2, 0, pi, 0)
expected.u(0, 0, pi / 2, 0)
expected.u(pi / 2, 0, pi, 1)
expected.crz(pi, 0, 1)
expected.u(pi / 2, 0, pi, 1)
expected_dag = circuit_to_dag(expected)
self.assertEqual(out_dag, expected_dag)
def test_global_phase(self):
"""Verify global phase preserved in basis translation"""
circ = QuantumCircuit(1)
gate_angle = pi / 5
circ_angle = pi / 3
circ.rz(gate_angle, 0)
circ.global_phase = circ_angle
in_dag = circuit_to_dag(circ)
out_dag = BasisTranslator(std_eqlib, ["p"]).run(in_dag)
qr = QuantumRegister(1, "q")
expected = QuantumCircuit(qr)
expected.p(gate_angle, qr)
expected.global_phase = circ_angle - gate_angle / 2
expected_dag = circuit_to_dag(expected)
self.assertEqual(out_dag, expected_dag)
self.assertAlmostEqual(
float(out_dag.global_phase), float(expected_dag.global_phase), places=14
)
self.assertEqual(Operator(dag_to_circuit(out_dag)), Operator(expected))
def test_condition_set_substitute_node(self):
"""Verify condition is set in BasisTranslator on substitute_node"""
# βββββ βββββ
# q_0: β€ H ββββ βββββββ€ H ββ
# ββββββββ΄βββββ βββ₯ββ
# q_1: ββββββ€ X ββ€Mβββββ«βββ
# βββββββ₯βββββ¨βββ
# c: 2/ββββββββββββ©ββ‘ 0x1 β
# 1 βββββββ
qr = QuantumRegister(2, "q")
cr = ClassicalRegister(2, "c")
circ = QuantumCircuit(qr, cr)
circ.h(0)
circ.cx(0, 1)
circ.measure(1, 1)
circ.h(0).c_if(cr, 1)
circ_transpiled = transpile(circ, optimization_level=3, basis_gates=["cx", "id", "u"])
# ββββββββββββββ ββββββββββββββ
# q_0: β€ U(Ο/2,0,Ο) ββββ ββββββ€ U(Ο/2,0,Ο) β
# βββββββββββββββββ΄ββββββββββββ₯βββββββ
# q_1: βββββββββββββββ€ X ββ€Mββββββββ«βββββββ
# βββββββ₯β ββββ¨βββ
# c: 2/βββββββββββββββββββββ©βββββ‘ 0x1 βββββ
# 1 βββββββ
qr = QuantumRegister(2, "q")
cr = ClassicalRegister(2, "c")
expected = QuantumCircuit(qr, cr)
expected.u(pi / 2, 0, pi, 0)
expected.cx(0, 1)
expected.measure(1, 1)
expected.u(pi / 2, 0, pi, 0).c_if(cr, 1)
self.assertEqual(circ_transpiled, expected)
def test_skip_target_basis_equivalences_1(self):
"""Test that BasisTranslator skips gates in the target_basis - #6085"""
circ = QuantumCircuit()
qasm_file = os.path.join(
os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
"qasm",
"TestBasisTranslator_skip_target.qasm",
)
circ = circ.from_qasm_file(qasm_file)
circ_transpiled = transpile(
circ,
basis_gates=["id", "rz", "sx", "x", "cx"],
seed_transpiler=42,
)
self.assertEqual(circ_transpiled.count_ops(), {"cx": 91, "rz": 66, "sx": 22})
class TestBasisTranslatorWithTarget(QiskitTestCase):
"""Test the basis translator when running with a Target."""
def setUp(self):
super().setUp()
self.target = Target()
# U gate in qubit 0.
self.theta = Parameter("theta")
self.phi = Parameter("phi")
self.lam = Parameter("lambda")
u_props = {
(0,): InstructionProperties(duration=5.23e-8, error=0.00038115),
}
self.target.add_instruction(UGate(self.theta, self.phi, self.lam), u_props)
# Rz gate in qubit 1.
rz_props = {
(1,): InstructionProperties(duration=0.0, error=0),
}
self.target.add_instruction(RZGate(self.phi), rz_props)
# X gate in qubit 1.
x_props = {
(1,): InstructionProperties(
duration=3.5555555555555554e-08, error=0.00020056469709026198
),
}
self.target.add_instruction(XGate(), x_props)
# SX gate in qubit 1.
sx_props = {
(1,): InstructionProperties(
duration=3.5555555555555554e-08, error=0.00020056469709026198
),
}
self.target.add_instruction(SXGate(), sx_props)
cx_props = {
(0, 1): InstructionProperties(duration=5.23e-7, error=0.00098115),
(1, 0): InstructionProperties(duration=4.52e-7, error=0.00132115),
}
self.target.add_instruction(CXGate(), cx_props)
def test_2q_with_non_global_1q(self):
"""Test translation works with a 2q gate on an non-global 1q basis."""
qc = QuantumCircuit(2)
qc.cz(0, 1)
bt_pass = BasisTranslator(std_eqlib, target_basis=None, target=self.target)
output = bt_pass(qc)
# We need a second run of BasisTranslator to correct gates outside of
# the target basis. This is a known isssue, see:
# https://qiskit.org/documentation/release_notes.html#release-notes-0-19-0-known-issues
output = bt_pass(output)
expected = QuantumCircuit(2)
expected.rz(pi, 1)
expected.sx(1)
expected.rz(3 * pi / 2, 1)
expected.sx(1)
expected.rz(3 * pi, 1)
expected.cx(0, 1)
expected.rz(pi, 1)
expected.sx(1)
expected.rz(3 * pi / 2, 1)
expected.sx(1)
expected.rz(3 * pi, 1)
self.assertEqual(output, expected)
|
https://github.com/ahkatlio/QHSO_Basics_of_Qiskit
|
ahkatlio
|
from qiskit import QuantumCircuit
from qiskit.visualization import visualize_transition
qc = QuantumCircuit(1)
qc.y(0)
qc.draw('mpl')
visualize_transition(qc)
qc1 = QuantumCircuit(1)
qc1.x(0)
qc1.y(0)
qc1.draw('mpl')
visualize_transition(qc1)
|
https://github.com/anpaschool/QC-School-Fall2020
|
anpaschool
|
from qiskit import QuantumCircuit, execute,QuantumCircuit, ClassicalRegister, QuantumRegister, Aer
from math import pi
import numpy as np
from qiskit.visualization import plot_bloch_multivector, plot_histogram
%matplotlib inline
qc = QuantumCircuit(3)
# Apply H-gate to each qubit:
for qubit in range(3):
qc.h(qubit)
# See the circuit:
qc.draw('mpl')
# Let's see the result
def final_state(circuit):
backend = Aer.get_backend('statevector_simulator')
final_state = execute(circuit,backend).result().get_statevector()
return final_state
fs=final_state(qc)
fs
# In Jupyter Notebooks we can display this nicely using Latex.
# If not using Jupyter Notebooks you may need to remove the
# array_to_latex function and use print(final_state) instead.
from qiskit_textbook.tools import array_to_latex
array_to_latex(fs, pretext="\\text{Statevector} = ")
qchx = QuantumCircuit(2)
qchx.h(0)
qchx.x(1)
qchx.draw('mpl')
backend = Aer.get_backend('unitary_simulator')
unitary = execute(qchx,backend).result().get_unitary()
# In Jupyter Notebooks we can display this nicely using Latex.
# If not using Jupyter Notebooks you may need to remove the
# array_to_latex function and use print(unitary) instead.
from qiskit_textbook.tools import array_to_latex
array_to_latex(unitary, pretext="\\text{Circuit = }\n")
qci = QuantumCircuit(2)
qci.x(1)
qci.draw('mpl')
# Simulate the unitary
backend = Aer.get_backend('unitary_simulator')
unitary = execute(qci,backend).result().get_unitary()
# Display the results:
array_to_latex(unitary, pretext="\\text{Circuit = } ")
qcn = QuantumCircuit(2)
# Apply CNOT
qcn.cx(0,1)
# See the circuit:
qcn.draw('mpl')
qch = QuantumCircuit(2)
# Apply H-gate to the first:
qch.h(0)
qch.draw('mpl')
# # Let's see the result:
# backend = Aer.get_backend('statevector_simulator')
# final_state = execute(qch,backend).result().get_statevector()
fs1 = final_state(qch)
fs1
# # Print the statevector neatly:
array_to_latex(fs1, pretext="\\text{Statevector = }")
qchn = QuantumCircuit(2)
# Apply H-gate to the first:
qchn.h(0)
# Apply a CNOT:
qchn.cx(0,1)
qchn.draw('mpl')
# Let's see the result:
fs2 = final_state(qchn)
# Print the statevector neatly:
array_to_latex(fs2, pretext="\\text{Statevector = }")
qcu = QuantumCircuit(2)
# Apply H-gate to the first:
qcu.h(0)
qcu.draw('mpl')
# Let's see the result:
backend = Aer.get_backend('unitary_simulator')
final_state = execute(qcu,backend).result().get_unitary()
# Print the statevector neatly:
array_to_latex(final_state, pretext="\\text{Circuit = }")
qcm = QuantumCircuit(2,2)
# Apply H-gate to the first:
qcm.h(0)
qcm.draw('mpl')
qcm.cx(0,1)
qcm.measure([0,1],[0,1])
qcm.draw('mpl')
# Let's see the result:
backend = Aer.get_backend('qasm_simulator')
results = execute(qcm,backend, shots=1000).result()
counts = results.get_counts(qcm)
print(counts)
plot_histogram(counts)
import qiskit
qiskit.__qiskit_version__
|
https://github.com/dkp-quantum/Tutorials
|
dkp-quantum
|
%matplotlib inline
# Importing standard Qiskit libraries and configuring account
from qiskit import QuantumCircuit, execute, Aer, IBMQ
from qiskit.compiler import transpile, assemble
from qiskit.tools.jupyter import *
from qiskit.visualization import *
# Loading your IBM Q account(s)
provider = IBMQ.load_account()
import scipy
from scipy.stats import unitary_group
u = unitary_group.rvs(2)
print(u)
qc = QuantumCircuit(2)
qc.iso(u, [0], [])
qc = transpile(qc, basis_gates = ['u3', 'cx'], seed_transpiler=0, optimization_level=3)
circuit_drawer(qc)
import scipy
from scipy import linalg
h = scipy.linalg.hadamard(2)
import numpy as np
u1 = np.dot(h, u)
u2 = np.dot(u1, h)
c2 = []
for i in range (2):
c2.append(u2[i,i])
print(c2)
qc = QuantumCircuit(2)
qc.diagonal(c2, [0])
qc = transpile(qc, basis_gates = ['u3', 'cx'], seed_transpiler=0, optimization_level=3)
circuit_drawer(qc)
import scipy
from scipy.stats import unitary_group
u = unitary_group.rvs(4)
print(u)
qc = QuantumCircuit(4)
qc.iso(u, [0,1], [])
qc = transpile(qc, basis_gates = ['u3', 'cx'], seed_transpiler=0, optimization_level=3)
circuit_drawer(qc)
import scipy
from scipy import linalg
h = scipy.linalg.hadamard(4)/2
import numpy as np
u1 = np.dot(h, u)
u2 = np.dot(u1, h)
c2 = []
for i in range (4):
c2.append(u2[i,i])
print(c2)
qc = QuantumCircuit(4)
qc.diagonal(c2, [0, 1])
qc = transpile(qc, basis_gates = ['u3', 'cx'], seed_transpiler=0, optimization_level=3)
circuit_drawer(qc)
import scipy
from scipy.stats import unitary_group
u = unitary_group.rvs(8)
print(u)
qc = QuantumCircuit(4)
qc.iso(u, [0, 1, 2], [])
qc = transpile(qc, basis_gates = ['u3', 'cx'], seed_transpiler=0, optimization_level=3)
circuit_drawer(qc)
import scipy
from scipy import linalg
h = scipy.linalg.hadamard(8)/3
import numpy as np
u1 = np.dot(h, u)
u2 = np.dot(u1, h)
c2 = []
for i in range (8):
c2.append(u2[i,i])
print(c2)
qc = QuantumCircuit(4)
qc.diagonal(c2, [0, 1, 2])
qc = transpile(qc, basis_gates = ['u3', 'cx'], seed_transpiler=0, optimization_level=3)
circuit_drawer(qc)
import scipy
from scipy.stats import unitary_group
u = unitary_group.rvs(16)
print(u)
qc = QuantumCircuit(4)
qc.iso(u, [0, 1, 2, 3], [])
qc = transpile(qc, basis_gates = ['u3', 'cx'], seed_transpiler=0, optimization_level=3)
circuit_drawer(qc)
import scipy
from scipy import linalg
h = scipy.linalg.hadamard(16)/4
import numpy as np
u1 = np.dot(h, u)
u2 = np.dot(u1, h)
c2 = []
for i in range (16):
c2.append(u2[i,i])
print(c2)
qc = QuantumCircuit(4)
qc.diagonal(c2, [0, 1, 2, 3])
qc = transpile(qc, basis_gates = ['u3', 'cx'], seed_transpiler=0, optimization_level=3)
circuit_drawer(qc)
import scipy
from scipy.stats import unitary_group
u = unitary_group.rvs(32)
print(u)
qc = QuantumCircuit(8)
qc.iso(u, [0, 1, 2, 3, 4], [])
qc = transpile(qc, basis_gates = ['u3', 'cx'], seed_transpiler=0, optimization_level=3)
circuit_drawer(qc)
import scipy
from scipy import linalg
h = scipy.linalg.hadamard(32)/5
import numpy as np
u1 = np.dot(h, u)
u2 = np.dot(u1, h)
c2 = []
for i in range (32):
c2.append(u2[i,i])
print(c2)
qc = QuantumCircuit(8)
qc.diagonal(c2, [0, 1, 2, 3, 4])
qc = transpile(qc, basis_gates = ['u3', 'cx'], seed_transpiler=0, optimization_level=3)
circuit_drawer(qc)
import scipy
from scipy.stats import unitary_group
u = unitary_group.rvs(64)
print(u)
qc = QuantumCircuit(8)
qc.iso(u, [0, 1, 2, 3, 4, 5], [])
qc = transpile(qc, basis_gates = ['u3', 'cx'], seed_transpiler=0, optimization_level=3)
circuit_drawer(qc)
import scipy
from scipy import linalg
h = scipy.linalg.hadamard(64)/6
import numpy as np
u1 = np.dot(h, u)
u2 = np.dot(u1, h)
c2 = []
for i in range (64):
c2.append(u2[i,i])
print(c2)
qc = QuantumCircuit(8)
qc.diagonal(c2, [0, 1, 2, 3, 4, 5])
qc = transpile(qc, basis_gates = ['u3', 'cx'], seed_transpiler=0, optimization_level=3)
circuit_drawer(qc)
import scipy
from scipy.stats import unitary_group
u = unitary_group.rvs(128)
print(u)
qc = QuantumCircuit(8)
qc.iso(u, [0, 1, 2, 3, 4, 5, 6], [])
qc = transpile(qc, basis_gates = ['u3', 'cx'], seed_transpiler=0, optimization_level=3)
circuit_drawer(qc)
import scipy
from scipy import linalg
h = scipy.linalg.hadamard(128)/7
import numpy as np
u1 = np.dot(h, u)
u2 = np.dot(u1, h)
c2 = []
for i in range (128):
c2.append(u2[i,i])
print(c2)
qc = QuantumCircuit(8)
qc.diagonal(c2, [0, 1, 2, 3, 4, 5, 6])
qc = transpile(qc, basis_gates = ['u3', 'cx'], seed_transpiler=0, optimization_level=3)
circuit_drawer(qc)
import scipy
from scipy.stats import unitary_group
u = unitary_group.rvs(256)
print(u)
qc = QuantumCircuit(8)
qc.iso(u, [0, 1, 2, 3, 4, 5, 6, 7], [])
qc = transpile(qc, basis_gates = ['u3', 'cx'], seed_transpiler=0, optimization_level=3)
circuit_drawer(qc)
import scipy
from scipy import linalg
h = scipy.linalg.hadamard(256)/8
import numpy as np
u1 = np.dot(h, u)
u2 = np.dot(u1, h)
c2 = []
for i in range (256):
c2.append(u2[i,i])
print(c2)
qc = QuantumCircuit(8)
qc.diagonal(c2, [0, 1, 2, 3, 4, 5, 6, 7])
qc = transpile(qc, basis_gates = ['u3', 'cx'], seed_transpiler=0, optimization_level=3)
circuit_drawer(qc)
import scipy
from scipy.stats import unitary_group
u = unitary_group.rvs(512)
print(u)
qc = QuantumCircuit(16)
qc.iso(u, [0, 1, 2, 3, 4, 5, 6, 7, 8], [])
qc = transpile(qc, basis_gates = ['u3', 'cx'], seed_transpiler=0, optimization_level=3)
circuit_drawer(qc)
import scipy
from scipy import linalg
h = scipy.linalg.hadamard(512)/9
import numpy as np
u1 = np.dot(h, u)
u2 = np.dot(u1, h)
c2 = []
for i in range (512):
c2.append(u2[i,i])
print(c2)
qc = QuantumCircuit(16)
qc.diagonal(c2, [0, 1, 2, 3, 4, 5, 6, 7, 8])
qc = transpile(qc, basis_gates = ['u3', 'cx'], seed_transpiler=0, optimization_level=3)
circuit_drawer(qc)
import scipy
from scipy.stats import unitary_group
u = unitary_group.rvs(1024)
print(u)
qc = QuantumCircuit(16)
qc.iso(u, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [])
qc = transpile(qc, basis_gates = ['u3', 'cx'], seed_transpiler=0, optimization_level=3)
circuit_drawer(qc)
import scipy
from scipy import linalg
h = scipy.linalg.hadamard(1024)/10
import numpy as np
u1 = np.dot(h, u)
u2 = np.dot(u1, h)
c2 = []
for i in range (1024):
c2.append(u2[i,i])
print(c2)
qc = QuantumCircuit(16)
qc.diagonal(c2, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
qc = transpile(qc, basis_gates = ['u3', 'cx'], seed_transpiler=0, optimization_level=3)
circuit_drawer(qc)
|
https://github.com/vm6502q/qiskit-qrack-provider
|
vm6502q
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2018, 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 circuits and reference outputs for snapshot state instructions.
"""
import numpy as np
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.quantum_info.states import Statevector
# from qiskit.providers.aer.extensions.snapshot_expectation_value import *
# Backwards compatibility for Terra <= 0.13
if not hasattr(QuantumCircuit, 'i'):
QuantumCircuit.i = QuantumCircuit.iden
def snapshot_expval_labels():
"""List of labels for exp val snapshots."""
return [
"<H[0]>", "<H[1]>", "<X[0]>", "<X[1]>", "<Z[0]>", "<Z[1]>",
"<H[0], I[1]>", "<I[0], H[1]>", "<X[0], I[1]>", "<I[0], X[1]>",
"<Z[0], I[1]>", "<I[0], Z[1]>", "<X[0], X[1]>", "<Z[0], Z[1]>"
]
def snapshot_expval_params(pauli=False):
"""Dictionary of labels and params, qubits for exp val snapshots."""
if pauli:
X_wpo = [[1, 'X']]
Y_wpo = [[1, 'Y']]
Z_wpo = [[1, 'Z']]
H_wpo = [[1 / np.sqrt(2), 'X'], [1 / np.sqrt(2), 'Z']]
IX_wpo = [[1, 'IX']]
IY_wpo = [[1, 'IY']]
IZ_wpo = [[1, 'IZ']]
IH_wpo = [[1 / np.sqrt(2), 'IX'], [1 / np.sqrt(2), 'IZ']]
XX_wpo = [[1, 'XX']]
YY_wpo = [[1, 'YY']]
ZZ_wpo = [[1, 'ZZ']]
else:
X_wpo = np.array([[0, 1], [1, 0]], dtype=complex)
Y_wpo = np.array([[0, -1j], [1j, 0]], dtype=complex)
Z_wpo = np.array([[1, 0], [0, -1]], dtype=complex)
H_wpo = np.array([[1, 1], [1, -1]], dtype=complex) / np.sqrt(2)
IX_wpo = np.kron(np.eye(2), X_wpo)
IY_wpo = np.kron(np.eye(2), Y_wpo)
IZ_wpo = np.kron(np.eye(2), Z_wpo)
IH_wpo = np.kron(np.eye(2), H_wpo)
XX_wpo = np.kron(X_wpo, X_wpo)
YY_wpo = np.kron(Y_wpo, Y_wpo)
ZZ_wpo = np.kron(Z_wpo, Z_wpo)
return {
"<H[0]>": (H_wpo, [0]),
"<H[1]>": (H_wpo, [1]),
"<X[0]>": (X_wpo, [0]),
"<X[1]>": (X_wpo, [1]),
"<Y[1]>": (Y_wpo, [0]),
"<Y[1]>": (Y_wpo, [1]),
"<Z[0]>": (Z_wpo, [0]),
"<Z[1]>": (Z_wpo, [1]),
"<H[0], I[1]>": (IH_wpo, [0, 1]),
"<I[0], H[1]>": (IH_wpo, [1, 0]),
"<X[0], I[1]>": (IX_wpo, [0, 1]),
"<I[0], X[1]>": (IX_wpo, [1, 0]),
"<Y[0], I[1]>": (IY_wpo, [0, 1]),
"<I[0], Y[1]>": (IY_wpo, [1, 0]),
"<Z[0], I[1]>": (IZ_wpo, [0, 1]),
"<I[0], Z[1]>": (IZ_wpo, [1, 0]),
"<X[0], X[1]>": (XX_wpo, [0, 1]),
"<Y[0], Y[1]>": (YY_wpo, [0, 1]),
"<Z[0], Z[1]>": (ZZ_wpo, [0, 1]),
}
def snapshot_expval_circuits(pauli=False,
single_shot=False,
variance=False,
post_measure=False,
skip_measure=False):
"""SnapshotExpectationValue test circuits with deterministic counts"""
circuits = []
num_qubits = 2
qr = QuantumRegister(num_qubits)
cr = ClassicalRegister(num_qubits)
regs = (qr, cr)
# State |+1>
circuit = QuantumCircuit(*regs)
circuit.x(0)
circuit.h(1)
if not post_measure:
for label, (params,
qubits) in snapshot_expval_params(pauli=pauli).items():
circuit.snapshot_expectation_value(label,
params,
qubits,
single_shot=single_shot,
variance=variance)
circuit.barrier(qr)
if not skip_measure:
circuit.measure(qr, cr)
circuit.barrier(qr)
if post_measure:
for label, (params,
qubits) in snapshot_expval_params(pauli=pauli).items():
circuit.snapshot_expectation_value(label,
params,
qubits,
single_shot=single_shot,
variance=variance)
circuits.append(circuit)
# State |00> + |11>
circuit = QuantumCircuit(*regs)
circuit.h(0)
circuit.cx(0, 1)
if not post_measure:
for label, (params,
qubits) in snapshot_expval_params(pauli=pauli).items():
circuit.snapshot_expectation_value(label,
params,
qubits,
single_shot=single_shot,
variance=variance)
circuit.barrier(qr)
if not skip_measure:
circuit.measure(qr, cr)
circuit.barrier(qr)
if post_measure:
for label, (params,
qubits) in snapshot_expval_params(pauli=pauli).items():
circuit.snapshot_expectation_value(label,
params,
qubits,
single_shot=single_shot,
variance=variance)
circuits.append(circuit)
# State |10> -i|01>
circuit = QuantumCircuit(*regs)
circuit.h(0)
circuit.sdg(0)
circuit.cx(0, 1)
circuit.x(1)
if not post_measure:
for label, (params,
qubits) in snapshot_expval_params(pauli=pauli).items():
circuit.snapshot_expectation_value(label,
params,
qubits,
single_shot=single_shot,
variance=variance)
circuit.barrier(qr)
if not skip_measure:
circuit.measure(qr, cr)
circuit.barrier(qr)
if post_measure:
for label, (params,
qubits) in snapshot_expval_params(pauli=pauli).items():
circuit.snapshot_expectation_value(label,
params,
qubits,
single_shot=single_shot,
variance=variance)
circuits.append(circuit)
return circuits
def snapshot_expval_counts(shots):
"""SnapshotExpectationValue test circuits reference counts."""
targets = []
# State |+1>
targets.append({'0x1': shots / 2, '0x3': shots / 2})
# State |00> + |11>
targets.append({'0x0': shots / 2, '0x3': shots / 2})
# State |01> -i|01>
targets.append({'0x1': shots / 2, '0x2': shots / 2})
return targets
def snapshot_expval_final_statevecs():
"""SnapshotExpectationValue test circuits pre meas statevecs"""
# Get pre-measurement statevectors
statevecs = []
# State |+1>
statevec = Statevector.from_label('+1')
statevecs.append(statevec)
# State |00> + |11>
statevec = (Statevector.from_label('00') +
Statevector.from_label('11')) / np.sqrt(2)
statevecs.append(statevec)
# State |10> -i|01>
statevec = (Statevector.from_label('10') -
1j * Statevector.from_label('01')) / np.sqrt(2)
statevecs.append(statevec)
return statevecs
def snapshot_expval_pre_meas_values():
"""SnapshotExpectationValue test circuits reference final probs"""
targets = []
for statevec in snapshot_expval_final_statevecs():
values = {}
for label, (mat, qubits) in snapshot_expval_params().items():
values[label] = {
'0x0': statevec.data.conj().dot(statevec.evolve(mat, qubits).data)
}
targets.append(values)
return targets
def snapshot_expval_post_meas_values():
"""SnapshotExpectationValue test circuits reference final statevector"""
targets = []
for statevec in snapshot_expval_final_statevecs():
values = {}
for label, (mat, qubits) in snapshot_expval_params().items():
inner_dict = {}
for j in ['00', '01', '10', '11']:
# Check if non-zero measurement probability for given
# measurement outcome for final statevector
vec = Statevector.from_label(j)
if not np.isclose(vec.data.dot(statevec.data), 0):
# If outcome is non-zero compute expectation value
# with post-selected outcome state
inner_dict[hex(int(j, 2))] = vec.data.conj().dot(vec.evolve(mat, qubits).data)
values[label] = inner_dict
targets.append(values)
return targets
def snapshot_expval_circuit_parameterized(single_shot=False,
measure=True,
snapshot=False):
"""SnapshotExpectationValue test circuits, rewritten as a single parameterized circuit and
parameterizations array. """
num_qubits = 2
qr = QuantumRegister(num_qubits)
cr = ClassicalRegister(num_qubits)
regs = (qr, cr)
circuit = QuantumCircuit(*regs)
circuit.u3(0, 0, 0, 0)
circuit.u1(0, 0)
circuit.u3(0, 0, 0, 1)
circuit.cu3(0, 0, 0, 0, 1)
circuit.u3(0, 0, 0, 1)
circuit.i(0)
if snapshot:
for label, (params, qubits) in snapshot_expval_params(pauli=True).items():
circuit.snapshot_expectation_value(label,
params,
qubits,
single_shot=single_shot)
if measure:
circuit.barrier(qr)
circuit.measure(qr, cr)
circuit.barrier(qr)
# Parameterizations
# State |+1>
plus_one_params = {
# X on 0
(0, 0): np.pi,
(0, 1): 0,
(0, 2): np.pi,
# No rZ
(1, 0): 0,
# H on 1
(2, 0): np.pi / 2,
(2, 2): np.pi,
# No CrX
(3, 0): 0,
(3, 1): 0,
(3, 2): 0,
# No X
(4, 0): 0,
(4, 1): 0,
(4, 2): 0,
}
# State |00> + |11>
bell_params = {
# H 0
(0, 0): np.pi / 2,
(0, 1): 0,
(0, 2): np.pi,
# No rZ
(1, 0): 0,
# No H
(2, 0): 0,
(2, 2): 0,
# CX from 0 on 1
(3, 0): np.pi,
(3, 1): 0,
(3, 2): np.pi,
# No X
(4, 0): 0,
(4, 1): 0,
(4, 2): 0,
}
# State |10> -i|01>
iminus_bell_params = {
# H 0
(0, 0): np.pi / 2,
(0, 1): 0,
(0, 2): np.pi,
# S 0
(1, 0): - np.pi / 2,
# No H
(2, 0): 0,
(2, 2): 0,
# CX from 0 on 1
(3, 0): np.pi,
(3, 1): 0,
(3, 2): np.pi,
# X 1
(4, 0): np.pi,
(4, 1): 0,
(4, 2): np.pi,
}
param_mat = np.transpose([list(plus_one_params.values()),
list(bell_params.values()),
list(iminus_bell_params.values())]).tolist()
parameterizations = [[list(index), params]
for (index, params) in zip(plus_one_params.keys(), param_mat)]
return circuit, parameterizations
|
https://github.com/BOBO1997/osp_solutions
|
BOBO1997
|
import numpy as np
import matplotlib.pyplot as plt
import itertools
from pprint import pprint
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("../utils/")
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)
scale_factors = [1.0, 2.0, 3.0]
# 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_init110(qc, targets=[0, 1, 2]) # decode
# Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time
qc = qc.bind_parameters({dt: target_time / num_steps})
print("created qc")
# Generate state tomography circuits to evaluate fidelity of simulation
st_qcs = state_tomography_circuits(qc, [0, 1, 2][::-1]) #! state tomography requires === BIG ENDIAN ===
print("created st_qcs (length:", len(st_qcs), ")")
# remove barriers
st_qcs = [RemoveBarriers()(qc) for qc in st_qcs]
print("removed barriers from st_qcs")
# optimize circuit
t3_st_qcs = transpile(st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"])
t3_st_qcs = transpile(t3_st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"])
print("created t3_st_qcs (length:", len(t3_st_qcs), ")")
# zne wrapping
zne_qcs = zne_wrapper(t3_st_qcs, scale_factors = scale_factors, pt = True) # Pauli Twirling
print("created zne_qcs (length:", len(zne_qcs), ")")
# optimization_level must be 0
# feed initial_layout here to see the picture of the circuits before casting the job
t3_zne_qcs = transpile(zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout)
print("created t3_zne_qcs (length:", len(t3_zne_qcs), ")")
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-community', group='ibmquantumawards', project='open-science-22')
# print("provider:", provider)
# backend = provider.get_backend("ibmq_jakarta")
print(str(backend))
shots = 1 << 13
reps = 8 # unused
jobs = []
for _ in range(reps):
#! CHECK: run t3_zne_qcs, with optimization_level = 0 and straightforward initial_layout
job = execute(t3_zne_qcs, backend, shots=shots, optimization_level=0)
print('Job ID', job.job_id())
jobs.append(job)
# QREM
qr = QuantumRegister(num_qubits, name="calq")
meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal')
# we have to feed initial_layout to calibration matrix
cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout = initial_layout)
print('Job ID', cal_job.job_id())
meas_calibs[0].draw("mpl")
dt_now = datetime.datetime.now()
print(dt_now)
filename = "job_ids_" + str(backend) + "_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl"
print(filename)
# with open("jobs_" + str(backend) + "_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(filename, "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_" + str(backend) + "_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f:
# pickle.dump(backend.properties(), f)
retrieved_jobs = jobs
retrieved_cal_job = cal_job
cal_results = retrieved_cal_job.result()
meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal')
target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!!
fids = []
for job in retrieved_jobs:
mit_results = meas_fitter.filter.apply(job.result())
zne_expvals = zne_decoder(num_qubits, mit_results, scale_factors = scale_factors)
rho = expvals_to_valid_rho(num_qubits, zne_expvals)
fid = state_fidelity(rho, target_state)
fids.append(fid)
print('state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(fids), np.std(fids)))
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# -*- 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/2lambda123/Qiskit-qiskit
|
2lambda123
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 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.
"""Remove all barriers in a circuit"""
from qiskit.dagcircuit import DAGCircuit
from qiskit.transpiler.basepasses import TransformationPass
from qiskit.transpiler.passes.utils import control_flow
class RemoveBarriers(TransformationPass):
"""Return a circuit with any barrier removed.
This transformation is not semantics preserving.
Example:
.. plot::
:include-source:
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')
"""
@control_flow.trivial_recurse
def run(self, dag: DAGCircuit) -> DAGCircuit:
"""Run the RemoveBarriers pass on `dag`."""
dag.remove_all_ops_named("barrier")
return dag
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2021, 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.
"""Class for holding time evolution result."""
from __future__ import annotations
import numpy as np
from qiskit import QuantumCircuit
from qiskit.quantum_info import Statevector
from qiskit_algorithms.list_or_dict import ListOrDict
from ..algorithm_result import AlgorithmResult
class TimeEvolutionResult(AlgorithmResult):
"""
Class for holding time evolution result.
Attributes:
evolved_state (QuantumCircuit|Statevector): An evolved quantum state.
aux_ops_evaluated (ListOrDict[tuple[complex, complex]] | None): Optional list of
observables for which expected values on an evolved state are calculated. These values
are in fact tuples formatted as (mean, standard deviation).
observables (ListOrDict[tuple[np.ndarray, np.ndarray]] | None): Optional list of
observables for which expected on an evolved state are calculated at each timestep.
These values are in fact lists of tuples formatted as (mean, standard deviation).
times (np.array | None): Optional list of times at which each observable has been evaluated.
"""
def __init__(
self,
evolved_state: QuantumCircuit | Statevector,
aux_ops_evaluated: ListOrDict[tuple[complex, complex]] | None = None,
observables: ListOrDict[tuple[np.ndarray, np.ndarray]] | None = None,
times: np.ndarray | None = None,
):
"""
Args:
evolved_state: An evolved quantum state.
aux_ops_evaluated: Optional list of observables for which expected values on an evolved
state are calculated. These values are in fact tuples formatted as (mean, standard
deviation).
observables: Optional list of observables for which expected values are calculated for
each timestep. These values are in fact tuples formatted as (mean array, standard
deviation array).
times: Optional list of times at which each observable has been evaluated.
"""
self.evolved_state = evolved_state
self.aux_ops_evaluated = aux_ops_evaluated
self.observables = observables
self.times = times
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import matplotlib.pyplot as plt
from scipy.interpolate import griddata
%matplotlib inline
import numpy as np
from qiskit import QuantumRegister, QuantumCircuit, AncillaRegister, transpile
from qiskit.circuit.library import IntegerComparator, WeightedAdder, LinearAmplitudeFunction
from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem
from qiskit_aer.primitives import Sampler
from qiskit_finance.circuit.library import LogNormalDistribution
# number of qubits per dimension to represent the uncertainty
num_uncertainty_qubits = 2
# parameters for considered random distribution
S = 2.0 # initial spot price
vol = 0.4 # volatility of 40%
r = 0.05 # annual interest rate of 4%
T = 40 / 365 # 40 days to maturity
# resulting parameters for log-normal distribution
mu = (r - 0.5 * vol**2) * T + np.log(S)
sigma = vol * np.sqrt(T)
mean = np.exp(mu + sigma**2 / 2)
variance = (np.exp(sigma**2) - 1) * np.exp(2 * mu + sigma**2)
stddev = np.sqrt(variance)
# lowest and highest value considered for the spot price; in between, an equidistant discretization is considered.
low = np.maximum(0, mean - 3 * stddev)
high = mean + 3 * stddev
# map to higher dimensional distribution
# for simplicity assuming dimensions are independent and identically distributed)
dimension = 2
num_qubits = [num_uncertainty_qubits] * dimension
low = low * np.ones(dimension)
high = high * np.ones(dimension)
mu = mu * np.ones(dimension)
cov = sigma**2 * np.eye(dimension)
# construct circuit
u = LogNormalDistribution(num_qubits=num_qubits, mu=mu, sigma=cov, bounds=(list(zip(low, high))))
# plot PDF of uncertainty model
x = [v[0] for v in u.values]
y = [v[1] for v in u.values]
z = u.probabilities
# z = map(float, z)
# z = list(map(float, z))
resolution = np.array([2**n for n in num_qubits]) * 1j
grid_x, grid_y = np.mgrid[min(x) : max(x) : resolution[0], min(y) : max(y) : resolution[1]]
grid_z = griddata((x, y), z, (grid_x, grid_y))
plt.figure(figsize=(10, 8))
ax = plt.axes(projection="3d")
ax.plot_surface(grid_x, grid_y, grid_z, cmap=plt.cm.Spectral)
ax.set_xlabel("Spot Price $S_1$ (\$)", size=15)
ax.set_ylabel("Spot Price $S_2$ (\$)", size=15)
ax.set_zlabel("Probability (\%)", size=15)
plt.show()
# determine number of qubits required to represent total loss
weights = []
for n in num_qubits:
for i in range(n):
weights += [2**i]
# create aggregation circuit
agg = WeightedAdder(sum(num_qubits), weights)
n_s = agg.num_sum_qubits
n_aux = agg.num_qubits - n_s - agg.num_state_qubits # number of additional qubits
# set the strike price (should be within the low and the high value of the uncertainty)
strike_price_1 = 3
strike_price_2 = 4
# set the barrier threshold
barrier = 2.5
# map strike prices and barrier threshold from [low, high] to {0, ..., 2^n-1}
max_value = 2**n_s - 1
low_ = low[0]
high_ = high[0]
mapped_strike_price_1 = (
(strike_price_1 - dimension * low_) / (high_ - low_) * (2**num_uncertainty_qubits - 1)
)
mapped_strike_price_2 = (
(strike_price_2 - dimension * low_) / (high_ - low_) * (2**num_uncertainty_qubits - 1)
)
mapped_barrier = (barrier - low) / (high - low) * (2**num_uncertainty_qubits - 1)
# condition and condition result
conditions = []
barrier_thresholds = [2] * dimension
n_aux_conditions = 0
for i in range(dimension):
# target dimension of random distribution and corresponding condition (which is required to be True)
comparator = IntegerComparator(num_qubits[i], mapped_barrier[i] + 1, geq=False)
n_aux_conditions = max(n_aux_conditions, comparator.num_ancillas)
conditions += [comparator]
# set the approximation scaling for the payoff function
c_approx = 0.25
# setup piecewise linear objective fcuntion
breakpoints = [0, mapped_strike_price_1, mapped_strike_price_2]
slopes = [0, 1, 0]
offsets = [0, 0, mapped_strike_price_2 - mapped_strike_price_1]
f_min = 0
f_max = mapped_strike_price_2 - mapped_strike_price_1
objective = LinearAmplitudeFunction(
n_s,
slopes,
offsets,
domain=(0, max_value),
image=(f_min, f_max),
rescaling_factor=c_approx,
breakpoints=breakpoints,
)
# define overall multivariate problem
qr_state = QuantumRegister(u.num_qubits, "state") # to load the probability distribution
qr_obj = QuantumRegister(1, "obj") # to encode the function values
ar_sum = AncillaRegister(n_s, "sum") # number of qubits used to encode the sum
ar_cond = AncillaRegister(len(conditions) + 1, "conditions")
ar = AncillaRegister(
max(n_aux, n_aux_conditions, objective.num_ancillas), "work"
) # additional qubits
objective_index = u.num_qubits
# define the circuit
asian_barrier_spread = QuantumCircuit(qr_state, qr_obj, ar_cond, ar_sum, ar)
# load the probability distribution
asian_barrier_spread.append(u, qr_state)
# apply the conditions
for i, cond in enumerate(conditions):
state_qubits = qr_state[(num_uncertainty_qubits * i) : (num_uncertainty_qubits * (i + 1))]
asian_barrier_spread.append(cond, state_qubits + [ar_cond[i]] + ar[: cond.num_ancillas])
# aggregate the conditions on a single qubit
asian_barrier_spread.mcx(ar_cond[:-1], ar_cond[-1])
# apply the aggregation function controlled on the condition
asian_barrier_spread.append(agg.control(), [ar_cond[-1]] + qr_state[:] + ar_sum[:] + ar[:n_aux])
# apply the payoff function
asian_barrier_spread.append(objective, ar_sum[:] + qr_obj[:] + ar[: objective.num_ancillas])
# uncompute the aggregation
asian_barrier_spread.append(
agg.inverse().control(), [ar_cond[-1]] + qr_state[:] + ar_sum[:] + ar[:n_aux]
)
# uncompute the conditions
asian_barrier_spread.mcx(ar_cond[:-1], ar_cond[-1])
for j, cond in enumerate(reversed(conditions)):
i = len(conditions) - j - 1
state_qubits = qr_state[(num_uncertainty_qubits * i) : (num_uncertainty_qubits * (i + 1))]
asian_barrier_spread.append(
cond.inverse(), state_qubits + [ar_cond[i]] + ar[: cond.num_ancillas]
)
print(asian_barrier_spread.draw())
print("objective qubit index", objective_index)
# plot exact payoff function
plt.figure(figsize=(7, 5))
x = np.linspace(sum(low), sum(high))
y = (x <= 5) * np.minimum(np.maximum(0, x - strike_price_1), strike_price_2 - strike_price_1)
plt.plot(x, y, "r-")
plt.grid()
plt.title("Payoff Function (for $S_1 = S_2$)", size=15)
plt.xlabel("Sum of Spot Prices ($S_1 + S_2)$", size=15)
plt.ylabel("Payoff", size=15)
plt.xticks(size=15, rotation=90)
plt.yticks(size=15)
plt.show()
# plot contour of payoff function with respect to both time steps, including barrier
plt.figure(figsize=(7, 5))
z = np.zeros((17, 17))
x = np.linspace(low[0], high[0], 17)
y = np.linspace(low[1], high[1], 17)
for i, x_ in enumerate(x):
for j, y_ in enumerate(y):
z[i, j] = np.minimum(
np.maximum(0, x_ + y_ - strike_price_1), strike_price_2 - strike_price_1
)
if x_ > barrier or y_ > barrier:
z[i, j] = 0
plt.title("Payoff Function", size=15)
plt.contourf(x, y, z)
plt.colorbar()
plt.xlabel("Spot Price $S_1$", size=15)
plt.ylabel("Spot Price $S_2$", size=15)
plt.xticks(size=15)
plt.yticks(size=15)
plt.show()
# evaluate exact expected value
sum_values = np.sum(u.values, axis=1)
payoff = np.minimum(np.maximum(sum_values - strike_price_1, 0), strike_price_2 - strike_price_1)
leq_barrier = [np.max(v) <= barrier for v in u.values]
exact_value = np.dot(u.probabilities[leq_barrier], payoff[leq_barrier])
print("exact expected value:\t%.4f" % exact_value)
num_state_qubits = asian_barrier_spread.num_qubits - asian_barrier_spread.num_ancillas
print("state qubits: ", num_state_qubits)
transpiled = transpile(asian_barrier_spread, basis_gates=["u", "cx"])
print("circuit width:", transpiled.width())
print("circuit depth:", transpiled.depth())
asian_barrier_spread_measure = asian_barrier_spread.measure_all(inplace=False)
sampler = Sampler()
job = sampler.run(asian_barrier_spread_measure)
# evaluate the result
value = 0
probabilities = job.result().quasi_dists[0].binary_probabilities()
for i, prob in probabilities.items():
if prob > 1e-4 and i[-num_state_qubits:][0] == "1":
value += prob
# map value to original range
mapped_value = objective.post_processing(value) / (2**num_uncertainty_qubits - 1) * (high_ - low_)
print("Exact Operator Value: %.4f" % value)
print("Mapped Operator value: %.4f" % mapped_value)
print("Exact Expected Payoff: %.4f" % exact_value)
# set target precision and confidence level
epsilon = 0.01
alpha = 0.05
problem = EstimationProblem(
state_preparation=asian_barrier_spread,
objective_qubits=[objective_index],
post_processing=objective.post_processing,
)
# construct amplitude estimation
ae = IterativeAmplitudeEstimation(epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}))
result = ae.estimate(problem)
conf_int = (
np.array(result.confidence_interval_processed)
/ (2**num_uncertainty_qubits - 1)
* (high_ - low_)
)
print("Exact value: \t%.4f" % exact_value)
print(
"Estimated value:\t%.4f"
% (result.estimation_processed / (2**num_uncertainty_qubits - 1) * (high_ - low_))
)
print("Confidence interval: \t[%.4f, %.4f]" % tuple(conf_int))
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/JohnBurke4/qaoa_testing_framework
|
JohnBurke4
|
from Image_Reader import ImageReader
from DCT_Classic import DCT
import Quantum_Subroutines
import os
import Image_Compression
import cv2
import matplotlib.pyplot as plt
import numpy as np
from qiskit import QuantumCircuit, Aer, transpile
from qiskit_aer.backends.aerbackend import AerBackend
from qiskit.providers.fake_provider import FakeSydneyV2
from qiskit_aer import AerSimulator
import csv
import CustomUnitaryDecomp
np.set_printoptions(precision=3, suppress=True)
max = 16
path = "StateCompression/images/camera.png"
image = ImageReader.getImage(path)
image = cv2.resize(image, (max, max))
basis_gates = ['u1', 'u2', 'u3', 'cx', 'id']
basis_gates = ['u3', 'cx', 'id']
[U, D, V] = np.linalg.svd(image)
U[max-1, 0] *= -1
print(U)
thetas = []
for i in range(0, max-1):
val = U[i, 0]
print(val)
for theta in thetas:
val /= np.sin(theta)
print(val)
print()
thetas.append(np.arccos(val))
# print(thetas)
# print(np.cos(thetas[0]))
print("")
for i in range(0, max-1):
val = np.cos(thetas[i])
for j in range(i-1, -1, -1):
# print(j)
val *= np.sin(thetas[j])
print(val)
val = 1
for i in range(0, max-1):
val *= np.sin(thetas[i])
print(val)
|
https://github.com/nahumsa/volta
|
nahumsa
|
import sys
sys.path.append('../../')
# Python imports
import numpy as np
import matplotlib.pyplot as plt
# Qiskit
from qiskit import BasicAer, Aer
from qiskit.aqua import QuantumInstance
from qiskit.aqua.components.optimizers import COBYLA, SPSA
from qiskit.circuit.library import TwoLocal
# VOLTA
from volta.vqd import VQD
from volta.utils import classical_solver
from volta.hamiltonians import BCS_hamiltonian
%load_ext autoreload
%autoreload 2
EPSILONS = [3, 3]
V = -2.
hamiltonian = BCS_hamiltonian(EPSILONS, V)
print(hamiltonian)
eigenvalues, eigenvectors = classical_solver(hamiltonian)
print(f"Eigenvalues: {eigenvalues}")
from qiskit.providers.aer.noise import depolarizing_error
from qiskit.providers.aer.noise import thermal_relaxation_error
from qiskit.providers.aer.noise import NoiseModel
# Defining noise model
# T1 and T2 values for qubits 0-n
n_qubits = 2*len(EPSILONS)
# T1s = np.random.normal(50e3, 10e3, n_qubits) # Sampled from normal distribution mean 50 microsec
# T2s = np.random.normal(70e3, 10e3, n_qubits) # Sampled from normal distribution mean 50 microsec
T1s = [30e3]*n_qubits
T2s = [20e3]*n_qubits
# Truncate random T2s <= T1s
T2s = np.array([min(T2s[j], 2 * T1s[j]) for j in range(n_qubits)])
# Instruction times (in nanoseconds)
time_u1 = 0 # virtual gate
time_u2 = 50 # (single X90 pulse)
time_u3 = 100 # (two X90 pulses)
time_cx = 300
time_reset = 1000 # 1 microsecond
time_measure = 1000 # 1 microsecond
# QuantumError objects
errors_reset = [thermal_relaxation_error(t1, t2, time_reset)
for t1, t2 in zip(T1s, T2s)]
errors_measure = [thermal_relaxation_error(t1, t2, time_measure)
for t1, t2 in zip(T1s, T2s)]
errors_u1 = [thermal_relaxation_error(t1, t2, time_u1)
for t1, t2 in zip(T1s, T2s)]
errors_u2 = [thermal_relaxation_error(t1, t2, time_u2)
for t1, t2 in zip(T1s, T2s)]
errors_u3 = [thermal_relaxation_error(t1, t2, time_u3)
for t1, t2 in zip(T1s, T2s)]
errors_cx = [[thermal_relaxation_error(t1a, t2a, time_cx).expand(
thermal_relaxation_error(t1b, t2b, time_cx))
for t1a, t2a in zip(T1s, T2s)]
for t1b, t2b in zip(T1s, T2s)]
# Add errors to noise model
noise_thermal = NoiseModel()
for j in range(n_qubits):
noise_thermal.add_quantum_error(errors_reset[j], "reset", [j])
noise_thermal.add_quantum_error(errors_measure[j], "measure", [j])
noise_thermal.add_quantum_error(errors_u1[j], "u1", [j])
noise_thermal.add_quantum_error(errors_u2[j], "u2", [j])
noise_thermal.add_quantum_error(errors_u3[j], "u3", [j])
for k in range(n_qubits):
noise_thermal.add_quantum_error(errors_cx[j][k], "cx", [j, k])
print(noise_thermal)
from tqdm import tqdm
def hamiltonian_varying_V(min_V, max_V, points, epsilons, n_trials):
solution_VQD = {}
energies_Classical = []
V = np.linspace(min_V, max_V, points)
backend = QuantumInstance(backend= Aer.get_backend('qasm_simulator'),
noise_model=noise_thermal,
shots=10000)
optimizer = SPSA(maxiter=250, c1=1.2, last_avg=25)
#optimizer = COBYLA()
for v in tqdm(V):
hamiltonian = BCS_hamiltonian(epsilons, v)
ansatz = TwoLocal(hamiltonian.num_qubits, ['ry','rz'], 'cx', reps=3)
es_1 = []
es_2 = []
for _ in tqdm(range(n_trials), desc=f"V= {v}"):
# Run algorithm
Algo = VQD(hamiltonian=hamiltonian,
ansatz=ansatz,
n_excited_states=2,
beta=10.,
optimizer=optimizer,
backend=backend)
Algo.run(0)
vqd_energies = Algo.energies
es_1.append(vqd_energies[1])
es_2.append(vqd_energies[2])
es_1 = np.array(es_1)
es_2 = np.array(es_2)
solution_VQD[v] = {'mean':np.mean(es_2 - es_1), 'std':np.std(es_2 - es_1)}
classical, _ = classical_solver(hamiltonian)
energies_Classical.append(classical[2]- classical[1])
return solution_VQD, np.array(energies_Classical), V
min_V = -0.
max_V = -2.
points = 5
epsilons = [3,3]
n_trials = 50
solution_VQD, energy_classical, V = hamiltonian_varying_V(min_V, max_V, points, epsilons, n_trials)
solution_VQD
import seaborn as sns
sns.set()
mean = []
std = []
for _, sol in solution_VQD.items():
mean.append(sol['mean'])
std.append(sol['std'])
plt.errorbar(V,
np.array(mean)/2,
yerr=np.array(std)/2,
fmt='ro', ecolor='green',
label='VQD')
plt.plot(V, energy_classical/2, 'b-', label="Exact")
plt.xlabel('V')
plt.ylabel('Gap')
plt.legend()
plt.savefig('Var_V.png')
plt.show()
V
spsa_dict = {-0.0: {'mean': 2.2544600000000004, 'std': 3.6059371187529052},
-0.5: {'mean': 2.201132, 'std': 3.5924339523749076},
-1.0: {'mean': 2.3685160000000005, 'std': 3.2362400972956262},
-1.5: {'mean': 2.262069, 'std': 3.6215824729514305},
-2.0: {'mean': 2.151896, 'std': 3.285247713884601}}
cobyla_dict = {-0.0: {'mean': 0.2738039999999999, 'std': 0.5017597014348602},
-0.5: {'mean': 1.1608589999999999, 'std': 0.7228235554884747},
-1.0: {'mean': 2.0350799999999993, 'std': 0.8327042377699295},
-1.5: {'mean': 3.137112, 'std': 0.6724548732487554},
-2.0: {'mean': 4.314758, 'std': 0.5284894406097439}}
mean_spsa = []
std_spsa = []
mean_cobyla = []
std_cobyla = []
x_axis = np.array([-0. , -0.5, -1. , -1.5, -2. ])
for sol in x_axis:
mean_spsa.append(spsa_dict[sol]['mean'])
std_spsa.append(spsa_dict[sol]['std'])
mean_cobyla.append(cobyla_dict[sol]['mean'])
std_cobyla.append(cobyla_dict[sol]['std'])
from matplotlib.ticker import MaxNLocator
x_axis = np.array([-0. , -0.5, -1. , -1.5, -2. ])
energy_classical = np.array([0., 1., 2., 3., 4.])
plt.errorbar(x_axis,
np.array(mean_spsa)/2,
yerr=np.array(std_spsa)/2,
fmt='o', color='black',
ecolor='gray', elinewidth=2,
label='SPSA')
plt.errorbar(x_axis,
np.array(mean_cobyla)/2,
yerr=np.array(std_cobyla)/2,
fmt='o', color='red',
ecolor='green', elinewidth=2,
label='COBYLA')
plt.plot(V, energy_classical/2, 'b-', label="Exact")
plt.xlabel('V')
plt.ylabel('Gap')
plt.legend()
plt.savefig('Var_V_optimizers.png')
plt.show()
|
https://github.com/theflyingrahul/qiskitsummerschool2020
|
theflyingrahul
|
# -*- 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/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit_optimization import QuadraticProgram
qp = QuadraticProgram()
qp.binary_var("x")
qp.binary_var("y")
qp.integer_var(lowerbound=0, upperbound=7, name="z")
qp.maximize(linear={"x": 2, "y": 1, "z": 1})
qp.linear_constraint(linear={"x": 1, "y": 1, "z": 1}, sense="LE", rhs=5.5, name="xyz_leq")
qp.linear_constraint(linear={"x": 1, "y": 1, "z": 1}, sense="GE", rhs=2.5, name="xyz_geq")
print(qp.prettyprint())
from qiskit_optimization.converters import InequalityToEquality
ineq2eq = InequalityToEquality()
qp_eq = ineq2eq.convert(qp)
print(qp_eq.prettyprint())
print(qp_eq.prettyprint())
from qiskit_optimization.converters import IntegerToBinary
int2bin = IntegerToBinary()
qp_eq_bin = int2bin.convert(qp_eq)
print(qp_eq_bin.prettyprint())
print(qp_eq_bin.prettyprint())
from qiskit_optimization.converters import LinearEqualityToPenalty
lineq2penalty = LinearEqualityToPenalty()
qubo = lineq2penalty.convert(qp_eq_bin)
print(qubo.prettyprint())
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
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 = 100
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.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.231052657869664, -7.078319612689266, -7.215401871826676, -7.230221135636873, -7.262455020005291, -7.267031049860837, -7.501572363017872, -7.4813356803216, -7.4947234955867215, -7.467291869278843], 'approximated_eneriges_1': [-7.563886100199448, -7.658659320088765, -7.578874516640113, -7.5780818494863516, -7.560965458088562, -7.637089945397857, -7.663568893024004, -7.5617725937859115, -7.705323888763656, -7.702392677865555], 'approximated_eneriges_2': [-7.579265030661066, -7.5773451380441585, -7.599916344085796, -7.618297129617218, -7.60986111046384, -7.491511476610149, -7.270122634763994, -7.295684673991992, -7.268791877445621, -7.325654461172013], 'approximated_eneriges_3': [-7.592367719916387, -7.681333606694948, -7.696180773666084, -7.713150310751485, -7.710985775433959, -7.709751408629662, -7.676158468825629, -7.621108302975905, -7.706198964984833, -7.67241616951112]}
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.527374926796388, -7.490948460217839, -7.471351892950928, -7.490702422799052, -7.515817970419744, -7.31595982882803, -7.099053535351137, -7.366127033312333, -7.558208686809385, -7.245080154006243], 'approximated_eneriges_1': [-7.435160167575143, -7.3454563436422955, -7.467036090723377, -7.46674892502807, -7.512177681355114, -7.551799781215262, -7.56977798445727, -7.337817913611366, -7.542405722352239, -7.604048469384494], 'approximated_eneriges_2': [-7.45094378726649, -7.494835406044515, -7.546427492721137, -7.5519911271001785, -7.621700741850081, -7.480593237888603, -7.63756007071119, -7.485733803067446, -7.551661441110606, -7.532503440725798], 'approximated_eneriges_3': [-7.420383731278358, -7.269163097081034, -7.378626010242662, -7.344163256333969, -7.384431167351, -7.606108205702219, -7.7098709634708, -7.590454974935595, -7.404154849273452, -7.621812392089753]}
plot_convergence_of_optimization_process(TI_approximated_energies, transverse_ising_4_qubits, )
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
# You can choose different colors for the real and imaginary parts of the density matrix.
from qiskit import QuantumCircuit
from qiskit.quantum_info import DensityMatrix
from qiskit.visualization import plot_state_city
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
state = DensityMatrix(qc)
plot_state_city(state, color=['midnightblue', 'crimson'], title="New State City")
|
https://github.com/mistryiam/IBM-Qiskit-Machine-Learning
|
mistryiam
|
import numpy as np
# Importing standard Qiskit libraries
from qiskit import QuantumCircuit, transpile, assemble, Aer, IBMQ, execute
from qiskit.quantum_info import Statevector
from qiskit.visualization import plot_bloch_multivector, plot_histogram
from qiskit_textbook.problems import dj_problem_oracle
def lab1_ex1():
qc = QuantumCircuit(1)
#
#
# FILL YOUR CODE IN HERE
#
#
qc.x(0)
return qc
state = Statevector.from_instruction(lab1_ex1())
plot_bloch_multivector(state)
from qc_grader import grade_lab1_ex1
# Note that the grading function is expecting a quantum circuit without measurements
grade_lab1_ex1(lab1_ex1())
def lab1_ex2():
qc = QuantumCircuit(1)
#
#
# FILL YOUR CODE IN HERE
#
#
qc.h(0)
return qc
state = Statevector.from_instruction(lab1_ex2())
plot_bloch_multivector(state)
from qc_grader import grade_lab1_ex2
# Note that the grading function is expecting a quantum circuit without measurements
grade_lab1_ex2(lab1_ex2())
def lab1_ex3():
qc = QuantumCircuit(1)
#
#
# FILL YOUR CODE IN HERE
#
#
qc.x(0)
qc.h(0)
return qc
state = Statevector.from_instruction(lab1_ex3())
plot_bloch_multivector(state)
from qc_grader import grade_lab1_ex3
# Note that the grading function is expecting a quantum circuit without measurements
grade_lab1_ex3(lab1_ex3())
def lab1_ex4():
qc = QuantumCircuit(1)
#
#
# FILL YOUR CODE IN HERE
#
#
qc.h(0)
qc.sdg(0)
return qc
state = Statevector.from_instruction(lab1_ex4())
plot_bloch_multivector(state)
from qc_grader import grade_lab1_ex4
# Note that the grading function is expecting a quantum circuit without measurements
grade_lab1_ex4(lab1_ex4())
def lab1_ex5():
qc = QuantumCircuit(2,2) # this time, we not only want two qubits, but also two classical bits for the measurement
#
#
# FILL YOUR CODE IN HERE
#
#
qc.h(0)
qc.cx(0,1)
qc.x(0)
return qc
qc = lab1_ex5()
qc.draw() # we draw the circuit
from qc_grader import grade_lab1_ex5
# Note that the grading function is expecting a quantum circuit without measurements
grade_lab1_ex5(lab1_ex5())
qc.measure(0, 0) # we perform a measurement on qubit q_0 and store the information on the classical bit c_0
qc.measure(1, 1) # we perform a measurement on qubit q_1 and store the information on the classical bit c_1
backend = Aer.get_backend('qasm_simulator') # we choose the simulator as our backend
counts = execute(qc, backend, shots = 1000).result().get_counts() # we run the simulation and get the counts
plot_histogram(counts) # let us plot a histogram to see the possible outcomes and corresponding probabilities
def lab1_ex6():
#
#
# FILL YOUR CODE IN HERE
#
#
qc = QuantumCircuit(3,3)
qc.h(0)
qc.cx(0,1)
qc.cx(1,2)
qc.y(1)
return qc
qc = lab1_ex6()
qc.draw() # we draw the circuit
from qc_grader import grade_lab1_ex6
# Note that the grading function is expecting a quantum circuit without measurements
grade_lab1_ex6(lab1_ex6())
oraclenr = 4 # determines the oracle (can range from 1 to 5)
oracle = dj_problem_oracle(oraclenr) # gives one out of 5 oracles
oracle.name = "DJ-Oracle"
def dj_classical(n, input_str):
# build a quantum circuit with n qubits and 1 classical readout bit
dj_circuit = QuantumCircuit(n+1,1)
# Prepare the initial state corresponding to your input bit string
for i in range(n):
if input_str[i] == '1':
dj_circuit.x(i)
# append oracle
dj_circuit.append(oracle, range(n+1))
# measure the fourth qubit
dj_circuit.measure(n,0)
return dj_circuit
n = 4 # number of qubits
input_str = '1111'
dj_circuit = dj_classical(n, input_str)
dj_circuit.draw() # draw the circuit
input_str = '1111'
dj_circuit = dj_classical(n, input_str)
qasm_sim = Aer.get_backend('qasm_simulator')
transpiled_dj_circuit = transpile(dj_circuit, qasm_sim)
qobj = assemble(transpiled_dj_circuit, qasm_sim)
results = qasm_sim.run(qobj).result()
answer = results.get_counts()
plot_histogram(answer)
def lab1_ex7():
min_nr_inputs = 2
max_nr_inputs = 9
return [min_nr_inputs, max_nr_inputs]
from qc_grader import grade_lab1_ex7
# Note that the grading function is expecting a list of two integers
grade_lab1_ex7(lab1_ex7())
n=4
def psi_0(n):
qc = QuantumCircuit(n+1,n)
# Build the state (|00000> - |10000>)/sqrt(2)
#
#
# FILL YOUR CODE IN HERE
#
#
qc.x(4)
qc.h(4)
return qc
dj_circuit = psi_0(n)
dj_circuit.draw()
def psi_1(n):
# obtain the |psi_0> = |00001> state
qc = psi_0(n)
# create the superposition state |psi_1>
#
#
qc.h(0)
qc.h(1)
qc.h(2)
qc.h(3)
#
#
qc.barrier()
return qc
dj_circuit = psi_1(n)
dj_circuit.draw()
def psi_2(oracle,n):
# circuit to obtain psi_1
qc = psi_1(n)
# append the oracle
qc.append(oracle, range(n+1))
return qc
dj_circuit = psi_2(oracle, n)
dj_circuit.draw()
def lab1_ex8(oracle, n): # note that this exercise also depends on the code in the functions psi_0 (In [24]) and psi_1 (In [25])
qc = psi_2(oracle, n)
# apply n-fold hadamard gate
#
#
# FILL YOUR CODE IN HERE
#
#
qc.h(0)
qc.h(1)
qc.h(2)
qc.h(3)
# add the measurement by connecting qubits to classical bits
#
#
qc.measure(0,0)
qc.measure(1,1)
qc.measure(2,2)
qc.measure(3,3)
#
#
return qc
dj_circuit = lab1_ex8(oracle, n)
dj_circuit.draw()
from qc_grader import grade_lab1_ex8
# Note that the grading function is expecting a quantum circuit with measurements
grade_lab1_ex8(lab1_ex8(dj_problem_oracle(4),n))
qasm_sim = Aer.get_backend('qasm_simulator')
transpiled_dj_circuit = transpile(dj_circuit, qasm_sim)
qobj = assemble(transpiled_dj_circuit)
results = qasm_sim.run(qobj).result()
answer = results.get_counts()
plot_histogram(answer)
|
https://github.com/BOBO1997/osp_solutions
|
BOBO1997
|
import numpy as np
import matplotlib.pyplot as plt
import itertools
from pprint import pprint
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("../utils/")
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)
scale_factors = [1.0, 2.0, 3.0]
# 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_init110(qc, targets=[0, 1, 2]) # decode
# Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time
qc = qc.bind_parameters({dt: target_time / num_steps})
print("created qc")
# Generate state tomography circuits to evaluate fidelity of simulation
st_qcs = state_tomography_circuits(qc, [0, 1, 2][::-1]) #! state tomography requires === BIG ENDIAN ===
print("created st_qcs (length:", len(st_qcs), ")")
# remove barriers
st_qcs = [RemoveBarriers()(qc) for qc in st_qcs]
print("removed barriers from st_qcs")
# optimize circuit
t3_st_qcs = transpile(st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"])
t3_st_qcs = transpile(t3_st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"])
print("created t3_st_qcs (length:", len(t3_st_qcs), ")")
# zne wrapping
zne_qcs = zne_wrapper(t3_st_qcs, scale_factors = scale_factors, pt = True) # Pauli Twirling
print("created zne_qcs (length:", len(zne_qcs), ")")
# optimization_level must be 0
# feed initial_layout here to see the picture of the circuits before casting the job
t3_zne_qcs = transpile(zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout)
print("created t3_zne_qcs (length:", len(t3_zne_qcs), ")")
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-community', group='ibmquantumawards', project='open-science-22')
# print("provider:", provider)
# backend = provider.get_backend("ibmq_jakarta")
print(str(backend))
shots = 1 << 13
reps = 8 # unused
jobs = []
for _ in range(reps):
#! CHECK: run t3_zne_qcs, with optimization_level = 0 and straightforward initial_layout
job = execute(t3_zne_qcs, backend, shots=shots, optimization_level=0)
print('Job ID', job.job_id())
jobs.append(job)
# QREM
qr = QuantumRegister(num_qubits, name="calq")
meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal')
# we have to feed initial_layout to calibration matrix
cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout = initial_layout)
print('Job ID', cal_job.job_id())
meas_calibs[0].draw("mpl")
dt_now = datetime.datetime.now()
print(dt_now)
filename = "job_ids_" + str(backend) + "_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl"
print(filename)
# with open("jobs_" + str(backend) + "_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(filename, "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_" + str(backend) + "_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f:
# pickle.dump(backend.properties(), f)
retrieved_jobs = jobs
retrieved_cal_job = cal_job
cal_results = retrieved_cal_job.result()
meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal')
target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!!
fids = []
for job in retrieved_jobs:
mit_results = meas_fitter.filter.apply(job.result())
zne_expvals = zne_decoder(num_qubits, mit_results, scale_factors = scale_factors)
rho = expvals_to_valid_rho(num_qubits, zne_expvals)
fid = state_fidelity(rho, target_state)
fids.append(fid)
print('state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(fids), np.std(fids)))
|
https://github.com/urwin419/QiskitChecker
|
urwin419
|
from qiskit import QuantumCircuit
def create_bell_pair():
qc = QuantumCircuit(2)
qc.h(1)
qc.cx(1, 0)
return qc
def encode_message(qc, qubit, msg):
if len(msg) != 2 or not set([0,1]).issubset({0,1}):
raise ValueError(f"message '{msg}' is invalid")
if msg[1] == "1":
qc.x(qubit)
if msg[0] == "1":
### removed z gate ###
pass
return qc
def decode_message(qc):
### removed cx gate ###
qc.h(1)
return qc
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, transpile
from qiskit.visualization import plot_circuit_layout
from qiskit.providers.fake_provider import FakeVigo
backend = FakeVigo()
ghz = QuantumCircuit(3, 3)
ghz.h(0)
ghz.cx(0,range(1,3))
ghz.barrier()
ghz.measure(range(3), range(3))
new_circ_lv3 = transpile(ghz, backend=backend, optimization_level=3)
plot_circuit_layout(new_circ_lv3, backend)
|
https://github.com/mballarin97/mps_qnn
|
mballarin97
|
# This code is part of qcircha.
#
# 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.
"""
Here we generate the data for Fig 7 where ALL the parameters are random
without any data reuploading
"""
import os
import numpy as np
from qcircha.circuit_selector import _select_circ
from qiskit import QuantumCircuit
import qmatchatea as qmt
from qmatchatea.qk_utils import qk_transpilation_params
import qtealeaves.observables as obs
from qtealeaves.emulator import MPS
from tqdm import tqdm
depth = 14
dir_name = f"data/all_random"
num_qubits = 13
num_reps = 1
num_trials = 1
max_bond_dim = 128
if not os.path.isdir(dir_name):
os.makedirs(dir_name)
observables = obs.TNObservables()
observables += obs.TNObsBondEntropy()
observables += obs.TNState2File('mps_state.txt', 'F')
conv_params = qmt.QCConvergenceParameters(int(max_bond_dim), singval_mode="C")
backend = qmt.QCBackend()
trans_params = qk_transpilation_params(linearize=True, tensor_compiler=False)
feature_map = _select_circ(num_qubits, "zzfeaturemap")
ansatz = _select_circ(num_qubits, "twolocal")
num_avg = 1000
for idx, data in tqdm(enumerate(range(num_avg))):
entanglement_total = []
singvals_cut_total = []
states_total = []
initial_state = "Vacuum"
for num_reps in range(depth):
print(f"\n__Reps {num_reps}/{depth}")
random_params = np.pi * np.random.rand(len(ansatz.parameters))
random_params_data = np.pi * np.random.rand(len(feature_map.parameters))
binded_ansatz = ansatz.bind_parameters(random_params)
binded_fmap = feature_map.bind_parameters(random_params_data)
# Pick a PQC (modify the function)
qc = QuantumCircuit(num_qubits)
qc = qc.compose(binded_fmap)
qc = qc.compose(binded_ansatz)
io_info = qmt.QCIO(initial_state=initial_state)
results = qmt.run_simulation(qc, convergence_parameters=conv_params,
transpilation_parameters=trans_params, backend=backend,
observables=observables, io_info=io_info)
entanglement = np.array(list(results.entanglement.values()))
initial_state = results.mps
entanglement_total.append(entanglement)
states_total.append(results.singular_values_cut)
initial_state = MPS.from_tensor_list(initial_state)
np.save( os.path.join(dir_name, f"entanglement_{idx+num_avg}.npy"), entanglement_total, allow_pickle=True)
|
https://github.com/Qiskit/feedback
|
Qiskit
|
import qiskit
qiskit.__version__
from qiskit.circuit.library import XGate
gate = XGate()
print(f"name: {gate.name}\n")
print(f"params: {gate.params}\n")
print(f"matrix:\n{gate.to_matrix()}\n")
print(f"definition:\n{gate.definition}\n")
new_gate = XGate()
print(f"name: {gate.name}\n")
print(f"params: {gate.params}\n")
print(f"matrix:\n{gate.to_matrix()}\n")
print(f"definition:\n{gate.definition}\n")
XGate() is XGate() is XGate() is XGate() is XGate() is XGate() is XGate() is XGate() is XGate() is XGate()
try:
XGate().label = "My Extra Special XGate made with secret sauce"
except NotImplementedError as e:
print(e)
labelled_gate = XGate(label="My Extra Special XGate made with secret sauce")
print(labelled_gate.label)
print(f"Shared object: {labelled_gate is XGate()}")
gate = XGate()
gate.mutable
mutable_gate = gate.to_mutable()
mutable_gate.label = "My Extra Special XGate made with secret sauce"
print(mutable_gate.label)
print(f"Shared object: {mutable_gate is XGate()}")
from qiskit.circuit import Clbit
gate = XGate()
conditional_gate = gate.c_if(Clbit(), 0)
print(conditional_gate.condition)
print(f"Shared object: {conditional_gate is XGate()}")
from qiskit.circuit import QuantumCircuit
qc = QuantumCircuit(1, 1)
qc.x(0).c_if(qc.clbits[0], 1)
print(qc)
print(qc.data[0].operation is XGate())
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
from qiskit.algorithms import AmplificationProblem
# the state we desire to find is '11'
good_state = ['11']
# specify the oracle that marks the state '11' as a good solution
oracle = QuantumCircuit(2)
oracle.cz(0, 1)
# define Grover's algorithm
problem = AmplificationProblem(oracle, is_good_state=good_state)
# now we can have a look at the Grover operator that is used in running the algorithm
# (Algorithm circuits are wrapped in a gate to appear in composition as a block
# so we have to decompose() the op to see it expanded into its component gates.)
problem.grover_operator.decompose().draw(output='mpl')
from qiskit.algorithms import Grover
from qiskit.primitives import Sampler
grover = Grover(sampler=Sampler())
result = grover.amplify(problem)
print('Result type:', type(result))
print()
print('Success!' if result.oracle_evaluation else 'Failure!')
print('Top measurement:', result.top_measurement)
from qiskit.quantum_info import Statevector
oracle = Statevector.from_label('11')
problem = AmplificationProblem(oracle, is_good_state=['11'])
grover = Grover(sampler=Sampler())
result = grover.amplify(problem)
print('Result type:', type(result))
print()
print('Success!' if result.oracle_evaluation else 'Failure!')
print('Top measurement:', result.top_measurement)
problem.grover_operator.oracle.decompose().draw(output='mpl')
from qiskit.circuit.library.phase_oracle import PhaseOracle
from qiskit.exceptions import MissingOptionalLibraryError
# `Oracle` (`PhaseOracle`) as the `oracle` argument
expression = '(a & b)'
try:
oracle = PhaseOracle(expression)
problem = AmplificationProblem(oracle)
display(problem.grover_operator.oracle.decompose().draw(output='mpl'))
except MissingOptionalLibraryError as ex:
print(ex)
import numpy as np
# Specifying `state_preparation`
# to prepare a superposition of |01>, |10>, and |11>
oracle = QuantumCircuit(3)
oracle.ccz(0, 1, 2)
theta = 2 * np.arccos(1 / np.sqrt(3))
state_preparation = QuantumCircuit(3)
state_preparation.ry(theta, 0)
state_preparation.ch(0,1)
state_preparation.x(1)
state_preparation.h(2)
# we only care about the first two bits being in state 1, thus add both possibilities for the last qubit
problem = AmplificationProblem(oracle, state_preparation=state_preparation, is_good_state=['110', '111'])
# state_preparation
print('state preparation circuit:')
problem.grover_operator.state_preparation.draw(output='mpl')
grover = Grover(sampler=Sampler())
result = grover.amplify(problem)
print('Success!' if result.oracle_evaluation else 'Failure!')
print('Top measurement:', result.top_measurement)
oracle = QuantumCircuit(5)
oracle.ccz(0, 1, 2)
oracle.draw(output='mpl')
from qiskit.circuit.library import GroverOperator
grover_op = GroverOperator(oracle, insert_barriers=True)
grover_op.decompose().draw(output='mpl')
grover_op = GroverOperator(oracle, reflection_qubits=[0, 1, 2], insert_barriers=True)
grover_op.decompose().draw(output='mpl')
# a list of binary strings good state
oracle = QuantumCircuit(2)
oracle.cz(0, 1)
good_state = ['11', '00']
problem = AmplificationProblem(oracle, is_good_state=good_state)
print(problem.is_good_state('11'))
# a list of integer good state
oracle = QuantumCircuit(2)
oracle.cz(0, 1)
good_state = [0, 1]
problem = AmplificationProblem(oracle, is_good_state=good_state)
print(problem.is_good_state('11'))
from qiskit.quantum_info import Statevector
# `Statevector` good state
oracle = QuantumCircuit(2)
oracle.cz(0, 1)
good_state = Statevector.from_label('11')
problem = AmplificationProblem(oracle, is_good_state=good_state)
print(problem.is_good_state('11'))
# Callable good state
def callable_good_state(bitstr):
if bitstr == "11":
return True
return False
oracle = QuantumCircuit(2)
oracle.cz(0, 1)
problem = AmplificationProblem(oracle, is_good_state=good_state)
print(problem.is_good_state('11'))
# integer iteration
oracle = QuantumCircuit(2)
oracle.cz(0, 1)
problem = AmplificationProblem(oracle, is_good_state=['11'])
grover = Grover(iterations=1)
# list iteration
oracle = QuantumCircuit(2)
oracle.cz(0, 1)
problem = AmplificationProblem(oracle, is_good_state=['11'])
grover = Grover(iterations=[1, 2, 3])
# using sample_from_iterations
oracle = QuantumCircuit(2)
oracle.cz(0, 1)
problem = AmplificationProblem(oracle, is_good_state=['11'])
grover = Grover(iterations=[1, 2, 3], sample_from_iterations=True)
iterations = Grover.optimal_num_iterations(num_solutions=1, num_qubits=8)
iterations
def to_DIAMACS_CNF_format(bit_rep):
return [index+1 if val==1 else -1 * (index + 1) for index, val in enumerate(bit_rep)]
oracle = QuantumCircuit(2)
oracle.cz(0, 1)
problem = AmplificationProblem(oracle, is_good_state=['11'], post_processing=to_DIAMACS_CNF_format)
problem.post_processing([1, 0, 1])
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/2lambda123/Qiskit-qiskit
|
2lambda123
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2022.
#
# 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 linear reversible circuits synthesis functions."""
import unittest
import numpy as np
from ddt import ddt, data
from qiskit import QuantumCircuit
from qiskit.circuit.library import LinearFunction
from qiskit.synthesis.linear import (
synth_cnot_count_full_pmh,
synth_cnot_depth_line_kms,
random_invertible_binary_matrix,
check_invertible_binary_matrix,
calc_inverse_matrix,
)
from qiskit.synthesis.linear.linear_circuits_utils import transpose_cx_circ, optimize_cx_4_options
from qiskit.test import QiskitTestCase
@ddt
class TestLinearSynth(QiskitTestCase):
"""Test the linear reversible circuit synthesis functions."""
def test_lnn_circuit(self):
"""Test the synthesis of a CX circuit with LNN connectivity."""
n = 5
qc = QuantumCircuit(n)
for i in range(n - 1):
qc.cx(i, i + 1)
mat = LinearFunction(qc).linear
for optimized in [True, False]:
optimized_qc = optimize_cx_4_options(
synth_cnot_count_full_pmh, mat, optimize_count=optimized
)
self.assertEqual(optimized_qc.depth(), 4)
self.assertEqual(optimized_qc.count_ops()["cx"], 4)
def test_full_circuit(self):
"""Test the synthesis of a CX circuit with full connectivity."""
n = 5
qc = QuantumCircuit(n)
for i in range(n):
for j in range(i + 1, n):
qc.cx(i, j)
mat = LinearFunction(qc).linear
for optimized in [True, False]:
optimized_qc = optimize_cx_4_options(
synth_cnot_count_full_pmh, mat, optimize_count=optimized
)
self.assertEqual(optimized_qc.depth(), 4)
self.assertEqual(optimized_qc.count_ops()["cx"], 4)
def test_transpose_circ(self):
"""Test the transpose_cx_circ() function."""
n = 5
mat = random_invertible_binary_matrix(n, seed=1234)
qc = synth_cnot_count_full_pmh(mat)
transposed_qc = transpose_cx_circ(qc)
transposed_mat = LinearFunction(transposed_qc).linear.astype(int)
self.assertTrue((mat.transpose() == transposed_mat).all())
def test_example_circuit(self):
"""Test the synthesis of an example CX circuit which provides different CX count
and depth for different optimization methods."""
qc = QuantumCircuit(9)
qc.swap(8, 7)
qc.swap(7, 6)
qc.cx(5, 6)
qc.cx(6, 5)
qc.swap(4, 5)
qc.cx(3, 4)
qc.cx(4, 3)
qc.swap(2, 3)
qc.cx(1, 2)
qc.cx(2, 1)
qc.cx(0, 1)
qc.cx(1, 0)
mat = LinearFunction(qc).linear
optimized_qc = optimize_cx_4_options(synth_cnot_count_full_pmh, mat, optimize_count=True)
self.assertEqual(optimized_qc.depth(), 17)
self.assertEqual(optimized_qc.count_ops()["cx"], 20)
optimized_qc = optimize_cx_4_options(synth_cnot_count_full_pmh, mat, optimize_count=False)
self.assertEqual(optimized_qc.depth(), 15)
self.assertEqual(optimized_qc.count_ops()["cx"], 23)
@data(5, 6)
def test_invertible_matrix(self, n):
"""Test the functions for generating a random invertible matrix and inverting it."""
mat = random_invertible_binary_matrix(n, seed=1234)
out = check_invertible_binary_matrix(mat)
mat_inv = calc_inverse_matrix(mat, verify=True)
mat_out = np.dot(mat, mat_inv) % 2
self.assertTrue(np.array_equal(mat_out, np.eye(n)))
self.assertTrue(out)
@data(5, 6)
def test_synth_lnn_kms(self, num_qubits):
"""Test that synth_cnot_depth_line_kms produces the correct synthesis."""
rng = np.random.default_rng(1234)
num_trials = 10
for _ in range(num_trials):
mat = random_invertible_binary_matrix(num_qubits, seed=rng)
mat = np.array(mat, dtype=bool)
qc = synth_cnot_depth_line_kms(mat)
mat1 = LinearFunction(qc).linear
self.assertTrue((mat == mat1).all())
# Check that the circuit depth is bounded by 5*num_qubits
depth = qc.depth()
self.assertTrue(depth <= 5 * num_qubits)
# Check that the synthesized circuit qc fits LNN connectivity
for inst in qc.data:
self.assertEqual(inst.operation.name, "cx")
q0 = qc.find_bit(inst.qubits[0]).index
q1 = qc.find_bit(inst.qubits[1]).index
dist = abs(q0 - q1)
self.assertEqual(dist, 1)
if __name__ == "__main__":
unittest.main()
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# 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.
"""An implementation of the AdaptVQE algorithm."""
from __future__ import annotations
from collections.abc import Sequence
from enum import Enum
import re
import logging
from typing import Any
import numpy as np
from qiskit import QiskitError
from qiskit_algorithms.list_or_dict import ListOrDict
from qiskit.quantum_info.operators.base_operator import BaseOperator
from qiskit.opflow import OperatorBase, PauliSumOp
from qiskit.circuit.library import EvolvedOperatorAnsatz
from qiskit.utils.deprecation import deprecate_arg, deprecate_func
from qiskit.utils.validation import validate_min
from .minimum_eigensolver import MinimumEigensolver
from .vqe import VQE, VQEResult
from ..observables_evaluator import estimate_observables
from ..variational_algorithm import VariationalAlgorithm
logger = logging.getLogger(__name__)
class TerminationCriterion(Enum):
"""A class enumerating the various finishing criteria."""
CONVERGED = "Threshold converged"
CYCLICITY = "Aborted due to a cyclic selection of evolution operators"
MAXIMUM = "Maximum number of iterations reached"
class AdaptVQE(VariationalAlgorithm, MinimumEigensolver):
"""The Adaptive Variational Quantum Eigensolver algorithm.
`AdaptVQE <https://arxiv.org/abs/1812.11173>`__ is a quantum algorithm which creates a compact
ansatz from a set of evolution operators. It iteratively extends the ansatz circuit, by
selecting the building block that leads to the largest gradient from a set of candidates. In
chemistry, this is usually a list of orbital excitations. Thus, a common choice of ansatz to be
used with this algorithm is the Unitary Coupled Cluster ansatz implemented in Qiskit Nature.
This results in a wavefunction ansatz which is uniquely adapted to the operator whose minimum
eigenvalue is being determined. This class relies on a supplied instance of :class:`~.VQE` to
find the minimum eigenvalue. The performance of AdaptVQE significantly depends on the
minimization routine.
.. code-block:: python
from qiskit_algorithms.minimum_eigensolvers import AdaptVQE, VQE
from qiskit_algorithms.optimizers import SLSQP
from qiskit.primitives import Estimator
from qiskit.circuit.library import EvolvedOperatorAnsatz
# get your Hamiltonian
hamiltonian = ...
# construct your ansatz
ansatz = EvolvedOperatorAnsatz(...)
vqe = VQE(Estimator(), ansatz, SLSQP())
adapt_vqe = AdaptVQE(vqe)
eigenvalue, _ = adapt_vqe.compute_minimum_eigenvalue(hamiltonian)
The following attributes can be set via the initializer but can also be read and updated once
the AdaptVQE object has been constructed.
Attributes:
solver: a :class:`~.VQE` instance used internally to compute the minimum eigenvalues.
It is a requirement that the :attr:`~.VQE.ansatz` of this solver is of type
:class:`~qiskit.circuit.library.EvolvedOperatorAnsatz`.
gradient_threshold: once all gradients have an absolute value smaller than this threshold,
the algorithm has converged and terminates.
eigenvalue_threshold: once the eigenvalue has changed by less than this threshold from one
iteration to the next, the algorithm has converged and terminates. When this case
occurs, the excitation included in the final iteration did not result in a significant
improvement of the eigenvalue and, thus, the results from this iteration are not
considered.
max_iterations: the maximum number of iterations for the adaptive loop. If ``None``, the
algorithm is not bound in its number of iterations.
"""
@deprecate_arg(
"threshold",
since="0.24.0",
pending=True,
new_alias="gradient_threshold",
)
def __init__(
self,
solver: VQE,
*,
gradient_threshold: float = 1e-5,
eigenvalue_threshold: float = 1e-5,
max_iterations: int | None = None,
threshold: float | None = None, # pylint: disable=unused-argument
) -> None:
"""
Args:
solver: a :class:`~.VQE` instance used internally to compute the minimum eigenvalues.
It is a requirement that the :attr:`~.VQE.ansatz` of this solver is of type
:class:`~qiskit.circuit.library.EvolvedOperatorAnsatz`.
gradient_threshold: once all gradients have an absolute value smaller than this
threshold, the algorithm has converged and terminates.
eigenvalue_threshold: once the eigenvalue has changed by less than this threshold from
one iteration to the next, the algorithm has converged and terminates. When this
case occurs, the excitation included in the final iteration did not result in a
significant improvement of the eigenvalue and, thus, the results from this iteration
are not considered.
max_iterations: the maximum number of iterations for the adaptive loop. If ``None``, the
algorithm is not bound in its number of iterations.
threshold: once all gradients have an absolute value smaller than this threshold, the
algorithm has converged and terminates. Defaults to ``1e-5``.
"""
validate_min("gradient_threshold", gradient_threshold, 1e-15)
validate_min("eigenvalue_threshold", eigenvalue_threshold, 1e-15)
self.solver = solver
self.gradient_threshold = gradient_threshold
self.eigenvalue_threshold = eigenvalue_threshold
self.max_iterations = max_iterations
self._tmp_ansatz: EvolvedOperatorAnsatz | None = None
self._excitation_pool: list[OperatorBase] = []
self._excitation_list: list[OperatorBase] = []
@property
@deprecate_func(
since="0.24.0",
pending=True,
is_property=True,
additional_msg="Instead, use the gradient_threshold attribute.",
)
def threshold(self) -> float:
"""The threshold for the gradients.
Once all gradients have an absolute value smaller than this threshold, the algorithm has
converged and terminates.
"""
return self.gradient_threshold
@threshold.setter
@deprecate_func(
since="0.24.0",
pending=True,
is_property=True,
additional_msg="Instead, use the gradient_threshold attribute.",
)
def threshold(self, threshold: float) -> None:
self.gradient_threshold = threshold
@property
def initial_point(self) -> Sequence[float] | None:
"""Returns the initial point of the internal :class:`~.VQE` solver."""
return self.solver.initial_point
@initial_point.setter
def initial_point(self, value: Sequence[float] | None) -> None:
"""Sets the initial point of the internal :class:`~.VQE` solver."""
self.solver.initial_point = value
@classmethod
def supports_aux_operators(cls) -> bool:
return True
def _compute_gradients(
self,
theta: list[float],
operator: BaseOperator | OperatorBase,
) -> list[tuple[complex, dict[str, Any]]]:
"""
Computes the gradients for all available excitation operators.
Args:
theta: List of (up to now) optimal parameters.
operator: operator whose gradient needs to be computed.
Returns:
List of pairs consisting of the computed gradient and excitation operator.
"""
# The excitations operators are applied later as exp(i*theta*excitation).
# For this commutator, we need to explicitly pull in the imaginary phase.
commutators = [1j * (operator @ exc - exc @ operator) for exc in self._excitation_pool]
res = estimate_observables(self.solver.estimator, self.solver.ansatz, commutators, theta)
return res
@staticmethod
def _check_cyclicity(indices: list[int]) -> bool:
"""
Auxiliary function to check for cycles in the indices of the selected excitations.
Args:
indices: The list of chosen gradient indices.
Returns:
Whether repeating sequences of indices have been detected.
"""
cycle_regex = re.compile(r"(\b.+ .+\b)( \b\1\b)+")
# reg-ex explanation:
# 1. (\b.+ .+\b) will match at least two numbers and try to match as many as possible. The
# word boundaries in the beginning and end ensure that now numbers are split into digits.
# 2. the match of this part is placed into capture group 1
# 3. ( \b\1\b)+ will match a space followed by the contents of capture group 1 (again
# delimited by word boundaries to avoid separation into digits).
# -> this results in any sequence of at least two numbers being detected
match = cycle_regex.search(" ".join(map(str, indices)))
logger.debug("Cycle detected: %s", match)
# Additionally we also need to check whether the last two numbers are identical, because the
# reg-ex above will only find cycles of at least two consecutive numbers.
# It is sufficient to assert that the last two numbers are different due to the iterative
# nature of the algorithm.
return match is not None or (len(indices) > 1 and indices[-2] == indices[-1])
def compute_minimum_eigenvalue(
self,
operator: BaseOperator | PauliSumOp,
aux_operators: ListOrDict[BaseOperator | PauliSumOp] | None = None,
) -> AdaptVQEResult:
"""Computes the minimum eigenvalue.
Args:
operator: Operator whose minimum eigenvalue we want to find.
aux_operators: Additional auxiliary operators to evaluate.
Raises:
TypeError: If an ansatz other than :class:`~.EvolvedOperatorAnsatz` is provided.
QiskitError: If all evaluated gradients lie below the convergence threshold in the first
iteration of the algorithm.
Returns:
An :class:`~.AdaptVQEResult` which is a :class:`~.VQEResult` but also but also
includes runtime information about the AdaptVQE algorithm like the number of iterations,
termination criterion, and the final maximum gradient.
"""
if not isinstance(self.solver.ansatz, EvolvedOperatorAnsatz):
raise TypeError("The AdaptVQE ansatz must be of the EvolvedOperatorAnsatz type.")
# Overwrite the solver's ansatz with the initial state
self._tmp_ansatz = self.solver.ansatz
self._excitation_pool = self._tmp_ansatz.operators
self.solver.ansatz = self._tmp_ansatz.initial_state
prev_op_indices: list[int] = []
prev_raw_vqe_result: VQEResult | None = None
raw_vqe_result: VQEResult | None = None
theta: list[float] = []
max_grad: tuple[complex, dict[str, Any] | None] = (0.0, None)
self._excitation_list = []
history: list[complex] = []
iteration = 0
while self.max_iterations is None or iteration < self.max_iterations:
iteration += 1
logger.info("--- Iteration #%s ---", str(iteration))
# compute gradients
logger.debug("Computing gradients")
cur_grads = self._compute_gradients(theta, operator)
# pick maximum gradient
max_grad_index, max_grad = max(
enumerate(cur_grads), key=lambda item: np.abs(item[1][0])
)
logger.info(
"Found maximum gradient %s at index %s",
str(np.abs(max_grad[0])),
str(max_grad_index),
)
# log gradients
if np.abs(max_grad[0]) < self.gradient_threshold:
if iteration == 1:
raise QiskitError(
"All gradients have been evaluated to lie below the convergence threshold "
"during the first iteration of the algorithm. Try to either tighten the "
"convergence threshold or pick a different ansatz."
)
logger.info(
"AdaptVQE terminated successfully with a final maximum gradient: %s",
str(np.abs(max_grad[0])),
)
termination_criterion = TerminationCriterion.CONVERGED
break
# store maximum gradient's index for cycle detection
prev_op_indices.append(max_grad_index)
# check indices of picked gradients for cycles
if self._check_cyclicity(prev_op_indices):
logger.info("Alternating sequence found. Finishing.")
logger.info("Final maximum gradient: %s", str(np.abs(max_grad[0])))
termination_criterion = TerminationCriterion.CYCLICITY
break
# add new excitation to self._ansatz
logger.info(
"Adding new operator to the ansatz: %s", str(self._excitation_pool[max_grad_index])
)
self._excitation_list.append(self._excitation_pool[max_grad_index])
theta.append(0.0)
# setting up the ansatz for the VQE iteration
self._tmp_ansatz.operators = self._excitation_list
self.solver.ansatz = self._tmp_ansatz
self.solver.initial_point = theta
# evaluating the eigenvalue with the internal VQE
prev_raw_vqe_result = raw_vqe_result
raw_vqe_result = self.solver.compute_minimum_eigenvalue(operator)
theta = raw_vqe_result.optimal_point.tolist()
# checking convergence based on the change in eigenvalue
if iteration > 1:
eigenvalue_diff = np.abs(raw_vqe_result.eigenvalue - history[-1])
if eigenvalue_diff < self.eigenvalue_threshold:
logger.info(
"AdaptVQE terminated successfully with a final change in eigenvalue: %s",
str(eigenvalue_diff),
)
termination_criterion = TerminationCriterion.CONVERGED
logger.debug(
"Reverting the addition of the last excitation to the ansatz since it "
"resulted in a change of the eigenvalue below the configured threshold."
)
self._excitation_list.pop()
theta.pop()
self._tmp_ansatz.operators = self._excitation_list
self.solver.ansatz = self._tmp_ansatz
self.solver.initial_point = theta
raw_vqe_result = prev_raw_vqe_result
break
# appending the computed eigenvalue to the tracking history
history.append(raw_vqe_result.eigenvalue)
logger.info("Current eigenvalue: %s", str(raw_vqe_result.eigenvalue))
else:
# reached maximum number of iterations
termination_criterion = TerminationCriterion.MAXIMUM
logger.info("Maximum number of iterations reached. Finishing.")
logger.info("Final maximum gradient: %s", str(np.abs(max_grad[0])))
result = AdaptVQEResult()
result.combine(raw_vqe_result)
result.num_iterations = iteration
result.final_max_gradient = max_grad[0]
result.termination_criterion = termination_criterion
result.eigenvalue_history = history
# once finished evaluate auxiliary operators if any
if aux_operators is not None:
aux_values = estimate_observables(
self.solver.estimator, self.solver.ansatz, aux_operators, result.optimal_point
)
result.aux_operators_evaluated = aux_values
logger.info("The final eigenvalue is: %s", str(result.eigenvalue))
self.solver.ansatz.operators = self._excitation_pool
return result
class AdaptVQEResult(VQEResult):
"""AdaptVQE Result."""
def __init__(self) -> None:
super().__init__()
self._num_iterations: int | None = None
self._final_max_gradient: float | None = None
self._termination_criterion: str = ""
self._eigenvalue_history: list[float] | None = None
@property
def num_iterations(self) -> int:
"""Returns the number of iterations."""
return self._num_iterations
@num_iterations.setter
def num_iterations(self, value: int) -> None:
"""Sets the number of iterations."""
self._num_iterations = value
@property
def final_max_gradient(self) -> float:
"""Returns the final maximum gradient."""
return self._final_max_gradient
@final_max_gradient.setter
def final_max_gradient(self, value: float) -> None:
"""Sets the final maximum gradient."""
self._final_max_gradient = value
@property
def termination_criterion(self) -> str:
"""Returns the termination criterion."""
return self._termination_criterion
@termination_criterion.setter
def termination_criterion(self, value: str) -> None:
"""Sets the termination criterion."""
self._termination_criterion = value
@property
def eigenvalue_history(self) -> list[float]:
"""Returns the history of computed eigenvalues.
The history's length matches the number of iterations and includes the final computed value.
"""
return self._eigenvalue_history
@eigenvalue_history.setter
def eigenvalue_history(self, eigenvalue_history: list[float]) -> None:
"""Sets the history of computed eigenvalues."""
self._eigenvalue_history = eigenvalue_history
|
https://github.com/NesyaLab/qaoa
|
NesyaLab
|
import os
os.chdir("..")
from classes import Qaoa as Q
from classes import Problems as P
from functions import qaoa_utilities as qaoa_utils
from functions import maxcut_utilities as mcut_utils
from functions import qaoa_optimizers as optims
import numpy as np
import pickle
import sys
from config import *
# Graphs
graphs = []
for i in range(num_graphs):
sys.path.append("classes/")
path = "data/graph_"+str(i)+".nx"
with open(path, 'rb') as f:
g = pickle.load(f)
graphs.append(g)
# Select a graph
G = graphs[idx]
G.get_draw()
# Generate initial random angles
betas = qaoa_utils.generate_parameters(n=p, k=1, seed=seed)
gammas = qaoa_utils.generate_parameters(n=p, k=2, seed=seed)
# Instantiate QAOA
qaoa = Q.Qaoa(p=p, G=G, betas=betas, gammas=gammas, mixer=mixer, seed=seed, verbose=verbose)
qaoa.get_circuit().draw()
# QAOA execution (simple optimization)
_, f = optims.simple_optimization(qaoa, method=method, seed=seed, shots=shots, verbose=verbose)
_,f
|
https://github.com/COFAlumni-USB/qiskit-fall-2022
|
COFAlumni-USB
|
#For Python and advanced manipulation import these packages
try:
import numpy as np
except:
!pip install numpy
import numpy as np
try:
import qiskit
except:
!pip install qiskit
import qiskit
try:
!pip install pylatexenc
estilo = 'mpl'
QuantumCircuit(1).draw(estilo)
except:
estilo = 'text'
#Libraries for quantum circuits
from qiskit import QuantumCircuit, execute
#For calibration
from qiskit import pulse, transpile
from qiskit.pulse.library import Gaussian
#Personalized gates
from qiskit.circuit import Gate
from qiskit import QiskitError
#For information
import qiskit.tools.jupyter
from qiskit import IBMQ
#Load our IBM Quantum account
provider = IBMQ.enable_account("c8440457d4ccb10786816758f1ffd909ea528ea12c2ac744598dd73ec90d1476ffa9f58251d0db77b256bcb655f85be37e3163e5548178ed618bc2ec2c57fbf4")
provider.backends()
from qiskit.providers.ibmq import least_busy
#This searches for the least busy backend, with 5 qubits
small_devices = provider.backends(filters=lambda x: x.configuration().n_qubits == 5
and not x.configuration().simulator)
least_busy(small_devices)
#Once we saw which backend was lest busy, we choose it with .get_backend()
provider = IBMQ.get_provider(hub='ibm-q', group='open', project='main')
backend = provider.get_backend('ibmq_quito')
backend_config = backend.configuration()
#Sampling time of the pulses
dt = backend_config.dt
print(f"Sampling time: {dt*1e9} ns")
#Timing constraint of the backend
backend.configuration().timing_constraints
#We get those values and save it in a variable
acquire_alignment = backend.configuration().timing_constraints['acquire_alignment']
granularity = backend.configuration().timing_constraints['granularity']
pulse_alignment = backend.configuration().timing_constraints['pulse_alignment']
lcm = np.lcm(acquire_alignment, pulse_alignment)
print(f"Least common multiple of acquire_alignment and pulse_alignment: {lcm}")
backend_defaults = backend.defaults()
#Finding qubit's frequency
#Defining units
GHz = 1.0e9 # Gigahertz
MHz = 1.0e6 # Megahertz
us = 1.0e-6 # Microseconds
ns = 1.0e-9 # Nanoseconds
#We will work with the following qubit
qubit = 0
#Center the sweep in a qubit estimated frequency
center_frequency_Hz = backend_defaults.qubit_freq_est[qubit] # in Hz
print(f"Qubit {qubit} has an estimated frequency of {center_frequency_Hz / GHz} GHz.")
# scale factor to remove factors of 10 from the data ???
scale_factor = 1e-7
#Sweep 40 MHz around the estimated frequency
frequency_span_Hz = 40 * MHz
#With 1MHz steps
frequency_step_Hz = 1 * MHz
#Sweep 20 MHz above and 20 MHz below the estimated frequency
frequency_min = center_frequency_Hz - frequency_span_Hz / 2
frequency_max = center_frequency_Hz + frequency_span_Hz / 2
#Array of the frequencies
frequencies_GHz = np.arange(frequency_min / GHz,
frequency_max / GHz,
frequency_step_Hz / GHz)
print(f"The sweep will go from {frequency_min / GHz} GHz to {frequency_max / GHz} GHz \
in steps of {frequency_step_Hz / MHz} MHz.")
#This function returns the closest multiple between two values
def get_closest_multiple_of(value, base_number):
return int(value + base_number/2) - (int(value + base_number/2) % base_number)
#Lenght of the pulse: it has to be multiple of 16 (granularity)
def get_closest_multiple_of_16(num):
return get_closest_multiple_of(num, granularity)
#Lenght of the delay, converts s to dt
def get_dt_from(sec):
return get_closest_multiple_of(sec/dt, lcm)
from qiskit.circuit import Parameter
from qiskit.circuit import QuantumCircuit, Gate
#Drive pulse parameters (us = microseconds)
#Determines width of the Gaussian
drive_sigma_sec = 0.015 * us
#Truncating parameter
drive_duration_sec = drive_sigma_sec * 8
#Pulse's amplitude
drive_amp = 0.05
#Base schedule
freq = Parameter('freq')
with pulse.build(backend=backend, default_alignment='sequential', name='Frequency sweep') as sweep_sched:
#seconds_to_samples(s) gets the number of samples that will elapse in seconds on the active backend.
drive_duration = get_closest_multiple_of_16(pulse.seconds_to_samples(drive_duration_sec))
drive_sigma = pulse.seconds_to_samples(drive_sigma_sec)
#Returns the qubit's DriveChannel on the active backend
#Drive channels transmit signals to qubits which enact gate operations
drive_chan = pulse.drive_channel(qubit)
pulse.set_frequency(freq, drive_chan)
#Drive pulse samples
pulse.play(pulse.Gaussian(duration=drive_duration,
sigma=drive_sigma,
amp=drive_amp,
name='freq_sweep_excitation_pulse'), drive_chan)
#Plot Gaussian pulse
sweep_sched.draw()
#Gate(name, num_qubits, params) creates a new gate
sweep_gate = Gate("sweep", 1, [freq])
#Create the quantum circuit, 1 qubit, 1 bit
qc_sweep = QuantumCircuit(1, 1)
#Add our new gate sweep_gate to the quantum circuit
qc_sweep.append(sweep_gate, [0])
qc_sweep.measure(0, 0)
"""This command: add_calibration(gate, qubits, schedule, params=None)
registers a low-level, custom pulse definition for the given gate"""
qc_sweep.add_calibration(sweep_gate, (0,), sweep_sched, [freq])
#Frequency settings for the sweep (MUST BE IN HZ)
frequencies_Hz = frequencies_GHz*GHz #convert to Hz
"""This command: assign_parameters(parameters, inplace=False)
assigns parameters to new parameters or values"""
exp_sweep_circs = [qc_sweep.assign_parameters({freq: f}, inplace=False) for f in frequencies_Hz]
from qiskit import schedule
#schedule(circuits, backend) to schedule a circuit to a pulse Schedule, using the backend
sweep_schedule = schedule(exp_sweep_circs[0], backend)
#To show the schedule
sweep_schedule.draw(backend=backend)
#Each schedule will be repeated num_shots_per_frequency times
num_shots_per_frequency = 1024
job = backend.run(exp_sweep_circs,
meas_level=1, #kerneled data
meas_return='avg',
shots=num_shots_per_frequency)
from qiskit.tools.monitor import job_monitor
#Monitor the job status
job_monitor(job)
#Retrieve the results
frequency_sweep_results = job.result(timeout=1200)
#Plotting the results with matplotlib
import matplotlib.pyplot as plt
sweep_values = []
for i in range(len(frequency_sweep_results.results)):
#Get the results from the ith experiment
res = frequency_sweep_results.get_memory(i)*scale_factor
#Get the results for `qubit` from this experiment
sweep_values.append(res[qubit])
#Plot frequencies vs. real part of sweep values
plt.scatter(frequencies_GHz, np.real(sweep_values), color='black')
plt.xlim([min(frequencies_GHz), max(frequencies_GHz)])
plt.xlabel("Frequency [GHz]")
plt.ylabel("Measured signal [a.u.]")
plt.show()
#Using scipy for the curve fitting
from scipy.optimize import curve_fit
def fit_function(x_values, y_values, function, init_params):
fitparams, conv = curve_fit(function, x_values, y_values, init_params)
y_fit = function(x_values, *fitparams)
return fitparams, y_fit
#Fitting the curve. We use a Lorentzian function for the fit
"""We need to assign the correct initial parameters for our data
A is related to the height of the curve,
B is related to the width of the Lorentzian,
C is the cut with the Y axis and
q_freq is the estimated peak frequency of the curve."""
fit_params, y_fit = fit_function(frequencies_GHz,
np.real(sweep_values),
lambda x, A, q_freq, B, C: (A / np.pi) * (B / ((x - q_freq)**2 + B**2)) + C,
[1e8, 5.3, 0.02, -1e8] # initial parameters for curve_fit
)
#Plotting the data
plt.scatter(frequencies_GHz, np.real(sweep_values), color='black')
#and plotting the fit
plt.plot(frequencies_GHz, y_fit, color='red')
plt.xlim([min(frequencies_GHz), max(frequencies_GHz)])
plt.xlabel("Frequency [GHz]")
plt.ylabel("Measured Signal [a.u.]")
plt.show()
A, rough_qubit_frequency, B, C = fit_params
rough_qubit_frequency = rough_qubit_frequency*GHz # make sure qubit freq is in Hz
print(f"We've updated our qubit frequency estimate from "
f"{round(backend_defaults.qubit_freq_est[qubit] / GHz, 5)} GHz to {round(rough_qubit_frequency/GHz, 5)} GHz.")
#Calibrating using a pi pulse
#Pi pulses takes a qubit from |0> to |1> (X gate)
# Rabi experiment parameters
num_rabi_points = 50
#Drive amplitude values to iterate over
#50 amplitudes evenly spaced from 0 to 0.75 using linspace
drive_amp_min = 0
drive_amp_max = 0.55 #Changed this parameter
drive_amps = np.linspace(drive_amp_min, drive_amp_max, num_rabi_points)
#Build the Rabi experiments:
"""A drive pulse at the qubit frequency, followed by a measurement,
where we vary the drive amplitude each time"""
#This is similar to the frequency sweep schedule
drive_amp = Parameter('drive_amp')
with pulse.build(backend=backend, default_alignment='sequential', name='Rabi Experiment') as rabi_sched:
drive_duration = get_closest_multiple_of_16(pulse.seconds_to_samples(drive_duration_sec))
drive_sigma = pulse.seconds_to_samples(drive_sigma_sec)
drive_chan = pulse.drive_channel(qubit)
pulse.set_frequency(rough_qubit_frequency, drive_chan)
pulse.play(pulse.Gaussian(duration=drive_duration,
amp=drive_amp,
sigma=drive_sigma,
name='Rabi Pulse'), drive_chan)
#New rabi gate
rabi_gate = Gate("rabi", 1, [drive_amp])
#New quantum circuit for Rabi Experiment
qc_rabi = QuantumCircuit(1, 1)
#Add the rabi_gate we just defined
qc_rabi.append(rabi_gate, [0])
#Measure the QC
qc_rabi.measure(0, 0)
#Add calibration to the rabi_gate
qc_rabi.add_calibration(rabi_gate, (0,), rabi_sched, [drive_amp])
exp_rabi_circs = [qc_rabi.assign_parameters({drive_amp: a}, inplace=False) for a in drive_amps]
#Create our schedule and draw it
rabi_schedule = schedule(exp_rabi_circs[-1], backend)
rabi_schedule.draw(backend=backend)
num_shots_per_point = 1024
job = backend.run(exp_rabi_circs,
meas_level=1,
meas_return='avg',
shots=num_shots_per_point)
job_monitor(job)
#Get the results
rabi_results = job.result(timeout=120)
#We need to extract the results and fit them to a sinusoidal curve.
"""The range of amplitudes we got will rotate (hopefully) the qubit several times
around the Bloch sphere. We need to find the drive amplitude needed for the
signal to oscillate from a maximum to a minimum (all |0> to all |1>).
That's exactly what gives us the calibrated amplitude represented
by the pi pulse"""
#First we center the data around 0
def baseline_remove(values):
return np.array(values) - np.mean(values)
#Empty array for Rabi values
rabi_values = []
#Remember we defined num_rabi_points initially at 50
for i in range(num_rabi_points):
#Get the results for `qubit` from the ith experiment
rabi_values.append(rabi_results.get_memory(i)[qubit] * scale_factor)
#We get the real values from the centered rabi_values
rabi_values = np.real(baseline_remove(rabi_values))
#Plot the results
plt.xlabel("Drive amp [a.u.]")
plt.ylabel("Measured signal [a.u.]")
#Plotting amplitudes vs Rabi values
plt.scatter(drive_amps, rabi_values, color='black')
plt.show()
#Now we fit the curve, similarly to the frequencies fit
fit_params, y_fit = fit_function(drive_amps,
rabi_values,
lambda x, A, B, drive_period, phi: (A*np.cos(2*np.pi*x/drive_period - phi) + B),
[7e7, 0, 0.20, 0])
plt.scatter(drive_amps, rabi_values, color='black')
plt.plot(drive_amps, y_fit, color='red')
drive_period = fit_params[2] #get period of rabi oscillation
plt.xlabel("Drive amp [a.u.]", fontsize=15)
plt.ylabel("Measured signal [a.u.]", fontsize=15)
plt.show()
#Pi pulse's amplitude needed for the signal to oscillate from maximum to minimum
pi_amp = abs(drive_period / 2)
print(f"Pi Amplitude = {pi_amp}")
#We can define our pi pulse now
with pulse.build(backend) as pi_pulse:
drive_duration = get_closest_multiple_of_16(pulse.seconds_to_samples(drive_duration_sec))
drive_sigma = pulse.seconds_to_samples(drive_sigma_sec)
drive_chan = pulse.drive_channel(qubit)
pulse.play(pulse.Gaussian(duration=drive_duration,
amp=pi_amp,
sigma=drive_sigma,
name='pi_pulse'), drive_chan)
#Now we create a ground state to try our pi pulse
qc_gnd = QuantumCircuit(1, 1)
qc_gnd.measure(0, 0)
#And its ground schedule
gnd_schedule = schedule(qc_gnd, backend)
gnd_schedule.draw(backend=backend)
#We create the excited state
with pulse.build(backend=backend, default_alignment='sequential', name='excited state') as exc_schedule:
drive_chan = pulse.drive_channel(qubit)
pulse.set_frequency(rough_qubit_frequency, drive_chan)
pulse.call(pi_pulse)
#And another QC for the excited state
qc_exc = QuantumCircuit(1, 1)
#Apply X gate to qubit 0
qc_exc.x(0)
#And measure it
qc_exc.measure(0, 0)
#Then we add the calibration from the excited state's sched
qc_exc.add_calibration("x", (0,), exc_schedule, [])
#Now execute the exc state's schedule
exec_schedule = schedule(qc_exc, backend)
exec_schedule.draw(backend=backend)
#Preparation schedules for the ground and excited states
num_shots = 1024
job = backend.run([qc_gnd, qc_exc],
#Choosing meas_level 1 for kerneled data
meas_level=1,
meas_return='single',
shots=num_shots)
job_monitor(job)
gnd_exc_results = job.result(timeout=120)
#Getting the ground and excited state's results
gnd_results = gnd_exc_results.get_memory(0)[:, qubit]*scale_factor
exc_results = gnd_exc_results.get_memory(1)[:, qubit]*scale_factor
#Plotting results
plt.figure()
#Ground state in blue
plt.scatter(np.real(gnd_results), np.imag(gnd_results),
s=5, cmap='viridis', c='blue', alpha=0.5, label='Gnd state')
#Excited state in red
plt.scatter(np.real(exc_results), np.imag(exc_results),
s=5, cmap='viridis', c='red', alpha=0.5, label='Exc state')
plt.axis('square')
#Plot a large black dot for the average result of the 0 and 1 states
#Mean of real and imaginary parts of results
mean_gnd = np.mean(gnd_results)
mean_exc = np.mean(exc_results)
plt.scatter(np.real(mean_gnd), np.imag(mean_gnd),
s=100, cmap='viridis', c='black',alpha=1.0, label='Mean')
plt.scatter(np.real(mean_exc), np.imag(mean_exc),
s=100, cmap='viridis', c='black',alpha=1.0)
plt.ylabel('Im [a.u.]', fontsize=15)
plt.xlabel('Q (Real) [a.u.]', fontsize=15)
plt.title("0-1 discrimination", fontsize=15)
plt.legend()
plt.show()
"""Setting up a classifier function:
returns 0 if a given point is closer to the mean of ground state results
and returns 1 if the point is closer to the avg exc state results"""
import math
#This functions classifies the given state as |0> or |1>.
def classify(point: complex):
def distance(a, b):
return math.sqrt((np.real(a) - np.real(b))**2 + (np.imag(a) - np.imag(b))**2)
return int(distance(point, mean_exc) < distance(point, mean_gnd))
#T1 time: time it takes for a qubit to decay from exc_state to gnd_state
"""To measure T1 we use the pi pulse we've calibrated, then a measure pulse.
But first we have to insert a delay."""
#T1 experiment parameters
time_max_sec = 450 * us
time_step_sec = 6.5 * us
delay_times_sec = np.arange(1 * us, time_max_sec, time_step_sec)
#We define the delay
delay = Parameter('delay')
#Create another quantum circuit
qc_t1 = QuantumCircuit(1, 1)
#X Gate
qc_t1.x(0)
#Delay
qc_t1.delay(delay, 0)
#Measurement
qc_t1.measure(0, 0)
#Calibration on X gate with our pi pulse
qc_t1.add_calibration("x", (0,), pi_pulse)
exp_t1_circs = [qc_t1.assign_parameters({delay: get_dt_from(d)}, inplace=False) for d in delay_times_sec]
#Schedule for T1
sched_idx = -1
t1_schedule = schedule(exp_t1_circs[sched_idx], backend)
t1_schedule.draw(backend=backend)
#Execution settings
num_shots = 256
job = backend.run(exp_t1_circs,
meas_level=1,
meas_return='single',
shots=num_shots)
job_monitor(job)
t1_results = job.result(timeout=120)
#Getting the results to plot
t1_values = []
for i in range(len(delay_times_sec)):
iq_data = t1_results.get_memory(i)[:,qubit] * scale_factor
#sum() returns the sum of all items.
#map() returns a map object of the result after applying a given
#function (sum) to each item of a given iterable.
t1_values.append(sum(map(classify, iq_data)) / num_shots)
plt.scatter(delay_times_sec/us, t1_values, color='black')
plt.title("$T_1$ Experiment", fontsize=15)
plt.xlabel('Delay before measurement [$\mu$s]', fontsize=15)
plt.ylabel('Signal [a.u.]', fontsize=15)
plt.show()
#Fitting data with an exponential curve
fit_params, y_fit = fit_function(delay_times_sec/us, t1_values,
lambda x, A, C, T1: (A * np.exp(-x / T1) + C),
[-3, 3, 100]
)
_, _, T1 = fit_params
plt.scatter(delay_times_sec/us, t1_values, color='black')
plt.plot(delay_times_sec/us, y_fit, color='red', label=f"T1 = {T1:.2f} us")
plt.xlim(0, np.max(delay_times_sec/us))
plt.title("$T_1$ Experiment", fontsize=15)
plt.xlabel('Delay before measurement [$\mu$s]', fontsize=15)
plt.ylabel('Signal [a.u.]', fontsize=15)
plt.legend()
plt.show()
#Measure qubit frequency (precisely) with Ramsey Experiment
#Apply a pi/2 pulse, wait some time, and then anothe pi/2 pulse.
#Ramsey experiment parameters
time_max_sec = 1.8 * us
time_step_sec = 0.025 * us
delay_times_sec = np.arange(0.1 * us, time_max_sec, time_step_sec)
#Drive parameters
#Drive amplitude for pi/2 is simply half the amplitude of the pi pulse
drive_amp = pi_amp / 2
#Build the x_90 pulse, which is an X rotation of 90 degrees, a pi/2 rotation
with pulse.build(backend) as x90_pulse:
drive_duration = get_closest_multiple_of_16(pulse.seconds_to_samples(drive_duration_sec))
drive_sigma = pulse.seconds_to_samples(drive_sigma_sec)
drive_chan = pulse.drive_channel(qubit)
pulse.play(pulse.Gaussian(duration=drive_duration,
amp=drive_amp,
sigma=drive_sigma,
name='x90_pulse'), drive_chan)
#Now we have to drive the pulses off-resonance an amount detuning_MHz
detuning_MHz = 2
ramsey_frequency = round(rough_qubit_frequency + detuning_MHz * MHz, 6) #Ramsey freq in Hz
#Pulse for Ramsey experiment
delay = Parameter('delay')
with pulse.build(backend=backend, default_alignment='sequential', name="Ramsey delay Experiment") as ramsey_schedule:
drive_chan = pulse.drive_channel(qubit)
pulse.set_frequency(ramsey_frequency, drive_chan)
pulse.call(x90_pulse)
pulse.delay(delay, drive_chan)
pulse.call(x90_pulse)
#Ramsey gate
ramsey_gate = Gate("ramsey", 1, [delay])
#Another QC for Ramsey experiment
qc_ramsey = QuantumCircuit(1, 1)
#Adding the gate to the circuit
qc_ramsey.append(ramsey_gate, [0])
qc_ramsey.measure(0, 0)
qc_ramsey.add_calibration(ramsey_gate, (0,), ramsey_schedule, [delay])
exp_ramsey_circs = [qc_ramsey.assign_parameters({delay: get_dt_from(d)}, inplace=False) for d in delay_times_sec]
ramsey_schedule = schedule(exp_ramsey_circs[2], backend)
ramsey_schedule.draw(backend=backend)
#Execution settings for Ramsey experimet
num_shots = 256
job = backend.run(exp_ramsey_circs,
meas_level=1,
meas_return='single',
shots=num_shots)
job_monitor(job)
ramsey_results = job.result(timeout=120)
#Array for the results
ramsey_values = []
for i in range(len(delay_times_sec)):
iq_data = ramsey_results.get_memory(i)[:,qubit] * scale_factor
ramsey_values.append(sum(map(classify, iq_data)) / num_shots)
#Plotting the results
plt.scatter(delay_times_sec/us, np.real(ramsey_values), color='black')
plt.xlim(0, np.max(delay_times_sec/us))
plt.title("Ramsey Experiment", fontsize=15)
plt.xlabel('Delay between X90 pulses [$\mu$s]', fontsize=15)
plt.ylabel('Measured Signal [a.u.]', fontsize=15)
plt.show()
#Fitting data to a sinusoid
fit_params, y_fit = fit_function(delay_times_sec/us, np.real(ramsey_values),
lambda x, A, del_f_MHz, C, B: (
A * np.cos(2*np.pi*del_f_MHz*x - C) + B
),
[5, 2.2, 0, 0.4]
)
# Off-resonance component
_, del_f_MHz, _, _, = fit_params # freq is MHz since times in us
plt.scatter(delay_times_sec/us, np.real(ramsey_values), color='black')
plt.plot(delay_times_sec/us, y_fit, color='red', label=f"df = {del_f_MHz:.2f} MHz")
plt.xlim(0, np.max(delay_times_sec/us))
plt.xlabel('Delay between X90 pulses [$\mu$s]', fontsize=15)
plt.ylabel('Measured Signal [a.u.]', fontsize=15)
plt.title('Ramsey Experiment', fontsize=15)
plt.legend()
plt.show()
precise_qubit_freq = rough_qubit_frequency + (detuning_MHz - del_f_MHz) * MHz # get new freq in Hz
print(f"Our updated qubit frequency is now {round(precise_qubit_freq/GHz, 6)} GHz. "
f"It used to be {round(rough_qubit_frequency / GHz, 6)} GHz")
#Measuring coherence time (T2) with Hahn Echoes experiment
#It's the same as Ramsey's experiment, with a pi pulse between the pi/2
#T2 experiment parameters
tau_max_sec = 200 * us
tau_step_sec = 4 * us
delay_times_sec = np.arange(2 * us, tau_max_sec, tau_step_sec)
#Define the delay and build the pulse for T2
delay = Parameter('delay')
with pulse.build(backend=backend, default_alignment='sequential', name="T2 delay Experiment") as t2_schedule:
drive_chan = pulse.drive_channel(qubit)
pulse.set_frequency(precise_qubit_freq, drive_chan)
pulse.call(x90_pulse)
pulse.delay(delay, drive_chan)
pulse.call(pi_pulse)
pulse.delay(delay, drive_chan)
pulse.call(x90_pulse)
#Define T2 gate
t2_gate = Gate("t2", 1, [delay])
#QC for T2
qc_t2 = QuantumCircuit(1, 1)
#Add T2 gate
qc_t2.append(t2_gate, [0])
qc_t2.measure(0, 0)
#Add calibration with delay
qc_t2.add_calibration(t2_gate, (0,), t2_schedule, [delay])
exp_t2_circs = [qc_t2.assign_parameters({delay: get_dt_from(d)}, inplace=False) for d in delay_times_sec]
#Schedule for T2 and show it
t2_schedule = schedule(exp_t2_circs[-1], backend)
t2_schedule.draw(backend=backend)
#Execution settings
num_shots_per_point = 512
job = backend.run(exp_t2_circs,
meas_level=1, #Kerneled data
meas_return='single',
shots=num_shots_per_point)
job_monitor(job)
#Getting results
t2_results = job.result(timeout=120)
#T2 empty array
t2_values = []
#Retrieving results and adding them classified to the array
for i in range(len(delay_times_sec)):
iq_data = t2_results.get_memory(i)[:,qubit] * scale_factor
t2_values.append(sum(map(classify, iq_data)) / num_shots_per_point)
#Plot ressults for Hanh Echo experiment
plt.scatter(2*delay_times_sec/us, t2_values, color='black')
plt.xlabel('Delay between X90 pulse and $\pi$ pulse [$\mu$s]', fontsize=15)
plt.ylabel('Measured Signal [a.u.]', fontsize=15)
plt.title('Hahn Echo Experiment', fontsize=15)
plt.show()
#Fitting data with an exponential function
fit_params, y_fit = fit_function(2*delay_times_sec/us, t2_values,
lambda x, A, B, T2: (A * np.exp(-x / T2) + B),
[-3, 0, 100])
_, _, T2 = fit_params
#Plotting results and fit curve
plt.scatter(2*delay_times_sec/us, t2_values, color='black')
plt.plot(2*delay_times_sec/us, y_fit, color='red', label=f"T2 = {T2:.2f} us")
plt.xlim(0, np.max(2*delay_times_sec/us))
plt.xlabel('Delay between X90 pulse and $\pi$ pulse [$\mu$s]', fontsize=15)
plt.ylabel('Measured Signal [a.u.]', fontsize=15)
plt.title('Hahn Echo Experiment', fontsize=15)
plt.legend()
plt.show()
#Dynamical decoupling technique
#Used to extract longer coherence times from qubits
#Experiment parameters
tau_sec_min = 1 * us
tau_sec_max = 180 * us
tau_step_sec = 4 * us
taus_sec = np.arange(tau_sec_min, tau_sec_max, tau_step_sec)
num_sequence = 1
print(f"Total time ranges from {2.*num_sequence*taus_sec[0] / us} to {2.*num_sequence*taus_sec[-1] / us} us")
#This schedule is different from the others...
delay = Parameter('delay')
with pulse.build(backend=backend, default_alignment='sequential', name="T2DD delay Experiment") as T2DD_schedule:
drive_chan = pulse.drive_channel(qubit)
pulse.set_frequency(precise_qubit_freq, drive_chan)
pulse.call(x90_pulse)
pulse.delay(delay/2, drive_chan)
for loop_counts in range(num_sequence):
pulse.call(pi_pulse)
pulse.delay(delay, drive_chan)
with pulse.phase_offset(np.pi/2, pulse.drive_channel(qubit)):
pulse.call(pi_pulse)
pulse.delay(delay, drive_chan)
pulse.call(pi_pulse)
pulse.delay(delay, drive_chan)
with pulse.phase_offset(np.pi/2, pulse.drive_channel(qubit)):
pulse.call(pi_pulse)
if loop_counts != num_sequence-1:
pulse.delay(delay, drive_chan)
pulse.delay(delay/2, drive_chan)
pulse.call(x90_pulse)
#Create new gate for T2 Dynamical Decouling
T2DD_gate = Gate("T2DD", 1, [delay])
#Another QC
qc_T2DD = QuantumCircuit(1, 1)
qc_T2DD.append(T2DD_gate, [0])
qc_T2DD.measure(0, 0)
qc_T2DD.add_calibration(T2DD_gate, (0,), T2DD_schedule, [delay])
exp_T2DD_circs = [qc_T2DD.assign_parameters({delay: get_dt_from(d)}, inplace=False) for d in taus_sec]
#Schedule fot T2 D.D.
T2DD_schedule = schedule(exp_T2DD_circs[-1], backend)
T2DD_schedule.draw(backend=backend)
num_shots_per_point = 1024
job = backend.run(exp_T2DD_circs,
meas_level=1,
meas_return='single',
shots=num_shots_per_point)
job_monitor(job)
T2DD_results = job.result(timeout=120)
times_sec = 4*num_sequence*taus_sec
DD_values = []
for i in range(len(times_sec)):
iq_data = T2DD_results.get_memory(i)[:,qubit] * scale_factor
DD_values.append(sum(map(classify, iq_data)) / num_shots_per_point)
plt.scatter(times_sec/us, DD_values, color='black')
plt.xlim(0, np.max(times_sec/us))
plt.xlabel('Total time before measurement [$\mu$s]', fontsize=15)
plt.ylabel('Measured Signal [a.u.]', fontsize=15)
plt.title('Dynamical Decoupling Experiment', fontsize=15)
plt.show()
# Fit the data
fit_func = lambda x, A, B, T2DD: (A * np.exp(-x / T2DD) + B)
fitparams, conv = curve_fit(fit_func, times_sec/us, DD_values, [3.5, 0.8, 150])
_, _, T2DD = fitparams
plt.scatter(times_sec/us, DD_values, color='black')
plt.plot(times_sec/us, fit_func(times_sec/us, *fitparams), color='red', label=f"T2DD = {T2DD:.2f} us")
plt.xlim([0, np.max(times_sec/us)])
plt.xlabel('Total time before measurement [$\mu$s]', fontsize=15)
plt.ylabel('Measured Signal [a.u.]', fontsize=15)
plt.title('Dynamical Decoupling Experiment', fontsize=15)
plt.legend()
plt.show()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
from qiskit.quantum_info import DensityMatrix
from qiskit.visualization import plot_state_city
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0,1)
# plot using a DensityMatrix
state = DensityMatrix(qc)
plot_state_city(state)
|
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
|
aryashah2k
|
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
from qiskit import IBMQ, BasicAer
from qiskit.providers.ibmq import least_busy
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute
from qiskit.quantum_info import Statevector
from qiskit.visualization import plot_state_qsphere
from qiskit.visualization import plot_histogram
from qiskit.tools.monitor import job_monitor
from qiskit.tools.visualization import plot_histogram
from IPython.display import display, Math, Latex
#define a 1 qubit state |0>
sv = Statevector.from_label('0')
print('State_0 |x> = ', sv.data)
#build a circuit with the H gate
mycircuit = QuantumCircuit(1)
mycircuit.h(0)
#apply the circuit into |x>
sv = sv.evolve(mycircuit)
print('State_1 H|x> = ', sv.data)
mycircuit.draw('mpl')
'''
OUR FUNCTION F IS DEFINED AS
n = 2
f(0, 0) = 0
f(0, 1) = 1
f(1, 0) = 1
f(1, 1) = 1
'''
#input size
n = 2
#initialize qubits and measurement bits
input_qubits = QuantumRegister(n+1)
output_bits = ClassicalRegister(n)
#create circuit
my_circuit = QuantumCircuit(input_qubits, output_bits)
#apply X on the last qubit
my_circuit.x(n)
#apply Hadamard on all qubits
my_circuit.h(range(n+1))
my_circuit.barrier()
#Apply Uf, these CNOT gates will mark the desired |x_i>
my_circuit.cx(0, 1)
my_circuit.cx(1, 2)
my_circuit.cx(0, 1)
my_circuit.barrier()
#apply Hadamard on all qubits
my_circuit.h(range(n+1))
my_circuit.measure(range(n), range(n))
#Backend classical simulation
backend = BasicAer.get_backend('qasm_simulator')
atp = 1024
res = execute(my_circuit, backend=backend, shots=atp).result()
ans = res.get_counts()
my_circuit.draw(output='mpl')
#Quantum Backend
#SOON#
plot_histogram(ans)
from qiskit import IBMQ
IBMQ.load_account()
provider = IBMQ.get_provider(group='open', project='main')
backend = provider.get_backend('ibmq_vigo')
job = execute(my_circuit, backend=backend)
result = job.result().get_counts()
plot_histogram(result)
|
https://github.com/shell-raiser/Qiskit-Developer-Certification-Notes-and-Code
|
shell-raiser
|
from qiskit import IBMQ, assemble, transpile
from qiskit.circuit.random import random_circuit
provider = IBMQ.load_account()
backend = provider.backend.ibmq_vigo
qx = random_circuit(n_qubits=5, depth=4) #generate random ckt
transpiled = transpile(qx, backend=backend)
job = backend.run(transpiled)
retrieved_job = backend.retrieve_job(job.job_id())
status = backend.status()
is_operational = status.operational
jobs_in_queue = status.pending_jobs
job_limit = backend.job_limit()
job_list = backend.jobs(limit=5, status=JobStatus.ERROR)
filter = {'hubInfo.hub.name': 'ibm-q'}
job_list = backend.jobs(limit=5, db_filter=filter)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
top = QuantumCircuit(1)
top.x(0);
bottom = QuantumCircuit(2)
bottom.cry(0.2, 0, 1);
tensored = bottom.tensor(top)
tensored.draw('mpl')
|
https://github.com/2lambda123/Qiskit-qiskit
|
2lambda123
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2020, 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.
"""Test cases for the circuit qasm_file and qasm_string method."""
import io
import json
import random
import ddt
import numpy as np
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, pulse
from qiskit.circuit import CASE_DEFAULT
from qiskit.circuit.classical import expr, types
from qiskit.circuit.classicalregister import Clbit
from qiskit.circuit.quantumregister import Qubit
from qiskit.circuit.random import random_circuit
from qiskit.circuit.gate import Gate
from qiskit.circuit.library import (
XGate,
QFT,
QAOAAnsatz,
PauliEvolutionGate,
DCXGate,
MCU1Gate,
MCXGate,
MCXGrayCode,
MCXRecursive,
MCXVChain,
)
from qiskit.circuit.instruction import Instruction
from qiskit.circuit.parameter import Parameter
from qiskit.circuit.parametervector import ParameterVector
from qiskit.synthesis import LieTrotter, SuzukiTrotter
from qiskit.extensions import UnitaryGate
from qiskit.test import QiskitTestCase
from qiskit.qpy import dump, load
from qiskit.quantum_info import Pauli, SparsePauliOp
from qiskit.quantum_info.random import random_unitary
from qiskit.circuit.controlledgate import ControlledGate
@ddt.ddt
class TestLoadFromQPY(QiskitTestCase):
"""Test circuit.from_qasm_* set of methods."""
def assertDeprecatedBitProperties(self, original, roundtripped):
"""Test that deprecated bit attributes are equal if they are set in the original circuit."""
owned_qubits = [
(a, b) for a, b in zip(original.qubits, roundtripped.qubits) if a._register is not None
]
if owned_qubits:
original_qubits, roundtripped_qubits = zip(*owned_qubits)
self.assertEqual(original_qubits, roundtripped_qubits)
owned_clbits = [
(a, b) for a, b in zip(original.clbits, roundtripped.clbits) if a._register is not None
]
if owned_clbits:
original_clbits, roundtripped_clbits = zip(*owned_clbits)
self.assertEqual(original_clbits, roundtripped_clbits)
def test_qpy_full_path(self):
"""Test full path qpy serialization for basic circuit."""
qr_a = QuantumRegister(4, "a")
qr_b = QuantumRegister(4, "b")
cr_c = ClassicalRegister(4, "c")
cr_d = ClassicalRegister(4, "d")
q_circuit = QuantumCircuit(
qr_a,
qr_b,
cr_c,
cr_d,
name="MyCircuit",
metadata={"test": 1, "a": 2},
global_phase=3.14159,
)
q_circuit.h(qr_a)
q_circuit.cx(qr_a, qr_b)
q_circuit.barrier(qr_a)
q_circuit.barrier(qr_b)
q_circuit.measure(qr_a, cr_c)
q_circuit.measure(qr_b, cr_d)
qpy_file = io.BytesIO()
dump(q_circuit, qpy_file)
qpy_file.seek(0)
new_circ = load(qpy_file)[0]
self.assertEqual(q_circuit, new_circ)
self.assertEqual(q_circuit.global_phase, new_circ.global_phase)
self.assertEqual(q_circuit.metadata, new_circ.metadata)
self.assertEqual(q_circuit.name, new_circ.name)
self.assertDeprecatedBitProperties(q_circuit, new_circ)
def test_circuit_with_conditional(self):
"""Test that instructions with conditions are correctly serialized."""
qc = QuantumCircuit(1, 1)
qc.x(0).c_if(qc.cregs[0], 1)
qpy_file = io.BytesIO()
dump(qc, qpy_file)
qpy_file.seek(0)
new_circ = load(qpy_file)[0]
self.assertEqual(qc, new_circ)
self.assertDeprecatedBitProperties(qc, new_circ)
def test_int_parameter(self):
"""Test that integer parameters are correctly serialized."""
qc = QuantumCircuit(1)
qc.rx(3, 0)
qpy_file = io.BytesIO()
dump(qc, qpy_file)
qpy_file.seek(0)
new_circ = load(qpy_file)[0]
self.assertEqual(qc, new_circ)
self.assertDeprecatedBitProperties(qc, new_circ)
def test_float_parameter(self):
"""Test that float parameters are correctly serialized."""
qc = QuantumCircuit(1)
qc.rx(3.14, 0)
qpy_file = io.BytesIO()
dump(qc, qpy_file)
qpy_file.seek(0)
new_circ = load(qpy_file)[0]
self.assertEqual(qc, new_circ)
self.assertDeprecatedBitProperties(qc, new_circ)
def test_numpy_float_parameter(self):
"""Test that numpy float parameters are correctly serialized."""
qc = QuantumCircuit(1)
qc.rx(np.float32(3.14), 0)
qpy_file = io.BytesIO()
dump(qc, qpy_file)
qpy_file.seek(0)
new_circ = load(qpy_file)[0]
self.assertEqual(qc, new_circ)
self.assertDeprecatedBitProperties(qc, new_circ)
def test_numpy_int_parameter(self):
"""Test that numpy integer parameters are correctly serialized."""
qc = QuantumCircuit(1)
qc.rx(np.int16(3), 0)
qpy_file = io.BytesIO()
dump(qc, qpy_file)
qpy_file.seek(0)
new_circ = load(qpy_file)[0]
self.assertEqual(qc, new_circ)
self.assertDeprecatedBitProperties(qc, new_circ)
def test_unitary_gate(self):
"""Test that numpy array parameters are correctly serialized"""
qc = QuantumCircuit(1)
unitary = np.array([[0, 1], [1, 0]])
qc.unitary(unitary, 0)
qpy_file = io.BytesIO()
dump(qc, qpy_file)
qpy_file.seek(0)
new_circ = load(qpy_file)[0]
self.assertEqual(qc, new_circ)
self.assertDeprecatedBitProperties(qc, new_circ)
def test_opaque_gate(self):
"""Test that custom opaque gate is correctly serialized"""
custom_gate = Gate("black_box", 1, [])
qc = QuantumCircuit(1)
qc.append(custom_gate, [0])
qpy_file = io.BytesIO()
dump(qc, qpy_file)
qpy_file.seek(0)
new_circ = load(qpy_file)[0]
self.assertEqual(qc, new_circ)
self.assertDeprecatedBitProperties(qc, new_circ)
def test_opaque_instruction(self):
"""Test that custom opaque instruction is correctly serialized"""
custom_gate = Instruction("black_box", 1, 0, [])
qc = QuantumCircuit(1)
qc.append(custom_gate, [0])
qpy_file = io.BytesIO()
dump(qc, qpy_file)
qpy_file.seek(0)
new_circ = load(qpy_file)[0]
self.assertEqual(qc, new_circ)
self.assertDeprecatedBitProperties(qc, new_circ)
def test_custom_gate(self):
"""Test that custom gate is correctly serialized"""
custom_gate = Gate("black_box", 1, [])
custom_definition = QuantumCircuit(1)
custom_definition.h(0)
custom_definition.rz(1.5, 0)
custom_definition.sdg(0)
custom_gate.definition = custom_definition
qc = QuantumCircuit(1)
qc.append(custom_gate, [0])
qpy_file = io.BytesIO()
dump(qc, qpy_file)
qpy_file.seek(0)
new_circ = load(qpy_file)[0]
self.assertEqual(qc, new_circ)
self.assertEqual(qc.decompose(), new_circ.decompose())
self.assertDeprecatedBitProperties(qc, new_circ)
def test_custom_instruction(self):
"""Test that custom instruction is correctly serialized"""
custom_gate = Instruction("black_box", 1, 0, [])
custom_definition = QuantumCircuit(1)
custom_definition.h(0)
custom_definition.rz(1.5, 0)
custom_definition.sdg(0)
custom_gate.definition = custom_definition
qc = QuantumCircuit(1)
qc.append(custom_gate, [0])
qpy_file = io.BytesIO()
dump(qc, qpy_file)
qpy_file.seek(0)
new_circ = load(qpy_file)[0]
self.assertEqual(qc, new_circ)
self.assertEqual(qc.decompose(), new_circ.decompose())
self.assertDeprecatedBitProperties(qc, new_circ)
def test_parameter(self):
"""Test that a circuit with a parameter is correctly serialized."""
theta = Parameter("theta")
qc = QuantumCircuit(5, 1)
qc.h(0)
for i in range(4):
qc.cx(i, i + 1)
qc.barrier()
qc.rz(theta, range(5))
qc.barrier()
for i in reversed(range(4)):
qc.cx(i, i + 1)
qc.h(0)
qc.measure(0, 0)
qpy_file = io.BytesIO()
dump(qc, qpy_file)
qpy_file.seek(0)
new_circ = load(qpy_file)[0]
self.assertEqual(qc, new_circ)
self.assertEqual(qc.bind_parameters({theta: 3.14}), new_circ.bind_parameters({theta: 3.14}))
self.assertDeprecatedBitProperties(qc, new_circ)
def test_bound_parameter(self):
"""Test a circuit with a bound parameter is correctly serialized."""
theta = Parameter("theta")
qc = QuantumCircuit(5, 1)
qc.h(0)
for i in range(4):
qc.cx(i, i + 1)
qc.barrier()
qc.rz(theta, range(5))
qc.barrier()
for i in reversed(range(4)):
qc.cx(i, i + 1)
qc.h(0)
qc.measure(0, 0)
qc.assign_parameters({theta: 3.14})
qpy_file = io.BytesIO()
dump(qc, qpy_file)
qpy_file.seek(0)
new_circ = load(qpy_file)[0]
self.assertEqual(qc, new_circ)
self.assertDeprecatedBitProperties(qc, new_circ)
def test_bound_calibration_parameter(self):
"""Test a circuit with a bound calibration parameter is correctly serialized.
In particular, this test ensures that parameters on a circuit
instruction are consistent with the circuit's calibrations dictionary
after serialization.
"""
amp = Parameter("amp")
with pulse.builder.build() as sched:
pulse.builder.play(pulse.Constant(100, amp), pulse.DriveChannel(0))
gate = Gate("custom", 1, [amp])
qc = QuantumCircuit(1)
qc.append(gate, (0,))
qc.add_calibration(gate, (0,), sched)
qc.assign_parameters({amp: 1 / 3}, inplace=True)
qpy_file = io.BytesIO()
dump(qc, qpy_file)
qpy_file.seek(0)
new_circ = load(qpy_file)[0]
self.assertEqual(qc, new_circ)
instruction = new_circ.data[0]
cal_key = (
tuple(new_circ.find_bit(q).index for q in instruction.qubits),
tuple(instruction.operation.params),
)
# Make sure that looking for a calibration based on the instruction's
# parameters succeeds
self.assertIn(cal_key, new_circ.calibrations[gate.name])
def test_parameter_expression(self):
"""Test a circuit with a parameter expression."""
theta = Parameter("theta")
phi = Parameter("phi")
sum_param = theta + phi
qc = QuantumCircuit(5, 1)
qc.h(0)
for i in range(4):
qc.cx(i, i + 1)
qc.barrier()
qc.rz(sum_param, range(3))
qc.rz(phi, 3)
qc.rz(theta, 4)
qc.barrier()
for i in reversed(range(4)):
qc.cx(i, i + 1)
qc.h(0)
qc.measure(0, 0)
qpy_file = io.BytesIO()
dump(qc, qpy_file)
qpy_file.seek(0)
new_circuit = load(qpy_file)[0]
self.assertEqual(qc, new_circuit)
self.assertDeprecatedBitProperties(qc, new_circuit)
def test_string_parameter(self):
"""Test a PauliGate instruction that has string parameters."""
circ = QuantumCircuit(3)
circ.z(0)
circ.y(1)
circ.x(2)
qpy_file = io.BytesIO()
dump(circ, qpy_file)
qpy_file.seek(0)
new_circuit = load(qpy_file)[0]
self.assertEqual(circ, new_circuit)
self.assertDeprecatedBitProperties(circ, new_circuit)
def test_multiple_circuits(self):
"""Test multiple circuits can be serialized together."""
circuits = []
for i in range(10):
circuits.append(
random_circuit(10, 10, measure=True, conditional=True, reset=True, seed=42 + i)
)
qpy_file = io.BytesIO()
dump(circuits, qpy_file)
qpy_file.seek(0)
new_circs = load(qpy_file)
self.assertEqual(circuits, new_circs)
for old, new in zip(circuits, new_circs):
self.assertDeprecatedBitProperties(old, new)
def test_shared_bit_register(self):
"""Test a circuit with shared bit registers."""
qubits = [Qubit() for _ in range(5)]
qc = QuantumCircuit()
qc.add_bits(qubits)
qr = QuantumRegister(bits=qubits)
qc.add_register(qr)
qc.h(qr)
qc.cx(0, 1)
qc.cx(0, 2)
qc.cx(0, 3)
qc.cx(0, 4)
qc.measure_all()
qpy_file = io.BytesIO()
dump(qc, qpy_file)
qpy_file.seek(0)
new_qc = load(qpy_file)[0]
self.assertEqual(qc, new_qc)
self.assertDeprecatedBitProperties(qc, new_qc)
def test_hybrid_standalone_register(self):
"""Test qpy serialization with registers that mix bit types"""
qr = QuantumRegister(5, "foo")
qr = QuantumRegister(name="bar", bits=qr[:3] + [Qubit(), Qubit()])
cr = ClassicalRegister(5, "foo")
cr = ClassicalRegister(name="classical_bar", bits=cr[:3] + [Clbit(), Clbit()])
qc = QuantumCircuit(qr, cr)
qc.h(0)
qc.cx(0, 1)
qc.cx(0, 2)
qc.cx(0, 3)
qc.cx(0, 4)
qc.measure(qr, cr)
qpy_file = io.BytesIO()
dump(qc, qpy_file)
qpy_file.seek(0)
new_circ = load(qpy_file)[0]
self.assertEqual(qc, new_circ)
self.assertDeprecatedBitProperties(qc, new_circ)
def test_mixed_registers(self):
"""Test circuit with mix of standalone and shared registers."""
qubits = [Qubit() for _ in range(5)]
clbits = [Clbit() for _ in range(5)]
qc = QuantumCircuit()
qc.add_bits(qubits)
qc.add_bits(clbits)
qr = QuantumRegister(bits=qubits)
cr = ClassicalRegister(bits=clbits)
qc.add_register(qr)
qc.add_register(cr)
qr_standalone = QuantumRegister(2, "standalone")
qc.add_register(qr_standalone)
cr_standalone = ClassicalRegister(2, "classical_standalone")
qc.add_register(cr_standalone)
qc.unitary(random_unitary(32, seed=42), qr)
qc.unitary(random_unitary(4, seed=100), qr_standalone)
qc.measure(qr, cr)
qc.measure(qr_standalone, cr_standalone)
qpy_file = io.BytesIO()
dump(qc, qpy_file)
qpy_file.seek(0)
new_circ = load(qpy_file)[0]
self.assertEqual(qc, new_circ)
self.assertDeprecatedBitProperties(qc, new_circ)
def test_standalone_and_shared_out_of_order(self):
"""Test circuit with register bits inserted out of order."""
qr_standalone = QuantumRegister(2, "standalone")
qubits = [Qubit() for _ in range(5)]
clbits = [Clbit() for _ in range(5)]
qc = QuantumCircuit()
qc.add_bits(qubits)
qc.add_bits(clbits)
random.shuffle(qubits)
random.shuffle(clbits)
qr = QuantumRegister(bits=qubits)
cr = ClassicalRegister(bits=clbits)
qc.add_register(qr)
qc.add_register(cr)
qr_standalone = QuantumRegister(2, "standalone")
cr_standalone = ClassicalRegister(2, "classical_standalone")
qc.add_bits([qr_standalone[1], qr_standalone[0]])
qc.add_bits([cr_standalone[1], cr_standalone[0]])
qc.add_register(qr_standalone)
qc.add_register(cr_standalone)
qc.unitary(random_unitary(32, seed=42), qr)
qc.unitary(random_unitary(4, seed=100), qr_standalone)
qc.measure(qr, cr)
qc.measure(qr_standalone, cr_standalone)
qpy_file = io.BytesIO()
dump(qc, qpy_file)
qpy_file.seek(0)
new_circ = load(qpy_file)[0]
self.assertEqual(qc, new_circ)
self.assertDeprecatedBitProperties(qc, new_circ)
def test_unitary_gate_with_label(self):
"""Test that numpy array parameters are correctly serialized with a label"""
qc = QuantumCircuit(1)
unitary = np.array([[0, 1], [1, 0]])
unitary_gate = UnitaryGate(unitary, "My Special unitary")
qc.append(unitary_gate, [0])
qpy_file = io.BytesIO()
dump(qc, qpy_file)
qpy_file.seek(0)
new_circ = load(qpy_file)[0]
self.assertEqual(qc, new_circ)
self.assertEqual(
[x.operation.label for x in qc.data], [x.operation.label for x in new_circ.data]
)
self.assertDeprecatedBitProperties(qc, new_circ)
def test_opaque_gate_with_label(self):
"""Test that custom opaque gate is correctly serialized with a label"""
custom_gate = Gate("black_box", 1, [])
custom_gate.label = "My Special Black Box"
qc = QuantumCircuit(1)
qc.append(custom_gate, [0])
qpy_file = io.BytesIO()
dump(qc, qpy_file)
qpy_file.seek(0)
new_circ = load(qpy_file)[0]
self.assertEqual(qc, new_circ)
self.assertEqual(
[x.operation.label for x in qc.data], [x.operation.label for x in new_circ.data]
)
self.assertDeprecatedBitProperties(qc, new_circ)
def test_opaque_instruction_with_label(self):
"""Test that custom opaque instruction is correctly serialized with a label"""
custom_gate = Instruction("black_box", 1, 0, [])
custom_gate.label = "My Special Black Box Instruction"
qc = QuantumCircuit(1)
qc.append(custom_gate, [0])
qpy_file = io.BytesIO()
dump(qc, qpy_file)
qpy_file.seek(0)
new_circ = load(qpy_file)[0]
self.assertEqual(qc, new_circ)
self.assertEqual(
[x.operation.label for x in qc.data], [x.operation.label for x in new_circ.data]
)
self.assertDeprecatedBitProperties(qc, new_circ)
def test_custom_gate_with_label(self):
"""Test that custom gate is correctly serialized with a label"""
custom_gate = Gate("black_box", 1, [])
custom_definition = QuantumCircuit(1)
custom_definition.h(0)
custom_definition.rz(1.5, 0)
custom_definition.sdg(0)
custom_gate.definition = custom_definition
custom_gate.label = "My special black box with a definition"
qc = QuantumCircuit(1)
qc.append(custom_gate, [0])
qpy_file = io.BytesIO()
dump(qc, qpy_file)
qpy_file.seek(0)
new_circ = load(qpy_file)[0]
self.assertEqual(qc, new_circ)
self.assertEqual(qc.decompose(), new_circ.decompose())
self.assertEqual(
[x.operation.label for x in qc.data], [x.operation.label for x in new_circ.data]
)
self.assertDeprecatedBitProperties(qc, new_circ)
def test_custom_instruction_with_label(self):
"""Test that custom instruction is correctly serialized with a label"""
custom_gate = Instruction("black_box", 1, 0, [])
custom_definition = QuantumCircuit(1)
custom_definition.h(0)
custom_definition.rz(1.5, 0)
custom_definition.sdg(0)
custom_gate.definition = custom_definition
custom_gate.label = "My Special Black Box Instruction with a definition"
qc = QuantumCircuit(1)
qc.append(custom_gate, [0])
qpy_file = io.BytesIO()
dump(qc, qpy_file)
qpy_file.seek(0)
new_circ = load(qpy_file)[0]
self.assertEqual(qc, new_circ)
self.assertEqual(qc.decompose(), new_circ.decompose())
self.assertEqual(
[x.operation.label for x in qc.data], [x.operation.label for x in new_circ.data]
)
self.assertDeprecatedBitProperties(qc, new_circ)
def test_custom_gate_with_noop_definition(self):
"""Test that a custom gate whose definition contains no elements is serialized with a
proper definition.
Regression test of gh-7429."""
empty = QuantumCircuit(1, name="empty").to_gate()
opaque = Gate("opaque", 1, [])
qc = QuantumCircuit(2)
qc.append(empty, [0], [])
qc.append(opaque, [1], [])
qpy_file = io.BytesIO()
dump(qc, qpy_file)
qpy_file.seek(0)
new_circ = load(qpy_file)[0]
self.assertEqual(qc, new_circ)
self.assertEqual(qc.decompose(), new_circ.decompose())
self.assertEqual(len(new_circ), 2)
self.assertIsInstance(new_circ.data[0].operation.definition, QuantumCircuit)
self.assertIs(new_circ.data[1].operation.definition, None)
self.assertDeprecatedBitProperties(qc, new_circ)
def test_custom_instruction_with_noop_definition(self):
"""Test that a custom instruction whose definition contains no elements is serialized with a
proper definition.
Regression test of gh-7429."""
empty = QuantumCircuit(1, name="empty").to_instruction()
opaque = Instruction("opaque", 1, 0, [])
qc = QuantumCircuit(2)
qc.append(empty, [0], [])
qc.append(opaque, [1], [])
qpy_file = io.BytesIO()
dump(qc, qpy_file)
qpy_file.seek(0)
new_circ = load(qpy_file)[0]
self.assertEqual(qc, new_circ)
self.assertEqual(qc.decompose(), new_circ.decompose())
self.assertEqual(len(new_circ), 2)
self.assertIsInstance(new_circ.data[0].operation.definition, QuantumCircuit)
self.assertIs(new_circ.data[1].operation.definition, None)
self.assertDeprecatedBitProperties(qc, new_circ)
def test_standard_gate_with_label(self):
"""Test a standard gate with a label."""
qc = QuantumCircuit(1)
gate = XGate()
gate.label = "My special X gate"
qc.append(gate, [0])
qpy_file = io.BytesIO()
dump(qc, qpy_file)
qpy_file.seek(0)
new_circ = load(qpy_file)[0]
self.assertEqual(qc, new_circ)
self.assertEqual(
[x.operation.label for x in qc.data], [x.operation.label for x in new_circ.data]
)
self.assertDeprecatedBitProperties(qc, new_circ)
def test_circuit_with_conditional_with_label(self):
"""Test that instructions with conditions are correctly serialized."""
qc = QuantumCircuit(1, 1)
gate = XGate(label="My conditional x gate")
gate.c_if(qc.cregs[0], 1)
qc.append(gate, [0])
qpy_file = io.BytesIO()
dump(qc, qpy_file)
qpy_file.seek(0)
new_circ = load(qpy_file)[0]
self.assertEqual(qc, new_circ)
self.assertEqual(
[x.operation.label for x in qc.data], [x.operation.label for x in new_circ.data]
)
self.assertDeprecatedBitProperties(qc, new_circ)
def test_initialize_qft(self):
"""Test that initialize with a complex statevector and qft work."""
k = 5
state = (1 / np.sqrt(8)) * np.array(
[
np.exp(-1j * 2 * np.pi * k * (0) / 8),
np.exp(-1j * 2 * np.pi * k * (1) / 8),
np.exp(-1j * 2 * np.pi * k * (2) / 8),
np.exp(-1j * 2 * np.pi * k * 3 / 8),
np.exp(-1j * 2 * np.pi * k * 4 / 8),
np.exp(-1j * 2 * np.pi * k * 5 / 8),
np.exp(-1j * 2 * np.pi * k * 6 / 8),
np.exp(-1j * 2 * np.pi * k * 7 / 8),
]
)
qubits = 3
qc = QuantumCircuit(qubits, qubits)
qc.initialize(state)
qc.append(QFT(qubits), range(qubits))
qc.measure(range(qubits), range(qubits))
qpy_file = io.BytesIO()
dump(qc, qpy_file)
qpy_file.seek(0)
new_circ = load(qpy_file)[0]
self.assertEqual(qc, new_circ)
self.assertEqual(
[x.operation.label for x in qc.data], [x.operation.label for x in new_circ.data]
)
self.assertDeprecatedBitProperties(qc, new_circ)
def test_statepreparation(self):
"""Test that state preparation with a complex statevector and qft work."""
k = 5
state = (1 / np.sqrt(8)) * np.array(
[
np.exp(-1j * 2 * np.pi * k * (0) / 8),
np.exp(-1j * 2 * np.pi * k * (1) / 8),
np.exp(-1j * 2 * np.pi * k * (2) / 8),
np.exp(-1j * 2 * np.pi * k * 3 / 8),
np.exp(-1j * 2 * np.pi * k * 4 / 8),
np.exp(-1j * 2 * np.pi * k * 5 / 8),
np.exp(-1j * 2 * np.pi * k * 6 / 8),
np.exp(-1j * 2 * np.pi * k * 7 / 8),
]
)
qubits = 3
qc = QuantumCircuit(qubits, qubits)
qc.prepare_state(state)
qc.append(QFT(qubits), range(qubits))
qc.measure(range(qubits), range(qubits))
qpy_file = io.BytesIO()
dump(qc, qpy_file)
qpy_file.seek(0)
new_circ = load(qpy_file)[0]
self.assertEqual(qc, new_circ)
self.assertEqual(
[x.operation.label for x in qc.data], [x.operation.label for x in new_circ.data]
)
self.assertDeprecatedBitProperties(qc, new_circ)
def test_single_bit_teleportation(self):
"""Test a teleportation circuit with single bit conditions."""
qr = QuantumRegister(1)
cr = ClassicalRegister(2, name="name")
qc = QuantumCircuit(qr, cr, name="Reset Test")
qc.x(0)
qc.measure(0, cr[0])
qc.x(0).c_if(cr[0], 1)
qc.measure(0, cr[1])
qpy_file = io.BytesIO()
dump(qc, qpy_file)
qpy_file.seek(0)
new_circ = load(qpy_file)[0]
self.assertEqual(qc, new_circ)
self.assertEqual(
[x.operation.label for x in qc.data], [x.operation.label for x in new_circ.data]
)
self.assertDeprecatedBitProperties(qc, new_circ)
def test_qaoa(self):
"""Test loading a QAOA circuit works."""
cost_operator = Pauli("ZIIZ")
qaoa = QAOAAnsatz(cost_operator, reps=2)
qpy_file = io.BytesIO()
dump(qaoa, qpy_file)
qpy_file.seek(0)
new_circ = load(qpy_file)[0]
self.assertEqual(qaoa, new_circ)
self.assertEqual(
[x.operation.label for x in qaoa.data], [x.operation.label for x in new_circ.data]
)
self.assertDeprecatedBitProperties(qaoa, new_circ)
def test_evolutiongate(self):
"""Test loading a circuit with evolution gate works."""
synthesis = LieTrotter(reps=2)
evo = PauliEvolutionGate(
SparsePauliOp.from_list([("ZI", 1), ("IZ", 1)]), time=2, synthesis=synthesis
)
qc = QuantumCircuit(2)
qc.append(evo, range(2))
qpy_file = io.BytesIO()
dump(qc, qpy_file)
qpy_file.seek(0)
new_circ = load(qpy_file)[0]
self.assertEqual(qc, new_circ)
self.assertEqual(
[x.operation.label for x in qc.data], [x.operation.label for x in new_circ.data]
)
new_evo = new_circ.data[0].operation
self.assertIsInstance(new_evo, PauliEvolutionGate)
self.assertDeprecatedBitProperties(qc, new_circ)
def test_evolutiongate_param_time(self):
"""Test loading a circuit with an evolution gate that has a parameter for time."""
synthesis = LieTrotter(reps=2)
time = Parameter("t")
evo = PauliEvolutionGate(
SparsePauliOp.from_list([("ZI", 1), ("IZ", 1)]), time=time, synthesis=synthesis
)
qc = QuantumCircuit(2)
qc.append(evo, range(2))
qpy_file = io.BytesIO()
dump(qc, qpy_file)
qpy_file.seek(0)
new_circ = load(qpy_file)[0]
self.assertEqual(qc, new_circ)
self.assertEqual(
[x.operation.label for x in qc.data], [x.operation.label for x in new_circ.data]
)
new_evo = new_circ.data[0].operation
self.assertIsInstance(new_evo, PauliEvolutionGate)
self.assertDeprecatedBitProperties(qc, new_circ)
def test_evolutiongate_param_expr_time(self):
"""Test loading a circuit with an evolution gate that has a parameter for time."""
synthesis = LieTrotter(reps=2)
time = Parameter("t")
evo = PauliEvolutionGate(
SparsePauliOp.from_list([("ZI", 1), ("IZ", 1)]), time=time * time, synthesis=synthesis
)
qc = QuantumCircuit(2)
qc.append(evo, range(2))
qpy_file = io.BytesIO()
dump(qc, qpy_file)
qpy_file.seek(0)
new_circ = load(qpy_file)[0]
self.assertEqual(qc, new_circ)
self.assertEqual(
[x.operation.label for x in qc.data], [x.operation.label for x in new_circ.data]
)
new_evo = new_circ.data[0].operation
self.assertIsInstance(new_evo, PauliEvolutionGate)
self.assertDeprecatedBitProperties(qc, new_circ)
def test_evolutiongate_param_vec_time(self):
"""Test loading a an evolution gate that has a param vector element for time."""
synthesis = LieTrotter(reps=2)
time = ParameterVector("TimeVec", 1)
evo = PauliEvolutionGate(
SparsePauliOp.from_list([("ZI", 1), ("IZ", 1)]), time=time[0], synthesis=synthesis
)
qc = QuantumCircuit(2)
qc.append(evo, range(2))
qpy_file = io.BytesIO()
dump(qc, qpy_file)
qpy_file.seek(0)
new_circ = load(qpy_file)[0]
self.assertEqual(qc, new_circ)
self.assertEqual(
[x.operation.label for x in qc.data], [x.operation.label for x in new_circ.data]
)
new_evo = new_circ.data[0].operation
self.assertIsInstance(new_evo, PauliEvolutionGate)
self.assertDeprecatedBitProperties(qc, new_circ)
def test_op_list_evolutiongate(self):
"""Test loading a circuit with evolution gate works."""
evo = PauliEvolutionGate(
[SparsePauliOp.from_list([("ZI", 1), ("IZ", 1)])] * 5, time=0.2, synthesis=None
)
qc = QuantumCircuit(2)
qc.append(evo, range(2))
qpy_file = io.BytesIO()
dump(qc, qpy_file)
qpy_file.seek(0)
new_circ = load(qpy_file)[0]
self.assertEqual(qc, new_circ)
self.assertEqual(
[x.operation.label for x in qc.data], [x.operation.label for x in new_circ.data]
)
new_evo = new_circ.data[0].operation
self.assertIsInstance(new_evo, PauliEvolutionGate)
self.assertDeprecatedBitProperties(qc, new_circ)
def test_op_evolution_gate_suzuki_trotter(self):
"""Test qpy path with a suzuki trotter synthesis method on an evolution gate."""
synthesis = SuzukiTrotter()
evo = PauliEvolutionGate(
SparsePauliOp.from_list([("ZI", 1), ("IZ", 1)]), time=0.2, synthesis=synthesis
)
qc = QuantumCircuit(2)
qc.append(evo, range(2))
qpy_file = io.BytesIO()
dump(qc, qpy_file)
qpy_file.seek(0)
new_circ = load(qpy_file)[0]
self.assertEqual(qc, new_circ)
self.assertEqual(
[x.operation.label for x in qc.data], [x.operation.label for x in new_circ.data]
)
new_evo = new_circ.data[0].operation
self.assertIsInstance(new_evo, PauliEvolutionGate)
self.assertDeprecatedBitProperties(qc, new_circ)
def test_parameter_expression_global_phase(self):
"""Test a circuit with a parameter expression global_phase."""
theta = Parameter("theta")
phi = Parameter("phi")
sum_param = theta + phi
qc = QuantumCircuit(5, 1, global_phase=sum_param)
qc.h(0)
for i in range(4):
qc.cx(i, i + 1)
qc.barrier()
qc.rz(sum_param, range(3))
qc.rz(phi, 3)
qc.rz(theta, 4)
qc.barrier()
for i in reversed(range(4)):
qc.cx(i, i + 1)
qc.h(0)
qc.measure(0, 0)
qpy_file = io.BytesIO()
dump(qc, qpy_file)
qpy_file.seek(0)
new_circuit = load(qpy_file)[0]
self.assertEqual(qc, new_circuit)
self.assertDeprecatedBitProperties(qc, new_circuit)
def test_parameter_global_phase(self):
"""Test a circuit with a parameter expression global_phase."""
theta = Parameter("theta")
qc = QuantumCircuit(2, global_phase=theta)
qc.h(0)
qc.cx(0, 1)
qc.measure_all()
qpy_file = io.BytesIO()
dump(qc, qpy_file)
qpy_file.seek(0)
new_circuit = load(qpy_file)[0]
self.assertEqual(qc, new_circuit)
def test_parameter_vector(self):
"""Test a circuit with a parameter vector for gate parameters."""
qc = QuantumCircuit(11)
input_params = ParameterVector("x_par", 11)
user_params = ParameterVector("ΞΈ_par", 11)
for i, param in enumerate(user_params):
qc.ry(param, i)
for i, param in enumerate(input_params):
qc.rz(param, i)
qpy_file = io.BytesIO()
dump(qc, qpy_file)
qpy_file.seek(0)
new_circuit = load(qpy_file)[0]
expected_params = [x.name for x in qc.parameters]
self.assertEqual([x.name for x in new_circuit.parameters], expected_params)
self.assertDeprecatedBitProperties(qc, new_circuit)
def test_parameter_vector_element_in_expression(self):
"""Test a circuit with a parameter vector used in a parameter expression."""
qc = QuantumCircuit(7)
entanglement = [[i, i + 1] for i in range(7 - 1)]
input_params = ParameterVector("x_par", 14)
user_params = ParameterVector("\u03B8_par", 1)
for i in range(qc.num_qubits):
qc.ry(user_params[0], qc.qubits[i])
for source, target in entanglement:
qc.cz(qc.qubits[source], qc.qubits[target])
for i in range(qc.num_qubits):
qc.rz(-2 * input_params[2 * i + 1], qc.qubits[i])
qc.rx(-2 * input_params[2 * i], qc.qubits[i])
qpy_file = io.BytesIO()
dump(qc, qpy_file)
qpy_file.seek(0)
new_circuit = load(qpy_file)[0]
expected_params = [x.name for x in qc.parameters]
self.assertEqual([x.name for x in new_circuit.parameters], expected_params)
self.assertDeprecatedBitProperties(qc, new_circuit)
def test_parameter_vector_incomplete_warns(self):
"""Test that qpy's deserialization warns if a ParameterVector isn't fully identical."""
vec = ParameterVector("test", 3)
qc = QuantumCircuit(1, name="fun")
qc.rx(vec[1], 0)
qpy_file = io.BytesIO()
dump(qc, qpy_file)
qpy_file.seek(0)
with self.assertWarnsRegex(UserWarning, r"^The ParameterVector.*Elements 0, 2.*fun$"):
new_circuit = load(qpy_file)[0]
self.assertEqual(qc, new_circuit)
self.assertDeprecatedBitProperties(qc, new_circuit)
def test_parameter_vector_global_phase(self):
"""Test that a circuit with a standalone ParameterVectorElement phase works."""
vec = ParameterVector("phase", 1)
qc = QuantumCircuit(1, global_phase=vec[0])
qpy_file = io.BytesIO()
dump(qc, qpy_file)
qpy_file.seek(0)
new_circuit = load(qpy_file)[0]
self.assertEqual(qc, new_circuit)
self.assertDeprecatedBitProperties(qc, new_circuit)
def test_custom_metadata_serializer_full_path(self):
"""Test that running with custom metadata serialization works."""
class CustomObject:
"""Custom string container object."""
def __init__(self, string):
self.string = string
def __eq__(self, other):
return self.string == other.string
class CustomSerializer(json.JSONEncoder):
"""Custom json encoder to handle CustomObject."""
def default(self, o):
if isinstance(o, CustomObject):
return {"__type__": "Custom", "value": o.string}
return json.JSONEncoder.default(self, o)
class CustomDeserializer(json.JSONDecoder):
"""Custom json decoder to handle CustomObject."""
def object_hook(self, o): # pylint: disable=invalid-name,method-hidden
"""Hook to override default decoder.
Normally specified as a kwarg on load() that overloads the
default decoder. Done here to avoid reimplementing the
decode method.
"""
if "__type__" in o:
obj_type = o["__type__"]
if obj_type == "Custom":
return CustomObject(o["value"])
return o
theta = Parameter("theta")
qc = QuantumCircuit(2, global_phase=theta)
qc.h(0)
qc.cx(0, 1)
qc.measure_all()
circuits = [qc, qc.copy()]
circuits[0].metadata = {"key": CustomObject("Circuit 1")}
circuits[1].metadata = {"key": CustomObject("Circuit 2")}
qpy_file = io.BytesIO()
dump(circuits, qpy_file, metadata_serializer=CustomSerializer)
qpy_file.seek(0)
new_circuits = load(qpy_file, metadata_deserializer=CustomDeserializer)
self.assertEqual(qc, new_circuits[0])
self.assertEqual(circuits[0].metadata["key"], CustomObject("Circuit 1"))
self.assertEqual(qc, new_circuits[1])
self.assertEqual(circuits[1].metadata["key"], CustomObject("Circuit 2"))
self.assertDeprecatedBitProperties(qc, new_circuits[0])
self.assertDeprecatedBitProperties(qc, new_circuits[1])
def test_qpy_with_ifelseop(self):
"""Test qpy serialization with an if block."""
qc = QuantumCircuit(2, 2)
qc.h(0)
qc.measure(0, 0)
with qc.if_test((qc.clbits[0], True)):
qc.x(1)
qc.measure(1, 1)
qpy_file = io.BytesIO()
dump(qc, qpy_file)
qpy_file.seek(0)
new_circuit = load(qpy_file)[0]
self.assertEqual(qc, new_circuit)
self.assertDeprecatedBitProperties(qc, new_circuit)
def test_qpy_with_ifelseop_with_else(self):
"""Test qpy serialization with an else block."""
qc = QuantumCircuit(2, 2)
qc.h(0)
qc.measure(0, 0)
with qc.if_test((qc.clbits[0], True)) as else_:
qc.x(1)
with else_:
qc.y(1)
qc.measure(1, 1)
qpy_file = io.BytesIO()
dump(qc, qpy_file)
qpy_file.seek(0)
new_circuit = load(qpy_file)[0]
self.assertEqual(qc, new_circuit)
self.assertDeprecatedBitProperties(qc, new_circuit)
def test_qpy_with_while_loop(self):
"""Test qpy serialization with a for loop."""
qc = QuantumCircuit(2, 1)
with qc.while_loop((qc.clbits[0], 0)):
qc.h(0)
qc.cx(0, 1)
qc.measure(0, 0)
qpy_file = io.BytesIO()
dump(qc, qpy_file)
qpy_file.seek(0)
new_circuit = load(qpy_file)[0]
self.assertEqual(qc, new_circuit)
self.assertDeprecatedBitProperties(qc, new_circuit)
def test_qpy_with_for_loop(self):
"""Test qpy serialization with a for loop."""
qc = QuantumCircuit(2, 1)
with qc.for_loop(range(5)):
qc.h(0)
qc.cx(0, 1)
qc.measure(0, 0)
qc.break_loop().c_if(0, True)
qpy_file = io.BytesIO()
dump(qc, qpy_file)
qpy_file.seek(0)
new_circuit = load(qpy_file)[0]
self.assertEqual(qc, new_circuit)
self.assertDeprecatedBitProperties(qc, new_circuit)
def test_qpy_with_for_loop_iterator(self):
"""Test qpy serialization with a for loop."""
qc = QuantumCircuit(2, 1)
with qc.for_loop(iter(range(5))):
qc.h(0)
qc.cx(0, 1)
qc.measure(0, 0)
qc.break_loop().c_if(0, True)
qpy_file = io.BytesIO()
dump(qc, qpy_file)
qpy_file.seek(0)
new_circuit = load(qpy_file)[0]
self.assertEqual(qc, new_circuit)
self.assertDeprecatedBitProperties(qc, new_circuit)
def test_qpy_clbit_switch(self):
"""Test QPY serialisation for a switch statement with a Clbit target."""
case_t = QuantumCircuit(2, 1)
case_t.x(0)
case_f = QuantumCircuit(2, 1)
case_f.z(0)
qc = QuantumCircuit(2, 1)
qc.switch(0, [(True, case_t), (False, case_f)], qc.qubits, qc.clbits)
with io.BytesIO() as fptr:
dump(qc, fptr)
fptr.seek(0)
new_circuit = load(fptr)[0]
self.assertEqual(qc, new_circuit)
self.assertDeprecatedBitProperties(qc, new_circuit)
def test_qpy_register_switch(self):
"""Test QPY serialisation for a switch statement with a ClassicalRegister target."""
qreg = QuantumRegister(2, "q")
creg = ClassicalRegister(3, "c")
case_0 = QuantumCircuit(qreg, creg)
case_0.x(0)
case_1 = QuantumCircuit(qreg, creg)
case_1.z(1)
case_2 = QuantumCircuit(qreg, creg)
case_2.x(1)
qc = QuantumCircuit(qreg, creg)
qc.switch(creg, [(0, case_0), ((1, 2), case_1), ((3, 4, CASE_DEFAULT), case_2)], qreg, creg)
with io.BytesIO() as fptr:
dump(qc, fptr)
fptr.seek(0)
new_circuit = load(fptr)[0]
self.assertEqual(qc, new_circuit)
self.assertDeprecatedBitProperties(qc, new_circuit)
def test_standalone_register_partial_bit_in_circuit(self):
"""Test qpy with only some bits from standalone register."""
qr = QuantumRegister(2)
qc = QuantumCircuit([qr[0]])
qc.x(0)
qpy_file = io.BytesIO()
dump(qc, qpy_file)
qpy_file.seek(0)
new_circuit = load(qpy_file)[0]
self.assertEqual(qc, new_circuit)
self.assertDeprecatedBitProperties(qc, new_circuit)
def test_nested_tuple_param(self):
"""Test qpy with an instruction that contains nested tuples."""
inst = Instruction("tuple_test", 1, 0, [((((0, 1), (0, 1)), 2, 3), ("A", "B", "C"))])
qc = QuantumCircuit(1)
qc.append(inst, [0])
qpy_file = io.BytesIO()
dump(qc, qpy_file)
qpy_file.seek(0)
new_circuit = load(qpy_file)[0]
self.assertEqual(qc, new_circuit)
self.assertDeprecatedBitProperties(qc, new_circuit)
def test_empty_tuple_param(self):
"""Test qpy with an instruction that contains an empty tuple."""
inst = Instruction("empty_tuple_test", 1, 0, [()])
qc = QuantumCircuit(1)
qc.append(inst, [0])
qpy_file = io.BytesIO()
dump(qc, qpy_file)
qpy_file.seek(0)
new_circuit = load(qpy_file)[0]
self.assertEqual(qc, new_circuit)
self.assertDeprecatedBitProperties(qc, new_circuit)
def test_ucr_gates(self):
"""Test qpy with UCRX, UCRY, and UCRZ gates."""
qc = QuantumCircuit(3)
qc.ucrz([0, 0, 0, -np.pi], [0, 1], 2)
qc.ucry([0, 0, 0, -np.pi], [0, 2], 1)
qc.ucrx([0, 0, 0, -np.pi], [2, 1], 0)
qc.measure_all()
qpy_file = io.BytesIO()
dump(qc, qpy_file)
qpy_file.seek(0)
new_circuit = load(qpy_file)[0]
self.assertEqual(qc.decompose().decompose(), new_circuit.decompose().decompose())
self.assertDeprecatedBitProperties(qc, new_circuit)
def test_controlled_gate(self):
"""Test a custom controlled gate."""
qc = QuantumCircuit(3)
controlled_gate = DCXGate().control(1)
qc.append(controlled_gate, [0, 1, 2])
qpy_file = io.BytesIO()
dump(qc, qpy_file)
qpy_file.seek(0)
new_circuit = load(qpy_file)[0]
self.assertEqual(qc, new_circuit)
self.assertDeprecatedBitProperties(qc, new_circuit)
def test_controlled_gate_open_controls(self):
"""Test a controlled gate with open controls round-trips exactly."""
qc = QuantumCircuit(3)
controlled_gate = DCXGate().control(1, ctrl_state=0)
qc.append(controlled_gate, [0, 1, 2])
qpy_file = io.BytesIO()
dump(qc, qpy_file)
qpy_file.seek(0)
new_circuit = load(qpy_file)[0]
self.assertEqual(qc, new_circuit)
self.assertDeprecatedBitProperties(qc, new_circuit)
def test_nested_controlled_gate(self):
"""Test a custom nested controlled gate."""
custom_gate = Gate("black_box", 1, [])
custom_definition = QuantumCircuit(1)
custom_definition.h(0)
custom_definition.rz(1.5, 0)
custom_definition.sdg(0)
custom_gate.definition = custom_definition
qc = QuantumCircuit(3)
qc.append(custom_gate, [0])
controlled_gate = custom_gate.control(2)
qc.append(controlled_gate, [0, 1, 2])
qpy_file = io.BytesIO()
dump(qc, qpy_file)
qpy_file.seek(0)
new_circ = load(qpy_file)[0]
self.assertEqual(qc, new_circ)
self.assertEqual(qc.decompose(), new_circ.decompose())
self.assertDeprecatedBitProperties(qc, new_circ)
def test_open_controlled_gate(self):
"""Test an open control is preserved across serialization."""
qc = QuantumCircuit(2)
qc.cx(0, 1, ctrl_state=0)
with io.BytesIO() as fd:
dump(qc, fd)
fd.seek(0)
new_circ = load(fd)[0]
self.assertEqual(qc, new_circ)
self.assertEqual(qc.data[0].operation.ctrl_state, new_circ.data[0].operation.ctrl_state)
self.assertDeprecatedBitProperties(qc, new_circ)
def test_standard_control_gates(self):
"""Test standard library controlled gates."""
qc = QuantumCircuit(6)
mcu1_gate = MCU1Gate(np.pi, 2)
mcx_gate = MCXGate(5)
mcx_gray_gate = MCXGrayCode(5)
mcx_recursive_gate = MCXRecursive(4)
mcx_vchain_gate = MCXVChain(3)
qc.append(mcu1_gate, [0, 2, 1])
qc.append(mcx_gate, list(range(0, 6)))
qc.append(mcx_gray_gate, list(range(0, 6)))
qc.append(mcx_recursive_gate, list(range(0, 5)))
qc.append(mcx_vchain_gate, list(range(0, 5)))
qc.mcp(np.pi, [0, 2], 1)
qc.mct([0, 2], 1)
qc.mcx([0, 2], 1)
qc.measure_all()
qpy_file = io.BytesIO()
dump(qc, qpy_file)
qpy_file.seek(0)
new_circuit = load(qpy_file)[0]
self.assertEqual(qc, new_circuit)
self.assertDeprecatedBitProperties(qc, new_circuit)
def test_controlled_gate_subclass_custom_definition(self):
"""Test controlled gate with overloaded definition.
Reproduce from: https://github.com/Qiskit/qiskit-terra/issues/8794
"""
class CustomCXGate(ControlledGate):
"""Custom CX with overloaded _define."""
def __init__(self, label=None, ctrl_state=None):
super().__init__(
"cx", 2, [], label, num_ctrl_qubits=1, ctrl_state=ctrl_state, base_gate=XGate()
)
def _define(self) -> None:
qc = QuantumCircuit(2, name=self.name)
qc.cx(0, 1)
self.definition = qc
qc = QuantumCircuit(2)
qc.append(CustomCXGate(), [0, 1])
qpy_file = io.BytesIO()
dump(qc, qpy_file)
qpy_file.seek(0)
new_circ = load(qpy_file)[0]
self.assertEqual(qc, new_circ)
self.assertEqual(qc.decompose(), new_circ.decompose())
self.assertDeprecatedBitProperties(qc, new_circ)
def test_load_with_loose_bits(self):
"""Test that loading from a circuit with loose bits works."""
qc = QuantumCircuit([Qubit(), Qubit(), Clbit()])
qpy_file = io.BytesIO()
dump(qc, qpy_file)
qpy_file.seek(0)
new_circuit = load(qpy_file)[0]
self.assertEqual(tuple(new_circuit.qregs), ())
self.assertEqual(tuple(new_circuit.cregs), ())
self.assertEqual(qc, new_circuit)
self.assertDeprecatedBitProperties(qc, new_circuit)
def test_load_with_loose_bits_and_registers(self):
"""Test that loading from a circuit with loose bits and registers works."""
qc = QuantumCircuit(QuantumRegister(3), ClassicalRegister(1), [Clbit()])
qpy_file = io.BytesIO()
dump(qc, qpy_file)
qpy_file.seek(0)
new_circuit = load(qpy_file)[0]
self.assertEqual(qc, new_circuit)
self.assertDeprecatedBitProperties(qc, new_circuit)
def test_registers_after_loose_bits(self):
"""Test that a circuit whose registers appear after some loose bits roundtrips. Regression
test of gh-9094."""
qc = QuantumCircuit()
qc.add_bits([Qubit(), Clbit()])
qc.add_register(QuantumRegister(2, name="q1"))
qc.add_register(ClassicalRegister(2, name="c1"))
with io.BytesIO() as fptr:
dump(qc, fptr)
fptr.seek(0)
new_circuit = load(fptr)[0]
self.assertEqual(qc, new_circuit)
self.assertDeprecatedBitProperties(qc, new_circuit)
def test_roundtrip_empty_register(self):
"""Test that empty registers round-trip correctly."""
qc = QuantumCircuit(QuantumRegister(0), ClassicalRegister(0))
with io.BytesIO() as fptr:
dump(qc, fptr)
fptr.seek(0)
new_circuit = load(fptr)[0]
self.assertEqual(qc, new_circuit)
self.assertEqual(qc.qregs, new_circuit.qregs)
self.assertEqual(qc.cregs, new_circuit.cregs)
self.assertDeprecatedBitProperties(qc, new_circuit)
def test_roundtrip_several_empty_registers(self):
"""Test that several empty registers round-trip correctly."""
qc = QuantumCircuit(
QuantumRegister(0, "a"),
QuantumRegister(0, "b"),
ClassicalRegister(0, "c"),
ClassicalRegister(0, "d"),
)
with io.BytesIO() as fptr:
dump(qc, fptr)
fptr.seek(0)
new_circuit = load(fptr)[0]
self.assertEqual(qc, new_circuit)
self.assertEqual(qc.qregs, new_circuit.qregs)
self.assertEqual(qc.cregs, new_circuit.cregs)
self.assertDeprecatedBitProperties(qc, new_circuit)
def test_roundtrip_empty_registers_with_loose_bits(self):
"""Test that empty registers still round-trip correctly in the presence of loose bits."""
loose = [Qubit(), Clbit()]
qc = QuantumCircuit(loose, QuantumRegister(0), ClassicalRegister(0))
with io.BytesIO() as fptr:
dump(qc, fptr)
fptr.seek(0)
new_circuit = load(fptr)[0]
self.assertEqual(qc, new_circuit)
self.assertEqual(qc.qregs, new_circuit.qregs)
self.assertEqual(qc.cregs, new_circuit.cregs)
qc = QuantumCircuit(QuantumRegister(0), ClassicalRegister(0), loose)
with io.BytesIO() as fptr:
dump(qc, fptr)
fptr.seek(0)
new_circuit = load(fptr)[0]
self.assertEqual(qc, new_circuit)
self.assertEqual(qc.qregs, new_circuit.qregs)
self.assertEqual(qc.cregs, new_circuit.cregs)
self.assertDeprecatedBitProperties(qc, new_circuit)
def test_incomplete_owned_bits(self):
"""Test that a circuit that contains only some bits that are owned by a register are
correctly roundtripped."""
reg = QuantumRegister(5, "q")
qc = QuantumCircuit(reg[:3])
qc.ccx(0, 1, 2)
with io.BytesIO() as fptr:
dump(qc, fptr)
fptr.seek(0)
new_circuit = load(fptr)[0]
self.assertEqual(qc, new_circuit)
self.assertDeprecatedBitProperties(qc, new_circuit)
def test_diagonal_gate(self):
"""Test that a `DiagonalGate` successfully roundtrips."""
qc = QuantumCircuit(2)
qc.diagonal([1, -1, -1, 1], [0, 1])
with io.BytesIO() as fptr:
dump(qc, fptr)
fptr.seek(0)
new_circuit = load(fptr)[0]
# DiagonalGate (and a bunch of the qiskit.extensions gates) have non-deterministic
# definitions with regard to internal instruction names, so cannot be directly compared for
# equality.
self.assertIs(type(qc.data[0].operation), type(new_circuit.data[0].operation))
self.assertEqual(qc.data[0].operation.params, new_circuit.data[0].operation.params)
self.assertDeprecatedBitProperties(qc, new_circuit)
@ddt.data(QuantumCircuit.if_test, QuantumCircuit.while_loop)
def test_if_else_while_expr_simple(self, control_flow):
"""Test that `IfElseOp` and `WhileLoopOp` can have an `Expr` node as their `condition`, and
that this round-trips through QPY."""
body = QuantumCircuit(1)
qr = QuantumRegister(2, "q1")
cr = ClassicalRegister(2, "c1")
qc = QuantumCircuit(qr, cr)
control_flow(qc, expr.equal(cr, 3), body.copy(), [0], [])
control_flow(qc, expr.lift(qc.clbits[0]), body.copy(), [0], [])
with io.BytesIO() as fptr:
dump(qc, fptr)
fptr.seek(0)
new_circuit = load(fptr)[0]
self.assertEqual(qc, new_circuit)
self.assertEqual(qc.qregs, new_circuit.qregs)
self.assertEqual(qc.cregs, new_circuit.cregs)
self.assertDeprecatedBitProperties(qc, new_circuit)
@ddt.data(QuantumCircuit.if_test, QuantumCircuit.while_loop)
def test_if_else_while_expr_nested(self, control_flow):
"""Test that `IfElseOp` and `WhileLoopOp` can have an `Expr` node as their `condition`, and
that this round-trips through QPY."""
inner = QuantumCircuit(1)
outer = QuantumCircuit(1, 1)
control_flow(outer, expr.lift(outer.clbits[0]), inner.copy(), [0], [])
qr = QuantumRegister(2, "q1")
cr = ClassicalRegister(2, "c1")
qc = QuantumCircuit(qr, cr)
control_flow(qc, expr.equal(cr, 3), outer.copy(), [1], [1])
with io.BytesIO() as fptr:
dump(qc, fptr)
fptr.seek(0)
new_circuit = load(fptr)[0]
self.assertEqual(qc, new_circuit)
self.assertEqual(qc.qregs, new_circuit.qregs)
self.assertEqual(qc.cregs, new_circuit.cregs)
self.assertDeprecatedBitProperties(qc, new_circuit)
def test_if_else_expr_stress(self):
"""Stress-test the `Expr` handling in the condition of an `IfElseOp`. This should hit on
every aspect of the `Expr` tree."""
inner = QuantumCircuit(1)
inner.x(0)
outer = QuantumCircuit(1, 1)
outer.if_test(expr.cast(outer.clbits[0], types.Bool()), inner.copy(), [0], [])
# Register whose size is deliberately larger that one byte.
cr1 = ClassicalRegister(256, "c1")
cr2 = ClassicalRegister(4, "c2")
loose = Clbit()
qc = QuantumCircuit([Qubit(), Qubit(), loose], cr1, cr2)
qc.rz(1.0, 0)
qc.if_test(
expr.logic_and(
expr.logic_and(
expr.logic_or(
expr.cast(
expr.less(expr.bit_and(cr1, 0x0F), expr.bit_not(cr1)),
types.Bool(),
),
expr.cast(
expr.less_equal(expr.bit_or(cr2, 7), expr.bit_xor(cr2, 7)),
types.Bool(),
),
),
expr.logic_and(
expr.logic_or(expr.equal(cr2, 2), expr.logic_not(expr.not_equal(cr2, 3))),
expr.logic_or(
expr.greater(cr2, 3),
expr.greater_equal(cr2, 3),
),
),
),
expr.logic_not(loose),
),
outer.copy(),
[1],
[0],
)
qc.rz(1.0, 0)
with io.BytesIO() as fptr:
dump(qc, fptr)
fptr.seek(0)
new_circuit = load(fptr)[0]
self.assertEqual(qc, new_circuit)
self.assertEqual(qc.qregs, new_circuit.qregs)
self.assertEqual(qc.cregs, new_circuit.cregs)
self.assertDeprecatedBitProperties(qc, new_circuit)
def test_switch_expr_simple(self):
"""Test that `SwitchCaseOp` can have an `Expr` node as its `target`, and that this
round-trips through QPY."""
body = QuantumCircuit(1)
qr = QuantumRegister(2, "q1")
cr = ClassicalRegister(2, "c1")
qc = QuantumCircuit(qr, cr)
qc.switch(expr.bit_and(cr, 3), [(1, body.copy())], [0], [])
qc.switch(expr.logic_not(qc.clbits[0]), [(False, body.copy())], [0], [])
with io.BytesIO() as fptr:
dump(qc, fptr)
fptr.seek(0)
new_circuit = load(fptr)[0]
self.assertEqual(qc, new_circuit)
self.assertEqual(qc.qregs, new_circuit.qregs)
self.assertEqual(qc.cregs, new_circuit.cregs)
self.assertDeprecatedBitProperties(qc, new_circuit)
def test_switch_expr_nested(self):
"""Test that `SwitchCaseOp` can have an `Expr` node as its `target`, and that this
round-trips through QPY."""
inner = QuantumCircuit(1)
outer = QuantumCircuit(1, 1)
outer.switch(expr.lift(outer.clbits[0]), [(False, inner.copy())], [0], [])
qr = QuantumRegister(2, "q1")
cr = ClassicalRegister(2, "c1")
qc = QuantumCircuit(qr, cr)
qc.switch(expr.lift(cr), [(3, outer.copy())], [1], [1])
with io.BytesIO() as fptr:
dump(qc, fptr)
fptr.seek(0)
new_circuit = load(fptr)[0]
self.assertEqual(qc, new_circuit)
self.assertEqual(qc.qregs, new_circuit.qregs)
self.assertEqual(qc.cregs, new_circuit.cregs)
self.assertDeprecatedBitProperties(qc, new_circuit)
def test_switch_expr_stress(self):
"""Stress-test the `Expr` handling in the target of a `SwitchCaseOp`. This should hit on
every aspect of the `Expr` tree."""
inner = QuantumCircuit(1)
inner.x(0)
outer = QuantumCircuit(1, 1)
outer.switch(expr.cast(outer.clbits[0], types.Bool()), [(True, inner.copy())], [0], [])
# Register whose size is deliberately larger that one byte.
cr1 = ClassicalRegister(256, "c1")
cr2 = ClassicalRegister(4, "c2")
loose = Clbit()
qc = QuantumCircuit([Qubit(), Qubit(), loose], cr1, cr2)
qc.rz(1.0, 0)
qc.switch(
expr.logic_and(
expr.logic_and(
expr.logic_or(
expr.cast(
expr.less(expr.bit_and(cr1, 0x0F), expr.bit_not(cr1)),
types.Bool(),
),
expr.cast(
expr.less_equal(expr.bit_or(cr2, 7), expr.bit_xor(cr2, 7)),
types.Bool(),
),
),
expr.logic_and(
expr.logic_or(expr.equal(cr2, 2), expr.logic_not(expr.not_equal(cr2, 3))),
expr.logic_or(
expr.greater(cr2, 3),
expr.greater_equal(cr2, 3),
),
),
),
expr.logic_not(loose),
),
[(False, outer.copy())],
[1],
[0],
)
qc.rz(1.0, 0)
with io.BytesIO() as fptr:
dump(qc, fptr)
fptr.seek(0)
new_circuit = load(fptr)[0]
self.assertEqual(qc, new_circuit)
self.assertEqual(qc.qregs, new_circuit.qregs)
self.assertEqual(qc.cregs, new_circuit.cregs)
self.assertDeprecatedBitProperties(qc, new_circuit)
def test_multiple_nested_control_custom_definitions(self):
"""Test that circuits with multiple controlled custom gates that in turn depend on custom
gates can be exported successfully when there are several such gates in the outer circuit.
See gh-9746"""
inner_1 = QuantumCircuit(1, name="inner_1")
inner_1.x(0)
inner_2 = QuantumCircuit(1, name="inner_2")
inner_2.y(0)
outer_1 = QuantumCircuit(1, name="outer_1")
outer_1.append(inner_1.to_gate(), [0], [])
outer_2 = QuantumCircuit(1, name="outer_2")
outer_2.append(inner_2.to_gate(), [0], [])
qc = QuantumCircuit(2)
qc.append(outer_1.to_gate().control(1), [0, 1], [])
qc.append(outer_2.to_gate().control(1), [0, 1], [])
with io.BytesIO() as fptr:
dump(qc, fptr)
fptr.seek(0)
new_circuit = load(fptr)[0]
self.assertEqual(qc, new_circuit)
self.assertDeprecatedBitProperties(qc, new_circuit)
def test_qpy_deprecation(self):
"""Test the old import path's deprecations fire."""
with self.assertWarnsRegex(DeprecationWarning, "is deprecated"):
# pylint: disable=no-name-in-module, unused-import, redefined-outer-name, reimported
from qiskit.circuit.qpy_serialization import dump, load
|
https://github.com/xtophe388/QISKIT
|
xtophe388
|
from IPython.display import Image
Image(filename="error_correction_files/error_correction_1_0.png", width=450, height=300)
Image(filename="error_correction_files/error_correction_3_0.png", width=450, height=300)
Image(filename="error_correction_files/error_correction_5_0.png", width=450, height=300)
Image(filename="error_correction_files/error_correction_7_0.png", width=450, height=300)
import sys
if sys.version_info < (3,5):
raise Exception('Please use Python version 3.5 or greater.')
from qiskit import QuantumProgram
#import Qconfig
# Needed to visualize quantum circuits
import os
import shutil
from qiskit.tools.visualization import latex_drawer
import pdf2image
from IPython.display import Image
# Initialize quantum program
qp = QuantumProgram()
#qp.set_api(Qconfig.APItoken, Qconfig.config['url']) # set the APIToken and API url
# Circuit requires 5 qubits and 5 classical bits
qr = qp.create_quantum_register('qr', 5)
cr = qp.create_classical_register('cr',5)
qc = qp.create_circuit('Circuit', [qr], [cr])
circuit = qp.get_circuit('Circuit')
# get the Quantum Register by Name
quantum_r = qp.get_quantum_register('qr')
# get the Classical Register by Name
classical_r = qp.get_classical_register('cr')
def circuitImage(circuit, filename, basis="u1,u2,u3,cx"):
"""
Obtain the circuit in image format
Note: Requires pdflatex installed (to compile Latex)
Note: Required pdf2image Python package (to display pdf as image)
"""
tmpdir='tmp/'
if not os.path.exists(tmpdir):
os.makedirs(tmpdir)
latex_drawer(circuit, tmpdir+filename+".tex", basis=basis)
os.system("pdflatex -output-directory {} {}".format(tmpdir, filename+".tex"))
images = pdf2image.convert_from_path(tmpdir+filename+".pdf")
shutil.rmtree(tmpdir)
return images[0]
def toffoli(circuit,quantum_r,a,b,c):
"""
Creates toffoli gate in existing circuit with a and b
as the test points and c as the affected point
"""
circuit.iden(quantum_r[c])
circuit.h(quantum_r[c])
circuit.cx(quantum_r[b],quantum_r[c])
circuit.tdg(quantum_r[c])
circuit.cx(quantum_r[a],quantum_r[c])
circuit.t(quantum_r[c])
circuit.cx(quantum_r[b],quantum_r[c])
circuit.tdg(quantum_r[c])
circuit.cx(quantum_r[a],quantum_r[c])
circuit.t(quantum_r[c])
circuit.t(quantum_r[b])
circuit.h(quantum_r[c])
circuit.cx(quantum_r[b],quantum_r[c])
circuit.h(quantum_r[c])
circuit.h(quantum_r[b])
circuit.cx(quantum_r[b],quantum_r[c])
circuit.h(quantum_r[c])
circuit.h(quantum_r[b])
circuit.cx(quantum_r[b],quantum_r[c])
circuit.cx(quantum_r[a],quantum_r[c])
circuit.t(quantum_r[a])
circuit.tdg(quantum_r[c])
circuit.cx(quantum_r[a],quantum_r[c])
circuit.cx(quantum_r[b],quantum_r[c])
circuit.cx(quantum_r[c],quantum_r[b])
circuit.cx(quantum_r[b],quantum_r[c])
#circuit.x(quantum_r[2])
circuit.x(quantum_r[3])
circuit.x(quantum_r[4])
circuit.cx(quantum_r[2],quantum_r[0])
circuit.cx(quantum_r[3],quantum_r[0])
circuit.cx(quantum_r[3],quantum_r[1])
circuit.cx(quantum_r[4],quantum_r[1])
circuit.cx(quantum_r[0],quantum_r[2])
circuit.cx(quantum_r[1],quantum_r[4])
toffoli(circuit,quantum_r,0,1,2)
toffoli(circuit,quantum_r,0,1,3)
toffoli(circuit,quantum_r,0,1,4)
circuit.measure(quantum_r[0], classical_r[0])
circuit.measure(quantum_r[1], classical_r[1])
circuit.measure(quantum_r[2], classical_r[2])
circuit.measure(quantum_r[3], classical_r[3])
circuit.measure(quantum_r[4], classical_r[4])
"""
Image of the final circuit. Becuase it contains three Toffoli gates where
each gate is made up of many basis gates, this circuit is unfortunately
very hard to visualize.
"""
basis="u1,u2,u3,cx,x,y,z,h,s,t,rx,ry,rz"
circuitImage(circuit,'circuit',basis)
#!!! for better visibility plot using the now built-in code
from qiskit.tools.visualization import circuit_drawer
circuit_drawer(circuit)
"""
Results of the computation. Note that the states of the five qubits
from up to down in the circuit are shown from right to left in the result.
"""
backend = 'ibmqx_qasm_simulator'
circuits = ['Circuit'] # Group of circuits to execute
qobj=qp.compile(circuits, backend, shots=1024, max_credits=3)
result = qp.run(qobj, wait=2, timeout=240)
print(result.get_counts('Circuit'))
Image(filename="error_correction_files/error_correction_27_0.png", width=250, height=300)
Image(filename="error_correction_files/error_correction_30_0.png", width=450, height=300)
Image(filename="error_correction_files/error_correction_33_0.png", width=450, height=300)
Image(filename="error_correction_files/error_correction_36_0.png", width=450, height=300)
Image(filename="error_correction_files/error_correction_39_0.png", width=900, height=600)
Image(filename="error_correction_files/error_correction_40_0.png", width=900, height=600)
Image(filename="error_correction_files/error_correction_43_0.png", width=900, height=450)
|
https://github.com/GabrielPontolillo/Quantum_Algorithm_Implementations
|
GabrielPontolillo
|
from scipy.stats import kruskal
import pandas as pd
import numpy as np
#if p value less than alpha reject
qiskit_data = np.concatenate((np.full(4925, 'z00'), np.full(5075, 'z11'), np.full(5016, 'x00'),
np.full(4984, 'x11'), np.full(4898, 'y10'), np.full(5102, 'y01')))
print(qiskit_data)
cirq_data = np.concatenate((np.full(5043, 'z00'), np.full(4957, 'z11'), np.full(5041, 'x00'),
np.full(4959, 'x11'), np.full(4971, 'y10'), np.full(5029, 'y01')))
print(cirq_data)
qs_data = np.concatenate((np.full(4981, 'z00'), np.full(5019, 'z11'), np.full(4994, 'x00'),
np.full(5006, 'x11'), np.full(4956, 'y10'), np.full(5044, 'y01')))
print(qs_data)
kruskal(qiskit_data, cirq_data, qs_data)
qiskit_data = np.concatenate((np.full(4957, 'z10'), np.full(5043, 'z01'), np.full(5039, 'x10'),
np.full(4961, 'x01'), np.full(5059, 'y10'), np.full(4941, 'y01')))
print(qiskit_data)
cirq_data = np.concatenate((np.full(4946, 'z10'), np.full(5054, 'z01'), np.full(4926, 'x10'),
np.full(5074, 'x01'), np.full(5078, 'y10'), np.full(4922, 'y01')))
print(cirq_data)
qs_data = np.concatenate((np.full(5012, 'z10'), np.full(4988, 'z01'), np.full(4990, 'x10'),
np.full(5010, 'x01'), np.full(4956, 'y10'), np.full(5044, 'y01')))
print(qs_data)
kruskal(qiskit_data, cirq_data, qs_data)
qiskit_data = np.concatenate((np.full(4958, 'z00'), np.full(5042, 'z11'), np.full(4950, 'x10'),
np.full(5050, 'x01'), np.full(5029, 'y00'), np.full(4971, 'y11')))
print(qiskit_data)
cirq_data = np.concatenate((np.full(5063, 'z00'), np.full(4937, 'z11'), np.full(5001, 'x10'),
np.full(4999, 'x01'), np.full(4921, 'y00'), np.full(5079, 'y11')))
print(cirq_data)
qs_data = np.concatenate((np.full(4993, 'z00'), np.full(5007, 'z11'), np.full(5058, 'x10'),
np.full(4942, 'x01'), np.full(4998, 'y00'), np.full(5002, 'y11')))
print(qs_data)
kruskal(qiskit_data, cirq_data, qs_data)
qiskit_data = np.concatenate((np.full(10000, 'z00'), np.full(2545, 'x00'), np.full(2486, 'x01'),
np.full(2458, 'x10'), np.full(2511, 'x11'), np.full(2479, 'y00'),
np.full(2436, 'y01'), np.full(2583, 'y10'), np.full(2502, 'y11')))
print(qiskit_data)
cirq_data = np.concatenate((np.full(10000, 'z00'), np.full(2431, 'x00'), np.full(2506, 'x01'),
np.full(2498, 'x10'), np.full(2565, 'x11'), np.full(2436, 'y00'),
np.full(2563, 'y01'), np.full(2538, 'y10'), np.full(2463, 'y11')))
print(cirq_data)
qs_data = np.concatenate((np.full(10000, 'z00'), np.full(2512, 'x00'), np.full(2528, 'x01'),
np.full(2529, 'x10'), np.full(2431, 'x11'), np.full(2560, 'y00'),
np.full(2524, 'y01'), np.full(2451, 'y10'), np.full(2465, 'y11')))
print(qs_data)
kruskal(qiskit_data, cirq_data, qs_data)
qiskit_data = np.concatenate((np.full(10000, 'z01'), np.full(2528, 'x00'), np.full(2475, 'x01'),
np.full(2493, 'x10'), np.full(2504, 'x11'), np.full(2502, 'y00'),
np.full(2569, 'y01'), np.full(2474, 'y10'), np.full(2455, 'y11')))
print(qiskit_data)
cirq_data = np.concatenate((np.full(10000, 'z01'), np.full(2497, 'x00'), np.full(2525, 'x01'),
np.full(2512, 'x10'), np.full(2466, 'x11'), np.full(2487, 'y00'),
np.full(2484, 'y01'), np.full(2507, 'y10'), np.full(2522, 'y11')))
print(cirq_data)
qs_data = np.concatenate((np.full(10000, 'z01'), np.full(2551, 'x00'), np.full(2504, 'x01'),
np.full(2490, 'x10'), np.full(2455, 'x11'), np.full(2528, 'y00'),
np.full(2494, 'y01'), np.full(2506, 'y10'), np.full(2472, 'y11')))
print(qs_data)
kruskal(qiskit_data, cirq_data, qs_data)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, transpile
from qiskit.visualization import plot_circuit_layout
from qiskit.providers.fake_provider import FakeVigo
backend = FakeVigo()
ghz = QuantumCircuit(3, 3)
ghz.h(0)
ghz.cx(0,range(1,3))
ghz.barrier()
ghz.measure(range(3), range(3))
new_circ_lv0 = transpile(ghz, backend=backend, optimization_level=0)
plot_circuit_layout(new_circ_lv0, backend)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/swe-train/qiskit__qiskit
|
swe-train
|
# 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.
"""Tests for qiskit/tools/parallel"""
import os
import time
from unittest.mock import patch
from qiskit.tools.parallel import get_platform_parallel_default, parallel_map
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.pulse import Schedule
from qiskit.test import QiskitTestCase
def _parfunc(x):
"""Function for testing parallel_map"""
time.sleep(1)
return x
def _build_simple_circuit(_):
qreg = QuantumRegister(2)
creg = ClassicalRegister(2)
qc = QuantumCircuit(qreg, creg)
return qc
def _build_simple_schedule(_):
return Schedule()
class TestGetPlatformParallelDefault(QiskitTestCase):
"""Tests get_parallel_default_for_platform."""
def test_windows_parallel_default(self):
"""Verifies the parallel default for Windows."""
with patch("sys.platform", "win32"):
parallel_default = get_platform_parallel_default()
self.assertEqual(parallel_default, False)
def test_mac_os_unsupported_version_parallel_default(self):
"""Verifies the parallel default for macOS."""
with patch("sys.platform", "darwin"):
with patch("sys.version_info", (3, 8, 0, "final", 0)):
parallel_default = get_platform_parallel_default()
self.assertEqual(parallel_default, False)
def test_other_os_parallel_default(self):
"""Verifies the parallel default for Linux and other OSes."""
with patch("sys.platform", "linux"):
parallel_default = get_platform_parallel_default()
self.assertEqual(parallel_default, True)
class TestParallel(QiskitTestCase):
"""A class for testing parallel_map functionality."""
def test_parallel_env_flag(self):
"""Verify parallel env flag is set"""
self.assertEqual(os.getenv("QISKIT_IN_PARALLEL", None), "FALSE")
def test_parallel(self):
"""Test parallel_map"""
ans = parallel_map(_parfunc, list(range(10)))
self.assertEqual(ans, list(range(10)))
def test_parallel_circuit_names(self):
"""Verify unique circuit names in parallel"""
out_circs = parallel_map(_build_simple_circuit, list(range(10)))
names = [circ.name for circ in out_circs]
self.assertEqual(len(names), len(set(names)))
def test_parallel_schedule_names(self):
"""Verify unique schedule names in parallel"""
out_schedules = parallel_map(_build_simple_schedule, list(range(10)))
names = [schedule.name for schedule in out_schedules]
self.assertEqual(len(names), len(set(names)))
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, transpile
from qiskit.visualization import plot_circuit_layout
from qiskit.providers.fake_provider import FakeVigo
backend = FakeVigo()
ghz = QuantumCircuit(3, 3)
ghz.h(0)
ghz.cx(0,range(1,3))
ghz.barrier()
ghz.measure(range(3), range(3))
ghz.draw(output='mpl')
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 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.
"""The Variational Quantum Time Evolution Interface"""
from __future__ import annotations
from abc import ABC
from collections.abc import Mapping, Callable, Sequence
from typing import Type
import numpy as np
from scipy.integrate import OdeSolver
from qiskit import QuantumCircuit
from qiskit.circuit import Parameter
from qiskit.opflow import PauliSumOp
from qiskit.primitives import BaseEstimator
from qiskit.quantum_info.operators.base_operator import BaseOperator
from .solvers.ode.forward_euler_solver import ForwardEulerSolver
from .solvers.ode.ode_function_factory import OdeFunctionFactory
from .solvers.ode.var_qte_ode_solver import VarQTEOdeSolver
from .solvers.var_qte_linear_solver import VarQTELinearSolver
from .variational_principles.variational_principle import VariationalPrinciple
from .var_qte_result import VarQTEResult
from ..time_evolution_problem import TimeEvolutionProblem
from ...observables_evaluator import estimate_observables
class VarQTE(ABC):
"""Variational Quantum Time Evolution.
Algorithms that use variational principles to compute a time evolution for a given
Hermitian operator (Hamiltonian) and a quantum state prepared by a parameterized quantum
circuit.
Attributes:
ansatz (QuantumCircuit): Ansatz to be used for variational time evolution.
initial_parameters (Mapping[Parameter, float] | Sequence[float]): Initial
parameter values for an ansatz.
variational_principle (VariationalPrinciple): Variational Principle to be used.
estimator (BaseEstimator): An estimator primitive used for calculating expectation
values of ``TimeEvolutionProblem.aux_operators``.
ode_solver(Type[OdeSolver] | str): ODE solver callable that implements a SciPy
``OdeSolver`` interface or a string indicating a valid method offered by SciPy.
lse_solver (Callable[[np.ndarray, np.ndarray], np.ndarray] | None): Linear system
of equations solver callable. It accepts ``A`` and ``b`` to solve ``Ax=b``
and returns ``x``.
num_timesteps (int | None): The number of timesteps to take. If None, it is
automatically selected to achieve a timestep of approximately 0.01. Only
relevant in case of the ``ForwardEulerSolver``.
imag_part_tol (float): Allowed value of an imaginary part that can be neglected if no
imaginary part is expected.
num_instability_tol (float): The amount of negative value that is allowed to be
rounded up to 0 for quantities that are expected to be
non-negative.
References:
[1] Benjamin, Simon C. et al. (2019).
Theory of variational quantum simulation. `<https://doi.org/10.22331/q-2019-10-07-191>`_
"""
def __init__(
self,
ansatz: QuantumCircuit,
initial_parameters: Mapping[Parameter, float] | Sequence[float],
variational_principle: VariationalPrinciple,
estimator: BaseEstimator,
ode_solver: Type[OdeSolver] | str = ForwardEulerSolver,
lse_solver: Callable[[np.ndarray, np.ndarray], np.ndarray] | None = None,
num_timesteps: int | None = None,
imag_part_tol: float = 1e-7,
num_instability_tol: float = 1e-7,
) -> None:
r"""
Args:
ansatz: Ansatz to be used for variational time evolution.
initial_parameters: Initial parameter values for an ansatz.
variational_principle: Variational Principle to be used.
estimator: An estimator primitive used for calculating expectation values of
TimeEvolutionProblem.aux_operators.
ode_solver: ODE solver callable that implements a SciPy ``OdeSolver`` interface or a
string indicating a valid method offered by SciPy.
lse_solver: Linear system of equations solver callable. It accepts ``A`` and ``b`` to
solve ``Ax=b`` and returns ``x``.
num_timesteps: The number of timesteps to take. If None, it is
automatically selected to achieve a timestep of approximately 0.01. Only
relevant in case of the ``ForwardEulerSolver``.
imag_part_tol: Allowed value of an imaginary part that can be neglected if no
imaginary part is expected.
num_instability_tol: The amount of negative value that is allowed to be
rounded up to 0 for quantities that are expected to be
non-negative.
"""
super().__init__()
self.ansatz = ansatz
self.initial_parameters = initial_parameters
self.variational_principle = variational_principle
self.estimator = estimator
self.num_timesteps = num_timesteps
self.lse_solver = lse_solver
self.ode_solver = ode_solver
self.imag_part_tol = imag_part_tol
self.num_instability_tol = num_instability_tol
# OdeFunction abstraction kept for potential extensions - unclear at the moment;
# currently hidden from the user
self._ode_function_factory = OdeFunctionFactory()
def evolve(self, evolution_problem: TimeEvolutionProblem) -> VarQTEResult:
"""Apply Variational Quantum Time Evolution to the given operator.
Args:
evolution_problem: Instance defining an evolution problem.
Returns:
Result of the evolution which includes a quantum circuit with bound parameters as an
evolved state and, if provided, observables evaluated on the evolved state.
Raises:
ValueError: If ``initial_state`` is included in the ``evolution_problem``.
"""
self._validate_aux_ops(evolution_problem)
if evolution_problem.initial_state is not None:
raise ValueError(
"An initial_state was provided to the TimeEvolutionProblem but this is not "
"supported by VarQTE. Please remove this state from the problem definition "
"and set VarQTE.initial_parameters with the corresponding initial parameter "
"values instead."
)
init_state_param_dict = self._create_init_state_param_dict(
self.initial_parameters, self.ansatz.parameters
)
# unwrap PauliSumOp (in the future this will be deprecated)
if isinstance(evolution_problem.hamiltonian, PauliSumOp):
hamiltonian = (
evolution_problem.hamiltonian.primitive * evolution_problem.hamiltonian.coeff
)
else:
hamiltonian = evolution_problem.hamiltonian
evolved_state, param_values, time_points = self._evolve(
init_state_param_dict,
hamiltonian,
evolution_problem.time,
evolution_problem.t_param,
)
observables = []
if evolution_problem.aux_operators is not None:
for values in param_values:
# cannot batch evaluation because estimate_observables
# only accepts single circuits
evol_state = self.ansatz.assign_parameters(
dict(zip(init_state_param_dict.keys(), values))
)
observable = estimate_observables(
self.estimator,
evol_state,
evolution_problem.aux_operators,
)
observables.append(observable)
# TODO: deprecate returning evaluated_aux_ops.
# As these are the observables for the last time step.
evaluated_aux_ops = observables[-1] if len(observables) > 0 else None
return VarQTEResult(
evolved_state, evaluated_aux_ops, observables, time_points, param_values
)
def _evolve(
self,
init_state_param_dict: Mapping[Parameter, float],
hamiltonian: BaseOperator,
time: float,
t_param: Parameter | None = None,
) -> tuple[QuantumCircuit | None, Sequence[Sequence[float]], Sequence[float]]:
r"""
Helper method for performing time evolution. Works both for imaginary and real case.
Args:
init_state_param_dict: Parameter dictionary with initial values for a given
parametrized state/ansatz.
hamiltonian: Operator used for Variational Quantum Time Evolution (VarQTE).
time: Total time of evolution.
t_param: Time parameter in case of a time-dependent Hamiltonian.
Returns:
Result of the evolution which is a quantum circuit with bound parameters as an
evolved state.
"""
init_state_parameters = list(init_state_param_dict.keys())
init_state_parameter_values = list(init_state_param_dict.values())
linear_solver = VarQTELinearSolver(
self.variational_principle,
hamiltonian,
self.ansatz,
init_state_parameters,
t_param,
self.lse_solver,
self.imag_part_tol,
)
# Convert the operator that holds the Hamiltonian and ansatz into a NaturalGradient operator
ode_function = self._ode_function_factory._build(
linear_solver, init_state_param_dict, t_param
)
ode_solver = VarQTEOdeSolver(
init_state_parameter_values, ode_function, self.ode_solver, self.num_timesteps
)
final_param_values, param_values, time_points = ode_solver.run(time)
param_dict_from_ode = dict(zip(init_state_parameters, final_param_values))
return self.ansatz.assign_parameters(param_dict_from_ode), param_values, time_points
@staticmethod
def _create_init_state_param_dict(
param_values: Mapping[Parameter, float] | Sequence[float],
init_state_parameters: Sequence[Parameter],
) -> Mapping[Parameter, float]:
r"""
If ``param_values`` is a dictionary, it looks for parameters present in an initial state
(an ansatz) in a ``param_values``. Based on that, it creates a new dictionary containing
only parameters present in an initial state and their respective values.
If ``param_values`` is a list of values, it creates a new dictionary containing
parameters present in an initial state and their respective values.
Args:
param_values: Dictionary which relates parameter values to the parameters or a list of
values.
init_state_parameters: Parameters present in a quantum state.
Returns:
Dictionary that maps parameters of an initial state to some values.
Raises:
ValueError: If the dictionary with parameter values provided does not include all
parameters present in the initial state or if the list of values provided is not the
same length as the list of parameters.
TypeError: If an unsupported type of ``param_values`` provided.
"""
if isinstance(param_values, Mapping):
init_state_parameter_values: Sequence[float] = []
for param in init_state_parameters:
if param in param_values.keys():
init_state_parameter_values.append(param_values[param])
else:
raise ValueError(
f"The dictionary with parameter values provided does not "
f"include all parameters present in the initial state."
f"Parameters present in the state: {init_state_parameters}, "
f"parameters in the dictionary: "
f"{list(param_values.keys())}."
)
elif isinstance(param_values, (Sequence, np.ndarray)):
if len(init_state_parameters) != len(param_values):
raise ValueError(
f"Initial state has {len(init_state_parameters)} parameters and the"
f" list of values has {len(param_values)} elements. They should be"
f" equal in length."
)
init_state_parameter_values = param_values
else:
raise TypeError(f"Unsupported type of param_values provided: {type(param_values)}.")
init_state_param_dict = dict(zip(init_state_parameters, init_state_parameter_values))
return init_state_param_dict
def _validate_aux_ops(self, evolution_problem: TimeEvolutionProblem) -> None:
if evolution_problem.aux_operators is not None and self.estimator is None:
raise ValueError(
"aux_operators were provided for evaluations but no ``estimator`` was provided."
)
|
https://github.com/carstenblank/qiskit-aws-braket-provider
|
carstenblank
|
import cmath
import math
import numpy as np
import qiskit
import matplotlib.pyplot as plt
from qiskit import QuantumCircuit
from typing import Optional, List, Dict
from qiskit_aws_braket_provider.awsprovider import AWSProvider
def compute_rotation(index_state):
if len(index_state) != 2:
return None, None
index_state = np.asarray(index_state)
if abs(np.linalg.norm(index_state)) < 1e-6:
return None, None
index_state = index_state / np.linalg.norm(index_state)
if abs(index_state[0] - index_state[1]) < 1e-6:
return None, None
a_1 = abs(index_state[0])
w_1 = cmath.phase(index_state[0])
a_2 = abs(index_state[1])
w_2 = cmath.phase(index_state[1])
alpha_z = w_2 - w_1
alpha_y = 2 * np.arcsin(abs(a_2) / np.sqrt(a_2 ** 2 + a_1 ** 2))
return alpha_y, alpha_z
def create_swap_test_circuit(index_state, theta, **kwargs):
# type: (List[float], float, Optional[dict]) -> QuantumCircuit
"""
:param index_state:
:param theta:
:param kwargs: use_barriers (bool) and readout_swap (Dict[int, int])
:return:
"""
use_barriers = kwargs.get('use_barriers', False)
readout_swap = kwargs.get('readout_swap', None)
q = qiskit.QuantumRegister(5, "q")
c = qiskit.ClassicalRegister(2, "c")
qc = qiskit.QuantumCircuit(q, c, name="improvement")
# Index on q_0
alpha_y, _ = compute_rotation(index_state)
if alpha_y is None:
qc.h(q[0])
else:
qc.ry(-alpha_y, q[0]).inverse()
if use_barriers: jupyter = qc.barrier()
# Conditionally exite x_1 on data q_2 (center!)
qc.h(q[2])
if use_barriers: qc.barrier()
qc.rz(math.pi, q[2]).inverse()
if use_barriers: qc.barrier()
qc.s(q[2])
if use_barriers: qc.barrier()
qc.cz(q[0], q[2])
if use_barriers: qc.barrier()
# Label y_1
qc.cx(q[0], q[1])
if use_barriers: qc.barrier()
# Ancilla Superposition
qc.h(q[4])
if use_barriers: qc.barrier()
# Unknown data
qc.rx(theta, q[3])
if use_barriers: qc.barrier()
# c-SWAP!!!
# standard.barrier(qc)
qc.cswap(q[4], q[2], q[3])
if use_barriers: qc.barrier()
# Hadamard on ancilla q_4
qc.h(q[4])
if use_barriers: qc.barrier()
# Measure on ancilla q_4 and label q_1
if readout_swap is not None:
qc.barrier()
for i in range(q.size):
j = readout_swap.get(i, i)
if i != j:
qc.swap(q[i], q[j])
else:
readout_swap = {}
qc.barrier()
m1 = readout_swap.get(4, 4)
m2 = readout_swap.get(1, 1)
qiskit.circuit.measure.measure(qc, q[m1], c[0])
qiskit.circuit.measure.measure(qc, q[m2], c[1])
return qc
def extract_classification(counts: Dict[str, int]) -> float:
shots = sum(counts.values())
return (counts.get('00', 0) - counts.get('01', 0) - counts.get('10', 0) + counts.get('11', 0)) / float(shots)
def compare_plot(theta, classification, classification_label=None, compare_classification=None, compare_classification_label=None):
plt.figure(figsize=(10, 7))
theta = theta if len(theta) == len(classification) else range(len(classification))
prefix_label = '{} '.format(classification_label) if classification_label is not None else ''
plt.scatter(x=[xx for xx, p in zip(theta, classification) if p >= 0],
y=[p for p in classification if p >= 0],
label=prefix_label + '$\\tilde{y} = 0$',
c='red',
marker='^',
linewidths=1.0)
plt.scatter(x=[xx for xx, p in zip(theta, classification) if p < 0],
y=[p for p in classification if p < 0],
label=prefix_label + '$\\tilde{y} = 1$',
c='white',
marker='^',
linewidths=1.0, edgecolors='red')
y_lim_lower = min(classification) - 0.1
y_lim_upper = max(classification) + 0.1
if compare_classification is not None and len(compare_classification) == len(classification):
prefix_label = '{} '.format(compare_classification_label) if compare_classification_label is not None else ''
plt.scatter(x=[xx for xx, p in zip(theta, compare_classification) if p >= 0],
y=[p for p in compare_classification if p >= 0],
label=prefix_label + '$\\tilde{y} = 0$',
c='blue',
marker='s',
linewidths=1.0)
plt.scatter(x=[xx for xx, p in zip(theta, compare_classification) if p < 0],
y=[p for p in compare_classification if p < 0],
label=prefix_label + '$\\tilde{y} = 1$',
c='white',
marker='s',
linewidths=1.0, edgecolors='blue')
y_lim_lower = min(min(compare_classification) - 0.1, y_lim_lower)
y_lim_upper = max(max(compare_classification) + 0.1, y_lim_upper)
plt.legend(fontsize=17)
plt.xlabel("$\\theta$ (rad.)", fontsize=22)
plt.ylabel("$\\langle \\sigma_z^{(a)} \\sigma_z^{(l)} \\rangle$", fontsize=22)
plt.tick_params(labelsize=22)
plt.ylim((y_lim_lower, y_lim_upper))
index_state = [np.sqrt(2), np.sqrt(2)]
theta_list = np.arange(start=0, stop=2*np.pi, step=0.2)
qc_list = [create_swap_test_circuit(index_state, theta=theta) for theta in theta_list]
qc_list[0].draw()
provider = AWSProvider(region_name='us-east-1')
backend = provider.get_backend('IonQ Device')
sim_backend = provider.get_backend('SV1')
qc_transpiled_list = qiskit.transpile(qc_list, backend)
qobj = qiskit.assemble(qc_transpiled_list, backend, shots=100)
backend.estimate_costs(qobj), sim_backend.estimate_costs(qobj)
# ATTENTION!!!!!!
# Uncomment to execute
# BE AWARE that this will create costs!
# ATTENTION!!!!!!
# job = backend.run(qobj, extra_data={
# 'index_state': index_state,
# 'theta_list': list(theta_list)
# })
# job_id = job.job_id()
#
# sim_job = sim_backend.run(qobj, extra_data={
# 'index_state': index_state,
# 'theta_list': list(theta_list)
# })
# sim_job_id = sim_job.job_id()
#
# job_id, sim_job_id
# Please input the job ids here
sim_retrieved_job = sim_backend.retrieve_job('<sim_job_id>')
retrieved_job = backend.retrieve_job('<job_id>')
result = retrieved_job.result()
sim_result = sim_retrieved_job.result()
x = retrieved_job.extra_data['theta_list']
experiment_classification = [extract_classification(c) for c in result.get_counts()]
simulation_classification = [extract_classification(c) for c in sim_result.get_counts()]
compare_plot(
theta=theta_list,
classification=experiment_classification, classification_label='experiment',
compare_classification=simulation_classification, compare_classification_label='simulation'
)
|
https://github.com/jonasmaziero/computacao_quantica_qiskit
|
jonasmaziero
|
%run init.ipynb
def pf(t,r):
f = (1-r**t)/(1-r) - t
return f
from mpl_toolkits import mplot3d
def pf_3d(th,ph):
import matplotlib
matplotlib.rcParams.update({'font.size':12});
#plt.figure(figsize = (6,4,4), dpi = 100)
x = np.linspace(0, 1, 20)
y = np.linspace(0, 1, 20)
X, Y = np.meshgrid(x, y)
Z = pf(X,Y)
fig = plt.figure();
ax = plt.axes(projection="3d")
ax.plot_wireframe(X, Y, Z, color='blue')
ax.set_xlabel(r'$\lambda$')
ax.set_ylabel(r'$t$'); ax.set_zlabel(r'$r$')
ax.view_init(th, ph)
fig.tight_layout()
plt.show()
interactive(pf_3d, th = (0,90,10), ph = (0,360,10))
import numpy as np
import math
from matplotlib import pyplot as plt
x = np.arange(0.1,5,0.1) # d tau/dt
y = np.log(np.sinh(x/2)/math.sinh(1/2)) #faz beta*hbat*omega/2 = 1
plt.plot(x,y)
plt.show()
x = np.arange(0,10,0.1) # x = hb*omega, kT=1
y1 = np.exp(-x) # dtau/dt = 1
y2 = np.exp(-0.5*x) # dtau/dt = 0.5
y3 = np.exp(-1.5*x) # dtau/dt = 1.5
plt.plot(x,y1,label='1')
plt.plot(x,y2,label='0.5')
plt.plot(x,y3,label='1.5')
plt.legend()
plt.show()
|
https://github.com/benkoehlL/Qiskit_Playground
|
benkoehlL
|
from qiskit import *
import matplotlib.pyplot as plt
from matplotlib.pyplot import plot, draw, show
import numpy as np
from qiskit.providers.ibmq import least_busy
from qiskit.tools.visualization import plot_histogram
import os, shutil
def dot(s,z):
sum = 0
for i in range(len(str(s))):
sum += int(s[i])*int(z[i])
return(sum%2)
LaTex_folder_Simon = str(os.getcwd())+'/Latex_quantum_gates/Simon_algorithm/'
if not os.path.exists(LaTex_folder_Simon):
os.makedirs(LaTex_folder_Simon)
else:
shutil.rmtree(LaTex_folder_Simon)
os.makedirs(LaTex_folder_Simon)
s = '10'
s_len = len(str(s))
# create quantum register which is double the size of the secret string
qr = QuantumRegister(s_len, 'q')
qr_ancilla = QuantumRegister(s_len, 'qa')
cr = ClassicalRegister(2*s_len, 'c')
qc = QuantumCircuit(qr, qr_ancilla, cr)
# First Hadamard phase
for qubit in qr:
qc.h(qubit)
# Apply barrier just to separate
qc.barrier()
# oracle for s
for qubit1 in qr:
for qubit2 in qr_ancilla:
qc.cx(qubit1, qubit2)
qc.barrier()
# measure ancilla qubits
for i, qubit in enumerate(qr_ancilla):
qc.measure(qubit, cr[i+s_len])
qc.barrier()
# another Hadamard phase
for qubit in qr:
qc.h(qubit)
qc.barrier()
# Measure the input register
for i, qubit in enumerate(qr):
qc.measure(qubit, cr[i])
qc.draw(output='mpl')
draw()
show(block=True)
# create a LaTex file for the algorithm
LaTex_code = qc.draw(output='latex_source', initial_state=True, justify=None)
f_name = 'Simon_algorithm.tex'
with open(LaTex_folder_Simon+f_name, 'w') as f:
f.write(LaTex_code)
# simulate
backend = BasicAer.get_backend('qasm_simulator')
shots = 1000
results = execute(qc, backend=backend, shots = shots).result()
answer = results.get_counts()
# Categorise measurements by input register values
answer_plot = {}
for measureresult in answer.keys():
measureresults_input = measureresult[s_len:]
if measureresults_input in answer_plot:
answer_plot[measureresults_input] += answer[measureresult]
else:
answer_plot[measureresults_input] = answer[measureresult]
# Plot the categorised results
print(answer_plot)
plt = plot_histogram(answer_plot)
draw()
show(block=True)
# Calculate the dot product of the most significant results
print('s , z , s.z (mod 2)')
for z_rev in answer_plot:
if answer_plot[z_rev] >= 0.1*shots:
z = z_rev[::-1]
print( '{}, {}, {}.{} = {}'.format(s, z, s, z, dot(s,z)))
|
https://github.com/ahkatlio/QHSO_Basics_of_Qiskit
|
ahkatlio
|
import numpy as np
import matplotlib.pyplot as plt
# Constants
electron_wavelength = 0.1 # De Broglie wavelength of electrons
slit_width = 0.1 # Width of each slit
screen_distance = 2.0 # Distance from the slits to the screen
screen_width = 2.0 # Width of the screen
screen_resolution = 800 # Number of pixels on the screen
electron_intensity = 1000 # Number of electrons emitted
# Create a grid of points on the screen
x = np.linspace(-screen_width / 2, screen_width / 2, screen_resolution)
y = np.linspace(-screen_width / 2, screen_width / 2, screen_resolution)
X, Y = np.meshgrid(x, y)
# Initialize an empty intensity matrix
intensity = np.zeros_like(X, dtype=float)
# Simulate the electron impacts on the screen
for _ in range(electron_intensity):
# Randomly select a slit
slit_choice = np.random.choice([-1, 1])
# Randomly choose the impact point on the slit
slit_position = np.random.uniform(-slit_width / 2, slit_width / 2) * slit_choice
# Calculate the corresponding position on the screen
x_position = screen_distance * np.tan(np.arctan2(X - slit_position, screen_distance))
# Filter out positions outside the screen
valid_positions = np.logical_and(x_position >= -screen_width / 2, x_position <= screen_width / 2)
# Accumulate impacts on the screen
intensity += valid_positions
# Create a heatmap of electron impacts
plt.figure(figsize=(8, 6))
plt.imshow(intensity, cmap='hot', extent=(-screen_width / 2, screen_width / 2, -screen_width / 2, screen_width / 2))
plt.colorbar(label='Accumulated Impacts')
plt.title('Double-Slit Experiment Heatmap (Electrons as Particles)')
plt.xlabel('X Position (meters)')
plt.ylabel('Y Position (meters)')
plt.show()
import numpy as np
import matplotlib.pyplot as plt
# Set up the experiment parameters
d = 0.1 # Width of the slits
wavelength = 0.01 # Wavelength of the waves or particles
L = 1.0 # Distance from the screen to the slits
dx = 0.01 # Spacing for the observation screen in the x-direction
dy = 0.01 # Spacing for the observation screen in the y-direction
x = np.arange(-1.0, 1.0, dx)
y = np.arange(-1.0, 1.0, dy)
X, Y = np.meshgrid(x, y)
# Calculate the intensity at each point on the screen
intensity = (
(np.sin(np.pi * d * X / (wavelength * L))) ** 2
* (np.sin(np.pi * d * Y / (wavelength * L))) ** 2
)
# Calculate the intensity distribution along the x-axis
intensity_x = (
(np.sin(np.pi * d * x / (wavelength * L))) ** 2
)
# Create subplots
fig, axs = plt.subplots(1, 2, figsize=(12, 6))
# Heatmap subplot
axs[0].imshow(intensity, extent=(-1, 1, -1, 1), cmap="hot", origin="lower")
axs[0].set_title("Double-Slit Interference Heat Map")
axs[0].set_xlabel("X Position (m)")
axs[0].set_ylabel("Y Position (m)")
axs[0].grid(False)
# Distribution plot subplot
axs[1].plot(x, intensity_x, color="blue")
axs[1].set_title("Double-Slit Interference Distribution (X-axis)")
axs[1].set_xlabel("X Position (m)")
axs[1].set_ylabel("Intensity")
axs[1].grid(True)
plt.tight_layout() # Ensure proper spacing between subplots
plt.show()
import numpy as np
import matplotlib.pyplot as plt
from ipywidgets import interact, FloatSlider
# Define the function that simulates the double-slit experiment
def double_slit_experiment(d, wavelength, L, dx, dy):
# Create a grid of points on the screen
x = np.arange(-1.0, 1.0, dx)
y = np.arange(-1.0, 1.0, dy)
X, Y = np.meshgrid(x, y)
# Calculate the intensity at each point on the screen
intensity = (
(np.sin(np.pi * d * X / (wavelength * L))) ** 2
* (np.sin(np.pi * d * Y / (wavelength * L))) ** 2
)
# Calculate the intensity distribution along the x-axis
intensity_x = (
(np.sin(np.pi * d * x / (wavelength * L))) ** 2
)
# Create subplots
fig, axs = plt.subplots(1, 2, figsize=(12, 6))
# Heatmap subplot
axs[0].imshow(intensity, extent=(-1, 1, -1, 1), cmap="hot", origin="lower")
axs[0].set_title("Double-Slit Interference Heat Map")
axs[0].set_xlabel("X Position (m)")
axs[0].set_ylabel("Y Position (m)")
axs[0].grid(False)
# Distribution plot subplot
axs[1].plot(x, intensity_x, color="blue")
axs[1].set_title("Double-Slit Interference Distribution (X-axis)")
axs[1].set_xlabel("X Position (m)")
axs[1].set_ylabel("Intensity")
axs[1].grid(True)
plt.tight_layout() # Ensure proper spacing between subplots
plt.show()
# Define the interactive sliders for the parameters
d_slider = FloatSlider(min=0.01, max=1.0, step=0.01, value=0.1, description='Slit Width:')
wavelength_slider = FloatSlider(min=0.001, max=0.1, step=0.001, value=0.01, description='Wavelength:')
L_slider = FloatSlider(min=0.1, max=10.0, step=0.1, value=1.0, description='Distance to Screen:')
dx_slider = FloatSlider(min=0.001, max=0.1, step=0.001, value=0.01, description='Screen Spacing (X-axis):')
dy_slider = FloatSlider(min=0.001, max=0.1, step=0.001, value=0.01, description='Screen Spacing (Y-axis):')
# Define the interactive function that updates the plot when the sliders are changed
def update_plot(d, wavelength, L, dx, dy):
double_slit_experiment(d, wavelength, L, dx, dy)
# Create the interactive plot
interact(update_plot, d=d_slider, wavelength=wavelength_slider, L=L_slider, dx=dx_slider, dy=dy_slider)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import matplotlib.pyplot as plt
import numpy as np
from qiskit.circuit import ParameterVector
from qiskit.circuit.library import TwoLocal
from qiskit.quantum_info import Statevector
from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem
from qiskit_aer.primitives import Sampler
from qiskit_finance.applications.estimation import EuropeanCallPricing
from qiskit_finance.circuit.library import NormalDistribution
# Set upper and lower data values
bounds = np.array([0.0, 7.0])
# Set number of qubits used in the uncertainty model
num_qubits = 3
# Load the trained circuit parameters
g_params = [0.29399714, 0.38853322, 0.9557694, 0.07245791, 6.02626428, 0.13537225]
# Set an initial state for the generator circuit
init_dist = NormalDistribution(num_qubits, mu=1.0, sigma=1.0, bounds=bounds)
# construct the variational form
var_form = TwoLocal(num_qubits, "ry", "cz", entanglement="circular", reps=1)
# keep a list of the parameters so we can associate them to the list of numerical values
# (otherwise we need a dictionary)
theta = var_form.ordered_parameters
# compose the generator circuit, this is the circuit loading the uncertainty model
g_circuit = init_dist.compose(var_form)
# set the strike price (should be within the low and the high value of the uncertainty)
strike_price = 2
# set the approximation scaling for the payoff function
c_approx = 0.25
# Evaluate trained probability distribution
values = [
bounds[0] + (bounds[1] - bounds[0]) * x / (2**num_qubits - 1) for x in range(2**num_qubits)
]
uncertainty_model = g_circuit.assign_parameters(dict(zip(theta, g_params)))
amplitudes = Statevector.from_instruction(uncertainty_model).data
x = np.array(values)
y = np.abs(amplitudes) ** 2
# Sample from target probability distribution
N = 100000
log_normal = np.random.lognormal(mean=1, sigma=1, size=N)
log_normal = np.round(log_normal)
log_normal = log_normal[log_normal <= 7]
log_normal_samples = []
for i in range(8):
log_normal_samples += [np.sum(log_normal == i)]
log_normal_samples = np.array(log_normal_samples / sum(log_normal_samples))
# Plot distributions
plt.bar(x, y, width=0.2, label="trained distribution", color="royalblue")
plt.xticks(x, size=15, rotation=90)
plt.yticks(size=15)
plt.grid()
plt.xlabel("Spot Price at Maturity $S_T$ (\$)", size=15)
plt.ylabel("Probability ($\%$)", size=15)
plt.plot(
log_normal_samples,
"-o",
color="deepskyblue",
label="target distribution",
linewidth=4,
markersize=12,
)
plt.legend(loc="best")
plt.show()
# Evaluate payoff for different distributions
payoff = np.array([0, 0, 0, 1, 2, 3, 4, 5])
ep = np.dot(log_normal_samples, payoff)
print("Analytically calculated expected payoff w.r.t. the target distribution: %.4f" % ep)
ep_trained = np.dot(y, payoff)
print("Analytically calculated expected payoff w.r.t. the trained distribution: %.4f" % ep_trained)
# Plot exact payoff function (evaluated on the grid of the trained uncertainty model)
x = np.array(values)
y_strike = np.maximum(0, x - strike_price)
plt.plot(x, y_strike, "ro-")
plt.grid()
plt.title("Payoff Function", size=15)
plt.xlabel("Spot Price", size=15)
plt.ylabel("Payoff", size=15)
plt.xticks(x, size=15, rotation=90)
plt.yticks(size=15)
plt.show()
# construct circuit for payoff function
european_call_pricing = EuropeanCallPricing(
num_qubits,
strike_price=strike_price,
rescaling_factor=c_approx,
bounds=bounds,
uncertainty_model=uncertainty_model,
)
# set target precision and confidence level
epsilon = 0.01
alpha = 0.05
problem = european_call_pricing.to_estimation_problem()
# construct amplitude estimation
ae = IterativeAmplitudeEstimation(
epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100})
)
result = ae.estimate(problem)
conf_int = np.array(result.confidence_interval_processed)
print("Exact value: \t%.4f" % ep_trained)
print("Estimated value: \t%.4f" % (result.estimation_processed))
print("Confidence interval:\t[%.4f, %.4f]" % tuple(conf_int))
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/anirban-m/qiskit-superstaq
|
anirban-m
|
import importlib
from typing import List, Optional, Union
import applications_superstaq
import qiskit
try:
import qtrl.sequencer
except ModuleNotFoundError:
pass
class AQTCompilerOutput:
def __init__(
self,
circuits: Union[qiskit.QuantumCircuit, List[qiskit.QuantumCircuit]],
seq: Optional["qtrl.sequencer.Sequence"] = None,
pulse_lists: Optional[Union[List[List], List[List[List]]]] = None,
) -> None:
if isinstance(circuits, qiskit.QuantumCircuit):
self.circuit = circuits
self.pulse_list = pulse_lists
else:
self.circuits = circuits
self.pulse_lists = pulse_lists
self.seq = seq
def has_multiple_circuits(self) -> bool:
"""Returns True if this object represents multiple circuits.
If so, this object has .circuits and .pulse_lists attributes. Otherwise, this object
represents a single circuit, and has .circuit and .pulse_list attributes.
"""
return hasattr(self, "circuits")
def __repr__(self) -> str:
if not self.has_multiple_circuits():
return f"AQTCompilerOutput({self.circuit!r}, {self.seq!r}, {self.pulse_list!r})"
return f"AQTCompilerOutput({self.circuits!r}, {self.seq!r}, {self.pulse_lists!r})"
def read_json(json_dict: dict, circuits_list: bool) -> AQTCompilerOutput:
"""Reads out returned JSON from SuperstaQ API's AQT compilation endpoint.
Args:
json_dict: a JSON dictionary matching the format returned by /aqt_compile endpoint
circuits_list: bool flag that controls whether the returned object has a .circuits
attribute (if True) or a .circuit attribute (False)
Returns:
a AQTCompilerOutput object with the compiled circuit(s). If qtrl is available locally,
the returned object also stores the pulse sequence in the .seq attribute and the
list(s) of cycles in the .pulse_list(s) attribute.
"""
seq = None
pulse_lists = None
if importlib.util.find_spec(
"qtrl"
): # pragma: no cover, b/c qtrl is not open source so it is not in qiskit-superstaq reqs
state_str = json_dict["state_jp"]
state = applications_superstaq.converters.deserialize(state_str)
seq = qtrl.sequencer.Sequence(n_elements=1)
seq.__setstate__(state)
seq.compile()
pulse_lists_str = json_dict["pulse_lists_jp"]
pulse_lists = applications_superstaq.converters.deserialize(pulse_lists_str)
compiled_circuits = [qiskit.QuantumCircuit.from_qasm_str(q) for q in json_dict["qasm_strs"]]
if circuits_list:
return AQTCompilerOutput(compiled_circuits, seq, pulse_lists)
pulse_list = pulse_lists[0] if pulse_lists is not None else None
return AQTCompilerOutput(compiled_circuits[0], seq, pulse_list)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, transpile
from qiskit.visualization import plot_circuit_layout
from qiskit.providers.fake_provider import FakeVigo
backend = FakeVigo()
ghz = QuantumCircuit(3, 3)
ghz.h(0)
ghz.cx(0,range(1,3))
ghz.barrier()
ghz.measure(range(3), range(3))
# Virtual -> physical
# 0 -> 3
# 1 -> 4
# 2 -> 2
my_ghz = transpile(ghz, backend, initial_layout=[3, 4, 2])
plot_circuit_layout(my_ghz, backend)
|
https://github.com/arthurfaria/Qiskit_certificate_prep
|
arthurfaria
|
from qiskit import QuantumCircuit, BasicAer, execute, IBMQ
from qiskit.visualization import plot_histogram
ghz = QuantumCircuit(3,3)
ghz.h(0)
ghz.cx(0,1)
ghz.cx(1,2)
#ghz.barrier(0,2)
ghz.measure([0,1,2],[0,1,2])
# also possible to measure only one qubit with the desired classical bit.
#For example, qubit 2 with classical bit 1: qc.measure(1,0)
ghz.draw('mpl')
backend = BasicAer.get_backend('qasm_simulator')
result = execute(ghz, backend).result() #shots=1024 is by default defined
counts = result.get_counts()
plot_histogram(counts)
leg = ['counts']
plot_histogram(counts, legend=leg, sort='asc',color='green')
# for more counts, we have
job2 = execute(ghz, backend, shots=1024)
result2 = job2.result()
counts2 = result2.get_counts()
job3 = execute(ghz, backend, shots=1024)
result3 = job3.result()
counts3 = result3.get_counts()
#brazilian flag :D
leg = ['counts-1','counts-2', 'counts-3']
plot_histogram([counts,counts2,counts3], legend=leg, sort='asc', figsize = (8,7),
color=['gold','green','blue'])
plot_histogram([counts,counts2,counts3], legend=leg, sort='asc')
qc_spec = QuantumCircuit(3)
qc_spec.measure_all()
backend = BasicAer.get_backend('qasm_simulator')
#specify some linear connection
couple_map = [[0,1],[1,2]]
qc_spec.draw('mpl')
job = execute(qc_spec,backend, shots= 1024, coupling_map = couple_map)
results = job.result()
counts = result.get_counts()
print(counts)
import qiskit.tools.jupyter
from qiskit.tools import job_monitor
provider = IBMQ.load_account()
%qiskit_backend_overview
backend_real = provider.get_backend('ibmq_belem')
job = execute(ghz, backend_real)
job_monitor(job)
result = job.result()
counts = result.get_counts()
plot_histogram(counts)
|
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.
"""Test the LookaheadSwap pass"""
import unittest
from numpy import pi
from qiskit.dagcircuit import DAGCircuit
from qiskit.transpiler.passes import LookaheadSwap
from qiskit.transpiler import CouplingMap, Target
from qiskit.converters import circuit_to_dag
from qiskit.circuit.library import CXGate
from qiskit import ClassicalRegister, QuantumRegister, QuantumCircuit
from qiskit.test import QiskitTestCase
from qiskit.providers.fake_provider import FakeMelbourne
class TestLookaheadSwap(QiskitTestCase):
"""Tests the LookaheadSwap pass."""
def test_lookahead_swap_doesnt_modify_mapped_circuit(self):
"""Test that lookahead swap is idempotent.
It should not modify a circuit which is already compatible with the
coupling map, and can be applied repeatedly without modifying the circuit.
"""
qr = QuantumRegister(3, name="q")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[2])
circuit.cx(qr[0], qr[1])
original_dag = circuit_to_dag(circuit)
# Create coupling map which contains all two-qubit gates in the circuit.
coupling_map = CouplingMap([[0, 1], [0, 2]])
mapped_dag = LookaheadSwap(coupling_map).run(original_dag)
self.assertEqual(original_dag, mapped_dag)
remapped_dag = LookaheadSwap(coupling_map).run(mapped_dag)
self.assertEqual(mapped_dag, remapped_dag)
def test_lookahead_swap_should_add_a_single_swap(self):
"""Test that LookaheadSwap will insert a SWAP to match layout.
For a single cx gate which is not available in the current layout, test
that the mapper inserts a single swap to enable the gate.
"""
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[2])
dag_circuit = circuit_to_dag(circuit)
coupling_map = CouplingMap([[0, 1], [1, 2]])
mapped_dag = LookaheadSwap(coupling_map).run(dag_circuit)
self.assertEqual(
mapped_dag.count_ops().get("swap", 0), dag_circuit.count_ops().get("swap", 0) + 1
)
def test_lookahead_swap_finds_minimal_swap_solution(self):
"""Of many valid SWAPs, test that LookaheadSwap finds the cheapest path.
For a two CNOT circuit: cx q[0],q[2]; cx q[0],q[1]
on the initial layout: qN -> qN
(At least) two solutions exist:
- SWAP q[0],[1], cx q[0],q[2], cx q[0],q[1]
- SWAP q[1],[2], cx q[0],q[2], SWAP q[1],q[2], cx q[0],q[1]
Verify that we find the first solution, as it requires fewer SWAPs.
"""
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[2])
circuit.cx(qr[0], qr[1])
dag_circuit = circuit_to_dag(circuit)
coupling_map = CouplingMap([[0, 1], [1, 2]])
mapped_dag = LookaheadSwap(coupling_map).run(dag_circuit)
self.assertEqual(
mapped_dag.count_ops().get("swap", 0), dag_circuit.count_ops().get("swap", 0) + 1
)
def test_lookahead_swap_maps_measurements(self):
"""Verify measurement nodes are updated to map correct cregs to re-mapped qregs.
Create a circuit with measures on q0 and q2, following a swap between q0 and q2.
Since that swap is not in the coupling, one of the two will be required to move.
Verify that the mapped measure corresponds to one of the two possible layouts following
the swap.
"""
qr = QuantumRegister(3, "q")
cr = ClassicalRegister(2)
circuit = QuantumCircuit(qr, cr)
circuit.cx(qr[0], qr[2])
circuit.measure(qr[0], cr[0])
circuit.measure(qr[2], cr[1])
dag_circuit = circuit_to_dag(circuit)
coupling_map = CouplingMap([[0, 1], [1, 2]])
mapped_dag = LookaheadSwap(coupling_map).run(dag_circuit)
mapped_measure_qargs = {op.qargs[0] for op in mapped_dag.named_nodes("measure")}
self.assertIn(mapped_measure_qargs, [{qr[0], qr[1]}, {qr[1], qr[2]}])
def test_lookahead_swap_maps_measurements_with_target(self):
"""Verify measurement nodes are updated to map correct cregs to re-mapped qregs.
Create a circuit with measures on q0 and q2, following a swap between q0 and q2.
Since that swap is not in the coupling, one of the two will be required to move.
Verify that the mapped measure corresponds to one of the two possible layouts following
the swap.
"""
qr = QuantumRegister(3, "q")
cr = ClassicalRegister(2)
circuit = QuantumCircuit(qr, cr)
circuit.cx(qr[0], qr[2])
circuit.measure(qr[0], cr[0])
circuit.measure(qr[2], cr[1])
dag_circuit = circuit_to_dag(circuit)
target = Target()
target.add_instruction(CXGate(), {(0, 1): None, (1, 2): None})
mapped_dag = LookaheadSwap(target).run(dag_circuit)
mapped_measure_qargs = {op.qargs[0] for op in mapped_dag.named_nodes("measure")}
self.assertIn(mapped_measure_qargs, [{qr[0], qr[1]}, {qr[1], qr[2]}])
def test_lookahead_swap_maps_barriers(self):
"""Verify barrier nodes are updated to re-mapped qregs.
Create a circuit with a barrier on q0 and q2, following a swap between q0 and q2.
Since that swap is not in the coupling, one of the two will be required to move.
Verify that the mapped barrier corresponds to one of the two possible layouts following
the swap.
"""
qr = QuantumRegister(3, "q")
cr = ClassicalRegister(2)
circuit = QuantumCircuit(qr, cr)
circuit.cx(qr[0], qr[2])
circuit.barrier(qr[0], qr[2])
dag_circuit = circuit_to_dag(circuit)
coupling_map = CouplingMap([[0, 1], [1, 2]])
mapped_dag = LookaheadSwap(coupling_map).run(dag_circuit)
mapped_barrier_qargs = [set(op.qargs) for op in mapped_dag.named_nodes("barrier")][0]
self.assertIn(mapped_barrier_qargs, [{qr[0], qr[1]}, {qr[1], qr[2]}])
def test_lookahead_swap_higher_depth_width_is_better(self):
"""Test that lookahead swap finds better circuit with increasing search space.
Increasing the tree width and depth is expected to yield a better (or same) quality
circuit, in the form of fewer SWAPs.
"""
# q_0: βββ ββββββββββββββββββββ βββββββββββββββββββββββββββββββββββββββββββββββΒ»
# βββ΄ββ β βββββ Β»
# q_1: β€ X ββββ βββββββββββββββΌββββββββββββββββββ€ X ββββββββββββββββββββββββββΒ»
# ββββββββ΄ββ β βββ¬βββββββ βββββ Β»
# q_2: ββββββ€ X ββββ ββββββββββΌββββββββββββββββββββΌβββ€ X ββββββββββββ€ X ββββ ββΒ»
# ββββββββ΄ββ βββ΄ββ β βββ¬ββ ββββββββ¬ββ β Β»
# q_3: βββββββββββ€ X ββββ βββ€ X βββββββββββββββββββΌβββββΌβββββ βββ€ X ββββΌβββββΌββΒ»
# ββββββββ΄βββββββ βββββ β β β βββ¬ββ β β Β»
# q_4: ββββββββββββββββ€ X ββββ βββββββββββββ€ X ββββΌβββββ βββββΌβββββΌβββββΌβββββΌββΒ»
# ββββββββ΄ββ βββ¬ββ β β β β β Β»
# q_5: βββββββββββββββββββββ€ X ββββ ββββββββββΌβββββΌββββββββββΌβββββ βββββΌβββββΌββΒ»
# ββββββββ΄ββ β β β β β Β»
# q_6: ββββββββββββββββββββββββββ€ X ββββ βββββ βββββΌββββββββββΌββββββββββ βββββΌββΒ»
# ββββββββ΄ββ β βββ΄ββ βββ΄ββΒ»
# q_7: βββββββββββββββββββββββββββββββ€ X βββββββββ ββββββββ€ X ββββββββββββ€ X βΒ»
# βββββ βββββ βββββΒ»
# Β«q_0: βββ βββββββ
# Β« β
# Β«q_1: βββΌβββββββ
# Β« β
# Β«q_2: βββΌβββββββ
# Β« β
# Β«q_3: βββΌβββββββ
# Β« β
# Β«q_4: βββΌβββββββ
# Β« β
# Β«q_5: βββΌβββββ ββ
# Β« βββ΄ββ β
# Β«q_6: β€ X ββββΌββ
# Β« ββββββββ΄ββ
# Β«q_7: ββββββ€ X β
# Β« βββββ
qr = QuantumRegister(8, name="q")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[1])
circuit.cx(qr[1], qr[2])
circuit.cx(qr[2], qr[3])
circuit.cx(qr[3], qr[4])
circuit.cx(qr[4], qr[5])
circuit.cx(qr[5], qr[6])
circuit.cx(qr[6], qr[7])
circuit.cx(qr[0], qr[3])
circuit.cx(qr[6], qr[4])
circuit.cx(qr[7], qr[1])
circuit.cx(qr[4], qr[2])
circuit.cx(qr[3], qr[7])
circuit.cx(qr[5], qr[3])
circuit.cx(qr[6], qr[2])
circuit.cx(qr[2], qr[7])
circuit.cx(qr[0], qr[6])
circuit.cx(qr[5], qr[7])
original_dag = circuit_to_dag(circuit)
# Create a ring of 8 connected qubits
coupling_map = CouplingMap.from_grid(num_rows=2, num_columns=4)
mapped_dag_1 = LookaheadSwap(coupling_map, search_depth=3, search_width=3).run(original_dag)
mapped_dag_2 = LookaheadSwap(coupling_map, search_depth=5, search_width=5).run(original_dag)
num_swaps_1 = mapped_dag_1.count_ops().get("swap", 0)
num_swaps_2 = mapped_dag_2.count_ops().get("swap", 0)
self.assertLessEqual(num_swaps_2, num_swaps_1)
def test_lookahead_swap_hang_in_min_case(self):
"""Verify LookaheadSwap does not stall in minimal case."""
# ref: https://github.com/Qiskit/qiskit-terra/issues/2171
qr = QuantumRegister(14, "q")
qc = QuantumCircuit(qr)
qc.cx(qr[0], qr[13])
qc.cx(qr[1], qr[13])
qc.cx(qr[1], qr[0])
qc.cx(qr[13], qr[1])
dag = circuit_to_dag(qc)
cmap = CouplingMap(FakeMelbourne().configuration().coupling_map)
out = LookaheadSwap(cmap, search_depth=4, search_width=4).run(dag)
self.assertIsInstance(out, DAGCircuit)
def test_lookahead_swap_hang_full_case(self):
"""Verify LookaheadSwap does not stall in reported case."""
# ref: https://github.com/Qiskit/qiskit-terra/issues/2171
qr = QuantumRegister(14, "q")
qc = QuantumCircuit(qr)
qc.cx(qr[0], qr[13])
qc.cx(qr[1], qr[13])
qc.cx(qr[1], qr[0])
qc.cx(qr[13], qr[1])
qc.cx(qr[6], qr[7])
qc.cx(qr[8], qr[7])
qc.cx(qr[8], qr[6])
qc.cx(qr[7], qr[8])
qc.cx(qr[0], qr[13])
qc.cx(qr[1], qr[0])
qc.cx(qr[13], qr[1])
qc.cx(qr[0], qr[1])
dag = circuit_to_dag(qc)
cmap = CouplingMap(FakeMelbourne().configuration().coupling_map)
out = LookaheadSwap(cmap, search_depth=4, search_width=4).run(dag)
self.assertIsInstance(out, DAGCircuit)
def test_global_phase_preservation(self):
"""Test that LookaheadSwap preserves global phase"""
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
circuit.global_phase = pi / 3
circuit.cx(qr[0], qr[2])
dag_circuit = circuit_to_dag(circuit)
coupling_map = CouplingMap([[0, 1], [1, 2]])
mapped_dag = LookaheadSwap(coupling_map).run(dag_circuit)
self.assertEqual(mapped_dag.global_phase, circuit.global_phase)
self.assertEqual(
mapped_dag.count_ops().get("swap", 0), dag_circuit.count_ops().get("swap", 0) + 1
)
if __name__ == "__main__":
unittest.main()
|
https://github.com/sohamch08/Qiskit-Quantum-Algo
|
sohamch08
|
# Import all the necessary libraries numpy, math, random, time
import numpy as np
import math
import random
import time
seed = np.random.seed(0)
"""
Define parameters
n - Problem size in terms of input variables. Change it as per the problem size
theta,delta,m1,m2 - Parameters defined in the algorithm
"""
n = 3
theta = 0.5 # Theta and delta parameters, feel free to change
delta = 0.1
# Expression for m1 and m2
m1 = int((1/theta**2)*math.log2(n/(delta*theta**2)))
m2 = int((1/theta**4)*math.log2(n*m1/(delta*theta**2)))
"""
Values of m1 and m2 are usually restricted to be m1<=100 and m2 ,= 5/(theta**2)
"""
if(m1>=100):
m1 = 100
m2_max = math.ceil(5/(theta**2))
if(m2>=m2_max):
m2 = m2_max
print(m1,m2)
def f_val(x):
f = [1,1,1,-1,1,1,1,-1]
return f[x]
"""
-Function to generate a random binary string of size l bits
"""
def generate_binary_string(l):
bin_string = []
for i in range(l):
bin_string.append(random.randint(0,1))
return bin_string
def bin_to_dec(b):
n = 0
for i in range(len(b)):
n = n + (2**(i))*(b[i])
return n
def exponent(a,b):
if a == 0:
return 1
elif a == 1:
return b
elif a % 2 == 0:
n = exponent(a//2 , b)
return n*n
else:
n = exponent(a//2, b)
return (n*n)*b
def dot(a,b):
length = len(a)
norm = 0
for i in range(length):
norm = norm + a[i]*b[i]
return norm
"""
- SUBROUTINE Approx(alpha,k)
- Returns an estimate of the significance of the fourier coefficient whose prefix is alpha, where length of alpha is k.
"""
def approx(alpha, k):
"""
- Special case: k==n; # for k==n case, there is no list of x_i s
- Generate yij_list. This has two cases, 2**(k)<=m2 and 2**(k)>m2. We chose the length of yij to be min of either.
- Compute A_i by iterating of yij and beta_alpha (Recall that there is only one i in this case)
"""
min1 = min(m1, exponent(n-k,2))
min2 = min(m2, exponent(k,2))
if(k==n):
## Write your code here for the case when k==n
yi = []
for j in range(min2):
yij = generate_binary_string(n)
yi.append(yij)
A_i = 0
for j in range(min2):
# value of sum f(yij) xhi_alpha(yij)
A_i = (f_val(bin_to_dec(yi[j])))*((-1)**(dot(alpha, yi[j]))) + A_i
A_i = A_i/min2 # approximated value of f_alpha(xi)
return [A_i**2, A_i] # keeps track of the expected fourier coefficient when n==k
else:
"""
1. Generate xi_list. This has two cases, 2**(n-k)<=m1 and 2**(n-k)>m1. We chose the length of xi to be min of either.
2. Generate yij_list. This has two cases, 2**(k)<=m2 and 2**(k)>m2. We chose the length of yij to be min of either.
3. Iterate over x_i and y_ij and compute A_i and finally beta_alpha
"""
# Part-1: Write a code to Generate random Xi string
beta_alpha = 0
A = []
for i in range(min1):
xi = generate_binary_string(n-k)
yi = []
# -----------------------------------------------------------------------
# Part -2 : Write a code to Generate random Yi string
for j in range(min2):
yij = generate_binary_string(k)
yi.append(yij)
#------------------------------------------------------------
# Part 3: Iterate over xi and yj and compute Ai and beta_alpha
A_i = 0
for j in range(min2):
# value of sum f(yij xi) xhi_alpha(yij)
A_i = (f_val(bin_to_dec(xi+yi[j])))*((-1)**(dot(alpha, yi[j]))) + A_i
A_i = A_i/min2 # value of f_alpha(xi)
A.append(A_i)
for i in range(min1):
beta_alpha = beta_alpha + (A[i]**2)
beta_alpha = beta_alpha/min1
return [beta_alpha, beta_alpha] # keeps track of the expected fourier coefficient
"""
SUBROUTINE Coef(alpha,k)
Input: alpha value, k - Size of alpha
Output: Set of binary strings corresponding to the monomials with largest fourier coefficients
This function is called recursively call till k==n by extending the prefix with both '0' and '1'
and pruned as needed (refer to the algorithm).
"""
def Coef(alpha,k, list):
# Compute B_alpha for each value of alpha and keep those alpha values for which B_alpha> threshold
# Write your code here
B_alpha_list = approx(alpha, k)
if B_alpha_list[0] >= (theta**2)/2:
if k == n:
list.append([alpha, B_alpha_list[1]])
else:
Coef(alpha+[0], k+1, list)
Coef(alpha+[1], k+1, list)
if __name__ == '__main__':
k=1
alpha = [0]
coephs = []
Coef([], 0, coephs) # starting with 0 then we will recurse on adding new bits
print(coephs)
# Using the alpha values and the corresponding fourier estimates, create the fourier expansion of the majority function
# You can output the expression as a string and print below
def bin_to_coefficient(lst):
strg = ""
flag = True
for i in range(len(lst)):
if lst[i] == 1:
strg = strg + "x_" + str(len(lst)-i)
flag = False
if flag:
strg = strg + '1'
return strg
return strg
to_print = []
for coefficient in coephs:
if coefficient[1] < 0:
to_print.append('(')
to_print.append(str(coefficient[1]))
to_print.append(')')
else:
to_print.append(str(coefficient[1]))
to_print.append('*')
to_print.append(bin_to_coefficient(coefficient[0]))
to_print.append(' + ')
for item in to_print[:-1]:
print(item, end="")
"""
Ex. 5: Generate a random function f
"""
n = 5
N = 2**n
f = []
for i in range(N):
f.append((-1)**np.random.randint(0,2))
#print(f)
#for i in range(len(f)):
# f[i] = (-1)**np.random.randint(0,2)
print(f)
def f_val(a_int):
a = a_int % N
return f[a]
# Generate a random function. One example is shown below
#f = (x32 Β© x8 Β© x34 Β© x13) AND (x33 Β© x20 Β© x9 Β© x1 Β© x15 Β© x39) OR (x24 Β© x10 Β© x27 Β© x6 Β© x34)
# f = f1 and f2 or f3
n = 40
# Hardcode the f1,f2,f3 lists as
f1_list = [32,8,34,13]
f2_list = [33,20,9,1,15,39]
f3_list = [24,10,27,6,34]
f_list = set(f1_list + f2_list + f3_list )
# OR Generate f1_list, f2_list, f3_list randomly as below
f1_l1 = 7
f2_l2 = 5
f3_l3 = 8
f4_l4 = 4
f1_list,f2_list,f3_list,f4_list = [],[],[],[]
f = []
i=0
while(i<f1_l1):
r=random.randint(1,n)
if r not in f1_list:
f1_list.append(r)
i = i+1
else:
pass
# Write similar code for f2_l2, f3_l3, f4_l4
f_list = set(f1_list + f2_list + f3_list + f4_list)
print(f' f1_list data is {f1_list}')
print(f' f2_list data is {f2_list}')
print(f' f3_list data is {f3_list}')
print(f' f4_list data is {f4_list}')
print(f' f_list data is {f_list}')
def count(f_bits):
f_ = f_bits.count(1)
if (f_%2==0):
return 0
else:
return 1
def f_val(a_int):
a = bin(a_int)[2:].zfill(n)
f1_bits = []
f2_bits = []
f3_bits = []
f4_bits = []
for i in f1_list:
f1_bits.append(int(a[n-i]))
for i in f2_list:
f2_bits.append(int(a[n-i]))
for i in f3_list:
f3_bits.append(int(a[n-i]))
for i in f4_list:
f4_bits.append(int(a[n-i]))
#print(f1_bits)
#print(f2_bits)
#print(f3_bits)
#print(f4_bits)
f1 = count(f1_bits)
f2 = count(f2_bits)
f3 = count(f3_bits)
f4 = count(f4_bits)
f = f1 and f2 or f3
return (-1)**f
# Write a code to compute fourier coefficients and final alpha values as explained
# Verify your end result for following 3 points by compairing it with elements present in the original function
# 1. Check for Elements correctly retrieved
# 2. Elements retrieved but not present in the original function
# 3. Elements present in the original function but not retrieved
# Write your code here
# Compare total execution times of both and accuracy of the KM
"""
Ex.3 (4 variables), Ex. Ref. 1 sec. 2.3.1 page no 8
f(x1,x2,x3,x4) = x1 AND x3 (x1 is lsb and x4 is msb, x=x4, y=x3, z=x2, w=x1)
f = [1,1,1,1,1,-1,1,-1,1,1,1,1,1,-1,1,-1]
"""
def f_val(a_int):
a = bin(a_int)[2:].zfill(n)
f = int(a[1]) and int(a[3])
return (-1)**f
"""
Ex. 4 (40 variables), Ref. 1, sec. 3.1 page no 15
f = (x32 Β© x8 Β© x34 Β© x13) AND (x33 Β© x20 Β© x9 Β© x1 Β© x15 Β© x39) OR (x24 Β© x10 Β© x27 Β© x6 Β© x34)
"""
def f_val(a_int):
a = bin(a_int)[2:].zfill(n)
f1 = int(a[40-32])^int(a[40-8])^int(a[40-34])^int(a[40-13])
f2 = int(a[40-33])^int(a[40-20])^int(a[40-9])^int(a[40-39])
f3 = int(a[40-24])^int(a[40-10])^int(a[40-27])^int(a[40-34])
f = f1 and f2 or f3
return (-1)**f
|
https://github.com/indian-institute-of-science-qc/qiskit-aakash
|
indian-institute-of-science-qc
|
# 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.
"""Meta tests for mappers.
The test checks the output of the swapper to a ground truth DAG (one for each
test/swapper) saved in as a QASM (in `test/python/qasm/`). If they need
to be regenerated, the DAG candidate is compiled and run in a simulator and
the count is checked before being saved. This happens with (in the root
directory):
> python -m test.python.transpiler.test_mappers regenerate
To make a new swapper pass throw all the common tests, create a new class inside the file
`path/to/test_mappers.py` that:
* the class name should start with `Tests...`.
* inheriting from ``SwapperCommonTestCases, QiskitTestCase``
* overwrite the required attribute ``pass_class``
For example::
class TestsSomeSwap(SwapperCommonTestCases, QiskitTestCase):
pass_class = SomeSwap # The pass class
additional_args = {'seed_transpiler': 42} # In case SomeSwap.__init__ requires
# additional arguments
To **add a test for all the swappers**, add a new method ``test_foo``to the
``SwapperCommonTestCases`` class:
* defining the following required ``self`` attributes: ``self.count``,
``self.shots``, ``self.delta``. They are required for the regeneration of the
ground truth.
* use the ``self.assertResult`` assertion for comparing for regeneration of the
ground truth.
* explicitly set a unique ``name`` of the ``QuantumCircuit``, as it it used
for the name of the QASM file of the ground truth.
For example::
def test_a_common_test(self):
self.count = {'000': 512, '110': 512} # The expected count for this circuit
self.shots = 1024 # Shots to run in the backend.
self.delta = 5 # This is delta for the AlmostEqual during
# the count check
coupling_map = [[0, 1], [0, 2]] # The coupling map for this specific test
qr = QuantumRegister(3, 'q') #
cr = ClassicalRegister(3, 'c') # Set the circuit to test
circuit = QuantumCircuit(qr, cr, # and don't forget to put a name
name='some_name') # (it will be used to save the QASM
circuit.h(qr[1]) #
circuit.cx(qr[1], qr[2]) #
circuit.measure(qr, cr) #
result = transpile(circuit, self.create_backend(), coupling_map=coupling_map,
pass_manager=self.create_passmanager(coupling_map))
self.assertResult(result, circuit)
```
"""
# pylint: disable=attribute-defined-outside-init
import unittest
import os
import sys
from qiskit import execute
from qiskit import ClassicalRegister, QuantumRegister, QuantumCircuit, BasicAer
from qiskit.transpiler import PassManager
from qiskit.transpiler.passes import BasicSwap, LookaheadSwap, StochasticSwap, SabreSwap
from qiskit.transpiler.passes import SetLayout
from qiskit.transpiler import CouplingMap, Layout
from qiskit.test import QiskitTestCase
class CommonUtilitiesMixin:
"""Utilities for meta testing.
Subclasses should redefine the ``pass_class`` argument, with a Swap Mapper
class.
Note: This class assumes that the subclass is also inheriting from
``QiskitTestCase``, and it uses ``QiskitTestCase`` methods directly.
"""
regenerate_expected = False
seed_simulator = 42
seed_transpiler = 42
additional_args = {}
pass_class = None
def create_passmanager(self, coupling_map, initial_layout=None):
"""Returns a PassManager using self.pass_class(coupling_map, initial_layout)"""
passmanager = PassManager()
if initial_layout:
passmanager.append(SetLayout(Layout(initial_layout)))
# pylint: disable=not-callable
passmanager.append(self.pass_class(CouplingMap(coupling_map), **self.additional_args))
return passmanager
def create_backend(self):
"""Returns a Backend."""
return BasicAer.get_backend("qasm_simulator")
def generate_ground_truth(self, transpiled_result, filename):
"""Generates the expected result into a file.
Checks if transpiled_result matches self.counts by running in a backend
(self.create_backend()). That's saved in a QASM in filename.
Args:
transpiled_result (DAGCircuit): The DAGCircuit to execute.
filename (string): Where the QASM is saved.
"""
sim_backend = self.create_backend()
job = execute(
transpiled_result,
sim_backend,
seed_simulator=self.seed_simulator,
seed_transpiler=self.seed_transpiler,
shots=self.shots,
)
self.assertDictAlmostEqual(self.counts, job.result().get_counts(), delta=self.delta)
transpiled_result.qasm(formatted=False, filename=filename)
def assertResult(self, result, circuit):
"""Fetches the QASM in circuit.name file and compares it with result."""
qasm_name = f"{type(self).__name__}_{circuit.name}.qasm"
qasm_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "qasm")
filename = os.path.join(qasm_dir, qasm_name)
if self.regenerate_expected:
# Run result in backend to test that is valid.
self.generate_ground_truth(result, filename)
expected = QuantumCircuit.from_qasm_file(filename)
self.assertEqual(result, expected)
class SwapperCommonTestCases(CommonUtilitiesMixin):
"""Tests that are run in several mappers.
The tests here will be run in several mappers. When adding a test, please
ensure that the test:
* defines ``self.count``, ``self.shots``, ``self.delta``.
* uses the ``self.assertResult`` assertion for comparing for regeneration of
the ground truth.
* explicitly sets a unique ``name`` of the ``QuantumCircuit``.
See also ``CommonUtilitiesMixin`` and the module docstring.
"""
def test_a_cx_to_map(self):
"""A single CX needs to be remapped.
q0:----------m-----
|
q1:-[H]-(+)--|-m---
| | |
q2:------.---|-|-m-
| | |
c0:----------.-|-|-
c1:------------.-|-
c2:--------------.-
CouplingMap map: [1]<-[0]->[2]
expected count: '000': 50%
'110': 50%
"""
self.counts = {"000": 512, "110": 512}
self.shots = 1024
self.delta = 5
coupling_map = [[0, 1], [0, 2]]
qr = QuantumRegister(3, "q")
cr = ClassicalRegister(3, "c")
circuit = QuantumCircuit(qr, cr, name="a_cx_to_map")
circuit.h(qr[1])
circuit.cx(qr[1], qr[2])
circuit.measure(qr, cr)
result = self.create_passmanager(coupling_map).run(circuit)
self.assertResult(result, circuit)
def test_initial_layout(self):
"""Using a non-trivial initial_layout.
q3:----------------m--
q0:----------m-----|--
| |
q1:-[H]-(+)--|-m---|--
| | | |
q2:------.---|-|-m-|--
| | | |
c0:----------.-|-|-|--
c1:------------.-|-|--
c2:--------------.-|--
c3:----------------.--
CouplingMap map: [1]<-[0]->[2]->[3]
expected count: '000': 50%
'110': 50%
"""
self.counts = {"0000": 512, "0110": 512}
self.shots = 1024
self.delta = 5
coupling_map = [[0, 1], [0, 2], [2, 3]]
qr = QuantumRegister(4, "q")
cr = ClassicalRegister(4, "c")
circuit = QuantumCircuit(qr, cr, name="initial_layout")
circuit.h(qr[1])
circuit.cx(qr[1], qr[2])
circuit.measure(qr, cr)
layout = {qr[3]: 0, qr[0]: 1, qr[1]: 2, qr[2]: 3}
result = self.create_passmanager(coupling_map, layout).run(circuit)
self.assertResult(result, circuit)
def test_handle_measurement(self):
"""Handle measurement correctly.
q0:--.-----(+)-m-------
| | |
q1:-(+)-(+)-|--|-m-----
| | | |
q2:------|--|--|-|-m---
| | | | |
q3:-[H]--.--.--|-|-|-m-
| | | |
c0:------------.-|-|-|-
c1:--------------.-|-|-
c2:----------------.-|-
c3:------------------.-
CouplingMap map: [0]->[1]->[2]->[3]
expected count: '0000': 50%
'1011': 50%
"""
self.counts = {"1011": 512, "0000": 512}
self.shots = 1024
self.delta = 5
coupling_map = [[0, 1], [1, 2], [2, 3]]
qr = QuantumRegister(4, "q")
cr = ClassicalRegister(4, "c")
circuit = QuantumCircuit(qr, cr, name="handle_measurement")
circuit.h(qr[3])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[3], qr[1])
circuit.cx(qr[3], qr[0])
circuit.measure(qr, cr)
result = self.create_passmanager(coupling_map).run(circuit)
self.assertResult(result, circuit)
class TestsBasicSwap(SwapperCommonTestCases, QiskitTestCase):
"""Test SwapperCommonTestCases using BasicSwap."""
pass_class = BasicSwap
class TestsLookaheadSwap(SwapperCommonTestCases, QiskitTestCase):
"""Test SwapperCommonTestCases using LookaheadSwap."""
pass_class = LookaheadSwap
class TestsStochasticSwap(SwapperCommonTestCases, QiskitTestCase):
"""Test SwapperCommonTestCases using StochasticSwap."""
pass_class = StochasticSwap
additional_args = {"seed": 0}
class TestsSabreSwap(SwapperCommonTestCases, QiskitTestCase):
"""Test SwapperCommonTestCases using SabreSwap."""
pass_class = SabreSwap
additional_args = {"seed": 1242}
if __name__ == "__main__":
if len(sys.argv) >= 2 and sys.argv[1] == "regenerate":
CommonUtilitiesMixin.regenerate_expected = True
del sys.argv[1]
unittest.main()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.