repo
stringclasses 885
values | file
stringclasses 741
values | content
stringlengths 4
215k
|
|---|---|---|
https://github.com/AbeerVaishnav13/Quantum-Programs
|
AbeerVaishnav13
|
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import style
%matplotlib inline
style.use('bmh')
style.use('dark_background')
a = 13; N = 15; num_iter = 15
# Finding the period
values = []
for x in range(num_iter):
values.append((a**x) % N)
print(values)
plt.plot(values)
start = values[0]
period = 0
for i in range(1, len(values)):
if values[i] == start:
period = i
break
print('Period:', period)
a = 18; N = 77; num_iter = 80
# Finding the period
values = []
for x in range(num_iter):
values.append((a**x) % N)
print(values)
plt.plot(values)
start = values[0]
period = 0
for i in range(1, len(values)):
if values[i] == start:
period = i
break
print('Period:', period)
|
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/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Tests for pass manager visualization tool."""
import unittest
import os
from qiskit.transpiler import CouplingMap, Layout
from qiskit.transpiler.passmanager import PassManager
from qiskit import QuantumRegister
from qiskit.transpiler.passes import GateDirection, Unroller
from qiskit.transpiler.passes import CheckMap
from qiskit.transpiler.passes import SetLayout
from qiskit.transpiler.passes import TrivialLayout
from qiskit.transpiler.passes import BarrierBeforeFinalMeasurements
from qiskit.transpiler.passes import FullAncillaAllocation
from qiskit.transpiler.passes import EnlargeWithAncilla
from qiskit.transpiler.passes import RemoveResetInZeroState
from qiskit.utils import optionals
from .visualization import QiskitVisualizationTestCase, path_to_diagram_reference
@unittest.skipUnless(optionals.HAS_GRAPHVIZ, "Graphviz not installed.")
@unittest.skipUnless(optionals.HAS_PYDOT, "pydot not installed")
@unittest.skipUnless(optionals.HAS_PIL, "Pillow not installed")
class TestPassManagerDrawer(QiskitVisualizationTestCase):
"""Qiskit pass manager drawer tests."""
def setUp(self):
super().setUp()
coupling = [[0, 1], [1, 2], [2, 3], [3, 4], [4, 5], [5, 6]]
coupling_map = CouplingMap(couplinglist=coupling)
basis_gates = ["u1", "u3", "u2", "cx"]
qr = QuantumRegister(7, "q")
layout = Layout({qr[i]: i for i in range(coupling_map.size())})
# Create a pass manager with a variety of passes and flow control structures
self.pass_manager = PassManager()
self.pass_manager.append(SetLayout(layout))
self.pass_manager.append(TrivialLayout(coupling_map), condition=lambda x: True)
self.pass_manager.append(FullAncillaAllocation(coupling_map))
self.pass_manager.append(EnlargeWithAncilla())
self.pass_manager.append(Unroller(basis_gates))
self.pass_manager.append(CheckMap(coupling_map))
self.pass_manager.append(BarrierBeforeFinalMeasurements(), do_while=lambda x: False)
self.pass_manager.append(GateDirection(coupling_map))
self.pass_manager.append(RemoveResetInZeroState())
def test_pass_manager_drawer_basic(self):
"""Test to see if the drawer draws a normal pass manager correctly"""
filename = "current_standard.dot"
self.pass_manager.draw(filename=filename, raw=True)
try:
self.assertFilesAreEqual(
filename, path_to_diagram_reference("pass_manager_standard.dot")
)
finally:
os.remove(filename)
def test_pass_manager_drawer_style(self):
"""Test to see if the colours are updated when provided by the user"""
# set colours for some passes, but leave others to take the default values
style = {
SetLayout: "cyan",
CheckMap: "green",
EnlargeWithAncilla: "pink",
RemoveResetInZeroState: "grey",
}
filename = "current_style.dot"
self.pass_manager.draw(filename=filename, style=style, raw=True)
try:
self.assertFilesAreEqual(filename, path_to_diagram_reference("pass_manager_style.dot"))
finally:
os.remove(filename)
if __name__ == "__main__":
unittest.main(verbosity=2)
|
https://github.com/lockwo/Paper-Review
|
lockwo
|
import numpy as np
from scipy.linalg import sqrtm
from qiskit import Aer
from qiskit.utils import QuantumInstance
from qiskit.quantum_info import state_fidelity, DensityMatrix
from qiskit.circuit import QuantumCircuit, ParameterVector
from qiskit.opflow import StateFn, I, X, Y, Z, CircuitSampler, Gradient, PauliExpectation
from qiskit.algorithms.optimizers import GradientDescent, ADAM, L_BFGS_B
from qiskit.providers.aer import AerSimulator, extensions, QasmSimulator
from qiskit.providers.aer.noise import depolarizing_error, amplitude_damping_error, phase_damping_error, NoiseModel
import matplotlib.pyplot as plt
def get_fidelity(s1, s2):
return state_fidelity(s1, s2)
pauli_y = np.array([[0, -1j], [1j, 0]])
krons = np.kron(pauli_y, pauli_y)
def get_concurrance(p):
p = np.array(p)
p_hat = np.matmul(np.matmul(krons, p.conj().T), krons)
try:
mat = sqrtm(np.matmul(np.matmul(sqrtm(p), p_hat), sqrtm(p)))
except:
return 0
eigs = np.linalg.eigvals(mat)
sorted_eigs = sorted(eigs, reverse=True)
return max(0, sorted_eigs[0] - sorted_eigs[1] - sorted_eigs[2] - sorted_eigs[3])
def get_density_matrix(circuit, params, noise_model=NoiseModel()):
c = circuit.bind_parameters(params)
c.save_density_matrix()
sim_noise = AerSimulator(noise_model=noise_model)
result = sim_noise.run(c).result()
density_matrix = result.data()['density_matrix']
return density_matrix
def make_circuit(version):
circuit = QuantumCircuit(2)
params = ParameterVector("theta", length=4 if version == 2 else 3)
circuit.ry(params[0], 0)
circuit.ry(params[1], 1)
circuit.cx(0, 1)
if version == 0:
circuit.ry(params[2], 0)
elif version == 1:
circuit.ry(params[2], 1)
elif version == 2:
circuit.ry(params[2], 0)
circuit.ry(params[3], 1)
return circuit
hamiltonian = (Z ^ Z) + (X ^ I) + (I ^ X)
print(hamiltonian)
noises = [phase_damping_error, amplitude_damping_error, depolarizing_error]
gammas = np.linspace(0, 1, 100)
backend = Aer.get_backend('qasm_simulator')
fig, axs = plt.subplots(3, 3, figsize=(16, 10))
for count, noise_type in enumerate(noises):
for ver in range(3):
print(count, ver)
energies = []
fidelities = []
concurrances = []
noiseless_solution = None
for g in gammas:
initial_point = np.random.uniform(0, 2 * np.pi, 4)
def evaluate_expectation(x):
value_dict = dict(zip(cir.parameters, x))
result = sampler.convert(op, params=value_dict).eval()
return np.real(result)
def evaluate_gradient(x):
value_dict = dict(zip(cir.parameters, x))
result = sampler.convert(gradient, params=value_dict).eval()
return np.real(result)
#print(noise_type, ver, g)
params = 4 if ver == 2 else 3
cir = make_circuit(ver)
noise_model = NoiseModel()
if g != 0:
if count == 2:
noise = noise_type(g, 2)
else:
noise = noise_type(g)
noise = noise.tensor(noise)
noise_model.add_all_qubit_quantum_error(noise, ['cx'])
q_instance = QuantumInstance(backend, noise_model=noise_model)
sampler = CircuitSampler(q_instance)
expectation = StateFn(hamiltonian, is_measurement=True) @ StateFn(cir)
op = PauliExpectation().convert(expectation)
gradient = Gradient(grad_method='param_shift').convert(op)
#gd = GradientDescent(maxiter=100, learning_rate=0.05, tol=1e-4)
#gd = ADAM(maxiter=80, lr=0.05)
gd = L_BFGS_B()
point, value, nfev = gd.optimize(params, evaluate_expectation, gradient_function=evaluate_gradient, initial_point=initial_point[:params])
energies.append(value)
if g == 0 and noiseless_solution is None:
noiseless_solution = get_density_matrix(cir, point)
current_density_matrix = get_density_matrix(cir, point, noise_model)
fidelity = get_fidelity(noiseless_solution, current_density_matrix)
fidelities.append(fidelity)
concurrance = get_concurrance(current_density_matrix)
concurrances.append(concurrance)
axs[0, count].scatter(gammas, energies, label=str(ver))
axs[1, count].scatter(gammas, fidelities)
axs[2, count].scatter(gammas, concurrances)
axs[2, 0].set_xlabel("$\gamma$")
axs[2, 1].set_xlabel("$\gamma$")
axs[2, 2].set_xlabel("$\gamma$")
axs[0, 0].set_title('Phase damping')
axs[0, 1].set_title('Amplitude damping')
axs[0, 2].set_title('Depolarizing')
axs[0, 0].set_ylim(-2.3, -1.5)
axs[0, 1].set_ylim(-2.3, -1.5)
axs[0, 2].set_ylim(-2.2, 0)
axs[1, 0].set_ylim(0.5, 1)
axs[1, 1].set_ylim(0.5, 1)
axs[1, 2].set_ylim(0.2, 1)
axs[2, 0].set_ylim(0, 0.5)
axs[2, 1].set_ylim(0, 0.5)
axs[2, 2].set_ylim(0, 0.5)
axs[0, 0].legend()
axs[0, 0].set_ylabel("Energy")
axs[1, 0].set_ylabel("Fidelity")
axs[2, 0].set_ylabel("Concurrance")
plt.show()
def make_circuit_four():
circuit = QuantumCircuit(4)
params = ParameterVector("theta", length=8)
for i in range(4):
circuit.ry(params[i], i)
circuit.cx(0, 1)
circuit.cx(1, 2)
circuit.cx(2, 3)
for i in range(4):
circuit.ry(params[i + 4], i)
return circuit
hamiltonian = (I ^ Z ^ I ^ Z) + 1/2 * ((I ^ I ^ X ^ X) + (I ^ I ^ Y ^ Y) + (X ^ X ^ I ^ I) + (Y ^ Y ^ I ^ I))
print(hamiltonian)
noises = [phase_damping_error, amplitude_damping_error, depolarizing_error]
noise_names = ["Phase Damping", "Amplitude Damping", "Depolarizing"]
gammas = np.linspace(0, 1, 50)
backend = Aer.get_backend('qasm_simulator')
fig, axs = plt.subplots(2, 1, figsize=(10, 10))
for count, noise_type in enumerate(noises):
energies = []
fidelities = []
noiseless_solution = None
for g in gammas:
initial_point = np.random.uniform(0, 2 * np.pi, 8)
def evaluate_expectation(x):
value_dict = dict(zip(cir.parameters, x))
result = sampler.convert(op, params=value_dict).eval()
return np.real(result)
def evaluate_gradient(x):
value_dict = dict(zip(cir.parameters, x))
result = sampler.convert(gradient, params=value_dict).eval()
return np.real(result)
#print(noise_type, g)
cir = make_circuit_four()
noise_model = NoiseModel()
if g != 0:
if count == 2:
noise = noise_type(g, 2)
else:
noise = noise_type(g)
noise = noise.tensor(noise)
noise_model.add_all_qubit_quantum_error(noise, ['cx'])
q_instance = QuantumInstance(backend, noise_model=noise_model)
sampler = CircuitSampler(q_instance)
expectation = StateFn(hamiltonian, is_measurement=True) @ StateFn(cir)
op = PauliExpectation().convert(expectation)
gradient = Gradient(grad_method='param_shift').convert(op)
#gd = GradientDescent(maxiter=100, learning_rate=0.05, tol=1e-4)
#gd = ADAM(maxiter=80, lr=0.05)
gd = L_BFGS_B()
point, value, nfev = gd.optimize(8, evaluate_expectation, gradient_function=evaluate_gradient, initial_point=initial_point)
energies.append(value)
if g == 0 and noiseless_solution is None:
noiseless_solution = get_density_matrix(cir, point)
current_density_matrix = get_density_matrix(cir, point, noise_model)
fidelity = get_fidelity(noiseless_solution, current_density_matrix)
fidelities.append(fidelity)
axs[0].scatter(gammas, energies, label=noise_names[count])
axs[1].scatter(gammas, fidelities)
axs[1].set_xlabel("$\gamma$")
axs[0].set_ylim(-2.5, 0)
axs[1].set_ylim(0, 1)
axs[0].legend()
axs[0].set_ylabel("Energy")
axs[1].set_ylabel("Fidelity")
plt.show()
def make_circuit_one():
circuit = QuantumCircuit(1)
params = ParameterVector("theta", length=2)
circuit.ry(params[0], 0, label='first')
circuit.ry(params[1], 0)
return circuit
hamiltonian = Z
gamma = 0.4
backend = Aer.get_backend('qasm_simulator')
def evaluate_expectation(x):
value_dict = dict(zip(cir.parameters, x))
result = sampler.convert(op, params=value_dict).eval()
return np.real(result)
cir = make_circuit_one()
noise_model = NoiseModel()
#noise = depolarizing_error(gamma, 1)
noise = phase_damping_error(gamma)
noise_model.add_all_qubit_quantum_error(noise, ['first'])
q_instance = QuantumInstance(backend, noise_model=noise_model)
sampler = CircuitSampler(q_instance)
expectation = StateFn(hamiltonian, is_measurement=True) @ StateFn(cir)
op = PauliExpectation().convert(expectation)
N = 30
xs = np.linspace(-np.pi, np.pi, N)
ys = np.linspace(-np.pi, np.pi, N)
zs = np.zeros(shape=(N, N))
for i in range(len(xs)):
#print(i)
for j in range(len(ys)):
zs[i][j] = evaluate_expectation([xs[i], ys[j]])
cir = make_circuit_one()
q_instance = QuantumInstance(backend)
sampler = CircuitSampler(q_instance)
expectation = StateFn(hamiltonian, is_measurement=True) @ StateFn(cir)
op = PauliExpectation().convert(expectation)
xs = np.linspace(-np.pi, np.pi, N)
ys = np.linspace(-np.pi, np.pi, N)
zs1 = np.zeros(shape=(N, N))
for i in range(len(xs)):
#print(i)
for j in range(len(ys)):
zs1[i][j] = evaluate_expectation([xs[i], ys[j]])
# Label axes
fig, axs = plt.subplots(1, 2, figsize=(20, 10))
axs[1].contourf(xs, ys, zs, 10, cmap='YlGnBu')
#axs[1].contour(xs, ys, zs, 30, cmap='cool')
axs[1].set_title("Noisy")
axs[0].contourf(xs, ys, zs1, 10, cmap='YlGnBu')
#axs[0].contour(xs, ys, zs1, 30, cmap='cool')
axs[0].set_title("Noiseless")
plt.show()
def make_circuit_layers(l):
circuit = QuantumCircuit(4)
params = ParameterVector("theta", length=4 * l)
counter = 0
for i in range(l):
for j in range(4):
circuit.ry(params[counter], j)
counter += 1
circuit.cx(0, 1, label='first')
circuit.cx(2, 3)
circuit.cx(1, 2, label='second')
return circuit
noises = [phase_damping_error, amplitude_damping_error, depolarizing_error]
gammas = [0, 1e-3, 1e-2, 5 * 1e-2, 1e-1]
layers = [i for i in range(1, 7)]
backend = Aer.get_backend('qasm_simulator')
fig, axs = plt.subplots(2, 3, figsize=(10, 10))
target_state = np.random.uniform(0, 1, (1, 2**4)) + np.random.uniform(0, 1, (1, 2**4)) * 1j
target_state = target_state / np.linalg.norm(target_state)
target_dm = np.matmul(target_state.conj().T, target_state)
for count, noise_type in enumerate(noises):
for g in gammas:
reopts = []
non_reopts = []
for lay in layers:
initial_point = np.random.uniform(0, 2 * np.pi, lay * 4)
def evaluate_expectation_noiseless(x):
fid = get_fidelity(target_dm, get_density_matrix(cir, x))
return 1 - fid
def evaluate_expectation_noisy(x):
fid = get_fidelity(target_dm, get_density_matrix(cir, x, noise_model))
return 1 - fid
cir = make_circuit_layers(lay)
noise_model = NoiseModel()
no_noise = NoiseModel()
if g != 0:
if count == 2:
noise = noise_type(g, 2)
else:
noise = noise_type(g)
noise = noise.tensor(noise)
noise_model.add_all_qubit_quantum_error(noise, ['first', 'second'])
gd = L_BFGS_B()
point, value, nfev = gd.optimize(initial_point.size, evaluate_expectation_noiseless, initial_point=initial_point)
current_density_matrix = get_density_matrix(cir, point, noise_model)
fidelity = get_fidelity(target_dm, current_density_matrix)
non_reopts.append(fidelity)
gd = L_BFGS_B()
point, value, nfev = gd.optimize(initial_point.size, evaluate_expectation_noisy, initial_point=point)
current_density_matrix = get_density_matrix(cir, point, noise_model)
fidelity = get_fidelity(target_dm, current_density_matrix)
reopts.append(fidelity)
axs[0, count].plot(layers, reopts, label=str(g))
axs[0, count].scatter(layers, reopts)
axs[1, count].plot(layers, non_reopts)
axs[1, count].scatter(layers, non_reopts)
axs[1, 0].set_xlabel("Layers")
axs[1, 1].set_xlabel("Layers")
axs[1, 2].set_xlabel("Layers")
axs[0, 0].set_title('Phase damping')
axs[0, 1].set_title('Amplitude damping')
axs[0, 2].set_title('Depolarizing')
axs[0, 0].set_ylim(0.3, 1)
axs[0, 1].set_ylim(0.3, 1)
axs[0, 2].set_ylim(0.2, 1)
axs[1, 0].set_ylim(0.3, 1)
axs[1, 1].set_ylim(0.3, 1)
axs[1, 2].set_ylim(0.2, 1)
axs[0, 0].legend()
axs[0, 0].set_ylabel("Reoptimized Fidelity")
axs[1, 0].set_ylabel("Non-Reoptimized Fidelity")
plt.show()
from qiskit.tools.jupyter import *
%qiskit_version_table
|
https://github.com/renatawong/classical-shadow-vqe
|
renatawong
|
'''
(C) 2023 Renata Wong
Electronic structure problem with classical shadows, as presented in https://arxiv.org/abs/2103.07510
This code uses Qiskit as platform.
The shadow is constructed based on derandomized Hamiltonian.
The molecules tested are: H2 (6-31s basis), LiH (sto3g basis), BeH2 (sto3g), H2O (sto3g), and NH3 (sto3g).
The coordinates for NH3 were taken from 'Algorithms for Computer Detection of Symmetry Elementsin Molecular Systems'.
'''
import time
import numpy as np
from collections import Counter
import matplotlib.pyplot as plt
from qiskit import QuantumCircuit, execute
from qiskit_aer import QasmSimulator
from qiskit.quantum_info import SparsePauliOp
from qiskit_nature.units import DistanceUnit
from qiskit_nature.second_q.drivers import PySCFDriver
from qiskit_nature.second_q.algorithms import GroundStateEigensolver
from qiskit_nature.second_q.mappers import BravyiKitaevMapper, JordanWignerMapper, ParityMapper
from qiskit_nature.second_q.circuit.library import UCCSD, HartreeFock
from qiskit_nature.second_q.algorithms import VQEUCCFactory
from qiskit.algorithms.minimum_eigensolvers import VQE
from qiskit.algorithms.optimizers import SLSQP, COBYLA, SPSA
# Estimator primitive is based on the Statevector construct = algebraic simulation
from qiskit.primitives import Estimator
from qiskit.utils import algorithm_globals
from modified_derandomization import modified_derandomized_classical_shadow
from predicting_quantum_properties.data_acquisition_shadow import derandomized_classical_shadow
from predicting_quantum_properties.prediction_shadow import estimate_exp
import qiskit_nature
qiskit_nature.settings.use_pauli_sum_op = False
import h5py
H5PY_DEFAULT_READONLY=1
'''
DEFINING DRIVERS FOR THE MOLECULES
'''
H2_driver = PySCFDriver(
atom="H 0 0 0; H 0 0 0.735",
basis="6-31g",
charge=0,
spin=0,
unit=DistanceUnit.ANGSTROM,
)
LiH_driver = PySCFDriver(
atom="Li 0 0 0.5; H 0 0 0",
basis="sto3g",
charge=0,
spin=0,
unit=DistanceUnit.ANGSTROM,
)
BeH2_driver = PySCFDriver(
atom="Be 0 0 0; H 0 0 1.3264; H 0 0 -1.3264",
basis="sto3g",
charge=0,
spin=0,
unit=DistanceUnit.ANGSTROM,
)
H2O_driver = PySCFDriver(
atom="O 0.0 0.0 0.0; H 0.757 0.586 0.0; H -0.757 0.586 0.0",
basis="sto3g",
charge=0,
spin=0,
unit=DistanceUnit.ANGSTROM,
)
NH3_driver = PySCFDriver(
atom="N 0 0 0; H 0 0 1.008000; H 0.950353 0 -0.336000; H -0.475176 -0.823029 -0.336000",
basis="sto3g",
charge=0,
spin=0,
unit=DistanceUnit.ANGSTROM,
)
'''
FORMATTING HAMILTONIAN
'''
def process_hamiltonian(hamiltonian, derandomize = False):
hamiltonian_observables = []
hamiltonian_coefficients = []
for observable in hamiltonian.paulis:
op_list = []
for op_index, pauli_op in enumerate(observable):
pauli_op = str(pauli_op)
if pauli_op == 'I' or pauli_op == 'X' or pauli_op == 'Y' or pauli_op == 'Z':
op_list.append((pauli_op, op_index))
hamiltonian_observables.append(op_list)
hamiltonian_coefficients = hamiltonian.coeffs.real
system_size = len(hamiltonian_observables[0])
# removing all occurrences of Pauli-I, for all-Pauli-I there is an empty list left
# these observables are needed for estimate_exp()
observables_xyze = []
for observable in hamiltonian_observables:
XYZE = []
for pauli in observable:
if pauli[0] != 'I':
XYZE.append(pauli)
observables_xyze.append(XYZE)
# derandomisation procedure requires that coefficients are non-negative
if derandomize == True:
absolute_coefficients = [abs(coeffcient) for coeffcient in hamiltonian_coefficients]
# removing the empty list as well
# these observables are needed for derandomisation procedure
observables_xyz = []
for idx, observable in enumerate(observables_xyze):
if observable:
observables_xyz.append(observable)
else:
absolute_coefficients.pop(idx)
return system_size, observables_xyze, observables_xyz, hamiltonian_coefficients, absolute_coefficients
return system_size, observables_xyze, hamiltonian_coefficients
'''
COST FUNCTION AND HELPER FUNCTIONS
'''
def basis_change_circuit(pauli_op):
# Generating circuit with just the basis change operators
#
# pauli_op: n-qubit Pauli operator
basis_change = QuantumCircuit(ansatz.num_qubits, ansatz.num_qubits)
for idx, op in enumerate(pauli_op):
if op == 'X':
basis_change.h(idx)
if op == 'Y':
basis_change.h(idx)
basis_change.p(-np.pi/2, idx)
return basis_change
def ground_state_energy_from_shadow(operators, params):
backend = QasmSimulator(method='statevector', shots=1)
pauli_op_dict = Counter(tuple(x) for x in operators)
shadow = []
for pauli_op in pauli_op_dict:
qc = ansatz.bind_parameters(params)
qc = qc.compose(basis_change_circuit(pauli_op))
qc.measure(reversed(range(system_size)), range(system_size))
result = execute(qc, backend, shots=pauli_op_dict[pauli_op]).result()
counts = result.get_counts() # given in order q0 q1 ... qn-1 after register reversal in qc.measure
for count in counts:
for _ in range(counts[count]): # number of repeated measurement values
output_str = list(count)
output = [int(i) for i in output_str]
eigenvals = [x+1 if x == 0 else x-2 for x in output]
snapshot = [(op, eigenval) for op, eigenval in zip(pauli_op, eigenvals)]
shadow.append(snapshot)
expectation_value = 0.0
for term, weight in zip(observables_xyze, hamiltonian_coefficients):
sum_product, match_count = estimate_exp(shadow, term)
if match_count != 0:
expectation_value += (weight * sum_product / match_count)
return expectation_value
'''
EXPERIMENTS
'''
start_time = time.time()
all_molecules_rmse_errors = []
# CALCULATING FERMIONIC HAMILTONIAN AND CONVERTING TO QUBIT HAMILTONIAN
MOLECULES = ['H2', 'LiH', 'BeH2', 'H2O', 'NH3']
for molecule in MOLECULES:
rmse_errors = []
if molecule == 'H2':
problem = H2_driver.run()
if molecule == 'LiH':
problem = LiH_driver.run()
if molecule == 'BeH2':
problem = BeH2_driver.run()
if molecule == 'H2O':
problem = H2O_driver.run()
if molecule == 'NH3':
problem = NH3_driver.run()
hamiltonian = problem.hamiltonian
second_q_op = hamiltonian.second_q_op()
bk_mapper = BravyiKitaevMapper()
bkencoded_hamiltonian = bk_mapper.map(second_q_op)
#print('Qubit Hamiltonian in Bravyi-Kitaev encoding', bkencoded_hamiltonian)
# process the Hamiltonian to obtain properly formatted data
hamiltonian_data = process_hamiltonian(bkencoded_hamiltonian, derandomize = True)
system_size, observables_xyze, observables_xyz, hamiltonian_coefficients, absolute_coefficients = hamiltonian_data
'''
VARIATIONAL ANSATZ
'''
ansatz = UCCSD(
problem.num_spatial_orbitals,
problem.num_particles,
bk_mapper,
initial_state=HartreeFock(
problem.num_spatial_orbitals,
problem.num_particles,
bk_mapper,
),
)
'''
Running VQE on the Hamiltonian obtained from PySCFDriver using Statevector simulator (Estimator primitive)
'''
#estimator = Estimator()
# If shots = None, it calculates the exact expectation values. Otherwise, it samples from normal distributions
# with standard errors as standard deviations using normal distribution approximation.
#estimator.set_options(shots = None)
vqe_solver = VQE(Estimator(), ansatz, SLSQP())
vqe_solver.initial_point = np.zeros(ansatz.num_parameters)
calc = GroundStateEigensolver(bk_mapper, vqe_solver)
result = calc.solve(problem)
print(result.raw_result)
#print('NUMBER OF OPERATORS | DERANDOMISED OPERATORS | AVERAGE RMSE ERROR\n')
measurement_range = [50, 250, 500, 750, 1000, 1250, 1500, 1750]
for num_operators in measurement_range:
derandomized_hamiltonian = derandomized_classical_shadow(observables_xyz, num_operators,
system_size, weight=absolute_coefficients)
tuples = (tuple(pauli) for pauli in derandomized_hamiltonian)
counts = Counter(tuples)
print('Original derandomized Hamiltonian', counts)
# derandomized classical shadow will usually either undergenerate or overgenerate derandomized operators
# adjusting for this issue:
while sum(counts.values()) != num_operators:
for key, value in zip(counts.keys(), counts.values()):
sum_counts = sum(counts.values())
if sum_counts == num_operators:
break
if sum_counts < num_operators:
# generate additional operators from the existing ones by increasing the number of counts
counts[key] += 1
if sum_counts > num_operators:
# remove the element with highest count
max_element_key = [k for k, v in counts.items() if v == max(counts.values())][0]
counts[max_element_key] -= 1
#print('Size-adjusted derandomized Hamiltonian', counts)
# translate the Counter to a set of derandomized operators
new_derandomized_hamiltonian = []
for key, value in counts.items():
for _ in range(value):
new_derandomized_hamiltonian.append(list(key))
#print('Size-adjusted derandomized Hamiltonian', new_derandomized_hamiltonian)
expectation_values = []
num_experiments = 10
for iteration in range(num_experiments):
expectation_value = ground_state_energy_from_shadow(new_derandomized_hamiltonian, result.raw_result.optimal_point)
expectation_values.append(expectation_value)
print("EXPERIMENT {}: GROUND STATE ENERGY FOUND = {}".format(iteration, expectation_value))
rmse_derandomised_cs = np.sqrt(np.sum([(expectation_values[i] - result.raw_result.optimal_value)**2
for i in range(num_experiments)])/num_experiments)
rmse_errors.append(rmse_derandomised_cs)
print('{} | {} | {}'.format(num_operators, counts, rmse_derandomised_cs))
all_molecules_rmse_errors.append(rmse_errors)
elapsed_time = time.time() - start_time
print("Execution time = ", time.strftime("%H:%M:%S", time.gmtime(elapsed_time)))
print(all_molecules_rmse_errors)
# all_molecules_rmse_errors contains a list of lists of errors
'''
points = measurement_range
num_points = len(measurement_range)
for molecule, index in zip(molecules, enumerate(all_molecules_rmse_errors)):
plt.plot([i for i in points], [all_molecules_rmse_errors[index][i] for i in range(num_points)], 'r', label=molecule)
plt.xlabel('Number of measurements')
plt.ylabel('Average RMSE error')
plt.legend(loc=1)
'''
|
https://github.com/rodneyosodo/variational-quantum-classifier-on-heartattack
|
rodneyosodo
|
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
pd.set_option('display.max_rows', None)
pd.set_option('display.max_columns', None)
pd.set_option('display.width', None)
pd.set_option('display.max_colwidth', -1)
df = pd.read_csv("../../Data/Processed/winecosts.csv")
df.columns = ['Spec', "CostValues"]
df.head(1)
df['Spec']
def check_lowest_cost(df):
"""
Checks the configs which attained the lowest sost
"""
cost = []
lowest_cost = []
for i in range(df.shape[0]):
data = [float(x.replace("[", "").replace("]", "")) for x in df['CostValues'][i].split(',')]
lowest_cost.append(data[len(data) - 1])
lowest_cost = sorted(lowest_cost)[:10]
for m in lowest_cost:
for i in range(df.shape[0]):
data = df['CostValues'][i].split(',')
data = [float(x.replace("[", "").replace("]", "")) for x in data]
if float(m) == float(data[len(data) - 1]):
print("{} : Cost: {}".format(df["Spec"][i], data[len(data) - 1]))
cost.append(data[len(data) - 1])
#df['CostValues'] = []
#df.to_excel("n.xlsx")
# print(df.head(80))
check_lowest_cost(df)
# Plotting all
for i in range(df.shape[0]):
fig = plt.figure()
data = df['CostValues'][i].split(',')
data = [float(x.replace("[", "").replace("]", "")) for x in data]
plt.plot(range(0, len(data), 1), data)
plt.xlabel('Steps')
plt.ylabel('Cost value')
plt.title(str(df['Spec'][i]))
plt.show()
path = '../../Output/Figures/{}.jpeg'.format(df['Spec'][i].replace("(", "").replace("FeatureMap", "").replace(")", "").replace(",", "").replace("=", "").replace(" ", "").replace("_", ""))
# fig.savefig(path)
def plot_individual_optimizers(Optimizers):
for opt in Optimizers:
max_iter = 0
fig = plt.figure(figsize=(20,20))
for i in range(df.shape[0]):
if df['Spec'][i].__contains__(opt):
data = [float(x.replace("[", "").replace("]", "")) for x in df['CostValues'][i].split(',')]
if len(data) >= max_iter:
max_iter = len(data)
for i in range(df.shape[0]):
if df['Spec'][i].__contains__(opt):
data = df['CostValues'][i].split(',')
data = [float(x.replace("[", "").replace("]", "")) for x in data]
if max_iter >= len(data):
temp = np.full((max_iter, ), data[len(data) -1])
temp[:len(data)] = data
data = temp
plt.plot(range(0, len(data), 1), data, label='{}'.format(df['Spec'][i].replace("(", "").replace("FeatureMap", "").replace(")", "").replace(",", "").replace("=", "").replace(" ", "").replace("_", "")))
plt.xlabel('Steps')
plt.ylabel('Cost value')
plt.title(opt)
plt.legend()
plt.show()
plot_individual_optimizers(["COBYLA", "SPSA", "ADAM"])
def plot_increase_vdepth(optimizer, featuremap, reps, checking):
points = []
for i in range(df.shape[0]):
title = str(df['Spec'][i])
if title.split("(")[0] == featuremap and str(title).__contains__(optimizer) and str(title).__contains__("reps={}".format(reps)):
points.append(float(df['CostValues'][i].split(',')[-1].replace("[", "").replace("]", "")))
fig = plt.figure()
plt.plot(range(0, len(points), 1), points)
plt.xlabel(checking)
plt.ylabel('Cost value')
plt.title("{} {} featuremap {} fdepth".format(optimizer, featuremap, reps))
plt.show()
def plot_increase_fdepth(optimizer, featuremap, fdepth, checking):
points = []
for i in range(df.shape[0]):
title = str(df['Spec'][i])
if title.split("(")[0] == featuremap and str(title).__contains__(optimizer) and str(title).__contains__("vdepth {}".format(fdepth)):
points.append(float(df['CostValues'][i].split(',')[-1].replace("[", "").replace("]", "")))
fig = plt.figure()
plt.plot(range(0, len(points), 1), points)
plt.xlabel(checking)
plt.ylabel('Cost value')
plt.title("{} {} featuremap {} vdepth".format(optimizer, featuremap, fdepth))
plt.show()
plot_increase_vdepth("SPSA", "PauliFeatureMap", 1, "fdepth")
plot_increase_fdepth("SPSA", "PauliFeatureMap", 1, "vdepth")
for opt in ['SPSA', "COBYLA", "ADAM"]:
for fmap in ['ZZFeatureMap', 'ZFeatureMap', "PauliFeatureMap"]:
for fdepth in [1, 2, 4]:
plot_increase_vdepth(opt, fmap, fdepth, "vdepth")
for opt in ['SPSA', "COBYLA", "ADAM"]:
for fmap in ['ZZFeatureMap', 'ZFeatureMap', "PauliFeatureMap"]:
for fdepth in [1, 3, 5]:
plot_increase_fdepth(opt, fmap, fdepth, "fdepth")
|
https://github.com/swe-train/qiskit__qiskit
|
swe-train
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test RemoveFinalMeasurements pass"""
import unittest
from qiskit import ClassicalRegister, QuantumRegister, QuantumCircuit
from qiskit.circuit.classicalregister import Clbit
from qiskit.transpiler.passes import RemoveFinalMeasurements
from qiskit.converters import circuit_to_dag
from qiskit.test import QiskitTestCase
class TestRemoveFinalMeasurements(QiskitTestCase):
"""Test removing final measurements."""
def test_multi_bit_register_removed_with_clbits(self):
"""Remove register when all clbits removed."""
def expected_dag():
q0 = QuantumRegister(2, "q0")
qc = QuantumCircuit(q0)
return circuit_to_dag(qc)
q0 = QuantumRegister(2, "q0")
c0 = ClassicalRegister(2, "c0")
qc = QuantumCircuit(q0, c0)
# measure into all clbits of c0
qc.measure(0, 0)
qc.measure(1, 1)
dag = circuit_to_dag(qc)
dag = RemoveFinalMeasurements().run(dag)
self.assertFalse(dag.cregs)
self.assertFalse(dag.clbits)
self.assertEqual(dag, expected_dag())
def test_register_kept_if_measured_clbit_busy(self):
"""
A register is kept if the measure destination bit is still
busy after measure removal.
"""
def expected_dag():
q0 = QuantumRegister(1, "q0")
c0 = ClassicalRegister(1, "c0")
qc = QuantumCircuit(q0, c0)
qc.x(0).c_if(c0[0], 0)
return circuit_to_dag(qc)
q0 = QuantumRegister(1, "q0")
c0 = ClassicalRegister(1, "c0")
qc = QuantumCircuit(q0, c0)
# make c0 busy
qc.x(0).c_if(c0[0], 0)
# measure into c0
qc.measure(0, c0[0])
dag = circuit_to_dag(qc)
dag = RemoveFinalMeasurements().run(dag)
self.assertListEqual(list(dag.cregs.values()), [c0])
self.assertListEqual(dag.clbits, list(c0))
self.assertEqual(dag, expected_dag())
def test_multi_bit_register_kept_if_not_measured_clbit_busy(self):
"""
A multi-bit register is kept if it contains a busy bit even if
the measure destination bit itself is idle.
"""
def expected_dag():
q0 = QuantumRegister(1, "q0")
c0 = ClassicalRegister(2, "c0")
qc = QuantumCircuit(q0, c0)
qc.x(q0[0]).c_if(c0[0], 0)
return circuit_to_dag(qc)
q0 = QuantumRegister(1, "q0")
c0 = ClassicalRegister(2, "c0")
qc = QuantumCircuit(q0, c0)
# make c0[0] busy
qc.x(q0[0]).c_if(c0[0], 0)
# measure into not busy c0[1]
qc.measure(0, c0[1])
dag = circuit_to_dag(qc)
dag = RemoveFinalMeasurements().run(dag)
# c0 should not be removed because it has busy bit c0[0]
self.assertListEqual(list(dag.cregs.values()), [c0])
# note: c0[1] should not be removed even though it is now idle
# because it is referenced by creg c0.
self.assertListEqual(dag.clbits, list(c0))
self.assertEqual(dag, expected_dag())
def test_overlapping_register_removal(self):
"""Only registers that become idle directly as a result of
final op removal are removed. In this test, a 5-bit creg
is implicitly created with its own bits, along with cregs
``c0_lower_3`` and ``c0_upper_3`` which reuse those underlying bits.
``c0_lower_3`` and ``c0_upper_3`` reference only 1 bit in common.
A final measure is performed into a bit that exists in ``c0_lower_3``
but not in ``c0_upper_3``, and subsequently is removed. Consequently,
both ``c0_lower_3`` and the 5-bit register are removed, because they
have become unused as a result of the final measure removal.
``c0_upper_3`` remains, because it was idle beforehand, not as a
result of the measure removal, along with all of its bits,
including the bit shared with ``c0_lower_3``."""
def expected_dag():
q0 = QuantumRegister(3, "q0")
c0 = ClassicalRegister(5, "c0")
c0_upper_3 = ClassicalRegister(name="c0_upper_3", bits=c0[2:])
# note c0 is *not* added to circuit!
qc = QuantumCircuit(q0, c0_upper_3)
return circuit_to_dag(qc)
q0 = QuantumRegister(3, "q0")
c0 = ClassicalRegister(5, "c0")
qc = QuantumCircuit(q0, c0)
c0_lower_3 = ClassicalRegister(name="c0_lower_3", bits=c0[:3])
c0_upper_3 = ClassicalRegister(name="c0_upper_3", bits=c0[2:])
# Only qc.clbits[2] is shared between the two.
qc.add_register(c0_lower_3)
qc.add_register(c0_upper_3)
qc.measure(0, c0_lower_3[0])
dag = circuit_to_dag(qc)
dag = RemoveFinalMeasurements().run(dag)
self.assertListEqual(list(dag.cregs.values()), [c0_upper_3])
self.assertListEqual(dag.clbits, list(c0_upper_3))
self.assertEqual(dag, expected_dag())
def test_multi_bit_register_removed_if_all_bits_idle(self):
"""A multibit register is removed when all bits are idle."""
def expected_dag():
q0 = QuantumRegister(1, "q0")
qc = QuantumCircuit(q0)
return circuit_to_dag(qc)
q0 = QuantumRegister(1, "q0")
c0 = ClassicalRegister(2, "c0")
qc = QuantumCircuit(q0, c0)
# measure into single bit c0[0] of c0
qc.measure(0, 0)
dag = circuit_to_dag(qc)
dag = RemoveFinalMeasurements().run(dag)
self.assertFalse(dag.cregs)
self.assertFalse(dag.clbits)
self.assertEqual(dag, expected_dag())
def test_multi_reg_shared_bits_removed(self):
"""All registers sharing removed bits should be removed."""
def expected_dag():
q0 = QuantumRegister(2, "q0")
qc = QuantumCircuit(q0)
return circuit_to_dag(qc)
q0 = QuantumRegister(2, "q0")
c0 = ClassicalRegister(2, "c0")
qc = QuantumCircuit(q0, c0)
# Create reg with shared bits (same as c0)
c1 = ClassicalRegister(name="c1", bits=qc.clbits)
qc.add_register(c1)
# measure into all clbits of c0
qc.measure(0, c0[0])
qc.measure(1, c0[1])
dag = circuit_to_dag(qc)
dag = RemoveFinalMeasurements().run(dag)
self.assertFalse(dag.cregs)
self.assertFalse(dag.clbits)
self.assertEqual(dag, expected_dag())
def test_final_measures_share_dest(self):
"""Multiple final measurements use the same clbit."""
def expected_dag():
qc = QuantumCircuit(QuantumRegister(2, "q0"))
return circuit_to_dag(qc)
rq = QuantumRegister(2, "q0")
rc = ClassicalRegister(1, "c0")
qc = QuantumCircuit(rq, rc)
qc.measure(0, 0)
qc.measure(1, 0)
dag = circuit_to_dag(qc)
dag = RemoveFinalMeasurements().run(dag)
self.assertEqual(dag, expected_dag())
def test_remove_chained_final_measurements(self):
"""Remove successive final measurements."""
def expected_dag():
q0 = QuantumRegister(1, "q0")
q1 = QuantumRegister(1, "q1")
c0 = ClassicalRegister(1, "c0")
qc = QuantumCircuit(q0, c0, q1)
qc.measure(q0, c0)
qc.measure(q0, c0)
qc.barrier()
qc.h(q1)
return circuit_to_dag(qc)
q0 = QuantumRegister(1, "q0")
q1 = QuantumRegister(1, "q1")
c0 = ClassicalRegister(1, "c0")
c1 = ClassicalRegister(1, "c1")
qc = QuantumCircuit(q0, c0, q1, c1)
qc.measure(q0, c0)
qc.measure(q0, c0)
qc.barrier()
qc.h(q1)
qc.measure(q1, c1)
qc.measure(q0, c1)
dag = circuit_to_dag(qc)
dag = RemoveFinalMeasurements().run(dag)
self.assertEqual(dag, expected_dag())
def test_remove_clbits_without_register(self):
"""clbits of final measurements not in a register are removed."""
def expected_dag():
q0 = QuantumRegister(1, "q0")
qc = QuantumCircuit(q0)
return circuit_to_dag(qc)
q0 = QuantumRegister(1, "q0")
qc = QuantumCircuit(q0)
# Add clbit without adding register
qc.add_bits([Clbit()])
self.assertFalse(qc.cregs)
# Measure to regless clbit
qc.measure(0, 0)
dag = circuit_to_dag(qc)
dag = RemoveFinalMeasurements().run(dag)
self.assertFalse(dag.cregs)
self.assertFalse(dag.clbits)
self.assertEqual(dag, expected_dag())
def test_final_barriers_and_measures_complex(self):
"""Test complex final barrier and measure removal."""
def expected_dag():
q0 = QuantumRegister(5, "q0")
c1 = ClassicalRegister(1, "c1")
qc = QuantumCircuit(q0, c1)
qc.h(q0[0])
return circuit_to_dag(qc)
# ┌───┐┌─┐ ░ ░ ┌─┐
# q0_0: ┤ H ├┤M├─░─────░─┤M├───────────────
# └┬─┬┘└╥┘ ░ ░ └╥┘┌─┐
# q0_1: ─┤M├──╫──░─────░──╫─┤M├────────────
# └╥┘ ║ ░ ░ ░ ║ └╥┘┌─┐
# q0_2: ──╫───╫──░──░──░──╫──╫─┤M├─────────
# ║ ║ ░ ░ ░ ║ ║ └╥┘┌─┐
# q0_3: ──╫───╫──░──░──░──╫──╫──╫─┤M├──────
# ║ ║ ░ ░ ░ ║ ║ ║ └╥┘┌─┐ ░
# q0_4: ──╫───╫──░─────░──╫──╫──╫──╫─┤M├─░─
# ║ ║ ░ ░ ║ ║ ║ ║ └╥┘ ░
# c0: 1/══╩═══╩═══════════╬══╬══╬══╬══╬════
# 0 0 ║ ║ ║ ║ ║
# ║ ║ ║ ║ ║
# c1: 1/══════════════════╬══╬══╬══╬══╬════
# ║ ║ ║ ║ ║
# meas: 5/════════════════╩══╩══╩══╩══╩════
# 0 1 2 3 4
q0 = QuantumRegister(5, "q0")
c0 = ClassicalRegister(1, "c0")
c1 = ClassicalRegister(1, "c1")
qc = QuantumCircuit(q0, c0, c1)
qc.measure(q0[1], c0)
qc.h(q0[0])
qc.measure(q0[0], c0[0])
qc.barrier()
qc.barrier(q0[2], q0[3])
qc.measure_all()
qc.barrier(q0[4])
dag = circuit_to_dag(qc)
dag = RemoveFinalMeasurements().run(dag)
self.assertEqual(dag, expected_dag())
if __name__ == "__main__":
unittest.main()
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2022, 2023.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Tests evaluator of auxiliary operators for algorithms."""
from __future__ import annotations
import unittest
from typing import Tuple
from test.python.algorithms import QiskitAlgorithmsTestCase
import numpy as np
from ddt import ddt, data
from qiskit_algorithms.list_or_dict import ListOrDict
from qiskit.quantum_info.operators.base_operator import BaseOperator
from qiskit_algorithms import estimate_observables
from qiskit.primitives import Estimator
from qiskit.quantum_info import Statevector, SparsePauliOp
from qiskit import QuantumCircuit
from qiskit.circuit.library import EfficientSU2
from qiskit.opflow import PauliSumOp
from qiskit.utils import algorithm_globals
@ddt
class TestObservablesEvaluator(QiskitAlgorithmsTestCase):
"""Tests evaluator of auxiliary operators for algorithms."""
def setUp(self):
super().setUp()
self.seed = 50
algorithm_globals.random_seed = self.seed
self.threshold = 1e-8
def get_exact_expectation(
self, ansatz: QuantumCircuit, observables: ListOrDict[BaseOperator | PauliSumOp]
):
"""
Calculates the exact expectation to be used as an expected result for unit tests.
"""
if isinstance(observables, dict):
observables_list = list(observables.values())
else:
observables_list = observables
# the exact value is a list of (mean, (variance, shots)) where we expect 0 variance and
# 0 shots
exact = [
(Statevector(ansatz).expectation_value(observable), {})
for observable in observables_list
]
if isinstance(observables, dict):
return dict(zip(observables.keys(), exact))
return exact
def _run_test(
self,
expected_result: ListOrDict[Tuple[complex, complex]],
quantum_state: QuantumCircuit,
decimal: int,
observables: ListOrDict[BaseOperator | PauliSumOp],
estimator: Estimator,
):
result = estimate_observables(estimator, quantum_state, observables, None, self.threshold)
if isinstance(observables, dict):
np.testing.assert_equal(list(result.keys()), list(expected_result.keys()))
means = [element[0] for element in result.values()]
expected_means = [element[0] for element in expected_result.values()]
np.testing.assert_array_almost_equal(means, expected_means, decimal=decimal)
vars_and_shots = [element[1] for element in result.values()]
expected_vars_and_shots = [element[1] for element in expected_result.values()]
np.testing.assert_array_equal(vars_and_shots, expected_vars_and_shots)
else:
means = [element[0] for element in result]
expected_means = [element[0] for element in expected_result]
np.testing.assert_array_almost_equal(means, expected_means, decimal=decimal)
vars_and_shots = [element[1] for element in result]
expected_vars_and_shots = [element[1] for element in expected_result]
np.testing.assert_array_equal(vars_and_shots, expected_vars_and_shots)
@data(
[
PauliSumOp.from_list([("II", 0.5), ("ZZ", 0.5), ("YY", 0.5), ("XX", -0.5)]),
PauliSumOp.from_list([("II", 2.0)]),
],
[
PauliSumOp.from_list([("ZZ", 2.0)]),
],
{
"op1": PauliSumOp.from_list([("II", 2.0)]),
"op2": PauliSumOp.from_list([("II", 0.5), ("ZZ", 0.5), ("YY", 0.5), ("XX", -0.5)]),
},
{
"op1": PauliSumOp.from_list([("ZZ", 2.0)]),
},
[],
{},
)
def test_estimate_observables(self, observables: ListOrDict[BaseOperator | PauliSumOp]):
"""Tests evaluator of auxiliary operators for algorithms."""
ansatz = EfficientSU2(2)
parameters = np.array(
[1.2, 4.2, 1.4, 2.0, 1.2, 4.2, 1.4, 2.0, 1.2, 4.2, 1.4, 2.0, 1.2, 4.2, 1.4, 2.0],
dtype=float,
)
bound_ansatz = ansatz.bind_parameters(parameters)
states = bound_ansatz
expected_result = self.get_exact_expectation(bound_ansatz, observables)
estimator = Estimator()
decimal = 6
self._run_test(
expected_result,
states,
decimal,
observables,
estimator,
)
def test_estimate_observables_zero_op(self):
"""Tests if a zero operator is handled correctly."""
ansatz = EfficientSU2(2)
parameters = np.array(
[1.2, 4.2, 1.4, 2.0, 1.2, 4.2, 1.4, 2.0, 1.2, 4.2, 1.4, 2.0, 1.2, 4.2, 1.4, 2.0],
dtype=float,
)
bound_ansatz = ansatz.bind_parameters(parameters)
state = bound_ansatz
estimator = Estimator()
observables = [SparsePauliOp(["XX", "YY"]), 0]
result = estimate_observables(estimator, state, observables, None, self.threshold)
expected_result = [(0.015607318055509564, {}), (0.0, {})]
means = [element[0] for element in result]
expected_means = [element[0] for element in expected_result]
np.testing.assert_array_almost_equal(means, expected_means, decimal=0.01)
vars_and_shots = [element[1] for element in result]
expected_vars_and_shots = [element[1] for element in expected_result]
np.testing.assert_array_equal(vars_and_shots, expected_vars_and_shots)
def test_estimate_observables_shots(self):
"""Tests that variances and shots are returned properly."""
ansatz = EfficientSU2(2)
parameters = np.array(
[1.2, 4.2, 1.4, 2.0, 1.2, 4.2, 1.4, 2.0, 1.2, 4.2, 1.4, 2.0, 1.2, 4.2, 1.4, 2.0],
dtype=float,
)
bound_ansatz = ansatz.bind_parameters(parameters)
state = bound_ansatz
estimator = Estimator(options={"shots": 2048})
with self.assertWarns(DeprecationWarning):
observables = [PauliSumOp.from_list([("ZZ", 2.0)])]
result = estimate_observables(estimator, state, observables, None, self.threshold)
exact_result = self.get_exact_expectation(bound_ansatz, observables)
expected_result = [(exact_result[0][0], {"variance": 1.0898, "shots": 2048})]
means = [element[0] for element in result]
expected_means = [element[0] for element in expected_result]
np.testing.assert_array_almost_equal(means, expected_means, decimal=0.01)
vars_and_shots = [element[1] for element in result]
expected_vars_and_shots = [element[1] for element in expected_result]
for computed, expected in zip(vars_and_shots, expected_vars_and_shots):
self.assertAlmostEqual(computed.pop("variance"), expected.pop("variance"), 2)
self.assertEqual(computed.pop("shots"), expected.pop("shots"))
if __name__ == "__main__":
unittest.main()
|
https://github.com/liyaochong/quantum-algorithm-learning-and-implementation
|
liyaochong
|
# 导入相应的运算库
import numpy as np
from math import pi
from qiskit import BasicAer, execute
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute
from qiskit.tools.visualization import circuit_drawer
# 定义相应的量子寄存器,并添加至电路当中去
# q0寄存器表示地址寄存器
q0 = QuantumRegister(1,'q0')
c0 = ClassicalRegister(1,'c0')
# q1寄存器表示数据寄存器,寄存器的位数表示计算的精度,这里设置为3,最后误差在0.125以内
q1 = QuantumRegister(3,'q1')
c1 = ClassicalRegister(3,'c1')
# q2寄存器表示执行量子算数的的目标寄存器,位数一般与q1寄存器相同
q2 = QuantumRegister(3,'q2')
c2 = ClassicalRegister(3,'c2')
# q3寄存器用来做辅助量子比特,执行系列的受控旋转操作
q3 = QuantumRegister(1,'q3')
c3 = ClassicalRegister(1,'c3')
# 定义一个量子电路对象
Circuit = QuantumCircuit()
# 往寄存器中添加4个量子寄存器
Circuit.add_register(q0,c0)
Circuit.add_register(q1,c1)
Circuit.add_register(q2,c2)
Circuit.add_register(q3,c3)
# 添加量子门操作,注意这里的命名方式为最低有效位
# 执行H门操作,将地址寄存器q0张开,分叉存储,由于两个数据只需要用1个量子比特进行表示
Circuit.h(q0[0])
# 写入数据至q1寄存器,更为通用的采用的是QRAM算法,或者其他数据制备算法,注意这里的数据用基态表示,本质上以经典的形式出现
Circuit.x(q0[0])
Circuit.cx(q0[0],q1[1])
Circuit.x(q0[0])
Circuit.cx(q0[0],q1[0])
Circuit.cx(q0[0],q1[1])
# 这里执行的量子算数运算,进行的是类似一个函数的运算过程
Circuit.barrier()
Circuit.x(q1[0])
Circuit.cx(q1[0],q2[0])
Circuit.x(q1[0])
Circuit.cx(q1[1],q2[1])
Circuit.cx(q1[2],q2[2])
# 执行受控旋转操作,将数据从函数运算的输出,加载到概率幅度上
Circuit.barrier()
Circuit.cu3(pi/2, 0, 0, q2[0], q3)
Circuit.cu3(pi/4, 0, 0, q2[1], q3)
Circuit.cu3(pi/8, 0, 0, q2[2], q3)
# 执行量子算数运算的解运算过程
Circuit.barrier()
Circuit.cx(q1[2],q2[2])
Circuit.cx(q1[1],q2[1])
Circuit.x(q1[0])
Circuit.cx(q1[0],q2[0])
Circuit.x(q1[0])
# 执行数据的量子制备过程的逆变换(IQRAM),完成解运算
Circuit.barrier()
Circuit.cx(q0[0],q1[1])
Circuit.cx(q0[0],q1[0])
Circuit.x(q0[0])
Circuit.cx(q0[0],q1[1])
Circuit.x(q0[0])
# 添加测量操作,量子寄存器关联相应的经典寄存器
Circuit.barrier()
Circuit.measure(q0,c0)
Circuit.measure(q1,c1)
Circuit.measure(q2,c2)
Circuit.measure(q3,c3)
# 绘制整个量子电路图
Circuit.draw(output='mpl')
# 使用 Aer's qasm_simulator
backend_sim = BasicAer.get_backend('qasm_simulator')
# 执行量子仿真器
job_sim = execute(Circuit, backend_sim, shots=8096)
# 获得结果
result_sim = job_sim.result()
counts = result_sim.get_counts(Circuit)
# 打印结果输出
print(counts)
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
# pylint: disable=wrong-import-order
"""Main Qiskit public functionality."""
import pkgutil
# First, check for required Python and API version
from . import util
# qiskit errors operator
from .exceptions import QiskitError
# The main qiskit operators
from qiskit.circuit import ClassicalRegister
from qiskit.circuit import QuantumRegister
from qiskit.circuit import QuantumCircuit
# pylint: disable=redefined-builtin
from qiskit.tools.compiler import compile # TODO remove after 0.8
from qiskit.execute import execute
# The qiskit.extensions.x imports needs to be placed here due to the
# mechanism for adding gates dynamically.
import qiskit.extensions
import qiskit.circuit.measure
import qiskit.circuit.reset
# Allow extending this namespace. Please note that currently this line needs
# to be placed *before* the wrapper imports or any non-import code AND *before*
# importing the package you want to allow extensions for (in this case `backends`).
__path__ = pkgutil.extend_path(__path__, __name__)
# Please note these are global instances, not modules.
from qiskit.providers.basicaer import BasicAer
# Try to import the Aer provider if installed.
try:
from qiskit.providers.aer import Aer
except ImportError:
pass
# Try to import the IBMQ provider if installed.
try:
from qiskit.providers.ibmq import IBMQ
except ImportError:
pass
from .version import __version__
from .version import __qiskit_version__
|
https://github.com/AbdulahAmer/PHYS-31415-Summer-2021
|
AbdulahAmer
|
# first lets make a table of the possible inputs and outputs, first we need to install tabulate using
# pip the python package installer
# make sure it has its own cell
pip install tabulate
#Here are the possible inputs and corresponding outputs,
from tabulate import tabulate
print(tabulate([[ '|0>c |0>t', '|0>c |0>t' ], ['|0>c |1>t', '|0>c |1>t'],
[ '|1>c |0>t', '|1>c |1>t' ],
[ '|1>c |0>t', '|1>c |0>t' ]], headers=['Input', 'Output']))
from qiskit import * # this means that from the qiskit package
# import ALL functionality(*)
# we also want to see our results in insightful ways through graphs!
from qiskit.visualization import * # bloch sphere graphs, bar graphs for measurements
# We also need to import the simulators that we will use to make measurements
S_simulator=Aer.backends(name='statevector_simulator')[0] # allows you to simulate statevectors
M_simulator=Aer.backends(name='qasm_simulator')[0] # allows you to simulate measurements
# make a quantum circuit with two qubits and two classical bits
qc= QuantumCircuit(2,2)
# Initialize first qubit to |1> so that we can see CNOT (cx) do something
one = [0,1]
qc.initialize(one, 0)
# print out initial state to confirm that something happens when we use our gate!
initial_state=execute(qc, S_simulator).result().get_statevector()
print('Initial state: ', initial_state)
# use the Cx gate, first qubit as control and second qubit as target
qc.cx(0,1)
# print out results!
state_after_gate= execute(qc, S_simulator).result().get_statevector()
print('state after CX gate: ', state_after_gate)
# example of DJ algorithm (CX for balanced)
# make circuit
dj = QuantumCircuit(2,2)
# Initialize second qubit
one=[0,1]
dj.initialize(one, 1)
# we use barries to seperate steps
dj.barrier()
# Apply H gates
dj.h(0)
dj.h(1)
dj.barrier()
# Use cx as Uf
dj.cx(0,1)
dj.barrier()
dj.h(0)
dj.barrier()
dj.measure(0,0)
dj.draw(output='mpl')
plot_histogram(execute(dj, M_simulator).result().get_counts())
# example of DJ algorithm (CX for balanced)
# make circuit
dj = QuantumCircuit(2,2)
# Initialize second qubit
one=[0,1]
dj.initialize(one, 1)
# we use barries to seperate steps
dj.barrier()
# Apply H gates
dj.h(0)
dj.h(1)
dj.barrier()
# do nothing for constant function
dj.barrier()
dj.h(0)
dj.barrier()
dj.measure(0,0)
dj.draw(output='mpl')
plot_histogram(execute(dj, M_simulator).result().get_counts())
|
https://github.com/rochelleli165/qiskitfallfest2023
|
rochelleli165
|
########################################
# ENTER YOUR NAME AND WISC EMAIL HERE: #
########################################
# Name: Rochelle Li
# Email: rli484@wisc.edu
## Run this cell to make sure your grader is setup correctly
%set_env QC_GRADE_ONLY=true
%set_env QC_GRADING_ENDPOINT=https://qac-grading.quantum-computing.ibm.com
from qiskit import QuantumCircuit
from qiskit.circuit import QuantumRegister, ClassicalRegister
qr = QuantumRegister(1)
cr = ClassicalRegister(2)
qc = QuantumCircuit(qr, cr)
# unpack the qubit and classical bits from the registers
(q0,) = qr
b0, b1 = cr
# apply Hadamard
qc.h(q0)
# measure
qc.measure(q0, b0)
# begin if test block. the contents of the block are executed if b0 == 1
with qc.if_test((b0, 1)):
# if the condition is satisfied (b0 == 1), then flip the bit back to 0
qc.x(q0)
# finally, measure q0 again
qc.measure(q0, b1)
qc.draw(output="mpl", idle_wires=False)
from qiskit_aer import AerSimulator
# initialize the simulator
backend_sim = AerSimulator()
# run the circuit
reset_sim_job = backend_sim.run(qc)
# get the results
reset_sim_result = reset_sim_job.result()
# retrieve the bitstring counts
reset_sim_counts = reset_sim_result.get_counts()
print(f"Counts: {reset_sim_counts}")
from qiskit.visualization import *
# plot histogram
plot_histogram(reset_sim_counts)
qr = QuantumRegister(2)
cr = ClassicalRegister(2)
qc = QuantumCircuit(qr, cr)
q0, q1 = qr
b0, b1 = cr
qc.h(q0)
qc.measure(q0, b0)
## Write your code below this line ##
with qc.if_test((b0, 0)) as else_:
qc.x(1)
with else_:
qc.h(1)
## Do not change the code below this line ##
qc.measure(q1, b1)
qc.draw(output="mpl", idle_wires=False)
backend_sim = AerSimulator()
job_1 = backend_sim.run(qc)
result_1 = job_1.result()
counts_1 = result_1.get_counts()
print(f"Counts: {counts_1}")
# Grader Cell: Run this to submit your answer
from qc_grader.challenges.fall_fest23 import grade_ex3b
grade_ex3b(qc)
controls = QuantumRegister(2, name="control")
target = QuantumRegister(1, name="target")
mid_measure = ClassicalRegister(2, name="mid")
final_measure = ClassicalRegister(1, name="final")
base = QuantumCircuit(controls, target, mid_measure, final_measure)
def trial(
circuit: QuantumCircuit,
target: QuantumRegister,
controls: QuantumRegister,
measures: ClassicalRegister,
):
"""Probabilistically perform Rx(theta) on the target, where cos(theta) = 3/5."""
## Write your code below this line, making sure it's indented to where this comment begins from ##
c0,c1 = controls
(t0,) = target
b0, b1 = mid_measure
circuit.h(c0)
circuit.h(c1)
circuit.h(t0)
circuit.ccx(c0, c1, t0)
circuit.s(t0)
circuit.ccx(c0, c1, t0)
circuit.h(c0)
circuit.h(c1)
circuit.h(t0)
circuit.measure(c0, b0)
circuit.measure(c1, b1)
## Do not change the code below this line ##
qc = base.copy_empty_like()
trial(qc, target, controls, mid_measure)
qc.draw("mpl", cregbundle=False)
# Grader Cell: Run this to submit your answer
from qc_grader.challenges.fall_fest23 import grade_ex3c
grade_ex3c(qc)
def reset_controls(
circuit: QuantumCircuit, controls: QuantumRegister, measures: ClassicalRegister
):
"""Reset the control qubits if they are in |1>."""
## Write your code below this line, making sure it's indented to where this comment begins from ##
c0, c1 = controls
r0, r1 = measures
# circuit.h(c0)
# circuit.h(c1)
# circuit.measure(c0, r0)
# circuit.measure(c1, r1)
with circuit.if_test((r0, 1)):
circuit.x(c0)
with circuit.if_test((r1, 1)):
circuit.x(c1)
## Do not change the code below this line ##
qc = base.copy_empty_like()
trial(qc, target, controls, mid_measure)
reset_controls(qc, controls, mid_measure)
qc.measure(controls, mid_measure)
qc.draw("mpl", cregbundle=False)
# Grader Cell: Run this to submit your answer
from qc_grader.challenges.fall_fest23 import grade_ex3d
grade_ex3d(qc)
# Set the maximum number of trials
max_trials = 2
# Create a clean circuit with the same structure (bits, registers, etc) as the initial base we set up.
circuit = base.copy_empty_like()
# The first trial does not need to reset its inputs, since the controls are guaranteed to start in the |0> state.
trial(circuit, target, controls, mid_measure)
# Manually add the rest of the trials. In the future, we will be able to use a dynamic `while` loop to do this, but for now,
# we statically add each loop iteration with a manual condition check on each one.
# This involves more classical synchronizations than the while loop, but will suffice for now.
for _ in range(max_trials - 1):
reset_controls(circuit, controls, mid_measure)
with circuit.if_test((mid_measure, 0b00)) as else_:
# This is the success path, but Qiskit can't directly
# represent a negative condition yet, so we have an
# empty `true` block in order to use the `else` branch.
pass
with else_:
## Write your code below this line, making sure it's indented to where this comment begins from ##
# (t0,) = target
circuit.x(2)
trial(circuit, target, controls, mid_measure)
## Do not change the code below this line ##
# We need to measure the control qubits again to ensure we get their final results; this is a hardware limitation.
circuit.measure(controls, mid_measure)
# Finally, let's measure our target, to check that we're getting the rotation we desired.
circuit.measure(target, final_measure)
circuit.draw("mpl", cregbundle=False)
# Grader Cell: Run this to submit your answer
from qc_grader.challenges.fall_fest23 import grade_ex3e
grade_ex3e(circuit)
sim = AerSimulator()
job = sim.run(circuit, shots=1000)
result = job.result()
counts = result.get_counts()
plot_histogram(counts)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import execute, pulse
d0 = pulse.DriveChannel(0)
with pulse.build() as pulse_prog:
pulse.play(pulse.Constant(100, 1.0), d0)
pulse_prog.draw()
|
https://github.com/JessicaJohnBritto/Quantum-Computing-and-Information
|
JessicaJohnBritto
|
pip install pennylane
import pennylane as qml
from pennylane import numpy as np
import matplotlib.pyplot as plt
dev = qml.device('default.qubit', wires=3)
@qml.qnode(dev)
def make_basis_state(basis_id):
"""Produce the 3-qubit basis state corresponding to |basis_id>.
Note that the system starts in |000>.
Args:
basis_id (int): An integer value identifying the basis state to construct.
Returns:
array[complex]: The computational basis state |basis_id>.
"""
##################
# YOUR CODE HERE #
##################
# CREATE THE BASIS STATE
k = np.binary_repr(basis_id, width = 3)
l = [int(x) for x in k]
print(l)
print(np.arange(3))
qml.BasisStatePreparation(l, wires=range(3))
return qml.state()
basis_id = 3
print(f"Output state = {make_basis_state(basis_id)}")
# Creates a device with *two* qubits
dev = qml.device('default.qubit', wires=2)
@qml.qnode(dev)
def two_qubit_circuit():
##################
# YOUR CODE HERE #
##################
# PREPARE |+>|1>
qml.Hadamard(wires=0)
qml.PauliX(wires=1)
# RETURN TWO EXPECTATION VALUES, Y ON FIRST QUBIT, Z ON SECOND QUBIT
k = qml.expval(qml.PauliY(wires=0))
m = qml.expval(qml.PauliZ(wires=1))
l = [k,m]
return l
print(two_qubit_circuit())
dev = qml.device("default.qubit", wires=2)
@qml.qnode(dev)
def create_one_minus():
##################
# YOUR CODE HERE #
##################
# PREPARE |1>|->
qml.PauliX(wires=0)
qml.PauliX(wires=1)
qml.Hadamard(wires=1)
# RETURN A SINGLE EXPECTATION VALUE Z \otimes X
return qml.expval(qml.PauliZ(0)@qml.PauliX(1))
print(create_one_minus())
dev = qml.device('default.qubit', wires=2)
@qml.qnode(dev)
def circuit_1(theta):
"""Implement the circuit and measure Z I and I Z.
Args:
theta (float): a rotation angle.
Returns:
float, float: The expectation values of the observables Z I, and I Z
"""
##################
# YOUR CODE HERE #
##################
qml.RX(theta, wires=0)
qml.RY(2*theta, wires=1)
return qml.expval(qml.PauliZ(0)), qml.expval(qml.PauliZ(1))
@qml.qnode(dev)
def circuit_2(theta):
"""Implement the circuit and measure Z Z.
Args:
theta (float): a rotation angle.
Returns:
float: The expectation value of the observable Z Z
"""
##################
# YOUR CODE HERE #
##################
qml.RX(theta, wires=0)
qml.RY(2*theta, wires=1)
return qml.expval(qml.PauliZ(0) @qml.PauliZ(1))
def zi_iz_combination(ZI_results, IZ_results):
"""Implement a function that acts on the ZI and IZ results to
produce the ZZ results. How do you think they should combine?
Args:
ZI_results (array[float]): Results from the expectation value of
ZI in circuit_1.
IZ_results (array[float]): Results from the expectation value of
IZ in circuit_2.
Returns:
array[float]: A combination of ZI_results and IZ_results that
produces results equivalent to measuring ZZ.
"""
combined_results = np.zeros(len(ZI_results))
##################
# YOUR CODE HERE #
##################
return ZI_results*IZ_results
theta = np.linspace(0, 2 * np.pi, 100)
# Run circuit 1, and process the results
circuit_1_results = np.array([circuit_1(t) for t in theta])
ZI_results = circuit_1_results[:, 0]
IZ_results = circuit_1_results[:, 1]
combined_results = zi_iz_combination(ZI_results, IZ_results)
# Run circuit 2
ZZ_results = np.array([circuit_2(t) for t in theta])
# Plot your results
plot = plotter(theta, ZI_results, IZ_results, ZZ_results, combined_results)
dev = qml.device('default.qubit', wires=2)
@qml.qnode(dev)
def apply_cnot(basis_id):
"""Apply a CNOT to |basis_id>.
Args:
basis_id (int): An integer value identifying the basis state to construct.
Returns:
array[complex]: The resulting state after applying CNOT|basis_id>.
"""
# Prepare the basis state |basis_id>
bits = [int(x) for x in np.binary_repr(basis_id, width=dev.num_wires)]
qml.BasisStatePreparation(bits, wires=[0, 1])
##################
# YOUR CODE HERE #
##################
# APPLY THE CNOT
qml.CNOT(wires=[0,1])
return qml.state()
##################
# YOUR CODE HERE #
##################
# REPLACE THE BIT STRINGS VALUES BELOW WITH THE CORRECT ONES
cnot_truth_table = {
"00" : "00",
"01" : "01",
"10" : "11",
"11" : "10"
}
# Run your QNode with various inputs to help fill in your truth table
# for k in cnot_truth_table:
for k in range(4):
print(apply_cnot(k))
dev = qml.device("default.qubit", wires=2)
@qml.qnode(dev)
def apply_h_cnot():
##################
# YOUR CODE HERE #
##################
# APPLY THE OPERATIONS IN THE CIRCUIT
qml.Hadamard(wires=0)
qml.CNOT(wires=[0,1])
return qml.state()
print(apply_h_cnot())
##################
# YOUR CODE HERE #
##################
# SET THIS AS 'separable' OR 'entangled' BASED ON YOUR OUTCOME
state_status = "entangled"
dev = qml.device('default.qubit', wires=3)
@qml.qnode(dev)
def controlled_rotations(theta, phi, omega):
"""Implement the circuit above and return measurement outcome probabilities.
Args:
theta (float): A rotation angle
phi (float): A rotation angle
omega (float): A rotation angle
Returns:
array[float]: Measurement outcome probabilities of the 3-qubit
computational basis states.
"""
qml.Hadamard(wires=0)
qml.CRX(theta, wires=[0,1])
qml.CRY(phi, wires=[1,2])
qml.CRZ(omega, wires=[2,0])
##################
# YOUR CODE HERE #
##################
# APPLY THE OPERATIONS IN THE CIRCUIT AND RETURN MEASUREMENT PROBABILITIES
return qml.probs(wires=[0,1,2])
theta, phi, omega = 0.1, 0.2, 0.3
print(controlled_rotations(theta, phi, omega))
dev = qml.device("default.qubit", wires=2)
# Prepare a two-qubit state; change up the angles if you like
phi, theta, omega = 1.2, 2.3, 3.4
@qml.qnode(device=dev)
def true_cz(phi, theta, omega):
prepare_states(phi, theta, omega)
##################
# YOUR CODE HERE #
##################
# IMPLEMENT THE REGULAR CZ GATE HERE
qml.CZ(wires=[0,1])
return qml.state()
@qml.qnode(dev)
def imposter_cz(phi, theta, omega):
prepare_states(phi, theta, omega)
# qml.Hadamard(wires=0)
qml.Hadamard(wires=1)
qml.CNOT(wires=[0,1])
qml.Hadamard(wires=1)
# qml.Hadamard(wires=0)
##################
# YOUR CODE HERE #
##################
# IMPLEMENT CZ USING ONLY H AND CNOT
return qml.state()
print(f"True CZ output state {true_cz(phi, theta, omega)}")
print(f"Imposter CZ output state {imposter_cz(phi, theta, omega)}")
dev = qml.device("default.qubit", wires=2)
# Prepare a two-qubit state; change up the angles if you like
phi, theta, omega = 1.2, 2.3, 3.4
@qml.qnode(dev)
def apply_swap(phi, theta, omega):
prepare_states(phi, theta, omega)
##################
# YOUR CODE HERE #
##################
# IMPLEMENT THE REGULAR SWAP GATE HERE
qml.SWAP(wires=[0,1])
return qml.state()
@qml.qnode(dev)
def apply_swap_with_cnots(phi, theta, omega):
prepare_states(phi, theta, omega)
##################
# YOUR CODE HERE #
##################
qml.CNOT(wires=[0,1])
qml.CNOT(wires=[1,0])
qml.CNOT(wires=[0,1])
# IMPLEMENT THE SWAP GATE USING A SEQUENCE OF CNOTS
return qml.state()
print(f"Regular SWAP state = {apply_swap(phi, theta, omega)}")
print(f"CNOT SWAP state = {apply_swap_with_cnots(phi, theta, omega)}")
dev = qml.device("default.qubit", wires=3)
# Prepare first qubit in |1>, and arbitrary states on the second two qubits
phi, theta, omega = 1.2, 2.3, 3.4
# A helper function just so you can visualize the initial state
# before the controlled SWAP occurs.
@qml.qnode(dev)
def no_swap(phi, theta, omega):
prepare_states(phi, theta, omega)
return qml.state()
@qml.qnode(dev)
def controlled_swap(phi, theta, omega):
prepare_states(phi, theta, omega)
##################
# YOUR CODE HERE #
##################
# PERFORM A CONTROLLED SWAP USING A SEQUENCE OF TOFFOLIS
qml.Toffoli(wires=[0, 1, 2])
qml.Toffoli(wires=[0, 2, 1])
qml.Toffoli(wires=[0, 1, 2])
# qml.Toffoli(wires=[control1, control2, target])
return qml.state()
print(no_swap(phi, theta, omega))
print(controlled_swap(phi, theta, omega))
|
https://github.com/Jayshah25/Quantum-Algorithms-and-Circuits
|
Jayshah25
|
import numpy as np
zero_state = np.array([[1],[0]])
one_state = np.array([[0],[1]])
print("The |0> is \n", zero_state)
print("The |1> is \n", one_state)
print("The shape of the Vector |0> is",zero_state.shape)
print("The shape of the Vector |1> is",one_state.shape)
#Getting the user input int values for two numbers
num1 = int(input("Enter a value for Number One! \n"))
num2 = int(input("Enter a value for Number Two! \n"))
num1, num2 = num2, num1 #Swapping
print("The value of Number 1 after swapping: ",num1)
print("The value of Number 2 after swapping: ",num2)
#Getting the user input int values for two numbers
num1 = int(input("Enter a value for Number One! \n"))
num2 = int(input("Enter a value for Number Two! \n"))
def cvtb(num):
binnum = [int(i) for i in list('{0:0b}'.format(num))]
return binnum
'{0:0b}'.format(4)
list('{0:0b}'.format(4))
[int(i) for i in list('{0:0b}'.format(4))]
#Calling the method "cvtb" and getting the binary equivalents of num1 and num2
num1_b = cvtb(num1)
num2_b = cvtb(num2)
#Getting the length of each list
num1_l = len(num1_b)
num2_l = len(num2_b)
#Adjusting the length of two lists
if num1_l==num2_l:
pass
elif num1_l < num2_l:
diff = num2_l - num1_l #Getting the difference in the lengths
for ind in range(diff):
num1_b.insert(ind,0)#Adding zeroes to the left
elif num2_l < num1_l:
diff = num1_l - num2_l
for ind in range(diff):
num2_b.insert(ind,0)
print(num1_b)
print(num2_b)
#In this block, we check for the indices with the value 1 in the lists num1_b,
#num2_b, and store the indices in the corresponding list
indices_num1 = []
indices_num2 = []
for i in range(len(num2_b)):
if num1_b[i]==1:
indices_num1.append(i)
if num2_b[i]==1:
indices_num2.append(i)
#In this block, we check for the indices for which the values
#differ in both the lists
indices = []
for i in range(len(num2_b)):
if num1_b[i]!=num2_b[i]:
indices.append(i)
!pip install qiskit #Install qiskit on colab
!pip install pylatexenc #Required for matplotlib support to render the images of circuit
from IPython.display import clear_output #Clear the output after installation
clear_output()
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, Aer, execute
n_qubits = len(num2_b)#Number of required qubits
#equals to the length of num2_b or num1_b list
n_q1 = QuantumRegister(n_qubits,name='num1')
print(n_q1)
n_b1 = ClassicalRegister(n_qubits)
print(n_b1)
qnum1 = QuantumCircuit(n_q1, n_b1) #Initializing the Quantum Circuit
#For every index with a value one, we appply a NOT Gate
#that transforms state |0> to |1>
for i in indices_num1:
qnum1.x(i)
qnum1.barrier() #We will add a barrier for visual discrimination between the initial
#encoding part and the transformation part
qnum1.draw('mpl') #Visualizing the Circuit qnum1
n_q2 = QuantumRegister(n_qubits,name='num2')
n_b2 = ClassicalRegister(n_qubits)
qnum2 = QuantumCircuit(n_q2,n_b2)
for i in indices_num2:
qnum2.x(i)
qnum2.barrier()
qnum2.draw('mpl')
for i in indices:
qnum1.x(i)
qnum2.x(i)
#Using barriers to distinguish transformation part from output extraction
qnum1.barrier()
qnum2.barrier()
qnum1.draw('mpl')
qnum2.draw('mpl')
for i in range(3):
qnum1.measure(i,i)
qnum2.measure(i,i)
qnum1.draw('mpl')
#Using qasm_simulator, we can simulate our circuit on an actual quantum device
simulator = Aer.get_backend('qasm_simulator')
#Get the results for each simulation
result_num1 = execute(qnum1,backend=simulator).result().get_counts()
#Visualizing the results through a histogram
from qiskit.visualization import plot_histogram
plot_histogram(result_num1)
qnum2.draw('mpl')
simulator = Aer.get_backend('qasm_simulator')
result_num2 = execute(qnum2,backend=simulator).result().get_counts()
plot_histogram(result_num2)
|
https://github.com/jonasmaziero/computacao_quantica_qiskit
|
jonasmaziero
|
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
|
from qiskit import ClassicalRegister, QuantumRegister, QuantumCircuit
qr = QuantumRegister(2)
cr = ClassicalRegister(2)
qc = QuantumCircuit(qr, cr)
qc.h(range(2))
qc.measure(range(2), range(2))
# apply x gate if the classical register has the value 2 (10 in binary)
qc.x(0).c_if(cr, 2)
# apply y gate if bit 0 is set to 1
qc.y(1).c_if(0, 1)
qc.draw('mpl')
|
https://github.com/gustavomirapalheta/Quantum-Computing-with-Qiskit
|
gustavomirapalheta
|
def chop(x, tol=1.e-14):
r = np.real(x)
if abs(r)<tol:
r = 0
i = np.imag(x)
if abs(i)<tol:
i = 0
if i == 0:
n = r
elif r == 0:
n = i*1j
else:
n = r + i*1j
return(n)
import numpy as np
a = 1e-16 + 1e-16*1j
b = 1e-16 + 1j
c = 1 + 1e-16*1j
chop(a), chop(b), chop(c)
n = 4
w4 = np.exp(2*np.pi*1j/n)
w4 = chop(w4)
w4
F4 = np.zeros([4,4], dtype=complex)
for i in range(4):
for j in range(4):
F4[i,j] = w4**(i*j)
F4
I2 = np.array([[1,0],[0,1]]); I2
D2_4 = np.zeros([2,2], dtype=complex)
for i in range(2):
D2_4[i,i] = w4**(i)
D2_4
M1 = np.concatenate([I2,D2_4],axis=1)
M2 = np.concatenate([I2,-D2_4],axis=1)
M3 = np.concatenate([M1,M2],axis=0); M3
n = 2
w2 = np.exp(2*np.pi*1j/n)
w2 = chop(w2)
w2
F2 = np.zeros([2,2], dtype=complex)
for i in range(2):
for j in range(2):
F2[i,j] = w2**(i*j)
F2
Z2 = np.zeros([2,2], dtype=complex)
Z2
K1 = np.concatenate([F2,Z2],axis=1)
K2 = np.concatenate([Z2,F2],axis=1)
K3 = np.concatenate([K1,K2],axis=0); K3
P4 = np.array([[1,0,0,0],
[0,0,1,0],
[0,1,0,0],
[0,0,0,1]])
P4
M3.dot(K3).dot(P4)
F4
np.all(F4 == M3.dot(K3).dot(P4))
|
https://github.com/Quantum-Simulation-Group-2/Session-2
|
Quantum-Simulation-Group-2
|
import numpy as np
from qiskit import *
%matplotlib inline
circ = QuantumCircuit(2)
circ.h(0)
circ.x(1)
circ.h(1)
circ.cx(0,1) #oracle here for f(x)=x
circ.h(0)
circ.draw('mpl')
meas = QuantumCircuit(2, 2)
meas.barrier(range(2))
meas.measure(range(2), range(2)) # map the quantum measurement to the classical bits
qc = circ + meas
qc.draw()
# Use Aer's qasm_simulator
backend_sim = Aer.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)
result_sim = job_sim.result()
counts = result_sim.get_counts(qc)
print("Counts for QASM:", counts)
from qiskit.visualization import plot_histogram
plot_histogram(counts)
from qiskit.providers.ibmq import least_busy
provider = IBMQ.load_account()
backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= (3) and
not x.configuration().simulator and x.status().operational==True))
print("least busy backend: ", backend)
from qiskit.tools.monitor import job_monitor
shots = 1024
job = execute(qc, backend=backend, shots=shots, optimization_level=3)
job_monitor(job, interval = 2)
from qiskit.visualization import plot_histogram
results = job.result()
answer = results.get_counts()
print("Counts for IBM machine:", answer)
plot_histogram((counts, answer), legend=['QASM simulation','IBM machine']) # ibm machine
n = 2
grover = QuantumCircuit(n)
grover.h([0,1])
grover.cz(0,1) # Oracle
# Diffusion operator (U_s)
grover.h([0,1])
grover.z([0,1])
grover.cz(0,1)
grover.h([0,1])
grover.draw()
meas = QuantumCircuit(2, 2)
meas.barrier(range(2))
meas.measure(range(2), range(2)) # map the quantum measurement to the classical bits
qc3 = grover + meas
qc3.draw()
#Simulator
from qiskit.visualization import plot_histogram
backend = Aer.get_backend('statevector_simulator')
shots = 1024
results = execute(qc3, backend=backend, shots=shots).result()
counts = results.get_counts()
plot_histogram(counts)
from qiskit.providers.ibmq import least_busy
provider = IBMQ.load_account()
backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= (3) and
not x.configuration().simulator and x.status().operational==True))
print("least busy backend: ", backend)
from qiskit.tools.monitor import job_monitor
shots = 1024
job = execute(qc3, backend=backend, shots=shots, optimization_level=3)
job_monitor(job, interval = 2)
from qiskit.visualization import plot_histogram
results = job.result()
answer = results.get_counts()
print("Counts for IBM machine:", answer)
plot_histogram((counts, answer), legend=['QASM simulation','IBM machine']) # ibm machine
circ2 = QuantumCircuit(3)
for i in range(2):
circ2.h(i)
circ2.x(i)
circ2.h(2)
circ2.x(2)
circ2.h(2)
# Toffoli gate = oracle
circ2.ccx(0,1,2)
for i in range(2):
circ2.h(i)
circ2.x(i)
circ2.h(2)
circ2.x(2)
circ2.h(2)
circ2.draw('mpl')
meas2 = QuantumCircuit(3, 3)
meas2.barrier(range(3))
meas2.measure(range(3), range(3)) # map the quantum measurement to the classical bits
qc2 = circ2 + meas2
qc2.draw()
# Use Aer's qasm_simulator
backend_sim = Aer.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(qc2, backend_sim, shots=1024)
result_sim = job_sim.result()
counts = result_sim.get_counts(qc2)
print("Counts for QASM:", counts)
from qiskit.visualization import plot_histogram
plot_histogram(counts)
from qiskit.providers.ibmq import least_busy
provider = IBMQ.load_account()
backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= (3) and
not x.configuration().simulator and x.status().operational==True))
print("least busy backend: ", backend)
from qiskit.tools.monitor import job_monitor
shots = 1024
job = execute(qc2, backend=backend, shots=shots, optimization_level=3)
job_monitor(job, interval = 2)
from qiskit.visualization import plot_histogram
results = job.result()
answer = results.get_counts()
print("Counts for IBM machine:", answer)
plot_histogram((counts, answer), legend=['QASM simulation','IBM machine']) # ibm machine
# The groover algorithm needs 3 work qubits to execute the algorithm, therefore 8 qubits needed here
circ2 = QuantumCircuit(8)
for i in range(4):
circ2.h(i)
circ2.x(i)
circ2.h(7)
circ2.x(7)
circ2.h(7)
# Toffoli gate = oracle
circ2.ccx(0,1,4)
circ2.ccx(4,2,5)
circ2.ccx(5,3,6)
circ2.cx(6,7)
circ2.ccx(5,3,6)
circ2.ccx(4,2,5)
circ2.ccx(0,1,4)
for i in range(4):
circ2.h(i)
circ2.x(i)
circ2.h(7)
circ2.x(7)
circ2.h(7)
circ2.draw('mpl')
meas2 = QuantumCircuit(8, 8)
meas2.barrier([0,1,2,3,7])
meas2.measure([0,1,2,3,7], [0,1,2,3,7]) # map the quantum measurement to the classical bits
qc2 = circ2 + meas2
qc2.draw()
# Use Aer's qasm_simulator
backend_sim = Aer.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(qc2, backend_sim, shots=1024)
result_sim = job_sim.result()
counts = result_sim.get_counts(qc2)
print("Counts for QASM:", counts)
from qiskit.visualization import plot_histogram
plot_histogram(counts)
from qiskit.providers.ibmq import least_busy
provider = IBMQ.load_account()
backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= (3) and
not x.configuration().simulator and x.status().operational==True))
print("least busy backend: ", backend)
from qiskit.tools.monitor import job_monitor
shots = 1024
job = execute(qc2, backend=backend, shots=shots, optimization_level=3)
job_monitor(job, interval = 2)
|
https://github.com/topgun007-oss/Quantum-gates
|
topgun007-oss
|
from qiskit import *
from qiskit.visualization import plot_bloch_multivector, plot_histogram
from qiskit.tools.monitor import job_monitor
from matplotlib import style
style.use('dark_background')
qc = QuantumCircuit(1,1)
qc.h(0)
qc.measure([0], [0])
qc.draw('mpl')
qasm_simulator = Aer.get_backend('qasm_simulator')
job = execute(qc, qasm_simulator, shots = 1000)
output = job.result()
counts = output.get_counts(qc)
plot_histogram(counts)
qc1 = QuantumCircuit(1,1)
qc1.x(0)
qc1.measure([0], [0])
display(qc1.draw('mpl'))
counts = execute(qc1, qasm_simulator, shots = 10000).result().get_counts(qc1)
plot_histogram(counts)
qc2 = QuantumCircuit(2, 2)
qc2.h(0)
qc2.y(1)
qc2.measure([0,1], [0,1])
display(qc2.draw('mpl'))
counts = execute(qc2, qasm_simulator, shots = 10000).result().get_counts(qc2)
plot_histogram(counts)
from qiskit import *
from qiskit.visualization import plot_bloch_multivector, plot_histogram
from qiskit.tools.monitor import job_monitor
from matplotlib import style
style.use('dark_background')
qc3 = QuantumCircuit(2,2)
qc3.cx(0,1)
qc3.measure([0,1], [0,1])
display(qc3.draw('mpl'))
counts = execute(qc3, qasm_simulator, shots = 10).result().get_counts(qc3)
plot_histogram(counts)
#now applying the X gate first
qc3 = QuantumCircuit(2,2)
qc3.x(0)
qc3.cx(0,1)
qc3.measure([0,1], [0,1])
display(qc3.draw('mpl'))
counts = execute(qc3, qasm_simulator, shots = 10).result().get_counts(qc3)
plot_histogram(counts)
from qiskit import *
from qiskit.visualization import plot_bloch_multivector, plot_histogram
from qiskit.tools.monitor import job_monitor
from matplotlib import style
style.use('dark_background')
qc4 = QuantumCircuit(3,3)
qc4.ccx(0,1,2)
qc4.measure([0,1,2], [0,1,2])
display(qc4.draw('mpl'))
counts = execute(qc4, qasm_simulator, shots = 10).result().get_counts(qc4)
plot_histogram(counts)
import numpy as np
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit import IBMQ, Aer, transpile, assemble
from qiskit.visualization import plot_histogram, plot_bloch_multivector, array_to_latex,plot_bloch_vector
from qiskit.extensions import Initialize
qureg = QuantumRegister(3, 'q')
cr1 = ClassicalRegister(1, name="cr1")
cr2 = ClassicalRegister(1, name="cr2")
circuit = QuantumCircuit(qureg, cr1,cr2)
circuit.draw('mpl')
plot_bloch_multivector([(1/9)**0.5 , (8/9)**0.5])
circuit.initialize([(1/9)**0.5 , (8/9)**0.5],0)
#initializing the bloch vector and making the circuit for teleportation
circuit.h(qureg[1])
circuit.cx(qureg[1], qureg[2])
circuit.barrier(qureg[1], qureg[0], qureg[2])
circuit.cx(qureg[0], qureg[1])
circuit.h(qureg[0])
circuit.barrier(qureg[1], qureg[0], qureg[2])
circuit.measure(qureg[0], cr1)
circuit.measure(qureg[1], cr2)
circuit.draw('mpl')
circuit.x(qureg[2]).c_if(cr1, 1)#applying the condition to get the info from alice to bob
circuit.z(qureg[2]).c_if(cr2, 1)
circuit.draw('mpl')
sim = Aer.get_backend('aer_simulator')
circuit.save_statevector()
out_vector = sim.run(circuit).result().get_statevector()
plot_bloch_multivector(out_vector)
from qiskit import *
from qiskit.tools.visualization import plot_histogram
import numpy as np
from matplotlib import style
circuit = QuantumCircuit()
classicalRegister = ClassicalRegister(4 , name = 'classicalRegister')
data = QuantumRegister(4, name = 'data')
circuit.add_register(data)
circuit.add_register(classicalRegister)
circuit.draw('mpl')
circuit.h(data)
circuit.draw('mpl')
# creating the extra bit or ancilla
ancilla = QuantumRegister(1, name = 'ancilla')
circuit.add_register(ancilla)
circuit.x(ancilla)
circuit.h(ancilla)
circuit.barrier()
circuit.draw('mpl')
#oracle part
def constant_oracle(circuit):
return circuit
def balanced_oracle(circuit):
circuit.cx(data, ancilla)
return circuit
circuit = constant_oracle(circuit)
circuit.barrier()
circuit.draw('mpl')
circuit.h(data)
circuit.measure(data, classicalRegister)
sim = Aer.get_backend('qasm_simulator')
result = execute(circuit, sim, shots = 1).result()
plot_histogram(result.get_counts(circuit))
from qiskit import QuantumCircuit
from qiskit import IBMQ, Aer, transpile, assemble
from qiskit.visualization import plot_histogram
from matplotlib import style
style.use('dark_background')
def bell_pair(qC, a, b):
qC.h(a)
qC.cx(a,b)
def encoded_message(qC, qubit, msg):
if msg == "00":
pass
elif msg == "10":
qC.x(qubit)
elif msg == "01":
qC.z(qubit)
elif msg == "11":
qC.z(qubit)
qC.x(qubit)
else:
print("ERROR: Sending '00'")
def decoded_message(qC, a, b):
qC.cx(a,b)
qC.h(a)
qC = QuantumCircuit(2)
bell_pair(qC, 0, 1)
qC.barrier()
message = "00"
encoded_message(qC, 0, message)
qC.barrier()
decoded_message(qC, 0, 1)
qC.measure_all()
qC.draw('mpl')
aer_sim = Aer.get_backend('aer_simulator')
job = assemble(qC)
result = aer_sim.run(job).result()
counts = result.get_counts(qC)
print(counts)
plot_histogram(counts)
|
https://github.com/abbarreto/qiskit3
|
abbarreto
| |
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
from qiskit.quantum_info import Clifford, random_clifford
qc = QuantumCircuit(3)
cliff = random_clifford(2)
qc.append(cliff, [0, 1])
qc.ccx(0, 1, 2)
qc.draw('mpl')
|
https://github.com/daimurat/qiskit-implementation
|
daimurat
|
from qiskit import *
from qiskit.visualization import plot_histogram
import numpy as np
IBMQ.load_account()
IBMQ.providers()
provider = IBMQ.get_provider('ibm-q')
provider.backends()
import qiskit.tools.jupyter
backend_ex = provider.get_backend('ibmq_16_melbourne')
backend_ex
backends = provider.backends(filters =
lambda x:x.configuration().n_qubits >= 2
and not x.configuration().simulator
and x.status().operational==True
)
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
))
backends
backend = provider.get_backend('ibmqx2')
qc_and = QuantumCircuit(3)
qc_and.ccx(0,1,2)
qc_and.draw()
qc_and.decompose().draw()
from qiskit.tools.monitor import job_monitor
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 = execute(qc_trans, backend, shots=8192)
print(job.job_id())
job_monitor(job)
output = job.result().get_counts()
return qc_trans, output
qc_trans, output = AND('0', '0', backend, [0, 2, 4])
qc_trans
output
from qiskit.visualization import plot_gate_map, plot_error_map
plot_gate_map(backend)
plot_error_map(backend)
|
https://github.com/OldGinko/Qiskit-CKS-Algorithm
|
OldGinko
|
"""
THIS VERSION DOES NOT NEED TO TURN U INTO A MATRIX TO EXPONENT IT,
WE USE THE QISKIT LANGUAGE FOR IT. WE ALSO USE QISKIT TO CREATE cU
AUTOMATICALLY INSTEWAD BY HAND AS IT IS BADLY IN IPE_BOX
This is the same IPE as in "IPE with HamiltonSiumlation" instead of applying
U 2^k times we apply U^(2k) once the k-th itartation step.
@author: ugsga
What to fix: Use GPE instead of IPE to reduce number of gates and
increase Nr of qubits
"""
from qiskit import *
import numpy as np
from qiskit.visualization import plot_histogram
import qiskit.tools.jupyter
import matplotlib.pyplot as plt
from qiskit.aqua.algorithms import IQPE
from scipy.linalg import expm, sinm, cosm #for the bridge Hamiltonian simulation
from qiskit.extensions import *
from qiskit.quantum_info.operators import Operator
# A = np.array([[1/2+0.j,-1/3],[-1/3,1/2]])
# A =A/np.linalg.norm(A) #Norm the matrix as stated in Problem 1 CKS
def IPE_box(A,m,hist=False, draw=False):
"""
Iterative Phase Estiamtion for 2x2 Hermitian Matrix
Input:
A: hermitian matrix
m: m- bit desired resbpresentation of output
hist: return histogram, default == False
draw: return circuit plot, defualt == False
Output:
Tuple:
(EW, IPE.png, hist.png)
"""
U_list_temp = [0]*m
U_list = []
# control = np.array([[1.+0.j,0,0,0],[0,1,0,0],[0,0,0,0],[0,0,0,0]])
x = np.arange(0,m,1) #save output of classical register here
U = qiskit.extensions.HamiltonianGate(A, -1,"Hsim") #generate unitary in H-Gate class
#-1 to get same as expm(A*1j)
for k in range(0,m):
U_list_temp[k]=U.power(2**k)
# control[2:,2:] = U_list_temp[k]
# U_list.append(control.copy())
eigenvec = np.linalg.eig(A)
dim_b = int(np.log2(len(eigenvec[1][1])))
sim = Aer.get_backend('qasm_simulator')
q = QuantumRegister(1) #build q-register
b = QuantumRegister(dim_b) #register for |b>
c = ClassicalRegister(m) #build classical-register
circuit = QuantumCircuit(q,b,c) #build curicuit from register "q"
initial_state = eigenvec[1][1] # Define initial_state, last index is cahngeable to 1/0
# print(initial_state)
circuit.initialize(initial_state, b)
cU = [0]*m
for i in range(0,m):
cU[i] = U_list_temp[i].control() #generate controlled operator U
for i in range(1,m+1):
repetitions = 2**(m-i)
circuit.h([0])
circuit.append(cU[m-i],list(range(0,dim_b+1))) #apply cU
if i == 1:
pass
else:
circuit.rz(-2*np.pi*x[i-2]/2**(m-i-1),q[0])
circuit.h(0)
circuit.measure(q[0],c[i-1])
job = execute(circuit, sim, shots=1, memory=True)
x[m-i] = int(job.result().get_memory()[0][m-i])
circuit.reset(q[0])
if draw == True:
circuit.draw(filename="IPE.png", output="mpl")
else:
pass
n=m
count0 = execute(circuit, sim,shots=4096).result().get_counts()
key_new = [str(int(key,2)/2**n) for key in list(count0.keys())]
count1 = dict(zip(key_new, count0.values()))
if hist == True:
fig, ax = plt.subplots(1,2)
plot_histogram(count0, ax=ax[0])
plot_histogram(count1, ax=ax[1])
fig.savefig("hist.png")
plt.tight_layout()
plt.close()
else:
pass
#get maximum of plot
maxim = count0.most_frequent() #Return the most frequent count
maxim_dec = int(maxim,2)/2**n # Convert a binary string to a decimal int.
EW = np.exp(maxim_dec*2*np.pi*1j) #get eigenvalues in mixed for(re and im are mixed)
EW1 = EW.real
EW2 = EW.imag
print("EW1=",EW1, "EW2=",EW2)
return [EW,"IPE.png","hist.png"]
# B = np.array([[1+0.j,2,3,4],[2,1,2,3],[3,2,4,1],[4,3,1,2]])
# B = B/np.linalg.norm(B)
# print(IPE_box(B,6,draw=True,hist=True))
# print(np.matmul(B,B.transpose()))
# print("EW by numpy:",np.linalg.eig(B)[0])
|
https://github.com/davidedellagiustina/qasp-solver
|
davidedellagiustina
|
'''Amplitude estimation algorithms.
'''
import copy
import math
from typing import Callable
import intervals as interval
from intervals import Interval
from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister
from qiskit.circuit.library import GroverOperator, QFT
from ..oracle import Oracle, QuantumOracle
from ..simul import exec_circuit
# +--------------------+
# | Estimation circuit |
# +--------------------+
def circuit(
algorithm: QuantumCircuit,
oracle: QuantumOracle,
m: int,
eps: float,
aux_qubits: list[int] = None
) -> QuantumCircuit:
'''Build a quantum circuit implementing the amplitude estimation algorithm.
#### Arguments
algorithm (QuantumCircuit): Ciruit that implements the initialization algorithm.
oracle (QuantumOracle): Citcuit that implements the oracle.
m (int): Desired number of binary digits to be estimated.
eps (float): Complement of the desired success probability.
aux_qubits (list[int]): List of indices of auxiliary qubits (e.g. used by the oracle) \
that should not be used for the search procedure. Defaults to the empty list.
#### Return
QuantumCircuit: Built circuit.
'''
# pylint: disable=too-many-locals
aux_qubits = [] if aux_qubits is None else aux_qubits
assert m > 0 and eps > 0
assert algorithm.num_qubits == oracle.num_qubits
n = algorithm.num_qubits + 1 # Also counting `aug` qubit
t = m + math.ceil(math.log2(2 + 1/(2*eps)))
# Add `aug` qubit to algorithm
algorithm.name = 'AlgorithmAug'
aug = QuantumRegister(1, 'aug')
algorithm.add_register(aug)
algorithm.h(aug) # Equiprobable superposition
assert algorithm.num_qubits == n
# Add `aug` qubit to oracle
c_oracle = oracle.control()
c_oracle.name = 'OracleAug'
oracle.data = []
aug = QuantumRegister(1, 'aug')
oracle.add_register(aug)
oracle.compose(
c_oracle,
[n-1] + list(range(n-1)),
inplace=True,
)
assert oracle.num_qubits == n
# Circuit structure
qr0 = QuantumRegister(t)
qr_others = list( # Clone qubit labels from oracle
dict.fromkeys( # Remove duplicates while maintaining order
map(lambda q: oracle.find_bit(q).registers[0][0], oracle.qubits)
)
)
circ = QuantumCircuit(qr0, *qr_others)
circ.name = 'Est'
# Qubit partitioning
qubits_search = list(filter(
lambda x: not x in aux_qubits,
list(range(n))
))
# Initialization
circ.h(qr0)
circ.append(algorithm, qr_others)
# Iterations
pow_g = GroverOperator(
oracle, state_preparation=algorithm, reflection_qubits=qubits_search)
pow_g.name = 'Q^(2^0)'
for idx in range(t):
c_pow_g = copy.deepcopy(pow_g).control()
circ.compose(c_pow_g, [t-idx-1] + list(range(t, t+n)), inplace=True)
# Next power of G
pow_g.compose(pow_g, pow_g.qubits, inplace=True)
pow_g.name = f'Q^(2^{idx+1})'
# Inverse QFT
# NOTE: Qiskit's QFT has the opposite bit order w.r.t. the one used in the thesis, hence why \
# we disable the swaps.
iqft = QFT(t, inverse=True, do_swaps=False)
circ.append(iqft, qr0)
# Measurements
result = ClassicalRegister(m, name='result')
circ.add_register(result)
circ.measure(list(range(t-m, t)), result) # Only requested m bits
return circ
# +-----------------------+
# | Algoroithm simulation |
# +-----------------------+
def __phase_to_count(n: int, phase: float) -> float:
'''Compute the number M of solutions of a search problem given an estimate of the rotation \
angle phi of the respective Grover Operator.
#### Arguments
N (int): Number of search qubits.
phase (float): Estimate value of the phase phi.
#### Return
float: Estimated value of M.
'''
return 2**n * math.sin(phase/2)**2
def __measure_to_count(
measurements: str,
num_search_qubits: int,
count_fn: Callable[[float], float] = None
) -> tuple[Interval, Interval]:
'''Convert the result of a measurement to estimation intervals for the respective phase and \
for the solutions count.
#### Arguments
measurements (str): Measured bits.
num_search_qubits (int): Number of search qubits.
count_fn (Callable[[float], float]): Function that, given an estimate for phi, computes \
the solutions count (or any other needed value). Defaults to N * sin^2(theta/2).
#### Return
tuple[Interval, Interval]: Estimation intervals for the measured phase and the solutions \
count, respectively.
'''
count_fn = (
lambda phase: __phase_to_count(num_search_qubits, phase)
) if count_fn is None else count_fn
m = len(measurements)
phi = 0.0
for (idx, bit) in zip(range(m), measurements):
phi += int(bit) * 2**(-idx-1)
phases = [2 * math.pi * (phi + delta) for delta in [0, 2**(-m)]]
if phi <= 1/2: # If theta was measured
interval_type = interval.closedopen
else: # If (2 pi - theta) was measured
interval_type = interval.openclosed
phases = [2 * math.pi - phase for phase in reversed(phases)]
phase_estimate = interval_type(phases[0], phases[1])
counts = [count_fn(phase) for phase in phases]
count_estimate = interval_type(counts[0], counts[1])
return (phase_estimate, count_estimate)
def exec_count(
algorithm: QuantumCircuit,
oracle: Oracle,
m: int,
eps: float,
aux_qubits: list[int] = None,
count_fn: Callable[[float], float] = None
) -> tuple[QuantumCircuit, Interval, Interval]:
'''Simulate the amplitude estimation circuit to approximate the number of solutions of the \
problem.
#### Arguments
algorithm (QuantumCircuit): Ciruit that implements the initialization algorithm.
oracle (Oracle): Pair of classical and quantum oracles.
m (int): Desired number of binary digits to be estimated.
eps (float): Complement of the desired success probability.
aux_qubits (list[int]): List of indices of auxiliary qubits (e.g. used by the oracle) \
that should not be used for the search procedure. Defaults to the empty list.
count_fn (Callable[[float], float]): Function that, given an estimate for phi, computes \
the solutions count (or any other needed value). Defaults to N * sin^2(theta/2).
#### Return
tuple[QuantumCircuit, Interval, Interval]: Used circuit, estimation interval for the \
measured phase, and estimation interval for the solutions count.
'''
# pylint: disable=too-many-arguments
aux_qubits = [] if aux_qubits is None else aux_qubits
(_, q_oracle) = oracle # Classical oracle is unused
n = len(q_oracle.qubits) - len(aux_qubits) + 1 # Account for `aug`
# Build circuit
circ = circuit(algorithm, q_oracle, m, eps, aux_qubits)
# Run simulation and compute results
result = exec_circuit(circ, shots=1)
measurements = list(result.get_counts().keys())[0]
(phase, count) = __measure_to_count(measurements, n, count_fn)
return (circ, phase, count)
|
https://github.com/swe-train/qiskit__qiskit
|
swe-train
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test Qiskit's controlled gate operation."""
import unittest
from test import combine
import numpy as np
from numpy import pi
from ddt import ddt, data, unpack
from qiskit import QuantumRegister, QuantumCircuit, execute, BasicAer, QiskitError
from qiskit.test import QiskitTestCase
from qiskit.circuit import ControlledGate, Parameter, Gate
from qiskit.circuit.exceptions import CircuitError
from qiskit.quantum_info.operators.predicates import matrix_equal, is_unitary_matrix
from qiskit.quantum_info.random import random_unitary
from qiskit.quantum_info.states import Statevector
import qiskit.circuit.add_control as ac
from qiskit.transpiler.passes import Unroller
from qiskit.converters.circuit_to_dag import circuit_to_dag
from qiskit.converters.dag_to_circuit import dag_to_circuit
from qiskit.quantum_info import Operator
from qiskit.circuit.library import (
CXGate,
XGate,
YGate,
ZGate,
U1Gate,
CYGate,
CZGate,
CU1Gate,
SwapGate,
PhaseGate,
CCXGate,
HGate,
RZGate,
RXGate,
CPhaseGate,
RYGate,
CRYGate,
CRXGate,
CSwapGate,
UGate,
U3Gate,
CHGate,
CRZGate,
CU3Gate,
CUGate,
SXGate,
CSXGate,
MSGate,
Barrier,
RCCXGate,
RC3XGate,
MCU1Gate,
MCXGate,
MCXGrayCode,
MCXRecursive,
MCXVChain,
C3XGate,
C3SXGate,
C4XGate,
MCPhaseGate,
GlobalPhaseGate,
)
from qiskit.circuit._utils import _compute_control_matrix
import qiskit.circuit.library.standard_gates as allGates
from qiskit.extensions import UnitaryGate
from qiskit.circuit.library.standard_gates.multi_control_rotation_gates import _mcsu2_real_diagonal
from .gate_utils import _get_free_params
@ddt
class TestControlledGate(QiskitTestCase):
"""Tests for controlled gates and the ControlledGate class."""
def test_controlled_x(self):
"""Test creation of controlled x gate"""
self.assertEqual(XGate().control(), CXGate())
def test_controlled_y(self):
"""Test creation of controlled y gate"""
self.assertEqual(YGate().control(), CYGate())
def test_controlled_z(self):
"""Test creation of controlled z gate"""
self.assertEqual(ZGate().control(), CZGate())
def test_controlled_h(self):
"""Test the creation of a controlled H gate."""
self.assertEqual(HGate().control(), CHGate())
def test_controlled_phase(self):
"""Test the creation of a controlled U1 gate."""
theta = 0.5
self.assertEqual(PhaseGate(theta).control(), CPhaseGate(theta))
def test_double_controlled_phase(self):
"""Test the creation of a controlled phase gate."""
theta = 0.5
self.assertEqual(PhaseGate(theta).control(2), MCPhaseGate(theta, 2))
def test_controlled_u1(self):
"""Test the creation of a controlled U1 gate."""
theta = 0.5
self.assertEqual(U1Gate(theta).control(), CU1Gate(theta))
circ = QuantumCircuit(1)
circ.append(U1Gate(theta), circ.qregs[0])
unroller = Unroller(["cx", "u", "p"])
ctrl_circ_gate = dag_to_circuit(unroller.run(circuit_to_dag(circ))).control()
ctrl_circ = QuantumCircuit(2)
ctrl_circ.append(ctrl_circ_gate, ctrl_circ.qregs[0])
ctrl_circ = ctrl_circ.decompose().decompose()
self.assertEqual(ctrl_circ.size(), 1)
def test_controlled_rz(self):
"""Test the creation of a controlled RZ gate."""
theta = 0.5
self.assertEqual(RZGate(theta).control(), CRZGate(theta))
def test_control_parameters(self):
"""Test different ctrl_state formats for control function."""
theta = 0.5
self.assertEqual(
CRYGate(theta).control(2, ctrl_state="01"), CRYGate(theta).control(2, ctrl_state=1)
)
self.assertEqual(
CRYGate(theta).control(2, ctrl_state=None), CRYGate(theta).control(2, ctrl_state=3)
)
self.assertEqual(CCXGate().control(2, ctrl_state="01"), CCXGate().control(2, ctrl_state=1))
self.assertEqual(CCXGate().control(2, ctrl_state=None), CCXGate().control(2, ctrl_state=3))
def test_controlled_ry(self):
"""Test the creation of a controlled RY gate."""
theta = 0.5
self.assertEqual(RYGate(theta).control(), CRYGate(theta))
def test_controlled_rx(self):
"""Test the creation of a controlled RX gate."""
theta = 0.5
self.assertEqual(RXGate(theta).control(), CRXGate(theta))
def test_controlled_u(self):
"""Test the creation of a controlled U gate."""
theta, phi, lamb = 0.1, 0.2, 0.3
self.assertEqual(UGate(theta, phi, lamb).control(), CUGate(theta, phi, lamb, 0))
def test_controlled_u3(self):
"""Test the creation of a controlled U3 gate."""
theta, phi, lamb = 0.1, 0.2, 0.3
self.assertEqual(U3Gate(theta, phi, lamb).control(), CU3Gate(theta, phi, lamb))
circ = QuantumCircuit(1)
circ.append(U3Gate(theta, phi, lamb), circ.qregs[0])
unroller = Unroller(["cx", "u", "p"])
ctrl_circ_gate = dag_to_circuit(unroller.run(circuit_to_dag(circ))).control()
ctrl_circ = QuantumCircuit(2)
ctrl_circ.append(ctrl_circ_gate, ctrl_circ.qregs[0])
ctrl_circ = ctrl_circ.decompose().decompose()
self.assertEqual(ctrl_circ.size(), 1)
def test_controlled_cx(self):
"""Test creation of controlled cx gate"""
self.assertEqual(CXGate().control(), CCXGate())
def test_controlled_swap(self):
"""Test creation of controlled swap gate"""
self.assertEqual(SwapGate().control(), CSwapGate())
def test_special_cases_equivalent_to_controlled_base_gate(self):
"""Test that ``ControlledGate`` subclasses for more efficient representations give
equivalent matrices and definitions to the naive ``base_gate.control(n)``."""
# Angles used here are not important, we just pick slightly strange values to ensure that
# there are no coincidental equivalences.
tests = [
(CXGate(), 1),
(CCXGate(), 2),
(C3XGate(), 3),
(C4XGate(), 4),
(MCXGate(5), 5),
(CYGate(), 1),
(CZGate(), 1),
(CPhaseGate(np.pi / 7), 1),
(MCPhaseGate(np.pi / 7, 2), 2),
(CSwapGate(), 1),
(CSXGate(), 1),
(C3SXGate(), 3),
(CHGate(), 1),
(CU1Gate(np.pi / 7), 1),
(MCU1Gate(np.pi / 7, 2), 2),
# `CUGate` takes an extra "global" phase parameter compared to `UGate`, and consequently
# is only equal to `base_gate.control()` when this extra phase is 0.
(CUGate(np.pi / 7, np.pi / 5, np.pi / 3, 0), 1),
(CU3Gate(np.pi / 7, np.pi / 5, np.pi / 3), 1),
(CRXGate(np.pi / 7), 1),
(CRYGate(np.pi / 7), 1),
(CRZGate(np.pi / 7), 1),
]
for special_case_gate, n_controls in tests:
with self.subTest(gate=special_case_gate.name):
naive_operator = Operator(special_case_gate.base_gate.control(n_controls))
# Ensure that both the array form (if the gate overrides `__array__`) and the
# circuit-definition form are tested.
self.assertTrue(Operator(special_case_gate).equiv(naive_operator))
if not isinstance(special_case_gate, CXGate):
# CX is treated like a primitive within Terra, and doesn't have a definition.
self.assertTrue(Operator(special_case_gate.definition).equiv(naive_operator))
def test_global_phase_control(self):
"""Test creation of a GlobalPhaseGate."""
base = GlobalPhaseGate(np.pi / 7)
expected_1q = PhaseGate(np.pi / 7)
self.assertEqual(Operator(base.control()), Operator(expected_1q))
expected_2q = PhaseGate(np.pi / 7).control()
self.assertEqual(Operator(base.control(2)), Operator(expected_2q))
expected_open = QuantumCircuit(1)
expected_open.x(0)
expected_open.p(np.pi / 7, 0)
expected_open.x(0)
self.assertEqual(Operator(base.control(ctrl_state=0)), Operator(expected_open))
def test_circuit_append(self):
"""Test appending a controlled gate to a quantum circuit."""
circ = QuantumCircuit(5)
inst = CXGate()
circ.append(inst.control(), qargs=[0, 2, 1])
circ.append(inst.control(2), qargs=[0, 3, 1, 2])
circ.append(inst.control().control(), qargs=[0, 3, 1, 2]) # should be same as above
self.assertEqual(circ[1].operation, circ[2].operation)
self.assertEqual(circ.depth(), 3)
self.assertEqual(circ[0].operation.num_ctrl_qubits, 2)
self.assertEqual(circ[1].operation.num_ctrl_qubits, 3)
self.assertEqual(circ[2].operation.num_ctrl_qubits, 3)
self.assertEqual(circ[0].operation.num_qubits, 3)
self.assertEqual(circ[1].operation.num_qubits, 4)
self.assertEqual(circ[2].operation.num_qubits, 4)
for instr in circ:
self.assertTrue(isinstance(instr.operation, ControlledGate))
def test_swap_definition_specification(self):
"""Test the instantiation of a controlled swap gate with explicit definition."""
swap = SwapGate()
cswap = ControlledGate(
"cswap", 3, [], num_ctrl_qubits=1, definition=swap.definition, base_gate=swap
)
self.assertEqual(swap.definition, cswap.definition)
def test_multi_controlled_composite_gate(self):
"""Test a multi controlled composite gate."""
num_ctrl = 3
# create composite gate
sub_q = QuantumRegister(2)
cgate = QuantumCircuit(sub_q, name="cgate")
cgate.h(sub_q[0])
cgate.crz(pi / 2, sub_q[0], sub_q[1])
cgate.swap(sub_q[0], sub_q[1])
cgate.u(0.1, 0.2, 0.3, sub_q[1])
cgate.t(sub_q[0])
num_target = cgate.width()
gate = cgate.to_gate()
cont_gate = gate.control(num_ctrl_qubits=num_ctrl)
control = QuantumRegister(num_ctrl)
target = QuantumRegister(num_target)
qc = QuantumCircuit(control, target)
qc.append(cont_gate, control[:] + target[:])
op_mat = Operator(cgate).data
cop_mat = _compute_control_matrix(op_mat, num_ctrl)
ref_mat = Operator(qc).data
self.assertTrue(matrix_equal(cop_mat, ref_mat))
def test_single_controlled_composite_gate(self):
"""Test a singly controlled composite gate."""
num_ctrl = 1
# create composite gate
sub_q = QuantumRegister(2)
cgate = QuantumCircuit(sub_q, name="cgate")
cgate.h(sub_q[0])
cgate.cx(sub_q[0], sub_q[1])
num_target = cgate.width()
gate = cgate.to_gate()
cont_gate = gate.control(num_ctrl_qubits=num_ctrl)
control = QuantumRegister(num_ctrl, "control")
target = QuantumRegister(num_target, "target")
qc = QuantumCircuit(control, target)
qc.append(cont_gate, control[:] + target[:])
op_mat = Operator(cgate).data
cop_mat = _compute_control_matrix(op_mat, num_ctrl)
ref_mat = Operator(qc).data
self.assertTrue(matrix_equal(cop_mat, ref_mat))
def test_control_open_controlled_gate(self):
"""Test control(2) vs control.control where inner gate has open controls."""
gate1pre = ZGate().control(1, ctrl_state=0)
gate1 = gate1pre.control(1, ctrl_state=1)
gate2 = ZGate().control(2, ctrl_state=1)
expected = Operator(_compute_control_matrix(ZGate().to_matrix(), 2, ctrl_state=1))
self.assertEqual(expected, Operator(gate1))
self.assertEqual(expected, Operator(gate2))
def test_multi_control_z(self):
"""Test a multi controlled Z gate."""
qc = QuantumCircuit(1)
qc.z(0)
ctr_gate = qc.to_gate().control(2)
ctr_circ = QuantumCircuit(3)
ctr_circ.append(ctr_gate, range(3))
ref_circ = QuantumCircuit(3)
ref_circ.h(2)
ref_circ.ccx(0, 1, 2)
ref_circ.h(2)
self.assertEqual(ctr_circ.decompose(), ref_circ)
def test_multi_control_u3(self):
"""Test the matrix representation of the controlled and controlled-controlled U3 gate."""
from qiskit.circuit.library.standard_gates import u3
num_ctrl = 3
# U3 gate params
alpha, beta, gamma = 0.2, 0.3, 0.4
u3gate = u3.U3Gate(alpha, beta, gamma)
cu3gate = u3.CU3Gate(alpha, beta, gamma)
# cnu3 gate
cnu3 = u3gate.control(num_ctrl)
width = cnu3.num_qubits
qr = QuantumRegister(width)
qcnu3 = QuantumCircuit(qr)
qcnu3.append(cnu3, qr, [])
# U3 gate
qu3 = QuantumCircuit(1)
qu3.append(u3gate, [0])
# CU3 gate
qcu3 = QuantumCircuit(2)
qcu3.append(cu3gate, [0, 1])
# c-cu3 gate
width = 3
qr = QuantumRegister(width)
qc_cu3 = QuantumCircuit(qr)
c_cu3 = cu3gate.control(1)
qc_cu3.append(c_cu3, qr, [])
# Circuit unitaries
mat_cnu3 = Operator(qcnu3).data
mat_u3 = Operator(qu3).data
mat_cu3 = Operator(qcu3).data
mat_c_cu3 = Operator(qc_cu3).data
# Target Controlled-U3 unitary
target_cnu3 = _compute_control_matrix(mat_u3, num_ctrl)
target_cu3 = np.kron(mat_u3, np.diag([0, 1])) + np.kron(np.eye(2), np.diag([1, 0]))
target_c_cu3 = np.kron(mat_cu3, np.diag([0, 1])) + np.kron(np.eye(4), np.diag([1, 0]))
tests = [
("check unitary of u3.control against tensored unitary of u3", target_cu3, mat_cu3),
(
"check unitary of cu3.control against tensored unitary of cu3",
target_c_cu3,
mat_c_cu3,
),
("check unitary of cnu3 against tensored unitary of u3", target_cnu3, mat_cnu3),
]
for itest in tests:
info, target, decomp = itest[0], itest[1], itest[2]
with self.subTest(i=info):
self.assertTrue(matrix_equal(target, decomp, atol=1e-8, rtol=1e-5))
def test_multi_control_u1(self):
"""Test the matrix representation of the controlled and controlled-controlled U1 gate."""
from qiskit.circuit.library.standard_gates import u1
num_ctrl = 3
# U1 gate params
theta = 0.2
u1gate = u1.U1Gate(theta)
cu1gate = u1.CU1Gate(theta)
# cnu1 gate
cnu1 = u1gate.control(num_ctrl)
width = cnu1.num_qubits
qr = QuantumRegister(width)
qcnu1 = QuantumCircuit(qr)
qcnu1.append(cnu1, qr, [])
# U1 gate
qu1 = QuantumCircuit(1)
qu1.append(u1gate, [0])
# CU1 gate
qcu1 = QuantumCircuit(2)
qcu1.append(cu1gate, [0, 1])
# c-cu1 gate
width = 3
qr = QuantumRegister(width)
qc_cu1 = QuantumCircuit(qr)
c_cu1 = cu1gate.control(1)
qc_cu1.append(c_cu1, qr, [])
job = execute(
[qcnu1, qu1, qcu1, qc_cu1],
BasicAer.get_backend("unitary_simulator"),
basis_gates=["u1", "u2", "u3", "id", "cx"],
)
result = job.result()
# Circuit unitaries
mat_cnu1 = result.get_unitary(0)
# trace out ancillae
mat_u1 = result.get_unitary(1)
mat_cu1 = result.get_unitary(2)
mat_c_cu1 = result.get_unitary(3)
# Target Controlled-U1 unitary
target_cnu1 = _compute_control_matrix(mat_u1, num_ctrl)
target_cu1 = np.kron(mat_u1, np.diag([0, 1])) + np.kron(np.eye(2), np.diag([1, 0]))
target_c_cu1 = np.kron(mat_cu1, np.diag([0, 1])) + np.kron(np.eye(4), np.diag([1, 0]))
tests = [
("check unitary of u1.control against tensored unitary of u1", target_cu1, mat_cu1),
(
"check unitary of cu1.control against tensored unitary of cu1",
target_c_cu1,
mat_c_cu1,
),
("check unitary of cnu1 against tensored unitary of u1", target_cnu1, mat_cnu1),
]
for itest in tests:
info, target, decomp = itest[0], itest[1], itest[2]
with self.subTest(i=info):
self.log.info(info)
self.assertTrue(matrix_equal(target, decomp))
@data(1, 2, 3, 4)
def test_multi_controlled_u1_matrix(self, num_controls):
"""Test the matrix representation of the multi-controlled CU1 gate.
Based on the test moved here from Aqua:
https://github.com/Qiskit/qiskit-aqua/blob/769ca8f/test/aqua/test_mcu1.py
"""
# registers for the circuit
q_controls = QuantumRegister(num_controls)
q_target = QuantumRegister(1)
# iterate over all possible combinations of control qubits
for ctrl_state in range(2**num_controls):
bitstr = bin(ctrl_state)[2:].zfill(num_controls)[::-1]
lam = 0.3165354 * pi
qc = QuantumCircuit(q_controls, q_target)
for idx, bit in enumerate(bitstr):
if bit == "0":
qc.x(q_controls[idx])
qc.mcp(lam, q_controls, q_target[0])
# for idx in subset:
for idx, bit in enumerate(bitstr):
if bit == "0":
qc.x(q_controls[idx])
backend = BasicAer.get_backend("unitary_simulator")
simulated = execute(qc, backend).result().get_unitary(qc)
base = PhaseGate(lam).to_matrix()
expected = _compute_control_matrix(base, num_controls, ctrl_state=ctrl_state)
with self.subTest(msg=f"control state = {ctrl_state}"):
self.assertTrue(matrix_equal(simulated, expected))
@data(1, 2, 3, 4)
def test_multi_control_toffoli_matrix_clean_ancillas(self, num_controls):
"""Test the multi-control Toffoli gate with clean ancillas.
Based on the test moved here from Aqua:
https://github.com/Qiskit/qiskit-aqua/blob/769ca8f/test/aqua/test_mct.py
"""
# set up circuit
q_controls = QuantumRegister(num_controls)
q_target = QuantumRegister(1)
qc = QuantumCircuit(q_controls, q_target)
if num_controls > 2:
num_ancillas = num_controls - 2
q_ancillas = QuantumRegister(num_controls)
qc.add_register(q_ancillas)
else:
num_ancillas = 0
q_ancillas = None
# apply hadamard on control qubits and toffoli gate
qc.mct(q_controls, q_target[0], q_ancillas, mode="basic")
# execute the circuit and obtain statevector result
backend = BasicAer.get_backend("unitary_simulator")
simulated = execute(qc, backend).result().get_unitary(qc)
# compare to expectation
if num_ancillas > 0:
simulated = simulated[: 2 ** (num_controls + 1), : 2 ** (num_controls + 1)]
base = XGate().to_matrix()
expected = _compute_control_matrix(base, num_controls)
self.assertTrue(matrix_equal(simulated, expected))
@data(1, 2, 3, 4, 5)
def test_multi_control_toffoli_matrix_basic_dirty_ancillas(self, num_controls):
"""Test the multi-control Toffoli gate with dirty ancillas (basic-dirty-ancilla).
Based on the test moved here from Aqua:
https://github.com/Qiskit/qiskit-aqua/blob/769ca8f/test/aqua/test_mct.py
"""
q_controls = QuantumRegister(num_controls)
q_target = QuantumRegister(1)
qc = QuantumCircuit(q_controls, q_target)
q_ancillas = None
if num_controls <= 2:
num_ancillas = 0
else:
num_ancillas = num_controls - 2
q_ancillas = QuantumRegister(num_ancillas)
qc.add_register(q_ancillas)
qc.mct(q_controls, q_target[0], q_ancillas, mode="basic-dirty-ancilla")
simulated = execute(qc, BasicAer.get_backend("unitary_simulator")).result().get_unitary(qc)
if num_ancillas > 0:
simulated = simulated[: 2 ** (num_controls + 1), : 2 ** (num_controls + 1)]
base = XGate().to_matrix()
expected = _compute_control_matrix(base, num_controls)
self.assertTrue(matrix_equal(simulated, expected, atol=1e-8))
@data(1, 2, 3, 4, 5)
def test_multi_control_toffoli_matrix_advanced_dirty_ancillas(self, num_controls):
"""Test the multi-control Toffoli gate with dirty ancillas (advanced).
Based on the test moved here from Aqua:
https://github.com/Qiskit/qiskit-aqua/blob/769ca8f/test/aqua/test_mct.py
"""
q_controls = QuantumRegister(num_controls)
q_target = QuantumRegister(1)
qc = QuantumCircuit(q_controls, q_target)
q_ancillas = None
if num_controls <= 4:
num_ancillas = 0
else:
num_ancillas = 1
q_ancillas = QuantumRegister(num_ancillas)
qc.add_register(q_ancillas)
qc.mct(q_controls, q_target[0], q_ancillas, mode="advanced")
simulated = execute(qc, BasicAer.get_backend("unitary_simulator")).result().get_unitary(qc)
if num_ancillas > 0:
simulated = simulated[: 2 ** (num_controls + 1), : 2 ** (num_controls + 1)]
base = XGate().to_matrix()
expected = _compute_control_matrix(base, num_controls)
self.assertTrue(matrix_equal(simulated, expected, atol=1e-8))
@data(1, 2, 3)
def test_multi_control_toffoli_matrix_noancilla_dirty_ancillas(self, num_controls):
"""Test the multi-control Toffoli gate with dirty ancillas (noancilla).
Based on the test moved here from Aqua:
https://github.com/Qiskit/qiskit-aqua/blob/769ca8f/test/aqua/test_mct.py
"""
q_controls = QuantumRegister(num_controls)
q_target = QuantumRegister(1)
qc = QuantumCircuit(q_controls, q_target)
qc.mct(q_controls, q_target[0], None, mode="noancilla")
simulated = execute(qc, BasicAer.get_backend("unitary_simulator")).result().get_unitary(qc)
base = XGate().to_matrix()
expected = _compute_control_matrix(base, num_controls)
self.assertTrue(matrix_equal(simulated, expected, atol=1e-8))
def test_mcsu2_real_diagonal(self):
"""Test mcsu2_real_diagonal"""
num_ctrls = 6
theta = 0.3
ry_matrix = RYGate(theta).to_matrix()
qc = _mcsu2_real_diagonal(ry_matrix, num_ctrls)
mcry_matrix = _compute_control_matrix(ry_matrix, 6)
self.assertTrue(np.allclose(mcry_matrix, Operator(qc).to_matrix()))
@combine(num_controls=[1, 2, 4], base_gate_name=["x", "y", "z"], use_basis_gates=[True, False])
def test_multi_controlled_rotation_gate_matrices(
self, num_controls, base_gate_name, use_basis_gates
):
"""Test the multi controlled rotation gates without ancillas.
Based on the test moved here from Aqua:
https://github.com/Qiskit/qiskit-aqua/blob/769ca8f/test/aqua/test_mcr.py
"""
q_controls = QuantumRegister(num_controls)
q_target = QuantumRegister(1)
# iterate over all possible combinations of control qubits
for ctrl_state in range(2**num_controls):
bitstr = bin(ctrl_state)[2:].zfill(num_controls)[::-1]
theta = 0.871236 * pi
qc = QuantumCircuit(q_controls, q_target)
for idx, bit in enumerate(bitstr):
if bit == "0":
qc.x(q_controls[idx])
# call mcrx/mcry/mcrz
if base_gate_name == "y":
qc.mcry(
theta,
q_controls,
q_target[0],
None,
mode="noancilla",
use_basis_gates=use_basis_gates,
)
else: # case 'x' or 'z' only support the noancilla mode and do not have this keyword
getattr(qc, "mcr" + base_gate_name)(
theta, q_controls, q_target[0], use_basis_gates=use_basis_gates
)
for idx, bit in enumerate(bitstr):
if bit == "0":
qc.x(q_controls[idx])
if use_basis_gates:
with self.subTest(msg="check only basis gates used"):
gates_used = set(qc.count_ops().keys())
self.assertTrue(gates_used.issubset({"x", "u", "p", "cx"}))
backend = BasicAer.get_backend("unitary_simulator")
simulated = execute(qc, backend).result().get_unitary(qc)
if base_gate_name == "x":
rot_mat = RXGate(theta).to_matrix()
elif base_gate_name == "y":
rot_mat = RYGate(theta).to_matrix()
else: # case 'z'
rot_mat = RZGate(theta).to_matrix()
expected = _compute_control_matrix(rot_mat, num_controls, ctrl_state=ctrl_state)
with self.subTest(msg=f"control state = {ctrl_state}"):
self.assertTrue(matrix_equal(simulated, expected))
@combine(num_controls=[1, 2, 4], use_basis_gates=[True, False])
def test_multi_controlled_y_rotation_matrix_basic_mode(self, num_controls, use_basis_gates):
"""Test the multi controlled Y rotation using the mode 'basic'.
Based on the test moved here from Aqua:
https://github.com/Qiskit/qiskit-aqua/blob/769ca8f/test/aqua/test_mcr.py
"""
# get the number of required ancilla qubits
if num_controls <= 2:
num_ancillas = 0
else:
num_ancillas = num_controls - 2
q_controls = QuantumRegister(num_controls)
q_target = QuantumRegister(1)
for ctrl_state in range(2**num_controls):
bitstr = bin(ctrl_state)[2:].zfill(num_controls)[::-1]
theta = 0.871236 * pi
if num_ancillas > 0:
q_ancillas = QuantumRegister(num_ancillas)
qc = QuantumCircuit(q_controls, q_target, q_ancillas)
else:
qc = QuantumCircuit(q_controls, q_target)
q_ancillas = None
for idx, bit in enumerate(bitstr):
if bit == "0":
qc.x(q_controls[idx])
qc.mcry(
theta,
q_controls,
q_target[0],
q_ancillas,
mode="basic",
use_basis_gates=use_basis_gates,
)
for idx, bit in enumerate(bitstr):
if bit == "0":
qc.x(q_controls[idx])
rot_mat = RYGate(theta).to_matrix()
backend = BasicAer.get_backend("unitary_simulator")
simulated = execute(qc, backend).result().get_unitary(qc)
if num_ancillas > 0:
simulated = simulated[: 2 ** (num_controls + 1), : 2 ** (num_controls + 1)]
expected = _compute_control_matrix(rot_mat, num_controls, ctrl_state=ctrl_state)
with self.subTest(msg=f"control state = {ctrl_state}"):
self.assertTrue(matrix_equal(simulated, expected))
def test_mcry_defaults_to_vchain(self):
"""Test mcry defaults to the v-chain mode if sufficient work qubits are provided."""
circuit = QuantumCircuit(5)
control_qubits = circuit.qubits[:3]
target_qubit = circuit.qubits[3]
additional_qubits = circuit.qubits[4:]
circuit.mcry(0.2, control_qubits, target_qubit, additional_qubits)
# If the v-chain mode is selected, all qubits are used. If the noancilla mode would be
# selected, the bottom qubit would remain unused.
dag = circuit_to_dag(circuit)
self.assertEqual(len(list(dag.idle_wires())), 0)
@data(1, 2)
def test_mcx_gates_yield_explicit_gates(self, num_ctrl_qubits):
"""Test the creating a MCX gate yields the explicit definition if we know it."""
cls = MCXGate(num_ctrl_qubits).__class__
explicit = {1: CXGate, 2: CCXGate}
self.assertEqual(cls, explicit[num_ctrl_qubits])
@data(1, 2, 3, 4)
def test_mcxgraycode_gates_yield_explicit_gates(self, num_ctrl_qubits):
"""Test creating an mcx gate calls MCXGrayCode and yeilds explicit definition."""
qc = QuantumCircuit(num_ctrl_qubits + 1)
qc.mcx(list(range(num_ctrl_qubits)), [num_ctrl_qubits])
explicit = {1: CXGate, 2: CCXGate, 3: C3XGate, 4: C4XGate}
self.assertEqual(type(qc[0].operation), explicit[num_ctrl_qubits])
@data(3, 4, 5, 8)
def test_mcx_gates(self, num_ctrl_qubits):
"""Test the mcx gates."""
backend = BasicAer.get_backend("statevector_simulator")
reference = np.zeros(2 ** (num_ctrl_qubits + 1))
reference[-1] = 1
for gate in [
MCXGrayCode(num_ctrl_qubits),
MCXRecursive(num_ctrl_qubits),
MCXVChain(num_ctrl_qubits, False),
MCXVChain(num_ctrl_qubits, True),
]:
with self.subTest(gate=gate):
circuit = QuantumCircuit(gate.num_qubits)
if num_ctrl_qubits > 0:
circuit.x(list(range(num_ctrl_qubits)))
circuit.append(gate, list(range(gate.num_qubits)), [])
statevector = execute(circuit, backend).result().get_statevector()
# account for ancillas
if hasattr(gate, "num_ancilla_qubits") and gate.num_ancilla_qubits > 0:
corrected = np.zeros(2 ** (num_ctrl_qubits + 1), dtype=complex)
for i, statevector_amplitude in enumerate(statevector):
i = int(bin(i)[2:].zfill(circuit.num_qubits)[gate.num_ancilla_qubits :], 2)
corrected[i] += statevector_amplitude
statevector = corrected
np.testing.assert_array_almost_equal(statevector.real, reference)
@data(1, 2, 3, 4)
def test_inverse_x(self, num_ctrl_qubits):
"""Test inverting the controlled X gate."""
cnx = XGate().control(num_ctrl_qubits)
inv_cnx = cnx.inverse()
result = Operator(cnx).compose(Operator(inv_cnx))
np.testing.assert_array_almost_equal(result.data, np.identity(result.dim[0]))
@data(1, 2, 3)
def test_inverse_gate(self, num_ctrl_qubits):
"""Test inverting a controlled gate based on a circuit definition."""
qc = QuantumCircuit(3)
qc.h(0)
qc.cx(0, 1)
qc.cx(1, 2)
qc.rx(np.pi / 4, [0, 1, 2])
gate = qc.to_gate()
cgate = gate.control(num_ctrl_qubits)
inv_cgate = cgate.inverse()
result = Operator(cgate).compose(Operator(inv_cgate))
np.testing.assert_array_almost_equal(result.data, np.identity(result.dim[0]))
@data(1, 2, 3)
def test_inverse_circuit(self, num_ctrl_qubits):
"""Test inverting a controlled gate based on a circuit definition."""
qc = QuantumCircuit(3)
qc.h(0)
qc.cx(0, 1)
qc.cx(1, 2)
qc.rx(np.pi / 4, [0, 1, 2])
cqc = qc.control(num_ctrl_qubits)
cqc_inv = cqc.inverse()
result = Operator(cqc).compose(Operator(cqc_inv))
np.testing.assert_array_almost_equal(result.data, np.identity(result.dim[0]))
@data(1, 2, 3, 4, 5)
def test_controlled_unitary(self, num_ctrl_qubits):
"""Test the matrix data of an Operator, which is based on a controlled gate."""
num_target = 1
q_target = QuantumRegister(num_target)
qc1 = QuantumCircuit(q_target)
# for h-rx(pi/2)
theta, phi, lamb = 1.57079632679490, 0.0, 4.71238898038469
qc1.u(theta, phi, lamb, q_target[0])
base_gate = qc1.to_gate()
# get UnitaryGate version of circuit
base_op = Operator(qc1)
base_mat = base_op.data
cgate = base_gate.control(num_ctrl_qubits)
test_op = Operator(cgate)
cop_mat = _compute_control_matrix(base_mat, num_ctrl_qubits)
self.assertTrue(is_unitary_matrix(base_mat))
self.assertTrue(matrix_equal(cop_mat, test_op.data))
@data(1, 2, 3, 4, 5)
def test_controlled_random_unitary(self, num_ctrl_qubits):
"""Test the matrix data of an Operator based on a random UnitaryGate."""
num_target = 2
base_gate = random_unitary(2**num_target).to_instruction()
base_mat = base_gate.to_matrix()
cgate = base_gate.control(num_ctrl_qubits)
test_op = Operator(cgate)
cop_mat = _compute_control_matrix(base_mat, num_ctrl_qubits)
self.assertTrue(matrix_equal(cop_mat, test_op.data))
@combine(num_ctrl_qubits=[1, 2, 3], ctrl_state=[0, None])
def test_open_controlled_unitary_z(self, num_ctrl_qubits, ctrl_state):
"""Test that UnitaryGate with control returns params."""
umat = np.array([[1, 0], [0, -1]])
ugate = UnitaryGate(umat)
cugate = ugate.control(num_ctrl_qubits, ctrl_state=ctrl_state)
ref_mat = _compute_control_matrix(umat, num_ctrl_qubits, ctrl_state=ctrl_state)
self.assertEqual(Operator(cugate), Operator(ref_mat))
def test_controlled_controlled_rz(self):
"""Test that UnitaryGate with control returns params."""
qc = QuantumCircuit(1)
qc.rz(0.2, 0)
controlled = QuantumCircuit(2)
controlled.compose(qc.control(), inplace=True)
self.assertEqual(Operator(controlled), Operator(CRZGate(0.2)))
self.assertEqual(Operator(controlled), Operator(RZGate(0.2).control()))
def test_controlled_controlled_unitary(self):
"""Test that global phase in iso decomposition of unitary is handled."""
umat = np.array([[1, 0], [0, -1]])
ugate = UnitaryGate(umat)
cugate = ugate.control()
ccugate = cugate.control()
ccugate2 = ugate.control(2)
ref_mat = _compute_control_matrix(umat, 2)
self.assertTrue(Operator(ccugate2).equiv(Operator(ref_mat)))
self.assertTrue(Operator(ccugate).equiv(Operator(ccugate2)))
@data(1, 2, 3)
def test_open_controlled_unitary_matrix(self, num_ctrl_qubits):
"""test open controlled unitary matrix"""
# verify truth table
num_target_qubits = 2
num_qubits = num_ctrl_qubits + num_target_qubits
target_op = Operator(XGate())
for i in range(num_target_qubits - 1):
target_op = target_op.tensor(XGate())
for i in range(2**num_qubits):
input_bitstring = bin(i)[2:].zfill(num_qubits)
input_target = input_bitstring[0:num_target_qubits]
input_ctrl = input_bitstring[-num_ctrl_qubits:]
phi = Statevector.from_label(input_bitstring)
cop = Operator(
_compute_control_matrix(target_op.data, num_ctrl_qubits, ctrl_state=input_ctrl)
)
for j in range(2**num_qubits):
output_bitstring = bin(j)[2:].zfill(num_qubits)
output_target = output_bitstring[0:num_target_qubits]
output_ctrl = output_bitstring[-num_ctrl_qubits:]
psi = Statevector.from_label(output_bitstring)
cxout = np.dot(phi.data, psi.evolve(cop).data)
if input_ctrl == output_ctrl:
# flip the target bits
cond_output = "".join([str(int(not int(a))) for a in input_target])
else:
cond_output = input_target
if cxout == 1:
self.assertTrue((output_ctrl == input_ctrl) and (output_target == cond_output))
else:
self.assertTrue(
((output_ctrl == input_ctrl) and (output_target != cond_output))
or output_ctrl != input_ctrl
)
def test_open_control_cx_unrolling(self):
"""test unrolling of open control gates when gate is in basis"""
qc = QuantumCircuit(2)
qc.cx(0, 1, ctrl_state=0)
dag = circuit_to_dag(qc)
unroller = Unroller(["u3", "cx"])
uqc = dag_to_circuit(unroller.run(dag))
ref_circuit = QuantumCircuit(2)
ref_circuit.append(U3Gate(np.pi, 0, np.pi), [0])
ref_circuit.cx(0, 1)
ref_circuit.append(U3Gate(np.pi, 0, np.pi), [0])
self.assertEqual(uqc, ref_circuit)
def test_open_control_cy_unrolling(self):
"""test unrolling of open control gates when gate is in basis"""
qc = QuantumCircuit(2)
qc.cy(0, 1, ctrl_state=0)
dag = circuit_to_dag(qc)
unroller = Unroller(["u3", "cy"])
uqc = dag_to_circuit(unroller.run(dag))
ref_circuit = QuantumCircuit(2)
ref_circuit.append(U3Gate(np.pi, 0, np.pi), [0])
ref_circuit.cy(0, 1)
ref_circuit.append(U3Gate(np.pi, 0, np.pi), [0])
self.assertEqual(uqc, ref_circuit)
def test_open_control_ccx_unrolling(self):
"""test unrolling of open control gates when gate is in basis"""
qreg = QuantumRegister(3)
qc = QuantumCircuit(qreg)
ccx = CCXGate(ctrl_state=0)
qc.append(ccx, [0, 1, 2])
dag = circuit_to_dag(qc)
unroller = Unroller(["x", "ccx"])
unrolled_dag = unroller.run(dag)
# ┌───┐ ┌───┐
# q0_0: ┤ X ├──■──┤ X ├
# ├───┤ │ ├───┤
# q0_1: ┤ X ├──■──┤ X ├
# └───┘┌─┴─┐└───┘
# q0_2: ─────┤ X ├─────
# └───┘
ref_circuit = QuantumCircuit(qreg)
ref_circuit.x(qreg[0])
ref_circuit.x(qreg[1])
ref_circuit.ccx(qreg[0], qreg[1], qreg[2])
ref_circuit.x(qreg[0])
ref_circuit.x(qreg[1])
ref_dag = circuit_to_dag(ref_circuit)
self.assertEqual(unrolled_dag, ref_dag)
def test_ccx_ctrl_state_consistency(self):
"""Test the consistency of parameters ctrl_state in CCX
See issue: https://github.com/Qiskit/qiskit-terra/issues/6465
"""
qreg = QuantumRegister(3)
qc = QuantumCircuit(qreg)
qc.ccx(qreg[0], qreg[1], qreg[2], ctrl_state=0)
ref_circuit = QuantumCircuit(qreg)
ccx = CCXGate(ctrl_state=0)
ref_circuit.append(ccx, [qreg[0], qreg[1], qreg[2]])
self.assertEqual(qc, ref_circuit)
def test_open_control_composite_unrolling(self):
"""test unrolling of open control gates when gate is in basis"""
# create composite gate
qreg = QuantumRegister(2)
qcomp = QuantumCircuit(qreg, name="bell")
qcomp.h(qreg[0])
qcomp.cx(qreg[0], qreg[1])
bell = qcomp.to_gate()
# create controlled composite gate
cqreg = QuantumRegister(3)
qc = QuantumCircuit(cqreg)
qc.append(bell.control(ctrl_state=0), qc.qregs[0][:])
dag = circuit_to_dag(qc)
unroller = Unroller(["x", "u1", "cbell"])
unrolled_dag = unroller.run(dag)
# create reference circuit
ref_circuit = QuantumCircuit(cqreg)
ref_circuit.x(cqreg[0])
ref_circuit.append(bell.control(), [cqreg[0], cqreg[1], cqreg[2]])
ref_circuit.x(cqreg[0])
ref_dag = circuit_to_dag(ref_circuit)
self.assertEqual(unrolled_dag, ref_dag)
@data(*ControlledGate.__subclasses__())
def test_standard_base_gate_setting(self, gate_class):
"""Test all gates in standard extensions which are of type ControlledGate
and have a base gate setting.
"""
num_free_params = len(_get_free_params(gate_class.__init__, ignore=["self"]))
free_params = [0.1 * i for i in range(num_free_params)]
if gate_class in [MCU1Gate, MCPhaseGate]:
free_params[1] = 3
elif gate_class in [MCXGate]:
free_params[0] = 3
base_gate = gate_class(*free_params)
cgate = base_gate.control()
# the base gate of CU is U (3 params), the base gate of CCU is CU (4 params)
if gate_class == CUGate:
self.assertListEqual(cgate.base_gate.params[:3], base_gate.base_gate.params[:3])
else:
self.assertEqual(base_gate.base_gate, cgate.base_gate)
@combine(
gate=[cls for cls in allGates.__dict__.values() if isinstance(cls, type)],
num_ctrl_qubits=[1, 2],
ctrl_state=[None, 0, 1],
)
def test_all_inverses(self, gate, num_ctrl_qubits, ctrl_state):
"""Test all gates in standard extensions except those that cannot be controlled
or are being deprecated.
"""
if not (issubclass(gate, ControlledGate) or issubclass(gate, allGates.IGate)):
# only verify basic gates right now, as already controlled ones
# will generate differing definitions
try:
numargs = len(_get_free_params(gate))
args = [2] * numargs
gate = gate(*args)
self.assertEqual(
gate.inverse().control(num_ctrl_qubits, ctrl_state=ctrl_state),
gate.control(num_ctrl_qubits, ctrl_state=ctrl_state).inverse(),
)
except AttributeError:
# skip gates that do not have a control attribute (e.g. barrier)
pass
@data(2, 3)
def test_relative_phase_toffoli_gates(self, num_ctrl_qubits):
"""Test the relative phase Toffoli gates.
This test compares the matrix representation of the relative phase gate classes
(i.e. RCCXGate().to_matrix()), the matrix obtained from the unitary simulator,
and the exact version of the gate as obtained through `_compute_control_matrix`.
"""
# get target matrix (w/o relative phase)
base_mat = XGate().to_matrix()
target_mat = _compute_control_matrix(base_mat, num_ctrl_qubits)
# build the matrix for the relative phase toffoli using the unitary simulator
circuit = QuantumCircuit(num_ctrl_qubits + 1)
if num_ctrl_qubits == 2:
circuit.rccx(0, 1, 2)
else: # num_ctrl_qubits == 3:
circuit.rcccx(0, 1, 2, 3)
simulator = BasicAer.get_backend("unitary_simulator")
simulated_mat = execute(circuit, simulator).result().get_unitary()
# get the matrix representation from the class itself
if num_ctrl_qubits == 2:
repr_mat = RCCXGate().to_matrix()
else: # num_ctrl_qubits == 3:
repr_mat = RC3XGate().to_matrix()
# test up to phase
# note, that all entries may have an individual phase! (as opposed to a global phase)
self.assertTrue(matrix_equal(np.abs(simulated_mat), target_mat))
# compare simulated matrix with the matrix representation provided by the class
self.assertTrue(matrix_equal(simulated_mat, repr_mat))
def test_open_controlled_gate(self):
"""
Test controlled gates with control on '0'
"""
base_gate = XGate()
base_mat = base_gate.to_matrix()
num_ctrl_qubits = 3
ctrl_state = 5
cgate = base_gate.control(num_ctrl_qubits, ctrl_state=ctrl_state)
target_mat = _compute_control_matrix(base_mat, num_ctrl_qubits, ctrl_state=ctrl_state)
self.assertEqual(Operator(cgate), Operator(target_mat))
ctrl_state = None
cgate = base_gate.control(num_ctrl_qubits, ctrl_state=ctrl_state)
target_mat = _compute_control_matrix(base_mat, num_ctrl_qubits, ctrl_state=ctrl_state)
self.assertEqual(Operator(cgate), Operator(target_mat))
ctrl_state = 0
cgate = base_gate.control(num_ctrl_qubits, ctrl_state=ctrl_state)
target_mat = _compute_control_matrix(base_mat, num_ctrl_qubits, ctrl_state=ctrl_state)
self.assertEqual(Operator(cgate), Operator(target_mat))
ctrl_state = 7
cgate = base_gate.control(num_ctrl_qubits, ctrl_state=ctrl_state)
target_mat = _compute_control_matrix(base_mat, num_ctrl_qubits, ctrl_state=ctrl_state)
self.assertEqual(Operator(cgate), Operator(target_mat))
ctrl_state = "110"
cgate = base_gate.control(num_ctrl_qubits, ctrl_state=ctrl_state)
target_mat = _compute_control_matrix(base_mat, num_ctrl_qubits, ctrl_state=ctrl_state)
self.assertEqual(Operator(cgate), Operator(target_mat))
def test_open_controlled_gate_raises(self):
"""
Test controlled gates with open controls raises if ctrl_state isn't allowed.
"""
base_gate = XGate()
num_ctrl_qubits = 3
with self.assertRaises(CircuitError):
base_gate.control(num_ctrl_qubits, ctrl_state=-1)
with self.assertRaises(CircuitError):
base_gate.control(num_ctrl_qubits, ctrl_state=2**num_ctrl_qubits)
with self.assertRaises(CircuitError):
base_gate.control(num_ctrl_qubits, ctrl_state="201")
def test_base_gate_params_reference(self):
"""
Test all gates in standard extensions which are of type ControlledGate and have a base gate
setting have params which reference the one in their base gate.
"""
num_ctrl_qubits = 1
for gate_class in ControlledGate.__subclasses__():
with self.subTest(i=repr(gate_class)):
num_free_params = len(_get_free_params(gate_class.__init__, ignore=["self"]))
free_params = [0.1 * (i + 1) for i in range(num_free_params)]
if gate_class in [MCU1Gate, MCPhaseGate]:
free_params[1] = 3
elif gate_class in [MCXGate]:
free_params[0] = 3
base_gate = gate_class(*free_params)
if base_gate.params:
cgate = base_gate.control(num_ctrl_qubits)
self.assertIs(cgate.base_gate.params, cgate.params)
def test_assign_parameters(self):
"""Test assigning parameters to quantum circuit with controlled gate."""
qc = QuantumCircuit(2, name="assign")
ptest = Parameter("p")
gate = CRYGate(ptest)
qc.append(gate, [0, 1])
subs1, subs2 = {ptest: Parameter("a")}, {ptest: Parameter("b")}
bound1 = qc.assign_parameters(subs1, inplace=False)
bound2 = qc.assign_parameters(subs2, inplace=False)
self.assertEqual(qc.parameters, {ptest})
self.assertEqual(bound1.parameters, {subs1[ptest]})
self.assertEqual(bound2.parameters, {subs2[ptest]})
@data(-1, 0, 1.4, "1", 4, 10)
def test_improper_num_ctrl_qubits(self, num_ctrl_qubits):
"""
Test improperly specified num_ctrl_qubits.
"""
num_qubits = 4
with self.assertRaises(CircuitError):
ControlledGate(
name="cgate", num_qubits=num_qubits, params=[], num_ctrl_qubits=num_ctrl_qubits
)
def test_improper_num_ctrl_qubits_base_gate(self):
"""Test that the allowed number of control qubits takes the base gate into account."""
with self.assertRaises(CircuitError):
ControlledGate(
name="cx?", num_qubits=2, params=[], num_ctrl_qubits=2, base_gate=XGate()
)
self.assertIsInstance(
ControlledGate(
name="cx?", num_qubits=2, params=[], num_ctrl_qubits=1, base_gate=XGate()
),
ControlledGate,
)
self.assertIsInstance(
ControlledGate(
name="p",
num_qubits=1,
params=[np.pi],
num_ctrl_qubits=1,
base_gate=Gate("gphase", 0, [np.pi]),
),
ControlledGate,
)
def test_open_controlled_equality(self):
"""
Test open controlled gates are equal if their base gates and control states are equal.
"""
self.assertEqual(XGate().control(1), XGate().control(1))
self.assertNotEqual(XGate().control(1), YGate().control(1))
self.assertNotEqual(XGate().control(1), XGate().control(2))
self.assertEqual(XGate().control(1, ctrl_state="0"), XGate().control(1, ctrl_state="0"))
self.assertNotEqual(XGate().control(1, ctrl_state="0"), XGate().control(1, ctrl_state="1"))
def test_cx_global_phase(self):
"""
Test controlling CX with global phase
"""
theta = pi / 2
circ = QuantumCircuit(2, global_phase=theta)
circ.cx(0, 1)
cx = circ.to_gate()
self.assertNotEqual(Operator(CXGate()), Operator(cx))
ccx = cx.control(1)
base_mat = Operator(cx).data
target = _compute_control_matrix(base_mat, 1)
self.assertEqual(Operator(ccx), Operator(target))
expected = QuantumCircuit(*ccx.definition.qregs)
expected.ccx(0, 1, 2)
expected.p(theta, 0)
self.assertEqual(ccx.definition, expected)
@data(1, 2)
def test_controlled_global_phase(self, num_ctrl_qubits):
"""
Test controlled global phase on base gate.
"""
theta = pi / 4
circ = QuantumCircuit(2, global_phase=theta)
base_gate = circ.to_gate()
base_mat = Operator(base_gate).data
target = _compute_control_matrix(base_mat, num_ctrl_qubits)
cgate = base_gate.control(num_ctrl_qubits)
ccirc = circ.control(num_ctrl_qubits)
self.assertEqual(Operator(cgate), Operator(target))
self.assertEqual(Operator(ccirc), Operator(target))
@data(1, 2)
def test_rz_composite_global_phase(self, num_ctrl_qubits):
"""
Test controlling CX with global phase
"""
theta = pi / 4
circ = QuantumCircuit(2, global_phase=theta)
circ.rz(0.1, 0)
circ.rz(0.2, 1)
ccirc = circ.control(num_ctrl_qubits)
base_gate = circ.to_gate()
cgate = base_gate.control(num_ctrl_qubits)
base_mat = Operator(base_gate).data
target = _compute_control_matrix(base_mat, num_ctrl_qubits)
self.assertEqual(Operator(cgate), Operator(target))
self.assertEqual(Operator(ccirc), Operator(target))
@data(1, 2)
def test_nested_global_phase(self, num_ctrl_qubits):
"""
Test controlling a gate with nested global phase.
"""
theta = pi / 4
circ = QuantumCircuit(1, global_phase=theta)
circ.z(0)
v = circ.to_gate()
qc = QuantumCircuit(1)
qc.append(v, [0])
ctrl_qc = qc.control(num_ctrl_qubits)
base_mat = Operator(qc).data
target = _compute_control_matrix(base_mat, num_ctrl_qubits)
self.assertEqual(Operator(ctrl_qc), Operator(target))
@data(1, 2)
def test_control_zero_operand_gate(self, num_ctrl_qubits):
"""Test that a zero-operand gate (such as a make-shift global-phase gate) can be
controlled."""
gate = QuantumCircuit(global_phase=np.pi).to_gate()
controlled = gate.control(num_ctrl_qubits)
self.assertIsInstance(controlled, ControlledGate)
self.assertEqual(controlled.num_ctrl_qubits, num_ctrl_qubits)
self.assertEqual(controlled.num_qubits, num_ctrl_qubits)
target = np.eye(2**num_ctrl_qubits, dtype=np.complex128)
target.flat[-1] = -1
self.assertEqual(Operator(controlled), Operator(target))
@ddt
class TestOpenControlledToMatrix(QiskitTestCase):
"""Test controlled_gates implementing to_matrix work with ctrl_state"""
@combine(gate_class=ControlledGate.__subclasses__(), ctrl_state=[0, None])
def test_open_controlled_to_matrix(self, gate_class, ctrl_state):
"""Test open controlled to_matrix."""
num_free_params = len(_get_free_params(gate_class.__init__, ignore=["self"]))
free_params = [0.1 * i for i in range(1, num_free_params + 1)]
if gate_class in [MCU1Gate, MCPhaseGate]:
free_params[1] = 3
elif gate_class in [MCXGate]:
free_params[0] = 3
cgate = gate_class(*free_params)
cgate.ctrl_state = ctrl_state
base_mat = Operator(cgate.base_gate).data
if gate_class == CUGate: # account for global phase
base_mat = np.array(base_mat) * np.exp(1j * cgate.params[3])
target = _compute_control_matrix(base_mat, cgate.num_ctrl_qubits, ctrl_state=ctrl_state)
try:
actual = cgate.to_matrix()
except CircuitError as cerr:
self.skipTest(str(cerr))
self.assertTrue(np.allclose(actual, target))
@ddt
class TestSingleControlledRotationGates(QiskitTestCase):
"""Test the controlled rotation gates controlled on one qubit."""
from qiskit.circuit.library.standard_gates import u1, rx, ry, rz
num_ctrl = 2
num_target = 1
theta = pi / 2
gu1 = u1.U1Gate(theta)
grx = rx.RXGate(theta)
gry = ry.RYGate(theta)
grz = rz.RZGate(theta)
ugu1 = ac._unroll_gate(gu1, ["p", "u", "cx"])
ugrx = ac._unroll_gate(grx, ["p", "u", "cx"])
ugry = ac._unroll_gate(gry, ["p", "u", "cx"])
ugrz = ac._unroll_gate(grz, ["p", "u", "cx"])
ugrz.params = grz.params
cgu1 = ugu1.control(num_ctrl)
cgrx = ugrx.control(num_ctrl)
cgry = ugry.control(num_ctrl)
cgrz = ugrz.control(num_ctrl)
@data((gu1, cgu1), (grx, cgrx), (gry, cgry), (grz, cgrz))
@unpack
def test_single_controlled_rotation_gates(self, gate, cgate):
"""Test the controlled rotation gates controlled on one qubit."""
if gate.name == "rz":
iden = Operator.from_label("I")
zgen = Operator.from_label("Z")
op_mat = (np.cos(0.5 * self.theta) * iden - 1j * np.sin(0.5 * self.theta) * zgen).data
else:
op_mat = Operator(gate).data
ref_mat = Operator(cgate).data
cop_mat = _compute_control_matrix(op_mat, self.num_ctrl)
self.assertTrue(matrix_equal(cop_mat, ref_mat))
cqc = QuantumCircuit(self.num_ctrl + self.num_target)
cqc.append(cgate, cqc.qregs[0])
dag = circuit_to_dag(cqc)
unroller = Unroller(["u", "cx"])
uqc = dag_to_circuit(unroller.run(dag))
self.log.info("%s gate count: %d", cgate.name, uqc.size())
self.log.info("\n%s", str(uqc))
# these limits could be changed
if gate.name == "ry":
self.assertLessEqual(uqc.size(), 32, f"\n{uqc}")
elif gate.name == "rz":
self.assertLessEqual(uqc.size(), 43, f"\n{uqc}")
else:
self.assertLessEqual(uqc.size(), 20, f"\n{uqc}")
def test_composite(self):
"""Test composite gate count."""
qreg = QuantumRegister(self.num_ctrl + self.num_target)
qc = QuantumCircuit(qreg, name="composite")
qc.append(self.grx.control(self.num_ctrl), qreg)
qc.append(self.gry.control(self.num_ctrl), qreg)
qc.append(self.gry, qreg[0 : self.gry.num_qubits])
qc.append(self.grz.control(self.num_ctrl), qreg)
dag = circuit_to_dag(qc)
unroller = Unroller(["u", "cx"])
uqc = dag_to_circuit(unroller.run(dag))
self.log.info("%s gate count: %d", uqc.name, uqc.size())
self.assertLessEqual(uqc.size(), 96, f"\n{uqc}") # this limit could be changed
@ddt
class TestControlledStandardGates(QiskitTestCase):
"""Tests for control standard gates."""
@combine(
num_ctrl_qubits=[1, 2, 3],
gate_class=[cls for cls in allGates.__dict__.values() if isinstance(cls, type)],
)
def test_controlled_standard_gates(self, num_ctrl_qubits, gate_class):
"""Test controlled versions of all standard gates."""
theta = pi / 2
ctrl_state_ones = 2**num_ctrl_qubits - 1
ctrl_state_zeros = 0
ctrl_state_mixed = ctrl_state_ones >> int(num_ctrl_qubits / 2)
numargs = len(_get_free_params(gate_class))
args = [theta] * numargs
if gate_class in [MSGate, Barrier]:
args[0] = 2
elif gate_class in [MCU1Gate, MCPhaseGate]:
args[1] = 2
elif issubclass(gate_class, MCXGate):
args = [5]
gate = gate_class(*args)
for ctrl_state in (ctrl_state_ones, ctrl_state_zeros, ctrl_state_mixed):
with self.subTest(i=f"{gate_class.__name__}, ctrl_state={ctrl_state}"):
if hasattr(gate, "num_ancilla_qubits") and gate.num_ancilla_qubits > 0:
# skip matrices that include ancilla qubits
continue
try:
cgate = gate.control(num_ctrl_qubits, ctrl_state=ctrl_state)
except (AttributeError, QiskitError):
# 'object has no attribute "control"'
# skipping Id and Barrier
continue
base_mat = Operator(gate).data
target_mat = _compute_control_matrix(
base_mat, num_ctrl_qubits, ctrl_state=ctrl_state
)
self.assertEqual(Operator(cgate), Operator(target_mat))
@ddt
class TestParameterCtrlState(QiskitTestCase):
"""Test gate equality with ctrl_state parameter."""
@data(
(RXGate(0.5), CRXGate(0.5)),
(RYGate(0.5), CRYGate(0.5)),
(RZGate(0.5), CRZGate(0.5)),
(XGate(), CXGate()),
(YGate(), CYGate()),
(ZGate(), CZGate()),
(U1Gate(0.5), CU1Gate(0.5)),
(PhaseGate(0.5), CPhaseGate(0.5)),
(SwapGate(), CSwapGate()),
(HGate(), CHGate()),
(U3Gate(0.1, 0.2, 0.3), CU3Gate(0.1, 0.2, 0.3)),
(UGate(0.1, 0.2, 0.3), CUGate(0.1, 0.2, 0.3, 0)),
)
@unpack
def test_ctrl_state_one(self, gate, controlled_gate):
"""Test controlled gates with ctrl_state
See https://github.com/Qiskit/qiskit-terra/pull/4025
"""
self.assertEqual(
Operator(gate.control(1, ctrl_state="1")), Operator(controlled_gate.to_matrix())
)
@ddt
class TestControlledGateLabel(QiskitTestCase):
"""Tests for controlled gate labels."""
gates_and_args = [
(XGate, []),
(YGate, []),
(ZGate, []),
(HGate, []),
(CXGate, []),
(CCXGate, []),
(C3XGate, []),
(C3SXGate, []),
(C4XGate, []),
(MCXGate, [5]),
(PhaseGate, [0.1]),
(U1Gate, [0.1]),
(CYGate, []),
(CZGate, []),
(CPhaseGate, [0.1]),
(CU1Gate, [0.1]),
(SwapGate, []),
(SXGate, []),
(CSXGate, []),
(CCXGate, []),
(RZGate, [0.1]),
(RXGate, [0.1]),
(RYGate, [0.1]),
(CRYGate, [0.1]),
(CRXGate, [0.1]),
(CSwapGate, []),
(UGate, [0.1, 0.2, 0.3]),
(U3Gate, [0.1, 0.2, 0.3]),
(CHGate, []),
(CRZGate, [0.1]),
(CUGate, [0.1, 0.2, 0.3, 0.4]),
(CU3Gate, [0.1, 0.2, 0.3]),
(MSGate, [5, 0.1]),
(RCCXGate, []),
(RC3XGate, []),
(MCU1Gate, [0.1, 1]),
(MCXGate, [5]),
]
@data(*gates_and_args)
@unpack
def test_control_label(self, gate, args):
"""Test gate(label=...).control(label=...)"""
cgate = gate(*args, label="a gate").control(label="a controlled gate")
self.assertEqual(cgate.label, "a controlled gate")
self.assertEqual(cgate.base_gate.label, "a gate")
@data(*gates_and_args)
@unpack
def test_control_label_1(self, gate, args):
"""Test gate(label=...).control(1, label=...)"""
cgate = gate(*args, label="a gate").control(1, label="a controlled gate")
self.assertEqual(cgate.label, "a controlled gate")
self.assertEqual(cgate.base_gate.label, "a gate")
if __name__ == "__main__":
unittest.main()
|
https://github.com/jonasmaziero/computacao_quantica_qiskit
|
jonasmaziero
|
%run init.ipynb
simplify(cos(pi/8)), simplify(sin(pi/8))
from qiskit.visualization import plot_bloch_vector
th, ph = pi/4, 0
#plot_bloch_vector([[math.sin(th)*math.cos(ph), math.sin(th)*math.sin(ph), math.cos(th)]])
float(1+1/sqrt(2))/2
X = Matrix([[0,1],[1,0]]); Z = Matrix([[1,0],[0,-1]]); O = (X+Z)/sqrt(2); O.eigenvects()
from qiskit import *
nshots = 8192
qiskit.IBMQ.load_account()
provider = qiskit.IBMQ.get_provider(hub='ibm-q', group='open', project='main')
simulator = Aer.get_backend('qasm_simulator')
device = provider.get_backend('ibmq_belem')
from qiskit.tools.monitor import job_monitor
from qiskit.tools.visualization import plot_histogram
qc = QuantumCircuit(1, 1)
qc.h(0) # preparação do estado
qc.barrier()
# medida de O=H
th = math.pi/4; ph = 0; lb = math.pi - ph; qc.u(th, ph, lb, 0)
qc.measure(0, 0)
qc.draw()
result = execute(qc, backend = simulator, shots = nshots).result()
plot_histogram(result.get_counts(qc))
job = execute(qc, backend = device, shots = nshots)
job_monitor(job)
plot_histogram(job.result().get_counts(qc))
def qc_bb_cb():
qc = QuantumCircuit(2, name = 'BB->CB')
qc.cx(0,1); qc.h(0)#; qc.measure([0,1],[0,1])
return qc
qc_bb_cb_ = qc_bb_cb(); qc_bb_cb_.draw()
qc = QuantumCircuit(2, 2)
qc.x(1); qc.h([0,1]) # preparação do estado |+->
qc.barrier()
qc_bb_cb_ = qc_bb_cb(); qc.append(qc_bb_cb_, [0,1]); qc.measure([0,1],[0,1])
qc.draw()
result = execute(qc, backend = simulator, shots = nshots).result()
plot_histogram(result.get_counts(qc))
job = execute(qc, backend = device, shots = nshots)
job_monitor(job)
plot_histogram(job.result().get_counts(qc))
|
https://github.com/quantumyatra/quantum_computing
|
quantumyatra
|
# Useful additional packages
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
from math import pi
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute
from qiskit.tools.visualization import circuit_drawer
from qiskit.quantum_info import state_fidelity
from qiskit import BasicAer
backend = BasicAer.get_backend('unitary_simulator')
q = QuantumRegister(1)
qc = QuantumCircuit(q)
qc.u3(pi/2,pi/2,pi/2,q)
qc.draw(output='mpl')
job = execute(qc, backend)
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.u2(pi/2,pi/2,q)
qc.draw(output='mpl')
job = execute(qc, backend)
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.u1(pi/2,q)
qc.draw(output='mpl')
job = execute(qc, backend)
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.iden(q)
qc.draw(output='mpl')
job = execute(qc, backend)
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.x(q)
qc.draw(output='mpl')
job = execute(qc, backend)
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.y(q)
qc.draw(output='mpl')
job = execute(qc, backend)
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.z(q)
qc.draw(output='mpl')
job = execute(qc, backend)
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.h(q)
qc.draw(output='mpl')
job = execute(qc, backend)
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.s(q)
qc.draw(output='mpl')
job = execute(qc, backend)
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.sdg(q)
qc.draw(output='mpl')
job = execute(qc, backend)
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.t(q)
qc.draw(output='mpl')
job = execute(qc, backend)
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.tdg(q)
qc.draw(output='mpl')
job = execute(qc, backend)
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.rx(pi/2,q)
qc.draw(output='mpl')
job = execute(qc, backend)
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.ry(pi/2,q)
qc.draw(output='mpl')
job = execute(qc, backend)
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.rz(pi/2,q)
qc.draw(output='mpl')
job = execute(qc, backend)
job.result().get_unitary(qc, decimals=3)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/BOBO1997/osp_solutions
|
BOBO1997
|
import numpy as np
import matplotlib.pyplot as plt
import itertools
from pprint import pprint
# plt.rcParams.update({'font.size': 16}) # enlarge matplotlib fonts
import pickle
import time
import datetime
# Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z)
from qiskit.opflow import Zero, One, I, X, Y, Z
from qiskit import QuantumCircuit, QuantumRegister, IBMQ, execute, transpile, Aer
from qiskit.tools.monitor import job_monitor
from qiskit.circuit import Parameter
from qiskit.transpiler.passes import RemoveBarriers
# Import QREM package
from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter
from qiskit.ignis.mitigation import expectation_value
# Import mitiq for zne
import mitiq
# Import state tomography modules
from qiskit.ignis.verification.tomography import state_tomography_circuits
from qiskit.quantum_info import state_fidelity
import sys
import importlib
sys.path.append("./")
import circuit_utils, zne_utils, tomography_utils, sgs_algorithm
importlib.reload(circuit_utils)
importlib.reload(zne_utils)
importlib.reload(tomography_utils)
importlib.reload(sgs_algorithm)
from circuit_utils import *
from zne_utils import *
from tomography_utils import *
from sgs_algorithm import *
# Combine subcircuits into a single multiqubit gate representing a single trotter step
num_qubits = 3
# The final time of the state evolution
target_time = np.pi
# Parameterize variable t to be evaluated at t=pi later
dt = Parameter('t')
# Convert custom quantum circuit into a gate
trot_gate = trotter_gate(dt)
# initial layout
initial_layout = [5,3,1]
# Number of trotter steps
num_steps = 100
print("trotter step: ", num_steps)
# Initialize quantum circuit for 3 qubits
qr = QuantumRegister(num_qubits, name="lq")
qc = QuantumCircuit(qr)
# Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>)
make_initial_state(qc, "110") # DO NOT MODIFY (|q_5,q_3,q_1> = |110>)
subspace_encoder_init110(qc, targets=[0, 1, 2]) # encode
trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian
subspace_decoder(qc, targets=[0, 1, 2]) # decode
# Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time
qc = qc.bind_parameters({dt: target_time / num_steps})
print("created qc")
# Generate state tomography circuits to evaluate fidelity of simulation
st_qcs = state_tomography_circuits(qc, [0, 1, 2][::-1]) #! state tomography requires === BIG ENDIAN ===
print("created st_qcs (length:", len(st_qcs), ")")
# remove barriers
st_qcs = [RemoveBarriers()(qc) for qc in st_qcs]
print("removed barriers from st_qcs")
# optimize circuit
t3_st_qcs = transpile(st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"])
print("created t3_st_qcs (length:", len(t3_st_qcs), ")")
# zne wrapping
zne_qcs = zne_wrapper(t3_st_qcs)
print("created zne_qcs (length:", len(zne_qcs), ")")
t3_zne_qcs = transpile(zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout)
print("created t3_zne_qcs (length:", len(t3_zne_qcs), ")")
t3_zne_qcs[32].draw("mpl")
from qiskit.test.mock import FakeJakarta
# backend = FakeJakarta()
# backend = Aer.get_backend("qasm_simulator")
IBMQ.load_account()
# provider = IBMQ.get_provider(hub='ibm-q-utokyo', group='internal', project='hirashi-jst')
provider = IBMQ.get_provider(hub='ibm-q-community', group='ibmquantumawards', project='open-science-22')
print("provider:", provider)
backend = provider.get_backend("ibmq_jakarta")
# QREM
shots = 1 << 13
qr = QuantumRegister(num_qubits)
meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal')
cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout = initial_layout)
print('Job ID', cal_job.job_id())
shots = 1 << 13
reps = 8 # unused
jobs = []
for _ in range(reps):
job = execute(t3_zne_qcs, backend, shots=shots, optimization_level=0) # 毎回チェック: ここちゃんと変えた?
print('Job ID', job.job_id())
jobs.append(job)
# 1回目: 2022-04-12 17:27:43.880500
# 2回目: 2022-04-13 01:19:40.602655
dt_now = datetime.datetime.now()
print(dt_now)
import pickle
with open("jobs_jakarta_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f:
pickle.dump({"jobs": jobs, "cal_job": cal_job}, f)
with open("job_ids_jakarta_100step_" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f:
pickle.dump({"job_ids": [job.job_id() for job in jobs], "cal_job_id": cal_job.job_id()}, f)
with open("properties_jakarta" + dt_now.strftime('%Y%m%d_%H%M%S') + "_.pkl", "wb") as f:
pickle.dump(backend.properties(), f)
cal_results = cal_job.result()
meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal')
target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!!
fids = []
for job in jobs:
mit_results = meas_fitter.filter.apply(job.result())
zne_expvals = zne_decoder(num_qubits, mit_results)
rho = expvals_to_valid_rho(num_qubits, zne_expvals)
fid = state_fidelity(rho, target_state)
fids.append(fid)
print('state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(fids), np.std(fids)))
|
https://github.com/intrinsicvardhan/QuantumComputingAlgos
|
intrinsicvardhan
|
print('hello world')
|
https://github.com/qcware/qusetta
|
qcware
|
import sys; sys.path.append("..")
import qusetta as qs
# The first element of the circuit is a column of Hadamards
circuit = "H(0); H(1); H(2); "
# next we have exp(-i z_0 z_1 gamma / 2)
circuit += "CX(0, 1); RZ({gamma})(1); CX(0, 1); "
# now the same for exp(-i z_1 z_2 gamma / 2)
circuit += "CX(1, 2); RZ({gamma})(2); CX(1, 2); "
# now we have a row of x rotations by beta
circuit += "RX({beta})(0); RX({beta})(1); RX({beta})(2)"
def qusetta_qaoa_circuit(beta, gamma):
return circuit.format(beta=beta, gamma=gamma).split("; ")
print(qusetta_qaoa_circuit("beta", "gamma"))
c = qusetta_qaoa_circuit("PI/2", "PI/4")
print(c)
print(qs.Cirq.from_qusetta(c))
print(qs.Quasar.from_qusetta(c))
print(qs.Qiskit.from_qusetta(c))
|
https://github.com/GabrielPontolillo/Quantum_Algorithm_Implementations
|
GabrielPontolillo
|
import unittest
import cirq
import random
import numpy as np
import hypothesis.strategies as st
from hypothesis import given, settings
def create_bell_pair(qubits):
qc = cirq.Circuit()
qc.append(cirq.H(qubits[1]))
qc.append(cirq.CNOT(qubits[1],qubits[0]))
return qc
def encode_message(qc, qubit, msg):
if len(msg) != 2 or not set([0,1]).issubset({0,1}):
raise ValueError(f"message '{msg}' is invalid")
if msg[1] == "1":
qc.append(cirq.X(qubit))
if msg[0] == "1":
qc.append(cirq.Z(qubit))
return qc
def decode_message(qc, qubits):
qc.append(cirq.CNOT(qubits[1],qubits[0]))
qc.append(cirq.H(qubits[1]))
return qc
qubits = cirq.LineQubit.range(2)
qc = create_bell_pair(qubits)
message = '11'
qc = encode_message(qc, qubits[1], message)
qc = decode_message(qc, qubits)
qc.append(cirq.measure(*qubits, key='m'))
print(qc)
simulator = cirq.Simulator()
results = simulator.run(qc , repetitions =1)
readings = np.array2string(results.measurements['m'][0], separator='')[1:-1][::-1]
print(readings)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
qr = QuantumRegister(3, 'q')
anc = QuantumRegister(1, 'ancilla')
cr = ClassicalRegister(3, 'c')
qc = QuantumCircuit(qr, anc, cr)
qc.x(anc[0])
qc.h(anc[0])
qc.h(qr[0:3])
qc.cx(qr[0:3], anc[0])
qc.h(qr[0:3])
qc.barrier(qr)
qc.measure(qr, cr)
qc.draw('mpl')
|
https://github.com/rubenandrebarreiro/summer-school-on-quantum-computing-software-for-near-term-quantum-devices-2020
|
rubenandrebarreiro
|
import numpy as np
import matplotlib.pyplot as plt
plt.rc('font', size=16, family='serif')
from PIL import Image, ImageOps
import urllib.request
urllib.request.urlretrieve("https://raw.githubusercontent.com/juanjosegarciaripoll/uimp-2020/master/cat.png", "cat.png")
cat = ImageOps.grayscale(Image.open('cat.png'))
cat
cat_array = np.asarray(cat)
cat_array[1,1]
cat_array[100,300]
(np.min(cat_array), np.max(cat_array))
cat_I = cat_array.flatten()+0.0
cat_ψ = np.sqrt(cat_I)/np.sqrt(np.sum(cat_I))
np.linalg.norm(cat_ψ)
def order_by_size(ψ, q):
size = [2 for i in range(2*q)]
ndx = [i + j for i in range(q) for j in [0, q]]
return ψ.reshape(size).transpose(ndx)
def order_by_dimension(ψ, q):
size = [2 for i in range(2*q)]
ndx = [2*i + j for j in [0,1] for i in range(q)]
return ψ.reshape(size).transpose(ndx)
def image2state(image, reorder=True):
# Convert image to an array
image = ImageOps.grayscale(image)
image_I = np.asarray(image)
# Reshape to fit some qubit size, the same for both dimensions
L1, L2 = image_I.shape
q1 = int(round(np.log2(L1)))
q2 = int(round(np.log2(L2)))
q = max(q1, q2)
L = 2**q
new_I = np.zeros((L, L), dtype=np.float64)
new_I[0:L1,0:L2] = image_I
I_t = np.sum(new_I.flatten())
ψ = np.sqrt(new_I.flatten())/np.sqrt(I_t)
if reorder:
ψ = order_by_size(ψ, q)
return ψ
def intensity2image(I):
I = np.uint8(np.round(I/np.max(I) * 255.0))
return Image.fromarray(I)
def state2image(ψ, reorder=True):
q = int(round(np.log2(ψ.size))) // 2
L = 2**q
if reorder:
ψ = order_by_dimension(ψ, q)
return intensity2image(np.abs(ψ*ψ).reshape((L,L)))
state2image(image2state(cat, reorder=True), reorder=True)
def resample(ψ, nqubits=None, reorder=True):
q = int(np.round(np.log2(ψ.size)))
if nqubits is None:
nqubits = q-2
elif nqubits < 0:
nqubits = q + nqubits
L1 = 2**nqubits
L2 = ψ.size // L1
#
# We are now going to extract the diagonal of
# the reduced density matrix, and output it as a
# new image
if True:
I = np.einsum('kii->k',
ψ.reshape((L1, L2, 1)) * ψ.conj().reshape(L1, 1, L2))
else:
# This is very slow and consumes a lot of memory
ρ = ψ.reshape((L1,L2)) @ ψ.reshape((L1,L2)).T.conj()
I = np.diag(ρ)
# We may need to undo the ordering of qubits
I = order_by_dimension(I, nqubits//2)
# Intensity is now a vector. We have to rearrange it into
# a square matrix for converting it to an image
L = 2**(nqubits//2)
return intensity2image(I.reshape((L,L)))
resample(image2state(cat), -2)
resample(image2state(cat), -4)
resample(image2state(cat), -6)
resample(image2state(cat), -8)
def enlarge(ψ, nqb):
ψ = ψ.reshape((ψ.size,1)) * np.ones((1,2**nqb))
ψ = ψ.flatten()
return ψ / np.linalg.norm(ψ)
state2image(enlarge(image2state(resample(image2state(cat), -8)), 8))
def Gaussian(nqb, σ=0.1, reorder=True):
x = np.linspace(-1, 1, 2**nqb)
f = np.exp(-0.5 * (x/σ)**2)
f /= np.linalg.norm(f)
ψ = f.reshape((1,2**nqb)) * f.reshape((2**nqb,1))
if reorder:
ψ = order_by_size(ψ, nqb)
return ψ / np.linalg.norm(ψ.flatten())
aux = state2image(Gaussian(9, 0.2))
aux
resample(image2state(aux), -2)
resample(image2state(aux), -4)
resample(image2state(aux), -6)
resample(image2state(aux), -8)
state2image(enlarge(image2state(resample(image2state(aux), -8)), 8))
def Schmidt(ψ, qubits_left=1):
Lleft = 2**qubits_left
Lright = ψ.size // Lleft
ψ = ψ / np.linalg.norm(ψ)
A = ψ.reshape((Lleft, Lright))
Φ, sqrtΛ, Ξ = np.linalg.svd(A)
return (sqrtΛ)**2
ψGaus = Gaussian(9, 0.2)
ψcat = image2state(cat)
fig, ax = plt.subplots()
ax.plot(Schmidt(ψcat, 9), label='cat')
ax.plot(Schmidt(ψGaus, 9), label='Gaussian')
ax.set_ylabel('$\\lambda_i$')
ax.set_xlabel('#eigenvalue')
ax.set_yscale('log')
ax.set_ylim([1e-12,1.2])
ax.legend();
|
https://github.com/muehlhausen/vqls-bachelor-thesis
|
muehlhausen
|
from qiskit import (
QuantumCircuit, QuantumRegister, ClassicalRegister,
Aer, execute, transpile, assemble
)
from qiskit.circuit import Gate, Instruction
from qiskit.quantum_info.operators import Operator
from qiskit.extensions import ZGate, YGate, XGate, IGate
from scipy.optimize import (
minimize, basinhopping, differential_evolution,
shgo, dual_annealing
)
import random
import numpy as np
import cmath
from typing import List, Set, Dict, Tuple, Optional, Union
"""
######### Global Parameters
Those parameters are required by almost all functions but do not need to be
changed during runtime. As one might want to change them between program
executions it is very helpful to have them accesible and in one place.
"""
class GlobalParameters:
def _init_alpha_randomly(self) -> List[float]:
"""
This function initalizes alpha randomly.
"""
# how many parameters are required
n_alpha_i = self.n_qubits + self.n_layers * (self.n_qubits-1) * 2
alpha_rand = [float(random.randint(0, 6283))/1000 for _ in range(n_alpha_i)]
return alpha_rand
def _decompose_asOperator(self, gate: str) -> List[Operator]:
"""
This function returns a list of Operator-Objects of length n_qubits.
The first item is the Operator representing a Z gate acting on the
first qubit. The last item is the Operator representing a Z gate
acting on the last qubit.
"""
if gate == "Z":
Op = Operator(ZGate())
elif gate == "X":
Op = Operator(XGate())
elif gate == "Y":
Op = Operator(YGate())
elif gate == "Id":
Op = Operator(IGate())
Id = Operator(IGate())
dec_asOperator: List[Operator] = []
# Operator acting on the last qubit
temp1 = Op.copy()
for _ in range(self.n_qubits - 1):
temp1 = temp1.tensor(Id)
dec_asOperator.insert(0, temp1)
# all other qubits
for x in range(self.n_qubits - 1):
i = x+1
temp = Id
for j in range(i-1):
temp = temp.tensor(Id)
temp = temp.tensor(Op)
for j in range(self.n_qubits - i - 1):
temp = temp.tensor(Id)
dec_asOperator.insert(0, temp)
return dec_asOperator
def _decompose_asGate(self, gate: str) -> List[Gate]:
"""
This function returns a list of Gate-Objects of length n_qubits.
The first item is the Gate applied to the first qubit, the last item
is the Gate applied to the last qubit.
"""
dec_asGate: List[Gate] = []
for i in range(self.n_qubits):
temp = QuantumCircuit(self.n_qubits)
if gate == "Z":
temp.z(i)
elif gate == "Y":
temp.y(i)
elif gate == "X":
temp.x(i)
elif gate == "Id":
temp.x(i)
temp.x(i)
temp.to_gate()
dec_asGate.append(temp)
return dec_asGate
def _decompositions(self):
"""
This helper function is used to prepare some lists with standard decompositions
that might be used to set together A.
Those lists are stored in the class.
"""
# Z Gates
self.decomposition_asGate_Z = self._decompose_asGate("Z")
self.decomposition_asOperator_Z = self._decompose_asOperator("Z")
# [A_0(+), A_1(+), ...]
self.decomposition_adjoint_asOperator_Z = [op.adjoint() for op in
self.decomposition_asOperator_Z]
# Y Gates
self.decomposition_asGate_Y = self._decompose_asGate("Y")
self.decomposition_asOperator_Y = self._decompose_asOperator("Y")
# [A_0(+), A_1(+), ...]
self.decomposition_adjoint_asOperator_Y = [operator.adjoint() for operator in
self.decomposition_asOperator_Y]
# X Gates
self.decomposition_asGate_X = self._decompose_asGate("X")
self.decomposition_asOperator_X = self._decompose_asOperator("X")
# [A_0(+), A_1(+), ...]
self.decomposition_adjoint_asOperator_X = [operator.adjoint() for operator in
self.decomposition_asOperator_X]
# Identity Gates
self.decomposition_asGate_Id = self._decompose_asGate("Id")
self.decomposition_asOperator_Id = self._decompose_asOperator("Id")
# [A_0(+), A_1(+), ...]
self.decomposition_adjoint_asOperator_Id = [operator.adjoint() for operator in
self.decomposition_asOperator_Id]
def __init__(self, n_qubits: int, n_layers: int, coefficients: List[complex],
COBYLA_maxiter: int = 150, qiskit_simulation_shots: int = 10**3,
qiskit_simulation_backend: str = 'qasm_simulator',
method_minimization: str = 'COBYLA'):
self.n_qubits = n_qubits
# alpha has form: [[0th sublayer], [1st sublayer], [2nd sublayer], ... ]
self.n_layers = n_layers
self.n_sublayers = 1 + 2 * self.n_layers
self.coefficients = coefficients
self.coefficients_conjugate = [np.conjugate(coeff) for coeff
in self.coefficients]
self.COBYLA_maxiter = COBYLA_maxiter
self.qiskit_simulation_backend = qiskit_simulation_backend
self.qiskit_simulation_shots = qiskit_simulation_shots
self.method_minimization = method_minimization
# initialize the parameters for the Ansatz randomly
self.alpha_0 = self._init_alpha_randomly()
self._decompositions()
"""
Only things below this line require user interaction in the classes code
(normally).
"""
"""
The following lines present an example on how to define A and its decomposition.
"""
self.decomposition_asGate = self.decomposition_asGate_Id
self.decomposition_asOperator = self.decomposition_adjoint_asOperator_Id
self.decomposition_adjoint_asOperator = self.decomposition_adjoint_asOperator_Id
# the Operator A
self.A = self.coefficients[0] * self.decomposition_asOperator[0]
for coeff, op in zip(self.coefficients[1:], self.decomposition_asOperator[1:]):
self.A += coeff * op
# This instance of the class is imported and used by all other modules.
# Use it to model your physcal problem.
# To change A or its decomposition you have to modify the code of the class itself.
params = GlobalParameters(
n_qubits=4,
n_layers=4,
coefficients=[complex(0, 0), complex(1, 0),
complex(0, 0), complex(0, 0)],
COBYLA_maxiter=400,
qiskit_simulation_shots=8192,
qiskit_simulation_backend="qasm_simulator"
)
|
https://github.com/xtophe388/QISKIT
|
xtophe388
|
import sys, getpass
try:
sys.path.append("../../") # go to parent dir
import Qconfig
qx_config = {
"APItoken": Qconfig.APItoken,
"url": Qconfig.config['url']}
print('Qconfig loaded from %s.' % Qconfig.__file__)
except:
APItoken = getpass.getpass('Please input your token and hit enter: ')
qx_config = {
"APItoken": APItoken,
"url":"https://quantumexperience.ng.bluemix.net/api"}
print('Qconfig.py not found in qiskit-tutorial directory; Qconfig loaded using user input.')
# useful additional packages
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
from pprint import pprint
from scipy import linalg as la
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, QISKitError
from qiskit import available_backends, execute, register, get_backend
# import state tomography functions
from qiskit.tools.visualization import plot_histogram, plot_state
def ghz_state(q, c, n):
# Create a GHZ state
qc = QuantumCircuit(q, c)
qc.h(q[0])
for i in range(n-1):
qc.cx(q[i], q[i+1])
return qc
def superposition_state(q, c):
# Create a Superposition state
qc = QuantumCircuit(q, c)
qc.h(q)
return qc
# Build the quantum cirucit. We are going to build two circuits a GHZ over 3 qubits and a
# superpositon over all 3 qubits
n = 3 # number of qubits
q = QuantumRegister(n)
c = ClassicalRegister(n)
# quantum circuit to make a GHZ state
ghz = ghz_state(q, c, n)
# quantum circuit to make a superposition state
superposition = superposition_state(q, c)
measure_circuit = QuantumCircuit(q,c)
measure_circuit.measure(q, c)
# execute the quantum circuit
backend = 'local_qasm_simulator' # the device to run on
circuits = [ghz+measure_circuit, superposition+measure_circuit]
job = execute(circuits, backend=backend, shots=1000)
plot_histogram(job.result().get_counts(circuits[0]))
plot_histogram(job.result().get_counts(circuits[1]),15)
n = 2 # number of qubits
q = QuantumRegister(n)
c = ClassicalRegister(n)
qc = QuantumCircuit(q, c)
qc.h(q[1])
# execute the quantum circuit
job = execute(qc, backend='local_statevector_simulator')
state_superposition = job.result().get_statevector(qc)
state_superposition
def overlap(state1, state2):
return round(np.dot(state1.conj(), state2))
print(state_superposition)
overlap(state_superposition, state_superposition)
def expectation_value(state, Operator):
return round(np.dot(state.conj(), np.dot(Operator, state)).real)
X = np.array([[0, 1], [1, 0]])
Z = np.array([[1, 0], [0, -1]])
IZ = np.kron(np.eye(2), Z)
ZI = np.kron(Z, np.eye(2))
IX = np.kron(np.eye(2), X)
XI = np.kron(X, np.eye(2))
print("Operator Z on qubit 0 is " + str(expectation_value(state_superposition, IZ)))
print("Operator Z on qubit 1 is " + str(expectation_value(state_superposition, ZI)))
print("Operator X on qubit 0 is " + str(expectation_value(state_superposition, IX)))
print("Operator X on qubit 1 is " + str(expectation_value(state_superposition, XI)))
def state_2_rho(state):
return np.outer(state, state.conj())
rho_superposition=state_2_rho(state_superposition)
print(rho_superposition)
plot_state(rho_superposition,'city')
plot_state(rho_superposition,'paulivec')
plot_state(rho_superposition,'qsphere')
plot_state(rho_superposition,'bloch')
n = 2 # number of qubits
q = QuantumRegister(n)
c = ClassicalRegister(n)
qc2 = QuantumCircuit(q, c)
qc2.h(q[1])
qc2.z(q[1])
# execute the quantum circuit
job = execute(qc2, backend='local_statevector_simulator')
state_neg_superposition = job.result().get_statevector(qc2)
rho_neg_superposition=state_2_rho(state_neg_superposition)
plot_state(rho_neg_superposition, 'qsphere')
plot_state(0.5*rho_neg_superposition + 0.5* rho_superposition, 'qsphere')
|
https://github.com/2lambda123/Qiskit-qiskit
|
2lambda123
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Tests for SuperOp quantum channel representation class."""
import copy
import unittest
import numpy as np
from numpy.testing import assert_allclose
from qiskit import QiskitError, QuantumCircuit
from qiskit.quantum_info.states import DensityMatrix
from qiskit.quantum_info.operators import Operator
from qiskit.quantum_info.operators.channel import SuperOp
from .channel_test_case import ChannelTestCase
class TestSuperOp(ChannelTestCase):
"""Tests for SuperOp channel representation."""
def test_init(self):
"""Test initialization"""
chan = SuperOp(self.sopI)
assert_allclose(chan.data, self.sopI)
self.assertEqual(chan.dim, (2, 2))
self.assertEqual(chan.num_qubits, 1)
mat = np.zeros((4, 16))
chan = SuperOp(mat)
assert_allclose(chan.data, mat)
self.assertEqual(chan.dim, (4, 2))
self.assertIsNone(chan.num_qubits)
chan = SuperOp(mat.T)
assert_allclose(chan.data, mat.T)
self.assertEqual(chan.dim, (2, 4))
self.assertIsNone(chan.num_qubits)
# Wrong input or output dims should raise exception
self.assertRaises(QiskitError, SuperOp, mat, input_dims=[4], output_dims=[4])
def test_circuit_init(self):
"""Test initialization from a circuit."""
# Test tensor product of 1-qubit gates
circuit = QuantumCircuit(3)
circuit.h(0)
circuit.x(1)
circuit.ry(np.pi / 2, 2)
op = SuperOp(circuit)
y90 = (1 / np.sqrt(2)) * np.array([[1, -1], [1, 1]])
target = SuperOp(Operator(np.kron(y90, np.kron(self.UX, self.UH))))
self.assertEqual(target, op)
# Test decomposition of Controlled-Phase gate
lam = np.pi / 4
circuit = QuantumCircuit(2)
circuit.cp(lam, 0, 1)
op = SuperOp(circuit)
target = SuperOp(Operator(np.diag([1, 1, 1, np.exp(1j * lam)])))
self.assertEqual(target, op)
# Test decomposition of controlled-H gate
circuit = QuantumCircuit(2)
circuit.ch(0, 1)
op = SuperOp(circuit)
target = SuperOp(
Operator(np.kron(self.UI, np.diag([1, 0])) + np.kron(self.UH, np.diag([0, 1])))
)
self.assertEqual(target, op)
def test_circuit_init_except(self):
"""Test initialization from circuit with measure raises exception."""
circuit = self.simple_circuit_with_measure()
self.assertRaises(QiskitError, SuperOp, circuit)
def test_equal(self):
"""Test __eq__ method"""
mat = self.rand_matrix(4, 4)
self.assertEqual(SuperOp(mat), SuperOp(mat))
def test_copy(self):
"""Test copy method"""
mat = np.eye(4)
with self.subTest("Deep copy"):
orig = SuperOp(mat)
cpy = orig.copy()
cpy._data[0, 0] = 0.0
self.assertFalse(cpy == orig)
with self.subTest("Shallow copy"):
orig = SuperOp(mat)
clone = copy.copy(orig)
clone._data[0, 0] = 0.0
self.assertTrue(clone == orig)
def test_clone(self):
"""Test clone method"""
mat = np.eye(4)
orig = SuperOp(mat)
clone = copy.copy(orig)
clone._data[0, 0] = 0.0
self.assertTrue(clone == orig)
def test_evolve(self):
"""Test evolve method."""
input_rho = DensityMatrix([[0, 0], [0, 1]])
# Identity channel
chan = SuperOp(self.sopI)
target_rho = DensityMatrix([[0, 0], [0, 1]])
self.assertEqual(input_rho.evolve(chan), target_rho)
# Hadamard channel
mat = np.array([[1, 1], [1, -1]]) / np.sqrt(2)
chan = SuperOp(np.kron(mat.conj(), mat))
target_rho = DensityMatrix(np.array([[1, -1], [-1, 1]]) / 2)
self.assertEqual(input_rho.evolve(chan), target_rho)
# Completely depolarizing channel
chan = SuperOp(self.depol_sop(1))
target_rho = DensityMatrix(np.eye(2) / 2)
self.assertEqual(input_rho.evolve(chan), target_rho)
def test_evolve_subsystem(self):
"""Test subsystem evolve method."""
# Single-qubit random superoperators
op_a = SuperOp(self.rand_matrix(4, 4))
op_b = SuperOp(self.rand_matrix(4, 4))
op_c = SuperOp(self.rand_matrix(4, 4))
id1 = SuperOp(np.eye(4))
id2 = SuperOp(np.eye(16))
rho = DensityMatrix(self.rand_rho(8))
# Test evolving single-qubit of 3-qubit system
op = op_a
# Evolve on qubit 0
full_op = id2.tensor(op_a)
rho_targ = rho.evolve(full_op)
rho_test = rho.evolve(op, qargs=[0])
self.assertEqual(rho_test, rho_targ)
# Evolve on qubit 1
full_op = id1.tensor(op_a).tensor(id1)
rho_targ = rho.evolve(full_op)
rho_test = rho.evolve(op, qargs=[1])
self.assertEqual(rho_test, rho_targ)
# Evolve on qubit 2
full_op = op_a.tensor(id2)
rho_targ = rho.evolve(full_op)
rho_test = rho.evolve(op, qargs=[2])
self.assertEqual(rho_test, rho_targ)
# Test 2-qubit evolution
op = op_b.tensor(op_a)
# Evolve on qubits [0, 2]
full_op = op_b.tensor(id1).tensor(op_a)
rho_targ = rho.evolve(full_op)
rho_test = rho.evolve(op, qargs=[0, 2])
self.assertEqual(rho_test, rho_targ)
# Evolve on qubits [2, 0]
full_op = op_a.tensor(id1).tensor(op_b)
rho_targ = rho.evolve(full_op)
rho_test = rho.evolve(op, qargs=[2, 0])
self.assertEqual(rho_test, rho_targ)
# Test 3-qubit evolution
op = op_c.tensor(op_b).tensor(op_a)
# Evolve on qubits [0, 1, 2]
full_op = op
rho_targ = rho.evolve(full_op)
rho_test = rho.evolve(op, qargs=[0, 1, 2])
self.assertEqual(rho_test, rho_targ)
# Evolve on qubits [2, 1, 0]
full_op = op_a.tensor(op_b).tensor(op_c)
rho_targ = rho.evolve(full_op)
rho_test = rho.evolve(op, qargs=[2, 1, 0])
self.assertEqual(rho_test, rho_targ)
def test_is_cptp(self):
"""Test is_cptp method."""
self.assertTrue(SuperOp(self.depol_sop(0.25)).is_cptp())
# Non-CPTP should return false
self.assertFalse(SuperOp(1.25 * self.sopI - 0.25 * self.depol_sop(1)).is_cptp())
def test_conjugate(self):
"""Test conjugate method."""
mat = self.rand_matrix(4, 4)
chan = SuperOp(mat)
targ = SuperOp(np.conjugate(mat))
self.assertEqual(chan.conjugate(), targ)
def test_transpose(self):
"""Test transpose method."""
mat = self.rand_matrix(4, 4)
chan = SuperOp(mat)
targ = SuperOp(np.transpose(mat))
self.assertEqual(chan.transpose(), targ)
def test_adjoint(self):
"""Test adjoint method."""
mat = self.rand_matrix(4, 4)
chan = SuperOp(mat)
targ = SuperOp(np.transpose(np.conj(mat)))
self.assertEqual(chan.adjoint(), targ)
def test_compose_except(self):
"""Test compose different dimension exception"""
self.assertRaises(QiskitError, SuperOp(np.eye(4)).compose, SuperOp(np.eye(16)))
self.assertRaises(QiskitError, SuperOp(np.eye(4)).compose, 2)
def test_compose(self):
"""Test compose method."""
# UnitaryChannel evolution
chan1 = SuperOp(self.sopX)
chan2 = SuperOp(self.sopY)
chan = chan1.compose(chan2)
targ = SuperOp(self.sopZ)
self.assertEqual(chan, targ)
# 50% depolarizing channel
chan1 = SuperOp(self.depol_sop(0.5))
chan = chan1.compose(chan1)
targ = SuperOp(self.depol_sop(0.75))
self.assertEqual(chan, targ)
# Random superoperator
mat1 = self.rand_matrix(4, 4)
mat2 = self.rand_matrix(4, 4)
chan1 = SuperOp(mat1)
chan2 = SuperOp(mat2)
targ = SuperOp(np.dot(mat2, mat1))
self.assertEqual(chan1.compose(chan2), targ)
self.assertEqual(chan1 & chan2, targ)
targ = SuperOp(np.dot(mat1, mat2))
self.assertEqual(chan2.compose(chan1), targ)
self.assertEqual(chan2 & chan1, targ)
# Compose different dimensions
chan1 = SuperOp(self.rand_matrix(16, 4))
chan2 = SuperOp(
self.rand_matrix(4, 16),
)
chan = chan1.compose(chan2)
self.assertEqual(chan.dim, (2, 2))
chan = chan2.compose(chan1)
self.assertEqual(chan.dim, (4, 4))
def test_dot(self):
"""Test dot method."""
# UnitaryChannel evolution
chan1 = SuperOp(self.sopX)
chan2 = SuperOp(self.sopY)
targ = SuperOp(self.sopZ)
self.assertEqual(chan1.dot(chan2), targ)
self.assertEqual(chan1 @ chan2, targ)
# 50% depolarizing channel
chan1 = SuperOp(self.depol_sop(0.5))
targ = SuperOp(self.depol_sop(0.75))
self.assertEqual(chan1.dot(chan1), targ)
self.assertEqual(chan1 @ chan1, targ)
# Random superoperator
mat1 = self.rand_matrix(4, 4)
mat2 = self.rand_matrix(4, 4)
chan1 = SuperOp(mat1)
chan2 = SuperOp(mat2)
targ = SuperOp(np.dot(mat2, mat1))
self.assertEqual(chan2.dot(chan1), targ)
targ = SuperOp(np.dot(mat1, mat2))
# Compose different dimensions
chan1 = SuperOp(self.rand_matrix(16, 4))
chan2 = SuperOp(self.rand_matrix(4, 16))
chan = chan1.dot(chan2)
self.assertEqual(chan.dim, (4, 4))
chan = chan1 @ chan2
self.assertEqual(chan.dim, (4, 4))
chan = chan2.dot(chan1)
self.assertEqual(chan.dim, (2, 2))
chan = chan2 @ chan1
self.assertEqual(chan.dim, (2, 2))
def test_compose_front(self):
"""Test front compose method."""
# DEPRECATED
# UnitaryChannel evolution
chan1 = SuperOp(self.sopX)
chan2 = SuperOp(self.sopY)
chan = chan1.compose(chan2, front=True)
targ = SuperOp(self.sopZ)
self.assertEqual(chan, targ)
# 50% depolarizing channel
chan1 = SuperOp(self.depol_sop(0.5))
chan = chan1.compose(chan1, front=True)
targ = SuperOp(self.depol_sop(0.75))
self.assertEqual(chan, targ)
# Random superoperator
mat1 = self.rand_matrix(4, 4)
mat2 = self.rand_matrix(4, 4)
chan1 = SuperOp(mat1)
chan2 = SuperOp(mat2)
targ = SuperOp(np.dot(mat2, mat1))
self.assertEqual(chan2.compose(chan1, front=True), targ)
targ = SuperOp(np.dot(mat1, mat2))
self.assertEqual(chan1.compose(chan2, front=True), targ)
# Compose different dimensions
chan1 = SuperOp(self.rand_matrix(16, 4))
chan2 = SuperOp(self.rand_matrix(4, 16))
chan = chan1.compose(chan2, front=True)
self.assertEqual(chan.dim, (4, 4))
chan = chan2.compose(chan1, front=True)
self.assertEqual(chan.dim, (2, 2))
def test_compose_subsystem(self):
"""Test subsystem compose method."""
# 3-qubit superoperator
mat = self.rand_matrix(64, 64)
mat_a = self.rand_matrix(4, 4)
mat_b = self.rand_matrix(4, 4)
mat_c = self.rand_matrix(4, 4)
iden = SuperOp(np.eye(4))
op = SuperOp(mat)
op1 = SuperOp(mat_a)
op2 = SuperOp(mat_b).tensor(SuperOp(mat_a))
op3 = SuperOp(mat_c).tensor(SuperOp(mat_b)).tensor(SuperOp(mat_a))
# op3 qargs=[0, 1, 2]
full_op = SuperOp(mat_c).tensor(SuperOp(mat_b)).tensor(SuperOp(mat_a))
targ = np.dot(full_op.data, mat)
self.assertEqual(op.compose(op3, qargs=[0, 1, 2]), SuperOp(targ))
self.assertEqual(op & op3([0, 1, 2]), SuperOp(targ))
# op3 qargs=[2, 1, 0]
full_op = SuperOp(mat_a).tensor(SuperOp(mat_b)).tensor(SuperOp(mat_c))
targ = np.dot(full_op.data, mat)
self.assertEqual(op.compose(op3, qargs=[2, 1, 0]), SuperOp(targ))
self.assertEqual(op & op3([2, 1, 0]), SuperOp(targ))
# op2 qargs=[0, 1]
full_op = iden.tensor(SuperOp(mat_b)).tensor(SuperOp(mat_a))
targ = np.dot(full_op.data, mat)
self.assertEqual(op.compose(op2, qargs=[0, 1]), SuperOp(targ))
self.assertEqual(op & op2([0, 1]), SuperOp(targ))
# op2 qargs=[2, 0]
full_op = SuperOp(mat_a).tensor(iden).tensor(SuperOp(mat_b))
targ = np.dot(full_op.data, mat)
self.assertEqual(op.compose(op2, qargs=[2, 0]), SuperOp(targ))
self.assertEqual(op & op2([2, 0]), SuperOp(targ))
# op1 qargs=[0]
full_op = iden.tensor(iden).tensor(SuperOp(mat_a))
targ = np.dot(full_op.data, mat)
self.assertEqual(op.compose(op1, qargs=[0]), SuperOp(targ))
self.assertEqual(op & op1([0]), SuperOp(targ))
# op1 qargs=[1]
full_op = iden.tensor(SuperOp(mat_a)).tensor(iden)
targ = np.dot(full_op.data, mat)
self.assertEqual(op.compose(op1, qargs=[1]), SuperOp(targ))
self.assertEqual(op & op1([1]), SuperOp(targ))
# op1 qargs=[2]
full_op = SuperOp(mat_a).tensor(iden).tensor(iden)
targ = np.dot(full_op.data, mat)
self.assertEqual(op.compose(op1, qargs=[2]), SuperOp(targ))
self.assertEqual(op & op1([2]), SuperOp(targ))
def test_dot_subsystem(self):
"""Test subsystem dot method."""
# 3-qubit operator
mat = self.rand_matrix(64, 64)
mat_a = self.rand_matrix(4, 4)
mat_b = self.rand_matrix(4, 4)
mat_c = self.rand_matrix(4, 4)
iden = SuperOp(np.eye(4))
op = SuperOp(mat)
op1 = SuperOp(mat_a)
op2 = SuperOp(mat_b).tensor(SuperOp(mat_a))
op3 = SuperOp(mat_c).tensor(SuperOp(mat_b)).tensor(SuperOp(mat_a))
# op3 qargs=[0, 1, 2]
full_op = SuperOp(mat_c).tensor(SuperOp(mat_b)).tensor(SuperOp(mat_a))
targ = np.dot(mat, full_op.data)
self.assertEqual(op.dot(op3, qargs=[0, 1, 2]), SuperOp(targ))
# op3 qargs=[2, 1, 0]
full_op = SuperOp(mat_a).tensor(SuperOp(mat_b)).tensor(SuperOp(mat_c))
targ = np.dot(mat, full_op.data)
self.assertEqual(op.dot(op3, qargs=[2, 1, 0]), SuperOp(targ))
# op2 qargs=[0, 1]
full_op = iden.tensor(SuperOp(mat_b)).tensor(SuperOp(mat_a))
targ = np.dot(mat, full_op.data)
self.assertEqual(op.dot(op2, qargs=[0, 1]), SuperOp(targ))
# op2 qargs=[2, 0]
full_op = SuperOp(mat_a).tensor(iden).tensor(SuperOp(mat_b))
targ = np.dot(mat, full_op.data)
self.assertEqual(op.dot(op2, qargs=[2, 0]), SuperOp(targ))
# op1 qargs=[0]
full_op = iden.tensor(iden).tensor(SuperOp(mat_a))
targ = np.dot(mat, full_op.data)
self.assertEqual(op.dot(op1, qargs=[0]), SuperOp(targ))
# op1 qargs=[1]
full_op = iden.tensor(SuperOp(mat_a)).tensor(iden)
targ = np.dot(mat, full_op.data)
self.assertEqual(op.dot(op1, qargs=[1]), SuperOp(targ))
# op1 qargs=[2]
full_op = SuperOp(mat_a).tensor(iden).tensor(iden)
targ = np.dot(mat, full_op.data)
self.assertEqual(op.dot(op1, qargs=[2]), SuperOp(targ))
def test_compose_front_subsystem(self):
"""Test subsystem front compose method."""
# 3-qubit operator
mat = self.rand_matrix(64, 64)
mat_a = self.rand_matrix(4, 4)
mat_b = self.rand_matrix(4, 4)
mat_c = self.rand_matrix(4, 4)
iden = SuperOp(np.eye(4))
op = SuperOp(mat)
op1 = SuperOp(mat_a)
op2 = SuperOp(mat_b).tensor(SuperOp(mat_a))
op3 = SuperOp(mat_c).tensor(SuperOp(mat_b)).tensor(SuperOp(mat_a))
# op3 qargs=[0, 1, 2]
full_op = SuperOp(mat_c).tensor(SuperOp(mat_b)).tensor(SuperOp(mat_a))
targ = np.dot(mat, full_op.data)
self.assertEqual(op.compose(op3, qargs=[0, 1, 2], front=True), SuperOp(targ))
# op3 qargs=[2, 1, 0]
full_op = SuperOp(mat_a).tensor(SuperOp(mat_b)).tensor(SuperOp(mat_c))
targ = np.dot(mat, full_op.data)
self.assertEqual(op.compose(op3, qargs=[2, 1, 0], front=True), SuperOp(targ))
# op2 qargs=[0, 1]
full_op = iden.tensor(SuperOp(mat_b)).tensor(SuperOp(mat_a))
targ = np.dot(mat, full_op.data)
self.assertEqual(op.compose(op2, qargs=[0, 1], front=True), SuperOp(targ))
# op2 qargs=[2, 0]
full_op = SuperOp(mat_a).tensor(iden).tensor(SuperOp(mat_b))
targ = np.dot(mat, full_op.data)
self.assertEqual(op.compose(op2, qargs=[2, 0], front=True), SuperOp(targ))
# op1 qargs=[0]
full_op = iden.tensor(iden).tensor(SuperOp(mat_a))
targ = np.dot(mat, full_op.data)
self.assertEqual(op.compose(op1, qargs=[0], front=True), SuperOp(targ))
# op1 qargs=[1]
full_op = iden.tensor(SuperOp(mat_a)).tensor(iden)
targ = np.dot(mat, full_op.data)
self.assertEqual(op.compose(op1, qargs=[1], front=True), SuperOp(targ))
# op1 qargs=[2]
full_op = SuperOp(mat_a).tensor(iden).tensor(iden)
targ = np.dot(mat, full_op.data)
self.assertEqual(op.compose(op1, qargs=[2], front=True), SuperOp(targ))
def test_expand(self):
"""Test expand method."""
rho0, rho1 = np.diag([1, 0]), np.diag([0, 1])
rho_init = DensityMatrix(np.kron(rho0, rho0))
chan1 = SuperOp(self.sopI)
chan2 = SuperOp(self.sopX)
# X \otimes I
chan = chan1.expand(chan2)
rho_targ = DensityMatrix(np.kron(rho1, rho0))
self.assertEqual(chan.dim, (4, 4))
self.assertEqual(rho_init.evolve(chan), rho_targ)
# I \otimes X
chan = chan2.expand(chan1)
rho_targ = DensityMatrix(np.kron(rho0, rho1))
self.assertEqual(chan.dim, (4, 4))
self.assertEqual(rho_init.evolve(chan), rho_targ)
def test_tensor(self):
"""Test tensor method."""
rho0, rho1 = np.diag([1, 0]), np.diag([0, 1])
rho_init = DensityMatrix(np.kron(rho0, rho0))
chan1 = SuperOp(self.sopI)
chan2 = SuperOp(self.sopX)
# X \otimes I
chan = chan2.tensor(chan1)
rho_targ = DensityMatrix(np.kron(rho1, rho0))
self.assertEqual(chan.dim, (4, 4))
self.assertEqual(rho_init.evolve(chan), rho_targ)
chan = chan2 ^ chan1
self.assertEqual(chan.dim, (4, 4))
self.assertEqual(rho_init.evolve(chan), rho_targ)
# I \otimes X
chan = chan1.tensor(chan2)
rho_targ = DensityMatrix(np.kron(rho0, rho1))
self.assertEqual(chan.dim, (4, 4))
self.assertEqual(rho_init.evolve(chan), rho_targ)
chan = chan1 ^ chan2
self.assertEqual(chan.dim, (4, 4))
self.assertEqual(rho_init.evolve(chan), rho_targ)
def test_power(self):
"""Test power method."""
# 10% depolarizing channel
p_id = 0.9
depol = SuperOp(self.depol_sop(1 - p_id))
# Compose 3 times
p_id3 = p_id**3
chan3 = depol.power(3)
targ3 = SuperOp(self.depol_sop(1 - p_id3))
self.assertEqual(chan3, targ3)
def test_add(self):
"""Test add method."""
mat1 = 0.5 * self.sopI
mat2 = 0.5 * self.depol_sop(1)
chan1 = SuperOp(mat1)
chan2 = SuperOp(mat2)
targ = SuperOp(mat1 + mat2)
self.assertEqual(chan1._add(chan2), targ)
self.assertEqual(chan1 + chan2, targ)
targ = SuperOp(mat1 - mat2)
self.assertEqual(chan1 - chan2, targ)
def test_add_qargs(self):
"""Test add method with qargs."""
mat = self.rand_matrix(8**2, 8**2)
mat0 = self.rand_matrix(4, 4)
mat1 = self.rand_matrix(4, 4)
op = SuperOp(mat)
op0 = SuperOp(mat0)
op1 = SuperOp(mat1)
op01 = op1.tensor(op0)
eye = SuperOp(self.sopI)
with self.subTest(msg="qargs=[0]"):
value = op + op0([0])
target = op + eye.tensor(eye).tensor(op0)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[1]"):
value = op + op0([1])
target = op + eye.tensor(op0).tensor(eye)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[2]"):
value = op + op0([2])
target = op + op0.tensor(eye).tensor(eye)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[0, 1]"):
value = op + op01([0, 1])
target = op + eye.tensor(op1).tensor(op0)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[1, 0]"):
value = op + op01([1, 0])
target = op + eye.tensor(op0).tensor(op1)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[0, 2]"):
value = op + op01([0, 2])
target = op + op1.tensor(eye).tensor(op0)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[2, 0]"):
value = op + op01([2, 0])
target = op + op0.tensor(eye).tensor(op1)
self.assertEqual(value, target)
def test_sub_qargs(self):
"""Test subtract method with qargs."""
mat = self.rand_matrix(8**2, 8**2)
mat0 = self.rand_matrix(4, 4)
mat1 = self.rand_matrix(4, 4)
op = SuperOp(mat)
op0 = SuperOp(mat0)
op1 = SuperOp(mat1)
op01 = op1.tensor(op0)
eye = SuperOp(self.sopI)
with self.subTest(msg="qargs=[0]"):
value = op - op0([0])
target = op - eye.tensor(eye).tensor(op0)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[1]"):
value = op - op0([1])
target = op - eye.tensor(op0).tensor(eye)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[2]"):
value = op - op0([2])
target = op - op0.tensor(eye).tensor(eye)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[0, 1]"):
value = op - op01([0, 1])
target = op - eye.tensor(op1).tensor(op0)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[1, 0]"):
value = op - op01([1, 0])
target = op - eye.tensor(op0).tensor(op1)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[0, 2]"):
value = op - op01([0, 2])
target = op - op1.tensor(eye).tensor(op0)
self.assertEqual(value, target)
with self.subTest(msg="qargs=[2, 0]"):
value = op - op01([2, 0])
target = op - op0.tensor(eye).tensor(op1)
self.assertEqual(value, target)
def test_add_except(self):
"""Test add method raises exceptions."""
chan1 = SuperOp(self.sopI)
chan2 = SuperOp(np.eye(16))
self.assertRaises(QiskitError, chan1._add, chan2)
self.assertRaises(QiskitError, chan1._add, 5)
def test_multiply(self):
"""Test multiply method."""
chan = SuperOp(self.sopI)
val = 0.5
targ = SuperOp(val * self.sopI)
self.assertEqual(chan._multiply(val), targ)
self.assertEqual(val * chan, targ)
targ = SuperOp(self.sopI * val)
self.assertEqual(chan * val, targ)
def test_multiply_except(self):
"""Test multiply method raises exceptions."""
chan = SuperOp(self.sopI)
self.assertRaises(QiskitError, chan._multiply, "s")
self.assertRaises(QiskitError, chan.__rmul__, "s")
self.assertRaises(QiskitError, chan._multiply, chan)
self.assertRaises(QiskitError, chan.__rmul__, chan)
def test_negate(self):
"""Test negate method"""
chan = SuperOp(self.sopI)
targ = SuperOp(-self.sopI)
self.assertEqual(-chan, targ)
if __name__ == "__main__":
unittest.main()
|
https://github.com/anpaschool/QC-School-Fall2020
|
anpaschool
|
import numpy as np
import pylab as plt
from numpy import pi
from qiskit import QuantumCircuit, execute, Aer, IBMQ
from qiskit.visualization import plot_histogram, plot_bloch_multivector
qc = QuantumCircuit(3)
qc = QuantumCircuit(3)
qc.h(2)
display( qc.draw('mpl') )
# UROT_2 gate to x1 depending on x2
qc.cu1(pi/2, 1, 2) # CROT from qubit 1 to qubit 2 hence the angle: pi/2^{2-1}
display ( qc.draw('mpl') )
qc.cu1(pi/4, 0, 2) # CROT from qubit 2 to qubit 0 hence the angle: pi/2^{2-0}
display( qc.draw('mpl') )
# Repeat the process for 2 and 3
qc.h(1) # Hadamard on 1
qc.cu1(pi/2, 0, 1) # CROT from qubit 0 to qubit 1 hence the angle: pi/2^{1-0}
qc.h(0) # Hadamard on 0
display( qc.draw('mpl') )
# Now swap the qubit 0 and 2 to complete QFT. [NOT CLEAR TO ME]
qc.swap(0,2)
display ( qc.draw('mpl') )
def qft_rotations(ckt, n):
if n == 0:
return ckt
n -= 1
ckt.h(n)
for qubit in range(n):
ckt.cu1( pi/2**(n-qubit), qubit, n )
qc = QuantumCircuit(4)
qft_rotations(qc,4)
qc.draw('mpl')
def qft_rotations(ckt, n):
if n == 0:
return ckt
n -= 1
ckt.h(n)
for qubit in range(n):
ckt.cu1( pi/2**(n-qubit), qubit, n )
qft_rotations(ckt, n)
qc = QuantumCircuit(4)
qft_rotations(qc,4)
qc.draw('mpl')
from qiskit_textbook.widgets import scalable_circuit
scalable_circuit(qft_rotations)
def swap_registers(ckt, n):
for qubit in range(n//2):
ckt.swap(qubit, n-qubit-1)
return ckt
def qft(ckt, n):
qft_rotations(ckt, n)
swap_registers(ckt, n)
return ckt
qc = QuantumCircuit(4)
qft(qc, 4)
qc.draw('mpl')
print (f"5 and it's binary: {bin(5)}")
#bin(9)
qc = QuantumCircuit(3)
qc.x(0)
qc.x(2)
display(qc.draw('mpl'))
backend = Aer.get_backend('statevector_simulator')
sv = execute(qc, backend=backend).result().get_statevector()
plot_bloch_multivector(sv)
print (sv.real)
qft(qc, 3)
qc.draw('mpl')
sv = execute(qc, backend=backend).result().get_statevector()
plot_bloch_multivector(sv)
print ('The statevectors are:\n', sv.round(1))
print ('Angle subtended by each states (as a factor of pi):\n',(np.angle(sv)/np.pi).round(2))
# 10
qc = QuantumCircuit(2)
qc.x(0)
qc.draw('mpl')
backend = Aer.get_backend('statevector_simulator')
sv = execute(qc, backend=backend).result().get_statevector()
plot_bloch_multivector(sv)
qft(qc, 2)
qc.draw('mpl')
backend = Aer.get_backend('statevector_simulator')
sv = execute(qc, backend=backend).result().get_statevector()
plot_bloch_multivector(sv)
def inverse_qft(circuit, n):
"""Does the inverse QFT on the first n qubits in circuit"""
# First we create a QFT circuit of the correct size:
qft_circ = qft(QuantumCircuit(n), n)
# Then we take the inverse of this circuit
invqft_circ = qft_circ.inverse()
# And add it to the first n qubits in our existing circuit
circuit.append(invqft_circ, circuit.qubits[:n])
# use .decompose() which allows us to see the individual gates
return circuit.decompose()
nqubits = 3
number = 6
qc = QuantumCircuit(nqubits)
for qubit in range(nqubits):
qc.h(qubit)
qc.u1(number*pi/4,0)
qc.u1(number*pi/2,1)
qc.u1(number*pi,2)
qc.draw('mpl')
backend = Aer.get_backend("statevector_simulator")
sv = execute(qc, backend=backend).result().get_statevector()
plot_bloch_multivector(sv)
print ('The statevectors are:\n', sv.round(1))
print ('Angle subtended by each states (as a factor of pi):\n',(np.angle(sv)/np.pi).round(2))
qc = inverse_qft(qc,nqubits)
qc.measure_all()
qc.draw('mpl')
backend = Aer.get_backend("qasm_simulator")
shots = 2048
job = execute(qc, backend=backend, shots=shots, optimization_level=3)
counts = job.result().get_counts()
plot_histogram(counts)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit.circuit.library import RealAmplitudes
from qiskit.algorithms.optimizers import COBYLA
from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver, SamplingVQE
from qiskit.primitives import Sampler
from qiskit_optimization.converters import LinearEqualityToPenalty
from qiskit_optimization.algorithms import MinimumEigenOptimizer
from qiskit_optimization.translators import from_docplex_mp
from qiskit.utils import algorithm_globals
import numpy as np
import matplotlib.pyplot as plt
from docplex.mp.model import Model
algorithm_globals.random_seed = 123456
# prepare problem instance
n = 6 # number of assets
q = 0.5 # risk factor
budget = n // 2 # budget
penalty = 2 * n # scaling of penalty term
# instance from [1]
mu = np.array([0.7313, 0.9893, 0.2725, 0.8750, 0.7667, 0.3622])
sigma = np.array(
[
[0.7312, -0.6233, 0.4689, -0.5452, -0.0082, -0.3809],
[-0.6233, 2.4732, -0.7538, 2.4659, -0.0733, 0.8945],
[0.4689, -0.7538, 1.1543, -1.4095, 0.0007, -0.4301],
[-0.5452, 2.4659, -1.4095, 3.5067, 0.2012, 1.0922],
[-0.0082, -0.0733, 0.0007, 0.2012, 0.6231, 0.1509],
[-0.3809, 0.8945, -0.4301, 1.0922, 0.1509, 0.8992],
]
)
# or create random instance
# mu, sigma = portfolio.random_model(n, seed=123) # expected returns and covariance matrix
# create docplex model
mdl = Model("portfolio_optimization")
x = mdl.binary_var_list(range(n), name="x")
objective = mdl.sum([mu[i] * x[i] for i in range(n)])
objective -= q * mdl.sum([sigma[i, j] * x[i] * x[j] for i in range(n) for j in range(n)])
mdl.maximize(objective)
mdl.add_constraint(mdl.sum(x[i] for i in range(n)) == budget)
# case to
qp = from_docplex_mp(mdl)
# solve classically as reference
opt_result = MinimumEigenOptimizer(NumPyMinimumEigensolver()).solve(qp)
print(opt_result.prettyprint())
# we convert the problem to an unconstrained problem for further analysis,
# otherwise this would not be necessary as the MinimumEigenSolver would do this
# translation automatically
linear2penalty = LinearEqualityToPenalty(penalty=penalty)
qp = linear2penalty.convert(qp)
_, offset = qp.to_ising()
# set classical optimizer
maxiter = 100
optimizer = COBYLA(maxiter=maxiter)
# set variational ansatz
ansatz = RealAmplitudes(n, reps=1)
m = ansatz.num_parameters
# set sampler
sampler = Sampler()
# run variational optimization for different values of alpha
alphas = [1.0, 0.50, 0.25] # confidence levels to be evaluated
# dictionaries to store optimization progress and results
objectives = {alpha: [] for alpha in alphas} # set of tested objective functions w.r.t. alpha
results = {} # results of minimum eigensolver w.r.t alpha
# callback to store intermediate results
def callback(i, params, obj, stddev, alpha):
# we translate the objective from the internal Ising representation
# to the original optimization problem
objectives[alpha].append(np.real_if_close(-(obj + offset)))
# loop over all given alpha values
for alpha in alphas:
# initialize SamplingVQE using CVaR
vqe = SamplingVQE(
sampler=sampler,
ansatz=ansatz,
optimizer=optimizer,
aggregation=alpha,
callback=lambda i, params, obj, stddev: callback(i, params, obj, stddev, alpha),
)
# initialize optimization algorithm based on CVaR-SamplingVQE
opt_alg = MinimumEigenOptimizer(vqe)
# solve problem
results[alpha] = opt_alg.solve(qp)
# print results
print("alpha = {}:".format(alpha))
print(results[alpha].prettyprint())
print()
# plot resulting history of objective values
plt.figure(figsize=(10, 5))
plt.plot([0, maxiter], [opt_result.fval, opt_result.fval], "r--", linewidth=2, label="optimum")
for alpha in alphas:
plt.plot(objectives[alpha], label="alpha = %.2f" % alpha, linewidth=2)
plt.legend(loc="lower right", fontsize=14)
plt.xlim(0, maxiter)
plt.xticks(fontsize=14)
plt.xlabel("iterations", fontsize=14)
plt.yticks(fontsize=14)
plt.ylabel("objective value", fontsize=14)
plt.show()
# evaluate and sort all objective values
objective_values = np.zeros(2**n)
for i in range(2**n):
x_bin = ("{0:0%sb}" % n).format(i)
x = [0 if x_ == "0" else 1 for x_ in reversed(x_bin)]
objective_values[i] = qp.objective.evaluate(x)
ind = np.argsort(objective_values)
# evaluate final optimal probability for each alpha
for alpha in alphas:
probabilities = np.fromiter(
results[alpha].min_eigen_solver_result.eigenstate.binary_probabilities().values(),
dtype=float,
)
print("optimal probability (alpha = %.2f): %.4f" % (alpha, probabilities[ind][-1:]))
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
# If you introduce a list with less colors than bars, the color of the bars will
# alternate following the sequence from the list.
import numpy as np
from qiskit.quantum_info import DensityMatrix
from qiskit import QuantumCircuit
from qiskit.visualization import plot_state_paulivec
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
qc = QuantumCircuit(2)
qc.h([0, 1])
qc.cz(0, 1)
qc.ry(np.pi/3, 0)
qc.rx(np.pi/5, 1)
matrix = DensityMatrix(qc)
plot_state_paulivec(matrix, color=['crimson', 'midnightblue', 'seagreen'])
|
https://github.com/QForestCommunity/launchpad
|
QForestCommunity
|
import qiskit
qiskit.__qiskit_version__
from qiskit import QuantumCircuit, BasicAer, execute
from qiskit.visualization import plot_histogram
qcSwap = QuantumCircuit(2, 2) #create a quantum circuit with 2 quantum bits and 2 classical bits.
qcSwap.x(0) #apply a pauli X gate to the first qubit to better demonstrate the swap.
qcSwap.swap(0, 1) #apply a swap gate on the first and second qubits.
qcSwap.measure([0, 1], [0, 1]) #measure the qubits to see what their states end up being
qcSwap.draw(output = "mpl") #draw the circuit.
backend = BasicAer.get_backend("statevector_simulator")
state = execute(qcSwap, backend, shots=1024).result().get_counts()
#the initial state should've been '01' before the swap,
#go ahead and comment the swap gate out and run the code!
#the state is '01' before the swap because of qiskit's little endian encoding.
print(state)
n = 4 #number of data qubits.
ancilla = n #number of ancillary qubits is the same as number of qubits in this example.
#number of classical registers is equal to the number of data qubits, since we want the values of only those.
qcShift = QuantumCircuit(n + ancilla, n)
seed = "1011" #this is the initial value of our data qubits.
seed = list(map(int, list(seed)))[::-1] #reverse the list to follow qiskit's encoding scheme.
#to encode the seed, when we encounter a 1, we apply a pauli x gate.
for bit in range(len(seed)):
if seed[bit] == 1:
qcShift.x(bit)
qcShift.barrier(range(n + ancilla)) #add a barrier to mark the end of the encoding phase.
#to apply the swap gates
for qubit in range(1, n + ancilla)[::-1]:
qcShift.swap(qubit, qubit - 1)
qcShift.barrier(range(n + ancilla)) #add a barrier to mark the end of the swapping phase.
#measure the values of the data qubits.
qcShift.measure(range(n), range(n))
qcShift.barrier(range(n + ancilla)) #add a barrier to mark the end of the measuring phase.
qcShift.draw(output = "mpl")
def create_shift_gate(n:int, circular:bool = False):
"""Creates a gate out of a shift circuit.
Args:
n : number of data qubits.
seed : initial state of the data qubits.
circular : flag indicating whether the shift register is circular in nature or not.
"""
if circular:
name = "Circular Left Shift"
else:
name = "Left Shift"
ancilla = n
#n data qubits and the same number of ancillary qubits and one extra qubit to act as the control
#bit for deciding if the operation should be a left shift or a circular left shift.
shiftGate = QuantumCircuit(n + ancilla + 1, name=name)
for qubit in range(1, n + ancilla)[::-1]:
shiftGate.swap(qubit, qubit - 1)
#implement the controlled swap.
shiftGate.cx(0, n)
shiftGate.toffoli(n + ancilla, n, 0)
shiftGate.cx(0, n)
return shiftGate.to_gate()
n = 4
seed = '1011'
ancilla = n
#n data qubits and the same number of ancillary qubits and one extra qubit to act as the control
#bit for deciding if the operation should be a left shift or a circular left shift.
shiftCirc = QuantumCircuit(n + ancilla + 1, n)
seed = list(map(int, list(seed)))[::-1]
circular = True
#encode the circuit
for bit in range(len(seed)):
if seed[bit] == 1:
shiftCirc.x(bit)
if circular:
shiftCirc.x(n + ancilla) #encode the control qubit.
shiftCirc.barrier(range(n + ancilla + 1))
shiftGate = create_shift_gate(n, circular)
#perform 2 shift operations.
shiftCirc.append(shiftGate, range(n + ancilla + 1))
shiftCirc.append(shiftGate, range(n + ancilla + 1))
shiftCirc.barrier(range(n + ancilla + 1))
#get the state of the data qubits.
shiftCirc.measure(range(n), range(n))
shiftCirc.barrier(range(n + ancilla))
#draw the circuit.
shiftCirc.draw(output="mpl")
#get the state of the shift register
backend = BasicAer.get_backend("statevector_simulator")
register_state = execute(shiftCirc, backend, shots=1024).result().get_counts()
plot_histogram(register_state)
#as it can be seen, the state of the register is '1110' which is what
#you would get by performing two left shift operations circularly.
#to see what the shift gate is acutally made up of.
seeShiftGate = QuantumCircuit(n + ancilla + 1)
seeShiftGate.append(shiftGate, range(n + ancilla + 1))
seeShiftGate.decompose().draw(output = "mpl")
#q8 is the control qubit. q0-q3 are the data qubits and q4-q7 are the ancillary qubits.
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
# You can set a color for all the bars.
from qiskit import QuantumCircuit
from qiskit.quantum_info import Statevector
from qiskit.visualization import plot_state_paulivec
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
state = Statevector(qc)
plot_state_paulivec(state, color='midnightblue', title="New PauliVec plot")
|
https://github.com/2lambda123/Qiskit-qiskit
|
2lambda123
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""
Kraus representation of a Quantum Channel.
"""
from __future__ import annotations
import copy
import math
from numbers import Number
import numpy as np
from qiskit import circuit
from qiskit.circuit.quantumcircuit import QuantumCircuit
from qiskit.circuit.instruction import Instruction
from qiskit.exceptions import QiskitError
from qiskit.quantum_info.operators.predicates import is_identity_matrix
from qiskit.quantum_info.operators.channel.quantum_channel import QuantumChannel
from qiskit.quantum_info.operators.op_shape import OpShape
from qiskit.quantum_info.operators.channel.choi import Choi
from qiskit.quantum_info.operators.channel.superop import SuperOp
from qiskit.quantum_info.operators.channel.transformations import _to_kraus
from qiskit.quantum_info.operators.mixins import generate_apidocs
from qiskit.quantum_info.operators.base_operator import BaseOperator
class Kraus(QuantumChannel):
r"""Kraus representation of a quantum channel.
For a quantum channel :math:`\mathcal{E}`, the Kraus representation is
given by a set of matrices :math:`[A_0,...,A_{K-1}]` such that the
evolution of a :class:`~qiskit.quantum_info.DensityMatrix`
:math:`\rho` is given by
.. math::
\mathcal{E}(\rho) = \sum_{i=0}^{K-1} A_i \rho A_i^\dagger
A general operator map :math:`\mathcal{G}` can also be written using the
generalized Kraus representation which is given by two sets of matrices
:math:`[A_0,...,A_{K-1}]`, :math:`[B_0,...,A_{B-1}]` such that
.. math::
\mathcal{G}(\rho) = \sum_{i=0}^{K-1} A_i \rho B_i^\dagger
See reference [1] for further details.
References:
1. C.J. Wood, J.D. Biamonte, D.G. Cory, *Tensor networks and graphical calculus
for open quantum systems*, Quant. Inf. Comp. 15, 0579-0811 (2015).
`arXiv:1111.6950 [quant-ph] <https://arxiv.org/abs/1111.6950>`_
"""
def __init__(
self,
data: QuantumCircuit | circuit.instruction.Instruction | BaseOperator | np.ndarray,
input_dims: tuple | None = None,
output_dims: tuple | None = None,
):
"""Initialize a quantum channel Kraus operator.
Args:
data: data to initialize superoperator.
input_dims: the input subsystem dimensions.
output_dims: the output subsystem dimensions.
Raises:
QiskitError: if input data cannot be initialized as a list of Kraus matrices.
Additional Information:
If the input or output dimensions are None, they will be
automatically determined from the input data. If the input data is
a list of Numpy arrays of shape :math:`(2^N,\\,2^N)` qubit systems will be
used. If the input does not correspond to an N-qubit channel, it
will assign a single subsystem with dimension specified by the
shape of the input.
"""
# If the input is a list or tuple we assume it is a list of Kraus
# matrices, if it is a numpy array we assume that it is a single Kraus
# operator
# TODO properly handle array construction from ragged data (like tuple(np.ndarray, None))
# and document these accepted input cases. See also Qiskit/qiskit-terra#9307.
if isinstance(data, (list, tuple, np.ndarray)):
# Check if it is a single unitary matrix A for channel:
# E(rho) = A * rho * A^\dagger
if _is_matrix(data):
# Convert single Kraus op to general Kraus pair
kraus = ([np.asarray(data, dtype=complex)], None)
shape = kraus[0][0].shape
# Check if single Kraus set [A_i] for channel:
# E(rho) = sum_i A_i * rho * A_i^dagger
elif isinstance(data, list) and len(data) > 0:
# Get dimensions from first Kraus op
kraus = [np.asarray(data[0], dtype=complex)]
shape = kraus[0].shape
# Iterate over remaining ops and check they are same shape
for i in data[1:]:
op = np.asarray(i, dtype=complex)
if op.shape != shape:
raise QiskitError("Kraus operators are different dimensions.")
kraus.append(op)
# Convert single Kraus set to general Kraus pair
kraus = (kraus, None)
# Check if generalized Kraus set ([A_i], [B_i]) for channel:
# E(rho) = sum_i A_i * rho * B_i^dagger
elif isinstance(data, tuple) and len(data) == 2 and len(data[0]) > 0:
kraus_left = [np.asarray(data[0][0], dtype=complex)]
shape = kraus_left[0].shape
for i in data[0][1:]:
op = np.asarray(i, dtype=complex)
if op.shape != shape:
raise QiskitError("Kraus operators are different dimensions.")
kraus_left.append(op)
if data[1] is None:
kraus = (kraus_left, None)
else:
kraus_right = []
for i in data[1]:
op = np.asarray(i, dtype=complex)
if op.shape != shape:
raise QiskitError("Kraus operators are different dimensions.")
kraus_right.append(op)
kraus = (kraus_left, kraus_right)
else:
raise QiskitError("Invalid input for Kraus channel.")
op_shape = OpShape.auto(dims_l=output_dims, dims_r=input_dims, shape=kraus[0][0].shape)
else:
# Otherwise we initialize by conversion from another Qiskit
# object into the QuantumChannel.
if isinstance(data, (QuantumCircuit, Instruction)):
# If the input is a Terra QuantumCircuit or Instruction we
# convert it to a SuperOp
data = SuperOp._init_instruction(data)
else:
# We use the QuantumChannel init transform to initialize
# other objects into a QuantumChannel or Operator object.
data = self._init_transformer(data)
op_shape = data._op_shape
output_dim, input_dim = op_shape.shape
# Now that the input is an operator we convert it to a Kraus
rep = getattr(data, "_channel_rep", "Operator")
kraus = _to_kraus(rep, data._data, input_dim, output_dim)
# Initialize either single or general Kraus
if kraus[1] is None or np.allclose(kraus[0], kraus[1]):
# Standard Kraus map
data = (kraus[0], None)
else:
# General (non-CPTP) Kraus map
data = kraus
super().__init__(data, op_shape=op_shape)
@property
def data(self):
"""Return list of Kraus matrices for channel."""
if self._data[1] is None:
# If only a single Kraus set, don't return the tuple
# Just the fist set
return self._data[0]
else:
# Otherwise return the tuple of both kraus sets
return self._data
def is_cptp(self, atol=None, rtol=None):
"""Return True if completely-positive trace-preserving."""
if self._data[1] is not None:
return False
if atol is None:
atol = self.atol
if rtol is None:
rtol = self.rtol
accum = 0j
for op in self._data[0]:
accum += np.dot(np.transpose(np.conj(op)), op)
return is_identity_matrix(accum, rtol=rtol, atol=atol)
def _evolve(self, state, qargs=None):
return SuperOp(self)._evolve(state, qargs)
# ---------------------------------------------------------------------
# BaseOperator methods
# ---------------------------------------------------------------------
def conjugate(self):
ret = copy.copy(self)
kraus_l, kraus_r = self._data
kraus_l = [np.conj(k) for k in kraus_l]
if kraus_r is not None:
kraus_r = [k.conj() for k in kraus_r]
ret._data = (kraus_l, kraus_r)
return ret
def transpose(self):
ret = copy.copy(self)
ret._op_shape = self._op_shape.transpose()
kraus_l, kraus_r = self._data
kraus_l = [np.transpose(k) for k in kraus_l]
if kraus_r is not None:
kraus_r = [np.transpose(k) for k in kraus_r]
ret._data = (kraus_l, kraus_r)
return ret
def adjoint(self):
ret = copy.copy(self)
ret._op_shape = self._op_shape.transpose()
kraus_l, kraus_r = self._data
kraus_l = [np.conj(np.transpose(k)) for k in kraus_l]
if kraus_r is not None:
kraus_r = [np.conj(np.transpose(k)) for k in kraus_r]
ret._data = (kraus_l, kraus_r)
return ret
def compose(self, other: Kraus, qargs: list | None = None, front: bool = False) -> Kraus:
if qargs is None:
qargs = getattr(other, "qargs", None)
if qargs is not None:
return Kraus(SuperOp(self).compose(other, qargs=qargs, front=front))
if not isinstance(other, Kraus):
other = Kraus(other)
new_shape = self._op_shape.compose(other._op_shape, qargs, front)
input_dims = new_shape.dims_r()
output_dims = new_shape.dims_l()
if front:
ka_l, ka_r = self._data
kb_l, kb_r = other._data
else:
ka_l, ka_r = other._data
kb_l, kb_r = self._data
kab_l = [np.dot(a, b) for a in ka_l for b in kb_l]
if ka_r is None and kb_r is None:
kab_r = None
elif ka_r is None:
kab_r = [np.dot(a, b) for a in ka_l for b in kb_r]
elif kb_r is None:
kab_r = [np.dot(a, b) for a in ka_r for b in kb_l]
else:
kab_r = [np.dot(a, b) for a in ka_r for b in kb_r]
ret = Kraus((kab_l, kab_r), input_dims, output_dims)
ret._op_shape = new_shape
return ret
def tensor(self, other: Kraus) -> Kraus:
if not isinstance(other, Kraus):
other = Kraus(other)
return self._tensor(self, other)
def expand(self, other: Kraus) -> Kraus:
if not isinstance(other, Kraus):
other = Kraus(other)
return self._tensor(other, self)
@classmethod
def _tensor(cls, a, b):
ret = copy.copy(a)
ret._op_shape = a._op_shape.tensor(b._op_shape)
# Get tensor matrix
ka_l, ka_r = a._data
kb_l, kb_r = b._data
kab_l = [np.kron(ka, kb) for ka in ka_l for kb in kb_l]
if ka_r is None and kb_r is None:
kab_r = None
else:
if ka_r is None:
ka_r = ka_l
if kb_r is None:
kb_r = kb_l
kab_r = [np.kron(a, b) for a in ka_r for b in kb_r]
ret._data = (kab_l, kab_r)
return ret
def __add__(self, other):
qargs = getattr(other, "qargs", None)
if not isinstance(other, QuantumChannel):
other = Choi(other)
return self._add(other, qargs=qargs)
def __sub__(self, other):
qargs = getattr(other, "qargs", None)
if not isinstance(other, QuantumChannel):
other = Choi(other)
return self._add(-other, qargs=qargs)
def _add(self, other, qargs=None):
# Since we cannot directly add two channels in the Kraus
# representation we try and use the other channels method
# or convert to the Choi representation
return Kraus(Choi(self)._add(other, qargs=qargs))
def _multiply(self, other):
if not isinstance(other, Number):
raise QiskitError("other is not a number")
ret = copy.copy(self)
# If the number is complex we need to convert to general
# kraus channel so we multiply via Choi representation
if isinstance(other, complex) or other < 0:
# Convert to Choi-matrix
ret._data = Kraus(Choi(self)._multiply(other))._data
return ret
# If the number is real we can update the Kraus operators
# directly
val = math.sqrt(other)
kraus_r = None
kraus_l = [val * k for k in self._data[0]]
if self._data[1] is not None:
kraus_r = [val * k for k in self._data[1]]
ret._data = (kraus_l, kraus_r)
return ret
def _is_matrix(data):
# return True if data is a 2-d array/tuple/list
if not isinstance(data, np.ndarray):
data = np.array(data, dtype=object)
return data.ndim == 2
# Update docstrings for API docs
generate_apidocs(Kraus)
|
https://github.com/Yadu9238/Shor-Algo
|
Yadu9238
|
from qiskit import BasicAer
from qiskit.aqua import QuantumInstance
from qiskit.aqua.algorithms import Shor
N = 15
shor = Shor(N)
backend = BasicAer.get_backend('qasm_simulator')
quantum_instance = QuantumInstance(backend, shots=1024)
ret = shor.run(quantum_instance)
print("The list of factors of {} as computed by the Shor's algorithm is {}.".format(N, ret['factors'][0]))
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
# You can set a color for all the bars.
from qiskit import QuantumCircuit
from qiskit.quantum_info import Statevector
from qiskit.visualization import plot_state_paulivec
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
state = Statevector(qc)
plot_state_paulivec(state, color='midnightblue', title="New PauliVec plot")
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit.utils import algorithm_globals
algorithm_globals.random_seed = 12345
from qiskit_machine_learning.datasets import ad_hoc_data
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,
)
import matplotlib.pyplot as plt
import numpy as np
def plot_features(ax, features, labels, class_label, marker, face, edge, label):
# A train plot
ax.scatter(
# x coordinate of labels where class is class_label
features[np.where(labels[:] == class_label), 0],
# y coordinate of labels where class is class_label
features[np.where(labels[:] == class_label), 1],
marker=marker,
facecolors=face,
edgecolors=edge,
label=label,
)
def plot_dataset(train_features, train_labels, test_features, test_labels, adhoc_total):
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],
)
# A train plot
plot_features(plt, train_features, train_labels, 0, "s", "w", "b", "A train")
# B train plot
plot_features(plt, train_features, train_labels, 1, "o", "w", "r", "B train")
# A test plot
plot_features(plt, test_features, test_labels, 0, "s", "b", "w", "A test")
# B test plot
plot_features(plt, test_features, test_labels, 1, "o", "r", "w", "B test")
plt.legend(bbox_to_anchor=(1.05, 1), loc="upper left", borderaxespad=0.0)
plt.title("Ad hoc dataset")
plt.show()
plot_dataset(train_features, train_labels, test_features, test_labels, adhoc_total)
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
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)
from sklearn.svm import SVC
adhoc_svc = SVC(kernel=adhoc_kernel.evaluate)
adhoc_svc.fit(train_features, train_labels)
adhoc_score_callable_function = adhoc_svc.score(test_features, test_labels)
print(f"Callable kernel classification test score: {adhoc_score_callable_function}")
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_precomputed_kernel = adhoc_svc.score(adhoc_matrix_test, test_labels)
print(f"Precomputed kernel classification test score: {adhoc_score_precomputed_kernel}")
from qiskit_machine_learning.algorithms import QSVC
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}")
print(f"Classification Model | Accuracy Score")
print(f"---------------------------------------------------------")
print(f"SVC using kernel as a callable function | {adhoc_score_callable_function:10.2f}")
print(f"SVC using precomputed kernel matrix | {adhoc_score_precomputed_kernel:10.2f}")
print(f"QSVC | {qsvc_score:10.2f}")
adhoc_dimension = 2
train_features, train_labels, test_features, test_labels, adhoc_total = ad_hoc_data(
training_size=25,
test_size=0,
n=adhoc_dimension,
gap=0.6,
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],
)
# A label plot
plot_features(plt, train_features, train_labels, 0, "s", "w", "b", "B")
# B label plot
plot_features(plt, train_features, train_labels, 1, "o", "w", "r", "B")
plt.legend(bbox_to_anchor=(1.05, 1), loc="upper left", borderaxespad=0.0)
plt.title("Ad hoc dataset for clustering")
plt.show()
adhoc_feature_map = ZZFeatureMap(feature_dimension=adhoc_dimension, reps=2, entanglement="linear")
adhoc_kernel = FidelityQuantumKernel(feature_map=adhoc_feature_map)
adhoc_matrix = adhoc_kernel.evaluate(x_vec=train_features)
plt.figure(figsize=(5, 5))
plt.imshow(np.asmatrix(adhoc_matrix), interpolation="nearest", origin="upper", cmap="Greens")
plt.title("Ad hoc clustering kernel matrix")
plt.show()
from sklearn.cluster import SpectralClustering
from sklearn.metrics import normalized_mutual_info_score
adhoc_spectral = SpectralClustering(2, affinity="precomputed")
cluster_labels = adhoc_spectral.fit_predict(adhoc_matrix)
cluster_score = normalized_mutual_info_score(cluster_labels, train_labels)
print(f"Clustering score: {cluster_score}")
adhoc_dimension = 2
train_features, train_labels, test_features, test_labels, adhoc_total = ad_hoc_data(
training_size=25,
test_size=10,
n=adhoc_dimension,
gap=0.6,
plot_data=False,
one_hot=False,
include_sample_total=True,
)
plot_dataset(train_features, train_labels, test_features, test_labels, adhoc_total)
feature_map = ZZFeatureMap(feature_dimension=2, reps=2, entanglement="linear")
qpca_kernel = FidelityQuantumKernel(fidelity=fidelity, feature_map=feature_map)
matrix_train = qpca_kernel.evaluate(x_vec=train_features)
matrix_test = qpca_kernel.evaluate(x_vec=test_features, y_vec=test_features)
from sklearn.decomposition import KernelPCA
kernel_pca_rbf = KernelPCA(n_components=2, kernel="rbf")
kernel_pca_rbf.fit(train_features)
train_features_rbf = kernel_pca_rbf.transform(train_features)
test_features_rbf = kernel_pca_rbf.transform(test_features)
kernel_pca_q = KernelPCA(n_components=2, kernel="precomputed")
train_features_q = kernel_pca_q.fit_transform(matrix_train)
test_features_q = kernel_pca_q.fit_transform(matrix_test)
from sklearn.linear_model import LogisticRegression
logistic_regression = LogisticRegression()
logistic_regression.fit(train_features_q, train_labels)
logistic_score = logistic_regression.score(test_features_q, test_labels)
print(f"Logistic regression score: {logistic_score}")
fig, (q_ax, rbf_ax) = plt.subplots(1, 2, figsize=(10, 5))
plot_features(q_ax, train_features_q, train_labels, 0, "s", "w", "b", "A train")
plot_features(q_ax, train_features_q, train_labels, 1, "o", "w", "r", "B train")
plot_features(q_ax, test_features_q, test_labels, 0, "s", "b", "w", "A test")
plot_features(q_ax, test_features_q, test_labels, 1, "o", "r", "w", "A test")
q_ax.set_ylabel("Principal component #1")
q_ax.set_xlabel("Principal component #0")
q_ax.set_title("Projection of training and test data\n using KPCA with Quantum Kernel")
# Plotting the linear separation
h = 0.01 # step size in the mesh
# create a mesh to plot in
x_min, x_max = train_features_q[:, 0].min() - 1, train_features_q[:, 0].max() + 1
y_min, y_max = train_features_q[:, 1].min() - 1, train_features_q[:, 1].max() + 1
xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))
predictions = logistic_regression.predict(np.c_[xx.ravel(), yy.ravel()])
# Put the result into a color plot
predictions = predictions.reshape(xx.shape)
q_ax.contourf(xx, yy, predictions, cmap=plt.cm.RdBu, alpha=0.2)
plot_features(rbf_ax, train_features_rbf, train_labels, 0, "s", "w", "b", "A train")
plot_features(rbf_ax, train_features_rbf, train_labels, 1, "o", "w", "r", "B train")
plot_features(rbf_ax, test_features_rbf, test_labels, 0, "s", "b", "w", "A test")
plot_features(rbf_ax, test_features_rbf, test_labels, 1, "o", "r", "w", "A test")
rbf_ax.set_ylabel("Principal component #1")
rbf_ax.set_xlabel("Principal component #0")
rbf_ax.set_title("Projection of training data\n using KernelPCA")
plt.show()
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/mnp-club/Quantum_Computing_Workshop_2020
|
mnp-club
|
#Declaring variables
a = 2
print(a)
print(type(a)) #This is an integer
#True and False are special keywords in python
boolean = True
print(boolean)
print(type(boolean))
#Here 7e-2 is 7x10^-2 and the 1j actually is the square root of -1
b = 7e-2 + (8e-2)*1j
print(b)
print(type(b)) # This is a complex number
#We will now try to re initiallize variable a and it will change its class
a = 7.2
print(a)
print(type(a)) #this is a float
string = "a word"
print(string)
print(type(string))
#Type conversions can be done too
a_s = str(a)
bool3 = bool(a)
print(a_s)
print(type(a_s))
print(bool3)
print(type(bool3))
#we also have lists, dictionaries and tuples
list1 = [1,2,3,4,5,6,"word"] # A list. Same as an array and is dynamic in length
dict1 = {1: 3, 'k':'f'} #A dictionary. This maps the first one as index to the second term as value
tuple1 = (1,2,4,5,0,-1,dict1) #A tuple. This is a collection of objects which get reordered are cannot be changed once assigned (immutable)
print(list1)
print(type(list1))
print(dict1)
print(type(dict1))
print(tuple1)
print(type(tuple1))
print(list1[-1])#Prints last index
print(dict1['k'])#Prints the mapped value to 'k'
#Using is
var1 = 78
tuple2 = (1,2,4,5,0,-1,dict1)
print(var1 is 78)#This will be true
print(tuple1 is tuple2)#This will be false since tuples,lists and dicts essentially are addresses
#Hence even when they have same value, is requires also same addresses
print(tuple1 == tuple2)#This shows true since == checks equality in values
print(tuple1[-1] is tuple1[-1])#This is true since these both point to the same variable
var2 = 1
print(var2 in list1)#Shows true since var2 is infact in this list
bool1 = True
bool2 = False
print(bool1 and bool2)
print(bool1 or bool2)
print(not bool2)
if bool1:
print('bool1 is true')#This one is executed as per our declarations
elif not bool2:
print('bool2 is false and so is bool1')#This one isnt reached
else:
print('bool1 is false but bool2 is true')#This one isnt reached
for i in list1:
print(i)
for i in range(10):#iterates over numbers 0 to 9 both included
print(i)
print(" ")
for i in range(1,10):#iterates over numbers 1 to 9 both included
print(i)
for k,d in dict1.items():
print(k,d)
g = 100
while(g > 0):
g = g//2#This returns the integer division of g
print(g)
def myfunc(a):#takes an input of a
return a*2 #returns the double of a
print(myfunc(2))#Calls function giving 2 as input
print(myfunc(3.4 + 4j))
print(myfunc(list1))
def myfunc2(*args):# we use *args when we do not know how many arguments will be sent
s = 0
for i in args:
s = s + i
return s
print(myfunc2(34))
print(myfunc2(34,35,36))
def myfunc3(**kwargs):#we use **kwargs when we are to receive unkown number of keyword arguments
#A keyword argument is where you provide a name to the variable as you pass it into the function.
for i,j in kwargs.items():
print(i,j)
myfunc3(x1 = 1, x2 = "abcd", x3 = list1)
add = lambda a,b: a+b #A lamda function takes arguments and returns only one value
print(add(list1,list1)) #essentially adds the list to itself
import numpy as np #imports the package numpy and we have renamed it to np so our code looks cleaner
print(np.pi)#Good old pi
arr = np.array([[1,3],[4,2]])#Essentially an array and the argument given
print(arr)
print(arr.shape)#this gives the shape of the arr
arr2 = np.array([[0.3,8j],[9j,0]])
arr3 = np.matmul(arr2,arr)#this will give the matrix multiplication of arr2*arr
print(arr3)
|
https://github.com/rodneyosodo/variational-quantum-classifier-on-heartattack
|
rodneyosodo
|
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
pd.set_option('display.max_rows', None)
pd.set_option('display.max_columns', None)
pd.set_option('display.width', None)
pd.set_option('display.max_colwidth', -1)
df = pd.read_csv("../../Data/Processed/costs.csv")
df.columns = ['Spec', "CostValues"]
df.head(1)
df['Spec']
def check_lowest_cost():
"""
Checks the configs which attained the lowest sost
"""
cost = []
lowest_cost = []
for i in range(df.shape[0]):
data = [float(x.replace("[", "").replace("]", "")) for x in df['CostValues'][i].split(',')]
lowest_cost.append(data[len(data) - 1])
lowest_cost = sorted(lowest_cost)[:80]
# for m in lowest_cost:
for i in range(df.shape[0]):
data = df['CostValues'][i].split(',')
data = [float(x.replace("[", "").replace("]", "")) for x in data]
# if float(m) == float(data[len(data) - 1]):
# print("{} : Cost: {}".format(df["Spec"][i], data[len(data) - 1]))
cost.append(data[len(data) - 1])
print(len(cost))
df['exel'] = cost
df.to_excel("n.xlsx")
check_lowest_cost()
# Plotting all
for i in range(df.shape[0]):
fig = plt.figure()
data = df['CostValues'][i].split(',')
data = [float(x.replace("[", "").replace("]", "")) for x in data]
plt.plot(range(0, len(data), 1), data)
plt.xlabel('Steps')
plt.ylabel('Cost value')
plt.title(str(df['Spec'][i]))
plt.show()
path = '../../Output/Figures/{}.jpeg'.format(df['Spec'][i].replace("(", "").replace("FeatureMap", "").replace(")", "").replace(",", "").replace("=", "").replace(" ", "").replace("_", ""))
# fig.savefig(path)
def plot_individual_optimizers(Optimizers):
for opt in Optimizers:
max_iter = 0
fig = plt.figure(figsize=(20,20))
for i in range(df.shape[0]):
if df['Spec'][i].__contains__(opt):
data = [float(x.replace("[", "").replace("]", "")) for x in df['CostValues'][i].split(',')]
if len(data) >= max_iter:
max_iter = len(data)
for i in range(df.shape[0]):
if df['Spec'][i].__contains__(opt):
data = df['CostValues'][i].split(',')
data = [float(x.replace("[", "").replace("]", "")) for x in data]
if max_iter >= len(data):
temp = np.full((max_iter, ), data[len(data) -1])
temp[:len(data)] = data
data = temp
plt.plot(range(0, len(data), 1), data, label='{}'.format(df['Spec'][i].replace("(", "").replace("FeatureMap", "").replace(")", "").replace(",", "").replace("=", "").replace(" ", "").replace("_", "")))
plt.xlabel('Steps')
plt.ylabel('Cost value')
plt.title(opt)
plt.legend()
plt.show()
plot_individual_optimizers(["COBYLA", "SPSA", "ADAM"])
def plot_increase_vdepth(optimizer, featuremap, reps, checking):
points = []
for i in range(df.shape[0]):
title = str(df['Spec'][i])
if title.split("(")[0] == featuremap and str(title).__contains__(optimizer) and str(title).__contains__("reps={}".format(reps)):
points.append(float(df['CostValues'][i].split(',')[-1].replace("[", "").replace("]", "")))
fig = plt.figure()
plt.plot(range(0, len(points), 1), points)
plt.xlabel(checking)
plt.ylabel('Cost value')
plt.title("{} {} featuremap {} fdepth".format(optimizer, featuremap, reps))
plt.show()
def plot_increase_fdepth(optimizer, featuremap, fdepth, checking):
points = []
for i in range(df.shape[0]):
title = str(df['Spec'][i])
if title.split("(")[0] == featuremap and str(title).__contains__(optimizer) and str(title).__contains__("vdepth {}".format(fdepth)):
points.append(float(df['CostValues'][i].split(',')[-1].replace("[", "").replace("]", "")))
fig = plt.figure()
plt.plot(range(0, len(points), 1), points)
plt.xlabel(checking)
plt.ylabel('Cost value')
plt.title("{} {} featuremap {} vdepth".format(optimizer, featuremap, fdepth))
plt.show()
plot_increase_vdepth("SPSA", "PauliFeatureMap", 1, "fdepth")
plot_increase_fdepth("SPSA", "PauliFeatureMap", 1, "vdepth")
for opt in ['SPSA', "COBYLA", "ADAM"]:
for fmap in ['ZZFeatureMap', 'ZFeatureMap', "PauliFeatureMap"]:
for fdepth in [1, 2, 4]:
plot_increase_vdepth(opt, fmap, fdepth, "vdepth")
for opt in ['SPSA', "COBYLA", "ADAM"]:
for fmap in ['ZZFeatureMap', 'ZFeatureMap', "PauliFeatureMap"]:
for fdepth in [1, 3, 5]:
plot_increase_fdepth(opt, fmap, fdepth, "fdepth")
|
https://github.com/SultanMS/Qiskit_Tutorial
|
SultanMS
|
%matplotlib inline
# Importing standard Qiskit libraries and configuring account
from qiskit import QuantumCircuit, execute, Aer, IBMQ
from qiskit.compiler import transpile, assemble
from qiskit.tools.jupyter import *
from qiskit.visualization import *
# Loading your IBM Q account(s)
provider = IBMQ.load_account()
import qiskit as q
import math # for Pi and other math functions
from qiskit.visualization import plot_histogram, plot_bloch_multivector
qasm_sim= q.Aer.get_backend("qasm_simulator") #Choose to run the code on a simulator or a real quantum computer
statevec_sim = q.Aer.get_backend("statevector_simulator")
print("done setup")
# This circuit to practice Qiskit (gives hints to HW5)
c = q.QuantumCircuit(4,3) # create a circuit with 4 qubits and 3 cbits. The cbits are needed to store the measerued qubits values.
c.rx(math.pi/2, 0) # Rotate qbit-0 90 degrees on X
c.ry(math.pi/4, 1) # Rorate qbit-1 45 degrees on Y
c.h(2) # apply H gate on qbit-2
c.cnot(0,3) # apply CNot gate on qubits (0 and 1)
c.cnot(1,3) # apply CNot gate on qubits (1 and 3)
c.cnot(2,3) # apply CNot gate on qubits (2 and 3)
c.rz(math.pi/4, 2) # Rotate qbit-2 45 degrees on Z
c.h(2) # Apply H gate again on qbit-2
c.measure([0,1,2], [0,1,2]) # measure qubits [0,1,2] and store the results in cbit [0,1,2]
psi0 = q.execute(c,backend=statevec_sim).result().get_statevector()
print("Done.. Draw circuit:")
c.draw()
plot_bloch_multivector(psi0)
count1 = q.execute(c,backend=qasm_sim, shots=1024).result().get_counts()
plot_histogram([count1], legend=['counts'] )
|
https://github.com/usamisaori/qLipschitz
|
usamisaori
|
import pennylane as qml
import numpy as np
from pennylane.optimize import AdamOptimizer
import matplotlib.pyplot as plt
def loadData(filename):
return_data = []
return_label = []
with open(filename, 'r') as file:
for row in file:
data = row.split(' ')[:-1]
data = [ float(d) for d in data ]
label = int(row.split(' ')[-1])
return_data.append(data)
return_label.append(label)
return np.array(return_data), np.array(return_label)
X_train, Y_train = loadData('./data/training_set.txt')
X_test, Y_test = loadData('./data/testing_set.txt')
print(X_train[:10])
print(Y_train[:10])
plt.scatter(X_train[:, 0], X_train[:, 1], c=Y_train)
plt.show()
print(f'total datas: {len(X_train)}')
print(f'label 0 datas: {len(list(filter(lambda x: x==0, Y_train)))}')
print(f'label 0 datas: {len(list(filter(lambda x: x==1, Y_train)))}')
def rotateDatas(X, Y):
gen_X = []
gen_Y = []
for i, data in enumerate(X):
gen_X.append(list(reversed(data)))
gen_Y.append(Y[i])
return np.array(gen_X), np.array(gen_Y)
X_train_rotate, Y_train_rotate = rotateDatas(X_train, Y_train)
plt.scatter(X_train_rotate[:, 0], X_train_rotate[:, 1], c=Y_train_rotate)
plt.show()
# Concat datas
X_temp = np.zeros((X_train.shape[0] * 2, len(X_train[0])))
X_temp[0:40,:] = X_train
X_temp[40:80,] = X_train_rotate
Y_temp = np.zeros((Y_train.shape[0] * 2))
Y_temp[0:40] = Y_train
Y_temp[40:80] = Y_train_rotate
plt.scatter(X_temp[:, 0], X_temp[:, 1], c=Y_temp)
plt.show()
X_train = X_temp
Y_train = Y_temp
print(f'total datas: {len(X_train)}')
print(f'label 0 datas: {len(list(filter(lambda x: x==0, Y_train)))}')
print(f'label 0 datas: {len(list(filter(lambda x: x==1, Y_train)))}')
Z_train = (X_train[:, 0] ** 2 + X_train[:, 1] ** 2) ** 0.5
# Z_train = (X_train[:, 0] ** 2 + X_train[:, 1] ** 2)
temp = np.zeros((X_train.shape[0], len(X_train[0]) + 1))
temp[:, :-1] = X_train
temp[:, -1] = Z_train
X_train2 = temp
print(X_train2[:10])
Z_test = (X_test[:, 0] ** 2 + X_test[:, 1] ** 2) ** 0.5
# Z_test = (X_test[:, 0] ** 2 + X_test[:, 1] ** 2)
temp = np.zeros((X_test.shape[0], len(X_test[0]) + 1))
temp[:, :-1] = X_test
temp[:, -1] = Z_test
X_test2 = temp
print(X_test2[:10])
def plot3D(X, Y):
fig = plt.figure(figsize=(10, 10))
ax = fig.add_subplot(111, projection='3d')
ax.scatter(
X[:, 0], X[:, 1], X[:, 2],
zdir='z', s=30, c=Y, depthshade=True
)
plt.show()
plot3D(X_train2, Y_train)
print(f'total datas: {len(X_train2)}')
print(f'label 0 datas: {len(list(filter(lambda x: x==0, Y_train)))}')
print(f'label 0 datas: {len(list(filter(lambda x: x==1, Y_train)))}')
qubits_num = 3
layers_num = 2
dev = qml.device("default.qubit",wires=qubits_num)
class VQC:
def __init__(self):
# 3 => U3(theta, phi, lambda)
self.params = (0.01 * np.random.randn(layers_num, qubits_num, 3))
self.bestparams = self.params
self.bestcost = 10
self.opt = AdamOptimizer(0.205)
self.weights = []
self.costs = []
self.accuracies = []
def fit(self, X_train, Y_train, epoch=300):
batch_size = 20
for turn in range(epoch):
# Update the weights by one optimizer step
batch_index = np.random.randint(0, len(X_train), (batch_size,))
X_train_batch = X_train[batch_index]
Y_train_batch = Y_train[batch_index]
self.params = self.opt.step(lambda v: cost(v, X_train_batch, Y_train_batch), self.params)
cost_now = cost(self.params, X_train, Y_train)
acc_now = accuracy(self.params, X_train, Y_train)
if cost_now < self.bestcost:
self.bestcost = cost_now
self.bestparams = self.params
self.weights.append(self.params)
self.costs.append(cost_now)
self.accuracies.append(acc_now)
print(
"Turn: {:5d} | Cost: {:0.7f} | Accuracy: {:0.2f}% ".format(
turn + 1, cost_now, acc_now * 100
))
def score(self, X_test, Y_test):
predictions = [ predict(self.bestparams, data) for data in X_test ]
acc = accuracy(self.bestparams, X_test, Y_test)
print("FINAL ACCURACY: {:0.2f}%".format(acc * 100))
@qml.qnode(dev)
def circuit(params, data):
angles = [ i * np.pi for i in data ]
for i in range(qubits_num):
qml.RX(angles[i], wires=i)
qml.Rot( *params[0, i], wires=i )
qml.CZ(wires=[1, 0])
qml.CZ(wires=[1, 2])
qml.CZ(wires=[0, 2])
for i in range(qubits_num):
qml.Rot( *params[1, i], wires=i )
# PauliZ measure => 1 -> |0> while -1 -> |1>
return qml.expval(qml.PauliZ(0)), qml.expval(qml.PauliZ(1)), qml.expval(qml.PauliZ(2))
import qiskit
import numpy as np
from qiskit import QuantumCircuit
from qiskit import Aer, execute
unitary_backend = Aer.get_backend('unitary_simulator')
qasm_backend = Aer.get_backend('qasm_simulator')
def predict(params, data):
qcircuit = QuantumCircuit(3, 3)
qubits = qcircuit.qubits
for i, d in enumerate(data):
qcircuit.rx(d * np.pi, qubits[i])
for i in range(qubits_num):
qcircuit.u3(*params[0][i], qubits[i])
qcircuit.cz(qubits[0], qubits[1])
qcircuit.cz(qubits[1], qubits[2])
qcircuit.cz(qubits[0], qubits[2])
for i in range(qubits_num):
qcircuit.u3(*params[1][i], qubits[i])
# the measurement
qcircuit.measure([0, 1, 2], [0, 1, 2])
# job execution
shots = 1000
job_sim = execute(qcircuit, qasm_backend, shots=shots)
result_sim = job_sim.result()
counts = result_sim.get_counts(qcircuit)
p1 = (counts.get('100', 0) + counts.get('111', 0) + counts.get('101', 0) + counts.get('110',0)) / shots
if p1 > 0.5:
return 1
else:
return 0
def cost(weights, datas, labels):
loss = 0
for i, data in enumerate(datas):
# like [-1, 1, 1]
measured = circuit(weights, data)
p = measured[2]
if labels[i] == 0:
loss += (1 - p) ** 2
else:
loss += (-1 - p) ** 2
return loss / len(datas)
def accuracy(weights, datas, labels):
predictions = [ predict(weights, data) for data in datas ]
acc = 0
for i, p in enumerate(predictions):
if p == labels[i]:
acc += 1
return acc / len(predictions)
vqc = VQC()
vqc.fit(X_train2, Y_train, epoch=200)
|
https://github.com/shell-raiser/Qiskit-Developer-Certification-Notes-and-Code
|
shell-raiser
|
my_list=[1,3,6,8,4,9,5,7,0,5,2] #list of random numbers
#oracle
def the_oracle(my_input):
winner=7
if my_input is winner:
response = True
else:
response = False
return response
#Searching the Oracle
for index, trial_number in enumerate(my_list):
if the_oracle(trial_number) is True:
print('Winner found at index %i'%index)
print('%i calls to the Oracle used'%(index+1))
break
from qiskit import *
import matplotlib.pyplot as plt
import numpy as np
# define the oracle ckt
oracle = QuantumCircuit(2,name='oracle')
oracle.cz(0,1)
oracle.to_gate()
oracle.draw()
backend = Aer.get_backend('statevector_simulator')
grover_circ = QuantumCircuit(2,2)
grover_circ.h([0,1])
grover_circ.append(oracle,[0,1])
grover_circ.draw()
job = execute(grover_circ, backend)
result = job.result()
sv = result.get_statevector()
np.around(sv,2)
reflection = QuantumCircuit(2,name='reflection')
reflection.h([0,1])
reflection.z([0,1])
reflection.cz(0,1)
reflection.h([0,1])
reflection.to_gate()
reflection.draw()
backend = Aer.get_backend('qasm_simulator')
grover_circ = QuantumCircuit(2,2)
grover_circ.h([0,1])
grover_circ.append(oracle, [0,1])
grover_circ.append(reflection,[0,1])
grover_circ.measure([0,1],[0,1])
grover_circ.draw()
job = execute(grover_circ, backend, shots=1)
result = job.result()
result.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 LookaheadSwap pass"""
import unittest
from numpy import pi
from qiskit.dagcircuit import DAGCircuit
from qiskit.transpiler.passes import LookaheadSwap
from qiskit.transpiler import CouplingMap, Target
from qiskit.converters import circuit_to_dag
from qiskit.circuit.library import CXGate
from qiskit import ClassicalRegister, QuantumRegister, QuantumCircuit
from qiskit.test import QiskitTestCase
from qiskit.providers.fake_provider import FakeMelbourne
class TestLookaheadSwap(QiskitTestCase):
"""Tests the LookaheadSwap pass."""
def test_lookahead_swap_doesnt_modify_mapped_circuit(self):
"""Test that lookahead swap is idempotent.
It should not modify a circuit which is already compatible with the
coupling map, and can be applied repeatedly without modifying the circuit.
"""
qr = QuantumRegister(3, name="q")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[2])
circuit.cx(qr[0], qr[1])
original_dag = circuit_to_dag(circuit)
# Create coupling map which contains all two-qubit gates in the circuit.
coupling_map = CouplingMap([[0, 1], [0, 2]])
mapped_dag = LookaheadSwap(coupling_map).run(original_dag)
self.assertEqual(original_dag, mapped_dag)
remapped_dag = LookaheadSwap(coupling_map).run(mapped_dag)
self.assertEqual(mapped_dag, remapped_dag)
def test_lookahead_swap_should_add_a_single_swap(self):
"""Test that LookaheadSwap will insert a SWAP to match layout.
For a single cx gate which is not available in the current layout, test
that the mapper inserts a single swap to enable the gate.
"""
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[2])
dag_circuit = circuit_to_dag(circuit)
coupling_map = CouplingMap([[0, 1], [1, 2]])
mapped_dag = LookaheadSwap(coupling_map).run(dag_circuit)
self.assertEqual(
mapped_dag.count_ops().get("swap", 0), dag_circuit.count_ops().get("swap", 0) + 1
)
def test_lookahead_swap_finds_minimal_swap_solution(self):
"""Of many valid SWAPs, test that LookaheadSwap finds the cheapest path.
For a two CNOT circuit: cx q[0],q[2]; cx q[0],q[1]
on the initial layout: qN -> qN
(At least) two solutions exist:
- SWAP q[0],[1], cx q[0],q[2], cx q[0],q[1]
- SWAP q[1],[2], cx q[0],q[2], SWAP q[1],q[2], cx q[0],q[1]
Verify that we find the first solution, as it requires fewer SWAPs.
"""
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[2])
circuit.cx(qr[0], qr[1])
dag_circuit = circuit_to_dag(circuit)
coupling_map = CouplingMap([[0, 1], [1, 2]])
mapped_dag = LookaheadSwap(coupling_map).run(dag_circuit)
self.assertEqual(
mapped_dag.count_ops().get("swap", 0), dag_circuit.count_ops().get("swap", 0) + 1
)
def test_lookahead_swap_maps_measurements(self):
"""Verify measurement nodes are updated to map correct cregs to re-mapped qregs.
Create a circuit with measures on q0 and q2, following a swap between q0 and q2.
Since that swap is not in the coupling, one of the two will be required to move.
Verify that the mapped measure corresponds to one of the two possible layouts following
the swap.
"""
qr = QuantumRegister(3, "q")
cr = ClassicalRegister(2)
circuit = QuantumCircuit(qr, cr)
circuit.cx(qr[0], qr[2])
circuit.measure(qr[0], cr[0])
circuit.measure(qr[2], cr[1])
dag_circuit = circuit_to_dag(circuit)
coupling_map = CouplingMap([[0, 1], [1, 2]])
mapped_dag = LookaheadSwap(coupling_map).run(dag_circuit)
mapped_measure_qargs = {op.qargs[0] for op in mapped_dag.named_nodes("measure")}
self.assertIn(mapped_measure_qargs, [{qr[0], qr[1]}, {qr[1], qr[2]}])
def test_lookahead_swap_maps_measurements_with_target(self):
"""Verify measurement nodes are updated to map correct cregs to re-mapped qregs.
Create a circuit with measures on q0 and q2, following a swap between q0 and q2.
Since that swap is not in the coupling, one of the two will be required to move.
Verify that the mapped measure corresponds to one of the two possible layouts following
the swap.
"""
qr = QuantumRegister(3, "q")
cr = ClassicalRegister(2)
circuit = QuantumCircuit(qr, cr)
circuit.cx(qr[0], qr[2])
circuit.measure(qr[0], cr[0])
circuit.measure(qr[2], cr[1])
dag_circuit = circuit_to_dag(circuit)
target = Target()
target.add_instruction(CXGate(), {(0, 1): None, (1, 2): None})
mapped_dag = LookaheadSwap(target).run(dag_circuit)
mapped_measure_qargs = {op.qargs[0] for op in mapped_dag.named_nodes("measure")}
self.assertIn(mapped_measure_qargs, [{qr[0], qr[1]}, {qr[1], qr[2]}])
def test_lookahead_swap_maps_barriers(self):
"""Verify barrier nodes are updated to re-mapped qregs.
Create a circuit with a barrier on q0 and q2, following a swap between q0 and q2.
Since that swap is not in the coupling, one of the two will be required to move.
Verify that the mapped barrier corresponds to one of the two possible layouts following
the swap.
"""
qr = QuantumRegister(3, "q")
cr = ClassicalRegister(2)
circuit = QuantumCircuit(qr, cr)
circuit.cx(qr[0], qr[2])
circuit.barrier(qr[0], qr[2])
dag_circuit = circuit_to_dag(circuit)
coupling_map = CouplingMap([[0, 1], [1, 2]])
mapped_dag = LookaheadSwap(coupling_map).run(dag_circuit)
mapped_barrier_qargs = [set(op.qargs) for op in mapped_dag.named_nodes("barrier")][0]
self.assertIn(mapped_barrier_qargs, [{qr[0], qr[1]}, {qr[1], qr[2]}])
def test_lookahead_swap_higher_depth_width_is_better(self):
"""Test that lookahead swap finds better circuit with increasing search space.
Increasing the tree width and depth is expected to yield a better (or same) quality
circuit, in the form of fewer SWAPs.
"""
# q_0: ──■───────────────────■───────────────────────────────────────────────»
# ┌─┴─┐ │ ┌───┐ »
# q_1: ┤ X ├──■──────────────┼─────────────────┤ X ├─────────────────────────»
# └───┘┌─┴─┐ │ └─┬─┘┌───┐ ┌───┐ »
# q_2: ─────┤ X ├──■─────────┼───────────────────┼──┤ X ├──────────┤ X ├──■──»
# └───┘┌─┴─┐ ┌─┴─┐ │ └─┬─┘ ┌───┐└─┬─┘ │ »
# q_3: ──────────┤ X ├──■──┤ X ├─────────────────┼────┼────■──┤ X ├──┼────┼──»
# └───┘┌─┴─┐└───┘ ┌───┐ │ │ │ └─┬─┘ │ │ »
# q_4: ───────────────┤ X ├──■────────────┤ X ├──┼────■────┼────┼────┼────┼──»
# └───┘┌─┴─┐ └─┬─┘ │ │ │ │ │ »
# q_5: ────────────────────┤ X ├──■─────────┼────┼─────────┼────■────┼────┼──»
# └───┘┌─┴─┐ │ │ │ │ │ »
# q_6: ─────────────────────────┤ X ├──■────■────┼─────────┼─────────■────┼──»
# └───┘┌─┴─┐ │ ┌─┴─┐ ┌─┴─┐»
# q_7: ──────────────────────────────┤ X ├───────■───────┤ X ├──────────┤ X ├»
# └───┘ └───┘ └───┘»
# «q_0: ──■───────
# « │
# «q_1: ──┼───────
# « │
# «q_2: ──┼───────
# « │
# «q_3: ──┼───────
# « │
# «q_4: ──┼───────
# « │
# «q_5: ──┼────■──
# « ┌─┴─┐ │
# «q_6: ┤ X ├──┼──
# « └───┘┌─┴─┐
# «q_7: ─────┤ X ├
# « └───┘
qr = QuantumRegister(8, name="q")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[1])
circuit.cx(qr[1], qr[2])
circuit.cx(qr[2], qr[3])
circuit.cx(qr[3], qr[4])
circuit.cx(qr[4], qr[5])
circuit.cx(qr[5], qr[6])
circuit.cx(qr[6], qr[7])
circuit.cx(qr[0], qr[3])
circuit.cx(qr[6], qr[4])
circuit.cx(qr[7], qr[1])
circuit.cx(qr[4], qr[2])
circuit.cx(qr[3], qr[7])
circuit.cx(qr[5], qr[3])
circuit.cx(qr[6], qr[2])
circuit.cx(qr[2], qr[7])
circuit.cx(qr[0], qr[6])
circuit.cx(qr[5], qr[7])
original_dag = circuit_to_dag(circuit)
# Create a ring of 8 connected qubits
coupling_map = CouplingMap.from_grid(num_rows=2, num_columns=4)
mapped_dag_1 = LookaheadSwap(coupling_map, search_depth=3, search_width=3).run(original_dag)
mapped_dag_2 = LookaheadSwap(coupling_map, search_depth=5, search_width=5).run(original_dag)
num_swaps_1 = mapped_dag_1.count_ops().get("swap", 0)
num_swaps_2 = mapped_dag_2.count_ops().get("swap", 0)
self.assertLessEqual(num_swaps_2, num_swaps_1)
def test_lookahead_swap_hang_in_min_case(self):
"""Verify LookaheadSwap does not stall in minimal case."""
# ref: https://github.com/Qiskit/qiskit-terra/issues/2171
qr = QuantumRegister(14, "q")
qc = QuantumCircuit(qr)
qc.cx(qr[0], qr[13])
qc.cx(qr[1], qr[13])
qc.cx(qr[1], qr[0])
qc.cx(qr[13], qr[1])
dag = circuit_to_dag(qc)
cmap = CouplingMap(FakeMelbourne().configuration().coupling_map)
out = LookaheadSwap(cmap, search_depth=4, search_width=4).run(dag)
self.assertIsInstance(out, DAGCircuit)
def test_lookahead_swap_hang_full_case(self):
"""Verify LookaheadSwap does not stall in reported case."""
# ref: https://github.com/Qiskit/qiskit-terra/issues/2171
qr = QuantumRegister(14, "q")
qc = QuantumCircuit(qr)
qc.cx(qr[0], qr[13])
qc.cx(qr[1], qr[13])
qc.cx(qr[1], qr[0])
qc.cx(qr[13], qr[1])
qc.cx(qr[6], qr[7])
qc.cx(qr[8], qr[7])
qc.cx(qr[8], qr[6])
qc.cx(qr[7], qr[8])
qc.cx(qr[0], qr[13])
qc.cx(qr[1], qr[0])
qc.cx(qr[13], qr[1])
qc.cx(qr[0], qr[1])
dag = circuit_to_dag(qc)
cmap = CouplingMap(FakeMelbourne().configuration().coupling_map)
out = LookaheadSwap(cmap, search_depth=4, search_width=4).run(dag)
self.assertIsInstance(out, DAGCircuit)
def test_global_phase_preservation(self):
"""Test that LookaheadSwap preserves global phase"""
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
circuit.global_phase = pi / 3
circuit.cx(qr[0], qr[2])
dag_circuit = circuit_to_dag(circuit)
coupling_map = CouplingMap([[0, 1], [1, 2]])
mapped_dag = LookaheadSwap(coupling_map).run(dag_circuit)
self.assertEqual(mapped_dag.global_phase, circuit.global_phase)
self.assertEqual(
mapped_dag.count_ops().get("swap", 0), dag_circuit.count_ops().get("swap", 0) + 1
)
if __name__ == "__main__":
unittest.main()
|
https://github.com/indian-institute-of-science-qc/qiskit-aakash
|
indian-institute-of-science-qc
|
"""Python implementation of Grovers algorithm through use of the Qiskit library to find the value 3 (|11>)
out of four possible values."""
#import numpy and plot library
import matplotlib.pyplot as plt
import numpy as np
# importing Qiskit
from qiskit import IBMQ, Aer, QuantumCircuit, ClassicalRegister, QuantumRegister, execute
from qiskit.providers.ibmq import least_busy
from qiskit.quantum_info import Statevector
# import basic plot tools
from qiskit.visualization import plot_histogram
# define variables, 1) initialize qubits to zero
n = 2
grover_circuit = QuantumCircuit(n)
#define initialization function
def initialize_s(qc, qubits):
'''Apply a H-gate to 'qubits' in qc'''
for q in qubits:
qc.h(q)
return qc
### begin grovers circuit ###
#2) Put qubits in equal state of superposition
grover_circuit = initialize_s(grover_circuit, [0,1])
# 3) Apply oracle reflection to marked instance x_0 = 3, (|11>)
grover_circuit.cz(0,1)
statevec = job_sim.result().get_statevector()
from qiskit_textbook.tools import vector2latex
vector2latex(statevec, pretext="|\\psi\\rangle =")
# 4) apply additional reflection (diffusion operator)
grover_circuit.h([0,1])
grover_circuit.z([0,1])
grover_circuit.cz(0,1)
grover_circuit.h([0,1])
# 5) measure the qubits
grover_circuit.measure_all()
# Load IBM Q account and get the least busy backend device
provider = IBMQ.load_account()
device = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 3 and
not x.configuration().simulator and x.status().operational==True))
print("Running on current least busy device: ", device)
from qiskit.tools.monitor import job_monitor
job = execute(grover_circuit, backend=device, shots=1024, optimization_level=3)
job_monitor(job, interval = 2)
results = job.result()
answer = results.get_counts(grover_circuit)
plot_histogram(answer)
#highest amplitude should correspond with marked value x_0 (|11>)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
# useful additional packages
import matplotlib.pyplot as plt
import numpy as np
import networkx as nx
from qiskit_aer import Aer
from qiskit.tools.visualization import plot_histogram
from qiskit.circuit.library import TwoLocal
from qiskit_optimization.applications import Maxcut, Tsp
from qiskit.algorithms.minimum_eigensolvers import SamplingVQE, NumPyMinimumEigensolver
from qiskit.algorithms.optimizers import SPSA
from qiskit.utils import algorithm_globals
from qiskit.primitives import Sampler
from qiskit_optimization.algorithms import MinimumEigenOptimizer
# Generating a graph of 4 nodes
n = 4 # Number of nodes in graph
G = nx.Graph()
G.add_nodes_from(np.arange(0, n, 1))
elist = [(0, 1, 1.0), (0, 2, 1.0), (0, 3, 1.0), (1, 2, 1.0), (2, 3, 1.0)]
# tuple is (i,j,weight) where (i,j) is the edge
G.add_weighted_edges_from(elist)
colors = ["r" for node in G.nodes()]
pos = nx.spring_layout(G)
def draw_graph(G, colors, pos):
default_axes = plt.axes(frameon=True)
nx.draw_networkx(G, node_color=colors, node_size=600, alpha=0.8, ax=default_axes, pos=pos)
edge_labels = nx.get_edge_attributes(G, "weight")
nx.draw_networkx_edge_labels(G, pos=pos, edge_labels=edge_labels)
draw_graph(G, colors, pos)
# Computing the weight matrix from the random graph
w = np.zeros([n, n])
for i in range(n):
for j in range(n):
temp = G.get_edge_data(i, j, default=0)
if temp != 0:
w[i, j] = temp["weight"]
print(w)
best_cost_brute = 0
for b in range(2**n):
x = [int(t) for t in reversed(list(bin(b)[2:].zfill(n)))]
cost = 0
for i in range(n):
for j in range(n):
cost = cost + w[i, j] * x[i] * (1 - x[j])
if best_cost_brute < cost:
best_cost_brute = cost
xbest_brute = x
print("case = " + str(x) + " cost = " + str(cost))
colors = ["r" if xbest_brute[i] == 0 else "c" for i in range(n)]
draw_graph(G, colors, pos)
print("\nBest solution = " + str(xbest_brute) + " cost = " + str(best_cost_brute))
max_cut = Maxcut(w)
qp = max_cut.to_quadratic_program()
print(qp.prettyprint())
qubitOp, offset = qp.to_ising()
print("Offset:", offset)
print("Ising Hamiltonian:")
print(str(qubitOp))
# solving Quadratic Program using exact classical eigensolver
exact = MinimumEigenOptimizer(NumPyMinimumEigensolver())
result = exact.solve(qp)
print(result.prettyprint())
# Making the Hamiltonian in its full form and getting the lowest eigenvalue and eigenvector
ee = NumPyMinimumEigensolver()
result = ee.compute_minimum_eigenvalue(qubitOp)
x = max_cut.sample_most_likely(result.eigenstate)
print("energy:", result.eigenvalue.real)
print("max-cut objective:", result.eigenvalue.real + offset)
print("solution:", x)
print("solution objective:", qp.objective.evaluate(x))
colors = ["r" if x[i] == 0 else "c" for i in range(n)]
draw_graph(G, colors, pos)
algorithm_globals.random_seed = 123
seed = 10598
# construct SamplingVQE
optimizer = SPSA(maxiter=300)
ry = TwoLocal(qubitOp.num_qubits, "ry", "cz", reps=5, entanglement="linear")
vqe = SamplingVQE(sampler=Sampler(), ansatz=ry, optimizer=optimizer)
# run SamplingVQE
result = vqe.compute_minimum_eigenvalue(qubitOp)
# print results
x = max_cut.sample_most_likely(result.eigenstate)
print("energy:", result.eigenvalue.real)
print("time:", result.optimizer_time)
print("max-cut objective:", result.eigenvalue.real + offset)
print("solution:", x)
print("solution objective:", qp.objective.evaluate(x))
# plot results
colors = ["r" if x[i] == 0 else "c" for i in range(n)]
draw_graph(G, colors, pos)
# create minimum eigen optimizer based on SamplingVQE
vqe_optimizer = MinimumEigenOptimizer(vqe)
# solve quadratic program
result = vqe_optimizer.solve(qp)
print(result.prettyprint())
colors = ["r" if result.x[i] == 0 else "c" for i in range(n)]
draw_graph(G, colors, pos)
# Generating a graph of 3 nodes
n = 3
num_qubits = n**2
tsp = Tsp.create_random_instance(n, seed=123)
adj_matrix = nx.to_numpy_array(tsp.graph)
print("distance\n", adj_matrix)
colors = ["r" for node in tsp.graph.nodes]
pos = [tsp.graph.nodes[node]["pos"] for node in tsp.graph.nodes]
draw_graph(tsp.graph, colors, pos)
from itertools import permutations
def brute_force_tsp(w, N):
a = list(permutations(range(1, N)))
last_best_distance = 1e10
for i in a:
distance = 0
pre_j = 0
for j in i:
distance = distance + w[j, pre_j]
pre_j = j
distance = distance + w[pre_j, 0]
order = (0,) + i
if distance < last_best_distance:
best_order = order
last_best_distance = distance
print("order = " + str(order) + " Distance = " + str(distance))
return last_best_distance, best_order
best_distance, best_order = brute_force_tsp(adj_matrix, n)
print(
"Best order from brute force = "
+ str(best_order)
+ " with total distance = "
+ str(best_distance)
)
def draw_tsp_solution(G, order, colors, pos):
G2 = nx.DiGraph()
G2.add_nodes_from(G)
n = len(order)
for i in range(n):
j = (i + 1) % n
G2.add_edge(order[i], order[j], weight=G[order[i]][order[j]]["weight"])
default_axes = plt.axes(frameon=True)
nx.draw_networkx(
G2, node_color=colors, edge_color="b", node_size=600, alpha=0.8, ax=default_axes, pos=pos
)
edge_labels = nx.get_edge_attributes(G2, "weight")
nx.draw_networkx_edge_labels(G2, pos, font_color="b", edge_labels=edge_labels)
draw_tsp_solution(tsp.graph, best_order, colors, pos)
qp = tsp.to_quadratic_program()
print(qp.prettyprint())
from qiskit_optimization.converters import QuadraticProgramToQubo
qp2qubo = QuadraticProgramToQubo()
qubo = qp2qubo.convert(qp)
qubitOp, offset = qubo.to_ising()
print("Offset:", offset)
print("Ising Hamiltonian:")
print(str(qubitOp))
result = exact.solve(qubo)
print(result.prettyprint())
# Making the Hamiltonian in its full form and getting the lowest eigenvalue and eigenvector
ee = NumPyMinimumEigensolver()
result = ee.compute_minimum_eigenvalue(qubitOp)
print("energy:", result.eigenvalue.real)
print("tsp objective:", result.eigenvalue.real + offset)
x = tsp.sample_most_likely(result.eigenstate)
print("feasible:", qubo.is_feasible(x))
z = tsp.interpret(x)
print("solution:", z)
print("solution objective:", tsp.tsp_value(z, adj_matrix))
draw_tsp_solution(tsp.graph, z, colors, pos)
algorithm_globals.random_seed = 123
seed = 10598
optimizer = SPSA(maxiter=300)
ry = TwoLocal(qubitOp.num_qubits, "ry", "cz", reps=5, entanglement="linear")
vqe = SamplingVQE(sampler=Sampler(), ansatz=ry, optimizer=optimizer)
result = vqe.compute_minimum_eigenvalue(qubitOp)
print("energy:", result.eigenvalue.real)
print("time:", result.optimizer_time)
x = tsp.sample_most_likely(result.eigenstate)
print("feasible:", qubo.is_feasible(x))
z = tsp.interpret(x)
print("solution:", z)
print("solution objective:", tsp.tsp_value(z, adj_matrix))
draw_tsp_solution(tsp.graph, z, colors, pos)
algorithm_globals.random_seed = 123
seed = 10598
# create minimum eigen optimizer based on SamplingVQE
vqe_optimizer = MinimumEigenOptimizer(vqe)
# solve quadratic program
result = vqe_optimizer.solve(qp)
print(result.prettyprint())
z = tsp.interpret(x)
print("solution:", z)
print("solution objective:", tsp.tsp_value(z, adj_matrix))
draw_tsp_solution(tsp.graph, z, colors, pos)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/BOBO1997/osp_solutions
|
BOBO1997
|
import numpy as np
import matplotlib.pyplot as plt
from pprint import pprint
import pickle
import time
import datetime
# Import qubit states Zero (|0>) and One (|1>), and Pauli operators (X, Y, Z)
from qiskit.opflow import Zero, One
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
# unused for this file
import mitiq
# Import state tomography modules
from qiskit.ignis.verification.tomography import state_tomography_circuits, StateTomographyFitter
from qiskit.quantum_info import state_fidelity
import sys
import importlib
sys.path.append("../../solutions/utils/")
import circuit_utils, zne_utils, tomography_utils
importlib.reload(circuit_utils)
importlib.reload(zne_utils) # unused for this file
importlib.reload(tomography_utils) # unused for this file
from circuit_utils import *
from zne_utils import zne_wrapper, zne_decoder
from tomography_utils import expvals_to_valid_rho
from qiskit.test.mock import FakeJakarta
backend = FakeJakarta()
# backend = Aer.get_backend("qasm_simulator")
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_list = [1,2,3,4,5,6,7,8,9,10,20,30,40,50,60,70,80,90,100]
print("trotter step list: ", num_steps_list)
scale_factors = [1.0, 2.0, 3.0] # unused for this file
shots = 1 << 13
reps = 8 # unused
target_state = (One^One^Zero).to_matrix() # DO NOT CHANGE!!!
# QREM
qr = QuantumRegister(num_qubits, name="calq")
meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal')
# we have to feed initial_layout to calibration matrix
cal_job = execute(meas_calibs, backend=backend, shots=shots, optimization_level=3, initial_layout = initial_layout)
print('Job ID', cal_job.job_id())
retrieved_cal_job = cal_job
cal_results = retrieved_cal_job.result()
meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal')
qrem_fid_list = []
qrem_stddev_list = []
for num_steps in num_steps_list:
print("trotter steps: ", num_steps)
t1 = time.perf_counter()
# Initialize quantum circuit for 3 qubits
qr = QuantumRegister(num_qubits, name="q")
qc = QuantumCircuit(qr)
# Prepare initial state (remember we are only evolving 3 of the 7 qubits on jakarta qubits (q_5, q_3, q_1) corresponding to the state |110>)
make_initial_state(qc, "110") # DO NOT MODIFY (|q_5,q_3,q_1> = |110>)
subspace_encoder_init110(qc, targets=[0, 1, 2]) # encode
trotterize(qc, trot_gate, num_steps, targets=[1, 2]) # Simulate time evolution under H_heis3 Hamiltonian
subspace_decoder_init110(qc, targets=[0, 1, 2]) # decode
# Evaluate simulation at target_time (t=pi) meaning each trotter step evolves pi/trotter_steps in time
qc = qc.bind_parameters({dt: target_time / num_steps})
print("created qc")
# Generate state tomography circuits to evaluate fidelity of simulation
st_qcs = state_tomography_circuits(qc, [0, 1, 2][::-1]) #! state tomography requires === BIG ENDIAN ===
print("created st_qcs (length:", len(st_qcs), ")")
# remove barriers
st_qcs = [RemoveBarriers()(qc) for qc in st_qcs]
print("removed barriers from st_qcs")
# optimize circuit
t3_st_qcs = transpile(st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"])
t3_st_qcs = transpile(t3_st_qcs, optimization_level=3, basis_gates=["sx", "cx", "rz"])
print("created t3_st_qcs (length:", len(t3_st_qcs), ")")
# zne wrapping
zne_qcs = t3_st_qcs
# zne_qcs = zne_wrapper(t3_st_qcs, scale_factors = scale_factors, pt = False)
# print("created zne_qcs (length:", len(zne_qcs), ")")
# optimization_level must be 0
# feed initial_layout here to see the picture of the circuits before casting the job
t3_zne_qcs = transpile(zne_qcs, optimization_level=0, basis_gates=["sx", "cx", "rz"], initial_layout=initial_layout)
print("created t3_zne_qcs (length:", len(t3_zne_qcs), ")")
jobs = []
for _ in range(reps):
#! CHECK: run t3_zne_qcs, with optimization_level = 0 and straightforward initial_layout
job = execute(t3_zne_qcs, backend, shots=shots, optimization_level=0)
print('Job ID', job.job_id())
jobs.append(job)
retrieved_jobs = jobs
qrem_fids = []
for job in retrieved_jobs:
raw_results = job.result()
mit_results = meas_fitter.filter.apply(raw_results)
qrem_rho = StateTomographyFitter(mit_results, t3_zne_qcs).fit(method='lstsq')
qrem_fids.append(state_fidelity(qrem_rho, target_state))
qrem_fid_list.append(np.mean(qrem_fids))
qrem_stddev_list.append(np.std(qrem_fids))
t2 = time.perf_counter()
print('qrem state tomography fidelity = {:.4f} \u00B1 {:.4f}'.format(np.mean(qrem_fids), np.std(qrem_fids)))
print("time:", t2 - t1)
print()
with open("e2d2_qrem.pkl", "wb") as f:
pickle.dump({"num_steps_list": num_steps_list, "fid": qrem_fid_list, "stddev": qrem_stddev_list}, f)
import qiskit.tools.jupyter
%qiskit_version_table
plt.plot(num_steps_list, qrem_fid_list)
|
https://github.com/swe-train/qiskit__qiskit
|
swe-train
|
# This code is part of Qiskit.
#
# (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.
"""
Estimator Pub class
"""
from __future__ import annotations
from numbers import Real
from collections.abc import Mapping
from typing import Tuple, Union
import numpy as np
from qiskit import QuantumCircuit
from .bindings_array import BindingsArray, BindingsArrayLike
from .observables_array import ObservablesArray, ObservablesArrayLike
from .shape import ShapedMixin
# Public API classes
__all__ = ["EstimatorPubLike"]
class EstimatorPub(ShapedMixin):
"""Primitive Unified Bloc for any Estimator primitive.
An estimator pub is essentially a tuple ``(circuit, observables, parameter_values, precision)``.
If precision is provided this should be used for the target precision of an
estimator, if ``precision=None`` the estimator will determine the target precision.
"""
__slots__ = ("_circuit", "_observables", "_parameter_values", "_precision", "_shape")
def __init__(
self,
circuit: QuantumCircuit,
observables: ObservablesArray,
parameter_values: BindingsArray | None = None,
precision: float | None = None,
validate: bool = True,
):
"""Initialize an estimator pub.
Args:
circuit: A quantum circuit.
observables: An observables array.
parameter_values: A bindings array, if the circuit is parametric.
precision: An optional target precision for expectation value estimates.
validate: Whether to validate arguments during initialization.
Raises:
ValueError: If the ``observables`` and ``parameter_values`` are not broadcastable, that
is, if their shapes, when right-aligned, do not agree or equal 1.
"""
super().__init__()
self._circuit = circuit
self._observables = observables
self._parameter_values = parameter_values or BindingsArray()
self._precision = precision
# for ShapedMixin
try:
# _shape has to be defined to properly be Shaped, so we can't put it in validation
self._shape = np.broadcast_shapes(self.observables.shape, self.parameter_values.shape)
except ValueError as ex:
raise ValueError(
f"The observables shape {self.observables.shape} and the "
f"parameter values shape {self.parameter_values.shape} are not broadcastable."
) from ex
if validate:
self.validate()
@property
def circuit(self) -> QuantumCircuit:
"""A quantum circuit."""
return self._circuit
@property
def observables(self) -> ObservablesArray:
"""An observables array."""
return self._observables
@property
def parameter_values(self) -> BindingsArray:
"""A bindings array."""
return self._parameter_values
@property
def precision(self) -> float | None:
"""The target precision for expectation value estimates (optional)."""
return self._precision
@classmethod
def coerce(cls, pub: EstimatorPubLike, precision: float | None = None) -> EstimatorPub:
"""Coerce :class:`~.EstimatorPubLike` into :class:`~.EstimatorPub`.
Args:
pub: A compatible object for coercion.
precision: an optional default precision to use if not
already specified by the pub-like object.
Returns:
An estimator pub.
"""
# Validate precision kwarg if provided
if precision is not None:
if not isinstance(precision, Real):
raise TypeError(f"precision must be a real number, not {type(precision)}.")
if precision < 0:
raise ValueError("precision must be non-negative")
if isinstance(pub, EstimatorPub):
if pub.precision is None and precision is not None:
return cls(
circuit=pub.circuit,
observables=pub.observables,
parameter_values=pub.parameter_values,
precision=precision,
validate=False, # Assume Pub is already validated
)
return pub
if isinstance(pub, QuantumCircuit):
raise ValueError(
f"An invalid Estimator pub-like was given ({type(pub)}). "
"If you want to run a single pub, you need to wrap it with `[]` like "
"`estimator.run([(circuit, observables, param_values)])` "
"instead of `estimator.run((circuit, observables, param_values))`."
)
if len(pub) not in [2, 3, 4]:
raise ValueError(
f"The length of pub must be 2, 3 or 4, but length {len(pub)} is given."
)
circuit = pub[0]
observables = ObservablesArray.coerce(pub[1])
if len(pub) > 2 and pub[2] is not None:
values = pub[2]
if not isinstance(values, (BindingsArray, Mapping)):
values = {tuple(circuit.parameters): values}
parameter_values = BindingsArray.coerce(values)
else:
parameter_values = None
if len(pub) > 3 and pub[3] is not None:
precision = pub[3]
return cls(
circuit=circuit,
observables=observables,
parameter_values=parameter_values,
precision=precision,
validate=True,
)
def validate(self):
"""Validate the pub."""
if not isinstance(self.circuit, QuantumCircuit):
raise TypeError("circuit must be QuantumCircuit.")
self.observables.validate()
self.parameter_values.validate()
if self.precision is not None:
if not isinstance(self.precision, Real):
raise TypeError(f"precision must be a real number, not {type(self.precision)}.")
if self.precision < 0:
raise ValueError("precision must be non-negative.")
# Cross validate circuits and observables
for i, observable in np.ndenumerate(self.observables):
num_qubits = len(next(iter(observable)))
if self.circuit.num_qubits != num_qubits:
raise ValueError(
f"The number of qubits of the circuit ({self.circuit.num_qubits}) does "
f"not match the number of qubits of the {i}-th observable ({num_qubits})."
)
# Cross validate circuits and parameter_values
num_parameters = self.parameter_values.num_parameters
if num_parameters != self.circuit.num_parameters:
raise ValueError(
f"The number of values ({num_parameters}) does not match "
f"the number of parameters ({self.circuit.num_parameters}) for the circuit."
)
EstimatorPubLike = Union[
EstimatorPub,
Tuple[QuantumCircuit, ObservablesArrayLike],
Tuple[QuantumCircuit, ObservablesArrayLike, BindingsArrayLike],
Tuple[QuantumCircuit, ObservablesArrayLike, BindingsArrayLike, Real],
]
"""A Pub (Primitive Unified Bloc) for an Estimator primitive.
A fully specified estimator pub is a tuple ``(circuit, observables, parameter_values, precision)``.
If precision is provided this should be used for the target precision of an
estimator, if ``precision=None`` the estimator will determine the target precision.
.. note::
An Estimator Pub can also be initialized in the following formats which
will be converted to the full Pub tuple:
* ``(circuit, observables)``
* ``(circuit, observables, parameter_values)``
"""
|
https://github.com/AbeerVaishnav13/Quantum-Programs
|
AbeerVaishnav13
|
import matplotlib as mpl
import numpy as np
import matplotlib.pyplot as plt
from qiskit import QuantumCircuit, Aer, transpile, assemble
from qiskit.visualization import plot_histogram, plot_bloch_multivector
qc = QuantumCircuit(1,1)
# Alice prepares qubit in state |+>
qc.h(0)
qc.barrier()
# Alice now sends the qubit to Bob
# who measures it in the X-basis
qc.h(0)
qc.measure(0,0)
# Draw and simulate circuit
display(qc.draw())
aer_sim = Aer.get_backend('aer_simulator')
job = aer_sim.run(assemble(qc))
plot_histogram(job.result().get_counts())
qc = QuantumCircuit(1,1)
# Alice prepares qubit in state |+>
qc.h(0)
# Alice now sends the qubit to Bob
# but Eve intercepts and tries to read it
qc.measure(0, 0)
qc.barrier()
# Eve then passes this on to Bob
# who measures it in the X-basis
qc.h(0)
qc.measure(0,0)
# Draw and simulate circuit
display(qc.draw())
aer_sim = Aer.get_backend('aer_simulator')
job = aer_sim.run(assemble(qc))
plot_histogram(job.result().get_counts())
n = 100
## Step 1
# Alice generates bits.
alice_bits = np.random.randint(0,2,n)
## Step 2
# Create an array to tell us which qubits
# are encoded in which bases
alice_bases = np.random.randint(0,2,n)
# Function to compare the bits & bases generated by alice, and then 'encode' the message. Basically determines the state of the qubit/photon to send.
def encode_message(bits, bases):
message = []
for i in range(n):
qc = QuantumCircuit(1,1)
if bases[i] == 0: # Prepare qubit in Z-basis
if bits[i] == 0:
pass
else:
qc.x(0)
else: # Prepare qubit in X-basis
if bits[i] == 0:
qc.h(0)
else:
qc.x(0)
qc.h(0)
qc.barrier()
message.append(qc)
return message
# Alice computes the encoded message using the function defined above.
message = encode_message(alice_bits, alice_bases)
## Step 3
# Decide which basis to measure in:
bob_bases = np.random.randint(0,2,n)
# Function to decode the message sent by alice by comparing qubit/photon states with Bob's generated bases.
def measure_message(message, bases):
backend = Aer.get_backend('aer_simulator')
measurements = []
for q in range(n):
if bases[q] == 0: # measuring in Z-basis
message[q].measure(0,0)
if bases[q] == 1: # measuring in X-basis
message[q].h(0)
message[q].measure(0,0)
aer_sim = Aer.get_backend('aer_simulator')
qobj = assemble(message[q], shots=1, memory=True)
result = aer_sim.run(qobj).result()
measured_bit = int(result.get_memory()[0])
measurements.append(measured_bit)
return measurements
# Decode the message according to his bases
bob_results = measure_message(message, bob_bases)
## Step 4
# Function to perform sifting i.e. disregard the bits for which Bob's & A;ice's bases didnot match.
def remove_garbage(a_bases, b_bases, bits):
good_bits = []
for q in range(n):
if a_bases[q] == b_bases[q]:
# If both used the same basis, add
# this to the list of 'good' bits
good_bits.append(bits[q])
return good_bits
# Performing sifting for Alice's and Bob's bits.
alice_key = remove_garbage(alice_bases, bob_bases, alice_bits)
bob_key = remove_garbage(alice_bases, bob_bases, bob_results)
print("Alice's key after sifting (without interception)", alice_key)
print("Bob's key after sifting (without interception) ", bob_key)
# # Step 5
# # Function for parameter estimation i.e. determining the error rate by comparing subsets taen from both Alice's key & Bob's key.
# def sample_bits(bits, selection):
# sample = []
# for i in selection:
# # use np.mod to make sure the
# # bit we sample is always in
# # the list range
# i = np.mod(i, len(bits))
# # pop(i) removes the element of the
# # list at index 'i'
# sample.append(bits.pop(i))
# return sample
# # Performing parameter estimation & disregarding the bits used for comparison from Alice's & Bob's key.
# sample_size = 15
# bit_selection = np.random.randint(0,n,size=sample_size)
# bob_sample = sample_bits(bob_key, bit_selection)
# alice_sample = sample_bits(alice_key, bit_selection)
num = 0
for i in range(0,len(bob_key)):
if alice_key[i] == bob_key[i]:
num = num + 1
matching_bits = (num/len(bob_key))*100
print(matching_bits,"% of the bits match.")
## Step 1
alice_bits = np.random.randint(2, size=n)
## Step 2
alice_bases = np.random.randint(2, size=n)
message = encode_message(alice_bits, alice_bases)
## Interception!!
eve_bases = np.random.randint(2, size=n)
intercepted_message = measure_message(message, eve_bases)
## Step 3
bob_bases = np.random.randint(2, size=n)
bob_results = measure_message(message, bob_bases)
## Step 4
bob_key = remove_garbage(alice_bases, bob_bases, bob_results)
alice_key = remove_garbage(alice_bases, bob_bases, alice_bits)
print("Alice's key after sifting (with interception)", alice_key)
print("Bob's key after sifting (with interception) ", bob_key)
# ## Step 5
# sample_size = 15
# bit_selection = np.random.randint(n, size=sample_size)
# bob_sample = sample_bits(bob_key, bit_selection)
# alice_sample = sample_bits(alice_key, bit_selection)
num = 0
for i in range(0,len(bob_key)):
if alice_key[i] == bob_key[i]:
num = num + 1
matching_bits = (num/len(bob_key))*100
print(matching_bits,"% of the bits match.")
plt.rcParams['axes.linewidth'] = 2
mpl.rcParams['font.family'] = ['Georgia']
plt.figure(figsize=(10.5,6))
ax=plt.axes()
ax.set_title('')
ax.set_xlabel('$n$ (Number of bits drawn from the sifted keys for determining error rate)',fontsize = 18,labelpad=10)
ax.set_ylabel(r'$P(Eve\ detected)$',fontsize = 18,labelpad=10)
ax.xaxis.set_tick_params(which='major', size=8, width=2, direction='in', top='on')
ax.yaxis.set_tick_params(which='major', size=8, width=2, direction='in', top='on')
ax.tick_params(axis='x', labelsize=20)
ax.tick_params(axis='y', labelsize=20)
ax. xaxis. label. set_size(20)
ax. yaxis. label. set_size(20)
n = 30
x = np.arange(n+1)
y = 1 - 0.75**x
ax.plot(x,y,color = plt.cm.rainbow(np.linspace(0, 1, 5))[0], marker = "s", markerfacecolor='r')
|
https://github.com/swe-train/qiskit__qiskit
|
swe-train
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""A collection of backend information formatted to generate drawing data.
This instance will be provided to generator functions. The module provides an abstract
class :py:class:``DrawerBackendInfo`` with necessary methods to generate drawing objects.
Because the data structure of backend class may depend on providers, this abstract class
has an abstract factory method `create_from_backend`. Each subclass should provide
the factory method which conforms to the associated provider. By default we provide
:py:class:``OpenPulseBackendInfo`` class that has the factory method taking backends
satisfying OpenPulse specification [1].
This class can be also initialized without the factory method by manually specifying
required information. This may be convenient for visualizing a pulse program for simulator
backend that only has a device Hamiltonian information. This requires two mapping objects
for channel/qubit and channel/frequency along with the system cycle time.
If those information are not provided, this class will be initialized with a set of
empty data and the drawer illustrates a pulse program without any specific information.
Reference:
- [1] Qiskit Backend Specifications for OpenQASM and OpenPulse Experiments,
https://arxiv.org/abs/1809.03452
"""
from abc import ABC, abstractmethod
from collections import defaultdict
from typing import Dict, List, Union, Optional
from qiskit import pulse
from qiskit.providers import BackendConfigurationError
from qiskit.providers.backend import Backend
class DrawerBackendInfo(ABC):
"""Backend information to be used for the drawing data generation."""
def __init__(
self,
name: Optional[str] = None,
dt: Optional[float] = None,
channel_frequency_map: Optional[Dict[pulse.channels.Channel, float]] = None,
qubit_channel_map: Optional[Dict[int, List[pulse.channels.Channel]]] = None,
):
"""Create new backend information.
Args:
name: Name of the backend.
dt: System cycle time.
channel_frequency_map: Mapping of channel and associated frequency.
qubit_channel_map: Mapping of qubit and associated channels.
"""
self.backend_name = name or "no-backend"
self._dt = dt
self._chan_freq_map = channel_frequency_map or {}
self._qubit_channel_map = qubit_channel_map or {}
@classmethod
@abstractmethod
def create_from_backend(cls, backend: Backend):
"""Initialize a class with backend information provided by provider.
Args:
backend: Backend object.
"""
raise NotImplementedError
@property
def dt(self):
"""Return cycle time."""
return self._dt
def get_qubit_index(self, chan: pulse.channels.Channel) -> Union[int, None]:
"""Get associated qubit index of given channel object."""
for qind, chans in self._qubit_channel_map.items():
if chan in chans:
return qind
return chan.index
def get_channel_frequency(self, chan: pulse.channels.Channel) -> Union[float, None]:
"""Get frequency of given channel object."""
return self._chan_freq_map.get(chan, None)
class OpenPulseBackendInfo(DrawerBackendInfo):
"""Drawing information of backend that conforms to OpenPulse specification."""
@classmethod
def create_from_backend(cls, backend: Backend):
"""Initialize a class with backend information provided by provider.
Args:
backend: Backend object.
Returns:
OpenPulseBackendInfo: New configured instance.
"""
configuration = backend.configuration()
defaults = backend.defaults()
# load name
name = backend.name()
# load cycle time
dt = configuration.dt
# load frequencies
chan_freqs = {}
chan_freqs.update(
{pulse.DriveChannel(qind): freq for qind, freq in enumerate(defaults.qubit_freq_est)}
)
chan_freqs.update(
{pulse.MeasureChannel(qind): freq for qind, freq in enumerate(defaults.meas_freq_est)}
)
for qind, u_lo_mappers in enumerate(configuration.u_channel_lo):
temp_val = 0.0 + 0.0j
for u_lo_mapper in u_lo_mappers:
temp_val += defaults.qubit_freq_est[u_lo_mapper.q] * u_lo_mapper.scale
chan_freqs[pulse.ControlChannel(qind)] = temp_val.real
# load qubit channel mapping
qubit_channel_map = defaultdict(list)
for qind in range(configuration.n_qubits):
qubit_channel_map[qind].append(configuration.drive(qubit=qind))
qubit_channel_map[qind].append(configuration.measure(qubit=qind))
for tind in range(configuration.n_qubits):
try:
qubit_channel_map[qind].extend(configuration.control(qubits=(qind, tind)))
except BackendConfigurationError:
pass
return OpenPulseBackendInfo(
name=name, dt=dt, channel_frequency_map=chan_freqs, qubit_channel_map=qubit_channel_map
)
|
https://github.com/qwqmlf/qwgc
|
qwqmlf
|
import numpy as np
import random
import copy
import sys
import networkx as nx
import matplotlib.pyplot as plt
from numpy import pi
from tqdm import trange
from grakel import datasets, Graph
from sklearn.model_selection import KFold
sys.path.append("../")
from qwgc.QWGC import QWGC
# MUTAGを取ってくる
Data = datasets.fetch_dataset('MUTAG', verbose=False)
data_x, data_y = np.array(Data.data), np.array(Data.target)
# visualization of data
subtract = 0
lens = []
for d, l in zip(data_x[:10], data_y[:10]):
print(l)
plt.figure(figsize=(10, 10))
G = nx.DiGraph()
connection = d[0]
nodesize = [(i+1)**800 for i in d[1].values()]
edge_weight = d[2]
lens.append(len([i for i in d[1].values()]))
adjacency = Graph(connection).get_adjacency_matrix()
nodes = np.array([str(i+1) for i, _ in enumerate(adjacency)])
edges = []
weight = []
for i, v in edge_weight.items():
ed = [str(st-subtract) for st in list(i)]
ed.append(v+1)
edges.append(tuple(ed))
subtract = max(d[1].keys())
G.add_nodes_from(nodes)
G.add_weighted_edges_from(edges)
pos = nx.kamada_kawai_layout(G)
edge_labels = {(i, j): w['weight'] for i, j, w in G.edges(data=True)}
nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels)
nx.draw_networkx(G, pos, with_labels=True, alpha=0.8)
plt.show()
from qwgc.preprocess.qwalk import QuantumWalk
# 対象のデータ
data = data_x[0]
label = data_y[0]
# 隣接行列
adjacency = Graph(data[0]).get_adjacency_matrix()
count = np.count_nonzero(adjacency)//2
# 量子ウォークのハイパーパラメータ
step = 1
# 次数が2の場合のコインのパラメータ(今回は簡単のために全てアダマールコイン)
coin = np.kron(np.identity(count), 1/np.sqrt(2)*np.array([[1, 1], [1, -1]]))
# 初期状態 (0からスタート)
initial = None
# 量子ウォーカーが測定される確率
qwalk = QuantumWalk(initial, coin, adjacency)
qwalk.n_steps(step)
probs = qwalk.calc_probs()
# 描画
plt.figure(figsize=(10, 10))
G = nx.DiGraph()
# ノードの大きさで確率を表す
connection = data[0]
nodesize = [(i+0.1)*800 for i in probs]
edge_weight = data[2]
nodes = np.array([str(i+1) for i, _ in enumerate(adjacency)])
edges = []
weight = []
for i, v in edge_weight.items():
ed = [str(st) for st in list(i)]
ed.append(v+1)
edges.append(tuple(ed))
subtract = max(data[1].keys())
G.add_nodes_from(nodes)
G.add_weighted_edges_from(edges)
pos = nx.spring_layout(G)
edge_labels = {(i, j): w['weight'] for i, j, w in G.edges(data=True)}
nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels)
nx.draw_networkx(G, pos, with_labels=True, alpha=0.8, node_size=nodesize)
plt.show()
def draw(nodesize):
plt.figure(figsize=(10, 10))
G = nx.DiGraph()
# ノードの大きさで確率を表す
connection = data[0]
nodesize = [(i)*800 for i in probs]
edge_weight = data[2]
nodes = np.array([str(i+1) for i, _ in enumerate(adjacency)])
edges = []
weight = []
for i, v in edge_weight.items():
ed = [str(st) for st in list(i)]
ed.append(v+1)
edges.append(tuple(ed))
subtract = max(data[1].keys())
G.add_nodes_from(nodes)
G.add_weighted_edges_from(edges)
pos = nx.spring_layout(G)
edge_labels = {(i, j): w['weight'] for i, j, w in G.edges(data=True)}
nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels)
nx.draw_networkx(G, pos, with_labels=True, alpha=0.8, node_size=nodesize)
plt.show()
data = data_x[0]
label = data_y[0]
# 隣接行列
adjacency = Graph(data[0]).get_adjacency_matrix()
count = np.count_nonzero(adjacency)//2
# 量子ウォークのハイパーパラメータ
for step in range(1, 10):
# 次数が2の場合のコインのパラメータ(今回は簡単のために全てアダマールコイン)
coin = np.kron(np.identity(count), 1/np.sqrt(2)*np.array([[1, 1], [1, -1]]))
# 初期状態 (0からスタート)
initial = None
# 量子ウォーカーが測定される確率
qwalk = QuantumWalk(initial, coin, adjacency)
qwalk.n_steps(step)
probs = qwalk.calc_probs()
draw(probs)
from qwgc.preprocess.qwfilter import QWfilter
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit import Aer, execute, transpile
data = data_x[0]
label = data_y[0]
# filter
u3param = [pi, 0, pi/2]
# step
step = 3
# initial 重ね合わせを初期状態として利用
initial = "super"
qwfilter = QWfilter(u3param, step, initial)
# 今回は測定をせずに、振幅をそのまま量子回路にマッピングを行います。
amplitude = qwfilter.single_amplitude(data)
la = len(amplitude)
new_amplitude = list(amplitude) + [0 for i in range(64 - 38)]
print(len(new_amplitude))
nq = 6
# 量子レジスタの定義
qr = QuantumRegister(nq, name="quantum walk")
ancilla = QuantumRegister(2, name="ancilla")
# 古典レジスタの定義
cr = ClassicalRegister(2)
# 量子回路の定義
qc = QuantumCircuit(qr, ancilla, cr)
qc.draw(output='mpl')
qc.initialize(new_amplitude, qr)
# 回転角を初期化
theta = [np.random.uniform(-pi, pi) for i in range(nq)]
for ith, th in enumerate(theta):
qc.cry(th, qr[ith], ancilla[ith%2])
qc.draw(output="mpl")
qc.measure(ancilla, cr)
backend = Aer.get_backend("qasm_simulator")
shots = 1024
job = execute(qc, backend=backend, shots=shots)
counts = job.result().get_counts(qc)
dinom = counts.get('01', 0) + counts.get('10', 0) + 1e-10
print("クラス-1である確率:", counts.get('01', 0)/dinom, "クラス1である確率:", counts.get('10', 0)/dinom)
if counts.get('01', 0)/dinom > counts.get('10', 0)/dinom:
answer = -1
else:
answer = 1
print("このグラフはクラス ", answer, "です.")
print("正解は", data_y[1], "です。")
|
https://github.com/Fergus-Hayes/qiskit_tools
|
Fergus-Hayes
|
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer, IBMQ
import qiskit_tools as qt
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
digit = 10.25
k = 2
target = np.power(digit, k)
print(digit,'^'+str(k),'=',target)
nintx = qt.get_nint(digit)
npresx = qt.get_npres(digit)
nx = nintx + npresx + 1
print(nx, nintx, npresx)
nint = qt.get_nint(target)
npres = qt.get_npres(target)
n = nint + npres + 1
print(n, nint)
phase = True
binary = qt.my_binary_repr(digit, nx, nint=nintx, phase=phase)
binary_t = qt.my_binary_repr(target, n, nint=nint, phase=phase)
qx = QuantumRegister(nx, 'x')
qtarg = QuantumRegister(n,'targ')
c_out = ClassicalRegister(n, 'c_out')
circ = QuantumCircuit(qx, qtarg, c_out)
in_gate = qt.input_bits_to_qubits(binary, circ, reg=qx, wrap=True)
circ.append(in_gate, qx);
power_gate = qt.QFTPowerN(circ, qx, qtarg, k, wrap=True, nintx=nintx, nint=nint)
circ.append(power_gate, [*qx, *qtarg]);
circ.measure(qtarg, c_out);
circ.draw('latex')
shots=10
emulator = Aer.get_backend('qasm_simulator')
job = execute(circ, emulator, shots=shots )
hist = job.result().get_counts()
print('Target:')
print(digit,'^'+str(k),'=',target,'->',binary_t)
print('Result:')
for label in hist.keys():
print(digit,'^'+str(k),'=',qt.bin_to_dec(label, nint=nint, phase=phase),'->',label,'with probability',float(hist[label])/shots)
digit = 1.25
k = 5
target = np.power(digit, k)
print(digit,'^'+str(k),'=',target)
nintx = qt.get_nint(digit)
npresx = qt.get_npres(digit)
nx = nintx + npresx + 1
print(nx, nintx, npresx)
nint = qt.get_nint(target)
npres = qt.get_npres(target)
n = nint + npres + 1
print(n, nint)
phase = True
binary = qt.my_binary_repr(digit, nx, nint=nintx, phase=phase)
binary_t = qt.my_binary_repr(target, n, nint=nint, phase=phase)
qx = QuantumRegister(nx, 'x')
qtarg = QuantumRegister(n,'targ')
c_out = ClassicalRegister(n, 'c_out')
circ = QuantumCircuit(qx, qtarg, c_out)
in_gate = qt.input_bits_to_qubits(binary, circ, reg=qx, wrap=True)
circ.append(in_gate, qx);
power_gate = qt.QFTPowerN(circ, qx, qtarg, k, wrap=True, nintx=nintx, nint=nint)
circ.append(power_gate, [*qx, *qtarg]);
circ.measure(qtarg, c_out);
shots=10
emulator = Aer.get_backend('qasm_simulator')
job = execute(circ, emulator, shots=shots )
hist = job.result().get_counts()
print('Target:')
print(digit,'^'+str(k),'=',target,'->',binary_t)
print('Result:')
for label in hist.keys():
print(digit,'^'+str(k),'=',qt.bin_to_dec(label, nint=nint, phase=phase),'->',label,'with probability',float(hist[label])/shots)
|
https://github.com/Axect/QuantumAlgorithms
|
Axect
|
#In case you don't have qiskit, install it now
%pip install qiskit --quiet
#Installing/upgrading pylatexenc seems to have fixed my mpl issue
#If you try this and it doesn't work, try also restarting the runtime/kernel
%pip install pylatexenc --quiet
!pip install -Uqq ipdb
!pip install qiskit_optimization
import networkx as nx
import matplotlib.pyplot as plt
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit import BasicAer
from qiskit.compiler import transpile
from qiskit.quantum_info.operators import Operator, Pauli
from qiskit.quantum_info import process_fidelity
from qiskit.extensions.hamiltonian_gate import HamiltonianGate
from qiskit.extensions import RXGate, XGate, CXGate
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, Aer, execute
import numpy as np
from qiskit.visualization import plot_histogram
import ipdb
from qiskit import QuantumCircuit, execute, Aer, IBMQ
from qiskit.compiler import transpile, assemble
from qiskit.tools.jupyter import *
from qiskit.visualization import *
#quadratic optimization
from qiskit_optimization import QuadraticProgram
from qiskit_optimization.converters import QuadraticProgramToQubo
%pdb on
# def ApplyCost(qc, gamma):
# Ix = np.array([[1,0],[0,1]])
# Zx= np.array([[1,0],[0,-1]])
# Xx = np.array([[0,1],[1,0]])
# Temp = (Ix-Zx)/2
# T = Operator(Temp)
# I = Operator(Ix)
# Z = Operator(Zx)
# X = Operator(Xx)
# FinalOp=-2*(T^I^T)-(I^T^T)-(T^I^I)+2*(I^T^I)-3*(I^I^T)
# ham = HamiltonianGate(FinalOp,gamma)
# qc.append(ham,[0,1,2])
task = QuadraticProgram(name = 'QUBO on QC')
task.binary_var(name = 'x')
task.binary_var(name = 'y')
task.binary_var(name = 'z')
task.minimize(linear = {"x":-1,"y":2,"z":-3}, quadratic = {("x", "z"): -2, ("y", "z"): -1})
qubo = QuadraticProgramToQubo().convert(task) #convert to QUBO
operator, offset = qubo.to_ising()
print(operator)
# ham = HamiltonianGate(operator,0)
# print(ham)
Ix = np.array([[1,0],[0,1]])
Zx= np.array([[1,0],[0,-1]])
Xx = np.array([[0,1],[1,0]])
Temp = (Ix-Zx)/2
T = Operator(Temp)
I = Operator(Ix)
Z = Operator(Zx)
X = Operator(Xx)
FinalOp=-2*(T^I^T)-(I^T^T)-(T^I^I)+2*(I^T^I)-3*(I^I^T)
ham = HamiltonianGate(FinalOp,0)
print(ham)
#define PYBIND11_DETAILED_ERROR_MESSAGES
def compute_expectation(counts):
"""
Computes expectation value based on measurement results
Args:
counts: dict
key as bitstring, val as count
G: networkx graph
Returns:
avg: float
expectation value
"""
avg = 0
sum_count = 0
for bitstring, count in counts.items():
x = int(bitstring[2])
y = int(bitstring[1])
z = int(bitstring[0])
obj = -2*x*z-y*z-x+2*y-3*z
avg += obj * count
sum_count += count
return avg/sum_count
# We will also bring the different circuit components that
# build the qaoa circuit under a single function
def create_qaoa_circ(theta):
"""
Creates a parametrized qaoa circuit
Args:
G: networkx graph
theta: list
unitary parameters
Returns:
qc: qiskit circuit
"""
nqubits = 3
n,m=3,3
p = len(theta)//2 # number of alternating unitaries
qc = QuantumCircuit(nqubits,nqubits)
Ix = np.array([[1,0],[0,1]])
Zx= np.array([[1,0],[0,-1]])
Xx = np.array([[0,1],[1,0]])
Temp = (Ix-Zx)/2
T = Operator(Temp)
I = Operator(Ix)
Z = Operator(Zx)
X = Operator(Xx)
FinalOp=-2*(Z^I^Z)-(I^Z^Z)-(Z^I^I)+2*(I^Z^I)-3*(I^I^Z)
beta = theta[:p]
gamma = theta[p:]
# initial_state
for i in range(0, nqubits):
qc.h(i)
for irep in range(0, p):
#ipdb.set_trace(context=6)
# problem unitary
# for pair in list(G.edges()):
# qc.rzz(2 * gamma[irep], pair[0], pair[1])
#ApplyCost(qc,2*0)
ham = HamiltonianGate(operator,2 * gamma[irep])
qc.append(ham,[0,1,2])
# mixer unitary
for i in range(0, nqubits):
qc.rx(2 * beta[irep], i)
qc.measure(qc.qubits[:n],qc.clbits[:m])
return qc
# Finally we write a function that executes the circuit on the chosen backend
def get_expectation(shots=512):
"""
Runs parametrized circuit
Args:
G: networkx graph
p: int,
Number of repetitions of unitaries
"""
backend = Aer.get_backend('qasm_simulator')
backend.shots = shots
def execute_circ(theta):
qc = create_qaoa_circ(theta)
# ipdb.set_trace(context=6)
counts = {}
job = execute(qc, backend, shots=1024)
result = job.result()
counts=result.get_counts(qc)
return compute_expectation(counts)
return execute_circ
from scipy.optimize import minimize
expectation = get_expectation()
res = minimize(expectation, [1, 1], method='COBYLA')
expectation = get_expectation()
res = minimize(expectation, res.x, method='COBYLA')
res
from qiskit.visualization import plot_histogram
backend = Aer.get_backend('aer_simulator')
backend.shots = 512
qc_res = create_qaoa_circ(res.x)
backend = Aer.get_backend('qasm_simulator')
job = execute(qc_res, backend, shots=1024)
result = job.result()
counts=result.get_counts(qc_res)
plot_histogram(counts)
|
https://github.com/KMU-quantum-classroom/qiskit-classroom-converter
|
KMU-quantum-classroom
|
"""
Base Converter
"""
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
from abc import ABC, abstractmethod
import qiskit
import qiskit_aer
from loguru import logger
class BaseConverter(ABC):
"""
Converter class
"""
def __init__(self, option=None):
"""
BaseConverter init value
"""
if option is None:
option = {}
self.option = option
self.input_value = None
self.qiskit = qiskit
self.qiskit_aer = qiskit_aer
self.logger = logger
def convert(self, input_value):
"""
convert main process
:return:
"""
self.input_value = input_value
return self.actual_convert_action()
@abstractmethod
def actual_convert_action(self):
"""
actual action
:return:
"""
raise NotImplementedError
|
https://github.com/usamisaori/Grover
|
usamisaori
|
import qiskit
from qiskit import QuantumCircuit
from qiskit.visualization import plot_histogram
from qiskit.quantum_info import Operator
import numpy as np
from qiskit import execute, Aer
simulator = Aer.get_backend('qasm_simulator')
import matplotlib.pyplot as plt
import warnings
warnings.filterwarnings('ignore')
# https://towardsdatascience.com/behind-oracles-grovers-algorithm-amplitude-amplification-46b928b46f1e
def createSATInitCircuit(var, clause):
# input + workspace(clause) + checker(1)
circuit = QuantumCircuit(var + clause + 1, var)
for i in range(var):
circuit.h(i)
circuit.barrier()
return circuit
SATInitCircuit = createSATInitCircuit(4, 3)
SATInitCircuit.draw(output='mpl')
def createSATOracle(var, clause):
circuit = QuantumCircuit(var + clause + 1, var)
# (a ∧ b ∧ ¬c)
circuit.x(2)
circuit.mcx([0, 1, 2], 4)
circuit.x(2)
circuit.barrier()
# (¬b ∧d )
circuit.x(1)
circuit.mcx([1, 3], 5)
circuit.x(1)
circuit.barrier()
# ¬d
circuit.x(3)
circuit.cx(3, 6)
circuit.x(3)
circuit.barrier()
# (a ∧ b ∧ ¬c) ∨ ¬(¬b ∧d ) ∨ ¬d
circuit.x(5)
circuit.mcx([4, 5, 6], 7)
circuit.x(5)
circuit.barrier()
# uncomputation
# ¬d
circuit.x(3)
circuit.cx(3, 6)
circuit.x(3)
circuit.barrier()
# (¬b ∧d )
circuit.x(1)
circuit.mcx([1, 3], 5)
circuit.x(1)
circuit.barrier()
# (a ∧ b ∧ ¬c)
circuit.x(2)
circuit.mcx([0, 1, 2], 4)
circuit.x(2)
circuit.barrier()
return circuit
SATOracleCircuit = createSATOracle(4, 3)
SATOracleCircuit.draw(output='mpl')
def createSATDiffuser(var, clause):
circuit = QuantumCircuit(var + clause + 1, var)
circuit.h(0)
circuit.h(1)
circuit.h(2)
circuit.h(3)
circuit.x(0)
circuit.x(1)
circuit.x(2)
circuit.x(3)
circuit.mcx([0, 1, 2, 3], var + clause)
circuit.x(0)
circuit.x(1)
circuit.x(2)
circuit.x(3)
circuit.h(0)
circuit.h(1)
circuit.h(2)
circuit.h(3)
return circuit
SATDiffuserCircuit = createSATDiffuser(4, 3)
SATDiffuserCircuit.draw(output='mpl')
SATCircuit = createSATInitCircuit(4, 3).compose(createSATOracle(4, 3)).compose(createSATDiffuser(4, 3))
SATCircuit.draw(output='mpl')
SATCircuit.measure([0, 1, 2, 3], [0, 1, 2, 3])
job = execute(SATCircuit, simulator, shots = 10000)
results = job.result()
counts = results.get_counts(SATCircuit)
print(counts)
plot_histogram(counts, figsize=(12, 5), color="#CCCCFF", title="SAT - solving (a ∧ b ∧ ¬c) ∨ ¬(¬b ∧d ) ∨ ¬d, k = 1")
SATIteration = Operator(createSATOracle(4, 3).compose(createSATDiffuser(4, 3)))
SATCircuit2 = createSATInitCircuit(4, 3)
SATCircuit2.append(SATIteration, list(range(8)))
SATCircuit2.append(SATIteration, list(range(8)))
SATCircuit2.append(SATIteration, list(range(8)))
SATCircuit2.draw(output='mpl')
SATCircuit2.measure([0, 1, 2, 3], [0, 1, 2, 3])
job = execute(SATCircuit2, simulator, shots = 10000)
results = job.result()
counts = results.get_counts(SATCircuit2)
print(counts)
plot_histogram(counts, figsize=(12, 5), color="#6666FF", title="SAT - solving (a ∧ b ∧ ¬c) ∨ ¬(¬b ∧d ) ∨ ¬d, k = 3")
import math
math.degrees( math.asin(1 / 4))
for k in range(1, 5):
print(f'k = {k}: { math.sin(math.radians( (2 * k+1) * 14.47) ) ** 2 }')
|
https://github.com/TanveshT/IBM-Quantum-Challenge
|
TanveshT
|
%matplotlib inline
# Importing standard Qiskit libraries
import random
from qiskit import execute, Aer, IBMQ, QuantumCircuit
from qiskit.tools.jupyter import *
from qiskit.visualization import *
from may4_challenge.ex3 import alice_prepare_qubit, check_bits, check_key, check_decrypted, show_message
# Configuring account
provider = IBMQ.load_account()
backend = provider.get_backend('ibmq_qasm_simulator') # with this simulator it wouldn't work \
# Initial setup
random.seed(84) # do not change this seed, otherwise you will get a different key
# This is your 'random' bit string that determines your bases
numqubits = 100
bob_bases = str('{0:0100b}'.format(random.getrandbits(numqubits)))
def bb84():
print('Bob\'s bases:', bob_bases)
# Now Alice will send her bits one by one...
all_qubit_circuits = []
for qubit_index in range(numqubits):
# This is Alice creating the qubit
thisqubit_circuit = alice_prepare_qubit(qubit_index)
# This is Bob finishing the protocol below
bob_measure_qubit(bob_bases, qubit_index, thisqubit_circuit)
# We collect all these circuits and put them in an array
all_qubit_circuits.append(thisqubit_circuit)
# Now execute all the circuits for each qubit
results = execute(all_qubit_circuits, backend=backend, shots=1).result()
# And combine the results
bits = ''
for qubit_index in range(numqubits):
bits += [measurement for measurement in results.get_counts(qubit_index)][0]
return bits
# Here is your task
def bob_measure_qubit(bob_bases, qubit_index, qubit_circuit):
#
#
# insert your code here to measure Alice's bits
#
#
if bob_bases[qubit_index] == '1':
qubit_circuit.h(0)
qubit_circuit.measure(0,0)
bits = bb84()
print('Bob\'s bits: ', bits)
check_bits(bits)
alice_bases = '10000000000100011111110011011001010001111101001101111110001100000110000010011000111'\
'00111010010000110' # Alice's bases bits
#
#
# insert your code here to extract the key
#
#
key = ''
n = len(alice_bases)
for i in range(n):
if bob_bases[i] == alice_bases[i]:
key+=bits[i]
check_key(key)
m = '0011011010100011101000001100010000001000011000101110110111100111111110001111100011100101011010111010111010001'\
'1101010010111111100101000011010011011011011101111010111000101111111001010101001100101111011' # encrypted message
#
#
# insert your code here to decrypt the message
#
#
n = len(m)
decrypted = ''
for i in range(n):
decrypted += str( int(key[i%50]) ^ int(m[i]) )
check_decrypted(decrypted)
MORSE_CODE_DICT = { 'a':'.-', 'b':'-...',
'c':'-.-.', 'd':'-..', 'e':'.',
'f':'..-.', 'g':'--.', 'h':'....',
'i':'..', 'j':'.---', 'k':'-.-',
'l':'.-..', 'm':'--', 'n':'-.',
'o':'---', 'p':'.--.', 'q':'--.-',
'r':'.-.', 's':'...', 't':'-',
'u':'..-', 'v':'...-', 'w':'.--',
'x':'-..-', 'y':'-.--', 'z':'--..',
'1':'.----', '2':'..---', '3':'...--',
'4':'....-', '5':'.....', '6':'-....',
'7':'--...', '8':'---..', '9':'----.',
'0':'-----', ', ':'--..--', '.':'.-.-.-',
'?':'..--..', '/':'-..-.', '-':'-....-',
'(':'-.--.', ')':'-.--.-'}
#
#
# insert your code here to decode Alice's Morse code
#
#
MORSE_CODE_REVERSE_DICT = dict([(value, key) for key, value in MORSE_CODE_DICT.items()])
solution = ''
for word in decrypted.split('000'):
for letter in word.split('00'):
full_code = ''
for morse_character in letter.split('0'):
if morse_character == '1': full_code += '.'
else: full_code += '-'
solution += MORSE_CODE_REVERSE_DICT[full_code]
solution+= ' '
show_message(solution)
|
https://github.com/vm6502q/qiskit-qrack-provider
|
vm6502q
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2018, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""
QasmSimulator Integration Tests
"""
from test.terra.reference import ref_multiplexer
from qiskit import execute
from qiskit.providers.qrack import QasmSimulator
class QasmMultiplexerTests:
"""QasmSimulator multiplexer gate tests in default basis."""
SIMULATOR = QasmSimulator()
BACKEND_OPTS = {}
# ---------------------------------------------------------------------
# Test multiplexer-cx-gate
# ---------------------------------------------------------------------
def test_multiplexer_cx_gate_deterministic(self):
"""Test multiplxer cx-gate circuits compiling to backend default basis_gates."""
shots = 100
circuits = ref_multiplexer.multiplexer_cx_gate_circuits_deterministic(
final_measure=True)
targets = ref_multiplexer.multiplexer_cx_gate_counts_deterministic(shots)
job = execute(circuits, self.SIMULATOR, shots=shots, **self.BACKEND_OPTS)
result = job.result()
self.assertSuccess(result)
self.compare_counts(result, circuits, targets, delta=0)
def test_multiplexer_cx_gate_nondeterministic(self):
"""Test multiplexer cx-gate circuits compiling to backend default basis_gates."""
shots = 4000
circuits = ref_multiplexer.multiplexer_cx_gate_circuits_nondeterministic(
final_measure=True)
targets = ref_multiplexer.multiplexer_cx_gate_counts_nondeterministic(shots)
job = execute(circuits, self.SIMULATOR, shots=shots, **self.BACKEND_OPTS)
result = job.result()
self.assertSuccess(result)
self.compare_counts(result, circuits, targets, delta=0.05 * shots)
# ---------------------------------------------------------------------
# Test multiplexer-gate
# ---------------------------------------------------------------------
def test_multiplexer_cxx_gate_deterministic(self):
"""Test multiplexer-gate gate circuits """
shots = 100
circuits = ref_multiplexer.multiplexer_ccx_gate_circuits_deterministic(
final_measure=True)
targets = ref_multiplexer.multiplexer_ccx_gate_counts_deterministic(
shots)
job = execute(circuits, self.SIMULATOR, shots=shots,
**self.BACKEND_OPTS)
result = job.result()
self.assertSuccess(result)
self.compare_counts(result, circuits, targets, delta=0)
def test_multiplexer_cxx_gate_nondeterministic(self):
"""Test multiplexer ccx-gate gate circuits """
shots = 4000
circuits = ref_multiplexer.multiplexer_ccx_gate_circuits_nondeterministic(
final_measure=True)
targets = ref_multiplexer.multiplexer_ccx_gate_counts_nondeterministic(
shots)
job = execute(circuits, self.SIMULATOR, shots=shots,
**self.BACKEND_OPTS)
result = job.result()
self.assertSuccess(result)
self.compare_counts(result, circuits, targets, delta=0.05 * shots)
|
https://github.com/AbdulahAmer/PHYS-31415-Summer-2021
|
AbdulahAmer
|
just_an_integer = 12 # a plain old number with no fractional parts
a_float = 3.1415 # a float is a decimal that has a certain number of digits
plain_old_string = 'Hey, I am a string!' # a character or list of characters wrapped in single or double quotes
boolean_true = True # True or false, good for ifelse statements and comparative operators
boolean_false = False
a_list = [ True, 6, 18.99, "potato", False] # a list is a list (duh) of elements that can have lots of different data types
# or even a single type or even other lists with their own elemetns!
|
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/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 BasicSwap pass"""
import unittest
from qiskit.transpiler.passes import BasicSwap
from qiskit.transpiler.passmanager import PassManager
from qiskit.transpiler.layout import Layout
from qiskit.transpiler import CouplingMap, Target
from qiskit.circuit.library import CXGate
from qiskit.converters import circuit_to_dag
from qiskit import QuantumRegister, QuantumCircuit
from qiskit.test import QiskitTestCase
class TestBasicSwap(QiskitTestCase):
"""Tests the BasicSwap pass."""
def test_trivial_case(self):
"""No need to have any swap, the CX are distance 1 to each other
q0:--(+)-[U]-(+)-
| |
q1:---.-------|--
|
q2:-----------.--
CouplingMap map: [1]--[0]--[2]
"""
coupling = CouplingMap([[0, 1], [0, 2]])
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[1])
circuit.h(qr[0])
circuit.cx(qr[0], qr[2])
dag = circuit_to_dag(circuit)
pass_ = BasicSwap(coupling)
after = pass_.run(dag)
self.assertEqual(dag, after)
def test_trivial_in_same_layer(self):
"""No need to have any swap, two CXs distance 1 to each other, in the same layer
q0:--(+)--
|
q1:---.---
q2:--(+)--
|
q3:---.---
CouplingMap map: [0]--[1]--[2]--[3]
"""
coupling = CouplingMap([[0, 1], [1, 2], [2, 3]])
qr = QuantumRegister(4, "q")
circuit = QuantumCircuit(qr)
circuit.cx(qr[2], qr[3])
circuit.cx(qr[0], qr[1])
dag = circuit_to_dag(circuit)
pass_ = BasicSwap(coupling)
after = pass_.run(dag)
self.assertEqual(dag, after)
def test_a_single_swap(self):
"""Adding a swap
q0:-------
q1:--(+)--
|
q2:---.---
CouplingMap map: [1]--[0]--[2]
q0:--X---.---
| |
q1:--X---|---
|
q2:-----(+)--
"""
coupling = CouplingMap([[0, 1], [0, 2]])
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
circuit.cx(qr[1], qr[2])
dag = circuit_to_dag(circuit)
expected = QuantumCircuit(qr)
expected.swap(qr[1], qr[0])
expected.cx(qr[0], qr[2])
pass_ = BasicSwap(coupling)
after = pass_.run(dag)
self.assertEqual(circuit_to_dag(expected), after)
def test_a_single_swap_with_target(self):
"""Adding a swap
q0:-------
q1:--(+)--
|
q2:---.---
CouplingMap map: [1]--[0]--[2]
q0:--X---.---
| |
q1:--X---|---
|
q2:-----(+)--
"""
target = Target()
target.add_instruction(CXGate(), {(0, 1): None, (0, 2): None})
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
circuit.cx(qr[1], qr[2])
dag = circuit_to_dag(circuit)
expected = QuantumCircuit(qr)
expected.swap(qr[1], qr[0])
expected.cx(qr[0], qr[2])
pass_ = BasicSwap(target)
after = pass_.run(dag)
self.assertEqual(circuit_to_dag(expected), after)
def test_a_single_swap_bigger_cm(self):
"""Swapper in a bigger coupling map
q0:-------
q1:---.---
|
q2:--(+)--
CouplingMap map: [1]--[0]--[2]--[3]
q0:--X---.---
| |
q1:--X---|---
|
q2:-----(+)--
"""
coupling = CouplingMap([[0, 1], [0, 2], [2, 3]])
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
circuit.cx(qr[1], qr[2])
dag = circuit_to_dag(circuit)
expected = QuantumCircuit(qr)
expected.swap(qr[1], qr[0])
expected.cx(qr[0], qr[2])
pass_ = BasicSwap(coupling)
after = pass_.run(dag)
self.assertEqual(circuit_to_dag(expected), after)
def test_keep_layout(self):
"""After a swap, the following gates also change the wires.
qr0:---.---[H]--
|
qr1:---|--------
|
qr2:--(+)-------
CouplingMap map: [0]--[1]--[2]
qr0:--X-----------
|
qr1:--X---.--[H]--
|
qr2:-----(+)------
"""
coupling = CouplingMap([[1, 0], [1, 2]])
qr = QuantumRegister(3, "q")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[2])
circuit.h(qr[0])
dag = circuit_to_dag(circuit)
expected = QuantumCircuit(qr)
expected.swap(qr[0], qr[1])
expected.cx(qr[1], qr[2])
expected.h(qr[1])
pass_ = BasicSwap(coupling)
after = pass_.run(dag)
self.assertEqual(circuit_to_dag(expected), after)
def test_far_swap(self):
"""A far swap that affects coming CXs.
qr0:--(+)---.--
| |
qr1:---|----|--
| |
qr2:---|----|--
| |
qr3:---.---(+)-
CouplingMap map: [0]--[1]--[2]--[3]
qr0:--X--------------
|
qr1:--X--X-----------
|
qr2:-----X--(+)---.--
| |
qr3:---------.---(+)-
"""
coupling = CouplingMap([[0, 1], [1, 2], [2, 3]])
qr = QuantumRegister(4, "q")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[3])
circuit.cx(qr[3], qr[0])
dag = circuit_to_dag(circuit)
expected = QuantumCircuit(qr)
expected.swap(qr[0], qr[1])
expected.swap(qr[1], qr[2])
expected.cx(qr[2], qr[3])
expected.cx(qr[3], qr[2])
pass_ = BasicSwap(coupling)
after = pass_.run(dag)
self.assertEqual(circuit_to_dag(expected), after)
def test_far_swap_with_gate_the_front(self):
"""A far swap with a gate in the front.
q0:------(+)--
|
q1:-------|---
|
q2:-------|---
|
q3:--[H]--.---
CouplingMap map: [0]--[1]--[2]--[3]
q0:-----------(+)--
|
q1:---------X--.---
|
q2:------X--X------
|
q3:-[H]--X---------
"""
coupling = CouplingMap([[0, 1], [1, 2], [2, 3]])
qr = QuantumRegister(4, "q")
circuit = QuantumCircuit(qr)
circuit.h(qr[3])
circuit.cx(qr[3], qr[0])
dag = circuit_to_dag(circuit)
expected = QuantumCircuit(qr)
expected.h(qr[3])
expected.swap(qr[3], qr[2])
expected.swap(qr[2], qr[1])
expected.cx(qr[1], qr[0])
pass_ = BasicSwap(coupling)
after = pass_.run(dag)
self.assertEqual(circuit_to_dag(expected), after)
def test_far_swap_with_gate_the_back(self):
"""A far swap with a gate in the back.
q0:--(+)------
|
q1:---|-------
|
q2:---|-------
|
q3:---.--[H]--
CouplingMap map: [0]--[1]--[2]--[3]
q0:-------(+)------
|
q1:-----X--.--[H]--
|
q2:--X--X----------
|
q3:--X-------------
"""
coupling = CouplingMap([[0, 1], [1, 2], [2, 3]])
qr = QuantumRegister(4, "q")
circuit = QuantumCircuit(qr)
circuit.cx(qr[3], qr[0])
circuit.h(qr[3])
dag = circuit_to_dag(circuit)
expected = QuantumCircuit(qr)
expected.swap(qr[3], qr[2])
expected.swap(qr[2], qr[1])
expected.cx(qr[1], qr[0])
expected.h(qr[1])
pass_ = BasicSwap(coupling)
after = pass_.run(dag)
self.assertEqual(circuit_to_dag(expected), after)
def test_far_swap_with_gate_the_middle(self):
"""A far swap with a gate in the middle.
q0:--(+)-------.--
| |
q1:---|--------|--
|
q2:---|--------|--
| |
q3:---.--[H]--(+)-
CouplingMap map: [0]--[1]--[2]--[3]
q0:-------(+)-------.---
| |
q1:-----X--.--[H]--(+)--
|
q2:--X--X---------------
|
q3:--X------------------
"""
coupling = CouplingMap([[0, 1], [1, 2], [2, 3]])
qr = QuantumRegister(4, "q")
circuit = QuantumCircuit(qr)
circuit.cx(qr[3], qr[0])
circuit.h(qr[3])
circuit.cx(qr[0], qr[3])
dag = circuit_to_dag(circuit)
expected = QuantumCircuit(qr)
expected.swap(qr[3], qr[2])
expected.swap(qr[2], qr[1])
expected.cx(qr[1], qr[0])
expected.h(qr[1])
expected.cx(qr[0], qr[1])
pass_ = BasicSwap(coupling)
after = pass_.run(dag)
self.assertEqual(circuit_to_dag(expected), after)
def test_fake_run(self):
"""A fake run, doesn't change dag
q0:--(+)-------.--
| |
q1:---|--------|--
|
q2:---|--------|--
| |
q3:---.--[H]--(+)-
CouplingMap map: [0]--[1]--[2]--[3]
q0:-------(+)-------.---
| |
q1:-----X--.--[H]--(+)--
|
q2:--X--X---------------
|
q3:--X------------------
"""
coupling = CouplingMap([[0, 1], [1, 2], [2, 3]])
qr = QuantumRegister(4, "q")
circuit = QuantumCircuit(qr)
circuit.cx(qr[3], qr[0])
circuit.h(qr[3])
circuit.cx(qr[0], qr[3])
fake_pm = PassManager([BasicSwap(coupling, fake_run=True)])
real_pm = PassManager([BasicSwap(coupling, fake_run=False)])
self.assertEqual(circuit, fake_pm.run(circuit))
self.assertNotEqual(circuit, real_pm.run(circuit))
self.assertIsInstance(fake_pm.property_set["final_layout"], Layout)
self.assertEqual(fake_pm.property_set["final_layout"], real_pm.property_set["final_layout"])
if __name__ == "__main__":
unittest.main()
|
https://github.com/mmetcalf14/Hamiltonian_Downfolding_IBM
|
mmetcalf14
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2018.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""
Implementation of Sven Jandura's swap mapper submission for the 2018 QISKit
Developer Challenge, adapted to integrate into the transpiler architecture.
The role of the mapper pass is to modify the starting circuit to be compatible
with the target device's topology (the set of two-qubit gates available on the
hardware.) To do this, the mapper will insert SWAP gates to relocate the virtual
qubits for each upcoming gate onto a set of coupled physical qubits. However, as
SWAP gates are particularly lossy, the goal is to accomplish this remapping while
introducing the fewest possible additional SWAPs.
This algorithm searches through the available combinations of SWAP gates by means
of a narrowed best first/beam search, described as follows:
- Start with a layout of virtual qubits onto physical qubits.
- Find any gates in the input circuit which can be performed with the current
layout and mark them as mapped.
- For all possible SWAP gates, calculate the layout that would result from their
application and rank them according to the distance of the resulting layout
over upcoming gates (see _calc_layout_distance.)
- For the four (SEARCH_WIDTH) highest-ranking SWAPs, repeat the above process on
the layout that would be generated if they were applied.
- Repeat this process down to a depth of four (SEARCH_DEPTH) SWAPs away from the
initial layout, for a total of 256 (SEARCH_WIDTH^SEARCH_DEPTH) prospective
layouts.
- Choose the layout which maximizes the number of two-qubit which could be
performed. Add its mapped gates, including the SWAPs generated, to the
output circuit.
- Repeat the above until all gates from the initial circuit are mapped.
For more details on the algorithm, see Sven's blog post:
https://medium.com/qiskit/improving-a-quantum-compiler-48410d7a7084
"""
from copy import deepcopy
from qiskit import QuantumRegister
from qiskit.dagcircuit import DAGCircuit
from qiskit.extensions.standard import SwapGate
from qiskit.transpiler.basepasses import TransformationPass
from qiskit.transpiler.exceptions import TranspilerError
from qiskit.transpiler import Layout
from qiskit.dagcircuit import DAGNode
SEARCH_DEPTH = 4
SEARCH_WIDTH = 4
class LookaheadSwap(TransformationPass):
"""Map input circuit onto a backend topology via insertion of SWAPs."""
def __init__(self, coupling_map, initial_layout=None):
"""Initialize a LookaheadSwap instance.
Arguments:
coupling_map (CouplingMap): CouplingMap of the target backend.
initial_layout (Layout): The initial layout of the DAG to analyze.
"""
super().__init__()
self._coupling_map = coupling_map
self.initial_layout = initial_layout
def run(self, dag):
"""Run one pass of the lookahead mapper on the provided DAG.
Args:
dag (DAGCircuit): the directed acyclic graph to be mapped
Returns:
DAGCircuit: A dag mapped to be compatible with the coupling_map in
the property_set.
Raises:
TranspilerError: if the coupling map or the layout are not
compatible with the DAG
"""
coupling_map = self._coupling_map
ordered_virtual_gates = list(dag.serial_layers())
if self.initial_layout is None:
if self.property_set["layout"]:
self.initial_layout = self.property_set["layout"]
else:
self.initial_layout = Layout.generate_trivial_layout(*dag.qregs.values())
if len(dag.qubits()) != len(self.initial_layout):
raise TranspilerError('The layout does not match the amount of qubits in the DAG')
if len(self._coupling_map.physical_qubits) != len(self.initial_layout):
raise TranspilerError(
"Mappers require to have the layout to be the same size as the coupling map")
mapped_gates = []
layout = self.initial_layout.copy()
gates_remaining = ordered_virtual_gates.copy()
while gates_remaining:
best_step = _search_forward_n_swaps(layout, gates_remaining,
coupling_map)
layout = best_step['layout']
gates_mapped = best_step['gates_mapped']
gates_remaining = best_step['gates_remaining']
mapped_gates.extend(gates_mapped)
# Preserve input DAG's name, regs, wire_map, etc. but replace the graph.
mapped_dag = _copy_circuit_metadata(dag, coupling_map)
for node in mapped_gates:
mapped_dag.apply_operation_back(op=node.op, qargs=node.qargs, cargs=node.cargs)
return mapped_dag
def _search_forward_n_swaps(layout, gates, coupling_map,
depth=SEARCH_DEPTH, width=SEARCH_WIDTH):
"""Search for SWAPs which allow for application of largest number of gates.
Arguments:
layout (Layout): Map from virtual qubit index to physical qubit index.
gates (list): Gates to be mapped.
coupling_map (CouplingMap): CouplingMap of the target backend.
depth (int): Number of SWAP layers to search before choosing a result.
width (int): Number of SWAPs to consider at each layer.
Returns:
dict: Describes solution step found.
layout (Layout): Virtual to physical qubit map after SWAPs.
gates_remaining (list): Gates that could not be mapped.
gates_mapped (list): Gates that were mapped, including added SWAPs.
"""
gates_mapped, gates_remaining = _map_free_gates(layout, gates, coupling_map)
base_step = {'layout': layout,
'swaps_added': 0,
'gates_mapped': gates_mapped,
'gates_remaining': gates_remaining}
if not gates_remaining or depth == 0:
return base_step
possible_swaps = coupling_map.get_edges()
def _score_swap(swap):
"""Calculate the relative score for a given SWAP."""
trial_layout = layout.copy()
trial_layout.swap(*swap)
return _calc_layout_distance(gates, coupling_map, trial_layout)
ranked_swaps = sorted(possible_swaps, key=_score_swap)
best_swap, best_step = None, None
for swap in ranked_swaps[:width]:
trial_layout = layout.copy()
trial_layout.swap(*swap)
next_step = _search_forward_n_swaps(trial_layout, gates_remaining,
coupling_map, depth - 1, width)
# ranked_swaps already sorted by distance, so distance is the tie-breaker.
if best_swap is None or _score_step(next_step) > _score_step(best_step):
best_swap, best_step = swap, next_step
best_swap_gate = _swap_ops_from_edge(best_swap, layout)
return {
'layout': best_step['layout'],
'swaps_added': 1 + best_step['swaps_added'],
'gates_remaining': best_step['gates_remaining'],
'gates_mapped': gates_mapped + best_swap_gate + best_step['gates_mapped'],
}
def _map_free_gates(layout, gates, coupling_map):
"""Map all gates that can be executed with the current layout.
Args:
layout (Layout): Map from virtual qubit index to physical qubit index.
gates (list): Gates to be mapped.
coupling_map (CouplingMap): CouplingMap for target device topology.
Returns:
tuple:
mapped_gates (list): ops for gates that can be executed, mapped onto layout.
remaining_gates (list): gates that cannot be executed on the layout.
"""
blocked_qubits = set()
mapped_gates = []
remaining_gates = []
for gate in gates:
# Gates without a partition (barrier, snapshot, save, load, noise) may
# still have associated qubits. Look for them in the qargs.
if not gate['partition']:
qubits = [n for n in gate['graph'].nodes() if n.type == 'op'][0].qargs
if not qubits:
continue
if blocked_qubits.intersection(qubits):
blocked_qubits.update(qubits)
remaining_gates.append(gate)
else:
mapped_gate = _transform_gate_for_layout(gate, layout)
mapped_gates.append(mapped_gate)
continue
qubits = gate['partition'][0]
if blocked_qubits.intersection(qubits):
blocked_qubits.update(qubits)
remaining_gates.append(gate)
elif len(qubits) == 1:
mapped_gate = _transform_gate_for_layout(gate, layout)
mapped_gates.append(mapped_gate)
elif coupling_map.distance(*[layout[q] for q in qubits]) == 1:
mapped_gate = _transform_gate_for_layout(gate, layout)
mapped_gates.append(mapped_gate)
else:
blocked_qubits.update(qubits)
remaining_gates.append(gate)
return mapped_gates, remaining_gates
def _calc_layout_distance(gates, coupling_map, layout, max_gates=None):
"""Return the sum of the distances of two-qubit pairs in each CNOT in gates
according to the layout and the coupling.
"""
if max_gates is None:
max_gates = 50 + 10 * len(coupling_map.physical_qubits)
return sum(coupling_map.distance(*[layout[q] for q in gate['partition'][0]])
for gate in gates[:max_gates]
if gate['partition'] and len(gate['partition'][0]) == 2)
def _score_step(step):
"""Count the mapped two-qubit gates, less the number of added SWAPs."""
# Each added swap will add 3 ops to gates_mapped, so subtract 3.
return len([g for g in step['gates_mapped']
if len(g.qargs) == 2]) - 3 * step['swaps_added']
def _copy_circuit_metadata(source_dag, coupling_map):
"""Return a copy of source_dag with metadata but empty.
Generate only a single qreg in the output DAG, matching the size of the
coupling_map."""
target_dag = DAGCircuit()
target_dag.name = source_dag.name
for creg in source_dag.cregs.values():
target_dag.add_creg(creg)
device_qreg = QuantumRegister(len(coupling_map.physical_qubits), 'q')
target_dag.add_qreg(device_qreg)
return target_dag
def _transform_gate_for_layout(gate, layout):
"""Return op implementing a virtual gate on given layout."""
mapped_op_node = deepcopy([n for n in gate['graph'].nodes() if n.type == 'op'][0])
# Workaround until #1816, apply mapped to qargs to both DAGNode and op
device_qreg = QuantumRegister(len(layout.get_physical_bits()), 'q')
mapped_qargs = [(device_qreg, layout[a]) for a in mapped_op_node.qargs]
mapped_op_node.qargs = mapped_op_node.op.qargs = mapped_qargs
mapped_op_node.pop('name')
return mapped_op_node
def _swap_ops_from_edge(edge, layout):
"""Generate list of ops to implement a SWAP gate along a coupling edge."""
device_qreg = QuantumRegister(len(layout.get_physical_bits()), 'q')
qreg_edge = [(device_qreg, i) for i in edge]
# TODO shouldn't be making other nodes not by the DAG!!
return [
DAGNode({'op': SwapGate(), 'qargs': qreg_edge, 'cargs': [], 'type': 'op'})
]
|
https://github.com/ahkatlio/QHSO_Basics_of_Qiskit
|
ahkatlio
|
# We import necessary libraries from Qiskit
from qiskit import QuantumCircuit, Aer, execute
from qiskit.visualization import plot_histogram
# We create a quantum circuit with two qubits and two classical bits
qc = QuantumCircuit(2, 2)
# We apply the CX gate with the first qubit as control and the second qubit as target
control_qubit = 0
target_qubit = 1
qc.cx(control_qubit, target_qubit)
qc.measure([0, 1], [0, 1])
# We visualize the quantum circuit
qc.draw('mpl')
# We simulate the quantum circuit
simulator = Aer.get_backend('qasm_simulator')
result = execute(qc, simulator).result()
# We get the measurement results
counts = result.get_counts(qc)
# We visualize the measurement results
plot_histogram(counts)
qc1 = QuantumCircuit(2, 2)
qc1.x(1)
qc1.cx(0, 1)
qc1.measure([0, 1], [0, 1])
qc1.draw('mpl')
# We simulate the quantum circuit
simulator = Aer.get_backend('qasm_simulator')
result = execute(qc1, simulator).result()
# We get the measurement results
counts = result.get_counts(qc1)
# We visualize the measurement results
plot_histogram(counts)
qc2 = QuantumCircuit(2, 2)
qc2.x(0)
qc2.cx(0, 1)
qc2.measure([0, 1], [0, 1])
qc2.draw('mpl')
# We simulate the quantum circuit
simulator = Aer.get_backend('qasm_simulator')
result = execute(qc2, simulator).result()
# We get the measurement results
counts = result.get_counts(qc2)
# We visualize the measurement results
plot_histogram(counts)
magical_circuit = QuantumCircuit(2, 2)
magical_circuit.x(1)
magical_circuit.barrier()
magical_circuit.h(0)
magical_circuit.h(1)
magical_circuit.cx(0, 1)
magical_circuit.h(0)
magical_circuit.h(1)
magical_circuit.barrier()
magical_circuit.measure([0, 1], [0, 1])
magical_circuit.draw('mpl')
simulator = Aer.get_backend('qasm_simulator')
result = execute(magical_circuit, simulator).result()
counts = result.get_counts(magical_circuit)
plot_histogram(counts)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit.quantum_info import SparsePauliOp
H2_op = SparsePauliOp.from_list(
[
("II", -1.052373245772859),
("IZ", 0.39793742484318045),
("ZI", -0.39793742484318045),
("ZZ", -0.01128010425623538),
("XX", 0.18093119978423156),
]
)
print(f"Number of qubits: {H2_op.num_qubits}")
from qiskit.algorithms import NumPyMinimumEigensolver
from qiskit.opflow import PauliSumOp
numpy_solver = NumPyMinimumEigensolver()
result = numpy_solver.compute_minimum_eigenvalue(operator=PauliSumOp(H2_op))
ref_value = result.eigenvalue.real
print(f"Reference value: {ref_value:.5f}")
# define ansatz and optimizer
from qiskit.circuit.library import TwoLocal
from qiskit.algorithms.optimizers import SPSA
iterations = 125
ansatz = TwoLocal(rotation_blocks="ry", entanglement_blocks="cz")
spsa = SPSA(maxiter=iterations)
# define callback
# note: Re-run this cell to restart lists before training
counts = []
values = []
def store_intermediate_result(eval_count, parameters, mean, std):
counts.append(eval_count)
values.append(mean)
# define Aer Estimator for noiseless statevector simulation
from qiskit.utils import algorithm_globals
from qiskit_aer.primitives import Estimator as AerEstimator
seed = 170
algorithm_globals.random_seed = seed
noiseless_estimator = AerEstimator(
run_options={"seed": seed, "shots": 1024},
transpile_options={"seed_transpiler": seed},
)
# instantiate and run VQE
from qiskit.algorithms.minimum_eigensolvers import VQE
vqe = VQE(
noiseless_estimator, ansatz, optimizer=spsa, callback=store_intermediate_result
)
result = vqe.compute_minimum_eigenvalue(operator=H2_op)
print(f"VQE on Aer qasm simulator (no noise): {result.eigenvalue.real:.5f}")
print(
f"Delta from reference energy value is {(result.eigenvalue.real - ref_value):.5f}"
)
import pylab
pylab.rcParams["figure.figsize"] = (12, 4)
pylab.plot(counts, values)
pylab.xlabel("Eval count")
pylab.ylabel("Energy")
pylab.title("Convergence with no noise")
from qiskit_aer.noise import NoiseModel
from qiskit.providers.fake_provider import FakeVigo
# fake providers contain data from real IBM Quantum devices stored in Qiskit Terra,
# and are useful for extracting realistic noise models.
device = FakeVigo()
coupling_map = device.configuration().coupling_map
noise_model = NoiseModel.from_backend(device)
print(noise_model)
noisy_estimator = AerEstimator(
backend_options={
"method": "density_matrix",
"coupling_map": coupling_map,
"noise_model": noise_model,
},
run_options={"seed": seed, "shots": 1024},
transpile_options={"seed_transpiler": seed},
)
# re-start callback variables
counts = []
values = []
vqe.estimator = noisy_estimator
result1 = vqe.compute_minimum_eigenvalue(operator=H2_op)
print(f"VQE on Aer qasm simulator (with noise): {result1.eigenvalue.real:.5f}")
print(
f"Delta from reference energy value is {(result1.eigenvalue.real - ref_value):.5f}"
)
if counts or values:
pylab.rcParams["figure.figsize"] = (12, 4)
pylab.plot(counts, values)
pylab.xlabel("Eval count")
pylab.ylabel("Energy")
pylab.title("Convergence with noise")
print(f"Reference value: {ref_value:.5f}")
print(f"VQE on Aer qasm simulator (no noise): {result.eigenvalue.real:.5f}")
print(f"VQE on Aer qasm simulator (with noise): {result1.eigenvalue.real:.5f}")
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/MonitSharma/Qiskit-Summer-School-and-Quantum-Challenges
|
MonitSharma
|
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
|
# You can set a color for all the bars.
from qiskit import QuantumCircuit
from qiskit.quantum_info import Statevector
from qiskit.visualization import plot_state_paulivec
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
state = Statevector(qc)
plot_state_paulivec(state, color='midnightblue', title="New PauliVec plot")
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
# Useful additional packages
import matplotlib.pyplot as plt
import numpy as np
from math import pi
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, transpile
from qiskit.tools.visualization import circuit_drawer
from qiskit.quantum_info import state_fidelity
from qiskit import BasicAer
backend = BasicAer.get_backend('unitary_simulator')
q = QuantumRegister(1)
qc = QuantumCircuit(q)
qc.u(pi/2,pi/4,pi/8,q)
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.p(pi/2,q)
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.id(q)
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.x(q)
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.y(q)
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.z(q)
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.h(q)
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.s(q)
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.sdg(q)
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.t(q)
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.tdg(q)
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.rx(pi/2,q)
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.ry(pi/2,q)
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.rz(pi/2,q)
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_unitary(qc, decimals=3)
q = QuantumRegister(2)
qc = QuantumCircuit(q)
qc.cx(q[0],q[1])
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.cy(q[0],q[1])
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.cz(q[0],q[1])
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.ch(q[0],q[1])
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.crz(pi/2,q[0],q[1])
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.cp(pi/2,q[0], q[1])
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.cu(pi/2, pi/2, pi/2, 0, q[0], q[1])
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.swap(q[0], q[1])
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_unitary(qc, decimals=3)
q = QuantumRegister(3)
qc = QuantumCircuit(q)
qc.ccx(q[0], q[1], q[2])
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_unitary(qc, decimals=3)
qc = QuantumCircuit(q)
qc.cswap(q[0], q[1], q[2])
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_unitary(qc, decimals=3)
q = QuantumRegister(1)
c = ClassicalRegister(1)
qc = QuantumCircuit(q, c)
qc.measure(q, c)
qc.draw()
backend = BasicAer.get_backend('qasm_simulator')
job = backend.run(transpile(qc, backend))
job.result().get_counts(qc)
qc = QuantumCircuit(q, c)
qc.h(q)
qc.measure(q, c)
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_counts(qc)
qc = QuantumCircuit(q, c)
qc.reset(q[0])
qc.measure(q, c)
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_counts(qc)
qc = QuantumCircuit(q, c)
qc.h(q)
qc.reset(q[0])
qc.measure(q, c)
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_counts(qc)
qc = QuantumCircuit(q, c)
qc.x(q[0]).c_if(c, 0)
qc.measure(q,c)
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_counts(qc)
qc = QuantumCircuit(q, c)
qc.h(q)
qc.measure(q,c)
qc.x(q[0]).c_if(c, 0)
qc.measure(q,c)
qc.draw()
job = backend.run(transpile(qc, backend))
job.result().get_counts(qc)
# Initializing a three-qubit quantum state
import math
desired_vector = [
1 / math.sqrt(16) * complex(0, 1),
1 / math.sqrt(8) * complex(1, 0),
1 / math.sqrt(16) * complex(1, 1),
0,
0,
1 / math.sqrt(8) * complex(1, 2),
1 / math.sqrt(16) * complex(1, 0),
0]
q = QuantumRegister(3)
qc = QuantumCircuit(q)
qc.initialize(desired_vector, [q[0],q[1],q[2]])
qc.draw()
backend = BasicAer.get_backend('statevector_simulator')
job = backend.run(transpile(qc, backend))
qc_state = job.result().get_statevector(qc)
qc_state
state_fidelity(desired_vector,qc_state)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/rainmaker29/QuantumComputing-qiskit
|
rainmaker29
|
import qiskit as q
%matplotlib inline
# Creating a quantum circuit with 3 qbits
circuit = q.QuantumCircuit(2,2)
#Adding a NOT gate to 0th qbit which flips the input
circuit.x(0)
#Adding a 'Controlled NOT' gate between 0th,1st qbits
#CNOT Gate operation : The second bit is flipped if the first bit is 1
circuit.cx(0,1)
#Mapping the value of qbit to classical bits (collapse)
circuit.measure([0,1],[0,1])
circuit.draw()
circuit.draw(output="mpl")
from qiskit import IBMQ
IBMQ.save_account("e870e2997e01a21385263381f81495beff826d71a12d646658a7a15ffc5400dbbefa30e9ce0d2e65b872b30170038db21cdf8482e422510d62ef16297ad5c8a2")
IBMQ.load_account()
IBMQ.providers()
provider = IBMQ.get_provider("ibm-q")
# In QC practice,a simulator or a quantum computer is referred to as 'backend'
for backend in provider.backends():
try:
qubit_count = len(backend.properties().qubits)
except :
qubit_count = "simulated"
print(backend.name(),"has",backend.status().pending_jobs," queued and ",qubit_count,"qubits")
from qiskit.tools.monitor import job_monitor
backend = provider.get_backend("ibmqx2") #Since it has0 queued
job = q.execute(circuit,backend=backend,shots=500)
job_monitor(job)
# Now our circuit has been successfully run on IBM Cloud's IBMQX2 machine
from qiskit.visualization import plot_histogram
result = job.result()
counts = result.get_counts(circuit)
plot_histogram([counts],legend=['Device'])
circuit = q.QuantumCircuit(2,2)
# Hadamard gate to the first qbit
circuit.h(0)
# The same good old CNOT gate
circuit.cx(0,1)
circuit.measure([0,1],[0,1])
circuit.draw(output="mpl")
# Let's execute this circuit
# This cell isn't much needed yet we'll use it as a revision cell
for backend in provider.backends():
try:
qubit_count = len(backend.properties().qubits)
except:
qubit_count = "simulated"
print(backend.name(),"has ",backend.status().pending_jobs,"queued and",qubit_count,"qubits")
# let's choose ibmqx2
backend = provider.get_backend("ibmqx2")
job = q.execute(circuit,backend = backend,shots=500)
job_monitor(job) # Gives the status of our job
result = job.result()
counts = result.get_counts(circuit)
plot_histogram([counts],legend=['Device '])
from qiskit import Aer
for backend in Aer.backends():
print(backend)
#Let's use qasm_simulator
sim_backend = Aer.get_backend('qasm_simulator')
job = q.execute(circuit,backend=sim_backend,shots=500)
job_monitor(job)
result = job.result()
counts = result.get_counts(circuit)
plot_histogram([counts],legend=['Device'])
import qiskit as q
from qiskit.tools.visualization import plot_bloch_multivector
%matplotlib inline
statevec_simulator = q.Aer.get_backend("statevector_simulator")
qasm_sim = q.Aer.get_backend('qasm_simulator')
def do_job(circuit):
job = q.execute(circuit,backend=statevec_simulator)
result = job.result()
statevec = result.get_statevector()
n_qubits = circuit.n_qubits
circuit.measure([i for i in range(n_qubits)],[i for i in range(n_qubits)])
qasm_job = q.execute(circuit,backend=qasm_sim,shots=1024).result()
counts = qasm_job.get_counts()
return statevec,counts
circuit = q.QuantumCircuit(2,2)
statevec,counts=do_job(circuit)
plot_bloch_multivector(statevec)
# Let's see how superposition looks like in bloch sphere
circuit = q.QuantumCircuit(2,2)
circuit.h(0)
statevec,counts = do_job(circuit)
plot_bloch_multivector(statevec)
# The qubit 0 is under superposition . So, it lies between 1 and 0 states in the space
#Let's entangle the qubits
circuit = q.QuantumCircuit(2,2)
circuit.h(0)
circuit.cx(0,1)
statevec,counts = do_job(circuit)
plot_bloch_multivector(statevec)
from qiskit.visualization import plot_histogram
plot_histogram([counts],legend=['Device'])
#Let's take 3 qubits and control the last qubit by the first two qubits
circuit = q.QuantumCircuit(3,3)
circuit.h(0)
circuit.h(1)
circuit.cx(0,2)
circuit.cx(1,2)
circuit.draw(output="mpl")
statevec,counts = do_job(circuit)
plot_bloch_multivector(statevec)
plot_histogram([counts],legend=['Device'])
circuit = q.QuantumCircuit(3,3)
circuit.h(0)
circuit.h(1)
circuit.ccx(0,1,2)
circuit.draw(output="mpl")
statevec,counts = do_job(circuit)
plot_bloch_multivector(statevec)
plot_histogram([counts],legend=['Device'])
circuit = q.QuantumCircuit(3,1)
circuit.h(0)
circuit.h(1)
circuit.ccx(0,1,2)
circuit.measure([2],[0])
result = q.execute(circuit,backend=qasm_sim,shots=1024).result()
counts = result.get_counts()
plot_histogram([counts],legend=['Device'])
import math
circuit = q.QuantumCircuit(3,1)
circuit.h(0)
circuit.h(1)
circuit.ccx(0,1,2)
circuit.rx(math.pi/2,2)
circuit.draw(output="mpl")
circuit.measure([2],[0])
result = q.execute(circuit,backend=qasm_sim,shots=1024).result()
counts = result.get_counts()
plot_histogram([counts],legend=['output'])
#Rotate X by 45 deg
circuit = q.QuantumCircuit(3,3)
circuit.h(0)
circuit.h(1)
circuit.ccx(0,1,2)
circuit.rx(math.pi/4,2)
statevec,counts = do_job(circuit)
plot_bloch_multivector(statevec)
plot_histogram([counts],legend=['output'])
circuit = q.QuantumCircuit(3,3)
circuit.h(0)
circuit.h(1)
circuit.ccx(0,1,2)
circuit.rx(math.pi/4, 2)
circuit.rz(math.pi, 2)
circuit.ry(math.pi, 2)
statevec, counts = do_job(circuit)
plot_bloch_multivector(statevec)
circuit = q.QuantumCircuit(3,3)
circuit.h(0)
circuit.h(1)
circuit.x(2)
circuit.crz(math.pi,1,2)
circuit.draw(output="mpl")
statevec,counts = do_job(circuit)
plot_bloch_multivector(statevec)
|
https://github.com/carstenblank/dc-qiskit-qml
|
carstenblank
|
# -*- coding: utf-8 -*-
# Copyright 2018 Carsten Blank
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
r"""
QmlHadamardNeighborClassifier
===============================
.. currentmodule:: dc_qiskit_qml.distance_based.hadamard._QmlHadamardNeighborClassifier
Implementing the Hadamard distance & majority based classifier (http://stacks.iop.org/0295-5075/119/i=6/a=60002).
.. autosummary::
:nosignatures:
QmlHadamardNeighborClassifier
AsyncPredictJob
More details:
QmlHadamardNeighborClassifier
###############################
.. autoclass:: QmlHadamardNeighborClassifier
:members:
AsyncPredictJob
##################
.. autoclass:: AsyncPredictJob
:members:
"""
import logging
import time
from typing import List, Union, Optional, Iterable, Sized
import numpy as np
import qiskit
from qiskit.circuit import QuantumCircuit
from qiskit.providers import JobStatus, BackendV2, JobV1
from qiskit.qobj import QasmQobj
from qiskit.result import Result
from qiskit.result.models import ExperimentResult
from qiskit.transpiler import CouplingMap
from sklearn.base import ClassifierMixin, TransformerMixin
from dc_qiskit_qml.QiskitOptions import QiskitOptions
from .state import QmlStateCircuitBuilder
from .state._measurement_outcome import MeasurementOutcome
from ...encoding_maps import EncodingMap
log = logging.getLogger(__name__)
class QmlHadamardNeighborClassifier(ClassifierMixin, TransformerMixin):
"""
The Hadamard distance & majority based classifier implementing sci-kit learn's mechanism of fit/predict
"""
def __init__(self, encoding_map, classifier_circuit_factory, backend, shots=1024, coupling_map=None,
basis_gates=None, theta=None, options=None):
# type: (EncodingMap, QmlStateCircuitBuilder, BackendV2, int, CouplingMap, List[str], Optional[float], Optional[QiskitOptions]) -> None
"""
Create the classifier
:param encoding_map: a classical feature map to apply to every training and testing sample before building
the circuit
:param classifier_circuit_factory: the circuit building factory class
:param backend: the qiskit backend to do the compilation & computation on
:param shots: *deprecated* use options. the amount of shots for the experiment
:param coupling_map: *deprecated* use options. if given overrides the backend's coupling map, useful when using the simulator
:param basis_gates: *deprecated* use options. if given overrides the backend's basis gates, useful for the simulator
:param theta: an advanced feature that generalizes the "Hadamard" gate as a rotation with this angle
:param options: the options for transpilation & executions with qiskit.
"""
self.encoding_map = encoding_map # type: EncodingMap
self.basis_gates = basis_gates # type: List[str]
self.shots = shots # type: int
self.backend = backend # type: BackendV2
self.coupling_map = coupling_map # type: CouplingMap
self._X = np.asarray([]) # type: np.ndarray
self._y = np.asarray([]) # type: np.ndarray
self.last_predict_X = None
self.last_predict_label = None
self.last_predict_probability = [] # type: List[float]
self._last_predict_circuits = [] # type: List[QuantumCircuit]
self.last_predict_p_acc = [] # type: List[float]
self.classifier_state_factory = classifier_circuit_factory # type: QmlStateCircuitBuilder
self.theta = np.pi / 2 if theta is None else theta # type: float
if options is not None:
self.options = options # type: QiskitOptions
else:
self.options = QiskitOptions()
self.options.basis_gates = basis_gates
self.options.coupling_map = coupling_map
self.options.shots = shots
def transform(self, X, y='deprecated', copy=None):
return X
def fit(self, X, y):
# type: (QmlHadamardNeighborClassifier, Iterable) -> QmlHadamardNeighborClassifier
"""
Internal fit method just saves the train sample set
:param X: array_like, training sample
"""
self._X = np.asarray(X)
self._y = y
log.debug("Setting training data:")
for x, y in zip(self._X, self._y):
log.debug("%s: %s", x, y)
return self
def _create_circuits(self, unclassified_input):
# type: (QmlHadamardNeighborClassifier, Iterable) -> None
"""
Creates the circuits to be executed on the quantum computer
:param unclassified_input: array like, the input set
"""
self._last_predict_circuits = []
if self.classifier_state_factory is None:
raise Exception("Classifier state factory is not set!")
for index, x in enumerate(unclassified_input):
log.info("Creating state for input %d: %s.", index, x)
circuit_name = 'qml_hadamard_index_%d' % index
X_input = self.encoding_map.map(x)
X_train = [self.encoding_map.map(s) for s in self._X]
qc = self.classifier_state_factory.build_circuit(circuit_name=circuit_name, X_train=X_train,
y_train=self._y, X_input=X_input) # type: QuantumCircuit
ancillary = [q for q in qc.qregs if q.name == 'a'][0]
qlabel = [q for q in qc.qregs if q.name == 'l^q'][0]
clabel = [q for q in qc.cregs if q.name == 'l^c'][0]
branch = [q for q in qc.cregs if q.name == 'b'][0]
# Classifier
# Instead of a Hadamard gate we want this to be parametrized
# use comments for now to toggle!
# standard.h(qc, ancillary)
# Must be minus, as the IBMQX gate is implemented this way!
qc.ry(-self.theta, ancillary)
qc.z(ancillary)
# Make sure measurements aren't shifted around
# This would have some consequences as no gates
# are allowed after a measurement.
qc.barrier()
# The correct label is on ancillary branch |0>!
qc.measure(ancillary[0], branch[0])
qc.measure(qlabel, clabel)
self._last_predict_circuits.append(qc)
@staticmethod
def _extract_measurement_answer_from_index(index, result):
# type: (int, Result) -> List[MeasurementOutcome]
# Aggregate Counts
experiment = None # type: Optional[ExperimentResult]
experiment_names = [
experiment.header.name
for experiment in result.results
if experiment.header and 'qml_hadamard_index_%d' % index in experiment.header.name
]
counts = {} # type: dict
for name in experiment_names:
c = result.get_counts(name) # type: dict
for k, v in c.items():
if k not in counts:
counts[k] = v
else:
counts[k] += v
log.debug(counts)
answer = [
MeasurementOutcome(label=int(k.split(' ')[-1], 2), branch=int(k.split(' ')[-2], 2), count=v)
for k, v in counts.items()
]
return answer
def _read_result(self, test_size, result):
# type: (QmlHadamardNeighborClassifier, int, Result) -> Optional[List[int]]
"""
The logic to read out the classification from the result
:param test_size: the input set size
:param result: the qiskit result object holding the results from the experiment execution
:return: if there is a result, will return it as a list of class labels
"""
self.last_predict_label = []
self.last_predict_probability = []
for index in range(test_size):
answer = QmlHadamardNeighborClassifier._extract_measurement_answer_from_index(index, result)
log.info(answer)
answer_branch = [e for e in answer if self.classifier_state_factory.is_classifier_branch(e.branch)]
if len(answer_branch) == 0:
return None
p_acc = sum([e.count for e in answer_branch]) / self.shots
sum_of_all = sum([e.count for e in answer_branch])
predicted_answer = max(answer_branch, key=lambda e: e.count)
log.debug(predicted_answer)
predict_label = predicted_answer.label
probability = predicted_answer.count / sum_of_all
self.last_predict_label.append(predict_label)
self.last_predict_probability.append(probability)
self.last_predict_p_acc.append(p_acc)
return self.last_predict_label
def predict_qasm_only(self, X):
# type: (QmlHadamardNeighborClassifier, Union[Sized, Iterable]) -> QasmQobj
"""
Instead of predicting straight away returns the Qobj, the command object for executing
the experiment
:param X: array like, unclassified input set
:return: the compiled Qobj ready for execution!
"""
self.last_predict_X = X
self.last_predict_label = []
self._last_predict_circuits = []
self.last_predict_probability = []
self.last_predict_p_acc = []
log.info("Creating circuits (#%d inputs)..." % len(X))
self._create_circuits(X)
log.info("Compiling circuits...")
transpiled_qc = qiskit.transpile(
self._last_predict_circuits,
backend=self.backend,
coupling_map=self.options.coupling_map,
basis_gates=self.options.basis_gates,
backend_properties=self.options.backend_properties,
initial_layout=self.options.initial_layout,
seed_transpiler=self.options.seed_transpiler,
optimization_level=self.options.optimization_level
) # type: List[QuantumCircuit]
qobj = qiskit.assemble(transpiled_qc,
backend=self.backend,
shots=self.options.shots,
qobj_id=self.options.qobj_id,
qobj_header=self.options.qobj_header,
memory=self.options.memory,
max_credits=self.options.max_credits,
seed_simulator=self.options.seed_simulator,
default_qubit_los=self.options.default_qubit_los,
default_meas_los=self.options.default_meas_los,
schedule_los=self.options.schedule_los,
meas_level=self.options.meas_level,
meas_return=self.options.meas_return,
memory_slots=self.options.memory_slots,
memory_slot_size=self.options.memory_slot_size,
rep_time=self.options.rep_time,
parameter_binds=self.options.parameter_binds,
**self.options.run_config
)
return qobj
def predict(self, X, do_async=False):
# type: (QmlHadamardNeighborClassifier, Union[Sized, Iterable], bool) -> Union[Optional[List[int]], 'AsyncPredictJob']
"""
Predict the class labels of the unclassified input set!
:param X: array like, the unclassified input set
:param do_async: if True return a wrapped job, it is handy for reading out the prediction results from a real processor
:return: depending on the input either the prediction on class labels or a wrapper object for an async task
"""
qobj = self.predict_qasm_only(X)
log.info("Executing circuits...")
job = self.backend.run(qobj) # type: JobV1
async_job = AsyncPredictJob(X, job, self) # type: AsyncPredictJob
if do_async:
return async_job
job.result()
while not job.status() == JobStatus.DONE:
if job.status() == JobStatus.CANCELLED:
break
log.debug("Waiting for job...")
time.sleep(10)
if job.status() == JobStatus.DONE:
log.info("Circuits Executed!")
return async_job.predict_result()
else:
log.error("Circuits not executed!")
log.error(job.status)
return None
def predict_async(self, X):
# type: (QmlHadamardNeighborClassifier, any) -> 'AsyncPredictJob'
"""
Same as predict(self, X, do_aysnc=True)
:param X: unclassified input set
:return: Wrapper for a Job
"""
return self.predict(X, do_async=True)
def predict_sync(self, X):
# type: (QmlHadamardNeighborClassifier, any) -> Optional[List[int]]
"""
Same as predict(self, X, do_aysnc=False)
:param X: unclassified input set
:return: List of class labels
"""
return self.predict(X, do_async=False)
@staticmethod
def p_acc_theory(X_train, y_train, X_test):
# type: (List[np.ndarray], Iterable, np.ndarray) -> float
"""
Computes the branch acceptance probability
:param X_train: training set (list of numpy arrays shape (n,1)
:param y_train: Class labels of training set
:param X_test: Unclassified input vector (shape (n,1))
:return: branch acceptance probability P_acc
"""
M = len(X_train)
p_acc = sum([np.linalg.norm(X_train[i] + X_test) ** 2 for i, e in enumerate(y_train)]) / (4 * M)
return p_acc
@staticmethod
def p_label_theory(X_train, y_train, X_test, label):
# type: (List[np.ndarray], Iterable, np.ndarray, int) -> float
"""
Computes the label's probability
:param X_train: training set
:param y_train: Class labels of training set
:param X_test: Unclassified input vector (shape: (n,1))
:param label: The label to test
:return: probability of class label
"""
M = len(X_train)
p_acc = QmlHadamardNeighborClassifier.p_acc_theory(X_train, y_train, X_test)
p_label = sum([np.linalg.norm(X_train[i] + X_test) ** 2
for i, e in enumerate(y_train) if e == label]) / (4 * p_acc * M)
return p_label
class AsyncPredictJob(object):
"""
Wrapper for a qiskit BaseJob and classification experiments
"""
def __init__(self, input, job, qml):
# type: (AsyncPredictJob, Sized, JobV1, QmlHadamardNeighborClassifier) -> None
"""
Constructs a new Wrapper
:param input: the unclassified input data set
:param job: the qiskit BaseJob running the experiment
:param qml: the classifier
"""
self.input = input # type: Sized
self.job = job # type: JobV1
self.qml = qml # type: QmlHadamardNeighborClassifier
def predict_result(self):
# type: () -> Optional[List[int]]
"""
Returns the prediction result if it exists
:return: a list of class labels or None
"""
if self.job.status() == JobStatus.DONE:
log.info("Circuits Executed!")
return self.qml._read_result(len(self.input), self.job.result())
else:
log.error("Circuits not executed!")
log.error(self.job.status)
return None
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, transpile
from qiskit_aer import AerSimulator
from qiskit.tools.visualization import plot_histogram
import random
circ = QuantumCircuit(40, 40)
# Initialize with a Hadamard layer
circ.h(range(40))
# Apply some random CNOT and T gates
qubit_indices = [i for i in range(40)]
for i in range(10):
control, target, t = random.sample(qubit_indices, 3)
circ.cx(control, target)
circ.t(t)
circ.measure(range(40), range(40))
# Create statevector method simulator
statevector_simulator = AerSimulator(method='statevector')
# Transpile circuit for backend
tcirc = transpile(circ, statevector_simulator)
# Try and run circuit
statevector_result = statevector_simulator.run(tcirc, shots=1).result()
print('This succeeded?: {}'.format(statevector_result.success))
print('Why not? {}'.format(statevector_result.status))
# Create extended stabilizer method simulator
extended_stabilizer_simulator = AerSimulator(method='extended_stabilizer')
# Transpile circuit for backend
tcirc = transpile(circ, extended_stabilizer_simulator)
extended_stabilizer_result = extended_stabilizer_simulator.run(tcirc, shots=1).result()
print('This succeeded?: {}'.format(extended_stabilizer_result.success))
small_circ = QuantumCircuit(2, 2)
small_circ.h(0)
small_circ.cx(0, 1)
small_circ.t(0)
small_circ.measure([0, 1], [0, 1])
# This circuit should give 00 or 11 with equal probability...
expected_results ={'00': 50, '11': 50}
tsmall_circ = transpile(small_circ, extended_stabilizer_simulator)
result = extended_stabilizer_simulator.run(
tsmall_circ, shots=100).result()
counts = result.get_counts(0)
print('100 shots in {}s'.format(result.time_taken))
plot_histogram([expected_results, counts],
legend=['Expected', 'Extended Stabilizer'])
# Add runtime options for extended stabilizer simulator
opts = {'extended_stabilizer_approximation_error': 0.03}
reduced_error = extended_stabilizer_simulator.run(
tsmall_circ, shots=100, **opts).result()
reduced_error_counts = reduced_error.get_counts(0)
print('100 shots in {}s'.format(reduced_error.time_taken))
plot_histogram([expected_results, reduced_error_counts],
legend=['Expected', 'Extended Stabilizer'])
print("The circuit above, with 100 shots at precision 0.03 "
"and default mixing time, needed {}s".format(int(reduced_error.time_taken)))
opts = {
'extended_stabilizer_approximation_error': 0.03,
'extended_stabilizer_mixing_time': 100
}
optimized = extended_stabilizer_simulator.run(
tsmall_circ, shots=100, **opts).result()
print('Dialing down the mixing time, we completed in just {}s'.format(optimized.time_taken))
# We set these options here only to make the example run more quickly.
opts = {'extended_stabilizer_mixing_time': 100}
multishot = extended_stabilizer_simulator.run(
tcirc, shots=100, **opts).result()
print("100 shots took {} s".format(multishot.time_taken))
opts = {
'extended_stabilizer_measure_sampling': True,
'extended_stabilizer_mixing_time': 100
}
measure_sampling = extended_stabilizer_simulator.run(
circ, shots=100, **opts).result()
print("With the optimization, 100 shots took {} s".format(result.time_taken))
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/GabrielPontolillo/Quantum_Algorithm_Implementations
|
GabrielPontolillo
|
from qiskit import QuantumCircuit
def create_bell_pair():
qc = QuantumCircuit(2)
qc.h(1)
qc.cx(1, 0)
return qc
def encode_message(qc, qubit, msg):
if len(msg) != 2 or not set([0,1]).issubset({0,1}):
raise ValueError(f"message '{msg}' is invalid")
if msg[1] == "1":
qc.x(qubit)
if msg[0] == "1":
qc.z(qubit)
return qc
def decode_message(qc):
qc.cx(1, 0)
### replaced x gate ###
qc.x(1)
return qc
|
https://github.com/drnickallgood/simonqiskit
|
drnickallgood
|
import qiskit
qiskit.__qiskit_version__
#initialization
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
# importing Qiskit
from qiskit import BasicAer, IBMQ
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute
from qiskit.compiler import transpile
from qiskit.tools.monitor import job_monitor
# import basic plot tools
from qiskit.tools.visualization import plot_histogram
# Load the saved IBMQ accounts
IBMQ.load_account()
s = "010101" # the hidden bitstring
assert 1 < len(s) < 20, "The length of s must be between 2 and 19"
for c in s:
assert c == "0" or c == "1", "s must be a bitstring of '0' and '1'"
n = len(s) #the length of the bitstring
# Step 1
# Creating registers
# qubits for querying the oracle and recording its output
qr = QuantumRegister(2*n)
# for recording the measurement on the first register of qr
cr = ClassicalRegister(n)
circuitName = "Simon"
simonCircuit = QuantumCircuit(qr, cr)
# Step 2
# Apply Hadamard gates before querying the oracle
for i in range(n):
simonCircuit.h(qr[i])
# Apply barrier to mark the beginning of the blackbox function
simonCircuit.barrier()
# Step 3 query the blackbox function
# copy the content of the first register to the second register
for i in range(n):
simonCircuit.cx(qr[i], qr[n+i])
# get the least index j such that s_j is "1"
j = -1
for i, c in enumerate(s):
if c == "1":
j = i
break
# Creating 1-to-1 or 2-to-1 mapping with the j-th qubit of x as control to XOR the second register with s
for i, c in enumerate(s):
if c == "1" and j >= 0:
simonCircuit.cx(qr[j], qr[n+i]) #the i-th qubit is flipped if s_i is 1
# get random permutation of n qubits
perm = list(np.random.permutation(n))
#initial position
init = list(range(n))
i = 0
while i < n:
if init[i] != perm[i]:
k = perm.index(init[i])
simonCircuit.swap(qr[n+i], qr[n+k]) #swap qubits
init[i], init[k] = init[k], init[i] #marked swapped qubits
else:
i += 1
# randomly flip the qubit
for i in range(n):
if np.random.random() > 0.5:
simonCircuit.x(qr[n+i])
# Apply the barrier to mark the end of the blackbox function
simonCircuit.barrier()
# Step 4 apply Hadamard gates to the first register
for i in range(n):
simonCircuit.h(qr[i])
# Step 5 perform measurement on the first register
for i in range(n):
simonCircuit.measure(qr[i], cr[i])
#draw the circuit
simonCircuit.draw(output='mpl')
# use local simulator
backend = BasicAer.get_backend("qasm_simulator")
# the number of shots is twice the length of the bitstring
shots = 2*n
job = execute(simonCircuit, backend=backend, shots=shots)
answer = job.result().get_counts()
plot_histogram(answer)
# Post-processing step
# Constructing the system of linear equations Y s = 0
# By k[::-1], we reverse the order of the bitstring
lAnswer = [ (k[::-1],v) for k,v in answer.items() if k != "0"*n ] #excluding the trivial all-zero
#Sort the basis by their probabilities
lAnswer.sort(key = lambda x: x[1], reverse=True)
Y = []
for k, v in lAnswer:
Y.append( [ int(c) for c in k ] )
#import tools from sympy
from sympy import Matrix, pprint, MatrixSymbol, expand, mod_inverse
Y = Matrix(Y)
#pprint(Y)
#Perform Gaussian elimination on Y
Y_transformed = Y.rref(iszerofunc=lambda x: x % 2==0) # linear algebra on GF(2)
#to convert rational and negatives in rref of linear algebra on GF(2)
def mod(x,modulus):
numer, denom = x.as_numer_denom()
return numer*mod_inverse(denom,modulus) % modulus
Y_new = Y_transformed[0].applyfunc(lambda x: mod(x,2)) #must takecare of negatives and fractional values
#pprint(Y_new)
print("The hidden bistring s[ 0 ], s[ 1 ]....s[",n-1,"] is the one satisfying the following system of linear equations:")
rows, cols = Y_new.shape
for r in range(rows):
Yr = [ "s[ "+str(i)+" ]" for i, v in enumerate(list(Y_new[r,:])) if v == 1 ]
if len(Yr) > 0:
tStr = " + ".join(Yr)
print(tStr, "= 0")
#Use one of the available backends
backend = IBMQ.get_backend("ibmq_16_melbourne")
# show the status of the backend
print("Status of", backend, "is", backend.status())
shots = 10*n #run more experiments to be certain
max_credits = 3 # Maximum number of credits to spend on executions.
simonCompiled = transpile(simonCircuit, backend=backend, optimization_level=1)
job_exp = execute(simonCompiled, backend=backend, shots=shots, max_credits=max_credits)
job_monitor(job_exp)
results = job_exp.result()
answer = results.get_counts(simonCircuit)
plot_histogram(answer)
# Post-processing step
# Constructing the system of linear equations Y s = 0
# By k[::-1], we reverse the order of the bitstring
lAnswer = [ (k[::-1][:n],v) for k,v in answer.items() ] #excluding the qubits that are not part of the inputs
#Sort the basis by their probabilities
lAnswer.sort(key = lambda x: x[1], reverse=True)
Y = []
for k, v in lAnswer:
Y.append( [ int(c) for c in k ] )
Y = Matrix(Y)
#Perform Gaussian elimination on Y
Y_transformed = Y.rref(iszerofunc=lambda x: x % 2==0) # linear algebra on GF(2)
Y_new = Y_transformed[0].applyfunc(lambda x: mod(x,2)) #must takecare of negatives and fractional values
#pprint(Y_new)
print("The hidden bistring s[ 0 ], s[ 1 ]....s[",n-1,"] is the one satisfying the following system of linear equations:")
rows, cols = Y_new.shape
for r in range(rows):
Yr = [ "s[ "+str(i)+" ]" for i, v in enumerate(list(Y_new[r,:])) if v == 1 ]
if len(Yr) > 0:
tStr = " + ".join(Yr)
print(tStr, "= 0")
|
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/GabrielPontolillo/Quantum_Algorithm_Implementations
|
GabrielPontolillo
|
from qiskit import QuantumCircuit
def create_bell_pair():
qc = QuantumCircuit(2)
qc.h(1)
qc.cx(1, 0)
return qc
def encode_message(qc, qubit, msg):
if len(msg) != 2 or not set([0,1]).issubset({0,1}):
raise ValueError(f"message '{msg}' is invalid")
if msg[1] == "1":
qc.x(qubit)
if msg[0] == "1":
qc.z(qubit)
return qc
def decode_message(qc):
qc.cx(1, 0)
qc.h(1)
return qc
|
https://github.com/KMU-quantum-classroom/qiskit-classroom
|
KMU-quantum-classroom
|
"""
worker for convert and visualize expressions
"""
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import asyncio
import datetime
import random
import os
import string
import sys
import matplotlib as mpl
import matplotlib.pyplot as plt
from .expression_enum import QuantumExpression
from .input_model import Input, QuantumCircuitInput, MatrixInput
mpl.rcParams["font.size"] = 9
mpl.rcParams["text.usetex"] = True
mpl.rcParams["text.latex.preamble"] = r"\usepackage{{amsmath}}"
ARRAY_TO_LATEX_IMPORT = "from qiskit.visualization import array_to_latex"
CONVERTER_IMPORT = "from qiskit_class_converter import ConversionService"
def add_new_line(strings: list[str]) -> str:
"""add \\n between every line
Args:
strings (list[str]): list of line
Returns:
str: joined string with \\n
"""
return "\n".join(strings)
# pylint: disable=too-many-instance-attributes
class ConverterWorker:
"""worker for convert expression and visualize expression"""
# pylint: disable=too-many-arguments
def __init__(
self,
from_expression: QuantumExpression,
to_expression: QuantumExpression,
input_data: Input,
expression_text: str,
shows_result: bool,
) -> None:
self.from_expression = from_expression
self.to_expression = to_expression
self.__injected_sourcecode_path = ConverterWorker.generate_random_file_name()
# copy text
self.expression_text = "" + expression_text
self.input_data = input_data
self.shows_result = shows_result
@staticmethod
def generate_random_file_name() -> str: # pragma: no cover
# this method implmented with random function
"""return generated file name
Returns:
str: generated file name
"""
return (
"/tmp/"
+ "".join(random.choice(string.ascii_letters) for _ in range(10))
+ ".py"
)
@staticmethod
def write_converting_code(file_path: str, code: str) -> bool: # pragma: no cover
"""write code to file_path
Args:
file_path (str): target
code (str): contents
Returns:
bool: is succesful
"""
try:
with open(file_path, mode="w", encoding="UTF-8") as file:
file.write(code)
except FileNotFoundError:
return False
return True
def __generate_code(self): # pragma: no cover
expression_text = self.expression_text
if self.from_expression is QuantumExpression.MATRIX:
input_data: MatrixInput = self.input_data
expression_text = f"{input_data.value_name}={expression_text}"
ConverterWorker.write_converting_code(
self.__injected_sourcecode_path,
add_new_line(
[
expression_text,
CONVERTER_IMPORT,
ARRAY_TO_LATEX_IMPORT,
self.generate_conversion_code(),
self.generate_visualization_code(),
]
),
)
def generate_conversion_code(self) -> str:
"""generate the conversion code according to the conversion method.
Returns:
str: generated conversion code
"""
if self.to_expression == self.from_expression:
return ""
matrix_to_qc_option: dict[str, str] = {"label": "unitary gate"}
default_option: dict[str, str] = {"print": "raw"}
option: dict[str, str] = {}
if self.to_expression is QuantumExpression.CIRCUIT:
option = matrix_to_qc_option
else:
option = default_option
first_line = (
"converter = ConversionService(conversion_type="
+ f"'{self.from_expression.value[1]}_TO_{self.to_expression.value[1]}', "
+ f"option={option})"
)
next_line: str = ""
if self.from_expression is QuantumExpression.CIRCUIT:
quantum_circuit_input: QuantumCircuitInput = self.input_data
next_line = (
"result = converter.convert"
+ f"(input_value={quantum_circuit_input.value_name})"
)
if self.from_expression is QuantumExpression.MATRIX:
matrix_input: MatrixInput = self.input_data
next_line = add_new_line(
[
"from qiskit import QuantumCircuit",
""
f"result = converter.convert(input_value={matrix_input.value_name})",
f"quantum_circuit = QuantumCircuit({matrix_input.num_qubits})",
"quantum_circuit.append(result, list(range(result.num_qubits)))",
"quantum_circuit.measure_all()" if matrix_input.do_measure else "",
]
)
return add_new_line([first_line, next_line])
def generate_visualization_code(self) -> str:
"""generate visualiszation code according to the conversion method
Returns:
str: visualization code
"""
if self.to_expression is not self.from_expression:
if self.to_expression is QuantumExpression.MATRIX:
return add_new_line(
[
(
"for gate, name in zip(reversed(result['gate']),"
+ "reversed(result['name'])):"
),
"\totimes=' \\\\otimes '",
"""\tprint('\\stackrel{' + otimes.join(name[1]) +'}' + f'{{{gate}}}')""",
"print(f\"= \\stackrel{{result}}{{{result['result']}}}\")"
if self.shows_result
else "",
]
)
if self.to_expression is QuantumExpression.CIRCUIT:
return add_new_line(
[
'quantum_circuit.draw(output="mpl")'
+ f'.savefig("{self.__injected_sourcecode_path+".png"}", '
+ 'bbox_inches="tight")'
]
)
if self.to_expression is QuantumExpression.DIRAC:
return add_new_line(["print(result)"])
else:
if self.to_expression is QuantumExpression.MATRIX:
matrix_input: MatrixInput = self.input_data
return add_new_line(
[f"print(array_to_latex({matrix_input.value_name}, source=True))"]
)
if self.to_expression is QuantumExpression.CIRCUIT:
qunatum_input: QuantumCircuitInput = self.input_data
return add_new_line(
[
f'{qunatum_input.value_name}.draw(output="mpl")'
+ f'.savefig("{self.__injected_sourcecode_path+".png"}",'
+ 'bbox_inches="tight")'
]
)
return ""
async def run(self) -> str:
"""inject expression convert code to user's source code and create
subprocess for drawing converted expresion
Returns:
str: path of subprocess created image
"""
print("now running")
print(datetime.datetime.now().time())
self.__generate_code()
stdout, stderr = await self.run_subprocess()
if stdout:
print(f"output {stdout}")
if stderr:
stderr: str = stderr
print(f"error {stderr}")
if stderr.find("SyntaxError") != -1:
raise SyntaxError
if stderr.find("NameError") != -1:
raise NameError
print("end at ")
print(datetime.datetime.now().time())
# remove injected source code
if not self.cleanup():
print("error removing file")
if self.to_expression is QuantumExpression.CIRCUIT:
return self.__injected_sourcecode_path + ".png"
return self.draw_latex(latex=stdout)
async def run_subprocess(self) -> (str, str):
"""run generated script's subprocess
Returns:
(str, str): subprocess's stdout and stderr
"""
proc = await asyncio.create_subprocess_exec(
sys.executable,
self.__injected_sourcecode_path,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
)
stdout, stderr = await proc.communicate()
await proc.wait()
return (stdout.decode(), stderr.decode())
def cleanup(self) -> bool:
"""remove generated script
Returns:
bool: result of removing file
"""
try:
os.remove(self.__injected_sourcecode_path)
except FileNotFoundError:
return False
return True
def draw_latex(self, latex: str) -> str: # pragma: no cover
"""
render latex to image and save as file.
Args:
latex (str): latex matrix code
Raises:
MatrixNotFound: when latex not have matrix
Returns:
str: image file path
"""
# this code avoid latex runtime error (\n ocurse error)
latex = latex.replace("\n", " ").strip()
fig = plt.figure()
fig.text(0, 0, f"${latex}$")
output = self.__injected_sourcecode_path + ".png"
fig.savefig(output, dpi=200, bbox_inches="tight")
plt.close()
return output
|
https://github.com/Qiskit/feedback
|
Qiskit
|
import qiskit
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, transpile
from qiskit.transpiler import CouplingMap
from qiskit.converters import circuit_to_dag, dag_to_circuit
from qiskit.visualization.gate_map import plot_gate_map, plot_coupling_map, plot_circuit_layout
import matplotlib.pyplot as plt
import numpy as np
from numpy import pi
%matplotlib inline
# OpenQASM 2.0 control flow
qr, cr = QuantumRegister(2), ClassicalRegister(1)
qc = QuantumCircuit(qr, cr)
qc.h(0)
qc.measure(0, 0)
qc.x(1).c_if(cr, 1)
qc.draw()
# `if` statement
qc = QuantumCircuit(qr, cr)
qc.h(0)
qc.measure(0, 0)
with qc.if_test((cr[0], 0)):
qc.x(1)
qc.draw()
qc = QuantumCircuit(2)
with qc.for_loop(range(3)) as i:
qc.cx(0, 1)
qc.rx(i * pi/2, 0)
qc.draw()
qr, cr = QuantumRegister(3), ClassicalRegister(3)
qc = QuantumCircuit(qr, cr)
qc.h(qr)
qc.cx(0, [1, 2])
qc.measure(qr, cr)
with qc.while_loop((cr, 0)):
qc.reset(qr)
qc.cx(0, [1, 2])
qc.measure(qr, cr)
qc.draw()
print(f'circuit depth = {qc.depth()}')
print(f'dag depth = {circuit_to_dag(qc).depth(recurse=True)}')
qc = QuantumCircuit(2)
qc.rz(0.2, 0)
qc.cx(0, 1)
with qc.for_loop((range(3))):
qc.rx(0.3, 1)
qc.rx(0.2, 1)
qc.cx(0, 1)
qc.cx(0, 1)
cqc = transpile(qc, basis_gates=["u", "cx", "for_loop"])
cqc.draw()
cqc.data[2].operation.params[2].draw()
cmap = CouplingMap.from_line(4)
plot_coupling_map(4, [(0, i) for i in range(4)], list(cmap.get_edges()))
qc = QuantumCircuit(4)
with qc.for_loop(range(2)):
qc.cx(0, [1, 2, 3])
qc.barrier()
cqc = transpile(qc, basis_gates=["u", "cx", "swap", "for_loop"], coupling_map=cmap)
cqc.data[0].operation.params[2].draw()
|
https://github.com/Bikramaditya0154/Quantum-Simulation-of-the-ground-states-of-Li-and-Li-2-using-Variational-Quantum-EIgensolver
|
Bikramaditya0154
|
from qiskit import Aer
from qiskit_nature.drivers import UnitsType, Molecule
from qiskit_nature.drivers.second_quantization import (
ElectronicStructureDriverType,
ElectronicStructureMoleculeDriver,
)
from qiskit_nature.problems.second_quantization import ElectronicStructureProblem
from qiskit_nature.converters.second_quantization import QubitConverter
from qiskit_nature.mappers.second_quantization import JordanWignerMapper
molecule = Molecule(
geometry=[["Li", [0.0, 0.0, 0.0]]], charge=1, multiplicity=1
)
driver = ElectronicStructureMoleculeDriver(
molecule, basis="sto3g", driver_type=ElectronicStructureDriverType.PYSCF
)
es_problem = ElectronicStructureProblem(driver)
qubit_converter = QubitConverter(JordanWignerMapper())
from qiskit.providers.aer import StatevectorSimulator
from qiskit import Aer
from qiskit.utils import QuantumInstance
from qiskit_nature.algorithms import VQEUCCFactory
quantum_instance = QuantumInstance(backend=Aer.get_backend("aer_simulator_statevector"))
vqe_solver = VQEUCCFactory(quantum_instance=quantum_instance)
from qiskit.algorithms import VQE
from qiskit.circuit.library import TwoLocal
tl_circuit = TwoLocal(
rotation_blocks=["h", "rx"],
entanglement_blocks="cz",
entanglement="full",
reps=2,
parameter_prefix="y",
)
another_solver = VQE(
ansatz=tl_circuit,
quantum_instance=QuantumInstance(Aer.get_backend("aer_simulator_statevector")),
)
from qiskit_nature.algorithms import GroundStateEigensolver
calc = GroundStateEigensolver(qubit_converter, vqe_solver)
res = calc.solve(es_problem)
print(res)
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
# import all necessary objects and methods for quantum circuits
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
from qiskit.tools.visualization import matplotlib_circuit_drawer as drawer
# define a quantum register with one qubit
qreg3 = QuantumRegister(1)
# define a classical register with one bit
# it stores the measurement result of the quantum part
creg3 = ClassicalRegister(1)
# define our quantum circuit
mycircuit3 = QuantumCircuit(qreg3,creg3)
# apply x-gate to the first qubit
mycircuit3.x(qreg3[0])
# apply h-gate (Hadamard: quantum coin-flipping) to the first qubit
mycircuit3.h(qreg3[0])
# measure the first qubit, and store the result in the first classical bit
mycircuit3.measure(qreg3,creg3)
print("Everything looks fine, let's continue ...")
# draw the circuit
drawer(mycircuit3)
# reexecute me if you DO NOT see the circuit diagram
# execute the circuit and read the results
job = execute(mycircuit3,Aer.get_backend('qasm_simulator'),shots=10000)
counts3 = job.result().get_counts(mycircuit3)
print(counts3)
# import all necessary objects and methods for quantum circuits
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
from qiskit.tools.visualization import matplotlib_circuit_drawer as drawer
# define a quantum register with one qubit
qreg4 = QuantumRegister(1)
# define a classical register with one bit
# it stores the measurement result of the quantum part
creg4 = ClassicalRegister(1)
# define our quantum circuit
mycircuit4 = QuantumCircuit(qreg4,creg4)
# apply x-gate to the first qubit
mycircuit4.x(qreg4[0])
# apply h-gate (Hadamard: quantum coin-flipping) to the first qubit twice
mycircuit4.h(qreg4[0])
mycircuit4.h(qreg4[0])
# measure the first qubit, and store the result in the first classical bit
mycircuit4.measure(qreg4,creg4)
print("Everyhing looks fine, let's continue ...")
# draw the circuit
drawer(mycircuit4)
# reexecute me if you DO NOT see the circuit diagram
# execute the circuit and read the results
job = execute(mycircuit4,Aer.get_backend('qasm_simulator'),shots=10000)
counts4 = job.result().get_counts(mycircuit4)
print(counts4)
|
https://github.com/jonasmaziero/computacao_quantica_qiskit
|
jonasmaziero
|
from qiskit_ibm_runtime import QiskitRuntimeService
QiskitRuntimeService.save_account(channel='ibm_quantum',
token='83ab2a86232e48767228534cdae2cf55b8e8ea4e0eb1e57804268f40d7bee64692f719528e8871de617ffc35040d21bd389f4696313f46900c077c7f617a1512',
overwrite=True)
service = QiskitRuntimeService(instance='ibm-q/open/main')
print(service.backends())
from qiskit import QuantumCircuit
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0,1)
qc.measure_all()
qc.draw()
from qiskit_ibm_runtime import Sampler, Options, Session
options = Options(optimization_level=1)
with Session(service=service, backend="ibmq_qasm_simulator") as session:
sampler = Sampler(session=session, options=options)
job = sampler.run(circuits=qc) # foi usado 18 s dos 10 min (por conjunto de 4000 prepara-evolui-mede experimentos)
job.result() # 'probabilidades' (eles chamam de quasiprobabilidades)
counts = job.result().quasi_dists[0].binary_probabilities()
counts
from qiskit.visualization import plot_histogram
plot_histogram(counts)
backend = service.get_backend("ibm_osaka")
with Session(service=service, backend=backend) as session:
sampler = Sampler(session=session, options=options)
job = sampler.run(circuits=qc)
print(job.job_id())
jobr = service.job('cnvn5zzvn4c0008a6df0')
jobr.result()
counts = jobr.result().quasi_dists[0].binary_probabilities()
counts # ?
plot_histogram(counts)
print(jobr.logs())
from qiskit.circuit.library import RealAmplitudes
from qiskit.quantum_info import SparsePauliOp
from qiskit_ibm_runtime import QiskitRuntimeService, Estimator
service = QiskitRuntimeService(channel="ibm_cloud")
psi1 = RealAmplitudes(num_qubits=2, reps=2)
H1 = SparsePauliOp.from_list([("II", 1), ("IZ", 2), ("XI", 3)])
H2 = SparsePauliOp.from_list([("IZ", 1)])
H3 = SparsePauliOp.from_list([("ZI", 1), ("ZZ", 1)])
with Session(service=service, backend="ibmq_qasm_simulator") as session:
estimator = Estimator(session=session)
theta1 = [0, 1, 1, 2, 3, 5]
# calculate [ <psi1(theta1)|H1|psi1(theta1)> ]
psi1_H1 = estimator.run(circuits=[psi1], observables=[H1], parameter_values=[theta1])
print(psi1_H1.result())
# calculate [ <psi1(theta1)|H2|psi1(theta1)>, <psi1(theta1)|H3|psi1(theta1)> ]
psi1_H23 = estimator.run(
circuits=[psi1, psi1],
observables=[H2, H3],
parameter_values=[theta1]*2
)
print(psi1_H23.result())
|
https://github.com/iqm-finland/qiskit-on-iqm
|
iqm-finland
|
# Copyright 2022 Qiskit on IQM developers
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Testing IQMJob.
"""
import io
import uuid
import mockito
from mockito import mock, unstub, verify, when
import pytest
from qiskit import QuantumCircuit
from qiskit.providers import JobStatus
from qiskit.result import Counts
from qiskit.result import Result as QiskitResult
from qiskit.tools.monitor import job_monitor
from iqm.iqm_client import (
HeraldingMode,
Instruction,
IQMClient,
JobAbortionError,
RunResult,
RunStatus,
SingleQubitMapping,
Status,
)
from iqm.qiskit_iqm.iqm_job import IQMJob
from iqm.qiskit_iqm.iqm_provider import IQMBackend
@pytest.fixture()
def job(adonis_architecture):
client = mock(IQMClient)
when(client).get_quantum_architecture().thenReturn(adonis_architecture)
backend = IQMBackend(client)
return IQMJob(backend, str(uuid.uuid4()))
@pytest.fixture()
def iqm_result_no_shots():
return {'c_2_0_0': [], 'c_2_0_1': []}
@pytest.fixture()
def iqm_result_two_registers():
return {'c_2_0_0': [[1], [0], [1], [0]], 'c_2_0_1': [[1], [1], [0], [1]], 'd_4_1_2': [[1], [1], [1], [1]]}
@pytest.fixture()
def iqm_metadata():
measurement = Instruction(name='measure', implementation=None, qubits=('0',), args={'key': 'm1'})
return {
'calibration_set_id': 'df124054-f6d8-41f9-b880-8487f90018f9',
'request': {
'shots': 4,
'circuits': [{'name': 'circuit_1', 'instructions': (measurement,), 'metadata': {'a': 'b'}}],
'calibration_set_id': 'df124054-f6d8-41f9-b880-8487f90018f9',
'qubit_mapping': [
SingleQubitMapping(logical_name='0', physical_name='QB1'),
SingleQubitMapping(logical_name='1', physical_name='QB2'),
],
},
}
@pytest.fixture()
def iqm_metadata_with_timestamps():
measurement = Instruction(name='measure', implementation=None, qubits=('0',), args={'key': 'm1'})
return {
'calibration_set_id': 'df124054-f6d8-41f9-b880-8487f90018f9',
'request': {
'shots': 4,
'circuits': [{'name': 'circuit_1', 'instructions': (measurement,), 'metadata': {'a': 'b'}}],
'calibration_set_id': 'df124054-f6d8-41f9-b880-8487f90018f9',
'qubit_mapping': [
SingleQubitMapping(logical_name='0', physical_name='QB1'),
SingleQubitMapping(logical_name='1', physical_name='QB2'),
],
},
'timestamps': {
'job_start': '2023-01-02T12:34:56.123456+00:00',
'job_end': '2023-01-02T12:34:56.123456+03:00',
},
}
def test_submit_raises(job):
with pytest.raises(NotImplementedError, match='You should never have to submit jobs by calling this method.'):
job.submit()
def test_cancel_successful(job, recwarn):
when(job._client).abort_job(uuid.UUID(job.job_id())).thenReturn(None)
assert job.cancel() is True
assert len(recwarn) == 0
verify(job._client, times=1).abort_job(uuid.UUID(job.job_id()))
unstub()
def test_cancel_failed(job):
when(job._client).abort_job(uuid.UUID(job.job_id())).thenRaise(JobAbortionError)
with pytest.warns(UserWarning, match='Failed to cancel job'):
assert job.cancel() is False
verify(job._client, times=1).abort_job(uuid.UUID(job.job_id()))
unstub()
def test_status_for_ready_result(job):
job._result = [('circuit_1', ['11', '10', '10'])]
assert job.status() == JobStatus.DONE
result = job.result()
assert isinstance(result, QiskitResult)
assert result.get_memory() == ['11', '10', '10']
def test_status_done(job, iqm_metadata):
client_result = RunResult(status=Status.READY, measurements=None, metadata=iqm_metadata)
when(job._client).get_run_status(uuid.UUID(job.job_id())).thenReturn(client_result)
assert job.status() == JobStatus.DONE
assert job._result is None
@pytest.mark.parametrize(
'run_status,job_status',
[
(Status.PENDING_COMPILATION, JobStatus.QUEUED),
(Status.PENDING_EXECUTION, JobStatus.RUNNING),
(Status.FAILED, JobStatus.ERROR),
(Status.ABORTED, JobStatus.CANCELLED),
],
)
def test_other_job_statuses(job, run_status: Status, job_status: JobStatus):
when(job._client).get_run_status(uuid.UUID(job.job_id())).thenReturn(RunStatus(status=run_status))
assert job.status() == job_status
def test_error_message(job, iqm_metadata):
err_msg = 'The job failed with this error message'
client_result = RunResult(status=Status.FAILED, message=err_msg, metadata=iqm_metadata)
when(job._client).get_run_status(uuid.UUID(job.job_id())).thenReturn(client_result)
assert job.status() == JobStatus.ERROR
assert job.error_message() == err_msg
def test_error_message_on_successful_job(job, iqm_metadata):
client_result = RunResult(status=Status.READY, metadata=iqm_metadata)
when(job._client).get_run_status(uuid.UUID(job.job_id())).thenReturn(client_result)
assert job.status() == JobStatus.DONE
assert job.error_message() is None
def test_result(job, iqm_result_two_registers, iqm_metadata):
client_result = RunResult(
status=Status.READY,
measurements=[iqm_result_two_registers],
metadata=iqm_metadata,
)
when(job._client).wait_for_results(uuid.UUID(job.job_id())).thenReturn(client_result)
result = job.result()
assert isinstance(result, QiskitResult)
assert result.get_memory() == ['0100 11', '0100 10', '0100 01', '0100 10']
assert result.get_counts() == Counts({'0100 11': 1, '0100 10': 2, '0100 01': 1})
for r in result.results:
assert r.calibration_set_id == uuid.UUID('df124054-f6d8-41f9-b880-8487f90018f9')
assert r.data.metadata == {'a': 'b'}
assert result.request.qubit_mapping == iqm_metadata['request']['qubit_mapping']
# Assert that repeated call does not query the client (i.e. works without calling the mocked wait_for_results)
# and call to status() does not call any functions from client.
result = job.result()
assert isinstance(result, QiskitResult)
assert job.status() == JobStatus.DONE
mockito.verify(job._client, times=1).wait_for_results(uuid.UUID(job.job_id()))
def test_result_no_shots(job, iqm_result_no_shots, iqm_metadata):
iqm_metadata['request']['heralding_mode'] = HeraldingMode.ZEROS
client_result = RunResult(
status=Status.READY,
measurements=[iqm_result_no_shots],
metadata=iqm_metadata,
)
when(job._client).wait_for_results(uuid.UUID(job.job_id())).thenReturn(client_result)
with pytest.warns(UserWarning, match='Received measurement results containing zero shots.'):
result = job.result()
assert isinstance(result, QiskitResult)
assert result.get_memory() == []
assert result.get_counts() == Counts({})
def test_result_multiple_circuits(job, iqm_result_two_registers):
instruction_meta = [{'name': 'measure', 'qubits': ['0'], 'args': {'key': 'm1'}}]
iqm_metadata_multiple_circuits = {
'calibration_set_id': '9d75904b-0c93-461f-b1dc-bd200cfad1f1',
'request': {
'shots': 4,
'circuits': [
{'name': 'circuit_1', 'instructions': instruction_meta, 'metadata': {'a': 0}},
{'name': 'circuit_2', 'instructions': instruction_meta, 'metadata': {'a': 1}},
],
'calibration_set_id': '9d75904b-0c93-461f-b1dc-bd200cfad1f1',
'qubit_mapping': [
SingleQubitMapping(logical_name='0', physical_name='QB1'),
SingleQubitMapping(logical_name='1', physical_name='QB2'),
SingleQubitMapping(logical_name='2', physical_name='QB3'),
],
},
}
client_result = RunResult(
status=Status.READY,
measurements=[iqm_result_two_registers, iqm_result_two_registers],
metadata=iqm_metadata_multiple_circuits,
)
when(job._client).wait_for_results(uuid.UUID(job.job_id())).thenReturn(client_result)
result = job.result()
assert isinstance(result, QiskitResult)
for circuit_idx in range(2):
assert result.get_memory(circuit_idx) == ['0100 11', '0100 10', '0100 01', '0100 10']
assert result.get_counts(circuit_idx) == Counts({'0100 11': 1, '0100 10': 2, '0100 01': 1})
assert result.get_counts(QuantumCircuit(name='circuit_1')) == Counts({'0100 11': 1, '0100 10': 2, '0100 01': 1})
assert result.get_counts(QuantumCircuit(name='circuit_2')) == Counts({'0100 11': 1, '0100 10': 2, '0100 01': 1})
for i, r in enumerate(result.results):
assert r.calibration_set_id == uuid.UUID('9d75904b-0c93-461f-b1dc-bd200cfad1f1')
assert r.data.metadata == {'a': i}
assert result.request.qubit_mapping == iqm_metadata_multiple_circuits['request']['qubit_mapping']
def test_result_with_timestamps(job, iqm_result_two_registers, iqm_metadata_with_timestamps):
client_result = RunResult(
status=Status.READY,
measurements=[iqm_result_two_registers],
metadata=iqm_metadata_with_timestamps,
)
when(job._client).wait_for_results(uuid.UUID(job.job_id())).thenReturn(client_result)
assert job.metadata.get('timestamps') is None
result = job.result()
assert 'timestamps' in job.metadata
assert job.metadata.pop('timestamps') == iqm_metadata_with_timestamps.get('timestamps')
assert 'timestamps' in result._metadata
assert result.timestamps == iqm_metadata_with_timestamps.get('timestamps')
def test_job_monitor(job, iqm_metadata):
client_result = RunResult(status=Status.READY, metadata=iqm_metadata)
run_responses = [
[RunStatus(status=Status.PENDING_COMPILATION), RunStatus(status=Status.ABORTED)],
[RunStatus(status=Status.PENDING_COMPILATION)] * 2 + [RunStatus(status=Status.FAILED)],
[RunStatus(status=Status.PENDING_COMPILATION)] * 2
+ [RunStatus(status=Status.PENDING_EXECUTION), client_result],
[RunStatus(status=s.value) for s in Status],
]
sep = '---'
for responses in run_responses:
when(job._client).get_run_status(uuid.UUID(job.job_id())).thenReturn(*responses)
monitor_string = io.StringIO()
job_monitor(job, output=monitor_string, line_discipline=sep, interval=0)
monitor_string.close()
|
https://github.com/Pitt-JonesLab/mirror-gates
|
Pitt-JonesLab
|
from qiskit.transpiler.coupling import CouplingMap
import numpy as np
# Import from Qiskit Aer noise module
from mirror_gates.noisy_fidelity import get_noisy_fidelity
from tqdm import tqdm
from qiskit.circuit.random import random_circuit
import matplotlib.pyplot as plt
import numpy as np
from qiskit.circuit.library import QFT
from qiskit.transpiler import CouplingMap
from mirror_gates.noisy_fidelity import T1, T2
N = 8
# coupling_map = CouplingMap.from_full(N)
coupling_map = CouplingMap.from_line(N)
data1 = []
for i in tqdm(range(2, 100, 4)):
qc = random_circuit(N, i, max_operands=2, measure=False)
fid, duration, transp, expected_fid = get_noisy_fidelity(qc, coupling_map)
data1.append((i, duration, fid)) # Added depth (i) here
# sort by duration
data1 = sorted(data1, key=lambda x: x[1])
depths_sorted, durations_sorted, fidelities_sorted = zip(*data1)
fig, ax1 = plt.subplots()
# Plotting the fidelity vs. duration (main line)
ax1.set_xlabel("Duration")
ax1.set_ylabel("Fidelity")
ax1.plot(durations_sorted, fidelities_sorted, label="Fidelity")
# Setting the secondary x-axis for the depth of the random circuit
ax2 = ax1.twiny()
ax2.set_xlabel("Depth of Random Circuit")
ax2.set_xticks(durations_sorted)
ax2.set_xticklabels(depths_sorted)
n_qubits = N
duration_samples = np.linspace(min(durations_sorted), max(durations_sorted), 500)
decay_factor = [(1 / T1 + 1 / T2) * duration for duration in duration_samples]
single_qubit_fidelity = [np.exp(-factor) for factor in decay_factor]
total_fidelity = [fidelity**n_qubits for fidelity in single_qubit_fidelity]
label_string = r"$\left( e^{(-D/T_1 -D/T_2)} \right)^{N}$"
ax1.plot(duration_samples, total_fidelity, label=label_string, linestyle="--")
ax1.legend()
plt.title("Random Circuit (8-qubits) Fidelity vs Duration with Circuit Depth Reference")
plt.tight_layout() # Adjust layout to prevent overlap
plt.show()
N = 8
coupling_map = CouplingMap.from_full(N)
data2 = []
for i in tqdm(range(2, N + 1)):
qc = QFT(i)
fid, duration, transp = get_noisy_fidelity(qc, coupling_map)
data2.append((i, duration, fid))
# sort by duration
data2 = sorted(data2, key=lambda x: x[1])
sizes_sorted, durations_sorted, fidelities_sorted = zip(*data2)
fig, ax1 = plt.subplots()
# Plotting the fidelity vs. duration (main line)
ax1.set_xlabel("Duration")
ax1.set_ylabel("Fidelity")
ax1.plot(durations_sorted, fidelities_sorted, label="Fidelity")
ax1.tick_params(axis="y")
# Setting the secondary x-axis for the size of QFT
ax2 = ax1.twiny()
ax2.set_xlabel("Size of QFT")
ax2.set_xticks(durations_sorted)
ax2.set_xticklabels(sizes_sorted)
ax2.tick_params(axis="x")
# Adjusting the reference line calculation
unique_sizes = list(set(sizes_sorted))
reference_y_total = []
duration_samples_total = []
for size in unique_sizes:
min_duration = min(
[
duration
for size_curr, duration in zip(sizes_sorted, durations_sorted)
if size_curr == size
]
)
max_duration = max(
[
duration
for size_curr, duration in zip(sizes_sorted, durations_sorted)
if size_curr == size
]
)
duration_samples = np.linspace(min_duration, max_duration, 100)
reference_y = [
np.exp(-size * duration / (T1 + T2)) for duration in duration_samples
]
reference_y_total.extend(reference_y)
duration_samples_total.extend(duration_samples)
ax1.plot(
duration_samples_total,
reference_y_total,
label="e^{-nD / (T_1+T_2)}",
linestyle="--",
)
plt.title("n-QFT Fidelity vs Duration with QFT Size Reference")
plt.tight_layout() # Adjust layout to prevent overlap
plt.show()
|
https://github.com/qiskit-community/Qiskit-Hackathon-at-World-of-QUANTUM
|
qiskit-community
|
import numpy as np
# Importing standard Qiskit libraries
from qiskit.quantum_info import Statevector
from qiskit import QuantumCircuit, transpile, Aer, IBMQ, assemble
from qiskit.tools.jupyter import *
from qiskit.visualization import *
from ibm_quantum_widgets import *
# Loading your IBM Quantum account(s)
provider = IBMQ.load_account()
## X-gate
# FILL IN YOUR CODE HERE
# Keep theta<=np.pi
#
#
#
#
#
## Z-gate
# FILL IN YOUR CODE HERE
#
#
#
#
#
## Y-gate
# FILL IN YOUR CODE HERE
#
#
#
#
## Hadamard
# FILL IN YOUR CODE HERE
#
#
#
#
#
## Which rotation corresponds to the gate set H-Y-S-T ?
#Circuit:
qc=QuantumCircuit(1)
qc.h(0)
qc.y(0)
qc.s(0)
qc.t(0)
##FILL IN YOUR ANSWER HERE
#
#
#
#
#
#Check the result with the u3 rotation gate (arbitrary single qubit rotations)
qc2=QuantumCircuit(1)
qc2.u3(theta,phi,lam,0)
|
https://github.com/GabrielPontolillo/QiskitPBT
|
GabrielPontolillo
|
# class that inherits from property based test
from qiskit import QuantumCircuit
from QiskitPBT.property import Property
from QiskitPBT.input_generators import RandomState
class EntangledPrecondition(Property):
# specify the inputs that are to be generated
def get_input_generators(self):
# The assumption of our code is that we need at least one input generator, if we do not include it,
# the code breaks in the test runner - also its a fine assumption to include, property based testing requires inputs
return [RandomState(2)]
# specify the preconditions for the test
def preconditions(self, mock):
return True
# specify the operations to be performed on the input
def operations(self, mock):
qc = QuantumCircuit(2, 2)
qc.h(0)
qc.cx(0, 1)
self.statistical_analysis.assert_entangled(self, [0, 1], qc)
class EntangledCheckOnUnentangledState(Property):
# specify the inputs that are to be generated
def get_input_generators(self):
# The assumption of our code is that we need at least one input generator, if we do not include it,
# the code breaks in the test runner - also its a fine assumption to include, property based testing requires inputs
return [RandomState(2)]
# specify the preconditions for the test
def preconditions(self, mock):
return True
# specify the operations to be performed on the input
def operations(self, mock):
qc = QuantumCircuit(2, 2)
qc.h(0)
qc.h(1)
self.statistical_analysis.assert_entangled(self, [0, 1], qc)
class EntangledCheckOnGHZState(Property):
# specify the inputs that are to be generated
def get_input_generators(self):
# The assumption of our code is that we need at least one input generator, if we do not include it,
# the code breaks in the test runner - also its a fine assumption to include, property based testing requires inputs
return [RandomState(2)]
# specify the preconditions for the test
def preconditions(self, mock):
return True
# specify the operations to be performed on the input
def operations(self, mock):
qc = QuantumCircuit(3, 3)
qc.h(0)
qc.cx(0, 1)
qc.cx(1, 2)
self.statistical_analysis.assert_entangled(self, [0, 1, 2], qc, basis=["z"])
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
qc = QuantumCircuit(2, 2)
qc.h(0)
qc.cx(0, 1)
qc.measure([0, 1], [0, 1])
qc.draw('mpl')
|
https://github.com/MonitSharma/Learn-Quantum-Computing-with-Qiskit
|
MonitSharma
|
from qiskit import QuantumCircuit, QuantumRegister
input_bit = QuantumRegister(1, 'input')
output_bit = QuantumRegister(1, 'output')
garbage_bit = QuantumRegister(1, 'garbage')
Uf = QuantumCircuit(input_bit, output_bit, garbage_bit)
Uf.cx(input_bit[0], output_bit[0])
Uf.draw('mpl')
Vf = QuantumCircuit(input_bit, output_bit, garbage_bit)
Vf.cx(input_bit[0], garbage_bit[0])
Vf.cx(input_bit[0], output_bit[0])
Vf.draw('mpl')
qc = Uf.compose(Vf.inverse())
qc.draw('mpl')
final_output_bit = QuantumRegister(1, 'final-output')
copy = QuantumCircuit(output_bit, final_output_bit)
copy.cx(output_bit, final_output_bit)
copy.draw('mpl')
(Vf.inverse().compose(copy).compose(Vf)).draw('mpl')
|
https://github.com/AsishMandoi/VRP-explorations
|
AsishMandoi
|
import numpy as np
import utility
from full_qubo_solver import FullQuboSolver
from average_partition_solver import AveragePartitionSolver
from qiskit_native_solver import QiskitNativeSolver
from route_activation_solver import RouteActivationSolver
from clustered_tsp_solver import ClusteredTspSolver
from solution_partition_solver import SolutionPartitionSolver
n = 5
m = 2
seed = 1543
instance, xc, yc = utility.generate_vrp_instance(n, seed)
fqs = FullQuboSolver(n, m, instance)
fqs.solve(solver='leap')
fqs.visualize(xc, yc)
aps = AveragePartitionSolver(n, m, instance)
aps.solve(solver='leap')
aps.visualize(xc, yc)
ras = RouteActivationSolver(n, m, instance)
ras.solve(solver='leap')
ras.visualize(xc, yc)
qns = QiskitNativeSolver(n, m, instance)
qns.solve(solver='leap')
qns.visualize(xc, yc)
cts = ClusteredTspSolver(n, m, instance)
cts.solve(solver='leap')
cts.visualize(xc, yc)
sps = SolutionPartitionSolver(n, m, instance)
sps.solve(solver='leap')
sps.visualize(xc, yc)
vrp_list = [fqs, aps, ras, qns, cts, sps]
solver_types = ['FQS', 'APS', 'RAS', 'QNS', 'CTS', 'SPS']
for i, vrp in enumerate(vrp_list):
print(f'{solver_types[i]} - Optimized Cost: {vrp.evaluate_vrp_cost()}')
qubo_time = [vrp.timing['qubo_build_time'] for vrp in vrp_list]
for i in range(len(vrp_list)):
print(f'{solver_types[i]} - Classical QUBO Build Time: {qubo_time[i]} us')
qpu_time = [vrp.timing['qpu_access_time'] for vrp in vrp_list]
qpu_time[4] += cts.timing['clustering_time']['qpu_access_time']
for i in range(len(vrp_list)):
print(f'{solver_types[i]} - QPU Access Time: {qpu_time[i]} us')
from solution_partition_solver import CapcSolutionPartitionSolver
cap = 10
dem = [1, 2, 3, 4, 5]
sps = CapcSolutionPartitionSolver(n, m, instance, cap, dem)
sps.solve(solver='leap')
sps.visualize(xc, yc)
|
https://github.com/mberna/qce23-qiskit-runtime-primitives-tutorial
|
mberna
|
# instantiate runtime service
from qiskit_ibm_runtime import QiskitRuntimeService
QiskitRuntimeService.save_account(channel="ibm_quantum", token="MY_IBM_QUANTUM_TOKEN")
service = QiskitRuntimeService(channel="ibm_quantum")
# import required libraries and instantiate runtime service
from qiskit_ibm_runtime import Session, Estimator, Options
from qiskit.circuit.library import RealAmplitudes
from qiskit.quantum_info import SparsePauliOp
# create circuits and observables
psi1 = RealAmplitudes(num_qubits=2, reps=2)
psi2 = RealAmplitudes(num_qubits=2, reps=3)
H1 = SparsePauliOp.from_list([("II", 1), ("IZ", 2), ("XI", 3)])
H2 = SparsePauliOp.from_list([("IZ", 1)])
H3 = SparsePauliOp.from_list([("ZI", 1), ("ZZ", 1)])
psi1.decompose().draw(output='mpl')
psi2.decompose().draw(output='mpl')
import numpy as np
# generate random theta params
np.random.seed(0)
theta1 = np.random.rand(6) * np.pi
theta2 = np.random.rand(8) * np.pi
theta3 = np.random.rand(6) * np.pi
print(theta1)
print(theta2)
print(theta3)
options = Options()
options.execution.shots = 100
estimator = Estimator(backend="ibmq_qasm_simulator", options=options)
from qiskit_ibm_runtime import Options
options = Options(resilience_level=0)
options.execution.shots = 1024
estimator = Estimator(backend="ibmq_qasm_simulator", options=options)
# calculate [ <psi1(theta1)|H1|psi1(theta1)> ]
psi1_H1 = estimator.run(circuits=[psi1], observables=[H1],
parameter_values=[theta1])
print(psi1_H1.result())
# You can invoke run() multiple times!
# calculate [ <psi1(theta1)|H2|psi1(theta1)>, <psi1(theta1)|H3|psi1(theta1)> ]
psi1_H23 = estimator.run(circuits=[psi1, psi1], observables=[H2, H3],
parameter_values=[theta1]*2)
print(psi1_H23.result())
# Ex. 1: Calculate [ <psi2(theta2)|H2|psi2(theta2)> ]
# psi2_H2 = ...
# Ex. 2 calculate [ <psi1(theta1)|H1|psi1(theta1)>,
# <psi2(theta2)|H2|psi2(theta2)>,
# <psi1(theta3)|H3|psi1(theta3)> ]
# psi12_H23 = ...
# Ex. 3: use optimization_level 3
options = Options()
# options... # hint: use autocomplete
with Session(service=service, backend="ibmq_qasm_simulator") as session:
estimator = Estimator(session=session, options=options)
theta4 = [0, 1, 1, 2, 3, 5]
# calculate [ <psi1(theta1)|H1|psi1(theta1)> ]
psi1_H1 = estimator.run(circuits=[psi1], observables=[H1], parameter_values=[theta4])
print(psi1_H1.result())
# Ex. 4: Apply ZNE to the following example
# Remeber ZNE is enabled when resilience level is 2
options = Options()
# options... # hint: use autocomplete
estimator = Estimator(backend="ibmq_qasm_simulator", options=options)
theta4 = [0, 1, 1, 2, 3, 5]
psi1_H1 = estimator.run(circuits=[psi1], observables=[H1], parameter_values=[theta4])
print(psi1_H1.result())
from qiskit import QuantumCircuit
from qiskit_ibm_runtime import Sampler
bell = QuantumCircuit(2)
bell.h(0)
bell.cx(0, 1)
bell.measure_all()
sampler = Sampler(backend="ibmq_qasm_simulator") # Not passing any options, uses M3
job = sampler.run(circuits=bell)
print(job.result())
# You can invoke run() multiple times.
job = sampler.run(circuits=bell)
print(job.result())
|
https://github.com/MonitSharma/Qiskit-Summer-School-and-Quantum-Challenges
|
MonitSharma
|
import numpy as np
# Importing standard Qiskit libraries
from qiskit import QuantumCircuit, transpile, assemble, Aer, IBMQ, execute
from qiskit.quantum_info import Statevector
from qiskit.visualization import plot_bloch_multivector, plot_histogram
from qiskit_textbook.problems import dj_problem_oracle
def lab1_ex1():
qc = QuantumCircuit(1)
#
#
# FILL YOUR CODE IN HERE
#
#
qc.x(0)
return qc
state = Statevector.from_instruction(lab1_ex1())
plot_bloch_multivector(state)
from qc_grader import grade_lab1_ex1
# Note that the grading function is expecting a quantum circuit without measurements
grade_lab1_ex1(lab1_ex1())
def lab1_ex2():
qc = QuantumCircuit(1)
#
#
# FILL YOUR CODE IN HERE
#
#
qc.h(0)
return qc
state = Statevector.from_instruction(lab1_ex2())
plot_bloch_multivector(state)
from qc_grader import grade_lab1_ex2
# Note that the grading function is expecting a quantum circuit without measurements
grade_lab1_ex2(lab1_ex2())
def lab1_ex3():
qc = QuantumCircuit(1)
#
#
# FILL YOUR CODE IN HERE
#
#
qc.x(0)
qc.h(0)
return qc
state = Statevector.from_instruction(lab1_ex3())
plot_bloch_multivector(state)
from qc_grader import grade_lab1_ex3
# Note that the grading function is expecting a quantum circuit without measurements
grade_lab1_ex3(lab1_ex3())
def lab1_ex4():
qc = QuantumCircuit(1)
#
#
# FILL YOUR CODE IN HERE
#
#
qc.h(0)
qc.sdg(0)
return qc
state = Statevector.from_instruction(lab1_ex4())
plot_bloch_multivector(state)
from qc_grader import grade_lab1_ex4
# Note that the grading function is expecting a quantum circuit without measurements
grade_lab1_ex4(lab1_ex4())
def lab1_ex5():
qc = QuantumCircuit(2,2) # this time, we not only want two qubits, but also two classical bits for the measurement
#
#
# FILL YOUR CODE IN HERE
#
#
qc.h(0)
qc.cx(0,1)
qc.x(0)
return qc
qc = lab1_ex5()
qc.draw() # we draw the circuit
from qc_grader import grade_lab1_ex5
# Note that the grading function is expecting a quantum circuit without measurements
grade_lab1_ex5(lab1_ex5())
qc.measure(0, 0) # we perform a measurement on qubit q_0 and store the information on the classical bit c_0
qc.measure(1, 1) # we perform a measurement on qubit q_1 and store the information on the classical bit c_1
backend = Aer.get_backend('qasm_simulator') # we choose the simulator as our backend
counts = execute(qc, backend, shots = 1000).result().get_counts() # we run the simulation and get the counts
plot_histogram(counts) # let us plot a histogram to see the possible outcomes and corresponding probabilities
def lab1_ex6():
#
#
# FILL YOUR CODE IN HERE
#
#
qc = QuantumCircuit(3,3)
qc.h(0)
qc.cx(0,1)
qc.cx(1,2)
qc.y(1)
return qc
qc = lab1_ex6()
qc.draw() # we draw the circuit
from qc_grader import grade_lab1_ex6
# Note that the grading function is expecting a quantum circuit without measurements
grade_lab1_ex6(lab1_ex6())
oraclenr = 4 # determines the oracle (can range from 1 to 5)
oracle = dj_problem_oracle(oraclenr) # gives one out of 5 oracles
oracle.name = "DJ-Oracle"
def dj_classical(n, input_str):
# build a quantum circuit with n qubits and 1 classical readout bit
dj_circuit = QuantumCircuit(n+1,1)
# Prepare the initial state corresponding to your input bit string
for i in range(n):
if input_str[i] == '1':
dj_circuit.x(i)
# append oracle
dj_circuit.append(oracle, range(n+1))
# measure the fourth qubit
dj_circuit.measure(n,0)
return dj_circuit
n = 4 # number of qubits
input_str = '1111'
dj_circuit = dj_classical(n, input_str)
dj_circuit.draw() # draw the circuit
input_str = '1111'
dj_circuit = dj_classical(n, input_str)
qasm_sim = Aer.get_backend('qasm_simulator')
transpiled_dj_circuit = transpile(dj_circuit, qasm_sim)
qobj = assemble(transpiled_dj_circuit, qasm_sim)
results = qasm_sim.run(qobj).result()
answer = results.get_counts()
plot_histogram(answer)
def lab1_ex7():
min_nr_inputs = 2
max_nr_inputs = 9
return [min_nr_inputs, max_nr_inputs]
from qc_grader import grade_lab1_ex7
# Note that the grading function is expecting a list of two integers
grade_lab1_ex7(lab1_ex7())
n=4
def psi_0(n):
qc = QuantumCircuit(n+1,n)
# Build the state (|00000> - |10000>)/sqrt(2)
#
#
# FILL YOUR CODE IN HERE
#
#
qc.x(4)
qc.h(4)
return qc
dj_circuit = psi_0(n)
dj_circuit.draw()
def psi_1(n):
# obtain the |psi_0> = |00001> state
qc = psi_0(n)
# create the superposition state |psi_1>
#
#
qc.h(0)
qc.h(1)
qc.h(2)
qc.h(3)
#
#
qc.barrier()
return qc
dj_circuit = psi_1(n)
dj_circuit.draw()
def psi_2(oracle,n):
# circuit to obtain psi_1
qc = psi_1(n)
# append the oracle
qc.append(oracle, range(n+1))
return qc
dj_circuit = psi_2(oracle, n)
dj_circuit.draw()
def lab1_ex8(oracle, n): # note that this exercise also depends on the code in the functions psi_0 (In [24]) and psi_1 (In [25])
qc = psi_2(oracle, n)
# apply n-fold hadamard gate
#
#
# FILL YOUR CODE IN HERE
#
#
qc.h(0)
qc.h(1)
qc.h(2)
qc.h(3)
# add the measurement by connecting qubits to classical bits
#
#
qc.measure(0,0)
qc.measure(1,1)
qc.measure(2,2)
qc.measure(3,3)
#
#
return qc
dj_circuit = lab1_ex8(oracle, n)
dj_circuit.draw()
from qc_grader import grade_lab1_ex8
# Note that the grading function is expecting a quantum circuit with measurements
grade_lab1_ex8(lab1_ex8(dj_problem_oracle(4),n))
qasm_sim = Aer.get_backend('qasm_simulator')
transpiled_dj_circuit = transpile(dj_circuit, qasm_sim)
qobj = assemble(transpiled_dj_circuit)
results = qasm_sim.run(qobj).result()
answer = results.get_counts()
plot_histogram(answer)
|
https://github.com/alpine-quantum-technologies/qiskit-aqt-provider-rc
|
alpine-quantum-technologies
|
import numpy as np
from qiskit import(
QuantumCircuit,
execute,
Aer)
from qiskit.visualization import plot_histogram
# Use Aer's qasm_simulator
simulator = Aer.get_backend('qasm_simulator')
# Create a Quantum Circuit acting on the q register
circuit = QuantumCircuit(2, 2)
# Add a H gate on qubit 0
circuit.h(0)
# Add a CX (CNOT) gate on control qubit 0 and target qubit 1
circuit.cx(0, 1)
# Map the quantum measurement to the classical bits
circuit.measure([0,1], [0,1])
# Execute the circuit on the qasm simulator
job = execute(circuit, simulator, shots=1000)
# Grab results from the job
result = job.result()
# Returns counts
counts = result.get_counts(circuit)
print(counts)
# Draw the circuit
circuit.draw()
print(circuit)
|
https://github.com/mspronesti/qlearnkit
|
mspronesti
|
import logging
from typing import Union, Optional, List
import numpy as np
from abc import abstractmethod
from qiskit import QuantumCircuit
from qiskit.providers import Backend
from qiskit.result import Result
from sklearn.base import TransformerMixin
from qiskit.utils import QuantumInstance
from qiskit.exceptions import QiskitError
logger = logging.getLogger(__name__)
class QuantumEstimator(TransformerMixin):
def __init__(
self,
encoding_map=None,
quantum_instance: Optional[Union[QuantumInstance, Backend]] = None,
):
"""
Args:
encoding_map:
Map to classical data to quantum states.
This class does not impose any constraint on it. It
can either be a custom encoding map or a qiskit FeatureMap
quantum_instance:
The quantum instance to set. Can be a
:class:`~qiskit.utils.QuantumInstance` or a :class:`~qiskit.providers.Backend`
"""
self.X_train = np.asarray([])
self.y_train = np.asarray([])
self._encoding_map = encoding_map
self._set_quantum_instance(quantum_instance)
@abstractmethod
def fit(self, X_train: np.ndarray, y_train: np.ndarray):
"""
Fits the model using X as training dataset
and y as training labels
Args:
X_train: training dataset
y_train: training labels
"""
raise NotImplementedError("Must have implemented this.")
@abstractmethod
def predict(self, X_test: np.ndarray) -> np.ndarray:
"""
Predicts the labels associated to the
unclassified data X_test
Args:
X_test: the unclassified data
Returns:
the labels associated to X_test
"""
raise NotImplementedError("Must have implemented this.")
@property
def quantum_instance(self) -> QuantumInstance:
"""Returns the quantum instance to evaluate the circuit."""
return self._quantum_instance
@quantum_instance.setter
def quantum_instance(
self, quantum_instance: Optional[Union[QuantumInstance, Backend]]
):
"""Quantum Instance setter"""
self._set_quantum_instance(quantum_instance)
def _set_quantum_instance(
self, quantum_instance: Optional[Union[QuantumInstance, Backend]]
):
"""
Internal method to set a quantum instance according to its type
Args:
The quantum instance to set. Can be a
:class:``~qiskit.utils.QuantumInstance``, a :class:`~qiskit.providers.Backend`
or a :class:`~qiskit.providers.BaseBackend`
"""
if isinstance(quantum_instance, Backend):
quantum_instance = QuantumInstance(quantum_instance)
self._quantum_instance = quantum_instance
@property
def encoding_map(self):
"""Returns the Encoding Map"""
return self._encoding_map
@encoding_map.setter
def encoding_map(self, encoding_map):
"""Encoding Map setter"""
self._encoding_map = encoding_map
def execute(
self, qcircuits: Union[QuantumCircuit, List[QuantumCircuit]]
) -> Union[Optional[Result], None]:
"""
Executes the given quantum circuit
Args:
qcircuits:
a :class:`~qiskit.QuantumCircuit` or a list of
this type to be executed
Returns:
the execution results
"""
if self._quantum_instance is None:
raise QiskitError("Circuits execution requires a quantum instance")
logger.info("Executing circuits...")
# Instead of transpiling and assembling the quantum object
# and running the backend, we call execute from the quantum
# instance that does it at once a very efficient way
# please notice: this execution is parallelized
# which is why we pass a list of circuits and not one at a time
result = self._quantum_instance.execute(qcircuits)
return result
@abstractmethod
def score(
self, X: np.ndarray, y: np.ndarray, sample_weight: Optional[np.ndarray] = None
) -> float:
"""
Returns a score of this model given samples and true values for the samples.
In case of classification, this value should correspond to mean accuracy,
in case of regression, the coefficient of determination :math:`R^2` of the prediction.
In case of clustering, the `y` parameter is typically ignored.
Args:
X: array-like of shape (n_samples, n_features)
y: array-like of labels of shape (n_samples,)
sample_weight: array-like of shape (n_samples,), default=None
The weights for each observation in X. If None, all observations
are assigned equal weight.
Returns:
a float score of the model.
"""
raise NotImplementedError("Must have implemented this.")
|
https://github.com/tomtuamnuq/compare-qiskit-ocean
|
tomtuamnuq
|
import time, warnings
from typing import Tuple
warnings.simplefilter("ignore")
import numpy as np
from qiskit import IBMQ
from qiskit.test.mock import FakeMumbai
from qiskit.test.mock.fake_qasm_backend import FakeQasmBackend
from qiskit.providers.aer import AerSimulator
from qiskit.providers.aer.noise import NoiseModel
from qiskit_optimization import QuadraticProgram
from qiskit_optimization.algorithms import MinimumEigenOptimizer as MEO
from qiskit_optimization.algorithms import MinimumEigenOptimizationResult as MEORes
from qiskit_optimization.algorithms import CplexOptimizer
import dimod
from dwave.system import DWaveSampler, EmbeddingComposite, DWaveCliqueSampler
from utilities.helpers import create_qaoa_meo, create_quadratic_programs_from_paths
DIR = 'TEST_DATA' + "/" + time.strftime("%d_%m_%Y")
DIR
# select QUBOs to solve
qps_dense = create_quadratic_programs_from_paths(DIR + "/DENSE/")
qp_dense = qps_dense['test_3']
qps_sparse = create_quadratic_programs_from_paths(DIR + "/SPARSE/")
qp_sparse = qps_sparse['test_3']
qps_multiple = create_quadratic_programs_from_paths(DIR + "/MULTIPLE/")
qp_mult = qps_multiple["test_20"]
qp_cplex = create_quadratic_programs_from_paths(DIR + "/CPLEX/")['test_cplex']
# set parameters and arguments
num_reads = 1024
classic_iters = 5
def qaoa_callback(eval_ct: int, opt_pars: np.ndarray, mean: float, stdev: float) -> None:
"""Print parameterset of last iteration."""
if eval_ct == classic_iters:
print("Evaluation count reached ", eval_ct, "with pars:", opt_pars)
device = FakeMumbai()
qaoa_kwargs = {"shots": num_reads, "noise_model": NoiseModel.from_backend(device),
"max_iter": classic_iters, "qaoa_callback": qaoa_callback, "optimization_level": 3}
dwave_parameters = {'num_reads': num_reads, 'annealing_time': 3}
def init_qaoa_optimizers(device: FakeQasmBackend) -> Tuple[MEO, MEO]:
# init local backend simulator with noise model
local = AerSimulator.from_backend(device)
qaoa_local = create_qaoa_meo(backend=local, **qaoa_kwargs)
# init IBM Q Experience Simulator
IBMQ.load_account()
ibmq = IBMQ.get_provider(hub='ibm-q').get_backend('simulator_statevector')
conf = device.configuration()
qaoa_ibmq_sim = create_qaoa_meo(backend=ibmq, coupling_map=conf.coupling_map, basis_gates=conf.basis_gates,
**qaoa_kwargs)
return qaoa_local, qaoa_ibmq_sim
# init Optimizers
cplex = CplexOptimizer()
qaoa_local_sim, qaoa_ibmq_sim = init_qaoa_optimizers(device)
dwave_dense = DWaveCliqueSampler()
dwave_sparse = EmbeddingComposite(DWaveSampler()) # TODO rename to dwave_auto
def dwave_solve_qp(sampler: dimod.Sampler, qubo: QuadraticProgram):
bqm = dimod.as_bqm(qubo.objective.linear.to_array(), qubo.objective.quadratic.to_array(), dimod.BINARY)
sampleset = sampler.sample(bqm, **dwave_parameters)
return sampleset
def eval_qaoa_result(res: MEORes) -> Tuple[float, float]:
prob = res.samples[0].probability
fval = res.samples[0].fval
return prob, fval
def eval_bqm_sampleset(sampleset) -> Tuple[float, float]:
prob = sampleset.record.num_occurrences[0] / num_reads
fval = sampleset.record.energy[0]
return prob, fval
# solve classically
for qp in (qp_dense, qp_sparse):
print(qp.name)
print(cplex.solve(qp))
# solve by using Mumbai noise model with local qasm sim
res_dense_qaoa = qaoa_local_sim.solve(qp_dense)
eval_qaoa_result(res_dense_qaoa)
# solve by using D-Wave Pegasus Advantage system
res_dense_dwave = dwave_solve_qp(dwave_dense, qp_dense)
eval_bqm_sampleset(res_dense_dwave)
qp_sparse = qps_sparse['test_8']
cplex.solve(qp_sparse)
# solve by using Mumbai noise model with IBM Q Experience simulator
warnings.filterwarnings("ignore", category=DeprecationWarning)
res_sparse_qaoa = qaoa_ibmq_sim.solve(qp_sparse)
eval_qaoa_result(res_sparse_qaoa)
cplex.solve(qp_mult) # takes just a few minutes
# solve by using D-Wave Pegasus Advantage system
res_mult_dwave = dwave_solve_qp(dwave_sparse, qp_mult)
eval_bqm_sampleset(res_mult_dwave)
start_time = time.perf_counter()
res_cplex = cplex.solve(qp_cplex)
cplex_runtime = time.perf_counter() - start_time
print(res_cplex)
cplex_runtime
start_time = time.perf_counter()
res_cplex_dwave = dwave_solve_qp(dwave_sparse, qp_cplex)
dwave_runtime = time.perf_counter() - start_time
print(eval_bqm_sampleset(res_cplex_dwave))
dwave_runtime
|
https://github.com/daimurat/qiskit-implementation
|
daimurat
|
from qiskit import *
from qiskit.circuit import ParameterVector, QuantumCircuit
from qiskit.aqua import QuantumInstance
from qiskit.aqua.operators import I, Z
from qiskit.aqua.operators.state_fns import StateFn, CircuitStateFn
from qiskit.aqua.operators.expectations import PauliExpectation, AerPauliExpectation
from qiskit.aqua.operators.converters import CircuitSampler
import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline
######## パラメータ #############
nqubit = 3 ## qubitの数
c_depth = 3 ## circuitの深さ
## [x_min, x_max]のうち, ランダムにnum_x_train個の点をとって教師データとする.
x_min = - 1.; x_max = 1.;
num_x_train = 50
## 学習したい1変数関数
func_to_learn = lambda x: np.sin(x*np.pi)
## 乱数のシード
random_seed = 0
## 乱数発生器の初期化
np.random.seed(random_seed)
x_train = x_min + (x_max - x_min) * np.random.rand(num_x_train)
y_train = func_to_learn(x_train)
# 現実のデータを用いる場合を想定しノイズを付加
mag_noise = 0.05
y_train = y_train + mag_noise * np.random.randn(num_x_train)
plt.plot(x_train, y_train, "o"); plt.show()
def get_expectation_val(psi, op):
# define your backend or quantum instance
backend = Aer.get_backend('qasm_simulator')
q_instance = QuantumInstance(backend, shots=1024)
# define the state to sample
measurable_expression = StateFn(op, is_measurement=True).compose(psi)
# convert to expectation value
expectation = PauliExpectation().convert(measurable_expression)
# expectation = AerPauliExpectation().convert(measurable_expression)
# get state sampler (you can also pass the backend directly)
sampler = CircuitSampler(q_instance).convert(expectation)
# evaluate
return sampler.eval().real
def U_in(x):
U = QuantumCircuit(nqubit)
angle_y = np.arcsin(x)
angle_z = np.arccos(x**2)
for i in range(nqubit):
U.ry(angle_y, i)
U.rz(angle_z, i)
return U
# 横磁場イジングモデルのパラメーター
time_step = 0.77 # ランダムハミルトニアンによる時間発展の経過時間
M = 2 # トロッター分解の分割数
delta = time_step/M # 時間の刻み幅
h = 3 # 外部磁場
# 回転ゲートのパラメーター
param_list = ParameterVector('theta', c_depth*nqubit*3)
def U_out():
qc = QuantumCircuit(nqubit)
for d in range(c_depth):
for s in range(M):
# トロッター分解の1回分、
for i in range(nqubit):
qc.cx(i,(i+1)%nqubit)
qc.rz(-2*delta,(i+1)%nqubit)
qc.cx(i,(i+1)%nqubit)
qc.rx(-2*delta*h, i)
# 回転ゲートを導入
for i in range(nqubit):
qc.rx(-2*param_list[3*(nqubit*d+i)], i)
qc.rz(-2*param_list[3*(nqubit*d+i)+1], i)
qc.rx(-2*param_list[3*(nqubit*d+i)+2], i)
return qc
# モデルの出力
# 出力状態において最初の量子ビットのZでの期待値を計算
from qiskit.aqua.operators import Z, I
def qcl_pred(x, param_dict):
qcl_cirq = U_in(x) + U_out()
qcl_cirq.assign_parameters(param_dict, inplace=True)
op = Z ^ I ^ I
psi = StateFn(qcl_cirq)
return 2 * get_expectation_val(psi, op)
# cost function Lを計算
def cost_func(theta_list):
param_dict = dict(zip(param_list.params, theta_list))
# num_x_train個のデータについて計算
y_pred = [qcl_pred(x, param_dict) for x in x_train]
# quadratic loss
L = ((y_pred - y_train)**2).mean()
return L
# パラメータthetaの初期値theta_initにおけるコスト関数の値
# theta: 長さc_depth * nqubit * 3のndarray
theta_init = [2.0 * np.pi * np.random.rand() for i in range(c_depth*nqubit*3)]
cost_func(theta_init)
# パラメータthetaの初期値のもとでのグラフ
xlist = np.arange(x_min, x_max, 0.02)
theta_init_dict = dict(zip(param_list.params, theta_init))
y_init = [qcl_pred(x, theta_init_dict) for x in xlist]
plt.plot(xlist, y_init)
from scipy.optimize import minimize
# 学習(注意:2.5時間かかりました)
result = minimize(cost_func, theta_init, method='Nelder-Mead')
theta_opt = result.x
print(theta_opt)
# プロット
plt.figure(figsize=(10, 6))
xlist = np.arange(x_min, x_max, 0.02)
# 教師データ
plt.plot(x_train, y_train, "o", label='Teacher')
# パラメータθの初期値のもとでのグラフ
plt.plot(xlist, y_init, '--', label='Initial Model Prediction', c='gray')
# モデルの予測値
theta_opt_dict = dict(zip(param_list.params, theta_opt))
y_pred = np.array([qcl_pred(x, theta_opt_dict) for x in xlist])
plt.plot(xlist, y_pred, label='Final Model Prediction')
plt.legend()
plt.show()
20:57 23:30
|
https://github.com/swe-train/qiskit__qiskit
|
swe-train
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test the Layout Score pass"""
import unittest
from qiskit import QuantumRegister, QuantumCircuit
from qiskit.circuit.library import CXGate
from qiskit.transpiler.passes import Layout2qDistance
from qiskit.transpiler import CouplingMap, Layout
from qiskit.converters import circuit_to_dag
from qiskit.transpiler.target import Target
from qiskit.test import QiskitTestCase
class TestLayoutScoreError(QiskitTestCase):
"""Test error-ish of Layout Score"""
def test_no_layout(self):
"""No Layout. Empty Circuit CouplingMap map: None. Result: None"""
qr = QuantumRegister(3, "qr")
circuit = QuantumCircuit(qr)
coupling = CouplingMap()
layout = None
dag = circuit_to_dag(circuit)
pass_ = Layout2qDistance(coupling)
pass_.property_set["layout"] = layout
pass_.run(dag)
self.assertIsNone(pass_.property_set["layout_score"])
class TestTrivialLayoutScore(QiskitTestCase):
"""Trivial layout scenarios"""
def test_no_cx(self):
"""Empty Circuit CouplingMap map: None. Result: 0"""
qr = QuantumRegister(3, "qr")
circuit = QuantumCircuit(qr)
coupling = CouplingMap()
layout = Layout().generate_trivial_layout(qr)
dag = circuit_to_dag(circuit)
pass_ = Layout2qDistance(coupling)
pass_.property_set["layout"] = layout
pass_.run(dag)
self.assertEqual(pass_.property_set["layout_score"], 0)
def test_swap_mapped_true(self):
"""Mapped circuit. Good Layout
qr0 (0):--(+)---(+)-
| |
qr1 (1):---.-----|--
|
qr2 (2):---------.--
CouplingMap map: [1]--[0]--[2]
"""
qr = QuantumRegister(3, "qr")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[1])
circuit.cx(qr[0], qr[2])
coupling = CouplingMap([[0, 1], [0, 2]])
layout = Layout().generate_trivial_layout(qr)
dag = circuit_to_dag(circuit)
pass_ = Layout2qDistance(coupling)
pass_.property_set["layout"] = layout
pass_.run(dag)
self.assertEqual(pass_.property_set["layout_score"], 0)
def test_swap_mapped_false(self):
"""Needs [0]-[1] in a [0]--[2]--[1] Result: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]])
layout = Layout().generate_trivial_layout(qr)
dag = circuit_to_dag(circuit)
pass_ = Layout2qDistance(coupling)
pass_.property_set["layout"] = layout
pass_.run(dag)
self.assertEqual(pass_.property_set["layout_score"], 1)
def test_swap_mapped_true_target(self):
"""Mapped circuit. Good Layout
qr0 (0):--(+)---(+)-
| |
qr1 (1):---.-----|--
|
qr2 (2):---------.--
CouplingMap map: [1]--[0]--[2]
"""
qr = QuantumRegister(3, "qr")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[1])
circuit.cx(qr[0], qr[2])
target = Target()
target.add_instruction(CXGate(), {(0, 1): None, (0, 2): None})
layout = Layout().generate_trivial_layout(qr)
dag = circuit_to_dag(circuit)
pass_ = Layout2qDistance(target)
pass_.property_set["layout"] = layout
pass_.run(dag)
self.assertEqual(pass_.property_set["layout_score"], 0)
def test_swap_mapped_false_target(self):
"""Needs [0]-[1] in a [0]--[2]--[1] Result:1
qr0:--(+)--
|
qr1:---.---
CouplingMap map: [0]--[2]--[1]
"""
qr = QuantumRegister(2, "qr")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[1])
target = Target()
target.add_instruction(CXGate(), {(0, 2): None, (2, 1): None})
layout = Layout().generate_trivial_layout(qr)
dag = circuit_to_dag(circuit)
pass_ = Layout2qDistance(target)
pass_.property_set["layout"] = layout
pass_.run(dag)
self.assertEqual(pass_.property_set["layout_score"], 1)
if __name__ == "__main__":
unittest.main()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.