repo
stringclasses 900
values | file
stringclasses 754
values | content
stringlengths 4
215k
|
|---|---|---|
https://github.com/qiskit-community/qiskit-cold-atom
|
qiskit-community
|
from pprint import pprint
import numpy as np
import matplotlib.pyplot as plt
from qiskit_cold_atom.providers import ColdAtomProvider
# save an account to disk
# ColdAtomProvider.save_account(url = ["url_of_backend_1", "url_of_backend_2"], username="JohnDoe",token="123456")
# load the stored account
provider = ColdAtomProvider.load_account()
print(provider.backends())
spin_device_backend = provider.get_backend("SYNQS_SoPa_backend")
spin_device_backend.status().to_dict()
spin_device_backend.configuration().supported_instructions
from qiskit.circuit import QuantumCircuit, Parameter
import numpy as np
t = Parameter("t")
circuit = QuantumCircuit(1, 1)
circuit.delay(duration = t, unit='s', qarg=0)
circuit.measure(0, 0)
circuit.draw(output='mpl')
# create a list of circuits with variable loading times:
load_times = np.arange(0.1, 15, 2)
circuit_list =[circuit.bind_parameters({t: load_time}) for load_time in load_times]
# send the list of circuits to the backend and execute with 5 shots each
# demo_job = spin_device_backend.run(circuit_list, shots = 5)
job_retrieved = spin_device_backend.retrieve_job(job_id = "20210520_171502_89aec")
print("job status: ", job_retrieved.status())
result = job_retrieved.result()
print(type(result))
outcomes = [result.get_memory(i) for i in range(len(circuit_list))]
atom_numbers = [np.mean(np.array(counts, dtype=float)) for counts in outcomes]
atom_stds = [np.std(np.array(counts, dtype=float)) for counts in outcomes]
import matplotlib.pyplot as plt
plt.errorbar(load_times, atom_numbers, yerr=atom_stds, fmt='x--')
plt.grid(alpha=0.5)
plt.title("loading of atoms in cold atomic device through Qiskit")
plt.xlabel("loading time [s]")
plt.ylabel("atom number in trap [a.u.]")
plt.show()
result.to_dict()
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/qiskit-community/qiskit-cold-atom
|
qiskit-community
|
%load_ext autoreload
%autoreload 2
from qiskit_cold_atom.applications import FermiHubbard1D
# defining the system
system = FermiHubbard1D(
num_sites = 3, # number of lattice sites
particles_up = 1, # number of spin up particles
particles_down = 1, # number of spin down particles
hop_strength = 2., # parameter J tuning the hopping
int_strength = 1, # parameter U tuning the interaction
potential = [1, 0, -1] # parameters mu tuning the local potential
)
from qiskit_cold_atom.fermions.fermion_circuit_solver import FermionicState
# defining the initial state with one spin_up particle in the left site
# and one spin-down particle in the right site
initial_state = FermionicState([[1, 0, 0], [0, 0, 1]])
from qiskit_nature.second_q.operators import FermionicOp
# Observables: Spin-density and particle density at the first site
spin_density = FermionicOp({'+_0 -_0': 1, '+_3 -_3': -1}, num_spin_orbitals=6)
particle_density = FermionicOp({'+_0 -_0': 1, '+_3 -_3': 1}, num_spin_orbitals=6)
import numpy as np
evolution_times = np.linspace(0.1, 5, 40)
from qiskit_cold_atom.applications import FermionicEvolutionProblem
spin_problem = FermionicEvolutionProblem(system, initial_state, evolution_times, spin_density)
particle_problem = FermionicEvolutionProblem(system, initial_state, evolution_times, particle_density)
from qiskit_cold_atom.providers.fermionic_tweezer_backend import FermionicTweezerSimulator
from qiskit_cold_atom.applications import TimeEvolutionSolver
# initializing the fermionic solver
fermionic_backend = FermionicTweezerSimulator(n_tweezers=3)
fermionic_solver = TimeEvolutionSolver(backend = fermionic_backend)
from qiskit import Aer
# initializing the qubit solver with the qasm simulator backend
qubit_backend = Aer.get_backend('qasm_simulator')
mapping = 'bravyi_kitaev'
# mapping = 'jordan_wigner'
# mapping = 'parity'
shallow_qubit_solver = TimeEvolutionSolver(backend = qubit_backend, map_type = mapping, trotter_steps = 1)
deep_qubit_solver = TimeEvolutionSolver(backend = qubit_backend, map_type = mapping, trotter_steps = 6)
spin_vals_fermions = fermionic_solver.solve(spin_problem)
particle_vals_fermions = fermionic_solver.solve(particle_problem)
spin_vals_qubits_shallow = shallow_qubit_solver.solve(spin_problem)
particle_vals_qubits_shallow = shallow_qubit_solver.solve(particle_problem)
spin_vals_qubits_deep = deep_qubit_solver.solve(spin_problem)
particle_vals_qubits_deep = deep_qubit_solver.solve(particle_problem)
import matplotlib.pyplot as plt
plt.rcParams['figure.figsize'] = [9, 6]
plt.rcParams.update({'font.size': 14})
plt.xlabel('evolution time')
plt.ylabel('Spin at site 1')
plt.ylim(-1.1, 1.1)
plt.title('evolution of spin density')
plt.plot(evolution_times, np.real_if_close(spin_vals_qubits_shallow), '--o', color='#d02670', alpha=0.5, label='qubits, 1 trotter step')
plt.plot(evolution_times, np.real_if_close(spin_vals_qubits_deep), '-o', color='#08bdba', alpha=0.8, label='qubits, 6 trotter steps')
plt.plot(evolution_times, np.real_if_close(spin_vals_fermions), '-o', color='#0f62fe', alpha=0.8, label='fermionic backend')
plt.legend()
plt.show()
plt.xlabel('evolution time')
plt.ylabel('Particle number at site 1')
plt.title('evolution of particle density')
plt.plot(evolution_times, particle_vals_qubits_shallow, '--o', color='#d02670', alpha=0.5, label='qubits, 1 trotter step')
plt.plot(evolution_times, particle_vals_qubits_deep, '-o', color='#08bdba', alpha=0.8, label='qubits, 6 trotter steps')
plt.plot(evolution_times, particle_vals_fermions, '-o', color='#0f62fe', alpha=0.8, label='fermionic backend')
plt.legend()
plt.show()
fermion_circuit = spin_problem.circuits(fermionic_backend.initialize_circuit(initial_state.occupations))[-1]
fermion_circuit.measure_all()
qubit_circuit = deep_qubit_solver.construct_qubit_circuits(spin_problem)[-1]
qubit_circuit.measure_all()
fermion_circuit.draw(output='mpl', style="clifford")
from qiskit import transpile
from qiskit.providers.fake_provider import FakeGuadalupe
qubit_device = FakeGuadalupe()
transpiled_circ = transpile(qubit_circuit, qubit_device, optimization_level=3)
transpiled_circ.draw(output='mpl', idle_wires=False, style="clifford")
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/qiskit-community/qiskit-cold-atom
|
qiskit-community
|
import numpy as np
from qiskit import QuantumCircuit
circuit = QuantumCircuit(2)
# initialization to create a 50 - 50 superposition
circuit.h(0)
circuit.h(1)
# measurement
circuit.measure_all()
circuit.draw("mpl", style='clifford')
from qiskit import Aer
from qiskit.visualization import plot_histogram
def bit_counts_to_Lz(counts):
"""transform bitstring counts to collective counts.
Args:
counts: a dict whose keys are the observed integers for the spin
and whose values is the number of observations
Returns:
counts: a dict whose keys are the observed integers for the total observed numbers of up
and whose values is the number of observations
"""
lz_counts = {}
for bitstring, count in counts.items():
measured_label = bitstring.count("1")
if str(measured_label) in lz_counts:
lz_counts[str(measured_label)] += count
else:
lz_counts[str(measured_label)] = count
return lz_counts
qasm_simulator = Aer.get_backend("aer_simulator")
job = qasm_simulator.run(circuit, shots=1000)
counts = job.result().get_counts()
lz_counts_uncorrelated = bit_counts_to_Lz(counts)
plot_histogram(lz_counts_uncorrelated)
circuit = QuantumCircuit(2)
# initialization on x
circuit.h(0)
circuit.x(1)
circuit.cx(0, 1)
# measurement
circuit.measure_all()
circuit.draw("mpl", style='clifford')
job = qasm_simulator.run(circuit, shots=1000)
counts = job.result().get_counts()
counts["00"] = 0
counts["11"] = 0
squeezed_lz_counts = bit_counts_to_Lz(counts)
plot_histogram(squeezed_lz_counts)
from qiskit_cold_atom.providers import ColdAtomProvider
from qiskit_cold_atom.spins.spins_gate_library import OATGate
from qiskit.circuit import Parameter
import numpy as np
provider = ColdAtomProvider()
backend = provider.get_backend("collective_spin_simulator")
qc = QuantumCircuit(1)
alpha = Parameter("α")
beta = Parameter("β")
gamma = Parameter("γ")
qc.rly(np.pi / 2, 0)
qc.append(OATGate(chi=gamma, delta=0, omega=beta), qargs=[0])
qc.rlx(np.pi, 0)
qc.append(OATGate(chi=gamma, delta=0, omega=beta), qargs=[0])
qc.rlx(alpha, 0)
qc.measure_all()
qc.draw("mpl", style='clifford')
# Number of atoms
Nat = 100
# The length of the spin
l = Nat / 2
# Strength of the rotation around x
omegax = 2 * np.pi * 20
# Time of the evolution
time = 15e-3
# Strength of the Lz-squared operator
Lambda = 1.5
chi = Lambda * abs(omegax) / Nat;
alphas = np.array([50, 140]) / 180 * np.pi
circuit = qc.assign_parameters(
{
alpha: np.pi - alphas[0],
beta: omegax * time / 2,
gamma: chi * time / 2,
},
inplace=False,
)
job = backend.run(circuit, shots=1000, spin=Nat / 2)
counts1 = job.result().get_counts()
circuit = qc.assign_parameters(
{
alpha: np.pi - alphas[1],
beta: omegax * time / 2,
gamma: chi * time / 2,
},
inplace=False,
)
job = backend.run(circuit, shots=1000, spin=Nat / 2)
counts2 = job.result().get_counts()
import matplotlib.pyplot as plt
from scipy.special import binom
f, ax = plt.subplots()
obs_num = np.array([int(key) for key in counts1.keys()])
obs_vals = np.array([val for val in counts1.values()])
ax.bar(
obs_num - Nat / 2,
obs_vals / obs_vals.sum(),
align="center",
alpha=0.5,
label="squeezed",
)
obs_num = np.array([int(key) for key in counts2.keys()])
obs_vals = np.array([val for val in counts2.values()])
ax.bar(
obs_num - Nat / 2,
obs_vals / obs_vals.sum(),
align="center",
alpha=0.5,
label="anti-squeezed",
)
# and compare to the binomial distribution;
ks = np.arange(Nat)
pk = binom(Nat, ks) * 0.5 ** ks * 0.5 ** (Nat - ks)
ax.plot(ks - Nat / 2, pk, label="uncorrelated noise", c="C2")
ax.legend()
ax.set_ylabel("Probability")
ax.set_xlabel(r"$L_z$");
t1 = 15e-3
t2 = 25e-3
def mean_var_from_counts(counts):
"""calculate mean and variance from the counts.
Args:
counts: a dict whose keys are the observed integers for the spin
and whose values is the number of observations
Returns:
mean, var: mean and variance of the observed counts
"""
mean, var, count_sum = 0, 0, 0
for k, v in counts.items():
mean += int(k) * v
count_sum += v
mean = mean / count_sum
for k, v in counts.items():
var += (int(k) - mean) ** 2 * v / count_sum
return mean, var
alphas = np.linspace(0, np.pi, 15)
variances_1 = np.zeros(len(alphas))
variances_2 = np.zeros(len(alphas))
for ii in range(len(alphas)):
# first time step
circuit = qc.assign_parameters(
{
alpha: alphas[ii],
beta: omegax * t1 / 2,
gamma: chi * t1 / 2,
},
inplace=False,
)
job = backend.run(circuit, shots=1000, spin=Nat / 2, seed=14)
counts = job.result().get_counts()
mean, var = mean_var_from_counts(counts)
variances_1[ii] = var
# and the second time step
circuit = qc.assign_parameters(
{
alpha: alphas[ii],
beta: omegax * t2 / 2,
gamma: chi * t2 / 2,
},
inplace=False,
)
job = backend.run(circuit, shots=1000, spin=Nat / 2, seed=14)
counts = job.result().get_counts()
mean, var = mean_var_from_counts(counts)
variances_2[ii] = var;
# Import the data from the paper by Strobel et al.
strobel_15_dB = np.array(
[
0.51993068,
10.39861352,
20.5372617,
30.41594454,
40.81455806,
45.49393414,
50.6932409,
56.152513,
60.05199307,
69.93067591,
79.80935875,
90.98786828,
100.08665511,
109.96533795,
120.36395147,
130.24263432,
139.86135182,
150.51993068,
160.13864818,
170.01733102,
180.1559792,
]
)
strobel_15_alpha = np.array(
[
9.27455357,
8.03571429,
6.19419643,
3.54910714,
-0.46875,
-2.27678571,
-4.11830357,
-4.01785714,
-2.94642857,
1.30580357,
4.55357143,
6.99776786,
8.50446429,
9.140625,
10.41294643,
10.546875,
10.64732143,
10.27901786,
9.74330357,
9.40848214,
8.27008929,
]
)
# and the values for 25ms
strobel_25_dB = np.array(
[
0.51993068,
10.39861352,
20.5372617,
30.41594454,
40.81455806,
45.49393414,
50.6932409,
56.152513,
60.05199307,
69.93067591,
79.80935875,
90.98786828,
100.08665511,
109.96533795,
120.36395147,
130.24263432,
139.86135182,
150.51993068,
160.13864818,
170.01733102,
180.1559792,
]
)
strobel_25_alpha = np.array(
[
16.07142857,
15.46875,
14.02901786,
11.71875,
8.40401786,
4.72098214,
2.20982143,
-0.46875,
0.0,
2.74553571,
7.734375,
10.98214286,
13.39285714,
14.89955357,
15.73660714,
16.50669643,
17.00892857,
17.31026786,
17.24330357,
16.77455357,
15.80357143,
]
)
def number_squeezing_factor_to_db(var_CSS, var):
"""Calcululate the squeezing parameter from the observed variance."""
return 10 * np.log10(var / var_CSS)
f, ax = plt.subplots()
ax.set_title("Number Squeezing")
ax.plot(
np.rad2deg(np.pi - alphas),
number_squeezing_factor_to_db(l / 2, variances_1),
"r-",
lw=5,
label="simulated 15ms",
alpha=0.5,
)
ax.plot(strobel_15_dB, strobel_15_alpha, "ro", label="1experiment 5ms", markersize=4)
ax.plot(
np.rad2deg(np.pi - alphas),
number_squeezing_factor_to_db(l / 2, variances_2),
"b-",
lw=5,
label="simulated 25ms",
alpha=0.5,
)
ax.plot(strobel_25_dB, strobel_25_alpha, "bo", label="experiment 25ms", markersize=4)
ax.axhline(y=0, color="g", linestyle="--")
ax.set_ylabel(r"Number Squeezing in $dB$")
ax.set_xlabel(r"tomography angle $\alpha$")
ax.legend();
from qiskit_cold_atom.providers import ColdAtomProvider
from pprint import pprint
# save an account to disk
#provider = ColdAtomProvider.save_account(
# url=[
# "https://qlued.alqor.io/api/v2/singlequdit",
# "https://qlued.alqor.io/api/v2/multiqudit",
# "https://qlued.alqor.io/api/v2/fermions",
# ],
# username="name",
# token="token",
# overwrite=True
#)
# or enable an account in the current session
#provider = ColdAtomProvider.enable_account(
# url=[
# "https://qlued.alqor.io/api/v2/singlequdit",
# "https://qlued.alqor.io/api/v2/multiqudit",
# "https://qlued.alqor.io/api/v2/fermions",
# ],
# username="name",
# token="token",
# overwrite=True
#)
provider = ColdAtomProvider.load_account()
spin_device_backend = provider.get_backend("alqor_singlequdit_simulator")
pprint(spin_device_backend.configuration().supported_instructions)
Nat = 200
l = Nat / 2 # spin length
omegax = 2 * np.pi * 20
t1 = 15e-3
t2 = 25e-3
Lambda = 1.5
chi = Lambda * abs(omegax) / Nat
Ntrott = 15
alphas = np.linspace(0, np.pi, 15)
alpha = Parameter("α")
beta = Parameter("β")
gamma = Parameter("γ")
qc_trott = QuantumCircuit(1, 1)
qc_trott.load_spins(Nat, 0)
qc_trott.rlx(np.pi / 2, 0)
qc_trott.rlz(np.pi / 2, 0)
for ii in range(Ntrott):
qc_trott.rlx(beta, 0)
qc_trott.rlz2(gamma, 0)
qc_trott.rlx(alpha, 0)
qc_trott.measure(0, 0)
qc_trott.draw(output="mpl")
circuit1_list = [
qc_trott.assign_parameters(
{alpha: -a % (2 * np.pi), gamma: chi * t1 / Ntrott, beta: omegax * t1 / Ntrott},
inplace=False,
)
for a in alphas
]
job1 = spin_device_backend.run(circuit1_list, shots=500)
job1.job_id()
job_retrieved1 = spin_device_backend.retrieve_job(job_id=job1.job_id())
print("job status: ", job_retrieved1.status())
circuit2_list = [
qc_trott.assign_parameters(
{alpha: -a % (2 * np.pi), gamma: chi * t2 / Ntrott, beta: omegax * t2 / Ntrott},
inplace=False,
)
for a in alphas
]
job2 = spin_device_backend.run(circuit2_list, shots=500)
job2.job_id()
job_retrieved2 = spin_device_backend.retrieve_job(job_id=job2.job_id())
print("job status: ", job_retrieved2.status())
result1 = job_retrieved1.result()
result2 = job_retrieved2.result()
outcomes1 = [result1.get_memory(i) for i in range(len(circuit1_list))]
outcomes2 = [result2.get_memory(i) for i in range(len(circuit2_list))]
variances_1 = [np.var(np.array(counts1, dtype=float)) for counts1 in outcomes1]
variances_2 = [np.var(np.array(counts2, dtype=float)) for counts2 in outcomes2]
variances_1 = np.array(variances_1)
variances_2 = np.array(variances_2)
f, ax = plt.subplots()
ax.set_title("Number Squeezing")
plt.plot(
np.rad2deg(alphas),
number_squeezing_factor_to_db(l / 2, variances_1),
"r-",
lw=5,
label="simulated 15ms",
alpha=0.5,
)
plt.plot(
np.rad2deg(alphas),
number_squeezing_factor_to_db(l / 2, variances_2),
"b-",
lw=5,
label="simulated 25ms",
alpha=0.5,
)
plt.plot(strobel_15_dB, strobel_15_alpha, "ro", label="15ms", markersize=4)
plt.plot(strobel_25_dB, strobel_25_alpha, "bo", label="25ms", markersize=4)
ax.axhline(y=0, color="g", linestyle="--")
ax.set_ylabel(r"Number Squeezing in $dB$")
ax.set_xlabel(r"tomography angle $\alpha$")
ax.legend()
import qiskit.tools.jupyter
%qiskit_version_table
|
https://github.com/qiskit-community/qiskit-cold-atom
|
qiskit-community
|
import numpy as np
import matplotlib.pyplot as plt
# the experimental parameters
J = np.pi * 134 # hopping parameter in units of hbar
U = 0.7 * J # interaction parameter
Nt_an = 50 # number of time steps for plotting
t_analytical = np.linspace(0, 25, Nt_an) * 1e-3 # evolution times
H_with_int = np.array([[U, -J, -J, 0], [-J, 0, 0, -J], [-J, 0, 0, -J], [0, -J, -J, U]])
H_wo_int = np.array([[0, -J, -J, 0], [-J, 0, 0, -J], [-J, 0, 0, -J], [0, -J, -J, 0]])
psi0 = np.zeros(4) * 1j
psi0[0] = 1.0
from scipy.linalg import expm
psis_wo_int = 1j * np.zeros((4, Nt_an))
psis_w_int = 1j * np.zeros((4, Nt_an))
for i, ti in enumerate(t_analytical):
U_wo = expm(-1j * ti * H_wo_int)
psis_wo_int[:, i] = np.dot(U_wo, psi0)
U_w = expm(-1j * ti * H_with_int)
psis_w_int[:, i] = np.dot(U_w, psi0)
pops_wo = np.abs(psis_wo_int) ** 2
pops_w = np.abs(psis_w_int) ** 2
nR_wo = pops_wo[1, :] + pops_wo[2, :] + 2 * pops_wo[3, :]
nR_w = pops_w[1, :] + pops_w[2, :] + 2 * pops_w[3, :];
# raw values on experiments without interactions from the paper by Murmann et al.
no_int_time = np.array(
[0.0, 0.84951456, 1.52912621, 2.20873786, 3.05825243, 4.0776699, 4.75728155, 5.26699029, 6.28640777, 6.7961165, 7.64563107, 8.32524272, 9.00485437, 9.85436893, 10.53398058, 11.38349515, 12.0631068, 12.74271845, 13.4223301, 14.27184466, 14.95145631, 15.80097087, 16.48058252, 17.16019417, 18.00970874, 18.68932039, 19.53883495, 20.2184466, 21.06796117, 21.74757282, 22.42718447, 23.27669903, 23.95631068, 24.80582524,]
)
no_int_nR = np.array(
[0.07042254, 0.56338028, 1.23943662, 1.43661972, 1.8028169, 1.57746479, 1.22535211, 0.81690141, 0.42253521, 0.21126761, 0.07042254, 0.43661972, 0.73239437, 1.33802817, 1.66197183, 1.66197183, 1.36619718, 0.85915493, 0.6056338, 0.07042254, 0.14084507, 0.42253521, 0.67605634, 1.28169014, 1.36619718, 1.54929577, 1.4084507, 1.07042254, 0.57746479, 0.36619718, 0.1971831, 0.28169014, 0.49295775, 0.92957746,]
)
# raw values on experiments with interactions from the paper by Murmann et al.
with_int_time = np.array(
[-0.16990291, 0.84951456, 1.52912621, 2.03883495, 2.88834951, 3.73786408, 4.41747573, 5.94660194, 5.09708738, 6.62621359, 7.47572816, 8.15533981, 9.00485437, 9.68446602, 10.53398058, 11.21359223, 11.89320388, 12.74271845, 13.4223301, 14.27184466, 14.95145631, 15.63106796, 16.48058252, 17.16019417, 18.00970874, 18.68932039, 19.36893204, 20.2184466, 21.06796117, 21.74757282, 22.42718447, 23.27669903, 23.95631068, 24.63592233, 25.48543689, 26.16504854, 27.01456311, 27.69417476,]
)
with_int_nR = np.array(
[0.06896552, 0.35862069, 1.00689655, 1.35172414, 1.42068966, 1.35172414, 1.28275862, 1.00689655, 0.85517241, 0.56551724, 0.35862069, 0.57931034, 0.8, 0.8, 0.99310345, 1.2, 1.14482759, 0.99310345, 1.46206897, 1.43448276, 1.48965517, 1.07586207, 0.92413793, 0.75862069, 0.28965517, 0.4, 0.60689655, 0.64827586, 1.42068966, 1.35172414, 1.25517241, 1.35172414, 1.06206897, 0.71724138, 0.42758621, 0.28965517, 0.37241379, 0.35862069,]
)
f, (ax1, ax2) = plt.subplots(
2, 1, sharex=True, sharey=True, figsize=(12, 6), constrained_layout=True
)
ax1.plot(no_int_time, no_int_nR, "ro", label="experiment", markersize=4)
ax1.plot(t_analytical * 1e3, nR_wo, "r-", label="analytical", linewidth=4, alpha=0.5)
ax2.plot(with_int_time, with_int_nR, "bo", label="experiment", markersize=4)
ax2.plot(t_analytical * 1e3, nR_w, "b-", label="analytical", linewidth=4, alpha=0.5)
ax1.set_ylabel(r"atoms in right tweezer")
ax2.set_ylabel(r"atoms in right tweezer")
ax2.set_xlabel(r"time (ms)")
# ax2.set_xlim(0, 20)
ax1.set_title(r"Hopping without interactions ($U=0$)")
ax2.set_title(r"Hopping with interactions ($U=0.7*J$)")
ax1.legend()
ax2.legend()
ax1.grid()
ax2.grid()
from qiskit_cold_atom.fermions import FermionSimulator
from qiskit_cold_atom.fermions.fermion_gate_library import FermiHubbard
from qiskit_nature.second_q.operators import FermionicOp
from qiskit.circuit import Parameter
backend = FermionSimulator()
hop_param = Parameter("hop_param")
int_param = Parameter("int_param")
# initialize one spin-up and one spin-down atom in the left tweezer
qc = backend.initialize_circuit([[1, 0], [1, 0]])
# apply a global Fermi-Hubbard gate with interaction
qc.fhubbard(j=[hop_param], u=int_param, mu=[0],modes=range(4))
qc.measure_all()
qc.draw(output="mpl", style="clifford", scale=0.8)
Ntimes = 50
times = np.linspace(0, 25, Ntimes) * 1e-3
# create list of circuits without interaction
circuits_no_int = [qc.assign_parameters({hop_param: J*t, int_param: 0}) for t in times]
# measure the observable from simulated shots
job_no_int = backend.run(circuits_no_int, shots=1000)
# create list of circuits without interaction
circuits_int = [qc.assign_parameters({hop_param: J*t, int_param: U*t}) for t in times]
# measure the observable from simulated shots
job_int = backend.run(circuits_int, shots=1000)
# extract the observable from the measured data
def mean_counts_right(job, N_circs):
"""Compute the average number of number of atoms in the right tweezer."""
result = job.result()
mean_counts = []
for i in range(N_circs):
outcomes = result.get_memory(i)
right_counts = 0
for outcome in outcomes:
outcome_string = "".join(outcome.split())
# select spin-up (idx 1) and spin-down (idx 3) of the right tweezer
right_counts += (int(outcome_string[1]) + int(outcome_string[3]))
mean_counts.append(right_counts/len(outcomes))
return mean_counts
means_no_int = mean_counts_right(job_no_int, Ntimes)
means_int = mean_counts_right(job_int, Ntimes)
f, (ax1, ax2) = plt.subplots(
2, 1, sharex=True, sharey=True, figsize=(12, 6), constrained_layout=True
)
ax1.plot(times * 1e3, means_no_int, "r-", label="qiskit", linewidth=4, alpha=0.5)
ax1.plot(t_analytical * 1e3, nR_wo, "rx", label="analytical", linewidth=4, alpha=0.5)
ax1.plot(no_int_time, no_int_nR, "ro", label="experiment", markersize=4)
ax2.plot(times * 1e3, means_int, "b-", label="qiskit", linewidth=4, alpha=0.5)
ax2.plot(t_analytical * 1e3, nR_w, "bx", label="analytical", linewidth=4, alpha=0.5)
ax2.plot(with_int_time, with_int_nR, "bo", label="experiment", markersize=4)
ax1.set_ylabel(r"atoms in right tweezer")
ax2.set_ylabel(r"atoms in right tweezer")
ax2.set_xlabel(r"time (ms)")
ax1.legend(loc="upper right")
ax2.legend(loc="upper right")
# ax1.set_xlim(-1, 20)
ax1.set_title(r"Hopping without interactions ($U=0$)")
ax2.set_title(r"Hopping with interactions ($U=0.7*J$)")
ax1.grid()
ax2.grid();
from qiskit_cold_atom.providers import ColdAtomProvider
from qiskit.circuit import QuantumCircuit, Parameter
# save an account to disk
#provider = ColdAtomProvider.save_account(
# url=[
# "https://qlued.alqor.io/api/v2/singlequdit",
# "https://qlued.alqor.io/api/v2/multiqudit",
# "https://qlued.alqor.io/api/v2/fermions",
# ],
# username="name",
# token="password",
#)
# or enable an account in the current session
#provider = ColdAtomProvider.enable_account(
# url=[
# "https://qlued.alqor.io/api/v2/singlequdit",
# "https://qlued.alqor.io/api/v2/multiqudit",
# "https://qlued.alqor.io/api/v2/fermions", ],
# username="name",
# token="password",
#)
provider = ColdAtomProvider.load_account()
fermion_device_backend = provider.get_backend("alqor_fermionic_tweezer_simulator")
print(fermion_device_backend.configuration().supported_instructions)
theta_j = Parameter("theta_j")
# the parameters of the experiment
J = np.pi * 134
Ntimes = 15
times = np.linspace(0, 20, Ntimes) * 1e-3
theta_js = -1 * J * times
means = np.zeros(Ntimes)
circuit1 = QuantumCircuit(4)
circuit1.fload(0)
circuit1.fload(2)
circuit1.fhop([theta_j], list(range(0, 4)))
circuit1.measure_all()
circuit1.draw(output="mpl")
circuit1_list = [circuit1.bind_parameters({theta_j: theta % (2 * np.pi)}) for theta in theta_js]
job1 = fermion_device_backend.run(circuit1_list, shots=500)
job_retrieved1 = fermion_device_backend.retrieve_job(job_id=job1.job_id())
print("job status: ", job_retrieved1.status())
means = mean_counts_right(job_retrieved1, Ntimes)
f, ax1 = plt.subplots(1, 1, sharex=True, sharey=True)
ax1.plot(times * 1e3, means, "r-", label="Qiskit", linewidth=4, alpha=0.5)
ax1.plot(no_int_time, no_int_nR, "ro", label="U = 0", markersize=4)
ax1.set_ylabel(r"atoms in right valley")
ax1.set_xlabel(r"time (ms)")
ax1.legend()
ax1.set_xlim(0, 20);
theta_j = Parameter("theta_j")
theta_u = Parameter("theta_u")
# the parameters of the experiment
J = np.pi * 134
U = 0.7 * J
Ntimes = 15
times = np.linspace(0, 20, Ntimes) * 1e-3
theta_js = -1 * J * times
theta_us = U * times
means_int = np.zeros(Ntimes)
Ntrott = 14
circuit2 = QuantumCircuit(8, 8)
circuit2.fload(0)
circuit2.fload(4)
for ii in range(Ntrott):
circuit2.fhop([theta_j], [0, 1, 4, 5])
circuit2.fint(theta_u, list(range(0, 8)))
for idx in [0, 1, 4, 5]:
circuit2.measure(idx, idx)
circuit2.draw(output="mpl", scale=0.6)
circuit2_list = [
circuit2.bind_parameters(
{
theta_j: (theta1 / Ntrott) % (2 * np.pi),
theta_u: (theta2 / Ntrott) % (2 * np.pi),
}
)
for (theta1, theta2) in zip(theta_js, theta_us)
]
job2 = fermion_device_backend.run(circuit2_list, shots=500)
job_retrieved2 = fermion_device_backend.retrieve_job(job_id=job2.job_id())
print("job status: ", job_retrieved2.status())
means_int = mean_counts_right(job_retrieved2, Ntimes)
f, ax2 = plt.subplots(1, 1, sharex=True, sharey=True)
ax2.plot(times * 1e3, means_int, "b.-", label="Qiskit simulation", linewidth=4, alpha=0.5)
ax2.plot(
with_int_time,
with_int_nR,
"bo",
label="experimental data",
markersize=4,
)
ax2.set_ylabel(r"atoms in right valley")
ax2.set_xlabel(r"time (ms)")
ax2.legend()
ax2.set_xlim(0, 20)
import qiskit.tools.jupyter
%qiskit_version_table
|
https://github.com/qiskit-community/qiskit-cold-atom
|
qiskit-community
|
from qiskit import QuantumRegister
from qiskit.circuit import QuantumCircuit, Parameter
from qiskit_cold_atom.spins.spins_gate_library import RydbergFull
from qiskit_cold_atom.spins import SpinSimulator
import numpy as np
import matplotlib.pyplot as plt
Nwires = 2
backend = SpinSimulator()
qc_rabi = QuantumCircuit(QuantumRegister(Nwires, "spin"))
all_modes=range(Nwires)
omega_t = Parameter("ω")
qc_rabi.rlx(omega_t, [0, 1])
qc_rabi.measure_all()
qc_rabi.draw(output='mpl', style='clifford')
phases = np.linspace(0, 2*np.pi, 15)
rabi_list = [
qc_rabi.assign_parameters(
{omega_t: phase},
inplace=False,
)
for phase in phases
]
n_shots = 500
job_rabi = backend.run(rabi_list, shots=n_shots)
result_rabi = job_rabi.result()
counts_rabi = result_rabi.get_counts()
sum_rabi = []
for i, _ in enumerate(phases):
counts_up = 0
for outcome, count in counts_rabi[i].items():
if outcome[0] == "1":
counts_up += count
if outcome[-1] == "1":
counts_up += count
sum_rabi.append(counts_up/n_shots)
f, ax = plt.subplots()
ax.plot(phases, sum_rabi, 'o')
ax.set_xlabel('phase')
ax.set_ylabel('sum of spins up')
Nwires = 2
backend = SpinSimulator()
qc_block = QuantumCircuit(QuantumRegister(Nwires, "spin"))
all_modes=range(Nwires)
omega_t = Parameter("ω")
phi_t = Parameter("φ")
qc_block.rydberg_full(omega=omega_t, delta=0, phi=phi_t, modes=all_modes)
qc_block.measure_all()
qc_block.draw(output='mpl', style='clifford')
phases = np.linspace(0., 2*np.pi, 15)
block_list = [
qc_block.assign_parameters(
{omega_t: phase, phi_t: phase*10},
inplace=False,
)
for phase in phases
]
job_block = backend.run(block_list, shots=n_shots)
result_block = job_block.result()
counts_block = job_block.result().get_counts()
sum_block = []
for i, _ in enumerate(phases):
counts_up = 0
for outcome, count in counts_block[i].items():
if outcome[0] == "1":
counts_up += count
if outcome[-1] == "1":
counts_up += count
sum_block.append(counts_up/n_shots)
f, ax = plt.subplots()
ax.plot(phases, sum_rabi, 'o', label= 'Rabi')
ax.plot(phases, sum_block, 'o', label= 'Blockade')
ax.plot(phases, (1-np.cos(np.sqrt(2)*phases))/2, '-', color = "C1", alpha = 0.5, linewidth = 3, label= 'blocked theory')
ax.legend()
ax.set_xlabel('phase')
ax.set_ylabel('sum of spins up')
Nwires = 2
backend = SpinSimulator()
qc_entangle = QuantumCircuit(QuantumRegister(Nwires, "spin"))
all_modes=range(Nwires)
qc_entangle.rlx(np.pi/2, all_modes)
qc_entangle.rydberg_block(np.pi, modes=all_modes)
qc_entangle.rly(np.pi/2, 0)
qc_entangle.rly(np.pi/2, 1)
qc_entangle.measure_all()
qc_entangle.draw(output='mpl', style='clifford')
job_entangle = backend.run(qc_entangle, shots=500)
result_entangle = job_entangle.result()
print(result_entangle.get_counts())
Nwires = 5
backend = SpinSimulator()
qc_rabi = QuantumCircuit(QuantumRegister(Nwires, "spin"))
all_modes=range(Nwires)
omega_t = Parameter("ω")
qc_rabi.rlx(omega_t, all_modes)
qc_rabi.measure_all()
qc_rabi.draw(output='mpl', style='clifford')
phases = np.linspace(0, 2*np.pi, 15)
rabi_list = [
qc_rabi.assign_parameters(
{omega_t: phase},
inplace=False,
)
for phase in phases
]
job_rabi = backend.run(rabi_list, shots=500)
result_rabi = job_rabi.result()
outcomes_rabi = [result_rabi.get_memory(i) for i in range(len(rabi_list))]
for i, outcome in enumerate(outcomes_rabi):
for j, run in enumerate(outcome):
outcomes_rabi[i][j] = np.array(run.split(' '), dtype = int)
outcomes_rabi = np.array(outcomes_rabi)
means_rabi = outcomes_rabi.mean(axis=1)
f, ax = plt.subplots()
im = ax.pcolormesh(phases, np.arange(Nwires), means_rabi.T)
f.colorbar(im, ax=ax)
ax.set_ylabel('site')
ax.set_xlabel('time')
Nwires = 7
backend = SpinSimulator()
qc_block = QuantumCircuit(QuantumRegister(Nwires, "spin"))
all_modes=range(Nwires)
omega_t = Parameter("ω")
phi_t = Parameter("φ")
qc_block.rydberg_full(omega=omega_t, delta=0, phi=phi_t, modes=all_modes)
qc_block.measure_all()
qc_block.draw(output='mpl', style='clifford')
phases = np.linspace(0, 2*np.pi, 15)
block_list = [
qc_block.assign_parameters(
{omega_t: phase, phi_t: phase*5},
inplace=False,
)
for phase in phases
]
job_block = backend.run(block_list, shots=500)
result_block = job_block.result()
outcomes = [result_block.get_memory(i) for i in range(len(block_list))]
for i, outcome in enumerate(outcomes):
for j, run in enumerate(outcome):
outcomes[i][j] = np.array(run.split(' '), dtype = int)
outcomes = np.array(outcomes)
means_block = outcomes.mean(axis=1)
f, ax = plt.subplots()
im = ax.pcolormesh(phases, np.arange(Nwires), means_block.T)
f.colorbar(im, ax=ax)
ax.set_ylabel('site')
ax.set_xlabel('time')
from qiskit_cold_atom.providers import ColdAtomProvider
from pprint import pprint
#provider = ColdAtomProvider.save_account(
# url=[
# "https://qlued.alqor.io/api/v2/singlequdit",
# "https://qlued.alqor.io/api/v2/multiqudit",
# "https://qlued.alqor.io/api/v2/fermions",
# "https://qlued.alqor.io/api/v2/rydberg",
# ],
# username="name",
# token="token",
# overwrite=True
#)
provider = ColdAtomProvider.load_account()
spin_device_backend = provider.get_backend("alqor_rydberg_simulator")
pprint(spin_device_backend.configuration().supported_instructions)
Nwires = 5
qc_rabi = QuantumCircuit(5)
all_modes=range(Nwires)
omega_t = Parameter("ω")
qc_rabi.rlx( omega_t, all_modes)
qc_rabi.measure_all()
qc_rabi.draw(output='mpl')
phases = np.linspace(0, 2*np.pi,15)
remote_rabi_list = [
qc_rabi.assign_parameters(
{omega_t: phase},
inplace=False,
)
for phase in phases
]
job_remote_rabi = spin_device_backend.run(remote_rabi_list, shots=500)
job_remote_rabi.job_id()
job_rabi_retrieved = spin_device_backend.retrieve_job(job_id=job_remote_rabi.job_id())
print("job status: ", job_rabi_retrieved.status())
result_remote_rabi = job_rabi_retrieved.result()
outcomes = [result_remote_rabi.get_memory(i) for i in range(len(remote_rabi_list))]
for i, outcome in enumerate(outcomes):
for j, run in enumerate(outcome):
outcomes[i][j] = np.array(run.split(' '), dtype = int)
outcomes = np.array(outcomes)
means_remote_rabi = outcomes.mean(axis=1)
f, ax = plt.subplots()
im = ax.pcolormesh(phases,np.arange(5), means_remote_rabi.T)
f.colorbar(im, ax=ax)
ax.set_ylabel('site')
ax.set_xlabel('time')
Nwires = 5
qc2 = QuantumCircuit(5)
all_modes=range(Nwires)
alpha = Parameter("α")
beta = Parameter("β")
qc2.rydberg_full(omega = alpha, delta =0, phi = beta, modes=all_modes)
qc2.measure_all()
qc2.draw(output='mpl')
phases = np.linspace(0, 2*np.pi,15)
circuit2_list = [
qc2.assign_parameters(
{alpha: phase, beta: phase*2},
inplace=False,
)
for phase in phases
]
job2 = spin_device_backend.run(circuit2_list, shots=500)
job2.job_id()
job_retrieved2 = spin_device_backend.retrieve_job(job_id=job2.job_id())
print("job status: ", job_retrieved2.status())
result2 = job_retrieved2.result()
outcomes = [result2.get_memory(i) for i in range(len(circuit2_list))]
for i, outcome in enumerate(outcomes):
for j, run in enumerate(outcome):
outcomes[i][j] = np.array(run.split(' '), dtype = int)
outcomes = np.array(outcomes)
means_1 = outcomes.mean(axis=1)
means_1.shape
f, ax = plt.subplots()
im = ax.pcolormesh(phases,np.arange(5), means_1.T)
f.colorbar(im, ax=ax)
ax.set_ylabel('site')
ax.set_xlabel('time')
import qiskit.tools.jupyter
%qiskit_version_table
|
https://github.com/qiskit-community/qiskit-cold-atom
|
qiskit-community
|
import numpy as np
import matplotlib.pyplot as plt
import time
from qiskit_cold_atom.fermions import FermionSimulator, FfsimBackend
from qiskit_cold_atom.fermions.fermion_gate_library import FermiHubbard
from qiskit_nature.operators.second_quantization import FermionicOp
from qiskit.circuit import Parameter
backend = FermionSimulator()
backend_ffsim = FfsimBackend()
def prep_init_states(dmax: int, with_hole: bool) -> tuple[list, list]:
"""
Prepares a list of initial states for the Fermi-Hubbard model.
Args:
dmax: the maximum distance from the center
with_hole: whether to include a hole in the initial state
Returns:
two lists of initial states starting with spin-up and spin-down, respectively
"""
Nsites = 2 * dmax + 1
# the up state
state_up = [i % 2 for i in range(Nsites)]
state_down = [(i + 1) % 2 for i in range(Nsites)]
if with_hole:
state_up[dmax] = 0
state_down[dmax] = 0
init_state_1 = [state_up, state_down]
init_state_2 = [state_down, state_up]
return init_state_1, init_state_2
dmax = 3
Nsites = 2 * dmax + 1
init_state_1, init_state_2 = prep_init_states(dmax, with_hole=True)
hop_param = Parameter("hop_param")
int_param = Parameter("int_param")
# initialize one spin-up and one spin-down atom in the left tweezer
qc_1 = backend.initialize_circuit(init_state_1)
# apply a global Fermi-Hubbard gate with interaction
qc_1.fhubbard(j=hop_param * np.ones(Nsites - 1), u=int_param, mu=np.zeros(Nsites), modes=range(2*Nsites))
qc_1.measure_all()
# qc_1.draw(output="mpl")
hop_param_down = Parameter("hop_param")
int_param_down = Parameter("int_param")
# initialize one spin-up and one spin-down atom in the left tweezer
qc_2 = backend.initialize_circuit(init_state_2)
# apply a global Fermi-Hubbard gate with interaction
qc_2.fhubbard(
j=hop_param_down * np.ones(Nsites - 1),
u=int_param_down,
mu=np.zeros(Nsites),
modes=range(2 * Nsites),
)
qc_2.measure_all()
circuit_up_init = qc_1.bind_parameters({hop_param: 0, int_param: 0})
job_up_init = backend.run(circuit_up_init, shots=5, num_species=2)
circuit_down_init = qc_2.bind_parameters({hop_param_down: 0, int_param_down: 0})
job_down_init = backend.run(circuit_down_init, shots=5, num_species=2)
def nocc_from_counts(counts: dict[str, int], Nsites: int) -> np.ndarray:
"""
The calculates the occupation from all observed configurations.
Args:
counts: the counts of the observed configurations
Nsites: the number of sites in the system
Returns:
1D array The occupation for each site
"""
nocc_t = np.zeros(Nsites)
Nobs = 0
for occ_string, observations in counts.items():
# get the occupation of each site in the observed configuration
nocc = np.zeros(Nsites)
for site_index in range(Nsites):
nocc[site_index] = int(occ_string[site_index]) + int(occ_string[site_index + Nsites])
# now add the value to the correct time step and with it by the number of observations
Nobs = Nobs + observations
nocc_t = nocc_t + nocc * observations
return nocc_t / Nobs
def squeezed_spin_corr_from_counts(counts: dict[str, int], Nsites: int) -> np.ndarray:
"""
The calculates the spin projection from all observed configurations.
However, we filter out situations with a hole and a doublon in the system.
Args:
counts: the counts of the observed configurations
Nsites: the number of sites in the system
Returns:
1D array The occupation for each site
"""
sz_squeeze = np.zeros(Nsites)
szvar = np.zeros(Nsites)
Nobs = 0
Nobs_var = np.zeros(Nsites)
Nobs = np.zeros(Nsites)
for occ_string, observations in counts.items():
occ_int = [int(occ) for occ in occ_string]
# get the spin of each site in the observed configuration
sz = np.zeros(Nsites)
nocc = np.zeros(Nsites)
for site_index in range(Nsites):
sz[site_index] = 1 / 2 * (occ_int[site_index] - occ_int[site_index + Nsites])
nocc[site_index] = occ_int[site_index] + occ_int[site_index + Nsites]
# now obtain the symmetrized variance
# first for the first site
site_index = 0
if nocc[site_index] == 1 and nocc[site_index + 1] == 1:
szvar[site_index] = (
szvar[site_index] + sz[site_index] * sz[site_index + 1] * observations
)
Nobs_var[site_index] = Nobs_var[site_index] + observations
# then for the last site
site_index = Nsites - 1
if nocc[site_index] == 1 and nocc[site_index - 1] == 1:
szvar[site_index] = (
szvar[site_index] + sz[site_index] * sz[site_index - 1] * observations
)
Nobs_var[site_index] = Nobs_var[site_index] + observations
# and finally for all the other sites
for site_index in range(1,Nsites-1):
if (
nocc[site_index] == 1
and nocc[site_index + 1] == 1
and nocc[site_index - 1] == 1
):
szvar[site_index] = (
szvar[site_index]
+ 1
/ 2
* sz[site_index]
* (sz[site_index + 1] + sz[site_index - 1])
* observations
)
Nobs_var[site_index] = Nobs_var[site_index] + observations
elif (
nocc[site_index] == 1
and nocc[site_index + 1] == 1
and nocc[site_index - 1] == 0
):
szvar[site_index] = (
szvar[site_index] + sz[site_index] * sz[site_index + 1] * observations
)
Nobs_var[site_index] = Nobs_var[site_index] + observations
elif (
nocc[site_index] == 1
and nocc[site_index + 1] == 0
and nocc[site_index - 1] == 1
):
szvar[site_index] = (
szvar[site_index] + sz[site_index] * sz[site_index - 1] * observations
)
Nobs_var[site_index] = Nobs_var[site_index] + observations
sz_squeeze += sz * (nocc == 1) * observations
Nobs += (nocc == 1) * observations
# regularize the observations
var_weight = 1 / Nobs_var
var_weight[np.isinf(var_weight)] = 0
mean_weight = 1 / Nobs
mean_weight[np.isinf(mean_weight)] = 0
# now that we have gone through all observations, we can average
fluc = np.zeros(Nsites)
for site_index in range(Nsites):
if site_index == 0:
fluc[site_index] = 4 * (
szvar[site_index] * var_weight[site_index]
- sz_squeeze[site_index]
* mean_weight[site_index]
* sz_squeeze[site_index + 1]
* mean_weight[site_index + 1]
)
elif site_index == Nsites - 1:
fluc[site_index] = 4 * (
szvar[site_index] * var_weight[site_index]
- sz_squeeze[site_index]
* mean_weight[site_index]
* sz_squeeze[site_index - 1]
* mean_weight[site_index - 1]
)
else:
fluc[site_index] = 4 * (
szvar[site_index] * var_weight[site_index]
- sz_squeeze[site_index]
* mean_weight[site_index]
* (
sz_squeeze[site_index + 1] * mean_weight[site_index + 1]
+ sz_squeeze[site_index - 1] * mean_weight[site_index - 1]
)
/ 2
)
return fluc, Nobs_var, Nobs
noccs_init = np.zeros( Nsites)
corrs_init = np.zeros(Nsites)
counts_1 = job_up_init.result().get_counts()
counts_2 = job_down_init.result().get_counts()
total_counts = counts_1
total_counts.update(counts_2)
nocc = nocc_from_counts(total_counts, Nsites)
corr, _, _ = squeezed_spin_corr_from_counts(total_counts, Nsites)
f, ax = plt.subplots()
ax.plot(np.arange(Nsites) - dmax, nocc, "bo", label="nocc")
ax.plot(np.arange(Nsites) - dmax, corr, "ro", label="corr", alpha = 0.5)
ax.legend()
ax.set_xlabel("site index")
# the experimental parameters
J = 2 * np.pi * 250 # hopping parameter in units of hbar
U = 15 * J # interaction parameter
Ntimes = 8
tmax = 1.5
times = np.linspace(0, tmax, Ntimes) * 1e-3
Nshots = 500
# create list of circuits with interaction
circuits_1 = [qc_1.bind_parameters({hop_param: J * t, int_param: U * t}) for t in times]
# measure the observable from simulated shots
jobs_1 = backend.run(circuits_1, shots=Nshots, num_species=2)
# create list of circuits with interaction
circuits_2 = [qc_2.bind_parameters({hop_param_down: J * t, int_param_down: U * t}) for t in times]
# measure the observable from simulated shots
jobs_2 = backend.run(circuits_2, shots=Nshots, num_species=2)
noccs = np.zeros((Ntimes, Nsites))
corrs = np.zeros((Ntimes, Nsites))
start_time = time.time()
count_list_1 = jobs_1.result().get_counts()
count_list_2 = jobs_2.result().get_counts()
end_time = time.time()
print(f"Duration for of the two jobs: {end_time - start_time} seconds")
for ii in range(Ntimes):
counts_1 = count_list_1[ii]
counts_2 = count_list_2[ii]
total_counts = counts_1
total_counts.update(counts_2)
nocc = nocc_from_counts(total_counts, Nsites)
corr, _,_ = squeezed_spin_corr_from_counts(total_counts, Nsites)
noccs[ii, :] = nocc
corrs[ii, :] = corr
f, [ax1, ax2] = plt.subplots(1, 2, sharey=True)
# color plot of the occupation in a heatmap
velo = J
ax1.pcolor(np.arange(Nsites) - dmax, times * 1e3, corrs, cmap="Reds")
ax1.set_xlabel("time [ms]")
ax1.set_xlabel("site index")
ax1.set_title("Spin")
ax2.pcolor(np.arange(Nsites) - dmax, times * 1e3, noccs, cmap="Blues")
ax2.set_xlabel("site index")
ax2.set_title("Density")
stds_spin = np.zeros(Ntimes)
for ii, corr in enumerate(corrs):
mass_func = corr + 1
mean_position = np.average(np.arange(len(mass_func)), weights=mass_func)
# Calculate the standard deviation of the position
std_position = np.sqrt(
np.average((np.arange(len(mass_func)) - mean_position) ** 2, weights=mass_func)
)
stds_spin[ii] = std_position
stds_density = np.zeros(Ntimes)
for ii, nocc in enumerate(noccs):
# print(nocc)
mass_func = 1 - nocc
mean_position = np.average(np.arange(len(mass_func)), weights=mass_func)
# Calculate the standard deviation of the position
std_position = np.sqrt(
np.average((np.arange(len(mass_func)) - mean_position) ** 2, weights=mass_func)
)
stds_density[ii] = std_position
f, ax = plt.subplots()
ax.plot(times * 1e3, stds_spin, "ro", label="spin")
ax.plot(times * 1e3, stds_density, "bo", label="density")
ax.set_xlabel("time [ms]")
ax.set_ylabel("standard deviation")
ax.legend()
# prepare the jobs
jobs_1_ffsim = backend_ffsim.run(circuits_1, shots=Nshots, num_species=2)
jobs_2_ffsim = backend_ffsim.run(circuits_2, shots=Nshots, num_species=2)
# run them and time it
start_time = time.time()
count_list_1 = jobs_1_ffsim.result().get_counts()
count_list_2 = jobs_2_ffsim.result().get_counts()
end_time = time.time()
print(f"Duration for of the two jobs: {end_time - start_time} seconds")
hop_long = Parameter("hop_long")
int_long = Parameter("int_long")
# initialize one spin-up and one spin-down atom in the left tweezer
qc_long = backend_ffsim.initialize_circuit(init_state_1)
# apply a global Fermi-Hubbard gate with interaction
qc_long.fhubbard(
j=hop_long * np.ones(Nsites - 1), u=int_long, mu=np.zeros(Nsites), modes=range(2 * Nsites)
)
qc_long.measure_all()
tmax = 1 / U
circuit_long = qc_long.bind_parameters({hop_long: J * tmax, int_long: U * tmax})
job_long = backend.run(circuit_long, shots=5, num_species=2)
start_time = time.time()
count_long = job_long.result().get_counts()
end_time = time.time()
print(f"Duration for of the two jobs: {end_time - start_time:.2f} seconds")
time_step = 1/(4*U)
print(f"time step = {time_step*1e3:.2f} ms")
Ntrott = int(tmax / time_step)
print(f"Number of trotter steps: {Ntrott}")
trott_hop = Parameter("trott_hop")
trott_int = Parameter("trott_int")
# initialize one spin-up and one spin-down atom in the left tweezer
qc_trott = backend_ffsim.initialize_circuit(init_state_1)
for ii in range(Ntrott):
# apply a global Fermi-Hubbard gate with interaction
qc_trott.fhop(
j=trott_hop * np.ones(Nsites - 1),
modes=range(2 * Nsites),
)
qc_trott.fint(u=trott_int, modes=range(2 * Nsites))
# apply a global Fermi-Hubbard gate with interaction
qc_trott.measure_all()
circuit_trott = qc_trott.bind_parameters({trott_hop: J * time_step, trott_int: U * time_step})
job_trott = backend_ffsim.run(circuit_trott, shots=5, num_species=2)
start_time = time.time()
count_long = job_long.result().get_counts()
end_time = time.time()
print(f"Duration for of the two jobs: {(end_time - start_time)*1e3:.2f} ms")
import qiskit.tools.jupyter
%qiskit_version_table
|
https://github.com/qiskit-community/qiskit-cold-atom
|
qiskit-community
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""A base class for circuit solvers of cold atomic quantum circuits."""
from abc import ABC, abstractmethod
from typing import List, Optional, Dict, Any
import warnings
import numpy as np
from scipy.sparse import csc_matrix, identity, SparseEfficiencyWarning
from scipy.sparse.linalg import expm
from qiskit import QuantumCircuit
from qiskit.circuit import Gate
from qiskit_nature.second_q.operators import SparseLabelOp
from qiskit_cold_atom.exceptions import QiskitColdAtomError
class BaseCircuitSolver(ABC):
"""An abstract class for circuit solvers of different cold atom types.
By subclassing BaseCircuitSolver one can create circuit solvers for different
types of cold atomic setups such as spin, fermionic, and bosonic setups. All
these subclasses will simulate cold atom quantum circuits by exponentiating
matrices. Therefore, subclasses of BaseCircuitSolver are not intended to solve
large circuits.
"""
def __init__(
self,
shots: Optional[int] = None,
seed: Optional[int] = None,
max_dimension: int = 1e6,
ignore_barriers: bool = True,
):
"""
Args:
shots: amount of shots for the measurement simulation;
if not None, measurements are performed, otherwise no measurements are done.
seed: seed for the RNG for the measurement simulation
max_dimension: The maximum Hilbert space dimension (limited to keep
computation times reasonably short)
ignore_barriers: If true, will ignore barrier instructions
"""
self.shots = shots
self._seed = seed
if self._seed is not None:
np.random.seed(self._seed)
self._max_dimension = max_dimension
self._ignore_barriers = ignore_barriers
self._dim = None
@property
def seed(self) -> int:
"""The seed for the random number generator of the measurement simulation."""
return self._seed
@seed.setter
def seed(self, value: int):
"""Set the seed for the random number generator. This will also update numpy's seed."""
np.random.seed(value)
self._seed = value
@property
def max_dimension(self) -> int:
"""The maximal Hilbert space dimension of the simulation."""
return self._max_dimension
@max_dimension.setter
def max_dimension(self, value: int):
self._max_dimension = value
@property
def ignore_barriers(self) -> bool:
"""Boolean flag that defines how barrier instructions in the circuit are handled."""
return self._ignore_barriers
@property
def dim(self) -> int:
"""Return the dimension set by the last quantum circuit on which the solver was called."""
return self._dim
@ignore_barriers.setter
def ignore_barriers(self, boolean):
self._ignore_barriers = boolean
def __call__(self, circuit: QuantumCircuit) -> Dict[str, Any]:
"""
Performs the simulation of the circuit: Each operator is converted into a sparse matrix
over the basis and is then exponentiated to get the unitary of the gate. All these
unitaries are multiplied to give the total unitary of the circuit. Applying this to the
initial state yields the final state of the circuit, from which we sample a number `shots`
of shots (if specified).
Args:
circuit: A quantum circuit with gates described by second quantized generators
Returns:
output: dict{'unitary' : np.array((dimension, dimension)),
'statevector': np.array((dimension, 1)),
'counts': dict{string: int}}
Raises:
QiskitColdAtomError:
- If one of the generating Hamiltonians is not hermitian which would
lead to non-unitary time evolution.
- If the dimension of the Hilbert space is larger than the max. dimension.
NotImplementedError:
- If ignore_barriers is False.
"""
self.preprocess_circuit(circuit)
if self._dim > self.max_dimension:
raise QiskitColdAtomError(
f"Hilbert space dimension of the simulation ({self._dim}) exceeds the "
f"maximally supported value {self.max_dimension}."
)
# initialize the circuit unitary as an identity matrix
circuit_unitary = identity(self._dim, dtype=complex)
for op in self.to_operators(circuit):
operator_mat = self.operator_to_mat(op)
# check that the operators are hermitian before exponentiating
if (operator_mat.H - operator_mat).count_nonzero() != 0:
raise QiskitColdAtomError("generator of unitary gate is not hermitian!")
# with the next release of qiskit nature this can be replaced with
# if not operator.is_hermitian():
# raise QiskitColdAtomError("generator of unitary gate is not hermitian!")
with warnings.catch_warnings():
warnings.filterwarnings("ignore", category=SparseEfficiencyWarning)
gate_unitary = expm(-1j * operator_mat)
circuit_unitary = gate_unitary @ circuit_unitary
final_state = circuit_unitary @ self.get_initial_state(circuit)
output = {
"unitary": circuit_unitary.toarray(),
"statevector": final_state.toarray().reshape(self._dim),
}
# If shots is specified, simulate measurements on the entire register!
if self.shots is not None:
meas_distr = np.abs(final_state.toarray().reshape(self._dim)) ** 2
if not np.isclose(sum(meas_distr), 1.0):
raise QiskitColdAtomError("Final statevector is not normalized")
meas_results = self.draw_shots(meas_distr)
counts_dict = {
outcome: list(meas_results).count(outcome) for outcome in set(meas_results)
}
output["memory"] = meas_results
output["counts"] = counts_dict
# return empty memory and counts dictionary if no shots are specified
else:
output["memory"] = []
output["counts"] = {}
return output
def to_operators(self, circuit: QuantumCircuit) -> List[SparseLabelOp]:
"""
Convert a circuit to a list of second quantized operators that describe the generators of the
gates applied to the circuit. The SparseLabelOps generating the gates are embedded in the
larger space corresponding to the entire circuit.
Args:
circuit: A quantum circuit with gates described by second quantized generators
Returns:
operators: a list of second-quantized operators, one for each applied gate, in the order
of the gates in the circuit
Raises:
QiskitColdAtomError: - If a given gate can not be converted into a second-quantized operator
- If a gate is applied after a measurement instruction
- If a circuit instruction other than a Gate, measure, load or barrier is given
NotImplementedError: If ignore_barriers is False
"""
operators = []
measured = [False] * circuit.num_qubits
for inst in circuit.data:
name = inst[0].name
qargs = [circuit.qubits.index(qubit) for qubit in inst[1]]
if name == "measure":
for idx in qargs:
measured[idx] = True
elif name == "load":
continue
elif name == "barrier":
if self.ignore_barriers:
continue
raise NotImplementedError
elif isinstance(inst[0], Gate):
try:
second_quantized_op = inst[0].generator
except AttributeError as attribute_error:
raise QiskitColdAtomError(
f"Gate {inst[0].name} has no defined generator"
) from attribute_error
if not isinstance(second_quantized_op, SparseLabelOp):
raise QiskitColdAtomError(
"Gate generator needs to be initialized as qiskit_nature SparseLabelOp"
)
for idx in qargs:
if measured[idx]:
raise QiskitColdAtomError(
f"Simulator cannot handle gate {name} after previous measure instruction."
)
if not second_quantized_op.register_length == len(qargs):
raise QiskitColdAtomError(
f"length of operator labels {second_quantized_op.register_length} must be "
f"equal to length of wires {len(qargs)} the gate acts on"
)
operators.append(
self._embed_operator(second_quantized_op, circuit.num_qubits, qargs)
)
else:
raise QiskitColdAtomError(f"Unknown instruction {name} applied to circuit")
return operators
@abstractmethod
def get_initial_state(self, circuit: QuantumCircuit) -> csc_matrix:
"""Returns the initial state of the quantum circuit as a sparse column vector."""
@abstractmethod
def _embed_operator(
self, operator: SparseLabelOp, num_wires: int, qargs: List[int]
) -> SparseLabelOp:
"""
Turning an operator that acts on the wires given in qargs into an operator
that acts on the entire state space of a circuit. The implementation of the subclasses
depends on whether the operators use sparse labels (SpinOp) or dense labels (FermionicOp).
Args:
operator: SparseLabelOp describing the generating Hamiltonian of a gate
num_wires: number of wires of the space in which to embed the operator
qargs: The wire indices the gate acts on
Returns: A SparseLabelOp acting on the entire quantum register of the Circuit
"""
@abstractmethod
def operator_to_mat(self, operator: SparseLabelOp) -> csc_matrix:
"""Turn a SparseLabelOp into a sparse matrix."""
@abstractmethod
def preprocess_circuit(self, circuit: QuantumCircuit):
"""Pre-process the circuit, e.g. initialize the basis and validate.
This needs to update ``dim``, i.e. the Hilbert space dimension of the solver."""
@abstractmethod
def draw_shots(self, measurement_distribution: List[float]) -> List[str]:
"""
Simulates shots by drawing from a given distribution of measurement outcomes.
Assigning the index of each outcome to the occupations of the modes can be
non-trivial which is why this step needs to be implemented by the subclasses.
Args:
measurement_distribution: A list with the probabilities of the different
measurement outcomes that has the length of the Hilbert space dimension.
Returns:
A list of strings encoding the outcome of the individual shots.
"""
|
https://github.com/qiskit-community/qiskit-cold-atom
|
qiskit-community
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Module to convert cold atom circuits to dictionaries that can be sent to backends."""
from typing import List, Union, Optional
from enum import Enum
from qiskit import QuantumCircuit
from qiskit.providers import BackendV1 as Backend
from qiskit_cold_atom.exceptions import QiskitColdAtomError
class WireOrder(str, Enum):
"""The possible wire orderings for cold atomic circuits.
For example, a sequential register [0, 1, 2, 3, 4, 5] with two species implies that wires 0, 1, 2
are of the same type while an interleaved ordering implies that wires 0, 2, and 4 are of the
same type.
"""
SEQUENTIAL = "sequential"
INTERLEAVED = "interleaved"
class CircuitTools:
"""A class to provide tooling for cold-atomic circuits.
Since all methods are class methods this class does not need to be instantiated. This
class groups tools for cold atomic circuits. It also makes clear the ordering of the
fermionic wires that qiskit works with.
"""
# Qiskit for fermions works with a sequential register definition. For fermionic
# modes with more than on species the circuits will have a corresponding number of
# sequential registers with the same length. For example, a three site system with two
# species will have two sequential registers with three wires each. Other packages may
# use an "interleaved" wire order.
__wire_order__ = WireOrder("sequential")
@classmethod
def validate_circuits(
cls,
circuits: Union[List[QuantumCircuit], QuantumCircuit],
backend: Backend,
shots: Optional[int] = None,
convert_wires: bool = True,
) -> None:
"""
Performs validity checks on circuits against the configuration of the backends. This checks
whether all applied instructions in the circuit are accepted by the backend and whether the
applied gates comply with their respective coupling maps.
Args:
circuits: The circuits that need to be run.
backend: The backend on which the circuit should be run.
shots: The number of shots for each circuit.
convert_wires: If True, the circuits are converted to the wiring convention of the backend.
Raises:
QiskitColdAtomError: If the maximum shot number specified by the backend is exceeded.
QiskitColdAtomError: If the backend does not support an instruction in the circuit.
QiskitColdAtomError: If the width of the circuit is too large.
QiskitColdAtomError: If the circuit has unbound parameters.
"""
if isinstance(circuits, QuantumCircuit):
circuits = [circuits]
# check for number of experiments allowed by the backend
if backend.configuration().max_experiments:
max_circuits = backend.configuration().max_experiments
if len(circuits) > max_circuits:
raise QiskitColdAtomError(
f"{backend.name()} allows for max. {max_circuits} different circuits; "
f"but {len(circuits)} circuits were given"
)
# check for number of individual shots allowed by the backend
if backend.configuration().max_shots and shots:
max_shots = backend.configuration().max_shots
if shots > max_shots:
raise QiskitColdAtomError(
f"{backend.name()} allows for max. {max_shots} shots per circuit; "
f"{shots} shots were requested"
)
config_dict = backend.configuration().to_dict()
for circuit in circuits:
try:
native_gates = {
gate.name: gate.coupling_map for gate in backend.configuration().gates
}
native_instructions = backend.configuration().supported_instructions
except NameError as name_error:
raise QiskitColdAtomError(
"backend needs to be initialized with config file first"
) from name_error
if circuit.num_qubits > backend.configuration().num_qubits:
raise QiskitColdAtomError(
f"{backend.name()} supports circuits with up to "
f"{backend.configuration().num_qubits} wires, but"
f"{circuit.num_qubits} wires were given."
)
# If num_species is specified by the backend, the wires describe different atomic species
# and the circuit's wire count must be a multiple of the number of species.
num_species = None
wire_order = None
if "num_species" in config_dict and convert_wires:
num_species = backend.configuration().num_species
if "wire_order" in config_dict:
wire_order = WireOrder(backend.configuration().wire_order)
else:
wire_order = cls.__wire_order__
if num_species > 1 and circuit.num_qubits % num_species:
raise QiskitColdAtomError(
f"{backend.name()} requires circuits to be submitted with a multiple of "
f"{num_species} wires, but {circuit.num_qubits} wires were given."
)
for inst in circuit.data:
# get the correct wire indices of the instruction with respect
# to the total index of the qubit objects in the circuit
wires = [circuit.qubits.index(qubit) for qubit in inst[1]]
for param in inst[0].params:
try:
float(param)
except TypeError as type_error:
raise QiskitColdAtomError(
"Cannot run circuit with unbound parameters."
) from type_error
# check if instruction is supported by the backend
name = inst[0].name
if name not in native_instructions:
raise QiskitColdAtomError(f"{backend.name()} does not support {name}")
# for the gates, check whether coupling map fits
if name in native_gates:
couplings = native_gates[name]
if num_species and convert_wires:
wires = cls.convert_wire_order(
wires,
convention_from=cls.__wire_order__,
convention_to=wire_order,
num_species=num_species,
num_sites=circuit.num_qubits // num_species,
sort=True,
)
if wires not in couplings:
raise QiskitColdAtomError(
f"coupling {wires} not supported for gate "
f"{name} on {backend.name()}; possible couplings: {couplings}"
)
@classmethod
def circuit_to_data(
cls, circuit: QuantumCircuit, backend: Backend, convert_wires: bool = True
) -> List[List]:
"""Convert the circuit to JSON serializable instructions.
Helper function that converts a QuantumCircuit into a list of symbolic
instructions as required by the Json format which is sent to the backend.
Args:
circuit: The quantum circuit for which to extract the instructions.
backend: The backend on which the circuit should be run.
convert_wires: If True, the circuits are converted to the wiring convention of the backend.
Returns:
A list of lists describing the instructions in the circuit. Each sublist
has three entries the name of the instruction, the wires that the instruction
applies to and the parameter values of the instruction.
"""
instructions = []
config_dict = backend.configuration().to_dict()
num_species = None
wire_order = None
if "num_species" in config_dict:
num_species = backend.configuration().num_species
if "wire_order" in config_dict:
wire_order = WireOrder(backend.configuration().wire_order)
else:
wire_order = cls.__wire_order__
for inst in circuit.data:
name = inst[0].name
wires = [circuit.qubits.index(qubit) for qubit in inst[1]]
if num_species and convert_wires:
wires = cls.convert_wire_order(
wires,
convention_from=cls.__wire_order__,
convention_to=wire_order,
num_species=num_species,
num_sites=circuit.num_qubits // num_species,
sort=True,
)
params = [float(param) for param in inst[0].params]
instructions.append([name, wires, params])
return instructions
@classmethod
def circuit_to_cold_atom(
cls,
circuits: Union[List[QuantumCircuit], QuantumCircuit],
backend: Backend,
shots: int = 60,
convert_wires: bool = True,
) -> dict:
"""
Converts a circuit to a JSon payload to be sent to a given backend.
Args:
circuits: The circuits that need to be run.
backend: The backend on which the circuit should be run.
shots: The number of shots for each circuit.
convert_wires: If True, the circuits are converted to the wiring convention of the backend.
Returns:
A list of dicts.
"""
if isinstance(circuits, QuantumCircuit):
circuits = [circuits]
# validate the circuits against the backend configuration
cls.validate_circuits(
circuits=circuits, backend=backend, shots=shots, convert_wires=convert_wires
)
if "wire_order" in backend.configuration().to_dict():
wire_order = WireOrder(backend.configuration().wire_order)
else:
wire_order = cls.__wire_order__
experiments = {}
for idx, circuit in enumerate(circuits):
experiments["experiment_%i" % idx] = {
"instructions": cls.circuit_to_data(
circuit, backend=backend, convert_wires=convert_wires
),
"shots": shots,
"num_wires": circuit.num_qubits,
"wire_order": wire_order,
}
return experiments
@classmethod
def convert_wire_order(
cls,
wires: List[int],
convention_from: WireOrder,
convention_to: WireOrder,
num_sites: int,
num_species: int,
sort: Optional[bool] = False,
) -> List[int]:
"""
Converts a list of wire indices onto which a gate acts from one convention to another.
Possible conventions are "sequential", where the first num_sites wires denote the
first species, the second num_sites wires denote the second species etc., and "interleaved",
where the first num_species wires denote the first site, the second num_species wires denote
the second site etc.
Args:
wires: Wires onto which a gate acts, e.g. [3, 4, 7, 8].
convention_from: The convention in which "wires" is given.
convention_to: The convention into which to convert.
num_sites: The total number of sites.
num_species: The number of different atomic species.
sort: If true, the returned list of indices is sorted in ascending order.
Raises:
QiskitColdAtomError: If the convention to and from is not supported.
Returns:
A list of wire indices following the convention_to.
"""
if (convention_to or convention_from) not in WireOrder:
raise QiskitColdAtomError(
f"Wire order conversion from {convention_from} to {convention_to}"
f" is not supported."
)
new_wires = None
if convention_from == convention_to:
new_wires = wires
if convention_from == WireOrder.SEQUENTIAL and convention_to == WireOrder.INTERLEAVED:
new_wires = [idx % num_sites * num_species + idx // num_sites for idx in wires]
elif convention_from == WireOrder.INTERLEAVED and convention_to == WireOrder.SEQUENTIAL:
new_wires = [idx % num_species * num_sites + idx // num_species for idx in wires]
if sort:
return sorted(new_wires)
else:
return new_wires
|
https://github.com/qiskit-community/qiskit-cold-atom
|
qiskit-community
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
r"""
.. image:: ../images/qiskit_cold_atom_logo_with_text.svg
:alt: Missing Logo
==================================================
Qiskit Cold Atom module (:mod:`qiskit_cold_atom`)
==================================================
.. currentmodule:: qiskit_cold_atom
The Qiskit Cold Atom module provides functionality to describe quantum systems of trapped cold atoms
in a gate- and circuit-based framework.
Traditionally, each wire in a quantum circuit represents one qubit as the fundamental unit of information
processing. Here, we extend this concept and allow wires to represent individual internal states of
trapped cold atoms. This currently covers two settings, one for fermionic modes and one for spin
modes.
In a fermionic setting, each wire of a quantum circuit represents an abstract fermionic mode in second
quantization which can either be occupied (1) or empty (0). Such systems are realized experimentally by
individual fermionic atoms trapped in arrays of optical tweezers. Circuit instructions and backends
to interact with and simulate such circuits are given by the :mod:`qiskit_cold_atom.fermions` module.
In a spin setting, each wire of a quantum circuit represents a quantum mechanical spin of a given length
:math:`S`. Upon measurement, each spin is measured in one of its :math:`2S+1` internal basis states
labelled :math:`0` to :math:`2S`, thus it can be thought of as a qudit with dimension :math:`d = 2S+1`.
This setting describes the collective spin of bosonic atoms trapped in a Bose-Einstein-condensate.
Circuit instructions and backends to interact with and simulate such circuits are provided by the
:mod:`qiskit_cold_atom.spins` module.
The quantum circuits that these systems can implement thus utilize a fundamentally different form of
quantum information processing compared to qubits. Therefore, the typical qubit gates can not be applied
to these circuits. Instead, the fermions and spin modules define their own gate sets which are defined
by their second-quantized Hamiltonians that generate the unitary gate. Note that loading the
:mod:`qiskit_cold_atom.fermions` or :mod:`qiskit_cold_atom.spins` module will decorate the
:class:`QuantumCircuit` class in Qiskit by adding methods to call pre-defined fermionic and spin gates,
respectively.
To enable the control of real quantum hardware, the :mod:`qiskit_cold_atom.providers`
module contains a provider which enables access to cold atomic device backends.
The top-level classes and submodules of qiskit_cold_atom are:
.. autosummary::
:toctree: ../stubs/
:nosignatures:
QiskitColdAtomError
Submodules
==========
.. autosummary::
:toctree:
applications
fermions
providers
spins
"""
from functools import wraps
from qiskit import QuantumCircuit
from qiskit_cold_atom.exceptions import QiskitColdAtomError
def add_gate(func):
"""Decorator to add a gate method to the QuantumCircuit class"""
@wraps(func)
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
setattr(QuantumCircuit, func.__name__, wrapper)
return func
__version__ = "0.1.0"
__all__ = ["__version__", "QiskitColdAtomError", "add_gate"]
|
https://github.com/qiskit-community/qiskit-cold-atom
|
qiskit-community
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Class that holds a fermionic time-evolution problem."""
from typing import List, Union
from qiskit import QuantumCircuit
from qiskit_nature.second_q.operators import FermionicOp
from qiskit_cold_atom.fermions.fermionic_state import FermionicState
from qiskit_cold_atom.fermions.fermionic_basis import FermionicBasis
from qiskit_cold_atom.fermions.fermion_gate_library import FermionicGate
from qiskit_cold_atom.exceptions import QiskitColdAtomError
from qiskit_cold_atom.applications.fermi_hubbard import FermionicLattice
class FermionicEvolutionProblem:
"""
Problem class corresponding to evaluating an observable of a fermionic system after a time
evolution under a hamiltonian from an initial state in an occupation number representation.
"""
def __init__(
self,
system: FermionicLattice,
initial_state: FermionicState,
evolution_times: Union[float, List[float]],
observable: FermionicOp,
):
"""
Initialize a fermionic time evolution problem.
Args:
system: The fermionic system under which the initial state will evolve.
initial_state: The fermionic state at time t=0.
evolution_times: List of times (or single time) after which the observable is measured.
observable: The observable to measure after the time evolution, given as a FermionicOp.
The observable must be diagonal in the fermionic occupation number basis.
Raises:
QiskitColdAtomError: - If the sizes of the system, initial state and the observable
do not match.
- If the observables is not diagonal in the fermionic occupation number
basis
"""
if system.size != initial_state.sites:
raise QiskitColdAtomError(
f"The size of the system {system.size} does not match "
f"the size of the initial state {initial_state.sites}."
)
if 2 * system.size != observable.register_length:
raise QiskitColdAtomError(
f"The fermionic modes of the system {2*system.size} do not match "
f"the size of the observable {observable.register_length}."
)
# check if matrix is diagonal
# can later be replaced when the FermionicOp from qiskit-nature has its own .to_matrix() method
basis = FermionicBasis.from_fermionic_op(observable)
observable_mat = FermionicGate.operator_to_mat(observable, num_species=1, basis=basis)
if list(observable_mat.nonzero()[0]) != list(observable_mat.nonzero()[1]):
raise QiskitColdAtomError(
"The fermionic observable needs to be diagonal in the computational basis, "
"as measuring general, non-diagonal observables is not yet implemented for "
"fermionic backends. This requires non-trivial basis transformations that "
"are in general difficult to find and depend on the backend's native gate set."
)
self._system = system
self._initial_state = initial_state
self._evolution_times = evolution_times
self._observable = observable
@property
def system(self) -> FermionicLattice:
"""Return the system of the problem."""
return self._system
@property
def initial_state(self) -> FermionicState:
"""Return the initial state of the system."""
return self._initial_state
@property
def evolution_times(self) -> List[float]:
"""Return the evolution times to simulate."""
return self._evolution_times
@property
def observable(self) -> FermionicOp:
"""Return the observable as a FermionicOp."""
return self._observable
def circuits(self, initial_state: QuantumCircuit) -> List[QuantumCircuit]:
"""
The problem embedded in a quantum circuit.
Args:
initial_state: A quantum circuit which corresponds to the initial state for the
time-evolution problem.
Return:
A list of quantum circuits. Circuit :math:`i` is a single instruction which
corresponds to :math:`exp(-i*H*t_i)` where :math:`t_i` is the time of the
the ith evolution time.
"""
circuits = []
for time in self.evolution_times:
circ = QuantumCircuit(initial_state.num_qubits)
circ.compose(initial_state, inplace=True)
circ.compose(self.system.to_circuit(time), inplace=True)
circuits.append(circ)
return circuits
|
https://github.com/qiskit-community/qiskit-cold-atom
|
qiskit-community
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Module to build a Fermi-Hubbard problem."""
from abc import ABC, abstractmethod
from typing import List
from qiskit import QuantumCircuit
from qiskit_nature.second_q.operators import FermionicOp
from qiskit_cold_atom.fermions.fermion_circuit_solver import FermionicBasis
from qiskit_cold_atom.fermions.fermion_gate_library import FermiHubbard
from qiskit_cold_atom.exceptions import QiskitColdAtomError
class FermionicLattice(ABC):
"""Abstract base fermionic lattice."""
@property
@abstractmethod
def size(self) -> int:
"""The number of lattice sites of the system."""
@abstractmethod
def to_fermionic_op(self) -> FermionicOp:
"""Creates the Hamiltonian of the lattice in second quantization.
Returns:
The Hamiltonian as a FermionicOp.
"""
@abstractmethod
def to_circuit(self, time: float = 1.0) -> QuantumCircuit:
"""
Wrap the generator of the system in a QuantumCircuit.
Args:
time: Duration of the time evolution.
Returns:
A quantum circuit which corresponds to the time-evolved Hamiltonian.
"""
class FermiHubbard1D(FermionicLattice):
"""Describes a one-dimensional Fermi-Hubbard model with open boundary conditions."""
def __init__(
self,
num_sites: int,
particles_up: int,
particles_down: int,
hop_strength: float,
int_strength: float,
potential: List[float],
):
r"""
Initialize a one-dimensional fermi-hubbard system. In second quantization this system is
described by the Hamiltonian
:math:`H = \sum_{i=1,\sigma}^{L-1} - J_i (f^\dagger_{i,\sigma} f_{i+1,\sigma} +
f^\dagger_{i+1,\sigma} f_{i,\sigma}) + U \sum_{i=1}^{L} n_{i,\uparrow} n_{i,\downarrow}
+ \sum_{i=1,\sigma}^{L} \mu_i n_{i,\sigma}`
Args:
num_sites: number of lattice sites in the 1D chain.
particles_up: total number of spin-up particles in the lattice
particles_down: total number of spin-down particles in the lattice
hop_strength: strength of hopping between sites
int_strength: strength of the local interaction
potential: list of local phases, must be on length num_wires
Raises:
QiskitColdAtomError: if the length of the potential does not match the system size.
"""
# pylint: disable=invalid-name
self._size = num_sites
self.particles_up = particles_up
self.particles_down = particles_down
self.J = hop_strength
self.U = int_strength
self.basis = FermionicBasis(self.size, n_particles=[self.particles_up, self.particles_down])
if not len(potential) == self.size:
raise QiskitColdAtomError(
f"The length of the potentials {len(potential)} must match system size {self.size}"
)
self.mu = potential
@property
def size(self) -> int:
"""Return the number of sites of the problem."""
return self._size
def to_fermionic_op(self) -> FermionicOp:
"""Construct the hamiltonian of the lattice as a FermionicOp.
Returns:
A FermionicOp defining the systems Hamiltonian
"""
operator_labels = {}
# add hopping terms
for idx in range(self.size - 1):
right_to_left_up = f"+_{idx} -_{idx+1}"
operator_labels[right_to_left_up] = -self.J
left_to_right_up = f"-_{idx} +_{idx+1}"
operator_labels[left_to_right_up] = self.J
right_to_left_down = f"+_{self.size + idx} -_{self.size + idx+1}"
operator_labels[right_to_left_down] = -self.J
left_to_right_down = f"-_{self.size + idx} +_{self.size + idx+1}"
operator_labels[left_to_right_down] = self.J
# add interaction terms
for idx in range(self.size):
opstring = f"+_{idx} -_{idx} +_{self.size + idx} -_{self.size + idx}"
operator_labels[opstring] = self.U
# add potential terms
for idx in range(self.size):
op_up = f"+_{idx} -_{idx}"
operator_labels[op_up] = self.mu[idx]
op_down = f"+_{self.size + idx} -_{self.size + idx}"
operator_labels[op_down] = self.mu[idx]
return FermionicOp(operator_labels, num_spin_orbitals=2 * self.size)
def to_circuit(self, time: float = 1.0) -> QuantumCircuit:
"""
Wrap the generator of the system in a QuantumCircuit.
Args:
time: Duration of the time evolution.
Returns:
A quantum circuit which corresponds to the time-evolved Hamiltonian.
"""
circ = QuantumCircuit(2 * self.size)
circ.append(
FermiHubbard(
num_modes=2 * self.size,
j=[self.J * time] * (self.size - 1),
u=self.U * time,
mu=[mu_i * time for mu_i in self.mu],
),
qargs=range(2 * self.size),
)
return circ
|
https://github.com/qiskit-community/qiskit-cold-atom
|
qiskit-community
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""A solver for time-evolution problems."""
from typing import List
from qiskit_nature.second_q.operators import FermionicOp
from qiskit_nature.second_q.mappers import (
JordanWignerMapper,
BravyiKitaevMapper,
ParityMapper,
)
from qiskit import QuantumRegister
from qiskit import QuantumCircuit
from qiskit.algorithms import TimeEvolutionProblem
from qiskit.algorithms.time_evolvers import TrotterQRTE
from qiskit.quantum_info import Statevector
from qiskit_cold_atom.applications.fermionic_evolution_problem import (
FermionicEvolutionProblem,
)
from qiskit_cold_atom.fermions.base_fermion_backend import BaseFermionBackend
class TimeEvolutionSolver:
"""
Solver class that solves time evolution problem by either analog simulation on fermionic
hardware or trotterized time evolution on qubit hardware. The computation that this time
evolution solver will do depends on the type of the backend.
"""
MAPPER_DICT = {
"bravyi_kitaev": BravyiKitaevMapper(),
"jordan_wigner": JordanWignerMapper(),
"parity": ParityMapper(),
}
def __init__(
self,
backend,
map_type: str = None,
trotter_steps: int = None,
shots: int = 1000,
):
"""
Initialize a time evolution solver
Args:
backend: The backend on which to execute the problem, may be qubit or fermionic.
map_type: The fermion-to-qubit mapping required if a qubit backend is given
trotter_steps: The amount of trotter steps to approximate time evolution on
qubit backends
shots: number of measurements taken of the constructed circuits
"""
self.backend = backend
self.map_type = map_type
self.trotter_steps = trotter_steps
self.shots = shots
def solve(self, problem: FermionicEvolutionProblem) -> List[float]:
"""Solve the problem using the provided backend
Args:
problem: The FermionicEvolutionProblem to solve.
Returns:
A list of expectation values of the observable of the problem. This list has the
same length as the list of times for which to compute the time evolution.
"""
if isinstance(self.backend, BaseFermionBackend):
qc_load = self.backend.initialize_circuit(problem.initial_state.occupations)
circuits = problem.circuits(qc_load)
observable_evs = self.backend.measure_observable_expectation(
circuits, problem.observable, self.shots
)
else:
# use qubit pipeline
circuits = self.construct_qubit_circuits(problem)
mapper = self.MAPPER_DICT[self.map_type]
qubit_observable = mapper.map(problem.observable)
observable_evs = [
Statevector(qc).expectation_value(qubit_observable) for qc in circuits
]
return observable_evs
def construct_qubit_circuits(self, problem: FermionicEvolutionProblem) -> List[QuantumCircuit]:
"""Convert the problem to a trotterized qubit circuit using the specified map_type
Args:
problem: The fermionic evolution problem specifying the system, evolution-time
and observable to be measured
Returns:
a list of quantum circuits that simulate the time evolution.
There is one circuit for each evolution time specified in the problem'
"""
psi_0 = problem.initial_state
system = problem.system
hamiltonian = system.to_fermionic_op()
mapper = self.MAPPER_DICT[self.map_type]
circuits = []
# construct circuit of initial state:
label = {f"+_{i}": 1.0 for i, bit in enumerate(psi_0.occupations_flat) if bit}
bitstr_op = FermionicOp(label, num_spin_orbitals=len(psi_0.occupations_flat))
qubit_op = mapper.map(bitstr_op)[0]
init_circ = QuantumCircuit(QuantumRegister(qubit_op.num_qubits, "q"))
for i, pauli_label in enumerate(qubit_op.paulis.to_labels()[0][::-1]):
if pauli_label == "X":
init_circ.x(i)
elif pauli_label == "Y":
init_circ.y(i)
elif pauli_label == "Z":
init_circ.z(i)
for time in problem.evolution_times:
# map fermionic hamiltonian to qubits
qubit_hamiltonian = mapper.map(hamiltonian)
# construct trotterization circuits
evolution_problem = TimeEvolutionProblem(qubit_hamiltonian, time, init_circ)
trotter_qrte = TrotterQRTE(num_timesteps=self.trotter_steps)
evolved_state = trotter_qrte.evolve(evolution_problem).evolved_state
circuits.append(evolved_state)
return circuits
|
https://github.com/qiskit-community/qiskit-cold-atom
|
qiskit-community
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Module for cold-atom fermion backends."""
from abc import ABC
from typing import Union, List, Optional
import numpy as np
from qiskit.providers import BackendV1 as Backend
from qiskit import QuantumCircuit
from qiskit_nature.second_q.operators import FermionicOp
from qiskit_cold_atom.fermions.fermion_gate_library import LoadFermions
from qiskit_cold_atom.fermions.fermion_circuit_solver import FermionCircuitSolver
from qiskit_cold_atom.fermions.fermionic_state import FermionicState
from qiskit_cold_atom.exceptions import QiskitColdAtomError
class BaseFermionBackend(Backend, ABC):
"""Abstract base class for fermionic tweezer backends."""
def initialize_circuit(self, occupations: Union[List[int], List[List[int]]]):
"""
Initialize a fermionic quantum circuit with the given occupations.
Args:
occupations: List of occupation numbers. When ``List[int]`` is given, the occupations
correspond to the number of indistinguishable fermionic particles in each mode,
e.g. ``[0, 1, 1, 0]`` implies that sites one and two are occupied by a fermion.
When ``List[List[int]]`` is given, the occupations describe the number of particles in
fermionic modes with different (distinguishable) species of fermions. Each
inner list gives the occupations of one fermionic species.
Returns:
circuit: Qiskit QuantumCircuit with a quantum register for each fermionic species
initialized with the ``load`` instructions corresponding to the given occupations
Raises:
QiskitColdAtomError: If occupations do not match the backend
"""
try:
backend_size = self.configuration().to_dict()["n_qubits"]
except NameError as name_error:
raise QiskitColdAtomError(
f"Number of tweezers not specified for {self.name()}"
) from name_error
initial_state = FermionicState(occupations)
n_wires = initial_state.sites * initial_state.num_species
if n_wires > backend_size:
raise QiskitColdAtomError(
f"{self.name()} supports up to {backend_size} sites, {n_wires} were given"
)
# if num_species is specified by the backend, the wires describe different atomic species
# and the circuit must exactly match the expected wire count of the backend.
if "num_species" in self.configuration().to_dict().keys():
num_species = self.configuration().num_species
if num_species > 1 and n_wires < self.configuration().num_qubits:
raise QiskitColdAtomError(
f"{self.name()} requires circuits with exactly "
f"{self.configuration().num_qubits} wires, but an initial occupation of size "
f"{n_wires} was given."
)
from qiskit.circuit import QuantumRegister
if initial_state.num_species > 1:
registers = []
for i in range(initial_state.num_species):
registers.append(QuantumRegister(initial_state.sites, f"spin_{i}"))
circuit = QuantumCircuit(*registers)
else:
circuit = QuantumCircuit(QuantumRegister(initial_state.sites, "fer_mode"))
for i, occupation_list in enumerate(initial_state.occupations):
for j, occ in enumerate(occupation_list):
if occ:
circuit.append(LoadFermions(), qargs=[i * initial_state.sites + j])
return circuit
def measure_observable_expectation(
self,
circuits: Union[QuantumCircuit, List[QuantumCircuit]],
observable: FermionicOp,
shots: int,
seed: Optional[int] = None,
num_species: int = 1,
get_variance: bool = False,
):
"""Measure the expectation value of an observable in a state prepared by a given quantum circuit
that uses fermionic gates. Measurements are added to the entire register if they are not yet
applied in the circuit.
Args:
circuits: QuantumCircuit applying gates with fermionic generators
observable: A FermionicOp describing an observable of which the expectation value is sampled
shots: Number of measurement shots taken in case the circuit has measure instructions
seed: seed for the random number generator of the measurement simulation
num_species: number of different fermionic species described by the circuits
get_variance: If True, also returns an estimate of the variance of the observable
Raises:
QiskitColdAtomError: if the observable is non-diagonal
Returns:
observable_ev: List of the measured expectation values of the observables in given circuits
variance: List of the estimated variances of of the observables (if get_variance is True)
"""
if isinstance(circuits, QuantumCircuit):
circuits = [circuits]
observable_evs = [0] * len(circuits)
observable_vars = [0] * len(circuits)
for idx, circuit in enumerate(circuits):
# check whether the observable is diagonal in the computational basis.
solver = FermionCircuitSolver(num_species=2)
solver.preprocess_circuit(circuit)
observable_mat = solver.operator_to_mat(observable)
if list(observable_mat.nonzero()[0]) != list(observable_mat.nonzero()[1]):
raise QiskitColdAtomError(
"Measuring general observables that are non-diagonal in the "
"computational basis is not yet implemented for "
"fermionic backends. This requires non-trivial basis "
"transformations that are in general difficult to find and "
"depend on the backend's native gate set."
)
circuit.remove_final_measurements()
circuit.measure_all()
# pylint: disable=unexpected-keyword-arg
job = self.run(circuit, shots=shots, seed=seed, num_species=num_species)
counts = job.result().get_counts()
for bitstring in counts:
# Extract the index of the measured count-bitstring in the fermionic basis.
# In contrast to qubits, this is not trivial and requires an additional step.
ind = solver.basis.get_index_of_measurement(bitstring)
# contribution to the operator estimate of this outcome
p = counts[bitstring] / shots
observable_evs[idx] += p * observable_mat[ind, ind].real
if get_variance:
# contribution to the variance of the operator
observable_vars[idx] += (
np.sqrt(p * (1 - p) / shots) * observable_mat[ind, ind]
) ** 2
if get_variance:
return observable_evs, observable_vars
else:
return observable_evs
def draw(self, qc: QuantumCircuit, **draw_options):
"""Modified circuit drawer to better display atomic mixture quantum circuits.
Note that in the future this method may be modified and tailored to fermionic quantum circuits.
Args:
qc: The quantum circuit to draw.
draw_options: Key word arguments for the drawing of circuits.
"""
qc.draw(**draw_options)
|
https://github.com/qiskit-community/qiskit-cold-atom
|
qiskit-community
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Module to describe fermionic states in occupation number basis"""
from typing import List, Union
import warnings
import numpy as np
from qiskit import QuantumCircuit
from qiskit_cold_atom.exceptions import QiskitColdAtomError
class FermionicState:
"""Fermionic states in an occupation number representation."""
def __init__(self, occupations: Union[List[int], List[List[int]]]):
"""Create a :class:`FermionicState` from the given occupations.
Args:
occupations: List of occupation numbers. When List[int] is given, the occupations
correspond to the number of indistinguishable fermionic particles in each mode,
e.g. [0, 1, 1, 0] implies that sites one and two are occupied by a fermion.
When List[List[int]] is given, the occupations describe the number of particles in
fermionic modes with different (distinguishable) species of fermions. Each
inner list gives the occupations of one fermionic species.
Raises:
QiskitColdAtomError:
- If the inner lists do not have the same length
- If the occupations are not 0 or 1
"""
if isinstance(occupations[0], (int, np.integer)):
occupations = [occupations]
self._sites = len(occupations[0])
self._occupations = occupations
self._num_species = len(occupations)
self._occupations_flat = []
for occs in self.occupations:
self._occupations_flat += occs
for occs in self.occupations[0:]:
if len(occs) != self._sites:
raise QiskitColdAtomError(
f"All occupations of different fermionic species must have "
f"same length, received {self.occupations[0]} and {occs}."
)
for n in occs:
if n not in (0, 1):
raise QiskitColdAtomError(f"Fermionic occupations must be 0 or 1, got {n}.")
@property
def occupations(self) -> List[List[int]]:
"""Return the occupation number of each fermionic mode."""
return self._occupations
@property
def occupations_flat(self) -> List[int]:
"""Return the occupations of each fermionic mode in a flat list."""
return self._occupations_flat
@property
def sites(self) -> int:
"""Return the number of fermionic sites."""
return self._sites
@property
def num_species(self) -> int:
"""Return the number of species of fermions, e.g. 2 for spin up/down systems."""
return self._num_species
def __str__(self):
output = ""
for i in range(self.num_species):
output += "|" + str(self.occupations[i])[1:-1] + ">"
return output
@classmethod
def from_total_occupations(cls, occupations: List[int], num_species: int) -> "FermionicState":
"""
Create a fermionic state from a single (flat) list of total occupations.
Args:
occupations: a list of occupations of all fermionic modes, e.g. [0, 1, 1, 0, 1, 0].
num_species: number of fermionic species. If > 1, the total occupation list is cast
into a nested list where each inner list describes one fermionic species. In the
above example, for num_species = 2, this becomes
FermionicState([[0, 1, 1], [0, 1, 0]]).
Returns:
A fermionic state initialized with the given input.
Raises:
QiskitColdAtomError: If the length of occupations is not a multiple of num_species.
"""
if len(occupations) % num_species != 0:
raise QiskitColdAtomError(
"The state must have a number of occupations that is a multiple of the"
"number of fermionic species."
)
sites = int(len(occupations) / num_species)
return cls(np.reshape(occupations, (num_species, sites)).tolist())
@classmethod
def initial_state(cls, circuit: QuantumCircuit, num_species: int = 1) -> "FermionicState":
"""
Create a fermionic state from a quantum circuit that uses the `LoadFermion` instruction.
This instruction must be the first instructions of the circuit and no further LoadFermion
instruction can be applied, even after other instructions such as gates have been applied.
Args:
circuit: a quantum circuit with LoadFermions instructions that initialize fermionic
particles.
num_species: number of different fermionic species, e.g. 1 for a single
type of spinless fermions (default), 2 for spin-1/2 fermions etc.
Returns:
A FermionicState initialized from the given circuit.
Raises:
QiskitColdAtomError:
- If the number of wires in the circuit is not a multiple of num_species,
- If LoadFermions instructions come after other instructions.
"""
if num_species > 1:
if circuit.num_qubits % num_species != 0:
raise QiskitColdAtomError(
"The circuit must have a number of wires that is a multiple of the"
"number of fermionic species."
)
occupations = [0] * circuit.num_qubits
gates_applied = [False] * circuit.num_qubits
if not circuit.data[0][0].name == "load":
warnings.warn(
"No particles have been initialized, the circuit will return a trivial result."
)
# check that there are no more 'LoadFermions' instructions
for instruction in circuit.data:
qargs = [circuit.qubits.index(qubit) for qubit in instruction[1]]
if instruction[0].name == "load":
for idx in qargs:
if gates_applied[idx]:
raise QiskitColdAtomError(
f"State preparation instruction in circuit after gates on wire {idx}"
)
occupations[idx] = 1
else:
for idx in qargs:
gates_applied[idx] = True
return cls.from_total_occupations(occupations, num_species)
|
https://github.com/qiskit-community/qiskit-cold-atom
|
qiskit-community
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Module to simulate fermionic circuits."""
from typing import List, Tuple, Optional
import numpy as np
from scipy.sparse import csc_matrix
from qiskit import QuantumCircuit
from qiskit_nature.second_q.operators import FermionicOp
from qiskit_cold_atom.base_circuit_solver import BaseCircuitSolver
from qiskit_cold_atom.exceptions import QiskitColdAtomError
from qiskit_cold_atom.fermions.fermionic_state import FermionicState
from qiskit_cold_atom.fermions.fermionic_basis import FermionicBasis
from qiskit_cold_atom.fermions.fermion_gate_library import FermionicGate
class FermionCircuitSolver(BaseCircuitSolver):
"""
Numerically simulate fermionic systems by exactly computing the time
evolution under unitary operations generated by fermionic Hamiltonians.
"""
def __init__(
self,
shots: Optional[int] = None,
seed: Optional[int] = None,
num_species: int = 1,
):
"""
Args:
shots: amount of shots for the measurement simulation;
if not None, measurements are performed
seed: seed for the RNG for the measurement simulation
num_species: number of different fermionic species, defaults to 1 for a single type of
(spinless) fermions, 2 for spin-1/2 fermions etc. If > 1, the solver will check for
conservation of the particle number per fermionic species in order to reduce the
Hilbert space dimension of the simulation
"""
self._basis = None
self.num_species = num_species
super().__init__(shots=shots, seed=seed)
@property
def basis(self) -> FermionicBasis:
"""
Return the basis of fermionic occupation number states. This basis is updated via the
setter whenever a new circuit is passed to __call__.
"""
return self._basis
@basis.setter
def basis(self, basis: FermionicBasis):
"""
Set the basis of the simulation and check its dimensions.
Args:
basis: The new basis.
Raises:
QiskitColdAtomError: If the dimension of the basis is too large.
"""
if basis.dimension > self.max_dimension:
raise QiskitColdAtomError(
f"Dimension {basis.dimension} exceeds the maximum "
f"allowed dimension {self.max_dimension}."
)
self._basis = basis
def preprocess_circuit(self, circuit: QuantumCircuit):
"""
Pre-processing fermionic circuits includes setting up the basis for the simulation
by extracting the size, particle number and spin conservation from the circuit.
Args:
circuit: A fermionic quantum circuit for which to setup a basis.
"""
initial_occupations = FermionicState.initial_state(circuit, self.num_species)
_, spin_conservation = self._check_conservations(circuit)
self.basis = FermionicBasis.from_state(initial_occupations, spin_conservation)
self._dim = self.basis.dimension
def get_initial_state(self, circuit: QuantumCircuit) -> csc_matrix:
"""
Return the initial state of the quantum circuit as a sparse column vector.
Args:
circuit: The circuit for which to extract the initial_state.
Returns:
The initial state of the circuit as a sparse matrix.
"""
init_state = FermionicState.initial_state(circuit, self.num_species)
initial_occs = init_state.occupations_flat
initial_index = self.basis.get_occupations().index(initial_occs)
initial_state = csc_matrix(
([1 + 0j], ([initial_index], [0])),
shape=(self.basis.dimension, 1),
dtype=complex,
)
return initial_state
def _embed_operator(
self, operator: FermionicOp, num_wires: int, qargs: List[int]
) -> FermionicOp:
"""
Turn a FermionicOp operator that acts on the wires given in qargs into an operator
that acts on the entire state space of the circuit by padding with identities "I" on the
remaining wires
Args:
operator: FermionicOp describing the generating Hamiltonian of a gate
num_wires: The total number of wires in which the operator should be embedded into
qargs: The wire indices the gate acts on
Returns:
FermionicOp, an operator acting on the entire quantum register of the Circuit
Raises:
QiskitColdAtomError:
- If the given operator is not a FermionicOp
- If the size of the operator does not match the given qargs
"""
if not isinstance(operator, FermionicOp):
raise QiskitColdAtomError(
f"Expected FermionicOp; got {type(operator).__name__} instead."
)
if operator.num_spin_orbitals != len(qargs):
raise QiskitColdAtomError(
f"length of gate labels {operator.num_spin_orbitals} does not match "
f"qargs {qargs} of the gates"
)
embedded_terms = []
for partial_label, factor in operator.terms():
embedded_terms.append((operator._permute_term(partial_label, qargs), factor))
reordered_op = FermionicOp.from_terms(embedded_terms)
reordered_op.num_spin_orbitals = num_wires
return reordered_op
def _check_conservations(self, circuit: QuantumCircuit) -> Tuple[bool, bool]:
"""
Check if the fermionic operators defined in the circuit conserve the total particle number
(i.e. there are as many creation operators as annihilation operators) and the particle
number per spin species (e.g. there are as many up/down creation operators as there are
up/down annihilation operators).
Args:
circuit: A quantum circuit with fermionic gates
Returns:
particle_conservation: True if the particle number is conserved in the circuit
spin_conservation: True if the particle number is conserved for each spin species
Raises:
QiskitColdAtomError:
- If an operator in the circuit is not a FermionicOp.
- If the length of the fermionic operators does not match the system size.
- If the circuit has a number of wires that is not a multiple of the number
of fermionic species.
"""
particle_conservation = True
spin_conservation = True
for fermionic_op in self.to_operators(circuit):
if not isinstance(fermionic_op, FermionicOp):
raise QiskitColdAtomError("operators need to be given as FermionicOp")
if fermionic_op.num_spin_orbitals != circuit.num_qubits:
raise QiskitColdAtomError(
f"Expected length {circuit.num_qubits} for fermionic operator; "
f"received {fermionic_op.num_spin_orbitals}."
)
for opstring, _ in fermionic_op.terms():
op_types = [op for op, _ in opstring]
num_creators = op_types.count("+")
num_annihilators = op_types.count("-")
if num_creators != num_annihilators:
return False, False
if self.num_species > 1:
if circuit.num_qubits % self.num_species != 0:
raise QiskitColdAtomError(
f"The number of wires in the circuit {circuit.num_qubits} is not a "
f"multiple of the {self.num_species} fermionic species number."
)
sites = circuit.num_qubits // self.num_species
# check if the particle number is conserved for each spin species
for i in range(self.num_species):
spin_range = range(i * sites, (i + 1) * sites)
op_types_in_range = [op for op, idx in opstring if idx in spin_range]
num_creators = op_types_in_range.count("+")
num_annihilators = op_types_in_range.count("-")
if num_creators != num_annihilators:
spin_conservation = False
break
return particle_conservation, spin_conservation
def operator_to_mat(self, operator: FermionicOp) -> csc_matrix:
"""Convert the fermionic operator to a sparse matrix.
Args:
operator: fermionic operator of which to compute the matrix representation
Returns:
scipy.sparse matrix of the Hamiltonian
"""
return FermionicGate.operator_to_mat(operator, self.num_species, self._basis)
def draw_shots(self, measurement_distribution: List[float]) -> List[str]:
"""
Helper function to draw counts from a given distribution of measurement outcomes.
Args:
measurement_distribution: List of probabilities of the individual measurement outcomes
Returns:
a list of individual measurement results, e.g. ["011000", "100010", ...]
The outcome of each shot is denoted by a binary string of the occupations of the individual
modes in little endian convention
Raises:
QiskitColdAtomError:
- If the length of the given probabilities does not match the expected Hilbert space
dimension.
- If the number of shots self.shots has not been specified.
"""
meas_dim = len(measurement_distribution)
if meas_dim != self.dim:
raise QiskitColdAtomError(
f"Dimension of the measurement probabilities {meas_dim} does not "
f"match the dimension expected by the solver, {self.dim}"
)
if self.shots is None:
raise QiskitColdAtomError(
"The number of shots has to be set before drawing measurements"
)
# list all possible outcomes as strings '001011', reversing the order of the wires
# to comply with Qiskit's ordering convention
outcome_strings = ["".join(map(str, k)) for k in self.basis.get_occupations()]
# Draw measurements:
meas_results = np.random.choice(outcome_strings, self.shots, p=measurement_distribution)
return meas_results.tolist()
|
https://github.com/qiskit-community/qiskit-cold-atom
|
qiskit-community
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""General Fermion simulator backend."""
from typing import Union, List, Dict, Any, Optional
import uuid
import warnings
import time
import datetime
from qiskit.providers.models import BackendConfiguration
from qiskit.providers import Options
from qiskit import QuantumCircuit
from qiskit.result import Result
from qiskit_aer import AerJob
from qiskit_cold_atom.fermions.fermion_circuit_solver import FermionCircuitSolver
from qiskit_cold_atom.fermions.base_fermion_backend import BaseFermionBackend
from qiskit_cold_atom.circuit_tools import CircuitTools
class FermionSimulator(BaseFermionBackend):
"""A simulator to simulate general fermionic circuits.
This general fermion simulator backend simulates fermionic circuits with gates that have
generators described by fermionic Hamiltonians. It computes the statevector and unitary
of a circuit and simulates measurements.
"""
_DEFAULT_CONFIGURATION = {
"backend_name": "fermion_simulator",
"backend_version": "0.0.1",
"n_qubits": 20,
"basis_gates": None,
"gates": [],
"local": False,
"simulator": True,
"conditional": False,
"open_pulse": False,
"memory": True,
"max_shots": 1e5,
"coupling_map": None,
"description": "a base simulator for fermionic circuits. Instead of qubits, each wire represents"
" a single fermionic mode",
"supported_instructions": None,
}
def __init__(self, config_dict: Dict[str, Any] = None, provider=None):
"""Initializing the backend from a configuration dictionary"""
if config_dict is None:
config_dict = self._DEFAULT_CONFIGURATION
super().__init__(
configuration=BackendConfiguration.from_dict(config_dict), provider=provider
)
@classmethod
def _default_options(cls):
return Options(shots=1)
def _execute(self, data: Dict[str, Any], job_id: str = ""):
"""Helper function to execute a job. The circuit and all relevant parameters are given in the
data dict. Performs validation checks on the received circuits and utilizes
the FermionCircuitSolver to perform the numerical simulations.
Args:
data: Data dictionary that that contains the experiments to simulate, given in the shape:
data = {
"num_species": int,
"shots": int,
"seed": int,
"experiments": Dict[str, QuantumCircuit],
}
job_id: The job id assigned by the run method
Returns:
result: A qiskit job result.
"""
# Start timer
start = time.time()
output = {"results": []}
num_species = data["num_species"]
shots = data["shots"]
seed = data["seed"]
solver = FermionCircuitSolver(num_species=num_species, shots=shots, seed=seed)
for exp_i, exp_name in enumerate(data["experiments"]):
experiment = data["experiments"][exp_name]
circuit = experiment["circuit"]
# perform compatibility checks with the backend configuration in case gates and supported
# instructions are constrained by the backend's configuration
if self.configuration().gates and self.configuration().supported_instructions:
CircuitTools.validate_circuits(circuits=circuit, backend=self, shots=shots)
# check whether all wires are measured
measured_wires = []
for inst in circuit.data:
name = inst[0].name
if name == "measure":
for wire in inst[1]:
index = circuit.qubits.index(wire)
if index in measured_wires:
warnings.warn(
f"Wire {index} has already been measured, "
f"second measurement is ignored"
)
else:
measured_wires.append(index)
if measured_wires and len(measured_wires) != len(circuit.qubits):
warnings.warn(
f"Number of wires in circuit ({len(circuit.qubits)}) exceeds number of wires "
+ f" with assigned measurement instructions ({len(measured_wires)}). "
+ "This simulator backend only supports measurement of the entire quantum register "
"which will instead be performed."
)
# If there are no measurements, set shots to None
if not measured_wires:
solver.shots = None
simulation_result = solver(circuit)
output["results"].append(
{
"header": {"name": exp_name, "random_seed": seed},
"shots": shots,
"status": "DONE",
"success": True,
}
)
# add the simulation result at the correct place in the result dictionary
output["results"][exp_i]["data"] = simulation_result
output["job_id"] = job_id
output["date"] = datetime.datetime.now().isoformat()
output["backend_name"] = self.name()
output["backend_version"] = self.configuration().backend_version
output["time_taken"] = time.time() - start
output["success"] = True
output["qobj_id"] = None
return Result.from_dict(output)
# pylint: disable=arguments-differ, unused-argument
def run(
self,
circuits: Union[QuantumCircuit, List[QuantumCircuit]],
shots: int = 1000,
seed: Optional[int] = None,
num_species: int = 1,
**run_kwargs,
) -> AerJob:
"""
Method to run circuits on the backend.
Args:
circuits: QuantumCircuit applying fermionic gates to run on the backend
shots: Number of measurement shots taken in case the circuit has measure instructions
seed: seed for the random number generator of the measurement simulation
num_species: number of different fermionic species described by the circuits
run_kwargs: Additional keyword arguments that might be passed down when calling
qiskit.execute() which will have no effect on this backend.
Returns:
aer_job: a job object containing the result of the simulation
"""
if isinstance(circuits, QuantumCircuit):
circuits = [circuits]
data = {
"num_species": num_species,
"shots": shots,
"seed": seed,
"experiments": {},
}
for idx, circuit in enumerate(circuits):
data["experiments"][f"experiment_{idx}"] = {
"circuit": circuit,
}
job_id = str(uuid.uuid4())
aer_job = AerJob(self, job_id, self._execute, data)
aer_job.submit()
return aer_job
@staticmethod
def get_basis(circuit: QuantumCircuit, num_species: int = 1):
"""Get the basis of fermionic states in occupation number representation for the simulation
of a given quantum circuit.
Args:
circuit: A quantum circuit using Fermionic Gates.
num_species: Number of different fermionic species described by the circuit.
Returns:
basis: the fermionic basis in which the simulation of the circuit is performed.
"""
solver = FermionCircuitSolver(num_species=num_species)
solver.preprocess_circuit(circuit)
basis = solver.basis
return basis
def draw(self, qc: QuantumCircuit, **draw_options):
"""Draw the circuit by defaulting to the draw method of QuantumCircuit.
Note that in the future this method may be modified and tailored to fermion
quantum circuits.
Args:
qc: The quantum circuit to draw.
draw_options: Key word arguments for the drawing of circuits.
"""
qc.draw(**draw_options)
|
https://github.com/qiskit-community/qiskit-cold-atom
|
qiskit-community
|
# 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.
"""Fermionic simulator backend that uses ffsim."""
from __future__ import annotations
import datetime
import time
import uuid
import warnings
from collections import Counter
from typing import Any, Dict, List, Optional, Union
import ffsim # pylint: disable=import-error
import numpy as np
import scipy.linalg
from qiskit import QuantumCircuit
from qiskit.circuit.library import Barrier, Measure
from qiskit.providers import Options
from qiskit.providers.models import BackendConfiguration
from qiskit.result import Result
from qiskit_aer import AerJob
from qiskit_nature.second_q.operators import FermionicOp
from scipy.sparse.linalg import expm_multiply
from qiskit_cold_atom.circuit_tools import CircuitTools
from qiskit_cold_atom.fermions.base_fermion_backend import BaseFermionBackend
from qiskit_cold_atom.fermions.fermion_gate_library import (
FermionicGate,
FRXGate,
FRYGate,
FRZGate,
Hop,
Interaction,
LoadFermions,
Phase,
)
class FfsimBackend(BaseFermionBackend):
"""Fermionic simulator backend that uses ffsim.
This is a high-performance simulator backend for fermionic circuits that uses `ffsim`_.
It computes the state vector and simulate measurements with vastly improved efficiency
compared with the :class:`~.FermionSimulator` backend. Unlike :class:`~.FermionSimulator`,
it does not compute the full unitary of a circuit.
Currently, this simulator only supports simulations with 1 or 2 species of fermions.
The number of fermions of each species is assumed to be preserved, so that the
dimension of the state vector can be determined from the number of species and the
number of particles of each species. In particular, when simulating 2 species of fermions,
gates that mix particles of different species, such as :class:`~.FRXGate` and
:class:`FRYGate`, are not supported. In this respect, the behavior of this simulator
differs from :class:`FermionSimulator`, which would automatically resort to a
single-species simulation in which particles of each species are not distinguished.
This backend is not supported on Windows, and in order for it to be available,
Qiskit Cold Atom must be installed with the ``ffsim`` extra, e.g.
.. code::
pip install "qiskit-cold-atom[ffsim]"
.. _ffsim: https://github.com/qiskit-community/ffsim
"""
_DEFAULT_CONFIGURATION = {
"backend_name": "ffsim_simulator",
"backend_version": "0.0.1",
"n_qubits": 100,
"basis_gates": None,
"gates": [],
"local": False,
"simulator": True,
"conditional": False,
"open_pulse": False,
"memory": True,
"max_shots": 1e6,
"coupling_map": None,
"description": "ffsim simulator for fermionic circuits. Instead of qubits, each wire represents"
" a single fermionic mode",
"supported_instructions": None,
}
def __init__(self, config_dict: Dict[str, Any] = None, provider=None):
"""Initializing the backend from a configuration dictionary"""
if config_dict is None:
config_dict = self._DEFAULT_CONFIGURATION
super().__init__(
configuration=BackendConfiguration.from_dict(config_dict), provider=provider
)
@classmethod
def _default_options(cls):
return Options(shots=1)
def _execute(self, data: Dict[str, Any], job_id: str = ""):
"""Helper function to execute a job. The circuit and all relevant parameters are given in the
data dict. Performs validation checks on the received circuits and utilizes
ffsim to perform the numerical simulations.
Args:
data: Data dictionary that that contains the experiments to simulate, given in the shape:
data = {
"num_species": int,
"shots": int,
"seed": int,
"experiments": Dict[str, QuantumCircuit],
}
job_id: The job id assigned by the run method
Returns:
result: A qiskit job result.
"""
# Start timer
start = time.time()
output = {"results": []}
num_species = data["num_species"]
shots = data["shots"]
seed = data["seed"]
for exp_i, exp_name in enumerate(data["experiments"]):
experiment = data["experiments"][exp_name]
circuit = experiment["circuit"]
# perform compatibility checks with the backend configuration in case gates and supported
# instructions are constrained by the backend's configuration
if self.configuration().gates and self.configuration().supported_instructions:
CircuitTools.validate_circuits(circuits=circuit, backend=self, shots=shots)
# check whether all wires are measured
measured_wires = []
for inst in circuit.data:
name = inst[0].name
if name == "measure":
for wire in inst[1]:
index = circuit.qubits.index(wire)
if index in measured_wires:
warnings.warn(
f"Wire {index} has already been measured, "
f"second measurement is ignored"
)
else:
measured_wires.append(index)
if measured_wires and len(measured_wires) != len(circuit.qubits):
warnings.warn(
f"Number of wires in circuit ({len(circuit.qubits)}) exceeds number of wires "
+ f" with assigned measurement instructions ({len(measured_wires)}). "
+ "This simulator backend only supports measurement of the entire quantum register "
"which will instead be performed."
)
# If there are no measurements, set shots to None
if not measured_wires:
shots = None
simulation_result = _simulate_ffsim(circuit, num_species, shots, seed)
output["results"].append(
{
"header": {"name": exp_name, "random_seed": seed},
"shots": shots,
"status": "DONE",
"success": True,
}
)
# add the simulation result at the correct place in the result dictionary
output["results"][exp_i]["data"] = simulation_result
output["job_id"] = job_id
output["date"] = datetime.datetime.now().isoformat()
output["backend_name"] = self.name()
output["backend_version"] = self.configuration().backend_version
output["time_taken"] = time.time() - start
output["success"] = True
output["qobj_id"] = None
return Result.from_dict(output)
# pylint: disable=arguments-differ, unused-argument
def run(
self,
circuits: Union[QuantumCircuit, List[QuantumCircuit]],
shots: int = 1000,
seed: Optional[int] = None,
num_species: int = 1,
**run_kwargs,
) -> AerJob:
"""
Method to run circuits on the backend.
Args:
circuits: QuantumCircuit applying fermionic gates to run on the backend
shots: Number of measurement shots taken in case the circuit has measure instructions
seed: seed for the random number generator of the measurement simulation
num_species: number of different fermionic species described by the circuits
run_kwargs: Additional keyword arguments that might be passed down when calling
qiskit.execute() which will have no effect on this backend.
Returns:
aer_job: a job object containing the result of the simulation
Raises:
ValueError: FfsimBackend only supports num_species=1 or 2.
"""
if num_species not in (1, 2):
raise ValueError(f"FfsimBackend only supports num_species=1 or 2. Got {num_species}.")
if isinstance(circuits, QuantumCircuit):
circuits = [circuits]
data = {
"num_species": num_species,
"shots": shots,
"seed": seed,
"experiments": {},
}
for idx, circuit in enumerate(circuits):
data["experiments"][f"experiment_{idx}"] = {
"circuit": circuit,
}
job_id = str(uuid.uuid4())
aer_job = AerJob(self, job_id, self._execute, data)
aer_job.submit()
return aer_job
def _simulate_ffsim(
circuit: QuantumCircuit, num_species: int, shots: int | None = None, seed=None
) -> dict[str, Any]:
assert circuit.num_qubits % num_species == 0
norb = circuit.num_qubits // num_species
occ_a, occ_b = _get_initial_occupations(circuit, num_species)
nelec = len(occ_a), len(occ_b)
vec = ffsim.slater_determinant(norb, (occ_a, occ_b))
qubit_indices = {q: i for i, q in enumerate(circuit.qubits)}
for instruction in circuit.data:
op, qubits, _ = instruction.operation, instruction.qubits, instruction.clbits
if isinstance(op, Hop):
orbs = [qubit_indices[q] for q in qubits]
spatial_orbs = _get_spatial_orbitals(orbs, norb, num_species)
vec = _simulate_hop(
vec,
np.array(op.params),
spatial_orbs,
norb=norb,
nelec=nelec,
num_species=num_species,
copy=False,
)
elif isinstance(op, Interaction):
orbs = [qubit_indices[q] for q in qubits]
spatial_orbs = _get_spatial_orbitals(orbs, norb, num_species)
(interaction,) = op.params
vec = _simulate_interaction(
vec,
interaction,
spatial_orbs,
norb=norb,
nelec=nelec,
num_species=num_species,
copy=False,
)
elif isinstance(op, Phase):
orbs = [qubit_indices[q] for q in qubits]
spatial_orbs = _get_spatial_orbitals(orbs, norb, num_species)
vec = _simulate_phase(
vec,
np.array(op.params),
spatial_orbs,
norb=norb,
nelec=nelec,
num_species=num_species,
copy=False,
)
elif isinstance(op, FRZGate):
orbs = [qubit_indices[q] for q in qubits]
# pass num_species=1 here due to the definition of FRZGate
spatial_orbs = _get_spatial_orbitals(orbs, norb, num_species=1)
(phi,) = op.params
vec = _simulate_frz(
vec,
phi,
spatial_orbs,
norb=norb,
nelec=nelec,
num_species=num_species,
copy=False,
)
elif isinstance(op, FRXGate):
if num_species != 1:
raise RuntimeError(
f"Encountered FRXGate even though num_species={num_species}. "
"FRXGate is only supported for num_species=1."
)
orbs = [qubit_indices[q] for q in qubits]
spatial_orbs = _get_spatial_orbitals(orbs, norb, num_species=1)
(phi,) = op.params
vec = ffsim.apply_tunneling_interaction(
vec, -phi, spatial_orbs, norb, nelec, copy=False
)
elif isinstance(op, FRYGate):
if num_species != 1:
raise RuntimeError(
f"Encountered FRXGate even though num_species={num_species}. "
"FRXGate is only supported for num_species=1."
)
orbs = [qubit_indices[q] for q in qubits]
spatial_orbs = _get_spatial_orbitals(orbs, norb, num_species=1)
(phi,) = op.params
vec = ffsim.apply_givens_rotation(vec, -phi, spatial_orbs, norb, nelec, copy=False)
elif isinstance(op, FermionicGate):
orbs = [qubit_indices[q] for q in qubits]
spatial_orbs = _get_spatial_orbitals(orbs, norb, num_species)
ferm_op = _fermionic_op_to_fermion_operator(op.generator, spatial_orbs)
linop = ffsim.linear_operator(ferm_op, norb, nelec)
# TODO use ferm_op.values once it's available
scale = sum(abs(ferm_op[k]) for k in ferm_op)
vec = expm_multiply(-1j * linop, vec, traceA=scale)
elif isinstance(op, (LoadFermions, Measure, Barrier)):
# these gates are handled separately or are no-ops
pass
else:
warnings.warn(f"Unrecognized gate type {type(op)}, skipping it...")
result = {"statevector": vec}
if shots is None:
result["memory"] = []
result["counts"] = {}
else:
rng = np.random.default_rng(seed)
probs = np.abs(vec) ** 2
samples = rng.choice(np.arange(len(vec)), size=shots, replace=True, p=probs)
bitstrings = ffsim.indices_to_strings(samples, norb, nelec)
# flip beta-alpha to alpha-beta ordering
bitstrings = [f"{b[len(b) // 2 :]}{b[: len(b) // 2]}" for b in bitstrings]
# remove bits from absent spins
bitstrings = [b[: num_species * norb] for b in bitstrings]
result["memory"] = bitstrings
result["counts"] = Counter(bitstrings)
return result
def _get_initial_occupations(circuit: QuantumCircuit, num_species: int):
norb = circuit.num_qubits // num_species
occ_a, occ_b = set(), set()
occupations = [occ_a, occ_b]
active_qubits = set()
for instruction in circuit.data:
if isinstance(instruction.operation, LoadFermions):
for q in instruction.qubits:
if q in active_qubits:
raise ValueError(
f"Encountered Load instruction on qubit {q} after it has "
"already been operated on."
)
spin, orb = divmod(circuit.qubits.index(q), norb)
# reverse index due to qiskit convention
occupations[spin].add(norb - 1 - orb)
else:
active_qubits |= set(instruction.qubits)
return tuple(occ_a), tuple(occ_b)
def _get_spatial_orbitals(orbs: list[int], norb: int, num_species: int) -> list[int]:
assert len(orbs) % num_species == 0
alpha_orbs = orbs[: len(orbs) // num_species]
if num_species == 2:
beta_orbs = [orb - norb for orb in orbs[len(orbs) // 2 :]]
assert alpha_orbs == beta_orbs
# reverse orbitals due to qiskit convention
alpha_orbs = [norb - 1 - orb for orb in alpha_orbs]
return alpha_orbs
def _simulate_hop(
vec: np.ndarray,
coeffs: np.ndarray,
target_orbs: list[int],
norb: int,
nelec: tuple[int, int],
num_species: int,
copy: bool,
) -> np.ndarray:
if num_species == 1:
return _simulate_hop_spinless(
vec=vec,
coeffs=coeffs,
target_orbs=target_orbs,
norb=norb,
nelec=nelec,
copy=copy,
)
else: # num_species == 2
return _simulate_hop_spinful(
vec=vec,
coeffs=coeffs,
target_orbs=target_orbs,
norb=norb,
nelec=nelec,
copy=copy,
)
def _simulate_hop_spinless(
vec: np.ndarray,
coeffs: np.ndarray,
target_orbs: list[int],
norb: int,
nelec: tuple[int, int],
copy: bool,
) -> np.ndarray:
assert norb % 2 == 0
assert len(target_orbs) % 2 == 0
mat = np.zeros((norb, norb))
for i, val in zip(range(len(target_orbs) // 2 - 1), coeffs):
j, k = target_orbs[i], target_orbs[i + 1]
mat[j, k] = -val
mat[k, j] = -val
for i, val in zip(range(len(target_orbs) // 2, len(target_orbs) - 1), coeffs):
j, k = target_orbs[i], target_orbs[i + 1]
mat[j, k] = -val
mat[k, j] = -val
coeffs, orbital_rotation = scipy.linalg.eigh(mat)
return ffsim.apply_num_op_sum_evolution(
vec,
coeffs,
1.0,
norb=norb,
nelec=nelec,
orbital_rotation=orbital_rotation,
copy=copy,
)
def _simulate_hop_spinful(
vec: np.ndarray,
coeffs: np.ndarray,
target_orbs: list[int],
norb: int,
nelec: tuple[int, int],
copy: bool,
) -> np.ndarray:
mat = np.zeros((norb, norb))
for i, val in zip(range(len(target_orbs) - 1), coeffs):
j, k = target_orbs[i], target_orbs[i + 1]
mat[j, k] = -val
mat[k, j] = -val
coeffs, orbital_rotation = scipy.linalg.eigh(mat)
return ffsim.apply_num_op_sum_evolution(
vec,
coeffs,
1.0,
norb=norb,
nelec=nelec,
orbital_rotation=orbital_rotation,
copy=copy,
)
def _simulate_interaction(
vec: np.ndarray,
interaction: float,
target_orbs: list[int],
norb: int,
nelec: tuple[int, int],
num_species: int,
copy: bool,
) -> np.ndarray:
if num_species == 1:
return _simulate_interaction_spinless(
vec=vec,
interaction=interaction,
target_orbs=target_orbs,
norb=norb,
nelec=nelec,
copy=copy,
)
else: # num_species == 2
return _simulate_interaction_spinful(
vec=vec,
interaction=interaction,
target_orbs=target_orbs,
norb=norb,
nelec=nelec,
copy=copy,
)
def _simulate_interaction_spinless(
vec: np.ndarray,
interaction: float,
target_orbs: list[int],
norb: int,
nelec: tuple[int, int],
copy: bool,
) -> np.ndarray:
assert len(target_orbs) % 2 == 0
n_spatial_orbs = len(target_orbs) // 2
mat = np.zeros((norb, norb))
mat[target_orbs[:n_spatial_orbs], target_orbs[n_spatial_orbs:]] = interaction
mat[target_orbs[n_spatial_orbs:], target_orbs[:n_spatial_orbs]] = interaction
return ffsim.apply_diag_coulomb_evolution(
vec,
mat=mat,
time=1.0,
norb=norb,
nelec=nelec,
copy=copy,
)
def _simulate_interaction_spinful(
vec: np.ndarray,
interaction: float,
target_orbs: list[int],
norb: int,
nelec: tuple[int, int],
copy: bool,
) -> np.ndarray:
mat_alpha_beta = np.zeros((norb, norb))
mat_alpha_beta[target_orbs, target_orbs] = interaction
return ffsim.apply_diag_coulomb_evolution(
vec,
mat=np.zeros((norb, norb)),
mat_alpha_beta=mat_alpha_beta,
time=1.0,
norb=norb,
nelec=nelec,
copy=copy,
)
def _simulate_phase(
vec: np.ndarray,
mu: np.ndarray,
target_orbs: list[int],
norb: int,
nelec: tuple[int, int],
num_species: int,
copy: bool,
) -> np.ndarray:
if num_species == 1:
return _simulate_phase_spinless(
vec=vec,
mu=mu,
target_orbs=target_orbs,
norb=norb,
nelec=nelec,
copy=copy,
)
else: # num_species == 2
return _simulate_phase_spinful(
vec=vec,
mu=mu,
target_orbs=target_orbs,
norb=norb,
nelec=nelec,
copy=copy,
)
def _simulate_phase_spinless(
vec: np.ndarray,
mu: np.ndarray,
target_orbs: list[int],
norb: int,
nelec: tuple[int, int],
copy: bool,
) -> np.ndarray:
assert len(target_orbs) % 2 == 0
n_spatial_orbs = len(target_orbs) // 2
coeffs = np.zeros(norb)
coeffs[target_orbs[:n_spatial_orbs]] = mu
coeffs[target_orbs[n_spatial_orbs:]] = mu
return ffsim.apply_num_op_sum_evolution(
vec, coeffs, time=1.0, norb=norb, nelec=nelec, copy=copy
)
def _simulate_phase_spinful(
vec: np.ndarray,
mu: np.ndarray,
target_orbs: list[int],
norb: int,
nelec: tuple[int, int],
copy: bool,
) -> np.ndarray:
coeffs = np.zeros(norb)
coeffs[target_orbs] = mu
return ffsim.apply_num_op_sum_evolution(
vec, coeffs, time=1.0, norb=norb, nelec=nelec, copy=copy
)
def _simulate_frz(
vec: np.ndarray,
phi: np.ndarray,
target_orbs: list[int],
norb: int,
nelec: tuple[int, int],
num_species: int,
copy: bool,
) -> np.ndarray:
if num_species == 1:
a, b = target_orbs
vec = ffsim.apply_num_interaction(vec, -phi, a, norb, nelec, copy=copy)
vec = ffsim.apply_num_interaction(vec, phi, b, norb, nelec, copy=False)
return vec
else: # num_species == 2
a, b = target_orbs
spin_a, orb_a = divmod(a, norb)
spin_b, orb_b = divmod(b, norb)
spins = (ffsim.Spin.ALPHA, ffsim.Spin.BETA)
vec = ffsim.apply_num_interaction(vec, -phi, orb_a, norb, nelec, spins[spin_a], copy=copy)
vec = ffsim.apply_num_interaction(vec, phi, orb_b, norb, nelec, spins[spin_b], copy=False)
return vec
def _fermionic_op_to_fermion_operator( # pylint: disable=invalid-name
op: FermionicOp, target_orbs: list[int]
) -> ffsim.FermionOperator:
"""Convert a Qiskit Nature FermionicOp to an ffsim FermionOperator."""
norb_small = len(target_orbs)
coeffs = {}
for term, coeff in op.terms():
fermion_actions = []
for action_str, index in term:
action = action_str == "+"
spin, orb = divmod(index, norb_small)
fermion_actions.append((action, bool(spin), target_orbs[orb]))
coeffs[tuple(fermion_actions)] = coeff
return ffsim.FermionOperator(coeffs)
|
https://github.com/qiskit-community/qiskit-cold-atom
|
qiskit-community
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Classes for remote cold atom backends."""
import json
from typing import List, Dict, Union
import requests
from qiskit.providers.models import BackendConfiguration
from qiskit.providers import Options
from qiskit import QuantumCircuit
from qiskit.providers import ProviderV1 as Provider
from qiskit.providers import BackendV1 as Backend
from qiskit.providers import JobStatus
from qiskit_cold_atom.spins.base_spin_backend import BaseSpinBackend
from qiskit_cold_atom.fermions.base_fermion_backend import BaseFermionBackend
from qiskit_cold_atom.circuit_tools import CircuitTools
from qiskit_cold_atom.providers.cold_atom_job import ColdAtomJob
from qiskit_cold_atom.exceptions import QiskitColdAtomError
class RemoteBackend(Backend):
"""Remote cold atom backend."""
def __init__(self, provider: Provider, url: str):
"""
Initialize the backend by querying the server for the backend configuration dictionary.
Args:
provider: The provider which need to have the correct credentials attributes in place
url: The url of the backend server
Raises:
QiskitColdAtomError: If the connection to the backend server can not be established.
"""
self.url = url
self.username = provider.credentials["username"]
self.token = provider.credentials["token"]
# Get the config file from the remote server
try:
r = requests.get(
self.url + "/get_config",
params={
"username": self.username,
"token": self.token,
},
)
except requests.exceptions.ConnectionError as err:
raise QiskitColdAtomError(
"connection to the backend server can not be established."
) from err
super().__init__(configuration=BackendConfiguration.from_dict(r.json()), provider=provider)
@classmethod
def _default_options(cls) -> Options:
"""Return the default options.
Returns:
qiskit.providers.Options: A options object with default values set
"""
return Options(shots=1)
@property
def credentials(self) -> Dict[str, Union[str, List[str]]]:
"""Returns: the access credentials used."""
return self.provider().credentials
# pylint: disable=arguments-differ, unused-argument
def run(
self,
circuit: Union[QuantumCircuit, List[QuantumCircuit]],
shots: int = 1,
convert_wires: bool = True,
**run_kwargs,
) -> ColdAtomJob:
"""
Run a quantum circuit or list of quantum circuits.
Args:
circuit: The quantum circuits to be executed on the device backend
shots: The number of measurement shots to be measured for each given circuit
convert_wires: If True (the default), the circuits are converted to the wiring convention
of the backend.
run_kwargs: Additional keyword arguments that might be passed down when calling
qiskit.execute() which will have no effect on this backend.
Raises:
QiskitColdAtomError: If the response from the backend does not have a job_id.
Returns:
A Job object through the backend can be queried for status, result etc.
"""
job_payload = CircuitTools.circuit_to_cold_atom(circuit, self, shots=shots)
res = requests.post(
self.url + "/post_job",
json={
"job": json.dumps(job_payload),
"username": self.username,
"token": self.token,
},
)
res.raise_for_status()
response = res.json()
if "job_id" not in response:
raise QiskitColdAtomError("The response has no job_id.")
return ColdAtomJob(self, response["job_id"])
def retrieve_job(self, job_id: str) -> ColdAtomJob:
"""Return a single job submitted to this backend.
Args:
job_id: The ID of the job to retrieve.
Returns:
The job with the given ID.
Raises:
QiskitColdAtomError: If the job retrieval failed.
"""
retrieved_job = ColdAtomJob(backend=self, job_id=job_id)
try:
job_status = retrieved_job.status()
except requests.exceptions.RequestException as request_error:
raise QiskitColdAtomError(
"connection to the remote backend could not be established"
) from request_error
if job_status == JobStatus.ERROR:
raise QiskitColdAtomError(f"Job with id {job_id} could not be retrieved")
return retrieved_job
class RemoteSpinBackend(RemoteBackend, BaseSpinBackend):
"""Remote backend which runs spin circuits."""
class RemoteFermionBackend(RemoteBackend, BaseFermionBackend):
"""Remote backend which runs fermionic circuits."""
|
https://github.com/qiskit-community/qiskit-cold-atom
|
qiskit-community
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Module for cold-atom spin backends."""
from abc import ABC
from qiskit.providers import BackendV1 as Backend
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit_cold_atom import QiskitColdAtomError
class BaseSpinBackend(Backend, ABC):
"""Abstract base class for atomic mixture backends."""
def get_empty_circuit(self) -> QuantumCircuit:
"""
Convenience function to set up an empty circuit with the right QuantumRegisters.
For each atomic species specified in the config file, a quantum register is added to the circuit.
Returns:
qc: An empty quantum circuit ready to use in spin-based cold-atom setups.
Raises:
QiskitColdAtomError:
- If backend has no config file.
- If number of wires of the backend config is not a multiple of the atomic species.
"""
config = self.configuration().to_dict()
try:
num_wires = config["n_qubits"]
num_species = len(config["atomic_species"])
except NameError as name_error:
raise QiskitColdAtomError(
"backend needs to be initialized with config file first"
) from name_error
if not (isinstance(num_wires, int) and num_wires % num_species == 0):
raise QiskitColdAtomError(
"num_wires {num_wires} must be multiple of num_species {num_species}"
)
qregs = [
QuantumRegister(num_wires / num_species, species)
for species in config["atomic_species"]
]
class_reg = ClassicalRegister(num_wires, "c{}".format(num_wires))
empty_circuit = QuantumCircuit(*qregs, class_reg)
return empty_circuit
def draw(self, qc: QuantumCircuit, **draw_options):
"""Modified circuit drawer to better display atomic mixture quantum circuits.
For now this method is just an alias to `QuantumCircuit.draw()` but in the future this method
may be modified and tailored to spin quantum circuits.
Args:
qc: The quantum circuit to draw.
draw_options: Key word arguments for the drawing of circuits.
"""
qc.draw(**draw_options)
|
https://github.com/qiskit-community/qiskit-cold-atom
|
qiskit-community
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Module to simulate spin circuits."""
import math
from typing import List, Union, Optional
from fractions import Fraction
import numpy as np
from scipy.sparse import csc_matrix
from qiskit import QuantumCircuit
from qiskit_nature.second_q.operators import SpinOp
from qiskit_cold_atom.base_circuit_solver import BaseCircuitSolver
from qiskit_cold_atom.exceptions import QiskitColdAtomError
class SpinCircuitSolver(BaseCircuitSolver):
"""Performs numerical simulations of spin systems by exactly computing the time
evolution under unitary operations generated by exponentiating spin Hamiltonians."""
def __init__(
self,
spin: Union[float, Fraction] = Fraction(1, 2),
shots: Optional[int] = None,
seed: Optional[int] = None,
):
"""
Initialize a spin circuit solver.
Args:
spin: The length of the spin of each wire in the circuit.
shots: Amount of shots for the measurement simulation;
if not None, measurements are performed.
seed: The seed for the RNG for the measurement simulation.
Raises:
QiskitColdAtomError: if the spin is not a positive integer or half-integer.
"""
self.spin = Fraction(spin)
if self.spin.denominator not in (1, 2):
raise QiskitColdAtomError(
f"spin must be a positive half-integer (integer or half-odd-integer), "
f"not {self.spin}."
)
super().__init__(shots=shots, seed=seed)
def get_initial_state(self, circuit: QuantumCircuit) -> csc_matrix:
"""
Return the initial state as a sparse column vector.
Args:
circuit: A circuit that tells us the dimension of the initial state to return.
Returns:
initial state: A sparse column vector of the initial state.
"""
dim = int((2 * self.spin + 1) ** circuit.num_qubits)
initial_state = csc_matrix(([1 + 0j], ([0], [0])), shape=(dim, 1), dtype=complex)
return initial_state
def _embed_operator(self, operator: SpinOp, num_wires: int, qargs: List[int]) -> SpinOp:
"""
Turning a SpinOp operator that acts onto the wires given in qargs into an operator
that acts on the entire register of the circuit by manipulating the indices of the
sparse labels of the SpinOps.
Args:
operator: SpinOp describing the generating Hamiltonian of a gate
num_wires: The total number of wires in which the operator should be embedded into
qargs: The wire indices the gate acts on
Returns:
A SpinOp acting on the entire quantum register of the Circuit
Raises:
QiskitColdAtomError: - If the given operator is not a SpinOp
- If the size of the operator does not match the given qargs
"""
if not isinstance(operator, SpinOp):
raise QiskitColdAtomError(f"Expected SpinOp; got {type(operator).__name__} instead")
if operator.num_spins != len(qargs):
raise QiskitColdAtomError(
f"operator size {operator.num_spins} does not match qargs {qargs} of the gates."
)
embedded_op_dict = {}
for label, factor in operator._data.items():
old_labels = label.split()
new_labels = [term[:2] + str(qargs[int(term[2])]) + term[3:] for term in old_labels]
embedded_op_dict[" ".join(map(str, new_labels))] = factor
return SpinOp(embedded_op_dict, spin=self.spin, num_spins=num_wires)
def operator_to_mat(self, operator: SpinOp) -> csc_matrix:
"""
Convert a SpinOp describing a gate generator to a sparse matrix.
Args:
operator: spin operator of which to compute the matrix representation
Returns:
scipy.sparse matrix of the Hamiltonian
"""
return csc_matrix(operator.to_matrix())
def preprocess_circuit(self, circuit: QuantumCircuit):
r"""
Compute the Hilbert space dimension of the given quantum circuit as :math:`(2S+1)^N`
where :math:`S` is the length of the spin and :math:`N` is the number of spins in
the quantum circuit.
Args:
circuit: The circuit to pre-process.
"""
self._dim = int((2 * self.spin + 1) ** circuit.num_qubits)
def draw_shots(self, measurement_distribution: List[float]) -> List[str]:
r"""A helper function to draw counts from a given distribution of measurement outcomes.
Args:
measurement_distribution: List of probabilities of the individual measurement outcomes.
Returns:
outcome_memory: A list of individual measurement results, e.g. ["12 3 4", "0 4 9", ...]
The outcome of each shot is denoted by a space-delimited string "a1 a2 a3 ..." where
:math:`a_i` is the measured level of the spin with possible values ranging from 0 to 2S
The :math:`a_i` are in reverse order of the spins of the register to comply with qiskit's
little endian convention.
Raises:
QiskitColdAtomError:
- If the length of the given probabilities does not math the expected Hilbert
space dimension.
- If the dimension is not a power of the spin length of the solver.
- If the number of shots self.shots has not been specified.
"""
meas_dim = len(measurement_distribution)
if meas_dim != self.dim:
raise QiskitColdAtomError(
f"Dimension of the measurement probabilities {meas_dim} does not "
f"match the dimension expected by the solver, {self.dim}"
)
if self.shots is None:
raise QiskitColdAtomError(
"The number of shots has to be set before drawing measurements"
)
# Draw measurements as the indices of the basis states:
meas_results = np.random.choice(range(meas_dim), self.shots, p=measurement_distribution)
base = int(2 * self.spin + 1)
num_wires = math.log(meas_dim, base)
if num_wires.is_integer():
num_wires = int(num_wires)
else:
raise QiskitColdAtomError(
"The length of given measurement distribution it not compatible with "
"the spin-length of the solver."
)
outcome_memory = []
for meas_idx in meas_results:
digits = [0] * num_wires
for i in range(num_wires):
digits[i] = meas_idx % base
meas_idx //= base
outcome_memory.append(" ".join(map(str, digits)))
return outcome_memory
|
https://github.com/qiskit-community/qiskit-cold-atom
|
qiskit-community
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""General spin simulator backend."""
from typing import Union, List, Dict, Any, Optional
import uuid
from fractions import Fraction
import warnings
import time
import datetime
from qiskit.providers.models import BackendConfiguration
from qiskit.providers import Options
from qiskit import QuantumCircuit
from qiskit.result import Result
from qiskit.circuit.measure import Measure
from qiskit_aer import AerJob
from qiskit_cold_atom.spins.spin_circuit_solver import SpinCircuitSolver
from qiskit_cold_atom.spins.base_spin_backend import BaseSpinBackend
from qiskit_cold_atom.circuit_tools import CircuitTools
class SpinSimulator(BaseSpinBackend):
"""A simulator to simulate general spin circuits.
This general spin simulator backend simulates spin circuits with gates that have
generators described by spin Hamiltonians. It computes the statevector and unitary
of a circuit and simulates measurements.
"""
# Default configuration of the backend if the user does not provide one.
__DEFAULT_CONFIGURATION__ = {
"backend_name": "spin_simulator",
"backend_version": "0.0.1",
"n_qubits": None,
"basis_gates": None,
"gates": [],
"local": True,
"simulator": True,
"conditional": False,
"open_pulse": False,
"memory": True,
"max_shots": 1e5,
"coupling_map": None,
"description": "a base simulator for spin circuits. Instead of a qubit, each wire represents a "
"single high-dimensional spin",
}
def __init__(self, config_dict: Optional[Dict[str, Any]] = None, provider=None):
"""
Initialize the backend from a configuration dictionary.
Args:
config_dict: Configuration dictionary of the backend. If None is given
a default is assumed.
"""
if config_dict is None:
config_dict = self.__DEFAULT_CONFIGURATION__
super().__init__(
configuration=BackendConfiguration.from_dict(config_dict), provider=provider
)
@classmethod
def _default_options(cls):
return Options(shots=1)
def _execute(self, data: Dict[str, Any], job_id: str = "") -> Result:
"""
Helper function to execute a job. The circuit and all relevant parameters are
given in the data dict. Performs validation checks on the received circuits
and utilizes the SpinCircuitSolver to perform the numerical simulations.
Args:
data: Data dictionary that that contains the experiments to simulate, given in the shape:
data = {
"num_species": int,
"shots": int,
"seed": int,
"experiments": Dict[str, QuantumCircuit],
}
job_id: The job id assigned by the run method
Returns:
result: A qiskit job result.
"""
# Start timer
start = time.time()
output = {"results": []}
spin = data["spin"]
shots = data["shots"]
seed = data["seed"]
solver = SpinCircuitSolver(spin, shots, seed)
for exp_i, exp_name in enumerate(data["experiments"]):
experiment = data["experiments"][exp_name]
circuit = experiment["circuit"]
# perform compatibility checks with the backend configuration in case gates and supported
# instructions are constrained by the backend's configuration
if self.configuration().gates and self.configuration().supported_instructions:
CircuitTools.validate_circuits(circuits=circuit, backend=self, shots=shots)
# check whether all wires are measured
measured_wires = set()
for inst in circuit.data:
if isinstance(inst[0], Measure):
for wire in inst[1]:
index = circuit.qubits.index(wire)
if index in measured_wires:
warnings.warn(
f"Wire {index} has already been measured, "
f"second measurement is ignored"
)
else:
measured_wires.add(index)
if measured_wires and len(measured_wires) != len(circuit.qubits):
warnings.warn(
f"Number of wires in the circuit ({len(circuit.qubits)}) does not equal the "
f"number of wires with measurement instructions ({len(measured_wires)}). "
f"{self.__class__.__name__} only supports measurement of the entire quantum "
"register which will be performed instead."
)
if not measured_wires:
solver.shots = None
simulation_result = solver(circuit)
output["results"].append(
{
"header": {"name": exp_name, "random_seed": seed},
"shots": shots,
"spin": spin,
"status": "DONE",
"success": True,
}
)
# add the simulation result at the correct place in the result dictionary
output["results"][exp_i]["data"] = simulation_result
output["job_id"] = job_id
output["date"] = datetime.datetime.now().isoformat()
output["backend_name"] = self.name()
output["backend_version"] = self.configuration().backend_version
output["time_taken"] = time.time() - start
output["success"] = True
output["qobj_id"] = None
return Result.from_dict(output)
# pylint: disable=arguments-differ, unused-argument
def run(
self,
circuits: Union[QuantumCircuit, List[QuantumCircuit]],
shots: int = 1000,
spin: Union[float, Fraction] = Fraction(1, 2),
seed: Optional[int] = None,
**run_kwargs,
) -> AerJob:
"""
Run the simulator with a variable length of the individual spins.
Args:
circuits: A list of quantum circuits.
shots: The number of shots to measure.
spin: The spin length of the simulated system which must be a positive
integer or half-integer. Defaults to 1/2 which is equivalent to qubits.
seed: The seed for the simulator.
run_kwargs: Additional keyword arguments that might be passed down when calling
qiskit.execute() which will have no effect on this backend.
Returns:
aer_job: a job object containing the result of the simulation
"""
if isinstance(circuits, QuantumCircuit):
circuits = [circuits]
data = {"spin": spin, "shots": shots, "seed": seed, "experiments": {}}
for idx, circuit in enumerate(circuits):
data["experiments"]["experiment_%i" % idx] = {
"circuit": circuit,
}
job_id = str(uuid.uuid4())
aer_job = AerJob(self, job_id, self._execute, data)
aer_job.submit()
return aer_job
|
https://github.com/qiskit-community/qiskit-cold-atom
|
qiskit-community
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""tests for circuit_to_cold_atom functions"""
from typing import Dict
from qiskit import QuantumCircuit
from qiskit.test import QiskitTestCase
from qiskit.circuit import Parameter
from qiskit.providers import BackendV1 as Backend
from qiskit.providers.models import BackendConfiguration
from qiskit_cold_atom.exceptions import QiskitColdAtomError
from qiskit_cold_atom.circuit_tools import CircuitTools, WireOrder
# These imports are needed to decorate the quantum circuit
import qiskit_cold_atom.spins # pylint: disable=unused-import
import qiskit_cold_atom.fermions # pylint: disable=unused-import
class DummyBackend(Backend):
"""dummy backend class for test purposes only"""
def __init__(self, config_dict: Dict):
super().__init__(configuration=BackendConfiguration.from_dict(config_dict))
def run(self, run_input, **options):
pass
@classmethod
def _default_options(cls):
pass
class TestCircuitToColdAtom(QiskitTestCase):
"""circuit to cold atom tests."""
def setUp(self):
super().setUp()
# Set up a dummy backend from a configuration dictionary
test_config = {
"backend_name": "test_backend",
"backend_version": "0.0.1",
"simulator": True,
"local": True,
"coupling_map": None,
"description": "dummy backend for testing purposes only",
"basis_gates": ["hop, int"],
"memory": False,
"n_qubits": 5,
"conditional": False,
"max_shots": 100,
"max_experiments": 2,
"open_pulse": False,
"gates": [
{
"coupling_map": [[0], [1], [2], [3], [4]],
"name": "rlz",
"parameters": ["delta"],
"qasm_def": "gate rLz(delta) {}",
},
{
"coupling_map": [[0], [1], [2]],
"name": "rlz2",
"parameters": ["chi"],
"qasm_def": "gate rlz2(chi) {}",
},
{
"coupling_map": [[0], [1], [2], [3], [4]],
"name": "rlx",
"parameters": ["omega"],
"qasm_def": "gate rx(omega) {}",
},
],
"supported_instructions": [
"delay",
"rlx",
"rlz",
"rlz2",
"measure",
"barrier",
],
}
self.dummy_backend = DummyBackend(test_config)
def test_circuit_to_cold_atom(self):
"""test the circuit_to_cold_atom function"""
circ1 = QuantumCircuit(3)
circ1.rlx(0.5, [0, 1])
circ1.rlz(0.3, [1, 2])
circ1.measure_all()
circ2 = QuantumCircuit(2)
circ2.rlz2(0.5, 1)
circ2.measure_all()
shots = 10
target_output = {
"experiment_0": {
"instructions": [
["rlx", [0], [0.5]],
["rlx", [1], [0.5]],
["rlz", [1], [0.3]],
["rlz", [2], [0.3]],
["barrier", [0, 1, 2], []],
["measure", [0], []],
["measure", [1], []],
["measure", [2], []],
],
"num_wires": 3,
"shots": shots,
"wire_order": "sequential",
},
"experiment_1": {
"instructions": [
["rlz2", [1], [0.5]],
["barrier", [0, 1], []],
["measure", [0], []],
["measure", [1], []],
],
"num_wires": 2,
"shots": shots,
"wire_order": "sequential",
},
}
actual_output = CircuitTools.circuit_to_cold_atom(
[circ1, circ2], backend=self.dummy_backend, shots=shots
)
self.assertEqual(actual_output, target_output)
def test_validate_circuits(self):
"""test the validation of circuits against the backend configuration"""
with self.subTest("test size of circuit"):
circ = QuantumCircuit(6)
circ.rlx(0.4, 2)
with self.assertRaises(QiskitColdAtomError):
CircuitTools.validate_circuits(circ, backend=self.dummy_backend)
with self.subTest("test support of native instructions"):
circ = QuantumCircuit(4)
# add gate that is not supported by the backend
circ.fhop([0.5], [0, 1, 2, 3])
with self.assertRaises(QiskitColdAtomError):
CircuitTools.validate_circuits(circ, backend=self.dummy_backend)
with self.subTest("check gate coupling map"):
circ = QuantumCircuit(5)
circ.rlz2(0.5, 4)
with self.assertRaises(QiskitColdAtomError):
CircuitTools.validate_circuits(circ, backend=self.dummy_backend)
with self.subTest("test max. allowed circuits"):
circuits = [QuantumCircuit(2)] * 3
with self.assertRaises(QiskitColdAtomError):
CircuitTools.circuit_to_cold_atom(circuits=circuits, backend=self.dummy_backend)
with self.subTest("test max. allowed shots"):
circuits = QuantumCircuit(2)
with self.assertRaises(QiskitColdAtomError):
CircuitTools.circuit_to_cold_atom(
circuits=circuits, backend=self.dummy_backend, shots=1000
)
with self.subTest("test running with unbound parameters"):
theta = Parameter("θ")
circ = QuantumCircuit(1)
circ.rlx(theta, 0)
with self.assertRaises(QiskitColdAtomError):
CircuitTools.validate_circuits(circ, backend=self.dummy_backend)
def test_circuit_to_data(self):
"""test the circuit to data method"""
circ = QuantumCircuit(3)
circ.rlx(0.5, [0, 1])
circ.rlz(0.3, [1, 2])
circ.measure_all()
target_output = [
["rlx", [0], [0.5]],
["rlx", [1], [0.5]],
["rlz", [1], [0.3]],
["rlz", [2], [0.3]],
["barrier", [0, 1, 2], []],
["measure", [0], []],
["measure", [1], []],
["measure", [2], []],
]
actual_output = CircuitTools.circuit_to_data(circ, backend=self.dummy_backend)
self.assertEqual(actual_output, target_output)
def test_convert_wire_order(self):
"""test the convert_wire_order method"""
num_sites = 4
num_species = 3
# conversion rule: i -> (i % num_sites) * num_species + i // num_sites
wires_sequential = [0, 1, 4, 5, 8, 9]
wires_interleaved = [0, 3, 1, 4, 2, 5]
with self.subTest("test sequential to interleaved"):
wires_converted = CircuitTools.convert_wire_order(
wires=wires_sequential,
convention_from=WireOrder.SEQUENTIAL,
convention_to=WireOrder.INTERLEAVED,
num_sites=num_sites,
num_species=num_species,
)
self.assertEqual(wires_converted, wires_interleaved)
with self.subTest("test interleaved to sequential"):
wires_converted = CircuitTools.convert_wire_order(
wires=wires_interleaved,
convention_from=WireOrder.INTERLEAVED,
convention_to=WireOrder.SEQUENTIAL,
num_sites=num_sites,
num_species=num_species,
)
self.assertEqual(wires_converted, wires_sequential)
|
https://github.com/qiskit-community/qiskit-cold-atom
|
qiskit-community
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Fermionic circuit solver tests."""
import numpy as np
from qiskit import QuantumCircuit
from qiskit.test import QiskitTestCase
from qiskit_nature.second_q.operators import FermionicOp, SpinOp
from qiskit_cold_atom.fermions.fermion_circuit_solver import (
FermionCircuitSolver,
FermionicBasis,
)
from qiskit_cold_atom.fermions.fermion_gate_library import Hop
from qiskit_cold_atom.exceptions import QiskitColdAtomError
# Black import needed to decorate the quantum circuit with spin gates.
import qiskit_cold_atom.spins # pylint: disable=unused-import
class TestFermionCircuitSolver(QiskitTestCase):
"""class to test the FermionCircuitSolver class."""
def setUp(self):
super().setUp()
# Setup two solvers with different number of fermionic species
self.solver1 = FermionCircuitSolver()
self.solver2 = FermionCircuitSolver(num_species=2)
def test_basis_setter(self):
"""test max. dimension of the basis"""
self.solver1.max_dimension = 500
with self.assertRaises(QiskitColdAtomError):
self.solver1.basis = FermionicBasis(sites=12, n_particles=6)
def test_preprocess_circuit(self):
"""test the preprocessing of the circuit"""
circ = QuantumCircuit(4, 4)
circ.fload([0, 2])
circ.fhop([0.5], [0, 1, 2, 3])
with self.subTest("spin conserving circuit"):
self.solver2.preprocess_circuit(circ)
self.assertEqual(self.solver2._dim, 4)
with self.subTest("non spin conserving circuit"):
self.solver1.preprocess_circuit(circ)
self.assertEqual(self.solver1._dim, 6)
def test_get_initial_state(self):
"""test initialization of the state for the simulation"""
circ = QuantumCircuit(4, 4)
circ.fload([0, 3])
self.solver2.preprocess_circuit(circ)
init_state = self.solver2.get_initial_state(circ)
target = np.array([0, 0, 1, 0])
self.assertTrue(np.all(init_state.toarray().T == target))
def test_embed_operator(self):
"""test embedding of an operator"""
fer_op = FermionicOp({"+_0 -_1": 1.0})
spin_op = SpinOp({"X_0 Y_1": 1})
num_wires = 4
qargs = [1, 3]
qargs_wrong = [0, 1, 3]
with self.subTest("check operator type"):
with self.assertRaises(QiskitColdAtomError):
self.solver1._embed_operator(spin_op, num_wires, qargs)
with self.subTest("check operator wiring"):
with self.assertRaises(QiskitColdAtomError):
self.solver1._embed_operator(fer_op, num_wires, qargs_wrong)
with self.subTest("operator embedding"):
embedded_op = self.solver1._embed_operator(fer_op, num_wires, qargs)
target_op = FermionicOp({"+_1 -_3": 1.0}, num_spin_orbitals=4)
self.assertTrue(embedded_op.simplify() == target_op.simplify())
def test_conservation_checks(self):
"""test the checks for conservation of spin-species."""
with self.subTest("check operator type"):
circ = QuantumCircuit(4, 4)
circ.fhop([0.5], [0, 1, 2, 3])
circ.rlx(0.5, 0) # apply gate with a SpinOp generator
with self.assertRaises(QiskitColdAtomError):
self.solver1._check_conservations(circ)
with self.subTest("check compatibility with number of species"):
circ = QuantumCircuit(5, 5)
circ.fhop([0.5], [0, 1, 2, 3])
self.assertTrue(self.solver1._check_conservations(circ) == (True, True))
with self.assertRaises(QiskitColdAtomError):
self.solver2._check_conservations(circ)
with self.subTest("spin conserved"):
circ = QuantumCircuit(4, 4)
circ.fload([0, 3])
circ.fhop([0.5], [0, 1, 2, 3])
self.assertTrue(self.solver2._check_conservations(circ) == (True, True))
with self.subTest("spin not conserved"):
circ = QuantumCircuit(4, 4)
circ.fload([0, 3])
circ.fhop([0.5], [0, 1, 2, 3])
circ.frx(0.3, [0, 2]) # non spin-conserving gate
self.assertTrue(self.solver2._check_conservations(circ) == (True, False))
def test_operator_to_mat(self):
"""test matrix representation of fermionic gates"""
with self.subTest("check operator type"):
spin_op = SpinOp({"X_0 Y_1": 1.0})
with self.assertRaises(QiskitColdAtomError):
self.solver1.operator_to_mat(spin_op)
circ = QuantumCircuit(4, 4)
circ.fload([0, 3])
circ.fhop([0.5], [0, 1, 2, 3])
with self.subTest("check dimensionality of operator"):
self.solver2.preprocess_circuit(circ)
fer_op_wrong = FermionicOp({"+_0 -_1": 1.0}, num_spin_orbitals=3)
fer_op_correct = FermionicOp({"+_0 -_1": 1.0}, num_spin_orbitals=4)
with self.assertRaises(QiskitColdAtomError):
self.solver2.operator_to_mat(fer_op_wrong)
self.solver2.operator_to_mat(fer_op_correct)
with self.subTest("test matrix representation"):
self.solver2.preprocess_circuit(circ)
target = np.array(
[
[0.0, -0.5, -0.5, 0.0],
[-0.5, 0.0, 0.0, -0.5],
[-0.5, 0.0, 0.0, -0.5],
[0.0, -0.5, -0.5, 0.0],
]
)
test_op = self.solver2.operator_to_mat(Hop(num_modes=4, j=[0.5]).generator)
self.assertTrue(np.all(test_op.toarray() == target))
def test_draw_shots(self):
"""test drawing of the shots from a measurement distribution"""
circ = QuantumCircuit(4, 4)
circ.fload([0, 3])
circ.fhop([0.5], [0, 1, 2, 3])
self.solver2.preprocess_circuit(circ)
with self.subTest("check missing shot number"):
# error because the number of shots is not specified
with self.assertRaises(QiskitColdAtomError):
self.solver2.draw_shots(np.ones(4) / 4)
self.solver2.shots = 5
with self.subTest("check match of dimensions"):
# error because there is a mismatch in the dimension
with self.assertRaises(QiskitColdAtomError):
self.solver2.draw_shots(np.ones(3) / 3)
with self.subTest("formatting of measurement outcomes"):
self.solver2.seed = 40
outcomes = self.solver2.draw_shots(np.ones(4) / 4)
self.assertEqual(outcomes, ["0110", "0101", "1010", "0110", "0110"])
def test_to_operators(self):
"""test the to_operators method inherited form BaseCircuitSolver"""
test_circ = QuantumCircuit(4, 4)
test_circ.fload([0, 3])
test_circ.fhop([0.5], [0, 1, 2, 3])
test_circ.fint(1.0, [0, 1, 2, 3])
test_circ.measure_all()
with self.subTest("test ignore barriers"):
self.solver1.ignore_barriers = False
with self.assertRaises(NotImplementedError):
self.solver1.to_operators(test_circ)
self.solver1.ignore_barriers = True
with self.subTest("check for gate generators"):
qubit_circ = QuantumCircuit(1)
qubit_circ.h(0)
with self.assertRaises(QiskitColdAtomError):
self.solver1.to_operators(qubit_circ)
with self.subTest("gate after previous measurement instruction"):
meas_circ = QuantumCircuit(4, 4)
meas_circ.measure_all()
meas_circ.fhop([0.5], [0, 1, 2, 3])
with self.assertRaises(QiskitColdAtomError):
self.solver1.to_operators(meas_circ)
with self.subTest("check returned operators"):
operators = self.solver1.to_operators(test_circ)
target_ops = [
FermionicOp(
{
"+_0 -_1": -0.5,
"-_0 +_1": 0.5,
"+_2 -_3": -0.5,
"-_2 +_3": 0.5,
},
num_spin_orbitals=4,
),
FermionicOp({"+_0 -_0 +_2 -_2": 1, "+_1 -_1 +_3 -_3": 1}, num_spin_orbitals=4),
]
for op, target in zip(operators, target_ops):
self.assertTrue(op == target)
def test_call_method(self):
"""test the call method inherited form BaseCircuitSolver that simulates a circuit"""
test_circ = QuantumCircuit(4)
test_circ.fload([0, 3])
test_circ.fhop([np.pi / 4], [0, 1, 2, 3])
test_circ.fint(np.pi, [0, 1, 2, 3])
with self.subTest("running the circuit"):
self.solver2.shots = 5
self.solver2.seed = 40
simulation = self.solver2(test_circ)
self.assertEqual(simulation["memory"], ["0110", "0101", "1010", "0110", "0110"])
self.assertEqual(simulation["counts"], {"1010": 1, "0110": 3, "0101": 1})
self.assertTrue(
np.allclose(simulation["statevector"], np.array([-0.5j, -0.5, 0.5, -0.5j]))
)
self.assertTrue(
np.allclose(
simulation["unitary"],
np.array(
[
[-0.5, -0.5j, -0.5j, 0.5],
[0.5j, 0.5, -0.5, 0.5j],
[0.5j, -0.5, 0.5, 0.5j],
[0.5, -0.5j, -0.5j, -0.5],
]
),
)
)
with self.subTest("check for maximum dimension"):
self.solver2.max_dimension = 3
with self.assertRaises(QiskitColdAtomError):
simulation = self.solver2(test_circ)
self.solver2.max_dimension = 100
with self.subTest("check if shots are specified"):
self.solver2.shots = None
simulation = self.solver2(test_circ)
self.assertEqual(simulation["memory"], [])
self.assertEqual(simulation["counts"], {})
|
https://github.com/qiskit-community/qiskit-cold-atom
|
qiskit-community
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""General fermionic simulator backend tests."""
from time import sleep
import numpy as np
from qiskit import QuantumCircuit, QuantumRegister
from qiskit.providers import JobStatus
from qiskit.result import Result
from qiskit.test import QiskitTestCase
from qiskit_aer import AerJob
from qiskit_nature.second_q.operators import FermionicOp
from qiskit_cold_atom.exceptions import QiskitColdAtomError
from qiskit_cold_atom.fermions.base_fermion_backend import BaseFermionBackend
from qiskit_cold_atom.fermions.fermion_gate_library import FermionicGate
from qiskit_cold_atom.fermions.fermion_simulator_backend import FermionSimulator
class TestFermionSimulatorBackend(QiskitTestCase):
"""class to test the FermionSimulatorBackend class."""
def setUp(self):
super().setUp()
self.backend = FermionSimulator()
def test_initialization(self):
"""test the initialization of the backend"""
target_config = {
"backend_name": "fermion_simulator",
"backend_version": "0.0.1",
"n_qubits": 20,
"basis_gates": None,
"gates": [],
"local": False,
"simulator": True,
"conditional": False,
"open_pulse": False,
"memory": True,
"max_shots": 1e5,
"coupling_map": None,
"description": r"a base simulator for fermionic circuits. Instead of qubits, "
r"each wire represents a single fermionic mode",
}
backend = FermionSimulator()
self.assertIsInstance(backend, BaseFermionBackend)
self.assertTrue(target_config.items() <= backend.configuration().to_dict().items())
def test_run_method(self):
"""Test the run method of the backend simulator"""
with self.subTest("test call"):
circ = self.backend.initialize_circuit([[0, 1], [1, 0]])
job = self.backend.run(circ)
self.assertIsInstance(job, AerJob)
self.assertIsInstance(job.job_id(), str)
self.assertIsInstance(job.result(), Result)
sleep(0.01)
self.assertEqual(job.status(), JobStatus.DONE)
circ1 = self.backend.initialize_circuit([[0, 1], [1, 0]])
circ2 = self.backend.initialize_circuit([[1, 1], [1, 0]])
with self.subTest("test call with multiple circuits"):
job = self.backend.run([circ1, circ2])
self.assertIsInstance(job, AerJob)
with self.subTest("test shot number"):
target_shots = 123
job = self.backend.run([circ1, circ2], shots=target_shots)
for exp in job.result().results:
self.assertEqual(exp.shots, target_shots)
with self.subTest("test seed of RNG"):
target_seed = 123
job = self.backend.run([circ1, circ2], seed=target_seed)
for exp in job.result().results:
self.assertEqual(exp.header.random_seed, target_seed)
with self.subTest("test number of fermionic species"):
# define a circuit that conserves the particle number per fermionic spin species
test_circ = QuantumCircuit(4)
test_circ.fload([0, 3])
test_circ.fhop([np.pi / 4], [0, 1, 2, 3])
statevector_1 = self.backend.run(test_circ).result().get_statevector()
self.assertEqual(len(statevector_1), 6)
# check whether specifying the number of species reduces the dimension of the simulation
statevector_2 = self.backend.run(test_circ, num_species=2).result().get_statevector()
self.assertEqual(len(statevector_2), 4)
def test_execute(self):
"""test the ._execute() method internally called by .run()"""
with self.subTest("test partial measurement"):
circ_meas = QuantumCircuit(2, 2)
circ_meas.fload(0)
circ_meas.measure(0, 0)
with self.assertWarns(UserWarning):
self.backend.run(circ_meas)
test_circ = QuantumCircuit(4)
test_circ.fload([0, 3])
test_circ.fhop([np.pi / 4], [0, 1, 2, 3])
test_circ.fint(np.pi, [0, 1, 2, 3])
test_circ.measure_all()
result = self.backend.run(test_circ, num_species=2, seed=40, shots=5).result()
with self.subTest("test simulation counts"):
self.assertEqual(result.get_counts(), {"1010": 1, "0110": 3, "0101": 1})
with self.subTest("test simulation memory"):
self.assertEqual(result.get_memory(), ["0110", "0101", "1010", "0110", "0110"])
with self.subTest("test simulation statevector"):
self.assertTrue(
np.allclose(result.get_statevector(), np.array([-0.5j, -0.5, 0.5, -0.5j]))
)
with self.subTest("test simulation unitary"):
self.assertTrue(
np.allclose(
result.get_unitary(),
np.array(
[
[-0.5, -0.5j, -0.5j, 0.5],
[0.5j, 0.5, -0.5, 0.5j],
[0.5j, -0.5, 0.5, 0.5j],
[0.5, -0.5j, -0.5j, -0.5],
]
),
)
)
with self.subTest("test time taken"):
self.assertTrue(result.to_dict()["time_taken"] < 0.1)
with self.subTest("test result success"):
self.assertTrue(result.to_dict()["success"])
def test_initialize_circuit(self):
"""test of initialize_circuit inherited from the abstract base class BaseFermionBackend"""
with self.subTest("Initialize circuit with single species of fermions"):
actual_circ = self.backend.initialize_circuit([0, 1, 0, 1])
target_circ = QuantumCircuit(QuantumRegister(4, "fer_mode"))
target_circ.fload(1)
target_circ.fload(3)
self.assertEqual(actual_circ, target_circ)
with self.subTest("Initialize circuit with multiple species of fermions"):
actual_circ = self.backend.initialize_circuit([[0, 1], [0, 1]])
target_circ = QuantumCircuit(QuantumRegister(2, "spin_0"), QuantumRegister(2, "spin_1"))
target_circ.fload(1)
target_circ.fload(3)
self.assertEqual(actual_circ, target_circ)
with self.subTest("check maximum size of circuit"):
with self.assertRaises(QiskitColdAtomError):
self.backend.initialize_circuit(np.ones(30, dtype=int).tolist())
def test_measure_observable_expectation(self):
"""test of the measure_observable_expectation method inherited from the abstract base class
BaseFermionBackend"""
with self.subTest("test error for non-diagonal observables"):
non_diag_observable = FermionicOp({"+_0 -_1 +_2 -_2": 1.0}, num_spin_orbitals=4)
test_circ = self.backend.initialize_circuit([0, 1, 0, 1])
with self.assertRaises(QiskitColdAtomError):
self.backend.measure_observable_expectation(
test_circ, non_diag_observable, shots=10
)
with self.subTest("test match of dimensionality"):
observable_too_small = FermionicOp({"+_0 -_1": 1.0}, num_spin_orbitals=2)
test_circ = self.backend.initialize_circuit([0, 1, 0, 1])
with self.assertRaises(QiskitColdAtomError):
self.backend.measure_observable_expectation(
test_circ, observable_too_small, shots=10
)
with self.subTest("test single measurement circuit"):
observable_1 = FermionicOp({"+_1 -_1 -_2 +_2": 1}, num_spin_orbitals=4)
observable_2 = FermionicOp({"+_1 -_1": 1}, num_spin_orbitals=4) + FermionicOp(
{"-_2 +_2": 1}, num_spin_orbitals=4
)
observable_3 = FermionicOp({"+_0 -_0 +_1 -_1": 1}, num_spin_orbitals=4)
eval_1 = self.backend.measure_observable_expectation(
circuits=self.backend.initialize_circuit([0, 1, 0, 1]),
observable=observable_1,
shots=1,
)
eval_2 = self.backend.measure_observable_expectation(
circuits=self.backend.initialize_circuit([0, 1, 0, 1]),
observable=observable_2,
shots=1,
)
eval_3 = self.backend.measure_observable_expectation(
circuits=self.backend.initialize_circuit([0, 1, 0, 1]),
observable=observable_3,
shots=1,
)
self.assertEqual(eval_1, [1.0])
self.assertEqual(eval_2, [2.0])
self.assertEqual(eval_3, [0.0])
with self.subTest("test multiple measurement circuits"):
test_circ_1 = self.backend.initialize_circuit([0, 1, 0, 1])
test_circ_2 = self.backend.initialize_circuit([1, 0, 0, 1])
observable = FermionicOp({"+_1 -_1 -_2 +_2": 1}, num_spin_orbitals=4)
expval = self.backend.measure_observable_expectation(
[test_circ_1, test_circ_2], observable, shots=1
)
self.assertEqual(expval, [1.0, 0.0])
def test_parameterized_circuits(self):
"""Test that parameterized circuits work."""
from qiskit.circuit import Parameter
theta = Parameter("theta")
test_circ = QuantumCircuit(4)
test_circ.fload([0, 3])
test_circ.fhop([theta], [0, 1, 2, 3])
with self.subTest("test running with unbound parameters:"):
with self.assertRaises(TypeError):
self.assertTrue(isinstance(self.backend.run(test_circ).result(), Result))
with self.subTest("test running with bound parameters"):
bound_circ = test_circ.assign_parameters([0.2])
self.assertTrue(isinstance(self.backend.run(bound_circ).result(), Result))
def test_permutation_invariance(self):
"""Test that a permutation-invariant gate doesn't care about qubit order."""
generator = FermionicOp(
{"+_0 -_1": 1, "+_1 -_0": 1},
num_spin_orbitals=2,
)
gate = FermionicGate(name="test", num_modes=2, generator=generator)
circuit01 = self.backend.initialize_circuit([1, 0])
circuit01.append(gate, [0, 1])
vec01 = self.backend.run(circuit01).result().get_statevector()
circuit10 = self.backend.initialize_circuit([1, 0])
circuit10.append(gate, [1, 0])
vec10 = self.backend.run(circuit10).result().get_statevector()
np.testing.assert_allclose(vec01, vec10)
|
https://github.com/qiskit-community/qiskit-cold-atom
|
qiskit-community
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
""" Fermionic state tests."""
from qiskit import QuantumCircuit
from qiskit.test import QiskitTestCase
from qiskit_cold_atom.exceptions import QiskitColdAtomError
from qiskit_cold_atom.fermions.fermion_circuit_solver import FermionicState
class TestFermionState(QiskitTestCase):
"""Class to test the fermion state class."""
def test_initialize(self):
"""Test the initialization of fermionic states."""
state = FermionicState([0, 1, 1, 0])
self.assertEqual(state.sites, 4)
self.assertEqual(state.num_species, 1)
with self.assertRaises(QiskitColdAtomError):
FermionicState([0, 2])
with self.assertRaises(QiskitColdAtomError):
FermionicState([[0, 1], [1, 0, 1]])
state = FermionicState([[0, 1, 0], [1, 0, 1]])
self.assertEqual(state.occupations_flat, [0, 1, 0, 1, 0, 1])
self.assertEqual(state.num_species, 2)
def test_string(self):
"""Test the string representation."""
state = FermionicState([0, 1])
self.assertEqual(str(state), "|0, 1>")
state = FermionicState([[0, 1], [1, 0]])
self.assertEqual(str(state), "|0, 1>|1, 0>")
def test_occupations(self):
"""Test that to get the fermionic occupations."""
state = FermionicState([0, 1])
self.assertEqual(state.occupations, [[0, 1]])
def test_from_flat_list(self):
"""Test the creation of fermionic states from flat lists."""
state = FermionicState.from_total_occupations([0, 1, 1, 0], 2)
self.assertEqual(state.occupations, [[0, 1], [1, 0]])
with self.assertRaises(QiskitColdAtomError):
FermionicState.from_total_occupations([0, 1, 1, 0], 3)
state = FermionicState.from_total_occupations([0, 1, 1, 0], 1)
self.assertEqual(state.occupations, [[0, 1, 1, 0]])
def test_from_initial_state(self):
"""Test that we can load an initial state from a circuit."""
circ = QuantumCircuit(4)
circ.fload(0)
circ.fload(2)
state = FermionicState.initial_state(circ, 2)
self.assertEqual(state.occupations, [[1, 0], [1, 0]])
self.assertEqual(state.occupations_flat, [1, 0, 1, 0])
state = FermionicState.initial_state(circ, 1)
self.assertEqual(state.occupations, [[1, 0, 1, 0]])
self.assertEqual(state.occupations_flat, [1, 0, 1, 0])
|
https://github.com/qiskit-community/qiskit-cold-atom
|
qiskit-community
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Spin circuit solver tests"""
import numpy as np
from qiskit import QuantumCircuit
from qiskit.test import QiskitTestCase
from qiskit_nature.second_q.operators import FermionicOp, SpinOp
from qiskit_cold_atom.spins.spin_circuit_solver import SpinCircuitSolver
from qiskit_cold_atom.exceptions import QiskitColdAtomError
class TestSpinCircuitSolver(QiskitTestCase):
"""class to test the SpinCircuitSolver class."""
def setUp(self):
super().setUp()
# Set up the simulator
self.solver = SpinCircuitSolver(spin=3 / 2)
def test_spin_solver_initialization(self):
"""test constructor of SpinCircuitSolver"""
with self.assertRaises(QiskitColdAtomError):
SpinCircuitSolver(spin=2 / 3)
def test_get_initial_state(self):
"""test initialization of the state for the simulation"""
circ = QuantumCircuit(1)
init_state = self.solver.get_initial_state(circ)
target = np.array([1, 0, 0, 0])
self.assertTrue(np.all(init_state.toarray().T == target))
def test_embed_operator(self):
"""test embedding of an operator"""
fer_op = FermionicOp({"+_0 -_1": 1}, num_spin_orbitals=2)
# define a spin operator that has terms with different prefactors, support and power
spin_op = SpinOp(
{"X_0 X_1": 1, "Y_0 X_1": 1j, "X_0 Y_1": -1j, "Y_0 Y_1": 1}, num_spins=2
) + 2 * SpinOp({"X_0^2": 1}, num_spins=2)
num_wires = 4
qargs = [1, 3]
qargs_wrong = [0, 1, 3]
with self.subTest("check operator type"):
with self.assertRaises(QiskitColdAtomError):
self.solver._embed_operator(fer_op, num_wires, qargs)
with self.subTest("check operator wiring"):
with self.assertRaises(QiskitColdAtomError):
self.solver._embed_operator(spin_op, num_wires, qargs_wrong)
with self.subTest("operator embedding"):
embedded_op = self.solver._embed_operator(spin_op, num_wires, qargs)
target_op = SpinOp(
{"X_1 X_3": 1, "Y_1 X_3": 1j, "X_1 Y_3": -1j, "Y_1 Y_3": 1, "X_1^2": 2.0},
spin=3 / 2,
num_spins=4,
)
self.assertTrue(
np.allclose(embedded_op.simplify().to_matrix(), target_op.simplify().to_matrix())
)
def test_preprocess_circuit(self):
"""test whether preprocessing of the circuit correctly sets the dimension"""
circ = QuantumCircuit(2)
self.solver.preprocess_circuit(circ)
self.assertEqual(self.solver.dim, 4**2)
def test_draw_shots(self):
"""test drawing of the shots from a measurement distribution"""
n_spins = 5
circ = QuantumCircuit(n_spins)
circ.rly(np.pi / 2, [3])
self.solver.preprocess_circuit(circ)
dim = int((2 * self.solver.spin + 1) ** n_spins)
with self.subTest("check missing shot number"):
# error because the number of shots is not specified
with self.assertRaises(QiskitColdAtomError):
self.solver.draw_shots(np.ones(dim) / dim)
self.solver.shots = 3
with self.subTest("check match of dimensions"):
# error because there is a mismatch in the dimension
with self.assertRaises(QiskitColdAtomError):
self.solver.draw_shots(np.ones(dim - 1) / (dim - 1))
with self.subTest("formatting of measurement outcomes"):
meas_distr = np.abs(self.solver(circ)["statevector"]) ** 2
self.solver.seed = 45
outcomes = self.solver.draw_shots(meas_distr)
# Note the second index changing with the gate being applied to wire [3] of 5
self.assertEqual(outcomes, ["0 3 0 0 0", "0 2 0 0 0", "0 1 0 0 0"])
def test_to_operators(self):
"""test the to_operators method inherited form BaseCircuitSolver"""
test_circ = QuantumCircuit(2)
test_circ.rlx(0.5, [0, 1])
test_circ.rlz2(0.25, 1)
test_circ.measure_all()
with self.subTest("test ignore barriers"):
self.solver.ignore_barriers = False
with self.assertRaises(NotImplementedError):
self.solver.to_operators(test_circ)
self.solver.ignore_barriers = True
with self.subTest("check for gate generators"):
qubit_circ = QuantumCircuit(1)
qubit_circ.h(0)
with self.assertRaises(QiskitColdAtomError):
self.solver.to_operators(qubit_circ)
with self.subTest("gate after previous measurement instruction"):
meas_circ = QuantumCircuit(2)
meas_circ.measure_all()
meas_circ.rlx(0.5, 0)
with self.assertRaises(QiskitColdAtomError):
self.solver.to_operators(meas_circ)
with self.subTest("check returned operators"):
operators = self.solver.to_operators(test_circ)
target = [
SpinOp({"X_0": (0.5 + 0j)}, spin=3 / 2, num_spins=2),
SpinOp({"X_1": (0.5 + 0j)}, spin=3 / 2, num_spins=2),
SpinOp({"Z_1^2": (0.25 + 0j)}, spin=3 / 2, num_spins=2),
]
for i, op in enumerate(operators):
self.assertTrue(
np.allclose(op.simplify().to_matrix(), target[i].simplify().to_matrix())
)
def test_call_method(self):
"""test the call method inherited from BaseCircuitSolver that simulates a circuit"""
test_circ = QuantumCircuit(1)
test_circ.rlx(np.pi / 2, 0)
test_circ.measure_all()
with self.subTest("running the circuit"):
self.solver.shots = 5
self.solver.seed = 45
simulation = self.solver(test_circ)
self.assertEqual(simulation["memory"], ["3", "2", "1", "0", "1"])
self.assertEqual(simulation["counts"], {"0": 1, "1": 2, "2": 1, "3": 1})
self.assertTrue(
np.allclose(
simulation["statevector"],
np.array(
[
np.sqrt(1 / 8),
-1j * np.sqrt(3 / 8),
-np.sqrt(3 / 8),
1j * np.sqrt(1 / 8),
]
),
)
)
self.assertTrue(
np.allclose(
simulation["unitary"],
np.array(
[
[
np.sqrt(1 / 8),
-1j * np.sqrt(3 / 8),
-np.sqrt(3 / 8),
1j * np.sqrt(1 / 8),
],
[
-1j * np.sqrt(3 / 8),
-np.sqrt(1 / 8),
-1j * np.sqrt(1 / 8),
-np.sqrt(3 / 8),
],
[
-np.sqrt(3 / 8),
-1j * np.sqrt(1 / 8),
-np.sqrt(1 / 8),
-1j * np.sqrt(3 / 8),
],
[
1j * np.sqrt(1 / 8),
-np.sqrt(3 / 8),
-1j * np.sqrt(3 / 8),
np.sqrt(1 / 8),
],
]
),
)
)
with self.subTest("check for maximum dimension"):
self.solver.max_dimension = 3
with self.assertRaises(QiskitColdAtomError):
self.solver(test_circ)
self.solver.max_dimension = 100
with self.subTest("check if shots are specified"):
self.solver.shots = None
simulation = self.solver(test_circ)
self.assertEqual(simulation["memory"], [])
self.assertEqual(simulation["counts"], {})
self.solver.shots = 5
multiple_wire_circ = QuantumCircuit(2)
multiple_wire_circ.rlx(np.pi / 2, [0])
multiple_wire_circ.rlz(-np.pi / 2, [0, 1])
with self.subTest("formatting of multiple wires"):
self.solver.seed = 45
simulation = self.solver(multiple_wire_circ)
self.assertTrue(simulation["memory"], ["0 3", "0 2", "0 1", "0 0", "0 1"])
self.assertTrue(simulation["counts"], {"0 2": 1, "0 0": 1, "0 3": 1, "0 1": 2})
with self.subTest("check equivalence to qubits for spin-1/2"):
from qiskit_aer import AerSimulator
qubit_circ = QuantumCircuit(2)
qubit_circ.rx(np.pi / 2, [0])
qubit_circ.rz(-np.pi / 2, [0, 1])
qubit_circ.save_unitary()
qubit_backend = AerSimulator()
job = qubit_backend.run(qubit_circ)
qubit_unitary = job.result().get_unitary()
spin_half_solver = SpinCircuitSolver(spin=1 / 2)
simulation = spin_half_solver(multiple_wire_circ)
spin_unitary = simulation["unitary"]
# Switch some axes in the spin simulator unitary because the basis of qiskit_nature.SpinOp
# uses an ordering of the states (00, 10, 01, 11) that is different from qiskit Aer which
# uses (00, 01, 10, 11)
spin_unitary[[1, 2]] = spin_unitary[[2, 1]]
spin_unitary[:, [1, 2]] = spin_unitary[:, [2, 1]]
self.assertTrue(np.allclose(qubit_unitary, spin_unitary))
|
https://github.com/qiskit-community/qiskit-cold-atom
|
qiskit-community
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
""" Spin gate tests."""
import numpy as np
from scipy.linalg import expm
from qiskit.test import QiskitTestCase
from qiskit import QuantumCircuit
from qiskit_nature.second_q.operators import SpinOp
from qiskit_cold_atom.spins.spin_circuit_solver import SpinCircuitSolver
from qiskit_cold_atom.spins import SpinSimulator
from qiskit_cold_atom.spins.spins_gate_library import (
RLXGate,
RLYGate,
RLZGate,
RLZ2Gate,
RLXLYGate,
RydbergBlockade,
RydbergFull,
)
class TestSpinGates(QiskitTestCase):
"""Tests for the spin hardware gates"""
def setUp(self):
super().setUp()
self.backend = SpinSimulator()
self.spin = 3 / 2
self.solver = SpinCircuitSolver(spin=self.spin)
def test_lx_gate(self):
"""check matrix form of the lx gate"""
omega = np.pi / 2
circ = QuantumCircuit(1)
circ.append(RLXGate(omega), qargs=[0])
# add gate to circuit via the @add_gate-decorated method
circ_decorated = QuantumCircuit(1)
circ_decorated.rlx(omega, 0)
for circuit in [circ, circ_decorated]:
unitary = self.backend.run(circuit, spin=self.spin).result().get_unitary()
self.assertTrue(
np.allclose(
unitary,
expm(
-1j
* omega
* np.array(
[
[0.0, np.sqrt(3) / 2, 0, 0],
[np.sqrt(3) / 2, 0, 1, 0],
[0, 1, 0, np.sqrt(3) / 2],
[0, 0, np.sqrt(3) / 2, 0],
]
)
),
)
)
def test_lxly_gate(self):
"""check matrix form of the lxly gate"""
omega = np.pi
circ = QuantumCircuit(2)
circ.append(RLXLYGate(omega), qargs=[0, 1])
# add gate to circuit via the @add_gate-decorated method
circ_decorated = QuantumCircuit(2)
circ_decorated.rlxly(omega, [0, 1])
for circuit in [circ, circ_decorated]:
unitary = self.backend.run(circuit, spin=1 / 2).result().get_unitary()
self.assertTrue(
np.allclose(
unitary,
[
[1, 0, 0, 0],
[0, 0, -1j, 0],
[0, -1j, 0, 0],
[0, 0, 0, 1],
],
)
)
def test_ly_gate(self):
"""check matrix form of the ly gate"""
omega = np.pi / 2
circ = QuantumCircuit(1)
circ.append(RLYGate(omega), qargs=[0])
# add gate to circuit via the @add_gate-decorated method
circ_decorated = QuantumCircuit(1)
circ_decorated.rly(omega, 0)
for circuit in [circ, circ_decorated]:
unitary = self.backend.run(circuit, spin=self.spin).result().get_unitary()
self.assertTrue(
np.allclose(
unitary,
expm(
-1j
* omega
* np.array(
[
[0.0, -1j * np.sqrt(3) / 2, 0, 0],
[1j * np.sqrt(3) / 2, 0, -1j, 0],
[0, 1j, 0, -1j * np.sqrt(3) / 2],
[0, 0, 1j * np.sqrt(3) / 2, 0],
]
)
),
)
)
def test_lz_gate(self):
"""check matrix form of the lz gate"""
delta = np.pi / 2
circ = QuantumCircuit(1)
circ.append(RLZGate(delta), qargs=[0])
# add gate to circuit via the @add_gate-decorated method
circ_decorated = QuantumCircuit(1)
circ_decorated.rlz(delta, 0)
for circuit in [circ, circ_decorated]:
unitary = self.backend.run(circuit, spin=self.spin).result().get_unitary()
self.assertTrue(
np.allclose(
unitary,
expm(
-1j
* delta
* np.array(
[
[3 / 2, 0, 0, 0],
[0, 1 / 2, 0, 0],
[0, 0, -1 / 2, 0],
[0, 0, 0, -3 / 2],
]
)
),
)
)
def test_lz2_gate(self):
"""check matrix form of the lz2 gate"""
chi = np.pi / 2
circ = QuantumCircuit(1)
circ.append(RLZ2Gate(chi), qargs=[0])
# add gate to circuit via the @add_gate-decorated method
circ_decorated = QuantumCircuit(1)
circ_decorated.rlz2(chi, 0)
for circuit in [circ, circ_decorated]:
unitary = self.backend.run(circuit, spin=self.spin).result().get_unitary()
self.assertTrue(
np.allclose(
unitary,
expm(
-1j
* chi
* np.array(
[
[3 / 2, 0, 0, 0],
[0, 1 / 2, 0, 0],
[0, 0, -1 / 2, 0],
[0, 0, 0, -3 / 2],
]
)
** 2
),
)
)
def test_rydberg_block_gate(self):
"""check matrix form of the rydberg blockade gate on two qubits"""
chi = 2 * np.pi
# the expected unitary is the following
expected = np.exp(1j * np.pi / 2) * expm(
-1j
* chi
* np.array(
[
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 1],
]
)
)
# first test the RydbergBlockade only
with self.subTest("test generation of operator"):
from qiskit.quantum_info import Operator
self.assertTrue(np.allclose(Operator(RydbergBlockade(2, phi=chi)).data, expected))
# add gate to circuit via the @add_gate-decorated method
circ_decorated = QuantumCircuit(2)
circ_decorated.rydberg_block(chi, [0, 1])
unitary = self.backend.run(circ_decorated).result().get_unitary()
self.assertTrue(np.allclose(unitary, expected))
def test_rydberg_full_gate(self):
"""check matrix form of the full rydberg Hamiltonian on two qubits"""
chi = 2 * np.pi
circ = QuantumCircuit(2)
circ.append(RydbergFull(2, omega=0, delta=0, phi=chi), qargs=[0, 1])
# add gate to circuit via the @add_gate-decorated method
circ_decorated = QuantumCircuit(2)
circ_decorated.rydberg_full(omega=0, delta=0, phi=chi, modes=range(2))
for circuit in [circ, circ_decorated]:
unitary = self.backend.run(circuit).result().get_unitary()
self.assertTrue(
np.allclose(
unitary,
np.exp(1j * np.pi / 2)
* expm(
-1j
* chi
* np.array(
[
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 1],
]
)
),
)
)
# also test the sigma gates
circ = QuantumCircuit(2)
circ.append(RydbergFull(2, omega=np.pi, delta=0, phi=0), qargs=[0, 1])
# add gate to circuit via the @add_gate-decorated method
circ_decorated = QuantumCircuit(2)
circ_decorated.rydberg_full(omega=np.pi, delta=0, phi=0, modes=range(2))
for circuit in [circ, circ_decorated]:
unitary = self.backend.run(circuit).result().get_unitary()
self.assertTrue(
np.allclose(
unitary,
expm(
-1j
* np.pi
/ 2
* np.array(
[
[0, 1, 1, 0],
[1, 0, 0, 1],
[1, 0, 0, 1],
[0, 1, 1, 0],
]
)
),
)
)
# also test the sigmaz gates
circ = QuantumCircuit(2)
circ.append(RydbergFull(2, omega=0, delta=np.pi, phi=0), qargs=[0, 1])
# add gate to circuit via the @add_gate-decorated method
circ_decorated = QuantumCircuit(2)
circ_decorated.rydberg_full(omega=0, delta=np.pi, phi=0, modes=range(2))
for circuit in [circ, circ_decorated]:
unitary = self.backend.run(circuit).result().get_unitary()
self.assertTrue(
np.allclose(
unitary,
expm(
-1j
* np.pi
/ 2
* np.array(
[
[-2, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 2],
]
)
),
)
)
def test_spin_gate(self):
"""test the functionality of the base class for fermionic gates"""
test_gates = [RLXGate(0.8), RLYGate(2.4), RLZGate(5.6), RLZ2Gate(1.3)]
with self.subTest("test to_matrix and power"):
for gate in test_gates:
exp_matrix = gate.to_matrix() @ gate.to_matrix()
exp_gate = gate.power(2)
self.assertTrue(np.allclose(exp_matrix, exp_gate.to_matrix()))
with self.subTest("test generation of operator"):
from qiskit.quantum_info import Operator
for gate in test_gates:
self.assertTrue(isinstance(Operator(gate), Operator))
def test_identity_gates(self):
"""test that gates with parameters equal to zero still have a well-defined generator."""
test_gates = [RLXGate(0.0), RLYGate(0.0), RLZGate(0.0), RLZ2Gate(0.0)]
for gate in test_gates:
self.assertIsInstance(gate.generator, SpinOp)
|
https://github.com/qiskit-community/qiskit-cold-atom
|
qiskit-community
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""General spin simulator backend tests."""
from time import sleep
import numpy as np
from qiskit import QuantumCircuit
from qiskit.providers import JobStatus
from qiskit.result import Result
from qiskit.test import QiskitTestCase
from qiskit_aer import AerJob
from qiskit_cold_atom.exceptions import QiskitColdAtomError
from qiskit_cold_atom.spins import SpinSimulator
from qiskit_cold_atom.spins.base_spin_backend import BaseSpinBackend
class TestSpinSimulatorBackend(QiskitTestCase):
"""class to test the FermionSimulatorBackend class."""
def setUp(self):
super().setUp()
self.backend = SpinSimulator()
def test_initialization(self):
"""test the initialization of the backend"""
target_config = {
"backend_name": "spin_simulator",
"backend_version": "0.0.1",
"n_qubits": None,
"basis_gates": None,
"gates": [],
"local": True,
"simulator": True,
"conditional": False,
"open_pulse": False,
"memory": True,
"max_shots": 1e5,
"coupling_map": None,
"description": "a base simulator for spin circuits. Instead of a qubit, each wire "
"represents a single high-dimensional spin",
}
backend = SpinSimulator()
self.assertIsInstance(backend, BaseSpinBackend)
self.assertTrue(target_config.items() <= backend.configuration().to_dict().items())
def test_run_method(self):
"""Test the run method of the backend simulator"""
with self.subTest("test call"):
circ = QuantumCircuit(2)
job = self.backend.run(circ)
self.assertIsInstance(job, AerJob)
self.assertIsInstance(job.job_id(), str)
self.assertIsInstance(job.result(), Result)
self.assertEqual(job.status(), JobStatus.DONE)
circ1 = QuantumCircuit(2)
circ2 = QuantumCircuit(3)
with self.subTest("test call with multiple circuits"):
job = self.backend.run([circ1, circ2])
self.assertIsInstance(job, AerJob)
with self.subTest("test shot number"):
target_shots = 123
job = self.backend.run([circ1, circ2], shots=target_shots)
for exp in job.result().results:
self.assertEqual(exp.shots, target_shots)
with self.subTest("test seed of RNG"):
target_seed = 123
job = self.backend.run([circ1, circ2], seed=target_seed)
for exp in job.result().results:
self.assertEqual(exp.header.random_seed, target_seed)
with self.subTest("test dimension of simulation"):
test_circ = QuantumCircuit(2)
test_circ.rlx(np.pi / 2, 0)
test_circ.rly(np.pi / 4, [0, 1])
statevector_1 = self.backend.run(test_circ, spin=1).result().get_statevector()
self.assertEqual(len(statevector_1), 3**2)
statevector_2 = self.backend.run(test_circ, spin=5 / 2).result().get_statevector()
self.assertEqual(len(statevector_2), 6**2)
with self.subTest("test irregular spin values"):
test_circ = QuantumCircuit(2)
job = self.backend.run(test_circ, spin=5 / 4)
sleep(0.01)
self.assertIs(job.status(), JobStatus.ERROR)
with self.assertRaises(QiskitColdAtomError):
job.result()
def test_execute(self):
"""test the ._execute() method internally called by .run()"""
test_circ = QuantumCircuit(2)
test_circ.rly(np.pi / 2, 0)
test_circ.rlx(np.pi / 2, 1)
test_circ.measure_all()
result = self.backend.run(test_circ, spin=1, seed=45, shots=5).result()
with self.subTest("test simulation counts"):
self.assertEqual(result.get_counts(), {"0 1": 1, "2 2": 1, "1 1": 2, "1 0": 1})
with self.subTest("test simulation memory"):
self.assertEqual(result.get_memory(), ["2 2", "1 1", "0 1", "1 0", "1 1"])
with self.subTest("test simulation statevector"):
self.assertTrue(
np.allclose(
result.get_statevector(),
np.array(
[
1 / 4,
-1j / np.sqrt(8),
-1 / 4,
1 / np.sqrt(8),
-1j / 2,
-1 / np.sqrt(8),
1 / 4,
-1j / np.sqrt(8),
-1 / 4,
]
),
)
)
with self.subTest("test simulation unitary"):
# test the unitary on a single spin-2 example
test_circ = QuantumCircuit(1)
test_circ.rlx(np.pi / 2, 0)
test_circ.rlz(np.pi / 2, 0)
test_circ.measure_all()
result = self.backend.run(test_circ, spin=2, seed=45, shots=5).result()
self.assertTrue(
np.allclose(
result.get_unitary(),
np.array(
[
[-0.25, 0.5j, np.sqrt(3 / 8), -0.5j, -0.25],
[-0.5, 0.5j, 0.0, 0.5j, 0.5],
[-np.sqrt(3 / 8), 0.0, -0.5, 0.0, -np.sqrt(3 / 8)],
[-0.5, -0.5j, 0.0, -0.5j, 0.5],
[-0.25, -0.5j, np.sqrt(3 / 8), 0.5j, -0.25],
]
),
)
)
with self.subTest("test time taken"):
self.assertTrue(result.to_dict()["time_taken"] < 0.5)
with self.subTest("test result success"):
self.assertTrue(result.to_dict()["success"])
|
https://github.com/qiskit-community/qiskit-cold-atom
|
qiskit-community
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Testing module for transpiling."""
import numpy as np
from qiskit import QuantumCircuit
from qiskit.transpiler import PassManager
from qiskit.test import QiskitTestCase
from qiskit_cold_atom.transpiler import Optimize1SpinGates
# pylint: disable=no-member
class TestSpinTranspilation(QiskitTestCase):
"""Test class for spin-based transpilation."""
def test_optimize_1s_gates(self):
"""Test the single-spin gate transpilation."""
circ = QuantumCircuit(1)
circ.rlx(np.pi / 2, 0)
circ.rlx(np.pi / 2, 0)
circ.rlx(np.pi / 2, 0)
circ.rly(np.pi / 2, 0)
circ.rly(np.pi / 2, 0)
circ.rlz2(np.pi / 4, 0)
circ.rlz2(np.pi / 4, 0)
circ.rlz2(np.pi / 4, 0)
circ.rlx(np.pi / 2, 0)
pass_manager = PassManager(Optimize1SpinGates())
circ_new = pass_manager.run(circ)
self.assertEqual(circ_new.count_ops()["rlx"], 2)
self.assertEqual(circ_new.count_ops()["rly"], 1)
self.assertEqual(circ_new.count_ops()["rlz2"], 1)
self.assertTrue(np.allclose(circ_new.data[0][0].params[0], 3 * np.pi / 2))
self.assertTrue(np.allclose(circ_new.data[1][0].params[0], np.pi))
self.assertTrue(np.allclose(circ_new.data[2][0].params[0], 3 * np.pi / 4))
self.assertTrue(np.allclose(circ_new.data[3][0].params[0], np.pi / 2))
def test_optimize_1s_gates_multi_spin(self):
"""Test the single-spin gate transpilation."""
circ = QuantumCircuit(2)
circ.rlx(np.pi / 3, 0)
circ.rlx(np.pi / 3, 0)
circ.rlx(np.pi / 3, 0)
circ.rly(np.pi / 4, 1)
circ.rly(np.pi / 4, 1)
pass_manager = PassManager(Optimize1SpinGates())
circ_new = pass_manager.run(circ)
self.assertEqual(circ_new.count_ops()["rlx"], 1)
self.assertEqual(circ_new.count_ops()["rly"], 1)
self.assertTrue(np.allclose(circ_new.data[0][0].params[0], np.pi))
self.assertTrue(np.allclose(circ_new.data[1][0].params[0], np.pi / 2))
|
https://github.com/qiskit-community/qiskit-pocket-guide
|
qiskit-community
|
from qiskit import QuantumCircuit
QuantumCircuit(2)
QuantumCircuit(2, 2)
import math
qc = QuantumCircuit(4)
qc.h(0)
qc.id(2)
qc.i(2)
qc.p(math.pi/2,0)
qc.rx(math.pi/4,2)
qc.ry(math.pi/8,0)
qc.rz(math.pi/2,1)
qc.s(3)
qc.sdg(3)
qc.sx(2)
qc.t(1)
qc.tdg(1)
qc.u(math.pi/2,0,math.pi,1)
qc.x(3)
qc.y([0,2,3])
qc.z(2)
qc = QuantumCircuit(4)
qc.h(0)
qc.id(2)
qc.p(math.pi/2,0)
qc.rx(math.pi/4,2)
qc.ry(math.pi/8,0)
qc.rz(math.pi/2,1)
qc.s(3)
qc.sdg(3)
qc.sx(2)
qc.t(1)
qc.tdg(1)
qc.u(math.pi/2,0,math.pi,1)
qc.x(3)
qc.y([0,2,3])
qc.z(2)
qc.draw('mpl')
qc.ccx(0,1,2)
qc.ch(0,1)
qc.cp(math.pi/4,0,1)
qc.crx(math.pi/2,2,3)
qc.crz(math.pi/4,0,1)
qc.cswap(0,2,3)
qc.fredkin(0,2,3)
qc.csx(0,1)
qc.cu(math.pi/2,0,math.pi,0,0,1)
qc.cx(2,3)
qc.cnot(2,3)
qc.cy(2,3)
qc.cz(1,2)
qc.dcx(2,3)
qc.iswap(0,1)
qc.mcp(math.pi/4,[0,1,2],3)
qc.mcx([0,1,2],3)
qc.swap(2,3)
qc = QuantumCircuit(4)
qc.ccx(0,1,2)
qc.ch(0,1)
qc.cp(math.pi/4,0,1)
qc.crx(math.pi/2,2,3)
qc.crz(math.pi/4,0,1)
qc.cswap(0,2,3)
qc.csx(0,1)
qc.cu(math.pi/2,0,math.pi,0,0,1)
qc.cx(2,3)
qc.cy(2,3)
qc.cz(1,2)
qc.dcx(2,3)
qc.iswap(0,1)
qc.mcp(math.pi/4,[0,1,2],3)
qc.mcx([0,1,2],3)
qc.swap(2,3)
qc.draw('mpl')
qc = QuantumCircuit(3)
qc.h(0)
qc.cx(0, 1)
qc.cx(0, 2)
qc.draw('mpl')
qc = QuantumCircuit(2)
qc.h([0,1])
qc.barrier()
qc.x(0)
qc.x(0)
qc.s(1)
qc.barrier([1])
qc.s(1)
qc.draw('mpl')
qc = QuantumCircuit(3, 3)
qc.h([0,1,2])
qc.measure([0,1,2], [0,1,2])
qc.draw('mpl')
qc = QuantumCircuit(3)
qc.h([0,1,2])
qc.measure_all()
qc.draw('mpl')
qc.depth()
qc.size()
qc.width()
qc.clbits
qc.data
qc.global_phase
qc.num_clbits
qc.num_qubits
qc.qubits
from qiskit.circuit.library import CXGate
qc = QuantumCircuit(2)
qc.h(1)
cx_gate = CXGate()
qc.append(cx_gate, [1,0])
qc.draw()
from qiskit.circuit import QuantumCircuit,\
Parameter
theta1 = Parameter('θ1')
theta2 = Parameter('θ2')
theta3 = Parameter('θ3')
qc = QuantumCircuit(3)
qc.h([0,1,2])
qc.p(theta1,0)
qc.p(theta2,1)
qc.p(theta3,2)
qc.draw()
b_qc = qc.bind_parameters({theta1: math.pi/8,
theta2: math.pi/4,
theta3: math.pi/2})
b_qc.draw()
qc = QuantumCircuit(2,2)
qc.h(0)
another_qc = QuantumCircuit(2,2)
another_qc.cx(0,1)
bell_qc = qc.compose(another_qc)
bell_qc.draw()
qc = QuantumCircuit(2)
qc.h(0)
qc.s(0)
qc.x(1)
decomposed_qc = qc.decompose()
decomposed_qc.draw()
qasm_str = """
OPENQASM 2.0;
include "qelib1.inc";
qreg q[2];
creg c[2];
h q[0];
cx q[0],q[1];
measure q[0] -> c[0];
measure q[1] -> c[1];
"""
new_qc = QuantumCircuit.from_qasm_str(qasm_str)
new_qc.draw()
qc = QuantumCircuit(2)
qc.initialize([0, 0, 0, 1])
qc.draw()
qc = QuantumCircuit(1)
qc.x(0)
qc.reset(0)
qc.draw()
anti_cnot_qc = QuantumCircuit(2)
anti_cnot_qc.x(0)
anti_cnot_qc.cx(0,1)
anti_cnot_qc.x(0)
anti_cnot_qc.draw()
anti_cnot_gate = anti_cnot_qc.to_gate()
qc = QuantumCircuit(3)
qc.x([0,1,2])
qc.append(anti_cnot_gate, [0,2])
qc.decompose().draw()
reset_one_qc = QuantumCircuit(1)
reset_one_qc.reset(0)
reset_one_qc.x(0)
reset_one_qc.draw()
reset_one_inst = reset_one_qc.to_instruction()
qc = QuantumCircuit(2)
qc.h([0,1])
qc.reset(0)
qc.append(reset_one_inst, [1])
qc.decompose().draw()
from qiskit import QuantumRegister, \
ClassicalRegister
qr = QuantumRegister(3, 'q')
scratch = QuantumRegister(1, 'scratch')
cr = ClassicalRegister(3, 'c')
qc = QuantumCircuit(qr, scratch, cr)
qc.h(qr)
qc.x(scratch)
qc.h(scratch)
qc.cx(qr[0], scratch)
qc.cx(qr[2], scratch)
qc.barrier(qr)
qc.h(qr)
qc.measure(qr, cr)
qc.draw()
|
https://github.com/qiskit-community/qiskit-pocket-guide
|
qiskit-community
|
from qiskit.circuit.library import CCXGate
toffoli = CCXGate()
print(toffoli.num_ctrl_qubits)
toffoli = CCXGate()
toffoli.ctrl_state = 2
toffoli.definition.draw()
from qiskit import QuantumCircuit
import math
p16_qc = QuantumCircuit(1)
p16_qc.p(math.pi/16, 0)
p16_gate = p16_qc.to_gate()
p16_gate.definition.draw()
ctrl_p16 = p16_gate.control(2)
ctrl_p16.definition.draw()
qc = QuantumCircuit(4)
qc.h([0,1,2,3])
qc.append(ctrl_p16,[0,1,3])
qc.decompose().draw()
|
https://github.com/qiskit-community/qiskit-pocket-guide
|
qiskit-community
|
from qiskit.circuit import QuantumCircuit,\
ParameterVector
theta = ParameterVector('θ', 3)
qc = QuantumCircuit(3)
qc.h([0,1,2])
qc.p(theta[0],0)
qc.p(theta[1],1)
qc.p(theta[2],2)
qc.draw()
import math
b_qc = qc.bind_parameters({theta: [math.pi/8,
math.pi/4,
math.pi/2]})
b_qc.draw()
|
https://github.com/qiskit-community/qiskit-pocket-guide
|
qiskit-community
|
from qiskit import BasicAer
print(BasicAer.backends())
from qiskit import QuantumCircuit,BasicAer,transpile
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
qc.measure_all()
backend = BasicAer.get_backend("qasm_simulator")
tqc = transpile(qc, backend)
job = backend.run(tqc, shots=1000)
result = job.result()
counts = result.get_counts(tqc)
print(counts)
from qiskit import QuantumCircuit,BasicAer,transpile
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
backend = BasicAer.get_backend("statevector_simulator")
tqc = transpile(qc, backend)
job = backend.run(tqc)
result = job.result()
statevector = result.get_statevector(tqc, 4)
print(statevector)
from qiskit import QuantumCircuit,BasicAer,transpile
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
backend = BasicAer.get_backend("unitary_simulator")
tqc = transpile(qc, backend)
job = backend.run(tqc)
result = job.result()
unitary = result.get_unitary(tqc, 4)
print(unitary)
|
https://github.com/qiskit-community/qiskit-pocket-guide
|
qiskit-community
|
from qiskit import Aer
print(Aer.backends())
from qiskit import QuantumCircuit,Aer,transpile
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
qc.measure_all()
backend = Aer.get_backend("aer_simulator")
tqc = transpile(qc, backend)
job = backend.run(tqc, shots=1000)
result = job.result()
counts = result.get_counts(tqc)
print(counts)
from qiskit import QuantumCircuit,Aer,transpile
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
backend = Aer.get_backend("aer_simulator")
qc.save_statevector()
tqc = transpile(qc, backend)
job = backend.run(tqc)
result = job.result()
statevector = result.get_statevector(tqc, 4)
print(statevector)
from qiskit import QuantumCircuit,Aer,transpile
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
backend = Aer.get_backend("aer_simulator")
qc.save_unitary()
tqc = transpile(qc, backend)
job = backend.run(tqc)
result = job.result()
unitary = result.get_unitary(qc, 4)
print(unitary)
from qiskit import QuantumCircuit, Aer, transpile
from qiskit.providers.aer.noise import \
NoiseModel, depolarizing_error
err_1 = depolarizing_error(0.95, 1)
err_2 = depolarizing_error(0.01, 2)
noise_model = NoiseModel()
noise_model.add_all_qubit_quantum_error(err_1,
['u1', 'u2', 'u3'])
noise_model.add_all_qubit_quantum_error(err_2,
['cx'])
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
qc.measure_all()
backend = Aer.get_backend("aer_simulator")
backend.set_options(noise_model=noise_model)
tqc = transpile(qc, backend)
job = backend.run(tqc, shots=1000)
result = job.result()
counts = result.get_counts(tqc)
print(counts)
from qiskit import QuantumCircuit, transpile
from qiskit.providers.aer import AerSimulator
from qiskit.test.mock import FakeVigo
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
qc.measure_all()
device_backend = FakeVigo()
backend = AerSimulator.from_backend(device_backend)
tqc = transpile(qc, backend)
job = backend.run(tqc, shots=1000)
result = job.result()
counts = result.get_counts(tqc)
print(counts)
|
https://github.com/qiskit-community/qiskit-pocket-guide
|
qiskit-community
|
from qiskit import QuantumCircuit,Aer,transpile
from qiskit.visualization import plot_histogram
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
qc.measure_all()
backend = Aer.get_backend("aer_simulator")
tqc = transpile(qc, backend)
job = backend.run(tqc, shots=1000)
result = job.result()
counts = result.get_counts(tqc)
plot_histogram(counts)
|
https://github.com/qiskit-community/qiskit-pocket-guide
|
qiskit-community
|
from qiskit import QuantumCircuit,Aer,transpile
from qiskit.visualization import plot_state_qsphere
from math import pi
backend = Aer.get_backend("aer_simulator_statevector")
qc = QuantumCircuit(3)
qc.rx(pi, 0)
qc.ry(pi/8, 2)
qc.swap(0, 2)
qc.h(0)
qc.cp(pi/2,0, 1)
qc.cp(pi/4, 0, 2)
qc.h(1)
qc.cp(pi/2, 1, 2)
qc.h(2)
qc.save_statevector()
tqc = transpile(qc, backend)
job = backend.run(tqc)
result = job.result()
statevector = result.get_statevector()
plot_state_qsphere(statevector)
from qiskit.quantum_info import DensityMatrix, \
Operator
from qiskit.visualization import plot_state_city
dens_mat = 0.5*DensityMatrix.from_label('11') + \
0.5*DensityMatrix.from_label('+0')
tt_op = Operator.from_label('TT')
dens_mat = dens_mat.evolve(tt_op)
plot_state_city(dens_mat)
from qiskit import QuantumCircuit,Aer,transpile
from qiskit.visualization import plot_bloch_multivector
from math import pi
backend = Aer.get_backend("aer_simulator_statevector")
qc = QuantumCircuit(3)
qc.rx(pi, 0)
qc.ry(pi/8, 2)
qc.swap(0, 2)
qc.h(0)
qc.cp(pi/2,0, 1)
qc.cp(pi/4, 0, 2)
qc.h(1)
qc.cp(pi/2, 1, 2)
qc.h(2)
qc.save_statevector()
tqc = transpile(qc, backend)
job = backend.run(tqc)
result = job.result()
statevector = result.get_statevector()
plot_bloch_multivector(statevector)
from qiskit.quantum_info import DensityMatrix, \
Operator
from qiskit.visualization import plot_state_hinton
dens_mat = 0.5*DensityMatrix.from_label('11') + \
0.5*DensityMatrix.from_label('+0')
tt_op = Operator.from_label('TT')
dens_mat = dens_mat.evolve(tt_op)
plot_state_hinton(dens_mat)
from qiskit.quantum_info import DensityMatrix, \
Operator
from qiskit.visualization import plot_state_paulivec
dens_mat = 0.5*DensityMatrix.from_label('11') + \
0.5*DensityMatrix.from_label('+0')
tt_op = Operator.from_label('TT')
dens_mat = dens_mat.evolve(tt_op)
plot_state_paulivec(dens_mat)
|
https://github.com/qiskit-community/qiskit-pocket-guide
|
qiskit-community
|
from qiskit import QuantumCircuit
from qiskit.quantum_info import Statevector
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
statevector = Statevector(qc)
print(statevector.data)
import numpy as np
from qiskit.quantum_info import Statevector
statevector = Statevector([1, 0, 0, 1] / np.sqrt(2))
print(statevector.data)
from qiskit.quantum_info import Statevector
statevector = Statevector.from_label('01-')
print(statevector.data)
from qiskit.quantum_info import Statevector
statevector = Statevector.from_label('+-')
print(statevector.data)
statevector.draw("qsphere")
print(statevector.probabilities())
print(statevector.sample_counts(1000))
from qiskit import QuantumCircuit
from qiskit.quantum_info import DensityMatrix
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
qc.z(1)
dens_mat = DensityMatrix(qc)
print(dens_mat.data)
from qiskit.quantum_info import DensityMatrix, \
Operator
dens_mat = 0.5*DensityMatrix.from_label('11') + \
0.5*DensityMatrix.from_label('+0')
print(dens_mat.data)
tt_op = Operator.from_label('TT')
dens_mat = dens_mat.evolve(tt_op)
dens_mat.draw('city')
print(dens_mat.probabilities())
print(dens_mat.sample_counts(1000))
|
https://github.com/qiskit-community/qiskit-pocket-guide
|
qiskit-community
|
from qiskit import QuantumCircuit
from qiskit.quantum_info import Operator
qc = QuantumCircuit(2)
qc.id(0)
qc.x(1)
op_XI = Operator(qc)
print(op_XI.data)
from qiskit.quantum_info import Operator
op_XI = Operator([[0, 0, 1, 0],
[0, 0, 0, 1],
[1, 0, 0, 0],
[0, 1, 0, 0]])
print(op_XI.data)
from qiskit.quantum_info import Operator, Pauli
op_XI = Operator(Pauli('XI'))
print(op_XI.data)
from qiskit.quantum_info import Operator
from qiskit.circuit.library.standard_gates \
import CPhaseGate
import numpy as np
op_CP = Operator(CPhaseGate(np.pi / 4))
print(op_CP.data)
from qiskit.quantum_info import Pauli
pauli_piXZ = Pauli('-XZ')
print(pauli_piXZ.to_matrix())
from qiskit import QuantumCircuit
from qiskit.quantum_info import Pauli
qc = QuantumCircuit(2)
qc.z(0)
qc.x(1)
pauli_XZ = Pauli(qc)
print(pauli_XZ.equiv(Pauli('-XZ')))
|
https://github.com/qiskit-community/qiskit-pocket-guide
|
qiskit-community
|
from qiskit import QuantumCircuit
from qiskit.quantum_info import Kraus
import numpy as np
noise_ops = [np.sqrt(0.9) * np.array([[1, 0],
[0, 1]]),
np.sqrt(0.1) * np.array([[0, 1],
[1, 0]])]
kraus = Kraus(noise_ops)
qc = QuantumCircuit(2)
qc.append(kraus, [0])
qc.append(kraus, [1])
qc.measure_all()
qc.draw()
from qiskit import Aer, transpile
backend = Aer.get_backend("aer_simulator")
tqc = transpile(qc, backend)
job = backend.run(tqc, shots=1000)
result = job.result()
counts = result.get_counts(tqc)
print(counts)
|
https://github.com/qiskit-community/qiskit-pocket-guide
|
qiskit-community
|
from qiskit.quantum_info import Statevector
from qiskit.quantum_info import Statevector, \
Operator, state_fidelity
sv_a = Statevector.from_label('+')
sv_b = sv_a.evolve(Operator.from_label('T'))
print(state_fidelity(sv_a, sv_b))
|
https://github.com/qiskit-community/qiskit-pocket-guide
|
qiskit-community
|
from qiskit.opflow import Zero, One
state = One ^ Zero ^ One ^ Zero ^ Zero
print(state)
from qiskit.opflow import X, Z
pauli_piXZ = -(X ^ Z)
print(pauli_piXZ)
print(pauli_piXZ.to_matrix())
from qiskit.opflow import I, X, H, CX
op = (CX ^ I) @ (I ^ CX) @ (I ^ I ^ H)
print(op)
from qiskit.quantum_info import Statevector
qc = op.to_circuit()
sv = Statevector(qc)
print(sv.sample_counts(1000))
|
https://github.com/qiskit-community/qiskit-pocket-guide
|
qiskit-community
|
from qiskit.opflow.state_fns import StateFn
statefn = StateFn('10100')
print(statefn)
from qiskit import QuantumCircuit
qc = QuantumCircuit(3)
qc.h(0)
qc.cx(0, 1)
qc.cx(1, 2)
statefn = StateFn(qc)
print(statefn)
import numpy as np
statefn = StateFn([1, 0, 0, 1] / np.sqrt(2))
print(statefn)
from qiskit.opflow.state_fns import StateFn
from qiskit.opflow import One, Zero
statefn_a = StateFn('100', is_measurement=True)
print('statefn_a:', statefn_a, statefn_a.is_measurement)
statefn_b = ~(One ^ Zero ^ Zero)
print('statefn_b:', statefn_b, statefn_b.is_measurement)
|
https://github.com/qiskit-community/qiskit-pocket-guide
|
qiskit-community
|
from qiskit.opflow.primitive_ops import PrimitiveOp
from qiskit.quantum_info import Pauli
primop_piXZ = PrimitiveOp(Pauli('-XZ'))
print(primop_piXZ)
print(type(primop_piXZ))
from qiskit.opflow import X, Z
pauli_piXZ = -(X ^ Z)
print(type(pauli_piXZ))
print(primop_piXZ.primitive
.equiv(pauli_piXZ.primitive))
from qiskit import QuantumCircuit
qc = QuantumCircuit(3)
qc.h([0,1,2])
h_primop = PrimitiveOp(qc)
print(h_primop)
print(type(h_primop))
from qiskit.opflow import H
hgates = H^3
print(hgates)
print(type(hgates))
|
https://github.com/qiskit-community/qiskit-quantinuum-provider
|
qiskit-community
|
import numpy as np
from qiskit import QuantumCircuit, execute
from qiskit_quantinuum import Quantinuum
from qiskit.visualization import plot_histogram
# Quantinuum.save_account(user_name="first.last@company.com")
Quantinuum.save_account(user_name="megan.l.kohagen@quantinuum.com")
Quantinuum.load_account()
Quantinuum.backends()
device = 'H1-2E'
backend = Quantinuum.get_backend(device)
status = backend.status()
print(device, "status :", status.status_msg)
n_qubits = 2
circuit = QuantumCircuit(n_qubits, n_qubits, name='Bell Test')
circuit.h(0)
circuit.cx(0, 1)
circuit.measure_all()
circuit.draw()
shots = 100
job = execute(circuit, backend, shots=shots)
job.status()
result = job.result()
print("Job ID:", result.job_id)
print("Job success:", result.success)
counts = result.get_counts()
print("Total count for 00 and 11 are:",counts)
# Result should not be '0', it should be '00'!
plot_histogram(counts)
import json
with open(f'results_{result.job_id}.json', 'w') as f:
json.dump(result.get_counts(), f)
device = 'H1-2E'
job_id = 'insert job id'
backend = Quantinuum.get_backend(device)
job = backend.retrieve_job(job_id)
result = job.result()
counts = result.get_counts()
print(counts)
device = 'H1'
shots = 100
backend = Quantinuum.get_backend(device)
job = execute(circuit, backend, shots=shots)
result = job.result()
counts = result.get_counts()
print(counts)
|
https://github.com/qiskit-community/qiskit-quantinuum-provider
|
qiskit-community
|
# 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.
# Copyright 2019-2020 Quantinuum, Intl. (www.quantinuum.com)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Module for interfacing with a Quantinuum Backend."""
import logging
import warnings
from qiskit.circuit import QuantumCircuit
from qiskit.providers import BackendV1
from qiskit.providers.models import BackendStatus
from qiskit.providers import Options
from qiskit.utils import deprecate_arguments
from qiskit import qobj as qobj_mod
from qiskit import pulse
from qiskit_quantinuum.exceptions import QiskitError
from .quantinuumjob import QuantinuumJob
logger = logging.getLogger(__name__)
class QuantinuumBackend(BackendV1):
"""Backend class interfacing with a Quantinuum backend."""
def __init__(self, name, configuration, provider, api):
"""Initialize remote backend for Quantinuum Quantum Computer.
Args:
name (String): name of backend.
configuration (BackendConfiguration): backend configuration
provider (QuantinuumProvider): provider.
api (QuantinuumClient): API client instance to use for backend
communication
"""
super().__init__(configuration=configuration, provider=provider)
self._api = api
self._name = name
@classmethod
def _default_options(cls):
return Options(shots=1024, priority='normal')
@deprecate_arguments({'qobj': 'run_input'})
def run(self, run_input, **kwargs):
"""Run a circuit on the backend.
Args:
run_input (QuantumCircuit|list): A QuantumCircuit or a list of
QuantumCircuit objects to run on the backend
Returns:
HoneywelJob: a handle to the async execution of the circuit(s) on
the backend
Raises:
QiskitError: If a pulse schedule is passed in for ``run_input``
"""
if isinstance(run_input, qobj_mod.QasmQobj):
warnings.warn("Passing in a QASMQobj object to run() is "
"deprecated and will be removed in a future "
"release", DeprecationWarning)
job = QuantinuumJob(self, None, self._api, circuits=run_input)
elif isinstance(run_input, (qobj_mod.PulseQobj, pulse.Schedule)):
raise QiskitError("Pulse jobs are not accepted")
else:
if isinstance(run_input, QuantumCircuit):
run_input = [run_input]
job_config = {}
for kwarg in kwargs:
if not hasattr(self.options, kwarg):
warnings.warn(
"Option %s is not used by this backend" % kwarg,
UserWarning, stacklevel=2)
else:
job_config[kwarg] = kwargs[kwarg]
if 'shots' not in job_config:
job_config['shots'] = self.options.shots
job_config['priority'] = self.options.priority
job = QuantinuumJob(self, None, self._api, circuits=run_input,
job_config=job_config)
job.submit()
return job
def retrieve_job(self, job_id):
""" Returns the job associated with the given job_id """
job = QuantinuumJob(self, job_id, self._api)
return job
def retrieve_jobs(self, job_ids):
""" Returns a list of jobs associated with the given job_ids """
return [QuantinuumJob(self, job_id, self._api) for job_id in job_ids]
def status(self):
"""Return the online backend status.
Returns:
BackendStatus: The status of the backend.
Raises:
LookupError: If status for the backend can't be found.
QuantinuumBackendError: If the status can't be formatted properly.
"""
api_status = self._api.backend_status(self.name())
try:
return BackendStatus.from_dict(api_status)
except QiskitError as ex:
raise LookupError(
"Couldn't get backend status: {0}".format(ex)
)
def name(self):
return self._name
|
https://github.com/qiskit-community/qiskit-quantinuum-provider
|
qiskit-community
|
# 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.
# Copyright 2019-2020 Quantinuum, Intl. (www.quantinuum.com)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# pylint: disable=arguments-differ
"""QuantinuumJob module
This module is used for creating asynchronous job objects for Quantinuum.
"""
import asyncio
import json
import logging
from collections import Counter
from datetime import datetime, timezone
from time import sleep
import nest_asyncio
import websockets
from qiskit.assembler.disassemble import disassemble
from qiskit.providers import JobV1, JobError
from qiskit.providers.jobstatus import JOB_FINAL_STATES, JobStatus
from qiskit import qobj as qobj_mod
from qiskit.result import Result
from .apiconstants import ApiJobStatus
from .api import QuantinuumClient
logger = logging.getLogger(__name__)
# Because Qiskit is often used with the Jupyter notebook who runs its own asyncio event loop
# (via Tornado), we must be able to apply our own event loop. This is something that is done
# in the IBMQ provider as well
nest_asyncio.apply()
class QuantinuumJob(JobV1):
"""Representation of a job that will be execute on a Quantinuum backend.
Represent the jobs that will be executed on Quantinuum devices. Jobs are
intended to be created calling ``run()`` on a particular backend.
Currently jobs that are created using a qobj can only have one experiment
in the qobj. If more that one experiment exists in the qobj only the first
experiment will be run and the rest will be ignored.
Creating a ``Job`` instance does not imply running it. You need to do it in
separate steps::
job = QuantinuumJob(...)
job.submit()
An error while submitting a job will cause the next call to ``status()`` to
raise. If submitting the job successes, you can inspect the job's status by
using ``status()``. Status can be one of ``JobStatus`` members::
from qiskit.backends.jobstatus import JobStatus
job = QuantinuumJob(...)
job.submit()
try:
job_status = job.status() # It will query the backend API.
if job_status is JobStatus.RUNNING:
print('The job is still running')
except JobError as ex:
print("Something wrong happened!: {}".format(ex))
A call to ``status()`` can raise if something happens at the API level that
prevents Qiskit from determining the status of the job. An example of this
is a temporary connection lose or a network failure.
``Job`` instances also have `id()` and ``result()`` methods which will
block::
job = QuantinuumJob(...)
job.submit()
try:
job_id = job.id()
print('The job {} was successfully submitted'.format(job_id))
job_result = job.result() # It will block until finishing.
print('The job finished with result {}'.format(job_result))
except JobError as ex:
print("Something wrong happened!: {}".format(ex))
Both methods can raise if something at the API level happens that prevent
Qiskit from determining the status of the job.
Note:
When querying the API for getting the status, two kinds of errors are
possible. The most severe is the one preventing Qiskit from getting a
response from the backend. This can be caused by a network failure or a
temporary system break. In these cases, calling ``status()`` will raise.
If Qiskit successfully retrieves the status of a job, it could be it
finished with errors. In that case, ``status()`` will simply return
``JobStatus.ERROR`` and you can call ``error_message()`` to get more
info.
"""
def __init__(self, backend, job_id, api=None, circuits=None, job_config=None):
"""QuantinuumJob init function.
We can instantiate jobs from two sources: A circuit, and an already
submitted job returned by the API servers.
Args:
backend (QuantinuumBackend): The backend instance used to run this job.
job_id (str or None): The job ID of an already submitted job.
Pass `None` if you are creating a new job.
api (QuantinuumClient): Quantinuum api client.
circuits (list): A list of quantum circuit objects to run. Can also
be a ``QasmQobj`` object, but this is deprecated (and won't raise a
warning (since it's raised by ``backend.run()``). See notes below
job_config (dict): A dictionary for the job configuration options
Notes:
It is mandatory to pass either ``circuits`` or ``job_id``. Passing a ``circuits``
will ignore ``job_id`` and will create an instance to be submitted to the
API server for job creation. Passing only a `job_id` will create an instance
representing an already-created job retrieved from the API server.
"""
super().__init__(backend, job_id)
if api:
self._api = api
else:
self._api = QuantinuumClient(backend.provider().credentials)
self._creation_date = datetime.utcnow().replace(tzinfo=timezone.utc).isoformat()
# Properties used for caching.
self._cancelled = False
self._api_error_msg = None
self._result = None
self._job_ids = []
self._experiment_results = []
self._qobj_payload = {}
self._circuits_job = False
if circuits:
if isinstance(circuits, qobj_mod.QasmQobj):
self._qobj_payload = circuits.to_dict()
# Extract individual experiments
# if we want user qobj headers, the third argument contains it
self._experiments, self._job_config, _ = disassemble(circuits)
self._status = JobStatus.INITIALIZING
else:
self._experiments = circuits
self._job_config = job_config
self._circuits_job = True
else:
self._status = JobStatus.INITIALIZING
self._job_ids.append(job_id)
self._job_config = {}
def submit(self):
"""Submit the job to the backend."""
backend_name = self.backend().name()
for exp in self._experiments:
submit_info = self._api.job_submit(backend_name, self._job_config, exp.qasm())
# Error in job after submission:
# Transition to the `ERROR` final state.
if 'error' in submit_info:
self._status = JobStatus.ERROR
self._api_error_msg = str(submit_info['error'])
# Don't continue
return
self._job_ids.append(submit_info['job'])
# Take the last submitted job's info
self._creation_date = submit_info.get('submit-date')
self._status = submit_info.get('status')
self._job_id = submit_info.get('job')
def result(self, timeout=300):
"""Return the result of the job.
Args:
timeout (float): number of seconds to wait for job
Returns:
qiskit.Result: Result object
Raises:
JobError: if attempted to recover a result on a failed job.
Notes:
Currently when calling get_counts() on a result returned by a Quantinuum
backend, since Quantinuum backends currently support only running one
experiment per job, do not supply an argument to the get_counts() function.
Doing so may raise an exception.
"""
if self._result:
return self._result
# Wait for results sequentially
for job_id in self._job_ids:
self._experiment_results.append(
asyncio.get_event_loop().run_until_complete(self._get_status(job_id, timeout))
)
# Process results
self._result = self._process_results()
if not (self._status is JobStatus.DONE or self._status is JobStatus.CANCELLED):
raise JobError('Invalid job state. The job should be DONE or CANCELLED but '
'it is {}'.format(str(self._status)))
if not self._result:
raise JobError('Server did not return result')
return self._result
def cancel(self):
"""Attempt to cancel job."""
pass
async def _get_status(self, job_id, timeout=300):
"""Query the API to update the status.
Returns:
qiskit.providers.JobStatus: The api response including the job status
Raises:
JobError: if there was an exception in the future being executed
or the server sent an unknown answer.
"""
if job_id is None or self._status in JOB_FINAL_STATES:
return self._status
try:
api_response = self._api.job_status(job_id)
if 'websocket' in api_response:
task_token = api_response['websocket']['task_token']
execution_arn = api_response['websocket']['executionArn']
credentials = self.backend().provider().credentials
websocket_uri = credentials.url.replace('https://', 'wss://ws.')
async with websockets.connect(
websocket_uri, extra_headers={
'Authorization': credentials.access_token}) as websocket:
body = {
"action": "OpenConnection",
"task_token": task_token,
"executionArn": execution_arn
}
await websocket.send(json.dumps(body))
api_response = await asyncio.wait_for(websocket.recv(), timeout=timeout)
api_response = json.loads(api_response)
else:
logger.warning('Websockets via proxy not supported. Falling-back to polling.')
residual_delay = timeout/1000 # convert us -> s
request_delay = min(1.0, residual_delay)
while api_response['status'] not in ['failed', 'completed', 'canceled']:
sleep(request_delay)
api_response = self._api.job_status(job_id)
residual_delay = residual_delay - request_delay
if residual_delay <= 0:
# break if we have exceeded timeout
break
# Max-out at 10 second delay
request_delay = min(min(request_delay*1.5, 10), residual_delay)
except Exception as err:
raise JobError(str(err))
return api_response
def status(self, timeout=300):
"""Query the API to update the status.
Returns:
qiskit.providers.JobStatus: The status of the job, once updated.
Raises:
JobError: if there was an exception in the future being executed
or the server sent an unknown answer.
"""
# Wait for results sequentially
for job_id in self._job_ids:
self._experiment_results.append(
asyncio.get_event_loop().run_until_complete(self._get_status(job_id, timeout))
)
# Process results
self._result = self._process_results()
return self._status
def error_message(self):
"""Provide details about the reason of failure.
Returns:
str: An error report if the job errored or ``None`` otherwise.
"""
for job_id in self._job_ids:
if self.status(job_id) is not JobStatus.ERROR:
return None
if not self._api_error_msg:
self._api_error_msg = 'An unknown error occurred.'
return self._api_error_msg
def _process_results(self):
"""Convert Quantinuum job result to qiskit.Result"""
results = []
self._status = JobStatus.DONE
for i, res_resp in enumerate(self._experiment_results):
status = res_resp.get('status', 'failed')
if status == 'failed':
self._status = JobStatus.ERROR
res = res_resp['results']
counts = dict(Counter(hex(int("".join(r), 2)) for r in [*zip(*list(res.values()))]))
experiment_result = {
'shots': self._job_config.get('shots', 1),
'success': ApiJobStatus(status) is ApiJobStatus.COMPLETED,
'data': {'counts': counts},
'job_id': self._job_ids[i]
}
if self._circuits_job:
if self._experiments[i].metadata is None:
metadata = {}
else:
metadata = self._experiments[i].metadata
experiment_result['header'] = metadata
else:
experiment_result['header'] = self._qobj_payload[
'experiments'][i]['header'] if self._qobj_payload else {}
results.append(experiment_result)
result = {
'success': self._status is JobStatus.DONE,
'job_id': self._job_id,
'results': results,
'backend_name': self._backend.name(),
'backend_version': self._backend.status().backend_version,
'qobj_id': self._job_id
}
return Result.from_dict(result)
def creation_date(self):
"""Return creation date."""
return self._creation_date
def job_ids(self):
""" Return all the job_ids associated with this experiment """
return self._job_ids
|
https://github.com/qiskit-community/qiskit-quantinuum-provider
|
qiskit-community
|
# 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.
# Copyright 2019-2020 Quantinuum, Intl. (www.quantinuum.com)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Quantinuum TestCase for testing backends."""
from qiskit import execute
from qiskit import QuantumCircuit
from qiskit.providers.jobstatus import JobStatus
from qiskit.providers.models import BackendStatus
from qiskit.test import QiskitTestCase
from qiskit_quantinuum import Quantinuum
from qiskit_quantinuum import QuantinuumProvider
from qiskit_quantinuum import QuantinuumJob
from qiskit_quantinuum import QuantinuumBackend
from qiskit_quantinuum.api import QuantinuumClient
from .decorators import online_test
class QuantinuumBackendTestCase(QiskitTestCase):
"""Test case for Quantinuum backend.
Members:
proivder_cls (BaseProvider): provider to be used in this test case.
api_cls (QuantinuumClient): api to be used in this test case
backend_cls (BaseBackend): backend to be used in this test case. Its
instantiation can be further customized by overriding the
``_get_backend`` function.
backend_name (str): name of backend to be used in tests.
"""
provider_cls = QuantinuumProvider
api_cls = QuantinuumClient
backend_cls = QuantinuumBackend
backend_name = 'H1-1SC'
def setUp(self):
super().setUp()
self.circuit = QuantumCircuit(4)
self.circuit.h(0)
self.circuit.cx(0, 1)
self.circuit.h(0)
self.circuit.cp(1.0, 0, 1)
self.circuit.toffoli(0, 1, 2)
self.circuit.toffoli(1, 2, 3)
self.circuit.x(0)
self.circuit.y(0)
self.circuit.z(0)
self.circuit.cx(0, 1)
self.circuit.h(0)
self.circuit.s(0)
self.circuit.sdg(0)
self.circuit.t(0)
self.circuit.tdg(0)
self.circuit.rx(1.0, 0)
self.circuit.ry(1.0, 0)
self.circuit.rz(1.0, 0)
self.circuit.cz(0, 1)
self.circuit.cy(0, 2)
self.circuit.ch(0, 3)
self.circuit.ccx(0, 1, 2)
self.circuit.crz(1.0, 0, 1)
self.circuit.crx(1.0, 0, 1)
self.circuit.cry(1.0, 0, 1)
self.circuit.cp(1.0, 0, 1)
self.circuit.cu(1.0, 2.0, 3.0, 0.0, 0, 1)
self.circuit.measure_all()
def test_configuration(self):
"""Test backend.configuration()."""
pass
def test_properties(self):
"""Test backend.properties()."""
pass
@online_test
def test_provider(self):
"""Test backend.provider()."""
Quantinuum.load_account()
backend = Quantinuum.get_backend(self.backend_name)
provider = backend.provider()
self.assertEqual(provider, self.provider_cls())
@online_test
def test_status(self):
"""Test backend.status()."""
Quantinuum.load_account()
backend = Quantinuum.get_backend(self.backend_name)
status = backend.status()
self.assertIsInstance(status, BackendStatus)
@online_test
def test_name(self):
"""Test backend.name()."""
Quantinuum.load_account()
backend = Quantinuum.get_backend(self.backend_name)
name = backend.name()
self.assertEqual(name, self.backend_name)
@online_test
def _submit_job(self):
"""Helper method to submit job and return job instance"""
Quantinuum.load_account()
backend = Quantinuum.get_backend(self.backend_name)
return execute(self.circuit, backend)
@online_test
def test_submit_job(self):
"""Test running a single circuit."""
Quantinuum.load_account()
job = self._submit_job()
self.assertIsInstance(job, QuantinuumJob)
@online_test
def test_get_job_result(self):
"""Test get result of job"""
Quantinuum.load_account()
job = self._submit_job()
result = job.result()
self.assertEqual(result.success, True)
return result
@online_test
def test_get_job_status(self):
"""Test get status of job"""
job = self._submit_job()
Quantinuum.load_account()
status = job.status()
self.assertIsInstance(status, JobStatus)
def test_get_job_error_message(self):
"""Test get error message of job"""
pass
@online_test
def test_get_creation_date(self):
"""Test get creation date of job"""
Quantinuum.load_account()
job = self._submit_job()
creation_date = job.creation_date()
self.assertIsNotNone(creation_date)
@online_test
def test_get_job_id(self):
"""Test get id of job"""
Quantinuum.load_account()
job = self._submit_job()
job_id = job.job_id()
self.assertIsNotNone(job_id)
@online_test
def test_job_with_id(self):
"""Test creating a job with an id."""
Quantinuum.load_account()
backend = Quantinuum.get_backend(self.backend_name)
job = self._submit_job()
job_id = job.job_id()
credentials = backend.provider().credentials
job_created_with_id = QuantinuumJob(backend, job_id, self.api_cls(credentials))
result = job_created_with_id.result()
self.assertEqual(result.success, True)
return result
|
https://github.com/Qiskit/qiskit-neko
|
Qiskit
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2022.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Qiskit Aer default backend plugin."""
import qiskit_aer as aer
from qiskit_ibm_runtime import fake_provider
from qiskit_neko import backend_plugin
class AerBackendPlugin(backend_plugin.BackendPlugin):
"""A backend plugin for using qiskit-aer as the backend."""
def __init__(self):
super().__init__()
self.mock_provider = fake_provider.FakeProvider()
self.mock_provider_backend_names = set()
for backend in self.mock_provider.backends():
if backend.version == 1:
self.mock_provider_backend_names.add(backend.name())
elif backend.version == 2:
self.mock_provider_backend_names.add(backend.name)
def get_backend(self, backend_selection=None):
"""Return the Backend object to run tests on.
:param str backend_selection: An optional selection string to specify
the backend object returned from this method. This can be used
in two different ways. Either it can be used to specify a fake
backend name from ``qiskit.test.mock`` in ``qiskit-terra`` such
as ``fake_quito`` which will return that fake backend object or
alternatively if the string starts with ``method=`` an ideal
:class:`~qiskit.providers.aer.AerSimulator` object with that method
will be set. If this is not specified a
:class:`~qiskit.providers.aer.AerSimulator` will be returned with
the defailt settings.
:raises ValueError: If an invalid backend selection string is passed in
"""
if backend_selection is None:
return aer.AerSimulator()
if backend_selection.startswith("method="):
method = backend_selection.split("=")[1]
return aer.AerSimulator(method=method)
if backend_selection in self.mock_provider_backend_names:
return self.mock_provider.get_backend(backend_selection)
raise ValueError(f"Invalid selection string {backend_selection}.")
|
https://github.com/Qiskit/qiskit-neko
|
Qiskit
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2022.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Tests from circuit basics tutorial."""
import math
import ddt
from qiskit import QuantumCircuit, transpile
from qiskit_neko import decorators
from qiskit_neko.tests import base
@ddt.ddt
class TestCircuitBasics(base.BaseTestCase):
"""Tests adapted from circuit basics tutorial."""
def setUp(self):
super().setUp()
self.circ = QuantumCircuit(3)
self.circ.h(0)
self.circ.cx(0, 1)
self.circ.cx(0, 2)
@decorators.component_attr("terra", "backend")
@ddt.data(0, 1, 2, 3)
def test_ghz_circuit(self, opt_level):
"""Test execution of ghz circuit."""
self.circ.measure_all()
tqc = transpile(self.circ, self.backend, optimization_level=opt_level)
run_kwargs = {}
expected_value = None
if hasattr(self.backend.options, "shots"):
run_kwargs["shots"] = 1000
expected_value = 500
if hasattr(self.backend.options, "seed_simulator"):
run_kwargs["seed_simulator"] = 42
job = self.backend.run(tqc, **run_kwargs)
result = job.result()
counts = result.get_counts()
if expected_value is None:
expected_value = sum(counts.values()) / 2
expected = {"000": expected_value, "111": expected_value}
delta = 10 ** math.floor(math.log10(expected_value))
self.assertDictAlmostEqual(counts, expected, delta=delta)
|
https://github.com/Qiskit/qiskit-neko
|
Qiskit
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2022.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test backend on execute()."""
import math
from qiskit.circuit import QuantumCircuit
from qiskit import transpile
from qiskit_neko import decorators
from qiskit_neko.tests import base
class TestExecute(base.BaseTestCase):
"""Test the use of the execute() method in qiskit-terra."""
def setUp(self):
super().setUp()
if not hasattr(self.backend.options, "shots"):
raise self.skipException(
"Provided backend {self.backend} does not have a configurable shots option"
)
if hasattr(self.backend.options, "seed_simulator"):
self.backend.set_options(seed_simulator=42)
@decorators.component_attr("terra", "backend")
def test_bell_execute_fixed_shots(self):
"""Test the execution of a bell circuit with an explicit shot count."""
circuit = QuantumCircuit(2)
circuit.h(0)
circuit.cx(0, 1)
circuit.measure_all()
job = self.backend.run(transpile(circuit, self.backend), shots=100)
result = job.result()
counts = result.get_counts()
self.assertDictAlmostEqual(counts, {"00": 50, "11": 50}, delta=10)
@decorators.component_attr("terra", "backend")
def test_bell_execute_default_shots(self):
"""Test the execution of a bell circuit with an explicit shot count."""
circuit = QuantumCircuit(2)
circuit.h(0)
circuit.cx(0, 1)
circuit.measure_all()
expected_count = self.backend.options.shots / 2
job = self.backend.run(transpile(circuit, self.backend))
result = job.result()
counts = result.get_counts()
delta = 10 ** (math.log10(self.backend.options.shots) - 1)
self.assertDictAlmostEqual(
counts, {"00": expected_count, "11": expected_count}, delta=delta
)
@decorators.component_attr("terra", "backend")
def test_bell_execute_backend_shots_set_options(self):
"""Test the execution of a bell circuit with an explicit shot count set via options."""
circuit = QuantumCircuit(2)
circuit.h(0)
circuit.cx(0, 1)
circuit.measure_all()
self.backend.set_options(shots=100)
job = self.backend.run(transpile(circuit, self.backend))
result = job.result()
counts = result.get_counts()
self.assertDictAlmostEqual(counts, {"00": 50, "11": 50}, delta=10)
|
https://github.com/Qiskit/qiskit-neko
|
Qiskit
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2022.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Tests for quantum state tomography."""
from qiskit_experiments.library import StateTomography
from qiskit import QuantumCircuit
from qiskit.quantum_info import DensityMatrix, state_fidelity
from qiskit_neko import decorators
from qiskit_neko.tests import base
class TestQuantumStateTomography(base.BaseTestCase):
"""Tests adapted from circuit basics tutorial."""
@decorators.component_attr("terra", "backend", "experiment")
def test_ghz_circuit_quantum_info(self):
"""Test state tomography of ghz state circuit"""
nq = 3
qc_ghz = QuantumCircuit(nq)
qc_ghz.h(0)
qc_ghz.s(0)
for i in range(1, nq):
qc_ghz.cx(0, i)
qstexp1 = StateTomography(qc_ghz)
qstdata1 = qstexp1.run(self.backend, seed_simulation=42).block_for_results()
state_result = qstdata1.analysis_results("state")
density_matrix = state_result.value
ideal_density_matrix = DensityMatrix(qc_ghz)
fidelity = state_fidelity(density_matrix, ideal_density_matrix)
self.assertGreaterEqual(fidelity, 0.55)
|
https://github.com/Qiskit/qiskit-neko
|
Qiskit
|
# 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 quantum neural networks."""
import numpy as np
from ddt import ddt, data, unpack
from qiskit import QuantumCircuit
from qiskit.circuit import Parameter
from qiskit.primitives import Sampler as ReferenceSampler, Estimator as ReferenceEstimator
from qiskit.quantum_info import SparsePauliOp
from qiskit_aer.primitives import Sampler as AerSampler, Estimator as AerEstimator
from qiskit_machine_learning.neural_networks import SamplerQNN, EstimatorQNN
from qiskit_neko import decorators
from qiskit_neko.tests import base
@ddt
class TestNeuralNetworksOnPrimitives(base.BaseTestCase):
"""Test adapted from the qiskit_machine_learning tutorials."""
def setUp(self):
super().setUp()
self.input_params = [Parameter("x")]
self.weight_params = [Parameter("w")]
self.circuit = QuantumCircuit(1)
self.circuit.ry(self.input_params[0], 0)
self.circuit.rx(self.weight_params[0], 0)
self.samplers = dict(reference=ReferenceSampler(), aer=AerSampler(run_options={"seed": 42}))
self.estimators = dict(
reference=ReferenceEstimator(), aer=AerEstimator(run_options={"seed": 42})
)
@decorators.component_attr("terra", "aer", "machine_learning")
@data(["reference", 4], ["aer", 1])
@unpack
def test_sampler_qnn(self, implementation, decimal):
"""Test the execution of quantum neural networks using SamplerQNN."""
sampler = self.samplers[implementation]
qnn = SamplerQNN(
circuit=self.circuit,
input_params=self.input_params,
weight_params=self.weight_params,
input_gradients=True,
sampler=sampler,
)
input_data = np.ones(len(self.input_params))
weights = np.ones(len(self.weight_params))
probabilities = qnn.forward(input_data, weights)
np.testing.assert_array_almost_equal(probabilities, [[0.6460, 0.3540]], decimal)
input_grad, weight_grad = qnn.backward(input_data, weights)
np.testing.assert_array_almost_equal(input_grad, [[[-0.2273], [0.2273]]], decimal)
np.testing.assert_array_almost_equal(weight_grad, [[[-0.2273], [0.2273]]], decimal)
@decorators.component_attr("terra", "aer", "machine_learning")
@data(["reference", 4], ["aer", 1])
@unpack
def test_estimator_qnn(self, implementation, decimal):
"""Test the execution of quantum neural networks using EstimatorQNN."""
estimator = self.estimators[implementation]
qnn = EstimatorQNN(
circuit=self.circuit,
observables=SparsePauliOp.from_list([("Z", 1)]),
input_params=self.input_params,
weight_params=self.weight_params,
input_gradients=True,
estimator=estimator,
)
input_data = np.ones(len(self.input_params))
weights = np.ones(len(self.weight_params))
expectations = qnn.forward(input_data, weights)
np.testing.assert_array_almost_equal(expectations, [[0.2919]], decimal)
input_grad, weight_grad = qnn.backward(input_data, weights)
np.testing.assert_array_almost_equal(input_grad, [[[-0.4546]]], decimal)
np.testing.assert_array_almost_equal(weight_grad, [[[-0.4546]]], decimal)
|
https://github.com/Qiskit/qiskit-neko
|
Qiskit
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2022, 2024.
#
# 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 ground state solvers."""
import unittest
from qiskit_algorithms import NumPyMinimumEigensolver, VQE
from qiskit_algorithms.optimizers import SLSQP
from qiskit.primitives import Estimator
import qiskit_nature
from qiskit_nature.second_q.algorithms import GroundStateEigensolver
from qiskit_nature.second_q.circuit.library import HartreeFock, UCCSD
from qiskit_nature.second_q.drivers import PySCFDriver
from qiskit_nature.second_q.mappers import JordanWignerMapper
from qiskit_neko.tests import base
from qiskit_neko import decorators
class TestGroundStateSolvers(base.BaseTestCase):
"""Test the use of the execute() method in qiskit-terra."""
@unittest.skipIf(
tuple(map(int, qiskit_nature.__version__.split(".")[:2])) < (0, 7),
"This test is incompatible with qiskit_nature versions below 0.7.0",
)
@decorators.component_attr("terra", "backend", "nature", "algorithms")
def test_ground_state_solver(self):
"""Test the execution of a bell circuit with an explicit shot count."""
driver = PySCFDriver(atom="H 0.0 0.0 0.0; H 0.0 0.0 0.735", basis="sto3g")
es_problem = driver.run()
qubit_mapper = JordanWignerMapper()
estimator = Estimator()
optimizer = SLSQP()
ansatz = UCCSD(
es_problem.num_spatial_orbitals,
es_problem.num_particles,
qubit_mapper,
initial_state=HartreeFock(
es_problem.num_spatial_orbitals,
es_problem.num_particles,
qubit_mapper,
),
)
vqe_solver = VQE(estimator, ansatz, optimizer)
vqe_solver.initial_point = [0.0] * ansatz.num_parameters
calc = GroundStateEigensolver(qubit_mapper, vqe_solver)
result = calc.solve(es_problem)
# Calculate expected result from numpy solver
numpy_solver = NumPyMinimumEigensolver()
np_calc = GroundStateEigensolver(qubit_mapper, numpy_solver)
expected = np_calc.solve(es_problem)
self.assertAlmostEqual(result.hartree_fock_energy, expected.hartree_fock_energy)
self.assertEqual(len(result.total_energies), 1)
self.assertAlmostEqual(result.total_energies[0], expected.total_energies[0], delta=0.02)
|
https://github.com/qiskit-community/qiskit-aqua-interfaces
|
qiskit-community
|
# -*- coding: utf-8 -*-
# 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.
"""Root main view"""
import sys
import tkinter as tk
import tkinter.messagebox as tkmb
import tkinter.ttk as ttk
import tkinter.filedialog as tkfd
from tkinter import font
import webbrowser
import os
from qiskit_aqua_interfaces import __version__, APP_DEPRECATION_MSG
from ._sectionsview import SectionsView
from ._sectiontextview import SectionTextView
from ._threadsafeoutputview import ThreadSafeOutputView
from ._emptyview import EmptyView
from ._preferencesdialog import PreferencesDialog
# pylint: disable=import-outside-toplevel
class MainView(ttk.Frame):
""" Main View """
def __init__(self, parent, guiprovider) -> None:
"""Create MainView object."""
super(MainView, self).__init__(parent)
self._guiprovider = guiprovider
self._guiprovider.controller.view = self
self.pack(expand=tk.YES, fill=tk.BOTH)
self._create_widgets()
self.master.title(self._guiprovider.title)
if parent is not None:
parent.protocol('WM_DELETE_WINDOW', self.quit)
def _show_about_dialog(self):
import qiskit.aqua as qa
lines = ['Qiskit Aqua Interfaces',
'Version: {}'.format(__version__),
'',
'Qiskit Aqua',
'Version: {}'.format(qa.__version__),
]
tkmb.showinfo(self._guiprovider.title, message='\n'.join(lines))
def _show_preferences(self):
dialog = PreferencesDialog(self, self._guiprovider)
dialog.do_init(tk.LEFT)
dialog.do_modal()
def _create_widgets(self):
self._make_menubar()
self._make_toolbar()
self._create_pane()
def _make_toolbar(self):
toolbar = ttk.Frame(self, relief=tk.SUNKEN, borderwidth=2)
toolbar.pack(side=tk.BOTTOM, fill=tk.X)
self._guiprovider.controller._button_text = tk.StringVar()
self._guiprovider.controller._button_text.set(self._guiprovider.controller._command)
self._guiprovider.controller._start_button = \
ttk.Button(toolbar,
textvariable=self._guiprovider.controller._button_text,
state='disabled',
command=self._guiprovider.controller.toggle)
self._guiprovider.controller._start_button.pack(side=tk.LEFT)
self._guiprovider.add_toolbar_items(toolbar)
self._guiprovider.controller._progress = ttk.Progressbar(toolbar, orient=tk.HORIZONTAL)
self._guiprovider.controller._progress.pack(side=tk.RIGHT, fill=tk.BOTH, expand=tk.TRUE)
def _make_menubar(self):
menubar = tk.Menu(self.master)
if sys.platform == 'darwin':
app_menu = tk.Menu(menubar, name='apple')
menubar.add_cascade(menu=app_menu)
app_menu.add_command(label='About {}'.format(
self._guiprovider.title), command=self._show_about_dialog)
self.master.createcommand('tk::mac::ShowPreferences', self._show_preferences)
self.master.createcommand('tk::mac::Quit', self.quit)
self.master.config(menu=menubar)
self._guiprovider.controller._filemenu = self._make_filemenu(menubar)
if sys.platform != 'darwin':
tools_menu = tk.Menu(menubar, tearoff=False)
tools_menu.add_command(label='Options', command=self._show_preferences)
menubar.add_cascade(label='Tools', menu=tools_menu)
help_menu = tk.Menu(menubar, tearoff=False)
if sys.platform != 'darwin':
help_menu.add_command(label='About {}'.format(self._guiprovider.title),
command=self._show_about_dialog)
help_menu.add_command(label='Open Help Center', command=self._open_help_center)
menubar.add_cascade(label='Help', menu=help_menu)
def _open_help_center(self):
webbrowser.open(self._guiprovider.help_hyperlink)
def _make_filemenu(self, menubar):
file_menu = tk.Menu(menubar, tearoff=False, postcommand=self._recent_files_menu)
file_menu.add_command(label='New', command=self._new_input)
file_menu.add_command(label='Open...', command=self._open_file)
file_menu.add_cascade(label='Open Recent', menu=tk.Menu(file_menu, tearoff=False))
file_menu.add_separator()
file_menu.add_command(label='Save', command=self._save_file)
file_menu.add_command(label='Save As...', command=self._save_file_as)
self._guiprovider.add_file_menu_items(file_menu)
if sys.platform != 'darwin':
file_menu.add_separator()
file_menu.add_command(label='Exit', command=self.quit)
menubar.add_cascade(label='File', menu=file_menu)
return file_menu
def _recent_files_menu(self):
recent_menu = tk.Menu(self._guiprovider.controller._filemenu, tearoff=False)
preferences = self._guiprovider.create_uipreferences()
for file in preferences.get_recent_files():
recent_menu.add_command(label=file, command=lambda f=file: self._open_recent_file(f))
recent_menu.add_separator()
recent_menu.add_command(label='Clear', command=self._clear_recent)
self._guiprovider.controller._filemenu.entryconfig(2, menu=recent_menu)
def _new_input(self):
self._guiprovider.controller.new_input()
def _open_file(self):
preferences = self._guiprovider.create_uipreferences()
filename = tkfd.askopenfilename(parent=self,
title='Open File',
initialdir=preferences.get_openfile_initialdir())
if filename and self._guiprovider.controller.open_file(filename):
preferences.add_recent_file(filename)
preferences.set_openfile_initialdir(os.path.dirname(filename))
preferences.save()
def _open_recent_file(self, filename):
self._guiprovider.controller.open_file(filename)
def _clear_recent(self):
preferences = self._guiprovider.create_uipreferences()
preferences.clear_recent_files()
preferences.save()
def _save_file(self):
self._guiprovider.controller.save_file()
def _save_file_as(self):
if self._guiprovider.controller.is_empty():
self._guiprovider.controller.outputview.write_line("No data to save.")
return
preferences = self._guiprovider.create_uipreferences()
filename = tkfd.asksaveasfilename(parent=self,
title='Save File',
initialdir=preferences.get_savefile_initialdir())
if filename and self._guiprovider.controller.save_file_as(filename):
preferences.add_recent_file(filename)
preferences.set_savefile_initialdir(os.path.dirname(filename))
preferences.save()
def _create_pane(self):
label_font = font.nametofont('TkHeadingFont').copy()
label_font.configure(size=12, weight='bold')
style = ttk.Style()
style.configure('Title.TLabel',
borderwidth=0,
anchor=tk.CENTER)
label = ttk.Label(self,
style='Title.TLabel',
padding=(5, 5, 5, 5),
textvariable=self._guiprovider.controller._title)
label['font'] = label_font
label.pack(side=tk.TOP, expand=tk.NO, fill=tk.X)
main_pane = ttk.PanedWindow(self, orient=tk.VERTICAL)
main_pane.pack(expand=tk.YES, fill=tk.BOTH)
top_pane = ttk.PanedWindow(main_pane, orient=tk.HORIZONTAL)
top_pane.pack(expand=tk.YES, fill=tk.BOTH)
main_pane.add(top_pane)
self._guiprovider.controller._sections_view = \
SectionsView(self._guiprovider.controller, top_pane)
self._guiprovider.controller._sections_view.pack(expand=tk.YES, fill=tk.BOTH)
top_pane.add(self._guiprovider.controller._sections_view, weight=1)
main_container = tk.Frame(top_pane)
main_container.pack(expand=tk.YES, fill=tk.BOTH)
style = ttk.Style()
style.configure('PropViewTitle.TLabel',
borderwidth=1,
relief=tk.RIDGE,
anchor=tk.CENTER)
label = ttk.Label(main_container,
style='PropViewTitle.TLabel',
padding=(5, 5, 5, 5),
textvariable=self._guiprovider.controller._sections_view_title)
label['font'] = label_font
label.pack(side=tk.TOP, expand=tk.NO, fill=tk.X)
container = tk.Frame(main_container)
container.pack(side=tk.BOTTOM, expand=tk.YES, fill=tk.BOTH)
container.grid_rowconfigure(0, weight=1)
container.grid_columnconfigure(0, weight=1)
self._guiprovider.controller._empty_view = EmptyView(container)
self._guiprovider.controller._empty_view.grid(row=0, column=0, sticky='nsew')
self._guiprovider.controller._text_view = \
SectionTextView(self._guiprovider.controller, container)
self._guiprovider.controller._text_view.grid(row=0, column=0, sticky='nsew')
self._guiprovider.controller._properties_view = \
self._guiprovider.create_section_properties_view(container)
self._guiprovider.controller._properties_view.grid(row=0, column=0, sticky='nsew')
self._guiprovider.controller._empty_view.tkraise()
top_pane.add(main_container, weight=1)
self._guiprovider.controller.outputview = ThreadSafeOutputView(main_pane)
self._guiprovider.controller.outputview.pack(expand=tk.YES, fill=tk.BOTH)
main_pane.add(self._guiprovider.controller.outputview)
# redirect output
sys.stdout = self._guiprovider.controller.outputview
sys.stderr = self._guiprovider.controller.outputview
# update logging after redirect
self.after(0, self._set_preferences_logging)
self.update_idletasks()
self._guiprovider.controller._sections_view.show_add_button(False)
self._guiprovider.controller._sections_view.show_remove_button(False)
self._guiprovider.controller._sections_view.show_defaults_button(False)
self._guiprovider.controller._empty_view.set_toolbar_size(
self._guiprovider.controller._sections_view.get_toolbar_size())
self._guiprovider.controller.outputview.write_line(APP_DEPRECATION_MSG)
def _set_preferences_logging(self):
preferences = self._guiprovider.create_uipreferences()
config = preferences.get_logging_config()
if config is not None:
self._guiprovider.set_logging_config(config)
def quit(self):
if tkmb.askyesno('Verify quit', 'Are you sure you want to quit?'):
preferences = self._guiprovider.create_uipreferences()
preferences.set_geometry(self.master.winfo_geometry())
preferences.save()
self._guiprovider.controller.stop()
ttk.Frame.quit(self)
return True
return False
|
https://github.com/qiskit-community/qiskit-aqua-interfaces
|
qiskit-community
|
# -*- coding: utf-8 -*-
# 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.
"""Root main view"""
import sys
import tkinter as tk
import tkinter.messagebox as tkmb
import tkinter.ttk as ttk
import tkinter.filedialog as tkfd
from tkinter import font
import webbrowser
import os
from qiskit_aqua_interfaces import __version__, APP_DEPRECATION_MSG
from ._sectionsview import SectionsView
from ._sectiontextview import SectionTextView
from ._threadsafeoutputview import ThreadSafeOutputView
from ._emptyview import EmptyView
from ._preferencesdialog import PreferencesDialog
# pylint: disable=import-outside-toplevel
class MainView(ttk.Frame):
""" Main View """
def __init__(self, parent, guiprovider) -> None:
"""Create MainView object."""
super(MainView, self).__init__(parent)
self._guiprovider = guiprovider
self._guiprovider.controller.view = self
self.pack(expand=tk.YES, fill=tk.BOTH)
self._create_widgets()
self.master.title(self._guiprovider.title)
if parent is not None:
parent.protocol('WM_DELETE_WINDOW', self.quit)
def _show_about_dialog(self):
import qiskit.aqua as qa
lines = ['Qiskit Aqua Interfaces',
'Version: {}'.format(__version__),
'',
'Qiskit Aqua',
'Version: {}'.format(qa.__version__),
]
tkmb.showinfo(self._guiprovider.title, message='\n'.join(lines))
def _show_preferences(self):
dialog = PreferencesDialog(self, self._guiprovider)
dialog.do_init(tk.LEFT)
dialog.do_modal()
def _create_widgets(self):
self._make_menubar()
self._make_toolbar()
self._create_pane()
def _make_toolbar(self):
toolbar = ttk.Frame(self, relief=tk.SUNKEN, borderwidth=2)
toolbar.pack(side=tk.BOTTOM, fill=tk.X)
self._guiprovider.controller._button_text = tk.StringVar()
self._guiprovider.controller._button_text.set(self._guiprovider.controller._command)
self._guiprovider.controller._start_button = \
ttk.Button(toolbar,
textvariable=self._guiprovider.controller._button_text,
state='disabled',
command=self._guiprovider.controller.toggle)
self._guiprovider.controller._start_button.pack(side=tk.LEFT)
self._guiprovider.add_toolbar_items(toolbar)
self._guiprovider.controller._progress = ttk.Progressbar(toolbar, orient=tk.HORIZONTAL)
self._guiprovider.controller._progress.pack(side=tk.RIGHT, fill=tk.BOTH, expand=tk.TRUE)
def _make_menubar(self):
menubar = tk.Menu(self.master)
if sys.platform == 'darwin':
app_menu = tk.Menu(menubar, name='apple')
menubar.add_cascade(menu=app_menu)
app_menu.add_command(label='About {}'.format(
self._guiprovider.title), command=self._show_about_dialog)
self.master.createcommand('tk::mac::ShowPreferences', self._show_preferences)
self.master.createcommand('tk::mac::Quit', self.quit)
self.master.config(menu=menubar)
self._guiprovider.controller._filemenu = self._make_filemenu(menubar)
if sys.platform != 'darwin':
tools_menu = tk.Menu(menubar, tearoff=False)
tools_menu.add_command(label='Options', command=self._show_preferences)
menubar.add_cascade(label='Tools', menu=tools_menu)
help_menu = tk.Menu(menubar, tearoff=False)
if sys.platform != 'darwin':
help_menu.add_command(label='About {}'.format(self._guiprovider.title),
command=self._show_about_dialog)
help_menu.add_command(label='Open Help Center', command=self._open_help_center)
menubar.add_cascade(label='Help', menu=help_menu)
def _open_help_center(self):
webbrowser.open(self._guiprovider.help_hyperlink)
def _make_filemenu(self, menubar):
file_menu = tk.Menu(menubar, tearoff=False, postcommand=self._recent_files_menu)
file_menu.add_command(label='New', command=self._new_input)
file_menu.add_command(label='Open...', command=self._open_file)
file_menu.add_cascade(label='Open Recent', menu=tk.Menu(file_menu, tearoff=False))
file_menu.add_separator()
file_menu.add_command(label='Save', command=self._save_file)
file_menu.add_command(label='Save As...', command=self._save_file_as)
self._guiprovider.add_file_menu_items(file_menu)
if sys.platform != 'darwin':
file_menu.add_separator()
file_menu.add_command(label='Exit', command=self.quit)
menubar.add_cascade(label='File', menu=file_menu)
return file_menu
def _recent_files_menu(self):
recent_menu = tk.Menu(self._guiprovider.controller._filemenu, tearoff=False)
preferences = self._guiprovider.create_uipreferences()
for file in preferences.get_recent_files():
recent_menu.add_command(label=file, command=lambda f=file: self._open_recent_file(f))
recent_menu.add_separator()
recent_menu.add_command(label='Clear', command=self._clear_recent)
self._guiprovider.controller._filemenu.entryconfig(2, menu=recent_menu)
def _new_input(self):
self._guiprovider.controller.new_input()
def _open_file(self):
preferences = self._guiprovider.create_uipreferences()
filename = tkfd.askopenfilename(parent=self,
title='Open File',
initialdir=preferences.get_openfile_initialdir())
if filename and self._guiprovider.controller.open_file(filename):
preferences.add_recent_file(filename)
preferences.set_openfile_initialdir(os.path.dirname(filename))
preferences.save()
def _open_recent_file(self, filename):
self._guiprovider.controller.open_file(filename)
def _clear_recent(self):
preferences = self._guiprovider.create_uipreferences()
preferences.clear_recent_files()
preferences.save()
def _save_file(self):
self._guiprovider.controller.save_file()
def _save_file_as(self):
if self._guiprovider.controller.is_empty():
self._guiprovider.controller.outputview.write_line("No data to save.")
return
preferences = self._guiprovider.create_uipreferences()
filename = tkfd.asksaveasfilename(parent=self,
title='Save File',
initialdir=preferences.get_savefile_initialdir())
if filename and self._guiprovider.controller.save_file_as(filename):
preferences.add_recent_file(filename)
preferences.set_savefile_initialdir(os.path.dirname(filename))
preferences.save()
def _create_pane(self):
label_font = font.nametofont('TkHeadingFont').copy()
label_font.configure(size=12, weight='bold')
style = ttk.Style()
style.configure('Title.TLabel',
borderwidth=0,
anchor=tk.CENTER)
label = ttk.Label(self,
style='Title.TLabel',
padding=(5, 5, 5, 5),
textvariable=self._guiprovider.controller._title)
label['font'] = label_font
label.pack(side=tk.TOP, expand=tk.NO, fill=tk.X)
main_pane = ttk.PanedWindow(self, orient=tk.VERTICAL)
main_pane.pack(expand=tk.YES, fill=tk.BOTH)
top_pane = ttk.PanedWindow(main_pane, orient=tk.HORIZONTAL)
top_pane.pack(expand=tk.YES, fill=tk.BOTH)
main_pane.add(top_pane)
self._guiprovider.controller._sections_view = \
SectionsView(self._guiprovider.controller, top_pane)
self._guiprovider.controller._sections_view.pack(expand=tk.YES, fill=tk.BOTH)
top_pane.add(self._guiprovider.controller._sections_view, weight=1)
main_container = tk.Frame(top_pane)
main_container.pack(expand=tk.YES, fill=tk.BOTH)
style = ttk.Style()
style.configure('PropViewTitle.TLabel',
borderwidth=1,
relief=tk.RIDGE,
anchor=tk.CENTER)
label = ttk.Label(main_container,
style='PropViewTitle.TLabel',
padding=(5, 5, 5, 5),
textvariable=self._guiprovider.controller._sections_view_title)
label['font'] = label_font
label.pack(side=tk.TOP, expand=tk.NO, fill=tk.X)
container = tk.Frame(main_container)
container.pack(side=tk.BOTTOM, expand=tk.YES, fill=tk.BOTH)
container.grid_rowconfigure(0, weight=1)
container.grid_columnconfigure(0, weight=1)
self._guiprovider.controller._empty_view = EmptyView(container)
self._guiprovider.controller._empty_view.grid(row=0, column=0, sticky='nsew')
self._guiprovider.controller._text_view = \
SectionTextView(self._guiprovider.controller, container)
self._guiprovider.controller._text_view.grid(row=0, column=0, sticky='nsew')
self._guiprovider.controller._properties_view = \
self._guiprovider.create_section_properties_view(container)
self._guiprovider.controller._properties_view.grid(row=0, column=0, sticky='nsew')
self._guiprovider.controller._empty_view.tkraise()
top_pane.add(main_container, weight=1)
self._guiprovider.controller.outputview = ThreadSafeOutputView(main_pane)
self._guiprovider.controller.outputview.pack(expand=tk.YES, fill=tk.BOTH)
main_pane.add(self._guiprovider.controller.outputview)
# redirect output
sys.stdout = self._guiprovider.controller.outputview
sys.stderr = self._guiprovider.controller.outputview
# update logging after redirect
self.after(0, self._set_preferences_logging)
self.update_idletasks()
self._guiprovider.controller._sections_view.show_add_button(False)
self._guiprovider.controller._sections_view.show_remove_button(False)
self._guiprovider.controller._sections_view.show_defaults_button(False)
self._guiprovider.controller._empty_view.set_toolbar_size(
self._guiprovider.controller._sections_view.get_toolbar_size())
self._guiprovider.controller.outputview.write_line(APP_DEPRECATION_MSG)
def _set_preferences_logging(self):
preferences = self._guiprovider.create_uipreferences()
config = preferences.get_logging_config()
if config is not None:
self._guiprovider.set_logging_config(config)
def quit(self):
if tkmb.askyesno('Verify quit', 'Are you sure you want to quit?'):
preferences = self._guiprovider.create_uipreferences()
preferences.set_geometry(self.master.winfo_geometry())
preferences.save()
self._guiprovider.controller.stop()
ttk.Frame.quit(self)
return True
return False
|
https://github.com/qiskit-community/qiskit-nature-pyscf
|
qiskit-community
|
import qiskit_qasm3_import
project = 'Qiskit OpenQASM 3 Importer'
copyright = '2022, Jake Lishman'
author = 'Jake Lishman'
version = qiskit_qasm3_import.__version__
release = qiskit_qasm3_import.__version__
extensions = [
"sphinx.ext.autodoc",
"sphinx.ext.intersphinx",
"reno.sphinxext",
'qiskit_sphinx_theme',
]
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']
# Document the docstring for the class and the __init__ method together.
autoclass_content = "both"
html_theme = "qiskit-ecosystem"
html_title = f"{project} {release}"
intersphinx_mapping = {
"qiskit-terra": ("https://docs.quantum.ibm.com/api/qiskit/", None),
}
|
https://github.com/unitaryfund/mitiq
|
unitaryfund
|
import numpy as np
from pyquil import get_qc, Program
from pyquil.gates import RX, RY, H, CNOT, MEASURE
import mitiq
from mitiq import zne
from scipy import optimize
# initialize the quantum device
qc = get_qc("2q-noisy-qvm")
program = Program()
theta = program.declare("theta", memory_type="REAL")
ro = program.declare("ro", memory_type="BIT", memory_size=1)
program += RX(theta, 0)
program += RY(theta, 0)
program += RX(theta, 1)
program += RY(theta, 1)
program += H(0)
program += CNOT(1,0)
program += H(0)
program += MEASURE(0, ro[0])
def expectation(theta, executable: Program) -> float:
bitstrings = qc.run(
executable.write_memory(region_name="theta", value=theta)
).readout_data.get("ro")
result = np.mean(bitstrings[:, 0])
return result
program.wrap_in_numshots_loop(1000)
quil_prog = qc.compiler.quil_to_native_quil(program, protoquil=True)
thetas = np.linspace(0, 2 * np.pi, 21)
results = []
for theta in thetas:
results.append(expectation(theta, quil_prog))
from matplotlib import pyplot as plt
_ = plt.figure(1)
_ = plt.plot(thetas, results, 'o-')
_ = plt.xlabel(r'$\theta$', fontsize=18)
_ = plt.ylabel(r'$\langle \Psi(\theta) | \frac{1 - Z}{2} | \Psi(\theta) \rangle$', fontsize=18)
_ = plt.title('Noisy Energy Landscape')
plt.show()
quil_prog = qc.compiler.quil_to_native_quil(program, protoquil=True)
init_angle = [0.1]
res = optimize.minimize(expectation, init_angle, args=(quil_prog), method='COBYLA')
print(res)
quil_prog = qc.compiler.quil_to_native_quil(program, protoquil=True)
init_angle = [0.1]
results_zne = []
# here we use a linear fit for the zero noise extrapolation
fac = mitiq.zne.inference.LinearFactory(scale_factors=[1.0, 3.0])
for theta in thetas:
results_zne.append(
zne.execute_with_zne(quil_prog, lambda p: expectation(theta, p), factory=fac)
)
_ = plt.figure(2)
_ = plt.plot(thetas, results_zne, 'o-')
_ = plt.xlabel(r'$\theta$', fontsize=18)
_ = plt.ylabel(r'$\langle \Psi(\theta) | \frac{1 - Z}{2} | \Psi(\theta) \rangle$', fontsize=18)
_ = plt.title('Mitigated Energy Landscape')
plt.show()
def mitigated_expectation(thetas, executable: Program, factory) -> float:
mitigated_exp = zne.execute_with_zne(quil_prog, lambda p: expectation(thetas, p), factory=factory)
return mitigated_exp
quil_prog = qc.compiler.quil_to_native_quil(program, protoquil=True)
res_zne = optimize.minimize(mitigated_expectation, init_angle, args=(quil_prog, fac), method='COBYLA')
print(res_zne)
mitiq.about()
|
https://github.com/unitaryfund/mitiq
|
unitaryfund
|
import numpy as np
from pyquil import get_qc, Program
from pyquil.gates import RX, RY, S, T, Z, CNOT, MEASURE
from pyquil.paulis import PauliTerm, PauliSum, sZ
from pyquil.noise import pauli_kraus_map, append_kraus_to_gate
from typing import List, Union
from collections import Counter
from matplotlib import pyplot as plt
from scipy import optimize
import mitiq
from mitiq import zne
from mitiq.zne.scaling.folding import fold_gates_at_random
backend = get_qc("2q-qvm")
program = Program()
theta = program.declare("theta", memory_type="REAL")
program += RX(theta, 0)
program += T(0)
program += CNOT(1, 0)
program += S(0)
program += Z(0)
def add_noise_to_circuit(quil_prog):
"""Define pyQuil gates with a custom noise model via Kraus operators:
1. Generate Kraus operators at given survival probability
2. Append Kraus operators to the gate matrices
3. Add custom gates to circuit
Args:
quil_prog: the pyQuil quantum program to which the noise model will be added
Returns:
A quantum program with depolarizing noise on the static gates.
"""
prob = 0.8
num_qubits = 1
d = 4 ** num_qubits
d_sq = d ** 2
kraus_list = [(1 - prob) / d] * d
kraus_list[0] += prob
kraus_ops = pauli_kraus_map(kraus_list)
k_list = [(1 - prob) / d_sq] * d_sq
k_list[0] += prob
k_ops = pauli_kraus_map(k_list)
T_gate = np.array([[1, 0], [0, np.exp(1j * np.pi / 4)]])
CNOT_gate = np.block(
[[np.eye(2), np.zeros((2, 2))], [np.zeros((2, 2)), np.flip(np.eye(2), 1)]]
)
S_gate = np.array([[1, 0], [0, 1j]])
Z_gate = np.array([[1, 0], [0, -1]])
quil_prog.define_noisy_gate("T", [0], append_kraus_to_gate(kraus_ops, T_gate))
quil_prog.define_noisy_gate("CNOT", [1, 0], append_kraus_to_gate(k_ops, CNOT_gate))
quil_prog.define_noisy_gate("S", [0], append_kraus_to_gate(kraus_ops, S_gate))
quil_prog.define_noisy_gate("Z", [0], append_kraus_to_gate(kraus_ops, Z_gate))
return quil_prog
hamiltonian = sZ(0)
pauli_sum = PauliSum([hamiltonian])
for j, term in enumerate(pauli_sum.terms):
meas_basis_change = Program()
marked_qubits = []
for index, gate in term:
marked_qubits.append(index)
if gate == "X":
meas_basis_change.inst(RY(-np.pi / 2, index))
elif gate == "Y":
meas_basis_change.inst(RX(np.pi / 2, index))
program += meas_basis_change
readout_qubit = program.declare("ro", "BIT", max(marked_qubits) + 1)
samples = 3000
program.wrap_in_numshots_loop(samples)
def executor(
theta,
backend,
readout_qubit,
samples: int,
pauli_sum: Union[PauliSum, PauliTerm, np.ndarray],
pyquil_prog: Program,
) -> float:
"""
Compute the expectation value of pauli_sum over the distribution generated from
pyquil_prog.
"""
noisy = pyquil_prog.copy()
noisy += [
MEASURE(qubit, r) for qubit, r in zip(list(range(max(marked_qubits) + 1)), readout_qubit)
]
noisy = add_noise_to_circuit(noisy)
expectation = 0.0
pauli_sum = PauliSum([pauli_sum])
for j, term in enumerate(pauli_sum.terms):
qubits_to_measure = []
for index, gate in term:
qubits_to_measure.append(index)
meas_outcome = expectation_from_sampling(
theta, noisy, qubits_to_measure, backend, samples
)
expectation += term.coefficient * meas_outcome
return expectation.real
def expectation_from_sampling(
theta, executable: Program, marked_qubits: List[int], backend, samples: int
) -> float:
"""Calculate the expectation value of the Zi operator where i ranges over all
qubits given in marked_qubits.
"""
bitstring_samples = backend.run(
executable.write_memory(region_name="theta", value=theta)
).readout_data.get("ro")
bitstring_tuples = list(map(tuple, bitstring_samples))
freq = Counter(bitstring_tuples)
exp_val = 0
for bitstring, count in freq.items():
bitstring_int = int("".join([str(x) for x in bitstring[::-1]]), 2)
if parity_even_p(bitstring_int, marked_qubits):
exp_val += float(count) / samples
else:
exp_val -= float(count) / samples
return exp_val
def parity_even_p(state, marked_qubits):
mask = 0
for q in marked_qubits:
mask |= 1 << q
return bin(mask & state).count("1") % 2 == 0
thetas = np.linspace(0, 2 * np.pi, 51)
results = []
for theta in thetas:
results.append(executor(theta, backend, readout_qubit, samples, hamiltonian, program))
init_angle = [3.0]
res = optimize.minimize(
executor,
init_angle,
args=(backend, readout_qubit, samples, hamiltonian, program),
method="Nelder-Mead",
options={"xatol": 1.0e-3, "fatol": 1.0e-2},
)
print(res)
def mitigated_expectation(
thetas, backend, readout_qubit, samples, pauli_sum, executable: Program, factory
) -> float:
"""
This function is the ZNE-wrapped executor, which outputs the error-mitigated
expectation value.
Args:
thetas: the input parameter for the optimization
backend: the quantum computer that runs the quantum program
readout_qubit: declared memory for the readout
samples: number of times the experiment (or simulation) will be run
pauli_sum: the Hamiltonian expressed as
executable: the pyQuil quantum program
factory: factory object containing the type of inference and scaling parameters
Returns:
The error-mitigated expectation value as a float.
"""
mitigated_exp = zne.execute_with_zne(
executable,
lambda p: executor(thetas, backend, readout_qubit, samples, pauli_sum, p),
factory=factory,
scale_noise=fold_gates_at_random,
)
return mitigated_exp
fac = mitiq.zne.inference.LinearFactory(scale_factors=[1.0, 3.0])
results_zne = []
for theta in thetas:
results_zne.append(
mitigated_expectation(theta, backend, readout_qubit, samples, hamiltonian, program, fac)
)
_ = plt.figure()
_ = plt.plot(thetas, np.cos(thetas), "o-", label="Ideal landscape")
_ = plt.plot(thetas, results, "o-", label="Noisy landscape")
_ = plt.plot(thetas, results_zne, "o-", label="Mitigated landscape")
_ = plt.xlabel(r"$\theta$", fontsize=18)
_ = plt.ylabel(r"$\langle \Psi(\theta) | Z | \Psi(\theta) \rangle$", fontsize=18)
_ = plt.legend()
_ = plt.title("Mitigated Energy Landscape")
plt.show()
res_zne = optimize.minimize(
mitigated_expectation,
init_angle,
args=(backend, readout_qubit, samples, hamiltonian, program, fac),
method="Nelder-Mead",
options={"xatol": 1.0e-3, "fatol": 1.0e-2},
)
print(res_zne)
mitiq.about()
|
https://github.com/unitaryfund/mitiq
|
unitaryfund
|
# Copyright (C) Unitary Fund
#
# This source code is licensed under the GPL license (v3) found in the
# LICENSE file in the root directory of this source tree.
"""Defines input / output types for a quantum computer (simulator):
* SUPPORTED_PROGRAM_TYPES: All supported packages / circuits which Mitiq can
interface with,
* QPROGRAM: All supported packages / circuits which are installed in the
environment Mitiq is run in, and
* QuantumResult: An object returned by a quantum computer (simulator) running
a quantum program from which expectation values to be mitigated can be
computed. Note this includes expectation values themselves.
"""
from collections import Counter
from dataclasses import dataclass
from enum import Enum, EnumMeta
from typing import (
Any,
Dict,
Iterable,
List,
Optional,
Sequence,
Tuple,
Type,
Union,
cast,
)
import numpy as np
import numpy.typing as npt
from cirq import Circuit as _Circuit
class EnhancedEnumMeta(EnumMeta):
def __str__(cls) -> str:
return ", ".join([member.value for member in cast(Type[Enum], cls)])
class EnhancedEnum(Enum, metaclass=EnhancedEnumMeta):
# This is for backwards compatibility with the old representation
# of SUPPORTED_PROGRAM_TYPES, which was a dictionary
@classmethod
def keys(cls) -> Iterable[str]:
return [member.value for member in cls]
# Supported quantum programs.
class SUPPORTED_PROGRAM_TYPES(EnhancedEnum):
BRAKET = "braket"
CIRQ = "cirq"
PENNYLANE = "pennylane"
PYQUIL = "pyquil"
QIBO = "qibo"
QISKIT = "qiskit"
try:
from pyquil import Program as _Program
except ImportError: # pragma: no cover
_Program = _Circuit # type: ignore
try:
from qiskit import QuantumCircuit as _QuantumCircuit
except ImportError: # pragma: no cover
_QuantumCircuit = _Circuit
try:
from braket.circuits import Circuit as _BKCircuit
except ImportError: # pragma: no cover
_BKCircuit = _Circuit
try:
from pennylane.tape import QuantumTape as _QuantumTape
except ImportError: # pragma: no cover
_QuantumTape = _Circuit
try:
from qibo.models.circuit import Circuit as _QiboCircuit
except ImportError: # pragma: no cover
_QiboCircuit = _Circuit
# Supported + installed quantum programs.
QPROGRAM = Union[
_Circuit, _Program, _QuantumCircuit, _BKCircuit, _QuantumTape, _QiboCircuit
]
# Define MeasurementResult, a result obtained by measuring qubits on a quantum
# computer.
Bitstring = Union[str, List[int]]
@dataclass
class MeasurementResult:
"""Mitiq object for collecting the bitstrings sampled from a quantum
computer when executing a circuit. This is one of the possible types
(see :class:`~mitiq.typing.QuantumResult`) that an
:class:`.Executor` can return.
Args:
result:
The sequence of measured bitstrings.
qubit_indices:
The qubit indices associated to each
bit in a bitstring (from left to right).
If not given, Mitiq assumes the default ordering
``tuple(range(self.nqubits))``, where ``self.nqubits``
is the bitstring length deduced from ``result``.
Note:
Use caution when selecting the default option for ``qubit_indices``,
especially when estimating an :class:`.Observable`
acting on a subset of qubits. In this case Mitiq
only applies measurement gates to the specific qubits and, therefore,
it is essential to specify the corresponding ``qubit_indices``.
"""
result: Sequence[Bitstring]
qubit_indices: Optional[Tuple[int, ...]] = None
def __post_init__(self) -> None:
# Validate arguments
symbols = set(b for bits in self.result for b in bits)
if not (symbols.issubset({0, 1}) or symbols.issubset({"0", "1"})):
raise ValueError("Bitstrings should look like '011' or [0, 1, 1].")
if symbols.issubset({"0", "1"}):
# Convert to list of integers
int_result = [[int(b) for b in bits] for bits in self.result]
self.result: List[List[int]] = list(int_result)
if isinstance(self.result, np.ndarray):
self.result = self.result.tolist()
self._bitstrings = np.array(self.result)
if not self.qubit_indices:
self.qubit_indices = tuple(range(self.nqubits))
else:
if len(self.qubit_indices) != self.nqubits:
raise ValueError(
f"MeasurementResult has {self.nqubits} qubit(s) but there "
f"are {len(self.qubit_indices)} `qubit_indices`."
)
self._measurements = dict(zip(self.qubit_indices, self._bitstrings.T))
@property
def shots(self) -> int:
return self._bitstrings.shape[0]
@property
def nqubits(self) -> int:
return (
self._bitstrings.shape[1]
if len(self._bitstrings.shape) >= 2
else 0
)
@property
def asarray(self) -> npt.NDArray[np.int64]:
return self._bitstrings
@classmethod
def from_counts(
cls,
counts: Dict[str, int],
qubit_indices: Optional[Tuple[int, ...]] = None,
) -> "MeasurementResult":
"""Initializes a ``MeasurementResult`` from a dictionary of counts.
**Example**::
MeasurementResult.from_counts({"00": 175, "11": 177})
"""
counter = Counter(counts)
return cls(list(counter.elements()), qubit_indices)
def get_counts(self) -> Dict[str, int]:
"""Returns a Python dictionary whose keys are the measured
bitstrings and whose values are the counts.
"""
strings = ["".join(map(str, bits)) for bits in self.result]
return dict(Counter(strings))
def prob_distribution(self) -> Dict[str, float]:
"""Returns a Python dictionary whose keys are the measured
bitstrings and whose values are their empirical frequencies.
"""
return {k: v / self.shots for k, v in self.get_counts().items()}
def to_dict(self) -> Dict[str, Any]:
"""Exports data to a Python dictionary.
Note: Information about the order measurements is not preserved.
"""
return {
"nqubits": self.nqubits,
"qubit_indices": self.qubit_indices,
"shots": self.shots,
"counts": self.get_counts(),
}
@classmethod
def from_dict(cls, data: Dict[str, Any]) -> "MeasurementResult":
"""Loads a ``MeasurementResult`` from a Python dictionary.
Note: Only ``data["counts"]`` and ``data["qubit_indices"]`` are used
by this method. Total shots and number of qubits are deduced.
"""
return cls.from_counts(data["counts"], data["qubit_indices"])
def filter_qubits(self, qubit_indices: List[int]) -> npt.NDArray[np.int64]:
"""Returns the bitstrings associated to a subset of qubits."""
return np.array([self._measurements[i] for i in qubit_indices]).T
def __repr__(self) -> str:
# We redefine __repr__ in this way to avoid very long output strings.
return "MeasurementResult: " + str(self.to_dict())
# An `executor` function inputs a quantum program and outputs an object from
# which expectation values can be computed. Explicitly, this object can be one
# of the following types:
QuantumResult = Union[
float, # The expectation value itself.
MeasurementResult, # Sampled bitstrings.
np.ndarray, # Density matrix.
# TODO: Support the following:
# Sequence[np.ndarray], # Wavefunctions sampled via quantum trajectories.
]
|
https://github.com/unitaryfund/mitiq
|
unitaryfund
|
# Copyright (C) Unitary Fund
#
# This source code is licensed under the GPL license (v3) found in the
# LICENSE file in the root directory of this source tree.
"""Information about Mitiq and dependencies."""
import platform
from cirq import __version__ as cirq_version
from numpy import __version__ as numpy_version
from scipy import __version__ as scipy_version
import mitiq
def about() -> None:
"""Displays information about Mitiq, core/optional packages, and Python
version/platform information.
"""
try:
from pyquil import __version__ as pyquil_version
except ImportError:
pyquil_version = "Not installed"
try:
from qiskit import __qiskit_version__
qiskit_version = __qiskit_version__["qiskit"]
except ImportError:
qiskit_version = "Not installed"
try:
from braket._sdk import __version__ as braket_version
except ImportError:
braket_version = "Not installed"
about_str = f"""
Mitiq: A Python toolkit for implementing error mitigation on quantum computers
==============================================================================
Authored by: Mitiq team, 2020 & later (https://github.com/unitaryfund/mitiq)
Mitiq Version:\t{mitiq.__version__}
Core Dependencies
-----------------
Cirq Version:\t{cirq_version}
NumPy Version:\t{numpy_version}
SciPy Version:\t{scipy_version}
Optional Dependencies
---------------------
PyQuil Version:\t{pyquil_version}
Qiskit Version:\t{qiskit_version}
Braket Version:\t{braket_version}
Python Version:\t{platform.python_version()}
Platform Info:\t{platform.system()} ({platform.machine()})"""
print(about_str)
if __name__ == "__main__":
about()
|
https://github.com/unitaryfund/mitiq
|
unitaryfund
|
# Copyright (C) Unitary Fund
#
# This source code is licensed under the GPL license (v3) found in the
# LICENSE file in the root directory of this source tree.
import json
import cirq
import numpy as np
import pytest
import qiskit
from mitiq import QPROGRAM, SUPPORTED_PROGRAM_TYPES
from mitiq.calibration import PEC_SETTINGS, ZNE_SETTINGS, Settings
from mitiq.calibration.settings import (
BenchmarkProblem,
MitigationTechnique,
Strategy,
)
from mitiq.pec import (
execute_with_pec,
represent_operation_with_local_depolarizing_noise,
)
from mitiq.raw import execute
from mitiq.zne.inference import LinearFactory, RichardsonFactory
from mitiq.zne.scaling import fold_global
light_pec_settings = Settings(
[
{
"circuit_type": "mirror",
"num_qubits": 1,
"circuit_depth": 1,
},
{
"circuit_type": "mirror",
"num_qubits": 2,
"circuit_depth": 1,
},
],
strategies=[
{
"technique": "pec",
"representation_function": (
represent_operation_with_local_depolarizing_noise
),
"is_qubit_dependent": False,
"noise_level": 0.001,
"num_samples": 200,
},
],
)
light_zne_settings = Settings(
[
{
"circuit_type": "mirror",
"num_qubits": 1,
"circuit_depth": 1,
},
{
"circuit_type": "mirror",
"num_qubits": 2,
"circuit_depth": 1,
},
],
strategies=[
{
"technique": "zne",
"scale_noise": fold_global,
"factory": LinearFactory([1.0, 2.0]),
},
],
)
basic_settings = Settings(
benchmarks=[
{
"circuit_type": "ghz",
"num_qubits": 2,
"circuit_depth": 999,
}
],
strategies=[
{
"technique": "zne",
"scale_noise": fold_global,
"factory": RichardsonFactory([1.0, 2.0, 3.0]),
},
{
"technique": "pec",
"representation_function": (
represent_operation_with_local_depolarizing_noise
),
"is_qubit_dependent": False,
"noise_level": 0.001,
"num_samples": 200,
},
],
)
def test_MitigationTechnique():
pec_enum = MitigationTechnique.PEC
assert pec_enum.mitigation_function == execute_with_pec
assert pec_enum.name == "PEC"
raw_enum = MitigationTechnique.RAW
assert raw_enum.mitigation_function == execute
assert raw_enum.name == "RAW"
def test_BenchmarkProblem_make_problems():
settings = basic_settings
problems = settings.make_problems()
assert len(problems) == 1
ghz_problem = problems[0]
assert len(ghz_problem.circuit) == 2
assert ghz_problem.two_qubit_gate_count == 1
assert ghz_problem.ideal_distribution == {"00": 0.5, "11": 0.5}
def test_BenchmarkProblem_repr():
settings = basic_settings
problems = settings.make_problems()
problem_repr = repr(problems[0]).replace("'", '"')
assert isinstance(json.loads(problem_repr), dict)
def test_BenchmarkProblem_str():
settings = basic_settings
circuits = settings.make_problems()
problem = circuits[0]
lines = str(problem).split("\n")
problem_dict = problem.to_dict()
for line in lines:
[title, value] = line.split(":", 1)
key = title.lower().replace(" ", "_")
value = value.strip()
assert key in problem_dict
assert value == str(problem_dict[key])
assert "Ideal distribution: " not in str(problem)
def test_Strategy_repr():
settings = basic_settings
strategies = settings.make_strategies()
strategy_repr = repr(strategies[0]).replace("'", '"')
assert isinstance(json.loads(strategy_repr), dict)
def test_Strategy_str():
settings = basic_settings
strategies = settings.make_strategies()
strategy_str = str(strategies[0])
strategy_pretty_dict = strategies[0].to_pretty_dict()
for line in strategy_str.split("\n"):
[title, value] = line.split(":")
key = title.lower().replace(" ", "_")
value = value.strip()
assert key in strategy_pretty_dict
assert value == str(strategy_pretty_dict[key])
def test_Strategy_pretty_dict():
settings = basic_settings
strategies = settings.make_strategies()
strategy_dict = strategies[0].to_dict()
strategy_pretty_dict = strategies[0].to_pretty_dict()
if strategy_pretty_dict["technique"] == "ZNE":
assert strategy_pretty_dict["factory"] == strategy_dict["factory"][:-7]
assert (
strategy_pretty_dict["scale_factors"]
== str(strategy_dict["scale_factors"])[1:-1]
)
elif strategy_pretty_dict["technique"] == "PEC":
assert strategy_pretty_dict["noise_bias"] == strategy_dict.get(
"noise_bias", "N/A"
)
assert (
strategy_pretty_dict["representation_function"]
== strategy_dict["representation_function"][25:]
)
def test_make_circuits_rotated_rb_circuits():
settings = Settings(
benchmarks=[
{
"circuit_type": "rotated_rb",
"num_qubits": 1,
"circuit_depth": 10,
"theta": np.pi / 3,
}
],
strategies=[
{
"technique": "zne",
"scale_noise": fold_global,
"factory": RichardsonFactory([1.0, 2.0, 3.0]),
},
],
)
problems = settings.make_problems()
assert len(problems) == 1
assert problems[0].type == "rotated_rb"
def test_make_circuits_rotated_rb_circuits_invalid_qubits():
settings = Settings(
benchmarks=[
{
"circuit_type": "rotated_rb",
"num_qubits": 2,
"circuit_depth": 10,
"theta": np.pi / 3,
}
],
strategies=[
{
"technique": "zne",
"scale_noise": fold_global,
"factory": RichardsonFactory([1.0, 2.0, 3.0]),
},
],
)
with pytest.raises(NotImplementedError, match="rotated rb circuits"):
settings.make_problems()
def test_make_circuits_qv_circuits():
settings = Settings(
[
{
"circuit_type": "qv",
"num_qubits": 2,
"circuit_depth": 999,
}
],
strategies=[
{
"technique": "zne",
"scale_noise": fold_global,
"factory": RichardsonFactory([1.0, 2.0, 3.0]),
}
],
)
with pytest.raises(NotImplementedError, match="quantum volume circuits"):
settings.make_problems()
def test_make_circuits_invalid_circuit_type():
settings = Settings(
[{"circuit_type": "foobar", "num_qubits": 2, "circuit_depth": 999}],
strategies=[
{
"technique": "zne",
"scale_noise": fold_global,
"factory": RichardsonFactory([1.0, 2.0, 3.0]),
}
],
)
with pytest.raises(
ValueError, match="invalid value passed for `circuit_types`"
):
settings.make_problems()
def test_make_strategies_invalid_technique():
with pytest.raises(KeyError, match="DESTROY"):
Settings(
[{"circuit_types": "shor", "num_qubits": 2, "circuit_depth": 999}],
strategies=[
{
"technique": "destroy_my_errors",
"scale_noise": fold_global,
"factory": RichardsonFactory([1.0, 2.0, 3.0]),
}
],
)
def test_unsupported_technique_error():
strategy = Strategy(1, MitigationTechnique.RAW, {})
with pytest.raises(
ValueError,
match="Specified technique is not supported by calibration.",
):
strategy.mitigation_function()
def test_ZNE_SETTINGS():
circuits = ZNE_SETTINGS.make_problems()
strategies = ZNE_SETTINGS.make_strategies()
repr_string = repr(circuits[0])
assert all(
s in repr_string
for s in ("type", "ideal_distribution", "num_qubits", "circuit_depth")
)
assert len(circuits) == 4
assert len(strategies) == 2 * 2 * 2
def test_PEC_SETTINGS():
circuits = PEC_SETTINGS.make_problems()
strategies = PEC_SETTINGS.make_strategies()
repr_string = repr(circuits[0])
assert all(
s in repr_string
for s in ("type", "ideal_distribution", "num_qubits", "circuit_depth")
)
assert len(circuits) == 4
assert len(strategies) == 2
@pytest.mark.parametrize("circuit_type", SUPPORTED_PROGRAM_TYPES)
def test_benchmark_problem_class(circuit_type):
qubit = cirq.LineQubit(0)
circuit = cirq.Circuit(cirq.X(qubit))
circuit_with_measurements = circuit.copy()
circuit_with_measurements.append(cirq.measure(qubit))
problem = BenchmarkProblem(
id=7,
circuit=circuit,
type="",
ideal_distribution={},
)
assert problem.circuit == circuit
conv_circ = problem.converted_circuit(circuit_type)
assert any([isinstance(conv_circ, q) for q in QPROGRAM.__args__])
# For at least one case, test the circuit is correct and has measurements
if circuit_type == "qiskit":
qreg = qiskit.QuantumRegister(1, name="q")
creg = qiskit.ClassicalRegister(1, name="m0")
expected = qiskit.QuantumCircuit(qreg, creg)
expected.x(0)
expected.measure(0, 0)
assert conv_circ == expected
def test_settings_make_problems():
"""Test the `make_problems` method of `Settings`"""
settings = Settings(
[
{
"circuit_type": "w",
"num_qubits": 2,
}
],
strategies=[
{
"technique": "zne",
"scale_noise": fold_global,
"factory": RichardsonFactory([1.0, 2.0, 3.0]),
}
],
)
problems = settings.make_problems()
assert len(problems) == 1
ideal_distribution = {"01": 0.5, "10": 0.5}
problem = problems[0]
assert problem.ideal_distribution == ideal_distribution
assert problem.two_qubit_gate_count == 2
assert problem.num_qubits == 2
assert problem.circuit_depth == 2
def test_to_dict():
pec_strategy = light_pec_settings.make_strategies()[0]
assert pec_strategy.to_dict() == {
"technique": "PEC",
"representation_function": (
"represent_operation_with_local_depolarizing_noise"
),
"is_qubit_dependent": False,
"noise_level": 0.001,
"noise_bias": 0,
"num_samples": 200,
}
zne_strategy = light_zne_settings.make_strategies()[0]
assert zne_strategy.to_dict() == {
"technique": "ZNE",
"scale_method": "fold_global",
"factory": "LinearFactory",
"scale_factors": [1.0, 2.0],
}
def test_num_circuits_required_raw_execution():
undefine_strategy = Strategy(
id=1,
technique=MitigationTechnique.RAW,
technique_params={},
)
assert undefine_strategy.num_circuits_required() == 1
|
https://github.com/unitaryfund/mitiq
|
unitaryfund
|
# Copyright (C) Unitary Fund
#
# This source code is licensed under the GPL license (v3) found in the
# LICENSE file in the root directory of this source tree.
"""Unit tests for DDD slack windows and DDD insertion tools."""
import cirq
import numpy as np
import pyquil
import pytest
import qiskit
from mitiq.ddd.insertion import (
_get_circuit_mask,
get_slack_matrix_from_circuit_mask,
insert_ddd_sequences,
)
from mitiq.ddd.rules import xx, xyxy
circuit_cirq_one = cirq.Circuit(
cirq.SWAP(q, q + 1) for q in cirq.LineQubit.range(7)
)
qreg_cirq = cirq.GridQubit.rect(10, 1)
circuit_cirq_two = cirq.Circuit(
cirq.ops.H.on_each(*qreg_cirq),
cirq.ops.H.on(qreg_cirq[1]),
)
circuit_cirq_three = cirq.Circuit(
cirq.ops.H.on_each(*qreg_cirq),
5 * [cirq.ops.H.on(qreg_cirq[1])],
)
circuit_cirq_three_validated = cirq.Circuit(
cirq.ops.H.on_each(*qreg_cirq),
5 * [cirq.ops.H.on(qreg_cirq[1])],
cirq.ops.I.on_each(qreg_cirq[0], *qreg_cirq[2:]),
cirq.ops.X.on_each(qreg_cirq[0], *qreg_cirq[2:]),
cirq.ops.Y.on_each(qreg_cirq[0], *qreg_cirq[2:]),
cirq.ops.X.on_each(qreg_cirq[0], *qreg_cirq[2:]),
cirq.ops.Y.on_each(qreg_cirq[0], *qreg_cirq[2:]),
)
qreg = qiskit.QuantumRegister(4)
creg = qiskit.ClassicalRegister(4)
# Qiskit test without measurement
circuit_qiskit_one = qiskit.QuantumCircuit(qreg)
for q in qreg:
circuit_qiskit_one.x(q)
circuit_qiskit_one.x(3)
circuit_qiskit_one.cx(0, 3)
# Qiskit test with measurement
circuit_qiskit_two = qiskit.QuantumCircuit(qreg, creg)
for q in qreg:
circuit_qiskit_two.x(q)
circuit_qiskit_two.x(3)
circuit_qiskit_two.measure(2, 3)
circuit_qiskit_two.cx(0, 3)
circuit_qiskit_validated = qiskit.QuantumCircuit(qreg)
for i in range(4):
circuit_qiskit_validated.x(i)
circuit_qiskit_validated.x(3)
if i != 3 and i != 0:
circuit_qiskit_validated.id(i)
circuit_qiskit_validated.x(i)
circuit_qiskit_validated.id(i)
circuit_qiskit_validated.x(i)
circuit_qiskit_validated.id(i)
elif i == 0:
circuit_qiskit_validated.id(i)
circuit_qiskit_validated.x(i)
circuit_qiskit_validated.x(i)
circuit_qiskit_validated.id(i)
circuit_qiskit_validated.cx(0, 3)
# Qiskit validate with measurement
circuit_qiskit_two_validated = qiskit.QuantumCircuit(qreg, creg)
for i in range(4):
circuit_qiskit_two_validated.x(i)
circuit_qiskit_two_validated.x(3)
if i != 3 and i != 0:
if i == 1:
circuit_qiskit_two_validated.id(i)
circuit_qiskit_two_validated.id(i)
circuit_qiskit_two_validated.x(i)
circuit_qiskit_two_validated.id(i)
circuit_qiskit_two_validated.x(i)
circuit_qiskit_two_validated.id(i)
elif i == 0:
circuit_qiskit_two_validated.id(i)
circuit_qiskit_two_validated.x(i)
circuit_qiskit_two_validated.x(i)
circuit_qiskit_two_validated.id(i)
circuit_qiskit_two_validated.cx(0, 3)
circuit_qiskit_two_validated.measure(2, 3)
# Define test mask matrices
test_mask_one = np.array(
[
[1, 0, 0, 0, 0, 0, 0],
[1, 1, 0, 0, 0, 0, 0],
[0, 1, 1, 0, 0, 0, 0],
[0, 0, 1, 1, 0, 0, 0],
[0, 0, 0, 1, 1, 0, 0],
[0, 0, 0, 0, 1, 1, 0],
[0, 0, 0, 0, 0, 1, 1],
[0, 0, 0, 0, 0, 0, 1],
]
)
test_mask_two = np.array(
[
[1, 0],
[1, 1],
[1, 0],
[1, 0],
[1, 0],
[1, 0],
[1, 0],
[1, 0],
[1, 0],
[1, 0],
]
)
one_mask = np.array(
[
[0, 1, 1, 1, 1],
[1, 0, 1, 1, 1],
[1, 1, 0, 1, 1],
[1, 1, 1, 0, 1],
[1, 1, 1, 1, 0],
[0, 1, 0, 1, 1],
[1, 0, 1, 0, 1],
[0, 1, 0, 1, 0],
]
)
two_mask = np.array(
[
[0, 0, 1, 1, 1],
[1, 0, 0, 1, 1],
[1, 1, 0, 0, 1],
[1, 1, 1, 0, 0],
[0, 0, 1, 0, 0],
]
)
mixed_mask = np.array(
[
[1, 0, 1, 1, 1],
[1, 1, 0, 0, 1],
[0, 0, 0, 1, 1],
[1, 1, 0, 0, 0],
[1, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[1, 1, 1, 1, 1],
]
)
# Define test slack matrices
one_slack = np.array(
[
[1, 0, 0, 0, 0],
[0, 1, 0, 0, 0],
[0, 0, 1, 0, 0],
[0, 0, 0, 1, 0],
[0, 0, 0, 0, 1],
[1, 0, 1, 0, 0],
[0, 1, 0, 1, 0],
[1, 0, 1, 0, 1],
]
)
two_slack = np.array(
[
[2, 0, 0, 0, 0],
[0, 2, 0, 0, 0],
[0, 0, 2, 0, 0],
[0, 0, 0, 2, 0],
[2, 0, 0, 2, 0],
]
)
mixed_slack = np.array(
[
[0, 1, 0, 0, 0],
[0, 0, 2, 0, 0],
[3, 0, 0, 0, 0],
[0, 0, 3, 0, 0],
[0, 4, 0, 0, 0],
[5, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
]
)
masks = [one_mask, two_mask, mixed_mask]
slack_matrices = [one_slack, two_slack, mixed_slack]
@pytest.mark.parametrize(
("circuit", "test_mask"),
[(circuit_cirq_one, test_mask_one), (circuit_cirq_two, test_mask_two)],
)
def test_get_circuit_mask(circuit, test_mask):
circuit_mask = _get_circuit_mask(circuit)
assert np.allclose(circuit_mask, test_mask)
def test_get_slack_matrix_from_circuit_mask():
for mask, expected in zip(masks, slack_matrices):
slack_matrix = get_slack_matrix_from_circuit_mask(mask)
assert np.allclose(slack_matrix, expected)
def test_get_slack_matrix_from_circuit_mask_extreme_cases():
assert np.allclose(
get_slack_matrix_from_circuit_mask(np.array([[0]])), np.array([[1]])
)
assert np.allclose(
get_slack_matrix_from_circuit_mask(np.array([[1]])), np.array([[0]])
)
def test_get_slack_matrix_from_circuit__bad_input_errors():
with pytest.raises(TypeError, match="must be a numpy"):
get_slack_matrix_from_circuit_mask([[1, 0], [0, 1]])
with pytest.raises(ValueError, match="must be a 2-dimensional"):
get_slack_matrix_from_circuit_mask(np.array([1, 2]))
with pytest.raises(TypeError, match="must have integer elements"):
get_slack_matrix_from_circuit_mask(np.array([[1, 0], [1, 1.7]]))
with pytest.raises(ValueError, match="elements must be 0 or 1"):
get_slack_matrix_from_circuit_mask(np.array([[2, 0], [0, 0]]))
@pytest.mark.parametrize(
("circuit", "result", "rule"),
[
(circuit_cirq_two, circuit_cirq_two, xx),
(circuit_cirq_three, circuit_cirq_three_validated, xyxy),
(circuit_qiskit_one, circuit_qiskit_validated, xx),
(circuit_qiskit_two, circuit_qiskit_two_validated, xx),
],
)
def test_insert_sequences(circuit, result, rule):
circuit_with_sequences = insert_ddd_sequences(circuit, rule)
assert circuit_with_sequences == result
def test_midcircuit_measurement_raises_error():
qreg = qiskit.QuantumRegister(2)
creg = qiskit.ClassicalRegister(1)
circuit = qiskit.QuantumCircuit(qreg, creg)
for q in qreg:
circuit.x(q)
circuit.measure(0, 0)
circuit.cx(0, 1)
with pytest.raises(ValueError, match="midcircuit measurements"):
insert_ddd_sequences(circuit, xx)
def test_pyquil_midcircuit_measurement_raises_error():
p = pyquil.Program()
cbit = p.declare("cbit")
p += pyquil.gates.X(0)
p += pyquil.gates.X(1)
p += pyquil.gates.MEASURE(0, cbit[0])
p += pyquil.gates.X(0)
with pytest.raises(ValueError, match="midcircuit measurements"):
insert_ddd_sequences(p, xx)
def test_insert_sequence_over_identity_gates():
qubits = cirq.LineQubit.range(2)
circuit = cirq.Circuit(
cirq.ops.H.on_each(*qubits),
cirq.ops.I.on_each(*qubits),
cirq.ops.I.on_each(*qubits),
cirq.ops.H.on_each(*qubits),
)
circuit_expected = cirq.Circuit(
cirq.ops.H.on_each(*qubits),
cirq.ops.X.on_each(*qubits),
cirq.ops.X.on_each(*qubits),
cirq.ops.H.on_each(*qubits),
)
ddd_circuit = insert_ddd_sequences(circuit, rule=xx)
assert ddd_circuit == circuit_expected
|
https://github.com/unitaryfund/mitiq
|
unitaryfund
|
# Copyright (C) Unitary Fund
#
# This source code is licensed under the GPL license (v3) found in the
# LICENSE file in the root directory of this source tree.
"""Functions to convert between Mitiq's internal circuit representation and
Qiskit's circuit representation.
"""
import re
from typing import Any, List, Optional, Set, Tuple
import cirq
import numpy as np
import qiskit
from cirq.contrib.qasm_import import circuit_from_qasm
from cirq.contrib.qasm_import.exception import QasmException
from qiskit import qasm2
from qiskit.transpiler import PassManager
from qiskit.transpiler.layout import Layout
from qiskit.transpiler.passes import SetLayout
from mitiq.interface.mitiq_qiskit.transpiler import (
ApplyMitiqLayout,
ClearLayout,
)
from mitiq.utils import _simplify_circuit_exponents
QASMType = str
def _remove_qasm_barriers(qasm: QASMType) -> QASMType:
"""Returns a copy of the input QASM with all barriers removed.
Args:
qasm: QASM to remove barriers from.
Note:
According to the OpenQASM 2.X language specification
(https://arxiv.org/pdf/1707.03429v2.pdf), "Statements are separated by
semicolons. Whitespace is ignored. The language is case sensitive.
Comments begin with a pair of forward slashes and end with a new line."
"""
quoted_re = r"(?:\"[^\"]*?\")"
statement_re = r"((?:[^;{}\"]*?" + quoted_re + r"?)*[;{}])?"
comment_re = r"(\n?//[^\n]*(?:\n|$))?"
statements_comments = re.findall(statement_re + comment_re, qasm)
lines = []
for statement, comment in statements_comments:
if re.match(r"^\s*barrier(?:(?:\s+)|(?:;))", statement) is None:
lines.append(statement + comment)
return "".join(lines)
def _map_bit_index(
bit_index: int, new_register_sizes: List[int]
) -> Tuple[int, int]:
"""Returns the register index and (qu)bit index in this register for the
mapped bit_index.
Args:
bit_index: Index of (qu)bit in the original register.
new_register_sizes: List of sizes of the new registers.
Example:
bit_index = 3, new_register_sizes = [2, 3]
returns (1, 0), meaning the mapped (qu)bit is in the 1st new register
and has index 0 in this register.
Note:
The bit_index is assumed to come from a circuit with 1 or n registers
where n is the maximum bit_index.
"""
max_indices_in_registers = np.cumsum(new_register_sizes) - 1
# Could be faster via bisection.
register_index = None
for i in range(len(max_indices_in_registers)):
if bit_index <= max_indices_in_registers[i]:
register_index = i
break
assert register_index is not None
if register_index == 0:
return register_index, bit_index
return (
register_index,
bit_index - max_indices_in_registers[register_index - 1] - 1,
)
def _add_identity_to_idle(
circuit: qiskit.QuantumCircuit,
) -> Set[qiskit.circuit.Qubit]:
"""Adds identities to idle qubits in the circuit and returns the altered
indices. Used to preserve idle qubits and indices in conversion.
Args:
circuit: Qiskit circuit to have identities added to idle qubits
Returns:
An unordered set of the indices that were altered
Note: An idle qubit is a qubit without any gates (including Qiskit
barriers) acting on it.
"""
all_qubits = set(circuit.qubits)
used_qubits = set()
idle_qubits = set()
# Get used qubits
for op in circuit.data:
_, qubits, _ = op
used_qubits.update(set(qubits))
idle_qubits = all_qubits - used_qubits
# Modify input circuit applying I to idle qubits
for q in idle_qubits:
circuit.id(q)
return idle_qubits
def _remove_identity_from_idle(
circuit: qiskit.QuantumCircuit,
idle_qubits: Set[qiskit.circuit.Qubit],
) -> None:
"""Removes identities from the circuit corresponding to the input
idle qubits.
Used in conjunction with _add_identity_to_idle to preserve idle qubits in
conversion.
Args:
circuit: Qiskit circuit to have identities removed
idle_indices: Set of altered idle qubits.
"""
to_delete_indices: List[int] = []
for index, op in enumerate(circuit._data):
gate, qubits, cbits = op
if gate.name == "id" and set(qubits).intersection(idle_qubits):
to_delete_indices.append(index)
# Traverse data from list end to preserve index
for index in to_delete_indices[::-1]:
del circuit._data[index]
def _measurement_order(
circuit: qiskit.QuantumCircuit,
) -> List[Tuple[Any, ...]]:
"""Returns the left-to-right measurement order in the circuit.
The "measurement order" is a list of tuples (qubit, bit) involved in
measurements ordered as they appear going left-to-right through the circuit
(i.e., iterating through circuit.data). The purpose of this is to be able
to do
>>> for (qubit, bit) in _measurement_order(circuit):
>>> other_circuit.measure(qubit, bit)
which ensures ``other_circuit`` has the same measurement order as
``circuit``, assuming ``other_circuit`` has the same register(s) as
``circuit``.
Args:
circuit: Qiskit circuit to get the measurement order of.
"""
order = []
for gate, qubits, cbits in circuit.data:
if isinstance(gate, qiskit.circuit.Measure):
if len(qubits) != 1 or len(cbits) != 1:
raise ValueError(
f"Only measurements with one qubit and one bit are "
f"supported, but this measurement has {len(qubits)} "
f"qubit(s) and {len(cbits)} bit(s). If you think this "
f"should be supported and is a bug, please open an issue "
f"at https://github.com/unitaryfund/mitiq."
)
order.append((*qubits, *cbits))
return order
def _transform_registers(
circuit: qiskit.QuantumCircuit,
new_qregs: Optional[List[qiskit.QuantumRegister]] = None,
) -> qiskit.QuantumCircuit:
"""Transforms the registers in the circuit to the new registers.
Args:
circuit: Qiskit circuit.
new_qregs: The new quantum registers for the circuit.
Raises:
ValueError:
* If the number of qubits in the new quantum registers is
greater than the number of qubits in the circuit.
"""
if new_qregs is None:
return circuit
qreg_sizes = [qreg.size for qreg in new_qregs]
nqubits_in_circuit = circuit.num_qubits
if len(qreg_sizes) and sum(qreg_sizes) < nqubits_in_circuit:
raise ValueError(
f"The circuit has {nqubits_in_circuit} qubit(s), but the provided "
f"quantum registers have {sum(qreg_sizes)} qubit(s)."
)
circuit_layout = Layout.from_qubit_list(circuit.qubits)
pass_manager = PassManager(
[SetLayout(circuit_layout), ApplyMitiqLayout(new_qregs), ClearLayout()]
)
return pass_manager.run(circuit)
def to_qasm(circuit: cirq.Circuit) -> QASMType:
"""Returns a QASM string representing the input Mitiq circuit.
Args:
circuit: Mitiq circuit to convert to a QASM string.
Returns:
QASMType: QASM string equivalent to the input Mitiq circuit.
"""
# Simplify exponents of gates. For example, H**-1 is simplified to H.
_simplify_circuit_exponents(circuit)
return circuit.to_qasm()
def to_qiskit(circuit: cirq.Circuit) -> qiskit.QuantumCircuit:
"""Returns a Qiskit circuit equivalent to the input Mitiq circuit. Note
that the output circuit registers may not match the input circuit
registers.
Args:
circuit: Mitiq circuit to convert to a Qiskit circuit.
Returns:
Qiskit.QuantumCircuit object equivalent to the input Mitiq circuit.
"""
return qiskit.QuantumCircuit.from_qasm_str(to_qasm(circuit))
def from_qiskit(circuit: qiskit.QuantumCircuit) -> cirq.Circuit:
"""Returns a Mitiq circuit equivalent to the input Qiskit circuit.
Args:
circuit: Qiskit circuit to convert to a Mitiq circuit.
Returns:
Mitiq circuit representation equivalent to the input Qiskit circuit.
"""
try:
mitiq_circuit = from_qasm(qasm2.dumps(circuit))
except QasmException:
# Try to decompose circuit before running
# This is necessary for converting qiskit circuits with
# custom packaged gates, e.g., QFT gates
circuit = circuit.decompose()
mitiq_circuit = from_qasm(qasm2.dumps(circuit))
return mitiq_circuit
def from_qasm(qasm: QASMType) -> cirq.Circuit:
"""Returns a Mitiq circuit equivalent to the input QASM string.
Args:
qasm: QASM string to convert to a Mitiq circuit.
Returns:
Mitiq circuit representation equivalent to the input QASM string.
"""
qasm = _remove_qasm_barriers(qasm)
return circuit_from_qasm(qasm)
|
https://github.com/unitaryfund/mitiq
|
unitaryfund
|
# Copyright (C) Unitary Fund
#
# This source code is licensed under the GPL license (v3) found in the
# LICENSE file in the root directory of this source tree.
"""Qiskit utility functions."""
from functools import partial
from typing import Optional, Tuple
import numpy as np
import numpy.typing as npt
import qiskit
from qiskit import QuantumCircuit
from qiskit.providers import Backend
from qiskit_aer import AerSimulator
# Noise simulation packages
from qiskit_aer.noise import NoiseModel
from qiskit_aer.noise.errors.standard_errors import depolarizing_error
from mitiq import Executor, MeasurementResult, Observable
def initialized_depolarizing_noise(noise_level: float) -> NoiseModel:
"""Initializes a depolarizing noise Qiskit NoiseModel.
Args:
noise_level: The noise strength as a float, e.g., 0.01 is 1%.
Returns:
A Qiskit depolarizing NoiseModel.
"""
# initialize a qiskit noise model
noise_model = NoiseModel()
# we assume the same depolarizing error for each
# gate of the standard IBM basis
noise_model.add_all_qubit_quantum_error(
depolarizing_error(noise_level, 1), ["u1", "u2", "u3"]
)
noise_model.add_all_qubit_quantum_error(
depolarizing_error(noise_level, 2), ["cx"]
)
return noise_model
def execute(circuit: QuantumCircuit, obs: npt.NDArray[np.complex64]) -> float:
"""Simulates a noiseless evolution and returns the
expectation value of some observable.
Args:
circuit: The input Qiskit circuit.
obs: The observable to measure as a NumPy array.
Returns:
The expectation value of obs as a float.
"""
return execute_with_noise(circuit, obs, noise_model=None)
def execute_with_shots(
circuit: QuantumCircuit, obs: npt.NDArray[np.complex64], shots: int
) -> float:
"""Simulates the evolution of the circuit and returns
the expectation value of the observable.
Args:
circuit: The input Qiskit circuit.
obs: The observable to measure as a NumPy array.
shots: The number of measurements.
Returns:
The expectation value of obs as a float.
"""
return execute_with_shots_and_noise(
circuit,
obs,
noise_model=None,
shots=shots,
)
def execute_with_noise(
circuit: QuantumCircuit,
obs: npt.NDArray[np.complex64],
noise_model: NoiseModel,
) -> float:
"""Simulates the evolution of the noisy circuit and returns
the exact expectation value of the observable.
Args:
circuit: The input Qiskit circuit.
obs: The observable to measure as a NumPy array.
noise_model: The input Qiskit noise model.
Returns:
The expectation value of obs as a float.
"""
# Avoid mutating circuit
circ = circuit.copy()
circ.save_density_matrix()
if noise_model is None:
basis_gates = None
else:
basis_gates = noise_model.basis_gates + ["save_density_matrix"]
# execution of the experiment
backend = AerSimulator(method="density_matrix", noise_model=noise_model)
exec_circuit = qiskit.transpile(
circ,
backend=backend,
basis_gates=basis_gates,
# we want all gates to be actually applied,
# so we skip any circuit optimization
optimization_level=0,
)
job = backend.run(exec_circuit, shots=1)
rho = job.result().data()["density_matrix"]
expectation = np.real(np.trace(rho @ obs))
return expectation
def execute_with_shots_and_noise(
circuit: QuantumCircuit,
obs: npt.NDArray[np.complex64],
noise_model: NoiseModel,
shots: int,
seed: Optional[int] = None,
) -> float:
"""Simulates the evolution of the noisy circuit and returns
the statistical estimate of the expectation value of the observable.
Args:
circuit: The input Qiskit circuit.
obs: The observable to measure as a NumPy array.
noise_model: The input Qiskit noise model.
shots: The number of measurements.
seed: Optional seed for qiskit simulator.
Returns:
The expectation value of obs as a float.
"""
# Avoid mutating circuit
circ = circuit.copy()
# we need to modify the circuit to measure obs in its eigenbasis
# we do this by appending a unitary operation
# obtains a U s.t. obs = U diag(eigvals) U^dag
eigvals, U = np.linalg.eigh(obs)
circ.unitary(np.linalg.inv(U), qubits=range(circ.num_qubits))
circ.measure_all()
if noise_model is None:
basis_gates = None
else:
basis_gates = noise_model.basis_gates
# execution of the experiment
backend = AerSimulator(method="density_matrix", noise_model=noise_model)
exec_circuit = qiskit.transpile(
circ,
backend=backend,
basis_gates=basis_gates,
# we want all gates to be actually applied,
# so we skip any circuit optimization
optimization_level=0,
)
job = backend.run(exec_circuit, shots=shots, seed_simulator=seed)
counts = job.result().get_counts()
expectation = 0
for bitstring, count in counts.items():
expectation += (
eigvals[int(bitstring[0 : circ.num_qubits], 2)] * count / shots
)
return expectation
def sample_bitstrings(
circuit: QuantumCircuit,
backend: Optional[Backend] = None,
noise_model: Optional[NoiseModel] = None,
shots: int = 10000,
measure_all: bool = False,
qubit_indices: Optional[Tuple[int]] = None,
) -> MeasurementResult:
"""Returns measurement bitstrings obtained from executing the input circuit
on a Qiskit backend (passed as an argument).
Note that the input circuit must contain measurement gates
(unless ``measure_all`` is ``True``).
Args:
circuit: The input Qiskit circuit.
backend: A real or fake Qiskit backend. The input circuit
should be transpiled into a compatible gate set.
It may be necessary to set ``optimization_level=0`` when
transpiling.
noise_model: A valid Qiskit ``NoiseModel`` object. This option is used
if and only if ``backend`` is ``None``. In this case a default
density matrix simulator is used with ``optimization_level=0``.
shots: The number of measurements.
measure_all: If True, measurement gates are applied to all qubits.
qubit_indices: Optional qubit indices associated to bitstrings.
Returns:
The measured bitstrings casted as a Mitiq :class:`.MeasurementResult`
object.
"""
if measure_all:
circuit = circuit.measure_all(inplace=False)
if backend:
job = backend.run(circuit, shots=shots)
elif noise_model:
backend = AerSimulator(
method="density_matrix", noise_model=noise_model
)
exec_circuit = qiskit.transpile(
circuit,
backend=backend,
basis_gates=noise_model.basis_gates,
# we want all gates to be actually applied,
# so we skip any circuit optimization
optimization_level=0,
)
job = backend.run(exec_circuit, shots=shots)
else:
raise ValueError(
"Either a backend or a noise model must be given as input."
)
counts = job.result().get_counts(circuit)
bitstrings = []
for key, val in counts.items():
bitstring = [int(c) for c in key]
for _ in range(val):
bitstrings.append(bitstring)
return MeasurementResult(
result=bitstrings,
qubit_indices=qubit_indices,
)
def compute_expectation_value_on_noisy_backend(
circuit: QuantumCircuit,
obs: Observable,
backend: Optional[Backend] = None,
noise_model: Optional[NoiseModel] = None,
shots: int = 10000,
measure_all: bool = False,
qubit_indices: Optional[Tuple[int]] = None,
) -> complex:
"""Returns the noisy expectation value of the input Mitiq observable
obtained from executing the input circuit on a Qiskit backend.
Args:
circuit: The input Qiskit circuit.
obs: The Mitiq observable to compute the expectation value of.
backend: A real or fake Qiskit backend. The input circuit
should be transpiled into a compatible gate set.
noise_model: A valid Qiskit ``NoiseModel`` object. This option is used
if and only if ``backend`` is ``None``. In this case a default
density matrix simulator is used with ``optimization_level=0``.
shots: The number of measurements.
measure_all: If True, measurement gates are applied to all qubits.
qubit_indices: Optional qubit indices associated to bitstrings.
Returns:
The noisy expectation value.
"""
execute = partial(
sample_bitstrings,
backend=backend,
noise_model=noise_model,
shots=shots,
measure_all=measure_all,
qubit_indices=qubit_indices,
)
executor = Executor(execute)
return executor.evaluate(circuit, obs)[0]
|
https://github.com/unitaryfund/mitiq
|
unitaryfund
|
# -*- 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=too-many-function-args, unexpected-keyword-arg
"""THIS FILE IS DEPRECATED AND WILL BE REMOVED IN RELEASE 0.9.
"""
import warnings
from qiskit.converters import dag_to_circuit, circuit_to_dag
from qiskit.transpiler import CouplingMap
from qiskit import compiler
from qiskit.transpiler.preset_passmanagers import (default_pass_manager_simulator,
default_pass_manager)
def transpile(circuits, backend=None, basis_gates=None, coupling_map=None,
initial_layout=None, seed_mapper=None, pass_manager=None):
"""transpile one or more circuits.
Args:
circuits (QuantumCircuit or list[QuantumCircuit]): circuits to compile
backend (BaseBackend): a backend to compile for
basis_gates (list[str]): list of basis gate names supported by the
target. Default: ['u1','u2','u3','cx','id']
coupling_map (list): coupling map (perhaps custom) to target in mapping
initial_layout (Layout or dict or list):
Initial position of virtual qubits on physical qubits. The final
layout is not guaranteed to be the same, as the transpiler may permute
qubits through swaps or other means.
seed_mapper (int): random seed for the swap_mapper
pass_manager (PassManager): a pass_manager for the transpiler stages
Returns:
QuantumCircuit or list[QuantumCircuit]: transpiled circuit(s).
Raises:
TranspilerError: in case of bad inputs to transpiler or errors in passes
"""
warnings.warn("qiskit.transpiler.transpile() has been deprecated and will be "
"removed in the 0.9 release. Use qiskit.compiler.transpile() instead.",
DeprecationWarning)
return compiler.transpile(circuits=circuits, backend=backend,
basis_gates=basis_gates, coupling_map=coupling_map,
initial_layout=initial_layout, seed_transpiler=seed_mapper,
pass_manager=pass_manager)
def transpile_dag(dag, basis_gates=None, coupling_map=None,
initial_layout=None, seed_mapper=None, pass_manager=None):
"""Deprecated - Use qiskit.compiler.transpile for transpiling from
circuits to circuits.
Transform a dag circuit into another dag circuit
(transpile), through consecutive passes on the dag.
Args:
dag (DAGCircuit): dag circuit to transform via transpilation
basis_gates (list[str]): list of basis gate names supported by the
target. Default: ['u1','u2','u3','cx','id']
coupling_map (list): A graph of coupling::
[
[control0(int), target0(int)],
[control1(int), target1(int)],
]
eg. [[0, 2], [1, 2], [1, 3], [3, 4]}
initial_layout (Layout or None): A layout object
seed_mapper (int): random seed_mapper for the swap mapper
pass_manager (PassManager): pass manager instance for the transpilation process
If None, a default set of passes are run.
Otherwise, the passes defined in it will run.
If contains no passes in it, no dag transformations occur.
Returns:
DAGCircuit: transformed dag
"""
warnings.warn("transpile_dag has been deprecated and will be removed in the "
"0.9 release. Circuits can be transpiled directly to other "
"circuits with the transpile function.", DeprecationWarning)
if basis_gates is None:
basis_gates = ['u1', 'u2', 'u3', 'cx', 'id']
if pass_manager is None:
# default set of passes
# if a coupling map is given compile to the map
if coupling_map:
pass_manager = default_pass_manager(basis_gates,
CouplingMap(coupling_map),
initial_layout,
seed_transpiler=seed_mapper)
else:
pass_manager = default_pass_manager_simulator(basis_gates)
# run the passes specified by the pass manager
# TODO return the property set too. See #1086
name = dag.name
circuit = dag_to_circuit(dag)
circuit = pass_manager.run(circuit)
dag = circuit_to_dag(circuit)
dag.name = name
return dag
|
https://github.com/unitaryfund/mitiq
|
unitaryfund
|
# Copyright (C) 2024 qBraid
#
# This file is part of the qBraid-SDK
#
# The qBraid-SDK is free software released under the GNU General Public License v3
# or later. You can redistribute and/or modify it under the terms of the GPL v3.
# See the LICENSE file in the project root or <https://www.gnu.org/licenses/gpl-3.0.html>.
#
# THERE IS NO WARRANTY for the qBraid-SDK, as per Section 15 of the GPL v3.
"""
Unit tests for conversions between Cirq circuits and Qiskit circuits.
"""
import cirq
import numpy as np
import pytest
import qiskit
from cirq import Circuit, LineQubit, ops, testing
from qiskit import QuantumCircuit
from qiskit.circuit.random import random_circuit
from qbraid.interface import circuits_allclose
from qbraid.programs import load_program
from qbraid.programs.exceptions import QasmError
from qbraid.transpiler.conversions.cirq import cirq_to_qasm2
from qbraid.transpiler.conversions.qasm2 import qasm2_to_cirq
from qbraid.transpiler.conversions.qasm3 import qasm3_to_qiskit
from qbraid.transpiler.conversions.qiskit import qiskit_to_qasm2, qiskit_to_qasm3
from qbraid.transpiler.converter import transpile
from qbraid.transpiler.exceptions import CircuitConversionError
from ..cirq_utils import _equal
def test_bell_state_to_from_circuits():
"""Tests cirq.Circuit --> qiskit.QuantumCircuit --> cirq.Circuit
with a Bell state circuit.
"""
qreg = cirq.LineQubit.range(2)
cirq_circuit = cirq.Circuit([cirq.ops.H.on(qreg[0]), cirq.ops.CNOT.on(qreg[0], qreg[1])])
qiskit_circuit = transpile(cirq_circuit, "qiskit") # Qiskit from Cirq
circuit_cirq = transpile(qiskit_circuit, "cirq") # Cirq from Qiskit
assert np.allclose(cirq_circuit.unitary(), circuit_cirq.unitary())
def test_bell_state_to_qiskit():
"""Tests cirq.Circuit --> qiskit.QuantumCircuit --> cirq.Circuit
with a Bell state circuit."""
qreg = LineQubit.range(2)
cirq_circuit = Circuit([ops.H.on(qreg[0]), ops.CNOT.on(qreg[0], qreg[1])])
qiskit_circuit = transpile(cirq_circuit, "qiskit")
assert circuits_allclose(qiskit_circuit, cirq_circuit, strict_gphase=True)
@pytest.mark.parametrize("num_qubits", [1, 2, 3, 4, 5])
def test_random_circuit_to_qiskit(num_qubits):
"""Tests converting random Cirq circuits to Qiskit circuits."""
for _ in range(10):
cirq_circuit = testing.random_circuit(
qubits=num_qubits,
n_moments=np.random.randint(1, 6),
op_density=1,
random_state=np.random.randint(1, 10),
)
qiskit_circuit = transpile(cirq_circuit, "qiskit")
assert circuits_allclose(qiskit_circuit, cirq_circuit, strict_gphase=True)
def test_bell_state_to_from_qasm():
"""Tests cirq.Circuit --> QASM string --> cirq.Circuit
with a Bell state circuit.
"""
qreg = cirq.LineQubit.range(2)
cirq_circuit = cirq.Circuit([cirq.ops.H.on(qreg[0]), cirq.ops.CNOT.on(qreg[0], qreg[1])])
qasm = cirq_to_qasm2(cirq_circuit) # Qasm from Cirq
circuit_cirq = qasm2_to_cirq(qasm)
assert np.allclose(cirq_circuit.unitary(), circuit_cirq.unitary())
def test_random_circuit_to_from_circuits():
"""Tests cirq.Circuit --> qiskit.QuantumCircuit --> cirq.Circuit
with a random two-qubit circuit.
"""
cirq_circuit = cirq.testing.random_circuit(
qubits=2, n_moments=10, op_density=0.99, random_state=1
)
qiskit_circuit = transpile(cirq_circuit, "qiskit")
circuit_cirq = transpile(qiskit_circuit, "cirq")
assert np.allclose(cirq_circuit.unitary(), circuit_cirq.unitary())
def test_random_circuit_to_from_qasm():
"""Tests cirq.Circuit --> QASM string --> cirq.Circuit
with a random one-qubit circuit.
"""
circuit_0 = cirq.testing.random_circuit(qubits=2, n_moments=10, op_density=0.99, random_state=2)
qasm = cirq_to_qasm2(circuit_0)
circuit_1 = qasm2_to_cirq(qasm)
u_0 = circuit_0.unitary()
u_1 = circuit_1.unitary()
assert cirq.equal_up_to_global_phase(u_0, u_1)
@pytest.mark.parametrize("as_qasm", (True, False))
def test_convert_with_barrier(as_qasm):
"""Tests converting a Qiskit circuit with a barrier to a Cirq circuit."""
n = 5
qiskit_circuit = qiskit.QuantumCircuit(qiskit.QuantumRegister(n))
qiskit_circuit.barrier()
if as_qasm:
cirq_circuit = qasm2_to_cirq(qiskit_to_qasm2(qiskit_circuit))
else:
cirq_circuit = transpile(qiskit_circuit, "cirq")
assert _equal(cirq_circuit, cirq.Circuit())
@pytest.mark.parametrize("as_qasm", (True, False))
def test_convert_with_multiple_barriers(as_qasm):
"""Tests converting a Qiskit circuit with barriers to a Cirq circuit."""
n = 1
num_ops = 10
qreg = qiskit.QuantumRegister(n)
qiskit_circuit = qiskit.QuantumCircuit(qreg)
for _ in range(num_ops):
qiskit_circuit.h(qreg)
qiskit_circuit.barrier()
if as_qasm:
cirq_circuit = qasm2_to_cirq(qiskit_to_qasm2(qiskit_circuit))
else:
cirq_circuit = transpile(qiskit_circuit, "cirq")
qbit = cirq.LineQubit(0)
correct = cirq.Circuit(cirq.ops.H.on(qbit) for _ in range(num_ops))
assert _equal(cirq_circuit, correct)
assert circuits_allclose(qiskit_circuit, cirq_circuit, strict_gphase=True)
def test_bell_state_from_qiskit():
"""Tests qiskit.QuantumCircuit --> cirq.Circuit
with a Bell state circuit.
"""
qiskit_circuit = QuantumCircuit(2)
qiskit_circuit.h(0)
qiskit_circuit.cx(0, 1)
cirq_circuit = transpile(qiskit_circuit, "cirq")
assert circuits_allclose(qiskit_circuit, cirq_circuit, strict_gphase=True)
def test_common_gates_from_qiskit():
"""Tests converting standard gates from Qiskit to Cirq."""
qiskit_circuit = QuantumCircuit(4)
qiskit_circuit.h([0, 1, 2, 3])
qiskit_circuit.x([0, 1])
qiskit_circuit.y(2)
qiskit_circuit.z(3)
qiskit_circuit.s(0)
qiskit_circuit.sdg(1)
qiskit_circuit.t(2)
qiskit_circuit.tdg(3)
qiskit_circuit.rx(np.pi / 4, 0)
qiskit_circuit.ry(np.pi / 2, 1)
qiskit_circuit.rz(3 * np.pi / 4, 2)
qiskit_circuit.p(np.pi / 8, 3)
qiskit_circuit.sx(0)
qiskit_circuit.sxdg(1)
qiskit_circuit.iswap(2, 3)
qiskit_circuit.swap([0, 1], [2, 3])
qiskit_circuit.cx(0, 1)
qiskit_circuit.cp(np.pi / 4, 2, 3)
cirq_circuit = transpile(qiskit_circuit, "cirq")
assert circuits_allclose(qiskit_circuit, cirq_circuit, strict_gphase=True)
@pytest.mark.parametrize("qubits", ([0, 1], [1, 0]))
def test_crz_gate_from_qiskit(qubits):
"""Tests converting controlled Rz gate from Qiskit to Cirq."""
qiskit_circuit = QuantumCircuit(2)
qiskit_circuit.crz(np.pi / 4, *qubits)
cirq_circuit = transpile(qiskit_circuit, "cirq", require_native=True)
assert circuits_allclose(qiskit_circuit, cirq_circuit, strict_gphase=True)
@pytest.mark.parametrize("qubits", ([0, 1], [1, 0]))
@pytest.mark.parametrize("theta", (0, 2 * np.pi, np.pi / 2, np.pi / 4))
def test_rzz_gate_from_qiskit(qubits, theta):
"""Tests converting Rzz gate from Qiskit to Cirq."""
qiskit_circuit = QuantumCircuit(2)
qiskit_circuit.rzz(theta, *qubits)
cirq_circuit = transpile(qiskit_circuit, "cirq")
assert circuits_allclose(qiskit_circuit, cirq_circuit, strict_gphase=True)
def test_iswap_gate_from_qiskit():
"""Tests converting iSwap gate from Qiskit to Cirq."""
qiskit_circuit = QuantumCircuit(2)
qiskit_circuit.h([0, 1])
qiskit_circuit.iswap(0, 1)
cirq_circuit = transpile(qiskit_circuit, "cirq")
assert circuits_allclose(qiskit_circuit, cirq_circuit, strict_gphase=True)
def test_qiskit_roundtrip():
"""Test converting qiskit gates that previously failed qiskit roundtrip test."""
qiskit_circuit = QuantumCircuit(3)
qiskit_circuit.ccz(0, 1, 2)
qiskit_circuit.ecr(1, 2)
qiskit_circuit.cs(2, 0)
cirq_circuit = transpile(qiskit_circuit, "cirq", require_native=True)
assert circuits_allclose(qiskit_circuit, cirq_circuit, strict_gphase=False)
def test_qiskit_roundtrip_noncontig():
"""Test converting gates that previously failed qiskit roundtrip test
with non-contiguous qubits."""
qiskit_circuit = QuantumCircuit(4)
qiskit_circuit.ccz(0, 1, 2)
qiskit_circuit.ecr(1, 2)
qiskit_circuit.cs(2, 0)
cirq_circuit = transpile(qiskit_circuit, "cirq", require_native=True)
qprogram = load_program(cirq_circuit)
qprogram.remove_idle_qubits()
qiskit_contig = qprogram.program
assert circuits_allclose(qiskit_contig, cirq_circuit, strict_gphase=False)
def test_100_random_qiskit():
"""Test converting 100 random qiskit circuits to cirq."""
for _ in range(100):
qiskit_circuit = random_circuit(4, 1)
cirq_circuit = transpile(qiskit_circuit, "cirq", require_native=True)
assert circuits_allclose(qiskit_circuit, cirq_circuit, strict_gphase=False)
def test_qiskit_to_from_qasm3():
"""Test converting qiskit circuit to/from OpenQASM 3.0 string"""
circuit_in = QuantumCircuit(2)
circuit_in.h(0)
circuit_in.cx(0, 1)
qasm3_str = qiskit_to_qasm3(circuit_in)
circuit_out = qasm3_to_qiskit(qasm3_str)
assert circuits_allclose(circuit_in, circuit_out, strict_gphase=True)
def test_raise_circuit_conversion_error():
"""Tests raising error for unsupported gates."""
with pytest.raises(CircuitConversionError):
probs = np.random.uniform(low=0, high=0.5)
cirq_circuit = Circuit(ops.PhaseDampingChannel(probs).on(*LineQubit.range(1)))
transpile(cirq_circuit, "qiskit")
def test_raise_qasm_error():
"""Test raising error for unsupported gates."""
with pytest.raises(QasmError):
qiskit_circuit = QuantumCircuit(1)
qiskit_circuit.delay(300, 0)
qasm2 = qiskit_to_qasm2(qiskit_circuit)
_ = qasm2_to_cirq(qasm2)
|
https://github.com/unitaryfund/mitiq
|
unitaryfund
|
# Copyright (C) Unitary Fund
#
# This source code is licensed under the GPL license (v3) found in the
# LICENSE file in the root directory of this source tree.
"""Unit tests for qiskit executors (qiskit_utils.py)."""
import numpy as np
import pytest
from qiskit import QuantumCircuit
from qiskit_ibm_runtime.fake_provider import FakeLima
from mitiq import MeasurementResult, Observable, PauliString
from mitiq.interface.mitiq_qiskit.qiskit_utils import (
compute_expectation_value_on_noisy_backend,
execute,
execute_with_noise,
execute_with_shots,
execute_with_shots_and_noise,
initialized_depolarizing_noise,
sample_bitstrings,
)
NOISE = 0.007
ONE_QUBIT_GS_PROJECTOR = np.array([[1, 0], [0, 0]])
TWO_QUBIT_GS_PROJECTOR = np.diag([1, 0, 0, 0])
SHOTS = 1_000
def test_execute():
"""Tests the Qiskit wavefunction simulation executor returns
appropriate expectation value given an observable.
"""
circ = QuantumCircuit(1)
expected_value = execute(circ, obs=ONE_QUBIT_GS_PROJECTOR)
assert expected_value == 1.0
second_circ = QuantumCircuit(1)
second_circ.x(0)
expected_value = execute(second_circ, obs=ONE_QUBIT_GS_PROJECTOR)
assert expected_value == 0.0
def test_execute_with_shots():
"""Tests the Qiskit wavefunction sampling simulation executor returns
appropriate expectation value given an observable.
"""
circ = QuantumCircuit(1, 1)
expectation_value = execute_with_shots(
circuit=circ, obs=ONE_QUBIT_GS_PROJECTOR, shots=SHOTS
)
assert expectation_value == 1.0
second_circ = QuantumCircuit(1)
second_circ.x(0)
expectation_value = execute_with_shots(
circuit=second_circ, obs=ONE_QUBIT_GS_PROJECTOR, shots=SHOTS
)
assert expectation_value == 0.0
def test_execute_with_depolarizing_noise_single_qubit():
"""Tests the noisy sampling executor across increasing levels
of single qubit gate noise
"""
single_qubit_circ = QuantumCircuit(1)
# noise model is defined on gates so include the gate to
# demonstrate noise
single_qubit_circ.z(0)
noiseless_exp_value = 1.0
expectation_value = execute_with_noise(
circuit=single_qubit_circ,
obs=ONE_QUBIT_GS_PROJECTOR,
noise_model=initialized_depolarizing_noise(NOISE),
)
# anticipate that the expectation value will be less than
# the noiseless simulation of the same circuit
assert expectation_value < noiseless_exp_value
def test_execute_with_depolarizing_noise_two_qubit():
"""Tests the noisy sampling executor across increasing levels of
two qubit gate noise.
"""
two_qubit_circ = QuantumCircuit(2)
# noise model is defined on gates so include the gate to
# demonstrate noise
two_qubit_circ.cx(0, 1)
noiseless_exp_value = 1.0
expectation_value = execute_with_noise(
circuit=two_qubit_circ,
obs=TWO_QUBIT_GS_PROJECTOR,
noise_model=initialized_depolarizing_noise(NOISE),
)
# anticipate that the expectation value will be less than
# the noiseless simulation of the same circuit
assert expectation_value < noiseless_exp_value
def test_execute_with_shots_and_depolarizing_noise_single_qubit():
"""Tests the noisy sampling executor across increasing levels
of single qubit gate noise.
"""
single_qubit_circ = QuantumCircuit(1, 1)
# noise model is defined on gates so include the gate to
# demonstrate noise
single_qubit_circ.z(0)
noiseless_exp_value = 1.0
expectation_value = execute_with_shots_and_noise(
circuit=single_qubit_circ,
obs=ONE_QUBIT_GS_PROJECTOR,
noise_model=initialized_depolarizing_noise(NOISE),
shots=SHOTS,
)
# anticipate that the expectation value will be less than
# the noiseless simulation of the same circuit
assert expectation_value < noiseless_exp_value
def test_execute_with_shots_and_depolarizing_noise_two_qubit():
"""Tests the noisy sampling executor across increasing levels of
two qubit gate noise.
"""
two_qubit_circ = QuantumCircuit(2, 2)
# noise model is defined on gates so include the gate to
# demonstrate noise
two_qubit_circ.cx(0, 1)
noiseless_exp_value = 1.0
expectation_value = execute_with_shots_and_noise(
circuit=two_qubit_circ,
obs=TWO_QUBIT_GS_PROJECTOR,
noise_model=initialized_depolarizing_noise(NOISE),
shots=SHOTS,
)
# anticipate that the expectation value will be less than
# the noiseless simulation of the same circuit
assert expectation_value < noiseless_exp_value
def test_circuit_is_not_mutated_by_executors():
single_qubit_circ = QuantumCircuit(1, 1)
single_qubit_circ.z(0)
expected_circuit = single_qubit_circ.copy()
execute_with_shots_and_noise(
circuit=single_qubit_circ,
obs=ONE_QUBIT_GS_PROJECTOR,
noise_model=initialized_depolarizing_noise(NOISE),
shots=SHOTS,
)
assert single_qubit_circ.data == expected_circuit.data
assert single_qubit_circ == expected_circuit
execute_with_noise(
circuit=single_qubit_circ,
obs=ONE_QUBIT_GS_PROJECTOR,
noise_model=initialized_depolarizing_noise(NOISE),
)
assert single_qubit_circ.data == expected_circuit.data
assert single_qubit_circ == expected_circuit
def test_sample_bitstrings():
"""Tests that the function sample_bitstrings returns a valid
mitiq.MeasurementResult.
"""
two_qubit_circ = QuantumCircuit(2, 1)
two_qubit_circ.cx(0, 1)
two_qubit_circ.measure(0, 0)
measurement_result = sample_bitstrings(
circuit=two_qubit_circ,
backend=None,
noise_model=initialized_depolarizing_noise(0),
shots=5,
)
assert measurement_result.result == [[0], [0], [0], [0], [0]]
assert measurement_result.qubit_indices == (0,)
def test_sample_bitstrings_with_measure_all():
"""Tests that the function sample_bitstrings returns a valid
mitiq.MeasurementResult when "measure_all" is True.
"""
two_qubit_circ = QuantumCircuit(2)
two_qubit_circ.cx(0, 1)
measurement_result = sample_bitstrings(
circuit=two_qubit_circ,
backend=None,
noise_model=initialized_depolarizing_noise(0),
shots=2,
measure_all=True,
)
assert measurement_result.result == [[0, 0], [0, 0]]
assert measurement_result.qubit_indices == (0, 1)
assert isinstance(measurement_result, MeasurementResult)
def test_sample_bitstrings_with_backend():
"""Tests that the function sample_bitstrings returns a valid
mitiq.MeasurementResult if a qiskit backend is used.
"""
two_qubit_circ = QuantumCircuit(2)
two_qubit_circ.cx(0, 1)
measurement_result = sample_bitstrings(
circuit=two_qubit_circ,
backend=FakeLima(),
shots=5,
measure_all=True,
)
assert len(measurement_result.result) == 5
assert len(measurement_result.result[0]) == 2
assert measurement_result.qubit_indices == (0, 1)
def test_sample_bitstrings_error_message():
"""Tests that an error is given backend and nose_model are both None."""
two_qubit_circ = QuantumCircuit(2)
two_qubit_circ.cx(0, 1)
with pytest.raises(ValueError, match="Either a backend or a noise model"):
sample_bitstrings(
circuit=two_qubit_circ,
shots=5,
)
def test_compute_expectation_value_on_noisy_backend_with_noise_model():
"""Tests the evaluation of an expectation value assuming a noise model."""
obs = Observable(PauliString("X"))
qiskit_circuit = QuantumCircuit(1)
qiskit_circuit.h(0)
# First we try without noise
noiseless_expval = compute_expectation_value_on_noisy_backend(
qiskit_circuit,
obs,
noise_model=initialized_depolarizing_noise(0),
)
assert isinstance(noiseless_expval, complex)
assert np.isclose(np.imag(noiseless_expval), 0.0)
assert np.isclose(np.real(noiseless_expval), 1.0)
# Now we try with noise
expval = compute_expectation_value_on_noisy_backend(
qiskit_circuit,
obs,
noise_model=initialized_depolarizing_noise(0.01),
)
assert isinstance(expval, complex)
assert np.isclose(np.imag(expval), 0.0)
# With noise the result is non-deterministic
assert 0.9 < np.real(expval) < 1.0
def test_compute_expectation_value_on_noisy_backend_with_qiskit_backend():
"""Tests the evaluation of an expectation value on a noisy backed"""
obs = Observable(PauliString("X"))
qiskit_circuit = QuantumCircuit(1)
qiskit_circuit.h(0)
expval = compute_expectation_value_on_noisy_backend(
qiskit_circuit,
obs,
backend=FakeLima(),
)
assert isinstance(expval, complex)
assert np.isclose(np.imag(expval), 0.0)
# With noise the result is non-deterministic
assert 0.9 < np.real(expval) < 1.0
|
https://github.com/unitaryfund/mitiq
|
unitaryfund
|
# 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.
"""Tests basic functionality of the transpile function"""
import copy
import io
import math
import os
import sys
import unittest
from logging import StreamHandler, getLogger
from test import combine # pylint: disable=wrong-import-order
from unittest.mock import patch
import numpy as np
import rustworkx as rx
from ddt import data, ddt, unpack
from qiskit import BasicAer, ClassicalRegister, QuantumCircuit, QuantumRegister, pulse, qasm3, qpy
from qiskit.circuit import (
Clbit,
ControlFlowOp,
ForLoopOp,
Gate,
IfElseOp,
Parameter,
Qubit,
Reset,
SwitchCaseOp,
WhileLoopOp,
)
from qiskit.circuit.classical import expr
from qiskit.circuit.delay import Delay
from qiskit.circuit.library import (
CXGate,
CZGate,
HGate,
RXGate,
RYGate,
RZGate,
SXGate,
U1Gate,
U2Gate,
UGate,
XGate,
)
from qiskit.circuit.measure import Measure
from qiskit.compiler import transpile
from qiskit.converters import circuit_to_dag
from qiskit.dagcircuit import DAGOpNode, DAGOutNode
from qiskit.exceptions import QiskitError
from qiskit.providers.backend import BackendV2
from qiskit.providers.fake_provider import (
FakeBoeblingen,
FakeMelbourne,
FakeMumbaiV2,
FakeNairobiV2,
FakeRueschlikon,
FakeSherbrooke,
FakeVigo,
)
from qiskit.providers.options import Options
from qiskit.pulse import InstructionScheduleMap
from qiskit.quantum_info import Operator, random_unitary
from qiskit.test import QiskitTestCase, slow_test
from qiskit.tools import parallel
from qiskit.transpiler import CouplingMap, Layout, PassManager, TransformationPass
from qiskit.transpiler.exceptions import TranspilerError
from qiskit.transpiler.passes import BarrierBeforeFinalMeasurements, GateDirection, VF2PostLayout
from qiskit.transpiler.passmanager_config import PassManagerConfig
from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager, level_0_pass_manager
from qiskit.transpiler.target import InstructionProperties, Target
class CustomCX(Gate):
"""Custom CX gate representation."""
def __init__(self):
super().__init__("custom_cx", 2, [])
def _define(self):
self._definition = QuantumCircuit(2)
self._definition.cx(0, 1)
def connected_qubits(physical: int, coupling_map: CouplingMap) -> set:
"""Get the physical qubits that have a connection to this one in the coupling map."""
for component in coupling_map.connected_components():
if physical in (qubits := set(component.graph.nodes())):
return qubits
raise ValueError(f"physical qubit {physical} is not in the coupling map")
@ddt
class TestTranspile(QiskitTestCase):
"""Test transpile function."""
def test_empty_transpilation(self):
"""Test that transpiling an empty list is a no-op. Regression test of gh-7287."""
self.assertEqual(transpile([]), [])
def test_pass_manager_none(self):
"""Test passing the default (None) pass manager to the transpiler.
It should perform the default qiskit flow:
unroll, swap_mapper, cx_direction, cx_cancellation, optimize_1q_gates
and should be equivalent to using tools.compile
"""
qr = QuantumRegister(2, "qr")
circuit = QuantumCircuit(qr)
circuit.h(qr[0])
circuit.h(qr[0])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[1], qr[0])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[1], qr[0])
coupling_map = [[1, 0]]
basis_gates = ["u1", "u2", "u3", "cx", "id"]
backend = BasicAer.get_backend("qasm_simulator")
circuit2 = transpile(
circuit,
backend=backend,
coupling_map=coupling_map,
basis_gates=basis_gates,
)
circuit3 = transpile(
circuit, backend=backend, coupling_map=coupling_map, basis_gates=basis_gates
)
self.assertEqual(circuit2, circuit3)
def test_transpile_basis_gates_no_backend_no_coupling_map(self):
"""Verify transpile() works with no coupling_map or backend."""
qr = QuantumRegister(2, "qr")
circuit = QuantumCircuit(qr)
circuit.h(qr[0])
circuit.h(qr[0])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[0], qr[1])
basis_gates = ["u1", "u2", "u3", "cx", "id"]
circuit2 = transpile(circuit, basis_gates=basis_gates, optimization_level=0)
resources_after = circuit2.count_ops()
self.assertEqual({"u2": 2, "cx": 4}, resources_after)
def test_transpile_non_adjacent_layout(self):
"""Transpile pipeline can handle manual layout on non-adjacent qubits.
circuit:
.. parsed-literal::
┌───┐
qr_0: ┤ H ├──■──────────── -> 1
└───┘┌─┴─┐
qr_1: ─────┤ X ├──■─────── -> 2
└───┘┌─┴─┐
qr_2: ──────────┤ X ├──■── -> 3
└───┘┌─┴─┐
qr_3: ───────────────┤ X ├ -> 5
└───┘
device:
0 - 1 - 2 - 3 - 4 - 5 - 6
| | | | | |
13 - 12 - 11 - 10 - 9 - 8 - 7
"""
qr = QuantumRegister(4, "qr")
circuit = QuantumCircuit(qr)
circuit.h(qr[0])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[1], qr[2])
circuit.cx(qr[2], qr[3])
coupling_map = FakeMelbourne().configuration().coupling_map
basis_gates = FakeMelbourne().configuration().basis_gates
initial_layout = [None, qr[0], qr[1], qr[2], None, qr[3]]
new_circuit = transpile(
circuit,
basis_gates=basis_gates,
coupling_map=coupling_map,
initial_layout=initial_layout,
)
qubit_indices = {bit: idx for idx, bit in enumerate(new_circuit.qubits)}
for instruction in new_circuit.data:
if isinstance(instruction.operation, CXGate):
self.assertIn([qubit_indices[x] for x in instruction.qubits], coupling_map)
def test_transpile_qft_grid(self):
"""Transpile pipeline can handle 8-qubit QFT on 14-qubit grid."""
qr = QuantumRegister(8)
circuit = QuantumCircuit(qr)
for i, _ in enumerate(qr):
for j in range(i):
circuit.cp(math.pi / float(2 ** (i - j)), qr[i], qr[j])
circuit.h(qr[i])
coupling_map = FakeMelbourne().configuration().coupling_map
basis_gates = FakeMelbourne().configuration().basis_gates
new_circuit = transpile(circuit, basis_gates=basis_gates, coupling_map=coupling_map)
qubit_indices = {bit: idx for idx, bit in enumerate(new_circuit.qubits)}
for instruction in new_circuit.data:
if isinstance(instruction.operation, CXGate):
self.assertIn([qubit_indices[x] for x in instruction.qubits], coupling_map)
def test_already_mapped_1(self):
"""Circuit not remapped if matches topology.
See: https://github.com/Qiskit/qiskit-terra/issues/342
"""
backend = FakeRueschlikon()
coupling_map = backend.configuration().coupling_map
basis_gates = backend.configuration().basis_gates
qr = QuantumRegister(16, "qr")
cr = ClassicalRegister(16, "cr")
qc = QuantumCircuit(qr, cr)
qc.cx(qr[3], qr[14])
qc.cx(qr[5], qr[4])
qc.h(qr[9])
qc.cx(qr[9], qr[8])
qc.x(qr[11])
qc.cx(qr[3], qr[4])
qc.cx(qr[12], qr[11])
qc.cx(qr[13], qr[4])
qc.measure(qr, cr)
new_qc = transpile(
qc,
coupling_map=coupling_map,
basis_gates=basis_gates,
initial_layout=Layout.generate_trivial_layout(qr),
)
qubit_indices = {bit: idx for idx, bit in enumerate(new_qc.qubits)}
cx_qubits = [instr.qubits for instr in new_qc.data if instr.operation.name == "cx"]
cx_qubits_physical = [
[qubit_indices[ctrl], qubit_indices[tgt]] for [ctrl, tgt] in cx_qubits
]
self.assertEqual(
sorted(cx_qubits_physical), [[3, 4], [3, 14], [5, 4], [9, 8], [12, 11], [13, 4]]
)
def test_already_mapped_via_layout(self):
"""Test that a manual layout that satisfies a coupling map does not get altered.
See: https://github.com/Qiskit/qiskit-terra/issues/2036
circuit:
.. parsed-literal::
┌───┐ ┌───┐ ░ ┌─┐
qn_0: ┤ H ├──■────────────■──┤ H ├─░─┤M├─── -> 9
└───┘ │ │ └───┘ ░ └╥┘
qn_1: ───────┼────────────┼────────░──╫──── -> 6
│ │ ░ ║
qn_2: ───────┼────────────┼────────░──╫──── -> 5
│ │ ░ ║
qn_3: ───────┼────────────┼────────░──╫──── -> 0
│ │ ░ ║
qn_4: ───────┼────────────┼────────░──╫──── -> 1
┌───┐┌─┴─┐┌──────┐┌─┴─┐┌───┐ ░ ║ ┌─┐
qn_5: ┤ H ├┤ X ├┤ P(2) ├┤ X ├┤ H ├─░──╫─┤M├ -> 4
└───┘└───┘└──────┘└───┘└───┘ ░ ║ └╥┘
cn: 2/════════════════════════════════╩══╩═
0 1
device:
0 -- 1 -- 2 -- 3 -- 4
| |
5 -- 6 -- 7 -- 8 -- 9
| |
10 - 11 - 12 - 13 - 14
| |
15 - 16 - 17 - 18 - 19
"""
basis_gates = ["u1", "u2", "u3", "cx", "id"]
coupling_map = [
[0, 1],
[0, 5],
[1, 0],
[1, 2],
[2, 1],
[2, 3],
[3, 2],
[3, 4],
[4, 3],
[4, 9],
[5, 0],
[5, 6],
[5, 10],
[6, 5],
[6, 7],
[7, 6],
[7, 8],
[7, 12],
[8, 7],
[8, 9],
[9, 4],
[9, 8],
[9, 14],
[10, 5],
[10, 11],
[10, 15],
[11, 10],
[11, 12],
[12, 7],
[12, 11],
[12, 13],
[13, 12],
[13, 14],
[14, 9],
[14, 13],
[14, 19],
[15, 10],
[15, 16],
[16, 15],
[16, 17],
[17, 16],
[17, 18],
[18, 17],
[18, 19],
[19, 14],
[19, 18],
]
q = QuantumRegister(6, name="qn")
c = ClassicalRegister(2, name="cn")
qc = QuantumCircuit(q, c)
qc.h(q[0])
qc.h(q[5])
qc.cx(q[0], q[5])
qc.p(2, q[5])
qc.cx(q[0], q[5])
qc.h(q[0])
qc.h(q[5])
qc.barrier(q)
qc.measure(q[0], c[0])
qc.measure(q[5], c[1])
initial_layout = [
q[3],
q[4],
None,
None,
q[5],
q[2],
q[1],
None,
None,
q[0],
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
]
new_qc = transpile(
qc, coupling_map=coupling_map, basis_gates=basis_gates, initial_layout=initial_layout
)
qubit_indices = {bit: idx for idx, bit in enumerate(new_qc.qubits)}
cx_qubits = [instr.qubits for instr in new_qc.data if instr.operation.name == "cx"]
cx_qubits_physical = [
[qubit_indices[ctrl], qubit_indices[tgt]] for [ctrl, tgt] in cx_qubits
]
self.assertEqual(sorted(cx_qubits_physical), [[9, 4], [9, 4]])
def test_transpile_bell(self):
"""Test Transpile Bell.
If all correct some should exists.
"""
backend = BasicAer.get_backend("qasm_simulator")
qubit_reg = QuantumRegister(2, name="q")
clbit_reg = ClassicalRegister(2, name="c")
qc = QuantumCircuit(qubit_reg, clbit_reg, name="bell")
qc.h(qubit_reg[0])
qc.cx(qubit_reg[0], qubit_reg[1])
qc.measure(qubit_reg, clbit_reg)
circuits = transpile(qc, backend)
self.assertIsInstance(circuits, QuantumCircuit)
def test_transpile_one(self):
"""Test transpile a single circuit.
Check that the top-level `transpile` function returns
a single circuit."""
backend = BasicAer.get_backend("qasm_simulator")
qubit_reg = QuantumRegister(2)
clbit_reg = ClassicalRegister(2)
qc = QuantumCircuit(qubit_reg, clbit_reg, name="bell")
qc.h(qubit_reg[0])
qc.cx(qubit_reg[0], qubit_reg[1])
qc.measure(qubit_reg, clbit_reg)
circuit = transpile(qc, backend)
self.assertIsInstance(circuit, QuantumCircuit)
def test_transpile_two(self):
"""Test transpile two circuits.
Check that the transpiler returns a list of two circuits.
"""
backend = BasicAer.get_backend("qasm_simulator")
qubit_reg = QuantumRegister(2)
clbit_reg = ClassicalRegister(2)
qubit_reg2 = QuantumRegister(2)
clbit_reg2 = ClassicalRegister(2)
qc = QuantumCircuit(qubit_reg, clbit_reg, name="bell")
qc.h(qubit_reg[0])
qc.cx(qubit_reg[0], qubit_reg[1])
qc.measure(qubit_reg, clbit_reg)
qc_extra = QuantumCircuit(qubit_reg, qubit_reg2, clbit_reg, clbit_reg2, name="extra")
qc_extra.measure(qubit_reg, clbit_reg)
circuits = transpile([qc, qc_extra], backend)
self.assertIsInstance(circuits, list)
self.assertEqual(len(circuits), 2)
for circuit in circuits:
self.assertIsInstance(circuit, QuantumCircuit)
def test_transpile_singleton(self):
"""Test transpile a single-element list with a circuit.
Check that `transpile` returns a single-element list.
See https://github.com/Qiskit/qiskit-terra/issues/5260
"""
backend = BasicAer.get_backend("qasm_simulator")
qubit_reg = QuantumRegister(2)
clbit_reg = ClassicalRegister(2)
qc = QuantumCircuit(qubit_reg, clbit_reg, name="bell")
qc.h(qubit_reg[0])
qc.cx(qubit_reg[0], qubit_reg[1])
qc.measure(qubit_reg, clbit_reg)
circuits = transpile([qc], backend)
self.assertIsInstance(circuits, list)
self.assertEqual(len(circuits), 1)
self.assertIsInstance(circuits[0], QuantumCircuit)
def test_mapping_correction(self):
"""Test mapping works in previous failed case."""
backend = FakeRueschlikon()
qr = QuantumRegister(name="qr", size=11)
cr = ClassicalRegister(name="qc", size=11)
circuit = QuantumCircuit(qr, cr)
circuit.u(1.564784764685993, -1.2378965763410095, 2.9746763177861713, qr[3])
circuit.u(1.2269835563676523, 1.1932982847014162, -1.5597357740824318, qr[5])
circuit.cx(qr[5], qr[3])
circuit.p(0.856768317675967, qr[3])
circuit.u(-3.3911273825190915, 0.0, 0.0, qr[5])
circuit.cx(qr[3], qr[5])
circuit.u(2.159209321625547, 0.0, 0.0, qr[5])
circuit.cx(qr[5], qr[3])
circuit.u(0.30949966910232335, 1.1706201763833217, 1.738408691990081, qr[3])
circuit.u(1.9630571407274755, -0.6818742967975088, 1.8336534616728195, qr[5])
circuit.u(1.330181833806101, 0.6003162754946363, -3.181264980452862, qr[7])
circuit.u(0.4885914820775024, 3.133297443244865, -2.794457469189904, qr[8])
circuit.cx(qr[8], qr[7])
circuit.p(2.2196187596178616, qr[7])
circuit.u(-3.152367609631023, 0.0, 0.0, qr[8])
circuit.cx(qr[7], qr[8])
circuit.u(1.2646005789809263, 0.0, 0.0, qr[8])
circuit.cx(qr[8], qr[7])
circuit.u(0.7517780502091939, 1.2828514296564781, 1.6781179605443775, qr[7])
circuit.u(0.9267400575390405, 2.0526277839695153, 2.034202361069533, qr[8])
circuit.u(2.550304293455634, 3.8250017126569698, -2.1351609599720054, qr[1])
circuit.u(0.9566260876600556, -1.1147561503064538, 2.0571590492298797, qr[4])
circuit.cx(qr[4], qr[1])
circuit.p(2.1899329069137394, qr[1])
circuit.u(-1.8371715243173294, 0.0, 0.0, qr[4])
circuit.cx(qr[1], qr[4])
circuit.u(0.4717053496327104, 0.0, 0.0, qr[4])
circuit.cx(qr[4], qr[1])
circuit.u(2.3167620677708145, -1.2337330260253256, -0.5671322899563955, qr[1])
circuit.u(1.0468499525240678, 0.8680750644809365, -1.4083720073192485, qr[4])
circuit.u(2.4204244021892807, -2.211701932616922, 3.8297006565735883, qr[10])
circuit.u(0.36660280497727255, 3.273119149343493, -1.8003362351299388, qr[6])
circuit.cx(qr[6], qr[10])
circuit.p(1.067395863586385, qr[10])
circuit.u(-0.7044917541291232, 0.0, 0.0, qr[6])
circuit.cx(qr[10], qr[6])
circuit.u(2.1830003849921527, 0.0, 0.0, qr[6])
circuit.cx(qr[6], qr[10])
circuit.u(2.1538343756723917, 2.2653381826084606, -3.550087952059485, qr[10])
circuit.u(1.307627685019188, -0.44686656993522567, -2.3238098554327418, qr[6])
circuit.u(2.2046797998462906, 0.9732961754855436, 1.8527865921467421, qr[9])
circuit.u(2.1665254613904126, -1.281337664694577, -1.2424905413631209, qr[0])
circuit.cx(qr[0], qr[9])
circuit.p(2.6209599970201007, qr[9])
circuit.u(0.04680566321901303, 0.0, 0.0, qr[0])
circuit.cx(qr[9], qr[0])
circuit.u(1.7728411151289603, 0.0, 0.0, qr[0])
circuit.cx(qr[0], qr[9])
circuit.u(2.4866395967434443, 0.48684511243566697, -3.0069186877854728, qr[9])
circuit.u(1.7369112924273789, -4.239660866163805, 1.0623389015296005, qr[0])
circuit.barrier(qr)
circuit.measure(qr, cr)
circuits = transpile(circuit, backend)
self.assertIsInstance(circuits, QuantumCircuit)
def test_transpiler_layout_from_intlist(self):
"""A list of ints gives layout to correctly map circuit.
virtual physical
q1_0 - 4 ---[H]---
q2_0 - 5
q2_1 - 6 ---[H]---
q3_0 - 8
q3_1 - 9
q3_2 - 10 ---[H]---
"""
qr1 = QuantumRegister(1, "qr1")
qr2 = QuantumRegister(2, "qr2")
qr3 = QuantumRegister(3, "qr3")
qc = QuantumCircuit(qr1, qr2, qr3)
qc.h(qr1[0])
qc.h(qr2[1])
qc.h(qr3[2])
layout = [4, 5, 6, 8, 9, 10]
cmap = [
[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],
]
new_circ = transpile(
qc, backend=None, coupling_map=cmap, basis_gates=["u2"], initial_layout=layout
)
qubit_indices = {bit: idx for idx, bit in enumerate(new_circ.qubits)}
mapped_qubits = []
for instruction in new_circ.data:
mapped_qubits.append(qubit_indices[instruction.qubits[0]])
self.assertEqual(mapped_qubits, [4, 6, 10])
def test_mapping_multi_qreg(self):
"""Test mapping works for multiple qregs."""
backend = FakeRueschlikon()
qr = QuantumRegister(3, name="qr")
qr2 = QuantumRegister(1, name="qr2")
qr3 = QuantumRegister(4, name="qr3")
cr = ClassicalRegister(3, name="cr")
qc = QuantumCircuit(qr, qr2, qr3, cr)
qc.h(qr[0])
qc.cx(qr[0], qr2[0])
qc.cx(qr[1], qr3[2])
qc.measure(qr, cr)
circuits = transpile(qc, backend)
self.assertIsInstance(circuits, QuantumCircuit)
def test_transpile_circuits_diff_registers(self):
"""Transpile list of circuits with different qreg names."""
backend = FakeRueschlikon()
circuits = []
for _ in range(2):
qr = QuantumRegister(2)
cr = ClassicalRegister(2)
circuit = QuantumCircuit(qr, cr)
circuit.h(qr[0])
circuit.cx(qr[0], qr[1])
circuit.measure(qr, cr)
circuits.append(circuit)
circuits = transpile(circuits, backend)
self.assertIsInstance(circuits[0], QuantumCircuit)
def test_wrong_initial_layout(self):
"""Test transpile with a bad initial layout."""
backend = FakeMelbourne()
qubit_reg = QuantumRegister(2, name="q")
clbit_reg = ClassicalRegister(2, name="c")
qc = QuantumCircuit(qubit_reg, clbit_reg, name="bell")
qc.h(qubit_reg[0])
qc.cx(qubit_reg[0], qubit_reg[1])
qc.measure(qubit_reg, clbit_reg)
bad_initial_layout = [
QuantumRegister(3, "q")[0],
QuantumRegister(3, "q")[1],
QuantumRegister(3, "q")[2],
]
with self.assertRaises(TranspilerError):
transpile(qc, backend, initial_layout=bad_initial_layout)
def test_parameterized_circuit_for_simulator(self):
"""Verify that a parameterized circuit can be transpiled for a simulator backend."""
qr = QuantumRegister(2, name="qr")
qc = QuantumCircuit(qr)
theta = Parameter("theta")
qc.rz(theta, qr[0])
transpiled_qc = transpile(qc, backend=BasicAer.get_backend("qasm_simulator"))
expected_qc = QuantumCircuit(qr)
expected_qc.append(RZGate(theta), [qr[0]])
self.assertEqual(expected_qc, transpiled_qc)
def test_parameterized_circuit_for_device(self):
"""Verify that a parameterized circuit can be transpiled for a device backend."""
qr = QuantumRegister(2, name="qr")
qc = QuantumCircuit(qr)
theta = Parameter("theta")
qc.rz(theta, qr[0])
transpiled_qc = transpile(
qc, backend=FakeMelbourne(), initial_layout=Layout.generate_trivial_layout(qr)
)
qr = QuantumRegister(14, "q")
expected_qc = QuantumCircuit(qr, global_phase=-1 * theta / 2.0)
expected_qc.append(U1Gate(theta), [qr[0]])
self.assertEqual(expected_qc, transpiled_qc)
def test_parameter_expression_circuit_for_simulator(self):
"""Verify that a circuit including expressions of parameters can be
transpiled for a simulator backend."""
qr = QuantumRegister(2, name="qr")
qc = QuantumCircuit(qr)
theta = Parameter("theta")
square = theta * theta
qc.rz(square, qr[0])
transpiled_qc = transpile(qc, backend=BasicAer.get_backend("qasm_simulator"))
expected_qc = QuantumCircuit(qr)
expected_qc.append(RZGate(square), [qr[0]])
self.assertEqual(expected_qc, transpiled_qc)
def test_parameter_expression_circuit_for_device(self):
"""Verify that a circuit including expressions of parameters can be
transpiled for a device backend."""
qr = QuantumRegister(2, name="qr")
qc = QuantumCircuit(qr)
theta = Parameter("theta")
square = theta * theta
qc.rz(square, qr[0])
transpiled_qc = transpile(
qc, backend=FakeMelbourne(), initial_layout=Layout.generate_trivial_layout(qr)
)
qr = QuantumRegister(14, "q")
expected_qc = QuantumCircuit(qr, global_phase=-1 * square / 2.0)
expected_qc.append(U1Gate(square), [qr[0]])
self.assertEqual(expected_qc, transpiled_qc)
def test_final_measurement_barrier_for_devices(self):
"""Verify BarrierBeforeFinalMeasurements pass is called in default pipeline for devices."""
qasm_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "qasm")
circ = QuantumCircuit.from_qasm_file(os.path.join(qasm_dir, "example.qasm"))
layout = Layout.generate_trivial_layout(*circ.qregs)
orig_pass = BarrierBeforeFinalMeasurements()
with patch.object(BarrierBeforeFinalMeasurements, "run", wraps=orig_pass.run) as mock_pass:
transpile(
circ,
coupling_map=FakeRueschlikon().configuration().coupling_map,
initial_layout=layout,
)
self.assertTrue(mock_pass.called)
def test_do_not_run_gatedirection_with_symmetric_cm(self):
"""When the coupling map is symmetric, do not run GateDirection."""
qasm_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "qasm")
circ = QuantumCircuit.from_qasm_file(os.path.join(qasm_dir, "example.qasm"))
layout = Layout.generate_trivial_layout(*circ.qregs)
coupling_map = []
for node1, node2 in FakeRueschlikon().configuration().coupling_map:
coupling_map.append([node1, node2])
coupling_map.append([node2, node1])
orig_pass = GateDirection(CouplingMap(coupling_map))
with patch.object(GateDirection, "run", wraps=orig_pass.run) as mock_pass:
transpile(circ, coupling_map=coupling_map, initial_layout=layout)
self.assertFalse(mock_pass.called)
def test_optimize_to_nothing(self):
"""Optimize gates up to fixed point in the default pipeline
See https://github.com/Qiskit/qiskit-terra/issues/2035
"""
# ┌───┐ ┌───┐┌───┐┌───┐ ┌───┐
# q0_0: ┤ H ├──■──┤ X ├┤ Y ├┤ Z ├──■──┤ H ├──■────■──
# └───┘┌─┴─┐└───┘└───┘└───┘┌─┴─┐└───┘┌─┴─┐┌─┴─┐
# q0_1: ─────┤ X ├───────────────┤ X ├─────┤ X ├┤ X ├
# └───┘ └───┘ └───┘└───┘
qr = QuantumRegister(2)
circ = QuantumCircuit(qr)
circ.h(qr[0])
circ.cx(qr[0], qr[1])
circ.x(qr[0])
circ.y(qr[0])
circ.z(qr[0])
circ.cx(qr[0], qr[1])
circ.h(qr[0])
circ.cx(qr[0], qr[1])
circ.cx(qr[0], qr[1])
after = transpile(circ, coupling_map=[[0, 1], [1, 0]], basis_gates=["u3", "u2", "u1", "cx"])
expected = QuantumCircuit(QuantumRegister(2, "q"), global_phase=-np.pi / 2)
msg = f"after:\n{after}\nexpected:\n{expected}"
self.assertEqual(after, expected, msg=msg)
def test_pass_manager_empty(self):
"""Test passing an empty PassManager() to the transpiler.
It should perform no transformations on the circuit.
"""
qr = QuantumRegister(2)
circuit = QuantumCircuit(qr)
circuit.h(qr[0])
circuit.h(qr[0])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[0], qr[1])
resources_before = circuit.count_ops()
pass_manager = PassManager()
out_circuit = pass_manager.run(circuit)
resources_after = out_circuit.count_ops()
self.assertDictEqual(resources_before, resources_after)
def test_move_measurements(self):
"""Measurements applied AFTER swap mapping."""
backend = FakeRueschlikon()
cmap = backend.configuration().coupling_map
qasm_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "qasm")
circ = QuantumCircuit.from_qasm_file(os.path.join(qasm_dir, "move_measurements.qasm"))
lay = [0, 1, 15, 2, 14, 3, 13, 4, 12, 5, 11, 6]
out = transpile(circ, initial_layout=lay, coupling_map=cmap, routing_method="stochastic")
out_dag = circuit_to_dag(out)
meas_nodes = out_dag.named_nodes("measure")
for meas_node in meas_nodes:
is_last_measure = all(
isinstance(after_measure, DAGOutNode)
for after_measure in out_dag.quantum_successors(meas_node)
)
self.assertTrue(is_last_measure)
@data(0, 1, 2, 3)
def test_init_resets_kept_preset_passmanagers(self, optimization_level):
"""Test initial resets kept at all preset transpilation levels"""
num_qubits = 5
qc = QuantumCircuit(num_qubits)
qc.reset(range(num_qubits))
num_resets = transpile(qc, optimization_level=optimization_level).count_ops()["reset"]
self.assertEqual(num_resets, num_qubits)
@data(0, 1, 2, 3)
def test_initialize_reset_is_not_removed(self, optimization_level):
"""The reset in front of initializer should NOT be removed at beginning"""
qr = QuantumRegister(1, "qr")
qc = QuantumCircuit(qr)
qc.initialize([1.0 / math.sqrt(2), 1.0 / math.sqrt(2)], [qr[0]])
qc.initialize([1.0 / math.sqrt(2), -1.0 / math.sqrt(2)], [qr[0]])
after = transpile(qc, basis_gates=["reset", "u3"], optimization_level=optimization_level)
self.assertEqual(after.count_ops()["reset"], 2, msg=f"{after}\n does not have 2 resets.")
def test_initialize_FakeMelbourne(self):
"""Test that the zero-state resets are remove in a device not supporting them."""
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]])
out = transpile(qc, backend=FakeMelbourne())
out_dag = circuit_to_dag(out)
reset_nodes = out_dag.named_nodes("reset")
self.assertEqual(len(reset_nodes), 3)
def test_non_standard_basis(self):
"""Test a transpilation with a non-standard basis"""
qr1 = QuantumRegister(1, "q1")
qr2 = QuantumRegister(2, "q2")
qr3 = QuantumRegister(3, "q3")
qc = QuantumCircuit(qr1, qr2, qr3)
qc.h(qr1[0])
qc.h(qr2[1])
qc.h(qr3[2])
layout = [4, 5, 6, 8, 9, 10]
cmap = [
[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],
]
circuit = transpile(
qc, backend=None, coupling_map=cmap, basis_gates=["h"], initial_layout=layout
)
dag_circuit = circuit_to_dag(circuit)
resources_after = dag_circuit.count_ops()
self.assertEqual({"h": 3}, resources_after)
def test_hadamard_to_rot_gates(self):
"""Test a transpilation from H to Rx, Ry gates"""
qr = QuantumRegister(1)
qc = QuantumCircuit(qr)
qc.h(0)
expected = QuantumCircuit(qr, global_phase=np.pi / 2)
expected.append(RYGate(theta=np.pi / 2), [0])
expected.append(RXGate(theta=np.pi), [0])
circuit = transpile(qc, basis_gates=["rx", "ry"], optimization_level=0)
self.assertEqual(circuit, expected)
def test_basis_subset(self):
"""Test a transpilation with a basis subset of the standard basis"""
qr = QuantumRegister(1, "q1")
qc = QuantumCircuit(qr)
qc.h(qr[0])
qc.x(qr[0])
qc.t(qr[0])
layout = [4]
cmap = [
[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],
]
circuit = transpile(
qc, backend=None, coupling_map=cmap, basis_gates=["u3"], initial_layout=layout
)
dag_circuit = circuit_to_dag(circuit)
resources_after = dag_circuit.count_ops()
self.assertEqual({"u3": 1}, resources_after)
def test_check_circuit_width(self):
"""Verify transpilation of circuit with virtual qubits greater than
physical qubits raises error"""
cmap = [
[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 = QuantumCircuit(15, 15)
with self.assertRaises(TranspilerError):
transpile(qc, coupling_map=cmap)
@data(0, 1, 2, 3)
def test_ccx_routing_method_none(self, optimization_level):
"""CCX without routing method."""
qc = QuantumCircuit(3)
qc.cx(0, 1)
qc.cx(1, 2)
out = transpile(
qc,
routing_method="none",
basis_gates=["u", "cx"],
initial_layout=[0, 1, 2],
seed_transpiler=0,
coupling_map=[[0, 1], [1, 2]],
optimization_level=optimization_level,
)
self.assertTrue(Operator(qc).equiv(out))
@data(0, 1, 2, 3)
def test_ccx_routing_method_none_failed(self, optimization_level):
"""CCX without routing method cannot be routed."""
qc = QuantumCircuit(3)
qc.ccx(0, 1, 2)
with self.assertRaises(TranspilerError):
transpile(
qc,
routing_method="none",
basis_gates=["u", "cx"],
initial_layout=[0, 1, 2],
seed_transpiler=0,
coupling_map=[[0, 1], [1, 2]],
optimization_level=optimization_level,
)
@data(0, 1, 2, 3)
def test_ms_unrolls_to_cx(self, optimization_level):
"""Verify a Rx,Ry,Rxx circuit transpile to a U3,CX target."""
qc = QuantumCircuit(2)
qc.rx(math.pi / 2, 0)
qc.ry(math.pi / 4, 1)
qc.rxx(math.pi / 4, 0, 1)
out = transpile(qc, basis_gates=["u3", "cx"], optimization_level=optimization_level)
self.assertTrue(Operator(qc).equiv(out))
@data(0, 1, 2, 3)
def test_ms_can_target_ms(self, optimization_level):
"""Verify a Rx,Ry,Rxx circuit can transpile to an Rx,Ry,Rxx target."""
qc = QuantumCircuit(2)
qc.rx(math.pi / 2, 0)
qc.ry(math.pi / 4, 1)
qc.rxx(math.pi / 4, 0, 1)
out = transpile(qc, basis_gates=["rx", "ry", "rxx"], optimization_level=optimization_level)
self.assertTrue(Operator(qc).equiv(out))
@data(0, 1, 2, 3)
def test_cx_can_target_ms(self, optimization_level):
"""Verify a U3,CX circuit can transpiler to a Rx,Ry,Rxx target."""
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
qc.rz(math.pi / 4, [0, 1])
out = transpile(qc, basis_gates=["rx", "ry", "rxx"], optimization_level=optimization_level)
self.assertTrue(Operator(qc).equiv(out))
@data(0, 1, 2, 3)
def test_measure_doesnt_unroll_ms(self, optimization_level):
"""Verify a measure doesn't cause an Rx,Ry,Rxx circuit to unroll to U3,CX."""
qc = QuantumCircuit(2, 2)
qc.rx(math.pi / 2, 0)
qc.ry(math.pi / 4, 1)
qc.rxx(math.pi / 4, 0, 1)
qc.measure([0, 1], [0, 1])
out = transpile(qc, basis_gates=["rx", "ry", "rxx"], optimization_level=optimization_level)
self.assertEqual(qc, out)
@data(
["cx", "u3"],
["cz", "u3"],
["cz", "rx", "rz"],
["rxx", "rx", "ry"],
["iswap", "rx", "rz"],
)
def test_block_collection_runs_for_non_cx_bases(self, basis_gates):
"""Verify block collection is run when a single two qubit gate is in the basis."""
twoq_gate, *_ = basis_gates
qc = QuantumCircuit(2)
qc.cx(0, 1)
qc.cx(1, 0)
qc.cx(0, 1)
qc.cx(0, 1)
out = transpile(qc, basis_gates=basis_gates, optimization_level=3)
self.assertLessEqual(out.count_ops()[twoq_gate], 2)
@unpack
@data(
(["u3", "cx"], {"u3": 1, "cx": 1}),
(["rx", "rz", "iswap"], {"rx": 6, "rz": 12, "iswap": 2}),
(["rx", "ry", "rxx"], {"rx": 6, "ry": 5, "rxx": 1}),
)
def test_block_collection_reduces_1q_gate(self, basis_gates, gate_counts):
"""For synthesis to non-U3 bases, verify we minimize 1q gates."""
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
out = transpile(qc, basis_gates=basis_gates, optimization_level=3)
self.assertTrue(Operator(out).equiv(qc))
self.assertTrue(set(out.count_ops()).issubset(basis_gates))
for basis_gate in basis_gates:
self.assertLessEqual(out.count_ops()[basis_gate], gate_counts[basis_gate])
@combine(
optimization_level=[0, 1, 2, 3],
basis_gates=[
["u3", "cx"],
["rx", "rz", "iswap"],
["rx", "ry", "rxx"],
],
)
def test_translation_method_synthesis(self, optimization_level, basis_gates):
"""Verify translation_method='synthesis' gets to the basis."""
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
out = transpile(
qc,
translation_method="synthesis",
basis_gates=basis_gates,
optimization_level=optimization_level,
)
self.assertTrue(Operator(out).equiv(qc))
self.assertTrue(set(out.count_ops()).issubset(basis_gates))
def test_transpiled_custom_gates_calibration(self):
"""Test if transpiled calibrations is equal to custom gates circuit calibrations."""
custom_180 = Gate("mycustom", 1, [3.14])
custom_90 = Gate("mycustom", 1, [1.57])
circ = QuantumCircuit(2)
circ.append(custom_180, [0])
circ.append(custom_90, [1])
with pulse.build() as q0_x180:
pulse.play(pulse.library.Gaussian(20, 1.0, 3.0), pulse.DriveChannel(0))
with pulse.build() as q1_y90:
pulse.play(pulse.library.Gaussian(20, -1.0, 3.0), pulse.DriveChannel(1))
# Add calibration
circ.add_calibration(custom_180, [0], q0_x180)
circ.add_calibration(custom_90, [1], q1_y90)
backend = FakeBoeblingen()
transpiled_circuit = transpile(
circ,
backend=backend,
layout_method="trivial",
)
self.assertEqual(transpiled_circuit.calibrations, circ.calibrations)
self.assertEqual(list(transpiled_circuit.count_ops().keys()), ["mycustom"])
self.assertEqual(list(transpiled_circuit.count_ops().values()), [2])
def test_transpiled_basis_gates_calibrations(self):
"""Test if the transpiled calibrations is equal to basis gates circuit calibrations."""
circ = QuantumCircuit(2)
circ.h(0)
with pulse.build() as q0_x180:
pulse.play(pulse.library.Gaussian(20, 1.0, 3.0), pulse.DriveChannel(0))
# Add calibration
circ.add_calibration("h", [0], q0_x180)
backend = FakeBoeblingen()
transpiled_circuit = transpile(
circ,
backend=backend,
)
self.assertEqual(transpiled_circuit.calibrations, circ.calibrations)
def test_transpile_calibrated_custom_gate_on_diff_qubit(self):
"""Test if the custom, non calibrated gate raises QiskitError."""
custom_180 = Gate("mycustom", 1, [3.14])
circ = QuantumCircuit(2)
circ.append(custom_180, [0])
with pulse.build() as q0_x180:
pulse.play(pulse.library.Gaussian(20, 1.0, 3.0), pulse.DriveChannel(0))
# Add calibration
circ.add_calibration(custom_180, [1], q0_x180)
backend = FakeBoeblingen()
with self.assertRaises(QiskitError):
transpile(circ, backend=backend, layout_method="trivial")
def test_transpile_calibrated_nonbasis_gate_on_diff_qubit(self):
"""Test if the non-basis gates are transpiled if they are on different qubit that
is not calibrated."""
circ = QuantumCircuit(2)
circ.h(0)
circ.h(1)
with pulse.build() as q0_x180:
pulse.play(pulse.library.Gaussian(20, 1.0, 3.0), pulse.DriveChannel(0))
# Add calibration
circ.add_calibration("h", [1], q0_x180)
backend = FakeBoeblingen()
transpiled_circuit = transpile(
circ,
backend=backend,
)
self.assertEqual(transpiled_circuit.calibrations, circ.calibrations)
self.assertEqual(set(transpiled_circuit.count_ops().keys()), {"u2", "h"})
def test_transpile_subset_of_calibrated_gates(self):
"""Test transpiling a circuit with both basis gate (not-calibrated) and
a calibrated gate on different qubits."""
x_180 = Gate("mycustom", 1, [3.14])
circ = QuantumCircuit(2)
circ.h(0)
circ.append(x_180, [0])
circ.h(1)
with pulse.build() as q0_x180:
pulse.play(pulse.library.Gaussian(20, 1.0, 3.0), pulse.DriveChannel(0))
circ.add_calibration(x_180, [0], q0_x180)
circ.add_calibration("h", [1], q0_x180) # 'h' is calibrated on qubit 1
transpiled_circ = transpile(circ, FakeBoeblingen(), layout_method="trivial")
self.assertEqual(set(transpiled_circ.count_ops().keys()), {"u2", "mycustom", "h"})
def test_parameterized_calibrations_transpile(self):
"""Check that gates can be matched to their calibrations before and after parameter
assignment."""
tau = Parameter("tau")
circ = QuantumCircuit(3, 3)
circ.append(Gate("rxt", 1, [2 * 3.14 * tau]), [0])
def q0_rxt(tau):
with pulse.build() as q0_rxt:
pulse.play(pulse.library.Gaussian(20, 0.4 * tau, 3.0), pulse.DriveChannel(0))
return q0_rxt
circ.add_calibration("rxt", [0], q0_rxt(tau), [2 * 3.14 * tau])
transpiled_circ = transpile(circ, FakeBoeblingen(), layout_method="trivial")
self.assertEqual(set(transpiled_circ.count_ops().keys()), {"rxt"})
circ = circ.assign_parameters({tau: 1})
transpiled_circ = transpile(circ, FakeBoeblingen(), layout_method="trivial")
self.assertEqual(set(transpiled_circ.count_ops().keys()), {"rxt"})
def test_inst_durations_from_calibrations(self):
"""Test that circuit calibrations can be used instead of explicitly
supplying inst_durations.
"""
qc = QuantumCircuit(2)
qc.append(Gate("custom", 1, []), [0])
with pulse.build() as cal:
pulse.play(pulse.library.Gaussian(20, 1.0, 3.0), pulse.DriveChannel(0))
qc.add_calibration("custom", [0], cal)
out = transpile(qc, scheduling_method="alap")
self.assertEqual(out.duration, cal.duration)
@data(0, 1, 2, 3)
def test_multiqubit_gates_calibrations(self, opt_level):
"""Test multiqubit gate > 2q with calibrations works
Adapted from issue description in https://github.com/Qiskit/qiskit-terra/issues/6572
"""
circ = QuantumCircuit(5)
custom_gate = Gate("my_custom_gate", 5, [])
circ.append(custom_gate, [0, 1, 2, 3, 4])
circ.measure_all()
backend = FakeBoeblingen()
with pulse.build(backend, name="custom") as my_schedule:
pulse.play(
pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.drive_channel(0)
)
pulse.play(
pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.drive_channel(1)
)
pulse.play(
pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.drive_channel(2)
)
pulse.play(
pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.drive_channel(3)
)
pulse.play(
pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.drive_channel(4)
)
pulse.play(
pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.ControlChannel(1)
)
pulse.play(
pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.ControlChannel(2)
)
pulse.play(
pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.ControlChannel(3)
)
pulse.play(
pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.ControlChannel(4)
)
circ.add_calibration("my_custom_gate", [0, 1, 2, 3, 4], my_schedule, [])
trans_circ = transpile(circ, backend, optimization_level=opt_level, layout_method="trivial")
self.assertEqual({"measure": 5, "my_custom_gate": 1, "barrier": 1}, trans_circ.count_ops())
@data(0, 1, 2, 3)
def test_circuit_with_delay(self, optimization_level):
"""Verify a circuit with delay can transpile to a scheduled circuit."""
qc = QuantumCircuit(2)
qc.h(0)
qc.delay(500, 1)
qc.cx(0, 1)
out = transpile(
qc,
scheduling_method="alap",
basis_gates=["h", "cx"],
instruction_durations=[("h", 0, 200), ("cx", [0, 1], 700)],
optimization_level=optimization_level,
)
self.assertEqual(out.duration, 1200)
def test_delay_converts_to_dt(self):
"""Test that a delay instruction is converted to units of dt given a backend."""
qc = QuantumCircuit(2)
qc.delay(1000, [0], unit="us")
backend = FakeRueschlikon()
backend.configuration().dt = 0.5e-6
out = transpile([qc, qc], backend)
self.assertEqual(out[0].data[0].operation.unit, "dt")
self.assertEqual(out[1].data[0].operation.unit, "dt")
out = transpile(qc, dt=1e-9)
self.assertEqual(out.data[0].operation.unit, "dt")
def test_scheduling_backend_v2(self):
"""Test that scheduling method works with Backendv2."""
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
qc.measure_all()
backend = FakeMumbaiV2()
out = transpile([qc, qc], backend, scheduling_method="alap")
self.assertIn("delay", out[0].count_ops())
self.assertIn("delay", out[1].count_ops())
@data(1, 2, 3)
def test_no_infinite_loop(self, optimization_level):
"""Verify circuit cost always descends and optimization does not flip flop indefinitely."""
qc = QuantumCircuit(1)
qc.ry(0.2, 0)
out = transpile(
qc, basis_gates=["id", "p", "sx", "cx"], optimization_level=optimization_level
)
# Expect a -pi/2 global phase for the U3 to RZ/SX conversion, and
# a -0.5 * theta phase for RZ to P twice, once at theta, and once at 3 pi
# for the second and third RZ gates in the U3 decomposition.
expected = QuantumCircuit(
1, global_phase=-np.pi / 2 - 0.5 * (-0.2 + np.pi) - 0.5 * 3 * np.pi
)
expected.p(-np.pi, 0)
expected.sx(0)
expected.p(np.pi - 0.2, 0)
expected.sx(0)
error_message = (
f"\nOutput circuit:\n{out!s}\n{Operator(out).data}\n"
f"Expected circuit:\n{expected!s}\n{Operator(expected).data}"
)
self.assertEqual(out, expected, error_message)
@data(0, 1, 2, 3)
def test_transpile_preserves_circuit_metadata(self, optimization_level):
"""Verify that transpile preserves circuit metadata in the output."""
circuit = QuantumCircuit(2, metadata={"experiment_id": "1234", "execution_number": 4})
circuit.h(0)
circuit.cx(0, 1)
cmap = [
[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],
]
res = transpile(
circuit,
basis_gates=["id", "p", "sx", "cx"],
coupling_map=cmap,
optimization_level=optimization_level,
)
self.assertEqual(circuit.metadata, res.metadata)
@data(0, 1, 2, 3)
def test_transpile_optional_registers(self, optimization_level):
"""Verify transpile accepts circuits without registers end-to-end."""
qubits = [Qubit() for _ in range(3)]
clbits = [Clbit() for _ in range(3)]
qc = QuantumCircuit(qubits, clbits)
qc.h(0)
qc.cx(0, 1)
qc.cx(1, 2)
qc.measure(qubits, clbits)
out = transpile(qc, FakeBoeblingen(), optimization_level=optimization_level)
self.assertEqual(len(out.qubits), FakeBoeblingen().configuration().num_qubits)
self.assertEqual(len(out.clbits), len(clbits))
@data(0, 1, 2, 3)
def test_translate_ecr_basis(self, optimization_level):
"""Verify that rewriting in ECR basis is efficient."""
circuit = QuantumCircuit(2)
circuit.append(random_unitary(4, seed=1), [0, 1])
circuit.barrier()
circuit.cx(0, 1)
circuit.barrier()
circuit.swap(0, 1)
circuit.barrier()
circuit.iswap(0, 1)
res = transpile(circuit, basis_gates=["u", "ecr"], optimization_level=optimization_level)
self.assertEqual(res.count_ops()["ecr"], 9)
self.assertTrue(Operator(res).equiv(circuit))
def test_optimize_ecr_basis(self):
"""Test highest optimization level can optimize over ECR."""
circuit = QuantumCircuit(2)
circuit.swap(1, 0)
circuit.iswap(0, 1)
res = transpile(circuit, basis_gates=["u", "ecr"], optimization_level=3)
self.assertEqual(res.count_ops()["ecr"], 1)
self.assertTrue(Operator(res).equiv(circuit))
def test_approximation_degree_invalid(self):
"""Test invalid approximation degree raises."""
circuit = QuantumCircuit(2)
circuit.swap(0, 1)
with self.assertRaises(QiskitError):
transpile(circuit, basis_gates=["u", "cz"], approximation_degree=1.1)
def test_approximation_degree(self):
"""Test more approximation gives lower-cost circuit."""
circuit = QuantumCircuit(2)
circuit.swap(0, 1)
circuit.h(0)
circ_10 = transpile(
circuit,
basis_gates=["u", "cx"],
translation_method="synthesis",
approximation_degree=0.1,
)
circ_90 = transpile(
circuit,
basis_gates=["u", "cx"],
translation_method="synthesis",
approximation_degree=0.9,
)
self.assertLess(circ_10.depth(), circ_90.depth())
@data(0, 1, 2, 3)
def test_synthesis_translation_method_with_single_qubit_gates(self, optimization_level):
"""Test that synthesis basis translation works for solely 1q circuit"""
qc = QuantumCircuit(3)
qc.h(0)
qc.h(1)
qc.h(2)
res = transpile(
qc,
basis_gates=["id", "rz", "x", "sx", "cx"],
translation_method="synthesis",
optimization_level=optimization_level,
)
expected = QuantumCircuit(3, global_phase=3 * np.pi / 4)
expected.rz(np.pi / 2, 0)
expected.rz(np.pi / 2, 1)
expected.rz(np.pi / 2, 2)
expected.sx(0)
expected.sx(1)
expected.sx(2)
expected.rz(np.pi / 2, 0)
expected.rz(np.pi / 2, 1)
expected.rz(np.pi / 2, 2)
self.assertEqual(res, expected)
@data(0, 1, 2, 3)
def test_synthesis_translation_method_with_gates_outside_basis(self, optimization_level):
"""Test that synthesis translation works for circuits with single gates outside bassis"""
qc = QuantumCircuit(2)
qc.swap(0, 1)
res = transpile(
qc,
basis_gates=["id", "rz", "x", "sx", "cx"],
translation_method="synthesis",
optimization_level=optimization_level,
)
if optimization_level != 3:
self.assertTrue(Operator(qc).equiv(res))
self.assertNotIn("swap", res.count_ops())
else:
# Optimization level 3 eliminates the pointless swap
self.assertEqual(res, QuantumCircuit(2))
@data(0, 1, 2, 3)
def test_target_ideal_gates(self, opt_level):
"""Test that transpile() with a custom ideal sim target works."""
theta = Parameter("θ")
phi = Parameter("ϕ")
lam = Parameter("λ")
target = Target(num_qubits=2)
target.add_instruction(UGate(theta, phi, lam), {(0,): None, (1,): None})
target.add_instruction(CXGate(), {(0, 1): None})
target.add_instruction(Measure(), {(0,): None, (1,): None})
qubit_reg = QuantumRegister(2, name="q")
clbit_reg = ClassicalRegister(2, name="c")
qc = QuantumCircuit(qubit_reg, clbit_reg, name="bell")
qc.h(qubit_reg[0])
qc.cx(qubit_reg[0], qubit_reg[1])
result = transpile(qc, target=target, optimization_level=opt_level)
self.assertEqual(Operator.from_circuit(result), Operator.from_circuit(qc))
@data(0, 1, 2, 3)
def test_transpile_with_custom_control_flow_target(self, opt_level):
"""Test transpile() with a target and constrol flow ops."""
target = FakeMumbaiV2().target
target.add_instruction(ForLoopOp, name="for_loop")
target.add_instruction(WhileLoopOp, name="while_loop")
target.add_instruction(IfElseOp, name="if_else")
target.add_instruction(SwitchCaseOp, name="switch_case")
circuit = QuantumCircuit(6, 1)
circuit.h(0)
circuit.measure(0, 0)
circuit.cx(0, 1)
circuit.cz(0, 2)
circuit.append(CustomCX(), [1, 2], [])
with circuit.for_loop((1,)):
circuit.cx(0, 1)
circuit.cz(0, 2)
circuit.append(CustomCX(), [1, 2], [])
with circuit.if_test((circuit.clbits[0], True)) as else_:
circuit.cx(0, 1)
circuit.cz(0, 2)
circuit.append(CustomCX(), [1, 2], [])
with else_:
circuit.cx(3, 4)
circuit.cz(3, 5)
circuit.append(CustomCX(), [4, 5], [])
with circuit.while_loop((circuit.clbits[0], True)):
circuit.cx(3, 4)
circuit.cz(3, 5)
circuit.append(CustomCX(), [4, 5], [])
with circuit.switch(circuit.cregs[0]) as case_:
with case_(0):
circuit.cx(0, 1)
circuit.cz(0, 2)
circuit.append(CustomCX(), [1, 2], [])
with case_(1):
circuit.cx(1, 2)
circuit.cz(1, 3)
circuit.append(CustomCX(), [2, 3], [])
transpiled = transpile(
circuit, optimization_level=opt_level, target=target, seed_transpiler=12434
)
# Tests of the complete validity of a circuit are mostly done at the indiviual pass level;
# here we're just checking that various passes do appear to have run.
self.assertIsInstance(transpiled, QuantumCircuit)
# Assert layout ran.
self.assertIsNot(getattr(transpiled, "_layout", None), None)
def _visit_block(circuit, qubit_mapping=None):
for instruction in circuit:
qargs = tuple(qubit_mapping[x] for x in instruction.qubits)
self.assertTrue(target.instruction_supported(instruction.operation.name, qargs))
if isinstance(instruction.operation, ControlFlowOp):
for block in instruction.operation.blocks:
new_mapping = {
inner: qubit_mapping[outer]
for outer, inner in zip(instruction.qubits, block.qubits)
}
_visit_block(block, new_mapping)
# Assert unrolling ran.
self.assertNotIsInstance(instruction.operation, CustomCX)
# Assert translation ran.
self.assertNotIsInstance(instruction.operation, CZGate)
# Assert routing ran.
_visit_block(
transpiled,
qubit_mapping={qubit: index for index, qubit in enumerate(transpiled.qubits)},
)
@data(1, 2, 3)
def test_transpile_identity_circuit_no_target(self, opt_level):
"""Test circuit equivalent to identity is optimized away for all optimization levels >0.
Reproduce taken from https://github.com/Qiskit/qiskit-terra/issues/9217
"""
qr1 = QuantumRegister(3, "state")
qr2 = QuantumRegister(2, "ancilla")
cr = ClassicalRegister(2, "c")
qc = QuantumCircuit(qr1, qr2, cr)
qc.h(qr1[0])
qc.cx(qr1[0], qr1[1])
qc.cx(qr1[1], qr1[2])
qc.cx(qr1[1], qr1[2])
qc.cx(qr1[0], qr1[1])
qc.h(qr1[0])
empty_qc = QuantumCircuit(qr1, qr2, cr)
result = transpile(qc, optimization_level=opt_level)
self.assertEqual(empty_qc, result)
@data(0, 1, 2, 3)
def test_initial_layout_with_loose_qubits(self, opt_level):
"""Regression test of gh-10125."""
qc = QuantumCircuit([Qubit(), Qubit()])
qc.cx(0, 1)
transpiled = transpile(qc, initial_layout=[1, 0], optimization_level=opt_level)
self.assertIsNotNone(transpiled.layout)
self.assertEqual(
transpiled.layout.initial_layout, Layout({0: qc.qubits[1], 1: qc.qubits[0]})
)
@data(0, 1, 2, 3)
def test_initial_layout_with_overlapping_qubits(self, opt_level):
"""Regression test of gh-10125."""
qr1 = QuantumRegister(2, "qr1")
qr2 = QuantumRegister(bits=qr1[:])
qc = QuantumCircuit(qr1, qr2)
qc.cx(0, 1)
transpiled = transpile(qc, initial_layout=[1, 0], optimization_level=opt_level)
self.assertIsNotNone(transpiled.layout)
self.assertEqual(
transpiled.layout.initial_layout, Layout({0: qc.qubits[1], 1: qc.qubits[0]})
)
@combine(opt_level=[0, 1, 2, 3], basis=[["rz", "x"], ["rx", "z"], ["rz", "y"], ["ry", "x"]])
def test_paulis_to_constrained_1q_basis(self, opt_level, basis):
"""Test that Pauli-gate circuits can be transpiled to constrained 1q bases that do not
contain any root-Pauli gates."""
qc = QuantumCircuit(1)
qc.x(0)
qc.barrier()
qc.y(0)
qc.barrier()
qc.z(0)
transpiled = transpile(qc, basis_gates=basis, optimization_level=opt_level)
self.assertGreaterEqual(set(basis) | {"barrier"}, transpiled.count_ops().keys())
self.assertEqual(Operator(qc), Operator(transpiled))
@ddt
class TestPostTranspileIntegration(QiskitTestCase):
"""Test that the output of `transpile` is usable in various other integration contexts."""
def _regular_circuit(self):
a = Parameter("a")
regs = [
QuantumRegister(2, name="q0"),
QuantumRegister(3, name="q1"),
ClassicalRegister(2, name="c0"),
]
bits = [Qubit(), Qubit(), Clbit()]
base = QuantumCircuit(*regs, bits)
base.h(0)
base.measure(0, 0)
base.cx(0, 1)
base.cz(0, 2)
base.cz(0, 3)
base.cz(1, 4)
base.cx(1, 5)
base.measure(1, 1)
base.append(CustomCX(), [3, 6])
base.append(CustomCX(), [5, 4])
base.append(CustomCX(), [5, 3])
base.append(CustomCX(), [2, 4]).c_if(base.cregs[0], 3)
base.ry(a, 4)
base.measure(4, 2)
return base
def _control_flow_circuit(self):
a = Parameter("a")
regs = [
QuantumRegister(2, name="q0"),
QuantumRegister(3, name="q1"),
ClassicalRegister(2, name="c0"),
]
bits = [Qubit(), Qubit(), Clbit()]
base = QuantumCircuit(*regs, bits)
base.h(0)
base.measure(0, 0)
with base.if_test((base.cregs[0], 1)) as else_:
base.cx(0, 1)
base.cz(0, 2)
base.cz(0, 3)
with else_:
base.cz(1, 4)
with base.for_loop((1, 2)):
base.cx(1, 5)
base.measure(2, 2)
with base.while_loop((2, False)):
base.append(CustomCX(), [3, 6])
base.append(CustomCX(), [5, 4])
base.append(CustomCX(), [5, 3])
base.append(CustomCX(), [2, 4])
base.ry(a, 4)
base.measure(4, 2)
with base.switch(base.cregs[0]) as case_:
with case_(0, 1):
base.cz(3, 5)
with case_(case_.DEFAULT):
base.cz(1, 4)
base.append(CustomCX(), [2, 4])
base.append(CustomCX(), [3, 4])
return base
def _control_flow_expr_circuit(self):
a = Parameter("a")
regs = [
QuantumRegister(2, name="q0"),
QuantumRegister(3, name="q1"),
ClassicalRegister(2, name="c0"),
]
bits = [Qubit(), Qubit(), Clbit()]
base = QuantumCircuit(*regs, bits)
base.h(0)
base.measure(0, 0)
with base.if_test(expr.equal(base.cregs[0], 1)) as else_:
base.cx(0, 1)
base.cz(0, 2)
base.cz(0, 3)
with else_:
base.cz(1, 4)
with base.for_loop((1, 2)):
base.cx(1, 5)
base.measure(2, 2)
with base.while_loop(expr.logic_not(bits[2])):
base.append(CustomCX(), [3, 6])
base.append(CustomCX(), [5, 4])
base.append(CustomCX(), [5, 3])
base.append(CustomCX(), [2, 4])
base.ry(a, 4)
base.measure(4, 2)
with base.switch(expr.bit_and(base.cregs[0], 2)) as case_:
with case_(0, 1):
base.cz(3, 5)
with case_(case_.DEFAULT):
base.cz(1, 4)
base.append(CustomCX(), [2, 4])
base.append(CustomCX(), [3, 4])
return base
@data(0, 1, 2, 3)
def test_qpy_roundtrip(self, optimization_level):
"""Test that the output of a transpiled circuit can be round-tripped through QPY."""
transpiled = transpile(
self._regular_circuit(),
backend=FakeMelbourne(),
optimization_level=optimization_level,
seed_transpiler=2022_10_17,
)
# Round-tripping the layout is out-of-scope for QPY while it's a private attribute.
transpiled._layout = None
buffer = io.BytesIO()
qpy.dump(transpiled, buffer)
buffer.seek(0)
round_tripped = qpy.load(buffer)[0]
self.assertEqual(round_tripped, transpiled)
@data(0, 1, 2, 3)
def test_qpy_roundtrip_backendv2(self, optimization_level):
"""Test that the output of a transpiled circuit can be round-tripped through QPY."""
transpiled = transpile(
self._regular_circuit(),
backend=FakeMumbaiV2(),
optimization_level=optimization_level,
seed_transpiler=2022_10_17,
)
# Round-tripping the layout is out-of-scope for QPY while it's a private attribute.
transpiled._layout = None
buffer = io.BytesIO()
qpy.dump(transpiled, buffer)
buffer.seek(0)
round_tripped = qpy.load(buffer)[0]
self.assertEqual(round_tripped, transpiled)
@data(0, 1, 2, 3)
def test_qpy_roundtrip_control_flow(self, optimization_level):
"""Test that the output of a transpiled circuit with control flow can be round-tripped
through QPY."""
if optimization_level == 3 and sys.platform == "win32":
self.skipTest(
"This test case triggers a bug in the eigensolver routine on windows. "
"See #10345 for more details."
)
backend = FakeMelbourne()
transpiled = transpile(
self._control_flow_circuit(),
backend=backend,
basis_gates=backend.configuration().basis_gates
+ ["if_else", "for_loop", "while_loop", "switch_case"],
optimization_level=optimization_level,
seed_transpiler=2022_10_17,
)
# Round-tripping the layout is out-of-scope for QPY while it's a private attribute.
transpiled._layout = None
buffer = io.BytesIO()
qpy.dump(transpiled, buffer)
buffer.seek(0)
round_tripped = qpy.load(buffer)[0]
self.assertEqual(round_tripped, transpiled)
@data(0, 1, 2, 3)
def test_qpy_roundtrip_control_flow_backendv2(self, optimization_level):
"""Test that the output of a transpiled circuit with control flow can be round-tripped
through QPY."""
backend = FakeMumbaiV2()
backend.target.add_instruction(IfElseOp, name="if_else")
backend.target.add_instruction(ForLoopOp, name="for_loop")
backend.target.add_instruction(WhileLoopOp, name="while_loop")
backend.target.add_instruction(SwitchCaseOp, name="switch_case")
transpiled = transpile(
self._control_flow_circuit(),
backend=backend,
optimization_level=optimization_level,
seed_transpiler=2022_10_17,
)
# Round-tripping the layout is out-of-scope for QPY while it's a private attribute.
transpiled._layout = None
buffer = io.BytesIO()
qpy.dump(transpiled, buffer)
buffer.seek(0)
round_tripped = qpy.load(buffer)[0]
self.assertEqual(round_tripped, transpiled)
@data(0, 1, 2, 3)
def test_qpy_roundtrip_control_flow_expr(self, optimization_level):
"""Test that the output of a transpiled circuit with control flow including `Expr` nodes can
be round-tripped through QPY."""
if optimization_level == 3 and sys.platform == "win32":
self.skipTest(
"This test case triggers a bug in the eigensolver routine on windows. "
"See #10345 for more details."
)
backend = FakeMelbourne()
transpiled = transpile(
self._control_flow_expr_circuit(),
backend=backend,
basis_gates=backend.configuration().basis_gates
+ ["if_else", "for_loop", "while_loop", "switch_case"],
optimization_level=optimization_level,
seed_transpiler=2023_07_26,
)
buffer = io.BytesIO()
qpy.dump(transpiled, buffer)
buffer.seek(0)
round_tripped = qpy.load(buffer)[0]
self.assertEqual(round_tripped, transpiled)
@data(0, 1, 2, 3)
def test_qpy_roundtrip_control_flow_expr_backendv2(self, optimization_level):
"""Test that the output of a transpiled circuit with control flow including `Expr` nodes can
be round-tripped through QPY."""
backend = FakeMumbaiV2()
backend.target.add_instruction(IfElseOp, name="if_else")
backend.target.add_instruction(ForLoopOp, name="for_loop")
backend.target.add_instruction(WhileLoopOp, name="while_loop")
backend.target.add_instruction(SwitchCaseOp, name="switch_case")
transpiled = transpile(
self._control_flow_circuit(),
backend=backend,
optimization_level=optimization_level,
seed_transpiler=2023_07_26,
)
buffer = io.BytesIO()
qpy.dump(transpiled, buffer)
buffer.seek(0)
round_tripped = qpy.load(buffer)[0]
self.assertEqual(round_tripped, transpiled)
@data(0, 1, 2, 3)
def test_qasm3_output(self, optimization_level):
"""Test that the output of a transpiled circuit can be dumped into OpenQASM 3."""
transpiled = transpile(
self._regular_circuit(),
backend=FakeMelbourne(),
optimization_level=optimization_level,
seed_transpiler=2022_10_17,
)
# TODO: There's not a huge amount we can sensibly test for the output here until we can
# round-trip the OpenQASM 3 back into a Terra circuit. Mostly we're concerned that the dump
# itself doesn't throw an error, though.
self.assertIsInstance(qasm3.dumps(transpiled).strip(), str)
@data(0, 1, 2, 3)
def test_qasm3_output_control_flow(self, optimization_level):
"""Test that the output of a transpiled circuit with control flow can be dumped into
OpenQASM 3."""
backend = FakeMumbaiV2()
backend.target.add_instruction(IfElseOp, name="if_else")
backend.target.add_instruction(ForLoopOp, name="for_loop")
backend.target.add_instruction(WhileLoopOp, name="while_loop")
backend.target.add_instruction(SwitchCaseOp, name="switch_case")
transpiled = transpile(
self._control_flow_circuit(),
backend=backend,
optimization_level=optimization_level,
seed_transpiler=2022_10_17,
)
# TODO: There's not a huge amount we can sensibly test for the output here until we can
# round-trip the OpenQASM 3 back into a Terra circuit. Mostly we're concerned that the dump
# itself doesn't throw an error, though.
self.assertIsInstance(
qasm3.dumps(transpiled, experimental=qasm3.ExperimentalFeatures.SWITCH_CASE_V1).strip(),
str,
)
@data(0, 1, 2, 3)
def test_qasm3_output_control_flow_expr(self, optimization_level):
"""Test that the output of a transpiled circuit with control flow and `Expr` nodes can be
dumped into OpenQASM 3."""
backend = FakeMumbaiV2()
backend.target.add_instruction(IfElseOp, name="if_else")
backend.target.add_instruction(ForLoopOp, name="for_loop")
backend.target.add_instruction(WhileLoopOp, name="while_loop")
backend.target.add_instruction(SwitchCaseOp, name="switch_case")
transpiled = transpile(
self._control_flow_circuit(),
backend=backend,
optimization_level=optimization_level,
seed_transpiler=2023_07_26,
)
# TODO: There's not a huge amount we can sensibly test for the output here until we can
# round-trip the OpenQASM 3 back into a Terra circuit. Mostly we're concerned that the dump
# itself doesn't throw an error, though.
self.assertIsInstance(
qasm3.dumps(transpiled, experimental=qasm3.ExperimentalFeatures.SWITCH_CASE_V1).strip(),
str,
)
@data(0, 1, 2, 3)
def test_transpile_target_no_measurement_error(self, opt_level):
"""Test that transpile with a target which contains ideal measurement works
Reproduce from https://github.com/Qiskit/qiskit-terra/issues/8969
"""
target = Target()
target.add_instruction(Measure(), {(0,): None})
qc = QuantumCircuit(1, 1)
qc.measure(0, 0)
res = transpile(qc, target=target, optimization_level=opt_level)
self.assertEqual(qc, res)
def test_transpile_final_layout_updated_with_post_layout(self):
"""Test that the final layout is correctly set when vf2postlayout runs.
Reproduce from #10457
"""
def _get_index_layout(transpiled_circuit: QuantumCircuit, num_source_qubits: int):
"""Return the index layout of a transpiled circuit"""
layout = transpiled_circuit.layout
if layout is None:
return list(range(num_source_qubits))
pos_to_virt = {v: k for k, v in layout.input_qubit_mapping.items()}
qubit_indices = []
for index in range(num_source_qubits):
qubit_idx = layout.initial_layout[pos_to_virt[index]]
if layout.final_layout is not None:
qubit_idx = layout.final_layout[transpiled_circuit.qubits[qubit_idx]]
qubit_indices.append(qubit_idx)
return qubit_indices
vf2_post_layout_called = False
def callback(**kwargs):
nonlocal vf2_post_layout_called
if isinstance(kwargs["pass_"], VF2PostLayout):
vf2_post_layout_called = True
self.assertIsNotNone(kwargs["property_set"]["post_layout"])
backend = FakeVigo()
qubits = 3
qc = QuantumCircuit(qubits)
for i in range(5):
qc.cx(i % qubits, int(i + qubits / 2) % qubits)
tqc = transpile(qc, backend=backend, seed_transpiler=4242, callback=callback)
self.assertTrue(vf2_post_layout_called)
self.assertEqual([3, 2, 1], _get_index_layout(tqc, qubits))
class StreamHandlerRaiseException(StreamHandler):
"""Handler class that will raise an exception on formatting errors."""
def handleError(self, record):
raise sys.exc_info()
class TestLogTranspile(QiskitTestCase):
"""Testing the log_transpile 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 assertTranspileLog(self, log_msg):
"""Runs the transpiler and check for logs containing specified message"""
transpile(self.circuit)
self.output.seek(0)
# Filter unrelated log lines
output_lines = self.output.readlines()
transpile_log_lines = [x for x in output_lines if log_msg in x]
self.assertTrue(len(transpile_log_lines) > 0)
def test_transpile_log_time(self):
"""Check Total Transpile Time is logged"""
self.assertTranspileLog("Total Transpile Time")
class TestTranspileCustomPM(QiskitTestCase):
"""Test transpile function with custom pass manager"""
def test_custom_multiple_circuits(self):
"""Test transpiling with custom pass manager and multiple circuits.
This tests created a deadlock, so it needs to be monitored for timeout.
See: https://github.com/Qiskit/qiskit-terra/issues/3925
"""
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
pm_conf = PassManagerConfig(
initial_layout=None,
basis_gates=["u1", "u2", "u3", "cx"],
coupling_map=CouplingMap([[0, 1]]),
backend_properties=None,
seed_transpiler=1,
)
passmanager = level_0_pass_manager(pm_conf)
transpiled = passmanager.run([qc, qc])
expected = QuantumCircuit(QuantumRegister(2, "q"))
expected.append(U2Gate(0, 3.141592653589793), [0])
expected.cx(0, 1)
self.assertEqual(len(transpiled), 2)
self.assertEqual(transpiled[0], expected)
self.assertEqual(transpiled[1], expected)
@ddt
class TestTranspileParallel(QiskitTestCase):
"""Test transpile() in parallel."""
def setUp(self):
super().setUp()
# Force parallel execution to True to test multiprocessing for this class
original_val = parallel.PARALLEL_DEFAULT
def restore_default():
parallel.PARALLEL_DEFAULT = original_val
self.addCleanup(restore_default)
parallel.PARALLEL_DEFAULT = True
@data(0, 1, 2, 3)
def test_parallel_multiprocessing(self, opt_level):
"""Test parallel dispatch works with multiprocessing."""
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
qc.measure_all()
backend = FakeMumbaiV2()
pm = generate_preset_pass_manager(opt_level, backend)
res = pm.run([qc, qc])
for circ in res:
self.assertIsInstance(circ, QuantumCircuit)
@data(0, 1, 2, 3)
def test_parallel_with_target(self, opt_level):
"""Test that parallel dispatch works with a manual target."""
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
qc.measure_all()
target = FakeMumbaiV2().target
res = transpile([qc] * 3, target=target, optimization_level=opt_level)
self.assertIsInstance(res, list)
for circ in res:
self.assertIsInstance(circ, QuantumCircuit)
@data(0, 1, 2, 3)
def test_parallel_dispatch(self, opt_level):
"""Test that transpile in parallel works for all optimization levels."""
backend = FakeRueschlikon()
qr = QuantumRegister(16)
cr = ClassicalRegister(16)
qc = QuantumCircuit(qr, cr)
qc.h(qr[0])
for k in range(1, 15):
qc.cx(qr[0], qr[k])
qc.measure(qr, cr)
qlist = [qc for k in range(15)]
tqc = transpile(
qlist, backend=backend, optimization_level=opt_level, seed_transpiler=424242
)
result = backend.run(tqc, seed_simulator=4242424242, shots=1000).result()
counts = result.get_counts()
for count in counts:
self.assertTrue(math.isclose(count["0000000000000000"], 500, rel_tol=0.1))
self.assertTrue(math.isclose(count["0111111111111111"], 500, rel_tol=0.1))
def test_parallel_dispatch_lazy_cal_loading(self):
"""Test adding calibration by lazy loading in parallel environment."""
class TestAddCalibration(TransformationPass):
"""A fake pass to test lazy pulse qobj loading in parallel environment."""
def __init__(self, target):
"""Instantiate with target."""
super().__init__()
self.target = target
def run(self, dag):
"""Run test pass that adds calibration of SX gate of qubit 0."""
dag.add_calibration(
"sx",
qubits=(0,),
schedule=self.target["sx"][(0,)].calibration, # PulseQobj is parsed here
)
return dag
backend = FakeMumbaiV2()
# This target has PulseQobj entries that provides a serialized schedule data
pass_ = TestAddCalibration(backend.target)
pm = PassManager(passes=[pass_])
self.assertIsNone(backend.target["sx"][(0,)]._calibration._definition)
qc = QuantumCircuit(1)
qc.sx(0)
qc_copied = [qc for _ in range(10)]
qcs_cal_added = pm.run(qc_copied)
ref_cal = backend.target["sx"][(0,)].calibration
for qc_test in qcs_cal_added:
added_cal = qc_test.calibrations["sx"][((0,), ())]
self.assertEqual(added_cal, ref_cal)
@data(0, 1, 2, 3)
def test_backendv2_and_basis_gates(self, opt_level):
"""Test transpile() with BackendV2 and basis_gates set."""
backend = FakeNairobiV2()
qc = QuantumCircuit(5)
qc.h(0)
qc.cz(0, 1)
qc.cz(0, 2)
qc.cz(0, 3)
qc.cz(0, 4)
qc.measure_all()
tqc = transpile(
qc,
backend=backend,
basis_gates=["u", "cz"],
optimization_level=opt_level,
seed_transpiler=12345678942,
)
op_count = set(tqc.count_ops())
self.assertEqual({"u", "cz", "measure", "barrier"}, op_count)
for inst in tqc.data:
if inst.operation.name not in {"u", "cz"}:
continue
qubits = tuple(tqc.find_bit(x).index for x in inst.qubits)
self.assertIn(qubits, backend.target.qargs)
@data(0, 1, 2, 3)
def test_backendv2_and_coupling_map(self, opt_level):
"""Test transpile() with custom coupling map."""
backend = FakeNairobiV2()
qc = QuantumCircuit(5)
qc.h(0)
qc.cz(0, 1)
qc.cz(0, 2)
qc.cz(0, 3)
qc.cz(0, 4)
qc.measure_all()
cmap = CouplingMap.from_line(5, bidirectional=False)
tqc = transpile(
qc,
backend=backend,
coupling_map=cmap,
optimization_level=opt_level,
seed_transpiler=12345678942,
)
op_count = set(tqc.count_ops())
self.assertTrue({"rz", "sx", "x", "cx", "measure", "barrier"}.issuperset(op_count))
for inst in tqc.data:
if len(inst.qubits) == 2:
qubit_0 = tqc.find_bit(inst.qubits[0]).index
qubit_1 = tqc.find_bit(inst.qubits[1]).index
self.assertEqual(qubit_1, qubit_0 + 1)
def test_transpile_with_multiple_coupling_maps(self):
"""Test passing a different coupling map for every circuit"""
backend = FakeNairobiV2()
qc = QuantumCircuit(3)
qc.cx(0, 2)
# Add a connection between 0 and 2 so that transpile does not change
# the gates
cmap = CouplingMap.from_line(7)
cmap.add_edge(0, 2)
with self.assertRaisesRegex(TranspilerError, "Only a single input coupling"):
# Initial layout needed to prevent transpiler from relabeling
# qubits to avoid doing the swap
transpile(
[qc] * 2,
backend,
coupling_map=[backend.coupling_map, cmap],
initial_layout=(0, 1, 2),
)
@data(0, 1, 2, 3)
def test_backend_and_custom_gate(self, opt_level):
"""Test transpile() with BackendV2, custom basis pulse gate."""
backend = FakeNairobiV2()
inst_map = InstructionScheduleMap()
inst_map.add("newgate", [0, 1], pulse.ScheduleBlock())
newgate = Gate("newgate", 2, [])
circ = QuantumCircuit(2)
circ.append(newgate, [0, 1])
tqc = transpile(
circ, backend, inst_map=inst_map, basis_gates=["newgate"], optimization_level=opt_level
)
self.assertEqual(len(tqc.data), 1)
self.assertEqual(tqc.data[0].operation, newgate)
qubits = tuple(tqc.find_bit(x).index for x in tqc.data[0].qubits)
self.assertIn(qubits, backend.target.qargs)
@ddt
class TestTranspileMultiChipTarget(QiskitTestCase):
"""Test transpile() with a disjoint coupling map."""
def setUp(self):
super().setUp()
class FakeMultiChip(BackendV2):
"""Fake multi chip backend."""
def __init__(self):
super().__init__()
graph = rx.generators.directed_heavy_hex_graph(3)
num_qubits = len(graph) * 3
rng = np.random.default_rng(seed=12345678942)
rz_props = {}
x_props = {}
sx_props = {}
measure_props = {}
delay_props = {}
self._target = Target("Fake multi-chip backend", num_qubits=num_qubits)
for i in range(num_qubits):
qarg = (i,)
rz_props[qarg] = InstructionProperties(error=0.0, duration=0.0)
x_props[qarg] = InstructionProperties(
error=rng.uniform(1e-6, 1e-4), duration=rng.uniform(1e-8, 9e-7)
)
sx_props[qarg] = InstructionProperties(
error=rng.uniform(1e-6, 1e-4), duration=rng.uniform(1e-8, 9e-7)
)
measure_props[qarg] = InstructionProperties(
error=rng.uniform(1e-3, 1e-1), duration=rng.uniform(1e-8, 9e-7)
)
delay_props[qarg] = None
self._target.add_instruction(XGate(), x_props)
self._target.add_instruction(SXGate(), sx_props)
self._target.add_instruction(RZGate(Parameter("theta")), rz_props)
self._target.add_instruction(Measure(), measure_props)
self._target.add_instruction(Delay(Parameter("t")), delay_props)
cz_props = {}
for i in range(3):
for root_edge in graph.edge_list():
offset = i * len(graph)
edge = (root_edge[0] + offset, root_edge[1] + offset)
cz_props[edge] = InstructionProperties(
error=rng.uniform(1e-5, 5e-3), duration=rng.uniform(1e-8, 9e-7)
)
self._target.add_instruction(CZGate(), cz_props)
@property
def target(self):
return self._target
@property
def max_circuits(self):
return None
@classmethod
def _default_options(cls):
return Options(shots=1024)
def run(self, circuit, **kwargs):
raise NotImplementedError
self.backend = FakeMultiChip()
@data(0, 1, 2, 3)
def test_basic_connected_circuit(self, opt_level):
"""Test basic connected circuit on disjoint backend"""
qc = QuantumCircuit(5)
qc.h(0)
qc.cx(0, 1)
qc.cx(0, 2)
qc.cx(0, 3)
qc.cx(0, 4)
qc.measure_all()
tqc = transpile(qc, self.backend, optimization_level=opt_level)
for inst in tqc.data:
qubits = tuple(tqc.find_bit(x).index for x in inst.qubits)
op_name = inst.operation.name
if op_name == "barrier":
continue
self.assertIn(qubits, self.backend.target[op_name])
@data(0, 1, 2, 3)
def test_triple_circuit(self, opt_level):
"""Test a split circuit with one circuit component per chip."""
qc = QuantumCircuit(30)
qc.h(0)
qc.h(10)
qc.h(20)
qc.cx(0, 1)
qc.cx(0, 2)
qc.cx(0, 3)
qc.cx(0, 4)
qc.cx(0, 5)
qc.cx(0, 6)
qc.cx(0, 7)
qc.cx(0, 8)
qc.cx(0, 9)
qc.ecr(10, 11)
qc.ecr(10, 12)
qc.ecr(10, 13)
qc.ecr(10, 14)
qc.ecr(10, 15)
qc.ecr(10, 16)
qc.ecr(10, 17)
qc.ecr(10, 18)
qc.ecr(10, 19)
qc.cy(20, 21)
qc.cy(20, 22)
qc.cy(20, 23)
qc.cy(20, 24)
qc.cy(20, 25)
qc.cy(20, 26)
qc.cy(20, 27)
qc.cy(20, 28)
qc.cy(20, 29)
qc.measure_all()
if opt_level == 0:
with self.assertRaises(TranspilerError):
tqc = transpile(qc, self.backend, optimization_level=opt_level, seed_transpiler=42)
return
tqc = transpile(qc, self.backend, optimization_level=opt_level, seed_transpiler=42)
for inst in tqc.data:
qubits = tuple(tqc.find_bit(x).index for x in inst.qubits)
op_name = inst.operation.name
if op_name == "barrier":
continue
self.assertIn(qubits, self.backend.target[op_name])
def test_disjoint_control_flow(self):
"""Test control flow circuit on disjoint coupling map."""
qc = QuantumCircuit(6, 1)
qc.h(0)
qc.ecr(0, 1)
qc.cx(0, 2)
qc.measure(0, 0)
with qc.if_test((qc.clbits[0], True)):
qc.reset(0)
qc.cz(1, 0)
qc.h(3)
qc.cz(3, 4)
qc.cz(3, 5)
target = self.backend.target
target.add_instruction(Reset(), {(i,): None for i in range(target.num_qubits)})
target.add_instruction(IfElseOp, name="if_else")
tqc = transpile(qc, target=target)
edges = set(target.build_coupling_map().graph.edge_list())
def _visit_block(circuit, qubit_mapping=None):
for instruction in circuit:
if instruction.operation.name == "barrier":
continue
qargs = tuple(qubit_mapping[x] for x in instruction.qubits)
self.assertTrue(target.instruction_supported(instruction.operation.name, qargs))
if isinstance(instruction.operation, ControlFlowOp):
for block in instruction.operation.blocks:
new_mapping = {
inner: qubit_mapping[outer]
for outer, inner in zip(instruction.qubits, block.qubits)
}
_visit_block(block, new_mapping)
elif len(qargs) == 2:
self.assertIn(qargs, edges)
self.assertIn(instruction.operation.name, target)
_visit_block(
tqc,
qubit_mapping={qubit: index for index, qubit in enumerate(tqc.qubits)},
)
def test_disjoint_control_flow_shared_classical(self):
"""Test circuit with classical data dependency between connected components."""
creg = ClassicalRegister(19)
qc = QuantumCircuit(25)
qc.add_register(creg)
qc.h(0)
for i in range(18):
qc.cx(0, i + 1)
for i in range(18):
qc.measure(i, creg[i])
with qc.if_test((creg, 0)):
qc.h(20)
qc.ecr(20, 21)
qc.ecr(20, 22)
qc.ecr(20, 23)
qc.ecr(20, 24)
target = self.backend.target
target.add_instruction(Reset(), {(i,): None for i in range(target.num_qubits)})
target.add_instruction(IfElseOp, name="if_else")
tqc = transpile(qc, target=target)
def _visit_block(circuit, qubit_mapping=None):
for instruction in circuit:
if instruction.operation.name == "barrier":
continue
qargs = tuple(qubit_mapping[x] for x in instruction.qubits)
self.assertTrue(target.instruction_supported(instruction.operation.name, qargs))
if isinstance(instruction.operation, ControlFlowOp):
for block in instruction.operation.blocks:
new_mapping = {
inner: qubit_mapping[outer]
for outer, inner in zip(instruction.qubits, block.qubits)
}
_visit_block(block, new_mapping)
_visit_block(
tqc,
qubit_mapping={qubit: index for index, qubit in enumerate(tqc.qubits)},
)
@slow_test
@data(2, 3)
def test_six_component_circuit(self, opt_level):
"""Test input circuit with more than 1 component per backend component."""
qc = QuantumCircuit(42)
qc.h(0)
qc.h(10)
qc.h(20)
qc.cx(0, 1)
qc.cx(0, 2)
qc.cx(0, 3)
qc.cx(0, 4)
qc.cx(0, 5)
qc.cx(0, 6)
qc.cx(0, 7)
qc.cx(0, 8)
qc.cx(0, 9)
qc.ecr(10, 11)
qc.ecr(10, 12)
qc.ecr(10, 13)
qc.ecr(10, 14)
qc.ecr(10, 15)
qc.ecr(10, 16)
qc.ecr(10, 17)
qc.ecr(10, 18)
qc.ecr(10, 19)
qc.cy(20, 21)
qc.cy(20, 22)
qc.cy(20, 23)
qc.cy(20, 24)
qc.cy(20, 25)
qc.cy(20, 26)
qc.cy(20, 27)
qc.cy(20, 28)
qc.cy(20, 29)
qc.h(30)
qc.cx(30, 31)
qc.cx(30, 32)
qc.cx(30, 33)
qc.h(34)
qc.cx(34, 35)
qc.cx(34, 36)
qc.cx(34, 37)
qc.h(38)
qc.cx(38, 39)
qc.cx(39, 40)
qc.cx(39, 41)
qc.measure_all()
tqc = transpile(qc, self.backend, optimization_level=opt_level, seed_transpiler=42)
for inst in tqc.data:
qubits = tuple(tqc.find_bit(x).index for x in inst.qubits)
op_name = inst.operation.name
if op_name == "barrier":
continue
self.assertIn(qubits, self.backend.target[op_name])
def test_six_component_circuit_level_1(self):
"""Test input circuit with more than 1 component per backend component."""
opt_level = 1
qc = QuantumCircuit(42)
qc.h(0)
qc.h(10)
qc.h(20)
qc.cx(0, 1)
qc.cx(0, 2)
qc.cx(0, 3)
qc.cx(0, 4)
qc.cx(0, 5)
qc.cx(0, 6)
qc.cx(0, 7)
qc.cx(0, 8)
qc.cx(0, 9)
qc.ecr(10, 11)
qc.ecr(10, 12)
qc.ecr(10, 13)
qc.ecr(10, 14)
qc.ecr(10, 15)
qc.ecr(10, 16)
qc.ecr(10, 17)
qc.ecr(10, 18)
qc.ecr(10, 19)
qc.cy(20, 21)
qc.cy(20, 22)
qc.cy(20, 23)
qc.cy(20, 24)
qc.cy(20, 25)
qc.cy(20, 26)
qc.cy(20, 27)
qc.cy(20, 28)
qc.cy(20, 29)
qc.h(30)
qc.cx(30, 31)
qc.cx(30, 32)
qc.cx(30, 33)
qc.h(34)
qc.cx(34, 35)
qc.cx(34, 36)
qc.cx(34, 37)
qc.h(38)
qc.cx(38, 39)
qc.cx(39, 40)
qc.cx(39, 41)
qc.measure_all()
tqc = transpile(qc, self.backend, optimization_level=opt_level, seed_transpiler=42)
for inst in tqc.data:
qubits = tuple(tqc.find_bit(x).index for x in inst.qubits)
op_name = inst.operation.name
if op_name == "barrier":
continue
self.assertIn(qubits, self.backend.target[op_name])
@data(0, 1, 2, 3)
def test_shared_classical_between_components_condition(self, opt_level):
"""Test a condition sharing classical bits between components."""
creg = ClassicalRegister(19)
qc = QuantumCircuit(25)
qc.add_register(creg)
qc.h(0)
for i in range(18):
qc.cx(0, i + 1)
for i in range(18):
qc.measure(i, creg[i])
qc.ecr(20, 21).c_if(creg, 0)
tqc = transpile(qc, self.backend, optimization_level=opt_level)
def _visit_block(circuit, qubit_mapping=None):
for instruction in circuit:
if instruction.operation.name == "barrier":
continue
qargs = tuple(qubit_mapping[x] for x in instruction.qubits)
self.assertTrue(
self.backend.target.instruction_supported(instruction.operation.name, qargs)
)
if isinstance(instruction.operation, ControlFlowOp):
for block in instruction.operation.blocks:
new_mapping = {
inner: qubit_mapping[outer]
for outer, inner in zip(instruction.qubits, block.qubits)
}
_visit_block(block, new_mapping)
_visit_block(
tqc,
qubit_mapping={qubit: index for index, qubit in enumerate(tqc.qubits)},
)
@data(0, 1, 2, 3)
def test_shared_classical_between_components_condition_large_to_small(self, opt_level):
"""Test a condition sharing classical bits between components."""
creg = ClassicalRegister(2)
qc = QuantumCircuit(25)
qc.add_register(creg)
# Component 0
qc.h(24)
qc.cx(24, 23)
qc.measure(24, creg[0])
qc.measure(23, creg[1])
# Component 1
qc.h(0).c_if(creg, 0)
for i in range(18):
qc.ecr(0, i + 1).c_if(creg, 0)
tqc = transpile(qc, self.backend, optimization_level=opt_level, seed_transpiler=123456789)
def _visit_block(circuit, qubit_mapping=None):
for instruction in circuit:
if instruction.operation.name == "barrier":
continue
qargs = tuple(qubit_mapping[x] for x in instruction.qubits)
self.assertTrue(
self.backend.target.instruction_supported(instruction.operation.name, qargs)
)
if isinstance(instruction.operation, ControlFlowOp):
for block in instruction.operation.blocks:
new_mapping = {
inner: qubit_mapping[outer]
for outer, inner in zip(instruction.qubits, block.qubits)
}
_visit_block(block, new_mapping)
_visit_block(
tqc,
qubit_mapping={qubit: index for index, qubit in enumerate(tqc.qubits)},
)
# Check that virtual qubits that interact with each other via quantum links are placed into
# the same component of the coupling map.
initial_layout = tqc.layout.initial_layout
coupling_map = self.backend.target.build_coupling_map()
components = [
connected_qubits(initial_layout[qc.qubits[23]], coupling_map),
connected_qubits(initial_layout[qc.qubits[0]], coupling_map),
]
self.assertLessEqual({initial_layout[qc.qubits[i]] for i in [23, 24]}, components[0])
self.assertLessEqual({initial_layout[qc.qubits[i]] for i in range(19)}, components[1])
# Check clbits are in order.
# Traverse the output dag over the sole clbit, checking that the qubits of the ops
# go in order between the components. This is a sanity check to ensure that routing
# doesn't reorder a classical data dependency between components. Inside a component
# we have the dag ordering so nothing should be out of order within a component.
tqc_dag = circuit_to_dag(tqc)
qubit_map = {qubit: index for index, qubit in enumerate(tqc_dag.qubits)}
input_node = tqc_dag.input_map[tqc_dag.clbits[0]]
first_meas_node = tqc_dag._multi_graph.find_successors_by_edge(
input_node._node_id, lambda edge_data: isinstance(edge_data, Clbit)
)[0]
# The first node should be a measurement
self.assertIsInstance(first_meas_node.op, Measure)
# This should be in the first component
self.assertIn(qubit_map[first_meas_node.qargs[0]], components[0])
op_node = tqc_dag._multi_graph.find_successors_by_edge(
first_meas_node._node_id, lambda edge_data: isinstance(edge_data, Clbit)
)[0]
while isinstance(op_node, DAGOpNode):
self.assertIn(qubit_map[op_node.qargs[0]], components[1])
op_node = tqc_dag._multi_graph.find_successors_by_edge(
op_node._node_id, lambda edge_data: isinstance(edge_data, Clbit)
)[0]
@data(1, 2, 3)
def test_shared_classical_between_components_condition_large_to_small_reverse_index(
self, opt_level
):
"""Test a condition sharing classical bits between components."""
creg = ClassicalRegister(2)
qc = QuantumCircuit(25)
qc.add_register(creg)
# Component 0
qc.h(0)
qc.cx(0, 1)
qc.measure(0, creg[0])
qc.measure(1, creg[1])
# Component 1
qc.h(24).c_if(creg, 0)
for i in range(23, 5, -1):
qc.ecr(24, i).c_if(creg, 0)
tqc = transpile(qc, self.backend, optimization_level=opt_level, seed_transpiler=2023)
def _visit_block(circuit, qubit_mapping=None):
for instruction in circuit:
if instruction.operation.name == "barrier":
continue
qargs = tuple(qubit_mapping[x] for x in instruction.qubits)
self.assertTrue(
self.backend.target.instruction_supported(instruction.operation.name, qargs)
)
if isinstance(instruction.operation, ControlFlowOp):
for block in instruction.operation.blocks:
new_mapping = {
inner: qubit_mapping[outer]
for outer, inner in zip(instruction.qubits, block.qubits)
}
_visit_block(block, new_mapping)
_visit_block(
tqc,
qubit_mapping={qubit: index for index, qubit in enumerate(tqc.qubits)},
)
# Check that virtual qubits that interact with each other via quantum links are placed into
# the same component of the coupling map.
initial_layout = tqc.layout.initial_layout
coupling_map = self.backend.target.build_coupling_map()
components = [
connected_qubits(initial_layout[qc.qubits[0]], coupling_map),
connected_qubits(initial_layout[qc.qubits[6]], coupling_map),
]
self.assertLessEqual({initial_layout[qc.qubits[i]] for i in range(2)}, components[0])
self.assertLessEqual({initial_layout[qc.qubits[i]] for i in range(6, 25)}, components[1])
# Check clbits are in order.
# Traverse the output dag over the sole clbit, checking that the qubits of the ops
# go in order between the components. This is a sanity check to ensure that routing
# doesn't reorder a classical data dependency between components. Inside a component
# we have the dag ordering so nothing should be out of order within a component.
tqc_dag = circuit_to_dag(tqc)
qubit_map = {qubit: index for index, qubit in enumerate(tqc_dag.qubits)}
input_node = tqc_dag.input_map[tqc_dag.clbits[0]]
first_meas_node = tqc_dag._multi_graph.find_successors_by_edge(
input_node._node_id, lambda edge_data: isinstance(edge_data, Clbit)
)[0]
# The first node should be a measurement
self.assertIsInstance(first_meas_node.op, Measure)
# This shoulde be in the first ocmponent
self.assertIn(qubit_map[first_meas_node.qargs[0]], components[0])
op_node = tqc_dag._multi_graph.find_successors_by_edge(
first_meas_node._node_id, lambda edge_data: isinstance(edge_data, Clbit)
)[0]
while isinstance(op_node, DAGOpNode):
self.assertIn(qubit_map[op_node.qargs[0]], components[1])
op_node = tqc_dag._multi_graph.find_successors_by_edge(
op_node._node_id, lambda edge_data: isinstance(edge_data, Clbit)
)[0]
@data(1, 2, 3)
def test_chained_data_dependency(self, opt_level):
"""Test 3 component circuit with shared clbits between each component."""
creg = ClassicalRegister(1)
qc = QuantumCircuit(30)
qc.add_register(creg)
# Component 0
qc.h(0)
for i in range(9):
qc.cx(0, i + 1)
measure_op = Measure()
qc.append(measure_op, [9], [creg[0]])
# Component 1
qc.h(10).c_if(creg, 0)
for i in range(11, 20):
qc.ecr(10, i).c_if(creg, 0)
measure_op = Measure()
qc.append(measure_op, [19], [creg[0]])
# Component 2
qc.h(20).c_if(creg, 0)
for i in range(21, 30):
qc.cz(20, i).c_if(creg, 0)
measure_op = Measure()
qc.append(measure_op, [29], [creg[0]])
tqc = transpile(qc, self.backend, optimization_level=opt_level, seed_transpiler=2023)
def _visit_block(circuit, qubit_mapping=None):
for instruction in circuit:
if instruction.operation.name == "barrier":
continue
qargs = tuple(qubit_mapping[x] for x in instruction.qubits)
self.assertTrue(
self.backend.target.instruction_supported(instruction.operation.name, qargs)
)
if isinstance(instruction.operation, ControlFlowOp):
for block in instruction.operation.blocks:
new_mapping = {
inner: qubit_mapping[outer]
for outer, inner in zip(instruction.qubits, block.qubits)
}
_visit_block(block, new_mapping)
_visit_block(
tqc,
qubit_mapping={qubit: index for index, qubit in enumerate(tqc.qubits)},
)
# Check that virtual qubits that interact with each other via quantum links are placed into
# the same component of the coupling map.
initial_layout = tqc.layout.initial_layout
coupling_map = self.backend.target.build_coupling_map()
components = [
connected_qubits(initial_layout[qc.qubits[0]], coupling_map),
connected_qubits(initial_layout[qc.qubits[10]], coupling_map),
connected_qubits(initial_layout[qc.qubits[20]], coupling_map),
]
self.assertLessEqual({initial_layout[qc.qubits[i]] for i in range(10)}, components[0])
self.assertLessEqual({initial_layout[qc.qubits[i]] for i in range(10, 20)}, components[1])
self.assertLessEqual({initial_layout[qc.qubits[i]] for i in range(20, 30)}, components[2])
# Check clbits are in order.
# Traverse the output dag over the sole clbit, checking that the qubits of the ops
# go in order between the components. This is a sanity check to ensure that routing
# doesn't reorder a classical data dependency between components. Inside a component
# we have the dag ordering so nothing should be out of order within a component.
tqc_dag = circuit_to_dag(tqc)
qubit_map = {qubit: index for index, qubit in enumerate(tqc_dag.qubits)}
input_node = tqc_dag.input_map[tqc_dag.clbits[0]]
first_meas_node = tqc_dag._multi_graph.find_successors_by_edge(
input_node._node_id, lambda edge_data: isinstance(edge_data, Clbit)
)[0]
self.assertIsInstance(first_meas_node.op, Measure)
self.assertIn(qubit_map[first_meas_node.qargs[0]], components[0])
op_node = tqc_dag._multi_graph.find_successors_by_edge(
first_meas_node._node_id, lambda edge_data: isinstance(edge_data, Clbit)
)[0]
while not isinstance(op_node.op, Measure):
self.assertIn(qubit_map[op_node.qargs[0]], components[1])
op_node = tqc_dag._multi_graph.find_successors_by_edge(
op_node._node_id, lambda edge_data: isinstance(edge_data, Clbit)
)[0]
self.assertIn(qubit_map[op_node.qargs[0]], components[1])
op_node = tqc_dag._multi_graph.find_successors_by_edge(
op_node._node_id, lambda edge_data: isinstance(edge_data, Clbit)
)[0]
while not isinstance(op_node.op, Measure):
self.assertIn(qubit_map[op_node.qargs[0]], components[2])
op_node = tqc_dag._multi_graph.find_successors_by_edge(
op_node._node_id, lambda edge_data: isinstance(edge_data, Clbit)
)[0]
self.assertIn(qubit_map[op_node.qargs[0]], components[2])
@data("sabre", "stochastic", "basic", "lookahead")
def test_basic_connected_circuit_dense_layout(self, routing_method):
"""Test basic connected circuit on disjoint backend"""
qc = QuantumCircuit(5)
qc.h(0)
qc.cx(0, 1)
qc.cx(0, 2)
qc.cx(0, 3)
qc.cx(0, 4)
qc.measure_all()
tqc = transpile(
qc,
self.backend,
layout_method="dense",
routing_method=routing_method,
seed_transpiler=42,
)
for inst in tqc.data:
qubits = tuple(tqc.find_bit(x).index for x in inst.qubits)
op_name = inst.operation.name
if op_name == "barrier":
continue
self.assertIn(qubits, self.backend.target[op_name])
# Lookahead swap skipped for performance
@data("sabre", "stochastic", "basic")
def test_triple_circuit_dense_layout(self, routing_method):
"""Test a split circuit with one circuit component per chip."""
qc = QuantumCircuit(30)
qc.h(0)
qc.h(10)
qc.h(20)
qc.cx(0, 1)
qc.cx(0, 2)
qc.cx(0, 3)
qc.cx(0, 4)
qc.cx(0, 5)
qc.cx(0, 6)
qc.cx(0, 7)
qc.cx(0, 8)
qc.cx(0, 9)
qc.ecr(10, 11)
qc.ecr(10, 12)
qc.ecr(10, 13)
qc.ecr(10, 14)
qc.ecr(10, 15)
qc.ecr(10, 16)
qc.ecr(10, 17)
qc.ecr(10, 18)
qc.ecr(10, 19)
qc.cy(20, 21)
qc.cy(20, 22)
qc.cy(20, 23)
qc.cy(20, 24)
qc.cy(20, 25)
qc.cy(20, 26)
qc.cy(20, 27)
qc.cy(20, 28)
qc.cy(20, 29)
qc.measure_all()
tqc = transpile(
qc,
self.backend,
layout_method="dense",
routing_method=routing_method,
seed_transpiler=42,
)
for inst in tqc.data:
qubits = tuple(tqc.find_bit(x).index for x in inst.qubits)
op_name = inst.operation.name
if op_name == "barrier":
continue
self.assertIn(qubits, self.backend.target[op_name])
@data("sabre", "stochastic", "basic", "lookahead")
def test_triple_circuit_invalid_layout(self, routing_method):
"""Test a split circuit with one circuit component per chip."""
qc = QuantumCircuit(30)
qc.h(0)
qc.h(10)
qc.h(20)
qc.cx(0, 1)
qc.cx(0, 2)
qc.cx(0, 3)
qc.cx(0, 4)
qc.cx(0, 5)
qc.cx(0, 6)
qc.cx(0, 7)
qc.cx(0, 8)
qc.cx(0, 9)
qc.ecr(10, 11)
qc.ecr(10, 12)
qc.ecr(10, 13)
qc.ecr(10, 14)
qc.ecr(10, 15)
qc.ecr(10, 16)
qc.ecr(10, 17)
qc.ecr(10, 18)
qc.ecr(10, 19)
qc.cy(20, 21)
qc.cy(20, 22)
qc.cy(20, 23)
qc.cy(20, 24)
qc.cy(20, 25)
qc.cy(20, 26)
qc.cy(20, 27)
qc.cy(20, 28)
qc.cy(20, 29)
qc.measure_all()
with self.assertRaises(TranspilerError):
transpile(
qc,
self.backend,
layout_method="trivial",
routing_method=routing_method,
seed_transpiler=42,
)
# Lookahead swap skipped for performance reasons
@data("sabre", "stochastic", "basic")
def test_six_component_circuit_dense_layout(self, routing_method):
"""Test input circuit with more than 1 component per backend component."""
qc = QuantumCircuit(42)
qc.h(0)
qc.h(10)
qc.h(20)
qc.cx(0, 1)
qc.cx(0, 2)
qc.cx(0, 3)
qc.cx(0, 4)
qc.cx(0, 5)
qc.cx(0, 6)
qc.cx(0, 7)
qc.cx(0, 8)
qc.cx(0, 9)
qc.ecr(10, 11)
qc.ecr(10, 12)
qc.ecr(10, 13)
qc.ecr(10, 14)
qc.ecr(10, 15)
qc.ecr(10, 16)
qc.ecr(10, 17)
qc.ecr(10, 18)
qc.ecr(10, 19)
qc.cy(20, 21)
qc.cy(20, 22)
qc.cy(20, 23)
qc.cy(20, 24)
qc.cy(20, 25)
qc.cy(20, 26)
qc.cy(20, 27)
qc.cy(20, 28)
qc.cy(20, 29)
qc.h(30)
qc.cx(30, 31)
qc.cx(30, 32)
qc.cx(30, 33)
qc.h(34)
qc.cx(34, 35)
qc.cx(34, 36)
qc.cx(34, 37)
qc.h(38)
qc.cx(38, 39)
qc.cx(39, 40)
qc.cx(39, 41)
qc.measure_all()
tqc = transpile(
qc,
self.backend,
layout_method="dense",
routing_method=routing_method,
seed_transpiler=42,
)
for inst in tqc.data:
qubits = tuple(tqc.find_bit(x).index for x in inst.qubits)
op_name = inst.operation.name
if op_name == "barrier":
continue
self.assertIn(qubits, self.backend.target[op_name])
@data(0, 1, 2, 3)
def test_transpile_target_with_qubits_without_ops(self, opt_level):
"""Test qubits without operations aren't ever used."""
target = Target(num_qubits=5)
target.add_instruction(XGate(), {(i,): InstructionProperties(error=0.5) for i in range(3)})
target.add_instruction(HGate(), {(i,): InstructionProperties(error=0.5) for i in range(3)})
target.add_instruction(
CXGate(), {edge: InstructionProperties(error=0.5) for edge in [(0, 1), (1, 2), (2, 0)]}
)
qc = QuantumCircuit(3)
qc.x(0)
qc.cx(0, 1)
qc.cx(0, 2)
tqc = transpile(qc, target=target, optimization_level=opt_level)
invalid_qubits = {3, 4}
self.assertEqual(tqc.num_qubits, 5)
for inst in tqc.data:
for bit in inst.qubits:
self.assertNotIn(tqc.find_bit(bit).index, invalid_qubits)
@data(0, 1, 2, 3)
def test_transpile_target_with_qubits_without_ops_with_routing(self, opt_level):
"""Test qubits without operations aren't ever used."""
target = Target(num_qubits=5)
target.add_instruction(XGate(), {(i,): InstructionProperties(error=0.5) for i in range(4)})
target.add_instruction(HGate(), {(i,): InstructionProperties(error=0.5) for i in range(4)})
target.add_instruction(
CXGate(),
{edge: InstructionProperties(error=0.5) for edge in [(0, 1), (1, 2), (2, 0), (2, 3)]},
)
qc = QuantumCircuit(4)
qc.x(0)
qc.cx(0, 1)
qc.cx(0, 2)
qc.cx(1, 3)
qc.cx(0, 3)
tqc = transpile(qc, target=target, optimization_level=opt_level)
invalid_qubits = {
4,
}
self.assertEqual(tqc.num_qubits, 5)
for inst in tqc.data:
for bit in inst.qubits:
self.assertNotIn(tqc.find_bit(bit).index, invalid_qubits)
@data(0, 1, 2, 3)
def test_transpile_target_with_qubits_without_ops_circuit_too_large(self, opt_level):
"""Test qubits without operations aren't ever used and error if circuit needs them."""
target = Target(num_qubits=5)
target.add_instruction(XGate(), {(i,): InstructionProperties(error=0.5) for i in range(3)})
target.add_instruction(HGate(), {(i,): InstructionProperties(error=0.5) for i in range(3)})
target.add_instruction(
CXGate(), {edge: InstructionProperties(error=0.5) for edge in [(0, 1), (1, 2), (2, 0)]}
)
qc = QuantumCircuit(4)
qc.x(0)
qc.cx(0, 1)
qc.cx(0, 2)
qc.cx(0, 3)
with self.assertRaises(TranspilerError):
transpile(qc, target=target, optimization_level=opt_level)
@data(0, 1, 2, 3)
def test_transpile_target_with_qubits_without_ops_circuit_too_large_disconnected(
self, opt_level
):
"""Test qubits without operations aren't ever used if a disconnected circuit needs them."""
target = Target(num_qubits=5)
target.add_instruction(XGate(), {(i,): InstructionProperties(error=0.5) for i in range(3)})
target.add_instruction(HGate(), {(i,): InstructionProperties(error=0.5) for i in range(3)})
target.add_instruction(
CXGate(), {edge: InstructionProperties(error=0.5) for edge in [(0, 1), (1, 2), (2, 0)]}
)
qc = QuantumCircuit(5)
qc.x(0)
qc.x(1)
qc.x(3)
qc.x(4)
with self.assertRaises(TranspilerError):
transpile(qc, target=target, optimization_level=opt_level)
@data(0, 1, 2, 3)
def test_transpile_does_not_affect_backend_coupling(self, opt_level):
"""Test that transpiliation of a circuit does not mutate the `CouplingMap` stored by a V2
backend. Regression test of gh-9997."""
if opt_level == 3:
raise unittest.SkipTest("unitary resynthesis fails due to gh-10004")
qc = QuantumCircuit(127)
for i in range(1, 127):
qc.ecr(0, i)
backend = FakeSherbrooke()
original_map = copy.deepcopy(backend.coupling_map)
transpile(qc, backend, optimization_level=opt_level)
self.assertEqual(original_map, backend.coupling_map)
@combine(
optimization_level=[0, 1, 2, 3],
scheduling_method=["asap", "alap"],
)
def test_transpile_target_with_qubits_without_delays_with_scheduling(
self, optimization_level, scheduling_method
):
"""Test qubits without operations aren't ever used."""
no_delay_qubits = [1, 3, 4]
target = Target(num_qubits=5, dt=1)
target.add_instruction(
XGate(), {(i,): InstructionProperties(duration=160) for i in range(4)}
)
target.add_instruction(
HGate(), {(i,): InstructionProperties(duration=160) for i in range(4)}
)
target.add_instruction(
CXGate(),
{
edge: InstructionProperties(duration=800)
for edge in [(0, 1), (1, 2), (2, 0), (2, 3)]
},
)
target.add_instruction(
Delay(Parameter("t")), {(i,): None for i in range(4) if i not in no_delay_qubits}
)
qc = QuantumCircuit(4)
qc.x(0)
qc.cx(0, 1)
qc.cx(0, 2)
qc.cx(1, 3)
qc.cx(0, 3)
tqc = transpile(
qc,
target=target,
optimization_level=optimization_level,
scheduling_method=scheduling_method,
)
invalid_qubits = {
4,
}
self.assertEqual(tqc.num_qubits, 5)
for inst in tqc.data:
for bit in inst.qubits:
self.assertNotIn(tqc.find_bit(bit).index, invalid_qubits)
if isinstance(inst.operation, Delay):
self.assertNotIn(tqc.find_bit(bit).index, no_delay_qubits)
|
https://github.com/unitaryfund/mitiq
|
unitaryfund
|
# Copyright (C) Unitary Fund
#
# This source code is licensed under the GPL license (v3) found in the
# LICENSE file in the root directory of this source tree.
import os
import numpy as np
import pytest
import qiskit
from cirq import (
Circuit,
CXPowGate,
DepolarizingChannel,
I,
LineQubit,
MixedUnitaryChannel,
Rx,
Rz,
X,
Y,
Z,
ops,
unitary,
)
from mitiq import Executor, Observable, PauliString
from mitiq.cdr import generate_training_circuits
from mitiq.cdr._testing import random_x_z_cnot_circuit
from mitiq.interface.mitiq_cirq import compute_density_matrix
from mitiq.interface.mitiq_qiskit import qiskit_utils
from mitiq.interface.mitiq_qiskit.conversions import to_qiskit
from mitiq.pec.representations.learning import (
_parse_learning_kwargs,
biased_noise_loss_function,
depolarizing_noise_loss_function,
learn_biased_noise_parameters,
learn_depolarizing_noise_parameter,
)
rng = np.random.RandomState(1)
circuit = random_x_z_cnot_circuit(
LineQubit.range(2), n_moments=5, random_state=rng
)
# Set number of samples used to calculate mitigated value in loss function
pec_kwargs = {"num_samples": 20, "random_state": 1}
observable = Observable(PauliString("XZ"), PauliString("YY"))
training_circuits = generate_training_circuits(
circuit=circuit,
num_training_circuits=3,
fraction_non_clifford=0,
method_select="uniform",
method_replace="closest",
)
CNOT_ops = list(circuit.findall_operations_with_gate_type(CXPowGate))
Rx_ops = list(circuit.findall_operations_with_gate_type(Rx))
Rz_ops = list(circuit.findall_operations_with_gate_type(Rz))
def ideal_execute(circ: Circuit) -> np.ndarray:
return compute_density_matrix(circ, noise_level=(0.0,))
ideal_executor = Executor(ideal_execute)
ideal_values = np.array(ideal_executor.evaluate(training_circuits, observable))
def biased_noise_channel(epsilon: float, eta: float) -> MixedUnitaryChannel:
a = 1 - epsilon
b = epsilon * (3 * eta + 1) / (3 * (eta + 1))
c = epsilon / (3 * (eta + 1))
mix = [
(a, unitary(I)),
(b, unitary(Z)),
(c, unitary(X)),
(c, unitary(Y)),
]
return ops.MixedUnitaryChannel(mix)
@pytest.mark.parametrize("epsilon", [0.05, 0.1])
@pytest.mark.parametrize(
"operations", [[Circuit(CNOT_ops[0][1])], [Circuit(Rx_ops[0][1])]]
)
def test_depolarizing_noise_loss_function(epsilon, operations):
"""Test that the biased noise loss function value (calculated with error
mitigation) is less than (or equal to) the loss calculated with the noisy
(unmitigated) executor"""
def noisy_execute(circ: Circuit) -> np.ndarray:
noisy_circ = circ.with_noise(DepolarizingChannel(epsilon))
return ideal_execute(noisy_circ)
noisy_executor = Executor(noisy_execute)
noisy_values = np.array(
noisy_executor.evaluate(training_circuits, observable)
)
loss = depolarizing_noise_loss_function(
epsilon=np.array([epsilon]),
operations_to_mitigate=operations,
training_circuits=training_circuits,
ideal_values=ideal_values,
noisy_executor=noisy_executor,
pec_kwargs=pec_kwargs,
observable=observable,
)
assert loss <= np.mean((noisy_values - ideal_values) ** 2)
@pytest.mark.parametrize("epsilon", [0, 0.7, 1])
@pytest.mark.parametrize("eta", [0, 1])
@pytest.mark.parametrize(
"operations", [[Circuit(CNOT_ops[0][1])], [Circuit(Rx_ops[0][1])]]
)
def test_biased_noise_loss_function(epsilon, eta, operations):
"""Test that the biased noise loss function value (calculated with error
mitigation) is less than (or equal to) the loss calculated with the noisy
(unmitigated) executor"""
def noisy_execute(circ: Circuit) -> np.ndarray:
noisy_circ = circ.with_noise(biased_noise_channel(epsilon, eta))
return ideal_execute(noisy_circ)
noisy_executor = Executor(noisy_execute)
noisy_values = np.array(
noisy_executor.evaluate(training_circuits, observable)
)
loss = biased_noise_loss_function(
params=[epsilon, eta],
operations_to_mitigate=operations,
training_circuits=training_circuits,
ideal_values=ideal_values,
noisy_executor=noisy_executor,
pec_kwargs=pec_kwargs,
observable=observable,
)
assert loss <= np.mean((noisy_values - ideal_values) ** 2)
@pytest.mark.parametrize(
"operations", [[Circuit(CNOT_ops[0][1])], [Circuit(Rz_ops[0][1])]]
)
def test_biased_noise_loss_compare_ideal(operations):
"""Test that the loss function is zero when the noise strength is zero"""
def noisy_execute(circ: Circuit) -> np.ndarray:
noisy_circ = circ.with_noise(biased_noise_channel(0, 0))
return ideal_execute(noisy_circ)
noisy_executor = Executor(noisy_execute)
loss = biased_noise_loss_function(
params=[0, 0],
operations_to_mitigate=operations,
training_circuits=training_circuits,
ideal_values=ideal_values,
noisy_executor=noisy_executor,
pec_kwargs=pec_kwargs,
observable=observable,
)
assert np.isclose(loss, 0)
@pytest.mark.parametrize(
"operations",
[
[to_qiskit(Circuit(CNOT_ops[0][1]))],
[to_qiskit(Circuit(Rx_ops[0][1]))],
[to_qiskit(Circuit(Rz_ops[0][1]))],
],
)
def test_biased_noise_loss_function_qiskit(operations):
"""Test the learning function with initial noise strength and noise bias
with a small offset from the simulated noise model values"""
qiskit_circuit = to_qiskit(circuit)
qiskit_training_circuits = generate_training_circuits(
circuit=qiskit_circuit,
num_training_circuits=3,
fraction_non_clifford=0.2,
method_select="uniform",
method_replace="closest",
random_state=rng,
)
obs = Observable(PauliString("XY"), PauliString("ZZ"))
def ideal_execute_qiskit(circ: qiskit.QuantumCircuit) -> float:
return qiskit_utils.execute(circ, obs.matrix())
ideal_executor_qiskit = Executor(ideal_execute_qiskit)
ideal_values = np.array(
ideal_executor_qiskit.evaluate(qiskit_training_circuits)
)
epsilon = 0.1
def noisy_execute_qiskit(circ: qiskit.QuantumCircuit) -> float:
noise_model = qiskit_utils.initialized_depolarizing_noise(epsilon)
return qiskit_utils.execute_with_noise(circ, obs.matrix(), noise_model)
noisy_executor_qiskit = Executor(noisy_execute_qiskit)
noisy_values = np.array(
noisy_executor_qiskit.evaluate(qiskit_training_circuits)
)
loss = biased_noise_loss_function(
params=[epsilon, 0],
operations_to_mitigate=operations,
training_circuits=qiskit_training_circuits,
ideal_values=ideal_values,
noisy_executor=noisy_executor_qiskit,
pec_kwargs=pec_kwargs,
)
assert loss <= np.mean((noisy_values - ideal_values) ** 2)
@pytest.mark.parametrize("epsilon", [0.05, 0.1])
def test_learn_depolarizing_noise_parameter(epsilon):
"""Test the learning function with initial noise strength with a small
offset from the simulated noise model values"""
operations_to_learn = [Circuit(op[1]) for op in CNOT_ops]
offset = 0.1
def noisy_execute(circ: Circuit) -> np.ndarray:
noisy_circ = circ.copy()
insertions = []
for op in CNOT_ops:
index = op[0] + 1
qubits = op[1].qubits
for q in qubits:
insertions.append((index, DepolarizingChannel(epsilon)(q)))
noisy_circ.batch_insert(insertions)
return ideal_execute(noisy_circ)
noisy_executor = Executor(noisy_execute)
epsilon0 = (1 - offset) * epsilon
eps_string = str(epsilon).replace(".", "_")
pec_data = np.loadtxt(
os.path.join(
"./mitiq/pec/representations/tests/learning_pec_data",
f"learning_pec_data_eps_{eps_string}.txt",
)
)
[success, epsilon_opt] = learn_depolarizing_noise_parameter(
operations_to_learn=operations_to_learn,
circuit=circuit,
ideal_executor=ideal_executor,
noisy_executor=noisy_executor,
num_training_circuits=5,
fraction_non_clifford=0.2,
training_random_state=np.random.RandomState(1),
epsilon0=epsilon0,
observable=observable,
learning_kwargs={"pec_data": pec_data},
)
assert success
assert abs(epsilon_opt - epsilon) < offset * epsilon
@pytest.mark.parametrize("epsilon", [0.05, 0.1])
@pytest.mark.parametrize("eta", [1, 2])
def test_learn_biased_noise_parameters(epsilon, eta):
"""Test the learning function can run without pre-executed data"""
operations_to_learn = [Circuit(op[1]) for op in CNOT_ops]
def noisy_execute(circ: Circuit) -> np.ndarray:
noisy_circ = circ.copy()
insertions = []
for op in CNOT_ops:
index = op[0] + 1
qubits = op[1].qubits
for q in qubits:
insertions.append(
(index, biased_noise_channel(epsilon, eta)(q))
)
noisy_circ.batch_insert(insertions)
return ideal_execute(noisy_circ)
noisy_executor = Executor(noisy_execute)
eps_offset = 0.1
eta_offset = 0.2
epsilon0 = (1 - eps_offset) * epsilon
eta0 = (1 - eta_offset) * eta
num_training_circuits = 5
pec_data = np.zeros([122, 122, num_training_circuits])
eps_string = str(epsilon).replace(".", "_")
for tc in range(0, num_training_circuits):
pec_data[:, :, tc] = np.loadtxt(
os.path.join(
"./mitiq/pec/representations/tests/learning_pec_data",
f"learning_pec_data_eps_{eps_string}eta_{eta}tc_{tc}.txt",
)
)
[success, epsilon_opt, eta_opt] = learn_biased_noise_parameters(
operations_to_learn=operations_to_learn,
circuit=circuit,
ideal_executor=ideal_executor,
noisy_executor=noisy_executor,
num_training_circuits=num_training_circuits,
fraction_non_clifford=0.2,
training_random_state=np.random.RandomState(1),
epsilon0=epsilon0,
eta0=eta0,
observable=observable,
learning_kwargs={"pec_data": pec_data},
)
assert success
assert abs(epsilon_opt - epsilon) < eps_offset * epsilon
assert abs(eta_opt - eta) < eta_offset * eta
def test_empty_learning_kwargs():
learning_kwargs = {}
pec_data, method, minimize_kwargs = _parse_learning_kwargs(
learning_kwargs=learning_kwargs
)
assert pec_data is None
assert method == "Nelder-Mead"
assert minimize_kwargs == {}
|
https://github.com/unitaryfund/mitiq
|
unitaryfund
|
# Copyright (C) Unitary Fund
#
# This source code is licensed under the GPL license (v3) found in the
# LICENSE file in the root directory of this source tree.
"""Unit tests for PEC."""
import warnings
from functools import partial
from typing import List, Optional
import cirq
import numpy as np
import pyquil
import pytest
import qiskit
from mitiq import QPROGRAM, SUPPORTED_PROGRAM_TYPES, Observable, PauliString
from mitiq.interface import convert_from_mitiq, convert_to_mitiq, mitiq_cirq
from mitiq.interface.mitiq_cirq import compute_density_matrix
from mitiq.pec import (
NoisyOperation,
OperationRepresentation,
execute_with_pec,
mitigate_executor,
pec_decorator,
)
from mitiq.pec.representations import (
represent_operations_in_circuit_with_local_depolarizing_noise,
)
# Noisy representations of Pauli and CNOT operations for testing.
def get_pauli_and_cnot_representations(
base_noise: float,
qubits: Optional[List[cirq.Qid]] = None,
) -> List[OperationRepresentation]:
if qubits is None:
qreg = cirq.LineQubit.range(2)
else:
qreg = qubits
# Generate all ideal single-qubit Pauli operations for both qubits
pauli_gates = [cirq.X, cirq.Y, cirq.Z]
ideal_operations = []
for gate in pauli_gates:
for qubit in qreg:
ideal_operations.append(gate(qubit))
# Add CNOT operation too
ideal_operations.append(cirq.CNOT(*qreg))
# Generate all representations
return represent_operations_in_circuit_with_local_depolarizing_noise(
ideal_circuit=cirq.Circuit(ideal_operations),
noise_level=base_noise,
)
BASE_NOISE = 0.02
pauli_representations = get_pauli_and_cnot_representations(BASE_NOISE)
noiseless_pauli_representations = get_pauli_and_cnot_representations(0.0)
def serial_executor(circuit: QPROGRAM, noise: float = BASE_NOISE) -> float:
"""A noisy executor function which executes the input circuit with `noise`
depolarizing noise and returns the expectation value of the ground state
projector. Simulation will be slow for "large circuits" (> a few qubits).
"""
circuit, _ = convert_to_mitiq(circuit)
return compute_density_matrix(
circuit, noise_model_function=cirq.depolarize, noise_level=(noise,)
)[0, 0].real
def batched_executor(circuits) -> List[float]:
return [serial_executor(circuit) for circuit in circuits]
def noiseless_serial_executor(circuit: QPROGRAM) -> float:
return serial_executor(circuit, noise=0.0)
def fake_executor(circuit: cirq.Circuit, random_state: np.random.RandomState):
"""A fake executor which just samples from a normal distribution."""
return random_state.randn()
# Simple circuits for testing.
q0, q1 = cirq.LineQubit.range(2)
oneq_circ = cirq.Circuit(cirq.Z.on(q0), cirq.Z.on(q0))
twoq_circ = cirq.Circuit(cirq.Y.on(q1), cirq.CNOT.on(q0, q1), cirq.Y.on(q1))
def test_execute_with_pec_cirq_trivial_decomposition():
circuit = cirq.Circuit(cirq.H.on(cirq.LineQubit(0)))
rep = OperationRepresentation(
circuit,
[NoisyOperation(circuit)],
[1.0],
)
unmitigated = serial_executor(circuit)
mitigated = execute_with_pec(
circuit,
serial_executor,
representations=[rep],
num_samples=10,
random_state=1,
)
assert np.isclose(unmitigated, mitigated)
def test_execute_with_pec_pyquil_trivial_decomposition():
circuit = pyquil.Program(pyquil.gates.H(0))
rep = OperationRepresentation(
circuit,
[NoisyOperation(circuit)],
[1.0],
)
unmitigated = serial_executor(circuit)
mitigated = execute_with_pec(
circuit,
serial_executor,
representations=[rep],
num_samples=10,
random_state=1,
)
assert np.isclose(unmitigated, mitigated)
def test_execute_with_pec_qiskit_trivial_decomposition():
qreg = qiskit.QuantumRegister(1)
circuit = qiskit.QuantumCircuit(qreg)
_ = circuit.x(qreg)
rep = OperationRepresentation(
circuit,
[NoisyOperation(circuit)],
[1.0],
)
unmitigated = serial_executor(circuit)
mitigated = execute_with_pec(
circuit,
serial_executor,
representations=[rep],
num_samples=10,
random_state=1,
)
assert np.isclose(unmitigated, mitigated)
@pytest.mark.parametrize("circuit", [oneq_circ, twoq_circ])
def test_execute_with_pec_cirq_noiseless_decomposition(circuit):
unmitigated = noiseless_serial_executor(circuit)
mitigated = execute_with_pec(
circuit,
noiseless_serial_executor,
representations=noiseless_pauli_representations,
num_samples=10,
random_state=1,
)
assert np.isclose(unmitigated, mitigated)
@pytest.mark.parametrize("nqubits", [1, 2])
def test_pyquil_noiseless_decomposition_multiqubit(nqubits):
circuit = pyquil.Program(pyquil.gates.H(q) for q in range(nqubits))
# Decompose H(q) for each qubit q into Paulis.
representations = []
for q in range(nqubits):
representation = OperationRepresentation(
pyquil.Program(pyquil.gates.H(q)),
[
NoisyOperation(pyquil.Program(pyquil.gates.X(q))),
NoisyOperation(pyquil.Program(pyquil.gates.Z(q))),
],
coeffs=[0.5, 0.5],
)
representations.append(representation)
exact = noiseless_serial_executor(circuit)
pec_value = execute_with_pec(
circuit,
noiseless_serial_executor,
representations=representations,
num_samples=500,
random_state=1,
force_run_all=False,
)
assert np.isclose(pec_value, exact, atol=0.1)
@pytest.mark.parametrize("nqubits", [1, 2])
def test_qiskit_noiseless_decomposition_multiqubit(nqubits):
qreg = [qiskit.QuantumRegister(1) for _ in range(nqubits)]
circuit = qiskit.QuantumCircuit(*qreg)
for q in qreg:
circuit.h(q)
# Decompose H(q) for each qubit q into Paulis.
representations = []
for q in qreg:
opcircuit = qiskit.QuantumCircuit(q)
opcircuit.h(q)
xcircuit = qiskit.QuantumCircuit(q)
xcircuit.x(q)
zcircuit = qiskit.QuantumCircuit(q)
zcircuit.z(q)
representation = OperationRepresentation(
opcircuit,
[
NoisyOperation(circuit=xcircuit),
NoisyOperation(circuit=zcircuit),
],
[0.5, 0.5],
)
representations.append(representation)
exact = noiseless_serial_executor(circuit)
pec_value = execute_with_pec(
circuit,
noiseless_serial_executor,
representations=representations,
num_samples=500,
random_state=1,
force_run_all=False,
)
assert np.isclose(pec_value, exact, atol=0.1)
@pytest.mark.parametrize("circuit", [oneq_circ, twoq_circ])
@pytest.mark.parametrize("executor", [serial_executor, batched_executor])
@pytest.mark.parametrize("circuit_type", SUPPORTED_PROGRAM_TYPES.keys())
def test_execute_with_pec_mitigates_noise(circuit, executor, circuit_type):
"""Tests that execute_with_pec mitigates the error of a noisy
expectation value.
"""
circuit = convert_from_mitiq(circuit, circuit_type)
true_noiseless_value = 1.0
unmitigated = serial_executor(circuit)
if circuit_type in ["qiskit", "pennylane", "qibo"]:
# Note this is an important subtlety necessary because of conversions.
reps = get_pauli_and_cnot_representations(
base_noise=BASE_NOISE,
qubits=[cirq.NamedQubit(name) for name in ("q_0", "q_1")],
)
# TODO: PEC with Qiskit is slow.
# See https://github.com/unitaryfund/mitiq/issues/507.
circuit, _ = convert_to_mitiq(circuit)
else:
reps = pauli_representations
mitigated = execute_with_pec(
circuit,
executor,
representations=reps,
num_samples=100,
force_run_all=False,
random_state=101,
)
error_unmitigated = abs(unmitigated - true_noiseless_value)
error_mitigated = abs(mitigated - true_noiseless_value)
assert error_mitigated < error_unmitigated
assert np.isclose(mitigated, true_noiseless_value, atol=0.1)
def test_execute_with_pec_with_observable():
circuit = twoq_circ
obs = Observable(PauliString("ZZ"))
executor = partial(
mitiq_cirq.compute_density_matrix,
noise_model_function=cirq.depolarize,
noise_level=(BASE_NOISE,),
)
true_value = 1.0
noisy_value = obs.expectation(circuit, mitiq_cirq.compute_density_matrix)
pec_value = execute_with_pec(
circuit,
executor,
observable=obs,
representations=pauli_representations,
num_samples=100,
force_run_all=False,
random_state=101,
)
assert abs(pec_value - true_value) < abs(noisy_value - true_value)
assert np.isclose(pec_value, true_value, atol=0.1)
def test_execute_with_pec_partial_representations():
# Only use the CNOT representation.
reps = [pauli_representations[-1]]
pec_value = execute_with_pec(
twoq_circ,
executor=partial(
mitiq_cirq.compute_density_matrix,
noise_model_function=cirq.depolarize,
noise_level=(BASE_NOISE,),
),
observable=Observable(PauliString("ZZ")),
representations=reps,
num_samples=100,
force_run_all=False,
random_state=101,
)
assert isinstance(pec_value, float)
@pytest.mark.parametrize("circuit", [oneq_circ, twoq_circ])
@pytest.mark.parametrize("seed", (2, 3))
def test_execute_with_pec_with_different_samples(circuit, seed):
"""Tests that, on average, the error decreases as the number of samples is
increased.
"""
small_sample_number = 10
large_sample_number = 100
errors = []
for num_samples in (small_sample_number, large_sample_number):
mitigated = execute_with_pec(
circuit,
serial_executor,
representations=pauli_representations,
num_samples=num_samples,
force_run_all=True,
random_state=seed,
)
errors.append(abs(mitigated - 1.0))
assert np.average(errors[1]) < np.average(errors[0])
@pytest.mark.parametrize("num_samples", [100, 500])
def test_execute_with_pec_error_scaling(num_samples: int):
"""Tests that the error associated to the PEC value scales as
1/sqrt(num_samples).
"""
_, pec_data = execute_with_pec(
oneq_circ,
partial(fake_executor, random_state=np.random.RandomState(0)),
representations=pauli_representations,
num_samples=num_samples,
force_run_all=True,
full_output=True,
)
# The error should scale as 1/sqrt(num_samples)
normalized_error = pec_data["pec_error"] * np.sqrt(num_samples)
assert np.isclose(normalized_error, 1.0, atol=0.1)
@pytest.mark.parametrize("precision", [0.2, 0.1])
def test_precision_option_in_execute_with_pec(precision: float):
"""Tests that the 'precision' argument is used to deduce num_samples."""
# For a noiseless circuit we expect num_samples = 1/precision^2:
_, pec_data = execute_with_pec(
oneq_circ,
partial(fake_executor, random_state=np.random.RandomState(0)),
representations=pauli_representations,
precision=precision,
force_run_all=True,
full_output=True,
random_state=1,
)
# The error should scale as precision
assert np.isclose(pec_data["pec_error"] / precision, 1.0, atol=0.15)
# Check precision is ignored when num_samples is given.
num_samples = 1
_, pec_data = execute_with_pec(
oneq_circ,
partial(fake_executor, random_state=np.random.RandomState(0)),
representations=pauli_representations,
precision=precision,
num_samples=num_samples,
force_run_all=False,
full_output=True,
)
assert pec_data["num_samples"] == num_samples
@pytest.mark.parametrize("bad_value", (0, -1, 2))
def test_bad_precision_argument(bad_value: float):
"""Tests that if 'precision' is not within (0, 1] an error is raised."""
with pytest.raises(ValueError, match="The value of 'precision' should"):
execute_with_pec(
oneq_circ,
serial_executor,
representations=pauli_representations,
precision=bad_value,
)
def test_large_sample_size_warning():
"""Tests whether a warning is raised when PEC sample size
is greater than 10 ** 5.
"""
warnings.simplefilter("error")
with pytest.raises(
Warning,
match="The number of PEC samples is very large.",
):
execute_with_pec(
oneq_circ,
partial(fake_executor, random_state=np.random.RandomState(0)),
representations=pauli_representations,
num_samples=100001,
force_run_all=False,
)
def test_pec_data_with_full_output():
"""Tests that execute_with_pec mitigates the error of a noisy
expectation value.
"""
precision = 0.5
pec_value, pec_data = execute_with_pec(
twoq_circ,
serial_executor,
precision=precision,
representations=pauli_representations,
full_output=True,
random_state=102,
)
# Get num samples from precision
norm = 1.0
for op in twoq_circ.all_operations():
for rep in pauli_representations:
if rep.ideal == cirq.Circuit(op):
norm *= rep.norm
num_samples = int((norm / precision) ** 2)
# Manually get raw expectation values
exp_values = [serial_executor(c) for c in pec_data["sampled_circuits"]]
assert pec_data["num_samples"] == num_samples
assert pec_data["precision"] == precision
assert np.isclose(pec_data["pec_value"], pec_value)
assert np.isclose(
pec_data["pec_error"],
np.std(pec_data["unbiased_estimators"]) / np.sqrt(num_samples),
)
assert np.isclose(np.average(pec_data["unbiased_estimators"]), pec_value)
assert np.allclose(pec_data["measured_expectation_values"], exp_values)
def decorated_serial_executor(circuit: QPROGRAM) -> float:
"""Returns a decorated serial executor for use with other tests. The serial
executor is decorated with the same representations as those that are used
in the tests for trivial decomposition.
"""
rep = OperationRepresentation(
circuit,
[NoisyOperation(circuit)],
[1.0],
)
@pec_decorator(representations=[rep], precision=0.08, force_run_all=False)
def decorated_executor(qp):
return serial_executor(qp)
return decorated_executor(circuit)
def test_mitigate_executor_qiskit():
"""Performs the same test as
test_execute_with_pec_qiskit_trivial_decomposition(), but using
mitigate_executor() instead of execute_with_pec().
"""
qreg = qiskit.QuantumRegister(1)
circuit = qiskit.QuantumCircuit(qreg)
_ = circuit.x(qreg)
rep = OperationRepresentation(
circuit,
[NoisyOperation(circuit)],
[1.0],
)
unmitigated = serial_executor(circuit)
mitigated_executor = mitigate_executor(
serial_executor,
representations=[rep],
num_samples=10,
random_state=1,
)
mitigated = mitigated_executor(circuit)
assert np.isclose(unmitigated, mitigated)
batched_unmitigated = batched_executor([circuit] * 3)
batched_mitigated_executor = mitigate_executor(
batched_executor,
representations=[rep],
num_samples=10,
random_state=1,
)
batched_mitigated = batched_mitigated_executor([circuit] * 3)
assert [
np.isclose(batched_unmitigated_value, batched_mitigated_value)
for batched_unmitigated_value, batched_mitigated_value in zip(
batched_unmitigated, batched_mitigated
)
]
def test_pec_decorator_qiskit():
"""Performs the same test as test_mitigate_executor_qiskit(), but using
pec_decorator() instead of mitigate_executor().
"""
qreg = qiskit.QuantumRegister(1)
circuit = qiskit.QuantumCircuit(qreg)
_ = circuit.x(qreg)
unmitigated = serial_executor(circuit)
mitigated = decorated_serial_executor(circuit)
assert np.isclose(unmitigated, mitigated)
def test_mitigate_executor_cirq():
"""Performs the same test as
test_execute_with_pec_cirq_trivial_decomposition(), but using
mitigate_executor() instead of execute_with_pec().
"""
circuit = cirq.Circuit(cirq.H.on(cirq.LineQubit(0)))
rep = OperationRepresentation(
circuit,
[NoisyOperation(circuit)],
[1.0],
)
unmitigated = serial_executor(circuit)
mitigated_executor = mitigate_executor(
serial_executor,
representations=[rep],
num_samples=10,
random_state=1,
)
mitigated = mitigated_executor(circuit)
assert np.isclose(unmitigated, mitigated)
def test_pec_decorator_cirq():
"""Performs the same test as test_mitigate_executor_cirq(), but using
pec_decorator() instead of mitigate_executor().
"""
circuit = cirq.Circuit(cirq.H.on(cirq.LineQubit(0)))
unmitigated = serial_executor(circuit)
mitigated = decorated_serial_executor(circuit)
assert np.isclose(unmitigated, mitigated)
def test_mitigate_executor_pyquil():
"""Performs the same test as
test_execute_with_pec_pyquil_trivial_decomposition(), but using
mitigate_executor() instead of execute_with_pec().
"""
circuit = pyquil.Program(pyquil.gates.H(0))
rep = OperationRepresentation(
circuit,
[NoisyOperation(circuit)],
[1.0],
)
unmitigated = serial_executor(circuit)
mitigated_executor = mitigate_executor(
serial_executor,
representations=[rep],
num_samples=10,
random_state=1,
)
mitigated = mitigated_executor(circuit)
assert np.isclose(unmitigated, mitigated)
def test_pec_decorator_pyquil():
"""Performs the same test as test_mitigate_executor_pyquil(), but using
pec_decorator() instead of mitigate_executor().
"""
circuit = pyquil.Program(pyquil.gates.H(0))
unmitigated = serial_executor(circuit)
mitigated = decorated_serial_executor(circuit)
assert np.isclose(unmitigated, mitigated)
def test_doc_is_preserved():
"""Tests that the doc of the original executor is preserved."""
representations = get_pauli_and_cnot_representations(0)
def first_executor(circuit):
"""Doc of the original executor."""
return 0
mit_executor = mitigate_executor(
first_executor, representations=representations
)
assert mit_executor.__doc__ == first_executor.__doc__
@pec_decorator(representations=representations)
def second_executor(circuit):
"""Doc of the original executor."""
return 0
assert second_executor.__doc__ == first_executor.__doc__
@pytest.mark.parametrize("circuit_type", SUPPORTED_PROGRAM_TYPES.keys())
def test_executed_circuits_have_the_expected_type(circuit_type):
circuit = convert_from_mitiq(oneq_circ, circuit_type)
circuit_type = type(circuit)
# Fake executor just for testing types
def type_detecting_executor(circuit: QPROGRAM):
assert type(circuit) is circuit_type
return 0.0
mitigated = execute_with_pec(
circuit,
executor=type_detecting_executor,
representations=pauli_representations,
num_samples=1,
)
assert np.isclose(mitigated, 0.0)
|
https://github.com/unitaryfund/mitiq
|
unitaryfund
|
# Copyright (C) Unitary Fund
#
# This source code is licensed under the GPL license (v3) found in the
# LICENSE file in the root directory of this source tree.
"""Tests for mitiq.pec.sampling functions."""
import cirq
import numpy as np
import pytest
from cirq import (
Circuit,
Gate,
LineQubit,
NamedQubit,
depolarize,
measure,
measure_each,
ops,
)
from pyquil import Program, gates
from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister
from mitiq.pec import (
NoisyOperation,
OperationRepresentation,
represent_operation_with_global_depolarizing_noise,
sample_circuit,
sample_sequence,
)
from mitiq.pec.channels import _circuit_to_choi, _operation_to_choi
from mitiq.pec.representations import (
represent_operation_with_local_depolarizing_noise,
represent_operations_in_circuit_with_local_depolarizing_noise,
)
from mitiq.utils import _equal
xcirq = Circuit(cirq.X(cirq.LineQubit(0)))
zcirq = Circuit(cirq.Z(cirq.LineQubit(0)))
cnotcirq = Circuit(cirq.CNOT(cirq.LineQubit(0), cirq.LineQubit(1)))
czcirq = Circuit(cirq.CZ(cirq.LineQubit(0), cirq.LineQubit(1)))
def test_sample_sequence_cirq():
circuit = Circuit(cirq.H(LineQubit(0)))
circuit.append(measure(LineQubit(0)))
rep = OperationRepresentation(
ideal=circuit,
noisy_operations=[NoisyOperation(xcirq), NoisyOperation(zcirq)],
coeffs=[0.5, -0.5],
)
for _ in range(5):
seqs, signs, norm = sample_sequence(circuit, representations=[rep])
assert isinstance(seqs[0], Circuit)
assert signs[0] in {1, -1}
assert norm == 1.0
def test_sample_sequence_qiskit():
qreg = QuantumRegister(1)
circuit = QuantumCircuit(qreg)
_ = circuit.h(qreg)
xcircuit = QuantumCircuit(qreg)
_ = xcircuit.x(qreg)
zcircuit = QuantumCircuit(qreg)
_ = zcircuit.z(qreg)
noisy_xop = NoisyOperation(xcircuit)
noisy_zop = NoisyOperation(zcircuit)
rep = OperationRepresentation(
ideal=circuit,
noisy_operations=[noisy_xop, noisy_zop],
coeffs=[0.5, -0.5],
)
for _ in range(5):
seqs, signs, norm = sample_sequence(circuit, representations=[rep])
assert isinstance(seqs[0], QuantumCircuit)
assert signs[0] in {1, -1}
assert norm == 1.0
def test_sample_sequence_pyquil():
circuit = Program(gates.H(0))
noisy_xop = NoisyOperation(Program(gates.X(0)))
noisy_zop = NoisyOperation(Program(gates.Z(0)))
rep = OperationRepresentation(
ideal=circuit,
noisy_operations=[noisy_xop, noisy_zop],
coeffs=[0.5, -0.5],
)
for _ in range(50):
seqs, signs, norm = sample_sequence(circuit, representations=[rep])
assert isinstance(seqs[0], Program)
assert signs[0] in {1, -1}
assert norm == 1.0
@pytest.mark.parametrize("seed", (1, 2, 3, 5))
def test_sample_sequence_cirq_random_state(seed):
circuit = Circuit(cirq.H.on(LineQubit(0)))
rep = OperationRepresentation(
ideal=circuit,
noisy_operations=[NoisyOperation(xcirq), NoisyOperation(zcirq)],
coeffs=[0.5, -0.5],
)
sequences, signs, norm = sample_sequence(
circuit, [rep], random_state=np.random.RandomState(seed)
)
for _ in range(20):
new_sequences, new_signs, new_norm = sample_sequence(
circuit, [rep], random_state=np.random.RandomState(seed)
)
assert _equal(new_sequences[0], sequences[0])
assert new_signs[0] == signs[0]
assert np.isclose(new_norm, norm)
def test_qubit_independent_representation_cirq():
"""Test that an OperationRepresentation defined for some qubits can
(optionally) be used to mitigate gates acting on different qubits."""
circuit = Circuit([cirq.I.on(LineQubit(0)), cirq.H.on(LineQubit(1))])
circuit.append(measure_each(*LineQubit.range(2)))
rep = OperationRepresentation(
ideal=Circuit(cirq.H.on(LineQubit(0))),
noisy_operations=[NoisyOperation(xcirq), NoisyOperation(zcirq)],
coeffs=[0.5, -0.5],
is_qubit_dependent=False,
)
expected_a = Circuit([cirq.I.on(LineQubit(0)), cirq.X.on(LineQubit(1))])
expected_a.append(measure_each(*LineQubit.range(2)))
expected_b = Circuit([cirq.I.on(LineQubit(0)), cirq.Z.on(LineQubit(1))])
expected_b.append(measure_each(*LineQubit.range(2)))
for _ in range(5):
seqs, signs, norm = sample_circuit(circuit, representations=[rep])
assert seqs[0] in [expected_a, expected_b]
assert signs[0] in {1, -1}
assert norm == 1.0
def test_qubit_independent_representation_qiskit():
"""Test that an OperationRepresentation defined for some qubits can
(optionally) be used to mitigate gates acting on different qubits."""
different_qreg = QuantumRegister(2, name="q")
circuit_to_mitigate = QuantumCircuit(different_qreg)
_ = circuit_to_mitigate.cx(*different_qreg)
qreg = QuantumRegister(2, name="rep_register")
xcircuit = QuantumCircuit(qreg)
_ = xcircuit.x(qreg)
zcircuit = QuantumCircuit(qreg)
_ = zcircuit.z(qreg)
noisy_xop = NoisyOperation(xcircuit)
noisy_zop = NoisyOperation(zcircuit)
ideal_op = QuantumCircuit(qreg)
_ = ideal_op.cx(*qreg)
rep = OperationRepresentation(
ideal=ideal_op,
noisy_operations=[noisy_xop, noisy_zop],
coeffs=[0.5, -0.5],
is_qubit_dependent=False,
)
# Expected outcomes
xcircuit_different = QuantumCircuit(different_qreg)
xcircuit_different.x(different_qreg)
zcircuit_different = QuantumCircuit(different_qreg)
zcircuit_different.z(different_qreg)
for _ in range(5):
seqs, signs, norm = sample_sequence(
circuit_to_mitigate, representations=[rep]
)
assert seqs[0] in [xcircuit_different, zcircuit_different]
assert signs[0] in {1, -1}
assert norm == 1.0
def test_qubit_independent_representation_pyquil():
"""Test that an OperationRepresentation defined for some qubits can
(optionally) be used to mitigate gates acting on different qubits."""
circuit_to_mitigate = Program(gates.H(1))
noisy_xop = NoisyOperation(Program(gates.X(0)))
noisy_zop = NoisyOperation(Program(gates.Z(0)))
rep = OperationRepresentation(
ideal=Program(gates.H(0)),
noisy_operations=[noisy_xop, noisy_zop],
coeffs=[0.5, -0.5],
is_qubit_dependent=False,
)
for _ in range(50):
seqs, signs, norm = sample_sequence(
circuit_to_mitigate, representations=[rep]
)
assert seqs[0] in [Program(gates.X(1)), Program(gates.Z(1))]
assert signs[0] in {1, -1}
assert norm == 1.0
@pytest.mark.parametrize(
"reps",
[
[],
[
OperationRepresentation(
Circuit(cirq.H.on(LineQubit(0))),
[NoisyOperation(xcirq), NoisyOperation(zcirq)],
[0.5, -0.5],
)
],
],
)
def test_sample_sequence_no_representation(reps):
circuit = Circuit(cirq.H.on(LineQubit(0)), cirq.H.on(LineQubit(1)))
circuit.append(measure_each(*LineQubit.range(2)))
with pytest.warns(UserWarning, match="No representation found for"):
sequences, signs, norm = sample_sequence(circuit, reps)
assert _equal(sequences[0], circuit, require_qubit_equality=True)
assert signs == [1]
assert norm == 1
@pytest.mark.parametrize("measure", [True, False])
def test_sample_circuit_cirq(measure):
circuit = Circuit(
ops.H.on(LineQubit(0)),
ops.CNOT.on(*LineQubit.range(2)),
)
if measure:
circuit.append(measure_each(*LineQubit.range(2)))
h_rep = OperationRepresentation(
circuit[:1],
[NoisyOperation(xcirq), NoisyOperation(zcirq)],
[0.6, -0.6],
)
cnot_rep = OperationRepresentation(
circuit[1:2],
[NoisyOperation(cnotcirq), NoisyOperation(czcirq)],
[0.7, -0.7],
)
for _ in range(50):
sampled_circuits, signs, norm = sample_circuit(
circuit, representations=[h_rep, cnot_rep]
)
assert isinstance(sampled_circuits[0], Circuit)
assert signs[0] in (-1, 1)
assert norm >= 1
if measure:
assert len(sampled_circuits[0]) == 3
assert cirq.is_measurement(
list(sampled_circuits[0].all_operations())[-1] # last gate
)
else:
assert len(sampled_circuits[0]) == 2
def test_sample_circuit_partial_representations():
circuit = Circuit(
ops.H.on(LineQubit(0)),
ops.CNOT.on(*LineQubit.range(2)),
)
cnot_rep = OperationRepresentation(
circuit[1:2],
[NoisyOperation(cnotcirq), NoisyOperation(czcirq)],
[0.7, -0.7],
)
for _ in range(10):
with pytest.warns(UserWarning, match="No representation found for"):
sampled_circuits, signs, norm = sample_circuit(
circuit, representations=[cnot_rep]
)
assert isinstance(sampled_circuits[0], Circuit)
assert len(sampled_circuits[0]) == 2
assert signs[0] in (-1, 1)
assert norm >= 1
def test_sample_circuit_pyquil():
circuit = Program(gates.H(0), gates.CNOT(0, 1))
h_rep = OperationRepresentation(
circuit[:1],
[
NoisyOperation(Program(gates.X(0))),
NoisyOperation(Program(gates.Z(0))),
],
[0.6, -0.6],
)
cnot_rep = OperationRepresentation(
circuit[1:],
[
NoisyOperation(Program(gates.CNOT(0, 1))),
NoisyOperation(Program(gates.CZ(0, 1))),
],
[0.7, -0.7],
)
for _ in range(50):
sampled_circuits, signs, norm = sample_circuit(
circuit, representations=[h_rep, cnot_rep]
)
assert isinstance(sampled_circuits[0], Program)
assert len(sampled_circuits[0]) == 2
assert signs[0] in (-1, 1)
assert norm >= 1
def test_sample_circuit_with_seed():
circ = Circuit([cirq.X.on(LineQubit(0)) for _ in range(10)])
rep = OperationRepresentation(
ideal=Circuit(cirq.X.on(LineQubit(0))),
noisy_operations=[NoisyOperation(zcirq), NoisyOperation(xcirq)],
coeffs=[1.0, -1.0],
)
expected_circuits, expected_signs, expected_norm = sample_circuit(
circ, [rep], random_state=4
)
# Check we're not sampling the same operation every call to sample_sequence
assert len(set(expected_circuits[0].all_operations())) > 1
for _ in range(10):
sampled_circuits, sampled_signs, sampled_norm = sample_circuit(
circ, [rep], random_state=4
)
assert _equal(sampled_circuits[0], expected_circuits[0])
assert sampled_signs[0] == expected_signs[0]
assert sampled_norm == expected_norm
def test_sample_circuit_trivial_decomposition():
circuit = Circuit(ops.H.on(NamedQubit("Q")))
rep = OperationRepresentation(
ideal=circuit,
noisy_operations=[NoisyOperation(circuit)],
coeffs=[1.0],
)
sampled_circuits, signs, norm = sample_circuit(
circuit, [rep], random_state=1
)
assert _equal(sampled_circuits[0], circuit)
assert signs[0] == 1
assert np.isclose(norm, 1)
BASE_NOISE = 0.02
qreg = LineQubit.range(2)
@pytest.mark.parametrize("gate", [cirq.Y, cirq.CNOT])
def test_sample_sequence_choi(gate: Gate):
"""Tests the sample_sequence by comparing the exact Choi matrices."""
qreg = LineQubit.range(gate.num_qubits())
ideal_op = gate.on(*qreg)
ideal_circ = Circuit(ideal_op)
noisy_op_tree = [ideal_op] + [depolarize(BASE_NOISE)(q) for q in qreg]
ideal_choi = _operation_to_choi(ideal_op)
noisy_choi = _operation_to_choi(noisy_op_tree)
representation = represent_operation_with_local_depolarizing_noise(
ideal_circ,
BASE_NOISE,
)
choi_unbiased_estimates = []
rng = np.random.RandomState(1)
for _ in range(500):
imp_seqs, signs, norm = sample_sequence(
ideal_circ, [representation], random_state=rng
)
noisy_sequence = imp_seqs[0].with_noise(depolarize(BASE_NOISE))
sequence_choi = _circuit_to_choi(noisy_sequence)
choi_unbiased_estimates.append(norm * signs[0] * sequence_choi)
choi_pec_estimate = np.average(choi_unbiased_estimates, axis=0)
noise_error = np.linalg.norm(ideal_choi - noisy_choi)
pec_error = np.linalg.norm(ideal_choi - choi_pec_estimate)
assert pec_error < noise_error
assert np.allclose(ideal_choi, choi_pec_estimate, atol=0.05)
def test_sample_circuit_choi():
"""Tests the sample_circuit by comparing the exact Choi matrices."""
# A simple 2-qubit circuit
qreg = LineQubit.range(2)
ideal_circ = Circuit(
cirq.X.on(qreg[0]),
cirq.I.on(qreg[1]),
cirq.CNOT.on(*qreg),
)
noisy_circuit = ideal_circ.with_noise(depolarize(BASE_NOISE))
ideal_choi = _circuit_to_choi(ideal_circ)
noisy_choi = _operation_to_choi(noisy_circuit)
rep_list = represent_operations_in_circuit_with_local_depolarizing_noise(
ideal_circuit=ideal_circ,
noise_level=BASE_NOISE,
)
choi_unbiased_estimates = []
rng = np.random.RandomState(1)
for _ in range(500):
imp_circs, signs, norm = sample_circuit(
ideal_circ, rep_list, random_state=rng
)
noisy_imp_circ = imp_circs[0].with_noise(depolarize(BASE_NOISE))
sequence_choi = _circuit_to_choi(noisy_imp_circ)
choi_unbiased_estimates.append(norm * signs[0] * sequence_choi)
choi_pec_estimate = np.average(choi_unbiased_estimates, axis=0)
noise_error = np.linalg.norm(ideal_choi - noisy_choi)
pec_error = np.linalg.norm(ideal_choi - choi_pec_estimate)
assert pec_error < noise_error
assert np.allclose(ideal_choi, choi_pec_estimate, atol=0.05)
def test_conversions_in_sample_circuit():
"""Tests sample_circuit preserves idle qubits and quantum registers."""
qreg = QuantumRegister(3, name="Q")
creg = ClassicalRegister(2, name="C")
circuit = QuantumCircuit(qreg, creg)
circuit.h(qreg[0])
circuit.cx(qreg[0], qreg[1])
circuit.measure(0, 0)
cnot_circuit = QuantumCircuit(qreg)
cnot_circuit.cx(qreg[0], qreg[1])
rep = represent_operation_with_global_depolarizing_noise(
cnot_circuit,
noise_level=0.0,
)
out_circuits, signs, norm = sample_circuit(circuit, [rep], num_samples=3)
for out_circ in out_circuits:
out_circ == circuit
assert len(signs) == 3
assert set(signs).issubset({1.0, -1.0})
assert np.isclose(norm, 1.0)
|
https://github.com/unitaryfund/mitiq
|
unitaryfund
|
# Copyright (C) Unitary Fund
#
# This source code is licensed under the GPL license (v3) found in the
# LICENSE file in the root directory of this source tree.
import cirq
import numpy as np
import pyquil
import pytest
import qiskit
from cirq import Circuit
from mitiq.pec.types import NoisyBasis, NoisyOperation, OperationRepresentation
from mitiq.utils import _equal
icirq = Circuit(cirq.I(cirq.LineQubit(0)))
xcirq = Circuit(cirq.X(cirq.LineQubit(0)))
ycirq = Circuit(cirq.Y(cirq.LineQubit(0)))
zcirq = Circuit(cirq.Z(cirq.LineQubit(0)))
hcirq = Circuit(cirq.H(cirq.LineQubit(0)))
cnotcirq = Circuit(cirq.CNOT(cirq.LineQubit(0), cirq.LineQubit(1)))
def test_init_with_cirq_circuit():
real = np.zeros(shape=(4, 4))
noisy_op = NoisyOperation(zcirq, real)
assert isinstance(noisy_op._circuit, cirq.Circuit)
assert noisy_op.qubits == (cirq.LineQubit(0),)
assert np.allclose(noisy_op.channel_matrix, real)
assert noisy_op.channel_matrix is not real
assert noisy_op._native_type == "cirq"
assert _equal(zcirq, noisy_op.circuit)
assert _equal(noisy_op._native_circuit, noisy_op.circuit)
@pytest.mark.parametrize(
"qubit",
(cirq.LineQubit(0), cirq.GridQubit(1, 2), cirq.NamedQubit("Qubit")),
)
def test_init_with_different_qubits(qubit):
ideal_op = Circuit(cirq.H.on(qubit))
real = np.zeros(shape=(4, 4))
noisy_op = NoisyOperation(ideal_op, real)
assert isinstance(noisy_op._circuit, cirq.Circuit)
assert _equal(
noisy_op.circuit,
cirq.Circuit(ideal_op),
require_qubit_equality=True,
)
assert noisy_op.qubits == (qubit,)
assert np.allclose(noisy_op.channel_matrix, real)
assert noisy_op.channel_matrix is not real
assert noisy_op._native_type == "cirq"
assert _equal(cirq.Circuit(ideal_op), noisy_op.circuit)
assert _equal(noisy_op._native_circuit, noisy_op.circuit)
def test_init_with_cirq_input():
qreg = cirq.LineQubit.range(2)
circ = cirq.Circuit(cirq.H.on(qreg[0]), cirq.CNOT.on(*qreg))
real = np.zeros(shape=(16, 16))
noisy_op = NoisyOperation(circ, real)
assert isinstance(noisy_op._circuit, cirq.Circuit)
assert _equal(noisy_op.circuit, circ, require_qubit_equality=True)
assert set(noisy_op.qubits) == set(qreg)
assert np.allclose(noisy_op.channel_matrix, real)
assert noisy_op.channel_matrix is not real
def test_init_with_qiskit_circuit():
qreg = qiskit.QuantumRegister(2)
circ = qiskit.QuantumCircuit(qreg)
_ = circ.h(qreg[0])
_ = circ.cx(*qreg)
cirq_qreg = cirq.LineQubit.range(2)
cirq_circ = cirq.Circuit(cirq.H.on(cirq_qreg[0]), cirq.CNOT.on(*cirq_qreg))
real = np.zeros(shape=(16, 16))
noisy_op = NoisyOperation(circ, real)
assert isinstance(noisy_op._circuit, cirq.Circuit)
assert _equal(noisy_op._circuit, cirq_circ)
assert _equal(noisy_op.circuit, cirq_circ)
assert noisy_op.native_circuit == circ
assert noisy_op._native_circuit == circ
assert noisy_op._native_type == "qiskit"
assert np.allclose(noisy_op.channel_matrix, real)
assert noisy_op.channel_matrix is not real
@pytest.mark.parametrize(
"gate",
(
cirq.H,
cirq.H(cirq.LineQubit(0)),
qiskit.circuit.library.HGate,
qiskit.circuit.library.CHGate,
pyquil.gates.H,
),
)
def test_init_with_gates_raises_error(gate):
rng = np.random.RandomState(seed=1)
with pytest.raises(TypeError, match="Failed to convert to an internal"):
NoisyOperation(circuit=gate, channel_matrix=rng.rand(4, 4))
def test_init_with_pyquil_program():
circ = pyquil.Program(pyquil.gates.H(0), pyquil.gates.CNOT(0, 1))
cirq_qreg = cirq.LineQubit.range(2)
cirq_circ = cirq.Circuit(cirq.H.on(cirq_qreg[0]), cirq.CNOT.on(*cirq_qreg))
real = np.zeros(shape=(16, 16))
noisy_op = NoisyOperation(circ, real)
assert isinstance(noisy_op._circuit, cirq.Circuit)
assert _equal(noisy_op._circuit, cirq_circ)
assert _equal(noisy_op.circuit, cirq_circ)
assert noisy_op.native_circuit == circ
assert noisy_op._native_circuit == circ
assert noisy_op._native_type == "pyquil"
assert np.allclose(noisy_op.channel_matrix, real)
assert noisy_op.channel_matrix is not real
def test_init_dimension_mismatch_error():
ideal = cirq.Circuit(cirq.H.on(cirq.LineQubit(0)))
real = np.zeros(shape=(3, 3))
with pytest.raises(ValueError, match="has shape"):
NoisyOperation(ideal, real)
def test_unknown_channel_matrix():
qreg = qiskit.QuantumRegister(2)
circ = qiskit.QuantumCircuit(qreg)
_ = circ.h(qreg[0])
_ = circ.cx(*qreg)
cirq_qreg = cirq.LineQubit.range(2)
cirq_circ = cirq.Circuit(cirq.H.on(cirq_qreg[0]), cirq.CNOT.on(*cirq_qreg))
noisy_op = NoisyOperation(circ)
assert isinstance(noisy_op._circuit, cirq.Circuit)
assert _equal(noisy_op._circuit, cirq_circ)
assert _equal(noisy_op.circuit, cirq_circ)
assert noisy_op.native_circuit == circ
assert noisy_op._native_circuit == circ
assert noisy_op._native_type == "qiskit"
with pytest.raises(ValueError, match="The channel matrix is unknown."):
_ = noisy_op.channel_matrix
def test_add_simple():
circuit1 = cirq.Circuit([cirq.X.on(cirq.NamedQubit("Q"))])
circuit2 = cirq.Circuit([cirq.Y.on(cirq.NamedQubit("Q"))])
super_op1 = np.random.rand(4, 4)
super_op2 = np.random.rand(4, 4)
noisy_op1 = NoisyOperation(circuit1, super_op1)
noisy_op2 = NoisyOperation(circuit2, super_op2)
noisy_op = noisy_op1 + noisy_op2
correct = cirq.Circuit(
[cirq.X.on(cirq.NamedQubit("Q")), cirq.Y.on(cirq.NamedQubit("Q"))],
)
assert _equal(noisy_op._circuit, correct, require_qubit_equality=True)
assert np.allclose(noisy_op.channel_matrix, super_op2 @ super_op1)
def test_add_pyquil_noisy_operations():
ideal = pyquil.Program(pyquil.gates.X(0))
real = np.random.rand(4, 4)
noisy_op1 = NoisyOperation(ideal, real)
noisy_op2 = NoisyOperation(ideal, real)
noisy_op = noisy_op1 + noisy_op2
correct = cirq.Circuit([cirq.X.on(cirq.NamedQubit("Q"))] * 2)
assert _equal(noisy_op._circuit, correct, require_qubit_equality=False)
assert np.allclose(noisy_op.channel_matrix, real @ real)
def test_add_qiskit_noisy_operations():
qreg = qiskit.QuantumRegister(1)
ideal = qiskit.QuantumCircuit(qreg)
_ = ideal.x(qreg)
real = np.random.rand(4, 4)
noisy_op1 = NoisyOperation(ideal, real)
noisy_op2 = NoisyOperation(ideal, real)
noisy_op = noisy_op1 + noisy_op2
correct = cirq.Circuit([cirq.X.on(cirq.NamedQubit("Q"))] * 2)
assert _equal(noisy_op._circuit, correct, require_qubit_equality=False)
assert np.allclose(noisy_op.channel_matrix, real @ real)
def test_add_bad_type():
ideal = cirq.Circuit([cirq.X.on(cirq.NamedQubit("Q"))])
real = np.random.rand(4, 4)
noisy_op = NoisyOperation(ideal, real)
with pytest.raises(ValueError, match="must be a NoisyOperation"):
noisy_op + ideal
def test_add_noisy_operation_no_channel_matrix():
noisy_op1 = NoisyOperation(cirq.Circuit([cirq.X.on(cirq.NamedQubit("Q"))]))
noisy_op2 = NoisyOperation(
cirq.Circuit([cirq.X.on(cirq.NamedQubit("Q"))]),
channel_matrix=np.random.rand(4, 4),
)
with pytest.raises(ValueError):
(noisy_op1 + noisy_op2).channel_matrix
def test_noisy_operation_str():
noisy_op = NoisyOperation(circuit=icirq, channel_matrix=np.identity(4))
assert isinstance(noisy_op.__str__(), str)
def test_noisy_basis_deprecation_error():
with pytest.raises(NotImplementedError, match="NoisyBasis"):
NoisyBasis()
with pytest.raises(NotImplementedError, match="NoisyBasis"):
NoisyBasis(zcirq, xcirq)
def get_test_representation():
ideal = cirq.Circuit(cirq.H(cirq.LineQubit(0)))
noisy_xop = NoisyOperation(
circuit=xcirq, channel_matrix=np.zeros(shape=(4, 4))
)
noisy_zop = NoisyOperation(
circuit=zcirq, channel_matrix=np.zeros(shape=(4, 4))
)
decomp = OperationRepresentation(
ideal,
[noisy_xop, noisy_zop],
[0.5, -0.5],
)
return ideal, noisy_xop, noisy_zop, decomp
def test_representation_simple():
ideal, noisy_xop, noisy_zop, decomp = get_test_representation()
assert _equal(decomp.ideal, ideal)
assert decomp.coeffs == [0.5, -0.5]
assert np.allclose(decomp.distribution, np.array([0.5, 0.5]))
assert np.isclose(decomp.norm, 1.0)
assert isinstance(decomp.basis_expansion[0][0], float)
assert set(decomp.noisy_operations) == {noisy_xop, noisy_zop}
def test_representation_bad_type():
ideal = cirq.Circuit(cirq.H(cirq.LineQubit(0)))
noisy_xop = NoisyOperation(
circuit=xcirq, channel_matrix=np.zeros(shape=(4, 4))
)
with pytest.raises(TypeError, match="All elements of `noisy_operations`"):
OperationRepresentation(
ideal=ideal,
noisy_operations=[0.1],
coeffs=[0.1],
)
with pytest.raises(TypeError, match="All elements of `coeffs` must"):
OperationRepresentation(
ideal=ideal,
noisy_operations=[noisy_xop],
coeffs=["x"],
)
def test_representation_sample():
_, noisy_xop, noisy_zop, decomp = get_test_representation()
for _ in range(10):
noisy_op, sign, coeff = decomp.sample()
assert sign in (-1, 1)
assert coeff in (-0.5, 0.5)
assert noisy_op in (noisy_xop, noisy_zop)
case_one = noisy_op == noisy_xop and coeff == 0.5
case_two = noisy_op == noisy_zop and coeff == -0.5
assert case_one or case_two
def test_representation_sample_seed():
_, noisy_xop, noisy_zop, decomp = get_test_representation()
seed1 = np.random.RandomState(seed=1)
seed2 = np.random.RandomState(seed=1)
for _ in range(10):
_, sign1, coeff1 = decomp.sample(random_state=seed1)
_, sign2, coeff2 = decomp.sample(random_state=seed2)
assert sign1 == sign2
assert np.isclose(coeff1, coeff2)
def test_representation_sample_bad_seed_type():
_, _, _, decomp = get_test_representation()
with pytest.raises(TypeError, match="should be of type"):
decomp.sample(random_state="8")
def test_representation_sample_zero_coefficient():
ideal = cirq.Circuit(cirq.H(cirq.LineQubit(0)))
noisy_xop = NoisyOperation(
circuit=xcirq, channel_matrix=np.zeros(shape=(4, 4))
)
noisy_zop = NoisyOperation(
circuit=zcirq, channel_matrix=np.zeros(shape=(4, 4))
)
decomp = OperationRepresentation(
ideal=ideal,
noisy_operations=[noisy_xop, noisy_zop],
coeffs=[0.5, 0.0], # 0 term should never be sampled.
)
random_state = np.random.RandomState(seed=1)
for _ in range(500):
noisy_op, sign, coeff = decomp.sample(random_state=random_state)
assert sign == 1
assert coeff == 0.5
assert np.allclose(
cirq.unitary(noisy_op.circuit),
cirq.unitary(cirq.X),
)
def test_print_cirq_operation_representation():
ideal = cirq.Circuit(cirq.H(cirq.LineQubit(0)))
noisy_xop = NoisyOperation(
circuit=xcirq, channel_matrix=np.zeros(shape=(4, 4))
)
noisy_zop = NoisyOperation(
circuit=zcirq, channel_matrix=np.zeros(shape=(4, 4))
)
# Positive first coefficient
decomp = OperationRepresentation(
ideal=ideal,
noisy_operations=[noisy_xop, noisy_zop],
coeffs=[0.5, 0.5],
)
expected = r"0: ───H─── = 0.500*(0: ───X───)+0.500*(0: ───Z───)"
assert str(decomp) == expected
# Negative first coefficient
decomp = OperationRepresentation(
ideal=ideal,
noisy_operations=[noisy_xop, noisy_zop],
coeffs=[-0.5, 1.5],
)
expected = r"0: ───H─── = -0.500*(0: ───X───)+1.500*(0: ───Z───)"
assert str(decomp) == expected
# Empty representation
decomp = OperationRepresentation(ideal, [], [])
expected = r"0: ───H─── = 0.000"
assert str(decomp) == expected
# Small coefficient approximation
decomp = OperationRepresentation(
ideal=ideal,
noisy_operations=[noisy_xop, noisy_zop],
coeffs=[1.00001, 0.00001],
)
expected = r"0: ───H─── = 1.000*(0: ───X───)"
assert str(decomp) == expected
# Small coefficient approximation different position
decomp = OperationRepresentation(
ideal=ideal,
noisy_operations=[noisy_xop, noisy_zop],
coeffs=[0.00001, 1.00001],
)
expected = r"0: ───H─── = 1.000*(0: ───Z───)"
# Small coefficient approximation different position
decomp = OperationRepresentation(
ideal=ideal,
noisy_operations=[noisy_xop],
coeffs=[0.00001],
)
expected = r"0: ───H─── = 0.000"
assert str(decomp) == expected
def test_print_operation_representation_two_qubits():
qreg = cirq.LineQubit.range(2)
ideal = cirq.Circuit(cirq.CNOT(*qreg))
noisy_a = NoisyOperation(
circuit=cirq.Circuit(
cirq.H.on_each(qreg), cirq.CNOT(*qreg), cirq.H.on_each(qreg)
)
)
noisy_b = NoisyOperation(
circuit=cirq.Circuit(
cirq.Z.on_each(qreg),
cirq.CNOT(*qreg),
cirq.Z.on_each(qreg),
)
)
decomp = OperationRepresentation(
ideal=ideal,
noisy_operations=[noisy_a, noisy_b],
coeffs=[0.5, 0.5],
)
expected = f"""
0: ───@───
│
1: ───X─── ={" "}
0.500
0: ───H───@───H───
│
1: ───H───X───H───
+0.500
0: ───Z───@───Z───
│
1: ───Z───X───Z───"""
# Remove initial newline
expected = expected[1:]
assert str(decomp) == expected
def test_print_operation_representation_two_qubits_neg():
qreg = cirq.LineQubit.range(2)
ideal = cirq.Circuit(cirq.CNOT(*qreg))
noisy_a = NoisyOperation(
circuit=cirq.Circuit(
cirq.H.on_each(qreg[0]), cirq.CNOT(*qreg), cirq.H.on_each(qreg[1])
)
)
noisy_b = NoisyOperation(circuit=cirq.Circuit(cirq.Z.on_each(*qreg)))
decomp = OperationRepresentation(
ideal=ideal,
noisy_operations=[noisy_a, noisy_b],
coeffs=[-0.5, 1.5],
)
expected = f"""
0: ───@───
│
1: ───X─── ={" "}
-0.500
0: ───H───@───────
│
1: ───────X───H───
+1.500
0: ───Z───
1: ───Z───"""
# Remove initial newline
expected = expected[1:]
assert str(decomp) == expected
def test_equal_method_of_representations():
q = cirq.LineQubit(0)
ideal = cirq.Circuit(cirq.H(q))
noisy_xop_a = NoisyOperation(
circuit=cirq.Circuit(cirq.X(q)),
channel_matrix=np.zeros(shape=(4, 4)),
)
noisy_zop_a = NoisyOperation(
circuit=cirq.Circuit(cirq.Z(q)),
channel_matrix=np.zeros(shape=(4, 4)),
)
rep_a = OperationRepresentation(
ideal=ideal,
noisy_operations=[noisy_xop_a, noisy_zop_a],
coeffs=[0.5, 0.5],
)
noisy_xop_b = NoisyOperation(
circuit=cirq.Circuit(cirq.X(q)),
channel_matrix=np.ones(shape=(4, 4)),
)
noisy_zop_b = NoisyOperation(
circuit=cirq.Circuit(cirq.Z(q)),
channel_matrix=np.ones(shape=(4, 4)),
)
rep_b = OperationRepresentation(
ideal=ideal,
noisy_operations=[noisy_xop_b, noisy_zop_b],
coeffs=[0.5, 0.5],
)
# Equal representation up to real superoperators
assert rep_a == rep_b
# Different ideal
ideal_b = cirq.Circuit(cirq.X(q))
rep_b = OperationRepresentation(
ideal=ideal_b,
noisy_operations=[noisy_xop_b, noisy_zop_b],
coeffs=[0.5, 0.5],
)
assert rep_a != rep_b
# Different type
q_b = qiskit.QuantumRegister(1)
ideal_b = qiskit.QuantumCircuit(q_b)
ideal_b.x(q_b)
noisy_opx = NoisyOperation(ideal_b)
rep_b = OperationRepresentation(
ideal=ideal_b,
noisy_operations=[noisy_opx, noisy_opx],
coeffs=[0.5, 0.5],
)
assert rep_a != rep_b
# Different length
rep_b = OperationRepresentation(
ideal=ideal,
noisy_operations=[noisy_xop_b],
coeffs=[0.5],
)
assert rep_a != rep_b
# Different operations
noisy_diff = NoisyOperation(circuit=cirq.Circuit(cirq.H(q)))
rep_b = OperationRepresentation(
ideal=ideal,
noisy_operations=[noisy_xop_b, noisy_diff],
coeffs=[0.5, 0.5],
)
assert rep_a != rep_b
# Different coefficients
rep_b = OperationRepresentation(
ideal=ideal,
noisy_operations=[noisy_xop_b, noisy_zop_b],
coeffs=[0.7, 0.5],
)
assert rep_a != rep_b
# Different value of is_qubit_dependent
rep_b = OperationRepresentation(
ideal=ideal,
noisy_operations=[noisy_xop_a, noisy_zop_a],
coeffs=[0.5, 0.5],
is_qubit_dependent=False,
)
assert rep_a != rep_b
def test_operation_representation_warnings():
with pytest.warns(UserWarning, match="different from 1"):
OperationRepresentation(
ideal=xcirq,
noisy_operations=[NoisyOperation(xcirq), NoisyOperation(zcirq)],
coeffs=[0.5, 0.1],
)
def test_different_qubits_error():
"""Ideal operation and noisy operations must have equal qubits."""
with pytest.raises(ValueError, match="must act on the same qubits"):
OperationRepresentation(
ideal=cirq.Circuit(cirq.X(cirq.NamedQubit("a"))),
noisy_operations=[NoisyOperation(xcirq), NoisyOperation(zcirq)],
coeffs=[0.5, 0.5],
)
def test_different_length_error():
"""The number of coefficients must be equal to the number of noisy
operations.
"""
with pytest.raises(ValueError, match="must have equal length"):
OperationRepresentation(
ideal=cirq.Circuit(cirq.X(cirq.LineQubit(0))),
noisy_operations=[NoisyOperation(xcirq), NoisyOperation(zcirq)],
coeffs=[0.5, 0.5, 0.4],
)
|
https://github.com/unitaryfund/mitiq
|
unitaryfund
|
# Copyright (C) Unitary Fund
#
# This source code is licensed under the GPL license (v3) found in the
# LICENSE file in the root directory of this source tree.
import random
import cirq
import networkx as nx
import numpy as np
import pennylane as qml
import pytest
import qiskit
from pennylane.tape import QuantumTape
from mitiq.benchmarks import generate_mirror_circuit
from mitiq.interface.mitiq_cirq import compute_density_matrix
from mitiq.pt.pt import (
CIRQ_NOISE_OP,
PENNYLANE_NOISE_OP,
CNOT_twirling_gates,
CZ_twirling_gates,
pauli_twirl_circuit,
twirl_CNOT_gates,
twirl_CZ_gates,
)
from mitiq.utils import _equal
num_qubits = 2
qubits = cirq.LineQubit.range(num_qubits)
circuit = cirq.Circuit()
circuit.append(cirq.CNOT(*qubits))
circuit.append(cirq.CZ(*qubits))
def amp_damp_executor(circuit: cirq.Circuit, noise: float = 0.005) -> float:
return compute_density_matrix(
circuit, noise_model_function=cirq.amplitude_damp, noise_level=(noise,)
)[0, 0].real
def test_twirl_CNOT_implements_same_unitary():
num_circuits = 1
twirled = twirl_CNOT_gates(circuit, num_circuits=num_circuits)
assert len(twirled) == num_circuits
original_unitary = cirq.unitary(circuit)
twirled_unitary = cirq.unitary(twirled[0])
assert np.array_equal(twirled_unitary, original_unitary) or np.array_equal(
-1 * twirled_unitary, original_unitary
)
def test_twirl_CZ_implements_same_unitary():
num_circuits = 1
twirled = twirl_CZ_gates(circuit, num_circuits=num_circuits)
assert len(twirled) == num_circuits
original_unitary = cirq.unitary(circuit)
twirled_unitary = cirq.unitary(twirled[0])
assert np.array_equal(twirled_unitary, original_unitary) or np.array_equal(
-1 * twirled_unitary, original_unitary
)
def test_CNOT_twirl_table():
a, b = cirq.LineQubit.range(2)
for P, Q, R, S in CNOT_twirling_gates:
circuit = cirq.Circuit(
P.on(a),
Q.on(b),
cirq.CNOT.on(a, b),
R.on(a),
S.on(b),
cirq.CNOT.on(a, b),
)
assert np.allclose(cirq.unitary(circuit), np.eye(4)) or np.allclose(
-1 * cirq.unitary(circuit), np.eye(4)
)
def test_CZ_twirl_table():
a, b = cirq.LineQubit.range(2)
for P, Q, R, S in CZ_twirling_gates:
circuit = cirq.Circuit(
P.on(a),
Q.on(b),
cirq.CZ.on(a, b),
R.on(a),
S.on(b),
cirq.CZ.on(a, b),
)
assert np.allclose(cirq.unitary(circuit), np.eye(4)) or np.allclose(
-1 * cirq.unitary(circuit), np.eye(4)
)
def test_twirl_CNOT_qiskit():
qc = qiskit.QuantumCircuit(2, 2)
qc.h(0)
qc.cx(0, 1)
qc.measure([0, 1], [0, 1])
num_circuits = 10
twirled = twirl_CNOT_gates(qc, num_circuits=num_circuits)
assert len(twirled) == num_circuits
random_index = random.randint(0, 9)
assert isinstance(twirled[random_index], qiskit.QuantumCircuit)
def test_twirl_CNOT_increases_layer_count():
num_qubits = 3
num_layers = 10
gateset = {cirq.X: 1, cirq.Y: 1, cirq.Z: 1, cirq.H: 1, cirq.CNOT: 2}
circuit = cirq.testing.random_circuit(
num_qubits, num_layers, op_density=0.8, gate_domain=gateset
)
num_CNOTS = sum([op.gate == cirq.CNOT for op in circuit.all_operations()])
twirled = twirl_CNOT_gates(circuit, num_circuits=1)[0]
num_gates_before = len(list(circuit.all_operations()))
num_gates_after = len(list(twirled.all_operations()))
if num_CNOTS:
assert num_gates_after > num_gates_before
else:
assert num_gates_after == num_gates_before
def test_pauli_twirl_circuit():
num_qubits = 3
num_layers = 20
circuit, _ = generate_mirror_circuit(
nlayers=num_layers,
two_qubit_gate_prob=1.0,
connectivity_graph=nx.complete_graph(num_qubits),
)
num_circuits = 10
twirled_output = pauli_twirl_circuit(circuit, num_circuits)
assert len(twirled_output) == num_circuits
@pytest.mark.parametrize(
"twirl_func", [pauli_twirl_circuit, twirl_CNOT_gates, twirl_CZ_gates]
)
def test_no_CNOT_CZ_circuit(twirl_func):
num_qubits = 2
qubits = cirq.LineQubit.range(num_qubits)
circuit = cirq.Circuit()
circuit.append(cirq.X.on_each(qubits))
twirled_output = twirl_func(circuit, 5)
assert len(twirled_output) == 5
for i in range(5):
assert _equal(circuit, twirled_output[i])
@pytest.mark.parametrize("noise_name", ["bit-flip", "depolarize"])
def test_noisy_cirq(noise_name):
p = 0.01
a, b = cirq.LineQubit.range(2)
circuit = cirq.Circuit(cirq.H.on(a), cirq.CNOT.on(a, b), cirq.CZ.on(a, b))
twirled_circuit = pauli_twirl_circuit(
circuit, num_circuits=1, noise_name=noise_name, p=p
)[0]
for i, current_moment in enumerate(twirled_circuit):
for op in current_moment:
if op.gate in [cirq.CNOT, cirq.CZ]:
for next_op in twirled_circuit[i + 1]:
assert next_op.gate == CIRQ_NOISE_OP[noise_name](p=p)
@pytest.mark.parametrize("noise_name", ["bit-flip", "depolarize"])
def test_noisy_pennylane(noise_name):
p = 0.01
ops = [
qml.Hadamard(0),
qml.CNOT((0, 1)),
qml.CZ((0, 1)),
]
circuit = QuantumTape(ops)
twirled_circuit = pauli_twirl_circuit(
circuit, num_circuits=1, noise_name=noise_name, p=p
)[0]
noisy_gates = ["CNOT", "CZ"]
for i, op in enumerate(twirled_circuit.operations):
if op.name in noisy_gates:
for j in range(1, len(op.wires) + 1):
assert (
type(twirled_circuit.operations[i + j])
== PENNYLANE_NOISE_OP[noise_name]
)
|
https://github.com/unitaryfund/mitiq
|
unitaryfund
|
# Copyright (C) Unitary Fund
#
# This source code is licensed under the GPL license (v3) found in the
# LICENSE file in the root directory of this source tree.
"""Tests for circuit conversions."""
from typing import List
import cirq
import numpy as np
import pennylane as qml
import pytest
import qibo
import qiskit
from braket.circuits import Circuit as BKCircuit
from braket.circuits import Instruction
from braket.circuits import gates as braket_gates
from pyquil import Program, gates
from mitiq import SUPPORTED_PROGRAM_TYPES
from mitiq.interface import (
UnsupportedCircuitError,
accept_any_qprogram_as_input,
accept_qprogram_and_validate,
atomic_one_to_many_converter,
convert_from_mitiq,
convert_to_mitiq,
register_mitiq_converters,
)
from mitiq.interface.mitiq_qiskit import from_qasm, to_qasm
from mitiq.utils import _equal
QASMType = str
# Cirq Bell circuit.
cirq_qreg = cirq.LineQubit.range(2)
cirq_circuit = cirq.Circuit(
cirq.ops.H.on(cirq_qreg[0]), cirq.ops.CNOT.on(*cirq_qreg)
)
# Qiskit Bell circuit.
qiskit_qreg = qiskit.QuantumRegister(2)
qiskit_circuit = qiskit.QuantumCircuit(qiskit_qreg)
qiskit_circuit.h(qiskit_qreg[0])
qiskit_circuit.cx(*qiskit_qreg)
qasm_str = qiskit.qasm2.dumps(qiskit_circuit)
# pyQuil Bell circuit.
pyquil_circuit = Program(gates.H(0), gates.CNOT(0, 1))
# Braket Bell circuit.
braket_circuit = BKCircuit(
[
Instruction(braket_gates.H(), 0),
Instruction(braket_gates.CNot(), [0, 1]),
]
)
circuit_types = {
"cirq": cirq.Circuit,
"qiskit": qiskit.QuantumCircuit,
"pyquil": Program,
"braket": BKCircuit,
"pennylane": qml.tape.QuantumTape,
"qibo": qibo.models.circuit.Circuit,
}
@accept_qprogram_and_validate
def scaling_function(circ: cirq.Circuit, *args, **kwargs) -> cirq.Circuit:
return circ
def one_to_many_circuit_modifier(
circ: cirq.Circuit, *args, **kwargs
) -> List[cirq.Circuit]:
return [circ, circ[0:1] + circ]
# Apply one-to-many decorator
one_to_many_circuit_modifier = accept_qprogram_and_validate(
one_to_many_circuit_modifier,
one_to_many=True,
)
@accept_any_qprogram_as_input
def get_wavefunction(circ: cirq.Circuit) -> np.ndarray:
return circ.final_state_vector()
@atomic_one_to_many_converter
def returns_several_circuits(circ: cirq.Circuit, *args, **kwargs):
return [circ] * 5
@pytest.mark.parametrize(
"circuit", (qiskit_circuit, pyquil_circuit, braket_circuit)
)
def test_to_mitiq(circuit):
converted_circuit, input_type = convert_to_mitiq(circuit)
assert _equal(converted_circuit, cirq_circuit)
assert input_type in circuit.__module__
def test_register_from_to_mitiq():
class CircuitStr(str):
__module__ = "qasm"
qasm_circuit = CircuitStr(qasm_str)
register_mitiq_converters(
qasm_circuit.__module__,
convert_to_function=to_qasm,
convert_from_function=from_qasm,
)
converted_circuit = convert_from_mitiq(cirq_circuit, "qasm")
converted_qasm = CircuitStr(converted_circuit)
circuit, input_type = convert_to_mitiq(converted_qasm)
assert _equal(circuit, cirq_circuit)
assert input_type == qasm_circuit.__module__
@pytest.mark.parametrize("item", ("circuit", 1, None))
def test_to_mitiq_bad_types(item):
with pytest.raises(
UnsupportedCircuitError,
match="Could not determine the package of the input circuit.",
):
convert_to_mitiq(item)
@pytest.mark.parametrize("to_type", SUPPORTED_PROGRAM_TYPES.keys())
def test_from_mitiq(to_type):
converted_circuit = convert_from_mitiq(cirq_circuit, to_type)
circuit, input_type = convert_to_mitiq(converted_circuit)
assert _equal(circuit, cirq_circuit)
assert input_type == to_type
def test_unsupported_circuit_error():
class CircuitStr(str):
__module__ = "qasm"
mock_circuit = CircuitStr("mock")
with pytest.raises(
UnsupportedCircuitError,
match="Conversion to circuit type unsupported_circuit_type",
):
convert_from_mitiq(mock_circuit, "unsupported_circuit_type")
@pytest.mark.parametrize(
"circuit_and_expected",
[
(cirq.Circuit(cirq.X.on(cirq.LineQubit(0))), np.array([0, 1])),
(cirq_circuit, np.array([1, 0, 0, 1]) / np.sqrt(2)),
],
)
@pytest.mark.parametrize("to_type", SUPPORTED_PROGRAM_TYPES.keys())
def test_accept_any_qprogram_as_input(circuit_and_expected, to_type):
circuit, expected = circuit_and_expected
wavefunction = get_wavefunction(convert_from_mitiq(circuit, to_type))
assert np.allclose(wavefunction, expected)
@pytest.mark.parametrize(
"circuit_and_type",
(
(qiskit_circuit, "qiskit"),
(pyquil_circuit, "pyquil"),
(braket_circuit, "braket"),
),
)
def test_converter(circuit_and_type):
circuit, input_type = circuit_and_type
# Return the input type
scaled = scaling_function(circuit)
assert isinstance(scaled, circuit_types[input_type])
# Return a Cirq Circuit
cirq_scaled = scaling_function(circuit, return_mitiq=True)
assert isinstance(cirq_scaled, cirq.Circuit)
assert _equal(cirq_scaled, cirq_circuit)
@pytest.mark.parametrize("nbits", [1, 10])
@pytest.mark.parametrize("measure", [True, False])
def test_converter_keeps_register_structure_qiskit(nbits, measure):
qreg = qiskit.QuantumRegister(nbits)
creg = qiskit.ClassicalRegister(nbits)
circ = qiskit.QuantumCircuit(qreg, creg)
circ.h(qreg)
if measure:
circ.measure(qreg, creg)
scaled = scaling_function(circ)
assert scaled.qregs == circ.qregs
assert scaled.cregs == circ.cregs
assert scaled == circ
@pytest.mark.parametrize("nbits", [1, 10])
@pytest.mark.parametrize("measure", [True, False])
def test_converter_keeps_register_structure_qiskit_one_to_many(nbits, measure):
qreg = qiskit.QuantumRegister(nbits)
creg = qiskit.ClassicalRegister(nbits)
circ = qiskit.QuantumCircuit(qreg, creg)
circ.h(qreg)
if measure:
circ.measure(qreg, creg)
out_circuits = one_to_many_circuit_modifier(circ)
for out_circ in out_circuits:
assert out_circ.qregs == circ.qregs
assert out_circ.cregs == circ.cregs
print(out_circ)
assert out_circuits[0] == circ
assert out_circuits[1] != circ
@pytest.mark.parametrize("to_type", SUPPORTED_PROGRAM_TYPES.keys())
def test_atomic_one_to_many_converter(to_type):
circuit = convert_from_mitiq(cirq_circuit, to_type)
circuits = returns_several_circuits(circuit)
for circuit in circuits:
assert isinstance(circuit, circuit_types[to_type])
circuits = returns_several_circuits(circuit, return_mitiq=True)
for circuit in circuits:
assert isinstance(circuit, cirq.Circuit)
def test_noise_scaling_converter_with_qiskit_idle_qubits_and_barriers():
"""Idle qubits must be preserved even if the input has barriers.
Test input:
┌───┐ ░
q_0: ┤ X ├─░─
└───┘ ░
q_1: ──────░─
┌───┐ ░
q_2: ┤ X ├─░─
└───┘ ░
q_3: ────────
Expected output:
┌───┐
q_0: ┤ X ├
└───┘
q_1: ─────
┌───┐
q_2: ┤ X ├
└───┘
q_3: ─────
"""
test_circuit_qiskit = qiskit.QuantumCircuit(4)
test_circuit_qiskit.x(0)
test_circuit_qiskit.x(2)
test_circuit_qiskit.barrier(0, 1, 2)
test_copy = test_circuit_qiskit.copy()
scaled = scaling_function(test_circuit_qiskit)
# Mitiq is expected to remove qiskit barriers
expected = qiskit.QuantumCircuit(4)
expected.x(0)
expected.x(2)
assert scaled == expected
# Mitiq should not mutate the input circuit
assert test_circuit_qiskit == test_copy
|
https://github.com/unitaryfund/mitiq
|
unitaryfund
|
# Copyright (C) Unitary Fund
#
# This source code is licensed under the GPL license (v3) found in the
# LICENSE file in the root directory of this source tree.
"""Unit tests for scaling noise by unitary folding."""
import numpy as np
import pytest
from cirq import (
Circuit,
GridQubit,
InsertStrategy,
LineQubit,
equal_up_to_global_phase,
inverse,
ops,
ry,
rz,
testing,
)
from pyquil import Program, gates
from pyquil.quilbase import Pragma
from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister
from qiskit.quantum_info.operators import Operator
from sympy import Symbol
from mitiq.interface import (
CircuitConversionError,
convert_from_mitiq,
convert_to_mitiq,
)
from mitiq.utils import _equal
from mitiq.zne.scaling.folding import (
UnfoldableCircuitError,
_apply_fold_mask,
_create_fold_mask,
_create_weight_mask,
_default_weight,
_fold_all,
_squash_moments,
fold_all,
fold_gates_at_random,
fold_global,
)
def test_squash_moments_two_qubits():
"""Tests squashing moments in a two-qubit circuit with 'staggered' single
qubit gates.
"""
# Test circuit:
# 0: ───────H───────H───────H───────H───────H───
#
# 1: ───H───────H───────H───────H───────H───────
# Get the test circuit
d = 10
qreg = LineQubit.range(2)
circuit = Circuit()
for i in range(d):
circuit.insert(0, ops.H.on(qreg[i % 2]), strategy=InsertStrategy.NEW)
assert len(circuit) == d
# Squash the moments
squashed = _squash_moments(circuit)
assert len(squashed) == d // 2
def test_squash_moments_returns_new_circuit_and_doesnt_modify_input_circuit():
"""Tests that squash moments returns a new circuit and doesn't modify the
input circuit.
"""
qbit = GridQubit(0, 0)
circ = Circuit(ops.H.on(qbit))
squashed = _squash_moments(circ)
assert len(squashed) == 1
assert circ is not squashed
assert _equal(circ, Circuit(ops.H.on(qbit)))
def test_squash_moments_never_increases_moments():
"""Squashes moments for several random circuits and ensures the squashed
circuit always <= # moments as the input circuit.
"""
for _ in range(50):
circuit = testing.random_circuit(
qubits=5, n_moments=8, op_density=0.75
)
squashed = _squash_moments(circuit)
assert len(squashed) <= len(circuit)
@pytest.mark.parametrize("scale_factor", (1, 3, 5))
@pytest.mark.parametrize("with_measurements", (True, False))
def test_fold_all(scale_factor, with_measurements):
# Test circuit
# 0: ───H───@───@───
# │ │
# 1: ───H───X───@───
# │
# 2: ───H───X───X───
qreg = LineQubit.range(3)
circ = Circuit(
[ops.H.on_each(*qreg)],
[ops.CNOT.on(qreg[0], qreg[1])],
[ops.X.on(qreg[2])],
[ops.TOFFOLI.on(*qreg)],
)
if with_measurements:
circ.append(ops.measure_each(*qreg))
folded = fold_all(circ, scale_factor=scale_factor)
correct = Circuit(
[ops.H.on_each(*qreg)] * scale_factor,
[ops.CNOT.on(qreg[0], qreg[1])] * scale_factor,
[ops.X.on(qreg[2])] * scale_factor,
[ops.TOFFOLI.on(*qreg)] * scale_factor,
)
if with_measurements:
correct.append(ops.measure_each(*qreg))
assert _equal(folded, correct, require_qubit_equality=True)
def test_fold_all_exclude_with_gates():
circuit = Circuit(
[ops.H(LineQubit(0))],
[ops.CNOT(*LineQubit.range(2))],
[ops.TOFFOLI(*LineQubit.range(3))],
)
folded = fold_all(circuit, scale_factor=3.0, exclude={ops.H})
correct = Circuit(
[ops.H(LineQubit(0))],
[ops.CNOT(*LineQubit.range(2))] * 3,
[ops.TOFFOLI(*LineQubit.range(3))] * 3,
)
assert _equal(folded, correct, require_qubit_equality=True)
folded = fold_all(circuit, scale_factor=3.0, exclude={ops.CNOT})
correct = Circuit(
[ops.H(LineQubit(0))] * 3,
[ops.CNOT(*LineQubit.range(2))],
[ops.TOFFOLI(*LineQubit.range(3))] * 3,
)
assert _equal(folded, correct, require_qubit_equality=True)
folded = fold_all(circuit, scale_factor=5.0, exclude={ops.H, ops.TOFFOLI})
correct = Circuit(
[ops.H(LineQubit(0))],
[ops.CNOT(*LineQubit.range(2))] * 5,
[ops.TOFFOLI(*LineQubit.range(3))],
)
assert _equal(folded, correct, require_qubit_equality=True)
def test_fold_all_exclude_with_strings():
circuit = Circuit(
[ops.H(LineQubit(0))],
[ops.CNOT(*LineQubit.range(2))],
[ops.TOFFOLI(*LineQubit.range(3))],
)
folded = fold_all(circuit, scale_factor=3.0, exclude={"single"})
correct = Circuit(
[ops.H(LineQubit(0))],
[ops.CNOT(*LineQubit.range(2))] * 3,
[ops.TOFFOLI(*LineQubit.range(3))] * 3,
)
assert _equal(folded, correct, require_qubit_equality=True)
folded = fold_all(circuit, scale_factor=3.0, exclude={"double"})
correct = Circuit(
[ops.H(LineQubit(0))] * 3,
[ops.CNOT(*LineQubit.range(2))],
[ops.TOFFOLI(*LineQubit.range(3))] * 3,
)
assert _equal(folded, correct, require_qubit_equality=True)
folded = fold_all(circuit, scale_factor=5.0, exclude={"single", "triple"})
correct = Circuit(
[ops.H(LineQubit(0))],
[ops.CNOT(*LineQubit.range(2))] * 5,
[ops.TOFFOLI(*LineQubit.range(3))],
)
assert _equal(folded, correct, require_qubit_equality=True)
@pytest.mark.parametrize("skip", (frozenset((0, 1)), frozenset((0, 3, 7))))
def test_fold_all_skip_moments(skip):
circuit = testing.random_circuit(
qubits=3,
n_moments=7,
op_density=1,
random_state=1,
gate_domain={ops.H: 1, ops.X: 1, ops.CNOT: 2},
)
folded = _fold_all(circuit, skip_moments=skip)
correct = Circuit()
for i, moment in enumerate(circuit):
times_to_add = 3 * (i not in skip) + (i in skip)
for _ in range(times_to_add):
correct += moment
assert _equal(
_squash_moments(folded),
_squash_moments(correct),
require_qubit_equality=True,
)
def test_folding_with_bad_scale_factor():
for fold_function in (
fold_all,
fold_gates_at_random,
):
with pytest.raises(ValueError, match="Requires scale_factor >= 1"):
fold_function(Circuit(), scale_factor=0.0)
def test_create_mask_with_bad_scale_factor():
with pytest.raises(ValueError, match="Requires scale_factor >= 1"):
_create_fold_mask([1], scale_factor=0.999)
def test_fold_all_bad_exclude():
with pytest.raises(ValueError, match="Do not know how to parse"):
fold_all(
Circuit(),
scale_factor=1.0,
exclude=frozenset(("not a gate name",)),
)
with pytest.raises(ValueError, match="Do not know how to exclude"):
fold_all(Circuit(), scale_factor=1.0, exclude=frozenset((7,)))
@pytest.mark.parametrize(
"fold_method",
[
fold_gates_at_random,
fold_global,
],
)
def test_fold_with_intermediate_measurements_raises_error(fold_method):
"""Tests local folding functions raise an error on circuits with
intermediate measurements.
"""
qbit = LineQubit(0)
circ = Circuit([ops.H.on(qbit)], [ops.measure(qbit)], [ops.T.on(qbit)])
with pytest.raises(
UnfoldableCircuitError,
match="Circuit contains intermediate measurements",
):
fold_method(circ, scale_factor=3.0)
@pytest.mark.parametrize(
"fold_method",
[
fold_gates_at_random,
fold_global,
],
)
def test_fold_with_channels_raises_error(fold_method):
"""Tests local folding functions raise an error on circuits with
non-invertible channels (which are not measurements).
"""
qbit = LineQubit(0)
circ = Circuit(
ops.H.on(qbit), ops.depolarize(p=0.1).on(qbit), ops.measure(qbit)
)
with pytest.raises(
UnfoldableCircuitError, match="Circuit contains non-invertible"
):
fold_method(circ, scale_factor=3.0)
@pytest.mark.parametrize(
"fold_method",
[
fold_gates_at_random,
fold_global,
],
)
def test_parametrized_circuit_folding(fold_method):
"""Checks if the circuit is folded as expected when the circuit operations
have a valid inverse.
"""
theta = Symbol("theta")
q = LineQubit(0)
ansatz_circ = Circuit(ry(theta).on(q))
folded_circ = fold_method(ansatz_circ, scale_factor=3.0)
expected_circ = Circuit(ry(theta).on(q), ry(-theta).on(q), ry(theta).on(q))
assert _equal(folded_circ, expected_circ)
@pytest.mark.parametrize(
"fold_method",
[
fold_gates_at_random,
fold_global,
],
)
def test_parametrized_circuit_folding_terminal_measurement(fold_method):
"""Checks if the circuit with a terminal measurement is folded as expected
when the circuit operations have a valid inverse.
"""
theta = Symbol("theta")
q = LineQubit(0)
ansatz_circ = Circuit(ry(theta).on(q), ops.measure(q))
folded_circ = fold_method(ansatz_circ, scale_factor=3.0)
expected_circ = Circuit(
ry(theta).on(q), ry(-theta).on(q), ry(theta).on(q), ops.measure(q)
)
assert _equal(folded_circ, expected_circ)
@pytest.mark.parametrize(
"fold_method",
[
fold_gates_at_random,
fold_global,
],
)
def test_errors_raised_parametrized_circuits(fold_method):
"""Checks if proper error is raised in a symbolic circuit when it cannot
be folded.
"""
theta = Symbol("theta")
q = LineQubit(0)
ansatz_circ = Circuit(ry(theta).on(q), ops.measure(q), rz(theta).on(q))
with pytest.raises(
UnfoldableCircuitError,
match="Circuit contains intermediate measurements",
):
fold_method(ansatz_circ, scale_factor=3.0)
qbit = LineQubit(0)
circ = Circuit(
ry(theta).on(q), ops.depolarize(p=0.1).on(qbit), ops.measure(qbit)
)
with pytest.raises(
UnfoldableCircuitError, match="Circuit contains non-invertible"
):
fold_method(circ, scale_factor=3.0)
def test_fold_gates_at_random_no_stretch():
"""Tests folded circuit is identical for a scale factor of one."""
circuit = testing.random_circuit(qubits=3, n_moments=10, op_density=0.99)
folded = fold_gates_at_random(circuit, scale_factor=1, seed=None)
assert _equal(folded, _squash_moments(circuit))
def test_fold_gates_at_random_seed_one_qubit():
"""Test for folding gates at random on a one qubit circuit with a seed for
repeated behavior.
"""
qubit = LineQubit(0)
circuit = Circuit([ops.X.on(qubit), ops.Y.on(qubit), ops.Z.on(qubit)])
# Small scale
folded = fold_gates_at_random(circuit, scale_factor=1.4, seed=3)
correct = Circuit(
[ops.X.on(qubit)], [ops.Y.on(qubit)] * 3, [ops.Z.on(qubit)]
)
assert _equal(folded, correct)
# Medium scale, fold two gates
folded = fold_gates_at_random(circuit, scale_factor=2.5, seed=2)
correct = Circuit(
[ops.X.on(qubit)],
[ops.Y.on(qubit)] * 3,
[ops.Z.on(qubit)] * 3,
)
assert _equal(folded, correct)
# Max scale, fold three gates
folded = fold_gates_at_random(circuit, scale_factor=3, seed=3)
correct = Circuit(
[ops.X.on(qubit)] * 3,
[ops.Y.on(qubit)] * 3,
[ops.Z.on(qubit)] * 3,
)
assert _equal(folded, correct)
def test_fold_random_min_stretch():
"""Tests that folding at random with min scale returns a copy of the
input circuit.
"""
# Test circuit
# 0: ───H───@───@───
# │ │
# 1: ───H───X───@───
# │
# 2: ───H───T───X───
qreg = LineQubit.range(3)
circ = Circuit(
[ops.H.on_each(*qreg)],
[ops.CNOT.on(qreg[0], qreg[1])],
[ops.T.on(qreg[2])],
[ops.TOFFOLI.on(*qreg)],
)
folded = fold_gates_at_random(circ, scale_factor=1, seed=1)
assert _equal(folded, circ)
assert folded is not circ
def test_fold_random_max_stretch():
"""Tests that folding at random with max scale folds all gates on a
multi-qubit circuit.
"""
# Test circuit
# 0: ───H───@───@───
# │ │
# 1: ───H───X───@───
# │
# 2: ───H───T───X───
qreg = LineQubit.range(3)
circ = Circuit(
[ops.H.on_each(*qreg)],
[ops.CNOT.on(qreg[0], qreg[1])],
[ops.T.on(qreg[2])],
[ops.TOFFOLI.on(*qreg)],
)
folded = fold_gates_at_random(circ, scale_factor=3, seed=1)
correct = Circuit(
[ops.H.on_each(*qreg)] * 3,
[ops.CNOT.on(qreg[0], qreg[1])] * 3,
[ops.T.on(qreg[2]), ops.T.on(qreg[2]) ** -1, ops.T.on(qreg[2])],
[ops.TOFFOLI.on(*qreg)] * 3,
)
assert _equal(folded, correct)
def test_fold_random_scale_factor_larger_than_three():
"""Folds at random with a scale_factor larger than three."""
qreg = LineQubit.range(2)
circuit = Circuit([ops.SWAP.on(*qreg)], [ops.CNOT.on(*qreg)])
folded = fold_gates_at_random(circuit, scale_factor=6.0, seed=0)
correct = Circuit([ops.SWAP.on(*qreg)] * 5, [ops.CNOT.on(*qreg)] * 7)
assert len(folded) == 12
assert _equal(folded, correct)
def test_fold_random_no_repeats():
"""Tests folding at random to ensure that no gates are folded twice and
folded gates are not folded again.
"""
# Test circuit:
# 0: ───H───@───Y───@───
# │ │
# 1: ───────X───X───@───
# Note that each gate only occurs once and is self-inverse.
# This allows us to check that no gates are folded more than once
qreg = LineQubit.range(2)
circ = Circuit(
[ops.H.on_each(qreg[0])],
[ops.CNOT.on(*qreg)],
[ops.X.on(qreg[1])],
[ops.Y.on(qreg[0])],
[ops.CZ.on(*qreg)],
)
circuit_ops = set(circ.all_operations())
for scale in np.linspace(1.0, 3.0, 5):
folded = fold_gates_at_random(circ, scale_factor=scale, seed=1)
gates = list(folded.all_operations())
counts = {gate: gates.count(gate) for gate in circuit_ops}
assert all(count <= 3 for count in counts.values())
def test_fold_random_with_terminal_measurements_min_stretch():
"""Tests folding from left with terminal measurements."""
# Test circuit
# 0: ───H───@───@───M───
# │ │
# 1: ───H───X───@───M───
# │
# 2: ───H───T───X───M───
qreg = LineQubit.range(3)
circ = Circuit(
[ops.H.on_each(*qreg)],
[ops.CNOT.on(qreg[0], qreg[1])],
[ops.T.on(qreg[2])],
[ops.TOFFOLI.on(*qreg)],
[ops.measure_each(*qreg)],
)
folded = fold_gates_at_random(circ, scale_factor=1.0)
correct = Circuit(
[ops.H.on_each(*qreg)],
[ops.CNOT.on(qreg[0], qreg[1])],
[ops.T.on(qreg[2])],
[ops.TOFFOLI.on(*qreg)],
[ops.measure_each(*qreg)],
)
assert _equal(folded, correct)
def test_fold_random_with_terminal_measurements_max_stretch():
"""Tests folding from left with terminal measurements."""
# Test circuit
# 0: ───H───@───@───M───
# │ │
# 1: ───H───X───@───M───
# │
# 2: ───H───T───X───M───
qreg = LineQubit.range(3)
circ = Circuit(
[ops.H.on_each(*qreg)],
[ops.CNOT.on(qreg[0], qreg[1])],
[ops.T.on(qreg[2])],
[ops.TOFFOLI.on(*qreg)],
[ops.measure_each(*qreg)],
)
folded = fold_gates_at_random(circ, scale_factor=3.0)
correct = Circuit(
[ops.H.on_each(*qreg)] * 3,
[ops.CNOT.on(qreg[0], qreg[1])] * 3,
[ops.T.on(qreg[2]), ops.T.on(qreg[2]) ** -1, ops.T.on(qreg[2])],
[ops.TOFFOLI.on(*qreg)] * 3,
[ops.measure_each(*qreg)],
)
assert _equal(folded, correct)
def test_global_fold_min_stretch():
"""Tests that global fold with scale = 1 is the same circuit."""
# Test circuit
# 0: ───H───@───@───
# │ │
# 1: ───H───X───@───
# │
# 2: ───H───T───X───
qreg = LineQubit.range(3)
circ = Circuit(
[ops.H.on_each(*qreg)],
[ops.CNOT.on(qreg[0], qreg[1])],
[ops.T.on(qreg[2])],
[ops.TOFFOLI.on(*qreg)],
)
folded = fold_global(circ, 1.0)
assert _equal(folded, circ)
assert folded is not circ
def test_global_fold_min_stretch_with_terminal_measurements():
"""Tests that global fold with scale = 1 is the same circuit."""
# Test circuit
# 0: ───H───@───@───M───
# │ │
# 1: ───H───X───@───M───
# │
# 2: ───H───T───X───M───
qreg = LineQubit.range(3)
circ = Circuit(
[ops.H.on_each(*qreg)],
[ops.CNOT.on(qreg[0], qreg[1])],
[ops.T.on(qreg[2])],
[ops.TOFFOLI.on(*qreg)],
[ops.measure_each(*qreg)],
)
folded = fold_global(circ, scale_factor=1.0)
assert _equal(folded, circ)
assert folded is not circ
def test_global_fold_stretch_factor_of_three():
"""Tests global folding with the scale as a factor of 3."""
# Test circuit
# 0: ───H───@───@───
# │ │
# 1: ───H───X───@───
# │
# 2: ───H───T───X───
qreg = LineQubit.range(3)
circ = Circuit(
[ops.H.on_each(*qreg)],
[ops.CNOT.on(qreg[0], qreg[1])],
[ops.T.on(qreg[2])],
[ops.TOFFOLI.on(*qreg)],
)
folded = fold_global(circ, scale_factor=3.0)
correct = Circuit(circ, inverse(circ), circ)
assert _equal(folded, correct)
def test_global_fold_stretch_factor_of_three_with_terminal_measurements():
"""Tests global folding with the scale as a factor of 3 for a circuit
with terminal measurements.
"""
# Test circuit
# 0: ───H───@───@───M───
# │ │
# 1: ───H───X───@───M───
# │
# 2: ───H───T───X───M───
qreg = LineQubit.range(3)
circ = Circuit(
[ops.H.on_each(*qreg)],
[ops.CNOT.on(qreg[0], qreg[1])],
[ops.T.on(qreg[2])],
[ops.TOFFOLI.on(*qreg)],
)
meas = Circuit([ops.measure_each(*qreg)])
folded = fold_global(circ + meas, scale_factor=3.0)
correct = Circuit(circ, inverse(circ), circ, meas)
assert _equal(folded, correct)
# Test the number of moments too
assert len(folded) == len(correct)
def test_global_fold_stretch_factor_nine_with_terminal_measurements():
"""Tests global folding with the scale as a factor of 9 for a circuit
with terminal measurements.
"""
# Test circuit
# 0: ───H───@───@───M───
# │ │
# 1: ───H───X───@───M───
# │
# 2: ───H───T───X───M───
qreg = LineQubit.range(3)
circ = Circuit(
[ops.H.on_each(*qreg)],
[ops.CNOT.on(qreg[0], qreg[1])],
[ops.T.on(qreg[2])],
[ops.TOFFOLI.on(*qreg)],
)
meas = Circuit([ops.measure_each(*qreg)])
folded = fold_global(circ + meas, scale_factor=9.0)
correct = Circuit([circ, inverse(circ)] * 4, [circ], [meas])
assert _equal(folded, correct)
def test_global_fold_stretch_factor_eight_terminal_measurements():
"""Tests global folding with a scale factor not a multiple of three so
that local folding is also called.
"""
# Test circuit
# 0: ───H───@───@───M───
# │ │
# 1: ───H───X───@───M───
# │
# 2: ───H───T───X───M───
qreg = LineQubit.range(3)
circ = Circuit(
[ops.H.on_each(*qreg)],
[ops.CNOT.on(qreg[0], qreg[1])],
[ops.T.on(qreg[2])],
[ops.TOFFOLI.on(*qreg)],
)
meas = Circuit(ops.measure_each(*qreg))
folded = fold_global(circ + meas, scale_factor=3.5)
correct = Circuit(
circ,
inverse(circ),
circ,
inverse(
Circuit(
[ops.T.on(qreg[2])],
[ops.TOFFOLI.on(*qreg)],
)
),
[ops.T.on(qreg[2])],
[ops.TOFFOLI.on(*qreg)],
meas,
)
assert _equal(folded, correct)
def test_global_fold_moment_structure_maintained_full_scale_factors():
"""Tests global folding maintains the input circuit's moment structure."""
# Test circuit 1
# 0: ───H───────────────
# 1: ───────Z───────────
# 2: ───────────S───────
# 3: ───────────────T───
qreg = LineQubit.range(4)
gate_list1 = [ops.H, ops.Z, ops.S, ops.T]
circuit1 = Circuit(gate_list1[0](qreg[0]))
for i in range(1, 4):
circuit1 += Circuit(gate_list1[i](qreg[i]))
folded = fold_global(circuit1, scale_factor=3)
correct = Circuit(
circuit1,
inverse(circuit1),
circuit1,
)
assert _equal(folded, correct)
# Test Circuit 2
# 0: ───H───@───────@───
# │ |
# 1: ───H───X───────@───
# │
# 2: ───H───────T───X───
qreg = LineQubit.range(3)
gate_list = [
ops.CNOT.on(qreg[0], qreg[1]),
[ops.T.on(qreg[2])],
[ops.TOFFOLI.on(*qreg)],
]
circ = Circuit([ops.H.on_each(*qreg)])
for i in range(len(gate_list)):
circ += Circuit(gate_list[i])
folded = fold_global(circ, scale_factor=3)
correct = Circuit(
circ,
inverse(circ),
circ,
)
assert _equal(folded, correct)
def test_global_fold_moment_structure_maintained_partial_scale_factors():
"""Tests global folding maintains the input circuit's moment structure."""
# Test circuit 1
# 0: ───H───────────────
# 1: ───────Z───────────
# 2: ───────────S───────
# 3: ───────────────T───
qreg = LineQubit.range(4)
gate_list1 = [ops.H, ops.Z, ops.S, ops.T]
circuit1 = Circuit(gate_list1[0](qreg[0]))
for i in range(1, 4):
circuit1 += Circuit(gate_list1[i](qreg[i]))
folded1 = fold_global(circuit1, scale_factor=1.5)
correct1 = Circuit(circuit1, inverse(circuit1)[0], circuit1[-1])
assert _equal(folded1, correct1)
folded2 = fold_global(circuit1, scale_factor=2.5)
correct2 = Circuit(circuit1, inverse(circuit1)[0:3], circuit1[1:])
assert _equal(folded2, correct2)
folded3 = fold_global(circuit1, scale_factor=2.75)
correct3 = Circuit(circuit1, inverse(circuit1), circuit1)
assert _equal(folded3, correct3)
def test_convert_to_from_mitiq_qiskit():
"""Basic test for converting a Qiskit circuit to a Cirq circuit."""
# Test Qiskit circuit:
# ┌───┐
# q0_0: |0>┤ H ├──■──
# └───┘┌─┴─┐
# q0_1: |0>─────┤ X ├
# └───┘
qiskit_qreg = QuantumRegister(2)
qiskit_circuit = QuantumCircuit(qiskit_qreg)
qiskit_circuit.h(qiskit_qreg[0])
qiskit_circuit.cx(*qiskit_qreg)
# Convert to a mitiq circuit
mitiq_circuit, input_circuit_type = convert_to_mitiq(qiskit_circuit)
assert isinstance(mitiq_circuit, Circuit)
# Check correctness
mitiq_qreg = LineQubit.range(2)
correct_mitiq_circuit = Circuit(
ops.H.on(mitiq_qreg[0]), ops.CNOT.on(*mitiq_qreg)
)
assert _equal(
mitiq_circuit, correct_mitiq_circuit, require_qubit_equality=False
)
# Convert back to original circuit type
original_circuit = convert_from_mitiq(mitiq_circuit, input_circuit_type)
assert isinstance(original_circuit, QuantumCircuit)
def test_fold_at_random_with_qiskit_circuits():
"""Tests folding at random with Qiskit circuits."""
# Test Qiskit circuit:
# ┌───┐
# q0_0: |0>┤ H ├──■────■──
# ├───┤┌─┴─┐ │
# q0_1: |0>┤ H ├┤ X ├──■──
# ├───┤├───┤┌─┴─┐
# q0_2: |0>┤ H ├┤ T ├┤ X ├
# └───┘└───┘└───┘
qiskit_qreg = QuantumRegister(3)
qiskit_creg = ClassicalRegister(3)
qiskit_circuit = QuantumCircuit(qiskit_qreg, qiskit_creg)
qiskit_circuit.h(qiskit_qreg)
qiskit_circuit.cx(qiskit_qreg[0], qiskit_qreg[1])
qiskit_circuit.t(qiskit_qreg[2])
qiskit_circuit.ccx(*qiskit_qreg)
qiskit_circuit.measure(qiskit_qreg, qiskit_creg)
folded_circuit = fold_gates_at_random(
qiskit_circuit, scale_factor=1.0, return_mitiq=True
)
qreg = LineQubit.range(3)
correct_folded_circuit = Circuit(
[ops.H.on_each(*qreg)],
[ops.CNOT.on(qreg[0], qreg[1])],
[ops.T.on(qreg[2])],
[ops.TOFFOLI.on(*qreg)],
[ops.measure_each(*qreg)],
)
assert isinstance(folded_circuit, Circuit)
assert _equal(folded_circuit, correct_folded_circuit)
# Keep the input type
qiskit_folded_circuit = fold_gates_at_random(
qiskit_circuit, scale_factor=1.0
)
assert isinstance(qiskit_folded_circuit, QuantumCircuit)
assert qiskit_folded_circuit.qregs == qiskit_circuit.qregs
assert qiskit_folded_circuit.cregs == qiskit_circuit.cregs
def test_fold_global_with_qiskit_circuits():
"""Tests _fold_local with input Qiskit circuits."""
# Test Qiskit circuit:
# ┌───┐
# q0_0: |0>┤ H ├──■────■──
# ├───┤┌─┴─┐ │
# q0_1: |0>┤ H ├┤ X ├──■──
# ├───┤├───┤┌─┴─┐
# q0_2: |0>┤ H ├┤ T ├┤ X ├
# └───┘└───┘└───┘
qiskit_qreg = QuantumRegister(3)
qiskit_creg = ClassicalRegister(3)
qiskit_circuit = QuantumCircuit(qiskit_qreg, qiskit_creg)
qiskit_circuit.h(qiskit_qreg)
qiskit_circuit.cx(qiskit_qreg[0], qiskit_qreg[1])
qiskit_circuit.t(qiskit_qreg[2])
qiskit_circuit.ccx(*qiskit_qreg)
qiskit_circuit.measure(qiskit_qreg, qiskit_creg)
# Return mitiq circuit
folded_circuit = fold_global(
qiskit_circuit,
scale_factor=2.71828,
fold_method=fold_gates_at_random,
return_mitiq=True,
)
assert isinstance(folded_circuit, Circuit)
# Return input circuit type
folded_qiskit_circuit = fold_global(
qiskit_circuit, scale_factor=2.0, fold_method=fold_gates_at_random
)
assert isinstance(folded_qiskit_circuit, QuantumCircuit)
assert folded_qiskit_circuit.qregs == qiskit_circuit.qregs
assert folded_qiskit_circuit.cregs == qiskit_circuit.cregs
def test_fold_global_with_qiskit_circuits_and_idle_qubits():
"""Tests _fold_local with input Qiskit circuits where idle qubits are
interspered.
"""
# Test Qiskit circuit:
# ┌───┐ ┌─┐
# q4_0: |0>┤ H ├──■────■──┤M├──────
# └───┘ │ │ └╥┘
# q4_1: |0>───────┼────┼───╫───────
# ┌───┐┌─┴─┐ │ ║ ┌─┐
# q4_2: |0>┤ H ├┤ X ├──■───╫─┤M├───
# └───┘└───┘ │ ║ └╥┘
# q4_3: |0>────────────┼───╫──╫────
# ┌───┐┌───┐┌─┴─┐ ║ ║ ┌─┐
# q4_4: |0>┤ H ├┤ T ├┤ X ├─╫──╫─┤M├
# └───┘└───┘└───┘ ║ ║ └╥┘
# c4: 5/════════════════╩══╩══╩═
# 0 2 4
qiskit_qreg = QuantumRegister(5)
qiskit_creg = ClassicalRegister(5)
qiskit_circuit = QuantumCircuit(qiskit_qreg, qiskit_creg)
qiskit_circuit.h(qiskit_qreg[0])
qiskit_circuit.h(qiskit_qreg[2])
qiskit_circuit.h(qiskit_qreg[4])
qiskit_circuit.cx(qiskit_qreg[0], qiskit_qreg[2])
qiskit_circuit.t(qiskit_qreg[4])
qiskit_circuit.ccx(qiskit_qreg[0], qiskit_qreg[2], qiskit_qreg[4])
qiskit_circuit.measure(qiskit_qreg[0], qiskit_creg[0])
qiskit_circuit.measure(qiskit_qreg[2], qiskit_creg[2])
qiskit_circuit.measure(qiskit_qreg[4], qiskit_creg[4])
# Return mitiq circuit
folded_circuit = fold_global(
qiskit_circuit,
scale_factor=2.71828,
fold_method=fold_gates_at_random,
return_mitiq=True,
)
assert isinstance(folded_circuit, Circuit)
# Return input circuit type
folded_qiskit_circuit = fold_global(
qiskit_circuit, scale_factor=2.0, fold_method=fold_gates_at_random
)
assert isinstance(folded_qiskit_circuit, QuantumCircuit)
assert folded_qiskit_circuit.qregs == qiskit_circuit.qregs
assert folded_qiskit_circuit.cregs == qiskit_circuit.cregs
def test_fold_left_squash_moments():
"""Tests folding from left with kwarg squash_moments."""
# Test circuit
# 0: ───H───@───@───M───
# │ │
# 1: ───H───X───@───M───
# │
# 2: ───H───T───X───M───
qreg = LineQubit.range(3)
circ = Circuit(
[ops.H.on_each(*qreg)],
[ops.CNOT.on(qreg[0], qreg[1])],
[ops.T.on(qreg[2])],
[ops.TOFFOLI.on(*qreg)],
[ops.measure_each(*qreg)],
)
folded_not_squashed = fold_gates_at_random(
circ, scale_factor=3, squash_moments=False
)
folded_and_squashed = fold_gates_at_random(
circ, scale_factor=3, squash_moments=True
)
correct = Circuit(
[ops.H.on_each(*qreg)] * 3,
[ops.CNOT.on(qreg[0], qreg[1])] * 3,
[ops.T.on(qreg[2]), ops.T.on(qreg[2]) ** -1, ops.T.on(qreg[2])],
[ops.TOFFOLI.on(*qreg)] * 3,
[ops.measure_each(*qreg)],
)
assert _equal(folded_and_squashed, folded_not_squashed)
assert _equal(folded_and_squashed, correct)
assert len(folded_and_squashed) == 10
def test_fold_and_squash_max_stretch():
"""Tests folding and squashing a two-qubit circuit."""
# Test circuit:
# 0: ───────H───────H───────H───────H───────H───
#
# 1: ───H───────H───────H───────H───────H───────
# Get the test circuit
d = 10
qreg = LineQubit.range(2)
circuit = Circuit()
for i in range(d):
circuit.insert(0, ops.H.on(qreg[i % 2]), strategy=InsertStrategy.NEW)
folded_not_squashed = fold_gates_at_random(
circuit, scale_factor=3.0, squash_moments=False
)
folded_and_squashed = fold_gates_at_random(
circuit, scale_factor=3.0, squash_moments=True
)
folded_with_squash_moments_not_specified = fold_gates_at_random(
circuit, scale_factor=3.0
) # Checks that the default is to squash moments
assert len(folded_not_squashed) == 30
assert len(folded_and_squashed) == 15
assert len(folded_with_squash_moments_not_specified) == 15
def test_fold_and_squash_random_circuits_random_stretches():
"""Tests folding and squashing random circuits and ensures the number of
moments in the squashed circuits is never greater than the number of
moments in the un-squashed circuit.
"""
rng = np.random.RandomState(seed=1)
for trial in range(5):
circuit = testing.random_circuit(
qubits=8, n_moments=8, op_density=0.75
)
scale = 2 * rng.random() + 1
folded_not_squashed = fold_gates_at_random(
circuit,
scale_factor=scale,
squash_moments=False,
seed=trial,
)
folded_and_squashed = fold_gates_at_random(
circuit,
scale_factor=scale,
squash_moments=True,
seed=trial,
)
assert len(folded_and_squashed) <= len(folded_not_squashed)
def test_default_weight():
"""Tests default weight of an n-qubit gates is 0.99**n."""
qreg = LineQubit.range(3)
assert np.isclose(_default_weight(ops.H.on(qreg[0])), 0.99)
assert np.isclose(_default_weight(ops.CZ.on(qreg[0], qreg[1])), 0.9801)
assert np.isclose(_default_weight(ops.TOFFOLI.on(*qreg[:3])), 0.970299)
@pytest.mark.parametrize("qiskit", [True, False])
def test_fold_local_with_fidelities(qiskit):
qreg = LineQubit.range(3)
circ = Circuit(
ops.H.on_each(*qreg),
ops.CNOT.on(qreg[0], qreg[1]),
ops.T.on(qreg[2]),
ops.TOFFOLI.on(*qreg),
)
if qiskit:
circ = convert_from_mitiq(circ, "qiskit")
# Only fold the Toffoli gate
fidelities = {"H": 1.0, "T": 1.0, "CNOT": 1.0, "TOFFOLI": 0.95}
folded = fold_gates_at_random(
circ, scale_factor=3.0, fidelities=fidelities
)
correct = Circuit(
[ops.H.on_each(*qreg)],
[ops.CNOT.on(qreg[0], qreg[1])],
[ops.T.on(qreg[2])],
[ops.TOFFOLI.on(*qreg)] * 3,
)
if qiskit:
folded, _ = convert_to_mitiq(folded)
assert equal_up_to_global_phase(folded.unitary(), correct.unitary())
else:
assert _equal(folded, correct)
@pytest.mark.parametrize("qiskit", [True, False])
def test_fold_local_with_single_qubit_gates_fidelity_one(qiskit):
"""Tests folding only two-qubit gates by using
fidelities = {"single": 1.}.
"""
qreg = LineQubit.range(3)
circ = Circuit(
ops.H.on_each(*qreg),
ops.CNOT.on(qreg[0], qreg[1]),
ops.T.on(qreg[2]),
ops.TOFFOLI.on(*qreg),
)
if qiskit:
circ = convert_from_mitiq(circ, "qiskit")
folded = fold_gates_at_random(
circ,
scale_factor=3.0,
fidelities={"single": 1.0, "CNOT": 0.99, "TOFFOLI": 0.95},
)
correct = Circuit(
[ops.H.on_each(*qreg)],
[ops.CNOT.on(qreg[0], qreg[1])] * 3,
[ops.T.on(qreg[2])],
[ops.TOFFOLI.on(*qreg)] * 3,
)
if qiskit:
assert folded.qregs == circ.qregs
assert folded.cregs == circ.cregs
folded, _ = convert_to_mitiq(folded)
assert equal_up_to_global_phase(folded.unitary(), correct.unitary())
else:
assert _equal(folded, correct)
@pytest.mark.parametrize("qiskit", [True, False])
def test_all_gates_folded_at_max_scale_with_fidelities(qiskit):
"""Tests that all gates are folded regardless of the input fidelities when
the scale factor is three.
"""
rng = np.random.RandomState(1)
qreg = LineQubit.range(3)
circ = Circuit(
ops.H.on_each(*qreg),
ops.CNOT.on(qreg[0], qreg[1]),
ops.T.on(qreg[2]),
ops.TOFFOLI.on(*qreg),
)
ngates = len(list(circ.all_operations()))
if qiskit:
circ = convert_from_mitiq(circ, "qiskit")
folded = fold_gates_at_random(
circ,
scale_factor=3.0,
fidelities={
"H": rng.rand(),
"T": rng.rand(),
"CNOT": rng.rand(),
"TOFFOLI": rng.rand(),
},
)
correct = Circuit(
[ops.H.on_each(*qreg)] * 3,
[ops.CNOT.on(qreg[0], qreg[1])] * 3,
[ops.T.on(qreg[2]), ops.T.on(qreg[2]) ** -1, ops.T.on(qreg[2])],
[ops.TOFFOLI.on(*qreg)] * 3,
)
if qiskit:
assert folded.qregs == circ.qregs
assert folded.cregs == circ.cregs
folded, _ = convert_to_mitiq(folded)
assert equal_up_to_global_phase(folded.unitary(), correct.unitary())
else:
assert _equal(folded, correct)
assert len(list(folded.all_operations())) == 3 * ngates
def test_fold_local_raises_error_with_bad_fidelities():
with pytest.raises(ValueError, match="Fidelities should be"):
fold_gates_at_random(
Circuit(), scale_factor=1.21, fidelities={"H": -1.0}
)
with pytest.raises(ValueError, match="Fidelities should be"):
fold_gates_at_random(
Circuit(), scale_factor=1.21, fidelities={"CNOT": 0.0}
)
with pytest.raises(ValueError, match="Fidelities should be"):
fold_gates_at_random(
Circuit(), scale_factor=1.21, fidelities={"triple": 1.2}
)
@pytest.mark.parametrize("conversion_type", ("qiskit", "pyquil"))
def test_convert_from_mitiq_circuit_conversion_error(conversion_type):
circuit = testing.random_circuit(qubits=5, n_moments=5, op_density=0.99)
noisy = circuit.with_noise(ops.depolarize(p=0.1))
with pytest.raises(
CircuitConversionError, match="Circuit could not be converted from"
):
convert_from_mitiq(noisy, conversion_type)
def test_convert_qiskit_to_mitiq_circuit_conversion_error():
# Custom gates are not supported in conversions
gate = Operator([[0.0, 1.0], [-1.0, 0.0]])
qreg = QuantumRegister(1)
circ = QuantumCircuit(qreg)
circ.unitary(gate, [0])
with pytest.raises(
CircuitConversionError, match="Circuit could not be converted to"
):
convert_to_mitiq(circ)
def test_convert_pyquil_to_mitiq_circuit_conversion_error():
# Pragmas are not supported in conversions
prog = Program(Pragma("INITIAL_REWIRING", ['"Partial"']))
with pytest.raises(
CircuitConversionError, match="Circuit could not be converted to"
):
convert_to_mitiq(prog)
@pytest.mark.parametrize(
"fold_method",
(
fold_gates_at_random,
fold_global,
),
)
def test_folding_circuit_conversion_error_qiskit(fold_method):
# Custom gates are not supported in conversions
gate = Operator([[0.0, 1.0], [-1.0, 0.0]])
qreg = QuantumRegister(1)
circ = QuantumCircuit(qreg)
circ.unitary(gate, [0])
with pytest.raises(
CircuitConversionError, match="Circuit could not be converted to"
):
fold_method(circ, scale_factor=2.0)
@pytest.mark.parametrize(
"fold_method",
(
fold_gates_at_random,
fold_global,
),
)
def test_folding_circuit_conversion_error_pyquil(fold_method):
# Pragmas are not supported in conversions
prog = Program(Pragma("INITIAL_REWIRING", ['"Partial"']))
with pytest.raises(
CircuitConversionError, match="Circuit could not be converted to"
):
fold_method(prog, scale_factor=2.0)
@pytest.mark.parametrize("scale", [1, 3, 5, 9])
def test_fold_fidelity_large_scale_factor_only_twoq_gates(scale):
qreg = LineQubit.range(2)
circuit = Circuit(ops.H(qreg[0]), ops.CNOT(*qreg))
folded = fold_gates_at_random(
circuit, scale_factor=scale, fidelities={"single": 1.0}
)
correct = Circuit(ops.H(qreg[0]), [ops.CNOT(*qreg)] * scale)
assert _equal(folded, correct)
def test_folding_keeps_measurement_order_with_qiskit():
qreg, creg = QuantumRegister(2), ClassicalRegister(2)
circuit = QuantumCircuit(qreg, creg)
circuit.h(qreg[0])
circuit.measure(qreg, creg)
folded = fold_gates_at_random(circuit, scale_factor=1.0)
assert folded == circuit
def test_create_weight_mask_with_fidelities():
qreg = LineQubit.range(3)
circ = Circuit(
ops.H.on_each(*qreg),
ops.CNOT.on(qreg[0], qreg[1]),
ops.T.on(qreg[2]),
ops.ISWAP.on(qreg[1], qreg[0]),
ops.TOFFOLI.on(*qreg),
ops.measure_each(*qreg),
)
# Measurement gates should be ignored
fidelities = {
"H": 0.9,
"CNOT": 0.8,
"T": 0.7,
"TOFFOLI": 0.6,
"ISWAP": 0.5,
}
weight_mask = _create_weight_mask(circ, fidelities)
assert np.allclose(weight_mask, [0.1, 0.1, 0.1, 0.2, 0.3, 0.5, 0.4])
fidelities = {"single": 1.0, "double": 0.5, "triple": 0.1}
weight_mask = _create_weight_mask(circ, fidelities)
assert np.allclose(weight_mask, [0.0, 0.0, 0.0, 0.5, 0.0, 0.5, 0.9])
fidelities = {
"single": 1.0,
"double": 1.0,
"H": 0.1,
"CNOT": 0.2,
"TOFFOLI": 0.3,
}
weight_mask = _create_weight_mask(circ, fidelities)
assert np.allclose(weight_mask, [0.9, 0.9, 0.9, 0.8, 0.0, 0.0, 0.7])
fidelities = {"waitgate": 1.0, "H": 0.1}
with pytest.warns(UserWarning, match="don't currently support"):
weight_mask = _create_weight_mask(circ, fidelities)
def test_create_fold_mask_with_real_scale_factors_at_random():
fold_mask = _create_fold_mask(
weight_mask=[0.1, 0.2, 0.3, 0.0],
scale_factor=1.0,
seed=1,
)
assert fold_mask == [0, 0, 0, 0]
fold_mask = _create_fold_mask(
weight_mask=[0.1, 0.1, 0.1, 0.1, 0.0],
scale_factor=1.5,
seed=2,
)
assert fold_mask == [0, 0, 1, 0, 0]
fold_mask = _create_fold_mask(
weight_mask=[1, 1, 1, 1],
scale_factor=2,
seed=3,
)
assert fold_mask == [0, 1, 0, 1]
fold_mask = _create_fold_mask(
weight_mask=[1, 1, 1, 1],
scale_factor=3.9,
seed=7,
)
assert fold_mask == [1, 2, 2, 1]
def test_create_fold_mask_approximates_well():
"""Check _create_fold_mask well approximates the scale factor."""
rnd_state = np.random.RandomState(seed=0)
for scale_factor in [1, 1.5, 1.7, 2.7, 6.7, 18.7, 19.0, 31]:
weight_mask = [rnd_state.rand() for _ in range(100)]
seed = rnd_state.randint(100)
fold_mask = _create_fold_mask(
weight_mask,
scale_factor,
seed=seed,
)
out_weights = [w + 2 * n * w for w, n in zip(weight_mask, fold_mask)]
actual_scale = sum(out_weights) / sum(weight_mask)
# Less than 1% error
assert np.isclose(scale_factor / actual_scale, 1.0, atol=0.01)
def test_apply_fold_mask():
# Test circuit
# 0: ───H───@───@───M───
# │ │
# 1: ───H───X───@───M───
# │
# 2: ───H───T───X───M───
qreg = LineQubit.range(3)
circ = Circuit(
[ops.H.on_each(*qreg)],
[ops.CNOT.on(qreg[0], qreg[1])],
[ops.T.on(qreg[2])],
[ops.TOFFOLI.on(*qreg)],
[ops.measure_each(*qreg)],
)
folded = _apply_fold_mask(circ, [0, 0, 0, 0, 0, 0])
assert _equal(folded, circ)
folded = _apply_fold_mask(circ, [1, 1, 1, 0, 0, 0])
correct = Circuit([ops.H.on_each(*qreg)] * 2) + circ
assert _equal(folded, correct)
folded = _apply_fold_mask(circ, [0, 0, 0, 0, 0, 2])
correct = circ[:-1] + Circuit([ops.TOFFOLI.on(*qreg)] * 4) + circ[-1]
assert _equal(folded, correct)
folded = _apply_fold_mask(circ, [0, 3, 0, 0, 0, 0])
correct = Circuit([ops.H.on(qreg[1])] * 6) + circ
assert _equal(folded, _squash_moments(correct))
folded = _apply_fold_mask(circ, [0, 0, 1, 0, 0, 0])
correct = Circuit([ops.H.on(qreg[2])] * 2 + circ)
assert _equal(folded, _squash_moments(correct))
folded = _apply_fold_mask(circ, [1, 1, 1, 1, 1, 1])
correct = Circuit(
[ops.H.on_each(*qreg)] * 3,
[ops.CNOT.on(qreg[0], qreg[1])] * 3,
[ops.T.on(qreg[2]), inverse(ops.T.on(qreg[2])), ops.T.on(qreg[2])],
[ops.TOFFOLI.on(*qreg)] * 3,
[ops.measure_each(*qreg)],
)
assert _equal(folded, correct)
def test_apply_fold_mask_wrong_size():
qreg = LineQubit(0)
circ = Circuit(ops.H(qreg))
with pytest.raises(ValueError, match="have incompatible sizes"):
_ = _apply_fold_mask(circ, [1, 1])
def test_apply_fold_mask_with_squash_moments_option():
# Test circuit:
# 0: ───T────────
#
# 1: ───T────H───
q = LineQubit.range(2)
circ = Circuit(
[ops.T.on_each(*q), ops.H(q[1])],
)
folded = _apply_fold_mask(circ, [1, 0, 0], squash_moments=False)
# 0: ───T───T^-1───T───────
#
# 1: ───T──────────────H───
correct = Circuit(
[ops.T.on_each(*q), inverse(ops.T(q[0])), ops.T(q[0])],
) + Circuit(ops.H(q[1]))
assert _equal(folded, correct)
# If 2 gates of the same moment are folded,
# only 2 moments should be created and not 4.
folded = _apply_fold_mask(circ, [1, 1, 0], squash_moments=False)
# 0: ───T───T^-1───T───────
#
# 1: ───T───T^-1───T────H───
correct = Circuit(
[
ops.T.on_each(*q),
inverse(ops.T.on_each(*q)),
ops.T.on_each(*q),
ops.H(q[1]),
],
)
assert _equal(folded, correct)
folded = _apply_fold_mask(circ, [1, 0, 0], squash_moments=True)
# 0: ───T───T^-1───T───
#
# 1: ───T───H──────────
correct = Circuit(
[ops.T.on_each(*q), inverse(ops.T(q[0])), ops.T(q[0]), ops.H(q[1])],
)
assert _equal(folded, correct)
@pytest.mark.parametrize(
"fold_method",
(
fold_gates_at_random,
fold_global,
),
)
def test_scaling_with_pyquil_retains_declarations(fold_method):
program = Program()
theta = program.declare("theta", memory_type="REAL")
_ = program.declare("beta", memory_type="REAL")
program += gates.RY(theta, 0)
scaled = fold_method(program, 1)
assert scaled.declarations == program.declarations
|
https://github.com/unitaryfund/mitiq
|
unitaryfund
|
# Copyright (C) Unitary Fund
#
# This source code is licensed under the GPL license (v3) found in the
# LICENSE file in the root directory of this source tree.
"""Unit tests for zero-noise extrapolation."""
import functools
from typing import List
import cirq
import numpy as np
import pytest
import qiskit
import qiskit.circuit
from qiskit_aer import AerSimulator
from mitiq import QPROGRAM, SUPPORTED_PROGRAM_TYPES
from mitiq.benchmarks.randomized_benchmarking import generate_rb_circuits
from mitiq.interface import accept_any_qprogram_as_input, convert_from_mitiq
from mitiq.interface.mitiq_cirq import (
compute_density_matrix,
sample_bitstrings,
)
from mitiq.interface.mitiq_qiskit import (
execute_with_shots_and_noise,
initialized_depolarizing_noise,
)
from mitiq.observable import Observable, PauliString
from mitiq.zne import (
execute_with_zne,
inference,
mitigate_executor,
scaling,
zne_decorator,
)
from mitiq.zne.inference import (
AdaExpFactory,
LinearFactory,
PolyFactory,
RichardsonFactory,
)
from mitiq.zne.scaling import (
fold_gates_at_random,
get_layer_folding,
insert_id_layers,
)
BASE_NOISE = 0.007
TEST_DEPTH = 30
ONE_QUBIT_GS_PROJECTOR = np.array([[1, 0], [0, 0]])
npX = np.array([[0, 1], [1, 0]])
"""Defines the sigma_x Pauli matrix in SU(2) algebra as a (2,2) `np.array`."""
npZ = np.array([[1, 0], [0, -1]])
"""Defines the sigma_z Pauli matrix in SU(2) algebra as a (2,2) `np.array`."""
# Default qubit register and circuit for unit tests
qreg = cirq.GridQubit.rect(2, 1)
circ = cirq.Circuit(cirq.ops.H.on_each(*qreg), cirq.measure_each(*qreg))
@accept_any_qprogram_as_input
def generic_executor(circuit, noise_level: float = 0.1) -> float:
"""Executor that simulates a circuit of any type and returns
the expectation value of the ground state projector."""
noisy_circuit = circuit.with_noise(cirq.depolarize(p=noise_level))
result = cirq.DensityMatrixSimulator().simulate(noisy_circuit)
return result.final_density_matrix[0, 0].real
# Default executor for unit tests
def executor(circuit) -> float:
wavefunction = circuit.final_state_vector(
ignore_terminal_measurements=True
)
return np.real(wavefunction.conj().T @ np.kron(npX, npZ) @ wavefunction)
@pytest.mark.parametrize(
"executor", (sample_bitstrings, compute_density_matrix)
)
def test_with_observable_batched_factory(executor):
observable = Observable(PauliString(spec="Z"))
circuit = cirq.Circuit(cirq.H.on(cirq.LineQubit(0))) * 20
noisy_value = observable.expectation(circuit, sample_bitstrings)
zne_value = execute_with_zne(
circuit,
executor=functools.partial(
executor, noise_model_function=cirq.depolarize
),
observable=observable,
factory=PolyFactory(scale_factors=[1, 3, 5], order=2),
)
true_value = observable.expectation(
circuit, functools.partial(compute_density_matrix, noise_level=(0,))
)
assert abs(zne_value - true_value) <= abs(noisy_value - true_value)
@pytest.mark.parametrize(
"executor", (sample_bitstrings, compute_density_matrix)
)
def test_with_observable_adaptive_factory(executor):
observable = Observable(PauliString(spec="Z"))
circuit = cirq.Circuit(cirq.H.on(cirq.LineQubit(0))) * 20
noisy_value = observable.expectation(circuit, sample_bitstrings)
zne_value = execute_with_zne(
circuit,
executor=functools.partial(
executor, noise_model_function=cirq.amplitude_damp
),
observable=observable,
factory=AdaExpFactory(steps=4, asymptote=0.5),
)
true_value = observable.expectation(
circuit, functools.partial(compute_density_matrix, noise_level=(0,))
)
assert abs(zne_value - true_value) <= abs(noisy_value - true_value)
def test_with_observable_two_qubits():
observable = Observable(
PauliString(spec="XX", coeff=-1.21), PauliString(spec="ZZ", coeff=0.7)
)
circuit = cirq.Circuit(
cirq.H.on(cirq.LineQubit(0)), cirq.CNOT.on(*cirq.LineQubit.range(2))
)
circuit += [circuit.copy(), cirq.inverse(circuit.copy())] * 20
executor = compute_density_matrix
noisy_value = observable.expectation(circuit, executor)
zne_value = execute_with_zne(
circuit,
executor=functools.partial(
executor, noise_model_function=cirq.depolarize
),
observable=observable,
factory=PolyFactory(scale_factors=[1, 3, 5], order=2),
)
true_value = observable.expectation(
circuit, functools.partial(executor, noise_level=(0,))
)
assert abs(zne_value - true_value) <= 3 * abs(noisy_value - true_value)
@pytest.mark.parametrize(
"fold_method",
[
fold_gates_at_random,
insert_id_layers,
],
)
@pytest.mark.parametrize("factory", [LinearFactory, RichardsonFactory])
@pytest.mark.parametrize("num_to_average", [1, 2, 5])
def test_execute_with_zne_no_noise(fold_method, factory, num_to_average):
"""Tests execute_with_zne with noiseless simulation."""
zne_value = execute_with_zne(
circ,
executor,
num_to_average=num_to_average,
scale_noise=fold_method,
factory=factory([1.0, 2.0, 3.0]),
)
assert np.isclose(zne_value, 0.0)
@pytest.mark.parametrize("factory", [LinearFactory, RichardsonFactory])
@pytest.mark.parametrize(
"fold_method",
[
fold_gates_at_random,
insert_id_layers,
],
)
def test_averaging_improves_zne_value_with_fake_noise(factory, fold_method):
"""Tests that averaging with Gaussian noise produces a better ZNE value
compared to not averaging with several folding methods.
For non-deterministic folding, the ZNE value with average should be better.
For deterministic folding, the ZNE value should be the same.
"""
for seed in range(5):
rng = np.random.RandomState(seed)
def noisy_executor(circuit) -> float:
return executor(circuit) + rng.randn()
zne_value_no_averaging = execute_with_zne(
circ,
noisy_executor,
num_to_average=1,
scale_noise=fold_gates_at_random,
factory=factory([1.0, 2.0, 3.0]),
)
zne_value_averaging = execute_with_zne(
circ,
noisy_executor,
num_to_average=10,
scale_noise=fold_method,
factory=factory([1.0, 2.0, 3.0]),
)
# True (noiseless) value is zero. Averaging should ==> closer to zero.
assert abs(zne_value_averaging) <= abs(zne_value_no_averaging)
def test_execute_with_zne_bad_arguments():
"""Tests errors are raised when execute_with_zne is called with bad
arguments.
"""
with pytest.raises(TypeError, match="Argument `factory` must be of type"):
execute_with_zne(circ, executor, factory=RichardsonFactory)
with pytest.raises(TypeError, match="Argument `scale_noise` must be"):
execute_with_zne(circ, executor, scale_noise=None)
def test_error_zne_decorator():
"""Tests that the proper error is raised if the decorator is
used without parenthesis.
"""
with pytest.raises(TypeError, match="Decorator must be used with paren"):
@zne_decorator
def test_executor(circuit):
return 0
def test_doc_is_preserved():
"""Tests that the doc of the original executor is preserved."""
def first_executor(circuit):
"""Doc of the original executor."""
return 0
mit_executor = mitigate_executor(first_executor)
assert mit_executor.__doc__ == first_executor.__doc__
@zne_decorator()
def second_executor(circuit):
"""Doc of the original executor."""
return 0
assert second_executor.__doc__ == first_executor.__doc__
def qiskit_measure(circuit, qid) -> qiskit.QuantumCircuit:
"""Helper function to measure one qubit."""
# Ensure that we have a classical register of enough size available
if len(circuit.clbits) == 0:
reg = qiskit.ClassicalRegister(qid + 1, "cbits")
circuit.add_register(reg)
circuit.measure(0, qid)
return circuit
def qiskit_executor(qp: QPROGRAM, shots: int = 10000) -> float:
# initialize a qiskit noise model
expectation = execute_with_shots_and_noise(
qp,
shots=shots,
obs=ONE_QUBIT_GS_PROJECTOR,
noise_model=initialized_depolarizing_noise(BASE_NOISE),
seed=1,
)
return expectation
def get_counts(circuit: qiskit.QuantumCircuit):
return AerSimulator().run(circuit, shots=100).result().get_counts()
def test_qiskit_execute_with_zne():
true_zne_value = 1.0
circuit = qiskit_measure(
*generate_rb_circuits(
n_qubits=1,
num_cliffords=TEST_DEPTH,
trials=1,
return_type="qiskit",
),
0,
)
base = qiskit_executor(circuit)
zne_value = execute_with_zne(circuit, qiskit_executor)
assert abs(true_zne_value - zne_value) < abs(true_zne_value - base)
@zne_decorator()
def qiskit_decorated_executor(qp: QPROGRAM) -> float:
return qiskit_executor(qp)
def batched_qiskit_executor(circuits) -> List[float]:
return [qiskit_executor(circuit) for circuit in circuits]
def test_qiskit_mitigate_executor():
true_zne_value = 1.0
circuit = qiskit_measure(
*generate_rb_circuits(
n_qubits=1,
num_cliffords=TEST_DEPTH,
trials=1,
return_type="qiskit",
),
0,
)
base = qiskit_executor(circuit)
mitigated_executor = mitigate_executor(qiskit_executor)
zne_value = mitigated_executor(circuit)
assert abs(true_zne_value - zne_value) < abs(true_zne_value - base)
batched_mitigated_executor = mitigate_executor(batched_qiskit_executor)
batched_zne_values = batched_mitigated_executor([circuit] * 3)
assert [
abs(true_zne_value - batched_zne_value) < abs(true_zne_value - base)
for batched_zne_value in batched_zne_values
]
def test_qiskit_zne_decorator():
true_zne_value = 1.0
circuit = qiskit_measure(
*generate_rb_circuits(
n_qubits=1,
num_cliffords=TEST_DEPTH,
trials=1,
return_type="qiskit",
),
0,
)
base = qiskit_executor(circuit)
zne_value = qiskit_decorated_executor(circuit)
assert abs(true_zne_value - zne_value) < abs(true_zne_value - base)
def test_qiskit_run_factory_with_number_of_shots():
true_zne_value = 1.0
scale_factors = [1.0, 3.0]
shot_list = [10_000, 30_000]
fac = inference.ExpFactory(
scale_factors=scale_factors,
shot_list=shot_list,
asymptote=0.5,
)
circuit = qiskit_measure(
*generate_rb_circuits(
n_qubits=1,
num_cliffords=TEST_DEPTH,
trials=1,
return_type="qiskit",
),
0,
)
base = qiskit_executor(circuit)
zne_value = fac.run(
circuit,
qiskit_executor,
scale_noise=scaling.fold_gates_at_random,
).reduce()
assert abs(true_zne_value - zne_value) < abs(true_zne_value - base)
for i in range(len(fac._instack)):
assert fac._instack[i] == {
"scale_factor": scale_factors[i],
"shots": shot_list[i],
}
def test_qiskit_mitigate_executor_with_shot_list():
true_zne_value = 1.0
scale_factors = [1.0, 3.0]
shot_list = [10_000, 30_000]
fac = inference.ExpFactory(
scale_factors=scale_factors,
shot_list=shot_list,
asymptote=0.5,
)
mitigated_executor = mitigate_executor(qiskit_executor, factory=fac)
circuit = qiskit_measure(
*generate_rb_circuits(
n_qubits=1,
num_cliffords=TEST_DEPTH,
trials=1,
return_type="qiskit",
),
0,
)
base = qiskit_executor(circuit)
zne_value = mitigated_executor(circuit)
assert abs(true_zne_value - zne_value) < abs(true_zne_value - base)
for i in range(len(fac._instack)):
assert fac._instack[i] == {
"scale_factor": scale_factors[i],
"shots": shot_list[i],
}
@pytest.mark.parametrize("order", [(0, 1), (1, 0), (0, 1, 2), (1, 2, 0)])
def test_qiskit_measurement_order_is_preserved_single_register(order):
"""Tests measurement order is preserved when folding, i.e., the dictionary
of counts is the same as the original circuit on a noiseless simulator.
"""
qreg, creg = (
qiskit.QuantumRegister(len(order)),
qiskit.ClassicalRegister(len(order)),
)
circuit = qiskit.QuantumCircuit(qreg, creg)
circuit.x(qreg[0])
for i in order:
circuit.measure(qreg[i], creg[i])
folded = scaling.fold_gates_at_random(circuit, scale_factor=1.0)
assert get_counts(folded) == get_counts(circuit)
def test_qiskit_measurement_order_is_preserved_two_registers():
"""Tests measurement order is preserved when folding, i.e., the dictionary
of counts is the same as the original circuit on a noiseless simulator.
"""
n = 4
qreg = qiskit.QuantumRegister(n)
creg1, creg2 = (
qiskit.ClassicalRegister(n // 2),
qiskit.ClassicalRegister(n // 2),
)
circuit = qiskit.QuantumCircuit(qreg, creg1, creg2)
circuit.x(qreg[0])
circuit.x(qreg[2])
# Some order of measurements.
circuit.measure(qreg[0], creg2[1])
circuit.measure(qreg[1], creg1[0])
circuit.measure(qreg[2], creg1[1])
circuit.measure(qreg[3], creg2[1])
folded = scaling.fold_gates_at_random(circuit, scale_factor=1.0)
assert get_counts(folded) == get_counts(circuit)
@pytest.mark.parametrize("circuit_type", SUPPORTED_PROGRAM_TYPES.keys())
def test_execute_with_zne_with_supported_circuits(circuit_type):
# Define a circuit equivalent to the identity
qreg = cirq.LineQubit.range(2)
cirq_circuit = cirq.Circuit(
cirq.H.on_each(qreg),
cirq.CNOT(*qreg),
cirq.CNOT(*qreg),
cirq.H.on_each(qreg),
)
# Convert to one of the supported program types
circuit = convert_from_mitiq(cirq_circuit, circuit_type)
expected = generic_executor(circuit, noise_level=0.0)
unmitigated = generic_executor(circuit)
# Use odd scale factors for deterministic results
fac = RichardsonFactory([1.0, 3.0, 5.0])
zne_value = execute_with_zne(circuit, generic_executor, factory=fac)
# Test zero noise limit is better than unmitigated expectation value
assert abs(unmitigated - expected) > abs(zne_value - expected)
@pytest.mark.parametrize("circuit_type", SUPPORTED_PROGRAM_TYPES.keys())
def test_layerwise_execute_with_zne_with_supported_circuits(circuit_type):
# Define a circuit equivalent to the identity
qreg = cirq.LineQubit.range(2)
cirq_circuit = cirq.Circuit(
cirq.H.on_each(qreg),
cirq.CNOT(*qreg),
cirq.CNOT(*qreg),
cirq.H.on_each(qreg),
)
# Convert to one of the supported program types
circuit = convert_from_mitiq(cirq_circuit, circuit_type)
expected = generic_executor(circuit, noise_level=0.0)
unmitigated = generic_executor(circuit)
# Use odd scale factors for deterministic results
fac = RichardsonFactory([1, 3, 5])
# Layerwise-fold
layer_to_fold = 0
fold_layer_func = get_layer_folding(layer_to_fold)
zne_value = execute_with_zne(
circuit, generic_executor, factory=fac, scale_noise=fold_layer_func
)
# Test zero noise limit is better than unmitigated expectation value
assert abs(unmitigated - expected) > abs(zne_value - expected)
def test_execute_with_zne_transpiled_qiskit_circuit():
"""Tests ZNE when transpiling to a Qiskit device. Note transpiling can
introduce idle (unused) qubits to the circuit.
"""
from qiskit_ibm_runtime.fake_provider import FakeSantiago
santiago = FakeSantiago()
backend = AerSimulator.from_backend(santiago)
def execute(circuit: qiskit.QuantumCircuit, shots: int = 8192) -> float:
job = backend.run(circuit, shots=shots)
return job.result().get_counts().get("00", 0.0) / shots
qreg = qiskit.QuantumRegister(2)
creg = qiskit.ClassicalRegister(2)
circuit = qiskit.QuantumCircuit(qreg, creg)
for _ in range(10):
circuit.x(qreg)
circuit.measure(qreg, creg)
circuit = qiskit.transpile(circuit, backend, optimization_level=0)
true_value = 1.0
zne_value = execute_with_zne(circuit, execute)
# Note: Unmitigated value is also (usually) within 10% of the true value.
# This is more to test usage than effectiveness.
assert abs(zne_value - true_value) < 0.1
def test_execute_zne_on_qiskit_circuit_with_QFT():
"""Tests ZNE of a Qiskit device with a QFT gate."""
def qs_noisy_simulation(
circuit: qiskit.QuantumCircuit, shots: int = 1
) -> float:
noise_model = initialized_depolarizing_noise(noise_level=0.02)
backend = AerSimulator(noise_model=noise_model)
job = backend.run(circuit.decompose(), shots=shots)
return job.result().get_counts().get("0", 0.0) / shots
circuit = qiskit.QuantumCircuit(1)
circuit &= qiskit.circuit.library.QFT(1)
circuit.measure_all()
mitigated = execute_with_zne(circuit, qs_noisy_simulation)
assert abs(mitigated) < 1000
|
https://github.com/Sentdex/QuantumComputing
|
Sentdex
|
import qiskit as q
%matplotlib inline
circuit = q.QuantumCircuit(2,2) # 2 qubits, 2 classical bits
circuit.x(0) # not gate, flips qubit 0.
circuit.cx(0, 1) #cnot, controlled not, Flips 2nd qubit's value if first qubit is 1
circuit.measure([0,1], [0,1]) # ([qbitregister], [classicalbitregister]) Measure qubit 0 and 1 to classical bits 0 and 1
circuit.draw() # text-based visualization. (pretty cool ...actually! Nice job whoever did this.)
circuit.draw(output="mpl") # matplotlib-based visualization.
from qiskit import IBMQ
IBMQ.save_account(open("token.txt","r").read())
IBMQ.load_account()
IBMQ.providers()
provider = IBMQ.get_provider("ibm-q")
for backend in provider.backends():
try:
qubit_count = len(backend.properties().qubits)
except:
qubit_count = "simulated"
print(f"{backend.name()} has {backend.status().pending_jobs} queued and {qubit_count} qubits")
from qiskit.tools.monitor import job_monitor
backend = provider.get_backend("ibmq_london")
job = q.execute(circuit, backend=backend, shots=500)
job_monitor(job)
from qiskit.visualization import plot_histogram
from matplotlib import style
style.use("dark_background") # I am using dark mode notebook, so I use this to see the chart.
result = job.result()
counts = result.get_counts(circuit)
plot_histogram([counts], legend=['Device'])
circuit = q.QuantumCircuit(2,2) # 2 qbits, 2 classical bits.
circuit.h(0) # Hadamard gate, puts qubit 0 into superposition
circuit.cx(0, 1) #cnot, controlled not, Flips 2nd qubit's value if first qubit is 1
circuit.measure([0,1], [0,1]) # ([qbitregister], [classicalbitregister]) Measure qubit 0 and 1 to classical bits 0 and 1
circuit.draw(output="mpl")
backend = provider.get_backend("ibmq_london")
job = q.execute(circuit, backend=backend, shots=500)
job_monitor(job)
result = job.result()
counts = result.get_counts(circuit)
plot_histogram([counts], legend=['Device'])
from qiskit import Aer # simulator framework from qiskit
# will create a statevector of possibilities.
sim_backend = Aer.get_backend('qasm_simulator')
for backend in Aer.backends():
print(backend)
job = q.execute(circuit, backend=sim_backend, shots=500)
job_monitor(job)
result = job.result()
counts = result.get_counts(circuit)
plot_histogram([counts], legend=['Device'])
|
https://github.com/qiskit-community/qiskit-qcgpu-provider
|
qiskit-community
|
import click
import time
import random
import statistics
import csv
import os.path
import math
from qiskit import ClassicalRegister, QuantumRegister, QuantumCircuit
from qiskit import QiskitError, execute, Aer
from qiskit_qcgpu_provider import QCGPUProvider
# Implementation of the Quantum Fourier Transform
def construct_circuit(num_qubits):
q = QuantumRegister(num_qubits)
c = ClassicalRegister(num_qubits)
circ = QuantumCircuit(q, c)
# Quantum Fourier Transform
for j in range(num_qubits):
for k in range(j):
circ.cu1(math.pi / float(2**(j - k)), q[j], q[k])
circ.h(q[j])
# circ.measure(q, c)
return circ
# Benchmarking functions
# qiskit_backend = Aer.get_backend('qasm_simulator')
# qcgpu_backend = QCGPUProvider().get_backend('qasm_simulator')
qiskit_backend = Aer.get_backend('statevector_simulator')
qcgpu_backend = QCGPUProvider().get_backend('statevector_simulator')
def bench_qiskit(qc):
start = time.time()
job_sim = execute(qc, qiskit_backend)
sim_result = job_sim.result()
return time.time() - start
def bench_qcgpu(qc):
start = time.time()
job_sim = execute(qc, qcgpu_backend)
sim_result = job_sim.result()
return time.time() - start
# Reporting
def create_csv(filename):
file_exists = os.path.isfile(filename)
csvfile = open(filename, 'a')
headers = ['name', 'num_qubits', 'time']
writer = csv.DictWriter(csvfile, delimiter=',', lineterminator='\n', fieldnames=headers)
if not file_exists:
writer.writeheader() # file doesn't exist yet, write a header
return writer
def write_csv(writer, data):
writer.writerow(data)
@click.command()
@click.option('--samples', default=5, help='Number of samples to take for each qubit.')
@click.option('--qubits', default=5, help='How many qubits you want to test for')
@click.option('--out', default='benchmark_data.csv',
help='Where to store the CSV output of each test')
@click.option(
'--single',
default=False,
help='Only run the benchmark for a single amount of qubits, and print an analysis')
@click.option('--burn', default=True, help='Burn the first few samples for accuracy')
def benchmark(samples, qubits, out, single, burn):
burn_count = 5 if burn else 0
if single:
functions = bench_qcgpu, bench_qiskit
times = {f.__name__: [] for f in functions}
names = []
means = []
qc = construct_circuit(qubits)
# Run the benchmarks
for i in range(samples + burn_count):
progress = (i) / (samples + burn_count)
if samples > 1:
print("\rProgress: [{0:50s}] {1:.1f}%".format('#' * int(progress * 50), progress * 100), end="", flush=True)
func = random.choice(functions)
t = func(qc)
if i >= burn_count:
times[func.__name__].append(t)
print('')
for name, numbers in times.items():
print('FUNCTION:', name, 'Used', len(numbers), 'times')
print('\tMEDIAN', statistics.median(numbers))
print('\tMEAN ', statistics.mean(numbers))
if len(numbers) > 1:
print('\tSTDEV ', statistics.stdev(numbers))
return
functions = bench_qcgpu, bench_qiskit
writer = create_csv(out)
for n in range(1, qubits):
# Progress counter
progress = (n + 1) / (qubits)
print("\rProgress: [{0:50s}] {1:.1f}%".format('#' * int(progress * 50), progress * 100), end="", flush=True)
# Construct the circuit
qc = construct_circuit(n + 1)
# Run the benchmarks
for i in range(samples):
func = random.choice(functions)
t = func(qc)
# times[func.__name__].append(t)
write_csv(writer, {'name': func.__name__, 'num_qubits': n + 1, 'time': t})
if __name__ == '__main__':
benchmark()
|
https://github.com/qiskit-community/qiskit-qcgpu-provider
|
qiskit-community
|
"""
Example used in the README. In this example a Bell state is made.
"""
# Import the Qiskit
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, QiskitError
from qiskit import execute
from qiskit_qcgpu_provider import QCGPUProvider
# Create a Quantum Register with 2 qubits.
q = QuantumRegister(2)
# Create a Classical Register with 2 bits.
c = ClassicalRegister(2)
# Create a Quantum Circuit
qc = QuantumCircuit(q, c)
# Add a H gate on qubit 0, putting this qubit in superposition.
qc.h(q[0])
# Add a CX (CNOT) gate on control qubit 0 and target qubit 1, putting
# the qubits in a Bell state.
qc.cx(q[0], q[1])
# Add a Measure gate to see the state.
qc.measure(q, c)
# Get the QCGPU Provider
Provider = QCGPUProvider()
# See a list of available local simulators
print("QCGPU backends: ", Provider.backends())
backend_sim = Provider.get_backend('qasm_simulator')
# Compile and run the Quantum circuit on a simulator backend
job_sim = execute(qc, backend_sim)
result_sim = job_sim.result()
# Show the results
print(result_sim.get_counts(qc))
|
https://github.com/qiskit-community/qiskit-qcgpu-provider
|
qiskit-community
|
"""
In this example a Bell state is made.
"""
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit import execute
from qiskit_qcgpu_provider import QCGPUProvider
Provider = QCGPUProvider()
# Create a Quantum Register with 2 qubits.
q = QuantumRegister(2)
# Create a Quantum Circuit with 2 Qubits
qc = QuantumCircuit(q)
# Add a H gate on qubit 0, putting this qubit in superposition.
qc.h(q[0])
# Add a CX (CNOT) gate on control qubit 0 and target qubit 1, putting
# the qubits in a Bell state.
qc.cx(q[0], q[1])
# See a list of available local simulators
print("QCGPU backends: ", Provider.backends())
backend_sim = Provider.get_backend('statevector_simulator')
# Compile and run the Quantum circuit on a simulator backend
job_sim = execute(qc, backend_sim)
result_sim = job_sim.result()
# Show the results
print("Simulation Results: ", result_sim)
print(result_sim.get_statevector(qc))
|
https://github.com/qiskit-community/qiskit-qcgpu-provider
|
qiskit-community
|
from qiskit_chemistry import QiskitChemistry
from qiskit import Aer
qiskit_chemistry_dict = {
'driver': {'name': 'HDF5'},
'HDF5': {'hdf5_input': '0.7_sto-3g.hdf5'},
'operator': {'name': 'hamiltonian'},
'algorithm': {'name': 'VQE'},
'optimizer': {'name': 'COBYLA'},
'variational_form': {'name': 'UCCSD'},
'initial_state': {'name': 'HartreeFock'}
}
from qiskit import Aer
backend = Aer.get_backend('statevector_simulator')
solver = QiskitChemistry()
%time result = solver.run(qiskit_chemistry_dict, backend=backend)
from qiskit_qcgpu_provider import QCGPUProvider
backend = QCGPUProvider().get_backend('statevector_simulator')
solver = QiskitChemistry()
%time result = solver.run(qiskit_chemistry_dict, backend=backend)
for line in result['printable']:
print(line)
|
https://github.com/qiskit-community/qiskit-qcgpu-provider
|
qiskit-community
|
from qiskit_aqua import run_algorithm
from qiskit_qcgpu_provider import QCGPUProvider
sat_cnf = """
c Example DIMACS 3-sat
p cnf 3 5
-1 -2 -3 0
1 -2 3 0
1 2 -3 0
1 -2 -3 0
-1 2 3 0
"""
params = {
"problem": { "name": "search" },
"algorithm": { "name": "Grover" },
"oracle": { "name": "SAT", "cnf": sat_cnf },
"backend": { "name": "qasm_simulator" }
}
backend = QCGPUProvider().get_backend('qasm_simulator')
%time result_qiskit = run_algorithm(params)
%time result = run_algorithm(params, backend=backend)
print(result["result"])
|
https://github.com/qiskit-community/qiskit-qcgpu-provider
|
qiskit-community
|
import matplotlib.pyplot as ply
%matplotlib inline
import networkx as nx
import numpy as np
from qiskit_aqua.translators.ising import maxcut
from qiskit_aqua.input import EnergyInput
from qiskit_aqua import run_algorithm
from qiskit_qcgpu_provider import QCGPUProvider
nodes = 5
edges = [
# Tuple (i, j, weight),
# where (i, j) is an edge.
(0, 1, 1.0),
(0, 2, 1.0),
(1, 2, 1.0),
(1, 4, 1.0),
(3, 4, 1.0),
(2, 3, 1.0)
]
G = nx.Graph()
G.add_nodes_from(np.arange(0, nodes, 1))
G.add_weighted_edges_from(edges)
nx.draw(G, with_labels=True)
# Computing the weight matrix
weights = np.zeros([nodes, nodes])
for i in range(nodes):
for j in range(nodes):
edge_data = G.get_edge_data(i, j, default = None)
# check if there is no edge
if edge_data != None:
weights[i, j] = edge_data['weight']
weights
# Calculate the max cut
best = 0
for b in range(2**nodes):
x = [int(t) for t in reversed(list(bin(b)[2:].zfill(nodes)))]
cost = 0
for i in range(nodes):
for j in range(nodes):
cost = cost + weights[i,j]*x[i]*(1-x[j])
if best < cost:
best = cost
xbest_brute = x
# print('case = ' + str(x)+ ' cost = ' + str(cost))
print('Optimal Solution: case = ' + str(xbest_brute) + ', cost = ' + str(best))
# Plot the optimal solution
colors = ['r' if xbest_brute[i] == 0 else 'b' for i in range(nodes)]
nx.draw(G, node_color=colors, with_labels=True)
operator, offset = maxcut.get_maxcut_qubitops(weights)
algorithm_input = EnergyInput(operator)
algorithm_parameters = {
'problem': { 'name': 'ising', 'random_seed': 3242 },
'algorithm': { 'name': 'VQE', 'operator_mode': 'matrix' },
'optimizer': { 'name': 'SPSA', 'max_trials': 300 },
'variational_form': {'name': 'RY', 'depth': 5, 'entanglement': 'linear'}
}
backend = QCGPUProvider().get_backend('statevector_simulator')
%time result_qiskit = run_algorithm(algorithm_parameters, algorithm_input, backend=backend)
%time result = run_algorithm(algorithm_parameters, algorithm_input, backend=backend)
x = maxcut.sample_most_likely(result['eigvecs'][0])
print('energy:', result['energy'])
print('maxcut objective:', result['energy'] + offset)
print('solution:', maxcut.get_graph_solution(x))
print('solution objective:', maxcut.maxcut_value(x, weights))
colors = ['r' if maxcut.get_graph_solution(x)[i] == 0 else 'b' for i in range(nodes)]
nx.draw(G, node_color=colors, with_labels=True)
import warnings
warnings.filterwarnings('ignore')
|
https://github.com/qiskit-community/qiskit-qcgpu-provider
|
qiskit-community
|
import numpy as np
import scipy
from scipy.linalg import expm
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler, MinMaxScaler
from sklearn.decomposition import PCA
def breast_cancer(training_size, test_size, n, PLOT_DATA=True):
class_labels = [r'Benign', r'Malignant']
# First the dataset must be imported.
cancer = datasets.load_breast_cancer()
# To find if the classifier is accurate, a common strategy is
# to divide the dataset into a training set and a test set.
# Here the data is divided into 70% training, 30% testing.
X_train, X_test, Y_train, Y_test = train_test_split(cancer.data, cancer.target, test_size=0.3, random_state=109)
# Now the dataset's features will be standardized
# to fit a normal distribution.
scaler = StandardScaler().fit(X_train)
X_train = scaler.transform(X_train)
X_test = scaler.transform(X_test)
# To be able to use this data with the given
# number of qubits, the data must be broken down from
# 30 dimensions to `n` dimensions.
# This is done with Principal Component Analysis (PCA),
# which finds patterns while keeping variation.
pca = PCA(n_components=n).fit(X_train)
X_train = pca.transform(X_train)
X_test = pca.transform(X_test)
# The last step in the data processing is
# to scale the data to be between -1 and 1
samples = np.append(X_train, X_test, axis=0)
minmax_scale = MinMaxScaler((-1, 1)).fit(samples)
X_train = minmax_scale.transform(X_train)
X_test = minmax_scale.transform(X_test)
# Now some sample should be picked to train the model from
training_input = {key: (X_train[Y_train == k, :])[:training_size] for k, key in enumerate(class_labels)}
test_input = {key: (X_train[Y_train == k, :])[training_size:(
training_size+test_size)] for k, key in enumerate(class_labels)}
if PLOT_DATA:
for k in range(0, 2):
x_axis_data = X_train[Y_train == k, 0][:training_size]
y_axis_data = X_train[Y_train == k, 1][:training_size]
label = 'Malignant' if k is 1 else 'Benign'
plt.scatter(x_axis_data, y_axis_data, label=label)
plt.title("Breast Cancer Dataset (Dimensionality Reduced With PCA)")
plt.legend()
plt.show()
return X_train, training_input, test_input, class_labels
from qiskit_aqua.utils import split_dataset_to_data_and_labels
n = 2 # How many features to use (dimensionality)
training_dataset_size = 20
testing_dataset_size = 10
sample_Total, training_input, test_input, class_labels = breast_cancer(training_dataset_size, testing_dataset_size, n)
datapoints, class_to_label = split_dataset_to_data_and_labels(test_input)
print(class_to_label)
from qiskit_aqua.input import SVMInput
from qiskit_qcgpu_provider import QCGPUProvider
from qiskit_aqua import run_algorithm
params = {
'problem': {'name': 'svm_classification', 'random_seed': 10598},
'algorithm': { 'name': 'QSVM.Kernel' },
'backend': {'name': 'qasm_simulator', 'shots': 1024},
'feature_map': {'name': 'SecondOrderExpansion', 'depth': 2, 'entanglement': 'linear'}
}
backend = QCGPUProvider().get_backend('qasm_simulator')
algo_input = SVMInput(training_input, test_input, datapoints[0])
%time result = run_algorithm(params, algo_input)
%time result = run_algorithm(params, algo_input, backend=backend)
print("ground truth: {}".format(datapoints[1]))
print("prediction: {}".format(result['predicted_labels']))
print("predicted class: {}".format(result['predicted_classes']))
print("accuracy: {}".format(result['testing_accuracy']))
|
https://github.com/qiskit-community/qiskit-qcgpu-provider
|
qiskit-community
|
import matplotlib.pyplot as ply
%matplotlib inline
import networkx as nx
import numpy as np
from qiskit_aqua.translators.ising import tsp
from qiskit_aqua.input import EnergyInput
from qiskit_aqua import run_algorithm
from qiskit_qcgpu_provider import QCGPUProvider
locations = 3
problem = tsp.random_tsp(locations)
positions = {k: v for k, v in enumerate(problem.coord)}
G = nx.Graph()
G.add_nodes_from(np.arange(0, locations, 1))
nx.draw(G, with_labels=True, pos=positions)
best_distance, best_order = brute_force(problem.w, problem.dim)
draw(G, best_order, positions)
operator, offset = tsp.get_tsp_qubitops(problem)
algorithm_input = EnergyInput(operator)
algorithm_parameters = {
'problem': { 'name': 'ising', 'random_seed': 23 },
'algorithm': { 'name': 'VQE', 'operator_mode': 'matrix' },
'optimizer': { 'name': 'SPSA', 'max_trials':100 },
'variational_form': {'name': 'RY', 'depth': 5, 'entanglement': 'linear'}
}
backend = QCGPUProvider().get_backend('statevector_simulator')
%time result_qiskit = run_algorithm(algorithm_parameters, algorithm_input)
%time result = run_algorithm(algorithm_parameters, algorithm_input, backend=backend)
#print('tsp objective:', result['energy'] + offset)
x = tsp.sample_most_likely(result['eigvecs'][0])
print('feasible:', tsp.tsp_feasible(x))
z = tsp.get_tsp_solution(x)
print('solution:', z)
print('solution objective:', tsp.tsp_value(z, problem.w))
draw(G, z, positions)
# Utitlity Functions
def draw(G, order, positions):
G2 = G.copy()
n = len(order)
for i in range(n):
j = (i + 1) % n
G2.add_edge(order[i], order[j])
nx.draw(G2, pos=positions, with_labels=True)
# Classically solve the problem using a brute-force method
from itertools import permutations
def brute_force(weights, N):
a = list(permutations(range(1, N)))
best_distance = None
for i in a:
distance = 0
pre_j = 0
for j in i:
distance += weights[j, pre_j]
pre_j = j
distance += weights[pre_j, 0]
order = (0,) + i
if best_distance is None or distance < best_distance:
best_order = order
best_distance = distance
return best_distance, best_order
import warnings
warnings.filterwarnings('ignore')
|
https://github.com/qiskit-community/qiskit-qcgpu-provider
|
qiskit-community
|
"""
Exception for errors raised by QCGPU simulators
"""
from qiskit import QiskitError
class QCGPUSimulatorError(QiskitError):
"""Base class for errors raised by simulators."""
def __init__(self, *message):
"""Set the error message"""
super().__init__(*message)
self.message = ' '.join(message)
def __str__(self):
"""Return the message"""
return repr(self.message)
|
https://github.com/qiskit-community/qiskit-qcgpu-provider
|
qiskit-community
|
# -*- coding: utf-8 -*-
# Copyright 2017, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
# pylint: disable=missing-docstring,redefined-builtin
import unittest
import os
from qiskit import QuantumCircuit
from .common import QiskitTestCase
from qiskit_jku_provider import QasmSimulator
from qiskit import execute
class TestQasmSimulatorJKUBasic(QiskitTestCase):
"""Runs the Basic qasm_simulator tests from Terra on JKU."""
def setUp(self):
self.seed = 88
self.backend = QasmSimulator(silent=True)
qasm_filename = os.path.join(os.path.dirname(__file__), 'qasms', 'example.qasm')
compiled_circuit = QuantumCircuit.from_qasm_file(qasm_filename)
compiled_circuit.name = 'test'
self.circuit = compiled_circuit
def test_qasm_simulator_single_shot(self):
"""Test single shot run."""
result = execute(self.circuit, self.backend, seed_transpiler=34342, shots=1).result()
self.assertEqual(result.success, True)
def test_qasm_simulator(self):
"""Test data counts output for single circuit run against reference."""
shots = 1024
result = execute(self.circuit, self.backend, seed_transpiler=34342, shots=shots).result()
threshold = 0.04 * shots
counts = result.get_counts('test')
target = {'100 100': shots / 8, '011 011': shots / 8,
'101 101': shots / 8, '111 111': shots / 8,
'000 000': shots / 8, '010 010': shots / 8,
'110 110': shots / 8, '001 001': shots / 8}
self.assertDictAlmostEqual(counts, target, threshold)
if __name__ == '__main__':
unittest.main()
|
https://github.com/qiskit-community/qiskit-qcgpu-provider
|
qiskit-community
|
import unittest
import math
from qiskit_qcgpu_provider import QCGPUProvider
from qiskit import execute, QuantumRegister, QuantumCircuit, BasicAer
from qiskit.quantum_info import state_fidelity
from .case import MyTestCase
class TestStatevectorSimulator(MyTestCase):
"""Test the state vector simulator"""
def test_computations(self):
for n in range(2, 10):
circ = self.random_circuit(n, 5)
self._compare_outcomes(circ)
def _compare_outcomes(self, circ):
Provider = QCGPUProvider()
backend_qcgpu = Provider.get_backend('statevector_simulator')
statevector_qcgpu = execute(circ, backend_qcgpu).result().get_statevector()
backend_qiskit = BasicAer.get_backend('statevector_simulator')
statevector_qiskit = execute(circ, backend_qiskit).result().get_statevector()
self.assertAlmostEqual(state_fidelity(statevector_qcgpu, statevector_qiskit), 1, 5)
if __name__ == '__main__':
unittest.main()
|
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
"""
# Import Qiskit
import qiskit
# Set versions variable to the current Qiskit versions
versions=qiskit.__qiskit_version__
# Print the version number for the Qiskit components
print("Qiskit components and versions:")
print("===============================")
for i in versions:
print (i, versions[i])
|
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/PacktPublishing/Quantum-Computing-in-Practice-with-Qiskit-and-IBM-Quantum-Experience
|
PacktPublishing
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created Nov 2020
@author: hassi
"""
from qiskit import QuantumRegister, ClassicalRegister
from qiskit import QuantumCircuit, Aer, execute
from qiskit.tools.visualization import plot_histogram
from IPython.core.display import display
print("Ch 4: Quantum coin toss")
print("-----------------------")
q = QuantumRegister(1)
c = ClassicalRegister(1)
qc = QuantumCircuit(q, c)
qc.h(q[0])
qc.measure(q, c)
display(qc.draw('mpl'))
print(qc)
display(qc.draw('text'))
backend = Aer.get_backend('qasm_simulator')
job = execute(qc, backend, shots=1)
result = job.result()
counts = result.get_counts(qc)
print(counts)
display(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
"""
from qiskit import QuantumRegister, ClassicalRegister
from qiskit import QuantumCircuit, Aer, execute
from qiskit.tools.visualization import plot_histogram
from IPython.core.display import display
print("Ch 4: Quantum coin tosses")
print("-------------------------")
q = QuantumRegister(1)
c = ClassicalRegister(1)
qc = QuantumCircuit(q, c)
qc.h(q[0])
qc.measure(q, c)
display(qc.draw('mpl'))
backend = Aer.get_backend('qasm_simulator')
job = execute(qc, backend, shots=1000)
result = job.result()
counts = result.get_counts(qc)
print(counts)
display(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
"""
from qiskit import QuantumCircuit, Aer, execute
from qiskit.visualization import plot_histogram
from IPython.core.display import display
print("Ch 4: Upside down quantum coin toss")
print("-----------------------------------")
qc = QuantumCircuit(1, 1)
initial_vector = [0.+0.j, 1.+0.j]
qc.initialize(initial_vector,0)
#qc.x(0)
qc.h(0)
qc.measure(0, 0)
print(qc)
#display(qc.draw())
backend = Aer.get_backend('qasm_simulator')
counts = execute(qc, backend, shots=1).result().get_counts(qc)
display(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
"""
from qiskit import QuantumCircuit, Aer, execute
from qiskit.tools.visualization import plot_histogram
from IPython.core.display import display
print("Ch 4: Quantum double coin toss")
print("------------------------------")
qc = QuantumCircuit(2, 2)
qc.h([0,1])
qc.measure([0,1],[0,1])
display(qc.draw('mpl'))
backend = Aer.get_backend('qasm_simulator')
counts = execute(qc, backend, shots=1).result().get_counts(qc)
display(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
"""
from qiskit import QuantumCircuit, Aer, execute
from qiskit.tools.visualization import plot_histogram
from IPython.core.display import display
print("Ch 4: Cheating quantum coin toss")
print("--------------------------------")
qc = QuantumCircuit(2, 2)
qc.h(0)
qc.cx(0,1)
qc.measure([0,1],[0,1])
display(qc.draw('mpl'))
backend = Aer.get_backend('qasm_simulator')
counts = execute(qc, backend, shots=1000).result().get_counts(qc)
display(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
"""
from qiskit import QuantumCircuit, Aer, execute
from qiskit.tools.visualization import plot_histogram
from IPython.core.display import display
from math import pi
# Function that returns the state vector (Psi) for the circuit
def get_psi(circuit, title):
show_bloch=True
if show_bloch:
from qiskit.visualization import plot_bloch_multivector
backend = Aer.get_backend('statevector_simulator')
result = execute(circuit, backend).result()
psi = result.get_statevector(circuit)
print(title)
display(qc.draw('mpl'))
display(plot_bloch_multivector(psi))
print("Ch 4: More Cheating quantum coin toss")
print("-------------------------------------")
qc = QuantumCircuit(1, 1)
get_psi(qc, title='Qubit in ground state |0>')
qc.h(0)
get_psi(qc, title='Qubit in super position')
qc.ry(pi/8,0)
get_psi(qc, title='Qubit pi/8 radians closer to |1>')
qc.measure(0, 0)
display(qc.draw('mpl'))
backend = Aer.get_backend('qasm_simulator')
counts = execute(qc, backend, shots=1000).result().get_counts(qc)
display(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
"""
from qiskit import QuantumCircuit, Aer, execute
from qiskit.tools.visualization import plot_histogram
from IPython.core.display import display
print("Ch 4: Three-qubit coin toss")
print("---------------------------")
qc = QuantumCircuit(3, 6)
qc.h([0,1,2])
qc.measure([0,1,2],[0,1,2])
display(qc.draw('mpl'))
backend = Aer.get_backend('qasm_simulator')
counts = execute(qc, backend, shots=1000).result().get_counts(qc)
display(plot_histogram(counts))
qc.barrier([0,1,2])
qc.reset([0,1,2])
qc.h(0)
qc.cx(0,1)
qc.cx(0,2)
qc.measure([0,1,2],[3,4,5])
display(qc.draw('mpl'))
counts = execute(qc, backend, shots=1000).result().get_counts(qc)
display(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
"""
from qiskit import QuantumCircuit, execute
from qiskit import IBMQ
from qiskit.tools.monitor import job_monitor
from IPython.core.display import display
print("Getting provider...")
if not IBMQ.active_account():
IBMQ.load_account()
provider = IBMQ.get_provider()
print("Ch 4: Quantum coin toss on IBM Q backend")
print("----------------------------------------")
qc = QuantumCircuit(2, 2)
qc.h(0)
qc.cx(0,1)
qc.measure([0,1],[0,1])
display(qc.draw('mpl'))
from qiskit.providers.ibmq import least_busy
backend = least_busy(provider.backends(n_qubits=5, operational=True, simulator=False))
print(backend.name())
job = execute(qc, backend, shots=1000)
job_monitor(job)
result = job.result()
print(result)
counts = result.get_counts(qc)
from qiskit.tools.visualization import plot_histogram
display(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
Updated Aug 2021
@author: hassi
"""
from qiskit import IBMQ, QuantumCircuit, execute
from qiskit.tools.monitor import job_monitor
print("Ch 5: Identifying backends")
print("--------------------------")
print("Getting provider...")
if not IBMQ.active_account():
IBMQ.load_account()
provider = IBMQ.get_provider()
print("\nAvailable backends:")
print(provider.backends(operational=True, simulator=False))
select_backend=input("Type in the name of a backend: ")
backend = provider.get_backend(select_backend)
print("\nSelected backend:", backend.name())
# Create a quantum circuit to test
qc = QuantumCircuit(2,2)
qc.h(0)
qc.cx(0,1)
qc.measure([0,1],[0,1])
print("\nQuantum circuit:")
print(qc)
job = execute(qc, backend, shots=1000)
job_monitor(job)
result = job.result()
counts = result.get_counts(qc)
print("\nResults:", counts)
print("\nAvailable simulator backends:")
print(provider.backends(operational=True, simulator=True))
backend = provider.get_backend('ibmq_qasm_simulator')
job = execute(qc, backend, shots=1000)
job_monitor(job)
result = job.result()
counts = result.get_counts(qc)
print("\nSimulator results:", 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
"""
from qiskit import IBMQ, QuantumCircuit, execute
from qiskit.tools.monitor import job_monitor
from qiskit.visualization import plot_histogram
from IPython.core.display import display
print("Ch 5: Comparing backends")
print("------------------------")
print("Getting provider...")
if not IBMQ.active_account():
IBMQ.load_account()
provider = IBMQ.get_provider()
# Cceate a Bell circuit
qc = QuantumCircuit(2,2)
qc.h(0)
qc.cx(0,1)
qc.measure([0,1],[0,1])
print("\nQuantum circuit:")
print(qc)
# Get all available and operational backends.
backends = provider.backends(filters=lambda b: b.configuration().n_qubits > 1 and b.status().operational)
print("\nAvailable backends:", backends)
# Run the program on all backends and create a counts dictionary with the results from the executions.
counts = {}
for n in range(0, len(backends)):
print('Run on:', backends[n])
job = execute(qc, backends[n], shots=1000)
job_monitor(job)
result = job.result()
counts[backends[n].name()] = result.get_counts(qc)
#Display the data that we want to plot.
print("\nRaw results:", counts)
#Optionally define the histogram colors.
colors = ['green','darkgreen','red','darkred', 'orange','yellow','blue','darkblue','purple']
#Plot the counts dictionary values in a histogram, using the counts dictionary keys as legend.
display(plot_histogram(list(counts.values()), title = "Bell results on all available backends", legend=list(counts), color = colors[0:len(backends)], bar_labels = True))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.