repo
stringclasses 885
values | file
stringclasses 741
values | content
stringlengths 4
215k
|
|---|---|---|
https://github.com/DuarteSerranoR/qiskit_quantum_algorithms
|
DuarteSerranoR
|
from qiskit import *
from qiskit.extensions import *
from qiskit.tools.visualization import *
def OR(inp1,inp2):
"""An OR gate.
Parameters:
inpt1 (str): Input 1, encoded in qubit 0.
inpt2 (str): Input 2, encoded in qubit 1.
Returns:
QuantumCircuit: Output XOR circuit.
str: Output value measured from qubit 2.
"""
qc = QuantumCircuit(3, 1)
qc.reset(range(3))
if inp1=='1':
qc.x(0)
if inp2=='1':
qc.x(1)
qc.barrier()
# this is where your program for quantum OR gate goes
qc.ccx(0,1,2)
qc.cx(0,2)
qc.cx(1,2)
qc.barrier()
qc.measure(2, 0) # output from qubit 2 is measured
# We'll run the program on a simulator
backend = Aer.get_backend('aer_simulator')
# Since the output will be deterministic, we can use just a single shot to get it
job = backend.run(qc,shots=1,memory=True)
output = job.result().get_memory()[0]
return qc, output
## Test the function
for inp1 in ['0', '1']:
for inp2 in ['0', '1']:
qc, output = OR(inp1, inp2)
print('OR with inputs',inp1,inp2,'gives output',output)
display(qc.draw())
print('\n')
|
https://github.com/TheGupta2012/QPE-Algorithms
|
TheGupta2012
|
from qiskit import *
import numpy as np
import sys
sys.path.append("..")
qiskit.__qiskit_version__
from Modules.kitaev_qpe import KQPE
U = np.array([[1, 0],
[0, np.exp(2*np.pi*1j*(1/3))]])
kqpe = KQPE(unitary=U, precision=16)
kq_circ = kqpe.get_circuit(show=True, save_circ=True,
circ_name="KQPE_circ_1qubit.JPG")
q = QuantumCircuit(5, 6)
q.x(3)
q.append(kq_circ, qargs=[1, 2, 3])
q.draw('mpl')
phase = kqpe.get_phase(backend=Aer.get_backend(
'qasm_simulator'), QC=q, ancilla=[1, 2], clbits=[0, 1], show=True)
print("Phase of the unitary is :", phase)
q = QuantumCircuit(2, name='Unitary')
q.cp(2*np.pi*(1/7), 0, 1)
q.draw('mpl')
unitary = q
kqpe = KQPE(unitary, precision=12)
kq_circ = kqpe.get_circuit(show=True)
q = QuantumCircuit(5, 2)
q.x([2, 3])
q.append(kq_circ, qargs=[0, 1, 2, 3])
q.draw('mpl')
sim = Aer.get_backend('qasm_simulator')
phase = kqpe.get_phase(backend=sim, QC=q, ancilla=[
0, 1], clbits=[0, 1], show=True)
print("Phase returned is :", phase)
q = QuantumCircuit(2, name='Phase Unitary')
q.cp(2*np.pi*(1/7), 0, 1)
display(q.draw('mpl'))
unitary = q
precision = [i for i in range(8, 18)]
precision
estimates, errors = [], []
for prec in precision:
kqpe = KQPE(unitary, precision=prec)
kq_circ = kqpe.get_circuit(show=False)
# making circuit
q = QuantumCircuit(5, 2)
q.x([2, 3])
q.append(kq_circ, qargs=[0, 1, 2, 3])
# getting the phase
phase = kqpe.get_phase(backend=sim, QC=q, ancilla=[
0, 1], clbits=[0, 1], show=False)
estimates.append(phase[0])
errors.append(abs(1/7-phase[0]))
import matplotlib.pyplot as plt
plt.title("Phase Estimation for $ \phi $ = 1/7", fontsize=16)
plt.xlabel("Precision for estimation")
plt.ylabel("Estimates for Error and Phase")
plt.plot([7, 18], [1/7, 1/7], color='black', label='Actual', linewidth=2)
plt.plot(precision, estimates, marker='o', color='magenta',
alpha=0.6, label='Phase Estimate')
plt.plot(precision, errors, marker='s', color='cyan',
alpha=0.6, label="Error estimate")
plt.grid()
plt.legend()
plt.savefig("Kitaev Multiqubit Estimation Plot.JPG", dpi=200)
|
https://github.com/abhik-99/Qiskit-Summer-School
|
abhik-99
|
!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/dimple12M/Qiskit-Certification-Guide
|
dimple12M
|
from qiskit import *
from qiskit.quantum_info import Statevector
def qasm_sim(qc):
backend = Aer.get_backend('qasm_simulator')
job = execute(qc, backend, shots=1024)
result = job.result()
counts = result.get_counts(qc)
return counts
qc=QuantumCircuit(2)
qc.x(0)
qc.h(1)
qc.draw(output="mpl")
qc.measure_all()
qc.draw(output="mpl")
qc.size()
qc.clbits
qc=QuantumCircuit(2)
qc.x(0)
qc.h(1)
qc.draw(output="mpl")
qc=QuantumCircuit(2,2) # 2 qubits and 2 bits
qc.x(0)
qc.h(1)
qc.draw(output="mpl")
qc.measure(0,0)
qc.measure(1,1)
qc.draw(output="mpl")
qc=QuantumCircuit(2,2) # 2 qubits and 2 bits
qc.x(0)
qc.h(1)
qc.draw(output="mpl")
qc.measure([0,1],[0,1])
qc.draw(output="mpl")
qc=QuantumCircuit(2)
qc.measure_all()
qc.draw(output="mpl")
backend = Aer.get_backend('qasm_simulator')
job=execute (qc, backend)
result = job.result()
counts = result.get_counts()
print(counts)
qc=QuantumCircuit(2,2) # 2 qubits and 2 bits
qc.x(0)
qc.h(1)
qc.measure(range(2),range(2))
qc.draw(output="mpl")
q=QuantumRegister(2,'qr')
c=ClassicalRegister(2,'cr')
qc=QuantumCircuit(q,c)
qc.h(0)
qc.x(1)
qc.draw(output="mpl")
qc=QuantumCircuit(2,2) # 2 qubits and 2 bits
qc.x(0)
qc.h(1)
qc.draw(output="mpl")
state = Statevector.from_instruction(qc)
state.draw(output='latex')
qc.reset(1)
qc.draw(output="mpl")
state = Statevector.from_instruction(qc)
state.draw(output='latex')
qc=QuantumCircuit(1)
qc.x(0)
qc.h(0)
qc.draw(output="mpl")
state = Statevector.from_instruction(qc)
state.draw(output='latex')
qc=QuantumCircuit(1) # 2 qubits and 2 bits
qc.x(0)
qc.reset(0)
qc.h(0)
qc.draw(output="mpl")
state = Statevector.from_instruction(qc)
state.draw(output='latex')
qr=QuantumRegister(2,'qr')
cr=ClassicalRegister(2,'cr')
qc=QuantumCircuit(qr,cr) # 2 qubits and 2 bits
qc.x(0)
qc.x(1)
qc.draw(output="mpl")
state = Statevector.from_instruction(qc)
state.draw(output='latex')
qc.s(qr[1]).c_if(cr,0)
qc.draw(output="mpl")
state = Statevector.from_instruction(qc)
state.draw(output='latex')
qr=QuantumRegister(2,'qr')
cr=ClassicalRegister(2,'cr')
qc=QuantumCircuit(qr,cr) # 2 qubits and 2 bits
qc.x(0)
qc.measure([0,1],[0,1])
qc.draw(output="mpl")
qasm_sim(qc)
qc.s(qr[0]).c_if(cr,1)
qc.draw(output="mpl")
qasm_sim(qc)
qc.x(qr[1]).c_if(cr,1)
qc.measure([0,1],[0,1])
qc.draw(output="mpl")
qasm_sim(qc)
|
https://github.com/dcavar/q
|
dcavar
|
!pip install -U --user qiskit
!pip install -U --user qiskit_ibm_runtime
!pip install -U --user matplotlib
!pip install -U --user pylatexenc
import qiskit
import secret
qiskit.__version__
from qiskit_ibm_runtime import QiskitRuntimeService
service = QiskitRuntimeService(channel="ibm_quantum", # or ibm_cloud
token=secret.api_key_ibm_q)
QiskitRuntimeService.save_account(channel="ibm_quantum",
token=secret.api_key_ibm_q)
backend = service.backend(name="ibm_brisbane")
backend.num_qubits
|
https://github.com/bayesian-randomized-benchmarking/qiskit-advocates-bayes-RB
|
bayesian-randomized-benchmarking
|
import numpy as np
import time
from qiskit_experiments.library import StandardRB, InterleavedRB
from qiskit_experiments.framework import ParallelExperiment
from qiskit_experiments.library.randomized_benchmarking import RBUtils
import qiskit.circuit.library as circuits
# for retrieving gate calibration
from datetime import datetime
import qiskit.providers.aer.noise.device as dv
# import the bayesian packages
import pymc3 as pm
import arviz as az
simulation = False # make your choice here
if simulation:
from qiskit.providers.aer import AerSimulator
from qiskit.test.mock import FakeParis
backend = AerSimulator.from_backend(FakeParis())
else:
from qiskit import IBMQ
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q')
backend = provider.get_backend('ibmq_bogota') # type here hardware backend
# describe RB experiment
interleaved_gate = "cx"
qubits = [0,1]
interleaved_circuit = circuits.CXGate()
lengths = np.arange(1, 200, 30)
num_samples = 10
seed = None
# get the backend's calibration value
t = None # enter t in datetime format if necessary
# use properties(datetime=t) if t is defined
e_list = dv.gate_error_values(backend.properties())
epc_calib = np.nan
for tuple_e in e_list:
if tuple_e[0] == 'cx' and tuple_e[1] == qubits:
epc_calib = tuple_e[2]
print('EPC calibration: {0:1.4e}'.format(epc_calib))
#prepare circuits
int_exp2 = InterleavedRB(interleaved_circuit, qubits,
lengths, num_samples=num_samples, seed=seed)
#run
print("start experiments",time.strftime('%d/%m/%Y %H:%M:%S'))
int_expdata2 = int_exp2.run(backend).block_for_results()
print(" end experiments",time.strftime('%d/%m/%Y %H:%M:%S'))
#analyse
print(" start analysis",time.strftime('%d/%m/%Y %H:%M:%S'))
int_results2 = int_expdata2.analysis_results()
print(" end analysis",time.strftime('%d/%m/%Y %H:%M:%S'))
# look at result data
for result in int_results2:
print(result)
def get_GSP_counts(data, x_length, data_range):
#obtain the observed counts used in the bayesian model
#corrected for accomodation pooled data from 1Q, 2Q and 3Q interleave processes
list_bitstring = ['0','00', '000', '100'] # all valid bistrings
Y_list = []
for i_samples in data_range:
row_list = []
for c_index in range(x_length) :
total_counts = 0
i_data = i_samples*x_length + c_index
for key,val in data[i_data]['counts'].items():
if key in list_bitstring:
total_counts += val
row_list.append(total_counts)
Y_list.append(row_list)
return np.array(Y_list)
# get count data and other values from int_expdata2
Y1 = get_GSP_counts(int_expdata2._data, len(lengths),
range(0,2*num_samples-1,2))
Y2 = get_GSP_counts(int_expdata2._data, len(lengths),
range(1,2*num_samples,2))
experiment_type = int_expdata2._data[0]['metadata']['experiment_type']
physical_qubits = int_expdata2._data[0]['metadata']['physical_qubits']
shots = int_expdata2._data[0]['shots']
nQ = len(qubits)
scale = (2 ** nQ - 1) / 2 ** nQ
# to compare ultimately: EPC and sigma(EPC) by LSF
epc_est_fm = int_expdata2.analysis_results()[3].value.value
epc_est_fm_err = int_expdata2.analysis_results()[3].value.stderr
# use 2m length array
Y = np.hstack((Y1,Y2))
RvsI_h = np.ravel(np.vstack((np.ones_like(lengths),np.zeros_like(lengths))))
IvsR_h = np.ravel(np.vstack((np.zeros_like(lengths),np.ones_like(lengths))))
X0 = np.tile(lengths,2)
X = np.vstack((X0,RvsI_h,IvsR_h))
y_mean = np.mean(Y, axis = 0)/shots
sigma_y = np.std(Y, axis = 0)/shots
model = "hierarchical_model"
# priors for unknown model parameters
T_priors = int_expdata2.analysis_results()[0].value.value
print(T_priors)
# building the model
h_model = pm.Model()
with h_model:
# Tying parameters
BoundedUniform = pm.Bound(pm.Uniform,
lower=np.fmax(T_priors-0.1, np.full(T_priors.shape,1.e-9)),
upper=np.fmin(T_priors+0.1, np.full(T_priors.shape,1.-1e-9)))
pi = BoundedUniform("Tying_Parameters",testval = T_priors, shape = T_priors.shape)
EPC = pm.Deterministic('EPC', scale*(1-pi[2]))
# sigma of Beta functions
sigma_t = pm.Uniform("σ_Beta", testval = 0.005,
upper = 0.05, lower = 0.0005)
# Tying function
GSP = pi[0] * ( X[1]*pi[1]**X[0] +\
X[2]*(pi[1]*pi[2])**X[0] ) + pi[3]
theta = pm.Beta('θ', mu=GSP, sigma = sigma_t,
shape = ((2*len(lengths, ))) )
# Likelihood (sampling distribution) of observations
p = pm.Binomial("Counts", p = theta, observed = Y, n = shots)
# model graph
pm.model_to_graphviz(h_model)
# sample
with h_model:
trace_h = pm.sample(draws = 4000, tune= 1000, target_accept=.99,
return_inferencedata=True)
with h_model:
az.plot_trace(trace_h);
with h_model:
az.plot_posterior(trace_h, var_names = ["Tying_Parameters","σ_Beta","EPC"], round_to = 4, figsize = [16, 8]);
# look at the posterior values of the hyperparameters:
with h_model:
# (hdi_prob=.94 is default)
azt_summary = az.summary(trace_h, round_to=12,
var_names = ["Tying_Parameters", "σ_Beta","EPC"],
kind="stats")
azt_summary
# mean and sigma of EPC
epc_est_a = azt_summary['mean']['EPC']
epc_est_a_err = azt_summary['sd']['EPC']
# plot
import matplotlib.pyplot as plt # if not yet imported
with h_model:
az.plot_posterior(trace_h, var_names = ["EPC"],
round_to = 4, figsize = [10,6],
textsize = 12)
Bayes_legend = "EPC SMC: {0:1.3e} ± {1:1.3e}"\
.format(epc_est_a, epc_est_a_err)
LSF_legend = "EPC LSF: {0:1.3e} ± {1:1.3e}".format(epc_est_fm, epc_est_fm_err)
Cal_legend = "EPC Calibration: {0:1.3e}".format(epc_calib)
plt.axvline(x=epc_est_fm,color='cyan',ls="-")
if epc_calib != np.nan:
plt.axvline(x=epc_calib,color='r',ls=":")
plt.axvline(x=epc_est_a,color='blue',ls=":")
if epc_calib > 0.0:
plt.legend((Bayes_legend, "$Highest\; density\; interval$ HDI",
LSF_legend,
Cal_legend), fontsize=12 )
else:
plt.legend((Bayes_legend, "$Highest\; density\; interval$ HDI",
LSF_legend))
plt.title(experiment_type +', ' + interleaved_gate + " qubit(s):" + str(physical_qubits)\
+', backend: '+backend.name() + "\n Bayesian "+model,
fontsize=16);
# compare LSF and SMC
print("Model: Frequentist Bayesian Calibration")
print("__________________________________________________________")
print("EPC {0:1.3e} {1:1.3e} {2:1.3e}"
.format(epc_est_fm,epc_est_a,epc_calib ))
print("± sigma ± {0:1.3e} ± {1:1.3e} "
.format(epc_est_fm_err, epc_est_a_err))
def calc_chisquare(ydata, sigma, ycalc):
r = ydata - ycalc
chisq = np.sum((r / sigma) ** 2)
return chisq
# prepare box for GSP plot
# perform reduced χ² value calculation for Bayes hierarchical
mean_h = trace_h.posterior.mean(dim=['chain', 'draw'])
theta_stacked = mean_h.θ.values
NDF_h = len(lengths)*2 - 4 - 1 # (-1 is for σ_Beta)
chisq_h = calc_chisquare(y_mean, sigma_y, theta_stacked)/NDF_h
texto_0 = " alpha = {0:7.4f} ± {1:1.4e}"\
.format(azt_summary['mean']['Tying_Parameters[1]'],
azt_summary['sd']['Tying_Parameters[1]'])
texto_1 =" alpha_c = {0:7.4f} ± {1:1.4e}"\
.format(azt_summary['mean']['Tying_Parameters[2]'],
azt_summary['sd']['Tying_Parameters[2]'])
texto_2 = " EPC = {0:1.4e} ± {1:1.4e}"\
.format(azt_summary['mean']['EPC'],
azt_summary['sd']['EPC'])
texto_3 = " Fit χ² = {0:7.4f} "\
.format(chisq_h)
texto = texto_0 + "\n" + texto_1 + "\n" + texto_2 + "\n" + texto_3
# prepare data for GSP plot
# get the calculated GSP values
with h_model:
hdi_prob = .94
# (hdi_prob=.94 is default, roughly coreresponding to 2σ)
theta_summary = az.summary(trace_h, round_to=12, hdi_prob = hdi_prob,
var_names = ["θ"], kind="stats")
y1 = theta_summary.values[:,0][0:len(lengths)]
y2 = theta_summary.values[:,0][len(lengths):len(lengths)*2]
HDI = False # make your choice here
if HDI:
# HDI values as bounds
bounds_rmk = "(shown bounds are "+ str(int(100*hdi_prob)) + "% HDI)"
y1_min = theta_summary.values[:,2][0:len(lengths)]
y2_min = theta_summary.values[:,2][len(lengths):len(lengths)*2]
y1_max = theta_summary.values[:,3][0:len(lengths)]
y2_max = theta_summary.values[:,3][len(lengths):len(lengths)*2]
else:
# two sigma bounds for plot
bounds_rmk = "(shown bounds are ± two σ)"
sy = theta_summary.values[:,1]
y1_min = y1 - sy[0:len(lengths)]*2
y1_max = y1 + sy[0:len(lengths)]*2
y2_min = y2 - sy[len(lengths):len(lengths)*2]*2
y2_max = y2 + sy[len(lengths):len(lengths)*2]*2
# GSP plot
import matplotlib.pyplot as plt # if not yet imported
font = {'family' : 'DejaVu Sans',
'weight' : 'normal',
'size' : 14}
plt.rc('font', **font)
fig, plt = plt.subplots(1, 1, figsize = [8,5])
plt.set_ylabel("P(0)")
plt.set_xlabel("Clifford Length")
plt.legend(("Standard" , "Interleaved" ),
loc = 'center right', fontsize=10)
plt.plot(lengths,y1,color="purple", marker="o", lw = 0.75)
#plt.errorbar(lengths,y1,2*sy[0:len(lengths)],
#color="purple", marker='o')
plt.fill_between(lengths, y1_min, y1_max,
alpha=.2, edgecolor='purple', facecolor= 'r')
plt.plot(lengths,y2,color="cyan", marker='^', lw = 0.75)
#plt.errorbar(lengths,y2,2*sy[len(lengths):2*len(lengths)],
#color="cyan", marker='^')
plt.fill_between(lengths, y2_min, y2_max,
alpha=.2, edgecolor='cyan', facecolor= 'cyan')
for i_seed in range(num_samples):
plt.scatter(lengths, Y1[i_seed,:]/shots,
label = "data", marker="x",color="grey")
plt.scatter(lengths, Y2[i_seed,:]/shots,
label = "data", marker="+",color="grey")
plt.legend(("Standard" , "Interleaved" ),
loc = 'center right', fontsize=10)
plt.text(lengths[-1]*0.3,0.75, texto, bbox=dict(facecolor='white'))
plt.grid()
plt.set_title(experiment_type +', ' + interleaved_gate\
+ str(physical_qubits)\
+', backend: '+backend.name()+\
"\n Bayesian "+model+" "+ bounds_rmk,
fontsize=14);
# View result data for frequentist model
display(int_expdata2.figure(0))
|
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 initialize instruction.
"""
from numpy import array, sqrt
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
def initialize_circuits_w_1(init_state, final_measure=True):
"""Initialize test circuits"""
circuits = []
qr = QuantumRegister(3)
if final_measure:
cr = ClassicalRegister(3)
regs = (qr, cr)
else:
regs = (qr, )
# Start with |+++> state
# Initialize qr[i] to |1> for i=0,1,2
for qubit in range(3):
circuit = QuantumCircuit(*regs)
circuit.h(qr[0])
circuit.h(qr[1])
circuit.h(qr[2])
circuit.initialize(init_state, [qr[qubit]])
if final_measure:
circuit.barrier(qr)
circuit.measure(qr, cr)
circuits.append(circuit)
return circuits
def initialize_circuits_w_2(init_state, final_measure=True):
"""Initialize test circuits"""
circuits = []
qr = QuantumRegister(3)
if final_measure:
cr = ClassicalRegister(3)
regs = (qr, cr)
else:
regs = (qr, )
# Start with |+++> state
# Initialize qr[i] to |1> and qr[j] to |0>
# For [i,j] = [0,1], [1, 0], [0, 2], [2, 0], [1, 2], [2, 1]
for qubit_i in range(3):
for qubit_j in range(3):
if (qubit_i != qubit_j):
circuit = QuantumCircuit(*regs)
circuit.h(qr[0])
circuit.h(qr[1])
circuit.h(qr[2])
circuit.initialize(init_state, [qr[qubit_i], qr[qubit_j]])
if final_measure:
circuit.barrier(qr)
circuit.measure(qr, cr)
circuits.append(circuit)
return circuits
def initialize_circuits_1(final_measure=True):
"""Initialize test circuits"""
circuits = []
qr = QuantumRegister(3)
if final_measure:
cr = ClassicalRegister(3)
regs = (qr, cr)
else:
regs = (qr, )
# Start with |+++> state
# Initialize qr[i] to |1> for i=0,1,2
for qubit in range(3):
circuit = QuantumCircuit(*regs)
circuit.h(qr[0])
circuit.h(qr[1])
circuit.h(qr[2])
circuit.initialize([0, 1], [qr[qubit]])
if final_measure:
circuit.barrier(qr)
circuit.measure(qr, cr)
circuits.append(circuit)
# Start with |+++> state
# Initialize qr[i] to |1> and qr[j] to |0>
# For [i,j] = [0,1], [1, 0], [0, 2], [2, 0], [1, 2], [2, 1]
for qubit_i in range(3):
for qubit_j in range(3):
if (qubit_i != qubit_j):
circuit = QuantumCircuit(*regs)
circuit.h(qr[0])
circuit.h(qr[1])
circuit.h(qr[2])
circuit.initialize([0, 1, 0, 0], [qr[qubit_i], qr[qubit_j]])
if final_measure:
circuit.barrier(qr)
circuit.measure(qr, cr)
circuits.append(circuit)
# Start with |+++> state
# Initialize qr[i] to |1>, qr[j] to |0> and qr[k] to |->
# For [i,j,k] = [0, 1, 2], [0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]
for qubit_i in range(3):
for qubit_j in range(3):
for qubit_k in range(3):
if (qubit_i != qubit_j) & (qubit_i != qubit_k) & (qubit_k != qubit_j):
circuit = QuantumCircuit(*regs)
circuit.h(qr[0])
circuit.h(qr[1])
circuit.h(qr[2])
circuit.initialize([0, 1, 0, 0, 0, -1, 0, 0] / sqrt(2), \
[qr[qubit_i], qr[qubit_j], qr[qubit_k]])
if final_measure:
circuit.barrier(qr)
circuit.measure(qr, cr)
circuits.append(circuit)
return circuits
def initialize_counts_1(shots, hex_counts=True):
"""Initialize test circuits reference counts."""
targets = []
if hex_counts:
# Initialize 0 to |1> from |+++>
targets.append({'0x1': shots/4,
'0x3': shots/4,
'0x5': shots/4,
'0x7': shots/4})
# Initialize 1 to |1> from |+++>
targets.append({'0x2': shots/4,
'0x3': shots/4,
'0x6': shots/4,
'0x7': shots/4})
# Initialize 2 to |1> from |+++>
targets.append({'0x4': shots/4,
'0x5': shots/4,
'0x6': shots/4,
'0x7': shots/4})
# Initialize 0,1 to |01> from |+++>
targets.append({'0x1': shots/2,
'0x5': shots/2})
# Initialize 0,2 to |01> from |+++>
targets.append({'0x1': shots/2,
'0x3': shots/2})
# Initialize 1,0 to |01> from |+++>
targets.append({'0x2': shots/2,
'0x6': shots/2})
# Initialize 1,2 to |01> from |+++>
targets.append({'0x2': shots/2,
'0x3': shots/2})
# Initialize 2,0 to |01> from |+++>
targets.append({'0x4': shots/2,
'0x6': shots/2})
# Initialize 2,1 to |01> from |+++>
targets.append({'0x4': shots/2,
'0x5': shots/2})
# Initialize 0,1,2 to |01-> from |+++>
targets.append({'0x1': shots/2,
'0x5': shots/2})
# Initialize 0,2,1 to |01-> from |+++>
targets.append({'0x1': shots/2,
'0x3': shots/2})
# Initialize 1,0,2 to |01-> from |+++>
targets.append({'0x2': shots/2,
'0x6': shots/2})
# Initialize 1,2,0 to |01-> from |+++>
targets.append({'0x2': shots/2,
'0x3': shots/2})
# Initialize 2,0,1 to |01-> from |+++>
targets.append({'0x4': shots/2,
'0x6': shots/2})
# Initialize 2,1,0 to |01-> from |+++>
targets.append({'0x4': shots/2,
'0x5': shots/2})
else:
# Initialize 0 to |1> from |+++>
targets.append({'001': shots/4,
'011': shots/4,
'101': shots/4,
'111': shots/4})
# Initialize 1 to |1> from |+++>
targets.append({'010': shots/4,
'011': shots/4,
'110': shots/4,
'111': shots/4})
# Initialize 2 to |1> from |+++>
targets.append({'100': shots/4,
'101': shots/4,
'110': shots/4,
'111': shots/4})
# Initialize 0,1 to |01> from |+++>
targets.append({'001': shots/2,
'101': shots/2})
# Initialize 0,2 to |01> from |+++>
targets.append({'001': shots/2,
'011': shots/2})
# Initialize 1,0 to |01> from |+++>
targets.append({'010': shots/2,
'110': shots/2})
# Initialize 1,2 to |01> from |+++>
targets.append({'010': shots/2,
'011': shots/2})
# Initialize 2,0 to |01> from |+++>
targets.append({'100': shots/2,
'110': shots/2})
# Initialize 2,1 to |01> from |+++>
targets.append({'100': shots/2,
'101': shots/2})
# Initialize 0,1,2 to |01-> from |+++>
targets.append({'001': shots/2,
'101': shots/2})
# Initialize 0,2,1 to |01-> from |+++>
targets.append({'001': shots/2,
'011': shots/2})
# Initialize 1,0,2 to |01-> from |+++>
targets.append({'010': shots/2,
'110': shots/2})
# Initialize 1,2,0 to |01-> from |+++>
targets.append({'010': shots/2,
'011': shots/2})
# Initialize 2,0,1 to |01-> from |+++>
targets.append({'100': shots/2,
'110': shots/2})
# Initialize 2,1,0 to |01-> from |+++>
targets.append({'100': shots/2,
'101': shots/2})
return targets
def initialize_statevector_1():
"""Initialize test circuits reference counts."""
targets = []
# Start with |+++> state
# Initialize qr[i] to |1> for i=0,1,2
targets.append(array([0. +0.j, 0.5+0.j, 0. +0.j, 0.5+0.j, 0. +0.j, 0.5+0.j, 0. +0.j, 0.5+0.j]))
targets.append(array([0. +0.j, 0. +0.j, 0.5+0.j, 0.5+0.j, 0. +0.j, 0. +0.j, 0.5+0.j, 0.5+0.j]))
targets.append(array([0. +0.j, 0. +0.j, 0. +0.j, 0. +0.j, 0.5+0.j, 0.5+0.j, 0.5+0.j, 0.5+0.j]))
# Start with |+++> state
# Initialize qr[i] to |1> and qr[j] to |0>
# For [i,j] = [0,1], [1, 0], [0, 2], [2, 0], [1, 2], [2, 1]
targets.append(array([0. + 0.j, 1.0 + 0.j, 0. + 0.j, 0. + 0.j, \
0. + 0.j, 1.0 + 0.j, 0. + 0.j, 0. + 0.j] / sqrt(2)))
targets.append(array([0. + 0.j, 1.0 + 0.j, 0. + 0.j, 1.0 + 0.j, \
0. + 0.j, 0. + 0.j, 0. + 0.j, 0. + 0.j] / sqrt(2)))
targets.append(array([0. + 0.j, 0. + 0.j, 1.0 + 0.j, 0. + 0.j, \
0. + 0.j, 0. + 0.j, 1.0 + 0.j, 0. + 0.j] / sqrt(2)))
targets.append(array([0. + 0.j, 0. + 0.j, 1.0 + 0.j, 1.0 + 0.j, \
0. + 0.j, 0. + 0.j, 0 + 0.j, 0. + 0.j] / sqrt(2)))
targets.append(array([0. + 0.j, 0. + 0.j, 0 + 0.j, 0. + 0.j, \
1.0 + 0.j, 0. + 0.j, 1.0 + 0.j, 0. + 0.j] / sqrt(2)))
targets.append(array([0. + 0.j, 0. + 0.j, 0 + 0.j, 0. + 0.j, \
1.0 + 0.j, 1.0 + 0.j, 0. + 0.j, 0. + 0.j] / sqrt(2)))
# Start with |+++> state
# Initialize qr[i] to |1>, qr[j] to |0> and qr[k] to |->
# For [i,j,k] = [0, 1, 2], [0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]
targets.append(array([0. + 0.j, 1.0 + 0.j, 0. + 0.j, 0. + 0.j, \
0. + 0.j, -1.0 + 0.j, 0. + 0.j, 0. + 0.j] / sqrt(2)))
targets.append(array([0. + 0.j, 1.0 + 0.j, 0. + 0.j, -1.0 + 0.j,
0. + 0.j, 0. + 0.j, 0. + 0.j, 0. + 0.j] / sqrt(2)))
targets.append(array([0. + 0.j, 0. + 0.j, 1.0 + 0.j, 0. + 0.j, \
0. + 0.j, 0. + 0.j, -1.0 + 0.j, 0. + 0.j] / sqrt(2)))
targets.append(array([0. + 0.j, 0. + 0.j, 1.0 + 0.j, -1.0 + 0.j, \
0. + 0.j, 0. + 0.j, 0. + 0.j, 0. + 0.j] / sqrt(2)))
targets.append(array([0. + 0.j, 0. + 0.j, 0. + 0.j, 0. + 0.j, \
1.0 + 0.j, 0. + 0.j, -1.0 + 0.j, 0. + 0.j] / sqrt(2)))
targets.append(array([0. + 0.j, 0. + 0.j, 0. + 0.j, 0. + 0.j, \
1.0 + 0.j, -1.0 + 0.j, 0. + 0.j, 0. + 0.j] / sqrt(2)))
return targets
def initialize_circuits_2(final_measure=True):
"""Initialize test circuits"""
circuits = []
qr = QuantumRegister(2)
if final_measure:
cr = ClassicalRegister(2)
regs = (qr, cr)
else:
regs = (qr, )
# Initialize 0 to |1> from |++>
circuit = QuantumCircuit(*regs)
circuit.h(qr)
circuit.initialize([0, 1], [qr[0]])
if final_measure:
circuit.barrier(qr)
circuit.measure(qr, cr)
circuits.append(circuit)
# Initialize 1 to |1> from |++>
circuit = QuantumCircuit(*regs)
circuit.h(qr)
circuit.initialize([0, 1], [qr[1]])
if final_measure:
circuit.barrier(qr)
circuit.measure(qr, cr)
circuits.append(circuit)
return circuits
def initialize_counts_2(shots, hex_counts=True):
"""Initialize test circuits reference counts."""
targets = []
if hex_counts:
# Initialize 0 to |1> from |++>
targets.append({'0x1': shots / 2, '0x3': shots / 2})
# Initialize 1 to |1> from |++>
targets.append({'0x2': shots / 2, '0x3': shots / 2})
else:
# Initialize 0 to |1> from |++>
targets.append({'01': shots / 2, '11': shots / 2})
# Initialize 1 to |1> from |++>
targets.append({'10': shots / 2, '11': shots / 2})
return targets
def initialize_statevector_2():
"""Initialize test circuits reference counts."""
targets = []
# Initialize 0 to |1> from |++>
targets.append(array([0, 1, 0, 1]) / sqrt(2))
# Initialize 1 to |1> from |++>
targets.append(array([0, 0, 1, 1]) / sqrt(2))
return targets
# ==========================================================================
# Sampling optimization
# ==========================================================================
def initialize_sampling_optimization():
"""Test sampling optimization"""
qr = QuantumRegister(2)
cr = ClassicalRegister(2)
qc = QuantumCircuit(qr, cr)
# The optimization should not be triggerred
# because the initialize operation performs randomizations
qc.h(qr[0])
qc.cx(qr[0], qr[1])
qc.initialize([1, 0], [qr[0]])
qc.measure(qr, cr)
return [qc]
def initialize_counts_sampling_optimization(shots, hex_counts=True):
"""Sampling optimization counts"""
if hex_counts:
return [{'0x0': shots/2, '0x2': shots/2}]
else:
return [{'0x00': shots/2, '0x10': shots/2}]
|
https://github.com/zapata-engineering/orquestra-qiskit
|
zapata-engineering
|
import os
from functools import partial
from unittest.mock import Mock
import pytest
from orquestra.quantum.api import EstimationTask
from orquestra.quantum.api.circuit_runner_contracts import (
CIRCUIT_RUNNER_CONTRACTS,
circuit_runner_gate_compatibility_contracts,
)
from orquestra.quantum.circuits import CNOT, Circuit, H, X
from orquestra.quantum.estimation import estimate_expectation_values_by_averaging
from orquestra.quantum.measurements import ExpectationValues
from orquestra.quantum.operators import PauliTerm
from qiskit import QiskitError, execute
from qiskit.transpiler import CouplingMap
from qiskit_aer import Aer
from orquestra.integrations.qiskit.noise import get_qiskit_noise_model
from orquestra.integrations.qiskit.runner import QiskitRunner
def _test_id(val):
return val.backend.name()
@pytest.fixture
def aer_backend_with_real_shots_limit():
"""Sophisticated AerBackend mock that actually respects reported limits."""
backend = Aer.get_backend("aer_simulator")
max_shots = backend.configuration().max_shots
old_run = backend.run
def _run(*args, **kwargs):
if kwargs.get("shots", 0) > max_shots:
raise QiskitError("Maximum number of shots in experiment_exceeded")
return old_run(*args, **kwargs)
backend.run = _run
return backend
COMPATIBLE_BACKENDS = (
# This list contains names of all possible AerBackends.
# The ones that are not working are commented out so that we
# remember why they are not used in the tests
"aer_simulator",
"aer_simulator_statevector",
"aer_simulator_density_matrix",
# "aer_simulator_stabilizer", # Has limited gateset
"aer_simulator_matrix_product_state",
# "aer_simulator_extended_stabilizer", # Technically compatible, incredibly slow
# "aer_simulator_unitary", # Does not support measurements
# "aer_simulator_superop", # Does not support measurements
# "qasm_simulator", # Compatible, but deprecated
# "statevector_simulator", # Compatible, but deprecated
# "unitary_simulator", # Does not support measurements
# "pulse_simulator" # Does not support measurements
)
@pytest.mark.parametrize(
"runner",
[*[QiskitRunner(Aer.get_backend(name)) for name in COMPATIBLE_BACKENDS]],
ids=_test_id,
)
@pytest.mark.parametrize("contract", CIRCUIT_RUNNER_CONTRACTS)
def test_qiskit_runner_fulfills_circuit_runner_contracts(runner, contract):
assert contract(runner)
@pytest.mark.parametrize(
"contract",
circuit_runner_gate_compatibility_contracts(
gates_to_exclude=["RH", "XY"], exp_val_spread=1.5
),
)
@pytest.mark.parametrize(
"runner",
[
*[
QiskitRunner(
Aer.get_backend(name),
execute_function=partial(execute, seed_simulator=1234),
)
for name in COMPATIBLE_BACKENDS
]
],
ids=_test_id,
)
def test_qiskit_runner_uses_correct_gate_definitions(runner, contract):
assert contract(runner)
def test_qiskit_runner_can_run_job_with_sample_size_exceeding_backends_limit(
aer_backend_with_real_shots_limit,
):
runner = QiskitRunner(aer_backend_with_real_shots_limit)
max_shots = runner.backend.configuration().max_shots
circuit = Circuit([H(0)])
measurements = runner.run_and_measure(circuit, n_samples=max_shots + 1)
assert len(measurements.bitstrings) >= max_shots + 1
@pytest.fixture(params=["aer_simulator"])
def noisy_simulator(request):
ibmq_api_token = os.getenv("ZAPATA_IBMQ_API_TOKEN")
noise_model, connectivity = get_qiskit_noise_model(
"ibm_kyoto", api_token=ibmq_api_token
)
backend = Aer.get_backend(request.param)
return QiskitRunner(backend, noise_model=noise_model, coupling_map=connectivity)
@pytest.mark.parametrize("num_flips", [10, 50])
def test_expectation_value_with_noisy_simulator(noisy_simulator, num_flips):
# Initialize in |1> state and flip even number of times.
# Thus, we and up in |1> state but decoherence is allowed to take effect
circuit = Circuit([X(0) for _ in range(num_flips + 1)])
qubit_operator = PauliTerm("Z0")
n_samples = 8192
estimation_tasks = [EstimationTask(qubit_operator, circuit, n_samples)]
expectation_values = estimate_expectation_values_by_averaging(
noisy_simulator, estimation_tasks
)[0]
assert isinstance(expectation_values, ExpectationValues)
assert len(expectation_values.values) == 1
assert -1 < expectation_values.values[0] < 0.0
def test_qiskit_runner_passes_coupling_map_to_execute_function():
circuit = Circuit([X(0), CNOT(1, 2)])
coupling_map = CouplingMap([(0, 2), (0, 1)])
execute_func = Mock(wraps=execute)
runner = QiskitRunner(
Aer.get_backend("aer_simulator_statevector"),
coupling_map=coupling_map,
execute_function=execute_func,
)
runner.run_and_measure(circuit, n_samples=10)
assert execute_func.call_args.kwargs["coupling_map"] == coupling_map
@pytest.mark.parametrize(
"runner",
[
*[
QiskitRunner(Aer.get_backend(name), discard_extra_measurements=True)
for name in COMPATIBLE_BACKENDS
]
],
ids=_test_id,
)
def test_qiskit_runner_discards_extra_measurements_exact_num_measurements_is_true(
runner: QiskitRunner,
):
circuits = [Circuit([X(0), CNOT(0, 1)])] * 3
n_samples = [5, 10, 15]
result = runner.run_batch_and_measure(circuits, n_samples=n_samples)
assert [len(r.bitstrings) for r in result] == n_samples
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import numpy as np
# Import Qiskit
from qiskit import QuantumCircuit, transpile
from qiskit_aer import AerSimulator
# Construct quantum circuit
circ = QuantumCircuit(2, 2)
circ.h(0)
circ.cx(0, 1)
circ.measure([0,1], [0,1])
# Select the AerSimulator from the Aer provider
simulator = AerSimulator(method='matrix_product_state')
# Run and get counts, using the matrix_product_state method
tcirc = transpile(circ, simulator)
result = simulator.run(tcirc).result()
counts = result.get_counts(0)
counts
circ = QuantumCircuit(2, 2)
circ.h(0)
circ.cx(0, 1)
# Define a snapshot that shows the current state vector
circ.save_statevector(label='my_sv')
circ.save_matrix_product_state(label='my_mps')
circ.measure([0,1], [0,1])
# Execute and get saved data
tcirc = transpile(circ, simulator)
result = simulator.run(tcirc).result()
data = result.data(0)
#print the result data
data
num_qubits = 50
circ = QuantumCircuit(num_qubits, num_qubits)
# Create EPR state
circ.h(0)
for i in range (0, num_qubits-1):
circ.cx(i, i+1)
# Measure
circ.measure(range(num_qubits), range(num_qubits))
tcirc = transpile(circ, simulator)
result = simulator.run(tcirc).result()
print("Time taken: {} sec".format(result.time_taken))
result.get_counts()
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
#
# you may use python
#
|
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/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import numpy as np
from qiskit import QuantumCircuit
from qiskit.providers.fake_provider import FakeVigoV2
backend = FakeVigoV2()
qc = QuantumCircuit(2, 1)
qc.h(0)
qc.x(1)
qc.cp(np.pi/4, 0, 1)
qc.h(0)
qc.measure([0], [0])
qc.draw(output='mpl')
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
qc = QuantumCircuit(12)
for idx in range(5):
qc.h(idx)
qc.cx(idx, idx+5)
qc.cx(1, 7)
qc.x(8)
qc.cx(1, 9)
qc.x(7)
qc.cx(1, 11)
qc.swap(6, 11)
qc.swap(6, 9)
qc.swap(6, 10)
qc.x(6)
qc.draw('mpl')
|
https://github.com/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.
"""
Initialize test.
"""
import math
import unittest
import numpy as np
from ddt import ddt, data
from qiskit import QuantumCircuit
from qiskit import QuantumRegister
from qiskit import ClassicalRegister
from qiskit import transpile
from qiskit import execute, assemble, BasicAer
from qiskit.quantum_info import state_fidelity, Statevector, Operator
from qiskit.exceptions import QiskitError
from qiskit.test import QiskitTestCase
from qiskit.extensions.quantum_initializer import Initialize
@ddt
class TestInitialize(QiskitTestCase):
"""Qiskit Initialize tests."""
_desired_fidelity = 0.99
def test_uniform_superposition(self):
"""Initialize a uniform superposition on 2 qubits."""
desired_vector = [0.5, 0.5, 0.5, 0.5]
qr = QuantumRegister(2, "qr")
qc = QuantumCircuit(qr)
qc.initialize(desired_vector, [qr[0], qr[1]])
job = execute(qc, BasicAer.get_backend("statevector_simulator"))
result = job.result()
statevector = result.get_statevector()
fidelity = state_fidelity(statevector, desired_vector)
self.assertGreater(
fidelity,
self._desired_fidelity,
f"Initializer has low fidelity {fidelity:.2g}.",
)
def test_deterministic_state(self):
"""Initialize a computational-basis state |01> on 2 qubits."""
desired_vector = [0, 1, 0, 0]
qr = QuantumRegister(2, "qr")
qc = QuantumCircuit(qr)
qc.initialize(desired_vector, [qr[0], qr[1]])
job = execute(qc, BasicAer.get_backend("statevector_simulator"))
result = job.result()
statevector = result.get_statevector()
fidelity = state_fidelity(statevector, desired_vector)
self.assertGreater(
fidelity,
self._desired_fidelity,
f"Initializer has low fidelity {fidelity:.2g}.",
)
def test_statevector(self):
"""Initialize gates from a statevector."""
# ref: https://github.com/Qiskit/qiskit-terra/issues/5134 (footnote)
desired_vector = [0, 0, 0, 1]
qc = QuantumCircuit(2)
statevector = Statevector.from_label("11")
qc.initialize(statevector, [0, 1])
self.assertEqual(qc.data[0].operation.params, desired_vector)
def test_bell_state(self):
"""Initialize a Bell state on 2 qubits."""
desired_vector = [1 / math.sqrt(2), 0, 0, 1 / math.sqrt(2)]
qr = QuantumRegister(2, "qr")
qc = QuantumCircuit(qr)
qc.initialize(desired_vector, [qr[0], qr[1]])
job = execute(qc, BasicAer.get_backend("statevector_simulator"))
result = job.result()
statevector = result.get_statevector()
fidelity = state_fidelity(statevector, desired_vector)
self.assertGreater(
fidelity,
self._desired_fidelity,
f"Initializer has low fidelity {fidelity:.2g}.",
)
def test_ghz_state(self):
"""Initialize a GHZ state on 3 qubits."""
desired_vector = [1 / math.sqrt(2), 0, 0, 0, 0, 0, 0, 1 / math.sqrt(2)]
qr = QuantumRegister(3, "qr")
qc = QuantumCircuit(qr)
qc.initialize(desired_vector, [qr[0], qr[1], qr[2]])
job = execute(qc, BasicAer.get_backend("statevector_simulator"))
result = job.result()
statevector = result.get_statevector()
fidelity = state_fidelity(statevector, desired_vector)
self.assertGreater(
fidelity,
self._desired_fidelity,
f"Initializer has low fidelity {fidelity:.2g}.",
)
def test_initialize_register(self):
"""Initialize one register out of two."""
desired_vector = [1 / math.sqrt(2), 0, 0, 1 / math.sqrt(2)]
qr = QuantumRegister(2, "qr")
qr2 = QuantumRegister(2, "qr2")
qc = QuantumCircuit(qr, qr2)
qc.initialize(desired_vector, qr)
job = execute(qc, BasicAer.get_backend("statevector_simulator"))
result = job.result()
statevector = result.get_statevector()
fidelity = state_fidelity(statevector, np.kron([1, 0, 0, 0], desired_vector))
self.assertGreater(
fidelity,
self._desired_fidelity,
f"Initializer has low fidelity {fidelity:.2g}.",
)
def test_initialize_one_by_one(self):
"""Initializing qubits individually into product state same as initializing the pair."""
qubit_0_state = [1, 0]
qubit_1_state = [1 / math.sqrt(2), 1 / math.sqrt(2)]
qr = QuantumRegister(2, "qr")
qc_a = QuantumCircuit(qr)
qc_a.initialize(np.kron(qubit_1_state, qubit_0_state), qr)
qc_b = QuantumCircuit(qr)
qc_b.initialize(qubit_0_state, [qr[0]])
qc_b.initialize(qubit_1_state, [qr[1]])
job = execute([qc_a, qc_b], BasicAer.get_backend("statevector_simulator"))
result = job.result()
statevector_a = result.get_statevector(0)
statevector_b = result.get_statevector(1)
fidelity = state_fidelity(statevector_a, statevector_b)
self.assertGreater(
fidelity,
self._desired_fidelity,
f"Initializer has low fidelity {fidelity:.2g}.",
)
def test_single_qubit(self):
"""Initialize a single qubit to a weighted superposition state."""
desired_vector = [1 / math.sqrt(3), math.sqrt(2) / math.sqrt(3)]
qr = QuantumRegister(1, "qr")
qc = QuantumCircuit(qr)
qc.initialize(desired_vector, [qr[0]])
job = execute(qc, BasicAer.get_backend("statevector_simulator"))
result = job.result()
statevector = result.get_statevector()
fidelity = state_fidelity(statevector, desired_vector)
self.assertGreater(
fidelity,
self._desired_fidelity,
f"Initializer has low fidelity {fidelity:.2g}.",
)
def test_random_3qubit(self):
"""Initialize to a non-trivial 3-qubit state."""
desired_vector = [
1 / math.sqrt(16) * complex(0, 1),
1 / math.sqrt(8) * complex(1, 0),
1 / math.sqrt(16) * complex(1, 1),
0,
0,
1 / math.sqrt(8) * complex(1, 2),
1 / math.sqrt(16) * complex(1, 0),
0,
]
qr = QuantumRegister(3, "qr")
qc = QuantumCircuit(qr)
qc.initialize(desired_vector, [qr[0], qr[1], qr[2]])
job = execute(qc, BasicAer.get_backend("statevector_simulator"))
result = job.result()
statevector = result.get_statevector()
fidelity = state_fidelity(statevector, desired_vector)
self.assertGreater(
fidelity,
self._desired_fidelity,
f"Initializer has low fidelity {fidelity:.2g}.",
)
def test_random_4qubit(self):
"""Initialize to a non-trivial 4-qubit state."""
desired_vector = [
1 / math.sqrt(4) * complex(0, 1),
1 / math.sqrt(8) * complex(1, 0),
0,
0,
0,
0,
0,
0,
1 / math.sqrt(8) * complex(1, 0),
1 / math.sqrt(8) * complex(0, 1),
0,
0,
0,
0,
1 / math.sqrt(4) * complex(1, 0),
1 / math.sqrt(8) * complex(1, 0),
]
qr = QuantumRegister(4, "qr")
qc = QuantumCircuit(qr)
qc.initialize(desired_vector, [qr[0], qr[1], qr[2], qr[3]])
job = execute(qc, BasicAer.get_backend("statevector_simulator"))
result = job.result()
statevector = result.get_statevector()
fidelity = state_fidelity(statevector, desired_vector)
self.assertGreater(
fidelity,
self._desired_fidelity,
f"Initializer has low fidelity {fidelity:.2g}.",
)
def test_malformed_amplitudes(self):
"""Initializing to a vector with 3 amplitudes fails."""
desired_vector = [1 / math.sqrt(3), math.sqrt(2) / math.sqrt(3), 0]
qr = QuantumRegister(2, "qr")
qc = QuantumCircuit(qr)
self.assertRaises(QiskitError, qc.initialize, desired_vector, [qr[0], qr[1]])
def test_non_unit_probability(self):
"""Initializing to a vector with probabilities not summing to 1 fails."""
desired_vector = [1, 1]
qr = QuantumRegister(2, "qr")
qc = QuantumCircuit(qr)
self.assertRaises(QiskitError, qc.initialize, desired_vector, [qr[0], qr[1]])
def test_normalize(self):
"""Test initializing with a non-normalized vector is normalized, if specified."""
desired_vector = [1, 1]
normalized = np.asarray(desired_vector) / np.linalg.norm(desired_vector)
qc = QuantumCircuit(1)
qc.initialize(desired_vector, [0], normalize=True)
op = qc.data[0].operation
self.assertAlmostEqual(np.linalg.norm(op.params), 1)
self.assertEqual(Statevector(qc), Statevector(normalized))
def test_wrong_vector_size(self):
"""Initializing to a vector with a size different to the qubit parameter length.
See https://github.com/Qiskit/qiskit-terra/issues/2372"""
qr = QuantumRegister(2)
random_state = [
1 / math.sqrt(4) * complex(0, 1),
1 / math.sqrt(8) * complex(1, 0),
0,
1 / math.sqrt(8) * complex(1, 0),
1 / math.sqrt(8) * complex(0, 1),
0,
1 / math.sqrt(4) * complex(1, 0),
1 / math.sqrt(8) * complex(1, 0),
]
qc = QuantumCircuit(qr)
self.assertRaises(QiskitError, qc.initialize, random_state, qr[0:2])
def test_initialize_middle_circuit(self):
"""Reset + initialize gives the correct statevector."""
desired_vector = [0.5, 0.5, 0.5, 0.5]
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(2, "cr")
qc = QuantumCircuit(qr, cr)
qc.h(qr[0])
qc.cx(qr[0], qr[1])
qc.reset(qr[0])
qc.reset(qr[1])
qc.initialize(desired_vector, [qr[0], qr[1]])
qc.measure(qr, cr)
# statevector simulator does not support reset
shots = 2000
threshold = 0.005 * shots
job = execute(qc, BasicAer.get_backend("qasm_simulator"), shots=shots, seed_simulator=42)
result = job.result()
counts = result.get_counts()
target = {"00": shots / 4, "01": shots / 4, "10": shots / 4, "11": shots / 4}
self.assertDictAlmostEqual(counts, target, threshold)
def test_math_amplitudes(self):
"""Initialize to amplitudes given by math expressions"""
desired_vector = [
0,
math.cos(math.pi / 3) * complex(0, 1) / math.sqrt(4),
math.sin(math.pi / 3) / math.sqrt(4),
0,
0,
0,
0,
0,
1 / math.sqrt(8) * complex(1, 0),
1 / math.sqrt(8) * complex(0, 1),
0,
0,
0,
0,
1 / math.sqrt(4),
1 / math.sqrt(4) * complex(0, 1),
]
qr = QuantumRegister(4, "qr")
qc = QuantumCircuit(qr)
qc.initialize(desired_vector, [qr[0], qr[1], qr[2], qr[3]])
job = execute(qc, BasicAer.get_backend("statevector_simulator"))
result = job.result()
statevector = result.get_statevector()
fidelity = state_fidelity(statevector, desired_vector)
self.assertGreater(
fidelity,
self._desired_fidelity,
f"Initializer has low fidelity {fidelity:.2g}.",
)
def test_combiner(self):
"""Combining two circuits containing initialize."""
desired_vector_1 = [1.0 / math.sqrt(2), 1.0 / math.sqrt(2)]
desired_vector_2 = [1.0 / math.sqrt(2), -1.0 / math.sqrt(2)]
qr = QuantumRegister(1, "qr")
cr = ClassicalRegister(1, "cr")
qc1 = QuantumCircuit(qr, cr)
qc1.initialize(desired_vector_1, [qr[0]])
qc2 = QuantumCircuit(qr, cr)
qc2.initialize(desired_vector_2, [qr[0]])
job = execute(qc1.compose(qc2), BasicAer.get_backend("statevector_simulator"))
result = job.result()
quantum_state = result.get_statevector()
fidelity = state_fidelity(quantum_state, desired_vector_2)
self.assertGreater(
fidelity,
self._desired_fidelity,
f"Initializer has low fidelity {fidelity:.2g}.",
)
def test_equivalence(self):
"""Test two similar initialize instructions evaluate to equal."""
desired_vector = [0.5, 0.5, 0.5, 0.5]
qr = QuantumRegister(2, "qr")
qc1 = QuantumCircuit(qr, name="circuit")
qc1.initialize(desired_vector, [qr[0], qr[1]])
qc2 = QuantumCircuit(qr, name="circuit")
qc2.initialize(desired_vector, [qr[0], qr[1]])
self.assertEqual(qc1, qc2)
def test_max_number_cnots(self):
"""
Check if the number of cnots <= 2^(n+1) - 2n (arXiv:quant-ph/0406176)
"""
num_qubits = 4
_optimization_level = 0
vector = np.array(
[
0.1314346 + 0.0j,
0.32078572 - 0.01542775j,
0.13146466 + 0.0945312j,
0.21090852 + 0.07935982j,
0.1700122 - 0.07905648j,
0.15570757 - 0.12309154j,
0.18039667 + 0.04904504j,
0.22227187 - 0.05055569j,
0.23573255 - 0.09894111j,
0.27307292 - 0.10372994j,
0.24162792 + 0.1090791j,
0.3115577 + 0.1211683j,
0.1851788 + 0.08679141j,
0.36226463 - 0.09940202j,
0.13863395 + 0.10558225j,
0.30767986 + 0.02073838j,
]
)
vector = vector / np.linalg.norm(vector)
qr = QuantumRegister(num_qubits, "qr")
circuit = QuantumCircuit(qr)
circuit.initialize(vector, qr)
b = transpile(
circuit,
basis_gates=["u1", "u2", "u3", "cx"],
optimization_level=_optimization_level,
seed_transpiler=42,
)
number_cnots = b.count_ops()["cx"]
max_cnots = 2 ** (num_qubits + 1) - 2 * num_qubits
self.assertLessEqual(number_cnots, max_cnots)
def test_from_labels(self):
"""Initialize from labels."""
desired_sv = Statevector.from_label("01+-lr")
qc = QuantumCircuit(6)
qc.initialize("01+-lr", range(6))
actual_sv = Statevector.from_instruction(qc)
self.assertTrue(desired_sv == actual_sv)
def test_from_int(self):
"""Initialize from int."""
desired_sv = Statevector.from_label("110101")
qc = QuantumCircuit(6)
qc.initialize(53, range(6))
actual_sv = Statevector.from_instruction(qc)
self.assertTrue(desired_sv == actual_sv)
def _remove_resets(self, circ):
circ.data = [instr for instr in circ.data if instr.operation.name != "reset"]
def test_global_phase_random(self):
"""Test global phase preservation with random state vectors"""
from qiskit.quantum_info.random import random_statevector
repeats = 5
for n_qubits in [1, 2, 4]:
for irep in range(repeats):
with self.subTest(i=f"{n_qubits}_{irep}"):
dim = 2**n_qubits
qr = QuantumRegister(n_qubits)
initializer = QuantumCircuit(qr)
target = random_statevector(dim)
initializer.initialize(target, qr)
uninit = initializer.data[0].operation.definition
self._remove_resets(uninit)
evolve = Statevector(uninit)
self.assertEqual(target, evolve)
def test_global_phase_1q(self):
"""Test global phase preservation with some simple 1q statevectors"""
target_list = [
Statevector([1j, 0]),
Statevector([0, 1j]),
Statevector([1j / np.sqrt(2), 1j / np.sqrt(2)]),
]
n_qubits = 1
dim = 2**n_qubits
qr = QuantumRegister(n_qubits)
for target in target_list:
with self.subTest(i=target):
initializer = QuantumCircuit(qr)
initializer.initialize(target, qr)
# need to get rid of the resets in order to use the Operator class
disentangler = Operator(initializer.data[0].operation.definition.data[1].operation)
zero = Statevector.from_int(0, dim)
actual = zero & disentangler
self.assertEqual(target, actual)
@data(2, "11", [1 / math.sqrt(2), 0, 0, 1 / math.sqrt(2)])
def test_decompose_contains_stateprep(self, state):
"""Test initialize decomposes to a StatePreparation and reset"""
qc = QuantumCircuit(2)
qc.initialize(state)
decom_circ = qc.decompose()
self.assertEqual(decom_circ.data[0].operation.name, "reset")
self.assertEqual(decom_circ.data[1].operation.name, "reset")
self.assertEqual(decom_circ.data[2].operation.name, "state_preparation")
def test_mutating_params(self):
"""Test mutating Initialize params correctly updates StatePreparation params"""
init = Initialize("11")
init.params = "00"
qr = QuantumRegister(2)
qc = QuantumCircuit(qr)
qc.append(init, qr)
decom_circ = qc.decompose()
self.assertEqual(decom_circ.data[2].operation.name, "state_preparation")
self.assertEqual(decom_circ.data[2].operation.params, ["0", "0"])
class TestInstructionParam(QiskitTestCase):
"""Test conversion of numpy type parameters."""
def test_diag(self):
"""Verify diagonal gate converts numpy.complex to complex."""
# ref: https://github.com/Qiskit/qiskit-aer/issues/696
diag = np.array([1 + 0j, 1 + 0j])
qc = QuantumCircuit(1)
qc.diagonal(list(diag), [0])
params = qc.data[0].operation.params
self.assertTrue(
all(isinstance(p, complex) and not isinstance(p, np.number) for p in params)
)
qobj = assemble(qc)
params = qobj.experiments[0].instructions[0].params
self.assertTrue(
all(isinstance(p, complex) and not isinstance(p, np.number) for p in params)
)
def test_init(self):
"""Verify initialize gate converts numpy.complex to complex."""
# ref: https://github.com/Qiskit/qiskit-terra/issues/4151
qc = QuantumCircuit(1)
vec = np.array([0, 0 + 1j])
qc.initialize(vec, 0)
params = qc.data[0].operation.params
self.assertTrue(
all(isinstance(p, complex) and not isinstance(p, np.number) for p in params)
)
qobj = assemble(qc)
params = qobj.experiments[0].instructions[0].params
self.assertTrue(
all(isinstance(p, complex) and not isinstance(p, np.number) for p in params)
)
if __name__ == "__main__":
unittest.main()
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Assembler Test."""
import unittest
import io
from logging import StreamHandler, getLogger
import sys
import copy
import numpy as np
from qiskit import pulse
from qiskit.circuit import Instruction, Gate, Parameter, ParameterVector
from qiskit.circuit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.compiler.assembler import assemble
from qiskit.exceptions import QiskitError
from qiskit.pulse import Schedule, Acquire, Play
from qiskit.pulse.channels import MemorySlot, AcquireChannel, DriveChannel, MeasureChannel
from qiskit.pulse.configuration import Kernel, Discriminator
from qiskit.pulse.library import gaussian
from qiskit.qobj import QasmQobj, PulseQobj
from qiskit.qobj.utils import MeasLevel, MeasReturnType
from qiskit.pulse.macros import measure
from qiskit.test import QiskitTestCase
from qiskit.providers.fake_provider import (
FakeOpenPulse2Q,
FakeOpenPulse3Q,
FakeYorktown,
FakeHanoi,
)
class RxGate(Gate):
"""Used to test custom gate assembly.
Useful for testing pulse gates with parameters, as well.
Note: Parallel maps (e.g., in assemble_circuits) pickle their input,
so circuit features have to be defined top level.
"""
def __init__(self, theta):
super().__init__("rxtheta", 1, [theta])
class TestCircuitAssembler(QiskitTestCase):
"""Tests for assembling circuits to qobj."""
def setUp(self):
super().setUp()
qr = QuantumRegister(2, name="q")
cr = ClassicalRegister(2, name="c")
self.circ = QuantumCircuit(qr, cr, name="circ")
self.circ.h(qr[0])
self.circ.cx(qr[0], qr[1])
self.circ.measure(qr, cr)
self.backend = FakeYorktown()
self.backend_config = self.backend.configuration()
self.num_qubits = self.backend_config.n_qubits
# lo test values
self.default_qubit_lo_freq = [5e9 for _ in range(self.num_qubits)]
self.default_meas_lo_freq = [6.7e9 for _ in range(self.num_qubits)]
self.user_lo_config_dict = {
pulse.DriveChannel(0): 5.55e9,
pulse.MeasureChannel(0): 6.64e9,
pulse.DriveChannel(3): 4.91e9,
pulse.MeasureChannel(4): 6.1e9,
}
self.user_lo_config = pulse.LoConfig(self.user_lo_config_dict)
def test_assemble_single_circuit(self):
"""Test assembling a single circuit."""
qobj = assemble(self.circ, shots=2000, memory=True)
self.assertIsInstance(qobj, QasmQobj)
self.assertEqual(qobj.config.shots, 2000)
self.assertEqual(qobj.config.memory, True)
self.assertEqual(len(qobj.experiments), 1)
self.assertEqual(qobj.experiments[0].instructions[1].name, "cx")
def test_assemble_multiple_circuits(self):
"""Test assembling multiple circuits, all should have the same config."""
qr0 = QuantumRegister(2, name="q0")
qc0 = ClassicalRegister(2, name="c0")
circ0 = QuantumCircuit(qr0, qc0, name="circ0")
circ0.h(qr0[0])
circ0.cx(qr0[0], qr0[1])
circ0.measure(qr0, qc0)
qr1 = QuantumRegister(3, name="q1")
qc1 = ClassicalRegister(3, name="c1")
circ1 = QuantumCircuit(qr1, qc1, name="circ0")
circ1.h(qr1[0])
circ1.cx(qr1[0], qr1[1])
circ1.cx(qr1[0], qr1[2])
circ1.measure(qr1, qc1)
qobj = assemble([circ0, circ1], shots=100, memory=False, seed_simulator=6)
self.assertIsInstance(qobj, QasmQobj)
self.assertEqual(qobj.config.seed_simulator, 6)
self.assertEqual(len(qobj.experiments), 2)
self.assertEqual(qobj.experiments[1].config.n_qubits, 3)
self.assertEqual(len(qobj.experiments), 2)
self.assertEqual(len(qobj.experiments[1].instructions), 6)
def test_assemble_no_run_config(self):
"""Test assembling with no run_config, relying on default."""
qobj = assemble(self.circ)
self.assertIsInstance(qobj, QasmQobj)
self.assertEqual(qobj.config.shots, 1024)
def test_shots_greater_than_max_shots(self):
"""Test assembling with shots greater than max shots"""
self.assertRaises(QiskitError, assemble, self.backend, shots=1024000)
def test_shots_not_of_type_int(self):
"""Test assembling with shots having type other than int"""
self.assertRaises(QiskitError, assemble, self.backend, shots="1024")
def test_shots_of_type_numpy_int64(self):
"""Test assembling with shots having type numpy.int64"""
qobj = assemble(self.circ, shots=np.int64(2048))
self.assertEqual(qobj.config.shots, 2048)
def test_default_shots_greater_than_max_shots(self):
"""Test assembling with default shots greater than max shots"""
self.backend_config.max_shots = 5
qobj = assemble(self.circ, self.backend)
self.assertIsInstance(qobj, QasmQobj)
self.assertEqual(qobj.config.shots, 5)
def test_assemble_initialize(self):
"""Test assembling a circuit with an initialize."""
q = QuantumRegister(2, name="q")
circ = QuantumCircuit(q, name="circ")
circ.initialize([1 / np.sqrt(2), 0, 0, 1 / np.sqrt(2)], q[:])
qobj = assemble(circ)
self.assertIsInstance(qobj, QasmQobj)
self.assertEqual(qobj.experiments[0].instructions[0].name, "initialize")
np.testing.assert_almost_equal(
qobj.experiments[0].instructions[0].params, [0.7071067811865, 0, 0, 0.707106781186]
)
def test_assemble_meas_level_meas_return(self):
"""Test assembling a circuit schedule with `meas_level`."""
qobj = assemble(self.circ, meas_level=1, meas_return="single")
self.assertIsInstance(qobj, QasmQobj)
self.assertEqual(qobj.config.meas_level, 1)
self.assertEqual(qobj.config.meas_return, "single")
# no meas_level set
qobj = assemble(self.circ)
self.assertIsInstance(qobj, QasmQobj)
self.assertEqual(qobj.config.meas_level, 2)
self.assertEqual(hasattr(qobj.config, "meas_return"), False)
def test_assemble_backend_rep_delays(self):
"""Check that rep_delay is properly set from backend values."""
rep_delay_range = [2.5e-3, 4.5e-3] # sec
default_rep_delay = 3.0e-3
setattr(self.backend_config, "rep_delay_range", rep_delay_range)
setattr(self.backend_config, "default_rep_delay", default_rep_delay)
# dynamic rep rates off
setattr(self.backend_config, "dynamic_reprate_enabled", False)
qobj = assemble(self.circ, self.backend)
self.assertEqual(hasattr(qobj.config, "rep_delay"), False)
# dynamic rep rates on
setattr(self.backend_config, "dynamic_reprate_enabled", True)
qobj = assemble(self.circ, self.backend)
self.assertEqual(qobj.config.rep_delay, default_rep_delay * 1e6)
def test_assemble_user_rep_time_delay(self):
"""Check that user runtime config rep_delay works."""
# set custom rep_delay in runtime config
rep_delay = 2.2e-6
rep_delay_range = [0, 3e-6] # sec
setattr(self.backend_config, "rep_delay_range", rep_delay_range)
# dynamic rep rates off (no default so shouldn't be in qobj config)
setattr(self.backend_config, "dynamic_reprate_enabled", False)
qobj = assemble(self.circ, self.backend, rep_delay=rep_delay)
self.assertEqual(hasattr(qobj.config, "rep_delay"), False)
# turn on dynamic rep rates, rep_delay should be set
setattr(self.backend_config, "dynamic_reprate_enabled", True)
qobj = assemble(self.circ, self.backend, rep_delay=rep_delay)
self.assertEqual(qobj.config.rep_delay, 2.2)
# test ``rep_delay=0``
qobj = assemble(self.circ, self.backend, rep_delay=0)
self.assertEqual(qobj.config.rep_delay, 0)
# use ``rep_delay`` outside of ``rep_delay_range```
rep_delay_large = 5.0e-6
with self.assertRaises(QiskitError):
assemble(self.circ, self.backend, rep_delay=rep_delay_large)
def test_assemble_opaque_inst(self):
"""Test opaque instruction is assembled as-is"""
opaque_inst = Instruction(name="my_inst", num_qubits=4, num_clbits=2, params=[0.5, 0.4])
q = QuantumRegister(6, name="q")
c = ClassicalRegister(4, name="c")
circ = QuantumCircuit(q, c, name="circ")
circ.append(opaque_inst, [q[0], q[2], q[5], q[3]], [c[3], c[0]])
qobj = assemble(circ)
self.assertIsInstance(qobj, QasmQobj)
self.assertEqual(len(qobj.experiments[0].instructions), 1)
self.assertEqual(qobj.experiments[0].instructions[0].name, "my_inst")
self.assertEqual(qobj.experiments[0].instructions[0].qubits, [0, 2, 5, 3])
self.assertEqual(qobj.experiments[0].instructions[0].memory, [3, 0])
self.assertEqual(qobj.experiments[0].instructions[0].params, [0.5, 0.4])
def test_assemble_unroll_parametervector(self):
"""Verfiy that assemble unrolls parametervectors ref #5467"""
pv1 = ParameterVector("pv1", 3)
pv2 = ParameterVector("pv2", 3)
qc = QuantumCircuit(2, 2)
for i in range(3):
qc.rx(pv1[i], 0)
qc.ry(pv2[i], 1)
qc.barrier()
qc.measure([0, 1], [0, 1])
qc.bind_parameters({pv1: [0.1, 0.2, 0.3], pv2: [0.4, 0.5, 0.6]})
qobj = assemble(qc, parameter_binds=[{pv1: [0.1, 0.2, 0.3], pv2: [0.4, 0.5, 0.6]}])
self.assertIsInstance(qobj, QasmQobj)
self.assertEqual(qobj.experiments[0].instructions[0].params[0], 0.100000000000000)
self.assertEqual(qobj.experiments[0].instructions[1].params[0], 0.400000000000000)
self.assertEqual(qobj.experiments[0].instructions[2].params[0], 0.200000000000000)
self.assertEqual(qobj.experiments[0].instructions[3].params[0], 0.500000000000000)
self.assertEqual(qobj.experiments[0].instructions[4].params[0], 0.300000000000000)
self.assertEqual(qobj.experiments[0].instructions[5].params[0], 0.600000000000000)
def test_measure_to_registers_when_conditionals(self):
"""Verify assemble_circuits maps all measure ops on to a register slot
for a circuit containing conditionals."""
qr = QuantumRegister(2)
cr1 = ClassicalRegister(1)
cr2 = ClassicalRegister(2)
qc = QuantumCircuit(qr, cr1, cr2)
qc.measure(qr[0], cr1) # Measure not required for a later conditional
qc.measure(qr[1], cr2[1]) # Measure required for a later conditional
qc.h(qr[1]).c_if(cr2, 3)
qobj = assemble(qc)
first_measure, second_measure = (
op for op in qobj.experiments[0].instructions if op.name == "measure"
)
self.assertTrue(hasattr(first_measure, "register"))
self.assertEqual(first_measure.register, first_measure.memory)
self.assertTrue(hasattr(second_measure, "register"))
self.assertEqual(second_measure.register, second_measure.memory)
def test_convert_to_bfunc_plus_conditional(self):
"""Verify assemble_circuits converts conditionals from QASM to Qobj."""
qr = QuantumRegister(1)
cr = ClassicalRegister(1)
qc = QuantumCircuit(qr, cr)
qc.h(qr[0]).c_if(cr, 1)
qobj = assemble(qc)
bfunc_op, h_op = qobj.experiments[0].instructions
self.assertEqual(bfunc_op.name, "bfunc")
self.assertEqual(bfunc_op.mask, "0x1")
self.assertEqual(bfunc_op.val, "0x1")
self.assertEqual(bfunc_op.relation, "==")
self.assertTrue(hasattr(h_op, "conditional"))
self.assertEqual(bfunc_op.register, h_op.conditional)
def test_convert_to_bfunc_plus_conditional_onebit(self):
"""Verify assemble_circuits converts single bit conditionals from QASM to Qobj."""
qr = QuantumRegister(1)
cr = ClassicalRegister(3)
qc = QuantumCircuit(qr, cr)
qc.h(qr[0]).c_if(cr[2], 1)
qobj = assemble(qc)
inst_set = qobj.experiments[0].instructions
[bfunc_op, h_op] = inst_set
self.assertEqual(len(inst_set), 2)
self.assertEqual(bfunc_op.name, "bfunc")
self.assertEqual(bfunc_op.mask, "0x4")
self.assertEqual(bfunc_op.val, "0x4")
self.assertEqual(bfunc_op.relation, "==")
self.assertTrue(hasattr(h_op, "conditional"))
self.assertEqual(bfunc_op.register, h_op.conditional)
def test_resize_value_to_register(self):
"""Verify assemble_circuits converts the value provided on the classical
creg to its mapped location on the device register."""
qr = QuantumRegister(1)
cr1 = ClassicalRegister(2)
cr2 = ClassicalRegister(2)
cr3 = ClassicalRegister(1)
qc = QuantumCircuit(qr, cr1, cr2, cr3)
qc.h(qr[0]).c_if(cr2, 2)
qobj = assemble(qc)
bfunc_op, h_op = qobj.experiments[0].instructions
self.assertEqual(bfunc_op.name, "bfunc")
self.assertEqual(bfunc_op.mask, "0xC")
self.assertEqual(bfunc_op.val, "0x8")
self.assertEqual(bfunc_op.relation, "==")
self.assertTrue(hasattr(h_op, "conditional"))
self.assertEqual(bfunc_op.register, h_op.conditional)
def test_assemble_circuits_raises_for_bind_circuit_mismatch(self):
"""Verify assemble_circuits raises error for parameterized circuits without matching
binds."""
qr = QuantumRegister(2)
x = Parameter("x")
y = Parameter("y")
full_bound_circ = QuantumCircuit(qr)
full_param_circ = QuantumCircuit(qr)
partial_param_circ = QuantumCircuit(qr)
partial_param_circ.p(x, qr[0])
full_param_circ.p(x, qr[0])
full_param_circ.p(y, qr[1])
partial_bind_args = {"parameter_binds": [{x: 1}, {x: 0}]}
full_bind_args = {"parameter_binds": [{x: 1, y: 1}, {x: 0, y: 0}]}
inconsistent_bind_args = {"parameter_binds": [{x: 1}, {x: 0, y: 0}]}
# Raise when parameters passed for non-parametric circuit
self.assertRaises(QiskitError, assemble, full_bound_circ, **partial_bind_args)
# Raise when no parameters passed for parametric circuit
self.assertRaises(QiskitError, assemble, partial_param_circ)
self.assertRaises(QiskitError, assemble, full_param_circ)
# Raise when circuit has more parameters than run_config
self.assertRaises(QiskitError, assemble, full_param_circ, **partial_bind_args)
# Raise when not all circuits have all parameters
self.assertRaises(
QiskitError, assemble, [full_param_circ, partial_param_circ], **full_bind_args
)
# Raise when not all binds have all circuit params
self.assertRaises(QiskitError, assemble, full_param_circ, **inconsistent_bind_args)
def test_assemble_circuits_rases_for_bind_mismatch_over_expressions(self):
"""Verify assemble_circuits raises for invalid binds for circuit including
ParameterExpressions.
"""
qr = QuantumRegister(1)
x = Parameter("x")
y = Parameter("y")
expr_circ = QuantumCircuit(qr)
expr_circ.p(x + y, qr[0])
partial_bind_args = {"parameter_binds": [{x: 1}, {x: 0}]}
# Raise when no parameters passed for parametric circuit
self.assertRaises(QiskitError, assemble, expr_circ)
# Raise when circuit has more parameters than run_config
self.assertRaises(QiskitError, assemble, expr_circ, **partial_bind_args)
def test_assemble_circuits_binds_parameters(self):
"""Verify assemble_circuits applies parameter bindings and output circuits are bound."""
qr = QuantumRegister(1)
qc1 = QuantumCircuit(qr)
qc2 = QuantumCircuit(qr)
qc3 = QuantumCircuit(qr)
x = Parameter("x")
y = Parameter("y")
sum_ = x + y
product_ = x * y
qc1.u(x, y, 0, qr[0])
qc2.rz(x, qr[0])
qc2.rz(y, qr[0])
qc3.u(sum_, product_, 0, qr[0])
bind_args = {"parameter_binds": [{x: 0, y: 0}, {x: 1, y: 0}, {x: 1, y: 1}]}
qobj = assemble([qc1, qc2, qc3], **bind_args)
self.assertEqual(len(qobj.experiments), 9)
self.assertEqual(
[len(expt.instructions) for expt in qobj.experiments], [1, 1, 1, 2, 2, 2, 1, 1, 1]
)
def _qobj_inst_params(expt_no, inst_no):
expt = qobj.experiments[expt_no]
inst = expt.instructions[inst_no]
return [float(p) for p in inst.params]
self.assertEqual(_qobj_inst_params(0, 0), [0, 0, 0])
self.assertEqual(_qobj_inst_params(1, 0), [1, 0, 0])
self.assertEqual(_qobj_inst_params(2, 0), [1, 1, 0])
self.assertEqual(_qobj_inst_params(3, 0), [0])
self.assertEqual(_qobj_inst_params(3, 1), [0])
self.assertEqual(_qobj_inst_params(4, 0), [1])
self.assertEqual(_qobj_inst_params(4, 1), [0])
self.assertEqual(_qobj_inst_params(5, 0), [1])
self.assertEqual(_qobj_inst_params(5, 1), [1])
self.assertEqual(_qobj_inst_params(6, 0), [0, 0, 0])
self.assertEqual(_qobj_inst_params(7, 0), [1, 0, 0])
self.assertEqual(_qobj_inst_params(8, 0), [2, 1, 0])
def test_init_qubits_default(self):
"""Check that the init_qubits=None assemble option is passed on to the qobj."""
qobj = assemble(self.circ)
self.assertEqual(qobj.config.init_qubits, True)
def test_init_qubits_true(self):
"""Check that the init_qubits=True assemble option is passed on to the qobj."""
qobj = assemble(self.circ, init_qubits=True)
self.assertEqual(qobj.config.init_qubits, True)
def test_init_qubits_false(self):
"""Check that the init_qubits=False assemble option is passed on to the qobj."""
qobj = assemble(self.circ, init_qubits=False)
self.assertEqual(qobj.config.init_qubits, False)
def test_circuit_with_global_phase(self):
"""Test that global phase for a circuit is handled correctly."""
circ = QuantumCircuit(2)
circ.h(0)
circ.cx(0, 1)
circ.measure_all()
circ.global_phase = 0.3 * np.pi
qobj = assemble([circ, self.circ])
self.assertEqual(getattr(qobj.experiments[1].header, "global_phase"), 0)
self.assertEqual(getattr(qobj.experiments[0].header, "global_phase"), 0.3 * np.pi)
def test_circuit_global_phase_gate_definitions(self):
"""Test circuit with global phase on gate definitions."""
class TestGate(Gate):
"""dummy gate"""
def __init__(self):
super().__init__("test_gate", 1, [])
def _define(self):
circ_def = QuantumCircuit(1)
circ_def.x(0)
circ_def.global_phase = np.pi
self._definition = circ_def
gate = TestGate()
circ = QuantumCircuit(1)
circ.append(gate, [0])
qobj = assemble([circ])
self.assertEqual(getattr(qobj.experiments[0].header, "global_phase"), 0)
circ.global_phase = np.pi / 2
qobj = assemble([circ])
self.assertEqual(getattr(qobj.experiments[0].header, "global_phase"), np.pi / 2)
def test_pulse_gates_single_circ(self):
"""Test that we can add calibrations to circuits."""
theta = Parameter("theta")
circ = QuantumCircuit(2)
circ.h(0)
circ.append(RxGate(3.14), [0])
circ.append(RxGate(theta), [1])
circ = circ.assign_parameters({theta: 3.14})
with pulse.build() as custom_h_schedule:
pulse.play(pulse.library.Drag(50, 0.15, 4, 2), pulse.DriveChannel(0))
with pulse.build() as x180:
pulse.play(pulse.library.Gaussian(50, 0.2, 5), pulse.DriveChannel(1))
circ.add_calibration("h", [0], custom_h_schedule)
circ.add_calibration(RxGate(3.14), [0], x180)
circ.add_calibration(RxGate(3.14), [1], x180)
qobj = assemble(circ, FakeOpenPulse2Q())
# Only one circuit, so everything is stored at the job level
cals = qobj.config.calibrations
lib = qobj.config.pulse_library
self.assertFalse(hasattr(qobj.experiments[0].config, "calibrations"))
self.assertEqual([gate.name == "rxtheta" for gate in cals.gates].count(True), 2)
self.assertEqual([gate.name == "h" for gate in cals.gates].count(True), 1)
self.assertEqual(len(lib), 2)
self.assertTrue(all(len(item.samples) == 50 for item in lib))
def test_pulse_gates_with_parameteric_pulses(self):
"""Test that pulse gates are assembled efficiently for backends that enable
parametric pulses.
"""
with pulse.build() as custom_h_schedule:
pulse.play(pulse.library.Drag(50, 0.15, 4, 2), pulse.DriveChannel(0))
circ = QuantumCircuit(2)
circ.h(0)
circ.add_calibration("h", [0], custom_h_schedule)
backend = FakeOpenPulse2Q()
backend.configuration().parametric_pulses = ["drag"]
qobj = assemble(circ, backend)
self.assertFalse(hasattr(qobj.config, "pulse_library"))
self.assertTrue(hasattr(qobj.config, "calibrations"))
def test_pulse_gates_multiple_circuits(self):
"""Test one circuit with cals and another without."""
with pulse.build() as dummy_sched:
pulse.play(pulse.library.Drag(50, 0.15, 4, 2), pulse.DriveChannel(0))
circ = QuantumCircuit(2)
circ.h(0)
circ.append(RxGate(3.14), [1])
circ.add_calibration("h", [0], dummy_sched)
circ.add_calibration(RxGate(3.14), [1], dummy_sched)
circ2 = QuantumCircuit(2)
circ2.h(0)
qobj = assemble([circ, circ2], FakeOpenPulse2Q())
self.assertEqual(len(qobj.config.pulse_library), 1)
self.assertEqual(len(qobj.experiments[0].config.calibrations.gates), 2)
self.assertFalse(hasattr(qobj.config, "calibrations"))
self.assertFalse(hasattr(qobj.experiments[1].config, "calibrations"))
def test_pulse_gates_common_cals(self):
"""Test that common calibrations are added at the top level."""
with pulse.build() as dummy_sched:
pulse.play(pulse.library.Drag(50, 0.15, 4, 2), pulse.DriveChannel(0))
circ = QuantumCircuit(2)
circ.h(0)
circ.append(RxGate(3.14), [1])
circ.add_calibration("h", [0], dummy_sched)
circ.add_calibration(RxGate(3.14), [1], dummy_sched)
circ2 = QuantumCircuit(2)
circ2.h(0)
circ2.add_calibration(RxGate(3.14), [1], dummy_sched)
qobj = assemble([circ, circ2], FakeOpenPulse2Q())
# Identical pulses are only added once
self.assertEqual(len(qobj.config.pulse_library), 1)
# Identical calibrations are only added once
self.assertEqual(qobj.config.calibrations.gates[0].name, "rxtheta")
self.assertEqual(qobj.config.calibrations.gates[0].params, [3.14])
self.assertEqual(qobj.config.calibrations.gates[0].qubits, [1])
self.assertEqual(len(qobj.experiments[0].config.calibrations.gates), 1)
self.assertFalse(hasattr(qobj.experiments[1].config, "calibrations"))
def test_assemble_adds_circuit_metadata_to_experiment_header(self):
"""Verify that any circuit metadata is added to the exeriment header."""
circ = QuantumCircuit(2, metadata={"experiment_type": "gst", "execution_number": "1234"})
qobj = assemble(circ, shots=100, memory=False, seed_simulator=6)
self.assertEqual(
qobj.experiments[0].header.metadata,
{"experiment_type": "gst", "execution_number": "1234"},
)
def test_pulse_gates_delay_only(self):
"""Test that a single delay gate is translated to an instruction."""
circ = QuantumCircuit(2)
circ.append(Gate("test", 1, []), [0])
test_sched = pulse.Delay(64, DriveChannel(0)) + pulse.Delay(160, DriveChannel(0))
circ.add_calibration("test", [0], test_sched)
qobj = assemble(circ, FakeOpenPulse2Q())
self.assertEqual(len(qobj.config.calibrations.gates[0].instructions), 2)
self.assertEqual(
qobj.config.calibrations.gates[0].instructions[1].to_dict(),
{"name": "delay", "t0": 64, "ch": "d0", "duration": 160},
)
def test_job_qubit_meas_los_no_range(self):
"""Test that adding job qubit/meas lo freq lists are assembled into the qobj.config, w/ out
any lo range."""
qobj = assemble(
self.circ,
backend=self.backend,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
)
# convert to ghz
qubit_lo_freq_ghz = [freq / 1e9 for freq in self.default_qubit_lo_freq]
meas_lo_freq_ghz = [freq / 1e9 for freq in self.default_meas_lo_freq]
self.assertEqual(qobj.config.qubit_lo_freq, qubit_lo_freq_ghz)
self.assertEqual(qobj.config.meas_lo_freq, meas_lo_freq_ghz)
def test_job_lo_errors(self):
"""Test that job lo's are checked against the lo ranges and that errors are thrown if either
quantity has an incorrect length or type."""
qubit_lo_range = [[freq - 5e6, freq + 5e6] for freq in self.default_qubit_lo_freq]
meas_lo_range = [[freq - 5e6, freq + 5e6] for freq in self.default_meas_lo_freq]
# lo range not a nested list
with self.assertRaises(QiskitError):
assemble(
self.circ,
backend=self.backend,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
qubit_lo_range=[4.995e9 for i in range(self.num_qubits)],
meas_lo_range=meas_lo_range,
)
# qubit lo range inner list not 2d
with self.assertRaises(QiskitError):
assemble(
self.circ,
backend=self.backend,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
qubit_lo_range=qubit_lo_range,
meas_lo_range=[[6.695e9] for i in range(self.num_qubits)],
)
# meas lo range inner list not 2d
with self.assertRaises(QiskitError):
assemble(
self.circ,
backend=self.backend,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
qubit_lo_range=qubit_lo_range,
meas_lo_range=[[6.695e9] for i in range(self.num_qubits)],
)
# qubit lo out of range
with self.assertRaises(QiskitError):
assemble(
self.circ,
backend=self.backend,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
qubit_lo_range=[[5.005e9, 5.010e9] for i in range(self.num_qubits)],
meas_lo_range=meas_lo_range,
)
# meas lo out of range
with self.assertRaises(QiskitError):
assemble(
self.circ,
backend=self.backend,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
qubit_lo_range=qubit_lo_range,
meas_lo_range=[[6.705e9, 6.710e9] for i in range(self.num_qubits)],
)
def test_job_qubit_meas_los_w_range(self):
"""Test that adding job qubit/meas lo freq lists are assembled into the qobj.config, w/ lo
ranges input. Verify that lo ranges do not enter into the config."""
qubit_lo_range = [[freq - 5e6, freq + 5e6] for freq in self.default_qubit_lo_freq]
meas_lo_range = [[freq - 5e6, freq + 5e6] for freq in self.default_meas_lo_freq]
qobj = assemble(
self.circ,
backend=self.backend,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
qubit_lo_range=qubit_lo_range,
meas_lo_range=meas_lo_range,
)
# convert to ghz
qubit_lo_freq_ghz = [freq / 1e9 for freq in self.default_qubit_lo_freq]
meas_lo_freq_ghz = [freq / 1e9 for freq in self.default_meas_lo_freq]
self.assertEqual(qobj.config.qubit_lo_freq, qubit_lo_freq_ghz)
self.assertEqual(qobj.config.meas_lo_freq, meas_lo_freq_ghz)
self.assertNotIn("qubit_lo_range", qobj.config.to_dict())
self.assertNotIn("meas_lo_range", qobj.config.to_dict())
def test_assemble_single_circ_single_lo_config(self):
"""Test assembling a single circuit, with a single experiment level lo config."""
qobj = assemble(
self.circ,
self.backend,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
schedule_los=self.user_lo_config,
)
self.assertListEqual(qobj.config.qubit_lo_freq, [5.55, 5, 5, 4.91, 5])
self.assertListEqual(qobj.config.meas_lo_freq, [6.64, 6.7, 6.7, 6.7, 6.1])
self.assertEqual(len(qobj.experiments), 1)
def test_assemble_single_circ_single_lo_config_dict(self):
"""Test assembling a single circuit, with a single experiment level lo config supplied as
dictionary."""
qobj = assemble(
self.circ,
self.backend,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
schedule_los=self.user_lo_config_dict,
)
self.assertListEqual(qobj.config.qubit_lo_freq, [5.55, 5, 5, 4.91, 5])
self.assertListEqual(qobj.config.meas_lo_freq, [6.64, 6.7, 6.7, 6.7, 6.1])
self.assertEqual(len(qobj.experiments), 1)
def test_assemble_single_circ_multi_lo_config(self):
"""Test assembling a single circuit, with multiple experiment level lo configs (frequency
sweep).
"""
user_lo_config_dict2 = {
pulse.DriveChannel(1): 5.55e9,
pulse.MeasureChannel(1): 6.64e9,
pulse.DriveChannel(4): 4.91e9,
pulse.MeasureChannel(3): 6.1e9,
}
user_lo_config2 = pulse.LoConfig(user_lo_config_dict2)
qobj = assemble(
self.circ,
self.backend,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
schedule_los=[self.user_lo_config, user_lo_config2],
)
qubit_lo_freq_ghz = [freq / 1e9 for freq in self.default_qubit_lo_freq]
meas_lo_freq_ghz = [freq / 1e9 for freq in self.default_meas_lo_freq]
self.assertListEqual(qobj.config.qubit_lo_freq, qubit_lo_freq_ghz)
self.assertListEqual(qobj.config.meas_lo_freq, meas_lo_freq_ghz)
self.assertEqual(len(qobj.experiments), 2)
# experiment 0 los
self.assertEqual(qobj.experiments[0].config.qubit_lo_freq, [5.55, 5, 5, 4.91, 5])
self.assertEqual(qobj.experiments[0].config.meas_lo_freq, [6.64, 6.7, 6.7, 6.7, 6.1])
# experiment 1 los
self.assertEqual(qobj.experiments[1].config.qubit_lo_freq, [5, 5.55, 5, 5, 4.91])
self.assertEqual(qobj.experiments[1].config.meas_lo_freq, [6.7, 6.64, 6.7, 6.1, 6.7])
def test_assemble_multi_circ_multi_lo_config(self):
"""Test assembling circuits, with the same number of experiment level lo configs (n:n
setup)."""
user_lo_config_dict2 = {
pulse.DriveChannel(1): 5.55e9,
pulse.MeasureChannel(1): 6.64e9,
pulse.DriveChannel(4): 4.91e9,
pulse.MeasureChannel(3): 6.1e9,
}
user_lo_config2 = pulse.LoConfig(user_lo_config_dict2)
qobj = assemble(
[self.circ, self.circ],
self.backend,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
schedule_los=[self.user_lo_config, user_lo_config2],
)
qubit_lo_freq_ghz = [freq / 1e9 for freq in self.default_qubit_lo_freq]
meas_lo_freq_ghz = [freq / 1e9 for freq in self.default_meas_lo_freq]
self.assertListEqual(qobj.config.qubit_lo_freq, qubit_lo_freq_ghz)
self.assertListEqual(qobj.config.meas_lo_freq, meas_lo_freq_ghz)
self.assertEqual(len(qobj.experiments), 2)
# experiment 0 los
self.assertEqual(qobj.experiments[0].config.qubit_lo_freq, [5.55, 5, 5, 4.91, 5])
self.assertEqual(qobj.experiments[0].config.meas_lo_freq, [6.64, 6.7, 6.7, 6.7, 6.1])
# experiment 1 los
self.assertEqual(qobj.experiments[1].config.qubit_lo_freq, [5, 5.55, 5, 5, 4.91])
self.assertEqual(qobj.experiments[1].config.meas_lo_freq, [6.7, 6.64, 6.7, 6.1, 6.7])
def test_assemble_multi_circ_single_lo_config(self):
"""Test assembling multiple circuits, with a single experiment level lo config (should
override job level)."""
qobj = assemble(
[self.circ, self.circ],
self.backend,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
schedule_los=self.user_lo_config,
)
self.assertListEqual(qobj.config.qubit_lo_freq, [5.55, 5, 5, 4.91, 5])
self.assertListEqual(qobj.config.meas_lo_freq, [6.64, 6.7, 6.7, 6.7, 6.1])
self.assertEqual(len(qobj.experiments), 2)
def test_assemble_multi_circ_wrong_number_of_multi_lo_configs(self):
"""Test assembling circuits, with a different number of experiment level lo configs (n:m
setup).
"""
with self.assertRaises(QiskitError):
assemble(
[self.circ, self.circ, self.circ],
self.backend,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
schedule_los=[self.user_lo_config, self.user_lo_config],
)
def test_assemble_circ_lo_config_errors(self):
"""Test that lo config errors are raised properly if experiment level los are provided and
some are missing or if default values are not provided. Also check that experiment level lo
range is validated."""
# no defaults, but have drive/meas experiment level los for each qubit (no error)
full_lo_config_dict = {
pulse.DriveChannel(0): 4.85e9,
pulse.DriveChannel(1): 4.9e9,
pulse.DriveChannel(2): 4.95e9,
pulse.DriveChannel(3): 5e9,
pulse.DriveChannel(4): 5.05e9,
pulse.MeasureChannel(0): 6.8e9,
pulse.MeasureChannel(1): 6.85e9,
pulse.MeasureChannel(2): 6.9e9,
pulse.MeasureChannel(3): 6.95e9,
pulse.MeasureChannel(4): 7e9,
}
qobj = assemble(self.circ, self.backend, schedule_los=full_lo_config_dict)
self.assertListEqual(qobj.config.qubit_lo_freq, [4.85, 4.9, 4.95, 5, 5.05])
self.assertListEqual(qobj.config.meas_lo_freq, [6.8, 6.85, 6.9, 6.95, 7])
self.assertEqual(len(qobj.experiments), 1)
# no defaults and missing experiment level drive lo raises
missing_drive_lo_config_dict = copy.deepcopy(full_lo_config_dict)
missing_drive_lo_config_dict.pop(pulse.DriveChannel(0))
with self.assertRaises(QiskitError):
qobj = assemble(self.circ, self.backend, schedule_los=missing_drive_lo_config_dict)
# no defaults and missing experiment level meas lo raises
missing_meas_lo_config_dict = copy.deepcopy(full_lo_config_dict)
missing_meas_lo_config_dict.pop(pulse.MeasureChannel(0))
with self.assertRaises(QiskitError):
qobj = assemble(self.circ, self.backend, schedule_los=missing_meas_lo_config_dict)
# verify lo ranges are checked at experiment level
lo_values = list(full_lo_config_dict.values())
qubit_lo_range = [[freq - 5e6, freq + 5e6] for freq in lo_values[:5]]
meas_lo_range = [[freq - 5e6, freq + 5e6] for freq in lo_values[5:]]
# out of range drive lo
full_lo_config_dict[pulse.DriveChannel(0)] -= 5.5e6
with self.assertRaises(QiskitError):
qobj = assemble(
self.circ,
self.backend,
qubit_lo_range=qubit_lo_range,
schedule_los=full_lo_config_dict,
)
full_lo_config_dict[pulse.DriveChannel(0)] += 5.5e6 # reset drive value
# out of range meas lo
full_lo_config_dict[pulse.MeasureChannel(0)] += 5.5e6
with self.assertRaises(QiskitError):
qobj = assemble(
self.circ,
self.backend,
meas_lo_range=meas_lo_range,
schedule_los=full_lo_config_dict,
)
class TestPulseAssembler(QiskitTestCase):
"""Tests for assembling schedules to qobj."""
def setUp(self):
super().setUp()
self.backend = FakeOpenPulse2Q()
self.backend_config = self.backend.configuration()
test_pulse = pulse.Waveform(
samples=np.array([0.02739068, 0.05, 0.05, 0.05, 0.02739068], dtype=np.complex128),
name="pulse0",
)
self.schedule = pulse.Schedule(name="fake_experiment")
self.schedule = self.schedule.insert(0, Play(test_pulse, self.backend_config.drive(0)))
for i in range(self.backend_config.n_qubits):
self.schedule = self.schedule.insert(
5, Acquire(5, self.backend_config.acquire(i), MemorySlot(i))
)
self.user_lo_config_dict = {self.backend_config.drive(0): 4.91e9}
self.user_lo_config = pulse.LoConfig(self.user_lo_config_dict)
self.default_qubit_lo_freq = [4.9e9, 5.0e9]
self.default_meas_lo_freq = [6.5e9, 6.6e9]
self.config = {"meas_level": 1, "memory_slot_size": 100, "meas_return": "avg"}
self.header = {"backend_name": "FakeOpenPulse2Q", "backend_version": "0.0.0"}
def test_assemble_adds_schedule_metadata_to_experiment_header(self):
"""Verify that any circuit metadata is added to the exeriment header."""
self.schedule.metadata = {"experiment_type": "gst", "execution_number": "1234"}
qobj = assemble(
self.schedule,
shots=100,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
schedule_los=[],
)
self.assertEqual(
qobj.experiments[0].header.metadata,
{"experiment_type": "gst", "execution_number": "1234"},
)
def test_assemble_sample_pulse(self):
"""Test that the pulse lib and qobj instruction can be paired up."""
schedule = pulse.Schedule()
schedule += pulse.Play(
pulse.Waveform([0.1] * 16, name="test0"), pulse.DriveChannel(0), name="test1"
)
schedule += pulse.Play(
pulse.Waveform([0.1] * 16, name="test1"), pulse.DriveChannel(0), name="test2"
)
schedule += pulse.Play(
pulse.Waveform([0.5] * 16, name="test0"), pulse.DriveChannel(0), name="test1"
)
qobj = assemble(
schedule,
qobj_header=self.header,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
schedule_los=[],
**self.config,
)
test_dict = qobj.to_dict()
experiment = test_dict["experiments"][0]
inst0_name = experiment["instructions"][0]["name"]
inst1_name = experiment["instructions"][1]["name"]
inst2_name = experiment["instructions"][2]["name"]
pulses = {}
for item in test_dict["config"]["pulse_library"]:
pulses[item["name"]] = item["samples"]
self.assertTrue(all(name in pulses for name in [inst0_name, inst1_name, inst2_name]))
# Their pulses are the same
self.assertEqual(inst0_name, inst1_name)
self.assertTrue(np.allclose(pulses[inst0_name], [0.1] * 16))
self.assertTrue(np.allclose(pulses[inst2_name], [0.5] * 16))
def test_assemble_single_schedule_without_lo_config(self):
"""Test assembling a single schedule, no lo config."""
qobj = assemble(
self.schedule,
qobj_header=self.header,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
schedule_los=[],
**self.config,
)
test_dict = qobj.to_dict()
self.assertListEqual(test_dict["config"]["qubit_lo_freq"], [4.9, 5.0])
self.assertEqual(len(test_dict["experiments"]), 1)
self.assertEqual(len(test_dict["experiments"][0]["instructions"]), 2)
def test_assemble_multi_schedules_without_lo_config(self):
"""Test assembling schedules, no lo config."""
qobj = assemble(
[self.schedule, self.schedule],
qobj_header=self.header,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
**self.config,
)
test_dict = qobj.to_dict()
self.assertListEqual(test_dict["config"]["qubit_lo_freq"], [4.9, 5.0])
self.assertEqual(len(test_dict["experiments"]), 2)
self.assertEqual(len(test_dict["experiments"][0]["instructions"]), 2)
def test_assemble_single_schedule_with_lo_config(self):
"""Test assembling a single schedule, with a single lo config."""
qobj = assemble(
self.schedule,
qobj_header=self.header,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
schedule_los=self.user_lo_config,
**self.config,
)
test_dict = qobj.to_dict()
self.assertListEqual(test_dict["config"]["qubit_lo_freq"], [4.91, 5.0])
self.assertEqual(len(test_dict["experiments"]), 1)
self.assertEqual(len(test_dict["experiments"][0]["instructions"]), 2)
def test_assemble_single_schedule_with_lo_config_dict(self):
"""Test assembling a single schedule, with a single lo config supplied as dictionary."""
qobj = assemble(
self.schedule,
qobj_header=self.header,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
schedule_los=self.user_lo_config_dict,
**self.config,
)
test_dict = qobj.to_dict()
self.assertListEqual(test_dict["config"]["qubit_lo_freq"], [4.91, 5.0])
self.assertEqual(len(test_dict["experiments"]), 1)
self.assertEqual(len(test_dict["experiments"][0]["instructions"]), 2)
def test_assemble_single_schedule_with_multi_lo_configs(self):
"""Test assembling a single schedule, with multiple lo configs (frequency sweep)."""
qobj = assemble(
self.schedule,
qobj_header=self.header,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
schedule_los=[self.user_lo_config, self.user_lo_config],
**self.config,
)
test_dict = qobj.to_dict()
self.assertListEqual(test_dict["config"]["qubit_lo_freq"], [4.9, 5.0])
self.assertEqual(len(test_dict["experiments"]), 2)
self.assertEqual(len(test_dict["experiments"][0]["instructions"]), 2)
self.assertDictEqual(test_dict["experiments"][0]["config"], {"qubit_lo_freq": [4.91, 5.0]})
def test_assemble_multi_schedules_with_multi_lo_configs(self):
"""Test assembling schedules, with the same number of lo configs (n:n setup)."""
qobj = assemble(
[self.schedule, self.schedule],
qobj_header=self.header,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
schedule_los=[self.user_lo_config, self.user_lo_config],
**self.config,
)
test_dict = qobj.to_dict()
self.assertListEqual(test_dict["config"]["qubit_lo_freq"], [4.9, 5.0])
self.assertEqual(len(test_dict["experiments"]), 2)
self.assertEqual(len(test_dict["experiments"][0]["instructions"]), 2)
self.assertDictEqual(test_dict["experiments"][0]["config"], {"qubit_lo_freq": [4.91, 5.0]})
def test_assemble_multi_schedules_with_wrong_number_of_multi_lo_configs(self):
"""Test assembling schedules, with a different number of lo configs (n:m setup)."""
with self.assertRaises(QiskitError):
assemble(
[self.schedule, self.schedule, self.schedule],
qobj_header=self.header,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
schedule_los=[self.user_lo_config, self.user_lo_config],
**self.config,
)
def test_assemble_meas_map(self):
"""Test assembling a single schedule, no lo config."""
schedule = Schedule(name="fake_experiment")
schedule = schedule.insert(5, Acquire(5, AcquireChannel(0), MemorySlot(0)))
schedule = schedule.insert(5, Acquire(5, AcquireChannel(1), MemorySlot(1)))
qobj = assemble(
schedule,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
meas_map=[[0], [1]],
)
self.assertIsInstance(qobj, PulseQobj)
qobj = assemble(
schedule,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
meas_map=[[0, 1, 2]],
)
self.assertIsInstance(qobj, PulseQobj)
def test_assemble_memory_slots(self):
"""Test assembling a schedule and inferring number of memoryslots."""
n_memoryslots = 10
# single acquisition
schedule = Acquire(
5, self.backend_config.acquire(0), mem_slot=pulse.MemorySlot(n_memoryslots - 1)
)
qobj = assemble(
schedule,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
meas_map=[[0], [1]],
)
self.assertEqual(qobj.config.memory_slots, n_memoryslots)
# this should be in experimental header as well
self.assertEqual(qobj.experiments[0].header.memory_slots, n_memoryslots)
# multiple acquisition
schedule = Acquire(
5, self.backend_config.acquire(0), mem_slot=pulse.MemorySlot(n_memoryslots - 1)
)
schedule = schedule.insert(
10,
Acquire(
5, self.backend_config.acquire(0), mem_slot=pulse.MemorySlot(n_memoryslots - 1)
),
)
qobj = assemble(
schedule,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
meas_map=[[0], [1]],
)
self.assertEqual(qobj.config.memory_slots, n_memoryslots)
# this should be in experimental header as well
self.assertEqual(qobj.experiments[0].header.memory_slots, n_memoryslots)
def test_assemble_memory_slots_for_schedules(self):
"""Test assembling schedules with different memory slots."""
n_memoryslots = [10, 5, 7]
schedules = []
for n_memoryslot in n_memoryslots:
schedule = Acquire(
5, self.backend_config.acquire(0), mem_slot=pulse.MemorySlot(n_memoryslot - 1)
)
schedules.append(schedule)
qobj = assemble(
schedules,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
meas_map=[[0], [1]],
)
self.assertEqual(qobj.config.memory_slots, max(n_memoryslots))
self.assertEqual(qobj.experiments[0].header.memory_slots, n_memoryslots[0])
self.assertEqual(qobj.experiments[1].header.memory_slots, n_memoryslots[1])
self.assertEqual(qobj.experiments[2].header.memory_slots, n_memoryslots[2])
def test_pulse_name_conflicts(self):
"""Test that pulse name conflicts can be resolved."""
name_conflict_pulse = pulse.Waveform(
samples=np.array([0.02, 0.05, 0.05, 0.05, 0.02], dtype=np.complex128), name="pulse0"
)
self.schedule = self.schedule.insert(
1, Play(name_conflict_pulse, self.backend_config.drive(1))
)
qobj = assemble(
self.schedule,
qobj_header=self.header,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
schedule_los=[],
**self.config,
)
self.assertNotEqual(qobj.config.pulse_library[0].name, qobj.config.pulse_library[1].name)
def test_pulse_name_conflicts_in_other_schedule(self):
"""Test two pulses with the same name in different schedule can be resolved."""
backend = FakeHanoi()
defaults = backend.defaults()
schedules = []
ch_d0 = pulse.DriveChannel(0)
for amp in (0.1, 0.2):
sched = Schedule()
sched += Play(gaussian(duration=100, amp=amp, sigma=30, name="my_pulse"), ch_d0)
sched += measure(qubits=[0], backend=backend) << 100
schedules.append(sched)
qobj = assemble(
schedules, qubit_lo_freq=defaults.qubit_freq_est, meas_lo_freq=defaults.meas_freq_est
)
# two user pulses and one measurement pulse should be contained
self.assertEqual(len(qobj.config.pulse_library), 3)
def test_assemble_with_delay(self):
"""Test that delay instruction is not ignored in assembly."""
delay_schedule = pulse.Delay(10, self.backend_config.drive(0))
delay_schedule += self.schedule
delay_qobj = assemble(delay_schedule, self.backend)
self.assertEqual(delay_qobj.experiments[0].instructions[0].name, "delay")
self.assertEqual(delay_qobj.experiments[0].instructions[0].duration, 10)
self.assertEqual(delay_qobj.experiments[0].instructions[0].t0, 0)
def test_delay_removed_on_acq_ch(self):
"""Test that delay instructions on acquire channels are skipped on assembly with times
shifted properly.
"""
delay0 = pulse.Delay(5, self.backend_config.acquire(0))
delay1 = pulse.Delay(7, self.backend_config.acquire(1))
sched0 = delay0
sched0 += self.schedule # includes ``Acquire`` instr
sched0 += delay1
sched1 = self.schedule # includes ``Acquire`` instr
sched1 += delay0
sched1 += delay1
sched2 = delay0
sched2 += delay1
sched2 += self.schedule # includes ``Acquire`` instr
delay_qobj = assemble([sched0, sched1, sched2], self.backend)
# check that no delay instrs occur on acquire channels
is_acq_delay = False
for exp in delay_qobj.experiments:
for instr in exp.instructions:
if instr.name == "delay" and "a" in instr.ch:
is_acq_delay = True
self.assertFalse(is_acq_delay)
# check that acquire instr are shifted from ``t0=5`` as needed
self.assertEqual(delay_qobj.experiments[0].instructions[1].t0, 10)
self.assertEqual(delay_qobj.experiments[0].instructions[1].name, "acquire")
self.assertEqual(delay_qobj.experiments[1].instructions[1].t0, 5)
self.assertEqual(delay_qobj.experiments[1].instructions[1].name, "acquire")
self.assertEqual(delay_qobj.experiments[2].instructions[1].t0, 12)
self.assertEqual(delay_qobj.experiments[2].instructions[1].name, "acquire")
def test_assemble_schedule_enum(self):
"""Test assembling a schedule with enum input values to assemble."""
qobj = assemble(
self.schedule,
qobj_header=self.header,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
schedule_los=[],
meas_level=MeasLevel.CLASSIFIED,
meas_return=MeasReturnType.AVERAGE,
)
test_dict = qobj.to_dict()
self.assertEqual(test_dict["config"]["meas_return"], "avg")
self.assertEqual(test_dict["config"]["meas_level"], 2)
def test_assemble_parametric(self):
"""Test that parametric pulses can be assembled properly into a PulseQobj."""
amp = [0.5, 0.6, 1, 0.2]
angle = [np.pi / 2, 0.6, 0, 0]
sched = pulse.Schedule(name="test_parametric")
sched += Play(
pulse.Gaussian(duration=25, sigma=4, amp=amp[0], angle=angle[0]), DriveChannel(0)
)
sched += Play(
pulse.Drag(duration=25, amp=amp[1], angle=angle[1], sigma=7.8, beta=4), DriveChannel(1)
)
sched += Play(pulse.Constant(duration=25, amp=amp[2], angle=angle[2]), DriveChannel(2))
sched += (
Play(
pulse.GaussianSquare(duration=150, amp=amp[3], angle=angle[3], sigma=8, width=140),
MeasureChannel(0),
)
<< sched.duration
)
backend = FakeOpenPulse3Q()
backend.configuration().parametric_pulses = [
"gaussian",
"drag",
"gaussian_square",
"constant",
]
qobj = assemble(sched, backend)
self.assertEqual(qobj.config.pulse_library, [])
qobj_insts = qobj.experiments[0].instructions
self.assertTrue(all(inst.name == "parametric_pulse" for inst in qobj_insts))
self.assertEqual(qobj_insts[0].pulse_shape, "gaussian")
self.assertEqual(qobj_insts[1].pulse_shape, "drag")
self.assertEqual(qobj_insts[2].pulse_shape, "constant")
self.assertEqual(qobj_insts[3].pulse_shape, "gaussian_square")
self.assertDictEqual(
qobj_insts[0].parameters,
{"duration": 25, "sigma": 4, "amp": amp[0] * np.exp(1j * angle[0])},
)
self.assertDictEqual(
qobj_insts[1].parameters,
{"duration": 25, "sigma": 7.8, "amp": amp[1] * np.exp(1j * angle[1]), "beta": 4},
)
self.assertDictEqual(
qobj_insts[2].parameters, {"duration": 25, "amp": amp[2] * np.exp(1j * angle[2])}
)
self.assertDictEqual(
qobj_insts[3].parameters,
{"duration": 150, "sigma": 8, "amp": amp[3] * np.exp(1j * angle[3]), "width": 140},
)
self.assertEqual(
qobj.to_dict()["experiments"][0]["instructions"][0]["parameters"]["amp"],
amp[0] * np.exp(1j * angle[0]),
)
def test_assemble_parametric_unsupported(self):
"""Test that parametric pulses are translated to Waveform if they're not supported
by the backend during assemble time.
"""
sched = pulse.Schedule(name="test_parametric_to_sample_pulse")
sched += Play(
pulse.Drag(duration=25, amp=0.5, angle=-0.3, sigma=7.8, beta=4), DriveChannel(1)
)
sched += Play(pulse.Constant(duration=25, amp=1), DriveChannel(2))
backend = FakeOpenPulse3Q()
backend.configuration().parametric_pulses = ["something_extra"]
qobj = assemble(sched, backend)
self.assertNotEqual(qobj.config.pulse_library, [])
qobj_insts = qobj.experiments[0].instructions
self.assertFalse(hasattr(qobj_insts[0], "pulse_shape"))
def test_assemble_parametric_pulse_kwarg_with_backend_setting(self):
"""Test that parametric pulses respect the kwarg over backend"""
backend = FakeHanoi()
qc = QuantumCircuit(1, 1)
qc.x(0)
qc.measure(0, 0)
with pulse.build(backend, name="x") as x_q0:
pulse.play(pulse.Gaussian(duration=128, amp=0.1, sigma=16), pulse.drive_channel(0))
qc.add_calibration("x", (0,), x_q0)
qobj = assemble(qc, backend, parametric_pulses=["gaussian"])
self.assertEqual(qobj.config.parametric_pulses, ["gaussian"])
def test_assemble_parametric_pulse_kwarg_empty_list_with_backend_setting(self):
"""Test that parametric pulses respect the kwarg as empty list over backend"""
backend = FakeHanoi()
qc = QuantumCircuit(1, 1)
qc.x(0)
qc.measure(0, 0)
with pulse.build(backend, name="x") as x_q0:
pulse.play(pulse.Gaussian(duration=128, amp=0.1, sigma=16), pulse.drive_channel(0))
qc.add_calibration("x", (0,), x_q0)
qobj = assemble(qc, backend, parametric_pulses=[])
self.assertEqual(qobj.config.parametric_pulses, [])
def test_init_qubits_default(self):
"""Check that the init_qubits=None assemble option is passed on to the qobj."""
qobj = assemble(self.schedule, self.backend)
self.assertEqual(qobj.config.init_qubits, True)
def test_init_qubits_true(self):
"""Check that the init_qubits=True assemble option is passed on to the qobj."""
qobj = assemble(self.schedule, self.backend, init_qubits=True)
self.assertEqual(qobj.config.init_qubits, True)
def test_init_qubits_false(self):
"""Check that the init_qubits=False assemble option is passed on to the qobj."""
qobj = assemble(self.schedule, self.backend, init_qubits=False)
self.assertEqual(qobj.config.init_qubits, False)
def test_assemble_backend_rep_times_delays(self):
"""Check that rep_time and rep_delay are properly set from backend values."""
# use first entry from allowed backend values
rep_times = [2.0, 3.0, 4.0] # sec
rep_delay_range = [2.5e-3, 4.5e-3]
default_rep_delay = 3.0e-3
self.backend_config.rep_times = rep_times
setattr(self.backend_config, "rep_delay_range", rep_delay_range)
setattr(self.backend_config, "default_rep_delay", default_rep_delay)
# dynamic rep rates off
qobj = assemble(self.schedule, self.backend)
self.assertEqual(qobj.config.rep_time, int(rep_times[0] * 1e6))
self.assertEqual(hasattr(qobj.config, "rep_delay"), False)
# dynamic rep rates on
setattr(self.backend_config, "dynamic_reprate_enabled", True)
# RuntimeWarning bc ``rep_time`` is specified`` when dynamic rep rates not enabled
with self.assertWarns(RuntimeWarning):
qobj = assemble(self.schedule, self.backend)
self.assertEqual(qobj.config.rep_time, int(rep_times[0] * 1e6))
self.assertEqual(qobj.config.rep_delay, default_rep_delay * 1e6)
def test_assemble_user_rep_time_delay(self):
"""Check that user runtime config rep_time and rep_delay work."""
# set custom rep_time and rep_delay in runtime config
rep_time = 200.0e-6
rep_delay = 2.5e-6
self.config["rep_time"] = rep_time
self.config["rep_delay"] = rep_delay
# dynamic rep rates off
# RuntimeWarning bc using ``rep_delay`` when dynamic rep rates off
with self.assertWarns(RuntimeWarning):
qobj = assemble(self.schedule, self.backend, **self.config)
self.assertEqual(qobj.config.rep_time, int(rep_time * 1e6))
self.assertEqual(hasattr(qobj.config, "rep_delay"), False)
# now remove rep_delay and enable dynamic rep rates
# RuntimeWarning bc using ``rep_time`` when dynamic rep rates are enabled
del self.config["rep_delay"]
setattr(self.backend_config, "dynamic_reprate_enabled", True)
with self.assertWarns(RuntimeWarning):
qobj = assemble(self.schedule, self.backend, **self.config)
self.assertEqual(qobj.config.rep_time, int(rep_time * 1e6))
self.assertEqual(hasattr(qobj.config, "rep_delay"), False)
# use ``default_rep_delay``
# ``rep_time`` comes from allowed backend rep_times
rep_times = [0.5, 1.0, 1.5] # sec
self.backend_config.rep_times = rep_times
setattr(self.backend_config, "rep_delay_range", [0, 3.0e-6])
setattr(self.backend_config, "default_rep_delay", 2.2e-6)
del self.config["rep_time"]
qobj = assemble(self.schedule, self.backend, **self.config)
self.assertEqual(qobj.config.rep_time, int(rep_times[0] * 1e6))
self.assertEqual(qobj.config.rep_delay, 2.2)
# use qobj ``default_rep_delay``
self.config["rep_delay"] = 1.5e-6
qobj = assemble(self.schedule, self.backend, **self.config)
self.assertEqual(qobj.config.rep_time, int(rep_times[0] * 1e6))
self.assertEqual(qobj.config.rep_delay, 1.5)
# use ``rep_delay`` outside of ``rep_delay_range
self.config["rep_delay"] = 5.0e-6
with self.assertRaises(QiskitError):
assemble(self.schedule, self.backend, **self.config)
def test_assemble_with_individual_discriminators(self):
"""Test that assembly works with individual discriminators."""
disc_one = Discriminator("disc_one", test_params=True)
disc_two = Discriminator("disc_two", test_params=False)
schedule = Schedule()
schedule = schedule.append(
Acquire(5, AcquireChannel(0), MemorySlot(0), discriminator=disc_one),
)
schedule = schedule.append(
Acquire(5, AcquireChannel(1), MemorySlot(1), discriminator=disc_two),
)
qobj = assemble(
schedule,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
meas_map=[[0, 1]],
)
qobj_discriminators = qobj.experiments[0].instructions[0].discriminators
self.assertEqual(len(qobj_discriminators), 2)
self.assertEqual(qobj_discriminators[0].name, "disc_one")
self.assertEqual(qobj_discriminators[0].params["test_params"], True)
self.assertEqual(qobj_discriminators[1].name, "disc_two")
self.assertEqual(qobj_discriminators[1].params["test_params"], False)
def test_assemble_with_single_discriminators(self):
"""Test that assembly works with both a single discriminator."""
disc_one = Discriminator("disc_one", test_params=True)
schedule = Schedule()
schedule = schedule.append(
Acquire(5, AcquireChannel(0), MemorySlot(0), discriminator=disc_one),
)
schedule = schedule.append(
Acquire(5, AcquireChannel(1), MemorySlot(1)),
)
qobj = assemble(
schedule,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
meas_map=[[0, 1]],
)
qobj_discriminators = qobj.experiments[0].instructions[0].discriminators
self.assertEqual(len(qobj_discriminators), 1)
self.assertEqual(qobj_discriminators[0].name, "disc_one")
self.assertEqual(qobj_discriminators[0].params["test_params"], True)
def test_assemble_with_unequal_discriminators(self):
"""Test that assembly works with incorrect number of discriminators for
number of qubits."""
disc_one = Discriminator("disc_one", test_params=True)
disc_two = Discriminator("disc_two", test_params=False)
schedule = Schedule()
schedule += Acquire(5, AcquireChannel(0), MemorySlot(0), discriminator=disc_one)
schedule += Acquire(5, AcquireChannel(1), MemorySlot(1), discriminator=disc_two)
schedule += Acquire(5, AcquireChannel(2), MemorySlot(2))
with self.assertRaises(QiskitError):
assemble(
schedule,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
meas_map=[[0, 1, 2]],
)
def test_assemble_with_individual_kernels(self):
"""Test that assembly works with individual kernels."""
disc_one = Kernel("disc_one", test_params=True)
disc_two = Kernel("disc_two", test_params=False)
schedule = Schedule()
schedule = schedule.append(
Acquire(5, AcquireChannel(0), MemorySlot(0), kernel=disc_one),
)
schedule = schedule.append(
Acquire(5, AcquireChannel(1), MemorySlot(1), kernel=disc_two),
)
qobj = assemble(
schedule,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
meas_map=[[0, 1]],
)
qobj_kernels = qobj.experiments[0].instructions[0].kernels
self.assertEqual(len(qobj_kernels), 2)
self.assertEqual(qobj_kernels[0].name, "disc_one")
self.assertEqual(qobj_kernels[0].params["test_params"], True)
self.assertEqual(qobj_kernels[1].name, "disc_two")
self.assertEqual(qobj_kernels[1].params["test_params"], False)
def test_assemble_with_single_kernels(self):
"""Test that assembly works with both a single kernel."""
disc_one = Kernel("disc_one", test_params=True)
schedule = Schedule()
schedule = schedule.append(
Acquire(5, AcquireChannel(0), MemorySlot(0), kernel=disc_one),
)
schedule = schedule.append(
Acquire(5, AcquireChannel(1), MemorySlot(1)),
)
qobj = assemble(
schedule,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
meas_map=[[0, 1]],
)
qobj_kernels = qobj.experiments[0].instructions[0].kernels
self.assertEqual(len(qobj_kernels), 1)
self.assertEqual(qobj_kernels[0].name, "disc_one")
self.assertEqual(qobj_kernels[0].params["test_params"], True)
def test_assemble_with_unequal_kernels(self):
"""Test that assembly works with incorrect number of discriminators for
number of qubits."""
disc_one = Kernel("disc_one", test_params=True)
disc_two = Kernel("disc_two", test_params=False)
schedule = Schedule()
schedule += Acquire(5, AcquireChannel(0), MemorySlot(0), kernel=disc_one)
schedule += Acquire(5, AcquireChannel(1), MemorySlot(1), kernel=disc_two)
schedule += Acquire(5, AcquireChannel(2), MemorySlot(2))
with self.assertRaises(QiskitError):
assemble(
schedule,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
meas_map=[[0, 1, 2]],
)
def test_assemble_single_instruction(self):
"""Test assembling schedules, no lo config."""
inst = pulse.Play(pulse.Constant(100, 1.0), pulse.DriveChannel(0))
self.assertIsInstance(assemble(inst, self.backend), PulseQobj)
def test_assemble_overlapping_time(self):
"""Test that assembly errors when qubits are measured in overlapping time."""
schedule = Schedule()
schedule = schedule.append(
Acquire(5, AcquireChannel(0), MemorySlot(0)),
)
schedule = schedule.append(
Acquire(5, AcquireChannel(1), MemorySlot(1)) << 1,
)
with self.assertRaises(QiskitError):
assemble(
schedule,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
meas_map=[[0, 1]],
)
def test_assemble_meas_map_vs_insts(self):
"""Test that assembly errors when the qubits are measured in overlapping time
and qubits are not in the first meas_map list."""
schedule = Schedule()
schedule += Acquire(5, AcquireChannel(0), MemorySlot(0))
schedule += Acquire(5, AcquireChannel(1), MemorySlot(1))
schedule += Acquire(5, AcquireChannel(2), MemorySlot(2)) << 2
schedule += Acquire(5, AcquireChannel(3), MemorySlot(3)) << 2
with self.assertRaises(QiskitError):
assemble(
schedule,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
meas_map=[[0], [1, 2], [3]],
)
def test_assemble_non_overlapping_time_single_meas_map(self):
"""Test that assembly works when qubits are measured in non-overlapping
time within the same measurement map list."""
schedule = Schedule()
schedule = schedule.append(
Acquire(5, AcquireChannel(0), MemorySlot(0)),
)
schedule = schedule.append(
Acquire(5, AcquireChannel(1), MemorySlot(1)) << 5,
)
qobj = assemble(
schedule,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
meas_map=[[0, 1]],
)
self.assertIsInstance(qobj, PulseQobj)
def test_assemble_disjoint_time(self):
"""Test that assembly works when qubits are in disjoint meas map sets."""
schedule = Schedule()
schedule = schedule.append(
Acquire(5, AcquireChannel(0), MemorySlot(0)),
)
schedule = schedule.append(
Acquire(5, AcquireChannel(1), MemorySlot(1)) << 1,
)
qobj = assemble(
schedule,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
meas_map=[[0, 2], [1, 3]],
)
self.assertIsInstance(qobj, PulseQobj)
def test_assemble_valid_qubits(self):
"""Test that assembly works when qubits that are in the measurement map
is measured."""
schedule = Schedule()
schedule = schedule.append(
Acquire(5, AcquireChannel(1), MemorySlot(1)),
)
schedule = schedule.append(
Acquire(5, AcquireChannel(2), MemorySlot(2)),
)
schedule = schedule.append(
Acquire(5, AcquireChannel(3), MemorySlot(3)),
)
qobj = assemble(
schedule,
qubit_lo_freq=self.default_qubit_lo_freq,
meas_lo_freq=self.default_meas_lo_freq,
meas_map=[[0, 1, 2], [3]],
)
self.assertIsInstance(qobj, PulseQobj)
class TestPulseAssemblerMissingKwargs(QiskitTestCase):
"""Verify that errors are raised in case backend is not provided and kwargs are missing."""
def setUp(self):
super().setUp()
self.schedule = pulse.Schedule(name="fake_experiment")
self.backend = FakeOpenPulse2Q()
self.config = self.backend.configuration()
self.defaults = self.backend.defaults()
self.qubit_lo_freq = list(self.defaults.qubit_freq_est)
self.meas_lo_freq = list(self.defaults.meas_freq_est)
self.qubit_lo_range = self.config.qubit_lo_range
self.meas_lo_range = self.config.meas_lo_range
self.schedule_los = {
pulse.DriveChannel(0): self.qubit_lo_freq[0],
pulse.DriveChannel(1): self.qubit_lo_freq[1],
pulse.MeasureChannel(0): self.meas_lo_freq[0],
pulse.MeasureChannel(1): self.meas_lo_freq[1],
}
self.meas_map = self.config.meas_map
self.memory_slots = self.config.n_qubits
# default rep_time and rep_delay
self.rep_time = self.config.rep_times[0]
self.rep_delay = None
def test_defaults(self):
"""Test defaults work."""
qobj = assemble(
self.schedule,
qubit_lo_freq=self.qubit_lo_freq,
meas_lo_freq=self.meas_lo_freq,
qubit_lo_range=self.qubit_lo_range,
meas_lo_range=self.meas_lo_range,
schedule_los=self.schedule_los,
meas_map=self.meas_map,
memory_slots=self.memory_slots,
rep_time=self.rep_time,
rep_delay=self.rep_delay,
)
self.assertIsInstance(qobj, PulseQobj)
def test_missing_qubit_lo_freq(self):
"""Test error raised if qubit_lo_freq missing."""
with self.assertRaises(QiskitError):
assemble(
self.schedule,
qubit_lo_freq=None,
meas_lo_freq=self.meas_lo_freq,
qubit_lo_range=self.qubit_lo_range,
meas_lo_range=self.meas_lo_range,
meas_map=self.meas_map,
memory_slots=self.memory_slots,
rep_time=self.rep_time,
rep_delay=self.rep_delay,
)
def test_missing_meas_lo_freq(self):
"""Test error raised if meas_lo_freq missing."""
with self.assertRaises(QiskitError):
assemble(
self.schedule,
qubit_lo_freq=self.qubit_lo_freq,
meas_lo_freq=None,
qubit_lo_range=self.qubit_lo_range,
meas_lo_range=self.meas_lo_range,
meas_map=self.meas_map,
memory_slots=self.memory_slots,
rep_time=self.rep_time,
rep_delay=self.rep_delay,
)
def test_missing_memory_slots(self):
"""Test error is not raised if memory_slots are missing."""
qobj = assemble(
self.schedule,
qubit_lo_freq=self.qubit_lo_freq,
meas_lo_freq=self.meas_lo_freq,
qubit_lo_range=self.qubit_lo_range,
meas_lo_range=self.meas_lo_range,
schedule_los=self.schedule_los,
meas_map=self.meas_map,
memory_slots=None,
rep_time=self.rep_time,
rep_delay=self.rep_delay,
)
self.assertIsInstance(qobj, PulseQobj)
def test_missing_rep_time_and_delay(self):
"""Test qobj is valid if rep_time and rep_delay are missing."""
qobj = assemble(
self.schedule,
qubit_lo_freq=self.qubit_lo_freq,
meas_lo_freq=self.meas_lo_freq,
qubit_lo_range=self.qubit_lo_range,
meas_lo_range=self.meas_lo_range,
schedule_los=self.schedule_los,
meas_map=self.meas_map,
memory_slots=None,
rep_time=None,
rep_delay=None,
)
self.assertEqual(hasattr(qobj, "rep_time"), False)
self.assertEqual(hasattr(qobj, "rep_delay"), False)
def test_missing_meas_map(self):
"""Test that assembly still works if meas_map is missing."""
qobj = assemble(
self.schedule,
qubit_lo_freq=self.qubit_lo_freq,
meas_lo_freq=self.meas_lo_freq,
qubit_lo_range=self.qubit_lo_range,
meas_lo_range=self.meas_lo_range,
schedule_los=self.schedule_los,
meas_map=None,
memory_slots=self.memory_slots,
rep_time=self.rep_time,
rep_delay=self.rep_delay,
)
self.assertIsInstance(qobj, PulseQobj)
def test_missing_lo_ranges(self):
"""Test that assembly still works if lo_ranges are missing."""
qobj = assemble(
self.schedule,
qubit_lo_freq=self.qubit_lo_freq,
meas_lo_freq=self.meas_lo_freq,
qubit_lo_range=None,
meas_lo_range=None,
schedule_los=self.schedule_los,
meas_map=self.meas_map,
memory_slots=self.memory_slots,
rep_time=self.rep_time,
rep_delay=self.rep_delay,
)
self.assertIsInstance(qobj, PulseQobj)
def test_unsupported_meas_level(self):
"""Test that assembly raises an error if meas_level is not supported"""
backend = FakeOpenPulse2Q()
backend.configuration().meas_levels = [1, 2]
with self.assertRaises(QiskitError):
assemble(
self.schedule,
backend,
qubit_lo_freq=self.qubit_lo_freq,
meas_lo_freq=self.meas_lo_freq,
qubit_lo_range=self.qubit_lo_range,
meas_lo_range=self.meas_lo_range,
schedule_los=self.schedule_los,
meas_level=0,
meas_map=self.meas_map,
memory_slots=self.memory_slots,
rep_time=self.rep_time,
rep_delay=self.rep_delay,
)
def test_single_and_deprecated_acquire_styles(self):
"""Test that acquires are identically combined with Acquires that take a single channel."""
backend = FakeOpenPulse2Q()
new_style_schedule = Schedule()
acq_dur = 1200
for i in range(2):
new_style_schedule += Acquire(acq_dur, AcquireChannel(i), MemorySlot(i))
deprecated_style_schedule = Schedule()
for i in range(2):
deprecated_style_schedule += Acquire(1200, AcquireChannel(i), MemorySlot(i))
# The Qobj IDs will be different
n_qobj = assemble(new_style_schedule, backend)
n_qobj.qobj_id = None
n_qobj.experiments[0].header.name = None
d_qobj = assemble(deprecated_style_schedule, backend)
d_qobj.qobj_id = None
d_qobj.experiments[0].header.name = None
self.assertEqual(n_qobj, d_qobj)
assembled_acquire = n_qobj.experiments[0].instructions[0]
self.assertEqual(assembled_acquire.qubits, [0, 1])
self.assertEqual(assembled_acquire.memory_slot, [0, 1])
class StreamHandlerRaiseException(StreamHandler):
"""Handler class that will raise an exception on formatting errors."""
def handleError(self, record):
raise sys.exc_info()
class TestLogAssembler(QiskitTestCase):
"""Testing the log_assembly option."""
def setUp(self):
super().setUp()
logger = getLogger()
self.addCleanup(logger.setLevel, logger.level)
logger.setLevel("DEBUG")
self.output = io.StringIO()
logger.addHandler(StreamHandlerRaiseException(self.output))
self.circuit = QuantumCircuit(QuantumRegister(1))
def assertAssembleLog(self, log_msg):
"""Runs assemble and checks for logs containing specified message"""
assemble(self.circuit, shots=2000, memory=True)
self.output.seek(0)
# Filter unrelated log lines
output_lines = self.output.readlines()
assembly_log_lines = [x for x in output_lines if log_msg in x]
self.assertTrue(len(assembly_log_lines) == 1)
def test_assembly_log_time(self):
"""Check Total Assembly Time is logged"""
self.assertAssembleLog("Total Assembly Time")
if __name__ == "__main__":
unittest.main(verbosity=2)
|
https://github.com/acfilok96/Quantum-Computation
|
acfilok96
|
import qiskit
from qiskit import *
print(qiskit.__version__)
%matplotlib inline
from qiskit.tools.visualization import plot_histogram
from ibm_quantum_widgets import draw_circuit
circuit = QuantumCircuit(2,2)
circuit
circuit.draw(output='mpl')
circuit.x(0)
circuit.draw(output='mpl')
circuit.h(0)
circuit.draw(output='mpl')
circuit.cx(0,1)
circuit.draw(output='mpl')
circuit.measure([0,1],[1,1])
circuit.draw(output='mpl')
draw_circuit(circuit)
simulator = Aer.get_backend('qasm_simulator')
simulator
job = execute(circuit, backend=simulator, shots=1024)
job
result = job.result()
result
counts = result.get_counts()
counts
plot_histogram(counts)
|
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
"""
# For this simple recipe we will only need the QuantumCircuit method
from qiskit import QuantumCircuit
print("Ch 3: Moving between worlds 1")
print("-----------------------------")
# First we import the QASM string from IBM Qx
qasm_string=input("Paste in a QASM string from IBM Qx (or enter the full path and file name of a .qasm file to import):\n")
if qasm_string[-5:] == ".qasm":
# Create a quantum circuit from the file
circ=QuantumCircuit.from_qasm_file(qasm_string)
else:
# Create a quantum circuit from the string
circ=QuantumCircuit.from_qasm_str(qasm_string)
# Print the circuitCoin.qasm
print("Imported quantum circuit")
print("------------------------")
print(circ)
|
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.
"""Test the Check Map pass"""
import unittest
from qiskit import QuantumRegister, QuantumCircuit, ClassicalRegister
from qiskit.circuit.library import CXGate
from qiskit.transpiler.passes import CheckMap
from qiskit.transpiler import CouplingMap, Target
from qiskit.converters import circuit_to_dag
from qiskit.test import QiskitTestCase
class TestCheckMapCX(QiskitTestCase):
"""Tests the CheckMap pass with CX gates"""
def test_trivial_nop_map(self):
"""Trivial map in a circuit without entanglement
qr0:---[H]---
qr1:---[H]---
qr2:---[H]---
CouplingMap map: None
"""
qr = QuantumRegister(3, "qr")
circuit = QuantumCircuit(qr)
circuit.h(qr)
coupling = CouplingMap()
dag = circuit_to_dag(circuit)
pass_ = CheckMap(coupling)
pass_.run(dag)
self.assertTrue(pass_.property_set["is_swap_mapped"])
def test_trivial_nop_map_target(self):
"""Trivial map in a circuit without entanglement
qr0:---[H]---
qr1:---[H]---
qr2:---[H]---
CouplingMap map: None
"""
qr = QuantumRegister(3, "qr")
circuit = QuantumCircuit(qr)
circuit.h(qr)
target = Target()
dag = circuit_to_dag(circuit)
pass_ = CheckMap(target)
pass_.run(dag)
self.assertTrue(pass_.property_set["is_swap_mapped"])
def test_swap_mapped_true(self):
"""Mapped is easy to check
qr0:--(+)-[H]-(+)-
| |
qr1:---.-------|--
|
qr2:-----------.--
CouplingMap map: [1]--[0]--[2]
"""
qr = QuantumRegister(3, "qr")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[1])
circuit.h(qr[0])
circuit.cx(qr[0], qr[2])
coupling = CouplingMap([[0, 1], [0, 2]])
dag = circuit_to_dag(circuit)
pass_ = CheckMap(coupling)
pass_.run(dag)
self.assertTrue(pass_.property_set["is_swap_mapped"])
def test_swap_mapped_false(self):
"""Needs [0]-[1] in a [0]--[2]--[1]
qr0:--(+)--
|
qr1:---.---
CouplingMap map: [0]--[2]--[1]
"""
qr = QuantumRegister(2, "qr")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[1])
coupling = CouplingMap([[0, 2], [2, 1]])
dag = circuit_to_dag(circuit)
pass_ = CheckMap(coupling)
pass_.run(dag)
self.assertFalse(pass_.property_set["is_swap_mapped"])
def test_swap_mapped_false_target(self):
"""Needs [0]-[1] in a [0]--[2]--[1]
qr0:--(+)--
|
qr1:---.---
CouplingMap map: [0]--[2]--[1]
"""
qr = QuantumRegister(2, "qr")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[1])
target = Target(num_qubits=2)
target.add_instruction(CXGate(), {(0, 2): None, (2, 1): None})
dag = circuit_to_dag(circuit)
pass_ = CheckMap(target)
pass_.run(dag)
self.assertFalse(pass_.property_set["is_swap_mapped"])
def test_swap_mapped_cf_true(self):
"""Check control flow blocks are mapped."""
num_qubits = 3
coupling = CouplingMap.from_line(num_qubits)
qr = QuantumRegister(3)
cr = ClassicalRegister(3)
circuit = QuantumCircuit(qr, cr)
true_body = QuantumCircuit(qr, cr)
true_body.swap(0, 1)
true_body.cx(2, 1)
circuit.if_else((cr[0], 0), true_body, None, qr, cr)
dag = circuit_to_dag(circuit)
pass_ = CheckMap(coupling)
pass_.run(dag)
self.assertTrue(pass_.property_set["is_swap_mapped"])
def test_swap_mapped_cf_false(self):
"""Check control flow blocks are not mapped."""
num_qubits = 3
coupling = CouplingMap.from_line(num_qubits)
qr = QuantumRegister(3)
cr = ClassicalRegister(3)
circuit = QuantumCircuit(qr, cr)
true_body = QuantumCircuit(qr)
true_body.cx(0, 2)
circuit.if_else((cr[0], 0), true_body, None, qr, [])
dag = circuit_to_dag(circuit)
pass_ = CheckMap(coupling)
pass_.run(dag)
self.assertFalse(pass_.property_set["is_swap_mapped"])
def test_swap_mapped_cf_layout_change_false(self):
"""Check control flow blocks with layout change are not mapped."""
num_qubits = 3
coupling = CouplingMap.from_line(num_qubits)
qr = QuantumRegister(3)
cr = ClassicalRegister(3)
circuit = QuantumCircuit(qr, cr)
true_body = QuantumCircuit(qr, cr)
true_body.cx(1, 2)
circuit.if_else((cr[0], 0), true_body, None, qr[[1, 0, 2]], cr)
dag = circuit_to_dag(circuit)
pass_ = CheckMap(coupling)
pass_.run(dag)
self.assertFalse(pass_.property_set["is_swap_mapped"])
def test_swap_mapped_cf_layout_change_true(self):
"""Check control flow blocks with layout change are mapped."""
num_qubits = 3
coupling = CouplingMap.from_line(num_qubits)
qr = QuantumRegister(3)
cr = ClassicalRegister(3)
circuit = QuantumCircuit(qr, cr)
true_body = QuantumCircuit(qr)
true_body.cx(0, 2)
circuit.if_else((cr[0], 0), true_body, None, qr[[1, 0, 2]], [])
dag = circuit_to_dag(circuit)
pass_ = CheckMap(coupling)
pass_.run(dag)
self.assertTrue(pass_.property_set["is_swap_mapped"])
def test_swap_mapped_cf_different_bits(self):
"""Check control flow blocks with layout change are mapped."""
num_qubits = 3
coupling = CouplingMap.from_line(num_qubits)
qr = QuantumRegister(3)
cr = ClassicalRegister(3)
circuit = QuantumCircuit(qr, cr)
true_body = QuantumCircuit(3, 1)
true_body.cx(0, 2)
circuit.if_else((cr[0], 0), true_body, None, qr[[1, 0, 2]], [cr[0]])
dag = circuit_to_dag(circuit)
pass_ = CheckMap(coupling)
pass_.run(dag)
self.assertTrue(pass_.property_set["is_swap_mapped"])
def test_disjoint_controlflow_bits(self):
"""test control flow on with different registers"""
num_qubits = 4
coupling = CouplingMap.from_line(num_qubits)
qr1 = QuantumRegister(4, "qr")
qr2 = QuantumRegister(3, "qrif")
cr = ClassicalRegister(3)
circuit = QuantumCircuit(qr1, cr)
true_body = QuantumCircuit(qr2, [cr[0]])
true_body.cx(0, 2)
circuit.if_else((cr[0], 0), true_body, None, qr1[[1, 0, 2]], [cr[0]])
dag = circuit_to_dag(circuit)
pass_ = CheckMap(coupling)
pass_.run(dag)
self.assertTrue(pass_.property_set["is_swap_mapped"])
def test_nested_controlflow_true(self):
"""Test nested controlflow with true evaluation."""
num_qubits = 4
coupling = CouplingMap.from_line(num_qubits)
qr1 = QuantumRegister(4, "qr")
qr2 = QuantumRegister(3, "qrif")
cr1 = ClassicalRegister(1)
cr2 = ClassicalRegister(1)
circuit = QuantumCircuit(qr1, cr1)
true_body = QuantumCircuit(qr2, cr2)
for_body = QuantumCircuit(3)
for_body.cx(0, 2)
true_body.for_loop(range(5), body=for_body, qubits=qr2, clbits=[])
circuit.if_else((cr1[0], 0), true_body, None, qr1[[1, 0, 2]], cr1)
dag = circuit_to_dag(circuit)
pass_ = CheckMap(coupling)
pass_.run(dag)
self.assertTrue(pass_.property_set["is_swap_mapped"])
def test_nested_controlflow_false(self):
"""Test nested controlflow with true evaluation."""
num_qubits = 4
coupling = CouplingMap.from_line(num_qubits)
qr1 = QuantumRegister(4, "qr")
qr2 = QuantumRegister(3, "qrif")
cr1 = ClassicalRegister(1)
cr2 = ClassicalRegister(1)
circuit = QuantumCircuit(qr1, cr1)
true_body = QuantumCircuit(qr2, cr2)
for_body = QuantumCircuit(3)
for_body.cx(0, 2)
true_body.for_loop(range(5), body=for_body, qubits=qr2, clbits=[])
circuit.if_else((cr1[0], 0), true_body, None, qr1[[0, 1, 2]], cr1)
dag = circuit_to_dag(circuit)
pass_ = CheckMap(coupling)
pass_.run(dag)
self.assertFalse(pass_.property_set["is_swap_mapped"])
def test_nested_conditional_unusual_bit_order(self):
"""Test that `CheckMap` succeeds when inner conditional blocks have clbits that are involved
in their own (nested conditionals), and the binding order is not the same as the
bit-definition order. See gh-10394."""
qr = QuantumRegister(2, "q")
cr1 = ClassicalRegister(2, "c1")
cr2 = ClassicalRegister(2, "c2")
# Note that the bits here are not in the same order as in the outer circuit object, but they
# are the same as the binding order in the `if_test`, so everything maps `{x: x}` and it
# should all be fine. This kind of thing is a staple of the control-flow builders.
inner_order = [cr2[0], cr1[0], cr2[1], cr1[1]]
inner = QuantumCircuit(qr, inner_order, cr1, cr2)
inner.cx(0, 1).c_if(cr2, 3)
outer = QuantumCircuit(qr, cr1, cr2)
outer.if_test((cr1, 3), inner, outer.qubits, inner_order)
pass_ = CheckMap(CouplingMap.from_line(2))
pass_(outer)
self.assertTrue(pass_.property_set["is_swap_mapped"])
if __name__ == "__main__":
unittest.main()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
ghz = QuantumCircuit(5)
ghz.h(0)
ghz.cx(0,range(1,5))
ghz.draw(output='mpl')
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
# load necessary Runtime libraries
from qiskit_ibm_runtime import QiskitRuntimeService, Sampler, Session
backend = "ibmq_qasm_simulator" # use the simulator
from qiskit.circuit import Parameter
from qiskit.opflow import I, X, Z
mu = Parameter('$\\mu$')
ham_pauli = mu * X
cc = Parameter('$c$')
ww = Parameter('$\\omega$')
ham_res = -(1/2)*ww*(I^Z) + cc*(X^X) + (ham_pauli^I)
tt = Parameter('$t$')
U_ham = (tt*ham_res).exp_i()
from qiskit import transpile
from qiskit.circuit import ClassicalRegister
from qiskit.opflow import PauliTrotterEvolution, Suzuki
import numpy as np
num_trot_steps = 5
total_time = 10
cr = ClassicalRegister(1, 'c')
spec_op = PauliTrotterEvolution(trotter_mode=Suzuki(order=2, reps=num_trot_steps)).convert(U_ham)
spec_circ = spec_op.to_circuit()
spec_circ_t = transpile(spec_circ, basis_gates=['sx', 'rz', 'cx'])
spec_circ_t.add_register(cr)
spec_circ_t.measure(0, cr[0])
spec_circ_t.draw('mpl')
# fixed Parameters
fixed_params = {
cc: 0.3,
mu: 0.7,
tt: total_time
}
# Parameter value for single circuit
param_keys = list(spec_circ_t.parameters)
# run through all the ww values to create a List of Lists of Parameter value
num_pts = 101
wvals = np.linspace(-2, 2, num_pts)
param_vals = []
for wval in wvals:
all_params = {**fixed_params, **{ww: wval}}
param_vals.append([all_params[key] for key in param_keys])
with Session(backend=backend):
sampler = Sampler()
job = sampler.run(
circuits=[spec_circ_t]*num_pts,
parameter_values=param_vals,
shots=1e5
)
result = job.result()
Zexps = []
for dist in result.quasi_dists:
if 1 in dist:
Zexps.append(1 - 2*dist[1])
else:
Zexps.append(1)
from qiskit.opflow import PauliExpectation, Zero
param_bind = {
cc: 0.3,
mu: 0.7,
tt: total_time
}
init_state = Zero^2
obsv = I^Z
Zexp_exact = (U_ham @ init_state).adjoint() @ obsv @ (U_ham @ init_state)
diag_meas_op = PauliExpectation().convert(Zexp_exact)
Zexact_values = []
for w_set in wvals:
param_bind[ww] = w_set
Zexact_values.append(np.real(diag_meas_op.bind_parameters(param_bind).eval()))
import matplotlib.pyplot as plt
plt.style.use('dark_background')
fig, ax = plt.subplots(dpi=100)
ax.plot([-param_bind[mu], -param_bind[mu]], [0, 1], ls='--', color='purple')
ax.plot([param_bind[mu], param_bind[mu]], [0, 1], ls='--', color='purple')
ax.plot(wvals, Zexact_values, label='Exact')
ax.plot(wvals, Zexps, label=f"{backend}")
ax.set_xlabel(r'$\omega$ (arb)')
ax.set_ylabel(r'$\langle Z \rangle$ Expectation')
ax.legend()
import qiskit_ibm_runtime
qiskit_ibm_runtime.version.get_version_info()
from qiskit.tools.jupyter import *
%qiskit_version_table
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
# Build a quantum circuit
circuit = QuantumCircuit(3, 3)
circuit.x(1)
circuit.h(range(3))
circuit.cx(0, 1)
circuit.measure(range(3), range(3));
print(circuit)
circuit.draw()
# Matplotlib Drawing
circuit.draw(output='mpl')
# Draw a new circuit with barriers and more registers
q_a = QuantumRegister(3, name='qa')
q_b = QuantumRegister(5, name='qb')
c_a = ClassicalRegister(3)
c_b = ClassicalRegister(5)
circuit = QuantumCircuit(q_a, q_b, c_a, c_b)
circuit.x(q_a[1])
circuit.x(q_b[1])
circuit.x(q_b[2])
circuit.x(q_b[4])
circuit.barrier()
circuit.h(q_a)
circuit.barrier(q_a)
circuit.h(q_b)
circuit.cswap(q_b[0], q_b[1], q_b[2])
circuit.cswap(q_b[2], q_b[3], q_b[4])
circuit.cswap(q_b[3], q_b[4], q_b[0])
circuit.barrier(q_b)
circuit.measure(q_a, c_a)
circuit.measure(q_b, c_b);
# Draw the circuit
circuit.draw(output='mpl')
# Draw the circuit with reversed bit order
circuit.draw(output='mpl', reverse_bits=True)
# Draw the circuit without barriers
circuit.draw(output='mpl', plot_barriers=False)
# Draw the circuit without barriers and reverse bit order
circuit.draw(output='mpl', plot_barriers=False, reverse_bits=True)
# Set line length to 80 for above circuit
circuit.draw(output='text')
# Change the background color in mpl
style = {'backgroundcolor': 'lightgreen'}
circuit.draw(output='mpl', style=style)
# Scale the mpl output to 1/2 the normal size
circuit.draw(output='mpl', scale=0.5)
from qiskit.tools.visualization import circuit_drawer
circuit_drawer(circuit, output='mpl', plot_barriers=False)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
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()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit_aer.utils import approximate_quantum_error, approximate_noise_model
import numpy as np
# Import Aer QuantumError functions that will be used
from qiskit_aer.noise import amplitude_damping_error, reset_error, pauli_error
from qiskit.quantum_info import Kraus
gamma = 0.23
error = amplitude_damping_error(gamma)
results = approximate_quantum_error(error, operator_string="reset")
print(results)
p = (1 + gamma - np.sqrt(1 - gamma)) / 2
q = 0
print("")
print("Expected results:")
print("P(0) = {}".format(1-(p+q)))
print("P(1) = {}".format(p))
print("P(2) = {}".format(q))
gamma = 0.23
K0 = np.array([[1,0],[0,np.sqrt(1-gamma)]])
K1 = np.array([[0,np.sqrt(gamma)],[0,0]])
results = approximate_quantum_error(Kraus([K0, K1]), operator_string="reset")
print(results)
reset_to_0 = Kraus([np.array([[1,0],[0,0]]), np.array([[0,1],[0,0]])])
reset_to_1 = Kraus([np.array([[0,0],[1,0]]), np.array([[0,0],[0,1]])])
reset_kraus = [reset_to_0, reset_to_1]
gamma = 0.23
error = amplitude_damping_error(gamma)
results = approximate_quantum_error(error, operator_list=reset_kraus)
print(results)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import numpy as np
# Import Qiskit
from qiskit import QuantumCircuit, transpile
from qiskit_aer import AerSimulator
# Construct quantum circuit
circ = QuantumCircuit(2, 2)
circ.h(0)
circ.cx(0, 1)
circ.measure([0,1], [0,1])
# Select the AerSimulator from the Aer provider
simulator = AerSimulator(method='matrix_product_state')
# Run and get counts, using the matrix_product_state method
tcirc = transpile(circ, simulator)
result = simulator.run(tcirc).result()
counts = result.get_counts(0)
counts
circ = QuantumCircuit(2, 2)
circ.h(0)
circ.cx(0, 1)
# Define a snapshot that shows the current state vector
circ.save_statevector(label='my_sv')
circ.save_matrix_product_state(label='my_mps')
circ.measure([0,1], [0,1])
# Execute and get saved data
tcirc = transpile(circ, simulator)
result = simulator.run(tcirc).result()
data = result.data(0)
#print the result data
data
num_qubits = 50
circ = QuantumCircuit(num_qubits, num_qubits)
# Create EPR state
circ.h(0)
for i in range (0, num_qubits-1):
circ.cx(i, i+1)
# Measure
circ.measure(range(num_qubits), range(num_qubits))
tcirc = transpile(circ, simulator)
result = simulator.run(tcirc).result()
print("Time taken: {} sec".format(result.time_taken))
result.get_counts()
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/UST-QuAntiL/nisq-analyzer-content
|
UST-QuAntiL
|
from qiskit import QuantumRegister, ClassicalRegister
from qiskit import QuantumCircuit
qc = QuantumCircuit()
q = QuantumRegister(5, 'q')
c = ClassicalRegister(5, 'c')
qc.add_register(q)
qc.add_register(c)
qc.h(q[0])
qc.h(q[1])
qc.h(q[2])
qc.h(q[3])
# add identity gates to the circuit to enable replacing the oracle after 2 gates per qubit
qc.i(q[0])
qc.i(q[1])
qc.i(q[2])
qc.i(q[3])
# ancilla qubit
qc.h(q[4])
qc.z(q[4])
qc.barrier()
# searched bit string: s = 00110 (first bit is ancilla and using qiskit's reverse qubit ordering)
qc.cx(q[1], q[4])
qc.cx(q[2], q[4])
qc.barrier()
qc.h(q[0])
qc.h(q[1])
qc.h(q[2])
qc.h(q[3])
qc.i(q[4])
qc.measure([0, 1, 2, 3], [0, 1, 2, 3])
def get_circuit(**kwargs):
"""Get base circuit of the Bernstein-Vazirani algorithm."""
return qc
|
https://github.com/ElePT/qiskit-algorithms-test
|
ElePT
|
# 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.
"""Test Providers that support BackendV2 interface"""
import unittest
from test.python.algorithms import QiskitAlgorithmsTestCase
from qiskit import QuantumCircuit
from qiskit.providers.fake_provider import FakeProvider
from qiskit.providers.fake_provider.fake_backend_v2 import FakeBackendSimple
from qiskit.utils import QuantumInstance
from qiskit_algorithms import VQE, Grover, AmplificationProblem
from qiskit.opflow import X, Z, I
from qiskit_algorithms.optimizers import SPSA
from qiskit.circuit.library import TwoLocal
class TestBackendV2(QiskitAlgorithmsTestCase):
"""test BackendV2 interface"""
def setUp(self):
super().setUp()
self._provider = FakeProvider()
self._qasm = FakeBackendSimple()
self.seed = 50
def test_vqe_qasm(self):
"""Test the VQE on QASM simulator."""
optimizer = SPSA(maxiter=300, last_avg=5)
wavefunction = TwoLocal(rotation_blocks="ry", entanglement_blocks="cz")
with self.assertWarns(DeprecationWarning):
h2_op = (
-1.052373245772859 * (I ^ I)
+ 0.39793742484318045 * (I ^ Z)
- 0.39793742484318045 * (Z ^ I)
- 0.01128010425623538 * (Z ^ Z)
+ 0.18093119978423156 * (X ^ X)
)
qasm_simulator = QuantumInstance(
self._qasm, shots=1024, seed_simulator=self.seed, seed_transpiler=self.seed
)
with self.assertWarns(DeprecationWarning):
vqe = VQE(
ansatz=wavefunction,
optimizer=optimizer,
max_evals_grouped=1,
quantum_instance=qasm_simulator,
)
result = vqe.compute_minimum_eigenvalue(operator=h2_op)
self.assertAlmostEqual(result.eigenvalue.real, -1.86, delta=0.05)
def test_run_circuit_oracle(self):
"""Test execution with a quantum circuit oracle"""
oracle = QuantumCircuit(2)
oracle.cz(0, 1)
problem = AmplificationProblem(oracle, is_good_state=["11"])
with self.assertWarns(DeprecationWarning):
qi = QuantumInstance(
self._provider.get_backend("fake_yorktown"), seed_simulator=12, seed_transpiler=32
)
with self.assertWarns(DeprecationWarning):
grover = Grover(quantum_instance=qi)
result = grover.amplify(problem)
self.assertIn(result.top_measurement, ["11"])
def test_run_circuit_oracle_single_experiment_backend(self):
"""Test execution with a quantum circuit oracle"""
oracle = QuantumCircuit(2)
oracle.cz(0, 1)
problem = AmplificationProblem(oracle, is_good_state=["11"])
backend = self._provider.get_backend("fake_yorktown")
backend._configuration.max_experiments = 1
with self.assertWarns(DeprecationWarning):
qi = QuantumInstance(
self._provider.get_backend("fake_yorktown"), seed_simulator=12, seed_transpiler=32
)
with self.assertWarns(DeprecationWarning):
grover = Grover(quantum_instance=qi)
result = grover.amplify(problem)
self.assertIn(result.top_measurement, ["11"])
if __name__ == "__main__":
unittest.main()
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
#
# your solution is here
#
#
# your solution is here
#
# operator for the test
A = [
[0.4,0.6,0],
[0.2,0.1,0.7],
[0.4,0.3,0.3]
]
# state for test
v = [0.1,0.3,0.6]
#
# your solution is here
#
# the initial state
initial = [0.5, 0, 0.5, 0]
# probabilistic operator for symbol a
A = [
[0.5, 0, 0, 0],
[0.25, 1, 0, 0],
[0, 0, 1, 0],
[0.25, 0, 0, 1]
]
# probabilistic operator for symbol b
B = [
[1, 0, 0, 0],
[0, 1, 0.25, 0],
[0, 0, 0.5, 0],
[0, 0, 0.25, 1]
]
#
# your solution is here
#
|
https://github.com/Dpbm/scientific-research-1-quantum-oracles
|
Dpbm
|
import numpy as np
# Importing standard Qiskit libraries
from qiskit import QuantumCircuit, transpile, Aer, IBMQ
from qiskit.tools.jupyter import *
from qiskit.visualization import *
from ibm_quantum_widgets import *
from qiskit.providers.aer import QasmSimulator
# Loading your IBM Quantum account(s)
provider = IBMQ.load_account()
from qiskit.circuit.library.standard_gates import XGate, HGate
from operator import *
n = 3
N = 8 #2**n
index_colour_table = {}
colour_hash_map = {}
index_colour_table = {'000':"yellow", '001':"red", '010':"blue", '011':"red", '100':"green", '101':"blue", '110':"orange", '111':"red"}
colour_hash_map = {"yellow":'100', "red":'011', "blue":'000', "green":'001', "orange":'010'}
def database_oracle(index_colour_table, colour_hash_map):
circ_database = QuantumCircuit(n + n)
for i in range(N):
circ_data = QuantumCircuit(n)
idx = bin(i)[2:].zfill(n) # removing the "0b" prefix appended by the bin() funtion
colour = index_colour_table[idx]
colour_hash = colour_hash_map[colour][::-1]
for j in range(n):
if colour_hash[j] == '1':
circ_data.x(j)
# qiskit maps the rightmost bit as the 0th qubit -> qn, ..., q0
# we therefore reverse the index string -> q0, ..., qn
data_gate = circ_data.to_gate(label=colour).control(num_ctrl_qubits=n, ctrl_state=idx, label="index-"+colour)
circ_database.append(data_gate, list(range(n+n)))
return circ_database
# drawing the database oracle circuit
print("Database Encoding")
database_oracle(index_colour_table, colour_hash_map).draw()
circ_data = QuantumCircuit(n)
m = 4
idx = bin(m)[2:].zfill(n) # removing the "0b" prefix appended by the bin() funtion
colour = index_colour_table[idx]
colour_hash = colour_hash_map[colour][::-1]
for j in range(n):
if colour_hash[j] == '1':
circ_data.x(j)
print("Internal colour encoding for the colour green (as an example)");
circ_data.draw()
def oracle_grover(database, data_entry):
circ_grover = QuantumCircuit(n + n + 1)
circ_grover.append(database, list(range(n+n)))
target_reflection_gate = XGate().control(num_ctrl_qubits=n, ctrl_state=colour_hash_map[data_entry], label="Reflection of " + "\"" + data_entry + "\" Target")
# control() missing 1 required positional argument: 'self' .... if only 'XGate' used instead of 'XGate()'
# The “missing 1 required positional argument: 'self'” error is raised when you do not instantiate an object of a class before calling a class method. This error is also raised when you incorrectly instantiate a class.
circ_grover.append(target_reflection_gate, list(range(n, n+n+1)))
circ_grover.append(database, list(range(n+n)))
return circ_grover
print("Grover Oracle (target example: orange)")
oracle_grover(database_oracle(index_colour_table, colour_hash_map).to_gate(label="Database Encoding"), "orange").decompose().draw()
def mcz_gate(num_qubits):
num_controls = num_qubits - 1
mcz_gate = QuantumCircuit(num_qubits)
target_mcz = QuantumCircuit(1)
target_mcz.z(0)
target_mcz = target_mcz.to_gate(label="Z_Gate").control(num_ctrl_qubits=num_controls, ctrl_state=None, label="MCZ")
mcz_gate.append(target_mcz, list(range(num_qubits)))
return mcz_gate.reverse_bits()
print("Multi-controlled Z (MCZ) Gate")
mcz_gate(n).decompose().draw()
def diffusion_operator(num_qubits):
circ_diffusion = QuantumCircuit(num_qubits)
qubits_list = list(range(num_qubits))
# Layer of H^n gates
circ_diffusion.h(qubits_list)
# Layer of X^n gates
circ_diffusion.x(qubits_list)
# Layer of Multi-controlled Z (MCZ) Gate
circ_diffusion = circ_diffusion.compose(mcz_gate(num_qubits), qubits_list)
# Layer of X^n gates
circ_diffusion.x(qubits_list)
# Layer of H^n gates
circ_diffusion.h(qubits_list)
return circ_diffusion
print("Diffusion Circuit")
diffusion_operator(n).draw()
# Putting it all together ... !!!
item = "green"
print("Searching for the index of the colour", item)
circuit = QuantumCircuit(n + n + 1, n)
circuit.x(n + n)
circuit.barrier()
circuit.h(list(range(n)))
circuit.h(n+n)
circuit.barrier()
unitary_oracle = oracle_grover(database_oracle(index_colour_table, colour_hash_map).to_gate(label="Database Encoding"), item).to_gate(label="Oracle Operator")
unitary_diffuser = diffusion_operator(n).to_gate(label="Diffusion Operator")
M = countOf(index_colour_table.values(), item)
Q = int(np.pi * np.sqrt(N/M) / 4)
for i in range(Q):
circuit.append(unitary_oracle, list(range(n + n + 1)))
circuit.append(unitary_diffuser, list(range(n)))
circuit.barrier()
circuit.measure(list(range(n)), list(range(n)))
circuit.draw()
backend_sim = Aer.get_backend('qasm_simulator')
job_sim = backend_sim.run(transpile(circuit, backend_sim), shots=1024)
result_sim = job_sim.result()
counts = result_sim.get_counts(circuit)
if M==1:
print("Index of the colour", item, "is the index with most probable outcome")
else:
print("Indices of the colour", item, "are the indices the most probable outcomes")
from qiskit.visualization import plot_histogram
plot_histogram(counts)
|
https://github.com/pranavdurai10/quantum-gates
|
pranavdurai10
|
'''
///////////////////////////////////////////////////////////////////////////
Code written by Pranav Durai for Quantum Computer on 02.06.2023 @ 21:34:23
Component: Toffoli Gate
Framework: Qiskit 0.43.0
///////////////////////////////////////////////////////////////////////////
'''
# Import necessary libraries
from qiskit import QuantumCircuit, Aer, execute
# Create a quantum circuit with three qubits
circuit = QuantumCircuit(3)
# Apply the Toffoli gate
circuit.ccx(0, 1, 2)
# Measure the qubits
circuit.measure_all()
# Simulate the circuit using the local Aer simulator
simulator = Aer.get_backend('qasm_simulator')
job = execute(circuit, simulator, shots=1)
# Get the result
result = job.result()
counts = result.get_counts(circuit)
# Print the measurement outcome
print("Measurement outcome:", list(counts.keys())[0])
|
https://github.com/aaghazaly/quantum-project-using-qiskit
|
aaghazaly
|
'''
Deutsch-Jozsa Algorithm
Consider a function f(x) that takes as input n-bit strings x and returns 0 or 1. Suppose we are
promised that f(x) is either a constant function that takes the same value c in {0,1} on all
inputs x, or a balanced function that takes each value 0 and 1 on exactly half of the inputs.
The goal is to decide whether f is constant or balanced by making as few function evaluations
as possible. Classically, it requires 2^{n-1}+1 function evaluations in the worst case. Using
the Deutsch-Jozsa algorithm, the question can be answered with just one function evaluation.
Deutsch's algorithm is the simpler case of Deutsch-Jozsa Algorithm which has a function f(x)
which takes 1-bit as input.
Source: https://github.com/Qiskit/ibmqx-user-guides/blob/master/rst/full-user-guide/004-Quantum_Algorithms/080-Deutsch-Jozsa_Algorithm.rst
'''
from qiskit import IBMQ, BasicAer
from qiskit.providers.ibmq import least_busy
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute
from qiskit.tools.monitor import job_monitor
qr = QuantumRegister(2) # Initialize two qubits
cr = ClassicalRegister(2) # Initialize two bits for record measurements
circuit = QuantumCircuit(qr, cr)
circuit.x(qr[1]) # initialize the ancilla qubit in the |1> state
circuit.barrier()
# First step of quantum algorithms - Prepare the superposition
# For superposition, we apply the Hadamard gate on both qubits
circuit.h(qr[0])
circuit.h(qr[1])
circuit.barrier()
# Oracle function
circuit.cx(qr[0], qr[1])
circuit.barrier()
# Apply Hadamard gates after querying oracle function
circuit.h(qr[0])
circuit.h(qr[1])
circuit.barrier()
# Measure qubit
circuit.measure(qr[0], cr[0])
# Run our circuit with local simulator
backend = BasicAer.get_backend('qasm_simulator')
shots = 1024
results = execute(circuit, backend=backend, shots=shots).result()
answer = results.get_counts()
print("Simulator result")
for c1c0 in answer:
print(f'c0 = {c1c0[1]} ({answer[c1c0]} shots)')
# C0 observed as 1 in 1024 shots
# It indicates f(0) != f(1)
# Run our circuit with real devices
IBMQ.load_account()
IBMQ.backends()
backend_lb = least_busy(IBMQ.backends(simulator=False))
backend = backend_lb
shots = 1024
job_exp = execute(circuit, backend=backend, shots=shots)
job_monitor(job_exp, interval=2)
results = job_exp.result()
answer = results.get_counts(circuit)
print("Real Device Result")
for c1c0 in answer:
print(f'c0 = {c1c0[1]} ({answer[c1c0]} shots)')
# As we can see in results, most of the results for C0 is 1
# It indicates f(0) != f(1)
# The results with C0 = 0 occur due to errors in the quantum computation.
|
https://github.com/swe-train/qiskit__qiskit
|
swe-train
|
# 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.
"""`_text_circuit_drawer` draws a circuit in ascii art"""
import pathlib
import os
import tempfile
import unittest.mock
from codecs import encode
from math import pi
import numpy
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, transpile
from qiskit.circuit import Gate, Parameter, Qubit, Clbit, Instruction
from qiskit.quantum_info.operators import SuperOp
from qiskit.quantum_info.random import random_unitary
from qiskit.test import QiskitTestCase
from qiskit.transpiler.layout import Layout, TranspileLayout
from qiskit.visualization import circuit_drawer
from qiskit.visualization.circuit import text as elements
from qiskit.visualization.circuit.circuit_visualization import _text_circuit_drawer
from qiskit.extensions import UnitaryGate, HamiltonianGate
from qiskit.extensions.quantum_initializer import UCGate
from qiskit.circuit.library import (
HGate,
U2Gate,
U3Gate,
XGate,
CZGate,
ZGate,
YGate,
U1Gate,
SwapGate,
RZZGate,
CU3Gate,
CU1Gate,
CPhaseGate,
)
from qiskit.transpiler.passes import ApplyLayout
from qiskit.utils.optionals import HAS_TWEEDLEDUM
from .visualization import path_to_diagram_reference, QiskitVisualizationTestCase
if HAS_TWEEDLEDUM:
from qiskit.circuit.classicalfunction import classical_function
from qiskit.circuit.classicalfunction.types import Int1
class TestTextDrawerElement(QiskitTestCase):
"""Draw each element"""
def assertEqualElement(self, expected, element):
"""
Asserts the top,mid,bot trio
Args:
expected (list[top,mid,bot]): What is expected.
element (DrawElement): The element to check.
"""
try:
encode("\n".join(expected), encoding="cp437")
except UnicodeEncodeError:
self.fail("_text_circuit_drawer() should only use extended ascii (aka code page 437).")
self.assertEqual(expected[0], element.top)
self.assertEqual(expected[1], element.mid)
self.assertEqual(expected[2], element.bot)
def test_measure_to(self):
"""MeasureTo element."""
element = elements.MeasureTo()
# fmt: off
expected = [" ║ ",
"═╩═",
" "]
# fmt: on
self.assertEqualElement(expected, element)
def test_measure_to_label(self):
"""MeasureTo element with cregbundle"""
element = elements.MeasureTo("1")
# fmt: off
expected = [" ║ ",
"═╩═",
" 1 "]
# fmt: on
self.assertEqualElement(expected, element)
def test_measure_from(self):
"""MeasureFrom element."""
element = elements.MeasureFrom()
# fmt: off
expected = ["┌─┐",
"┤M├",
"└╥┘"]
# fmt: on
self.assertEqualElement(expected, element)
def test_text_empty(self):
"""The empty circuit."""
expected = ""
circuit = QuantumCircuit()
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_text_pager(self):
"""The pager breaks the circuit when the drawing does not fit in the console."""
expected = "\n".join(
[
" ┌───┐ »",
"q_0: |0>┤ X ├──■──»",
" └─┬─┘┌─┴─┐»",
"q_1: |0>──■──┤ X ├»",
" └───┘»",
" c: 0 1/══════════»",
" »",
"« ┌─┐┌───┐ »",
"«q_0: ┤M├┤ X ├──■──»",
"« └╥┘└─┬─┘┌─┴─┐»",
"«q_1: ─╫───■──┤ X ├»",
"« ║ └───┘»",
"«c: 1/═╩═══════════»",
"« 0 »",
"« ┌─┐┌───┐ ",
"«q_0: ┤M├┤ X ├──■──",
"« └╥┘└─┬─┘┌─┴─┐",
"«q_1: ─╫───■──┤ X ├",
"« ║ └───┘",
"«c: 1/═╩═══════════",
"« 0 ",
]
)
qr = QuantumRegister(2, "q")
cr = ClassicalRegister(1, "c")
circuit = QuantumCircuit(qr, cr)
circuit.cx(qr[1], qr[0])
circuit.cx(qr[0], qr[1])
circuit.measure(qr[0], cr[0])
circuit.cx(qr[1], qr[0])
circuit.cx(qr[0], qr[1])
circuit.measure(qr[0], cr[0])
circuit.cx(qr[1], qr[0])
circuit.cx(qr[0], qr[1])
self.assertEqual(str(_text_circuit_drawer(circuit, fold=20)), expected)
def test_text_no_pager(self):
"""The pager can be disable."""
qr = QuantumRegister(1, "q")
circuit = QuantumCircuit(qr)
for _ in range(100):
circuit.h(qr[0])
amount_of_lines = str(_text_circuit_drawer(circuit, fold=-1)).count("\n")
self.assertEqual(amount_of_lines, 2)
class TestTextDrawerGatesInCircuit(QiskitTestCase):
"""Gate by gate checks in different settings."""
def test_text_measure_cregbundle(self):
"""The measure operator, using 3-bit-length registers with cregbundle=True."""
expected = "\n".join(
[
" ┌─┐ ",
"q_0: |0>┤M├──────",
" └╥┘┌─┐ ",
"q_1: |0>─╫─┤M├───",
" ║ └╥┘┌─┐",
"q_2: |0>─╫──╫─┤M├",
" ║ ║ └╥┘",
" c: 0 3/═╩══╩══╩═",
" 0 1 2 ",
]
)
qr = QuantumRegister(3, "q")
cr = ClassicalRegister(3, "c")
circuit = QuantumCircuit(qr, cr)
circuit.measure(qr, cr)
self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=True)), expected)
def test_text_measure_cregbundle_2(self):
"""The measure operator, using 2 classical registers with cregbundle=True."""
expected = "\n".join(
[
" ┌─┐ ",
"q_0: |0>┤M├───",
" └╥┘┌─┐",
"q_1: |0>─╫─┤M├",
" ║ └╥┘",
"cA: 0 1/═╩══╬═",
" 0 ║ ",
"cB: 0 1/════╩═",
" 0 ",
]
)
qr = QuantumRegister(2, "q")
cr_a = ClassicalRegister(1, "cA")
cr_b = ClassicalRegister(1, "cB")
circuit = QuantumCircuit(qr, cr_a, cr_b)
circuit.measure(qr[0], cr_a[0])
circuit.measure(qr[1], cr_b[0])
self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=True)), expected)
def test_text_measure_1(self):
"""The measure operator, using 3-bit-length registers."""
expected = "\n".join(
[
" ┌─┐ ",
"q_0: |0>┤M├──────",
" └╥┘┌─┐ ",
"q_1: |0>─╫─┤M├───",
" ║ └╥┘┌─┐",
"q_2: |0>─╫──╫─┤M├",
" ║ ║ └╥┘",
" c_0: 0 ═╩══╬══╬═",
" ║ ║ ",
" c_1: 0 ════╩══╬═",
" ║ ",
" c_2: 0 ═══════╩═",
" ",
]
)
qr = QuantumRegister(3, "q")
cr = ClassicalRegister(3, "c")
circuit = QuantumCircuit(qr, cr)
circuit.measure(qr, cr)
self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=False)), expected)
def test_text_measure_1_reverse_bits(self):
"""The measure operator, using 3-bit-length registers, with reverse_bits"""
expected = "\n".join(
[
" ┌─┐",
"q_2: |0>──────┤M├",
" ┌─┐└╥┘",
"q_1: |0>───┤M├─╫─",
" ┌─┐└╥┘ ║ ",
"q_0: |0>┤M├─╫──╫─",
" └╥┘ ║ ║ ",
" c: 0 3/═╩══╩══╩═",
" 0 1 2 ",
]
)
qr = QuantumRegister(3, "q")
cr = ClassicalRegister(3, "c")
circuit = QuantumCircuit(qr, cr)
circuit.measure(qr, cr)
self.assertEqual(str(_text_circuit_drawer(circuit, reverse_bits=True)), expected)
def test_text_measure_2(self):
"""The measure operator, using some registers."""
expected = "\n".join(
[
" ",
"q1_0: |0>──────",
" ",
"q1_1: |0>──────",
" ┌─┐ ",
"q2_0: |0>┤M├───",
" └╥┘┌─┐",
"q2_1: |0>─╫─┤M├",
" ║ └╥┘",
" c1: 0 2/═╬══╬═",
" ║ ║ ",
" c2: 0 2/═╩══╩═",
" 0 1 ",
]
)
qr1 = QuantumRegister(2, "q1")
cr1 = ClassicalRegister(2, "c1")
qr2 = QuantumRegister(2, "q2")
cr2 = ClassicalRegister(2, "c2")
circuit = QuantumCircuit(qr1, qr2, cr1, cr2)
circuit.measure(qr2, cr2)
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_text_measure_2_reverse_bits(self):
"""The measure operator, using some registers, with reverse_bits"""
expected = "\n".join(
[
" ┌─┐",
"q2_1: |0>───┤M├",
" ┌─┐└╥┘",
"q2_0: |0>┤M├─╫─",
" └╥┘ ║ ",
"q1_1: |0>─╫──╫─",
" ║ ║ ",
"q1_0: |0>─╫──╫─",
" ║ ║ ",
" c2: 0 2/═╩══╩═",
" 0 1 ",
" c1: 0 2/══════",
" ",
]
)
qr1 = QuantumRegister(2, "q1")
cr1 = ClassicalRegister(2, "c1")
qr2 = QuantumRegister(2, "q2")
cr2 = ClassicalRegister(2, "c2")
circuit = QuantumCircuit(qr1, qr2, cr1, cr2)
circuit.measure(qr2, cr2)
self.assertEqual(str(_text_circuit_drawer(circuit, reverse_bits=True)), expected)
def test_wire_order(self):
"""Test the wire_order option"""
expected = "\n".join(
[
" ",
"q_2: |0>────────────",
" ┌───┐ ",
"q_1: |0>┤ X ├───────",
" ├───┤ ┌───┐ ",
"q_3: |0>┤ H ├─┤ X ├─",
" ├───┤ └─╥─┘ ",
"q_0: |0>┤ H ├───╫───",
" └───┘┌──╨──┐",
" c: 0 4/═════╡ 0xa ╞",
" └─────┘",
"ca: 0 2/════════════",
" ",
]
)
qr = QuantumRegister(4, "q")
cr = ClassicalRegister(4, "c")
cr2 = ClassicalRegister(2, "ca")
circuit = QuantumCircuit(qr, cr, cr2)
circuit.h(0)
circuit.h(3)
circuit.x(1)
circuit.x(3).c_if(cr, 10)
self.assertEqual(
str(_text_circuit_drawer(circuit, wire_order=[2, 1, 3, 0, 6, 8, 9, 5, 4, 7])), expected
)
def test_text_swap(self):
"""Swap drawing."""
expected = "\n".join(
[
" ",
"q1_0: |0>─X────",
" │ ",
"q1_1: |0>─┼──X─",
" │ │ ",
"q2_0: |0>─X──┼─",
" │ ",
"q2_1: |0>────X─",
" ",
]
)
qr1 = QuantumRegister(2, "q1")
qr2 = QuantumRegister(2, "q2")
circuit = QuantumCircuit(qr1, qr2)
circuit.swap(qr1, qr2)
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_text_swap_reverse_bits(self):
"""Swap drawing with reverse_bits."""
expected = "\n".join(
[
" ",
"q2_1: |0>────X─",
" │ ",
"q2_0: |0>─X──┼─",
" │ │ ",
"q1_1: |0>─┼──X─",
" │ ",
"q1_0: |0>─X────",
" ",
]
)
qr1 = QuantumRegister(2, "q1")
qr2 = QuantumRegister(2, "q2")
circuit = QuantumCircuit(qr1, qr2)
circuit.swap(qr1, qr2)
self.assertEqual(str(_text_circuit_drawer(circuit, reverse_bits=True)), expected)
def test_text_reverse_bits_read_from_config(self):
"""Swap drawing with reverse_bits set in the configuration file."""
expected_forward = "\n".join(
[
" ",
"q1_0: ─X────",
" │ ",
"q1_1: ─┼──X─",
" │ │ ",
"q2_0: ─X──┼─",
" │ ",
"q2_1: ────X─",
" ",
]
)
expected_reverse = "\n".join(
[
" ",
"q2_1: ────X─",
" │ ",
"q2_0: ─X──┼─",
" │ │ ",
"q1_1: ─┼──X─",
" │ ",
"q1_0: ─X────",
" ",
]
)
qr1 = QuantumRegister(2, "q1")
qr2 = QuantumRegister(2, "q2")
circuit = QuantumCircuit(qr1, qr2)
circuit.swap(qr1, qr2)
self.assertEqual(str(circuit_drawer(circuit, output="text")), expected_forward)
config_content = """
[default]
circuit_reverse_bits = true
"""
with tempfile.TemporaryDirectory() as dir_path:
file_path = pathlib.Path(dir_path) / "qiskit.conf"
with open(file_path, "w") as fptr:
fptr.write(config_content)
with unittest.mock.patch.dict(os.environ, {"QISKIT_SETTINGS": str(file_path)}):
test_reverse = str(circuit_drawer(circuit, output="text"))
self.assertEqual(test_reverse, expected_reverse)
def test_text_cswap(self):
"""CSwap drawing."""
expected = "\n".join(
[
" ",
"q_0: |0>─■──X──X─",
" │ │ │ ",
"q_1: |0>─X──■──X─",
" │ │ │ ",
"q_2: |0>─X──X──■─",
" ",
]
)
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
circuit.cswap(qr[0], qr[1], qr[2])
circuit.cswap(qr[1], qr[0], qr[2])
circuit.cswap(qr[2], qr[1], qr[0])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_text_cswap_reverse_bits(self):
"""CSwap drawing with reverse_bits."""
expected = "\n".join(
[
" ",
"q_2: |0>─X──X──■─",
" │ │ │ ",
"q_1: |0>─X──■──X─",
" │ │ │ ",
"q_0: |0>─■──X──X─",
" ",
]
)
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
circuit.cswap(qr[0], qr[1], qr[2])
circuit.cswap(qr[1], qr[0], qr[2])
circuit.cswap(qr[2], qr[1], qr[0])
self.assertEqual(str(_text_circuit_drawer(circuit, reverse_bits=True)), expected)
def test_text_cu3(self):
"""cu3 drawing."""
expected = "\n".join(
[
" ┌─────────────────┐",
"q_0: |0>─────────■─────────┤ U3(π/2,π/2,π/2) ├",
" ┌────────┴────────┐└────────┬────────┘",
"q_1: |0>┤ U3(π/2,π/2,π/2) ├─────────┼─────────",
" └─────────────────┘ │ ",
"q_2: |0>────────────────────────────■─────────",
" ",
]
)
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
circuit.append(CU3Gate(pi / 2, pi / 2, pi / 2), [qr[0], qr[1]])
circuit.append(CU3Gate(pi / 2, pi / 2, pi / 2), [qr[2], qr[0]])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_text_cu3_reverse_bits(self):
"""cu3 drawing with reverse_bits"""
expected = "\n".join(
[
" ",
"q_2: |0>────────────────────────────■─────────",
" ┌─────────────────┐ │ ",
"q_1: |0>┤ U3(π/2,π/2,π/2) ├─────────┼─────────",
" └────────┬────────┘┌────────┴────────┐",
"q_0: |0>─────────■─────────┤ U3(π/2,π/2,π/2) ├",
" └─────────────────┘",
]
)
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
circuit.append(CU3Gate(pi / 2, pi / 2, pi / 2), [qr[0], qr[1]])
circuit.append(CU3Gate(pi / 2, pi / 2, pi / 2), [qr[2], qr[0]])
self.assertEqual(str(_text_circuit_drawer(circuit, reverse_bits=True)), expected)
def test_text_crz(self):
"""crz drawing."""
expected = "\n".join(
[
" ┌─────────┐",
"q_0: |0>─────■─────┤ Rz(π/2) ├",
" ┌────┴────┐└────┬────┘",
"q_1: |0>┤ Rz(π/2) ├─────┼─────",
" └─────────┘ │ ",
"q_2: |0>────────────────■─────",
" ",
]
)
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
circuit.crz(pi / 2, qr[0], qr[1])
circuit.crz(pi / 2, qr[2], qr[0])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_text_cry(self):
"""cry drawing."""
expected = "\n".join(
[
" ┌─────────┐",
"q_0: |0>─────■─────┤ Ry(π/2) ├",
" ┌────┴────┐└────┬────┘",
"q_1: |0>┤ Ry(π/2) ├─────┼─────",
" └─────────┘ │ ",
"q_2: |0>────────────────■─────",
" ",
]
)
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
circuit.cry(pi / 2, qr[0], qr[1])
circuit.cry(pi / 2, qr[2], qr[0])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_text_crx(self):
"""crx drawing."""
expected = "\n".join(
[
" ┌─────────┐",
"q_0: |0>─────■─────┤ Rx(π/2) ├",
" ┌────┴────┐└────┬────┘",
"q_1: |0>┤ Rx(π/2) ├─────┼─────",
" └─────────┘ │ ",
"q_2: |0>────────────────■─────",
" ",
]
)
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
circuit.crx(pi / 2, qr[0], qr[1])
circuit.crx(pi / 2, qr[2], qr[0])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_text_cx(self):
"""cx drawing."""
expected = "\n".join(
[
" ┌───┐",
"q_0: |0>──■──┤ X ├",
" ┌─┴─┐└─┬─┘",
"q_1: |0>┤ X ├──┼──",
" └───┘ │ ",
"q_2: |0>───────■──",
" ",
]
)
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[1])
circuit.cx(qr[2], qr[0])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_text_cy(self):
"""cy drawing."""
expected = "\n".join(
[
" ┌───┐",
"q_0: |0>──■──┤ Y ├",
" ┌─┴─┐└─┬─┘",
"q_1: |0>┤ Y ├──┼──",
" └───┘ │ ",
"q_2: |0>───────■──",
" ",
]
)
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
circuit.cy(qr[0], qr[1])
circuit.cy(qr[2], qr[0])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_text_cz(self):
"""cz drawing."""
expected = "\n".join(
[
" ",
"q_0: |0>─■──■─",
" │ │ ",
"q_1: |0>─■──┼─",
" │ ",
"q_2: |0>────■─",
" ",
]
)
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
circuit.cz(qr[0], qr[1])
circuit.cz(qr[2], qr[0])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_text_ch(self):
"""ch drawing."""
expected = "\n".join(
[
" ┌───┐",
"q_0: |0>──■──┤ H ├",
" ┌─┴─┐└─┬─┘",
"q_1: |0>┤ H ├──┼──",
" └───┘ │ ",
"q_2: |0>───────■──",
" ",
]
)
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
circuit.ch(qr[0], qr[1])
circuit.ch(qr[2], qr[0])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_text_rzz(self):
"""rzz drawing. See #1957"""
expected = "\n".join(
[
" ",
"q_0: |0>─■────────────────",
" │ZZ(0) ",
"q_1: |0>─■───────■────────",
" │ZZ(π/2) ",
"q_2: |0>─────────■────────",
" ",
]
)
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
circuit.rzz(0, qr[0], qr[1])
circuit.rzz(pi / 2, qr[2], qr[1])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_text_cu1(self):
"""cu1 drawing."""
expected = "\n".join(
[
" ",
"q_0: |0>─■─────────■────────",
" │U1(π/2) │ ",
"q_1: |0>─■─────────┼────────",
" │U1(π/2) ",
"q_2: |0>───────────■────────",
" ",
]
)
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
circuit.append(CU1Gate(pi / 2), [qr[0], qr[1]])
circuit.append(CU1Gate(pi / 2), [qr[2], qr[0]])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_text_cp(self):
"""cp drawing."""
expected = "\n".join(
[
" ",
"q_0: |0>─■────────■───────",
" │P(π/2) │ ",
"q_1: |0>─■────────┼───────",
" │P(π/2) ",
"q_2: |0>──────────■───────",
" ",
]
)
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
circuit.append(CPhaseGate(pi / 2), [qr[0], qr[1]])
circuit.append(CPhaseGate(pi / 2), [qr[2], qr[0]])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_text_cu1_condition(self):
"""Test cu1 with condition"""
expected = "\n".join(
[
" ",
"q_0: ────────■────────",
" │U1(π/2) ",
"q_1: ────────■────────",
" ║ ",
"q_2: ────────╫────────",
" ┌────╨────┐ ",
"c: 3/═══╡ c_1=0x1 ╞═══",
" └─────────┘ ",
]
)
qr = QuantumRegister(3, "q")
cr = ClassicalRegister(3, "c")
circuit = QuantumCircuit(qr, cr)
circuit.append(CU1Gate(pi / 2), [qr[0], qr[1]]).c_if(cr[1], 1)
self.assertEqual(str(_text_circuit_drawer(circuit, initial_state=False)), expected)
def test_text_rzz_condition(self):
"""Test rzz with condition"""
expected = "\n".join(
[
" ",
"q_0: ────────■────────",
" │ZZ(π/2) ",
"q_1: ────────■────────",
" ║ ",
"q_2: ────────╫────────",
" ┌────╨────┐ ",
"c: 3/═══╡ c_1=0x1 ╞═══",
" └─────────┘ ",
]
)
qr = QuantumRegister(3, "q")
cr = ClassicalRegister(3, "c")
circuit = QuantumCircuit(qr, cr)
circuit.append(RZZGate(pi / 2), [qr[0], qr[1]]).c_if(cr[1], 1)
self.assertEqual(str(_text_circuit_drawer(circuit, initial_state=False)), expected)
def test_text_cp_condition(self):
"""Test cp with condition"""
expected = "\n".join(
[
" ",
"q_0: ───────■───────",
" │P(π/2) ",
"q_1: ───────■───────",
" ║ ",
"q_2: ───────╫───────",
" ┌────╨────┐ ",
"c: 3/══╡ c_1=0x1 ╞══",
" └─────────┘ ",
]
)
qr = QuantumRegister(3, "q")
cr = ClassicalRegister(3, "c")
circuit = QuantumCircuit(qr, cr)
circuit.append(CPhaseGate(pi / 2), [qr[0], qr[1]]).c_if(cr[1], 1)
self.assertEqual(str(_text_circuit_drawer(circuit, initial_state=False)), expected)
def test_text_cu1_reverse_bits(self):
"""cu1 drawing with reverse_bits"""
expected = "\n".join(
[
" ",
"q_2: |0>───────────■────────",
" │ ",
"q_1: |0>─■─────────┼────────",
" │U1(π/2) │U1(π/2) ",
"q_0: |0>─■─────────■────────",
" ",
]
)
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
circuit.append(CU1Gate(pi / 2), [qr[0], qr[1]])
circuit.append(CU1Gate(pi / 2), [qr[2], qr[0]])
self.assertEqual(str(_text_circuit_drawer(circuit, reverse_bits=True)), expected)
def test_text_ccx(self):
"""cx drawing."""
expected = "\n".join(
[
" ┌───┐",
"q_0: |0>──■────■──┤ X ├",
" │ ┌─┴─┐└─┬─┘",
"q_1: |0>──■──┤ X ├──■──",
" ┌─┴─┐└─┬─┘ │ ",
"q_2: |0>┤ X ├──■────■──",
" └───┘ ",
]
)
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
circuit.ccx(qr[0], qr[1], qr[2])
circuit.ccx(qr[2], qr[0], qr[1])
circuit.ccx(qr[2], qr[1], qr[0])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_text_reset(self):
"""Reset drawing."""
expected = "\n".join(
[
" ",
"q1_0: |0>─|0>─",
" ",
"q1_1: |0>─|0>─",
" ",
"q2_0: |0>─────",
" ",
"q2_1: |0>─|0>─",
" ",
]
)
qr1 = QuantumRegister(2, "q1")
qr2 = QuantumRegister(2, "q2")
circuit = QuantumCircuit(qr1, qr2)
circuit.reset(qr1)
circuit.reset(qr2[1])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_text_single_gate(self):
"""Single Qbit gate drawing."""
expected = "\n".join(
[
" ┌───┐",
"q1_0: |0>┤ H ├",
" ├───┤",
"q1_1: |0>┤ H ├",
" └───┘",
"q2_0: |0>─────",
" ┌───┐",
"q2_1: |0>┤ H ├",
" └───┘",
]
)
qr1 = QuantumRegister(2, "q1")
qr2 = QuantumRegister(2, "q2")
circuit = QuantumCircuit(qr1, qr2)
circuit.h(qr1)
circuit.h(qr2[1])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_text_id(self):
"""Id drawing."""
expected = "\n".join(
[
" ┌───┐",
"q1_0: |0>┤ I ├",
" ├───┤",
"q1_1: |0>┤ I ├",
" └───┘",
"q2_0: |0>─────",
" ┌───┐",
"q2_1: |0>┤ I ├",
" └───┘",
]
)
qr1 = QuantumRegister(2, "q1")
qr2 = QuantumRegister(2, "q2")
circuit = QuantumCircuit(qr1, qr2)
circuit.id(qr1)
circuit.id(qr2[1])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_text_barrier(self):
"""Barrier drawing."""
expected = "\n".join(
[
" ░ ",
"q1_0: |0>─░─",
" ░ ",
"q1_1: |0>─░─",
" ░ ",
"q2_0: |0>───",
" ░ ",
"q2_1: |0>─░─",
" ░ ",
]
)
qr1 = QuantumRegister(2, "q1")
qr2 = QuantumRegister(2, "q2")
circuit = QuantumCircuit(qr1, qr2)
circuit.barrier(qr1)
circuit.barrier(qr2[1])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_text_no_barriers(self):
"""Drawing without plotbarriers."""
expected = "\n".join(
[
" ┌───┐ ",
"q1_0: |0>┤ H ├─────",
" ├───┤ ",
"q1_1: |0>┤ H ├─────",
" ├───┤ ",
"q2_0: |0>┤ H ├─────",
" └───┘┌───┐",
"q2_1: |0>─────┤ H ├",
" └───┘",
]
)
qr1 = QuantumRegister(2, "q1")
qr2 = QuantumRegister(2, "q2")
circuit = QuantumCircuit(qr1, qr2)
circuit.h(qr1)
circuit.barrier(qr1)
circuit.barrier(qr2[1])
circuit.h(qr2)
self.assertEqual(str(_text_circuit_drawer(circuit, plot_barriers=False)), expected)
def test_text_measure_html(self):
"""The measure operator. HTML representation."""
expected = "\n".join(
[
'<pre style="word-wrap: normal;'
"white-space: pre;"
"background: #fff0;"
"line-height: 1.1;"
'font-family: "Courier New",Courier,monospace">'
" ┌─┐",
" q: |0>┤M├",
" └╥┘",
"c: 0 1/═╩═",
" 0 </pre>",
]
)
qr = QuantumRegister(1, "q")
cr = ClassicalRegister(1, "c")
circuit = QuantumCircuit(qr, cr)
circuit.measure(qr, cr)
self.assertEqual(_text_circuit_drawer(circuit)._repr_html_(), expected)
def test_text_repr(self):
"""The measure operator. repr."""
expected = "\n".join(
[
" ┌─┐",
" q: |0>┤M├",
" └╥┘",
"c: 0 1/═╩═",
" 0 ",
]
)
qr = QuantumRegister(1, "q")
cr = ClassicalRegister(1, "c")
circuit = QuantumCircuit(qr, cr)
circuit.measure(qr, cr)
self.assertEqual(_text_circuit_drawer(circuit).__repr__(), expected)
def test_text_justify_left(self):
"""Drawing with left justify"""
expected = "\n".join(
[
" ┌───┐ ",
"q1_0: |0>┤ X ├───",
" ├───┤┌─┐",
"q1_1: |0>┤ H ├┤M├",
" └───┘└╥┘",
" c1: 0 2/══════╩═",
" 1 ",
]
)
qr1 = QuantumRegister(2, "q1")
cr1 = ClassicalRegister(2, "c1")
circuit = QuantumCircuit(qr1, cr1)
circuit.x(qr1[0])
circuit.h(qr1[1])
circuit.measure(qr1[1], cr1[1])
self.assertEqual(str(_text_circuit_drawer(circuit, justify="left")), expected)
def test_text_justify_right(self):
"""Drawing with right justify"""
expected = "\n".join(
[
" ┌───┐",
"q1_0: |0>─────┤ X ├",
" ┌───┐└┬─┬┘",
"q1_1: |0>┤ H ├─┤M├─",
" └───┘ └╥┘ ",
" c1: 0 2/═══════╩══",
" 1 ",
]
)
qr1 = QuantumRegister(2, "q1")
cr1 = ClassicalRegister(2, "c1")
circuit = QuantumCircuit(qr1, cr1)
circuit.x(qr1[0])
circuit.h(qr1[1])
circuit.measure(qr1[1], cr1[1])
self.assertEqual(str(_text_circuit_drawer(circuit, justify="right")), expected)
def test_text_justify_none(self):
"""Drawing with none justify"""
expected = "\n".join(
[
" ┌───┐ ",
"q1_0: |0>┤ X ├────────",
" └───┘┌───┐┌─┐",
"q1_1: |0>─────┤ H ├┤M├",
" └───┘└╥┘",
" c1: 0 2/═══════════╩═",
" 1 ",
]
)
qr1 = QuantumRegister(2, "q1")
cr1 = ClassicalRegister(2, "c1")
circuit = QuantumCircuit(qr1, cr1)
circuit.x(qr1[0])
circuit.h(qr1[1])
circuit.measure(qr1[1], cr1[1])
self.assertEqual(str(_text_circuit_drawer(circuit, justify="none")), expected)
def test_text_justify_left_barrier(self):
"""Left justify respects barriers"""
expected = "\n".join(
[
" ┌───┐ ░ ",
"q1_0: |0>┤ H ├─░──────",
" └───┘ ░ ┌───┐",
"q1_1: |0>──────░─┤ H ├",
" ░ └───┘",
]
)
qr1 = QuantumRegister(2, "q1")
circuit = QuantumCircuit(qr1)
circuit.h(qr1[0])
circuit.barrier(qr1)
circuit.h(qr1[1])
self.assertEqual(str(_text_circuit_drawer(circuit, justify="left")), expected)
def test_text_justify_right_barrier(self):
"""Right justify respects barriers"""
expected = "\n".join(
[
" ┌───┐ ░ ",
"q1_0: |0>┤ H ├─░──────",
" └───┘ ░ ┌───┐",
"q1_1: |0>──────░─┤ H ├",
" ░ └───┘",
]
)
qr1 = QuantumRegister(2, "q1")
circuit = QuantumCircuit(qr1)
circuit.h(qr1[0])
circuit.barrier(qr1)
circuit.h(qr1[1])
self.assertEqual(str(_text_circuit_drawer(circuit, justify="right")), expected)
def test_text_barrier_label(self):
"""Show barrier label"""
expected = "\n".join(
[
" ┌───┐ ░ ┌───┐ End Y/X ",
"q_0: |0>┤ X ├─░─┤ Y ├────░────",
" ├───┤ ░ ├───┤ ░ ",
"q_1: |0>┤ Y ├─░─┤ X ├────░────",
" └───┘ ░ └───┘ ░ ",
]
)
qr = QuantumRegister(2, "q")
circuit = QuantumCircuit(qr)
circuit.x(0)
circuit.y(1)
circuit.barrier()
circuit.y(0)
circuit.x(1)
circuit.barrier(label="End Y/X")
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_text_overlap_cx(self):
"""Overlapping CX gates are drawn not overlapping"""
expected = "\n".join(
[
" ",
"q1_0: |0>──■───────",
" │ ",
"q1_1: |0>──┼────■──",
" │ ┌─┴─┐",
"q1_2: |0>──┼──┤ X ├",
" ┌─┴─┐└───┘",
"q1_3: |0>┤ X ├─────",
" └───┘ ",
]
)
qr1 = QuantumRegister(4, "q1")
circuit = QuantumCircuit(qr1)
circuit.cx(qr1[0], qr1[3])
circuit.cx(qr1[1], qr1[2])
self.assertEqual(str(_text_circuit_drawer(circuit, justify="left")), expected)
def test_text_overlap_measure(self):
"""Measure is drawn not overlapping"""
expected = "\n".join(
[
" ┌─┐ ",
"q1_0: |0>┤M├─────",
" └╥┘┌───┐",
"q1_1: |0>─╫─┤ X ├",
" ║ └───┘",
" c1: 0 2/═╩══════",
" 0 ",
]
)
qr1 = QuantumRegister(2, "q1")
cr1 = ClassicalRegister(2, "c1")
circuit = QuantumCircuit(qr1, cr1)
circuit.measure(qr1[0], cr1[0])
circuit.x(qr1[1])
self.assertEqual(str(_text_circuit_drawer(circuit, justify="left")), expected)
def test_text_overlap_swap(self):
"""Swap is drawn in 2 separate columns"""
expected = "\n".join(
[
" ",
"q1_0: |0>─X────",
" │ ",
"q1_1: |0>─┼──X─",
" │ │ ",
"q2_0: |0>─X──┼─",
" │ ",
"q2_1: |0>────X─",
" ",
]
)
qr1 = QuantumRegister(2, "q1")
qr2 = QuantumRegister(2, "q2")
circuit = QuantumCircuit(qr1, qr2)
circuit.swap(qr1, qr2)
self.assertEqual(str(_text_circuit_drawer(circuit, justify="left")), expected)
def test_text_justify_right_measure_resize(self):
"""Measure gate can resize if necessary"""
expected = "\n".join(
[
" ┌───┐",
"q1_0: |0>┤ X ├",
" └┬─┬┘",
"q1_1: |0>─┤M├─",
" └╥┘ ",
" c1: 0 2/══╩══",
" 1 ",
]
)
qr1 = QuantumRegister(2, "q1")
cr1 = ClassicalRegister(2, "c1")
circuit = QuantumCircuit(qr1, cr1)
circuit.x(qr1[0])
circuit.measure(qr1[1], cr1[1])
self.assertEqual(str(_text_circuit_drawer(circuit, justify="right")), expected)
def test_text_box_length(self):
"""The length of boxes is independent of other boxes in the layer
https://github.com/Qiskit/qiskit-terra/issues/1882"""
expected = "\n".join(
[
" ┌───┐ ┌───┐",
"q1_0: |0>────┤ H ├────┤ H ├",
" └───┘ └───┘",
"q1_1: |0>──────────────────",
" ┌───────────┐ ",
"q1_2: |0>┤ Rz(1e-07) ├─────",
" └───────────┘ ",
]
)
qr = QuantumRegister(3, "q1")
circuit = QuantumCircuit(qr)
circuit.h(qr[0])
circuit.h(qr[0])
circuit.rz(0.0000001, qr[2])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_text_spacing_2378(self):
"""Small gates in the same layer as long gates.
See https://github.com/Qiskit/qiskit-terra/issues/2378"""
expected = "\n".join(
[
" ",
"q_0: |0>──────X──────",
" │ ",
"q_1: |0>──────X──────",
" ┌───────────┐",
"q_2: |0>┤ Rz(11111) ├",
" └───────────┘",
]
)
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
circuit.swap(qr[0], qr[1])
circuit.rz(11111, qr[2])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
@unittest.skipUnless(HAS_TWEEDLEDUM, "Tweedledum is required for these tests.")
def test_text_synth_no_registerless(self):
"""Test synthesis's label when registerless=False.
See https://github.com/Qiskit/qiskit-terra/issues/9363"""
expected = "\n".join(
[
" ",
" a: |0>──■──",
" │ ",
" b: |0>──■──",
" │ ",
" c: |0>──o──",
" ┌─┴─┐",
"return: |0>┤ X ├",
" └───┘",
]
)
@classical_function
def grover_oracle(a: Int1, b: Int1, c: Int1) -> Int1:
return a and b and not c
circuit = grover_oracle.synth(registerless=False)
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
class TestTextDrawerLabels(QiskitTestCase):
"""Gates with labels."""
def test_label(self):
"""Test a gate with a label."""
# fmt: off
expected = "\n".join([" ┌───────────┐",
"q: |0>┤ an H gate ├",
" └───────────┘"])
# fmt: on
circuit = QuantumCircuit(1)
circuit.append(HGate(label="an H gate"), [0])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_controlled_gate_with_label(self):
"""Test a controlled gate-with-a-label."""
expected = "\n".join(
[
" ",
"q_0: |0>──────■──────",
" ┌─────┴─────┐",
"q_1: |0>┤ an H gate ├",
" └───────────┘",
]
)
circuit = QuantumCircuit(2)
circuit.append(HGate(label="an H gate").control(1), [0, 1])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_label_on_controlled_gate(self):
"""Test a controlled gate with a label (as a as a whole)."""
expected = "\n".join(
[
" a controlled H gate ",
"q_0: |0>──────────■──────────",
" ┌─┴─┐ ",
"q_1: |0>────────┤ H ├────────",
" └───┘ ",
]
)
circuit = QuantumCircuit(2)
circuit.append(HGate().control(1, label="a controlled H gate"), [0, 1])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_rzz_on_wide_layer(self):
"""Test a labeled gate (RZZ) in a wide layer.
See https://github.com/Qiskit/qiskit-terra/issues/4838"""
expected = "\n".join(
[
" ",
"q_0: |0>────────────────■──────────────────────",
" │ZZ(π/2) ",
"q_1: |0>────────────────■──────────────────────",
" ┌─────────────────────────────────────┐",
"q_2: |0>┤ This is a really long long long box ├",
" └─────────────────────────────────────┘",
]
)
circuit = QuantumCircuit(3)
circuit.rzz(pi / 2, 0, 1)
circuit.x(2, label="This is a really long long long box")
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_cu1_on_wide_layer(self):
"""Test a labeled gate (CU1) in a wide layer.
See https://github.com/Qiskit/qiskit-terra/issues/4838"""
expected = "\n".join(
[
" ",
"q_0: |0>────────────────■──────────────────────",
" │U1(π/2) ",
"q_1: |0>────────────────■──────────────────────",
" ┌─────────────────────────────────────┐",
"q_2: |0>┤ This is a really long long long box ├",
" └─────────────────────────────────────┘",
]
)
circuit = QuantumCircuit(3)
circuit.append(CU1Gate(pi / 2), [0, 1])
circuit.x(2, label="This is a really long long long box")
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
class TestTextDrawerMultiQGates(QiskitTestCase):
"""Gates implying multiple qubits."""
def test_2Qgate(self):
"""2Q no params."""
expected = "\n".join(
[
" ┌───────┐",
"q_1: |0>┤1 ├",
" │ twoQ │",
"q_0: |0>┤0 ├",
" └───────┘",
]
)
qr = QuantumRegister(2, "q")
circuit = QuantumCircuit(qr)
my_gate2 = Gate(name="twoQ", num_qubits=2, params=[], label="twoQ")
circuit.append(my_gate2, [qr[0], qr[1]])
self.assertEqual(str(_text_circuit_drawer(circuit, reverse_bits=True)), expected)
def test_2Qgate_cross_wires(self):
"""2Q no params, with cross wires"""
expected = "\n".join(
[
" ┌───────┐",
"q_1: |0>┤0 ├",
" │ twoQ │",
"q_0: |0>┤1 ├",
" └───────┘",
]
)
qr = QuantumRegister(2, "q")
circuit = QuantumCircuit(qr)
my_gate2 = Gate(name="twoQ", num_qubits=2, params=[], label="twoQ")
circuit.append(my_gate2, [qr[1], qr[0]])
self.assertEqual(str(_text_circuit_drawer(circuit, reverse_bits=True)), expected)
def test_3Qgate_cross_wires(self):
"""3Q no params, with cross wires"""
expected = "\n".join(
[
" ┌─────────┐",
"q_2: |0>┤1 ├",
" │ │",
"q_1: |0>┤0 threeQ ├",
" │ │",
"q_0: |0>┤2 ├",
" └─────────┘",
]
)
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
my_gate3 = Gate(name="threeQ", num_qubits=3, params=[], label="threeQ")
circuit.append(my_gate3, [qr[1], qr[2], qr[0]])
self.assertEqual(str(_text_circuit_drawer(circuit, reverse_bits=True)), expected)
def test_2Qgate_nottogether(self):
"""2Q that are not together"""
expected = "\n".join(
[
" ┌───────┐",
"q_2: |0>┤1 ├",
" │ │",
"q_1: |0>┤ twoQ ├",
" │ │",
"q_0: |0>┤0 ├",
" └───────┘",
]
)
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
my_gate2 = Gate(name="twoQ", num_qubits=2, params=[], label="twoQ")
circuit.append(my_gate2, [qr[0], qr[2]])
self.assertEqual(str(_text_circuit_drawer(circuit, reverse_bits=True)), expected)
def test_2Qgate_nottogether_across_4(self):
"""2Q that are 2 bits apart"""
expected = "\n".join(
[
" ┌───────┐",
"q_3: |0>┤1 ├",
" │ │",
"q_2: |0>┤ ├",
" │ twoQ │",
"q_1: |0>┤ ├",
" │ │",
"q_0: |0>┤0 ├",
" └───────┘",
]
)
qr = QuantumRegister(4, "q")
circuit = QuantumCircuit(qr)
my_gate2 = Gate(name="twoQ", num_qubits=2, params=[], label="twoQ")
circuit.append(my_gate2, [qr[0], qr[3]])
self.assertEqual(str(_text_circuit_drawer(circuit, reverse_bits=True)), expected)
def test_unitary_nottogether_across_4(self):
"""unitary that are 2 bits apart"""
expected = "\n".join(
[
" ┌──────────┐",
"q_0: |0>┤0 ├",
" │ │",
"q_1: |0>┤ ├",
" │ Unitary │",
"q_2: |0>┤ ├",
" │ │",
"q_3: |0>┤1 ├",
" └──────────┘",
]
)
qr = QuantumRegister(4, "q")
qc = QuantumCircuit(qr)
qc.append(random_unitary(4, seed=42), [qr[0], qr[3]])
self.assertEqual(str(_text_circuit_drawer(qc)), expected)
def test_kraus(self):
"""Test Kraus.
See https://github.com/Qiskit/qiskit-terra/pull/2238#issuecomment-487630014"""
# fmt: off
expected = "\n".join([" ┌───────┐",
"q: |0>┤ kraus ├",
" └───────┘"])
# fmt: on
error = SuperOp(0.75 * numpy.eye(4) + 0.25 * numpy.diag([1, -1, -1, 1]))
qr = QuantumRegister(1, name="q")
qc = QuantumCircuit(qr)
qc.append(error, [qr[0]])
self.assertEqual(str(_text_circuit_drawer(qc)), expected)
def test_multiplexer(self):
"""Test Multiplexer.
See https://github.com/Qiskit/qiskit-terra/pull/2238#issuecomment-487630014"""
expected = "\n".join(
[
" ┌──────────────┐",
"q_0: |0>┤0 ├",
" │ Multiplexer │",
"q_1: |0>┤1 ├",
" └──────────────┘",
]
)
cx_multiplexer = UCGate([numpy.eye(2), numpy.array([[0, 1], [1, 0]])])
qr = QuantumRegister(2, name="q")
qc = QuantumCircuit(qr)
qc.append(cx_multiplexer, [qr[0], qr[1]])
self.assertEqual(str(_text_circuit_drawer(qc)), expected)
def test_label_over_name_2286(self):
"""If there is a label, it should be used instead of the name
See https://github.com/Qiskit/qiskit-terra/issues/2286"""
expected = "\n".join(
[
" ┌───┐┌───────┐┌────────┐",
"q_0: |0>┤ X ├┤ alt-X ├┤0 ├",
" └───┘└───────┘│ iswap │",
"q_1: |0>──────────────┤1 ├",
" └────────┘",
]
)
qr = QuantumRegister(2, "q")
circ = QuantumCircuit(qr)
circ.append(XGate(), [qr[0]])
circ.append(XGate(label="alt-X"), [qr[0]])
circ.append(UnitaryGate(numpy.eye(4), label="iswap"), [qr[0], qr[1]])
self.assertEqual(str(_text_circuit_drawer(circ)), expected)
def test_label_turns_to_box_2286(self):
"""If there is a label, non-boxes turn into boxes
See https://github.com/Qiskit/qiskit-terra/issues/2286"""
expected = "\n".join(
[
" cz label ",
"q_0: |0>─■─────■─────",
" │ │ ",
"q_1: |0>─■─────■─────",
" ",
]
)
qr = QuantumRegister(2, "q")
circ = QuantumCircuit(qr)
circ.append(CZGate(), [qr[0], qr[1]])
circ.append(CZGate(label="cz label"), [qr[0], qr[1]])
self.assertEqual(str(_text_circuit_drawer(circ)), expected)
def test_control_gate_with_base_label_4361(self):
"""Control gate has a label and a base gate with a label
See https://github.com/Qiskit/qiskit-terra/issues/4361"""
expected = "\n".join(
[
" ┌──────┐ my ch ┌──────┐",
"q_0: |0>┤ my h ├───■────┤ my h ├",
" └──────┘┌──┴───┐└──┬───┘",
"q_1: |0>────────┤ my h ├───■────",
" └──────┘ my ch ",
]
)
qr = QuantumRegister(2, "q")
circ = QuantumCircuit(qr)
hgate = HGate(label="my h")
controlh = hgate.control(label="my ch")
circ.append(hgate, [0])
circ.append(controlh, [0, 1])
circ.append(controlh, [1, 0])
self.assertEqual(str(_text_circuit_drawer(circ)), expected)
def test_control_gate_label_with_cond_1_low(self):
"""Control gate has a label and a conditional (compression=low)
See https://github.com/Qiskit/qiskit-terra/issues/4361"""
expected = "\n".join(
[
" my ch ",
"q_0: |0>───■────",
" │ ",
" ┌──┴───┐",
"q_1: |0>┤ my h ├",
" └──╥───┘",
" ┌──╨──┐ ",
" c: 0 1/╡ 0x1 ╞═",
" └─────┘ ",
]
)
qr = QuantumRegister(2, "q")
cr = ClassicalRegister(1, "c")
circ = QuantumCircuit(qr, cr)
hgate = HGate(label="my h")
controlh = hgate.control(label="my ch").c_if(cr, 1)
circ.append(controlh, [0, 1])
self.assertEqual(str(_text_circuit_drawer(circ, vertical_compression="low")), expected)
def test_control_gate_label_with_cond_1_low_cregbundle(self):
"""Control gate has a label and a conditional (compression=low) with cregbundle
See https://github.com/Qiskit/qiskit-terra/issues/4361"""
expected = "\n".join(
[
" my ch ",
"q_0: |0>───■────",
" │ ",
" ┌──┴───┐",
"q_1: |0>┤ my h ├",
" └──╥───┘",
" ┌──╨──┐ ",
" c: 0 1/╡ 0x1 ╞═",
" └─────┘ ",
]
)
qr = QuantumRegister(2, "q")
cr = ClassicalRegister(1, "c")
circ = QuantumCircuit(qr, cr)
hgate = HGate(label="my h")
controlh = hgate.control(label="my ch").c_if(cr, 1)
circ.append(controlh, [0, 1])
self.assertEqual(
str(_text_circuit_drawer(circ, vertical_compression="low", cregbundle=True)), expected
)
def test_control_gate_label_with_cond_1_med(self):
"""Control gate has a label and a conditional (compression=med)
See https://github.com/Qiskit/qiskit-terra/issues/4361"""
expected = "\n".join(
[
" my ch ",
"q_0: |0>───■────",
" ┌──┴───┐",
"q_1: |0>┤ my h ├",
" └──╥───┘",
" c: 0 ═══■════",
" 0x1 ",
]
)
qr = QuantumRegister(2, "q")
cr = ClassicalRegister(1, "c")
circ = QuantumCircuit(qr, cr)
hgate = HGate(label="my h")
controlh = hgate.control(label="my ch").c_if(cr, 1)
circ.append(controlh, [0, 1])
self.assertEqual(
str(_text_circuit_drawer(circ, cregbundle=False, vertical_compression="medium")),
expected,
)
def test_control_gate_label_with_cond_1_med_cregbundle(self):
"""Control gate has a label and a conditional (compression=med) with cregbundle
See https://github.com/Qiskit/qiskit-terra/issues/4361"""
expected = "\n".join(
[
" my ch ",
"q_0: |0>───■────",
" ┌──┴───┐",
"q_1: |0>┤ my h ├",
" └──╥───┘",
" ┌──╨──┐ ",
" c: 0 1/╡ 0x1 ╞═",
" └─────┘ ",
]
)
qr = QuantumRegister(2, "q")
cr = ClassicalRegister(1, "c")
circ = QuantumCircuit(qr, cr)
hgate = HGate(label="my h")
controlh = hgate.control(label="my ch").c_if(cr, 1)
circ.append(controlh, [0, 1])
self.assertEqual(
str(_text_circuit_drawer(circ, vertical_compression="medium", cregbundle=True)),
expected,
)
def test_control_gate_label_with_cond_1_high(self):
"""Control gate has a label and a conditional (compression=high)
See https://github.com/Qiskit/qiskit-terra/issues/4361"""
expected = "\n".join(
[
" my ch ",
"q_0: |0>───■────",
" ┌──┴───┐",
"q_1: |0>┤ my h ├",
" └──╥───┘",
" c: 0 ═══■════",
" 0x1 ",
]
)
qr = QuantumRegister(2, "q")
cr = ClassicalRegister(1, "c")
circ = QuantumCircuit(qr, cr)
hgate = HGate(label="my h")
controlh = hgate.control(label="my ch").c_if(cr, 1)
circ.append(controlh, [0, 1])
self.assertEqual(
str(_text_circuit_drawer(circ, cregbundle=False, vertical_compression="high")), expected
)
def test_control_gate_label_with_cond_1_high_cregbundle(self):
"""Control gate has a label and a conditional (compression=high) with cregbundle
See https://github.com/Qiskit/qiskit-terra/issues/4361"""
expected = "\n".join(
[
" my ch ",
"q_0: |0>───■────",
" ┌──┴───┐",
"q_1: |0>┤ my h ├",
" ├──╨──┬┘",
" c: 0 1/╡ 0x1 ╞═",
" └─────┘ ",
]
)
qr = QuantumRegister(2, "q")
cr = ClassicalRegister(1, "c")
circ = QuantumCircuit(qr, cr)
hgate = HGate(label="my h")
controlh = hgate.control(label="my ch").c_if(cr, 1)
circ.append(controlh, [0, 1])
self.assertEqual(
str(_text_circuit_drawer(circ, vertical_compression="high", cregbundle=True)), expected
)
def test_control_gate_label_with_cond_2_med_space(self):
"""Control gate has a label and a conditional (on label, compression=med)
See https://github.com/Qiskit/qiskit-terra/issues/4361"""
expected = "\n".join(
[
" ┌──────┐",
"q_0: |0>┤ my h ├",
" └──┬───┘",
"q_1: |0>───■────",
" my ch ",
" ┌──╨──┐ ",
" c: 0 1/╡ 0x1 ╞═",
" └─────┘ ",
]
)
qr = QuantumRegister(2, "q")
cr = ClassicalRegister(1, "c")
circ = QuantumCircuit(qr, cr)
hgate = HGate(label="my h")
controlh = hgate.control(label="my ch").c_if(cr, 1)
circ.append(controlh, [1, 0])
self.assertEqual(str(_text_circuit_drawer(circ, vertical_compression="medium")), expected)
def test_control_gate_label_with_cond_2_med(self):
"""Control gate has a label and a conditional (on label, compression=med)
See https://github.com/Qiskit/qiskit-terra/issues/4361"""
expected = "\n".join(
[
" ┌──────┐ ",
"q_0: |0>──┤ my h ├─",
" └──┬───┘ ",
"q_1: |0>─────■─────",
" my ctrl-h ",
" ║ ",
" c: 0 ═════■═════",
" 0x1 ",
]
)
qr = QuantumRegister(2, "q")
cr = ClassicalRegister(1, "c")
circ = QuantumCircuit(qr, cr)
hgate = HGate(label="my h")
controlh = hgate.control(label="my ctrl-h").c_if(cr, 1)
circ.append(controlh, [1, 0])
self.assertEqual(
str(_text_circuit_drawer(circ, cregbundle=False, vertical_compression="medium")),
expected,
)
def test_control_gate_label_with_cond_2_med_cregbundle(self):
"""Control gate has a label and a conditional (on label, compression=med) with cregbundle
See https://github.com/Qiskit/qiskit-terra/issues/4361"""
expected = "\n".join(
[
" ┌──────┐",
"q_0: |0>┤ my h ├",
" └──┬───┘",
"q_1: |0>───■────",
" my ch ",
" ┌──╨──┐ ",
" c: 0 1/╡ 0x1 ╞═",
" └─────┘ ",
]
)
qr = QuantumRegister(2, "q")
cr = ClassicalRegister(1, "c")
circ = QuantumCircuit(qr, cr)
hgate = HGate(label="my h")
controlh = hgate.control(label="my ch").c_if(cr, 1)
circ.append(controlh, [1, 0])
self.assertEqual(
str(_text_circuit_drawer(circ, vertical_compression="medium", cregbundle=True)),
expected,
)
def test_control_gate_label_with_cond_2_low(self):
"""Control gate has a label and a conditional (on label, compression=low)
See https://github.com/Qiskit/qiskit-terra/issues/4361"""
expected = "\n".join(
[
" ┌──────┐",
"q_0: |0>┤ my h ├",
" └──┬───┘",
" │ ",
"q_1: |0>───■────",
" my ch ",
" ║ ",
" c: 0 ═══■════",
" 0x1 ",
]
)
qr = QuantumRegister(2, "q")
cr = ClassicalRegister(1, "c")
circ = QuantumCircuit(qr, cr)
hgate = HGate(label="my h")
controlh = hgate.control(label="my ch").c_if(cr, 1)
circ.append(controlh, [1, 0])
self.assertEqual(
str(_text_circuit_drawer(circ, cregbundle=False, vertical_compression="low")), expected
)
def test_control_gate_label_with_cond_2_low_cregbundle(self):
"""Control gate has a label and a conditional (on label, compression=low) with cregbundle
See https://github.com/Qiskit/qiskit-terra/issues/4361"""
expected = "\n".join(
[
" ┌──────┐",
"q_0: |0>┤ my h ├",
" └──┬───┘",
" │ ",
"q_1: |0>───■────",
" my ch ",
" ┌──╨──┐ ",
" c: 0 1/╡ 0x1 ╞═",
" └─────┘ ",
]
)
qr = QuantumRegister(2, "q")
cr = ClassicalRegister(1, "c")
circ = QuantumCircuit(qr, cr)
hgate = HGate(label="my h")
controlh = hgate.control(label="my ch").c_if(cr, 1)
circ.append(controlh, [1, 0])
self.assertEqual(
str(_text_circuit_drawer(circ, vertical_compression="low", cregbundle=True)), expected
)
class TestTextDrawerParams(QiskitTestCase):
"""Test drawing parameters."""
def test_text_no_parameters(self):
"""Test drawing with no parameters"""
expected = "\n".join(
[
" ┌───┐",
"q: |0>┤ X ├",
" └───┘",
]
)
qr = QuantumRegister(1, "q")
circuit = QuantumCircuit(qr)
circuit.x(0)
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_text_parameters_mix(self):
"""cu3 drawing with parameters"""
expected = "\n".join(
[
" ",
"q_0: |0>─────────■──────────",
" ┌────────┴─────────┐",
"q_1: |0>┤ U(π/2,theta,π,0) ├",
" └──────────────────┘",
]
)
qr = QuantumRegister(2, "q")
circuit = QuantumCircuit(qr)
circuit.cu(pi / 2, Parameter("theta"), pi, 0, qr[0], qr[1])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_text_bound_parameters(self):
"""Bound parameters
See: https://github.com/Qiskit/qiskit-terra/pull/3876"""
# fmt: off
expected = "\n".join([" ┌────────────┐",
"qr: |0>┤ my_u2(π,π) ├",
" └────────────┘"])
# fmt: on
my_u2_circuit = QuantumCircuit(1, name="my_u2")
phi = Parameter("phi")
lam = Parameter("lambda")
my_u2_circuit.u(3.141592653589793, phi, lam, 0)
my_u2 = my_u2_circuit.to_gate()
qr = QuantumRegister(1, name="qr")
circuit = QuantumCircuit(qr, name="circuit")
circuit.append(my_u2, [qr[0]])
circuit = circuit.bind_parameters({phi: 3.141592653589793, lam: 3.141592653589793})
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_text_pi_param_expr(self):
"""Text pi in circuit with parameter expression."""
expected = "\n".join(
[
" ┌─────────────────────┐",
"q: ┤ Rx((π - x)*(π - y)) ├",
" └─────────────────────┘",
]
)
x, y = Parameter("x"), Parameter("y")
circuit = QuantumCircuit(1)
circuit.rx((pi - x) * (pi - y), 0)
self.assertEqual(circuit.draw(output="text").single_string(), expected)
def test_text_utf8(self):
"""Test that utf8 characters work in windows CI env."""
# fmt: off
expected = "\n".join([" ┌──────────┐",
"q: ┤ U(0,φ,λ) ├",
" └──────────┘"])
# fmt: on
phi, lam = Parameter("φ"), Parameter("λ")
circuit = QuantumCircuit(1)
circuit.u(0, phi, lam, 0)
self.assertEqual(circuit.draw(output="text").single_string(), expected)
def test_text_ndarray_parameters(self):
"""Test that if params are type ndarray, params are not displayed."""
# fmt: off
expected = "\n".join([" ┌─────────┐",
"q: |0>┤ Unitary ├",
" └─────────┘"])
# fmt: on
qr = QuantumRegister(1, "q")
circuit = QuantumCircuit(qr)
circuit.unitary(numpy.array([[0, 1], [1, 0]]), 0)
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_text_qc_parameters(self):
"""Test that if params are type QuantumCircuit, params are not displayed."""
expected = "\n".join(
[
" ┌───────┐",
"q_0: |0>┤0 ├",
" │ name │",
"q_1: |0>┤1 ├",
" └───────┘",
]
)
my_qc_param = QuantumCircuit(2)
my_qc_param.h(0)
my_qc_param.cx(0, 1)
inst = Instruction("name", 2, 0, [my_qc_param])
qr = QuantumRegister(2, "q")
circuit = QuantumCircuit(qr)
circuit.append(inst, [0, 1])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
class TestTextDrawerVerticalCompressionLow(QiskitTestCase):
"""Test vertical_compression='low'"""
def test_text_conditional_1(self):
"""Conditional drawing with 1-bit-length regs."""
qasm_string = """
OPENQASM 2.0;
include "qelib1.inc";
qreg q[1];
creg c0[1];
creg c1[1];
if(c0==1) x q[0];
if(c1==1) x q[0];
"""
expected = "\n".join(
[
" ┌───┐┌───┐",
"q: |0>┤ X ├┤ X ├",
" └─╥─┘└─╥─┘",
" ║ ║ ",
"c0: 0 ══■════╬══",
" 0x1 ║ ",
" ║ ",
"c1: 0 ═══════■══",
" 0x1 ",
]
)
circuit = QuantumCircuit.from_qasm_str(qasm_string)
self.assertEqual(
str(_text_circuit_drawer(circuit, cregbundle=False, vertical_compression="low")),
expected,
)
def test_text_conditional_1_bundle(self):
"""Conditional drawing with 1-bit-length regs."""
qasm_string = """
OPENQASM 2.0;
include "qelib1.inc";
qreg q[1];
creg c0[1];
creg c1[1];
if(c0==1) x q[0];
if(c1==1) x q[0];
"""
expected = "\n".join(
[
" ┌───┐ ┌───┐ ",
" q: |0>─┤ X ├──┤ X ├─",
" └─╥─┘ └─╥─┘ ",
" ┌──╨──┐ ║ ",
"c0: 0 1/╡ 0x1 ╞═══╬═══",
" └─────┘ ║ ",
" ┌──╨──┐",
"c1: 0 1/═══════╡ 0x1 ╞",
" └─────┘",
]
)
circuit = QuantumCircuit.from_qasm_str(qasm_string)
self.assertEqual(
str(_text_circuit_drawer(circuit, vertical_compression="low", cregbundle=True)),
expected,
)
def test_text_conditional_reverse_bits_true(self):
"""Conditional drawing with 1-bit-length regs."""
cr = ClassicalRegister(2, "cr")
cr2 = ClassicalRegister(1, "cr2")
qr = QuantumRegister(3, "qr")
circuit = QuantumCircuit(qr, cr, cr2)
circuit.h(0)
circuit.h(1)
circuit.h(2)
circuit.x(0)
circuit.x(0)
circuit.measure(2, 1)
circuit.x(2).c_if(cr, 2)
expected = "\n".join(
[
" ┌───┐ ┌─┐ ┌───┐",
"qr_2: |0>┤ H ├─────┤M├─────┤ X ├",
" └───┘ └╥┘ └─╥─┘",
" ┌───┐ ║ ║ ",
"qr_1: |0>┤ H ├──────╫────────╫──",
" └───┘ ║ ║ ",
" ┌───┐┌───┐ ║ ┌───┐ ║ ",
"qr_0: |0>┤ H ├┤ X ├─╫─┤ X ├──╫──",
" └───┘└───┘ ║ └───┘ ║ ",
" ║ ║ ",
" cr2: 0 ═══════════╬════════╬══",
" ║ ║ ",
" ║ ║ ",
" cr_1: 0 ═══════════╩════════■══",
" ║ ",
" ║ ",
" cr_0: 0 ════════════════════o══",
" 0x2 ",
]
)
self.assertEqual(
str(
_text_circuit_drawer(
circuit, vertical_compression="low", cregbundle=False, reverse_bits=True
)
),
expected,
)
def test_text_conditional_reverse_bits_false(self):
"""Conditional drawing with 1-bit-length regs."""
cr = ClassicalRegister(2, "cr")
cr2 = ClassicalRegister(1, "cr2")
qr = QuantumRegister(3, "qr")
circuit = QuantumCircuit(qr, cr, cr2)
circuit.h(0)
circuit.h(1)
circuit.h(2)
circuit.x(0)
circuit.x(0)
circuit.measure(2, 1)
circuit.x(2).c_if(cr, 2)
expected = "\n".join(
[
" ┌───┐┌───┐┌───┐",
"qr_0: |0>┤ H ├┤ X ├┤ X ├",
" └───┘└───┘└───┘",
" ┌───┐ ",
"qr_1: |0>┤ H ├──────────",
" └───┘ ",
" ┌───┐ ┌─┐ ┌───┐",
"qr_2: |0>┤ H ├─┤M├─┤ X ├",
" └───┘ └╥┘ └─╥─┘",
" ║ ║ ",
" cr_0: 0 ═══════╬════o══",
" ║ ║ ",
" ║ ║ ",
" cr_1: 0 ═══════╩════■══",
" 0x2 ",
" ",
" cr2: 0 ═══════════════",
" ",
]
)
self.assertEqual(
str(
_text_circuit_drawer(
circuit, vertical_compression="low", cregbundle=False, reverse_bits=False
)
),
expected,
)
def test_text_justify_right(self):
"""Drawing with right justify"""
expected = "\n".join(
[
" ┌───┐",
"q1_0: |0>─────┤ X ├",
" └───┘",
" ┌───┐ ┌─┐ ",
"q1_1: |0>┤ H ├─┤M├─",
" └───┘ └╥┘ ",
" ║ ",
" c1: 0 2/═══════╩══",
" 1 ",
]
)
qr1 = QuantumRegister(2, "q1")
cr1 = ClassicalRegister(2, "c1")
circuit = QuantumCircuit(qr1, cr1)
circuit.x(qr1[0])
circuit.h(qr1[1])
circuit.measure(qr1[1], cr1[1])
self.assertEqual(
str(_text_circuit_drawer(circuit, justify="right", vertical_compression="low")),
expected,
)
class TestTextDrawerVerticalCompressionMedium(QiskitTestCase):
"""Test vertical_compression='medium'"""
def test_text_conditional_1(self):
"""Medium vertical compression avoids box overlap."""
qasm_string = """
OPENQASM 2.0;
include "qelib1.inc";
qreg q[1];
creg c0[1];
creg c1[1];
if(c0==1) x q[0];
if(c1==1) x q[0];
"""
expected = "\n".join(
[
" ┌───┐┌───┐",
"q: |0>┤ X ├┤ X ├",
" └─╥─┘└─╥─┘",
"c0: 0 ══■════╬══",
" 0x1 ║ ",
"c1: 0 ═══════■══",
" 0x1 ",
]
)
circuit = QuantumCircuit.from_qasm_str(qasm_string)
self.assertEqual(
str(_text_circuit_drawer(circuit, cregbundle=False, vertical_compression="medium")),
expected,
)
def test_text_conditional_1_bundle(self):
"""Medium vertical compression avoids box overlap."""
qasm_string = """
OPENQASM 2.0;
include "qelib1.inc";
qreg q[1];
creg c0[1];
creg c1[1];
if(c0==1) x q[0];
if(c1==1) x q[0];
"""
expected = "\n".join(
[
" ┌───┐ ┌───┐ ",
" q: |0>─┤ X ├──┤ X ├─",
" └─╥─┘ └─╥─┘ ",
" ┌──╨──┐ ║ ",
"c0: 0 1/╡ 0x1 ╞═══╬═══",
" └─────┘┌──╨──┐",
"c1: 0 1/═══════╡ 0x1 ╞",
" └─────┘",
]
)
circuit = QuantumCircuit.from_qasm_str(qasm_string)
self.assertEqual(
str(_text_circuit_drawer(circuit, vertical_compression="medium", cregbundle=True)),
expected,
)
def test_text_measure_with_spaces(self):
"""Measure wire might have extra spaces
Found while reproducing
https://quantumcomputing.stackexchange.com/q/10194/1859"""
qasm_string = """
OPENQASM 2.0;
include "qelib1.inc";
qreg q[2];
creg c[3];
measure q[0] -> c[1];
if(c==1) x q[1];
"""
expected = "\n".join(
[
" ┌─┐ ",
"q_0: |0>┤M├─────",
" └╥┘┌───┐",
"q_1: |0>─╫─┤ X ├",
" ║ └─╥─┘",
" c_0: 0 ═╬═══■══",
" ║ ║ ",
" c_1: 0 ═╩═══o══",
" ║ ",
" c_2: 0 ═════o══",
" 0x1 ",
]
)
circuit = QuantumCircuit.from_qasm_str(qasm_string)
self.assertEqual(
str(_text_circuit_drawer(circuit, cregbundle=False, vertical_compression="medium")),
expected,
)
def test_text_measure_with_spaces_bundle(self):
"""Measure wire might have extra spaces
Found while reproducing
https://quantumcomputing.stackexchange.com/q/10194/1859"""
qasm_string = """
OPENQASM 2.0;
include "qelib1.inc";
qreg q[2];
creg c[3];
measure q[0] -> c[1];
if(c==1) x q[1];
"""
expected = "\n".join(
[
" ┌─┐ ",
"q_0: |0>┤M├───────",
" └╥┘ ┌───┐ ",
"q_1: |0>─╫──┤ X ├─",
" ║ └─╥─┘ ",
" ║ ┌──╨──┐",
" c: 0 3/═╩═╡ 0x1 ╞",
" 1 └─────┘",
]
)
circuit = QuantumCircuit.from_qasm_str(qasm_string)
self.assertEqual(
str(_text_circuit_drawer(circuit, vertical_compression="medium", cregbundle=True)),
expected,
)
def test_text_barrier_med_compress_1(self):
"""Medium vertical compression avoids connection break."""
circuit = QuantumCircuit(4)
circuit.cx(1, 3)
circuit.x(1)
circuit.barrier((2, 3), label="Bar 1")
expected = "\n".join(
[
" ",
"q_0: |0>────────────",
" ┌───┐ ",
"q_1: |0>──■───┤ X ├─",
" │ └───┘ ",
" │ Bar 1 ",
"q_2: |0>──┼─────░───",
" ┌─┴─┐ ░ ",
"q_3: |0>┤ X ├───░───",
" └───┘ ░ ",
]
)
self.assertEqual(
str(_text_circuit_drawer(circuit, vertical_compression="medium", cregbundle=False)),
expected,
)
def test_text_barrier_med_compress_2(self):
"""Medium vertical compression avoids overprint."""
circuit = QuantumCircuit(4)
circuit.barrier((0, 1, 2), label="a")
circuit.cx(1, 3)
circuit.x(1)
circuit.barrier((2, 3), label="Bar 1")
expected = "\n".join(
[
" a ",
"q_0: |0>─░─────────────",
" ░ ┌───┐ ",
"q_1: |0>─░───■───┤ X ├─",
" ░ │ └───┘ ",
" ░ │ Bar 1 ",
"q_2: |0>─░───┼─────░───",
" ░ ┌─┴─┐ ░ ",
"q_3: |0>───┤ X ├───░───",
" └───┘ ░ ",
]
)
self.assertEqual(
str(_text_circuit_drawer(circuit, vertical_compression="medium", cregbundle=False)),
expected,
)
def test_text_barrier_med_compress_3(self):
"""Medium vertical compression avoids conditional connection break."""
qr = QuantumRegister(1, "qr")
qc1 = ClassicalRegister(3, "cr")
qc2 = ClassicalRegister(1, "cr2")
circuit = QuantumCircuit(qr, qc1, qc2)
circuit.x(0).c_if(qc1, 3)
circuit.x(0).c_if(qc2[0], 1)
expected = "\n".join(
[
" ┌───┐┌───┐",
" qr: |0>┤ X ├┤ X ├",
" └─╥─┘└─╥─┘",
"cr_0: 0 ══■════╬══",
" ║ ║ ",
"cr_2: 0 ══o════╬══",
" ║ ║ ",
" cr2: 0 ══╬════■══",
" ║ ",
"cr_1: 0 ══■═══════",
" 0x3 ",
]
)
self.assertEqual(
str(
_text_circuit_drawer(
circuit,
vertical_compression="medium",
wire_order=[0, 1, 3, 4, 2],
cregbundle=False,
)
),
expected,
)
class TestTextConditional(QiskitTestCase):
"""Gates with conditionals"""
def test_text_conditional_1_cregbundle(self):
"""Conditional drawing with 1-bit-length regs and cregbundle."""
qasm_string = """
OPENQASM 2.0;
include "qelib1.inc";
qreg q[1];
creg c0[1];
creg c1[1];
if(c0==1) x q[0];
if(c1==1) x q[0];
"""
expected = "\n".join(
[
" ┌───┐ ┌───┐ ",
" q: |0>─┤ X ├──┤ X ├─",
" ┌┴─╨─┴┐ └─╥─┘ ",
"c0: 0 1/╡ 0x1 ╞═══╬═══",
" └─────┘┌──╨──┐",
"c1: 0 1/═══════╡ 0x1 ╞",
" └─────┘",
]
)
circuit = QuantumCircuit.from_qasm_str(qasm_string)
self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=True)), expected)
def test_text_conditional_1(self):
"""Conditional drawing with 1-bit-length regs."""
qasm_string = """
OPENQASM 2.0;
include "qelib1.inc";
qreg q[1];
creg c0[1];
creg c1[1];
if(c0==1) x q[0];
if(c1==1) x q[0];
"""
expected = "\n".join(
[
" ┌───┐┌───┐",
"q: |0>┤ X ├┤ X ├",
" └─╥─┘└─╥─┘",
"c0: 0 ══■════╬══",
" 0x1 ║ ",
"c1: 0 ═══════■══",
" 0x1 ",
]
)
circuit = QuantumCircuit.from_qasm_str(qasm_string)
self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=False)), expected)
def test_text_conditional_2_cregbundle(self):
"""Conditional drawing with 2-bit-length regs with cregbundle"""
qasm_string = """
OPENQASM 2.0;
include "qelib1.inc";
qreg q[1];
creg c0[2];
creg c1[2];
if(c0==2) x q[0];
if(c1==2) x q[0];
"""
expected = "\n".join(
[
" ┌───┐ ┌───┐ ",
" q: |0>─┤ X ├──┤ X ├─",
" ┌┴─╨─┴┐ └─╥─┘ ",
"c0: 0 2/╡ 0x2 ╞═══╬═══",
" └─────┘┌──╨──┐",
"c1: 0 2/═══════╡ 0x2 ╞",
" └─────┘",
]
)
circuit = QuantumCircuit.from_qasm_str(qasm_string)
self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=True)), expected)
def test_text_conditional_2(self):
"""Conditional drawing with 2-bit-length regs."""
qasm_string = """
OPENQASM 2.0;
include "qelib1.inc";
qreg q[1];
creg c0[2];
creg c1[2];
if(c0==2) x q[0];
if(c1==2) x q[0];
"""
expected = "\n".join(
[
" ┌───┐┌───┐",
" q: |0>┤ X ├┤ X ├",
" └─╥─┘└─╥─┘",
"c0_0: 0 ══o════╬══",
" ║ ║ ",
"c0_1: 0 ══■════╬══",
" 0x2 ║ ",
"c1_0: 0 ═══════o══",
" ║ ",
"c1_1: 0 ═══════■══",
" 0x2 ",
]
)
circuit = QuantumCircuit.from_qasm_str(qasm_string)
self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=False)), expected)
def test_text_conditional_3_cregbundle(self):
"""Conditional drawing with 3-bit-length regs with cregbundle."""
qasm_string = """
OPENQASM 2.0;
include "qelib1.inc";
qreg q[1];
creg c0[3];
creg c1[3];
if(c0==3) x q[0];
if(c1==3) x q[0];
"""
expected = "\n".join(
[
" ┌───┐ ┌───┐ ",
" q: |0>─┤ X ├──┤ X ├─",
" ┌┴─╨─┴┐ └─╥─┘ ",
"c0: 0 3/╡ 0x3 ╞═══╬═══",
" └─────┘┌──╨──┐",
"c1: 0 3/═══════╡ 0x3 ╞",
" └─────┘",
]
)
circuit = QuantumCircuit.from_qasm_str(qasm_string)
self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=True)), expected)
def test_text_conditional_3(self):
"""Conditional drawing with 3-bit-length regs."""
qasm_string = """
OPENQASM 2.0;
include "qelib1.inc";
qreg q[1];
creg c0[3];
creg c1[3];
if(c0==3) x q[0];
if(c1==3) x q[0];
"""
expected = "\n".join(
[
" ┌───┐┌───┐",
" q: |0>┤ X ├┤ X ├",
" └─╥─┘└─╥─┘",
"c0_0: 0 ══■════╬══",
" ║ ║ ",
"c0_1: 0 ══■════╬══",
" ║ ║ ",
"c0_2: 0 ══o════╬══",
" 0x3 ║ ",
"c1_0: 0 ═══════■══",
" ║ ",
"c1_1: 0 ═══════■══",
" ║ ",
"c1_2: 0 ═══════o══",
" 0x3 ",
]
)
circuit = QuantumCircuit.from_qasm_str(qasm_string)
self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=False)), expected)
def test_text_conditional_4(self):
"""Conditional drawing with 4-bit-length regs."""
qasm_string = """
OPENQASM 2.0;
include "qelib1.inc";
qreg q[1];
creg c0[4];
creg c1[4];
if(c0==4) x q[0];
if(c1==4) x q[0];
"""
expected = "\n".join(
[
" ┌───┐ ┌───┐ ",
" q: |0>─┤ X ├──┤ X ├─",
" ┌┴─╨─┴┐ └─╥─┘ ",
"c0: 0 4/╡ 0x4 ╞═══╬═══",
" └─────┘┌──╨──┐",
"c1: 0 4/═══════╡ 0x4 ╞",
" └─────┘",
]
)
circuit = QuantumCircuit.from_qasm_str(qasm_string)
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_text_conditional_5(self):
"""Conditional drawing with 5-bit-length regs."""
qasm_string = """
OPENQASM 2.0;
include "qelib1.inc";
qreg q[1];
creg c0[5];
creg c1[5];
if(c0==5) x q[0];
if(c1==5) x q[0];
"""
expected = "\n".join(
[
" ┌───┐┌───┐",
" q: |0>┤ X ├┤ X ├",
" └─╥─┘└─╥─┘",
"c0_0: 0 ══■════╬══",
" ║ ║ ",
"c0_1: 0 ══o════╬══",
" ║ ║ ",
"c0_2: 0 ══■════╬══",
" ║ ║ ",
"c0_3: 0 ══o════╬══",
" ║ ║ ",
"c0_4: 0 ══o════╬══",
" 0x5 ║ ",
"c1_0: 0 ═══════■══",
" ║ ",
"c1_1: 0 ═══════o══",
" ║ ",
"c1_2: 0 ═══════■══",
" ║ ",
"c1_3: 0 ═══════o══",
" ║ ",
"c1_4: 0 ═══════o══",
" 0x5 ",
]
)
circuit = QuantumCircuit.from_qasm_str(qasm_string)
self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=False)), expected)
def test_text_conditional_cz_no_space_cregbundle(self):
"""Conditional CZ without space"""
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.cz(qr[0], qr[1]).c_if(cr, 1)
expected = "\n".join(
[
" ",
"qr_0: |0>───■───",
" │ ",
"qr_1: |0>───■───",
" ┌──╨──┐",
" cr: 0 1/╡ 0x1 ╞",
" └─────┘",
]
)
self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=True)), expected)
def test_text_conditional_cz_no_space(self):
"""Conditional CZ without space"""
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.cz(qr[0], qr[1]).c_if(cr, 1)
expected = "\n".join(
[
" ",
"qr_0: |0>──■──",
" │ ",
"qr_1: |0>──■──",
" ║ ",
" cr: 0 ══■══",
" 0x1 ",
]
)
self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=False)), expected)
def test_text_conditional_cz_cregbundle(self):
"""Conditional CZ with a wire in the middle"""
qr = QuantumRegister(3, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.cz(qr[0], qr[1]).c_if(cr, 1)
expected = "\n".join(
[
" ",
"qr_0: |0>───■───",
" │ ",
"qr_1: |0>───■───",
" ║ ",
"qr_2: |0>───╫───",
" ┌──╨──┐",
" cr: 0 1/╡ 0x1 ╞",
" └─────┘",
]
)
self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=True)), expected)
def test_text_conditional_cz(self):
"""Conditional CZ with a wire in the middle"""
qr = QuantumRegister(3, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.cz(qr[0], qr[1]).c_if(cr, 1)
expected = "\n".join(
[
" ",
"qr_0: |0>──■──",
" │ ",
"qr_1: |0>──■──",
" ║ ",
"qr_2: |0>──╫──",
" ║ ",
" cr: 0 ══■══",
" 0x1 ",
]
)
self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=False)), expected)
def test_text_conditional_cx_ct_cregbundle(self):
"""Conditional CX (control-target) with a wire in the middle"""
qr = QuantumRegister(3, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.cx(qr[0], qr[1]).c_if(cr, 1)
expected = "\n".join(
[
" ",
"qr_0: |0>───■───",
" ┌─┴─┐ ",
"qr_1: |0>─┤ X ├─",
" └─╥─┘ ",
"qr_2: |0>───╫───",
" ┌──╨──┐",
" cr: 0 1/╡ 0x1 ╞",
" └─────┘",
]
)
self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=True)), expected)
def test_text_conditional_cx_ct(self):
"""Conditional CX (control-target) with a wire in the middle"""
qr = QuantumRegister(3, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.cx(qr[0], qr[1]).c_if(cr, 1)
expected = "\n".join(
[
" ",
"qr_0: |0>──■──",
" ┌─┴─┐",
"qr_1: |0>┤ X ├",
" └─╥─┘",
"qr_2: |0>──╫──",
" ║ ",
" cr: 0 ══■══",
" 0x1 ",
]
)
self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=False)), expected)
def test_text_conditional_cx_tc_cregbundle(self):
"""Conditional CX (target-control) with a wire in the middle with cregbundle."""
qr = QuantumRegister(3, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.cx(qr[1], qr[0]).c_if(cr, 1)
expected = "\n".join(
[
" ┌───┐ ",
"qr_0: |0>─┤ X ├─",
" └─┬─┘ ",
"qr_1: |0>───■───",
" ║ ",
"qr_2: |0>───╫───",
" ┌──╨──┐",
" cr: 0 1/╡ 0x1 ╞",
" └─────┘",
]
)
self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=True)), expected)
def test_text_conditional_cx_tc(self):
"""Conditional CX (target-control) with a wire in the middle"""
qr = QuantumRegister(3, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.cx(qr[1], qr[0]).c_if(cr, 1)
expected = "\n".join(
[
" ┌───┐",
"qr_0: |0>┤ X ├",
" └─┬─┘",
"qr_1: |0>──■──",
" ║ ",
"qr_2: |0>──╫──",
" ║ ",
" cr: 0 ══■══",
" 0x1 ",
]
)
self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=False)), expected)
def test_text_conditional_cu3_ct_cregbundle(self):
"""Conditional Cu3 (control-target) with a wire in the middle with cregbundle"""
qr = QuantumRegister(3, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.append(CU3Gate(pi / 2, pi / 2, pi / 2), [qr[0], qr[1]]).c_if(cr, 1)
expected = "\n".join(
[
" ",
"qr_0: |0>─────────■─────────",
" ┌────────┴────────┐",
"qr_1: |0>┤ U3(π/2,π/2,π/2) ├",
" └────────╥────────┘",
"qr_2: |0>─────────╫─────────",
" ┌──╨──┐ ",
" cr: 0 1/══════╡ 0x1 ╞══════",
" └─────┘ ",
]
)
self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=True)), expected)
def test_text_conditional_cu3_ct(self):
"""Conditional Cu3 (control-target) with a wire in the middle"""
qr = QuantumRegister(3, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.append(CU3Gate(pi / 2, pi / 2, pi / 2), [qr[0], qr[1]]).c_if(cr, 1)
expected = "\n".join(
[
" ",
"qr_0: |0>─────────■─────────",
" ┌────────┴────────┐",
"qr_1: |0>┤ U3(π/2,π/2,π/2) ├",
" └────────╥────────┘",
"qr_2: |0>─────────╫─────────",
" ║ ",
" cr: 0 ═════════■═════════",
" 0x1 ",
]
)
self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=False)), expected)
def test_text_conditional_cu3_tc_cregbundle(self):
"""Conditional Cu3 (target-control) with a wire in the middle with cregbundle"""
qr = QuantumRegister(3, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.append(CU3Gate(pi / 2, pi / 2, pi / 2), [qr[1], qr[0]]).c_if(cr, 1)
expected = "\n".join(
[
" ┌─────────────────┐",
"qr_0: |0>┤ U3(π/2,π/2,π/2) ├",
" └────────┬────────┘",
"qr_1: |0>─────────■─────────",
" ║ ",
"qr_2: |0>─────────╫─────────",
" ┌──╨──┐ ",
" cr: 0 1/══════╡ 0x1 ╞══════",
" └─────┘ ",
]
)
self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=True)), expected)
def test_text_conditional_cu3_tc(self):
"""Conditional Cu3 (target-control) with a wire in the middle"""
qr = QuantumRegister(3, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.append(CU3Gate(pi / 2, pi / 2, pi / 2), [qr[1], qr[0]]).c_if(cr, 1)
expected = "\n".join(
[
" ┌─────────────────┐",
"qr_0: |0>┤ U3(π/2,π/2,π/2) ├",
" └────────┬────────┘",
"qr_1: |0>─────────■─────────",
" ║ ",
"qr_2: |0>─────────╫─────────",
" ║ ",
" cr: 0 ═════════■═════════",
" 0x1 ",
]
)
self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=False)), expected)
def test_text_conditional_ccx_cregbundle(self):
"""Conditional CCX with a wire in the middle with cregbundle"""
qr = QuantumRegister(4, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.ccx(qr[0], qr[1], qr[2]).c_if(cr, 1)
expected = "\n".join(
[
" ",
"qr_0: |0>───■───",
" │ ",
"qr_1: |0>───■───",
" ┌─┴─┐ ",
"qr_2: |0>─┤ X ├─",
" └─╥─┘ ",
"qr_3: |0>───╫───",
" ┌──╨──┐",
" cr: 0 1/╡ 0x1 ╞",
" └─────┘",
]
)
self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=True)), expected)
def test_text_conditional_ccx(self):
"""Conditional CCX with a wire in the middle"""
qr = QuantumRegister(4, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.ccx(qr[0], qr[1], qr[2]).c_if(cr, 1)
expected = "\n".join(
[
" ",
"qr_0: |0>──■──",
" │ ",
"qr_1: |0>──■──",
" ┌─┴─┐",
"qr_2: |0>┤ X ├",
" └─╥─┘",
"qr_3: |0>──╫──",
" ║ ",
" cr: 0 ══■══",
" 0x1 ",
]
)
self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=False)), expected)
def test_text_conditional_ccx_no_space_cregbundle(self):
"""Conditional CCX without space with cregbundle"""
qr = QuantumRegister(3, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.ccx(qr[0], qr[1], qr[2]).c_if(cr, 1)
expected = "\n".join(
[
" ",
"qr_0: |0>───■───",
" │ ",
"qr_1: |0>───■───",
" ┌─┴─┐ ",
"qr_2: |0>─┤ X ├─",
" ┌┴─╨─┴┐",
" cr: 0 1/╡ 0x1 ╞",
" └─────┘",
]
)
self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=True)), expected)
def test_text_conditional_ccx_no_space(self):
"""Conditional CCX without space"""
qr = QuantumRegister(3, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.ccx(qr[0], qr[1], qr[2]).c_if(cr, 1)
expected = "\n".join(
[
" ",
"qr_0: |0>──■──",
" │ ",
"qr_1: |0>──■──",
" ┌─┴─┐",
"qr_2: |0>┤ X ├",
" └─╥─┘",
" cr: 0 ══■══",
" 0x1 ",
]
)
self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=False)), expected)
def test_text_conditional_h_cregbundle(self):
"""Conditional H with a wire in the middle with cregbundle"""
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.h(qr[0]).c_if(cr, 1)
expected = "\n".join(
[
" ┌───┐ ",
"qr_0: |0>─┤ H ├─",
" └─╥─┘ ",
"qr_1: |0>───╫───",
" ┌──╨──┐",
" cr: 0 1/╡ 0x1 ╞",
" └─────┘",
]
)
self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=True)), expected)
def test_text_conditional_h(self):
"""Conditional H with a wire in the middle"""
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.h(qr[0]).c_if(cr, 1)
expected = "\n".join(
[
" ┌───┐",
"qr_0: |0>┤ H ├",
" └─╥─┘",
"qr_1: |0>──╫──",
" ║ ",
" cr: 0 ══■══",
" 0x1 ",
]
)
self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=False)), expected)
def test_text_conditional_swap_cregbundle(self):
"""Conditional SWAP with cregbundle"""
qr = QuantumRegister(3, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.swap(qr[0], qr[1]).c_if(cr, 1)
expected = "\n".join(
[
" ",
"qr_0: |0>───X───",
" │ ",
"qr_1: |0>───X───",
" ║ ",
"qr_2: |0>───╫───",
" ┌──╨──┐",
" cr: 0 1/╡ 0x1 ╞",
" └─────┘",
]
)
self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=True)), expected)
def test_text_conditional_swap(self):
"""Conditional SWAP"""
qr = QuantumRegister(3, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.swap(qr[0], qr[1]).c_if(cr, 1)
expected = "\n".join(
[
" ",
"qr_0: |0>──X──",
" │ ",
"qr_1: |0>──X──",
" ║ ",
"qr_2: |0>──╫──",
" ║ ",
" cr: 0 ══■══",
" 0x1 ",
]
)
self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=False)), expected)
def test_text_conditional_cswap_cregbundle(self):
"""Conditional CSwap with cregbundle"""
qr = QuantumRegister(4, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.cswap(qr[0], qr[1], qr[2]).c_if(cr, 1)
expected = "\n".join(
[
" ",
"qr_0: |0>───■───",
" │ ",
"qr_1: |0>───X───",
" │ ",
"qr_2: |0>───X───",
" ║ ",
"qr_3: |0>───╫───",
" ┌──╨──┐",
" cr: 0 1/╡ 0x1 ╞",
" └─────┘",
]
)
self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=True)), expected)
def test_text_conditional_cswap(self):
"""Conditional CSwap"""
qr = QuantumRegister(4, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.cswap(qr[0], qr[1], qr[2]).c_if(cr, 1)
expected = "\n".join(
[
" ",
"qr_0: |0>──■──",
" │ ",
"qr_1: |0>──X──",
" │ ",
"qr_2: |0>──X──",
" ║ ",
"qr_3: |0>──╫──",
" ║ ",
" cr: 0 ══■══",
" 0x1 ",
]
)
self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=False)), expected)
def test_conditional_reset_cregbundle(self):
"""Reset drawing with cregbundle."""
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.reset(qr[0]).c_if(cr, 1)
expected = "\n".join(
[
" ",
"qr_0: |0>──|0>──",
" ║ ",
"qr_1: |0>───╫───",
" ┌──╨──┐",
" cr: 0 1/╡ 0x1 ╞",
" └─────┘",
]
)
self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=True)), expected)
def test_conditional_reset(self):
"""Reset drawing."""
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.reset(qr[0]).c_if(cr, 1)
expected = "\n".join(
[
" ",
"qr_0: |0>─|0>─",
" ║ ",
"qr_1: |0>──╫──",
" ║ ",
" cr: 0 ══■══",
" 0x1 ",
]
)
self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=False)), expected)
def test_conditional_multiplexer_cregbundle(self):
"""Test Multiplexer with cregbundle."""
cx_multiplexer = UCGate([numpy.eye(2), numpy.array([[0, 1], [1, 0]])])
qr = QuantumRegister(3, name="qr")
cr = ClassicalRegister(1, "cr")
qc = QuantumCircuit(qr, cr)
qc.append(cx_multiplexer.c_if(cr, 1), [qr[0], qr[1]])
expected = "\n".join(
[
" ┌──────────────┐",
"qr_0: |0>┤0 ├",
" │ Multiplexer │",
"qr_1: |0>┤1 ├",
" └──────╥───────┘",
"qr_2: |0>───────╫────────",
" ┌──╨──┐ ",
" cr: 0 1/════╡ 0x1 ╞═════",
" └─────┘ ",
]
)
self.assertEqual(str(_text_circuit_drawer(qc, cregbundle=True)), expected)
def test_conditional_multiplexer(self):
"""Test Multiplexer."""
cx_multiplexer = UCGate([numpy.eye(2), numpy.array([[0, 1], [1, 0]])])
qr = QuantumRegister(3, name="qr")
cr = ClassicalRegister(1, "cr")
qc = QuantumCircuit(qr, cr)
qc.append(cx_multiplexer.c_if(cr, 1), [qr[0], qr[1]])
expected = "\n".join(
[
" ┌──────────────┐",
"qr_0: |0>┤0 ├",
" │ Multiplexer │",
"qr_1: |0>┤1 ├",
" └──────╥───────┘",
"qr_2: |0>───────╫────────",
" ║ ",
" cr: 0 ═══════■════════",
" 0x1 ",
]
)
self.assertEqual(str(_text_circuit_drawer(qc, cregbundle=False)), expected)
def test_text_conditional_measure_cregbundle(self):
"""Conditional with measure on same clbit with cregbundle"""
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(2, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.h(qr[0])
circuit.measure(qr[0], cr[0])
circuit.h(qr[1]).c_if(cr, 1)
expected = "\n".join(
[
" ┌───┐┌─┐ ",
"qr_0: |0>┤ H ├┤M├───────",
" └───┘└╥┘ ┌───┐ ",
"qr_1: |0>──────╫──┤ H ├─",
" ║ ┌┴─╨─┴┐",
" cr: 0 2/══════╩═╡ 0x1 ╞",
" 0 └─────┘",
]
)
self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=True)), expected)
def test_text_conditional_measure(self):
"""Conditional with measure on same clbit"""
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(2, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.h(qr[0])
circuit.measure(qr[0], cr[0])
circuit.h(qr[1]).c_if(cr, 1)
expected = "\n".join(
[
" ┌───┐┌─┐ ",
"qr_0: |0>┤ H ├┤M├─────",
" └───┘└╥┘┌───┐",
"qr_1: |0>──────╫─┤ H ├",
" ║ └─╥─┘",
" cr_0: 0 ══════╩═══■══",
" ║ ",
" cr_1: 0 ══════════o══",
" 0x1 ",
]
)
self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=False)), expected)
def test_text_bit_conditional(self):
"""Test bit conditions on gates"""
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(2, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.h(qr[0]).c_if(cr[0], 1)
circuit.h(qr[1]).c_if(cr[1], 0)
expected = "\n".join(
[
" ┌───┐ ",
"qr_0: |0>┤ H ├─────",
" └─╥─┘┌───┐",
"qr_1: |0>──╫──┤ H ├",
" ║ └─╥─┘",
" cr_0: 0 ══■════╬══",
" ║ ",
" cr_1: 0 ═══════o══",
" ",
]
)
self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=False)), expected)
def test_text_bit_conditional_cregbundle(self):
"""Test bit conditions on gates when cregbundle=True"""
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(2, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.h(qr[0]).c_if(cr[0], 1)
circuit.h(qr[1]).c_if(cr[1], 0)
expected = "\n".join(
[
" ┌───┐ ",
"qr_0: |0>───┤ H ├────────────────",
" └─╥─┘ ┌───┐ ",
"qr_1: |0>─────╫─────────┤ H ├────",
" ║ └─╥─┘ ",
" ┌────╨─────┐┌────╨─────┐",
" cr: 0 2/╡ cr_0=0x1 ╞╡ cr_1=0x0 ╞",
" └──────────┘└──────────┘",
]
)
self.assertEqual(
str(_text_circuit_drawer(circuit, cregbundle=True, vertical_compression="medium")),
expected,
)
def test_text_condition_measure_bits_true(self):
"""Condition and measure on single bits cregbundle true"""
bits = [Qubit(), Qubit(), Clbit(), Clbit()]
cr = ClassicalRegister(2, "cr")
crx = ClassicalRegister(3, "cs")
circuit = QuantumCircuit(bits, cr, [Clbit()], crx)
circuit.x(0).c_if(crx[1], 0)
circuit.measure(0, bits[3])
expected = "\n".join(
[
" ┌───┐ ┌─┐",
" 0: ───┤ X ├────┤M├",
" └─╥─┘ └╥┘",
" 1: ─────╫───────╫─",
" ║ ║ ",
" 0: ═════╬═══════╬═",
" ║ ║ ",
" 1: ═════╬═══════╩═",
" ║ ",
"cr: 2/═════╬═════════",
" ║ ",
" 4: ═════╬═════════",
" ┌────╨─────┐ ",
"cs: 3/╡ cs_1=0x0 ╞═══",
" └──────────┘ ",
]
)
self.assertEqual(
str(_text_circuit_drawer(circuit, cregbundle=True, initial_state=False)), expected
)
def test_text_condition_measure_bits_false(self):
"""Condition and measure on single bits cregbundle false"""
bits = [Qubit(), Qubit(), Clbit(), Clbit()]
cr = ClassicalRegister(2, "cr")
crx = ClassicalRegister(3, "cs")
circuit = QuantumCircuit(bits, cr, [Clbit()], crx)
circuit.x(0).c_if(crx[1], 0)
circuit.measure(0, bits[3])
expected = "\n".join(
[
" ┌───┐┌─┐",
" 0: ┤ X ├┤M├",
" └─╥─┘└╥┘",
" 1: ──╫───╫─",
" ║ ║ ",
" 0: ══╬═══╬═",
" ║ ║ ",
" 1: ══╬═══╩═",
" ║ ",
"cr_0: ══╬═════",
" ║ ",
"cr_1: ══╬═════",
" ║ ",
" 4: ══╬═════",
" ║ ",
"cs_0: ══╬═════",
" ║ ",
"cs_1: ══o═════",
" ",
"cs_2: ════════",
" ",
]
)
self.assertEqual(
str(_text_circuit_drawer(circuit, cregbundle=False, initial_state=False)), expected
)
def test_text_conditional_reverse_bits_1(self):
"""Classical condition on 2q2c circuit with cregbundle=False and reverse bits"""
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(2, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.h(qr[0])
circuit.measure(qr[0], cr[0])
circuit.h(qr[1]).c_if(cr, 1)
expected = "\n".join(
[
" ┌───┐",
"qr_1: |0>────────┤ H ├",
" ┌───┐┌─┐└─╥─┘",
"qr_0: |0>┤ H ├┤M├──╫──",
" └───┘└╥┘ ║ ",
" cr_1: 0 ══════╬═══o══",
" ║ ║ ",
" cr_0: 0 ══════╩═══■══",
" 0x1 ",
]
)
self.assertEqual(
str(_text_circuit_drawer(circuit, cregbundle=False, reverse_bits=True)), expected
)
def test_text_conditional_reverse_bits_2(self):
"""Classical condition on 3q3c circuit with cergbundle=False and reverse bits"""
qr = QuantumRegister(3, "qr")
cr = ClassicalRegister(3, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.h(qr[0]).c_if(cr, 6)
circuit.h(qr[1]).c_if(cr, 1)
circuit.h(qr[2]).c_if(cr, 2)
circuit.cx(0, 1).c_if(cr, 3)
expected = "\n".join(
[
" ┌───┐ ",
"qr_2: |0>──────────┤ H ├─────",
" ┌───┐└─╥─┘┌───┐",
"qr_1: |0>─────┤ H ├──╫──┤ X ├",
" ┌───┐└─╥─┘ ║ └─┬─┘",
"qr_0: |0>┤ H ├──╫────╫────■──",
" └─╥─┘ ║ ║ ║ ",
" cr_2: 0 ══■════o════o════o══",
" ║ ║ ║ ║ ",
" cr_1: 0 ══■════o════■════■══",
" ║ ║ ║ ║ ",
" cr_0: 0 ══o════■════o════■══",
" 0x6 0x1 0x2 0x3 ",
]
)
self.assertEqual(
str(_text_circuit_drawer(circuit, cregbundle=False, reverse_bits=True)), expected
)
def test_text_condition_bits_reverse(self):
"""Condition and measure on single bits cregbundle true and reverse_bits true"""
bits = [Qubit(), Qubit(), Clbit(), Clbit()]
cr = ClassicalRegister(2, "cr")
crx = ClassicalRegister(3, "cs")
circuit = QuantumCircuit(bits, cr, [Clbit()], crx)
circuit.x(0).c_if(bits[3], 0)
expected = "\n".join(
[
" ",
" 1: ─────",
" ┌───┐",
" 0: ┤ X ├",
" └─╥─┘",
"cs: 3/══╬══",
" ║ ",
" 4: ══╬══",
" ║ ",
"cr: 2/══╬══",
" ║ ",
" 1: ══o══",
" ",
" 0: ═════",
" ",
]
)
self.assertEqual(
str(
_text_circuit_drawer(
circuit, cregbundle=True, initial_state=False, reverse_bits=True
)
),
expected,
)
class TestTextIdleWires(QiskitTestCase):
"""The idle_wires option"""
def test_text_h(self):
"""Remove QuWires."""
# fmt: off
expected = "\n".join([" ┌───┐",
"q1_1: |0>┤ H ├",
" └───┘"])
# fmt: on
qr1 = QuantumRegister(3, "q1")
circuit = QuantumCircuit(qr1)
circuit.h(qr1[1])
self.assertEqual(str(_text_circuit_drawer(circuit, idle_wires=False)), expected)
def test_text_measure(self):
"""Remove QuWires and ClWires."""
expected = "\n".join(
[
" ┌─┐ ",
"q2_0: |0>┤M├───",
" └╥┘┌─┐",
"q2_1: |0>─╫─┤M├",
" ║ └╥┘",
" c2: 0 2/═╩══╩═",
" 0 1 ",
]
)
qr1 = QuantumRegister(2, "q1")
cr1 = ClassicalRegister(2, "c1")
qr2 = QuantumRegister(2, "q2")
cr2 = ClassicalRegister(2, "c2")
circuit = QuantumCircuit(qr1, qr2, cr1, cr2)
circuit.measure(qr2, cr2)
self.assertEqual(str(_text_circuit_drawer(circuit, idle_wires=False)), expected)
def test_text_empty_circuit(self):
"""Remove everything in an empty circuit."""
expected = ""
circuit = QuantumCircuit()
self.assertEqual(str(_text_circuit_drawer(circuit, idle_wires=False)), expected)
def test_text_barrier(self):
"""idle_wires should ignore barrier
See https://github.com/Qiskit/qiskit-terra/issues/4391"""
# fmt: off
expected = "\n".join([" ┌───┐ ░ ",
"qr_1: |0>┤ H ├─░─",
" └───┘ ░ "])
# fmt: on
qr = QuantumRegister(3, "qr")
circuit = QuantumCircuit(qr)
circuit.h(qr[1])
circuit.barrier(qr[1], qr[2])
self.assertEqual(str(_text_circuit_drawer(circuit, idle_wires=False)), expected)
def test_text_barrier_delay(self):
"""idle_wires should ignore delay"""
# fmt: off
expected = "\n".join([" ┌───┐ ░ ",
"qr_1: |0>┤ H ├─░──",
" └───┘ ░ "])
# fmt: on
qr = QuantumRegister(4, "qr")
circuit = QuantumCircuit(qr)
circuit.h(qr[1])
circuit.barrier()
circuit.delay(100, qr[2])
self.assertEqual(str(_text_circuit_drawer(circuit, idle_wires=False)), expected)
def test_does_not_mutate_circuit(self):
"""Using 'idle_wires=False' should not mutate the circuit. Regression test of gh-8739."""
circuit = QuantumCircuit(1)
before_qubits = circuit.num_qubits
circuit.draw(idle_wires=False)
self.assertEqual(circuit.num_qubits, before_qubits)
class TestTextNonRational(QiskitTestCase):
"""non-rational numbers are correctly represented"""
def test_text_pifrac(self):
"""u drawing with -5pi/8 fraction"""
# fmt: off
expected = "\n".join(
[" ┌──────────────┐",
"q: |0>┤ U(π,-5π/8,0) ├",
" └──────────────┘"]
)
# fmt: on
qr = QuantumRegister(1, "q")
circuit = QuantumCircuit(qr)
circuit.u(pi, -5 * pi / 8, 0, qr[0])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_text_complex(self):
"""Complex numbers show up in the text
See https://github.com/Qiskit/qiskit-terra/issues/3640"""
expected = "\n".join(
[
" ┌────────────────────────────────────┐",
"q_0: ┤0 ├",
" │ Initialize(0.5+0.1j,0,0,0.86023j) │",
"q_1: ┤1 ├",
" └────────────────────────────────────┘",
]
)
ket = numpy.array([0.5 + 0.1 * 1j, 0, 0, 0.8602325267042626 * 1j])
circuit = QuantumCircuit(2)
circuit.initialize(ket, [0, 1])
self.assertEqual(circuit.draw(output="text").single_string(), expected)
def test_text_complex_pireal(self):
"""Complex numbers including pi show up in the text
See https://github.com/Qiskit/qiskit-terra/issues/3640"""
expected = "\n".join(
[
" ┌────────────────────────────────┐",
"q_0: |0>┤0 ├",
" │ Initialize(π/10,0,0,0.94937j) │",
"q_1: |0>┤1 ├",
" └────────────────────────────────┘",
]
)
ket = numpy.array([0.1 * numpy.pi, 0, 0, 0.9493702944526474 * 1j])
circuit = QuantumCircuit(2)
circuit.initialize(ket, [0, 1])
self.assertEqual(circuit.draw(output="text", initial_state=True).single_string(), expected)
def test_text_complex_piimaginary(self):
"""Complex numbers including pi show up in the text
See https://github.com/Qiskit/qiskit-terra/issues/3640"""
expected = "\n".join(
[
" ┌────────────────────────────────┐",
"q_0: |0>┤0 ├",
" │ Initialize(0.94937,0,0,π/10j) │",
"q_1: |0>┤1 ├",
" └────────────────────────────────┘",
]
)
ket = numpy.array([0.9493702944526474, 0, 0, 0.1 * numpy.pi * 1j])
circuit = QuantumCircuit(2)
circuit.initialize(ket, [0, 1])
self.assertEqual(circuit.draw(output="text", initial_state=True).single_string(), expected)
class TestTextInstructionWithBothWires(QiskitTestCase):
"""Composite instructions with both kind of wires
See https://github.com/Qiskit/qiskit-terra/issues/2973"""
def test_text_all_1q_1c(self):
"""Test q0-c0 in q0-c0"""
expected = "\n".join(
[
" ┌───────┐",
"qr: |0>┤0 ├",
" │ name │",
" cr: 0 ╡0 ╞",
" └───────┘",
]
)
qr1 = QuantumRegister(1, "qr")
cr1 = ClassicalRegister(1, "cr")
inst = QuantumCircuit(qr1, cr1, name="name").to_instruction()
circuit = QuantumCircuit(qr1, cr1)
circuit.append(inst, qr1[:], cr1[:])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_text_all_2q_2c(self):
"""Test q0-q1-c0-c1 in q0-q1-c0-c1"""
expected = "\n".join(
[
" ┌───────┐",
"qr_0: |0>┤0 ├",
" │ │",
"qr_1: |0>┤1 ├",
" │ name │",
" cr_0: 0 ╡0 ╞",
" │ │",
" cr_1: 0 ╡1 ╞",
" └───────┘",
]
)
qr2 = QuantumRegister(2, "qr")
cr2 = ClassicalRegister(2, "cr")
inst = QuantumCircuit(qr2, cr2, name="name").to_instruction()
circuit = QuantumCircuit(qr2, cr2)
circuit.append(inst, qr2[:], cr2[:])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_text_all_2q_2c_cregbundle(self):
"""Test q0-q1-c0-c1 in q0-q1-c0-c1. Ignore cregbundle=True"""
expected = "\n".join(
[
" ┌───────┐",
"qr_0: |0>┤0 ├",
" │ │",
"qr_1: |0>┤1 ├",
" │ name │",
" cr_0: 0 ╡0 ╞",
" │ │",
" cr_1: 0 ╡1 ╞",
" └───────┘",
]
)
qr2 = QuantumRegister(2, "qr")
cr2 = ClassicalRegister(2, "cr")
inst = QuantumCircuit(qr2, cr2, name="name").to_instruction()
circuit = QuantumCircuit(qr2, cr2)
circuit.append(inst, qr2[:], cr2[:])
with self.assertWarns(RuntimeWarning):
self.assertEqual(str(_text_circuit_drawer(circuit, cregbundle=True)), expected)
def test_text_4q_2c(self):
"""Test q1-q2-q3-q4-c1-c2 in q0-q1-q2-q3-q4-q5-c0-c1-c2-c3-c4-c5"""
expected = "\n".join(
[
" ",
"q_0: |0>─────────",
" ┌───────┐",
"q_1: |0>┤0 ├",
" │ │",
"q_2: |0>┤1 ├",
" │ │",
"q_3: |0>┤2 ├",
" │ │",
"q_4: |0>┤3 ├",
" │ name │",
"q_5: |0>┤ ├",
" │ │",
" c_0: 0 ╡ ╞",
" │ │",
" c_1: 0 ╡0 ╞",
" │ │",
" c_2: 0 ╡1 ╞",
" └───────┘",
" c_3: 0 ═════════",
" ",
" c_4: 0 ═════════",
" ",
" c_5: 0 ═════════",
" ",
]
)
qr4 = QuantumRegister(4)
cr4 = ClassicalRegister(2)
inst = QuantumCircuit(qr4, cr4, name="name").to_instruction()
qr6 = QuantumRegister(6, "q")
cr6 = ClassicalRegister(6, "c")
circuit = QuantumCircuit(qr6, cr6)
circuit.append(inst, qr6[1:5], cr6[1:3])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_text_2q_1c(self):
"""Test q0-c0 in q0-q1-c0
See https://github.com/Qiskit/qiskit-terra/issues/4066"""
expected = "\n".join(
[
" ┌───────┐",
"q_0: |0>┤0 ├",
" │ │",
"q_1: |0>┤ Name ├",
" │ │",
" c: 0 ╡0 ╞",
" └───────┘",
]
)
qr = QuantumRegister(2, name="q")
cr = ClassicalRegister(1, name="c")
circuit = QuantumCircuit(qr, cr)
inst = QuantumCircuit(1, 1, name="Name").to_instruction()
circuit.append(inst, [qr[0]], [cr[0]])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_text_3q_3c_qlabels_inverted(self):
"""Test q3-q0-q1-c0-c1-c_10 in q0-q1-q2-q3-c0-c1-c2-c_10-c_11
See https://github.com/Qiskit/qiskit-terra/issues/6178"""
expected = "\n".join(
[
" ┌───────┐",
"q_0: |0>┤1 ├",
" │ │",
"q_1: |0>┤2 ├",
" │ │",
"q_2: |0>┤ ├",
" │ │",
"q_3: |0>┤0 ├",
" │ Name │",
" c_0: 0 ╡0 ╞",
" │ │",
" c_1: 0 ╡1 ╞",
" │ │",
" c_2: 0 ╡ ╞",
" │ │",
"c1_0: 0 ╡2 ╞",
" └───────┘",
"c1_1: 0 ═════════",
" ",
]
)
qr = QuantumRegister(4, name="q")
cr = ClassicalRegister(3, name="c")
cr1 = ClassicalRegister(2, name="c1")
circuit = QuantumCircuit(qr, cr, cr1)
inst = QuantumCircuit(3, 3, name="Name").to_instruction()
circuit.append(inst, [qr[3], qr[0], qr[1]], [cr[0], cr[1], cr1[0]])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_text_3q_3c_clabels_inverted(self):
"""Test q0-q1-q3-c_11-c0-c_10 in q0-q1-q2-q3-c0-c1-c2-c_10-c_11
See https://github.com/Qiskit/qiskit-terra/issues/6178"""
expected = "\n".join(
[
" ┌───────┐",
"q_0: |0>┤0 ├",
" │ │",
"q_1: |0>┤1 ├",
" │ │",
"q_2: |0>┤ ├",
" │ │",
"q_3: |0>┤2 ├",
" │ │",
" c_0: 0 ╡1 Name ╞",
" │ │",
" c_1: 0 ╡ ╞",
" │ │",
" c_2: 0 ╡ ╞",
" │ │",
"c1_0: 0 ╡2 ╞",
" │ │",
"c1_1: 0 ╡0 ╞",
" └───────┘",
]
)
qr = QuantumRegister(4, name="q")
cr = ClassicalRegister(3, name="c")
cr1 = ClassicalRegister(2, name="c1")
circuit = QuantumCircuit(qr, cr, cr1)
inst = QuantumCircuit(3, 3, name="Name").to_instruction()
circuit.append(inst, [qr[0], qr[1], qr[3]], [cr1[1], cr[0], cr1[0]])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_text_3q_3c_qclabels_inverted(self):
"""Test q3-q1-q2-c_11-c0-c_10 in q0-q1-q2-q3-c0-c1-c2-c_10-c_11
See https://github.com/Qiskit/qiskit-terra/issues/6178"""
expected = "\n".join(
[
" ",
"q_0: |0>─────────",
" ┌───────┐",
"q_1: |0>┤1 ├",
" │ │",
"q_2: |0>┤2 ├",
" │ │",
"q_3: |0>┤0 ├",
" │ │",
" c_0: 0 ╡1 ╞",
" │ Name │",
" c_1: 0 ╡ ╞",
" │ │",
" c_2: 0 ╡ ╞",
" │ │",
"c1_0: 0 ╡2 ╞",
" │ │",
"c1_1: 0 ╡0 ╞",
" └───────┘",
]
)
qr = QuantumRegister(4, name="q")
cr = ClassicalRegister(3, name="c")
cr1 = ClassicalRegister(2, name="c1")
circuit = QuantumCircuit(qr, cr, cr1)
inst = QuantumCircuit(3, 3, name="Name").to_instruction()
circuit.append(inst, [qr[3], qr[1], qr[2]], [cr1[1], cr[0], cr1[0]])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
class TestTextDrawerAppendedLargeInstructions(QiskitTestCase):
"""Composite instructions with more than 10 qubits
See https://github.com/Qiskit/qiskit-terra/pull/4095"""
def test_text_11q(self):
"""Test q0-...-q10 in q0-...-q10"""
expected = "\n".join(
[
" ┌────────┐",
" q_0: |0>┤0 ├",
" │ │",
" q_1: |0>┤1 ├",
" │ │",
" q_2: |0>┤2 ├",
" │ │",
" q_3: |0>┤3 ├",
" │ │",
" q_4: |0>┤4 ├",
" │ │",
" q_5: |0>┤5 Name ├",
" │ │",
" q_6: |0>┤6 ├",
" │ │",
" q_7: |0>┤7 ├",
" │ │",
" q_8: |0>┤8 ├",
" │ │",
" q_9: |0>┤9 ├",
" │ │",
"q_10: |0>┤10 ├",
" └────────┘",
]
)
qr = QuantumRegister(11, "q")
circuit = QuantumCircuit(qr)
inst = QuantumCircuit(11, name="Name").to_instruction()
circuit.append(inst, qr)
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_text_11q_1c(self):
"""Test q0-...-q10-c0 in q0-...-q10-c0"""
expected = "\n".join(
[
" ┌────────┐",
" q_0: |0>┤0 ├",
" │ │",
" q_1: |0>┤1 ├",
" │ │",
" q_2: |0>┤2 ├",
" │ │",
" q_3: |0>┤3 ├",
" │ │",
" q_4: |0>┤4 ├",
" │ │",
" q_5: |0>┤5 ├",
" │ Name │",
" q_6: |0>┤6 ├",
" │ │",
" q_7: |0>┤7 ├",
" │ │",
" q_8: |0>┤8 ├",
" │ │",
" q_9: |0>┤9 ├",
" │ │",
"q_10: |0>┤10 ├",
" │ │",
" c: 0 ╡0 ╞",
" └────────┘",
]
)
qr = QuantumRegister(11, "q")
cr = ClassicalRegister(1, "c")
circuit = QuantumCircuit(qr, cr)
inst = QuantumCircuit(11, 1, name="Name").to_instruction()
circuit.append(inst, qr, cr)
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
class TestTextControlledGate(QiskitTestCase):
"""Test controlled gates"""
def test_cch_bot(self):
"""Controlled CH (bottom)"""
expected = "\n".join(
[
" ",
"q_0: |0>──■──",
" │ ",
"q_1: |0>──■──",
" ┌─┴─┐",
"q_2: |0>┤ H ├",
" └───┘",
]
)
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
circuit.append(HGate().control(2), [qr[0], qr[1], qr[2]])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_cch_mid(self):
"""Controlled CH (middle)"""
expected = "\n".join(
[
" ",
"q_0: |0>──■──",
" ┌─┴─┐",
"q_1: |0>┤ H ├",
" └─┬─┘",
"q_2: |0>──■──",
" ",
]
)
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
circuit.append(HGate().control(2), [qr[0], qr[2], qr[1]])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_cch_top(self):
"""Controlled CH"""
expected = "\n".join(
[
" ┌───┐",
"q_0: |0>┤ H ├",
" └─┬─┘",
"q_1: |0>──■──",
" │ ",
"q_2: |0>──■──",
" ",
]
)
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
circuit.append(HGate().control(2), [qr[2], qr[1], qr[0]])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_c3h(self):
"""Controlled Controlled CH"""
expected = "\n".join(
[
" ",
"q_0: |0>──■──",
" │ ",
"q_1: |0>──■──",
" │ ",
"q_2: |0>──■──",
" ┌─┴─┐",
"q_3: |0>┤ H ├",
" └───┘",
]
)
qr = QuantumRegister(4, "q")
circuit = QuantumCircuit(qr)
circuit.append(HGate().control(3), [qr[0], qr[1], qr[2], qr[3]])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_c3h_middle(self):
"""Controlled Controlled CH (middle)"""
expected = "\n".join(
[
" ",
"q_0: |0>──■──",
" ┌─┴─┐",
"q_1: |0>┤ H ├",
" └─┬─┘",
"q_2: |0>──■──",
" │ ",
"q_3: |0>──■──",
" ",
]
)
qr = QuantumRegister(4, "q")
circuit = QuantumCircuit(qr)
circuit.append(HGate().control(3), [qr[0], qr[3], qr[2], qr[1]])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_c3u2(self):
"""Controlled Controlled U2"""
expected = "\n".join(
[
" ",
"q_0: |0>───────■───────",
" ┌──────┴──────┐",
"q_1: |0>┤ U2(π,-5π/8) ├",
" └──────┬──────┘",
"q_2: |0>───────■───────",
" │ ",
"q_3: |0>───────■───────",
" ",
]
)
qr = QuantumRegister(4, "q")
circuit = QuantumCircuit(qr)
circuit.append(U2Gate(pi, -5 * pi / 8).control(3), [qr[0], qr[3], qr[2], qr[1]])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_controlled_composite_gate_edge(self):
"""Controlled composite gates (edge)
See: https://github.com/Qiskit/qiskit-terra/issues/3546"""
expected = "\n".join(
[
" ┌──────┐",
"q_0: |0>┤0 ├",
" │ │",
"q_1: |0>■ ├",
" │ ghz │",
"q_2: |0>┤1 ├",
" │ │",
"q_3: |0>┤2 ├",
" └──────┘",
]
)
ghz_circuit = QuantumCircuit(3, name="ghz")
ghz_circuit.h(0)
ghz_circuit.cx(0, 1)
ghz_circuit.cx(1, 2)
ghz = ghz_circuit.to_gate()
cghz = ghz.control(1)
circuit = QuantumCircuit(4)
circuit.append(cghz, [1, 0, 2, 3])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_controlled_composite_gate_top(self):
"""Controlled composite gates (top)"""
expected = "\n".join(
[
" ",
"q_0: |0>───■────",
" ┌──┴───┐",
"q_1: |0>┤0 ├",
" │ │",
"q_2: |0>┤2 ghz ├",
" │ │",
"q_3: |0>┤1 ├",
" └──────┘",
]
)
ghz_circuit = QuantumCircuit(3, name="ghz")
ghz_circuit.h(0)
ghz_circuit.cx(0, 1)
ghz_circuit.cx(1, 2)
ghz = ghz_circuit.to_gate()
cghz = ghz.control(1)
circuit = QuantumCircuit(4)
circuit.append(cghz, [0, 1, 3, 2])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_controlled_composite_gate_bot(self):
"""Controlled composite gates (bottom)"""
expected = "\n".join(
[
" ┌──────┐",
"q_0: |0>┤1 ├",
" │ │",
"q_1: |0>┤0 ghz ├",
" │ │",
"q_2: |0>┤2 ├",
" └──┬───┘",
"q_3: |0>───■────",
" ",
]
)
ghz_circuit = QuantumCircuit(3, name="ghz")
ghz_circuit.h(0)
ghz_circuit.cx(0, 1)
ghz_circuit.cx(1, 2)
ghz = ghz_circuit.to_gate()
cghz = ghz.control(1)
circuit = QuantumCircuit(4)
circuit.append(cghz, [3, 1, 0, 2])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_controlled_composite_gate_top_bot(self):
"""Controlled composite gates (top and bottom)"""
expected = "\n".join(
[
" ",
"q_0: |0>───■────",
" ┌──┴───┐",
"q_1: |0>┤0 ├",
" │ │",
"q_2: |0>┤1 ghz ├",
" │ │",
"q_3: |0>┤2 ├",
" └──┬───┘",
"q_4: |0>───■────",
" ",
]
)
ghz_circuit = QuantumCircuit(3, name="ghz")
ghz_circuit.h(0)
ghz_circuit.cx(0, 1)
ghz_circuit.cx(1, 2)
ghz = ghz_circuit.to_gate()
ccghz = ghz.control(2)
circuit = QuantumCircuit(5)
circuit.append(ccghz, [4, 0, 1, 2, 3])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_controlled_composite_gate_all(self):
"""Controlled composite gates (top, bot, and edge)"""
expected = "\n".join(
[
" ",
"q_0: |0>───■────",
" ┌──┴───┐",
"q_1: |0>┤0 ├",
" │ │",
"q_2: |0>■ ├",
" │ ghz │",
"q_3: |0>┤1 ├",
" │ │",
"q_4: |0>┤2 ├",
" └──┬───┘",
"q_5: |0>───■────",
" ",
]
)
ghz_circuit = QuantumCircuit(3, name="ghz")
ghz_circuit.h(0)
ghz_circuit.cx(0, 1)
ghz_circuit.cx(1, 2)
ghz = ghz_circuit.to_gate()
ccghz = ghz.control(3)
circuit = QuantumCircuit(6)
circuit.append(ccghz, [0, 2, 5, 1, 3, 4])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_controlled_composite_gate_even_label(self):
"""Controlled composite gates (top and bottom) with a even label length"""
expected = "\n".join(
[
" ",
"q_0: |0>────■────",
" ┌───┴───┐",
"q_1: |0>┤0 ├",
" │ │",
"q_2: |0>┤1 cghz ├",
" │ │",
"q_3: |0>┤2 ├",
" └───┬───┘",
"q_4: |0>────■────",
" ",
]
)
ghz_circuit = QuantumCircuit(3, name="cghz")
ghz_circuit.h(0)
ghz_circuit.cx(0, 1)
ghz_circuit.cx(1, 2)
ghz = ghz_circuit.to_gate()
ccghz = ghz.control(2)
circuit = QuantumCircuit(5)
circuit.append(ccghz, [4, 0, 1, 2, 3])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
class TestTextOpenControlledGate(QiskitTestCase):
"""Test open controlled gates"""
def test_ch_bot(self):
"""Open controlled H (bottom)"""
# fmt: off
expected = "\n".join(
[" ",
"q_0: |0>──o──",
" ┌─┴─┐",
"q_1: |0>┤ H ├",
" └───┘"]
)
# fmt: on
qr = QuantumRegister(2, "q")
circuit = QuantumCircuit(qr)
circuit.append(HGate().control(1, ctrl_state=0), [qr[0], qr[1]])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_cz_bot(self):
"""Open controlled Z (bottom)"""
# fmt: off
expected = "\n".join([" ",
"q_0: |0>─o─",
" │ ",
"q_1: |0>─■─",
" "])
# fmt: on
qr = QuantumRegister(2, "q")
circuit = QuantumCircuit(qr)
circuit.append(ZGate().control(1, ctrl_state=0), [qr[0], qr[1]])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_ccz_bot(self):
"""Closed-Open controlled Z (bottom)"""
expected = "\n".join(
[
" ",
"q_0: |0>─■─",
" │ ",
"q_1: |0>─o─",
" │ ",
"q_2: |0>─■─",
" ",
]
)
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
circuit.append(ZGate().control(2, ctrl_state="01"), [qr[0], qr[1], qr[2]])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_cccz_conditional(self):
"""Closed-Open controlled Z (with conditional)"""
expected = "\n".join(
[
" ",
"q_0: |0>───■───",
" │ ",
"q_1: |0>───o───",
" │ ",
"q_2: |0>───■───",
" │ ",
"q_3: |0>───■───",
" ┌──╨──┐",
" c: 0 1/╡ 0x1 ╞",
" └─────┘",
]
)
qr = QuantumRegister(4, "q")
cr = ClassicalRegister(1, "c")
circuit = QuantumCircuit(qr, cr)
circuit.append(
ZGate().control(3, ctrl_state="101").c_if(cr, 1), [qr[0], qr[1], qr[2], qr[3]]
)
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_cch_bot(self):
"""Controlled CH (bottom)"""
expected = "\n".join(
[
" ",
"q_0: |0>──o──",
" │ ",
"q_1: |0>──■──",
" ┌─┴─┐",
"q_2: |0>┤ H ├",
" └───┘",
]
)
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
circuit.append(HGate().control(2, ctrl_state="10"), [qr[0], qr[1], qr[2]])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_cch_mid(self):
"""Controlled CH (middle)"""
expected = "\n".join(
[
" ",
"q_0: |0>──o──",
" ┌─┴─┐",
"q_1: |0>┤ H ├",
" └─┬─┘",
"q_2: |0>──■──",
" ",
]
)
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
circuit.append(HGate().control(2, ctrl_state="10"), [qr[0], qr[2], qr[1]])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_cch_top(self):
"""Controlled CH"""
expected = "\n".join(
[
" ┌───┐",
"q_0: |0>┤ H ├",
" └─┬─┘",
"q_1: |0>──o──",
" │ ",
"q_2: |0>──■──",
" ",
]
)
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
circuit.append(HGate().control(2, ctrl_state="10"), [qr[1], qr[2], qr[0]])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_c3h(self):
"""Controlled Controlled CH"""
expected = "\n".join(
[
" ",
"q_0: |0>──o──",
" │ ",
"q_1: |0>──o──",
" │ ",
"q_2: |0>──■──",
" ┌─┴─┐",
"q_3: |0>┤ H ├",
" └───┘",
]
)
qr = QuantumRegister(4, "q")
circuit = QuantumCircuit(qr)
circuit.append(HGate().control(3, ctrl_state="100"), [qr[0], qr[1], qr[2], qr[3]])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_c3h_middle(self):
"""Controlled Controlled CH (middle)"""
expected = "\n".join(
[
" ",
"q_0: |0>──o──",
" ┌─┴─┐",
"q_1: |0>┤ H ├",
" └─┬─┘",
"q_2: |0>──o──",
" │ ",
"q_3: |0>──■──",
" ",
]
)
qr = QuantumRegister(4, "q")
circuit = QuantumCircuit(qr)
circuit.append(HGate().control(3, ctrl_state="010"), [qr[0], qr[3], qr[2], qr[1]])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_c3u2(self):
"""Controlled Controlled U2"""
expected = "\n".join(
[
" ",
"q_0: |0>───────o───────",
" ┌──────┴──────┐",
"q_1: |0>┤ U2(π,-5π/8) ├",
" └──────┬──────┘",
"q_2: |0>───────■───────",
" │ ",
"q_3: |0>───────o───────",
" ",
]
)
qr = QuantumRegister(4, "q")
circuit = QuantumCircuit(qr)
circuit.append(
U2Gate(pi, -5 * pi / 8).control(3, ctrl_state="100"), [qr[0], qr[3], qr[2], qr[1]]
)
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_controlled_composite_gate_edge(self):
"""Controlled composite gates (edge)
See: https://github.com/Qiskit/qiskit-terra/issues/3546"""
expected = "\n".join(
[
" ┌──────┐",
"q_0: |0>┤0 ├",
" │ │",
"q_1: |0>o ├",
" │ ghz │",
"q_2: |0>┤1 ├",
" │ │",
"q_3: |0>┤2 ├",
" └──────┘",
]
)
ghz_circuit = QuantumCircuit(3, name="ghz")
ghz_circuit.h(0)
ghz_circuit.cx(0, 1)
ghz_circuit.cx(1, 2)
ghz = ghz_circuit.to_gate()
cghz = ghz.control(1, ctrl_state="0")
circuit = QuantumCircuit(4)
circuit.append(cghz, [1, 0, 2, 3])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_controlled_composite_gate_top(self):
"""Controlled composite gates (top)"""
expected = "\n".join(
[
" ",
"q_0: |0>───o────",
" ┌──┴───┐",
"q_1: |0>┤0 ├",
" │ │",
"q_2: |0>┤2 ghz ├",
" │ │",
"q_3: |0>┤1 ├",
" └──────┘",
]
)
ghz_circuit = QuantumCircuit(3, name="ghz")
ghz_circuit.h(0)
ghz_circuit.cx(0, 1)
ghz_circuit.cx(1, 2)
ghz = ghz_circuit.to_gate()
cghz = ghz.control(1, ctrl_state="0")
circuit = QuantumCircuit(4)
circuit.append(cghz, [0, 1, 3, 2])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_controlled_composite_gate_bot(self):
"""Controlled composite gates (bottom)"""
expected = "\n".join(
[
" ┌──────┐",
"q_0: |0>┤1 ├",
" │ │",
"q_1: |0>┤0 ghz ├",
" │ │",
"q_2: |0>┤2 ├",
" └──┬───┘",
"q_3: |0>───o────",
" ",
]
)
ghz_circuit = QuantumCircuit(3, name="ghz")
ghz_circuit.h(0)
ghz_circuit.cx(0, 1)
ghz_circuit.cx(1, 2)
ghz = ghz_circuit.to_gate()
cghz = ghz.control(1, ctrl_state="0")
circuit = QuantumCircuit(4)
circuit.append(cghz, [3, 1, 0, 2])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_controlled_composite_gate_top_bot(self):
"""Controlled composite gates (top and bottom)"""
expected = "\n".join(
[
" ",
"q_0: |0>───o────",
" ┌──┴───┐",
"q_1: |0>┤0 ├",
" │ │",
"q_2: |0>┤1 ghz ├",
" │ │",
"q_3: |0>┤2 ├",
" └──┬───┘",
"q_4: |0>───■────",
" ",
]
)
ghz_circuit = QuantumCircuit(3, name="ghz")
ghz_circuit.h(0)
ghz_circuit.cx(0, 1)
ghz_circuit.cx(1, 2)
ghz = ghz_circuit.to_gate()
ccghz = ghz.control(2, ctrl_state="01")
circuit = QuantumCircuit(5)
circuit.append(ccghz, [4, 0, 1, 2, 3])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_controlled_composite_gate_all(self):
"""Controlled composite gates (top, bot, and edge)"""
expected = "\n".join(
[
" ",
"q_0: |0>───o────",
" ┌──┴───┐",
"q_1: |0>┤0 ├",
" │ │",
"q_2: |0>o ├",
" │ ghz │",
"q_3: |0>┤1 ├",
" │ │",
"q_4: |0>┤2 ├",
" └──┬───┘",
"q_5: |0>───o────",
" ",
]
)
ghz_circuit = QuantumCircuit(3, name="ghz")
ghz_circuit.h(0)
ghz_circuit.cx(0, 1)
ghz_circuit.cx(1, 2)
ghz = ghz_circuit.to_gate()
ccghz = ghz.control(3, ctrl_state="000")
circuit = QuantumCircuit(6)
circuit.append(ccghz, [0, 2, 5, 1, 3, 4])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_open_controlled_x(self):
"""Controlled X gates.
See https://github.com/Qiskit/qiskit-terra/issues/4180"""
expected = "\n".join(
[
" ",
"qr_0: |0>──o────o────o────o────■──",
" ┌─┴─┐ │ │ │ │ ",
"qr_1: |0>┤ X ├──o────■────■────o──",
" └───┘┌─┴─┐┌─┴─┐ │ │ ",
"qr_2: |0>─────┤ X ├┤ X ├──o────o──",
" └───┘└───┘┌─┴─┐┌─┴─┐",
"qr_3: |0>───────────────┤ X ├┤ X ├",
" └───┘└─┬─┘",
"qr_4: |0>──────────────────────■──",
" ",
]
)
qreg = QuantumRegister(5, "qr")
circuit = QuantumCircuit(qreg)
control1 = XGate().control(1, ctrl_state="0")
circuit.append(control1, [0, 1])
control2 = XGate().control(2, ctrl_state="00")
circuit.append(control2, [0, 1, 2])
control2_2 = XGate().control(2, ctrl_state="10")
circuit.append(control2_2, [0, 1, 2])
control3 = XGate().control(3, ctrl_state="010")
circuit.append(control3, [0, 1, 2, 3])
control3 = XGate().control(4, ctrl_state="0101")
circuit.append(control3, [0, 1, 4, 2, 3])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_open_controlled_y(self):
"""Controlled Y gates.
See https://github.com/Qiskit/qiskit-terra/issues/4180"""
expected = "\n".join(
[
" ",
"qr_0: |0>──o────o────o────o────■──",
" ┌─┴─┐ │ │ │ │ ",
"qr_1: |0>┤ Y ├──o────■────■────o──",
" └───┘┌─┴─┐┌─┴─┐ │ │ ",
"qr_2: |0>─────┤ Y ├┤ Y ├──o────o──",
" └───┘└───┘┌─┴─┐┌─┴─┐",
"qr_3: |0>───────────────┤ Y ├┤ Y ├",
" └───┘└─┬─┘",
"qr_4: |0>──────────────────────■──",
" ",
]
)
qreg = QuantumRegister(5, "qr")
circuit = QuantumCircuit(qreg)
control1 = YGate().control(1, ctrl_state="0")
circuit.append(control1, [0, 1])
control2 = YGate().control(2, ctrl_state="00")
circuit.append(control2, [0, 1, 2])
control2_2 = YGate().control(2, ctrl_state="10")
circuit.append(control2_2, [0, 1, 2])
control3 = YGate().control(3, ctrl_state="010")
circuit.append(control3, [0, 1, 2, 3])
control3 = YGate().control(4, ctrl_state="0101")
circuit.append(control3, [0, 1, 4, 2, 3])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_open_controlled_z(self):
"""Controlled Z gates."""
expected = "\n".join(
[
" ",
"qr_0: |0>─o──o──o──o──■─",
" │ │ │ │ │ ",
"qr_1: |0>─■──o──■──■──o─",
" │ │ │ │ ",
"qr_2: |0>────■──■──o──o─",
" │ │ ",
"qr_3: |0>──────────■──■─",
" │ ",
"qr_4: |0>─────────────■─",
" ",
]
)
qreg = QuantumRegister(5, "qr")
circuit = QuantumCircuit(qreg)
control1 = ZGate().control(1, ctrl_state="0")
circuit.append(control1, [0, 1])
control2 = ZGate().control(2, ctrl_state="00")
circuit.append(control2, [0, 1, 2])
control2_2 = ZGate().control(2, ctrl_state="10")
circuit.append(control2_2, [0, 1, 2])
control3 = ZGate().control(3, ctrl_state="010")
circuit.append(control3, [0, 1, 2, 3])
control3 = ZGate().control(4, ctrl_state="0101")
circuit.append(control3, [0, 1, 4, 2, 3])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_open_controlled_u1(self):
"""Controlled U1 gates."""
expected = "\n".join(
[
" ",
"qr_0: |0>─o─────────o─────────o─────────o─────────■────────",
" │U1(0.1) │ │ │ │ ",
"qr_1: |0>─■─────────o─────────■─────────■─────────o────────",
" │U1(0.2) │U1(0.3) │ │ ",
"qr_2: |0>───────────■─────────■─────────o─────────o────────",
" │U1(0.4) │ ",
"qr_3: |0>───────────────────────────────■─────────■────────",
" │U1(0.5) ",
"qr_4: |0>─────────────────────────────────────────■────────",
" ",
]
)
qreg = QuantumRegister(5, "qr")
circuit = QuantumCircuit(qreg)
control1 = U1Gate(0.1).control(1, ctrl_state="0")
circuit.append(control1, [0, 1])
control2 = U1Gate(0.2).control(2, ctrl_state="00")
circuit.append(control2, [0, 1, 2])
control2_2 = U1Gate(0.3).control(2, ctrl_state="10")
circuit.append(control2_2, [0, 1, 2])
control3 = U1Gate(0.4).control(3, ctrl_state="010")
circuit.append(control3, [0, 1, 2, 3])
control3 = U1Gate(0.5).control(4, ctrl_state="0101")
circuit.append(control3, [0, 1, 4, 2, 3])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_open_controlled_swap(self):
"""Controlled SWAP gates."""
expected = "\n".join(
[
" ",
"qr_0: |0>─o──o──o──o─",
" │ │ │ │ ",
"qr_1: |0>─X──o──■──■─",
" │ │ │ │ ",
"qr_2: |0>─X──X──X──o─",
" │ │ │ ",
"qr_3: |0>────X──X──X─",
" │ ",
"qr_4: |0>──────────X─",
" ",
]
)
qreg = QuantumRegister(5, "qr")
circuit = QuantumCircuit(qreg)
control1 = SwapGate().control(1, ctrl_state="0")
circuit.append(control1, [0, 1, 2])
control2 = SwapGate().control(2, ctrl_state="00")
circuit.append(control2, [0, 1, 2, 3])
control2_2 = SwapGate().control(2, ctrl_state="10")
circuit.append(control2_2, [0, 1, 2, 3])
control3 = SwapGate().control(3, ctrl_state="010")
circuit.append(control3, [0, 1, 2, 3, 4])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_open_controlled_rzz(self):
"""Controlled RZZ gates."""
expected = "\n".join(
[
" ",
"qr_0: |0>─o───────o───────o───────o──────",
" │ │ │ │ ",
"qr_1: |0>─■───────o───────■───────■──────",
" │ZZ(1) │ │ │ ",
"qr_2: |0>─■───────■───────■───────o──────",
" │ZZ(1) │ZZ(1) │ ",
"qr_3: |0>─────────■───────■───────■──────",
" │ZZ(1) ",
"qr_4: |0>─────────────────────────■──────",
" ",
]
)
qreg = QuantumRegister(5, "qr")
circuit = QuantumCircuit(qreg)
control1 = RZZGate(1).control(1, ctrl_state="0")
circuit.append(control1, [0, 1, 2])
control2 = RZZGate(1).control(2, ctrl_state="00")
circuit.append(control2, [0, 1, 2, 3])
control2_2 = RZZGate(1).control(2, ctrl_state="10")
circuit.append(control2_2, [0, 1, 2, 3])
control3 = RZZGate(1).control(3, ctrl_state="010")
circuit.append(control3, [0, 1, 2, 3, 4])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_open_out_of_order(self):
"""Out of order CXs
See: https://github.com/Qiskit/qiskit-terra/issues/4052#issuecomment-613736911"""
expected = "\n".join(
[
" ",
"q_0: |0>──■──",
" │ ",
"q_1: |0>──■──",
" ┌─┴─┐",
"q_2: |0>┤ X ├",
" └─┬─┘",
"q_3: |0>──o──",
" ",
"q_4: |0>─────",
" ",
]
)
qr = QuantumRegister(5, "q")
circuit = QuantumCircuit(qr)
circuit.append(XGate().control(3, ctrl_state="101"), [qr[0], qr[3], qr[1], qr[2]])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
class TestTextWithLayout(QiskitTestCase):
"""The with_layout option"""
def test_with_no_layout(self):
"""A circuit without layout"""
expected = "\n".join(
[
" ",
"q_0: |0>─────",
" ┌───┐",
"q_1: |0>┤ H ├",
" └───┘",
"q_2: |0>─────",
" ",
]
)
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
circuit.h(qr[1])
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_mixed_layout(self):
"""With a mixed layout."""
expected = "\n".join(
[
" ┌───┐",
" v_0 -> 0 |0>┤ H ├",
" └───┘",
"ancilla_1 -> 1 |0>─────",
" ",
"ancilla_0 -> 2 |0>─────",
" ┌───┐",
" v_1 -> 3 |0>┤ H ├",
" └───┘",
]
)
qr = QuantumRegister(2, "v")
ancilla = QuantumRegister(2, "ancilla")
circuit = QuantumCircuit(qr, ancilla)
circuit.h(qr)
pass_ = ApplyLayout()
pass_.property_set["layout"] = Layout({qr[0]: 0, ancilla[1]: 1, ancilla[0]: 2, qr[1]: 3})
circuit_with_layout = pass_(circuit)
self.assertEqual(str(_text_circuit_drawer(circuit_with_layout)), expected)
def test_partial_layout(self):
"""With a partial layout.
See: https://github.com/Qiskit/qiskit-terra/issues/4757"""
expected = "\n".join(
[
" ┌───┐",
"v_0 -> 0 |0>┤ H ├",
" └───┘",
" 1 |0>─────",
" ",
" 2 |0>─────",
" ┌───┐",
"v_1 -> 3 |0>┤ H ├",
" └───┘",
]
)
qr = QuantumRegister(2, "v")
pqr = QuantumRegister(4, "physical")
circuit = QuantumCircuit(pqr)
circuit.h(0)
circuit.h(3)
circuit._layout = TranspileLayout(
Layout({0: qr[0], 1: None, 2: None, 3: qr[1]}),
{qubit: index for index, qubit in enumerate(circuit.qubits)},
)
circuit._layout.initial_layout.add_register(qr)
self.assertEqual(str(_text_circuit_drawer(circuit)), expected)
def test_with_classical_regs(self):
"""Involving classical registers"""
expected = "\n".join(
[
" ",
"qr1_0 -> 0 |0>──────",
" ",
"qr1_1 -> 1 |0>──────",
" ┌─┐ ",
"qr2_0 -> 2 |0>┤M├───",
" └╥┘┌─┐",
"qr2_1 -> 3 |0>─╫─┤M├",
" ║ └╥┘",
" cr: 0 2/═╩══╩═",
" 0 1 ",
]
)
qr1 = QuantumRegister(2, "qr1")
qr2 = QuantumRegister(2, "qr2")
cr = ClassicalRegister(2, "cr")
circuit = QuantumCircuit(qr1, qr2, cr)
circuit.measure(qr2[0], cr[0])
circuit.measure(qr2[1], cr[1])
pass_ = ApplyLayout()
pass_.property_set["layout"] = Layout({qr1[0]: 0, qr1[1]: 1, qr2[0]: 2, qr2[1]: 3})
circuit_with_layout = pass_(circuit)
self.assertEqual(str(_text_circuit_drawer(circuit_with_layout)), expected)
def test_with_layout_but_disable(self):
"""With parameter without_layout=False"""
expected = "\n".join(
[
" ",
"q_0: |0>──────",
" ",
"q_1: |0>──────",
" ┌─┐ ",
"q_2: |0>┤M├───",
" └╥┘┌─┐",
"q_3: |0>─╫─┤M├",
" ║ └╥┘",
"cr: 0 2/═╩══╩═",
" 0 1 ",
]
)
pqr = QuantumRegister(4, "q")
qr1 = QuantumRegister(2, "qr1")
cr = ClassicalRegister(2, "cr")
qr2 = QuantumRegister(2, "qr2")
circuit = QuantumCircuit(pqr, cr)
circuit._layout = Layout({qr1[0]: 0, qr1[1]: 1, qr2[0]: 2, qr2[1]: 3})
circuit.measure(pqr[2], cr[0])
circuit.measure(pqr[3], cr[1])
self.assertEqual(str(_text_circuit_drawer(circuit, with_layout=False)), expected)
def test_after_transpile(self):
"""After transpile, the drawing should include the layout"""
expected = "\n".join(
[
" ┌─────────┐┌─────────┐┌───┐┌─────────┐┌─┐ ",
" userqr_0 -> 0 ┤ U2(0,π) ├┤ U2(0,π) ├┤ X ├┤ U2(0,π) ├┤M├───",
" ├─────────┤├─────────┤└─┬─┘├─────────┤└╥┘┌─┐",
" userqr_1 -> 1 ┤ U2(0,π) ├┤ U2(0,π) ├──■──┤ U2(0,π) ├─╫─┤M├",
" └─────────┘└─────────┘ └─────────┘ ║ └╥┘",
" ancilla_0 -> 2 ───────────────────────────────────────╫──╫─",
" ║ ║ ",
" ancilla_1 -> 3 ───────────────────────────────────────╫──╫─",
" ║ ║ ",
" ancilla_2 -> 4 ───────────────────────────────────────╫──╫─",
" ║ ║ ",
" ancilla_3 -> 5 ───────────────────────────────────────╫──╫─",
" ║ ║ ",
" ancilla_4 -> 6 ───────────────────────────────────────╫──╫─",
" ║ ║ ",
" ancilla_5 -> 7 ───────────────────────────────────────╫──╫─",
" ║ ║ ",
" ancilla_6 -> 8 ───────────────────────────────────────╫──╫─",
" ║ ║ ",
" ancilla_7 -> 9 ───────────────────────────────────────╫──╫─",
" ║ ║ ",
" ancilla_8 -> 10 ───────────────────────────────────────╫──╫─",
" ║ ║ ",
" ancilla_9 -> 11 ───────────────────────────────────────╫──╫─",
" ║ ║ ",
"ancilla_10 -> 12 ───────────────────────────────────────╫──╫─",
" ║ ║ ",
"ancilla_11 -> 13 ───────────────────────────────────────╫──╫─",
" ║ ║ ",
" c0_0: ═══════════════════════════════════════╩══╬═",
" ║ ",
" c0_1: ══════════════════════════════════════════╩═",
" ",
]
)
qr = QuantumRegister(2, "userqr")
cr = ClassicalRegister(2, "c0")
qc = QuantumCircuit(qr, cr)
qc.h(qr)
qc.cx(qr[0], qr[1])
qc.measure(qr, cr)
coupling_map = [
[1, 0],
[1, 2],
[2, 3],
[4, 3],
[4, 10],
[5, 4],
[5, 6],
[5, 9],
[6, 8],
[7, 8],
[9, 8],
[9, 10],
[11, 3],
[11, 10],
[11, 12],
[12, 2],
[13, 1],
[13, 12],
]
qc_result = transpile(
qc,
basis_gates=["u1", "u2", "u3", "cx", "id"],
coupling_map=coupling_map,
optimization_level=0,
seed_transpiler=0,
)
self.assertEqual(qc_result.draw(output="text", cregbundle=False).single_string(), expected)
class TestTextInitialValue(QiskitTestCase):
"""Testing the initial_state parameter"""
def setUp(self) -> None:
super().setUp()
qr = QuantumRegister(2, "q")
cr = ClassicalRegister(2, "c")
self.circuit = QuantumCircuit(qr, cr)
self.circuit.measure(qr, cr)
def test_draw_initial_value_default(self):
"""Text drawer (.draw) default initial_state parameter (False)."""
expected = "\n".join(
[
" ┌─┐ ",
"q_0: ┤M├───",
" └╥┘┌─┐",
"q_1: ─╫─┤M├",
" ║ └╥┘",
"c_0: ═╩══╬═",
" ║ ",
"c_1: ════╩═",
" ",
]
)
self.assertEqual(
self.circuit.draw(output="text", cregbundle=False).single_string(), expected
)
def test_draw_initial_value_true(self):
"""Text drawer .draw(initial_state=True)."""
expected = "\n".join(
[
" ┌─┐ ",
"q_0: |0>┤M├───",
" └╥┘┌─┐",
"q_1: |0>─╫─┤M├",
" ║ └╥┘",
" c_0: 0 ═╩══╬═",
" ║ ",
" c_1: 0 ════╩═",
" ",
]
)
self.assertEqual(
self.circuit.draw(output="text", initial_state=True, cregbundle=False).single_string(),
expected,
)
def test_initial_value_false(self):
"""Text drawer with initial_state parameter False."""
expected = "\n".join(
[
" ┌─┐ ",
"q_0: ┤M├───",
" └╥┘┌─┐",
"q_1: ─╫─┤M├",
" ║ └╥┘",
"c: 2/═╩══╩═",
" 0 1 ",
]
)
self.assertEqual(str(_text_circuit_drawer(self.circuit, initial_state=False)), expected)
class TestTextHamiltonianGate(QiskitTestCase):
"""Testing the Hamiltonian gate drawer"""
def test_draw_hamiltonian_single(self):
"""Text Hamiltonian gate with single qubit."""
# fmt: off
expected = "\n".join([" ┌─────────────┐",
"q0: ┤ Hamiltonian ├",
" └─────────────┘"])
# fmt: on
qr = QuantumRegister(1, "q0")
circuit = QuantumCircuit(qr)
matrix = numpy.zeros((2, 2))
theta = Parameter("theta")
circuit.append(HamiltonianGate(matrix, theta), [qr[0]])
circuit = circuit.bind_parameters({theta: 1})
self.assertEqual(circuit.draw(output="text").single_string(), expected)
def test_draw_hamiltonian_multi(self):
"""Text Hamiltonian gate with mutiple qubits."""
expected = "\n".join(
[
" ┌──────────────┐",
"q0_0: ┤0 ├",
" │ Hamiltonian │",
"q0_1: ┤1 ├",
" └──────────────┘",
]
)
qr = QuantumRegister(2, "q0")
circuit = QuantumCircuit(qr)
matrix = numpy.zeros((4, 4))
theta = Parameter("theta")
circuit.append(HamiltonianGate(matrix, theta), [qr[0], qr[1]])
circuit = circuit.bind_parameters({theta: 1})
self.assertEqual(circuit.draw(output="text").single_string(), expected)
class TestTextPhase(QiskitTestCase):
"""Testing the draweing a circuit with phase"""
def test_bell(self):
"""Text Bell state with phase."""
expected = "\n".join(
[
"global phase: \u03C0/2",
" ┌───┐ ",
"q_0: ┤ H ├──■──",
" └───┘┌─┴─┐",
"q_1: ─────┤ X ├",
" └───┘",
]
)
qr = QuantumRegister(2, "q")
circuit = QuantumCircuit(qr)
circuit.global_phase = 3.141592653589793 / 2
circuit.h(0)
circuit.cx(0, 1)
self.assertEqual(circuit.draw(output="text").single_string(), expected)
def test_empty(self):
"""Text empty circuit (two registers) with phase."""
# fmt: off
expected = "\n".join(["global phase: 3",
" ",
"q_0: ",
" ",
"q_1: ",
" "])
# fmt: on
qr = QuantumRegister(2, "q")
circuit = QuantumCircuit(qr)
circuit.global_phase = 3
self.assertEqual(circuit.draw(output="text").single_string(), expected)
def test_empty_noregs(self):
"""Text empty circuit (no registers) with phase."""
expected = "\n".join(["global phase: 4.21"])
circuit = QuantumCircuit()
circuit.global_phase = 4.21
self.assertEqual(circuit.draw(output="text").single_string(), expected)
def test_registerless_one_bit(self):
"""Text circuit with one-bit registers and registerless bits."""
# fmt: off
expected = "\n".join([" ",
"qrx_0: ",
" ",
"qrx_1: ",
" ",
" 2: ",
" ",
" 3: ",
" ",
" qry: ",
" ",
" 0: ",
" ",
" 1: ",
" ",
"crx: 2/",
" "])
# fmt: on
qrx = QuantumRegister(2, "qrx")
qry = QuantumRegister(1, "qry")
crx = ClassicalRegister(2, "crx")
circuit = QuantumCircuit(qrx, [Qubit(), Qubit()], qry, [Clbit(), Clbit()], crx)
self.assertEqual(circuit.draw(output="text", cregbundle=True).single_string(), expected)
class TestCircuitVisualizationImplementation(QiskitVisualizationTestCase):
"""Tests utf8 and cp437 encoding."""
text_reference_utf8 = path_to_diagram_reference("circuit_text_ref_utf8.txt")
text_reference_cp437 = path_to_diagram_reference("circuit_text_ref_cp437.txt")
def sample_circuit(self):
"""Generate a sample circuit that includes the most common elements of
quantum circuits.
"""
qr = QuantumRegister(3, "q")
cr = ClassicalRegister(3, "c")
circuit = QuantumCircuit(qr, cr)
circuit.x(qr[0])
circuit.y(qr[0])
circuit.z(qr[0])
circuit.barrier(qr[0])
circuit.barrier(qr[1])
circuit.barrier(qr[2])
circuit.h(qr[0])
circuit.s(qr[0])
circuit.sdg(qr[0])
circuit.t(qr[0])
circuit.tdg(qr[0])
circuit.sx(qr[0])
circuit.sxdg(qr[0])
circuit.i(qr[0])
circuit.reset(qr[0])
circuit.rx(pi, qr[0])
circuit.ry(pi, qr[0])
circuit.rz(pi, qr[0])
circuit.append(U1Gate(pi), [qr[0]])
circuit.append(U2Gate(pi, pi), [qr[0]])
circuit.append(U3Gate(pi, pi, pi), [qr[0]])
circuit.swap(qr[0], qr[1])
circuit.cx(qr[0], qr[1])
circuit.cy(qr[0], qr[1])
circuit.cz(qr[0], qr[1])
circuit.ch(qr[0], qr[1])
circuit.append(CU1Gate(pi), [qr[0], qr[1]])
circuit.append(CU3Gate(pi, pi, pi), [qr[0], qr[1]])
circuit.crz(pi, qr[0], qr[1])
circuit.cry(pi, qr[0], qr[1])
circuit.crx(pi, qr[0], qr[1])
circuit.ccx(qr[0], qr[1], qr[2])
circuit.cswap(qr[0], qr[1], qr[2])
circuit.measure(qr, cr)
return circuit
def test_text_drawer_utf8(self):
"""Test that text drawer handles utf8 encoding."""
filename = "current_textplot_utf8.txt"
qc = self.sample_circuit()
output = _text_circuit_drawer(
qc, filename=filename, fold=-1, initial_state=True, cregbundle=False, encoding="utf8"
)
try:
encode(str(output), encoding="utf8")
except UnicodeEncodeError:
self.fail("_text_circuit_drawer() should be utf8.")
self.assertFilesAreEqual(filename, self.text_reference_utf8, "utf8")
os.remove(filename)
def test_text_drawer_cp437(self):
"""Test that text drawer handles cp437 encoding."""
filename = "current_textplot_cp437.txt"
qc = self.sample_circuit()
output = _text_circuit_drawer(
qc, filename=filename, fold=-1, initial_state=True, cregbundle=False, encoding="cp437"
)
try:
encode(str(output), encoding="cp437")
except UnicodeEncodeError:
self.fail("_text_circuit_drawer() should be cp437.")
self.assertFilesAreEqual(filename, self.text_reference_cp437, "cp437")
os.remove(filename)
if __name__ == "__main__":
unittest.main()
|
https://github.com/shantomborah/Quantum-Algorithms
|
shantomborah
|
import numpy as np
import matplotlib.pyplot as plt
from qiskit import QuantumCircuit
from qiskit import QuantumRegister
from qiskit.quantum_info import Operator
from qiskit.circuit.library.standard_gates import XGate
class ThreeQubitCode:
def __init__(self):
# Initialize Registers
self.code = QuantumRegister(3, name="code")
self.syndrm = QuantumRegister(2, name="syndrome")
# Build Circuit Components
self.encoder_ckt = self.build_encoder()
self.syndrome_ckt = self.build_syndrome()
self.correction_ckt = self.build_correction()
# Build Noisy Channel
self.noise_ckt = QuantumCircuit(self.code, self.syndrm)
self.noise_ckt.unitary(Operator(np.eye(2)), [self.code[0]], label='noise')
self.noise_ckt.unitary(Operator(np.eye(2)), [self.code[1]], label='noise')
self.noise_ckt.unitary(Operator(np.eye(2)), [self.code[2]], label='noise')
# Compose Full Circuit
circ = QuantumCircuit(self.code, self.syndrm)
circ.barrier()
self.circuit = self.encoder_ckt + circ + self.noise_ckt + circ + self.syndrome_ckt + circ + self.correction_ckt
def build_encoder(self):
# Build Encoder Circuit
circ = QuantumCircuit(self.code, self.syndrm, name="Encoder Circuit")
circ.cx(self.code[0], self.code[1])
circ.cx(self.code[0], self.code[2])
return circ
def build_syndrome(self):
# Build Syndrome Circuit
circ = QuantumCircuit(self.code, self.syndrm, name="Syndrome Circuit")
circ.h(self.syndrm)
circ.barrier()
circ.cz(self.syndrm[1], self.code[2])
circ.cz(self.syndrm[1], self.code[1])
circ.cz(self.syndrm[0], self.code[1])
circ.cz(self.syndrm[0], self.code[0])
circ.barrier()
circ.h(self.syndrm)
return circ
def build_correction(self):
# Build Correction Circuit
circ = QuantumCircuit(self.code, self.syndrm)
circ.append(XGate().control(2, ctrl_state=2), [self.syndrm[0], self.syndrm[1], self.code[2]])
circ.append(XGate().control(2, ctrl_state=3), [self.syndrm[0], self.syndrm[1], self.code[1]])
circ.append(XGate().control(2, ctrl_state=1), [self.syndrm[0], self.syndrm[1], self.code[0]])
return circ
def visualize(self):
# Draw Circuits
self.encoder_ckt.draw('mpl', reverse_bits=True).suptitle('Encoder Circuit', fontsize=16)
self.syndrome_ckt.draw('mpl', reverse_bits=True).suptitle('Syndrome Circuit', fontsize=16)
self.correction_ckt.draw('mpl', reverse_bits=True).suptitle('Error Correction', fontsize=16)
self.circuit.draw('mpl', reverse_bits=True).suptitle('Three Qubit Error Correction', fontsize=16)
plt.show()
|
https://github.com/arthurfaria/Qiskit_certificate_prep
|
arthurfaria
|
import numpy as np
from qiskit import QuantumCircuit, BasicAer, execute
from qiskit.circuit.library import YGate
from qiskit.quantum_info import Operator, average_gate_fidelity, process_fidelity, state_fidelity
#we define a operator op_a = Ygate
op_a = Operator(YGate())
# we define also op_b=np.exp(1j / 2) * op_a which is essentially op_a but with a global phase np.exp(1j / 2)
op_b = np.exp(1j / 2) * op_a
#we run the fidelity for those gates
average_gate_fidelity(op_a,op_b)
process_fidelity(op_a, op_b)
# same here, but now with a general state
n = 1/np.sqrt(3)
desired_state = [n,np.sqrt(1-n**2)]
qc = QuantumCircuit(1)
qc.initialize(desired_state,0)
qc.draw('mpl')
# we run it with help of a simulator
back_sv = BasicAer.get_backend('statevector_simulator')
result = execute(qc, back_sv).result()
qc_sv = result.get_statevector(qc)
#Now, we run the fidelity for those states and we see they are the same
state_fidelity(desired_state, qc_sv)
|
https://github.com/Pitt-JonesLab/clonk_transpilation
|
Pitt-JonesLab
|
"""Define circuits to test"""
lambda_list = []
from supermarq.benchmarks import *
from supermarq.features import cirq_to_qiskit
# Random
# from qiskit.circuit.random import random_circuit
# random_lambda = lambda q: random_circuit(num_qubits=q, depth=q, measure=False, max_operands=2)
# lambda_list.append(random_lambda)
# # Quantum Volume
from qiskit.circuit.library import QuantumVolume
qv_lambda = lambda q: QuantumVolume(num_qubits=q, depth=q)
lambda_list.append(qv_lambda)
# QFT
from qiskit.circuit.library.basis_change import QFT
qft_lambda = lambda q: QFT(q)
lambda_list.append(qft_lambda)
# # Inverse QFT
# inverse_qft_lambda = lambda q: QFT(q, inverse=True)
# label = "IQFT"
# circuits[label] = CircuitTranspilerBenchmark(inverse_qft_lambda, q_range, label=label)
# QAOA, takes a long time to generate - consider capping max size before 20
# qaoa_lambda = lambda q: cirq_to_qiskit(QAOAFermionicSwapProxy(q).circuit())
# label = "QAOA_Fermionic_Swap"
# circuits[label] = CircuitTranspilerBenchmark(qaoa_lambda, q_range, label=label)
# # QAOA vanilla
qaoa_vanilla_lambda = lambda q: cirq_to_qiskit(QAOAVanillaProxy(q).circuit())
lambda_list.append(qaoa_vanilla_lambda)
# VQE - very slow to generate
# vqe_lambda = lambda q: cirq_to_qiskit(VQEProxy(q, 4).circuit()[0])
# label = "VQE"
# circuits[label] = CircuitTranspilerBenchmark(vqe_lambda, q_range, label=label)
# Simulation
hamiltonian_lambda = lambda q: cirq_to_qiskit(
HamiltonianSimulation(q, 1 / 10, 0.5).circuit()
)
lambda_list.append(hamiltonian_lambda)
# weighted adder or ripple carry adder
from qiskit.circuit.library.arithmetic.adders.cdkm_ripple_carry_adder import (
CDKMRippleCarryAdder,
)
from qiskit import QuantumCircuit
# using trick of composing into an empty circuit so that it builds everything into a single quantumregister
adder_lambda = (
lambda q: QuantumCircuit(q)
.compose(CDKMRippleCarryAdder(num_state_qubits=int((q - 1) / 2)), inplace=False)
.decompose()
.decompose()
.decompose()
)
lambda_list.append(adder_lambda)
# multiplier
from qiskit.circuit.library.arithmetic.multipliers import RGQFTMultiplier
multiplier_lambda = (
lambda q: QuantumCircuit(q)
.compose(RGQFTMultiplier(num_state_qubits=int(q / 4)), inplace=False)
.decompose()
.decompose()
.decompose()
)
lambda_list.append(multiplier_lambda)
# # GHZ
ghz_lambda = lambda q: cirq_to_qiskit(GHZ(q).circuit())
lambda_list.append(ghz_lambda)
import weylchamber
from qiskit.converters import circuit_to_dag
from qiskit import transpile
from qiskit.transpiler import PassManager
from qiskit.transpiler.passes import ConsolidateBlocks, Collect2qBlocks
from qiskit.quantum_info import Operator
# # Random
# from qiskit.circuit.random import random_circuit
# random_lambda = lambda q: random_circuit(num_qubits=q, depth=q, measure=False, max_operands=2)
# lambda_list = [random_lambda]
coordinate_list = []
for lambda_item in lambda_list:
circuit = lambda_item(16)
pm = PassManager()
pm.append(Collect2qBlocks())
pm.append(ConsolidateBlocks(force_consolidate=True))
transp_circuit = pm.run(circuit)
dag = circuit_to_dag(transp_circuit)
for gate in dag.collect_2q_runs():
assert len(gate) == 1
d = Operator(gate[0].op).data
coordinate_list.append(weylchamber.c1c2c3(d))
coordinate_freq = {i: coordinate_list.count(i) for i in set(coordinate_list)}
import matplotlib.pyplot as plt
plt.close()
fig = plt.figure()
ax = fig.add_subplot(111, projection="3d")
from weylchamber import WeylChamber
w = WeylChamber()
##
for k, v in coordinate_freq.items():
w.scatter(*k, s=0.6 * v)
##
w.labels = {}
w.render(ax)
plt.savefig("weyl.svg", format="svg", facecolor="None")
fig.show()
|
https://github.com/bagmk/Quantum_Machine_Learning_Express
|
bagmk
|
from qiskit import *
from oracle_generation import generate_oracle
get_bin = lambda x, n: format(x, 'b').zfill(n)
def gen_circuits(min,max,size):
circuits = []
secrets = []
ORACLE_SIZE = size
for i in range(min,max+1):
cur_str = get_bin(i,ORACLE_SIZE-1)
(circuit, secret) = generate_oracle(ORACLE_SIZE,False,3,cur_str)
circuits.append(circuit)
secrets.append(secret)
return (circuits, secrets)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import pulse
with pulse.build(name='my_example') as my_program:
# Add instructions here
pass
my_program
from qiskit.pulse import DriveChannel
channel = DriveChannel(0)
from qiskit.providers.fake_provider import FakeValencia
backend = FakeValencia()
with pulse.build(backend=backend, name='backend_aware') as backend_aware_program:
channel = pulse.drive_channel(0)
print(pulse.num_qubits())
# Raises an error as backend only has 5 qubits
#pulse.drive_channel(100)
with pulse.build(backend) as delay_5dt:
pulse.delay(5, channel)
from qiskit.pulse import library
amp = 1
sigma = 10
num_samples = 128
gaus = pulse.library.Gaussian(num_samples, amp, sigma,
name="Parametric Gaus")
gaus.draw()
import numpy as np
times = np.arange(num_samples)
gaussian_samples = np.exp(-1/2 *((times - num_samples / 2) ** 2 / sigma**2))
gaus = library.Waveform(gaussian_samples, name="WF Gaus")
gaus.draw()
gaus = library.gaussian(duration=num_samples, amp=amp, sigma=sigma, name="Lib Gaus")
gaus.draw()
with pulse.build() as schedule:
pulse.play(gaus, channel)
schedule.draw()
with pulse.build() as schedule:
pulse.play([0.001*i for i in range(160)], channel)
schedule.draw()
with pulse.build(backend) as schedule:
pulse.set_frequency(4.5e9, channel)
with pulse.build(backend) as schedule:
pulse.shift_phase(np.pi, channel)
from qiskit.pulse import Acquire, AcquireChannel, MemorySlot
with pulse.build(backend) as schedule:
pulse.acquire(1200, pulse.acquire_channel(0), MemorySlot(0))
with pulse.build(backend, name='Left align example') as program:
with pulse.align_left():
gaussian_pulse = library.gaussian(100, 0.5, 20)
pulse.play(gaussian_pulse, pulse.drive_channel(0))
pulse.play(gaussian_pulse, pulse.drive_channel(1))
pulse.play(gaussian_pulse, pulse.drive_channel(1))
program.draw()
with pulse.build(backend, name='Right align example') as program:
with pulse.align_right():
gaussian_pulse = library.gaussian(100, 0.5, 20)
pulse.play(gaussian_pulse, pulse.drive_channel(0))
pulse.play(gaussian_pulse, pulse.drive_channel(1))
pulse.play(gaussian_pulse, pulse.drive_channel(1))
program.draw()
with pulse.build(backend, name='example') as program:
gaussian_pulse = library.gaussian(100, 0.5, 20)
with pulse.align_equispaced(2*gaussian_pulse.duration):
pulse.play(gaussian_pulse, pulse.drive_channel(0))
pulse.play(gaussian_pulse, pulse.drive_channel(1))
pulse.play(gaussian_pulse, pulse.drive_channel(1))
program.draw()
with pulse.build(backend, name='example') as program:
with pulse.align_sequential():
gaussian_pulse = library.gaussian(100, 0.5, 20)
pulse.play(gaussian_pulse, pulse.drive_channel(0))
pulse.play(gaussian_pulse, pulse.drive_channel(1))
pulse.play(gaussian_pulse, pulse.drive_channel(1))
program.draw()
with pulse.build(backend, name='Offset example') as program:
with pulse.phase_offset(3.14, pulse.drive_channel(0)):
pulse.play(gaussian_pulse, pulse.drive_channel(0))
with pulse.frequency_offset(10e6, pulse.drive_channel(0)):
pulse.play(gaussian_pulse, pulse.drive_channel(0))
program.draw()
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/indian-institute-of-science-qc/qiskit-aakash
|
indian-institute-of-science-qc
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2018.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
# pylint: disable=invalid-name,missing-docstring
"""mpl circuit visualization backend."""
import collections
import fractions
import itertools
import json
import logging
import math
import numpy as np
try:
from matplotlib import patches
from matplotlib import pyplot as plt
from matplotlib import pyplot as plt, gridspec
HAS_MATPLOTLIB = True
except ImportError:
HAS_MATPLOTLIB = False
from qiskit.visualization import exceptions
from qiskit.visualization import interpolation
from qiskit.visualization.qcstyle import (OPStylePulse, OPStyleSched,
DefaultStyle, BWStyle)
from qiskit.pulse.channels import (DriveChannel, ControlChannel, MeasureChannel,
AcquireChannel, SnapshotChannel)
from qiskit.pulse import (SamplePulse, FrameChange, PersistentValue, Snapshot, Acquire,
PulseError)
from qiskit import user_config
logger = logging.getLogger(__name__)
Register = collections.namedtuple('Register', 'reg index')
WID = 0.65
HIG = 0.65
DEFAULT_SCALE = 4.3
PORDER_GATE = 5
PORDER_LINE = 2
PORDER_GRAY = 3
PORDER_TEXT = 6
PORDER_SUBP = 4
class Anchor:
def __init__(self, reg_num, yind, fold):
self.__yind = yind
self.__fold = fold
self.__reg_num = reg_num
self.__gate_placed = []
self.gate_anchor = 0
def plot_coord(self, index, gate_width):
h_pos = index % self.__fold + 1
# check folding
if self.__fold > 0:
if h_pos + (gate_width - 1) > self.__fold:
index += self.__fold - (h_pos - 1)
x_pos = index % self.__fold + 1 + 0.5 * (gate_width - 1)
y_pos = self.__yind - (index // self.__fold) * (self.__reg_num + 1)
else:
x_pos = index + 1 + 0.5 * (gate_width - 1)
y_pos = self.__yind
# could have been updated, so need to store
self.gate_anchor = index
return x_pos, y_pos
def is_locatable(self, index, gate_width):
hold = [index + i for i in range(gate_width)]
for p in hold:
if p in self.__gate_placed:
return False
return True
def set_index(self, index, gate_width):
h_pos = index % self.__fold + 1
if h_pos + (gate_width - 1) > self.__fold:
_index = index + self.__fold - (h_pos - 1)
else:
_index = index
for ii in range(gate_width):
if _index + ii not in self.__gate_placed:
self.__gate_placed.append(_index + ii)
self.__gate_placed.sort()
def get_index(self):
if self.__gate_placed:
return self.__gate_placed[-1] + 1
return 0
class MatplotlibDrawer:
def __init__(self, qregs, cregs, ops,
scale=1.0, style=None, plot_barriers=True,
reverse_bits=False):
if not HAS_MATPLOTLIB:
raise ImportError('The class MatplotlibDrawer needs matplotlib. '
'Run "pip install matplotlib" before.')
self._ast = None
self._scale = DEFAULT_SCALE * scale
self._creg = []
self._qreg = []
self._registers(cregs, qregs)
self._ops = ops
self._qreg_dict = collections.OrderedDict()
self._creg_dict = collections.OrderedDict()
self._cond = {
'n_lines': 0,
'xmax': 0,
'ymax': 0,
}
config = user_config.get_config()
if config:
config_style = config.get('circuit_mpl_style', 'default')
if config_style == 'default':
self._style = DefaultStyle()
elif config_style == 'bw':
self._style = BWStyle()
elif style is False:
self._style = BWStyle()
else:
self._style = DefaultStyle()
self.plot_barriers = plot_barriers
self.reverse_bits = reverse_bits
if style:
if isinstance(style, dict):
self._style.set_style(style)
elif isinstance(style, str):
with open(style, 'r') as infile:
dic = json.load(infile)
self._style.set_style(dic)
self.figure = plt.figure()
self.figure.patch.set_facecolor(color=self._style.bg)
self.ax = self.figure.add_subplot(111)
self.ax.axis('off')
self.ax.set_aspect('equal')
self.ax.tick_params(labelbottom=False, labeltop=False,
labelleft=False, labelright=False)
def _registers(self, creg, qreg):
self._creg = []
for r in creg:
self._creg.append(Register(reg=r[0], index=r[1]))
self._qreg = []
for r in qreg:
self._qreg.append(Register(reg=r[0], index=r[1]))
@property
def ast(self):
return self._ast
def _custom_multiqubit_gate(self, xy, fc=None, wide=True, text=None,
subtext=None):
xpos = min([x[0] for x in xy])
ypos = min([y[1] for y in xy])
ypos_max = max([y[1] for y in xy])
if wide:
if subtext:
boxes_length = round(max([len(text), len(subtext)]) / 8) or 1
else:
boxes_length = round(len(text) / 8) or 1
wid = WID * 2.8 * boxes_length
else:
wid = WID
if fc:
_fc = fc
else:
_fc = self._style.gc
qubit_span = abs(ypos) - abs(ypos_max) + 1
height = HIG + (qubit_span - 1)
box = patches.Rectangle(
xy=(xpos - 0.5 * wid, ypos - .5 * HIG),
width=wid, height=height, fc=_fc, ec=self._style.lc,
linewidth=1.5, zorder=PORDER_GATE)
self.ax.add_patch(box)
# Annotate inputs
for bit, y in enumerate([x[1] for x in xy]):
self.ax.text(xpos - 0.45 * wid, y, str(bit), ha='left', va='center',
fontsize=self._style.fs, color=self._style.gt,
clip_on=True, zorder=PORDER_TEXT)
if text:
disp_text = text
if subtext:
self.ax.text(xpos, ypos + 0.5 * height, disp_text, ha='center',
va='center', fontsize=self._style.fs,
color=self._style.gt, clip_on=True,
zorder=PORDER_TEXT)
self.ax.text(xpos, ypos + 0.3 * height, subtext, ha='center',
va='center', fontsize=self._style.sfs,
color=self._style.sc, clip_on=True,
zorder=PORDER_TEXT)
else:
self.ax.text(xpos, ypos + .5 * (qubit_span - 1), disp_text,
ha='center',
va='center',
fontsize=self._style.fs,
color=self._style.gt,
clip_on=True,
zorder=PORDER_TEXT)
def _gate(self, xy, fc=None, wide=False, text=None, subtext=None):
xpos, ypos = xy
if wide:
if subtext:
wid = WID * 2.8
else:
boxes_wide = round(len(text) / 10) or 1
wid = WID * 2.8 * boxes_wide
else:
wid = WID
if fc:
_fc = fc
elif text and text in self._style.dispcol:
_fc = self._style.dispcol[text]
else:
_fc = self._style.gc
box = patches.Rectangle(
xy=(xpos - 0.5 * wid, ypos - 0.5 * HIG), width=wid, height=HIG,
fc=_fc, ec=self._style.lc, linewidth=1.5, zorder=PORDER_GATE)
self.ax.add_patch(box)
if text:
if text in self._style.dispcol:
disp_text = "${}$".format(self._style.disptex[text])
else:
disp_text = text
if subtext:
self.ax.text(xpos, ypos + 0.15 * HIG, disp_text, ha='center',
va='center', fontsize=self._style.fs,
color=self._style.gt, clip_on=True,
zorder=PORDER_TEXT)
self.ax.text(xpos, ypos - 0.3 * HIG, subtext, ha='center',
va='center', fontsize=self._style.sfs,
color=self._style.sc, clip_on=True,
zorder=PORDER_TEXT)
else:
self.ax.text(xpos, ypos, disp_text, ha='center', va='center',
fontsize=self._style.fs,
color=self._style.gt,
clip_on=True,
zorder=PORDER_TEXT)
def _subtext(self, xy, text):
xpos, ypos = xy
self.ax.text(xpos, ypos - 0.3 * HIG, text, ha='center', va='top',
fontsize=self._style.sfs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
def _sidetext(self, xy, text):
xpos, ypos = xy
# 0.15 = the initial gap, each char means it needs to move
# another 0.0375 over
xp = xpos + 0.15 + (0.0375 * len(text))
self.ax.text(xp, ypos+HIG, text, ha='center', va='top',
fontsize=self._style.sfs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
def _line(self, xy0, xy1, lc=None, ls=None):
x0, y0 = xy0
x1, y1 = xy1
if lc is None:
linecolor = self._style.lc
else:
linecolor = lc
if ls is None:
linestyle = 'solid'
else:
linestyle = ls
if linestyle == 'doublet':
theta = np.arctan2(np.abs(x1 - x0), np.abs(y1 - y0))
dx = 0.05 * WID * np.cos(theta)
dy = 0.05 * WID * np.sin(theta)
self.ax.plot([x0 + dx, x1 + dx], [y0 + dy, y1 + dy],
color=linecolor,
linewidth=1.0,
linestyle='solid',
zorder=PORDER_LINE)
self.ax.plot([x0 - dx, x1 - dx], [y0 - dy, y1 - dy],
color=linecolor,
linewidth=1.0,
linestyle='solid',
zorder=PORDER_LINE)
else:
self.ax.plot([x0, x1], [y0, y1],
color=linecolor,
linewidth=1.0,
linestyle=linestyle,
zorder=PORDER_LINE)
def _measure(self, qxy, cxy, cid):
qx, qy = qxy
cx, cy = cxy
self._gate(qxy, fc=self._style.dispcol['meas'])
# add measure symbol
arc = patches.Arc(xy=(qx, qy - 0.15 * HIG), width=WID * 0.7,
height=HIG * 0.7, theta1=0, theta2=180, fill=False,
ec=self._style.lc, linewidth=1.5,
zorder=PORDER_GATE)
self.ax.add_patch(arc)
self.ax.plot([qx, qx + 0.35 * WID],
[qy - 0.15 * HIG, qy + 0.20 * HIG],
color=self._style.lc, linewidth=1.5, zorder=PORDER_GATE)
# arrow
self._line(qxy, [cx, cy + 0.35 * WID], lc=self._style.cc,
ls=self._style.cline)
arrowhead = patches.Polygon(((cx - 0.20 * WID, cy + 0.35 * WID),
(cx + 0.20 * WID, cy + 0.35 * WID),
(cx, cy)),
fc=self._style.cc,
ec=None)
self.ax.add_artist(arrowhead)
# target
if self._style.bundle:
self.ax.text(cx + .25, cy + .1, str(cid), ha='left', va='bottom',
fontsize=0.8 * self._style.fs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
def _conds(self, xy, istrue=False):
xpos, ypos = xy
if istrue:
_fc = self._style.lc
else:
_fc = self._style.gc
box = patches.Circle(xy=(xpos, ypos), radius=WID * 0.15,
fc=_fc, ec=self._style.lc,
linewidth=1.5, zorder=PORDER_GATE)
self.ax.add_patch(box)
def _ctrl_qubit(self, xy):
xpos, ypos = xy
box = patches.Circle(xy=(xpos, ypos), radius=WID * 0.15,
fc=self._style.lc, ec=self._style.lc,
linewidth=1.5, zorder=PORDER_GATE)
self.ax.add_patch(box)
def _tgt_qubit(self, xy):
xpos, ypos = xy
box = patches.Circle(xy=(xpos, ypos), radius=HIG * 0.35,
fc=self._style.dispcol['target'],
ec=self._style.lc, linewidth=1.5,
zorder=PORDER_GATE)
self.ax.add_patch(box)
# add '+' symbol
self.ax.plot([xpos, xpos], [ypos - 0.35 * HIG, ypos + 0.35 * HIG],
color=self._style.lc, linewidth=1.0, zorder=PORDER_GATE)
self.ax.plot([xpos - 0.35 * HIG, xpos + 0.35 * HIG], [ypos, ypos],
color=self._style.lc, linewidth=1.0, zorder=PORDER_GATE)
def _swap(self, xy):
xpos, ypos = xy
self.ax.plot([xpos - 0.20 * WID, xpos + 0.20 * WID],
[ypos - 0.20 * WID, ypos + 0.20 * WID],
color=self._style.lc, linewidth=1.5, zorder=PORDER_LINE)
self.ax.plot([xpos - 0.20 * WID, xpos + 0.20 * WID],
[ypos + 0.20 * WID, ypos - 0.20 * WID],
color=self._style.lc, linewidth=1.5, zorder=PORDER_LINE)
def _barrier(self, config, anc):
xys = config['coord']
group = config['group']
y_reg = []
for qreg in self._qreg_dict.values():
if qreg['group'] in group:
y_reg.append(qreg['y'])
x0 = xys[0][0]
box_y0 = min(y_reg) - int(anc / self._style.fold) * (self._cond['n_lines'] + 1) - 0.5
box_y1 = max(y_reg) - int(anc / self._style.fold) * (self._cond['n_lines'] + 1) + 0.5
box = patches.Rectangle(xy=(x0 - 0.3 * WID, box_y0),
width=0.6 * WID, height=box_y1 - box_y0,
fc=self._style.bc, ec=None, alpha=0.6,
linewidth=1.5, zorder=PORDER_GRAY)
self.ax.add_patch(box)
for xy in xys:
xpos, ypos = xy
self.ax.plot([xpos, xpos], [ypos + 0.5, ypos - 0.5],
linewidth=1, linestyle="dashed",
color=self._style.lc,
zorder=PORDER_TEXT)
def _linefeed_mark(self, xy):
xpos, ypos = xy
self.ax.plot([xpos - .1, xpos - .1],
[ypos, ypos - self._cond['n_lines'] + 1],
color=self._style.lc, zorder=PORDER_LINE)
self.ax.plot([xpos + .1, xpos + .1],
[ypos, ypos - self._cond['n_lines'] + 1],
color=self._style.lc, zorder=PORDER_LINE)
def draw(self, filename=None, verbose=False):
self._draw_regs()
self._draw_ops(verbose)
_xl = - self._style.margin[0]
_xr = self._cond['xmax'] + self._style.margin[1]
_yb = - self._cond['ymax'] - self._style.margin[2] + 1 - 0.5
_yt = self._style.margin[3] + 0.5
self.ax.set_xlim(_xl, _xr)
self.ax.set_ylim(_yb, _yt)
# update figure size
fig_w = _xr - _xl
fig_h = _yt - _yb
if self._style.figwidth < 0.0:
self._style.figwidth = fig_w * self._scale * self._style.fs / 72 / WID
self.figure.set_size_inches(self._style.figwidth, self._style.figwidth * fig_h / fig_w)
if filename:
self.figure.savefig(filename, dpi=self._style.dpi,
bbox_inches='tight')
plt.close(self.figure)
return self.figure
def _draw_regs(self):
# quantum register
for ii, reg in enumerate(self._qreg):
if len(self._qreg) > 1:
label = '${}_{{{}}}$'.format(reg.reg.name, reg.index)
else:
label = '${}$'.format(reg.reg.name)
pos = -ii
self._qreg_dict[ii] = {
'y': pos,
'label': label,
'index': reg.index,
'group': reg.reg
}
self._cond['n_lines'] += 1
# classical register
if self._creg:
n_creg = self._creg.copy()
n_creg.pop(0)
idx = 0
y_off = -len(self._qreg)
for ii, (reg, nreg) in enumerate(itertools.zip_longest(
self._creg, n_creg)):
pos = y_off - idx
if self._style.bundle:
label = '${}$'.format(reg.reg.name)
self._creg_dict[ii] = {
'y': pos,
'label': label,
'index': reg.index,
'group': reg.reg
}
if not (not nreg or reg.reg != nreg.reg):
continue
else:
label = '${}_{{{}}}$'.format(reg.reg.name, reg.index)
self._creg_dict[ii] = {
'y': pos,
'label': label,
'index': reg.index,
'group': reg.reg
}
self._cond['n_lines'] += 1
idx += 1
def _draw_regs_sub(self, n_fold, feedline_l=False, feedline_r=False):
# quantum register
for qreg in self._qreg_dict.values():
if n_fold == 0:
label = qreg['label'] + ' : $\\left|0\\right\\rangle$'
else:
label = qreg['label']
y = qreg['y'] - n_fold * (self._cond['n_lines'] + 1)
self.ax.text(-0.5, y, label, ha='right', va='center',
fontsize=self._style.fs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
self._line([0, y], [self._cond['xmax'], y])
# classical register
this_creg_dict = {}
for creg in self._creg_dict.values():
if n_fold == 0:
label = creg['label'] + ' : 0 '
else:
label = creg['label']
y = creg['y'] - n_fold * (self._cond['n_lines'] + 1)
if y not in this_creg_dict.keys():
this_creg_dict[y] = {'val': 1, 'label': label}
else:
this_creg_dict[y]['val'] += 1
for y, this_creg in this_creg_dict.items():
# bundle
if this_creg['val'] > 1:
self.ax.plot([.6, .7], [y - .1, y + .1],
color=self._style.cc,
zorder=PORDER_LINE)
self.ax.text(0.5, y + .1, str(this_creg['val']), ha='left',
va='bottom',
fontsize=0.8 * self._style.fs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
self.ax.text(-0.5, y, this_creg['label'], ha='right', va='center',
fontsize=self._style.fs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
self._line([0, y], [self._cond['xmax'], y], lc=self._style.cc,
ls=self._style.cline)
# lf line
if feedline_r:
self._linefeed_mark((self._style.fold + 1 - 0.1,
- n_fold * (self._cond['n_lines'] + 1)))
if feedline_l:
self._linefeed_mark((0.1,
- n_fold * (self._cond['n_lines'] + 1)))
def _draw_ops(self, verbose=False):
_wide_gate = ['u2', 'u3', 'cu2', 'cu3']
_barriers = {'coord': [], 'group': []}
#
# generate coordinate manager
#
q_anchors = {}
for key, qreg in self._qreg_dict.items():
q_anchors[key] = Anchor(reg_num=self._cond['n_lines'],
yind=qreg['y'],
fold=self._style.fold)
c_anchors = {}
for key, creg in self._creg_dict.items():
c_anchors[key] = Anchor(reg_num=self._cond['n_lines'],
yind=creg['y'],
fold=self._style.fold)
#
# draw gates
#
prev_anc = -1
for layer in self._ops:
layer_width = 1
for op in layer:
if op.name in _wide_gate:
if layer_width < 2:
layer_width = 2
# if custom gate with a longer than standard name determine
# width
elif op.name not in ['barrier', 'snapshot', 'load', 'save',
'noise', 'cswap', 'swap', 'measure'] and len(
op.name) >= 4:
box_width = round(len(op.name) / 8)
# handle params/subtext longer than op names
if op.type == 'op' and hasattr(op.op, 'params'):
param = self.param_parse(op.op.params, self._style.pimode)
if len(param) > len(op.name):
box_width = round(len(param) / 8)
# If more than 4 characters min width is 2
if box_width <= 1:
box_width = 2
if layer_width < box_width:
if box_width > 2:
layer_width = box_width * 2
else:
layer_width = 2
continue
# If more than 4 characters min width is 2
if box_width <= 1:
box_width = 2
if layer_width < box_width:
if box_width > 2:
layer_width = box_width * 2
else:
layer_width = 2
this_anc = prev_anc + 1
for op in layer:
_iswide = op.name in _wide_gate
if op.name not in ['barrier', 'snapshot', 'load', 'save',
'noise', 'cswap', 'swap', 'measure'] and len(
op.name) >= 4:
_iswide = True
# get qreg index
q_idxs = []
for qarg in op.qargs:
for index, reg in self._qreg_dict.items():
if (reg['group'] == qarg[0] and
reg['index'] == qarg[1]):
q_idxs.append(index)
break
# get creg index
c_idxs = []
for carg in op.cargs:
for index, reg in self._creg_dict.items():
if (reg['group'] == carg[0] and
reg['index'] == carg[1]):
c_idxs.append(index)
break
# Only add the gate to the anchors if it is going to be plotted.
# This prevents additional blank wires at the end of the line if
# the last instruction is a barrier type
if self.plot_barriers or \
op.name not in ['barrier', 'snapshot', 'load', 'save',
'noise']:
for ii in q_idxs:
q_anchors[ii].set_index(this_anc, layer_width)
# qreg coordinate
q_xy = [q_anchors[ii].plot_coord(this_anc, layer_width) for ii in q_idxs]
# creg coordinate
c_xy = [c_anchors[ii].plot_coord(this_anc, layer_width) for ii in c_idxs]
# bottom and top point of qreg
qreg_b = min(q_xy, key=lambda xy: xy[1])
qreg_t = max(q_xy, key=lambda xy: xy[1])
# update index based on the value from plotting
this_anc = q_anchors[q_idxs[0]].gate_anchor
if verbose:
print(op)
if op.type == 'op' and hasattr(op.op, 'params'):
param = self.param_parse(op.op.params, self._style.pimode)
else:
param = None
# conditional gate
if op.condition:
c_xy = [c_anchors[ii].plot_coord(this_anc, layer_width) for
ii in self._creg_dict]
mask = 0
for index, cbit in enumerate(self._creg):
if cbit.reg == op.condition[0]:
mask |= (1 << index)
val = op.condition[1]
# cbit list to consider
fmt_c = '{{:0{}b}}'.format(len(c_xy))
cmask = list(fmt_c.format(mask))[::-1]
# value
fmt_v = '{{:0{}b}}'.format(cmask.count('1'))
vlist = list(fmt_v.format(val))[::-1]
# plot conditionals
v_ind = 0
xy_plot = []
for xy, m in zip(c_xy, cmask):
if m == '1':
if xy not in xy_plot:
if vlist[v_ind] == '1' or self._style.bundle:
self._conds(xy, istrue=True)
else:
self._conds(xy, istrue=False)
xy_plot.append(xy)
v_ind += 1
creg_b = sorted(xy_plot, key=lambda xy: xy[1])[0]
self._subtext(creg_b, hex(val))
self._line(qreg_t, creg_b, lc=self._style.cc,
ls=self._style.cline)
#
# draw special gates
#
if op.name == 'measure':
vv = self._creg_dict[c_idxs[0]]['index']
self._measure(q_xy[0], c_xy[0], vv)
elif op.name in ['barrier', 'snapshot', 'load', 'save',
'noise']:
_barriers = {'coord': [], 'group': []}
for index, qbit in enumerate(q_idxs):
q_group = self._qreg_dict[qbit]['group']
if q_group not in _barriers['group']:
_barriers['group'].append(q_group)
_barriers['coord'].append(q_xy[index])
if self.plot_barriers:
self._barrier(_barriers, this_anc)
else:
# this stop there being blank lines plotted in place of barriers
this_anc -= 1
elif op.name == 'initialize':
vec = '[%s]' % param
self._custom_multiqubit_gate(q_xy, wide=_iswide,
text="|psi>",
subtext=vec)
elif op.name == 'unitary':
# TODO(mtreinish): Look into adding the unitary to the
# subtext
self._custom_multiqubit_gate(q_xy, wide=_iswide,
text="U")
#
# draw single qubit gates
#
elif len(q_xy) == 1:
disp = op.name
if param:
prm = '({})'.format(param)
if len(prm) < 20:
self._gate(q_xy[0], wide=_iswide, text=disp,
subtext=prm)
else:
self._gate(q_xy[0], wide=_iswide, text=disp)
else:
self._gate(q_xy[0], wide=_iswide, text=disp)
#
# draw multi-qubit gates (n=2)
#
elif len(q_xy) == 2:
# cx
if op.name == 'cx':
self._ctrl_qubit(q_xy[0])
self._tgt_qubit(q_xy[1])
# add qubit-qubit wiring
self._line(qreg_b, qreg_t)
# cz for latexmode
elif op.name == 'cz':
if self._style.latexmode:
self._ctrl_qubit(q_xy[0])
self._ctrl_qubit(q_xy[1])
else:
disp = op.name.replace('c', '')
self._ctrl_qubit(q_xy[0])
self._gate(q_xy[1], wide=_iswide, text=disp)
# add qubit-qubit wiring
self._line(qreg_b, qreg_t)
# control gate
elif op.name in ['cy', 'ch', 'cu3', 'crz']:
disp = op.name.replace('c', '')
self._ctrl_qubit(q_xy[0])
if param:
self._gate(q_xy[1], wide=_iswide, text=disp,
subtext='{}'.format(param))
else:
self._gate(q_xy[1], wide=_iswide, text=disp)
# add qubit-qubit wiring
self._line(qreg_b, qreg_t)
# cu1
elif op.name == 'cu1':
self._ctrl_qubit(q_xy[0])
self._ctrl_qubit(q_xy[1])
self._sidetext(qreg_b, param)
# add qubit-qubit wiring
self._line(qreg_b, qreg_t)
# rzz gate
elif op.name == 'rzz':
self._ctrl_qubit(q_xy[0])
self._ctrl_qubit(q_xy[1])
self._sidetext(qreg_b, text='zz({})'.format(param))
# add qubit-qubit wiring
self._line(qreg_b, qreg_t)
# swap gate
elif op.name == 'swap':
self._swap(q_xy[0])
self._swap(q_xy[1])
# add qubit-qubit wiring
self._line(qreg_b, qreg_t)
# Custom gate
else:
self._custom_multiqubit_gate(q_xy, wide=_iswide,
text=op.name)
#
# draw multi-qubit gates (n=3)
#
elif len(q_xy) == 3:
# cswap gate
if op.name == 'cswap':
self._ctrl_qubit(q_xy[0])
self._swap(q_xy[1])
self._swap(q_xy[2])
# add qubit-qubit wiring
self._line(qreg_b, qreg_t)
# ccx gate
elif op.name == 'ccx':
self._ctrl_qubit(q_xy[0])
self._ctrl_qubit(q_xy[1])
self._tgt_qubit(q_xy[2])
# add qubit-qubit wiring
self._line(qreg_b, qreg_t)
# custom gate
else:
self._custom_multiqubit_gate(q_xy, wide=_iswide,
text=op.name)
# draw custom multi-qubit gate
elif len(q_xy) > 3:
self._custom_multiqubit_gate(q_xy, wide=_iswide,
text=op.name)
else:
logger.critical('Invalid gate %s', op)
raise exceptions.VisualizationError('invalid gate {}'.format(op))
prev_anc = this_anc + layer_width - 1
#
# adjust window size and draw horizontal lines
#
anchors = [q_anchors[ii].get_index() for ii in self._qreg_dict]
if anchors:
max_anc = max(anchors)
else:
max_anc = 0
n_fold = max(0, max_anc - 1) // self._style.fold
# window size
if max_anc > self._style.fold > 0:
self._cond['xmax'] = self._style.fold + 1
self._cond['ymax'] = (n_fold + 1) * (self._cond['n_lines'] + 1) - 1
else:
self._cond['xmax'] = max_anc + 1
self._cond['ymax'] = self._cond['n_lines']
# add horizontal lines
for ii in range(n_fold + 1):
feedline_r = (n_fold > 0 and n_fold > ii)
feedline_l = (ii > 0)
self._draw_regs_sub(ii, feedline_l, feedline_r)
# draw gate number
if self._style.index:
for ii in range(max_anc):
if self._style.fold > 0:
x_coord = ii % self._style.fold + 1
y_coord = - (ii // self._style.fold) * (self._cond['n_lines'] + 1) + 0.7
else:
x_coord = ii + 1
y_coord = 0.7
self.ax.text(x_coord, y_coord, str(ii + 1), ha='center',
va='center', fontsize=self._style.sfs,
color=self._style.tc, clip_on=True,
zorder=PORDER_TEXT)
@staticmethod
def param_parse(v, pimode=False):
# create an empty list to store the parameters in
param_parts = [None] * len(v)
for i, e in enumerate(v):
if pimode:
try:
param_parts[i] = MatplotlibDrawer.format_pi(e)
except TypeError:
param_parts[i] = str(e)
else:
try:
param_parts[i] = MatplotlibDrawer.format_numeric(e)
except TypeError:
param_parts[i] = str(e)
if param_parts[i].startswith('-'):
param_parts[i] = '$-$' + param_parts[i][1:]
param_parts = ', '.join(param_parts)
return param_parts
@staticmethod
def format_pi(val):
fracvals = MatplotlibDrawer.fraction(val)
buf = ''
if fracvals:
nmr, dnm = fracvals.numerator, fracvals.denominator
if nmr == 1:
buf += '$\\pi$'
elif nmr == -1:
buf += '-$\\pi$'
else:
buf += '{}$\\pi$'.format(nmr)
if dnm > 1:
buf += '/{}'.format(dnm)
return buf
else:
coef = MatplotlibDrawer.format_numeric(val / np.pi)
if coef == '0':
return '0'
return '{}$\\pi$'.format(coef)
@staticmethod
def format_numeric(val, tol=1e-5):
if isinstance(val, complex):
return str(val)
elif complex(val).imag != 0:
val = complex(val)
abs_val = abs(val)
if math.isclose(abs_val, 0.0, abs_tol=1e-100):
return '0'
if math.isclose(math.fmod(abs_val, 1.0),
0.0, abs_tol=tol) and 0.5 < abs_val < 9999.5:
return str(int(val))
if 0.1 <= abs_val < 100.0:
return '{:.2f}'.format(val)
return '{:.1e}'.format(val)
@staticmethod
def fraction(val, base=np.pi, n=100, tol=1e-5):
abs_val = abs(val)
for i in range(1, n):
for j in range(1, n):
if math.isclose(abs_val, i / j * base, rel_tol=tol):
if val < 0:
i *= -1
return fractions.Fraction(i, j)
return None
class EventsOutputChannels:
"""Pulse dataset for channel."""
def __init__(self, t0, tf):
"""Create new channel dataset.
Args:
t0 (int): starting time of plot
tf (int): ending time of plot
"""
self.pulses = {}
self.t0 = t0
self.tf = tf
self._waveform = None
self._framechanges = None
self._conditionals = None
self._snapshots = None
self._labels = None
self.enable = False
def add_instruction(self, start_time, pulse):
"""Add new pulse instruction to channel.
Args:
start_time (int): Starting time of instruction
pulse (Instruction): Instruction object to be added
"""
if start_time in self.pulses.keys():
self.pulses[start_time].append(pulse.command)
else:
self.pulses[start_time] = [pulse.command]
@property
def waveform(self):
"""Get waveform."""
if self._waveform is None:
self._build_waveform()
return self._waveform[self.t0:self.tf]
@property
def framechanges(self):
"""Get frame changes."""
if self._framechanges is None:
self._build_waveform()
return self._trim(self._framechanges)
@property
def conditionals(self):
"""Get conditionals."""
if self._conditionals is None:
self._build_waveform()
return self._trim(self._conditionals)
@property
def snapshots(self):
"""Get snapshots."""
if self._snapshots is None:
self._build_waveform()
return self._trim(self._snapshots)
@property
def labels(self):
"""Get labels."""
if self._labels is None:
self._build_waveform()
return self._trim(self._labels)
def is_empty(self):
"""Return if pulse is empty.
Returns:
bool: if the channel has nothing to plot
"""
if any(self.waveform) or self.framechanges or self.conditionals or self.snapshots:
return False
return True
def to_table(self, name):
"""Get table contains.
Args:
name (str): name of channel
Returns:
dict: dictionary of events in the channel
"""
time_event = []
framechanges = self.framechanges
conditionals = self.conditionals
snapshots = self.snapshots
for key, val in framechanges.items():
data_str = 'framechange: %.2f' % val
time_event.append((key, name, data_str))
for key, val in conditionals.items():
data_str = 'conditional, %s' % val
time_event.append((key, name, data_str))
for key, val in snapshots.items():
data_str = 'snapshot: %s' % val
time_event.append((key, name, data_str))
return time_event
def _build_waveform(self):
"""Create waveform from stored pulses.
"""
self._framechanges = {}
self._conditionals = {}
self._snapshots = {}
self._labels = {}
fc = 0
pv = np.zeros(self.tf + 1, dtype=np.complex128)
wf = np.zeros(self.tf + 1, dtype=np.complex128)
last_pv = None
for time, commands in sorted(self.pulses.items()):
if time > self.tf:
break
tmp_fc = 0
for command in commands:
if isinstance(command, FrameChange):
tmp_fc += command.phase
pv[time:] = 0
elif isinstance(command, Snapshot):
self._snapshots[time] = command.name
if tmp_fc != 0:
self._framechanges[time] = tmp_fc
fc += tmp_fc
for command in commands:
if isinstance(command, PersistentValue):
pv[time:] = np.exp(1j*fc) * command.value
last_pv = (time, command)
break
for command in commands:
duration = command.duration
tf = min(time + duration, self.tf)
if isinstance(command, SamplePulse):
wf[time:tf] = np.exp(1j*fc) * command.samples[:tf-time]
pv[time:] = 0
self._labels[time] = (tf, command)
if last_pv is not None:
pv_cmd = last_pv[1]
self._labels[last_pv[0]] = (time, pv_cmd)
last_pv = None
elif isinstance(command, Acquire):
wf[time:tf] = np.ones(command.duration)
self._labels[time] = (tf, command)
self._waveform = wf + pv
def _trim(self, events):
"""Return events during given `time_range`.
Args:
events (dict): time and operation of events
Returns:
dict: dictionary of events within the time
"""
events_in_time_range = {}
for k, v in events.items():
if self.t0 <= k <= self.tf:
events_in_time_range[k] = v
return events_in_time_range
class SamplePulseDrawer:
"""A class to create figure for sample pulse."""
def __init__(self, style):
"""Create new figure.
Args:
style (OPStylePulse): style sheet
"""
self.style = style or OPStylePulse()
def draw(self, pulse, dt, interp_method, scaling=1):
"""Draw figure.
Args:
pulse (SamplePulse): SamplePulse to draw
dt (float): time interval
interp_method (Callable): interpolation function
See `qiskit.visualization.interpolation` for more information
scaling (float): Relative visual scaling of waveform amplitudes
Returns:
matplotlib.figure: A matplotlib figure object of the pulse envelope
"""
figure = plt.figure()
interp_method = interp_method or interpolation.step_wise
figure.set_size_inches(self.style.figsize[0], self.style.figsize[1])
ax = figure.add_subplot(111)
ax.set_facecolor(self.style.bg_color)
samples = pulse.samples
time = np.arange(0, len(samples) + 1, dtype=float) * dt
time, re, im = interp_method(time, samples, self.style.num_points)
# plot
ax.fill_between(x=time, y1=re, y2=np.zeros_like(time),
facecolor=self.style.wave_color[0], alpha=0.3,
edgecolor=self.style.wave_color[0], linewidth=1.5,
label='real part')
ax.fill_between(x=time, y1=im, y2=np.zeros_like(time),
facecolor=self.style.wave_color[1], alpha=0.3,
edgecolor=self.style.wave_color[1], linewidth=1.5,
label='imaginary part')
ax.set_xlim(0, pulse.duration * dt)
if scaling:
ax.set_ylim(-scaling, scaling)
else:
v_max = max(max(np.abs(re)), max(np.abs(im)))
ax.set_ylim(-1.2 * v_max, 1.2 * v_max)
return figure
class ScheduleDrawer:
"""A class to create figure for schedule and channel."""
def __init__(self, style):
"""Create new figure.
Args:
style (OPStyleSched): style sheet
"""
self.style = style or OPStyleSched()
def _build_channels(self, schedule, t0, tf):
# prepare waveform channels
drive_channels = collections.OrderedDict()
measure_channels = collections.OrderedDict()
control_channels = collections.OrderedDict()
acquire_channels = collections.OrderedDict()
snapshot_channels = collections.OrderedDict()
for chan in schedule.channels:
if isinstance(chan, DriveChannel):
try:
drive_channels[chan] = EventsOutputChannels(t0, tf)
except PulseError:
pass
elif isinstance(chan, MeasureChannel):
try:
measure_channels[chan] = EventsOutputChannels(t0, tf)
except PulseError:
pass
elif isinstance(chan, ControlChannel):
try:
control_channels[chan] = EventsOutputChannels(t0, tf)
except PulseError:
pass
elif isinstance(chan, AcquireChannel):
try:
acquire_channels[chan] = EventsOutputChannels(t0, tf)
except PulseError:
pass
elif isinstance(chan, SnapshotChannel):
try:
snapshot_channels[chan] = EventsOutputChannels(t0, tf)
except PulseError:
pass
output_channels = {**drive_channels, **measure_channels,
**control_channels, **acquire_channels}
channels = {**output_channels, **acquire_channels, **snapshot_channels}
# sort by index then name to group qubits together.
output_channels = collections.OrderedDict(sorted(output_channels.items(),
key=lambda x: (x[0].index, x[0].name)))
channels = collections.OrderedDict(sorted(channels.items(),
key=lambda x: (x[0].index, x[0].name)))
for start_time, instruction in schedule.instructions:
for channel in instruction.channels:
if channel in output_channels:
output_channels[channel].add_instruction(start_time, instruction)
elif channel in snapshot_channels:
snapshot_channels[channel].add_instruction(start_time, instruction)
return channels, output_channels, snapshot_channels
def _count_valid_waveforms(self, channels, scaling=1, channels_to_plot=None,
plot_all=False):
# count numbers of valid waveform
n_valid_waveform = 0
v_max = 0
for channel, events in channels.items():
if channels_to_plot:
if channel in channels_to_plot:
waveform = events.waveform
v_max = max(v_max,
max(np.abs(np.real(waveform))),
max(np.abs(np.imag(waveform))))
n_valid_waveform += 1
events.enable = True
else:
if not events.is_empty() or plot_all:
waveform = events.waveform
v_max = max(v_max,
max(np.abs(np.real(waveform))),
max(np.abs(np.imag(waveform))))
n_valid_waveform += 1
events.enable = True
if scaling:
v_max = 0.5 * scaling
else:
v_max = 0.5 / (1.2 * v_max)
return n_valid_waveform, v_max
def _draw_table(self, figure, channels, dt, n_valid_waveform):
del n_valid_waveform # unused
# create table
table_data = []
if self.style.use_table:
for channel, events in channels.items():
if events.enable:
table_data.extend(events.to_table(channel.name))
table_data = sorted(table_data, key=lambda x: x[0])
# plot table
if table_data:
# table area size
ncols = self.style.table_columns
nrows = int(np.ceil(len(table_data)/ncols))
# fig size
h_table = nrows * self.style.fig_unit_h_table
h_waves = (self.style.figsize[1] - h_table)
# create subplots
gs = gridspec.GridSpec(2, 1, height_ratios=[h_table, h_waves], hspace=0)
tb = plt.subplot(gs[0])
ax = plt.subplot(gs[1])
# configure each cell
tb.axis('off')
cell_value = [['' for _kk in range(ncols * 3)] for _jj in range(nrows)]
cell_color = [self.style.table_color * ncols for _jj in range(nrows)]
cell_width = [*([0.2, 0.2, 0.5] * ncols)]
for ii, data in enumerate(table_data):
# pylint: disable=unbalanced-tuple-unpacking
r, c = np.unravel_index(ii, (nrows, ncols), order='f')
# pylint: enable=unbalanced-tuple-unpacking
time, ch_name, data_str = data
# item
cell_value[r][3 * c + 0] = 't = %s' % time * dt
cell_value[r][3 * c + 1] = 'ch %s' % ch_name
cell_value[r][3 * c + 2] = data_str
table = tb.table(cellText=cell_value,
cellLoc='left',
rowLoc='center',
colWidths=cell_width,
bbox=[0, 0, 1, 1],
cellColours=cell_color)
table.auto_set_font_size(False)
table.set_fontsize = self.style.table_font_size
else:
ax = figure.add_subplot(111)
figure.set_size_inches(self.style.figsize[0], self.style.figsize[1])
return ax
def _draw_snapshots(self, ax, snapshot_channels, dt, y0):
for events in snapshot_channels.values():
snapshots = events.snapshots
if snapshots:
for time in snapshots:
ax.annotate(s="\u25D8", xy=(time*dt, y0), xytext=(time*dt, y0+0.08),
arrowprops={'arrowstyle': 'wedge'}, ha='center')
def _draw_framechanges(self, ax, fcs, dt, y0):
framechanges_present = True
for time in fcs.keys():
ax.text(x=time*dt, y=y0, s=r'$\circlearrowleft$',
fontsize=self.style.icon_font_size,
ha='center', va='center')
return framechanges_present
def _get_channel_color(self, channel):
# choose color
if isinstance(channel, DriveChannel):
color = self.style.d_ch_color
elif isinstance(channel, ControlChannel):
color = self.style.u_ch_color
elif isinstance(channel, MeasureChannel):
color = self.style.m_ch_color
elif isinstance(channel, AcquireChannel):
color = self.style.a_ch_color
else:
color = 'black'
return color
def _prev_label_at_time(self, prev_labels, time):
for _, labels in enumerate(prev_labels):
for t0, (tf, _) in labels.items():
if time in (t0, tf):
return True
return False
def _draw_labels(self, ax, labels, prev_labels, dt, y0):
for t0, (tf, cmd) in labels.items():
if isinstance(cmd, PersistentValue):
name = cmd.name if cmd.name else 'pv'
elif isinstance(cmd, Acquire):
name = cmd.name if cmd.name else 'acquire'
else:
name = cmd.name
ax.annotate(r'%s' % name,
xy=((t0+tf)//2*dt, y0),
xytext=((t0+tf)//2*dt, y0-0.07),
fontsize=self.style.label_font_size,
ha='center', va='center')
linestyle = self.style.label_ch_linestyle
alpha = self.style.label_ch_alpha
color = self.style.label_ch_color
if not self._prev_label_at_time(prev_labels, t0):
ax.axvline(t0*dt, -1, 1, color=color,
linestyle=linestyle, alpha=alpha)
if not (self._prev_label_at_time(prev_labels, tf) or tf in labels):
ax.axvline(tf*dt, -1, 1, color=color,
linestyle=linestyle, alpha=alpha)
def _draw_channels(self, ax, output_channels, interp_method, t0, tf, dt, v_max,
label=False, framechange=True):
y0 = 0
prev_labels = []
for channel, events in output_channels.items():
if events.enable:
# plot waveform
waveform = events.waveform
time = np.arange(t0, tf + 1, dtype=float) * dt
time, re, im = interp_method(time, waveform, self.style.num_points)
color = self._get_channel_color(channel)
# scaling and offset
re = v_max * re + y0
im = v_max * im + y0
offset = np.zeros_like(time) + y0
# plot
ax.fill_between(x=time, y1=re, y2=offset,
facecolor=color[0], alpha=0.3,
edgecolor=color[0], linewidth=1.5,
label='real part')
ax.fill_between(x=time, y1=im, y2=offset,
facecolor=color[1], alpha=0.3,
edgecolor=color[1], linewidth=1.5,
label='imaginary part')
ax.plot((t0, tf), (y0, y0), color='#000000', linewidth=1.0)
# plot frame changes
fcs = events.framechanges
if fcs and framechange:
self._draw_framechanges(ax, fcs, dt, y0)
# plot labels
labels = events.labels
if labels and label:
self._draw_labels(ax, labels, prev_labels, dt, y0)
prev_labels.append(labels)
else:
continue
# plot label
ax.text(x=0, y=y0, s=channel.name,
fontsize=self.style.axis_font_size,
ha='right', va='center')
y0 -= 1
return y0
def draw(self, schedule, dt, interp_method, plot_range,
scaling=1, channels_to_plot=None, plot_all=True,
table=True, label=False, framechange=True):
"""Draw figure.
Args:
schedule (ScheduleComponent): Schedule to draw
dt (float): time interval
interp_method (Callable): interpolation function
See `qiskit.visualization.interpolation` for more information
plot_range (tuple[float]): plot range
scaling (float): Relative visual scaling of waveform amplitudes
channels_to_plot (list[OutputChannel]): channels to draw
plot_all (bool): if plot all channels even it is empty
table (bool): Draw event table
label (bool): Label individual instructions
framechange (bool): Add framechange indicators
Returns:
matplotlib.figure: A matplotlib figure object for the pulse schedule
Raises:
VisualizationError: when schedule cannot be drawn
"""
figure = plt.figure()
if not channels_to_plot:
channels_to_plot = []
interp_method = interp_method or interpolation.step_wise
# setup plot range
if plot_range:
t0 = int(np.floor(plot_range[0]/dt))
tf = int(np.floor(plot_range[1]/dt))
else:
t0 = 0
tf = schedule.stop_time
# prepare waveform channels
(channels, output_channels,
snapshot_channels) = self._build_channels(schedule, t0, tf)
# count numbers of valid waveform
n_valid_waveform, v_max = self._count_valid_waveforms(output_channels, scaling=scaling,
channels_to_plot=channels_to_plot,
plot_all=plot_all)
if table:
ax = self._draw_table(figure, channels, dt, n_valid_waveform)
else:
ax = figure.add_subplot(111)
figure.set_size_inches(self.style.figsize[0], self.style.figsize[1])
ax.set_facecolor(self.style.bg_color)
y0 = self._draw_channels(ax, output_channels, interp_method,
t0, tf, dt, v_max, label=label,
framechange=framechange)
self._draw_snapshots(ax, snapshot_channels, dt, y0)
ax.set_xlim(t0 * dt, tf * dt)
ax.set_ylim(y0, 1)
ax.set_yticklabels([])
return figure
|
https://github.com/vandnaChaturvedi/Qauntum_algorithms_Qiskit
|
vandnaChaturvedi
|
import numpy as np
from qiskit import BasicAer
from qiskit.aqua import QuantumInstance
from qiskit.aqua.algorithms import Simon
from qiskit.aqua.components.oracles import TruthTableOracle
bitmaps = [
'01101001',
'10011001',
'01100110'
]
oracle = TruthTableOracle(bitmaps)
def compute_mask(input_bitmaps):
vals = list(zip(*input_bitmaps))[::-1]
def find_pair():
for i in range(len(vals)):
for j in range(i + 1, len(vals)):
if vals[i] == vals[j]:
return i, j
return 0, 0
k1, k2 = find_pair()
return np.binary_repr(k1 ^ k2, int(np.log2(len(input_bitmaps[0]))))
mask = compute_mask(bitmaps)
print(f'The groundtruth mask is {mask}.')
simon = Simon(oracle)
backend = BasicAer.get_backend('qasm_simulator')
result = simon.run(QuantumInstance(backend, shots=1024))
print('The mask computed using Simon is {}.'.format(result['result']))
assert(result['result'] == mask)
bitmaps = [
'00011110',
'01100110',
'10101010'
]
mask = compute_mask(bitmaps)
print(f'The groundtruth mask is {mask}.')
oracle = TruthTableOracle(bitmaps)
simon = Simon(oracle)
result = simon.run(QuantumInstance(backend, shots=1024))
print('The mask computed using Simon is {}.'.format(result['result']))
assert(result['result'] == mask)
|
https://github.com/Harcipan/QAI_GroverSim
|
Harcipan
|
# Built-in modules
import math
# Imports from Qiskit
from qiskit import QuantumCircuit
from qiskit.circuit.library import GroverOperator, MCMT, ZGate
from qiskit.visualization import plot_distribution
# Imports from Qiskit Runtime
from qiskit_ibm_runtime import QiskitRuntimeService, Sampler, Batch
# To run on hardware, select the backend with the fewest number of jobs in the queue
service = QiskitRuntimeService(channel="ibm_quantum")
backend = service.least_busy(operational=True, simulator=False)
backend.name
def grover_oracle(marked_states):
"""Build a Grover oracle for multiple marked states
Here we assume all input marked states have the same number of bits
Parameters:
marked_states (str or list): Marked states of oracle
Returns:
QuantumCircuit: Quantum circuit representing Grover oracle
"""
if not isinstance(marked_states, list):
marked_states = [marked_states]
# Compute the number of qubits in circuit
num_qubits = len(marked_states[0])
qc = QuantumCircuit(num_qubits)
# Mark each target state in the input list
for target in marked_states:
# Flip target bit-string to match Qiskit bit-ordering
rev_target = target[::-1]
# Find the indices of all the '0' elements in bit-string
zero_inds = [ind for ind in range(num_qubits) if rev_target.startswith("0", ind)]
# Add a multi-controlled Z-gate with pre- and post-applied X-gates (open-controls)
# where the target bit-string has a '0' entry
qc.x(zero_inds)
qc.compose(MCMT(ZGate(), num_qubits - 1, 1), inplace=True)
qc.x(zero_inds)
return qc
marked_states = ["011", "100"]
oracle = grover_oracle(marked_states)
oracle.draw(output="mpl", style="iqp")
grover_op = GroverOperator(oracle)
grover_op.decompose().draw(output="mpl", style="iqp")
optimal_num_iterations = math.floor(
math.pi / (4 * math.asin(math.sqrt(len(marked_states) / 2**grover_op.num_qubits)))
)
qc = QuantumCircuit(grover_op.num_qubits)
# Create even superposition of all basis states
qc.h(range(grover_op.num_qubits))
# Apply Grover operator the optimal number of times
qc.compose(grover_op.power(optimal_num_iterations), inplace=True)
# Measure all qubits
qc.measure_all()
qc.draw(output="mpl", style="iqp")
# To run on local simulator:
# 1. Use the Sampler from qiskit.primitives instead
# 2. Remove the Batch context manager below
with Batch(backend=backend) as batch:
sampler = Sampler()
dist = sampler.run(qc, shots=10000).result().quasi_dists[0]
plot_distribution(dist.binary_probabilities())
import qiskit_ibm_runtime
qiskit_ibm_runtime.version.get_version_info()
import qiskit
qiskit.version.get_version_info()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, transpile
ghz = QuantumCircuit(15)
ghz.h(0)
ghz.cx(0, range(1, 15))
ghz.draw(output='mpl')
|
https://github.com/nahumsa/volta
|
nahumsa
|
import sys
sys.path.append('../')
import numpy as np
import matplotlib.pyplot as plt
# Qiskit
from qiskit.aqua.operators import I, X, Y, Z
from qiskit import BasicAer
from qiskit.aqua.components.optimizers import COBYLA
# VOLTA
from VOLTA.VQD import VQD
from VOLTA.utils import classical_solver
from VOLTA.Hamiltonians import BCS_hamiltonian
%load_ext autoreload
%autoreload 2
def SPT_hamiltonian(g:float):
gzz = 2*(1 - g**2)
gx = (1 + g)**2
gzxz = (g - 1)**2
return - (gzz*(Z^Z^I^I^I) + gzz*(I^Z^Z^I^I) + gzz*(I^I^Z^Z^I) + gzz*(I^I^I^Z^Z)) - (gx*(X^I^I^I^I) + gx*(I^X^I^I^I) + gx*(I^I^X^I^I) + gx*(I^I^I^X^I) + gx*(I^I^I^I^X)) + (gzxz*(Z^X^Z^I^I) + gzxz*(I^Z^X^Z^I) + gzxz*(I^I^Z^X^Z))
g = 1
hamiltonian = SPT_hamiltonian(g)
print(hamiltonian)
eigenvalues, _ = classical_solver(hamiltonian)
print(f"Energy Density: {eigenvalues[0]/3}")
print(f"Expected Energy: {-2*(1 + g**2)}")
energy = []
n_points = 10
x = np.linspace(-1, 1, n_points)
for g in x:
hamiltonian = SPT_hamiltonian(g)
eigenvalues, _ = classical_solver(hamiltonian)
energy.append(eigenvalues[0])
plt.plot(x, np.array(energy)/5, label='energy')
ideal = lambda g:-2*(1 + g**2)
plt.plot(x, ideal(x), label='expected')
plt.legend()
plt.show()
import numpy as np
from VOLTA.Observables import sample_hamiltonian
from tqdm import tqdm
optimizer = COBYLA()
backend = BasicAer.get_backend('qasm_simulator')
def simulation(n_points:int,
backend,
optimizer) -> (np.array, np.array):
g = np.linspace(-1, 1, n_points)
result = []
for g_val in tqdm(g):
hamiltonian = SPT_hamiltonian(g_val)
Algo = VQD(hamiltonian=hamiltonian,
n_excited_states=0,
beta=0.,
optimizer=optimizer,
backend=backend)
Algo.run(0)
vqd_energies = Algo.energies
vqd_states = Algo.states
string_order = Z^Y^X^Y^Z
res = sample_hamiltonian(hamiltonian=string_order,
backend=backend,
ansatz=vqd_states[0])
result.append(res)
return g, np.array(result)
g, result = simulation(n_points=10,
backend=backend,
optimizer=optimizer)
plt.plot(g, result, 'o');
from qiskit.aqua import QuantumInstance
from qiskit.circuit.library import TwoLocal
optimizer = COBYLA(maxiter=10000)
backend = QuantumInstance(backend=BasicAer.get_backend('qasm_simulator'),
shots=10000)
# Define ansatz
ansatz = TwoLocal(hamiltonian.num_qubits, ['ry','rz'], 'cx', reps=2)
# Run algorithm
Algo = VQD(hamiltonian=hamiltonian,
ansatz=ansatz,
n_excited_states=0,
beta=0.,
optimizer=optimizer,
backend=backend)
Algo.run(0)
vqd_energies = Algo.energies
vqd_states = Algo.states
print(f'Energy: {vqd_energies[0]}')
from VOLTA.Observables import sample_hamiltonian
#string_order = Z^Y^X^Y^Z
string_order = I^I^X^I^I
sample_hamiltonian(hamiltonian=string_order,
backend=backend,
ansatz=vqd_states[0])
4*np.abs(g)/(1 + np.abs(g))**2
|
https://github.com/qiskit-community/prototype-entanglement-forging
|
qiskit-community
|
import warnings
warnings.filterwarnings("ignore")
from matplotlib import pyplot as plt
import numpy as np
from qiskit.circuit.library import TwoLocal
from qiskit_nature.drivers import UnitsType, Molecule
from qiskit_nature.drivers.second_quantization import PySCFDriver
from qiskit_nature.problems.second_quantization import ElectronicStructureProblem
from qiskit_nature.mappers.second_quantization import JordanWignerMapper
from qiskit_nature.converters.second_quantization import QubitConverter
from qiskit import Aer
import sys
sys.path.append("../../")
from entanglement_forging import EntanglementForgedVQE
from entanglement_forging import EntanglementForgedGroundStateSolver
from entanglement_forging import EntanglementForgedConfig
distances = np.arange(0.3, 1.5, 0.1)
molecules = []
for dist in distances:
molecule = Molecule(
geometry=[["H", [0.0, 0.0, 0.0]], ["H", [0.0, 0.0, dist]]],
charge=0,
multiplicity=1,
)
molecules = molecules + [molecule]
bitstrings = [[1, 0], [0, 1]]
ansatz = TwoLocal(2, [], "cry", [[0, 1], [1, 0]], reps=1)
backend = Aer.get_backend("statevector_simulator")
converter = QubitConverter(JordanWignerMapper())
config = EntanglementForgedConfig(backend=backend, maxiter=100)
calc = EntanglementForgedGroundStateSolver(
qubit_converter=converter, ansatz=ansatz, bitstrings_u=bitstrings, config=config
)
energies = []
for molecule, distance in zip(molecules, distances):
driver = PySCFDriver.from_molecule(molecule, basis="sto3g")
problem = ElectronicStructureProblem(driver)
problem.second_q_ops()
res = calc.solve(problem)
energies_history = res.get_energies_history()
energy = [None]
if len(energies_history) > 0:
energy = res.get_energies_history()[-1]
energies = energies + energy
print(f"Distance = {distance}, Energy = {energy[0]}")
plt.plot(distances, energies)
plt.xlabel("Atomic distance (Angstrom)")
plt.ylabel("Energy")
plt.show()
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
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/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/sjana01/QiskitNotebooks
|
sjana01
|
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
# Importing standard Qiskit libraries and configuring account
from qiskit import QuantumRegister, ClassicalRegister, execute
from qiskit import QuantumCircuit, execute, Aer, IBMQ
from qiskit.compiler import transpile, assemble
from qiskit.tools.jupyter import *
from qiskit.visualization import plot_state_city
def real_map(value, leftMin, leftMax, rightMin, rightMax):
# Maps one range to another
# Figure out how 'wide' each range is
leftSpan = leftMax - leftMin
rightSpan = rightMax - rightMin
# Convert the left range into a 0-1 range (float)
valueScaled = float(value - leftMin) / float(leftSpan)
# Convert the 0-1 range into a value in the right range.
return rightMin + (valueScaled * rightSpan)
def QRandNum(lb, ub):
# Quantum Random Number generator
# Select the number of qubits
qubits = int(np.log2(ub-lb))
q = QuantumRegister(qubits, 'q')
circ = QuantumCircuit(q)
c0 = ClassicalRegister(2, 'c0')
circ.add_register(c0)
for i in range(qubits):
circ.h(q[i])
for i in range(qubits):
circ.measure(q[i], c0)
backend = Aer.get_backend('statevector_simulator')
job = execute(circ, backend)
#print(job.status())
result = job.result()
output = np.asarray(result.get_statevector(circ))
num = 0
for i in range(len(output)):
if output[i] != 0:
num = i
y = real_map(num + 1 , 1, 2**qubits, lb, ub)
return y
x = []
for i in range(100):
x.append(QRandNum(1, 100))
plt.scatter(range(0, 100), x)
from qiskit.extensions import UnitaryGate
from qiskit.circuit.library import GroverOperator
from qiskit.visualization import plot_histogram
def grover_search(marked_elt: str):
index = int(marked_elt, 2)
arr = np.identity(2**(len(marked_elt)))
arr[index, index] = -1
unitary_gate = UnitaryGate(arr)
oracle = QuantumCircuit(5)
oracle.compose(unitary_gate, qubits=range(5), inplace=True)
#oracle.draw(output='mpl')
grover_op = GroverOperator(oracle)
init = QuantumCircuit(5, 5)
init.h(range(5))
qc = init.compose(grover_op)
qc.compose(grover_op, inplace=True)
qc.compose(grover_op, inplace=True)
qc.compose(grover_op, inplace=True)
qc.measure(range(5),range(5))
#qc.draw(output='mpl')
sim = Aer.get_backend('aer_simulator')
t_qc = transpile(qc, sim)
counts = sim.run(t_qc).result().get_counts()
return counts
counts = grover_search('01101')
plot_histogram(counts)
def grover_circuit(marked_elts: list):
n = len(marked_elts[0])
indices = [int(marked_elt, 2) for marked_elt in marked_elts]
arr = np.identity(2**n)
for index in indices:
arr[index, index] = -1
unitary_gate = UnitaryGate(arr)
oracle = QuantumCircuit(n)
oracle.compose(unitary_gate, qubits=range(n), inplace=True)
# grover operator
grover_op = GroverOperator(oracle)
init = QuantumCircuit(n, n)
init.h(range(n))
r = int(np.pi/4*np.sqrt(2**n/len(indices)))
print(f'{n} qubits, basis states {indices} marked, {r} rounds')
qc = init.compose(grover_op)
for _ in range(1, r):
qc.compose(grover_op, inplace=True)
qc.measure(range(n),range(n))
return qc
q_circuit = grover_circuit(['001101', '101010'])
q_circuit.draw('mpl')
sim = Aer.get_backend('aer_simulator')
t_qc = transpile(q_circuit, sim)
counts = sim.run(t_qc).result().get_counts()
plot_histogram(counts)
# Implementation both with constant and balanced oracles
def build_oracle(size, type='constant'):
''' size (int): n for an n-bit the function
type (str): "constant" or "balanced". default value = constant
output: an oracle
'''
oracle = QuantumCircuit(size+1)
if type == 'constant':
r = np.random.randint(2)
if r == 1:
oracle.x(size)
elif type == 'balanced':
r = np.random.randint(2**size)
b_str = (bin(r)[2:]).zfill(size)
# place X gates determined by b_str
for qubit in range(size):
if b_str[qubit] == '1':
oracle.x(qubit)
oracle.barrier()
# controlled not gate
for qubit in range(size):
oracle.cx(qubit, size)
oracle.barrier()
# place X gates again
for qubit in range(size):
if b_str[qubit] == '1':
oracle.x(qubit)
else:
print("Give valid inputs")
return None
return oracle
balanced_oracle = build_oracle(5, 'balanced')
balanced_oracle.draw('mpl')
constant_oracle = build_oracle(5)
constant_oracle.draw('mpl')
# Let's built the dj circuit now
def build_dj_circuit(size, oracle):
''' size: size of the oracle
oracle: oracle representing the given function
'''
qc = QuantumCircuit(size+1, size)
# Apply H gates to the input qubits
for qubit in range(size):
qc.h(qubit)
# Initialize the output qubit in the |-> state
qc.x(size)
qc.h(size)
# Add oracle
qc = qc.compose(oracle)
# Add the H gate on the input qubits again
for qubit in range(size):
qc.h(qubit)
# Measure
for qubit in range(size):
qc.measure(qubit, qubit)
return qc
dj_circuit = build_dj_circuit(5, balanced_oracle)
dj_circuit.draw('mpl')
# Output using the Aer simulator
sim = Aer.get_backend('aer_simulator')
t_qc = transpile(dj_circuit, sim)
counts = sim.run(dj_circuit).result().get_counts()
#the output should be anything other than '00000'
plot_histogram(counts)
# with the constant oracle the output should always be '00000'
dj_circuit_const = build_dj_circuit(5, constant_oracle)
#dj_circuit_const.draw('mpl')
sim = Aer.get_backend('aer_simulator')
t_qc = transpile(dj_circuit_const, sim)
counts = sim.run(dj_circuit_const).result().get_counts()
plot_histogram(counts)
|
https://github.com/swe-train/qiskit__qiskit
|
swe-train
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2022, 2023.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Tests for BasePrimitive."""
import json
from ddt import data, ddt, unpack
from numpy import array, float32, float64, int32, int64
from qiskit import QuantumCircuit, pulse, transpile
from qiskit.circuit.random import random_circuit
from qiskit.primitives.base.base_primitive import BasePrimitive
from qiskit.primitives.utils import _circuit_key
from qiskit.providers.fake_provider import FakeAlmaden
from qiskit.test import QiskitTestCase
@ddt
class TestCircuitValidation(QiskitTestCase):
"""Test circuits validation logic."""
@data(
(random_circuit(2, 2, seed=0), (random_circuit(2, 2, seed=0),)),
(
[random_circuit(2, 2, seed=0), random_circuit(2, 2, seed=1)],
(random_circuit(2, 2, seed=0), random_circuit(2, 2, seed=1)),
),
)
@unpack
def test_validate_circuits(self, circuits, expected):
"""Test circuits standardization."""
self.assertEqual(BasePrimitive._validate_circuits(circuits), expected)
@data(None, "ERROR", True, 0, 1.0, 1j, [0.0])
def test_type_error(self, circuits):
"""Test type error if invalid input."""
with self.assertRaises(TypeError):
BasePrimitive._validate_circuits(circuits)
@data((), [], "")
def test_value_error(self, circuits):
"""Test value error if no circuits are provided."""
with self.assertRaises(ValueError):
BasePrimitive._validate_circuits(circuits)
@ddt
class TestParameterValuesValidation(QiskitTestCase):
"""Test parameter_values validation logic."""
@data(
((), ((),)),
([], ((),)),
(0, ((0,),)),
(1.2, ((1.2,),)),
((0,), ((0,),)),
([0], ((0,),)),
([1.2], ((1.2,),)),
((0, 1), ((0, 1),)),
([0, 1], ((0, 1),)),
([0, 1.2], ((0, 1.2),)),
([0.3, 1.2], ((0.3, 1.2),)),
(((0, 1)), ((0, 1),)),
(([0, 1]), ((0, 1),)),
([(0, 1)], ((0, 1),)),
([[0, 1]], ((0, 1),)),
([[0, 1.2]], ((0, 1.2),)),
([[0.3, 1.2]], ((0.3, 1.2),)),
# Test for numpy dtypes
(int32(5), ((float(int32(5)),),)),
(int64(6), ((float(int64(6)),),)),
(float32(3.2), ((float(float32(3.2)),),)),
(float64(6.4), ((float(float64(6.4)),),)),
([int32(5), float32(3.2)], ((float(int32(5)), float(float32(3.2))),)),
)
@unpack
def test_validate_parameter_values(self, _parameter_values, expected):
"""Test parameter_values standardization."""
for parameter_values in [_parameter_values, array(_parameter_values)]: # Numpy
self.assertEqual(BasePrimitive._validate_parameter_values(parameter_values), expected)
self.assertEqual(
BasePrimitive._validate_parameter_values(None, default=parameter_values), expected
)
@data(
"ERROR",
("E", "R", "R", "O", "R"),
(["E", "R", "R"], ["O", "R"]),
1j,
(1j,),
((1j,),),
True,
False,
float("inf"),
float("-inf"),
float("nan"),
)
def test_type_error(self, parameter_values):
"""Test type error if invalid input."""
with self.assertRaises(TypeError):
BasePrimitive._validate_parameter_values(parameter_values)
def test_value_error(self):
"""Test value error if no parameter_values or default are provided."""
with self.assertRaises(ValueError):
BasePrimitive._validate_parameter_values(None)
class TestCircuitKey(QiskitTestCase):
"""Tests for _circuit_key function"""
def test_different_circuits(self):
"""Test collision of quantum circuits."""
with self.subTest("Ry circuit"):
def test_func(n):
qc = QuantumCircuit(1, 1, name="foo")
qc.ry(n, 0)
return qc
keys = [_circuit_key(test_func(i)) for i in range(5)]
self.assertEqual(len(keys), len(set(keys)))
with self.subTest("pulse circuit"):
def test_with_scheduling(n):
custom_gate = pulse.Schedule(name="custom_x_gate")
custom_gate.insert(
0, pulse.Play(pulse.Constant(160 * n, 0.1), pulse.DriveChannel(0)), inplace=True
)
qc = QuantumCircuit(1)
qc.x(0)
qc.add_calibration("x", qubits=(0,), schedule=custom_gate)
return transpile(qc, FakeAlmaden(), scheduling_method="alap")
keys = [_circuit_key(test_with_scheduling(i)) for i in range(1, 5)]
self.assertEqual(len(keys), len(set(keys)))
def test_circuit_key_controlflow(self):
"""Test for a circuit with control flow."""
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)
self.assertIsInstance(hash(_circuit_key(qc)), int)
self.assertIsInstance(json.dumps(_circuit_key(qc)), str)
|
https://github.com/apcarrik/qiskit-dev
|
apcarrik
|
from qiskit import QuantumCircuit, transpile
from qiskit.providers.aer import AerSimulator
from qiskit.tools.visualization import plot_histogram
import random
circ = QuantumCircuit(40,40)
# initialize with a Hadamard layer
circ.h(range(40))
# apply some random CNOT and T gates
qubit_indicies = [i for i in range(40)]
for i in range(10):
control, target, t = random.sample(qubit_indicies,3)
circ.cx(control,target)
circ.t(t)
circ.measure(range(40), range(40))
# create statevector simulator
statevector_simulator = AerSimulator(method='statevector')
# transpile circuit for backend
tcirc = transpile(circ, statevector_simulator)
# try and run circuit
statevector_result = statevector_simulator.run(tcirc, shots=1).result()
print('This succeeded?: {}'.format(statevector_result.success))
print('Why not?: {}'.format(statevector_result.status))
# create an extended stablilizer method simulator
extended_stabilizer_simulator = AerSimulator(method='extended_stabilizer')
# transpile circuit for backend
tcirc = transpile(circ, extended_stabilizer_simulator)
# run circuit and get results
extended_stabilizer_result = extended_stabilizer_simulator.run(tcirc, shots=1).result()
print('This succeeded?: {}'.format(extended_stabilizer_result.success))
### Extended Stabilizer Only Gives Approximate Results
small_circ = QuantumCircuit(2,2)
small_circ.h(0)
small_circ.cx(0,1)
small_circ.t(0)
small_circ.measure([0,1],[0,1])
# the circuit should give 00 and 11 with equal probability
expected_results = {'00': 50, '11':50}
tsmall_circuit = transpile(small_circ, extended_stabilizer_simulator)
result = extended_stabilizer_simulator.run(
tsmall_circuit, shots=100).result()
counts = result.get_counts(0)
print('100 shots in {}s'.format(result.time_taken))
plot_histogram([expected_results, counts], legend=["Expected", "Extened Stabilizer"]).show()
## Add Runtime Options for Extended Stabilizer Simulator
opts = {"extended_stabilizer_approximation_error":0.03}
reduced_error_result = extended_stabilizer_simulator.run(
tsmall_circuit, shots=100, **opts).result()
reduced_error_counts = reduced_error_result.get_counts(0)
print('100 shots in {}s'.format(reduced_error_result.time_taken))
plot_histogram([expected_results, reduced_error_counts],
legend=["Expected", "Extened Stabilizer"]).show()
## Simulator Options
# if you expect your output will be concentrated on a few states, you can optimize the
# simulations by reducing the extended_stabilizer_simulator_mixing_time option
print("The circuit above, with 100 shots and precision 0.03 "
"and default mixing time, needed {}s".format(int(reduced_error_result.time_taken)))
opts = {"extended_stabilizer_approximation_error": 0.03,
"extended_stabilizer_simulator_mixing_time": 100}
optimized_result = extended_stabilizer_simulator.run(
tsmall_circuit, shots=100, **opts).result()
print('Dialing down the mixing time, the circuit completed in just {}s'.format(
optimized_result.time_taken))
# if your circuit has non-zero probability on all amplitudes (e.g. it is a random circuit),
# then you can avoid this expensive re-mixing step to take multiple shots from the output
# at once.
opts = {"extended_stabilizer_simulator_mixing_time": 100}
multishot = extended_stabilizer_simulator.run(
tcirc, shots=100, **opts).result()
print("100 shots took {}s".format(multishot.time_taken))
opts = {
'extended_stabilizer_measure_sampling': True,
'extended_stabilizer_mixing_time': 100
}
measure_sampling = extended_stabilizer_simulator.run(
tcirc, shots=100, **opts).result()
print("With the optimization, 100 shots took {}s".format(measure_sampling.time_taken))
|
https://github.com/deveshq/QC-with-qiskit
|
deveshq
|
import numpy as np
# Importing standard Qiskit libraries
from qiskit import *
from qiskit.tools.jupyter import *
from qiskit.visualization import *
from ibm_quantum_widgets import *
from qiskit.providers.aer import QasmSimulator
# Loading your IBM Quantum account(s)
provider = IBMQ.load_account()
from qiskit.quantum_info import Statevector
#Defining Quantum circuit
bell0 = QuantumCircuit(2)
#Creating Bell state
bell0.h(0)
bell0.cx(0,1)
#Extracting statevector
sv = Statevector.from_label('00')
sv_ev = sv.evolve(bell0)
sv_ev.draw('latex')
sv_ev.draw('qsphere')
#Defining Quantum circuit
bell1 = QuantumCircuit(2)
#Creating Bell state
bell1.h(0)
bell1.cx(0,1)
#Extracting statevector
sv1 = Statevector.from_label('01')
sv_ev1 = sv1.evolve(bell1)
sv_ev1.draw('latex')
sv_ev1.draw('qsphere')
#Defining Quantum circuit
bell2 = QuantumCircuit(2)
#Creating Bell state
bell2.x(1)
bell2.h(0)
bell2.cx(0,1)
#Extracting statevector
sv_ev2 = sv.evolve(bell2)
sv_ev2.draw('latex')
sv_ev2.draw('qsphere')
#Defining Quantum circuit
bell3 = QuantumCircuit(2)
#Creating Bell state
bell3.x(0)
bell3.x(1)
bell3.h(0)
bell3.cx(0,1)
#Extracting statevector
sv_ev3 = sv.evolve(bell3)
sv_ev3.draw('latex')
sv_ev3.draw('qsphere')
bell3.draw('text')
qc_ghz = QuantumCircuit(3)
qc_ghz.h(0)
qc_ghz.cx([0,0],[1,2])
qc_ghz.draw('text')
qc_ghz.draw()
sv = Statevector.from_label('000')
sv_ev = sv.evolve(qc_ghz)
sv_ev.draw('latex')
sv = Statevector.from_int(0,2**3)
sv_ev = sv.evolve(qc_ghz)
sv_ev.draw('latex')
BasicAer.backends()
ghz_backend = Aer.get_backend('statevector_simulator')
job = execute(qc_ghz, ghz_backend, shots = 1000)
result = job.result()
sv_ghz2 = result.get_statevector(qc_ghz)
plot_state_qsphere(sv_ghz2)
plot_state_city(sv_ghz2, title = 'GHZ')
plot_state_hinton(sv_ghz2, title = 'GHZ')
plot_state_paulivec(sv_ghz2, title = 'GHZ')
plot_bloch_multivector(sv_ghz2, title = 'GHZ')
plot_bloch_vector([0,0.5,1])
q_a = QuantumRegister(1, 'q_a')
q_b = QuantumRegister(1, 'q_b')
qc = QuantumCircuit(q_a,q_b)
qc.h(0)
qc.z(0)
backend = Aer.get_backend('statevector_simulator')
job = execute(qc, backend, shots = 1000)
res = job.result()
sv = res.get_statevector()
#sv.draw('latex')
plot_bloch_multivector(sv)
plot_state_city(sv, color = ['orange', 'black'])
qc.measure_all()
backend = Aer.get_backend('qasm_simulator')
res = execute(qc, backend, shots = 1000).result()
counts = res.get_counts()
plot_histogram(counts)
meas = QuantumCircuit(3,3)
meas.barrier()
meas.measure([0,1,2],[0,1,2])
circ = meas.compose(qc_ghz, range(3), front = True )
circ.draw()
backend = Aer.get_backend('qasm_simulator')
res = backend.run(circ, shots = 1000).result()
counts = res.get_counts()
print(counts)
res2 = execute(circ, backend, shots = 1000).result()
counts2 = res2.get_counts()
print(counts2)
legend = ['Count-1', 'Count-2']
colour = ['teal', 'black']
plot_histogram([counts,counts2], legend=legend, sort='asc', color=colour) #, bar_labels = False)
provider.backends()
from qiskit.tools import job_monitor
import qiskit.tools.jupyter
#%qiskit_job_watcher
quito = provider.get_backend('ibmq_quito')
job = execute(circ, quito, shots = 1000)
job_monitor(job)
counts3 = job.result().get_counts()
plot_histogram(counts3)
from qiskit.quantum_info import Operator
U = Operator(qc_ghz)
U.data
np.around(U.data, 3)
uni_backend = Aer.get_backend('unitary_simulator')
U = execute(qc_ghz, uni_backend).result().get_unitary(decimals=3)
U
q = QuantumRegister(2, 'q_reg')
c = ClassicalRegister(2, 'c_reg')
qc = QuantumCircuit(q,c)
qc.h([0,1])
qc.cx(q[0],q[1])
qc.draw('mpl')
U_bell = Operator(qc)
np.around(U_bell, 3)
uni_backend = Aer.get_backend('unitary_simulator')
U = execute(qc, uni_backend).result().get_unitary(decimals=3)
U
a = 1/np.sqrt(3)
desired_state = [a, np.sqrt(1-a**2)]
q = QuantumRegister(1, 'q')
qc = QuantumCircuit(q)
qc.initialize(desired_state,0)
qc.draw('mpl')
qc.decompose().draw()
qc.measure_all()
qc.draw()
backend = Aer.get_backend('qasm_simulator')
counts = execute(qc, backend, shots=1000).result().get_counts()
plot_histogram(counts)
back_sv = BasicAer.get_backend('statevector_simulator')
result = execute(qc, back_sv).result()
qc_sv = result.get_statevector()
qc_sv
from qiskit.quantum_info import state_fidelity
state_fidelity(desired_state, qc_sv)
# Gate and prrocess fidility
from qiskit.circuit.library import XGate
from qiskit.quantum_info import Operator, average_gate_fidelity, process_fidelity
op_a = Operator(XGate())
op_b = np.exp(1j / 2) * op_a
#these differ only by a phase so the gate and process
#fidelities are expected to be 1
a = average_gate_fidelity(op_a,op_b)
a
b = process_fidelity(op_a, op_b)
a == b
back = Aer.get_backend('unitary_simulator')
result = execute(qc, back).result()
U_qc = result.get_unitary(decimals = 3)
U_qc
qc = QuantumCircuit(3)
qc.h(0)
qc.cx(0,1)
qc.cx(1,2)
qc.draw()
qc_gate = qc.to_gate()
qc_gate.name = 'Bell State Gate'
circ = QuantumCircuit(3)
circ.append(qc_gate, [0,1,2])
circ.draw()
circ.decompose().draw()
c_qc_gate = qc.to_gate().control(2)
c_qc_gate.name = 'C-Bell State Gate'
circ2 = QuantumCircuit(5)
circ2.append(c_qc_gate, [0,4,1,2,3])
circ2.draw()
circ2.decompose().draw()
#going back to our simpler circuit!
qc = QuantumCircuit(3)
qc.mct([0,1],2)
qc.cx(0,2)
qc.h(1)
qc.z(0)
qc.draw(scale = 1.5, style = {'backgroundcolor': 'lightpink'})
trans = transpile(qc, basis_gates = ['u3','cx','s'])
trans.draw('mpl')
from qiskit.tools.visualization import circuit_drawer
circuit_drawer(qc, output='text')
qc.measure_all()
qasm_str = qc.qasm() #returning a qasm string, THIS SIMPLE
qasm_str
circ = QuantumCircuit.from_qasm_str(qasm_str) #you got to be kidding!
circ.draw()
qc.depth()
qiskit.__version__
#this is your tool to get all the information on all the hardware available, check it for yourself!
import qiskit.tools.jupyter
%qiskit_backend_overview
#that's not a problem!
from qiskit.visualization import plot_gate_map
backend = provider.get_backend('ibmq_manila')
plot_gate_map(backend, plot_directed=True) #check other things you can do in this within docs!
plot_error_map(backend)
qc = QuantumCircuit(3)
qc.h([0,1,2])
qc.measure_all()
sim = BasicAer.get_backend('qasm_simulator')
couple_map = [[0,2],[1,2]] #specify some linear connection
job = execute(qc, sim, shots=1000, coupling_map=couple_map) #here is how you take that in execute also!
result = job.result()
counts = result.get_counts()
print(counts)
|
https://github.com/jakelishman/qiskit-qasm2
|
jakelishman
|
# 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.
# pylint: disable=missing-module-docstring,missing-class-docstring,missing-function-docstring
import enum
import math
import ddt
import qiskit.qasm2
from qiskit.circuit import Gate, library as lib
from qiskit.test import QiskitTestCase
from test import combine # pylint: disable=wrong-import-order
# We need to use this enum a _bunch_ of times, so let's not give it a long name.
# pylint: disable=invalid-name
class T(enum.Enum):
# This is a deliberately stripped-down list that doesn't include most of the expression-specific
# tokens, because we don't want to complicate matters with those in tests of the general parser
# errors. We test the expression subparser elsewhere.
OPENQASM = "OPENQASM"
BARRIER = "barrier"
CREG = "creg"
GATE = "gate"
IF = "if"
INCLUDE = "include"
MEASURE = "measure"
OPAQUE = "opaque"
QREG = "qreg"
RESET = "reset"
PI = "pi"
ARROW = "->"
EQUALS = "=="
SEMICOLON = ";"
COMMA = ","
LPAREN = "("
RPAREN = ")"
LBRACKET = "["
RBRACKET = "]"
LBRACE = "{"
RBRACE = "}"
ID = "q"
REAL = "1.5"
INTEGER = "1"
FILENAME = '"qelib1.inc"'
def bad_token_parametrisation():
"""Generate the test cases for the "bad token" tests; this makes a sequence of OpenQASM 2
statements, then puts various invalid tokens after them to verify that the parser correctly
throws an error on them."""
token_set = frozenset(T)
def without(*tokens):
return token_set - set(tokens)
# ddt isn't a particularly great parametriser - it'll only correctly unpack tuples and lists in
# the way we really want, but if we want to control the test id, we also have to set `__name__`
# which isn't settable on either of those. We can't use unpack, then, so we just need a class
# to pass.
class BadTokenCase:
def __init__(self, statement, disallowed, name=None):
self.statement = statement
self.disallowed = disallowed
self.__name__ = name
for statement, disallowed in [
# This should only include stopping points where the next token is somewhat fixed; in
# places where there's a real decision to be made (such as number of qubits in a gate,
# or the statement type in a gate body), there should be a better error message.
#
# There's a large subset of OQ2 that's reducible to a regular language, so we _could_
# define that, build a DFA for it, and use that to very quickly generate a complete set
# of tests. That would be more complex to read and verify for correctness, though.
(
"",
without(
T.OPENQASM,
T.ID,
T.INCLUDE,
T.OPAQUE,
T.GATE,
T.QREG,
T.CREG,
T.IF,
T.RESET,
T.BARRIER,
T.MEASURE,
T.SEMICOLON,
),
),
("OPENQASM", without(T.REAL, T.INTEGER)),
("OPENQASM 2.0", without(T.SEMICOLON)),
("include", without(T.FILENAME)),
('include "qelib1.inc"', without(T.SEMICOLON)),
("opaque", without(T.ID)),
("opaque bell", without(T.LPAREN, T.ID, T.SEMICOLON)),
("opaque bell (", without(T.ID, T.RPAREN)),
("opaque bell (a", without(T.COMMA, T.RPAREN)),
("opaque bell (a,", without(T.ID, T.RPAREN)),
("opaque bell (a, b", without(T.COMMA, T.RPAREN)),
("opaque bell (a, b)", without(T.ID, T.SEMICOLON)),
("opaque bell (a, b) q1", without(T.COMMA, T.SEMICOLON)),
("opaque bell (a, b) q1,", without(T.ID, T.SEMICOLON)),
("opaque bell (a, b) q1, q2", without(T.COMMA, T.SEMICOLON)),
("gate", without(T.ID)),
("gate bell (", without(T.ID, T.RPAREN)),
("gate bell (a", without(T.COMMA, T.RPAREN)),
("gate bell (a,", without(T.ID, T.RPAREN)),
("gate bell (a, b", without(T.COMMA, T.RPAREN)),
("gate bell (a, b) q1", without(T.COMMA, T.LBRACE)),
("gate bell (a, b) q1,", without(T.ID, T.LBRACE)),
("gate bell (a, b) q1, q2", without(T.COMMA, T.LBRACE)),
("qreg", without(T.ID)),
("qreg reg", without(T.LBRACKET)),
("qreg reg[", without(T.INTEGER)),
("qreg reg[5", without(T.RBRACKET)),
("qreg reg[5]", without(T.SEMICOLON)),
("creg", without(T.ID)),
("creg reg", without(T.LBRACKET)),
("creg reg[", without(T.INTEGER)),
("creg reg[5", without(T.RBRACKET)),
("creg reg[5]", without(T.SEMICOLON)),
("CX", without(T.LPAREN, T.ID, T.SEMICOLON)),
("CX(", without(T.PI, T.INTEGER, T.REAL, T.ID, T.LPAREN, T.RPAREN)),
("CX()", without(T.ID, T.SEMICOLON)),
("CX q", without(T.LBRACKET, T.COMMA, T.SEMICOLON)),
("CX q[", without(T.INTEGER)),
("CX q[0", without(T.RBRACKET)),
("CX q[0]", without(T.COMMA, T.SEMICOLON)),
("CX q[0],", without(T.ID, T.SEMICOLON)),
("CX q[0], q", without(T.LBRACKET, T.COMMA, T.SEMICOLON)),
# No need to repeatedly "every" possible number of arguments.
("measure", without(T.ID)),
("measure q", without(T.LBRACKET, T.ARROW)),
("measure q[", without(T.INTEGER)),
("measure q[0", without(T.RBRACKET)),
("measure q[0]", without(T.ARROW)),
("measure q[0] ->", without(T.ID)),
("measure q[0] -> c", without(T.LBRACKET, T.SEMICOLON)),
("measure q[0] -> c[", without(T.INTEGER)),
("measure q[0] -> c[0", without(T.RBRACKET)),
("measure q[0] -> c[0]", without(T.SEMICOLON)),
("reset", without(T.ID)),
("reset q", without(T.LBRACKET, T.SEMICOLON)),
("reset q[", without(T.INTEGER)),
("reset q[0", without(T.RBRACKET)),
("reset q[0]", without(T.SEMICOLON)),
("barrier", without(T.ID, T.SEMICOLON)),
("barrier q", without(T.LBRACKET, T.COMMA, T.SEMICOLON)),
("barrier q[", without(T.INTEGER)),
("barrier q[0", without(T.RBRACKET)),
("barrier q[0]", without(T.COMMA, T.SEMICOLON)),
("if", without(T.LPAREN)),
("if (", without(T.ID)),
("if (cond", without(T.EQUALS)),
("if (cond ==", without(T.INTEGER)),
("if (cond == 0", without(T.RPAREN)),
("if (cond == 0)", without(T.ID, T.RESET, T.MEASURE)),
]:
for token in disallowed:
yield BadTokenCase(statement, token.value, name=f"'{statement}'-{token.name.lower()}")
def eof_parametrisation():
for tokens in [
("OPENQASM", "2.0", ";"),
("include", '"qelib1.inc"', ";"),
("opaque", "bell", "(", "a", ",", "b", ")", "q1", ",", "q2", ";"),
("gate", "bell", "(", "a", ",", "b", ")", "q1", ",", "q2", "{", "}"),
("qreg", "qr", "[", "5", "]", ";"),
("creg", "cr", "[", "5", "]", ";"),
("CX", "(", ")", "q", "[", "0", "]", ",", "q", "[", "1", "]", ";"),
("measure", "q", "[", "0", "]", "->", "c", "[", "0", "]", ";"),
("reset", "q", "[", "0", "]", ";"),
("barrier", "q", ";"),
# No need to test every combination of `if`, really.
("if", "(", "cond", "==", "0", ")", "CX q[0], q[1];"),
]:
prefix = ""
for token in tokens[:-1]:
prefix = f"{prefix} {token}".strip()
yield prefix
@ddt.ddt
class TestIncompleteStructure(QiskitTestCase):
PRELUDE = "OPENQASM 2.0; qreg q[5]; creg c[5]; creg cond[1];"
@ddt.idata(bad_token_parametrisation())
def test_bad_token(self, case):
"""Test that the parser raises an error when an incorrect token is given."""
statement = case.statement
disallowed = case.disallowed
prelude = "" if statement.startswith("OPENQASM") else self.PRELUDE
full = f"{prelude} {statement} {disallowed}"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "needed .*, but instead"):
qiskit.qasm2.loads(full)
@ddt.idata(eof_parametrisation())
def test_eof(self, statement):
"""Test that the parser raises an error when the end-of-file is reached instead of a token
that is required."""
prelude = "" if statement.startswith("OPENQASM") else self.PRELUDE
full = f"{prelude} {statement}"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "unexpected end-of-file"):
qiskit.qasm2.loads(full)
def test_loading_directory(self):
"""Test that the correct error is raised when a file fails to open."""
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "failed to read"):
qiskit.qasm2.load(".")
class TestVersion(QiskitTestCase):
def test_invalid_version(self):
program = "OPENQASM 3.0;"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "can only handle OpenQASM 2.0"):
qiskit.qasm2.loads(program)
program = "OPENQASM 2.1;"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "can only handle OpenQASM 2.0"):
qiskit.qasm2.loads(program)
program = "OPENQASM 20.e-1;"
with self.assertRaises(qiskit.qasm2.QASM2ParseError):
qiskit.qasm2.loads(program)
def test_openqasm_must_be_first_statement(self):
program = "qreg q[0]; OPENQASM 2.0;"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "only the first statement"):
qiskit.qasm2.loads(program)
@ddt.ddt
class TestScoping(QiskitTestCase):
def test_register_use_before_definition(self):
program = "CX after[0], after[1]; qreg after[2];"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "not defined in this scope"):
qiskit.qasm2.loads(program)
program = "qreg q[2]; measure q[0] -> c[0]; creg c[2];"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "not defined in this scope"):
qiskit.qasm2.loads(program)
@combine(
definer=["qreg reg[2];", "creg reg[2];", "gate reg a {}", "opaque reg a;"],
bad_definer=["qreg reg[2];", "creg reg[2];"],
)
def test_register_already_defined(self, definer, bad_definer):
program = f"{definer} {bad_definer}"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "already defined"):
qiskit.qasm2.loads(program)
def test_qelib1_not_implicit(self):
program = """
OPENQASM 2.0;
qreg q[2];
cx q[0], q[1];
"""
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "'cx' is not defined"):
qiskit.qasm2.loads(program)
def test_cannot_access_gates_before_definition(self):
program = """
qreg q[2];
cx q[0], q[1];
gate cx a, b {
CX a, b;
}
"""
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "'cx' is not defined"):
qiskit.qasm2.loads(program)
def test_cannot_access_gate_recursively(self):
program = """
gate cx a, b {
cx a, b;
}
"""
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "'cx' is not defined"):
qiskit.qasm2.loads(program)
def test_cannot_access_qubits_from_previous_gate(self):
program = """
gate cx a, b {
CX a, b;
}
gate other c {
CX a, b;
}
"""
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "'a' is not defined"):
qiskit.qasm2.loads(program)
def test_cannot_access_parameters_from_previous_gate(self):
program = """
gate first(a, b) q {
U(a, 0, b) q;
}
gate second q {
U(a, 0, b) q;
}
"""
with self.assertRaisesRegex(
qiskit.qasm2.QASM2ParseError, "'a' is not a parameter.*defined"
):
qiskit.qasm2.loads(program)
def test_cannot_access_quantum_registers_within_gate(self):
program = """
qreg q[2];
gate my_gate a {
CX a, q;
}
"""
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "'q' is a quantum register"):
qiskit.qasm2.loads(program)
def test_parameters_not_defined_outside_gate(self):
program = """
gate my_gate(a) q {}
qreg qr[2];
U(a, 0, 0) qr;
"""
with self.assertRaisesRegex(
qiskit.qasm2.QASM2ParseError, "'a' is not a parameter.*defined"
):
qiskit.qasm2.loads(program)
def test_qubits_not_defined_outside_gate(self):
program = """
gate my_gate(a) q {}
U(0, 0, 0) q;
"""
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "'q' is not defined"):
qiskit.qasm2.loads(program)
@ddt.data('include "qelib1.inc";', "gate h q { }")
def test_gates_cannot_redefine(self, definer):
program = f"{definer} gate h q {{ }}"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "already defined"):
qiskit.qasm2.loads(program)
def test_cannot_use_undeclared_register_conditional(self):
program = "qreg q[1]; if (c == 0) U(0, 0, 0) q[0];"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "not defined"):
qiskit.qasm2.loads(program)
@ddt.ddt
class TestTyping(QiskitTestCase):
@ddt.data(
"CX q[0], U;",
"measure U -> c[0];",
"measure q[0] -> U;",
"reset U;",
"barrier U;",
"if (U == 0) CX q[0], q[1];",
"gate my_gate a { U(0, 0, 0) U; }",
)
def test_cannot_use_gates_incorrectly(self, usage):
program = f"qreg q[2]; creg c[2]; {usage}"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "'U' is a gate"):
qiskit.qasm2.loads(program)
@ddt.data(
"measure q[0] -> q[1];",
"if (q == 0) CX q[0], q[1];",
"q q[0], q[1];",
"gate my_gate a { U(0, 0, 0) q; }",
)
def test_cannot_use_qregs_incorrectly(self, usage):
program = f"qreg q[2]; creg c[2]; {usage}"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "'q' is a quantum register"):
qiskit.qasm2.loads(program)
@ddt.data(
"CX q[0], c[1];",
"measure c[0] -> c[1];",
"reset c[0];",
"barrier c[0];",
"c q[0], q[1];",
"gate my_gate a { U(0, 0, 0) c; }",
)
def test_cannot_use_cregs_incorrectly(self, usage):
program = f"qreg q[2]; creg c[2]; {usage}"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "'c' is a classical register"):
qiskit.qasm2.loads(program)
def test_cannot_use_parameters_incorrectly(self):
program = "gate my_gate(p) q { CX p, q; }"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "'p' is a parameter"):
qiskit.qasm2.loads(program)
def test_cannot_use_qubits_incorrectly(self):
program = "gate my_gate(p) q { U(q, q, q) q; }"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "'q' is a gate qubit"):
qiskit.qasm2.loads(program)
@ddt.data(("h", 0), ("h", 2), ("CX", 0), ("CX", 1), ("CX", 3), ("ccx", 2), ("ccx", 4))
@ddt.unpack
def test_gates_accept_only_valid_number_qubits(self, gate, bad_count):
arguments = ", ".join(f"q[{i}]" for i in range(bad_count))
program = f'include "qelib1.inc"; qreg q[5];\n{gate} {arguments};'
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "takes .* quantum arguments?"):
qiskit.qasm2.loads(program)
@ddt.data(("U", 2), ("U", 4), ("rx", 0), ("rx", 2), ("u3", 1))
@ddt.unpack
def test_gates_accept_only_valid_number_parameters(self, gate, bad_count):
arguments = ", ".join("0" for _ in [None] * bad_count)
program = f'include "qelib1.inc"; qreg q[5];\n{gate}({arguments}) q[0];'
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "takes .* parameters?"):
qiskit.qasm2.loads(program)
@ddt.ddt
class TestGateDefinition(QiskitTestCase):
def test_no_zero_qubit(self):
program = "gate zero {}"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "gates must act on at least one"):
qiskit.qasm2.loads(program)
program = "gate zero(a) {}"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "gates must act on at least one"):
qiskit.qasm2.loads(program)
def test_no_zero_qubit_opaque(self):
program = "opaque zero;"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "gates must act on at least one"):
qiskit.qasm2.loads(program)
program = "opaque zero(a);"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "gates must act on at least one"):
qiskit.qasm2.loads(program)
def test_cannot_subscript_qubit(self):
program = """
gate my_gate a {
CX a[0], a[1];
}
"""
with self.assertRaises(qiskit.qasm2.QASM2ParseError):
qiskit.qasm2.loads(program)
def test_cannot_repeat_parameters(self):
program = "gate my_gate(a, a) q {}"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "already defined"):
qiskit.qasm2.loads(program)
def test_cannot_repeat_qubits(self):
program = "gate my_gate a, a {}"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "already defined"):
qiskit.qasm2.loads(program)
def test_qubit_cannot_shadow_parameter(self):
program = "gate my_gate(a) a {}"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "already defined"):
qiskit.qasm2.loads(program)
@ddt.data("measure q -> c;", "reset q", "if (c == 0) U(0, 0, 0) q;", "gate my_x q {}")
def test_definition_cannot_contain_nonunitary(self, statement):
program = f"OPENQASM 2.0; creg c[5]; gate my_gate q {{ {statement} }}"
with self.assertRaisesRegex(
qiskit.qasm2.QASM2ParseError, "only gate applications are valid"
):
qiskit.qasm2.loads(program)
def test_cannot_redefine_u(self):
program = "gate U(a, b, c) q {}"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "already defined"):
qiskit.qasm2.loads(program)
def test_cannot_redefine_cx(self):
program = "gate CX a, b {}"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "already defined"):
qiskit.qasm2.loads(program)
@ddt.ddt
class TestBitResolution(QiskitTestCase):
def test_disallow_out_of_range(self):
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "out-of-range"):
qiskit.qasm2.loads("qreg q[2]; U(0, 0, 0) q[2];")
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "out-of-range"):
qiskit.qasm2.loads("qreg q[2]; creg c[2]; measure q[2] -> c[0];")
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "out-of-range"):
qiskit.qasm2.loads("qreg q[2]; creg c[2]; measure q[0] -> c[2];")
@combine(
conditional=[True, False],
call=[
"CX q1[0], q1[0];",
"CX q1, q1[0];",
"CX q1[0], q1;",
"CX q1, q1;",
"ccx q1[0], q1[1], q1[0];",
"ccx q2, q1, q2[0];",
],
)
def test_disallow_duplicate_qubits(self, call, conditional):
program = """
include "qelib1.inc";
qreg q1[3];
qreg q2[3];
qreg q3[3];
"""
if conditional:
program += "creg cond[1]; if (cond == 0) "
program += call
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "duplicate qubit"):
qiskit.qasm2.loads(program)
@ddt.data(
(("q1[1]", "q2[2]"), "CX q1, q2"),
(("q1[1]", "q2[2]"), "CX q2, q1"),
(("q1[3]", "q2[2]"), "CX q1, q2"),
(("q1[2]", "q2[3]", "q3[3]"), "ccx q1, q2, q3"),
(("q1[2]", "q2[3]", "q3[3]"), "ccx q2, q3, q1"),
(("q1[2]", "q2[3]", "q3[3]"), "ccx q3, q1, q2"),
(("q1[2]", "q2[3]", "q3[3]"), "ccx q1, q2[0], q3"),
(("q1[2]", "q2[3]", "q3[3]"), "ccx q2[0], q3, q1"),
(("q1[2]", "q2[3]", "q3[3]"), "ccx q3, q1, q2[0]"),
)
@ddt.unpack
def test_incorrect_gate_broadcast_lengths(self, registers, call):
setup = 'include "qelib1.inc";\n' + "\n".join(f"qreg {reg};" for reg in registers)
program = f"{setup}\n{call};"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "cannot resolve broadcast"):
qiskit.qasm2.loads(program)
cond = "creg cond[1];\nif (cond == 0)"
program = f"{setup}\n{cond} {call};"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "cannot resolve broadcast"):
qiskit.qasm2.loads(program)
@ddt.data(
("qreg q[2]; creg c[2];", "q[0] -> c"),
("qreg q[2]; creg c[2];", "q -> c[0]"),
("qreg q[1]; creg c[2];", "q -> c[0]"),
("qreg q[2]; creg c[1];", "q[0] -> c"),
("qreg q[2]; creg c[3];", "q -> c"),
)
@ddt.unpack
def test_incorrect_measure_broadcast_lengths(self, setup, operands):
program = f"{setup}\nmeasure {operands};"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "cannot resolve broadcast"):
qiskit.qasm2.loads(program)
program = f"{setup}\ncreg cond[1];\nif (cond == 0) measure {operands};"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "cannot resolve broadcast"):
qiskit.qasm2.loads(program)
@ddt.ddt
class TestCustomInstructions(QiskitTestCase):
def test_cannot_use_custom_before_definition(self):
program = "qreg q[2]; my_gate q[0], q[1];"
class MyGate(Gate):
def __init__(self):
super().__init__("my_gate", 2, [])
with self.assertRaisesRegex(
qiskit.qasm2.QASM2ParseError, "cannot use .* before definition"
):
qiskit.qasm2.loads(
program,
custom_instructions=[qiskit.qasm2.CustomInstruction("my_gate", 0, 2, MyGate)],
)
def test_cannot_misdefine_u(self):
program = "qreg q[1]; U(0.5, 0.25) q[0]"
with self.assertRaisesRegex(
qiskit.qasm2.QASM2ParseError, "custom instruction .* mismatched"
):
qiskit.qasm2.loads(
program, custom_instructions=[qiskit.qasm2.CustomInstruction("U", 2, 1, lib.U2Gate)]
)
def test_cannot_misdefine_cx(self):
program = "qreg q[1]; CX q[0]"
with self.assertRaisesRegex(
qiskit.qasm2.QASM2ParseError, "custom instruction .* mismatched"
):
qiskit.qasm2.loads(
program, custom_instructions=[qiskit.qasm2.CustomInstruction("CX", 0, 1, lib.XGate)]
)
def test_builtin_is_typechecked(self):
program = "qreg q[1]; my(0.5) q[0];"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "'my' takes 2 quantum arguments"):
qiskit.qasm2.loads(
program,
custom_instructions=[
qiskit.qasm2.CustomInstruction("my", 1, 2, lib.RXXGate, builtin=True)
],
)
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "'my' takes 2 parameters"):
qiskit.qasm2.loads(
program,
custom_instructions=[
qiskit.qasm2.CustomInstruction("my", 2, 1, lib.U2Gate, builtin=True)
],
)
def test_cannot_define_builtin_twice(self):
program = "gate builtin q {}; gate builtin q {};"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "'builtin' is already defined"):
qiskit.qasm2.loads(
program,
custom_instructions=[
qiskit.qasm2.CustomInstruction("builtin", 0, 1, lambda: Gate("builtin", 1, []))
],
)
def test_cannot_redefine_custom_u(self):
program = "gate U(a, b, c) q {}"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "already defined"):
qiskit.qasm2.loads(
program,
custom_instructions=[
qiskit.qasm2.CustomInstruction("U", 3, 1, lib.UGate, builtin=True)
],
)
def test_cannot_redefine_custom_cx(self):
program = "gate CX a, b {}"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "already defined"):
qiskit.qasm2.loads(
program,
custom_instructions=[
qiskit.qasm2.CustomInstruction("CX", 0, 2, lib.CXGate, builtin=True)
],
)
@combine(
program=["gate my(a) q {}", "opaque my(a) q;"],
builtin=[True, False],
)
def test_custom_definition_must_match_gate(self, program, builtin):
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "'my' is mismatched"):
qiskit.qasm2.loads(
program,
custom_instructions=[
qiskit.qasm2.CustomInstruction("my", 1, 2, lib.RXXGate, builtin=builtin)
],
)
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "'my' is mismatched"):
qiskit.qasm2.loads(
program,
custom_instructions=[
qiskit.qasm2.CustomInstruction("my", 2, 1, lib.U2Gate, builtin=builtin)
],
)
def test_cannot_have_duplicate_customs(self):
customs = [
qiskit.qasm2.CustomInstruction("my", 1, 2, lib.RXXGate),
qiskit.qasm2.CustomInstruction("x", 0, 1, lib.XGate),
qiskit.qasm2.CustomInstruction("my", 1, 2, lib.RZZGate),
]
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "duplicate custom instruction"):
qiskit.qasm2.loads("", custom_instructions=customs)
def test_qiskit_delay_float_input_wraps_exception(self):
program = "opaque delay(t) q; qreg q[1]; delay(1.5) q[0];"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "can only accept an integer"):
qiskit.qasm2.loads(program, custom_instructions=qiskit.qasm2.LEGACY_CUSTOM_INSTRUCTIONS)
def test_u0_float_input_wraps_exception(self):
program = "opaque u0(n) q; qreg q[1]; u0(1.1) q[0];"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "must be an integer"):
qiskit.qasm2.loads(program, custom_instructions=qiskit.qasm2.LEGACY_CUSTOM_INSTRUCTIONS)
@ddt.ddt
class TestCustomClassical(QiskitTestCase):
@ddt.data("cos", "exp", "sin", "sqrt", "tan", "ln")
def test_cannot_override_builtin(self, builtin):
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, r"cannot override builtin"):
qiskit.qasm2.loads(
"",
custom_classical=[qiskit.qasm2.CustomClassical(builtin, 1, math.exp)],
)
def test_duplicate_names_disallowed(self):
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, r"duplicate custom classical"):
qiskit.qasm2.loads(
"",
custom_classical=[
qiskit.qasm2.CustomClassical("f", 1, math.exp),
qiskit.qasm2.CustomClassical("f", 1, math.exp),
],
)
def test_cannot_shadow_custom_instruction(self):
with self.assertRaisesRegex(
qiskit.qasm2.QASM2ParseError, r"custom classical.*naming clash"
):
qiskit.qasm2.loads(
"",
custom_instructions=[
qiskit.qasm2.CustomInstruction("f", 0, 1, lib.RXGate, builtin=True)
],
custom_classical=[qiskit.qasm2.CustomClassical("f", 1, math.exp)],
)
def test_cannot_shadow_builtin_instruction(self):
with self.assertRaisesRegex(
qiskit.qasm2.QASM2ParseError, r"custom classical.*cannot shadow"
):
qiskit.qasm2.loads(
"",
custom_classical=[qiskit.qasm2.CustomClassical("U", 1, math.exp)],
)
def test_cannot_shadow_with_gate_definition(self):
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, r"'f' is already defined"):
qiskit.qasm2.loads(
"gate f q {}",
custom_classical=[qiskit.qasm2.CustomClassical("f", 1, math.exp)],
)
@ddt.data("qreg", "creg")
def test_cannot_shadow_with_register_definition(self, regtype):
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, r"'f' is already defined"):
qiskit.qasm2.loads(
f"{regtype} f[2];",
custom_classical=[qiskit.qasm2.CustomClassical("f", 1, math.exp)],
)
@ddt.data((0, 1), (0, 2), (1, 0), (1, 2), (2, 0), (2, 1))
@ddt.unpack
def test_mismatched_argument_count(self, n_good, n_bad):
arg_string = ", ".join(["0" for _ in [None] * n_bad])
program = f"""
qreg q[1];
U(f({arg_string}), 0, 0) q[0];
"""
with self.assertRaisesRegex(
qiskit.qasm2.QASM2ParseError, r"custom function argument-count mismatch"
):
qiskit.qasm2.loads(
program, custom_classical=[qiskit.qasm2.CustomClassical("f", n_good, lambda *_: 0)]
)
def test_output_type_error_is_caught(self):
program = """
qreg q[1];
U(f(), 0, 0) q[0];
"""
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, r"user.*returned non-float"):
qiskit.qasm2.loads(
program,
custom_classical=[qiskit.qasm2.CustomClassical("f", 0, lambda: "not a float")],
)
def test_inner_exception_is_wrapped(self):
inner_exception = Exception("custom exception")
def raises():
raise inner_exception
program = """
qreg q[1];
U(raises(), 0, 0) q[0];
"""
with self.assertRaisesRegex(
qiskit.qasm2.QASM2ParseError, "caught exception when constant folding"
) as excinfo:
qiskit.qasm2.loads(
program, custom_classical=[qiskit.qasm2.CustomClassical("raises", 0, raises)]
)
assert excinfo.exception.__cause__ is inner_exception
def test_cannot_be_used_as_gate(self):
program = """
qreg q[1];
f(0) q[0];
"""
with self.assertRaisesRegex(
qiskit.qasm2.QASM2ParseError, r"'f' is a custom classical function"
):
qiskit.qasm2.loads(
program, custom_classical=[qiskit.qasm2.CustomClassical("f", 1, lambda x: x)]
)
def test_cannot_be_used_as_qarg(self):
program = """
U(0, 0, 0) f;
"""
with self.assertRaisesRegex(
qiskit.qasm2.QASM2ParseError, r"'f' is a custom classical function"
):
qiskit.qasm2.loads(
program, custom_classical=[qiskit.qasm2.CustomClassical("f", 1, lambda x: x)]
)
def test_cannot_be_used_as_carg(self):
program = """
qreg q[1];
measure q[0] -> f;
"""
with self.assertRaisesRegex(
qiskit.qasm2.QASM2ParseError, r"'f' is a custom classical function"
):
qiskit.qasm2.loads(
program, custom_classical=[qiskit.qasm2.CustomClassical("f", 1, lambda x: x)]
)
@ddt.ddt
class TestStrict(QiskitTestCase):
@ddt.data(
"gate my_gate(p0, p1,) q0, q1 {}",
"gate my_gate(p0, p1) q0, q1, {}",
"opaque my_gate(p0, p1,) q0, q1;",
"opaque my_gate(p0, p1) q0, q1,;",
'include "qelib1.inc"; qreg q[2]; cu3(0.5, 0.25, 0.125,) q[0], q[1];',
'include "qelib1.inc"; qreg q[2]; cu3(0.5, 0.25, 0.125) q[0], q[1],;',
"qreg q[2]; barrier q[0], q[1],;",
'include "qelib1.inc"; qreg q[1]; rx(sin(pi,)) q[0];',
)
def test_trailing_comma(self, program):
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, r"\[strict\] .*trailing comma"):
qiskit.qasm2.loads("OPENQASM 2.0;\n" + program, strict=True)
def test_trailing_semicolon_after_gate(self):
program = "OPENQASM 2.0; gate my_gate q {};"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, r"\[strict\] .*extra semicolon"):
qiskit.qasm2.loads(program, strict=True)
def test_empty_statement(self):
program = "OPENQASM 2.0; ;"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, r"\[strict\] .*empty statement"):
qiskit.qasm2.loads(program, strict=True)
def test_required_version_regular(self):
program = "qreg q[1];"
with self.assertRaisesRegex(
qiskit.qasm2.QASM2ParseError, r"\[strict\] the first statement"
):
qiskit.qasm2.loads(program, strict=True)
def test_required_version_empty(self):
with self.assertRaisesRegex(
qiskit.qasm2.QASM2ParseError, r"\[strict\] .*needed a version statement"
):
qiskit.qasm2.loads("", strict=True)
def test_barrier_requires_args(self):
program = "OPENQASM 2.0; qreg q[2]; barrier;"
with self.assertRaisesRegex(
qiskit.qasm2.QASM2ParseError, r"\[strict\] barrier statements must have at least one"
):
qiskit.qasm2.loads(program, strict=True)
|
https://github.com/abhishekchak52/quantum-computing-course
|
abhishekchak52
|
# Do the necessary imports
import numpy as np
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit import IBMQ, Aer, transpile, assemble
from qiskit.visualization import plot_histogram, plot_bloch_multivector, array_to_latex
from qiskit.extensions import Initialize
from qiskit.ignis.verification import marginal_counts
from qiskit.quantum_info import random_statevector
# Loading your IBM Quantum account(s)
provider = IBMQ.load_account()
## SETUP
# Protocol uses 3 qubits and 2 classical bits in 2 different registers
qr = QuantumRegister(3, name="q") # Protocol uses 3 qubits
crz = ClassicalRegister(1, name="crz") # and 2 classical bits
crx = ClassicalRegister(1, name="crx") # in 2 different registers
teleportation_circuit = QuantumCircuit(qr, crz, crx)
def create_bell_pair(qc, a, b):
qc.h(a)
qc.cx(a,b)
qr = QuantumRegister(3, name="q")
crz, crx = ClassicalRegister(1, name="crz"), ClassicalRegister(1, name="crx")
teleportation_circuit = QuantumCircuit(qr, crz, crx)
create_bell_pair(teleportation_circuit, 1, 2)
teleportation_circuit.draw()
def alice_gates(qc, psi, a):
qc.cx(psi, a)
qc.h(psi)
qr = QuantumRegister(3, name="q")
crz, crx = ClassicalRegister(1, name="crz"), ClassicalRegister(1, name="crx")
teleportation_circuit = QuantumCircuit(qr, crz, crx)
## STEP 1
create_bell_pair(teleportation_circuit, 1, 2)
## STEP 2
teleportation_circuit.barrier() # Use barrier to separate steps
alice_gates(teleportation_circuit, 0, 1)
teleportation_circuit.draw()
def measure_and_send(qc, a, b):
"""Measures qubits a & b and 'sends' the results to Bob"""
qc.barrier()
qc.measure(a,0)
qc.measure(b,1)
qr = QuantumRegister(3, name="q")
crz, crx = ClassicalRegister(1, name="crz"), ClassicalRegister(1, name="crx")
teleportation_circuit = QuantumCircuit(qr, crz, crx)
create_bell_pair(teleportation_circuit, 1, 2)
teleportation_circuit.barrier() # Use barrier to separate steps
alice_gates(teleportation_circuit, 0, 1)
measure_and_send(teleportation_circuit, 0 ,1)
teleportation_circuit.draw()
def bob_gates(qc, qubit, crz, crx):
qc.x(qubit).c_if(crx, 1) # Apply gates if the registers
qc.z(qubit).c_if(crz, 1) # are in the state '1'
qr = QuantumRegister(3, name="q")
crz, crx = ClassicalRegister(1, name="crz"), ClassicalRegister(1, name="crx")
teleportation_circuit = QuantumCircuit(qr, crz, crx)
## STEP 1
create_bell_pair(teleportation_circuit, 1, 2)
## STEP 2
teleportation_circuit.barrier() # Use barrier to separate steps
alice_gates(teleportation_circuit, 0, 1)
## STEP 3
measure_and_send(teleportation_circuit, 0, 1)
## STEP 4
teleportation_circuit.barrier() # Use barrier to separate steps
bob_gates(teleportation_circuit, 2, crz, crx)
teleportation_circuit.draw()
# Create random 1-qubit state
psi = random_statevector(2)
# Display it nicely
display(array_to_latex(psi, prefix="|\\psi\\rangle ="))
# Show it on a Bloch sphere
plot_bloch_multivector(psi)
init_gate = Initialize(psi)
init_gate.label = "init"
## SETUP
qr = QuantumRegister(3, name="q") # Protocol uses 3 qubits
crz = ClassicalRegister(1, name="crz") # and 2 classical registers
crx = ClassicalRegister(1, name="crx")
qc = QuantumCircuit(qr, crz, crx)
## STEP 0
# First, let's initialize Alice's q0
qc.append(init_gate, [0])
qc.barrier()
## STEP 1
# Now begins the teleportation protocol
create_bell_pair(qc, 1, 2)
qc.barrier()
## STEP 2
# Send q1 to Alice and q2 to Bob
alice_gates(qc, 0, 1)
## STEP 3
# Alice then sends her classical bits to Bob
measure_and_send(qc, 0, 1)
## STEP 4
# Bob decodes qubits
bob_gates(qc, 2, crz, crx)
# Display the circuit
qc.draw()
sim = Aer.get_backend('aer_simulator')
qc.save_statevector()
out_vector = sim.run(qc).result().get_statevector()
plot_bloch_multivector(out_vector)
|
https://github.com/swe-train/qiskit__qiskit
|
swe-train
|
# 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.
# pylint: disable=no-member,invalid-name,missing-docstring,no-name-in-module
# pylint: disable=attribute-defined-outside-init,unsubscriptable-object
from qiskit import transpile
from qiskit.transpiler import CouplingMap
from .utils import build_ripple_adder_circuit
class RippleAdderConstruction:
params = ([10, 50, 100, 200, 500],)
param_names = ["size"]
version = 1
timeout = 600
def time_build_ripple_adder(self, size):
build_ripple_adder_circuit(size)
class RippleAdderTranspile:
params = ([10, 20], [0, 1, 2, 3])
param_names = ["size", "level"]
version = 1
timeout = 600
def setup(self, size, _):
edge_len = int((2 * size + 2) ** 0.5) + 1
self.coupling_map = CouplingMap.from_grid(edge_len, edge_len)
self.circuit = build_ripple_adder_circuit(size)
def time_transpile_square_grid_ripple_adder(self, _, level):
transpile(
self.circuit,
coupling_map=self.coupling_map,
basis_gates=["u1", "u2", "u3", "cx", "id"],
optimization_level=level,
seed_transpiler=20220125,
)
def track_depth_transpile_square_grid_ripple_adder(self, _, level):
return transpile(
self.circuit,
coupling_map=self.coupling_map,
basis_gates=["u1", "u2", "u3", "cx", "id"],
optimization_level=level,
seed_transpiler=20220125,
).depth()
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# 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.
"""Tests for Stabilizerstate quantum state class."""
import unittest
from test import combine
import logging
from ddt import ddt, data, unpack
import numpy as np
from qiskit.test import QiskitTestCase
from qiskit import QuantumCircuit
from qiskit.quantum_info.random import random_clifford, random_pauli
from qiskit.quantum_info.states import StabilizerState, Statevector
from qiskit.circuit.library import IGate, XGate, HGate
from qiskit.quantum_info.operators import Clifford, Pauli, Operator
logger = logging.getLogger(__name__)
@ddt
class TestStabilizerState(QiskitTestCase):
"""Tests for StabilizerState class."""
rng = np.random.default_rng(12345)
samples = 10
shots = 1000
threshold = 0.1 * shots
@combine(num_qubits=[2, 3, 4, 5])
def test_init_clifford(self, num_qubits):
"""Test initialization from Clifford."""
stab1 = StabilizerState(random_clifford(num_qubits, seed=self.rng))
stab2 = StabilizerState(stab1)
self.assertEqual(stab1, stab2)
@combine(num_qubits=[2, 3, 4, 5])
def test_init_circuit(self, num_qubits):
"""Test initialization from a Clifford circuit."""
cliff = random_clifford(num_qubits, seed=self.rng)
stab1 = StabilizerState(cliff.to_circuit())
stab2 = StabilizerState(cliff)
self.assertEqual(stab1, stab2)
@combine(num_qubits=[2, 3, 4, 5])
def test_init_instruction(self, num_qubits):
"""Test initialization from a Clifford instruction."""
cliff = random_clifford(num_qubits, seed=self.rng)
stab1 = StabilizerState(cliff.to_instruction())
stab2 = StabilizerState(cliff)
self.assertEqual(stab1, stab2)
@combine(num_qubits=[2, 3, 4, 5])
def test_init_pauli(self, num_qubits):
"""Test initialization from pauli."""
pauli = random_pauli(num_qubits, seed=self.rng)
stab1 = StabilizerState(pauli)
stab2 = StabilizerState(stab1)
self.assertEqual(stab1, stab2)
@combine(num_qubits=[2, 3, 4, 5])
def test_to_operator(self, num_qubits):
"""Test to_operator method for returning projector."""
for _ in range(self.samples):
stab = StabilizerState(random_clifford(num_qubits, seed=self.rng))
target = Operator(stab)
op = StabilizerState(stab).to_operator()
self.assertEqual(op, target)
@combine(num_qubits=[2, 3, 4])
def test_trace(self, num_qubits):
"""Test trace methods"""
stab = StabilizerState(random_clifford(num_qubits, seed=self.rng))
trace = stab.trace()
self.assertEqual(trace, 1.0)
@combine(num_qubits=[2, 3, 4])
def test_purity(self, num_qubits):
"""Test purity methods"""
stab = StabilizerState(random_clifford(num_qubits, seed=self.rng))
purity = stab.purity()
self.assertEqual(purity, 1.0)
@combine(num_qubits=[2, 3])
def test_conjugate(self, num_qubits):
"""Test conjugate method."""
for _ in range(self.samples):
cliff = random_clifford(num_qubits, seed=self.rng)
target = StabilizerState(cliff.conjugate())
state = StabilizerState(cliff).conjugate()
self.assertEqual(state, target)
def test_tensor(self):
"""Test tensor method."""
for _ in range(self.samples):
cliff1 = random_clifford(2, seed=self.rng)
cliff2 = random_clifford(3, seed=self.rng)
stab1 = StabilizerState(cliff1)
stab2 = StabilizerState(cliff2)
target = StabilizerState(cliff1.tensor(cliff2))
state = stab1.tensor(stab2)
self.assertEqual(state, target)
def test_expand(self):
"""Test expand method."""
for _ in range(self.samples):
cliff1 = random_clifford(2, seed=self.rng)
cliff2 = random_clifford(3, seed=self.rng)
stab1 = StabilizerState(cliff1)
stab2 = StabilizerState(cliff2)
target = StabilizerState(cliff1.expand(cliff2))
state = stab1.expand(stab2)
self.assertEqual(state, target)
@combine(num_qubits=[2, 3, 4])
def test_evolve(self, num_qubits):
"""Test evolve method."""
for _ in range(self.samples):
cliff1 = random_clifford(num_qubits, seed=self.rng)
cliff2 = random_clifford(num_qubits, seed=self.rng)
stab1 = StabilizerState(cliff1)
stab2 = StabilizerState(cliff2)
target = StabilizerState(cliff1.compose(cliff2))
state = stab1.evolve(stab2)
self.assertEqual(state, target)
@combine(num_qubits_1=[4, 5, 6], num_qubits_2=[1, 2, 3])
def test_evolve_subsystem(self, num_qubits_1, num_qubits_2):
"""Test subsystem evolve method."""
for _ in range(self.samples):
cliff1 = random_clifford(num_qubits_1, seed=self.rng)
cliff2 = random_clifford(num_qubits_2, seed=self.rng)
stab1 = StabilizerState(cliff1)
stab2 = StabilizerState(cliff2)
qargs = sorted(np.random.choice(range(num_qubits_1), num_qubits_2, replace=False))
target = StabilizerState(cliff1.compose(cliff2, qargs))
state = stab1.evolve(stab2, qargs)
self.assertEqual(state, target)
def test_measure_single_qubit(self):
"""Test a measurement of a single qubit"""
for _ in range(self.samples):
cliff = Clifford(XGate())
stab = StabilizerState(cliff)
value = stab.measure()[0]
self.assertEqual(value, "1")
cliff = Clifford(IGate())
stab = StabilizerState(cliff)
value = stab.measure()[0]
self.assertEqual(value, "0")
cliff = Clifford(HGate())
stab = StabilizerState(cliff)
value = stab.measure()[0]
self.assertIn(value, ["0", "1"])
def test_measure_qubits(self):
"""Test a measurement of a subsystem of qubits"""
for _ in range(self.samples):
num_qubits = 4
qc = QuantumCircuit(num_qubits)
stab = StabilizerState(qc)
value = stab.measure()[0]
self.assertEqual(value, "0000")
value = stab.measure([0, 2])[0]
self.assertEqual(value, "00")
value = stab.measure([1])[0]
self.assertEqual(value, "0")
for i in range(num_qubits):
qc.x(i)
stab = StabilizerState(qc)
value = stab.measure()[0]
self.assertEqual(value, "1111")
value = stab.measure([2, 0])[0]
self.assertEqual(value, "11")
value = stab.measure([1])[0]
self.assertEqual(value, "1")
qc = QuantumCircuit(num_qubits)
qc.h(0)
stab = StabilizerState(qc)
value = stab.measure()[0]
self.assertIn(value, ["0000", "0001"])
value = stab.measure([0, 1])[0]
self.assertIn(value, ["00", "01"])
value = stab.measure([2])[0]
self.assertEqual(value, "0")
qc = QuantumCircuit(num_qubits)
qc.h(0)
qc.cx(0, 1)
qc.cx(0, 2)
qc.cx(0, 3)
stab = StabilizerState(qc)
value = stab.measure()[0]
self.assertIn(value, ["0000", "1111"])
value = stab.measure([3, 1])[0]
self.assertIn(value, ["00", "11"])
value = stab.measure([2])[0]
self.assertIn(value, ["0", "1"])
def test_reset_single_qubit(self):
"""Test reset method of a single qubit"""
empty_qc = QuantumCircuit(1)
for _ in range(self.samples):
cliff = Clifford(XGate())
stab = StabilizerState(cliff)
value = stab.reset([0])
target = StabilizerState(empty_qc)
self.assertEqual(value, target)
cliff = Clifford(HGate())
stab = StabilizerState(cliff)
value = stab.reset([0])
target = StabilizerState(empty_qc)
self.assertEqual(value, target)
def test_reset_qubits(self):
"""Test reset method of a subsystem of qubits"""
num_qubits = 3
qc = QuantumCircuit(num_qubits)
qc.h(0)
qc.cx(0, 1)
qc.cx(0, 2)
for _ in range(self.samples):
with self.subTest(msg="reset (None)"):
stab = StabilizerState(qc)
res = stab.reset()
value = res.measure()[0]
self.assertEqual(value, "000")
for _ in range(self.samples):
for qargs in [[0, 1, 2], [2, 1, 0], [1, 2, 0], [1, 0, 2]]:
with self.subTest(msg=f"reset (qargs={qargs})"):
stab = StabilizerState(qc)
res = stab.reset(qargs)
value = res.measure()[0]
self.assertEqual(value, "000")
for _ in range(self.samples):
with self.subTest(msg="reset ([0])"):
stab = StabilizerState(qc)
res = stab.reset([0])
value = res.measure()[0]
self.assertIn(value, ["000", "110"])
for _ in range(self.samples):
with self.subTest(msg="reset ([1])"):
stab = StabilizerState(qc)
res = stab.reset([1])
value = res.measure()[0]
self.assertIn(value, ["000", "101"])
for _ in range(self.samples):
with self.subTest(msg="reset ([2])"):
stab = StabilizerState(qc)
res = stab.reset([2])
value = res.measure()[0]
self.assertIn(value, ["000", "011"])
for _ in range(self.samples):
for qargs in [[0, 1], [1, 0]]:
with self.subTest(msg=f"reset (qargs={qargs})"):
stab = StabilizerState(qc)
res = stab.reset(qargs)
value = res.measure()[0]
self.assertIn(value, ["000", "100"])
for _ in range(self.samples):
for qargs in [[0, 2], [2, 0]]:
with self.subTest(msg=f"reset (qargs={qargs})"):
stab = StabilizerState(qc)
res = stab.reset(qargs)
value = res.measure()[0]
self.assertIn(value, ["000", "010"])
for _ in range(self.samples):
for qargs in [[1, 2], [2, 1]]:
with self.subTest(msg=f"reset (qargs={qargs})"):
stab = StabilizerState(qc)
res = stab.reset(qargs)
value = res.measure()[0]
self.assertIn(value, ["000", "001"])
def test_probablities_dict_single_qubit(self):
"""Test probabilities and probabilities_dict methods of a single qubit"""
num_qubits = 1
qc = QuantumCircuit(num_qubits)
for _ in range(self.samples):
with self.subTest(msg="P(id(0))"):
stab = StabilizerState(qc)
value = stab.probabilities_dict()
target = {"0": 1}
self.assertEqual(value, target)
probs = stab.probabilities()
target = np.array([1, 0])
self.assertTrue(np.allclose(probs, target))
qc.x(0)
for _ in range(self.samples):
with self.subTest(msg="P(x(0))"):
stab = StabilizerState(qc)
value = stab.probabilities_dict()
target = {"1": 1}
self.assertEqual(value, target)
probs = stab.probabilities()
target = np.array([0, 1])
self.assertTrue(np.allclose(probs, target))
qc = QuantumCircuit(num_qubits)
qc.h(0)
for _ in range(self.samples):
with self.subTest(msg="P(h(0))"):
stab = StabilizerState(qc)
value = stab.probabilities_dict()
target = {"0": 0.5, "1": 0.5}
self.assertEqual(value, target)
probs = stab.probabilities()
target = np.array([0.5, 0.5])
self.assertTrue(np.allclose(probs, target))
def test_probablities_dict_two_qubits(self):
"""Test probabilities and probabilities_dict methods of two qubits"""
num_qubits = 2
qc = QuantumCircuit(num_qubits)
qc.h(0)
stab = StabilizerState(qc)
for _ in range(self.samples):
with self.subTest(msg="P(None)"):
value = stab.probabilities_dict()
target = {"00": 0.5, "01": 0.5}
self.assertEqual(value, target)
probs = stab.probabilities()
target = np.array([0.5, 0.5, 0, 0])
self.assertTrue(np.allclose(probs, target))
for _ in range(self.samples):
with self.subTest(msg="P([0, 1])"):
value = stab.probabilities_dict([0, 1])
target = {"00": 0.5, "01": 0.5}
self.assertEqual(value, target)
probs = stab.probabilities([0, 1])
target = np.array([0.5, 0.5, 0, 0])
self.assertTrue(np.allclose(probs, target))
for _ in range(self.samples):
with self.subTest(msg="P([1, 0])"):
value = stab.probabilities_dict([1, 0])
target = {"00": 0.5, "10": 0.5}
self.assertEqual(value, target)
probs = stab.probabilities([1, 0])
target = np.array([0.5, 0, 0.5, 0])
self.assertTrue(np.allclose(probs, target))
for _ in range(self.samples):
with self.subTest(msg="P[0]"):
value = stab.probabilities_dict([0])
target = {"0": 0.5, "1": 0.5}
self.assertEqual(value, target)
probs = stab.probabilities([0])
target = np.array([0.5, 0.5])
self.assertTrue(np.allclose(probs, target))
for _ in range(self.samples):
with self.subTest(msg="P([1])"):
value = stab.probabilities_dict([1])
target = {"0": 1.0}
self.assertEqual(value, target)
probs = stab.probabilities([1])
target = np.array([1, 0])
self.assertTrue(np.allclose(probs, target))
def test_probablities_dict_qubits(self):
"""Test probabilities and probabilities_dict methods of a subsystem of qubits"""
num_qubits = 3
qc = QuantumCircuit(num_qubits)
qc.h(0)
qc.h(1)
qc.h(2)
stab = StabilizerState(qc)
for _ in range(self.samples):
with self.subTest(msg="P(None), decimals=1"):
value = stab.probabilities_dict(decimals=1)
target = {
"000": 0.1,
"001": 0.1,
"010": 0.1,
"011": 0.1,
"100": 0.1,
"101": 0.1,
"110": 0.1,
"111": 0.1,
}
self.assertEqual(value, target)
probs = stab.probabilities(decimals=1)
target = np.array([0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1])
self.assertTrue(np.allclose(probs, target))
for _ in range(self.samples):
with self.subTest(msg="P(None), decimals=2"):
value = stab.probabilities_dict(decimals=2)
target = {
"000": 0.12,
"001": 0.12,
"010": 0.12,
"011": 0.12,
"100": 0.12,
"101": 0.12,
"110": 0.12,
"111": 0.12,
}
self.assertEqual(value, target)
probs = stab.probabilities(decimals=2)
target = np.array([0.12, 0.12, 0.12, 0.12, 0.12, 0.12, 0.12, 0.12])
self.assertTrue(np.allclose(probs, target))
for _ in range(self.samples):
with self.subTest(msg="P(None), decimals=3"):
value = stab.probabilities_dict(decimals=3)
target = {
"000": 0.125,
"001": 0.125,
"010": 0.125,
"011": 0.125,
"100": 0.125,
"101": 0.125,
"110": 0.125,
"111": 0.125,
}
self.assertEqual(value, target)
probs = stab.probabilities(decimals=3)
target = np.array([0.125, 0.125, 0.125, 0.125, 0.125, 0.125, 0.125, 0.125])
self.assertTrue(np.allclose(probs, target))
def test_probablities_dict_ghz(self):
"""Test probabilities and probabilities_dict method of a subsystem of qubits"""
num_qubits = 3
qc = QuantumCircuit(num_qubits)
qc.h(0)
qc.cx(0, 1)
qc.cx(0, 2)
with self.subTest(msg="P(None)"):
stab = StabilizerState(qc)
value = stab.probabilities_dict()
target = {"000": 0.5, "111": 0.5}
self.assertEqual(value, target)
probs = stab.probabilities()
target = np.array([0.5, 0, 0, 0, 0, 0, 0, 0.5])
self.assertTrue(np.allclose(probs, target))
# 3-qubit qargs
for qargs in [[0, 1, 2], [2, 1, 0], [1, 2, 0], [1, 0, 2]]:
with self.subTest(msg=f"P({qargs})"):
probs = stab.probabilities_dict(qargs)
target = {"000": 0.5, "111": 0.5}
self.assertDictAlmostEqual(probs, target)
probs = stab.probabilities(qargs)
target = np.array([0.5, 0, 0, 0, 0, 0, 0, 0.5])
self.assertTrue(np.allclose(probs, target))
# 2-qubit qargs
for qargs in [[0, 1], [2, 1], [1, 0], [1, 2]]:
with self.subTest(msg=f"P({qargs})"):
probs = stab.probabilities_dict(qargs)
target = {"00": 0.5, "11": 0.5}
self.assertDictAlmostEqual(probs, target)
probs = stab.probabilities(qargs)
target = np.array([0.5, 0, 0, 0.5])
self.assertTrue(np.allclose(probs, target))
# 1-qubit qargs
for qargs in [[0], [1], [2]]:
with self.subTest(msg=f"P({qargs})"):
probs = stab.probabilities_dict(qargs)
target = {"0": 0.5, "1": 0.5}
self.assertDictAlmostEqual(probs, target)
probs = stab.probabilities(qargs)
target = np.array([0.5, 0.5])
self.assertTrue(np.allclose(probs, target))
@combine(num_qubits=[2, 3, 4])
def test_probs_random_subsystem(self, num_qubits):
"""Test probabilities and probabilities_dict methods
of random cliffords for a subsystem of qubits"""
for _ in range(self.samples):
for subsystem_size in range(1, num_qubits):
cliff = random_clifford(num_qubits, seed=self.rng)
qargs = np.random.choice(num_qubits, size=subsystem_size, replace=False)
qc = cliff.to_circuit()
stab = StabilizerState(cliff)
probs = stab.probabilities(qargs)
probs_dict = stab.probabilities_dict(qargs)
target = Statevector(qc).probabilities(qargs)
target_dict = Statevector(qc).probabilities_dict(qargs)
self.assertTrue(np.allclose(probs, target))
self.assertDictAlmostEqual(probs_dict, target_dict)
@combine(num_qubits=[2, 3, 4, 5])
def test_expval_from_random_clifford(self, num_qubits):
"""Test that the expectation values for a random Clifford,
where the Pauli operators are all its stabilizers,
are equal to 1."""
for _ in range(self.samples):
cliff = random_clifford(num_qubits, seed=self.rng)
qc = cliff.to_circuit()
stab = StabilizerState(qc)
stab_gen = stab.clifford.to_dict()["stabilizer"]
for i in range(num_qubits):
op = Pauli(stab_gen[i])
exp_val = stab.expectation_value(op)
self.assertEqual(exp_val, 1)
def test_sample_counts_reset_bell(self):
"""Test sample_counts after reset for Bell state"""
num_qubits = 2
qc = QuantumCircuit(num_qubits)
qc.h(0)
qc.cx(0, 1)
stab = StabilizerState(qc)
target = {"00": self.shots / 2, "10": self.shots / 2}
counts = {"00": 0, "10": 0}
for _ in range(self.shots):
res = stab.reset([0])
value = res.measure()[0]
counts[value] += 1
self.assertDictAlmostEqual(counts, target, self.threshold)
target = {"00": self.shots / 2, "01": self.shots / 2}
counts = {"00": 0, "01": 0}
for _ in range(self.shots):
res = stab.reset([1])
value = res.measure()[0]
counts[value] += 1
self.assertDictAlmostEqual(counts, target, self.threshold)
def test_sample_counts_memory_ghz(self):
"""Test sample_counts and sample_memory method for GHZ state"""
num_qubits = 3
qc = QuantumCircuit(num_qubits)
qc.h(0)
qc.cx(0, 1)
qc.cx(0, 2)
stab = StabilizerState(qc)
# 3-qubit qargs
target = {"000": self.shots / 2, "111": self.shots / 2}
for qargs in [[0, 1, 2], [2, 1, 0], [1, 2, 0], [1, 0, 2]]:
with self.subTest(msg=f"counts (qargs={qargs})"):
counts = stab.sample_counts(self.shots, qargs=qargs)
self.assertDictAlmostEqual(counts, target, self.threshold)
with self.subTest(msg=f"memory (qargs={qargs})"):
memory = stab.sample_memory(self.shots, qargs=qargs)
self.assertEqual(len(memory), self.shots)
self.assertEqual(set(memory), set(target))
# 2-qubit qargs
target = {"00": self.shots / 2, "11": self.shots / 2}
for qargs in [[0, 1], [2, 1], [1, 2], [1, 0]]:
with self.subTest(msg=f"counts (qargs={qargs})"):
counts = stab.sample_counts(self.shots, qargs=qargs)
self.assertDictAlmostEqual(counts, target, self.threshold)
with self.subTest(msg=f"memory (qargs={qargs})"):
memory = stab.sample_memory(self.shots, qargs=qargs)
self.assertEqual(len(memory), self.shots)
self.assertEqual(set(memory), set(target))
# 1-qubit qargs
target = {"0": self.shots / 2, "1": self.shots / 2}
for qargs in [[0], [1], [2]]:
with self.subTest(msg=f"counts (qargs={qargs})"):
counts = stab.sample_counts(self.shots, qargs=qargs)
self.assertDictAlmostEqual(counts, target, self.threshold)
with self.subTest(msg=f"memory (qargs={qargs})"):
memory = stab.sample_memory(self.shots, qargs=qargs)
self.assertEqual(len(memory), self.shots)
self.assertEqual(set(memory), set(target))
def test_sample_counts_memory_superposition(self):
"""Test sample_counts and sample_memory method of a 3-qubit superposition"""
num_qubits = 3
qc = QuantumCircuit(num_qubits)
qc.h(0)
qc.h(1)
qc.h(2)
stab = StabilizerState(qc)
# 3-qubit qargs
target = {
"000": self.shots / 8,
"001": self.shots / 8,
"010": self.shots / 8,
"011": self.shots / 8,
"100": self.shots / 8,
"101": self.shots / 8,
"110": self.shots / 8,
"111": self.shots / 8,
}
for qargs in [[0, 1, 2], [2, 1, 0], [1, 2, 0], [1, 0, 2]]:
with self.subTest(msg=f"counts (qargs={qargs})"):
counts = stab.sample_counts(self.shots, qargs=qargs)
self.assertDictAlmostEqual(counts, target, self.threshold)
with self.subTest(msg=f"memory (qargs={qargs})"):
memory = stab.sample_memory(self.shots, qargs=qargs)
self.assertEqual(len(memory), self.shots)
self.assertEqual(set(memory), set(target))
# 2-qubit qargs
target = {
"00": self.shots / 4,
"01": self.shots / 4,
"10": self.shots / 4,
"11": self.shots / 4,
}
for qargs in [[0, 1], [2, 1], [1, 2], [1, 0]]:
with self.subTest(msg=f"counts (qargs={qargs})"):
counts = stab.sample_counts(self.shots, qargs=qargs)
self.assertDictAlmostEqual(counts, target, self.threshold)
with self.subTest(msg=f"memory (qargs={qargs})"):
memory = stab.sample_memory(self.shots, qargs=qargs)
self.assertEqual(len(memory), self.shots)
self.assertEqual(set(memory), set(target))
# 1-qubit qargs
target = {"0": self.shots / 2, "1": self.shots / 2}
for qargs in [[0], [1], [2]]:
with self.subTest(msg=f"counts (qargs={qargs})"):
counts = stab.sample_counts(self.shots, qargs=qargs)
self.assertDictAlmostEqual(counts, target, self.threshold)
with self.subTest(msg=f"memory (qargs={qargs})"):
memory = stab.sample_memory(self.shots, qargs=qargs)
self.assertEqual(len(memory), self.shots)
self.assertEqual(set(memory), set(target))
@ddt
class TestStabilizerStateExpectationValue(QiskitTestCase):
"""Tests for StabilizerState.expectation_value method."""
rng = np.random.default_rng(12345)
samples = 10
shots = 1000
threshold = 0.1 * shots
@data(("Z", 1), ("X", 0), ("Y", 0), ("I", 1), ("Z", 1), ("-Z", -1), ("iZ", 1j), ("-iZ", -1j))
@unpack
def test_expval_single_qubit_0(self, label, target):
"""Test expectation_value method of a single qubit on |0>"""
qc = QuantumCircuit(1)
stab = StabilizerState(qc)
op = Pauli(label)
expval = stab.expectation_value(op)
self.assertEqual(expval, target)
@data(("Z", -1), ("X", 0), ("Y", 0), ("I", 1))
@unpack
def test_expval_single_qubit_1(self, label, target):
"""Test expectation_value method of a single qubit on |1>"""
qc = QuantumCircuit(1)
qc.x(0)
stab = StabilizerState(qc)
op = Pauli(label)
expval = stab.expectation_value(op)
self.assertEqual(expval, target)
@data(("Z", 0), ("X", 1), ("Y", 0), ("I", 1), ("X", 1), ("-X", -1), ("iX", 1j), ("-iX", -1j))
@unpack
def test_expval_single_qubit_plus(self, label, target):
"""Test expectation_value method of a single qubit on |+>"""
qc = QuantumCircuit(1)
qc.h(0)
stab = StabilizerState(qc)
op = Pauli(label)
expval = stab.expectation_value(op)
self.assertEqual(expval, target)
@data(
("II", 1),
("XX", 0),
("YY", 0),
("ZZ", 1),
("IX", 0),
("IY", 0),
("IZ", 1),
("XY", 0),
("XZ", 0),
("YZ", 0),
("-ZZ", -1),
("iZZ", 1j),
("-iZZ", -1j),
)
@unpack
def test_expval_two_qubits_00(self, label, target):
"""Test expectation_value method of two qubits in |00>"""
num_qubits = 2
qc = QuantumCircuit(num_qubits)
stab = StabilizerState(qc)
op = Pauli(label)
expval = stab.expectation_value(op)
self.assertEqual(expval, target)
@data(
("II", 1),
("XX", 0),
("YY", 0),
("ZZ", 1),
("IX", 0),
("IY", 0),
("IZ", -1),
("XY", 0),
("XZ", 0),
("YZ", 0),
)
@unpack
def test_expval_two_qubits_11(self, label, target):
"""Test expectation_value method of two qubits in |11>"""
qc = QuantumCircuit(2)
qc.x(0)
qc.x(1)
stab = StabilizerState(qc)
op = Pauli(label)
expval = stab.expectation_value(op)
self.assertEqual(expval, target)
@data(
("II", 1),
("XX", 1),
("YY", 0),
("ZZ", 0),
("IX", 1),
("IY", 0),
("IZ", 0),
("XY", 0),
("XZ", 0),
("YZ", 0),
("-XX", -1),
("iXX", 1j),
("-iXX", -1j),
)
@unpack
def test_expval_two_qubits_plusplus(self, label, target):
"""Test expectation_value method of two qubits in |++>"""
qc = QuantumCircuit(2)
qc.h(0)
qc.h(1)
stab = StabilizerState(qc)
op = Pauli(label)
expval = stab.expectation_value(op)
self.assertEqual(expval, target)
@data(
("II", 1),
("XX", 0),
("YY", 0),
("ZZ", 0),
("IX", 0),
("IY", 0),
("IZ", -1),
("XY", 0),
("XZ", -1),
("YZ", 0),
)
@unpack
def test_expval_two_qubits_plus1(self, label, target):
"""Test expectation_value method of two qubits in |+1>"""
qc = QuantumCircuit(2)
qc.x(0)
qc.h(1)
stab = StabilizerState(qc)
op = Pauli(label)
expval = stab.expectation_value(op)
self.assertEqual(expval, target)
@data(
("II", 1),
("XX", 1),
("YY", -1),
("ZZ", 1),
("IX", 0),
("IY", 0),
("IZ", 0),
("XY", 0),
("XZ", 0),
("YZ", 0),
("-YY", 1),
("iYY", -1j),
("-iYY", 1j),
)
@unpack
def test_expval_two_qubits_bell_phi_plus(self, label, target):
"""Test expectation_value method of two qubits in bell phi plus"""
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
stab = StabilizerState(qc)
op = Pauli(label)
expval = stab.expectation_value(op)
self.assertEqual(expval, target)
@data(
("II", 1),
("XX", 1),
("YY", 1),
("ZZ", -1),
("IX", 0),
("IY", 0),
("IZ", 0),
("XY", 0),
("XZ", 0),
("YZ", 0),
("-XX", -1),
("-YY", -1),
("iXX", 1j),
("iYY", 1j),
("-iXX", -1j),
("-iYY", -1j),
)
@unpack
def test_expval_two_qubits_bell_phi_minus(self, label, target):
"""Test expectation_value method of two qubits in bell phi minus"""
qc = QuantumCircuit(2)
qc.h(0)
qc.x(1)
qc.cx(0, 1)
stab = StabilizerState(qc)
op = Pauli(label)
expval = stab.expectation_value(op)
self.assertEqual(expval, target)
@data(
("II", 1),
("XX", 1),
("YY", 1),
("ZZ", -1),
("IX", 0),
("IY", 0),
("IZ", 0),
("XY", 0),
("XZ", 0),
("YZ", 0),
("-XX", -1),
("-YY", -1),
("iXX", 1j),
("iYY", 1j),
("-iXX", -1j),
("-iYY", -1j),
)
@unpack
def test_expval_two_qubits_bell_sdg_h(self, label, target):
"""Test expectation_value method of two qubits in bell followed by sdg and h"""
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
qc.sdg(0)
qc.sdg(1)
qc.h(0)
qc.h(1)
stab = StabilizerState(qc)
op = Pauli(label)
expval = stab.expectation_value(op)
self.assertEqual(expval, target)
@combine(num_qubits=[2, 3, 4, 5])
def test_expval_random(self, num_qubits):
"""Test expectation_value method of random Cliffords"""
for _ in range(self.samples):
cliff = random_clifford(num_qubits, seed=self.rng)
op = random_pauli(num_qubits, group_phase=True, seed=self.rng)
qc = cliff.to_circuit()
stab = StabilizerState(cliff)
exp_val = stab.expectation_value(op)
target = Statevector(qc).expectation_value(op)
self.assertAlmostEqual(exp_val, target)
@combine(num_qubits=[2, 3, 4, 5])
def test_expval_random_subsystem(self, num_qubits):
"""Test expectation_value method of random Cliffords and a subsystem"""
for _ in range(self.samples):
cliff = random_clifford(num_qubits, seed=self.rng)
op = random_pauli(2, group_phase=True, seed=self.rng)
qargs = np.random.choice(num_qubits, size=2, replace=False)
qc = cliff.to_circuit()
stab = StabilizerState(cliff)
exp_val = stab.expectation_value(op, qargs)
target = Statevector(qc).expectation_value(op, qargs)
self.assertAlmostEqual(exp_val, target)
def test_stabilizer_bell_equiv(self):
"""Test that two circuits produce the same stabilizer group."""
qc1 = QuantumCircuit(2)
qc1.h(0)
qc1.x(1)
qc1.cx(0, 1)
qc2 = QuantumCircuit(2)
qc2.h(0)
qc2.cx(0, 1)
qc2.sdg(0)
qc2.sdg(1)
qc2.h(0)
qc2.h(1)
qc3 = QuantumCircuit(2)
qc3.h(0)
qc3.cx(0, 1)
qc4 = QuantumCircuit(2)
qc4.h(0)
qc4.cx(0, 1)
qc4.s(0)
qc4.sdg(1)
qc4.h(0)
qc4.h(1)
cliff1 = StabilizerState(qc1) # ['+XX', '-ZZ']
cliff2 = StabilizerState(qc2) # ['+YY', '+XX']
cliff3 = StabilizerState(qc3) # ['+XX', '+ZZ']
cliff4 = StabilizerState(qc4) # ['-YY', '+XX']
# [XX, -ZZ] and [XX, YY] both generate the stabilizer group {II, XX, YY, -ZZ}
self.assertTrue(cliff1.equiv(cliff2))
self.assertEqual(cliff1.probabilities_dict(), cliff2.probabilities_dict())
# [XX, ZZ] and [XX, -YY] both generate the stabilizer group {II, XX, -YY, ZZ}
self.assertTrue(cliff3.equiv(cliff4))
self.assertEqual(cliff3.probabilities_dict(), cliff4.probabilities_dict())
self.assertFalse(cliff1.equiv(cliff3))
self.assertFalse(cliff2.equiv(cliff4))
if __name__ == "__main__":
unittest.main()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit_optimization import QuadraticProgram
from qiskit_optimization.translators import from_docplex_mp
# Make a Docplex model
from docplex.mp.model import Model
mdl = Model("docplex model")
x = mdl.binary_var("x")
y = mdl.integer_var(lb=-1, ub=5, name="y")
mdl.minimize(x + 2 * y)
mdl.add_constraint(x - y == 3)
mdl.add_constraint((x + y) * (x - y) <= 1)
print(mdl.export_as_lp_string())
# load from a Docplex model
mod = from_docplex_mp(mdl)
print(type(mod))
print()
print(mod.prettyprint())
# make an empty problem
mod = QuadraticProgram("my problem")
print(mod.prettyprint())
# Add variables
mod.binary_var(name="x")
mod.integer_var(name="y", lowerbound=-1, upperbound=5)
mod.continuous_var(name="z", lowerbound=-1, upperbound=5)
print(mod.prettyprint())
# Add objective function using dictionaries
mod.minimize(constant=3, linear={"x": 1}, quadratic={("x", "y"): 2, ("z", "z"): -1})
print(mod.prettyprint())
# Add objective function using lists/arrays
mod.minimize(constant=3, linear=[1, 0, 0], quadratic=[[0, 1, 0], [1, 0, 0], [0, 0, -1]])
print(mod.prettyprint())
print("constant:\t\t\t", mod.objective.constant)
print("linear dict:\t\t\t", mod.objective.linear.to_dict())
print("linear array:\t\t\t", mod.objective.linear.to_array())
print("linear array as sparse matrix:\n", mod.objective.linear.coefficients, "\n")
print("quadratic dict w/ index:\t", mod.objective.quadratic.to_dict())
print("quadratic dict w/ name:\t\t", mod.objective.quadratic.to_dict(use_name=True))
print(
"symmetric quadratic dict w/ name:\t",
mod.objective.quadratic.to_dict(use_name=True, symmetric=True),
)
print("quadratic matrix:\n", mod.objective.quadratic.to_array(), "\n")
print("symmetric quadratic matrix:\n", mod.objective.quadratic.to_array(symmetric=True), "\n")
print("quadratic matrix as sparse matrix:\n", mod.objective.quadratic.coefficients)
# Add linear constraints
mod.linear_constraint(linear={"x": 1, "y": 2}, sense="==", rhs=3, name="lin_eq")
mod.linear_constraint(linear={"x": 1, "y": 2}, sense="<=", rhs=3, name="lin_leq")
mod.linear_constraint(linear={"x": 1, "y": 2}, sense=">=", rhs=3, name="lin_geq")
print(mod.prettyprint())
# Add quadratic constraints
mod.quadratic_constraint(
linear={"x": 1, "y": 1},
quadratic={("x", "x"): 1, ("y", "z"): -1},
sense="==",
rhs=1,
name="quad_eq",
)
mod.quadratic_constraint(
linear={"x": 1, "y": 1},
quadratic={("x", "x"): 1, ("y", "z"): -1},
sense="<=",
rhs=1,
name="quad_leq",
)
mod.quadratic_constraint(
linear={"x": 1, "y": 1},
quadratic={("x", "x"): 1, ("y", "z"): -1},
sense=">=",
rhs=1,
name="quad_geq",
)
print(mod.prettyprint())
lin_geq = mod.get_linear_constraint("lin_geq")
print("lin_geq:", lin_geq.linear.to_dict(use_name=True), lin_geq.sense, lin_geq.rhs)
quad_geq = mod.get_quadratic_constraint("quad_geq")
print(
"quad_geq:",
quad_geq.linear.to_dict(use_name=True),
quad_geq.quadratic.to_dict(use_name=True),
quad_geq.sense,
lin_geq.rhs,
)
# Remove constraints
mod.remove_linear_constraint("lin_eq")
mod.remove_quadratic_constraint("quad_leq")
print(mod.prettyprint())
sub = mod.substitute_variables(constants={"x": 0}, variables={"y": ("z", -1)})
print(sub.prettyprint())
sub = mod.substitute_variables(constants={"x": -1})
print(sub.status)
from qiskit_optimization import QiskitOptimizationError
try:
sub = mod.substitute_variables(constants={"x": -1}, variables={"y": ("x", 1)})
except QiskitOptimizationError as e:
print("Error: {}".format(e))
mod = QuadraticProgram()
mod.binary_var(name="e")
mod.binary_var(name="f")
mod.continuous_var(name="g")
mod.minimize(linear=[1, 2, 3])
print(mod.export_as_lp_string())
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/swe-train/qiskit__qiskit
|
swe-train
|
# -*- 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/minnukota381/Quantum-Computing-Qiskit
|
minnukota381
|
from qiskit import *
from qiskit.visualization import plot_bloch_multivector, visualize_transition, plot_histogram
# Create a quantum circuit with 2 qubits
# The default initial state of qubits will be |0> or [1,0]
qc = QuantumCircuit(2)
a = 0
b = 1
#Applying the x gate to change a to |1>, b will be |0> itself
qc.x(a)
#apply the swap gate to both qubits
qc.swap(0,1)
#Draw the circuit
qc.draw('mpl')
#Get the backend for the circuit to display unitary matrix
backend = Aer.get_backend('unitary_simulator')
#execute the circuit using the backend
out = execute(qc,backend).result().get_unitary()
#import qiskit_textbook and display the combined unitary matrix
from qiskit_textbook.tools import array_to_latex
array_to_latex(out, pretext = "\\text{UnitaryMatrix} = ")
#Get the backend for the circuit (simulator or realtime system)
backend = Aer.get_backend('statevector_simulator')
#execute the circuit using the backend
out = execute(qc,backend).result().get_statevector()
#import qiskit_textbook and display the statevector
#from qiskit_textbook.tools import array_to_latex
array_to_latex(out, pretext = "\\text{Statevector} = ")
#plot the result as a bloch sphere visualization
plot_bloch_multivector(out)
#execute the circuit and get the plain result
out = execute(qc,backend).result()
#getting the count of the result
counts = out.get_counts()
#plotting the histogram
plot_histogram(counts)
|
https://github.com/electricalgorithm/QuantumFourierTransform
|
electricalgorithm
|
"""
This module contains the Quantum Fourier Transform class.
"""
from numpy import pi
from qiskit import QuantumCircuit, Aer, transpile, assemble
class QuantumFourierTransform:
"""Class for operations of the Quantum Fourier Transform."""
@staticmethod
def simulate(state: int) -> dict:
"""Simulate the QFT and iQFT.
Parameters
----------
state (int): The state to simulate.
Returns
-------
dict: The simulated state.
"""
# Get the number of qubits.
qubit_count = state.bit_length()
# Create the circuit.
circuit = QuantumCircuit(qubit_count, qubit_count)
# Apply the initial state.
for qubit in range(qubit_count):
if state & (1 << qubit):
circuit.x(qubit)
# Apply the QFT.
circuit = QuantumFourierTransform.qft(circuit)
# Apply the inverse QFT.
circuit = QuantumFourierTransform.iqft(circuit)
# Append the measurement.
circuit.measure(range(qubit_count), range(qubit_count))
# Run the simulation.
simulator = Aer.get_backend("aer_simulator")
circuit = transpile(circuit, simulator)
job = simulator.run(assemble(circuit))
result = job.result().get_counts()
answer_as_list = list(result.keys())
answer_int = int(answer_as_list[0], 2)
return {"result": answer_int}
@staticmethod
def qft(circuit: QuantumCircuit) -> QuantumCircuit:
"""Apply QFT to a circuit.
Parameters
----------
circuit (QuantumCircuit): The circuit to apply the QFT to.
Returns
-------
QuantumCircuit: The circuit with the QFT applied.
"""
# Apply the QFT to the circuit.
circuit = QuantumFourierTransform._qft_append_circuit(
circuit, circuit.num_qubits - 1
)
# Apply the swaps to the circuit.
circuit = QuantumFourierTransform._qft_append_swaps(circuit)
return circuit
@staticmethod
def qft_circuit(qubit_count: int) -> QuantumCircuit:
"""Create a QFT circuit with given Qubit count.
Parameters
----------
qubit_count : int
The number of qubits to use in the circuit.
Returns
-------
QuantumCircuit
The QFT circuit.
"""
return QuantumFourierTransform.qft(QuantumCircuit(qubit_count))
@staticmethod
def iqft_circuit(qubit_count: int) -> QuantumCircuit:
"""Create a iQFT circuit with given Qubit count.
Parameters
----------
qubit_count : int
The number of qubits to use in the circuit.
Returns
-------
QuantumCircuit
The iQFT circuit.
"""
return QuantumFourierTransform.iqft(QuantumCircuit(qubit_count))
@staticmethod
def iqft(circuit: QuantumCircuit) -> QuantumCircuit:
"""Apply inverse QFT to a circuit.
Parameters
----------
circuit (QuantumCircuit): The circuit to apply the IQFT to.
Returns
-------
QuantumCircuit: The circuit with the iQFT applied.
"""
# Apply the swaps to the circuit.
circuit = QuantumFourierTransform._qft_append_swaps(circuit, inverse=True)
circuit.barrier()
# Apply the QFT to the circuit.
circuit = QuantumFourierTransform._iqft_append_circuit(circuit, 0)
return circuit
@staticmethod
def _qft_append_circuit(circuit: QuantumCircuit, qubit: int) -> QuantumCircuit:
"""Apply a rotation to a qubit.
Parameters
----------
circuit (QuantumCircuit): The circuit to apply the rotation to.
qubit (int): The qubit to apply the rotation to.
Returns
-------
QuantumCircuit: The circuit with the rotation applied.
"""
# Recursive stop condition.
if qubit < 0:
return circuit
# Construct the minimal QFT circuit.
circuit.h(qubit)
for qubit_line in reversed(range(qubit)):
circuit.cp(pi / 2 ** (qubit - qubit_line), qubit_line, qubit)
circuit.barrier()
# Recursively apply the QFT to the next qubit.
return QuantumFourierTransform._qft_append_circuit(circuit, qubit - 1)
@staticmethod
def _iqft_append_circuit(circuit: QuantumCircuit, qubit: int) -> QuantumCircuit:
"""Apply a rotation to a qubit.
Parameters
----------
circuit (QuantumCircuit): The circuit to apply the rotation to.
qubit (int): The qubit to apply the rotation to.
Returns
-------
QuantumCircuit: The circuit with the rotation applied.
"""
# Recursive stop condition.
if qubit >= circuit.num_qubits:
return circuit
# Construct the minimal QFT circuit.
for qubit_line in range(qubit):
circuit.cp(-pi / 2 ** (qubit - qubit_line), qubit_line, qubit)
circuit.h(qubit)
circuit.barrier()
# Recursively apply the QFT to the next qubit.
return QuantumFourierTransform._iqft_append_circuit(circuit, qubit + 1)
@staticmethod
def _qft_append_swaps(
circuit: QuantumCircuit, inverse: bool = False
) -> QuantumCircuit:
"""Apply swaps to a circuit.
Parameters
----------
circuit (QuantumCircuit): The circuit to apply the swaps to.
qubit (int): The qubit to apply the rotation to.
Returns
-------
QuantumCircuit: The circuit with the swaps applied.
"""
qubit_count = circuit.num_qubits
qubits_list = (
reversed(range(qubit_count // 2))
if not inverse
else range(qubit_count // 2)
)
for qubit in qubits_list:
circuit.swap(qubit, qubit_count - qubit - 1)
return circuit
if __name__ == "__main__":
print("===================================")
print("Quantum Fourier Transform Simulator")
print("===================================")
# Get the input state as integer decimal.
state_int = int(input("> Enter the state as decimal integer: "))
# Run the algorithm.
result = QuantumFourierTransform.simulate(state_int)
print(f"iQFT result: {result['result']}")
|
https://github.com/Qiskit/feedback
|
Qiskit
|
import os
print(f"Working directory: '{os.getcwd()}'")
from test.python.transpiler.aqc.sample_data import ORIGINAL_CIRCUIT, INITIAL_THETAS
import numpy as np
from scipy.stats import unitary_group
from time import perf_counter
from qiskit import QuantumCircuit
from qiskit.algorithms.optimizers import L_BFGS_B
from qiskit.quantum_info import Operator
from qiskit.transpiler.synthesis.aqc.aqc import AQC
from qiskit.transpiler.synthesis.aqc.cnot_structures import make_cnot_network
from qiskit.transpiler.synthesis.aqc.cnot_unit_circuit import CNOTUnitCircuit
from qiskit.transpiler.synthesis.aqc.cnot_unit_objective import DefaultCNOTUnitObjective
from qiskit.transpiler.synthesis.aqc.fast_gradient.fast_gradient import FastCNOTUnitObjective
def print_misfits(target_mat: np.ndarray, approx_circ: QuantumCircuit, exe_tm: float):
"""
Calculates and prints out misfit measures.
"""
dim = target_mat.shape[0]
approx_mat = Operator(approx_circ).data
diff = approx_mat - target_mat
hs = np.vdot(approx_mat, target_mat) # HS == Tr(V.H @ U)
fidelity = (1.0 + np.abs(hs) ** 2 / dim) / (dim + 1)
fro_err = 0.5 * (np.linalg.norm(diff, "fro") ** 2) / dim
sin_err = np.linalg.norm(diff, 2)
print("\nApproximation misfit:")
print(f"Cost function based on Frobenius norm: {fro_err:0.5f}")
print(f"Fidelity: {fidelity:0.5f}")
print(f"Max. singular value of (V - U): {sin_err:0.5f}")
print(f"Execution time: {exe_tm:0.3f} secs")
print()
def make_target_matrix(num_qubits: int, target_name: str):
"""Creats a target matrix for testing."""
if target_name == "mcx":
# Define the target matrix: multi-control CNOT gate matrix.
target_matrix = np.eye(2**num_qubits, dtype=np.cfloat)
target_matrix[-2:, -2:] = [[0, 1], [1, 0]]
else:
# Define a random SU target matrix.
dim = 2 ** num_qubits
target_matrix = unitary_group.rvs(dim)
target_matrix /= (np.linalg.det(target_matrix) ** (1.0 / float(dim)))
return target_matrix
def create_circuit_and_objective(num_qubits: int, cnots: np.ndarray, fast: bool):
"""Instantiates AQC circuit and objective classes."""
circ = CNOTUnitCircuit(num_qubits, cnots)
if fast:
objv = FastCNOTUnitObjective(num_qubits, cnots)
else:
objv = DefaultCNOTUnitObjective(num_qubits, cnots)
return circ, objv
def aqc_example_hardcoded(fast: bool):
tic = perf_counter()
print(f"{'-' * 80}\nRunning \"{'accelerated' if fast else 'default'}\" "
f"AQC implementation on a hardcoded target matrix...\n{'-' * 80}")
# Define the number of qubits, circuit layout and other parameters.
seed = 12345
num_qubits = int(round(np.log2(ORIGINAL_CIRCUIT.shape[0])))
depth = 0 # depth=0 implies maximum depth
cnots = make_cnot_network(
num_qubits=num_qubits, network_layout="spin", connectivity_type="full", depth=depth
)
# Define the target matrix.
target_matrix = ORIGINAL_CIRCUIT
# Create instances of the optimizer, AQC, circuit and objective classes.
optimizer = L_BFGS_B(maxiter=200)
circ, objv = create_circuit_and_objective(num_qubits, cnots, fast=fast)
aqc = AQC(optimizer=optimizer, seed=seed)
# Optimize the circuit to approximate the target matrix.
aqc.compile_unitary(
target_matrix=target_matrix,
approximate_circuit=circ,
approximating_objective=objv,
initial_point=INITIAL_THETAS,
)
toc = perf_counter()
print_misfits(target_matrix, circ, toc - tic)
aqc_example_hardcoded(fast=False)
aqc_example_hardcoded(fast=True)
def aqc_example(target_name: str, depth: int, fast: bool):
tic = perf_counter()
print(f"{'-' * 80}\nRunning {'accelerated' if fast else 'default'} AQC on "
f"'{target_name}' target matrix with random initial guess...\n{'-' * 80}")
# Define the number of qubits, circuit layout and other parameters.
seed = 777
np.random.seed(seed)
num_qubits = int(4)
cnots = make_cnot_network(
num_qubits=num_qubits, network_layout="spin", connectivity_type="full", depth=depth
)
# Define a target matrix:
target_matrix = make_target_matrix(num_qubits, target_name)
# Create instances of the optimizer, AQC, circuit and objective classes.
optimizer = L_BFGS_B(maxiter=1500)
circ, objv = create_circuit_and_objective(num_qubits, cnots, fast=fast)
aqc = AQC(optimizer=optimizer, seed=seed)
# Optimize the circuit to approximate the target matrix.
aqc.compile_unitary(
target_matrix=target_matrix,
approximate_circuit=circ,
approximating_objective=objv,
initial_point=2 * np.pi * np.random.rand(objv.num_thetas),
)
toc = perf_counter()
print_misfits(target_matrix, circ, toc - tic)
depth = 64
print(f"\n\n******* Circuit depth = {depth}: *******\n")
aqc_example("random", depth, fast=True)
aqc_example("mcx", depth, fast=True)
depth = 40
print(f"\n\n******* Circuit depth = {depth}: *******\n")
aqc_example("random", depth, fast=True)
aqc_example("mcx", depth, fast=True)
aqc_example("mcx", depth, fast=False)
|
https://github.com/robinsonvs/tcc-information-systems
|
robinsonvs
|
import math
import random
import matplotlib.pyplot as plt
def is_edge(graph, u, v):
return u in graph[v] or v in graph[u]
def generate_clauses(graph, k):
n = len(graph)
clauses = []
# Cláusulas para garantir que k vértices são selecionados
for i in range(1, k+1):
clauses.append([j + n * (i - 1) for j in range(1, n+1)])
# Cláusulas para garantir que não há dois vértices no mesmo slot
for i in range(1, k+1):
for u in range(1, n+1):
for v in range(u + 1, n+1):
clauses.append([-(u + n * (i - 1)), -(v + n * (i - 1))])
# Cláusulas para garantir que todos os pares de vértices no clique são adjacentes
for i in range(1, k):
for j in range(i+1, k+1):
for u in range(1, n+1):
for v in range(1, n+1):
if not is_edge(graph, u-1, v-1):
clauses.append([-(u + n * (i - 1)), -(v + n * (j - 1))])
return clauses
if __name__ == '__main__':
graph = {
0: [1, 2, 3, 4],
1: [0, 2, 3, 4],
2: [0, 1, 3, 4],
3: [0, 1, 2, 4],
4: [0, 1, 2, 3],
}
K = 5
cnf_clauses = generate_clauses(graph, K)
print(cnf_clauses)
print("***************")
expression = ''
for i, clause in enumerate(cnf_clauses):
if i > 0:
expression += ' & '
expression += '(' + ' | '.join(['x' + str(x) if x > 0 else '~x' + str(abs(x)) for x in clause]) + ')'
print(expression)
# Apply "optimized" Grover
from qiskit.circuit.library import PhaseOracle
from qiskit.primitives import Sampler
from qiskit.visualization import plot_histogram
from qiskit_algorithms import AmplificationProblem, Grover
from qiskit import *
from qiskit_ibm_provider import IBMProvider
provider = IBMProvider(token='8f69cea4cf33304753bfe092aacdf58174e59f8e9813d9305e21c248e3bbb19b98b8508540e15ad4959f3a585675058da81276c3871dce532772da60b370566b')
backend = provider.get_backend('ibm_kyoto')
iteracoes = 3
oracle = PhaseOracle(expression)
problem = AmplificationProblem(oracle)
grover = Grover(sampler=Sampler(), iterations=iteracoes)
#results = grover.amplify(problem)
# Construir o circuito do Grover
qc = grover.construct_circuit(problem, iteracoes, True)
# Transpilar o circuito para o backend
transpiled_qc = transpile(qc, backend=backend)
print("Starting ........................")
# Executar o circuito no backend
job = backend.run(transpiled_qc, shots=1024)
result = job.result()
counts = result.get_counts()
# Análise dos resultados
top_measurement = max(counts, key=counts.get)
max_probability = counts[top_measurement] / 1024
oracle_evaluation = 'True' if max_probability > 0 else 'False'
print('É Satisfatível?', oracle_evaluation)
print('Estado amplificado', top_measurement)
print('Probabilidade estado amplificado', max_probability)
print('Iterações máximas', iteracoes)
print('Width', problem.grover_operator.decompose().width())
print('Depth', problem.grover_operator.decompose().depth())
# Gerar somente resultados relevantes
output = {}
for x in counts:
value = counts[x] / 1024
if value >= max_probability - max_probability * 0.05:
output[x] = value
print(f"estado_amplificado: {x} probabilidade {value}")
# Ordenar o output por probabilidade
sorted_output = dict(sorted(output.items(), key=lambda item: item[1], reverse=True))
# Plotar o histograma
plt.bar(sorted_output.keys(), sorted_output.values(), width=0.5)
plt.xticks(fontsize=8, rotation=45)
plt.xlabel('States')
plt.ylabel('Probability')
plt.title('Histogram of Amplified States')
plt.ylim(0, max(sorted_output.values()) * 1.1) # Ajustar o limite superior do eixo y
# Adicionar as probabilidades sobre as barras
for i, (state, probability) in enumerate(sorted_output.items()):
plt.text(i, probability, f'{probability:.2f}', ha='center', va='bottom', fontsize=8)
plt.show()
#input()
|
https://github.com/Harcipan/QAI_GroverSim
|
Harcipan
|
# Importing standard Qiskit libraries
from qiskit import QuantumCircuit, transpile
from qiskit_ibm_provider import IBMProvider
import qiskit_ibm_provider.jupyter
#provider = IBMProvider('ibm-q')
#backend = provider.get_backend('ibmq_vigo')
from qiskit.visualization import *
from ibm_quantum_widgets import *
# qiskit-ibmq-provider has been deprecated.
# Please see the Migration Guides in https://ibm.biz/provider_migration_guide for more detail.
from qiskit_ibm_runtime import QiskitRuntimeService, Sampler, Estimator, Session, Options
# Loading your IBM Quantum account(s)
service = QiskitRuntimeService(channel="ibm_quantum")
# Invoke a primitive. For more details see https://qiskit.org/documentation/partners/qiskit_ibm_runtime/tutorials.html
# result = Sampler("ibmq_qasm_simulator").run(circuits).result()
# Built-in modules
import math
# Imports from Qiskit
from qiskit import QuantumCircuit
from qiskit.circuit.library import GroverOperator, MCMT, ZGate
from qiskit.visualization import plot_distribution
# Imports from Qiskit Runtime
from qiskit_ibm_runtime import QiskitRuntimeService, Sampler, Session
# Add your token below
service = QiskitRuntimeService(channel="ibm_quantum")
from qiskit import IBMQ
IBMQ.save_account('33b329939cf6fe545c64afb41b84e0993a774c578c2d3e3a07b2ed8644261511d4712974c684ae3050ca82dd8f4ca161930bb344995de7934be32214bdb17079')
from qiskit.circuit import QuantumCircuit, Gate, Instruction
from qiskit.circuit.library.standard_gates import ZGate
def MCMT(gate, num_controls, num_targets):
"""Construct a multi-controlled multi-target gate.
Args:
gate (Gate): The gate to apply to the target qubits.
num_controls (int): The number of control qubits.
num_targets (int): The number of target qubits.
Returns:
Instruction: The multi-controlled multi-target gate as a Qiskit Instruction.
"""
mcmt_gate = QuantumCircuit(num_controls + num_targets)
mcmt_gate.append(gate.control(num_controls), list(range(num_controls + num_targets)))
return mcmt_gate.to_instruction()
def grover_oracle(marked_states):
"""Build a Grover oracle for multiple marked states
Here we assume all input marked states have the same number of bits
Parameters:
marked_states (str or list): Marked states of oracle
Returns:
QuantumCircuit: Quantum circuit representing Grover oracle
"""
if not isinstance(marked_states, list):
marked_states = [marked_states]
# Compute the number of qubits in circuit
num_qubits = len(marked_states[0])
qc = QuantumCircuit(num_qubits)
# Mark each target state in the input list
for target in marked_states:
# Flip target bit-string to match Qiskit bit-ordering
rev_target = target[::-1]
# Find the indices of all the '0' elements in bit-string
zero_inds = [ind for ind in range(num_qubits) if rev_target.startswith("0", ind)]
# Add a multi-controlled Z-gate with pre- and post-applied X-gates (open-controls)
# where the target bit-string has a '0' entry
qc.x(zero_inds)
qc.rx(0.1,zero_inds)
qc.compose(MCMT(ZGate(), num_qubits - 1, 1), inplace=True)
qc.x(zero_inds)
return qc
marked_states = ["011", "100"]
oracle = grover_oracle(marked_states)
oracle.draw("mpl")
grover_op = GroverOperator(oracle)
grover_op.decompose().draw("mpl")
optimal_num_iterations = math.floor(
math.pi / 4 * math.sqrt(2**grover_op.num_qubits / len(marked_states))
)
qc = QuantumCircuit(grover_op.num_qubits)
# Create even superposition of all basis states
qc.h(range(grover_op.num_qubits))
# Apply Grover operator the optimal number of times
qc.compose(grover_op.power(optimal_num_iterations), inplace=True)
# Measure all qubits
qc.measure_all()
qc.draw("mpl")
# Select the simulator with the fewest number of jobs in the queue
backend_simulator = service.least_busy(simulator=True, operational=True)
backend_simulator.name
# Initialize your session
sim_session = Session(backend=backend_simulator)
sim_sampler = Sampler(session=sim_session)
sim_dist = sim_sampler.run(qc, shots=int(1e4)).result().quasi_dists[0]
plot_distribution(sim_dist.binary_probabilities())
sim_session.close()
# Select the backend with the fewest number of jobs in the queue
backend = service.least_busy(simulator=False, operational=True)
backend.name
# Initialize your session
session = Session(backend=backend)
real_sampler = Sampler(session=session)
real_dist = real_sampler.run(qc, shots=int(1e4)).result().quasi_dists[0]
plot_distribution(real_dist.binary_probabilities())
# Close session
session.close()
|
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/dwarkeshsp/quantum-bomb-tester
|
dwarkeshsp
|
import numpy as np
import matplotlib.pyplot as plt
from qiskit import(
QuantumCircuit,
QuantumRegister,
execute,
Aer)
from qiskit.quantum_info.operators import Operator
e = np.pi / 100
rotations = int(np.pi / (2*e))
shots = 10000
def elitzur_vaidman(bomb):
measurements = rotations + 1 if bomb else 1
circuit = QuantumCircuit(1, measurements)
rotate = Operator([
[np.cos(e), -np.sin(e)],
[np.sin(e), np.cos(e)]])
for i in range(rotations):
circuit.unitary(rotate, [0], label='Re')
if bomb:
circuit.measure(0, i)
circuit.measure(0, measurements - 1)
simulator = Aer.get_backend('qasm_simulator')
job = execute(circuit, simulator, shots=shots)
result = job.result()
counts = result.get_counts(circuit)
predict_bomb = predict_no_bomb = blown_up = 0
if bomb:
predict_bomb = counts['0' * measurements]
zeros_one = '0' * (predict_no_bomb - 1) + '1'
predict_no_bomb = counts[zeros_one] if zeros_one in counts else 0
blown_up = shots - predict_bomb - predict_no_bomb
else:
predict_bomb = counts['0'] if '0' in counts else 0
predict_no_bomb = counts['1']
blown_up = 0
y_pos = np.arange(3)
plt.bar(y_pos, [predict_bomb, predict_no_bomb, blown_up])
plt.xticks(y_pos, ['Predicts bomb', 'Predicts no bomb', 'Blown up'])
plt.ylabel('Trials')
plt.title('Elitzur-Vaidman results with' +
(' ' if bomb else ' no ') + 'bomb')
plt.show()
elitzur_vaidman(bomb=True)
elitzur_vaidman(bomb=False)
|
https://github.com/nmoran/qiskit-qdrift-quid19
|
nmoran
|
import numpy as np
import pylab
from qiskit import LegacySimulators
from qiskit_chemistry import QiskitChemistry
import time
# Input dictionary to configure Qiskit Chemistry for the chemistry problem.
qiskit_chemistry_dict = {
'driver': {'name': 'PYSCF'},
'PYSCF': {'atom': '', 'basis': 'sto3g'},
'operator': {'name': 'hamiltonian', 'transformation': 'full', 'qubit_mapping': 'parity'},
'algorithm': {'name': ''},
'initial_state': {'name': 'HartreeFock'},
}
molecule = 'H .0 .0 -{0}; H .0 .0 {0}'
algorithms = [
{
'name': 'IQPE',
'num_iterations': 16,
'num_time_slices': 3000,
'expansion_mode': 'trotter',
'expansion_order': 1,
},
{
'name': 'ExactEigensolver'
}
]
backends = [
LegacySimulators.get_backend('qasm_simulator'),
None
]
start = 0.5 # Start distance
by = 0.5 # How much to increase distance by
steps = 20 # Number of steps to increase by
energies = np.empty([len(algorithms), steps+1])
hf_energies = np.empty(steps+1)
distances = np.empty(steps+1)
import concurrent.futures
import multiprocessing as mp
import copy
def subrountine(i, qiskit_chemistry_dict, d, backend, algorithm):
solver = QiskitChemistry()
qiskit_chemistry_dict['PYSCF']['atom'] = molecule.format(d/2)
qiskit_chemistry_dict['algorithm'] = algorithm
result = solver.run(qiskit_chemistry_dict, backend=backend)
return i, d, result['energy'], result['hf_energy']
start_time = time.time()
max_workers = max(4, mp.cpu_count())
with concurrent.futures.ProcessPoolExecutor(max_workers=max_workers) as executor:
futures = []
for j in range(len(algorithms)):
algorithm = algorithms[j]
backend = backends[j]
for i in range(steps+1):
d = start + i*by/steps
future = executor.submit(
subrountine,
i,
copy.deepcopy(qiskit_chemistry_dict),
d,
backend,
algorithm
)
futures.append(future)
for future in concurrent.futures.as_completed(futures):
i, d, energy, hf_energy = future.result()
energies[j][i] = energy
hf_energies[i] = hf_energy
distances[i] = d
print(' --- complete')
print('Distances: ', distances)
print('Energies:', energies)
print('Hartree-Fock energies:', hf_energies)
print("--- %s seconds ---" % (time.time() - start_time))
pylab.plot(distances, hf_energies, label='Hartree-Fock')
for j in range(len(algorithms)):
pylab.plot(distances, energies[j], label=algorithms[j]['name'])
pylab.xlabel('Interatomic distance')
pylab.ylabel('Energy')
pylab.title('H2 Ground State Energy')
pylab.legend(loc='upper right')
pylab.show()
pylab.plot(distances, np.subtract(hf_energies, energies[1]), label='Hartree-Fock')
pylab.plot(distances, np.subtract(energies[0], energies[1]), label='IQPE')
pylab.xlabel('Interatomic distance')
pylab.ylabel('Energy')
pylab.title('Energy difference from ExactEigensolver')
pylab.legend(loc='upper right')
pylab.show()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import numpy as np
from qiskit import QuantumCircuit, transpile
from qiskit.providers.fake_provider import FakeVigoV2
from qiskit.visualization import plot_circuit_layout
from qiskit.tools.monitor import job_monitor
from qiskit.providers.fake_provider import FakeVigoV2
import matplotlib.pyplot as plt
ghz = QuantumCircuit(3, 3)
ghz.h(0)
for idx in range(1,3):
ghz.cx(0,idx)
ghz.measure(range(3), range(3))
backend = FakeVigoV2()
new_circ_lv3 = transpile(ghz, backend=backend, optimization_level=3)
plot_circuit_layout(new_circ_lv3, backend)
|
https://github.com/annabsouza/qft-qiskit
|
annabsouza
|
import numpy as np
from numpy import pi
from qiskit import QuantumCircuit, transpile, assemble, Aer, IBMQ
from qiskit.providers.ibmq import least_busy
from qiskit.tools.monitor import job_monitor
from qiskit.visualization import plot_histogram, plot_bloch_multivector
qc = QuantumCircuit(3)
#Qiskit's least significant bit has the lowest index (0), thus the circuit will be mirrored through the horizontal
qc.h(2)
#Next, we want to turn this an extra quarter turn if qubit 1 is in the state |1>
qc.cp(pi/2, 1, 2) # CROT from qubit 1 to qubit 2
#And another eighth turn if the least significant qubit (0) is |1>
qc.cp(pi/4, 0, 2) # CROT from qubit 2 to qubit 0
qc.h(1)
qc.cp(pi/2, 0, 1) # CROT from qubit 0 to qubit 1
qc.h(0)
qc.swap(0,2)
qc.draw()
def qft_rotations(circuit, n):
if n == 0: # Exit function if circuit is empty
return circuit
n -= 1 # Indexes start from 0
circuit.h(n) # Apply the H-gate to the most significant qubit
for qubit in range(n):
# For each less significant qubit, we need to do a
# smaller-angled controlled rotation:
circuit.cp(pi/2**(n-qubit), qubit, n)
# At the end of our function, we call the same function again on
# the next qubits (we reduced n by one earlier in the function)
qft_rotations(circuit, n)
def swap_registers(circuit, n):
for qubit in range(n//2):
circuit.swap(qubit, n-qubit-1)
return circuit
def qft(circuit, n):
"""QFT on the first n qubits in circuit"""
qft_rotations(circuit, n)
swap_registers(circuit, n)
return circuit
qc1 = QuantumCircuit(4)
qft(qc1,4)
qc1.draw()
# Create the circuit
qc = QuantumCircuit(3)
# Encode the state 5
qc.x(0) # since we need '1' at first qubit and at last qubit
qc.x(2)
qc.draw()
# And let's check the qubit's states using the aer simulator:
sim = Aer.get_backend("aer_simulator")
qc_init = qc.copy() # making a copy so that we can work on the original one
qc_init.save_statevector()
statevector = sim.run(qc_init).result().get_statevector()
plot_bloch_multivector(statevector)
# we can see the state below as '101'
qft(qc,3)
qc.draw()
qc.save_statevector()
statevector = sim.run(qc).result().get_statevector()
plot_bloch_multivector(statevector)
def inverse_qft(circuit, n):
"""Does the inverse QFT on the first n qubits in circuit"""
# First we create a QFT circuit of the correct size:
qft_circ = qft(QuantumCircuit(n), n)
# Then we take the inverse of this circuit
invqft_circ = qft_circ.inverse()
# And add it to the first n qubits in our existing circuit
circuit.append(invqft_circ, circuit.qubits[:n])
return circuit.decompose() # .decompose() allows us to see the individual gates
nqubits = 3
number = 5
qc = QuantumCircuit(nqubits)
for qubit in range(nqubits):
qc.h(qubit)
qc.p(number*pi/4,0)
qc.p(number*pi/2,1)
qc.p(number*pi,2)
qc.draw()
qc_init = qc.copy()
qc_init.save_statevector()
sim = Aer.get_backend("aer_simulator")
statevector = sim.run(qc_init).result().get_statevector()
plot_bloch_multivector(statevector)
qc = inverse_qft(qc, nqubits)
qc.measure_all()
qc.draw()
# Load our saved IBMQ accounts and get the least busy backend device with less than or equal to nqubits
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q')
backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= nqubits
and not x.configuration().simulator
and x.status().operational==True))
print("least busy backend: ", backend)
shots = 2048
transpiled_qc = transpile(qc, backend, optimization_level=3)
job = backend.run(transpiled_qc, shots=shots)
job_monitor(job)
counts = job.result().get_counts()
plot_histogram(counts)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit.circuit.random import random_circuit
circuit = random_circuit(2, 2, seed=0, measure=True).decompose(reps=1)
display(circuit.draw("mpl"))
from qiskit.primitives import Sampler
sampler = Sampler()
job = sampler.run(circuit)
print(f">>> Job ID: {job.job_id()}")
print(f">>> Job Status: {job.status()}")
result = job.result()
print(f">>> {result}")
print(f" > Quasi-distribution: {result.quasi_dists[0]}")
circuit = random_circuit(2, 2, seed=1, measure=True).decompose(reps=1)
job = sampler.run(circuit)
result = job.result()
display(circuit.draw("mpl"))
print(f">>> Quasi-distribution: {result.quasi_dists[0]}")
circuits = (
random_circuit(2, 2, seed=0, measure=True).decompose(reps=1),
random_circuit(2, 2, seed=1, measure=True).decompose(reps=1),
)
job = sampler.run(circuits)
result = job.result()
[display(cir.draw("mpl")) for cir in circuits]
print(f">>> Quasi-distribution: {result.quasi_dists}")
from qiskit.circuit.library import RealAmplitudes
circuit = RealAmplitudes(num_qubits=2, reps=2).decompose(reps=1)
circuit.measure_all()
parameter_values = [0, 1, 2, 3, 4, 5]
job = sampler.run(circuit, parameter_values)
result = job.result()
display(circuit.draw("mpl"))
print(f">>> Parameter values: {parameter_values}")
print(f">>> Quasi-distribution: {result.quasi_dists[0]}")
from qiskit_ibm_runtime import QiskitRuntimeService
service = QiskitRuntimeService(channel="ibm_quantum")
backend = service.backend("ibmq_qasm_simulator")
from qiskit.circuit.random import random_circuit
circuit = random_circuit(2, 2, seed=0, measure=True).decompose(reps=1)
display(circuit.draw("mpl"))
from qiskit_ibm_runtime import Sampler
sampler = Sampler(session=backend)
job = sampler.run(circuit)
print(f">>> Job ID: {job.job_id()}")
print(f">>> Job Status: {job.status()}")
result = job.result()
print(f">>> {result}")
print(f" > Quasi-distribution: {result.quasi_dists[0]}")
print(f" > Metadata: {result.metadata[0]}")
from qiskit_ibm_runtime import Options
options = Options(optimization_level=3, environment={"log_level": "INFO"})
from qiskit_ibm_runtime import Options
options = Options()
options.resilience_level = 1
options.execution.shots = 2048
sampler = Sampler(session=backend, options=options)
result = sampler.run(circuit).result()
print(f">>> Metadata: {result.metadata[0]}")
sampler = Sampler(session=backend, options=options)
result = sampler.run(circuit, shots=1024).result()
print(f">>> Metadata: {result.metadata[0]}")
from qiskit_ibm_runtime import Options
# optimization_level=3 adds dynamical decoupling
# resilience_level=1 adds readout error mitigation
options = Options(optimization_level=3, resilience_level=1)
sampler = Sampler(session=backend, options=options)
result = sampler.run(circuit).result()
print(f">>> Quasi-distribution: {result.quasi_dists[0]}")
print(f">>> Metadata: {result.metadata[0]}")
from qiskit_ibm_runtime import Session, Estimator
with Session(backend=backend, max_time="1h"):
sampler = Sampler()
result = sampler.run(circuit).result()
print(f">>> Quasi-distribution from the first run: {result.quasi_dists[0]}")
result = sampler.run(circuit).result()
print(f">>> Quasi-distribution from the second run: {result.quasi_dists[0]}")
from qiskit.circuit.random import random_circuit
from qiskit.quantum_info import SparsePauliOp
estimator_circuit = random_circuit(2, 2, seed=0).decompose(reps=1)
display(estimator_circuit.draw("mpl"))
observable = SparsePauliOp("XZ")
print(f">>> Observable: {observable.paulis}")
from qiskit_ibm_runtime import Session, Sampler, Estimator
with Session(backend=backend):
sampler = Sampler()
estimator = Estimator()
result = sampler.run(circuit).result()
print(f">>> Quasi Distribution from the sampler job: {result.quasi_dists[0]}")
result = estimator.run(estimator_circuit, observable).result()
print(f">>> Expectation value from the estimator job: {result.values[0]}")
from qiskit_ibm_runtime import Session, Sampler, Estimator
with Session(backend=backend):
sampler = Sampler()
estimator = Estimator()
sampler_job = sampler.run(circuit)
estimator_job = estimator.run(estimator_circuit, observable)
print(f">>> Quasi Distribution from the sampler job: {sampler_job.result().quasi_dists[0]}")
print(f">>> Expectation value from the estimator job: {estimator_job.result().values[0]}")
from qiskit_ibm_runtime import QiskitRuntimeService, Session, Sampler, Estimator, Options
# 1. Initialize account
service = QiskitRuntimeService(channel="ibm_quantum")
# 2. Specify options, such as enabling error mitigation
options = Options(resilience_level=1)
# 3. Select a backend.
backend = service.backend("ibmq_qasm_simulator")
# 4. Create a session
with Session(backend=backend):
# 5. Create primitive instances
sampler = Sampler(options=options)
estimator = Estimator(options=options)
# 6. Submit jobs
sampler_job = sampler.run(circuit)
estimator_job = estimator.run(estimator_circuit, observable)
# 7. Get results
print(f">>> Quasi Distribution from the sampler job: {sampler_job.result().quasi_dists[0]}")
print(f">>> Expectation value from the estimator job: {estimator_job.result().values[0]}")
import qiskit_ibm_runtime
qiskit_ibm_runtime.version.get_version_info()
from qiskit.tools.jupyter import *
%qiskit_version_table
%qiskit_copyright
|
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
|
mmetcalf14
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 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.
"""
Functions used for the analysis of randomized benchmarking results.
"""
from scipy.optimize import curve_fit
import numpy as np
from qiskit import QiskitError
from ..tomography import marginal_counts
from ...characterization.fitters import build_counts_dict_from_list
try:
from matplotlib import pyplot as plt
HAS_MATPLOTLIB = True
except ImportError:
HAS_MATPLOTLIB = False
class RBFitter:
"""
Class for fitters for randomized benchmarking
"""
def __init__(self, backend_result, cliff_lengths,
rb_pattern=None):
"""
Args:
backend_result: list of results (qiskit.Result).
cliff_lengths: the Clifford lengths, 2D list i x j where i is the
number of patterns, j is the number of cliffords lengths
rb_pattern: the pattern for the rb sequences.
"""
if rb_pattern is None:
rb_pattern = [[0]]
self._cliff_lengths = cliff_lengths
self._rb_pattern = rb_pattern
self._raw_data = []
self._ydata = []
self._fit = []
self._nseeds = 0
self._result_list = []
self.add_data(backend_result)
@property
def raw_data(self):
"""Return raw data."""
return self._raw_data
@property
def cliff_lengths(self):
"""Return clifford lengths."""
return self.cliff_lengths
@property
def ydata(self):
"""Return ydata (means and std devs)."""
return self._ydata
@property
def fit(self):
"""Return fit."""
return self._fit
@property
def seeds(self):
"""Return the number of loaded seeds."""
return self._nseeds
@property
def results(self):
"""Return all the results."""
return self._result_list
def add_data(self, new_backend_result, rerun_fit=True):
"""
Add a new result. Re calculate the raw data, means and
fit.
Args:
new_backend_result: list of rb results
rerun_fit: re caculate the means and fit the result
Additional information:
Assumes that 'result' was executed is
the output of circuits generated by randomized_becnhmarking_seq,
"""
if new_backend_result is None:
return
if not isinstance(new_backend_result, list):
new_backend_result = [new_backend_result]
for result in new_backend_result:
self._result_list.append(result)
# update the number of seeds *if* new ones
# added. Note, no checking if we've done all the
# cliffords
for rbcirc in result.results:
nseeds_circ = int(rbcirc.header.name.split('_')[-1])
if (nseeds_circ+1) > self._nseeds:
self._nseeds = nseeds_circ+1
for result in self._result_list:
if not len(result.results) == len(self._cliff_lengths[0]):
raise ValueError(
"The number of clifford lengths must match the number of "
"results")
if rerun_fit:
self.calc_data()
self.calc_statistics()
self.fit_data()
@staticmethod
def _rb_fit_fun(x, a, alpha, b):
"""Function used to fit rb."""
# pylint: disable=invalid-name
return a * alpha ** x + b
def calc_data(self):
"""
Retrieve probabilities of success from execution results. Outputs
results into an internal variable _raw_data which is a 3-dimensional
list, where item (i,j,k) is the probability to measure the ground state
for the set of qubits in pattern "i" for seed no. j and vector length
self._cliff_lengths[i][k].
Additional information:
Assumes that 'result' was executed is
the output of circuits generated by randomized_becnhmarking_seq,
"""
circ_counts = {}
circ_shots = {}
for seedidx in range(self._nseeds):
for circ, _ in enumerate(self._cliff_lengths[0]):
circ_name = 'rb_length_%d_seed_%d' % (circ, seedidx)
count_list = []
for result in self._result_list:
try:
count_list.append(result.get_counts(circ_name))
except (QiskitError, KeyError):
pass
circ_counts[circ_name] = \
build_counts_dict_from_list(count_list)
circ_shots[circ_name] = sum(circ_counts[circ_name].values())
self._raw_data = []
startind = 0
for patt_ind in range(len(self._rb_pattern)):
string_of_0s = ''
string_of_0s = string_of_0s.zfill(len(self._rb_pattern[patt_ind]))
self._raw_data.append([])
endind = startind+len(self._rb_pattern[patt_ind])
for i in range(self._nseeds):
self._raw_data[-1].append([])
for k, _ in enumerate(self._cliff_lengths[patt_ind]):
circ_name = 'rb_length_%d_seed_%d' % (k, i)
counts_subspace = marginal_counts(
circ_counts[circ_name],
np.arange(startind, endind))
self._raw_data[-1][i].append(
counts_subspace.get(string_of_0s, 0)
/ circ_shots[circ_name])
startind += (endind)
def calc_statistics(self):
"""
Extract averages and std dev from the raw data (self._raw_data).
Assumes that self._calc_data has been run. Output into internal
_ydata variable:
ydata is a list of dictionaries (length number of patterns).
Dictionary ydata[i]:
ydata[i]['mean'] is a numpy_array of length n;
entry j of this array contains the mean probability of
success over seeds, for vector length
self._cliff_lengths[i][j].
And ydata[i]['std'] is a numpy_array of length n;
entry j of this array contains the std
of the probability of success over seeds,
for vector length self._cliff_lengths[i][j].
"""
self._ydata = []
for patt_ind in range(len(self._rb_pattern)):
self._ydata.append({})
self._ydata[-1]['mean'] = np.mean(self._raw_data[patt_ind], 0)
if len(self._raw_data[patt_ind]) == 1: # 1 seed
self._ydata[-1]['std'] = None
else:
self._ydata[-1]['std'] = np.std(self._raw_data[patt_ind], 0)
def fit_data(self):
"""
Fit the RB results to an exponential curve.
Fit each of the patterns
Puts the results into a list of fit dictionaries:
where each dictionary corresponds to a pattern and has fields:
'params' - three parameters of rb_fit_fun. The middle one is the
exponent.
'err' - the error limits of the parameters.
'epc' - error per Clifford
"""
self._fit = []
for patt_ind, (lens, qubits) in enumerate(zip(self._cliff_lengths,
self._rb_pattern)):
# if at least one of the std values is zero, then sigma is replaced
# by None
if not self._ydata[patt_ind]['std'] is None:
sigma = self._ydata[patt_ind]['std'].copy()
if len(sigma) - np.count_nonzero(sigma) > 0:
sigma = None
else:
sigma = None
params, pcov = curve_fit(self._rb_fit_fun, lens,
self._ydata[patt_ind]['mean'],
sigma=sigma,
p0=(1.0, 0.95, 0.0),
bounds=([-2, 0, -2], [2, 1, 2]))
alpha = params[1] # exponent
params_err = np.sqrt(np.diag(pcov))
alpha_err = params_err[1]
nrb = 2 ** len(qubits)
epc = (nrb-1)/nrb*(1-alpha)
epc_err = epc*alpha_err/alpha
self._fit.append({'params': params, 'params_err': params_err,
'epc': epc, 'epc_err': epc_err})
def plot_rb_data(self, pattern_index=0, ax=None,
add_label=True, show_plt=True):
"""
Plot randomized benchmarking data of a single pattern.
Args:
pattern_index: which RB pattern to plot
ax (Axes or None): plot axis (if passed in).
add_label (bool): Add an EPC label
show_plt (bool): display the plot.
Raises:
ImportError: If matplotlib is not installed.
"""
fit_function = self._rb_fit_fun
if not HAS_MATPLOTLIB:
raise ImportError('The function plot_rb_data needs matplotlib. '
'Run "pip install matplotlib" before.')
if ax is None:
plt.figure()
ax = plt.gca()
xdata = self._cliff_lengths[pattern_index]
# Plot the result for each sequence
for one_seed_data in self._raw_data[pattern_index]:
ax.plot(xdata, one_seed_data, color='gray', linestyle='none',
marker='x')
# Plot the mean with error bars
ax.errorbar(xdata, self._ydata[pattern_index]['mean'],
yerr=self._ydata[pattern_index]['std'],
color='r', linestyle='--', linewidth=3)
# Plot the fit
ax.plot(xdata,
fit_function(xdata, *self._fit[pattern_index]['params']),
color='blue', linestyle='-', linewidth=2)
ax.tick_params(labelsize=14)
ax.set_xlabel('Clifford Length', fontsize=16)
ax.set_ylabel('Ground State Population', fontsize=16)
ax.grid(True)
if add_label:
bbox_props = dict(boxstyle="round,pad=0.3",
fc="white", ec="black", lw=2)
ax.text(0.6, 0.9,
"alpha: %.3f(%.1e) EPC: %.3e(%.1e)" %
(self._fit[pattern_index]['params'][1],
self._fit[pattern_index]['params_err'][1],
self._fit[pattern_index]['epc'],
self._fit[pattern_index]['epc_err']),
ha="center", va="center", size=14,
bbox=bbox_props, transform=ax.transAxes)
if show_plt:
plt.show()
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# 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 phase estimation"""
import unittest
from test.python.algorithms import QiskitAlgorithmsTestCase
from ddt import ddt, data, unpack
import numpy as np
from qiskit.circuit.library import ZGate, XGate, HGate, IGate
from qiskit.quantum_info import Pauli, SparsePauliOp, Statevector, Operator
from qiskit.synthesis import MatrixExponential, SuzukiTrotter
from qiskit.primitives import Sampler
from qiskit_algorithms import PhaseEstimationScale
from qiskit_algorithms.phase_estimators import (
PhaseEstimation,
HamiltonianPhaseEstimation,
IterativePhaseEstimation,
)
import qiskit
from qiskit import QuantumCircuit
from qiskit.opflow import (
H,
X,
Y,
Z,
I,
StateFn,
PauliTrotterEvolution,
MatrixEvolution,
PauliSumOp,
)
from qiskit.test import slow_test
@ddt
class TestHamiltonianPhaseEstimation(QiskitAlgorithmsTestCase):
"""Tests for obtaining eigenvalues from phase estimation"""
def hamiltonian_pe(
self,
hamiltonian,
state_preparation=None,
num_evaluation_qubits=6,
backend=None,
evolution=None,
bound=None,
):
"""Run HamiltonianPhaseEstimation and return result with all phases."""
if backend is None:
backend = qiskit.BasicAer.get_backend("statevector_simulator")
with self.assertWarns(DeprecationWarning):
quantum_instance = qiskit.utils.QuantumInstance(backend=backend, shots=10000)
with self.assertWarns(DeprecationWarning):
phase_est = HamiltonianPhaseEstimation(
num_evaluation_qubits=num_evaluation_qubits, quantum_instance=quantum_instance
)
result = phase_est.estimate(
hamiltonian=hamiltonian,
state_preparation=state_preparation,
evolution=evolution,
bound=bound,
)
return result
@data(MatrixEvolution(), PauliTrotterEvolution("suzuki", 4))
def test_pauli_sum_1(self, evolution):
"""Two eigenvalues from Pauli sum with X, Z"""
with self.assertWarns(DeprecationWarning):
hamiltonian = 0.5 * X + Z
state_preparation = StateFn(H.to_circuit())
result = self.hamiltonian_pe(hamiltonian, state_preparation, evolution=evolution)
phase_dict = result.filter_phases(0.162, as_float=True)
phases = list(phase_dict.keys())
phases.sort()
self.assertAlmostEqual(phases[0], -1.125, delta=0.001)
self.assertAlmostEqual(phases[1], 1.125, delta=0.001)
@data(MatrixEvolution(), PauliTrotterEvolution("suzuki", 3))
def test_pauli_sum_2(self, evolution):
"""Two eigenvalues from Pauli sum with X, Y, Z"""
with self.assertWarns(DeprecationWarning):
hamiltonian = 0.5 * X + Y + Z
state_preparation = None
result = self.hamiltonian_pe(hamiltonian, state_preparation, evolution=evolution)
phase_dict = result.filter_phases(0.1, as_float=True)
phases = list(phase_dict.keys())
phases.sort()
self.assertAlmostEqual(phases[0], -1.484, delta=0.001)
self.assertAlmostEqual(phases[1], 1.484, delta=0.001)
def test_single_pauli_op(self):
"""Two eigenvalues from Pauli sum with X, Y, Z"""
hamiltonian = Z
state_preparation = None
with self.assertWarns(DeprecationWarning):
result = self.hamiltonian_pe(hamiltonian, state_preparation, evolution=None)
eigv = result.most_likely_eigenvalue
with self.subTest("First eigenvalue"):
self.assertAlmostEqual(eigv, 1.0, delta=0.001)
with self.assertWarns(DeprecationWarning):
state_preparation = StateFn(X.to_circuit())
result = self.hamiltonian_pe(hamiltonian, state_preparation, bound=1.05)
eigv = result.most_likely_eigenvalue
with self.subTest("Second eigenvalue"):
self.assertAlmostEqual(eigv, -0.98, delta=0.01)
@slow_test
def test_H2_hamiltonian(self):
"""Test H2 hamiltonian"""
with self.assertWarns(DeprecationWarning):
hamiltonian = (
(-1.0523732457728587 * (I ^ I))
+ (0.3979374248431802 * (I ^ Z))
+ (-0.3979374248431802 * (Z ^ I))
+ (-0.011280104256235324 * (Z ^ Z))
+ (0.18093119978423147 * (X ^ X))
)
state_preparation = StateFn((I ^ H).to_circuit())
evo = PauliTrotterEvolution(trotter_mode="suzuki", reps=4)
with self.assertWarns(DeprecationWarning):
result = self.hamiltonian_pe(hamiltonian, state_preparation, evolution=evo)
with self.subTest("Most likely eigenvalues"):
self.assertAlmostEqual(result.most_likely_eigenvalue, -1.855, delta=0.001)
with self.subTest("Most likely phase"):
self.assertAlmostEqual(result.phase, 0.5937, delta=0.001)
with self.subTest("All eigenvalues"):
phase_dict = result.filter_phases(0.1)
phases = list(phase_dict.keys())
self.assertAlmostEqual(phases[0], -0.8979, delta=0.001)
self.assertAlmostEqual(phases[1], -1.8551, delta=0.001)
self.assertAlmostEqual(phases[2], -1.2376, delta=0.001)
def test_matrix_evolution(self):
"""1Q Hamiltonian with MatrixEvolution"""
with self.assertWarns(DeprecationWarning):
hamiltonian = (0.5 * X) + (0.6 * Y) + (0.7 * I)
state_preparation = None
result = self.hamiltonian_pe(
hamiltonian, state_preparation, evolution=MatrixEvolution()
)
phase_dict = result.filter_phases(0.2, as_float=True)
phases = list(phase_dict.keys())
self.assertAlmostEqual(phases[0], 1.490, delta=0.001)
self.assertAlmostEqual(phases[1], -0.090, delta=0.001)
def _setup_from_bound(self, evolution, op_class):
with self.assertWarns(DeprecationWarning):
hamiltonian = 0.5 * X + Y + Z
state_preparation = None
bound = 1.2 * sum(abs(hamiltonian.coeff * coeff) for coeff in hamiltonian.coeffs)
if op_class == "MatrixOp":
hamiltonian = hamiltonian.to_matrix_op()
backend = qiskit.BasicAer.get_backend("statevector_simulator")
with self.assertWarns(DeprecationWarning):
qi = qiskit.utils.QuantumInstance(backend=backend, shots=10000)
with self.assertWarns(DeprecationWarning):
phase_est = HamiltonianPhaseEstimation(num_evaluation_qubits=6, quantum_instance=qi)
result = phase_est.estimate(
hamiltonian=hamiltonian,
bound=bound,
evolution=evolution,
state_preparation=state_preparation,
)
return result
def test_from_bound(self):
"""HamiltonianPhaseEstimation with bound"""
with self.assertWarns(DeprecationWarning):
for op_class in ("SummedOp", "MatrixOp"):
result = self._setup_from_bound(MatrixEvolution(), op_class)
cutoff = 0.01
phases = result.filter_phases(cutoff)
with self.subTest(f"test phases has the correct length: {op_class}"):
self.assertEqual(len(phases), 2)
with self.subTest(f"test scaled phases are correct: {op_class}"):
self.assertEqual(list(phases.keys()), [1.5, -1.5])
phases = result.filter_phases(cutoff, scaled=False)
with self.subTest(f"test unscaled phases are correct: {op_class}"):
self.assertEqual(list(phases.keys()), [0.25, 0.75])
def test_trotter_from_bound(self):
"""HamiltonianPhaseEstimation with bound and Trotterization"""
with self.assertWarns(DeprecationWarning):
result = self._setup_from_bound(
PauliTrotterEvolution(trotter_mode="suzuki", reps=3), op_class="SummedOp"
)
phase_dict = result.filter_phases(0.1)
phases = list(phase_dict.keys())
with self.subTest("test phases has the correct length"):
self.assertEqual(len(phases), 2)
with self.subTest("test phases has correct values"):
self.assertAlmostEqual(phases[0], 1.5, delta=0.001)
self.assertAlmostEqual(phases[1], -1.5, delta=0.001)
# sampler tests
def hamiltonian_pe_sampler(
self,
hamiltonian,
state_preparation=None,
num_evaluation_qubits=6,
evolution=None,
bound=None,
uses_opflow=True,
):
"""Run HamiltonianPhaseEstimation and return result with all phases."""
sampler = Sampler()
phase_est = HamiltonianPhaseEstimation(
num_evaluation_qubits=num_evaluation_qubits, sampler=sampler
)
if uses_opflow:
with self.assertWarns(DeprecationWarning):
result = phase_est.estimate(
hamiltonian=hamiltonian,
state_preparation=state_preparation,
evolution=evolution,
bound=bound,
)
else:
result = phase_est.estimate(
hamiltonian=hamiltonian,
state_preparation=state_preparation,
evolution=evolution,
bound=bound,
)
return result
@data(MatrixExponential(), SuzukiTrotter(reps=4))
def test_pauli_sum_1_sampler(self, evolution):
"""Two eigenvalues from Pauli sum with X, Z"""
with self.assertWarns(DeprecationWarning):
hamiltonian = PauliSumOp(SparsePauliOp.from_list([("X", 0.5), ("Z", 1)]))
state_preparation = QuantumCircuit(1).compose(HGate())
result = self.hamiltonian_pe_sampler(hamiltonian, state_preparation, evolution=evolution)
phase_dict = result.filter_phases(0.162, as_float=True)
phases = list(phase_dict.keys())
phases.sort()
self.assertAlmostEqual(phases[0], -1.125, delta=0.001)
self.assertAlmostEqual(phases[1], 1.125, delta=0.001)
@data(MatrixExponential(), SuzukiTrotter(reps=3))
def test_pauli_sum_2_sampler(self, evolution):
"""Two eigenvalues from Pauli sum with X, Y, Z"""
with self.assertWarns(DeprecationWarning):
hamiltonian = PauliSumOp(SparsePauliOp.from_list([("X", 0.5), ("Z", 1), ("Y", 1)]))
state_preparation = None
result = self.hamiltonian_pe_sampler(hamiltonian, state_preparation, evolution=evolution)
phase_dict = result.filter_phases(0.1, as_float=True)
phases = list(phase_dict.keys())
phases.sort()
self.assertAlmostEqual(phases[0], -1.484, delta=0.001)
self.assertAlmostEqual(phases[1], 1.484, delta=0.001)
def test_single_pauli_op_sampler(self):
"""Two eigenvalues from Pauli sum with X, Y, Z"""
hamiltonian = SparsePauliOp(Pauli("Z"))
state_preparation = None
result = self.hamiltonian_pe_sampler(
hamiltonian, state_preparation, evolution=None, uses_opflow=False
)
eigv = result.most_likely_eigenvalue
with self.subTest("First eigenvalue"):
self.assertAlmostEqual(eigv, 1.0, delta=0.001)
state_preparation = QuantumCircuit(1).compose(XGate())
result = self.hamiltonian_pe_sampler(
hamiltonian, state_preparation, bound=1.05, uses_opflow=False
)
eigv = result.most_likely_eigenvalue
with self.subTest("Second eigenvalue"):
self.assertAlmostEqual(eigv, -0.98, delta=0.01)
@data(
Statevector(QuantumCircuit(2).compose(IGate()).compose(HGate())),
QuantumCircuit(2).compose(IGate()).compose(HGate()),
)
def test_H2_hamiltonian_sampler(self, state_preparation):
"""Test H2 hamiltonian"""
with self.assertWarns(DeprecationWarning):
hamiltonian = PauliSumOp(
SparsePauliOp.from_list(
[
("II", -1.0523732457728587),
("IZ", 0.3979374248431802),
("ZI", -0.3979374248431802),
("ZZ", -0.011280104256235324),
("XX", 0.18093119978423147),
]
)
)
evo = SuzukiTrotter(reps=4)
result = self.hamiltonian_pe_sampler(hamiltonian, state_preparation, evolution=evo)
with self.subTest("Most likely eigenvalues"):
self.assertAlmostEqual(result.most_likely_eigenvalue, -1.855, delta=0.001)
with self.subTest("Most likely phase"):
self.assertAlmostEqual(result.phase, 0.5937, delta=0.001)
with self.subTest("All eigenvalues"):
phase_dict = result.filter_phases(0.1)
phases = sorted(phase_dict.keys())
self.assertAlmostEqual(phases[0], -1.8551, delta=0.001)
self.assertAlmostEqual(phases[1], -1.2376, delta=0.001)
self.assertAlmostEqual(phases[2], -0.8979, delta=0.001)
def test_matrix_evolution_sampler(self):
"""1Q Hamiltonian with MatrixEvolution"""
with self.assertWarns(DeprecationWarning):
hamiltonian = PauliSumOp(SparsePauliOp.from_list([("X", 0.5), ("Y", 0.6), ("I", 0.7)]))
state_preparation = None
result = self.hamiltonian_pe_sampler(
hamiltonian, state_preparation, evolution=MatrixExponential()
)
phase_dict = result.filter_phases(0.2, as_float=True)
phases = sorted(phase_dict.keys())
self.assertAlmostEqual(phases[0], -0.090, delta=0.001)
self.assertAlmostEqual(phases[1], 1.490, delta=0.001)
@ddt
class TestPhaseEstimation(QiskitAlgorithmsTestCase):
"""Evolution tests."""
def one_phase(
self,
unitary_circuit,
state_preparation=None,
backend_type=None,
phase_estimator=None,
num_iterations=6,
):
"""Run phase estimation with operator, eigenvalue pair `unitary_circuit`,
`state_preparation`. Return the estimated phase as a value in :math:`[0,1)`.
"""
if backend_type is None:
backend_type = "qasm_simulator"
backend = qiskit.BasicAer.get_backend(backend_type)
if phase_estimator is None:
phase_estimator = IterativePhaseEstimation
with self.assertWarns(DeprecationWarning):
qi = qiskit.utils.QuantumInstance(backend=backend, shots=10000)
with self.assertWarns(DeprecationWarning):
if phase_estimator == IterativePhaseEstimation:
p_est = IterativePhaseEstimation(num_iterations=num_iterations, quantum_instance=qi)
elif phase_estimator == PhaseEstimation:
p_est = PhaseEstimation(num_evaluation_qubits=6, quantum_instance=qi)
else:
raise ValueError("Unrecognized phase_estimator")
result = p_est.estimate(unitary=unitary_circuit, state_preparation=state_preparation)
phase = result.phase
return phase
@data(
(X.to_circuit(), 0.5, "statevector_simulator", IterativePhaseEstimation),
(X.to_circuit(), 0.5, "qasm_simulator", IterativePhaseEstimation),
(None, 0.0, "qasm_simulator", IterativePhaseEstimation),
(X.to_circuit(), 0.5, "qasm_simulator", PhaseEstimation),
(None, 0.0, "qasm_simulator", PhaseEstimation),
(X.to_circuit(), 0.5, "statevector_simulator", PhaseEstimation),
)
@unpack
def test_qpe_Z(self, state_preparation, expected_phase, backend_type, phase_estimator):
"""eigenproblem Z, |0> and |1>"""
unitary_circuit = Z.to_circuit()
with self.assertWarns(DeprecationWarning):
phase = self.one_phase(
unitary_circuit,
state_preparation,
backend_type=backend_type,
phase_estimator=phase_estimator,
)
self.assertEqual(phase, expected_phase)
@data(
(H.to_circuit(), 0.0, IterativePhaseEstimation),
((H @ X).to_circuit(), 0.5, IterativePhaseEstimation),
(H.to_circuit(), 0.0, PhaseEstimation),
((H @ X).to_circuit(), 0.5, PhaseEstimation),
)
@unpack
def test_qpe_X_plus_minus(self, state_preparation, expected_phase, phase_estimator):
"""eigenproblem X, (|+>, |->)"""
unitary_circuit = X.to_circuit()
with self.assertWarns(DeprecationWarning):
phase = self.one_phase(
unitary_circuit, state_preparation, phase_estimator=phase_estimator
)
self.assertEqual(phase, expected_phase)
@data(
(X.to_circuit(), 0.125, IterativePhaseEstimation),
(I.to_circuit(), 0.875, IterativePhaseEstimation),
(X.to_circuit(), 0.125, PhaseEstimation),
(I.to_circuit(), 0.875, PhaseEstimation),
)
@unpack
def test_qpe_RZ(self, state_preparation, expected_phase, phase_estimator):
"""eigenproblem RZ, (|0>, |1>)"""
alpha = np.pi / 2
unitary_circuit = QuantumCircuit(1)
unitary_circuit.rz(alpha, 0)
with self.assertWarns(DeprecationWarning):
phase = self.one_phase(
unitary_circuit, state_preparation, phase_estimator=phase_estimator
)
self.assertEqual(phase, expected_phase)
def test_check_num_iterations(self):
"""test check for num_iterations greater than zero"""
unitary_circuit = X.to_circuit()
state_preparation = None
with self.assertRaises(ValueError):
self.one_phase(unitary_circuit, state_preparation, num_iterations=-1)
def phase_estimation(
self,
unitary_circuit,
state_preparation=None,
num_evaluation_qubits=6,
backend=None,
construct_circuit=False,
):
"""Run phase estimation with operator, eigenvalue pair `unitary_circuit`,
`state_preparation`. Return all results
"""
if backend is None:
backend = qiskit.BasicAer.get_backend("statevector_simulator")
with self.assertWarns(DeprecationWarning):
qi = qiskit.utils.QuantumInstance(backend=backend, shots=10000)
with self.assertWarns(DeprecationWarning):
phase_est = PhaseEstimation(
num_evaluation_qubits=num_evaluation_qubits, quantum_instance=qi
)
if construct_circuit:
pe_circuit = phase_est.construct_circuit(unitary_circuit, state_preparation)
result = phase_est.estimate_from_pe_circuit(pe_circuit, unitary_circuit.num_qubits)
else:
result = phase_est.estimate(
unitary=unitary_circuit, state_preparation=state_preparation
)
return result
@data(True, False)
def test_qpe_Zplus(self, construct_circuit):
"""superposition eigenproblem Z, |+>"""
unitary_circuit = Z.to_circuit()
state_preparation = H.to_circuit() # prepare |+>
with self.assertWarns(DeprecationWarning):
result = self.phase_estimation(
unitary_circuit,
state_preparation,
backend=qiskit.BasicAer.get_backend("statevector_simulator"),
construct_circuit=construct_circuit,
)
phases = result.filter_phases(1e-15, as_float=True)
with self.subTest("test phases has correct values"):
self.assertEqual(list(phases.keys()), [0.0, 0.5])
with self.subTest("test phases has correct probabilities"):
np.testing.assert_allclose(list(phases.values()), [0.5, 0.5])
with self.subTest("test bitstring representation"):
phases = result.filter_phases(1e-15, as_float=False)
self.assertEqual(list(phases.keys()), ["000000", "100000"])
# sampler tests
def one_phase_sampler(
self,
unitary_circuit,
state_preparation=None,
phase_estimator=None,
num_iterations=6,
shots=None,
):
"""Run phase estimation with operator, eigenvalue pair `unitary_circuit`,
`state_preparation`. Return the estimated phase as a value in :math:`[0,1)`.
"""
if shots is not None:
options = {"shots": shots}
else:
options = {}
sampler = Sampler(options=options)
if phase_estimator is None:
phase_estimator = IterativePhaseEstimation
if phase_estimator == IterativePhaseEstimation:
p_est = IterativePhaseEstimation(num_iterations=num_iterations, sampler=sampler)
elif phase_estimator == PhaseEstimation:
p_est = PhaseEstimation(num_evaluation_qubits=6, sampler=sampler)
else:
raise ValueError("Unrecognized phase_estimator")
result = p_est.estimate(unitary=unitary_circuit, state_preparation=state_preparation)
phase = result.phase
return phase
@data(
(QuantumCircuit(1).compose(XGate()), 0.5, None, IterativePhaseEstimation),
(QuantumCircuit(1).compose(XGate()), 0.5, 1000, IterativePhaseEstimation),
(None, 0.0, 1000, IterativePhaseEstimation),
(QuantumCircuit(1).compose(XGate()), 0.5, 1000, PhaseEstimation),
(None, 0.0, 1000, PhaseEstimation),
(QuantumCircuit(1).compose(XGate()), 0.5, None, PhaseEstimation),
)
@unpack
def test_qpe_Z_sampler(self, state_preparation, expected_phase, shots, phase_estimator):
"""eigenproblem Z, |0> and |1>"""
unitary_circuit = QuantumCircuit(1).compose(ZGate())
phase = self.one_phase_sampler(
unitary_circuit,
state_preparation=state_preparation,
phase_estimator=phase_estimator,
shots=shots,
)
self.assertEqual(phase, expected_phase)
@data(
(QuantumCircuit(1).compose(HGate()), 0.0, IterativePhaseEstimation),
(QuantumCircuit(1).compose(HGate()).compose(ZGate()), 0.5, IterativePhaseEstimation),
(QuantumCircuit(1).compose(HGate()), 0.0, PhaseEstimation),
(QuantumCircuit(1).compose(HGate()).compose(ZGate()), 0.5, PhaseEstimation),
)
@unpack
def test_qpe_X_plus_minus_sampler(self, state_preparation, expected_phase, phase_estimator):
"""eigenproblem X, (|+>, |->)"""
unitary_circuit = QuantumCircuit(1).compose(XGate())
phase = self.one_phase_sampler(
unitary_circuit,
state_preparation,
phase_estimator,
)
self.assertEqual(phase, expected_phase)
@data(
(QuantumCircuit(1).compose(XGate()), 0.125, IterativePhaseEstimation),
(QuantumCircuit(1).compose(IGate()), 0.875, IterativePhaseEstimation),
(QuantumCircuit(1).compose(XGate()), 0.125, PhaseEstimation),
(QuantumCircuit(1).compose(IGate()), 0.875, PhaseEstimation),
)
@unpack
def test_qpe_RZ_sampler(self, state_preparation, expected_phase, phase_estimator):
"""eigenproblem RZ, (|0>, |1>)"""
alpha = np.pi / 2
unitary_circuit = QuantumCircuit(1)
unitary_circuit.rz(alpha, 0)
phase = self.one_phase_sampler(
unitary_circuit,
state_preparation,
phase_estimator,
)
self.assertEqual(phase, expected_phase)
@data(
((X ^ X).to_circuit(), 0.25, IterativePhaseEstimation),
((I ^ X).to_circuit(), 0.125, IterativePhaseEstimation),
((X ^ X).to_circuit(), 0.25, PhaseEstimation),
((I ^ X).to_circuit(), 0.125, PhaseEstimation),
)
@unpack
def test_qpe_two_qubit_unitary(self, state_preparation, expected_phase, phase_estimator):
"""two qubit unitary T ^ T"""
unitary_circuit = QuantumCircuit(2)
unitary_circuit.t(0)
unitary_circuit.t(1)
phase = self.one_phase_sampler(
unitary_circuit,
state_preparation,
phase_estimator,
)
self.assertEqual(phase, expected_phase)
def test_check_num_iterations_sampler(self):
"""test check for num_iterations greater than zero"""
unitary_circuit = QuantumCircuit(1).compose(XGate())
state_preparation = None
with self.assertRaises(ValueError):
self.one_phase_sampler(unitary_circuit, state_preparation, num_iterations=-1)
def test_phase_estimation_scale_from_operator(self):
"""test that PhaseEstimationScale from_pauli_sum works with Operator"""
circ = QuantumCircuit(2)
op = Operator(circ)
scale = PhaseEstimationScale.from_pauli_sum(op)
self.assertEqual(scale._bound, 4.0)
def phase_estimation_sampler(
self,
unitary_circuit,
sampler: Sampler,
state_preparation=None,
num_evaluation_qubits=6,
construct_circuit=False,
):
"""Run phase estimation with operator, eigenvalue pair `unitary_circuit`,
`state_preparation`. Return all results
"""
phase_est = PhaseEstimation(num_evaluation_qubits=num_evaluation_qubits, sampler=sampler)
if construct_circuit:
pe_circuit = phase_est.construct_circuit(unitary_circuit, state_preparation)
result = phase_est.estimate_from_pe_circuit(pe_circuit, unitary_circuit.num_qubits)
else:
result = phase_est.estimate(
unitary=unitary_circuit, state_preparation=state_preparation
)
return result
@data(True, False)
def test_qpe_Zplus_sampler(self, construct_circuit):
"""superposition eigenproblem Z, |+>"""
unitary_circuit = QuantumCircuit(1).compose(ZGate())
state_preparation = QuantumCircuit(1).compose(HGate()) # prepare |+>
sampler = Sampler()
result = self.phase_estimation_sampler(
unitary_circuit,
sampler,
state_preparation,
construct_circuit=construct_circuit,
)
phases = result.filter_phases(1e-15, as_float=True)
with self.subTest("test phases has correct values"):
self.assertEqual(list(phases.keys()), [0.0, 0.5])
with self.subTest("test phases has correct probabilities"):
np.testing.assert_allclose(list(phases.values()), [0.5, 0.5])
with self.subTest("test bitstring representation"):
phases = result.filter_phases(1e-15, as_float=False)
self.assertEqual(list(phases.keys()), ["000000", "100000"])
if __name__ == "__main__":
unittest.main()
|
https://github.com/renatawong/classical-shadow-vqe
|
renatawong
|
'''
(C) 2023 Renata Wong
Electronic structure problem with classical shadows, as presented in https://arxiv.org/abs/2103.07510
This code uses Qiskit as platform.
The shadow is constructed based on derandomized Hamiltonian.
The molecules tested are: H2 (6-31s basis), LiH (sto3g basis), BeH2 (sto3g), H2O (sto3g), and NH3 (sto3g).
The coordinates for NH3 were taken from 'Algorithms for Computer Detection of Symmetry Elementsin Molecular Systems'.
'''
import time
import numpy as np
from collections import Counter
import matplotlib.pyplot as plt
from qiskit import QuantumCircuit, execute
from qiskit_aer import QasmSimulator
from qiskit.quantum_info import SparsePauliOp
from qiskit_nature.units import DistanceUnit
from qiskit_nature.second_q.drivers import PySCFDriver
from qiskit_nature.second_q.algorithms import GroundStateEigensolver
from qiskit_nature.second_q.mappers import BravyiKitaevMapper, JordanWignerMapper, ParityMapper
from qiskit_nature.second_q.circuit.library import UCCSD, HartreeFock
from qiskit_nature.second_q.algorithms import VQEUCCFactory
from qiskit.algorithms.minimum_eigensolvers import VQE
from qiskit.algorithms.optimizers import SLSQP, COBYLA, SPSA
# Estimator primitive is based on the Statevector construct = algebraic simulation
from qiskit.primitives import Estimator
from qiskit.utils import algorithm_globals
from modified_derandomization import modified_derandomized_classical_shadow
from predicting_quantum_properties.data_acquisition_shadow import derandomized_classical_shadow
from predicting_quantum_properties.prediction_shadow import estimate_exp
import qiskit_nature
qiskit_nature.settings.use_pauli_sum_op = False
import h5py
H5PY_DEFAULT_READONLY=1
'''
DEFINING DRIVERS FOR THE MOLECULES
'''
H2_driver = PySCFDriver(
atom="H 0 0 0; H 0 0 0.735",
basis="6-31g",
charge=0,
spin=0,
unit=DistanceUnit.ANGSTROM,
)
LiH_driver = PySCFDriver(
atom="Li 0 0 0.5; H 0 0 0",
basis="sto3g",
charge=0,
spin=0,
unit=DistanceUnit.ANGSTROM,
)
BeH2_driver = PySCFDriver(
atom="Be 0 0 0; H 0 0 1.3264; H 0 0 -1.3264",
basis="sto3g",
charge=0,
spin=0,
unit=DistanceUnit.ANGSTROM,
)
H2O_driver = PySCFDriver(
atom="O 0.0 0.0 0.0; H 0.757 0.586 0.0; H -0.757 0.586 0.0",
basis="sto3g",
charge=0,
spin=0,
unit=DistanceUnit.ANGSTROM,
)
NH3_driver = PySCFDriver(
atom="N 0 0 0; H 0 0 1.008000; H 0.950353 0 -0.336000; H -0.475176 -0.823029 -0.336000",
basis="sto3g",
charge=0,
spin=0,
unit=DistanceUnit.ANGSTROM,
)
'''
FORMATTING HAMILTONIAN
'''
def process_hamiltonian(hamiltonian, derandomize = False):
hamiltonian_observables = []
hamiltonian_coefficients = []
for observable in hamiltonian.paulis:
op_list = []
for op_index, pauli_op in enumerate(observable):
pauli_op = str(pauli_op)
if pauli_op == 'I' or pauli_op == 'X' or pauli_op == 'Y' or pauli_op == 'Z':
op_list.append((pauli_op, op_index))
hamiltonian_observables.append(op_list)
hamiltonian_coefficients = hamiltonian.coeffs.real
system_size = len(hamiltonian_observables[0])
# removing all occurrences of Pauli-I, for all-Pauli-I there is an empty list left
# these observables are needed for estimate_exp()
observables_xyze = []
for observable in hamiltonian_observables:
XYZE = []
for pauli in observable:
if pauli[0] != 'I':
XYZE.append(pauli)
observables_xyze.append(XYZE)
# derandomisation procedure requires that coefficients are non-negative
if derandomize == True:
absolute_coefficients = [abs(coeffcient) for coeffcient in hamiltonian_coefficients]
# removing the empty list as well
# these observables are needed for derandomisation procedure
observables_xyz = []
for idx, observable in enumerate(observables_xyze):
if observable:
observables_xyz.append(observable)
else:
absolute_coefficients.pop(idx)
return system_size, observables_xyze, observables_xyz, hamiltonian_coefficients, absolute_coefficients
return system_size, observables_xyze, hamiltonian_coefficients
'''
COST FUNCTION AND HELPER FUNCTIONS
'''
def basis_change_circuit(pauli_op):
# Generating circuit with just the basis change operators
#
# pauli_op: n-qubit Pauli operator
basis_change = QuantumCircuit(ansatz.num_qubits, ansatz.num_qubits)
for idx, op in enumerate(pauli_op):
if op == 'X':
basis_change.h(idx)
if op == 'Y':
basis_change.h(idx)
basis_change.p(-np.pi/2, idx)
return basis_change
def ground_state_energy_from_shadow(operators, params):
backend = QasmSimulator(method='statevector', shots=1)
pauli_op_dict = Counter(tuple(x) for x in operators)
shadow = []
for pauli_op in pauli_op_dict:
qc = ansatz.bind_parameters(params)
qc = qc.compose(basis_change_circuit(pauli_op))
qc.measure(reversed(range(system_size)), range(system_size))
result = execute(qc, backend, shots=pauli_op_dict[pauli_op]).result()
counts = result.get_counts() # given in order q0 q1 ... qn-1 after register reversal in qc.measure
for count in counts:
for _ in range(counts[count]): # number of repeated measurement values
output_str = list(count)
output = [int(i) for i in output_str]
eigenvals = [x+1 if x == 0 else x-2 for x in output]
snapshot = [(op, eigenval) for op, eigenval in zip(pauli_op, eigenvals)]
shadow.append(snapshot)
expectation_value = 0.0
for term, weight in zip(observables_xyze, hamiltonian_coefficients):
sum_product, match_count = estimate_exp(shadow, term)
if match_count != 0:
expectation_value += (weight * sum_product / match_count)
return expectation_value
'''
EXPERIMENTS
'''
start_time = time.time()
rmse_errors = []
# CALCULATING FERMIONIC HAMILTONIAN AND CONVERTING TO QUBIT HAMILTONIAN
MOLECULES = ['H2', 'LiH', 'BeH2', 'H2O', 'NH3']
for molecule in MOLECULES:
if molecule == 'H2':
problem = H2_driver.run()
if molecule == 'LiH':
problem = LiH_driver.run()
if molecule == 'BeH2':
problem = BeH2_driver.run()
if molecule == 'H2O':
problem = H2O_driver.run()
if molecule == 'NH3':
problem = NH3_driver.run()
hamiltonian = problem.hamiltonian
second_q_op = hamiltonian.second_q_op()
bk_mapper = BravyiKitaevMapper()
bkencoded_hamiltonian = bk_mapper.map(second_q_op)
#print('Qubit Hamiltonian in Bravyi-Kitaev encoding', bkencoded_hamiltonian)
# process the Hamiltonian to obtain properly formatted data
hamiltonian_data = process_hamiltonian(bkencoded_hamiltonian, derandomize = True)
system_size, observables_xyze, observables_xyz, hamiltonian_coefficients, absolute_coefficients = hamiltonian_data
'''
VARIATIONAL ANSATZ
'''
ansatz = UCCSD(
problem.num_spatial_orbitals,
problem.num_particles,
bk_mapper,
initial_state=HartreeFock(
problem.num_spatial_orbitals,
problem.num_particles,
bk_mapper,
),
)
'''
Running VQE on the Hamiltonian obtained from PySCFDriver using Statevector simulator (Estimator primitive)
'''
#estimator = Estimator()
# If shots = None, it calculates the exact expectation values. Otherwise, it samples from normal distributions
# with standard errors as standard deviations using normal distribution approximation.
#estimator.set_options(shots = None)
vqe_solver = VQE(Estimator(), ansatz, SLSQP())
vqe_solver.initial_point = np.zeros(ansatz.num_parameters)
calc = GroundStateEigensolver(bk_mapper, vqe_solver)
result = calc.solve(problem)
print(result.raw_result)
#print('NUMBER OF OPERATORS | DERANDOMISED OPERATORS | AVERAGE RMSE ERROR\n')
measurement_range = [50, 250, 500, 750, 1000, 1250, 1500, 1750]
for num_operators in measurement_range:
derandomized_hamiltonian = modified_derandomized_classical_shadow(observables_xyz, num_operators,
system_size, weight=absolute_coefficients)
tuples = (tuple(pauli) for pauli in derandomized_hamiltonian)
counts = Counter(tuples)
expectation_values = []
num_experiments = 10
for iteration in range(num_experiments):
expectation_value = ground_state_energy_from_shadow(derandomized_hamiltonian, result.raw_result.optimal_point)
expectation_values.append(expectation_value)
print("EXPERIMENT {}: GROUND STATE ENERGY FOUND = {}".format(iteration, expectation_value))
rmse_derandomised_cs = np.sqrt(np.sum([(expectation_values[i] - result.raw_result.optimal_value)**2
for i in range(num_experiments)])/num_experiments)
rmse_errors.append(rmse_derandomised_cs)
print('{} | {} | {}'.format(num_operators, counts, rmse_derandomised_cs))
points = measurement_range
num_points = len(measurement_range)
plt.plot([i for i in points], [rmse_errors[i] for i in range(num_points)], 'r', label=molecule)
plt.xlabel('Number of measurements')
plt.ylabel('Average RMSE error')
plt.legend(loc=1)
elapsed_time = time.time() - start_time
print("Execution time = ", time.strftime("%H:%M:%S", time.gmtime(elapsed_time)))
|
https://github.com/dcavar/q
|
dcavar
|
import numpy as np
X = np.array([[0, 1], [1, 0]])
print("Matrix X:\n", X)
B = np.array([[1], [0]])
print("Matrix B:\n", B)
X @ B
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
import itertools
import matplotlib.pyplot as plt
import numpy as np
import dimod
%matplotlib inline
np.set_printoptions(precision=3, suppress=True)
n_spins = 10
n_samples = 1000
h = {v: np.random.uniform(-2, 2) for v in range(n_spins)}
J = {}
for u, v in itertools.combinations(h, 2):
if np.random.random() < .05:
J[(u, v)] = np.random.uniform(-1, 1)
model = dimod.BinaryQuadraticModel(h, J, 0.0, dimod.SPIN)
sampler = dimod.SimulatedAnnealingSampler()
temperature_0 = 1
response = sampler.sample(model, beta_range=[1/temperature_0, 1/temperature_0], num_reads=n_samples)
energies_0 = [solution.energy for solution in response.data()]
temperature_1 = 10
response = sampler.sample(model, beta_range=[1/temperature_1, 1/temperature_1], num_reads=n_samples)
energies_1 = [solution.energy for solution in response.data()]
temperature_2 = 100
response = sampler.sample(model, beta_range=[1/temperature_2, 1/temperature_2], num_reads=n_samples)
energies_2 = [solution.energy for solution in response.data()]
def plot_probabilities(energy_samples, temperatures):
fig, ax = plt.subplots()
for i, (energies, T) in enumerate(zip(energy_samples, temperatures)):
probabilities = np.exp(-np.array(sorted(energies))/T)
Z = probabilities.sum()
probabilities /= Z
ax.plot(energies, probabilities, linewidth=3, label = "$T_" + str(i+1)+"$")
minimum_energy = min([min(energies) for energies in energy_samples])
maximum_energy = max([max(energies) for energies in energy_samples])
ax.set_xlim(minimum_energy, maximum_energy)
ax.set_xticks([])
ax.set_yticks([])
ax.set_xlabel('Energy')
ax.set_ylabel('Probability')
ax.legend()
plt.show()
plot_probabilities([energies_0, energies_1, energies_2],
[temperature_0, temperature_1, temperature_2])
import itertools
import numpy as np
from functools import reduce
from qiskit import BasicAer, QuantumRegister, QuantumCircuit, ClassicalRegister
from qiskit import execute
from qiskit.quantum_info import Pauli
from qiskit_aqua import get_aer_backend, QuantumInstance
from qiskit_aqua.operator import Operator
from qiskit_aqua.components.optimizers import COBYLA
from qiskit_aqua.algorithms import VQE
from qiskit_aqua.algorithms.adaptive.qaoa.varform import QAOAVarForm
n_qubits = 2
n_system = n_qubits * 2
β = 0
weights = np.array([[0,1],[0,0]])
p = 1
def pauli_z(qubit, coeff):
eye = np.eye((n_system))
return Operator([[coeff, Pauli(eye[qubit], np.zeros(n_system))]])
def product_pauli_z(q1, q2, coeff):
eye = np.eye((n_system))
return Operator([[coeff, Pauli(eye[q1], np.zeros(n_system)) * Pauli(eye[q2], np.zeros(n_system))]])
def ising_hamiltonian(weights):
H = reduce(lambda x,y:x+y,
[product_pauli_z(i,j, -weights[i,j])
for (i,j) in itertools.product(range(n_qubits), range(n_qubits))])
H.to_matrix()
return H
Hc = ising_hamiltonian(weights)
qr = QuantumRegister(n_qubits * 2)
cr = ClassicalRegister(n_qubits)
backend = BasicAer.get_backend('qasm_simulator')
circuit_init = QuantumCircuit(qr)
α = 2 * np.arctan(np.exp(- β/2))
for i in range(n_qubits):
circuit_init.rx(α, qr[n_qubits+i])
circuit_init.cx(qr[n_qubits+i], qr[i])
class InitialState:
def __init__(self, β, n_qubits):
self.β = β
self.n_qubits = n_qubits
def construct_circuit(self, mode, qr):
circuit_init = QuantumCircuit(qr)
alpha = 2 * np.arctan(np.exp(- self.β / 2))
for i in range(n_qubits):
circuit_init.rx(alpha, qr[n_qubits+i])
circuit_init.cx(qr[n_qubits+i], qr[i])
return circuit_init
class MyQAOA(VQE):
def __init__(self, operator, optimizer, init_state, p=1, operator_mode='matrix', initial_point=None,
batch_mode=False, aux_operators=None):
self.validate(locals())
var_form = QAOAVarForm(operator, p, init_state)
super().__init__(operator, var_form, optimizer,
operator_mode=operator_mode, initial_point=initial_point)
class MyQAOAVarForm(QAOAVarForm):
def construct_circuit(self, angles, quantum_register, classical_register):
if not len(angles) == self.num_parameters:
raise ValueError('Incorrect number of angles: expecting {}, but {} given.'.format(
self.num_parameters, len(angles)
))
q = quantum_register
circuit = QuantumCircuit(quantum_register, classical_register)
if self._initial_state:
circuit += self._initial_state.construct_circuit('circuit', q)
else:
circuit.u2(0, np.pi, q)
for idx in range(self._p):
β, γ = angles[idx], angles[idx + self._p]
circuit += self._cost_operator.evolve(None, γ, 'circuit', 1, quantum_registers=q)
circuit += self._mixer_operator.evolve(None, β, 'circuit', 1, quantum_registers=q)
return circuit
initial_state = InitialState(β, n_qubits)
def get_thermal_state(weights, p):
Hc = ising_hamiltonian(weights)
print("Begin QAOA...")
optimizer = COBYLA()
qaoa = MyQAOA(Hc, optimizer, initial_state, p, "matrix")
backend = get_aer_backend('statevector_simulator')
quantum_instance = QuantumInstance(backend, shots=100)
result = qaoa.run(quantum_instance)
print("Results of QAOA", result)
return result
result = get_thermal_state(weights, 1)
var_form = MyQAOAVarForm(Hc, p, initial_state)
thermal_state = var_form.construct_circuit(result['opt_params'], qr, cr)
for i in range(n_qubits):
thermal_state.measure(qr[i], cr[i])
job = execute(thermal_state, backend, shots=2000)
results = job.result().get_counts(thermal_state)
def get_energy(spin_configuration):
x = spin_configuration.reshape(-1, 1)
return np.sum([[-weights[i,j] * x[i] * x[j] for j in range(n_qubits)] for i in range(n_qubits)])
list_spin_configs = np.array(np.concatenate([[list(spin_config)] * results[spin_config] for spin_config in results]), dtype="int")
list_spin_configs[list_spin_configs == 0] = -1
list_energy = np.array([get_energy(spin_config) for spin_config in list_spin_configs])
hist = plt.hist(list_energy, density=True)
β = 5
initial_state = InitialState(β, n_qubits)
result = get_thermal_state(weights, 1)
var_form = MyQAOAVarForm(Hc, p, initial_state)
thermal_state = var_form.construct_circuit(result['opt_params'], qr, cr)
for i in range(n_qubits):
thermal_state.measure(qr[i], cr[i])
job = execute(thermal_state, backend, shots=2000)
results = job.result().get_counts(thermal_state)
list_spin_configs = np.array(np.concatenate([[list(spin_config)] * results[spin_config] for spin_config in results]), dtype="int")
list_spin_configs[list_spin_configs == 0] = -1
list_energy = np.array([get_energy(spin_config) for spin_config in list_spin_configs])
plt.hist(list_energy, density=True)
|
https://github.com/BOBO1997/osp_solutions
|
BOBO1997
|
import numpy as np
import matplotlib.pyplot as plt
import itertools
from pprint import pprint
import pickle
# plt.rcParams.update({'font.size': 16}) # enlarge matplotlib fonts
import time
import datetime
# Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z)
from qiskit.opflow import Zero, One, I, X, Y, Z
from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer
from qiskit.tools.monitor import job_monitor
from qiskit.circuit import Parameter
from qiskit.transpiler.passes import RemoveBarriers
# Import QREM package
from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter
from qiskit.ignis.mitigation import expectation_value
# Import mitiq for zne
import mitiq
# Import state tomography modules
from qiskit.ignis.verification.tomography import state_tomography_circuits
from qiskit.quantum_info import state_fidelity
import sys
import importlib
sys.path.append("./")
import circuit_utils, zne_utils, tomography_utils, sgs_algorithm
importlib.reload(circuit_utils)
importlib.reload(zne_utils)
importlib.reload(tomography_utils)
importlib.reload(sgs_algorithm)
from circuit_utils import *
from zne_utils import *
from tomography_utils import *
from sgs_algorithm import *
# Combine subcircuits into a single multiqubit gate representing a single trotter step
num_qubits = 3
# The final time of the state evolution
target_time = np.pi
# Parameterize variable t to be evaluated at t=pi later
dt = Parameter('t')
# Convert custom quantum circuit into a gate
trot_gate = trotter_gate(dt)
# initial layout
initial_layout = [5,3,1]
# Number of trotter steps
num_steps = 100
print("trotter step: ", num_steps)
scale_factors = [1.0, 2.0, 3.0]
# Initialize quantum circuit for 3 qubits
qr = QuantumRegister(num_qubits, name="lq")
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"])
print("created t3_st_qcs (length:", len(t3_st_qcs), ")")
# zne wrapping
zne_qcs = zne_wrapper(t3_st_qcs, scale_factors=scale_factors)
print("created zne_qcs (length:", len(zne_qcs), ")")
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-utokyo', group='internal', project='hirashi-jst')
# provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22')
# print("provider:", provider)
# backend = provider.get_backend("ibmq_jakarta")
shots = 1 << 13
reps = 1 # unused
# Number of trotter steps
print("trotter step: ", num_steps)
# execute: reps = 1
job = execute(t3_zne_qcs, backend, shots=shots) # 毎回チェック: ここちゃんと変えた?
print('Job ID', job.job_id())
# QREM
qr = QuantumRegister(num_qubits)
meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal')
cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout = initial_layout)
print('Job ID', cal_job.job_id())
cal_results = cal_job.result()
meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal')
mit_results = meas_fitter.filter.apply(job.result())
zne_expvals = zne_decoder(num_qubits, mit_results)
target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!!
rho = expvals_to_valid_rho(num_qubits, zne_expvals)
fidelity = state_fidelity(rho, target_state)
print(fidelity)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, transpile
from qiskit.providers.fake_provider import FakeBoeblingen
backend = FakeBoeblingen()
ghz = QuantumCircuit(5)
ghz.h(0)
ghz.cx(0,range(1,5))
circ = transpile(ghz, backend, scheduling_method="asap")
circ.draw(output='mpl')
|
https://github.com/LFL-Lab/metal-library
|
LFL-Lab
|
%load_ext autoreload
%autoreload 2
%config IPython.sys.argv=['-Xfrozen_modules=off']
from qiskit_metal.designs.design_multiplanar import MultiPlanar
import numpy as np
import qiskit_metal as metal
from qiskit_metal import designs, draw
from qiskit_metal import MetalGUI, Dict, open_docs
design = MultiPlanar(metadata={},
overwrite_enabled=True)
# Design variables
design._chips.main.size.size_x = '5mm'
design._chips.main.size.size_y = '5mm'
# Check if layer data is useable, if so launch GUI
ls_unique = design.ls.is_layer_data_unique()
if (ls_unique != True):
raise ValueError('Layer data in `MultiPlanar` design is not unique')
# gui = MetalGUI(design)
metal.__version__
# Transmon
from qiskit_metal.qlibrary.qubits.transmon_cross import TransmonCross
xmon_options = Dict(
connection_pads=Dict(
readout = Dict(connector_location = '180')),
)
# Create a new Transmon Cross object with name 'Q1'
TransmonCross(design, 'transmon', options=xmon_options)
# gui.rebuild() # rebuild the design and plot
# gui.autoscale() #resize GUI to see QComponent
from qiskit_metal.renderers.renderer_ansys_pyaedt.hfss_renderer_eigenmode_aedt import QHFSSEigenmodePyaedt
import pyEPR as epr
em1_aedt = QHFSSEigenmodePyaedt(design,
'Qubit_Sabrina_proj',
'Qubit_Sabrina_design',
initiate=True)
hfss_aedt = em1_aedt.current_app
def render_design():
em1_aedt.render_design()
def run_simulation():
#### Computer's variables
num_cores=16
num_gpu=1
#### Setup Name
setup_name = 'TransmonSetup'
# Change Silicon to Ultracold Silicon
hfss_aedt.materials['silicon'].permittivity = 11.45
# Add project variables
add_project_level_vars(em1_aedt)
# Clear setups
if len(hfss_aedt.setups) != 0:
hfss_aedt.setups[0].delete()
# Add Setup
setup_options = dict(
name= setup_name,
MinimumFrequency = 3, # GHz
NumModes= 1,
MaxDeltaFreq = 0.1,
MaximumPasses= 1,
MinimumPasses= None,
MinimumConvergedPasses= 2,
PercentRefinement= 30,
BasisOrder= None
)
em1_aedt.add_hfss_em_setup(**setup_options)
hfss_aedt.analyze_setup(name=setup_name,
num_cores=num_cores,
num_gpu=num_gpu)
# Make silicon ultra cold
hfss_aedt.materials['silicon'].permittivity = 11.45
def add_project_level_vars(renderer):
"""
Finds all names, inductances, and capacitances of Josephson Junctions rendered into ANSYS.
Args:
renderer (QHFSSEigenmodePyaedt)
"""
# Get all josephson junctions from rendered components table
geom_table = renderer.path_poly_and_junction_with_valid_comps
all_jjs = geom_table.loc[geom_table['name'].str.contains('rect_jj')]
all_jjs = all_jjs.reset_index(drop=True)
for i, row in all_jjs.iterrows():
### Parsing Data ###
component = str(row['component'])
name = str(row['name'])
inductance = row['aedt_hfss_inductance'] # Lj in Henries
capacitance = row['aedt_hfss_capacitance'] # Cj in Farads
# Get ANSYS > Model > Sheet corresponding to JJs
rect_name = 'JJ_rect_Lj_' + component + '_' + name
# Get ANSYS > Model > Lines corresponding to JJs
line_name = 'JJ_Lj_' + component + '_' + name + '_'
### Appending data ###
# Add global Lj and Cj variables to ANSYS (for EPR analysis)
ansys_Lj_name = f'Lj_{i}'
ansys_Cj_name = f'Cj_{i}'
renderer.set_variable(ansys_Lj_name, str(inductance * 1E9) + 'nH')
renderer.set_variable(ansys_Cj_name, str(capacitance * 1E15) + 'fF')
def run_analysis():
'''
After finishing simulation, analyze results
'''
em1_aedt.run_epr()
# Extract observables of int
observables = extract_observables(em1_aedt.epr_quantum_analysis)
return observables
def extract_observables(epra,
cos_trunc: int = 10,
fock_trunc: int = 15):
'''
Extract observables from EPR quantum analysis
Args:
epra (epr.QuantumAnalysis): Raw EPR Quanutm analysis class
cos_trunc (int, optional): amount of terms to consider in cosine expansion
fock_trunc (int, optional): size of fock space before truncation
Returns:
package (dict): simulated observables
'''
# Extraction of variables
omegas = epra.get_frequencies()
chis = epra.get_chis()
other_data = epra.data
package = dict(qubit_freq_MHz = omegas['0'][0],
qubit_anharmonicity_MHz = chis[0][0],
other_data = str(other_data))
return package
def run_single_design(): # this will be used as `custom_analysis`
render_design()
run_simulation()
package = run_analysis()
return package
from metal_library.sweeper import QSweeper
sweeper = QSweeper(design)
sweep_parameters = dict(
connection_pads = dict(
readout = dict(
connector_type = '0',
claw_length = ['185um', '195um', '205um', '215um'],
ground_spacing = ['4um', '5um', '7um', '9um', '10um'],
claw_gap = ['5.1um'],
claw_width = ['10um', '15um']
)
),
cross_width = ['30um'],
cross_length = ['185um', '195um', '205um', '215um', '225um', '235um'],
cross_gap = ['29um'],
aedt_hfss_inductance = [9.686E-9, 10.471E-9, 11.268E-9, 12.679-9, 13.816]
)
my_librarian = sweeper.run_single_component_sweep(component_name='transmon',
parameters = sweep_parameters,
custom_analysis = run_single_design,
parameters_slice=slice(1,2),
save_path="./Tutorial2_QubitOnly.csv")
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
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()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, QuantumRegister
from qiskit.circuit.library.standard_gates import HGate
qr = QuantumRegister(3)
qc = QuantumCircuit(qr)
c3h_gate = HGate().control(2)
qc.append(c3h_gate, qr)
qc.draw('mpl')
|
https://github.com/googlercolin/Qiskit-Course
|
googlercolin
|
import numpy as np
# Importing standard Qiskit libraries
from qiskit import QuantumCircuit, transpile, Aer, IBMQ
from qiskit.tools.jupyter import *
from qiskit.visualization import *
from ibm_quantum_widgets import *
from qiskit.providers.aer import QasmSimulator
# Loading your IBM Quantum account(s)
provider = IBMQ.load_account()
from qiskit.circuit.library import RealAmplitudes
ansatz = RealAmplitudes(num_qubits=2, reps=1,
entanglement='linear').decompose()
ansatz.draw()
from qiskit.opflow import Z, I
hamiltonian = Z ^ Z
from qiskit.opflow import StateFn, PauliExpectation
expectation = StateFn(hamiltonian, is_measurement=True) @ StateFn(ansatz)
pauli_basis = PauliExpectation().convert(expectation)
print(pauli_basis)
from qiskit import Aer
from qiskit.utils import QuantumInstance
from qiskit.opflow import CircuitSampler
quantum_instance = QuantumInstance(Aer.get_backend('qasm_simulator'),
# we'll set a seed for reproducibility
shots = 8192, seed_simulator = 2718,
seed_transpiler = 2718)
sampler = CircuitSampler(quantum_instance)
def evaluate_expectation(x):
value_dict = dict(zip(ansatz.parameters, x))
result = sampler.convert(pauli_basis, params=value_dict).eval()
return np.real(result)
import numpy as np
point = np.random.random(ansatz.num_parameters)
index = 2
eps = 0.2
# make identity vector with a 1 at index ``index``, otherwise 0
e_i = np.identity(point.size)[:, index]
print(e_i)
plus = point + eps * e_i
minus = point - eps * e_i
finite_difference = (
evaluate_expectation(plus) - evaluate_expectation(minus)) / (2 * eps)
print(finite_difference)
from qiskit.opflow import Gradient
shifter = Gradient('fin_diff', analytic=False, epsilon=eps)
grad = shifter.convert(expectation, params=ansatz.parameters[index])
print(grad)
value_dict = dict(zip(ansatz.parameters, point))
sampler.convert(grad, value_dict).eval().real
eps = np.pi / 2
e_i = np.identity(point.size)[:, index]
plus = point + eps * e_i
minus = point - eps * e_i
finite_difference = (
evaluate_expectation(plus) - evaluate_expectation(minus)) / 2
print(finite_difference)
shifter = Gradient() # parameter-shift rule is the default
grad = shifter.convert(expectation, params=ansatz.parameters[index])
sampler.convert(grad, value_dict).eval().real
# initial_point = np.random.random(ansatz.num_parameters)
initial_point = np.array([0.43253681, 0.09507794, 0.42805949, 0.34210341]) # now fix and initial point for reproducibility
gradient = Gradient().convert(expectation)
gradient_in_pauli_basis = PauliExpectation().convert(gradient)
sampler = CircuitSampler(quantum_instance)
def evaluate_gradient(x):
value_dict = dict(zip(ansatz.parameters, x))
result = sampler.convert(gradient_in_pauli_basis,
params=value_dict).eval()
return np.real(result)
from qiskit.algorithms.optimizers import GradientDescent
gd_loss = []
def gd_callback(nfevs, x, fx, stepsize):
gd_loss.append(fx)
gd = GradientDescent(maxiter=300,
learning_rate=0.01,
callback=gd_callback)
x_opt, fx_opt, nfevs = gd.optimize(
initial_point.size, # number of parameters
evaluate_expectation, # function to minimize
gradient_function=evaluate_gradient, # function to evaluate gradient
initial_point=initial_point # initial point
)
import matplotlib
import matplotlib.pyplot as plt
plt.figure(figsize=(7, 3))
plt.plot(gd_loss, label='vanilla gradient descent')
plt.axhline(-1, ls='--', c='C3', label='target')
plt.ylabel('loss')
plt.xlabel('iterations')
plt.legend()
|
https://github.com/2lambda123/Qiskit-qiskit
|
2lambda123
|
# 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.
"""Test QASM3 exporter."""
# We can't really help how long the lines output by the exporter are in some cases.
# pylint: disable=line-too-long
from io import StringIO
from math import pi
import re
import unittest
from ddt import ddt, data
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, transpile
from qiskit.circuit import Parameter, Qubit, Clbit, Instruction, Gate, Delay, Barrier
from qiskit.circuit.classical import expr
from qiskit.circuit.controlflow import CASE_DEFAULT
from qiskit.test import QiskitTestCase
from qiskit.qasm3 import Exporter, dumps, dump, QASM3ExporterError, ExperimentalFeatures
from qiskit.qasm3.exporter import QASM3Builder
from qiskit.qasm3.printer import BasicPrinter
# Tests marked with this decorator should be restored after gate definition with parameters is fixed
# properly, and the dummy tests after them should be deleted. See gh-7335.
requires_fixed_parameterisation = unittest.expectedFailure
class TestQASM3Functions(QiskitTestCase):
"""QASM3 module - high level functions"""
def setUp(self):
self.circuit = QuantumCircuit(2)
self.circuit.u(2 * pi, 3 * pi, -5 * pi, 0)
self.expected_qasm = "\n".join(
[
"OPENQASM 3;",
'include "stdgates.inc";',
"qubit[2] q;",
"U(2*pi, 3*pi, -5*pi) q[0];",
"",
]
)
super().setUp()
def test_dumps(self):
"""Test dumps."""
result = dumps(self.circuit)
self.assertEqual(result, self.expected_qasm)
def test_dump(self):
"""Test dump into an IO stream."""
io = StringIO()
dump(self.circuit, io)
result = io.getvalue()
self.assertEqual(result, self.expected_qasm)
@ddt
class TestCircuitQASM3(QiskitTestCase):
"""QASM3 exporter."""
maxDiff = 1_000_000
@classmethod
def setUpClass(cls):
# These regexes are not perfect by any means, but sufficient for simple tests on controlled
# input circuits. They can allow false negatives (in which case, update the regex), but to
# be useful for the tests must _never_ have false positive matches. We use an explicit
# space (`\s`) or semicolon rather than the end-of-word `\b` because we want to ensure that
# the exporter isn't putting out invalid characters as part of the identifiers.
cls.register_regex = re.compile(
r"^\s*(let|(qu)?bit(\[\d+\])?)\s+(?P<name>\w+)[\s;]", re.U | re.M
)
scalar_type_names = {
"angle",
"duration",
"float",
"int",
"stretch",
"uint",
}
cls.scalar_parameter_regex = re.compile(
r"^\s*((input|output|const)\s+)?" # Modifier
rf"({'|'.join(scalar_type_names)})\s*(\[[^\]]+\])?\s+" # Type name and designator
r"(?P<name>\w+)[\s;]", # Parameter name
re.U | re.M,
)
super().setUpClass()
def test_regs_conds_qasm(self):
"""Test with registers and conditionals."""
qr1 = QuantumRegister(1, "qr1")
qr2 = QuantumRegister(2, "qr2")
cr = ClassicalRegister(3, "cr")
qc = QuantumCircuit(qr1, qr2, cr)
qc.measure(qr1[0], cr[0])
qc.measure(qr2[0], cr[1])
qc.measure(qr2[1], cr[2])
qc.x(qr2[1]).c_if(cr, 0)
qc.y(qr1[0]).c_if(cr, 1)
qc.z(qr1[0]).c_if(cr, 2)
expected_qasm = "\n".join(
[
"OPENQASM 3;",
'include "stdgates.inc";',
"bit[3] cr;",
"qubit[1] qr1;",
"qubit[2] qr2;",
"cr[0] = measure qr1[0];",
"cr[1] = measure qr2[0];",
"cr[2] = measure qr2[1];",
"if (cr == 0) {",
" x qr2[1];",
"}",
"if (cr == 1) {",
" y qr1[0];",
"}",
"if (cr == 2) {",
" z qr1[0];",
"}",
"",
]
)
self.assertEqual(Exporter().dumps(qc), expected_qasm)
def test_registers_as_aliases(self):
"""Test that different types of alias creation and concatenation work."""
qubits = [Qubit() for _ in [None] * 10]
first_four = QuantumRegister(name="first_four", bits=qubits[:4])
last_five = QuantumRegister(name="last_five", bits=qubits[5:])
alternate = QuantumRegister(name="alternate", bits=qubits[::2])
sporadic = QuantumRegister(name="sporadic", bits=[qubits[4], qubits[2], qubits[9]])
qc = QuantumCircuit(qubits, first_four, last_five, alternate, sporadic)
expected_qasm = "\n".join(
[
"OPENQASM 3;",
'include "stdgates.inc";',
"qubit _qubit0;",
"qubit _qubit1;",
"qubit _qubit2;",
"qubit _qubit3;",
"qubit _qubit4;",
"qubit _qubit5;",
"qubit _qubit6;",
"qubit _qubit7;",
"qubit _qubit8;",
"qubit _qubit9;",
"let first_four = {_qubit0, _qubit1, _qubit2, _qubit3};",
"let last_five = {_qubit5, _qubit6, _qubit7, _qubit8, _qubit9};",
"let alternate = {first_four[0], first_four[2], _qubit4, last_five[1], last_five[3]};",
"let sporadic = {alternate[2], alternate[1], last_five[4]};",
"",
]
)
self.assertEqual(Exporter(allow_aliasing=True).dumps(qc), expected_qasm)
def test_composite_circuit(self):
"""Test with a composite circuit instruction and barriers"""
composite_circ_qreg = QuantumRegister(2)
composite_circ = QuantumCircuit(composite_circ_qreg, name="composite_circ")
composite_circ.h(0)
composite_circ.x(1)
composite_circ.cx(0, 1)
composite_circ_instr = composite_circ.to_gate()
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(2, "cr")
qc = QuantumCircuit(qr, cr)
qc.h(0)
qc.cx(0, 1)
qc.barrier()
qc.append(composite_circ_instr, [0, 1])
qc.measure([0, 1], [0, 1])
expected_qasm = "\n".join(
[
"OPENQASM 3;",
'include "stdgates.inc";',
"gate composite_circ _gate_q_0, _gate_q_1 {",
" h _gate_q_0;",
" x _gate_q_1;",
" cx _gate_q_0, _gate_q_1;",
"}",
"bit[2] cr;",
"qubit[2] qr;",
"h qr[0];",
"cx qr[0], qr[1];",
"barrier qr[0], qr[1];",
"composite_circ qr[0], qr[1];",
"cr[0] = measure qr[0];",
"cr[1] = measure qr[1];",
"",
]
)
self.assertEqual(Exporter().dumps(qc), expected_qasm)
def test_custom_gate(self):
"""Test custom gates (via to_gate)."""
composite_circ_qreg = QuantumRegister(2)
composite_circ = QuantumCircuit(composite_circ_qreg, name="composite_circ")
composite_circ.h(0)
composite_circ.x(1)
composite_circ.cx(0, 1)
composite_circ_instr = composite_circ.to_gate()
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(2, "cr")
qc = QuantumCircuit(qr, cr)
qc.h(0)
qc.cx(0, 1)
qc.barrier()
qc.append(composite_circ_instr, [0, 1])
qc.measure([0, 1], [0, 1])
expected_qasm = "\n".join(
[
"OPENQASM 3;",
'include "stdgates.inc";',
"gate composite_circ _gate_q_0, _gate_q_1 {",
" h _gate_q_0;",
" x _gate_q_1;",
" cx _gate_q_0, _gate_q_1;",
"}",
"bit[2] cr;",
"qubit[2] qr;",
"h qr[0];",
"cx qr[0], qr[1];",
"barrier qr[0], qr[1];",
"composite_circ qr[0], qr[1];",
"cr[0] = measure qr[0];",
"cr[1] = measure qr[1];",
"",
]
)
self.assertEqual(Exporter().dumps(qc), expected_qasm)
def test_same_composite_circuits(self):
"""Test when a composite circuit is added to the circuit multiple times."""
composite_circ_qreg = QuantumRegister(2)
composite_circ = QuantumCircuit(composite_circ_qreg, name="composite_circ")
composite_circ.h(0)
composite_circ.x(1)
composite_circ.cx(0, 1)
composite_circ_instr = composite_circ.to_gate()
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(2, "cr")
qc = QuantumCircuit(qr, cr)
qc.h(0)
qc.cx(0, 1)
qc.barrier()
qc.append(composite_circ_instr, [0, 1])
qc.append(composite_circ_instr, [0, 1])
qc.measure([0, 1], [0, 1])
expected_qasm = "\n".join(
[
"OPENQASM 3;",
'include "stdgates.inc";',
"gate composite_circ _gate_q_0, _gate_q_1 {",
" h _gate_q_0;",
" x _gate_q_1;",
" cx _gate_q_0, _gate_q_1;",
"}",
"bit[2] cr;",
"qubit[2] qr;",
"h qr[0];",
"cx qr[0], qr[1];",
"barrier qr[0], qr[1];",
"composite_circ qr[0], qr[1];",
"composite_circ qr[0], qr[1];",
"cr[0] = measure qr[0];",
"cr[1] = measure qr[1];",
"",
]
)
self.assertEqual(Exporter().dumps(qc), expected_qasm)
def test_composite_circuits_with_same_name(self):
"""Test when multiple composite circuit instructions same name and different
implementation."""
my_gate = QuantumCircuit(1, name="my_gate")
my_gate.h(0)
my_gate_inst1 = my_gate.to_gate()
my_gate = QuantumCircuit(1, name="my_gate")
my_gate.x(0)
my_gate_inst2 = my_gate.to_gate()
my_gate = QuantumCircuit(1, name="my_gate")
my_gate.x(0)
my_gate_inst3 = my_gate.to_gate()
qr = QuantumRegister(1, name="qr")
circuit = QuantumCircuit(qr, name="circuit")
circuit.append(my_gate_inst1, [qr[0]])
circuit.append(my_gate_inst2, [qr[0]])
my_gate_inst2_id = id(circuit.data[-1].operation)
circuit.append(my_gate_inst3, [qr[0]])
my_gate_inst3_id = id(circuit.data[-1].operation)
expected_qasm = "\n".join(
[
"OPENQASM 3;",
'include "stdgates.inc";',
"gate my_gate _gate_q_0 {",
" h _gate_q_0;",
"}",
f"gate my_gate_{my_gate_inst2_id} _gate_q_0 {{",
" x _gate_q_0;",
"}",
f"gate my_gate_{my_gate_inst3_id} _gate_q_0 {{",
" x _gate_q_0;",
"}",
"qubit[1] qr;",
"my_gate qr[0];",
f"my_gate_{my_gate_inst2_id} qr[0];",
f"my_gate_{my_gate_inst3_id} qr[0];",
"",
]
)
self.assertEqual(Exporter().dumps(circuit), expected_qasm)
def test_pi_disable_constants_false(self):
"""Test pi constant (disable_constants=False)"""
circuit = QuantumCircuit(2)
circuit.u(2 * pi, 3 * pi, -5 * pi, 0)
expected_qasm = "\n".join(
[
"OPENQASM 3;",
'include "stdgates.inc";',
"qubit[2] q;",
"U(2*pi, 3*pi, -5*pi) q[0];",
"",
]
)
self.assertEqual(Exporter(disable_constants=False).dumps(circuit), expected_qasm)
def test_pi_disable_constants_true(self):
"""Test pi constant (disable_constants=True)"""
circuit = QuantumCircuit(2)
circuit.u(2 * pi, 3 * pi, -5 * pi, 0)
expected_qasm = "\n".join(
[
"OPENQASM 3;",
'include "stdgates.inc";',
"qubit[2] q;",
"U(6.283185307179586, 9.42477796076938, -15.707963267948966) q[0];",
"",
]
)
self.assertEqual(Exporter(disable_constants=True).dumps(circuit), expected_qasm)
def test_custom_gate_with_unbound_parameter(self):
"""Test custom gate with unbound parameter."""
parameter_a = Parameter("a")
custom = QuantumCircuit(1, name="custom")
custom.rx(parameter_a, 0)
circuit = QuantumCircuit(1)
circuit.append(custom.to_gate(), [0])
expected_qasm = "\n".join(
[
"OPENQASM 3;",
'include "stdgates.inc";',
"input float[64] a;",
"gate custom(a) _gate_q_0 {",
" rx(a) _gate_q_0;",
"}",
"qubit[1] q;",
"custom(a) q[0];",
"",
]
)
self.assertEqual(Exporter().dumps(circuit), expected_qasm)
def test_custom_gate_with_bound_parameter(self):
"""Test custom gate with bound parameter."""
parameter_a = Parameter("a")
custom = QuantumCircuit(1)
custom.rx(parameter_a, 0)
custom_gate = custom.bind_parameters({parameter_a: 0.5}).to_gate()
custom_gate.name = "custom"
circuit = QuantumCircuit(1)
circuit.append(custom_gate, [0])
expected_qasm = "\n".join(
[
"OPENQASM 3;",
'include "stdgates.inc";',
"gate custom _gate_q_0 {",
" rx(0.5) _gate_q_0;",
"}",
"qubit[1] q;",
"custom q[0];",
"",
]
)
self.assertEqual(Exporter().dumps(circuit), expected_qasm)
@requires_fixed_parameterisation
def test_custom_gate_with_params_bound_main_call(self):
"""Custom gate with unbound parameters that are bound in the main circuit"""
parameter0 = Parameter("p0")
parameter1 = Parameter("p1")
custom = QuantumCircuit(2, name="custom")
custom.rz(parameter0, 0)
custom.rz(parameter1 / 2, 1)
qr_all_qubits = QuantumRegister(3, "q")
qr_r = QuantumRegister(3, "r")
circuit = QuantumCircuit(qr_all_qubits, qr_r)
circuit.append(custom.to_gate(), [qr_all_qubits[0], qr_r[0]])
circuit.assign_parameters({parameter0: pi, parameter1: pi / 2}, inplace=True)
expected_qasm = "\n".join(
[
"OPENQASM 3;",
'include "stdgates.inc";',
"gate custom(_gate_p_0, _gate_p_0) _gate_q_0, _gate_q_1 {",
" rz(pi) _gate_q_0;",
" rz(pi/4) _gate_q_1;",
"}",
"qubit[3] q;",
"qubit[3] r;",
"custom(pi, pi/2) q[0], r[0];",
"",
]
)
self.assertEqual(Exporter().dumps(circuit), expected_qasm)
def test_reused_custom_parameter(self):
"""Test reused custom gate with parameter."""
parameter_a = Parameter("a")
custom = QuantumCircuit(1)
custom.rx(parameter_a, 0)
circuit = QuantumCircuit(1)
circuit.append(custom.bind_parameters({parameter_a: 0.5}).to_gate(), [0])
circuit.append(custom.bind_parameters({parameter_a: 1}).to_gate(), [0])
circuit_name_0 = circuit.data[0].operation.definition.name
circuit_name_1 = circuit.data[1].operation.definition.name
expected_qasm = "\n".join(
[
"OPENQASM 3;",
'include "stdgates.inc";',
f"gate {circuit_name_0} _gate_q_0 {{",
" rx(0.5) _gate_q_0;",
"}",
f"gate {circuit_name_1} _gate_q_0 {{",
" rx(1.0) _gate_q_0;",
"}",
"qubit[1] q;",
f"{circuit_name_0} q[0];",
f"{circuit_name_1} q[0];",
"",
]
)
self.assertEqual(Exporter().dumps(circuit), expected_qasm)
def test_unbound_circuit(self):
"""Test with unbound parameters (turning them into inputs)."""
qc = QuantumCircuit(1)
theta = Parameter("θ")
qc.rz(theta, 0)
expected_qasm = "\n".join(
[
"OPENQASM 3;",
'include "stdgates.inc";',
"input float[64] θ;",
"qubit[1] q;",
"rz(θ) q[0];",
"",
]
)
self.assertEqual(Exporter().dumps(qc), expected_qasm)
def test_unknown_parameterized_gate_called_multiple_times(self):
"""Test that a parameterised gate is called correctly if the first instance of it is
generic."""
x, y = Parameter("x"), Parameter("y")
qc = QuantumCircuit(2)
qc.rzx(x, 0, 1)
qc.rzx(y, 0, 1)
qc.rzx(0.5, 0, 1)
expected_qasm = "\n".join(
[
"OPENQASM 3;",
"input float[64] x;",
"input float[64] y;",
"gate rzx(x) _gate_q_0, _gate_q_1 {",
" h _gate_q_1;",
" cx _gate_q_0, _gate_q_1;",
" rz(x) _gate_q_1;",
" cx _gate_q_0, _gate_q_1;",
" h _gate_q_1;",
"}",
"qubit[2] q;",
"rzx(x) q[0], q[1];",
"rzx(y) q[0], q[1];",
"rzx(0.5) q[0], q[1];",
"",
]
)
# Set the includes and basis gates to ensure that this gate is unknown.
exporter = Exporter(includes=[], basis_gates=("rz", "h", "cx"))
self.assertEqual(exporter.dumps(qc), expected_qasm)
def test_gate_qasm_with_ctrl_state(self):
"""Test with open controlled gate that has ctrl_state"""
qc = QuantumCircuit(2)
qc.ch(0, 1, ctrl_state=0)
expected_qasm = "\n".join(
[
"OPENQASM 3;",
'include "stdgates.inc";',
"gate ch_o0 _gate_q_0, _gate_q_1 {",
" x _gate_q_0;",
" ch _gate_q_0, _gate_q_1;",
" x _gate_q_0;",
"}",
"qubit[2] q;",
"ch_o0 q[0], q[1];",
"",
]
)
self.assertEqual(Exporter().dumps(qc), expected_qasm)
def test_custom_gate_collision_with_stdlib(self):
"""Test a custom gate with name collision with the standard library."""
custom = QuantumCircuit(2, name="cx")
custom.cx(0, 1)
custom_gate = custom.to_gate()
qc = QuantumCircuit(2)
qc.append(custom_gate, [0, 1])
custom_gate_id = id(qc.data[-1].operation)
expected_qasm = "\n".join(
[
"OPENQASM 3;",
'include "stdgates.inc";',
f"gate cx_{custom_gate_id} _gate_q_0, _gate_q_1 {{",
" cx _gate_q_0, _gate_q_1;",
"}",
"qubit[2] q;",
f"cx_{custom_gate_id} q[0], q[1];",
"",
]
)
self.assertEqual(Exporter().dumps(qc), expected_qasm)
@requires_fixed_parameterisation
def test_no_include(self):
"""Test explicit gate declaration (no include)"""
q = QuantumRegister(2, "q")
circuit = QuantumCircuit(q)
circuit.rz(pi / 2, 0)
circuit.sx(0)
circuit.cx(0, 1)
expected_qasm = "\n".join(
[
"OPENQASM 3;",
"gate u3(_gate_p_0, _gate_p_1, _gate_p_2) _gate_q_0 {",
" U(0, 0, pi/2) _gate_q_0;",
"}",
"gate u1(_gate_p_0) _gate_q_0 {",
" u3(0, 0, pi/2) _gate_q_0;",
"}",
"gate rz(_gate_p_0) _gate_q_0 {",
" u1(pi/2) _gate_q_0;",
"}",
"gate sdg _gate_q_0 {",
" u1(-pi/2) _gate_q_0;",
"}",
"gate u2(_gate_p_0, _gate_p_1) _gate_q_0 {",
" u3(pi/2, 0, pi) _gate_q_0;",
"}",
"gate h _gate_q_0 {",
" u2(0, pi) _gate_q_0;",
"}",
"gate sx _gate_q_0 {",
" sdg _gate_q_0;",
" h _gate_q_0;",
" sdg _gate_q_0;",
"}",
"gate cx c, t {",
" ctrl @ U(pi, 0, pi) c, t;",
"}",
"qubit[2] q;",
"rz(pi/2) q[0];",
"sx q[0];",
"cx q[0], q[1];",
"",
]
)
self.assertEqual(Exporter(includes=[]).dumps(circuit), expected_qasm)
@requires_fixed_parameterisation
def test_teleportation(self):
"""Teleportation with physical qubits"""
qc = QuantumCircuit(3, 2)
qc.h(1)
qc.cx(1, 2)
qc.barrier()
qc.cx(0, 1)
qc.h(0)
qc.barrier()
qc.measure([0, 1], [0, 1])
qc.barrier()
qc.x(2).c_if(qc.clbits[1], 1)
qc.z(2).c_if(qc.clbits[0], 1)
transpiled = transpile(qc, initial_layout=[0, 1, 2])
expected_qasm = "\n".join(
[
"OPENQASM 3;",
"gate u3(_gate_p_0, _gate_p_1, _gate_p_2) _gate_q_0 {",
" U(pi/2, 0, pi) _gate_q_0;",
"}",
"gate u2(_gate_p_0, _gate_p_1) _gate_q_0 {",
" u3(pi/2, 0, pi) _gate_q_0;",
"}",
"gate h _gate_q_0 {",
" u2(0, pi) _gate_q_0;",
"}",
"gate cx c, t {",
" ctrl @ U(pi, 0, pi) c, t;",
"}",
"gate x _gate_q_0 {",
" u3(pi, 0, pi) _gate_q_0;",
"}",
"gate u1(_gate_p_0) _gate_q_0 {",
" u3(0, 0, pi) _gate_q_0;",
"}",
"gate z _gate_q_0 {",
" u1(pi) _gate_q_0;",
"}",
"bit[2] c;",
"h $1;",
"cx $1, $2;",
"barrier $0, $1, $2;",
"cx $0, $1;",
"h $0;",
"barrier $0, $1, $2;",
"c[0] = measure $0;",
"c[1] = measure $1;",
"barrier $0, $1, $2;",
"if (c[1]) {",
" x $2;",
"}",
"if (c[0]) {",
" z $2;",
"}",
"",
]
)
self.assertEqual(Exporter(includes=[]).dumps(transpiled), expected_qasm)
@requires_fixed_parameterisation
def test_basis_gates(self):
"""Teleportation with physical qubits"""
qc = QuantumCircuit(3, 2)
qc.h(1)
qc.cx(1, 2)
qc.barrier()
qc.cx(0, 1)
qc.h(0)
qc.barrier()
qc.measure([0, 1], [0, 1])
qc.barrier()
qc.x(2).c_if(qc.clbits[1], 1)
qc.z(2).c_if(qc.clbits[0], 1)
transpiled = transpile(qc, initial_layout=[0, 1, 2])
expected_qasm = "\n".join(
[
"OPENQASM 3;",
"gate u3(_gate_p_0, _gate_p_1, _gate_p_2) _gate_q_0 {",
" U(pi/2, 0, pi) _gate_q_0;",
"}",
"gate u2(_gate_p_0, _gate_p_1) _gate_q_0 {",
" u3(pi/2, 0, pi) _gate_q_0;",
"}",
"gate h _gate_q_0 {",
" u2(0, pi) _gate_q_0;",
"}",
"gate x _gate_q_0 {",
" u3(pi, 0, pi) _gate_q_0;",
"}",
"bit[2] c;",
"h $1;",
"cx $1, $2;",
"barrier $0, $1, $2;",
"cx $0, $1;",
"h $0;",
"barrier $0, $1, $2;",
"c[0] = measure $0;",
"c[1] = measure $1;",
"barrier $0, $1, $2;",
"if (c[1]) {",
" x $2;",
"}",
"if (c[0]) {",
" z $2;",
"}",
"",
]
)
self.assertEqual(
Exporter(includes=[], basis_gates=["cx", "z", "U"]).dumps(transpiled),
expected_qasm,
)
def test_opaque_instruction_in_basis_gates(self):
"""Test that an instruction that is set in the basis gates is output verbatim with no
definition."""
qc = QuantumCircuit(1)
qc.x(0)
qc.append(Gate("my_gate", 1, []), [0], [])
basis_gates = ["my_gate", "x"]
transpiled = transpile(qc, initial_layout=[0])
expected_qasm = "\n".join(
[
"OPENQASM 3;",
"x $0;",
"my_gate $0;",
"",
]
)
self.assertEqual(
Exporter(includes=[], basis_gates=basis_gates).dumps(transpiled), expected_qasm
)
def test_reset_statement(self):
"""Test that a reset statement gets output into valid QASM 3. This includes tests of reset
operations on single qubits and in nested scopes."""
qreg = QuantumRegister(2, "qr")
qc = QuantumCircuit(qreg)
qc.reset(0)
qc.reset([0, 1])
expected_qasm = "\n".join(
[
"OPENQASM 3;",
"qubit[2] qr;",
"reset qr[0];",
"reset qr[0];",
"reset qr[1];",
"",
]
)
self.assertEqual(Exporter(includes=[]).dumps(qc), expected_qasm)
def test_delay_statement(self):
"""Test that delay operations get output into valid QASM 3."""
qreg = QuantumRegister(2, "qr")
qc = QuantumCircuit(qreg)
qc.delay(100, qreg[0], unit="ms")
qc.delay(2, qreg[1], unit="ps") # "ps" is not a valid unit in OQ3, so we need to convert.
expected_qasm = "\n".join(
[
"OPENQASM 3;",
"qubit[2] qr;",
"delay[100ms] qr[0];",
"delay[2000ns] qr[1];",
"",
]
)
self.assertEqual(Exporter(includes=[]).dumps(qc), expected_qasm)
def test_loose_qubits(self):
"""Test that qubits that are not in any register can be used without issue."""
bits = [Qubit(), Qubit()]
qr = QuantumRegister(2, name="qr")
cr = ClassicalRegister(2, name="cr")
qc = QuantumCircuit(bits, qr, cr)
qc.h(0)
qc.h(1)
qc.h(2)
qc.h(3)
expected_qasm = "\n".join(
[
"OPENQASM 3;",
'include "stdgates.inc";',
"bit[2] cr;",
"qubit _qubit0;",
"qubit _qubit1;",
"qubit[2] qr;",
"h _qubit0;",
"h _qubit1;",
"h qr[0];",
"h qr[1];",
"",
]
)
self.assertEqual(dumps(qc), expected_qasm)
def test_loose_clbits(self):
"""Test that clbits that are not in any register can be used without issue."""
qreg = QuantumRegister(1, name="qr")
bits = [Clbit() for _ in [None] * 7]
cr1 = ClassicalRegister(name="cr1", bits=bits[1:3])
cr2 = ClassicalRegister(name="cr2", bits=bits[4:6])
qc = QuantumCircuit(bits, qreg, cr1, cr2)
qc.measure(0, 0)
qc.measure(0, 1)
qc.measure(0, 2)
qc.measure(0, 3)
qc.measure(0, 4)
qc.measure(0, 5)
qc.measure(0, 6)
expected_qasm = "\n".join(
[
"OPENQASM 3;",
'include "stdgates.inc";',
"bit _bit0;",
"bit _bit3;",
"bit _bit6;",
"bit[2] cr1;",
"bit[2] cr2;",
"qubit[1] qr;",
"_bit0 = measure qr[0];",
"cr1[0] = measure qr[0];",
"cr1[1] = measure qr[0];",
"_bit3 = measure qr[0];",
"cr2[0] = measure qr[0];",
"cr2[1] = measure qr[0];",
"_bit6 = measure qr[0];",
"",
]
)
self.assertEqual(dumps(qc), expected_qasm)
def test_classical_register_aliasing(self):
"""Test that clbits that are not in any register can be used without issue."""
qreg = QuantumRegister(1, name="qr")
bits = [Clbit() for _ in [None] * 7]
cr1 = ClassicalRegister(name="cr1", bits=bits[1:3])
cr2 = ClassicalRegister(name="cr2", bits=bits[4:6])
# cr3 overlaps cr2, but this should be allowed in this alias form.
cr3 = ClassicalRegister(name="cr3", bits=bits[5:])
qc = QuantumCircuit(bits, qreg, cr1, cr2, cr3)
qc.measure(0, 0)
qc.measure(0, 1)
qc.measure(0, 2)
qc.measure(0, 3)
qc.measure(0, 4)
qc.measure(0, 5)
qc.measure(0, 6)
expected_qasm = "\n".join(
[
"OPENQASM 3;",
'include "stdgates.inc";',
"bit _bit0;",
"bit _bit1;",
"bit _bit2;",
"bit _bit3;",
"bit _bit4;",
"bit _bit5;",
"bit _bit6;",
"let cr1 = {_bit1, _bit2};",
"let cr2 = {_bit4, _bit5};",
"let cr3 = {cr2[1], _bit6};",
"qubit[1] qr;",
"_bit0 = measure qr[0];",
"cr1[0] = measure qr[0];",
"cr1[1] = measure qr[0];",
"_bit3 = measure qr[0];",
"cr2[0] = measure qr[0];",
"cr3[0] = measure qr[0];",
"cr3[1] = measure qr[0];",
"",
]
)
self.assertEqual(dumps(qc, allow_aliasing=True), expected_qasm)
def test_old_alias_classical_registers_option(self):
"""Test that the ``alias_classical_registers`` option still functions during its changeover
period."""
qreg = QuantumRegister(1, name="qr")
bits = [Clbit() for _ in [None] * 7]
cr1 = ClassicalRegister(name="cr1", bits=bits[1:3])
cr2 = ClassicalRegister(name="cr2", bits=bits[4:6])
# cr3 overlaps cr2, but this should be allowed in this alias form.
cr3 = ClassicalRegister(name="cr3", bits=bits[5:])
qc = QuantumCircuit(bits, qreg, cr1, cr2, cr3)
qc.measure(0, 0)
qc.measure(0, 1)
qc.measure(0, 2)
qc.measure(0, 3)
qc.measure(0, 4)
qc.measure(0, 5)
qc.measure(0, 6)
expected_qasm = "\n".join(
[
"OPENQASM 3;",
'include "stdgates.inc";',
"bit _bit0;",
"bit _bit1;",
"bit _bit2;",
"bit _bit3;",
"bit _bit4;",
"bit _bit5;",
"bit _bit6;",
"let cr1 = {_bit1, _bit2};",
"let cr2 = {_bit4, _bit5};",
"let cr3 = {cr2[1], _bit6};",
"qubit[1] qr;",
"_bit0 = measure qr[0];",
"cr1[0] = measure qr[0];",
"cr1[1] = measure qr[0];",
"_bit3 = measure qr[0];",
"cr2[0] = measure qr[0];",
"cr3[0] = measure qr[0];",
"cr3[1] = measure qr[0];",
"",
]
)
self.assertEqual(dumps(qc, alias_classical_registers=True), expected_qasm)
def test_simple_for_loop(self):
"""Test that a simple for loop outputs the expected result."""
parameter = Parameter("x")
loop_body = QuantumCircuit(1)
loop_body.rx(parameter, 0)
loop_body.break_loop()
loop_body.continue_loop()
qc = QuantumCircuit(2)
qc.for_loop([0, 3, 4], parameter, loop_body, [1], [])
qc.x(0)
qr_name = qc.qregs[0].name
expected_qasm = "\n".join(
[
"OPENQASM 3;",
'include "stdgates.inc";',
f"qubit[2] {qr_name};",
f"for {parameter.name} in {{0, 3, 4}} {{",
f" rx({parameter.name}) {qr_name}[1];",
" break;",
" continue;",
"}",
f"x {qr_name}[0];",
"",
]
)
self.assertEqual(dumps(qc), expected_qasm)
def test_nested_for_loop(self):
"""Test that a for loop nested inside another outputs the expected result."""
inner_parameter = Parameter("x")
outer_parameter = Parameter("y")
inner_body = QuantumCircuit(2)
inner_body.rz(inner_parameter, 0)
inner_body.rz(outer_parameter, 1)
inner_body.break_loop()
outer_body = QuantumCircuit(2)
outer_body.h(0)
outer_body.rz(outer_parameter, 1)
# Note we reverse the order of the bits here to test that this is traced.
outer_body.for_loop(range(1, 5, 2), inner_parameter, inner_body, [1, 0], [])
outer_body.continue_loop()
qc = QuantumCircuit(2)
qc.for_loop(range(4), outer_parameter, outer_body, [0, 1], [])
qc.x(0)
qr_name = qc.qregs[0].name
expected_qasm = "\n".join(
[
"OPENQASM 3;",
'include "stdgates.inc";',
f"qubit[2] {qr_name};",
f"for {outer_parameter.name} in [0:3] {{",
f" h {qr_name}[0];",
f" rz({outer_parameter.name}) {qr_name}[1];",
f" for {inner_parameter.name} in [1:2:4] {{",
# Note the reversed bit order.
f" rz({inner_parameter.name}) {qr_name}[1];",
f" rz({outer_parameter.name}) {qr_name}[0];",
" break;",
" }",
" continue;",
"}",
f"x {qr_name}[0];",
"",
]
)
self.assertEqual(dumps(qc), expected_qasm)
def test_regular_parameter_in_nested_for_loop(self):
"""Test that a for loop nested inside another outputs the expected result, including
defining parameters that are used in nested loop scopes."""
inner_parameter = Parameter("x")
outer_parameter = Parameter("y")
regular_parameter = Parameter("t")
inner_body = QuantumCircuit(2)
inner_body.h(0)
inner_body.rx(regular_parameter, 1)
inner_body.break_loop()
outer_body = QuantumCircuit(2)
outer_body.h(0)
outer_body.h(1)
# Note we reverse the order of the bits here to test that this is traced.
outer_body.for_loop(range(1, 5, 2), inner_parameter, inner_body, [1, 0], [])
outer_body.continue_loop()
qc = QuantumCircuit(2)
qc.for_loop(range(4), outer_parameter, outer_body, [0, 1], [])
qc.x(0)
qr_name = qc.qregs[0].name
expected_qasm = "\n".join(
[
"OPENQASM 3;",
'include "stdgates.inc";',
# This next line will be missing until gh-7280 is fixed.
f"input float[64] {regular_parameter.name};",
f"qubit[2] {qr_name};",
f"for {outer_parameter.name} in [0:3] {{",
f" h {qr_name}[0];",
f" h {qr_name}[1];",
f" for {inner_parameter.name} in [1:2:4] {{",
# Note the reversed bit order.
f" h {qr_name}[1];",
f" rx({regular_parameter.name}) {qr_name}[0];",
" break;",
" }",
" continue;",
"}",
f"x {qr_name}[0];",
"",
]
)
self.assertEqual(dumps(qc), expected_qasm)
def test_for_loop_with_no_parameter(self):
"""Test that a for loop with the parameter set to ``None`` outputs the expected result."""
loop_body = QuantumCircuit(1)
loop_body.h(0)
qc = QuantumCircuit(2)
qc.for_loop([0, 3, 4], None, loop_body, [1], [])
qr_name = qc.qregs[0].name
expected_qasm = "\n".join(
[
"OPENQASM 3;",
'include "stdgates.inc";',
f"qubit[2] {qr_name};",
"for _ in {0, 3, 4} {",
f" h {qr_name}[1];",
"}",
"",
]
)
self.assertEqual(dumps(qc), expected_qasm)
def test_simple_while_loop(self):
"""Test that a simple while loop works correctly."""
loop_body = QuantumCircuit(1)
loop_body.h(0)
loop_body.break_loop()
loop_body.continue_loop()
qr = QuantumRegister(2, name="qr")
cr = ClassicalRegister(2, name="cr")
qc = QuantumCircuit(qr, cr)
qc.while_loop((cr, 0), loop_body, [1], [])
qc.x(0)
expected_qasm = "\n".join(
[
"OPENQASM 3;",
'include "stdgates.inc";',
"bit[2] cr;",
"qubit[2] qr;",
"while (cr == 0) {",
" h qr[1];",
" break;",
" continue;",
"}",
"x qr[0];",
"",
]
)
self.assertEqual(dumps(qc), expected_qasm)
def test_nested_while_loop(self):
"""Test that a while loop nested inside another outputs the expected result."""
inner_body = QuantumCircuit(2, 2)
inner_body.measure(0, 0)
inner_body.measure(1, 1)
inner_body.break_loop()
outer_body = QuantumCircuit(2, 2)
outer_body.measure(0, 0)
outer_body.measure(1, 1)
# We reverse the order of the bits here to test this works, and test a single-bit condition.
outer_body.while_loop((outer_body.clbits[0], 0), inner_body, [1, 0], [1, 0])
outer_body.continue_loop()
qr = QuantumRegister(2, name="qr")
cr = ClassicalRegister(2, name="cr")
qc = QuantumCircuit(qr, cr)
qc.while_loop((cr, 0), outer_body, [0, 1], [0, 1])
qc.x(0)
expected_qasm = "\n".join(
[
"OPENQASM 3;",
'include "stdgates.inc";',
"bit[2] cr;",
"qubit[2] qr;",
"while (cr == 0) {",
" cr[0] = measure qr[0];",
" cr[1] = measure qr[1];",
# Note the reversed bits in the body.
" while (!cr[0]) {",
" cr[1] = measure qr[1];",
" cr[0] = measure qr[0];",
" break;",
" }",
" continue;",
"}",
"x qr[0];",
"",
]
)
self.assertEqual(dumps(qc), expected_qasm)
def test_simple_if_statement(self):
"""Test that a simple if statement with no else works correctly."""
true_body = QuantumCircuit(1)
true_body.h(0)
qr = QuantumRegister(2, name="qr")
cr = ClassicalRegister(2, name="cr")
qc = QuantumCircuit(qr, cr)
qc.if_test((cr, 0), true_body, [1], [])
qc.x(0)
expected_qasm = "\n".join(
[
"OPENQASM 3;",
'include "stdgates.inc";',
"bit[2] cr;",
"qubit[2] qr;",
"if (cr == 0) {",
" h qr[1];",
"}",
"x qr[0];",
"",
]
)
self.assertEqual(dumps(qc), expected_qasm)
def test_simple_if_else_statement(self):
"""Test that a simple if statement with an else branch works correctly."""
true_body = QuantumCircuit(1)
true_body.h(0)
false_body = QuantumCircuit(1)
false_body.z(0)
qr = QuantumRegister(2, name="qr")
cr = ClassicalRegister(2, name="cr")
qc = QuantumCircuit(qr, cr)
qc.if_else((cr, 0), true_body, false_body, [1], [])
qc.x(0)
expected_qasm = "\n".join(
[
"OPENQASM 3;",
'include "stdgates.inc";',
"bit[2] cr;",
"qubit[2] qr;",
"if (cr == 0) {",
" h qr[1];",
"} else {",
" z qr[1];",
"}",
"x qr[0];",
"",
]
)
self.assertEqual(dumps(qc), expected_qasm)
def test_nested_if_else_statement(self):
"""Test that a nested if/else statement works correctly."""
inner_true_body = QuantumCircuit(2, 2)
inner_true_body.measure(0, 0)
inner_false_body = QuantumCircuit(2, 2)
inner_false_body.measure(1, 1)
outer_true_body = QuantumCircuit(2, 2)
outer_true_body.if_else(
(outer_true_body.clbits[0], 0), inner_true_body, inner_false_body, [0, 1], [0, 1]
)
outer_false_body = QuantumCircuit(2, 2)
# Note the flipped bits here.
outer_false_body.if_else(
(outer_false_body.clbits[0], 1), inner_true_body, inner_false_body, [1, 0], [1, 0]
)
qr = QuantumRegister(2, name="qr")
cr = ClassicalRegister(2, name="cr")
qc = QuantumCircuit(qr, cr)
qc.if_else((cr, 0), outer_true_body, outer_false_body, [0, 1], [0, 1])
expected_qasm = "\n".join(
[
"OPENQASM 3;",
'include "stdgates.inc";',
"bit[2] cr;",
"qubit[2] qr;",
"if (cr == 0) {",
" if (!cr[0]) {",
" cr[0] = measure qr[0];",
" } else {",
" cr[1] = measure qr[1];",
" }",
"} else {",
" if (cr[0]) {",
" cr[1] = measure qr[1];",
" } else {",
" cr[0] = measure qr[0];",
" }",
"}",
"",
]
)
self.assertEqual(dumps(qc), expected_qasm)
def test_chain_else_if(self):
"""Test the basic 'else/if' chaining logic for flattening the else scope if its content is a
single if/else statement."""
inner_true_body = QuantumCircuit(2, 2)
inner_true_body.measure(0, 0)
inner_false_body = QuantumCircuit(2, 2)
inner_false_body.measure(1, 1)
outer_true_body = QuantumCircuit(2, 2)
outer_true_body.if_else(
(outer_true_body.clbits[0], 0), inner_true_body, inner_false_body, [0, 1], [0, 1]
)
outer_false_body = QuantumCircuit(2, 2)
# Note the flipped bits here.
outer_false_body.if_else(
(outer_false_body.clbits[0], 1), inner_true_body, inner_false_body, [1, 0], [1, 0]
)
qr = QuantumRegister(2, name="qr")
cr = ClassicalRegister(2, name="cr")
qc = QuantumCircuit(qr, cr)
qc.if_else((cr, 0), outer_true_body, outer_false_body, [0, 1], [0, 1])
expected_qasm = "\n".join(
[
"OPENQASM 3;",
'include "stdgates.inc";',
"bit[2] cr;",
"qubit[2] qr;",
"if (cr == 0) {",
" if (!cr[0]) {",
" cr[0] = measure qr[0];",
" } else {",
" cr[1] = measure qr[1];",
" }",
"} else if (cr[0]) {",
" cr[1] = measure qr[1];",
"} else {",
" cr[0] = measure qr[0];",
"}",
"",
]
)
# This is not the default behaviour, and it's pretty buried how you'd access it.
builder = QASM3Builder(
qc,
includeslist=("stdgates.inc",),
basis_gates=("U",),
disable_constants=False,
allow_aliasing=False,
)
stream = StringIO()
BasicPrinter(stream, indent=" ", chain_else_if=True).visit(builder.build_program())
self.assertEqual(stream.getvalue(), expected_qasm)
def test_chain_else_if_does_not_chain_if_extra_instructions(self):
"""Test the basic 'else/if' chaining logic for flattening the else scope if its content is a
single if/else statement does not cause a flattening if the 'else' block is not a single
if/else."""
inner_true_body = QuantumCircuit(2, 2)
inner_true_body.measure(0, 0)
inner_false_body = QuantumCircuit(2, 2)
inner_false_body.measure(1, 1)
outer_true_body = QuantumCircuit(2, 2)
outer_true_body.if_else(
(outer_true_body.clbits[0], 0), inner_true_body, inner_false_body, [0, 1], [0, 1]
)
outer_false_body = QuantumCircuit(2, 2)
# Note the flipped bits here.
outer_false_body.if_else(
(outer_false_body.clbits[0], 1), inner_true_body, inner_false_body, [1, 0], [1, 0]
)
outer_false_body.h(0)
qr = QuantumRegister(2, name="qr")
cr = ClassicalRegister(2, name="cr")
qc = QuantumCircuit(qr, cr)
qc.if_else((cr, 0), outer_true_body, outer_false_body, [0, 1], [0, 1])
expected_qasm = "\n".join(
[
"OPENQASM 3;",
'include "stdgates.inc";',
"bit[2] cr;",
"qubit[2] qr;",
"if (cr == 0) {",
" if (!cr[0]) {",
" cr[0] = measure qr[0];",
" } else {",
" cr[1] = measure qr[1];",
" }",
"} else {",
" if (cr[0]) {",
" cr[1] = measure qr[1];",
" } else {",
" cr[0] = measure qr[0];",
" }",
" h qr[0];",
"}",
"",
]
)
# This is not the default behaviour, and it's pretty buried how you'd access it.
builder = QASM3Builder(
qc,
includeslist=("stdgates.inc",),
basis_gates=("U",),
disable_constants=False,
allow_aliasing=False,
)
stream = StringIO()
BasicPrinter(stream, indent=" ", chain_else_if=True).visit(builder.build_program())
self.assertEqual(stream.getvalue(), expected_qasm)
def test_custom_gate_used_in_loop_scope(self):
"""Test that a custom gate only used within a loop scope still gets a definition at the top
level."""
parameter_a = Parameter("a")
parameter_b = Parameter("b")
custom = QuantumCircuit(1)
custom.rx(parameter_a, 0)
custom_gate = custom.bind_parameters({parameter_a: 0.5}).to_gate()
custom_gate.name = "custom"
loop_body = QuantumCircuit(1)
loop_body.append(custom_gate, [0])
qc = QuantumCircuit(1)
qc.for_loop(range(2), parameter_b, loop_body, [0], [])
expected_qasm = "\n".join(
[
"OPENQASM 3;",
'include "stdgates.inc";',
"gate custom _gate_q_0 {",
" rx(0.5) _gate_q_0;",
"}",
"qubit[1] q;",
"for b in [0:1] {",
" custom q[0];",
"}",
"",
]
)
self.assertEqual(dumps(qc), expected_qasm)
def test_registers_have_escaped_names(self):
"""Test that both types of register are emitted with safely escaped names if they begin with
invalid names. Regression test of gh-9658."""
qc = QuantumCircuit(
QuantumRegister(2, name="q_{reg}"), ClassicalRegister(2, name="c_{reg}")
)
qc.measure([0, 1], [0, 1])
out_qasm = dumps(qc)
matches = {match_["name"] for match_ in self.register_regex.finditer(out_qasm)}
self.assertEqual(len(matches), 2, msg=f"Observed OQ3 output:\n{out_qasm}")
def test_parameters_have_escaped_names(self):
"""Test that parameters are emitted with safely escaped names if they begin with invalid
names. Regression test of gh-9658."""
qc = QuantumCircuit(1)
qc.u(Parameter("p_{0}"), 2 * Parameter("p_?0!"), 0, 0)
out_qasm = dumps(qc)
matches = {match_["name"] for match_ in self.scalar_parameter_regex.finditer(out_qasm)}
self.assertEqual(len(matches), 2, msg=f"Observed OQ3 output:\n{out_qasm}")
def test_parameter_expression_after_naming_escape(self):
"""Test that :class:`.Parameter` instances are correctly renamed when they are used with
:class:`.ParameterExpression` blocks, even if they have names that needed to be escaped."""
param = Parameter("measure") # an invalid name
qc = QuantumCircuit(1)
qc.u(2 * param, 0, 0, 0)
expected_qasm = "\n".join(
[
"OPENQASM 3;",
'include "stdgates.inc";',
"input float[64] _measure;",
"qubit[1] q;",
"U(2*_measure, 0, 0) q[0];",
"",
]
)
self.assertEqual(dumps(qc), expected_qasm)
def test_parameters_and_registers_cannot_have_naming_clashes(self):
"""Test that parameters and registers are considered part of the same symbol table for the
purposes of avoiding clashes."""
qreg = QuantumRegister(1, "clash")
param = Parameter("clash")
qc = QuantumCircuit(qreg)
qc.u(param, 0, 0, 0)
out_qasm = dumps(qc)
register_name = self.register_regex.search(out_qasm)
parameter_name = self.scalar_parameter_regex.search(out_qasm)
self.assertTrue(register_name)
self.assertTrue(parameter_name)
self.assertIn("clash", register_name["name"])
self.assertIn("clash", parameter_name["name"])
self.assertNotEqual(register_name["name"], parameter_name["name"])
# Not necessarily all the reserved keywords, just a sensibly-sized subset.
@data("bit", "const", "def", "defcal", "float", "gate", "include", "int", "let", "measure")
def test_reserved_keywords_as_names_are_escaped(self, keyword):
"""Test that reserved keywords used to name registers and parameters are escaped into
another form when output, and the escaping cannot introduce new conflicts."""
with self.subTest("register"):
qreg = QuantumRegister(1, keyword)
qc = QuantumCircuit(qreg)
out_qasm = dumps(qc)
register_name = self.register_regex.search(out_qasm)
self.assertTrue(register_name, msg=f"Observed OQ3:\n{out_qasm}")
self.assertNotEqual(keyword, register_name["name"])
with self.subTest("parameter"):
qc = QuantumCircuit(1)
param = Parameter(keyword)
qc.u(param, 0, 0, 0)
out_qasm = dumps(qc)
parameter_name = self.scalar_parameter_regex.search(out_qasm)
self.assertTrue(parameter_name, msg=f"Observed OQ3:\n{out_qasm}")
self.assertNotEqual(keyword, parameter_name["name"])
def test_expr_condition(self):
"""Simple test that the conditions of `if`s and `while`s can be `Expr` nodes."""
bits = [Qubit(), Clbit()]
cr = ClassicalRegister(2, "cr")
if_body = QuantumCircuit(1)
if_body.x(0)
while_body = QuantumCircuit(1)
while_body.x(0)
qc = QuantumCircuit(bits, cr)
qc.if_test(expr.logic_not(qc.clbits[0]), if_body, [0], [])
qc.while_loop(expr.equal(cr, 3), while_body, [0], [])
expected = """\
OPENQASM 3;
include "stdgates.inc";
bit _bit0;
bit[2] cr;
qubit _qubit0;
if (!_bit0) {
x _qubit0;
}
while (cr == 3) {
x _qubit0;
}
"""
self.assertEqual(dumps(qc), expected)
def test_expr_nested_condition(self):
"""Simple test that the conditions of `if`s and `while`s can be `Expr` nodes when nested,
and the mapping of inner bits to outer bits is correct."""
bits = [Qubit(), Clbit(), Clbit()]
cr = ClassicalRegister(2, "cr")
inner_if_body = QuantumCircuit(1)
inner_if_body.x(0)
outer_if_body = QuantumCircuit(1, 1)
outer_if_body.if_test(expr.lift(outer_if_body.clbits[0]), inner_if_body, [0], [])
inner_while_body = QuantumCircuit(1)
inner_while_body.x(0)
outer_while_body = QuantumCircuit([Qubit()], cr)
outer_while_body.while_loop(expr.equal(expr.bit_and(cr, 3), 3), inner_while_body, [0], [])
qc = QuantumCircuit(bits, cr)
qc.if_test(expr.logic_not(qc.clbits[0]), outer_if_body, [0], [1])
qc.while_loop(expr.equal(cr, 3), outer_while_body, [0], cr)
expected = """\
OPENQASM 3;
include "stdgates.inc";
bit _bit0;
bit _bit1;
bit[2] cr;
qubit _qubit0;
if (!_bit0) {
if (_bit1) {
x _qubit0;
}
}
while (cr == 3) {
while ((cr & 3) == 3) {
x _qubit0;
}
}
"""
self.assertEqual(dumps(qc), expected)
def test_expr_associativity_left(self):
"""Test that operations that are in the expression tree in a left-associative form are
output to OQ3 correctly."""
body = QuantumCircuit()
cr1 = ClassicalRegister(3, "cr1")
cr2 = ClassicalRegister(3, "cr2")
cr3 = ClassicalRegister(3, "cr3")
qc = QuantumCircuit(cr1, cr2, cr3)
qc.if_test(expr.equal(expr.bit_and(expr.bit_and(cr1, cr2), cr3), 7), body.copy(), [], [])
qc.if_test(expr.equal(expr.bit_or(expr.bit_or(cr1, cr2), cr3), 7), body.copy(), [], [])
qc.if_test(expr.equal(expr.bit_xor(expr.bit_xor(cr1, cr2), cr3), 7), body.copy(), [], [])
qc.if_test(expr.logic_and(expr.logic_and(cr1[0], cr1[1]), cr1[2]), body.copy(), [], [])
qc.if_test(expr.logic_or(expr.logic_or(cr1[0], cr1[1]), cr1[2]), body.copy(), [], [])
# Note that bitwise operations have lower priority than `==` so there's extra parentheses.
# All these operators are left-associative in OQ3.
expected = """\
OPENQASM 3;
include "stdgates.inc";
bit[3] cr1;
bit[3] cr2;
bit[3] cr3;
if ((cr1 & cr2 & cr3) == 7) {
}
if ((cr1 | cr2 | cr3) == 7) {
}
if ((cr1 ^ cr2 ^ cr3) == 7) {
}
if (cr1[0] && cr1[1] && cr1[2]) {
}
if (cr1[0] || cr1[1] || cr1[2]) {
}
"""
self.assertEqual(dumps(qc), expected)
def test_expr_associativity_right(self):
"""Test that operations that are in the expression tree in a right-associative form are
output to OQ3 correctly."""
body = QuantumCircuit()
cr1 = ClassicalRegister(3, "cr1")
cr2 = ClassicalRegister(3, "cr2")
cr3 = ClassicalRegister(3, "cr3")
qc = QuantumCircuit(cr1, cr2, cr3)
qc.if_test(expr.equal(expr.bit_and(cr1, expr.bit_and(cr2, cr3)), 7), body.copy(), [], [])
qc.if_test(expr.equal(expr.bit_or(cr1, expr.bit_or(cr2, cr3)), 7), body.copy(), [], [])
qc.if_test(expr.equal(expr.bit_xor(cr1, expr.bit_xor(cr2, cr3)), 7), body.copy(), [], [])
qc.if_test(expr.logic_and(cr1[0], expr.logic_and(cr1[1], cr1[2])), body.copy(), [], [])
qc.if_test(expr.logic_or(cr1[0], expr.logic_or(cr1[1], cr1[2])), body.copy(), [], [])
# Note that bitwise operations have lower priority than `==` so there's extra parentheses.
# All these operators are left-associative in OQ3, so we need parentheses for them to be
# parsed correctly. Mathematically, they're all actually associative in general, so the
# order doesn't _technically_ matter.
expected = """\
OPENQASM 3;
include "stdgates.inc";
bit[3] cr1;
bit[3] cr2;
bit[3] cr3;
if ((cr1 & (cr2 & cr3)) == 7) {
}
if ((cr1 | (cr2 | cr3)) == 7) {
}
if ((cr1 ^ (cr2 ^ cr3)) == 7) {
}
if (cr1[0] && (cr1[1] && cr1[2])) {
}
if (cr1[0] || (cr1[1] || cr1[2])) {
}
"""
self.assertEqual(dumps(qc), expected)
def test_expr_binding_unary(self):
"""Test that nested unary operators don't insert unnecessary brackets."""
body = QuantumCircuit()
cr = ClassicalRegister(2, "cr")
qc = QuantumCircuit(cr)
qc.if_test(expr.equal(expr.bit_not(expr.bit_not(cr)), 3), body.copy(), [], [])
qc.if_test(expr.logic_not(expr.logic_not(cr[0])), body.copy(), [], [])
expected = """\
OPENQASM 3;
include "stdgates.inc";
bit[2] cr;
if (~~cr == 3) {
}
if (!!cr[0]) {
}
"""
self.assertEqual(dumps(qc), expected)
def test_expr_precedence(self):
"""Test that the precedence properties of operators are correctly output."""
body = QuantumCircuit()
cr = ClassicalRegister(2, "cr")
# This tree is _completely_ inside out, so there's brackets needed round every operand.
inside_out = expr.logic_not(
expr.less(
expr.bit_and(
expr.bit_xor(expr.bit_or(cr, cr), expr.bit_or(cr, cr)),
expr.bit_xor(expr.bit_or(cr, cr), expr.bit_or(cr, cr)),
),
expr.bit_and(
expr.bit_xor(expr.bit_or(cr, cr), expr.bit_or(cr, cr)),
expr.bit_xor(expr.bit_or(cr, cr), expr.bit_or(cr, cr)),
),
)
)
# This one is the other way round - the tightest-binding operations are on the inside, so no
# brackets should be needed at all except to put in a comparison to a bitwise binary
# operation, since those bind less tightly than anything that can cast them to a bool.
outside_in = expr.logic_or(
expr.logic_and(
expr.equal(expr.bit_or(cr, cr), expr.bit_and(cr, cr)),
expr.equal(expr.bit_and(cr, cr), expr.bit_or(cr, cr)),
),
expr.logic_and(
expr.greater(expr.bit_or(cr, cr), expr.bit_xor(cr, cr)),
expr.less_equal(expr.bit_xor(cr, cr), expr.bit_or(cr, cr)),
),
)
# And an extra test of the logical operator order.
logics = expr.logic_or(
expr.logic_and(
expr.logic_or(expr.logic_not(cr[0]), expr.logic_not(cr[0])),
expr.logic_not(expr.logic_and(cr[0], cr[0])),
),
expr.logic_and(
expr.logic_not(expr.logic_and(cr[0], cr[0])),
expr.logic_or(expr.logic_not(cr[0]), expr.logic_not(cr[0])),
),
)
qc = QuantumCircuit(cr)
qc.if_test(inside_out, body.copy(), [], [])
qc.if_test(outside_in, body.copy(), [], [])
qc.if_test(logics, body.copy(), [], [])
expected = """\
OPENQASM 3;
include "stdgates.inc";
bit[2] cr;
if (!((((cr | cr) ^ (cr | cr)) & ((cr | cr) ^ (cr | cr)))\
< (((cr | cr) ^ (cr | cr)) & ((cr | cr) ^ (cr | cr))))) {
}
if ((cr | cr) == (cr & cr) && (cr & cr) == (cr | cr)\
|| (cr | cr) > (cr ^ cr) && (cr ^ cr) <= (cr | cr)) {
}
if ((!cr[0] || !cr[0]) && !(cr[0] && cr[0]) || !(cr[0] && cr[0]) && (!cr[0] || !cr[0])) {
}
"""
self.assertEqual(dumps(qc), expected)
def test_no_unnecessary_cast(self):
"""This is a bit of a cross `Expr`-constructor / OQ3-exporter test. It doesn't really
matter whether or not the `Expr` constructor functions insert cast nodes into their output
for the literals (at the time of writing [commit 2616602], they don't because they do some
type inference) but the OQ3 export definitely shouldn't have them."""
cr = ClassicalRegister(8, "cr")
qc = QuantumCircuit(cr)
# Note that the integer '1' has a minimum bit-width of 1, whereas the register has a width
# of 8. We're testing to make sure that there's no spurious cast up from `bit[1]` to
# `bit[8]`, or anything like that, _whether or not_ the `Expr` node includes one.
qc.if_test(expr.equal(cr, 1), QuantumCircuit(), [], [])
expected = """\
OPENQASM 3;
include "stdgates.inc";
bit[8] cr;
if (cr == 1) {
}
"""
self.assertEqual(dumps(qc), expected)
class TestCircuitQASM3ExporterTemporaryCasesWithBadParameterisation(QiskitTestCase):
"""Test functionality that is not what we _want_, but is what we need to do while the definition
of custom gates with parameterisation does not work correctly.
These tests are modified versions of those marked with the `requires_fixed_parameterisation`
decorator, and this whole class can be deleted once those are fixed. See gh-7335.
"""
maxDiff = 1_000_000
def test_basis_gates(self):
"""Teleportation with physical qubits"""
qc = QuantumCircuit(3, 2)
first_h = qc.h(1)[0].operation
qc.cx(1, 2)
qc.barrier()
qc.cx(0, 1)
qc.h(0)
qc.barrier()
qc.measure([0, 1], [0, 1])
qc.barrier()
first_x = qc.x(2).c_if(qc.clbits[1], 1)[0].operation
qc.z(2).c_if(qc.clbits[0], 1)
u2 = first_h.definition.data[0].operation
u3_1 = u2.definition.data[0].operation
u3_2 = first_x.definition.data[0].operation
expected_qasm = "\n".join(
[
"OPENQASM 3;",
f"gate u3_{id(u3_1)}(_gate_p_0, _gate_p_1, _gate_p_2) _gate_q_0 {{",
" U(pi/2, 0, pi) _gate_q_0;",
"}",
f"gate u2_{id(u2)}(_gate_p_0, _gate_p_1) _gate_q_0 {{",
f" u3_{id(u3_1)}(pi/2, 0, pi) _gate_q_0;",
"}",
"gate h _gate_q_0 {",
f" u2_{id(u2)}(0, pi) _gate_q_0;",
"}",
f"gate u3_{id(u3_2)}(_gate_p_0, _gate_p_1, _gate_p_2) _gate_q_0 {{",
" U(pi, 0, pi) _gate_q_0;",
"}",
"gate x _gate_q_0 {",
f" u3_{id(u3_2)}(pi, 0, pi) _gate_q_0;",
"}",
"bit[2] c;",
"qubit[3] q;",
"h q[1];",
"cx q[1], q[2];",
"barrier q[0], q[1], q[2];",
"cx q[0], q[1];",
"h q[0];",
"barrier q[0], q[1], q[2];",
"c[0] = measure q[0];",
"c[1] = measure q[1];",
"barrier q[0], q[1], q[2];",
"if (c[1]) {",
" x q[2];",
"}",
"if (c[0]) {",
" z q[2];",
"}",
"",
]
)
self.assertEqual(
Exporter(includes=[], basis_gates=["cx", "z", "U"]).dumps(qc),
expected_qasm,
)
def test_teleportation(self):
"""Teleportation with physical qubits"""
qc = QuantumCircuit(3, 2)
qc.h(1)
qc.cx(1, 2)
qc.barrier()
qc.cx(0, 1)
qc.h(0)
qc.barrier()
qc.measure([0, 1], [0, 1])
qc.barrier()
qc.x(2).c_if(qc.clbits[1], 1)
qc.z(2).c_if(qc.clbits[0], 1)
transpiled = transpile(qc, initial_layout=[0, 1, 2])
first_h = transpiled.data[0].operation
u2 = first_h.definition.data[0].operation
u3_1 = u2.definition.data[0].operation
first_x = transpiled.data[-2].operation
u3_2 = first_x.definition.data[0].operation
first_z = transpiled.data[-1].operation
u1 = first_z.definition.data[0].operation
u3_3 = u1.definition.data[0].operation
expected_qasm = "\n".join(
[
"OPENQASM 3;",
f"gate u3_{id(u3_1)}(_gate_p_0, _gate_p_1, _gate_p_2) _gate_q_0 {{",
" U(pi/2, 0, pi) _gate_q_0;",
"}",
f"gate u2_{id(u2)}(_gate_p_0, _gate_p_1) _gate_q_0 {{",
f" u3_{id(u3_1)}(pi/2, 0, pi) _gate_q_0;",
"}",
"gate h _gate_q_0 {",
f" u2_{id(u2)}(0, pi) _gate_q_0;",
"}",
"gate cx c, t {",
" ctrl @ U(pi, 0, pi) c, t;",
"}",
f"gate u3_{id(u3_2)}(_gate_p_0, _gate_p_1, _gate_p_2) _gate_q_0 {{",
" U(pi, 0, pi) _gate_q_0;",
"}",
"gate x _gate_q_0 {",
f" u3_{id(u3_2)}(pi, 0, pi) _gate_q_0;",
"}",
f"gate u3_{id(u3_3)}(_gate_p_0, _gate_p_1, _gate_p_2) _gate_q_0 {{",
" U(0, 0, pi) _gate_q_0;",
"}",
f"gate u1_{id(u1)}(_gate_p_0) _gate_q_0 {{",
f" u3_{id(u3_3)}(0, 0, pi) _gate_q_0;",
"}",
"gate z _gate_q_0 {",
f" u1_{id(u1)}(pi) _gate_q_0;",
"}",
"bit[2] c;",
"h $1;",
"cx $1, $2;",
"barrier $0, $1, $2;",
"cx $0, $1;",
"h $0;",
"barrier $0, $1, $2;",
"c[0] = measure $0;",
"c[1] = measure $1;",
"barrier $0, $1, $2;",
"if (c[1]) {",
" x $2;",
"}",
"if (c[0]) {",
" z $2;",
"}",
"",
]
)
self.assertEqual(Exporter(includes=[]).dumps(transpiled), expected_qasm)
def test_custom_gate_with_params_bound_main_call(self):
"""Custom gate with unbound parameters that are bound in the main circuit"""
parameter0 = Parameter("p0")
parameter1 = Parameter("p1")
custom = QuantumCircuit(2, name="custom")
custom.rz(parameter0, 0)
custom.rz(parameter1 / 2, 1)
qr_all_qubits = QuantumRegister(3, "q")
qr_r = QuantumRegister(3, "r")
circuit = QuantumCircuit(qr_all_qubits, qr_r)
circuit.append(custom.to_gate(), [qr_all_qubits[0], qr_r[0]])
circuit.assign_parameters({parameter0: pi, parameter1: pi / 2}, inplace=True)
custom_id = id(circuit.data[0].operation)
expected_qasm = "\n".join(
[
"OPENQASM 3;",
'include "stdgates.inc";',
f"gate custom_{custom_id}(_gate_p_0, _gate_p_1) _gate_q_0, _gate_q_1 {{",
" rz(pi) _gate_q_0;",
" rz(pi/4) _gate_q_1;",
"}",
"qubit[3] q;",
"qubit[3] r;",
f"custom_{custom_id}(pi, pi/2) q[0], r[0];",
"",
]
)
self.assertEqual(Exporter().dumps(circuit), expected_qasm)
def test_no_include(self):
"""Test explicit gate declaration (no include)"""
q = QuantumRegister(2, "q")
circuit = QuantumCircuit(q)
circuit.rz(pi / 2, 0)
circuit.sx(0)
circuit.cx(0, 1)
rz = circuit.data[0].operation
u1_1 = rz.definition.data[0].operation
u3_1 = u1_1.definition.data[0].operation
sx = circuit.data[1].operation
sdg = sx.definition.data[0].operation
u1_2 = sdg.definition.data[0].operation
u3_2 = u1_2.definition.data[0].operation
h_ = sx.definition.data[1].operation
u2_1 = h_.definition.data[0].operation
u3_3 = u2_1.definition.data[0].operation
expected_qasm = "\n".join(
[
"OPENQASM 3;",
f"gate u3_{id(u3_1)}(_gate_p_0, _gate_p_1, _gate_p_2) _gate_q_0 {{",
" U(0, 0, pi/2) _gate_q_0;",
"}",
f"gate u1_{id(u1_1)}(_gate_p_0) _gate_q_0 {{",
f" u3_{id(u3_1)}(0, 0, pi/2) _gate_q_0;",
"}",
f"gate rz_{id(rz)}(_gate_p_0) _gate_q_0 {{",
f" u1_{id(u1_1)}(pi/2) _gate_q_0;",
"}",
f"gate u3_{id(u3_2)}(_gate_p_0, _gate_p_1, _gate_p_2) _gate_q_0 {{",
" U(0, 0, -pi/2) _gate_q_0;",
"}",
f"gate u1_{id(u1_2)}(_gate_p_0) _gate_q_0 {{",
f" u3_{id(u3_2)}(0, 0, -pi/2) _gate_q_0;",
"}",
"gate sdg _gate_q_0 {",
f" u1_{id(u1_2)}(-pi/2) _gate_q_0;",
"}",
f"gate u3_{id(u3_3)}(_gate_p_0, _gate_p_1, _gate_p_2) _gate_q_0 {{",
" U(pi/2, 0, pi) _gate_q_0;",
"}",
f"gate u2_{id(u2_1)}(_gate_p_0, _gate_p_1) _gate_q_0 {{",
f" u3_{id(u3_3)}(pi/2, 0, pi) _gate_q_0;",
"}",
"gate h _gate_q_0 {",
f" u2_{id(u2_1)}(0, pi) _gate_q_0;",
"}",
"gate sx _gate_q_0 {",
" sdg _gate_q_0;",
" h _gate_q_0;",
" sdg _gate_q_0;",
"}",
"gate cx c, t {",
" ctrl @ U(pi, 0, pi) c, t;",
"}",
"qubit[2] q;",
f"rz_{id(rz)}(pi/2) q[0];",
"sx q[0];",
"cx q[0], q[1];",
"",
]
)
self.assertEqual(Exporter(includes=[]).dumps(circuit), expected_qasm)
def test_unusual_conditions(self):
"""Test that special QASM constructs such as ``measure`` are correctly handled when the
Terra instructions have old-style conditions."""
qc = QuantumCircuit(3, 2)
qc.h(0)
qc.measure(0, 0)
qc.measure(1, 1).c_if(0, True)
qc.reset([0, 1]).c_if(0, True)
with qc.while_loop((qc.clbits[0], True)):
qc.break_loop().c_if(0, True)
qc.continue_loop().c_if(0, True)
# Terra forbids delay and barrier from being conditioned through `c_if`, but in theory they
# should work fine in a dynamic-circuits sense (although what a conditional barrier _means_
# is a whole other kettle of fish).
delay = Delay(16, "dt")
delay.condition = (qc.clbits[0], True)
qc.append(delay, [0], [])
barrier = Barrier(2)
barrier.condition = (qc.clbits[0], True)
qc.append(barrier, [0, 1], [])
expected = """
OPENQASM 3;
include "stdgates.inc";
bit[2] c;
qubit[3] q;
h q[0];
c[0] = measure q[0];
if (c[0]) {
c[1] = measure q[1];
}
if (c[0]) {
reset q[0];
}
if (c[0]) {
reset q[1];
}
while (c[0]) {
if (c[0]) {
break;
}
if (c[0]) {
continue;
}
}
if (c[0]) {
delay[16dt] q[0];
}
if (c[0]) {
barrier q[0], q[1];
}"""
self.assertEqual(dumps(qc).strip(), expected.strip())
class TestExperimentalFeatures(QiskitTestCase):
"""Tests of features that are hidden behind experimental flags."""
maxDiff = None
def test_switch_forbidden_without_flag(self):
"""Omitting the feature flag should raise an error."""
case = QuantumCircuit(1)
circuit = QuantumCircuit(1, 1)
circuit.switch(circuit.clbits[0], [((True, False), case)], [0], [])
with self.assertRaisesRegex(QASM3ExporterError, "'switch' statements are not stabilized"):
dumps(circuit)
def test_switch_clbit(self):
"""Test that a switch statement can be constructed with a bit as a condition."""
qubit = Qubit()
clbit = Clbit()
case1 = QuantumCircuit([qubit, clbit])
case1.x(0)
case2 = QuantumCircuit([qubit, clbit])
case2.z(0)
circuit = QuantumCircuit([qubit, clbit])
circuit.switch(clbit, [(True, case1), (False, case2)], [0], [0])
test = dumps(circuit, experimental=ExperimentalFeatures.SWITCH_CASE_V1)
expected = """\
OPENQASM 3;
include "stdgates.inc";
bit _bit0;
int switch_dummy;
qubit _qubit0;
switch_dummy = _bit0;
switch (switch_dummy) {
case 1: {
x _qubit0;
}
break;
case 0: {
z _qubit0;
}
break;
}
"""
self.assertEqual(test, expected)
def test_switch_register(self):
"""Test that a switch statement can be constructed with a register as a condition."""
qubit = Qubit()
creg = ClassicalRegister(2, "c")
case1 = QuantumCircuit([qubit], creg)
case1.x(0)
case2 = QuantumCircuit([qubit], creg)
case2.y(0)
case3 = QuantumCircuit([qubit], creg)
case3.z(0)
circuit = QuantumCircuit([qubit], creg)
circuit.switch(creg, [(0, case1), (1, case2), (2, case3)], [0], circuit.clbits)
test = dumps(circuit, experimental=ExperimentalFeatures.SWITCH_CASE_V1)
expected = """\
OPENQASM 3;
include "stdgates.inc";
bit[2] c;
int switch_dummy;
qubit _qubit0;
switch_dummy = c;
switch (switch_dummy) {
case 0: {
x _qubit0;
}
break;
case 1: {
y _qubit0;
}
break;
case 2: {
z _qubit0;
}
break;
}
"""
self.assertEqual(test, expected)
def test_switch_with_default(self):
"""Test that a switch statement can be constructed with a default case at the end."""
qubit = Qubit()
creg = ClassicalRegister(2, "c")
case1 = QuantumCircuit([qubit], creg)
case1.x(0)
case2 = QuantumCircuit([qubit], creg)
case2.y(0)
case3 = QuantumCircuit([qubit], creg)
case3.z(0)
circuit = QuantumCircuit([qubit], creg)
circuit.switch(creg, [(0, case1), (1, case2), (CASE_DEFAULT, case3)], [0], circuit.clbits)
test = dumps(circuit, experimental=ExperimentalFeatures.SWITCH_CASE_V1)
expected = """\
OPENQASM 3;
include "stdgates.inc";
bit[2] c;
int switch_dummy;
qubit _qubit0;
switch_dummy = c;
switch (switch_dummy) {
case 0: {
x _qubit0;
}
break;
case 1: {
y _qubit0;
}
break;
default: {
z _qubit0;
}
break;
}
"""
self.assertEqual(test, expected)
def test_switch_multiple_cases_to_same_block(self):
"""Test that it is possible to add multiple cases that apply to the same block, if they are
given as a compound value. This is an allowed special case of block fall-through."""
qubit = Qubit()
creg = ClassicalRegister(2, "c")
case1 = QuantumCircuit([qubit], creg)
case1.x(0)
case2 = QuantumCircuit([qubit], creg)
case2.y(0)
circuit = QuantumCircuit([qubit], creg)
circuit.switch(creg, [(0, case1), ((1, 2), case2)], [0], circuit.clbits)
test = dumps(circuit, experimental=ExperimentalFeatures.SWITCH_CASE_V1)
expected = """\
OPENQASM 3;
include "stdgates.inc";
bit[2] c;
int switch_dummy;
qubit _qubit0;
switch_dummy = c;
switch (switch_dummy) {
case 0: {
x _qubit0;
}
break;
case 1:
case 2: {
y _qubit0;
}
break;
}
"""
self.assertEqual(test, expected)
def test_multiple_switches_dont_clash_on_dummy(self):
"""Test that having more than one switch statement in the circuit doesn't cause naming
clashes in the dummy integer value used."""
qubit = Qubit()
creg = ClassicalRegister(2, "switch_dummy")
case1 = QuantumCircuit([qubit], creg)
case1.x(0)
case2 = QuantumCircuit([qubit], creg)
case2.y(0)
circuit = QuantumCircuit([qubit], creg)
circuit.switch(creg, [(0, case1), ((1, 2), case2)], [0], circuit.clbits)
circuit.switch(creg, [(0, case1), ((1, 2), case2)], [0], circuit.clbits)
test = dumps(circuit, experimental=ExperimentalFeatures.SWITCH_CASE_V1)
expected = """\
OPENQASM 3;
include "stdgates.inc";
bit[2] switch_dummy;
int switch_dummy__generated0;
int switch_dummy__generated1;
qubit _qubit0;
switch_dummy__generated0 = switch_dummy;
switch (switch_dummy__generated0) {
case 0: {
x _qubit0;
}
break;
case 1:
case 2: {
y _qubit0;
}
break;
}
switch_dummy__generated1 = switch_dummy;
switch (switch_dummy__generated1) {
case 0: {
x _qubit0;
}
break;
case 1:
case 2: {
y _qubit0;
}
break;
}
"""
self.assertEqual(test, expected)
def test_switch_nested_in_if(self):
"""Test that the switch statement works when in a nested scope, including the dummy
classical variable being declared globally. This isn't necessary in the OQ3 language, but
it is universally valid and the IBM QSS stack prefers that. They're our primary consumers
of OQ3 strings, so it's best to play nicely with them."""
qubit = Qubit()
creg = ClassicalRegister(2, "c")
case1 = QuantumCircuit([qubit], creg)
case1.x(0)
case2 = QuantumCircuit([qubit], creg)
case2.y(0)
body = QuantumCircuit([qubit], creg)
body.switch(creg, [(0, case1), ((1, 2), case2)], [0], body.clbits)
circuit = QuantumCircuit([qubit], creg)
circuit.if_else((creg, 1), body.copy(), body, [0], body.clbits)
test = dumps(circuit, experimental=ExperimentalFeatures.SWITCH_CASE_V1)
expected = """\
OPENQASM 3;
include "stdgates.inc";
bit[2] c;
int switch_dummy;
int switch_dummy__generated0;
qubit _qubit0;
if (c == 1) {
switch_dummy = c;
switch (switch_dummy) {
case 0: {
x _qubit0;
}
break;
case 1:
case 2: {
y _qubit0;
}
break;
}
} else {
switch_dummy__generated0 = c;
switch (switch_dummy__generated0) {
case 0: {
x _qubit0;
}
break;
case 1:
case 2: {
y _qubit0;
}
break;
}
}
"""
self.assertEqual(test, expected)
def test_expr_target(self):
"""Simple test that the target of `switch` can be `Expr` nodes."""
bits = [Qubit(), Clbit()]
cr = ClassicalRegister(2, "cr")
case0 = QuantumCircuit(1)
case0.x(0)
case1 = QuantumCircuit(1)
case1.x(0)
qc = QuantumCircuit(bits, cr)
qc.switch(expr.logic_not(bits[1]), [(False, case0)], [0], [])
qc.switch(expr.bit_and(cr, 3), [(3, case1)], [0], [])
expected = """\
OPENQASM 3;
include "stdgates.inc";
bit _bit0;
bit[2] cr;
int switch_dummy;
int switch_dummy__generated0;
qubit _qubit0;
switch_dummy = !_bit0;
switch (switch_dummy) {
case 0: {
x _qubit0;
}
break;
}
switch_dummy__generated0 = cr & 3;
switch (switch_dummy__generated0) {
case 3: {
x _qubit0;
}
break;
}
"""
test = dumps(qc, experimental=ExperimentalFeatures.SWITCH_CASE_V1)
self.assertEqual(test, expected)
@ddt
class TestQASM3ExporterFailurePaths(QiskitTestCase):
"""Tests of the failure paths for the exporter."""
def test_disallow_overlapping_classical_registers_if_no_aliasing(self):
"""Test that the exporter rejects circuits with a classical bit in more than one register if
the ``alias_classical_registers`` option is set false."""
qubits = [Qubit() for _ in [None] * 3]
clbits = [Clbit() for _ in [None] * 5]
registers = [ClassicalRegister(bits=clbits[:4]), ClassicalRegister(bits=clbits[1:])]
qc = QuantumCircuit(qubits, *registers)
exporter = Exporter(alias_classical_registers=False)
with self.assertRaisesRegex(QASM3ExporterError, r"classical registers .* overlap"):
exporter.dumps(qc)
@data([1, 2, 1.1], [1j, 2])
def test_disallow_for_loops_with_non_integers(self, indices):
"""Test that the exporter rejects ``for`` loops that include non-integer values in their
index sets."""
loop_body = QuantumCircuit()
qc = QuantumCircuit(2, 2)
qc.for_loop(indices, None, loop_body, [], [])
exporter = Exporter()
with self.assertRaisesRegex(
QASM3ExporterError, r"The values in QASM 3 'for' loops must all be integers.*"
):
exporter.dumps(qc)
def test_disallow_custom_subroutine_with_parameters(self):
"""Test that the exporter throws an error instead of trying to export a subroutine with
parameters, while this is not supported."""
subroutine = QuantumCircuit(1)
subroutine.rx(Parameter("x"), 0)
qc = QuantumCircuit(1)
qc.append(subroutine.to_instruction(), [0], [])
exporter = Exporter()
with self.assertRaisesRegex(
QASM3ExporterError, "Exporting non-unitary instructions is not yet supported"
):
exporter.dumps(qc)
def test_disallow_opaque_instruction(self):
"""Test that the exporter throws an error instead of trying to export something into a
``defcal`` block, while this is not supported."""
qc = QuantumCircuit(1)
qc.append(Instruction("opaque", 1, 0, []), [0], [])
exporter = Exporter()
with self.assertRaisesRegex(
QASM3ExporterError, "Exporting opaque instructions .* is not yet supported"
):
exporter.dumps(qc)
|
https://github.com/mlvqc/Byskit
|
mlvqc
|
import numpy as np
import matplotlib.pyplot as plt
from qiskit import *
# First princinple for two parent nodes and one child
class byskit():
def __init__(self, provider, backend, n, parents, child):
self.provider = provider
self.backend = backend
self.parents = parents
self.child = child
self.n = n
self.ctrl = QuantumRegister(self.n, 'ctrl')
self.anc = QuantumRegister(self.n - 1, 'anc')
self.tgt = QuantumRegister(1, 'tgt')
self.circ = QuantumCircuit(self.ctrl, self.anc, self.tgt)
self.parent_init()
self.child_init()
self.circ.draw(output='mpl')
plt.show()
def parent_init(self):
for i in range(self.n):
theta = self.calc_theta(self.parents[2*i], self.parents[2*i+1])
self.circ.ry(theta, i)
self.circ.barrier()
def child_init(self):
self.a = np.arange(0, 2 ** self.n)
self.gates = []
for i in self.a:
s = str(np.binary_repr(i, width=self.n))
self.gates.append(s)
for i in range(2**self.n):
theta = self.calc_theta(self.child[2*i+1], self.child[2*i])
self.xgate(self.gates[i])
self.cn_ry(theta)
self.xgate(self.gates[i])
self.circ.barrier()
def xgate(self,gate):
for index, item in enumerate(gate):
if int(item) == 0:
self.circ.x(index)
#RY gates
def cn_ry(self,theta):
# compute
self.circ.ccx(self.ctrl[0], self.ctrl[1], self.anc[0])
for i in range(2, self.n):
self.circ.ccx(self.ctrl[i], self.anc[i - 2], self.anc[i - 1])
# copy
self.circ.cry(theta,self.anc[self.n - 2], self.tgt[0])
# uncompute
for i in range(self.n - 1, 1, -1):
self.circ.ccx(self.ctrl[i], self.anc[i - 2], self.anc[i - 1])
self.circ.ccx(self.ctrl[0], self.ctrl[1], self.anc[0])
def calc_theta(self,p1,p0):
return 2 * np.arctan(np.sqrt((p1)/(p0)))
#if __name__=='__main__':
from jupyterthemes import jtplot
jtplot.style(theme='monokai', context='notebook', ticks=True, grid=False)
from qiskit.tools.jupyter import *
from qiskit import IBMQ
IBMQ.load_account()
# provider = IBMQ.get_provider(hub='ibm-q', group='open', project='main')
provider = IBMQ.get_provider(hub='ibm-q-oxford', group='on-boarding', project='on-boarding-proj')
from qiskit import BasicAer
backend = BasicAer.get_backend('unitary_simulator')
n = 3
parents = np.random.rand(n*2)
child = np.random.rand(2**(n+1))
b = byskit(provider,backend,n,parents,child)
|
https://github.com/h-rathee851/Pulse_application_qiskit
|
h-rathee851
|
def speak(text):
from IPython.display import Javascript as js, clear_output
# Escape single quotes
text = text.replace("'", r"\'")
display(js(f'''
if(window.speechSynthesis) {{
var synth = window.speechSynthesis;
synth.speak(new window.SpeechSynthesisUtterance('{text}'));
}}
'''))
# Clear the JS so that the notebook doesn't speak again when reopened/refreshed
clear_output(False)
import numpy as np
# Importing standard Qiskit libraries
from qiskit import QuantumCircuit, transpile, Aer, IBMQ
from qiskit.tools.jupyter import *
from qiskit.visualization import *
# Loading your IBM Q account(s)
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q-research', group='iserc-1', project='main')
from qiskit import *
from matplotlib import pyplot as plt
backend = provider.get_backend('ibmq_armonk')
from qiskit import *
from qiskit.pulse import *
from qiskit.tools.monitor import job_monitor
qubit = 0
back_config = backend.configuration()
inst_sched_map = backend.defaults().instruction_schedule_map
meas_map_idx = None
for i, measure_group in enumerate(back_config.meas_map):
if qubit in measure_group:
meas_map_idx = i
break
assert meas_map_idx is not None, f"Couldn't find qubit {qubit} in the meas_map!"
measure = inst_sched_map.get('measure', qubits=back_config.meas_map[qubit])
pulse_sigma = 80
pulse_duration = (4*pulse_sigma)-((4*pulse_sigma)%16)
drive_chan = DriveChannel(0)
def create_cal_circuits(amp):
sched = Schedule()
sched+=Play(Gaussian(duration=pulse_duration, sigma=pulse_sigma, amp=amp), drive_chan)
measure = inst_sched_map.get('measure', qubits=[qubit])
sched+=measure << sched.duration
return sched
default_qubit_freq = backend.defaults().qubit_freq_est[0]
freq_list = np.linspace(default_qubit_freq-(20*1e+6), default_qubit_freq+(20*1e+6), 75)
sched_list = [create_cal_circuits(0.4)]*75
sweep_exp = assemble(sched_list, backend=backend, meas_level=1, meas_return='avg', shots=1024, schedule_los = [{drive_chan: freq} for freq in freq_list])
sweep_job = backend.run(sweep_exp)
job_monitor(sweep_job)
sweep_result = sweep_job.result()
sweep_values = []
for i in range(len(sweep_result.results)):
res = sweep_result.get_memory(i)*1e-14
sweep_values.append(res[qubit])
scale_factor = 1e+9
freq_list_scaled = freq_list/scale_factor
from scipy.optimize import curve_fit
def fit_function(x_values, y_values, function, init_params):
fitparams, conv = curve_fit(function, x_values, y_values, init_params)
y_fit = function(x_values, *fitparams)
return fitparams, y_fit
fit_params, y_fit = fit_function(freq_list_scaled,
np.real(sweep_values),
lambda x, A, q_freq, B, C: (A / np.pi) * (B / ((x - q_freq)**2 + B**2)) + C,
[5, 4.975, 1, 19] # initial parameters for curve_fit
)
plt.scatter(freq_list_scaled, np.real(sweep_values), color='black')
plt.plot(freq_list_scaled, y_fit, color='red')
plt.xlim([min(freq_list_scaled), max(freq_list_scaled)])
# plt.ylim([-7,0])
plt.xlabel("Frequency [GHz]")
plt.ylabel("Measured Signal [a.u.]")
plt.show()
_, qubit_freq_new, _, _ = fit_params
qubit_freq_ground = qubit_freq_new*scale_factor
speak("The test program is done.")
print(f"The new qubit frequency is : {qubit_freq_ground} Hz")
#### Moving on to the Rabi experiments for 0->1 transition.
amp_list = np.linspace(0, 1.0, 75)
rabi_sched_list = [create_cal_circuits(amp) for amp in amp_list]
rabi_exp = assemble(rabi_sched_list, backend=backend, meas_level=1, meas_return='avg', shots=1024, schedule_los=[{drive_chan: qubit_freq_ground}]*len(rabi_sched_list))
rabi_job = backend.run(rabi_exp)
job_monitor(rabi_job)
rabi_results = rabi_job.result()
scale_factor = 1e-14
rabi_values = []
for i in range(75):
# Get the results for `qubit` from the ith experiment
rabi_values.append(rabi_results.get_memory(i)[qubit]*scale_factor)
def baseline_remove(values):
return np.array(values) - np.mean(values)
rabi_values = np.real(baseline_remove(rabi_values))
fit_params, y_fit = fit_function(amp_list,
rabi_values,
lambda x, A, B, drive_period, phi: (A*np.sin(2*np.pi*x/drive_period - phi) + B),
[0.6, 0.1, 1.6, 0])
drive_period = fit_params[2]
pi_amp_ground = drive_period/2
plt.scatter(amp_list, rabi_values, color='black')
plt.plot(amp_list, y_fit, color='red')
plt.axvline(drive_period/2, color='red', linestyle='--')
plt.axvline(drive_period, color='red', linestyle='--')
plt.annotate("", xy=(drive_period, 0), xytext=(drive_period/2,0), arrowprops=dict(arrowstyle="<->", color='red'))
plt.annotate("$\pi$", xy=(drive_period/2-0.03, 0.1), color='red')
plt.xlabel("Drive amp [a.u.]", fontsize=15)
plt.ylabel("Measured signal [a.u.]", fontsize=15)
plt.show()
print(f"The calibrated pi amp is : {pi_amp_ground}")
def get_pi_pulse_ground():
try:
pulse = pulse_lib.gaussian(duration=pulse_duration, sigma=pulse_sigma, amp=pi_amp_ground)
except ValueError:
raise ValueError("pi_amp_ground not defined. Please compute pi_amp_ground first")
except Exception as err:
traceback.print_exc()
return pulse
def get_zero_sched():
zero_sched = Schedule()
zero_sched += measure
return zero_sched
def get_one_sched():
one_sched = Schedule()
one_sched += Play(get_pi_pulse_ground(), drive_chan)
one_sched += measure << one_sched.duration
return one_sched
def IQ_plot( zero_data, one_data):
"""Helper function for plotting IQ plane for 0, 1, 2. Limits of plot given
as arguments."""
# zero data plotted in blue
plt.scatter(np.real(zero_data), np.imag(zero_data),
s=5, cmap='viridis', c='blue', alpha=0.5, label=r'$|0\rangle$')
# one data plotted in red
plt.scatter(np.real(one_data), np.imag(one_data),
s=5, cmap='viridis', c='red', alpha=0.5, label=r'$|1\rangle$')
x_min = np.min(np.append(np.real(zero_data), np.real(one_data)))-5
x_max = np.max(np.append(np.real(zero_data), np.real(one_data)))+5
y_min = np.min(np.append(np.imag(zero_data), np.imag(one_data)))-5
y_max = np.max(np.append(np.imag(zero_data), np.imag(one_data)))+5
# Plot a large dot for the average result of the 0, 1 and 2 states.
mean_zero = np.mean(zero_data) # takes mean of both real and imaginary parts
mean_one = np.mean(one_data)
plt.scatter(np.real(mean_zero), np.imag(mean_zero),
s=200, cmap='viridis', c='black',alpha=1.0)
plt.scatter(np.real(mean_one), np.imag(mean_one),
s=200, cmap='viridis', c='black',alpha=1.0)
plt.xlim(x_min, x_max)
plt.ylim(y_min,y_max)
plt.legend()
plt.ylabel('I [a.u.]', fontsize=15)
plt.xlabel('Q [a.u.]', fontsize=15)
plt.title("0-1 discrimination", fontsize=15)
return x_min, x_max, y_min, y_max
def reshape_complex_vec( vec):
"""Take in complex vector vec and return 2d array w/ real, imag entries. This is needed for the learning.
Args:
vec (list): complex vector of data
Returns:
list: vector w/ entries given by (real(vec], imag(vec))
"""
length = len(vec)
vec_reshaped = np.zeros((length, 2))
for i in range(len(vec)):
vec_reshaped[i]=[np.real(vec[i]), np.imag(vec[i])]
return vec_reshaped
def separatrixPlot( lda, x_min, x_max, y_min, y_max, shots):
nx, ny = shots, shots
xx, yy = np.meshgrid(np.linspace(x_min, x_max, nx),
np.linspace(y_min, y_max, ny))
Z = lda.predict_proba(np.c_[xx.ravel(), yy.ravel()])
Z = Z[:, 1].reshape(xx.shape)
plt.contour(xx, yy, Z, [0.5], linewidths=2., colors='black')
measure = inst_sched_map.get('measure', qubits=[qubit])
one_sched = get_one_sched()
exp = assemble(one_sched, backend=backend, meas_level=2,
meas_return='single', shots=1024, schedule_los=[{drive_chan: qubit_freq_ground}])
qjob = backend.run(exp)
job_monitor(qjob)
print(qjob.result().get_counts())
# zero_sched = get_zero_sched()
# one_sched = get_one_sched()
# IQ_exp = assemble([zero_sched, one_sched], backend=backend,
# meas_level=1, meas_return='single', shots=1024,
# schedule_los=[{drive_chan: qubit_freq_ground}]*2
# )
IQ_exp_0 = assemble([zero_sched], backend=backend,
meas_level=1, meas_return='single', shots=1024,
schedule_los=[{drive_chan: qubit_freq_ground}]
)
IQ_job_0 = backend.run(IQ_exp_0)
print('Running job 1')
job_monitor(IQ_job_0)
IQ_exp_1 = assemble([one_sched], backend=backend,
meas_level=1, meas_return='single', shots=1024,
schedule_los=[{drive_chan: qubit_freq_ground}]
)
IQ_job_1 = backend.run(IQ_exp_1)
print('Running job 2')
job_monitor(IQ_job_1)
new_one_sched = Schedule()
new_one_sched += measure << pulse_duration
IQ_exp_11 = assemble([new_one_sched], backend=backend,
meas_level=1, meas_return='single', shots=1024,
schedule_los=[{drive_chan: qubit_freq_ground}]
)
IQ_job_11 = backend.run(IQ_exp_11)
print('Running job 3')
job_monitor(IQ_job_11)
new_one_sched_2 = Schedule()
new_one_sched_2 += measure << 2*pulse_duration
IQ_exp_12 = assemble([new_one_sched_2], backend=backend,
meas_level=1, meas_return='single', shots=1024,
schedule_los=[{drive_chan: qubit_freq_ground}]
)
IQ_job_12 = backend.run(IQ_exp_12)
print('Running job 4')
job_monitor(IQ_job_12)
data_0 = get_job_data(IQ_job_0, average=False)
data_1 = get_job_data(IQ_job_1, average=False)
data_11 = get_job_data(IQ_job_11, average=False)
data_12 = get_job_data(IQ_job_12, average=False)
plt.scatter(np.real(data_0[0]), np.imag(data_0[0]),
s=5, cmap='viridis', c='blue', alpha=0.5, label=r'0')
plt.scatter(np.real(data_1[0]), np.imag(data_1[0]),
s=5, cmap='viridis', c='red', alpha=0.5, label=r'1')
plt.scatter(np.real(data_11[0]), np.imag(data_11[0]),
s=5, cmap='viridis', c='yellow', alpha=0.5, label=r'11')
plt.scatter(np.real(data_12[0]), np.imag(data_12[0]),
s=5, cmap='viridis', c='green', alpha=0.5, label=r'12')
mean_0 = np.mean(data_0[0])
mean_1 = np.mean(data_1[0])
mean_11 = np.mean(data_11[0])
mean_12 = np.mean(data_12[0])
plt.scatter(np.real(mean_0), np.imag(mean_0),
s=200, cmap='viridis', c='black',alpha=1.0)
plt.scatter(np.real(mean_1), np.imag(mean_1),
s=200, cmap='viridis', c='black',alpha=1.0)
plt.scatter(np.real(mean_11), np.imag(mean_11),
s=200, cmap='viridis', c='black',alpha=1.0)
plt.scatter(np.real(mean_12), np.imag(mean_12),
s=200, cmap='viridis', c='black',alpha=1.0)
plt.legend()
zero_sched.draw() # 0
one_sched.draw() # 1
new_one_sched.draw() # 11
new_one_sched_2.draw() # 12
def get_job_data(job, average):
scale_factor = 1e-14
job_results = job.result(timeout=120) # timeout parameter set to 120 s
result_data = []
for i in range(len(job_results.results)):
if average: # get avg data
result_data.append(job_results.get_memory(i)[qubit]*scale_factor)
else: # get single data
result_data.append(job_results.get_memory(i)[:, qubit]*scale_factor)
return result_data
IQ_data = get_job_data(IQ_job, average=False)
zero_data = IQ_data[0]
one_data = IQ_data[1]
# zero_data = get_job_data(IQ_job_0, average=False)
# one_data = get_job_data(IQ_job_1, average=False)
from sklearn.model_selection import train_test_split
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
print("The discriminator plot for 0-1-2 discrimination.")
x_min, x_max, y_min, y_max = IQ_plot(zero_data, one_data)
# Create IQ vector (split real, imag parts)
zero_data_reshaped = reshape_complex_vec(zero_data)
one_data_reshaped = reshape_complex_vec(one_data)
IQ_data = np.concatenate((zero_data_reshaped, one_data_reshaped))
# construct vector w/ 0's, 1's and 2's (for testing)
state_012 = np.zeros(1024) # shots gives number of experiments
state_012 = np.concatenate((state_012, np.ones(1024)))
# state_012 = np.concatenate((state_012, 2*np.ones(1024)))
# Shuffle and split data into training and test sets
IQ_012_train, IQ_012_test, state_012_train, state_012_test = train_test_split(IQ_data, state_012, test_size=0.5)
LDA_012 = LinearDiscriminantAnalysis()
LDA_012.fit(IQ_012_train, state_012_train)
score_012 = LDA_012.score(IQ_012_test, state_012_test)
print('The accuracy score of the discriminator is: ', score_012)
# # _state_discriminator_012 = LDA_012
# if visual:
# IQ_plot(zero_data, one_data, two_data)
separatrixPlot(LDA_012, x_min, x_max, y_min, y_max, 1024)
new_exp_1 = assemble([new_one_sched], backend=backend,
meas_level=2, meas_return='single', shots=1024,
schedule_los=[{drive_chan: qubit_freq_ground}]
)
new_job_1 = backend.run(new_exp_1)
job_monitor(new_job_1)
new_one_sched.draw()
print(new_job_1.result().get_counts())
IQ_plot(new_data_0[0], new_data_1[0])
new_results = new_job.result()
new_data = get_job_data(new_job, average=False)
new_0_data = new_data[0]
new_1_data = new_data[1]
IQ_plot(new_0_data, new_1_data)
diff_one_sched = Schedule()
diff_one_sched += Play(Gaussian(duration=pulse_duration, sigma=pulse_sigma, amp=0), drive_chan)
diff_one_sched += measure
print(*np.around(zero_data[:10],2), sep='\n')
from sklearn.model_selection import train_test_split
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
print("The discriminator plot for 0-1-2 discrimination.")
x_min, x_max, y_min, y_max = IQ_plot(zero_data[0], one_data[0])
# Create IQ vector (split real, imag parts)
zero_data_reshaped = reshape_complex_vec(zero_data[0])
one_data_reshaped = reshape_complex_vec(one_data[0])
IQ_data = np.concatenate((zero_data_reshaped, one_data_reshaped))
# construct vector w/ 0's, 1's and 2's (for testing)
state_012 = np.zeros(1024) # shots gives number of experiments
state_012 = np.concatenate((state_012, np.ones(1024)))
# state_012 = np.concatenate((state_012, 2*np.ones(1024)))
# Shuffle and split data into training and test sets
IQ_012_train, IQ_012_test, state_012_train, state_012_test = train_test_split(IQ_data, state_012, test_size=0.5)
LDA_012 = LinearDiscriminantAnalysis()
LDA_012.fit(IQ_012_train, state_012_train)
score_012 = LDA_012.score(IQ_012_test, state_012_test)
print('The accuracy score of the discriminator is: ', score_012)
# _state_discriminator_012 = LDA_012
# if visual:
# IQ_plot(zero_data, one_data, two_data)
separatrixPlot(LDA_012, x_min, x_max, y_min, y_max, 1024)
speak('The test is over. Check it out.')
from qiskit.pulse import *
import qiskit.pulse.library as pulse_lib
from scipy.signal import find_peaks
### Next, going on to test the function to calibrate the 1->2 transition frequency
def apply_sideband(pulse, frequency):
t_samples = np.linspace(0, dt*pulse_duration, pulse_duration)
sine_pulse = np.sin(2*np.pi*(frequency-qubit_freq_ground)*t_samples)
sideband_pulse = Waveform(np.multiply(np.real(pulse.samples), sine_pulse), name='sideband_pulse')
return sideband_pulse
def get_job_data(job, average):
scale_factor = 1e-14
job_results = job.result(timeout=120) # timeout parameter set to 120 s
result_data = []
for i in range(len(job_results.results)):
if average:
result_data.append(job_results.get_memory(i)[qubit]*scale_factor)
else:
result_data.append(job_results.get_memory(i)[:, qubit]*scale_factor)
return result_data
def rel_maxima(freqs, output_data, height):
peaks, _ = find_peaks(output_data, height)
return freqs[peaks]
def create_cal_circuit_excited(base_pulse, freq):
sched = Schedule()
sched += Play(Gaussian(duration=pulse_duration, sigma=pulse_sigma, amp=pi_amp_ground), drive_chan)
sched += Play(apply_sideband(base_pulse, freq), drive_chan)
measure = inst_sched_map.get('measure', qubits=[qubit])
sched += measure << sched.duration
return sched
dt = backend.configuration().dt
base_pulse = pulse_lib.gaussian(duration=pulse_duration, sigma=pulse_sigma, amp=0.3)
sched_list = []
freq_list = qubit_freq_ground + np.linspace(-400*1e+6, 30*1e+6, 75)
for freq in freq_list:
sched_list.append(create_cal_circuit_excited(base_pulse, freq))
excited_sweep_exp = assemble(sched_list, backend=backend,
meas_level=1, meas_return='avg', shots=1024,
schedule_los=[{drive_chan: qubit_freq_ground}]*75
)
excited_sweep_job = backend.run(excited_sweep_exp)
job_monitor(excited_sweep_job)
excited_sweep_data = get_job_data(excited_sweep_job, average=True)
excited_sweep_freqs = freq_list
plt.scatter(excited_sweep_freqs/1e+9, excited_sweep_data, color='black')
# plt.xlim([min(excited_sweep_freqs/1e+9)+0.01, max(excited_sweep_freqs/1e+9)]) # ignore min point (is off)
# plt.ylim(-21,-20.5)
plt.xlabel("Frequency [GHz]", fontsize=15)
plt.ylabel("Measured Signal [a.u.]", fontsize=15)
plt.title("1->2 Frequency Sweep (first pass)", fontsize=15)
plt.show()
approx_12_freq = rel_maxima(freq_list, np.real(excited_sweep_data), 10)
speak("The test program is done.")
approx_12_freq = rel_maxima(freq_list, np.real(excited_sweep_data), 10)
#### This is to find the refined frequency of the second excited state.
refined_freq_list = approx_12_freq + np.linspace(-20*1e+6, 20*1e+6, 75)
refined_sched_list = []
for freq in refine_freq_list:
sched_list.append(create_cal_circuit_excited(base_pulse, freq))
refined_sweep_exp = assemble(refined_sched_list, backend=backend,
meas_level=1, meas_return='avg', shots=1024,
schedule_los=[{drive_chan: qubit_freq_ground}]*75
)
refined_sweep_job = backend.run(refined_sweep_exp)
refined_sweep_data = get_job_data(refined_sweep_job, average=True)
# do fit in Hz
(refined_sweep_fit_params,
refined_sweep_y_fit) = fit_function(refined_freq_list,
refined_sweep_data,
lambda x, A, q_freq, B, C: (A / np.pi) * (B / ((x - q_freq)**2 + B**2)) + C,
[-12, 4.625*1e+9, 0.05*1e+9, 3*1e+9] # initial parameters for curve_fit
)
plt.scatter(refined_excited_sweep_freqs/1e+9, refined_excited_freq_sweep_data, color='black')
plt.plot(refined_excited_sweep_freqs/1e+9, refined_excited_sweep_y_fit, color='red')
plt.xlim([min(refined_excited_sweep_freqs/1e+9), max(refined_excited_sweep_freqs/1e+9)])
plt.xlabel("Frequency [GHz]", fontsize=15)
plt.ylabel("Measured Signal [a.u.]", fontsize=15)
plt.title("1->2 Frequency Sweep (refined pass)", fontsize=15)
plt.show()
_, qubit_freq_12, _, _ = refined_sweep_fit_params
qubit_freq_excited = qubit_freq_12
|
https://github.com/arian-code/nptel_quantum_assignments
|
arian-code
|
import numpy as np
from qiskit import *
# Create a Quantum Circuit acting on a quantum register of three qubits
qc = QuantumCircuit(1)
qc.x(0)
qc.h(0) #set qubit to superposition
qc.z(0) #add Z gate to rotate out of phase by pi/2
#write the next lines to execute circuit and capture results
qc.draw('mpl')
# Import Aer
from qiskit import Aer
# Run the quantum circuit on a statevector simulator backend
backend = Aer.get_backend('statevector_simulator')
# Create a Quantum Program for execution
job = backend.run(qc)
result = job.result()
outputstate = result.get_statevector(qc, decimals=3)
print(outputstate)
from qiskit.visualization import plot_state_city
plot_state_city(outputstate)
from qiskit.visualization import plot_state_qsphere
%matplotlib inline
plot_state_qsphere(outputstate)
|
https://github.com/Pitt-JonesLab/slam_decomposition
|
Pitt-JonesLab
|
import logging
logger = logging.getLogger()
logger.setLevel(logging.INFO)
import numpy as np
%matplotlib widget
from weylchamber import c1c2c3
from qiskit import QuantumCircuit
from slam.utils.gates.custom_gates import RiSwapGate
from qiskit.quantum_info import Operator
from slam.utils.visualize import coordinate_2dlist_weyl
# class pass_manager_basic(PassManager):
# def __init__(self, gate='iswap'):
# passes = []
# # collect 2Q blocks
# passes.extend([Unroll3qOrMore(), Collect2qBlocks(), ConsolidateBlocks(force_consolidate=True)])
# if gate == 'iswap':
# passes.extend([decomposer(basis_gate=RiSwapGate(1/2))])
# elif gate == 'cx':
# passes.extend([decomposer(basis_gate=CXGate())])
# #combine 1Q gates
# passes.extend([Optimize1qGates()])
# #passes.extend([CountOps(), fooAnalysis()])
# super().__init__(passes)
# #transp1 = transpile(qc, optimization_level=3, basis_gates=['u', 'id', 'cx'])
# pm = pass_manager_basic(gate='iswap')
# qc = QuantumCircuit(2)
# qc.swap(0,1)
# transp1 = pm.run(qc)
# transp1.draw(output='mpl');
from slam.basisv2 import CircuitTemplateV2
basis = CircuitTemplateV2(n_qubits=2, base_gates=[RiSwapGate], edge_params=[[(0, 1)]])
basis.build(3)
basis.spanning_range = range(3, 4)
# bound all Qs to be >0
for el in basis.circuit.parameters:
s_el = str(el)
if "Q" in s_el:
basis.add_bound(s_el, 0.5, 0.5)
from slam.sampler import HaarSample, GateSample
from qiskit.circuit.library import CXGate, CZGate, SwapGate
from slam.utils.gates.custom_gates import CanonicalGate
sampler = GateSample(gate=SwapGate())
# sampler = GateSample(gate = CanonicalGate(np.pi / 4, np.pi / 8, np.pi/8))
# sampler = GateSample(gate = CXGate())
s = [s for s in sampler][0]
from slam.optimizer import TemplateOptimizer
from slam.cost_function import BasicCostInverse, BasicCost, SquareCost
objective1 = SquareCost()
optimizer3 = TemplateOptimizer(
basis=basis,
objective=objective1,
use_callback=False,
override_fail=True,
success_threshold=1e-7,
training_restarts=25,
)
_ret3 = optimizer3.approximate_target_U(s)
basis.build(_ret3.cycles)
circuit = basis.assign_Xk(_ret3.Xk)
transp1 = circuit
circuit.draw()
c1c2c3(Operator(transp1).data)
circuit[:2]
left_qc = QuantumCircuit(2)
for instruction, qargs, cargs in circuit[:8]:
left_qc.append(instruction, qargs, cargs)
# left_qc.draw(output='mpl')
print(c1c2c3(Operator(left_qc).data))
right_qc = QuantumCircuit(2)
for instruction, qargs, cargs in circuit[3:]:
right_qc.append(instruction, qargs, cargs)
# right_qc.draw(output='mpl')
print(c1c2c3(Operator(right_qc).data))
from qiskit.circuit import Parameter
def unbind_parameters(qc):
i = 0
out = qc.copy()
for instr, qargs, cargs in out:
if instr.params and instr.name == "riswap":
# num_params = len(instr.params)
# pvec.resize(len(pvec) + num_params)
instr.params = [Parameter(f"t{i}")]
i += 1
return out
transp1 = unbind_parameters(transp1)
transp1.draw()
from weylchamber import c1c2c3
endpoints = [5, 8, 11]
coordinate_list = []
# 5:1 ratio of 2Q/1Q gate duration, plot 2Q as 25 poitns, 1Q as 5 points
for _ in range(5):
coordinate_list.append((0, 0, 0))
for end in endpoints:
qc = QuantumCircuit(2)
for gate in transp1[0:end]:
qc.append(gate[0], gate[1])
# 2, 5, 8
qc2 = qc.copy()
for i in [2, 5, 8]:
if i < end - 3:
qc2 = qc2.bind_parameters({qc2[i][0].params[0]: 0.5})
# add coordinate during 1Q gate
# eliminating x-axis symmetry
c = list(c1c2c3(Operator(qc3).data))
if c[0] > 0.5:
c[0] = -1 * c[0] + 1
for _ in range(5):
coordinate_list.append(c)
for t in np.linspace(0, 0.5, 25):
qc3 = qc2.bind_parameters({qc2[end - 3][0].params[0]: t})
# eliminating x-axis symmetry
c = list(c1c2c3(Operator(qc3).data))
if c[0] > 0.5:
c[0] = -1 * c[0] + 1
coordinate_list.append(c)
# qc2.draw(output='mpl')
# from slam.utils.visualize import coordinate_2dlist_weyl
coordinate_2dlist_weyl(
coordinate_list, c=np.linspace(0, 1.5 + 0.2 * 4, len(coordinate_list))
);
coordinate_list[-25:]
# coordinate_list = []
# from slam.utils.gates.custom_gates import FSim, BerkeleyGate, CanonicalGate
# r = np.linspace(0,3,250)
# for t in r:
# qc2 = QuantumCircuit(2)
# #add fsim as a function of time
# #qc2.append(FSim(1*np.pi/2, 1*np.pi/6).power(t), [0,1])
# #qc2.append(CanonicalGate(np.pi / 4, np.pi / 8, np.pi/25).power(t), [0,1])
# #eliminating x-axis symmetry
# c = list(c1c2c3(Operator(qc2).data))
# # if c[0] > 0.5:
# # c[0] = -1*c[0] + 1
# coordinate_list.append(c)
# coordinate_2dlist_weyl(coordinate_list, c=r, cmap='viridis')
|
https://github.com/theflyingrahul/qiskitsummerschool2020
|
theflyingrahul
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# (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.
import json
from typing import Any, Callable, Optional, Tuple, Union
from urllib.parse import urljoin
from qiskit import QuantumCircuit, execute
from qiskit.providers import JobStatus
from qiskit.providers.ibmq.job import IBMQJob
from .api import get_server_endpoint, send_request, get_access_token, get_submission_endpoint
from .exercises import get_question_id
from .util import compute_cost, get_provider, get_job, circuit_to_json, get_job_urls, uses_multiqubit_gate
def _circuit_criteria(
circuit: QuantumCircuit,
max_qubits: Optional[int] = None,
min_cost: Optional[int] = None,
check_gates: Optional[bool] = False
) -> Tuple[Optional[int], Optional[int]]:
if max_qubits is not None and circuit.num_qubits > max_qubits:
print(f'Your circuit has {circuit.num_qubits} qubits, which exceeds the maximum allowed.')
print(f'Please reduce the number of qubits in your circuit to below {max_qubits}.')
return None, None
try:
if check_gates and not uses_multiqubit_gate(circuit):
print('Your circuit appears to not use any multi-quibit gates.')
print('Please review your circuit and try again.')
return None, None
cost = compute_cost(circuit)
if min_cost is not None and cost < min_cost:
print(f'Your circuit cost ({cost}) is too low. But if you are convinced that your circuit\n'
'is correct, please let us know in the `#ibm-quantum-challenge-2020` Slack channel.')
return None, None
return circuit.num_qubits, cost
except Exception as err:
print(f'Unable to compute cost: {err}')
return None, None
def _circuit_grading(
circuit: QuantumCircuit,
lab_id: str,
ex_id: str,
is_submit: Optional[bool] = False,
max_qubits: Optional[int] = None,
min_cost: Optional[int] = None,
check_gates: Optional[bool] = False
) -> Tuple[Optional[dict], Optional[str]]:
payload = None
server = None
if not isinstance(circuit, QuantumCircuit):
print(f'Expected a QuantumCircuit, but was given {type(circuit)}')
print(f'Please provide a circuit as your answer.')
return None, None
if not is_submit:
server = get_server_endpoint(lab_id, ex_id)
if not server:
print('Could not find a valid grading server or '
'the grading servers are down right now.')
return None, None
else:
server = None
_, cost = _circuit_criteria(
circuit,
max_qubits=max_qubits,
min_cost=min_cost,
check_gates=check_gates
)
if cost is not None:
payload = {
'answer': circuit_to_json(circuit)
}
if is_submit:
payload['questionNumber'] = get_question_id(lab_id, ex_id)
else:
payload['question_id'] = get_question_id(lab_id, ex_id)
return payload, server
def _job_grading(
job_or_id: Union[IBMQJob, str],
lab_id: str,
ex_id: str,
is_submit: Optional[bool] = False
) -> Tuple[Optional[dict], Optional[str]]:
if not isinstance(job_or_id, IBMQJob) and not isinstance(job_or_id, str):
print(f'Expected an IBMQJob or a job ID, but was given {type(job_or_id)}')
print(f'Please submit a job as your answer.')
return None, None
if not is_submit:
server = get_server_endpoint(lab_id, ex_id)
if not server:
print('Could not find a valid grading server or the grading '
'servers are down right now.')
return None, None
else:
server = None
job = get_job(job_or_id) if isinstance(job_or_id, str) else job_or_id
if not job:
print('An invalid or non-existent job was specified.')
return None, None
job_status = job.status()
if job_status in [JobStatus.CANCELLED, JobStatus.ERROR]:
print(f'Job did not successfully complete: {job_status.value}.')
return None, None
elif job_status is not JobStatus.DONE:
print(f'Job has not yet completed: {job_status.value}.')
print(f'Please wait for the job (id: {job.job_id()}) to complete then try again.')
return None, None
header = job.result().header.to_dict()
if 'qc_cost' not in header:
if is_submit:
print('An unprepared answer was specified. '
'Please prepare() and grade() answer before submitting.')
else:
print('An unprepared answer was specified. Please prepare() answer before grading.')
return None, None
download_url, result_url = get_job_urls(job)
if not download_url or not result_url:
print('Unable to obtain job URLs')
return None, None
payload = {
'answer': json.dumps({
'download_url': download_url,
'result_url': result_url
})
}
if is_submit:
payload['questionNumber'] = get_question_id(lab_id, ex_id)
else:
payload['question_id'] = get_question_id(lab_id, ex_id)
return payload, server
def _number_grading(
answer: int,
lab_id: str,
ex_id: str,
is_submit: Optional[bool] = False
) -> Tuple[Optional[dict], Optional[str]]:
if not isinstance(answer, int):
print(f'Expected a integer, but was given {type(answer)}')
print(f'Please provide a number as your answer.')
return None, None
if not is_submit:
server = get_server_endpoint(lab_id, ex_id)
if not server:
print('Could not find a valid grading server '
'or the grading servers are down right now.')
return None, None
else:
server = None
payload = {
'answer': str(answer)
}
if is_submit:
payload['questionNumber'] = get_question_id(lab_id, ex_id)
else:
payload['question_id'] = get_question_id(lab_id, ex_id)
return payload, server
def prepare_circuit(
circuit: QuantumCircuit,
max_qubits: Optional[int] = 28,
min_cost: Optional[int] = None,
check_gates: Optional[bool] = False,
**kwargs
) -> Optional[IBMQJob]:
job = None
if not isinstance(circuit, QuantumCircuit):
print(f'Expected a QuantumCircuit, but was given {type(circuit)}')
print(f'Please provide a circuit.')
return None
_, cost = _circuit_criteria(
circuit,
max_qubits=max_qubits,
min_cost=min_cost,
check_gates=check_gates
)
if cost is not None:
if 'backend' not in kwargs:
kwargs['backend'] = get_provider().get_backend('ibmq_qasm_simulator')
# execute experiments
print('Starting experiment. Please wait...')
job = execute(
circuit,
qobj_header={
'qc_cost': cost
},
**kwargs
)
print(f'You may monitor the job (id: {job.job_id()}) status '
'and proceed to grading when it successfully completes.')
return job
def prepare_solver(
solver_func: Callable,
lab_id: str,
ex_id: str,
problem_set: Optional[Any] = None,
max_qubits: Optional[int] = 28,
min_cost: Optional[int] = None,
check_gates: Optional[bool] = False,
**kwargs
) -> Optional[IBMQJob]:
job = None
if not callable(solver_func):
print(f'Expected a function, but was given {type(solver_func)}')
print(f'Please provide a function that returns a QuantumCircuit.')
return None
server = get_server_endpoint(lab_id, ex_id)
if not server:
print('Could not find a valid grading server or the grading servers are down right now.')
return
endpoint = server + 'problem-set'
index, value = get_problem_set(lab_id, ex_id, endpoint)
print(f'Running {solver_func.__name__}...')
qc_1 = solver_func(problem_set)
_, cost = _circuit_criteria(
qc_1,
max_qubits=max_qubits,
min_cost=min_cost,
check_gates=check_gates
)
if value and index is not None and index >= 0 and cost is not None:
qc_2 = solver_func(value)
if 'backend' not in kwargs:
kwargs['backend'] = get_provider().get_backend('ibmq_qasm_simulator')
# execute experiments
print('Starting experiments. Please wait...')
job = execute(
[qc_1, qc_2],
qobj_header={
'qc_index': [None, index],
'qc_cost': cost
},
**kwargs
)
print(f'You may monitor the job (id: {job.job_id()}) status '
'and proceed to grading when it successfully completes.')
return job
def grade_circuit(
circuit: QuantumCircuit,
lab_id: str,
ex_id: str,
max_qubits: Optional[int] = 28,
min_cost: Optional[int] = None
) -> bool:
payload, server = _circuit_grading(
circuit,
lab_id,
ex_id,
is_submit=False,
max_qubits=max_qubits,
min_cost=min_cost
)
if payload:
print('Grading your answer. Please wait...')
return grade_answer(
payload,
server + 'validate-answer'
)
return False
def grade_job(
job_or_id: Union[IBMQJob, str],
lab_id: str,
ex_id: str
) -> bool:
payload, server = _job_grading(job_or_id, lab_id, ex_id, is_submit=False)
if payload:
print('Grading your answer. Please wait...')
return grade_answer(
payload,
server + 'validate-answer'
)
return False
def grade_number(
answer: int,
lab_id: str,
ex_id: str
) -> bool:
payload, server = _number_grading(answer, lab_id, ex_id, is_submit=False)
if payload:
print('Grading your answer. Please wait...')
return grade_answer(
payload,
server + 'validate-answer'
)
return False
def submit_circuit(
circuit: QuantumCircuit,
lab_id: str,
ex_id: str,
max_qubits: Optional[int] = 28,
min_cost: Optional[int] = None
) -> bool:
payload, _ = _circuit_grading(
circuit,
lab_id,
ex_id,
is_submit=True,
max_qubits=max_qubits,
min_cost=min_cost
)
if payload:
print('Submitting your answer. Please wait...')
return submit_answer(payload)
return False
def submit_job(
job_or_id: IBMQJob,
lab_id: str,
ex_id: str,
) -> bool:
payload, _ = _job_grading(job_or_id, lab_id, ex_id, is_submit=True)
if payload:
print('Submitting your answer. Please wait...')
return submit_answer(payload)
return False
def submit_number(
answer: int,
lab_id: str,
ex_id: str
) -> bool:
payload, _ = _number_grading(answer, lab_id, ex_id, is_submit=True)
if payload:
print('Submitting your answer. Please wait...')
return submit_answer(payload)
return False
def get_problem_set(
lab_id: str, ex_id: str, endpoint: str
) -> Tuple[Optional[int], Optional[Any]]:
problem_set_response = None
try:
payload = {'question_id': get_question_id(lab_id, ex_id)}
problem_set_response = send_request(endpoint, query=payload, method='GET')
except Exception as err:
print('Unable to obtain the problem set')
if problem_set_response:
status = problem_set_response.get('status')
if status == 'valid':
try:
index = problem_set_response.get('index')
value = json.loads(problem_set_response.get('value'))
return index, value
except Exception as err:
print(f'Problem set could not be processed: {err}')
else:
cause = problem_set_response.get('cause')
print(f'Problem set failed: {cause}')
return None, None
def grade_answer(payload: dict, endpoint: str, cost: Optional[int] = None) -> bool:
try:
answer_response = send_request(endpoint, body=payload)
status = answer_response.get('status', None)
cause = answer_response.get('cause', None)
score = cost if cost else answer_response.get('score', None)
handle_grade_response(status, score=score, cause=cause)
return status == 'valid' or status is True
except Exception as err:
print(f'Failed: {err}')
return False
def submit_answer(payload: dict) -> bool:
try:
access_token = get_access_token()
baseurl = get_submission_endpoint()
endpoint = urljoin(baseurl, './challenges/answers')
submit_response = send_request(
endpoint,
body=payload,
query={'access_token': access_token}
)
status = submit_response.get('status', None)
if status is None:
status = submit_response.get('valid', None)
cause = submit_response.get('cause', None)
handle_submit_response(status, cause=cause)
return status == 'valid' or status is True
except Exception as err:
print(f'Failed: {err}')
return False
def handle_grade_response(
status: Optional[str], score: Optional[int] = None, cause: Optional[str] = None
) -> None:
if status == 'valid':
print('\nCongratulations 🎉! Your answer is correct.')
if score is not None:
print(f'Your score is {score}.')
elif status == 'invalid':
print(f'\nOops 😕! {cause}')
print('Please review your answer and try again.')
elif status == 'notFinished':
print(f'Job has not finished: {cause}')
print(f'Please wait for the job to complete then try again.')
else:
print(f'Failed: {cause}')
print('Unable to grade your answer.')
def handle_submit_response(
status: Union[str, bool], cause: Optional[str] = None
) -> None:
if status == 'valid' or status is True:
print('\nSuccess 🎉! Your answer has been submitted.')
elif status == 'invalid' or status is False:
print(f'\nOops 😕! {"Your answer is incorrect" if cause is None else cause}')
print('Make sure your answer is correct and successfully graded before submitting.')
elif status == 'notFinished':
print(f'Job has not finished: {cause}')
print(f'Please wait for the job to complete, grade it, and then try to submit again.')
else:
print(f'Failed: {cause}')
print('Unable to submit your answer at this time.')
|
https://github.com/Qiskit-Partners/partners
|
Qiskit-Partners
|
import qiskit_qasm2
project = 'Qiskit OpenQASM 2 Tools'
copyright = '2022, Jake Lishman'
author = 'Jake Lishman'
version = qiskit_qasm2.__version__
extensions = [
"sphinx.ext.autodoc",
"sphinx.ext.intersphinx",
]
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']
# Document the docstring for the class and the __init__ method together.
autoclass_content = "both"
html_theme = 'alabaster'
intersphinx_mapping = {
"qiskit-terra": ("https://qiskit.org/documentation", None),
}
|
https://github.com/Qiskit/feedback
|
Qiskit
|
from qiskit import transpile
from qiskit.circuit import QuantumRegister, QuantumCircuit, Parameter
from qiskit.quantum_info.synthesis.xx_decompose import XXDecomposer
from qiskit.quantum_info import random_unitary
import numpy as np
u = random_unitary(4)
decomposer = XXDecomposer(euler_basis='U')
output_circuit = decomposer(u, basis_fidelity=0.99, approximate=True)
output_circuit.draw('mpl', style='bw')
# emit XX everywhere
xx_circuit = QuantumCircuit(2)
theta = Parameter('theta')
xx_circuit.rxx(theta, 0, 1)
# except at theta=pi/2, emit CX
cx_circuit = QuantumCircuit(2)
cx_circuit.h(0)
cx_circuit.cx(0, 1)
cx_circuit.h(1)
cx_circuit.s(0)
cx_circuit.s(1)
cx_circuit.h(0)
cx_circuit.h(1)
cx_circuit.global_phase += np.pi / 4
embodiments = {t: xx_circuit.bind_parameters({theta: t}) for t in [np.pi/4, np.pi/6]}
embodiments.update({np.pi/2: cx_circuit})
decomposer = XXDecomposer(euler_basis='U3', embodiments=embodiments)
output_circuit = decomposer(u, basis_fidelity=.99)
output_circuit.draw('mpl')
from qiskit import transpile, QuantumRegister, QuantumCircuit
from qiskit.quantum_info import random_unitary
import numpy as np
# generate a random unitary
u = random_unitary(4)
q = QuantumRegister(2)
circuit = QuantumCircuit(q)
circuit.append(u, q)
output_circuit, = transpile([circuit], basis_gates=['rzx', 'rz', 'sx'], approximation_degree=0.99)
display(circuit.draw('mpl'))
display(output_circuit.draw('mpl'))
|
https://github.com/apcarrik/qiskit-dev
|
apcarrik
|
import numpy as np
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit import execute, BasicAer
from qiskit.compiler import transpile
from qiskit.quantum_info.operators import Operator, Pauli
from qiskit.quantum_info import process_fidelity
from qiskit.extensions import RXGate, XGate, CXGate
### Operator Class
# Create two-qubit Pauli-XX operator
XX = Operator([[0,0,0,1], [0,0,1,0], [0,1,0,0], [1,0,0,0]])
# Show operator properties
print(XX)
print(XX.data)
input_dim, output_dim = XX.dim
print(input_dim, output_dim)
# See input and output dimensions
op = Operator(np.random.rand(2**1, 2**2))
print('Input dimensions: ', op.input_dims())
print('Output dimensions: ', op.output_dims())
# If input matrix is not divisible into qubit systems,
# it will be stored as single-qubit operator
op = Operator(np.random.rand(6, 6))
print('Input dimensions: ', op.input_dims())
print('Output dimensions: ', op.output_dims())
# The input and output can also be manually specified when initializing new operator
op = Operator(np.random.rand(2**1, 2**2), input_dims=[4])
print('Input dimensions: ', op.input_dims())
print('Output dimensions: ', op.output_dims())
op = Operator(np.random.rand(6, 6), # system is qubit and qutrit
input_dims=[2,3], output_dims=[2,3])
print('Input dimensions: ', op.input_dims())
print('Output dimensions: ', op.output_dims())
# extract input/output dimensions of subset of subsystem
print('Dimension of input system 0:', op.input_dims([0]))
print('Dimension of input system 1:', op.input_dims([1]))
### Converting Classes to Operators
# Create operator from a Pauli object
pauliXX = Pauli('XX')
op = Operator(pauliXX)
print(op)
# Create operator from a Gate object
op = Operator(CXGate())
print(op)
# Create operator from a parameterized Gate object
op = Operator(RXGate(np.pi/2))
print(op)
# Create operator from a QuantumCircuit object
circ = QuantumCircuit(10)
circ.h(0)
for j in range(1,10):
circ.cx(j-1, j)
op = Operator(circ) #converts circuit into operator by implicit unitary simulation
print(op)
### Using Operators in circuits
from matplotlib import pyplot
# Create new operator
XX = Operator(Pauli('XX'))
circ = QuantumCircuit(2,2)
circ.append(XX, [0,1])
circ.measure([0,1],[0,1])
circ.draw('mpl')
pyplot.show()
# Can also directly insert Pauli object into circuit, to convert into sequence of
# single-qubit Pauli gates
backend = BasicAer.get_backend('qasm_simulator')
job = execute(circ, backend, basis_gates=['u1','u2','u3','cx'])
job.result().get_counts(0)
circ2 = QuantumCircuit(2,2)
circ2.append(Pauli('XX'), [0,1])
circ2.measure([0,1],[0,1])
circ2.draw('mpl')
pyplot.show()
### Combining Operators
# Tensor Product
A = Operator(Pauli('X'))
B = Operator(Pauli('Z'))
tens = A.tensor(B)
print(tens)
# Tensor Expansion
A = Operator(Pauli('X'))
B = Operator(Pauli('Z'))
tens = A.expand(B)
print(tens)
# Composition (matrix multiplication B.A)
A = Operator(Pauli('X'))
B = Operator(Pauli('Z'))
comp = A.compose(B)
print(comp)
# Reverse order composition (matrix multiplication A.B)
A = Operator(Pauli('X'))
B = Operator(Pauli('Z'))
comp = A.compose(B, front=True)
print(comp)
# Subsystem Composition
# compose XZ with a 3-qubit identity operator
op = Operator(np.eye(2**3))
XZ = Operator(Pauli('XZ'))
combop = op.compose(XZ, qargs=[0,2])
print(combop)
# compose YX in front of the previous operator
op = Operator(np.eye(2**3))
YX = Operator(Pauli('YX'))
combop = op.compose(XZ, qargs=[0,2], front=True)
print(combop)
# Linear Combinations
XX = Operator(Pauli('XX'))
YY = Operator(Pauli('YY'))
ZZ = Operator(Pauli('ZZ'))
op = 0.5 * (XX + YY - 3* ZZ)
print(op)
print("Operator is unitary?: ", op.is_unitary())
# Implicit conversion to Operators
op = Operator(np.eye(2)).compose([[0,1], [1,0]])
print(op)
### Comparison of Operators
print(
Operator(Pauli('X')) == Operator(XGate())
)
# Unitaries that differ by a global phase are not considered equal
print(
Operator(XGate()) == np.exp(1j * 0.5) * Operator(XGate())
)
# Process Fidelity - information theoretic quantification of how close two quantum
# channels are to each other, does not depend on global phase (must both be unitary)
op_a = Operator(XGate())
op_b = np.exp(1j * 0.5) * Operator(XGate())
F = process_fidelity(op_a, op_b)
print('Process fidelity = ', F)
|
https://github.com/pedroripper/qiskit_tutoriais
|
pedroripper
|
from qiskit import *
%matplotlib inline
qc1 = QuantumCircuit(1)
qc1.h(0)
qc1.draw(output = 'mpl')
qc2 = QuantumCircuit(1)
qc2.x(0)
qc2.draw(output = 'mpl')
print(qc1)
print(qc2)
qc3 = qc1 + qc2
qc3.draw(output = 'mpl')
qc1[0]
qc3.z(0)
qc3.draw(output = 'mpl')
|
https://github.com/0tt3r/QuaC-qiskit
|
0tt3r
|
# -*- coding: utf-8 -*-
"""This module contains functions for generating QASM with QuaC
"""
import re
from qiskit import QuantumCircuit, assemble, transpile
from qiskit.providers import BaseBackend
from quac_qiskit.simulators import list_schedule_experiment
def quac_time_qasm_transpiler(circuit: QuantumCircuit, backend: BaseBackend) -> str:
"""Converts a circuit of type QuantumCircuit to a string of TIMEQASM specification
:param circuit: a QuantumCircuit (need not be transpiled)
:param backend: a specific backend to generate the QASM for (for tranpsilation)
:return: a string containing necessary QASM with times for each gate
"""
# Get original QASM
transpiled_circuit = transpile(circuit, backend)
original_qasm = transpiled_circuit.qasm()
# Get body of original QASM
start = 2 + len(circuit.qregs) + len(circuit.cregs)
original_qasm_body = original_qasm.splitlines()[start:]
# Formulate header
qasm_modified = "TIMEQASM 1.0;\n"
qasm_modified += "\n".join(original_qasm.splitlines()[1:start])
qasm_modified += "\n"
# Schedule circuit
qobj = assemble(transpiled_circuit, backend)
qexp = qobj.experiments[0]
qschedule = list_schedule_experiment(qexp, backend.properties())
# Formulate body
for instruction, time in qschedule:
# Note: ID was custom injected by the scheduler in this plugin
qasm_modified += f"{original_qasm_body[instruction.id][:-1]} @{time};\n"
return qasm_modified
def quac_qasm_transpiler(qiskit_qasm: str) -> str:
"""Converts Qiskit-generated QASM instructions into QuaC-supported instructions
:param qiskit_qasm: a string with a QASM program
:return: a string with a modified QuaC-supported QASM program
"""
quac_qasm = ""
for line in qiskit_qasm.splitlines():
# Remove certain types of unsupported operations
if any(instruction in line for instruction in ["measure", "creg", "barrier", "id"]):
continue
# Reformat implicit multiplication by pi
for pi_mult in re.findall("[0-9]pi", line):
line = line.replace(pi_mult, pi_mult[0] + '*pi')
# Evaluate and inject new parameters
instruction_params = re.findall("\(.+\)", line) # only one parameter set per line
if len(instruction_params) == 1:
instruction_params = instruction_params[0]
else:
quac_qasm += line + "\n"
continue
# Evaluate pi-based parameter expressions
evaluated_instruction_params = "("
for parameter in instruction_params[1:-1].split(","):
parameter = parameter.replace("pi", "np.pi")
evaluated_instruction_params += str(eval(parameter)) + ","
evaluated_instruction_params = evaluated_instruction_params[:-1] + ")"
line = line.replace(instruction_params, evaluated_instruction_params)
# Add formatted QASM line to final result
quac_qasm += line + "\n"
return quac_qasm
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit.circuit.random import random_circuit
circuit = random_circuit(2, 2, seed=0, measure=True).decompose(reps=1)
display(circuit.draw("mpl"))
from qiskit.primitives import Sampler
sampler = Sampler()
job = sampler.run(circuit)
print(f">>> Job ID: {job.job_id()}")
print(f">>> Job Status: {job.status()}")
result = job.result()
print(f">>> {result}")
print(f" > Quasi-distribution: {result.quasi_dists[0]}")
circuit = random_circuit(2, 2, seed=1, measure=True).decompose(reps=1)
job = sampler.run(circuit)
result = job.result()
display(circuit.draw("mpl"))
print(f">>> Quasi-distribution: {result.quasi_dists[0]}")
circuits = (
random_circuit(2, 2, seed=0, measure=True).decompose(reps=1),
random_circuit(2, 2, seed=1, measure=True).decompose(reps=1),
)
job = sampler.run(circuits)
result = job.result()
[display(cir.draw("mpl")) for cir in circuits]
print(f">>> Quasi-distribution: {result.quasi_dists}")
from qiskit.circuit.library import RealAmplitudes
circuit = RealAmplitudes(num_qubits=2, reps=2).decompose(reps=1)
circuit.measure_all()
parameter_values = [0, 1, 2, 3, 4, 5]
job = sampler.run(circuit, parameter_values)
result = job.result()
display(circuit.draw("mpl"))
print(f">>> Parameter values: {parameter_values}")
print(f">>> Quasi-distribution: {result.quasi_dists[0]}")
from qiskit_ibm_runtime import QiskitRuntimeService
service = QiskitRuntimeService(channel="ibm_quantum")
backend = service.backend("ibmq_qasm_simulator")
from qiskit.circuit.random import random_circuit
circuit = random_circuit(2, 2, seed=0, measure=True).decompose(reps=1)
display(circuit.draw("mpl"))
from qiskit_ibm_runtime import Sampler
sampler = Sampler(session=backend)
job = sampler.run(circuit)
print(f">>> Job ID: {job.job_id()}")
print(f">>> Job Status: {job.status()}")
result = job.result()
print(f">>> {result}")
print(f" > Quasi-distribution: {result.quasi_dists[0]}")
print(f" > Metadata: {result.metadata[0]}")
from qiskit_ibm_runtime import Options
options = Options(optimization_level=3, environment={"log_level": "INFO"})
from qiskit_ibm_runtime import Options
options = Options()
options.resilience_level = 1
options.execution.shots = 2048
sampler = Sampler(session=backend, options=options)
result = sampler.run(circuit).result()
print(f">>> Metadata: {result.metadata[0]}")
sampler = Sampler(session=backend, options=options)
result = sampler.run(circuit, shots=1024).result()
print(f">>> Metadata: {result.metadata[0]}")
from qiskit_ibm_runtime import Options
# optimization_level=3 adds dynamical decoupling
# resilience_level=1 adds readout error mitigation
options = Options(optimization_level=3, resilience_level=1)
sampler = Sampler(session=backend, options=options)
result = sampler.run(circuit).result()
print(f">>> Quasi-distribution: {result.quasi_dists[0]}")
print(f">>> Metadata: {result.metadata[0]}")
from qiskit_ibm_runtime import Session, Estimator
with Session(backend=backend, max_time="1h"):
sampler = Sampler()
result = sampler.run(circuit).result()
print(f">>> Quasi-distribution from the first run: {result.quasi_dists[0]}")
result = sampler.run(circuit).result()
print(f">>> Quasi-distribution from the second run: {result.quasi_dists[0]}")
from qiskit.circuit.random import random_circuit
from qiskit.quantum_info import SparsePauliOp
estimator_circuit = random_circuit(2, 2, seed=0).decompose(reps=1)
display(estimator_circuit.draw("mpl"))
observable = SparsePauliOp("XZ")
print(f">>> Observable: {observable.paulis}")
from qiskit_ibm_runtime import Session, Sampler, Estimator
with Session(backend=backend):
sampler = Sampler()
estimator = Estimator()
result = sampler.run(circuit).result()
print(f">>> Quasi Distribution from the sampler job: {result.quasi_dists[0]}")
result = estimator.run(estimator_circuit, observable).result()
print(f">>> Expectation value from the estimator job: {result.values[0]}")
from qiskit_ibm_runtime import Session, Sampler, Estimator
with Session(backend=backend):
sampler = Sampler()
estimator = Estimator()
sampler_job = sampler.run(circuit)
estimator_job = estimator.run(estimator_circuit, observable)
print(f">>> Quasi Distribution from the sampler job: {sampler_job.result().quasi_dists[0]}")
print(f">>> Expectation value from the estimator job: {estimator_job.result().values[0]}")
from qiskit_ibm_runtime import QiskitRuntimeService, Session, Sampler, Estimator, Options
# 1. Initialize account
service = QiskitRuntimeService(channel="ibm_quantum")
# 2. Specify options, such as enabling error mitigation
options = Options(resilience_level=1)
# 3. Select a backend.
backend = service.backend("ibmq_qasm_simulator")
# 4. Create a session
with Session(backend=backend):
# 5. Create primitive instances
sampler = Sampler(options=options)
estimator = Estimator(options=options)
# 6. Submit jobs
sampler_job = sampler.run(circuit)
estimator_job = estimator.run(estimator_circuit, observable)
# 7. Get results
print(f">>> Quasi Distribution from the sampler job: {sampler_job.result().quasi_dists[0]}")
print(f">>> Expectation value from the estimator job: {estimator_job.result().values[0]}")
import qiskit_ibm_runtime
qiskit_ibm_runtime.version.get_version_info()
from qiskit.tools.jupyter import *
%qiskit_version_table
%qiskit_copyright
|
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
|
aryashah2k
|
import matplotlib.pyplot as plt
import numpy as np
from qiskit import Aer
from qiskit.ml.datasets import breast_cancer
from qiskit.circuit.library import ZZFeatureMap
from qiskit.aqua import QuantumInstance
from qiskit.aqua.algorithms import QSVM
np.random.seed(2020)
n = 30
# Training examples for class 0
mean = [0, 1]
cov = [[0.1, 0], [0, 0.1]]
A = (np.random.multivariate_normal(mean, cov, n))
x_A, y_A = A.T
plt.plot(x_A, y_A, 'ro');
# Training examples for class 1
mean = [1, 0]
cov = [[0.1, 0], [0, 0.1]]
B = (np.random.multivariate_normal(mean, cov, n))
x_B, y_B = B.T
plt.plot(x_B, y_B, 'bo');
feature_map = ZZFeatureMap(feature_dimension=2, reps=2, entanglement='linear')
feature_map.draw()
training_input = np.append(A,B,axis =0)
training_labels = np.array([0]*n+[1]*n) # Training labels are 0 and 1
backend = Aer.get_backend('statevector_simulator')
quantum_instance = QuantumInstance(backend)
qsvm = QSVM(feature_map, quantum_instance = quantum_instance)
qsvm.train(training_input,training_labels)
n = 10
# Test examples for class 0
mean = [0, 1]
cov = [[0.1, 0], [0, 0.1]]
C = (np.random.multivariate_normal(mean, cov, n))
x_C, y_C = C.T
plt.plot(x_C, y_C, 'ro');
# Test examples for class 1
mean = [1, 0]
cov = [[0.05, 0], [0, 0.05]]
D = (np.random.multivariate_normal(mean, cov, n))
x_D, y_D = D.T
plt.plot(x_D, y_D, 'bo');
print("Prediction for examples in test class 0",qsvm.predict(C))
print("Prediction for examples in test class 1",qsvm.predict(D))
test_input = np.append(C,D,axis =0)
test_labels = np.array([0]*n+[1]*n)
print("Accuracy",qsvm.test(test_input,test_labels))
sample_Total, training_input, test_input, class_labels = breast_cancer(
training_size=100,
test_size=10,
n=2,
plot_data=True
)
feature_map = ZZFeatureMap(feature_dimension=2, reps=1, entanglement='linear')
feature_map.draw()
qsvm = QSVM(feature_map, training_input, test_input)
result = qsvm.run(quantum_instance)
print("Accuracy: ", result['testing_accuracy'])
feature_map = ZZFeatureMap(feature_dimension=2, reps=2, entanglement='linear')
feature_map.draw()
qsvm = QSVM(feature_map, training_input, test_input)
result = qsvm.run(quantum_instance)
print("Accuracy: ", result['testing_accuracy'])
|
https://github.com/Qcatty/Sample-exam-Solution-IBM-Certified-Associate-Developer--Qiskit-v0.2X
|
Qcatty
|
# General tools
import numpy as np
import matplotlib.pyplot as plt
import math
# Importing standard Qiskit libraries
from qiskit import execute,QuantumCircuit, QuantumRegister, ClassicalRegister, Aer, transpile, IBMQ
from qiskit.tools.jupyter import *
from qiskit.visualization import *
from ibm_quantum_widgets import *
# Loading your IBM Quantum account(s)
provider = IBMQ.load_account()
QuantumCircuit(4, 4)
qc = QuantumCircuit(1)
qc.ry(3 * math.pi/4, 0)
# draw the circuit
qc.draw()
# et's plot the histogram and see the probability :)
qc.measure_all()
qasm_sim = Aer.get_backend('qasm_simulator') #this time we call the qasm simulator
result = execute(qc, qasm_sim).result() # NOTICE: we can skip some steps by doing .result() directly, we could go further!
counts = result.get_counts() #this time, we are not getting the state, but the counts!
plot_histogram(counts) #a new plotting method! this works for counts obviously!
inp_reg = QuantumRegister(2, name='inp')
ancilla = QuantumRegister(1, name='anc')
qc = QuantumCircuit(inp_reg, ancilla)
# Insert code here
qc.h(inp_reg[0:2])
qc.x(ancilla[0])
qc.draw()
bell = QuantumCircuit(2)
bell.h(0)
bell.x(1)
bell.cx(0, 1)
bell.draw()
qc = QuantumCircuit(1,1)
# Insert code fragment here
qc.ry(math.pi / 2,0)
simulator = Aer.get_backend('statevector_simulator')
job = execute(qc, simulator)
result = job.result()
outputstate = result.get_statevector(qc)
plot_bloch_multivector(outputstate)
from qiskit import QuantumCircuit, Aer, execute
from math import sqrt
qc = QuantumCircuit(2)
# Insert fragment here
v = [1/sqrt(2), 0, 0, 1/sqrt(2)]
qc.initialize(v,[0,1])
simulator = Aer.get_backend('statevector_simulator')
result = execute(qc, simulator).result()
statevector = result.get_statevector()
print(statevector)
qc = QuantumCircuit(3,3)
qc.barrier() # B. qc.barrier([0,1,2])
qc.draw()
qc = QuantumCircuit(1,1)
qc.h(0)
qc.s(0)
qc.h(0)
qc.measure(0,0)
qc.draw()
qc = QuantumCircuit(2, 2)
qc.h(0)
qc.barrier(0)
qc.cx(0,1)
qc.barrier([0,1])
qc.draw()
qc.depth()
# Use Aer's qasm_simulator
qasm_sim = Aer.get_backend('qasm_simulator')
#use a coupling map that connects three qubits linearly
couple_map = [[0, 1], [1, 2]]
# Execute the circuit on the qasm simulator.
# We've set the number of repeats of the circuit
# to be 1024, which is the default.
job = execute(qc, backend=qasm_sim, shots=1024, coupling_map=couple_map)
from qiskit import QuantumCircuit, execute, BasicAer
backend = BasicAer.get_backend('qasm_simulator')
qc = QuantumCircuit(3)
# insert code here
execute(qc, backend, shots=1024, coupling_map=[[0,1], [1,2]])
qc = QuantumCircuit(2, 2)
qc.x(0)
qc.measure([0,1], [0,1])
simulator = Aer.get_backend('qasm_simulator')
result = execute(qc, simulator, shots=1000).result()
counts = result.get_counts(qc)
print(counts)
|
https://github.com/swe-train/qiskit__qiskit
|
swe-train
|
# -*- 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 import QuantumRegister, ClassicalRegister, QuantumCircuit
q = QuantumRegister(1)
c = ClassicalRegister(1)
qc = QuantumCircuit(q, c)
qc.h(q)
qc.measure(q, c)
qc.draw(output='mpl', style={'backgroundcolor': '#EEEEEE'})
|
https://github.com/anpaschool/quantum-computing
|
anpaschool
|
from qiskit import *
from math import pi
import numpy as np
from qiskit.visualization import *
import matplotlib.pyplot as plt
from qutip import *
q = QuantumRegister(2)
qc = QuantumCircuit(q)
qc.cu1(pi/2,q[0], q[1])
qc.draw(output='mpl')
backend = Aer.get_backend('unitary_simulator')
job = execute(qc, backend)
result = job.result()
print(result.get_unitary(qc, decimals=3))
q = QuantumRegister(3)
qc = QuantumCircuit(q)
qc.u3(pi/2,pi/2,pi/2,q[0])
qc.cu1(pi/2,q[0], q[1])
qc.u3(pi/2,pi/2,pi/2,q[1])
qc.cu1(pi/2,q[1], q[2])
qc.u3(pi/2,pi/2,pi/2,q[2])
qc.draw(output='mpl')
backend = Aer.get_backend('unitary_simulator')
job = execute(qc, backend)
result = job.result()
print(result.get_unitary(qc, decimals=3))
q = QuantumRegister(4)
qc = QuantumCircuit(q)
qc.u3(pi/2,pi/2,pi/2,q[0])
qc.cu1(pi/2,q[0], q[1])
qc.u2(pi/2,pi/2,q[1])
qc.u1(pi/2,q[2])
qc.x(q[0])
qc.ccx(q[1],q[2],q[3])
qc.y(q[1])
qc.z(q[2])
qc.cx(q[2],q[3])
qc.z(q[3])
qc.h(q[3])
qc.s(q[0])
qc.cu1(pi/2,q[1], q[2])
qc.swap(q[0],q[2])
qc.cswap(q[0],q[1],q[3])
qc.draw(output='mpl')
backend = Aer.get_backend('unitary_simulator')
job = execute(qc, backend)
result = job.result()
print(result.get_unitary(qc, decimals=3))
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import numpy as np
from qiskit_nature.second_q.hamiltonians import QuadraticHamiltonian
# create Hamiltonian
hermitian_part = np.array(
[
[1.0, 2.0, 0.0, 0.0],
[2.0, 1.0, 2.0, 0.0],
[0.0, 2.0, 1.0, 2.0],
[0.0, 0.0, 2.0, 1.0],
]
)
antisymmetric_part = np.array(
[
[0.0, 3.0, 0.0, 0.0],
[-3.0, 0.0, 3.0, 0.0],
[0.0, -3.0, 0.0, 3.0],
[0.0, 0.0, -3.0, 0.0],
]
)
constant = 4.0
hamiltonian = QuadraticHamiltonian(
hermitian_part=hermitian_part,
antisymmetric_part=antisymmetric_part,
constant=constant,
)
# convert it to a FermionicOp and print it
hamiltonian_ferm = hamiltonian.second_q_op()
print(hamiltonian_ferm)
# get the transformation matrix W and orbital energies {epsilon_j}
(
transformation_matrix,
orbital_energies,
transformed_constant,
) = hamiltonian.diagonalizing_bogoliubov_transform()
print(f"Shape of matrix W: {transformation_matrix.shape}")
print(f"Orbital energies: {orbital_energies}")
print(f"Transformed constant: {transformed_constant}")
from qiskit_nature.second_q.circuit.library import FermionicGaussianState
occupied_orbitals = (0, 2)
eig = np.sum(orbital_energies[list(occupied_orbitals)]) + transformed_constant
print(f"Eigenvalue: {eig}")
circuit = FermionicGaussianState(transformation_matrix, occupied_orbitals=occupied_orbitals)
circuit.draw("mpl")
from qiskit.quantum_info import Statevector
from qiskit_nature.second_q.mappers import JordanWignerMapper
# simulate the circuit to get the final state
state = np.array(Statevector(circuit))
# convert the Hamiltonian to a matrix
hamiltonian_jw = JordanWignerMapper().map(hamiltonian_ferm).to_matrix()
# check that the state is an eigenvector with the expected eigenvalue
np.testing.assert_allclose(hamiltonian_jw @ state, eig * state, atol=1e-8)
# create Hamiltonian
hermitian_part = np.array(
[
[1.0, 2.0, 0.0, 0.0],
[2.0, 1.0, 2.0, 0.0],
[0.0, 2.0, 1.0, 2.0],
[0.0, 0.0, 2.0, 1.0],
]
)
constant = 4.0
hamiltonian = QuadraticHamiltonian(
hermitian_part=hermitian_part,
constant=constant,
)
print(f"Hamiltonian conserves particle number: {hamiltonian.conserves_particle_number()}")
# get the transformation matrix W and orbital energies {epsilon_j}
(
transformation_matrix,
orbital_energies,
transformed_constant,
) = hamiltonian.diagonalizing_bogoliubov_transform()
print(f"Shape of matrix W: {transformation_matrix.shape}")
print(f"Orbital energies: {orbital_energies}")
print(f"Transformed constant: {transformed_constant}")
from qiskit_nature.second_q.circuit.library import SlaterDeterminant
occupied_orbitals = (0, 2)
eig = np.sum(orbital_energies[list(occupied_orbitals)]) + transformed_constant
print(f"Eigenvalue: {eig}")
circuit = SlaterDeterminant(transformation_matrix[list(occupied_orbitals)])
circuit.draw("mpl")
from qiskit_nature.second_q.circuit.library import BogoliubovTransform
from qiskit import QuantumCircuit, QuantumRegister
from qiskit.quantum_info import random_hermitian, random_statevector, state_fidelity
from scipy.linalg import expm
# create Hamiltonian
n_modes = 5
hermitian_part = np.array(random_hermitian(n_modes))
hamiltonian = QuadraticHamiltonian(hermitian_part=hermitian_part)
# diagonalize Hamiltonian
(
transformation_matrix,
orbital_energies,
_,
) = hamiltonian.diagonalizing_bogoliubov_transform()
# set simulation time and construct time evolution circuit
time = 1.0
register = QuantumRegister(n_modes)
circuit = QuantumCircuit(register)
bog_circuit = BogoliubovTransform(transformation_matrix)
# change to the diagonal basis of the Hamiltonian
circuit.append(bog_circuit.inverse(), register)
# perform time evolution by applying z rotations
for q, energy in zip(register, orbital_energies):
circuit.rz(-energy * time, q)
# change back to the original basis
circuit.append(bog_circuit, register)
# simulate the circuit
initial_state = random_statevector(2**n_modes)
final_state = initial_state.evolve(circuit)
# compute the correct state by direct exponentiation
hamiltonian_jw = JordanWignerMapper().map(hamiltonian.second_q_op()).to_matrix()
exact_evolution_op = expm(-1j * time * hamiltonian_jw)
expected_state = exact_evolution_op @ np.array(initial_state)
# check that the simulated state is correct
fidelity = state_fidelity(final_state, expected_state)
np.testing.assert_allclose(fidelity, 1.0, atol=1e-8)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/BOBO1997/osp_solutions
|
BOBO1997
|
import numpy as np
import matplotlib.pyplot as plt
import itertools
from pprint import pprint
# plt.rcParams.update({'font.size': 16}) # enlarge matplotlib fonts
import pickle
import time
import datetime
# Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z)
from qiskit.opflow import Zero, One, I, X, Y, Z
from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer
from qiskit.tools.monitor import job_monitor
from qiskit.circuit import Parameter
from qiskit.transpiler.passes import RemoveBarriers
# Import QREM package
from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter
from qiskit.ignis.mitigation import expectation_value
# Import mitiq for zne
import mitiq
# Import state tomography modules
from qiskit.ignis.verification.tomography import state_tomography_circuits
from qiskit.quantum_info import state_fidelity
import sys
import importlib
sys.path.append("./")
import circuit_utils, zne_utils, tomography_utils, sgs_algorithm
importlib.reload(circuit_utils)
importlib.reload(zne_utils)
importlib.reload(tomography_utils)
importlib.reload(sgs_algorithm)
from circuit_utils import *
from zne_utils import *
from tomography_utils import *
from sgs_algorithm import *
# Combine subcircuits into a single multiqubit gate representing a single trotter step
num_qubits = 3
# The final time of the state evolution
target_time = np.pi
# Parameterize variable t to be evaluated at t=pi later
dt = Parameter('t')
# Convert custom quantum circuit into a gate
trot_gate = trotter_gate(dt)
# initial layout
initial_layout = [5,3,1]
# Number of trotter steps
num_steps = 100
print("trotter step: ", num_steps)
# Initialize quantum circuit for 3 qubits
qr = QuantumRegister(num_qubits, name="lq")
qc = QuantumCircuit(qr)
# Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>)
make_initial_state(qc, "110") # DO NOT MODIFY (|q_5,q_3,q_1> = |110>)
subspace_encoder_init110(qc, targets=[0, 1, 2]) # encode
trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian
subspace_decoder(qc, targets=[0,1,2]) # decode
# Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time
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"])
print("created t3_st_qcs (length:", len(t3_st_qcs), ")")
# zne wrapping
zne_qcs = zne_wrapper(t3_st_qcs)
print("created zne_qcs (length:", len(zne_qcs), ")")
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-utokyo', group='internal', project='hirashi-jst')
provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22')
print("provider:", provider)
backend = provider.get_backend("ibmq_jakarta")
# QREM
shots = 1 << 13
qr = QuantumRegister(num_qubits)
meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal')
cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout = initial_layout)
print('Job ID', cal_job.job_id())
shots = 1 << 13
reps = 8 # unused
jobs = []
for _ in range(reps):
job = execute(t3_zne_qcs, backend, shots=shots) # 毎回チェック: ここちゃんと変えた?
print('Job ID', job.job_id())
jobs.append(job)
dt_now = datetime.datetime.now()
import pickle
with open("jobs_jakarta_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f:
pickle.dump({"jobs": jobs, "cal_job": cal_job}, f)
with open("job_ids_jakarta_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f:
pickle.dump({"job_ids": [job.job_id() for job in jobs], "cal_job_id": cal_job.job_id()}, f)
with open("properties_jakarta" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f:
pickle.dump(backend.properties(), f)
with open("job_ids_jakarta_100step_20220411_030032_.pkl", "rb") as f:
job_ids_dict = pickle.load(f)
job_ids_dict['job_ids'] = job_ids_dict['job_ids'][:3]
job_ids = job_ids_dict["job_ids"]
cal_job_id = job_ids_dict["cal_job_id"]
job_ids, cal_job_id
retrieved_jobs = []
for job_id in job_ids:
retrieved_jobs.append(backend.retrieve_job(job_id))
retrieved_cal_job = backend.retrieve_job(cal_job_id)
# make the complete QREM fitter
qr = QuantumRegister(num_qubits)
_, state_labels = complete_meas_cal(qr=qr, circlabel='mcal')
cal_results = retrieved_cal_job.result()
meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal')
retrieved_results = []
for i in range(len(retrieved_jobs)):
retrieved_results.append(retrieved_jobs[i].result())
from qiskit.result import Result
labels = \
[('X', 'X', 'X'),
('X', 'X', 'Y'),
('X', 'X', 'Z'),
('X', 'Y', 'X'),
('X', 'Y', 'Y'),
('X', 'Y', 'Z'),
('X', 'Z', 'X'),
('X', 'Z', 'Y'),
('X', 'Z', 'Z'),
('Y', 'X', 'X'),
('Y', 'X', 'Y'),
('Y', 'X', 'Z'),
('Y', 'Y', 'X'),
('Y', 'Y', 'Y'),
('Y', 'Y', 'Z'),
('Y', 'Z', 'X'),
('Y', 'Z', 'Y'),
('Y', 'Z', 'Z'),
('Z', 'X', 'X'),
('Z', 'X', 'Y'),
('Z', 'X', 'Z'),
('Z', 'Y', 'X'),
('Z', 'Y', 'Y'),
('Z', 'Y', 'Z'),
('Z', 'Z', 'X'),
('Z', 'Z', 'Y'),
('Z', 'Z', 'Z'),
]
retrieved_results[0].results[0].header
reshaped_results = []
for result in retrieved_results:
res1 = Result(backend_name=result.backend_name, backend_version=result.backend_version, qobj_id=result.qobj_id, job_id=result.job_id, success=result.success, results=[])
res2 = Result(backend_name=result.backend_name, backend_version=result.backend_version, qobj_id=result.qobj_id, job_id=result.job_id, success=result.success, results=[])
res3 = Result(backend_name=result.backend_name, backend_version=result.backend_version, qobj_id=result.qobj_id, job_id=result.job_id, success=result.success, results=[])
for i, label in enumerate(labels):
result.results[3 * i].name = str(label)
result.results[3 * i].header.name = str(label)
result.results[3 * i + 1].name = str(label)
result.results[3 * i + 1].header.name = str(label)
result.results[3 * i + 2].name = str(label)
result.results[3 * i + 2].header.name = str(label)
res1.results.append(result.results[3 * i])
res2.results.append(result.results[3 * i + 1])
res3.results.append(result.results[3 * i + 2])
reshaped_results += [res1, res2, res3]
from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter
# Compute the state tomography based on the st_qcs quantum circuits and the results from those ciricuits
def state_tomo(result, st_qcs):
# The expected final state; necessary to determine state tomography fidelity
target_state = (One^One^Zero).to_matrix() # DO NOT MODIFY (|q_5,q_3,q_1> = |110>)
# Fit state tomography results
tomo_fitter = StateTomographyFitter(result, st_qcs)
rho_fit = tomo_fitter.fit(method='lstsq')
# Compute fidelity
fid = state_fidelity(rho_fit, target_state)
return fid
# Number of trotter steps
num_steps = 100
print("trotter step: ", num_steps)
# Initialize quantum circuit for 3 qubits
qr = QuantumRegister(num_qubits, name="lq")
qc = QuantumCircuit(qr)
# Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>)
make_initial_state(qc, "110") # DO NOT MODIFY (|q_5,q_3,q_1> = |110>)
subspace_encoder_init110(qc, targets=[0, 1, 2]) # encode
trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian
subspace_decoder(qc, targets=[0,1,2]) # decode
# Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time
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), ")")
st_qcs[0].name
# Compute tomography fidelities for each repetition
fids = []
for result in reshaped_results:
fid = state_tomo(result, st_qcs)
fids.append(fid)
print('state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(fids), np.std(fids)))
fids
reshaped_results[0].results[0]
str(('X', 'X', 'X'))
|
https://github.com/minnukota381/Quantum-Computing-Qiskit
|
minnukota381
|
from qiskit import *
from qiskit.visualization import plot_bloch_multivector, visualize_transition, plot_histogram
# Create a quantum circuit with 3 qubits
# The default initial state of qubits will be |0> or [1,0]
qc = QuantumCircuit(3)
#Applying hadamard gate to all the qubits
qc.h(0)
qc.h(1)
qc.h(2)
#Draw the circuit
# qc.draw()
qc.draw('mpl')
#Get the backend for the circuit (simulator or realtime system)
backend = Aer.get_backend('statevector_simulator')
#execute the circuit using the backend
out = execute(qc,backend).result().get_statevector()
#import qiskit_textbook and display the statevector
from qiskit_textbook.tools import array_to_latex
array_to_latex(out, pretext = "\\text{Statevector} = ")
#plot the result as a bloch sphere visualization
plot_bloch_multivector(out)
#execute the circuit and get the plain result
out = execute(qc,backend).result()
#getting the count of the result
counts = out.get_counts()
#plotting the histogram
plot_histogram(counts)
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
import qiskit
qiskit.__qiskit_version__
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
# importing Qiskit
from qiskit import BasicAer, IBMQ
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute
from qiskit.compiler import transpile
from qiskit.tools.visualization import plot_histogram
q = QuantumRegister(6)
qc = QuantumCircuit(q)
qc.x(q[2])
qc.cx(q[1], q[5])
qc.cx(q[2], q[5])
qc.cx(q[3], q[5])
qc.ccx(q[1], q[2], q[4])
qc.ccx(q[3], q[4], q[5])
qc.ccx(q[1], q[2], q[4])
qc.x(q[2])
qc.draw(output='mpl')
def black_box_u_f(circuit, f_in, f_out, aux, n, exactly_1_3_sat_formula):
"""Circuit that computes the black-box function from f_in to f_out.
Create a circuit that verifies whether a given exactly-1 3-SAT
formula is satisfied by the input. The exactly-1 version
requires exactly one literal out of every clause to be satisfied.
"""
num_clauses = len(exactly_1_3_sat_formula)
for (k, clause) in enumerate(exactly_1_3_sat_formula):
# This loop ensures aux[k] is 1 if an odd number of literals
# are true
for literal in clause:
if literal > 0:
circuit.cx(f_in[literal-1], aux[k])
else:
circuit.x(f_in[-literal-1])
circuit.cx(f_in[-literal-1], aux[k])
# Flip aux[k] if all literals are true, using auxiliary qubit
# (ancilla) aux[num_clauses]
circuit.ccx(f_in[0], f_in[1], aux[num_clauses])
circuit.ccx(f_in[2], aux[num_clauses], aux[k])
# Flip back to reverse state of negative literals and ancilla
circuit.ccx(f_in[0], f_in[1], aux[num_clauses])
for literal in clause:
if literal < 0:
circuit.x(f_in[-literal-1])
# The formula is satisfied if and only if all auxiliary qubits
# except aux[num_clauses] are 1
if (num_clauses == 1):
circuit.cx(aux[0], f_out[0])
elif (num_clauses == 2):
circuit.ccx(aux[0], aux[1], f_out[0])
elif (num_clauses == 3):
circuit.ccx(aux[0], aux[1], aux[num_clauses])
circuit.ccx(aux[2], aux[num_clauses], f_out[0])
circuit.ccx(aux[0], aux[1], aux[num_clauses])
else:
raise ValueError('We only allow at most 3 clauses')
# Flip back any auxiliary qubits to make sure state is consistent
# for future executions of this routine; same loop as above.
for (k, clause) in enumerate(exactly_1_3_sat_formula):
for literal in clause:
if literal > 0:
circuit.cx(f_in[literal-1], aux[k])
else:
circuit.x(f_in[-literal-1])
circuit.cx(f_in[-literal-1], aux[k])
circuit.ccx(f_in[0], f_in[1], aux[num_clauses])
circuit.ccx(f_in[2], aux[num_clauses], aux[k])
circuit.ccx(f_in[0], f_in[1], aux[num_clauses])
for literal in clause:
if literal < 0:
circuit.x(f_in[-literal-1])
# -- end function
def n_controlled_Z(circuit, controls, target):
"""Implement a Z gate with multiple controls"""
if (len(controls) > 2):
raise ValueError('The controlled Z with more than 2 ' +
'controls is not implemented')
elif (len(controls) == 1):
circuit.h(target)
circuit.cx(controls[0], target)
circuit.h(target)
elif (len(controls) == 2):
circuit.h(target)
circuit.ccx(controls[0], controls[1], target)
circuit.h(target)
# -- end function
def inversion_about_average(circuit, f_in, n):
"""Apply inversion about the average step of Grover's algorithm."""
# Hadamards everywhere
for j in range(n):
circuit.h(f_in[j])
# D matrix: flips the sign of the state |000> only
for j in range(n):
circuit.x(f_in[j])
n_controlled_Z(circuit, [f_in[j] for j in range(n-1)], f_in[n-1])
for j in range(n):
circuit.x(f_in[j])
# Hadamards everywhere again
for j in range(n):
circuit.h(f_in[j])
# -- end function
qr = QuantumRegister(3)
qInvAvg = QuantumCircuit(qr)
inversion_about_average(qInvAvg, qr, 3)
qInvAvg.draw(output='mpl')
"""
Grover search implemented in Qiskit.
This module contains the code necessary to run Grover search on 3
qubits, both with a simulator and with a real quantum computing
device. This code is the companion for the paper
"An introduction to quantum computing, without the physics",
Giacomo Nannicini, https://arxiv.org/abs/1708.03684.
"""
def input_state(circuit, f_in, f_out, n):
"""(n+1)-qubit input state for Grover search."""
for j in range(n):
circuit.h(f_in[j])
circuit.x(f_out)
circuit.h(f_out)
# -- end function
# Make a quantum program for the n-bit Grover search.
n = 3
# Exactly-1 3-SAT formula to be satisfied, in conjunctive
# normal form. We represent literals with integers, positive or
# negative, to indicate a Boolean variable or its negation.
exactly_1_3_sat_formula = [[1, 2, -3], [-1, -2, -3], [-1, 2, 3]]
# Define three quantum registers: 'f_in' is the search space (input
# to the function f), 'f_out' is bit used for the output of function
# f, aux are the auxiliary bits used by f to perform its
# computation.
f_in = QuantumRegister(n)
f_out = QuantumRegister(1)
aux = QuantumRegister(len(exactly_1_3_sat_formula) + 1)
# Define classical register for algorithm result
ans = ClassicalRegister(n)
# Define quantum circuit with above registers
grover = QuantumCircuit()
grover.add_register(f_in)
grover.add_register(f_out)
grover.add_register(aux)
grover.add_register(ans)
input_state(grover, f_in, f_out, n)
T = 2
for t in range(T):
# Apply T full iterations
black_box_u_f(grover, f_in, f_out, aux, n, exactly_1_3_sat_formula)
inversion_about_average(grover, f_in, n)
# Measure the output register in the computational basis
for j in range(n):
grover.measure(f_in[j], ans[j])
# Execute circuit
backend = BasicAer.get_backend('qasm_simulator')
job = execute([grover], backend=backend, shots=1000)
result = job.result()
# Get counts and plot histogram
counts = result.get_counts(grover)
plot_histogram(counts)
IBMQ.load_account()
# get ibmq_16_melbourne configuration and coupling map
backend = IBMQ.get_backend('ibmq_16_melbourne')
# compile the circuit for ibmq_16_rueschlikon
grover_compiled = transpile(grover, backend=backend, seed_transpiler=1, optimization_level=3)
print('gates = ', grover_compiled.count_ops())
print('depth = ', grover_compiled.depth())
grover.draw(output='mpl', scale=0.5)
|
https://github.com/Qiskit/feedback
|
Qiskit
|
import os
from typing import Any, Dict, List, Optional, Union
import numpy as np
import matplotlib.pyplot as plt
from qiskit import IBMQ, QuantumCircuit, QuantumRegister, ClassicalRegister, quantum_info as qi
from qiskit.providers.ibmq import RunnerResult
from qiskit.result import marginal_counts
import qiskit.tools.jupyter
%matplotlib inline
import warnings
warnings.filterwarnings("ignore")
%load_ext autoreload
%autoreload 2
# Note: This can be any hub/group/project that has access to the required device and the Qiskit runtime.
# Verify that ``qasm3`` is present in ``backend.configuration().supported_features``.
hub = "ibm-q-community"
group = "ieee-demos"
project = "main"
backend_name = "ibm_peekskill"
hgp = f"{hub}/{group}/{project}"
from qiskit.circuit import Delay, Parameter
from qiskit_ibm_runtime import QiskitRuntimeService
service = QiskitRuntimeService(instance=hgp)
backend = service.backend(backend_name, instance=hgp)
# Addresses a bug in the current Qiskit runtime package
# that will be fixed on the next Qiskit release
target = backend.target
if "delay" not in target:
target.add_instruction(
Delay(Parameter("t")), {(bit,): None for bit in range(target.num_qubits)}
)
from qiskit.providers.aer import AerSimulator, Aer
from qiskit.providers.aer.noise import NoiseModel
backend_noise_model = NoiseModel.from_backend(backend)
#backend_sim = AerSimulator(noise_model=backend_noise_model)
backend_sim = AerSimulator()
ideal_sim = Aer.get_backend('qasm_simulator')
import utils
backend
shots: int = 1024 # Number of shots to run each circuit for
init_num_resets: int = 3 # Set the number of resets to initialize qubits between circuits
init_delay: float = 0. # Set the initialization idle time for qubits between circuits
sim: bool = False # Set True to simulate our experiments and False to run in hardware
dynamical_decoupling: bool = False # Set True to enable dynamical decoupling
favourite_qubits: List[int] = [5, 3, 8, 2, 9]
# Some general helper routines that will be used throughout the notebook
import mapomatic as mm
from qiskit.circuit.library import XGate
from qiskit.transpiler import PassManager
from qiskit.transpiler.instruction_durations import InstructionDurations
from qiskit_ibm_runtime import RuntimeJob, IBMBackend
def convert_cycles(time_in_seconds: float, backend: IBMBackend) -> int:
cycles = time_in_seconds / (backend.configuration().dt)
return int(cycles + (16 - (cycles % 16)))
def execute(circuits: List[QuantumCircuit], verbose: bool = True, **kwargs) -> RuntimeJob:
"""A helper method to execute circuits with common settings in the notebook.
Args:
circuits: To execute.
verbose: Emit execution information.
sim: Run with simulator instead of hardware. By default reads global variable "sim"
"""
if isinstance(circuits, QuantumCircuit):
circuits = [circuits]
if sim:
return backend_sim.run(circuits, shots=shots, **kwargs)
else:
job = run_openqasm3(circuits, backend, verbose=False, shots=shots, init_num_resets=init_num_resets, init_delay=init_delay, **kwargs)
if verbose:
print(f"Running on qasm3, job id: {job.job_id}")
return job
def calculate_initial_layout(
circuit: QuantumCircuit,
mapomatic: Optional[bool] = None,
favourite_qubits: Optional[List[int]] = None,
blacklist_qubits: Optional[List[int]] = None
) -> List[int]:
"""Routine to help choose the ideal qubit layout given an input circuit.
Args:
circuit: To evaluate layout for.
mapomatic: Use mapomatic to choose ideal qubits, otherwise naievly choose ``favourite_qubits``
favourite_qubits: A list of favourite qubits to ensure are in the layout
blacklist_qubits: Qubits that are not allowed in the layout.
"""
deflated = mm.deflate_circuit(circuit)
if mapomatic:
deflated = mm.deflate_circuit(circuit)
available_layouts = [layout for layout in mm.matching_layouts(deflated, backend.configuration().coupling_map, strict_direction=False) if layout[:len(favourite_qubits)] == favourite_qubits and not set(layout).intersection(set(blacklist_qubits))]
scores = mm.evaluate_layouts(deflated, available_layouts, backend)
return scores[0][0]
if favourite_qubits is None:
favourite_qubits = []
if blacklist_qubits is None:
blacklist_qubits = []
return (favourite_qubits + list(set(range(backend.num_qubits)) - set(favourite_qubits)))[:deflated.num_qubits]
def apply_dynamical_decoupling(
circuits: List[QuantumCircuit],
backend: IBMBackend,
initial_layout: List[int],
) -> List[QuantumCircuit]:
"""Apply dynamic circuit dynamical decoupling."""
from qiskit_ibm_provider.transpiler.passes.scheduling import DynamicCircuitScheduleAnalysis, PadDynamicalDecoupling
dd_sequence = [XGate(), XGate()]
durations = InstructionDurations.from_backend(backend)
pm = PassManager(
[
DynamicCircuitScheduleAnalysis(durations),
PadDynamicalDecoupling(durations, dd_sequence, qubits=initial_layout),
]
)
return pm.run(circuits)
def apply_transpile(
circuits: List[QuantumCircuit],
backend: IBMBackend,
initial_layout: List[int],
dynamical_decoupling: bool = dynamical_decoupling,
**transpile_kwargs,
) -> List[QuantumCircuit]:
"""Fixed transpile routine to be used for consistency throughout the notebook."""
transpiled_circuits = transpile(circuits, backend, initial_layout=initial_layout, optimization_level=3, **transpile_kwargs)
if dynamical_decoupling:
return apply_dynamical_decoupling(transpiled_circuits, backend, initial_layout)
return transpiled_circuits
qubit = favourite_qubits[0]
print(f"We will use qubit {qubit}")
# Exercise
from utils import run_openqasm3
from qiskit import QuantumRegister, ClassicalRegister, transpile
qr = QuantumRegister(1)
crx = ClassicalRegister(1, name="xresult")
crm = ClassicalRegister(1, name="measureresult")
qc_reset = QuantumCircuit(qr, crx, crm, name="Reset")
# Complete the circuit to measure and conditionally reset the target
# qubit.
qc_reset = transpile(qc_reset, backend)
qc_reset.draw(output="mpl", idle_wires=False)
# Solution
from utils import run_openqasm3
from qiskit import QuantumRegister, ClassicalRegister, transpile
qr = QuantumRegister(1)
crx = ClassicalRegister(1, name="xresult")
crm = ClassicalRegister(1, name="measureresult")
qc_reset = QuantumCircuit(qr, crx, crm, name="Reset")
qc_reset.x(0)
qc_reset.measure(0, crx)
qc_reset.x(0).c_if(crx, 1)
qc_reset.measure(0, crm)
qc_reset = transpile(qc_reset, backend)
qc_reset.draw(output="mpl", idle_wires=False)
reset_job = run_openqasm3(qc_reset, backend, verbose=True, shots=shots, init_num_resets=0, init_delay=0) # Turn off automatic init
from qiskit.result import marginal_counts
reset_result = reset_job.result()
reset_counts = reset_result.get_counts(0)
# Look at only the final measurement result
initial_measurement_result = marginal_counts(reset_counts, indices=[0])
mitigated_reset_results = marginal_counts(reset_counts, indices=[1])
print(f"Full counts including reset: {reset_counts}")
print(f"Conditional X gate applied on: {initial_measurement_result['1']} shots")
print(f"Results from our reset - |0\rangles prepared: {mitigated_reset_results.get('0')}, |1\rangles prepared: {mitigated_reset_results.get('1', 0)}"
)
from qiskit import qasm3
basis_gates = backend.configuration().basis_gates
def dump_qasm3(circuit: QuantumCircuit, backend: IBMBackend = backend) -> str:
return qasm3.Exporter(includes=[],
basis_gates=backend.configuration().basis_gates,
disable_constants=True).dumps(circuit)
qasm3_reset = dump_qasm3(qc_reset)
print(qasm3_reset)
runtime_job = run_openqasm3(qasm3_reset, backend, verbose=True, shots=shots, init_num_resets=0, init_delay=0)
classical_compute_qasm3 = """
OPENQASM 3.0;
bit a;
bit b;
bit c;
x $0;
x $2;
a = measure $0; // expected "1"
b = measure $1; // expected "0"
c = measure $2; // expected "1"
bit[3] d = "100";
if (((a | b) & c) == 1) {
// Path will nearly always execute
d[0] = 1;
} else {
// Path will rarely execute outside of SPAM errors
d[0] = 0;
}
bit[3] e = "101";
// Conditionally execute based on classical bit array comparison
// Should always execute
if (d == e) {
x $1;
}
bit final;
final = measure $1; // expected "1"
"""
classical_compute_job = run_openqasm3(classical_compute_qasm3, backend, verbose=False, shots=shots)
qr = QuantumRegister(3)
cr = ClassicalRegister(3, name="result")
crz = cr[0]
crx = cr[1]
result = cr[2]
qc_teleport = QuantumCircuit(qr, cr, name="Teleport")
# Apply teleportation circuit
qc_teleport.h(qr[1])
qc_teleport.cx(qr[1], qr[2])
qc_teleport.cx(qr[0], qr[1])
qc_teleport.h(qr[0])
qc_teleport.measure(qr[0], crz)
qc_teleport.measure(qr[1], crx)
qc_teleport.z(qr[2]).c_if(crz, 1)
qc_teleport.x(qr[2]).c_if(crx, 1)
qc_teleport.draw(output="mpl")
# Prepare |1> for teleportation
qc_state_prep = QuantumCircuit(1)
qc_state_prep.x(0)
print(qc_state_prep)
target_state_prep = qi.Statevector.from_instruction(qc_state_prep)
target_state_prep.draw(output="bloch")
teleport_qubits = favourite_qubits[:3]
qc_teleport_state = QuantumCircuit(qr, cr, name="Teleport Hadamard")
# Prepare state to teleport
qc_teleport_state.compose(qc_state_prep, [qr[0]], inplace=True)
qc_teleport_state.barrier(qr)
# Compose with teleportation circuit
qc_teleport_state.compose(qc_teleport, inplace=True)
qc_teleport_state.draw(output="mpl")
qc_teleport_experiment = qc_teleport_state.copy()
qc_teleport_experiment.measure(qr[2], result)
qc_teleport_experiment = apply_transpile(qc_teleport_experiment, backend, initial_layout=teleport_qubits)
qc_teleport_experiment.draw(output="mpl", idle_wires=True)
teleport_job = execute(qc_teleport_experiment, verbose=False)
teleport_result = teleport_job.result()
print(f"All teleportation counts: {teleport_result.get_counts(0)}")
marginal_teleport_counts = marginal_counts(teleport_result.get_counts(0), indices=[2])
print(f"Marginalized teleportation counts: {marginal_teleport_counts}")
p1 = 0.01
p3 = 3 * p1**2 * (1-p1) + p1**3 # probability of 2 or 3 errors
print('Probability of a single reply being garbled: {}'.format(p1))
print('Probability of a majority of the three replies being garbled: {:.4f}'.format(p3))
# Approximate duration of the measurement processing / conditional latency
block_branch_duration = 0.5e-6
block_branch_cycles = convert_cycles(block_branch_duration, backend)
# Setup a base quantum circuit for our experiments
qreg_data = QuantumRegister(3)
qreg_measure = QuantumRegister(2)
creg_data = ClassicalRegister(3)
creg_syndrome = ClassicalRegister(2)
state_data = qreg_data[0]
ancillas_data = qreg_data[1:]
def build_qc() -> QuantumCircuit:
return QuantumCircuit(qreg_data, qreg_measure, creg_data, creg_syndrome)
# Exercise
qc_init = build_qc()
# Complete to initialize the |1> state
qc_init.barrier(qreg_data)
qc_init.draw(output="mpl")
# Solution
qc_init = build_qc()
qc_init.x(qreg_data[0])
qc_init.barrier(qreg_data)
qc_init.draw(output="mpl")
# Exercise
# Complete the method below to encode the bit-flip code
def encode_bit_flip(qc, state, ancillas):
# Complete
qc.barrier(state, *ancillas)
return qc
qc_encode_bit = build_qc()
encode_bit_flip(qc_encode_bit, state_data, ancillas_data)
qc_encode_bit.draw(output="mpl")
# Solution
def encode_bit_flip(qc, state, ancillas):
control = state
for ancilla in ancillas:
qc.cx(control, ancilla)
qc.barrier(state, *ancillas)
return qc
qc_encode_bit = build_qc()
encode_bit_flip(qc_encode_bit, state_data, ancillas_data)
qc_encode_bit.draw(output="mpl")
# Exercise
# Complete the routine below to decode from the bit-flip codespace
def decode_bit_flip(qc, state, ancillas):
#complete
return qc
qc_decode_bit = build_qc()
qc_decode_bit = decode_bit_flip(qc_decode_bit, state_data, ancillas_data)
qc_decode_bit.draw(output="mpl")
qc_encoded_state_bit = qc_init.compose(qc_encode_bit)
qc_encoded_state_bit.draw(output="mpl")
# Solution
def decode_bit_flip(qc, state, ancillas):
inv = qc_encode_bit.inverse()
return qc.compose(inv)
qc_decode_bit = build_qc()
qc_decode_bit = decode_bit_flip(qc_decode_bit, state_data, ancillas_data)
qc_decode_bit.draw(output="mpl")
# Exercise
# Complete the syndome measurement routine below
def measure_syndrome_bit(qc, qreg_data, qreg_measure, creg_measure):
# Complete
qc.barrier(*qreg_data, *qreg_measure)
return qc
qc_syndrome_bit = measure_syndrome_bit(build_qc(), qreg_data, qreg_measure, creg_syndrome)
qc_syndrome_bit.draw(output="mpl")
qc_measure_syndrome_bit = qc_encoded_state_bit.compose(qc_syndrome_bit)
qc_measure_syndrome_bit.draw(output="mpl")
# Solution
def measure_syndrome_bit(qc, qreg_data, qreg_measure, creg_measure):
def branch_delay():
if sim:
qc.barrier(qreg_data)
qc.delay(block_branch_cycles, qreg_data)
qc.barrier(qreg_data)
qc.cx(qreg_data[0], qreg_measure[0])
qc.cx(qreg_data[1], qreg_measure[0])
qc.cx(qreg_data[0], qreg_measure[1])
qc.cx(qreg_data[2], qreg_measure[1])
qc.measure(qreg_measure, creg_measure)
branch_delay() # grouped in hardware
qc.x(qreg_measure[0]).c_if(creg_measure[0], 1)
qc.x(qreg_measure[1]).c_if(creg_measure[1], 1)
qc.barrier(*qreg_data, *qreg_measure)
return qc
qc_syndrome_bit = measure_syndrome_bit(build_qc(), qreg_data, qreg_measure, creg_syndrome)
qc_syndrome_bit.draw(output="mpl")
# Exercise
# Complete the routine below to apply our decoding and correction sequence
def apply_correction_bit(qc, qreg_data, creg_syndrome):
# Complete
qc.barrier(qreg_data)
return qc
qc_correction_bit = apply_correction_bit(build_qc(), qreg_data, creg_syndrome)
qc_correction_bit.draw(output="mpl")
def apply_final_readout(qc, qreg_data, creg_data):
"""Apply inverse mapping so that we always try and measure |1> in the computational basis.
TODO: The above is just a stand in for proper measurement basis measurement
"""
qc.barrier(qreg_data)
qc.measure(qreg_data, creg_data)
return qc
qc_final_measure = apply_final_readout(build_qc(), qreg_data, creg_data)
qc_final_measure.draw(output="mpl")
bit_code_circuit = qc_measure_syndrome_bit.compose(qc_correction_bit).compose(qc_final_measure)
bit_code_circuit.draw(output="mpl")
# Solution
def apply_correction_bit(qc, qreg_data, creg_syndrome):
# If simulating we need to insert a delay to mirror the hardware
def branch_delay():
if sim:
qc.barrier(qreg_data)
qc.delay(block_branch_cycles, qreg_data)
qc.barrier(qreg_data)
branch_delay()
qc.x(qreg_data[0]).c_if(creg_syndrome, 3)
branch_delay()
qc.x(qreg_data[1]).c_if(creg_syndrome, 1)
branch_delay()
qc.x(qreg_data[2]).c_if(creg_syndrome, 2)
qc.barrier(qreg_data)
return qc
qc_correction_bit = apply_correction_bit(build_qc(), qreg_data, creg_syndrome)
qc_correction_bit.draw(output="mpl")
def build_error_correction_sequence(
qc_base: QuantumCircuit,
qc_init: Optional[QuantumCircuit],
qc_encode: QuantumCircuit,
qc_channels: List[QuantumCircuit],
qc_syndrome: QuantumCircuit,
qc_correct: QuantumCircuit,
qc_decode: Optional[QuantumCircuit] = None,
qc_final: Optional[QuantumCircuit] = None,
name=None,
) -> QuantumCircuit:
"""Build a typical error correction circuit"""
qc = qc_base
if qc_init:
qc = qc.compose(
qc_init
)
qc = qc.compose(
qc_encode
)
if name is not None:
qc.name = name
if not qc_channels:
qc_channels = [QuantumCircuit(*qc.qregs)]
for qc_channel in qc_channels:
qc = qc.compose(
qc_channel
).compose(
qc_syndrome
).compose(
qc_correct
)
if qc_decode:
qc = qc.compose(qc_decode)
if qc_final:
qc = qc.compose(qc_final)
return qc
bit_code_circuit = build_error_correction_sequence(
build_qc(),
qc_init,
qc_encode_bit,
[],
qc_syndrome_bit,
qc_correction_bit,
None,
qc_final_measure,
)
bit_code_circuit.draw(output="mpl")
layout_circuit = transpile(bit_code_circuit, backend, optimization_level=3)
print(initial_layout := calculate_initial_layout(layout_circuit, False, favourite_qubits))
transpiled_bit_code_circuit = apply_transpile(bit_code_circuit, backend, initial_layout=initial_layout)
transpiled_bit_code_circuit.draw(output="mpl")
result = execute(transpiled_bit_code_circuit).result()
def decode_result(data_counts, syndrome_counts, verbose=True, indent=0):
shots = sum(data_counts.values())
success_trials = data_counts.get('000', 0) + data_counts.get('111', 0)
failed_trials = shots-success_trials
error_correction_events = shots-syndrome_counts.get('00', 0)
if verbose:
print(f"{' ' * indent}Bit flip errors were corrected on {error_correction_events}/{shots} trials")
print(f"{' ' * indent}A final parity error was detected on {failed_trials}/{shots} trials")
print(f"{' ' * indent}No error was detected on {success_trials}/{shots} trials")
return error_correction_events, failed_trials
data_indices = list(range(len(qreg_data)))
syndrome_indices = list(range(data_indices[-1]+1, len(qreg_data) + len(qreg_measure) ))
marginalized_data_result = marginal_counts(result, data_indices)
marginalized_syndrome_result = marginal_counts(result, syndrome_indices)
print(f'Completed bit code experiment data measurement counts {marginalized_data_result.get_counts(0)}')
print(f'Completed bit code experiment syndrome measurement counts {marginalized_syndrome_result.get_counts(0)}')
decode_result(marginalized_data_result.get_counts(0), marginalized_syndrome_result.get_counts(0));
from qiskit.circuit.library import IGate, XGate, ZGate
qreg_error_ancilla = QuantumRegister(1)
creg_error_ancilla = ClassicalRegister(1)
def build_random_error_channel(gate, ancilla, creg_ancilla, error_qubit):
"""Build an error channel that randomly applies a single-qubit gate based on an ancilla qubit measurement result"""
qc = build_qc()
qc.add_register(qreg_error_ancilla)
qc.add_register(creg_error_ancilla)
qc.barrier(ancilla, error_qubit.register)
# 50-50 chance of applying a bit-flip
qc.h(ancilla)
qc.measure(ancilla, creg_ancilla)
qc.append(gate, [error_qubit]).c_if(creg_ancilla, 1)
qc.barrier(ancilla, error_qubit.register)
return qc
qc_id_error_channel = build_random_error_channel(IGate(), qreg_error_ancilla, creg_error_ancilla, qreg_data[0])
print("Identity error channel")
print(qc_id_error_channel.draw(idle_wires=False,output='text',fold=-1))
qc_bit_flip_error_channel = build_random_error_channel(XGate(), qreg_error_ancilla, creg_error_ancilla, qreg_data[0])
print("Bit flip error channel")
print(qc_bit_flip_error_channel.draw(idle_wires=False,output='text',fold=-1))
qc_phase_flip_error_channel = build_random_error_channel(ZGate(), qreg_error_ancilla, creg_error_ancilla, qreg_data[0])
print("Phase flip error channel")
print(qc_phase_flip_error_channel.draw(idle_wires=False,output='text',fold=-1))
def build_error_channel_base():
qc = build_qc()
qc.add_register(qreg_error_ancilla)
qc.add_register(creg_error_ancilla)
return qc
qc_id_error_bit_flip_code = build_error_correction_sequence(
build_error_channel_base(),
qc_init,
qc_encode_bit,
[qc_id_error_channel],
qc_syndrome_bit,
qc_correction_bit,
None,
qc_final_measure,
"Identity error channel"
)
qc_bit_flip_error_bit_flip_code = build_error_correction_sequence(
build_error_channel_base(),
qc_init,
qc_encode_bit,
[qc_bit_flip_error_channel],
qc_syndrome_bit,
qc_correction_bit,
None,
qc_final_measure,
"Bit flip error channel"
)
qc_phase_flip_error_bit_flip_code = build_error_correction_sequence(
build_error_channel_base(),
qc_init,
qc_encode_bit,
[qc_phase_flip_error_channel],
qc_syndrome_bit,
qc_correction_bit,
None,
qc_final_measure,
"Phase flip error channel"
)
circuits_error_channels_bit_flip_code = [qc_id_error_bit_flip_code, qc_bit_flip_error_bit_flip_code, qc_phase_flip_error_bit_flip_code]
qc_bit_flip_error_bit_flip_code.draw(output="mpl")
# We need to add an extra ancilla qubit to our layout
# It doesn't matter which qubit for the must part as we are using as a
# source of random information
error_channel_layout = error_channel_layout = initial_layout + list(set(range(circuits_error_channels_bit_flip_code[0].num_qubits)) - set(initial_layout))[:1]
transpiled_circuits_error_channels_bit_flip_code = apply_transpile(circuits_error_channels_bit_flip_code, backend, initial_layout=error_channel_layout)
result_error_channels_bit_flip_code = execute(transpiled_circuits_error_channels_bit_flip_code).result()
from qiskit.quantum_info.analysis import hellinger_fidelity
def decode_error_channel_result(qc_init, data_counts, syndrome_counts, verbose=True, indent=0):
shots = sum(data_counts.values())
logical_zero = data_counts.get('000', 0)
logical_one = data_counts.get('111', 0)
success_trials = logical_zero + logical_one
failed_trials = shots-success_trials
logical_counts = {"0": logical_zero, "1": logical_one}
ideal_transpiled = apply_transpile(qc_init_outcome, backend, initial_layout)
counts_ideal = marginal_counts(ideal_sim.run(ideal_transpiled, shots=success_trials).result().get_counts(0), indices=[0])
fidelity = hellinger_fidelity(counts_ideal, logical_counts)
error_correction_events = shots-syndrome_counts.get('00', 0)
if verbose:
print(f"{' ' * indent}Bit flip errors were corrected on {error_correction_events}/{shots} trials")
print(f"{' ' * indent}A final parity error was detected on {failed_trials}/{shots} trials")
print(f"{' ' * indent}For the successful trials the Hellinger fidelity is {fidelity}")
return error_correction_events, failed_trials
qc_init_outcome = qc_init.copy()
qc_init_outcome.measure(qreg_data[0], 0)
qreg_indices = list(range(len(qreg_data)))
data_indices = qreg_indices[:1]
syndrome_indices = list(range(qreg_indices[-1]+1, len(qreg_data) + len(qreg_measure) ))
result_decoded_data_qubit_marginal_err_ch = marginal_counts(result_error_channels_bit_flip_code, data_indices)
result_data_marginal_err_ch = marginal_counts(result_error_channels_bit_flip_code, qreg_indices)
result_syndrome_marginal_err_ch = marginal_counts(result_error_channels_bit_flip_code, syndrome_indices)
for i, qc in enumerate(transpiled_circuits_error_channels_bit_flip_code):
print(f"For {qc.name} with bit flip code")
print(f' Completed bit code experiment decoded data qubit measurement counts {result_decoded_data_qubit_marginal_err_ch.get_counts(i)}')
print(f' Completed bit code experiment data qubits measurement counts {result_data_marginal_err_ch.get_counts(i)}')
print(f' Completed bit code experiment syndrome measurement counts {result_data_marginal_err_ch.get_counts(i)}')
decode_error_channel_result(qc_init_outcome, result_data_marginal_err_ch.get_counts(i), result_syndrome_marginal_err_ch.get_counts(i), indent=4);
print("")
# Exercise
# Complete the routine below to apply an "identity" correction rather than
# the standard bit-flip correction sequence
def apply_no_correction_bit(qc, qreg_data, creg_syndrome):
"""Complete the method below to apply an "identity correction"
Make sure to still apply the conditional gates so that the comparison to the bit-flip
code is faithful.
"""
# Complete
qc.barrier(qreg_data)
return qc
qc_no_correction_bit = apply_no_correction_bit(build_qc(), qreg_data, creg_syndrome)
qc_no_correction_bit.draw(output="mpl")
# Exercise
# Complete the sequence using `build_error_correction_sequence` to evaluate the
# performance of the identity correction sequence
# Complete the following routines
qc_id_error_no_correct = QuantumCircuit() # build_error_correction_sequence(...)
qc_bit_flip_error_no_correct = QuantumCircuit() # build_error_correction_sequence(...)
qc_phase_flip_error_no_correct = QuantumCircuit() # build_error_correction_sequence(...)
circuits_error_channels_no_correct = [qc_id_error_no_correct, qc_bit_flip_error_no_correct, qc_phase_flip_error_no_correct]
qc_id_error_no_correct.draw(output="mpl")
# We need to add an extra ancilla qubit to our layout
# It doesn't matter which qubit for the must part as we are using as a
# source of random information
error_channel_layout = error_channel_layout = initial_layout + list(set(range(circuits_error_channels_bit_flip_code[0].num_qubits)) - set(initial_layout))[:1]
transpiled_circuits_error_channels_no_correct = apply_transpile(circuits_error_channels_no_correct, backend, initial_layout=error_channel_layout)
result_error_channels_no_correct = execute(transpiled_circuits_error_channels_no_correct).result()
qc_init_outcome = qc_init.copy()
qc_init_outcome.measure(qreg_data[0], 0)
qreg_indices = list(range(len(qreg_data)))
data_indices = qreg_indices[:1]
syndrome_indices = list(range(qreg_indices[-1]+1, len(qreg_data) + len(qreg_measure) ))
result_decoded_data_qubit_marginal_no_correct = marginal_counts(result_error_channels_no_correct, data_indices)
result_data_marginal_no_correct = marginal_counts(result_error_channels_no_correct, qreg_indices)
result_syndrome_marginal_no_correct = marginal_counts(result_error_channels_no_correct, syndrome_indices)
for i, qc in enumerate(transpiled_circuits_error_channels_no_correct):
print(f"For {qc.name} with bit flip code")
print(f' Completed bit code experiment decoded data qubit measurement counts {result_decoded_data_qubit_marginal_no_correct.get_counts(i)}')
print(f' Completed bit code experiment data qubits measurement counts {result_data_marginal_no_correct.get_counts(i)}')
print(f' Completed bit code experiment syndrome measurement counts {result_data_marginal_no_correct.get_counts(i)}')
decode_error_channel_result(qc_init_outcome, result_data_marginal_no_correct.get_counts(i), result_syndrome_marginal_no_correct.get_counts(i), indent=4);
print("")
def apply_final_readout_invert(qc, qc_init, qreg_data, creg_data):
"""Apply inverse mapping so that we always try and measure |1> in the computational basis."""
qc = qc.compose(qc_init.inverse())
qc.x(qreg_data[0])
qc.barrier(qreg_data)
qc.measure(qreg_data, creg_data)
return qc
qc_final_measure_invert = apply_final_readout_invert(build_qc(), qc_init, qreg_data, creg_data)
qc_final_measure_invert.draw(output="mpl")
# Solution
qc_id_error_no_correct = build_error_correction_sequence(
build_error_channel_base(),
qc_init,
qc_encode_bit,
[qc_id_error_channel],
qc_syndrome_bit,
qc_no_correction_bit,
None,
qc_final_measure,
"Identity error channel"
)
qc_bit_flip_error_no_correct = build_error_correction_sequence(
build_error_channel_base(),
qc_init,
qc_encode_bit,
[qc_bit_flip_error_channel],
qc_syndrome_bit,
qc_no_correction_bit,
None,
qc_final_measure,
"Bit flip error channel"
)
qc_phase_flip_error_no_correct = build_error_correction_sequence(
build_error_channel_base(),
qc_init,
qc_encode_bit,
[qc_phase_flip_error_channel],
qc_syndrome_bit,
qc_no_correction_bit,
None,
qc_final_measure,
"Phase flip error channel"
)
circuits_error_channels_no_correct = [qc_id_error_no_correct, qc_bit_flip_error_no_correct, qc_phase_flip_error_no_correct]
qc_id_error_no_correct.draw(output="mpl")
from collections import defaultdict
from qiskit.transpiler import PassManager, InstructionDurations
from qiskit.transpiler.passes import ASAPSchedule, PadDelay
from qiskit_ibm_provider.transpiler.passes.scheduling import DynamicCircuitScheduleAnalysis, PadDelay
def get_circuit_duration_(qc: QuantumCircuit) -> int:
"""Get duration of circuit in hardware cycles."""
durations = InstructionDurations.from_backend(backend)
pm = PassManager([DynamicCircuitScheduleAnalysis(durations)])
pm.run(qc)
node_start_times = pm.property_set["node_start_time"]
block_durations = defaultdict(int)
for inst, (block, t0) in node_start_times.items():
block_durations[block] = max(block_durations[block], t0+inst.op.duration)
duration = sum(block_durations.values())
# If we are running on real hardware the delays have not been appended to the
# circuit directly and are instead built into the conditional operations.
# We account for them manually here
if not sim:
duration += block_branch_cycles * (len(block_durations) - 1)
return duration
def build_idle_error_correction_sequence(
qc_base: QuantumCircuit,
qc_init: Optional[QuantumCircuit],
qc_encode: QuantumCircuit,
qc_channels: List[QuantumCircuit],
qc_syndrome: QuantumCircuit,
qc_correct: QuantumCircuit,
qc_decode: Optional[QuantumCircuit] = None,
qc_final: Optional[QuantumCircuit] = None,
initial_layout=initial_layout,
name: str = None,
) -> QuantumCircuit:
"""Build a quantum circuit that idles for the period of the input error correction sequence."""
qc = qc_base
if qc_init:
qc = qc.compose(
qc_init
)
if name is not None:
qc.name = name
qc_idle_region = qc_base.copy()
qc_idle_region.compose(
qc_encode
)
if not qc_channels:
qc_channels = [QuantumCircuit(*qc.qregs)]
for qc_channel in qc_channels:
qc_idle_region = qc_idle_region.compose(
qc_channel
).compose(
qc_syndrome
).compose(
qc_correct
)
if qc_decode:
qc_idle_region = qc_idle_region.compose(qc_decode)
qc_idle_transpiled = apply_transpile(qc_idle_region, backend, initial_layout=initial_layout, scheduling_method=None)
idle_duration = get_circuit_duration_(qc_idle_transpiled)
qc_idle = qc_base.copy()
qc_idle.barrier()
for qubit in qc_idle.qubits:
qc_idle.delay(idle_duration, qubit, unit="dt")
qc_idle.barrier()
qc = qc.compose(qc_idle)
if qc_final:
qc = qc.compose(qc_final_measure)
return qc
# Exercise
def build_idle_error_channel(time_in_seconds, qreg):
idle_cycles = convert_cycles(time_in_seconds, backend)
qc_idle = build_qc()
# Complete
qc_idle.barrier()
return qc_idle
# Solution
def build_idle_error_channel(time_in_seconds, qreg):
idle_cycles = convert_cycles(time_in_seconds, backend)
qc_idle = build_qc()
qc_idle.delay(idle_cycles, qreg, "dt")
qc_idle.barrier()
return qc_idle
# Exercise
num_rounds = 5
# Idle for a specified period in seconds
# This is how we build an idle error channel
idle_period = 5e-6
# Use the circuit we created above
qc_idle = build_idle_error_channel(idle_period, qreg_data)
qcs_corr_bit = []
qcs_no_corr_bit = []
qcs_idle_equiv_bit = []
for round_ in range(num_rounds):
qc_error_channels = [qc_idle] * (round_ + 1)
# Complete bit flip code iteration
qcs_corr_bit.append(QuantumCircuit())
# Complete no correction bit flip code iteration
qcs_no_corr_bit.append(QuantumCircuit())
# Complete idle equivalent bit flip code iteration
qcs_idle_equiv_bit.append(QuantumCircuit())
qcs_corr_bit[0].draw(output="mpl", idle_wires=False)
transpiled_qcs_corr_bit = apply_transpile(qcs_corr_bit, backend, initial_layout=initial_layout)
job_qcs_corr_bit = execute(transpiled_qcs_corr_bit)
transpiled_qcs_no_corr_bit = apply_transpile(qcs_no_corr_bit, backend, initial_layout=initial_layout)
job_qcs_no_corr_bit = execute(transpiled_qcs_no_corr_bit)
transpiled_qcs_idle_equiv_bit = apply_transpile(qcs_idle_equiv_bit, backend, initial_layout=initial_layout, dynamical_decoupling=True)
job_qcs_idle_equiv_bit = execute(transpiled_qcs_idle_equiv_bit)
result_qcs_corr_bit = job_qcs_corr_bit.result()
result_qcs_no_corr_bit = job_qcs_no_corr_bit.result()
result_qcs_idle_equiv_bit = job_qcs_idle_equiv_bit.result()
transpiled_qcs_idle_equiv_bit[-1].draw(output="mpl")
from qiskit.quantum_info.analysis import hellinger_fidelity
qc_init_outcome = qc_init.copy()
qc_init_outcome = qc_init_outcome.compose(qc_final_measure)
result_ideal = ideal_sim.run(apply_transpile(qc_init_outcome, backend, initial_layout)).result()
def calculate_hellinger_fidelity(result_ideal, result_experiment, data_qubit=0):
result_ideal = marginal_counts(result_ideal, indices=[data_qubit])
result_experiment = marginal_counts(result_experiment, indices=[data_qubit])
counts_ideal = result_ideal.get_counts(0)
hellinger_fidelities = []
for circuit_idx in range(len(result_experiment.results)):
hellinger_fidelities.append(hellinger_fidelity(counts_ideal, result_experiment.get_counts(circuit_idx)))
return hellinger_fidelities
# Evaluate the Hellinger fidelity using the routine above
fidelities_corr_bit = 0.
fidelities_no_corr_bit = 0.
fidelities_idle_equiv_bit = 0.
# Solution
num_rounds = 5
# Idle for a specified period in seconds
# This is how we build an idle error channel
idle_period = 5e-6
# Use the circuit we created above
qc_idle = build_idle_error_channel(idle_period, qreg_data)
qcs_corr_bit = []
qcs_no_corr_bit = []
qcs_idle_equiv_bit = []
for round_ in range(num_rounds):
qc_error_channels = [qc_idle] * (round_ + 1)
#qcs_corr_bit.append(QuantumCircuit())
qcs_corr_bit.append(
build_error_correction_sequence(
build_qc(),
qc_init,
qc_encode_bit,
qc_error_channels,
qc_syndrome_bit,
qc_correction_bit,
qc_decode_bit,
qc_final_measure_invert,
f"With Correction {round_}"
)
)
#qcs_no_corr_bit.append(QuantumCircuit())
qcs_no_corr_bit.append(
build_error_correction_sequence(
build_qc(),
qc_init,
qc_encode_bit,
qc_error_channels,
qc_syndrome_bit,
qc_no_correction_bit,
qc_decode_bit,
qc_final_measure_invert,
name=f"Without Correction {round_}"
)
)
#qcs_idle_equiv_bit.append(QuantumCircuit())
qcs_idle_equiv_bit.append(
build_idle_error_correction_sequence(
build_qc(),
qc_init,
qc_encode_bit,
qc_error_channels,
qc_syndrome_bit,
qc_correction_bit,
qc_decode_bit,
qc_final_measure_invert,
initial_layout=initial_layout,
name=f"Idle {round_}"
)
)
fidelities_corr_bit = calculate_hellinger_fidelity(result_ideal, result_qcs_corr_bit)
fidelities_no_corr_bit = calculate_hellinger_fidelity(result_ideal, result_qcs_no_corr_bit)
fidelities_idle_equiv_bit = calculate_hellinger_fidelity(result_ideal, result_qcs_idle_equiv_bit)
import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = (12, 6)
iters = range(1, num_rounds+1)
plt.plot(iters, fidelities_corr_bit, label="Bit flip code - correction")
plt.plot(iters, fidelities_no_corr_bit, label="Bit flip code - no correction")
plt.plot(iters, fidelities_idle_equiv_bit, label="Idle equivalent circuit")
plt.ylabel("Hellinger Fidelity")
plt.xlabel("Correction cycles")
plt.xticks(iters)
plt.suptitle("Comparing the performance of error-correction strategies for multiple correction cycles")
plt.title(f"Idle period: {idle_period*1e6}us - Qubit layout: {initial_layout} - Dynamical decoupling: {dynamical_decoupling}")
plt.legend(loc="upper right")
result_qcs_corr_bit = job_qcs_corr_bit.result()
result_qcs_no_corr_bit = job_qcs_no_corr_bit.result()
result_qcs_idle_equiv_bit = job_qcs_idle_equiv_bit.result()
def build_412(circuit,qubits,parity,layout='zxz') -> QuantumCircuit:
### qubits
# qubits: list of 7 qubits
# ex. [q[0],q[1],q[2],q[3],q[4],q[5],q[6],q[7]]
#where first 4 are data qubits, 5 and 6 are flags, and 7 is ancilla (see image from heavy-hex paper)
### parity
# parity is 'x' or 'z'
### initialized_ancilla = True or False.
# If True, will prepare f1,f2,a1 in correct basis and apply post rotation before measurement
# Will include barrier after prep and before post rot if True
[d1,d2,d3,d4,f1,f2,a1]=qubits
if layout == 'zxz':
if parity == 'x':
circuit.h(a1)
circuit.cx(a1,f2)
circuit.cx(a1,f1)
circuit.cx(f2,d1)
circuit.cx(f1,d4)
circuit.cx(f2,d2)
circuit.cx(f1,d3)
circuit.cx(a1,f2)
circuit.cx(a1,f1)
circuit.h(a1)
if parity == 'z':
circuit.cx(d2,f2)
circuit.cx(d1,f2)
circuit.cx(d3,f1)
circuit.cx(d4,f1)
return circuit
elif layout == 'xzx':
if parity == 'z':
circuit.h(f1)
circuit.h(f2)
circuit.cx(f2,a1)
circuit.cx(f1,a1)
circuit.cx(d1,f2)
circuit.cx(d3,f1)
circuit.cx(d2,f2)
circuit.cx(d4,f1)
circuit.cx(f2,a1)
circuit.cx(f1,a1)
circuit.h(f1)
circuit.h(f2)
if parity == 'x':
circuit.h(f1)
circuit.h(f2)
circuit.cx(f2,d2)
circuit.cx(f2,d1)
circuit.cx(f1,d3)
circuit.cx(f1,d4)
circuit.h(f1)
circuit.h(f2)
return circuit
# Complete - how do you do the Z and X checks for this code? How do you decode the errors?
# See: https://arxiv.org/abs/2110.04285
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 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.
# pylint: disable=missing-docstring,invalid-name,no-member
# pylint: disable=attribute-defined-outside-init
import itertools
from qiskit import QuantumRegister, QuantumCircuit
from qiskit.circuit import Parameter
def build_circuit(width, gates):
qr = QuantumRegister(width)
qc = QuantumCircuit(qr)
while len(qc) < gates:
for k in range(width):
qc.h(qr[k])
for k in range(width - 1):
qc.cx(qr[k], qr[k + 1])
return qc
class CircuitConstructionBench:
params = ([1, 2, 5, 8, 14, 20], [8, 128, 2048, 8192, 32768, 131072])
param_names = ["width", "gates"]
timeout = 600
def setup(self, width, gates):
self.empty_circuit = build_circuit(width, 0)
self.sample_circuit = build_circuit(width, gates)
def time_circuit_construction(self, width, gates):
build_circuit(width, gates)
def time_circuit_extend(self, _, __):
self.empty_circuit.extend(self.sample_circuit)
def time_circuit_copy(self, _, __):
self.sample_circuit.copy()
def build_parameterized_circuit(width, gates, param_count):
params = [Parameter("param-%s" % x) for x in range(param_count)]
param_iter = itertools.cycle(params)
qr = QuantumRegister(width)
qc = QuantumCircuit(qr)
while len(qc) < gates:
for k in range(width):
param = next(param_iter)
qc.u2(0, param, qr[k])
for k in range(width - 1):
param = next(param_iter)
qc.crx(param, qr[k], qr[k + 1])
return qc, params
class ParameterizedCircuitConstructionBench:
params = ([20], [8, 128, 2048, 8192, 32768, 131072], [8, 128, 2048, 8192, 32768, 131072])
param_names = ["width", "gates", "number of params"]
timeout = 600
def setup(self, _, gates, params):
if params > gates:
raise NotImplementedError
def time_build_parameterized_circuit(self, width, gates, params):
build_parameterized_circuit(width, gates, params)
class ParameterizedCircuitBindBench:
params = ([20], [8, 128, 2048, 8192, 32768, 131072], [8, 128, 2048, 8192, 32768, 131072])
param_names = ["width", "gates", "number of params"]
timeout = 600
def setup(self, width, gates, params):
if params > gates:
raise NotImplementedError
self.circuit, self.params = build_parameterized_circuit(width, gates, params)
def time_bind_params(self, _, __, ___):
self.circuit.bind_parameters({x: 3.14 for x in self.params})
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import numpy as np
from qiskit import QuantumCircuit
from qiskit.quantum_info import DensityMatrix
from qiskit.visualization import plot_state_hinton
qc = QuantumCircuit(2)
qc.h([0, 1])
qc.cz(0,1)
qc.ry(np.pi/3 , 0)
qc.rx(np.pi/5, 1)
state = DensityMatrix(qc)
plot_state_hinton(state, title="New Hinton Plot")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.