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
|
from qiskit import *
backend = BasicAer.get_backend('dm_simulator')
qc1 = QuantumCircuit(1)
options1 = {
'custom_densitymatrix': 'max_mixed'
}
run1 = execute(qc1,backend,**options1)
result1 = run1.result()
print('Density Matrix: \n',result1['results'][0]['data']['densitymatrix'])
qc2 = QuantumCircuit(2)
options2 = {
'custom_densitymatrix': 'binary_string',
'initial_densitymatrix': '01'
}
backend = BasicAer.get_backend('dm_simulator')
run2 = execute(qc2,backend,**options2)
result2 = run2.result()
print('Density Matrix: \n',result2['results'][0]['data']['densitymatrix'])
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import IBMQ, transpile
from qiskit import QuantumCircuit
from qiskit_aer import AerSimulator
from qiskit.tools.visualization import plot_histogram
from qiskit.providers.fake_provider import FakeVigo
device_backend = FakeVigo()
# Construct quantum circuit
circ = QuantumCircuit(3, 3)
circ.h(0)
circ.cx(0, 1)
circ.cx(1, 2)
circ.measure([0, 1, 2], [0, 1, 2])
sim_ideal = AerSimulator()
# Execute and get counts
result = sim_ideal.run(transpile(circ, sim_ideal)).result()
counts = result.get_counts(0)
plot_histogram(counts, title='Ideal counts for 3-qubit GHZ state')
sim_vigo = AerSimulator.from_backend(device_backend)
# Transpile the circuit for the noisy basis gates
tcirc = transpile(circ, sim_vigo)
# Execute noisy simulation and get counts
result_noise = sim_vigo.run(tcirc).result()
counts_noise = result_noise.get_counts(0)
plot_histogram(counts_noise,
title="Counts for 3-qubit GHZ state with device noise model")
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import numpy as np
import matplotlib.pyplot as plt
from IPython.display import display, clear_output
from qiskit.primitives import Estimator
from qiskit.algorithms.minimum_eigensolvers import VQE
from qiskit.algorithms.observables_evaluator import estimate_observables
from qiskit.algorithms.optimizers import COBYLA, SLSQP
from qiskit.circuit import QuantumCircuit, Parameter
from qiskit.circuit.library import TwoLocal
from qiskit.quantum_info import Pauli, SparsePauliOp
from qiskit.utils import algorithm_globals
from qiskit_nature.second_q.operators import FermionicOp
from qiskit_nature.second_q.mappers import JordanWignerMapper
def kronecker_delta_function(n: int, m: int) -> int:
"""An implementation of the Kronecker delta function.
Args:
n (int): The first integer argument.
m (int): The second integer argument.
Returns:
Returns 1 if n = m, else returns 0.
"""
return int(n == m)
def create_deuteron_hamiltonian(
N: int, hbar_omega: float = 7.0, V_0: float = -5.68658111
) -> SparsePauliOp:
"""Creates a version of the Deuteron Hamiltonian as a qubit operator.
Args:
N (int): An integer number that represents the dimension of the
basis.
hbar_omega (float, optional): The value of the product of hbar and omega. Defaults to 7.0.
V_0 (float, optional): The value of the potential energy. Defaults to -5.68658111.
Returns:
SparsePauliOp: The qubit-space Hamiltonian that represents the Deuteron.
"""
hamiltonian_terms = {}
for m in range(N):
for n in range(N):
label = "+_{} -_{}".format(str(n), str(m))
coefficient_kinect = (hbar_omega / 2) * (
(2 * n + 3 / 2) * kronecker_delta_function(n, m)
- np.sqrt(n * (n + (1 / 2))) * kronecker_delta_function(n, m + 1)
- np.sqrt((n + 1) * (n + (3 / 2)) * kronecker_delta_function(n, m - 1))
)
hamiltonian_terms[label] = coefficient_kinect
coefficient_potential = (
V_0 * kronecker_delta_function(n, 0) * kronecker_delta_function(n, m)
)
hamiltonian_terms[label] += coefficient_potential
hamiltonian = FermionicOp(hamiltonian_terms, num_spin_orbitals=N)
mapper = JordanWignerMapper()
qubit_hamiltonian = mapper.map(hamiltonian)
if not isinstance(qubit_hamiltonian, SparsePauliOp):
qubit_hamiltonian = qubit_hamiltonian.primitive
return qubit_hamiltonian
deuteron_hamiltonians = [create_deuteron_hamiltonian(i) for i in range(1, 5)]
for i, hamiltonian in enumerate(deuteron_hamiltonians):
print("Deuteron Hamiltonian: H_{}".format(i + 1))
print(hamiltonian)
print("\n")
theta = Parameter(r"$\theta$")
eta = Parameter(r"$\eta$")
wavefunction = QuantumCircuit(1)
wavefunction.ry(theta, 0)
wavefunction.draw("mpl")
wavefunction2 = QuantumCircuit(2)
wavefunction2.x(0)
wavefunction2.ry(theta, 1)
wavefunction2.cx(1, 0)
wavefunction2.draw("mpl")
wavefunction3 = QuantumCircuit(3)
wavefunction3.x(0)
wavefunction3.ry(eta, 1)
wavefunction3.ry(theta, 2)
wavefunction3.cx(2, 0)
wavefunction3.cx(0, 1)
wavefunction3.ry(-eta, 1)
wavefunction3.cx(0, 1)
wavefunction3.cx(1, 0)
wavefunction3.draw("mpl")
ansatz = [wavefunction, wavefunction2, wavefunction3]
reference_values = []
print("Exact binding energies calculated through numpy.linalg.eigh \n")
for i, hamiltonian in enumerate(deuteron_hamiltonians):
eigenvalues, eigenstates = np.linalg.eigh(hamiltonian.to_matrix())
reference_values.append(eigenvalues[0])
print("Exact binding energy for H_{}: {}".format(i + 1, eigenvalues[0]))
print(
"Results using Estimator for H_1, H_2 and H_3 with the ansatz given in the reference paper \n"
)
for i in range(3):
seed = 42
algorithm_globals.random_seed = seed
vqe = VQE(Estimator(), ansatz=ansatz[i], optimizer=SLSQP())
vqe_result = vqe.compute_minimum_eigenvalue(deuteron_hamiltonians[i])
binding_energy = vqe_result.optimal_value
print("Binding energy for H_{}: {} MeV".format(i + 1, binding_energy))
def callback(eval_count, parameters, mean, std):
# Overwrites the same line when printing
display("Evaluation: {}, Energy: {}, Std: {}".format(eval_count, mean, std))
clear_output(wait=True)
counts.append(eval_count)
values.append(mean)
params.append(parameters)
deviation.append(std)
plots = []
for i in range(3):
counts = []
values = []
params = []
deviation = []
seed = 42
algorithm_globals.random_seed = seed
vqe = VQE(Estimator(), ansatz=ansatz[i], optimizer=COBYLA(), callback=callback)
vqe_result = vqe.compute_minimum_eigenvalue(deuteron_hamiltonians[i])
plots.append([counts, values])
fig, ax = plt.subplots(nrows=3, ncols=1)
fig.set_size_inches((12, 12))
for i, plot in enumerate(plots):
ax[i].plot(plot[0], plot[1], "o-", label="COBYLA")
ax[i].axhline(
y=reference_values[i],
color="k",
linestyle="--",
label=f"Reference Value: {reference_values[i]}",
)
ax[i].legend()
ax[i].set_xlabel("Cost Function Evaluations", fontsize=15)
ax[i].set_ylabel(r"$\langle H_{} \rangle$ - Energy (MeV)".format(i + 1), fontsize=15)
plt.show()
twolocal_ansatzes = []
for i in range(1, 5):
ansatz = TwoLocal(
deuteron_hamiltonians[i - 1].num_qubits,
["rz", "ry"],
"cx",
entanglement="full",
reps=i,
initial_state=None,
)
twolocal_ansatzes.append(ansatz)
print("Results using Estimator for H_1, H_2, H_3 and H_4 with TwoLocal ansatz \n")
seed = 42
algorithm_globals.random_seed = seed
for i in range(4):
vqe = VQE(Estimator(), ansatz=twolocal_ansatzes[i], optimizer=SLSQP())
vqe_result = vqe.compute_minimum_eigenvalue(deuteron_hamiltonians[i])
binding_energy = vqe_result.optimal_value
print("Binding energy for H_{}:".format(i + 1), binding_energy, "MeV")
seed = 42
algorithm_globals.random_seed = seed
plots_tl = []
for i in range(4):
counts = []
values = []
params = []
deviation = []
vqe = VQE(
Estimator(),
ansatz=twolocal_ansatzes[i],
optimizer=SLSQP(),
callback=callback,
)
vqe_result = vqe.compute_minimum_eigenvalue(deuteron_hamiltonians[i])
plots_tl.append([counts, values])
fig, ax = plt.subplots(nrows=4, ncols=1)
fig.set_size_inches((15, 15))
for i, plot in enumerate(plots_tl):
ax[i].plot(plot[0], plot[1], "o-", label="COBYLA")
ax[i].axhline(
y=reference_values[i],
color="k",
linestyle="--",
label=f"Reference Value: {reference_values[i]}",
)
ax[i].legend()
ax[i].set_xlabel("Cost Function Evaluations", fontsize=15)
ax[i].set_ylabel(r"$\langle H_{} \rangle$ - Energy (MeV)".format(i + 1), fontsize=15)
plt.show()
def calculate_observables_exp_values(
quantum_circuit: QuantumCircuit, observables: list, angles: list
) -> list:
"""Calculate the expectation value of an observable given the quantum
circuit that represents the wavefunction and a list of parameters.
Args:
quantum_circuit (QuantumCircuit): A parameterized quantum circuit
that represents the wavefunction of the system.
observables (list): A list containing the observables that we want
to know the expectation values.
angles (list): A list with the values that will be used in the
'bind_parameters' method.
Returns:
list_exp_values (list): A list containing the expectation values
of the observables given as input.
"""
list_exp_values = []
for observable in observables:
exp_values = []
for angle in angles:
qc = quantum_circuit.bind_parameters({theta: angle})
result = estimate_observables(
Estimator(),
quantum_state=qc,
observables=[observable],
)
exp_values.append(result[0][0])
list_exp_values.append(exp_values)
return list_exp_values
angles = list(np.linspace(-np.pi, np.pi, 100))
observables = [
Pauli("IZ"),
Pauli("ZI"),
Pauli("XX"),
Pauli("YY"),
deuteron_hamiltonians[1],
]
h2_observables_exp_values = calculate_observables_exp_values(wavefunction2, observables, angles)
fig, ax = plt.subplots(nrows=2, ncols=1)
fig.set_size_inches((12, 12))
ax[0].plot(angles, h2_observables_exp_values[0], "o", label=r"$Z_0$")
ax[0].plot(angles, h2_observables_exp_values[1], "o", label=r"$Z_1$")
ax[0].plot(angles, h2_observables_exp_values[2], "o", label=r"$X_0X_1$")
ax[0].plot(angles, h2_observables_exp_values[3], "o", label=r"$Y_0Y_1$")
ax[0].axhline(
y=1,
color="k",
linestyle="--",
)
ax[0].axhline(y=-1, color="k", linestyle="--")
ax[0].legend()
ax[0].set_xlabel(r"Theta - $\theta$", fontsize=15)
ax[0].set_ylabel(r"$\langle O \rangle $ - Operator Expectation Value", fontsize=15)
ax[0].set_xticks(
[-np.pi, -np.pi / 2, 0, np.pi / 2, np.pi],
labels=[r"$-\pi$", r"$-\pi/2$", "0", r"$\pi/2$", r"$\pi$"],
)
ax[0].set_title(
r"Expectation value of the observables $Z_0$, $Z_1$, $X_0X_1$ and $Y_0Y_1$ when we vary $\theta$ in the ansatz.",
fontsize=15,
)
ax[1].plot(angles, h2_observables_exp_values[4], "o")
ax[1].axhline(
y=reference_values[1],
color="k",
linestyle="--",
label="Binding Energy: {} MeV".format(np.round(reference_values[1], 3)),
)
ax[1].legend()
ax[1].set_xlabel(r"Theta - $\theta$", fontsize=15)
ax[1].set_ylabel(r"$\langle H_2 \rangle $ - Energy (MeV)", fontsize=15)
ax[1].set_xticks(
[-np.pi, -np.pi / 2, 0, np.pi / 2, np.pi],
labels=[r"$-\pi$", r"$-\pi/2$", "0", r"$\pi/2$", r"$\pi$"],
)
ax[1].set_title(
r"Behavior of the expectation value of $H_2$ when we vary $\theta$ in the ansatz.", fontsize=15
)
plt.show()
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/Pitt-JonesLab/mirror-gates
|
Pitt-JonesLab
|
# TODO, show how different aggression configurations impact results
from qiskit.transpiler import CouplingMap
from mirror_gates.pass_managers import Mirage, QiskitLevel3
from transpile_benchy.metrics.abc_metrics import MetricInterface
from transpile_benchy.metrics.gate_counts import DepthMetric
from mirror_gates.utilities import DoNothing
from transpile_benchy.library import CircuitLibrary
library = CircuitLibrary.from_txt("../../circuits/aggression_select.txt")
# library = CircuitLibrary.from_txt("../../circuits/small_circuits.txt")
# library = CircuitLibrary.from_txt("speedups.txt")
coupling_map = CouplingMap.from_heavy_hex(5)
transpilers = [
QiskitLevel3(coupling_map),
Mirage(coupling_map, name="Mirage-a0", fixed_aggression=0, no_vf2=True),
Mirage(coupling_map, name="Mirage-a1", fixed_aggression=1, no_vf2=True),
Mirage(coupling_map, name="Mirage-a2", fixed_aggression=2, no_vf2=True),
Mirage(coupling_map, name="Mirage-a3", fixed_aggression=3, no_vf2=True),
]
metrics = [DepthMetric(consolidate=False)]
from transpile_benchy.benchmark import Benchmark
# only interested in TimeMetric, is there by default
benchmark = Benchmark(
transpilers=transpilers,
circuit_library=library,
metrics=metrics,
num_runs=1,
)
benchmark.run()
print(benchmark.summary_statistics(transpilers[0], transpilers[1])["monodromy_depth"])
print(benchmark.summary_statistics(transpilers[0], transpilers[2])["monodromy_depth"])
print(benchmark.summary_statistics(transpilers[0], transpilers[3])["monodromy_depth"])
print(benchmark.summary_statistics(transpilers[0], transpilers[4])["monodromy_depth"])
from transpile_benchy.render import plot_benchmark
plot_benchmark(
benchmark,
save=0,
legend_show=1,
filename="aggression",
color_override=[0, 2, 4, 5, 6],
auto_sort=0,
override_legend=[
"Qiskit",
"Mirage-a0",
"Mirage-a1",
"Mirage-a2",
"Mirage-a3",
],
)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, transpile, schedule
from qiskit.visualization.timeline import draw, IQXDebugging
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=IQXDebugging())
|
https://github.com/acfilok96/Quantum-Computation
|
acfilok96
|
import qiskit
from qiskit import *
# import matplotlib.pyplot as plt
%matplotlib inline
print(qiskit.__version__)
circuit = QuantumCircuit(2,2)
circuit.h(0)
circuit.cx(0,1)
circuit.measure([0,1],[0,1])
# circuit.measure_all()
circuit.barrier()
# circuit.draw(output='mpl')
circuit.draw(output='mpl')
simulator = Aer.get_backend('aer_simulator')
result = execute(circuit, backend=simulator, shots=1024).result()
count = result.get_counts()
print(count)
from qiskit.tools.visualization import plot_histogram
plot_histogram(count)
from qiskit import IBMQ
IBMQ.save_account("b32678329f7f6dd426b8cf18f20bea23c2cd056b0bee2b4bcf49744b612e598f20f7170a8da4bfd99b009b6fa59d596edea7a6926fd388be158843d8ef******", overwrite=True)
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q', group='open', project='main')
provider.backends()
from qiskit.providers.ibmq import least_busy
backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 2
and not x.configuration().simulator
and x.status().operational==True))
print("least busy backend: ", backend)
job = execute(circuit, backend=backend, shots=1024)
from qiskit.tools.monitor import job_monitor
job_monitor(job)
result = job.result()
count = result.get_counts()
print(count)
from qiskit.tools.visualization import plot_histogram
plot_histogram(count)
|
https://github.com/abbarreto/qiskit2
|
abbarreto
|
%run init.ipynb
def plot_Pr0(R1, R2):
matplotlib.rcParams.update({'font.size':12}); plt.figure(figsize = (6,4), dpi = 100)
ph_max = 2*math.pi; dph = ph_max/20; ph = np.arange(0, ph_max+dph, dph)
dimph = ph.shape[0]; P0 = np.zeros(dimph)
T1 = math.sqrt(1 - R1**2); T2 = math.sqrt(1 - R2**2)
P0 = T1**2*R2**2 + R1**2*T2**2 + 2*T1*R1*T2*R2*np.cos(ph)
plt.plot(ph, P0); plt.xlabel(r'$\phi$'); plt.ylabel(r'$Pr(0)$')
plt.xlim(0, 2*math.pi); plt.ylim(0, 1)
plt.annotate(r'$R_{1}=$'+str(R1), xy=(0.5,0.5), xytext=(0.5,0.5), fontsize=12)
plt.annotate(r'$R_{2}=$'+str(R1), xy=(0.5,0.4), xytext=(0.5,0.4), fontsize=12)
plt.show()
interactive(plot_Pr0, R1 = (0, 1, 0.05), R2 = (0, 1, 0.05))
def V1(T1, T2):
return (2*T1*T2*np.sqrt(1-T1**2)*np.sqrt(1-T2**2))/((T1**2)*(T2**2) + (1-T1**2)*(1-T2**2))
def V_3d(th, ph):
x = np.linspace(0.00001, 0.99999, 20); y = np.linspace(0.00001, 0.99999, 20); X, Y = np.meshgrid(x, y)
Z = V1(X, Y); fig = plt.figure();
ax = plt.axes(projection = "3d"); ax.plot_wireframe(X, Y, Z, color = 'blue')
ax.set_xlabel(r'$T_{1}$'); ax.set_ylabel(r'$T_{2}$'); ax.set_zlabel(r'$V_{0}$')
ax.view_init(th, ph); fig.tight_layout(); plt.show()
interactive(V_3d, th = (0,90,10), ph = (0,360,10))
from mpl_toolkits import mplot3d
def V0(T1, T2):
return (2*T1*T2*np.sqrt(1-T1**2)*np.sqrt(1-T2**2))/((T1**2)*(1-T2**2) + (1-T1**2)*T2**2)
def V_3d(th, ph):
x = np.linspace(0.00001, 0.99999, 20); y = np.linspace(0.00001, 0.99999, 20); X, Y = np.meshgrid(x, y)
Z = V0(X, Y); fig = plt.figure();
ax = plt.axes(projection = "3d"); ax.plot_wireframe(X, Y, Z, color = 'blue')
ax.set_xlabel(r'$T_{1}$'); ax.set_ylabel(r'$T_{2}$'); ax.set_zlabel(r'$V_{0}$')
ax.view_init(th, ph); fig.tight_layout(); plt.show()
interactive(V_3d, th = (0,90,10), ph = (0,360,10))
def V_3d(th, ph):
x = np.linspace(0.00001, 0.99999, 20); y = np.linspace(0.00001, 0.99999, 20); X, Y = np.meshgrid(x, y)
Z = V0(X, Y)-V1(X, Y); fig = plt.figure();
ax = plt.axes(projection = "3d"); ax.plot_wireframe(X, Y, Z, color = 'blue')
ax.set_xlabel(r'$T_{1}$'); ax.set_ylabel(r'$T_{2}$'); ax.set_zlabel(r'$V_{0}-V_{1}$')
ax.view_init(th, ph); fig.tight_layout(); plt.show()
interactive(V_3d, th = (0,90,10), ph = (0,360,10))
import math
import qiskit
def shannon_num(pv):
d = pv.shape[0]; SE = 0.0; j = -1
while (j < d-1):
j = j + 1
if pv[j] > 10**-15 and pv[j] < (1.0-10**-15):
SE -= pv[j]*math.log2(pv[j])
return SE
import scipy.linalg.lapack as lapak
def von_neumann_num(rho):
d = rho.shape[0]; b = lapak.zheevd(rho)
return shannon_num(b[0])
def coh_re_num(rho):
d = rho.shape[0]; pv = np.zeros(d)
for j in range(0,d):
pv[j] = rho[j,j].real
return shannon_num(pv) - von_neumann_num(rho)
def P_vn_num(rho):
d = rho.shape[0]; P = 0
for j in range(0, d):
if rho[j,j] > 10**-15 and rho[j,j] < (1.0-10**-15):
P += np.absolute(rho[j,j])*math.log2(np.absolute(rho[j,j]))
return math.log2(d) + P
def qc_gmzi(th, ph, ga):
qc = qiskit.QuantumCircuit(1)
qc.rx(-2*th, 0); qc.z(0); qc.y(0); qc.p(ph, 0); qc.rx(-2*ga, 0)
return qc
th, ph, ga = math.pi/3, math.pi/2, math.pi; qcgmzi = qc_gmzi(th, ph, ga); qcgmzi.draw(output = 'mpl')
nshots = 8192
qiskit.IBMQ.load_account()
provider = qiskit.IBMQ.get_provider(hub = 'ibm-q-research-2', group = 'federal-uni-sant-1', project = 'main')
device = provider.get_backend('ibmq_armonk')
simulator = qiskit.Aer.get_backend('qasm_simulator')
from qiskit.tools.monitor import job_monitor
from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter
# for error mitigation
from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter
qr = qiskit.QuantumRegister(1)
qubit_list = [0] # os qubits para os quais aplicaremos calibracao de medidas
meas_calibs, state_labels = complete_meas_cal(qubit_list = qubit_list, qr = qr)
job = qiskit.execute(meas_calibs, backend = device, shots = nshots); job_monitor(job)
cal_results = job.result()
meas_fitter = CompleteMeasFitter(cal_results, state_labels)
# for computing coherence and predictability
th_max = math.pi/2; dth = th_max/10; th = np.arange(0, th_max+dth, dth); dimth = th.shape[0]
Csim = np.zeros(dimth); Psim = np.zeros(dimth); Cexp = np.zeros(dimth); Pexp = np.zeros(dimth)
for j in range(0, dimth):
qr = qiskit.QuantumRegister(1); qc = qiskit.QuantumCircuit(qr); qc.rx(-2*th[j], qr[0])
qstc = state_tomography_circuits(qc, qr[0])
job = qiskit.execute(qstc, simulator, shots = nshots) # simulation
qstf = StateTomographyFitter(job.result(), qstc); rho = qstf.fit(method = 'lstsq')
Csim[j] = coh_re_num(rho); Psim[j] = P_vn_num(rho)
jobE = qiskit.execute(qstc, backend = device, shots = nshots); job_monitor(jobE)
mitigated_results = meas_fitter.filter.apply(jobE.result())
qstfE = StateTomographyFitter(mitigated_results, qstc)
#qstfE = StateTomographyFitter(jobE.result(), qstc)
rhoE = qstfE.fit(method = 'lstsq')
Cexp[j] = coh_re_num(rhoE); Pexp[j] = P_vn_num(rhoE)
Cexp
Pexp
matplotlib.rcParams.update({'font.size':12}); plt.figure(figsize = (6,4), dpi = 100)
plt.plot(th, Csim, label = r'$C_{re}^{sim}$')
plt.plot(th, Psim, label = r'$P_{vn}^{sim}$')
plt.plot(th, Cexp, 'o', label = r'$C_{re}^{exp}$')
plt.plot(th, Pexp, '*', label = r'$P_{vn}^{exp}$')
plt.legend(); plt.xlabel(r'$\theta$')
plt.savefig('coh_vs_ivi_armonk_mit.pdf', format = 'pdf', dpi = 200)
plt.show()
# for computing the visibility
ph_max = 2*math.pi; dph = ph_max/10; ph = np.arange(0, ph_max+dph, dph); dimph = ph.shape[0]
P0sim = np.zeros(dimph); P0exp = np.zeros(dimph)
th[j] = math.pi/2
for k in range(0, dimph):
qr = qiskit.QuantumRegister(1); cr = qiskit.ClassicalRegister(1); qc = qiskit.QuantumCircuit(qr, cr)
qc.rx(-2*th[j], qr[0]); qc.z(qr[0]); qc.y(qr[0])
qc.p(ph[k], qr[0]); ga = th[j]; qc.rx(-2*ga, qr[0]); qc.measure(qr[0], cr[0])
job = qiskit.execute(qc, backend = simulator, shots = nshots) # simulation
counts = job.result().get_counts(qc)
if '0' in counts:
P0sim[k] = counts['0']
jobE = qiskit.execute(qc, backend = device, shots = nshots); job_monitor(jobE)
mitigated_results = meas_fitter.filter.apply(jobE.result())
countsE = mitigated_results.get_counts(qc)
#countsE = jobE.result().get_counts(qc)
if '0' in countsE:
P0exp[k] = countsE['0']
P0sim = P0sim/nshots; P0exp = P0exp/nshots
P0exp
P0sim
P0expthpi2 =
P0simthpi2 =
P0expthpi4 = np.array([1. , 0.90838173, 0.66274091, 0.37488527, 0.11976134,
0.01881309, 0.12251453, 0.36310798, 0.65050474, 0.90455797,
1. ])
P0simthpi4 = np.array([1. , 0.90612793, 0.65258789, 0.34069824, 0.09924316,
0. , 0.09228516, 0.34741211, 0.64331055, 0.90209961,
1. ])
matplotlib.rcParams.update({'font.size':12}); plt.figure(figsize = (6,4), dpi = 100)
plt.plot(ph, P0simthpi4, label = r'$P_{0}^{sim}(\theta=\pi/4)$')
plt.plot(ph, P0expthpi4, 'o', label = r'$P_{0}^{exp}(\theta=\pi/4)$')
plt.plot(ph, P0simthpi2, label = r'$P_{0}^{sim}(\theta=\pi/2)$')
plt.plot(ph, P0expthpi2, '*', label = r'$P_{0}^{exp}(\theta=\pi/2)$')
plt.ylim(0, 2*math.pi); plt.ylim(-0.01, 1.01)
plt.legend(); plt.xlabel(r'$\phi$')
plt.savefig('P0_thpi4_armonk_mit.pdf', format = 'pdf', dpi = 200)
plt.show()
|
https://github.com/alejomonbar/Quantum-Supply-Chain-Manager
|
alejomonbar
|
%load_ext autoreload
%autoreload 2
#pip install pennyane
#improt pennylane dependnecies
import pennylane as qml
from pennylane import numpy as np
from pennylane.optimize import NesterovMomentumOptimizer
# load the csv files
import pandas as pd
# plot the historical acc and cost
import matplotlib.pyplot as plt
import seaborn as sns
from IPython.display import clear_output
clear_output(wait=False)
import os
data_train = pd.read_csv("dataset/fair_train.csv")
X_train,y_train = data_train[data_train.columns[:16]].values, data_train[data_train.columns[16]].values
data_test = pd.read_csv("dataset/classic_test.csv")
X_test,y_test = data_test[data_test.columns[:16]].values, data_test[data_test.columns[16]].values
(X_train.shape, y_train.shape),(X_test.shape, y_test.shape)
n_wires = 4
dev = qml.device("default.qubit", wires=n_wires)
def block(weights, wires):
qml.CNOT(wires=[wires[0],wires[1]])
qml.RY(weights[0], wires=wires[0])
qml.RY(weights[1], wires=wires[1])
n_block_wires = 2
n_params_block = 2
n_blocks = qml.MERA.get_n_blocks(range(n_wires),n_block_wires)
n_blocks
@qml.qnode(dev)
def circuit(weights, x):
qml.AmplitudeEmbedding(x, wires=[0,1,2,3],normalize=True,pad_with=True)
for w in weights:
qml.MERA(range(n_wires),n_block_wires,block, n_params_block, w)
#print(w)
#print(x)
return qml.expval(qml.PauliZ(1))
def variational_classifier(weights, bias, x):
return circuit(weights, x) + bias
def square_loss(labels, predictions):
loss = 0
for l, p in zip(labels, predictions):
loss = loss + (l - p) ** 2
loss = loss / len(labels)
return loss
def accuracy(labels, predictions):
loss = 0
for l, p in zip(labels, predictions):
if abs(l - p) < 1e-5:
loss = loss + 1
loss = loss / len(labels)
return loss
def cost(weights, bias, X, Y):
#print(1)
predictions = [variational_classifier(weights, bias, x) for x in X]
return square_loss(Y, predictions)
np.random.seed(0)
num_layers = 4
weights_init = 2*np.pi * np.random.randn(num_layers,n_blocks, n_params_block, requires_grad=True)
bias_init = np.array(0.0, requires_grad=True)
print(weights_init, bias_init)
print(qml.draw(circuit,expansion_strategy='device',wire_order=[0,1,2,3])(weights_init,np.asarray(X_train[0])))
for i in weights_init:
print(i[0])
y_train = np.where(y_train < 1, -1, y_train)
y_test = np.where(y_test < 1, -1, y_test)
from sklearn.utils import shuffle
X,y = shuffle(X_train, y_train, random_state=0)
from sklearn.model_selection import train_test_split
opt = NesterovMomentumOptimizer(0.4)
batch_size = 32
num_data = len(y_train)
num_train = 0.9
# train the variational classifier
weights = weights_init
bias = bias_init
print()
cost_g = []
acc_train = []
acc_test = []
plt.show()
for it in range(50):
X_train_70, X_test_30, y_train_70, y_test_30 =train_test_split(np.asarray(X), np.asarray(y), train_size=num_train, test_size=1.0-num_train, shuffle=True)
# Update the weights by one optimizer step
batch_index = np.random.randint(0, len(X_train_70), (batch_size,))
feats_train_batch = X_train_70[batch_index]
Y_train_batch = y_train_70[batch_index]
weights, bias, _, _ = opt.step(cost, weights, bias, feats_train_batch, Y_train_batch)
# Compute predictions on train and validation set
predictions_train = [np.sign(variational_classifier(weights, bias, f)) for f in X_train_70]
predictions_val = [np.sign(variational_classifier(weights, bias, f)) for f in X_test_30]
# Compute accuracy on train and validation set
acc_tra = accuracy(y_train_70, predictions_train)
acc_val = accuracy(y_test_30, predictions_val)
cost_train = cost(weights, bias,X_train, y_train)
cost_g.append(cost_train)
acc_train.append(acc_tra)
acc_test.append(acc_val)
clear_output(wait=True)
plt.plot(cost_g,label='cost')
plt.plot(acc_train,label='acc_train')
plt.plot(acc_test,label='acc_test')
plt.legend(['cost','acc_train','acc_test'])
plt.show()
print(
"Iter: {:5d} | Cost: {:0.7f} | Acc train: {:0.7f} | Acc validation: {:0.7f} "
"".format(it + 1, cost_train, acc_tra, acc_val)
)
print(weights)
x_test = []
for x in X_test.tolist():
if sum(x) == 0:
x[0]=1
x_test.append( x/ np.linalg.norm(x))
x_test[0]
y_test_pred = [np.sign(variational_classifier(weights, bias, f)) for f in x_test]
y_test_pred
from sklearn.metrics import confusion_matrix, roc_curve, auc
from sklearn.preprocessing import StandardScaler
# demonstration of calculating metrics for a neural network model using sklearn
from sklearn.metrics import accuracy_score
from sklearn.metrics import precision_score
from sklearn.metrics import recall_score
from sklearn.metrics import f1_score
from sklearn.metrics import cohen_kappa_score
from sklearn.metrics import roc_auc_score
accuracy = accuracy_score(y_test, y_test_pred)
print('Accuracy: %f' % accuracy)
# precision tp / (tp + fp)
precision = precision_score(y_test, y_test_pred)
print('Precision: %f' % precision)
# recall: tp / (tp + fn)
recall = recall_score(y_test, y_test_pred)
print('Recall: %f' % recall)
# f1: 2 tp / (2 tp + fp + fn)
f1 = f1_score(y_test, y_test_pred)
print('F1 score: %f' % f1)
# kappa
kappa = cohen_kappa_score(y_test, y_test_pred)
print('Cohens kappa: %f' % kappa)
# ROC AUC
auc = roc_auc_score(y_test, y_test_pred)
print('ROC AUC: %f' % auc)
# confusion matrix
test_matrix = confusion_matrix(y_test, y_test_pred)
print(test_matrix)
ax = sns.heatmap(test_matrix, annot=True, cmap='Blues', fmt='g')
ax.set_title('Seaborn Confusion Matrix with labels\n\n');
ax.set_xlabel('\nPredicted Values')
ax.set_ylabel('Actual Values ');
ax.xaxis.set_ticklabels(['0','1'])
ax.yaxis.set_ticklabels(['0','1'])
## Display the visualization of the Confusion Matrix.
plt.show()
y_pred_1 = [int(i) for i in y_test_pred ]
y_pred_1 = ["{}\n".format(i) for i in y_pred_1]
with open(r'mera_4_layers.csv', 'w') as fp:
fp.writelines(y_pred_1)
|
https://github.com/BOBO1997/osp_solutions
|
BOBO1997
|
import numpy as np
import matplotlib.pyplot as plt
import itertools
import pickle
# plt.rcParams.update({'font.size': 16}) # enlarge matplotlib fonts
import time
import datetime
# Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z)
from qiskit.opflow import Zero, One, I, X, Y, Z
from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer
from qiskit.providers.aer import QasmSimulator
from qiskit.tools.monitor import job_monitor
from qiskit.circuit import Parameter
# Import QREM package
from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter
# Import mitiq for zne
import mitiq
# Import state tomography modules
from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter
from qiskit.quantum_info import state_fidelity
# Suppress warnings
import warnings
warnings.filterwarnings('ignore')
def trotter_gate(dt, to_instruction = True):
qc = QuantumCircuit(2)
qc.rx(2*dt,0)
qc.rz(2*dt,1)
qc.h(1)
qc.cx(1,0)
qc.rz(-2*dt, 0)
qc.rx(-2*dt, 1)
qc.rz(2*dt, 1)
qc.cx(1,0)
qc.h(1)
qc.rz(2*dt, 0)
return qc.to_instruction() if to_instruction else qc
trotter_gate(np.pi / 6, to_instruction=False).draw("mpl")
# 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)
# Number of trotter steps
trotter_steps = list(range(1,10)) + list(range(10, 101, 10))
st_qcs_list = []
for num_steps in trotter_steps:
# Initialize quantum circuit for 3 qubits
qr = QuantumRegister(7)
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>)
qc.x([5]) # DO NOT MODIFY (|q_5,q_3,q_1> = |110>)
# Simulate time evolution under H_heis3 Hamiltonian
for _ in range(num_steps):
qc.append(Trot_gate, [qr[3], qr[5]])
qc.cx(qr[3], qr[1])
qc.cx(qr[5], qr[3])
# 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})
t3_qc = transpile(qc, optimization_level=3, basis_gates=["sx", "cx", "rz"])
t3_qc = transpile(t3_qc, optimization_level=3, basis_gates=["sx", "cx", "rz"])
# Generate state tomography circuits to evaluate fidelity of simulation
st_qcs = state_tomography_circuits(t3_qc, [qr[1], qr[3], qr[5]])
st_qcs_list.append(st_qcs)
# Display circuit for confirmation
# st_qcs[-1].decompose().draw() # view decomposition of trotter gates
st_qcs_list[-1][-1].draw("mpl") # only view trotter gates
from qiskit.test.mock import FakeJakarta
backend = FakeJakarta()
# backend = Aer.get_backend("qasm_simulator")
# IBMQ.load_account()
# provider = IBMQ.get_provider(hub='ibm-q-utokyo', group='internal', project='hirashi-jst')
# provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22')
# print("provider:", provider)
# backend = provider.get_backend("ibmq_jakarta")
shots = 8192
reps = 8
jobs = []
for _ in range(reps):
# execute
job = execute(st_qcs, backend, shots=shots)
print('Job ID', job.job_id())
jobs.append(job)
# QREM
qr = QuantumRegister(num_qubits)
meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal')
cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout=[5,3,1])
print('Job ID', cal_job.job_id())
dt_now = datetime.datetime.now()
print(dt_now)
with open("jobs_jakarta_50step_" + 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_50step_" + 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("jakarta_50step.pkl", "rb") as f:
job_list = pickle.load(f)
jobs = job_list["jobs"]
cal_job = job_list["cal_job"]
cal_results = cal_job.result()
print("retrieved cal_results")
meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal')
mit_results = []
for i, job in enumerate(jobs):
mit_results.append( meas_fitter.filter.apply(job.result()) )
print("retrieved", i, "th results")
# 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
# Compute tomography fidelities for each repetition
fids = []
for result in mit_results:
fid = state_tomo(result, st_qcs)
fids.append(fid)
print('state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(fids), np.std(fids)))
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
top = QuantumCircuit(1)
top.x(0);
bottom = QuantumCircuit(2)
bottom.cry(0.2, 0, 1);
tensored = bottom.tensor(top)
tensored.draw('mpl')
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
from qiskit.providers.fake_provider import FakeManilaV2
from qiskit import transpile
from qiskit.tools.visualization import plot_histogram
# Get a fake backend from the fake provider
backend = FakeManilaV2()
# Create a simple circuit
circuit = QuantumCircuit(3)
circuit.h(0)
circuit.cx(0,1)
circuit.cx(0,2)
circuit.measure_all()
circuit.draw('mpl')
# Transpile the ideal circuit to a circuit that can be directly executed by the backend
transpiled_circuit = transpile(circuit, backend)
transpiled_circuit.draw('mpl')
# Run the transpiled circuit using the simulated fake backend
job = backend.run(transpiled_circuit)
counts = job.result().get_counts()
plot_histogram(counts)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
# Build a quantum circuit
circuit = QuantumCircuit(3, 3)
circuit.x(1)
circuit.h(range(3))
circuit.cx(0, 1)
circuit.measure(range(3), range(3));
print(circuit)
circuit.draw()
# Matplotlib Drawing
circuit.draw(output='mpl')
# Draw a new circuit with barriers and more registers
q_a = QuantumRegister(3, name='qa')
q_b = QuantumRegister(5, name='qb')
c_a = ClassicalRegister(3)
c_b = ClassicalRegister(5)
circuit = QuantumCircuit(q_a, q_b, c_a, c_b)
circuit.x(q_a[1])
circuit.x(q_b[1])
circuit.x(q_b[2])
circuit.x(q_b[4])
circuit.barrier()
circuit.h(q_a)
circuit.barrier(q_a)
circuit.h(q_b)
circuit.cswap(q_b[0], q_b[1], q_b[2])
circuit.cswap(q_b[2], q_b[3], q_b[4])
circuit.cswap(q_b[3], q_b[4], q_b[0])
circuit.barrier(q_b)
circuit.measure(q_a, c_a)
circuit.measure(q_b, c_b);
# Draw the circuit
circuit.draw(output='mpl')
# Draw the circuit with reversed bit order
circuit.draw(output='mpl', reverse_bits=True)
# Draw the circuit without barriers
circuit.draw(output='mpl', plot_barriers=False)
# Draw the circuit without barriers and reverse bit order
circuit.draw(output='mpl', plot_barriers=False, reverse_bits=True)
# Set line length to 80 for above circuit
circuit.draw(output='text')
# Change the background color in mpl
style = {'backgroundcolor': 'lightgreen'}
circuit.draw(output='mpl', style=style)
# Scale the mpl output to 1/2 the normal size
circuit.draw(output='mpl', scale=0.5)
from qiskit.tools.visualization import circuit_drawer
circuit_drawer(circuit, output='mpl', plot_barriers=False)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.tools.visualization import circuit_drawer
q = QuantumRegister(1)
c = ClassicalRegister(1)
qc = QuantumCircuit(q, c)
qc.h(q)
qc.measure(q, c)
circuit_drawer(qc, output='mpl', style={'backgroundcolor': '#EEEEEE'})
|
https://github.com/Pitt-JonesLab/slam_decomposition
|
Pitt-JonesLab
|
import numpy as np
from slam.hamiltonian import ConversionGainSmush
U = ConversionGainSmush().construct_U(
0, 0, np.pi / 2, 0, [3, 3, 3, 3, 3, 3], [0, 0, 0, 0, 0, 0]
)
from qutip import mesolve
from qutip import tensor, basis, qeye, sigmax, sigmaz
# initial state: start with one of the qubits in its excited state
psi0 = tensor(basis(N, 0), basis(2, 1), basis(2, 0))
from weylchamber import *
WeylChamber().plot()
from slam.utils.visualize import unitary_to_weyl
unitary_to_weyl(U)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, transpile, schedule
from qiskit.visualization.pulse_v2 import draw, IQXSimple
from qiskit.providers.fake_provider import FakeBoeblingen
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
qc.measure_all()
qc = transpile(qc, FakeBoeblingen(), layout_method='trivial')
sched = schedule(qc, FakeBoeblingen())
draw(sched, style=IQXSimple(), backend=FakeBoeblingen())
|
https://github.com/rowanshah/IBM-Qiskit-Models
|
rowanshah
|
import numpy as np
from qiskit import *
%matplotlib inline
# Create a Quantum Register with 3 qubits.
q = QuantumRegister(4, 'q')
# Create a Quantum Circuit acting on the q register
circ = QuantumCircuit(q)
# Add a H gate on qubit 0, putting this qubit in superposition.
circ.h(q[0])
# Add a CX (CNOT) gate on control qubit 0 and target qubit 1, putting
# the qubits in a Bell state.
circ.cx(q[0], q[1])
# Add a CX (CNOT) gate on control qubit 0 and target qubit 2, putting
# the qubits in a GHZ state.
circ.cx(q[0], q[2])
# Add a CX (CNOT) gate on control qubit 0 and target qubit 3, putting
# the qubits in a GHZ state.
circ.cx(q[0], q[3])
circ.draw()
# Import Aer
from qiskit import BasicAer
# Run the quantum circuit on a statevector simulator backend
backend = BasicAer.get_backend('statevector_simulator')
# Create a Quantum Program for execution
job = execute(circ, backend)
result = job.result()
outputstate = result.get_statevector(circ, decimals=3)
print(outputstate)
from qiskit.visualization import plot_state_city
plot_state_city(outputstate)
# Run the quantum circuit on a unitary simulator backend
backend = BasicAer.get_backend('unitary_simulator')
job = execute(circ, backend)
result = job.result()
# Show the results
print(result.get_unitary(circ, decimals=3))
# Create a Classical Register with 3 bits.
c = ClassicalRegister(4, 'c')
# Create a Quantum Circuit
meas = QuantumCircuit(q, c)
meas.barrier(q)
# map the quantum measurement to the classical bits
meas.measure(q,c)
# The Qiskit circuit object supports composition using
# the addition operator.
qc = circ+meas
#drawing the circuit
qc.draw()
# Use Aer's qasm_simulator
backend_sim = BasicAer.get_backend('qasm_simulator')
# Execute the circuit on the qasm simulator.
# We've set the number of repeats of the circuit
# to be 1024, which is the default.
job_sim = execute(qc, backend_sim, shots=1024)
# Grab the results from the job.
result_sim = job_sim.result()
counts = result_sim.get_counts(qc)
print(counts)
from qiskit.visualization import plot_histogram
plot_histogram(counts)
from qiskit import IBMQ
provider = IBMQ.load_account()
print("Available backends:")
provider.backends()
from qiskit.providers.ibmq import least_busy
large_enough_devices = provider.backends(filters=lambda x: x.configuration().n_qubits < 10 and
not x.configuration().simulator)
backend = least_busy(large_enough_devices)
print("The best backend is " + backend.name())
from qiskit.tools.monitor import job_monitor
shots = 1024 # Number of shots to run the program (experiment); maximum is 8192 shots.
max_credits = 3 # Maximum number of credits to spend on executions.
job_exp = execute(qc, backend=backend, shots=shots, max_credits=max_credits)
job_monitor(job_exp)
result_exp = job_exp.result()
counts_exp = result_exp.get_counts(qc)
plot_histogram([counts_exp,counts])
simulator_backend = provider.get_backend('ibmq_qasm_simulator')
shots = 1024 # Number of shots to run the program (experiment); maximum is 8192 shots.
max_credits = 3 # Maximum number of credits to spend on executions.
job_hpc = execute(qc, backend=simulator_backend, shots=shots, max_credits=max_credits)
result_hpc = job_hpc.result()
counts_hpc = result_hpc.get_counts(qc)
plot_histogram(counts_hpc)
job_id = job_exp.job_id()
print('JOB ID: {}'.format(job_id))
retrieved_job = backend.retrieve_job(job_id)
retrieved_job.result().get_counts(qc)
|
https://github.com/Tojarieh97/VQE
|
Tojarieh97
|
%load_ext autoreload
%autoreload 2
import nbimporter
from typing import Dict, Tuple, List
import numpy as np
from tqdm import tqdm
QUBITS_NUM = 4
N = 2**QUBITS_NUM
K = 4
w = 0.5
NUM_SHOTS = 1024
NUM_ITERATIONS = 100
CIRCUIT_DEPTH = 3
PARAMS_NUM = 2*QUBITS_NUM*(CIRCUIT_DEPTH+1)
from qiskit import Aer
from qiskit.utils import QuantumInstance, algorithm_globals
seed = 50
algorithm_globals.random_seed = seed
simulator_backend = Aer.get_backend('qasm_simulator')
from scipy.optimize import minimize
from utiles import *
input_states = get_first_k_eigenvectors_from_n_computational_basis(K, N)
from ansatz_circuit_item2 import get_full_variational_quantum_circuit
init_circuit_params = {
"thetas": np.random.uniform(low=0, high=2*np.pi, size=8),
"phis": np.random.uniform(low=0, high=2*np.pi, size=4),
"D1": 2,
"D2": 6
}
def prepare_circuit_params(thetas) -> Dict:
return {
"thetas": thetas[4:],
"phis": thetas[:4],
"D1": 2,
"D2": 6
}
def get_ansatz_state(circuit_params, input_state):
circuit_params_with_input_state = {**circuit_params, "input_state": input_state}
return get_full_variational_quantum_circuit(**circuit_params_with_input_state)
def transfrom_hamiltonian_into_pauli_strings(hamiltonian) -> List:
pauli_operators = hamiltonian.to_pauli_op().settings['oplist']
pauli_coeffs = list(map(lambda pauli_operator: pauli_operator.coeff, pauli_operators))
pauli_strings = list(map(lambda pauli_operator: pauli_operator.primitive, pauli_operators))
return pauli_coeffs, pauli_strings
from qiskit.circuit.library.standard_gates import HGate, SGate
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
reducing_to_pauli_z_mapping = {
'I': 'I',
'Z': 'Z',
'X': 'Z',
'Y': 'Z'
}
def reduce_pauli_matrixes_into_sigma_z(pauli_string) -> str:
reduced_pauli_string = ""
for matrix_index in range(QUBITS_NUM):
pauli_matrix = str(pauli_string[matrix_index])
reduced_pauli_matrix = reducing_to_pauli_z_mapping[pauli_matrix]
reduced_pauli_string = reduced_pauli_matrix + reduced_pauli_string
return reduced_pauli_string
def add_layer_of_gates_for_reducing_paulis_to_sigma_z(pauli_string, quantum_circuit):
quantum_registers = QuantumRegister(QUBITS_NUM, name="qubit")
additional_circuit_layer = QuantumCircuit(quantum_registers)
for quantum_register_index, pauli_matrix in enumerate(pauli_string):
if pauli_matrix == "X":
additional_circuit_layer.append(HGate(), [quantum_registers[quantum_register_index]])
if pauli_string == "Y":
additional_circuit_layer.append(HGate(), [quantum_registers[quantum_register_index]])
additional_circuit_layer.append(SGate(), [quantum_registers[quantum_register_index]])
extended_quantum_circuit = quantum_circuit.compose(additional_circuit_layer)
return extended_quantum_circuit
def get_probability_distribution(counts: Dict) -> Dict:
proba_distribution = {state: (count / NUM_SHOTS) for state, count in counts.items()}
return proba_distribution
def calculate_probabilities_of_measurments_in_computational_basis(quantum_state_circuit) -> Dict:
quantum_state_circuit.measure_all()
transpiled_quantum_state_circuit = transpile(quantum_state_circuit, simulator_backend)
Qobj = assemble(transpiled_quantum_state_circuit)
result = simulator_backend.run(Qobj).result()
counts = result.get_counts(quantum_state_circuit)
return get_probability_distribution(counts)
def sort_probas_dict_by_qubits_string_keys(proba_distribution: Dict) -> Dict:
return dict(sorted(proba_distribution.items()))
def reset_power_of_minus_1(power_of_minus_1):
power_of_minus_1 = 0
return power_of_minus_1
def convert_pauli_string_into_str(pauli_string) -> str:
return str(pauli_string)
def calculate_expectation_value_of_pauli_string_by_measurments_probas(pauli_string, ansatz_circuit):
pauli_string_expectation_value = 0
power_of_minus_1 = 0
pauli_string_str = convert_pauli_string_into_str(pauli_string)
extended_ansatz_circuit = add_layer_of_gates_for_reducing_paulis_to_sigma_z(pauli_string_str, ansatz_circuit)
probas_distribution = calculate_probabilities_of_measurments_in_computational_basis(extended_ansatz_circuit)
reduced_pauli_string = reduce_pauli_matrixes_into_sigma_z(pauli_string)
sorted_probas_distribuition = sort_probas_dict_by_qubits_string_keys(probas_distribution)
for qubits_string, proba in sorted_probas_distribuition.items():
for string_index in range(QUBITS_NUM):
if(str(qubits_string[string_index])=="1" and str(reduced_pauli_string[string_index])=="Z"):
power_of_minus_1 += 1
pauli_string_expectation_value += pow(-1, power_of_minus_1)*proba
power_of_minus_1 = reset_power_of_minus_1(power_of_minus_1)
return pauli_string_expectation_value
def get_expectation_value(ansatz_circuit, pauli_coeffs, pauli_strings):
total_expection_value = 0
for pauli_coeff, pauli_string in tqdm(zip(pauli_coeffs, pauli_strings)):
total_expection_value += pauli_coeff*calculate_expectation_value_of_pauli_string_by_measurments_probas(
pauli_string, ansatz_circuit)
return total_expection_value
from qiskit import assemble, transpile
def cost_function(thetas, hamiltonian):
circuit_params = prepare_circuit_params(thetas)
computational_eigenvectors = get_first_k_eigenvectors_from_n_computational_basis(K, N)
pauli_coeffs, pauli_strings = transfrom_hamiltonian_into_pauli_strings(hamiltonian)
k_ansatz_state = get_ansatz_state(circuit_params, computational_eigenvectors[K-1])
approximated_energey = get_expectation_value(k_ansatz_state, pauli_coeffs, pauli_strings)
insert_approximated_energy_to_list_of_all_approximated_energies(approximated_energey)
L_w = w*approximated_energey
for j in range(K-1):
ansatz_state = get_ansatz_state(circuit_params, computational_eigenvectors[j])
L_w += get_expectation_value(ansatz_state, pauli_coeffs, pauli_strings)
return L_w
def get_optimal_thetas_of_ansatz_circuit_for_hamiltonian(hamiltonian):
initial_thetas = np.random.uniform(low=0, high=2*np.pi, size=PARAMS_NUM)
optimizer_result = minimize(cost_function,
x0=initial_thetas,
args=(hamiltonian),
method="COBYLA",
options={"maxiter":NUM_ITERATIONS,
"disp": True})
optimal_thetas = optimizer_result.x
return optimal_thetas
def get_approximated_eigenvalue_of_hamiltonian(hamiltonian):
optimal_thetas = get_optimal_thetas_of_ansatz_circuit_for_hamiltonian(hamiltonian)
print("### The optimal parameters found by the optimizer ###")
print(optimal_thetas)
optimal_circuit_params = prepare_circuit_params(optimal_thetas)
computational_eigenvectors = get_first_k_eigenvectors_from_n_computational_basis(K, N)
optimal_ansatz_state = get_ansatz_state(optimal_circuit_params, computational_eigenvectors[K-1])
pauli_coeffs, pauli_strings = transfrom_hamiltonian_into_pauli_strings(hamiltonian)
approximated_eigenvalue = get_expectation_value(optimal_ansatz_state, pauli_coeffs, pauli_strings)
return approximated_eigenvalue
from numpy import linalg as LA
def get_approximation_error(exact_eigenvalue, approximated_eigenvalue):
return abs(abs(exact_eigenvalue)-abs(approximated_eigenvalue))/abs(exact_eigenvalue)
def get_minimum_exact_eigenvalue_of_hamiltonian(hamiltonian):
eigen_values = LA.eigvals(hamiltonian.to_matrix())
print(sorted(eigen_values))
return min(sorted(eigen_values))
def compare_exact_and_approximated_eigenvalue(hamiltonian, approximated_eigenvalue):
exact_eigenvalue = get_minimum_exact_eigenvalue_of_hamiltonian(hamiltonian)
print("Exact Eigenvalue:")
print(exact_eigenvalue)
print("\nApproximated Eigenvalue:")
print(approximated_eigenvalue)
print("\nApproximation Error")
print(get_approximation_error(exact_eigenvalue, approximated_eigenvalue))
plot_convergence_of_optimization_process(approximated_energies, exact_eigenvalue, margin=3)
approximated_energies = []
def insert_approximated_energy_to_list_of_all_approximated_energies(energy):
approximated_energies.append(energy)
import matplotlib.pyplot as plt
def plot_convergence_of_optimization_process(approximated_energies, exact_eigenvalue, margin):
plt.title("convergence of optimization process to the exact eigenvalue")
plt.margins(0, margin)
plt.plot(approximated_energies[-NUM_ITERATIONS])
plt.axhline(y = exact_eigenvalue, color = 'r', linestyle = '-')
plt.grid()
plt.xlabel("# of iterations")
plt.ylabel("Energy")
def plot_fidelity():
plt.plot(LiH_approximated_energies)
plt.xlabel("# of iterations")
plt.ylabel("Energy")
from qiskit.opflow import X, Z, I, H, Y
LiH_molecule_4_qubits = -7.49894690201071*(I^I^I^I) + \
-0.0029329964409502266*(X^X^Y^Y) + \
0.0029329964409502266*(X^Y^Y^X) + \
0.01291078027311749*(X^Z^X^I) + \
-0.0013743761078958677*(X^Z^X^Z) + \
0.011536413200774975*(X^I^X^I) + \
0.0029329964409502266*(Y^X^X^Y) + \
-0.0029329964409502266*(Y^Y^X^X) + \
0.01291078027311749*(Y^Z^Y^I) + \
-0.0013743761078958677*(Y^Z^Y^Z) + \
0.011536413200774975*(Y^I^Y^I) + \
0.16199475388004184*(Z^I^I^I) + \
0.011536413200774975*(Z^X^Z^X) + \
0.011536413200774975*(Z^Y^Z^Y) + \
0.12444770133137588*(Z^Z^I^I) + \
0.054130445793298836*(Z^I^Z^I) + \
0.05706344223424907*(Z^I^I^Z) + \
0.012910780273117487*(I^X^Z^X) + \
-0.0013743761078958677*(I^X^I^X) + \
0.012910780273117487*(I^Y^Z^Y) + \
-0.0013743761078958677*(I^Y^I^Y) + \
0.16199475388004186*(I^Z^I^I) + \
0.05706344223424907*(I^Z^Z^I) + \
0.054130445793298836*(I^Z^I^Z) + \
-0.013243698330265966*(I^I^Z^I) + \
0.08479609543670981*(I^I^Z^Z) + \
-0.013243698330265952*(I^I^I^Z)
%%time
LiH_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(LiH_molecule_4_qubits)
compare_exact_and_approximated_eigenvalue(LiH_molecule_4_qubits, LiH_approximated_eigenvalue)
H2_molecule_Hamiltonian_4_qubits = -0.8105479805373279 * (I^I^I^I) \
+ 0.1721839326191554 * (I^I^I^Z) \
- 0.22575349222402372 * (I^I^Z^I) \
+ 0.17218393261915543 * (I^Z^I^I) \
- 0.2257534922240237 * (Z^I^I^I) \
+ 0.12091263261776627 * (I^I^Z^Z) \
+ 0.16892753870087907 * (I^Z^I^Z) \
+ 0.045232799946057826 * (Y^Y^Y^Y) \
+ 0.045232799946057826 * (X^X^Y^Y) \
+ 0.045232799946057826 * (Y^Y^X^X) \
+ 0.045232799946057826 * (X^X^X^X) \
+ 0.1661454325638241 * (Z^I^I^Z) \
+ 0.1661454325638241 * (I^Z^Z^I) \
+ 0.17464343068300453 * (Z^I^Z^I) \
+ 0.12091263261776627 * (Z^Z^I^I)
%%time
H2_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(H2_molecule_Hamiltonian_4_qubits)
compare_exact_and_approximated_eigenvalue(H2_molecule_Hamiltonian_4_qubits, H2_approximated_eigenvalue)
transverse_ising_4_qubits = 0.0 * (I^I^I^I) \
+ 0.8398088405253477 * (X^I^I^I) \
+ 0.7989496312070936 * (I^X^I^I) \
+ 0.38189710487113193 * (Z^Z^I^I) \
+ 0.057753122422666725 * (I^I^X^I) \
+ 0.5633292636970458 * (Z^I^Z^I) \
+ 0.3152740621483513 * (I^Z^Z^I) \
+ 0.07209487981989715 * (I^I^I^X) \
+ 0.17892334004292654 * (Z^I^I^Z) \
+ 0.2273896497668042 * (I^Z^I^Z) \
+ 0.09762902934216211 * (I^I^Z^Z)
%%time
TI_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(transverse_ising_4_qubits)
compare_exact_and_approximated_eigenvalue(transverse_ising_4_qubits, TI_approximated_eigenvalue)
QUBITS_NUM = 3
N = 2**QUBITS_NUM
NUM_SHOTS = 1024
NUM_ITERATIONS = 100
CIRCUIT_DEPTH = 3
PARAMS_NUM = 2*QUBITS_NUM*(CIRCUIT_DEPTH+1)
from qiskit.opflow import X, Z, I
transverse_ising_3_qubits = 0.0 * (I^I^I) \
+ 0.012764169333459807 * (X^I^I) \
+ 0.7691573729160869 * (I^X^I) \
+ 0.398094746026449 * (Z^Z^I) \
+ 0.15250261906586637 * (I^I^X) \
+ 0.2094051920882264 * (Z^I^Z) \
+ 0.5131291860752999 * (I^Z^Z)
%%time
TI_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(transverse_ising_3_qubits)
compare_exact_and_approximated_eigenvalue(transverse_ising_3_qubits, TI_approximated_eigenvalue)
QUBITS_NUM = 2
N = 2**QUBITS_NUM
NUM_SHOTS = 1024
NUM_ITERATIONS = 100
CIRCUIT_DEPTH = 3
PARAMS_NUM = 2*QUBITS_NUM*(CIRCUIT_DEPTH+1)
transverse_ising_2_qubits = 0.13755727363376802 * (I^X) \
+ 0.43305656297810435 * (X^I) \
+ 0.8538597608997253 * (Z^Z)
%%time
TI_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(transverse_ising_2_qubits)
compare_exact_and_approximated_eigenvalue(transverse_ising_2_qubits, TI_approximated_eigenvalue)
from qiskit.opflow import X, Z, I
H2_molecule_Hamiltonian_2_qubits = -0.5053051899926562*(I^I) + \
-0.3277380754984016*(Z^I) + \
0.15567463610622564*(Z^Z) + \
-0.3277380754984016*(I^Z)
%%time
H2_approximated_eigenvalue = get_approximated_eigenvalue_of_hamiltonian(H2_molecule_Hamiltonian_2_qubits)
compare_exact_and_approximated_eigenvalue(H2_molecule_Hamiltonian_2_qubits, H2_approximated_eigenvalue)
|
https://github.com/adlrocha/cryptoq
|
adlrocha
|
from qiskit import execute, QuantumCircuit, QuantumRegister, ClassicalRegister, Aer
from qiskit.quantum_info.operators import Operator
from qiskit.quantum_info import process_fidelity
from qiskit.providers.aer import QasmSimulator
from qiskit.providers.aer.noise import NoiseModel, errors
from qiskit.aqua.components.oracles import LogicalExpressionOracle, TruthTableOracle
import math
from qiskit.tools.visualization import plot_histogram
import numpy as np
import matplotlib.pyplot as plot
from qiskit import IBMQ
IBMQ.load_accounts()
# ParityCircuit for random bit generator and parity bit
def parityCircuitCheating(cheating=False, cheatingType=0):
if cheating:
# Cheating operator
c1 = cheatingMatrices()[cheatingType]
else:
c1 = np.identity(2)
id_op = Operator(c1)
truthtable = "10011001"
oracle = TruthTableOracle(truthtable)
or_cx = oracle.construct_circuit()
# print(oracle.output_register)
v = oracle.variable_register
o = oracle.output_register
cr1 = ClassicalRegister(3)
cr2 = ClassicalRegister(1)
cx_circ = QuantumCircuit(v, cr2)
or_cx.add_register(cr1)
cx_circ.h(v[1])
cx_circ.cx(v[1], v[0])
cx_circ.unitary(id_op, v[cheatingType+1:cheatingType+2], label='idop')
total_cx = cx_circ + or_cx
total_cx.measure(v, cr1)
total_cx.measure(o, cr2)
return total_cx
x = np.identity(16)
theta = 0.01
x[0][0] = math.cos(theta)
x[1][0] = math.sin(theta)
x[0][1] = -math.sin(theta)
x[1][1] = math.cos(theta)
def rotationMatrix(theta):
x = np.identity(2)
x[0][0] = math.cos(theta)
x[1][0] = math.sin(theta)
x[0][1] = -math.sin(theta)
x[1][1] = math.cos(theta)
return x
# ParityCircuit for random bit generator and parity bit
def parityCircuitCheating(cheating=False, cheatingType=0):
if cheating:
# Cheating operator
c1 = cheatingMatrices()[cheatingType]
else:
c1 = np.identity(2)
id_op = Operator(c1)
truthtable = "10011001"
oracle = TruthTableOracle(truthtable)
or_cx = oracle.construct_circuit()
# print(oracle.output_register)
v = oracle.variable_register
o = oracle.output_register
cr1 = ClassicalRegister(3)
cr2 = ClassicalRegister(1)
cx_circ = QuantumCircuit(v, cr2)
or_cx.add_register(cr1)
cx_circ.h(v[1])
cx_circ.cx(v[1], v[0])
cx_circ.unitary(id_op, v[cheatingType+1:cheatingType+2], label='idop')
total_cx = cx_circ + or_cx
total_cx.measure(v, cr1)
total_cx.measure(o, cr2)
return total_cx
def generateQK(num_bits, theta1=0, theta2=0, securityThresh=1000, simulation=True, withHist=False):
# Create the circuit
cx_circ = parityCircuit(theta1, theta2)
if simulation:
# Execute the circuit
print("Running on simulation...")
job = execute(cx_circ, backend = Aer.get_backend('qasm_simulator'), shots=256*num_bits, memory=True)
result = job.result()
else:
# Execute the circuit
print("Running on real quantum computer...")
job = execute(cx_circ, backend = IBMQ.get_backend('ibmqx2'), shots=256*num_bits, memory=True)
result = job.result()
# Print circuit.
# print(cx_circ)
# Print the result
if withHist:
counts = result.get_counts(cx_circ)
plot.bar(counts.keys(), counts.values(), 1.0, color='g')
plot.show()
memory = result.get_memory()
num_bits = int(num_bits)
# memory = memory[len(memory)-num_bits: len(memory)]
res = {'A': '', 'B': '', 'errorCounter':0, 'valid': True}
counter = 0
i = len(memory)-1
while len(res["A"]) != num_bits:
# print('Memory', memory[i], i)
# Check if error in parity bit and discard if there is
if memory[i][4] == '0':
counter+=1
else:
res["A"] = res["A"] + memory[i][1]
res["B"] = res["B"] + memory[i][2]
# SecurityThreshold from which we discard the key
if counter >= securityThresh:
res['valid'] = False
res["errorCounter"] = counter
return res
i-=1
res["errorCounter"] = counter
return res
# ParityCircuit for random bit generator and parity bit
def parityCircuitCheating(cheating=False, cheatingType=0):
if cheating:
# Cheating operator
c1 = cheatingMatrices()[cheatingType]
else:
c1 = np.identity(2)
id_op = Operator(c1)
truthtable = "10011001"
oracle = TruthTableOracle(truthtable)
or_cx = oracle.construct_circuit()
# print(oracle.output_register)
v = oracle.variable_register
o = oracle.output_register
cr1 = ClassicalRegister(3)
cr2 = ClassicalRegister(1)
cx_circ = QuantumCircuit(v, cr2)
or_cx.add_register(cr1)
cx_circ.h(v[1])
cx_circ.cx(v[1], v[0])
cx_circ.unitary(id_op, v[cheatingType+1:cheatingType+2], label='idop')
total_cx = cx_circ + or_cx
total_cx.measure(v, cr1)
total_cx.measure(o, cr2)
return total_cx
def quantumConsensus(nodes=3, cheating=False, cheatingType=[0,0,0]):
# Placeholder for the nodes results
res = dict(zip(string.ascii_uppercase, range(1, nodes+1)))
toSend = dict(zip(string.ascii_uppercase, range(1, nodes+1)))
# While two nodes with the same value
while sum(res.values()) != 1:
# Placeholder for all measurements
pkts = ''
for i in range(nodes):
cx_circ = parityCircuitCheating(cheating, cheatingType[i])
job = execute(cx_circ, backend = Aer.get_backend('qasm_simulator'), shots=1, memory=True)
result = job.result()
memory = result.get_memory()
res[list(res.keys())[i]] = int(memory[0][1])
#Adding measurements
pkts += memory[0][2]
pkts += memory[0][1]
print(res)
print(res)
tmp = res.copy()
for value in tmp:
if res[value] == 1:
res['winner'] = value
# Corner case
print(pkts)
toSend[list(toSend.keys())[0]] = pkts[0] + pkts[len(pkts)-1]
#Adding proper nodes
for i in range(0, nodes):
# Preparing the packets
toSend[list(toSend.keys())[i]] = pkts[2*i] + pkts[2*i-1]
return res, toSend
def network3nodes(cheating, cheatingType):
res = quantumConsensus(3, cheating, cheatingType)
toSend = res[1]
#TODO: Check the mistake here in the validation.
# Cheat check
if toSend['A'][1] == toSend['C'][0]:
print('As validation correct')
else:
print('As validation failed. Someone cheating')
if toSend['B'][1] == toSend['A'][0]:
print('Bs validation correct')
else:
print('Bs validation failed. Someone cheating')
if toSend['C'][1] == toSend['B'][0]:
print('Cs validation correct')
else:
print('Cs validation failed. Someone cheating')
|
https://github.com/Harcipan/QAI_GroverSim
|
Harcipan
|
from qiskit import QuantumCircuit, transpile, assemble
from qiskit_aer import AerSimulator
from qiskit.visualization import plot_histogram
# Define the function to create the oracle
def create_oracle(n, marked_states):
oracle = QuantumCircuit(n)
# Apply Z gate to the qubits corresponding to the marked states
for state in marked_states:
oracle.z(state)
# Apply controlled-Z gates for diffusion
if n > 2:
oracle.h(range(n))
oracle.x(range(n))
oracle.h(n-1)
oracle.mct(list(range(n-1)), n-1)
oracle.h(n-1)
oracle.x(range(n))
oracle.h(range(n))
return oracle
# Define the function to create the Grover's diffusion operator
def create_diffusion(n):
diffusion = QuantumCircuit(n)
diffusion.h(range(n))
diffusion.x(range(n))
diffusion.h(n-1)
diffusion.mct(list(range(n-1)), n-1)
diffusion.h(n-1)
diffusion.x(range(n))
diffusion.h(range(n))
return diffusion
# Define the function to apply Grover's algorithm
def grover_algorithm(oracle, diffusion, n, marked_states, num_iterations):
grover_circuit = QuantumCircuit(n)
# Apply Hadamard gates to all qubits
grover_circuit.h(range(n))
# Apply the Grover iterations
for _ in range(num_iterations):
grover_circuit.append(oracle, range(n))
grover_circuit.append(diffusion, range(n))
# Measure all qubits
grover_circuit.measure_all()
return grover_circuit
# Define the marked states and the number of qubits
n = 3
marked_states = [4, 7] # Corresponding to |100⟩ and |111⟩
num_iterations = 1
# Create the oracle and the diffusion operator
oracle = create_oracle(n, marked_states)
diffusion = create_diffusion(n)
# Apply Grover's algorithm
grover_circuit = grover_algorithm(oracle, diffusion, n, marked_states, num_iterations)
# Draw the circuit
print(grover_circuit.draw())
# Simulate the circuit
simulator = AerSimulator()
grover_transpiled = transpile(grover_circuit, simulator)
qobj = assemble(grover_transpiled)
result = simulator.run(qobj).result()
# Plot the histogram of the result
counts = result.get_counts()
print(counts)
plot_histogram(counts)
|
https://github.com/Naphann/Solving-TSP-Grover
|
Naphann
|
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit import IBMQ, Aer, execute
from qiskit.tools.visualization import plot_histogram
## distance_black_box
distances = {
"32": 3,
"31": 2,
"30": 4,
"21": 7,
"20": 6,
"10": 5,
}
def dist_single():
qr = QuantumRegister(2)
qr_target = QuantumRegister(5)
qc = QuantumCircuit(qr, qr_target, name='dist_single')
for edge in distances:
if edge[0] == '3':
node = format(int(edge[1]), '02b')[::-1]
d_bin = format(distances[edge], '02b')[::-1]
for idx in range(len(node)):
if node[idx] == '0':
qc.x(qr[idx])
for idx in range(len(d_bin)):
if d_bin[idx] == '1':
qc.ccx(qr[0], qr[1], qr_target[idx])
for idx in range(len(node)):
if node[idx] == '0':
qc.x(qr[idx])
return qc
def dist():
qr1 = QuantumRegister(2)
qr2 = QuantumRegister(2)
qr_target = QuantumRegister(5)
qr_anc = QuantumRegister(2)
qc = QuantumCircuit(qr1, qr2, qr_target, qr_anc, name='dist')
for edge in distances:
if edge[0] != '3':
# convert to binaries
node1 = format(int(edge[0]), '02b')[::-1]
node2 = format(int(edge[1]), '02b')[::-1]
d_bin = format(distances[edge], '02b')[::-1]
for idx in range(len(node1)): # assume node1 and node2 have the same length
if node1[idx] == '0':
qc.x(qr1[idx])
for idx in range(len(node2)):
if node2[idx] == '0':
qc.x(qr2[idx])
for idx in range(len(d_bin)):
if d_bin[idx] == '1':
qc.mct(qr1[:]+qr2[:], qr_target[idx], qr_anc)
for idx in range(len(node2)): # invert back
if node2[idx] == '0':
qc.x(qr2[idx])
for idx in range(len(node1)):
if node1[idx] == '0':
qc.x(qr1[idx])
return qc
qr1 = QuantumRegister(2) # node reg.
qr2 = QuantumRegister(2) # node reg.
qr_target = QuantumRegister(5) # distance reg.
qr_anc = QuantumRegister(2)
c = ClassicalRegister(5)
qc = QuantumCircuit(qr1, qr2, qr_target, qr_anc, c)
qc.x(qr1[0])
# qc.x(qr2[0])
qc.append(dist(), qr1[:] + qr2[:] + qr_target[:] + qr_anc[:])
qc.measure(qr_target, c)
# qc.draw(output='mpl')
backend = Aer.get_backend('qasm_simulator')
job = execute(qc, backend, shots=1024)
counts = job.result().get_counts()
plot_histogram(counts)
format(1, '02b')
|
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/MonitSharma/Learn-Quantum-Machine-Learning
|
MonitSharma
|
%pip install qiskit
from qiskit import ClassicalRegister, QuantumRegister, QuantumCircuit
from qiskit_aer import AerSimulator
from qiskit.primitives import BackendEstimator, BackendSampler
import numpy as np
np.set_printoptions(precision=3, suppress=True)
backend = AerSimulator(method='automatic')
q = QuantumRegister(1)
c = ClassicalRegister(1)
circuit = QuantumCircuit(q, c)
circuit.measure(q[0], c[0])
circuit.draw(output='mpl')
sampler = BackendSampler(backend)
job = sampler.run(circuit, options={'shots': 1})
result = job.result()
print("Counts",result.quasi_dists[0])
backend = AerSimulator(method='statevector')
from qiskit.quantum_info import Statevector
circuit = QuantumCircuit(q, c)
circuit.id(q[0])
# get the statevcector
state = Statevector.from_instruction(circuit)
print(state)
circuit.draw(output='mpl')
from qiskit.visualization import plot_bloch_multivector
print("Initial state")
plot_bloch_multivector(state)
circuit.h(q[0])
circuit.draw(output='mpl')
state = Statevector.from_instruction(circuit)
print("After a Hadamard gate")
plot_bloch_multivector(state)
from qiskit.visualization import plot_histogram
circuit.measure(q[0], c[0])
job = sampler.run(circuit, options={'shots': 1024})
result = job.result()
print("Initial state statistics")
plot_histogram(result.quasi_dists[0])
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, transpile, schedule
from qiskit.visualization.pulse_v2 import draw
from qiskit.providers.fake_provider import FakeBoeblingen
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
qc.measure_all()
qc = transpile(qc, FakeBoeblingen(), layout_method='trivial')
sched = schedule(qc, FakeBoeblingen())
draw(sched, backend=FakeBoeblingen())
|
https://github.com/tomtuamnuq/compare-qiskit-ocean
|
tomtuamnuq
|
from qiskit import IBMQ
import networkx as nx
from qiskit.providers.ibmq import least_busy
import matplotlib.pyplot as plt
IBMQ.load_account() # Load account from disk
IBMQ.providers() # List all available providers
provider = IBMQ.get_provider(hub='ibm-q')
provider.backends()
backends = provider.backends(filters=lambda x: x.configuration().n_qubits >= 5
and not x.configuration().simulator
and x.status().operational==True)
print(f" Backend with only {least_busy(backends).status().pending_jobs} pending jobs is {least_busy(backends).name()}")
backend = provider.get_backend('ibmq_16_melbourne')
print(f" {backend.name()} currently has {backend.status().pending_jobs} pending jobs")
melbourne_conf = backend.configuration()
G = nx.Graph()
G.add_nodes_from(range(0,melbourne_conf.n_qubits))
G.add_edges_from(melbourne_conf.coupling_map)
pos = nx.kamada_kawai_layout(G)
nx.draw_networkx(G, pos, with_labels = True)
melbourne_props = backend.properties()
melbourne_props.qubits[1]
melbourne_conf.basis_gates
gates_on_qubit_1 = [gate.to_dict() for gate in melbourne_props.gates if 1 in gate.qubits]
len(gates_on_qubit_1)
for gate in gates_on_qubit_1 :
if gate['qubits'][0] == 1:
print("{} involves qubits:{} and has an error rate of {}".format(gate['gate'],gate['qubits'],melbourne_props.gate_error(gate['gate'], gate['qubits'])))
|
https://github.com/dimple12M/Qiskit-Certification-Guide
|
dimple12M
| |
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 QFI."""
import unittest
from ddt import ddt, data
import numpy as np
from qiskit import QuantumCircuit
from qiskit_algorithms.gradients import LinCombQGT, ReverseQGT, QFI, DerivativeType
from qiskit.circuit import Parameter
from qiskit.circuit.parametervector import ParameterVector
from qiskit.primitives import Estimator
from qiskit.test import QiskitTestCase
@ddt
class TestQFI(QiskitTestCase):
"""Test QFI"""
def setUp(self):
super().setUp()
self.estimator = Estimator()
self.lcu_qgt = LinCombQGT(self.estimator, derivative_type=DerivativeType.REAL)
self.reverse_qgt = ReverseQGT(derivative_type=DerivativeType.REAL)
def test_qfi(self):
"""Test if the quantum fisher information calculation is correct for a simple test case.
QFI = [[1, 0], [0, 1]] - [[0, 0], [0, cos^2(a)]]
"""
# create the circuit
a, b = Parameter("a"), Parameter("b")
qc = QuantumCircuit(1)
qc.h(0)
qc.rz(a, 0)
qc.rx(b, 0)
param_list = [[np.pi / 4, 0.1], [np.pi, 0.1], [np.pi / 2, 0.1]]
correct_values = [[[1, 0], [0, 0.5]], [[1, 0], [0, 0]], [[1, 0], [0, 1]]]
qfi = QFI(self.lcu_qgt)
for i, param in enumerate(param_list):
qfis = qfi.run([qc], [param]).result().qfis
np.testing.assert_allclose(qfis[0], correct_values[i], atol=1e-3)
def test_qfi_phase_fix(self):
"""Test the phase-fix argument in the QFI calculation"""
# create the circuit
a, b = Parameter("a"), Parameter("b")
qc = QuantumCircuit(1)
qc.h(0)
qc.rz(a, 0)
qc.rx(b, 0)
param = [np.pi / 4, 0.1]
# test for different values
correct_values = [[1, 0], [0, 1]]
qgt = LinCombQGT(self.estimator, phase_fix=False)
qfi = QFI(qgt)
qfis = qfi.run([qc], [param]).result().qfis
np.testing.assert_allclose(qfis[0], correct_values, atol=1e-3)
@data("lcu", "reverse")
def test_qfi_maxcut(self, qgt_kind):
"""Test the QFI for a simple MaxCut problem.
This is interesting because it contains the same parameters in different gates.
"""
# create maxcut circuit for the hamiltonian
# H = (I ^ I ^ Z ^ Z) + (I ^ Z ^ I ^ Z) + (Z ^ I ^ I ^ Z) + (I ^ Z ^ Z ^ I)
x = ParameterVector("x", 2)
ansatz = QuantumCircuit(4)
# initial hadamard layer
ansatz.h(ansatz.qubits)
# e^{iZZ} layers
def expiz(qubit0, qubit1):
ansatz.cx(qubit0, qubit1)
ansatz.rz(2 * x[0], qubit1)
ansatz.cx(qubit0, qubit1)
expiz(2, 1)
expiz(3, 0)
expiz(2, 0)
expiz(1, 0)
# mixer layer with RX gates
for i in range(ansatz.num_qubits):
ansatz.rx(2 * x[1], i)
reference = np.array([[16.0, -5.551], [-5.551, 18.497]])
param = [0.4, 0.69]
qgt = self.lcu_qgt if qgt_kind == "lcu" else self.reverse_qgt
qfi = QFI(qgt)
qfi_result = qfi.run([ansatz], [param]).result().qfis
np.testing.assert_array_almost_equal(qfi_result[0], reference, decimal=3)
def test_options(self):
"""Test QFI's options"""
a = Parameter("a")
qc = QuantumCircuit(1)
qc.rx(a, 0)
qgt = LinCombQGT(estimator=self.estimator, options={"shots": 100})
with self.subTest("QGT"):
qfi = QFI(qgt=qgt)
options = qfi.options
result = qfi.run([qc], [[1]]).result()
self.assertEqual(result.options.get("shots"), 100)
self.assertEqual(options.get("shots"), 100)
with self.subTest("QFI init"):
qfi = QFI(qgt=qgt, options={"shots": 200})
result = qfi.run([qc], [[1]]).result()
options = qfi.options
self.assertEqual(result.options.get("shots"), 200)
self.assertEqual(options.get("shots"), 200)
with self.subTest("QFI update"):
qfi = QFI(qgt, options={"shots": 200})
qfi.update_default_options(shots=100)
options = qfi.options
result = qfi.run([qc], [[1]]).result()
self.assertEqual(result.options.get("shots"), 100)
self.assertEqual(options.get("shots"), 100)
with self.subTest("QFI run"):
qfi = QFI(qgt=qgt, options={"shots": 200})
result = qfi.run([qc], [[0]], shots=300).result()
options = qfi.options
self.assertEqual(result.options.get("shots"), 300)
self.assertEqual(options.get("shots"), 200)
if __name__ == "__main__":
unittest.main()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import numpy as np
from qiskit_nature.second_q.hamiltonians import QuadraticHamiltonian
# create Hamiltonian
hermitian_part = np.array(
[
[1.0, 2.0, 0.0, 0.0],
[2.0, 1.0, 2.0, 0.0],
[0.0, 2.0, 1.0, 2.0],
[0.0, 0.0, 2.0, 1.0],
]
)
antisymmetric_part = np.array(
[
[0.0, 3.0, 0.0, 0.0],
[-3.0, 0.0, 3.0, 0.0],
[0.0, -3.0, 0.0, 3.0],
[0.0, 0.0, -3.0, 0.0],
]
)
constant = 4.0
hamiltonian = QuadraticHamiltonian(
hermitian_part=hermitian_part,
antisymmetric_part=antisymmetric_part,
constant=constant,
)
# convert it to a FermionicOp and print it
hamiltonian_ferm = hamiltonian.second_q_op()
print(hamiltonian_ferm)
# get the transformation matrix W and orbital energies {epsilon_j}
(
transformation_matrix,
orbital_energies,
transformed_constant,
) = hamiltonian.diagonalizing_bogoliubov_transform()
print(f"Shape of matrix W: {transformation_matrix.shape}")
print(f"Orbital energies: {orbital_energies}")
print(f"Transformed constant: {transformed_constant}")
from qiskit_nature.second_q.circuit.library import FermionicGaussianState
occupied_orbitals = (0, 2)
eig = np.sum(orbital_energies[list(occupied_orbitals)]) + transformed_constant
print(f"Eigenvalue: {eig}")
circuit = FermionicGaussianState(transformation_matrix, occupied_orbitals=occupied_orbitals)
circuit.draw("mpl")
from qiskit.quantum_info import Statevector
from qiskit_nature.second_q.mappers import JordanWignerMapper
# simulate the circuit to get the final state
state = np.array(Statevector(circuit))
# convert the Hamiltonian to a matrix
hamiltonian_jw = JordanWignerMapper().map(hamiltonian_ferm).to_matrix()
# check that the state is an eigenvector with the expected eigenvalue
np.testing.assert_allclose(hamiltonian_jw @ state, eig * state, atol=1e-8)
# create Hamiltonian
hermitian_part = np.array(
[
[1.0, 2.0, 0.0, 0.0],
[2.0, 1.0, 2.0, 0.0],
[0.0, 2.0, 1.0, 2.0],
[0.0, 0.0, 2.0, 1.0],
]
)
constant = 4.0
hamiltonian = QuadraticHamiltonian(
hermitian_part=hermitian_part,
constant=constant,
)
print(f"Hamiltonian conserves particle number: {hamiltonian.conserves_particle_number()}")
# get the transformation matrix W and orbital energies {epsilon_j}
(
transformation_matrix,
orbital_energies,
transformed_constant,
) = hamiltonian.diagonalizing_bogoliubov_transform()
print(f"Shape of matrix W: {transformation_matrix.shape}")
print(f"Orbital energies: {orbital_energies}")
print(f"Transformed constant: {transformed_constant}")
from qiskit_nature.second_q.circuit.library import SlaterDeterminant
occupied_orbitals = (0, 2)
eig = np.sum(orbital_energies[list(occupied_orbitals)]) + transformed_constant
print(f"Eigenvalue: {eig}")
circuit = SlaterDeterminant(transformation_matrix[list(occupied_orbitals)])
circuit.draw("mpl")
from qiskit_nature.second_q.circuit.library import BogoliubovTransform
from qiskit import QuantumCircuit, QuantumRegister
from qiskit.quantum_info import random_hermitian, random_statevector, state_fidelity
from scipy.linalg import expm
# create Hamiltonian
n_modes = 5
hermitian_part = np.array(random_hermitian(n_modes))
hamiltonian = QuadraticHamiltonian(hermitian_part=hermitian_part)
# diagonalize Hamiltonian
(
transformation_matrix,
orbital_energies,
_,
) = hamiltonian.diagonalizing_bogoliubov_transform()
# set simulation time and construct time evolution circuit
time = 1.0
register = QuantumRegister(n_modes)
circuit = QuantumCircuit(register)
bog_circuit = BogoliubovTransform(transformation_matrix)
# change to the diagonal basis of the Hamiltonian
circuit.append(bog_circuit.inverse(), register)
# perform time evolution by applying z rotations
for q, energy in zip(register, orbital_energies):
circuit.rz(-energy * time, q)
# change back to the original basis
circuit.append(bog_circuit, register)
# simulate the circuit
initial_state = random_statevector(2**n_modes)
final_state = initial_state.evolve(circuit)
# compute the correct state by direct exponentiation
hamiltonian_jw = JordanWignerMapper().map(hamiltonian.second_q_op()).to_matrix()
exact_evolution_op = expm(-1j * time * hamiltonian_jw)
expected_state = exact_evolution_op @ np.array(initial_state)
# check that the simulated state is correct
fidelity = state_fidelity(final_state, expected_state)
np.testing.assert_allclose(fidelity, 1.0, atol=1e-8)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/usamisaori/quantum-expressibility-entangling-capability
|
usamisaori
|
import sys
sys.path.append('../')
from expressibility import expressibility
from entanglement import Ent
import numpy as np
import kaleidoscope.qiskit
from kaleidoscope import bloch_sphere
import matplotlib.pyplot as plt
from qiskit import QuantumCircuit
from qiskit.quantum_info import DensityMatrix
def getDensityMatrix(circuit):
return DensityMatrix(circuit).data
import warnings
warnings.filterwarnings('ignore')
def sampleI(layer=1, qubits=1):
circuit = QuantumCircuit(1)
circuit.i(0)
return circuit
def sampleHU1(layer=1, qubits=1):
circuit = QuantumCircuit(1)
circuit.h(0)
circuit.u1(np.random.uniform(0, np.pi * 2), 0)
return circuit
def sampleHU2(layer=1, qubits=1):
circuit = QuantumCircuit(1)
circuit.h(0)
circuit.u2(np.random.uniform(0, np.pi * 2), np.random.uniform(0, np.pi * 2), 0)
return circuit
def sampleHU3(layer=1, qubits=1):
circuit = QuantumCircuit(1)
circuit.h(0)
circuit.u3(np.random.uniform(0, np.pi * 2), np.random.uniform(0, np.pi * 2), np.random.uniform(0, np.pi * 2), 0)
return circuit
X = np.matrix([
[0, 1], [1, 0]
])
Y = np.matrix([
[0, -1j],
[1j, 0]
])
Z = np.matrix([
[1, 0],
[0, -1]
])
def point(sample):
rou = getDensityMatrix(sample())
return [
np.trace(rou @ X).real,
np.trace(rou @ Y).real,
np.trace(rou @ Z).real
]
color = "#FF9933"
bins = 100
sampleI().draw(output='mpl')
pointsI = [ point(sampleI) for i in range(100) ]
bloch_sphere(points=pointsI, points_color=color)
h_i, p_i = expressibility(1, sampleI, bins=bins, return_detail=True)
fig, ax = plt.subplots()
plt.bar([ i/100 for i in range(bins) ], h_i, color="#9999FF", label="Haar", width=0.01)
plt.bar([ i/100 for i in range(bins) ], p_i, color="#FF9933AA", label="VQC", width=0.01)
plt.ylabel("Probability", fontsize=15)
plt.xlabel("Fidelity", fontsize=15)
plt.title("Expr")
ax.legend(loc="upper center")
sampleHU1().draw(output='mpl')
pointsHU1 = [ point(sampleHU1) for i in range(2000) ]
bloch_sphere(points=pointsHU1, points_color=color)
h_hu1, p_hu1 = expressibility(1, sampleHU1, bins=bins, return_detail=True)
fig, ax = plt.subplots()
plt.bar([ i/100 for i in range(bins) ], h_hu1, color="#9999FF", label="Haar", width=0.01)
plt.bar([ i/100 for i in range(bins) ], p_hu1, color="#FF9933AA", label="VQC", width=0.01)
plt.ylabel("Probability", fontsize=15)
plt.xlabel("Fidelity", fontsize=15)
plt.title("Expr")
ax.legend(loc="upper center")
sampleHU2().draw(output='mpl')
pointsHU2 = [ point(sampleHU2) for i in range(2000) ]
bloch_sphere(points=pointsHU2, points_color=color)
h_hu2, p_hu2 = expressibility(1, sampleHU2, bins=bins, return_detail=True)
fig, ax = plt.subplots()
plt.bar([ i/100 for i in range(bins) ], h_hu2, color="#9999FF", label="Haar", width=0.01)
plt.bar([ i/100 for i in range(bins) ], p_hu2, color="#FF9933AA", label="VQC", width=0.01)
plt.ylabel("Probability", fontsize=15)
plt.xlabel("Fidelity", fontsize=15)
plt.title("Expr")
ax.legend(loc="upper center")
sampleHU3().draw(output='mpl')
pointsHU3 = [ point(sampleHU3) for i in range(2000) ]
bloch_sphere(points=pointsHU3, points_color=color)
h_hu3, p_hu3 = expressibility(1, sampleHU3, bins=bins, return_detail=True)
fig, ax = plt.subplots()
plt.bar([ i/100 for i in range(bins) ], h_hu3, color="#9999FF", label="Haar", width=0.01)
plt.bar([ i/100 for i in range(bins) ], p_hu3, color="#FF9933AA", label="VQC", width=0.01)
plt.ylabel("Probability", fontsize=15)
plt.xlabel("Fidelity", fontsize=15)
plt.title("Expr")
ax.legend(loc="upper center")
|
https://github.com/mathelatics/QGSS-2023-From-Theory-to-Implementations
|
mathelatics
|
from qiskit import *
from qiskit.visualization import plot_histogram
import numpy as np
def NOT(inp):
"""An NOT gate.
Parameters:
inp (str): Input, encoded in qubit 0.
Returns:
QuantumCircuit: Output NOT circuit.
str: Output value measured from qubit 0.
"""
qc = QuantumCircuit(1, 1) # A quantum circuit with a single qubit and a single classical bit
qc.reset(0)
# We encode '0' as the qubit state |0⟩, and '1' as |1⟩
# Since the qubit is initially |0⟩, we don't need to do anything for an input of '0'
# For an input of '1', we do an x to rotate the |0⟩ to |1⟩
if inp=='1':
qc.x(0)
# barrier between input state and gate operation
qc.barrier()
# Now we've encoded the input, we can do a NOT on it using x
qc.x(0)
#barrier between gate operation and measurement
qc.barrier()
# Finally, we extract the |0⟩/|1⟩ output of the qubit and encode it in the bit c[0]
qc.measure(0,0)
qc.draw()
# We'll run the program on a simulator
backend = Aer.get_backend('qasm_simulator')
# Since the output will be deterministic, we can use just a single shot to get it
job = backend.run(qc, shots=1, memory=True)
output = job.result().get_memory()[0]
return qc, output
## Test the function
for inp in ['0', '1']:
qc, out = NOT(inp)
print('NOT with input',inp,'gives output',out)
display(qc.draw())
print('\n')
def XOR(inp1,inp2):
"""An XOR gate.
Parameters:
inpt1 (str): Input 1, encoded in qubit 0.
inpt2 (str): Input 2, encoded in qubit 1.
Returns:
QuantumCircuit: Output XOR circuit.
str: Output value measured from qubit 1.
"""
qc = QuantumCircuit(2, 1)
qc.reset(range(2))
if inp1=='1':
qc.x(0)
if inp2=='1':
qc.x(1)
# barrier between input state and gate operation
qc.barrier()
# this is where your program for quantum XOR gate goes
qc.cx(0, 1)
# barrier between input state and gate operation
qc.barrier()
qc.measure(1,0) # output from qubit 1 is measured
#We'll run the program on a simulator
backend = Aer.get_backend('qasm_simulator')
#Since the output will be deterministic, we can use just a single shot to get it
job = backend.run(qc, shots=1, memory=True)
output = job.result().get_memory()[0]
return qc, output
## Test the function
for inp1 in ['0', '1']:
for inp2 in ['0', '1']:
qc, output = XOR(inp1, inp2)
print('XOR with inputs',inp1,inp2,'gives output',output)
display(qc.draw())
print('\n')
def AND(inp1,inp2):
"""An AND gate.
Parameters:
inpt1 (str): Input 1, encoded in qubit 0.
inpt2 (str): Input 2, encoded in qubit 1.
Returns:
QuantumCircuit: Output XOR circuit.
str: Output value measured from qubit 2.
"""
qc = QuantumCircuit(3, 1)
qc.reset(range(2))
if inp1=='1':
qc.x(0)
if inp2=='1':
qc.x(1)
qc.barrier()
# this is where your program for quantum AND gate goes
qc.ccx(0,1,2)
qc.barrier()
qc.measure(2, 0) # output from qubit 2 is measured
# We'll run the program on a simulator
backend = Aer.get_backend('qasm_simulator')
# Since the output will be deterministic, we can use just a single shot to get it
job = backend.run(qc, shots=1, memory=True)
output = job.result().get_memory()[0]
return qc, output
## Test the function
for inp1 in ['0', '1']:
for inp2 in ['0', '1']:
qc, output = AND(inp1, inp2)
print('AND with inputs',inp1,inp2,'gives output',output)
display(qc.draw())
print('\n')
def NAND(inp1,inp2):
"""An NAND gate.
Parameters:
inpt1 (str): Input 1, encoded in qubit 0.
inpt2 (str): Input 2, encoded in qubit 1.
Returns:
QuantumCircuit: Output NAND circuit.
str: Output value measured from qubit 2.
"""
qc = QuantumCircuit(3, 1)
qc.reset(range(3))
if inp1=='1':
qc.x(0)
if inp2=='1':
qc.x(1)
qc.barrier()
# this is where your program for quantum NAND gate goes
qc.ccx(0,1,2)
if inp=='1':
qc.x(2)
qc.barrier()
qc.measure(2, 0) # output from qubit 2 is measured
# We'll run the program on a simulator
backend = Aer.get_backend('aer_simulator')
# Since the output will be deterministic, we can use just a single shot to get it
job = backend.run(qc,shots=1,memory=True)
output = job.result().get_memory()[0]
return qc, output
## Test the function
for inp1 in ['0', '1']:
for inp2 in ['0', '1']:
qc, output = NAND(inp1, inp2)
print('NAND with inputs',inp1,inp2,'gives output',output)
display(qc.draw())
print('\n')
def OR(inp1,inp2):
"""An OR gate.
Parameters:
inpt1 (str): Input 1, encoded in qubit 0.
inpt2 (str): Input 2, encoded in qubit 1.
Returns:
QuantumCircuit: Output XOR circuit.
str: Output value measured from qubit 2.
"""
qc = QuantumCircuit(3, 1)
qc.reset(range(3))
if inp1=='1':
qc.x(0)
if inp2=='1':
qc.x(1)
qc.barrier()
# this is where your program for quantum OR gate goes
qc.cx(0, 2)
qc.cx(1, 2)
qc.barrier()
qc.measure(2, 0) # output from qubit 2 is measured
# We'll run the program on a simulator
backend = Aer.get_backend('aer_simulator')
# Since the output will be deterministic, we can use just a single shot to get it
job = backend.run(qc,shots=1,memory=True)
output = job.result().get_memory()[0]
return qc, output
## Test the function
for inp1 in ['0', '1']:
for inp2 in ['0', '1']:
qc, output = OR(inp1, inp2)
print('OR with inputs',inp1,inp2,'gives output',output)
display(qc.draw())
print('\n')
from qiskit import IBMQ
#IBMQ.save_account("a68a35747d4eccd1d58f275e637909987c789ce5c0edd8a4f43014672bf0301b54b28b1b5f44ba8ff87500777429e1e4ceb79621a6ba248d6cca6bca0e233d23", overwrite=True)
IBMQ.load_account()
IBMQ.providers()
provider = IBMQ.get_provider('ibm-q')
provider.backends()
import qiskit.tools.jupyter
# run this cell
backend = provider.get_backend('ibmq_quito')
qc_and = QuantumCircuit(3)
qc_and.ccx(0,1,2)
print('AND gate')
display(qc_and.draw())
print('\n\nTranspiled AND gate with all the required connectivity')
qc_and.decompose().draw()
from qiskit.tools.monitor import job_monitor
# run the cell to define AND gate for real quantum system
def AND(inp1, inp2, backend, layout):
qc = QuantumCircuit(3, 1)
qc.reset(range(3))
if inp1=='1':
qc.x(0)
if inp2=='1':
qc.x(1)
qc.barrier()
qc.ccx(0, 1, 2)
qc.barrier()
qc.measure(2, 0)
qc_trans = transpile(qc, backend, initial_layout=layout, optimization_level=3)
job = backend.run(qc_trans, shots=8192)
print(job.job_id())
job_monitor(job)
output = job.result().get_counts()
return qc_trans, output
backend
layout = [0, 1, 2]
output_all = []
qc_trans_all = []
prob_all = []
worst = 1
best = 0
for input1 in ['0','1']:
for input2 in ['0','1']:
qc_trans, output = AND(input1, input2, backend, layout)
output_all.append(output)
qc_trans_all.append(qc_trans)
prob = output[str(int( input1=='1' and input2=='1' ))]/8192
prob_all.append(prob)
print('\nProbability of correct answer for inputs',input1,input2)
print('{:.2f}'.format(prob) )
print('---------------------------------')
worst = min(worst,prob)
best = max(best, prob)
print('')
print('\nThe highest of these probabilities was {:.2f}'.format(best))
print('The lowest of these probabilities was {:.2f}'.format(worst))
print('Transpiled AND gate circuit for ibmq_vigo with input 0 0')
print('\nThe circuit depth : {}'.format (qc_trans_all[0].depth()))
print('# of nonlocal gates : {}'.format (qc_trans_all[0].num_nonlocal_gates()))
print('Probability of correct answer : {:.2f}'.format(prob_all[0]) )
qc_trans_all[0].draw()
print('Transpiled AND gate circuit for ibmq_vigo with input 0 1')
print('\nThe circuit depth : {}'.format (qc_trans_all[1].depth()))
print('# of nonlocal gates : {}'.format (qc_trans_all[1].num_nonlocal_gates()))
print('Probability of correct answer : {:.2f}'.format(prob_all[1]) )
qc_trans_all[1].draw()
print('Transpiled AND gate circuit for ibmq_vigo with input 1 0')
print('\nThe circuit depth : {}'.format (qc_trans_all[2].depth()))
print('# of nonlocal gates : {}'.format (qc_trans_all[2].num_nonlocal_gates()))
print('Probability of correct answer : {:.2f}'.format(prob_all[2]) )
qc_trans_all[2].draw()
print('Transpiled AND gate circuit for ibmq_vigo with input 1 1')
print('\nThe circuit depth : {}'.format (qc_trans_all[3].depth()))
print('# of nonlocal gates : {}'.format (qc_trans_all[3].num_nonlocal_gates()))
print('Probability of correct answer : {:.2f}'.format(prob_all[3]) )
qc_trans_all[3].draw()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
# Necessary imports
import numpy as np
import matplotlib.pyplot as plt
from torch import Tensor
from torch.nn import Linear, CrossEntropyLoss, MSELoss
from torch.optim import LBFGS
from qiskit import QuantumCircuit
from qiskit.utils import algorithm_globals
from qiskit.circuit import Parameter
from qiskit.circuit.library import RealAmplitudes, ZZFeatureMap
from qiskit_machine_learning.neural_networks import SamplerQNN, EstimatorQNN
from qiskit_machine_learning.connectors import TorchConnector
# Set seed for random generators
algorithm_globals.random_seed = 42
# Generate random dataset
# Select dataset dimension (num_inputs) and size (num_samples)
num_inputs = 2
num_samples = 20
# Generate random input coordinates (X) and binary labels (y)
X = 2 * algorithm_globals.random.random([num_samples, num_inputs]) - 1
y01 = 1 * (np.sum(X, axis=1) >= 0) # in { 0, 1}, y01 will be used for SamplerQNN example
y = 2 * y01 - 1 # in {-1, +1}, y will be used for EstimatorQNN example
# Convert to torch Tensors
X_ = Tensor(X)
y01_ = Tensor(y01).reshape(len(y)).long()
y_ = Tensor(y).reshape(len(y), 1)
# Plot dataset
for x, y_target in zip(X, y):
if y_target == 1:
plt.plot(x[0], x[1], "bo")
else:
plt.plot(x[0], x[1], "go")
plt.plot([-1, 1], [1, -1], "--", color="black")
plt.show()
# Set up a circuit
feature_map = ZZFeatureMap(num_inputs)
ansatz = RealAmplitudes(num_inputs)
qc = QuantumCircuit(num_inputs)
qc.compose(feature_map, inplace=True)
qc.compose(ansatz, inplace=True)
qc.draw("mpl")
# Setup QNN
qnn1 = EstimatorQNN(
circuit=qc, input_params=feature_map.parameters, weight_params=ansatz.parameters
)
# Set up PyTorch module
# Note: If we don't explicitly declare the initial weights
# they are chosen uniformly at random from [-1, 1].
initial_weights = 0.1 * (2 * algorithm_globals.random.random(qnn1.num_weights) - 1)
model1 = TorchConnector(qnn1, initial_weights=initial_weights)
print("Initial weights: ", initial_weights)
# Test with a single input
model1(X_[0, :])
# Define optimizer and loss
optimizer = LBFGS(model1.parameters())
f_loss = MSELoss(reduction="sum")
# Start training
model1.train() # set model to training mode
# Note from (https://pytorch.org/docs/stable/optim.html):
# Some optimization algorithms such as LBFGS need to
# reevaluate the function multiple times, so you have to
# pass in a closure that allows them to recompute your model.
# The closure should clear the gradients, compute the loss,
# and return it.
def closure():
optimizer.zero_grad() # Initialize/clear gradients
loss = f_loss(model1(X_), y_) # Evaluate loss function
loss.backward() # Backward pass
print(loss.item()) # Print loss
return loss
# Run optimizer step4
optimizer.step(closure)
# Evaluate model and compute accuracy
y_predict = []
for x, y_target in zip(X, y):
output = model1(Tensor(x))
y_predict += [np.sign(output.detach().numpy())[0]]
print("Accuracy:", sum(y_predict == y) / len(y))
# Plot results
# red == wrongly classified
for x, y_target, y_p in zip(X, y, y_predict):
if y_target == 1:
plt.plot(x[0], x[1], "bo")
else:
plt.plot(x[0], x[1], "go")
if y_target != y_p:
plt.scatter(x[0], x[1], s=200, facecolors="none", edgecolors="r", linewidths=2)
plt.plot([-1, 1], [1, -1], "--", color="black")
plt.show()
# Define feature map and ansatz
feature_map = ZZFeatureMap(num_inputs)
ansatz = RealAmplitudes(num_inputs, entanglement="linear", reps=1)
# Define quantum circuit of num_qubits = input dim
# Append feature map and ansatz
qc = QuantumCircuit(num_inputs)
qc.compose(feature_map, inplace=True)
qc.compose(ansatz, inplace=True)
# Define SamplerQNN and initial setup
parity = lambda x: "{:b}".format(x).count("1") % 2 # optional interpret function
output_shape = 2 # parity = 0, 1
qnn2 = SamplerQNN(
circuit=qc,
input_params=feature_map.parameters,
weight_params=ansatz.parameters,
interpret=parity,
output_shape=output_shape,
)
# Set up PyTorch module
# Reminder: If we don't explicitly declare the initial weights
# they are chosen uniformly at random from [-1, 1].
initial_weights = 0.1 * (2 * algorithm_globals.random.random(qnn2.num_weights) - 1)
print("Initial weights: ", initial_weights)
model2 = TorchConnector(qnn2, initial_weights)
# Define model, optimizer, and loss
optimizer = LBFGS(model2.parameters())
f_loss = CrossEntropyLoss() # Our output will be in the [0,1] range
# Start training
model2.train()
# Define LBFGS closure method (explained in previous section)
def closure():
optimizer.zero_grad(set_to_none=True) # Initialize gradient
loss = f_loss(model2(X_), y01_) # Calculate loss
loss.backward() # Backward pass
print(loss.item()) # Print loss
return loss
# Run optimizer (LBFGS requires closure)
optimizer.step(closure);
# Evaluate model and compute accuracy
y_predict = []
for x in X:
output = model2(Tensor(x))
y_predict += [np.argmax(output.detach().numpy())]
print("Accuracy:", sum(y_predict == y01) / len(y01))
# plot results
# red == wrongly classified
for x, y_target, y_ in zip(X, y01, y_predict):
if y_target == 1:
plt.plot(x[0], x[1], "bo")
else:
plt.plot(x[0], x[1], "go")
if y_target != y_:
plt.scatter(x[0], x[1], s=200, facecolors="none", edgecolors="r", linewidths=2)
plt.plot([-1, 1], [1, -1], "--", color="black")
plt.show()
# Generate random dataset
num_samples = 20
eps = 0.2
lb, ub = -np.pi, np.pi
f = lambda x: np.sin(x)
X = (ub - lb) * algorithm_globals.random.random([num_samples, 1]) + lb
y = f(X) + eps * (2 * algorithm_globals.random.random([num_samples, 1]) - 1)
plt.plot(np.linspace(lb, ub), f(np.linspace(lb, ub)), "r--")
plt.plot(X, y, "bo")
plt.show()
# Construct simple feature map
param_x = Parameter("x")
feature_map = QuantumCircuit(1, name="fm")
feature_map.ry(param_x, 0)
# Construct simple feature map
param_y = Parameter("y")
ansatz = QuantumCircuit(1, name="vf")
ansatz.ry(param_y, 0)
qc = QuantumCircuit(1)
qc.compose(feature_map, inplace=True)
qc.compose(ansatz, inplace=True)
# Construct QNN
qnn3 = EstimatorQNN(circuit=qc, input_params=[param_x], weight_params=[param_y])
# Set up PyTorch module
# Reminder: If we don't explicitly declare the initial weights
# they are chosen uniformly at random from [-1, 1].
initial_weights = 0.1 * (2 * algorithm_globals.random.random(qnn3.num_weights) - 1)
model3 = TorchConnector(qnn3, initial_weights)
# Define optimizer and loss function
optimizer = LBFGS(model3.parameters())
f_loss = MSELoss(reduction="sum")
# Start training
model3.train() # set model to training mode
# Define objective function
def closure():
optimizer.zero_grad(set_to_none=True) # Initialize gradient
loss = f_loss(model3(Tensor(X)), Tensor(y)) # Compute batch loss
loss.backward() # Backward pass
print(loss.item()) # Print loss
return loss
# Run optimizer
optimizer.step(closure)
# Plot target function
plt.plot(np.linspace(lb, ub), f(np.linspace(lb, ub)), "r--")
# Plot data
plt.plot(X, y, "bo")
# Plot fitted line
y_ = []
for x in np.linspace(lb, ub):
output = model3(Tensor([x]))
y_ += [output.detach().numpy()[0]]
plt.plot(np.linspace(lb, ub), y_, "g-")
plt.show()
# Additional torch-related imports
import torch
from torch import cat, no_grad, manual_seed
from torch.utils.data import DataLoader
from torchvision import datasets, transforms
import torch.optim as optim
from torch.nn import (
Module,
Conv2d,
Linear,
Dropout2d,
NLLLoss,
MaxPool2d,
Flatten,
Sequential,
ReLU,
)
import torch.nn.functional as F
# Train Dataset
# -------------
# Set train shuffle seed (for reproducibility)
manual_seed(42)
batch_size = 1
n_samples = 100 # We will concentrate on the first 100 samples
# Use pre-defined torchvision function to load MNIST train data
X_train = datasets.MNIST(
root="./data", train=True, download=True, transform=transforms.Compose([transforms.ToTensor()])
)
# Filter out labels (originally 0-9), leaving only labels 0 and 1
idx = np.append(
np.where(X_train.targets == 0)[0][:n_samples], np.where(X_train.targets == 1)[0][:n_samples]
)
X_train.data = X_train.data[idx]
X_train.targets = X_train.targets[idx]
# Define torch dataloader with filtered data
train_loader = DataLoader(X_train, batch_size=batch_size, shuffle=True)
n_samples_show = 6
data_iter = iter(train_loader)
fig, axes = plt.subplots(nrows=1, ncols=n_samples_show, figsize=(10, 3))
while n_samples_show > 0:
images, targets = data_iter.__next__()
axes[n_samples_show - 1].imshow(images[0, 0].numpy().squeeze(), cmap="gray")
axes[n_samples_show - 1].set_xticks([])
axes[n_samples_show - 1].set_yticks([])
axes[n_samples_show - 1].set_title("Labeled: {}".format(targets[0].item()))
n_samples_show -= 1
# Test Dataset
# -------------
# Set test shuffle seed (for reproducibility)
# manual_seed(5)
n_samples = 50
# Use pre-defined torchvision function to load MNIST test data
X_test = datasets.MNIST(
root="./data", train=False, download=True, transform=transforms.Compose([transforms.ToTensor()])
)
# Filter out labels (originally 0-9), leaving only labels 0 and 1
idx = np.append(
np.where(X_test.targets == 0)[0][:n_samples], np.where(X_test.targets == 1)[0][:n_samples]
)
X_test.data = X_test.data[idx]
X_test.targets = X_test.targets[idx]
# Define torch dataloader with filtered data
test_loader = DataLoader(X_test, batch_size=batch_size, shuffle=True)
# Define and create QNN
def create_qnn():
feature_map = ZZFeatureMap(2)
ansatz = RealAmplitudes(2, reps=1)
qc = QuantumCircuit(2)
qc.compose(feature_map, inplace=True)
qc.compose(ansatz, inplace=True)
# REMEMBER TO SET input_gradients=True FOR ENABLING HYBRID GRADIENT BACKPROP
qnn = EstimatorQNN(
circuit=qc,
input_params=feature_map.parameters,
weight_params=ansatz.parameters,
input_gradients=True,
)
return qnn
qnn4 = create_qnn()
# Define torch NN module
class Net(Module):
def __init__(self, qnn):
super().__init__()
self.conv1 = Conv2d(1, 2, kernel_size=5)
self.conv2 = Conv2d(2, 16, kernel_size=5)
self.dropout = Dropout2d()
self.fc1 = Linear(256, 64)
self.fc2 = Linear(64, 2) # 2-dimensional input to QNN
self.qnn = TorchConnector(qnn) # Apply torch connector, weights chosen
# uniformly at random from interval [-1,1].
self.fc3 = Linear(1, 1) # 1-dimensional output from QNN
def forward(self, x):
x = F.relu(self.conv1(x))
x = F.max_pool2d(x, 2)
x = F.relu(self.conv2(x))
x = F.max_pool2d(x, 2)
x = self.dropout(x)
x = x.view(x.shape[0], -1)
x = F.relu(self.fc1(x))
x = self.fc2(x)
x = self.qnn(x) # apply QNN
x = self.fc3(x)
return cat((x, 1 - x), -1)
model4 = Net(qnn4)
# Define model, optimizer, and loss function
optimizer = optim.Adam(model4.parameters(), lr=0.001)
loss_func = NLLLoss()
# Start training
epochs = 10 # Set number of epochs
loss_list = [] # Store loss history
model4.train() # Set model to training mode
for epoch in range(epochs):
total_loss = []
for batch_idx, (data, target) in enumerate(train_loader):
optimizer.zero_grad(set_to_none=True) # Initialize gradient
output = model4(data) # Forward pass
loss = loss_func(output, target) # Calculate loss
loss.backward() # Backward pass
optimizer.step() # Optimize weights
total_loss.append(loss.item()) # Store loss
loss_list.append(sum(total_loss) / len(total_loss))
print("Training [{:.0f}%]\tLoss: {:.4f}".format(100.0 * (epoch + 1) / epochs, loss_list[-1]))
# Plot loss convergence
plt.plot(loss_list)
plt.title("Hybrid NN Training Convergence")
plt.xlabel("Training Iterations")
plt.ylabel("Neg. Log Likelihood Loss")
plt.show()
torch.save(model4.state_dict(), "model4.pt")
qnn5 = create_qnn()
model5 = Net(qnn5)
model5.load_state_dict(torch.load("model4.pt"))
model5.eval() # set model to evaluation mode
with no_grad():
correct = 0
for batch_idx, (data, target) in enumerate(test_loader):
output = model5(data)
if len(output.shape) == 1:
output = output.reshape(1, *output.shape)
pred = output.argmax(dim=1, keepdim=True)
correct += pred.eq(target.view_as(pred)).sum().item()
loss = loss_func(output, target)
total_loss.append(loss.item())
print(
"Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%".format(
sum(total_loss) / len(total_loss), correct / len(test_loader) / batch_size * 100
)
)
# Plot predicted labels
n_samples_show = 6
count = 0
fig, axes = plt.subplots(nrows=1, ncols=n_samples_show, figsize=(10, 3))
model5.eval()
with no_grad():
for batch_idx, (data, target) in enumerate(test_loader):
if count == n_samples_show:
break
output = model5(data[0:1])
if len(output.shape) == 1:
output = output.reshape(1, *output.shape)
pred = output.argmax(dim=1, keepdim=True)
axes[count].imshow(data[0].numpy().squeeze(), cmap="gray")
axes[count].set_xticks([])
axes[count].set_yticks([])
axes[count].set_title("Predicted {}".format(pred.item()))
count += 1
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
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/nickk124/quantumsearch
|
nickk124
|
import sys
sys.path.insert(0, 'qrw/')
from qrw import QRWsearch
%config InlineBackend.figure_format = 'svg' # Makes the images look nice
search_circuit = QRWsearch(2,0)
# display the matrix the shift operator
search_circuit.S(display_matrix=True);
# display the matrix the shift operator
search_circuit.C(display_matrix=True);
# display the matrix the U
search_circuit.Uprime(display_matrix=True);
# display the operator U
search_circuit.Uprime()
search_circuit.draw_circuit()
search_circuit.plot_states_hist()
import sys
sys.path.insert(0, 'quantum_decomp/')
import quantum_decomp as qd
gates = qd.matrix_to_gates(search_circuit.Uprime().data)
gates
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
n_steps=1
q = QuantumRegister (3, name='q') #3 qubit register
c = ClassicalRegister (3, name='c') #3 bit classical register
circ = QuantumCircuit (q,c) #Main circuit
for i in range(1):
circ.h(0)
circ.ccx(0, 2, 1)
circ.ccx(1, 2, 0)
circ.x(0)
circ.ccx(0, 1, 2)
circ.x(0)
circ.x(2)
circ.ccx(1, 2, 0)
circ.ccx(0, 2, 1)
circ.x(1)
circ.ccx(1, 2, 0)
circ.x(1)
circ.x(2)
circ.ccx(1, 2, 0)
circ.x(0)
circ.ccx(0, 1, 2)
circ.x(0)
circ.x(2)
circ.ccx(1, 2, 0)
circ.x(2)
circ.ccx(0, 2, 1)
circ.ccx(1, 2, 0)
circ.x(0)
circ.ccx(0, 1, 2)
circ.x(0)
circ.x(1)
circ.ccx(1, 2, 0)
circ.x(1)
circ.ccx(0, 2, 1)
circ.ccx(1, 2, 0)
circ.barrier()
circ.measure ([q[0],q[1],q[2]], [c[0],c[1],c[2]])
circ.draw('mpl')
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit.visualization import plot_histogram, plot_state_city
from qiskit import execute, Aer
n_steps=4
q = QuantumRegister (3, name='q') #3 qubit register
c = ClassicalRegister (3, name='c') #3 bit classical register
circ = QuantumCircuit (q,c) #Main circuit
for i in range(n_steps):
circ.h(q[0]) # coin
circ.ccx(q[0],q[1],q[2]) # Toffoli
circ.cx (q[0], q[1]) # CNOT
circ.x(q[0])
circ.x(q[1])
circ.ccx(q[0], q[1], q[2])
circ.x(q[1])
circ.cx(q[0],q[1])
circ.barrier()
circ.measure([q[0],q[1],q[2]], [c[0],c[1],c[2]])
circ.draw('mpl')
backend = Aer.get_backend('qasm_simulator')
shots = 1024 # number of times circuit is run, for sampling
results = execute(circ, backend=backend, shots=shots).result()
answer = results.get_counts()
plot_histogram(answer)
|
https://github.com/qiskit-community/community.qiskit.org
|
qiskit-community
|
import math
# importing Qiskit
from qiskit import Aer, IBMQ
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute
from qiskit.providers.ibmq import least_busy
from qiskit.tools.monitor import job_monitor
from qiskit.tools.visualization import plot_histogram
IBMQ.load_account()
def input_state(circ, q, n):
"""n-qubit input state for QFT that produces output 1."""
for j in range(n):
circ.h(q[j])
circ.u1(-math.pi/float(2**(j)), q[j])
def qft(circ, q, n):
"""n-qubit QFT on q in circ."""
for j in range(n):
circ.h(q[j])
for k in range(j+1,n):
circ.cu1(math.pi/float(2**(k-j)), q[k], q[j])
circ.barrier()
q = QuantumRegister(3, 'x')
c = ClassicalRegister(3, 'c')
qft3 = QuantumCircuit(q, c)
# first, prepare the state that should return 001 and draw that circuit
input_state(qft3, q, 3)
qft3.draw(output='mpl')
# next, do a qft on the prepared state and draw the entire circuit
qft(qft3, q, 3)
for i in range(3):
qft3.measure(q[i], c[i])
qft3.draw(output='mpl')
# run on local simulator
backend = Aer.get_backend("qasm_simulator")
simulate = execute(qft3, backend=backend, shots=1024).result()
simulate.get_counts()
# Use the IBMQ Vigo device with 5 qubits
IBMQ.get_provider(hub='ibm-q')
backend = provider.get_backend('ibmq_vigo')
shots = 2048
job_exp = execute(qft3, backend=backend, shots=shots)
job_monitor(job_exp)
results = job_exp.result()
plot_histogram(results.get_counts())
import qiskit
qiskit.__qiskit_version__
|
https://github.com/PayalSolanki2906/Quantum_algorithms_using_Qiskit
|
PayalSolanki2906
|
from qiskit import QuantumCircuit
import numpy as np
from qiskit import QuantumCircuit, assemble, Aer
def deutsch_problem(seed=None):
"""Returns a circuit that carries out the function
from Deutsch's problem.
Args:
seed (int): If set, then returned circuit will
always be the same for the same seed.
Returns: QuantumCircuit
"""
np.random.seed(seed)
problem = QuantumCircuit(2)
if np.random.randint(2):
print("Function is balanced.")
problem.cx(0, 1)
else:
print("Function is constant.")
if np.random.randint(2):
problem.x(1)
return problem
def deutsch(problem):
"""Implements Deutsch's algorithm.
Args:
function (QuantumCircuit): Deutsch function to solve.
Must be a 2-qubit circuit, and either balanced,
or constant.
Returns:
bool: True if the circuit is balanced, otherwise False.
"""
qc=QuantumCircuit(2,1)
qc.x(1)
qc.h([0,1])
qc.draw()
qc.append(problem.to_gate(label='f'),[0,1])
qc.h(0)
qc.measure(0,0)
qc = qc.decompose('f')
display(qc.draw())
sim = Aer.get_backend('aer_simulator')
state = sim.run(qc).result().get_counts() # Execute the circuit and get the count
state=list(state.keys())[0] ## fetch the bit from the Dictionary
if state=='1':
return('balanced')
if state=='0':
return('constant')
problem=deutsch_problem()
print(deutsch(problem))
|
https://github.com/Z-928/Bugs4Q
|
Z-928
|
#change
from qiskit import QuantumProgram
import Qconfig
qp = QuantumProgram()
qp.set_api(Qconfig.APItoken, Qconfig.config['url'])
qr = qp.create_quantum_register('qr', 16) #if i create only 1, the program doesn't run
cr = qp.create_classical_register('cr', 16)
qc = qp.create_circuit('qc', [qr], [cr])
def pad_QId(circuit,N,qr):
for ii in range(N):
circuit.barrier(qr)
circuit.iden(qr)
return circuit
qc.x(qr[0])
qc = pad_QId(qc, 1000, qr[0])
qc.measure(qr[0], cr[0])
result = qp.execute('qc', timeout = 1000, backend = 'ibmqx5', shots = 8192, max_credits = 5)
result.get_counts('qc')
#to
from qiskit import QuantumCircuit,QuantumRegister,ClassicalRegister
from qiskit import *
from qiskit.providers.aer import QasmSimulator
#qp.set_api(Qconfig.APItoken, Qconfig.config['url'])
q = QuantumRegister(16) #if i create only 1, the program doesn't run
c = ClassicalRegister(16)
qc = QuantumCircuit(q, c)
def pad_QId(circuit,N,q):
for ii in range(N):
circuit.barrier(q)
circuit.id(q)
return circuit
qc.x(q[0])
qc = pad_QId(qc, 1000, q[0])
qc.measure(q[0], c[0])
result = execute(qc, timeout = 1000, backend=QasmSimulator(), shots = 8192, max_credits = 5)
counts = result.result().get_counts(qc)
print(counts)
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test the SabreLayout pass"""
import unittest
from qiskit import QuantumRegister, QuantumCircuit
from qiskit.transpiler import CouplingMap
from qiskit.transpiler.passes import SabreLayout
from qiskit.transpiler.exceptions import TranspilerError
from qiskit.converters import circuit_to_dag
from qiskit.test import QiskitTestCase
from qiskit.compiler.transpiler import transpile
from qiskit.providers.fake_provider import FakeAlmaden, FakeAlmadenV2
from qiskit.providers.fake_provider import FakeKolkata
from qiskit.providers.fake_provider import FakeMontreal
class TestSabreLayout(QiskitTestCase):
"""Tests the SabreLayout pass"""
def setUp(self):
super().setUp()
self.cmap20 = FakeAlmaden().configuration().coupling_map
def test_5q_circuit_20q_coupling(self):
"""Test finds layout for 5q circuit on 20q device."""
# ┌───┐
# q_0: ──■───────┤ X ├───────────────
# │ └─┬─┘┌───┐
# q_1: ──┼────■────┼──┤ X ├───────■──
# ┌─┴─┐ │ │ ├───┤┌───┐┌─┴─┐
# q_2: ┤ X ├──┼────┼──┤ X ├┤ X ├┤ X ├
# └───┘┌─┴─┐ │ └───┘└─┬─┘└───┘
# q_3: ─────┤ X ├──■─────────┼───────
# └───┘ │
# q_4: ──────────────────────■───────
qr = QuantumRegister(5, "q")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[2])
circuit.cx(qr[1], qr[3])
circuit.cx(qr[3], qr[0])
circuit.x(qr[2])
circuit.cx(qr[4], qr[2])
circuit.x(qr[1])
circuit.cx(qr[1], qr[2])
dag = circuit_to_dag(circuit)
pass_ = SabreLayout(CouplingMap(self.cmap20), seed=0, swap_trials=32, layout_trials=32)
pass_.run(dag)
layout = pass_.property_set["layout"]
self.assertEqual([layout[q] for q in circuit.qubits], [18, 11, 13, 12, 14])
def test_6q_circuit_20q_coupling(self):
"""Test finds layout for 6q circuit on 20q device."""
# ┌───┐┌───┐┌───┐┌───┐┌───┐
# q0_0: ┤ X ├┤ X ├┤ X ├┤ X ├┤ X ├
# └─┬─┘└─┬─┘└─┬─┘└─┬─┘└─┬─┘
# q0_1: ──┼────■────┼────┼────┼──
# │ ┌───┐ │ │ │
# q0_2: ──┼──┤ X ├──┼────■────┼──
# │ └───┘ │ │
# q1_0: ──■─────────┼─────────┼──
# ┌───┐ │ │
# q1_1: ─────┤ X ├──┼─────────■──
# └───┘ │
# q1_2: ────────────■────────────
qr0 = QuantumRegister(3, "q0")
qr1 = QuantumRegister(3, "q1")
circuit = QuantumCircuit(qr0, qr1)
circuit.cx(qr1[0], qr0[0])
circuit.cx(qr0[1], qr0[0])
circuit.cx(qr1[2], qr0[0])
circuit.x(qr0[2])
circuit.cx(qr0[2], qr0[0])
circuit.x(qr1[1])
circuit.cx(qr1[1], qr0[0])
dag = circuit_to_dag(circuit)
pass_ = SabreLayout(CouplingMap(self.cmap20), seed=0, swap_trials=32, layout_trials=32)
pass_.run(dag)
layout = pass_.property_set["layout"]
self.assertEqual([layout[q] for q in circuit.qubits], [7, 8, 12, 6, 11, 13])
def test_6q_circuit_20q_coupling_with_target(self):
"""Test finds layout for 6q circuit on 20q device."""
# ┌───┐┌───┐┌───┐┌───┐┌───┐
# q0_0: ┤ X ├┤ X ├┤ X ├┤ X ├┤ X ├
# └─┬─┘└─┬─┘└─┬─┘└─┬─┘└─┬─┘
# q0_1: ──┼────■────┼────┼────┼──
# │ ┌───┐ │ │ │
# q0_2: ──┼──┤ X ├──┼────■────┼──
# │ └───┘ │ │
# q1_0: ──■─────────┼─────────┼──
# ┌───┐ │ │
# q1_1: ─────┤ X ├──┼─────────■──
# └───┘ │
# q1_2: ────────────■────────────
qr0 = QuantumRegister(3, "q0")
qr1 = QuantumRegister(3, "q1")
circuit = QuantumCircuit(qr0, qr1)
circuit.cx(qr1[0], qr0[0])
circuit.cx(qr0[1], qr0[0])
circuit.cx(qr1[2], qr0[0])
circuit.x(qr0[2])
circuit.cx(qr0[2], qr0[0])
circuit.x(qr1[1])
circuit.cx(qr1[1], qr0[0])
dag = circuit_to_dag(circuit)
target = FakeAlmadenV2().target
pass_ = SabreLayout(target, seed=0, swap_trials=32, layout_trials=32)
pass_.run(dag)
layout = pass_.property_set["layout"]
self.assertEqual([layout[q] for q in circuit.qubits], [7, 8, 12, 6, 11, 13])
def test_layout_with_classical_bits(self):
"""Test sabre layout with classical bits recreate from issue #8635."""
qc = QuantumCircuit.from_qasm_str(
"""
OPENQASM 2.0;
include "qelib1.inc";
qreg q4833[1];
qreg q4834[6];
qreg q4835[7];
creg c982[2];
creg c983[2];
creg c984[2];
rzz(0) q4833[0],q4834[4];
cu(0,-6.1035156e-05,0,1e-05) q4834[1],q4835[2];
swap q4834[0],q4834[2];
cu(-1.1920929e-07,0,-0.33333333,0) q4833[0],q4834[2];
ccx q4835[2],q4834[5],q4835[4];
measure q4835[4] -> c984[0];
ccx q4835[2],q4835[5],q4833[0];
measure q4835[5] -> c984[1];
measure q4834[0] -> c982[1];
u(10*pi,0,1.9) q4834[5];
measure q4834[3] -> c984[1];
measure q4835[0] -> c982[0];
rz(0) q4835[1];
"""
)
res = transpile(qc, FakeKolkata(), layout_method="sabre", seed_transpiler=1234)
self.assertIsInstance(res, QuantumCircuit)
layout = res._layout.initial_layout
self.assertEqual(
[layout[q] for q in qc.qubits], [13, 10, 11, 12, 17, 14, 22, 26, 5, 16, 25, 19, 7, 8]
)
# pylint: disable=line-too-long
def test_layout_many_search_trials(self):
"""Test recreate failure from randomized testing that overflowed."""
qc = QuantumCircuit.from_qasm_str(
"""
OPENQASM 2.0;
include "qelib1.inc";
qreg q18585[14];
creg c1423[5];
creg c1424[4];
creg c1425[3];
barrier q18585[4],q18585[5],q18585[12],q18585[1];
cz q18585[11],q18585[3];
cswap q18585[8],q18585[10],q18585[6];
u(-2.00001,6.1035156e-05,-1.9) q18585[2];
barrier q18585[3],q18585[6],q18585[5],q18585[8],q18585[10],q18585[9],q18585[11],q18585[2],q18585[12],q18585[7],q18585[13],q18585[4],q18585[0],q18585[1];
cp(0) q18585[2],q18585[4];
cu(-0.99999,0,0,0) q18585[7],q18585[1];
cu(0,0,0,2.1507119) q18585[6],q18585[3];
barrier q18585[13],q18585[0],q18585[12],q18585[3],q18585[2],q18585[10];
ry(-1.1044662) q18585[13];
barrier q18585[13];
id q18585[12];
barrier q18585[12],q18585[6];
cu(-1.9,1.9,-1.5,0) q18585[10],q18585[0];
barrier q18585[13];
id q18585[8];
barrier q18585[12];
barrier q18585[12],q18585[1],q18585[9];
sdg q18585[2];
rz(-10*pi) q18585[6];
u(0,27.566433,1.9) q18585[1];
barrier q18585[12],q18585[11],q18585[9],q18585[4],q18585[7],q18585[0],q18585[13],q18585[3];
cu(-0.99999,-5.9604645e-08,-0.5,2.00001) q18585[3],q18585[13];
rx(-5.9604645e-08) q18585[7];
p(1.1) q18585[13];
barrier q18585[12],q18585[13],q18585[10],q18585[9],q18585[7],q18585[4];
z q18585[10];
measure q18585[7] -> c1423[2];
barrier q18585[0],q18585[3],q18585[7],q18585[4],q18585[1],q18585[8],q18585[6],q18585[11],q18585[5];
barrier q18585[5],q18585[2],q18585[8],q18585[3],q18585[6];
"""
)
res = transpile(
qc,
FakeMontreal(),
layout_method="sabre",
routing_method="stochastic",
seed_transpiler=12345,
)
self.assertIsInstance(res, QuantumCircuit)
layout = res._layout.initial_layout
self.assertEqual(
[layout[q] for q in qc.qubits], [7, 19, 14, 18, 10, 6, 12, 16, 13, 20, 15, 21, 1, 17]
)
class TestDisjointDeviceSabreLayout(QiskitTestCase):
"""Test SabreLayout with a disjoint coupling map."""
def setUp(self):
super().setUp()
self.dual_grid_cmap = CouplingMap(
[[0, 1], [0, 2], [1, 3], [2, 3], [4, 5], [4, 6], [5, 7], [5, 8]]
)
def test_dual_ghz(self):
"""Test a basic example with 2 circuit components and 2 cmap components."""
qc = QuantumCircuit(8, name="double dhz")
qc.h(0)
qc.cz(0, 1)
qc.cz(0, 2)
qc.h(3)
qc.cx(3, 4)
qc.cx(3, 5)
qc.cx(3, 6)
qc.cx(3, 7)
layout_routing_pass = SabreLayout(
self.dual_grid_cmap, seed=123456, swap_trials=1, layout_trials=1
)
layout_routing_pass(qc)
layout = layout_routing_pass.property_set["layout"]
self.assertEqual([layout[q] for q in qc.qubits], [3, 1, 2, 5, 4, 6, 7, 8])
def test_dual_ghz_with_wide_barrier(self):
"""Test a basic example with 2 circuit components and 2 cmap components."""
qc = QuantumCircuit(8, name="double dhz")
qc.h(0)
qc.cz(0, 1)
qc.cz(0, 2)
qc.h(3)
qc.cx(3, 4)
qc.cx(3, 5)
qc.cx(3, 6)
qc.cx(3, 7)
qc.measure_all()
layout_routing_pass = SabreLayout(
self.dual_grid_cmap, seed=123456, swap_trials=1, layout_trials=1
)
layout_routing_pass(qc)
layout = layout_routing_pass.property_set["layout"]
self.assertEqual([layout[q] for q in qc.qubits], [3, 1, 2, 5, 4, 6, 7, 8])
def test_dual_ghz_with_intermediate_barriers(self):
"""Test dual ghz circuit with intermediate barriers local to each componennt."""
qc = QuantumCircuit(8, name="double dhz")
qc.h(0)
qc.cz(0, 1)
qc.cz(0, 2)
qc.barrier(0, 1, 2)
qc.h(3)
qc.cx(3, 4)
qc.cx(3, 5)
qc.barrier(4, 5, 6)
qc.cx(3, 6)
qc.cx(3, 7)
qc.measure_all()
layout_routing_pass = SabreLayout(
self.dual_grid_cmap, seed=123456, swap_trials=1, layout_trials=1
)
layout_routing_pass(qc)
layout = layout_routing_pass.property_set["layout"]
self.assertEqual([layout[q] for q in qc.qubits], [3, 1, 2, 5, 4, 6, 7, 8])
def test_dual_ghz_with_intermediate_spanning_barriers(self):
"""Test dual ghz circuit with barrier in the middle across components."""
qc = QuantumCircuit(8, name="double dhz")
qc.h(0)
qc.cz(0, 1)
qc.cz(0, 2)
qc.barrier(0, 1, 2, 4, 5)
qc.h(3)
qc.cx(3, 4)
qc.cx(3, 5)
qc.cx(3, 6)
qc.cx(3, 7)
qc.measure_all()
layout_routing_pass = SabreLayout(
self.dual_grid_cmap, seed=123456, swap_trials=1, layout_trials=1
)
layout_routing_pass(qc)
layout = layout_routing_pass.property_set["layout"]
self.assertEqual([layout[q] for q in qc.qubits], [3, 1, 2, 5, 4, 6, 7, 8])
def test_too_large_components(self):
"""Assert trying to run a circuit with too large a connected component raises."""
qc = QuantumCircuit(8)
qc.h(0)
for i in range(1, 6):
qc.cx(0, i)
qc.h(7)
qc.cx(7, 6)
layout_routing_pass = SabreLayout(
self.dual_grid_cmap, seed=123456, swap_trials=1, layout_trials=1
)
with self.assertRaises(TranspilerError):
layout_routing_pass(qc)
if __name__ == "__main__":
unittest.main()
|
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
|
mmetcalf14
|
from qiskit import *
from oracle_generation import generate_oracle
get_bin = lambda x, n: format(x, 'b').zfill(n)
def gen_circuits(min,max,size):
circuits = []
secrets = []
ORACLE_SIZE = size
for i in range(min,max+1):
cur_str = get_bin(i,ORACLE_SIZE-1)
(circuit, secret) = generate_oracle(ORACLE_SIZE,False,3,cur_str)
circuits.append(circuit)
secrets.append(secret)
return (circuits, secrets)
|
https://github.com/kurtchahn/QiskitPrx
|
kurtchahn
|
import qiskit as qk
import qiskit_aer as qaer
import numpy as np
import math
sSimulator = qaer.Aer.backends(name="statevector_simulator")[0]
mSimulator = qaer.Aer.backends(name="qasm_simulator")[0]
|
https://github.com/TheGupta2012/QPE-Algorithms
|
TheGupta2012
|
from qiskit import QuantumCircuit, execute, transpile, Aer
from qiskit.extensions import UnitaryGate,Initialize
from qiskit.quantum_info import Statevector
from qiskit.tools.visualization import plot_bloch_vector
from qiskit.tools.visualization import plot_histogram,plot_bloch_multivector
import numpy as np
from time import sleep
import sys
sys.path.append("..")
import os
from scipy.stats import unitary_group
import matplotlib.pyplot as plt
%matplotlib inline
os.makedirs(name = "Plots/2-qubit/",exist_ok=True)
from Modules.vanilla_qpe import QPE
from Modules.iterative_qpe import IQPE
from Modules.normal_SPEA import SPEA
from Modules.kitaev_qpe import KQPE
# x gate
u1 = QuantumCircuit(2)
u1.cp(2*np.pi*(1/7),0,1)
u1.draw('mpl')
# x gate
u2 = QuantumCircuit(2)
u2.z(0)
u2.x(1)
u2.draw('mpl')
os.makedirs(name = "Plots/2-qubit/phase_gate/",exist_ok=True)
phase_path = "Plots/2-qubit/phase_gate/"
backend = Aer.get_backend('qasm_simulator')
estimates = []
for precision in range(1,9):
qpe = QPE(precision=precision,unitary = u1)
qpe_circ = qpe.get_QPE(show = False)
qc = QuantumCircuit(precision+2,precision)
qc.x(precision)
qc.x(precision+1)
qc.append(qpe_circ, qargs = list(range(precision+2)))
qc.measure(list(range(precision)),list(range(precision)))
# display(qc.draw('mpl'))
counts = execute(qc,backend=backend,shots = 2**10).result().get_counts()
m = -1
for i,j in counts.items():
if j > m:
m = j
phase = i
factor = 0.5
ans = 0.0
for i in range(precision):
ans+= int(phase[i])*factor
factor/=2
estimates.append(ans)
plt.title("Phase by basic QPE for the unitary CP(1/7)",fontsize = 16)
plt.plot([i for i in range(1,9)],estimates,alpha = 0.5,color = 'g',linewidth = 2,marker = 'o',label = 'Estimates')
plt.plot([0,8],[0.1428,0.1428],color = 'black')
plt.xlabel('Precision')
plt.ylabel('Estimates')
plt.grid()
plt.legend()
plt.savefig(phase_path+"basic_qpe.JPG",dpi = 200)
estimates = []
for precision in range(1,9):
qpe = IQPE(precision=precision,unitary = u1,unknown=True)
qc = QuantumCircuit(1+2,precision)
qc.x(1)
qc.x(2)
phase = qpe.get_circuit_phase(qc, qubits = [1,2], ancilla = 0,clbits = list(range(precision)),show = False)
# display(qc.draw('mpl'))
estimates.append(phase[1])
plt.title("Phase by iterative QPE for the unitary CP(1/7)",fontsize = 16)
plt.plot([i for i in range(1,9)],estimates,color = 'b',alpha = 0.5,linewidth = 2,marker = 'o',label = 'Estimates')
plt.plot([0,8],[0.1428,0.1428],color = 'black')
plt.xlabel('Precision')
plt.ylabel('Estimates')
plt.grid()
plt.legend()
plt.savefig(phase_path+"iqpe.JPG",dpi = 200)
backend = Aer.get_backend('qasm_simulator')
estimates = []
for _ in range(100):
qpe = SPEA(resolution = 30,unitary = u1, error =4,max_iters=12)
result = qpe.get_eigen_pair(progress = False, backend = backend)
print("Result : ",result)
estimates.append(result['theta'])
plt.figure(figsize = (12,11))
plt.title("Phase by SQPE for the unitary CP(1/7)",fontsize = 16)
plt.plot(range(100),estimates,color = 'g',linewidth = 2,marker = 'o',label = 'Estimates')
plt.plot([1,100],[0.1428,0.1428],color = 'black')
plt.plot([1,100],[0,0],color = 'black')
plt.plot([1,100],[1,1],color = 'black',label = 'Correct')
plt.xlabel('Experiment')
plt.ylabel('Estimates')
plt.grid()
plt.legend()
plt.savefig(phase_path+"stat_qpe.JPG",dpi = 200)
estimates = []
for precision in range(5,16):
kqpe = KQPE(precision=precision,unitary = u1)
kqpe_circ = kqpe.get_circuit()
qc = QuantumCircuit(2+2,2)
qc.x(2)
qc.x(3)
qc.append(kqpe_circ,qargs = [0,1,2,3])
phase = kqpe.get_phase(qc,backend = backend, ancilla = [0,1],clbits = [0,1],show = False)
print("Precision :",precision)
print("Phase:",phase)
estimates.append(phase[0])
plt.title("Phase by Kitaev's Algorithm for the phase gate(1/7)",fontsize = 16)
plt.plot([i for i in range(5,16)],estimates,color = 'cyan',alpha = 0.6,linewidth = 2,marker = 's',label = 'Estimates')
plt.plot([5,17],[0.1428,0.1428],color = 'black')
plt.xlabel('Precision')
plt.ylabel('Estimates')
plt.grid()
plt.legend()
plt.savefig(phase_path+"kitaev_qpe.JPG",dpi = 200)
os.makedirs(name = "Plots/2-qubit/zx_gate/",exist_ok=True)
zx_path = "Plots/2-qubit/zx_gate/"
estimates = []
for precision in range(1,9):
#
qpe = QPE(precision=precision,unitary = u2)
qpe_circ = qpe.get_QPE(show = False)
# Quantum Circuit
qc = QuantumCircuit(precision+2,precision)
# make the eigenvector
qc.x(precision+1)
qc.h(precision+1)
qc.append(qpe_circ, qargs = list(range(precision+2)))
qc.measure(list(range(precision)),list(range(precision)))
counts = execute(qc,backend=backend,shots = 2**10).result().get_counts()
m = -1
for i,j in counts.items():
if j > m:
m = j
phase = i
factor = 0.5
ans = 0.0
for i in range(precision):
ans+= int(phase[i])*factor
factor/=2
estimates.append(ans)
plt.title("Phase by basic QPE for the unitary ZX",fontsize = 16)
plt.plot([i for i in range(1,9)],estimates,alpha = 0.5,color = 'g',linewidth = 2,marker = 'o',label = 'Estimates')
plt.plot([0,8],[0.5,0.5],color = 'black')
plt.xlabel('Precision')
plt.ylabel('Estimates')
plt.grid()
plt.legend()
plt.savefig(zx_path+"basic_qpe.JPG",dpi = 200)
estimates = []
for precision in range(1,9):
qpe = IQPE(precision=precision,unitary = u2,unknown=True)
qc = QuantumCircuit(1+2,precision)
# making the eigenvector
qc.x(2)
qc.h(2)
phase = qpe.get_circuit_phase(qc, qubits = [1,2], ancilla = 0,clbits = list(range(precision)),show = False)
# display(qc.draw('mpl'))
estimates.append(phase[1])
plt.title("Phase by iterative QPE for the unitary ZX",fontsize = 16)
plt.plot([i for i in range(1,9)],estimates,color = 'b',alpha = 0.5,linewidth = 2,marker = 'o',label = 'Estimates')
plt.plot([0,8],[0.5,0.5],color = 'black')
plt.xlabel('Precision')
plt.ylabel('Estimates')
plt.grid()
plt.legend()
plt.savefig(zx_path+"iqpe.JPG",dpi = 200)
estimates = []
for resolution in range(10,40,5):
qpe = SPEA(resolution = resolution,unitary = u2, error =4,max_iters=12)
result = qpe.get_eigen_pair(progress = True, backend = backend)
print("Result : ",result)
estimates.append(result['theta'])
plt.title("Phase by SQPE for the unitary ZX",fontsize = 16)
plt.plot([i for i in range(10,40,5)],estimates,color = 'g',linewidth = 2,marker = 'o',label = 'Estimates')
plt.plot([5,50],[0.5,0.5],color = 'black')
plt.plot([5,50],[0,0],color = 'black')
plt.plot([5,50],[1,1],color = 'black',label = 'Correct')
plt.xlabel('Precision')
plt.ylabel('Estimates')
plt.grid()
plt.legend()
plt.savefig(zx_path+"stat_qpe.JPG",dpi = 200)
estimates = []
for precision in range(5,16):
kqpe = KQPE(precision=precision,unitary = u2)
kqpe_circ = kqpe.get_circuit()
qc = QuantumCircuit(2+2,2)
qc.x(3)
qc.h(3)
qc.append(kqpe_circ,qargs = [0,1,2,3])
phase = kqpe.get_phase(qc,backend = backend, ancilla = [0,1],clbits = [0,1],show = False)
# display(qc.draw('mpl'))
print("Precision :",precision)
print("Phase:",phase)
estimates.append(phase[0])
plt.title("Phase by Kitaev's Algorithm for the zx gate",fontsize = 16)
plt.plot([i for i in range(5,16)],estimates,color = 'orange',alpha = 0.6,linewidth = 2,marker = 's',label = 'Estimates')
plt.plot([5,17],[0.5,0.5],color = 'black')
plt.plot([5,17],[-0.5,-0.5],color = 'black')
plt.xlabel('Precision')
plt.ylabel('Estimates')
plt.grid()
plt.legend()
plt.savefig(zx_path+"kitaev_qpe.JPG",dpi = 200)
|
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.
# pylint: disable=missing-class-docstring
"""Test the passmanager logic"""
import copy
import numpy as np
from qiskit import QuantumRegister, QuantumCircuit
from qiskit.circuit.library import U2Gate
from qiskit.converters import circuit_to_dag
from qiskit.transpiler import PassManager, PropertySet, TransformationPass, FlowController
from qiskit.transpiler.passes import CommutativeCancellation
from qiskit.transpiler.passes import Optimize1qGates, Unroller
from qiskit.test import QiskitTestCase
class TestPassManager(QiskitTestCase):
"""Test Pass manager logic."""
def test_callback(self):
"""Test the callback parameter."""
qr = QuantumRegister(1, "qr")
circuit = QuantumCircuit(qr, name="MyCircuit")
circuit.h(qr[0])
circuit.h(qr[0])
circuit.h(qr[0])
expected_start = QuantumCircuit(qr)
expected_start.append(U2Gate(0, np.pi), [qr[0]])
expected_start.append(U2Gate(0, np.pi), [qr[0]])
expected_start.append(U2Gate(0, np.pi), [qr[0]])
expected_start_dag = circuit_to_dag(expected_start)
expected_end = QuantumCircuit(qr)
expected_end.append(U2Gate(0, np.pi), [qr[0]])
expected_end_dag = circuit_to_dag(expected_end)
calls = []
def callback(**kwargs):
out_dict = kwargs
out_dict["dag"] = copy.deepcopy(kwargs["dag"])
calls.append(out_dict)
passmanager = PassManager()
passmanager.append(Unroller(["u2"]))
passmanager.append(Optimize1qGates())
passmanager.run(circuit, callback=callback)
self.assertEqual(len(calls), 2)
self.assertEqual(len(calls[0]), 5)
self.assertEqual(calls[0]["count"], 0)
self.assertEqual(calls[0]["pass_"].name(), "Unroller")
self.assertEqual(expected_start_dag, calls[0]["dag"])
self.assertIsInstance(calls[0]["time"], float)
self.assertEqual(calls[0]["property_set"], PropertySet())
self.assertEqual("MyCircuit", calls[0]["dag"].name)
self.assertEqual(len(calls[1]), 5)
self.assertEqual(calls[1]["count"], 1)
self.assertEqual(calls[1]["pass_"].name(), "Optimize1qGates")
self.assertEqual(expected_end_dag, calls[1]["dag"])
self.assertIsInstance(calls[0]["time"], float)
self.assertEqual(calls[0]["property_set"], PropertySet())
self.assertEqual("MyCircuit", calls[1]["dag"].name)
def test_callback_with_pass_requires(self):
"""Test the callback with a pass with another pass requirement."""
qr = QuantumRegister(3, "qr")
circuit = QuantumCircuit(qr, name="MyCircuit")
circuit.z(qr[0])
circuit.cx(qr[0], qr[2])
circuit.z(qr[0])
expected_start = QuantumCircuit(qr)
expected_start.z(qr[0])
expected_start.cx(qr[0], qr[2])
expected_start.z(qr[0])
expected_start_dag = circuit_to_dag(expected_start)
expected_end = QuantumCircuit(qr)
expected_end.cx(qr[0], qr[2])
expected_end_dag = circuit_to_dag(expected_end)
calls = []
def callback(**kwargs):
out_dict = kwargs
out_dict["dag"] = copy.deepcopy(kwargs["dag"])
calls.append(out_dict)
passmanager = PassManager()
passmanager.append(CommutativeCancellation(basis_gates=["u1", "u2", "u3", "cx"]))
passmanager.run(circuit, callback=callback)
self.assertEqual(len(calls), 2)
self.assertEqual(len(calls[0]), 5)
self.assertEqual(calls[0]["count"], 0)
self.assertEqual(calls[0]["pass_"].name(), "CommutationAnalysis")
self.assertEqual(expected_start_dag, calls[0]["dag"])
self.assertIsInstance(calls[0]["time"], float)
self.assertIsInstance(calls[0]["property_set"], PropertySet)
self.assertEqual("MyCircuit", calls[0]["dag"].name)
self.assertEqual(len(calls[1]), 5)
self.assertEqual(calls[1]["count"], 1)
self.assertEqual(calls[1]["pass_"].name(), "CommutativeCancellation")
self.assertEqual(expected_end_dag, calls[1]["dag"])
self.assertIsInstance(calls[0]["time"], float)
self.assertIsInstance(calls[0]["property_set"], PropertySet)
self.assertEqual("MyCircuit", calls[1]["dag"].name)
def test_to_flow_controller(self):
"""Test that conversion to a `FlowController` works, and the result can be added to a
circuit and conditioned, with the condition only being called once."""
class DummyPass(TransformationPass):
def __init__(self, x):
super().__init__()
self.x = x
def run(self, dag):
return dag
def repeat(count):
def condition(_):
nonlocal count
if not count:
return False
count -= 1
return True
return condition
def make_inner(prefix):
inner = PassManager()
inner.append(DummyPass(f"{prefix} 1"))
inner.append(DummyPass(f"{prefix} 2"), condition=lambda _: False)
inner.append(DummyPass(f"{prefix} 3"), condition=lambda _: True)
inner.append(DummyPass(f"{prefix} 4"), do_while=repeat(1))
return inner.to_flow_controller()
self.assertIsInstance(make_inner("test"), FlowController)
outer = PassManager()
outer.append(make_inner("first"))
outer.append(make_inner("second"), condition=lambda _: False)
# The intent of this `condition=repeat(1)` is to ensure that the outer condition is only
# checked once and not flattened into the inner controllers; an inner pass invalidating the
# condition should not affect subsequent passes once the initial condition was met.
outer.append(make_inner("third"), condition=repeat(1))
calls = []
def callback(pass_, **_):
self.assertIsInstance(pass_, DummyPass)
calls.append(pass_.x)
outer.run(QuantumCircuit(), callback=callback)
expected = [
"first 1",
"first 3",
# it's a do-while loop, not a while, which is why the `repeat(1)` gives two calls
"first 4",
"first 4",
# If the outer pass-manager condition is called more than once, then only the first of
# the `third` passes will appear.
"third 1",
"third 3",
"third 4",
"third 4",
]
self.assertEqual(calls, expected)
|
https://github.com/2lambda123/Qiskit-qiskit
|
2lambda123
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Tests for circuit templates."""
import unittest
from test import combine
from inspect import getmembers, isfunction
from ddt import ddt
import numpy as np
from qiskit import QuantumCircuit
from qiskit.test import QiskitTestCase
from qiskit.quantum_info.operators import Operator
import qiskit.circuit.library.templates as templib
@ddt
class TestTemplates(QiskitTestCase):
"""Tests for the circuit templates."""
circuits = [o[1]() for o in getmembers(templib) if isfunction(o[1])]
for circuit in circuits:
if isinstance(circuit, QuantumCircuit):
circuit.assign_parameters({param: 0.2 for param in circuit.parameters}, inplace=True)
@combine(template_circuit=circuits)
def test_template(self, template_circuit):
"""test to verify that all templates are equivalent to the identity"""
target = Operator(template_circuit)
value = Operator(np.eye(2**template_circuit.num_qubits))
self.assertTrue(target.equiv(value))
if __name__ == "__main__":
unittest.main()
|
https://github.com/crabster/qiskit-learning
|
crabster
|
'''
This is a implementation of the quantum teleportation algorithm
'''
from qiskit import *
from qiskit.visualization import plot_histogram
import os, shutil, numpy
from matplotlib.pyplot import plot, draw, show
LaTex_folder_Quantum_Teleportation = str(os.getcwd())+'/Latex_quantum_gates/Quantum_Teleportation/'
if not os.path.exists(LaTex_folder_Quantum_Teleportation):
os.makedirs(LaTex_folder_Quantum_Teleportation)
else:
shutil.rmtree(LaTex_folder_Quantum_Teleportation)
os.makedirs(LaTex_folder_Quantum_Teleportation)
qc = QuantumCircuit(3,3)
## prepare the state to be teleported
phi = 0*numpy.pi
theta= 0.5*numpy.pi
lam = 0*numpy.pi
qc.u(phi=phi, theta=theta,lam=lam,qubit=0)
## teleport the state
qc.barrier()
qc.h(1)
qc.cx(1,2)
qc.cz(0,1)
qc.h(0)
qc.h(1)
qc.barrier()
qc.measure([0,1],[0,1])
qc.barrier()
qc.x(2).c_if(0,1)
qc.z(2).c_if(1,1)
qc.h(2)
qc.measure(2,2)
LaTex_code = qc.draw(output='latex_source', initial_state=True, justify=None) # draw the circuit
f_name = 'quantum_teleportation.tex'
with open(LaTex_folder_Quantum_Teleportation+f_name, 'w') as f:
f.write(LaTex_code)
# simulation
simulator = Aer.get_backend('qasm_simulator')
result = execute(qc, backend=simulator, shots=100000).result()
counts = {'0':0,
'1': 0}
print(result.get_counts().keys())
for key, value in result.get_counts().items():
if(key[0] == '0'):
counts['0'] += value
else:
counts['1'] += value
print(counts)
plt = plot_histogram(counts)
draw()
show(block=True)
|
https://github.com/swe-train/qiskit__qiskit
|
swe-train
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test permutation quantum circuits, permutation gates, and quantum circuits that
contain permutation gates."""
import io
import unittest
import numpy as np
from qiskit import QuantumRegister
from qiskit.test.base import QiskitTestCase
from qiskit.circuit import QuantumCircuit
from qiskit.circuit.exceptions import CircuitError
from qiskit.circuit.library import Permutation, PermutationGate
from qiskit.quantum_info import Operator
from qiskit.qpy import dump, load
class TestPermutationLibrary(QiskitTestCase):
"""Test library of permutation logic quantum circuits."""
def test_permutation(self):
"""Test permutation circuit."""
circuit = Permutation(num_qubits=4, pattern=[1, 0, 3, 2])
expected = QuantumCircuit(4)
expected.swap(0, 1)
expected.swap(2, 3)
expected = Operator(expected)
simulated = Operator(circuit)
self.assertTrue(expected.equiv(simulated))
def test_permutation_bad(self):
"""Test that [0,..,n-1] permutation is required (no -1 for last element)."""
self.assertRaises(CircuitError, Permutation, 4, [1, 0, -1, 2])
class TestPermutationGate(QiskitTestCase):
"""Tests for the PermutationGate class."""
def test_permutation(self):
"""Test that Operator can be constructed."""
perm = PermutationGate(pattern=[1, 0, 3, 2])
expected = QuantumCircuit(4)
expected.swap(0, 1)
expected.swap(2, 3)
expected = Operator(expected)
simulated = Operator(perm)
self.assertTrue(expected.equiv(simulated))
def test_permutation_bad(self):
"""Test that [0,..,n-1] permutation is required (no -1 for last element)."""
self.assertRaises(CircuitError, PermutationGate, [1, 0, -1, 2])
def test_permutation_array(self):
"""Test correctness of the ``__array__`` method."""
perm = PermutationGate([1, 2, 0])
# The permutation pattern means q1->q0, q2->q1, q0->q2, or equivalently
# q0'=q1, q1'=q2, q2'=q0, where the primed values are the values after the
# permutation. The following matrix is the expected unitary matrix for this.
# As an example, the second column represents the result of applying
# the permutation to |001>, i.e. to q2=0, q1=0, q0=1. We should get
# q2'=q0=1, q1'=q2=0, q0'=q1=0, that is the state |100>. This corresponds
# to the "1" in the 5 row.
expected_op = np.array(
[
[1, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 1, 0],
[0, 1, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 1, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 1],
]
)
self.assertTrue(np.array_equal(perm.__array__(dtype=int), expected_op))
def test_pattern(self):
"""Test the ``pattern`` method."""
pattern = [1, 3, 5, 0, 4, 2]
perm = PermutationGate(pattern)
self.assertTrue(np.array_equal(perm.pattern, pattern))
def test_inverse(self):
"""Test correctness of the ``inverse`` method."""
perm = PermutationGate([1, 3, 5, 0, 4, 2])
# We have the permutation 1->0, 3->1, 5->2, 0->3, 4->4, 2->5.
# The inverse permutations is 0->1, 1->3, 2->5, 3->0, 4->4, 5->2, or
# after reordering 3->0, 0->1, 5->2, 1->3, 4->4, 2->5.
inverse_perm = perm.inverse()
expected_inverse_perm = PermutationGate([3, 0, 5, 1, 4, 2])
self.assertTrue(np.array_equal(inverse_perm.pattern, expected_inverse_perm.pattern))
class TestPermutationGatesOnCircuit(QiskitTestCase):
"""Tests for quantum circuits containing permutations."""
def test_append_to_circuit(self):
"""Test method for adding Permutations to quantum circuit."""
qc = QuantumCircuit(5)
qc.append(PermutationGate([1, 2, 0]), [0, 1, 2])
qc.append(PermutationGate([2, 3, 0, 1]), [1, 2, 3, 4])
self.assertIsInstance(qc.data[0].operation, PermutationGate)
self.assertIsInstance(qc.data[1].operation, PermutationGate)
def test_inverse(self):
"""Test inverse method for circuits with permutations."""
qc = QuantumCircuit(5)
qc.append(PermutationGate([1, 2, 3, 0]), [0, 4, 2, 1])
qci = qc.inverse()
qci_pattern = qci.data[0].operation.pattern
expected_pattern = [3, 0, 1, 2]
# The inverse permutations should be defined over the same qubits but with the
# inverse permutation pattern.
self.assertTrue(np.array_equal(qci_pattern, expected_pattern))
self.assertTrue(np.array_equal(qc.data[0].qubits, qci.data[0].qubits))
def test_reverse_ops(self):
"""Test reverse_ops method for circuits with permutations."""
qc = QuantumCircuit(5)
qc.append(PermutationGate([1, 2, 3, 0]), [0, 4, 2, 1])
qcr = qc.reverse_ops()
# The reversed circuit should have the permutation gate with the same pattern and over the
# same qubits.
self.assertTrue(np.array_equal(qc.data[0].operation.pattern, qcr.data[0].operation.pattern))
self.assertTrue(np.array_equal(qc.data[0].qubits, qcr.data[0].qubits))
def test_conditional(self):
"""Test adding conditional permutations."""
qc = QuantumCircuit(5, 1)
qc.append(PermutationGate([1, 2, 0]), [2, 3, 4]).c_if(0, 1)
self.assertIsNotNone(qc.data[0].operation.condition)
def test_qasm(self):
"""Test qasm for circuits with permutations."""
qr = QuantumRegister(5, "q0")
circuit = QuantumCircuit(qr)
pattern = [2, 4, 3, 0, 1]
permutation = PermutationGate(pattern)
circuit.append(permutation, [0, 1, 2, 3, 4])
circuit.h(qr[0])
expected_qasm = (
"OPENQASM 2.0;\n"
'include "qelib1.inc";\n'
"gate permutation__2_4_3_0_1_ q0,q1,q2,q3,q4 { swap q2,q3; swap q1,q4; swap q0,q3; }\n"
"qreg q0[5];\n"
"permutation__2_4_3_0_1_ q0[0],q0[1],q0[2],q0[3],q0[4];\n"
"h q0[0];\n"
)
self.assertEqual(expected_qasm, circuit.qasm())
def test_qpy(self):
"""Test qpy for circuits with permutations."""
circuit = QuantumCircuit(6, 1)
circuit.cx(0, 1)
circuit.append(PermutationGate([1, 2, 0]), [2, 4, 5])
circuit.h(4)
print(circuit)
qpy_file = io.BytesIO()
dump(circuit, qpy_file)
qpy_file.seek(0)
new_circuit = load(qpy_file)[0]
self.assertEqual(circuit, new_circuit)
if __name__ == "__main__":
unittest.main()
|
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.
"""Unit tests for pulse instructions."""
import numpy as np
from qiskit import pulse, circuit
from qiskit.pulse import channels, configuration, instructions, library, exceptions
from qiskit.pulse.transforms import inline_subroutines, target_qobj_transform
from qiskit.test import QiskitTestCase
class TestAcquire(QiskitTestCase):
"""Acquisition tests."""
def test_can_construct_valid_acquire_command(self):
"""Test if valid acquire command can be constructed."""
kernel_opts = {"start_window": 0, "stop_window": 10}
kernel = configuration.Kernel(name="boxcar", **kernel_opts)
discriminator_opts = {
"neighborhoods": [{"qubits": 1, "channels": 1}],
"cal": "coloring",
"resample": False,
}
discriminator = configuration.Discriminator(
name="linear_discriminator", **discriminator_opts
)
acq = instructions.Acquire(
10,
channels.AcquireChannel(0),
channels.MemorySlot(0),
kernel=kernel,
discriminator=discriminator,
name="acquire",
)
self.assertEqual(acq.duration, 10)
self.assertEqual(acq.discriminator.name, "linear_discriminator")
self.assertEqual(acq.discriminator.params, discriminator_opts)
self.assertEqual(acq.kernel.name, "boxcar")
self.assertEqual(acq.kernel.params, kernel_opts)
self.assertIsInstance(acq.id, int)
self.assertEqual(acq.name, "acquire")
self.assertEqual(
acq.operands,
(
10,
channels.AcquireChannel(0),
channels.MemorySlot(0),
None,
kernel,
discriminator,
),
)
def test_instructions_hash(self):
"""Test hashing for acquire instruction."""
acq_1 = instructions.Acquire(
10,
channels.AcquireChannel(0),
channels.MemorySlot(0),
name="acquire",
)
acq_2 = instructions.Acquire(
10,
channels.AcquireChannel(0),
channels.MemorySlot(0),
name="acquire",
)
hash_1 = hash(acq_1)
hash_2 = hash(acq_2)
self.assertEqual(hash_1, hash_2)
class TestDelay(QiskitTestCase):
"""Delay tests."""
def test_delay(self):
"""Test delay."""
delay = instructions.Delay(10, channels.DriveChannel(0), name="test_name")
self.assertIsInstance(delay.id, int)
self.assertEqual(delay.name, "test_name")
self.assertEqual(delay.duration, 10)
self.assertIsInstance(delay.duration, int)
self.assertEqual(delay.operands, (10, channels.DriveChannel(0)))
self.assertEqual(delay, instructions.Delay(10, channels.DriveChannel(0)))
self.assertNotEqual(delay, instructions.Delay(11, channels.DriveChannel(1)))
self.assertEqual(repr(delay), "Delay(10, DriveChannel(0), name='test_name')")
# Test numpy int for duration
delay = instructions.Delay(np.int32(10), channels.DriveChannel(0), name="test_name2")
self.assertEqual(delay.duration, 10)
self.assertIsInstance(delay.duration, np.integer)
def test_operator_delay(self):
"""Test Operator(delay)."""
from qiskit.circuit import QuantumCircuit
from qiskit.quantum_info import Operator
circ = QuantumCircuit(1)
circ.delay(10)
op_delay = Operator(circ)
expected = QuantumCircuit(1)
expected.i(0)
op_identity = Operator(expected)
self.assertEqual(op_delay, op_identity)
class TestSetFrequency(QiskitTestCase):
"""Set frequency tests."""
def test_freq(self):
"""Test set frequency basic functionality."""
set_freq = instructions.SetFrequency(4.5e9, channels.DriveChannel(1), name="test")
self.assertIsInstance(set_freq.id, int)
self.assertEqual(set_freq.duration, 0)
self.assertEqual(set_freq.frequency, 4.5e9)
self.assertEqual(set_freq.operands, (4.5e9, channels.DriveChannel(1)))
self.assertEqual(
set_freq, instructions.SetFrequency(4.5e9, channels.DriveChannel(1), name="test")
)
self.assertNotEqual(
set_freq, instructions.SetFrequency(4.5e8, channels.DriveChannel(1), name="test")
)
self.assertEqual(repr(set_freq), "SetFrequency(4500000000.0, DriveChannel(1), name='test')")
def test_freq_non_pulse_channel(self):
"""Test set frequency constructor with illegal channel"""
with self.assertRaises(exceptions.PulseError):
instructions.SetFrequency(4.5e9, channels.RegisterSlot(1), name="test")
def test_parameter_expression(self):
"""Test getting all parameters assigned by expression."""
p1 = circuit.Parameter("P1")
p2 = circuit.Parameter("P2")
expr = p1 + p2
instr = instructions.SetFrequency(expr, channel=channels.DriveChannel(0))
self.assertSetEqual(instr.parameters, {p1, p2})
class TestShiftFrequency(QiskitTestCase):
"""Shift frequency tests."""
def test_shift_freq(self):
"""Test shift frequency basic functionality."""
shift_freq = instructions.ShiftFrequency(4.5e9, channels.DriveChannel(1), name="test")
self.assertIsInstance(shift_freq.id, int)
self.assertEqual(shift_freq.duration, 0)
self.assertEqual(shift_freq.frequency, 4.5e9)
self.assertEqual(shift_freq.operands, (4.5e9, channels.DriveChannel(1)))
self.assertEqual(
shift_freq, instructions.ShiftFrequency(4.5e9, channels.DriveChannel(1), name="test")
)
self.assertNotEqual(
shift_freq, instructions.ShiftFrequency(4.5e8, channels.DriveChannel(1), name="test")
)
self.assertEqual(
repr(shift_freq), "ShiftFrequency(4500000000.0, DriveChannel(1), name='test')"
)
def test_freq_non_pulse_channel(self):
"""Test shift frequency constructor with illegal channel"""
with self.assertRaises(exceptions.PulseError):
instructions.ShiftFrequency(4.5e9, channels.RegisterSlot(1), name="test")
def test_parameter_expression(self):
"""Test getting all parameters assigned by expression."""
p1 = circuit.Parameter("P1")
p2 = circuit.Parameter("P2")
expr = p1 + p2
instr = instructions.ShiftFrequency(expr, channel=channels.DriveChannel(0))
self.assertSetEqual(instr.parameters, {p1, p2})
class TestSetPhase(QiskitTestCase):
"""Test the instruction construction."""
def test_default(self):
"""Test basic SetPhase."""
set_phase = instructions.SetPhase(1.57, channels.DriveChannel(0))
self.assertIsInstance(set_phase.id, int)
self.assertEqual(set_phase.name, None)
self.assertEqual(set_phase.duration, 0)
self.assertEqual(set_phase.phase, 1.57)
self.assertEqual(set_phase.operands, (1.57, channels.DriveChannel(0)))
self.assertEqual(
set_phase, instructions.SetPhase(1.57, channels.DriveChannel(0), name="test")
)
self.assertNotEqual(
set_phase, instructions.SetPhase(1.57j, channels.DriveChannel(0), name="test")
)
self.assertEqual(repr(set_phase), "SetPhase(1.57, DriveChannel(0))")
def test_set_phase_non_pulse_channel(self):
"""Test shift phase constructor with illegal channel"""
with self.assertRaises(exceptions.PulseError):
instructions.SetPhase(1.57, channels.RegisterSlot(1), name="test")
def test_parameter_expression(self):
"""Test getting all parameters assigned by expression."""
p1 = circuit.Parameter("P1")
p2 = circuit.Parameter("P2")
expr = p1 + p2
instr = instructions.SetPhase(expr, channel=channels.DriveChannel(0))
self.assertSetEqual(instr.parameters, {p1, p2})
class TestShiftPhase(QiskitTestCase):
"""Test the instruction construction."""
def test_default(self):
"""Test basic ShiftPhase."""
shift_phase = instructions.ShiftPhase(1.57, channels.DriveChannel(0))
self.assertIsInstance(shift_phase.id, int)
self.assertEqual(shift_phase.name, None)
self.assertEqual(shift_phase.duration, 0)
self.assertEqual(shift_phase.phase, 1.57)
self.assertEqual(shift_phase.operands, (1.57, channels.DriveChannel(0)))
self.assertEqual(
shift_phase, instructions.ShiftPhase(1.57, channels.DriveChannel(0), name="test")
)
self.assertNotEqual(
shift_phase, instructions.ShiftPhase(1.57j, channels.DriveChannel(0), name="test")
)
self.assertEqual(repr(shift_phase), "ShiftPhase(1.57, DriveChannel(0))")
def test_shift_phase_non_pulse_channel(self):
"""Test shift phase constructor with illegal channel"""
with self.assertRaises(exceptions.PulseError):
instructions.ShiftPhase(1.57, channels.RegisterSlot(1), name="test")
def test_parameter_expression(self):
"""Test getting all parameters assigned by expression."""
p1 = circuit.Parameter("P1")
p2 = circuit.Parameter("P2")
expr = p1 + p2
instr = instructions.ShiftPhase(expr, channel=channels.DriveChannel(0))
self.assertSetEqual(instr.parameters, {p1, p2})
class TestSnapshot(QiskitTestCase):
"""Snapshot tests."""
def test_default(self):
"""Test default snapshot."""
snapshot = instructions.Snapshot(label="test_name", snapshot_type="state")
self.assertIsInstance(snapshot.id, int)
self.assertEqual(snapshot.name, "test_name")
self.assertEqual(snapshot.type, "state")
self.assertEqual(snapshot.duration, 0)
self.assertNotEqual(snapshot, instructions.Delay(10, channels.DriveChannel(0)))
self.assertEqual(repr(snapshot), "Snapshot(test_name, state, name='test_name')")
class TestPlay(QiskitTestCase):
"""Play tests."""
def setUp(self):
"""Setup play tests."""
super().setUp()
self.duration = 4
self.pulse_op = library.Waveform([1.0] * self.duration, name="test")
def test_play(self):
"""Test basic play instruction."""
play = instructions.Play(self.pulse_op, channels.DriveChannel(1))
self.assertIsInstance(play.id, int)
self.assertEqual(play.name, self.pulse_op.name)
self.assertEqual(play.duration, self.duration)
self.assertEqual(
repr(play),
"Play(Waveform(array([1.+0.j, 1.+0.j, 1.+0.j, 1.+0.j]), name='test'),"
" DriveChannel(1), name='test')",
)
def test_play_non_pulse_ch_raises(self):
"""Test that play instruction on non-pulse channel raises a pulse error."""
with self.assertRaises(exceptions.PulseError):
instructions.Play(self.pulse_op, channels.AcquireChannel(0))
class TestDirectives(QiskitTestCase):
"""Test pulse directives."""
def test_relative_barrier(self):
"""Test the relative barrier directive."""
a0 = channels.AcquireChannel(0)
d0 = channels.DriveChannel(0)
m0 = channels.MeasureChannel(0)
u0 = channels.ControlChannel(0)
mem0 = channels.MemorySlot(0)
reg0 = channels.RegisterSlot(0)
chans = (a0, d0, m0, u0, mem0, reg0)
name = "barrier"
barrier = instructions.RelativeBarrier(*chans, name=name)
self.assertEqual(barrier.name, name)
self.assertEqual(barrier.duration, 0)
self.assertEqual(barrier.channels, chans)
self.assertEqual(barrier.operands, chans)
class TestCall(QiskitTestCase):
"""Test call instruction."""
def setUp(self):
super().setUp()
with pulse.build() as _subroutine:
pulse.delay(10, pulse.DriveChannel(0))
self.subroutine = _subroutine
self.param1 = circuit.Parameter("amp1")
self.param2 = circuit.Parameter("amp2")
with pulse.build() as _function:
pulse.play(pulse.Gaussian(160, self.param1, 40), pulse.DriveChannel(0))
pulse.play(pulse.Gaussian(160, self.param2, 40), pulse.DriveChannel(0))
pulse.play(pulse.Gaussian(160, self.param1, 40), pulse.DriveChannel(0))
self.function = _function
def test_call(self):
"""Test basic call instruction."""
with self.assertWarns(DeprecationWarning):
call = instructions.Call(subroutine=self.subroutine)
self.assertEqual(call.duration, 10)
self.assertEqual(call.subroutine, self.subroutine)
def test_parameterized_call(self):
"""Test call instruction with parameterized subroutine."""
with self.assertWarns(DeprecationWarning):
call = instructions.Call(subroutine=self.function)
self.assertTrue(call.is_parameterized())
self.assertEqual(len(call.parameters), 2)
def test_assign_parameters_to_call(self):
"""Test create schedule by calling subroutine and assign parameters to it."""
init_dict = {self.param1: 0.1, self.param2: 0.5}
with pulse.build() as test_sched:
pulse.call(self.function)
test_sched = test_sched.assign_parameters(value_dict=init_dict)
test_sched = inline_subroutines(test_sched)
with pulse.build() as ref_sched:
pulse.play(pulse.Gaussian(160, 0.1, 40), pulse.DriveChannel(0))
pulse.play(pulse.Gaussian(160, 0.5, 40), pulse.DriveChannel(0))
pulse.play(pulse.Gaussian(160, 0.1, 40), pulse.DriveChannel(0))
self.assertEqual(target_qobj_transform(test_sched), target_qobj_transform(ref_sched))
def test_call_initialize_with_parameter(self):
"""Test call instruction with parameterized subroutine with initial dict."""
init_dict = {self.param1: 0.1, self.param2: 0.5}
with self.assertWarns(DeprecationWarning):
call = instructions.Call(subroutine=self.function, value_dict=init_dict)
with pulse.build() as ref_sched:
pulse.play(pulse.Gaussian(160, 0.1, 40), pulse.DriveChannel(0))
pulse.play(pulse.Gaussian(160, 0.5, 40), pulse.DriveChannel(0))
pulse.play(pulse.Gaussian(160, 0.1, 40), pulse.DriveChannel(0))
self.assertEqual(
target_qobj_transform(call.assigned_subroutine()), target_qobj_transform(ref_sched)
)
def test_call_subroutine_with_different_parameters(self):
"""Test call subroutines with different parameters in the same schedule."""
init_dict1 = {self.param1: 0.1, self.param2: 0.5}
init_dict2 = {self.param1: 0.3, self.param2: 0.7}
with pulse.build() as test_sched:
pulse.call(self.function, value_dict=init_dict1)
pulse.call(self.function, value_dict=init_dict2)
with pulse.build() as ref_sched:
pulse.play(pulse.Gaussian(160, 0.1, 40), pulse.DriveChannel(0))
pulse.play(pulse.Gaussian(160, 0.5, 40), pulse.DriveChannel(0))
pulse.play(pulse.Gaussian(160, 0.1, 40), pulse.DriveChannel(0))
pulse.play(pulse.Gaussian(160, 0.3, 40), pulse.DriveChannel(0))
pulse.play(pulse.Gaussian(160, 0.7, 40), pulse.DriveChannel(0))
pulse.play(pulse.Gaussian(160, 0.3, 40), pulse.DriveChannel(0))
self.assertEqual(target_qobj_transform(test_sched), target_qobj_transform(ref_sched))
|
https://github.com/swe-train/qiskit__qiskit
|
swe-train
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test RemoveResetInZeroState pass"""
import unittest
from qiskit import QuantumRegister, QuantumCircuit
from qiskit.transpiler import PassManager
from qiskit.transpiler.passes import RemoveResetInZeroState, DAGFixedPoint
from qiskit.converters import circuit_to_dag
from qiskit.test import QiskitTestCase
class TestRemoveResetInZeroState(QiskitTestCase):
"""Test swap-followed-by-measure optimizations."""
def test_optimize_single_reset(self):
"""Remove a single reset
qr0:--|0>-- ==> qr0:----
"""
qr = QuantumRegister(1, "qr")
circuit = QuantumCircuit(qr)
circuit.reset(qr)
dag = circuit_to_dag(circuit)
expected = QuantumCircuit(qr)
pass_ = RemoveResetInZeroState()
after = pass_.run(dag)
self.assertEqual(circuit_to_dag(expected), after)
def test_dont_optimize_non_zero_state(self):
"""Do not remove reset if not in a zero state
qr0:--[H]--|0>-- ==> qr0:--[H]--|0>--
"""
qr = QuantumRegister(1, "qr")
circuit = QuantumCircuit(qr)
circuit.h(qr)
circuit.reset(qr)
dag = circuit_to_dag(circuit)
expected = QuantumCircuit(qr)
expected.h(qr)
expected.reset(qr)
pass_ = RemoveResetInZeroState()
after = pass_.run(dag)
self.assertEqual(circuit_to_dag(expected), after)
def test_optimize_single_reset_in_diff_qubits(self):
"""Remove a single reset in different qubits
qr0:--|0>-- qr0:----
==>
qr1:--|0>-- qr1:----
"""
qr = QuantumRegister(2, "qr")
circuit = QuantumCircuit(qr)
circuit.reset(qr)
dag = circuit_to_dag(circuit)
expected = QuantumCircuit(qr)
pass_ = RemoveResetInZeroState()
after = pass_.run(dag)
self.assertEqual(circuit_to_dag(expected), after)
class TestRemoveResetInZeroStateFixedPoint(QiskitTestCase):
"""Test RemoveResetInZeroState in a transpiler, using fixed point."""
def test_two_resets(self):
"""Remove two initial resets
qr0:--|0>-|0>-- ==> qr0:----
"""
qr = QuantumRegister(1, "qr")
circuit = QuantumCircuit(qr)
circuit.reset(qr[0])
circuit.reset(qr[0])
expected = QuantumCircuit(qr)
pass_manager = PassManager()
pass_manager.append(
[RemoveResetInZeroState(), DAGFixedPoint()],
do_while=lambda property_set: not property_set["dag_fixed_point"],
)
after = pass_manager.run(circuit)
self.assertEqual(expected, after)
if __name__ == "__main__":
unittest.main()
|
https://github.com/swe-train/qiskit__qiskit
|
swe-train
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2023
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
# pylint: disable=no-member,invalid-name,missing-docstring,no-name-in-module
# pylint: disable=attribute-defined-outside-init,unsubscriptable-object
import os
from qiskit import QuantumCircuit
from qiskit.compiler import transpile
from qiskit.test.mock import FakeToronto
class TranspilerQualitativeBench:
params = ([0, 1, 2, 3], ["stochastic", "sabre"], ["dense", "noise_adaptive", "sabre"])
param_names = ["optimization level", "routing method", "layout method"]
timeout = 600
# pylint: disable=unused-argument
def setup(self, optimization_level, routing_method, layout_method):
self.backend = FakeToronto()
self.qasm_path = os.path.abspath(os.path.join(os.path.dirname(__file__), "qasm"))
self.depth_4gt10_v1_81 = QuantumCircuit.from_qasm_file(
os.path.join(self.qasm_path, "depth_4gt10-v1_81.qasm")
)
self.depth_4mod5_v0_19 = QuantumCircuit.from_qasm_file(
os.path.join(self.qasm_path, "depth_4mod5-v0_19.qasm")
)
self.depth_mod8_10_178 = QuantumCircuit.from_qasm_file(
os.path.join(self.qasm_path, "depth_mod8-10_178.qasm")
)
self.time_cnt3_5_179 = QuantumCircuit.from_qasm_file(
os.path.join(self.qasm_path, "time_cnt3-5_179.qasm")
)
self.time_cnt3_5_180 = QuantumCircuit.from_qasm_file(
os.path.join(self.qasm_path, "time_cnt3-5_180.qasm")
)
self.time_qft_16 = QuantumCircuit.from_qasm_file(
os.path.join(self.qasm_path, "time_qft_16.qasm")
)
def track_depth_transpile_4gt10_v1_81(self, optimization_level, routing_method, layout_method):
return transpile(
self.depth_4gt10_v1_81,
self.backend,
routing_method=routing_method,
layout_method=layout_method,
optimization_level=optimization_level,
seed_transpiler=0,
).depth()
def track_depth_transpile_4mod5_v0_19(self, optimization_level, routing_method, layout_method):
return transpile(
self.depth_4mod5_v0_19,
self.backend,
routing_method=routing_method,
layout_method=layout_method,
optimization_level=optimization_level,
seed_transpiler=0,
).depth()
def track_depth_transpile_mod8_10_178(self, optimization_level, routing_method, layout_method):
return transpile(
self.depth_mod8_10_178,
self.backend,
routing_method=routing_method,
layout_method=layout_method,
optimization_level=optimization_level,
seed_transpiler=0,
).depth()
def time_transpile_time_cnt3_5_179(self, optimization_level, routing_method, layout_method):
transpile(
self.time_cnt3_5_179,
self.backend,
routing_method=routing_method,
layout_method=layout_method,
optimization_level=optimization_level,
seed_transpiler=0,
)
def time_transpile_time_cnt3_5_180(self, optimization_level, routing_method, layout_method):
transpile(
self.time_cnt3_5_180,
self.backend,
routing_method=routing_method,
layout_method=layout_method,
optimization_level=optimization_level,
seed_transpiler=0,
)
def time_transpile_time_qft_16(self, optimization_level, routing_method, layout_method):
transpile(
self.time_qft_16,
self.backend,
routing_method=routing_method,
layout_method=layout_method,
optimization_level=optimization_level,
seed_transpiler=0,
)
|
https://github.com/ionq-samples/qiskit-getting-started
|
ionq-samples
|
#imports
from qiskit_ionq import IonQProvider
ionq_provider = IonQProvider(token='API-Key-goes-here')
import numpy as np
from qiskit import QuantumCircuit, execute, Aer
from qiskit.tools.visualization import plot_histogram, array_to_latex
from qiskit.extensions import UnitaryGate
BV=QuantumCircuit(4,3)
BV.h(0)
BV.h(1)
BV.h(2)
BV.h(3)
BV.z(3)
BV.barrier()
BV.draw()
BV.cx(0,3)
BV.barrier()
BV.draw()
BV.h(0)
BV.h(1)
BV.h(2)
BV.measure(0,0)
BV.measure(1,1)
BV.measure(2,2)
BV.draw()
backend = ionq_provider.get_backend("ionq_simulator")#choose your backend
job = execute(BV, backend,shot=50000) #get the job object
result = job.result() # get result object
counts = result.get_counts() #get the counts dictionary
fig=plot_histogram(counts) #plot the histogram of the counts
ax = fig.axes[0]
fig
|
https://github.com/0tt3r/QuaC-qiskit
|
0tt3r
|
# -*- coding: utf-8 -*-
"""A brief example showing the workflow of simulation with the plugin.
"""
import math
import matplotlib.pyplot as plt
from qiskit import QuantumCircuit, execute
from qiskit.tools.visualization import plot_histogram
from quac_qiskit import Quac
def main():
circuit1 = QuantumCircuit(5, 5)
circuit2 = QuantumCircuit(5, 5)
circuit3 = QuantumCircuit(1, 1)
circuit1.h(0)
circuit2.u2(0, math.pi, 0)
circuit3.u3(math.pi/2, math.pi, 0, 0)
circuit1.measure(0, 0)
circuit2.measure(0, 0)
circuit3.measure(0, 0)
print("Available QuaC backends:")
print(Quac.backends())
simulator = Quac.get_backend('fake_vigo_density_simulator', meas=True)
# Execute the circuit on the QuaC simulator
job1 = execute(circuit1, simulator)
job2 = execute(circuit2, simulator)
job3 = execute(circuit3, simulator)
print(f"Hadamard counts: {job1.result().get_counts()}")
print(f"U2 counts: {job2.result().get_counts()}")
print(f"U3 counts: {job3.result().get_counts()}")
plot_histogram(job1.result().get_counts())
plot_histogram((job2.result().get_counts()))
plot_histogram(job3.result().get_counts())
plt.show()
if __name__ == '__main__':
main()
|
https://github.com/abbarreto/qiskit4
|
abbarreto
|
from qiskit import *
import numpy as np
import math
from matplotlib import pyplot as plt
import qiskit
nshots = 8192
IBMQ.load_account()
provider = qiskit.IBMQ.get_provider(hub='ibm-q', group='open', project='main')
device = provider.get_backend('ibmq_belem')
simulator = Aer.get_backend('qasm_simulator')
from qiskit.tools.monitor import job_monitor
from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter
#from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter
from qiskit.visualization import plot_histogram
qr = QuantumRegister(4)
cr = ClassicalRegister(3)
qc = QuantumCircuit(qr, cr)
qc.x(3)
qc.h([0,1,2])
qc.draw('mpl')
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-np.pi/2, np.pi/2, 1000) # generate 1000 evenly spaced points between -pi and pi
y_sin = np.abs(np.sin(x/2)) # compute sin(x) for each x
y_x = np.abs(x/2) # set y=x for each x
plt.plot(x, y_sin, label='sin(x)') # plot sin(x) as a blue line
plt.plot(x, y_x, label='x', color='orange') # plot x as an orange line
plt.legend() # display the legend
plt.show() # show the plot
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import numpy as np
from qiskit import pulse
d0 = pulse.DriveChannel(0)
x90 = pulse.Gaussian(10, 0.1, 3)
x180 = pulse.Gaussian(10, 0.2, 3)
def udd10_pos(j):
return np.sin(np.pi*j/(2*10 + 2))**2
with pulse.build() as udd_sched:
pulse.play(x90, d0)
with pulse.align_func(duration=300, func=udd10_pos):
for _ in range(10):
pulse.play(x180, d0)
pulse.play(x90, d0)
udd_sched.draw()
|
https://github.com/ratansahu05/Quantum-Computing-and-Programming
|
ratansahu05
|
import matplotlib.pyplot as plt
import numpy as np
from sklearn.svm import SVC
from sklearn.cluster import SpectralClustering
from sklearn.metrics import normalized_mutual_info_score
from qiskit import BasicAer
from qiskit.circuit.library import ZZFeatureMap
from qiskit.utils import QuantumInstance, algorithm_globals
from qiskit_machine_learning.algorithms import QSVC
from qiskit_machine_learning.kernels import QuantumKernel
from qiskit_machine_learning.datasets import ad_hoc_data
seed = 12345
algorithm_globals.random_seed = seed
adhoc_dimension = 2
train_features, train_labels, test_features, test_labels, adhoc_total = ad_hoc_data(
training_size=20,
test_size=5,
n=adhoc_dimension,
gap=0.3,
plot_data=False,
one_hot=False,
include_sample_total=True,
)
plt.figure(figsize=(5, 5))
plt.ylim(0, 2 * np.pi)
plt.xlim(0, 2 * np.pi)
plt.imshow(
np.asmatrix(adhoc_total).T,
interpolation="nearest",
origin="lower",
cmap="RdBu",
extent=[0, 2 * np.pi, 0, 2 * np.pi],
)
plt.scatter(
train_features[np.where(train_labels[:] == 0), 0],
train_features[np.where(train_labels[:] == 0), 1],
marker="s",
facecolors="w",
edgecolors="b",
label="A train",
)
plt.scatter(
train_features[np.where(train_labels[:] == 1), 0],
train_features[np.where(train_labels[:] == 1), 1],
marker="o",
facecolors="w",
edgecolors="r",
label="B train",
)
plt.scatter(
test_features[np.where(test_labels[:] == 0), 0],
test_features[np.where(test_labels[:] == 0), 1],
marker="s",
facecolors="b",
edgecolors="w",
label="A test",
)
plt.scatter(
test_features[np.where(test_labels[:] == 1), 0],
test_features[np.where(test_labels[:] == 1), 1],
marker="o",
facecolors="r",
edgecolors="w",
label="B test",
)
plt.legend(bbox_to_anchor=(1.05, 1), loc="upper left", borderaxespad=0.0)
plt.title("Ad hoc dataset for classification")
plt.show()
adhoc_feature_map = ZZFeatureMap(feature_dimension=adhoc_dimension, reps=2, entanglement="linear")
adhoc_backend = QuantumInstance(
BasicAer.get_backend("qasm_simulator"), shots=1024, seed_simulator=seed, seed_transpiler=seed
)
adhoc_kernel = QuantumKernel(feature_map=adhoc_feature_map, quantum_instance=adhoc_backend)
adhoc_svc = SVC(kernel=adhoc_kernel.evaluate)
adhoc_svc.fit(train_features, train_labels)
adhoc_score = adhoc_svc.score(test_features, test_labels)
print(f"Callable kernel classification test score: {adhoc_score}")
adhoc_matrix_train = adhoc_kernel.evaluate(x_vec=train_features)
adhoc_matrix_test = adhoc_kernel.evaluate(x_vec=test_features, y_vec=train_features)
fig, axs = plt.subplots(1, 2, figsize=(10, 5))
axs[0].imshow(
np.asmatrix(adhoc_matrix_train), interpolation="nearest", origin="upper", cmap="Blues"
)
axs[0].set_title("Ad hoc training kernel matrix")
axs[1].imshow(np.asmatrix(adhoc_matrix_test), interpolation="nearest", origin="upper", cmap="Reds")
axs[1].set_title("Ad hoc testing kernel matrix")
plt.show()
adhoc_svc = SVC(kernel="precomputed")
adhoc_svc.fit(adhoc_matrix_train, train_labels)
adhoc_score = adhoc_svc.score(adhoc_matrix_test, test_labels)
print(f"Precomputed kernel classification test score: {adhoc_score}")
qsvc = QSVC(quantum_kernel=adhoc_kernel)
qsvc.fit(train_features, train_labels)
qsvc_score = qsvc.score(test_features, test_labels)
print(f"QSVC classification test score: {qsvc_score}")
|
https://github.com/dimple12M/Qiskit-Certification-Guide
|
dimple12M
|
from qiskit import *
from qiskit.quantum_info import Statevector
from math import pi
qc=QuantumCircuit(3)
qc.h(range(2))
qc.x(2)
qc.draw(output="mpl")
print(qc.qasm())
qc_qasm=qc.qasm(filename='sample.qasm')
print(qc_qasm)
qc1=qc.from_qasm_file("./sample.qasm")
qc1.draw(output="mpl")
qc2=qc.from_qasm_str(qc.qasm())
qc2.draw(output="mpl")
|
https://github.com/v0lta/Quantum-init
|
v0lta
|
# written by moritz (wolter@cs.uni-bonn.de) at 20/01/2021
import numpy as np
from qiskit import(
QuantumCircuit,
execute,
Aer)
from qiskit import IBMQ
from qiskit.providers.ibmq import least_busy
def get_backend(nqubits=5):
""" Returns a quantum computation backend.
Args:
nqubits (int, optional): The number of desired qbits.
Defaults to 5.
Returns:
backend (qiskit.providers.ibmq.IBMQBackend): The device to run on.
"""
provider = IBMQ.load_account()
# provider = IBMQ.get_provider(hub='ibm-q')
backend = least_busy(
provider.backends(
filters=lambda x: x.configuration().n_qubits >= nqubits
and not x.configuration().simulator
and x.status().operational is True))
# backend = provider.backends.ibmq_armonk
# backend = Aer.get_backend('qasm_simulator')
print("least busy backend: ", backend)
return backend
def get_qrandom(shots, backend, n_qbits):
""" Get a list of quantum random bits.
Args:
shots (int): The number of required circuit measurements.
backend (IBMQBackend): The device to run on.
n_qbits (int, optional): Number of available qbits. Defaults to 5.
Returns:
[list]: A list with uniformly distributed bits.
"""
# Create a Quantum Circuit
circuit = QuantumCircuit(n_qbits)
# Add a H gate on qubit 0
for q in range(n_qbits):
circuit.h(q)
# Map the quantum measurement to the classical bits
# circuit.measure([0,1], [0,1])
circuit.measure_all()
max_shots = backend.configuration().max_shots
if shots < max_shots:
# Execute the circuit on the qasm simulator
print('qrnd_job', ' ', 'shots', shots, 'missing', 0)
job = execute(circuit, backend, shots=shots,
memory=True)
# Grab results from the job
result = job.result()
# Return Memory
mem = result.get_memory(circuit)
else:
mem = []
# split shots over multiple runs.
runs = int(np.ceil(shots/max_shots))
total_shots = 0
for jobno in range(runs):
shots_missing = int(shots - total_shots)
if shots_missing > max_shots:
run_shots = max_shots
else:
run_shots = shots_missing
print('qrnd_job', jobno, 'shots', run_shots, 'missing',
shots_missing)
job = execute(circuit, backend, shots=run_shots,
memory=True)
result = job.result()
partial_mem = result.get_memory(circuit)
mem.extend(partial_mem)
total_shots += run_shots
return mem
def get_array(shape, n_qbits, backend=Aer.get_backend('qasm_simulator')):
"""Generates an array populated with uniformly distributed
numbers in [0, 1].
Args:
shape (tuple): The desired shape of the array.
n_qbits: The number of qbits per machine. Defaults to 5.
backend: The Qiskit backend used the generate the
random numbers.
Defaults to Aer.get_backend('qasm_simulator').
Returns:
[np.array]: An array filled with uniformly distributed numbers.
"""
int_total = np.prod(shape)
shot_total = np.ceil((16./n_qbits)*int_total)
mem = get_qrandom(shots=shot_total, backend=backend,
n_qbits=n_qbits)
bits_total = ''
for m in mem:
bits_total += m
int_lst = []
cint = ''
for b in bits_total:
cint += b
if len(cint) == 16:
int_lst.append(int(cint, 2))
cint = ''
array = np.array(int_lst[:int_total])
# move to [0, 1]
array = array / np.power(2, 16)
array = np.reshape(array, shape)
return array
def get_quantum_uniform(shape, a, b,
n_qbits=5,
backend=Aer.get_backend('qasm_simulator')):
""" Get a numpy array with quantum uniformly initialized numbers
Args:
shape (touple): Desired output array shape
a (float): The lower bound of the uniform distribution
b (float): The upper bound of the uniform distribution
n_qbits (int): The number of qbits to utilize.
backend (optional): Quiskit backend for number generation.
Defaults to Aer.get_backend('qasm_simulator').
Returns:
uniform (nparray): Array initialized to U(a, b).
"""
zero_one = get_array(shape, backend=backend, n_qbits=n_qbits)
spread = np.abs(a) + np.abs(b)
pos_array = zero_one * spread
uniform = pos_array + a
return uniform
if __name__ == '__main__':
import matplotlib.pyplot as plt
rnd_array = get_quantum_uniform([128, 128], a=-1., b=1.,
n_qbits=1)
print(rnd_array.shape)
print('done')
|
https://github.com/theflyingrahul/qiskitsummerschool2020
|
theflyingrahul
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
# pylint: disable=wrong-import-order
"""Main Qiskit public functionality."""
import pkgutil
# First, check for required Python and API version
from . import util
# qiskit errors operator
from .exceptions import QiskitError
# The main qiskit operators
from qiskit.circuit import ClassicalRegister
from qiskit.circuit import QuantumRegister
from qiskit.circuit import QuantumCircuit
# pylint: disable=redefined-builtin
from qiskit.tools.compiler import compile # TODO remove after 0.8
from qiskit.execute import execute
# The qiskit.extensions.x imports needs to be placed here due to the
# mechanism for adding gates dynamically.
import qiskit.extensions
import qiskit.circuit.measure
import qiskit.circuit.reset
# Allow extending this namespace. Please note that currently this line needs
# to be placed *before* the wrapper imports or any non-import code AND *before*
# importing the package you want to allow extensions for (in this case `backends`).
__path__ = pkgutil.extend_path(__path__, __name__)
# Please note these are global instances, not modules.
from qiskit.providers.basicaer import BasicAer
# Try to import the Aer provider if installed.
try:
from qiskit.providers.aer import Aer
except ImportError:
pass
# Try to import the IBMQ provider if installed.
try:
from qiskit.providers.ibmq import IBMQ
except ImportError:
pass
from .version import __version__
from .version import __qiskit_version__
|
https://github.com/Simultonian/hamilutor-qiskit
|
Simultonian
|
from qiskit import QuantumCircuit
def gate_count(circuit: QuantumCircuit):
return dict(circuit.count_ops())
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit_nature.second_q.drivers import PySCFDriver
driver = PySCFDriver()
problem = driver.run()
fermionic_op = problem.hamiltonian.second_q_op()
from qiskit_nature.second_q.mappers import JordanWignerMapper
mapper = JordanWignerMapper()
qubit_jw_op = mapper.map(fermionic_op)
print(qubit_jw_op)
from qiskit_nature.second_q.mappers import ParityMapper
mapper = ParityMapper()
qubit_p_op = mapper.map(fermionic_op)
print(qubit_p_op)
mapper = ParityMapper(num_particles=problem.num_particles)
qubit_op = mapper.map(fermionic_op)
print(qubit_op)
tapered_mapper = problem.get_tapered_mapper(mapper)
print(type(tapered_mapper))
qubit_op = tapered_mapper.map(fermionic_op)
print(qubit_op)
from qiskit_nature.second_q.circuit.library import HartreeFock
hf_state = HartreeFock(2, (1, 1), JordanWignerMapper())
hf_state.draw()
from qiskit_nature.second_q.mappers import InterleavedQubitMapper
interleaved_mapper = InterleavedQubitMapper(JordanWignerMapper())
hf_state = HartreeFock(2, (1, 1), interleaved_mapper)
hf_state.draw()
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, transpile
ghz = QuantumCircuit(15)
ghz.h(0)
ghz.cx(0, range(1, 15))
ghz.draw(output='mpl')
|
https://github.com/AmirhoseynpowAsghari/Qiskit-Tutorials
|
AmirhoseynpowAsghari
|
import numpy as np
import matplotlib.pyplot as plt
# Define a function to create a random Hermitian matrix of size n
def create_random_hermitian_matrix(n):
A = np.random.rand(n, n) + 1j * np.random.rand(n, n)
return A + A.conj().T
# Define the size of the matrix
n = 10
# Create the unperturbed density matrix (ground state)
rho_0_large = create_random_hermitian_matrix(n)
rho_0_large = (rho_0_large + rho_0_large.conj().T) / 2 # Ensure it's Hermitian
# Create a small perturbation matrix
perturbation_large = create_random_hermitian_matrix(n) * 0.05 # Scale it to be a small perturbation
# Linear response: rho(t) = rho_0 + perturbation
rho_linear_large = rho_0_large + perturbation_large
# Multiplicative response: rho(t) = rho_0 * perturbation (element-wise multiplication)
rho_multiplicative_large = rho_0_large * perturbation_large
# Compute the eigenvalues
eigenvalues_rho_0_large = np.linalg.eigvals(rho_0_large)
eigenvalues_linear_large = np.linalg.eigvals(rho_linear_large)
eigenvalues_multiplicative_large = np.linalg.eigvals(rho_multiplicative_large)
# Plot the eigenvalues
fig, ax = plt.subplots(figsize=(12, 6))
x = np.arange(n)
ax.plot(x, eigenvalues_rho_0_large.real, 'o-', label='rho_0')
ax.plot(x, eigenvalues_linear_large.real, 's-', label='Linear (rho_0 + perturbation)')
ax.plot(x, eigenvalues_multiplicative_large.real, 'd-', label='Multiplicative (rho_0 * perturbation)')
ax.set_xticks(x)
ax.set_xticklabels([f'Eigenvalue {i+1}' for i in x])
ax.set_ylabel('Eigenvalues (Real Part)')
ax.set_title('Eigenvalues of the Density Matrix for a Large System')
ax.legend()
plt.show()
|
https://github.com/msramalho/Teach-Me-Quantum
|
msramalho
|
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit import execute
# Choose the drawer you like best:
from qiskit.tools.visualization import matplotlib_circuit_drawer as draw
#from qiskit.tools.visualization import circuit_drawer as draw
from qiskit import IBMQ
IBMQ.load_accounts() # make sure you have setup your token locally to use this
%matplotlib inline
import matplotlib.pyplot as plt
def show_results(D):
# D is a dictionary with classical bits as keys and count as value
# example: D = {'000': 497, '001': 527}
plt.bar(range(len(D)), list(D.values()), align='center')
plt.xticks(range(len(D)), list(D.keys()))
plt.show()
from qiskit import Aer
# See a list of available local simulators
print("Aer backends: ", Aer.backends())
# see a list of available remote backends (these are freely given by IBM)
print("IBMQ Backends: ", IBMQ.backends())
# execute circuit and either display a histogram of the results
def execute_locally(qc, draw_circuit=False):
# Compile and run the Quantum circuit on a simulator backend
backend_sim = Aer.get_backend('qasm_simulator')
job_sim = execute(qc, backend_sim)
result_sim = job_sim.result()
result_counts = result_sim.get_counts(qc)
# Print the results
print("simulation: ", result_sim, result_counts)
if draw_circuit: # draw the circuit
draw(qc)
else: # or show the results
show_results(result_counts)
from qiskit.backends.ibmq import least_busy
import time
# Compile and run on a real device backend
def execute_remotely(qc, draw_circuit=False):
if draw_circuit: # draw the circuit
draw(qc)
try:
# select least busy available device and execute.
least_busy_device = least_busy(IBMQ.backends(simulator=False))
print("Running on current least busy device: ", least_busy_device)
# running the job
job_exp = execute(qc, backend=least_busy_device, shots=1024, max_credits=10)
lapse, interval = 0, 10
while job_exp.status().name != 'DONE':
print('Status @ {} seconds'.format(interval * lapse))
print(job_exp.status())
time.sleep(interval)
lapse += 1
print(job_exp.status())
exp_result = job_exp.result()
result_counts = exp_result.get_counts(qc)
# Show the results
print("experiment: ", exp_result, result_counts)
if not draw_circuit: # show the results
show_results(result_counts)
except:
print("All devices are currently unavailable.")
def new_circuit(size):
# Create a Quantum Register with size qubits
qr = QuantumRegister(size)
# Create a Classical Register with size bits
cr = ClassicalRegister(size)
# Create a Quantum Circuit acting on the qr and cr register
return qr, cr, QuantumCircuit(qr, cr)
# H gate on qubit 0
# measure the specific qubit
# H gate on qubit 1
# measure the specific qubit
# CNOT gate
# measure the specific qubit
# H gate on 2 qubits
# CNOT gate
# measure
# measure
# execute_remotely(circuit)
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# -*- 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.
"""
This module contains the definition of a base class for quantum fourier transforms.
"""
from abc import abstractmethod
from qiskit import QuantumRegister, QuantumCircuit
from qiskit.aqua import Pluggable, AquaError
class QFT(Pluggable):
"""Base class for QFT.
This method should initialize the module and its configuration, and
use an exception if a component of the module is
available.
Args:
configuration (dict): configuration dictionary
"""
@abstractmethod
def __init__(self, *args, **kwargs):
super().__init__()
@classmethod
def init_params(cls, params):
qft_params = params.get(Pluggable.SECTION_KEY_QFT)
kwargs = {k: v for k, v in qft_params.items() if k != 'name'}
return cls(**kwargs)
@abstractmethod
def _build_matrix(self):
raise NotImplementedError
@abstractmethod
def _build_circuit(self, qubits=None, circuit=None, do_swaps=True):
raise NotImplementedError
def construct_circuit(self, mode='circuit', qubits=None, circuit=None, do_swaps=True):
"""Construct the circuit.
Args:
mode (str): 'matrix' or 'circuit'
qubits (QuantumRegister or qubits): register or qubits to build the circuit on.
circuit (QuantumCircuit): circuit for construction.
do_swaps (bool): include the swaps.
Returns:
The matrix or circuit depending on the specified mode.
"""
if mode == 'circuit':
return self._build_circuit(qubits=qubits, circuit=circuit, do_swaps=do_swaps)
elif mode == 'matrix':
return self._build_matrix()
else:
raise AquaError('Unrecognized mode: {}.'.format(mode))
|
https://github.com/FilipeChagasDev/register-by-constant-qft-adder
|
FilipeChagasDev
|
#By Filipe Chagas
#2022
import qiskit
from math import *
def qft(n: int) -> qiskit.circuit.Gate:
"""Returns a QFT gate for n qubits.
:param n: Number of target qubits.
:type n: int
:return: QFT gate.
:rtype: qiskit.circuit.Gate
"""
def rotations(my_circuit: qiskit.circuit.Gate, m: int):
if m == 0:
return my_circuit
else:
my_circuit.h(m-1) #Add a Haddamard gate to the most significant qubit
for i in range(m-1):
my_circuit.crz(pi/(2**(m-1-i)), i, m-1)
rotations(my_circuit, m-1)
my_circuit = qiskit.QuantumCircuit(n, name='QFT')
rotations(my_circuit, n)
for m in range(n//2):
my_circuit.swap(m, n-m-1)
return my_circuit.to_gate()
|
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 qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z)
from qiskit.opflow import Zero, One, I, X, Y, Z
from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer
from qiskit.tools.monitor import job_monitor
from qiskit.circuit import Parameter
from qiskit.transpiler.passes import RemoveBarriers
# Import QREM package
from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter
from qiskit.ignis.mitigation import expectation_value
# Import mitiq for zne
import mitiq
# Import state tomography modules
from qiskit.ignis.verification.tomography import state_tomography_circuits
from qiskit.quantum_info import state_fidelity
import sys
import importlib
sys.path.append("./")
import circuit_utils, zne_utils, tomography_utils, sgs_algorithm
importlib.reload(circuit_utils)
importlib.reload(zne_utils)
importlib.reload(tomography_utils)
importlib.reload(sgs_algorithm)
from circuit_utils import *
from zne_utils import *
from tomography_utils import *
from sgs_algorithm import *
# Combine subcircuits into a single multiqubit gate representing a single trotter step
num_qubits = 3
# The final time of the state evolution
target_time = np.pi
# Parameterize variable t to be evaluated at t=pi later
dt = Parameter('t')
# Convert custom quantum circuit into a gate
trot_gate = trotter_gate(dt)
# initial layout
initial_layout = [5,3,1]
# Number of trotter steps
num_steps = 100
print("trotter step: ", num_steps)
scale_factors = [1.0, 2.0, 3.0]
# scale_factors = [1.0, 2.0, 3.0]
# Initialize quantum circuit for 3 qubits
qr = QuantumRegister(num_qubits, name="lq")
qc = QuantumCircuit(qr)
# Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>)
make_initial_state(qc, "110") # DO NOT MODIFY (|q_5,q_3,q_1> = |110>)
subspace_encoder_init110(qc, targets=[0, 1, 2]) # encode
trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian
subspace_decoder(qc, targets=[0,1,2]) # decode
# Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time
qc = qc.bind_parameters({dt: target_time / num_steps})
print("created qc")
# Generate state tomography circuits to evaluate fidelity of simulation
st_qcs = state_tomography_circuits(qc, [0, 1, 2][::-1]) #! state tomography requires === BIG ENDIAN ===
print("created st_qcs (length:", len(st_qcs), ")")
# remove barriers
st_qcs = [RemoveBarriers()(qc) for qc in st_qcs]
print("removed barriers from st_qcs")
# optimize circuit
t3_st_qcs = transpile(st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"])
print("created t3_st_qcs (length:", len(t3_st_qcs), ")")
# zne wrapping
zne_qcs = zne_wrapper(t3_st_qcs, scale_factors=scale_factors)
print("created zne_qcs (length:", len(zne_qcs), ")")
t3_zne_qcs = transpile(zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout)
print("created t3_zne_qcs (length:", len(t3_zne_qcs), ")")
t3_zne_qcs[-3].draw("mpl")
from qiskit.test.mock import FakeJakarta
backend = FakeJakarta()
# backend = Aer.get_backend("qasm_simulator")
# IBMQ.load_account()
# provider = IBMQ.get_provider(hub='ibm-q-utokyo', group='internal', project='hirashi-jst')
# provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22')
# print("provider:", provider)
# backend = provider.get_backend("ibmq_jakarta")
shots = 1 << 13
reps = 1 # unused
# Number of trotter steps
print("trotter step: ", num_steps)
# execute: reps = 1
job = execute(t3_zne_qcs, backend, shots=shots) # 毎回チェック: ここちゃんと変えた?
print('Job ID', job.job_id())
# QREM
qr = QuantumRegister(num_qubits)
meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal')
cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout = initial_layout)
print('Job ID', cal_job.job_id())
cal_results = cal_job.result()
meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal')
mit_results = meas_fitter.filter.apply(job.result())
zne_expvals = zne_decoder(num_qubits, mit_results, scale_factors=scale_factors, fac_type="lin")
target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!!
rho = expvals_to_valid_rho(num_qubits, zne_expvals)
fidelity = state_fidelity(rho, target_state)
print(fidelity)
|
https://github.com/menegolli/Quantum_synth
|
menegolli
|
#!/usr/bin/env python
# coding: utf-8
# In[44]:
from qiskit import *
import numpy as np
#import NewBackends
import random
import sys
from backends_select import ChooseBackEnd
# In[64]:
def GenerateCircuitSingleNote(circuit, note_id):
'''
Adds to the circuit the gates to measure a given note.
'''
if (note_id >= 12):
sys.exit("Note must be an integer smaller than 11 and larger (or equal) to 0.")
bitstring = str(bin(note_id)[2:])
bitstring = "0"*(4-len(bitstring))+bitstring
for i in range(len(bitstring)):
if bitstring[len(bitstring)-1-i] == "1":
circuit.x(i)
def BellStateGenerationTwoQubits(quantumCircuit, firstQubit=0, secondQubit=1, specificEntangledState="Phi"):
if specificEntangledState == "Phi":
quantumCircuit.h(firstQubit)
quantumCircuit.cx(firstQubit, secondQubit)
elif specificEntangledState == "Psi":
quantumCircuit.h(firstQubit)
quantumCircuit.x(secondQubit)
quantumCircuit.cx(firstQubit, secondQubit)
def ChooseEqualSuperposition(quantumCircuit, states):
desiredVector = np.zeros(2**quantumCircuit.n_qubits)
flag = 1
for k in states:
if 0 <= k <= 11:
desiredVector[k] = 1/np.sqrt(len(states))
flag = flag*1
else:
flag = flag*0
if flag == 1:
quantumCircuit.initialize(desiredVector, range(4))
def ChooseEqualSuperpositionRandom(quantumCircuit):
randomNumberOfNotes = np.random.randint(2,13)
listModes = list(range(12))
listToSuperimpose = []
for i in range(randomNumberOfNotes):
tmp = random.choice(listModes)
listToSuperimpose.append(tmp)
listModes.remove(tmp)
ChooseEqualSuperposition(quantumCircuit, listToSuperimpose)
def Hadamard(quantumCircuit, listOfQubits):
for k in listOfQubits:
if 0 <= k <= quantumCircuit.n_qubits:
quantumCircuit.h(k)
def RandomRotation(quantumCircuit):
for k in range(quantumCircuit.n_qubits):
quantumCircuit.u3(q=k, theta = np.random.random()*2*np.pi, phi = np.random.random()*np.pi, lam = np.random.random()*np.pi)
def __multiplecz(quantumCircuit, target, initialLength):
quantumCircuit.ccx(0,1, initialLength)
for k in range(2, initialLength-1):
quantumCircuit.ccx(k, initialLength+k-2, initialLength+k-1)
quantumCircuit.cz(quantumCircuit.n_qubits-1, initialLength-1)
for k in reversed(range(2, initialLength-1)):
quantumCircuit.ccx(k, initialLength+k-2, initialLength+k-1)
quantumCircuit.ccx(0,1, initialLength)
def Grover(quantumCircuit, target, initialLength):
for k in range(initialLength):
quantumCircuit.h(k)
ancillaQubit = QuantumRegister(2)
quantumCircuit.add_register(ancillaQubit)
for n in range(int(np.round(np.pi/4*np.sqrt(2**initialLength)))):
for singleBit in range(initialLength):
if target[initialLength-singleBit-1] == '0':
quantumCircuit.x(singleBit)
__multiplecz(quantumCircuit, target, initialLength)
for singleBit in range(initialLength):
if target[initialLength-singleBit-1] == '0':
quantumCircuit.x(singleBit)
for qubit in range(initialLength):
quantumCircuit.h(qubit)
quantumCircuit.x(qubit)
__multiplecz(quantumCircuit, target, initialLength)
for qubit in range(initialLength):
quantumCircuit.x(qubit)
quantumCircuit.h(qubit)
def AmplitudeAmplification(quantumCircuit, target, initialLength, numIterations):
for k in range(initialLength):
quantumCircuit.h(k)
ancillaQubit = QuantumRegister(2)
quantumCircuit.add_register(ancillaQubit)
for n in range(numIterations):
for singleBit in range(initialLength):
if target[initialLength - singleBit - 1] == '0':
quantumCircuit.x(singleBit)
__multiplecz(quantumCircuit, target, initialLength)
for singleBit in range(initialLength):
if target[initialLength - singleBit - 1] == '0':
quantumCircuit.x(singleBit)
for qubit in range(initialLength):
quantumCircuit.h(qubit)
quantumCircuit.x(qubit)
__multiplecz(quantumCircuit, target, initialLength)
for qubit in range(initialLength):
quantumCircuit.x(qubit)
quantumCircuit.h(qubit)
def HalfFilledSuperposition(quantumCircuit, number):
desiredVector=np.zeros(16)
for k in range(number//2):
desiredVector[k] = 1./np.sqrt(number/2.)
quantumCircuit.initialize(desiredVector, range(4))
def GroverSequence(target, initialLength,backendType,RealDeviceName,noisePresent):
iterations = []
for k in range(4):
temporaryQuantumCircuit = QuantumCircuit(initialLength, initialLength)
AmplitudeAmplification(temporaryQuantumCircuit, target, initialLength, k)
print(target)
# listForMusic = ChooseBackEnd(music, backendType=mystr[0], qubitsToBeMeasured=range(4),
# numberShots=int(mystr[3]), noisePresent=True, RealDeviceName=mystr[1])
iterations.append(ChooseBackEnd(quantumCircuit=temporaryQuantumCircuit, noisePresent=noisePresent,backendType=backendType,qubitsToBeMeasured=range(4),RealDeviceName=RealDeviceName))
# ChooseBackEnd(quantumCircuit=temporaryQuantumCircuit, noisePresent=True,backendType=backendType,qubitsToBeMeasured=range(4),RealDeviceName=RealDeviceName)
del (temporaryQuantumCircuit)
return iterations
|
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/sebasmos/QuantumVE
|
sebasmos
|
# !pip install qiskit torch torchvision matplotlib
# !pip install qiskit-machine-learning
# !pip install torchviz
# !pip install qiskit[all]
# !pip install qiskit == 0.45.2
# !pip install qiskit_algorithms == 0.7.1
# !pip install qiskit-ibm-runtime == 0.17.0
# !pip install qiskit-aer == 0.13.2
# #Quentum net draw
# !pip install pylatexenc
import os
MODEL_METADATA = "SVM"
model_name = "efficientnet_b3_embeddings_feat_space_16"#"efficientnet_v2_m"#"convnext_base"#"efficientnet_b3"#"mobileNet"
results_path = f"{model_name}/{MODEL_METADATA}"
os.makedirs(results_path, exist_ok = True)
train_path = f"{model_name}/train"
val_path = f"{model_name}/val"
os.makedirs(train_path, exist_ok = True)
os.makedirs(val_path, exist_ok=True)
from qiskit_algorithms.utils import algorithm_globals
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
from qiskit.circuit.library import ZZFeatureMap
from qiskit.primitives import Sampler
from qiskit_algorithms.state_fidelities import ComputeUncompute
from qiskit_machine_learning.kernels import FidelityQuantumKernel
from sklearn.metrics import confusion_matrix, classification_report
algorithm_globals.random_seed = 12345
train_embeddings = pd.read_csv(f'{train_path}/train_embeddings.csv')
val_embeddings = pd.read_csv(f'{val_path}/val_embeddings.csv')
print(f"Reading embeddings from: ", train_path)
# Prepare data for training
train_features = train_embeddings.iloc[:, :-1].values # Features
y_train = train_embeddings.iloc[:, -1].values # Labels
test_features = val_embeddings.iloc[:, :-1].values # Features
y_val = val_embeddings.iloc[:, -1].values # Labels
plt.figure(figsize=(18, 5))
ax = sns.countplot(x=y_train, palette='tab10')
total = len(y_train)
for p in ax.patches:
percentage = f'{100 * p.get_height() / total:.1f}%\n'
x = p.get_x() + p.get_width() / 2
y = p.get_height()
ax.annotate(percentage, (x, y), ha='center', va='center')
plt.show()
adhoc_dimension = 16
"""
class 0 : {0,2}
class 1 : {1,3}
"""
label_map = {0: 0,
1: 1,
2: 0,
3: 1,
4: 0}
# Merge labels using the dictionary
Y_train = np.array([label_map[label] for label in y_train])
y_test = np.array([label_map[label] for label in y_val])
print("labels_train:", np.unique(Y_train))
print("test_labels:", np.unique(y_test))
plt.figure(figsize=(18, 5))
ax = sns.countplot(x=Y_train, palette='tab10')
total = len(Y_train)
for p in ax.patches:
percentage = f'{100 * p.get_height() / total:.1f}%\n'
x = p.get_x() + p.get_width() / 2
y = p.get_height()
ax.annotate(percentage, (x, y), ha='center', va='center')
plt.show()
print(train_features.shape, Y_train.shape)
print(test_features.shape, y_test.shape)
adhoc_feature_map = ZZFeatureMap(feature_dimension=adhoc_dimension, reps=2, entanglement="linear")
sampler = Sampler()
fidelity = ComputeUncompute(sampler=sampler)
adhoc_kernel = FidelityQuantumKernel(fidelity=fidelity, feature_map=adhoc_feature_map)
train_features.shape
print(train_features.shape, Y_train.shape)
print(test_features.shape, y_test.shape)
# train_features = train_features[:100]
# test_features = test_features[:20]
# Y_train = Y_train[:100]
# y_test = y_test[:20]
train_features.shape, test_features.shape, Y_train.shape, y_test.shape
import time
from sklearn.metrics import accuracy_score, precision_score, f1_score, recall_score, fbeta_score
from sklearn.svm import SVC
# Start timer for training
start_train = time.time()
adhoc_svc = SVC(kernel=adhoc_kernel.evaluate)
adhoc_svc.fit(train_features, Y_train)
# End timer for training
end_train = time.time()
# Start timer for inference
start_inference = time.time()
predictions = adhoc_svc.predict(test_features)
# End timer for inference
end_inference = time.time()
accuracy = accuracy_score(y_test, predictions)
precision = precision_score(y_test, predictions, average='weighted')
f1 = f1_score(y_test, predictions, average='weighted')
recall = recall_score(y_test, predictions, average='weighted')
fbeta_75 = fbeta_score(y_test, predictions, beta=0.75, average='weighted')
# Print metrics and time
print(f"Accuracy: {accuracy} Precision: {precision} F1 Score: {f1} Recall: {recall} F0.75 Score: {fbeta_75}")
print(f"Training time: {end_train - start_train} seconds")
print(f"Inference time: {end_inference - start_inference} seconds")
unique_classes = np.unique(np.concatenate(((predictions, y_test))))
confusion_mat = confusion_matrix(predictions, y_test, labels=unique_classes)
conf_matrix = pd.DataFrame(confusion_mat, index=unique_classes, columns=unique_classes)
# Plot the confusion matrix using seaborn
plt.figure(figsize=(5, 4))
ax = sns.heatmap(conf_matrix, annot=True, fmt='.1f', cmap=sns.cubehelix_palette(as_cmap=True), linewidths=0.1, cbar=True)
# Set labels and ticks
ax.set_xlabel('Predicted Labels')
ax.set_ylabel('True Labels')
# Set x and y ticks using the unique classes
ax.set_xticks(range(len(unique_classes)))
ax.set_yticks(range(len(unique_classes)))
# Set x and y ticks at the center of the cells
ax.set_xticks([i + 0.5 for i in range(len(unique_classes))])
ax.set_yticks([i + 0.5 for i in range(len(unique_classes))])
plt.show()
report = classification_report(y_test,predictions, target_names=unique_classes,output_dict=True)# Mostrar el informe de
df = pd.DataFrame(report).transpose()
df.to_csv(os.path.join(results_path, f"confusion_matrix_{MODEL_METADATA}.csv"))
print(df)
|
https://github.com/vandnaChaturvedi/Qauntum_algorithms_Qiskit
|
vandnaChaturvedi
|
# Importing standard Qiskit libraries
from qiskit import QuantumCircuit, execute, Aer, IBMQ, QuantumRegister, ClassicalRegister
from qiskit.compiler import transpile, assemble
from qiskit.tools.jupyter import *
from qiskit.visualization import *
from qiskit.circuit.library import QFT
from numpy import pi
from qiskit.quantum_info import Statevector
from matplotlib import pyplot as plt
import numpy as np
# Loading your IBM Q account(s)
provider = IBMQ.load_account()
one_step_circuit = QuantumCircuit(6, name=' ONE STEP')
# Coin operator
one_step_circuit.h([4,5])
one_step_circuit.z([4,5])
one_step_circuit.cz(4,5)
one_step_circuit.h([4,5])
one_step_circuit.draw()
# Shift operator function for 4d-hypercube
def shift_operator(circuit):
for i in range(0,4):
circuit.x(4)
if i%2==0:
circuit.x(5)
circuit.ccx(4,5,i)
shift_operator(one_step_circuit)
one_step_gate = one_step_circuit.to_instruction()
one_step_circuit.draw()
one_step_circuit.inverse().draw()
# Make controlled gates
inv_cont_one_step = one_step_circuit.inverse().control()
inv_cont_one_step_gate = inv_cont_one_step.to_instruction()
cont_one_step = one_step_circuit.control()
cont_one_step_gate = cont_one_step.to_instruction()
inv_qft_gate = QFT(4, inverse=True).to_instruction()
qft_gate = QFT(4, inverse=False).to_instruction()
QFT(4, inverse=True).decompose().draw("mpl")
phase_circuit = QuantumCircuit(6, name=' phase oracle ')
# Mark 1011
phase_circuit.x(2)
phase_circuit.h(3)
phase_circuit.mct([0,1,2], 3)
phase_circuit.h(3)
phase_circuit.x(2)
# Mark 1111
phase_circuit.h(3)
phase_circuit.mct([0,1,2],3)
phase_circuit.h(3)
phase_oracle_gate = phase_circuit.to_instruction()
# Phase oracle circuit
phase_oracle_circuit = QuantumCircuit(11, name=' PHASE ORACLE CIRCUIT ')
phase_oracle_circuit.append(phase_oracle_gate, [4,5,6,7,8,9])
phase_circuit.draw()
# Mark q_4 if the other qubits are non-zero
mark_auxiliary_circuit = QuantumCircuit(5, name=' mark auxiliary ')
mark_auxiliary_circuit.x([0,1,2,3,4])
mark_auxiliary_circuit.mct([0,1,2,3], 4)
mark_auxiliary_circuit.z(4)
mark_auxiliary_circuit.mct([0,1,2,3], 4)
mark_auxiliary_circuit.x([0,1,2,3,4])
mark_auxiliary_gate = mark_auxiliary_circuit.to_instruction()
mark_auxiliary_circuit.draw()
# Phase estimation
phase_estimation_circuit = QuantumCircuit(11, name=' phase estimation ')
phase_estimation_circuit.h([0,1,2,3])
for i in range(0,4):
stop = 2**i
for j in range(0,stop):
phase_estimation_circuit.append(cont_one_step, [i,4,5,6,7,8,9])
# Inverse fourier transform
phase_estimation_circuit.append(inv_qft_gate, [0,1,2,3])
# Mark all angles theta that are not 0 with an auxiliary qubit
phase_estimation_circuit.append(mark_auxiliary_gate, [0,1,2,3,10])
# Reverse phase estimation
phase_estimation_circuit.append(qft_gate, [0,1,2,3])
for i in range(3,-1,-1):
stop = 2**i
for j in range(0,stop):
phase_estimation_circuit.append(inv_cont_one_step, [i,4,5,6,7,8,9])
phase_estimation_circuit.barrier(range(0,10))
phase_estimation_circuit.h([0,1,2,3])
# Make phase estimation gate
phase_estimation_gate = phase_estimation_circuit.to_instruction()
phase_estimation_circuit.draw()
# Implementation of the full quantum walk search algorithm
theta_q = QuantumRegister(4, 'theta')
node_q = QuantumRegister(4, 'node')
coin_q = QuantumRegister(2, 'coin')
auxiliary_q = QuantumRegister(1, 'auxiliary')
creg_c2 = ClassicalRegister(4, 'c')
circuit = QuantumCircuit(theta_q, node_q, coin_q, auxiliary_q, creg_c2)
# Apply Hadamard gates to the qubits that represent the nodes and the coin
circuit.h([4,5,6,7,8,9])
iterations = 2
for i in range(0,iterations):
circuit.append(phase_oracle_gate, [4,5,6,7,8,9])
circuit.append(phase_estimation_gate, [0,1,2,3,4,5,6,7,8,9,10])
circuit.measure(node_q[0], creg_c2[0])
circuit.measure(node_q[1], creg_c2[1])
circuit.measure(node_q[2], creg_c2[2])
circuit.measure(node_q[3], creg_c2[3])
circuit.draw()
backend = Aer.get_backend('qasm_simulator')
job = execute( circuit, backend, shots=1024 )
hist = job.result().get_counts()
plot_histogram( hist )
import qiskit.tools.jupyter
%qiskit_version_table
|
https://github.com/ColibrITD-SAS/mpqp
|
ColibrITD-SAS
|
from mpqp.gates import *
from mpqp.execution.result import Result
from mpqp import QCircuit, Barrier
from mpqp.execution import run, IBMDevice
from math import floor
import numpy as np
class QFT(QCircuit):
def __init__(self,n_qubits,inverse=False):
super().__init__(n_qubits, nb_cbits=n_qubits)
self.inverse = inverse
self._build()
def _build(self):
for j in range(self.nb_qubits):
self.add(H(j))
self.add([CRk(i+1, i, j) for i in range(j+1, self.nb_qubits)])
self.add(Barrier())
self.add([SWAP(i, self.nb_qubits-1-i) for i in range(int(floor(self.nb_qubits / 2)))])
if self.inverse == True:
self.inverse()
qft_5 = QFT(n_qubits=5)
print(qft_5)
result = run(qft_5, IBMDevice.AER_SIMULATOR_STATEVECTOR)
if isinstance(result, Result):
print(result.amplitudes)
qc1 = QCircuit([H(1)]) + QFT(2)
print(qc1)
result1 = run(qc1, IBMDevice.AER_SIMULATOR_STATEVECTOR)
if isinstance(result1, Result):
print(result1.amplitudes)
W_circuit = QCircuit([Ry(2*np.arccos(1/np.sqrt(3)),0),Ry(-np.pi/4,1),CZ(0,1),Ry(np.pi/4,1),CNOT(1,2),CNOT(0,1),X(0)])
qc2 = W_circuit + QFT(3)
print(qc2)
result2 = run(qc2, IBMDevice.AER_SIMULATOR_STATEVECTOR)
if isinstance(result2, Result):
print(result2.amplitudes)
|
https://github.com/pedrotelez/QuantumHelloWorld
|
pedrotelez
|
from qiskit import QuantumCircuit, execute, Aer, BasicAer
from qiskit.visualization import plot_state_qsphere, plot_histogram, plot_bloch_multivector
from qiskit.quantum_info import Statevector
import numpy as np
# numero de qubits do circuito
n = 4
# inicializando o circuito
qft = QuantumCircuit(n, n, name = "QFT")
for i in range(n-1, -1, -1):
#começa do último bit que só tem uma porta H
qft.h(i)
fase = 0
for j in range(i):
#conecta as portas de fase nos bits anteriores
fase +=1
qft.cp(np.pi/(2**fase), i - j -1, i)
#para melhorar a visualização
qft.barrier()
for i in range(int(n/2)):
#Operação de swap
qft.swap(i, n-1-i)
qft.draw('mpl')
sv = Statevector.from_label("1010")
plot_bloch_multivector(sv)
qft_sv = sv.evolve(qft) #aplica a QFT nos qubits
plot_bloch_multivector(qft_sv)
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
number = 5 # integer
real = -3.4 # float
name = 'Asja' # string
surname = "Sarkana" # string
boolean1 = True # Boolean
boolean1 = False # Boolean
a = 13
b = 5
print("a =",a)
print("b =",b)
print()
# basics operators
print("a + b =",a+b)
print("a - b =",a-b)
print("a * b =",a*b)
print("a / b =",a/b)
a = 13
b = 5
print("a =",a)
print("b =",b)
print()
# integer division
print("a//b =",a//b)
# modulus operator
print("a mod b =",a % b)
b = 5
print("b =",b)
print()
print("b*b =",b**2)
print("b*b*b =",b**3)
print("sqrt(b)=",b**0.5)
# list
mylist = [10,8,6,4,2]
print(mylist)
# tuple
mytuple=(1,4,5,'Asja')
print(mytuple)
# dictionary
mydictionary = {
'name' : "Asja",
'surname':'Sarkane',
'age': 23
}
print(mydictionary)
print(mydictionary['surname'])
# list of the other objects or variables
list_of_other_objects =[
mylist,
mytuple,
3,
"Asja",
mydictionary
]
print(list_of_other_objects)
# length of a string
print(len("Asja Sarkane"))
# size of a list
print(len([1,2,3,4]))
# size of a dictionary
mydictionary = { 'name' : "Asja", 'surname':'Sarkane', 'age': 23}
print(len(mydictionary))
i = 10
while i>0: # while condition(s):
print(i)
i = i - 1
for i in range(10): # i is in [0,1,...,9]
print(i)
for i in range(-5,6): # i is in [-5,-4,...,0,...,4,5]
print(i)
for i in range(0,23,4): # i is in [0,4,8,12,16,20]
print(i)
for i in [3,8,-5,11]:
print(i)
for i in "Sarkane":
print(i)
# dictionary
mydictionary = {
'name' : "Asja",
'surname':'Sarkane',
'age': 23,
}
for key in mydictionary:
print("key is",key,"and its value is",mydictionary[key])
for a in range(4,7):
# if condition(s)
if a<5:
print(a,"is less than 5")
# elif conditions(s)
elif a==5:
print(a,"is equal to 5")
# else
else:
print(a,"is greater than 5")
# Logical operator "and"
i = -3
j = 4
if i<0 and j > 0:
print(i,"is negative AND",j,"is positive")
# Logical operator "or"
i = -2
j = 2
if i==2 or j == 2:
print("i OR j is 2: (",i,",",j,")")
# Logical operator "not"
i = 3
if not (i==2):
print(i,"is NOT equal to 2")
# Operator "equal to"
i = -1
if i == -1:
print(i,"is EQUAL TO -1")
# Operator "not equal to"
i = 4
if i != 3:
print(i,"is NOT EQUAL TO 3")
# Operator "not equal to"
i = 2
if i <= 5:
print(i,"is LESS THAN OR EQUAL TO 5")
# Operator "not equal to"
i = 5
if i >= 1:
print(i,"is GREATER THAN OR EQUAL TO 3")
A =[
[1,2,3],
[-2,-4,-6],
[3,6,9]
]
# print all
print(A)
print()
# print list by list
for list in A:
print(list)
list1 = [1,2,3]
list2 = [4,5,6]
#concatenation of two lists
list3 = list1 + list2
print(list3)
list4 = list2 + list1
print(list4)
list = [0,1,2]
list.append(3)
print(list)
list = list + [4]
print(list)
def summation_of_integers(n):
summation = 0
for integer in range(n+1):
summation = summation + integer
return summation
print(summation_of_integers(10))
print(summation_of_integers(20))
from random import randrange
print(randrange(10),"is picked randomly between 0 and 9")
print(randrange(-9,10),"is picked randomly between -9 and 9")
print(randrange(0,20,3),"is picked randomly from the list [0,3,6,9,12,15,18]")
|
https://github.com/thyung/qiskit_factorization
|
thyung
|
import numpy as np
from numpy import pi
from qiskit import QuantumCircuit, Aer, transpile
from qiskit.visualization import plot_histogram, plot_bloch_multivector
from qiskit.circuit import QuantumRegister, ClassicalRegister
sim = Aer.get_backend('statevector_simulator')
qc = QuantumCircuit(3)
init_state = '101'
qc.initialize(init_state)
qc.barrier()
qc.h(2)
qc.cp(pi/2, 1, 2)
qc.cp(pi/4, 0, 2)
qc.h(1)
qc.cp(pi/2, 0, 1)
qc.h(0)
qc.swap(0, 2)
display(qc.draw())
sv = sim.run(qc).result().get_statevector()
plot_bloch_multivector(sv)
from qiskit.circuit.library import QFT
qc2 = QuantumCircuit(3)
qc2.initialize(init_state)
qc2.append(QFT(num_qubits=3), [0, 1, 2])
display(qc2.draw())
sv2 = sim.run(transpile(qc2, sim)).result().get_statevector()
plot_bloch_multivector(sv2)
# implement general QFT
def myqft(n):
qc = QuantumCircuit(n)
for i in reversed(range(n)):
qc.h(i)
for e, j in enumerate(reversed(range(i))):
qc.cp(pi/2**(e+1), j, i)
for i in range(n//2):
qc.swap(i, n-i-1)
return qc.to_gate(label='myqft{}'.format(n))
qc3 = QuantumCircuit(3)
qc3.initialize(init_state)
qc3.append(myqft(3), [0, 1, 2])
display(qc3.draw())
sv3 = sim.run(transpile(qc3, sim)).result().get_statevector()
plot_bloch_multivector(sv3)
def create_carrier(name=None):
qc = QuantumCircuit(4)
qc.toffoli(1, 2, 3)
qc.cx(1, 2)
qc.toffoli(0, 2, 3)
return qc.to_gate(label=name or 'carrier')
def create_carrier_inv(name=None):
qc = QuantumCircuit(4)
qc.append(create_carrier().inverse(), range(4))
return qc.to_gate(label=name or 'carrier_inv')
def create_sum(name=None):
qc = QuantumCircuit(3)
qc.cx(1, 2)
qc.cx(0, 2)
return qc.to_gate(label=name or 'sum')
def create_sum_inv(name=None):
qc = QuantumCircuit(3)
qc.append(create_sum().inverse(), range(3))
return qc.to_gate(label=name or 'sum_inv')
a = QuantumRegister(3, 'a')
b = QuantumRegister(4, 'b')
c = QuantumRegister(3, 'c')
creg = ClassicalRegister(4, 'creg')
qc = QuantumCircuit(a, b, c, creg)
qc.x(a[0])
qc.x(a[1])
qc.x(b[1])
qc.x(b[2])
qc.append(create_carrier(), [c[0], a[0], b[0], c[1]])
qc.append(create_carrier(), [c[1], a[1], b[1], c[2]])
qc.append(create_carrier(), [c[2], a[2], b[2], b[3]])
qc.cx(a[2], b[2])
qc.append(create_sum(), [c[2], a[2], b[2]])
qc.append(create_carrier_inv(), [c[1], a[1], b[1], c[2]])
qc.append(create_sum(), [c[1], a[1], b[1]])
qc.append(create_carrier_inv(), [c[0], a[0], b[0], c[1]])
qc.append(create_sum(), [c[0], a[0], b[0]])
qc.barrier()
qc.measure(b, creg)
display(qc.draw())
backend = Aer.get_backend('qasm_simulator')
job = backend.run(transpile(qc, backend), shots=1024)
counts = job.result().get_counts()
print(counts)
def create_adder(n):
"""create adder with n bits a, n+1 bits b and n bits carrier"""
a = QuantumRegister(n, 'a')
b = QuantumRegister(n+1, 'b')
c = QuantumRegister(n, 'c')
qc = QuantumCircuit(a, b, c)
for i in range(n-1):
qc.append(create_carrier(), [c[i], a[i], b[i], c[i+1]])
qc.append(create_carrier(), [c[n-1], a[n-1], b[n-1], b[n]])
qc.cx(a[n-1], b[n-1])
qc.append(create_sum(), [c[n-1], a[n-1], b[n-1]])
for i in reversed(range(n-1)):
qc.append(create_carrier_inv(), [c[i], a[i], b[i], c[i+1]])
qc.append(create_sum(), [c[i], a[i], b[i]])
return qc.to_gate(label='adder')
def create_adder_inv(n):
qc = QuantumCircuit(3*n+1)
qc.append(create_adder(n).inverse(), range(3*n+1))
return qc.to_gate(label='adder_inv')
qc = QuantumCircuit(10, 4)
qc.x(0)
qc.x(1)
qc.x(4)
qc.x(5)
qc.append(create_adder(3), range(10))
qc.measure([3, 4, 5, 6], range(4))
display(qc.draw())
backend = Aer.get_backend('qasm_simulator')
job = backend.run(transpile(qc, backend), shots=1024)
counts = job.result().get_counts()
print(counts)
def create_adder_mod(n, bigN):
"""
:param n: number of bits for a, c and bigN; b has n+1 bits
:param bigN: mod number
:return: Gate of 4n+2 qubits
0-2 qubits for a
3-6 qubits for b
7-9 qubits for c (init to 0)
10-12 qubits for bigN (init to bigN when use)
13 qubit for temp (init to 0)
"""
a = QuantumRegister(n, 'a')
b = QuantumRegister(n+1, 'b')
c = QuantumRegister(n, 'c')
bN = QuantumRegister(n, 'bigN')
t = QuantumRegister(1, 't')
qc = QuantumCircuit(a, b, c, bN, t)
# block 1
qc.append(create_adder(n), list(a)+list(b)+list(c))
for i in range(n):
qc.swap(a[i], bN[i])
qc.append(create_adder_inv(n), list(a)+list(b)+list(c))
qc.x(b[n])
qc.cx(b[n], t[0])
qc.x(b[n])
tempN = bigN
i = 0
while tempN != 0:
if tempN % 2 != 0:
qc.cx(t[0], a[i])
i = i + 1
tempN = tempN // 2
qc.append(create_adder(n), list(a)+list(b)+list(c))
tempN = bigN
i = 0
while tempN != 0:
if tempN % 2 != 0:
qc.cx(t[0], a[i])
i = i + 1
tempN = tempN // 2
for i in range(n):
qc.swap(a[i], bN[i])
# block 2
qc.append(create_adder_inv(n), list(a)+list(b)+list(c))
qc.cx(b[n], t[0])
qc.append(create_adder(n), list(a)+list(b)+list(c))
#display(qc.draw())
return qc.to_gate(label='adder_mod')
n = 3
bigN = 5
#qc = QuantumCircuit(4*n+2)
a = QuantumRegister(n, 'a')
b = QuantumRegister(n+1, 'b')
c = QuantumRegister(n, 'c')
bN = QuantumRegister(n, 'bigN')
t = QuantumRegister(1, 't')
creg = ClassicalRegister(4, 'creg')
qc = QuantumCircuit(a, b, c, bN, t, creg)
# qc.x(a[0]) # a = 3
# qc.x(a[1])
qc.x(a[2]) # a = 4
qc.x(b[2]) # b = 4
qc.x(bN[0])
qc.x(bN[2]) # bN = 5
qc.append(create_adder_mod(n, bigN), list(a) + list(b) + list(c) + list(bN) + list(t))
qc.measure(b, creg)
display(qc.draw())
backend = Aer.get_backend('qasm_simulator')
job = backend.run(transpile(qc, backend), shots=1024)
counts = job.result().get_counts()
print(counts)
def create_ctrl_mult_mod(n, bigN, m):
"""
Calculate zm mod N and output to b
:param n: number of bits for a, c and bigN; b has n+1 bits
:param bigN: mod number
:param m: multiplier
:return: Gate of 4n+2 qubits
0 (1 qubit) for x
1 to n (n qubits) for z
n+1 to 2n (n qubits) for a
2n+1 to 3n+1 (n+1 qubits) for b
3n+2 to 4n+1 (n qubits) for c (init to 0)
4n+2 to 5n+1 (n qubits) for bigN (init to bigN when use)
5n+2 (1 qubit) for temp (init to 0)
"""
x = QuantumRegister(1, 'x')
z = QuantumRegister(n, 'z')
a = QuantumRegister(n, 'a')
b = QuantumRegister(n+1, 'b')
c = QuantumRegister(n, 'c')
bN = QuantumRegister(n, 'bN')
t = QuantumRegister(1, 't')
qc = QuantumCircuit(x, z, a, b, c, bN, t)
next_mod = m # m 2^0 mod N
for j in range(n):
temp_mod = next_mod
i = 0
while temp_mod != 0:
if temp_mod % 2 != 0:
qc.ccx(x[0], z[j], a[i])
i = i + 1
temp_mod = temp_mod // 2
qc.append(create_adder_mod(n, bigN), list(a) + list(b) + list(c) + list(bN) + list(t))
temp_mod = next_mod
i = 0
while temp_mod != 0:
if temp_mod % 2 != 0:
qc.ccx(x[0], z[j], a[i])
i = i + 1
temp_mod = temp_mod // 2
next_mod = (next_mod * 2) % bigN # update for m 2^i+1 mod N
qc.x(x[0])
for j in range(n):
qc.ccx(x[0], z[j], b[j])
qc.x(x[0])
# display(qc.draw())
return qc.to_gate(label='ctrl_mult_mod')
def create_ctrl_mult_mod_inv(n, bigN, m):
qc = QuantumCircuit(5*n+3)
qc.append(create_ctrl_mult_mod(n, bigN, m).inverse(), range(5*n+3))
return qc.to_gate(label='ctrl_mult_mod_inv')
n = 3
bigN = 5
m = 3
x = QuantumRegister(1, 'x')
z = QuantumRegister(n, 'z')
a = QuantumRegister(n, 'a')
b = QuantumRegister(n+1, 'b')
c = QuantumRegister(n, 'c')
bN = QuantumRegister(n, 'bN')
t = QuantumRegister(1, 't')
creg = ClassicalRegister(n, 'creg')
qc = QuantumCircuit(x, z, a, b, c, bN, t, creg)
qc.x(x[0]) # x = 1
qc.x(z[0]) # z = 3
qc.x(z[1])
qc.x(bN[0]) # bN = 5
qc.x(bN[2])
qc.append(create_ctrl_mult_mod(n, bigN, m), list(x) + z[:] + list(a) + list(b) + list(c) + list(bN) + list(t))
# for i in range(n):
# qc.measure(b[i], creg[i])
qc.measure(b[0:n], creg)
display(qc.draw())
backend = Aer.get_backend('qasm_simulator')
job = backend.run(transpile(qc, backend), shots=1024)
counts = job.result().get_counts()
print(counts)
from sympy import mod_inverse
def create_mod_exp(n, bigN, y, nx):
"""
Calculate y^x mod N and output to z
:param n: number of bits for z, a, c and bigN; b has n+1 bits
:param bigN: mod number
:param y: multiplier
:param nx: number of bits for x
:return: Gate of 4n+2 qubits
0 to nx-1 (n qubit) for x
nx to nx+n-1 (n qubits) for z (init to 1 when use)
nx+n to nx+2n-1 (n qubits) for a (init to 0)
nx+2n to nx+3n (n+1 qubits) for b (init to 0)
nx+3n+1 to nx+4n (n qubits) for c (init to 0)
nx+4n+1 to nx+5n (n qubits) for bigN (init to bigN when use)
nx+5n+1 (1 qubit) for temp (init to 0)
"""
x = QuantumRegister(nx, 'x')
z = QuantumRegister(n, 'z')
a = QuantumRegister(n, 'a')
b = QuantumRegister(n+1, 'b')
c = QuantumRegister(n, 'c')
bN = QuantumRegister(n, 'bN')
t = QuantumRegister(1, 't')
qc = QuantumCircuit(x, z, a, b, c, bN, t)
m = y
for i in range(nx):
qc.append(create_ctrl_mult_mod(n, bigN, m),
[x[i]] + z[:] + a[:] + b[:] + c[:] + bN[:] + list(t))
for j in range(n):
qc.cswap(x[i], z[j], b[j])
m_inv = mod_inverse(m, bigN)
qc.append(create_ctrl_mult_mod_inv(n, bigN, m_inv),
[x[i]] + z[:] + a[:] + b[:] + c[:] + bN[:] + list(t))
m = (m * m) % bigN # update for next cycle
# display(qc.draw())
return qc.to_gate(label='mod_exp')
n = 3
bigN = 5
y = 3
nx = 6
x = QuantumRegister(nx, 'x')
z = QuantumRegister(n, 'z')
a = QuantumRegister(n, 'a')
b = QuantumRegister(n+1, 'b')
c = QuantumRegister(n, 'c')
bN = QuantumRegister(n, 'bN')
t = QuantumRegister(1, 't')
creg = ClassicalRegister(n, 'creg')
qc = QuantumCircuit(x, z, a, b, c, bN, t, creg)
#qc.x(x[2]) # x = 4
# qc.x(x[0]) # x = 3
# qc.x(x[1])
qc.x(x[1]) # x = 42
qc.x(x[3])
qc.x(x[5])
qc.x(z[0]) # z = 1 init
qc.x(bN[0]) # bN = 5
qc.x(bN[2])
qc.append(create_mod_exp(n, bigN, y, nx), x[:] + z[:] + a[:] + b[:] + c[:] + bN[:] + list(t))
qc.measure(z, creg)
display(qc.draw())
backend = Aer.get_backend('qasm_simulator')
job = backend.run(transpile(qc, backend), shots=1)
counts = job.result().get_counts()
print(counts)
n = 5 # use 4 qubits may not work, do not know the reason
bigN = 15
y = 7
nx = 8
x = QuantumRegister(nx, 'x')
z = QuantumRegister(n, 'z')
a = QuantumRegister(n, 'a')
b = QuantumRegister(n+1, 'b')
c = QuantumRegister(n, 'c')
bN = QuantumRegister(n, 'bN')
t = QuantumRegister(1, 't')
# cregz = ClassicalRegister(n, 'cregz')
cregx = ClassicalRegister(nx, 'cregx')
# qc = QuantumCircuit(x, z, a, b, c, bN, t, cregz, cregx)
qc = QuantumCircuit(x, z, a, b, c, bN, t, cregx)
qc.h(x)
qc.x(z[0]) # z = 1 init
qc.x(bN[0]) # bN = 15 = 1111(2)
qc.x(bN[1])
qc.x(bN[2])
qc.x(bN[3])
qc.append(create_mod_exp(n, bigN, y, nx), x[:] + z[:] + a[:] + b[:] + c[:] + bN[:] + list(t))
qc.append(myqft(nx).inverse(), x)
# qc.measure(z, cregz)
qc.measure(x, cregx)
display(qc.draw())
backend = Aer.get_backend('qasm_simulator')
job = backend.run(transpile(qc, backend), shots=1024)
counts = job.result().get_counts()
print(counts)
from fractions import Fraction
Fraction(192/2**8).limit_denominator(15)
import math
print(math.gcd(7**2+1, 15))
print(math.gcd(7**2-1, 15))
n = 6
bigN = 55
y = 7
nx = 12
x = QuantumRegister(nx, 'x')
z = QuantumRegister(n, 'z')
a = QuantumRegister(n, 'a')
b = QuantumRegister(n+1, 'b')
c = QuantumRegister(n, 'c')
bN = QuantumRegister(n, 'bN')
t = QuantumRegister(1, 't')
# cregz = ClassicalRegister(n, 'cregz')
cregx = ClassicalRegister(nx, 'cregx')
# qc = QuantumCircuit(x, z, a, b, c, bN, t, cregz, cregx)
qc = QuantumCircuit(x, z, a, b, c, bN, t, cregx)
qc.h(x)
qc.x(z[0]) # z = 1 init
qc.x(bN[0]) # bN = 55 = 110111(2)
qc.x(bN[1])
qc.x(bN[2])
qc.x(bN[4])
qc.x(bN[5])
# qc.x(bN[7])
qc.append(create_mod_exp(n, bigN, y, nx), x[:] + z[:] + a[:] + b[:] + c[:] + bN[:] + list(t))
qc.append(myqft(nx).inverse(), x)
# qc.measure(z, cregz)
qc.measure(x, cregx)
display(qc.draw())
backend = Aer.get_backend('qasm_simulator')
job = backend.run(transpile(qc, backend), shots=1024)
counts = job.result().get_counts()
print(counts)
from fractions import Fraction
Fraction(205/2**12).limit_denominator(55)
import math
print(math.gcd(7**10+1, 55))
print(math.gcd(7**10-1, 55))
n = 8
bigN = 221
y = 7
nx = 16
x = QuantumRegister(nx, 'x')
z = QuantumRegister(n, 'z')
a = QuantumRegister(n, 'a')
b = QuantumRegister(n+1, 'b')
c = QuantumRegister(n, 'c')
bN = QuantumRegister(n, 'bN')
t = QuantumRegister(1, 't')
# cregz = ClassicalRegister(n, 'cregz')
cregx = ClassicalRegister(nx, 'cregx')
# qc = QuantumCircuit(x, z, a, b, c, bN, t, cregz, cregx)
qc = QuantumCircuit(x, z, a, b, c, bN, t, cregx)
qc.h(x)
qc.x(z[0]) # z = 1 init
qc.x(bN[0]) # bN = 221 = 11011101(2)
qc.x(bN[2])
qc.x(bN[3])
qc.x(bN[4])
qc.x(bN[6])
qc.x(bN[7])
qc.append(create_mod_exp(n, bigN, y, nx), x[:] + z[:] + a[:] + b[:] + c[:] + bN[:] + list(t))
qc.append(myqft(nx).inverse(), x)
# qc.measure(z, cregz)
qc.measure(x, cregx)
display(qc.draw())
backend = Aer.get_backend('qasm_simulator')
job = backend.run(transpile(qc, backend), shots=1)
counts = job.result().get_counts()
print(counts)
from fractions import Fraction
Fraction(53248/2**16).limit_denominator(221)
import math
print(math.gcd(7**8+1, 221))
print(math.gcd(7**8-1, 221))
17*13
n = 9
bigN = 437
y = 7
nx = 18
x = QuantumRegister(nx, 'x')
z = QuantumRegister(n, 'z')
a = QuantumRegister(n, 'a')
b = QuantumRegister(n+1, 'b')
c = QuantumRegister(n, 'c')
bN = QuantumRegister(n, 'bN')
t = QuantumRegister(1, 't')
# cregz = ClassicalRegister(n, 'cregz')
cregx = ClassicalRegister(nx, 'cregx')
# qc = QuantumCircuit(x, z, a, b, c, bN, t, cregz, cregx)
qc = QuantumCircuit(x, z, a, b, c, bN, t, cregx)
qc.h(x)
qc.x(z[0]) # z = 1 init
qc.x(bN[0]) # bN = 437 = 110110101(2)
qc.x(bN[2])
qc.x(bN[4])
qc.x(bN[5])
qc.x(bN[7])
qc.x(bN[8])
qc.append(create_mod_exp(n, bigN, y, nx), x[:] + z[:] + a[:] + b[:] + c[:] + bN[:] + list(t))
qc.append(myqft(nx).inverse(), x)
# qc.measure(z, cregz)
qc.measure(x, cregx)
display(qc.draw())
backend = Aer.get_backend('qasm_simulator')
job = backend.run(transpile(qc, backend), shots=1024)
counts = job.result().get_counts()
print(counts)
from fractions import Fraction
Fraction(170791/2**18).limit_denominator(437)
import math
print(math.gcd(7**33+1, 437))
print(math.gcd(7**33-1, 437))
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2022.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Functions to generate the basic approximations of single qubit gates for Solovay-Kitaev."""
from __future__ import annotations
import warnings
import collections
import numpy as np
import qiskit.circuit.library.standard_gates as gates
from qiskit.circuit import Gate
from qiskit.quantum_info.operators.predicates import matrix_equal
from qiskit.utils import optionals
from .gate_sequence import GateSequence
Node = collections.namedtuple("Node", ("labels", "sequence", "children"))
_1q_inverses = {
"i": "i",
"x": "x",
"y": "y",
"z": "z",
"h": "h",
"t": "tdg",
"tdg": "t",
"s": "sdg",
"sdg": "s",
}
_1q_gates = {
"i": gates.IGate(),
"x": gates.XGate(),
"y": gates.YGate(),
"z": gates.ZGate(),
"h": gates.HGate(),
"t": gates.TGate(),
"tdg": gates.TdgGate(),
"s": gates.SGate(),
"sdg": gates.SdgGate(),
"sx": gates.SXGate(),
"sxdg": gates.SXdgGate(),
}
def _check_candidate(candidate, existing_sequences, tol=1e-10):
if optionals.HAS_SKLEARN:
return _check_candidate_kdtree(candidate, existing_sequences, tol)
warnings.warn(
"The SolovayKitaev algorithm relies on scikit-learn's KDTree for a "
"fast search over the basis approximations. Without this, we fallback onto a "
"greedy search with is significantly slower. We highly suggest to install "
"scikit-learn to use this feature.",
category=RuntimeWarning,
)
return _check_candidate_greedy(candidate, existing_sequences, tol)
def _check_candidate_greedy(candidate, existing_sequences, tol=1e-10):
# do a quick, string-based check if the same sequence already exists
if any(candidate.name == existing.name for existing in existing_sequences):
return False
for existing in existing_sequences:
if matrix_equal(existing.product_su2, candidate.product_su2, ignore_phase=True, atol=tol):
# is the new sequence less or more efficient?
return len(candidate.gates) < len(existing.gates)
return True
@optionals.HAS_SKLEARN.require_in_call
def _check_candidate_kdtree(candidate, existing_sequences, tol=1e-10):
"""Check if there's a candidate implementing the same matrix up to ``tol``.
This uses a k-d tree search and is much faster than the greedy, list-based search.
"""
from sklearn.neighbors import KDTree
# do a quick, string-based check if the same sequence already exists
if any(candidate.name == existing.name for existing in existing_sequences):
return False
points = np.array([sequence.product.flatten() for sequence in existing_sequences])
candidate = np.array([candidate.product.flatten()])
kdtree = KDTree(points)
dist, _ = kdtree.query(candidate)
return dist[0][0] > tol
def _process_node(node: Node, basis: list[str], sequences: list[GateSequence]):
inverse_last = _1q_inverses[node.labels[-1]] if node.labels else None
for label in basis:
if label == inverse_last:
continue
sequence = node.sequence.copy()
sequence.append(_1q_gates[label])
if _check_candidate(sequence, sequences):
sequences.append(sequence)
node.children.append(Node(node.labels + (label,), sequence, []))
return node.children
def generate_basic_approximations(
basis_gates: list[str | Gate], depth: int, filename: str | None = None
) -> list[GateSequence]:
"""Generates a list of ``GateSequence``s with the gates in ``basic_gates``.
Args:
basis_gates: The gates from which to create the sequences of gates.
depth: The maximum depth of the approximations.
filename: If provided, the basic approximations are stored in this file.
Returns:
List of ``GateSequences`` using the gates in ``basic_gates``.
Raises:
ValueError: If ``basis_gates`` contains an invalid gate identifier.
"""
basis = []
for gate in basis_gates:
if isinstance(gate, str):
if gate not in _1q_gates.keys():
raise ValueError(f"Invalid gate identifier: {gate}")
basis.append(gate)
else: # gate is a qiskit.circuit.Gate
basis.append(gate.name)
tree = Node((), GateSequence(), [])
cur_level = [tree]
sequences = [tree.sequence]
for _ in [None] * depth:
next_level = []
for node in cur_level:
next_level.extend(_process_node(node, basis, sequences))
cur_level = next_level
if filename is not None:
data = {}
for sequence in sequences:
gatestring = sequence.name
data[gatestring] = sequence.product
np.save(filename, data)
return sequences
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
# Create circuit to test transpiler on
from qiskit import QuantumCircuit
from qiskit.circuit.library import GroverOperator, Diagonal
oracle = Diagonal([1]*7 + [-1])
qc = QuantumCircuit(3)
qc.h([0,1,2])
qc = qc.compose(GroverOperator(oracle))
# Use Statevector object to calculate the ideal output
from qiskit.quantum_info import Statevector
ideal_distribution = Statevector.from_instruction(qc).probabilities_dict()
from qiskit.visualization import plot_histogram
plot_histogram(ideal_distribution)
from qiskit_ibm_runtime import QiskitRuntimeService
service = QiskitRuntimeService()
backend = service.backend('ibm_algiers')
# Need to add measurements to the circuit
qc.measure_all()
from qiskit import transpile
circuits = []
for optimization_level in [0, 3]:
t_qc = transpile(qc,
backend,
optimization_level=optimization_level,
seed_transpiler=0)
print(f'CNOTs (optimization_level={optimization_level}): ',
t_qc.count_ops()['cx'])
circuits.append(t_qc)
from qiskit.transpiler import PassManager, InstructionDurations
from qiskit.transpiler.passes import ASAPSchedule, DynamicalDecoupling
from qiskit.circuit.library import XGate
# Get gate durations so the transpiler knows how long each operation takes
durations = InstructionDurations.from_backend(backend)
# This is the sequence we'll apply to idling qubits
dd_sequence = [XGate(), XGate()]
# Run scheduling and dynamic decoupling passes on circuit
pm = PassManager([ASAPSchedule(durations),
DynamicalDecoupling(durations, dd_sequence)]
)
circ_dd = pm.run(circuits[1])
# Add this new circuit to our list
circuits.append(circ_dd)
from qiskit_ibm_runtime import Sampler, Session
with Session(service=service, backend=backend):
sampler = Sampler()
job = sampler.run(
circuits=circuits, # sample all three circuits
skip_transpilation=True,
shots=8000)
result = job.result()
from qiskit.visualization import plot_histogram
binary_prob = [quasi_dist.binary_probabilities() for quasi_dist in result.quasi_dists]
plot_histogram(binary_prob+[ideal_distribution],
bar_labels=False,
legend=['optimization_level=0',
'optimization_level=3',
'optimization_level=3 + dd',
'ideal distribution'])
from qiskit.quantum_info import hellinger_fidelity
for counts in result.quasi_dists:
print(
f"{hellinger_fidelity(counts.binary_probabilities(), ideal_distribution):.3f}"
)
import qiskit_ibm_runtime
qiskit_ibm_runtime.version.get_version_info()
from qiskit.tools.jupyter import *
%qiskit_version_table
%qiskit_copyright
|
https://github.com/victor-onofre/Quantum_Algorithms
|
victor-onofre
|
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer, IBMQ, BasicAer
import math
from qiskit.visualization import plot_histogram
backend = BasicAer.get_backend('statevector_simulator')
from wordcloud import WordCloud
import numpy as np
import pandas as pd # primary data structure library
import matplotlib.pyplot as plt
reg = QuantumRegister(8, name='reg') # The quantum register of the qubits, in this case 8 qubits
reg_c = ClassicalRegister(8, name='regc') # Where the measurements of the qubits will be saved
qc = QuantumCircuit(reg, reg_c)
qc.h(reg) # Apply Hadamard gate to put it into a superposition of 0 and 1 all the qubits
qc.measure(reg, reg_c) # read the result as a digital bit
job = execute(qc, backend) # Execute the circuit in the statevector_simulator
result = job.result()
outputstate = result.get_statevector(qc, decimals=5)
counts = result.get_counts(qc)
#print(outputstate)
qc.draw()
state, value = list(counts.items())[0] # key is de state of the system after the measuremnt, for example '11100001'
state
number = int(state, 2) # The state is converted into a number
ASCII_Character = chr(number) # The number in ASCII character
print('The random number is:',number)
print('The random ASCII character:',ASCII_Character)
def Quantum_random_number_and_ASCII_Character_generator(n):
reg = QuantumRegister(n, name='reg') # The quantum register of the n qubits
reg_c = ClassicalRegister(n, name='regc')# Where the measurements of the qubits will be saved
qc = QuantumCircuit(reg, reg_c)
qc.h(reg) # put it into a superposition of 0 and 1
qc.measure(reg, reg_c) # read the result as a digital bit
job = execute(qc, backend)
result = job.result()
counts = result.get_counts(qc)
key, value = list(counts.items())[0]
number = int(key, 2)
ASCII_Character = chr(number)
return ASCII_Character, number
Quantum_random_number_and_ASCII_Character_generator(8)[0] # Resturns the ASCII Character
Quantum_random_number_and_ASCII_Character_generator(8)[1] # Resturns the Random number
L = []
num = []
counter = []
for x in range(800):
string = Quantum_random_number_and_ASCII_Character_generator(8)[0] # ASCII_Character
number = Quantum_random_number_and_ASCII_Character_generator(8)[1] # Random_number
L.append(string) # Save the ASCII_Character in a the list "L"
num.append(number) # Save the Random_number in a the list "number"
counter.append(x)
# Convert the list to a dataframe
df1 = pd.DataFrame(counter, columns=['Counter'])
df2 = pd.DataFrame(L, columns=['Random_Character'])
df3 = pd.DataFrame(num, columns=['Random_Number'])
#Join the results in a dataframe
re = df1.join(df2)
Quantum_Random = re.join(df3)
Quantum_Random.head()
Quantum_Random.plot(x='Counter', y='Random_Number', figsize=(25,6.5), xlabel='Iteration', ylabel='Randon Number', legend = False, grid = True, fontsize = 14)
Quantum_Random['Random_Number'].describe()
#generate the word cloud
wordcloud = WordCloud(background_color='white').generate(' '.join(Quantum_Random['Random_Character']))
# display the word cloud
fig = plt.figure()
fig.set_figwidth(14)
fig.set_figheight(18)
plt.imshow(wordcloud, interpolation='bilinear')
plt.axis('off')
plt.show()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
top = QuantumCircuit(1)
top.x(0);
bottom = QuantumCircuit(2)
bottom.cry(0.2, 0, 1);
tensored = bottom.tensor(top)
tensored.draw('mpl')
|
https://github.com/jacobwatkins1/rodeo-algorithm
|
jacobwatkins1
|
import numpy as np
from sympy import *
from sympy.solvers import solve
import random
from qiskit import *
import scipy as sp
from numpy import linalg as la
from scipy import linalg as sla
from IPython.display import clear_output
from numpy import linalg as la
from qiskit.tools.visualization import plot_histogram
from qiskit.circuit import QuantumCircuit, ParameterVector
from qiskit.compiler import transpile, assemble
from qiskit.providers.ibmq.managed import IBMQJobManager
from qiskit.visualization import *
from operator import itemgetter
from functools import reduce
# Pauli Matrices
Id = np.matrix([[1,0],[0,1]],dtype=complex)
X = np.matrix([[0,1],[1,0]],dtype=complex)
Y = np.matrix([[0,-1j],[1j,0]],dtype=complex)
Z = np.matrix([[1,0],[0,-1]],dtype=complex)
# Generate random values.
a,b,c,d = [random.uniform(-1,1) for n in range(4)]
print('a=',a,',b=',b,',c=',c,',d=',d)
# The values used in our paper.
a= -0.08496099317164885
b= -0.8913449722923625
c= 0.2653567873681286
d= 0.5720506205204723
a = 2.0641811586466403
b = -0.8795521785527299
c = 0.2618460278326864
d = 0.5644821984323585
# Generate random values.
c_i,c_x,c_y,c_z = [random.uniform(-1,1) for n in range(4)]
print('c_i=', c_i,',c_x=',c_x,',c_y=',c_y,',c_z=',c_z)
# The values used in our paper.
c_i= -0.8453688208879107
c_x= 0.006726766902514836
c_y= -0.29354208134440296
c_z= 0.18477436355081123
# The Hamiltonian.
H = a*Id+b*X+c*Y+d*Z
print(H)
# Find the exact eigenstates and eigenvalues.
Awh, Avh = la.eig(H)
Aeval0h = float(re(Awh[0]))
Aeval1h = float(re(Awh[1]))
Aevec0h = Avh[:,0]
Aevec1h = Avh[:,1]
print('The energy eigenvalues of H are:',Aeval0h, 'and', Aeval1h)
print('The corresponding eigenvectors are:', '\n', Aevec0h,'\n', 'and','\n', Aevec1h)
O = c_i*Id+c_x*X+c_y*Y+c_z*Z
print(O)
Aw, Av = la.eig(O)
Aeval0 = float(re(Aw[0]))
Aeval1 = float(re(Aw[1]))
Aevec0 = Av[:,0]
Aevec1 = Av[:,1]
print('The energy eigenvalues are:',Aeval0, 'and', Aeval1)
print('The corresponding eigenvectors are:', '\n', Aevec0,'\n', 'and','\n', Aevec1)
Zero = np.matrix([[1],[0]],dtype=complex)
One = np.matrix([[0],[1]],dtype=complex)
Ze = np.squeeze(np.asarray(Zero))
On = np.squeeze(np.asarray(One))
def H_obj(phi): # All the information needed for H_obj.
# Hamiltonian.
Hobj = H + phi*O
wo, vo = la.eig(Hobj)
# Eigenvalues.
eval0o = float(re(wo[0]))
eval1o = float(re(wo[1]))
# Eigenvectors.
evec0o = vo[:,0]
evec1o = vo[:,1]
# Direct calculation of the expectation value.
Expe0 = evec0o.getH() @ O @ evec0o
Expe1 = evec1o.getH() @ O @ evec1o
return eval0o, eval1o, evec0o, evec1o, Expe0, Expe1
def GH(phimax,num,sigma):
plt.figure(figsize=(16.18,10))
philist = np.linspace(-phimax,phimax,num)
# epslist = np.concatenate((epslist[epslist<0], [0], epslist[epslist>0]))
x = np.arange(-1.5,1.5,0.005)
cm = LinearSegmentedColormap.from_list('defcol', ["#979A9A", "#17F514"])
trace_color = cm(np.linspace(0,1,len(philist)))
evalf = []
evals = []
expfi = []
expse = []
PS0 = []
PS1 = []
VEC0 = []
VEC1 = []
for phi, color in zip(philist, trace_color):
val0,val1,vec0,vec1,expe0,expe1 = H_obj(phi)
evalf.append(val0)
evals.append(val1)
expfi.append(expe0)
expse.append(expe1)
EV0 = np.squeeze(np.asarray(vec0))
EV1 = np.squeeze(np.asarray(vec1))
Pini0 = simplify(np.inner(Ze,EV0)*conjugate(np.inner(Ze,EV0)))
Pini1 = simplify(np.inner(Ze,EV1)*conjugate(np.inner(Ze,EV1)))
PS0.append(Pini0)
PS1.append(Pini1)
Probs = [Pini0,Pini1]
Evals = [val0,val1]
VEC0.append(vec0)
VEC1.append(vec1)
Yt = 0
for k in range (2):
y = Probs[k]
for i in range (3):
y *= 0.5*(1+np.exp((-0.5)*(x-Evals[k])**2*sigma**2))
Yt += y
if phi == 0:
expc = plt.plot(x,Yt,color = 'red',linewidth=3.6)
else:
expc = plt.plot(x,Yt,color = color)
plt.xlabel(r'$E_{target}$',fontsize = 25)
plt.ylabel(r'$P_{success}$',fontsize = 25)
plt.grid()
plt.show()
dx = 4*phimax/(num-1)
drf = [(evalf[i+1]-evalf[i-1])/dx for i in range(1,num-1)]
drs = [(evals[i+1]-evals[i-1])/dx for i in range(1,num-1)]
Df = dict(zip(philist[1:-1],drf))
Ds = dict(zip(philist[1:-1],drs))
Expf = dict(zip(philist[1:-1],expfi[1:-1]))
Exps = dict(zip(philist[1:-1],expse[1:-1]))
Energy1 = dict(zip(philist[1:-1],evalf[1:-1])) # Energy Eigenvalues
Energy2 = dict(zip(philist[1:-1],evals[1:-1]))
Pros0 = dict(zip(philist[1:-1],PS0[1:-1])) # Energy Eigenvalues
Pros1 = dict(zip(philist[1:-1],PS1[1:-1]))
return Df, Ds, Expf, Exps, Energy1, Energy2,Pros0,Pros1,VEC0,VEC1
Dc01, Dc02, Dc03, Dc04, Espec1, Espec2, PR0,PR1,VL0,VL1 = GH(0.1,21,12)
N = 3 # Number of cycles.
obj = 3 # Numbering of the physical (object) qubit on quantum device.
arena = 1 # Numbering of the physical (arena) qubit on quantum device.
def qc1(E_targ,tstep,phi):
ao = a + phi*c_i
bo = b + phi*c_x
co = c + phi*c_y
do = d + phi*c_z
sigo = Matrix([[bo],[co],[do]])
n_hato = np.dot(1/sqrt(bo**2+co**2+do**2),sigo)
nxo, nyo, nzo = [float(i.item()) for i in n_hato]
theta = 2*tstep*sqrt(bo**2+co**2+do**2) % (4*pi)
delta = float(re(atan(nzo*tan(theta/2))+atan(nxo/nyo)))
beta = float(re(atan(nzo*tan(theta/2))-atan(nxo/nyo)))
gamma = float(2*re(acos(cos(theta/2)/cos((delta+beta)/2))))
if nyo > 0 and theta > 2*pi:
gamma *= (-1)
elif nyo < 0 and theta <= 2*pi:
gamma *= (-1)
quanc1t = QuantumCircuit(2)
quanc1t.h(1)
quanc1t.cu(gamma,beta,delta,0,1,0)
quanc1t.p(tstep*(E_targ-ao)-0.5*(delta+beta),1) # The Energy Sensor.
quanc1t.h(1)
quanc1t.barrier()
return quanc1t
def qct(E_targ,sigma,phi):
qrz = QuantumRegister(2,'q')
crz = ClassicalRegister(N,'c')
qc = QuantumCircuit(qrz,crz)
t = np.random.normal(0, sigma, N).tolist()
init_gate = Initialize([i.item() for i in Aevec0h])
qc.append(init_gate, [1])
# qc.initialize([i.item() for i in Aevec0h],1)
# qc.append(init_gate, [1])
for i in range (N):
# sub_inst = qc1(E_targ,t[i],epsilon).to_instruction()
# qc.append(sub_inst,[obj,arena])
qc.append(qc1(E_targ,t[i],phi),[0,1]) # 0:Obj, 1:Arena.
qc.measure(1,i) # Mid-circuit measurement, arena is measured.
qc.barrier()
qc = transpile(qc,backend=backend,optimization_level=2,initial_layout = [obj,arena])
# qc = transpile(qc,backend=backend,optimization_level=2,layout_method = "noise_adaptive")
# qc.barrier()
return qc
def numsli_expc (L,rang1,rang2,nuni,nshots,sigma,k,phi):
val0, val1,_,_,_,_ = H_obj(phi)
EW = np.linspace(rang1,rang2,L) # The energy spectrum we're interested in.
circuits = [] # The 'circuit matrix'.
for i in range(L):
circuitsi = []
for j in range (nuni):
circuit = qct(EW[i],sigma,phi)
circuitsi.append(circuit)
circuits.append(circuitsi)
all_circuits = []
for i in range(L):
all_circuits += circuits[i][:]
MExperiments = job_manager.run(all_circuits, backend=backend, shots = nshots)
results = MExperiments.results()
# cresults = results.combine_results() # We are not doing read-out error mitigation here.
# mitigated_results = meas_filter.apply(cresults)
probsu = []
succs = '0'*N
for i in range (L):
probsui = []
for j in range (nuni):
# counts = mitigated_results.get_counts((nuni*i)+j)
counts = results.get_counts((nuni*i)+j)
if succs in counts:
prob = counts[succs]/sum(counts.values())
else:
prob = 0
probsui.append(prob)
probsu.append(np.average(probsui))
spec = dict(zip(EW,probsu))
plt.figure(figsize=(16.18,10))
plt.xlabel(r'$Energy\ Spectrum\ (E_{target})$',fontsize = 15)
plt.ylabel('Probability to measure the success state',fontsize = 15)
hist = plt.bar(spec.keys(), spec.values(), width=np.abs((rang2-rang1)/L), color='lightseagreen',alpha = 0.7)
plt.legend([hist],['Results from qasm'])
plt.grid()
plt.show()
# Weighted avg based on the highest bins.
#Larg = dict(sorted(spec.items(), key = itemgetter(1), reverse = True)[:Hisk])
#Wavg = np.average(list(Larg.keys()), weights=list(Larg.values()))
# Weighted avg of the highest consecutive bins.
keys = np.fromiter(spec.keys(), float, count=len(spec))
vals = np.fromiter(spec.values(), float, count=len(spec))
idx = np.convolve(vals, np.ones(k), 'valid').argmax()
Wavg = np.average(keys[idx:idx + k], weights=vals[idx:idx + k])
print('Range for the next scan', keys[idx:idx + k])
print('The estimated Eigenvalue is', Wavg)
print('The precise values are',val0,'and',val1)
return spec
# (L,rang1,rang2,nuni,nshots,sigma,k,phi) 9/26 qasm
firstscan = numsli_expc (18,0,np.pi+1,25,2500,2,6,0)
print(firstscan)
firstscan = numsli_expc (18,0,np.pi+1,15,2500,2,6,0)
print(firstscan)
# (L,rang1,rang2,nuni,nshots,sigma,k,phi) 7/22
firstscan = numsli_expc (18,-1-np.sqrt(3),1+np.sqrt(3),25,2500,2,6,0)
print(firstscan) #7/22
secondscan_a = numsli_expc (18, -1.768, -0.161 ,25,2500,7,6,0) # Small Peak. 7/22
print(secondscan_a)
secondscan_b = numsli_expc (18, 0.161, 1.768 ,25,2500,7,6,0) # Large Peak.
print(secondscan_b)
thirdscan_a = numsli_expc (18, -1.390, -0.917 ,25,2500,12,6,0) # Small Peak.
print(thirdscan_a)
thirdscan_a = numsli_expc (18, -1.390, -0.917 ,50,5000,12,6,0) # Small Peak.
print(thirdscan_a)
thirdscan_b = numsli_expc (18, 0.823, 1.295 ,25,2500,12,6,0) # Large Peak.
print(thirdscan_b)
firstscan_722 = {-2.732050807568877: 0.11027200000000001, -2.4106330655019503: 0.118928, -2.089215323435024: 0.12784, -1.767797581368097: 0.184432, -1.4463798393011702: 0.264032, -1.1249620972342433: 0.300608, -0.8035443551673167: 0.254656, -0.48212661310039007: 0.200192, -0.1607088710334632: 0.14988800000000002, 0.16070887103346365: 0.19345600000000002, 0.4821266131003905: 0.37512, 0.8035443551673169: 0.5875360000000001, 1.1249620972342438: 0.6517439999999999, 1.4463798393011706: 0.499424, 1.767797581368097: 0.22110400000000002, 2.0892153234350244: 0.101648, 2.410633065501951: 0.11871999999999998, 2.732050807568877: 0.17247999999999997}
secondscan_722a = {-1.768: 0.131792, -1.673470588235294: 0.115936, -1.5789411764705883: 0.122, -1.4844117647058823: 0.09486399999999998, -1.3898823529411766: 0.14913600000000002, -1.2953529411764706: 0.22596799999999997, -1.2008235294117648: 0.239616, -1.1062941176470589: 0.247136, -1.011764705882353: 0.223568, -0.9172352941176471: 0.16216, -0.8227058823529413: 0.08616000000000001, -0.7281764705882354: 0.09582399999999999, -0.6336470588235295: 0.10512, -0.5391176470588237: 0.10432000000000001, -0.44458823529411773: 0.09491199999999997, -0.350058823529412: 0.08795199999999999, -0.255529411764706: 0.08761599999999997, -0.161: 0.07192}
secondscan_722b = {0.161: 0.182816, 0.2555294117647059: 0.15763200000000002, 0.35005882352941176: 0.10408, 0.4445882352941176: 0.13350399999999998, 0.5391176470588235: 0.08361600000000001, 0.6336470588235293: 0.12872, 0.7281764705882353: 0.15812800000000002, 0.8227058823529412: 0.24163199999999999, 0.917235294117647: 0.554208, 1.011764705882353: 0.695728, 1.1062941176470587: 0.509696, 1.2008235294117646: 0.296912, 1.2953529411764706: 0.184352, 1.3898823529411763: 0.116848, 1.4844117647058823: 0.10819200000000001, 1.578941176470588: 0.145056, 1.673470588235294: 0.09142399999999999, 1.768: 0.09601599999999999}
thirdscan_722a = {-1.39: 0.105148, -1.362176470588235: 0.132608, -1.3343529411764705: 0.163096, -1.3065294117647057: 0.18905999999999998, -1.2787058823529411: 0.188512, -1.2508823529411763: 0.227852, -1.2230588235294118: 0.238048, -1.195235294117647: 0.311544, -1.1674117647058824: 0.288476, -1.1395882352941176: 0.27693999999999996, -1.111764705882353: 0.22833199999999998, -1.0839411764705882: 0.21373999999999999, -1.0561176470588234: 0.20185599999999998, -1.0282941176470588: 0.18544799999999997, -1.0004705882352942: 0.1288, -0.9726470588235294: 0.14307599999999998, -0.9448235294117647: 0.12436799999999998, -0.917: 0.121528}
thirdscan_722b = {0.823: 0.221904, 0.8507647058823529: 0.16145600000000002, 0.8785294117647058: 0.23401600000000003, 0.9062941176470588: 0.307184, 0.9340588235294117: 0.42928000000000005, 0.9618235294117646: 0.533504, 0.9895882352941177: 0.6538719999999999, 1.0173529411764706: 0.6308799999999999, 1.0451176470588235: 0.577024, 1.0728823529411764: 0.438288, 1.1006470588235293: 0.30886399999999997, 1.1284117647058824: 0.261488, 1.1561764705882354: 0.21272, 1.1839411764705883: 0.207696, 1.2117058823529412: 0.144432, 1.239470588235294: 0.117392, 1.267235294117647: 0.12107200000000003, 1.295: 0.13726400000000002}
firstscan_926qasm = {-2.732050807568877: 0.095152, -2.4106330655019503: 0.109664, -2.089215323435024: 0.147952, -1.767797581368097: 0.19204800000000002, -1.4463798393011702: 0.315872, -1.1249620972342433: 0.33392000000000005, -0.8035443551673167: 0.301248, -0.48212661310039007: 0.22039999999999998, -0.1607088710334632: 0.14299199999999998, 0.16070887103346365: 0.27012800000000003, 0.4821266131003905: 0.41830399999999995, 0.8035443551673169: 0.6923039999999999, 1.1249620972342438: 0.7712320000000001, 1.4463798393011706: 0.47627200000000003, 1.767797581368097: 0.21656000000000003, 2.0892153234350244: 0.157872, 2.410633065501951: 0.134464, 2.732050807568877: 0.154464}
#plt.figure(figsize=(5*(1+np.sqrt(5)),10))
plt.figure(figsize=(14*1.2,12))
hist1 = plt.bar(firstscan_722.keys(), firstscan_722.values(), width = 2*(1+sqrt(3))/18 , color='limegreen',alpha = 0.32)
plt.bar(secondscan_722a.keys(), secondscan_722a.values(), width= 1.608/18, color='deepskyblue',alpha = 0.49)
hist2 = plt.bar(secondscan_722b.keys(), secondscan_722b.values(), width= 1.607/18, color='deepskyblue',alpha = 0.49)
plt.bar(thirdscan_722a.keys(), thirdscan_722a.values(), width=0.5/18, color='darkorchid',alpha = 0.65)
hist3 = plt.bar(thirdscan_722b.keys(), thirdscan_722b.values(), width=0.5/18, color='darkorchid',alpha = 0.65)
hist_ref = plt.bar(firstscan_926qasm.keys(), firstscan_926qasm.values(),width = 2*(1+sqrt(3))/18,fill = False , color='grey',alpha = 0.49)
Zero = np.matrix([[1],[0]],dtype=complex)
One = np.matrix([[0],[1]],dtype=complex)
Ze = np.squeeze(np.asarray(Zero))
On = np.squeeze(np.asarray(One))
x = np.arange(-1-np.sqrt(3),1+np.sqrt(3),0.005)
EV0 = np.squeeze(np.asarray(Aevec0h))
EV1 = np.squeeze(np.asarray(Aevec1h))
Pini0 = np.inner(Ze,EV0)*conjugate(np.inner(Ze,EV0))
Pini1 = np.inner(Ze,EV1)*conjugate(np.inner(Ze,EV1))
Probs = [Pini0,Pini1]
Evals = [Aeval0h,Aeval1h]
Yt = 0
for k in range (2):
y = Probs[k]
for i in range (N):
y *= 0.5*(1+np.exp((-0.5)*(x-Evals[k])**2*2**2))
Yt += y
Ytl = 0
for k in range (2):
yl = Probs[k]
for i in range (N):
yl *= 0.5*(1+np.exp((-0.5)*(x-Evals[k])**2*7**2))
Ytl += yl
Yt2 = 0
for k in range (2):
y2 = Probs[k]
for i in range (N):
y2 *= 0.5*(1+np.exp((-0.5)*(x-Evals[k])**2*12**2))
Yt2 += y2
expc, = plt.plot(x,Yt,color = 'royalblue',linewidth=2.7,linestyle='--',alpha=1)
expc1, = plt.plot(x,Ytl,color = 'red',linewidth=2.7,linestyle='--',alpha=1)
expc2, = plt.plot(x,Yt2,color = 'black',linewidth=2.7,linestyle='--',alpha=1)
#plt.xlabel(r'$E$',fontsize = 35)
#plt.ylabel(r'$P_{0^N}$',fontsize = 35)
plt.legend([hist1,hist2,hist3,hist_ref,expc,expc1,expc2],
['$\sigma=2$ (1st scan)','$\sigma=7$ (2nd scan)','$\sigma=12$ (3rd scan)','Noiseless simulation (1st scan)','$\sigma=2$ (expected)','$\sigma=7$ (expected)','$\sigma=12$ (expected)'],
ncol = 2,loc="upper left",fontsize=20,columnspacing = -4.5)
#plt.grid(alpha = 0.6)
plt.xticks(fontsize=25)
plt.yticks(fontsize=25)
plt.text(0.087, 0.9, r'$P_{0^N}$', fontsize=35, transform=plt.gcf().transFigure)
plt.text(0.9, 0.087, r'$E$', fontsize=35, transform=plt.gcf().transFigure)
plt.savefig("SeqScan430_0610.png",dpi=430,bbox_inches='tight',pad_inches = 0)
plt.show()
thirdscan_a = numsli_expc (18, -1.390, -0.917 ,50,5000,12,6,0.01) # Small Peak.
print(thirdscan_a)
thirdscan_b = numsli_expc (18, 0.823, 1.295 ,25,2500,12,6,0.01) # Large Peak.
print(thirdscan_b)
thirdscan_a = numsli_expc (18, -1.390, -0.917 ,50,5000,12,6,-0.01) # Small Peak.
print(thirdscan_a)
thirdscan_b = numsli_expc (18, 0.823, 1.295 ,25,2500,12,6,-0.01) # Large Peak.
print(thirdscan_b)
thirdscan_a = numsli_expc (18, -1.390, -0.917 ,50,5000,12,6,0.02) # Small Peak.
print(thirdscan_a)
thirdscan_b = numsli_expc (18, 0.823, 1.295 ,25,2500,12,6,0.02) # Large Peak.
print(thirdscan_b)
thirdscan_a = numsli_expc (18, -1.390, -0.917 ,50,5000,12,6,-0.02) # Small Peak.
print(thirdscan_a)
thirdscan_b = numsli_expc (18, 0.823, 1.295 ,25,2500,12,6,-0.02) # Large Peak.
print(thirdscan_b)
thirdscan_a = numsli_expc (18, -1.390, -0.917 ,50,5000,12,6,0.03) # Small Peak.
print(thirdscan_a)
thirdscan_b = numsli_expc (18, 0.823, 1.295 ,25,2500,12,6,0.03) # Large Peak.
print(thirdscan_b)
thirdscan_a = numsli_expc (18, -1.390, -0.917 ,50,5000,12,6,-0.03) # Small Peak.
print(thirdscan_a)
thirdscan_b = numsli_expc (18, 0.823, 1.295 ,25,2500,12,6,-0.03) # Large Peak.
print(thirdscan_b)
thirdscan_a = numsli_expc (18, -1.390, -0.917 ,50,5000,12,6,-0.04) # Small Peak.
print(thirdscan_a)
thirdscan_b = numsli_expc (18, 0.823, 1.295 ,25,2500,12,6,-0.04) # Large Peak.
print(thirdscan_b)
thirdscan_a = numsli_expc (18, -1.490, -1.017 ,50,5000,12,6,0.04) # Small Peak.
print(thirdscan_a)
thirdscan_b = numsli_expc (18, 0.723, 1.195 ,25,2500,12,6,0.04) # Large Peak.
print(thirdscan_b)
thirdscan_a = numsli_expc (18, -1.490, -1.017 ,50,5000,12,6,0.05) # Small Peak.
print(thirdscan_a)
thirdscan_b = numsli_expc (18, 0.723, 1.195 ,25,2500,12,6,0.05) # Large Peak.
print(thirdscan_b)
thirdscan_a = numsli_expc (18, -1.390, -0.917 ,50,5000,12,6,-0.05) # Small Peak.
print(thirdscan_a)
thirdscan_b = numsli_expc (18, 0.823, 1.295 ,25,2500,12,6,-0.05) # Large Peak.
print(thirdscan_b)
thirdscan_a = numsli_expc (18, -1.490, -1.017 ,50,5000,12,6,0.06) # Small Peak.
print(thirdscan_a)
thirdscan_b = numsli_expc (18, 0.723, 1.195 ,25,2500,12,6,0.06) # Large Peak.
print(thirdscan_b)
thirdscan_a = numsli_expc (18, -1.390, -0.917 ,50,5000,12,6,-0.06) # Small Peak.
print(thirdscan_a)
thirdscan_b = numsli_expc (18, 0.823, 1.295 ,25,2500,12,6,-0.06) # Large Peak.
print(thirdscan_b)
thirdscan_a = numsli_expc (18, -1.490, -1.017 ,50,5000,12,6,0.07) # Small Peak.
print(thirdscan_a)
thirdscan_b = numsli_expc (18, 0.723, 1.195 ,25,2500,12,6,0.07) # Large Peak.
print(thirdscan_b)
thirdscan_a = numsli_expc (18, -1.390, -0.917 ,50,5000,12,6,-0.07) # Small Peak.
print(thirdscan_a)
thirdscan_b = numsli_expc (18, 0.823, 1.295 ,25,2500,12,6,-0.07) # Large Peak.
print(thirdscan_b)
thirdscan_a = numsli_expc (18, -1.490, -1.017 ,50,5000,12,6,0.08) # Small Peak.
print(thirdscan_a)
thirdscan_b = numsli_expc (18, 0.723, 1.195 ,25,2500,12,6,0.08) # Large Peak.
print(thirdscan_b)
thirdscan_a = numsli_expc (18, -1.390, -0.917 ,50,5000,12,6,-0.08) # Small Peak.
print(thirdscan_a)
thirdscan_b = numsli_expc (18, 0.823, 1.295 ,25,2500,12,6,-0.08) # Large Peak.
print(thirdscan_b)
thirdscan_a = numsli_expc (18, -1.490, -1.017 ,50,5000,12,6,0.09) # Small Peak.
print(thirdscan_a)
thirdscan_b = numsli_expc (18, 0.723, 1.195 ,25,2500,12,6,0.09) # Large Peak.
print(thirdscan_b)
thirdscan_a = numsli_expc (18, -1.290, -0.817 ,50,5000,12,6,-0.09) # Small Peak.
print(thirdscan_a)
thirdscan_b = numsli_expc (18, 0.823, 1.295 ,25,2500,12,6,-0.09) # Large Peak.
print(thirdscan_b)
thirdscan_a = numsli_expc (18, -1.490, -1.017 ,50,5000,12,6,0.1) # Small Peak.
print(thirdscan_a)
thirdscan_b = numsli_expc (18, 0.723, 1.195 ,25,2500,12,6,0.1) # Large Peak.
print(thirdscan_b)
thirdscan_a = numsli_expc (18, -1.290, -0.817 ,50,5000,12,6,-0.1) # Small Peak.
print(thirdscan_a)
thirdscan_b = numsli_expc (18, 0.823, 1.295 ,25,2500,12,6,-0.1) # Large Peak.
print(thirdscan_b)
|
https://github.com/swe-train/qiskit__qiskit
|
swe-train
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2022.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Tests for swap strategies."""
from typing import List
from ddt import data, ddt, unpack
import numpy as np
from qiskit import QiskitError
from qiskit.test import QiskitTestCase
from qiskit.transpiler import CouplingMap
from qiskit.transpiler.passes.routing.commuting_2q_gate_routing import SwapStrategy
@ddt
class TestSwapStrategy(QiskitTestCase):
"""A class to test the swap strategies."""
def setUp(self):
super().setUp()
self.line_coupling_map = CouplingMap(
couplinglist=[
(0, 1),
(1, 2),
(2, 3),
(3, 4),
(1, 0),
(2, 1),
(3, 2),
(4, 3),
]
)
self.line_swap_layers = (
((0, 1), (2, 3)),
((1, 2), (3, 4)),
((0, 1), (2, 3)),
((1, 2), (3, 4)),
((0, 1), (2, 3)),
)
self.line_edge_coloring = {(0, 1): 0, (1, 2): 1, (2, 3): 0, (3, 4): 1}
self.line_strategy = SwapStrategy(self.line_coupling_map, self.line_swap_layers)
@data(
(0, [0, 1, 2, 3, 4]),
(1, [1, 0, 3, 2, 4]),
(2, [1, 3, 0, 4, 2]),
(3, [3, 1, 4, 0, 2]),
(4, [3, 4, 1, 2, 0]),
(5, [4, 3, 2, 1, 0]),
)
@unpack
def test_inverse_composed_permutation(self, layer_idx: int, expected: List[int]):
"""Test the inverse of the permutations."""
self.assertEqual(self.line_strategy.inverse_composed_permutation(layer_idx), expected)
def test_apply_swap_layer(self):
"""Test that swapping a list of elements is correct."""
list_to_swap = [0, 10, 20, 30, 40]
swapped_list = self.line_strategy.apply_swap_layer(list_to_swap, 0)
self.assertEqual(swapped_list, [10, 0, 30, 20, 40])
self.assertFalse(list_to_swap == swapped_list)
swapped_list = self.line_strategy.apply_swap_layer(list_to_swap, 1, inplace=True)
self.assertEqual(swapped_list, [0, 20, 10, 40, 30])
self.assertTrue(list_to_swap == swapped_list)
def test_length(self):
"""Test the __len__ operator."""
self.assertEqual(len(self.line_strategy), 5)
def test_swapped_coupling_map(self):
"""Test the edges generated by a swap strategy."""
edge_set = {(2, 0), (0, 4), (4, 1), (1, 3), (3, 1), (1, 4), (4, 0), (0, 2)}
swapped_map = self.line_strategy.swapped_coupling_map(3)
self.assertEqual(edge_set, set(swapped_map.get_edges()))
def test_check_configuration(self):
"""Test that tries to initialize an invalid swap strategy."""
with self.assertRaises(QiskitError):
SwapStrategy(
coupling_map=self.line_coupling_map,
swap_layers=(((0, 1), (2, 3)), ((1, 3), (2, 4))),
)
def test_only_one_swap_per_qubit_per_layer(self):
"""Test that tries to initialize an invalid swap strategy."""
message = "The 0th swap layer contains a qubit with multiple swaps."
with self.assertRaises(QiskitError, msg=message):
SwapStrategy(
coupling_map=self.line_coupling_map,
swap_layers=(((0, 1), (1, 2)),),
)
def test_distance_matrix(self):
"""Test the computation of the swap strategy distance matrix."""
line_distance_matrix = np.array(
[
[0, 0, 3, 1, 2],
[0, 0, 0, 2, 3],
[3, 0, 0, 0, 1],
[1, 2, 0, 0, 0],
[2, 3, 1, 0, 0],
]
)
self.assertTrue(np.all(line_distance_matrix == self.line_strategy.distance_matrix))
# Check that the distance matrix cannot be written to.
with self.assertRaises(ValueError):
self.line_strategy.distance_matrix[1, 2] = 5
def test_reaches_full_connectivity(self):
"""Test to reach full connectivity on the longest line of Mumbai."""
# The longest line on e.g. Mumbai has 21 qubits
ll27 = list(range(21))
ll27_map = [[ll27[idx], ll27[idx + 1]] for idx in range(len(ll27) - 1)]
ll27_map += [[ll27[idx + 1], ll27[idx]] for idx in range(len(ll27) - 1)]
# Create a line swap strategy on this line
layer1 = tuple((ll27[idx], ll27[idx + 1]) for idx in range(0, len(ll27) - 1, 2))
layer2 = tuple((ll27[idx], ll27[idx + 1]) for idx in range(1, len(ll27), 2))
n = len(ll27)
for n_layers, result in [
(n - 4, False),
(n - 3, False),
(n - 2, True),
(n - 1, True),
]:
swap_strat_ll = []
for idx in range(n_layers):
if idx % 2 == 0:
swap_strat_ll.append(layer1)
else:
swap_strat_ll.append(layer2)
strat = SwapStrategy(CouplingMap(ll27_map), tuple(swap_strat_ll))
self.assertEqual(len(strat.missing_couplings) == 0, result)
def test_new_connections(self):
"""Test the new connections method."""
new_cnx = self.line_strategy.new_connections(0)
expected = [{1, 0}, {2, 1}, {3, 2}, {4, 3}]
self.assertListEqual(new_cnx, expected)
# Test after first swap layer (0, 1) first
new_cnx = self.line_strategy.new_connections(1)
expected = [{3, 0}, {4, 2}]
self.assertListEqual(new_cnx, expected)
def test_possible_edges(self):
"""Test that possible edges works as expected."""
coupling_map = CouplingMap(couplinglist=[(0, 1), (1, 2), (2, 3)])
strat = SwapStrategy(coupling_map, (((0, 1), (2, 3)), ((1, 2),)))
expected = set()
for i in range(4):
for j in range(4):
if i != j:
expected.add((i, j))
self.assertSetEqual(strat.possible_edges, expected)
class TestSwapStrategyExceptions(QiskitTestCase):
"""A class to test the exceptions raised by swap strategies."""
def test_invalid_strategy(self):
"""Test that a raise properly occurs."""
coupling_map = CouplingMap(couplinglist=[(0, 1), (1, 2)])
swap_layers = (((0, 1), (2, 3)), ((1, 2), (3, 4)))
with self.assertRaises(QiskitError):
SwapStrategy(coupling_map, swap_layers)
def test_invalid_line_strategy(self):
"""Test the number of layers."""
message = "Negative number -1 passed for number of swap layers."
with self.assertRaises(ValueError, msg=message):
SwapStrategy.from_line([0, 1, 2], -1)
class TestLineSwapStrategy(QiskitTestCase):
"""A class to test the line swap strategy."""
def test_invalid_line(self):
"""Test that lines should be longer than 1."""
message = "The line cannot have less than two elements, but is [1]"
with self.assertRaises(ValueError, msg=message):
SwapStrategy.from_line([1], 0)
def test_full_line(self):
"""Test to reach full connectivity on a line."""
n_nodes = 5
strategy = SwapStrategy.from_line(list(range(n_nodes)))
self.assertEqual(len(strategy._swap_layers), n_nodes - 2)
# The LineSwapStrategy will apply the following permutations
layers = [
[0, 1, 2, 3, 4], # coupling map
[1, 0, 3, 2, 4], # layer 1
[1, 3, 0, 4, 2], # layer 2
[3, 1, 4, 0, 2], # layer 3 <-- full connectivity is reached.
]
for layer_idx, layer in enumerate(layers):
expected = set()
for idx in range(len(layer) - 1):
expected.add((layer[idx], layer[idx + 1]))
expected.add((layer[idx + 1], layer[idx]))
strat_edges = strategy.swapped_coupling_map(layer_idx).get_edges()
self.assertEqual(len(strat_edges), len(expected))
for edge in strat_edges:
self.assertTrue(edge in expected)
self.assertEqual(strategy.swap_layer(0), [(0, 1), (2, 3)])
self.assertEqual(strategy.swap_layer(1), [(1, 2), (3, 4)])
self.assertEqual(strategy.swap_layer(2), [(0, 1), (2, 3)])
self.assertEqual(len(strategy.missing_couplings), 0)
def test_line(self):
"""Test the creation of a line swap strategy."""
n_nodes = 5
strategy = SwapStrategy.from_line(list(range(n_nodes)))
self.assertEqual(strategy.swap_layer(0), [(0, 1), (2, 3)])
self.assertEqual(strategy.swap_layer(1), [(1, 2), (3, 4)])
self.assertEqual(strategy.swap_layer(2), [(0, 1), (2, 3)])
self.assertEqual(len(strategy.missing_couplings), 0)
def test_repr(self):
"""The the representation."""
expected = (
"SwapStrategy with swap layers:\n((0, 1),),\non "
"[[0, 1], [1, 0], [1, 2], [2, 1]] coupling map."
)
self.assertEqual(repr(SwapStrategy.from_line([0, 1, 2])), expected)
|
https://github.com/microsoft/qiskit-qir
|
microsoft
|
import qiskit_qasm2
project = 'Qiskit OpenQASM 2 Tools'
copyright = '2022, Jake Lishman'
author = 'Jake Lishman'
version = qiskit_qasm2.__version__
extensions = [
"sphinx.ext.autodoc",
"sphinx.ext.intersphinx",
]
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']
# Document the docstring for the class and the __init__ method together.
autoclass_content = "both"
html_theme = 'alabaster'
intersphinx_mapping = {
"qiskit-terra": ("https://qiskit.org/documentation", None),
}
|
https://github.com/Naphann/Solving-TSP-Grover
|
Naphann
|
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit import IBMQ, Aer, execute
from qiskit.tools.visualization import plot_histogram
## oracle_initialize_part
def OR(qubit_1, qubit_2, k):
# enter qubit numbers here
""" function does the equivalent of a classical OR between qubit numbers a and b and stores the result in qubit number k """
# qc.barrier(q)
qc.x(q[qubit_1])
qc.x(q[qubit_2])
# qc.barrier(q)
qc.ccx(q[qubit_1], q[qubit_2], q[k])
qc.x(q[k])
# qc.barrier(q)
qc.x(q[qubit_1])
qc.x(q[qubit_2])
# qc.barrier(q)
def are_not_equal(a_0, b_0, k):
# enter node numbers here. For example, a is node 0, b is node 1 and c is node 2
""" function outputs 1 if nodes a and b are not the same. Node numbering starts from 0
as in the problem statement. k is the qubit number where the output is XOR-ed. qubit
numbering also starts from 0 """
# qc.barrier(q)
qc.cx(q[2*a_0], q[2*b_0])
qc.cx(q[(2*a_0) + 1], q[(2*b_0) + 1])
OR(2*b_0, (2*b_0)+1, k)
qc.cx(q[2*a_0], q[2*b_0])
qc.cx(q[(2*a_0) + 1], q[(2*b_0) + 1])
# qc.barrier(q)
def is_not_3(a, k):
qc.ccx(q[2*a], q[(2*a)+1], q[k])
qc.x(q[k])
def initialize_oracle_part(n):
t = 4
# qc.barrier(q)
are_not_equal(0, 1, 6) # node a and b are not equal
are_not_equal(0, 2, 7)
are_not_equal(1, 2, 8)
is_not_3(0, 11)
is_not_3(1, 12)
is_not_3(2, 13)
# qc.barrier(q)
qc.mct([q[6], q[7], q[8], q[11], q[12], q[13]], q[10],[q[9], q[14], q[15], q[16]]) # answer is stored in 10. please keep 9 a clean qubit, it's used as ancilla here
# qc.barrier(q)
is_not_3(0, 11)
is_not_3(1, 12)
is_not_3(2, 13)
are_not_equal(0, 1, 6) # node a and b are not equal
are_not_equal(0, 2, 7)
are_not_equal(1, 2, 8)
## distance_black_box
distances = {
"32": 3,
"31": 2,
"30": 4,
"21": 7,
"20": 6,
"10": 5,
}
def dist_single():
qr = QuantumRegister(2)
qr_target = QuantumRegister(5)
qc = QuantumCircuit(qr, qr_target, name='dist_single')
for edge in distances:
if edge[0] == '3':
node = format(int(edge[1]), '02b')
d_bin = format(distances[edge], '02b')
for idx in range(len(node)):
if node[idx] == '0':
qc.x(qr[idx])
for idx in range(len(d_bin)):
if d_bin[idx] == '1':
qc.ccx(qr[0], qr[1], qr_target[idx])
for idx in range(len(node)):
if node[idx] == '0':
qc.x(qr[idx])
return qc
def dist():
qr1 = QuantumRegister(2)
qr2 = QuantumRegister(2)
qr_target = QuantumRegister(5)
qr_anc = QuantumRegister(2)
qc = QuantumCircuit(qr1, qr2, qr_target, qr_anc, name='dist')
for edge in distances:
if edge[0] != '3':
# convert to binaries
node1 = format(int(edge[0]), '02b')
node2 = format(int(edge[1]), '02b')
d_bin = format(distances[edge], '02b')
for idx in range(len(node1)): # assume node1 and node2 have the same length
if node1[idx] == '0':
qc.x(qr1[idx])
for idx in range(len(node2)):
if node2[idx] == '0':
qc.x(qr2[idx])
for idx in range(len(d_bin)):
if d_bin[idx] == '1':
qc.mct(qr1[:]+qr2[:], qr_target[idx], qr_anc)
for idx in range(len(node2)): # invert back
if node2[idx] == '0':
qc.x(qr2[idx])
for idx in range(len(node1)):
if node1[idx] == '0':
qc.x(qr1[idx])
return qc
## multi_adder_1
def maj(a, b, k):
qc.cx(q[k], q[b])
qc.cx(q[k], q[a])
qc.ccx(q[a], q[b], q[k])
def unmaj(a, b, k):
qc.ccx(q[a], q[b], q[k])
qc.cx(q[k], q[a])
qc.cx(q[a], q[b])
def multiple_adder(a, b, c_0, z):
arr_size = len(a)
maj(c_0, b[0], a[0])
for i in range(arr_size-1):
maj(a[i], b[i+1], a[i+1])
qc.cx(q[a[arr_size-1]], q[z])
for i in reversed(range(arr_size-1)):
unmaj(a[i], b[i+1], a[i+1])
unmaj(c_0, b[0], a[0])
## diffusion
def diffusion():
qc.h(q[0:6])
qc.x(q[0:6])
qc.h(q[5])
qc.barrier()
qc.mct(q[0:5], q[5], q[7:10])
qc.barrier()
qc.h(q[5])
qc.x(q[0:6])
qc.h(q[0:6])
qubit_num = 25 # max is 32 if you're using the simulator
# Ancilla indices
inputs = [0, 1, 2, 3, 4, 5]
init_ancillae = [6, 7, 8, 9]
valid = [10]
temp_dist = [11, 12, 13, 14, 15]
total_dist = [16, 17, 18, 19, 20]
gate_ancillae = [21, 22, 23]
check_dist = [11, 12, 13, 14, 15] # initialize 13 here
carry_check = [24]
inputs = inputs[0]
init_ancillae = init_ancillae[0]
valid = valid[0]
temp_dist = temp_dist[0]
total_dist = total_dist[0]
gate_ancillae = gate_ancillae[0]
check_dist = check_dist[0]
carry_check = carry_check[0]
q = QuantumRegister(qubit_num)
c = ClassicalRegister(6)
qc = QuantumCircuit(q, c)
qc.h(q[0:6])
qc.x(q[carry_check])
for i in range(loop):
# forward oracle
initialize_oracle_part(4)
qc.append(dist_single(), q[inputs:inputs+2] + q[temp_dist:temp_dist+5])
multiple_adder([11, 12, 13, 14], [16, 17, 18, 19], init_ancillae, 20)
qc.append(dist_single().inverse(), q[inputs:inputs+2] + q[temp_dist:temp_dist+5])
qc.append(dist(), q[inputs:inputs+4] + q[temp_dist:temp_dist+5] + q[gate_ancillae:gate_ancillae+2])
multiple_adder([11, 12, 13, 14], [16, 17, 18, 19], init_ancillae, 20)
qc.append(dist().inverse(), q[inputs:inputs+4] + q[temp_dist:temp_dist+5] + q[gate_ancillae:gate_ancillae+2])
qc.append(dist(), q[inputs+2:inputs+6] + q[temp_dist:temp_dist+5] + q[gate_ancillae:gate_ancillae+2])
multiple_adder([11, 12, 13, 14], [16, 17, 18, 19], init_ancillae, 20)
qc.append(dist().inverse(), q[inputs+2:inputs+6] + q[temp_dist:temp_dist+5] + q[gate_ancillae:gate_ancillae+2])
qc.x(q[check_dist:check_dist+3]) # init 15
multiple_adder([11, 12, 13, 14, 15], [16, 17, 18, 19, 20], init_ancillae, carry_check)
# carry_check
# qc.barrier()
qc.cz(q[valid], q[carry_check])
# qc.barrier()
# inverse oracle
multiple_adder([11, 12, 13, 14, 15], [16, 17, 18, 19, 20], init_ancillae, carry_check)
qc.x(q[check_dist:check_dist+3]) # init 15
qc.append(dist().inverse(), q[inputs+2:inputs+6] + q[temp_dist:temp_dist+5] + q[gate_ancillae:gate_ancillae+2])
multiple_adder([11, 12, 13, 14], [16, 17, 18, 19], init_ancillae, 20)
qc.append(dist(), q[inputs+2:inputs+6] + q[temp_dist:temp_dist+5] + q[gate_ancillae:gate_ancillae+2])
qc.append(dist().inverse(), q[inputs:inputs+4] + q[temp_dist:temp_dist+5] + q[gate_ancillae:gate_ancillae+2])
multiple_adder([11, 12, 13, 14], [16, 17, 18, 19], init_ancillae, 20)
qc.append(dist(), q[inputs:inputs+4] + q[temp_dist:temp_dist+5] + q[gate_ancillae:gate_ancillae+2])
qc.append(dist_single().inverse(), q[inputs:inputs+2] + q[temp_dist:temp_dist+5])
multiple_adder([11, 12, 13, 14], [16, 17, 18, 19], init_ancillae, 20)
qc.append(dist_single(), q[inputs:inputs+2] + q[temp_dist:temp_dist+5])
initialize_oracle_part(4)
diffusion()
qc.measure(q[:6], c)
# qc.draw()
from qiskit.transpiler import PassManager
from qiskit.transpiler.passes import Unroller
pass_ = Unroller(['u3', 'cx'])
pm = PassManager(pass_)
new_circuit = pm.run(qc)
print(new_circuit.count_ops())
backend = Aer.get_backend('qasm_simulator')
job = execute(qc, backend, shots=1024)
counts = job.result().get_counts()
print(sorted(counts.items(), key=lambda x:x[1], reverse=True)[0:20])
plot_histogram(counts)
|
https://github.com/qiskit-community/qiskit-aqua-interfaces
|
qiskit-community
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2018, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Root main view"""
import sys
import tkinter as tk
import tkinter.messagebox as tkmb
import tkinter.ttk as ttk
import tkinter.filedialog as tkfd
from tkinter import font
import webbrowser
import os
from qiskit_aqua_interfaces import __version__, APP_DEPRECATION_MSG
from ._sectionsview import SectionsView
from ._sectiontextview import SectionTextView
from ._threadsafeoutputview import ThreadSafeOutputView
from ._emptyview import EmptyView
from ._preferencesdialog import PreferencesDialog
# pylint: disable=import-outside-toplevel
class MainView(ttk.Frame):
""" Main View """
def __init__(self, parent, guiprovider) -> None:
"""Create MainView object."""
super(MainView, self).__init__(parent)
self._guiprovider = guiprovider
self._guiprovider.controller.view = self
self.pack(expand=tk.YES, fill=tk.BOTH)
self._create_widgets()
self.master.title(self._guiprovider.title)
if parent is not None:
parent.protocol('WM_DELETE_WINDOW', self.quit)
def _show_about_dialog(self):
import qiskit.aqua as qa
lines = ['Qiskit Aqua Interfaces',
'Version: {}'.format(__version__),
'',
'Qiskit Aqua',
'Version: {}'.format(qa.__version__),
]
tkmb.showinfo(self._guiprovider.title, message='\n'.join(lines))
def _show_preferences(self):
dialog = PreferencesDialog(self, self._guiprovider)
dialog.do_init(tk.LEFT)
dialog.do_modal()
def _create_widgets(self):
self._make_menubar()
self._make_toolbar()
self._create_pane()
def _make_toolbar(self):
toolbar = ttk.Frame(self, relief=tk.SUNKEN, borderwidth=2)
toolbar.pack(side=tk.BOTTOM, fill=tk.X)
self._guiprovider.controller._button_text = tk.StringVar()
self._guiprovider.controller._button_text.set(self._guiprovider.controller._command)
self._guiprovider.controller._start_button = \
ttk.Button(toolbar,
textvariable=self._guiprovider.controller._button_text,
state='disabled',
command=self._guiprovider.controller.toggle)
self._guiprovider.controller._start_button.pack(side=tk.LEFT)
self._guiprovider.add_toolbar_items(toolbar)
self._guiprovider.controller._progress = ttk.Progressbar(toolbar, orient=tk.HORIZONTAL)
self._guiprovider.controller._progress.pack(side=tk.RIGHT, fill=tk.BOTH, expand=tk.TRUE)
def _make_menubar(self):
menubar = tk.Menu(self.master)
if sys.platform == 'darwin':
app_menu = tk.Menu(menubar, name='apple')
menubar.add_cascade(menu=app_menu)
app_menu.add_command(label='About {}'.format(
self._guiprovider.title), command=self._show_about_dialog)
self.master.createcommand('tk::mac::ShowPreferences', self._show_preferences)
self.master.createcommand('tk::mac::Quit', self.quit)
self.master.config(menu=menubar)
self._guiprovider.controller._filemenu = self._make_filemenu(menubar)
if sys.platform != 'darwin':
tools_menu = tk.Menu(menubar, tearoff=False)
tools_menu.add_command(label='Options', command=self._show_preferences)
menubar.add_cascade(label='Tools', menu=tools_menu)
help_menu = tk.Menu(menubar, tearoff=False)
if sys.platform != 'darwin':
help_menu.add_command(label='About {}'.format(self._guiprovider.title),
command=self._show_about_dialog)
help_menu.add_command(label='Open Help Center', command=self._open_help_center)
menubar.add_cascade(label='Help', menu=help_menu)
def _open_help_center(self):
webbrowser.open(self._guiprovider.help_hyperlink)
def _make_filemenu(self, menubar):
file_menu = tk.Menu(menubar, tearoff=False, postcommand=self._recent_files_menu)
file_menu.add_command(label='New', command=self._new_input)
file_menu.add_command(label='Open...', command=self._open_file)
file_menu.add_cascade(label='Open Recent', menu=tk.Menu(file_menu, tearoff=False))
file_menu.add_separator()
file_menu.add_command(label='Save', command=self._save_file)
file_menu.add_command(label='Save As...', command=self._save_file_as)
self._guiprovider.add_file_menu_items(file_menu)
if sys.platform != 'darwin':
file_menu.add_separator()
file_menu.add_command(label='Exit', command=self.quit)
menubar.add_cascade(label='File', menu=file_menu)
return file_menu
def _recent_files_menu(self):
recent_menu = tk.Menu(self._guiprovider.controller._filemenu, tearoff=False)
preferences = self._guiprovider.create_uipreferences()
for file in preferences.get_recent_files():
recent_menu.add_command(label=file, command=lambda f=file: self._open_recent_file(f))
recent_menu.add_separator()
recent_menu.add_command(label='Clear', command=self._clear_recent)
self._guiprovider.controller._filemenu.entryconfig(2, menu=recent_menu)
def _new_input(self):
self._guiprovider.controller.new_input()
def _open_file(self):
preferences = self._guiprovider.create_uipreferences()
filename = tkfd.askopenfilename(parent=self,
title='Open File',
initialdir=preferences.get_openfile_initialdir())
if filename and self._guiprovider.controller.open_file(filename):
preferences.add_recent_file(filename)
preferences.set_openfile_initialdir(os.path.dirname(filename))
preferences.save()
def _open_recent_file(self, filename):
self._guiprovider.controller.open_file(filename)
def _clear_recent(self):
preferences = self._guiprovider.create_uipreferences()
preferences.clear_recent_files()
preferences.save()
def _save_file(self):
self._guiprovider.controller.save_file()
def _save_file_as(self):
if self._guiprovider.controller.is_empty():
self._guiprovider.controller.outputview.write_line("No data to save.")
return
preferences = self._guiprovider.create_uipreferences()
filename = tkfd.asksaveasfilename(parent=self,
title='Save File',
initialdir=preferences.get_savefile_initialdir())
if filename and self._guiprovider.controller.save_file_as(filename):
preferences.add_recent_file(filename)
preferences.set_savefile_initialdir(os.path.dirname(filename))
preferences.save()
def _create_pane(self):
label_font = font.nametofont('TkHeadingFont').copy()
label_font.configure(size=12, weight='bold')
style = ttk.Style()
style.configure('Title.TLabel',
borderwidth=0,
anchor=tk.CENTER)
label = ttk.Label(self,
style='Title.TLabel',
padding=(5, 5, 5, 5),
textvariable=self._guiprovider.controller._title)
label['font'] = label_font
label.pack(side=tk.TOP, expand=tk.NO, fill=tk.X)
main_pane = ttk.PanedWindow(self, orient=tk.VERTICAL)
main_pane.pack(expand=tk.YES, fill=tk.BOTH)
top_pane = ttk.PanedWindow(main_pane, orient=tk.HORIZONTAL)
top_pane.pack(expand=tk.YES, fill=tk.BOTH)
main_pane.add(top_pane)
self._guiprovider.controller._sections_view = \
SectionsView(self._guiprovider.controller, top_pane)
self._guiprovider.controller._sections_view.pack(expand=tk.YES, fill=tk.BOTH)
top_pane.add(self._guiprovider.controller._sections_view, weight=1)
main_container = tk.Frame(top_pane)
main_container.pack(expand=tk.YES, fill=tk.BOTH)
style = ttk.Style()
style.configure('PropViewTitle.TLabel',
borderwidth=1,
relief=tk.RIDGE,
anchor=tk.CENTER)
label = ttk.Label(main_container,
style='PropViewTitle.TLabel',
padding=(5, 5, 5, 5),
textvariable=self._guiprovider.controller._sections_view_title)
label['font'] = label_font
label.pack(side=tk.TOP, expand=tk.NO, fill=tk.X)
container = tk.Frame(main_container)
container.pack(side=tk.BOTTOM, expand=tk.YES, fill=tk.BOTH)
container.grid_rowconfigure(0, weight=1)
container.grid_columnconfigure(0, weight=1)
self._guiprovider.controller._empty_view = EmptyView(container)
self._guiprovider.controller._empty_view.grid(row=0, column=0, sticky='nsew')
self._guiprovider.controller._text_view = \
SectionTextView(self._guiprovider.controller, container)
self._guiprovider.controller._text_view.grid(row=0, column=0, sticky='nsew')
self._guiprovider.controller._properties_view = \
self._guiprovider.create_section_properties_view(container)
self._guiprovider.controller._properties_view.grid(row=0, column=0, sticky='nsew')
self._guiprovider.controller._empty_view.tkraise()
top_pane.add(main_container, weight=1)
self._guiprovider.controller.outputview = ThreadSafeOutputView(main_pane)
self._guiprovider.controller.outputview.pack(expand=tk.YES, fill=tk.BOTH)
main_pane.add(self._guiprovider.controller.outputview)
# redirect output
sys.stdout = self._guiprovider.controller.outputview
sys.stderr = self._guiprovider.controller.outputview
# update logging after redirect
self.after(0, self._set_preferences_logging)
self.update_idletasks()
self._guiprovider.controller._sections_view.show_add_button(False)
self._guiprovider.controller._sections_view.show_remove_button(False)
self._guiprovider.controller._sections_view.show_defaults_button(False)
self._guiprovider.controller._empty_view.set_toolbar_size(
self._guiprovider.controller._sections_view.get_toolbar_size())
self._guiprovider.controller.outputview.write_line(APP_DEPRECATION_MSG)
def _set_preferences_logging(self):
preferences = self._guiprovider.create_uipreferences()
config = preferences.get_logging_config()
if config is not None:
self._guiprovider.set_logging_config(config)
def quit(self):
if tkmb.askyesno('Verify quit', 'Are you sure you want to quit?'):
preferences = self._guiprovider.create_uipreferences()
preferences.set_geometry(self.master.winfo_geometry())
preferences.save()
self._guiprovider.controller.stop()
ttk.Frame.quit(self)
return True
return False
|
https://github.com/JoelHBierman/SSVQE
|
JoelHBierman
|
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
import unittest
import qiskit
from qiskit.circuit.library import TwoLocal
from qiskit import QuantumCircuit, Aer
from qiskit.utils import QuantumInstance
from qiskit.opflow import Z, I
from volta.ssvqe import SSVQE
from volta.utils import classical_solver
class TestSSVQD(unittest.TestCase):
def setUp(self):
optimizer = qiskit.algorithms.optimizers.COBYLA()
backend = QuantumInstance(
backend=Aer.get_backend("qasm_simulator"), shots=10000
)
hamiltonian = 1 / 2 * (Z ^ I) + 1 / 2 * (Z ^ Z)
ansatz = TwoLocal(hamiltonian.num_qubits, ["ry", "rz"], "cx", reps=2)
self.Algo = SSVQE(
hamiltonian=hamiltonian,
ansatz=ansatz,
optimizer=optimizer,
n_excited=2,
backend=backend,
)
self.energy = []
self.energy.append(self.Algo.run(index=0)[0])
self.energy.append(self.Algo.run(index=1)[0])
self.eigenvalues, _ = classical_solver(hamiltonian)
def test_energies(self):
want = self.eigenvalues[0]
got = self.energy[0]
decimalPlace = 1
message = "SSVQE not working for the ground state of 1/2*((Z^I) + (Z^Z))"
self.assertAlmostEqual(want, got, decimalPlace, message)
decimalPlace = 1
want = self.eigenvalues[1]
got = self.energy[1]
message = "SSVQE not working for the first excited state of 1/2*((Z^I) + (Z^Z))"
self.assertAlmostEqual(want, got, decimalPlace, message)
if __name__ == "__main__":
unittest.main(argv=[""], verbosity=2, exit=False)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import pulse
d0 = pulse.DriveChannel(0)
d1 = pulse.DriveChannel(1)
with pulse.build() as pulse_prog:
with pulse.align_right():
# this pulse will start at t=0
pulse.play(pulse.Constant(100, 1.0), d0)
# this pulse will start at t=80
pulse.play(pulse.Constant(20, 1.0), d1)
pulse_prog.draw()
|
https://github.com/Qiskit-Extensions/circuit-knitting-toolbox
|
Qiskit-Extensions
|
# This code is a Qiskit project.
# (C) Copyright IBM 2024.
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Tests for cco_utils module."""
from __future__ import annotations
from typing import Callable
import pytest
from pytest import fixture
from qiskit.circuit.library import EfficientSU2
from qiskit import QuantumCircuit, QuantumRegister
from qiskit.circuit import Qubit, Instruction, CircuitInstruction
from circuit_knitting.cutting.cut_finding.cco_utils import (
qc_to_cco_circuit,
cco_to_qc_circuit,
)
from circuit_knitting.cutting.cut_finding.circuit_interface import (
SimpleGateList,
CircuitElement,
)
def create_test_circuit_1():
tc_1 = QuantumCircuit(2)
tc_1.h(1)
tc_1.barrier(1)
tc_1.s(0)
tc_1.barrier()
tc_1.cx(1, 0)
return tc_1
def create_test_circuit_2():
tc_2 = EfficientSU2(2, entanglement="linear", reps=2).decompose()
tc_2.assign_parameters([0.4] * len(tc_2.parameters), inplace=True)
return tc_2
# test circuit 3
@fixture
def internal_test_circuit():
circuit = [
CircuitElement(name="cx", params=[], qubits=[0, 1], gamma=3),
CircuitElement(name="cx", params=[], qubits=[2, 3], gamma=3),
CircuitElement(name="cx", params=[], qubits=[1, 2], gamma=3),
CircuitElement(name="cx", params=[], qubits=[0, 1], gamma=3),
CircuitElement(name="cx", params=[], qubits=[2, 3], gamma=3),
CircuitElement(name="h", params=[], qubits=[0], gamma=None),
CircuitElement(name="rx", params=[0.4], qubits=[0], gamma=None),
]
interface = SimpleGateList(circuit)
interface.insert_gate_cut(2, "LO")
interface.define_subcircuits([[0, 1], [2, 3]])
return interface
@pytest.mark.parametrize(
"create_test_circuit, known_output",
[
(
create_test_circuit_1,
[
CircuitElement("h", [], [1], None),
CircuitElement("barrier", [], [1], None),
CircuitElement("s", [], [0], None),
"barrier",
CircuitElement("cx", [], [1, 0], 3),
],
),
(
create_test_circuit_2,
[
CircuitElement("ry", [0.4], [0], None),
CircuitElement("rz", [0.4], [0], None),
CircuitElement("ry", [0.4], [1], None),
CircuitElement("rz", [0.4], [1], None),
CircuitElement("cx", [], [0, 1], 3),
CircuitElement("ry", [0.4], [0], None),
CircuitElement("rz", [0.4], [0], None),
CircuitElement("ry", [0.4], [1], None),
CircuitElement("rz", [0.4], [1], None),
CircuitElement("cx", [], [0, 1], 3),
CircuitElement("ry", [0.4], [0], None),
CircuitElement("rz", [0.4], [0], None),
CircuitElement("ry", [0.4], [1], None),
CircuitElement("rz", [0.4], [1], None),
],
),
],
)
def test_qc_to_cco_circuit(
create_test_circuit: Callable[[], QuantumCircuit],
known_output: list[CircuitElement, str],
):
test_circuit = create_test_circuit()
test_circuit_internal = qc_to_cco_circuit(test_circuit)
assert test_circuit_internal == known_output
def test_cco_to_qc_circuit(internal_test_circuit: SimpleGateList):
qc_cut = cco_to_qc_circuit(internal_test_circuit)
assert qc_cut.data == [
CircuitInstruction(
operation=Instruction(name="cx", num_qubits=2, num_clbits=0, params=[]),
qubits=(
Qubit(QuantumRegister(4, "q"), 0),
Qubit(QuantumRegister(4, "q"), 1),
),
clbits=(),
),
CircuitInstruction(
operation=Instruction(name="cx", num_qubits=2, num_clbits=0, params=[]),
qubits=(
Qubit(QuantumRegister(4, "q"), 2),
Qubit(QuantumRegister(4, "q"), 3),
),
clbits=(),
),
CircuitInstruction(
operation=Instruction(name="cx", num_qubits=2, num_clbits=0, params=[]),
qubits=(
Qubit(QuantumRegister(4, "q"), 0),
Qubit(QuantumRegister(4, "q"), 1),
),
clbits=(),
),
CircuitInstruction(
operation=Instruction(name="cx", num_qubits=2, num_clbits=0, params=[]),
qubits=(
Qubit(QuantumRegister(4, "q"), 2),
Qubit(QuantumRegister(4, "q"), 3),
),
clbits=(),
),
CircuitInstruction(
operation=Instruction(name="h", num_qubits=1, num_clbits=0, params=[]),
qubits=(Qubit(QuantumRegister(4, "q"), 0),),
clbits=(),
),
CircuitInstruction(
operation=Instruction(name="rx", num_qubits=1, num_clbits=0, params=[0.4]),
qubits=(Qubit(QuantumRegister(4, "q"), 0),),
clbits=(),
),
]
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import numpy as np
from qiskit import QuantumCircuit
from qiskit.providers.fake_provider import FakeVigoV2
backend = FakeVigoV2()
qc = QuantumCircuit(2, 1)
qc.h(0)
qc.x(1)
qc.cp(np.pi/4, 0, 1)
qc.h(0)
qc.measure([0], [0])
qc.draw(output='mpl')
|
https://github.com/yatharth0610/Quantum-Algorithms-qiskit-
|
yatharth0610
|
%matplotlib inline
# Importing standard Qiskit libraries and configuring account
from qiskit import QuantumCircuit, execute, Aer, IBMQ
from qiskit.compiler import transpile, assemble
from qiskit.tools.jupyter import *
from qiskit.visualization import *
import numpy as np
from fractions import Fraction as frac
import qiskit.quantum_info as qi
# Loading your IBM Q account(s)
provider = IBMQ.load_account()
qc=QuantumCircuit(4)
#In this particular oracle, the last qubit is storing the value of the function
qc.cx(0,3)
qc.cx(1,3)
qc.cx(2,3)
#The last qubit is 1 if there are odd no. of 1s in the other 3 qubits
#and 0 otherwise
#Hence it is a balanced function
qc.draw('mpl')
qc1=QuantumCircuit(3)
qc1.x(2)
qc1.h(0)
qc1.h(1)
qc1.h(2)
qc1.barrier(range(3))
qc1.cx(0,2)
qc1.cx(1,2)
qc1.barrier(range(3))
qc1.h(0)
qc1.h(1)
meas = QuantumCircuit(3, 2)
meas.measure(range(2),range(2))
# The Qiskit circuit object supports composition using
# the addition operator.
circ = qc1+meas
circ.draw('mpl')
backend_sim = Aer.get_backend('qasm_simulator')
job_sim = execute(circ, backend_sim, shots=1000)
result_sim = job_sim.result()
counts = result_sim.get_counts(circ)
print(counts)
plot_histogram(counts)
qc2=QuantumCircuit(5)
qc2.x(4)
qc2.h(0)
qc2.h(1)
qc2.h(2)
qc2.h(3)
qc2.h(4)
qc2.barrier(range(5))
#Your code for the oracle here
#YOU ARE PERMITTED TO USE ONLY SINGLE QUBIT GATES AND CNOT(cx) GATES
qc2.cx(0,4)
qc2.cx(1,4)
qc2.cx(2,4)
qc2.cx(3,4)
qc2.x(4)
qc2.barrier(range(5))
qc2.h(0)
qc2.h(1)
qc2.h(2)
qc2.h(3)
meas2 = QuantumCircuit(5, 4)
meas2.measure(range(4),range(4))
circ2 = qc2+meas2
circ2.draw('mpl')
#verification cell, reinitialising the circuit so that it's easier for you to copy-paste the oracle
qc2=QuantumCircuit(5)
#Add X gates HERE as required to change the input state
qc2.x([0,2])
qc2.barrier(range(5))
qc2.cx(0,4)
qc2.cx(1,4)
qc2.cx(2,4)
qc2.cx(3,4)
qc2.x(4)
qc2.barrier(range(5))
measv = QuantumCircuit(5, 1)
measv.measure(4,0)
circv = qc2+measv
circv.draw('mpl')
#DO NOT RUN THIS CELL WITHOUT EDITING THE ABOVE ONE AS DESIRED
#The following code will give you f(x) for the value of x you chose in the above cell
backend_sim2 = Aer.get_backend('qasm_simulator')
job_sim2 = execute(circv, backend_sim2, shots=1000)
result_sim2 = job_sim2.result()
counts2 = result_sim2.get_counts(circv)
print(counts2)
plot_histogram(counts2)
|
https://github.com/2lambda123/Qiskit-qiskit
|
2lambda123
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2023, 2024.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""
Statevector Sampler class
"""
from __future__ import annotations
import warnings
from dataclasses import dataclass
from typing import Iterable
import numpy as np
from numpy.typing import NDArray
from qiskit import ClassicalRegister, QiskitError, QuantumCircuit
from qiskit.circuit import ControlFlowOp
from qiskit.quantum_info import Statevector
from .base import BaseSamplerV2
from .base.validation import _has_measure
from .containers import (
BitArray,
DataBin,
PrimitiveResult,
SamplerPubResult,
SamplerPubLike,
)
from .containers.sampler_pub import SamplerPub
from .containers.bit_array import _min_num_bytes
from .primitive_job import PrimitiveJob
from .utils import bound_circuit_to_instruction
@dataclass
class _MeasureInfo:
creg_name: str
num_bits: int
num_bytes: int
qreg_indices: list[int]
class StatevectorSampler(BaseSamplerV2):
"""
Simple implementation of :class:`BaseSamplerV2` using full state vector simulation.
This class is implemented via :class:`~.Statevector` which turns provided circuits into
pure state vectors, and is therefore incompatible with mid-circuit measurements (although
other implementations may be).
As seen in the example below, this sampler supports providing arrays of parameter value sets to
bind against a single circuit.
Each tuple of ``(circuit, <optional> parameter values, <optional> shots)``, called a sampler
primitive unified bloc (PUB), produces its own array-valued result. The :meth:`~run` method can
be given many pubs at once.
.. code-block:: python
from qiskit.circuit import (
Parameter, QuantumCircuit, ClassicalRegister, QuantumRegister
)
from qiskit.primitives import StatevectorSampler
import matplotlib.pyplot as plt
import numpy as np
# Define our circuit registers, including classical registers
# called 'alpha' and 'beta'.
qreg = QuantumRegister(3)
alpha = ClassicalRegister(2, "alpha")
beta = ClassicalRegister(1, "beta")
# Define a quantum circuit with two parameters.
circuit = QuantumCircuit(qreg, alpha, beta)
circuit.h(0)
circuit.cx(0, 1)
circuit.cx(1, 2)
circuit.ry(Parameter("a"), 0)
circuit.rz(Parameter("b"), 0)
circuit.cx(1, 2)
circuit.cx(0, 1)
circuit.h(0)
circuit.measure([0, 1], alpha)
circuit.measure([2], beta)
# Define a sweep over parameter values, where the second axis is over.
# the two parameters in the circuit.
params = np.vstack([
np.linspace(-np.pi, np.pi, 100),
np.linspace(-4 * np.pi, 4 * np.pi, 100)
]).T
# Instantiate a new statevector simulation based sampler object.
sampler = StatevectorSampler()
# Start a job that will return shots for all 100 parameter value sets.
pub = (circuit, params)
job = sampler.run([pub], shots=256)
# Extract the result for the 0th pub (this example only has one pub).
result = job.result()[0]
# There is one BitArray object for each ClassicalRegister in the
# circuit. Here, we can see that the BitArray for alpha contains data
# for all 100 sweep points, and that it is indeed storing data for 2
# bits over 256 shots.
assert result.data.alpha.shape == (100,)
assert result.data.alpha.num_bits == 2
assert result.data.alpha.num_shots == 256
# We can work directly with a binary array in performant applications.
raw = result.data.alpha.array
# For small registers where it is anticipated to have many counts
# associated with the same bitstrings, we can turn the data from,
# for example, the 22nd sweep index into a dictionary of counts.
counts = result.data.alpha.get_counts(22)
# Or, convert into a list of bitstrings that preserve shot order.
bitstrings = result.data.alpha.get_bitstrings(22)
print(bitstrings)
"""
def __init__(self, *, default_shots: int = 1024, seed: np.random.Generator | int | None = None):
"""
Args:
default_shots: The default shots for the sampler if not specified during run.
seed: The seed or Generator object for random number generation.
If None, a random seeded default RNG will be used.
"""
self._default_shots = default_shots
self._seed = seed
@property
def default_shots(self) -> int:
"""Return the default shots"""
return self._default_shots
@property
def seed(self) -> np.random.Generator | int | None:
"""Return the seed or Generator object for random number generation."""
return self._seed
def run(
self, pubs: Iterable[SamplerPubLike], *, shots: int | None = None
) -> PrimitiveJob[PrimitiveResult[SamplerPubResult]]:
if shots is None:
shots = self._default_shots
coerced_pubs = [SamplerPub.coerce(pub, shots) for pub in pubs]
if any(len(pub.circuit.cregs) == 0 for pub in coerced_pubs):
warnings.warn(
"One of your circuits has no output classical registers and so the result "
"will be empty. Did you mean to add measurement instructions?",
UserWarning,
)
job = PrimitiveJob(self._run, coerced_pubs)
job._submit()
return job
def _run(self, pubs: Iterable[SamplerPub]) -> PrimitiveResult[SamplerPubResult]:
results = [self._run_pub(pub) for pub in pubs]
return PrimitiveResult(results)
def _run_pub(self, pub: SamplerPub) -> SamplerPubResult:
circuit, qargs, meas_info = _preprocess_circuit(pub.circuit)
bound_circuits = pub.parameter_values.bind_all(circuit)
arrays = {
item.creg_name: np.zeros(
bound_circuits.shape + (pub.shots, item.num_bytes), dtype=np.uint8
)
for item in meas_info
}
for index, bound_circuit in np.ndenumerate(bound_circuits):
final_state = Statevector(bound_circuit_to_instruction(bound_circuit))
final_state.seed(self._seed)
if qargs:
samples = final_state.sample_memory(shots=pub.shots, qargs=qargs)
else:
samples = [""] * pub.shots
samples_array = np.array([np.fromiter(sample, dtype=np.uint8) for sample in samples])
for item in meas_info:
ary = _samples_to_packed_array(samples_array, item.num_bits, item.qreg_indices)
arrays[item.creg_name][index] = ary
meas = {
item.creg_name: BitArray(arrays[item.creg_name], item.num_bits) for item in meas_info
}
return SamplerPubResult(DataBin(**meas, shape=pub.shape), metadata={"shots": pub.shots})
def _preprocess_circuit(circuit: QuantumCircuit):
num_bits_dict = {creg.name: creg.size for creg in circuit.cregs}
mapping = _final_measurement_mapping(circuit)
qargs = sorted(set(mapping.values()))
qargs_index = {v: k for k, v in enumerate(qargs)}
circuit = circuit.remove_final_measurements(inplace=False)
if _has_control_flow(circuit):
raise QiskitError("StatevectorSampler cannot handle ControlFlowOp")
if _has_measure(circuit):
raise QiskitError("StatevectorSampler cannot handle mid-circuit measurements")
# num_qubits is used as sentinel to fill 0 in _samples_to_packed_array
sentinel = len(qargs)
indices = {key: [sentinel] * val for key, val in num_bits_dict.items()}
for key, qreg in mapping.items():
creg, ind = key
indices[creg.name][ind] = qargs_index[qreg]
meas_info = [
_MeasureInfo(
creg_name=name,
num_bits=num_bits,
num_bytes=_min_num_bytes(num_bits),
qreg_indices=indices[name],
)
for name, num_bits in num_bits_dict.items()
]
return circuit, qargs, meas_info
def _samples_to_packed_array(
samples: NDArray[np.uint8], num_bits: int, indices: list[int]
) -> NDArray[np.uint8]:
# samples of `Statevector.sample_memory` will be in the order of
# qubit_last, ..., qubit_1, qubit_0.
# reverse the sample order into qubit_0, qubit_1, ..., qubit_last and
# pad 0 in the rightmost to be used for the sentinel introduced by _preprocess_circuit.
ary = np.pad(samples[:, ::-1], ((0, 0), (0, 1)), constant_values=0)
# place samples in the order of clbit_last, ..., clbit_1, clbit_0
ary = ary[:, indices[::-1]]
# pad 0 in the left to align the number to be mod 8
# since np.packbits(bitorder='big') pads 0 to the right.
pad_size = -num_bits % 8
ary = np.pad(ary, ((0, 0), (pad_size, 0)), constant_values=0)
# pack bits in big endian order
ary = np.packbits(ary, axis=-1)
return ary
def _final_measurement_mapping(circuit: QuantumCircuit) -> dict[tuple[ClassicalRegister, int], int]:
"""Return the final measurement mapping for the circuit.
Parameters:
circuit: Input quantum circuit.
Returns:
Mapping of classical bits to qubits for final measurements.
"""
active_qubits = set(range(circuit.num_qubits))
active_cbits = set(range(circuit.num_clbits))
# Find final measurements starting in back
mapping = {}
for item in circuit[::-1]:
if item.operation.name == "measure":
loc = circuit.find_bit(item.clbits[0])
cbit = loc.index
qbit = circuit.find_bit(item.qubits[0]).index
if cbit in active_cbits and qbit in active_qubits:
for creg in loc.registers:
mapping[creg] = qbit
active_cbits.remove(cbit)
elif item.operation.name not in ["barrier", "delay"]:
for qq in item.qubits:
_temp_qubit = circuit.find_bit(qq).index
if _temp_qubit in active_qubits:
active_qubits.remove(_temp_qubit)
if not active_cbits or not active_qubits:
break
return mapping
def _has_control_flow(circuit: QuantumCircuit) -> bool:
return any(isinstance(instruction.operation, ControlFlowOp) for instruction in circuit)
|
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
|
aryashah2k
|
from qiskit import *
q2=QuantumRegister(3,"qreg")
c2=ClassicalRegister(3,"creg")
qc2=QuantumCircuit(q2,c2)
qc2.x(q2[1])
qc2.barrier()
qc2.x(q2[2])
qc2.ccx(q2[2],q2[1],q2[0])
qc2.x(q2[2])
qc2.barrier()
qc2.measure(q2,c2)
job=execute(qc2,Aer.get_backend('qasm_simulator'),shots=100)
counts=job.result().get_counts(qc2)
print(counts)
qc2.draw('mpl')
q2 = QuantumRegister(2,"qreg")
c2 = ClassicalRegister(2,"creg")
qc2 = QuantumCircuit(q2,c2)
qc2.h(q2[0])
qc2.cx(q2[0],q2[1])
#Your code here
qc2.x(q2[0])
qc2.measure(q2,c2)
job = execute(qc2,Aer.get_backend('qasm_simulator'),shots=1000)
counts = job.result().get_counts(qc2)
print(counts) # counts is a dictionary
qc2.draw('mpl')
qc = QuantumCircuit(2)
#Your code here
qc.h(1)
qc.draw('mpl')
q3=QuantumRegister(3,"qreg")
c3=ClassicalRegister(3,"creg")
qc3=QuantumCircuit(q3,c3)
qc3.h(q3[0])
qc3.cx(q3[0],q3[1])
qc3.cx(q3[0],q3[2])
qc3.measure(q3,c3)
job=execute(qc3,Aer.get_backend('qasm_simulator'),shots=1000)
counts=job.result().get_counts(qc3)
print(counts)
qc3.draw('mpl')
|
https://github.com/wyqian1027/Qiskit-Fall-Fest-USC-2022
|
wyqian1027
|
from qiskit import QuantumCircuit, execute, Aer
from qiskit.opflow import One, Zero, Plus, Minus
from qiskit.opflow import I, X, Y, Z, S, H
from qiskit.visualization import plot_bloch_multivector, plot_bloch_vector, plot_histogram
from math import pi, sqrt, acos, asin, e, log, sin, cos
from numpy import angle
Zero
One
Plus
Minus
1.5 * Zero
-3 * Plus
Zero^Zero^One
Plus^Minus^Zero^Zero
Zero + One
Plus + Minus
(Zero^Zero^One) + (Zero^One^Zero) + (One^Zero^Zero)
(Zero^Zero^One) - 1.5*(Zero^One^Zero) + 3*(One^Zero^Zero)
def arbitrary_state(beta):
##### ==================================
# Write your solution in here.
alpha = sqrt(1 - abs(beta)**2)
return alpha*Zero + beta*One
##### ==================================
Zero.eval('0')
Zero.eval('1')
Minus.eval('0')
Minus.eval('1')
~Zero
~One
~Plus
print("< 0 | 0 > =",(~Zero @ Zero).eval())
print("< 1 | 0 > =",(~One @ Zero).eval())
beta = 0.232 + 0.341j
arbitrary_state(beta)
beta = 0.232 + 0.341j
print("< 1 | Ψ > =",(~One @ arbitrary_state(beta)).eval())
print("< 0 | Ψ > =",(~Zero @ arbitrary_state(beta)).eval())
print("< Ψ | Ψ > =", (~arbitrary_state(beta) @ arbitrary_state(beta)).eval())
def normality_check(beta):
##### ==================================
# Write your solution in here.
return abs((~One @ arbitrary_state(beta)).eval())**2 + abs((~Zero @ arbitrary_state(beta)).eval())**2
##### ==================================
# Play with your beta parameter to see if this value changes.
beta = 0.232 + 0.341j
print("|< 1 | Ψ >|^2 + |< 0 | Ψ >|^2 =", normality_check(beta))
def convert_braket_to_Bloch(beta):
if beta == 0: # special case
return [1.0, 0, 0]
##### ==================================
# Write your solution in here.
alpha = sqrt(1 - abs(beta)**2)
theta = acos(alpha)*2
beta = beta / sin(theta/2)
phi = angle(beta)
##### ==================================
return [1.0, theta, phi]
# Check
beta = -1/sqrt(2)*1j
plot_bloch_vector(convert_braket_to_Bloch(beta), coord_type='spherical',
title=r"$|\psi\rangle = \frac{1}{\sqrt{2}}|0\rangle-\frac{1}{\sqrt{2}}i|0\rangle$")
# Play with more values of beta to see if it matches with your expectation
beta = -1/sqrt(10)*1j
plot_bloch_vector(convert_braket_to_Bloch(beta), coord_type='spherical',
title=r"$|\psi\rangle = \sqrt{1-|\beta|^2}|0\rangle+\beta|0\rangle$ in Spherical")
X
Y
Z
def expectation_Z(beta):
##### ==================================
# Write your solution in here. There are more than one solution here...
return (~arbitrary_state(beta) @ Z @ arbitrary_state(beta)).eval()
##### ==================================
print("<Z> =", expectation_Z(beta))
def expectation_X(beta):
##### ==================================
# Write your solution in here. There are more than one solution here...
return (~arbitrary_state(beta) @ ~H @ Z @ H @ arbitrary_state(beta)).eval()
##### ==================================
def expectation_Y(beta):
##### ==================================
# Write your solution in here. There are more than one solution here...
return (~arbitrary_state(beta) @ ~(H @ ~S) @ Z @ (H @ ~S) @ arbitrary_state(beta)).eval()
##### ==================================
def get_cartesian_coordinate(beta):
##### ==================================
# Write your solution in here. There are more than one solution here...
x = expectation_X(beta).real
y = expectation_Y(beta).real
z = expectation_Z(beta).real
##### ==================================
return [x, y, z]
# Play with more values of beta to see if it matches with your previous Bloch sphere
beta = -1/sqrt(10)*1j
plot_bloch_vector(get_cartesian_coordinate(beta), coord_type='cartesian',
title=r"$|\psi\rangle = \sqrt{1-|\beta|^2}|0\rangle+\beta|0\rangle$ in Cartesian")
# Let's define the quantum simulator
sv_simulator = Aer.get_backend("statevector_simulator")
qasm_simulator = Aer.get_backend("qasm_simulator")
this_circ = QuantumCircuit(1)
this_circ.initialize([1/sqrt(2), -1/sqrt(2)])
this_circ.measure_all()
this_circ.draw('mpl')
shots = 1024
counts = execute(this_circ, backend=qasm_simulator, shots=shots).result().get_counts()
print(counts)
plot_histogram(counts, title=r"Measuring the $|+\rangle$ state")
def contruct_arbitrary_state_on_circuit(beta):
##### ==================================
# Write your solution in here. Here you do not need to append the measurement part in this function
circuit = QuantumCircuit(1)
circuit.initialize([sqrt(1-abs(beta)**2), beta])
##### ==================================
return circuit
shots = 81920
beta = 0.213
this_circuit = contruct_arbitrary_state_on_circuit(beta)
this_circuit.measure_all()
counts = execute(this_circuit, backend=qasm_simulator, shots=shots).result().get_counts()
print("Probability in |1> basis =", beta**2)
plot_histogram(counts, title=r"Measuring the arbitrary $|\psi(\beta)\rangle$ state")
def expectation_Z_with_QASM(beta, shots):
##### ==================================
# Write your solution in here. Here
circuit = contruct_arbitrary_state_on_circuit(beta)
circuit.measure_all()
counts = execute(circuit, backend=qasm_simulator, shots=shots).result().get_counts()
expectation = (counts["0"] - counts["1"])/(counts["0"] + counts["1"])
##### ==================================
return expectation
beta = -1/sqrt(2)*1j
shots = 81920
print("Expectation <Z> with QASM =", expectation_Z_with_QASM(beta, shots=shots))
print("Expectation <Z> with opflow =", expectation_Z(beta))
import qiskit.tools.jupyter
%qiskit_version_table
|
https://github.com/Z-928/Bugs4Q
|
Z-928
|
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit.wrapper import available_backends, get_backend
from qiskit.wrapper import execute as q_execute
q = QuantumRegister(2, name='q')
c = ClassicalRegister(2, name='c')
qc = QuantumCircuit(q,c)
qc.h(q[0])
qc.h(q[1])
qc.cx(q[0], q[1])
qc.measure(q, c)
z = 0.995004165 + 1j * 0.099833417
z = z / abs(z)
u_error = np.array([[1, 0], [0, z]])
noise_params = {'U':
{'gate_time': 1,
'p_depol': 0.001,
'p_pauli': [0, 0, 0.01],
'U_error': u_error
}
}
config = {"noise_params": noise_params}
ret = q_execute(qc, 'local_qasm_simulator_cpp', shots=1024, config=config)
ret = ret.result()
print(ret.get_counts())
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
circ = QuantumCircuit(2, 2)
circ.h(0)
circ.cx(0, 1)
circ.measure([0, 1], [0, 1])
circ.draw("mpl")
from qiskit import transpile, schedule as build_schedule
from qiskit.providers.fake_provider import FakeHanoi
backend = FakeHanoi()
transpiled_circ = transpile(circ, backend) # Undefined Hadamard is replaced by U1
schedule = build_schedule(transpiled_circ, backend)
schedule.draw()
from qiskit import pulse
with pulse.build() as h_q0:
pulse.play(pulse.library.Gaussian(duration=256, amp=0.2, sigma=50, name='custom'),
pulse.DriveChannel(0))
circ.add_calibration('h', [0], h_q0)
schedule = build_schedule(circ, backend)
schedule.draw()
circ = QuantumCircuit(2, 2)
circ.x(0)
circ.x(0)
circ.x(1)
circ.measure([0, 1], [0, 1])
circ.draw("mpl")
schedule = build_schedule(circ, backend, method="as_late_as_possible")
schedule.filter(channels=[pulse.DriveChannel(0), pulse.DriveChannel(1)]).draw()
schedule = build_schedule(circ, backend, method="as_soon_as_possible")
schedule.filter(channels=[pulse.DriveChannel(0), pulse.DriveChannel(1)]).draw()
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, 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.
"""Width pass testing"""
import unittest
from qiskit import QuantumCircuit, QuantumRegister
from qiskit.converters import circuit_to_dag
from qiskit.transpiler.passes import Width
from qiskit.test import QiskitTestCase
class TestWidthPass(QiskitTestCase):
"""Tests for Depth analysis methods."""
def test_empty_dag(self):
"""Empty DAG has 0 depth"""
circuit = QuantumCircuit()
dag = circuit_to_dag(circuit)
pass_ = Width()
_ = pass_.run(dag)
self.assertEqual(pass_.property_set["width"], 0)
def test_just_qubits(self):
"""A dag with 8 operations and no classic bits"""
qr = QuantumRegister(2)
circuit = QuantumCircuit(qr)
circuit.h(qr[0])
circuit.h(qr[1])
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])
dag = circuit_to_dag(circuit)
pass_ = Width()
_ = pass_.run(dag)
self.assertEqual(pass_.property_set["width"], 2)
if __name__ == "__main__":
unittest.main()
|
https://github.com/swe-train/qiskit__qiskit
|
swe-train
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2023
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
# pylint: disable=no-member,invalid-name,missing-docstring,no-name-in-module
# pylint: disable=attribute-defined-outside-init,unsubscriptable-object
"""Module for estimating import times."""
from sys import executable
from subprocess import call
class QiskitImport:
def time_qiskit_import(self):
call((executable, "-c", "import qiskit"))
|
https://github.com/jonasmaziero/computacao_quantica_qiskit_sbf_2023
|
jonasmaziero
|
from qiskit import QuantumCircuit; qc = QuantumCircuit(2,2)
qc.barrier()
qc.cx(0,1); qc.h(0)
qc.barrier()
qc.measure([0,1],[0,1])
qc.draw('mpl')
from qiskit import QuantumCircuit, execute, Aer; from qiskit.tools.visualization import plot_histogram
simulator = Aer.get_backend('qasm_simulator'); nshots = 2**13
qc = QuantumCircuit(2,2)
qc.h(0); qc.cx(0,1) # prepara |Phi+>
qc.barrier()
qc.cx(0,1); qc.h(0); qc.measure([0,1],[0,1]) # mede na BB
qc.draw('mpl')
job = execute(qc, backend=simulator, shots=nshots)
plot_histogram(job.result().get_counts())
qc = QuantumCircuit(2,2)
qc.x(1); qc.h(0); qc.cx(0,1) # prepara |Psi+>
qc.barrier()
qc.cx(0,1); qc.h(0); qc.measure([0,1],[0,1]) # mede na BB
qc.draw('mpl')
job = execute(qc, backend=simulator, shots=nshots)
plot_histogram(job.result().get_counts())
qc = QuantumCircuit(2,2)
qc.x(0); qc.h(0); qc.cx(0,1) # prepara |Phi->
qc.barrier()
qc.cx(0,1); qc.h(0); qc.measure([0,1],[0,1]) # mede na BB
qc.draw('mpl')
job = execute(qc, backend=simulator, shots=nshots)
plot_histogram(job.result().get_counts())
qc = QuantumCircuit(2,2)
qc.x([0,1]); qc.h(0); qc.cx(0,1) # prepara |Psi->
qc.barrier()
qc.cx(0,1); qc.h(0); qc.measure([0,1],[0,1]) # mede na BB
qc.draw('mpl')
job = execute(qc, backend=simulator, shots=nshots)
plot_histogram(job.result().get_counts())
import qiskit
qiskit.IBMQ.save_account('72f5d1e3769658b4908c384492eb3a9bd6d6ac4ab1fdf613d7fbe72884114d62728d6fd60a8bf8d0b6698f2f5463a605742658fee1ce3318181105c6acb8120e',
overwrite = True)
qiskit.IBMQ.load_account()
provider = qiskit.IBMQ.get_provider(hub='ibm-q', group='open', project='main')
device = provider.get_backend('ibm_nairobi')
nshots = 2**13
qc = QuantumCircuit(2,2)
qc.h(0); qc.cx(0,1) # prepara |Phi+>
qc.cx(0,1); qc.h(0); qc.measure([0,1],[0,1]) # mede na BB
job = execute(qc, backend=device, shots=nshots)
print(job.job_id())
job = device.retrieve_job('cmjn5w752bbg00825esg')
from qiskit.tools.visualization import plot_histogram; plot_histogram(job.result().get_counts())
qc = QuantumCircuit(2,2)
qc.x(1); qc.h(0); qc.cx(0,1) # prepara |Psi+>
qc.cx(0,1); qc.h(0); qc.measure([0,1],[0,1]) # mede na BB
job = execute(qc, backend=device, shots=nshots); print(job.job_id())
job = device.retrieve_job('cmjn66rffjhg0084we5g')
plot_histogram(job.result().get_counts())
qc = QuantumCircuit(2,2)
qc.x(0); qc.h(0); qc.cx(0,1) # prepara |Phi->
qc.cx(0,1); qc.h(0); qc.measure([0,1],[0,1]) # mede na BB
job = execute(qc, backend=device, shots=nshots); print(job.job_id())
job = device.retrieve_job('cmjn6wk6n5g0008xpgg0')
plot_histogram(job.result().get_counts())
provider = qiskit.IBMQ.get_provider(hub='ibm-q-research-2', group='federal-uni-sant-1', project='main')
device = provider.get_backend('ibm_nairobi')
qc = QuantumCircuit(2,2)
qc.x([0,1]); qc.h(0); qc.cx(0,1) # prepara |Psi->
qc.cx(0,1); qc.h(0); qc.measure([0,1],[0,1]) # mede na BB
job = execute(qc, backend=device, shots=nshots); print(job.job_id())
job = device.retrieve_job('cmjnb9nz44x0008bwa3g'); plot_histogram(job.result().get_counts())
def qc_psi(th,ph,lb): # prepara o estado a ser teletransportado
from qiskit import QuantumCircuit
qc = QuantumCircuit(1, name=r'$|\psi\rangle$'); qc.x(0); qc.u(th,ph,lb, 0)
return qc
qc_psi_ = qc_psi(0.1,0.2,0.3); qc_psi_.draw('mpl')
from qiskit.quantum_info import random_statevector
for j in range(0,6):
psi = random_statevector(2)
print(psi)
def angulos(psi): # psi = [c0,c1]
c0_abs = math.sqrt(psi[0].real**2 + psi[0].imag**2); c1_abs = math.sqrt(psi[1].real**2 + psi[1].imag**2)
ph0 = math.acos(psi[0].real/c0_abs); ph1 = math.acos(psi[1].real/c1_abs)
th = 2*math.acos(c1_abs)
lb = ph0 - math.pi; ph = ph1 - lb
return th, ph, lb # existem erros de sinal!
import math; import numpy as np
for j in range(0,3):
psi = random_statevector(2); print('rand = ',psi); th, ph, lb = angulos(psi)
psin = np.array([(math.cos(math.pi+lb)+1j*math.sin(math.pi+lb))*math.sin(th/2),
(math.cos(ph+lb)+1j*math.sin(ph+lb))*math.cos(th/2)])
print('new = ',psin) # existem erros de sinal!
def acosm(x): # solução do chagpt não funciona
angle = math.acos(x)
if x >= 0:
return angle
else:
return 2*math.pi - angle
import math; import numpy as np
thmax = 2*math.pi; npt = 10; dth = thmax/npt; th = np.arange(0,thmax+dth,dth)
for j in range(0,len(th)):
cs = math.cos(th[j]); acs = math.acos(cs); nacs = acosm(cs)
print('th=',th[j],', acs=',acs,', nacs=',nacs) # não funcionam
for j in range(0,len(th)):
tg = math.tan(th[j]); atg = math.atan(tg); sn = math.sin(th[j]); asn = math.asin(sn)
print('th=', th[j], ', atg=', atg,', asn=', asn) # também não funcionam
# As funções anteriores não funcionam pois o mapa é 2 pra 1
# Essa função retorna o ângulo cert0, fornecidos os valores (seno,cosseno)
def arc_fun(cs, sn):
if sn >= 0:
return math.acos(cs)
if sn < 0:
return 2*math.pi - math.acos(cs)
for j in range(0,len(th)):
cs = math.cos(th[j]); sn = math.sin(th[j])
print('th=', th[j], ', nth=', arc_fun(cs, sn))
def angulosn(psi): # psi = [c0,c1]
c0_abs = math.sqrt(psi[0].real**2 + psi[0].imag**2); c1_abs = math.sqrt(psi[1].real**2 + psi[1].imag**2)
ph0 = arc_fun(psi[0].real/c0_abs, psi[0].imag/c0_abs); ph1 = arc_fun(psi[1].real/c1_abs, psi[1].imag/c1_abs)
th = 2*arc_fun(c1_abs,c0_abs)
lb = ph0 - math.pi; ph = ph1 - lb
return th, ph, lb
import math; import numpy as np
for j in range(0,5):
psi = random_statevector(2); print('rand = ',psi); th, ph, lb = angulosn(psi)
psin = np.array([(math.cos(math.pi+lb)+1j*math.sin(math.pi+lb))*math.sin(th/2),
(math.cos(ph+lb)+1j*math.sin(ph+lb))*math.cos(th/2)])
print('new = ',psin) # Agora está certo ...
from qiskit import *
def qc_teleport(th,ph,lb):
qc = QuantumCircuit(3,2, name='tel')
qc_psi_ = qc_psi(th,ph,lb); qc.append(qc_psi_, [0]); qc.barrier()
qc.h(2); qc.cx(2,1); qc.barrier()
qc.cx(0,1); qc.h(0); qc.measure([0,1],[0,1]); qc.barrier()
qc.x(2).c_if(1, 1); qc.z(2).c_if(0, 1) # oprações condicionadas em info clássica
return qc
qc_teleport_ = qc_teleport(0.1,0.2,0.3); qc_teleport_.draw('mpl')
import qiskit; import math; import numpy as np; from qiskit import Aer, QuantumCircuit, execute
from qiskit.quantum_info import state_fidelity
from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter
simulator = Aer.get_backend('qasm_simulator')
nshots = 2**13; qc = QuantumCircuit(3)
psi = np.array([1/math.sqrt(2),1/math.sqrt(2)]); th,ph,lb=angulosn(psi) # estado a ser teletransportado
qc_teleport_ = qc_teleport(th,ph,lb); qc.append(qc_teleport_, [0,1,2])
qstc = state_tomography_circuits(qc_teleport_, [2])
job = execute(qstc, backend = simulator, shots = nshots)
qstf = StateTomographyFitter(job.result(), qstc)
rho_sim = qstf.fit(method='lstsq')
F = state_fidelity(rho_sim, psi); from sympy import Matrix
rho_teo = Matrix([[1/2,1/2],[1/2,1/2]]); print('rho_teo = ',rho_teo); print('rho_sim =',rho_sim); print('F = ', F)
import qiskit
qiskit.IBMQ.save_account('7ec48a29167ab443c525564bd84b033895cf87b6c6da8d263be59ad00a2d9e70718cf1398362403ace62320d0044793f08dbaa2629bfde7f6ec339f90fe74e7b',
overwrite = True)
qiskit.IBMQ.load_account()
provider = qiskit.IBMQ.get_provider(hub='ibm-q', group='open', project='main')
device = provider.get_backend('ibm_nairobi')
qc = QuantumCircuit(3)
psi = np.array([1/math.sqrt(2),1/math.sqrt(2)])
th,ph,lb=angulosn(psi)
qc_teleport_ = qc_teleport(th,ph,lb)
qc.append(qc_teleport_, [0,1,2])
qstc = state_tomography_circuits(qc_teleport_, [2])
job = execute(qstc, backend = device, shots = nshots)
jobid = job.job_id()
print(jobid)
def qc_teleport_coe(th,ph,lb):
from qiskit import QuantumCircuit
qc = QuantumCircuit(3, name='tel')
qc_psi_ = qc_psi(th,ph,lb); qc.append(qc_psi_, [0]); qc.barrier()
qc.h(2); qc.cx(2,1); qc.barrier(); qc.cx(0,1); qc.h(0); qc.barrier()
qc.cx(1,2); qc.cz(0,2) # oprações quânticas controladas
return qc
qc_teleport_coe_ = qc_teleport_coe(0.1,0.2,0.3); qc_teleport_coe_.draw('mpl')
import qiskit; import math; import numpy as np
from qiskit import Aer, QuantumCircuit, execute
from qiskit.quantum_info import state_fidelity
from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter
simulator = Aer.get_backend('qasm_simulator'); nshots = 2**13; qc = QuantumCircuit(3)
psi = np.array([1/math.sqrt(2),(1/math.sqrt(2))*1j]); th,ph,lb=angulosn(psi)
qc_teleport_coe_ = qc_teleport_coe(th,ph,lb); qc.append(qc_teleport_coe_, [0,1,2])
qstc = state_tomography_circuits(qc_teleport_coe_, [2])
job = qiskit.execute(qstc, backend = simulator, shots = nshots)
qstf = StateTomographyFitter(job.result(), qstc)
rho_sim = qstf.fit(method='lstsq')
F = state_fidelity(rho_sim, psi)
from sympy import Matrix,sqrt; rho = Matrix([[1/2,-1j/2],[1j/2,1/2]]); print('rho_teo =',rho)
print('rho_sim =',rho_sim); print('F = ', F)
import qiskit
qiskit.IBMQ.save_account('585d2242bad08223e0d894363adf8e4f76b1d426a84e85b2fbd51678adcb8e54e39cf0f33ff6c84c41e60a534a61ad4775091a01e338f0f9eff2265aa59a6a19',
overwrite = True); qiskit.IBMQ.load_account()
#provider = qiskit.IBMQ.get_provider(hub='ibm-q', group='open', project='main')
provider = qiskit.IBMQ.get_provider(hub='ibm-q-research-2', group='federal-uni-sant-1', project='main')
device = provider.get_backend('ibm_nairobi')
qc = QuantumCircuit(3)
psi = np.array([1/math.sqrt(2),(1/math.sqrt(2))*1j])
th,ph,lb=angulosn(psi)
qc_teleport_coe_ = qc_teleport_coe(th,ph,lb)
qc.append(qc_teleport_coe_, [0,1,2])
qstc = state_tomography_circuits(qc_teleport_coe_, [2])
job = execute(qstc, backend = device, shots = nshots)
jobid = job.job_id()
print(jobid)
provider = qiskit.IBMQ.get_provider(hub='ibm-q', group='open', project='main')
device = provider.get_backend('ibm_nairobi')
job = device.retrieve_job('cmke9bn8tsq00080987g')
qstf = StateTomographyFitter(job.result(), qstc)
rho_exp = qstf.fit(method='lstsq')
psi = np.array([1/math.sqrt(2),(1/math.sqrt(2))*1j])
from sympy import Matrix, sqrt
rho = Matrix([[0.5,-0.5*1j],[0.5*1j,0.5]])
print('rho_teo =',rho)
F = state_fidelity(psi, rho_exp)
print('rho_exp = ',rho_exp,', F = ', F)
import qiskit; import math; import numpy as np
from qiskit import Aer, QuantumCircuit, execute
from qiskit.quantum_info import state_fidelity
from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter
simulator = Aer.get_backend('qasm_simulator'); nshots = 2**13
for j in range(0,13):
qc = QuantumCircuit(3)
psi = random_statevector(2); th,ph,lb = angulosn(psi)#; print('psi=',psi)
qc_teleport_coe_ = qc_teleport_coe(th,ph,lb); qc.append(qc_teleport_coe_, [0,1,2])
qstc = state_tomography_circuits(qc_teleport_coe_, [2])
job = qiskit.execute(qstc, backend=simulator, shots=nshots)
qstf = StateTomographyFitter(job.result(), qstc); rho_sim = qstf.fit(method='lstsq')
F = state_fidelity(rho_sim, psi); print('F=', F)
|
https://github.com/Z-928/Bugs4Q
|
Z-928
|
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit.wrapper import available_backends, get_backend
from qiskit.wrapper import execute as q_execute
q = QuantumRegister(2, name='q')
c = ClassicalRegister(2, name='c')
qc = QuantumCircuit(q,c)
qc.h(q[0])
qc.h(q[1])
qc.cx(q[0], q[1])
qc.measure(q, c)
z = 0.995004165 + 1j * 0.099833417
z = z / abs(z)
u_error = np.array([[1, 0], [0, z]])
noise_params = {'U':
{'gate_time': 1,
'p_depol': 0.001,
'p_pauli': [0, 0, 0.01],
'U_error': u_error
}
}
config = {"noise_params": noise_params}
ret = q_execute(qc, 'local_qasm_simulator_cpp', shots=1024, config=config)
ret = ret.result()
print(ret.get_counts())
|
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.
"""Test the Check CNOT direction pass"""
import unittest
import ddt
from qiskit import QuantumRegister, QuantumCircuit
from qiskit.circuit.library import CXGate, CZGate, ECRGate
from qiskit.transpiler.passes import CheckGateDirection
from qiskit.transpiler import CouplingMap, Target
from qiskit.converters import circuit_to_dag
from qiskit.test import QiskitTestCase
@ddt.ddt
class TestCheckGateDirection(QiskitTestCase):
"""Tests the CheckGateDirection pass"""
def test_trivial_map(self):
"""Trivial map in a circuit without entanglement
qr0:---[H]---
qr1:---[H]---
qr2:---[H]---
CouplingMap map: None
"""
qr = QuantumRegister(3, "qr")
circuit = QuantumCircuit(qr)
circuit.h(qr)
coupling = CouplingMap()
dag = circuit_to_dag(circuit)
pass_ = CheckGateDirection(coupling)
pass_.run(dag)
self.assertTrue(pass_.property_set["is_direction_mapped"])
def test_true_direction(self):
"""Mapped is easy to check
qr0:---.--[H]--.--
| |
qr1:--(+)------|--
|
qr2:----------(+)-
CouplingMap map: [1]<-[0]->[2]
"""
qr = QuantumRegister(3, "qr")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[1])
circuit.h(qr[0])
circuit.cx(qr[0], qr[2])
coupling = CouplingMap([[0, 1], [0, 2]])
dag = circuit_to_dag(circuit)
pass_ = CheckGateDirection(coupling)
pass_.run(dag)
self.assertTrue(pass_.property_set["is_direction_mapped"])
def test_true_direction_in_same_layer(self):
"""Two CXs distance_qubits 1 to each other, in the same layer
qr0:--(+)--
|
qr1:---.---
qr2:--(+)--
|
qr3:---.---
CouplingMap map: [0]->[1]->[2]->[3]
"""
qr = QuantumRegister(4, "qr")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[1])
circuit.cx(qr[2], qr[3])
coupling = CouplingMap([[0, 1], [1, 2], [2, 3]])
dag = circuit_to_dag(circuit)
pass_ = CheckGateDirection(coupling)
pass_.run(dag)
self.assertTrue(pass_.property_set["is_direction_mapped"])
def test_wrongly_mapped(self):
"""Needs [0]-[1] in a [0]--[2]--[1]
qr0:--(+)--
|
qr1:---.---
CouplingMap map: [0]->[2]->[1]
"""
qr = QuantumRegister(2, "qr")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[1])
coupling = CouplingMap([[0, 2], [2, 1]])
dag = circuit_to_dag(circuit)
pass_ = CheckGateDirection(coupling)
pass_.run(dag)
self.assertFalse(pass_.property_set["is_direction_mapped"])
def test_true_direction_undirected(self):
"""Mapped but with wrong direction
qr0:--(+)-[H]--.--
| |
qr1:---.-------|--
|
qr2:----------(+)-
CouplingMap map: [1]<-[0]->[2]
"""
qr = QuantumRegister(3, "qr")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[1])
circuit.h(qr[0])
circuit.cx(qr[2], qr[0])
coupling = CouplingMap([[0, 1], [0, 2]])
dag = circuit_to_dag(circuit)
pass_ = CheckGateDirection(coupling)
pass_.run(dag)
self.assertFalse(pass_.property_set["is_direction_mapped"])
def test_false_direction_in_same_layer_undirected(self):
"""Two CXs in the same layer, but one is wrongly directed
qr0:--(+)--
|
qr1:---.---
qr2:---.---
|
qr3:--(+)--
CouplingMap map: [0]->[1]->[2]->[3]
"""
qr = QuantumRegister(4, "qr")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[1])
circuit.cx(qr[3], qr[2])
coupling = CouplingMap([[0, 1], [1, 2], [2, 3]])
dag = circuit_to_dag(circuit)
pass_ = CheckGateDirection(coupling)
pass_.run(dag)
self.assertFalse(pass_.property_set["is_direction_mapped"])
def test_2q_barrier(self):
"""A 2q barrier should be ignored
qr0:--|--
|
qr1:--|--
CouplingMap map: None
"""
qr = QuantumRegister(2, "qr")
circuit = QuantumCircuit(qr)
circuit.barrier(qr[0], qr[1])
coupling = CouplingMap()
dag = circuit_to_dag(circuit)
pass_ = CheckGateDirection(coupling)
pass_.run(dag)
self.assertTrue(pass_.property_set["is_direction_mapped"])
def test_ecr_gate(self):
"""A directional ECR gate is detected.
┌──────┐
q_0: ┤1 ├
│ ECR │
q_1: ┤0 ├
└──────┘
CouplingMap map: [0, 1]
"""
qr = QuantumRegister(2, "qr")
circuit = QuantumCircuit(qr)
circuit.ecr(qr[1], qr[0])
coupling = CouplingMap()
dag = circuit_to_dag(circuit)
pass_ = CheckGateDirection(coupling)
pass_.run(dag)
self.assertFalse(pass_.property_set["is_direction_mapped"])
@ddt.data(CXGate(), CZGate(), ECRGate())
def test_target_static(self, gate):
"""Test that static 2q gates are detected correctly both if available and not available."""
circuit = QuantumCircuit(2)
circuit.append(gate, [0, 1], [])
matching = Target(num_qubits=2)
matching.add_instruction(gate, {(0, 1): None})
pass_ = CheckGateDirection(None, target=matching)
pass_(circuit)
self.assertTrue(pass_.property_set["is_direction_mapped"])
swapped = Target(num_qubits=2)
swapped.add_instruction(gate, {(1, 0): None})
pass_ = CheckGateDirection(None, target=swapped)
pass_(circuit)
self.assertFalse(pass_.property_set["is_direction_mapped"])
def test_coupling_map_control_flow(self):
"""Test recursing into control-flow operations with a coupling map."""
matching = CouplingMap.from_line(5, bidirectional=True)
swapped = CouplingMap.from_line(5, bidirectional=False)
circuit = QuantumCircuit(5, 1)
circuit.h(0)
circuit.measure(0, 0)
with circuit.for_loop((2,)):
circuit.cx(1, 0)
pass_ = CheckGateDirection(matching)
pass_(circuit)
self.assertTrue(pass_.property_set["is_direction_mapped"])
pass_ = CheckGateDirection(swapped)
pass_(circuit)
self.assertFalse(pass_.property_set["is_direction_mapped"])
circuit = QuantumCircuit(5, 1)
circuit.h(0)
circuit.measure(0, 0)
with circuit.for_loop((2,)):
with circuit.if_test((circuit.clbits[0], True)) as else_:
circuit.cz(3, 2)
with else_:
with circuit.while_loop((circuit.clbits[0], True)):
circuit.ecr(4, 3)
pass_ = CheckGateDirection(matching)
pass_(circuit)
self.assertTrue(pass_.property_set["is_direction_mapped"])
pass_ = CheckGateDirection(swapped)
pass_(circuit)
self.assertFalse(pass_.property_set["is_direction_mapped"])
def test_target_control_flow(self):
"""Test recursing into control-flow operations with a coupling map."""
swapped = Target(num_qubits=5)
for gate in (CXGate(), CZGate(), ECRGate()):
swapped.add_instruction(gate, {qargs: None for qargs in zip(range(4), range(1, 5))})
matching = Target(num_qubits=5)
for gate in (CXGate(), CZGate(), ECRGate()):
matching.add_instruction(gate, {None: None})
circuit = QuantumCircuit(5, 1)
circuit.h(0)
circuit.measure(0, 0)
with circuit.for_loop((2,)):
circuit.cx(1, 0)
pass_ = CheckGateDirection(None, target=matching)
pass_(circuit)
self.assertTrue(pass_.property_set["is_direction_mapped"])
pass_ = CheckGateDirection(None, target=swapped)
pass_(circuit)
self.assertFalse(pass_.property_set["is_direction_mapped"])
circuit = QuantumCircuit(5, 1)
circuit.h(0)
circuit.measure(0, 0)
with circuit.for_loop((2,)):
with circuit.if_test((circuit.clbits[0], True)) as else_:
circuit.cz(3, 2)
with else_:
with circuit.while_loop((circuit.clbits[0], True)):
circuit.ecr(4, 3)
pass_ = CheckGateDirection(None, target=matching)
pass_(circuit)
self.assertTrue(pass_.property_set["is_direction_mapped"])
pass_ = CheckGateDirection(None, target=swapped)
pass_(circuit)
self.assertFalse(pass_.property_set["is_direction_mapped"])
if __name__ == "__main__":
unittest.main()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, transpile, schedule
from qiskit.visualization.timeline import draw, IQXDebugging
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=IQXDebugging())
|
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
|
import numpy as np
import copy
# Problem modelling imports
from docplex.mp.model import Model
# Qiskit imports
from qiskit.algorithms.minimum_eigensolvers import QAOA, NumPyMinimumEigensolver
from qiskit.algorithms.optimizers import COBYLA
from qiskit.primitives import Sampler
from qiskit.utils.algorithm_globals import algorithm_globals
from qiskit_optimization.algorithms import MinimumEigenOptimizer, CplexOptimizer
from qiskit_optimization import QuadraticProgram
from qiskit_optimization.problems.variable import VarType
from qiskit_optimization.converters.quadratic_program_to_qubo import QuadraticProgramToQubo
from qiskit_optimization.translators import from_docplex_mp
def create_problem(mu: np.array, sigma: np.array, total: int = 3) -> QuadraticProgram:
"""Solve the quadratic program using docplex."""
mdl = Model()
x = [mdl.binary_var("x%s" % i) for i in range(len(sigma))]
objective = mdl.sum([mu[i] * x[i] for i in range(len(mu))])
objective -= 2 * mdl.sum(
[sigma[i, j] * x[i] * x[j] for i in range(len(mu)) for j in range(len(mu))]
)
mdl.maximize(objective)
cost = mdl.sum(x)
mdl.add_constraint(cost == total)
qp = from_docplex_mp(mdl)
return qp
def relax_problem(problem) -> QuadraticProgram:
"""Change all variables to continuous."""
relaxed_problem = copy.deepcopy(problem)
for variable in relaxed_problem.variables:
variable.vartype = VarType.CONTINUOUS
return relaxed_problem
mu = np.array([3.418, 2.0913, 6.2415, 4.4436, 10.892, 3.4051])
sigma = np.array(
[
[1.07978412, 0.00768914, 0.11227606, -0.06842969, -0.01016793, -0.00839765],
[0.00768914, 0.10922887, -0.03043424, -0.0020045, 0.00670929, 0.0147937],
[0.11227606, -0.03043424, 0.985353, 0.02307313, -0.05249785, 0.00904119],
[-0.06842969, -0.0020045, 0.02307313, 0.6043817, 0.03740115, -0.00945322],
[-0.01016793, 0.00670929, -0.05249785, 0.03740115, 0.79839634, 0.07616951],
[-0.00839765, 0.0147937, 0.00904119, -0.00945322, 0.07616951, 1.08464544],
]
)
qubo = create_problem(mu, sigma)
print(qubo.prettyprint())
result = CplexOptimizer().solve(qubo)
print(result.prettyprint())
qp = relax_problem(QuadraticProgramToQubo().convert(qubo))
print(qp.prettyprint())
sol = CplexOptimizer().solve(qp)
print(sol.prettyprint())
c_stars = sol.samples[0].x
print(c_stars)
algorithm_globals.random_seed = 12345
qaoa_mes = QAOA(sampler=Sampler(), optimizer=COBYLA(), initial_point=[0.0, 1.0])
exact_mes = NumPyMinimumEigensolver()
qaoa = MinimumEigenOptimizer(qaoa_mes)
qaoa_result = qaoa.solve(qubo)
print(qaoa_result.prettyprint())
from qiskit import QuantumCircuit
thetas = [2 * np.arcsin(np.sqrt(c_star)) for c_star in c_stars]
init_qc = QuantumCircuit(len(sigma))
for idx, theta in enumerate(thetas):
init_qc.ry(theta, idx)
init_qc.draw(output="mpl")
from qiskit.circuit import Parameter
beta = Parameter("β")
ws_mixer = QuantumCircuit(len(sigma))
for idx, theta in enumerate(thetas):
ws_mixer.ry(-theta, idx)
ws_mixer.rz(-2 * beta, idx)
ws_mixer.ry(theta, idx)
ws_mixer.draw(output="mpl")
ws_qaoa_mes = QAOA(
sampler=Sampler(),
optimizer=COBYLA(),
initial_state=init_qc,
mixer=ws_mixer,
initial_point=[0.0, 1.0],
)
ws_qaoa = MinimumEigenOptimizer(ws_qaoa_mes)
ws_qaoa_result = ws_qaoa.solve(qubo)
print(ws_qaoa_result.prettyprint())
def format_qaoa_samples(samples, max_len: int = 10):
qaoa_res = []
for s in samples:
if sum(s.x) == 3:
qaoa_res.append(("".join([str(int(_)) for _ in s.x]), s.fval, s.probability))
res = sorted(qaoa_res, key=lambda x: -x[1])[0:max_len]
return [(_[0] + f": value: {_[1]:.3f}, probability: {1e2*_[2]:.1f}%") for _ in res]
format_qaoa_samples(qaoa_result.samples)
format_qaoa_samples(ws_qaoa_result.samples)
from qiskit_optimization.algorithms import WarmStartQAOAOptimizer
qaoa_mes = QAOA(sampler=Sampler(), optimizer=COBYLA(), initial_point=[0.0, 1.0])
ws_qaoa = WarmStartQAOAOptimizer(
pre_solver=CplexOptimizer(), relax_for_pre_solver=True, qaoa=qaoa_mes, epsilon=0.0
)
ws_result = ws_qaoa.solve(qubo)
print(ws_result.prettyprint())
format_qaoa_samples(ws_result.samples)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/Harcipan/QAI_GroverSim
|
Harcipan
|
# Importing standard Qiskit libraries
from qiskit import QuantumCircuit, transpile
from qiskit_ibm_provider import IBMProvider
import qiskit_ibm_provider.jupyter
#provider = IBMProvider('ibm-q')
#backend = provider.get_backend('ibmq_vigo')
from qiskit.visualization import *
from ibm_quantum_widgets import *
# qiskit-ibmq-provider has been deprecated.
# Please see the Migration Guides in https://ibm.biz/provider_migration_guide for more detail.
from qiskit_ibm_runtime import QiskitRuntimeService, Sampler, Estimator, Session, Options
# Loading your IBM Quantum account(s)
service = QiskitRuntimeService(channel="ibm_quantum")
# Invoke a primitive. For more details see https://qiskit.org/documentation/partners/qiskit_ibm_runtime/tutorials.html
# result = Sampler("ibmq_qasm_simulator").run(circuits).result()
# Built-in modules
import math
# Imports from Qiskit
from qiskit import QuantumCircuit
from qiskit.circuit.library import GroverOperator, MCMT, ZGate
from qiskit.visualization import plot_distribution
# Imports from Qiskit Runtime
from qiskit_ibm_runtime import QiskitRuntimeService, Sampler, Session
from qiskit.circuit import QuantumCircuit, Gate, Instruction
from qiskit.circuit.library.standard_gates import ZGate
def MCMT(gate, num_controls, num_targets):
"""Construct a multi-controlled multi-target gate.
Args:
gate (Gate): The gate to apply to the target qubits.
num_controls (int): The number of control qubits.
num_targets (int): The number of target qubits.
Returns:
Instruction: The multi-controlled multi-target gate as a Qiskit Instruction.
"""
mcmt_gate = QuantumCircuit(num_controls + num_targets)
mcmt_gate.append(gate.control(num_controls), list(range(num_controls + num_targets)))
return mcmt_gate.to_instruction()
def grover_oracle(marked_states):
"""Build a Grover oracle for multiple marked states
Here we assume all input marked states have the same number of bits
Parameters:
marked_states (str or list): Marked states of oracle
Returns:
QuantumCircuit: Quantum circuit representing Grover oracle
"""
if not isinstance(marked_states, list):
marked_states = [marked_states]
# Compute the number of qubits in circuit
num_qubits = len(marked_states[0])
qc = QuantumCircuit(num_qubits)
# Mark each target state in the input list
for target in marked_states:
# Flip target bit-string to match Qiskit bit-ordering
rev_target = target[::-1]
# Find the indices of all the '0' elements in bit-string
zero_inds = [ind for ind in range(num_qubits) if rev_target.startswith("0", ind)]
# Add a multi-controlled Z-gate with pre- and post-applied X-gates (open-controls)
# where the target bit-string has a '0' entry
qc.x(zero_inds)
#qc.ry(0.1,zero_inds)
qc.compose(MCMT(ZGate(), num_qubits - 1, 1), inplace=True)
qc.x(zero_inds)
return qc
marked_states = ["011", "100"]
oracle = grover_oracle(marked_states)
oracle.draw("mpl")
grover_op = GroverOperator(oracle)
grover_op.decompose().draw("mpl")
optimal_num_iterations = math.floor(
math.pi / 4 * math.sqrt(2**grover_op.num_qubits / len(marked_states))
)
qc = QuantumCircuit(grover_op.num_qubits)
# Create even superposition of all basis states
qc.h(range(grover_op.num_qubits))
# Apply Grover operator the optimal number of times
qc.compose(grover_op.power(optimal_num_iterations), inplace=True)
# Measure all qubits
qc.measure_all()
qc.draw("mpl")
from qiskit import QuantumCircuit
from qiskit.providers.basic_provider import BasicProvider
from qiskit.visualization import plot_histogram
from qiskit import transpile
from qiskit.providers.fake_provider import GenericBackendV2
#from qiskit.visualization import plot_histogram
# Generate a 5-qubit simulated backend
backend = GenericBackendV2(num_qubits=5)
"""
# Alternative
from qiskit_ibm_runtime.fake_provider import FakeProvider
backend1 = FakeProvider().get_backend("fake_ourense")
from qiskit_ibm_runtime.fake_provider import FakeSherbrooke
backend2 = FakeSherbrooke()"""
# Transpile the ideal circuit to a circuit that can be directly executed by the backend
transpiled_circuit = transpile(qc, backend)#transpiled_circuit = transpile(qc, backend=backend_simulator)
transpiled_circuit.draw('mpl')
# Run the transpiled circuit using the simulated backend
job = backend.run(transpiled_circuit)
counts = job.result().get_counts()
print(counts)
plot_histogram(counts)
from qiskit import QuantumCircuit
from qiskit.providers.basic_provider import BasicProvider
from qiskit.visualization import plot_histogram
from qiskit import transpile
from qiskit.providers.fake_provider import GenericBackendV2
#from qiskit.visualization import plot_histogram
# Generate a 5-qubit simulated backend
backend = GenericBackendV2(num_qubits=5)
"""
# Alternative
from qiskit_ibm_runtime.fake_provider import FakeProvider
backend1 = FakeProvider().get_backend("fake_ourense")
from qiskit_ibm_runtime.fake_provider import FakeSherbrooke
backend2 = FakeSherbrooke()"""
# Transpile the ideal circuit to a circuit that can be directly executed by the backend
transpiled_circuit = transpile(qc, backend)#transpiled_circuit = transpile(qc, backend=backend_simulator)
transpiled_circuit.draw('mpl')
# Run the transpiled circuit using the simulated backend
job = backend.run(transpiled_circuit)
counts = job.result().get_counts()
print(counts)
plot_histogram(counts)
from qiskit import QuantumCircuit
from qiskit.providers.basic_provider import BasicProvider
from qiskit.visualization import plot_histogram
#qc.measure_all()
from qiskit.providers.basic_provider import BasicProvider
backend = BasicProvider().get_backend("basic_simulator")
result = backend.run(qc).result()
"""
# Get the BasicSimulator backend from the BasicProvider
backend = BasicProvider().get_backend("basic_simulator")
# Simulate the quantum circuit
result = backend.run(qc).result()"""
# Alternative
from qiskit_ibm_runtime.fake_provider import FakeProvider
backend1 = FakeProvider().get_backend("fake_ourense")
from qiskit_ibm_runtime.fake_provider import FakeSherbrooke
backend2 = FakeSherbrooke()
# Get counts from the result
counts = result.get_counts()
# Plot the histogram
plot_histogram(counts)
backend_simulator = service.least_busy(operational=True, simulator=False)
backend_simulator.name
# Initialize your session
sim_session = Session(backend=backend_simulator)
sim_sampler = Sampler(session=sim_session)
from qiskit import transpile
from qiskit.visualization import plot_histogram
# Assuming qc is your quantum circuit
# Transpile the circuit to match the target backend
transpiled_circuit = transpile(qc, backend=backend_simulator)
from qiskit.providers.basic_provider import BasicProvider
backend = BasicProvider().get_backend("ibmq_qasm_simulator")
job = backend.run(transpiled_circuit)
job = execute(qc, simulator, shots=1024)
# Wait for the job to finish
job_result = job.result()
# Get counts from the result
counts = job_result.get_counts()
# Plot the histogram
plot_histogram(counts)
from qiskit import transpile
from qiskit.visualization import plot_histogram
# Assuming qc is your quantum circuit
# Transpile the circuit to match the target backend
transpiled_circuit = transpile(qc, backend=backend_simulator)
# Run the transpiled circuit on the backend
job = backend_simulator.run(transpiled_circuit)
# Wait for the job to finish
job_result = job.result()
# Get counts from the result
counts = job_result.get_counts()
# Plot the histogram
plot_histogram(counts)
sim_dist = sim_sampler.run(qc, shots=int(1e4)).result().quasi_dists[0]
plot_distribution(sim_dist.binary_probabilities())
sim_session.close()
# Select the backend with the fewest number of jobs in the queue
backend = service.least_busy(simulator=False, operational=True)
backend.name
# Initialize your session
session = Session(backend=backend)
real_sampler = Sampler(session=session)
real_dist = real_sampler.run(qc, shots=int(1e4)).result().quasi_dists[0]
plot_distribution(real_dist.binary_probabilities())
# Close session
session.close()
|
https://github.com/nahumsa/volta
|
nahumsa
|
# 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 typing import Union
import qiskit
import numpy as np
from qiskit.utils.backend_utils import is_aer_provider
from qiskit.opflow import (
CircuitSampler,
ExpectationFactory,
CircuitStateFn,
StateFn,
)
def sample_hamiltonian(
hamiltonian: qiskit.opflow.OperatorBase,
backend: Union[qiskit.providers.BaseBackend, qiskit.utils.QuantumInstance],
ansatz: qiskit.QuantumCircuit,
) -> float:
"""Samples a hamiltonian given an ansatz, which is a Quantum circuit
and outputs the expected value given the hamiltonian.
Args:
hamiltonian (qiskit.opflow.OperatorBase): Hamiltonian that you want to get the
expected value.
backend (Union[qiskit.providers.BaseBackend, qiskit.utils.QuantumInstance]): Backend
that you want to run.
ansatz (qiskit.QuantumCircuit): Quantum circuit that you want to get the expectation
value.
Returns:
float: Expected value
"""
if qiskit.utils.quantum_instance.QuantumInstance == type(backend):
sampler = CircuitSampler(backend, param_qobj=is_aer_provider(backend.backend))
else:
sampler = CircuitSampler(backend)
expectation = ExpectationFactory.build(operator=hamiltonian, backend=backend)
observable_meas = expectation.convert(StateFn(hamiltonian, is_measurement=True))
ansatz_circuit_op = CircuitStateFn(ansatz)
expect_op = observable_meas.compose(ansatz_circuit_op).reduce()
sampled_expect_op = sampler.convert(expect_op)
return np.real(sampled_expect_op.eval())
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit_nature.drivers.second_quantization import GaussianForcesDriver
from qiskit_nature.problems.second_quantization import VibrationalStructureProblem
from qiskit_nature.settings import settings
settings.dict_aux_operators = True
driver = GaussianForcesDriver(logfile="aux_files/CO2_freq_B3LYP_631g.log")
problem = VibrationalStructureProblem(driver, num_modals=[2, 2, 3, 4], truncation_order=2)
# Note: at this point, `driver.run()` has NOT been called yet. We can trigger this indirectly like so:
second_q_ops = problem.second_q_ops()
hamiltonian = second_q_ops["VibrationalEnergy"]
print("\n".join(str(hamiltonian).splitlines()[:10] + ["..."]))
from qiskit_nature.second_q.drivers import GaussianForcesDriver
from qiskit_nature.second_q.problems import HarmonicBasis
driver = GaussianForcesDriver(logfile="aux_files/CO2_freq_B3LYP_631g.log")
basis = HarmonicBasis(num_modals=[2, 2, 3, 4])
# this is now done explicitly and already requires the basis
problem = driver.run(basis=basis)
problem.hamiltonian.truncation_order = 2
hamiltonian = problem.hamiltonian.second_q_op()
print("\n".join(str(hamiltonian).splitlines()[:10] + ["..."]))
from qiskit_nature.drivers.second_quantization import GaussianLogResult
from qiskit_nature.properties.second_quantization.vibrational.bases import HarmonicBasis
from qiskit_nature.settings import settings
settings.dict_aux_operators = True
log_result = GaussianLogResult("aux_files/CO2_freq_B3LYP_631g.log")
hamiltonian = log_result.get_vibrational_energy()
print(hamiltonian)
hamiltonian.basis = HarmonicBasis([2, 2, 3, 4])
op = hamiltonian.second_q_ops()["VibrationalEnergy"]
print("\n".join(str(op).splitlines()[:10] + ["..."]))
from qiskit_nature.second_q.drivers import GaussianLogResult
from qiskit_nature.second_q.formats import watson_to_problem
from qiskit_nature.second_q.problems import HarmonicBasis
log_result = GaussianLogResult("aux_files/CO2_freq_B3LYP_631g.log")
watson = log_result.get_watson_hamiltonian()
print(watson)
basis = HarmonicBasis(num_modals=[2, 2, 3, 4])
problem = watson_to_problem(watson, basis)
hamiltonian = problem.hamiltonian.second_q_op()
print("\n".join(str(hamiltonian).splitlines()[:10] + ["..."]))
from qiskit_nature.drivers.second_quantization import GaussianForcesDriver
from qiskit_nature.problems.second_quantization import VibrationalStructureProblem
driver = GaussianForcesDriver(logfile="aux_files/CO2_freq_B3LYP_631g.log")
problem = VibrationalStructureProblem(driver, num_modals=[2, 2, 3, 4], truncation_order=2)
# we trigger driver.run() implicitly like so:
second_q_ops = problem.second_q_ops()
hamiltonian_op = second_q_ops.pop("VibrationalEnergy")
aux_ops = second_q_ops
from qiskit_nature.second_q.drivers import GaussianForcesDriver
from qiskit_nature.second_q.problems import HarmonicBasis
driver = GaussianForcesDriver(logfile="aux_files/CO2_freq_B3LYP_631g.log")
basis = HarmonicBasis(num_modals=[2, 2, 3, 4])
problem = driver.run(basis=basis)
problem.hamiltonian.truncation_order = 2
hamiltonian_op, aux_ops = problem.second_q_ops()
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.