repo
stringclasses 885
values | file
stringclasses 741
values | content
stringlengths 4
215k
|
---|---|---|
https://github.com/indian-institute-of-science-qc/qiskit-aakash
|
indian-institute-of-science-qc
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2018.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Tests for pass cancelling 2 consecutive CNOTs on the same qubits."""
from qiskit import QuantumRegister, QuantumCircuit
from qiskit.circuit import Clbit, Qubit
from qiskit.transpiler import PassManager
from qiskit.transpiler.passes import CXCancellation
from qiskit.test import QiskitTestCase
class TestCXCancellation(QiskitTestCase):
"""Test the CXCancellation pass."""
def test_pass_cx_cancellation(self):
"""Test the cx cancellation pass.
It should cancel consecutive cx pairs on same qubits.
"""
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])
circuit.cx(qr[1], qr[0])
circuit.cx(qr[1], qr[0])
pass_manager = PassManager()
pass_manager.append(CXCancellation())
out_circuit = pass_manager.run(circuit)
expected = QuantumCircuit(qr)
expected.h(qr[0])
expected.h(qr[0])
self.assertEqual(out_circuit, expected)
def test_pass_cx_cancellation_intermixed_ops(self):
"""Cancellation shouldn't be affected by the order of ops on different qubits."""
qr = QuantumRegister(4)
circuit = QuantumCircuit(qr)
circuit.h(qr[0])
circuit.h(qr[1])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[2], qr[3])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[2], qr[3])
pass_manager = PassManager()
pass_manager.append(CXCancellation())
out_circuit = pass_manager.run(circuit)
expected = QuantumCircuit(qr)
expected.h(qr[0])
expected.h(qr[1])
self.assertEqual(out_circuit, expected)
def test_pass_cx_cancellation_chained_cx(self):
"""Include a test were not all operations can be cancelled."""
# βββββ
# q0_0: β€ H ββββ ββββββββββ βββββββ
# βββββ€βββ΄ββ βββ΄ββ
# q0_1: β€ H ββ€ X ββββ βββ€ X ββββββ
# βββββββββββββ΄βββββββ
# q0_2: βββββββββββ€ X ββββ βββββ ββ
# ββββββββ΄βββββ΄ββ
# q0_3: ββββββββββββββββ€ X ββ€ X β
# ββββββββββ
qr = QuantumRegister(4)
circuit = QuantumCircuit(qr)
circuit.h(qr[0])
circuit.h(qr[1])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[1], qr[2])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[2], qr[3])
circuit.cx(qr[2], qr[3])
pass_manager = PassManager()
pass_manager.append(CXCancellation())
out_circuit = pass_manager.run(circuit)
# βββββ
# q0_0: β€ H ββββ ββββββββββ ββ
# βββββ€βββ΄ββ βββ΄ββ
# q0_1: β€ H ββ€ X ββββ βββ€ X β
# βββββββββββββ΄βββββββ
# q0_2: βββββββββββ€ X ββββββ
# βββββ
# q0_3: ββββββββββββββββββββ
expected = QuantumCircuit(qr)
expected.h(qr[0])
expected.h(qr[1])
expected.cx(qr[0], qr[1])
expected.cx(qr[1], qr[2])
expected.cx(qr[0], qr[1])
self.assertEqual(out_circuit, expected)
def test_swapped_cx(self):
"""Test that CX isn't cancelled if there are intermediary ops."""
qr = QuantumRegister(4)
circuit = QuantumCircuit(qr)
circuit.cx(qr[1], qr[0])
circuit.swap(qr[1], qr[2])
circuit.cx(qr[1], qr[0])
pass_manager = PassManager()
pass_manager.append(CXCancellation())
out_circuit = pass_manager.run(circuit)
self.assertEqual(out_circuit, circuit)
def test_inverted_cx(self):
"""Test that CX order dependence is respected."""
qr = QuantumRegister(4)
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[1])
circuit.cx(qr[1], qr[0])
circuit.cx(qr[0], qr[1])
pass_manager = PassManager()
pass_manager.append(CXCancellation())
out_circuit = pass_manager.run(circuit)
self.assertEqual(out_circuit, circuit)
def test_if_else(self):
"""Test that the pass recurses in a simple if-else."""
pass_ = CXCancellation()
inner_test = QuantumCircuit(4, 1)
inner_test.cx(0, 1)
inner_test.cx(0, 1)
inner_test.cx(2, 3)
inner_expected = QuantumCircuit(4, 1)
inner_expected.cx(2, 3)
test = QuantumCircuit(4, 1)
test.h(0)
test.measure(0, 0)
test.if_else((0, True), inner_test.copy(), inner_test.copy(), range(4), [0])
expected = QuantumCircuit(4, 1)
expected.h(0)
expected.measure(0, 0)
expected.if_else((0, True), inner_expected, inner_expected, range(4), [0])
self.assertEqual(pass_(test), expected)
def test_nested_control_flow(self):
"""Test that collection recurses into nested control flow."""
pass_ = CXCancellation()
qubits = [Qubit() for _ in [None] * 4]
clbit = Clbit()
inner_test = QuantumCircuit(qubits, [clbit])
inner_test.cx(0, 1)
inner_test.cx(0, 1)
inner_test.cx(2, 3)
inner_expected = QuantumCircuit(qubits, [clbit])
inner_expected.cx(2, 3)
true_body = QuantumCircuit(qubits, [clbit])
true_body.while_loop((clbit, True), inner_test.copy(), [0, 1, 2, 3], [0])
test = QuantumCircuit(qubits, [clbit])
test.for_loop(range(2), None, inner_test.copy(), [0, 1, 2, 3], [0])
test.if_else((clbit, True), true_body, None, [0, 1, 2, 3], [0])
expected_if_body = QuantumCircuit(qubits, [clbit])
expected_if_body.while_loop((clbit, True), inner_expected, [0, 1, 2, 3], [0])
expected = QuantumCircuit(qubits, [clbit])
expected.for_loop(range(2), None, inner_expected, [0, 1, 2, 3], [0])
expected.if_else((clbit, True), expected_if_body, None, [0, 1, 2, 3], [0])
self.assertEqual(pass_(test), expected)
|
https://github.com/Qottmann/Quantum-anomaly-detection
|
Qottmann
|
import time
import itertools
import numpy as np
import qiskit
from qiskit import *
from qiskit.quantum_info import Statevector
from qiskit.algorithms.optimizers import COBYLA, L_BFGS_B, SPSA
from qiskit.opflow.state_fns import StateFn, CircuitStateFn
from qiskit.providers.aer import StatevectorSimulator, AerSimulator
from qiskit.opflow import CircuitSampler
from qiskit.ignis.mitigation.measurement import CompleteMeasFitter # you will need to pip install qiskit-ignis
from qiskit.ignis.mitigation.measurement import complete_meas_cal
import matplotlib.pyplot as plt
from matplotlib.ticker import MaxNLocator
from matplotlib.colors import BoundaryNorm
cmap = plt.get_cmap("plasma") #'viridis'
from modules.utils import *
from qae import *
import datetime
print(qiskit.__version__, np.__version__)
#plt.rc('text', usetex=True)
plt.rc('font', family='serif',size=16)
#plt.rc('font', family='serif')
temp = np.load("data/QAEAnsatz_scaling_losses.npz", allow_pickle=True)
losses0 = temp["losses"]
Ls = temp["Ls"]
# It took 51 hrs to obtain these results.
# However, you can confirm the validity by just executing the circuit once for the optimized parameters (as demonstrated down below)
temp2 = np.load("data/QAEAnsatz_scaling_MPS_script_L-32_tracked-losses_results.npz",allow_pickle=True)
losses32 = temp2["losses"]
Ls = list(Ls)
Ls += [32]
Ls
fig, ax = plt.subplots(figsize=(6,5))
for i in range(4):
ax.plot(np.array(losses0[i]),label=f"L = {Ls[i]}")
ax.plot(losses32[1],label=f"L = {Ls[-1]}")
ax.legend()
left, bottom, width, height = [0.4,0.61, 0.25, 0.325]
ax2 = fig.add_axes([left, bottom, width, height])
for i in range(4):
ax2.plot(np.array(losses0[i]),label=f"L = {Ls[i]}")
ax2.plot(losses32[1],label=f"L = {Ls[-1]}")
ax2.set_yscale("log")
#ax.set_xlim(0,405)
#ax.set_yscale("log")
ax.set_ylabel("cost", fontsize=16)
ax.set_xlabel("iteration", fontsize=16)
plt.tight_layout()
plt.savefig("plots/QAEAnsatz_Ising-scaling.pdf")
plt.savefig("plots/QAEAnsatz_Ising-scaling.png")
#IBMQ.load_account() # this then automatically loads your saved account
#provider = IBMQ.get_provider(hub='ibm-q-research')
#device = provider.backend.ibmq_rome # 6 bogota ; 4 rome
### Real device execution:
#backend = device
### Simulation with noise profile from real device
#backend = qiskit.providers.aer.AerSimulator.from_backend(device)
### Simulation without noise
backend = qiskit.providers.aer.AerSimulator()
#backend = StatevectorSimulator()
### Preliminaries
L = 5
num_trash = 2
anti = 1 # 1 for ferromagnetic Ising model, -1 for antiferromagnet
filename = "data/QAEAnsatz_scaling"
gz = 0
gx = 0.3
ED_state, ED_E, ham = ising_groundstate(L, anti, np.float32(gx), np.float32(gz))
Sen = ED_E
Smag = ED_state.T.conj()@Mag(L,anti)@ED_state
def prepare_circuit(thetas, L=6, num_trash=2, init_state=None, measurement=True,vqe=False):
# QAE ansatz
QAE_circ = QAEAnsatz(num_qubits = L, num_trash_qubits= num_trash, trash_qubits_idxs = list(range(num_trash)), measure_trash=measurement).assign_parameters(thetas)
# initialize state vector
initcirc = QuantumCircuit(QuantumRegister(L,"q"),ClassicalRegister(num_trash, 'c'))
initcirc.initialize(init_state, initcirc.qubits)
# compose circuits
fullcirc = initcirc.compose(QAE_circ)
return fullcirc
circ = prepare_circuit(thetas = np.random.rand(2*L+2), L = L, init_state = ED_state)
circ.draw("mpl")
### Execute circuit
count = 0
def run_circuit(thetas, L, num_trash, init_state, vqe=False, shots=100, meas_fitter = None):
#global count
#count += 1
#print(count, "thetas: ", thetas)
circ = prepare_circuit(thetas, L, num_trash, init_state, vqe=vqe)
tcirc = qiskit.transpile(circ, backend)
# Execute the circuit
job_sim = backend.run(tcirc, shots=shots,seed_simulator=333, seed_transpiler=444) # , seed_simulator=123, seed_transpiler=234 fix seed to make it reproducible
result = job_sim.result()
# Results without mitigation
counts = result.get_counts()
if meas_fitter != None:
# Get the filter object
meas_filter = meas_fitter.filter
# Results with mitigation
mitigated_results = meas_filter.apply(result)
counts = mitigated_results.get_counts(0)
return counts
res = run_circuit(thetas = np.random.rand(num_trash*L+num_trash), L = L, num_trash = num_trash, init_state = ED_state, shots=1000)
res
def count_ones(string):
return np.sum([int(_) for _ in string])
count_ones("01010111")
[_ for _ in res]
[_ for _ in res if _ != "0" * num_trash]
np.sum([res[_]*count_ones(_) for _ in res if _ != "0" * num_trash]) # all measurement results except "000"
### Optimize circuit
def cost_function_single(thetas, L, num_trash, init_state, shots=1000, vqe=True, param_encoding=False, x=0, meas_fitter=None):
""" Optimizes circuit """
if param_encoding: thetas = feature_encoding(thetas, x)
out = run_circuit(thetas, L, num_trash, init_state, vqe=vqe, shots=shots, meas_fitter=meas_fitter)
cost = np.sum([out[_]*count_ones(_) for _ in out if _ != "0" * num_trash]) # all measurement results except "000"
return cost/shots
def cost_function(thetas, L, num_trash, init_states, shots=1000, vqe=True, param_encoding=False, x=0, meas_fitter=None):
""" Optimizes circuit """
cost = 0.
for init_state in init_states:
cost += cost_function_single(thetas, L, num_trash, init_state, shots, vqe, param_encoding, meas_fitter=meas_fitter)
return cost/len(init_states)
def optimize(init_states, L=6, num_trash=2, thetas=None, shots=1000, max_iter=400, vqe=True, param_encoding=False, x=0, pick_optimizer = None,
meas_fitter=None):
if thetas is None:
n_params = (num_trash*L+num_trasg)*2 if param_encoding else (num_trash*L+num_trash)
thetas = np.random.uniform(0, 2*np.pi, n_params) # initial parameters without feature encoding
#print("Initial cost: {:.3f}".format(cost_function(thetas, L, num_trash, init_states, shots, vqe, param_encoding, x)))
counts, values, accepted = [], [], []
def store_intermediate_result(eval_count, parameters, mean, std, ac):
# counts.append(eval_count)
values.append(mean)
accepted.append(ac)
# Initialize optimizer
if pick_optimizer == "cobyla":
optimizer = COBYLA(maxiter=max_iter, tol=0.0001)
if pick_optimizer == "adam" or pick_optimizer == "ADAM":
optimizer = qiskit.algorithms.optimizers.ADAM(maxiter=max_iter)
# optimizer = L_BFGS_B(maxfun=300, maxiter=max_iter)#, factr=10, iprint=- 1, epsilon=1e-08)
if pick_optimizer == "spsa" or pick_optimizer == None:
optimizer = SPSA(maxiter=max_iter,
#blocking=True,
callback=store_intermediate_result,
#learning_rate=0.3,
#perturbation=0.1
) # recommended from qiskit (first iteraction takes quite long)
# to reduce time figure out optimal learning rate and perturbation in advance
start_time = time.time()
ret = optimizer.optimize(
num_vars=len(thetas),
objective_function=(lambda thetas: cost_function(thetas, L, num_trash, init_states, shots, vqe, param_encoding, x, meas_fitter=meas_fitter)),
initial_point=thetas
)
print("Time: {:.5f} sec".format(time.time()-start_time))
print(ret)
return ret[0], values, accepted
thetas_opt_mitigated, losses, accepted = optimize([ED_state], max_iter=120, L=5, meas_fitter=None) #, pick_optimizer="adam")
plt.plot(losses)
Ls = [3,4,8,16] #note that L=16 may take up few hours, it is faster with MPS further below
max_iter = [400] * len(Ls)
num_trashs = np.log(Ls)/np.log(2)
num_trashs = np.array(num_trashs, dtype="int")
gz = 0
gx = 0.3
losses = [None] * len(Ls); accepted = [None] * len(Ls); thetas_opt= [None] * len(Ls)
# may have to re-run some sizes when it gets stuck in local minima
for j,(L,num_trash) in enumerate(zip(Ls,num_trashs)):
print(L,num_trash)
ED_state, ED_E, ham = ising_groundstate(L, anti, np.float32(gx), np.float32(gz))
thetas_opt[j], losses[j], accepted[j] = optimize([ED_state], max_iter=max_iter[j], L=L, num_trash=num_trash, meas_fitter=None) #, pick_optimizer="adam")
plt.plot(losses[j])
plt.show()
np.savez(filename + "_losses", losses=losses, thetas_opt = thetas_opt, Ls=Ls, max_iter=max_iter, num_trashs=num_trashs)
temp = np.load(filename + "_losses.npz", allow_pickle=True)
losses0 = temp["losses"]
fig, ax = plt.subplots(figsize=(6,5))
for i in range(4):
ax.plot(np.array(losses0[i]) + 1e-4,label=f"L = {Ls[i]}")
ax.legend()
ax.set_xlim(0,400)
ax.set_yscale("log")
ax.set_yticks([1,1e-1,1e-2,1e-3,1e-4])
ax.set_yticklabels(["$10^{}$".format(i) for i in range(4)] + ["0.0"])
ax.set_ylabel("cost", fontsize=16)
ax.set_xlabel("iterations", fontsize=16)
min_losses = [np.min(l) for l in losses0]
min_losses
fig, ax = plt.subplots(figsize=(6,5))
ax.plot(Ls, min_losses,"x--")
#ax.set_yscale("log")
#ax.set_xscale("log")
def DMRG_Ising(L, J, g, chi_max=30, bc_MPS='finite'):
print("finite DMRG, transverse field Ising model")
print("L={L:d}, g={g:.2f}".format(L=L, g=g))
model_params = dict(L=L, J=J, g=g, bc_MPS=bc_MPS, conserve=None)
M = TFIChain(model_params)
product_state = ["up"] * M.lat.N_sites
psi = MPS.from_product_state(M.lat.mps_sites(), product_state, bc=M.lat.bc_MPS)
dmrg_params = {
'mixer': None, # setting this to True helps to escape local minima
'max_E_err': 1.e-10,
'trunc_params': {
'chi_max': chi_max,
'svd_min': 1.e-10
},
'combine': True
}
info = dmrg.run(psi, M, dmrg_params) # the main work...
E = info['E']
print("E = {E:.13f}".format(E=E))
print("final bond dimensions: ", psi.chi)
mag_x = np.sum(psi.expectation_value("Sigmax"))
mag_z = np.sum(psi.expectation_value("Sigmaz"))
print("magnetization in X = {mag_x:.5f}".format(mag_x=mag_x))
print("magnetization in Z = {mag_z:.5f}".format(mag_z=mag_z))
#if L < 20: # compare to exact result
# from tfi_exact import finite_gs_energy
# E_exact = finite_gs_energy(L, 1., g)
# print("Exact diagonalization: E = {E:.13f}".format(E=E_exact))
# print("relative error: ", abs((E - E_exact) / E_exact))
return E, psi #, M
### Preliminaries
qiskit_chi = 100
L = 8
num_trash = int(np.log(L)/np.log(2))
anti = 1 # 1 for ferromagnetic Ising model, -1 for antiferromagnet
g = 0.05
J=anti
filename = "data/QAEAnsatz_scaling_MPS_script_L-32_tracked-losses"
backend = qiskit.providers.aer.AerSimulator(method="matrix_product_state",
precision="single",
matrix_product_state_max_bond_dimension = qiskit_chi,
matrix_product_state_truncation_threshold = 1e-10,
#mps_sample_measure_algorithm = "mps_apply_measure", #alt: "mps_probabilities"
)
from qiskit.utils import algorithm_globals
algorithm_globals.random_seed = 333
def qiskit_state(psi0):
# G is only the local tensor (not multiplied by any singular values) - see https://tenpy.readthedocs.io/en/latest/reference/tenpy.networks.mps.html
A_list = [psi0.get_B(i, form="G").to_ndarray().transpose([1,0,2]) for i in range(L)]
for i,A in enumerate(A_list):
A_list[i] = (A[0], A[1])
S_list = [psi0.get_SR(i) for i in range(L-1)] # skip trivial last bond; hast to be of size L-1
return (A_list, S_list)
def prepare_circuit(thetas, L=6, num_trash=2, init_state=None, measurement=True,vqe=False):
# QAE ansatz
QAE_circ = QAEAnsatz(num_qubits = L, num_trash_qubits= num_trash, trash_qubits_idxs = list(range(L//2-1,L//2-1+num_trash)), measure_trash=measurement).assign_parameters(thetas)
# initialize state vector
initcirc = QuantumCircuit(QuantumRegister(L,"q"),ClassicalRegister(num_trash, 'c'))
if init_state != None:
initcirc.set_matrix_product_state(qiskit_state(init_state))
# compose circuits
fullcirc = initcirc.compose(QAE_circ)
return fullcirc
### Execute circuit
count = 0
def run_circuit(thetas, L, num_trash, init_state, vqe=False, shots=100, meas_fitter = None):
#global count
#count += 1
#print(count, "thetas: ", thetas)
#print(L, num_trash)
circ = prepare_circuit(thetas, L, num_trash, init_state, vqe=vqe)
#circ.draw("mpl")
#tcirc = qiskit.transpile(circ, backend)
# Execute the circuit
job_sim = backend.run(circ, shots=shots, seed_simulator=333, seed_transpiler=444) #fix seed to make it reproducible
result = job_sim.result()
# Results without mitigation
counts = result.get_counts()
if meas_fitter != None:
# Get the filter object
meas_filter = meas_fitter.filter
# Results with mitigation
mitigated_results = meas_filter.apply(result)
counts = mitigated_results.get_counts(0)
return counts
def count_ones(string):
return np.sum([int(_) for _ in string])
### Optimize circuit
def cost_function_single(thetas, L, num_trash, init_state, shots=1000, vqe=True, param_encoding=False, x=0, meas_fitter=None):
""" Optimizes circuit """
if param_encoding: thetas = feature_encoding(thetas, x)
out = run_circuit(thetas, L, num_trash, init_state, vqe=vqe, shots=shots, meas_fitter=meas_fitter)
cost = np.sum([out[_]*count_ones(_) for _ in out if _ != "0" * num_trash]) # all measurement results except "000"
return cost/shots
def cost_function(thetas, L, num_trash, init_states, shots=1000, vqe=True, param_encoding=False, x=0, meas_fitter=None):
""" Optimizes circuit """
cost = 0.
for init_state in init_states:
cost += cost_function_single(thetas, L, num_trash, init_state, shots, vqe, param_encoding, meas_fitter=meas_fitter)
return cost/len(init_states)
def optimize(init_states, L=6, num_trash=2, thetas=None, shots=1000, max_iter=400, vqe=True, param_encoding=False, x=0, pick_optimizer = None,
meas_fitter=None):
if thetas is None:
n_params = (num_trash*L+num_trasg)*2 if param_encoding else (num_trash*L+num_trash)
thetas = np.random.uniform(0, 2*np.pi, n_params) # initial parameters without feature encoding
#print("Initial cost: {:.3f}".format(cost_function(thetas, L, num_trash, init_states, shots, vqe, param_encoding, x)))
counts, values, accepted = [], [], []
def store_intermediate_result(eval_count, parameters, mean, std, ac):
# counts.append(eval_count)
values.append(mean)
accepted.append(ac)
# Initialize optimizer
if pick_optimizer == "cobyla":
optimizer = COBYLA(maxiter=max_iter, tol=0.0001)
if pick_optimizer == "adam" or pick_optimizer == "ADAM":
optimizer = qiskit.algorithms.optimizers.ADAM(maxiter=max_iter)
# optimizer = L_BFGS_B(maxfun=300, maxiter=max_iter)#, factr=10, iprint=- 1, epsilon=1e-08)
if pick_optimizer == "spsa" or pick_optimizer == None:
optimizer = SPSA(maxiter=max_iter,
#blocking=True,
callback=store_intermediate_result,
#learning_rate=0.3,
#perturbation=0.1
) # recommended from qiskit (first iteraction takes quite long)
# to reduce time figure out optimal learning rate and perturbation in advance
start_time = time.time()
ret = optimizer.optimize(
num_vars=len(thetas),
objective_function=(lambda thetas: cost_function(thetas, L, num_trash, init_states, shots, vqe, param_encoding, x, meas_fitter=meas_fitter)),
initial_point=thetas
)
print("Time: {:.5f} sec".format(time.time()-start_time))
print(ret)
return ret[0], values, accepted
temp2 = np.load("data/QAEAnsatz_scaling/QAEAnsatz_scaling_MPS_script_L-32_results.npz",allow_pickle=True) # 500 iterations, gx = 0.3, chi=100 (but resulting bond dimension of state much smaller)
psi0 = temp2["psi0"].item()
thetas_opt = temp2["thetas_opt"][0]
L = psi0.L
loss_final = cost_function_single(thetas_opt, L, int(np.log(L)/np.log(2)), psi0, shots=1000)
print(f"Result for L = {L}: loss_opt = {loss_final} with optimal parameters {thetas_opt}")
temp2 = np.load("data/QAEAnsatz_scaling_MPS_script_L-32_tracked-losses_results.npz",allow_pickle=True) # 500 iterations, gx = 0.3, chi=100 (but resulting bond dimension of state much smaller)
psi0 = temp2["psis"][1]
thetas_opt = temp2["thetas_opt"][1]
L = psi0.L
loss_final = cost_function_single(thetas_opt, L, int(np.log(L)/np.log(2)), psi0, shots=1000)
print(f"Result for L = {L}: loss_opt = {loss_final} with optimal parameters {thetas_opt}")
|
https://github.com/anirban-m/qiskit-superstaq
|
anirban-m
|
from unittest.mock import MagicMock, patch
import applications_superstaq
import qiskit
import qiskit_superstaq as qss
def test_provider() -> None:
ss_provider = qss.superstaq_provider.SuperstaQProvider(access_token="MY_TOKEN")
assert str(ss_provider.get_backend("ibmq_qasm_simulator")) == str(
qss.superstaq_backend.SuperstaQBackend(
provider=ss_provider,
url=qss.API_URL,
backend="ibmq_qasm_simulator",
)
)
assert str(ss_provider) == "<SuperstaQProvider(name=superstaq_provider)>"
assert (
repr(ss_provider) == "<SuperstaQProvider(name=superstaq_provider, access_token=MY_TOKEN)>"
)
backend_names = [
"aqt_device",
"ionq_device",
"rigetti_device",
"ibmq_botoga",
"ibmq_casablanca",
"ibmq_jakarta",
"ibmq_qasm_simulator",
]
backends = []
for name in backend_names:
backends.append(
qss.superstaq_backend.SuperstaQBackend(
provider=ss_provider, url=qss.API_URL, backend=name
)
)
assert ss_provider.backends() == backends
@patch("requests.post")
def test_aqt_compile(mock_post: MagicMock) -> None:
provider = qss.superstaq_provider.SuperstaQProvider(access_token="MY_TOKEN")
qc = qiskit.QuantumCircuit(8)
qc.cz(4, 5)
out_qasm_str = """OPENQASM 2.0;
include "qelib1.inc";
//Qubits: [4, 5]
qreg q[2];
cz q[0],q[1];
"""
expected_qc = qiskit.QuantumCircuit(2)
expected_qc.cz(0, 1)
mock_post.return_value.json = lambda: {
"qasm_strs": [out_qasm_str],
"state_jp": applications_superstaq.converters.serialize({}),
"pulse_lists_jp": applications_superstaq.converters.serialize([[[]]]),
}
out = provider.aqt_compile(qc)
assert out.circuit == expected_qc
assert not hasattr(out, "circuits") and not hasattr(out, "pulse_lists")
out = provider.aqt_compile([qc])
assert out.circuits == [expected_qc]
assert not hasattr(out, "circuit") and not hasattr(out, "pulse_list")
mock_post.return_value.json = lambda: {
"qasm_strs": [out_qasm_str, out_qasm_str],
"state_jp": applications_superstaq.converters.serialize({}),
"pulse_lists_jp": applications_superstaq.converters.serialize([[[]], [[]]]),
}
out = provider.aqt_compile([qc, qc])
assert out.circuits == [expected_qc, expected_qc]
assert not hasattr(out, "circuit") and not hasattr(out, "pulse_list")
|
https://github.com/AasthaShayla/Qiskit-Teleportation
|
AasthaShayla
|
import numpy as np
# Importing standard Qiskit libraries
from qiskit import QuantumCircuit,execute, transpile, Aer, IBMQ
from qiskit.tools.jupyter import *
from qiskit.visualization import *
from ibm_quantum_widgets import *
from qiskit.providers.aer import QasmSimulator
# Loading your IBM Quantum account(s)
provider = IBMQ.load_account()
from qiskit.visualization import plot_state_qsphere
from qiskit.visualization import plot_bloch_multivector
qc=QuantumCircuit(1)
statevector_simulator = Aer.get_backend('statevector_simulator')
result=execute(qc,statevector_simulator).result()
statevector_results=result.get_statevector(qc)
plot_bloch_multivector(statevector_results)
plot_state_qsphere(statevector_results)
qc.x(0)
result=execute(qc,statevector_simulator).result()
statevector_results=result.get_statevector(qc)
plot_bloch_multivector(statevector_results)
plot_state_qsphere(statevector_results)
qc.h(0)
result=execute(qc,statevector_simulator).result()
statevector_results=result.get_statevector(qc)
plot_bloch_multivector(statevector_results)
plot_state_qsphere(statevector_results)
|
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
|
mmetcalf14
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""
Arbitrary State-Vector Circuit.
"""
from qiskit import QuantumRegister, QuantumCircuit
from qiskit.aqua import AquaError
from qiskit.aqua.utils.arithmetic import normalize_vector, is_power_of_2, log2
from qiskit.aqua.utils.circuit_utils import convert_to_basis_gates
class StateVectorCircuit:
def __init__(self, state_vector):
"""Constructor.
Args:
state_vector: vector representation of the desired quantum state
"""
if not is_power_of_2(len(state_vector)):
raise AquaError('The length of the input state vector needs to be a power of 2.')
self._num_qubits = log2(len(state_vector))
self._state_vector = normalize_vector(state_vector)
def construct_circuit(self, circuit=None, register=None):
"""
Construct the circuit representing the desired state vector.
Args:
circuit (QuantumCircuit): The optional circuit to extend from.
register (QuantumRegister): The optional register to construct the circuit with.
Returns:
QuantumCircuit.
"""
if register is None:
register = QuantumRegister(self._num_qubits, name='q')
# in case the register is a list of qubits
if type(register) is list:
# create empty circuit if necessary
if circuit is None:
circuit = QuantumCircuit()
# loop over all qubits and add the required registers
for q in register:
if not circuit.has_register(q[0]):
circuit.add_register(q[0])
# construct state initialization circuit
temp = QuantumCircuit(*circuit.qregs)
# otherwise, if it is a real register
else:
if len(register) < self._num_qubits:
raise AquaError('The provided register does not have enough qubits.')
if circuit is None:
circuit = QuantumCircuit(register)
else:
if not circuit.has_register(register):
circuit.add_register(register)
# TODO: add capability to start in the middle of the register
temp = QuantumCircuit(register)
temp.initialize(self._state_vector, [register[i] for i in range(self._num_qubits)])
temp = convert_to_basis_gates(temp)
# remove the reset gates terra's unroller added
temp.data = [g for g in temp.data if not g[0].name == 'reset']
circuit += temp
return circuit
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit.visualization.timeline import draw as timeline_draw
from qiskit import QuantumCircuit, transpile
from qiskit.providers.fake_provider import FakeBoeblingen
backend = FakeBoeblingen()
ghz = QuantumCircuit(5)
ghz.h(0)
ghz.cx(0,range(1,5))
circ = transpile(ghz, backend, scheduling_method="asap")
timeline_draw(circ)
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
from qiskit import Aer, IBMQ
import getpass, random, numpy, math
def title_screen ():
print("\n\n\n\n\n\n\n\n")
print(" βββββββ βββ βββ ββββββ ββββ βββββββββββββββ βββββββ ββββ ")
print(" ββββββββββββ ββββββββββββββββ βββββββββββββββ ββββββββ βββββ ")
print(" βββ ββββββ βββββββββββββββββ βββ βββ βββ ββββββββββββββ ")
print(" βββββ ββββββ βββββββββββββββββββββ βββ βββ ββββββββββββββ ")
print(" βββββββββββββββββββββ ββββββ ββββββ βββ ββββββββββββ βββ βββ ")
print(" βββββββ βββββββ βββ ββββββ βββββ βββ βββββββ βββ βββ ")
print("")
print(" βββββββ ββββββ βββββββββββββββββββββ βββββββββββββββββββ βββββββββββββ ββββββββ")
print(" βββββββββββββββββββββββββββββββββββββ βββββββββββββββββββ ββββββββββββββββββββββ")
print(" ββββββββββββββββ βββ βββ βββ ββββββ βββββββββββββββββββββββββββββββββββ")
print(" ββββββββββββββββ βββ βββ βββ ββββββ ββββββββββββββββββββββββββ ββββββββ")
print(" βββββββββββ βββ βββ βββ βββββββββββββββββββββββββββ βββββββββ ββββββββ")
print(" βββββββ βββ βββ βββ βββ βββββββββββββββββββββββββββ βββββββββ ββββββββ")
print("")
print(" ___ ___ _ _ ")
print(" | _ ) _ _ | \ ___ __ ___ __| | ___ | |__ _ _ ")
print(" | _ \| || | | |) |/ -_)/ _|/ _ \/ _` |/ _ \| / /| || |")
print(" |___/ \_, | |___/ \___|\__|\___/\__,_|\___/|_\_\ \_,_|")
print(" |__/ ")
print("")
print(" A game played on a real quantum computer!")
print("")
print("")
randPlace = input("> Press Enter to play...\n").upper()
def ask_for_device ():
d = input("Do you want to play on the real device? (y/n)\n").upper()
if (d=="Y"):
device = IBMQ.get_backend('ibmq_5_tenerife') # if real, we use ibmqx4
else:
device = Aer.get_backend('qasm_simulator') # otherwise, we use a simulator
return device
def ask_for_ships ():
# we'll start with a 'press enter to continue' type command. But it hides a secret! If you input 'R', the positions will be chosen randomly
randPlace = input("> Press Enter to start placing ships...\n").upper()
# The variable ship[X][Y] will hold the position of the Yth ship of player X+1
shipPos = [ [-1]*3 for _ in range(2)] # all values are initialized to the impossible position -1|
# loop over both players and all three ships for each
for player in [0,1]:
# if we chose to bypass player choice and do random, we do that
if randPlace=="R":
randPos = random.sample(range(5), 3)
for ship in [0,1,2]:
shipPos[player][ship] = randPos[ship]
#print(randPos) #uncomment if you want a sneaky peek at where the ships are
else:
for ship in [0,1,2]:
# ask for a position for each ship, and keep asking until a valid answer is given
choosing = True
while (choosing):
# get player input
position = getpass.getpass("Player " + str(player+1) + ", choose a position for ship " + str(ship+1) + " (0, 1, 2, 3 or 4)\n" )
# see if the input is valid and ask for another if not
if position.isdigit(): # valid answers have to be integers
position = int(position)
if (position in [0,1,2,3,4]) and (not position in shipPos[player]): # they need to be between 0 and 5, and not used for another ship of the same player
shipPos[player][ship] = position
choosing = False
print ("\n")
elif position in shipPos[player]:
print("\nYou already have a ship there. Try again.\n")
else:
print("\nThat's not a valid position. Try again.\n")
else:
print("\nThat's not a valid position. Try again.\n")
return shipPos
def ask_for_bombs ( bomb ):
input("> Press Enter to place some bombs...\n")
# ask both players where they want to bomb
for player in range(2):
print("\n\nIt's now Player " + str(player+1) + "'s turn.\n")
# keep asking until a valid answer is given
choosing = True
while (choosing):
# get player input
position = input("Choose a position to bomb (0, 1, 2, 3 or 4)\n")
# see if this is a valid input. ask for another if not
if position.isdigit(): # valid answers have to be integers
position = int(position)
if position in range(5): # they need to be between 0 and 5, and not used for another ship of the same player
bomb[player][position] = bomb[player][position] + 1
choosing = False
print ("\n")
else:
print("\nThat's not a valid position. Try again.\n")
else:
print("\nThat's not a valid position. Try again.\n")
return bomb
def display_grid ( grid, shipPos, shots ):
# since this function has been called, the game must still be on
game = True
# look at the damage on all qubits (we'll even do ones with no ships)
damage = [ [0]*5 for _ in range(2)] # this will hold the prob of a 1 for each qubit for each player
# for this we loop over all strings of 5 bits for each player
for player in range(2):
for bitString in grid[player].keys():
# and then over all positions
for position in range(5):
# if the string has a 1 at that position, we add a contribution to the damage
# remember that the bit for position 0 is the rightmost one, and so at bitString[4]
if (bitString[4-position]=="1"):
damage[player][position] += grid[player][bitString]/shots
# give results to players
for player in [0,1]:
input("\nPress Enter to see the results for Player " + str(player+1) + "'s ships...\n")
# report damage for qubits that are ships, and which have significant damage
# ideally this would be non-zero damage, but noise means it can happen for ships that haven't been hit
# so we choose 5% as the threshold
display = [" ? "]*5
# loop over all qubits that are ships
for position in shipPos[player]:
# if the damage is high enough, display the damage
if ( damage[player][position] > 0.1 ):
if (damage[player][position]>0.9):
display[position] = "100%"
else:
display[position] = str(int( 100*damage[player][position] )) + "% "
#print(position,damage[player][position])
print("Here is the percentage damage for ships that have been bombed.\n")
print(display[ 4 ] + " " + display[ 0 ])
print(" |\ /|")
print(" | \ / |")
print(" | \ / |")
print(" | " + display[ 2 ] + " |")
print(" | / \ |")
print(" | / \ |")
print(" |/ \|")
print(display[ 3 ] + " " + display[ 1 ])
print("\n")
print("Ships with 95% damage or more have been destroyed\n")
print("\n")
# if a player has all their ships destroyed, the game is over
# ideally this would mean 100% damage, but we go for 95% because of noise again
if (damage[player][ shipPos[player][0] ]>.9) and (damage[player][ shipPos[player][1] ]>.9) and (damage[player][ shipPos[player][2] ]>.9):
print ("***All Player " + str(player+1) + "'s ships have been destroyed!***\n\n")
game = False
if (game is False):
print("")
print("=====================================GAME OVER=====================================")
print("")
return game
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2018.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
# pylint: disable=invalid-name
# pylint: disable=missing-param-doc,missing-type-doc,unused-argument
"""
Visualization functions for quantum states.
"""
from typing import Optional, List, Union
from functools import reduce
import colorsys
import numpy as np
from qiskit import user_config
from qiskit.quantum_info.states.statevector import Statevector
from qiskit.quantum_info.operators.operator import Operator
from qiskit.quantum_info.operators.symplectic import PauliList, SparsePauliOp
from qiskit.quantum_info.states.densitymatrix import DensityMatrix
from qiskit.utils.deprecation import deprecate_arg, deprecate_func
from qiskit.utils import optionals as _optionals
from qiskit.circuit.tools.pi_check import pi_check
from .array import _num_to_latex, array_to_latex
from .utils import matplotlib_close_if_inline
from .exceptions import VisualizationError
@deprecate_arg("rho", new_alias="state", since="0.15.1")
@_optionals.HAS_MATPLOTLIB.require_in_call
def plot_state_hinton(
state, title="", figsize=None, ax_real=None, ax_imag=None, *, rho=None, filename=None
):
"""Plot a hinton diagram for the density matrix of a quantum state.
The hinton diagram represents the values of a matrix using
squares, whose size indicate the magnitude of their corresponding value
and their color, its sign. A white square means the value is positive and
a black one means negative.
Args:
state (Statevector or DensityMatrix or ndarray): An N-qubit quantum state.
title (str): a string that represents the plot title
figsize (tuple): Figure size in inches.
filename (str): file path to save image to.
ax_real (matplotlib.axes.Axes): An optional Axes object to be used for
the visualization output. If none is specified a new matplotlib
Figure will be created and used. If this is specified without an
ax_imag only the real component plot will be generated.
Additionally, if specified there will be no returned Figure since
it is redundant.
ax_imag (matplotlib.axes.Axes): An optional Axes object to be used for
the visualization output. If none is specified a new matplotlib
Figure will be created and used. If this is specified without an
ax_imag only the real component plot will be generated.
Additionally, if specified there will be no returned Figure since
it is redundant.
Returns:
:class:`matplotlib:matplotlib.figure.Figure` :
The matplotlib.Figure of the visualization if
neither ax_real or ax_imag is set.
Raises:
MissingOptionalLibraryError: Requires matplotlib.
VisualizationError: if input is not a valid N-qubit state.
Examples:
.. plot::
:include-source:
import numpy as np
from qiskit import QuantumCircuit
from qiskit.quantum_info import DensityMatrix
from qiskit.visualization import plot_state_hinton
qc = QuantumCircuit(2)
qc.h([0, 1])
qc.cz(0,1)
qc.ry(np.pi/3 , 0)
qc.rx(np.pi/5, 1)
state = DensityMatrix(qc)
plot_state_hinton(state, title="New Hinton Plot")
"""
from matplotlib import pyplot as plt
# Figure data
rho = DensityMatrix(state)
num = rho.num_qubits
if num is None:
raise VisualizationError("Input is not a multi-qubit quantum state.")
max_weight = 2 ** np.ceil(np.log(np.abs(rho.data).max()) / np.log(2))
datareal = np.real(rho.data)
dataimag = np.imag(rho.data)
if figsize is None:
figsize = (8, 5)
if not ax_real and not ax_imag:
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=figsize)
else:
if ax_real:
fig = ax_real.get_figure()
else:
fig = ax_imag.get_figure()
ax1 = ax_real
ax2 = ax_imag
# Reversal is to account for Qiskit's endianness.
column_names = [bin(i)[2:].zfill(num) for i in range(2**num)]
row_names = [bin(i)[2:].zfill(num) for i in range(2**num)][::-1]
ly, lx = datareal.shape
# Real
if ax1:
ax1.patch.set_facecolor("gray")
ax1.set_aspect("equal", "box")
ax1.xaxis.set_major_locator(plt.NullLocator())
ax1.yaxis.set_major_locator(plt.NullLocator())
for (x, y), w in np.ndenumerate(datareal):
# Convert from matrix co-ordinates to plot co-ordinates.
plot_x, plot_y = y, lx - x - 1
color = "white" if w > 0 else "black"
size = np.sqrt(np.abs(w) / max_weight)
rect = plt.Rectangle(
[0.5 + plot_x - size / 2, 0.5 + plot_y - size / 2],
size,
size,
facecolor=color,
edgecolor=color,
)
ax1.add_patch(rect)
ax1.set_xticks(0.5 + np.arange(lx))
ax1.set_yticks(0.5 + np.arange(ly))
ax1.set_xlim([0, lx])
ax1.set_ylim([0, ly])
ax1.set_yticklabels(row_names, fontsize=14)
ax1.set_xticklabels(column_names, fontsize=14, rotation=90)
ax1.set_title("Re[$\\rho$]", fontsize=14)
# Imaginary
if ax2:
ax2.patch.set_facecolor("gray")
ax2.set_aspect("equal", "box")
ax2.xaxis.set_major_locator(plt.NullLocator())
ax2.yaxis.set_major_locator(plt.NullLocator())
for (x, y), w in np.ndenumerate(dataimag):
# Convert from matrix co-ordinates to plot co-ordinates.
plot_x, plot_y = y, lx - x - 1
color = "white" if w > 0 else "black"
size = np.sqrt(np.abs(w) / max_weight)
rect = plt.Rectangle(
[0.5 + plot_x - size / 2, 0.5 + plot_y - size / 2],
size,
size,
facecolor=color,
edgecolor=color,
)
ax2.add_patch(rect)
ax2.set_xticks(0.5 + np.arange(lx))
ax2.set_yticks(0.5 + np.arange(ly))
ax2.set_xlim([0, lx])
ax2.set_ylim([0, ly])
ax2.set_yticklabels(row_names, fontsize=14)
ax2.set_xticklabels(column_names, fontsize=14, rotation=90)
ax2.set_title("Im[$\\rho$]", fontsize=14)
fig.tight_layout()
if title:
fig.suptitle(title, fontsize=16)
if ax_real is None and ax_imag is None:
matplotlib_close_if_inline(fig)
if filename is None:
return fig
else:
return fig.savefig(filename)
@_optionals.HAS_MATPLOTLIB.require_in_call
def plot_bloch_vector(
bloch, title="", ax=None, figsize=None, coord_type="cartesian", font_size=None
):
"""Plot the Bloch sphere.
Plot a Bloch sphere with the specified coordinates, that can be given in both
cartesian and spherical systems.
Args:
bloch (list[double]): array of three elements where [<x>, <y>, <z>] (Cartesian)
or [<r>, <theta>, <phi>] (spherical in radians)
<theta> is inclination angle from +z direction
<phi> is azimuth from +x direction
title (str): a string that represents the plot title
ax (matplotlib.axes.Axes): An Axes to use for rendering the bloch
sphere
figsize (tuple): Figure size in inches. Has no effect is passing ``ax``.
coord_type (str): a string that specifies coordinate type for bloch
(Cartesian or spherical), default is Cartesian
font_size (float): Font size.
Returns:
:class:`matplotlib:matplotlib.figure.Figure` : A matplotlib figure instance if ``ax = None``.
Raises:
MissingOptionalLibraryError: Requires matplotlib.
Examples:
.. plot::
:include-source:
from qiskit.visualization import plot_bloch_vector
plot_bloch_vector([0,1,0], title="New Bloch Sphere")
.. plot::
:include-source:
import numpy as np
from qiskit.visualization import plot_bloch_vector
# You can use spherical coordinates instead of cartesian.
plot_bloch_vector([1, np.pi/2, np.pi/3], coord_type='spherical')
"""
from .bloch import Bloch
if figsize is None:
figsize = (5, 5)
B = Bloch(axes=ax, font_size=font_size)
if coord_type == "spherical":
r, theta, phi = bloch[0], bloch[1], bloch[2]
bloch[0] = r * np.sin(theta) * np.cos(phi)
bloch[1] = r * np.sin(theta) * np.sin(phi)
bloch[2] = r * np.cos(theta)
B.add_vectors(bloch)
B.render(title=title)
if ax is None:
fig = B.fig
fig.set_size_inches(figsize[0], figsize[1])
matplotlib_close_if_inline(fig)
return fig
return None
@deprecate_arg("rho", new_alias="state", since="0.15.1")
@_optionals.HAS_MATPLOTLIB.require_in_call
def plot_bloch_multivector(
state,
title="",
figsize=None,
*,
rho=None,
reverse_bits=False,
filename=None,
font_size=None,
title_font_size=None,
title_pad=1,
):
r"""Plot a Bloch sphere for each qubit.
Each component :math:`(x,y,z)` of the Bloch sphere labeled as 'qubit i' represents the expected
value of the corresponding Pauli operator acting only on that qubit, that is, the expected value
of :math:`I_{N-1} \otimes\dotsb\otimes I_{i+1}\otimes P_i \otimes I_{i-1}\otimes\dotsb\otimes
I_0`, where :math:`N` is the number of qubits, :math:`P\in \{X,Y,Z\}` and :math:`I` is the
identity operator.
Args:
state (Statevector or DensityMatrix or ndarray): an N-qubit quantum state.
title (str): a string that represents the plot title
figsize (tuple): size of each individual Bloch sphere figure, in inches.
reverse_bits (bool): If True, plots qubits following Qiskit's convention [Default:False].
font_size (float): Font size for the Bloch ball figures.
title_font_size (float): Font size for the title.
title_pad (float): Padding for the title (suptitle `y` position is `y=1+title_pad/100`).
Returns:
:class:`matplotlib:matplotlib.figure.Figure` :
A matplotlib figure instance.
Raises:
MissingOptionalLibraryError: Requires matplotlib.
VisualizationError: if input is not a valid N-qubit state.
Examples:
.. plot::
:include-source:
from qiskit import QuantumCircuit
from qiskit.quantum_info import Statevector
from qiskit.visualization import plot_bloch_multivector
qc = QuantumCircuit(2)
qc.h(0)
qc.x(1)
state = Statevector(qc)
plot_bloch_multivector(state)
.. plot::
:include-source:
from qiskit import QuantumCircuit
from qiskit.quantum_info import Statevector
from qiskit.visualization import plot_bloch_multivector
qc = QuantumCircuit(2)
qc.h(0)
qc.x(1)
# You can reverse the order of the qubits.
from qiskit.quantum_info import DensityMatrix
qc = QuantumCircuit(2)
qc.h([0, 1])
qc.t(1)
qc.s(0)
qc.cx(0,1)
matrix = DensityMatrix(qc)
plot_bloch_multivector(matrix, title='My Bloch Spheres', reverse_bits=True)
"""
from matplotlib import pyplot as plt
# Data
bloch_data = (
_bloch_multivector_data(state)[::-1] if reverse_bits else _bloch_multivector_data(state)
)
num = len(bloch_data)
if figsize is not None:
width, height = figsize
width *= num
else:
width, height = plt.figaspect(1 / num)
default_title_font_size = font_size if font_size is not None else 16
title_font_size = title_font_size if title_font_size is not None else default_title_font_size
fig = plt.figure(figsize=(width, height))
for i in range(num):
pos = num - 1 - i if reverse_bits else i
ax = fig.add_subplot(1, num, i + 1, projection="3d")
plot_bloch_vector(
bloch_data[i], "qubit " + str(pos), ax=ax, figsize=figsize, font_size=font_size
)
fig.suptitle(title, fontsize=title_font_size, y=1.0 + title_pad / 100)
matplotlib_close_if_inline(fig)
if filename is None:
return fig
else:
return fig.savefig(filename)
@deprecate_arg("rho", new_alias="state", since="0.15.1")
@_optionals.HAS_MATPLOTLIB.require_in_call
def plot_state_city(
state,
title="",
figsize=None,
color=None,
alpha=1,
ax_real=None,
ax_imag=None,
*,
rho=None,
filename=None,
):
"""Plot the cityscape of quantum state.
Plot two 3d bar graphs (two dimensional) of the real and imaginary
part of the density matrix rho.
Args:
state (Statevector or DensityMatrix or ndarray): an N-qubit quantum state.
title (str): a string that represents the plot title
figsize (tuple): Figure size in inches.
color (list): A list of len=2 giving colors for real and
imaginary components of matrix elements.
alpha (float): Transparency value for bars
ax_real (matplotlib.axes.Axes): An optional Axes object to be used for
the visualization output. If none is specified a new matplotlib
Figure will be created and used. If this is specified without an
ax_imag only the real component plot will be generated.
Additionally, if specified there will be no returned Figure since
it is redundant.
ax_imag (matplotlib.axes.Axes): An optional Axes object to be used for
the visualization output. If none is specified a new matplotlib
Figure will be created and used. If this is specified without an
ax_real only the imaginary component plot will be generated.
Additionally, if specified there will be no returned Figure since
it is redundant.
Returns:
:class:`matplotlib:matplotlib.figure.Figure` :
The matplotlib.Figure of the visualization if the
``ax_real`` and ``ax_imag`` kwargs are not set
Raises:
MissingOptionalLibraryError: Requires matplotlib.
ValueError: When 'color' is not a list of len=2.
VisualizationError: if input is not a valid N-qubit state.
Examples:
.. plot::
:include-source:
# You can choose different colors for the real and imaginary parts of the density matrix.
from qiskit import QuantumCircuit
from qiskit.quantum_info import DensityMatrix
from qiskit.visualization import plot_state_city
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
state = DensityMatrix(qc)
plot_state_city(state, color=['midnightblue', 'crimson'], title="New State City")
.. plot::
:include-source:
# You can make the bars more transparent to better see the ones that are behind
# if they overlap.
import numpy as np
from qiskit.quantum_info import Statevector
from qiskit.visualization import plot_state_city
from qiskit import QuantumCircuit
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
qc = QuantumCircuit(2)
qc.h([0, 1])
qc.cz(0,1)
qc.ry(np.pi/3, 0)
qc.rx(np.pi/5, 1)
state = Statevector(qc)
plot_state_city(state, alpha=0.6)
"""
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d.art3d import Poly3DCollection
rho = DensityMatrix(state)
num = rho.num_qubits
if num is None:
raise VisualizationError("Input is not a multi-qubit quantum state.")
# get the real and imag parts of rho
datareal = np.real(rho.data)
dataimag = np.imag(rho.data)
# get the labels
column_names = [bin(i)[2:].zfill(num) for i in range(2**num)]
row_names = [bin(i)[2:].zfill(num) for i in range(2**num)]
lx = len(datareal[0]) # Work out matrix dimensions
ly = len(datareal[:, 0])
xpos = np.arange(0, lx, 1) # Set up a mesh of positions
ypos = np.arange(0, ly, 1)
xpos, ypos = np.meshgrid(xpos + 0.25, ypos + 0.25)
xpos = xpos.flatten()
ypos = ypos.flatten()
zpos = np.zeros(lx * ly)
dx = 0.5 * np.ones_like(zpos) # width of bars
dy = dx.copy()
dzr = datareal.flatten()
dzi = dataimag.flatten()
if color is None:
color = ["#648fff", "#648fff"]
else:
if len(color) != 2:
raise ValueError("'color' must be a list of len=2.")
if color[0] is None:
color[0] = "#648fff"
if color[1] is None:
color[1] = "#648fff"
if ax_real is None and ax_imag is None:
# set default figure size
if figsize is None:
figsize = (15, 5)
fig = plt.figure(figsize=figsize)
ax1 = fig.add_subplot(1, 2, 1, projection="3d")
ax2 = fig.add_subplot(1, 2, 2, projection="3d")
elif ax_real is not None:
fig = ax_real.get_figure()
ax1 = ax_real
ax2 = ax_imag
else:
fig = ax_imag.get_figure()
ax1 = None
ax2 = ax_imag
max_dzr = max(dzr)
min_dzr = min(dzr)
min_dzi = np.min(dzi)
max_dzi = np.max(dzi)
# There seems to be a rounding error in which some zero bars are negative
dzr = np.clip(dzr, 0, None)
if ax1 is not None:
fc1 = generate_facecolors(xpos, ypos, zpos, dx, dy, dzr, color[0])
for idx, cur_zpos in enumerate(zpos):
if dzr[idx] > 0:
zorder = 2
else:
zorder = 0
b1 = ax1.bar3d(
xpos[idx],
ypos[idx],
cur_zpos,
dx[idx],
dy[idx],
dzr[idx],
alpha=alpha,
zorder=zorder,
)
b1.set_facecolors(fc1[6 * idx : 6 * idx + 6])
xlim, ylim = ax1.get_xlim(), ax1.get_ylim()
x = [xlim[0], xlim[1], xlim[1], xlim[0]]
y = [ylim[0], ylim[0], ylim[1], ylim[1]]
z = [0, 0, 0, 0]
verts = [list(zip(x, y, z))]
pc1 = Poly3DCollection(verts, alpha=0.15, facecolor="k", linewidths=1, zorder=1)
if min(dzr) < 0 < max(dzr):
ax1.add_collection3d(pc1)
ax1.set_xticks(np.arange(0.5, lx + 0.5, 1))
ax1.set_yticks(np.arange(0.5, ly + 0.5, 1))
if max_dzr != min_dzr:
ax1.axes.set_zlim3d(np.min(dzr), max(np.max(dzr) + 1e-9, max_dzi))
else:
if min_dzr == 0:
ax1.axes.set_zlim3d(np.min(dzr), max(np.max(dzr) + 1e-9, np.max(dzi)))
else:
ax1.axes.set_zlim3d(auto=True)
ax1.get_autoscalez_on()
ax1.xaxis.set_ticklabels(row_names, fontsize=14, rotation=45, ha="right", va="top")
ax1.yaxis.set_ticklabels(column_names, fontsize=14, rotation=-22.5, ha="left", va="center")
ax1.set_zlabel("Re[$\\rho$]", fontsize=14)
for tick in ax1.zaxis.get_major_ticks():
tick.label1.set_fontsize(14)
if ax2 is not None:
fc2 = generate_facecolors(xpos, ypos, zpos, dx, dy, dzi, color[1])
for idx, cur_zpos in enumerate(zpos):
if dzi[idx] > 0:
zorder = 2
else:
zorder = 0
b2 = ax2.bar3d(
xpos[idx],
ypos[idx],
cur_zpos,
dx[idx],
dy[idx],
dzi[idx],
alpha=alpha,
zorder=zorder,
)
b2.set_facecolors(fc2[6 * idx : 6 * idx + 6])
xlim, ylim = ax2.get_xlim(), ax2.get_ylim()
x = [xlim[0], xlim[1], xlim[1], xlim[0]]
y = [ylim[0], ylim[0], ylim[1], ylim[1]]
z = [0, 0, 0, 0]
verts = [list(zip(x, y, z))]
pc2 = Poly3DCollection(verts, alpha=0.2, facecolor="k", linewidths=1, zorder=1)
if min(dzi) < 0 < max(dzi):
ax2.add_collection3d(pc2)
ax2.set_xticks(np.arange(0.5, lx + 0.5, 1))
ax2.set_yticks(np.arange(0.5, ly + 0.5, 1))
if min_dzi != max_dzi:
eps = 0
ax2.axes.set_zlim3d(np.min(dzi), max(np.max(dzr) + 1e-9, np.max(dzi) + eps))
else:
if min_dzi == 0:
ax2.set_zticks([0])
eps = 1e-9
ax2.axes.set_zlim3d(np.min(dzi), max(np.max(dzr) + 1e-9, np.max(dzi) + eps))
else:
ax2.axes.set_zlim3d(auto=True)
ax2.xaxis.set_ticklabels(row_names, fontsize=14, rotation=45, ha="right", va="top")
ax2.yaxis.set_ticklabels(column_names, fontsize=14, rotation=-22.5, ha="left", va="center")
ax2.set_zlabel("Im[$\\rho$]", fontsize=14)
for tick in ax2.zaxis.get_major_ticks():
tick.label1.set_fontsize(14)
ax2.get_autoscalez_on()
fig.suptitle(title, fontsize=16)
if ax_real is None and ax_imag is None:
matplotlib_close_if_inline(fig)
if filename is None:
return fig
else:
return fig.savefig(filename)
@deprecate_arg("rho", new_alias="state", since="0.15.1")
@_optionals.HAS_MATPLOTLIB.require_in_call
def plot_state_paulivec(
state, title="", figsize=None, color=None, ax=None, *, rho=None, filename=None
):
r"""Plot the Pauli-vector representation of a quantum state as bar graph.
The Pauli-vector of a density matrix :math:`\rho` is defined by the expectation of each
possible tensor product of single-qubit Pauli operators (including the identity), that is
.. math ::
\rho = \frac{1}{2^n} \sum_{\sigma \in \{I, X, Y, Z\}^{\otimes n}}
\mathrm{Tr}(\sigma \rho) \sigma.
This function plots the coefficients :math:`\mathrm{Tr}(\sigma\rho)` as bar graph.
Args:
state (Statevector or DensityMatrix or ndarray): an N-qubit quantum state.
title (str): a string that represents the plot title
figsize (tuple): Figure size in inches.
color (list or str): Color of the coefficient value bars.
ax (matplotlib.axes.Axes): An optional Axes object to be used for
the visualization output. If none is specified a new matplotlib
Figure will be created and used. Additionally, if specified there
will be no returned Figure since it is redundant.
Returns:
:class:`matplotlib:matplotlib.figure.Figure` :
The matplotlib.Figure of the visualization if the
``ax`` kwarg is not set
Raises:
MissingOptionalLibraryError: Requires matplotlib.
VisualizationError: if input is not a valid N-qubit state.
Examples:
.. plot::
:include-source:
# You can set a color for all the bars.
from qiskit import QuantumCircuit
from qiskit.quantum_info import Statevector
from qiskit.visualization import plot_state_paulivec
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
state = Statevector(qc)
plot_state_paulivec(state, color='midnightblue', title="New PauliVec plot")
.. plot::
:include-source:
# If you introduce a list with less colors than bars, the color of the bars will
# alternate following the sequence from the list.
import numpy as np
from qiskit.quantum_info import DensityMatrix
from qiskit import QuantumCircuit
from qiskit.visualization import plot_state_paulivec
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
qc = QuantumCircuit(2)
qc.h([0, 1])
qc.cz(0, 1)
qc.ry(np.pi/3, 0)
qc.rx(np.pi/5, 1)
matrix = DensityMatrix(qc)
plot_state_paulivec(matrix, color=['crimson', 'midnightblue', 'seagreen'])
"""
from matplotlib import pyplot as plt
labels, values = _paulivec_data(state)
numelem = len(values)
if figsize is None:
figsize = (7, 5)
if color is None:
color = "#648fff"
ind = np.arange(numelem) # the x locations for the groups
width = 0.5 # the width of the bars
if ax is None:
return_fig = True
fig, ax = plt.subplots(figsize=figsize)
else:
return_fig = False
fig = ax.get_figure()
ax.grid(zorder=0, linewidth=1, linestyle="--")
ax.bar(ind, values, width, color=color, zorder=2)
ax.axhline(linewidth=1, color="k")
# add some text for labels, title, and axes ticks
ax.set_ylabel("Coefficients", fontsize=14)
ax.set_xticks(ind)
ax.set_yticks([-1, -0.5, 0, 0.5, 1])
ax.set_xticklabels(labels, fontsize=14, rotation=70)
ax.set_xlabel("Pauli", fontsize=14)
ax.set_ylim([-1, 1])
ax.set_facecolor("#eeeeee")
for tick in ax.xaxis.get_major_ticks() + ax.yaxis.get_major_ticks():
tick.label1.set_fontsize(14)
ax.set_title(title, fontsize=16)
if return_fig:
matplotlib_close_if_inline(fig)
if filename is None:
return fig
else:
return fig.savefig(filename)
def n_choose_k(n, k):
"""Return the number of combinations for n choose k.
Args:
n (int): the total number of options .
k (int): The number of elements.
Returns:
int: returns the binomial coefficient
"""
if n == 0:
return 0
return reduce(lambda x, y: x * y[0] / y[1], zip(range(n - k + 1, n + 1), range(1, k + 1)), 1)
def lex_index(n, k, lst):
"""Return the lex index of a combination..
Args:
n (int): the total number of options .
k (int): The number of elements.
lst (list): list
Returns:
int: returns int index for lex order
Raises:
VisualizationError: if length of list is not equal to k
"""
if len(lst) != k:
raise VisualizationError("list should have length k")
comb = [n - 1 - x for x in lst]
dualm = sum(n_choose_k(comb[k - 1 - i], i + 1) for i in range(k))
return int(dualm)
def bit_string_index(s):
"""Return the index of a string of 0s and 1s."""
n = len(s)
k = s.count("1")
if s.count("0") != n - k:
raise VisualizationError("s must be a string of 0 and 1")
ones = [pos for pos, char in enumerate(s) if char == "1"]
return lex_index(n, k, ones)
def phase_to_rgb(complex_number):
"""Map a phase of a complexnumber to a color in (r,g,b).
complex_number is phase is first mapped to angle in the range
[0, 2pi] and then to the HSL color wheel
"""
angles = (np.angle(complex_number) + (np.pi * 5 / 4)) % (np.pi * 2)
rgb = colorsys.hls_to_rgb(angles / (np.pi * 2), 0.5, 0.5)
return rgb
@deprecate_arg("rho", new_alias="state", since="0.15.1")
@_optionals.HAS_MATPLOTLIB.require_in_call
@_optionals.HAS_SEABORN.require_in_call
def plot_state_qsphere(
state,
figsize=None,
ax=None,
show_state_labels=True,
show_state_phases=False,
use_degrees=False,
*,
rho=None,
filename=None,
):
"""Plot the qsphere representation of a quantum state.
Here, the size of the points is proportional to the probability
of the corresponding term in the state and the color represents
the phase.
Args:
state (Statevector or DensityMatrix or ndarray): an N-qubit quantum state.
figsize (tuple): Figure size in inches.
ax (matplotlib.axes.Axes): An optional Axes object to be used for
the visualization output. If none is specified a new matplotlib
Figure will be created and used. Additionally, if specified there
will be no returned Figure since it is redundant.
show_state_labels (bool): An optional boolean indicating whether to
show labels for each basis state.
show_state_phases (bool): An optional boolean indicating whether to
show the phase for each basis state.
use_degrees (bool): An optional boolean indicating whether to use
radians or degrees for the phase values in the plot.
Returns:
:class:`matplotlib:matplotlib.figure.Figure` :
A matplotlib figure instance if the ``ax`` kwarg is not set
Raises:
MissingOptionalLibraryError: Requires matplotlib.
VisualizationError: if input is not a valid N-qubit state.
QiskitError: Input statevector does not have valid dimensions.
Examples:
.. plot::
:include-source:
from qiskit import QuantumCircuit
from qiskit.quantum_info import Statevector
from qiskit.visualization import plot_state_qsphere
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
state = Statevector(qc)
plot_state_qsphere(state)
.. plot::
:include-source:
# You can show the phase of each state and use
# degrees instead of radians
from qiskit.quantum_info import DensityMatrix
import numpy as np
from qiskit import QuantumCircuit
from qiskit.visualization import plot_state_qsphere
qc = QuantumCircuit(2)
qc.h([0, 1])
qc.cz(0,1)
qc.ry(np.pi/3, 0)
qc.rx(np.pi/5, 1)
qc.z(1)
matrix = DensityMatrix(qc)
plot_state_qsphere(matrix,
show_state_phases = True, use_degrees = True)
"""
from matplotlib import gridspec
from matplotlib import pyplot as plt
from matplotlib.patches import Circle
import seaborn as sns
from scipy import linalg
from .bloch import Arrow3D
rho = DensityMatrix(state)
num = rho.num_qubits
if num is None:
raise VisualizationError("Input is not a multi-qubit quantum state.")
# get the eigenvectors and eigenvalues
eigvals, eigvecs = linalg.eigh(rho.data)
if figsize is None:
figsize = (7, 7)
if ax is None:
return_fig = True
fig = plt.figure(figsize=figsize)
else:
return_fig = False
fig = ax.get_figure()
gs = gridspec.GridSpec(nrows=3, ncols=3)
ax = fig.add_subplot(gs[0:3, 0:3], projection="3d")
ax.axes.set_xlim3d(-1.0, 1.0)
ax.axes.set_ylim3d(-1.0, 1.0)
ax.axes.set_zlim3d(-1.0, 1.0)
ax.axes.grid(False)
ax.view_init(elev=5, azim=275)
# Force aspect ratio
# MPL 3.2 or previous do not have set_box_aspect
if hasattr(ax.axes, "set_box_aspect"):
ax.axes.set_box_aspect((1, 1, 1))
# start the plotting
# Plot semi-transparent sphere
u = np.linspace(0, 2 * np.pi, 25)
v = np.linspace(0, np.pi, 25)
x = np.outer(np.cos(u), np.sin(v))
y = np.outer(np.sin(u), np.sin(v))
z = np.outer(np.ones(np.size(u)), np.cos(v))
ax.plot_surface(
x, y, z, rstride=1, cstride=1, color=plt.rcParams["grid.color"], alpha=0.2, linewidth=0
)
# Get rid of the panes
ax.xaxis.set_pane_color((1.0, 1.0, 1.0, 0.0))
ax.yaxis.set_pane_color((1.0, 1.0, 1.0, 0.0))
ax.zaxis.set_pane_color((1.0, 1.0, 1.0, 0.0))
# Get rid of the spines
ax.xaxis.line.set_color((1.0, 1.0, 1.0, 0.0))
ax.yaxis.line.set_color((1.0, 1.0, 1.0, 0.0))
ax.zaxis.line.set_color((1.0, 1.0, 1.0, 0.0))
# Get rid of the ticks
ax.set_xticks([])
ax.set_yticks([])
ax.set_zticks([])
# traversing the eigvals/vecs backward as sorted low->high
for idx in range(eigvals.shape[0] - 1, -1, -1):
if eigvals[idx] > 0.001:
# get the max eigenvalue
state = eigvecs[:, idx]
loc = np.absolute(state).argmax()
# remove the global phase from max element
angles = (np.angle(state[loc]) + 2 * np.pi) % (2 * np.pi)
angleset = np.exp(-1j * angles)
state = angleset * state
d = num
for i in range(2**num):
# get x,y,z points
element = bin(i)[2:].zfill(num)
weight = element.count("1")
zvalue = -2 * weight / d + 1
number_of_divisions = n_choose_k(d, weight)
weight_order = bit_string_index(element)
angle = (float(weight) / d) * (np.pi * 2) + (
weight_order * 2 * (np.pi / number_of_divisions)
)
if (weight > d / 2) or (
(weight == d / 2) and (weight_order >= number_of_divisions / 2)
):
angle = np.pi - angle - (2 * np.pi / number_of_divisions)
xvalue = np.sqrt(1 - zvalue**2) * np.cos(angle)
yvalue = np.sqrt(1 - zvalue**2) * np.sin(angle)
# get prob and angle - prob will be shade and angle color
prob = np.real(np.dot(state[i], state[i].conj()))
prob = min(prob, 1) # See https://github.com/Qiskit/qiskit-terra/issues/4666
colorstate = phase_to_rgb(state[i])
alfa = 1
if yvalue >= 0.1:
alfa = 1.0 - yvalue
if not np.isclose(prob, 0) and show_state_labels:
rprime = 1.3
angle_theta = np.arctan2(np.sqrt(1 - zvalue**2), zvalue)
xvalue_text = rprime * np.sin(angle_theta) * np.cos(angle)
yvalue_text = rprime * np.sin(angle_theta) * np.sin(angle)
zvalue_text = rprime * np.cos(angle_theta)
element_text = "$\\vert" + element + "\\rangle$"
if show_state_phases:
element_angle = (np.angle(state[i]) + (np.pi * 4)) % (np.pi * 2)
if use_degrees:
element_text += "\n$%.1f^\\circ$" % (element_angle * 180 / np.pi)
else:
element_angle = pi_check(element_angle, ndigits=3).replace("pi", "\\pi")
element_text += "\n$%s$" % (element_angle)
ax.text(
xvalue_text,
yvalue_text,
zvalue_text,
element_text,
ha="center",
va="center",
size=12,
)
ax.plot(
[xvalue],
[yvalue],
[zvalue],
markerfacecolor=colorstate,
markeredgecolor=colorstate,
marker="o",
markersize=np.sqrt(prob) * 30,
alpha=alfa,
)
a = Arrow3D(
[0, xvalue],
[0, yvalue],
[0, zvalue],
mutation_scale=20,
alpha=prob,
arrowstyle="-",
color=colorstate,
lw=2,
)
ax.add_artist(a)
# add weight lines
for weight in range(d + 1):
theta = np.linspace(-2 * np.pi, 2 * np.pi, 100)
z = -2 * weight / d + 1
r = np.sqrt(1 - z**2)
x = r * np.cos(theta)
y = r * np.sin(theta)
ax.plot(x, y, z, color=(0.5, 0.5, 0.5), lw=1, ls=":", alpha=0.5)
# add center point
ax.plot(
[0],
[0],
[0],
markerfacecolor=(0.5, 0.5, 0.5),
markeredgecolor=(0.5, 0.5, 0.5),
marker="o",
markersize=3,
alpha=1,
)
else:
break
n = 64
theta = np.ones(n)
colors = sns.hls_palette(n)
ax2 = fig.add_subplot(gs[2:, 2:])
ax2.pie(theta, colors=colors[5 * n // 8 :] + colors[: 5 * n // 8], radius=0.75)
ax2.add_artist(Circle((0, 0), 0.5, color="white", zorder=1))
offset = 0.95 # since radius of sphere is one.
if use_degrees:
labels = ["Phase\n(Deg)", "0", "90", "180 ", "270"]
else:
labels = ["Phase", "$0$", "$\\pi/2$", "$\\pi$", "$3\\pi/2$"]
ax2.text(0, 0, labels[0], horizontalalignment="center", verticalalignment="center", fontsize=14)
ax2.text(
offset, 0, labels[1], horizontalalignment="center", verticalalignment="center", fontsize=14
)
ax2.text(
0, offset, labels[2], horizontalalignment="center", verticalalignment="center", fontsize=14
)
ax2.text(
-offset, 0, labels[3], horizontalalignment="center", verticalalignment="center", fontsize=14
)
ax2.text(
0, -offset, labels[4], horizontalalignment="center", verticalalignment="center", fontsize=14
)
if return_fig:
matplotlib_close_if_inline(fig)
if filename is None:
return fig
else:
return fig.savefig(filename)
@_optionals.HAS_MATPLOTLIB.require_in_call
def generate_facecolors(x, y, z, dx, dy, dz, color):
"""Generates shaded facecolors for shaded bars.
This is here to work around a Matplotlib bug
where alpha does not work in Bar3D.
Args:
x (array_like): The x- coordinates of the anchor point of the bars.
y (array_like): The y- coordinates of the anchor point of the bars.
z (array_like): The z- coordinates of the anchor point of the bars.
dx (array_like): Width of bars.
dy (array_like): Depth of bars.
dz (array_like): Height of bars.
color (array_like): sequence of valid color specifications, optional
Returns:
list: Shaded colors for bars.
Raises:
MissingOptionalLibraryError: If matplotlib is not installed
"""
import matplotlib.colors as mcolors
cuboid = np.array(
[
# -z
(
(0, 0, 0),
(0, 1, 0),
(1, 1, 0),
(1, 0, 0),
),
# +z
(
(0, 0, 1),
(1, 0, 1),
(1, 1, 1),
(0, 1, 1),
),
# -y
(
(0, 0, 0),
(1, 0, 0),
(1, 0, 1),
(0, 0, 1),
),
# +y
(
(0, 1, 0),
(0, 1, 1),
(1, 1, 1),
(1, 1, 0),
),
# -x
(
(0, 0, 0),
(0, 0, 1),
(0, 1, 1),
(0, 1, 0),
),
# +x
(
(1, 0, 0),
(1, 1, 0),
(1, 1, 1),
(1, 0, 1),
),
]
)
# indexed by [bar, face, vertex, coord]
polys = np.empty(x.shape + cuboid.shape)
# handle each coordinate separately
for i, p, dp in [(0, x, dx), (1, y, dy), (2, z, dz)]:
p = p[..., np.newaxis, np.newaxis]
dp = dp[..., np.newaxis, np.newaxis]
polys[..., i] = p + dp * cuboid[..., i]
# collapse the first two axes
polys = polys.reshape((-1,) + polys.shape[2:])
facecolors = []
if len(color) == len(x):
# bar colors specified, need to expand to number of faces
for c in color:
facecolors.extend([c] * 6)
else:
# a single color specified, or face colors specified explicitly
facecolors = list(mcolors.to_rgba_array(color))
if len(facecolors) < len(x):
facecolors *= 6 * len(x)
normals = _generate_normals(polys)
return _shade_colors(facecolors, normals)
def _generate_normals(polygons):
"""Takes a list of polygons and return an array of their normals.
Normals point towards the viewer for a face with its vertices in
counterclockwise order, following the right hand rule.
Uses three points equally spaced around the polygon.
This normal of course might not make sense for polygons with more than
three points not lying in a plane, but it's a plausible and fast
approximation.
Args:
polygons (list): list of (M_i, 3) array_like, or (..., M, 3) array_like
A sequence of polygons to compute normals for, which can have
varying numbers of vertices. If the polygons all have the same
number of vertices and array is passed, then the operation will
be vectorized.
Returns:
normals: (..., 3) array_like
A normal vector estimated for the polygon.
"""
if isinstance(polygons, np.ndarray):
# optimization: polygons all have the same number of points, so can
# vectorize
n = polygons.shape[-2]
i1, i2, i3 = 0, n // 3, 2 * n // 3
v1 = polygons[..., i1, :] - polygons[..., i2, :]
v2 = polygons[..., i2, :] - polygons[..., i3, :]
else:
# The subtraction doesn't vectorize because polygons is jagged.
v1 = np.empty((len(polygons), 3))
v2 = np.empty((len(polygons), 3))
for poly_i, ps in enumerate(polygons):
n = len(ps)
i1, i2, i3 = 0, n // 3, 2 * n // 3
v1[poly_i, :] = ps[i1, :] - ps[i2, :]
v2[poly_i, :] = ps[i2, :] - ps[i3, :]
return np.cross(v1, v2)
def _shade_colors(color, normals, lightsource=None):
"""
Shade *color* using normal vectors given by *normals*.
*color* can also be an array of the same length as *normals*.
"""
from matplotlib.colors import Normalize, LightSource
import matplotlib.colors as mcolors
if lightsource is None:
# chosen for backwards-compatibility
lightsource = LightSource(azdeg=225, altdeg=19.4712)
def mod(v):
return np.sqrt(v[0] ** 2 + v[1] ** 2 + v[2] ** 2)
shade = np.array(
[np.dot(n / mod(n), lightsource.direction) if mod(n) else np.nan for n in normals]
)
mask = ~np.isnan(shade)
if mask.any():
norm = Normalize(min(shade[mask]), max(shade[mask]))
shade[~mask] = min(shade[mask])
color = mcolors.to_rgba_array(color)
# shape of color should be (M, 4) (where M is number of faces)
# shape of shade should be (M,)
# colors should have final shape of (M, 4)
alpha = color[:, 3]
colors = (0.5 + norm(shade)[:, np.newaxis] * 0.5) * color
colors[:, 3] = alpha
else:
colors = np.asanyarray(color).copy()
return colors
def state_to_latex(
state: Union[Statevector, DensityMatrix], dims: bool = None, convention: str = "ket", **args
) -> str:
"""Return a Latex representation of a state. Wrapper function
for `qiskit.visualization.array_to_latex` for convention 'vector'.
Adds dims if necessary.
Intended for use within `state_drawer`.
Args:
state: State to be drawn
dims (bool): Whether to display the state's `dims`
convention (str): Either 'vector' or 'ket'. For 'ket' plot the state in the ket-notation.
Otherwise plot as a vector
**args: Arguments to be passed directly to `array_to_latex` for convention 'ket'
Returns:
Latex representation of the state
"""
if dims is None: # show dims if state is not only qubits
if set(state.dims()) == {2}:
dims = False
else:
dims = True
prefix = ""
suffix = ""
if dims:
prefix = "\\begin{align}\n"
dims_str = state._op_shape.dims_l()
suffix = f"\\\\\n\\text{{dims={dims_str}}}\n\\end{{align}}"
operator_shape = state._op_shape
# we only use the ket convetion for qubit statevectors
# this means the operator shape should hve no input dimensions and all output dimensions equal to 2
is_qubit_statevector = len(operator_shape.dims_r()) == 0 and set(operator_shape.dims_l()) == {2}
if convention == "ket" and is_qubit_statevector:
latex_str = _state_to_latex_ket(state._data, **args)
else:
latex_str = array_to_latex(state._data, source=True, **args)
return prefix + latex_str + suffix
@deprecate_func(
additional_msg="For similar functionality, see sympy's ``nsimplify`` and ``latex`` functions.",
since="0.23.0",
)
def num_to_latex_ket(raw_value: complex, first_term: bool, decimals: int = 10) -> Optional[str]:
"""Convert a complex number to latex code suitable for a ket expression
Args:
raw_value: Value to convert
first_term: If True then generate latex code for the first term in an expression
decimals: Number of decimal places to round to (default: 10).
Returns:
String with latex code or None if no term is required
"""
if np.around(np.abs(raw_value), decimals=decimals) == 0:
return None
return _num_to_latex(raw_value, first_term=first_term, decimals=decimals, coefficient=True)
@deprecate_func(
additional_msg="For similar functionality, see sympy's ``nsimplify`` and ``latex`` functions.",
since="0.23.0",
)
def numbers_to_latex_terms(numbers: List[complex], decimals: int = 10) -> List[str]:
"""Convert a list of numbers to latex formatted terms
The first non-zero term is treated differently. For this term a leading + is suppressed.
Args:
numbers: List of numbers to format
decimals: Number of decimal places to round to (default: 10).
Returns:
List of formatted terms
"""
first_term = True
terms = []
for number in numbers:
term = num_to_latex_ket(number, first_term, decimals)
if term is not None:
first_term = False
terms.append(term)
return terms
def _numbers_to_latex_terms(numbers: List[complex], decimals: int = 10) -> List[str]:
"""Convert a list of numbers to latex formatted terms
The first non-zero term is treated differently. For this term a leading + is suppressed.
Args:
numbers: List of numbers to format
decimals: Number of decimal places to round to (default: 10).
Returns:
List of formatted terms
"""
first_term = True
terms = []
for number in numbers:
term = _num_to_latex(number, decimals=decimals, first_term=first_term, coefficient=True)
terms.append(term)
first_term = False
return terms
def _state_to_latex_ket(
data: List[complex], max_size: int = 12, prefix: str = "", decimals: int = 10
) -> str:
"""Convert state vector to latex representation
Args:
data: State vector
max_size: Maximum number of non-zero terms in the expression. If the number of
non-zero terms is larger than the max_size, then the representation is truncated.
prefix: Latex string to be prepended to the latex, intended for labels.
decimals: Number of decimal places to round to (default: 10).
Returns:
String with LaTeX representation of the state vector
"""
num = int(np.log2(len(data)))
def ket_name(i):
return bin(i)[2:].zfill(num)
data = np.around(data, decimals)
nonzero_indices = np.where(data != 0)[0].tolist()
if len(nonzero_indices) > max_size:
nonzero_indices = (
nonzero_indices[: max_size // 2] + [0] + nonzero_indices[-max_size // 2 + 1 :]
)
latex_terms = _numbers_to_latex_terms(data[nonzero_indices], decimals)
nonzero_indices[max_size // 2] = None
else:
latex_terms = _numbers_to_latex_terms(data[nonzero_indices], decimals)
latex_str = ""
for idx, ket_idx in enumerate(nonzero_indices):
if ket_idx is None:
latex_str += r" + \ldots "
else:
term = latex_terms[idx]
ket = ket_name(ket_idx)
latex_str += f"{term} |{ket}\\rangle"
return prefix + latex_str
class TextMatrix:
"""Text representation of an array, with `__str__` method so it
displays nicely in Jupyter notebooks"""
def __init__(self, state, max_size=8, dims=None, prefix="", suffix=""):
self.state = state
self.max_size = max_size
if dims is None: # show dims if state is not only qubits
if (isinstance(state, (Statevector, DensityMatrix)) and set(state.dims()) == {2}) or (
isinstance(state, Operator)
and len(state.input_dims()) == len(state.output_dims())
and set(state.input_dims()) == set(state.output_dims()) == {2}
):
dims = False
else:
dims = True
self.dims = dims
self.prefix = prefix
self.suffix = suffix
if isinstance(max_size, int):
self.max_size = max_size
elif isinstance(state, DensityMatrix):
# density matrices are square, so threshold for
# summarization is shortest side squared
self.max_size = min(max_size) ** 2
else:
self.max_size = max_size[0]
def __str__(self):
threshold = self.max_size
data = np.array2string(
self.state._data, prefix=self.prefix, threshold=threshold, separator=","
)
dimstr = ""
if self.dims:
data += ",\n"
dimstr += " " * len(self.prefix)
if isinstance(self.state, (Statevector, DensityMatrix)):
dimstr += f"dims={self.state._op_shape.dims_l()}"
else:
dimstr += f"input_dims={self.state.input_dims()}, "
dimstr += f"output_dims={self.state.output_dims()}"
return self.prefix + data + dimstr + self.suffix
def __repr__(self):
return self.__str__()
def state_drawer(state, output=None, **drawer_args):
"""Returns a visualization of the state.
**repr**: ASCII TextMatrix of the state's ``_repr_``.
**text**: ASCII TextMatrix that can be printed in the console.
**latex**: An IPython Latex object for displaying in Jupyter Notebooks.
**latex_source**: Raw, uncompiled ASCII source to generate array using LaTeX.
**qsphere**: Matplotlib figure, rendering of statevector using `plot_state_qsphere()`.
**hinton**: Matplotlib figure, rendering of statevector using `plot_state_hinton()`.
**bloch**: Matplotlib figure, rendering of statevector using `plot_bloch_multivector()`.
**city**: Matplotlib figure, rendering of statevector using `plot_state_city()`.
**paulivec**: Matplotlib figure, rendering of statevector using `plot_state_paulivec()`.
Args:
output (str): Select the output method to use for drawing the
circuit. Valid choices are ``text``, ``latex``, ``latex_source``,
``qsphere``, ``hinton``, ``bloch``, ``city`` or ``paulivec``.
Default is `'text`'.
drawer_args: Arguments to be passed to the relevant drawer. For
'latex' and 'latex_source' see ``array_to_latex``
Returns:
:class:`matplotlib.figure` or :class:`str` or
:class:`TextMatrix` or :class:`IPython.display.Latex`:
Drawing of the state.
Raises:
MissingOptionalLibraryError: when `output` is `latex` and IPython is not installed.
ValueError: when `output` is not a valid selection.
"""
config = user_config.get_config()
# Get default 'output' from config file else use 'repr'
default_output = "repr"
if output is None:
if config:
default_output = config.get("state_drawer", "repr")
output = default_output
output = output.lower()
# Choose drawing backend:
drawers = {
"text": TextMatrix,
"latex_source": state_to_latex,
"qsphere": plot_state_qsphere,
"hinton": plot_state_hinton,
"bloch": plot_bloch_multivector,
"city": plot_state_city,
"paulivec": plot_state_paulivec,
}
if output == "latex":
_optionals.HAS_IPYTHON.require_now("state_drawer")
from IPython.display import Latex
draw_func = drawers["latex_source"]
return Latex(f"$${draw_func(state, **drawer_args)}$$")
if output == "repr":
return state.__repr__()
try:
draw_func = drawers[output]
return draw_func(state, **drawer_args)
except KeyError as err:
raise ValueError(
"""'{}' is not a valid option for drawing {} objects. Please choose from:
'text', 'latex', 'latex_source', 'qsphere', 'hinton',
'bloch', 'city' or 'paulivec'.""".format(
output, type(state).__name__
)
) from err
def _bloch_multivector_data(state):
"""Return list of Bloch vectors for each qubit
Args:
state (DensityMatrix or Statevector): an N-qubit state.
Returns:
list: list of Bloch vectors (x, y, z) for each qubit.
Raises:
VisualizationError: if input is not an N-qubit state.
"""
rho = DensityMatrix(state)
num = rho.num_qubits
if num is None:
raise VisualizationError("Input is not a multi-qubit quantum state.")
pauli_singles = PauliList(["X", "Y", "Z"])
bloch_data = []
for i in range(num):
if num > 1:
paulis = PauliList.from_symplectic(
np.zeros((3, (num - 1)), dtype=bool), np.zeros((3, (num - 1)), dtype=bool)
).insert(i, pauli_singles, qubit=True)
else:
paulis = pauli_singles
bloch_state = [np.real(np.trace(np.dot(mat, rho.data))) for mat in paulis.matrix_iter()]
bloch_data.append(bloch_state)
return bloch_data
def _paulivec_data(state):
"""Return paulivec data for plotting.
Args:
state (DensityMatrix or Statevector): an N-qubit state.
Returns:
tuple: (labels, values) for Pauli vector.
Raises:
VisualizationError: if input is not an N-qubit state.
"""
rho = SparsePauliOp.from_operator(DensityMatrix(state))
if rho.num_qubits is None:
raise VisualizationError("Input is not a multi-qubit quantum state.")
return rho.paulis.to_labels(), np.real(rho.coeffs * 2**rho.num_qubits)
|
https://github.com/primaryobjects/oracle
|
primaryobjects
|
import json
import logging
import numpy as np
import warnings
from functools import wraps
from typing import Any, Callable, Optional, Tuple, Union
from qiskit import IBMQ, QuantumCircuit, assemble
from qiskit.circuit import Barrier, Gate, Instruction, Measure
from qiskit.circuit.library import UGate, U3Gate, CXGate
from qiskit.providers.ibmq import AccountProvider, IBMQProviderError
from qiskit.providers.ibmq.job import IBMQJob
def get_provider() -> AccountProvider:
with warnings.catch_warnings():
warnings.simplefilter('ignore')
ibmq_logger = logging.getLogger('qiskit.providers.ibmq')
current_level = ibmq_logger.level
ibmq_logger.setLevel(logging.ERROR)
# get provider
try:
provider = IBMQ.get_provider()
except IBMQProviderError:
provider = IBMQ.load_account()
ibmq_logger.setLevel(current_level)
return provider
def get_job(job_id: str) -> Optional[IBMQJob]:
try:
job = get_provider().backends.retrieve_job(job_id)
return job
except Exception:
pass
return None
def circuit_to_json(qc: QuantumCircuit) -> str:
class _QobjEncoder(json.encoder.JSONEncoder):
def default(self, obj: Any) -> Any:
if isinstance(obj, np.ndarray):
return obj.tolist()
if isinstance(obj, complex):
return (obj.real, obj.imag)
return json.JSONEncoder.default(self, obj)
return json.dumps(circuit_to_dict(qc), cls=_QobjEncoder)
def circuit_to_dict(qc: QuantumCircuit) -> dict:
qobj = assemble(qc)
return qobj.to_dict()
def get_job_urls(job: Union[str, IBMQJob]) -> Tuple[bool, Optional[str], Optional[str]]:
try:
job_id = job.job_id() if isinstance(job, IBMQJob) else job
download_url = get_provider()._api_client.account_api.job(job_id).download_url()['url']
result_url = get_provider()._api_client.account_api.job(job_id).result_url()['url']
return download_url, result_url
except Exception:
return None, None
def cached(key_function: Callable) -> Callable:
def _decorator(f: Any) -> Callable:
f.__cache = {}
@wraps(f)
def _decorated(*args: Any, **kwargs: Any) -> int:
key = key_function(*args, **kwargs)
if key not in f.__cache:
f.__cache[key] = f(*args, **kwargs)
return f.__cache[key]
return _decorated
return _decorator
def gate_key(gate: Gate) -> Tuple[str, int]:
return gate.name, gate.num_qubits
@cached(gate_key)
def gate_cost(gate: Gate) -> int:
if isinstance(gate, (UGate, U3Gate)):
return 1
elif isinstance(gate, CXGate):
return 10
elif isinstance(gate, (Measure, Barrier)):
return 0
return sum(map(gate_cost, (g for g, _, _ in gate.definition.data)))
def compute_cost(circuit: Union[Instruction, QuantumCircuit]) -> int:
print('Computing cost...')
circuit_data = None
if isinstance(circuit, QuantumCircuit):
circuit_data = circuit.data
elif isinstance(circuit, Instruction):
circuit_data = circuit.definition.data
else:
raise Exception(f'Unable to obtain circuit data from {type(circuit)}')
return sum(map(gate_cost, (g for g, _, _ in circuit_data)))
def uses_multiqubit_gate(circuit: QuantumCircuit) -> bool:
circuit_data = None
if isinstance(circuit, QuantumCircuit):
circuit_data = circuit.data
elif isinstance(circuit, Instruction) and circuit.definition is not None:
circuit_data = circuit.definition.data
else:
raise Exception(f'Unable to obtain circuit data from {type(circuit)}')
for g, _, _ in circuit_data:
if isinstance(g, (Barrier, Measure)):
continue
elif isinstance(g, Gate):
if g.num_qubits > 1:
return True
elif isinstance(g, (QuantumCircuit, Instruction)) and uses_multiqubit_gate(g):
return True
return False
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""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/AmirhoseynpowAsghari/Qiskit-Tutorials
|
AmirhoseynpowAsghari
|
import numpy as np
# Parameters
J = 1
k_B = 1
T = 2.269 # Critical temperature
K = J / (k_B * T)
# Transfer matrix for a 2x2 Ising model (simplified example)
def transfer_matrix(K):
T = np.zeros((4, 4))
configs = [(-1, -1), (-1, 1), (1, -1), (1, 1)]
for i, (s1, s2) in enumerate(configs):
for j, (s3, s4) in enumerate(configs):
E = K * (s1*s2 + s2*s3 + s3*s4 + s4*s1)
T[i, j] = np.exp(E)
return T
T_matrix = transfer_matrix(K)
eigenvalues, _ = np.linalg.eig(T_matrix)
lambda_max = np.max(eigenvalues)
# Free energy per spin
f = -k_B * T * np.log(lambda_max)
print(f"Free energy per spin: {f:.4f}")
# Output the transfer matrix and its largest eigenvalue
print("Transfer matrix:\n", T_matrix)
print("Largest eigenvalue:", lambda_max)
import numpy as np
import random
import math
def MC_step(config, beta):
'''Monte Carlo move using Metropolis algorithm '''
L = len(config)
for _ in range(L * L): # Corrected the loop
a = np.random.randint(0, L)
b = np.random.randint(0, L)
sigma = config[a, b]
neighbors = (config[(a + 1) % L, b] + config[a, (b + 1) % L] +
config[(a - 1) % L, b] + config[a, (b - 1) % L])
del_E = 2 * sigma * neighbors
if del_E < 0 or random.uniform(0, 1) < np.exp(-del_E * beta):
config[a, b] = -sigma
return config
def E_dimensionless(config, L):
'''Calculate the energy of the configuration'''
energy = 0
for i in range(L):
for j in range(L):
S = config[i, j]
neighbors = (config[(i + 1) % L, j] + config[i, (j + 1) % L] +
config[(i - 1) % L, j] + config[i, (j - 1) % L])
energy += -neighbors * S
return energy / 4 # To compensate for overcounting
def magnetization(config):
'''Calculate the magnetization of the configuration'''
return np.sum(config)
def calcul_energy_mag_C_X(config, L, eqSteps, err_runs):
print('finished')
nt = 100 # number of temperature points
mcSteps = 1000
T_c = 2 / math.log(1 + math.sqrt(2))
T = np.linspace(1., 7., nt)
E, M, C, X = np.zeros(nt), np.zeros(nt), np.zeros(nt), np.zeros(nt)
C_theoric, M_theoric = np.zeros(nt), np.zeros(nt)
delta_E, delta_M, delta_C, delta_X = np.zeros(nt), np.zeros(nt), np.zeros(nt), np.zeros(nt)
n1 = 1.0 / (mcSteps * L * L)
n2 = 1.0 / (mcSteps * mcSteps * L * L)
Energies, Magnetizations, SpecificHeats, Susceptibilities = [], [], [], []
delEnergies, delMagnetizations, delSpecificHeats, delSusceptibilities = [], [], [], []
for t in range(nt):
beta = 1. / T[t]
# Equilibrate the system
for _ in range(eqSteps):
MC_step(config, beta)
Ez, Cz, Mz, Xz = [], [], [], []
for _ in range(err_runs):
E, E_squared, M, M_squared = 0, 0, 0, 0
for _ in range(mcSteps):
MC_step(config, beta)
energy = E_dimensionless(config, L)
mag = abs(magnetization(config))
E += energy
E_squared += energy ** 2
M += mag
M_squared += mag ** 2
E_mean = E / mcSteps
E_squared_mean = E_squared / mcSteps
M_mean = M / mcSteps
M_squared_mean = M_squared / mcSteps
Energy = E_mean / (L ** 2)
SpecificHeat = beta ** 2 * (E_squared_mean - E_mean ** 2) / (L ** 2)
Magnetization = M_mean / (L ** 2)
Susceptibility = beta * (M_squared_mean - M_mean ** 2) / (L ** 2)
Ez.append(Energy)
Cz.append(SpecificHeat)
Mz.append(Magnetization)
Xz.append(Susceptibility)
Energies.append(np.mean(Ez))
delEnergies.append(np.std(Ez))
Magnetizations.append(np.mean(Mz))
delMagnetizations.append(np.std(Mz))
SpecificHeats.append(np.mean(Cz))
delSpecificHeats.append(np.std(Cz))
Susceptibilities.append(np.mean(Xz))
delSusceptibilities.append(np.std(Xz))
if T[t] < T_c:
M_theoric[t] = pow(1 - pow(np.sinh(2 * beta), -4), 1 / 8)
C_theoric[t] = (2.0 / np.pi) * (math.log(1 + math.sqrt(2)) ** 2) * (-math.log(1 - T[t] / T_c) + math.log(1.0 / math.log(1 + math.sqrt(2))) - (1 + np.pi / 4))
else:
C_theoric[t] = 0
return (T, Energies, Magnetizations, SpecificHeats, Susceptibilities,
delEnergies, delMagnetizations, M_theoric, C_theoric, delSpecificHeats, delSusceptibilities)
# Parameters
L = 10 # Size of the lattice
eqSteps = 1000 # Number of steps to reach equilibrium
err_runs = 10 # Number of error runs
# Initial configuration (random spins)
config = 2 * np.random.randint(2, size=(L, L)) - 1
# Perform calculations
results = calcul_energy_mag_C_X(config, L, eqSteps, err_runs)
# Unpack results
(T, Energies, Magnetizations, SpecificHeats, Susceptibilities,
delEnergies, delMagnetizations, M_theoric, C_theoric,
delSpecificHeats, delSusceptibilities) = results
# Plot results
import matplotlib.pyplot as plt
plt.figure()
plt.errorbar(T, Energies, yerr=delEnergies, label='Energy')
plt.xlabel('Temperature')
plt.ylabel('Energy')
plt.legend()
plt.show()
plt.figure()
plt.errorbar(T, Magnetizations, yerr=delMagnetizations, label='Magnetization')
plt.xlabel('Temperature')
plt.ylabel('Magnetization')
plt.legend()
plt.show()
plt.figure()
plt.errorbar(T, SpecificHeats, yerr=delSpecificHeats, label='Specific Heat')
plt.plot(T, C_theoric, label='Theoretical Specific Heat')
plt.xlabel('Temperature')
plt.ylabel('Specific Heat')
plt.legend()
plt.show()
plt.figure()
plt.errorbar(T, Susceptibilities, yerr=delSusceptibilities, label='Susceptibility')
plt.xlabel('Temperature')
plt.ylabel('Susceptibility')
plt.legend()
plt.show()
|
https://github.com/darkmatter2000/Quantum_phase_estimation
|
darkmatter2000
|
from qiskit import ClassicalRegister , QuantumCircuit, QuantumRegister
import numpy as np
qr = QuantumRegister(2)
cr = ClassicalRegister(3) #For tree classicals bites
qc = QuantumCircuit(qr , cr)
qc.h(qr[0]) #auxiliary qubit
qc.x(qr[1]) # eigenvector
#qc.cp((3/2)*np.pi , qr[0] , qr[1])
qc.cp(3*np.pi , qr[0] , qr[1])
qc.h(qr[0])
qc.measure(qr[0] , cr[0]) # this is the controlled-U^(2^n-1) operator for determine phi_n
qc.draw("mpl")
qc.reset(qr[0])
qc.h(qr[0])
# la valeur du bit du poids le plus faible est dans cr[0].
#Si cr[0] = 1 on enlΓ©ve le bit de poids le plus faible en fesant la rotation alpha_2
#et on continu le bit n-1 devient le bit le bit de poids le plus faible
#si cr[0] est Γ 0 alors on peut appliquer directement la matrice unitaire associΓ© sans avoir
#Γ faire de rotation inverse alpha_k
with qc.if_test((cr[0] , 1)) as else_:
qc.p(-np.pi/2 , qr[0])
#qc.cp((3/8)*np.pi , qr[0] ,qr[1])
qc.cp((3/2)*np.pi , qr[0] ,qr[1])
qc.h(qr[0]) # For make measure in X basis {|0> , |1>}
qc.measure(qr[0] , cr[1])
qc.draw("mpl")
qc.reset(qr[0])
qc.h(qr[0])
# la valeur du bit du poids le plus faible est dans cr[0].
#Si cr[0] = 1 on enlΓ©ve le bit de poids le plus faible en fesant la rotation alpha_2
#et on continu le bit n-1 devient le bit le bit de poids le plus faible
#si cr[0] est Γ 0 alors on peut appliquer directement la matrice unitaire associΓ© sans avoir
#Γ faire de rotation inverse alpha_k
with qc.if_test((cr[1] , 1)) as else_:
qc.p(-(3/4)*np.pi , qr[0])
qc.cp((3/4)*np.pi , qr[0] ,qr[1])
qc.h(qr[0]) # For make measure in X basis {|0> , |1>}
qc.measure(qr[0] , cr[2])
qc.draw("mpl")
from qiskit_aer import AerSimulator
sim = AerSimulator()
job = sim.run(qc, shots=1000)
result = job.result()
counts = result.get_counts()
counts
import qiskit.tools.jupyter
%qiskit_version_table
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from sklearn.datasets import load_iris
iris_data = load_iris()
print(iris_data.DESCR)
features = iris_data.data
labels = iris_data.target
from sklearn.preprocessing import MinMaxScaler
features = MinMaxScaler().fit_transform(features)
import pandas as pd
import seaborn as sns
df = pd.DataFrame(iris_data.data, columns=iris_data.feature_names)
df["class"] = pd.Series(iris_data.target)
sns.pairplot(df, hue="class", palette="tab10")
from sklearn.model_selection import train_test_split
from qiskit.utils import algorithm_globals
algorithm_globals.random_seed = 123
train_features, test_features, train_labels, test_labels = train_test_split(
features, labels, train_size=0.8, random_state=algorithm_globals.random_seed
)
from sklearn.svm import SVC
svc = SVC()
_ = svc.fit(train_features, train_labels) # suppress printing the return value
train_score_c4 = svc.score(train_features, train_labels)
test_score_c4 = svc.score(test_features, test_labels)
print(f"Classical SVC on the training dataset: {train_score_c4:.2f}")
print(f"Classical SVC on the test dataset: {test_score_c4:.2f}")
from qiskit.circuit.library import ZZFeatureMap
num_features = features.shape[1]
feature_map = ZZFeatureMap(feature_dimension=num_features, reps=1)
feature_map.decompose().draw(output="mpl", fold=20)
from qiskit.circuit.library import RealAmplitudes
ansatz = RealAmplitudes(num_qubits=num_features, reps=3)
ansatz.decompose().draw(output="mpl", fold=20)
from qiskit.algorithms.optimizers import COBYLA
optimizer = COBYLA(maxiter=100)
from qiskit.primitives import Sampler
sampler = Sampler()
from matplotlib import pyplot as plt
from IPython.display import clear_output
objective_func_vals = []
plt.rcParams["figure.figsize"] = (12, 6)
def callback_graph(weights, obj_func_eval):
clear_output(wait=True)
objective_func_vals.append(obj_func_eval)
plt.title("Objective function value against iteration")
plt.xlabel("Iteration")
plt.ylabel("Objective function value")
plt.plot(range(len(objective_func_vals)), objective_func_vals)
plt.show()
import time
from qiskit_machine_learning.algorithms.classifiers import VQC
vqc = VQC(
sampler=sampler,
feature_map=feature_map,
ansatz=ansatz,
optimizer=optimizer,
callback=callback_graph,
)
# clear objective value history
objective_func_vals = []
start = time.time()
vqc.fit(train_features, train_labels)
elapsed = time.time() - start
print(f"Training time: {round(elapsed)} seconds")
train_score_q4 = vqc.score(train_features, train_labels)
test_score_q4 = vqc.score(test_features, test_labels)
print(f"Quantum VQC on the training dataset: {train_score_q4:.2f}")
print(f"Quantum VQC on the test dataset: {test_score_q4:.2f}")
from sklearn.decomposition import PCA
features = PCA(n_components=2).fit_transform(features)
plt.rcParams["figure.figsize"] = (6, 6)
sns.scatterplot(x=features[:, 0], y=features[:, 1], hue=labels, palette="tab10")
train_features, test_features, train_labels, test_labels = train_test_split(
features, labels, train_size=0.8, random_state=algorithm_globals.random_seed
)
svc.fit(train_features, train_labels)
train_score_c2 = svc.score(train_features, train_labels)
test_score_c2 = svc.score(test_features, test_labels)
print(f"Classical SVC on the training dataset: {train_score_c2:.2f}")
print(f"Classical SVC on the test dataset: {test_score_c2:.2f}")
num_features = features.shape[1]
feature_map = ZZFeatureMap(feature_dimension=num_features, reps=1)
ansatz = RealAmplitudes(num_qubits=num_features, reps=3)
optimizer = COBYLA(maxiter=40)
vqc = VQC(
sampler=sampler,
feature_map=feature_map,
ansatz=ansatz,
optimizer=optimizer,
callback=callback_graph,
)
# clear objective value history
objective_func_vals = []
# make the objective function plot look nicer.
plt.rcParams["figure.figsize"] = (12, 6)
start = time.time()
vqc.fit(train_features, train_labels)
elapsed = time.time() - start
print(f"Training time: {round(elapsed)} seconds")
train_score_q2_ra = vqc.score(train_features, train_labels)
test_score_q2_ra = vqc.score(test_features, test_labels)
print(f"Quantum VQC on the training dataset using RealAmplitudes: {train_score_q2_ra:.2f}")
print(f"Quantum VQC on the test dataset using RealAmplitudes: {test_score_q2_ra:.2f}")
from qiskit.circuit.library import EfficientSU2
ansatz = EfficientSU2(num_qubits=num_features, reps=3)
optimizer = COBYLA(maxiter=40)
vqc = VQC(
sampler=sampler,
feature_map=feature_map,
ansatz=ansatz,
optimizer=optimizer,
callback=callback_graph,
)
# clear objective value history
objective_func_vals = []
start = time.time()
vqc.fit(train_features, train_labels)
elapsed = time.time() - start
print(f"Training time: {round(elapsed)} seconds")
train_score_q2_eff = vqc.score(train_features, train_labels)
test_score_q2_eff = vqc.score(test_features, test_labels)
print(f"Quantum VQC on the training dataset using EfficientSU2: {train_score_q2_eff:.2f}")
print(f"Quantum VQC on the test dataset using EfficientSU2: {test_score_q2_eff:.2f}")
print(f"Model | Test Score | Train Score")
print(f"SVC, 4 features | {train_score_c4:10.2f} | {test_score_c4:10.2f}")
print(f"VQC, 4 features, RealAmplitudes | {train_score_q4:10.2f} | {test_score_q4:10.2f}")
print(f"----------------------------------------------------------")
print(f"SVC, 2 features | {train_score_c2:10.2f} | {test_score_c2:10.2f}")
print(f"VQC, 2 features, RealAmplitudes | {train_score_q2_ra:10.2f} | {test_score_q2_ra:10.2f}")
print(f"VQC, 2 features, EfficientSU2 | {train_score_q2_eff:10.2f} | {test_score_q2_eff:10.2f}")
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
#General imports
import numpy as np
#Operator Imports
from qiskit.opflow import Z, X, I, StateFn, CircuitStateFn, SummedOp
from qiskit.opflow.gradients import Gradient, NaturalGradient, QFI, Hessian
#Circuit imports
from qiskit.circuit import QuantumCircuit, QuantumRegister, Parameter, ParameterVector, ParameterExpression
from qiskit.circuit.library import EfficientSU2
# Instantiate the quantum state
a = Parameter('a')
b = Parameter('b')
q = QuantumRegister(1)
qc = QuantumCircuit(q)
qc.h(q)
qc.rz(a, q[0])
qc.rx(b, q[0])
# Instantiate the Hamiltonian observable
H = (2 * X) + Z
# Combine the Hamiltonian observable and the state
op = ~StateFn(H) @ CircuitStateFn(primitive=qc, coeff=1.)
# Print the operator corresponding to the expectation value
print(op)
params = [a, b]
# Define the values to be assigned to the parameters
value_dict = {a: np.pi / 4, b: np.pi}
# Convert the operator and the gradient target params into the respective operator
grad = Gradient().convert(operator = op, params = params)
# Print the operator corresponding to the Gradient
print(grad)
# Assign the parameters and evaluate the gradient
grad_result = grad.assign_parameters(value_dict).eval()
print('Gradient', grad_result)
# Define the Hamiltonian with fixed coefficients
H = 0.5 * X - 1 * Z
# Define the parameters w.r.t. we want to compute the gradients
params = [a, b]
# Define the values to be assigned to the parameters
value_dict = { a: np.pi / 4, b: np.pi}
# Combine the Hamiltonian observable and the state into an expectation value operator
op = ~StateFn(H) @ CircuitStateFn(primitive=qc, coeff=1.)
print(op)
# Convert the expectation value into an operator corresponding to the gradient w.r.t. the state parameters using
# the parameter shift method.
state_grad = Gradient(grad_method='param_shift').convert(operator=op, params=params)
# Print the operator corresponding to the gradient
print(state_grad)
# Assign the parameters and evaluate the gradient
state_grad_result = state_grad.assign_parameters(value_dict).eval()
print('State gradient computed with parameter shift', state_grad_result)
# Convert the expectation value into an operator corresponding to the gradient w.r.t. the state parameter using
# the linear combination of unitaries method.
state_grad = Gradient(grad_method='lin_comb').convert(operator=op, params=params)
# Print the operator corresponding to the gradient
print(state_grad)
# Assign the parameters and evaluate the gradient
state_grad_result = state_grad.assign_parameters(value_dict).eval()
print('State gradient computed with the linear combination method', state_grad_result)
# Convert the expectation value into an operator corresponding to the gradient w.r.t. the state parameter using
# the finite difference method.
state_grad = Gradient(grad_method='fin_diff').convert(operator=op, params=params)
# Print the operator corresponding to the gradient
print(state_grad)
# Assign the parameters and evaluate the gradient
state_grad_result = state_grad.assign_parameters(value_dict).eval()
print('State gradient computed with finite difference', state_grad_result)
# Besides the method to compute the circuit gradients resp. QFI, a regularization method can be chosen:
# `ridge` or `lasso` with automatic parameter search or `perturb_diag_elements` or `perturb_diag`
# which perturb the diagonal elements of the QFI.
nat_grad = NaturalGradient(grad_method='lin_comb', qfi_method='lin_comb_full', regularization='ridge').convert(
operator=op, params=params)
# Assign the parameters and evaluate the gradient
nat_grad_result = nat_grad.assign_parameters(value_dict).eval()
print('Natural gradient computed with linear combination of unitaries', nat_grad_result)
# Instantiate the Hamiltonian observable
H = X
# Instantiate the quantum state with two parameters
a = Parameter('a')
b = Parameter('b')
q = QuantumRegister(1)
qc = QuantumCircuit(q)
qc.h(q)
qc.rz(a, q[0])
qc.rx(b, q[0])
# Combine the Hamiltonian observable and the state
op = ~StateFn(H) @ CircuitStateFn(primitive=qc, coeff=1.)
# Convert the operator and the hessian target coefficients into the respective operator
hessian = Hessian().convert(operator = op, params = [a, b])
# Define the values to be assigned to the parameters
value_dict = {a: np.pi / 4, b: np.pi/4}
# Assign the parameters and evaluate the Hessian w.r.t. the Hamiltonian coefficients
hessian_result = hessian.assign_parameters(value_dict).eval()
print('Hessian \n', np.real(np.array(hessian_result)))
# Define parameters
params = [a, b]
# Get the operator object representing the Hessian
state_hess = Hessian(hess_method='param_shift').convert(operator=op, params=params)
# Assign the parameters and evaluate the Hessian
hessian_result = state_hess.assign_parameters(value_dict).eval()
print('Hessian computed using the parameter shift method\n', (np.array(hessian_result)))
# Get the operator object representing the Hessian
state_hess = Hessian(hess_method='lin_comb').convert(operator=op, params=params)
# Assign the parameters and evaluate the Hessian
hessian_result = state_hess.assign_parameters(value_dict).eval()
print('Hessian computed using the linear combination of unitaries method\n', (np.array(hessian_result)))
# Get the operator object representing the Hessian using finite difference
state_hess = Hessian(hess_method='fin_diff').convert(operator=op, params=params)
# Assign the parameters and evaluate the Hessian
hessian_result = state_hess.assign_parameters(value_dict).eval()
print('Hessian computed with finite difference\n', (np.array(hessian_result)))
# Wrap the quantum circuit into a CircuitStateFn
state = CircuitStateFn(primitive=qc, coeff=1.)
# Convert the state and the parameters into the operator object that represents the QFI
qfi = QFI(qfi_method='lin_comb_full').convert(operator=state, params=params)
# Define the values for which the QFI is to be computed
values_dict = {a: np.pi / 4, b: 0.1}
# Assign the parameters and evaluate the QFI
qfi_result = qfi.assign_parameters(values_dict).eval()
print('full QFI \n', np.real(np.array(qfi_result)))
# Convert the state and the parameters into the operator object that represents the QFI
# and set the approximation to 'block_diagonal'
qfi = QFI('overlap_block_diag').convert(operator=state, params=params)
# Assign the parameters and evaluate the QFI
qfi_result = qfi.assign_parameters(values_dict).eval()
print('Block-diagonal QFI \n', np.real(np.array(qfi_result)))
# Convert the state and the parameters into the operator object that represents the QFI
# and set the approximation to 'diagonal'
qfi = QFI('overlap_diag').convert(operator=state, params=params)
# Assign the parameters and evaluate the QFI
qfi_result = qfi.assign_parameters(values_dict).eval()
print('Diagonal QFI \n', np.real(np.array(qfi_result)))
# Execution Imports
from qiskit import Aer
from qiskit.utils import QuantumInstance
# Algorithm Imports
from qiskit.algorithms import VQE
from qiskit.algorithms.optimizers import CG
from qiskit.opflow import I, X, Z
from qiskit.circuit import QuantumCircuit, ParameterVector
from scipy.optimize import minimize
# Instantiate the system Hamiltonian
h2_hamiltonian = -1.05 * (I ^ I) + 0.39 * (I ^ Z) - 0.39 * (Z ^ I) - 0.01 * (Z ^ Z) + 0.18 * (X ^ X)
# This is the target energy
h2_energy = -1.85727503
# Define the Ansatz
wavefunction = QuantumCircuit(2)
params = ParameterVector('theta', length=8)
it = iter(params)
wavefunction.ry(next(it), 0)
wavefunction.ry(next(it), 1)
wavefunction.rz(next(it), 0)
wavefunction.rz(next(it), 1)
wavefunction.cx(0, 1)
wavefunction.ry(next(it), 0)
wavefunction.ry(next(it), 1)
wavefunction.rz(next(it), 0)
wavefunction.rz(next(it), 1)
# Define the expectation value corresponding to the energy
op = ~StateFn(h2_hamiltonian) @ StateFn(wavefunction)
grad = Gradient(grad_method='lin_comb')
qi_sv = QuantumInstance(Aer.get_backend('aer_simulator_statevector'),
shots=1,
seed_simulator=2,
seed_transpiler=2)
#Conjugate Gradient algorithm
optimizer = CG(maxiter=50)
# Gradient callable
vqe = VQE(wavefunction, optimizer=optimizer, gradient=grad, quantum_instance=qi_sv)
result = vqe.compute_minimum_eigenvalue(h2_hamiltonian)
print('Result:', result.optimal_value, 'Reference:', h2_energy)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
from qiskit.quantum_info import Operator
from qiskit.transpiler.passes import UnitarySynthesis
circuit = QuantumCircuit(1)
circuit.rx(0.8, 0)
unitary = Operator(circuit).data
unitary_circ = QuantumCircuit(1)
unitary_circ.unitary(unitary, [0])
synth = UnitarySynthesis(basis_gates=["h", "s"], method="sk")
out = synth(unitary_circ)
out.draw('mpl')
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2020, 2023.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test cases for the circuit qasm_file and qasm_string method."""
import io
import json
import random
import ddt
import numpy as np
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, pulse
from qiskit.circuit import CASE_DEFAULT
from qiskit.circuit.classical import expr, types
from qiskit.circuit.classicalregister import Clbit
from qiskit.circuit.quantumregister import Qubit
from qiskit.circuit.random import random_circuit
from qiskit.circuit.gate import Gate
from qiskit.circuit.library import (
XGate,
QFT,
QAOAAnsatz,
PauliEvolutionGate,
DCXGate,
MCU1Gate,
MCXGate,
MCXGrayCode,
MCXRecursive,
MCXVChain,
)
from qiskit.circuit.instruction import Instruction
from qiskit.circuit.parameter import Parameter
from qiskit.circuit.parametervector import ParameterVector
from qiskit.synthesis import LieTrotter, SuzukiTrotter
from qiskit.extensions import UnitaryGate
from qiskit.test import QiskitTestCase
from qiskit.qpy import dump, load
from qiskit.quantum_info import Pauli, SparsePauliOp
from qiskit.quantum_info.random import random_unitary
from qiskit.circuit.controlledgate import ControlledGate
@ddt.ddt
class TestLoadFromQPY(QiskitTestCase):
"""Test circuit.from_qasm_* set of methods."""
def assertDeprecatedBitProperties(self, original, roundtripped):
"""Test that deprecated bit attributes are equal if they are set in the original circuit."""
owned_qubits = [
(a, b) for a, b in zip(original.qubits, roundtripped.qubits) if a._register is not None
]
if owned_qubits:
original_qubits, roundtripped_qubits = zip(*owned_qubits)
self.assertEqual(original_qubits, roundtripped_qubits)
owned_clbits = [
(a, b) for a, b in zip(original.clbits, roundtripped.clbits) if a._register is not None
]
if owned_clbits:
original_clbits, roundtripped_clbits = zip(*owned_clbits)
self.assertEqual(original_clbits, roundtripped_clbits)
def test_qpy_full_path(self):
"""Test full path qpy serialization for basic circuit."""
qr_a = QuantumRegister(4, "a")
qr_b = QuantumRegister(4, "b")
cr_c = ClassicalRegister(4, "c")
cr_d = ClassicalRegister(4, "d")
q_circuit = QuantumCircuit(
qr_a,
qr_b,
cr_c,
cr_d,
name="MyCircuit",
metadata={"test": 1, "a": 2},
global_phase=3.14159,
)
q_circuit.h(qr_a)
q_circuit.cx(qr_a, qr_b)
q_circuit.barrier(qr_a)
q_circuit.barrier(qr_b)
q_circuit.measure(qr_a, cr_c)
q_circuit.measure(qr_b, cr_d)
qpy_file = io.BytesIO()
dump(q_circuit, qpy_file)
qpy_file.seek(0)
new_circ = load(qpy_file)[0]
self.assertEqual(q_circuit, new_circ)
self.assertEqual(q_circuit.global_phase, new_circ.global_phase)
self.assertEqual(q_circuit.metadata, new_circ.metadata)
self.assertEqual(q_circuit.name, new_circ.name)
self.assertDeprecatedBitProperties(q_circuit, new_circ)
def test_circuit_with_conditional(self):
"""Test that instructions with conditions are correctly serialized."""
qc = QuantumCircuit(1, 1)
qc.x(0).c_if(qc.cregs[0], 1)
qpy_file = io.BytesIO()
dump(qc, qpy_file)
qpy_file.seek(0)
new_circ = load(qpy_file)[0]
self.assertEqual(qc, new_circ)
self.assertDeprecatedBitProperties(qc, new_circ)
def test_int_parameter(self):
"""Test that integer parameters are correctly serialized."""
qc = QuantumCircuit(1)
qc.rx(3, 0)
qpy_file = io.BytesIO()
dump(qc, qpy_file)
qpy_file.seek(0)
new_circ = load(qpy_file)[0]
self.assertEqual(qc, new_circ)
self.assertDeprecatedBitProperties(qc, new_circ)
def test_float_parameter(self):
"""Test that float parameters are correctly serialized."""
qc = QuantumCircuit(1)
qc.rx(3.14, 0)
qpy_file = io.BytesIO()
dump(qc, qpy_file)
qpy_file.seek(0)
new_circ = load(qpy_file)[0]
self.assertEqual(qc, new_circ)
self.assertDeprecatedBitProperties(qc, new_circ)
def test_numpy_float_parameter(self):
"""Test that numpy float parameters are correctly serialized."""
qc = QuantumCircuit(1)
qc.rx(np.float32(3.14), 0)
qpy_file = io.BytesIO()
dump(qc, qpy_file)
qpy_file.seek(0)
new_circ = load(qpy_file)[0]
self.assertEqual(qc, new_circ)
self.assertDeprecatedBitProperties(qc, new_circ)
def test_numpy_int_parameter(self):
"""Test that numpy integer parameters are correctly serialized."""
qc = QuantumCircuit(1)
qc.rx(np.int16(3), 0)
qpy_file = io.BytesIO()
dump(qc, qpy_file)
qpy_file.seek(0)
new_circ = load(qpy_file)[0]
self.assertEqual(qc, new_circ)
self.assertDeprecatedBitProperties(qc, new_circ)
def test_unitary_gate(self):
"""Test that numpy array parameters are correctly serialized"""
qc = QuantumCircuit(1)
unitary = np.array([[0, 1], [1, 0]])
qc.unitary(unitary, 0)
qpy_file = io.BytesIO()
dump(qc, qpy_file)
qpy_file.seek(0)
new_circ = load(qpy_file)[0]
self.assertEqual(qc, new_circ)
self.assertDeprecatedBitProperties(qc, new_circ)
def test_opaque_gate(self):
"""Test that custom opaque gate is correctly serialized"""
custom_gate = Gate("black_box", 1, [])
qc = QuantumCircuit(1)
qc.append(custom_gate, [0])
qpy_file = io.BytesIO()
dump(qc, qpy_file)
qpy_file.seek(0)
new_circ = load(qpy_file)[0]
self.assertEqual(qc, new_circ)
self.assertDeprecatedBitProperties(qc, new_circ)
def test_opaque_instruction(self):
"""Test that custom opaque instruction is correctly serialized"""
custom_gate = Instruction("black_box", 1, 0, [])
qc = QuantumCircuit(1)
qc.append(custom_gate, [0])
qpy_file = io.BytesIO()
dump(qc, qpy_file)
qpy_file.seek(0)
new_circ = load(qpy_file)[0]
self.assertEqual(qc, new_circ)
self.assertDeprecatedBitProperties(qc, new_circ)
def test_custom_gate(self):
"""Test that custom gate is correctly serialized"""
custom_gate = Gate("black_box", 1, [])
custom_definition = QuantumCircuit(1)
custom_definition.h(0)
custom_definition.rz(1.5, 0)
custom_definition.sdg(0)
custom_gate.definition = custom_definition
qc = QuantumCircuit(1)
qc.append(custom_gate, [0])
qpy_file = io.BytesIO()
dump(qc, qpy_file)
qpy_file.seek(0)
new_circ = load(qpy_file)[0]
self.assertEqual(qc, new_circ)
self.assertEqual(qc.decompose(), new_circ.decompose())
self.assertDeprecatedBitProperties(qc, new_circ)
def test_custom_instruction(self):
"""Test that custom instruction is correctly serialized"""
custom_gate = Instruction("black_box", 1, 0, [])
custom_definition = QuantumCircuit(1)
custom_definition.h(0)
custom_definition.rz(1.5, 0)
custom_definition.sdg(0)
custom_gate.definition = custom_definition
qc = QuantumCircuit(1)
qc.append(custom_gate, [0])
qpy_file = io.BytesIO()
dump(qc, qpy_file)
qpy_file.seek(0)
new_circ = load(qpy_file)[0]
self.assertEqual(qc, new_circ)
self.assertEqual(qc.decompose(), new_circ.decompose())
self.assertDeprecatedBitProperties(qc, new_circ)
def test_parameter(self):
"""Test that a circuit with a parameter is correctly serialized."""
theta = Parameter("theta")
qc = QuantumCircuit(5, 1)
qc.h(0)
for i in range(4):
qc.cx(i, i + 1)
qc.barrier()
qc.rz(theta, range(5))
qc.barrier()
for i in reversed(range(4)):
qc.cx(i, i + 1)
qc.h(0)
qc.measure(0, 0)
qpy_file = io.BytesIO()
dump(qc, qpy_file)
qpy_file.seek(0)
new_circ = load(qpy_file)[0]
self.assertEqual(qc, new_circ)
self.assertEqual(qc.bind_parameters({theta: 3.14}), new_circ.bind_parameters({theta: 3.14}))
self.assertDeprecatedBitProperties(qc, new_circ)
def test_bound_parameter(self):
"""Test a circuit with a bound parameter is correctly serialized."""
theta = Parameter("theta")
qc = QuantumCircuit(5, 1)
qc.h(0)
for i in range(4):
qc.cx(i, i + 1)
qc.barrier()
qc.rz(theta, range(5))
qc.barrier()
for i in reversed(range(4)):
qc.cx(i, i + 1)
qc.h(0)
qc.measure(0, 0)
qc.assign_parameters({theta: 3.14})
qpy_file = io.BytesIO()
dump(qc, qpy_file)
qpy_file.seek(0)
new_circ = load(qpy_file)[0]
self.assertEqual(qc, new_circ)
self.assertDeprecatedBitProperties(qc, new_circ)
def test_bound_calibration_parameter(self):
"""Test a circuit with a bound calibration parameter is correctly serialized.
In particular, this test ensures that parameters on a circuit
instruction are consistent with the circuit's calibrations dictionary
after serialization.
"""
amp = Parameter("amp")
with pulse.builder.build() as sched:
pulse.builder.play(pulse.Constant(100, amp), pulse.DriveChannel(0))
gate = Gate("custom", 1, [amp])
qc = QuantumCircuit(1)
qc.append(gate, (0,))
qc.add_calibration(gate, (0,), sched)
qc.assign_parameters({amp: 1 / 3}, inplace=True)
qpy_file = io.BytesIO()
dump(qc, qpy_file)
qpy_file.seek(0)
new_circ = load(qpy_file)[0]
self.assertEqual(qc, new_circ)
instruction = new_circ.data[0]
cal_key = (
tuple(new_circ.find_bit(q).index for q in instruction.qubits),
tuple(instruction.operation.params),
)
# Make sure that looking for a calibration based on the instruction's
# parameters succeeds
self.assertIn(cal_key, new_circ.calibrations[gate.name])
def test_parameter_expression(self):
"""Test a circuit with a parameter expression."""
theta = Parameter("theta")
phi = Parameter("phi")
sum_param = theta + phi
qc = QuantumCircuit(5, 1)
qc.h(0)
for i in range(4):
qc.cx(i, i + 1)
qc.barrier()
qc.rz(sum_param, range(3))
qc.rz(phi, 3)
qc.rz(theta, 4)
qc.barrier()
for i in reversed(range(4)):
qc.cx(i, i + 1)
qc.h(0)
qc.measure(0, 0)
qpy_file = io.BytesIO()
dump(qc, qpy_file)
qpy_file.seek(0)
new_circuit = load(qpy_file)[0]
self.assertEqual(qc, new_circuit)
self.assertDeprecatedBitProperties(qc, new_circuit)
def test_string_parameter(self):
"""Test a PauliGate instruction that has string parameters."""
circ = QuantumCircuit(3)
circ.z(0)
circ.y(1)
circ.x(2)
qpy_file = io.BytesIO()
dump(circ, qpy_file)
qpy_file.seek(0)
new_circuit = load(qpy_file)[0]
self.assertEqual(circ, new_circuit)
self.assertDeprecatedBitProperties(circ, new_circuit)
def test_multiple_circuits(self):
"""Test multiple circuits can be serialized together."""
circuits = []
for i in range(10):
circuits.append(
random_circuit(10, 10, measure=True, conditional=True, reset=True, seed=42 + i)
)
qpy_file = io.BytesIO()
dump(circuits, qpy_file)
qpy_file.seek(0)
new_circs = load(qpy_file)
self.assertEqual(circuits, new_circs)
for old, new in zip(circuits, new_circs):
self.assertDeprecatedBitProperties(old, new)
def test_shared_bit_register(self):
"""Test a circuit with shared bit registers."""
qubits = [Qubit() for _ in range(5)]
qc = QuantumCircuit()
qc.add_bits(qubits)
qr = QuantumRegister(bits=qubits)
qc.add_register(qr)
qc.h(qr)
qc.cx(0, 1)
qc.cx(0, 2)
qc.cx(0, 3)
qc.cx(0, 4)
qc.measure_all()
qpy_file = io.BytesIO()
dump(qc, qpy_file)
qpy_file.seek(0)
new_qc = load(qpy_file)[0]
self.assertEqual(qc, new_qc)
self.assertDeprecatedBitProperties(qc, new_qc)
def test_hybrid_standalone_register(self):
"""Test qpy serialization with registers that mix bit types"""
qr = QuantumRegister(5, "foo")
qr = QuantumRegister(name="bar", bits=qr[:3] + [Qubit(), Qubit()])
cr = ClassicalRegister(5, "foo")
cr = ClassicalRegister(name="classical_bar", bits=cr[:3] + [Clbit(), Clbit()])
qc = QuantumCircuit(qr, cr)
qc.h(0)
qc.cx(0, 1)
qc.cx(0, 2)
qc.cx(0, 3)
qc.cx(0, 4)
qc.measure(qr, cr)
qpy_file = io.BytesIO()
dump(qc, qpy_file)
qpy_file.seek(0)
new_circ = load(qpy_file)[0]
self.assertEqual(qc, new_circ)
self.assertDeprecatedBitProperties(qc, new_circ)
def test_mixed_registers(self):
"""Test circuit with mix of standalone and shared registers."""
qubits = [Qubit() for _ in range(5)]
clbits = [Clbit() for _ in range(5)]
qc = QuantumCircuit()
qc.add_bits(qubits)
qc.add_bits(clbits)
qr = QuantumRegister(bits=qubits)
cr = ClassicalRegister(bits=clbits)
qc.add_register(qr)
qc.add_register(cr)
qr_standalone = QuantumRegister(2, "standalone")
qc.add_register(qr_standalone)
cr_standalone = ClassicalRegister(2, "classical_standalone")
qc.add_register(cr_standalone)
qc.unitary(random_unitary(32, seed=42), qr)
qc.unitary(random_unitary(4, seed=100), qr_standalone)
qc.measure(qr, cr)
qc.measure(qr_standalone, cr_standalone)
qpy_file = io.BytesIO()
dump(qc, qpy_file)
qpy_file.seek(0)
new_circ = load(qpy_file)[0]
self.assertEqual(qc, new_circ)
self.assertDeprecatedBitProperties(qc, new_circ)
def test_standalone_and_shared_out_of_order(self):
"""Test circuit with register bits inserted out of order."""
qr_standalone = QuantumRegister(2, "standalone")
qubits = [Qubit() for _ in range(5)]
clbits = [Clbit() for _ in range(5)]
qc = QuantumCircuit()
qc.add_bits(qubits)
qc.add_bits(clbits)
random.shuffle(qubits)
random.shuffle(clbits)
qr = QuantumRegister(bits=qubits)
cr = ClassicalRegister(bits=clbits)
qc.add_register(qr)
qc.add_register(cr)
qr_standalone = QuantumRegister(2, "standalone")
cr_standalone = ClassicalRegister(2, "classical_standalone")
qc.add_bits([qr_standalone[1], qr_standalone[0]])
qc.add_bits([cr_standalone[1], cr_standalone[0]])
qc.add_register(qr_standalone)
qc.add_register(cr_standalone)
qc.unitary(random_unitary(32, seed=42), qr)
qc.unitary(random_unitary(4, seed=100), qr_standalone)
qc.measure(qr, cr)
qc.measure(qr_standalone, cr_standalone)
qpy_file = io.BytesIO()
dump(qc, qpy_file)
qpy_file.seek(0)
new_circ = load(qpy_file)[0]
self.assertEqual(qc, new_circ)
self.assertDeprecatedBitProperties(qc, new_circ)
def test_unitary_gate_with_label(self):
"""Test that numpy array parameters are correctly serialized with a label"""
qc = QuantumCircuit(1)
unitary = np.array([[0, 1], [1, 0]])
unitary_gate = UnitaryGate(unitary, "My Special unitary")
qc.append(unitary_gate, [0])
qpy_file = io.BytesIO()
dump(qc, qpy_file)
qpy_file.seek(0)
new_circ = load(qpy_file)[0]
self.assertEqual(qc, new_circ)
self.assertEqual(
[x.operation.label for x in qc.data], [x.operation.label for x in new_circ.data]
)
self.assertDeprecatedBitProperties(qc, new_circ)
def test_opaque_gate_with_label(self):
"""Test that custom opaque gate is correctly serialized with a label"""
custom_gate = Gate("black_box", 1, [])
custom_gate.label = "My Special Black Box"
qc = QuantumCircuit(1)
qc.append(custom_gate, [0])
qpy_file = io.BytesIO()
dump(qc, qpy_file)
qpy_file.seek(0)
new_circ = load(qpy_file)[0]
self.assertEqual(qc, new_circ)
self.assertEqual(
[x.operation.label for x in qc.data], [x.operation.label for x in new_circ.data]
)
self.assertDeprecatedBitProperties(qc, new_circ)
def test_opaque_instruction_with_label(self):
"""Test that custom opaque instruction is correctly serialized with a label"""
custom_gate = Instruction("black_box", 1, 0, [])
custom_gate.label = "My Special Black Box Instruction"
qc = QuantumCircuit(1)
qc.append(custom_gate, [0])
qpy_file = io.BytesIO()
dump(qc, qpy_file)
qpy_file.seek(0)
new_circ = load(qpy_file)[0]
self.assertEqual(qc, new_circ)
self.assertEqual(
[x.operation.label for x in qc.data], [x.operation.label for x in new_circ.data]
)
self.assertDeprecatedBitProperties(qc, new_circ)
def test_custom_gate_with_label(self):
"""Test that custom gate is correctly serialized with a label"""
custom_gate = Gate("black_box", 1, [])
custom_definition = QuantumCircuit(1)
custom_definition.h(0)
custom_definition.rz(1.5, 0)
custom_definition.sdg(0)
custom_gate.definition = custom_definition
custom_gate.label = "My special black box with a definition"
qc = QuantumCircuit(1)
qc.append(custom_gate, [0])
qpy_file = io.BytesIO()
dump(qc, qpy_file)
qpy_file.seek(0)
new_circ = load(qpy_file)[0]
self.assertEqual(qc, new_circ)
self.assertEqual(qc.decompose(), new_circ.decompose())
self.assertEqual(
[x.operation.label for x in qc.data], [x.operation.label for x in new_circ.data]
)
self.assertDeprecatedBitProperties(qc, new_circ)
def test_custom_instruction_with_label(self):
"""Test that custom instruction is correctly serialized with a label"""
custom_gate = Instruction("black_box", 1, 0, [])
custom_definition = QuantumCircuit(1)
custom_definition.h(0)
custom_definition.rz(1.5, 0)
custom_definition.sdg(0)
custom_gate.definition = custom_definition
custom_gate.label = "My Special Black Box Instruction with a definition"
qc = QuantumCircuit(1)
qc.append(custom_gate, [0])
qpy_file = io.BytesIO()
dump(qc, qpy_file)
qpy_file.seek(0)
new_circ = load(qpy_file)[0]
self.assertEqual(qc, new_circ)
self.assertEqual(qc.decompose(), new_circ.decompose())
self.assertEqual(
[x.operation.label for x in qc.data], [x.operation.label for x in new_circ.data]
)
self.assertDeprecatedBitProperties(qc, new_circ)
def test_custom_gate_with_noop_definition(self):
"""Test that a custom gate whose definition contains no elements is serialized with a
proper definition.
Regression test of gh-7429."""
empty = QuantumCircuit(1, name="empty").to_gate()
opaque = Gate("opaque", 1, [])
qc = QuantumCircuit(2)
qc.append(empty, [0], [])
qc.append(opaque, [1], [])
qpy_file = io.BytesIO()
dump(qc, qpy_file)
qpy_file.seek(0)
new_circ = load(qpy_file)[0]
self.assertEqual(qc, new_circ)
self.assertEqual(qc.decompose(), new_circ.decompose())
self.assertEqual(len(new_circ), 2)
self.assertIsInstance(new_circ.data[0].operation.definition, QuantumCircuit)
self.assertIs(new_circ.data[1].operation.definition, None)
self.assertDeprecatedBitProperties(qc, new_circ)
def test_custom_instruction_with_noop_definition(self):
"""Test that a custom instruction whose definition contains no elements is serialized with a
proper definition.
Regression test of gh-7429."""
empty = QuantumCircuit(1, name="empty").to_instruction()
opaque = Instruction("opaque", 1, 0, [])
qc = QuantumCircuit(2)
qc.append(empty, [0], [])
qc.append(opaque, [1], [])
qpy_file = io.BytesIO()
dump(qc, qpy_file)
qpy_file.seek(0)
new_circ = load(qpy_file)[0]
self.assertEqual(qc, new_circ)
self.assertEqual(qc.decompose(), new_circ.decompose())
self.assertEqual(len(new_circ), 2)
self.assertIsInstance(new_circ.data[0].operation.definition, QuantumCircuit)
self.assertIs(new_circ.data[1].operation.definition, None)
self.assertDeprecatedBitProperties(qc, new_circ)
def test_standard_gate_with_label(self):
"""Test a standard gate with a label."""
qc = QuantumCircuit(1)
gate = XGate()
gate.label = "My special X gate"
qc.append(gate, [0])
qpy_file = io.BytesIO()
dump(qc, qpy_file)
qpy_file.seek(0)
new_circ = load(qpy_file)[0]
self.assertEqual(qc, new_circ)
self.assertEqual(
[x.operation.label for x in qc.data], [x.operation.label for x in new_circ.data]
)
self.assertDeprecatedBitProperties(qc, new_circ)
def test_circuit_with_conditional_with_label(self):
"""Test that instructions with conditions are correctly serialized."""
qc = QuantumCircuit(1, 1)
gate = XGate(label="My conditional x gate")
gate.c_if(qc.cregs[0], 1)
qc.append(gate, [0])
qpy_file = io.BytesIO()
dump(qc, qpy_file)
qpy_file.seek(0)
new_circ = load(qpy_file)[0]
self.assertEqual(qc, new_circ)
self.assertEqual(
[x.operation.label for x in qc.data], [x.operation.label for x in new_circ.data]
)
self.assertDeprecatedBitProperties(qc, new_circ)
def test_initialize_qft(self):
"""Test that initialize with a complex statevector and qft work."""
k = 5
state = (1 / np.sqrt(8)) * np.array(
[
np.exp(-1j * 2 * np.pi * k * (0) / 8),
np.exp(-1j * 2 * np.pi * k * (1) / 8),
np.exp(-1j * 2 * np.pi * k * (2) / 8),
np.exp(-1j * 2 * np.pi * k * 3 / 8),
np.exp(-1j * 2 * np.pi * k * 4 / 8),
np.exp(-1j * 2 * np.pi * k * 5 / 8),
np.exp(-1j * 2 * np.pi * k * 6 / 8),
np.exp(-1j * 2 * np.pi * k * 7 / 8),
]
)
qubits = 3
qc = QuantumCircuit(qubits, qubits)
qc.initialize(state)
qc.append(QFT(qubits), range(qubits))
qc.measure(range(qubits), range(qubits))
qpy_file = io.BytesIO()
dump(qc, qpy_file)
qpy_file.seek(0)
new_circ = load(qpy_file)[0]
self.assertEqual(qc, new_circ)
self.assertEqual(
[x.operation.label for x in qc.data], [x.operation.label for x in new_circ.data]
)
self.assertDeprecatedBitProperties(qc, new_circ)
def test_statepreparation(self):
"""Test that state preparation with a complex statevector and qft work."""
k = 5
state = (1 / np.sqrt(8)) * np.array(
[
np.exp(-1j * 2 * np.pi * k * (0) / 8),
np.exp(-1j * 2 * np.pi * k * (1) / 8),
np.exp(-1j * 2 * np.pi * k * (2) / 8),
np.exp(-1j * 2 * np.pi * k * 3 / 8),
np.exp(-1j * 2 * np.pi * k * 4 / 8),
np.exp(-1j * 2 * np.pi * k * 5 / 8),
np.exp(-1j * 2 * np.pi * k * 6 / 8),
np.exp(-1j * 2 * np.pi * k * 7 / 8),
]
)
qubits = 3
qc = QuantumCircuit(qubits, qubits)
qc.prepare_state(state)
qc.append(QFT(qubits), range(qubits))
qc.measure(range(qubits), range(qubits))
qpy_file = io.BytesIO()
dump(qc, qpy_file)
qpy_file.seek(0)
new_circ = load(qpy_file)[0]
self.assertEqual(qc, new_circ)
self.assertEqual(
[x.operation.label for x in qc.data], [x.operation.label for x in new_circ.data]
)
self.assertDeprecatedBitProperties(qc, new_circ)
def test_single_bit_teleportation(self):
"""Test a teleportation circuit with single bit conditions."""
qr = QuantumRegister(1)
cr = ClassicalRegister(2, name="name")
qc = QuantumCircuit(qr, cr, name="Reset Test")
qc.x(0)
qc.measure(0, cr[0])
qc.x(0).c_if(cr[0], 1)
qc.measure(0, cr[1])
qpy_file = io.BytesIO()
dump(qc, qpy_file)
qpy_file.seek(0)
new_circ = load(qpy_file)[0]
self.assertEqual(qc, new_circ)
self.assertEqual(
[x.operation.label for x in qc.data], [x.operation.label for x in new_circ.data]
)
self.assertDeprecatedBitProperties(qc, new_circ)
def test_qaoa(self):
"""Test loading a QAOA circuit works."""
cost_operator = Pauli("ZIIZ")
qaoa = QAOAAnsatz(cost_operator, reps=2)
qpy_file = io.BytesIO()
dump(qaoa, qpy_file)
qpy_file.seek(0)
new_circ = load(qpy_file)[0]
self.assertEqual(qaoa, new_circ)
self.assertEqual(
[x.operation.label for x in qaoa.data], [x.operation.label for x in new_circ.data]
)
self.assertDeprecatedBitProperties(qaoa, new_circ)
def test_evolutiongate(self):
"""Test loading a circuit with evolution gate works."""
synthesis = LieTrotter(reps=2)
evo = PauliEvolutionGate(
SparsePauliOp.from_list([("ZI", 1), ("IZ", 1)]), time=2, synthesis=synthesis
)
qc = QuantumCircuit(2)
qc.append(evo, range(2))
qpy_file = io.BytesIO()
dump(qc, qpy_file)
qpy_file.seek(0)
new_circ = load(qpy_file)[0]
self.assertEqual(qc, new_circ)
self.assertEqual(
[x.operation.label for x in qc.data], [x.operation.label for x in new_circ.data]
)
new_evo = new_circ.data[0].operation
self.assertIsInstance(new_evo, PauliEvolutionGate)
self.assertDeprecatedBitProperties(qc, new_circ)
def test_evolutiongate_param_time(self):
"""Test loading a circuit with an evolution gate that has a parameter for time."""
synthesis = LieTrotter(reps=2)
time = Parameter("t")
evo = PauliEvolutionGate(
SparsePauliOp.from_list([("ZI", 1), ("IZ", 1)]), time=time, synthesis=synthesis
)
qc = QuantumCircuit(2)
qc.append(evo, range(2))
qpy_file = io.BytesIO()
dump(qc, qpy_file)
qpy_file.seek(0)
new_circ = load(qpy_file)[0]
self.assertEqual(qc, new_circ)
self.assertEqual(
[x.operation.label for x in qc.data], [x.operation.label for x in new_circ.data]
)
new_evo = new_circ.data[0].operation
self.assertIsInstance(new_evo, PauliEvolutionGate)
self.assertDeprecatedBitProperties(qc, new_circ)
def test_evolutiongate_param_expr_time(self):
"""Test loading a circuit with an evolution gate that has a parameter for time."""
synthesis = LieTrotter(reps=2)
time = Parameter("t")
evo = PauliEvolutionGate(
SparsePauliOp.from_list([("ZI", 1), ("IZ", 1)]), time=time * time, synthesis=synthesis
)
qc = QuantumCircuit(2)
qc.append(evo, range(2))
qpy_file = io.BytesIO()
dump(qc, qpy_file)
qpy_file.seek(0)
new_circ = load(qpy_file)[0]
self.assertEqual(qc, new_circ)
self.assertEqual(
[x.operation.label for x in qc.data], [x.operation.label for x in new_circ.data]
)
new_evo = new_circ.data[0].operation
self.assertIsInstance(new_evo, PauliEvolutionGate)
self.assertDeprecatedBitProperties(qc, new_circ)
def test_evolutiongate_param_vec_time(self):
"""Test loading a an evolution gate that has a param vector element for time."""
synthesis = LieTrotter(reps=2)
time = ParameterVector("TimeVec", 1)
evo = PauliEvolutionGate(
SparsePauliOp.from_list([("ZI", 1), ("IZ", 1)]), time=time[0], synthesis=synthesis
)
qc = QuantumCircuit(2)
qc.append(evo, range(2))
qpy_file = io.BytesIO()
dump(qc, qpy_file)
qpy_file.seek(0)
new_circ = load(qpy_file)[0]
self.assertEqual(qc, new_circ)
self.assertEqual(
[x.operation.label for x in qc.data], [x.operation.label for x in new_circ.data]
)
new_evo = new_circ.data[0].operation
self.assertIsInstance(new_evo, PauliEvolutionGate)
self.assertDeprecatedBitProperties(qc, new_circ)
def test_op_list_evolutiongate(self):
"""Test loading a circuit with evolution gate works."""
evo = PauliEvolutionGate(
[SparsePauliOp.from_list([("ZI", 1), ("IZ", 1)])] * 5, time=0.2, synthesis=None
)
qc = QuantumCircuit(2)
qc.append(evo, range(2))
qpy_file = io.BytesIO()
dump(qc, qpy_file)
qpy_file.seek(0)
new_circ = load(qpy_file)[0]
self.assertEqual(qc, new_circ)
self.assertEqual(
[x.operation.label for x in qc.data], [x.operation.label for x in new_circ.data]
)
new_evo = new_circ.data[0].operation
self.assertIsInstance(new_evo, PauliEvolutionGate)
self.assertDeprecatedBitProperties(qc, new_circ)
def test_op_evolution_gate_suzuki_trotter(self):
"""Test qpy path with a suzuki trotter synthesis method on an evolution gate."""
synthesis = SuzukiTrotter()
evo = PauliEvolutionGate(
SparsePauliOp.from_list([("ZI", 1), ("IZ", 1)]), time=0.2, synthesis=synthesis
)
qc = QuantumCircuit(2)
qc.append(evo, range(2))
qpy_file = io.BytesIO()
dump(qc, qpy_file)
qpy_file.seek(0)
new_circ = load(qpy_file)[0]
self.assertEqual(qc, new_circ)
self.assertEqual(
[x.operation.label for x in qc.data], [x.operation.label for x in new_circ.data]
)
new_evo = new_circ.data[0].operation
self.assertIsInstance(new_evo, PauliEvolutionGate)
self.assertDeprecatedBitProperties(qc, new_circ)
def test_parameter_expression_global_phase(self):
"""Test a circuit with a parameter expression global_phase."""
theta = Parameter("theta")
phi = Parameter("phi")
sum_param = theta + phi
qc = QuantumCircuit(5, 1, global_phase=sum_param)
qc.h(0)
for i in range(4):
qc.cx(i, i + 1)
qc.barrier()
qc.rz(sum_param, range(3))
qc.rz(phi, 3)
qc.rz(theta, 4)
qc.barrier()
for i in reversed(range(4)):
qc.cx(i, i + 1)
qc.h(0)
qc.measure(0, 0)
qpy_file = io.BytesIO()
dump(qc, qpy_file)
qpy_file.seek(0)
new_circuit = load(qpy_file)[0]
self.assertEqual(qc, new_circuit)
self.assertDeprecatedBitProperties(qc, new_circuit)
def test_parameter_global_phase(self):
"""Test a circuit with a parameter expression global_phase."""
theta = Parameter("theta")
qc = QuantumCircuit(2, global_phase=theta)
qc.h(0)
qc.cx(0, 1)
qc.measure_all()
qpy_file = io.BytesIO()
dump(qc, qpy_file)
qpy_file.seek(0)
new_circuit = load(qpy_file)[0]
self.assertEqual(qc, new_circuit)
def test_parameter_vector(self):
"""Test a circuit with a parameter vector for gate parameters."""
qc = QuantumCircuit(11)
input_params = ParameterVector("x_par", 11)
user_params = ParameterVector("ΞΈ_par", 11)
for i, param in enumerate(user_params):
qc.ry(param, i)
for i, param in enumerate(input_params):
qc.rz(param, i)
qpy_file = io.BytesIO()
dump(qc, qpy_file)
qpy_file.seek(0)
new_circuit = load(qpy_file)[0]
expected_params = [x.name for x in qc.parameters]
self.assertEqual([x.name for x in new_circuit.parameters], expected_params)
self.assertDeprecatedBitProperties(qc, new_circuit)
def test_parameter_vector_element_in_expression(self):
"""Test a circuit with a parameter vector used in a parameter expression."""
qc = QuantumCircuit(7)
entanglement = [[i, i + 1] for i in range(7 - 1)]
input_params = ParameterVector("x_par", 14)
user_params = ParameterVector("\u03B8_par", 1)
for i in range(qc.num_qubits):
qc.ry(user_params[0], qc.qubits[i])
for source, target in entanglement:
qc.cz(qc.qubits[source], qc.qubits[target])
for i in range(qc.num_qubits):
qc.rz(-2 * input_params[2 * i + 1], qc.qubits[i])
qc.rx(-2 * input_params[2 * i], qc.qubits[i])
qpy_file = io.BytesIO()
dump(qc, qpy_file)
qpy_file.seek(0)
new_circuit = load(qpy_file)[0]
expected_params = [x.name for x in qc.parameters]
self.assertEqual([x.name for x in new_circuit.parameters], expected_params)
self.assertDeprecatedBitProperties(qc, new_circuit)
def test_parameter_vector_incomplete_warns(self):
"""Test that qpy's deserialization warns if a ParameterVector isn't fully identical."""
vec = ParameterVector("test", 3)
qc = QuantumCircuit(1, name="fun")
qc.rx(vec[1], 0)
qpy_file = io.BytesIO()
dump(qc, qpy_file)
qpy_file.seek(0)
with self.assertWarnsRegex(UserWarning, r"^The ParameterVector.*Elements 0, 2.*fun$"):
new_circuit = load(qpy_file)[0]
self.assertEqual(qc, new_circuit)
self.assertDeprecatedBitProperties(qc, new_circuit)
def test_parameter_vector_global_phase(self):
"""Test that a circuit with a standalone ParameterVectorElement phase works."""
vec = ParameterVector("phase", 1)
qc = QuantumCircuit(1, global_phase=vec[0])
qpy_file = io.BytesIO()
dump(qc, qpy_file)
qpy_file.seek(0)
new_circuit = load(qpy_file)[0]
self.assertEqual(qc, new_circuit)
self.assertDeprecatedBitProperties(qc, new_circuit)
def test_custom_metadata_serializer_full_path(self):
"""Test that running with custom metadata serialization works."""
class CustomObject:
"""Custom string container object."""
def __init__(self, string):
self.string = string
def __eq__(self, other):
return self.string == other.string
class CustomSerializer(json.JSONEncoder):
"""Custom json encoder to handle CustomObject."""
def default(self, o):
if isinstance(o, CustomObject):
return {"__type__": "Custom", "value": o.string}
return json.JSONEncoder.default(self, o)
class CustomDeserializer(json.JSONDecoder):
"""Custom json decoder to handle CustomObject."""
def object_hook(self, o): # pylint: disable=invalid-name,method-hidden
"""Hook to override default decoder.
Normally specified as a kwarg on load() that overloads the
default decoder. Done here to avoid reimplementing the
decode method.
"""
if "__type__" in o:
obj_type = o["__type__"]
if obj_type == "Custom":
return CustomObject(o["value"])
return o
theta = Parameter("theta")
qc = QuantumCircuit(2, global_phase=theta)
qc.h(0)
qc.cx(0, 1)
qc.measure_all()
circuits = [qc, qc.copy()]
circuits[0].metadata = {"key": CustomObject("Circuit 1")}
circuits[1].metadata = {"key": CustomObject("Circuit 2")}
qpy_file = io.BytesIO()
dump(circuits, qpy_file, metadata_serializer=CustomSerializer)
qpy_file.seek(0)
new_circuits = load(qpy_file, metadata_deserializer=CustomDeserializer)
self.assertEqual(qc, new_circuits[0])
self.assertEqual(circuits[0].metadata["key"], CustomObject("Circuit 1"))
self.assertEqual(qc, new_circuits[1])
self.assertEqual(circuits[1].metadata["key"], CustomObject("Circuit 2"))
self.assertDeprecatedBitProperties(qc, new_circuits[0])
self.assertDeprecatedBitProperties(qc, new_circuits[1])
def test_qpy_with_ifelseop(self):
"""Test qpy serialization with an if block."""
qc = QuantumCircuit(2, 2)
qc.h(0)
qc.measure(0, 0)
with qc.if_test((qc.clbits[0], True)):
qc.x(1)
qc.measure(1, 1)
qpy_file = io.BytesIO()
dump(qc, qpy_file)
qpy_file.seek(0)
new_circuit = load(qpy_file)[0]
self.assertEqual(qc, new_circuit)
self.assertDeprecatedBitProperties(qc, new_circuit)
def test_qpy_with_ifelseop_with_else(self):
"""Test qpy serialization with an else block."""
qc = QuantumCircuit(2, 2)
qc.h(0)
qc.measure(0, 0)
with qc.if_test((qc.clbits[0], True)) as else_:
qc.x(1)
with else_:
qc.y(1)
qc.measure(1, 1)
qpy_file = io.BytesIO()
dump(qc, qpy_file)
qpy_file.seek(0)
new_circuit = load(qpy_file)[0]
self.assertEqual(qc, new_circuit)
self.assertDeprecatedBitProperties(qc, new_circuit)
def test_qpy_with_while_loop(self):
"""Test qpy serialization with a for loop."""
qc = QuantumCircuit(2, 1)
with qc.while_loop((qc.clbits[0], 0)):
qc.h(0)
qc.cx(0, 1)
qc.measure(0, 0)
qpy_file = io.BytesIO()
dump(qc, qpy_file)
qpy_file.seek(0)
new_circuit = load(qpy_file)[0]
self.assertEqual(qc, new_circuit)
self.assertDeprecatedBitProperties(qc, new_circuit)
def test_qpy_with_for_loop(self):
"""Test qpy serialization with a for loop."""
qc = QuantumCircuit(2, 1)
with qc.for_loop(range(5)):
qc.h(0)
qc.cx(0, 1)
qc.measure(0, 0)
qc.break_loop().c_if(0, True)
qpy_file = io.BytesIO()
dump(qc, qpy_file)
qpy_file.seek(0)
new_circuit = load(qpy_file)[0]
self.assertEqual(qc, new_circuit)
self.assertDeprecatedBitProperties(qc, new_circuit)
def test_qpy_with_for_loop_iterator(self):
"""Test qpy serialization with a for loop."""
qc = QuantumCircuit(2, 1)
with qc.for_loop(iter(range(5))):
qc.h(0)
qc.cx(0, 1)
qc.measure(0, 0)
qc.break_loop().c_if(0, True)
qpy_file = io.BytesIO()
dump(qc, qpy_file)
qpy_file.seek(0)
new_circuit = load(qpy_file)[0]
self.assertEqual(qc, new_circuit)
self.assertDeprecatedBitProperties(qc, new_circuit)
def test_qpy_clbit_switch(self):
"""Test QPY serialisation for a switch statement with a Clbit target."""
case_t = QuantumCircuit(2, 1)
case_t.x(0)
case_f = QuantumCircuit(2, 1)
case_f.z(0)
qc = QuantumCircuit(2, 1)
qc.switch(0, [(True, case_t), (False, case_f)], qc.qubits, qc.clbits)
with io.BytesIO() as fptr:
dump(qc, fptr)
fptr.seek(0)
new_circuit = load(fptr)[0]
self.assertEqual(qc, new_circuit)
self.assertDeprecatedBitProperties(qc, new_circuit)
def test_qpy_register_switch(self):
"""Test QPY serialisation for a switch statement with a ClassicalRegister target."""
qreg = QuantumRegister(2, "q")
creg = ClassicalRegister(3, "c")
case_0 = QuantumCircuit(qreg, creg)
case_0.x(0)
case_1 = QuantumCircuit(qreg, creg)
case_1.z(1)
case_2 = QuantumCircuit(qreg, creg)
case_2.x(1)
qc = QuantumCircuit(qreg, creg)
qc.switch(creg, [(0, case_0), ((1, 2), case_1), ((3, 4, CASE_DEFAULT), case_2)], qreg, creg)
with io.BytesIO() as fptr:
dump(qc, fptr)
fptr.seek(0)
new_circuit = load(fptr)[0]
self.assertEqual(qc, new_circuit)
self.assertDeprecatedBitProperties(qc, new_circuit)
def test_standalone_register_partial_bit_in_circuit(self):
"""Test qpy with only some bits from standalone register."""
qr = QuantumRegister(2)
qc = QuantumCircuit([qr[0]])
qc.x(0)
qpy_file = io.BytesIO()
dump(qc, qpy_file)
qpy_file.seek(0)
new_circuit = load(qpy_file)[0]
self.assertEqual(qc, new_circuit)
self.assertDeprecatedBitProperties(qc, new_circuit)
def test_nested_tuple_param(self):
"""Test qpy with an instruction that contains nested tuples."""
inst = Instruction("tuple_test", 1, 0, [((((0, 1), (0, 1)), 2, 3), ("A", "B", "C"))])
qc = QuantumCircuit(1)
qc.append(inst, [0])
qpy_file = io.BytesIO()
dump(qc, qpy_file)
qpy_file.seek(0)
new_circuit = load(qpy_file)[0]
self.assertEqual(qc, new_circuit)
self.assertDeprecatedBitProperties(qc, new_circuit)
def test_empty_tuple_param(self):
"""Test qpy with an instruction that contains an empty tuple."""
inst = Instruction("empty_tuple_test", 1, 0, [()])
qc = QuantumCircuit(1)
qc.append(inst, [0])
qpy_file = io.BytesIO()
dump(qc, qpy_file)
qpy_file.seek(0)
new_circuit = load(qpy_file)[0]
self.assertEqual(qc, new_circuit)
self.assertDeprecatedBitProperties(qc, new_circuit)
def test_ucr_gates(self):
"""Test qpy with UCRX, UCRY, and UCRZ gates."""
qc = QuantumCircuit(3)
qc.ucrz([0, 0, 0, -np.pi], [0, 1], 2)
qc.ucry([0, 0, 0, -np.pi], [0, 2], 1)
qc.ucrx([0, 0, 0, -np.pi], [2, 1], 0)
qc.measure_all()
qpy_file = io.BytesIO()
dump(qc, qpy_file)
qpy_file.seek(0)
new_circuit = load(qpy_file)[0]
self.assertEqual(qc.decompose().decompose(), new_circuit.decompose().decompose())
self.assertDeprecatedBitProperties(qc, new_circuit)
def test_controlled_gate(self):
"""Test a custom controlled gate."""
qc = QuantumCircuit(3)
controlled_gate = DCXGate().control(1)
qc.append(controlled_gate, [0, 1, 2])
qpy_file = io.BytesIO()
dump(qc, qpy_file)
qpy_file.seek(0)
new_circuit = load(qpy_file)[0]
self.assertEqual(qc, new_circuit)
self.assertDeprecatedBitProperties(qc, new_circuit)
def test_controlled_gate_open_controls(self):
"""Test a controlled gate with open controls round-trips exactly."""
qc = QuantumCircuit(3)
controlled_gate = DCXGate().control(1, ctrl_state=0)
qc.append(controlled_gate, [0, 1, 2])
qpy_file = io.BytesIO()
dump(qc, qpy_file)
qpy_file.seek(0)
new_circuit = load(qpy_file)[0]
self.assertEqual(qc, new_circuit)
self.assertDeprecatedBitProperties(qc, new_circuit)
def test_nested_controlled_gate(self):
"""Test a custom nested controlled gate."""
custom_gate = Gate("black_box", 1, [])
custom_definition = QuantumCircuit(1)
custom_definition.h(0)
custom_definition.rz(1.5, 0)
custom_definition.sdg(0)
custom_gate.definition = custom_definition
qc = QuantumCircuit(3)
qc.append(custom_gate, [0])
controlled_gate = custom_gate.control(2)
qc.append(controlled_gate, [0, 1, 2])
qpy_file = io.BytesIO()
dump(qc, qpy_file)
qpy_file.seek(0)
new_circ = load(qpy_file)[0]
self.assertEqual(qc, new_circ)
self.assertEqual(qc.decompose(), new_circ.decompose())
self.assertDeprecatedBitProperties(qc, new_circ)
def test_open_controlled_gate(self):
"""Test an open control is preserved across serialization."""
qc = QuantumCircuit(2)
qc.cx(0, 1, ctrl_state=0)
with io.BytesIO() as fd:
dump(qc, fd)
fd.seek(0)
new_circ = load(fd)[0]
self.assertEqual(qc, new_circ)
self.assertEqual(qc.data[0].operation.ctrl_state, new_circ.data[0].operation.ctrl_state)
self.assertDeprecatedBitProperties(qc, new_circ)
def test_standard_control_gates(self):
"""Test standard library controlled gates."""
qc = QuantumCircuit(6)
mcu1_gate = MCU1Gate(np.pi, 2)
mcx_gate = MCXGate(5)
mcx_gray_gate = MCXGrayCode(5)
mcx_recursive_gate = MCXRecursive(4)
mcx_vchain_gate = MCXVChain(3)
qc.append(mcu1_gate, [0, 2, 1])
qc.append(mcx_gate, list(range(0, 6)))
qc.append(mcx_gray_gate, list(range(0, 6)))
qc.append(mcx_recursive_gate, list(range(0, 5)))
qc.append(mcx_vchain_gate, list(range(0, 5)))
qc.mcp(np.pi, [0, 2], 1)
qc.mct([0, 2], 1)
qc.mcx([0, 2], 1)
qc.measure_all()
qpy_file = io.BytesIO()
dump(qc, qpy_file)
qpy_file.seek(0)
new_circuit = load(qpy_file)[0]
self.assertEqual(qc, new_circuit)
self.assertDeprecatedBitProperties(qc, new_circuit)
def test_controlled_gate_subclass_custom_definition(self):
"""Test controlled gate with overloaded definition.
Reproduce from: https://github.com/Qiskit/qiskit-terra/issues/8794
"""
class CustomCXGate(ControlledGate):
"""Custom CX with overloaded _define."""
def __init__(self, label=None, ctrl_state=None):
super().__init__(
"cx", 2, [], label, num_ctrl_qubits=1, ctrl_state=ctrl_state, base_gate=XGate()
)
def _define(self) -> None:
qc = QuantumCircuit(2, name=self.name)
qc.cx(0, 1)
self.definition = qc
qc = QuantumCircuit(2)
qc.append(CustomCXGate(), [0, 1])
qpy_file = io.BytesIO()
dump(qc, qpy_file)
qpy_file.seek(0)
new_circ = load(qpy_file)[0]
self.assertEqual(qc, new_circ)
self.assertEqual(qc.decompose(), new_circ.decompose())
self.assertDeprecatedBitProperties(qc, new_circ)
def test_load_with_loose_bits(self):
"""Test that loading from a circuit with loose bits works."""
qc = QuantumCircuit([Qubit(), Qubit(), Clbit()])
qpy_file = io.BytesIO()
dump(qc, qpy_file)
qpy_file.seek(0)
new_circuit = load(qpy_file)[0]
self.assertEqual(tuple(new_circuit.qregs), ())
self.assertEqual(tuple(new_circuit.cregs), ())
self.assertEqual(qc, new_circuit)
self.assertDeprecatedBitProperties(qc, new_circuit)
def test_load_with_loose_bits_and_registers(self):
"""Test that loading from a circuit with loose bits and registers works."""
qc = QuantumCircuit(QuantumRegister(3), ClassicalRegister(1), [Clbit()])
qpy_file = io.BytesIO()
dump(qc, qpy_file)
qpy_file.seek(0)
new_circuit = load(qpy_file)[0]
self.assertEqual(qc, new_circuit)
self.assertDeprecatedBitProperties(qc, new_circuit)
def test_registers_after_loose_bits(self):
"""Test that a circuit whose registers appear after some loose bits roundtrips. Regression
test of gh-9094."""
qc = QuantumCircuit()
qc.add_bits([Qubit(), Clbit()])
qc.add_register(QuantumRegister(2, name="q1"))
qc.add_register(ClassicalRegister(2, name="c1"))
with io.BytesIO() as fptr:
dump(qc, fptr)
fptr.seek(0)
new_circuit = load(fptr)[0]
self.assertEqual(qc, new_circuit)
self.assertDeprecatedBitProperties(qc, new_circuit)
def test_roundtrip_empty_register(self):
"""Test that empty registers round-trip correctly."""
qc = QuantumCircuit(QuantumRegister(0), ClassicalRegister(0))
with io.BytesIO() as fptr:
dump(qc, fptr)
fptr.seek(0)
new_circuit = load(fptr)[0]
self.assertEqual(qc, new_circuit)
self.assertEqual(qc.qregs, new_circuit.qregs)
self.assertEqual(qc.cregs, new_circuit.cregs)
self.assertDeprecatedBitProperties(qc, new_circuit)
def test_roundtrip_several_empty_registers(self):
"""Test that several empty registers round-trip correctly."""
qc = QuantumCircuit(
QuantumRegister(0, "a"),
QuantumRegister(0, "b"),
ClassicalRegister(0, "c"),
ClassicalRegister(0, "d"),
)
with io.BytesIO() as fptr:
dump(qc, fptr)
fptr.seek(0)
new_circuit = load(fptr)[0]
self.assertEqual(qc, new_circuit)
self.assertEqual(qc.qregs, new_circuit.qregs)
self.assertEqual(qc.cregs, new_circuit.cregs)
self.assertDeprecatedBitProperties(qc, new_circuit)
def test_roundtrip_empty_registers_with_loose_bits(self):
"""Test that empty registers still round-trip correctly in the presence of loose bits."""
loose = [Qubit(), Clbit()]
qc = QuantumCircuit(loose, QuantumRegister(0), ClassicalRegister(0))
with io.BytesIO() as fptr:
dump(qc, fptr)
fptr.seek(0)
new_circuit = load(fptr)[0]
self.assertEqual(qc, new_circuit)
self.assertEqual(qc.qregs, new_circuit.qregs)
self.assertEqual(qc.cregs, new_circuit.cregs)
qc = QuantumCircuit(QuantumRegister(0), ClassicalRegister(0), loose)
with io.BytesIO() as fptr:
dump(qc, fptr)
fptr.seek(0)
new_circuit = load(fptr)[0]
self.assertEqual(qc, new_circuit)
self.assertEqual(qc.qregs, new_circuit.qregs)
self.assertEqual(qc.cregs, new_circuit.cregs)
self.assertDeprecatedBitProperties(qc, new_circuit)
def test_incomplete_owned_bits(self):
"""Test that a circuit that contains only some bits that are owned by a register are
correctly roundtripped."""
reg = QuantumRegister(5, "q")
qc = QuantumCircuit(reg[:3])
qc.ccx(0, 1, 2)
with io.BytesIO() as fptr:
dump(qc, fptr)
fptr.seek(0)
new_circuit = load(fptr)[0]
self.assertEqual(qc, new_circuit)
self.assertDeprecatedBitProperties(qc, new_circuit)
def test_diagonal_gate(self):
"""Test that a `DiagonalGate` successfully roundtrips."""
qc = QuantumCircuit(2)
qc.diagonal([1, -1, -1, 1], [0, 1])
with io.BytesIO() as fptr:
dump(qc, fptr)
fptr.seek(0)
new_circuit = load(fptr)[0]
# DiagonalGate (and a bunch of the qiskit.extensions gates) have non-deterministic
# definitions with regard to internal instruction names, so cannot be directly compared for
# equality.
self.assertIs(type(qc.data[0].operation), type(new_circuit.data[0].operation))
self.assertEqual(qc.data[0].operation.params, new_circuit.data[0].operation.params)
self.assertDeprecatedBitProperties(qc, new_circuit)
@ddt.data(QuantumCircuit.if_test, QuantumCircuit.while_loop)
def test_if_else_while_expr_simple(self, control_flow):
"""Test that `IfElseOp` and `WhileLoopOp` can have an `Expr` node as their `condition`, and
that this round-trips through QPY."""
body = QuantumCircuit(1)
qr = QuantumRegister(2, "q1")
cr = ClassicalRegister(2, "c1")
qc = QuantumCircuit(qr, cr)
control_flow(qc, expr.equal(cr, 3), body.copy(), [0], [])
control_flow(qc, expr.lift(qc.clbits[0]), body.copy(), [0], [])
with io.BytesIO() as fptr:
dump(qc, fptr)
fptr.seek(0)
new_circuit = load(fptr)[0]
self.assertEqual(qc, new_circuit)
self.assertEqual(qc.qregs, new_circuit.qregs)
self.assertEqual(qc.cregs, new_circuit.cregs)
self.assertDeprecatedBitProperties(qc, new_circuit)
@ddt.data(QuantumCircuit.if_test, QuantumCircuit.while_loop)
def test_if_else_while_expr_nested(self, control_flow):
"""Test that `IfElseOp` and `WhileLoopOp` can have an `Expr` node as their `condition`, and
that this round-trips through QPY."""
inner = QuantumCircuit(1)
outer = QuantumCircuit(1, 1)
control_flow(outer, expr.lift(outer.clbits[0]), inner.copy(), [0], [])
qr = QuantumRegister(2, "q1")
cr = ClassicalRegister(2, "c1")
qc = QuantumCircuit(qr, cr)
control_flow(qc, expr.equal(cr, 3), outer.copy(), [1], [1])
with io.BytesIO() as fptr:
dump(qc, fptr)
fptr.seek(0)
new_circuit = load(fptr)[0]
self.assertEqual(qc, new_circuit)
self.assertEqual(qc.qregs, new_circuit.qregs)
self.assertEqual(qc.cregs, new_circuit.cregs)
self.assertDeprecatedBitProperties(qc, new_circuit)
def test_if_else_expr_stress(self):
"""Stress-test the `Expr` handling in the condition of an `IfElseOp`. This should hit on
every aspect of the `Expr` tree."""
inner = QuantumCircuit(1)
inner.x(0)
outer = QuantumCircuit(1, 1)
outer.if_test(expr.cast(outer.clbits[0], types.Bool()), inner.copy(), [0], [])
# Register whose size is deliberately larger that one byte.
cr1 = ClassicalRegister(256, "c1")
cr2 = ClassicalRegister(4, "c2")
loose = Clbit()
qc = QuantumCircuit([Qubit(), Qubit(), loose], cr1, cr2)
qc.rz(1.0, 0)
qc.if_test(
expr.logic_and(
expr.logic_and(
expr.logic_or(
expr.cast(
expr.less(expr.bit_and(cr1, 0x0F), expr.bit_not(cr1)),
types.Bool(),
),
expr.cast(
expr.less_equal(expr.bit_or(cr2, 7), expr.bit_xor(cr2, 7)),
types.Bool(),
),
),
expr.logic_and(
expr.logic_or(expr.equal(cr2, 2), expr.logic_not(expr.not_equal(cr2, 3))),
expr.logic_or(
expr.greater(cr2, 3),
expr.greater_equal(cr2, 3),
),
),
),
expr.logic_not(loose),
),
outer.copy(),
[1],
[0],
)
qc.rz(1.0, 0)
with io.BytesIO() as fptr:
dump(qc, fptr)
fptr.seek(0)
new_circuit = load(fptr)[0]
self.assertEqual(qc, new_circuit)
self.assertEqual(qc.qregs, new_circuit.qregs)
self.assertEqual(qc.cregs, new_circuit.cregs)
self.assertDeprecatedBitProperties(qc, new_circuit)
def test_switch_expr_simple(self):
"""Test that `SwitchCaseOp` can have an `Expr` node as its `target`, and that this
round-trips through QPY."""
body = QuantumCircuit(1)
qr = QuantumRegister(2, "q1")
cr = ClassicalRegister(2, "c1")
qc = QuantumCircuit(qr, cr)
qc.switch(expr.bit_and(cr, 3), [(1, body.copy())], [0], [])
qc.switch(expr.logic_not(qc.clbits[0]), [(False, body.copy())], [0], [])
with io.BytesIO() as fptr:
dump(qc, fptr)
fptr.seek(0)
new_circuit = load(fptr)[0]
self.assertEqual(qc, new_circuit)
self.assertEqual(qc.qregs, new_circuit.qregs)
self.assertEqual(qc.cregs, new_circuit.cregs)
self.assertDeprecatedBitProperties(qc, new_circuit)
def test_switch_expr_nested(self):
"""Test that `SwitchCaseOp` can have an `Expr` node as its `target`, and that this
round-trips through QPY."""
inner = QuantumCircuit(1)
outer = QuantumCircuit(1, 1)
outer.switch(expr.lift(outer.clbits[0]), [(False, inner.copy())], [0], [])
qr = QuantumRegister(2, "q1")
cr = ClassicalRegister(2, "c1")
qc = QuantumCircuit(qr, cr)
qc.switch(expr.lift(cr), [(3, outer.copy())], [1], [1])
with io.BytesIO() as fptr:
dump(qc, fptr)
fptr.seek(0)
new_circuit = load(fptr)[0]
self.assertEqual(qc, new_circuit)
self.assertEqual(qc.qregs, new_circuit.qregs)
self.assertEqual(qc.cregs, new_circuit.cregs)
self.assertDeprecatedBitProperties(qc, new_circuit)
def test_switch_expr_stress(self):
"""Stress-test the `Expr` handling in the target of a `SwitchCaseOp`. This should hit on
every aspect of the `Expr` tree."""
inner = QuantumCircuit(1)
inner.x(0)
outer = QuantumCircuit(1, 1)
outer.switch(expr.cast(outer.clbits[0], types.Bool()), [(True, inner.copy())], [0], [])
# Register whose size is deliberately larger that one byte.
cr1 = ClassicalRegister(256, "c1")
cr2 = ClassicalRegister(4, "c2")
loose = Clbit()
qc = QuantumCircuit([Qubit(), Qubit(), loose], cr1, cr2)
qc.rz(1.0, 0)
qc.switch(
expr.logic_and(
expr.logic_and(
expr.logic_or(
expr.cast(
expr.less(expr.bit_and(cr1, 0x0F), expr.bit_not(cr1)),
types.Bool(),
),
expr.cast(
expr.less_equal(expr.bit_or(cr2, 7), expr.bit_xor(cr2, 7)),
types.Bool(),
),
),
expr.logic_and(
expr.logic_or(expr.equal(cr2, 2), expr.logic_not(expr.not_equal(cr2, 3))),
expr.logic_or(
expr.greater(cr2, 3),
expr.greater_equal(cr2, 3),
),
),
),
expr.logic_not(loose),
),
[(False, outer.copy())],
[1],
[0],
)
qc.rz(1.0, 0)
with io.BytesIO() as fptr:
dump(qc, fptr)
fptr.seek(0)
new_circuit = load(fptr)[0]
self.assertEqual(qc, new_circuit)
self.assertEqual(qc.qregs, new_circuit.qregs)
self.assertEqual(qc.cregs, new_circuit.cregs)
self.assertDeprecatedBitProperties(qc, new_circuit)
def test_multiple_nested_control_custom_definitions(self):
"""Test that circuits with multiple controlled custom gates that in turn depend on custom
gates can be exported successfully when there are several such gates in the outer circuit.
See gh-9746"""
inner_1 = QuantumCircuit(1, name="inner_1")
inner_1.x(0)
inner_2 = QuantumCircuit(1, name="inner_2")
inner_2.y(0)
outer_1 = QuantumCircuit(1, name="outer_1")
outer_1.append(inner_1.to_gate(), [0], [])
outer_2 = QuantumCircuit(1, name="outer_2")
outer_2.append(inner_2.to_gate(), [0], [])
qc = QuantumCircuit(2)
qc.append(outer_1.to_gate().control(1), [0, 1], [])
qc.append(outer_2.to_gate().control(1), [0, 1], [])
with io.BytesIO() as fptr:
dump(qc, fptr)
fptr.seek(0)
new_circuit = load(fptr)[0]
self.assertEqual(qc, new_circuit)
self.assertDeprecatedBitProperties(qc, new_circuit)
def test_qpy_deprecation(self):
"""Test the old import path's deprecations fire."""
with self.assertWarnsRegex(DeprecationWarning, "is deprecated"):
# pylint: disable=no-name-in-module, unused-import, redefined-outer-name, reimported
from qiskit.circuit.qpy_serialization import dump, load
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
from qiskit import IBMQ
IBMQ.backends()
IBMQ.delete_accounts()
IBMQ.stored_accounts()
import Qconfig_IBMQ_experience
import Qconfig_IBMQ_network
IBMQ.enable_account(Qconfig_IBMQ_experience.APItoken)
# uncomment to print to screen (it will show your token and url)
# IBMQ.active_accounts()
IBMQ.backends()
IBMQ.disable_accounts(token=Qconfig_IBMQ_experience.APItoken)
IBMQ.backends()
IBMQ.save_account(Qconfig_IBMQ_experience.APItoken, overwrite=True)
IBMQ.save_account(Qconfig_IBMQ_network.APItoken, Qconfig_IBMQ_network.url, overwrite=True)
# uncomment to print to screen (it will show your token and url)
# IBMQ.stored_accounts()
IBMQ.active_accounts()
IBMQ.backends()
IBMQ.load_accounts()
IBMQ.backends()
IBMQ.backends(hub='ibm-q-internal')
IBMQ.disable_accounts(hub='ibm-q-internal')
# uncomment to print to screen (it will show your token and url)
# IBMQ.active_accounts()
IBMQ.backends()
IBMQ.disable_accounts()
IBMQ.load_accounts(hub=None)
IBMQ.backends()
IBMQ.backends(operational=True, simulator=False)
IBMQ.backends(filters=lambda x: x.configuration().n_qubits <= 5 and
not x.configuration().simulator and x.status().operational==True)
from qiskit.providers.ibmq import least_busy
small_devices = IBMQ.backends(filters=lambda x: x.configuration().n_qubits == 5 and
not x.configuration().simulator)
least_busy(small_devices)
IBMQ.get_backend('ibmq_16_melbourne')
backend = least_busy(small_devices)
backend.provider
backend.name()
backend.status()
backend.configuration()
backend.properties()
backend.hub
backend.group
backend.project
for ran_job in backend.jobs(limit=5):
print(str(ran_job.job_id()) + " " + str(ran_job.status()))
job = backend.retrieve_job(ran_job.job_id())
job.status()
backend_temp = job.backend()
backend_temp
job.job_id()
result = job.result()
counts = result.get_counts()
print(counts)
job.creation_date()
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit import compile
qr = QuantumRegister(3)
cr = ClassicalRegister(3)
circuit = QuantumCircuit(qr, cr)
circuit.x(qr[0])
circuit.x(qr[1])
circuit.ccx(qr[0], qr[1], qr[2])
circuit.cx(qr[0], qr[1])
circuit.measure(qr, cr)
qobj = compile(circuit, backend=backend, shots=1024)
job = backend.run(qobj)
job.status()
import time
#time.sleep(10)
job.cancel()
job.status()
job = backend.run(qobj)
from qiskit.tools.monitor import job_monitor
job_monitor(job)
result = job.result()
counts = result.get_counts()
print(counts)
|
https://github.com/MAI-cyber/QIT
|
MAI-cyber
|
# ! pip install numpy
# ! pip install qiskit
# ! pip install matplotlib
from qiskit import QuantumCircuit, execute, Aer, BasicAer
from qiskit.visualization import plot_histogram
import numpy as np
n = 2
f1 = QuantumCircuit(n+1, name='f1')
# Applying the x gate to ancilla for when f_1 = 1
f1.cx(1,2)
display(f1.draw())
f2 = QuantumCircuit(n+1, name='f2')
# Applying the x gate to ancilla for when f_1 = 1
f2.cx(0,2)
f2.cx(1,2)
f2.ccx(0,1,2)
display(f2.draw())
dj = QuantumCircuit(n+1, n)
# Apply H-gates
for qubit in range(n):
dj.h(qubit)
# Put ancilia qubit in state |->
dj.x(n)
dj.h(n)
dj.barrier()
# Add oracle corresponding to the fucntion
dj.append(f1, [*range(n+1)])
dj.barrier()
# Repeat H-gates
for qubit in range(n):
dj.h(qubit)
dj.barrier()
# Measure
for i in range(n):
dj.measure(i, i)
# Display circuit
dj.draw('mpl')
# use local simulator
backend = BasicAer.get_backend('qasm_simulator')
shots = 1024
results = execute(dj, backend=backend, shots=shots).result()
answer = results.get_counts()
plot_histogram(answer)
# Since we measure the state |00> with probability 0, the funciton is balanced as expected
dj = QuantumCircuit(n+1, n)
# Apply H-gates
for qubit in range(n):
dj.h(qubit)
# Put ancilia qubit in state |->
dj.x(n)
dj.h(n)
dj.barrier()
# Add oracle corresponding to the fucntion
dj.append(f2, [*range(n+1)])
dj.barrier()
# Repeat H-gates
for qubit in range(n):
dj.h(qubit)
dj.barrier()
# Measure
for i in range(n):
dj.measure(i, i)
# Display circuit
dj.draw('mpl')
# use local simulator
backend = BasicAer.get_backend('qasm_simulator')
shots = 1024
results = execute(dj, backend=backend, shots=shots).result()
answer = results.get_counts()
plot_histogram(answer)
# Since we measure the state |00> with probability ~0.25, the function is biased as expected
dj = QuantumCircuit(n+1, n)
# Apply H-gates
for qubit in range(n):
dj.h(qubit)
# Put ancilia qubit in state |->
dj.x(n)
dj.h(n)
dj.barrier()
# Add oracle corresponding to the function
dj.append(f1, [*range(n+1)])
dj.append(f2, [*range(n+1)])
dj.barrier()
# Repeat H-gates
for qubit in range(n):
dj.h(qubit)
dj.barrier()
# Measure
for i in range(n):
dj.measure(i, i)
# Display circuit
dj.draw('mpl')
# use local simulator
backend = BasicAer.get_backend('qasm_simulator')
shots = 1024
results = execute(dj, backend=backend, shots=shots).result()
answer = results.get_counts()
plot_histogram(answer)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import matplotlib.pyplot as plt
from scipy.interpolate import griddata
%matplotlib inline
import numpy as np
from qiskit import QuantumRegister, QuantumCircuit, AncillaRegister, transpile
from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem
from qiskit.circuit.library import WeightedAdder, LinearAmplitudeFunction
from qiskit_aer.primitives import Sampler
from qiskit_finance.circuit.library import LogNormalDistribution
# number of qubits per dimension to represent the uncertainty
num_uncertainty_qubits = 2
# parameters for considered random distribution
S = 2.0 # initial spot price
vol = 0.4 # volatility of 40%
r = 0.05 # annual interest rate of 4%
T = 40 / 365 # 40 days to maturity
# resulting parameters for log-normal distribution
mu = (r - 0.5 * vol**2) * T + np.log(S)
sigma = vol * np.sqrt(T)
mean = np.exp(mu + sigma**2 / 2)
variance = (np.exp(sigma**2) - 1) * np.exp(2 * mu + sigma**2)
stddev = np.sqrt(variance)
# lowest and highest value considered for the spot price; in between, an equidistant discretization is considered.
low = np.maximum(0, mean - 3 * stddev)
high = mean + 3 * stddev
# map to higher dimensional distribution
# for simplicity assuming dimensions are independent and identically distributed)
dimension = 2
num_qubits = [num_uncertainty_qubits] * dimension
low = low * np.ones(dimension)
high = high * np.ones(dimension)
mu = mu * np.ones(dimension)
cov = sigma**2 * np.eye(dimension)
# construct circuit
u = LogNormalDistribution(num_qubits=num_qubits, mu=mu, sigma=cov, bounds=list(zip(low, high)))
# plot PDF of uncertainty model
x = [v[0] for v in u.values]
y = [v[1] for v in u.values]
z = u.probabilities
# z = map(float, z)
# z = list(map(float, z))
resolution = np.array([2**n for n in num_qubits]) * 1j
grid_x, grid_y = np.mgrid[min(x) : max(x) : resolution[0], min(y) : max(y) : resolution[1]]
grid_z = griddata((x, y), z, (grid_x, grid_y))
plt.figure(figsize=(10, 8))
ax = plt.axes(projection="3d")
ax.plot_surface(grid_x, grid_y, grid_z, cmap=plt.cm.Spectral)
ax.set_xlabel("Spot Price $S_T^1$ (\$)", size=15)
ax.set_ylabel("Spot Price $S_T^2$ (\$)", size=15)
ax.set_zlabel("Probability (\%)", size=15)
plt.show()
# determine number of qubits required to represent total loss
weights = []
for n in num_qubits:
for i in range(n):
weights += [2**i]
# create aggregation circuit
agg = WeightedAdder(sum(num_qubits), weights)
n_s = agg.num_sum_qubits
n_aux = agg.num_qubits - n_s - agg.num_state_qubits # number of additional qubits
# set the strike price (should be within the low and the high value of the uncertainty)
strike_price = 3.5
# map strike price from [low, high] to {0, ..., 2^n-1}
max_value = 2**n_s - 1
low_ = low[0]
high_ = high[0]
mapped_strike_price = (
(strike_price - dimension * low_) / (high_ - low_) * (2**num_uncertainty_qubits - 1)
)
# set the approximation scaling for the payoff function
c_approx = 0.25
# setup piecewise linear objective fcuntion
breakpoints = [0, mapped_strike_price]
slopes = [0, 1]
offsets = [0, 0]
f_min = 0
f_max = 2 * (2**num_uncertainty_qubits - 1) - mapped_strike_price
basket_objective = LinearAmplitudeFunction(
n_s,
slopes,
offsets,
domain=(0, max_value),
image=(f_min, f_max),
rescaling_factor=c_approx,
breakpoints=breakpoints,
)
# define overall multivariate problem
qr_state = QuantumRegister(u.num_qubits, "state") # to load the probability distribution
qr_obj = QuantumRegister(1, "obj") # to encode the function values
ar_sum = AncillaRegister(n_s, "sum") # number of qubits used to encode the sum
ar = AncillaRegister(max(n_aux, basket_objective.num_ancillas), "work") # additional qubits
objective_index = u.num_qubits
basket_option = QuantumCircuit(qr_state, qr_obj, ar_sum, ar)
basket_option.append(u, qr_state)
basket_option.append(agg, qr_state[:] + ar_sum[:] + ar[:n_aux])
basket_option.append(basket_objective, ar_sum[:] + qr_obj[:] + ar[: basket_objective.num_ancillas])
print(basket_option.draw())
print("objective qubit index", objective_index)
# plot exact payoff function (evaluated on the grid of the uncertainty model)
x = np.linspace(sum(low), sum(high))
y = np.maximum(0, x - strike_price)
plt.plot(x, y, "r-")
plt.grid()
plt.title("Payoff Function", size=15)
plt.xlabel("Sum of Spot Prices ($S_T^1 + S_T^2)$", size=15)
plt.ylabel("Payoff", size=15)
plt.xticks(size=15, rotation=90)
plt.yticks(size=15)
plt.show()
# evaluate exact expected value
sum_values = np.sum(u.values, axis=1)
exact_value = np.dot(
u.probabilities[sum_values >= strike_price],
sum_values[sum_values >= strike_price] - strike_price,
)
print("exact expected value:\t%.4f" % exact_value)
num_state_qubits = basket_option.num_qubits - basket_option.num_ancillas
print("state qubits: ", num_state_qubits)
transpiled = transpile(basket_option, basis_gates=["u", "cx"])
print("circuit width:", transpiled.width())
print("circuit depth:", transpiled.depth())
basket_option_measure = basket_option.measure_all(inplace=False)
sampler = Sampler()
job = sampler.run(basket_option_measure)
# evaluate the result
value = 0
probabilities = job.result().quasi_dists[0].binary_probabilities()
for i, prob in probabilities.items():
if prob > 1e-4 and i[-num_state_qubits:][0] == "1":
value += prob
# map value to original range
mapped_value = (
basket_objective.post_processing(value) / (2**num_uncertainty_qubits - 1) * (high_ - low_)
)
print("Exact Operator Value: %.4f" % value)
print("Mapped Operator value: %.4f" % mapped_value)
print("Exact Expected Payoff: %.4f" % exact_value)
# set target precision and confidence level
epsilon = 0.01
alpha = 0.05
problem = EstimationProblem(
state_preparation=basket_option,
objective_qubits=[objective_index],
post_processing=basket_objective.post_processing,
)
# construct amplitude estimation
ae = IterativeAmplitudeEstimation(
epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100})
)
result = ae.estimate(problem)
conf_int = (
np.array(result.confidence_interval_processed)
/ (2**num_uncertainty_qubits - 1)
* (high_ - low_)
)
print("Exact value: \t%.4f" % exact_value)
print(
"Estimated value: \t%.4f"
% (result.estimation_processed / (2**num_uncertainty_qubits - 1) * (high_ - low_))
)
print("Confidence interval:\t[%.4f, %.4f]" % tuple(conf_int))
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/swe-train/qiskit__qiskit
|
swe-train
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test calling passes (passmanager-less)"""
from qiskit import QuantumRegister, QuantumCircuit
from qiskit.circuit.library import ZGate
from qiskit.transpiler.passes import Unroller
from qiskit.test import QiskitTestCase
from qiskit.exceptions import QiskitError
from qiskit.transpiler import PropertySet
from ._dummy_passes import PassD_TP_NR_NP, PassE_AP_NR_NP, PassN_AP_NR_NP
class TestPassCall(QiskitTestCase):
"""Test calling passes (passmanager-less)."""
def assertMessageLog(self, context, messages):
"""Checks the log messages"""
self.assertEqual([record.message for record in context.records], messages)
def test_transformation_pass(self):
"""Call a transformation pass without a scheduler"""
qr = QuantumRegister(1, "qr")
circuit = QuantumCircuit(qr, name="MyCircuit")
pass_d = PassD_TP_NR_NP(argument1=[1, 2])
with self.assertLogs("LocalLogger", level="INFO") as cm:
result = pass_d(circuit)
self.assertMessageLog(cm, ["run transformation pass PassD_TP_NR_NP", "argument [1, 2]"])
self.assertEqual(circuit, result)
def test_analysis_pass_dict(self):
"""Call an analysis pass without a scheduler (property_set dict)"""
qr = QuantumRegister(1, "qr")
circuit = QuantumCircuit(qr, name="MyCircuit")
property_set = {"another_property": "another_value"}
pass_e = PassE_AP_NR_NP("value")
with self.assertLogs("LocalLogger", level="INFO") as cm:
result = pass_e(circuit, property_set)
self.assertMessageLog(cm, ["run analysis pass PassE_AP_NR_NP", "set property as value"])
self.assertEqual(property_set, {"another_property": "another_value", "property": "value"})
self.assertIsInstance(property_set, dict)
self.assertEqual(circuit, result)
def test_analysis_pass_property_set(self):
"""Call an analysis pass without a scheduler (PropertySet dict)"""
qr = QuantumRegister(1, "qr")
circuit = QuantumCircuit(qr, name="MyCircuit")
property_set = PropertySet({"another_property": "another_value"})
pass_e = PassE_AP_NR_NP("value")
with self.assertLogs("LocalLogger", level="INFO") as cm:
result = pass_e(circuit, property_set)
self.assertMessageLog(cm, ["run analysis pass PassE_AP_NR_NP", "set property as value"])
self.assertEqual(
property_set, PropertySet({"another_property": "another_value", "property": "value"})
)
self.assertIsInstance(property_set, PropertySet)
self.assertEqual(circuit, result)
def test_analysis_pass_remove_property(self):
"""Call an analysis pass that removes a property without a scheduler"""
qr = QuantumRegister(1, "qr")
circuit = QuantumCircuit(qr, name="MyCircuit")
property_set = {"to remove": "value to remove", "to none": "value to none"}
pass_e = PassN_AP_NR_NP("to remove", "to none")
with self.assertLogs("LocalLogger", level="INFO") as cm:
result = pass_e(circuit, property_set)
self.assertMessageLog(
cm,
[
"run analysis pass PassN_AP_NR_NP",
"property to remove deleted",
"property to none noned",
],
)
self.assertEqual(property_set, PropertySet({"to none": None}))
self.assertIsInstance(property_set, dict)
self.assertEqual(circuit, result)
def test_error_unknown_defn_unroller_pass(self):
"""Check for proper error message when unroller cannot find the definition
of a gate."""
circuit = ZGate().control(2).definition
basis = ["u1", "u2", "u3", "cx"]
unroller = Unroller(basis)
with self.assertRaises(QiskitError) as cm:
unroller(circuit)
exp_msg = (
"Error decomposing node of instruction 'p': 'NoneType' object has no"
" attribute 'global_phase'. Unable to define instruction 'u' in the basis."
)
self.assertEqual(exp_msg, cm.exception.message)
|
https://github.com/dimple12M/Qiskit-Certification-Guide
|
dimple12M
|
from qiskit import QuantumCircuit,QuantumRegister,ClassicalRegister,AncillaRegister
q=QuantumRegister(2)
q=QuantumRegister(2,'qr')
c=ClassicalRegister(2)
c=ClassicalRegister(2,'cr')
qr1=QuantumRegister(2,'qr_1')
qr2=QuantumRegister(3,'qr_2')
c=ClassicalRegister(2,'cr')
qc=QuantumCircuit(qr1,qr2,c)
qc.draw(output="mpl")
qc.width()
qc.qubits
qc.num_qubits
qr1=QuantumRegister(2,'qr_1')
anc=AncillaRegister(3,'an')
c=ClassicalRegister(2,'cr')
qc=QuantumCircuit(qr1,anc,c)
qc.draw(output="mpl")
qc.width()
qc.num_qubits
qc.num_clbits
qc.qubits # provides the information of qubits added
qr1
anc
qc
qc=QuantumCircuit(2,2)
qc.h(0)
qc.cx(0,1)
qc.x(1)
qc.draw(output='mpl')
qc.qregs
qc.num_qubits
qc2=QuantumRegister(2)
qc.add_register(qc2)
qc.draw(output='mpl')
qc.qregs
qc.num_qubits
qr=QuantumRegister(2,'q')
cr=ClassicalRegister(2,'c')
qc=QuantumCircuit(qr,cr)
qc.h(0)
qc.x(1)
qc.draw(output="mpl")
qr
qc.qregs
qr_add=QuantumRegister(2,'qr_add')
qc.add_register(qr_add)
qc.draw(output="mpl")
qr_add
qc.qregs
cr_add=ClassicalRegister(2,'cr_add')
qc.add_register(cr_add)
qc.draw(output="mpl")
cr_add
qc.cregs
qc.measure([0,1,2,3],[0,1,2,3])
qc.draw(output="mpl")
|
https://github.com/kaelynj/Qiskit-IsingModel
|
kaelynj
|
%reset -f
#%matplotlib inline
# Importing standard Qiskit libraries and configuring account
from qiskit import QuantumCircuit, execute, Aer, IBMQ, QuantumRegister
from qiskit.providers.aer import QasmSimulator, StatevectorSimulator, UnitarySimulator
from qiskit.compiler import transpile, assemble
from qiskit.tools.monitor import job_monitor
import matplotlib.pyplot as plt
from qiskit.tools.jupyter import *
from qiskit.visualization import *
from qiskit.quantum_info import *
import numpy as np
provider = IBMQ.load_account()
# Loading your IBM Q account(s)
#provider = IBMQ.load_account()
#constants
n = 4
lambd = 1.2
def thetak(k,lamb):
num = lamb - np.cos(2*np.pi*k/n)
denom = np.sqrt( (lamb-np.cos(2*np.pi*k/n))**2 + np.sin(2*np.pi*k/n)**2)
theta = np.arccos(num/denom)
return theta
#Create functions based on the decomposition included in appendix of Ising paper
def bog(qcirc, q1, q2, theta):
qcirc.x(q2)
qcirc.cx(q2, q1)
#Controlled RX gate
qcirc.rz(np.pi/2, q2)
qcirc.ry(theta/2, q2)
qcirc.cx(q1, q2)
qcirc.ry(-theta/2, q2)
qcirc.cx(q1, q2) #changed from qc to qcirc here - Bruna
qcirc.rz(-np.pi/2, q2)
#####################
qcirc.cx(q2, q1)
qcirc.x(q2)
qcirc.barrier()
return qcirc
def fourier(qcirc, q1, q2, phase):
qcirc.rz(phase, q1)
qcirc.cx(q1, q2)
#Controlled Hadamard
qcirc.sdg(q1)
qcirc.h(q1)
qcirc.tdg(q1)
qcirc.cx(q2, q1)
qcirc.t(q1)
qcirc.h(q1)
qcirc.s(q1)
####################
qcirc.cx(q1, q2)
qcirc.cz(q1, q2)
qcirc.barrier()
return qcirc
def digit_sum(n):
num_str = str(n)
sum = 0
for i in range(0, len(num_str)):
sum += int(num_str[i])
return sum
def ground_state(lamb, backend_name): # backend is now an imput, so we can plot
# different ones easily - Bruna
qc = QuantumCircuit(4, 4)
#Set correct ground state if lambda < 1
if lamb < 1:
qc.x(3)
qc.barrier()
#magnetization
mag = []
#Apply disentangling gates
qc = bog(qc, 0, 1, thetak(1.,lamb))
qc = fourier(qc, 0, 1, 2*np.pi/n)
qc = fourier(qc, 2, 3, 0.)
qc = fourier(qc, 0, 1, 0.)
qc = fourier(qc, 2, 3, 0.)
#Set measurement step
for i in range(0,4):
qc.measure(i,i)
backend = Aer.get_backend(backend_name)
shots = 1024
max_credits = 10 #Max number of credits to spend on execution
job = execute(qc, backend=backend, shots=shots, max_credits=max_credits)
job_monitor(job)
result = job.result()
counts = result.get_counts(qc)
##while not '0000' in counts:
# job = execute(qc, backend=backend, shots=shots, max_credits=max_credits)
# job_monitor(job)
# result = job.result()
# counts = result.get_counts(qc)
#Check what ground state is based on lambda
r1=list(counts.keys())
r2=list(counts.values())
M=0
for j in range(0,len(r1)):
M=M+(4-2*digit_sum(r1[j]))*r2[j]/shots
#print("$\lambda$: ",lam,", $<\sigma_{z}>$: ",M/4)
mag.append(M/4)
return mag
# if lamb < 1:
# return counts['0001']
# return counts['0000']/shots # it does not always works, sometimes it returns keyword error
# maybe we can add another else for the possibility of other states, but
# do not use it for plotting - Bruna
print(ground_state(lambd, 'qasm_simulator'))
#print(ground_state(.8,'statevector_simulator'))
lmbd = np.arange(.2, 1.75, 0.1)
sigmaz = []
for l in lmbd:
sigmaz.append(ground_state(l, 'qasm_simulator'))
print(sigmaz)
plt.plot(lmbd, sigmaz,'bo')
plt.ylabel("$\sigma_z$")
plt.xlabel("$\lambda$")
plt.ylim(0., 1.1)
plt.xlim(0., 1.8)
#Start up and initialize circuit
#Measurement
qc = QuantumCircuit(4, 4)
#Set correct ground state if lambda < 1
if lambd < 1:
qc.x(3)
qc.barrier()
#Apply disentangling gates
qc = bog(qc, 0, 1, thetak(1.,1.2))
qc = fourier(qc, 0, 1, 2*np.pi/n)
qc = fourier(qc, 2, 3, 0.)
qc = fourier(qc, 0, 1, 0.)
qc = fourier(qc, 2, 3, 0.)
#Set measurement step
for i in range(0,4):
qc.measure(i,i)
#Choose provider and backend
#provider = IBMQ.get_provider()
#provider = AerProvider()
#backend = Aer.get_backend('statevector_simulator')
backend = Aer.get_backend('qasm_simulator')
#backend = provider.get_backend('ibmq_qasm_simulator')
#backend = provider.get_backend('ibmqx4')
#backend = provider.get_backend('ibmqx2')
#backend = provider.get_backend('ibmq_16_melbourne')
shots = 1024
max_credits = 10 #Max number of credits to spend on execution
job = execute(qc, backend=backend, shots=shots, max_credits=max_credits)
job_monitor(job)
result = job.result()
counts = result.get_counts(qc)
#print(counts['0000'])
plot_histogram(counts)
# had to comment this part because qc is a local variable in groundstate function now - Bruna
phi = np.arccos(lambd/np.sqrt(1+lambd**2))/2
#print(result.get_statevector(qc))
print("|0000> probability should be: ",np.cos(phi)**2)
print("|0011> probability should be: ",np.sin(phi)**2 )
#print(counts['0000'])
def Time_Evo(t, lamb, backend_name):
quc = QuantumCircuit(4, 4)
#step 1. we are already in the |111> state
# time evolution of computational basis, step 2
quc.u3(np.arccos(lamb/np.sqrt(1+lamb**2)), np.pi/2 + 4*t*np.sqrt(1+lamb**2),0,0)
quc.cx(0,1)
#magnetization
mag = []
#step 3
#Apply disentangling gates
quc = bog(quc, 0, 1, thetak(1.,lamb))
quc = fourier(quc, 0, 1, 2*np.pi/n)
quc = fourier(quc, 2, 3, 0.)
quc = fourier(quc, 0, 1, 0.)
quc = fourier(quc, 2, 3, 0.)
#Set measurement step
for i in range(0,4):
quc.measure(i,i)
#provider = IBMQ.get_provider(hub='ibm-q', group='open', project='main')
backend = provider.get_backend(backend_name)
#backend = Aer.get_backend('statevector_simulator')
#backend = Aer.get_backend('qasm_simulator')
#backend = provider.get_backend('ibmq_qasm_simulator')
#backend = provider.get_backend('ibmqx4')
#backend = provider.get_backend('ibmqx2')
#backend = provider.get_backend('ibmq_16_melbourne')
shots = 1024
max_credits = 10 #Max number of credits to spend on execution
job = execute(quc, backend=backend, shots=shots, max_credits=max_credits)
job_monitor(job)
result = job.result()
counts = result.get_counts(quc)
##while not '0000' in counts:
# job = execute(qc, backend=backend, shots=shots, max_credits=max_credits)
# job_monitor(job)
# result = job.result()
# counts = result.get_counts(qc)
#Check what ground state is based on lambda
r1=list(counts.keys())
r2=list(counts.values())
M=0
for j in range(0,len(r1)):
M=M+(4-2*digit_sum(r1[j]))*r2[j]/shots
#print("$\lambda$: ",lam,", $<\sigma_{z}>$: ",M/4)
mag.append(M/4)
return mag
#f = Time_Evo(qc,1,lambd,'qasm_simulator')
#print(f)
#
ti = 0
tf = 2
time = np.arange(ti,tf,(tf-ti)/10)
f = []
for t in time:
f.append(Time_Evo(t,0.5,'ibmq_athens'))
#step 4
plt.plot(time, f)
plt.ylim(0., 1)
plt.xlim(0., 1.8)
plt.ylabel("Magnetization")
plt.xlabel("t")
plt.show()
|
https://github.com/tomtuamnuq/compare-qiskit-ocean
|
tomtuamnuq
|
import warnings
import numpy as np
from qiskit import IBMQ, execute, transpile, BasicAer
from qiskit_optimization.algorithms import CplexOptimizer
from qiskit_optimization import QuadraticProgram
from qiskit.visualization import plot_histogram
from qiskit.providers.ibmq.job import job_monitor
from utilities.helpers import create_qaoa_meo
# select linear program to solve
qp = QuadraticProgram()
qp.read_from_lp_file("example.lp")
# solve classically as reference
cplex = CplexOptimizer()
print(cplex.solve(qp))
print(qp)
# solve qp with Minimum Eigen Optimizer and QAOA
SHOTS = 1024
EVALUATIONS = 5
def qaoa_callback(eval_ct: int, opt_pars: np.ndarray, mean: float, stdev: float) -> None:
"""Print parameterset of last iteration."""
if eval_ct == EVALUATIONS:
print("Evaluation count reached ", eval_ct, "with pars:", opt_pars)
warnings.filterwarnings("ignore", category=DeprecationWarning)
qaoa = create_qaoa_meo(max_iter=EVALUATIONS, qaoa_callback=qaoa_callback, shots=SHOTS)
res = qaoa.solve(qp)
res
circuit = qaoa.min_eigen_solver.get_optimal_circuit()
circuit.measure_all()
result_meas = execute(circuit, BasicAer.get_backend('qasm_simulator'), shots=SHOTS)
counts = result_meas.result().get_counts()
plot_histogram(counts)
circuit.draw()
# to this later for belem!
for meas, count in sorted(counts.items(), key= lambda item: item[1], reverse=True):
print(meas[::-1]," : ",count) # x0, x1, x2 sorted by count
backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 3
and not x.configuration().simulator
and x.status().operational==True))
print(backend)
job = execute(circuit, backend, shots=shots, job_name="qaoa_3_real", job_tags=["qaoa", "least busy"])
job_monitor(job)
counts = job.result().get_counts()
plot_histogram(counts)
|
https://github.com/ElePT/qiskit-algorithms-test
|
ElePT
|
# 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.
"""Test the QAOA algorithm."""
import unittest
from functools import partial
from test.python.algorithms import QiskitAlgorithmsTestCase
import numpy as np
import rustworkx as rx
from ddt import ddt, idata, unpack
from scipy.optimize import minimize as scipy_minimize
from qiskit import QuantumCircuit
from qiskit_algorithms.minimum_eigensolvers import QAOA
from qiskit_algorithms.optimizers import COBYLA, NELDER_MEAD
from qiskit.circuit import Parameter
from qiskit.primitives import Sampler
from qiskit.quantum_info import Pauli, SparsePauliOp
from qiskit.result import QuasiDistribution
from qiskit.utils import algorithm_globals
W1 = np.array([[0, 1, 0, 1], [1, 0, 1, 0], [0, 1, 0, 1], [1, 0, 1, 0]])
P1 = 1
M1 = SparsePauliOp.from_list(
[
("IIIX", 1),
("IIXI", 1),
("IXII", 1),
("XIII", 1),
]
)
S1 = {"0101", "1010"}
W2 = np.array(
[
[0.0, 8.0, -9.0, 0.0],
[8.0, 0.0, 7.0, 9.0],
[-9.0, 7.0, 0.0, -8.0],
[0.0, 9.0, -8.0, 0.0],
]
)
P2 = 1
M2 = None
S2 = {"1011", "0100"}
CUSTOM_SUPERPOSITION = [1 / np.sqrt(15)] * 15 + [0]
@ddt
class TestQAOA(QiskitAlgorithmsTestCase):
"""Test QAOA with MaxCut."""
def setUp(self):
super().setUp()
self.seed = 10598
algorithm_globals.random_seed = self.seed
self.sampler = Sampler()
@idata(
[
[W1, P1, M1, S1],
[W2, P2, M2, S2],
]
)
@unpack
def test_qaoa(self, w, reps, mixer, solutions):
"""QAOA test"""
self.log.debug("Testing %s-step QAOA with MaxCut on graph\n%s", reps, w)
qubit_op, _ = self._get_operator(w)
qaoa = QAOA(self.sampler, COBYLA(), reps=reps, mixer=mixer)
result = qaoa.compute_minimum_eigenvalue(operator=qubit_op)
x = self._sample_most_likely(result.eigenstate)
graph_solution = self._get_graph_solution(x)
self.assertIn(graph_solution, solutions)
@idata(
[
[W1, P1, S1],
[W2, P2, S2],
]
)
@unpack
def test_qaoa_qc_mixer(self, w, prob, solutions):
"""QAOA test with a mixer as a parameterized circuit"""
self.log.debug(
"Testing %s-step QAOA with MaxCut on graph with a mixer as a parameterized circuit\n%s",
prob,
w,
)
optimizer = COBYLA()
qubit_op, _ = self._get_operator(w)
num_qubits = qubit_op.num_qubits
mixer = QuantumCircuit(num_qubits)
theta = Parameter("ΞΈ")
mixer.rx(theta, range(num_qubits))
qaoa = QAOA(self.sampler, optimizer, reps=prob, mixer=mixer)
result = qaoa.compute_minimum_eigenvalue(operator=qubit_op)
x = self._sample_most_likely(result.eigenstate)
graph_solution = self._get_graph_solution(x)
self.assertIn(graph_solution, solutions)
def test_qaoa_qc_mixer_many_parameters(self):
"""QAOA test with a mixer as a parameterized circuit with the num of parameters > 1."""
optimizer = COBYLA()
qubit_op, _ = self._get_operator(W1)
num_qubits = qubit_op.num_qubits
mixer = QuantumCircuit(num_qubits)
for i in range(num_qubits):
theta = Parameter("ΞΈ" + str(i))
mixer.rx(theta, range(num_qubits))
qaoa = QAOA(self.sampler, optimizer, reps=2, mixer=mixer)
result = qaoa.compute_minimum_eigenvalue(operator=qubit_op)
x = self._sample_most_likely(result.eigenstate)
self.log.debug(x)
graph_solution = self._get_graph_solution(x)
self.assertIn(graph_solution, S1)
def test_qaoa_qc_mixer_no_parameters(self):
"""QAOA test with a mixer as a parameterized circuit with zero parameters."""
qubit_op, _ = self._get_operator(W1)
num_qubits = qubit_op.num_qubits
mixer = QuantumCircuit(num_qubits)
# just arbitrary circuit
mixer.rx(np.pi / 2, range(num_qubits))
qaoa = QAOA(self.sampler, COBYLA(), reps=1, mixer=mixer)
result = qaoa.compute_minimum_eigenvalue(operator=qubit_op)
# we just assert that we get a result, it is not meaningful.
self.assertIsNotNone(result.eigenstate)
def test_change_operator_size(self):
"""QAOA change operator size test"""
qubit_op, _ = self._get_operator(
np.array([[0, 1, 0, 1], [1, 0, 1, 0], [0, 1, 0, 1], [1, 0, 1, 0]])
)
qaoa = QAOA(self.sampler, COBYLA(), reps=1)
result = qaoa.compute_minimum_eigenvalue(operator=qubit_op)
x = self._sample_most_likely(result.eigenstate)
graph_solution = self._get_graph_solution(x)
with self.subTest(msg="QAOA 4x4"):
self.assertIn(graph_solution, {"0101", "1010"})
qubit_op, _ = self._get_operator(
np.array(
[
[0, 1, 0, 1, 0, 1],
[1, 0, 1, 0, 1, 0],
[0, 1, 0, 1, 0, 1],
[1, 0, 1, 0, 1, 0],
[0, 1, 0, 1, 0, 1],
[1, 0, 1, 0, 1, 0],
]
)
)
result = qaoa.compute_minimum_eigenvalue(operator=qubit_op)
x = self._sample_most_likely(result.eigenstate)
graph_solution = self._get_graph_solution(x)
with self.subTest(msg="QAOA 6x6"):
self.assertIn(graph_solution, {"010101", "101010"})
@idata([[W2, S2, None], [W2, S2, [0.0, 0.0]], [W2, S2, [1.0, 0.8]]])
@unpack
def test_qaoa_initial_point(self, w, solutions, init_pt):
"""Check first parameter value used is initial point as expected"""
qubit_op, _ = self._get_operator(w)
first_pt = []
def cb_callback(eval_count, parameters, mean, metadata):
nonlocal first_pt
if eval_count == 1:
first_pt = list(parameters)
qaoa = QAOA(
self.sampler,
COBYLA(),
initial_point=init_pt,
callback=cb_callback,
)
result = qaoa.compute_minimum_eigenvalue(operator=qubit_op)
x = self._sample_most_likely(result.eigenstate)
graph_solution = self._get_graph_solution(x)
with self.subTest("Initial Point"):
# If None the preferred random initial point of QAOA variational form
if init_pt is None:
self.assertLess(result.eigenvalue, -0.97)
else:
self.assertListEqual(init_pt, first_pt)
with self.subTest("Solution"):
self.assertIn(graph_solution, solutions)
def test_qaoa_random_initial_point(self):
"""QAOA random initial point"""
w = rx.adjacency_matrix(
rx.undirected_gnp_random_graph(5, 0.5, seed=algorithm_globals.random_seed)
)
qubit_op, _ = self._get_operator(w)
qaoa = QAOA(self.sampler, NELDER_MEAD(disp=True), reps=2)
result = qaoa.compute_minimum_eigenvalue(operator=qubit_op)
self.assertLess(result.eigenvalue, -0.97)
def test_optimizer_scipy_callable(self):
"""Test passing a SciPy optimizer directly as callable."""
w = rx.adjacency_matrix(
rx.undirected_gnp_random_graph(5, 0.5, seed=algorithm_globals.random_seed)
)
qubit_op, _ = self._get_operator(w)
qaoa = QAOA(
self.sampler,
partial(scipy_minimize, method="Nelder-Mead", options={"maxiter": 2}),
)
result = qaoa.compute_minimum_eigenvalue(qubit_op)
self.assertEqual(result.cost_function_evals, 5)
def _get_operator(self, weight_matrix):
"""Generate Hamiltonian for the max-cut problem of a graph.
Args:
weight_matrix (numpy.ndarray) : adjacency matrix.
Returns:
PauliSumOp: operator for the Hamiltonian
float: a constant shift for the obj function.
"""
num_nodes = weight_matrix.shape[0]
pauli_list = []
shift = 0
for i in range(num_nodes):
for j in range(i):
if weight_matrix[i, j] != 0:
x_p = np.zeros(num_nodes, dtype=bool)
z_p = np.zeros(num_nodes, dtype=bool)
z_p[i] = True
z_p[j] = True
pauli_list.append([0.5 * weight_matrix[i, j], Pauli((z_p, x_p))])
shift -= 0.5 * weight_matrix[i, j]
lst = [(pauli[1].to_label(), pauli[0]) for pauli in pauli_list]
return SparsePauliOp.from_list(lst), shift
def _get_graph_solution(self, x: np.ndarray) -> str:
"""Get graph solution from binary string.
Args:
x : binary string as numpy array.
Returns:
a graph solution as string.
"""
return "".join([str(int(i)) for i in 1 - x])
def _sample_most_likely(self, state_vector: QuasiDistribution) -> np.ndarray:
"""Compute the most likely binary string from state vector.
Args:
state_vector: Quasi-distribution.
Returns:
Binary string as numpy.ndarray of ints.
"""
values = list(state_vector.values())
n = int(np.log2(len(values)))
k = np.argmax(np.abs(values))
x = np.zeros(n)
for i in range(n):
x[i] = k % 2
k >>= 1
return x
if __name__ == "__main__":
unittest.main()
|
https://github.com/rohitgit1/Quantum-Computing-Summer-School
|
rohitgit1
|
!pip install -U -r grading_tools/requirements.txt
from IPython.display import clear_output
clear_output()
import numpy as np; pi = np.pi
from qiskit import QuantumCircuit, Aer, execute
from qiskit.visualization import plot_histogram
from copy import deepcopy as make_copy
def prepare_hets_circuit(depth, angle1, angle2):
hets_circ = QuantumCircuit(depth)
hets_circ.ry(angle1, 0)
hets_circ.rz(angle1, 0)
hets_circ.ry(angle1, 1)
hets_circ.rz(angle1, 1)
for ii in range(depth):
hets_circ.cx(0,1)
hets_circ.ry(angle2,0)
hets_circ.rz(angle2,0)
hets_circ.ry(angle2,1)
hets_circ.rz(angle2,1)
return hets_circ
hets_circuit = prepare_hets_circuit(2, pi/2, pi/2)
hets_circuit.draw()
def measure_zz_circuit(given_circuit):
zz_meas = make_copy(given_circuit)
zz_meas.measure_all()
return zz_meas
zz_meas = measure_zz_circuit(hets_circuit)
zz_meas.draw()
simulator = Aer.get_backend('qasm_simulator')
result = execute(zz_meas, backend = simulator, shots=10000).result()
counts = result.get_counts(zz_meas)
plot_histogram(counts)
def measure_zz(given_circuit, num_shots = 10000):
zz_meas = measure_zz_circuit(given_circuit)
result = execute(zz_meas, backend = simulator, shots = num_shots).result()
counts = result.get_counts(zz_meas)
if '00' not in counts:
counts['00'] = 0
if '01' not in counts:
counts['01'] = 0
if '10' not in counts:
counts['10'] = 0
if '11' not in counts:
counts['11'] = 0
total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10']
zz = counts['00'] + counts['11'] - counts['01'] - counts['10']
zz = zz / total_counts
return zz
zz = measure_zz(hets_circuit)
print("<ZZ> =", str(zz))
def measure_zi(given_circuit, num_shots = 10000):
zz_meas = measure_zz_circuit(given_circuit)
result = execute(zz_meas, backend = simulator, shots = num_shots).result()
counts = result.get_counts(zz_meas)
if '00' not in counts:
counts['00'] = 0
if '01' not in counts:
counts['01'] = 0
if '10' not in counts:
counts['10'] = 0
if '11' not in counts:
counts['11'] = 0
total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10']
zi = counts['00'] - counts['11'] + counts['01'] - counts['10']
zi = zi / total_counts
return zi
def measure_iz(given_circuit, num_shots = 10000):
zz_meas = measure_zz_circuit(given_circuit)
result = execute(zz_meas, backend = simulator, shots = num_shots).result()
counts = result.get_counts(zz_meas)
if '00' not in counts:
counts['00'] = 0
if '01' not in counts:
counts['01'] = 0
if '10' not in counts:
counts['10'] = 0
if '11' not in counts:
counts['11'] = 0
total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10']
iz = counts['00'] - counts['11'] - counts['01'] + counts['10']
iz = iz / total_counts
return iz
zi = measure_zi(hets_circuit)
print("<ZI> =", str(zi))
iz = measure_iz(hets_circuit)
print("<IZ> =", str(iz))
def measure_xx_circuit(given_circuit):
xx_meas = make_copy(given_circuit)
### WRITE YOUR CODE BETWEEN THESE LINES - START
xx_meas.h(0)
xx_meas.h(1)
xx_meas.measure_all()
### WRITE YOUR CODE BETWEEN THESE LINES - END
return xx_meas
xx_meas = measure_xx_circuit(hets_circuit)
xx_meas.draw()
def measure_xx(given_circuit, num_shots = 10000):
xx_meas = measure_xx_circuit(given_circuit)
result = execute(xx_meas, backend = simulator, shots = num_shots).result()
counts = result.get_counts(xx_meas)
if '00' not in counts:
counts['00'] = 0
if '01' not in counts:
counts['01'] = 0
if '10' not in counts:
counts['10'] = 0
if '11' not in counts:
counts['11'] = 0
total_counts = counts['00'] + counts['11'] + counts['01'] + counts['10']
xx = counts['00'] + counts['11'] - counts['01'] - counts['10']
xx = xx / total_counts
return xx
xx = measure_xx(hets_circuit)
print("<XX> =", str(xx))
def get_energy(given_circuit, num_shots = 10000):
zz = measure_zz(given_circuit, num_shots = num_shots)
iz = measure_iz(given_circuit, num_shots = num_shots)
zi = measure_zi(given_circuit, num_shots = num_shots)
xx = measure_xx(given_circuit, num_shots = num_shots)
energy = (-1.0523732)*1 + (0.39793742)*iz + (-0.3979374)*zi + (-0.0112801)*zz + (0.18093119)*xx
return energy
energy = get_energy(hets_circuit)
print("The energy of the trial state is", str(energy))
hets_circuit_plus = None
hets_circuit_minus = None
### WRITE YOUR CODE BETWEEN THESE LINES - START
hets_circuit_plus = prepare_hets_circuit(2, pi/2 + 0.1*pi/2, pi/2)
hets_circuit_minus = prepare_hets_circuit(2, pi/2 - 0.1*pi/2, pi/2)
### WRITE YOUR CODE BETWEEN THESE LINES - END
energy_plus = get_energy(hets_circuit_plus, num_shots=100000)
energy_minus = get_energy(hets_circuit_minus, num_shots=100000)
print(energy_plus, energy_minus)
name = 'Pon Rahul M'
email = 'ponrahul.21it@licet.ac.in'
### Do not change the lines below
from grading_tools import grade
grade(answer=measure_xx_circuit(hets_circuit), name=name, email=email, labid='lab9', exerciseid='ex1')
grade(answer=hets_circuit_plus, name=name, email=email, labid='lab9', exerciseid='ex2')
grade(answer=hets_circuit_minus, name=name, email=email, labid='lab9', exerciseid='ex3')
energy_plus_100, energy_plus_1000, energy_plus_10000 = 0, 0, 0
energy_minus_100, energy_minus_1000, energy_minus_10000 = 0, 0, 0
### WRITE YOUR CODE BETWEEN THESE LINES - START
energy_plus_100 = get_energy(hets_circuit_plus, num_shots = 100)
energy_minus_100 = get_energy(hets_circuit_minus, num_shots = 100)
energy_plus_1000 = get_energy(hets_circuit_plus, num_shots = 1000)
energy_minus_1000 = get_energy(hets_circuit_minus, num_shots = 1000)
energy_plus_10000 = get_energy(hets_circuit_plus, num_shots = 10000)
energy_minus_10000 = get_energy(hets_circuit_minus, num_shots = 10000)
### WRITE YOUR CODE BETWEEN THESE LINES - END
print(energy_plus_100, energy_minus_100, "difference = ", energy_minus_100 - energy_plus_100)
print(energy_plus_1000, energy_minus_1000, "difference = ", energy_minus_1000 - energy_plus_1000)
print(energy_plus_10000, energy_minus_10000, "difference = ", energy_minus_10000 - energy_plus_10000)
### WRITE YOUR CODE BETWEEN THESE LINES - START
I = np.array([
[1, 0],
[0, 1]
])
X = np.array([
[0, 1],
[1, 0]
])
Z = np.array([
[1, 0],
[0, -1]
])
h2_hamiltonian = (-1.0523732) * np.kron(I, I) + \
(0.39793742) * np.kron(I, Z) + \
(-0.3979374) * np.kron(Z, I) + \
(-0.0112801) * np.kron(Z, Z) + \
(0.18093119) * np.kron(X, X)
from numpy import linalg as LA
eigenvalues, eigenvectors = LA.eig(h2_hamiltonian)
for ii, eigenvalue in enumerate(eigenvalues):
print(f"Eigenvector {eigenvectors[:,ii]} has energy {eigenvalue}")
exact_eigenvector = eigenvectors[:,np.argmin(eigenvalues)]
exact_eigenvalue = np.min(eigenvalues)
print()
print("Minimum energy is", exact_eigenvalue)
### WRITE YOUR CODE BETWEEN THESE LINES - END
|
https://github.com/DaisukeIto-ynu/KosakaQ
|
DaisukeIto-ynu
|
# 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.
"""A swap strategy pass for blocks of commuting gates."""
from __future__ import annotations
from collections import defaultdict
from qiskit.circuit import Gate, QuantumCircuit, Qubit
from qiskit.converters import circuit_to_dag
from qiskit.dagcircuit import DAGCircuit, DAGOpNode
from qiskit.transpiler import TransformationPass, Layout, TranspilerError
from qiskit.transpiler.passes.routing.commuting_2q_gate_routing.swap_strategy import SwapStrategy
from qiskit.transpiler.passes.routing.commuting_2q_gate_routing.commuting_2q_block import (
Commuting2qBlock,
)
class Commuting2qGateRouter(TransformationPass):
"""A class to swap route one or more commuting gates to the coupling map.
This pass routes blocks of commuting two-qubit gates encapsulated as
:class:`.Commuting2qBlock` instructions. This pass will not apply to other instructions.
The mapping to the coupling map is done using swap strategies, see :class:`.SwapStrategy`.
The swap strategy should suit the problem and the coupling map. This transpiler pass
should ideally be executed before the quantum circuit is enlarged with any idle ancilla
qubits. Otherwise we may swap qubits outside of the portion of the chip we want to use.
Therefore, the swap strategy and its associated coupling map do not represent physical
qubits. Instead, they represent an intermediate mapping that corresponds to the physical
qubits once the initial layout is applied. The example below shows how to map a four
qubit :class:`.PauliEvolutionGate` to qubits 0, 1, 3, and 4 of the five qubit device with
the coupling map
.. parsed-literal::
0 -- 1 -- 2
|
3
|
4
To do this we use a line swap strategy for qubits 0, 1, 3, and 4 defined it in terms
of virtual qubits 0, 1, 2, and 3.
.. code-block:: python
from qiskit import QuantumCircuit
from qiskit.opflow import PauliSumOp
from qiskit.circuit.library import PauliEvolutionGate
from qiskit.transpiler import Layout, CouplingMap, PassManager
from qiskit.transpiler.passes import FullAncillaAllocation
from qiskit.transpiler.passes import EnlargeWithAncilla
from qiskit.transpiler.passes import ApplyLayout
from qiskit.transpiler.passes import SetLayout
from qiskit.transpiler.passes.routing.commuting_2q_gate_routing import (
SwapStrategy,
FindCommutingPauliEvolutions,
Commuting2qGateRouter,
)
# Define the circuit on virtual qubits
op = PauliSumOp.from_list([("IZZI", 1), ("ZIIZ", 2), ("ZIZI", 3)])
circ = QuantumCircuit(4)
circ.append(PauliEvolutionGate(op, 1), range(4))
# Define the swap strategy on qubits before the initial_layout is applied.
swap_strat = SwapStrategy.from_line([0, 1, 2, 3])
# Chose qubits 0, 1, 3, and 4 from the backend coupling map shown above.
backend_cmap = CouplingMap(couplinglist=[(0, 1), (1, 2), (1, 3), (3, 4)])
initial_layout = Layout.from_intlist([0, 1, 3, 4], *circ.qregs)
pm_pre = PassManager(
[
FindCommutingPauliEvolutions(),
Commuting2qGateRouter(swap_strat),
SetLayout(initial_layout),
FullAncillaAllocation(backend_cmap),
EnlargeWithAncilla(),
ApplyLayout(),
]
)
# Insert swap gates, map to initial_layout and finally enlarge with ancilla.
pm_pre.run(circ).draw("mpl")
This pass manager relies on the ``current_layout`` which corresponds to the qubit layout as
swap gates are applied. The pass will traverse all nodes in the dag. If a node should be
routed using a swap strategy then it will be decomposed into sub-instructions with swap
layers in between and the ``current_layout`` will be modified. Nodes that should not be
routed using swap strategies will be added back to the dag taking the ``current_layout``
into account.
"""
def __init__(
self,
swap_strategy: SwapStrategy | None = None,
edge_coloring: dict[tuple[int, int], int] | None = None,
) -> None:
r"""
Args:
swap_strategy: An instance of a :class:`.SwapStrategy` that holds the swap layers
that are used, and the order in which to apply them, to map the instruction to
the hardware. If this field is not given if should be contained in the
property set of the pass. This allows other passes to determine the most
appropriate swap strategy at run-time.
edge_coloring: An optional edge coloring of the coupling map (I.e. no two edges that
share a node have the same color). If the edge coloring is given then the commuting
gates that can be simultaneously applied given the current qubit permutation are
grouped according to the edge coloring and applied according to this edge
coloring. Here, a color is an int which is used as the index to define and
access the groups of commuting gates that can be applied simultaneously.
If the edge coloring is not given then the sets will be built-up using a
greedy algorithm. The edge coloring is useful to position gates such as
``RZZGate``\s next to swap gates to exploit CX cancellations.
"""
super().__init__()
self._swap_strategy = swap_strategy
self._bit_indices: dict[Qubit, int] | None = None
self._edge_coloring = edge_coloring
def run(self, dag: DAGCircuit) -> DAGCircuit:
"""Run the pass by decomposing the nodes it applies on.
Args:
dag: The dag to which we will add swaps.
Returns:
A dag where swaps have been added for the intended gate type.
Raises:
TranspilerError: If the swap strategy was not given at init time and there is
no swap strategy in the property set.
TranspilerError: If the quantum circuit contains more than one qubit register.
TranspilerError: If there are qubits that are not contained in the quantum register.
"""
if self._swap_strategy is None:
swap_strategy = self.property_set["swap_strategy"]
if swap_strategy is None:
raise TranspilerError("No swap strategy given at init or in the property set.")
else:
swap_strategy = self._swap_strategy
if len(dag.qregs) != 1:
raise TranspilerError(
f"{self.__class__.__name__} runs on circuits with one quantum register."
)
if len(dag.qubits) != next(iter(dag.qregs.values())).size:
raise TranspilerError("Circuit has qubits not contained in the qubit register.")
new_dag = dag.copy_empty_like()
current_layout = Layout.generate_trivial_layout(*dag.qregs.values())
# Used to keep track of nodes that do not decompose using swap strategies.
accumulator = new_dag.copy_empty_like()
for node in dag.topological_op_nodes():
if isinstance(node.op, Commuting2qBlock):
# Check that the swap strategy creates enough connectivity for the node.
self._check_edges(dag, node, swap_strategy)
# Compose any accumulated non-swap strategy gates to the dag
accumulator = self._compose_non_swap_nodes(accumulator, current_layout, new_dag)
# Decompose the swap-strategy node and add to the dag.
new_dag.compose(self.swap_decompose(dag, node, current_layout, swap_strategy))
else:
accumulator.apply_operation_back(node.op, node.qargs, node.cargs)
self._compose_non_swap_nodes(accumulator, current_layout, new_dag)
return new_dag
def _compose_non_swap_nodes(
self, accumulator: DAGCircuit, layout: Layout, new_dag: DAGCircuit
) -> DAGCircuit:
"""Add all the non-swap strategy nodes that we have accumulated up to now.
This method also resets the node accumulator to an empty dag.
Args:
layout: The current layout that keeps track of the swaps.
new_dag: The new dag that we are building up.
accumulator: A DAG to keep track of nodes that do not decompose
using swap strategies.
Returns:
A new accumulator with the same registers as ``new_dag``.
"""
# Add all the non-swap strategy nodes that we have accumulated up to now.
order = layout.reorder_bits(new_dag.qubits)
order_bits: list[int | None] = [None] * len(layout)
for idx, val in enumerate(order):
order_bits[val] = idx
new_dag.compose(accumulator, qubits=order_bits)
# Re-initialize the node accumulator
return new_dag.copy_empty_like()
def _position_in_cmap(self, dag: DAGCircuit, j: int, k: int, layout: Layout) -> tuple[int, ...]:
"""A helper function to track the movement of virtual qubits through the swaps.
Args:
j: The index of decision variable j (i.e. virtual qubit).
k: The index of decision variable k (i.e. virtual qubit).
layout: The current layout that takes into account previous swap gates.
Returns:
The position in the coupling map of the virtual qubits j and k as a tuple.
"""
bit0 = dag.find_bit(layout.get_physical_bits()[j]).index
bit1 = dag.find_bit(layout.get_physical_bits()[k]).index
return bit0, bit1
def _build_sub_layers(
self, current_layer: dict[tuple[int, int], Gate]
) -> list[dict[tuple[int, int], Gate]]:
"""A helper method to build-up sets of gates to simultaneously apply.
This is done with an edge coloring if the ``edge_coloring`` init argument was given or with
a greedy algorithm if not. With an edge coloring all gates on edges with the same color
will be applied simultaneously. These sublayers are applied in the order of their color,
which is an int, in increasing color order.
Args:
current_layer: All gates in the current layer can be applied given the qubit ordering
of the current layout. However, not all gates in the current layer can be applied
simultaneously. This function creates sub-layers by building up sub-layers
of gates. All gates in a sub-layer can simultaneously be applied given the coupling
map and current qubit configuration.
Returns:
A list of gate dicts that can be applied. The gates a position 0 are applied first.
A gate dict has the qubit tuple as key and the gate to apply as value.
"""
if self._edge_coloring is not None:
return self._edge_coloring_build_sub_layers(current_layer)
else:
return self._greedy_build_sub_layers(current_layer)
def _edge_coloring_build_sub_layers(
self, current_layer: dict[tuple[int, int], Gate]
) -> list[dict[tuple[int, int], Gate]]:
"""The edge coloring method of building sub-layers of commuting gates."""
sub_layers: list[dict[tuple[int, int], Gate]] = [
{} for _ in set(self._edge_coloring.values())
]
for edge, gate in current_layer.items():
color = self._edge_coloring[edge]
sub_layers[color][edge] = gate
return sub_layers
@staticmethod
def _greedy_build_sub_layers(
current_layer: dict[tuple[int, int], Gate]
) -> list[dict[tuple[int, int], Gate]]:
"""The greedy method of building sub-layers of commuting gates."""
sub_layers = []
while len(current_layer) > 0:
current_sub_layer, remaining_gates = {}, {}
blocked_vertices: set[tuple] = set()
for edge, evo_gate in current_layer.items():
if blocked_vertices.isdisjoint(edge):
current_sub_layer[edge] = evo_gate
# A vertex becomes blocked once a gate is applied to it.
blocked_vertices = blocked_vertices.union(edge)
else:
remaining_gates[edge] = evo_gate
current_layer = remaining_gates
sub_layers.append(current_sub_layer)
return sub_layers
def swap_decompose(
self, dag: DAGCircuit, node: DAGOpNode, current_layout: Layout, swap_strategy: SwapStrategy
) -> DAGCircuit:
"""Take an instance of :class:`.Commuting2qBlock` and map it to the coupling map.
The mapping is done with the swap strategy.
Args:
dag: The dag which contains the :class:`.Commuting2qBlock` we route.
node: A node whose operation is a :class:`.Commuting2qBlock`.
current_layout: The layout before the swaps are applied. This function will
modify the layout so that subsequent gates can be properly composed on the dag.
swap_strategy: The swap strategy used to decompose the node.
Returns:
A dag that is compatible with the coupling map where swap gates have been added
to map the gates in the :class:`.Commuting2qBlock` to the hardware.
"""
trivial_layout = Layout.generate_trivial_layout(*dag.qregs.values())
gate_layers = self._make_op_layers(dag, node.op, current_layout, swap_strategy)
# Iterate over and apply gate layers
max_distance = max(gate_layers.keys())
circuit_with_swap = QuantumCircuit(len(dag.qubits))
for i in range(max_distance + 1):
# Get current layer and replace the problem indices j,k by the corresponding
# positions in the coupling map. The current layer corresponds
# to all the gates that can be applied at the ith swap layer.
current_layer = {}
for (j, k), local_gate in gate_layers.get(i, {}).items():
current_layer[self._position_in_cmap(dag, j, k, current_layout)] = local_gate
# Not all gates that are applied at the ith swap layer can be applied at the same
# time. We therefore greedily build sub-layers.
sub_layers = self._build_sub_layers(current_layer)
# Apply sub-layers
for sublayer in sub_layers:
for edge, local_gate in sublayer.items():
circuit_with_swap.append(local_gate, edge)
# Apply SWAP gates
if i < max_distance:
for swap in swap_strategy.swap_layer(i):
(j, k) = [trivial_layout.get_physical_bits()[vertex] for vertex in swap]
circuit_with_swap.swap(j, k)
current_layout.swap(j, k)
return circuit_to_dag(circuit_with_swap)
def _make_op_layers(
self, dag: DAGCircuit, op: Commuting2qBlock, layout: Layout, swap_strategy: SwapStrategy
) -> dict[int, dict[tuple, Gate]]:
"""Creates layers of two-qubit gates based on the distance in the swap strategy."""
gate_layers: dict[int, dict[tuple, Gate]] = defaultdict(dict)
for node in op.node_block:
edge = (dag.find_bit(node.qargs[0]).index, dag.find_bit(node.qargs[1]).index)
bit0 = layout.get_virtual_bits()[dag.qubits[edge[0]]]
bit1 = layout.get_virtual_bits()[dag.qubits[edge[1]]]
distance = swap_strategy.distance_matrix[bit0, bit1]
gate_layers[distance][edge] = node.op
return gate_layers
def _check_edges(self, dag: DAGCircuit, node: DAGOpNode, swap_strategy: SwapStrategy):
"""Check if the swap strategy can create the required connectivity.
Args:
node: The dag node for which to check if the swap strategy provides enough connectivity.
swap_strategy: The swap strategy that is being used.
Raises:
TranspilerError: If there is an edge that the swap strategy cannot accommodate
and if the pass has been configured to raise on such issues.
"""
required_edges = set()
for sub_node in node.op:
edge = (dag.find_bit(sub_node.qargs[0]).index, dag.find_bit(sub_node.qargs[1]).index)
required_edges.add(edge)
# Check that the swap strategy supports all required edges
if not required_edges.issubset(swap_strategy.possible_edges):
raise TranspilerError(
f"{swap_strategy} cannot implement all edges in {required_edges}."
)
|
https://github.com/swe-train/qiskit__qiskit
|
swe-train
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Tests for pass manager visualization tool."""
import unittest
import os
from qiskit.transpiler import CouplingMap, Layout
from qiskit.transpiler.passmanager import PassManager
from qiskit import QuantumRegister
from qiskit.transpiler.passes import GateDirection, Unroller
from qiskit.transpiler.passes import CheckMap
from qiskit.transpiler.passes import SetLayout
from qiskit.transpiler.passes import TrivialLayout
from qiskit.transpiler.passes import BarrierBeforeFinalMeasurements
from qiskit.transpiler.passes import FullAncillaAllocation
from qiskit.transpiler.passes import EnlargeWithAncilla
from qiskit.transpiler.passes import RemoveResetInZeroState
from qiskit.utils import optionals
from .visualization import QiskitVisualizationTestCase, path_to_diagram_reference
@unittest.skipUnless(optionals.HAS_GRAPHVIZ, "Graphviz not installed.")
@unittest.skipUnless(optionals.HAS_PYDOT, "pydot not installed")
@unittest.skipUnless(optionals.HAS_PIL, "Pillow not installed")
class TestPassManagerDrawer(QiskitVisualizationTestCase):
"""Qiskit pass manager drawer tests."""
def setUp(self):
super().setUp()
coupling = [[0, 1], [1, 2], [2, 3], [3, 4], [4, 5], [5, 6]]
coupling_map = CouplingMap(couplinglist=coupling)
basis_gates = ["u1", "u3", "u2", "cx"]
qr = QuantumRegister(7, "q")
layout = Layout({qr[i]: i for i in range(coupling_map.size())})
# Create a pass manager with a variety of passes and flow control structures
self.pass_manager = PassManager()
self.pass_manager.append(SetLayout(layout))
self.pass_manager.append(TrivialLayout(coupling_map), condition=lambda x: True)
self.pass_manager.append(FullAncillaAllocation(coupling_map))
self.pass_manager.append(EnlargeWithAncilla())
self.pass_manager.append(Unroller(basis_gates))
self.pass_manager.append(CheckMap(coupling_map))
self.pass_manager.append(BarrierBeforeFinalMeasurements(), do_while=lambda x: False)
self.pass_manager.append(GateDirection(coupling_map))
self.pass_manager.append(RemoveResetInZeroState())
def test_pass_manager_drawer_basic(self):
"""Test to see if the drawer draws a normal pass manager correctly"""
filename = "current_standard.dot"
self.pass_manager.draw(filename=filename, raw=True)
try:
self.assertFilesAreEqual(
filename, path_to_diagram_reference("pass_manager_standard.dot")
)
finally:
os.remove(filename)
def test_pass_manager_drawer_style(self):
"""Test to see if the colours are updated when provided by the user"""
# set colours for some passes, but leave others to take the default values
style = {
SetLayout: "cyan",
CheckMap: "green",
EnlargeWithAncilla: "pink",
RemoveResetInZeroState: "grey",
}
filename = "current_style.dot"
self.pass_manager.draw(filename=filename, style=style, raw=True)
try:
self.assertFilesAreEqual(filename, path_to_diagram_reference("pass_manager_style.dot"))
finally:
os.remove(filename)
if __name__ == "__main__":
unittest.main(verbosity=2)
|
https://github.com/jonasmaziero/computacao_quantica_qiskit
|
jonasmaziero
|
%run init.ipynb
((10+9.8+9.5)/3+10)/2
(9.77+10)/2
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Tests for visualization of circuit with Latex drawer."""
import os
import unittest
import math
import numpy as np
from qiskit.visualization import circuit_drawer
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, transpile
from qiskit.providers.fake_provider import FakeTenerife
from qiskit.circuit.library import XGate, MCXGate, RZZGate, SwapGate, DCXGate, CPhaseGate
from qiskit.extensions import HamiltonianGate
from qiskit.circuit import Parameter, Qubit, Clbit
from qiskit.circuit.library import IQP
from qiskit.quantum_info.random import random_unitary
from qiskit.utils import optionals
from .visualization import QiskitVisualizationTestCase
pi = np.pi
@unittest.skipUnless(optionals.HAS_PYLATEX, "needs pylatexenc")
class TestLatexSourceGenerator(QiskitVisualizationTestCase):
"""Qiskit latex source generator tests."""
def _get_resource_path(self, filename):
reference_dir = os.path.dirname(os.path.abspath(__file__))
return os.path.join(reference_dir, filename)
def test_empty_circuit(self):
"""Test draw an empty circuit"""
filename = self._get_resource_path("test_latex_empty.tex")
circuit = QuantumCircuit(1)
circuit_drawer(circuit, filename=filename, output="latex_source")
self.assertEqualToReference(filename)
def test_tiny_circuit(self):
"""Test draw tiny circuit."""
filename = self._get_resource_path("test_latex_tiny.tex")
circuit = QuantumCircuit(1)
circuit.h(0)
circuit_drawer(circuit, filename=filename, output="latex_source")
self.assertEqualToReference(filename)
def test_multi_underscore_reg_names(self):
"""Test multi-underscores in register names display properly"""
filename1 = self._get_resource_path("test_latex_multi_underscore_true.tex")
filename2 = self._get_resource_path("test_latex_multi_underscore_false.tex")
q_reg1 = QuantumRegister(1, "q1_re__g__g")
q_reg3 = QuantumRegister(3, "q3_re_g__g")
c_reg1 = ClassicalRegister(1, "c1_re_g__g")
c_reg3 = ClassicalRegister(3, "c3_re_g__g")
circuit = QuantumCircuit(q_reg1, q_reg3, c_reg1, c_reg3)
circuit_drawer(circuit, cregbundle=True, filename=filename1, output="latex_source")
circuit_drawer(circuit, cregbundle=False, filename=filename2, output="latex_source")
self.assertEqualToReference(filename1)
self.assertEqualToReference(filename2)
def test_normal_circuit(self):
"""Test draw normal size circuit."""
filename = self._get_resource_path("test_latex_normal.tex")
circuit = QuantumCircuit(5)
for qubit in range(5):
circuit.h(qubit)
circuit_drawer(circuit, filename=filename, output="latex_source")
self.assertEqualToReference(filename)
def test_4597(self):
"""Test cregbundle and conditional gates.
See: https://github.com/Qiskit/qiskit-terra/pull/4597"""
filename = self._get_resource_path("test_latex_4597.tex")
qr = QuantumRegister(3, "q")
cr = ClassicalRegister(3, "c")
circuit = QuantumCircuit(qr, cr)
circuit.x(qr[2]).c_if(cr, 2)
circuit.draw(output="latex_source", cregbundle=True)
circuit_drawer(circuit, filename=filename, output="latex_source")
self.assertEqualToReference(filename)
def test_deep_circuit(self):
"""Test draw deep circuit."""
filename = self._get_resource_path("test_latex_deep.tex")
circuit = QuantumCircuit(1)
for _ in range(100):
circuit.h(0)
circuit_drawer(circuit, filename=filename, output="latex_source")
self.assertEqualToReference(filename)
def test_huge_circuit(self):
"""Test draw huge circuit."""
filename = self._get_resource_path("test_latex_huge.tex")
circuit = QuantumCircuit(40)
for qubit in range(39):
circuit.h(qubit)
circuit.cx(qubit, 39)
circuit_drawer(circuit, filename=filename, output="latex_source")
self.assertEqualToReference(filename)
def test_teleport(self):
"""Test draw teleport circuit."""
filename = self._get_resource_path("test_latex_teleport.tex")
qr = QuantumRegister(3, "q")
cr = ClassicalRegister(3, "c")
circuit = QuantumCircuit(qr, cr)
# Prepare an initial state
circuit.u(0.3, 0.2, 0.1, [qr[0]])
# Prepare a Bell pair
circuit.h(qr[1])
circuit.cx(qr[1], qr[2])
# Barrier following state preparation
circuit.barrier(qr)
# Measure in the Bell basis
circuit.cx(qr[0], qr[1])
circuit.h(qr[0])
circuit.measure(qr[0], cr[0])
circuit.measure(qr[1], cr[1])
# Apply a correction
circuit.z(qr[2]).c_if(cr, 1)
circuit.x(qr[2]).c_if(cr, 2)
circuit.measure(qr[2], cr[2])
circuit_drawer(circuit, filename=filename, output="latex_source")
self.assertEqualToReference(filename)
def test_global_phase(self):
"""Test circuit with global phase"""
filename = self._get_resource_path("test_latex_global_phase.tex")
circuit = QuantumCircuit(3, global_phase=1.57079632679)
circuit.h(range(3))
circuit_drawer(circuit, filename=filename, output="latex_source")
self.assertEqualToReference(filename)
def test_no_ops(self):
"""Test circuit with no ops.
See https://github.com/Qiskit/qiskit-terra/issues/5393"""
filename = self._get_resource_path("test_latex_no_ops.tex")
circuit = QuantumCircuit(2, 3)
circuit_drawer(circuit, filename=filename, output="latex_source")
self.assertEqualToReference(filename)
def test_long_name(self):
"""Test to see that long register names can be seen completely
As reported in #2605
"""
filename = self._get_resource_path("test_latex_long_name.tex")
# add a register with a very long name
qr = QuantumRegister(4, "veryLongQuantumRegisterName")
# add another to make sure adjustments are made based on longest
qrr = QuantumRegister(1, "q0")
circuit = QuantumCircuit(qr, qrr)
# check gates are shifted over accordingly
circuit.h(qr)
circuit.h(qr)
circuit.h(qr)
circuit_drawer(circuit, filename=filename, output="latex_source")
self.assertEqualToReference(filename)
def test_conditional(self):
"""Test that circuits with conditionals draw correctly"""
filename = self._get_resource_path("test_latex_conditional.tex")
qr = QuantumRegister(2, "q")
cr = ClassicalRegister(2, "c")
circuit = QuantumCircuit(qr, cr)
# check gates are shifted over accordingly
circuit.h(qr)
circuit.measure(qr, cr)
circuit.h(qr[0]).c_if(cr, 2)
circuit_drawer(circuit, filename=filename, output="latex_source")
self.assertEqualToReference(filename)
def test_plot_partial_barrier(self):
"""Test plotting of partial barriers."""
filename = self._get_resource_path("test_latex_plot_partial_barriers.tex")
# generate a circuit with barrier and other barrier like instructions in
q = QuantumRegister(2, "q")
c = ClassicalRegister(2, "c")
circuit = QuantumCircuit(q, c)
# check for barriers
circuit.h(q[0])
circuit.barrier(0)
circuit.h(q[0])
circuit_drawer(circuit, filename=filename, output="latex_source")
self.assertEqualToReference(filename)
def test_plot_barriers(self):
"""Test to see that plotting barriers works.
If it is set to False, no blank columns are introduced"""
filename1 = self._get_resource_path("test_latex_plot_barriers_true.tex")
filename2 = self._get_resource_path("test_latex_plot_barriers_false.tex")
# generate a circuit with barriers and other barrier like instructions in
q = QuantumRegister(2, "q")
c = ClassicalRegister(2, "c")
circuit = QuantumCircuit(q, c)
# check for barriers
circuit.h(q[0])
circuit.barrier()
# check for other barrier like commands
circuit.h(q[1])
# this import appears to be unused, but is actually needed to get snapshot instruction
import qiskit.extensions.simulator # pylint: disable=unused-import
circuit.snapshot("sn 1")
# check the barriers plot properly when plot_barriers= True
circuit_drawer(circuit, filename=filename1, output="latex_source", plot_barriers=True)
self.assertEqualToReference(filename1)
circuit_drawer(circuit, filename=filename2, output="latex_source", plot_barriers=False)
self.assertEqualToReference(filename2)
def test_no_barriers_false(self):
"""Generate the same circuit as test_plot_barriers but without the barrier commands
as this is what the circuit should look like when displayed with plot barriers false"""
filename = self._get_resource_path("test_latex_no_barriers_false.tex")
q1 = QuantumRegister(2, "q")
c1 = ClassicalRegister(2, "c")
circuit = QuantumCircuit(q1, c1)
circuit.h(q1[0])
circuit.h(q1[1])
circuit_drawer(circuit, filename=filename, output="latex_source")
self.assertEqualToReference(filename)
def test_barrier_label(self):
"""Test the barrier label"""
filename = self._get_resource_path("test_latex_barrier_label.tex")
qr = QuantumRegister(2, "q")
circuit = QuantumCircuit(qr)
circuit.x(0)
circuit.y(1)
circuit.barrier()
circuit.y(0)
circuit.x(1)
circuit.barrier(label="End Y/X")
circuit_drawer(circuit, filename=filename, output="latex_source")
self.assertEqualToReference(filename)
def test_big_gates(self):
"""Test large gates with params"""
filename = self._get_resource_path("test_latex_big_gates.tex")
qr = QuantumRegister(6, "q")
circuit = QuantumCircuit(qr)
circuit.append(IQP([[6, 5, 3], [5, 4, 5], [3, 5, 1]]), [0, 1, 2])
desired_vector = [
1 / math.sqrt(16) * complex(0, 1),
1 / math.sqrt(8) * complex(1, 0),
1 / math.sqrt(16) * complex(1, 1),
0,
0,
1 / math.sqrt(8) * complex(1, 2),
1 / math.sqrt(16) * complex(1, 0),
0,
]
circuit.initialize(desired_vector, [qr[3], qr[4], qr[5]])
circuit.unitary([[1, 0], [0, 1]], [qr[0]])
matrix = np.zeros((4, 4))
theta = Parameter("theta")
circuit.append(HamiltonianGate(matrix, theta), [qr[1], qr[2]])
circuit = circuit.bind_parameters({theta: 1})
circuit.isometry(np.eye(4, 4), list(range(3, 5)), [])
circuit_drawer(circuit, filename=filename, output="latex_source")
self.assertEqualToReference(filename)
def test_cnot(self):
"""Test different cnot gates (ccnot, mcx, etc)"""
filename = self._get_resource_path("test_latex_cnot.tex")
qr = QuantumRegister(5, "q")
circuit = QuantumCircuit(qr)
circuit.x(0)
circuit.cx(0, 1)
circuit.ccx(0, 1, 2)
circuit.append(XGate().control(3, ctrl_state="010"), [qr[2], qr[3], qr[0], qr[1]])
circuit.append(MCXGate(num_ctrl_qubits=3, ctrl_state="101"), [qr[0], qr[1], qr[2], qr[4]])
circuit_drawer(circuit, filename=filename, output="latex_source")
self.assertEqualToReference(filename)
def test_pauli_clifford(self):
"""Test Pauli(green) and Clifford(blue) gates"""
filename = self._get_resource_path("test_latex_pauli_clifford.tex")
qr = QuantumRegister(5, "q")
circuit = QuantumCircuit(qr)
circuit.x(0)
circuit.y(0)
circuit.z(0)
circuit.id(0)
circuit.h(1)
circuit.cx(1, 2)
circuit.cy(1, 2)
circuit.cz(1, 2)
circuit.swap(3, 4)
circuit.s(3)
circuit.sdg(3)
circuit.iswap(3, 4)
circuit.dcx(3, 4)
circuit_drawer(circuit, filename=filename, output="latex_source")
self.assertEqualToReference(filename)
def test_u_gates(self):
"""Test U 1, 2, & 3 gates"""
filename = self._get_resource_path("test_latex_u_gates.tex")
from qiskit.circuit.library import U1Gate, U2Gate, U3Gate, CU1Gate, CU3Gate
qr = QuantumRegister(4, "q")
circuit = QuantumCircuit(qr)
circuit.append(U1Gate(3 * pi / 2), [0])
circuit.append(U2Gate(3 * pi / 2, 2 * pi / 3), [1])
circuit.append(U3Gate(3 * pi / 2, 4.5, pi / 4), [2])
circuit.append(CU1Gate(pi / 4), [0, 1])
circuit.append(U2Gate(pi / 2, 3 * pi / 2).control(1), [2, 3])
circuit.append(CU3Gate(3 * pi / 2, -3 * pi / 4, -pi / 2), [0, 1])
circuit_drawer(circuit, filename=filename, output="latex_source")
self.assertEqualToReference(filename)
def test_creg_initial(self):
"""Test cregbundle and initial state options"""
filename1 = self._get_resource_path("test_latex_creg_initial_true.tex")
filename2 = self._get_resource_path("test_latex_creg_initial_false.tex")
qr = QuantumRegister(2, "q")
cr = ClassicalRegister(2, "c")
circuit = QuantumCircuit(qr, cr)
circuit.x(0)
circuit.h(0)
circuit.x(1)
circuit_drawer(
circuit, filename=filename1, output="latex_source", cregbundle=True, initial_state=True
)
self.assertEqualToReference(filename1)
circuit_drawer(
circuit,
filename=filename2,
output="latex_source",
cregbundle=False,
initial_state=False,
)
self.assertEqualToReference(filename2)
def test_r_gates(self):
"""Test all R gates"""
filename = self._get_resource_path("test_latex_r_gates.tex")
qr = QuantumRegister(4, "q")
circuit = QuantumCircuit(qr)
circuit.r(3 * pi / 4, 3 * pi / 8, 0)
circuit.rx(pi / 2, 1)
circuit.ry(-pi / 2, 2)
circuit.rz(3 * pi / 4, 3)
circuit.rxx(pi / 2, 0, 1)
circuit.ryy(3 * pi / 4, 2, 3)
circuit.rzx(-pi / 2, 0, 1)
circuit.rzz(pi / 2, 2, 3)
circuit_drawer(circuit, filename=filename, output="latex_source")
self.assertEqualToReference(filename)
def test_cswap_rzz(self):
"""Test controlled swap and rzz gates"""
filename = self._get_resource_path("test_latex_cswap_rzz.tex")
qr = QuantumRegister(5, "q")
circuit = QuantumCircuit(qr)
circuit.x(0)
circuit.x(1)
circuit.cswap(0, 1, 2)
circuit.append(RZZGate(3 * pi / 4).control(3, ctrl_state="010"), [2, 1, 4, 3, 0])
circuit_drawer(circuit, filename=filename, output="latex_source")
self.assertEqualToReference(filename)
def test_ghz_to_gate(self):
"""Test controlled GHZ to_gate circuit"""
filename = self._get_resource_path("test_latex_ghz_to_gate.tex")
qr = QuantumRegister(5, "q")
circuit = QuantumCircuit(qr)
ghz_circuit = QuantumCircuit(3, name="Ctrl-GHZ Circuit")
ghz_circuit.h(0)
ghz_circuit.cx(0, 1)
ghz_circuit.cx(1, 2)
ghz = ghz_circuit.to_gate()
ccghz = ghz.control(2, ctrl_state="10")
circuit.append(ccghz, [4, 0, 1, 3, 2])
circuit_drawer(circuit, filename=filename, output="latex_source")
self.assertEqualToReference(filename)
def test_scale(self):
"""Tests scale
See: https://github.com/Qiskit/qiskit-terra/issues/4179"""
filename1 = self._get_resource_path("test_latex_scale_default.tex")
filename2 = self._get_resource_path("test_latex_scale_half.tex")
filename3 = self._get_resource_path("test_latex_scale_double.tex")
circuit = QuantumCircuit(5)
circuit.unitary(random_unitary(2**5), circuit.qubits)
circuit_drawer(circuit, filename=filename1, output="latex_source")
self.assertEqualToReference(filename1)
circuit_drawer(circuit, filename=filename2, output="latex_source", scale=0.5)
self.assertEqualToReference(filename2)
circuit_drawer(circuit, filename=filename3, output="latex_source", scale=2.0)
self.assertEqualToReference(filename3)
def test_pi_param_expr(self):
"""Text pi in circuit with parameter expression."""
filename = self._get_resource_path("test_latex_pi_param_expr.tex")
x, y = Parameter("x"), Parameter("y")
circuit = QuantumCircuit(1)
circuit.rx((pi - x) * (pi - y), 0)
circuit_drawer(circuit, filename=filename, output="latex_source")
self.assertEqualToReference(filename)
def test_partial_layout(self):
"""Tests partial_layout
See: https://github.com/Qiskit/qiskit-terra/issues/4757"""
filename = self._get_resource_path("test_latex_partial_layout.tex")
circuit = QuantumCircuit(3)
circuit.h(1)
transpiled = transpile(
circuit,
backend=FakeTenerife(),
optimization_level=0,
initial_layout=[1, 2, 0],
seed_transpiler=0,
)
circuit_drawer(transpiled, filename=filename, output="latex_source")
self.assertEqualToReference(filename)
def test_init_reset(self):
"""Test reset and initialize with 1 and 2 qubits"""
filename = self._get_resource_path("test_latex_init_reset.tex")
circuit = QuantumCircuit(2)
circuit.initialize([0, 1], 0)
circuit.reset(1)
circuit.initialize([0, 1, 0, 0], [0, 1])
circuit_drawer(circuit, filename=filename, output="latex_source")
self.assertEqualToReference(filename)
def test_iqx_colors(self):
"""Tests with iqx color scheme"""
filename = self._get_resource_path("test_latex_iqx.tex")
circuit = QuantumCircuit(7)
circuit.h(0)
circuit.x(0)
circuit.cx(0, 1)
circuit.ccx(0, 1, 2)
circuit.swap(0, 1)
circuit.cswap(0, 1, 2)
circuit.append(SwapGate().control(2), [0, 1, 2, 3])
circuit.dcx(0, 1)
circuit.append(DCXGate().control(1), [0, 1, 2])
circuit.append(DCXGate().control(2), [0, 1, 2, 3])
circuit.z(4)
circuit.s(4)
circuit.sdg(4)
circuit.t(4)
circuit.tdg(4)
circuit.p(pi / 2, 4)
circuit.p(pi / 2, 4)
circuit.cz(5, 6)
circuit.cp(pi / 2, 5, 6)
circuit.y(5)
circuit.rx(pi / 3, 5)
circuit.rzx(pi / 2, 5, 6)
circuit.u(pi / 2, pi / 2, pi / 2, 5)
circuit.barrier(5, 6)
circuit.reset(5)
circuit_drawer(circuit, filename=filename, output="latex_source")
self.assertEqualToReference(filename)
def test_reverse_bits(self):
"""Tests reverse_bits parameter"""
filename = self._get_resource_path("test_latex_reverse_bits.tex")
circuit = QuantumCircuit(3)
circuit.h(0)
circuit.cx(0, 1)
circuit.ccx(2, 1, 0)
circuit_drawer(circuit, filename=filename, output="latex_source", reverse_bits=True)
self.assertEqualToReference(filename)
def test_meas_condition(self):
"""Tests measure with a condition"""
filename = self._get_resource_path("test_latex_meas_condition.tex")
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(2, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.h(qr[0])
circuit.measure(qr[0], cr[0])
circuit.h(qr[1]).c_if(cr, 1)
circuit_drawer(circuit, filename=filename, output="latex_source")
self.assertEqualToReference(filename)
def test_inst_with_cbits(self):
"""Test custom instructions with classical bits"""
filename = self._get_resource_path("test_latex_inst_with_cbits.tex")
qinst = QuantumRegister(2, "q")
cinst = ClassicalRegister(2, "c")
inst = QuantumCircuit(qinst, cinst, name="instruction").to_instruction()
qr = QuantumRegister(4, "qr")
cr = ClassicalRegister(4, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.append(inst, [qr[1], qr[2]], [cr[2], cr[1]])
circuit_drawer(circuit, filename=filename, output="latex_source")
self.assertEqualToReference(filename)
def test_cif_single_bit(self):
"""Tests conditioning gates on single classical bit"""
filename = self._get_resource_path("test_latex_cif_single_bit.tex")
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(2, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.h(qr[0]).c_if(cr[1], 0)
circuit.x(qr[1]).c_if(cr[0], 1)
circuit_drawer(circuit, cregbundle=False, filename=filename, output="latex_source")
self.assertEqualToReference(filename)
def test_cif_single_bit_cregbundle(self):
"""Tests conditioning gates on single classical bit with cregbundle"""
filename = self._get_resource_path("test_latex_cif_single_bit_bundle.tex")
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(2, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.h(qr[0]).c_if(cr[1], 0)
circuit.x(qr[1]).c_if(cr[0], 1)
circuit_drawer(circuit, cregbundle=True, filename=filename, output="latex_source")
self.assertEqualToReference(filename)
def test_registerless_one_bit(self):
"""Text circuit with one-bit registers and registerless bits."""
filename = self._get_resource_path("test_latex_registerless_one_bit.tex")
qrx = QuantumRegister(2, "qrx")
qry = QuantumRegister(1, "qry")
crx = ClassicalRegister(2, "crx")
circuit = QuantumCircuit(qrx, [Qubit(), Qubit()], qry, [Clbit(), Clbit()], crx)
circuit_drawer(circuit, filename=filename, output="latex_source")
self.assertEqualToReference(filename)
def test_measures_with_conditions(self):
"""Test that a measure containing a condition displays"""
filename1 = self._get_resource_path("test_latex_meas_cond_false.tex")
filename2 = self._get_resource_path("test_latex_meas_cond_true.tex")
qr = QuantumRegister(2, "qr")
cr1 = ClassicalRegister(2, "cr1")
cr2 = ClassicalRegister(2, "cr2")
circuit = QuantumCircuit(qr, cr1, cr2)
circuit.h(0)
circuit.h(1)
circuit.measure(0, cr1[1])
circuit.measure(1, cr2[0]).c_if(cr1, 1)
circuit.h(0).c_if(cr2, 3)
circuit_drawer(circuit, cregbundle=False, filename=filename1, output="latex_source")
circuit_drawer(circuit, cregbundle=True, filename=filename2, output="latex_source")
self.assertEqualToReference(filename1)
self.assertEqualToReference(filename2)
def test_measures_with_conditions_with_bits(self):
"""Condition and measure on single bits cregbundle true"""
filename1 = self._get_resource_path("test_latex_meas_cond_bits_false.tex")
filename2 = self._get_resource_path("test_latex_meas_cond_bits_true.tex")
bits = [Qubit(), Qubit(), Clbit(), Clbit()]
cr = ClassicalRegister(2, "cr")
crx = ClassicalRegister(3, "cs")
circuit = QuantumCircuit(bits, cr, [Clbit()], crx)
circuit.x(0).c_if(crx[1], 0)
circuit.measure(0, bits[3])
circuit_drawer(circuit, cregbundle=False, filename=filename1, output="latex_source")
circuit_drawer(circuit, cregbundle=True, filename=filename2, output="latex_source")
self.assertEqualToReference(filename1)
self.assertEqualToReference(filename2)
def test_conditions_with_bits_reverse(self):
"""Test that gates with conditions and measures work with bits reversed"""
filename = self._get_resource_path("test_latex_cond_reverse.tex")
bits = [Qubit(), Qubit(), Clbit(), Clbit()]
cr = ClassicalRegister(2, "cr")
crx = ClassicalRegister(3, "cs")
circuit = QuantumCircuit(bits, cr, [Clbit()], crx)
circuit.x(0).c_if(bits[3], 0)
circuit_drawer(
circuit, cregbundle=False, reverse_bits=True, filename=filename, output="latex_source"
)
self.assertEqualToReference(filename)
def test_sidetext_with_condition(self):
"""Test that sidetext gates align properly with a condition"""
filename = self._get_resource_path("test_latex_sidetext_condition.tex")
qr = QuantumRegister(2, "q")
cr = ClassicalRegister(2, "c")
circuit = QuantumCircuit(qr, cr)
circuit.append(CPhaseGate(pi / 2), [qr[0], qr[1]]).c_if(cr[1], 1)
circuit_drawer(circuit, cregbundle=False, filename=filename, output="latex_source")
self.assertEqualToReference(filename)
def test_idle_wires_barrier(self):
"""Test that idle_wires False works with barrier"""
filename = self._get_resource_path("test_latex_idle_wires_barrier.tex")
circuit = QuantumCircuit(4, 4)
circuit.x(2)
circuit.barrier()
circuit_drawer(circuit, idle_wires=False, filename=filename, output="latex_source")
self.assertEqualToReference(filename)
def test_wire_order(self):
"""Test the wire_order option to latex drawer"""
filename = self._get_resource_path("test_latex_wire_order.tex")
qr = QuantumRegister(4, "q")
cr = ClassicalRegister(4, "c")
cr2 = ClassicalRegister(2, "ca")
circuit = QuantumCircuit(qr, cr, cr2)
circuit.h(0)
circuit.h(3)
circuit.x(1)
circuit.x(3).c_if(cr, 12)
circuit_drawer(
circuit,
cregbundle=False,
wire_order=[2, 1, 3, 0, 6, 8, 9, 5, 4, 7],
filename=filename,
output="latex_source",
)
self.assertEqualToReference(filename)
if __name__ == "__main__":
unittest.main(verbosity=2)
|
https://github.com/anpaschool/quantum-computing
|
anpaschool
|
%matplotlib inline
import numpy as np
import IPython
import matplotlib.pyplot as plt
from qiskit import QuantumCircuit,ClassicalRegister,QuantumRegister
from qiskit import BasicAer
from qiskit.tools.jupyter import *
from qiskit.visualization import *
import seaborn as sns
sns.set()
from helper import *
def circuit1():
qc = QuantumCircuit(2,2)
qc.h(0)
return qc
hqc = circuit1()
drawCircuit_2q(hqc)
hqc = circuit1()
writeState(hqc)
hqc = circuit1()
simCircuit(hqc)
hqc = circuit1()
blochSphere(hqc)
hqc = circuit1()
drawCircuit_2q(hqc)
I = np.eye(2,2)
H = 1/np.sqrt(2)*np.array([[1,1],[1,-1]])
U = np.kron(I,H)
print(U)
ket_00 = np.array([1,0,0,0])
np.dot(U,ket_00)
hqc = circuit1()
plotMatrix(hqc)
def circuit2():
qc = QuantumCircuit(2,2)
qc.h(0)
qc.h(1)
return qc
hqc = circuit2()
drawCircuit_2q(hqc)
hqc = circuit2()
writeState(hqc)
def getPhaseSeq():
phaseDic = []
qc0 = QuantumCircuit(2,2)
qc1 = QuantumCircuit(2,2)
qc1.h(0)
qc1.h(1)
for iqc in [qc0,qc1]:
phaseDic.append(getPhase(iqc))
return phaseDic
drawPhase(getPhaseSeq())
hqc = circuit2()
simCircuit(hqc)
hqc = circuit2()
drawCircuit_2q(hqc)
H = 1/np.sqrt(2)*np.array([[1,1],[1,-1]])
U = np.kron(H,H)
print(U)
ket = np.array([1,0,0,0])
np.dot(U,ket)
hqc = circuit2()
plotMatrix(hqc)
n = 3
q = QuantumRegister(n)
c = ClassicalRegister(n)
hqc3 = QuantumCircuit(q,c)
for k in range(3):
hqc3.h(q[k])
hqc3.barrier()
hqc3.measure(q,c)
style = {'backgroundcolor': 'lavender'}
hqc3.draw(output='mpl', style = style)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
q = QuantumRegister(1)
c = ClassicalRegister(1)
qc = QuantumCircuit(q, c)
qc.h(q)
qc.measure(q, c)
qc.draw(output='mpl', style={'backgroundcolor': '#EEEEEE'})
|
https://github.com/mathelatics/QGSS-2023-From-Theory-to-Implementations
|
mathelatics
|
import numpy as np
import pylab
from qiskit import Aer, IBMQ
from qiskit.aqua import QuantumInstance, aqua_globals
from qiskit.aqua.algorithms import VQE, NumPyMinimumEigensolver
from qiskit.aqua.components.optimizers import SPSA
from qiskit.circuit.library import TwoLocal
from qiskit.aqua.operators import WeightedPauliOperator
pauli_dict = {
'paulis': [{"coeff": {"imag": 0.0, "real": -1.052373245772859}, "label": "II"},
{"coeff": {"imag": 0.0, "real": 0.39793742484318045}, "label": "ZI"},
{"coeff": {"imag": 0.0, "real": -0.39793742484318045}, "label": "IZ"},
{"coeff": {"imag": 0.0, "real": -0.01128010425623538}, "label": "ZZ"},
{"coeff": {"imag": 0.0, "real": 0.18093119978423156}, "label": "XX"}
]
}
qubit_op = WeightedPauliOperator.from_dict(pauli_dict)
num_qubits = qubit_op.num_qubits
print('Number of qubits: {}'.format(num_qubits))
ee = NumPyMinimumEigensolver(qubit_op.copy())
result = ee.run()
ref = result.eigenvalue.real
print('Reference value: {}'.format(ref))
backend = Aer.get_backend('qasm_simulator')
quantum_instance = QuantumInstance(backend=backend, seed_simulator=167, seed_transpiler=167)
counts = []
values = []
def store_intermediate_result(eval_count, parameters, mean, std):
counts.append(eval_count)
values.append(mean)
aqua_globals.random_seed = 167
optimizer = SPSA(maxiter=200)
var_form = TwoLocal(num_qubits, 'ry', 'cz')
vqe = VQE(qubit_op, var_form, optimizer, callback=store_intermediate_result)
vqe_result = vqe.run(quantum_instance)
print('VQE on Aer qasm simulator (no noise): {}'.format(vqe_result.eigenvalue.real))
print('Delta from reference: {}'.format(vqe_result.eigenvalue.real-ref))
pylab.rcParams['figure.figsize'] = (12, 4)
pylab.plot(counts, values)
pylab.xlabel('Eval count')
pylab.ylabel('Energy')
pylab.title('Convergence with no noise')
import os
from qiskit.providers.aer.noise import NoiseModel
from qiskit.providers.ibmq.exceptions import IBMQAccountCredentialsNotFound
backend = Aer.get_backend('qasm_simulator')
counts1 = []
values1 = []
noise_model = None
try:
os.environ['QISKIT_IN_PARALLEL'] = 'TRUE'
provider = IBMQ.load_account()
device = provider.get_backend('ibmqx2')
coupling_map = device.configuration().coupling_map
noise_model = NoiseModel.from_backend(device)
basis_gates = noise_model.basis_gates
print(noise_model)
quantum_instance = QuantumInstance(backend=backend, seed_simulator=167, seed_transpiler=167,
noise_model=noise_model,)
def store_intermediate_result1(eval_count, parameters, mean, std):
counts1.append(eval_count)
values1.append(mean)
aqua_globals.random_seed = 167
optimizer = SPSA(maxiter=200)
var_form = TwoLocal(num_qubits, 'ry', 'cz')
vqe = VQE(qubit_op, var_form, optimizer, callback=store_intermediate_result1)
vqe_result1 = vqe.run(quantum_instance)
print('VQE on Aer qasm simulator (with noise): {}'.format(vqe_result1.eigenvalue.real))
print('Delta from reference: {}'.format(vqe_result1.eigenvalue.real-ref))
except IBMQAccountCredentialsNotFound as ex:
print(str(ex))
if counts1 or values1:
pylab.rcParams['figure.figsize'] = (12, 4)
pylab.plot(counts1, values1)
pylab.xlabel('Eval count')
pylab.ylabel('Energy')
pylab.title('Convergence with noise')
from qiskit.ignis.mitigation.measurement import CompleteMeasFitter
counts1 = []
values1 = []
if noise_model is not None:
quantum_instance = QuantumInstance(backend=backend, seed_simulator=167, seed_transpiler=167,
noise_model=noise_model,
measurement_error_mitigation_cls=CompleteMeasFitter,
cals_matrix_refresh_period=30)
def store_intermediate_result1(eval_count, parameters, mean, std):
counts1.append(eval_count)
values1.append(mean)
aqua_globals.random_seed = 167
optimizer = SPSA(maxiter=200)
var_form = TwoLocal(num_qubits, 'ry', 'cz')
vqe = VQE(qubit_op, var_form, optimizer, callback=store_intermediate_result1)
vqe_result1 = vqe.run(quantum_instance)
print('VQE on Aer qasm simulator (with noise and measurement error mitigation): {}'.format(vqe_result1.eigenvalue))
print('Delta from reference: {}'.format(vqe_result1.eigenvalue.real-ref))
if counts1 or values1:
pylab.rcParams['figure.figsize'] = (12, 4)
pylab.plot(counts1, values1)
pylab.xlabel('Eval count')
pylab.ylabel('Energy')
pylab.title('Convergence with noise, enabling measurement error mitigation')
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import IBMQ
IBMQ.load_account()
provider = IBMQ.get_provider(hub="ibm-q", group="open", project="main")
program_id = "qaoa"
qaoa_program = provider.runtime.program(program_id)
print(f"Program name: {qaoa_program.name}, Program id: {qaoa_program.program_id}")
print(qaoa_program.parameters())
import numpy as np
from qiskit.tools import job_monitor
from qiskit.opflow import PauliSumOp, Z, I
from qiskit.algorithms.optimizers import SPSA
# Define the cost operator to run.
op = (
(Z ^ Z ^ I ^ I ^ I)
- (I ^ I ^ Z ^ Z ^ I)
+ (I ^ I ^ Z ^ I ^ Z)
- (Z ^ I ^ Z ^ I ^ I)
- (I ^ Z ^ Z ^ I ^ I)
+ (I ^ Z ^ I ^ Z ^ I)
+ (I ^ I ^ I ^ Z ^ Z)
)
# SPSA helps deal with noisy environments.
optimizer = SPSA(maxiter=100)
# We will run a depth two QAOA.
reps = 2
# The initial point for the optimization, chosen at random.
initial_point = np.random.random(2 * reps)
# The backend that will run the programm.
options = {"backend_name": "ibmq_qasm_simulator"}
# The inputs of the program as described above.
runtime_inputs = {
"operator": op,
"reps": reps,
"optimizer": optimizer,
"initial_point": initial_point,
"shots": 2**13,
# Set to True when running on real backends to reduce circuit
# depth by leveraging swap strategies. If False the
# given optimization_level (default is 1) will be used.
"use_swap_strategies": False,
# Set to True when optimizing sparse problems.
"use_initial_mapping": False,
# Set to true when using echoed-cross-resonance hardware.
"use_pulse_efficient": False,
}
job = provider.runtime.run(
program_id=program_id,
options=options,
inputs=runtime_inputs,
)
job_monitor(job)
print(f"Job id: {job.job_id()}")
print(f"Job status: {job.status()}")
result = job.result()
from collections import defaultdict
def op_adj_mat(op: PauliSumOp) -> np.array:
"""Extract the adjacency matrix from the op."""
adj_mat = np.zeros((op.num_qubits, op.num_qubits))
for pauli, coeff in op.primitive.to_list():
idx = tuple([i for i, c in enumerate(pauli[::-1]) if c == "Z"]) # index of Z
adj_mat[idx[0], idx[1]], adj_mat[idx[1], idx[0]] = np.real(coeff), np.real(coeff)
return adj_mat
def get_cost(bit_str: str, adj_mat: np.array) -> float:
"""Return the cut value of the bit string."""
n, x = len(bit_str), [int(bit) for bit in bit_str[::-1]]
cost = 0
for i in range(n):
for j in range(n):
cost += adj_mat[i, j] * x[i] * (1 - x[j])
return cost
def get_cut_distribution(result) -> dict:
"""Extract the cut distribution from the result.
Returns:
A dict of cut value: probability.
"""
adj_mat = op_adj_mat(PauliSumOp.from_list(result["inputs"]["operator"]))
state_results = []
for bit_str, amp in result["eigenstate"].items():
state_results.append((bit_str, get_cost(bit_str, adj_mat), amp**2 * 100))
vals = defaultdict(int)
for res in state_results:
vals[res[1]] += res[2]
return dict(vals)
import matplotlib.pyplot as plt
cut_vals = get_cut_distribution(result)
fig, axs = plt.subplots(1, 2, figsize=(14, 5))
axs[0].plot(result["optimizer_history"]["energy"])
axs[1].bar(list(cut_vals.keys()), list(cut_vals.values()))
axs[0].set_xlabel("Energy evaluation number")
axs[0].set_ylabel("Energy")
axs[1].set_xlabel("Cut value")
axs[1].set_ylabel("Probability")
from qiskit_optimization.runtime import QAOAClient
from qiskit_optimization.algorithms import MinimumEigenOptimizer
from qiskit_optimization import QuadraticProgram
qubo = QuadraticProgram()
qubo.binary_var("x")
qubo.binary_var("y")
qubo.binary_var("z")
qubo.minimize(linear=[1, -2, 3], quadratic={("x", "y"): 1, ("x", "z"): -1, ("y", "z"): 2})
print(qubo.prettyprint())
qaoa_mes = QAOAClient(
provider=provider, backend=provider.get_backend("ibmq_qasm_simulator"), reps=2, alpha=0.75
)
qaoa = MinimumEigenOptimizer(qaoa_mes)
result = qaoa.solve(qubo)
print(result.prettyprint())
from qiskit.transpiler import PassManager
from qiskit.circuit.library.standard_gates.equivalence_library import (
StandardEquivalenceLibrary as std_eqlib,
)
from qiskit.transpiler.passes import (
Collect2qBlocks,
ConsolidateBlocks,
UnrollCustomDefinitions,
BasisTranslator,
Optimize1qGatesDecomposition,
)
from qiskit.transpiler.passes.calibration.builders import RZXCalibrationBuilderNoEcho
from qiskit.transpiler.passes.optimization.echo_rzx_weyl_decomposition import (
EchoRZXWeylDecomposition,
)
from qiskit.test.mock import FakeBelem
backend = FakeBelem()
inst_map = backend.defaults().instruction_schedule_map
channel_map = backend.configuration().qubit_channel_mapping
rzx_basis = ["rzx", "rz", "x", "sx"]
pulse_efficient = PassManager(
[
# Consolidate consecutive two-qubit operations.
Collect2qBlocks(),
ConsolidateBlocks(basis_gates=["rz", "sx", "x", "rxx"]),
# Rewrite circuit in terms of Weyl-decomposed echoed RZX gates.
EchoRZXWeylDecomposition(backend.defaults().instruction_schedule_map),
# Attach scaled CR pulse schedules to the RZX gates.
RZXCalibrationBuilderNoEcho(
instruction_schedule_map=inst_map, qubit_channel_mapping=channel_map
),
# Simplify single-qubit gates.
UnrollCustomDefinitions(std_eqlib, rzx_basis),
BasisTranslator(std_eqlib, rzx_basis),
Optimize1qGatesDecomposition(rzx_basis),
]
)
from qiskit import QuantumCircuit
circ = QuantumCircuit(3)
circ.h([0, 1, 2])
circ.rzx(0.5, 0, 1)
circ.swap(0, 1)
circ.cx(2, 1)
circ.rz(0.4, 1)
circ.cx(2, 1)
circ.rx(1.23, 2)
circ.cx(2, 1)
circ.draw("mpl")
pulse_efficient.run(circ).draw("mpl", fold=False)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# 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.
"""Qobj tests."""
import copy
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.compiler import assemble
from qiskit.qobj import (
QasmQobj,
PulseQobj,
QobjHeader,
PulseQobjInstruction,
PulseQobjExperiment,
PulseQobjConfig,
QobjMeasurementOption,
PulseLibraryItem,
QasmQobjInstruction,
QasmQobjExperiment,
QasmQobjConfig,
QasmExperimentCalibrations,
GateCalibration,
)
from qiskit.test import QiskitTestCase
class TestQASMQobj(QiskitTestCase):
"""Tests for QasmQobj."""
def setUp(self):
super().setUp()
self.valid_qobj = QasmQobj(
qobj_id="12345",
header=QobjHeader(),
config=QasmQobjConfig(shots=1024, memory_slots=2),
experiments=[
QasmQobjExperiment(
instructions=[
QasmQobjInstruction(name="u1", qubits=[1], params=[0.4]),
QasmQobjInstruction(name="u2", qubits=[1], params=[0.4, 0.2]),
]
)
],
)
self.valid_dict = {
"qobj_id": "12345",
"type": "QASM",
"schema_version": "1.2.0",
"header": {},
"config": {"memory_slots": 2, "shots": 1024},
"experiments": [
{
"instructions": [
{"name": "u1", "params": [0.4], "qubits": [1]},
{"name": "u2", "params": [0.4, 0.2], "qubits": [1]},
]
}
],
}
self.bad_qobj = copy.deepcopy(self.valid_qobj)
self.bad_qobj.experiments = []
def test_from_dict_per_class(self):
"""Test Qobj and its subclass representations given a dictionary."""
test_parameters = {
QasmQobj: (self.valid_qobj, self.valid_dict),
QasmQobjConfig: (
QasmQobjConfig(shots=1, memory_slots=2),
{"shots": 1, "memory_slots": 2},
),
QasmQobjExperiment: (
QasmQobjExperiment(
instructions=[QasmQobjInstruction(name="u1", qubits=[1], params=[0.4])]
),
{"instructions": [{"name": "u1", "qubits": [1], "params": [0.4]}]},
),
QasmQobjInstruction: (
QasmQobjInstruction(name="u1", qubits=[1], params=[0.4]),
{"name": "u1", "qubits": [1], "params": [0.4]},
),
}
for qobj_class, (qobj_item, expected_dict) in test_parameters.items():
with self.subTest(msg=str(qobj_class)):
self.assertEqual(qobj_item, qobj_class.from_dict(expected_dict))
def test_snapshot_instruction_to_dict(self):
"""Test snapshot instruction to dict."""
valid_qobj = QasmQobj(
qobj_id="12345",
header=QobjHeader(),
config=QasmQobjConfig(shots=1024, memory_slots=2),
experiments=[
QasmQobjExperiment(
instructions=[
QasmQobjInstruction(name="u1", qubits=[1], params=[0.4]),
QasmQobjInstruction(name="u2", qubits=[1], params=[0.4, 0.2]),
QasmQobjInstruction(
name="snapshot",
qubits=[1],
snapshot_type="statevector",
label="my_snap",
),
]
)
],
)
res = valid_qobj.to_dict()
expected_dict = {
"qobj_id": "12345",
"type": "QASM",
"schema_version": "1.3.0",
"header": {},
"config": {"memory_slots": 2, "shots": 1024},
"experiments": [
{
"instructions": [
{"name": "u1", "params": [0.4], "qubits": [1]},
{"name": "u2", "params": [0.4, 0.2], "qubits": [1]},
{
"name": "snapshot",
"qubits": [1],
"snapshot_type": "statevector",
"label": "my_snap",
},
],
"config": {},
"header": {},
}
],
}
self.assertEqual(expected_dict, res)
def test_snapshot_instruction_from_dict(self):
"""Test snapshot instruction from dict."""
expected_qobj = QasmQobj(
qobj_id="12345",
header=QobjHeader(),
config=QasmQobjConfig(shots=1024, memory_slots=2),
experiments=[
QasmQobjExperiment(
instructions=[
QasmQobjInstruction(name="u1", qubits=[1], params=[0.4]),
QasmQobjInstruction(name="u2", qubits=[1], params=[0.4, 0.2]),
QasmQobjInstruction(
name="snapshot",
qubits=[1],
snapshot_type="statevector",
label="my_snap",
),
]
)
],
)
qobj_dict = {
"qobj_id": "12345",
"type": "QASM",
"schema_version": "1.2.0",
"header": {},
"config": {"memory_slots": 2, "shots": 1024},
"experiments": [
{
"instructions": [
{"name": "u1", "params": [0.4], "qubits": [1]},
{"name": "u2", "params": [0.4, 0.2], "qubits": [1]},
{
"name": "snapshot",
"qubits": [1],
"snapshot_type": "statevector",
"label": "my_snap",
},
]
}
],
}
self.assertEqual(expected_qobj, QasmQobj.from_dict(qobj_dict))
def test_change_qobj_after_compile(self):
"""Test modifying Qobj parameters after compile."""
qr = QuantumRegister(3)
cr = ClassicalRegister(3)
qc1 = QuantumCircuit(qr, cr)
qc2 = QuantumCircuit(qr, cr)
qc1.h(qr[0])
qc1.cx(qr[0], qr[1])
qc1.cx(qr[0], qr[2])
qc2.h(qr)
qc1.measure(qr, cr)
qc2.measure(qr, cr)
circuits = [qc1, qc2]
qobj1 = assemble(circuits, shots=1024, seed=88)
qobj1.experiments[0].config.shots = 50
qobj1.experiments[1].config.shots = 1
self.assertTrue(qobj1.experiments[0].config.shots == 50)
self.assertTrue(qobj1.experiments[1].config.shots == 1)
self.assertTrue(qobj1.config.shots == 1024)
def test_gate_calibrations_to_dict(self):
"""Test gate calibrations to dict."""
pulse_library = [PulseLibraryItem(name="test", samples=[1j, 1j])]
valid_qobj = QasmQobj(
qobj_id="12345",
header=QobjHeader(),
config=QasmQobjConfig(shots=1024, memory_slots=2, pulse_library=pulse_library),
experiments=[
QasmQobjExperiment(
instructions=[QasmQobjInstruction(name="u1", qubits=[1], params=[0.4])],
config=QasmQobjConfig(
calibrations=QasmExperimentCalibrations(
gates=[
GateCalibration(
name="u1", qubits=[1], params=[0.4], instructions=[]
)
]
)
),
)
],
)
res = valid_qobj.to_dict()
expected_dict = {
"qobj_id": "12345",
"type": "QASM",
"schema_version": "1.3.0",
"header": {},
"config": {
"memory_slots": 2,
"shots": 1024,
"pulse_library": [{"name": "test", "samples": [1j, 1j]}],
},
"experiments": [
{
"instructions": [{"name": "u1", "params": [0.4], "qubits": [1]}],
"config": {
"calibrations": {
"gates": [
{"name": "u1", "qubits": [1], "params": [0.4], "instructions": []}
]
}
},
"header": {},
}
],
}
self.assertEqual(expected_dict, res)
class TestPulseQobj(QiskitTestCase):
"""Tests for PulseQobj."""
def setUp(self):
super().setUp()
self.valid_qobj = PulseQobj(
qobj_id="12345",
header=QobjHeader(),
config=PulseQobjConfig(
shots=1024,
memory_slots=2,
meas_level=1,
memory_slot_size=8192,
meas_return="avg",
pulse_library=[
PulseLibraryItem(name="pulse0", samples=[0.0 + 0.0j, 0.5 + 0.0j, 0.0 + 0.0j])
],
qubit_lo_freq=[4.9],
meas_lo_freq=[6.9],
rep_time=1000,
),
experiments=[
PulseQobjExperiment(
instructions=[
PulseQobjInstruction(name="pulse0", t0=0, ch="d0"),
PulseQobjInstruction(name="fc", t0=5, ch="d0", phase=1.57),
PulseQobjInstruction(name="fc", t0=5, ch="d0", phase=0.0),
PulseQobjInstruction(name="fc", t0=5, ch="d0", phase="P1"),
PulseQobjInstruction(name="setp", t0=10, ch="d0", phase=3.14),
PulseQobjInstruction(name="setf", t0=10, ch="d0", frequency=8.0),
PulseQobjInstruction(name="shiftf", t0=10, ch="d0", frequency=4.0),
PulseQobjInstruction(
name="acquire",
t0=15,
duration=5,
qubits=[0],
memory_slot=[0],
kernels=[
QobjMeasurementOption(
name="boxcar", params={"start_window": 0, "stop_window": 5}
)
],
),
]
)
],
)
self.valid_dict = {
"qobj_id": "12345",
"type": "PULSE",
"schema_version": "1.2.0",
"header": {},
"config": {
"memory_slots": 2,
"shots": 1024,
"meas_level": 1,
"memory_slot_size": 8192,
"meas_return": "avg",
"pulse_library": [{"name": "pulse0", "samples": [0, 0.5, 0]}],
"qubit_lo_freq": [4.9],
"meas_lo_freq": [6.9],
"rep_time": 1000,
},
"experiments": [
{
"instructions": [
{"name": "pulse0", "t0": 0, "ch": "d0"},
{"name": "fc", "t0": 5, "ch": "d0", "phase": 1.57},
{"name": "fc", "t0": 5, "ch": "d0", "phase": 0},
{"name": "fc", "t0": 5, "ch": "d0", "phase": "P1"},
{"name": "setp", "t0": 10, "ch": "d0", "phase": 3.14},
{"name": "setf", "t0": 10, "ch": "d0", "frequency": 8.0},
{"name": "shiftf", "t0": 10, "ch": "d0", "frequency": 4.0},
{
"name": "acquire",
"t0": 15,
"duration": 5,
"qubits": [0],
"memory_slot": [0],
"kernels": [
{"name": "boxcar", "params": {"start_window": 0, "stop_window": 5}}
],
},
]
}
],
}
def test_from_dict_per_class(self):
"""Test converting to Qobj and its subclass representations given a dictionary."""
test_parameters = {
PulseQobj: (self.valid_qobj, self.valid_dict),
PulseQobjConfig: (
PulseQobjConfig(
meas_level=1,
memory_slot_size=8192,
meas_return="avg",
pulse_library=[PulseLibraryItem(name="pulse0", samples=[0.1 + 0.0j])],
qubit_lo_freq=[4.9],
meas_lo_freq=[6.9],
rep_time=1000,
),
{
"meas_level": 1,
"memory_slot_size": 8192,
"meas_return": "avg",
"pulse_library": [{"name": "pulse0", "samples": [0.1 + 0j]}],
"qubit_lo_freq": [4.9],
"meas_lo_freq": [6.9],
"rep_time": 1000,
},
),
PulseLibraryItem: (
PulseLibraryItem(name="pulse0", samples=[0.1 + 0.0j]),
{"name": "pulse0", "samples": [0.1 + 0j]},
),
PulseQobjExperiment: (
PulseQobjExperiment(
instructions=[PulseQobjInstruction(name="pulse0", t0=0, ch="d0")]
),
{"instructions": [{"name": "pulse0", "t0": 0, "ch": "d0"}]},
),
PulseQobjInstruction: (
PulseQobjInstruction(name="pulse0", t0=0, ch="d0"),
{"name": "pulse0", "t0": 0, "ch": "d0"},
),
}
for qobj_class, (qobj_item, expected_dict) in test_parameters.items():
with self.subTest(msg=str(qobj_class)):
self.assertEqual(qobj_item, qobj_class.from_dict(expected_dict))
def test_to_dict_per_class(self):
"""Test converting from Qobj and its subclass representations given a dictionary."""
test_parameters = {
PulseQobj: (self.valid_qobj, self.valid_dict),
PulseQobjConfig: (
PulseQobjConfig(
meas_level=1,
memory_slot_size=8192,
meas_return="avg",
pulse_library=[PulseLibraryItem(name="pulse0", samples=[0.1 + 0.0j])],
qubit_lo_freq=[4.9],
meas_lo_freq=[6.9],
rep_time=1000,
),
{
"meas_level": 1,
"memory_slot_size": 8192,
"meas_return": "avg",
"pulse_library": [{"name": "pulse0", "samples": [0.1 + 0j]}],
"qubit_lo_freq": [4.9],
"meas_lo_freq": [6.9],
"rep_time": 1000,
},
),
PulseLibraryItem: (
PulseLibraryItem(name="pulse0", samples=[0.1 + 0.0j]),
{"name": "pulse0", "samples": [0.1 + 0j]},
),
PulseQobjExperiment: (
PulseQobjExperiment(
instructions=[PulseQobjInstruction(name="pulse0", t0=0, ch="d0")]
),
{"instructions": [{"name": "pulse0", "t0": 0, "ch": "d0"}]},
),
PulseQobjInstruction: (
PulseQobjInstruction(name="pulse0", t0=0, ch="d0"),
{"name": "pulse0", "t0": 0, "ch": "d0"},
),
}
for qobj_class, (qobj_item, expected_dict) in test_parameters.items():
with self.subTest(msg=str(qobj_class)):
self.assertEqual(qobj_item.to_dict(), expected_dict)
def _nop():
pass
|
https://github.com/Glebegor/Quantum-programming-algorithms
|
Glebegor
|
import numpy as np
import networkx as nx
import qiskit
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer, assemble
from qiskit.quantum_info import Statevector
from qiskit.aqua.algorithms import NumPyEigensolver
from qiskit.quantum_info import Pauli
from qiskit.aqua.operators import op_converter
from qiskit.aqua.operators import WeightedPauliOperator
from qiskit.visualization import plot_histogram
from qiskit.providers.aer.extensions.snapshot_statevector import *
from thirdParty.classical import rand_graph, classical, bitstring_to_path, calc_cost
from utils import mapeo_grafo
from collections import defaultdict
from operator import itemgetter
from scipy.optimize import minimize
import matplotlib.pyplot as plt
LAMBDA = 10
SEED = 10
SHOTS = 10000
# returns the bit index for an alpha and j
def bit(i_city, l_time, num_cities):
return i_city * num_cities + l_time
# e^(cZZ)
def append_zz_term(qc, q_i, q_j, gamma, constant_term):
qc.cx(q_i, q_j)
qc.rz(2*gamma*constant_term,q_j)
qc.cx(q_i, q_j)
# e^(cZ)
def append_z_term(qc, q_i, gamma, constant_term):
qc.rz(2*gamma*constant_term, q_i)
# e^(cX)
def append_x_term(qc,qi,beta):
qc.rx(-2*beta, qi)
def get_not_edge_in(G):
N = G.number_of_nodes()
not_edge = []
for i in range(N):
for j in range(N):
if i != j:
buffer_tupla = (i,j)
in_edges = False
for edge_i, edge_j in G.edges():
if ( buffer_tupla == (edge_i, edge_j) or buffer_tupla == (edge_j, edge_i)):
in_edges = True
if in_edges == False:
not_edge.append((i, j))
return not_edge
def get_classical_simplified_z_term(G, _lambda):
# recorrer la formula Z con datos grafo se va guardando en diccionario que acumula si coinciden los terminos
N = G.number_of_nodes()
E = G.edges()
# z term #
z_classic_term = [0] * N**2
# first term
for l in range(N):
for i in range(N):
z_il_index = bit(i, l, N)
z_classic_term[z_il_index] += -1 * _lambda
# second term
for l in range(N):
for j in range(N):
for i in range(N):
if i < j:
# z_il
z_il_index = bit(i, l, N)
z_classic_term[z_il_index] += _lambda / 2
# z_jl
z_jl_index = bit(j, l, N)
z_classic_term[z_jl_index] += _lambda / 2
# third term
for i in range(N):
for l in range(N):
for j in range(N):
if l < j:
# z_il
z_il_index = bit(i, l, N)
z_classic_term[z_il_index] += _lambda / 2
# z_ij
z_ij_index = bit(i, j, N)
z_classic_term[z_ij_index] += _lambda / 2
# fourth term
not_edge = get_not_edge_in(G) # include order tuples ej = (1,0), (0,1)
for edge in not_edge:
for l in range(N):
i = edge[0]
j = edge[1]
# z_il
z_il_index = bit(i, l, N)
z_classic_term[z_il_index] += _lambda / 4
# z_j(l+1)
l_plus = (l+1) % N
z_jlplus_index = bit(j, l_plus, N)
z_classic_term[z_jlplus_index] += _lambda / 4
# fifthy term
weights = nx.get_edge_attributes(G,'weight')
for edge_i, edge_j in G.edges():
weight_ij = weights.get((edge_i,edge_j))
weight_ji = weight_ij
for l in range(N):
# z_il
z_il_index = bit(edge_i, l, N)
z_classic_term[z_il_index] += weight_ij / 4
# z_jlplus
l_plus = (l+1) % N
z_jlplus_index = bit(edge_j, l_plus, N)
z_classic_term[z_jlplus_index] += weight_ij / 4
# add order term because G.edges() do not include order tuples #
# z_i'l
z_il_index = bit(edge_j, l, N)
z_classic_term[z_il_index] += weight_ji / 4
# z_j'lplus
l_plus = (l+1) % N
z_jlplus_index = bit(edge_i, l_plus, N)
z_classic_term[z_jlplus_index] += weight_ji / 4
return z_classic_term
def tsp_obj_2(x, G,_lambda):
# obtenemos el valor evaluado en f(x_1, x_2,... x_n)
not_edge = get_not_edge_in(G)
N = G.number_of_nodes()
tsp_cost=0
#Distancia
weights = nx.get_edge_attributes(G,'weight')
for edge_i, edge_j in G.edges():
weight_ij = weights.get((edge_i,edge_j))
weight_ji = weight_ij
for l in range(N):
# x_il
x_il_index = bit(edge_i, l, N)
# x_jlplus
l_plus = (l+1) % N
x_jlplus_index = bit(edge_j, l_plus, N)
tsp_cost+= int(x[x_il_index]) * int(x[x_jlplus_index]) * weight_ij
# add order term because G.edges() do not include order tuples #
# x_i'l
x_il_index = bit(edge_j, l, N)
# x_j'lplus
x_jlplus_index = bit(edge_i, l_plus, N)
tsp_cost += int(x[x_il_index]) * int(x[x_jlplus_index]) * weight_ji
#Constraint 1
for l in range(N):
penal1 = 1
for i in range(N):
x_il_index = bit(i, l, N)
penal1 -= int(x[x_il_index])
tsp_cost += _lambda * penal1**2
#Contstraint 2
for i in range(N):
penal2 = 1
for l in range(N):
x_il_index = bit(i, l, N)
penal2 -= int(x[x_il_index])
tsp_cost += _lambda*penal2**2
#Constraint 3
for edge in not_edge:
for l in range(N):
i = edge[0]
j = edge[1]
# x_il
x_il_index = bit(i, l, N)
# x_j(l+1)
l_plus = (l+1) % N
x_jlplus_index = bit(j, l_plus, N)
tsp_cost += int(x[x_il_index]) * int(x[x_jlplus_index]) * _lambda
return tsp_cost
def get_classical_simplified_zz_term(G, _lambda):
# recorrer la formula Z con datos grafo se va guardando en diccionario que acumula si coinciden los terminos
N = G.number_of_nodes()
E = G.edges()
# zz term #
zz_classic_term = [[0] * N**2 for i in range(N**2) ]
# first term
for l in range(N):
for j in range(N):
for i in range(N):
if i < j:
# z_il
z_il_index = bit(i, l, N)
# z_jl
z_jl_index = bit(j, l, N)
zz_classic_term[z_il_index][z_jl_index] += _lambda / 2
# second term
for i in range(N):
for l in range(N):
for j in range(N):
if l < j:
# z_il
z_il_index = bit(i, l, N)
# z_ij
z_ij_index = bit(i, j, N)
zz_classic_term[z_il_index][z_ij_index] += _lambda / 2
# third term
not_edge = get_not_edge_in(G)
for edge in not_edge:
for l in range(N):
i = edge[0]
j = edge[1]
# z_il
z_il_index = bit(i, l, N)
# z_j(l+1)
l_plus = (l+1) % N
z_jlplus_index = bit(j, l_plus, N)
zz_classic_term[z_il_index][z_jlplus_index] += _lambda / 4
# fourth term
weights = nx.get_edge_attributes(G,'weight')
for edge_i, edge_j in G.edges():
weight_ij = weights.get((edge_i,edge_j))
weight_ji = weight_ij
for l in range(N):
# z_il
z_il_index = bit(edge_i, l, N)
# z_jlplus
l_plus = (l+1) % N
z_jlplus_index = bit(edge_j, l_plus, N)
zz_classic_term[z_il_index][z_jlplus_index] += weight_ij / 4
# add order term because G.edges() do not include order tuples #
# z_i'l
z_il_index = bit(edge_j, l, N)
# z_j'lplus
l_plus = (l+1) % N
z_jlplus_index = bit(edge_i, l_plus, N)
zz_classic_term[z_il_index][z_jlplus_index] += weight_ji / 4
return zz_classic_term
def get_classical_simplified_hamiltonian(G, _lambda):
# z term #
z_classic_term = get_classical_simplified_z_term(G, _lambda)
# zz term #
zz_classic_term = get_classical_simplified_zz_term(G, _lambda)
return z_classic_term, zz_classic_term
def get_cost_circuit(G, gamma, _lambda):
N = G.number_of_nodes()
N_square = N**2
qc = QuantumCircuit(N_square,N_square)
z_classic_term, zz_classic_term = get_classical_simplified_hamiltonian(G, _lambda)
# z term
for i in range(N_square):
if z_classic_term[i] != 0:
append_z_term(qc, i, gamma, z_classic_term[i])
# zz term
for i in range(N_square):
for j in range(N_square):
if zz_classic_term[i][j] != 0:
append_zz_term(qc, i, j, gamma, zz_classic_term[i][j])
return qc
def get_mixer_operator(G,beta):
N = G.number_of_nodes()
qc = QuantumCircuit(N**2,N**2)
for n in range(N**2):
append_x_term(qc, n, beta)
return qc
def get_QAOA_circuit(G, beta, gamma, _lambda):
assert(len(beta)==len(gamma))
N = G.number_of_nodes()
qc = QuantumCircuit(N**2,N**2)
# init min mix state
qc.h(range(N**2))
p = len(beta)
for i in range(p):
qc = qc.compose(get_cost_circuit(G, gamma[i], _lambda))
qc = qc.compose(get_mixer_operator(G, beta[i]))
qc.barrier(range(N**2))
qc.snapshot_statevector("final_state")
qc.measure(range(N**2),range(N**2))
return qc
def invert_counts(counts):
return {k[::-1] :v for k,v in counts.items()}
# Sample expectation value
def compute_tsp_energy_2(counts, G):
energy = 0
get_counts = 0
total_counts = 0
for meas, meas_count in counts.items():
obj_for_meas = tsp_obj_2(meas, G, LAMBDA)
energy += obj_for_meas*meas_count
total_counts += meas_count
mean = energy/total_counts
return mean
def get_black_box_objective_2(G,p):
backend = Aer.get_backend('qasm_simulator')
sim = Aer.get_backend('aer_simulator')
# function f costo
def f(theta):
beta = theta[:p]
gamma = theta[p:]
# Anzats
qc = get_QAOA_circuit(G, beta, gamma, LAMBDA)
result = execute(qc, backend, seed_simulator=SEED, shots= SHOTS).result()
final_state_vector = result.data()["snapshots"]["statevector"]["final_state"][0]
state_vector = Statevector(final_state_vector)
probabilities = state_vector.probabilities()
probabilities_states = invert_counts(state_vector.probabilities_dict())
expected_value = 0
for state,probability in probabilities_states.items():
cost = tsp_obj_2(state, G, LAMBDA)
expected_value += cost*probability
counts = result.get_counts()
mean = compute_tsp_energy_2(invert_counts(counts),G)
return mean
return f
def crear_grafo(cantidad_ciudades):
pesos, conexiones = None, None
mejor_camino = None
while not mejor_camino:
pesos, conexiones = rand_graph(cantidad_ciudades)
mejor_costo, mejor_camino = classical(pesos, conexiones, loop=False)
G = mapeo_grafo(conexiones, pesos)
return G, mejor_costo, mejor_camino
def run_QAOA(p,ciudades, grafo):
if grafo == None:
G, mejor_costo, mejor_camino = crear_grafo(ciudades)
print("Mejor Costo")
print(mejor_costo)
print("Mejor Camino")
print(mejor_camino)
print("Bordes del grafo")
print(G.edges())
print("Nodos")
print(G.nodes())
print("Pesos")
labels = nx.get_edge_attributes(G,'weight')
print(labels)
else:
G = grafo
intial_random = []
# beta, mixer Hammiltonian
for i in range(p):
intial_random.append(np.random.uniform(0,np.pi))
# gamma, cost Hammiltonian
for i in range(p):
intial_random.append(np.random.uniform(0,2*np.pi))
init_point = np.array(intial_random)
obj = get_black_box_objective_2(G,p)
res_sample = minimize(obj, init_point,method="COBYLA",options={"maxiter":2500,"disp":True})
print(res_sample)
if __name__ == '__main__':
# Run QAOA parametros: profundidad p, numero d ciudades,
run_QAOA(5, 3, None)
|
https://github.com/minnukota381/Quantum-Computing-Qiskit
|
minnukota381
|
from qiskit import *
from qiskit.visualization import plot_bloch_multivector, visualize_transition, plot_histogram
# Create a quantum circuit with a single qubit
qc = QuantumCircuit(1)
qc.x(0)
qc.h(0)
qc.z(0)
qc.h(0)
# qc.draw()
qc.draw('mpl')
backend = Aer.get_backend('statevector_simulator')
out = execute(qc,backend).result().get_statevector()
plot_bloch_multivector(out)
visualize_transition(qc)
out = execute(qc,backend).result()
counts = out.get_counts()
plot_histogram(counts)
|
https://github.com/ElePT/qiskit-algorithms-test
|
ElePT
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2021, 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.
"""The Iterative Quantum Phase Estimation Algorithm."""
from __future__ import annotations
import numpy
import qiskit
from qiskit.circuit import QuantumCircuit, QuantumRegister
from qiskit.circuit.classicalregister import ClassicalRegister
from qiskit.providers import Backend
from qiskit.utils import QuantumInstance
from qiskit.utils.deprecation import deprecate_arg
from qiskit_algorithms.exceptions import AlgorithmError
from .phase_estimator import PhaseEstimator
from .phase_estimator import PhaseEstimatorResult
from ...primitives import BaseSampler
class IterativePhaseEstimation(PhaseEstimator):
"""Run the Iterative quantum phase estimation (QPE) algorithm.
Given a unitary circuit and a circuit preparing an eigenstate, return the phase of the
eigenvalue as a number in :math:`[0,1)` using the iterative phase estimation algorithm.
[1]: Dobsicek et al. (2006), Arbitrary accuracy iterative phase estimation algorithm as a two
qubit benchmark, `arxiv/quant-ph/0610214 <https://arxiv.org/abs/quant-ph/0610214>`_
"""
@deprecate_arg(
"quantum_instance",
additional_msg=(
"Instead, use the ``sampler`` argument. See https://qisk.it/algo_migration for a "
"migration guide."
),
since="0.24.0",
)
def __init__(
self,
num_iterations: int,
quantum_instance: QuantumInstance | Backend | None = None,
sampler: BaseSampler | None = None,
) -> None:
r"""
Args:
num_iterations: The number of iterations (rounds) of the phase estimation to run.
quantum_instance: Deprecated: The quantum instance on which the
circuit will be run.
sampler: The sampler primitive on which the circuit will be sampled.
Raises:
ValueError: if num_iterations is not greater than zero.
AlgorithmError: If neither sampler nor quantum instance is provided.
"""
if sampler is None and quantum_instance is None:
raise AlgorithmError(
"Neither a sampler nor a quantum instance was provided. Please provide one of them."
)
if isinstance(quantum_instance, Backend):
quantum_instance = QuantumInstance(quantum_instance)
self._quantum_instance = quantum_instance
if num_iterations <= 0:
raise ValueError("`num_iterations` must be greater than zero.")
self._num_iterations = num_iterations
self._sampler = sampler
def construct_circuit(
self,
unitary: QuantumCircuit,
state_preparation: QuantumCircuit,
k: int,
omega: float = 0.0,
measurement: bool = False,
) -> QuantumCircuit:
"""Construct the kth iteration Quantum Phase Estimation circuit.
For details of parameters, see Fig. 2 in https://arxiv.org/pdf/quant-ph/0610214.pdf.
Args:
unitary: The circuit representing the unitary operator whose eigenvalue (via phase)
will be measured.
state_preparation: The circuit that prepares the state whose eigenphase will be
measured. If this parameter is omitted, no preparation circuit
will be run and input state will be the all-zero state in the
computational basis.
k: the iteration idx.
omega: the feedback angle.
measurement: Boolean flag to indicate if measurement should
be included in the circuit.
Returns:
QuantumCircuit: the quantum circuit per iteration
"""
k = self._num_iterations if k is None else k
# The auxiliary (phase measurement) qubit
phase_register = QuantumRegister(1, name="a")
eigenstate_register = QuantumRegister(unitary.num_qubits, name="q")
qc = QuantumCircuit(eigenstate_register)
qc.add_register(phase_register)
if isinstance(state_preparation, QuantumCircuit):
qc.append(state_preparation, eigenstate_register)
elif state_preparation is not None:
qc += state_preparation.construct_circuit("circuit", eigenstate_register)
# hadamard on phase_register[0]
qc.h(phase_register[0])
# controlled-U
# TODO: We may want to allow flexibility in how the power is computed
# For example, it may be desirable to compute the power via Trotterization, if
# we are doing Trotterization anyway.
unitary_power = unitary.power(2 ** (k - 1)).control()
qc = qc.compose(unitary_power, [unitary.num_qubits] + list(range(0, unitary.num_qubits)))
qc.p(omega, phase_register[0])
# hadamard on phase_register[0]
qc.h(phase_register[0])
if measurement:
c = ClassicalRegister(1, name="c")
qc.add_register(c)
qc.measure(phase_register, c)
return qc
def _estimate_phase_iteratively(self, unitary, state_preparation):
"""
Main loop of iterative phase estimation.
"""
omega_coef = 0
# k runs from the number of iterations back to 1
for k in range(self._num_iterations, 0, -1):
omega_coef /= 2
if self._sampler is not None:
qc = self.construct_circuit(
unitary, state_preparation, k, -2 * numpy.pi * omega_coef, True
)
try:
sampler_job = self._sampler.run([qc])
result = sampler_job.result().quasi_dists[0]
except Exception as exc:
raise AlgorithmError("The primitive job failed!") from exc
x = 1 if result.get(1, 0) > result.get(0, 0) else 0
elif self._quantum_instance.is_statevector:
qc = self.construct_circuit(
unitary, state_preparation, k, -2 * numpy.pi * omega_coef, measurement=False
)
result = self._quantum_instance.execute(qc)
complete_state_vec = result.get_statevector(qc)
ancilla_density_mat = qiskit.quantum_info.partial_trace(
complete_state_vec, range(unitary.num_qubits)
)
ancilla_density_mat_diag = numpy.diag(ancilla_density_mat)
max_amplitude = max(
ancilla_density_mat_diag.min(), ancilla_density_mat_diag.max(), key=abs
)
x = numpy.where(ancilla_density_mat_diag == max_amplitude)[0][0]
else:
qc = self.construct_circuit(
unitary, state_preparation, k, -2 * numpy.pi * omega_coef, measurement=True
)
measurements = self._quantum_instance.execute(qc).get_counts(qc)
x = 1 if measurements.get("1", 0) > measurements.get("0", 0) else 0
omega_coef = omega_coef + x / 2
return omega_coef
# pylint: disable=signature-differs
def estimate(
self, unitary: QuantumCircuit, state_preparation: QuantumCircuit
) -> "IterativePhaseEstimationResult":
"""
Estimate the eigenphase of the input unitary and initial-state pair.
Args:
unitary: The circuit representing the unitary operator whose eigenvalue (via phase)
will be measured.
state_preparation: The circuit that prepares the state whose eigenphase will be
measured. If this parameter is omitted, no preparation circuit
will be run and input state will be the all-zero state in the
computational basis.
Returns:
Estimated phase in an IterativePhaseEstimationResult object.
Raises:
AlgorithmError: If neither sampler nor quantum instance is provided.
"""
phase = self._estimate_phase_iteratively(unitary, state_preparation)
return IterativePhaseEstimationResult(self._num_iterations, phase)
class IterativePhaseEstimationResult(PhaseEstimatorResult):
"""Phase Estimation Result."""
def __init__(self, num_iterations: int, phase: float) -> None:
"""
Args:
num_iterations: number of iterations used in the phase estimation.
phase: the estimated phase.
"""
self._num_iterations = num_iterations
self._phase = phase
@property
def phase(self) -> float:
r"""Return the estimated phase as a number in :math:`[0.0, 1.0)`.
1.0 corresponds to a phase of :math:`2\pi`. It is assumed that the input vector is an
eigenvector of the unitary so that the peak of the probability density occurs at the bit
string that most closely approximates the true phase.
"""
return self._phase
@property
def num_iterations(self) -> int:
r"""Return the number of iterations used in the estimation algorithm."""
return self._num_iterations
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
import numpy as np
import qiskit
from qiskit import QuantumCircuit
import matplotlib.pyplot as plt
from qiskit.circuit import QuantumCircuit, Parameter
import warnings
warnings.filterwarnings('ignore')
theta = Parameter("ΞΈ")
phi = Parameter("Ο")
lamb = Parameter("Ξ»")
def sampleCircuitA(layer=1, qubits=4):
circuit = QuantumCircuit(qubits)
for i in range(layer):
for i in range(qubits - 1):
circuit.cx(i, i + 1)
circuit.cx(qubits - 1, 0)
for i in range(qubits - 1):
circuit.cx(i, i + 1)
circuit.cx(qubits - 1, 0)
circuit.barrier()
for i in range(qubits):
circuit.u3(theta, phi, lamb, i)
return circuit
circuitA = sampleCircuitA(qubits=4)
circuitA.draw(output='mpl')
def sampleCircuitB1(layer=1, qubits=4):
circuit = QuantumCircuit(qubits)
for i in range(qubits):
circuit.u1(theta, i)
for i in range(layer):
for j in range(qubits - 1):
circuit.cz(j, j + 1)
circuit.cz(qubits - 1, 0)
circuit.barrier()
for j in range(qubits):
circuit.u1(theta, j)
return circuit
def sampleCircuitB2(layer=1, qubits=4):
circuit = QuantumCircuit(qubits)
for i in range(qubits):
circuit.u2(phi, lamb, i)
for i in range(layer):
for j in range(qubits - 1):
circuit.cz(j, j + 1)
circuit.cz(qubits - 1, 0)
circuit.barrier()
for j in range(qubits):
circuit.u2(phi, lamb, j)
return circuit
def sampleCircuitB3(layer=1, qubits=4):
circuit = QuantumCircuit(qubits)
for i in range(qubits):
circuit.u3(theta, phi, lamb, i)
for i in range(layer):
for j in range(qubits - 1):
circuit.cz(j, j + 1)
circuit.cz(qubits - 1, 0)
circuit.barrier()
for j in range(qubits):
circuit.u3(theta, phi, lamb, j)
return circuit
circuitB1 = sampleCircuitB1(qubits=4)
circuitB1.draw(output='mpl')
circuitB2 = sampleCircuitB2(qubits=4)
circuitB2.draw(output='mpl')
circuitB3 = sampleCircuitB3(qubits=4)
circuitB3.draw(output='mpl')
def sampleCircuitC(layer=1, qubits=4):
circuit = QuantumCircuit(qubits)
for i in range(layer):
for j in range(qubits):
circuit.ry(theta, j)
circuit.crx(theta, qubits - 1, 0)
for j in range(qubits - 1, 0, -1):
circuit.crx(theta, j - 1, j)
circuit.barrier()
for j in range(qubits):
circuit.ry(theta, j)
circuit.crx(theta, 3, 2)
circuit.crx(theta, 0, 3)
circuit.crx(theta, 1, 0)
circuit.crx(theta, 2, 1)
return circuit
circuitC = sampleCircuitC(qubits=4)
circuitC.draw(output='mpl')
def sampleCircuitD(layer=1, qubits=4):
circuit = QuantumCircuit(qubits)
for i in range(layer):
for j in range(qubits):
circuit.rx(theta, j)
circuit.rz(theta, j)
for j in range(qubits - 1, -1, -1):
for k in range(qubits - 1, -1, -1):
if j != k:
circuit.crx(theta, j, k)
circuit.barrier()
for j in range(qubits):
circuit.rx(theta, j)
circuit.rz(theta, j)
return circuit
circuitD = sampleCircuitD(qubits=4)
circuitD.draw(output='mpl')
def sampleCircuitE(layer=1, qubits=4):
circuit = QuantumCircuit(qubits)
for i in range(layer):
for j in range(qubits):
circuit.rx(theta, j)
circuit.rz(theta, j)
for j in range(1, qubits, 2):
circuit.crx(theta, j, j - 1)
for j in range(qubits):
circuit.rx(theta, j)
circuit.rz(theta, j)
for j in range(2, qubits, 2):
circuit.crx(theta, j, j - 1)
return circuit
circuitE = sampleCircuitE(qubits=4)
circuitE.draw(output='mpl')
def sampleCircuitF(layer=1, qubits=4):
circuit = QuantumCircuit(qubits)
for i in range(layer):
for j in range(qubits):
circuit.rx(theta, j)
circuit.rz(theta, j)
circuit.crx(theta, qubits - 1, 0)
for j in range(qubits - 1, 0, -1):
circuit.crx(theta, j - 1, j)
return circuit
circuitF = sampleCircuitF(qubits=4)
circuitF.draw(output='mpl')
def sampleEncoding(qubits):
circuit = QuantumCircuit(qubits)
for i in range(qubits):
circuit.h(i)
circuit.ry(theta, i)
return circuit
circuit = sampleEncoding(4)
circuit.draw(output='mpl')
# demo:
circuit = sampleEncoding(5).compose(sampleCircuitB3(layer=2, qubits=5))
circuit.draw(output='mpl')
|
https://github.com/UST-QuAntiL/nisq-analyzer-content
|
UST-QuAntiL
|
from qiskit import QuantumCircuit
# n = 3 # number of qubits used to represent s
# s = '011' # the hidden binary string
# https://qiskit.org/textbook/ch-algorithms/bernstein-vazirani.html
def get_circuit(**kwargs):
n = kwargs["number_of_qubits"]
s = kwargs["s"]
# We need a circuit with n qubits, plus one ancilla qubit
# Also need n classical bits to write the output to
bv_circuit = QuantumCircuit(n + 1, n)
# put ancilla in state |->
bv_circuit.h(n)
bv_circuit.z(n)
# Apply Hadamard gates before querying the oracle
for i in range(n):
bv_circuit.h(i)
# Apply barrier
bv_circuit.barrier()
# Apply the inner-product oracle
s = s[::-1] # reverse s to fit qiskit's qubit ordering
for q in range(n):
if s[q] == '0':
bv_circuit.iden(q)
else:
bv_circuit.cx(q, n)
# Apply barrier
bv_circuit.barrier()
# Apply Hadamard gates after querying the oracle
for i in range(n):
bv_circuit.h(i)
# Measurement
for i in range(n):
bv_circuit.measure(i, i)
return bv_circuit
|
https://github.com/matteoacrossi/oqs-jupyterbook
|
matteoacrossi
|
import numpy as np
from scipy.optimize import fsolve, differential_evolution
# Main qiskit imports
from qiskit import QuantumRegister, ClassicalRegister
from qiskit import QuantumCircuit, execute, Aer, IBMQ
# Tomography
from qiskit.ignis.verification.tomography import state_tomography_circuits
from qiskit.ignis.verification.tomography import StateTomographyFitter
# Plots
import matplotlib.pyplot as plt
# We have an analytical solution of the system of equations
def theta_from_p(p):
""" Returns the angles [theta_1, theta_2, theta_3] that implement the Pauli channel with
probabilities p = [p_1, p_2, p_3]"""
p = np.asarray(p, dtype=complex)
c = [np.sqrt(1 - np.sqrt(-4*p[0]**2 + (1 - 2*p[2])**2 + 8*p[0]*(p[2] + np.sqrt(-(p[2]*(-1 + 2*p[0] + p[2]))))))/np.sqrt(2),
np.sqrt(8*p[0]**3 - 4*p[0]**2*(-1 - 6*p[2] + np.sqrt(-4*p[0]**2 + (1 - 2*p[2])**2 + 8*p[0]*(p[2] + np.sqrt(-(p[2]*(-1 + 2*p[0] + p[2])))))) +
(1 - 2*p[2])**2*(-1 + 2*p[2] + np.sqrt(-4*p[0]**2 + (1 - 2*p[2])**2 + 8*p[0]*(p[2] + np.sqrt(-(p[2]*(-1 + 2*p[0] + p[2])))))) -
2*p[0]*(1 + 4*(p[2] - 3*p[2]**2 - p[2]*np.sqrt(-4*p[0]**2 + (1 - 2*p[2])**2 + 8*p[0]*(p[2] + np.sqrt(-(p[2]*(-1 + 2*p[0] + p[2]))))) +
np.sqrt(-(p[2]*(-1 + 2*p[0] + p[2])))*np.sqrt(-4*p[0]**2 + (1 - 2*p[2])**2 + 8*p[0]*(p[2] + np.sqrt(-(p[2]*(-1 + 2*p[0] + p[2]))))))))/
(np.sqrt(2)*np.sqrt((-1 + 2*p[0] + 2*p[2])*(4*p[0]**2 + (1 - 2*p[2])**2 + p[0]*(4 + 8*p[2])))),
np.sqrt((8*p[0]**3 - 4*p[0]**2*(-1 - 6*p[2] + np.sqrt(-4*p[0]**2 + (1 - 2*p[2])**2 + 8*p[0]*(p[2] + np.sqrt(-(p[2]*(-1 + 2*p[0] + p[2])))))) +
(1 - 2*p[2])**2*(-1 + 2*p[2] + np.sqrt(-4*p[0]**2 + (1 - 2*p[2])**2 + 8*p[0]*(p[2] + np.sqrt(-(p[2]*(-1 + 2*p[0] + p[2])))))) -
2*p[0]*(1 + 4*(p[2] - 3*p[2]**2 - p[2]*np.sqrt(-4*p[0]**2 + (1 - 2*p[2])**2 + 8*p[0]*(p[2] + np.sqrt(-(p[2]*(-1 + 2*p[0] + p[2]))))) +
np.sqrt(-(p[2]*(-1 + 2*p[0] + p[2])))*np.sqrt(-4*p[0]**2 + (1 - 2*p[2])**2 + 8*p[0]*(p[2] + np.sqrt(-(p[2]*(-1 + 2*p[0] + p[2]))))))))/
(4*p[0]**2 + (1 - 2*p[2])**2 + p[0]*(4 + 8*p[2])))/np.sqrt(-2 + 4*p[0] + 4*p[2])]
theta = 2*np.arccos(np.real(c))
return theta
def pauli_channel(q, p, system, pauli_ancillae):
"""
Apply the Pauli channel to system with probabilities p
Args:
q (QuantumRegister): the quantum register for the circuit
system (int): index of the system qubit
pauli_ancillae (list): list of indices of the ancillary qubits
p (list): list of probabilities [p_1, p_2, p_3] for the Pauli channel
Returns:
A QuantumCircuit implementing the Pauli channel
"""
theta = theta_from_p(p)
dc = QuantumCircuit(q)
dc.ry(theta[0], q[pauli_ancillae[0]])
dc.cx(q[pauli_ancillae[0]], q[pauli_ancillae[1]])
dc.ry(theta[1], q[pauli_ancillae[0]])
dc.ry(theta[2], q[pauli_ancillae[1]])
dc.cx(q[pauli_ancillae[0]], q[system])
dc.cy(q[pauli_ancillae[1]], q[system])
return dc
from qiskit.quantum_info import entropy, partial_trace
def conditional_entropy(state, qubit_a, qubit_b):
"""Conditional entropy S(A|B) = S(AB) - S(B)
Args:
state: a vector or density operator
qubit_a: 0-based index of the qubit A
qubit_b: 0-based index of the qubit B
Returns:
int: the conditional entropy
"""
return entropy(state) - entropy(partial_trace(state, [qubit_b]))
def extractable_work(state, system_qubit, memory_qubit, n=1):
"""Extractable work from a two-qubit state
=
Cfr. Eq. (3-4) Bylicka et al., Sci. Rep. 6, 27989 (2016)
Args:
qubit_a: 0-based index of the system qubit S
qubit_b: 0-based index of the memory qubit M
"""
return (n - conditional_entropy(state, system_qubit, memory_qubit)/np.log(2))
def p_enm(t, eta=1., omega=1.):
p = [1/4 * (1 - np.exp(-2 * t *eta)),
1/4 * (1 - np.exp(-2 * t *eta)),
1/4 * (1 + np.exp(-2 * t * eta) - 2 *np.exp(-t *eta) * np.cosh(t *omega))]
return p
def p_ncp(t, eta=1., omega=1.):
p = [1/4 * (1 - np.exp(-2 * t *eta)),
1/4 * (1 - np.exp(-2 * t *eta)),
1/4 * (1 + np.exp(-2 * t * eta) - 2 *np.exp(-t *eta) * np.cos(t *omega))]
return p
# Here are the parameters
t_values = np.linspace(0, 3, 11)
# Parameters
params_ncp = {'eta': 0.1, 'omega': 2.0}
params_enm = {'eta': 1.0, 'omega': .5}
# And the qubit assignments
SHOTS = 8192
q = QuantumRegister(5, name='q')
c = ClassicalRegister(2, name='c')
system = 2
ancilla = 4
pauli_ancillae = [0, 1]
# Prepare the two qubits 0 and 2 in a psi- state
prepare_two_qubit = QuantumCircuit(q)
prepare_two_qubit.x(q[ancilla])
prepare_two_qubit.x(q[system])
prepare_two_qubit.h(q[ancilla])
prepare_two_qubit.cx(q[ancilla], q[system])
prepare_two_qubit.barrier()
wext_ncp = []
for t in t_values:
circ = prepare_two_qubit + pauli_channel(q, p_ncp(t, **params_ncp), system, pauli_ancillae)
tomo_circuits_ncp = state_tomography_circuits(circ, [q[ancilla], q[system]])
job = execute(tomo_circuits_ncp, Aer.get_backend('qasm_simulator'), shots=SHOTS)
result = job.result()
tomo_fitter = StateTomographyFitter(result, tomo_circuits_ncp)
rho = tomo_fitter.fit()
wext_ncp.append(extractable_work(rho, 1, 0))
wext_enm = []
for t in t_values:
circ = prepare_two_qubit + pauli_channel(q, p_enm(t, **params_enm), system, pauli_ancillae)
tomo_circuits_enm = state_tomography_circuits(circ, [q[ancilla], q[system]])
job = execute(tomo_circuits_enm, Aer.get_backend('qasm_simulator'), shots=SHOTS)
result = job.result()
tomo_fitter = StateTomographyFitter(result, tomo_circuits_enm)
rho = tomo_fitter.fit()
wext_enm.append(extractable_work(rho, 1, 0))
plt.plot(t_values, wext_ncp, 'x', label='Non CP-div.')
plt.plot(t_values, wext_enm, 'x', label='Et. Non-M')
plt.legend()
plt.xlabel('t')
plt.ylabel('$W_{ex}$');
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, execute
from qiskit.providers.fake_provider import FakeVigoV2
from qiskit.visualization import plot_gate_map
backend = FakeVigoV2()
plot_gate_map(backend)
|
https://github.com/Z-928/Bugs4Q
|
Z-928
|
from qiskit import Aer, QuantumCircuit, transpile
from qiskit.circuit.library import PhaseEstimation
qc= QuantumCircuit(3,3)
# dummy unitary circuit
unitary_circuit = QuantumCircuit(1)
unitary_circuit.h(0)
# QPE
qc.append(PhaseEstimation(2, unitary_circuit), list(range(3)))
qc.measure(list(range(3)), list(range(3)))
backend = Aer.get_backend('qasm_simulator')
qc_transpiled = transpile(qc, backend)
result = backend.run(qc, shots = 8192).result()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, transpile
from qiskit.providers.fake_provider import FakeBoeblingen
backend = FakeBoeblingen()
ghz = QuantumCircuit(5)
ghz.h(0)
ghz.cx(0,range(1,5))
circ = transpile(ghz, backend, scheduling_method="asap")
circ.draw(output='mpl')
|
https://github.com/PabloMartinezAngerosa/QAOA-uniform-convergence
|
PabloMartinezAngerosa
|
import qiskit
import numpy as np
import networkx as nx
import matplotlib.pyplot as plt
from collections import defaultdict
from operator import itemgetter
from scipy.optimize import minimize
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer
from qiskit.aqua.algorithms import NumPyEigensolver
from qiskit.quantum_info import Pauli
from qiskit.aqua.operators import op_converter
from qiskit.aqua.operators import WeightedPauliOperator
from tsp_qaoa import marina_solution
G=nx.Graph()
i=1
G.add_node(i,pos=(i,i))
G.add_node(2,pos=(2,2))
G.add_node(3,pos=(1,0))
G.add_edge(1,2,weight=20.5)
G.add_edge(1,3,weight=9.8)
pos=nx.get_node_attributes(G,'pos')
nx.draw(G,pos)
labels = nx.get_edge_attributes(G,'weight')
nx.draw_networkx_edge_labels(G,pos,edge_labels=labels)
def append_zz_term(qc,q1,q2,gamma):
qc.cx(q1,q2)
qc.rz(2*gamma,q2)
qc.cx(q1,q2)
def get_cost_circuit(G,gamma):
N=G.number_of_nodes()
qc=QuantumCircuit(N,N)
for i,j in G.edges():
append_zz_term(qc,i,j,gamma)
return qc
#print(get_cost_circuit(G,0.5))
def append_x_term(qc,q1,beta):
qc.rx(2*beta,q1)
def get_mixer_operator(G,beta):
N=G.number_of_nodes()
qc=QuantumCircuit(N,N)
for n in G.nodes():
append_x_term(qc,n,beta)
return qc
#print(get_mixer_operator(G,0.5))
def get_QAOA_circuit(G,beta,gamma):
assert(len(beta)==len(gamma))
N=G.number_of_nodes()
qc=QuantumCircuit(N,N)
qc.h(range(N))
p=len(beta)
#aplicamos las p rotaciones
for i in range(p):
qc=qc.compose(get_cost_circuit(G,gamma[i]))
qc=qc.compose(get_mixer_operator(G,beta[i]))
qc.barrier(range(N))
qc.measure(range(N),range(N))
return qc
print(get_QAOA_circuit(G,[0.5,0,6],[0.5,0,6]))
def invert_counts(counts):
return {k[::-1] :v for k,v in counts.items()}
qc=get_QAOA_circuit(G,[0.5,0,6],[0.5,0,6])
backend=Aer.get_backend('qasm_simulator')
job=execute(qc,backend)
result=job.result()
print(invert_counts(result.get_counts()))
def maxcut_obj(x,G):
cut=0
for i,j in G.edges():
if x[i]!=x[j]:
cut = cut-1
return cut
print(maxcut_obj("00011",G))
def compute_maxcut_energy(counts,G):
energy=0
get_counts=0
total_counts=0
for meas, meas_count in counts.items():
obj_for_meas=maxcut_obj(meas,G)
energy+=obj_for_meas*meas_count
total_counts+=meas_count
return energy/total_counts
def get_black_box_objective(G,p):
backend=Aer.get_backend('qasm_simulator')
def f(theta):
beta=theta[:p]
gamma=theta[p:]
qc=get_QAOA_circuit(G,beta,gamma)
counts=execute(qc,backend,seed_simulator=10).result().get_counts()
return compute_maxcut_energy(invert_counts(counts),G)
return f
p=5
obj=get_black_box_objective(G,p)
init_point=np.array([0.8,2.2,0.83,2.15,0.37,2.4,6.1,2.2,3.8,6.1])#([2,2,1,1,1,1,1,1,1,1])
res_sample=minimize(obj, init_point,method="COBYLA",options={"maxiter":2500,"disp":True})
res_sample
from thirdParty.classical import rand_graph, classical, bitstring_to_path, calc_cost
from utils import mapeo_grafo
cantidad_ciudades = 4
pesos, conexiones = None, None
mejor_camino = None
while not mejor_camino:
pesos, conexiones = rand_graph(cantidad_ciudades)
mejor_costo, mejor_camino = classical(pesos, conexiones, loop=False)
G = mapeo_grafo(conexiones, pesos)
pos=nx.spring_layout(G)
nx.draw(G,pos)
labels = nx.get_edge_attributes(G,'weight')
nx.draw_networkx_edge_labels(G,pos,edge_labels=labels)
G
pos=nx.get_node_attributes(G,'weight')
pos
labels = nx.get_edge_attributes(G,'weight')
labels
def funcion_costo(multiplicador_lagrange, cantidad_ciudades, pesos, conexiones ):
N = G.number_of_nodes()
N_square = N^2
# restriccion 1
for i in range(cantidad_ciudades):
cur = sI(N_square)
for j in range(num_cities):
cur -= D(i, j)
ret += cur**2
# retorna el indice de qubit por conversion al problema
def quibit_indice(i, l, N):
return i * N + l
from qiskit.quantum_info.operators import Operator, Pauli
# Create an operator
XX = Operator(Pauli(label='XX'))
# Add to a circuit
circ = QuantumCircuit(2, 2)
circ.append(XX, [0, 1])
circ.measure([0,1], [0,1])
circ.draw('mpl')
# Add to a circuit
circ = QuantumCircuit(2, 2)
circ.append(a, [0])
#circ.measure([0,1], [0,1])
circ.draw('mpl')
a = I - ( 0.5*(I+ Z))**2
a = Operator(a)
a.is_unitary()
print(I @ Z)
|
https://github.com/qwqmlf/qwgc
|
qwqmlf
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.3.1
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
import numpy as np
import copy
from qiskit import QuantumCircuit, QuantumRegister, Aer, execute
np.set_printoptions(linewidth=10000, threshold=10000)
# +
def theoretical_prob(initial, step, ptran, nq):
Pi_op = Pi_operator(ptran)
swap = swap_operator(nq)
operator = (2*Pi_op) - np.identity(len(Pi_op))
Szegedy = np.dot(operator, swap)
Szegedy_n = copy.copy(Szegedy)
print(id(Szegedy), id(Szegedy_n))
if step == 0:
init_prob = np.array([abs(i)**2 for i in initial], dtype=np.float)
return init_prob
elif step == 1:
prob = np.array([abs(i)**2 for i in np.dot(Szegedy, initial)],
dtype=np.float)
return prob
else:
for n in range(step-1):
Szegedy_n = np.dot(Szegedy_n, Szegedy)
probs = np.array([abs(i)**2 for i in np.dot(initial, Szegedy_n)],
dtype=np.float)
return probs
def swap_operator(n_qubit):
q1 = QuantumRegister(n_qubit//2)
q2 = QuantumRegister(n_qubit//2)
qc = QuantumCircuit(q1, q2)
for c, t in zip(q1, q2):
qc.swap(c, t)
# FIXME
backend = Aer.get_backend('unitary_simulator')
job = execute(qc, backend=backend)
swap = job.result().get_unitary(qc)
return swap
def Pi_operator(ptran):
'''
This is not a quantum operation,
just returning matrix
'''
lg = len(ptran)
psi_op = []
count = 0
for i in range(lg):
psi_vec = [0 for _ in range(lg**2)]
for j in range(lg):
psi_vec[count] = np.sqrt(ptran[j][i])
count += 1
psi_op.append(np.kron(np.array(psi_vec).T,
np.conjugate(psi_vec)).reshape((lg**2, lg**2)))
Pi = psi_op[0]
for i in psi_op[1:]:
Pi = np.add(Pi, i)
return Pi
def is_unitary(operator, tolerance=0.0001):
h, w = operator.shape
if not h == w:
return False
adjoint = np.conjugate(operator.transpose())
product1 = np.dot(operator, adjoint)
product2 = np.dot(adjoint, operator)
ida = np.eye(h)
return np.allclose(product1, ida) & np.allclose(product2, ida)
# +
alpha = 0.85
target_graph = np.array([[0, 1, 0, 0, 0, 0, 0, 1],
[0, 0, 1, 0, 0, 0, 0, 0],
[0, 1, 0, 1, 0, 0, 0, 0],
[0, 0, 1, 0, 1, 0, 0, 0],
[0, 0, 0, 1, 0, 1, 0, 0],
[0, 0, 0, 0, 1, 0, 1, 0],
[0, 0, 0, 0, 0, 1, 0, 1],
[0, 0, 0, 0, 0, 0, 1, 0]])
E = np.array([[1/8, 1/2, 0, 0, 0, 0, 0, 1/2],
[1/8, 0, 1/2, 0, 0, 0, 0, 0],
[1/8, 1/2, 0, 1/2, 0, 0, 0, 0],
[1/8, 0, 1/2, 0, 1/2, 0, 0, 0],
[1/8, 0, 0, 1/2, 0, 1/2, 0, 0],
[1/8, 0, 0, 0, 1/2, 0, 1/2, 0],
[1/8, 0, 0, 0, 0, 1/2, 0, 1/2],
[1/8, 0, 0, 0, 0, 0, 1/2, 0]])
# use google matrix
lt = len(target_graph)
prob_dist = alpha*E + ((1-alpha)/lt)*np.ones((lt, lt))
init_state_eight = 1/2*np.array([np.sqrt(prob_dist[j][i]) for i in range(lt) for j in range(lt)])
# -
Pi_op = Pi_operator(prob_dist)
operator = (2*Pi_op) - np.identity(len(Pi_op))
lo = len(operator)
initial = np.array([0 if i != 32 else 1 for i in range(lo)])
# initial = np.array([np.sqrt(1/lo) for i in range(lo)])
ideal = theoretical_prob(initial, 2, prob_dist, 6)
for i, v in enumerate(ideal):
print(i, v)
import networkx as nx
import matplotlib.pyplot as plt
target_graph = np.array([[0, 1, 0, 1],
[0, 0, 1, 0],
[0, 1, 0, 1],
[0, 0, 1, 0]])
Gs = nx.from_numpy_matrix(target_graph)
G = nx.MultiDiGraph()
pos = [(1, 1), (5, 1), (5, 5), (1, 5)]
G.add_edges_from(Gs.edges())
plt.figure(figsize=(8,8))
nx.draw_networkx(G, pos, node_size=1000, width=3, arrowsize=50)
plt.show()
# +
target_graph = np.array([[0, 1, 0, 0, 0, 0, 0, 1],
[0, 0, 1, 0, 0, 0, 0, 0],
[0, 1, 0, 1, 0, 0, 0, 0],
[0, 0, 1, 0, 1, 0, 0, 0],
[0, 0, 0, 1, 0, 1, 0, 0],
[0, 0, 0, 0, 1, 0, 1, 0],
[0, 0, 0, 0, 0, 1, 0, 1],
[0, 0, 0, 0, 0, 0, 1, 0]])
Gs = nx.from_numpy_matrix(target_graph)
G = nx.MultiDiGraph()
# pos = [(1, 1), (2, 2), (3, 3), (1, 5), (2, 2), (6, 2), (6, 6), (2, 6)]
pos = [(0, 0), (1, 1), (2, 2), (1, 3), (0, 4), (-1, 3), (-2, 2), (-1, 1)]
G.add_edges_from(Gs.edges())
# pos = nx.spring_layout(G)
plt.figure(figsize=(8,8))
nx.draw_networkx(G, pos, node_size=1000, width=3, arrowsize=50)
plt.show()
# +
target_graph = np.array([[0, 0, 0, 1, 1, 0, 0, 0],
[1, 0, 0, 0, 1, 0, 0, 0],
[0, 1, 0, 0, 0, 1, 0, 0],
[0, 0, 1, 0, 0, 1, 0, 0],
[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]])
Gs = nx.from_numpy_matrix(target_graph)
print(Gs.edges())
G = nx.MultiDiGraph()
# pos = [(1, 1), (2, 2), (3, 3), (1, 5), (2, 2), (6, 2), (6, 6), (2, 6)]
pos = [(0, 0), (3, 3), (2, 9), (-1, 5), (5, 1), (4, 5), (8, 5), (9, 3)]
G.add_edges_from(Gs.edges())
G.add_edges_from([(7, 6)])
# pos = nx.spring_layout(G, k=10)
plt.figure(figsize=(10, 10))
nx.draw_networkx(G, pos, node_size=1000, width=3, arrowsize=50)
plt.show()
# -
|
https://github.com/7enTropy7/Shor-s-Algorithm_Quantum
|
7enTropy7
|
from math import gcd,log
from random import randint
import numpy as np
from qiskit import *
qasm_sim = qiskit.Aer.get_backend('qasm_simulator')
def period(a,N):
available_qubits = 16
r=-1
if N >= 2**available_qubits:
print(str(N)+' is too big for IBMQX')
qr = QuantumRegister(available_qubits)
cr = ClassicalRegister(available_qubits)
qc = QuantumCircuit(qr,cr)
x0 = randint(1, N-1)
x_binary = np.zeros(available_qubits, dtype=bool)
for i in range(1, available_qubits + 1):
bit_state = (N%(2**i)!=0)
if bit_state:
N -= 2**(i-1)
x_binary[available_qubits-i] = bit_state
for i in range(0,available_qubits):
if x_binary[available_qubits-i-1]:
qc.x(qr[i])
x = x0
while np.logical_or(x != x0, r <= 0):
r+=1
qc.measure(qr, cr)
for i in range(0,3):
qc.x(qr[i])
qc.cx(qr[2],qr[1])
qc.cx(qr[1],qr[2])
qc.cx(qr[2],qr[1])
qc.cx(qr[1],qr[0])
qc.cx(qr[0],qr[1])
qc.cx(qr[1],qr[0])
qc.cx(qr[3],qr[0])
qc.cx(qr[0],qr[1])
qc.cx(qr[1],qr[0])
result = execute(qc,backend = qasm_sim, shots=1024).result()
counts = result.get_counts()
print(qc)
results = [[],[]]
for key,value in counts.items(): #the result should be deterministic but there might be some quantum calculation error so we take the most reccurent output
results[0].append(key)
results[1].append(int(value))
s = results[0][np.argmax(np.array(results[1]))]
return r
def shors_breaker(N):
N = int(N)
while True:
a=randint(0,N-1)
g=gcd(a,N)
if g!=1 or N==1:
return g,N//g
else:
r=period(a,N)
if r % 2 != 0:
continue
elif pow(a,r//2,N)==-1:
continue
else:
p=gcd(pow(a,r//2)+1,N)
q=gcd(pow(a,r//2)-1,N)
if p==N or q==N:
continue
return p,q
N=int(input("Enter a number:"))
assert N>0,"Input must be positive"
print(shors_breaker(N))
|
https://github.com/Pitt-JonesLab/slam_decomposition
|
Pitt-JonesLab
|
# this notebook I was trying to understand the fsim hamiltonian
# I couldn't make sense of the parameter g, so I think I have to make sense
import logging
logger = logging.getLogger()
logger.setLevel(logging.INFO)
%matplotlib widget
import numpy as np
import matplotlib.pyplot as plt
# %matplotlib widget
from qiskit import QuantumCircuit, BasicAer, execute
from qiskit.visualization import plot_histogram
from qiskit.quantum_info import (
mutual_information,
Statevector,
partial_trace,
concurrence,
entanglement_of_formation,
)
from slam.basisv2 import CircuitTemplateV2
from slam.utils.gates.custom_gates import CirculatorSNAILGate, ConversionGainSmushGate
from slam.cost_function import BasicCostInverse, BasicCost, BasicReducedCost
from slam.optimizer import TemplateOptimizer
import h5py
from slam.basisv2 import CircuitTemplateV2
from slam.utils.gates.custom_gates import ConversionGainSmushGate, FSimHamiltonianGate
gate_lambda = lambda g: FSimHamiltonianGate(g, -208e-3, t=12)
basis = CircuitTemplateV2(
n_qubits=2, base_gates=[gate_lambda], edge_params=[[(0, 1)]], no_exterior_1q=True
)
basis.spanning_range = range(1, 2)
# basis.build(1)
# basis.circuit.draw('mpl')
from slam.sampler import HaarSample, GateSample
from slam.utils.gates.custom_gates import FSim
sampler = GateSample(gate=FSim(1 * np.pi / 2, 1 * np.pi / 6))
s = [s for s in sampler][0]
from slam.optimizer import TemplateOptimizer
from slam.cost_function import BasicCost, ContinuousUnitaryCostFunction
objective1 = ContinuousUnitaryCostFunction(timesteps=100)
objective2 = BasicCost()
optimizer3 = TemplateOptimizer(
basis=basis,
objective=objective1,
use_callback=True,
override_fail=True,
success_threshold=1e-7,
training_restarts=25,
)
# from qiskit.circuit.library import iSwapGate, CZGate
# def fsim(theta, phi):
# gate = iSwapGate().power(-2 * theta/np.pi).to_matrix()
# gate2 = CZGate().power(-phi/np.pi).to_matrix()
# gate = np.matmul(gate, gate2)
# return UnitaryGate(gate)
# from slam.utils.visualize import unitary_to_weyl
# unitary_to_weyl(fsim(1*np.pi/2, 1*np.pi/6))
# c1c2c3(fsim(1*np.pi/2, 1*np.pi/6).to_matrix())
ret = optimizer3.approximate_target_U(s)
basis.reconstruct(ret).draw("mpl")
coordinate_list = []
from slam.utils.gates.custom_gates import FSim, BerkeleyGate, CanonicalGate
from slam.hamiltonian import FSimHamiltonian
from weylchamber import c1c2c3
from qiskit.quantum_info import Operator
from slam.utils.visualize import coordinate_2dlist_weyl
from qiskit.extensions import UnitaryGate
from tqdm import tqdm
coordinate_list = []
r = np.linspace(0, 12, 101)
for t in tqdm(r):
qc2 = QuantumCircuit(2)
# add fsim as a function of time
# qc2.append(FSim(1*np.pi/2, 1*np.pi/6).power(t), [0,1])
qc2.append(
UnitaryGate(
FSimHamiltonian.construct_U(
(-20e-3 * (2 * np.pi)), -208e-3 * (np.pi * 2), t=t
)
),
[0, 1],
)
# eliminating x-axis symmetry
c = list(c1c2c3(Operator(qc2).data))
# if c[0] > 0.5:
# c[0] = -1*c[0] + 1
coordinate_list.append(c)
coordinate_2dlist_weyl(coordinate_list, c=r, cmap="viridis")
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
from qiskit.algorithms import AmplificationProblem
# the state we desire to find is '11'
good_state = ['11']
# specify the oracle that marks the state '11' as a good solution
oracle = QuantumCircuit(2)
oracle.cz(0, 1)
# define Grover's algorithm
problem = AmplificationProblem(oracle, is_good_state=good_state)
# now we can have a look at the Grover operator that is used in running the algorithm
# (Algorithm circuits are wrapped in a gate to appear in composition as a block
# so we have to decompose() the op to see it expanded into its component gates.)
problem.grover_operator.decompose().draw(output='mpl')
from qiskit.algorithms import Grover
from qiskit.primitives import Sampler
grover = Grover(sampler=Sampler())
result = grover.amplify(problem)
print('Result type:', type(result))
print()
print('Success!' if result.oracle_evaluation else 'Failure!')
print('Top measurement:', result.top_measurement)
from qiskit.quantum_info import Statevector
oracle = Statevector.from_label('11')
problem = AmplificationProblem(oracle, is_good_state=['11'])
grover = Grover(sampler=Sampler())
result = grover.amplify(problem)
print('Result type:', type(result))
print()
print('Success!' if result.oracle_evaluation else 'Failure!')
print('Top measurement:', result.top_measurement)
problem.grover_operator.oracle.decompose().draw(output='mpl')
from qiskit.circuit.library.phase_oracle import PhaseOracle
from qiskit.exceptions import MissingOptionalLibraryError
# `Oracle` (`PhaseOracle`) as the `oracle` argument
expression = '(a & b)'
try:
oracle = PhaseOracle(expression)
problem = AmplificationProblem(oracle)
display(problem.grover_operator.oracle.decompose().draw(output='mpl'))
except MissingOptionalLibraryError as ex:
print(ex)
import numpy as np
# Specifying `state_preparation`
# to prepare a superposition of |01>, |10>, and |11>
oracle = QuantumCircuit(3)
oracle.ccz(0, 1, 2)
theta = 2 * np.arccos(1 / np.sqrt(3))
state_preparation = QuantumCircuit(3)
state_preparation.ry(theta, 0)
state_preparation.ch(0,1)
state_preparation.x(1)
state_preparation.h(2)
# we only care about the first two bits being in state 1, thus add both possibilities for the last qubit
problem = AmplificationProblem(oracle, state_preparation=state_preparation, is_good_state=['110', '111'])
# state_preparation
print('state preparation circuit:')
problem.grover_operator.state_preparation.draw(output='mpl')
grover = Grover(sampler=Sampler())
result = grover.amplify(problem)
print('Success!' if result.oracle_evaluation else 'Failure!')
print('Top measurement:', result.top_measurement)
oracle = QuantumCircuit(5)
oracle.ccz(0, 1, 2)
oracle.draw(output='mpl')
from qiskit.circuit.library import GroverOperator
grover_op = GroverOperator(oracle, insert_barriers=True)
grover_op.decompose().draw(output='mpl')
grover_op = GroverOperator(oracle, reflection_qubits=[0, 1, 2], insert_barriers=True)
grover_op.decompose().draw(output='mpl')
# a list of binary strings good state
oracle = QuantumCircuit(2)
oracle.cz(0, 1)
good_state = ['11', '00']
problem = AmplificationProblem(oracle, is_good_state=good_state)
print(problem.is_good_state('11'))
# a list of integer good state
oracle = QuantumCircuit(2)
oracle.cz(0, 1)
good_state = [0, 1]
problem = AmplificationProblem(oracle, is_good_state=good_state)
print(problem.is_good_state('11'))
from qiskit.quantum_info import Statevector
# `Statevector` good state
oracle = QuantumCircuit(2)
oracle.cz(0, 1)
good_state = Statevector.from_label('11')
problem = AmplificationProblem(oracle, is_good_state=good_state)
print(problem.is_good_state('11'))
# Callable good state
def callable_good_state(bitstr):
if bitstr == "11":
return True
return False
oracle = QuantumCircuit(2)
oracle.cz(0, 1)
problem = AmplificationProblem(oracle, is_good_state=good_state)
print(problem.is_good_state('11'))
# integer iteration
oracle = QuantumCircuit(2)
oracle.cz(0, 1)
problem = AmplificationProblem(oracle, is_good_state=['11'])
grover = Grover(iterations=1)
# list iteration
oracle = QuantumCircuit(2)
oracle.cz(0, 1)
problem = AmplificationProblem(oracle, is_good_state=['11'])
grover = Grover(iterations=[1, 2, 3])
# using sample_from_iterations
oracle = QuantumCircuit(2)
oracle.cz(0, 1)
problem = AmplificationProblem(oracle, is_good_state=['11'])
grover = Grover(iterations=[1, 2, 3], sample_from_iterations=True)
iterations = Grover.optimal_num_iterations(num_solutions=1, num_qubits=8)
iterations
def to_DIAMACS_CNF_format(bit_rep):
return [index+1 if val==1 else -1 * (index + 1) for index, val in enumerate(bit_rep)]
oracle = QuantumCircuit(2)
oracle.cz(0, 1)
problem = AmplificationProblem(oracle, is_good_state=['11'], post_processing=to_DIAMACS_CNF_format)
problem.post_processing([1, 0, 1])
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, transpile, schedule
from qiskit.visualization.timeline import draw, IQXSimple
from qiskit.providers.fake_provider import FakeBoeblingen
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0,1)
qc = transpile(qc, FakeBoeblingen(), scheduling_method='alap', layout_method='trivial')
draw(qc, style=IQXSimple())
|
https://github.com/jonasmaziero/computacao_quantica_qiskit
|
jonasmaziero
|
%run init.ipynb
CX_12 = tp(proj(cb(2,0)),id(2)) + tp(proj(cb(2,1)),pauli(1)); CX_12
CX_21 = tp(id(2),proj(cb(2,0))) + tp(pauli(1),proj(cb(2,1))); CX_21
SWAP = CX_12*CX_21*CX_12; SWAP
Cz = tp(proj(cb(2,0)), id(2)) + tp(proj(cb(2,1)), pauli(3)); Cz_12 = Cz
Cz_21 = tp(id(2),proj(cb(2,0))) + tp(pauli(3),proj(cb(2,1)))
Cz_12, Cz_21
H = (1/sqrt(2))*Matrix([[1,1],[1,-1]]); H
Cx12 = tp(id(2),H)*Cz*tp(id(2),H); Cx12
Cx21 = tp(H,id(2))*Cz*tp(H,id(2)); Cx21
CX_21 = tp(id(2),proj(cb(2,0))) + tp(pauli(1),proj(cb(2,1))); CX_21
Cz12 = tp(id(2),H)*Cx12*tp(id(2),H); Cz12
Cz21 = tp(id(2),H)*Cx21*tp(id(2),H); Cz12
CCX = tp(proj(cb(2,0)),id(4)) + tp(proj(cb(2,1)),Cx12); CCX
def qc_ry(th):
qr = QuantumRegister(1)
qc = QuantumCircuit(qr, name = 'RY')
qc.ry(th, 0)
return qc
from qiskit import *
qr = QuantumRegister(3)
cr = ClassicalRegister(2)
qc = QuantumCircuit(qr, cr)
qc_ry_ = qc_ry(math.pi)
ccry = qc_ry_.to_gate().control(2)
qc.append(ccry, [2, 0, 1])
qc.draw(output = 'mpl')
from qiskit import *
qc = QuantumCircuit(1, 1); qc.h([0]); qc.h([0]); qc.measure([0], [0]); qc.draw(output = 'mpl')
qc = QuantumCircuit(1, 1); qc.barrier(); qc.h([0]); qc.barrier(); qc.h([0]); qc.barrier(); qc.measure([0], [0])
qc.draw(output = 'mpl')
qc.decompose().draw(output = 'mpl')
qc = QuantumCircuit(1, 1)
N = 5
for j in range(0, N):
qc.id([0])
qc.measure([0], [0])
qc.draw(output = 'mpl')
nshots = 8192
qiskit.IBMQ.load_account()
#provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22')
provider = qiskit.IBMQ.get_provider(hub = 'ibm-q-research-2', group = 'federal-uni-sant-1', project = 'main')
device = provider.get_backend('ibmq_bogota')
simulator = Aer.get_backend('qasm_simulator')
from qiskit.tools.monitor import job_monitor
from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter
from qiskit.tools.monitor import backend_overview, backend_monitor
from qiskit.tools.visualization import plot_histogram
qc = QuantumCircuit(1, 1)
N = 0
for j in range(0, N):
qc.barrier(); qc.id([0])
qc.barrier(); qc.measure([0], [0])
qc.draw(output = 'mpl')
job_exp = execute(qc, backend = device, shots = nshots)
print(job_exp.job_id()); job_monitor(job_exp)
plot_histogram(job_exp.result().get_counts(qc))
qc = QuantumCircuit(1, 1)
N = 10000
for j in range(0, N):
qc.barrier(); qc.id([0])
qc.barrier(); qc.measure([0], [0]);
#qc.draw(output = 'mpl')
job_exp = execute(qc, backend = device, shots = nshots)
print(job_exp.job_id()); job_monitor(job_exp)
plot_histogram(job_exp.result().get_counts(qc))
qc = QuantumCircuit(4); qc.h([0]); qc.cx([0], [2]); qc.h([1]); qc.cx([1], [3]); qc.draw(output = 'mpl')
qc = QuantumCircuit(3); qc.h([0]); qc.cx([0], [1]); qc.reset([0]); qc.h([0]); qc.cx([0], [2])
qc.draw(output = 'mpl')
|
https://github.com/GabrielPontolillo/Quantum_Algorithm_Implementations
|
GabrielPontolillo
|
from qiskit import QuantumCircuit
def create_bell_pair():
qc = QuantumCircuit(2)
qc.h(1)
### removed cx gate ###
return qc
def encode_message(qc, qubit, msg):
if len(msg) != 2 or not set([0,1]).issubset({0,1}):
raise ValueError(f"message '{msg}' is invalid")
if msg[1] == "1":
qc.x(qubit)
if msg[0] == "1":
qc.z(qubit)
return qc
def decode_message(qc):
qc.cx(1, 0)
qc.h(1)
return qc
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
# Create a circuit with a register of three qubits
circ = QuantumCircuit(3)
# H gate on qubit 0, putting this qubit in a superposition of |0> + |1>.
circ.h(0)
# A CX (CNOT) gate on control qubit 0 and target qubit 1 generating a Bell state.
circ.cx(0, 1)
# CX (CNOT) gate on control qubit 0 and target qubit 2 resulting in a GHZ state.
circ.cx(0, 2)
# Draw the circuit
circ.draw('mpl')
|
https://github.com/idriss-hamadi/Qiskit-Quantaum-codes-
|
idriss-hamadi
|
# Importing standard Qiskit libraries
from qiskit import QuantumCircuit, transpile
from qiskit.tools.jupyter import *
from qiskit.visualization import *
from ibm_quantum_widgets import *
from qiskit_aer import AerSimulator
# qiskit-ibmq-provider has been deprecated.
# Please see the Migration Guides in https://ibm.biz/provider_migration_guide for more detail.
from qiskit_ibm_runtime import QiskitRuntimeService, Sampler, Estimator, Session, Options
# Loading your IBM Quantum account(s)
service = QiskitRuntimeService(channel="ibm_quantum")
# Invoke a primitive inside a session. For more details see https://qiskit.org/documentation/partners/qiskit_ibm_runtime/tutorials.html
# with Session(backend=service.backend("ibmq_qasm_simulator")):
# result = Sampler().run(circuits).result()
from qiskit import *
IBMQ.save_account(open("token.txt","r").read()) #signing in using my token in my txt file
IBMQ.load_account() #lading account
Aer.backends() #show simulators each is special
provider=IBMQ.get_provider("ibm-q") #show all the actual quantaum computers and simulators that are avaliable
provider.backends()
for backend in provider.backends(): #show properties
print(backend.properties())
i=0 #code to see if it is simulator or not and how many pending jobs are there
for backend in provider.backends():
i+=1
try:
qubit_count=len(backend.properties().qubits)
except:
qubit_count="simulated"
if(qubit_count=="simulated"):
print(f"{i}-{backend.name()} : there is {backend.status().pending_jobs} waiting jobs in the queue and it is a simulator")
else:
print(f"{i}-{backend.name()} : there is {backend.status().pending_jobs} waiting jobs in the queue and it has {qubit_count} qubits")
|
https://github.com/Qiskit/feedback
|
Qiskit
|
from qiskit import Aer
from qiskit.utils import QuantumInstance
from qiskit_nature.algorithms import VQEUCCFactory
from qiskit_nature.algorithms.initial_points.mp2_initial_point import MP2InitialPoint
from qiskit_nature.drivers import Molecule
from qiskit_nature.drivers.second_quantization import (
ElectronicStructureDriverType,
ElectronicStructureMoleculeDriver,
)
from qiskit_nature.problems.second_quantization import ElectronicStructureProblem
from qiskit_nature.converters.second_quantization import QubitConverter
from qiskit_nature.mappers.second_quantization import JordanWignerMapper
from qiskit_nature.algorithms import GroundStateEigensolver
from qiskit_nature.transformers.second_quantization.electronic import FreezeCoreTransformer
molecule = Molecule(
geometry=[["H", [0.0, 0.0, 0.0]], ["H", [0.0, 0.0, 0.735]]], charge=0, multiplicity=1
)
driver = ElectronicStructureMoleculeDriver(
molecule, basis="sto3g", driver_type=ElectronicStructureDriverType.PYSCF
)
freeze_core = FreezeCoreTransformer()
problem = ElectronicStructureProblem(driver, transformers=[freeze_core])
qubit_converter = QubitConverter(JordanWignerMapper())
initial_point = MP2InitialPoint()
quantum_instance = QuantumInstance(backend=Aer.get_backend("aer_simulator_statevector"))
vqe_ucc_factory = VQEUCCFactory(quantum_instance, initial_point=initial_point)
vqe_solver = GroundStateEigensolver(qubit_converter, vqe_ucc_factory)
res = vqe_solver.solve(problem)
print(res)
from qiskit.algorithms.optimizers import L_BFGS_B
from qiskit.algorithms import VQE
from qiskit_nature.circuit.library import UCCSD
from qiskit_nature.settings import settings
from qiskit_nature.drivers import Molecule
settings.dict_aux_operators = True
molecule = Molecule(
geometry=[["H", [0.0, 0.0, 0.0]], ["H", [0.0, 0.0, 0.735]]],
charge=0,
multiplicity=1,
)
driver = ElectronicStructureMoleculeDriver(
molecule, basis="sto3g", driver_type=ElectronicStructureDriverType.PYSCF
)
problem = ElectronicStructureProblem(driver)
# generate the second-quantized operators
second_q_ops = problem.second_q_ops()
main_op = second_q_ops["ElectronicEnergy"]
driver_result = problem.grouped_property_transformed
particle_number = driver_result.get_property("ParticleNumber")
electronic_energy = driver_result.get_property("ElectronicEnergy")
num_particles = (particle_number.num_alpha, particle_number.num_beta)
num_spin_orbitals = particle_number.num_spin_orbitals
# setup the classical optimizer for VQE
optimizer = L_BFGS_B()
# setup the qubit converter
converter = QubitConverter(JordanWignerMapper())
# map to qubit operators
qubit_op = converter.convert(main_op, num_particles=num_particles)
# setup the ansatz for VQE
ansatz = UCCSD(
qubit_converter=converter,
num_particles=num_particles,
num_spin_orbitals=num_spin_orbitals,
)
mp2_initial_point = MP2InitialPoint()
mp2_initial_point.grouped_property = driver_result
mp2_initial_point.ansatz = ansatz
initial_point = mp2_initial_point.to_numpy_array()
# set the backend for the quantum computation
backend = Aer.get_backend("aer_simulator_statevector")
# setup and run VQE
algorithm = VQE(
ansatz, optimizer=optimizer, quantum_instance=backend, initial_point=initial_point
)
result = algorithm.compute_minimum_eigenvalue(qubit_op)
print(result.eigenvalue.real)
electronic_structure_result = problem.interpret(result)
print(electronic_structure_result)
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2022, 2023.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test evolver problem class."""
import unittest
from test.python.algorithms import QiskitAlgorithmsTestCase
from ddt import data, ddt
from numpy.testing import assert_raises
from qiskit import QuantumCircuit
from qiskit_algorithms import TimeEvolutionProblem
from qiskit.quantum_info import Pauli, SparsePauliOp, Statevector
from qiskit.circuit import Parameter
from qiskit.opflow import Y, Z, One, X, Zero, PauliSumOp
@ddt
class TestTimeEvolutionProblem(QiskitAlgorithmsTestCase):
"""Test evolver problem class."""
def test_init_default(self):
"""Tests that all default fields are initialized correctly."""
hamiltonian = Y
time = 2.5
initial_state = One
evo_problem = TimeEvolutionProblem(hamiltonian, time, initial_state)
expected_hamiltonian = Y
expected_time = 2.5
expected_initial_state = One
expected_aux_operators = None
expected_t_param = None
expected_param_value_dict = None
self.assertEqual(evo_problem.hamiltonian, expected_hamiltonian)
self.assertEqual(evo_problem.time, expected_time)
self.assertEqual(evo_problem.initial_state, expected_initial_state)
self.assertEqual(evo_problem.aux_operators, expected_aux_operators)
self.assertEqual(evo_problem.t_param, expected_t_param)
self.assertEqual(evo_problem.param_value_map, expected_param_value_dict)
@data(QuantumCircuit(1), Statevector([1, 0]))
def test_init_all(self, initial_state):
"""Tests that all fields are initialized correctly."""
t_parameter = Parameter("t")
with self.assertWarns(DeprecationWarning):
hamiltonian = t_parameter * Z + Y
time = 2
aux_operators = [X, Y]
param_value_dict = {t_parameter: 3.2}
evo_problem = TimeEvolutionProblem(
hamiltonian,
time,
initial_state,
aux_operators,
t_param=t_parameter,
param_value_map=param_value_dict,
)
with self.assertWarns(DeprecationWarning):
expected_hamiltonian = Y + t_parameter * Z
expected_time = 2
expected_type = QuantumCircuit
expected_aux_operators = [X, Y]
expected_t_param = t_parameter
expected_param_value_dict = {t_parameter: 3.2}
with self.assertWarns(DeprecationWarning):
self.assertEqual(evo_problem.hamiltonian, expected_hamiltonian)
self.assertEqual(evo_problem.time, expected_time)
self.assertEqual(type(evo_problem.initial_state), expected_type)
self.assertEqual(evo_problem.aux_operators, expected_aux_operators)
self.assertEqual(evo_problem.t_param, expected_t_param)
self.assertEqual(evo_problem.param_value_map, expected_param_value_dict)
def test_validate_params(self):
"""Tests expected errors are thrown on parameters mismatch."""
param_x = Parameter("x")
with self.subTest(msg="Parameter missing in dict."):
with self.assertWarns(DeprecationWarning):
hamiltonian = PauliSumOp(SparsePauliOp([Pauli("X"), Pauli("Y")]), param_x)
evolution_problem = TimeEvolutionProblem(hamiltonian, 2, Zero)
with assert_raises(ValueError):
evolution_problem.validate_params()
if __name__ == "__main__":
unittest.main()
|
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
|
aryashah2k
|
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
from qiskit import Aer
from qiskit.aqua import QuantumInstance
from qiskit.aqua.algorithms import QGAN
np.random.seed(2020)
N = 1000
real_data = np.random.binomial(3,0.5,N)
plt.hist(real_data, bins = 4);
n = 2
num_qubits = [n]
num_epochs = 100
batch_size = 100
bounds = [0,3]
qgan = QGAN(data = real_data,
num_qubits = num_qubits,
batch_size = batch_size,
num_epochs = num_epochs,
bounds = bounds,
seed = 2020)
quantum_instance = QuantumInstance(backend=Aer.get_backend('statevector_simulator'))
result = qgan.run(quantum_instance)
samples_g, prob_g = qgan.generator.get_output(qgan.quantum_instance, shots=10000)
plt.hist(range(4), weights = prob_g, bins = 4);
plt.title("Loss function evolution")
plt.plot(range(num_epochs), qgan.g_loss, label='Generator')
plt.plot(range(num_epochs), qgan.d_loss, label='Discriminator')
plt.legend()
plt.show()
plt.title('Relative entropy evolution')
plt.plot(qgan.rel_entr)
plt.show()
import qiskit
qiskit.__qiskit_version__
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from __future__ import annotations
import numpy as np
import networkx as nx
num_nodes = 4
w = np.array([[0., 1., 1., 0.],
[1., 0., 1., 1.],
[1., 1., 0., 1.],
[0., 1., 1., 0.]])
G = nx.from_numpy_array(w)
layout = nx.random_layout(G, seed=10)
colors = ['r', 'g', 'b', 'y']
nx.draw(G, layout, node_color=colors)
labels = nx.get_edge_attributes(G, 'weight')
nx.draw_networkx_edge_labels(G, pos=layout, edge_labels=labels);
def objective_value(x: np.ndarray, w: np.ndarray) -> float:
"""Compute the value of a cut.
Args:
x: Binary string as numpy array.
w: Adjacency matrix.
Returns:
Value of the cut.
"""
X = np.outer(x, (1 - x))
w_01 = np.where(w != 0, 1, 0)
return np.sum(w_01 * X)
def bitfield(n: int, L: int) -> list[int]:
result = np.binary_repr(n, L)
return [int(digit) for digit in result] # [2:] to chop off the "0b" part
# use the brute-force way to generate the oracle
L = num_nodes
max = 2**L
sol = np.inf
for i in range(max):
cur = bitfield(i, L)
how_many_nonzero = np.count_nonzero(cur)
if how_many_nonzero * 2 != L: # not balanced
continue
cur_v = objective_value(np.array(cur), w)
if cur_v < sol:
sol = cur_v
print(f'Objective value computed by the brute-force method is {sol}')
from qiskit.quantum_info import Pauli, SparsePauliOp
def get_operator(weight_matrix: np.ndarray) -> tuple[SparsePauliOp, float]:
r"""Generate Hamiltonian for the graph partitioning
Notes:
Goals:
1 Separate the vertices into two set of the same size.
2 Make sure the number of edges between the two set is minimized.
Hamiltonian:
H = H_A + H_B
H_A = sum\_{(i,j)\in E}{(1-ZiZj)/2}
H_B = (sum_{i}{Zi})^2 = sum_{i}{Zi^2}+sum_{i!=j}{ZiZj}
H_A is for achieving goal 2 and H_B is for achieving goal 1.
Args:
weight_matrix: Adjacency matrix.
Returns:
Operator for the Hamiltonian
A constant shift for the obj function.
"""
num_nodes = len(weight_matrix)
pauli_list = []
coeffs = []
shift = 0
for i in range(num_nodes):
for j in range(i):
if weight_matrix[i, j] != 0:
x_p = np.zeros(num_nodes, dtype=bool)
z_p = np.zeros(num_nodes, dtype=bool)
z_p[i] = True
z_p[j] = True
pauli_list.append(Pauli((z_p, x_p)))
coeffs.append(-0.5)
shift += 0.5
for i in range(num_nodes):
for j in range(num_nodes):
if i != j:
x_p = np.zeros(num_nodes, dtype=bool)
z_p = np.zeros(num_nodes, dtype=bool)
z_p[i] = True
z_p[j] = True
pauli_list.append(Pauli((z_p, x_p)))
coeffs.append(1.0)
else:
shift += 1
return SparsePauliOp(pauli_list, coeffs=coeffs), shift
qubit_op, offset = get_operator(w)
from qiskit.algorithms.minimum_eigensolvers import QAOA
from qiskit.algorithms.optimizers import COBYLA
from qiskit.circuit.library import TwoLocal
from qiskit.primitives import Sampler
from qiskit.quantum_info import Pauli, Statevector
from qiskit.result import QuasiDistribution
from qiskit.utils import algorithm_globals
sampler = Sampler()
def sample_most_likely(state_vector: QuasiDistribution | Statevector) -> np.ndarray:
"""Compute the most likely binary string from state vector.
Args:
state_vector: State vector or quasi-distribution.
Returns:
Binary string as an array of ints.
"""
if isinstance(state_vector, QuasiDistribution):
values = list(state_vector.values())
else:
values = state_vector
n = int(np.log2(len(values)))
k = np.argmax(np.abs(values))
x = bitfield(k, n)
x.reverse()
return np.asarray(x)
algorithm_globals.random_seed = 10598
optimizer = COBYLA()
qaoa = QAOA(sampler, optimizer, reps=2)
result = qaoa.compute_minimum_eigenvalue(qubit_op)
x = sample_most_likely(result.eigenstate)
print(x)
print(f'Objective value computed by QAOA is {objective_value(x, w)}')
from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver
from qiskit.quantum_info import Operator
npme = NumPyMinimumEigensolver()
result = npme.compute_minimum_eigenvalue(Operator(qubit_op))
x = sample_most_likely(result.eigenstate)
print(x)
print(f'Objective value computed by the NumPyMinimumEigensolver is {objective_value(x, w)}')
from qiskit.algorithms.minimum_eigensolvers import SamplingVQE
from qiskit.circuit.library import TwoLocal
from qiskit.utils import algorithm_globals
algorithm_globals.random_seed = 10598
optimizer = COBYLA()
ansatz = TwoLocal(qubit_op.num_qubits, "ry", "cz", reps=2, entanglement="linear")
sampling_vqe = SamplingVQE(sampler, ansatz, optimizer)
result = sampling_vqe.compute_minimum_eigenvalue(qubit_op)
x = sample_most_likely(result.eigenstate)
print(x)
print(f"Objective value computed by VQE is {objective_value(x, w)}")
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
|
mmetcalf14
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 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.
from collections import OrderedDict
import importlib
import logging
from qiskit.providers import BaseBackend
from qiskit.providers.basicaer import BasicAerProvider
from qiskit.aqua import Preferences
logger = logging.getLogger(__name__)
try:
from qiskit.providers.ibmq import IBMQProvider
HAS_IBMQ = True
except Exception as e:
HAS_IBMQ = False
logger.debug("IBMQProvider not loaded: '{}'".format(str(e)))
try:
from qiskit.providers.aer import AerProvider
HAS_AER = True
except Exception as e:
HAS_AER = False
logger.debug("AerProvider not loaded: '{}'".format(str(e)))
_UNSUPPORTED_BACKENDS = ['unitary_simulator', 'clifford_simulator']
def has_ibmq():
return HAS_IBMQ
def has_aer():
return HAS_AER
def is_aer_provider(backend):
"""Detect whether or not backend is from Aer provider.
Args:
backend (BaseBackend): backend instance
Returns:
bool: True is AerProvider
"""
if has_aer():
return isinstance(backend.provider(), AerProvider)
else:
return False
def is_basicaer_provider(backend):
"""Detect whether or not backend is from BasicAer provider.
Args:
backend (BaseBackend): backend instance
Returns:
bool: True is BasicAer
"""
return isinstance(backend.provider(), BasicAerProvider)
def is_ibmq_provider(backend):
"""Detect whether or not backend is from IBMQ provider.
Args:
backend (BaseBackend): backend instance
Returns:
bool: True is IBMQ
"""
if has_ibmq():
return isinstance(backend.provider(), IBMQProvider)
else:
return False
def is_aer_statevector_backend(backend):
"""
Return True if backend object is statevector and from Aer provider.
Args:
backend (BaseBackend): backend instance
Returns:
bool: True is statevector
"""
return is_statevector_backend(backend) and is_aer_provider(backend)
def is_statevector_backend(backend):
"""
Return True if backend object is statevector.
Args:
backend (BaseBackend): backend instance
Returns:
bool: True is statevector
"""
return backend.name().startswith('statevector') if backend is not None else False
def is_simulator_backend(backend):
"""
Return True if backend is a simulator.
Args:
backend (BaseBackend): backend instance
Returns:
bool: True is a simulator
"""
return backend.configuration().simulator
def is_local_backend(backend):
"""
Return True if backend is a local backend.
Args:
backend (BaseBackend): backend instance
Returns:
bool: True is a local backend
"""
return backend.configuration().local
def get_aer_backend(backend_name):
providers = ['qiskit.Aer', 'qiskit.BasicAer']
for provider in providers:
try:
return get_backend_from_provider(provider, backend_name)
except:
pass
raise ImportError("Backend '{}' not found in providers {}".format(backend_name, providers))
def get_backends_from_provider(provider_name):
"""
Backends access method.
Args:
provider_name (str): Fullname of provider instance global property or class
Returns:
list: backend names
Raises:
ImportError: Invalid provider name or failed to find provider
"""
provider_object = _load_provider(provider_name)
if has_ibmq() and isinstance(provider_object, IBMQProvider):
preferences = Preferences()
url = preferences.get_url()
token = preferences.get_token()
kwargs = {}
if url is not None and url != '':
kwargs['url'] = url
if token is not None and token != '':
kwargs['token'] = token
return [x.name() for x in provider_object.backends(**kwargs) if x.name() not in _UNSUPPORTED_BACKENDS]
try:
# try as variable containing provider instance
return [x.name() for x in provider_object.backends() if x.name() not in _UNSUPPORTED_BACKENDS]
except:
# try as provider class then
try:
provider_instance = provider_object()
return [x.name() for x in provider_instance.backends() if x.name() not in _UNSUPPORTED_BACKENDS]
except:
pass
raise ImportError("'Backends not found for provider '{}'".format(provider_object))
def get_backend_from_provider(provider_name, backend_name):
"""
Backend access method.
Args:
provider_name (str): Fullname of provider instance global property or class
backend_name (str): name of backend for this provider
Returns:
BaseBackend: backend object
Raises:
ImportError: Invalid provider name or failed to find provider
"""
backend = None
provider_object = _load_provider(provider_name)
if has_ibmq() and isinstance(provider_object, IBMQProvider):
preferences = Preferences()
url = preferences.get_url()
token = preferences.get_token()
kwargs = {}
if url is not None and url != '':
kwargs['url'] = url
if token is not None and token != '':
kwargs['token'] = token
backend = provider_object.get_backend(backend_name, **kwargs)
else:
try:
# try as variable containing provider instance
backend = provider_object.get_backend(backend_name)
except:
# try as provider class then
try:
provider_instance = provider_object()
backend = provider_instance.get_backend(backend_name)
except:
pass
if backend is None:
raise ImportError("'{} not found in provider '{}'".format(backend_name, provider_object))
return backend
def get_local_providers():
providers = OrderedDict()
for provider in ['qiskit.Aer', 'qiskit.BasicAer']:
try:
providers[provider] = get_backends_from_provider(provider)
except Exception as e:
logger.debug("'{}' not loaded: '{}'.".format(provider, str(e)))
return providers
def register_ibmq_and_get_known_providers():
"""Gets known local providers and registers IBMQ."""
providers = get_local_providers()
if has_ibmq():
providers.update(_get_ibmq_provider())
return providers
def get_provider_from_backend(backend):
"""
Attempts to find a known provider that provides this backend.
Args:
backend (BaseBackend or str): backend object or backend name
Returns:
str: provider name
Raises:
ImportError: Failed to find provider
"""
known_providers = {
'BasicAerProvider': 'qiskit.BasicAer',
'AerProvider': 'qiskit.Aer',
'IBMQProvider': 'qiskit.IBMQ',
}
if isinstance(backend, BaseBackend):
provider = backend.provider()
if provider is None:
raise ImportError("Backend object '{}' has no provider".format(backend.name()))
return known_providers.get(provider.__class__.__name__, provider.__class__.__qualname__)
elif not isinstance(backend, str):
raise ImportError("Invalid Backend '{}'".format(backend))
for provider in known_providers.values():
try:
if get_backend_from_provider(provider, backend) is not None:
return provider
except:
pass
raise ImportError("Backend '{}' not found in providers {}".format(backend, list(known_providers.values())))
def _load_provider(provider_name):
index = provider_name.rfind(".")
if index < 1:
raise ImportError("Invalid provider name '{}'".format(provider_name))
modulename = provider_name[0:index]
objectname = provider_name[index + 1:len(provider_name)]
module = importlib.import_module(modulename)
if module is None:
raise ImportError("Failed to import provider '{}'".format(provider_name))
provider_object = getattr(module, objectname)
if provider_object is None:
raise ImportError("Failed to import provider '{}'".format(provider_name))
if has_ibmq() and isinstance(provider_object, IBMQProvider):
# enable IBMQ account
preferences = Preferences()
enable_ibmq_account(preferences.get_url(), preferences.get_token(), preferences.get_proxies({}))
return provider_object
def enable_ibmq_account(url, token, proxies):
"""
Enable IBMQ account, if not alreay enabled.
"""
if not has_ibmq():
return
try:
url = url or ''
token = token or ''
proxies = proxies or {}
if url != '' and token != '':
from qiskit import IBMQ
from qiskit.providers.ibmq.credentials import Credentials
credentials = Credentials(token, url, proxies=proxies)
unique_id = credentials.unique_id()
if unique_id in IBMQ._accounts:
# disable first any existent previous account with same unique_id and different properties
enabled_credentials = IBMQ._accounts[unique_id].credentials
if enabled_credentials.url != url or enabled_credentials.token != token or enabled_credentials.proxies != proxies:
del IBMQ._accounts[unique_id]
if unique_id not in IBMQ._accounts:
IBMQ.enable_account(token, url=url, proxies=proxies)
logger.info("Enabled IBMQ account. Url:'{}' Token:'{}' "
"Proxies:'{}'".format(url, token, proxies))
except Exception as e:
logger.warning("Failed to enable IBMQ account. Url:'{}' Token:'{}' "
"Proxies:'{}' :{}".format(url, token, proxies, str(e)))
def disable_ibmq_account(url, token, proxies):
"""Disable IBMQ account."""
if not has_ibmq():
return
try:
url = url or ''
token = token or ''
proxies = proxies or {}
if url != '' and token != '':
from qiskit import IBMQ
from qiskit.providers.ibmq.credentials import Credentials
credentials = Credentials(token, url, proxies=proxies)
unique_id = credentials.unique_id()
if unique_id in IBMQ._accounts:
del IBMQ._accounts[unique_id]
logger.info("Disabled IBMQ account. Url:'{}' "
"Token:'{}' Proxies:'{}'".format(url, token, proxies))
else:
logger.info("IBMQ account is not active. Not disabled. "
"Url:'{}' Token:'{}' Proxies:'{}'".format(url, token, proxies))
except Exception as e:
logger.warning("Failed to disable IBMQ account. Url:'{}' "
"Token:'{}' Proxies:'{}' :{}".format(url, token, proxies, str(e)))
def _get_ibmq_provider():
"""Registers IBMQ and return it."""
providers = OrderedDict()
try:
providers['qiskit.IBMQ'] = get_backends_from_provider('qiskit.IBMQ')
except Exception as e:
logger.warning("Failed to access IBMQ: {}".format(str(e)))
return providers
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit.circuit.random import random_circuit
circuit = random_circuit(2, 2, seed=0).decompose(reps=1)
display(circuit.draw("mpl"))
from qiskit.quantum_info import SparsePauliOp
observable = SparsePauliOp("XZ")
print(f">>> Observable: {observable.paulis}")
from qiskit.primitives import Estimator
estimator = Estimator()
job = estimator.run(circuit, observable)
print(f">>> Job ID: {job.job_id()}")
print(f">>> Job Status: {job.status()}")
result = job.result()
print(f">>> {result}")
print(f" > Expectation value: {result.values[0]}")
circuit = random_circuit(2, 2, seed=1).decompose(reps=1)
observable = SparsePauliOp("IY")
job = estimator.run(circuit, observable)
result = job.result()
display(circuit.draw("mpl"))
print(f">>> Observable: {observable.paulis}")
print(f">>> Expectation value: {result.values[0]}")
circuits = (
random_circuit(2, 2, seed=0).decompose(reps=1),
random_circuit(2, 2, seed=1).decompose(reps=1),
)
observables = (
SparsePauliOp("XZ"),
SparsePauliOp("IY"),
)
job = estimator.run(circuits, observables)
result = job.result()
[display(cir.draw("mpl")) for cir in circuits]
print(f">>> Observables: {[obs.paulis for obs in observables]}")
print(f">>> Expectation values: {result.values.tolist()}")
from qiskit.circuit.library import RealAmplitudes
circuit = RealAmplitudes(num_qubits=2, reps=2).decompose(reps=1)
observable = SparsePauliOp("ZI")
parameter_values = [0, 1, 2, 3, 4, 5]
job = estimator.run(circuit, observable, parameter_values)
result = job.result()
display(circuit.draw("mpl"))
print(f">>> Observable: {observable.paulis}")
print(f">>> Parameter values: {parameter_values}")
print(f">>> Expectation value: {result.values[0]}")
from qiskit_ibm_runtime import QiskitRuntimeService
service = QiskitRuntimeService(channel="ibm_quantum")
backend = service.backend("ibmq_qasm_simulator")
from qiskit.circuit.random import random_circuit
from qiskit.quantum_info import SparsePauliOp
circuit = random_circuit(2, 2, seed=0).decompose(reps=1)
display(circuit.draw("mpl"))
observable = SparsePauliOp("XZ")
print(f">>> Observable: {observable.paulis}")
from qiskit_ibm_runtime import Estimator
estimator = Estimator(session=backend)
job = estimator.run(circuit, observable)
print(f">>> Job ID: {job.job_id()}")
print(f">>> Job Status: {job.status()}")
result = job.result()
print(f">>> {result}")
print(f" > Expectation value: {result.values[0]}")
print(f" > Metadata: {result.metadata[0]}")
from qiskit_ibm_runtime import Options
options = Options(optimization_level=3, environment={"log_level": "INFO"})
from qiskit_ibm_runtime import Options
options = Options()
options.resilience_level = 1
options.execution.shots = 2048
estimator = Estimator(session=backend, options=options)
result = estimator.run(circuit, observable).result()
print(f">>> Metadata: {result.metadata[0]}")
estimator = Estimator(session=backend, options=options)
result = estimator.run(circuit, observable, shots=1024).result()
print(f">>> Metadata: {result.metadata[0]}")
from qiskit_ibm_runtime import Options
# optimization_level=3 adds dynamical decoupling
# resilience_level=1 adds readout error mitigation
options = Options(optimization_level=3, resilience_level=1)
estimator = Estimator(session=backend, options=options)
result = estimator.run(circuit, observable).result()
print(f">>> Expectation value: {result.values[0]}")
print(f">>> Metadata: {result.metadata[0]}")
from qiskit_ibm_runtime import Session, Estimator
with Session(backend=backend, max_time="1h"):
estimator = Estimator()
result = estimator.run(circuit, observable).result()
print(f">>> Expectation value from the first run: {result.values[0]}")
result = estimator.run(circuit, observable).result()
print(f">>> Expectation value from the second run: {result.values[0]}")
from qiskit.circuit.random import random_circuit
sampler_circuit = random_circuit(2, 2, seed=0).decompose(reps=1)
sampler_circuit.measure_all()
display(circuit.draw("mpl"))
from qiskit_ibm_runtime import Session, Sampler, Estimator
with Session(backend=backend):
sampler = Sampler()
estimator = Estimator()
result = sampler.run(sampler_circuit).result()
print(f">>> Quasi Distribution from the sampler job: {result.quasi_dists[0]}")
result = estimator.run(circuit, observable).result()
print(f">>> Expectation value from the estimator job: {result.values[0]}")
from qiskit_ibm_runtime import Session, Sampler, Estimator
with Session(backend=backend):
sampler = Sampler()
estimator = Estimator()
sampler_job = sampler.run(sampler_circuit)
estimator_job = estimator.run(circuit, observable)
print(f">>> Quasi Distribution from the sampler job: {sampler_job.result().quasi_dists[0]}")
print(f">>> Expectation value from the estimator job: {estimator_job.result().values[0]}")
from qiskit_ibm_runtime import QiskitRuntimeService, Session, Sampler, Estimator, Options
# 1. Initialize account
service = QiskitRuntimeService(channel="ibm_quantum")
# 2. Specify options, such as enabling error mitigation
options = Options(resilience_level=1)
# 3. Select a backend.
backend = service.backend("ibmq_qasm_simulator")
# 4. Create a session
with Session(backend=backend):
# 5. Create primitive instances
sampler = Sampler(options=options)
estimator = Estimator(options=options)
# 6. Submit jobs
sampler_job = sampler.run(sampler_circuit)
estimator_job = estimator.run(circuit, observable)
# 7. Get results
print(f">>> Quasi Distribution from the sampler job: {sampler_job.result().quasi_dists[0]}")
print(f">>> Expectation value from the estimator job: {estimator_job.result().values[0]}")
import qiskit_ibm_runtime
qiskit_ibm_runtime.version.get_version_info()
from qiskit.tools.jupyter import *
%qiskit_version_table
%qiskit_copyright
|
https://github.com/Heisenbug-s-Dog/qnn_visualization
|
Heisenbug-s-Dog
|
from google.colab import drive
drive.mount('/content/drive')
!pip install torch==1.3.1
!pip install torchvision==0.4.2
!pip install Pillow==6.2.1
!pip install pennylane==0.7.0
# OpenMP: number of parallel threads.
%env OMP_NUM_THREADS=1
# Plotting
%matplotlib inline
import matplotlib.pyplot as plt
# PyTorch
import torch
import torch.nn as nn
import torch.optim as optim
from torch.optim import lr_scheduler
import torchvision
from torchvision import datasets, models, transforms
# Pennylane
import pennylane as qml
from pennylane import numpy as np
# Other tools
import time
import copy
filtered_classes = ['cat', 'dog'] # Subset of CIFAR ('plane', 'car', 'bird', 'cat','deer', 'dog', 'frog', 'horse', 'ship', 'truck')
n_qubits = 4 # Number of qubits
quantum = True # If set to "False", the dressed quantum circuit is replaced by
# An enterily classical net (defined by the next parameter).
classical_model = '512_n' # Possible choices: '512_n','512_nq_n','551_512_n'. [nq=n_qubits, n=num_filtered_classes]
step = 0.001 # Learning rate
batch_size = 8 # Number of samples for each training step
num_epochs = 3 # Number of training epochs
q_depth = 5 # Depth of the quantum circuit (number of variational layers)
gamma_lr_scheduler = 1 # Learning rate reduction applied every 10 epochs.
max_layers = 15 # Keep 15 even if not all are used.
q_delta = 0.01 # Initial spread of random quantum weights
rng_seed = 0 # Seed for random number generator
start_time = time.time() # start of the computation timer
torch.manual_seed(rng_seed)
dev = qml.device('default.qubit', wires=n_qubits)
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
def H_layer(nqubits):
"""Layer of single-qubit Hadamard gates.
"""
for idx in range(nqubits):
qml.Hadamard(wires=idx)
def RY_layer(w):
"""Layer of parametrized qubit rotations around the y axis.
"""
for idx, element in enumerate(w):
qml.RY(element, wires=idx)
def entangling_layer(nqubits):
"""Layer of CNOTs followed by another shifted layer of CNOT.
"""
# In other words it should apply something like :
# CNOT CNOT CNOT CNOT... CNOT
# CNOT CNOT CNOT... CNOT
for i in range(0, nqubits - 1, 2): # Loop over even indices: i=0,2,...N-2
qml.CNOT(wires=[i, i + 1])
for i in range(1, nqubits - 1,2): # Loop over odd indices: i=1,3,...N-3
qml.CNOT(wires=[i, i + 1])
@qml.qnode(dev, interface='torch')
def q_net(q_in, q_weights_flat):
# Reshape weights
q_weights = q_weights_flat.reshape(max_layers, n_qubits)
# Start from state |+> , unbiased w.r.t. |0> and |1>
H_layer(n_qubits)
# Embed features in the quantum node
RY_layer(q_in)
# Sequence of trainable variational layers
for k in range(q_depth):
entangling_layer(n_qubits)
RY_layer(q_weights[k+1])
# Expectation values in the Z basis
return [qml.expval(qml.PauliZ(j)) for j in range(n_qubits)]
class Quantumnet(nn.Module):
def __init__(self):
super().__init__()
self.pre_net = nn.Linear(512, n_qubits)
self.q_params = nn.Parameter(q_delta * torch.randn(max_layers * n_qubits))
self.post_net = nn.Linear(n_qubits, len(filtered_classes))
def forward(self, input_features):
pre_out = self.pre_net(input_features)
q_in = torch.tanh(pre_out) * np.pi / 2.0
# Apply the quantum circuit to each element of the batch, and append to q_out
q_out = torch.Tensor(0, n_qubits)
q_out = q_out.to(device)
for elem in q_in:
q_out_elem = q_net(elem,self.q_params).float().unsqueeze(0)
q_out = torch.cat((q_out, q_out_elem))
return self.post_net(q_out)
class Quantumnet_Cut(nn.Module):
def __init__(self):
super().__init__()
self.pre_net = nn.Linear(512, n_qubits)
self.q_params = nn.Parameter(q_delta * torch.randn(max_layers * n_qubits))
def forward(self, input_features):
pre_out = self.pre_net(input_features)
q_in = torch.tanh(pre_out) * np.pi / 2.0
# Apply the quantum circuit to each element of the batch, and append to q_out
q_out = torch.Tensor(0, n_qubits)
q_out = q_out.to(device)
for elem in q_in:
q_out_elem = q_net(elem,self.q_params).float().unsqueeze(0)
q_out = torch.cat((q_out, q_out_elem))
return q_out
class Quantumnet_Classical_Cut(nn.Module):
def __init__(self):
super().__init__()
self.pre_net = nn.Linear(512, n_qubits)
self.q_params = nn.Parameter(q_delta * torch.randn(max_layers * n_qubits))
def forward(self, input_features):
pre_out = self.pre_net(input_features)
q_in = torch.tanh(pre_out) * np.pi / 2.0
return q_in
model = torchvision.models.resnet18(pretrained=True)
model.fc = Quantumnet()
for param in model.parameters():
param.requires_grad = False
# Use CUDA or CPU according to the "device" object.
model = model.to(device)
model_cut = torchvision.models.resnet18(pretrained=True)
model_cut.fc = Quantumnet_Cut()
for param in model_cut.parameters():
param.requires_grad = False
# Use CUDA or CPU according to the "device" object.
model_cut = model_cut.to(device)
model_classical_cut = torchvision.models.resnet18(pretrained=True)
model_classical_cut.fc = Quantumnet_Classical_Cut()
for param in model_classical_cut.parameters():
param.requires_grad = False
# Use CUDA or CPU according to the "device" object.
model_classical_cut = model_classical_cut.to(device)
# Load model from file
path = '/content/drive/MyDrive/Qiskit-Hackathon-Korea/qnn-visualization/'
if quantum:
model.load_state_dict(torch.load(
path+'quantum_' + filtered_classes[0] + '_' + filtered_classes[1] + '.pt'
)
)
else:
model.load_state_dict(torch.load(
path+'classical_' + filtered_classes[0] + '_' + filtered_classes[1] + '.pt'
)
)
model_dict = model.state_dict()
model_cut_dict = model_cut.state_dict()
model_cut_dict = {k: v for k, v in model_dict.items() if k in model_cut_dict}
model_cut.load_state_dict(model_cut_dict)
model_classical_cut_dict = model_classical_cut.state_dict()
model_classical_cut_dict = {k: v for k, v in model_dict.items() if k in model_classical_cut_dict}
model_classical_cut.load_state_dict(model_classical_cut_dict)
def dream(image, model, iterations, lr):
""" Updates the image to maximize outputs for n iterations """
Tensor = torch.cuda.FloatTensor if torch.cuda.is_available else torch.FloatTensor
image = preprocess(image).unsqueeze(0).cpu().data.numpy()
image = Variable(Tensor(image), requires_grad=True)
for i in range(iterations):
model.zero_grad()
out = model(image)
loss = out.norm()
if i % 10 == 0:
print('iter: {}/{}, loss: {}'.format(i+1, iterations, loss.item()))
loss.backward()
avg_grad = np.abs(image.grad.data.cpu().numpy()).mean()
norm_lr = lr / avg_grad
image.data += norm_lr * image.grad.data
image.data = clip(image.data)
image.grad.data.zero_()
return image.cpu().data.numpy()
def diff_dream(image, model1, model2, iterations, lr):
""" Updates the image to maximize outputs for n iterations """
Tensor = torch.cuda.FloatTensor if torch.cuda.is_available else torch.FloatTensor
image = preprocess(image).unsqueeze(0).cpu().data.numpy()
image = Variable(Tensor(image), requires_grad=True)
for i in range(iterations):
model1.zero_grad()
model2.zero_grad()
out1 = model1(image)
out2 = model2(image)
loss = out1.norm() / np.sqrt(np.prod(out1.shape)) - out2.norm() / np.sqrt(np.prod(out2.shape))
if i % 10 == 0:
print('iter: {}/{}, loss: {}'.format(i+1, iterations, loss.item()))
loss.backward()
avg_grad = np.abs(image.grad.data.cpu().numpy()).mean()
norm_lr = lr / avg_grad
image.data += norm_lr * image.grad.data
image.data = clip(image.data)
image.grad.data.zero_()
return image.cpu().data.numpy()
def deep_dream(image, model, iterations, lr, octave_scale, num_octaves):
""" Main deep dream method """
image = preprocess(image).unsqueeze(0).cpu().data.numpy()
# Extract image representations for each octave
octaves = [image]
for _ in range(num_octaves - 1):
octaves.append(nd.zoom(octaves[-1], (1, 1, 1 / octave_scale, 1 / octave_scale), order=1))
detail = np.zeros_like(octaves[-1])
for octave, octave_base in enumerate(tqdm.tqdm(octaves[::-1], desc="Dreaming")):
if octave > 0:
# Upsample detail to new octave dimension
detail = nd.zoom(detail, np.array(octave_base.shape) / np.array(detail.shape), order=1)
# Add deep dream detail from previous octave to new base
input_image = octave_base + detail
# Get new deep dream image
dreamed_image = dream(input_image, model, iterations, lr)
# Extract deep dream details
detail = dreamed_image - octave_base
return deprocess(dreamed_image)
mean = np.array([0.485, 0.456, 0.406])
std = np.array([0.229, 0.224, 0.225])
#preprocess = transforms.Compose([transforms.ToTensor(), transforms.Normalize(mean, std)])
preprocess = transforms.Compose([transforms.ToTensor()])
def deprocess(image_np):
image_np = image_np.squeeze().transpose(1, 2, 0)
image_np = image_np * std.reshape((1, 1, 3)) + mean.reshape((1, 1, 3))
image_np = np.clip(image_np, 0.0, 255.0)
return image_np
def clip(image_tensor):
for c in range(3):
m, s = mean[c], std[c]
image_tensor[0, c] = torch.clamp(image_tensor[0, c], -m / s, (1 - m) / s)
return image_tensor
from PIL import Image
import scipy.ndimage as nd
from torch.autograd import Variable
import tqdm, os
# Load image
image = Image.open("/content/drive/MyDrive/Qiskit-Hackathon-Korea/qnn-visualization/images/dog.jpg")
# Set Models
#network = model
#layers = list(network.children())
#classical_model = nn.Sequential(*layers[: 9]) #Max: 9
classical_model = model_classical_cut
quantum_model = model_cut
# Extract deep dream image
dreamed_image = dream(
image,
quantum_model,
iterations=1000,
lr=0.01
)
dreamed_image = np.transpose(dreamed_image, (0,2,3,1))
dreamed_image = dreamed_image[0]
# Save and plot image
#os.makedirs("outputs", exist_ok=True)
#filename = 'test'
plt.figure(figsize=(20, 20))
plt.imshow(dreamed_image)
#plt.imsave(f"outputs/output_{filename}", dreamed_image)
plt.show()
quantum_dreamed_image = diff_dream(
image,
quantum_model,
classical_model,
iterations=1000,
lr=0.01
)
dreamed_image = quantum_dreamed_image
dreamed_image = np.transpose(dreamed_image, (0,2,3,1))
dreamed_image = dreamed_image[0]
# Save and plot image
#os.makedirs("outputs", exist_ok=True)
#filename = 'test'
plt.figure(figsize=(20, 20))
plt.imshow(dreamed_image)
#plt.imsave(f"outputs/output_{filename}", dreamed_image)
plt.show()
classical_dreamed_image = diff_dream(
image,
classical_model,
quantum_model,
iterations=1000,
lr=0.01
)
dreamed_image = classical_dreamed_image
dreamed_image = np.transpose(dreamed_image, (0,2,3,1))
dreamed_image = dreamed_image[0]
# Save and plot image
#os.makedirs("outputs", exist_ok=True)
#filename = 'test'
plt.figure(figsize=(20, 20))
plt.imshow(dreamed_image)
#plt.imsave(f"outputs/output_{filename}", dreamed_image)
plt.show()
|
https://github.com/swe-train/qiskit__qiskit
|
swe-train
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
# pylint: disable=missing-docstring
import unittest
import os
from unittest.mock import patch
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit.test import QiskitTestCase
from qiskit.utils import optionals
from qiskit import visualization
from qiskit.visualization.circuit import text
from qiskit.visualization.exceptions import VisualizationError
if optionals.HAS_MATPLOTLIB:
from matplotlib import figure
if optionals.HAS_PIL:
from PIL import Image
_latex_drawer_condition = unittest.skipUnless(
all(
(
optionals.HAS_PYLATEX,
optionals.HAS_PIL,
optionals.HAS_PDFLATEX,
optionals.HAS_PDFTOCAIRO,
)
),
"Skipped because not all of PIL, pylatex, pdflatex and pdftocairo are available",
)
class TestCircuitDrawer(QiskitTestCase):
def test_default_output(self):
with patch("qiskit.user_config.get_config", return_value={}):
circuit = QuantumCircuit()
out = visualization.circuit_drawer(circuit)
self.assertIsInstance(out, text.TextDrawing)
@unittest.skipUnless(optionals.HAS_MATPLOTLIB, "Skipped because matplotlib is not available")
def test_user_config_default_output(self):
with patch("qiskit.user_config.get_config", return_value={"circuit_drawer": "mpl"}):
circuit = QuantumCircuit()
out = visualization.circuit_drawer(circuit)
self.assertIsInstance(out, figure.Figure)
def test_default_output_with_user_config_not_set(self):
with patch("qiskit.user_config.get_config", return_value={"other_option": True}):
circuit = QuantumCircuit()
out = visualization.circuit_drawer(circuit)
self.assertIsInstance(out, text.TextDrawing)
@unittest.skipUnless(optionals.HAS_MATPLOTLIB, "Skipped because matplotlib is not available")
def test_kwarg_priority_over_user_config_default_output(self):
with patch("qiskit.user_config.get_config", return_value={"circuit_drawer": "latex"}):
circuit = QuantumCircuit()
out = visualization.circuit_drawer(circuit, output="mpl")
self.assertIsInstance(out, figure.Figure)
@unittest.skipUnless(optionals.HAS_MATPLOTLIB, "Skipped because matplotlib is not available")
def test_default_backend_auto_output_with_mpl(self):
with patch("qiskit.user_config.get_config", return_value={"circuit_drawer": "auto"}):
circuit = QuantumCircuit()
out = visualization.circuit_drawer(circuit)
self.assertIsInstance(out, figure.Figure)
def test_default_backend_auto_output_without_mpl(self):
with patch("qiskit.user_config.get_config", return_value={"circuit_drawer": "auto"}):
with optionals.HAS_MATPLOTLIB.disable_locally():
circuit = QuantumCircuit()
out = visualization.circuit_drawer(circuit)
self.assertIsInstance(out, text.TextDrawing)
@_latex_drawer_condition
def test_latex_unsupported_image_format_error_message(self):
with patch("qiskit.user_config.get_config", return_value={"circuit_drawer": "latex"}):
circuit = QuantumCircuit()
with self.assertRaises(VisualizationError, msg="Pillow could not write the image file"):
visualization.circuit_drawer(circuit, filename="file.spooky")
@_latex_drawer_condition
def test_latex_output_file_correct_format(self):
with patch("qiskit.user_config.get_config", return_value={"circuit_drawer": "latex"}):
circuit = QuantumCircuit()
filename = "file.gif"
visualization.circuit_drawer(circuit, filename=filename)
with Image.open(filename) as im:
if filename.endswith("jpg"):
self.assertIn(im.format.lower(), "jpeg")
else:
self.assertIn(im.format.lower(), filename.split(".")[-1])
os.remove(filename)
def test_wire_order(self):
"""Test wire_order
See: https://github.com/Qiskit/qiskit-terra/pull/9893"""
qr = QuantumRegister(4, "q")
cr = ClassicalRegister(4, "c")
cr2 = ClassicalRegister(2, "ca")
circuit = QuantumCircuit(qr, cr, cr2)
circuit.h(0)
circuit.h(3)
circuit.x(1)
circuit.x(3).c_if(cr, 10)
expected = "\n".join(
[
" ",
" q_2: ββββββββββββ",
" βββββ βββββ ",
" q_3: β€ H βββ€ X ββ",
" βββββ€ βββ₯ββ ",
" q_0: β€ H βββββ«βββ",
" βββββ€ β ",
" q_1: β€ X βββββ«βββ",
" βββββββββ¨βββ",
" c: 4/ββββββ‘ 0xa β",
" βββββββ",
"ca: 2/ββββββββββββ",
" ",
]
)
result = visualization.circuit_drawer(circuit, wire_order=[2, 3, 0, 1])
self.assertEqual(result.__str__(), expected)
def test_wire_order_cregbundle(self):
"""Test wire_order with cregbundle=True
See: https://github.com/Qiskit/qiskit-terra/pull/9893"""
qr = QuantumRegister(4, "q")
cr = ClassicalRegister(4, "c")
cr2 = ClassicalRegister(2, "ca")
circuit = QuantumCircuit(qr, cr, cr2)
circuit.h(0)
circuit.h(3)
circuit.x(1)
circuit.x(3).c_if(cr, 10)
expected = "\n".join(
[
" ",
" q_2: ββββββββββββ",
" βββββ βββββ ",
" q_3: β€ H βββ€ X ββ",
" βββββ€ βββ₯ββ ",
" q_0: β€ H βββββ«βββ",
" βββββ€ β ",
" q_1: β€ X βββββ«βββ",
" βββββββββ¨βββ",
" c: 4/ββββββ‘ 0xa β",
" βββββββ",
"ca: 2/ββββββββββββ",
" ",
]
)
result = visualization.circuit_drawer(circuit, wire_order=[2, 3, 0, 1], cregbundle=True)
self.assertEqual(result.__str__(), expected)
def test_wire_order_raises(self):
"""Verify we raise if using wire order incorrectly."""
circuit = QuantumCircuit(3, 3)
circuit.x(1)
with self.assertRaisesRegex(VisualizationError, "should not have repeated elements"):
visualization.circuit_drawer(circuit, wire_order=[2, 1, 0, 3, 1, 5])
with self.assertRaisesRegex(VisualizationError, "cannot be set when the reverse_bits"):
visualization.circuit_drawer(circuit, wire_order=[0, 1, 2, 5, 4, 3], reverse_bits=True)
with self.assertWarnsRegex(RuntimeWarning, "cregbundle set"):
visualization.circuit_drawer(circuit, cregbundle=True, wire_order=[0, 1, 2, 5, 4, 3])
def test_reverse_bits(self):
"""Test reverse_bits should not raise warnings when no classical qubits:
See: https://github.com/Qiskit/qiskit-terra/pull/8689"""
circuit = QuantumCircuit(3)
circuit.x(1)
expected = "\n".join(
[
" ",
"q_2: βββββ",
" βββββ",
"q_1: β€ X β",
" βββββ",
"q_0: βββββ",
" ",
]
)
result = visualization.circuit_drawer(circuit, output="text", reverse_bits=True)
self.assertEqual(result.__str__(), expected)
@unittest.skipUnless(optionals.HAS_PYLATEX, "needs pylatexenc for LaTeX conversion")
def test_no_explict_cregbundle(self):
"""Test no explicit cregbundle should not raise warnings about being disabled
See: https://github.com/Qiskit/qiskit-terra/issues/8690"""
inner = QuantumCircuit(1, 1, name="inner")
inner.measure(0, 0)
circuit = QuantumCircuit(2, 2)
circuit.append(inner, [0], [0])
expected = "\n".join(
[
" ββββββββββ",
"q_0: β€0 β",
" β β",
"q_1: β€ inner β",
" β β",
"c_0: β‘0 β",
" ββββββββββ",
"c_1: ββββββββββ",
" ",
]
)
result = circuit.draw("text")
self.assertEqual(result.__str__(), expected)
# Extra tests that no cregbundle (or any other) warning is raised with the default settings
# for the other drawers, if they're available to test.
circuit.draw("latex_source")
if optionals.HAS_MATPLOTLIB and optionals.HAS_PYLATEX:
circuit.draw("mpl")
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, QuantumRegister
from qiskit.circuit.library.standard_gates import HGate
qc1 = QuantumCircuit(2)
qc1.x(0)
qc1.h(1)
custom = qc1.to_gate().control(2)
qc2 = QuantumCircuit(4)
qc2.append(custom, [0, 3, 1, 2])
qc2.draw('mpl')
|
https://github.com/orionhunts-ai/QiskitRuskit
|
orionhunts-ai
|
from qiskit import QuantumCircuit
from qiskit.quantum_info import SparsePauliOp
from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager
from qiskit_ibm_runtime import QiskitRuntimeService, EstimatorV2 as Estimator
# Create a new circuit with two qubits (first argument) and two classical
# bits (second argument)
qc = QuantumCircuit(2)
# Add a Hadamard gate to qubit 0
qc.h(0)
# Perform a controlled-X gate on qubit 1, controlled by qubit 0
qc.cx(0, 1)
# Return a drawing of the circuit using MatPlotLib ("mpl"). This is the
# last line of the cell, so the drawing appears in the cell output.
# Remove the "mpl" argument to get a text drawing.
qc.draw("mpl")
|
https://github.com/Simultonian/hamilutor-qiskit
|
Simultonian
|
from qiskit import QuantumCircuit
from qiskit.opflow import PauliTrotterEvolution, X, Y, Z, I # For `eval`
from ..utils.repr import qiskit_string_repr, qiskit_string_repr_pauli
def trotter_from_terms(terms: list[tuple[str, float]]) -> QuantumCircuit:
"""
API that takes a list of terms that must be exponentiated in the specific
order, that may or may not have repetitions. The coefficients are assumed
to already account the time scaling.
Input:
- terms: list of pairs of pauli operator and the coefficient.
Returns: Quantum Circuit with exponentiation in the defined ordered.
"""
num_qubits = len(terms[0][0])
final_circuit = QuantumCircuit(num_qubits)
for term in terms:
final_circuit = final_circuit.compose(trotter_from_term(term))
return final_circuit
def trotter_from_term(term: tuple[str, float]) -> QuantumCircuit:
pauli_op = eval(qiskit_string_repr_pauli(term))
evolution_op = pauli_op.exp_i()
trotterized_op = PauliTrotterEvolution(trotter_mode="trotter").convert(evolution_op)
return trotterized_op.to_circuit()
def trotter(h: dict[str, float], t: float = 1.0, reps: int = 1) -> QuantumCircuit:
"""
API that takes Hamiltonian in a familiar format along with time and creates
circuit that simulates the same using simple Trotterization.
Input:
- h: Hamiltonian in Pauli basis along with coefficients
- t: Time
- reps: The number of times to repeat trotterization steps.
Returns: Quantum Circuit for simulation
"""
hamiltonian = eval(qiskit_string_repr(h))
# evolution operator
evolution_op = ((t / reps) * hamiltonian).exp_i()
# into circuit
trotterized_op = PauliTrotterEvolution(trotter_mode="trotter", reps=reps).convert(
evolution_op
)
return trotterized_op.to_circuit()
|
https://github.com/urwin419/QiskitChecker
|
urwin419
|
from qiskit import QuantumCircuit
def create_bell_pair():
qc = QuantumCircuit(2)
### replaced x gate ###
qc.x(1)
qc.cx(1, 0)
return qc
def encode_message(qc, qubit, msg):
if len(msg) != 2 or not set([0,1]).issubset({0,1}):
raise ValueError(f"message '{msg}' is invalid")
if msg[1] == "1":
qc.x(qubit)
if msg[0] == "1":
qc.z(qubit)
return qc
def decode_message(qc):
qc.cx(1, 0)
### replaced x gate ###
qc.x(1)
return qc
|
https://github.com/MonitSharma/qiskit-projects
|
MonitSharma
|
import numpy as np
import random
import matplotlib.pyplot as plt
from sklearn.neighbors import KNeighborsClassifier
from sklearn.neighbors import NearestCentroid
from IPython.display import clear_output
import pandas as pd
# =======================================================
import math
import time
from qiskit import Aer, QuantumCircuit, execute
from qiskit.extensions import UnitaryGate
from qiskit.providers.jobstatus import JobStatus
import cv2
# Use Aer's qasm_simulator by default
backend = Aer.get_backend('qasm_simulator')
# generate chess board data: random 8 x 8 board
def generate_chess():
'''
Generates a random board of dimensions 8 x 8
Outputs:
board := flattened 8 x 8 array
winner := red wins == 1, blue wins == -1
sum_red := sum of red pieces
sum_blue := sum of blue pieces
'''
board=np.zeros((8*8))
board_label=np.zeros((8*8)).astype(object)
# Assign chess piece point values, names, max pieces per board
# dictionary key: {'name':[points, max_pieces]}
piece_list_w=['pawn_w','knight_w','bishop_w','rook_w','queen_w','king_w']
piece_list_b=['pawn_b','knight_b','bishop_b','rook_b','queen_b','king_b']
chess_values_w = {'pawn_w':[1,8],'knight_w':[3,2],'bishop_w':[3,2],'rook_w':[5,2],'queen_w':[9,1],'king_w':[40,1]}
chess_values_b = {'pawn_b':[1,8],'knight_b':[3,2],'bishop_b':[3,2],'rook_b':[5,2],'queen_b':[9,1],'king_b':[40,1]}
# generate random number of chess pieces with bounds for white and black (there must be at least a king for each side)
piece_locations_white=np.zeros((len(piece_list_w),3)).astype(object)
piece_locations_black=np.zeros((len(piece_list_b),3)).astype(object)
piece_locations_white[0]=['king_w',chess_values_w['king_w'][0],chess_values_w['king_w'][1]]
piece_locations_black[0]=['king_b',chess_values_b['king_b'][0],chess_values_b['king_b'][1]]
for n in range(len(piece_list_w)-1): # skip king because there must be a king
points_w,max_pieces_w=chess_values_w[piece_list_w[n]]
points_b,max_pieces_b=chess_values_b[piece_list_b[n]]
piece_locations_white[n+1,:]=[piece_list_w[n],points_w,random.sample(range(0,max_pieces_w+1),1)[0]]
piece_locations_black[n+1,:]=[piece_list_b[n],points_b,random.sample(range(0,max_pieces_b+1),1)[0]]
black_pieces=int(np.sum(piece_locations_black[:,2])) # count black pieces
white_pieces=int(np.sum(piece_locations_white[:,2])) # count white pieces
total_pieces=black_pieces+white_pieces # total number of pieces on the board
all_piece_locations=random.sample(range(0,8*8),total_pieces)
index=0
for n in range(len(piece_list_b)): # black piece location assignment
for p in range(piece_locations_black[n,2]):
board[all_piece_locations[index]]= piece_locations_black[n,1] # populate with piece value
board_label[all_piece_locations[index]]= piece_locations_black[n,0] # populate with piece name
index+=1
for n in range(len(piece_list_w)): # white piece location assignment
for p in range(piece_locations_white[n,2]):
board[all_piece_locations[index]]= -piece_locations_white[n,1] # populate with piece value
board_label[all_piece_locations[index]]= piece_locations_white[n,0] # populate with piece name
index+=1
sum_black=np.sum(piece_locations_black[:,1]*piece_locations_black[:,2])
sum_white=np.sum(piece_locations_white[:,1]*piece_locations_white[:,2])
return board, board_label, sum_black, sum_white
def chessBoardShow(chessBoard):
chessBoard = chessBoard.reshape(8, 8)
filepath='meta/chess/B.Knight.png'
kb=cv2.imread(filepath,cv2.IMREAD_UNCHANGED)
filepath='meta/chess/B.Bish.png'
bb=cv2.imread(filepath,cv2.IMREAD_UNCHANGED)
filepath='meta/chess/B.Quee.png'
qb=cv2.imread(filepath,cv2.IMREAD_UNCHANGED)
filepath='meta/chess/B.Rook.png'
rb=cv2.imread(filepath,cv2.IMREAD_UNCHANGED)
filepath='meta/chess/B.Pawn.png'
pb=cv2.imread(filepath,cv2.IMREAD_UNCHANGED)
filepath='meta/chess/B.King.png'
kib=cv2.imread(filepath,cv2.IMREAD_UNCHANGED)
filepath='meta/chess/W.Knight.png'
kw=cv2.imread(filepath,cv2.IMREAD_UNCHANGED)
filepath='meta/chess/W.Bish.png'
bw=cv2.imread(filepath,cv2.IMREAD_UNCHANGED)
filepath='meta/chess/W.Quee.png'
qw=cv2.imread(filepath,cv2.IMREAD_UNCHANGED)
filepath='meta/chess/W.Rook.png'
rw=cv2.imread(filepath,cv2.IMREAD_UNCHANGED)
filepath='meta/chess/W.Pawn.png'
pw=cv2.imread(filepath,cv2.IMREAD_UNCHANGED)
filepath='meta/chess/W.King.png'
kiw=cv2.imread(filepath,cv2.IMREAD_UNCHANGED)
filepath='meta/chess/trans.png'
trans=cv2.imread(filepath,cv2.IMREAD_UNCHANGED)
chessPiece = {
"knight_b":kb,
"bishop_b": bb,
"queen_b": qb,
"rook_b": rb,
"pawn_b": pb,
"king_b": kib,
"knight_w": kw,
"bishop_w": bw,
"queen_w": qw,
"rook_w": rw,
"pawn_w": pw,
"king_w": kiw,
0.0: trans
}
import warnings
warnings.filterwarnings("ignore", category=DeprecationWarning)
def pictureSelect(n,m):
try:
dictPiece = chessPiece[chessBoard[n][m]]
if dictPiece != trans:
ax[n,m].imshow(dictPiece,cmap='bone')
except (Exception):
pass
fig,ax=plt.subplots(figsize=(8,1))
ax.set_facecolor('grey')
ax.set_xticks([])
ax.set_yticks([])
ax.text(0.2,0.2,'Black Side',fontsize=45,c='w')
plt.show()
fig,ax=plt.subplots(ncols=8,nrows=8,figsize=(8,8))
for n in range(8):
for m in range(8):
count = 0
if (m % 2 != 0):
count += 1
if ((n % 2) == 0):
count += 1
if count == 2:
ax[n,m].set_facecolor('grey')
count = 0
if (m % 2 == 0):
count += 1
if ((n % 2) != 0):
count += 1
if count == 2:
ax[n,m].set_facecolor('grey')
ax[n,m].set_xticks([])
ax[n,m].set_yticks([])
pictureSelect(n,m)
fig,ax=plt.subplots(figsize=(8,1))
ax.set_facecolor('white')
ax.set_xticks([])
ax.set_yticks([])
ax.text(0.2,0.2,'White Side',fontsize=45,c='k')
plt.show()
def generate_best_move():
# create a board and make sure kings are at least 11 spaces away from each other
board, board_label, sum_black, sum_white=generate_chess() # generate board
king_b=np.where(board_label=='king_b')[0][0]
king_w=np.where(board_label=='king_w')[0][0]
while np.abs(king_b-king_w) < 11:
board, board_label, sum_black, sum_white=generate_chess()
king_b=np.where(board_label=='king_b')[0][0]
king_w=np.where(board_label=='king_w')[0][0]
board_label_sq=board_label.reshape(8,8)
# Assign chess piece point values, names, max pieces per board
# dictionary key: {'name':[points, max_pieces]}
piece_list_w=np.array(['pawn_w','knight_w','bishop_w','rook_w','queen_w','king_w'])
piece_list_b=np.array(['pawn_b','knight_b','bishop_b','rook_b','queen_b','king_b'])
chess_values_w = {'pawn_w':[1,8],'knight_w':[3,2],'bishop_w':[3,2],'rook_w':[5,2],'queen_w':[9,1],'king_w':[40,1]}
chess_values_b = {'pawn_b':[1,8],'knight_b':[3,2],'bishop_b':[3,2],'rook_b':[5,2],'queen_b':[9,1],'king_b':[40,1]}
# white starts on the bottom for our board
white_scores=[]
black_scores=[]
# we have to iterate on every piece to see what the best legal move is that gets the highest point value
for n in range(8): # rows
for m in range(8): # columns
# =========================================
if board_label_sq[n,m]=='pawn_w': # white pawn
take1 = 0.0
take2 = 0.0
take3 = 0.0
take4 = 0.0
pawn_w_take=[0]
if m==0 and n>0:
take1 = board_label_sq[n-1,m+1] # col 0, row +1
elif 7>m>0 and n>0:
take2 = board_label_sq[n-1,m+1] # col 0-6, row +1
take3 = board_label_sq[n-1,m-1] # col 0-6, row -1
elif m==7 and n>0:
take4 = board_label_sq[n-1,m-1] # col 7, row -1
if take1!=0 and np.sum(take1==piece_list_b)>0:
pawn_w_take.append(chess_values_b[take1][0])
if take2!=0 and np.sum(take2==piece_list_b)>0:
pawn_w_take.append(chess_values_b[take2][0])
if take3!=0 and np.sum(take3==piece_list_b)>0:
pawn_w_take.append(chess_values_b[take3][0])
if take4!=0 and np.sum(take4==piece_list_b)>0:
pawn_w_take.append(chess_values_b[take4][0])
else:
pass
white_scores.append(np.max(pawn_w_take))
# =========================================
elif board_label_sq[n,m]=='pawn_b': # black pawn
take1 = 0.0
take2 = 0.0
take3 = 0.0
take4 = 0.0
pawn_b_take=[0]
if m==0 and n<7:
take1 = board_label_sq[n+1,m+1] # col 0, row +1
elif 7>m>0 and n<7:
take2 = board_label_sq[n+1,m+1] # col 0-6, row +1
take3 = board_label_sq[n+1,m-1] # col 0-6, row -1
elif m==7 and n<7:
take4 = board_label_sq[n+1,m-1] # col 7, row -1
if take1!=0 and np.sum(take1==piece_list_w)>0:
pawn_b_take.append(chess_values_w[take1][0])
if take2!=0 and np.sum(take2==piece_list_w)>0:
pawn_b_take.append(chess_values_w[take2][0])
if take3!=0 and np.sum(take3==piece_list_w)>0:
pawn_b_take.append(chess_values_w[take3][0])
if take4!=0 and np.sum(take4==piece_list_w)>0:
pawn_b_take.append(chess_values_w[take4][0])
else:
pass
black_scores.append(np.max(pawn_b_take))
# =========================================
elif board_label_sq[n,m]=='bishop_w': # white bishop
take1=0.0
take2=0.0
take3=0.0
take4=0.0
bishop_w_take=[0]
for bishw in range(7):
if n+bishw<7 and m+bishw<7:
take1 = board_label_sq[n+bishw+1,m+bishw+1] # col +1, row +1
if take1!=0:
break
for bishw in range(7):
if n+bishw<7 and m-bishw>0:
take2 = board_label_sq[n+bishw+1,m-bishw-1] # col -1, row +1
if take2!=0:
break
for bishw in range(7):
if n-bishw>0 and m+bishw<7:
take3 = board_label_sq[n-bishw-1,m+bishw+1] # col +1, row -1
if take3!=0:
break
for bishw in range(7):
if n-bishw>0 and m-bishw>0:
take4 = board_label_sq[n-bishw-1,m-bishw-1] # col -1, row -1
if take4!=0:
break
if take1!=0 and np.sum(take1==piece_list_b)>0:
bishop_w_take.append(chess_values_b[take1][0])
if take2!=0 and np.sum(take2==piece_list_b)>0:
bishop_w_take.append(chess_values_b[take2][0])
if take3!=0 and np.sum(take3==piece_list_b)>0:
bishop_w_take.append(chess_values_b[take3][0])
if take4!=0 and np.sum(take4==piece_list_b)>0:
bishop_w_take.append(chess_values_b[take4][0])
else:
pass
white_scores.append(np.max(bishop_w_take))
# =========================================
elif board_label_sq[n,m]=='bishop_b': # black bishop
take1=0.0
take2=0.0
take3=0.0
take4=0.0
bishop_b_take=[0]
for bishw in range(7):
if n+bishw<7 and m+bishw<7:
take1 = board_label_sq[n+bishw+1,m+bishw+1] # col +1, row +1
if take1!=0:
break
for bishw in range(7):
if n+bishw<7 and m-bishw>0:
take2 = board_label_sq[n+bishw+1,m-bishw-1] # col -1, row +1
if take2!=0:
break
for bishw in range(7):
if n-bishw>0 and m+bishw<7:
take3 = board_label_sq[n-bishw-1,m+bishw+1] # col +1, row -1
if take3!=0:
break
for bishw in range(7):
if n-bishw>0 and m-bishw>0:
take4 = board_label_sq[n-bishw-1,m-bishw-1] # col -1, row -1
if take4!=0:
break
if take1!=0 and np.sum(take1==piece_list_w)>0:
bishop_b_take.append(chess_values_w[take1][0])
if take2!=0 and np.sum(take2==piece_list_w)>0:
bishop_b_take.append(chess_values_w[take2][0])
if take3!=0 and np.sum(take3==piece_list_w)>0:
bishop_b_take.append(chess_values_w[take3][0])
if take4!=0 and np.sum(take4==piece_list_w)>0:
bishop_b_take.append(chess_values_w[take4][0])
else:
pass
black_scores.append(np.max(bishop_b_take))
# =========================================
elif board_label_sq[n,m]=='rook_w': # white rook
take1=0.0
take2=0.0
take3=0.0
take4=0.0
rook_w_take=[0]
for bishw in range(7):
if n+bishw<7:
take1 = board_label_sq[n+bishw+1,m] # col 0, row +1
if take1!=0:
break
for bishw in range(7):
if m-bishw>0:
take2 = board_label_sq[n,m-bishw-1] # col -1, row 0
if take2!=0:
break
for bishw in range(7):
if m+bishw<7:
take3 = board_label_sq[n,m+bishw+1] # col +1, row 0
if take3!=0:
break
for bishw in range(7):
if n-bishw>0:
take4 = board_label_sq[n-bishw-1,m] # col 0, row -1
if take4!=0:
break
if take1!=0 and np.sum(take1==piece_list_b)>0:
rook_w_take.append(chess_values_b[take1][0])
if take2!=0 and np.sum(take2==piece_list_b)>0:
rook_w_take.append(chess_values_b[take2][0])
if take3!=0 and np.sum(take3==piece_list_b)>0:
rook_w_take.append(chess_values_b[take3][0])
if take4!=0 and np.sum(take4==piece_list_b)>0:
rook_w_take.append(chess_values_b[take4][0])
else:
pass
white_scores.append(np.max(rook_w_take))
# =========================================
elif board_label_sq[n,m]=='rook_b': # black rook
take1=0.0
take2=0.0
take3=0.0
take4=0.0
rook_b_take=[0]
for bishw in range(7):
if n+bishw<7:
take1 = board_label_sq[n+bishw+1,m] # col 0, row +1
if take1!=0:
break
for bishw in range(7):
if m-bishw>0:
take2 = board_label_sq[n,m-bishw-1] # col -1, row 0
if take2!=0:
break
for bishw in range(7):
if m+bishw<7:
take3 = board_label_sq[n,m+bishw+1] # col +1, row 0
if take3!=0:
break
for bishw in range(7):
if n-bishw>0:
take4 = board_label_sq[n-bishw-1,m] # col 0, row -1
if take4!=0:
break
if take1!=0 and np.sum(take1==piece_list_w)>0:
rook_b_take.append(chess_values_w[take1][0])
if take2!=0 and np.sum(take2==piece_list_w)>0:
rook_b_take.append(chess_values_w[take2][0])
if take3!=0 and np.sum(take3==piece_list_w)>0:
rook_b_take.append(chess_values_w[take3][0])
if take4!=0 and np.sum(take4==piece_list_w)>0:
rook_b_take.append(chess_values_w[take4][0])
else:
pass
black_scores.append(np.max(rook_b_take))
# =========================================
elif board_label_sq[n,m]=='queen_w': # white queen
take1=0.0
take2=0.0
take3=0.0
take4=0.0
take5=0.0
take6=0.0
take7=0.0
take8=0.0
queen_w_take=[0]
for bishw in range(7):
if n+bishw<7:
take1 = board_label_sq[n+bishw+1,m] # col 0, row +1
if take1!=0:
break
for bishw in range(7):
if m-bishw>0:
take2 = board_label_sq[n,m-bishw-1] # col -1, row 0
if take2!=0:
break
for bishw in range(7):
if m+bishw<7:
take3 = board_label_sq[n,m+bishw+1] # col +1, row 0
if take3!=0:
break
for bishw in range(7):
if n-bishw>0:
take4 = board_label_sq[n-bishw-1,m] # col 0, row -1
if take4!=0:
break
for bishw in range(7):
if n+bishw<7 and m+bishw<7:
take5 = board_label_sq[n+bishw+1,m+bishw+1] # col +1, row +1
if take5!=0:
break
for bishw in range(7):
if n+bishw<7 and m-bishw>0:
take6 = board_label_sq[n+bishw+1,m-bishw-1] # col -1, row +1
if take6!=0:
break
for bishw in range(7):
if n-bishw>0 and m+bishw<7:
take7 = board_label_sq[n-bishw-1,m+bishw+1] # col +1, row -1
if take7!=0:
break
for bishw in range(7):
if n-bishw>0 and m-bishw>0:
take8 = board_label_sq[n-bishw-1,m-bishw-1] # col -1, row -1
if take8!=0:
break
if take1!=0 and np.sum(take1==piece_list_b)>0:
queen_w_take.append(chess_values_b[take1][0])
if take2!=0 and np.sum(take2==piece_list_b)>0:
queen_w_take.append(chess_values_b[take2][0])
if take3!=0 and np.sum(take3==piece_list_b)>0:
queen_w_take.append(chess_values_b[take3][0])
if take4!=0 and np.sum(take4==piece_list_b)>0:
queen_w_take.append(chess_values_b[take4][0])
if take5!=0 and np.sum(take5==piece_list_b)>0:
queen_w_take.append(chess_values_b[take5][0])
if take6!=0 and np.sum(take6==piece_list_b)>0:
queen_w_take.append(chess_values_b[take6][0])
if take7!=0 and np.sum(take7==piece_list_b)>0:
queen_w_take.append(chess_values_b[take7][0])
if take8!=0 and np.sum(take8==piece_list_b)>0:
queen_w_take.append(chess_values_b[take8][0])
else:
pass
white_scores.append(np.max(queen_w_take))
# =========================================
elif board_label_sq[n,m]=='queen_b': # black queen
take1=0.0
take2=0.0
take3=0.0
take4=0.0
take5=0.0
take6=0.0
take7=0.0
take8=0.0
queen_b_take=[0]
for bishw in range(7):
if n+bishw<7:
take1 = board_label_sq[n+bishw+1,m] # col 0, row +1
if take1!=0:
break
for bishw in range(7):
if m-bishw>0:
take2 = board_label_sq[n,m-bishw-1] # col -1, row 0
if take2!=0:
break
for bishw in range(7):
if m+bishw<7:
take3 = board_label_sq[n,m+bishw+1] # col +1, row 0
if take3!=0:
break
for bishw in range(7):
if n-bishw>0:
take4 = board_label_sq[n-bishw-1,m] # col 0, row -1
if take4!=0:
break
for bishw in range(7):
if n+bishw<7 and m+bishw<7:
take5 = board_label_sq[n+bishw+1,m+bishw+1] # col +1, row +1
if take5!=0:
break
for bishw in range(7):
if n+bishw<7 and m-bishw>0:
take6 = board_label_sq[n+bishw+1,m-bishw-1] # col -1, row +1
if take6!=0:
break
for bishw in range(7):
if n-bishw>0 and m+bishw<7:
take7 = board_label_sq[n-bishw-1,m+bishw+1] # col +1, row -1
if take7!=0:
break
for bishw in range(7):
if n-bishw>0 and m-bishw>0:
take8 = board_label_sq[n-bishw-1,m-bishw-1] # col -1, row -1
if take8!=0:
break
if take1!=0 and np.sum(take1==piece_list_w)>0:
queen_b_take.append(chess_values_w[take1][0])
if take2!=0 and np.sum(take2==piece_list_w)>0:
queen_b_take.append(chess_values_w[take2][0])
if take3!=0 and np.sum(take3==piece_list_w)>0:
queen_b_take.append(chess_values_w[take3][0])
if take4!=0 and np.sum(take4==piece_list_w)>0:
queen_b_take.append(chess_values_w[take4][0])
if take5!=0 and np.sum(take5==piece_list_w)>0:
queen_b_take.append(chess_values_w[take5][0])
if take6!=0 and np.sum(take6==piece_list_w)>0:
queen_b_take.append(chess_values_w[take6][0])
if take7!=0 and np.sum(take7==piece_list_w)>0:
queen_b_take.append(chess_values_w[take7][0])
if take8!=0 and np.sum(take8==piece_list_w)>0:
queen_b_take.append(chess_values_w[take8][0])
else:
pass
black_scores.append(np.max(queen_b_take))
# =========================================
elif board_label_sq[n,m]=='knight_w': # white knight
take1 = 0.0
take2 = 0.0
take3 = 0.0
take4 = 0.0
take5 = 0.0
take6 = 0.0
take7 = 0.0
take8 = 0.0
knight_w_take=[0]
if m<7 and n<6:
take1 = board_label_sq[n+2,m+1] # col +1, row +2
if m>0 and n<6:
take2 = board_label_sq[n+2,m-1] # col -1, row +2
if m>0 and n>1:
take3 = board_label_sq[n-2,m-1] # col -1, row -2
if m<7 and n>1:
take4 = board_label_sq[n-2,m+1] # col +1, row -2
if n<7 and m<6:
take5 = board_label_sq[n+1,m+2] # col +2, row +1
if n<7 and m>1:
take6 = board_label_sq[n+1,m-2] # col -2, row +1
if n>0 and m>1:
take7 = board_label_sq[n-1,m-2] # col -2, row -1
if n>0 and m<6:
take8 = board_label_sq[n-1,m+2] # col +2, row -1
if take1!=0 and np.sum(take1==piece_list_b)>0:
knight_w_take.append(chess_values_b[take1][0])
if take2!=0 and np.sum(take2==piece_list_b)>0:
knight_w_take.append(chess_values_b[take2][0])
if take3!=0 and np.sum(take3==piece_list_b)>0:
knight_w_take.append(chess_values_b[take3][0])
if take4!=0 and np.sum(take4==piece_list_b)>0:
knight_w_take.append(chess_values_b[take4][0])
if take5!=0 and np.sum(take5==piece_list_b)>0:
knight_w_take.append(chess_values_b[take5][0])
if take6!=0 and np.sum(take6==piece_list_b)>0:
knight_w_take.append(chess_values_b[take6][0])
if take7!=0 and np.sum(take7==piece_list_b)>0:
knight_w_take.append(chess_values_b[take7][0])
if take8!=0 and np.sum(take8==piece_list_b)>0:
knight_w_take.append(chess_values_b[take8][0])
else:
pass
white_scores.append(np.max(knight_w_take))
# =========================================
elif board_label_sq[n,m]=='knight_b': # black knight
take1 = 0.0
take2 = 0.0
take3 = 0.0
take4 = 0.0
take5 = 0.0
take6 = 0.0
take7 = 0.0
take8 = 0.0
knight_b_take=[0]
if m<7 and n<6:
take1 = board_label_sq[n+2,m+1] # col +1, row +2
if m>0 and n<6:
take2 = board_label_sq[n+2,m-1] # col -1, row +2
if m>0 and n>1:
take3 = board_label_sq[n-2,m-1] # col -1, row -2
if m<7 and n>1:
take4 = board_label_sq[n-2,m+1] # col +1, row -2
if n<7 and m<6:
take5 = board_label_sq[n+1,m+2] # col +2, row +1
if n<7 and m>1:
take6 = board_label_sq[n+1,m-2] # col -2, row +1
if n>0 and m>1:
take7 = board_label_sq[n-1,m-2] # col -2, row -1
if n>0 and m<6:
take8 = board_label_sq[n-1,m+2] # col +2, row -1
if take1!=0 and np.sum(take1==piece_list_w)>0:
knight_b_take.append(chess_values_w[take1][0])
if take2!=0 and np.sum(take2==piece_list_w)>0:
knight_b_take.append(chess_values_w[take2][0])
if take3!=0 and np.sum(take3==piece_list_w)>0:
knight_b_take.append(chess_values_w[take3][0])
if take4!=0 and np.sum(take4==piece_list_w)>0:
knight_b_take.append(chess_values_w[take4][0])
if take5!=0 and np.sum(take5==piece_list_w)>0:
knight_b_take.append(chess_values_w[take5][0])
if take6!=0 and np.sum(take6==piece_list_w)>0:
knight_b_take.append(chess_values_w[take6][0])
if take7!=0 and np.sum(take7==piece_list_w)>0:
knight_b_take.append(chess_values_w[take7][0])
if take8!=0 and np.sum(take8==piece_list_w)>0:
knight_b_take.append(chess_values_w[take8][0])
else:
pass
black_scores.append(np.max(knight_b_take))
# =========================================
elif board_label_sq[n,m]=='king_w': # white king
take1 = 0.0
take2 = 0.0
take3 = 0.0
take4 = 0.0
take5 = 0.0
take6 = 0.0
take7 = 0.0
take8 = 0.0
king_w_take=[0]
if m<7 and n<7:
take1 = board_label_sq[n+1,m+1] # col +1, row +1
if m>0 and n<7:
take2 = board_label_sq[n+1,m-1] # col -1, row +1
if m>0 and n>0:
take3 = board_label_sq[n-1,m-1] # col -1, row -1
if m<7 and n>0:
take4 = board_label_sq[n-1,m+1] # col +1, row -1
if n<7:
take5 = board_label_sq[n+1,m] # col 0, row +1
if m>0:
take6 = board_label_sq[n,m-1] # col -1, row 0
if n>0:
take7 = board_label_sq[n-1,m] # col 0, row -1
if m<7:
take8 = board_label_sq[n,m+1] # col +1, row 0
if take1!=0 and np.sum(take1==piece_list_b)>0:
king_w_take.append(chess_values_b[take1][0])
if take2!=0 and np.sum(take2==piece_list_b)>0:
king_w_take.append(chess_values_b[take2][0])
if take3!=0 and np.sum(take3==piece_list_b)>0:
king_w_take.append(chess_values_b[take3][0])
if take4!=0 and np.sum(take4==piece_list_b)>0:
king_w_take.append(chess_values_b[take4][0])
if take5!=0 and np.sum(take5==piece_list_b)>0:
king_w_take.append(chess_values_b[take5][0])
if take6!=0 and np.sum(take6==piece_list_b)>0:
king_w_take.append(chess_values_b[take6][0])
if take7!=0 and np.sum(take7==piece_list_b)>0:
king_w_take.append(chess_values_b[take7][0])
if take8!=0 and np.sum(take8==piece_list_b)>0:
king_w_take.append(chess_values_b[take8][0])
else:
pass
white_scores.append(np.max(king_w_take))
# =========================================
elif board_label_sq[n,m]=='king_b': # black king
take1 = 0.0
take2 = 0.0
take3 = 0.0
take4 = 0.0
take5 = 0.0
take6 = 0.0
take7 = 0.0
take8 = 0.0
king_b_take=[0]
if m<7 and n<7:
take1 = board_label_sq[n+1,m+1] # col +1, row +1
if m>0 and n<7:
take2 = board_label_sq[n+1,m-1] # col -1, row +1
if m>0 and n>0:
take3 = board_label_sq[n-1,m-1] # col -1, row -1
if m<7 and n>0:
take4 = board_label_sq[n-1,m+1] # col +1, row -1
if n<7:
take5 = board_label_sq[n+1,m] # col 0, row +1
if m>0:
take6 = board_label_sq[n,m-1] # col -1, row 0
if n>0:
take7 = board_label_sq[n-1,m] # col 0, row -1
if m<7:
take8 = board_label_sq[n,m+1] # col +1, row 0
if take1!=0 and np.sum(take1==piece_list_w)>0:
king_b_take.append(chess_values_w[take1][0])
if take2!=0 and np.sum(take2==piece_list_w)>0:
king_b_take.append(chess_values_w[take2][0])
if take3!=0 and np.sum(take3==piece_list_w)>0:
king_b_take.append(chess_values_w[take3][0])
if take4!=0 and np.sum(take4==piece_list_w)>0:
king_b_take.append(chess_values_w[take4][0])
if take5!=0 and np.sum(take5==piece_list_w)>0:
king_b_take.append(chess_values_w[take5][0])
if take6!=0 and np.sum(take6==piece_list_w)>0:
king_b_take.append(chess_values_w[take6][0])
if take7!=0 and np.sum(take7==piece_list_w)>0:
king_b_take.append(chess_values_w[take7][0])
if take8!=0 and np.sum(take8==piece_list_w)>0:
king_b_take.append(chess_values_w[take8][0])
else:
pass
black_scores.append(np.max(king_b_take))
piece_ratio = (sum_black+1)/(sum_white+1)
move_ratio = (np.max(black_scores)+1)/(np.max(white_scores)+1) # ratio of best move that racks the most points
# you win if (your_total_piece_value - enemy_move_value) > (enemy_total_piece_value - your_move_value)
# tie if both kings are lost in that turn
winner=0.0
if np.max(black_scores)==40 and np.max(white_scores)==40:
winner = 0.0 # tie
elif (sum_black-np.max(white_scores)) > (sum_white-np.max(black_scores)):
winner = 1.0 # black wins
else:
winner = -1.0 # white wins
return board_label_sq, piece_ratio, move_ratio, winner
# generate D size training data
def generate_data(D,train_split):
'''
Generates labelled data arrays + images.
Inputs:
D := desired number of data points
N := 1D dimension of board, s.t. board.shape = (N,N)
train_split := split of training/testing data, e.g., 0.9 => 90% training, 10% testing
Outputs:
training_data := split training data, data array: [# red pieces, # blue pieces, winner] dims: (D*train_split) x 3
training_images := split training data, corresponding board images; flattened dims: (D*train_split) x N**2
testing_data := split testing data, data array: [# red pieces, # blue pieces, winner] dims: (D*(1-train_split)) x 3
testing_images := split testing data, corresponding board images; flattened dims: (D*(1-train_split)) x N**2
'''
N=8
data = np.zeros((D,3)) # create array to populate each row with x1: black sum, x2: white sum, label: ratio
images = np.zeros(D).astype(object) # create array to populate D rows with flattened N x N images in the columns
for n in range(D):
winner=0 # exclude ties
while winner==0:
board_label_sq, piece_ratio, move_ratio, winner = generate_best_move()
data[n,[0,1,2]]=[piece_ratio,move_ratio,winner]
images[n]=board_label_sq
training_data=data[:int(D*train_split),:] # labelled training data
training_images=images[:int(D*train_split)] # training images
testing_data=data[int(D*train_split):,:] # labelled testing data
testing_images=images[int(D*train_split):] # testing images
return training_data, training_images, testing_data, testing_images
# gameboard parameters
N=8 # 1D of gameboard. Game board => N x N dimensions
# generate training/testing data for the classical and quantum classifiers
training_data, training_images, testing_data, testing_images =generate_data(D=500,train_split=0.9)
for n in range(9):
chessBoardShow(training_images[n])
def nCen_train_test(training_data, testing_data, N, shrink, plot_testing=False):
'''
Train Nearest Centroid Neighbors algorithm. Plot results and accuracy. Output the best nCen.
Inputs:
training_data := split training data, data array: [# red pieces, # blue pieces, winner] dims: (D*train_split) x 3
testing_data := split testing data, data array: [# red pieces, # blue pieces, winner] dims: (D*(1-train_split)) x 3
N := 1D dimension of board, s.t. board.shape = (N,N); used here for normalizing the data
shrink := list of shrink values to test, e.g., shrink=[0.0,0.1,0.5,0.9]
plot_testing := True or False value; plots the testing dataset with classifier bounds
Outputs:
Plots the nearest centroid decision boundary, training data, test data, and accuracy plots
nCen := nearest centroid object with the highest accuracy
'''
# Assign training/test data
training_data[:,[0,1]]=training_data[:,[0,1]]/(N**2) # standardize data. Max pieces is N*N
testing_data[:,[0,1]]=testing_data[:,[0,1]]/(N**2) # standardize data. Max pieces is N*N
X_train = training_data[:,[0,1]] # training features
y_train = training_data[:,2] # training labels
X_test = testing_data[:,[0,1]] # testing features
y_test = testing_data[:,2] # testing labels
# =============================================================================
# run accuracy with training data for k=k neighbors
acc_list=[]
nCen_list=[]
for i in range(len(shrink)):
# run kNN classification
nCen_list.append(NearestCentroid(shrink_threshold=shrink[i])) # create k-NN object
nCen_list[i].fit(X_train, y_train) # fit classifier decision boundary to training data
# =============================================================================
# plot classification boundary with training data
meshres=50
RED,BLUE=np.meshgrid(np.linspace(np.min([np.min(X_train[:,0]),np.min(X_test[:,0])]),np.max([np.max(X_train[:,0]),np.max(X_test[:,0])]),meshres),
np.linspace(np.min([np.min(X_train[:,1]),np.min(X_test[:,1])]),np.max([np.max(X_train[:,1]),np.max(X_test[:,1])]),meshres))
boundary=nCen_list[i].predict(np.c_[RED.ravel(),BLUE.ravel()])
plt.figure()
plt.contourf(RED,BLUE,boundary.reshape(RED.shape),cmap='bwr',alpha=0.3)
plt.scatter(X_train[:,0],X_train[:,1],c=y_train,cmap='bwr',edgecolor='k')
plt.xlabel('# red pieces\n[normalized]')
plt.ylabel('# blue pieces\n[normalized]')
cbar=plt.colorbar()
cbar.ax.set_ylabel('Winner')
plt.title('Centroid Classification, shrink = '+str(shrink[i]))
plt.show()
# plot testing data
if plot_testing == True:
plt.figure()
plt.contourf(RED,BLUE,boundary.reshape(RED.shape),cmap='bwr',alpha=0.3)
testt=plt.scatter(X_test[:,0],X_test[:,1],c=y_test,cmap='bwr',edgecolor='k')
plt.xlabel('# red pieces\n[normalized]')
plt.ylabel('# blue pieces\n[normalized]')
plt.title('Testing Data, n = '+str(X_test.shape[0]))
cbar=plt.colorbar(testt)
cbar.ax.set_ylabel('Winner')
plt.show()
else:
pass
# =============================================================================
# calculate accuracy with training data set
predicted=nCen_list[i].predict(X_test) # calculate predicted label from training data
acc=np.sum(predicted==y_test)/len(y_test) # calculate accuracy of where prediction is correct vs incorrect relative to actual labels
acc_list.append(acc)
print('shrink = ',shrink[i],'\nTraining Accuracy =',acc*100,'%\n','='*40,'\n\n')
plt.figure()
plt.plot(shrink,acc_list,marker='o')
plt.xlabel('Centroid shrinking threshold')
plt.xticks(shrink)
plt.ylabel('Accuracy')
plt.show()
best_nCen=nCen_list[np.argmax(acc_list)]
print('best shrink = ',shrink[np.argmax(acc_list)])
return best_nCen
# generate best nearest centroid neighbors
best_nCen = nCen_train_test(training_data=training_data, testing_data=testing_data, N=N, shrink=list(np.arange(0.0,0.9,0.1)),plot_testing=True)
def player_prediction_classical(best_model,player_data):
'''
Outputs the classically predicted result of the 5 player games, not within the training dataset.
Inputs:
best_model := NearestCentroid object
player_data := generated data array: [# red pieces, # blue pieces, winner] dims: 5 x 3
Outputs:
cCompData := list of 0 or 1 values. 1 == red wins, 0 == blue wins
'''
X_player_data=player_data[:,[0,1]]
cCompData = best_model.predict(X_player_data)
cCompData[cCompData==-1.]=0
return list(cCompData.astype(int))
# Unit-normalized vector helper
def normalize(x):
return x / np.linalg.norm(x)
# Since in a space R^n there are n-1 RBS gates,
# in a 2-dimensional dataset (R^2), there is 1
# RBS parameter angle, as defined:
def theta_in_2d(x):
epsilon = math.pow(10, -10)
return math.acos((x[0] + epsilon) / (np.linalg.norm(x) + epsilon)) + epsilon
class QuantumCircuit(QuantumCircuit):
def irbs(self, theta, qubits):
ug = UnitaryGate([[1, 0, 0, 0],
[0, np.cos(theta), complex(0,-np.sin(theta)), 0],
[0, complex(0, -np.sin(theta)), np.cos(theta), 0],
[0, 0, 0, 1]], label=f'iRBS({np.around(theta, 3)})')
return self.append(ug, qubits, [])
# qc.irbs(theta, [qubit1, qubit2])
def estimation_circuit(x_theta, y_theta):
# As defined in Johri et al. (III.A.1), an iRBS is functionally
# identical in the distance estimation circuit to the RBS gate;
# thus, the iRBS gate is defined in the QuantumCircuit class to
# be used in the estimation circuit.
# Unitary implementation (throws IonQ backend error)
def irbs_unitary(theta):
return UnitaryGate([[1, 0, 0, 0],
[0, np.cos(theta), complex(0,-np.sin(theta)), 0],
[0, complex(0, -np.sin(theta)), np.cos(theta), 0],
[0, 0, 0, 1]], label=f'iRBS({np.around(theta, 3)})')
# Circuit implementation from figure 7 in Johri et al.
def irbs(qc, theta, qubits):
qc.rz(np.pi/2, qubits[1])
qc.cx(qubits[1], qubits[0])
qc.ry(np.pi/2 - 2 * theta, qubits[1])
qc.rz(-np.pi/2, qubits[0])
qc.cx(qubits[0], qubits[1])
qc.ry(2 * theta - np.pi/2, qubits[1])
qc.cx(qubits[1], qubits[0])
qc.rz(-np.pi / 2, qubits[0])
qc = QuantumCircuit(2,2)
qc.x(0)
irbs(qc, x_theta, [0, 1])
irbs(qc, y_theta, [0, 1])
qc.measure([0, 1], [0, 1])
return qc
# Returns estimated distance as defined in Johri et al. (Equation 3)
def probability_uncorrected(result):
counts = result.get_counts()
shots = np.sum(list(counts.values()))
if '10' in counts:
return counts["10"]/shots
else:
return 0
def probability_corrected(result):
counts = result.get_counts()
corrected_counts = {}
# Discard incorrect values (00, 11)
if '10' in counts:
corrected_counts['10'] = counts['10']
if '01' in counts:
corrected_counts['01'] = counts['01']
shots = np.sum(list(corrected_counts.values()))
if '10' in counts:
return corrected_counts["10"]/shots
else:
return 0
def euclidian_distance(x, y, corrected=False):
x_norm = np.linalg.norm(x)
y_norm = np.linalg.norm(y)
x_square_norm = x_norm**2
y_square_norm = y_norm**2
x_theta = theta_in_2d(x)
y_theta = theta_in_2d(y)
ec = estimation_circuit(x_theta, y_theta)
print(f'xTHETA {x_theta} yTHETA {y_theta}')
# IonQ
#job = backend.run(ec, shots=1000)
# QASM
job = execute(ec, backend, shots=1000)
job_id = job.job_id()
while job.status() is not JobStatus.DONE:
print(job.status())
time.sleep(1)
result = job.result()
if corrected:
probability = probability_corrected(result)
else:
probability = probability_uncorrected(result)
normalized_inner_product = math.sqrt(probability)
return math.sqrt(x_square_norm + y_square_norm - 2*x_norm*y_norm*normalized_inner_product)
import random
# generate toy data: random N x N board
def generate_board(N):
'''
Generates a random board of dimensions N x N
Inputs:
N := 1D dimension of board, s.t. board.shape = (N,N)
Outputs:
board := flattened N x N array
winner := red wins == 1, blue wins == -1
sum_red := sum of red pieces
sum_blue := sum of blue pieces
'''
board=np.zeros((N*N))
pieces=random.sample(range(1,N*N),1)[0]
inds = random.sample(range(0,N*N),pieces) # pick random location to place pieces
ratio = 1
while ratio == 1: # safeguard to remove possiblility of ties
for n in range(pieces):
board[inds[n]]=random.sample([-1,1],1)[0] # make space blue or red
sum_red = np.sum(board==1) # sum of 1 values (i.e., red pieces)
sum_blue = np.sum(board==-1) # sum of -1 values (i.e., blue pieces)
ratio = sum_red/sum_blue # find ratio
if ratio > 1: # red wins
winner = 1
elif ratio < 1: # blue wins
winner = -1
else:
pass
return board, winner, sum_red, sum_blue
class QuantumNearestCentroid:
def __init__(self):
self.centroids = {}
def centroid(self, x):
return np.mean(x, axis=0)
def fit(self, x, y):
organized_values = {}
for i, v in enumerate(y):
if v in organized_values:
organized_values[v].append(x[i])
else:
organized_values[v] = [x[i]]
for v in organized_values:
self.centroids[v] = self.centroid(organized_values[v])
return self.centroids
def predict(self, x):
min_dist = np.inf
closest_centroid = None
for key, centroid in self.centroids.items():
res = euclidian_distance(x, centroid)
if res < min_dist:
min_dist = res
closest_centroid = key
return closest_centroid
def player_prediction_quantum(best_model,player_data):
'''
Outputs the quantum predicted result of the 5 player games, not within the training dataset.
Inputs:
best_model := NearestCentroid object
player_data := generated data array: [# red pieces, # blue pieces, winner] dims: 5 x 3
Outputs:
cCompData := list of 0 or 1 values. 1 == red wins, 0 == blue wins
'''
X_player_data=player_data[:,[0,1]]
qCompData = []
for i in range(5):
qCompData.append(best_model.predict(X_player_data[i]))
qCompData[qCompData==-1.]=0
return list(qCompData)
def quantum_train_test(training_data, testing_data, N, plot_testing=False):
X_train = training_data[:,[0,1]] # training features
y_train = training_data[:,2] # training labels
X_test = testing_data[:,[0,1]] # testing features
y_test = testing_data[:,2] # testing labels
# =============================================================================
model = QuantumNearestCentroid()
centroid = model.fit(X_train.tolist(), y_train.flatten().tolist())
print(centroid)
meshres=10
RED,BLUE=np.meshgrid(np.linspace(np.min([np.min(X_train[:,0]),np.min(X_test[:,0])]),np.max([np.max(X_train[:,0]),np.max(X_test[:,0])]),meshres),
np.linspace(np.min([np.min(X_train[:,1]),np.min(X_test[:,1])]),np.max([np.max(X_train[:,1]),np.max(X_test[:,1])]),meshres))
print(len(np.c_[RED.ravel(),BLUE.ravel()]))
boundary=[]
for i, v in enumerate(np.c_[RED.ravel(),BLUE.ravel()]):
print(f"{i} : {v.tolist()}")
res = model.predict(list(v))
print(res)
boundary.append(res)
print(boundary)
boundary = np.array(boundary)
plt.figure()
plt.contourf(RED,BLUE,boundary.reshape(RED.shape),cmap='bwr',alpha=0.3)
plt.scatter(X_train[:,0],X_train[:,1],c=y_train,cmap='bwr',edgecolor='k')
plt.xlabel('# red pieces\n[normalized]')
plt.ylabel('# blue pieces\n[normalized]')
cbar=plt.colorbar()
cbar.ax.set_ylabel('Winner')
plt.title('Centroid Classification')
plt.show()
# plot testing data
if plot_testing == True:
plt.figure()
plt.contourf(RED,BLUE,boundary.reshape(RED.shape),cmap='bwr',alpha=0.3)
testt=plt.scatter(X_test[:,0],X_test[:,1],c=y_test,cmap='bwr',edgecolor='k')
plt.xlabel('# red pieces\n[normalized]')
plt.ylabel('# blue pieces\n[normalized]')
plt.title('Testing Data, n = '+str(X_test.shape[0]))
cbar=plt.colorbar(testt)
cbar.ax.set_ylabel('Winner')
plt.show()
else:
pass
# =============================================================================
# calculate accuracy with training data set
predicted=[] # calculate predicted label from training data
for v in X_test:
predicted.append(model.predict(v))
predicted = np.array(predicted)
acc=np.sum(predicted==y_test)/len(y_test) # calculate accuracy of where prediction is correct vs incorrect relative to actual labels
print('Training Accuracy =',acc*100,'%\n','='*40,'\n\n')
return model
def quantum_train(training_data, testing_data, N):
# Assign training/test data
X_train = training_data[:,[0,1]] # training features
y_train = training_data[:,2] # training labels
X_test = testing_data[:,[0,1]] # testing features
y_test = testing_data[:,2] # testing labels
model = QuantumNearestCentroid()
centroid = model.fit(X_train.tolist(), y_train.flatten().tolist())
return model
# generate best quantum nearest centroid model
best_quantum = quantum_train_test(training_data=training_data, testing_data=testing_data, N=N, plot_testing=True)
compData = []
compResults = []
def generateCompData(cData = [0,0,0,0,0], qData = [0,0,0,0,0], gData = [0, 0, 0, 0,]):
global compData
global compResults
''' Here we take the 2d array gData and transpose it '''
pgData = pd.DataFrame(gData).T.values.tolist()
pgData = [0 if x==-1.0 else 1 for x in pgData[2]]
'''
These reset the compData and compResults array so there are no errors
with the runtime
'''
compData = [
[0,0,0,0], # Storing what the [Q, C, H, G] say the answer is.
[0,0,0,0],
[0,0,0,0],
[0,0,0,0],
[0,0,0,0]
]
compResults = [
[0,0,0], # Storing [QvG, HvG, CvG]
[0,0,0],
[0,0,0],
[0,0,0],
[0,0,0]
]
'''
The entirety of this function is to setup the enviroment for future functions
'''
qCompData = qData # this will be the data from the QML on the 5 boards given
cCompData = cData # this will be the data from the Classical on the 5 boards given
gCompData = pgData # this is the ground truth answers
'''
These take the original qCompData and cCompData arrays and put them
together in the compData array for parrsing later in the program
'''
count = 0
for i in qCompData:
compData[count][1] = int(i)
count += 1
count = 0
for i in cCompData:
compData[count][0] = int(i)
count += 1
count = 0
for i in gCompData:
compData[count][3] = int(i)
count += 1
def finalizeCompResults():
'''
The entirety of this function is to check if the quatum model and
human match the conventional model
'''
global compData
global compResults
count = 0
for i in compData:
if i[3] == i[0]: # this is for the C v. G
compResults[count][1] = 1
if i[3] == i[1]: # this is for the Q v. G
compResults[count][0] = 1
if i[3] == i[2]: # this is for the H v. G
compResults[count][2] = 1
count += 1
def showCompResults():
global compResults
global compData
data = [
[0,0,0,0],
[0,0,0,0],
[0,0,0,0],
[0,0,0,0],
[0,0,0,0]
]
dataColors = [
["#a2cffe",0,0,0],
["#a2cffe",0,0,0],
["#a2cffe",0,0,0],
["#a2cffe",0,0,0],
["#a2cffe",0,0,0]
]
count = 0
# print(compResults)
for i in compResults:
if i[0] == 1: # Q v. G
data[count][3] = compData[count][1]
dataColors[count][3] = "palegreen"
else:
dataColors[count][3] = "#cf6275"
if i[2] == 1: # Human v. G
data[count][1] = compData[count][2]
dataColors[count][1] = "palegreen"
else:
dataColors[count][1] = "#cf6275"
if i[1] == 1: # C v. G
data[count][2] = compData[count][0]
dataColors[count][2] = "palegreen"
else:
dataColors[count][2] = "#cf6275"
data[count][0] = compData[count][3]
count += 1
print(data)
for i in range(0,5):
data[i] = ["Black" if x==1 else "White" for x in data[i]]
print(data)
Sum = [sum(x) for x in zip(*compResults)]
winner = ". . . wait what?!?!?! it was a tie! Well, I guess no one"
if (Sum[0] < Sum[1]) and (Sum[0] < Sum[2]):
winner = "Human"
elif (Sum[1] < Sum[0]) and (Sum[1] < Sum[2]):
winner = "Quantum Computer"
elif (Sum[2] < Sum[1]) and (Sum[2] < Sum[0]):
winner = "Classical Computer"
fig, ax = plt.subplots(1,1)
column_labels=["Truth", "Human v. Truth", "Classical v. Truth", "Quantum v. Truth"]
plt.title("Who won, a quantum computer or a human? Turns out the " + winner + " is better!")
ax.axis('tight')
ax.axis('off')
ax.table(cellText=data,
colLabels = column_labels,
cellColours = dataColors,
loc = "center",
cellLoc='center')
plt.show()
def showProblem(array):
global compData
# N = 8 # board dimensions: N x N
# board = array
# board = board.reshape(N,N)
plt.axis('off')
# plt.title("Does Black or White have a game-state advantage this turn?")
# plt.imshow(board,cmap='bwr')
chessBoardShow(array)
plt.show()
def playersMove(roundNum):
global compData
while True:
print('\033[1m'+'GAME #',str(roundNum+1)+'/5'+'\033[0m')
print('_'*100)
print('\033[1m'+'WHICH PLAYER HAS THE GAME-STATE ADVANTAGE THIS TURN?'+'\033[0m')
print('Hint: Game-state advantage is computed based on which player has a higher total\n',
'piece value minus the value of the best piece the opposing player can take this turn.\n',
'Note: There CANNOT be a tie.')
print('_'*100,'\n')
print("Does black or white have the advantage? (b/w): ")
playerChoice = input("").lower()
if playerChoice == "b":
playerChoice = 1
break
elif playerChoice == "w":
playerChoice = 0
break
compData[roundNum][2] = playerChoice
clear_output(wait=True)
newGame = True
while newGame:
# Generate 5 boards for the player to play
player_data_5, player_images_5, __, __ =generate_data(D=5,train_split=1)
cCompData = player_prediction_classical(best_model=best_nCen,player_data=player_data_5)
# qCompData = player_prediction_quantum(best_model=best_quantum,player_data=player_data_5)
qCompData=[1,1,1,1,1]
generateCompData(cCompData, qCompData, player_data_5)
clear_output(wait=True)
# Start the game!
for i in range(0, 5):
showProblem(player_images_5[i])
playersMove(i)
clear_output(wait=True)
finalizeCompResults()
showCompResults()
while True:
print("Would you like to play again? (y/n): ")
playerChoice = input("").lower()
if playerChoice == "y":
clear_output(wait=True)
break
elif playerChoice == "n":
clear_output(wait=True)
newGame = False
break
|
https://github.com/RavenPillmann/quantum-battleship
|
RavenPillmann
|
import numpy as np
import networkx as nx
import qiskit
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer, assemble
from qiskit.quantum_info import Statevector
from qiskit.aqua.algorithms import NumPyEigensolver
from qiskit.quantum_info import Pauli
from qiskit.aqua.operators import op_converter
from qiskit.aqua.operators import WeightedPauliOperator
from qiskit.visualization import plot_histogram
from qiskit.providers.aer.extensions.snapshot_statevector import *
from thirdParty.classical import rand_graph, classical, bitstring_to_path, calc_cost
from utils import mapeo_grafo
from collections import defaultdict
from operator import itemgetter
from scipy.optimize import minimize
import matplotlib.pyplot as plt
LAMBDA = 10
SEED = 10
SHOTS = 10000
# returns the bit index for an alpha and j
def bit(i_city, l_time, num_cities):
return i_city * num_cities + l_time
# e^(cZZ)
def append_zz_term(qc, q_i, q_j, gamma, constant_term):
qc.cx(q_i, q_j)
qc.rz(2*gamma*constant_term,q_j)
qc.cx(q_i, q_j)
# e^(cZ)
def append_z_term(qc, q_i, gamma, constant_term):
qc.rz(2*gamma*constant_term, q_i)
# e^(cX)
def append_x_term(qc,qi,beta):
qc.rx(-2*beta, qi)
def get_not_edge_in(G):
N = G.number_of_nodes()
not_edge = []
for i in range(N):
for j in range(N):
if i != j:
buffer_tupla = (i,j)
in_edges = False
for edge_i, edge_j in G.edges():
if ( buffer_tupla == (edge_i, edge_j) or buffer_tupla == (edge_j, edge_i)):
in_edges = True
if in_edges == False:
not_edge.append((i, j))
return not_edge
def get_classical_simplified_z_term(G, _lambda):
# recorrer la formula Z con datos grafo se va guardando en diccionario que acumula si coinciden los terminos
N = G.number_of_nodes()
E = G.edges()
# z term #
z_classic_term = [0] * N**2
# first term
for l in range(N):
for i in range(N):
z_il_index = bit(i, l, N)
z_classic_term[z_il_index] += -1 * _lambda
# second term
for l in range(N):
for j in range(N):
for i in range(N):
if i < j:
# z_il
z_il_index = bit(i, l, N)
z_classic_term[z_il_index] += _lambda / 2
# z_jl
z_jl_index = bit(j, l, N)
z_classic_term[z_jl_index] += _lambda / 2
# third term
for i in range(N):
for l in range(N):
for j in range(N):
if l < j:
# z_il
z_il_index = bit(i, l, N)
z_classic_term[z_il_index] += _lambda / 2
# z_ij
z_ij_index = bit(i, j, N)
z_classic_term[z_ij_index] += _lambda / 2
# fourth term
not_edge = get_not_edge_in(G) # include order tuples ej = (1,0), (0,1)
for edge in not_edge:
for l in range(N):
i = edge[0]
j = edge[1]
# z_il
z_il_index = bit(i, l, N)
z_classic_term[z_il_index] += _lambda / 4
# z_j(l+1)
l_plus = (l+1) % N
z_jlplus_index = bit(j, l_plus, N)
z_classic_term[z_jlplus_index] += _lambda / 4
# fifthy term
weights = nx.get_edge_attributes(G,'weight')
for edge_i, edge_j in G.edges():
weight_ij = weights.get((edge_i,edge_j))
weight_ji = weight_ij
for l in range(N):
# z_il
z_il_index = bit(edge_i, l, N)
z_classic_term[z_il_index] += weight_ij / 4
# z_jlplus
l_plus = (l+1) % N
z_jlplus_index = bit(edge_j, l_plus, N)
z_classic_term[z_jlplus_index] += weight_ij / 4
# add order term because G.edges() do not include order tuples #
# z_i'l
z_il_index = bit(edge_j, l, N)
z_classic_term[z_il_index] += weight_ji / 4
# z_j'lplus
l_plus = (l+1) % N
z_jlplus_index = bit(edge_i, l_plus, N)
z_classic_term[z_jlplus_index] += weight_ji / 4
return z_classic_term
def tsp_obj_2(x, G,_lambda):
# obtenemos el valor evaluado en f(x_1, x_2,... x_n)
not_edge = get_not_edge_in(G)
N = G.number_of_nodes()
tsp_cost=0
#Distancia
weights = nx.get_edge_attributes(G,'weight')
for edge_i, edge_j in G.edges():
weight_ij = weights.get((edge_i,edge_j))
weight_ji = weight_ij
for l in range(N):
# x_il
x_il_index = bit(edge_i, l, N)
# x_jlplus
l_plus = (l+1) % N
x_jlplus_index = bit(edge_j, l_plus, N)
tsp_cost+= int(x[x_il_index]) * int(x[x_jlplus_index]) * weight_ij
# add order term because G.edges() do not include order tuples #
# x_i'l
x_il_index = bit(edge_j, l, N)
# x_j'lplus
x_jlplus_index = bit(edge_i, l_plus, N)
tsp_cost += int(x[x_il_index]) * int(x[x_jlplus_index]) * weight_ji
#Constraint 1
for l in range(N):
penal1 = 1
for i in range(N):
x_il_index = bit(i, l, N)
penal1 -= int(x[x_il_index])
tsp_cost += _lambda * penal1**2
#Contstraint 2
for i in range(N):
penal2 = 1
for l in range(N):
x_il_index = bit(i, l, N)
penal2 -= int(x[x_il_index])
tsp_cost += _lambda*penal2**2
#Constraint 3
for edge in not_edge:
for l in range(N):
i = edge[0]
j = edge[1]
# x_il
x_il_index = bit(i, l, N)
# x_j(l+1)
l_plus = (l+1) % N
x_jlplus_index = bit(j, l_plus, N)
tsp_cost += int(x[x_il_index]) * int(x[x_jlplus_index]) * _lambda
return tsp_cost
def get_classical_simplified_zz_term(G, _lambda):
# recorrer la formula Z con datos grafo se va guardando en diccionario que acumula si coinciden los terminos
N = G.number_of_nodes()
E = G.edges()
# zz term #
zz_classic_term = [[0] * N**2 for i in range(N**2) ]
# first term
for l in range(N):
for j in range(N):
for i in range(N):
if i < j:
# z_il
z_il_index = bit(i, l, N)
# z_jl
z_jl_index = bit(j, l, N)
zz_classic_term[z_il_index][z_jl_index] += _lambda / 2
# second term
for i in range(N):
for l in range(N):
for j in range(N):
if l < j:
# z_il
z_il_index = bit(i, l, N)
# z_ij
z_ij_index = bit(i, j, N)
zz_classic_term[z_il_index][z_ij_index] += _lambda / 2
# third term
not_edge = get_not_edge_in(G)
for edge in not_edge:
for l in range(N):
i = edge[0]
j = edge[1]
# z_il
z_il_index = bit(i, l, N)
# z_j(l+1)
l_plus = (l+1) % N
z_jlplus_index = bit(j, l_plus, N)
zz_classic_term[z_il_index][z_jlplus_index] += _lambda / 4
# fourth term
weights = nx.get_edge_attributes(G,'weight')
for edge_i, edge_j in G.edges():
weight_ij = weights.get((edge_i,edge_j))
weight_ji = weight_ij
for l in range(N):
# z_il
z_il_index = bit(edge_i, l, N)
# z_jlplus
l_plus = (l+1) % N
z_jlplus_index = bit(edge_j, l_plus, N)
zz_classic_term[z_il_index][z_jlplus_index] += weight_ij / 4
# add order term because G.edges() do not include order tuples #
# z_i'l
z_il_index = bit(edge_j, l, N)
# z_j'lplus
l_plus = (l+1) % N
z_jlplus_index = bit(edge_i, l_plus, N)
zz_classic_term[z_il_index][z_jlplus_index] += weight_ji / 4
return zz_classic_term
def get_classical_simplified_hamiltonian(G, _lambda):
# z term #
z_classic_term = get_classical_simplified_z_term(G, _lambda)
# zz term #
zz_classic_term = get_classical_simplified_zz_term(G, _lambda)
return z_classic_term, zz_classic_term
def get_cost_circuit(G, gamma, _lambda):
N = G.number_of_nodes()
N_square = N**2
qc = QuantumCircuit(N_square,N_square)
z_classic_term, zz_classic_term = get_classical_simplified_hamiltonian(G, _lambda)
# z term
for i in range(N_square):
if z_classic_term[i] != 0:
append_z_term(qc, i, gamma, z_classic_term[i])
# zz term
for i in range(N_square):
for j in range(N_square):
if zz_classic_term[i][j] != 0:
append_zz_term(qc, i, j, gamma, zz_classic_term[i][j])
return qc
def get_mixer_operator(G,beta):
N = G.number_of_nodes()
qc = QuantumCircuit(N**2,N**2)
for n in range(N**2):
append_x_term(qc, n, beta)
return qc
def get_QAOA_circuit(G, beta, gamma, _lambda):
assert(len(beta)==len(gamma))
N = G.number_of_nodes()
qc = QuantumCircuit(N**2,N**2)
# init min mix state
qc.h(range(N**2))
p = len(beta)
for i in range(p):
qc = qc.compose(get_cost_circuit(G, gamma[i], _lambda))
qc = qc.compose(get_mixer_operator(G, beta[i]))
qc.barrier(range(N**2))
qc.snapshot_statevector("final_state")
qc.measure(range(N**2),range(N**2))
return qc
def invert_counts(counts):
return {k[::-1] :v for k,v in counts.items()}
# Sample expectation value
def compute_tsp_energy_2(counts, G):
energy = 0
get_counts = 0
total_counts = 0
for meas, meas_count in counts.items():
obj_for_meas = tsp_obj_2(meas, G, LAMBDA)
energy += obj_for_meas*meas_count
total_counts += meas_count
mean = energy/total_counts
return mean
def get_black_box_objective_2(G,p):
backend = Aer.get_backend('qasm_simulator')
sim = Aer.get_backend('aer_simulator')
# function f costo
def f(theta):
beta = theta[:p]
gamma = theta[p:]
# Anzats
qc = get_QAOA_circuit(G, beta, gamma, LAMBDA)
result = execute(qc, backend, seed_simulator=SEED, shots= SHOTS).result()
final_state_vector = result.data()["snapshots"]["statevector"]["final_state"][0]
state_vector = Statevector(final_state_vector)
probabilities = state_vector.probabilities()
probabilities_states = invert_counts(state_vector.probabilities_dict())
expected_value = 0
for state,probability in probabilities_states.items():
cost = tsp_obj_2(state, G, LAMBDA)
expected_value += cost*probability
counts = result.get_counts()
mean = compute_tsp_energy_2(invert_counts(counts),G)
return mean
return f
def crear_grafo(cantidad_ciudades):
pesos, conexiones = None, None
mejor_camino = None
while not mejor_camino:
pesos, conexiones = rand_graph(cantidad_ciudades)
mejor_costo, mejor_camino = classical(pesos, conexiones, loop=False)
G = mapeo_grafo(conexiones, pesos)
return G, mejor_costo, mejor_camino
def run_QAOA(p,ciudades, grafo):
if grafo == None:
G, mejor_costo, mejor_camino = crear_grafo(ciudades)
print("Mejor Costo")
print(mejor_costo)
print("Mejor Camino")
print(mejor_camino)
print("Bordes del grafo")
print(G.edges())
print("Nodos")
print(G.nodes())
print("Pesos")
labels = nx.get_edge_attributes(G,'weight')
print(labels)
else:
G = grafo
intial_random = []
# beta, mixer Hammiltonian
for i in range(p):
intial_random.append(np.random.uniform(0,np.pi))
# gamma, cost Hammiltonian
for i in range(p):
intial_random.append(np.random.uniform(0,2*np.pi))
init_point = np.array(intial_random)
obj = get_black_box_objective_2(G,p)
res_sample = minimize(obj, init_point,method="COBYLA",options={"maxiter":2500,"disp":True})
print(res_sample)
if __name__ == '__main__':
# Run QAOA parametros: profundidad p, numero d ciudades,
run_QAOA(5, 3, None)
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2023.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test the SetLayout pass"""
import unittest
from qiskit import QuantumRegister, QuantumCircuit, ClassicalRegister
from qiskit.transpiler import CouplingMap, Layout
from qiskit.transpiler.passes import SetLayout, ApplyLayout, FullAncillaAllocation
from qiskit.test import QiskitTestCase
from qiskit.transpiler import PassManager, TranspilerError
class TestSetLayout(QiskitTestCase):
"""Tests the SetLayout pass"""
def assertEqualToReference(self, result_to_compare):
"""Compare result_to_compare to a reference
βββββ β βββ
q_0 -> 0 β€ H βββββ€Mββββββββββββββββ
βββββ€ β ββ₯ββββ
q_1 -> 1 β€ H ββββββ«ββ€Mβββββββββββββ
βββββ€ β β ββ₯β βββ
q_4 -> 2 β€ H ββββββ«βββ«ββββββββ€Mββββ
βββββ€ β β β βββ ββ₯β
q_2 -> 3 β€ H ββββββ«βββ«ββ€Mββββββ«ββββ
βββββ β β β ββ₯β β
ancilla_0 -> 4 ββββββββββ«βββ«βββ«ββββββ«ββββ
βββββ β β β β βββ β
q_3 -> 5 β€ H ββββββ«βββ«βββ«ββ€Mβββ«ββββ
βββββ€ β β β β ββ₯β β βββ
q_5 -> 6 β€ H ββββββ«βββ«βββ«βββ«βββ«ββ€Mβ
βββββ β β β β β β ββ₯β
meas: 6/ββββββββββ©βββ©βββ©βββ©βββ©βββ©β
0 1 2 3 4 5
"""
qr = QuantumRegister(6, "q")
ancilla = QuantumRegister(1, "ancilla")
cl = ClassicalRegister(6, "meas")
reference = QuantumCircuit(qr, ancilla, cl)
reference.h(qr)
reference.barrier(qr)
reference.measure(qr, cl)
pass_manager = PassManager()
pass_manager.append(
SetLayout(
Layout({qr[0]: 0, qr[1]: 1, qr[4]: 2, qr[2]: 3, ancilla[0]: 4, qr[3]: 5, qr[5]: 6})
)
)
pass_manager.append(ApplyLayout())
self.assertEqual(result_to_compare, pass_manager.run(reference))
def test_setlayout_as_Layout(self):
"""Construct SetLayout with a Layout."""
qr = QuantumRegister(6, "q")
circuit = QuantumCircuit(qr)
circuit.h(qr)
circuit.measure_all()
pass_manager = PassManager()
pass_manager.append(
SetLayout(Layout.from_intlist([0, 1, 3, 5, 2, 6], QuantumRegister(6, "q")))
)
pass_manager.append(FullAncillaAllocation(CouplingMap.from_line(7)))
pass_manager.append(ApplyLayout())
result = pass_manager.run(circuit)
self.assertEqualToReference(result)
def test_setlayout_as_list(self):
"""Construct SetLayout with a list."""
qr = QuantumRegister(6, "q")
circuit = QuantumCircuit(qr)
circuit.h(qr)
circuit.measure_all()
pass_manager = PassManager()
pass_manager.append(SetLayout([0, 1, 3, 5, 2, 6]))
pass_manager.append(FullAncillaAllocation(CouplingMap.from_line(7)))
pass_manager.append(ApplyLayout())
result = pass_manager.run(circuit)
self.assertEqualToReference(result)
def test_raise_when_layout_len_does_not_match(self):
"""Test error is raised if layout defined as list does not match the circuit size."""
qr = QuantumRegister(42, "q")
circuit = QuantumCircuit(qr)
pass_manager = PassManager()
pass_manager.append(SetLayout([0, 1, 3, 5, 2, 6]))
pass_manager.append(FullAncillaAllocation(CouplingMap.from_line(7)))
pass_manager.append(ApplyLayout())
with self.assertRaises(TranspilerError):
pass_manager.run(circuit)
if __name__ == "__main__":
unittest.main()
|
https://github.com/IlliaOvcharenko/quantum-search
|
IlliaOvcharenko
|
import sys, os
sys.path.append(os.getcwd())
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from qiskit import QuantumCircuit
# from qiskit.primitives.sampler import Sampler
from qiskit_aer.primitives import SamplerV2 as Sampler
from qiskit_aer import AerSimulator
from qiskit import transpile
from fire import Fire
def main():
sim = AerSimulator()
qc = QuantumCircuit(3)
qc.h(0)
qc.cx(0, 1)
qc.cx(0, 2)
# qc.draw("mpl")
# plt.savefig("figs/test-qc.png", bbox_inches="tight")
qc_measured = qc.measure_all(inplace=False)
# qc_measured.draw("mpl")
# plt.savefig("figs/test-qc-measured.png", bbox_inches="tight")
qc_measured_opt = transpile(qc_measured, sim, optimization_level=0)
sampler = Sampler()
job = sampler.run([qc_measured_opt], shots=10)
print(f"Job ID is {job.job_id()}")
pub_result = job.result()
print(pub_result[0].data.meas.get_counts())
if __name__ == "__main__":
Fire(main)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import numpy as np
from qiskit import QuantumCircuit
from qiskit.circuit.library.arithmetic.piecewise_chebyshev import PiecewiseChebyshev
f_x, degree, breakpoints, num_state_qubits = lambda x: np.arcsin(1 / x), 2, [2, 4], 2
pw_approximation = PiecewiseChebyshev(f_x, degree, breakpoints, num_state_qubits)
pw_approximation._build()
qc = QuantumCircuit(pw_approximation.num_qubits)
qc.h(list(range(num_state_qubits)))
qc.append(pw_approximation.to_instruction(), qc.qubits)
qc.draw(output='mpl')
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2018.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""
Example showing how to draw a quantum circuit using Qiskit.
"""
from qiskit import QuantumCircuit
def build_bell_circuit():
"""Returns a circuit putting 2 qubits in the Bell state."""
qc = QuantumCircuit(2, 2)
qc.h(0)
qc.cx(0, 1)
qc.measure([0, 1], [0, 1])
return qc
# Create the circuit
bell_circuit = build_bell_circuit()
# Use the internal .draw() to print the circuit
print(bell_circuit)
|
https://github.com/JavaFXpert/quantum-pong
|
JavaFXpert
|
#!/usr/bin/env python
#
# Copyright 2019 the original author or authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import pygame
from qiskit import BasicAer, execute
from utils.colors import *
from utils.fonts import *
from utils.states import comp_basis_states
class UnitaryGrid(pygame.sprite.Sprite):
"""Displays a unitary matrix grid"""
def __init__(self, circuit):
pygame.sprite.Sprite.__init__(self)
self.image = None
self.rect = None
self.basis_states = comp_basis_states(circuit.width())
self.set_circuit(circuit)
# def update(self):
# # Nothing yet
# a = 1
def set_circuit(self, circuit):
backend_unit_sim = BasicAer.get_backend('unitary_simulator')
job_sim = execute(circuit, backend_unit_sim)
result_sim = job_sim.result()
unitary = result_sim.get_unitary(circuit, decimals=3)
# print('unitary: ', unitary)
self.image = pygame.Surface([100 + len(unitary) * 50, 100 + len(unitary) * 50])
self.image.convert()
self.image.fill(WHITE)
self.rect = self.image.get_rect()
block_size = 30
x_offset = 50
y_offset = 50
for y in range(len(unitary)):
text_surface = ARIAL_16.render(self.basis_states[y], False, (0, 0, 0))
self.image.blit(text_surface,(x_offset, (y + 1) * block_size + y_offset))
for x in range(len(unitary)):
text_surface = ARIAL_16.render(self.basis_states[x], False, (0, 0, 0))
self.image.blit(text_surface, ((x + 1) * block_size + x_offset, y_offset))
rect = pygame.Rect((x + 1) * block_size + x_offset,
(y + 1) * block_size + y_offset,
abs(unitary[y][x]) * block_size,
abs(unitary[y][x]) * block_size)
if abs(unitary[y][x]) > 0:
pygame.draw.rect(self.image, BLACK, rect, 1)
|
https://github.com/Chibikuri/qwopt
|
Chibikuri
|
import numpy as np
from .parser import GraphParser
from qiskit import QuantumRegister, QuantumCircuit
from numpy import pi
class OperationCreator:
'''
Creating operations of szegedy walk.
reference:
Loke, T., and J. B. Wang. "Efficient quantum circuits
for Szegedy quantum walks." Annals of Physics 382
(2017): 64-84.
all functions return instruction sets
which can be added to a circuit directly
'''
def __init__(self, graph, prob_tran, basis=0, optimize=True):
self.parser = GraphParser(graph, prob_tran)
self.graph = self.parser.graph
self.ptran = self.parser.ptrans
self.dim = self.parser.dim()
self.q_size = self._qubit_size(len(self.parser))
self.basis_state = basis
def T_operation(self):
'''
This is the operation called T operation.
This operator is converting some state to its reference state
by replacing binary order
NOTE: I'm not sure if there is an optimized way to do this,
but, thinking we can do this if we use some boolean calcuration.
'''
ref_states, ref_index = self.parser.reference_state()
ref_index.append(len(self.graph))
T_instructions = []
for irf, rf in enumerate(ref_index[:-1]):
temp = []
for i in range(rf, ref_index[irf+1]):
# control from i and target from bins
temp.append(self.graph[:, i])
Ti_op = self._bin_converter(temp, range(rf, ref_index[irf+1]))
if Ti_op is not None:
T_instructions.append(Ti_op)
return T_instructions
# TODO more understandable name
def _bin_converter(self, states, cont, ancilla=True):
if len(states) == 1:
# if the length of state is 1, we don't need to move
# with T operation
pass
else:
ref_state = states[0]
# make correspondence table
convs = [self._take_bins(ref_state, st) for st in states[1:]]
if convs == [[]]:
# if all table elements are the same value,
# we don't have to apply
return None
else:
# TODO
# here we have to optimize additional target
ctable = self._addi_analysis(convs)
target = [self._target_hm(cnv) for cnv in ctable]
control = [list(self._binary_formatter(ct, self.q_size//2))
for ct in cont]
# create instruction
q_cont = QuantumRegister(self.q_size//2)
q_targ = QuantumRegister(self.q_size//2)
if ancilla:
ancilla = QuantumRegister(self.q_size//2)
qc = QuantumCircuit(q_cont, q_targ,
ancilla, name='T%s' % cont[0])
else:
ancilla = None
qc = QuantumCircuit(q_cont, q_targ, name='T%s' % cont[0])
for cts, tgt in zip(control[1:], target):
for ic, ct in enumerate(cts):
if ct == '0' and tgt != set():
qc.x(q_cont[ic])
for tg in tgt:
qc.mct(q_cont, q_targ[tg], ancilla)
for ic, ct in enumerate(cts):
if ct == '0' and tgt != set():
qc.x(q_cont[ic])
return qc.to_instruction()
def _target_hm(self, state):
# the place we have to change
hm = []
for st in state:
# FIXME this reverse operations must be done before here.
# This reverse op is for making it applicable for qiskit.
for ids, s in enumerate(zip(st[0][::-1], st[1][::-1])):
if s[0] != s[1]:
hm.append(ids)
return set(hm)
def _take_bins(self, ref_state, other):
converter = []
for irf, rf in enumerate(ref_state):
if rf == 1:
converter.append([self._binary_formatter(irf, self.q_size//2)])
ct = 0
for iot, ot in enumerate(other):
if ot == 1:
converter[ct].append(self._binary_formatter(iot,
self.q_size//2))
ct += 1
return converter
# more understandable name
def _addi_analysis(self, conversions):
'''
remove duplications
'''
for icv, cv in enumerate(conversions):
# FIXME are there any efficient way rather than this?
if cv[0][0] == cv[0][1] and cv[1][0] == cv[1][1]:
conversions[icv] = []
conversion_table = conversions
return conversion_table
@staticmethod
def _binary_formatter(n, basis):
return format(n, '0%db' % basis)
def K_operation(self, dagger=False, ancilla=True, optimization=True,
n_opt_ancilla=2, rccx=True):
'''
Args:
dagger:
ancilla:
optimization:
n_opt_ancilla:
rccx
create reference states from basis state
or if this is Kdag, reverse operation
TODO: should separate the creation part and optimization part
'''
refs, refid = self.parser.reference_state()
rotations = self._get_rotaions(refs, dagger)
# create Ki operations
qcont = QuantumRegister(self.q_size//2, 'control')
qtarg = QuantumRegister(self.q_size//2, 'target')
# 1, ancilla mapping optimization
# if the number of reference states is the same as
# the length of matrix, we can't apply first optimization method.
if optimization and len(refid) != self.dim[0]:
# TODO surplus ancillary qubits should be used efficientry
# separate the optimization part and creation part
if n_opt_ancilla > len(qcont):
# FIXME:
raise ValueError('too much ancillary qubits')
opt_anc = QuantumRegister(n_opt_ancilla, name='opt_ancilla')
if ancilla:
anc = QuantumRegister(self.q_size//2)
qc = QuantumCircuit(qcont, qtarg, anc, opt_anc, name='opt_Kop')
else:
anc = None
qc = QuantumCircuit(qcont, qtarg, opt_anc, name='opt_Kop_n')
# HACK
# Unlke to bottom one, we need to detect which i we apply or not
qc = self._opt_K_operation(qc, qcont, qtarg, anc, opt_anc,
refid, rotations, dagger, rccx)
opt_K_instruction = qc.to_instruction()
return opt_K_instruction
else:
if ancilla:
anc = QuantumRegister(self.q_size//2)
qc = QuantumCircuit(qcont, qtarg, anc, name='Kop_anc')
else:
anc = None
qc = QuantumCircuit(qcont, qtarg, name='Kop')
ct = 0
for i in range(self.dim[0]):
ib = list(self._binary_formatter(i, self.q_size//2))
if i in refid:
rfrot = rotations[ct]
ct += 1
for ibx, bx in enumerate(ib):
if bx == '0':
qc.x(qcont[ibx])
qc = self._constructor(qc, rfrot, qcont, qtarg, anc)
for ibx, bx in enumerate(ib):
if bx == '0':
qc.x(qcont[ibx])
qc.barrier()
K_instruction = qc.to_instruction()
return K_instruction
def _opt_K_operation(self, qc, qcont, qtarg, anc, opt_anc,
refid, rotations, dagger, rcx=True):
'''
TODO: apply each optimizations separately.
using ancilla, the structure is a litlle bit different from
usual one. we need to care about it.
'''
# If you are using rccx, the phase is destroyed
# you need to fix after one iteration
# HACK
# make the loop with rotations
# we have to detect if we can apply ancilla optimization
lv_table = self._level_detector(refid)
if dagger:
# mapping with rccx
qc = self._map_ancilla_dag(qc, qcont, qtarg, anc, opt_anc,
refid, rotations, lv_table, rcx)
else:
# fix phase of ancilla
qc = self._map_ancilla(qc, qcont, qtarg, anc, opt_anc,
refid, rotations, lv_table, rcx)
return qc
def _level_detector(self, refid):
lv_table = []
mx_bin = self.dim[0]
for i in range(1, mx_bin):
if i in refid:
pre_i = list(self._binary_formatter(i-1, self.q_size//2))
bin_i = list(self._binary_formatter(i, self.q_size//2))
for ilv, st in enumerate(zip(pre_i, bin_i)):
if st[0] != st[1]:
lv_table.append(ilv)
break
return lv_table
# FIXME too much argument
def _map_ancilla_dag(self, qc, cont, targ, anc, opt_anc,
refid, rotations, lv_table, rcx):
'''
applying dagger operation
the number of rotaions is corresponding to the number of
partitions of matrix.
'''
n_partitions = len(refid) - 1
# FIXME debug settings!!!!!!!
# opt_level = len(opt_anc)
opt_level = 2
start = min(lv_table)
end = start + opt_level
# mapping once from control to ancillary qubits
# iopt is for pointing the index of ancillary qubits
# procedure
# In the case of the number of partitioin is one
# 1. detect the position of partitions if the position is the
# second most left or right, apply operations.
# 2. else, we need to detect the level of optimization
if n_partitions == 1:
# HACK
if refid[-1] == 1 or refid[-1] == self.dim[0] - 1:
qc = self._mapping(qc, cont, opt_anc[0], False, anc)
for rotation in rotations:
qc = self._constructor(qc, rotation, [opt_anc[0]],
targ, anc)
qc.x(opt_anc[0])
# no inverse is required here
else:
if opt_level == self.q_size//2 - 1:
# print('hello')
pass
# general case
# print(refid)
# print(lv_table)
for iopt, opt in enumerate(range(start, end)):
# TODO: do we have to take indices?
# qc.cx(cont[opt], opt_anc[iopt])
raise Warning('Under construction')
else:
raise Warning('the case of the number of partition is over \
1 is being under constructing.')
# print(qc)
return qc
@staticmethod
def _mapping(qc, cont, targ, rcx, anc):
if len(cont) == 1:
qc.cx(cont, targ)
elif len(cont) == 2:
if rcx:
qc.rccx(cont[0], cont[1], targ)
else:
qc.ccx(cont[0], cont[1], targ)
else:
qc.mct(cont, targ, anc)
return qc
def _map_ancilla(self, qc, cont, targ, anc, opt_anc,
refid, rotations, lv_table, rcx):
'''
'''
n_partitions = len(refid) - 1
# FIXME debug settings!!!!!!!
# opt_level = len(opt_anc)
opt_level = 2
start = min(lv_table)
end = start + opt_level
if n_partitions == 1:
# HACK
if refid[-1] == 1 or refid[-1] == self.dim[0] - 1:
for rotation in rotations:
qc = self._constructor(qc, rotation, [opt_anc[0]],
targ, anc)
qc.x(opt_anc[0])
# This corresponds to the reverse operation
qc = self._mapping(qc, cont, opt_anc[0], False, anc)
# no inverse is required here
else:
for iopt, opt in enumerate(range(start, end)):
# TODO: do we have to take indices?
# qc.cx(cont[opt], opt_anc[iopt])
raise Warning('Under construction')
else:
raise Warning('the case of the number of partition is over \
1 is being under constructing.')
return qc
def _qft_constructor(self):
'''
Thinking if we can reduce the number of operations with qft
'''
pass
def _constructor(self, circuit, rotations, cont, targ, anc):
# TODO check
if len(rotations) == 1:
circuit.mcry(rotations[0], cont, targ[0], anc)
return circuit
elif len(rotations) == 2:
circuit.mcry(rotations[0], cont, targ[0], anc)
circuit.mcry(rotations[1], cont, targ[1], anc)
return circuit
else:
circuit.mcry(rotations[0], cont, targ[0], anc)
circuit.x(targ[0])
circuit.mcry(rotations[1], [*cont, targ[0]], targ[1], anc)
circuit.x(targ[0])
for irt, rt in enumerate(rotations[2:]):
# insted of ccc...hhh...
for tg in targ[irt+1:]:
circuit.mcry(pi/2, [*cont, *targ[:irt+1]], tg, anc)
circuit.x(targ[:irt+2])
circuit.mcry(rt, [*cont, *targ[:irt+2]], targ[irt+2], anc)
circuit.x(targ[:irt+2])
return circuit
def _get_rotaions(self, state, dagger):
rotations = []
if self.basis_state != 0:
raise Exception('Under construction')
else:
for st in state:
rt = self._rotation(st, [], dagger)
rotations.append(rt)
return rotations
def _rotation(self, state, rotations, dagger):
lst = len(state)
if lst == 2:
if sum(state) != 0:
rotations.append(2*np.arccos(np.sqrt(state[0]/sum(state))))
else:
rotations.append(0)
else:
if sum(state) != 0:
rotations.append(2*np.arccos(
np.sqrt(sum(state[:int(lst/2)])/sum(state))))
else:
rotations.append(0)
self._rotation(state[:int(lst/2)], rotations, dagger)
if dagger:
rotations = [-i for i in rotations]
return rotations
def D_operation(self, n_anilla=0, mode='basic', barrier=False):
'''
This operation is for flipping phase of specific basis state
'''
# describe basis state as a binary number
nq = int(self.q_size/2)
basis_bin = list(self._binary_formatter(self.basis_state, nq))
# create operation
qr = QuantumRegister(nq)
Dop = QuantumCircuit(qr, name='D')
if n_anilla > 0:
anc = QuantumRegister(n_anilla)
Dop.add_register(anc)
for q, b in zip(qr, basis_bin):
if b == '0':
Dop.x(q)
# creating cz operation
if barrier:
Dop.barrier()
Dop.h(qr[-1])
Dop.mct(qr[:-1], qr[-1], None)
Dop.h(qr[-1])
if barrier:
Dop.barrier()
for q, b in zip(qr, basis_bin):
if b == '0':
Dop.x(q)
D_instruction = Dop.to_instruction()
return D_instruction
@staticmethod
def _qubit_size(dim):
qsize = int(np.ceil(np.log2(dim)))
return 2*qsize
def prob_transition(graph):
pmatrix = np.zeros(graph.shape)
indegrees = np.sum(graph, axis=0)
for ix, indeg in enumerate(indegrees):
if indeg == 0:
pmatrix[:, ix] = graph[:, ix]
else:
pmatrix[:, ix] = graph[:, ix]/indeg
return pmatrix
if __name__ == '__main__':
# graph = np.array([[0, 1, 0, 0],
# [0, 0, 1, 1],
# [0, 0, 0, 1],
# [0, 1, 1, 0]])
# graph = np.array([[0, 1, 0, 0, 1, 0],
# [0, 0, 0, 1, 1, 0],
# [0, 0, 0, 1, 1, 1],
# [0, 1, 1, 0, 0, 0],
# [0, 1, 0, 0, 0, 1],
# [0, 1, 0, 0, 1, 0])
# graph = np.array([[0, 0, 1, 0, 0, 0, 0, 1],
# [0, 0, 0, 1, 0, 0, 1, 0],
# [0, 0, 1, 0, 0, 1, 1, 1],
# [0, 0, 0, 0, 0, 1, 1, 0],
# [0, 0, 0, 1, 1, 1, 1, 1],
# [0, 0, 0, 0, 1, 1, 1, 1],
# [0, 0, 0, 0, 1, 0, 0, 1],
# [0, 0, 0, 0, 1, 0, 1, 0]])
graph = np.array([[0, 0, 0, 0, 0, 0, 0, 1],
[0, 0, 0, 1, 0, 0, 1, 0],
[0, 0, 0, 0, 0, 1, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 1, 1, 0, 0, 1],
[0, 0, 0, 0, 0, 1, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0, 1, 0]])
pb = prob_transition(graph)
opcreator = OperationCreator(graph, pb)
# opcreator.D_operation()
# opcreator.T_operation()
opcreator.K_operation(dagger=True)
|
https://github.com/2lambda123/Qiskit-qiskit
|
2lambda123
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
# pylint: disable=missing-function-docstring
"""Test scheduled circuit (quantum circuit with duration)."""
from ddt import ddt, data
from qiskit import QuantumCircuit, QiskitError
from qiskit import transpile, assemble, BasicAer
from qiskit.circuit import Parameter
from qiskit.providers.fake_provider import FakeParis
from qiskit.transpiler.exceptions import TranspilerError
from qiskit.transpiler.instruction_durations import InstructionDurations
from qiskit.test.base import QiskitTestCase
@ddt
class TestScheduledCircuit(QiskitTestCase):
"""Test scheduled circuit (quantum circuit with duration)."""
def setUp(self):
super().setUp()
self.backend_with_dt = FakeParis()
self.backend_without_dt = FakeParis()
delattr(self.backend_without_dt.configuration(), "dt")
self.dt = 2.2222222222222221e-10
self.simulator_backend = BasicAer.get_backend("qasm_simulator")
def test_schedule_circuit_when_backend_tells_dt(self):
"""dt is known to transpiler by backend"""
qc = QuantumCircuit(2)
qc.delay(0.1, 0, unit="ms") # 450000[dt]
qc.delay(100, 0, unit="ns") # 450[dt]
qc.h(0) # 160[dt]
qc.h(1) # 160[dt]
sc = transpile(qc, self.backend_with_dt, scheduling_method="alap", layout_method="trivial")
self.assertEqual(sc.duration, 450610)
self.assertEqual(sc.unit, "dt")
self.assertEqual(sc.data[0].operation.name, "delay")
self.assertEqual(sc.data[0].operation.duration, 450450)
self.assertEqual(sc.data[0].operation.unit, "dt")
self.assertEqual(sc.data[1].operation.name, "rz")
self.assertEqual(sc.data[1].operation.duration, 0)
self.assertEqual(sc.data[1].operation.unit, "dt")
self.assertEqual(sc.data[4].operation.name, "delay")
self.assertEqual(sc.data[4].operation.duration, 450450)
self.assertEqual(sc.data[4].operation.unit, "dt")
qobj = assemble(sc, self.backend_with_dt)
self.assertEqual(qobj.experiments[0].instructions[0].name, "delay")
self.assertEqual(qobj.experiments[0].instructions[0].params[0], 450450)
self.assertEqual(qobj.experiments[0].instructions[4].name, "delay")
self.assertEqual(qobj.experiments[0].instructions[4].params[0], 450450)
def test_schedule_circuit_when_transpile_option_tells_dt(self):
"""dt is known to transpiler by transpile option"""
qc = QuantumCircuit(2)
qc.delay(0.1, 0, unit="ms") # 450000[dt]
qc.delay(100, 0, unit="ns") # 450[dt]
qc.h(0)
qc.h(1)
sc = transpile(
qc,
self.backend_without_dt,
scheduling_method="alap",
dt=self.dt,
layout_method="trivial",
)
self.assertEqual(sc.duration, 450610)
self.assertEqual(sc.unit, "dt")
self.assertEqual(sc.data[0].operation.name, "delay")
self.assertEqual(sc.data[0].operation.duration, 450450)
self.assertEqual(sc.data[0].operation.unit, "dt")
self.assertEqual(sc.data[1].operation.name, "rz")
self.assertEqual(sc.data[1].operation.duration, 0)
self.assertEqual(sc.data[1].operation.unit, "dt")
self.assertEqual(sc.data[4].operation.name, "delay")
self.assertEqual(sc.data[4].operation.duration, 450450)
self.assertEqual(sc.data[4].operation.unit, "dt")
def test_schedule_circuit_in_sec_when_no_one_tells_dt(self):
"""dt is unknown and all delays and gate times are in SI"""
qc = QuantumCircuit(2)
qc.delay(0.1, 0, unit="ms")
qc.delay(100, 0, unit="ns")
qc.h(0)
qc.h(1)
sc = transpile(
qc, self.backend_without_dt, scheduling_method="alap", layout_method="trivial"
)
self.assertAlmostEqual(sc.duration, 450610 * self.dt)
self.assertEqual(sc.unit, "s")
self.assertEqual(sc.data[0].operation.name, "delay")
self.assertAlmostEqual(sc.data[0].operation.duration, 1.0e-4 + 1.0e-7)
self.assertEqual(sc.data[0].operation.unit, "s")
self.assertEqual(sc.data[1].operation.name, "rz")
self.assertAlmostEqual(sc.data[1].operation.duration, 160 * self.dt)
self.assertEqual(sc.data[1].operation.unit, "s")
self.assertEqual(sc.data[4].operation.name, "delay")
self.assertAlmostEqual(sc.data[4].operation.duration, 1.0e-4 + 1.0e-7)
self.assertEqual(sc.data[4].operation.unit, "s")
with self.assertRaises(QiskitError):
assemble(sc, self.backend_without_dt)
def test_cannot_schedule_circuit_with_mixed_SI_and_dt_when_no_one_tells_dt(self):
"""dt is unknown but delays and gate times have a mix of SI and dt"""
qc = QuantumCircuit(2)
qc.delay(100, 0, unit="ns")
qc.delay(30, 0, unit="dt")
qc.h(0)
qc.h(1)
with self.assertRaises(QiskitError):
transpile(qc, self.backend_without_dt, scheduling_method="alap")
def test_transpile_single_delay_circuit(self):
qc = QuantumCircuit(1)
qc.delay(1234, 0)
sc = transpile(qc, backend=self.backend_with_dt, scheduling_method="alap")
self.assertEqual(sc.duration, 1234)
self.assertEqual(sc.data[0].operation.name, "delay")
self.assertEqual(sc.data[0].operation.duration, 1234)
self.assertEqual(sc.data[0].operation.unit, "dt")
def test_transpile_t1_circuit(self):
qc = QuantumCircuit(1)
qc.x(0) # 320 [dt]
qc.delay(1000, 0, unit="ns") # 4500 [dt]
qc.measure_all() # 19584 [dt]
scheduled = transpile(qc, backend=self.backend_with_dt, scheduling_method="alap")
self.assertEqual(scheduled.duration, 23060)
def test_transpile_delay_circuit_with_backend(self):
qc = QuantumCircuit(2)
qc.h(0)
qc.delay(100, 1, unit="ns") # 450 [dt]
qc.cx(0, 1) # 1760 [dt]
scheduled = transpile(
qc, backend=self.backend_with_dt, scheduling_method="alap", layout_method="trivial"
)
self.assertEqual(scheduled.duration, 2082)
def test_transpile_delay_circuit_without_backend(self):
qc = QuantumCircuit(2)
qc.h(0)
qc.delay(500, 1)
qc.cx(0, 1)
scheduled = transpile(
qc,
scheduling_method="alap",
basis_gates=["h", "cx"],
instruction_durations=[("h", 0, 200), ("cx", [0, 1], 700)],
)
self.assertEqual(scheduled.duration, 1200)
def test_transpile_circuit_with_custom_instruction(self):
"""See: https://github.com/Qiskit/qiskit-terra/issues/5154"""
bell = QuantumCircuit(2, name="bell")
bell.h(0)
bell.cx(0, 1)
qc = QuantumCircuit(2)
qc.delay(500, 1)
qc.append(bell.to_instruction(), [0, 1])
scheduled = transpile(
qc, scheduling_method="alap", instruction_durations=[("bell", [0, 1], 1000)]
)
self.assertEqual(scheduled.duration, 1500)
def test_transpile_delay_circuit_with_dt_but_without_scheduling_method(self):
qc = QuantumCircuit(1)
qc.delay(100, 0, unit="ns")
transpiled = transpile(qc, backend=self.backend_with_dt)
self.assertEqual(transpiled.duration, None) # not scheduled
self.assertEqual(transpiled.data[0].operation.duration, 450) # unit is converted ns -> dt
def test_transpile_delay_circuit_without_scheduling_method_or_durs(self):
qc = QuantumCircuit(2)
qc.h(0)
qc.delay(500, 1)
qc.cx(0, 1)
not_scheduled = transpile(qc)
self.assertEqual(not_scheduled.duration, None)
def test_raise_error_if_transpile_with_scheduling_method_but_without_durations(self):
qc = QuantumCircuit(2)
qc.h(0)
qc.delay(500, 1)
qc.cx(0, 1)
with self.assertRaises(TranspilerError):
transpile(qc, scheduling_method="alap")
def test_invalidate_schedule_circuit_if_new_instruction_is_appended(self):
qc = QuantumCircuit(2)
qc.h(0)
qc.delay(500 * self.dt, 1, "s")
qc.cx(0, 1)
scheduled = transpile(qc, backend=self.backend_with_dt, scheduling_method="alap")
# append a gate to a scheduled circuit
scheduled.h(0)
self.assertEqual(scheduled.duration, None)
def test_default_units_for_my_own_duration_users(self):
qc = QuantumCircuit(2)
qc.h(0)
qc.delay(500, 1)
qc.cx(0, 1)
# accept None for qubits
scheduled = transpile(
qc,
basis_gates=["h", "cx", "delay"],
scheduling_method="alap",
instruction_durations=[("h", 0, 200), ("cx", None, 900)],
)
self.assertEqual(scheduled.duration, 1400)
# prioritize specified qubits over None
scheduled = transpile(
qc,
basis_gates=["h", "cx", "delay"],
scheduling_method="alap",
instruction_durations=[("h", 0, 200), ("cx", None, 900), ("cx", [0, 1], 800)],
)
self.assertEqual(scheduled.duration, 1300)
def test_unit_seconds_when_using_backend_durations(self):
qc = QuantumCircuit(2)
qc.h(0)
qc.delay(500 * self.dt, 1, "s")
qc.cx(0, 1)
# usual case
scheduled = transpile(
qc, backend=self.backend_with_dt, scheduling_method="alap", layout_method="trivial"
)
self.assertEqual(scheduled.duration, 2132)
# update durations
durations = InstructionDurations.from_backend(self.backend_with_dt)
durations.update([("cx", [0, 1], 1000 * self.dt, "s")])
scheduled = transpile(
qc,
backend=self.backend_with_dt,
scheduling_method="alap",
instruction_durations=durations,
layout_method="trivial",
)
self.assertEqual(scheduled.duration, 1500)
def test_per_qubit_durations(self):
"""See: https://github.com/Qiskit/qiskit-terra/issues/5109"""
qc = QuantumCircuit(3)
qc.h(0)
qc.delay(500, 1)
qc.cx(0, 1)
qc.h(1)
sc = transpile(
qc,
scheduling_method="alap",
basis_gates=["h", "cx"],
instruction_durations=[("h", None, 200), ("cx", [0, 1], 700)],
)
self.assertEqual(sc.qubit_start_time(0), 300)
self.assertEqual(sc.qubit_stop_time(0), 1200)
self.assertEqual(sc.qubit_start_time(1), 500)
self.assertEqual(sc.qubit_stop_time(1), 1400)
self.assertEqual(sc.qubit_start_time(2), 0)
self.assertEqual(sc.qubit_stop_time(2), 0)
self.assertEqual(sc.qubit_start_time(0, 1), 300)
self.assertEqual(sc.qubit_stop_time(0, 1), 1400)
qc.measure_all()
sc = transpile(
qc,
scheduling_method="alap",
basis_gates=["h", "cx", "measure"],
instruction_durations=[("h", None, 200), ("cx", [0, 1], 700), ("measure", None, 1000)],
)
q = sc.qubits
self.assertEqual(sc.qubit_start_time(q[0]), 300)
self.assertEqual(sc.qubit_stop_time(q[0]), 2400)
self.assertEqual(sc.qubit_start_time(q[1]), 500)
self.assertEqual(sc.qubit_stop_time(q[1]), 2400)
self.assertEqual(sc.qubit_start_time(q[2]), 1400)
self.assertEqual(sc.qubit_stop_time(q[2]), 2400)
self.assertEqual(sc.qubit_start_time(*q), 300)
self.assertEqual(sc.qubit_stop_time(*q), 2400)
def test_change_dt_in_transpile(self):
qc = QuantumCircuit(1, 1)
qc.x(0)
qc.measure(0, 0)
# default case
scheduled = transpile(qc, backend=self.backend_with_dt, scheduling_method="asap")
org_duration = scheduled.duration
# halve dt in sec = double duration in dt
scheduled = transpile(
qc, backend=self.backend_with_dt, scheduling_method="asap", dt=self.dt / 2
)
self.assertEqual(scheduled.duration, org_duration * 2)
@data("asap", "alap")
def test_duration_on_same_instruction_instance(self, scheduling_method):
"""See: https://github.com/Qiskit/qiskit-terra/issues/5771"""
assert self.backend_with_dt.properties().gate_length(
"cx", (0, 1)
) != self.backend_with_dt.properties().gate_length("cx", (1, 2))
qc = QuantumCircuit(3)
qc.cz(0, 1)
qc.cz(1, 2)
sc = transpile(qc, backend=self.backend_with_dt, scheduling_method=scheduling_method)
cxs = [inst.operation for inst in sc.data if inst.operation.name == "cx"]
self.assertNotEqual(cxs[0].duration, cxs[1].duration)
def test_transpile_and_assemble_delay_circuit_for_simulator(self):
"""See: https://github.com/Qiskit/qiskit-terra/issues/5962"""
qc = QuantumCircuit(1)
qc.delay(100, 0, "ns")
circ = transpile(qc, self.simulator_backend)
self.assertEqual(circ.duration, None) # not scheduled
qobj = assemble(circ, self.simulator_backend)
self.assertEqual(qobj.experiments[0].instructions[0].name, "delay")
self.assertEqual(qobj.experiments[0].instructions[0].params[0], 1e-7)
def test_transpile_and_assemble_t1_circuit_for_simulator(self):
"""Check if no scheduling is done in transpiling for simulator backends"""
qc = QuantumCircuit(1, 1)
qc.x(0)
qc.delay(0.1, 0, "us")
qc.measure(0, 0)
circ = transpile(qc, self.simulator_backend)
self.assertEqual(circ.duration, None) # not scheduled
qobj = assemble(circ, self.simulator_backend)
self.assertEqual(qobj.experiments[0].instructions[1].name, "delay")
self.assertAlmostEqual(qobj.experiments[0].instructions[1].params[0], 1e-7)
# Tests for circuits with parameterized delays
def test_can_transpile_circuits_after_assigning_parameters(self):
"""Check if not scheduled but duration is converted in dt"""
idle_dur = Parameter("t")
qc = QuantumCircuit(1, 1)
qc.x(0)
qc.delay(idle_dur, 0, "us")
qc.measure(0, 0)
qc = qc.assign_parameters({idle_dur: 0.1})
circ = transpile(qc, self.backend_with_dt)
self.assertEqual(circ.duration, None) # not scheduled
self.assertEqual(circ.data[1].operation.duration, 450) # converted in dt
def test_can_transpile_and_assemble_circuits_with_assigning_parameters_inbetween(self):
idle_dur = Parameter("t")
qc = QuantumCircuit(1, 1)
qc.x(0)
qc.delay(idle_dur, 0, "us")
qc.measure(0, 0)
circ = transpile(qc, self.backend_with_dt)
circ = circ.assign_parameters({idle_dur: 0.1})
qobj = assemble(circ, self.backend_with_dt)
self.assertEqual(qobj.experiments[0].instructions[1].name, "delay")
self.assertEqual(qobj.experiments[0].instructions[1].params[0], 450)
def test_can_transpile_circuits_with_unbounded_parameters(self):
idle_dur = Parameter("t")
qc = QuantumCircuit(1, 1)
qc.x(0)
qc.delay(idle_dur, 0, "us")
qc.measure(0, 0)
# not assign parameter
circ = transpile(qc, self.backend_with_dt)
self.assertEqual(circ.duration, None) # not scheduled
self.assertEqual(circ.data[1].operation.unit, "dt") # converted in dt
self.assertEqual(
circ.data[1].operation.duration, idle_dur * 1e-6 / self.dt
) # still parameterized
def test_fail_to_assemble_circuits_with_unbounded_parameters(self):
idle_dur = Parameter("t")
qc = QuantumCircuit(1, 1)
qc.x(0)
qc.delay(idle_dur, 0, "us")
qc.measure(0, 0)
qc = transpile(qc, self.backend_with_dt)
with self.assertRaises(QiskitError):
assemble(qc, self.backend_with_dt)
@data("asap", "alap")
def test_can_schedule_circuits_with_bounded_parameters(self, scheduling_method):
idle_dur = Parameter("t")
qc = QuantumCircuit(1, 1)
qc.x(0)
qc.delay(idle_dur, 0, "us")
qc.measure(0, 0)
qc = qc.assign_parameters({idle_dur: 0.1})
circ = transpile(qc, self.backend_with_dt, scheduling_method=scheduling_method)
self.assertIsNotNone(circ.duration) # scheduled
@data("asap", "alap")
def test_fail_to_schedule_circuits_with_unbounded_parameters(self, scheduling_method):
idle_dur = Parameter("t")
qc = QuantumCircuit(1, 1)
qc.x(0)
qc.delay(idle_dur, 0, "us")
qc.measure(0, 0)
# not assign parameter
with self.assertRaises(TranspilerError):
transpile(qc, self.backend_with_dt, scheduling_method=scheduling_method)
|
https://github.com/2lambda123/Qiskit-qiskit
|
2lambda123
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2018.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test the TrivialLayout pass"""
import unittest
from qiskit import ClassicalRegister, QuantumRegister, QuantumCircuit
from qiskit.transpiler import CouplingMap
from qiskit.transpiler.passes import TrivialLayout
from qiskit.transpiler.target import Target
from qiskit.circuit.library import CXGate
from qiskit.transpiler import TranspilerError
from qiskit.converters import circuit_to_dag
from qiskit.test import QiskitTestCase
from qiskit.providers.fake_provider import FakeTenerife, FakeRueschlikon
class TestTrivialLayout(QiskitTestCase):
"""Tests the TrivialLayout pass"""
def setUp(self):
super().setUp()
self.cmap5 = FakeTenerife().configuration().coupling_map
self.cmap16 = FakeRueschlikon().configuration().coupling_map
def test_3q_circuit_5q_coupling(self):
"""Test finds trivial layout for 3q circuit on 5q device."""
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
circuit.cx(qr[1], qr[0])
circuit.cx(qr[0], qr[2])
circuit.cx(qr[1], qr[2])
dag = circuit_to_dag(circuit)
pass_ = TrivialLayout(CouplingMap(self.cmap5))
pass_.run(dag)
layout = pass_.property_set["layout"]
for i in range(3):
self.assertEqual(layout[qr[i]], i)
def test_3q_circuit_5q_coupling_with_target(self):
"""Test finds trivial layout for 3q circuit on 5q device."""
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
circuit.cx(qr[1], qr[0])
circuit.cx(qr[0], qr[2])
circuit.cx(qr[1], qr[2])
dag = circuit_to_dag(circuit)
target = Target()
target.add_instruction(CXGate(), {tuple(edge): None for edge in self.cmap5})
pass_ = TrivialLayout(target)
pass_.run(dag)
layout = pass_.property_set["layout"]
for i in range(3):
self.assertEqual(layout[qr[i]], i)
def test_9q_circuit_16q_coupling(self):
"""Test finds trivial layout for 9q circuit with 2 registers on 16q device."""
qr0 = QuantumRegister(4, "q0")
qr1 = QuantumRegister(5, "q1")
cr = ClassicalRegister(2, "c")
circuit = QuantumCircuit(qr0, qr1, cr)
circuit.cx(qr0[1], qr0[2])
circuit.cx(qr0[0], qr1[3])
circuit.cx(qr1[4], qr0[2])
circuit.measure(qr1[1], cr[0])
circuit.measure(qr0[2], cr[1])
dag = circuit_to_dag(circuit)
pass_ = TrivialLayout(CouplingMap(self.cmap16))
pass_.run(dag)
layout = pass_.property_set["layout"]
for i in range(4):
self.assertEqual(layout[qr0[i]], i)
for i in range(5):
self.assertEqual(layout[qr1[i]], i + 4)
def test_raises_wider_circuit(self):
"""Test error is raised if the circuit is wider than coupling map."""
qr0 = QuantumRegister(3, "q0")
qr1 = QuantumRegister(3, "q1")
circuit = QuantumCircuit(qr0, qr1)
circuit.cx(qr0, qr1)
dag = circuit_to_dag(circuit)
with self.assertRaises(TranspilerError):
pass_ = TrivialLayout(CouplingMap(self.cmap5))
pass_.run(dag)
if __name__ == "__main__":
unittest.main()
|
https://github.com/Axect/QuantumAlgorithms
|
Axect
|
import qiskit
qiskit.__qiskit_version__
#initialization
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
# importing Qiskit
from qiskit import IBMQ, BasicAer
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute
from qiskit.compiler import transpile
from qiskit.tools.monitor import job_monitor
# import basic plot tools
from qiskit.tools.visualization import plot_histogram
# Load our saved IBMQ accounts.
IBMQ.load_account()
nQubits = 14 # number of physical qubits
a = 101 # the hidden integer whose bitstring is 1100101
# make sure that a can be represented with nQubits
a = a % 2**(nQubits)
# Creating registers
# qubits for querying the oracle and finding the hidden integer
qr = QuantumRegister(nQubits)
# for recording the measurement on qr
cr = ClassicalRegister(nQubits)
circuitName = "BernsteinVazirani"
bvCircuit = QuantumCircuit(qr, cr)
# Apply Hadamard gates before querying the oracle
for i in range(nQubits):
bvCircuit.h(qr[i])
# Apply barrier so that it is not optimized by the compiler
bvCircuit.barrier()
# Apply the inner-product oracle
for i in range(nQubits):
if (a & (1 << i)):
bvCircuit.z(qr[i])
else:
bvCircuit.iden(qr[i])
# Apply barrier
bvCircuit.barrier()
#Apply Hadamard gates after querying the oracle
for i in range(nQubits):
bvCircuit.h(qr[i])
# Measurement
bvCircuit.barrier(qr)
bvCircuit.measure(qr, cr)
bvCircuit.draw(output='mpl')
# use local simulator
backend = BasicAer.get_backend('qasm_simulator')
shots = 1000
results = execute(bvCircuit, backend=backend, shots=shots).result()
answer = results.get_counts()
plot_histogram(answer)
backend = IBMQ.get_backend('ibmq_16_melbourne')
shots = 1000
bvCompiled = transpile(bvCircuit, backend=backend, optimization_level=1)
job_exp = execute(bvCircuit, backend=backend, shots=shots)
job_monitor(job_exp)
results = job_exp.result()
answer = results.get_counts(bvCircuit)
threshold = int(0.01 * shots) #the threshold of plotting significant measurements
filteredAnswer = {k: v for k,v in answer.items() if v >= threshold} #filter the answer for better view of plots
removedCounts = np.sum([ v for k,v in answer.items() if v < threshold ]) #number of counts removed
filteredAnswer['other_bitstrings'] = removedCounts #the removed counts is assigned to a new index
plot_histogram(filteredAnswer)
print(filteredAnswer)
|
https://github.com/kaelynj/Qiskit-HubbardModel
|
kaelynj
|
%%capture
%pip install qiskit
%pip install qiskit_ibm_provider
%pip install qiskit-aer
# Importing standard Qiskit libraries
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, QuantumCircuit, transpile, Aer
from qiskit_ibm_provider import IBMProvider
from qiskit.tools.jupyter import *
from qiskit.visualization import *
from qiskit.circuit.library import C3XGate
# Importing matplotlib
import matplotlib.pyplot as plt
# Importing Numpy, Cmath and math
import numpy as np
import os, math, cmath
from numpy import pi
# Other imports
from IPython.display import display, Math, Latex
# Specify the path to your env file
env_file_path = 'config.env'
# Load environment variables from the file
os.environ.update(line.strip().split('=', 1) for line in open(env_file_path) if '=' in line and not line.startswith('#'))
# Load IBM Provider API KEY
IBMP_API_KEY = os.environ.get('IBMP_API_KEY')
# Loading your IBM Quantum account(s)
IBMProvider.save_account(IBMP_API_KEY, overwrite=True)
# Run the quantum circuit on a statevector simulator backend
backend = Aer.get_backend('statevector_simulator')
qc_b1 = QuantumCircuit(2, 2)
qc_b1.h(0)
qc_b1.cx(0, 1)
qc_b1.draw(output='mpl', style="iqp")
sv = backend.run(qc_b1).result().get_statevector()
sv.draw(output='latex', prefix = "|\Phi^+\\rangle = ")
qc_b2 = QuantumCircuit(2, 2)
qc_b2.x(0)
qc_b2.h(0)
qc_b2.cx(0, 1)
qc_b2.draw(output='mpl', style="iqp")
sv = backend.run(qc_b2).result().get_statevector()
sv.draw(output='latex', prefix = "|\Phi^-\\rangle = ")
qc_b2 = QuantumCircuit(2, 2)
qc_b2.h(0)
qc_b2.cx(0, 1)
qc_b2.z(0)
qc_b2.draw(output='mpl', style="iqp")
sv = backend.run(qc_b2).result().get_statevector()
sv.draw(output='latex', prefix = "|\Phi^-\\rangle = ")
qc_b3 = QuantumCircuit(2, 2)
qc_b3.x(1)
qc_b3.h(0)
qc_b3.cx(0, 1)
qc_b3.draw(output='mpl', style="iqp")
sv = backend.run(qc_b3).result().get_statevector()
sv.draw(output='latex', prefix = "|\Psi^+\\rangle = ")
qc_b3 = QuantumCircuit(2, 2)
qc_b3.h(0)
qc_b3.cx(0, 1)
qc_b3.x(0)
qc_b3.draw(output='mpl', style="iqp")
sv = backend.run(qc_b3).result().get_statevector()
sv.draw(output='latex', prefix = "|\Psi^+\\rangle = ")
qc_b4 = QuantumCircuit(2, 2)
qc_b4.x(0)
qc_b4.h(0)
qc_b4.x(1)
qc_b4.cx(0, 1)
qc_b4.draw(output='mpl', style="iqp")
sv = backend.run(qc_b4).result().get_statevector()
sv.draw(output='latex', prefix = "|\Psi^-\\rangle = ")
qc_b4 = QuantumCircuit(2, 2)
qc_b4.h(0)
qc_b4.cx(0, 1)
qc_b4.x(0)
qc_b4.z(1)
qc_b4.draw(output='mpl', style="iqp")
sv = backend.run(qc_b4).result().get_statevector()
sv.draw(output='latex', prefix = "|\Psi^-\\rangle = ")
def sv_latex_from_qc(qc, backend):
sv = backend.run(qc).result().get_statevector()
return sv.draw(output='latex')
qc_ej2 = QuantumCircuit(4, 4)
qc_ej2.x(0)
sv_latex_from_qc(qc_ej2, backend)
qc_ej2 = QuantumCircuit(4, 4)
qc_ej2.x(1)
sv_latex_from_qc(qc_ej2, backend)
qc_ej2 = QuantumCircuit(4, 4)
qc_ej2.x(0)
qc_ej2.x(1)
sv_latex_from_qc(qc_ej2, backend)
qc_ej2 = QuantumCircuit(4, 4)
qc_ej2.x(2)
sv_latex_from_qc(qc_ej2, backend)
qc_ej2 = QuantumCircuit(4, 4)
qc_ej2.x(0)
qc_ej2.x(2)
sv_latex_from_qc(qc_ej2, backend)
qc_ej2 = QuantumCircuit(4, 4)
qc_ej2.x(0)
qc_ej2.x(2)
sv_latex_from_qc(qc_ej2, backend)
qc_ej2 = QuantumCircuit(4, 4)
qc_ej2.x(0)
qc_ej2.x(1)
qc_ej2.x(2)
sv_latex_from_qc(qc_ej2, backend)
qc_ej2 = QuantumCircuit(4, 4)
qc_ej2.x(3)
sv_latex_from_qc(qc_ej2, backend)
def circuit_adder (num):
if num<1 or num>8:
raise ValueError("Out of range") ## El enunciado limita el sumador a los valores entre 1 y 8. Quitar esta restricciΓ³n serΓa directo.
# DefiniciΓ³n del circuito base que vamos a construir
qreg_q = QuantumRegister(4, 'q')
creg_c = ClassicalRegister(1, 'c')
circuit = QuantumCircuit(qreg_q, creg_c)
qbit_position = 0
for element in reversed(np.binary_repr(num)):
if (element=='1'):
circuit.barrier()
match qbit_position:
case 0: # +1
circuit.append(C3XGate(), [qreg_q[0], qreg_q[1], qreg_q[2], qreg_q[3]])
circuit.ccx(qreg_q[0], qreg_q[1], qreg_q[2])
circuit.cx(qreg_q[0], qreg_q[1])
circuit.x(qreg_q[0])
case 1: # +2
circuit.ccx(qreg_q[1], qreg_q[2], qreg_q[3])
circuit.cx(qreg_q[1], qreg_q[2])
circuit.x(qreg_q[1])
case 2: # +4
circuit.cx(qreg_q[2], qreg_q[3])
circuit.x(qreg_q[2])
case 3: # +8
circuit.x(qreg_q[3])
qbit_position+=1
return circuit
add_3 = circuit_adder(3)
add_3.draw(output='mpl', style="iqp")
qc_test_2 = QuantumCircuit(4, 4)
qc_test_2.x(1)
qc_test_2_plus_3 = qc_test_2.compose(add_3)
qc_test_2_plus_3.draw(output='mpl', style="iqp")
sv_latex_from_qc(qc_test_2_plus_3, backend)
qc_test_7 = QuantumCircuit(4, 4)
qc_test_7.x(0)
qc_test_7.x(1)
qc_test_7.x(2)
qc_test_7_plus_8 = qc_test_7.compose(circuit_adder(8))
sv_latex_from_qc(qc_test_7_plus_8, backend)
#qc_test_7_plus_8.draw()
theta = 6.544985
phi = 2.338741
lmbda = 0
alice_1 = 0
alice_2 = 1
bob_1 = 2
qr_alice = QuantumRegister(2, 'Alice')
qr_bob = QuantumRegister(1, 'Bob')
cr = ClassicalRegister(3, 'c')
qc_ej3 = QuantumCircuit(qr_alice, qr_bob, cr)
qc_ej3.barrier(label='1')
qc_ej3.u(theta, phi, lmbda, alice_1);
qc_ej3.barrier(label='2')
qc_ej3.h(alice_2)
qc_ej3.cx(alice_2, bob_1);
qc_ej3.barrier(label='3')
qc_ej3.cx(alice_1, alice_2)
qc_ej3.h(alice_1);
qc_ej3.barrier(label='4')
qc_ej3.measure([alice_1, alice_2], [alice_1, alice_2]);
qc_ej3.barrier(label='5')
qc_ej3.x(bob_1).c_if(alice_2, 1)
qc_ej3.z(bob_1).c_if(alice_1, 1)
qc_ej3.measure(bob_1, bob_1);
qc_ej3.draw(output='mpl', style="iqp")
result = backend.run(qc_ej3, shots=1024).result()
counts = result.get_counts()
plot_histogram(counts)
sv_0 = np.array([1, 0])
sv_1 = np.array([0, 1])
def find_symbolic_representation(value, symbolic_constants={1/np.sqrt(2): '1/β2'}, tolerance=1e-10):
"""
Check if the given numerical value corresponds to a symbolic constant within a specified tolerance.
Parameters:
- value (float): The numerical value to check.
- symbolic_constants (dict): A dictionary mapping numerical values to their symbolic representations.
Defaults to {1/np.sqrt(2): '1/β2'}.
- tolerance (float): Tolerance for comparing values with symbolic constants. Defaults to 1e-10.
Returns:
str or float: If a match is found, returns the symbolic representation as a string
(prefixed with '-' if the value is negative); otherwise, returns the original value.
"""
for constant, symbol in symbolic_constants.items():
if np.isclose(abs(value), constant, atol=tolerance):
return symbol if value >= 0 else '-' + symbol
return value
def array_to_dirac_notation(array, tolerance=1e-10):
"""
Convert a complex-valued array representing a quantum state in superposition
to Dirac notation.
Parameters:
- array (numpy.ndarray): The complex-valued array representing
the quantum state in superposition.
- tolerance (float): Tolerance for considering amplitudes as negligible.
Returns:
str: The Dirac notation representation of the quantum state.
"""
# Ensure the statevector is normalized
array = array / np.linalg.norm(array)
# Get the number of qubits
num_qubits = int(np.log2(len(array)))
# Find indices where amplitude is not negligible
non_zero_indices = np.where(np.abs(array) > tolerance)[0]
# Generate Dirac notation terms
terms = [
(find_symbolic_representation(array[i]), format(i, f"0{num_qubits}b"))
for i in non_zero_indices
]
# Format Dirac notation
dirac_notation = " + ".join([f"{amplitude}|{binary_rep}β©" for amplitude, binary_rep in terms])
return dirac_notation
def array_to_matrix_representation(array):
"""
Convert a one-dimensional array to a column matrix representation.
Parameters:
- array (numpy.ndarray): The one-dimensional array to be converted.
Returns:
numpy.ndarray: The column matrix representation of the input array.
"""
# Replace symbolic constants with their representations
matrix_representation = np.array([find_symbolic_representation(value) or value for value in array])
# Return the column matrix representation
return matrix_representation.reshape((len(matrix_representation), 1))
def array_to_dirac_and_matrix_latex(array):
"""
Generate LaTeX code for displaying both the matrix representation and Dirac notation
of a quantum state.
Parameters:
- array (numpy.ndarray): The complex-valued array representing the quantum state.
Returns:
Latex: A Latex object containing LaTeX code for displaying both representations.
"""
matrix_representation = array_to_matrix_representation(array)
latex = "Matrix representation\n\\begin{bmatrix}\n" + \
"\\\\\n".join(map(str, matrix_representation.flatten())) + \
"\n\\end{bmatrix}\n"
latex += f'Dirac Notation:\n{array_to_dirac_notation(array)}'
return Latex(latex)
sv_b1 = np.kron(sv_0, sv_0)
array_to_dirac_and_matrix_latex(sv_b1)
sv_b1 = (np.kron(sv_0, sv_0) + np.kron(sv_0, sv_1)) / np.sqrt(2)
array_to_dirac_and_matrix_latex(sv_b1)
sv_b1 = (np.kron(sv_0, sv_0) + np.kron(sv_1, sv_1)) / np.sqrt(2)
array_to_dirac_and_matrix_latex(sv_b1)
sv_b2 = np.kron(sv_0, sv_0)
array_to_dirac_and_matrix_latex(sv_b2)
sv_b2 = (np.kron(sv_0, sv_0) + np.kron(sv_0, sv_1)) / np.sqrt(2)
array_to_dirac_and_matrix_latex(sv_b2)
sv_b2 = (np.kron(sv_0, sv_0) + np.kron(sv_1, sv_1)) / np.sqrt(2)
array_to_dirac_and_matrix_latex(sv_b2)
sv_b2 = (np.kron(sv_0, sv_0) - np.kron(sv_1, sv_1)) / np.sqrt(2)
array_to_dirac_and_matrix_latex(sv_b2)
sv_b3 = np.kron(sv_0, sv_0)
array_to_dirac_and_matrix_latex(sv_b3)
sv_b3 = np.kron(sv_0, sv_1)
array_to_dirac_and_matrix_latex(sv_b3)
sv_b3 = (np.kron(sv_0, sv_0) - np.kron(sv_0, sv_1)) / np.sqrt(2)
array_to_dirac_and_matrix_latex(sv_b3)
sv_b3 = (np.kron(sv_0, sv_1) - np.kron(sv_1, sv_0)) / np.sqrt(2)
array_to_dirac_and_matrix_latex(sv_b3)
sv_b3 = (np.kron(sv_0, sv_1) + np.kron(sv_1, sv_0)) / np.sqrt(2)
array_to_dirac_and_matrix_latex(sv_b3)
sv_b4 = np.kron(sv_0, sv_0)
array_to_dirac_and_matrix_latex(sv_b4)
sv_b4 = np.kron(sv_0, sv_1)
array_to_dirac_and_matrix_latex(sv_b4)
sv_b4 = (np.kron(sv_0, sv_0) - np.kron(sv_0, sv_1)) / np.sqrt(2)
array_to_dirac_and_matrix_latex(sv_b4)
sv_b4 = (np.kron(sv_0, sv_1) - np.kron(sv_1, sv_0)) / np.sqrt(2)
array_to_dirac_and_matrix_latex(sv_b4)
|
https://github.com/BOBO1997/osp_solutions
|
BOBO1997
|
import numpy as np
import matplotlib.pyplot as plt
import itertools
from pprint import pprint
# plt.rcParams.update({'font.size': 16}) # enlarge matplotlib fonts
import pickle
import time
import datetime
# Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z)
from qiskit.opflow import Zero, One, I, X, Y, Z
from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer
from qiskit.tools.monitor import job_monitor
from qiskit.circuit import Parameter
from qiskit.transpiler.passes import RemoveBarriers
# Import QREM package
from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter
from qiskit.ignis.mitigation import expectation_value
# Import mitiq for zne
import mitiq
# Import state tomography modules
from qiskit.ignis.verification.tomography import state_tomography_circuits
from qiskit.quantum_info import state_fidelity
import sys
import importlib
sys.path.append("./")
import circuit_utils, zne_utils, tomography_utils, sgs_algorithm
importlib.reload(circuit_utils)
importlib.reload(zne_utils)
importlib.reload(tomography_utils)
importlib.reload(sgs_algorithm)
from circuit_utils import *
from zne_utils import *
from tomography_utils import *
from sgs_algorithm import *
# Combine subcircuits into a single multiqubit gate representing a single trotter step
num_qubits = 3
# The final time of the state evolution
target_time = np.pi
# Parameterize variable t to be evaluated at t=pi later
dt = Parameter('t')
# Convert custom quantum circuit into a gate
trot_gate = trotter_gate(dt)
# initial layout
initial_layout = [5,3,1]
# Number of trotter steps
num_steps = 100
print("trotter step: ", num_steps)
# Initialize quantum circuit for 3 qubits
qr = QuantumRegister(num_qubits, name="lq")
qc = QuantumCircuit(qr)
# Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>)
make_initial_state(qc, "110") # DO NOT MODIFY (|q_5,q_3,q_1> = |110>)
subspace_encoder_init110(qc, targets=[0, 1, 2]) # encode
trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian
subspace_decoder(qc, targets=[0,1,2]) # decode
# Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time
qc = qc.bind_parameters({dt: target_time / num_steps})
print("created qc")
# Generate state tomography circuits to evaluate fidelity of simulation
st_qcs = state_tomography_circuits(qc, [0, 1, 2][::-1]) #! state tomography requires === BIG ENDIAN ===
print("created st_qcs (length:", len(st_qcs), ")")
# remove barriers
st_qcs = [RemoveBarriers()(qc) for qc in st_qcs]
print("removed barriers from st_qcs")
# optimize circuit
t3_st_qcs = transpile(st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"])
print("created t3_st_qcs (length:", len(t3_st_qcs), ")")
# zne wrapping
zne_qcs = zne_wrapper(t3_st_qcs)
print("created zne_qcs (length:", len(zne_qcs), ")")
t3_zne_qcs = transpile(zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout)
print("created t3_zne_qcs (length:", len(t3_zne_qcs), ")")
t3_zne_qcs[-3].draw("mpl")
from qiskit.test.mock import FakeJakarta
# backend = FakeJakarta()
# backend = Aer.get_backend("qasm_simulator")
IBMQ.load_account()
# provider = IBMQ.get_provider(hub='ibm-q-utokyo', group='internal', project='hirashi-jst')
provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22')
print("provider:", provider)
backend = provider.get_backend("ibmq_jakarta")
# QREM
shots = 1 << 13
qr = QuantumRegister(num_qubits)
meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal')
cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout = initial_layout)
print('Job ID', cal_job.job_id())
shots = 1 << 13
reps = 8 # unused
jobs = []
for _ in range(reps):
job = execute(t3_zne_qcs, backend, shots=shots) # ζ―εγγ§γγ―: γγγ‘γγγ¨ε€γγοΌ
print('Job ID', job.job_id())
jobs.append(job)
dt_now = datetime.datetime.now()
import pickle
with open("jobs_jakarta_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f:
pickle.dump({"jobs": jobs, "cal_job": cal_job}, f)
with open("job_ids_jakarta_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f:
pickle.dump({"job_ids": [job.job_id() for job in jobs], "cal_job_id": cal_job.job_id()}, f)
with open("properties_jakarta" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f:
pickle.dump(backend.properties(), f)
with open("job_ids_jakarta_100step_20220411_030032_.pkl", "rb") as f:
job_ids_dict = pickle.load(f)
job_ids_dict['job_ids'] = job_ids_dict['job_ids'][:3]
job_ids = job_ids_dict["job_ids"]
cal_job_id = job_ids_dict["cal_job_id"]
job_ids, cal_job_id
retrieved_jobs = []
for job_id in job_ids:
retrieved_jobs.append(backend.retrieve_job(job_id))
retrieved_cal_job = backend.retrieve_job(cal_job_id)
# make the complete QREM fitter
qr = QuantumRegister(num_qubits)
_, state_labels = complete_meas_cal(qr=qr, circlabel='mcal')
cal_results = retrieved_cal_job.result()
meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal')
retrieved_results = []
for i in range(len(retrieved_jobs)):
retrieved_results.append(retrieved_jobs[i].result())
from qiskit.result import Result
labels = \
[('X', 'X', 'X'),
('X', 'X', 'Y'),
('X', 'X', 'Z'),
('X', 'Y', 'X'),
('X', 'Y', 'Y'),
('X', 'Y', 'Z'),
('X', 'Z', 'X'),
('X', 'Z', 'Y'),
('X', 'Z', 'Z'),
('Y', 'X', 'X'),
('Y', 'X', 'Y'),
('Y', 'X', 'Z'),
('Y', 'Y', 'X'),
('Y', 'Y', 'Y'),
('Y', 'Y', 'Z'),
('Y', 'Z', 'X'),
('Y', 'Z', 'Y'),
('Y', 'Z', 'Z'),
('Z', 'X', 'X'),
('Z', 'X', 'Y'),
('Z', 'X', 'Z'),
('Z', 'Y', 'X'),
('Z', 'Y', 'Y'),
('Z', 'Y', 'Z'),
('Z', 'Z', 'X'),
('Z', 'Z', 'Y'),
('Z', 'Z', 'Z'),
]
retrieved_results[0].results[0].header
reshaped_results = []
for result in retrieved_results:
res1 = Result(backend_name=result.backend_name, backend_version=result.backend_version, qobj_id=result.qobj_id, job_id=result.job_id, success=result.success, results=[])
res2 = Result(backend_name=result.backend_name, backend_version=result.backend_version, qobj_id=result.qobj_id, job_id=result.job_id, success=result.success, results=[])
res3 = Result(backend_name=result.backend_name, backend_version=result.backend_version, qobj_id=result.qobj_id, job_id=result.job_id, success=result.success, results=[])
for i, label in enumerate(labels):
result.results[3 * i].name = str(label)
result.results[3 * i].header.name = str(label)
result.results[3 * i + 1].name = str(label)
result.results[3 * i + 1].header.name = str(label)
result.results[3 * i + 2].name = str(label)
result.results[3 * i + 2].header.name = str(label)
res1.results.append(result.results[3 * i])
res2.results.append(result.results[3 * i + 1])
res3.results.append(result.results[3 * i + 2])
reshaped_results += [res1, res2, res3]
from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter
# Compute the state tomography based on the st_qcs quantum circuits and the results from those ciricuits
def state_tomo(result, st_qcs):
# The expected final state; necessary to determine state tomography fidelity
target_state = (One^One^Zero).to_matrix() # DO NOT MODIFY (|q_5,q_3,q_1> = |110>)
# Fit state tomography results
tomo_fitter = StateTomographyFitter(result, st_qcs)
rho_fit = tomo_fitter.fit(method='lstsq')
# Compute fidelity
fid = state_fidelity(rho_fit, target_state)
return fid
# Number of trotter steps
num_steps = 100
print("trotter step: ", num_steps)
# Initialize quantum circuit for 3 qubits
qr = QuantumRegister(num_qubits, name="lq")
qc = QuantumCircuit(qr)
# Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>)
make_initial_state(qc, "110") # DO NOT MODIFY (|q_5,q_3,q_1> = |110>)
subspace_encoder_init110(qc, targets=[0, 1, 2]) # encode
trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian
subspace_decoder(qc, targets=[0,1,2]) # decode
# Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time
qc = qc.bind_parameters({dt: target_time / num_steps})
print("created qc")
# Generate state tomography circuits to evaluate fidelity of simulation
st_qcs = state_tomography_circuits(qc, [0, 1, 2][::-1]) #! state tomography requires === BIG ENDIAN ===
print("created st_qcs (length:", len(st_qcs), ")")
st_qcs[0].name
# Compute tomography fidelities for each repetition
fids = []
for result in reshaped_results:
fid = state_tomo(result, st_qcs)
fids.append(fid)
print('state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(fids), np.std(fids)))
fids
reshaped_results[0].results[0]
str(('X', 'X', 'X'))
|
https://github.com/iqm-finland/qiskit-on-iqm
|
iqm-finland
|
# Copyright 2022 Qiskit on IQM developers
#
# 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.
"""Qiskit Backend Provider for IQM backends.
"""
from copy import copy
from importlib.metadata import PackageNotFoundError, version
from functools import reduce
from typing import Optional, Union
from uuid import UUID
import warnings
import numpy as np
from qiskit import QuantumCircuit
from qiskit.providers import JobStatus, JobV1, Options
from iqm.iqm_client import Circuit, HeraldingMode, Instruction, IQMClient
from iqm.iqm_client.util import to_json_dict
from iqm.qiskit_iqm.fake_backends import IQMFakeAdonis
from iqm.qiskit_iqm.iqm_backend import IQMBackendBase
from iqm.qiskit_iqm.iqm_job import IQMJob
from iqm.qiskit_iqm.qiskit_to_iqm import MeasurementKey
try:
__version__ = version('qiskit-iqm')
except PackageNotFoundError: # pragma: no cover
__version__ = 'unknown'
finally:
del version, PackageNotFoundError
class IQMBackend(IQMBackendBase):
"""Backend for executing quantum circuits on IQM quantum computers.
Args:
client: client instance for communicating with an IQM server
**kwargs: optional arguments to be passed to the parent Backend initializer
"""
def __init__(self, client: IQMClient, **kwargs):
architecture = client.get_quantum_architecture()
super().__init__(architecture, **kwargs)
self.client: IQMClient = client
self._max_circuits: Optional[int] = None
self.name = f'IQM{architecture.name}Backend'
@classmethod
def _default_options(cls) -> Options:
return Options(
shots=1024,
calibration_set_id=None,
max_circuit_duration_over_t2=None,
heralding_mode=HeraldingMode.NONE,
circuit_callback=None,
)
@property
def max_circuits(self) -> Optional[int]:
"""Maximum number of circuits that should be run in a single batch.
Currently there is no hard limit on the number of circuits that can be executed in a single batch/job.
However, some libraries like Qiskit Experiments use this property to split multi-circuit computational
tasks into multiple baches/jobs.
The default value is ``None``, meaning there is no limit. You can set it to a specific integer
value to force these libraries to execute at most that many circuits in a single batch.
"""
return self._max_circuits
@max_circuits.setter
def max_circuits(self, value: Optional[int]) -> None:
self._max_circuits = value
def run(self, run_input: Union[QuantumCircuit, list[QuantumCircuit]], **options) -> IQMJob:
if self.client is None:
raise RuntimeError('Session to IQM client has been closed.')
circuits = [run_input] if isinstance(run_input, QuantumCircuit) else run_input
if len(circuits) == 0:
raise ValueError('Empty list of circuits submitted for execution.')
unknown_options = set(options.keys()) - set(self.options.keys())
if unknown_options:
warnings.warn(f'Unknown backend option(s): {unknown_options}')
# merge given options with default options and get resulting values
merged_options = copy(self.options)
merged_options.update_options(**dict(options))
shots = merged_options['shots']
calibration_set_id = merged_options['calibration_set_id']
if calibration_set_id is not None and not isinstance(calibration_set_id, UUID):
calibration_set_id = UUID(calibration_set_id)
max_circuit_duration_over_t2 = merged_options['max_circuit_duration_over_t2']
heralding_mode = merged_options['heralding_mode']
circuit_callback = merged_options['circuit_callback']
if circuit_callback:
circuit_callback(circuits)
circuits_serialized: list[Circuit] = [self.serialize_circuit(circuit) for circuit in circuits]
used_indices: set[int] = reduce(
lambda qubits, circuit: qubits.union(set(int(q) for q in circuit.all_qubits())), circuits_serialized, set()
)
qubit_mapping = {str(idx): qb for idx, qb in self._idx_to_qb.items() if idx in used_indices}
job_id = self.client.submit_circuits(
circuits_serialized,
qubit_mapping=qubit_mapping,
calibration_set_id=calibration_set_id if calibration_set_id else None,
shots=shots,
max_circuit_duration_over_t2=max_circuit_duration_over_t2,
heralding_mode=heralding_mode,
)
job = IQMJob(self, str(job_id), shots=shots)
job.circuit_metadata = [c.metadata for c in circuits]
return job
def retrieve_job(self, job_id: str) -> IQMJob:
"""Create and return an IQMJob instance associated with this backend with given job id."""
return IQMJob(self, job_id)
def close_client(self):
"""Close IQMClient's session with the authentication server. Discard the client."""
if self.client is not None:
self.client.close_auth_session()
self.client = None
def serialize_circuit(self, circuit: QuantumCircuit) -> Circuit:
"""Serialize a quantum circuit into the IQM data transfer format.
Serializing is not strictly bound to the native gateset, i.e. some gates that are not explicitly mentioned in
the native gateset of the backend can still be serialized. For example, the native single qubit gate for IQM
backend is the 'r' gate, however 'x', 'rx', 'y' and 'ry' gates can also be serialized since they are just
particular cases of the 'r' gate. If the circuit was transpiled against a backend using Qiskit's transpiler
machinery, these gates are not supposed to be present. However, when constructing circuits manually and
submitting directly to the backend, it is sometimes more explicit and understandable to use these concrete
gates rather than 'r'. Serializing them explicitly makes it possible for the backend to accept such circuits.
Qiskit uses one measurement instruction per qubit (i.e. there is no measurement grouping concept). While
serializing we do not group any measurements together but rather associate a unique measurement key with each
measurement instruction, so that the results can later be reconstructed correctly (see :class:`MeasurementKey`
documentation for more details).
Args:
circuit: quantum circuit to serialize
Returns:
data transfer object representing the circuit
Raises:
ValueError: circuit contains an unsupported instruction or is not transpiled in general
"""
# pylint: disable=too-many-branches
if len(circuit.qregs) != 1 or len(circuit.qregs[0]) != self.num_qubits:
raise ValueError(
f"The circuit '{circuit.name}' does not contain a single quantum register of length {self.num_qubits}, "
f'which indicates that it has not been transpiled against the current backend.'
)
instructions = []
for instruction, qubits, clbits in circuit.data:
qubit_names = [str(circuit.find_bit(qubit).index) for qubit in qubits]
if instruction.name == 'r':
angle_t = float(instruction.params[0] / (2 * np.pi))
phase_t = float(instruction.params[1] / (2 * np.pi))
instructions.append(
Instruction(name='prx', qubits=qubit_names, args={'angle_t': angle_t, 'phase_t': phase_t})
)
elif instruction.name == 'x':
instructions.append(Instruction(name='prx', qubits=qubit_names, args={'angle_t': 0.5, 'phase_t': 0.0}))
elif instruction.name == 'rx':
angle_t = float(instruction.params[0] / (2 * np.pi))
instructions.append(
Instruction(name='prx', qubits=qubit_names, args={'angle_t': angle_t, 'phase_t': 0.0})
)
elif instruction.name == 'y':
instructions.append(Instruction(name='prx', qubits=qubit_names, args={'angle_t': 0.5, 'phase_t': 0.25}))
elif instruction.name == 'ry':
angle_t = float(instruction.params[0] / (2 * np.pi))
instructions.append(
Instruction(name='prx', qubits=qubit_names, args={'angle_t': angle_t, 'phase_t': 0.25})
)
elif instruction.name == 'cz':
instructions.append(Instruction(name='cz', qubits=qubit_names, args={}))
elif instruction.name == 'move':
instructions.append(Instruction(name='move', qubits=qubit_names, args={}))
elif instruction.name == 'barrier':
instructions.append(Instruction(name='barrier', qubits=qubit_names, args={}))
elif instruction.name == 'measure':
mk = MeasurementKey.from_clbit(clbits[0], circuit)
instructions.append(Instruction(name='measure', qubits=qubit_names, args={'key': str(mk)}))
elif instruction.name == 'id':
pass
else:
raise ValueError(
f"Instruction '{instruction.name}' in the circuit '{circuit.name}' is not natively supported. "
f'You need to transpile the circuit before execution.'
)
try:
metadata = to_json_dict(circuit.metadata)
except ValueError:
warnings.warn(
f'Metadata of circuit {circuit.name} was dropped because it could not be serialised to JSON.',
)
metadata = None
return Circuit(name=circuit.name, instructions=instructions, metadata=metadata)
class IQMFacadeBackend(IQMBackend):
"""Facade backend for mimicking the execution of quantum circuits on IQM quantum computers. Allows to submit a
circuit to the IQM server, and if the execution was successful, performs a simulation with a respective IQM noise
model locally, then returns the simulated results.
Args:
client: client instance for communicating with an IQM server
**kwargs: optional arguments to be passed to the parent Backend initializer
"""
def __init__(self, client: IQMClient, **kwargs):
self.fake_adonis = IQMFakeAdonis()
target_architecture = client.get_quantum_architecture()
if not self.fake_adonis.validate_compatible_architecture(target_architecture):
raise ValueError('Quantum architecture of the remote quantum computer does not match Adonis.')
super().__init__(client, **kwargs)
self.client = client
self.name = f'IQMFacade{target_architecture.name}Backend'
def _validate_no_empty_cregs(self, circuit):
"""Returns True if given circuit has no empty (unused) classical registers, False otherwise."""
cregs_utilization = dict.fromkeys(circuit.cregs, 0)
used_cregs = [circuit.find_bit(i.clbits[0]).registers[0][0] for i in circuit.data if len(i.clbits) > 0]
for creg in used_cregs:
cregs_utilization[creg] += 1
if 0 in cregs_utilization.values():
return False
return True
def run(self, run_input: Union[QuantumCircuit, list[QuantumCircuit]], **options) -> JobV1:
circuits = [run_input] if isinstance(run_input, QuantumCircuit) else run_input
circuits_validated_cregs: list[bool] = [self._validate_no_empty_cregs(circuit) for circuit in circuits]
if not all(circuits_validated_cregs):
raise ValueError(
'One or more circuits contain unused classical registers. This is not allowed for Facade simulation, '
'see user guide.'
)
iqm_backend_job = super().run(run_input, **options)
iqm_backend_job.result() # get and discard results
if iqm_backend_job.status() == JobStatus.ERROR:
raise RuntimeError('Remote execution did not succeed.')
return self.fake_adonis.run(run_input, **options)
class IQMProvider:
"""Provider for IQM backends.
Args:
url: URL of the IQM Cortex server
Keyword Args:
auth_server_url: URL of the user authentication server, if required by the IQM Cortex server.
Can also be set in the ``IQM_AUTH_SERVER`` environment variable.
username: Username, if required by the IQM Cortex server.
Can also be set in the ``IQM_AUTH_USERNAME`` environment variable.
password: Password, if required by the IQM Cortex server.
Can also be set in the ``IQM_AUTH_PASSWORD`` environment variable.
"""
def __init__(self, url: str, **user_auth_args): # contains keyword args auth_server_url, username, password
self.url = url
self.user_auth_args = user_auth_args
def get_backend(self, name=None) -> Union[IQMBackend, IQMFacadeBackend]:
"""An IQMBackend instance associated with this provider.
Args:
name: optional name of a custom facade backend
"""
client = IQMClient(self.url, client_signature=f'qiskit-iqm {__version__}', **self.user_auth_args)
if name == 'facade_adonis':
return IQMFacadeBackend(client)
return IQMBackend(client)
|
https://github.com/TheGupta2012/QPE-Algorithms
|
TheGupta2012
|
from qiskit import QuantumCircuit, execute
from qiskit.tools.visualization import plot_histogram
from qiskit.extensions import UnitaryGate
import numpy as np
from IPython.display import display
class KQPE:
"""
Implements the Kitaev's phase estimation algorithm where a single circuit
is used to estimate the phase of a unitary but the measurements are
exponential.
Attributes :
precision : (int)the precision upto which the phase needs to be estimated
NOTE : precision is estimated as 2^(-precision)
unitary (np.ndarray or QuantumCircuit or UnitaryGate) : the unitary matrix for which
we want to find the phase, given its eigenvector
qubits (int) : the number of qubits on which the unitary matrix acts
Methods :
get_phase(QC,ancilla,clbits,backend, show) : generate the resultant phase associated with the given Unitary
and the given eigenvector
get_circuit(show,save_circ, circ_name ) : generate a Kitaev phase estimation circuit which can be attached
to the parent quantum circuit containing eigenvector of the unitary matrix
"""
def __init__(self, unitary, precision=10):
"""
Args :
precision(int) : The precision upto which the phase is estimated.
Interpreted as 2^(-precision).
eg. precision = 4 means the phase is going to be precise
upto 2^(-4).
unitary(np.ndarray or UnitaryGate or QuantumCircuit):
The unitary for which we want to determine the phase.
Raises :
TypeError : if precision or unitary are not of a valid type
ValueError : if precision is not valid
Examples :
# passing as array
theta = 1/6
U1 = np.ndarray([[1,0],
[0, np.exp(2*np.pi*1j*(theta))]])
kqpe1 = KQPE(precision = 8, unitary = U1)
# passing as QuantumCircuit
U2 = QuantumCircuit(1)
U2.rz(np.pi/7,0)
kqpe2 = KQPE(precision = 8,unitary = U2)
"""
# handle precision
if not isinstance(precision, int):
raise TypeError("Precision needs to be an integer")
elif precision <= 0:
raise ValueError("Precision needs to be >=0")
self.precision = 1 / (2 ** precision)
# handle unitary
if unitary is None:
raise Exception(
"Unitary needs to be specified for the Kitaev QPE algorithm"
)
elif (
not isinstance(unitary, np.ndarray)
and not isinstance(unitary, QuantumCircuit)
and not isinstance(unitary, UnitaryGate)
):
raise TypeError(
"A numpy array, QuantumCircuit or UnitaryGate needs to be passed as the unitary matrix"
)
self.unitary = unitary
# get the number of qubits in the unitary
if isinstance(unitary, np.ndarray):
self.qubits = int(np.log2(unitary.shape[0]))
else:
self.qubits = int(unitary.num_qubits)
def get_phase(self, QC, ancilla, clbits, backend, show=False):
"""This function is used to determine the final measured phase from the circuit
with the specified precision.
Args :
QC (QuantumCircuit) : the quantum circuit on which we have attached
the kitaev's estimation circuit. Must contain atleast 2
classical bits for correct running of the algorithm
ancilla(list-like) : the ancilla qubits to be used in the kitaev phase
estimation
clbits(list-like) : the classical bits in which the measurement results
of the given ancilla qubits is stored
backend(ibmq_backend or 'qasm_simulator') : the backend on which the
circuit is executed on
show(bool) : boolean to specify whether the progress and the circuit
need to be shown
Raises :
Exception : If a QuantumCircuit with less than 2 classical bits or less
than 3 qubits is passed, if the ancilla or the clbits are
not unique, if more than 2 of classical or ancilla bits are
provided
Returns :
phase(tuple) : (phase_dec, phase_binary) : A 2-tuple representing
the calculated phase in decimal and binary upto the given
precision
NOTE : for details of the math please refer to section2A of https://arxiv.org/pdf/1910.11696.pdf.
Examples :
U = np.array([[1, 0],
[0, np.exp(2*np.pi*1j*(1/3))]])
kqpe = KQPE(unitary=U, precision=16)
kq_circ = kqpe.get_circuit(show=True, save_circ=True,
circ_name="KQPE_circ_1qubit.JPG")
# defining parent quantum circuit
q = QuantumCircuit(5, 6)
#eigenvector of unitary
q.x(3)
#kitaev circuit is attached on the eigenvector and
# two additional ancilla qubits
q.append(kq_circ, qargs=[1, 2, 3])
q.draw('mpl')
# result
phase = kqpe.get_phase(backend=Aer.get_backend(
'qasm_simulator'), QC=q, ancilla=[1, 2], clbits=[0, 1], show=True)
"""
# handle circuit
if not isinstance(QC, QuantumCircuit):
raise TypeError(
"A QuantumCircuit must be provided for generating the phase"
)
if len(QC.clbits) < 2:
raise Exception("Atleast 2 classical bits needed for measurement")
elif len(QC.qubits) < 3:
raise Exception("Quantum Circuit needs to have atleast 3 qubits")
# handle bits
elif len(ancilla) != 2 or ancilla is None:
raise Exception("Exactly two ancilla bits need to be specified")
elif len(clbits) != 2 or clbits is None:
raise Exception(
"Exactly two classical bits need to be specified for measurement"
)
elif len(set(clbits)) != len(clbits) or len(set(ancilla)) != len(ancilla):
raise Exception("Duplicate bits provided in lists")
# find number of shots -> atleast Big-O(1/precision shots)
shots = 10 * int(1 / self.precision)
if show == True:
print("Shots :", shots)
# measure into the given bits
QC.measure([ancilla[0], ancilla[1]], [clbits[0], clbits[1]])
if show == True:
display(QC.draw("mpl"))
# execute the circuit
result = execute(
QC, backend=backend, shots=shots, optimization_level=3
).result()
counts = result.get_counts()
if show:
print("Measurement results :", counts)
if show:
display(plot_histogram(counts))
# now get the results
C0, C1, S0, S1 = 0, 0, 0, 0
first = clbits[0]
second = clbits[1]
for i, j in zip(list(counts.keys()), list(counts.values())):
# get bits
l = len(i)
one = i[l - first - 1]
two = i[l - second - 1]
# First qubit 0 - C (0,theta)
if one == "0":
C0 += j
# First qubit 1 - C (1,theta)
else:
C1 += j
# Second qubit 0 - S (0,theta)
if two == "0":
S0 += j
# Second qubit 1 - S (1,theta)
else:
S1 += j
# normalize
C0, C1, S0, S1 = C0 / shots, C1 / shots, S0 / shots, S1 / shots
# determine theta_0
tan_1 = np.arctan2([(1 - 2 * S0)], [(2 * C0 - 1)])[0]
theta_0 = (1 / (2 * np.pi)) * tan_1
# determine theta_1
tan_2 = np.arctan2([(2 * S1 - 1)], [(1 - 2 * C1)])[0]
theta_1 = (1 / (2 * np.pi)) * tan_2
phase_dec = np.average([theta_0, theta_1])
phase_binary = []
phase = phase_dec
# generate the binary representation
for i in range(int(np.log2((1 / self.precision)))):
phase *= 2
if phase < 1:
phase_binary.append(0)
else:
phase -= 1
phase_binary.append(1)
return (phase_dec, phase_binary)
def get_circuit(self, show=False, save_circ=False, circ_name="KQPE_circ.JPG"):
"""Returns a kitaev phase estimation circuit
with the unitary provided
Args:
show(bool) : whether to draw the circuit or not
Default - False
save_circ(bool) : whether to save the circuit in
an image or not. Default - False
circ_name(str) : filename with which the circuit
is stored. Default - KQPE_circ.JPG
Returns : A QuantumCircuit with the controlled unitary matrix
and relevant gates attached to the circuit.
Size of the circuit is (2 + the number of qubits in unitary)
Examples:
theta = 1/5
unitary = UnitaryGate(np.ndarray([[1,0],
[0, np.exp(2*np.pi*1j*(theta))]]))
kqpe = KQPE(unitary,precision = 10)
kq_circ = kqpe.get_circuit(show = True,save_circ = True, circ_name= "KQPE_circ_1qubit.JPG")
# attaching the circuit
q = QuantumCircuit(5, 6)
q.x(3)
q.append(kq_circ, qargs=[1, 2, 3])
q.draw('mpl')
"""
qc = QuantumCircuit(2 + self.qubits, name="KQPE")
qubits = [i for i in range(2, 2 + self.qubits)]
# make the unitary
if isinstance(self.unitary, np.ndarray):
U = UnitaryGate(data=self.unitary)
C_U = U.control(num_ctrl_qubits=1, label="CU", ctrl_state="1")
else:
C_U = self.unitary.control(num_ctrl_qubits=1, label="CU", ctrl_state="1")
# qubit 0 is for the H estimation
qc.h(0)
qc = qc.compose(C_U, qubits=[0] + qubits)
qc.h(0)
qc.barrier()
# qubit 1 is for the H + S estimation
qc.h(1)
qc.s(1)
qc = qc.compose(C_U, qubits=[1] + qubits)
qc.h(1)
qc.barrier()
if show == True:
if save_circ:
display(qc.draw("mpl", filename=circ_name))
else:
display(qc.draw("mpl"))
return qc
|
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
|
mmetcalf14
|
# -*- 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.
"""Decorator for using with Qiskit unit tests."""
import functools
import os
import sys
import unittest
from .utils import Path
from .http_recorder import http_recorder
from .testing_options import get_test_options
def is_aer_provider_available():
"""Check if the C++ simulator can be instantiated.
Returns:
bool: True if simulator executable is available
"""
# TODO: HACK FROM THE DEPTHS OF DESPAIR AS AER DOES NOT WORK ON MAC
if sys.platform == 'darwin':
return False
try:
import qiskit.providers.aer # pylint: disable=unused-import
except ImportError:
return False
return True
def requires_aer_provider(test_item):
"""Decorator that skips test if qiskit aer provider is not available
Args:
test_item (callable): function or class to be decorated.
Returns:
callable: the decorated function.
"""
reason = 'Aer provider not found, skipping test'
return unittest.skipIf(not is_aer_provider_available(), reason)(test_item)
def slow_test(func):
"""Decorator that signals that the test takes minutes to run.
Args:
func (callable): test function to be decorated.
Returns:
callable: the decorated function.
"""
@functools.wraps(func)
def _wrapper(*args, **kwargs):
skip_slow = not TEST_OPTIONS['run_slow']
if skip_slow:
raise unittest.SkipTest('Skipping slow tests')
return func(*args, **kwargs)
return _wrapper
def _get_credentials(test_object, test_options):
"""Finds the credentials for a specific test and options.
Args:
test_object (QiskitTestCase): The test object asking for credentials
test_options (dict): Options after QISKIT_TESTS was parsed by
get_test_options.
Returns:
Credentials: set of credentials
Raises:
ImportError: if the
Exception: when the credential could not be set and they are needed
for that set of options
"""
try:
from qiskit.providers.ibmq.credentials import (Credentials,
discover_credentials)
except ImportError:
raise ImportError('qiskit-ibmq-provider could not be found, and is '
'required for mocking or executing online tests.')
dummy_credentials = Credentials(
'dummyapiusersloginWithTokenid01',
'https://quantumexperience.ng.bluemix.net/api')
if test_options['mock_online']:
return dummy_credentials
if os.getenv('USE_ALTERNATE_ENV_CREDENTIALS', ''):
# Special case: instead of using the standard credentials mechanism,
# load them from different environment variables. This assumes they
# will always be in place, as is used by the Travis setup.
return Credentials(os.getenv('IBMQ_TOKEN'), os.getenv('IBMQ_URL'))
else:
# Attempt to read the standard credentials.
discovered_credentials = discover_credentials()
if discovered_credentials:
# Decide which credentials to use for testing.
if len(discovered_credentials) > 1:
try:
# Attempt to use QE credentials.
return discovered_credentials[dummy_credentials.unique_id()]
except KeyError:
pass
# Use the first available credentials.
return list(discovered_credentials.values())[0]
# No user credentials were found.
if test_options['rec']:
raise Exception('Could not locate valid credentials. You need them for '
'recording tests against the remote API.')
test_object.log.warning('No user credentials were detected. '
'Running with mocked data.')
test_options['mock_online'] = True
return dummy_credentials
def requires_qe_access(func):
"""Decorator that signals that the test uses the online API:
It involves:
* determines if the test should be skipped by checking environment
variables.
* if the `USE_ALTERNATE_ENV_CREDENTIALS` environment variable is
set, it reads the credentials from an alternative set of environment
variables.
* if the test is not skipped, it reads `qe_token` and `qe_url` from
`Qconfig.py`, environment variables or qiskitrc.
* if the test is not skipped, it appends `qe_token` and `qe_url` as
arguments to the test function.
Args:
func (callable): test function to be decorated.
Returns:
callable: the decorated function.
"""
@functools.wraps(func)
def _wrapper(self, *args, **kwargs):
if TEST_OPTIONS['skip_online']:
raise unittest.SkipTest('Skipping online tests')
credentials = _get_credentials(self, TEST_OPTIONS)
self.using_ibmq_credentials = credentials.is_ibmq()
kwargs.update({'qe_token': credentials.token,
'qe_url': credentials.url})
decorated_func = func
if TEST_OPTIONS['rec'] or TEST_OPTIONS['mock_online']:
# For recording or for replaying existing cassettes, the test
# should be decorated with @use_cassette.
vcr_mode = 'new_episodes' if TEST_OPTIONS['rec'] else 'none'
decorated_func = http_recorder(
vcr_mode, Path.CASSETTES.value).use_cassette()(decorated_func)
return decorated_func(self, *args, **kwargs)
return _wrapper
TEST_OPTIONS = get_test_options()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import numpy as np
from qiskit import QuantumCircuit
from qiskit.quantum_info import DensityMatrix
from qiskit.visualization import plot_state_hinton
qc = QuantumCircuit(2)
qc.h([0, 1])
qc.cz(0,1)
qc.ry(np.pi/3 , 0)
qc.rx(np.pi/5, 1)
state = DensityMatrix(qc)
plot_state_hinton(state, title="New Hinton Plot")
|
https://github.com/abbarreto/qiskit2
|
abbarreto
|
import qiskit
from qiskit import *
import math
import numpy as np
def qc_ezz(t):
qc = QuantumCircuit(2, name = 'e^(-itZZ)')
qc.cx(0, 1); qc.rz(2*t, 1); qc.cx(0, 1)
return qc
def qc_exx(t):
qc = QuantumCircuit(2, name = 'e^(-itXX)')
qc.h([0,1]); qc.cx(0, 1); qc.rz(2*t, 1); qc.cx(0, 1); qc.h([0,1])
return qc
def qc_eyy(t):
qc = QuantumCircuit(2, name = 'e^(-itYY)')
qc.sdg([0,1]); qc.h([0,1]); qc.cx(0, 1); qc.rz(2*t, 1); qc.cx(0, 1); qc.h([0,1]); qc.s([0,1])
return qc
def qc_Bj(t):
qc = QuantumCircuit(3, name = 'B_j')
qc_ezz_ = qc_ezz(t); qc_eyy_ = qc_eyy(t); qc_exx_ = qc_exx(t)
qc.append(qc_ezz_, [1, 2]); qc.append(qc_eyy_, [1, 2]); qc.append(qc_exx_, [1, 2])
qc.append(qc_ezz_, [0, 1]); qc.append(qc_eyy_, [0, 1]); qc.append(qc_exx_, [0, 1])
return qc
qc_Bj_ = qc_Bj(math.pi/2); qc_Bj_.draw(output='mpl')
qc_Bj_.decompose().draw(output='mpl')
nshots = 8192
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22')
#provider = qiskit.IBMQ.get_provider(hub = 'ibm-q-research-2', group = 'federal-uni-sant-1', project = 'main')
device = provider.get_backend('ibmq_jakarta')
simulator = Aer.get_backend('qasm_simulator')
from qiskit.tools.monitor import job_monitor
from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter
from qiskit.tools.monitor import backend_overview, backend_monitor
from qiskit.providers.aer import noise
from qiskit.providers.aer.noise import NoiseModel
from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter
noise_model = NoiseModel.from_backend(device)
basis_gates = noise_model.basis_gates
coupling_map = device.configuration().coupling_map
ket0 = np.array([[1],[0]]); ket1 = np.array([[0],[1]]);
psi0 = np.kron(ket0, np.kron(ket1, ket1)) # initial state to be used for computing the fidelity
t = math.pi
for j in range(0, 10): # Trotter stepsm_info.
# quantum circuit
qc = QuantumCircuit(7)
qc.x([5, 3]) # prepares the initial state
qc_Bj_ = qc_Bj(t/(j+1))
for k in range(0, j+1):
qc.append(qc_Bj_, [5, 3, 1])
qstc = state_tomography_circuits(qc, [5, 3, 1])
# simulation
job_sim = execute(qstc, backend = simulator, shots = nshots)
qstf_sim = StateTomographyFitter(job_sim.result(), qstc)
rho_sim = qstf_sim.fit(method = 'lstsq')
F_sim = quantum_info.state_fidelity(psi0, rho_sim)
# simulation with simulated noise
job_exp = execute(qstc, backend = simulator, shots = nshots, noise_model = noise_model,
basis_gates = basis_gates, coupling_map = coupling_map)
qstf_exp = StateTomographyFitter(job_exp.result(), qstc)
rho_exp = qstf_exp.fit(method = 'lstsq')
F_exp = quantum_info.state_fidelity(psi0, rho_exp)
print('No. passos=', j+1, ',F_sim=', F_sim, ',F_exp=', F_exp)
inha visto essa reprovaΓ§Γ£o mas nΓ£o me dei por conta que n# for error mitigation
qr = QuantumRegister(7)
qubit_list = [5,3,1] # the qubits on which we shall apply error mitigation
meas_calibs, state_labels = complete_meas_cal(qubit_list = qubit_list, qr = qr)
job_cal = execute(meas_calibs, backend = simulator, shots = nshots, noise_model = noise_model,
basis_gates = basis_gates, coupling_map = coupling_map)
meas_fitter = CompleteMeasFitter(job_cal.result(), state_labels)
ket0 = np.array([[1],[0]]); ket1 = np.array([[0],[1]]); #ket0, ket1
psi0 = np.kron(ket0, np.kron(ket1, ket1)) # initial state to be used for computing the fidelity
t = math.pi
for j in range(0, 10): # Trotter steps
# quantum circuit
qc = QuantumCircuit(7)
qc.x([5, 3]) # prepares the initial state
qc_Bj_ = qc_Bj(t/(j+1))
for k in range(0, j+1):
qc.append(qc_Bj_, [5, 3, 1])
qstc = state_tomography_circuits(qc, [5, 3, 1])
# simulation
job_sim = execute(qstc, backend = simulator, shots = nshots)
qstf_sim = StateTomographyFitter(job_sim.result(), qstc)
rho_sim = qstf_sim.fit(method = 'lstsq')
F_sim = quantum_info.state_fidelity(psi0, rho_sim)
# simulation with simulated noise and error mitigation
job_exp = execute(qstc, backend = simulator, shots = nshots, noise_model = noise_model,
basis_gates = basis_gates, coupling_map = coupling_map)
mitigated_results = meas_fitter.filter.apply(job_exp.result())
qstf_exp = StateTomographyFitter(mitigated_results, qstc)
rho_exp = qstf_exp.fit(method = 'lstsq')
F_exp = quantum_info.state_fidelity(psi0, rho_exp)
print('No. passos=', j+1, ',F_sim=', F_sim, ',F_exp=', F_exp)
def qc_Bj_zz(t, th, ph):
qc = QuantumCircuit(3, name = 'B_j_zz')
qc_ezz_ = qc_ezz(t); qc_eyy_ = qc_eyy(t); qc_exx_ = qc_exx(t)
qc.rz(2*th, [1,2])
qc.append(qc_ezz_, [1, 2]); qc.append(qc_eyy_, [1, 2]); qc.append(qc_exx_, [1, 2])
qc.rz(-2*th, [1,2])
qc.rz(2*ph, [0,1])
qc.append(qc_ezz_, [0, 1]); qc.append(qc_eyy_, [0, 1]); qc.append(qc_exx_, [0, 1])
qc.rz(-2*ph, [0,1])
return qc
qc_Bj_zz_ = qc_Bj_zz(math.pi, math.pi/3, math.pi/4); qc_Bj_zz_.draw(output='mpl')
ket0 = np.array([[1],[0]]); ket1 = np.array([[0],[1]]); #ket0, ket1
psi0 = np.kron(ket0, np.kron(ket1, ket1)) # initial state to be used for computing the fidelity
t = math.pi
j = 6; print('N. of Trotter steps = ', j+1)
th_max = 2*math.pi; dth = th_max/16; th = np.arange(0, th_max+dth, dth); dim_th = th.shape[0]
ph_max = 2*math.pi; dph = ph_max/16; ph = np.arange(0, ph_max+dph, dph); dim_ph = ph.shape[0]
for m in range(0, dim_th):
for n in range(0, dim_ph):
# quantum circuit
qc = QuantumCircuit(7)
qc.x([5, 3]) # prepares the initial state
qc_Bj_zz_ = qc_Bj_zz(t/(j+1), th[m], ph[n])
for k in range(0, j+1):
qc.append(qc_Bj_zz_, [5, 3, 1])
qstc = state_tomography_circuits(qc, [5, 3, 1])
# simulation
job_sim = execute(qstc, backend = simulator, shots = nshots)
qstf_sim = StateTomographyFitter(job_sim.result(), qstc)
rho_sim = qstf_sim.fit(method = 'lstsq')
F_sim = quantum_info.state_fidelity(psi0, rho_sim)
# simulation with simulated noise and error mitigation
job_exp = execute(qstc, backend = simulator, shots = nshots, noise_model = noise_model,
basis_gates = basis_gates, coupling_map = coupling_map)
mitigated_results = meas_fitter.filter.apply(job_exp.result())
qstf_exp = StateTomographyFitter(mitigated_results, qstc)
rho_exp = qstf_exp.fit(method = 'lstsq')
F_exp = quantum_info.state_fidelity(psi0, rho_exp)
print('th=', th[m], ', ph=', ph[n], ', F_sim=', F_sim, ', F_exp=', F_exp)
def qc_Bj_zx(t, th, ph):
qc = QuantumCircuit(3, name = 'B_j_zz')
qc_ezz_ = qc_ezz(t); qc_eyy_ = qc_eyy(t); qc_exx_ = qc_exx(t)
qc.rx(2*th, [1,2])
qc.append(qc_ezz_, [1, 2]); qc.append(qc_eyy_, [1, 2]); qc.append(qc_exx_, [1, 2])
qc.rx(-2*th, [1,2])
qc.rz(2*ph, [0,1])
qc.append(qc_ezz_, [0, 1]); qc.append(qc_eyy_, [0, 1]); qc.append(qc_exx_, [0, 1])
qc.rz(-2*ph, [0,1])
return qc
qc_Bj_zx_ = qc_Bj_zx(math.pi, math.pi/3, math.pi/4); qc_Bj_zx_.draw(output='mpl')
inha visto essa reprovaΓ§Γ£o mas nΓ£o me dei por conta que nket0 = np.array([[1],[0]]); ket1 = np.array([[0],[1]]); #ket0, ket1
psi0 = np.kron(ket0, np.kron(ket1, ket1)) # initial state to be used for computing the fidelity
t = math.pi
j = 6; print('N. of Trotter steps = ', j+1)
th_max = 2*math.pi; dth = th_max/16; th = np.arange(0, th_max+dth, dth); dim_th = th.shape[0]
ph_max = 2*math.pi; dph = ph_max/16; ph = np.arange(0, ph_max+dph, dph); dim_ph = ph.shape[0]
for m in range(0, dim_th):
for n in range(0, dim_ph):
# quantum circuit
qc = QuantumCircuit(7)
qc.x([5, 3]) # prepares the initial state
qc_Bj_zx_ = qc_Bj_zx(t/(j+1), th[m], ph[n])
for k in range(0, j+1):
qc.append(qc_Bj_zx_, [5, 3, 1])
qstc = state_tomography_circuits(qc, [5, 3, 1])
# simulation
job_sim = execute(qstc, backend = simulator, shots = nshots)
qstf_sim = StateTomographyFitter(job_sim.result(), qstc)
rho_sim = qstf_sim.fit(method = 'lstsq')
F_sim = quantum_info.state_fidelity(psi0, rho_sim)
# simulation with simulated noise and error mitigation
job_exp = execute(qstc, backend = simulator, shots = nshots, noise_model = noise_model,
basis_gates = basis_gates, coupling_map = coupling_map)
mitigated_results = meas_fitter.filter.apply(job_exp.result())
qstf_exp = StateTomographyFitter(mitigated_results, qstc)
rho_exp = qstf_exp.fit(method = 'lstsq')
F_exp = quantum_info.state_fidelity(psi0, rho_exp)
print('th=', th[m], ', ph=', ph[n], ', F_sim=', F_sim, ', F_exp=', F_exp)
def qc_Bj_yx(t, th, ph):
qc = QuantumCircuit(3, name = 'B_j_zz')
qc_ezz_ = qc_ezz(t); qc_eyy_ = qc_eyy(t); qc_exx_ = qc_exx(t)
qc.rx(2*th, [1,2])
qc.append(qc_ezz_, [1, 2]); qc.append(qc_eyy_, [1, 2]); qc.append(qc_exx_, [1, 2])
qc.rx(-2*th, [1,2])
qc.barrier()
qc.ry(2*ph, [0,1])
qc.append(qc_ezz_, [0, 1]); qc.append(qc_eyy_, [0, 1]); qc.append(qc_exx_, [0, 1])
qc.ry(-2*ph, [0,1])
return qc
qc_Bj_yx_ = qc_Bj_yx(math.pi, math.pi/3, math.pi/4); qc_Bj_yx_.draw(output='mpl')
https://arxiv.org/abs/2204.07816ket0 = np.array([[1],[0]]); ket1 = np.array([[0],[1]]); #ket0, ket1
psi0 = np.kron(ket0, np.kron(ket1, ket1)) # initial state to be used for computing the fidelity
t = math.pi
j = 6; print('N. of Trotter steps = ', j+1)
th_max = 2*math.pi; dth = th_max/16; th = np.arange(0, th_max+dth, dth); dim_th = th.shape[0]
ph_max = 2*math.pi; dph = ph_max/16; ph = np.arange(0, ph_max+dph, dph); dim_ph = ph.shape[0]
for m in range(0, dim_th):
for n in range(0, dim_ph):
# quantum circuit
qc = QuantumCircuit(7)
qc.x([5, 3]) # prepares the initial state
qc_Bj_yx_ = qc_Bj_yx(t/(j+1), th[m], ph[n])
for k in range(0, j+1):
qc.append(qc_Bj_yx_, [5, 3, 1])
qstc = state_tomography_circuits(qc, [5, 3, 1])
# simulation
job_sim = execute(qstc, backend = simulator, shots = nshots)
qstf_sim = StateTomographyFitter(job_sim.result(), qstc)
rho_sim = qstf_sim.fit(method = 'lstsq')
F_sim = quantum_info.state_fidelity(psi0, rho_sim)
# simulation with simulated noise and error mitigation0.34
job_exp = execute(qstc, backend = simulator, shots = nshots, noise_model = noise_model,
basis_gates = basis_gates, coupling_map = coupling_map)
mitigated_results = meas_fitter.filter.apply(job_exp.result())
qstf_exp = StateTomographyFitter(mitigated_results, qstc)
rho_exp = qstf_exp.fit(method = 'lstsq')
F_exp = quantum_info.state_fidelity(psi0, rho_exp)
print('th=', th[m], ', ph=', ph[n], ', F_sim=', F_sim, ', F_exp=', F_exp)
noise_model = NoiseModel.from_backend(device)
basis_gates = noise_model.basis_gates
coupling_map = device.configuration().coupling_map
basis_gates
print(coupling_map)
553/3
|
https://github.com/2lambda123/Qiskit-qiskit
|
2lambda123
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
# pylint: disable=unused-argument
"""Waveform generators.
A collection of functions that generate drawings from formatted input data.
See py:mod:`qiskit.visualization.pulse_v2.types` for more info on the required data.
In this module the input data is `types.PulseInstruction`.
An end-user can write arbitrary functions that generate custom drawings.
Generators in this module are called with the `formatter` and `device` kwargs.
These data provides stylesheet configuration and backend system configuration.
The format of generator is restricted to:
```python
def my_object_generator(data: PulseInstruction,
formatter: Dict[str, Any],
device: DrawerBackendInfo) -> List[ElementaryData]:
pass
```
Arbitrary generator function satisfying the above format can be accepted.
Returned `ElementaryData` can be arbitrary subclasses that are implemented in
the plotter API.
"""
from __future__ import annotations
import re
from fractions import Fraction
from typing import Any
import numpy as np
from qiskit import pulse, circuit
from qiskit.pulse import instructions, library
from qiskit.visualization.exceptions import VisualizationError
from qiskit.visualization.pulse_v2 import drawings, types, device_info
def gen_filled_waveform_stepwise(
data: types.PulseInstruction, formatter: dict[str, Any], device: device_info.DrawerBackendInfo
) -> list[drawings.LineData | drawings.BoxData | drawings.TextData]:
"""Generate filled area objects of the real and the imaginary part of waveform envelope.
The curve of envelope is not interpolated nor smoothed and presented
as stepwise function at each data point.
Stylesheets:
- The `fill_waveform` style is applied.
Args:
data: Waveform instruction data to draw.
formatter: Dictionary of stylesheet settings.
device: Backend configuration.
Returns:
List of `LineData`, `BoxData`, or `TextData` drawings.
Raises:
VisualizationError: When the instruction parser returns invalid data format.
"""
# generate waveform data
waveform_data = _parse_waveform(data)
channel = data.inst.channel
# update metadata
meta = waveform_data.meta
qind = device.get_qubit_index(channel)
meta.update({"qubit": qind if qind is not None else "N/A"})
if isinstance(waveform_data, types.ParsedInstruction):
# Draw waveform with fixed shape
xdata = waveform_data.xvals
ydata = waveform_data.yvals
# phase modulation
if formatter["control.apply_phase_modulation"]:
ydata = np.asarray(ydata, dtype=complex) * np.exp(1j * data.frame.phase)
else:
ydata = np.asarray(ydata, dtype=complex)
return _draw_shaped_waveform(
xdata=xdata, ydata=ydata, meta=meta, channel=channel, formatter=formatter
)
elif isinstance(waveform_data, types.OpaqueShape):
# Draw parametric pulse with unbound parameters
# parameter name
unbound_params = []
for pname, pval in data.inst.pulse.parameters.items():
if isinstance(pval, circuit.ParameterExpression):
unbound_params.append(pname)
pulse_data = data.inst.pulse
if isinstance(pulse_data, library.SymbolicPulse):
pulse_shape = pulse_data.pulse_type
else:
pulse_shape = "Waveform"
return _draw_opaque_waveform(
init_time=data.t0,
duration=waveform_data.duration,
pulse_shape=pulse_shape,
pnames=unbound_params,
meta=meta,
channel=channel,
formatter=formatter,
)
else:
raise VisualizationError("Invalid data format is provided.")
def gen_ibmq_latex_waveform_name(
data: types.PulseInstruction, formatter: dict[str, Any], device: device_info.DrawerBackendInfo
) -> list[drawings.TextData]:
r"""Generate the formatted instruction name associated with the waveform.
Channel name and ID string are removed and the rotation angle is expressed in units of pi.
The controlled rotation angle associated with the CR pulse name is divided by 2.
Note that in many scientific articles the controlled rotation angle implies
the actual rotation angle, but in IQX backend the rotation angle represents
the difference between rotation angles with different control qubit states.
For example:
- 'X90p_d0_abcdefg' is converted into 'X(\frac{\pi}{2})'
- 'CR90p_u0_abcdefg` is converted into 'CR(\frac{\pi}{4})'
Stylesheets:
- The `annotate` style is applied.
Notes:
This generator can convert pulse names used in the IQX backends.
If pulses are provided by the third party providers or the user defined,
the generator output may be the as-is pulse name.
Args:
data: Waveform instruction data to draw.
formatter: Dictionary of stylesheet settings.
device: Backend configuration.
Returns:
List of `TextData` drawings.
"""
if data.is_opaque:
return []
style = {
"zorder": formatter["layer.annotate"],
"color": formatter["color.annotate"],
"size": formatter["text_size.annotate"],
"va": "center",
"ha": "center",
}
if isinstance(data.inst, pulse.instructions.Acquire):
systematic_name = "Acquire"
latex_name = None
elif isinstance(data.inst, instructions.Delay):
systematic_name = data.inst.name or "Delay"
latex_name = None
else:
pulse_data = data.inst.pulse
if pulse_data.name:
systematic_name = pulse_data.name
else:
if isinstance(pulse_data, library.SymbolicPulse):
systematic_name = pulse_data.pulse_type
else:
systematic_name = "Waveform"
template = r"(?P<op>[A-Z]+)(?P<angle>[0-9]+)?(?P<sign>[pm])_(?P<ch>[dum])[0-9]+"
match_result = re.match(template, systematic_name)
if match_result is not None:
match_dict = match_result.groupdict()
sign = "" if match_dict["sign"] == "p" else "-"
if match_dict["op"] == "CR":
# cross resonance
if match_dict["ch"] == "u":
op_name = r"{\rm CR}"
else:
op_name = r"\overline{\rm CR}"
# IQX name def is not standard. Echo CR is annotated with pi/4 rather than pi/2
angle_val = match_dict["angle"]
frac = Fraction(int(int(angle_val) / 2), 180)
if frac.numerator == 1:
angle = rf"\pi/{frac.denominator:d}"
else:
angle = r"{num:d}/{denom:d} \pi".format(
num=frac.numerator, denom=frac.denominator
)
else:
# single qubit pulse
op_name = r"{{\rm {}}}".format(match_dict["op"])
angle_val = match_dict["angle"]
if angle_val is None:
angle = r"\pi"
else:
frac = Fraction(int(angle_val), 180)
if frac.numerator == 1:
angle = rf"\pi/{frac.denominator:d}"
else:
angle = r"{num:d}/{denom:d} \pi".format(
num=frac.numerator, denom=frac.denominator
)
latex_name = rf"{op_name}({sign}{angle})"
else:
latex_name = None
text = drawings.TextData(
data_type=types.LabelType.PULSE_NAME,
channels=data.inst.channel,
xvals=[data.t0 + 0.5 * data.inst.duration],
yvals=[-formatter["label_offset.pulse_name"]],
text=systematic_name,
latex=latex_name,
ignore_scaling=True,
styles=style,
)
return [text]
def gen_waveform_max_value(
data: types.PulseInstruction, formatter: dict[str, Any], device: device_info.DrawerBackendInfo
) -> list[drawings.TextData]:
"""Generate the annotation for the maximum waveform height for
the real and the imaginary part of the waveform envelope.
Maximum values smaller than the vertical resolution limit is ignored.
Stylesheets:
- The `annotate` style is applied.
Args:
data: Waveform instruction data to draw.
formatter: Dictionary of stylesheet settings.
device: Backend configuration.
Returns:
List of `TextData` drawings.
"""
if data.is_opaque:
return []
style = {
"zorder": formatter["layer.annotate"],
"color": formatter["color.annotate"],
"size": formatter["text_size.annotate"],
"ha": "center",
}
# only pulses.
if isinstance(data.inst, instructions.Play):
# pulse
operand = data.inst.pulse
if isinstance(operand, (pulse.ParametricPulse, pulse.SymbolicPulse)):
pulse_data = operand.get_waveform()
else:
pulse_data = operand
xdata = np.arange(pulse_data.duration) + data.t0
ydata = pulse_data.samples
else:
return []
# phase modulation
if formatter["control.apply_phase_modulation"]:
ydata = np.asarray(ydata, dtype=complex) * np.exp(1j * data.frame.phase)
else:
ydata = np.asarray(ydata, dtype=complex)
texts = []
# max of real part
re_maxind = np.argmax(np.abs(ydata.real))
if np.abs(ydata.real[re_maxind]) > 0.01:
# generator shows only 2 digits after the decimal point.
if ydata.real[re_maxind] > 0:
max_val = f"{ydata.real[re_maxind]:.2f}\n\u25BE"
re_style = {"va": "bottom"}
else:
max_val = f"\u25B4\n{ydata.real[re_maxind]:.2f}"
re_style = {"va": "top"}
re_style.update(style)
re_text = drawings.TextData(
data_type=types.LabelType.PULSE_INFO,
channels=data.inst.channel,
xvals=[xdata[re_maxind]],
yvals=[ydata.real[re_maxind]],
text=max_val,
styles=re_style,
)
texts.append(re_text)
# max of imag part
im_maxind = np.argmax(np.abs(ydata.imag))
if np.abs(ydata.imag[im_maxind]) > 0.01:
# generator shows only 2 digits after the decimal point.
if ydata.imag[im_maxind] > 0:
max_val = f"{ydata.imag[im_maxind]:.2f}\n\u25BE"
im_style = {"va": "bottom"}
else:
max_val = f"\u25B4\n{ydata.imag[im_maxind]:.2f}"
im_style = {"va": "top"}
im_style.update(style)
im_text = drawings.TextData(
data_type=types.LabelType.PULSE_INFO,
channels=data.inst.channel,
xvals=[xdata[im_maxind]],
yvals=[ydata.imag[im_maxind]],
text=max_val,
styles=im_style,
)
texts.append(im_text)
return texts
def _draw_shaped_waveform(
xdata: np.ndarray,
ydata: np.ndarray,
meta: dict[str, Any],
channel: pulse.channels.PulseChannel,
formatter: dict[str, Any],
) -> list[drawings.LineData | drawings.BoxData | drawings.TextData]:
"""A private function that generates drawings of stepwise pulse lines.
Args:
xdata: Array of horizontal coordinate of waveform envelope.
ydata: Array of vertical coordinate of waveform envelope.
meta: Metadata dictionary of the waveform.
channel: Channel associated with the waveform to draw.
formatter: Dictionary of stylesheet settings.
Returns:
List of drawings.
Raises:
VisualizationError: When the waveform color for channel is not defined.
"""
fill_objs: list[drawings.LineData | drawings.BoxData | drawings.TextData] = []
resolution = formatter["general.vertical_resolution"]
# stepwise interpolation
xdata: np.ndarray = np.concatenate((xdata, [xdata[-1] + 1]))
ydata = np.repeat(ydata, 2)
re_y = np.real(ydata)
im_y = np.imag(ydata)
time: np.ndarray = np.concatenate(([xdata[0]], np.repeat(xdata[1:-1], 2), [xdata[-1]]))
# setup style options
style = {
"alpha": formatter["alpha.fill_waveform"],
"zorder": formatter["layer.fill_waveform"],
"linewidth": formatter["line_width.fill_waveform"],
"linestyle": formatter["line_style.fill_waveform"],
}
try:
color_real, color_imag = formatter["color.waveforms"][channel.prefix.upper()]
except KeyError as ex:
raise VisualizationError(
f"Waveform color for channel type {channel.prefix} is not defined"
) from ex
# create real part
if np.any(re_y):
# data compression
re_valid_inds = _find_consecutive_index(re_y, resolution)
# stylesheet
re_style = {"color": color_real}
re_style.update(style)
# metadata
re_meta = {"data": "real"}
re_meta.update(meta)
# active xy data
re_xvals = time[re_valid_inds]
re_yvals = re_y[re_valid_inds]
# object
real = drawings.LineData(
data_type=types.WaveformType.REAL,
channels=channel,
xvals=re_xvals,
yvals=re_yvals,
fill=formatter["control.fill_waveform"],
meta=re_meta,
styles=re_style,
)
fill_objs.append(real)
# create imaginary part
if np.any(im_y):
# data compression
im_valid_inds = _find_consecutive_index(im_y, resolution)
# stylesheet
im_style = {"color": color_imag}
im_style.update(style)
# metadata
im_meta = {"data": "imag"}
im_meta.update(meta)
# active xy data
im_xvals = time[im_valid_inds]
im_yvals = im_y[im_valid_inds]
# object
imag = drawings.LineData(
data_type=types.WaveformType.IMAG,
channels=channel,
xvals=im_xvals,
yvals=im_yvals,
fill=formatter["control.fill_waveform"],
meta=im_meta,
styles=im_style,
)
fill_objs.append(imag)
return fill_objs
def _draw_opaque_waveform(
init_time: int,
duration: int,
pulse_shape: str,
pnames: list[str],
meta: dict[str, Any],
channel: pulse.channels.PulseChannel,
formatter: dict[str, Any],
) -> list[drawings.LineData | drawings.BoxData | drawings.TextData]:
"""A private function that generates drawings of stepwise pulse lines.
Args:
init_time: Time when the opaque waveform starts.
duration: Duration of opaque waveform. This can be None or ParameterExpression.
pulse_shape: String that represents pulse shape.
pnames: List of parameter names.
meta: Metadata dictionary of the waveform.
channel: Channel associated with the waveform to draw.
formatter: Dictionary of stylesheet settings.
Returns:
List of drawings.
"""
fill_objs: list[drawings.LineData | drawings.BoxData | drawings.TextData] = []
fc, ec = formatter["color.opaque_shape"]
# setup style options
box_style = {
"zorder": formatter["layer.fill_waveform"],
"alpha": formatter["alpha.opaque_shape"],
"linewidth": formatter["line_width.opaque_shape"],
"linestyle": formatter["line_style.opaque_shape"],
"facecolor": fc,
"edgecolor": ec,
}
if duration is None or isinstance(duration, circuit.ParameterExpression):
duration = formatter["box_width.opaque_shape"]
box_obj = drawings.BoxData(
data_type=types.WaveformType.OPAQUE,
channels=channel,
xvals=[init_time, init_time + duration],
yvals=[
-0.5 * formatter["box_height.opaque_shape"],
0.5 * formatter["box_height.opaque_shape"],
],
meta=meta,
ignore_scaling=True,
styles=box_style,
)
fill_objs.append(box_obj)
# parameter name
func_repr = "{func}({params})".format(func=pulse_shape, params=", ".join(pnames))
text_style = {
"zorder": formatter["layer.annotate"],
"color": formatter["color.annotate"],
"size": formatter["text_size.annotate"],
"va": "bottom",
"ha": "center",
}
text_obj = drawings.TextData(
data_type=types.LabelType.OPAQUE_BOXTEXT,
channels=channel,
xvals=[init_time + 0.5 * duration],
yvals=[0.5 * formatter["box_height.opaque_shape"]],
text=func_repr,
ignore_scaling=True,
styles=text_style,
)
fill_objs.append(text_obj)
return fill_objs
def _find_consecutive_index(data_array: np.ndarray, resolution: float) -> np.ndarray:
"""A helper function to return non-consecutive index from the given list.
This drastically reduces memory footprint to represent a drawing,
especially for samples of very long flat-topped Gaussian pulses.
Tiny value fluctuation smaller than `resolution` threshold is removed.
Args:
data_array: The array of numbers.
resolution: Minimum resolution of sample values.
Returns:
The compressed data array.
"""
try:
vector = np.asarray(data_array, dtype=float)
diff = np.diff(vector)
diff[np.where(np.abs(diff) < resolution)] = 0
# keep left and right edges
consecutive_l = np.insert(diff.astype(bool), 0, True)
consecutive_r = np.append(diff.astype(bool), True)
return consecutive_l | consecutive_r
except ValueError:
return np.ones_like(data_array).astype(bool)
def _parse_waveform(
data: types.PulseInstruction,
) -> types.ParsedInstruction | types.OpaqueShape:
"""A helper function that generates an array for the waveform with
instruction metadata.
Args:
data: Instruction data set
Raises:
VisualizationError: When invalid instruction type is loaded.
Returns:
A data source to generate a drawing.
"""
inst = data.inst
meta: dict[str, Any] = {}
if isinstance(inst, instructions.Play):
# pulse
operand = inst.pulse
if isinstance(operand, (pulse.ParametricPulse, pulse.SymbolicPulse)):
# parametric pulse
params = operand.parameters
duration = params.pop("duration", None)
if isinstance(duration, circuit.Parameter):
duration = None
if isinstance(operand, library.SymbolicPulse):
pulse_shape = operand.pulse_type
else:
pulse_shape = "Waveform"
meta["waveform shape"] = pulse_shape
meta.update(
{
key: val.name if isinstance(val, circuit.Parameter) else val
for key, val in params.items()
}
)
if data.is_opaque:
# parametric pulse with unbound parameter
if duration:
meta.update(
{
"duration (cycle time)": inst.duration,
"duration (sec)": inst.duration * data.dt if data.dt else "N/A",
}
)
else:
meta.update({"duration (cycle time)": "N/A", "duration (sec)": "N/A"})
meta.update(
{
"t0 (cycle time)": data.t0,
"t0 (sec)": data.t0 * data.dt if data.dt else "N/A",
"phase": data.frame.phase,
"frequency": data.frame.freq,
"name": inst.name,
}
)
return types.OpaqueShape(duration=duration, meta=meta)
else:
# fixed shape parametric pulse
pulse_data = operand.get_waveform()
else:
# waveform
pulse_data = operand
xdata = np.arange(pulse_data.duration) + data.t0
ydata = pulse_data.samples
elif isinstance(inst, instructions.Delay):
# delay
xdata = np.arange(inst.duration) + data.t0
ydata = np.zeros(inst.duration)
elif isinstance(inst, instructions.Acquire):
# acquire
xdata = np.arange(inst.duration) + data.t0
ydata = np.ones(inst.duration)
acq_data = {
"memory slot": inst.mem_slot.name,
"register slot": inst.reg_slot.name if inst.reg_slot else "N/A",
"discriminator": inst.discriminator.name if inst.discriminator else "N/A",
"kernel": inst.kernel.name if inst.kernel else "N/A",
}
meta.update(acq_data)
else:
raise VisualizationError(
"Unsupported instruction {inst} by "
"filled envelope.".format(inst=inst.__class__.__name__)
)
meta.update(
{
"duration (cycle time)": inst.duration,
"duration (sec)": inst.duration * data.dt if data.dt else "N/A",
"t0 (cycle time)": data.t0,
"t0 (sec)": data.t0 * data.dt if data.dt else "N/A",
"phase": data.frame.phase,
"frequency": data.frame.freq,
"name": inst.name,
}
)
return types.ParsedInstruction(xvals=xdata, yvals=ydata, meta=meta)
|
https://github.com/stevvwen/QAlgoImplementation
|
stevvwen
|
# Do the necessary imports
import numpy as np
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, BasicAer, IBMQ
from qiskit.visualization import plot_histogram, plot_bloch_multivector
### Creating 3 qubit and 2 classical bits in each separate register
qr = QuantumRegister(3)
crz = ClassicalRegister(1)
crx = ClassicalRegister(1)
teleportation_circuit = QuantumCircuit(qr, crz, crx)
### A third party eve helps to create an entangled state
def create_bell_pair(qc, a, b):
qc.h(a)
qc.cx(a, b)
create_bell_pair(teleportation_circuit, 1, 2)
teleportation_circuit.draw()
def alice_gates(qc, a, b):
qc.cx(a, b)
qc.h(a)
teleportation_circuit.barrier()
alice_gates(teleportation_circuit, 0, 1)
teleportation_circuit.draw()
def measure_and_send(qc, a, b):
qc.barrier()
qc.measure(a,0)
qc.measure(b,1)
teleportation_circuit.barrier()
measure_and_send(teleportation_circuit, 0, 1)
teleportation_circuit.draw()
def bob_gates(qc, qubit, crz, crx):
qc.x(qubit).c_if(crx, 1)
qc.z(qubit).c_if(crz, 1)
teleportation_circuit.barrier()
bob_gates(teleportation_circuit, 2, crz, crx)
teleportation_circuit.draw()
from qiskit.extensions import Initialize
import math
qc = QuantumCircuit(1)
initial_state = [0,1]
init_gate = Initialize(initial_state)
# qc.append(initialize_qubit, [0])
qr = QuantumRegister(3) # Protocol uses 3 qubits
crz = ClassicalRegister(1) # and 2 classical registers
crx = ClassicalRegister(1)
qc = QuantumCircuit(qr, crz, crx)
# First, let's initialise Alice's q0
qc.append(init_gate, [0])
qc.barrier()
# Now begins the teleportation protocol
create_bell_pair(qc, 1, 2)
qc.barrier()
# Send q1 to Alice and q2 to Bob
alice_gates(qc, 0, 1)
# Alice then sends her classical bits to Bob
measure_and_send(qc, 0, 1)
# Bob decodes qubits
bob_gates(qc, 2, crz, crx)
qc.draw()
backend = BasicAer.get_backend('statevector_simulator')
out_vector = execute(qc, backend).result().get_statevector()
plot_bloch_multivector(out_vector)
inverse_init_gate = init_gate.gates_to_uncompute()
qc.append(inverse_init_gate, [2])
qc.draw()
cr_result = ClassicalRegister(1)
qc.add_register(cr_result)
qc.measure(2,2)
qc.draw()
backend = BasicAer.get_backend('qasm_simulator')
counts = execute(qc, backend, shots=1024).result().get_counts()
plot_histogram(counts)
def bob_gates(qc, a, b, c):
qc.cz(a, c)
qc.cx(b, c)
qc = QuantumCircuit(3,1)
# First, let's initialise Alice's q0
qc.append(init_gate, [0])
qc.barrier()
# Now begins the teleportation protocol
create_bell_pair(qc, 1, 2)
qc.barrier()
# Send q1 to Alice and q2 to Bob
alice_gates(qc, 0, 1)
qc.barrier()
# Alice sends classical bits to Bob
bob_gates(qc, 0, 1, 2)
# We undo the initialisation process
qc.append(inverse_init_gate, [2])
# See the results, we only care about the state of qubit 2
qc.measure(2,0)
# View the results:
qc.draw()
from qiskit import IBMQ
IBMQ.save_account('### IMB TOKEN ')
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q')
provider.backends()
from qiskit.providers.ibmq import least_busy
backend = least_busy(provider.backends(filters=lambda b: b.configuration().n_qubits >= 3 and
not b.configuration().simulator and b.status().operational==True))
job_exp = execute(qc, backend=backend, shots=8192)
exp_result = job_exp.result()
exp_measurement_result = exp_result.get_counts(qc)
print(exp_measurement_result)
plot_histogram(exp_measurement_result)
error_rate_percent = sum([exp_measurement_result[result] for result in exp_measurement_result.keys() if result[0]=='1']) \
* 100./ sum(list(exp_measurement_result.values()))
print("The experimental error rate : ", error_rate_percent, "%")
|
https://github.com/peiyong-addwater/Hackathon-QNLP
|
peiyong-addwater
|
import collections
import pickle
import warnings
warnings.filterwarnings("ignore")
import os
from random import shuffle
import random
from discopy.tensor import Tensor
from discopy import Word
from discopy.rigid import Functor
from discopy import grammar
import seaborn as sns
import pandas as pd
import matplotlib.pyplot as plt
from jax import numpy as np
import numpy
from lambeq import AtomicType, IQPAnsatz, remove_cups, NumpyModel, spiders_reader
from lambeq import BobcatParser, TreeReader, cups_reader, DepCCGParser, TreeReaderMode
from lambeq import Dataset
from lambeq import QuantumTrainer, SPSAOptimizer
from lambeq import TketModel
from lambeq import Rewriter
from pytket.extensions.qiskit import AerBackend
import seaborn as sns
import matplotlib.pyplot as plt
from pytket.circuit.display import render_circuit_jupyter
pd.set_option('display.width', 1000)
pd.options.display.max_colwidth=80
print(os.getcwd())
warnings.filterwarnings("ignore")
os.environ["TOKENIZERS_PARALLELISM"] = "false"
BATCH_SIZE = 50
EPOCHS = 200
SEED = 0
TRAIN_INDEX_RATIO = 0.08
VAL_INDEX_RATIO = TRAIN_INDEX_RATIO + 0.01
TEST_INDEX_RATIO = VAL_INDEX_RATIO + 0.01
assert TEST_INDEX_RATIO <= 1
def load_pickled_dict_to_df(filename):
saved_dict = pickle.load(open(filename, 'rb'))
df = pd.DataFrame.from_dict(saved_dict)
df = df.sample(frac=1, random_state=SEED).reset_index(drop=True)
sentiment = []
for i in df['target']:
if i == "Positive":
sentiment.append(1)
else:
sentiment.append(0)
df["Sentiment"] = sentiment
return df
cleaned_qnlp_filename = os.path.join(os.getcwd(), 'cleaned_qnlp_data.pkl')
cleaned_lemmatized_qnlp_filename = os.path.join(os.getcwd(), 'cleaned_qnlp_data_lematize.pkl')
cleaned_lemmatized_stemmed_qnlp_filename = os.path.join(os.getcwd(), 'cleaned_qnlp_data_stem_lematize.pkl')
cleaned_qnlp = load_pickled_dict_to_df(cleaned_qnlp_filename)
cleaned_lemmatized_qnlp = load_pickled_dict_to_df(cleaned_lemmatized_qnlp_filename)
cleaned__lemmatized_stemmed_qnlp = load_pickled_dict_to_df(cleaned_lemmatized_stemmed_qnlp_filename)
cleaned_qnlp.head(10)
cleaned_qnlp.info()
sns.countplot(x = "target", data = cleaned_qnlp)
cleaned_lemmatized_qnlp.head(10)
cleaned_lemmatized_qnlp.info()
sns.countplot(x='target', data = cleaned_lemmatized_qnlp)
cleaned__lemmatized_stemmed_qnlp.head(10)
cleaned__lemmatized_stemmed_qnlp.info()
sns.countplot(x='target', data = cleaned__lemmatized_stemmed_qnlp)
# parser = BobcatParser(verbose='text')
# parser = DepCCGParser(root_cats=['S[dcl]'])
# parser = spiders_reader
parser = TreeReader(mode=TreeReaderMode.RULE_TYPE)
NUM_DATA = 2578
loss = lambda y_hat, y: -np.sum(y * np.log(y_hat)) / len(y) # binary cross-entropy loss
acc = lambda y_hat, y: np.sum(np.round(y_hat) == y) / len(y) / 2 # half due to double-counting
rewriter = Rewriter(['prepositional_phrase', 'determiner', 'auxiliary', 'connector',
'coordination', 'object_rel_pronoun', 'subject_rel_pronoun',
'postadverb', 'preadverb'])
def rewrite(diagram):
# diagram = rewriter(diagram)
return remove_cups(diagram)
def create_diagrams_and_labels(total_df, NUM_DATA = 2578):
total_text = total_df['data'].tolist()
total_labels = total_df["Sentiment"].tolist()
total_labels = [[t, 1-t] for t in total_labels] # [1, 0] for positive, [0, 1] for negative
train_diagrams = parser.sentences2diagrams(total_text[:round(NUM_DATA*TRAIN_INDEX_RATIO)])
train_labels = total_labels[:round(NUM_DATA*TRAIN_INDEX_RATIO)]
dev_diagrams = parser.sentences2diagrams(total_text[round(NUM_DATA*TRAIN_INDEX_RATIO):round(NUM_DATA*VAL_INDEX_RATIO)])
dev_labels = total_labels[round(NUM_DATA*TRAIN_INDEX_RATIO):round(NUM_DATA*VAL_INDEX_RATIO)]
test_diagrams = parser.sentences2diagrams(total_text[round(NUM_DATA*VAL_INDEX_RATIO):round(NUM_DATA*TEST_INDEX_RATIO)])
test_labels = total_labels[round(NUM_DATA*VAL_INDEX_RATIO):round(NUM_DATA*TEST_INDEX_RATIO)]
return train_diagrams, train_labels, dev_diagrams, dev_labels, test_diagrams, test_labels
data = cleaned__lemmatized_stemmed_qnlp
raw_train_diagrams_1, train_labels_1, raw_dev_diagrams_1, dev_labels_1, raw_test_diagrams_1, test_labels_1 = create_diagrams_and_labels(data)
print(len(raw_train_diagrams_1))
raw_train_diagrams_1[0].draw(figsize=(12,3))
train_diagrams_1 = [rewrite(diagram) for diagram in raw_train_diagrams_1]
dev_diagrams_1 = [rewrite(diagram) for diagram in raw_dev_diagrams_1]
test_diagrams_1 = [rewrite(diagram) for diagram in raw_test_diagrams_1]
train_diagrams_1[0].draw(figsize=(6,5))
alternate_parser = BobcatParser(verbose='text')
dig_0 = alternate_parser.sentence2diagram(cleaned__lemmatized_stemmed_qnlp['data'].tolist()[0])
grammar.draw(dig_0, figsize=(14,3), fontsize=12)
ansatz_1 = IQPAnsatz({AtomicType.NOUN: 1, AtomicType.SENTENCE: 1, AtomicType.PREPOSITIONAL_PHRASE: 1, AtomicType.NOUN_PHRASE:1, AtomicType.CONJUNCTION:1}, n_layers=1, n_single_qubit_params=3)
train_circuits_1 = [ansatz_1(diagram) for diagram in train_diagrams_1]
dev_circuits_1 = [ansatz_1(diagram) for diagram in dev_diagrams_1]
test_circuits_1 = [ansatz_1(diagram) for diagram in test_diagrams_1]
train_circuits_1[0].draw(figsize=(9, 12))
# train_circuits_1[0].draw(figsize=(9, 12))
render_circuit_jupyter(train_circuits_1[0].to_tk())
[(s, s.size) for s in train_circuits_1[0].free_symbols]
all_circuits_1 = train_circuits_1 + dev_circuits_1 + test_circuits_1
model_1 = NumpyModel.from_diagrams(all_circuits_1, use_jit=True)
# model_1 = TketModel.from_diagrams(all_circuits_1, backend_config=backend_config)
trainer_1 = QuantumTrainer(
model_1,
loss_function=loss,
epochs=EPOCHS,
optimizer=SPSAOptimizer,
optim_hyperparams={'a': 0.2, 'c': 0.06, 'A':0.01*EPOCHS},
evaluate_functions={'acc': acc},
evaluate_on_train=True,
verbose = 'text',
seed=0
)
train_dataset_1 = Dataset(
train_circuits_1,
train_labels_1,
batch_size=BATCH_SIZE)
val_dataset_1 = Dataset(dev_circuits_1, dev_labels_1, shuffle=False)
trainer_1.fit(train_dataset_1, val_dataset_1, logging_step=1)
fig, ((ax_tl, ax_tr), (ax_bl, ax_br)) = plt.subplots(2, 2, sharex=True, sharey='row', figsize=(12, 8))
ax_tl.set_title('Training set')
ax_tr.set_title('Development set')
ax_bl.set_xlabel('Iterations')
ax_br.set_xlabel('Iterations')
ax_bl.set_ylabel('Accuracy')
ax_tl.set_ylabel('Loss')
colours = iter(plt.rcParams['axes.prop_cycle'].by_key()['color'])
ax_tl.plot(trainer_1.train_epoch_costs, color=next(colours))
ax_bl.plot(trainer_1.train_results['acc'], color=next(colours))
ax_tr.plot(trainer_1.val_costs, color=next(colours))
ax_br.plot(trainer_1.val_results['acc'], color=next(colours))
data = cleaned_lemmatized_qnlp
raw_train_diagrams_1, train_labels_1, raw_dev_diagrams_1, dev_labels_1, raw_test_diagrams_1, test_labels_1 = create_diagrams_and_labels(data)
print(len(raw_train_diagrams_1))
raw_train_diagrams_1[0].draw(figsize=(12,3))
train_diagrams_1 = [rewrite(diagram) for diagram in raw_train_diagrams_1]
dev_diagrams_1 = [rewrite(diagram) for diagram in raw_dev_diagrams_1]
test_diagrams_1 = [rewrite(diagram) for diagram in raw_test_diagrams_1]
train_diagrams_1[0].draw(figsize=(6,5))
ansatz_1 = IQPAnsatz({AtomicType.NOUN: 1, AtomicType.SENTENCE: 1, AtomicType.PREPOSITIONAL_PHRASE: 1, AtomicType.NOUN_PHRASE:1, AtomicType.CONJUNCTION:1}, n_layers=1, n_single_qubit_params=3)
train_circuits_1 = [ansatz_1(diagram) for diagram in train_diagrams_1]
dev_circuits_1 = [ansatz_1(diagram) for diagram in dev_diagrams_1]
test_circuits_1 = [ansatz_1(diagram) for diagram in test_diagrams_1]
train_circuits_1[0].draw(figsize=(9, 12))
render_circuit_jupyter(train_circuits_1[0].to_tk())
all_circuits_1 = train_circuits_1 + dev_circuits_1 + test_circuits_1
model_1 = NumpyModel.from_diagrams(all_circuits_1, use_jit=True)
trainer_1 = QuantumTrainer(
model_1,
loss_function=loss,
epochs=EPOCHS,
optimizer=SPSAOptimizer,
optim_hyperparams={'a': 0.2, 'c': 0.06, 'A':0.01*EPOCHS},
evaluate_functions={'acc': acc},
evaluate_on_train=True,
verbose = 'text',
seed=0
)
train_dataset_1 = Dataset(
train_circuits_1,
train_labels_1,
batch_size=BATCH_SIZE)
val_dataset_1 = Dataset(dev_circuits_1, dev_labels_1, shuffle=False)
trainer_1.fit(train_dataset_1, val_dataset_1, logging_step=1)
fig, ((ax_tl, ax_tr), (ax_bl, ax_br)) = plt.subplots(2, 2, sharex=True, sharey='row', figsize=(12, 8))
ax_tl.set_title('Training set')
ax_tr.set_title('Development set')
ax_bl.set_xlabel('Iterations')
ax_br.set_xlabel('Iterations')
ax_bl.set_ylabel('Accuracy')
ax_tl.set_ylabel('Loss')
colours = iter(plt.rcParams['axes.prop_cycle'].by_key()['color'])
ax_tl.plot(trainer_1.train_epoch_costs, color=next(colours))
ax_bl.plot(trainer_1.train_results['acc'], color=next(colours))
ax_tr.plot(trainer_1.val_costs, color=next(colours))
ax_br.plot(trainer_1.val_results['acc'], color=next(colours))
data = cleaned_qnlp
raw_train_diagrams_1, train_labels_1, raw_dev_diagrams_1, dev_labels_1, raw_test_diagrams_1, test_labels_1 = create_diagrams_and_labels(data)
print(len(raw_train_diagrams_1))
raw_train_diagrams_1[0].draw(figsize=(12,3))
train_diagrams_1 = [rewrite(diagram) for diagram in raw_train_diagrams_1]
dev_diagrams_1 = [rewrite(diagram) for diagram in raw_dev_diagrams_1]
test_diagrams_1 = [rewrite(diagram) for diagram in raw_test_diagrams_1]
train_diagrams_1[0].draw(figsize=(6,5))
render_circuit_jupyter(train_circuits_1[0].to_tk())
all_circuits_1 = train_circuits_1 + dev_circuits_1 + test_circuits_1
model_1 = NumpyModel.from_diagrams(all_circuits_1, use_jit=True)
trainer_1 = QuantumTrainer(
model_1,
loss_function=loss,
epochs=EPOCHS,
optimizer=SPSAOptimizer,
optim_hyperparams={'a': 0.2, 'c': 0.06, 'A':0.01*EPOCHS},
evaluate_functions={'acc': acc},
evaluate_on_train=True,
verbose = 'text',
seed=0
)
train_dataset_1 = Dataset(
train_circuits_1,
train_labels_1,
batch_size=BATCH_SIZE)
val_dataset_1 = Dataset(dev_circuits_1, dev_labels_1, shuffle=False)
trainer_1.fit(train_dataset_1, val_dataset_1, logging_step=1)
fig, ((ax_tl, ax_tr), (ax_bl, ax_br)) = plt.subplots(2, 2, sharex=True, sharey='row', figsize=(12, 8))
ax_tl.set_title('Training set')
ax_tr.set_title('Development set')
ax_bl.set_xlabel('Iterations')
ax_br.set_xlabel('Iterations')
ax_bl.set_ylabel('Accuracy')
ax_tl.set_ylabel('Loss')
colours = iter(plt.rcParams['axes.prop_cycle'].by_key()['color'])
ax_tl.plot(trainer_1.train_epoch_costs, color=next(colours))
ax_bl.plot(trainer_1.train_results['acc'], color=next(colours))
ax_tr.plot(trainer_1.val_costs, color=next(colours))
ax_br.plot(trainer_1.val_results['acc'], color=next(colours))
|
https://github.com/qiskit-community/community.qiskit.org
|
qiskit-community
|
from qiskit import *
from qiskit.visualization import plot_histogram
measure_z = QuantumCircuit(1,1)
measure_z.measure(0,0)
measure_z.draw(output='mpl')
measure_x = QuantumCircuit(1,1)
measure_x.h(0)
measure_x.measure(0,0)
measure_x.draw(output='mpl')
qc_0 = QuantumCircuit(1)
qc_0.draw(output='mpl')
qc = qc_0 + measure_z
print('Results for z measurement:')
counts = execute(qc,Aer.get_backend('qasm_simulator')).result().get_counts()
plot_histogram(counts)
qc = qc_0 + measure_x
print('Results for x measurement:')
counts = execute(qc,Aer.get_backend('qasm_simulator')).result().get_counts()
plot_histogram(counts)
qc_plus = QuantumCircuit(1)
qc_plus.h(0)
qc_plus.draw(output='mpl')
qc = qc_plus + measure_z
qc.draw()
print('Results for z measurement:')
counts = execute(qc,Aer.get_backend('qasm_simulator')).result().get_counts()
plot_histogram(counts)
qc = qc_plus + measure_x
print('Results for x measurement:')
counts = execute(qc,Aer.get_backend('qasm_simulator')).result().get_counts()
plot_histogram(counts)
qc_y = QuantumCircuit(1)
qc_y.ry( -3.14159/4,0)
qc_y.draw(output='mpl')
qc = qc_y + measure_z
print('Results for z measurement:')
counts = execute(qc,Aer.get_backend('qasm_simulator')).result().get_counts()
plot_histogram(counts)
qc = qc_y + measure_x
print('\nResults for x measurement:')
counts = execute(qc,Aer.get_backend('qasm_simulator')).result().get_counts()
plot_histogram(counts)
qc_hardy = QuantumCircuit(2)
qc_hardy.ry(1.911,1)
qc_hardy.cx(1,0)
qc_hardy.ry(0.785,0)
qc_hardy.cx(1,0)
qc_hardy.ry(2.356,0)
qc_hardy.draw(output='mpl')
measurements = QuantumCircuit(2,2)
# z measurement on both qubits
measurements.measure(0,0)
measurements.measure(1,1)
qc = qc_hardy + measurements
print('\nResults for two z measurements:')
counts = execute(qc,Aer.get_backend('qasm_simulator')).result().get_counts()
plot_histogram(counts)
measurements = QuantumCircuit(2,2)
# x measurement on qubit 0
measurements.h(0)
measurements.measure(0,0)
# z measurement on qubit 1
measurements.measure(1,1)
qc = qc_hardy + measurements
print('\nResults for two x measurement on qubit 0 and z measurement on qubit 1:')
counts = execute(qc,Aer.get_backend('qasm_simulator')).result().get_counts()
plot_histogram(counts)
measurements = QuantumCircuit(2,2)
measurements.h(0)
measurements.measure(0,0)
measurements.h(1)
measurements.measure(1,1)
qc = qc_hardy + measurements
print('\nResults for two x measurement on both qubits:')
counts = execute(qc,Aer.get_backend('qasm_simulator')).result().get_counts()
plot_histogram(counts)
|
https://github.com/khaledalam/QuantumComputingAndPrimesAndOthers
|
khaledalam
|
# Author: Khaled Alam(khaledalam.net@gmail.com)
'''
Guess binary string (secret) of length N in 1 shot only using quantum computing circuit!
~ by using clasical computers we need at least N shots to guess string (secret) of length N
~ by using quantum computer we need 1 shot to guess string (secret) of ANY length ( cool isn't it! ^^ )
'''
secret = '01000001' # `01000001` = `A`
from qiskit import *
n = len(secret)
qCircuit = QuantumCircuit(n+1, n) # n+1 qubits and n classical bits
qCircuit.x(n)
qCircuit.barrier()
qCircuit.h(range(n+1))
qCircuit.barrier()
for ii, OZ in enumerate(reversed(secret)):
if OZ == '1':
qCircuit.cx(ii, n)
qCircuit.barrier()
qCircuit.h(range(n+1))
qCircuit.barrier()
qCircuit.measure(range(n), range(n))
%matplotlib inline
qCircuit.draw(output='mpl')
# run on simulator
simulator = Aer.get_backend('qasm_simulator')
result = execute(qCircuit, backend=simulator, shots=1).result() # only 1 shot
from qiskit.visualization import plot_histogram
plot_histogram(
result.get_counts(qCircuit)
)
|
https://github.com/jonasmaziero/computacao_quantica_qiskit
|
jonasmaziero
|
from sympy import *
init_printing(use_unicode=True)
r1,r2,r3,s1,s2,s3 = symbols('r_1 r_2 r_3 s_1 s_2 s_3')
I = Matrix([[1,0],[0,1]]); X = Matrix([[0,1],[1,0]]); Y = Matrix([[0,-1j],[1j,0]]); Z = Matrix([[1,0],[0,-1]])
rho = (1/2)*(I+r1*X+r2*Y+r3*Z); sigma = (1/2)*(I+s1*X+s2*Y+s3*Z)
#rho, sigma
def frho(r1,r2,r3):
return (1/2)*(I+r1*X+r2*Y+r3*Z)
def fsigma(s1,s2,s3):
return (1/2)*(I+s1*X+s2*Y+s3*Z)
A = frho(r1,0,r2)*fsigma(0,s2,0)
simplify(A.eigenvals())
A = frho(0,0,r3); B = fsigma(s1,s2,0)
simplify(A*(B**2)*A - B*(A**2)*B)
M = A*B; simplify(M)
simplify(M.eigenvals()) # parecem ser positivos o que esta na raiz e o autovalores
|
https://github.com/TRSasasusu/qiskit-quantum-zoo
|
TRSasasusu
|
"""The following is python code utilizing the qiskit library that can be run on extant quantum
hardware using 5 qubits for factoring the integer 15 into 3 and 5. Using period finding,
for a^r mod N = 1, where a = 11 and N = 15 (the integer to be factored) the problem is to find
r values for this identity such that one can find the prime factors of N. For 11^r mod(15) =1,
results (as shown in fig 1.) correspond with period r = 4 (|00100>) and r = 0 (|00000>).
To find the factor, use the equivalence a^r mod 15. From this:
(a^r -1) mod 15 = (a^(r/2) + 1)(a^(r/2) - 1) mod 15.In this case, a = 11. Plugging in the two r
values for this a value yields (11^(0/2) +1)(11^(4/2) - 1) mod 15 = 2*(11 +1)(11-1) mod 15
Thus, we find (24)(20) mod 15. By finding the greatest common factor between the two coefficients,
gcd(24,15) and gcd(20,15), yields 3 and 5 respectively. These are the prime factors of 15,
so the result of running shors algorithm to find the prime factors of an integer using quantum
hardware are demonstrated. Note, this is not the same as the technical implementation of shor's
algorithm described in this section for breaking the discrete log hardness assumption,
though the proof of concept remains."""
# Import libraries
from qiskit.compiler import transpile, assemble
from qiskit.tools.jupyter import *
from qiskit.visualization import *
from numpy import pi
from qiskit import IBMQ, Aer, QuantumCircuit, ClassicalRegister, QuantumRegister, execute
from qiskit.providers.ibmq import least_busy
from qiskit.visualization import plot_histogram
# Initialize qubit registers
qreg_q = QuantumRegister(5, 'q')
creg_c = ClassicalRegister(5, 'c')
circuit = QuantumCircuit(qreg_q, creg_c)
circuit.reset(qreg_q[0])
circuit.reset(qreg_q[1])
circuit.reset(qreg_q[2])
circuit.reset(qreg_q[3])
circuit.reset(qreg_q[4])
# Apply Hadamard transformations to qubit registers
circuit.h(qreg_q[0])
circuit.h(qreg_q[1])
circuit.h(qreg_q[2])
# Apply first QFT, modular exponentiation, and another QFT
circuit.h(qreg_q[1])
circuit.cx(qreg_q[2], qreg_q[3])
circuit.crx(pi/2, qreg_q[0], qreg_q[1])
circuit.ccx(qreg_q[2], qreg_q[3], qreg_q[4])
circuit.h(qreg_q[0])
circuit.rx(pi/2, qreg_q[2])
circuit.crx(pi/2, qreg_q[1], qreg_q[2])
circuit.crx(pi/2, qreg_q[1], qreg_q[2])
circuit.cx(qreg_q[0], qreg_q[1])
# Measure the qubit registers 0-2
circuit.measure(qreg_q[2], creg_c[2])
circuit.measure(qreg_q[1], creg_c[1])
circuit.measure(qreg_q[0], creg_c[0])
# Get least busy quantum hardware backend to run on
provider = IBMQ.load_account()
device = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 3 and
not x.configuration().simulator and x.status().operational==True))
print("Running on current least busy device: ", device)
# Run the circuit on available quantum hardware and plot histogram
from qiskit.tools.monitor import job_monitor
job = execute(circuit, backend=device, shots=1024, optimization_level=3)
job_monitor(job, interval = 2)
results = job.result()
answer = results.get_counts(circuit)
plot_histogram(answer)
#largest amplitude results correspond with r values used to find the prime factor of N.
|
https://github.com/2lambda123/Qiskit-qiskit
|
2lambda123
|
# 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.
"""Example of using the StochasticSwap pass."""
from qiskit.transpiler.passes import StochasticSwap
from qiskit.transpiler import CouplingMap
from qiskit.converters import circuit_to_dag
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
coupling = CouplingMap([[0, 1], [1, 2], [1, 3]])
qr = QuantumRegister(4, "q")
cr = ClassicalRegister(4, "c")
circ = QuantumCircuit(qr, cr)
circ.cx(qr[1], qr[2])
circ.cx(qr[0], qr[3])
circ.measure(qr[0], cr[0])
circ.h(qr)
circ.cx(qr[0], qr[1])
circ.cx(qr[2], qr[3])
circ.measure(qr[0], cr[0])
circ.measure(qr[1], cr[1])
circ.measure(qr[2], cr[2])
circ.measure(qr[3], cr[3])
dag = circuit_to_dag(circ)
# ββββββββ βββ
# q_0: |0>ββββββββββββββββββ βββββββββββββββββββ€Mββ€ H ββββ ββββββ€Mβ
# βββββ β ββ₯βββββββββ΄βββββββ₯β
# q_1: |0>βββ ββββββββ€ H ββββΌββββββββββββββββββββ«βββββββ€ X ββ€Mβββ«β
# βββ΄ββββββββββββ β βββ β βββββββ₯β β
# q_2: |0>β€ X ββ€ H βββββββββΌββββββββββ ββββββ€Mβββ«βββββββββββββ«βββ«β
# ββββββββββ βββ΄ββββββββββ΄βββββββ₯β β β β
# q_3: |0>ββββββββββββββββ€ X ββ€ H ββ€ X ββ€Mβββ«βββ«βββββββββββββ«βββ«β
# βββββββββββββββββ₯β β β β β
# c_0: 0 ββββββββββββββββββββββββββββββββ¬βββ¬βββ©βββββββββββββ¬βββ©β
# β β β
# c_1: 0 ββββββββββββββββββββββββββββββββ¬βββ¬ββββββββββββββββ©ββββ
# β β
# c_2: 0 ββββββββββββββββββββββββββββββββ¬βββ©ββββββββββββββββββββ
# β
# c_3: 0 ββββββββββββββββββββββββββββββββ©βββββββββββββββββββββββ
#
# ββββββββ βββ
# q_0: |0>βββββββββββββββββββββ βββ€Mββ€ H ββββββββββββββββββββ βββ€Mβββββββ
# βββ΄ββββ₯ββββββββββββββββ βββ΄ββββ₯ββββ
# q_1: |0>βββ βββXββββββββββββ€ X βββ«βββββββ€ H ββ€ X ββXβββββ€ X βββ«ββ€Mββββ
# βββ΄ββ β ββββββββββ β ββββββββ¬ββ β βββββ β ββ₯ββββ
# q_2: |0>β€ X βββΌβββββββ€ H ββββββββ«ββββββββββββββ ββββΌβββββββββββ«βββ«ββ€Mβ
# βββββ β ββββββββββ β β βββ β β ββ₯β
# q_3: |0>ββββββXββ€ H βββββββββββββ«βββββββββββββββββXββ€Mββββββββ«βββ«βββ«β
# βββββ β ββ₯β β β β
# c_0: 0 βββββββββββββββββββββββββ©βββββββββββββββββββββ¬ββββββββ©βββ¬βββ¬β
# β β β
# c_1: 0 ββββββββββββββββββββββββββββββββββββββββββββββ¬βββββββββββ©βββ¬β
# β β
# c_2: 0 ββββββββββββββββββββββββββββββββββββββββββββββ¬ββββββββββββββ©β
# β
# c_3: 0 ββββββββββββββββββββββββββββββββββββββββββββββ©βββββββββββββββ
#
#
# 2
# |
# 0 - 1 - 3
# Build the expected output to verify the pass worked
expected = QuantumCircuit(qr, cr)
expected.cx(qr[1], qr[2])
expected.h(qr[2])
expected.swap(qr[0], qr[1])
expected.h(qr[0])
expected.cx(qr[1], qr[3])
expected.h(qr[3])
expected.measure(qr[1], cr[0])
expected.swap(qr[1], qr[3])
expected.cx(qr[2], qr[1])
expected.h(qr[3])
expected.swap(qr[0], qr[1])
expected.measure(qr[2], cr[2])
expected.cx(qr[3], qr[1])
expected.measure(qr[0], cr[3])
expected.measure(qr[3], cr[0])
expected.measure(qr[1], cr[1])
expected_dag = circuit_to_dag(expected)
# Run the pass on the dag from the input circuit
pass_ = StochasticSwap(coupling, 20, 999)
after = pass_.run(dag)
# Verify the output of the pass matches our expectation
assert expected_dag == after
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import IBMQ, transpile
from qiskit import QuantumCircuit
from qiskit_aer import AerSimulator
from qiskit.tools.visualization import plot_histogram
from qiskit.providers.fake_provider import FakeVigo
device_backend = FakeVigo()
# Construct quantum circuit
circ = QuantumCircuit(3, 3)
circ.h(0)
circ.cx(0, 1)
circ.cx(1, 2)
circ.measure([0, 1, 2], [0, 1, 2])
sim_ideal = AerSimulator()
# Execute and get counts
result = sim_ideal.run(transpile(circ, sim_ideal)).result()
counts = result.get_counts(0)
plot_histogram(counts, title='Ideal counts for 3-qubit GHZ state')
sim_vigo = AerSimulator.from_backend(device_backend)
# Transpile the circuit for the noisy basis gates
tcirc = transpile(circ, sim_vigo)
# Execute noisy simulation and get counts
result_noise = sim_vigo.run(tcirc).result()
counts_noise = result_noise.get_counts(0)
plot_histogram(counts_noise,
title="Counts for 3-qubit GHZ state with device noise model")
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/quantumjim/qreative
|
quantumjim
|
import sys
sys.path.append('../')
import CreativeQiskit
result = CreativeQiskit.bell_correlation('ZZ')
print(' Probability of agreement =',result['P'])
result = CreativeQiskit.bell_correlation('XZ')
print(' Probability of agreement =',result['P'])
result = CreativeQiskit.bell_correlation('ZX')
print(' Probability of agreement =',result['P'])
result = CreativeQiskit.bell_correlation('XX')
print(' Probability of agreement =',result['P'])
result = CreativeQiskit.bell_correlation('XX')
print(' Probability of agreement =',result['samples'])
for basis in ['ZZ','XZ','ZX','XX']:
result = CreativeQiskit.bell_correlation(basis,noisy=True)
print(' Probability of agreement for',basis,'=',result['P'])
|
https://github.com/tomtuamnuq/compare-qiskit-ocean
|
tomtuamnuq
|
import time
import numpy as np
from qiskit import BasicAer
from qiskit.aqua import QuantumInstance, aqua_globals
from qiskit.aqua.algorithms import QAOA
from qiskit.aqua.components.optimizers import COBYLA
from qiskit.optimization.algorithms import MinimumEigenOptimizer, CplexOptimizer
from qiskit.optimization.algorithms.optimization_algorithm import OptimizationResultStatus
from random_lp.lp_random_gen import create_models
DIR = 'TEST_DATA' + "/" + time.strftime("%d_%m_%Y") + "/DENSE/" # 23.04.2021
Q_SEED = 10598 # as used in most issues
aqua_globals.random_seed = Q_SEED
shots = 4096
# select linear program to solve
qps = create_models(DIR)
qp = qps['test_dense_3']
# init classical Optimizers
optimizer = COBYLA() # SLSQP is default in Class VQE
cplex = CplexOptimizer()
# solve qps with Minimum Eigen Optimizer QAOA
backend = BasicAer.get_backend('qasm_simulator')
quantum_instance = QuantumInstance(backend,
seed_simulator=Q_SEED,
seed_transpiler=Q_SEED,
shots=shots)
qaoa_mes = QAOA(quantum_instance=quantum_instance, optimizer=optimizer)
qaoa = MinimumEigenOptimizer(qaoa_mes)
cplex.solve(qp)
print("number of qubits: ",qp.get_num_vars())
res = qaoa.solve(qp)
res
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
from qiskit.transpiler.passes import RemoveBarriers
circuit = QuantumCircuit(1)
circuit.x(0)
circuit.barrier()
circuit.h(0)
circuit = RemoveBarriers()(circuit)
circuit.draw('mpl')
|
https://github.com/MAI-cyber/QIT
|
MAI-cyber
|
! pip install numpy
! pip install qiskit
! pip install matplotlib
from qiskit import QuantumCircuit, Aer ,BasicAer, execute
from qiskit.visualization import plot_bloch_multivector, plot_histogram, plot_state_qsphere
from qiskit.quantum_info import Statevector
import matplotlib.pyplot as plt
import numpy as np
def phase_oracle(n,name = 'Of'):
qc = QuantumCircuit(n, name=name)
qc.mct(list(range(n-1)), n-1)
return qc
def diffuser(n, name='V'):
qc = QuantumCircuit(n, name=name)
for qb in range(n-1): #first layer of Hadamards in diffuser
qc.h(qb)
for i in range(n-1):
qc.x(i)
qc.mct(list(range(n-1)), n-1)
for i in range(n-1):
qc.x(i)
for qb in range(n-1): #second layer of Hadamards in diffuser
qc.h(qb)
return qc
n = 2
gr = QuantumCircuit(n+1, n)
r = int(np.floor(np.pi/4*np.sqrt(2**(n)))) # Determine r
gr.h(range(n)) # step 1: apply Hadamard gates on all working qubits
# put ancilla in state |->
gr.x(n)
gr.h(n)
# step 2: apply r rounds of the phase oracle and the diffuser
for j in range(r):
gr.append(phase_oracle(n+1), range(n+1))
gr.append(diffuser(n+1), range(n+1))
gr.measure(range(n), range(n)) # step 3: measure all qubits
gr.draw('mpl')
simulator = Aer.get_backend('qasm_simulator')
job = execute(gr, backend=simulator, shots=1000)
counts = job.result().get_counts()
plot_histogram(counts)
n = 4
prob_marked = []
# Returns probability of success
def probability(counts):
key_sol = '1111'
val_sol = counts[key_sol]
val_total = sum(counts.values())
prob_of_success = val_sol/val_total
return prob_of_success
gr0 = QuantumCircuit(n+1, n)
r = 0
gr0.h(range(n)) # step 1: apply Hadamard gates on all working qubits
# put ancilla in state |->
gr0.x(n)
gr0.h(n)
# step 2: apply r rounds of the phase oracle and the diffuser
for j in range(r):
gr1.append(phase_oracle(n+1), range(n+1))
gr1.append(diffuser(n+1), range(n+1))
gr0.measure(range(n), range(n)) # step 3: measure all qubits
gr0.draw('mpl')
simulator = Aer.get_backend('qasm_simulator')
job = execute(gr0, backend=simulator, shots=1000)
counts = job.result().get_counts()
prob_marked.append(probability(counts))
plot_histogram(counts)
gr1 = QuantumCircuit(n+1, n)
r = 1
gr1.h(range(n)) # step 1: apply Hadamard gates on all working qubits
# put ancilla in state |->
gr1.x(n)
gr1.h(n)
# step 2: apply r rounds of the phase oracle and the diffuser
for j in range(r):
gr1.append(phase_oracle(n+1), range(n+1))
gr1.append(diffuser(n+1), range(n+1))
gr1.measure(range(n), range(n)) # step 3: measure all qubits
gr1.draw('mpl')
simulator = Aer.get_backend('qasm_simulator')
job = execute(gr1, backend=simulator, shots=1000)
counts = job.result().get_counts()
prob_marked.append(probability(counts))
plot_histogram(counts)
gr2 = QuantumCircuit(n+1, n)
r = 2
gr2.h(range(n)) # step 1: apply Hadamard gates on all working qubits
# put ancilla in state |->
gr2.x(n)
gr2.h(n)
# step 2: apply r rounds of the phase oracle and the diffuser
for j in range(r):
gr2.append(phase_oracle(n+1), range(n+1))
gr2.append(diffuser(n+1), range(n+1))
gr2.measure(range(n), range(n)) # step 3: measure all qubits
gr2.draw('mpl')
simulator = Aer.get_backend('qasm_simulator')
job = execute(gr2, backend=simulator, shots=1000)
counts = job.result().get_counts()
prob_marked.append(probability(counts))
plot_histogram(counts)
gr3 = QuantumCircuit(n+1, n)
r = 3
gr3.h(range(n)) # step 1: apply Hadamard gates on all working qubits
# put ancilla in state |->
gr3.x(n)
gr3.h(n)
# step 2: apply r rounds of the phase oracle and the diffuser
for j in range(r):
gr3.append(phase_oracle(n+1), range(n+1))
gr3.append(diffuser(n+1), range(n+1))
gr3.measure(range(n), range(n)) # step 3: measure all qubits
gr3.draw('mpl')
simulator = Aer.get_backend('qasm_simulator')
job = execute(gr3, backend=simulator, shots=1000)
counts = job.result().get_counts()
prob_marked.append(probability(counts))
plot_histogram(counts)
gr4 = QuantumCircuit(n+1, n)
r = 4
gr4.h(range(n)) # step 1: apply Hadamard gates on all working qubits
# put ancilla in state |->
gr4.x(n)
gr4.h(n)
# step 2: apply r rounds of the phase oracle and the diffuser
for j in range(r):
gr4.append(phase_oracle(n+1), range(n+1))
gr4.append(diffuser(n+1), range(n+1))
gr4.measure(range(n), range(n)) # step 3: measure all qubits
gr4.draw('mpl')
simulator = Aer.get_backend('qasm_simulator')
job = execute(gr4, backend=simulator, shots=1000)
counts = job.result().get_counts()
prob_marked.append(probability(counts))
plot_histogram(counts)
r = [0,1,2,3,4]
plt.plot(r, prob_marked, 'o-')
plt.xlabel("Grover Iterations (r)")
plt.ylabel("Probability of Marked State")
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, QuantumRegister
from qiskit.circuit.library.standard_gates import HGate
qc1 = QuantumCircuit(2)
qc1.x(0)
qc1.h(1)
custom = qc1.to_gate().control(2)
qc2 = QuantumCircuit(4)
qc2.append(custom, [0, 3, 1, 2])
qc2.draw('mpl')
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import json
import matplotlib.pyplot as plt
import numpy as np
from IPython.display import clear_output
from qiskit import QuantumCircuit
from qiskit.algorithms.optimizers import COBYLA
from qiskit.circuit import ParameterVector
from qiskit.circuit.library import ZFeatureMap
from qiskit.quantum_info import SparsePauliOp
from qiskit.utils import algorithm_globals
from qiskit_machine_learning.algorithms.classifiers import NeuralNetworkClassifier
from qiskit_machine_learning.neural_networks import EstimatorQNN
from sklearn.model_selection import train_test_split
algorithm_globals.random_seed = 12345
# We now define a two qubit unitary as defined in [3]
def conv_circuit(params):
target = QuantumCircuit(2)
target.rz(-np.pi / 2, 1)
target.cx(1, 0)
target.rz(params[0], 0)
target.ry(params[1], 1)
target.cx(0, 1)
target.ry(params[2], 1)
target.cx(1, 0)
target.rz(np.pi / 2, 0)
return target
# Let's draw this circuit and see what it looks like
params = ParameterVector("ΞΈ", length=3)
circuit = conv_circuit(params)
circuit.draw("mpl")
def conv_layer(num_qubits, param_prefix):
qc = QuantumCircuit(num_qubits, name="Convolutional Layer")
qubits = list(range(num_qubits))
param_index = 0
params = ParameterVector(param_prefix, length=num_qubits * 3)
for q1, q2 in zip(qubits[0::2], qubits[1::2]):
qc = qc.compose(conv_circuit(params[param_index : (param_index + 3)]), [q1, q2])
qc.barrier()
param_index += 3
for q1, q2 in zip(qubits[1::2], qubits[2::2] + [0]):
qc = qc.compose(conv_circuit(params[param_index : (param_index + 3)]), [q1, q2])
qc.barrier()
param_index += 3
qc_inst = qc.to_instruction()
qc = QuantumCircuit(num_qubits)
qc.append(qc_inst, qubits)
return qc
circuit = conv_layer(4, "ΞΈ")
circuit.decompose().draw("mpl")
def pool_circuit(params):
target = QuantumCircuit(2)
target.rz(-np.pi / 2, 1)
target.cx(1, 0)
target.rz(params[0], 0)
target.ry(params[1], 1)
target.cx(0, 1)
target.ry(params[2], 1)
return target
params = ParameterVector("ΞΈ", length=3)
circuit = pool_circuit(params)
circuit.draw("mpl")
def pool_layer(sources, sinks, param_prefix):
num_qubits = len(sources) + len(sinks)
qc = QuantumCircuit(num_qubits, name="Pooling Layer")
param_index = 0
params = ParameterVector(param_prefix, length=num_qubits // 2 * 3)
for source, sink in zip(sources, sinks):
qc = qc.compose(pool_circuit(params[param_index : (param_index + 3)]), [source, sink])
qc.barrier()
param_index += 3
qc_inst = qc.to_instruction()
qc = QuantumCircuit(num_qubits)
qc.append(qc_inst, range(num_qubits))
return qc
sources = [0, 1]
sinks = [2, 3]
circuit = pool_layer(sources, sinks, "ΞΈ")
circuit.decompose().draw("mpl")
def generate_dataset(num_images):
images = []
labels = []
hor_array = np.zeros((6, 8))
ver_array = np.zeros((4, 8))
j = 0
for i in range(0, 7):
if i != 3:
hor_array[j][i] = np.pi / 2
hor_array[j][i + 1] = np.pi / 2
j += 1
j = 0
for i in range(0, 4):
ver_array[j][i] = np.pi / 2
ver_array[j][i + 4] = np.pi / 2
j += 1
for n in range(num_images):
rng = algorithm_globals.random.integers(0, 2)
if rng == 0:
labels.append(-1)
random_image = algorithm_globals.random.integers(0, 6)
images.append(np.array(hor_array[random_image]))
elif rng == 1:
labels.append(1)
random_image = algorithm_globals.random.integers(0, 4)
images.append(np.array(ver_array[random_image]))
# Create noise
for i in range(8):
if images[-1][i] == 0:
images[-1][i] = algorithm_globals.random.uniform(0, np.pi / 4)
return images, labels
images, labels = generate_dataset(50)
train_images, test_images, train_labels, test_labels = train_test_split(
images, labels, test_size=0.3
)
fig, ax = plt.subplots(2, 2, figsize=(10, 6), subplot_kw={"xticks": [], "yticks": []})
for i in range(4):
ax[i // 2, i % 2].imshow(
train_images[i].reshape(2, 4), # Change back to 2 by 4
aspect="equal",
)
plt.subplots_adjust(wspace=0.1, hspace=0.025)
feature_map = ZFeatureMap(8)
feature_map.decompose().draw("mpl")
feature_map = ZFeatureMap(8)
ansatz = QuantumCircuit(8, name="Ansatz")
# First Convolutional Layer
ansatz.compose(conv_layer(8, "Ρ1"), list(range(8)), inplace=True)
# First Pooling Layer
ansatz.compose(pool_layer([0, 1, 2, 3], [4, 5, 6, 7], "p1"), list(range(8)), inplace=True)
# Second Convolutional Layer
ansatz.compose(conv_layer(4, "c2"), list(range(4, 8)), inplace=True)
# Second Pooling Layer
ansatz.compose(pool_layer([0, 1], [2, 3], "p2"), list(range(4, 8)), inplace=True)
# Third Convolutional Layer
ansatz.compose(conv_layer(2, "c3"), list(range(6, 8)), inplace=True)
# Third Pooling Layer
ansatz.compose(pool_layer([0], [1], "p3"), list(range(6, 8)), inplace=True)
# Combining the feature map and ansatz
circuit = QuantumCircuit(8)
circuit.compose(feature_map, range(8), inplace=True)
circuit.compose(ansatz, range(8), inplace=True)
observable = SparsePauliOp.from_list([("Z" + "I" * 7, 1)])
# we decompose the circuit for the QNN to avoid additional data copying
qnn = EstimatorQNN(
circuit=circuit.decompose(),
observables=observable,
input_params=feature_map.parameters,
weight_params=ansatz.parameters,
)
circuit.draw("mpl")
def callback_graph(weights, obj_func_eval):
clear_output(wait=True)
objective_func_vals.append(obj_func_eval)
plt.title("Objective function value against iteration")
plt.xlabel("Iteration")
plt.ylabel("Objective function value")
plt.plot(range(len(objective_func_vals)), objective_func_vals)
plt.show()
with open("11_qcnn_initial_point.json", "r") as f:
initial_point = json.load(f)
classifier = NeuralNetworkClassifier(
qnn,
optimizer=COBYLA(maxiter=200), # Set max iterations here
callback=callback_graph,
initial_point=initial_point,
)
x = np.asarray(train_images)
y = np.asarray(train_labels)
objective_func_vals = []
plt.rcParams["figure.figsize"] = (12, 6)
classifier.fit(x, y)
# score classifier
print(f"Accuracy from the train data : {np.round(100 * classifier.score(x, y), 2)}%")
y_predict = classifier.predict(test_images)
x = np.asarray(test_images)
y = np.asarray(test_labels)
print(f"Accuracy from the test data : {np.round(100 * classifier.score(x, y), 2)}%")
# Let's see some examples in our dataset
fig, ax = plt.subplots(2, 2, figsize=(10, 6), subplot_kw={"xticks": [], "yticks": []})
for i in range(0, 4):
ax[i // 2, i % 2].imshow(test_images[i].reshape(2, 4), aspect="equal")
if y_predict[i] == -1:
ax[i // 2, i % 2].set_title("The QCNN predicts this is a Horizontal Line")
if y_predict[i] == +1:
ax[i // 2, i % 2].set_title("The QCNN predicts this is a Vertical Line")
plt.subplots_adjust(wspace=0.1, hspace=0.5)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/Fergus-Hayes/qiskit_tools
|
Fergus-Hayes
|
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer, IBMQ
import qiskit_tools as qt
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
phase = True
digit_A = 5.25
digit_B = 7.5
print(digit_A,'x',digit_B,'=',digit_A*digit_B)
nintA = qt.get_nint(digit_A)
npresA = qt.get_npres(digit_A)
nA = nintA + npresA
if phase:
nA += 1
print(nA, nintA, npresA)
nintB = qt.get_nint(digit_B)
npresB = qt.get_npres(digit_B)
nB = nintB + npresB
if phase:
nB += 1
print(nB, nintB, npresB)
nintC = qt.get_nint(digit_A*digit_B)
npresC = qt.get_npres(digit_A*digit_B)
nC = nintC + npresC
if phase:
nC += 1
print(nC, nintC, npresC)
binary_A = qt.my_binary_repr(digit_A, nA, nint=nintA, phase=phase)
binary_B = qt.my_binary_repr(digit_B, nB, nint=nintB, phase=phase)
binary_C = qt.my_binary_repr(digit_A*digit_B, nC, nint=nintC, phase=phase)
print(binary_A,binary_B,binary_C)
qregA = QuantumRegister(nA, 'A')
qregB = QuantumRegister(nB, 'B')
qregC = QuantumRegister(nC, 'C')
out_reg = ClassicalRegister(nC,'out_reg')
circ = QuantumCircuit(qregA, qregB, qregC, out_reg)
A_gate = qt.input_bits_to_qubits(binary_A, circ, reg=qregA, wrap=True)
B_gate = qt.input_bits_to_qubits(binary_B, circ, reg=qregB, wrap=True)
circ.append(A_gate, qregA);
circ.append(B_gate, qregB);
mult_gate = qt.QFTMultiply(circ, qregA, qregB, qregC, nint1=nintA, nint2=nintB, nint3=nintC, phase=True, wrap=True)
circ.append(mult_gate, [*qregA, *qregB, *qregC]);
circ.measure(qregC, out_reg);
circ.draw('latex')
shots=10
emulator = Aer.get_backend('qasm_simulator')
job = execute(circ, emulator, shots=shots )
hist = job.result().get_counts()
print('Target:')
print(digit_B,'x',digit_A,'=',digit_B*digit_A,'->',binary_C)
print('Result:')
for label in hist.keys():
print(digit_B,'x',digit_A,'=',qt.bin_to_dec(label, nint=nintC, phase=phase),'->',label,'with probability',float(hist[label])/shots)
phase = True
digit_A = 5.25
digit_B = -7.5
print(digit_A,'x',digit_B,'=',digit_A*digit_B)
binary_A = qt.my_binary_repr(digit_A, nA, nint=nintA, phase=phase)
binary_B = qt.my_binary_repr(digit_B, nB, nint=nintB, phase=phase)
binary_C = qt.my_binary_repr(digit_A*digit_B, nC, nint=nintC, phase=phase)
print(binary_A,binary_B,binary_C)
qregA = QuantumRegister(nA, 'A')
qregB = QuantumRegister(nB, 'B')
qregC = QuantumRegister(nC, 'C')
out_reg = ClassicalRegister(nC,'out_reg')
circ = QuantumCircuit(qregA, qregB, qregC, out_reg)
A_gate = qt.input_bits_to_qubits(binary_A, circ, reg=qregA, wrap=True)
B_gate = qt.input_bits_to_qubits(binary_B, circ, reg=qregB, wrap=True)
circ.append(A_gate, qregA);
circ.append(B_gate, qregB);
mult_gate = qt.QFTMultiply(circ, qregA, qregB, qregC, nint1=nintA, nint2=nintB, nint3=nintC, phase=True, wrap=True)
circ.append(mult_gate, [*qregA, *qregB, *qregC]);
circ.measure(qregC, out_reg);
shots=10
emulator = Aer.get_backend('qasm_simulator')
job = execute(circ, emulator, shots=shots )
hist = job.result().get_counts()
print('Target:')
print(digit_B,'x',digit_A,'=',digit_B*digit_A,'->',binary_C)
print('Result:')
for label in hist.keys():
print(digit_B,'x',digit_A,'=',qt.bin_to_dec(label, nint=nintC, phase=phase),'->',label,'with probability',float(hist[label])/shots)
qregA = QuantumRegister(nA, 'A')
qregB = QuantumRegister(nB, 'B')
qregC = QuantumRegister(nC, 'C')
out_reg = ClassicalRegister(nC,'out_reg')
circ = QuantumCircuit(qregA, qregB, qregC, out_reg)
# Input the A and B binary strings into their registers
A_gate = qt.input_bits_to_qubits(binary_A, circ, reg=qregA, wrap=True)
B_gate = qt.input_bits_to_qubits(binary_B, circ, reg=qregB, wrap=True)
circ.append(A_gate, qregA);
circ.append(B_gate, qregB);
circ.barrier()
# Define the twos-complement operations
tc_gate_A = qt.TwosCompliment(circ, qregA[:-1], wrap=True).control(1)
tc_gate_B = qt.TwosCompliment(circ, qregB[:-1], wrap=True).control(1)
tc_gate_C = qt.TwosCompliment(circ, qregC[:-1], wrap=True).control(2)
# Add the twos-complement operations to convert registers A and B to sign-magnitude notation
circ.append(tc_gate_A, [qregA[-1], *qregA[:-1]]);
circ.append(tc_gate_B, [qregB[-1], *qregB[:-1]]);
circ.barrier()
# Apply simple QFT multiplication
mult_gate = qt.QFTMultiply(circ, qregA[:-1], qregB[:-1], qregC[:-1], nint1=nintA, nint2=nintB, nint3=nintC, wrap=True)
circ.append(mult_gate, [*qregA[:-1], *qregB[:-1], *qregC[:-1]]);
circ.barrier()
# If register A is positive, but register B is negative, then twos-complement operator on C
circ.x(qregA[-1]);
circ.append(tc_gate_C, [qregA[-1], qregB[-1], *qregC[:-1]]);
circ.x(qregA[-1]);
# If register B is positive, but register A is negative, then twos-complement operator on C
circ.x(qregB[-1]);
circ.append(tc_gate_C, [qregA[-1], qregB[-1], *qregC[:-1]]);
circ.x(qregB[-1]);
circ.barrier()
# If A is negative flip phase qubit of C, and if B is negative flip phase qubit of C
circ.cx(qregA[-1], qregC[-1]);
circ.cx(qregB[-1], qregC[-1]);
circ.barrier()
# Restore registers A and B to original twos-complement notation
circ.append(tc_gate_A, [qregA[-1], *qregA[:-1]]);
circ.append(tc_gate_B, [qregB[-1], *qregB[:-1]]);
circ.barrier()
circ.measure(qregC, out_reg);
circ.draw('latex')
shots=10
emulator = Aer.get_backend('qasm_simulator')
job = execute(circ, emulator, shots=shots )
hist = job.result().get_counts()
print('Target:')
print(digit_B,'x',digit_A,'=',digit_B*digit_A,'->',binary_C)
print('Result:')
for label in hist.keys():
print(digit_B,'x',digit_A,'=',qt.bin_to_dec(label, nint=nintC, phase=phase),'->',label,'with probability',float(hist[label])/shots)
phase = True
digit_A = 0.
digit_B = -7.5
print(digit_A,'x',digit_B,'=',digit_A*digit_B)
binary_A = qt.my_binary_repr(digit_A, nA, nint=nintA, phase=phase)
binary_B = qt.my_binary_repr(digit_B, nB, nint=nintB, phase=phase)
binary_C = qt.my_binary_repr(digit_A*digit_B, nC, nint=nintC, phase=phase)
print(binary_A,binary_B,binary_C)
qregA = QuantumRegister(nA, 'A')
qregB = QuantumRegister(nB, 'B')
qregC = QuantumRegister(nC, 'C')
out_reg = ClassicalRegister(nC,'out_reg')
circ = QuantumCircuit(qregA, qregB, qregC, out_reg)
# Input the A and B binary strings into their registers
A_gate = qt.input_bits_to_qubits(binary_A, circ, reg=qregA, wrap=True)
B_gate = qt.input_bits_to_qubits(binary_B, circ, reg=qregB, wrap=True)
circ.append(A_gate, qregA);
circ.append(B_gate, qregB);
circ.barrier()
# Define the twos-complement operations
tc_gate_A = qt.TwosCompliment(circ, qregA[:-1], wrap=True).control(1)
tc_gate_B = qt.TwosCompliment(circ, qregB[:-1], wrap=True).control(1)
tc_gate_C = qt.TwosCompliment(circ, qregC[:-1], wrap=True).control(2)
# Add the twos-complement operations to convert registers A and B to sign-magnitude notation
circ.append(tc_gate_A, [qregA[-1], *qregA[:-1]]);
circ.append(tc_gate_B, [qregB[-1], *qregB[:-1]]);
circ.barrier()
# Apply simple QFT multiplication
mult_gate = qt.QFTMultiply(circ, qregA[:-1], qregB[:-1], qregC[:-1], nint1=nintA, nint2=nintB, nint3=nintC, wrap=True)
circ.append(mult_gate, [*qregA[:-1], *qregB[:-1], *qregC[:-1]]);
circ.barrier()
# If register A is positive, but register B is negative, then twos-complement operator on C
circ.x(qregA[-1]);
circ.append(tc_gate_C, [qregA[-1], qregB[-1], *qregC[:-1]]);
circ.x(qregA[-1]);
# If register B is positive, but register A is negative, then twos-complement operator on C
circ.x(qregB[-1]);
circ.append(tc_gate_C, [qregA[-1], qregB[-1], *qregC[:-1]]);
circ.x(qregB[-1]);
circ.barrier()
# If A is negative flip phase qubit of C, and if B is negative flip phase qubit of C
circ.cx(qregA[-1], qregC[-1]);
circ.cx(qregB[-1], qregC[-1]);
circ.barrier()
# Restore registers A and B to original twos-complement notation
circ.append(tc_gate_A, [qregA[-1], *qregA[:-1]]);
circ.append(tc_gate_B, [qregB[-1], *qregB[:-1]]);
circ.barrier()
circ.measure(qregC, out_reg);
shots=10
emulator = Aer.get_backend('qasm_simulator')
job = execute(circ, emulator, shots=shots )
hist = job.result().get_counts()
print('Target:')
print(digit_B,'x',digit_A,'=',digit_B*digit_A,'->',binary_C)
print('Result:')
for label in hist.keys():
print(digit_B,'x',digit_A,'=',qt.bin_to_dec(label, nint=nintC, phase=phase),'->',label,'with probability',float(hist[label])/shots)
qregA = QuantumRegister(nA, 'A')
qregB = QuantumRegister(nB, 'B')
qregC = QuantumRegister(nC, 'C')
out_reg = ClassicalRegister(nC,'out_reg')
circ = QuantumCircuit(qregA, qregB, qregC, out_reg)
# Input the A and B binary strings into their registers
A_gate = qt.input_bits_to_qubits(binary_A, circ, reg=qregA, wrap=True)
B_gate = qt.input_bits_to_qubits(binary_B, circ, reg=qregB, wrap=True)
circ.append(A_gate, qregA);
circ.append(B_gate, qregB);
circ.barrier()
# Define the twos-complement operations
tc_gate_A = qt.TwosCompliment(circ, qregA[:-1], wrap=True).control(1)
tc_gate_B = qt.TwosCompliment(circ, qregB[:-1], wrap=True).control(1)
tc_gate_C = qt.TwosCompliment(circ, qregC[:-1], wrap=True).control(2)
# Add the twos-complement operations to convert registers A and B to sign-magnitude notation
circ.append(tc_gate_A, [qregA[-1], *qregA[:-1]]);
circ.append(tc_gate_B, [qregB[-1], *qregB[:-1]]);
circ.barrier()
# Apply simple QFT multiplication
mult_gate = qt.QFTMultiply(circ, qregA[:-1], qregB[:-1], qregC[:-1], nint1=nintA, nint2=nintB, nint3=nintC, wrap=True)
circ.append(mult_gate, [*qregA[:-1], *qregB[:-1], *qregC[:-1]]);
circ.barrier()
# If register A is positive, but register B is negative, then twos-complement operator on C
circ.x(qregA[-1]);
circ.append(tc_gate_C, [qregA[-1], qregB[-1], *qregC[:-1]]);
circ.x(qregA[-1]);
# If register B is positive, but register A is negative, then twos-complement operator on C
circ.x(qregB[-1]);
circ.append(tc_gate_C, [qregA[-1], qregB[-1], *qregC[:-1]]);
circ.x(qregB[-1]);
circ.barrier()
# If A is negative flip phase qubit of C, and if B is negative flip phase qubit of C
circ.cx(qregA[-1], qregC[-1]);
circ.cx(qregB[-1], qregC[-1]);
circ.barrier()
# Restore registers A and B to original twos-complement notation
circ.append(tc_gate_A, [qregA[-1], *qregA[:-1]]);
circ.append(tc_gate_B, [qregB[-1], *qregB[:-1]]);
circ.barrier()
# Flip register A
for qubit in np.arange(nA):
circ.x(qregA[qubit]);
# If register A is all zeros and phase of B is negative, then flip the phase of C
circ.mcx([*qregA, qregB[-1]], qregC[-1], mode='noancilla')
# Flip back register A
for qubit in np.arange(nA):
circ.x(qregA[qubit]);
circ.barrier()
# Flip register B
for qubit in np.arange(nB):
circ.x(qregB[qubit]);
# If register B is all zeros and phase of A is negative, then flip the phase of C
circ.mcx([*qregB, qregA[-1]], qregC[-1], mode='noancilla')
# Flip back register B
for qubit in np.arange(nB):
circ.x(qregB[qubit]);
circ.barrier()
circ.measure(qregC, out_reg);
circ.draw('latex')
shots=10
emulator = Aer.get_backend('qasm_simulator')
job = execute(circ, emulator, shots=shots )
hist = job.result().get_counts()
print('Target:')
print(digit_B,'x',digit_A,'=',digit_B*digit_A,'->',binary_C)
print('Result:')
for label in hist.keys():
print(digit_B,'x',digit_A,'=',qt.bin_to_dec(label, nint=nintC, phase=phase),'->',label,'with probability',float(hist[label])/shots)
phase = True
digit_A = 5.25
digit_B = -7.5
print(digit_A,'x',digit_B,'=',digit_A*digit_B)
binary_A = qt.my_binary_repr(digit_A, nA, nint=nintA, phase=phase)
binary_B = qt.my_binary_repr(digit_B, nB, nint=nintB, phase=phase)
binary_C = qt.my_binary_repr(digit_A*digit_B, nC, nint=nintC, phase=phase)
print(binary_A,binary_B,binary_C)
qregA = QuantumRegister(nA, 'A')
qregB = QuantumRegister(nB, 'B')
qregC = QuantumRegister(nC, 'C')
out_reg = ClassicalRegister(nC,'out_reg')
circ = QuantumCircuit(qregA, qregB, qregC, out_reg)
A_gate = qt.input_bits_to_qubits(binary_A, circ, reg=qregA, wrap=True)
B_gate = qt.input_bits_to_qubits(binary_B, circ, reg=qregB, wrap=True)
circ.append(A_gate, qregA);
circ.append(B_gate, qregB);
mult_gate = qt.QFTMultPhase(circ, qregA, qregB, qregC, nint1=nintA, nint2=nintB, nint3=nintC, wrap=True)
circ.append(mult_gate, [*qregA, *qregB, *qregC]);
circ.measure(qregC, out_reg);
circ.draw(output='latex')
shots=10
emulator = Aer.get_backend('qasm_simulator')
job = execute(circ, emulator, shots=shots )
hist = job.result().get_counts()
print('Target:')
print(digit_B,'x',digit_A,'=',digit_B*digit_A,'->',binary_C)
print('Result:')
for label in hist.keys():
print(digit_B,'x',digit_A,'=',qt.bin_to_dec(label, nint=nintC, phase=phase),'->',label,'with probability',float(hist[label])/shots)
phase = True
signmag = True
digit_A = -5.25
digit_B = 0
print(digit_A,'x',digit_B,'=',digit_A*digit_B)
binary_A = qt.my_binary_repr(digit_A, nA, nint=nintA, phase=phase, signmag=signmag)
binary_B = qt.my_binary_repr(digit_B, nB, nint=nintB, phase=phase, signmag=signmag)
binary_C = qt.my_binary_repr(digit_A*digit_B, nC, nint=nintC, phase=phase, signmag=signmag)
print(binary_A,binary_B,binary_C)
qregA = QuantumRegister(nA, 'A')
qregB = QuantumRegister(nB, 'B')
qregC = QuantumRegister(nC, 'C')
out_reg = ClassicalRegister(nC,'out_reg')
circ = QuantumCircuit(qregA, qregB, qregC, out_reg)
A_gate = qt.input_bits_to_qubits(binary_A, circ, reg=qregA, wrap=True)
B_gate = qt.input_bits_to_qubits(binary_B, circ, reg=qregB, wrap=True)
circ.append(A_gate, qregA);
circ.append(B_gate, qregB);
mult_gate = qt.QFTMultPhase(circ, qregA, qregB, qregC, nint1=nintA, nint2=nintB, nint3=nintC, wrap=True, signmag1=True, signmag2=True, signmag3=True)
circ.append(mult_gate, [*qregA, *qregB, *qregC]);
circ.measure(qregC, out_reg);
circ.decompose(reps=1).draw(output='latex')
shots=10
emulator = Aer.get_backend('qasm_simulator')
job = execute(circ, emulator, shots=shots )
hist = job.result().get_counts()
print('Target:')
print(digit_B,'x',digit_A,'=',digit_B*digit_A,'->',binary_C)
print('Result:')
for label in hist.keys():
print(digit_B,'x',digit_A,'=',qt.bin_to_dec(label, nint=nintC, phase=phase, signmag=signmag),'->',label,'with probability',float(hist[label])/shots)
phase = True
signmag = True
digit_A = -5.25
digit_B = 0
print(digit_A,'x',digit_B,'=',digit_A*digit_B)
binary_A = qt.my_binary_repr(digit_A, nA, nint=nintA, phase=phase, signmag=signmag)
binary_B = qt.my_binary_repr(digit_B, nB, nint=nintB, phase=phase, signmag=signmag)
binary_C = qt.my_binary_repr(digit_A*digit_B, nC, nint=nintC, phase=phase, signmag=signmag)
print(binary_A,binary_B,binary_C)
qregA = QuantumRegister(nA, 'A')
qregB = QuantumRegister(nB, 'B')
qregC = QuantumRegister(nC, 'C')
out_reg = ClassicalRegister(nC,'out_reg')
circ = QuantumCircuit(qregA, qregB, qregC, out_reg)
A_gate = qt.input_bits_to_qubits(binary_A, circ, reg=qregA, wrap=True)
B_gate = qt.input_bits_to_qubits(binary_B, circ, reg=qregB, wrap=True)
circ.append(A_gate, qregA);
circ.append(B_gate, qregB);
circ = qt.QFTMultPhase(circ, qregA, qregB, qregC, nint1=nintA, nint2=nintB, nint3=nintC, poszero=True, signmag1=True, signmag2=True, signmag3=True)
circ.measure(qregC, out_reg);
circ.decompose(reps=1).draw(output='latex')
shots=10
emulator = Aer.get_backend('qasm_simulator')
job = execute(circ, emulator, shots=shots )
hist = job.result().get_counts()
print('Target:')
print(digit_B,'x',digit_A,'=',digit_B*digit_A,'->',binary_C)
print('Result:')
for label in hist.keys():
print(digit_B,'x',digit_A,'=',qt.bin_to_dec(label, nint=nintC, phase=phase, signmag=signmag),'->',label,'with probability',float(hist[label])/shots)
|
https://github.com/mballarin97/mps_qnn
|
mballarin97
|
# This code is part of qcircha.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""
Main script in the library, where all the computation happens,
and that is imported in all other scripts. Here you can pass a PQC of your choice,
and select a simulation backend, MPS, or Qiskit's Aer.
Several random parameter vectors (100 by default) are generated and the circuit
is run this many times, and the entanglement entropy of the final state is saved.
In the subdirectiroy `entanglement` there are scripts for the evaluation of the
entanglement entropy of quantum states.
"""
# Import necessary modules
import time
try:
from qmatchatea import run_simulation
from qmatchatea.qk_utils import qk_transpilation_params
from qmatchatea import QCConvergenceParameters, QCBackend
import qtealeaves.observables as obs
MPS_AVAILABLE = True
except ImportError:
MPS_AVAILABLE = False
import numpy as np
from qiskit import Aer, transpile
from qcircha.entanglement.haar_entanglement import haar_bond_entanglement
from qcircha.entanglement.statevector_entanglement import entanglement_bond
from qcircha.utils import logger
import matplotlib.pyplot as plt
__all__ = ['entanglement_characterization']
def _run_mps(qc, max_bond_dim=1024, do_statevector=False):
"""
Runs a quantum circuit (parameters already numerical) with MPS.
Parameters
----------
qc : :py:class:`QuantumCircuit`
qiskit quantum circuit class
max_bond_dim: int, optional
Maximum bond dimension for the MPS. Default to 1024
do_statevector : bool, optional
If True, compute the statevector of the system. Default to None.
Returns
-------
:py:class:`qcomps.simulation_results`
The results of the simulations, comprehensive of the entanglement
"""
observables = obs.TNObservables()
observables += obs.TNObsBondEntropy()
if do_statevector:
observables += obs.TNState2File('mps_state.txt', 'F')
conv_params = QCConvergenceParameters(int(max_bond_dim) )
trans_params = qk_transpilation_params(linearize=True)
backend = QCBackend()
results = run_simulation(qc, convergence_parameters=conv_params,
transpilation_parameters=trans_params, backend=backend,
observables=observables)
return results
def _run_circuit(qc, parameters, max_bond_dim=1024, do_statevector=False):
"""
Assigns parameters to the quantum circuits and runs it with python-MPS.
Parameters
----------
qc : :py:class:`QuantumCircuit`
qiskit quantum circuit class
parameters : array-like
Array of parameters, which length should match the number of parameters
in the variational circuit
max_bond_dim: int, optional
Maximum bond dimension for the MPS. Default to 1024.
do_statevector : bool, optional
If True, compute the statevector of the system. Default to None.
Returns
-------
:py:class:`qcomps.simulation_results`
The results of the simulations, comprehensive of the entanglement
"""
qc = qc.assign_parameters(parameters)
results = _run_mps(qc, max_bond_dim=max_bond_dim, do_statevector=do_statevector)
return results
def _mps_simulation(qc, random_params, max_bond_dim=1024, do_statevector=False):
""""
Simulation using MPS to study bond entanglement.
Parameters
----------
qc : :py:class:`QuantumCircuit`
qiskit quantum circuit class
random_params : array-like of array-like
Sets of random parameters over which obtain the average
max_bond_dim : int, optional
Maximum bond dimension for MPS simulation
do_statevector : bool, optional
If True, compute the statevector of the system. Default to None.
Returns
-------
array-like of floats
Average of the entanglement over different parameter sets
array-like of floats
Standard deviation of the entanglement over different parameter sets
array-like of ndarray
Array of statevectors if do_statevector=True, otherwise array of None
"""
sim_bknd = Aer.get_backend('statevector_simulator')
mps_results_list = []
statevector_list = []
for idx, params in enumerate(random_params):
print(f"Run {idx}/{len(random_params)}", end="\r")
qc = transpile(qc, sim_bknd) # Why this transpilation?
mps_results = _run_circuit(qc, params, max_bond_dim=max_bond_dim,
do_statevector=do_statevector)
mps_results_list.append(mps_results)
#print(mps_results_list[0].entanglement )
mps_entanglement = np.array([list(res.entanglement.values()) for res in mps_results_list])
ent_means = np.mean(mps_entanglement, axis=0)
ent_std = np.std(mps_entanglement, axis=0)
statevector_list = [res.statevector for res in mps_results_list]
return ent_means, ent_std, statevector_list
def _aer_simulation(qc, random_params, get_statevector = False):
"""
Simulation using Qiskit Aer to study bond entanglement.
TODO: add **kwargs to customize the backend
Parameters
----------
qc : :py:class:`QuantumCircuit`
qiskit quantum circuit class
random_params : array-like of array-like
Sets of random parameters over which obtain the average
Returns
-------
array-like of floats
Average of the entanglement over different parameter sets
array-like of floats
Standard deviation of the entanglement over different parameter sets
array-like of floats or None
statevector of the system
"""
qk_results_list = []
sim_bknd = Aer.get_backend('statevector_simulator')
qc_t = transpile(qc, backend=sim_bknd)
for idx, params in enumerate(random_params):
print(f"Run {idx}/{len(random_params)}", end="\r")
qk_results = sim_bknd.run(qc_t.assign_parameters(params))
qk_results_list.append(np.asarray(qk_results.result().get_statevector()))
print("\nPartial tracing...")
now = time.time()
aer_ent = np.array([entanglement_bond(state) for state in qk_results_list])
print(f" >> Ended in {time.time()-now}")
ent_means = np.mean(aer_ent, axis=0)
ent_std = np.std(aer_ent, axis=0)
if get_statevector == False:
qk_results_list = None
return ent_means, ent_std, qk_results_list
def entanglement_characterization(ansatz = None, backend = 'Aer', get_statevector = False,
distribution=None, trials=100, **kwargs):
"""
Main method to perform the computation, given the simulation
details of the ansatz
Parameters
----------
ansatz : :py:class:`QuantumCircuit`, optional
Quantum circuit with additional metadata, by default None
backend : str, optional
backend of the simulation. Possible: 'MPS', 'Aer', by default 'Aer'
get_statevector : bool, optional
If True, returns the statevector, by default False
distribution : callable, optional
Function to generate the random parameters that will be used
in the simulation. It should take only a tuple as input, which
is the shape of the generated numpy array. If None, use random
parameters uniformly distributed in :math:`U(0, \\pi)`.
To obtain this distribution you might use the numpy.random module
with the aid of functools.partial. Default to None.
trials : int, optional
Number of repetitions over which the average is taken.
Default to 100.
Returns
-------
array-like of floats
average of the entanglement entropy of the ansatz along all bipartitions
array-like of floats
standard deviation of the entanglement entropy of the ansatz along all bipartitions
array-like of floats
average of the entanglement entropy of a Haar circuit along all bipartitions
array-like of floats or None
statevector of the system
"""
metadata = ansatz.metadata
logger(metadata)
num_qubits = metadata['num_qubits']
try:
max_bond_dim = metadata['max_bond_dim']
except:
max_bond_dim = 100
######################################################
# GENERATE RANDOM PARAMETERS (both inputs and weights)
if distribution is None:
random_params = np.pi * np.random.rand(trials, len(ansatz.parameters))
elif callable(distribution):
random_params = distribution( (trials, len(ansatz.parameters)) )
else:
raise TypeError('The variable distribution should be a callable or None, '
+ f'not {type(distribution)}')
######################################################
# SIMULATION WITH MPS or Aer
if backend == 'MPS':
if not MPS_AVAILABLE:
raise RuntimeError('MPS package qmatcha is not installed, so MPS simulation cannot be ran')
if 'max_bond_dim' in kwargs:
max_bond_dim = kwargs['max_bond_dim']
ent_means, ent_std, statevectors = _mps_simulation(ansatz, random_params, max_bond_dim, do_statevector=get_statevector)
elif backend == 'Aer':
ent_means, ent_std, statevectors = _aer_simulation(ansatz, random_params, get_statevector=get_statevector)
else:
raise TypeError(f"Backend {backend} not available")
######################################################
# ENTANGLEMENT STUDY
print("Measured entanglement = ", np.round(ent_means, 4))
# Expected entanglement accross cut lines if Haar distributed
ent_haar = haar_bond_entanglement(num_qubits)
print("Haar entanglement at bond = ", np.round(ent_haar, 4))
######################################################
return ent_means, ent_std, ent_haar, statevectors
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.