repo
stringclasses 885
values | file
stringclasses 741
values | content
stringlengths 4
215k
|
---|---|---|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
# You can show the phase of each state and use
# degrees instead of radians
from qiskit.quantum_info import DensityMatrix
import numpy as np
from qiskit import QuantumCircuit
from qiskit.visualization import plot_state_qsphere
qc = QuantumCircuit(2)
qc.h([0, 1])
qc.cz(0,1)
qc.ry(np.pi/3, 0)
qc.rx(np.pi/5, 1)
qc.z(1)
matrix = DensityMatrix(qc)
plot_state_qsphere(matrix,
show_state_phases = True, use_degrees = True)
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
import qiskit
from qiskit import IBMQ # requires qiskit version >= 0.6
IBMQ.save_account("MY_TOKEN")
IBMQ.load_accounts()
for backend in IBMQ.backends():
print(backend)
backend_0 = IBMQ.backends()[0] # retrieve the Backend at index 0
print(backend_0.configuration())
print("Go check its specification at %s" % backend_0.configuration()["url"])
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
circ = QuantumCircuit(2, 2)
circ.h(0)
circ.cx(0, 1)
circ.measure(0, 0)
circ.measure(1, 1)
circ.draw('mpl')
from qiskit import pulse
from qiskit.pulse.library import Gaussian
from qiskit.providers.fake_provider import FakeValencia
backend = FakeValencia()
with pulse.build(backend, name='hadamard') as h_q0:
pulse.play(Gaussian(duration=128, amp=0.1, sigma=16), pulse.drive_channel(0))
h_q0.draw()
circ.add_calibration('h', [0], h_q0)
from qiskit import transpile
from qiskit.providers.fake_provider import FakeHanoi
backend = FakeHanoi()
circ = transpile(circ, backend)
print(backend.configuration().basis_gates)
circ.draw('mpl', idle_wires=False)
from qiskit import QuantumCircuit
from qiskit.circuit import Gate
circ = QuantumCircuit(1, 1)
custom_gate = Gate('my_custom_gate', 1, [3.14, 1])
# 3.14 is an arbitrary parameter for demonstration
circ.append(custom_gate, [0])
circ.measure(0, 0)
circ.draw('mpl')
with pulse.build(backend, name='custom') as my_schedule:
pulse.play(Gaussian(duration=64, amp=0.2, sigma=8), pulse.drive_channel(0))
circ.add_calibration('my_custom_gate', [0], my_schedule, [3.14, 1])
# Alternatively: circ.add_calibration(custom_gate, [0], my_schedule)
circ = transpile(circ, backend)
circ.draw('mpl', idle_wires=False)
circ = QuantumCircuit(2, 2)
circ.append(custom_gate, [1])
from qiskit import QiskitError
try:
circ = transpile(circ, backend)
except QiskitError as e:
print(e)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/Dpbm/scientific-research-1-quantum-oracles
|
Dpbm
|
%matplotlib inline
from qiskit import QuantumCircuit, transpile
from qiskit.circuit.library import QFT
from qiskit.visualization import plot_histogram, plot_bloch_multivector
from qiskit.quantum_info import Statevector
from qiskit_aer import AerSimulator
import numpy as np
from fractions import Fraction
from utils import get_image_path
def create_qpe(phase, total_counting_qubits=3):
total_qubits = total_counting_qubits+1
qc = QuantumCircuit(total_qubits, total_counting_qubits)
qc.x(-1)
qc.h(range(total_counting_qubits))
repetitions = 1
for qubit in range(total_counting_qubits):
for _ in range(repetitions):
qc.cp(phase, qubit, -1)
repetitions *= 2
qc.append(QFT(total_counting_qubits, inverse=True), range(total_counting_qubits))
qc.measure(range(total_counting_qubits), range(total_counting_qubits))
return qc
sim = AerSimulator()
counting_qubits = 3
lambda_ = np.pi
qc = create_qpe(lambda_)
display(qc.draw('mpl', filename=get_image_path('qpe.png')))
job = sim.run(transpile(qc, sim), shots=1000).result().get_counts()
display(plot_histogram(job))
def get_theta(counting_qubits, counts):
N = 2**(counting_qubits)
estimated_value = int(max(counts, key=counts.get), 2)
return Fraction(estimated_value, N)
theta = get_theta(counting_qubits, job)
theta
def get_phi(counting_qubits, theta):
fraction = Fraction(2*float(theta)).limit_denominator(2**counting_qubits)
return float(fraction)*np.pi
phi = get_phi(counting_qubits, theta)
phi
def check(phi):
qc = QuantumCircuit(1)
qc.x(0)
qc.p(phi, 0)
display(Statevector(qc).draw('latex'))
check(phi)
lambda_ = np.pi/2
counting_qubits = 4
qc = create_qpe(lambda_, counting_qubits)
job = sim.run(transpile(qc, sim), shots=1000).result().get_counts()
plot_histogram(job)
theta = get_theta(counting_qubits, job)
phi = get_phi(counting_qubits, theta)
print(f"theta: {theta}\nphi:{phi}")
check(phi)
|
https://github.com/jonasmaziero/computacao_quantica_qiskit
|
jonasmaziero
|
!pip install --upgrade pyscf
from qiskit_nature.units import DistanceUnit
from qiskit_nature.second_q.drivers import PySCFDriver
driver = PySCFDriver(
atom="H 0 0 0; H 0 0 0.735",
basis="sto3g",
charge=0,
spin=0,
unit=DistanceUnit.ANGSTROM,
)
es_problem = driver.run()
#!pip install qiskit_algorithms
from qiskit_algorithms.optimizers import SPSA # simultaneous perturbation stochastic approximation
from qiskit.circuit.library import EfficientSU2 # ansatz para o circuito variacional
ansatz = EfficientSU2(2)
ansatz.decompose().draw('mpl')
from qiskit.primitives import Estimator
estimator = Estimator()
callback = lambda nfev, params, fval, step, acc: print(f'Evaluation {nfev}: {fval}')
optimizer = SPSA(callback=callback, maxiter=1000)
cost_func = lambda params: estimator.run(ansatz, H2_op, parameter_values=params).result().values[0]
result = optimizer.minimize(cost_func, x0=np.zeros(ansatz.num_parameters))
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2018, 2023.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test MatrixExpectation"""
import unittest
from test.python.opflow import QiskitOpflowTestCase
import itertools
import numpy as np
from qiskit.utils import QuantumInstance
from qiskit.opflow import (
X,
Y,
Z,
I,
CX,
H,
S,
ListOp,
Zero,
One,
Plus,
Minus,
StateFn,
MatrixExpectation,
CircuitSampler,
)
from qiskit import BasicAer
class TestMatrixExpectation(QiskitOpflowTestCase):
"""Pauli Change of Basis Expectation tests."""
def setUp(self) -> None:
super().setUp()
self.seed = 97
backend = BasicAer.get_backend("statevector_simulator")
with self.assertWarns(DeprecationWarning):
q_instance = QuantumInstance(
backend, seed_simulator=self.seed, seed_transpiler=self.seed
)
self.sampler = CircuitSampler(q_instance, attach_results=True)
self.expect = MatrixExpectation()
def test_pauli_expect_pair(self):
"""pauli expect pair test"""
op = Z ^ Z
# wf = (Pl^Pl) + (Ze^Ze)
wf = CX @ (H ^ I) @ Zero
converted_meas = self.expect.convert(~StateFn(op) @ wf)
self.assertAlmostEqual(converted_meas.eval(), 0, delta=0.1)
with self.assertWarns(DeprecationWarning):
sampled = self.sampler.convert(converted_meas)
self.assertAlmostEqual(sampled.eval(), 0, delta=0.1)
def test_pauli_expect_single(self):
"""pauli expect single test"""
paulis = [Z, X, Y, I]
states = [Zero, One, Plus, Minus, S @ Plus, S @ Minus]
for pauli, state in itertools.product(paulis, states):
converted_meas = self.expect.convert(~StateFn(pauli) @ state)
matmulmean = state.adjoint().to_matrix() @ pauli.to_matrix() @ state.to_matrix()
self.assertAlmostEqual(converted_meas.eval(), matmulmean, delta=0.1)
with self.assertWarns(DeprecationWarning):
sampled = self.sampler.convert(converted_meas)
self.assertAlmostEqual(sampled.eval(), matmulmean, delta=0.1)
def test_pauli_expect_op_vector(self):
"""pauli expect op vector test"""
paulis_op = ListOp([X, Y, Z, I])
converted_meas = self.expect.convert(~StateFn(paulis_op))
with self.assertWarns(DeprecationWarning):
plus_mean = converted_meas @ Plus
np.testing.assert_array_almost_equal(plus_mean.eval(), [1, 0, 0, 1], decimal=1)
sampled_plus = self.sampler.convert(plus_mean)
np.testing.assert_array_almost_equal(sampled_plus.eval(), [1, 0, 0, 1], decimal=1)
minus_mean = converted_meas @ Minus
np.testing.assert_array_almost_equal(minus_mean.eval(), [-1, 0, 0, 1], decimal=1)
sampled_minus = self.sampler.convert(minus_mean)
np.testing.assert_array_almost_equal(sampled_minus.eval(), [-1, 0, 0, 1], decimal=1)
zero_mean = converted_meas @ Zero
np.testing.assert_array_almost_equal(zero_mean.eval(), [0, 0, 1, 1], decimal=1)
sampled_zero = self.sampler.convert(zero_mean)
np.testing.assert_array_almost_equal(sampled_zero.eval(), [0, 0, 1, 1], decimal=1)
sum_zero = (Plus + Minus) * (0.5**0.5)
sum_zero_mean = converted_meas @ sum_zero
np.testing.assert_array_almost_equal(sum_zero_mean.eval(), [0, 0, 1, 1], decimal=1)
sampled_zero = self.sampler.convert(sum_zero)
np.testing.assert_array_almost_equal(
(converted_meas @ sampled_zero).eval(), [0, 0, 1, 1], decimal=1
)
for i, op in enumerate(paulis_op.oplist):
mat_op = op.to_matrix()
np.testing.assert_array_almost_equal(
zero_mean.eval()[i],
Zero.adjoint().to_matrix() @ mat_op @ Zero.to_matrix(),
decimal=1,
)
np.testing.assert_array_almost_equal(
plus_mean.eval()[i],
Plus.adjoint().to_matrix() @ mat_op @ Plus.to_matrix(),
decimal=1,
)
np.testing.assert_array_almost_equal(
minus_mean.eval()[i],
Minus.adjoint().to_matrix() @ mat_op @ Minus.to_matrix(),
decimal=1,
)
def test_pauli_expect_state_vector(self):
"""pauli expect state vector test"""
states_op = ListOp([One, Zero, Plus, Minus])
paulis_op = X
converted_meas = self.expect.convert(~StateFn(paulis_op) @ states_op)
np.testing.assert_array_almost_equal(converted_meas.eval(), [0, 0, 1, -1], decimal=1)
with self.assertWarns(DeprecationWarning):
sampled = self.sampler.convert(converted_meas)
np.testing.assert_array_almost_equal(sampled.eval(), [0, 0, 1, -1], decimal=1)
# Small test to see if execution results are accessible
for composed_op in sampled:
self.assertIn("statevector", composed_op[1].execution_results)
def test_pauli_expect_op_vector_state_vector(self):
"""pauli expect op vector state vector test"""
paulis_op = ListOp([X, Y, Z, I])
states_op = ListOp([One, Zero, Plus, Minus])
valids = [[+0, 0, 1, -1], [+0, 0, 0, 0], [-1, 1, 0, -0], [+1, 1, 1, 1]]
converted_meas = self.expect.convert(~StateFn(paulis_op))
np.testing.assert_array_almost_equal((converted_meas @ states_op).eval(), valids, decimal=1)
with self.assertWarns(DeprecationWarning):
sampled = self.sampler.convert(states_op)
np.testing.assert_array_almost_equal((converted_meas @ sampled).eval(), valids, decimal=1)
def test_multi_representation_ops(self):
"""Test observables with mixed representations"""
mixed_ops = ListOp([X.to_matrix_op(), H, H + I, X])
converted_meas = self.expect.convert(~StateFn(mixed_ops))
plus_mean = converted_meas @ Plus
with self.assertWarns(DeprecationWarning):
sampled_plus = self.sampler.convert(plus_mean)
np.testing.assert_array_almost_equal(
sampled_plus.eval(), [1, 0.5**0.5, (1 + 0.5**0.5), 1], decimal=1
)
def test_matrix_expectation_non_hermite_op(self):
"""Test MatrixExpectation for non hermitian operator"""
exp = ~StateFn(1j * Z) @ One
self.assertEqual(self.expect.convert(exp).eval(), 1j)
if __name__ == "__main__":
unittest.main()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
#General imports
import numpy as np
#Operator Imports
from qiskit.opflow import Z, X, I, StateFn, CircuitStateFn, SummedOp
from qiskit.opflow.gradients import Gradient, NaturalGradient, QFI, Hessian
#Circuit imports
from qiskit.circuit import QuantumCircuit, QuantumRegister, Parameter, ParameterVector, ParameterExpression
from qiskit.circuit.library import EfficientSU2
# Instantiate the quantum state
a = Parameter('a')
b = Parameter('b')
q = QuantumRegister(1)
qc = QuantumCircuit(q)
qc.h(q)
qc.rz(a, q[0])
qc.rx(b, q[0])
# Instantiate the Hamiltonian observable
H = (2 * X) + Z
# Combine the Hamiltonian observable and the state
op = ~StateFn(H) @ CircuitStateFn(primitive=qc, coeff=1.)
# Print the operator corresponding to the expectation value
print(op)
params = [a, b]
# Define the values to be assigned to the parameters
value_dict = {a: np.pi / 4, b: np.pi}
# Convert the operator and the gradient target params into the respective operator
grad = Gradient().convert(operator = op, params = params)
# Print the operator corresponding to the Gradient
print(grad)
# Assign the parameters and evaluate the gradient
grad_result = grad.assign_parameters(value_dict).eval()
print('Gradient', grad_result)
# Define the Hamiltonian with fixed coefficients
H = 0.5 * X - 1 * Z
# Define the parameters w.r.t. we want to compute the gradients
params = [a, b]
# Define the values to be assigned to the parameters
value_dict = { a: np.pi / 4, b: np.pi}
# Combine the Hamiltonian observable and the state into an expectation value operator
op = ~StateFn(H) @ CircuitStateFn(primitive=qc, coeff=1.)
print(op)
# Convert the expectation value into an operator corresponding to the gradient w.r.t. the state parameters using
# the parameter shift method.
state_grad = Gradient(grad_method='param_shift').convert(operator=op, params=params)
# Print the operator corresponding to the gradient
print(state_grad)
# Assign the parameters and evaluate the gradient
state_grad_result = state_grad.assign_parameters(value_dict).eval()
print('State gradient computed with parameter shift', state_grad_result)
# Convert the expectation value into an operator corresponding to the gradient w.r.t. the state parameter using
# the linear combination of unitaries method.
state_grad = Gradient(grad_method='lin_comb').convert(operator=op, params=params)
# Print the operator corresponding to the gradient
print(state_grad)
# Assign the parameters and evaluate the gradient
state_grad_result = state_grad.assign_parameters(value_dict).eval()
print('State gradient computed with the linear combination method', state_grad_result)
# Convert the expectation value into an operator corresponding to the gradient w.r.t. the state parameter using
# the finite difference method.
state_grad = Gradient(grad_method='fin_diff').convert(operator=op, params=params)
# Print the operator corresponding to the gradient
print(state_grad)
# Assign the parameters and evaluate the gradient
state_grad_result = state_grad.assign_parameters(value_dict).eval()
print('State gradient computed with finite difference', state_grad_result)
# Besides the method to compute the circuit gradients resp. QFI, a regularization method can be chosen:
# `ridge` or `lasso` with automatic parameter search or `perturb_diag_elements` or `perturb_diag`
# which perturb the diagonal elements of the QFI.
nat_grad = NaturalGradient(grad_method='lin_comb', qfi_method='lin_comb_full', regularization='ridge').convert(
operator=op, params=params)
# Assign the parameters and evaluate the gradient
nat_grad_result = nat_grad.assign_parameters(value_dict).eval()
print('Natural gradient computed with linear combination of unitaries', nat_grad_result)
# Instantiate the Hamiltonian observable
H = X
# Instantiate the quantum state with two parameters
a = Parameter('a')
b = Parameter('b')
q = QuantumRegister(1)
qc = QuantumCircuit(q)
qc.h(q)
qc.rz(a, q[0])
qc.rx(b, q[0])
# Combine the Hamiltonian observable and the state
op = ~StateFn(H) @ CircuitStateFn(primitive=qc, coeff=1.)
# Convert the operator and the hessian target coefficients into the respective operator
hessian = Hessian().convert(operator = op, params = [a, b])
# Define the values to be assigned to the parameters
value_dict = {a: np.pi / 4, b: np.pi/4}
# Assign the parameters and evaluate the Hessian w.r.t. the Hamiltonian coefficients
hessian_result = hessian.assign_parameters(value_dict).eval()
print('Hessian \n', np.real(np.array(hessian_result)))
# Define parameters
params = [a, b]
# Get the operator object representing the Hessian
state_hess = Hessian(hess_method='param_shift').convert(operator=op, params=params)
# Assign the parameters and evaluate the Hessian
hessian_result = state_hess.assign_parameters(value_dict).eval()
print('Hessian computed using the parameter shift method\n', (np.array(hessian_result)))
# Get the operator object representing the Hessian
state_hess = Hessian(hess_method='lin_comb').convert(operator=op, params=params)
# Assign the parameters and evaluate the Hessian
hessian_result = state_hess.assign_parameters(value_dict).eval()
print('Hessian computed using the linear combination of unitaries method\n', (np.array(hessian_result)))
# Get the operator object representing the Hessian using finite difference
state_hess = Hessian(hess_method='fin_diff').convert(operator=op, params=params)
# Assign the parameters and evaluate the Hessian
hessian_result = state_hess.assign_parameters(value_dict).eval()
print('Hessian computed with finite difference\n', (np.array(hessian_result)))
# Wrap the quantum circuit into a CircuitStateFn
state = CircuitStateFn(primitive=qc, coeff=1.)
# Convert the state and the parameters into the operator object that represents the QFI
qfi = QFI(qfi_method='lin_comb_full').convert(operator=state, params=params)
# Define the values for which the QFI is to be computed
values_dict = {a: np.pi / 4, b: 0.1}
# Assign the parameters and evaluate the QFI
qfi_result = qfi.assign_parameters(values_dict).eval()
print('full QFI \n', np.real(np.array(qfi_result)))
# Convert the state and the parameters into the operator object that represents the QFI
# and set the approximation to 'block_diagonal'
qfi = QFI('overlap_block_diag').convert(operator=state, params=params)
# Assign the parameters and evaluate the QFI
qfi_result = qfi.assign_parameters(values_dict).eval()
print('Block-diagonal QFI \n', np.real(np.array(qfi_result)))
# Convert the state and the parameters into the operator object that represents the QFI
# and set the approximation to 'diagonal'
qfi = QFI('overlap_diag').convert(operator=state, params=params)
# Assign the parameters and evaluate the QFI
qfi_result = qfi.assign_parameters(values_dict).eval()
print('Diagonal QFI \n', np.real(np.array(qfi_result)))
# Execution Imports
from qiskit import Aer
from qiskit.utils import QuantumInstance
# Algorithm Imports
from qiskit.algorithms import VQE
from qiskit.algorithms.optimizers import CG
from qiskit.opflow import I, X, Z
from qiskit.circuit import QuantumCircuit, ParameterVector
from scipy.optimize import minimize
# Instantiate the system Hamiltonian
h2_hamiltonian = -1.05 * (I ^ I) + 0.39 * (I ^ Z) - 0.39 * (Z ^ I) - 0.01 * (Z ^ Z) + 0.18 * (X ^ X)
# This is the target energy
h2_energy = -1.85727503
# Define the Ansatz
wavefunction = QuantumCircuit(2)
params = ParameterVector('theta', length=8)
it = iter(params)
wavefunction.ry(next(it), 0)
wavefunction.ry(next(it), 1)
wavefunction.rz(next(it), 0)
wavefunction.rz(next(it), 1)
wavefunction.cx(0, 1)
wavefunction.ry(next(it), 0)
wavefunction.ry(next(it), 1)
wavefunction.rz(next(it), 0)
wavefunction.rz(next(it), 1)
# Define the expectation value corresponding to the energy
op = ~StateFn(h2_hamiltonian) @ StateFn(wavefunction)
grad = Gradient(grad_method='lin_comb')
qi_sv = QuantumInstance(Aer.get_backend('aer_simulator_statevector'),
shots=1,
seed_simulator=2,
seed_transpiler=2)
#Conjugate Gradient algorithm
optimizer = CG(maxiter=50)
# Gradient callable
vqe = VQE(wavefunction, optimizer=optimizer, gradient=grad, quantum_instance=qi_sv)
result = vqe.compute_minimum_eigenvalue(h2_hamiltonian)
print('Result:', result.optimal_value, 'Reference:', h2_energy)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/DEBARGHYA4469/quantum-compiler
|
DEBARGHYA4469
|
from qiskit import register, available_backends , get_backend
# Establish connection with IBMQuantum Experience
try :
import sys
sys.path.append('../')
import Qconfig
qx_config = { # configuration details
'APItoken' : Qconfig.APItoken ,
'url' : Qconfig.config['url']}
except Exception as e :
print(e)
print("Check your API token")
register(qx_config['APItoken'],qx_config['url'])
def lowest_pending_jobs(): # find the best backend available
list_backends = available_backends({'local':False,'simulator':False})
device_status = [get_backend(backend).status for backend in list_backends]
best = min([x for x in device_status if x['available'] is True],key = lambda x: x['pending_jobs'])
return best['name']
def get_qc():
backend = lowest_pending_jobs()
print("The best backend is",backend)
return backend
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import numpy as np
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 import RXGate, XGate, CXGate
XX = Operator([[0, 0, 0, 1], [0, 0, 1, 0], [0, 1, 0, 0], [1, 0, 0, 0]])
XX
XX.data
input_dim, output_dim = XX.dim
input_dim, output_dim
op = Operator(np.random.rand(2 ** 1, 2 ** 2))
print('Input dimensions:', op.input_dims())
print('Output dimensions:', op.output_dims())
op = Operator(np.random.rand(6, 6))
print('Input dimensions:', op.input_dims())
print('Output dimensions:', op.output_dims())
# Force input dimension to be (4,) rather than (2, 2)
op = Operator(np.random.rand(2 ** 1, 2 ** 2), input_dims=[4])
print('Input dimensions:', op.input_dims())
print('Output dimensions:', op.output_dims())
# Specify system is a qubit and qutrit
op = Operator(np.random.rand(6, 6),
input_dims=[2, 3], output_dims=[2, 3])
print('Input dimensions:', op.input_dims())
print('Output dimensions:', op.output_dims())
print('Dimension of input system 0:', op.input_dims([0]))
print('Dimension of input system 1:', op.input_dims([1]))
# Create an Operator from a Pauli object
pauliXX = Pauli('XX')
Operator(pauliXX)
# Create an Operator for a Gate object
Operator(CXGate())
# Create an operator from a parameterized Gate object
Operator(RXGate(np.pi / 2))
# Create an operator from a QuantumCircuit object
circ = QuantumCircuit(10)
circ.h(0)
for j in range(1, 10):
circ.cx(j-1, j)
# Convert circuit to an operator by implicit unitary simulation
Operator(circ)
# Create an operator
XX = Operator(Pauli('XX'))
# Add to a circuit
circ = QuantumCircuit(2, 2)
circ.append(XX, [0, 1])
circ.measure([0,1], [0,1])
circ.draw('mpl')
backend = BasicAer.get_backend('qasm_simulator')
circ = transpile(circ, backend, basis_gates=['u1','u2','u3','cx'])
job = backend.run(circ)
job.result().get_counts(0)
# Add to a circuit
circ2 = QuantumCircuit(2, 2)
circ2.append(Pauli('XX'), [0, 1])
circ2.measure([0,1], [0,1])
circ2.draw()
A = Operator(Pauli('X'))
B = Operator(Pauli('Z'))
A.tensor(B)
A = Operator(Pauli('X'))
B = Operator(Pauli('Z'))
A.expand(B)
A = Operator(Pauli('X'))
B = Operator(Pauli('Z'))
A.compose(B)
A = Operator(Pauli('X'))
B = Operator(Pauli('Z'))
A.compose(B, front=True)
# Compose XZ with an 3-qubit identity operator
op = Operator(np.eye(2 ** 3))
XZ = Operator(Pauli('XZ'))
op.compose(XZ, qargs=[0, 2])
# Compose YX in front of the previous operator
op = Operator(np.eye(2 ** 3))
YX = Operator(Pauli('YX'))
op.compose(XZ, qargs=[0, 2], front=True)
XX = Operator(Pauli('XX'))
YY = Operator(Pauli('YY'))
ZZ = Operator(Pauli('ZZ'))
op = 0.5 * (XX + YY - 3 * ZZ)
op
op.is_unitary()
# Compose with a matrix passed as a list
Operator(np.eye(2)).compose([[0, 1], [1, 0]])
Operator(Pauli('X')) == Operator(XGate())
Operator(XGate()) == np.exp(1j * 0.5) * Operator(XGate())
# Two operators which differ only by phase
op_a = Operator(XGate())
op_b = np.exp(1j * 0.5) * Operator(XGate())
# Compute process fidelity
F = process_fidelity(op_a, op_b)
print('Process fidelity =', F)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, transpile
from qiskit.visualization import plot_circuit_layout
from qiskit.providers.fake_provider import FakeVigo
backend = FakeVigo()
ghz = QuantumCircuit(3, 3)
ghz.h(0)
ghz.cx(0,range(1,3))
ghz.barrier()
ghz.measure(range(3), range(3))
new_circ_lv0 = transpile(ghz, backend=backend, optimization_level=0)
plot_circuit_layout(new_circ_lv0, backend)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.dagcircuit import DAGCircuit
from qiskit.converters import circuit_to_dag
from qiskit.circuit.library.standard_gates import CHGate, U2Gate, CXGate
from qiskit.converters import dag_to_circuit
q = QuantumRegister(3, 'q')
c = ClassicalRegister(3, 'c')
circ = QuantumCircuit(q, c)
circ.h(q[0])
circ.cx(q[0], q[1])
circ.measure(q[0], c[0])
circ.rz(0.5, q[1]).c_if(c, 2)
dag = circuit_to_dag(circ)
circuit = dag_to_circuit(dag)
circuit.draw('mpl')
|
https://github.com/SanNare/qiskit-notebooks
|
SanNare
|
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit.quantum_info import Statevector
from qiskit.visualization import plot_state_qsphere, plot_histogram
def bellstate(n): #returns a bell state depending on the input integer
if n not in [0,1,2,3]:
print('Enter 0,1,2 or 3 only. Value taken as n mod 4 = {}.'.format(n%4))
n = 0
n = bin(n)[2:].zfill(2)
cir = QuantumCircuit(2)
cir.h(0)
cir.cx(0,1)
sv = Statevector.from_label(n[::-1])
return sv.evolve(cir)
psi = bellstate(4)
%matplotlib inline
plot_state_qsphere(psi.data)
def bell(cir,i,j):
cir.h(i)
cir.cx(i,j)
def bell_measure(cir,i,j):
cir.cx(i,j)
cir.h(i)
q = QuantumRegister(6,'q')
c0 = ClassicalRegister(1,'c0')
c1 = ClassicalRegister(1,'c1')
c2 = ClassicalRegister(1,'c2')
c3 = ClassicalRegister(1,'c3')
c4 = ClassicalRegister(1,'c4')
c5 = ClassicalRegister(1,'c5')
circuit = QuantumCircuit(q,c0,c1,c2,c3,c4,c5)
#initialize states
bell(circuit,0,1)
circuit.barrier()
bell(circuit,2,4)
circuit.barrier()
bell(circuit,3,5)
circuit.barrier()
#teleport Alice's first qubit
bell_measure(circuit,0,2)
circuit.barrier()
circuit.measure([0,2],[0,1])
circuit.x(4).c_if(c1,1)
circuit.z(4).c_if(c0,1)
circuit.barrier()
#teleport Alice's second qubit
bell_measure(circuit,1,3)
circuit.barrier()
circuit.measure([1,3],[2,3])
circuit.x(5).c_if(c3,1)
circuit.z(5).c_if(c2,1)
circuit.barrier()
#measure Bob's qubits
circuit.measure([4,5],[4,5])
circuit.draw('mpl')
from qiskit import Aer, execute
from collections import defaultdict
simulator = Aer.get_backend('qasm_simulator')
result = execute(circuit, simulator, shots=10000).result()
counts = result.get_counts(circuit)
print(counts)
plot_histogram(counts)
# count = {s.replace(' ',''):counts[s] for s in counts.keys()}
# print(count)
count = defaultdict(int)
for k in counts.keys():
key = k[0:3]
count[key]+=counts[k]
print(count)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, QuantumRegister
from qiskit.circuit.library.standard_gates import HGate
qc1 = QuantumCircuit(2)
qc1.x(0)
qc1.h(1)
custom = qc1.to_gate().control(2)
qc2 = QuantumCircuit(4)
qc2.append(custom, [0, 3, 1, 2])
qc2.draw('mpl')
|
https://github.com/DRA-chaos/Quantum-Classical-Hyrid-Neural-Network-for-binary-image-classification-using-PyTorch-Qiskit-pipeline
|
DRA-chaos
|
!pip install qiskit
# check if CUDA is available
import torch
train_on_gpu = torch.cuda.is_available()
if not train_on_gpu:
print('CUDA is not available. Training on CPU ...')
else:
print('CUDA is available! Training on GPU ...')
import numpy as np
import matplotlib.pyplot as plt
import torch
from torch.autograd import Function
from torchvision import datasets, transforms
import torch.optim as optim
import torch.nn as nn
import torch.nn.functional as F
import qiskit
from qiskit import transpile, assemble
from qiskit.visualization import *
import numpy as np
import torch
from torch.autograd import Function
import torch.optim as optim
import torch.nn as nn
import torch.nn.functional as F
import torchvision
from torchvision import datasets, transforms
from qiskit import QuantumRegister, QuantumCircuit, ClassicalRegister, execute
from qiskit.circuit import Parameter
from qiskit import Aer
from tqdm import tqdm
from matplotlib import pyplot as plt
%matplotlib inline
def to_numbers(tensor_list):
num_list = []
for tensor in tensor_list:
num_list += [tensor.item()]
return num_list
class QuantumCircuit:
"""
This class provides a simple interface for interaction
with the quantum circuit
"""
def __init__(self, n_qubits, backend, shots):
# --- Circuit definition ---
self._circuit = qiskit.QuantumCircuit(n_qubits)
all_qubits = [i for i in range(n_qubits)]
self.theta = qiskit.circuit.Parameter('theta')
self._circuit.h(all_qubits)
self._circuit.barrier()
self._circuit.ry(self.theta, all_qubits)
self._circuit.measure_all()
# ---------------------------
self.backend = backend
self.shots = shots
def run(self, thetas):
t_qc = transpile(self._circuit,
self.backend)
qobj = assemble(t_qc,
shots=self.shots,
parameter_binds = [{self.theta: theta} for theta in thetas])
job = self.backend.run(qobj)
result = job.result().get_counts()
counts = np.array(list(result.values()))
states = np.array(list(result.keys())).astype(float)
# Compute probabilities for each state
probabilities = counts / self.shots
# Get state expectation
expectation = np.sum(states * probabilities)
return np.array([expectation])
class HybridFunction(Function):
""" Hybrid quantum - classical function definition """
@staticmethod
def forward(ctx, input, quantum_circuit, shift):
""" Forward pass computation """
ctx.shift = shift
ctx.quantum_circuit = quantum_circuit
expectation_z = ctx.quantum_circuit.run(input[0].tolist())
result = torch.tensor([expectation_z])
ctx.save_for_backward(input, result)
return result
@staticmethod
def backward(ctx, grad_output):
""" Backward pass computation """
input, expectation_z = ctx.saved_tensors
input_list = np.array(input.tolist())
shift_right = input_list + np.ones(input_list.shape) * ctx.shift
shift_left = input_list - np.ones(input_list.shape) * ctx.shift
gradients = []
for i in range(len(input_list)):
expectation_right = ctx.quantum_circuit.run(shift_right[i])
expectation_left = ctx.quantum_circuit.run(shift_left[i])
gradient = torch.tensor([expectation_right]) - torch.tensor([expectation_left])
gradients.append(gradient)
gradients = np.array([gradients]).T
return torch.tensor([gradients]).float() * grad_output.float(), None, None
class Hybrid(nn.Module):
""" Hybrid quantum - classical layer definition """
def __init__(self, backend, shots, shift):
super(Hybrid, self).__init__()
self.quantum_circuit = QuantumCircuit(1, backend, shots)
self.shift = shift
def forward(self, input):
return HybridFunction.apply(input, self.quantum_circuit, self.shift)
import torchvision
transform = torchvision.transforms.Compose([torchvision.transforms.ToTensor()]) # transform images to tensors/vectors
cifar_trainset = datasets.CIFAR10(root='./data1', train=True, download=True, transform=transform)
len(cifar_trainset)
from torch.utils.data import DataLoader, random_split
#cifar_trainset = datasets.CIFAR10(root='./data1', train=True, download=True, transform=transform)
labels = cifar_trainset.targets # get the labels for the data
labels = np.array(labels)
idx1 = np.where(labels == 0) # filter on aeroplanes
idx2 = np.where(labels == 1) # filter on automobiles
# Specify number of datapoints per class (i.e. there will be n pictures of automobiles and n pictures of aeroplanes in the training set)
n=100
# concatenate the data indices
idx = np.concatenate((idx1[0][0:n],idx2[0][0:n]))
# create the filtered dataset for our training set
cifar_trainset.targets = labels[idx]
cifar_trainset.data = cifar_trainset.data[idx]
cifar_trainset, valid = random_split(cifar_trainset,[150,50])
train_loader = torch.utils.data.DataLoader(cifar_trainset, batch_size=1, shuffle=True)
valid_loader = torch.utils.data.DataLoader(valid, batch_size=1, shuffle=True)
@torch.no_grad()
def get_all_preds(model, train_loader):
all_preds = torch.tensor([])
for batch in train_loader:
images, labels = batch
preds = model(images)
all_preds = torch.cat(
(all_preds, preds)
,dim=0
)
return all_preds
import numpy as np
import matplotlib.pyplot as plt
n_samples_show = 6
data_iter = iter(train_loader)
fig, axes = plt.subplots(nrows=1, ncols=n_samples_show, figsize=(10, 2))
while n_samples_show > 0:
images, targets = data_iter.__next__()
images=images.squeeze()
axes[n_samples_show - 1].imshow(images[0].numpy(), cmap='gray')
axes[n_samples_show - 1].set_xticks([])
axes[n_samples_show - 1].set_yticks([])
axes[n_samples_show - 1].set_title("Labeled: {}".format(targets.item()))
n_samples_show -= 1
import torchvision
transform = torchvision.transforms.Compose([torchvision.transforms.ToTensor()]) # transform images to tensors/vectors
cifar_testset = datasets.CIFAR10(root='./data1', train=False, download=True, transform=transform)
labels = cifar_testset.targets # get the labels for the data
labels = np.array(labels)
idx1 = np.where(labels == 0) # filter on aeroplanes
idx2 = np.where(labels == 1) # filter on automobiles
# Specify number of datapoints per class (i.e. there will be n pictures of automobiles and n pictures of aeroplanes in the training set)
n=100
# concatenate the data indices
idx = np.concatenate((idx1[0][0:n],idx2[0][0:n]))
# create the filtered dataset for our training set
cifar_testset.targets = labels[idx]
cifar_testset.data = cifar_testset.data[idx]
test_loader = torch.utils.data.DataLoader(cifar_testset, batch_size=1, shuffle=False)
len(cifar_testset)
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(3, 10, kernel_size=5)
self.conv2 = nn.Conv2d(10, 20, kernel_size=5)
self.dropout = nn.Dropout2d()
self.fc1 = nn.Linear(500, 500)
self.fc2 = nn.Linear(500, 1)
self.hybrid = Hybrid(qiskit.Aer.get_backend('qasm_simulator'), 100, np.pi / 2)
def forward(self, x):
x = F.relu(self.conv1(x))
x = F.max_pool2d(x, 2)
x = F.relu(self.conv2(x))
x = F.max_pool2d(x, 2)
x = self.dropout(x)
x = x.view(1, -1)
x = F.relu(self.fc1(x))
x = self.fc2(x)
x = self.hybrid(x)
return torch.cat((x, 1 - x), -1)
%matplotlib inline
import matplotlib.pyplot as plt
model = Net()
optimizer = optim.Adam(model.parameters(), lr=0.001)
loss_func = nn.NLLLoss()
epochs = 5
loss_list = []
loss_list_V = []
#training the model
model.train()
for epoch in range(epochs):
train_loss = []
for batch_idx, (data, target) in enumerate(train_loader):
optimizer.zero_grad()
# Forward pass
output = model(data)
# Calculating loss
loss = loss_func(output, target)
# Backward pass
loss.backward()
# Optimize the weights
optimizer.step()
train_loss.append(loss.item())
loss_list.append(sum(train_loss)/len(train_loss))
#print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list[-1]))
#Validate the model
model.eval()
for epoch in range(epochs):
valid_loss = []
for batch_idx, (data, target) in enumerate(valid_loader):
optimizer.zero_grad()
# Forward pass
output = model(data)
# Calculating loss
validation_loss = loss_func(output, target)
# Backward pass
validation_loss.backward()
# Optimize the weights
optimizer.step()
valid_loss.append(validation_loss.item())
loss_list_V.append(sum(valid_loss)/len(valid_loss))
#print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list_V[-1]))
print('Epoch: {} \tTraining Loss: {:.6f} \tValidation Loss: {:.6f}'.format(
epoch, loss_list[-1], loss_list_V[-1]))
#Now plotting the training graph
plt.plot(loss_list,label='Training Loss')
plt.plot(loss_list_V,label='Validation Loss')
plt.legend()
plt.show()
total_loss=[]
model.eval()
with torch.no_grad():
correct = 0
for batch_idx, (data, target) in enumerate(test_loader):
output = model(data)
pred = output.argmax(dim=1, keepdim=True)
correct += pred.eq(target.view_as(pred)).sum().item()
loss = loss_func(output, target)
total_loss.append(loss.item())
print('Performance on train data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format(
sum(total_loss) / len(total_loss),
correct / len(test_loader) * 100)
)
model = Net()
optimizer = optim.Adam(model.parameters(), lr=0.0005)
loss_func = nn.NLLLoss()
epochs = 5
loss_list = []
loss_list_V = []
#training the model
model.train()
for epoch in range(epochs):
train_loss = []
for batch_idx, (data, target) in enumerate(train_loader):
optimizer.zero_grad()
# Forward pass
output = model(data)
# Calculating loss
loss = loss_func(output, target)
# Backward pass
loss.backward()
# Optimize the weights
optimizer.step()
train_loss.append(loss.item())
loss_list.append(sum(train_loss)/len(train_loss))
#print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list[-1]))
#Validate the model
model.eval()
for epoch in range(epochs):
valid_loss = []
for batch_idx, (data, target) in enumerate(valid_loader):
optimizer.zero_grad()
# Forward pass
output = model(data)
# Calculating loss
validation_loss = loss_func(output, target)
# Backward pass
validation_loss.backward()
# Optimize the weights
optimizer.step()
valid_loss.append(validation_loss.item())
loss_list_V.append(sum(valid_loss)/len(valid_loss))
#print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list_V[-1]))
print('Epoch: {} \tTraining Loss: {:.6f} \tValidation Loss: {:.6f}'.format(
epoch, loss_list[-1], loss_list_V[-1]))
#Now plotting the training graph
plt.plot(loss_list,label='Training Loss')
plt.plot(loss_list_V,label='Validation Loss')
plt.legend()
plt.show()
total_loss=[]
model.eval()
with torch.no_grad():
correct = 0
for batch_idx, (data, target) in enumerate(test_loader):
output = model(data)
pred = output.argmax(dim=1, keepdim=True)
correct += pred.eq(target.view_as(pred)).sum().item()
loss = loss_func(output, target)
total_loss.append(loss.item())
print('Performance on train data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format(
sum(total_loss) / len(total_loss),
correct / len(test_loader) * 100)
)
n_samples_show = 6
count = 0
fig, axes = plt.subplots(nrows=1, ncols=n_samples_show, figsize=(10, 3))
model.eval()
with torch.no_grad():
for batch_idx, (data, target) in enumerate(test_loader):
if count == n_samples_show:
break
output = model(data)
pred = output.argmax(dim=1, keepdim=True)
data=data.squeeze()
axes[count].imshow(data[0].numpy().squeeze(), cmap='gray')
axes[count].set_xticks([])
axes[count].set_yticks([])
axes[count].set_title('Predicted {}'.format(pred.item()))
count += 1
model = Net()
optimizer = optim.SGD(model.parameters(), lr=0.001)
loss_func = nn.NLLLoss()
epochs = 10
loss_list = []
loss_list_V = []
#training the model
model.train()
for epoch in range(epochs):
train_loss = []
for batch_idx, (data, target) in enumerate(train_loader):
optimizer.zero_grad()
# Forward pass
output = model(data)
# Calculating loss
loss = loss_func(output, target)
# Backward pass
loss.backward()
# Optimize the weights
optimizer.step()
train_loss.append(loss.item())
loss_list.append(sum(train_loss)/len(train_loss))
#print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list[-1]))
#Validate the model
model.eval()
for epoch in range(epochs):
valid_loss = []
for batch_idx, (data, target) in enumerate(valid_loader):
optimizer.zero_grad()
# Forward pass
output = model(data)
# Calculating loss
validation_loss = loss_func(output, target)
# Backward pass
validation_loss.backward()
# Optimize the weights
optimizer.step()
valid_loss.append(validation_loss.item())
loss_list_V.append(sum(valid_loss)/len(valid_loss))
#print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list_V[-1]))
print('Epoch: {} \tTraining Loss: {:.6f} \tValidation Loss: {:.6f}'.format(
epoch, loss_list[-1], loss_list_V[-1]))
#Now plotting the training graph
plt.plot(loss_list,label='Training Loss')
plt.plot(loss_list_V,label='Validation Loss')
plt.legend()
plt.show()
total_loss=[]
model.eval()
with torch.no_grad():
correct = 0
for batch_idx, (data, target) in enumerate(test_loader):
output = model(data)
pred = output.argmax(dim=1, keepdim=True)
correct += pred.eq(target.view_as(pred)).sum().item()
loss = loss_func(output, target)
total_loss.append(loss.item())
print('Performance on train data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format(
sum(total_loss) / len(total_loss),
correct / len(test_loader) * 100)
)
model = Net()
optimizer = optim.Adam(model.parameters(), lr=0.001)
loss_func = nn.NLLLoss()
epochs = 15
loss_list = []
loss_list_V = []
#training the model
model.train()
for epoch in range(epochs):
train_loss = []
for batch_idx, (data, target) in enumerate(train_loader):
optimizer.zero_grad()
# Forward pass
output = model(data)
# Calculating loss
loss = loss_func(output, target)
# Backward pass
loss.backward()
# Optimize the weights
optimizer.step()
train_loss.append(loss.item())
loss_list.append(sum(train_loss)/len(train_loss))
#print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list[-1]))
#Validate the model
model.eval()
for epoch in range(epochs):
valid_loss = []
for batch_idx, (data, target) in enumerate(valid_loader):
optimizer.zero_grad()
# Forward pass
output = model(data)
# Calculating loss
validation_loss = loss_func(output, target)
# Backward pass
validation_loss.backward()
# Optimize the weights
optimizer.step()
valid_loss.append(validation_loss.item())
loss_list_V.append(sum(valid_loss)/len(valid_loss))
#print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list_V[-1]))
print('Epoch: {} \tTraining Loss: {:.6f} \tValidation Loss: {:.6f}'.format(
epoch, loss_list[-1], loss_list_V[-1]))
#Now plotting the training graph
plt.plot(loss_list,label='Training Loss')
plt.plot(loss_list_V,label='Validation Loss')
plt.legend()
plt.show()
total_loss=[]
model.eval()
with torch.no_grad():
correct = 0
for batch_idx, (data, target) in enumerate(test_loader):
output = model(data)
pred = output.argmax(dim=1, keepdim=True)
correct += pred.eq(target.view_as(pred)).sum().item()
loss = loss_func(output, target)
total_loss.append(loss.item())
print('Performance on train data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format(
sum(total_loss) / len(total_loss),
correct / len(test_loader) * 100)
)
model = Net()
optimizer = optim.Adam(model.parameters(), lr=0.01)
loss_func = nn.NLLLoss()
epochs = 15
loss_list = []
loss_list_V = []
#training the model
model.train()
for epoch in range(epochs):
train_loss = []
for batch_idx, (data, target) in enumerate(train_loader):
optimizer.zero_grad()
# Forward pass
output = model(data)
# Calculating loss
loss = loss_func(output, target)
# Backward pass
loss.backward()
# Optimize the weights
optimizer.step()
train_loss.append(loss.item())
loss_list.append(sum(train_loss)/len(train_loss))
#print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list[-1]))
#Validate the model
model.eval()
for epoch in range(epochs):
valid_loss = []
for batch_idx, (data, target) in enumerate(valid_loader):
optimizer.zero_grad()
# Forward pass
output = model(data)
# Calculating loss
validation_loss = loss_func(output, target)
# Backward pass
validation_loss.backward()
# Optimize the weights
optimizer.step()
valid_loss.append(validation_loss.item())
loss_list_V.append(sum(valid_loss)/len(valid_loss))
#print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list_V[-1]))
print('Epoch: {} \tTraining Loss: {:.6f} \tValidation Loss: {:.6f}'.format(
epoch, loss_list[-1], loss_list_V[-1]))
#Now plotting the training graph
plt.plot(loss_list,label='Training Loss')
plt.plot(loss_list_V,label='Validation Loss')
plt.legend()
plt.show()
total_loss=[]
model.eval()
with torch.no_grad():
correct = 0
for batch_idx, (data, target) in enumerate(test_loader):
output = model(data)
pred = output.argmax(dim=1, keepdim=True)
correct += pred.eq(target.view_as(pred)).sum().item()
loss = loss_func(output, target)
total_loss.append(loss.item())
print('Performance on train data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format(
sum(total_loss) / len(total_loss),
correct / len(test_loader) * 100)
)
model = Net()
optimizer = optim.Adam(model.parameters(), lr=0.0005)
loss_func = nn.NLLLoss()
epochs = 15
loss_list = []
loss_list_V = []
#training the model
model.train()
for epoch in range(epochs):
train_loss = []
for batch_idx, (data, target) in enumerate(train_loader):
optimizer.zero_grad()
# Forward pass
output = model(data)
# Calculating loss
loss = loss_func(output, target)
# Backward pass
loss.backward()
# Optimize the weights
optimizer.step()
train_loss.append(loss.item())
loss_list.append(sum(train_loss)/len(train_loss))
#print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list[-1]))
#Validate the model
model.eval()
for epoch in range(epochs):
valid_loss = []
for batch_idx, (data, target) in enumerate(valid_loader):
optimizer.zero_grad()
# Forward pass
output = model(data)
# Calculating loss
validation_loss = loss_func(output, target)
# Backward pass
validation_loss.backward()
# Optimize the weights
optimizer.step()
valid_loss.append(validation_loss.item())
loss_list_V.append(sum(valid_loss)/len(valid_loss))
#print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list_V[-1]))
print('Epoch: {} \tTraining Loss: {:.6f} \tValidation Loss: {:.6f}'.format(
epoch, loss_list[-1], loss_list_V[-1]))
#Now plotting the training graph
plt.plot(loss_list,label='Training Loss')
plt.plot(loss_list_V,label='Validation Loss')
plt.legend()
plt.show()
total_loss=[]
model.eval()
with torch.no_grad():
correct = 0
for batch_idx, (data, target) in enumerate(test_loader):
output = model(data)
pred = output.argmax(dim=1, keepdim=True)
correct += pred.eq(target.view_as(pred)).sum().item()
loss = loss_func(output, target)
total_loss.append(loss.item())
print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format(
sum(total_loss) / len(total_loss),
correct / len(test_loader) * 100)
)
model = Net()
optimizer = optim.Adam(model.parameters(), lr=0.0005)
loss_func = nn.NLLLoss()
epochs = 10
loss_list = []
loss_list_V = []
#training the model
model.train()
for epoch in range(epochs):
train_loss = []
for batch_idx, (data, target) in enumerate(train_loader):
optimizer.zero_grad()
# Forward pass
output = model(data)
# Calculating loss
loss = loss_func(output, target)
# Backward pass
loss.backward()
# Optimize the weights
optimizer.step()
train_loss.append(loss.item())
loss_list.append(sum(train_loss)/len(train_loss))
#print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list[-1]))
#Validate the model
model.eval()
for epoch in range(epochs):
valid_loss = []
for batch_idx, (data, target) in enumerate(valid_loader):
optimizer.zero_grad()
# Forward pass
output = model(data)
# Calculating loss
validation_loss = loss_func(output, target)
# Backward pass
validation_loss.backward()
# Optimize the weights
optimizer.step()
valid_loss.append(validation_loss.item())
loss_list_V.append(sum(valid_loss)/len(valid_loss))
#print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list_V[-1]))
print('Epoch: {} \tTraining Loss: {:.6f} \tValidation Loss: {:.6f}'.format(
epoch, loss_list[-1], loss_list_V[-1]))
#Now plotting the training graph
plt.plot(loss_list,label='Training Loss')
plt.plot(loss_list_V,label='Validation Loss')
plt.legend()
plt.show()
total_loss=[]
model.eval()
with torch.no_grad():
correct = 0
for batch_idx, (data, target) in enumerate(test_loader):
output = model(data)
pred = output.argmax(dim=1, keepdim=True)
correct += pred.eq(target.view_as(pred)).sum().item()
loss = loss_func(output, target)
total_loss.append(loss.item())
print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format(
sum(total_loss) / len(total_loss),
correct / len(test_loader) * 100)
)
model = Net()
optimizer = optim.Adam(model.parameters(), lr=0.0005)
loss_func = nn.NLLLoss()
epochs = 3
loss_list = []
loss_list_V = []
#training the model
model.train()
for epoch in range(epochs):
train_loss = []
for batch_idx, (data, target) in enumerate(train_loader):
optimizer.zero_grad()
# Forward pass
output = model(data)
# Calculating loss
loss = loss_func(output, target)
# Backward pass
loss.backward()
# Optimize the weights
optimizer.step()
train_loss.append(loss.item())
loss_list.append(sum(train_loss)/len(train_loss))
#print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list[-1]))
#Validate the model
model.eval()
for epoch in range(epochs):
valid_loss = []
for batch_idx, (data, target) in enumerate(valid_loader):
optimizer.zero_grad()
# Forward pass
output = model(data)
# Calculating loss
validation_loss = loss_func(output, target)
# Backward pass
validation_loss.backward()
# Optimize the weights
optimizer.step()
valid_loss.append(validation_loss.item())
loss_list_V.append(sum(valid_loss)/len(valid_loss))
#print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list_V[-1]))
print('Epoch: {} \tTraining Loss: {:.6f} \tValidation Loss: {:.6f}'.format(
epoch, loss_list[-1], loss_list_V[-1]))
#Now plotting the training graph
plt.plot(loss_list,label='Training Loss')
plt.plot(loss_list_V,label='Validation Loss')
plt.legend()
plt.show()
total_loss=[]
model.eval()
with torch.no_grad():
correct = 0
for batch_idx, (data, target) in enumerate(test_loader):
output = model(data)
pred = output.argmax(dim=1, keepdim=True)
correct += pred.eq(target.view_as(pred)).sum().item()
loss = loss_func(output, target)
total_loss.append(loss.item())
print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format(
sum(total_loss) / len(total_loss),
correct / len(test_loader) * 100)
)
model = Net()
optimizer = optim.Adam(model.parameters(), lr=0.0005)
loss_func = nn.NLLLoss()
epochs = 7
loss_list = []
loss_list_V = []
#training the model
model.train()
for epoch in range(epochs):
train_loss = []
for batch_idx, (data, target) in enumerate(train_loader):
optimizer.zero_grad()
# Forward pass
output = model(data)
# Calculating loss
loss = loss_func(output, target)
# Backward pass
loss.backward()
# Optimize the weights
optimizer.step()
train_loss.append(loss.item())
loss_list.append(sum(train_loss)/len(train_loss))
#print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list[-1]))
#Validate the model
model.eval()
for epoch in range(epochs):
valid_loss = []
for batch_idx, (data, target) in enumerate(valid_loader):
optimizer.zero_grad()
# Forward pass
output = model(data)
# Calculating loss
validation_loss = loss_func(output, target)
# Backward pass
validation_loss.backward()
# Optimize the weights
optimizer.step()
valid_loss.append(validation_loss.item())
loss_list_V.append(sum(valid_loss)/len(valid_loss))
#print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list_V[-1]))
print('Epoch: {} \tTraining Loss: {:.6f} \tValidation Loss: {:.6f}'.format(
epoch, loss_list[-1], loss_list_V[-1]))
#Now plotting the training graph
plt.plot(loss_list,label='Training Loss')
plt.plot(loss_list_V,label='Validation Loss')
plt.legend()
plt.show()
total_loss=[]
model.eval()
with torch.no_grad():
correct = 0
for batch_idx, (data, target) in enumerate(test_loader):
output = model(data)
pred = output.argmax(dim=1, keepdim=True)
correct += pred.eq(target.view_as(pred)).sum().item()
loss = loss_func(output, target)
total_loss.append(loss.item())
print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format(
sum(total_loss) / len(total_loss),
correct / len(test_loader) * 100)
)
model = Net()
optimizer = optim.Adam(model.parameters(), lr=0.0008)
loss_func = nn.NLLLoss()
epochs = 10
loss_list = []
loss_list_V = []
#training the model
model.train()
for epoch in range(epochs):
train_loss = []
for batch_idx, (data, target) in enumerate(train_loader):
optimizer.zero_grad()
# Forward pass
output = model(data)
# Calculating loss
loss = loss_func(output, target)
# Backward pass
loss.backward()
# Optimize the weights
optimizer.step()
train_loss.append(loss.item())
loss_list.append(sum(train_loss)/len(train_loss))
#print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list[-1]))
#Validate the model
model.eval()
for epoch in range(epochs):
valid_loss = []
for batch_idx, (data, target) in enumerate(valid_loader):
optimizer.zero_grad()
# Forward pass
output = model(data)
# Calculating loss
validation_loss = loss_func(output, target)
# Backward pass
validation_loss.backward()
# Optimize the weights
optimizer.step()
valid_loss.append(validation_loss.item())
loss_list_V.append(sum(valid_loss)/len(valid_loss))
#print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list_V[-1]))
print('Epoch: {} \tTraining Loss: {:.6f} \tValidation Loss: {:.6f}'.format(
epoch, loss_list[-1], loss_list_V[-1]))
#Now plotting the training graph
plt.plot(loss_list,label='Training Loss')
plt.plot(loss_list_V,label='Validation Loss')
plt.legend()
plt.show()
total_loss=[]
model.eval()
with torch.no_grad():
correct = 0
for batch_idx, (data, target) in enumerate(test_loader):
output = model(data)
pred = output.argmax(dim=1, keepdim=True)
correct += pred.eq(target.view_as(pred)).sum().item()
loss = loss_func(output, target)
total_loss.append(loss.item())
print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format(
sum(total_loss) / len(total_loss),
correct / len(test_loader) * 100)
)
model = Net()
optimizer = optim.Adam(model.parameters(), lr=0.0008)
loss_func = nn.NLLLoss()
epochs = 15
loss_list = []
loss_list_V = []
#training the model
model.train()
for epoch in range(epochs):
train_loss = []
for batch_idx, (data, target) in enumerate(train_loader):
optimizer.zero_grad()
# Forward pass
output = model(data)
# Calculating loss
loss = loss_func(output, target)
# Backward pass
loss.backward()
# Optimize the weights
optimizer.step()
train_loss.append(loss.item())
loss_list.append(sum(train_loss)/len(train_loss))
#print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list[-1]))
#Validate the model
model.eval()
for epoch in range(epochs):
valid_loss = []
for batch_idx, (data, target) in enumerate(valid_loader):
optimizer.zero_grad()
# Forward pass
output = model(data)
# Calculating loss
validation_loss = loss_func(output, target)
# Backward pass
validation_loss.backward()
# Optimize the weights
optimizer.step()
valid_loss.append(validation_loss.item())
loss_list_V.append(sum(valid_loss)/len(valid_loss))
#print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list_V[-1]))
print('Epoch: {} \tTraining Loss: {:.6f} \tValidation Loss: {:.6f}'.format(
epoch, loss_list[-1], loss_list_V[-1]))
#Now plotting the training graph
plt.plot(loss_list,label='Training Loss')
plt.plot(loss_list_V,label='Validation Loss')
plt.legend()
plt.show()
total_loss=[]
model.eval()
with torch.no_grad():
correct = 0
for batch_idx, (data, target) in enumerate(test_loader):
output = model(data)
pred = output.argmax(dim=1, keepdim=True)
correct += pred.eq(target.view_as(pred)).sum().item()
loss = loss_func(output, target)
total_loss.append(loss.item())
print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format(
sum(total_loss) / len(total_loss),
correct / len(test_loader) * 100)
)
model = Net()
optimizer = optim.Adam(model.parameters(), lr=0.0008)
loss_func = nn.NLLLoss()
epochs = 5
loss_list = []
loss_list_V = []
#training the model
model.train()
for epoch in range(epochs):
train_loss = []
for batch_idx, (data, target) in enumerate(train_loader):
optimizer.zero_grad()
# Forward pass
output = model(data)
# Calculating loss
loss = loss_func(output, target)
# Backward pass
loss.backward()
# Optimize the weights
optimizer.step()
train_loss.append(loss.item())
loss_list.append(sum(train_loss)/len(train_loss))
#print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list[-1]))
#Validate the model
model.eval()
for epoch in range(epochs):
valid_loss = []
for batch_idx, (data, target) in enumerate(valid_loader):
optimizer.zero_grad()
# Forward pass
output = model(data)
# Calculating loss
validation_loss = loss_func(output, target)
# Backward pass
validation_loss.backward()
# Optimize the weights
optimizer.step()
valid_loss.append(validation_loss.item())
loss_list_V.append(sum(valid_loss)/len(valid_loss))
#print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list_V[-1]))
print('Epoch: {} \tTraining Loss: {:.6f} \tValidation Loss: {:.6f}'.format(
epoch, loss_list[-1], loss_list_V[-1]))
#Now plotting the training graph
plt.plot(loss_list,label='Training Loss')
plt.plot(loss_list_V,label='Validation Loss')
plt.legend()
plt.show()
total_loss=[]
model.eval()
with torch.no_grad():
correct = 0
for batch_idx, (data, target) in enumerate(test_loader):
output = model(data)
pred = output.argmax(dim=1, keepdim=True)
correct += pred.eq(target.view_as(pred)).sum().item()
loss = loss_func(output, target)
total_loss.append(loss.item())
print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format(
sum(total_loss) / len(total_loss),
correct / len(test_loader) * 100)
)
model = Net()
optimizer = optim.Adam(model.parameters(), lr=0.0008)
loss_func = nn.NLLLoss()
epochs = 3
loss_list = []
loss_list_V = []
#training the model
model.train()
for epoch in range(epochs):
train_loss = []
for batch_idx, (data, target) in enumerate(train_loader):
optimizer.zero_grad()
# Forward pass
output = model(data)
# Calculating loss
loss = loss_func(output, target)
# Backward pass
loss.backward()
# Optimize the weights
optimizer.step()
train_loss.append(loss.item())
loss_list.append(sum(train_loss)/len(train_loss))
#print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list[-1]))
#Validate the model
model.eval()
for epoch in range(epochs):
valid_loss = []
for batch_idx, (data, target) in enumerate(valid_loader):
optimizer.zero_grad()
# Forward pass
output = model(data)
# Calculating loss
validation_loss = loss_func(output, target)
# Backward pass
validation_loss.backward()
# Optimize the weights
optimizer.step()
valid_loss.append(validation_loss.item())
loss_list_V.append(sum(valid_loss)/len(valid_loss))
#print('Training [{:.0f}%]\tLoss: {:.4f}'.format(100. * (epoch + 1) / epochs, loss_list_V[-1]))
print('Epoch: {} \tTraining Loss: {:.6f} \tValidation Loss: {:.6f}'.format(
epoch, loss_list[-1], loss_list_V[-1]))
#Now plotting the training graph
plt.plot(loss_list,label='Training Loss')
plt.plot(loss_list_V,label='Validation Loss')
plt.legend()
plt.show()
total_loss=[]
model.eval()
with torch.no_grad():
correct = 0
for batch_idx, (data, target) in enumerate(test_loader):
output = model(data)
pred = output.argmax(dim=1, keepdim=True)
correct += pred.eq(target.view_as(pred)).sum().item()
loss = loss_func(output, target)
total_loss.append(loss.item())
print('Performance on test data:\n\tLoss: {:.4f}\n\tAccuracy: {:.1f}%'.format(
sum(total_loss) / len(total_loss),
correct / len(test_loader) * 100)
)
|
https://github.com/rmlarose/qcbq
|
rmlarose
|
# !pip install qiskit==0.7.1
# Include the necessary imports for this program
import numpy as np
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute
# Create a Quantum Register with 2 qubits
qr = QuantumRegister(2)
# Create a Classical Register with 2 bits
cr = ClassicalRegister(2)
# Create a Quantum Circuit from the quantum and classical registers
circ = QuantumCircuit(qr, cr)
# Place Hadamard gate on the top wire, putting this qubit in a superposition.
circ.h(qr[0])
# Add a CX (CNOT) gate across the top two wires, entangling the qubits.
circ.cx(qr[0], qr[1])
# Create a barrier that separates the gates from the measurements
circ.barrier(qr)
# Measure the qubits into the classical registers
circ.measure(qr, cr)
# Draw the new circuit
circ.draw(output='mpl')
# Use the BasicAer statevector_simulator backend
from qiskit import BasicAer
backend_sv_sim = BasicAer.get_backend('statevector_simulator')
# Execute the circuit on the state vector simulator
job_sim = execute(circ, backend_sv_sim)
# Grab the results from the job.
result_sim = job_sim.result()
# Obtain the state vector for the quantum circuit
quantum_state = result_sim.get_statevector(circ, decimals=3)
# Output the quantum state vector in a manner that contains a comma-delimited string.
quantum_state
# Plot the state vector on a Q-sphere
from qiskit.tools.visualization import plot_state_qsphere
plot_state_qsphere(quantum_state)
# Use the BasicAer qasm_simulator backend
from qiskit import BasicAer
backend_sim = BasicAer.get_backend('qasm_simulator')
# Execute the circuit on the qasm simulator, running it 1000 times.
job_sim = execute(circ, backend_sim, shots=1000)
# Grab the results from the job.
result_sim = job_sim.result()
# Print the counts, which are contained in a Python dictionary
counts = result_sim.get_counts(circ)
print(counts)
# Plot the results on a histogram
from qiskit.tools.visualization import plot_histogram
plot_histogram(counts)
# Include the necessary imports for this program
# Create a Quantum Register with 2 qubits
# Create a Classical Register with 2 bits
# Create a Quantum Circuit from the quantum and classical registers
# Place appropriate gates on the wires to achieve the desired Bell state
# Create a barrier that separates the gates from the measurements
# Measure the qubits into the classical registers
# Draw the circuit
# Use the BasicAer statevector_simulator backend
# Execute the circuit on the state vector simulator
# Grab the results from the job.
# Obtain the state vector for the quantum circuit
# Output the quantum state vector in a manner that contains a comma-delimited string.
# Plot the state vector on a Q-sphere
# Use the BasicAer qasm_simulator backend
# Execute the circuit on the qasm simulator, running it 1000 times.
# Grab the results from the job.
# Print the counts, which are contained in a Python dictionary
# Plot the results on a histogram
|
https://github.com/Marduk-42/Quantum-Algorithm-Tutorials
|
Marduk-42
|
from qiskit import *
def random_int(backend, size):
circuit = QuantumCircuit.from_qasm_file("Random_number.qasm")
job = execute(circuit, backend, shots=size, memory=True)
result = job.result()
bin_num = ''.join(result.get_memory())
return int(bin_num,2)
#QASM Simulator backend:
backend = Aer.get_backend('qasm_simulator')
#Real IBM Quantum Computer backend
#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))
bits = 64
print("Here you have a random number: ", random_int(backend, bits))
|
https://github.com/davidedellagiustina/qasp-solver
|
davidedellagiustina
|
'''Grover Search with a quantum oracle built from the classical procedure.
Reference: Example 4.2.1 in the thesis.
'''
import copy
from qiskit import QuantumCircuit, QuantumRegister
from src import qasp
from src.examples.util import tab, pause
# ASP program
PRGM = '''
p :- not q.
q.
'''
def build_oracle() -> tuple[qasp.oracle.Oracle, list[int]]:
'''Build the quantum oracle shown in Example 4.2.1 in the thesis.
#### Return
tuple[QuantumCircuit, list[int]]: Circuit implementing the oracle and list of auxiliary \
qubits used.
'''
# Build classical oracle
def c_oracle(interp):
m_p = {
('p', not ('q', True) in interp),
('q', True),
}
return interp == m_p
# Build quantum oracle
(p, q) = (QuantumRegister(1, 'p'), QuantumRegister(1, 'q'))
p_if_not_q = QuantumRegister(1, 'p_if_not_q')
p_in_reduct = QuantumRegister(1, 'p_in_reduct')
q_in_reduct = QuantumRegister(1, 'q_in_reduct')
p_equal = QuantumRegister(1, 'p_equal')
q_equal = QuantumRegister(1, 'q_equal')
equal = QuantumRegister(1, 'equal')
q_oracle = QuantumCircuit(p, q, p_if_not_q, p_in_reduct,
q_in_reduct, p_equal, q_equal, equal, name='Oracle')
aux_qubits = list(range(2, 8))
# Step 1
q_oracle.x(p_if_not_q)
q_oracle.cx(q, p_if_not_q)
q_oracle.barrier()
# Step 2
q_oracle.cx(p_if_not_q, p_in_reduct)
q_oracle.x(q_in_reduct)
q_oracle.barrier()
# Step 3
q_oracle.ccx(p, p_in_reduct, p_equal)
q_oracle.ccx(p, p_in_reduct, p_equal, ctrl_state='00')
q_oracle.ccx(q, q_in_reduct, q_equal)
q_oracle.ccx(q, q_in_reduct, q_equal, ctrl_state='00')
q_oracle.barrier()
undo = copy.deepcopy(q_oracle).reverse_ops()
# Step 4
q_oracle.x(equal)
q_oracle.h(equal)
q_oracle.ccx(p_equal, q_equal, equal)
q_oracle.h(equal)
q_oracle.x(equal)
q_oracle.barrier()
# Undo steps
q_oracle.compose(undo, q_oracle.qubits, inplace=True)
return ((c_oracle, q_oracle), aux_qubits)
def main():
'''Entrypoint.
'''
print(f'ASP program:\n{tab(PRGM.strip(), striplines=True)}\n')
pause()
# Program parameters
n_search = 2 # Number of search qubits
n_aux = 6 # Number of auxiliary qubits
# pylint: disable=invalid-name
M = 1
print(f'Number of variables: {n_search}.')
print(f'Number of stable models: {M}.')
print()
pause()
# Initialization algorithm
algorithm = qasp.init_algorithm.alg_grover(n_search) # Walsh-Hadamard
reg_aux = QuantumRegister(n_aux, 'aux')
algorithm.add_register(reg_aux)
algorithm.name += ' x Id'
print(f'Initialization algorithm:\n{tab(str(algorithm.draw()))}\n')
pause()
# Oracle
(oracle, aux_qubits) = build_oracle()
print(f'Quantum oracle:\n{tab(str(oracle[1].draw()))}\n')
pause()
# Simulation
(circuit, iters, stable_model) = qasp.problems.amplification.exec_find_one_known_m(
algorithm, oracle, M, aux_qubits)
print(f'Used circuit:\n{tab(str(circuit.draw()))}\n')
pause()
print(f'Found stable model: {stable_model}.')
print(f'Number of iterations: {iters}.')
print()
if __name__ == '__main__':
main()
|
https://github.com/WerWojtas/Quantum_algorithms
|
WerWojtas
|
from qiskit.circuit.library import PhaseOracle
from qiskit import QuantumCircuit
from qiskit.circuit.library import GroverOperator
from qiskit import Aer, transpile
sat_problem = [
[1],
[4,5,6],
[7],
[-3,-6],
[-2,4,-5]]
def save_to_dimacs(file_path, clauses,number_of_bits,number_of_clauses):
with open(file_path, 'w') as file:
file.write("p cnf " + str(number_of_bits) + " " + str(number_of_clauses) + "\n")
for clause in clauses:
file.write(" ".join(map(str, clause)) + " 0\n")
save_to_dimacs("formula.dimacs", sat_problem,7,len(sat_problem)
def Grovers_algorithm(number_of_qubits):
oracle = PhaseOracle.from_dimacs_file('formula.dimacs')
circuit = QuantumCircuit(number_of_qubits)
for i in range(number_of_qubits):
circuit.h(i)
grover = GroverOperator(oracle)
qc = circuit.compose(grover_operator)
qc.measure_all()
sim = Aer.get_backend('aer_simulator')
transpile_qc = transpile(qc, sim)
sim.run(transpile_qc).result().get_counts()
Grovers_algorithm(7)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import numpy as np
from qiskit import QuantumCircuit
from qiskit.quantum_info import DensityMatrix
from qiskit.visualization import plot_state_hinton
qc = QuantumCircuit(2)
qc.h([0, 1])
qc.cz(0,1)
qc.ry(np.pi/3 , 0)
qc.rx(np.pi/5, 1)
state = DensityMatrix(qc)
plot_state_hinton(state, title="New Hinton Plot")
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2019, 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.
# This code was originally copied from the qiskit-ignis see:
# https://github.com/Qiskit/qiskit-ignis/blob/b91066c72171bcd55a70e6e8993b813ec763cf41/qiskit/ignis/mitigation/measurement/filters.py
# it was migrated as qiskit-ignis is being deprecated
# pylint: disable=cell-var-from-loop
"""
Measurement correction filters.
"""
from typing import List
from copy import deepcopy
import numpy as np
import qiskit
from qiskit import QiskitError
from qiskit.tools import parallel_map
from qiskit.utils.mitigation.circuits import count_keys
from qiskit.utils.deprecation import deprecate_func
class MeasurementFilter:
"""
Deprecated: Measurement error mitigation filter.
Produced from a measurement calibration fitter and can be applied
to data.
"""
@deprecate_func(
since="0.24.0",
additional_msg="For code migration guidelines, visit https://qisk.it/qi_migration.",
)
def __init__(self, cal_matrix: np.matrix, state_labels: list):
"""
Initialize a measurement error mitigation filter using the cal_matrix
from a measurement calibration fitter.
Args:
cal_matrix: the calibration matrix for applying the correction
state_labels: the states for the ordering of the cal matrix
"""
self._cal_matrix = cal_matrix
self._state_labels = state_labels
@property
def cal_matrix(self):
"""Return cal_matrix."""
return self._cal_matrix
@property
def state_labels(self):
"""return the state label ordering of the cal matrix"""
return self._state_labels
@state_labels.setter
def state_labels(self, new_state_labels):
"""set the state label ordering of the cal matrix"""
self._state_labels = new_state_labels
@cal_matrix.setter
def cal_matrix(self, new_cal_matrix):
"""Set cal_matrix."""
self._cal_matrix = new_cal_matrix
def apply(self, raw_data, method="least_squares"):
"""Apply the calibration matrix to results.
Args:
raw_data (dict or list): The data to be corrected. Can be in a number of forms:
Form 1: a counts dictionary from results.get_counts
Form 2: a list of counts of `length==len(state_labels)`
Form 3: a list of counts of `length==M*len(state_labels)` where M is an
integer (e.g. for use with the tomography data)
Form 4: a qiskit Result
method (str): fitting method. If `None`, then least_squares is used.
``pseudo_inverse``: direct inversion of the A matrix
``least_squares``: constrained to have physical probabilities
Returns:
dict or list: The corrected data in the same form as `raw_data`
Raises:
QiskitError: if `raw_data` is not an integer multiple
of the number of calibrated states.
"""
from scipy.optimize import minimize
from scipy import linalg as la
# check forms of raw_data
if isinstance(raw_data, dict):
# counts dictionary
for data_label in raw_data.keys():
if data_label not in self._state_labels:
raise QiskitError(
f"Unexpected state label '{data_label}'."
" Verify the fitter's state labels correspond to the input data."
)
data_format = 0
# convert to form2
raw_data2 = [np.zeros(len(self._state_labels), dtype=float)]
for stateidx, state in enumerate(self._state_labels):
raw_data2[0][stateidx] = raw_data.get(state, 0)
elif isinstance(raw_data, list):
size_ratio = len(raw_data) / len(self._state_labels)
if len(raw_data) == len(self._state_labels):
data_format = 1
raw_data2 = [raw_data]
elif int(size_ratio) == size_ratio:
data_format = 2
size_ratio = int(size_ratio)
# make the list into chunks the size of state_labels for easier
# processing
raw_data2 = np.zeros([size_ratio, len(self._state_labels)])
for i in range(size_ratio):
raw_data2[i][:] = raw_data[
i * len(self._state_labels) : (i + 1) * len(self._state_labels)
]
else:
raise QiskitError(
"Data list is not an integer multiple of the number of calibrated states"
)
elif isinstance(raw_data, qiskit.result.result.Result):
# extract out all the counts, re-call the function with the
# counts and push back into the new result
new_result = deepcopy(raw_data)
new_counts_list = parallel_map(
self._apply_correction,
[resultidx for resultidx, _ in enumerate(raw_data.results)],
task_args=(raw_data, method),
)
for resultidx, new_counts in new_counts_list:
new_result.results[resultidx].data.counts = new_counts
return new_result
else:
raise QiskitError("Unrecognized type for raw_data.")
if method == "pseudo_inverse":
pinv_cal_mat = la.pinv(self._cal_matrix)
# Apply the correction
for data_idx, _ in enumerate(raw_data2):
if method == "pseudo_inverse":
raw_data2[data_idx] = np.dot(pinv_cal_mat, raw_data2[data_idx])
elif method == "least_squares":
nshots = sum(raw_data2[data_idx])
def fun(x):
return sum((raw_data2[data_idx] - np.dot(self._cal_matrix, x)) ** 2)
x0 = np.random.rand(len(self._state_labels))
x0 = x0 / sum(x0)
cons = {"type": "eq", "fun": lambda x: nshots - sum(x)}
bnds = tuple((0, nshots) for x in x0)
res = minimize(fun, x0, method="SLSQP", constraints=cons, bounds=bnds, tol=1e-6)
raw_data2[data_idx] = res.x
else:
raise QiskitError("Unrecognized method.")
if data_format == 2:
# flatten back out the list
raw_data2 = raw_data2.flatten()
elif data_format == 0:
# convert back into a counts dictionary
new_count_dict = {}
for stateidx, state in enumerate(self._state_labels):
if raw_data2[0][stateidx] != 0:
new_count_dict[state] = raw_data2[0][stateidx]
raw_data2 = new_count_dict
else:
# TODO: should probably change to:
# raw_data2 = raw_data2[0].tolist()
raw_data2 = raw_data2[0]
return raw_data2
def _apply_correction(self, resultidx, raw_data, method):
"""Wrapper to call apply with a counts dictionary."""
new_counts = self.apply(raw_data.get_counts(resultidx), method=method)
return resultidx, new_counts
class TensoredFilter:
"""
Deprecated: Tensored measurement error mitigation filter.
Produced from a tensored measurement calibration fitter and can be applied
to data.
"""
@deprecate_func(
since="0.24.0",
additional_msg="For code migration guidelines, visit https://qisk.it/qi_migration.",
)
def __init__(self, cal_matrices: np.matrix, substate_labels_list: list, mit_pattern: list):
"""
Initialize a tensored measurement error mitigation filter using
the cal_matrices from a tensored measurement calibration fitter.
A simple usage this class is explained [here]
(https://qiskit.org/documentation/tutorials/noise/3_measurement_error_mitigation.html).
Args:
cal_matrices: the calibration matrices for applying the correction.
substate_labels_list: for each calibration matrix
a list of the states (as strings, states in the subspace)
mit_pattern: for each calibration matrix
a list of the logical qubit indices (as int, states in the subspace)
"""
self._cal_matrices = cal_matrices
self._qubit_list_sizes = []
self._indices_list = []
self._substate_labels_list = []
self.substate_labels_list = substate_labels_list
self._mit_pattern = mit_pattern
@property
def cal_matrices(self):
"""Return cal_matrices."""
return self._cal_matrices
@cal_matrices.setter
def cal_matrices(self, new_cal_matrices):
"""Set cal_matrices."""
self._cal_matrices = deepcopy(new_cal_matrices)
@property
def substate_labels_list(self):
"""Return _substate_labels_list"""
return self._substate_labels_list
@substate_labels_list.setter
def substate_labels_list(self, new_substate_labels_list):
"""Return _substate_labels_list"""
self._substate_labels_list = new_substate_labels_list
# get the number of qubits in each subspace
self._qubit_list_sizes = []
for _, substate_label_list in enumerate(self._substate_labels_list):
self._qubit_list_sizes.append(int(np.log2(len(substate_label_list))))
# get the indices in the calibration matrix
self._indices_list = []
for _, sub_labels in enumerate(self._substate_labels_list):
self._indices_list.append({lab: ind for ind, lab in enumerate(sub_labels)})
@property
def qubit_list_sizes(self):
"""Return _qubit_list_sizes."""
return self._qubit_list_sizes
@property
def nqubits(self):
"""Return the number of qubits. See also MeasurementFilter.apply()"""
return sum(self._qubit_list_sizes)
def apply(
self,
raw_data,
method="least_squares",
meas_layout=None,
):
"""
Apply the calibration matrices to results.
Args:
raw_data (dict or Result): The data to be corrected. Can be in one of two forms:
* A counts dictionary from results.get_counts
* A Qiskit Result
method (str): fitting method. The following methods are supported:
* 'pseudo_inverse': direct inversion of the cal matrices.
Mitigated counts can contain negative values
and the sum of counts would not equal to the shots.
Mitigation is conducted qubit wise:
For each qubit, mitigate the whole counts using the calibration matrices
which affect the corresponding qubit.
For example, assume we are mitigating the 3rd bit of the 4-bit counts
using '2\times 2' calibration matrix `A_3`.
When mitigating the count of '0110' in this step,
the following formula is applied:
`count['0110'] = A_3^{-1}[1, 0]*count['0100'] + A_3^{-1}[1, 1]*count['0110']`.
The total time complexity of this method is `O(m2^{n + t})`,
where `n` is the size of calibrated qubits,
`m` is the number of sets in `mit_pattern`,
and `t` is the size of largest set of mit_pattern.
If the `mit_pattern` is shaped like `[[0], [1], [2], ..., [n-1]]`,
which corresponds to the tensor product noise model without cross-talk,
then the time complexity would be `O(n2^n)`.
If the `mit_pattern` is shaped like `[[0, 1, 2, ..., n-1]]`,
which exactly corresponds to the complete error mitigation,
then the time complexity would be `O(2^(n+n)) = O(4^n)`.
* 'least_squares': constrained to have physical probabilities.
Instead of directly applying inverse calibration matrices,
this method solve a constrained optimization problem to find
the closest probability vector to the result from 'pseudo_inverse' method.
Sequential least square quadratic programming (SLSQP) is used
in the internal process.
Every updating step in SLSQP takes `O(m2^{n+t})` time.
Since this method is using the SLSQP optimization over
the vector with lenght `2^n`, the mitigation for 8 bit counts
with the `mit_pattern = [[0], [1], [2], ..., [n-1]]` would
take 10 seconds or more.
* If `None`, 'least_squares' is used.
meas_layout (list of int): the mapping from classical registers to qubits
* If you measure qubit `2` to clbit `0`, `0` to `1`, and `1` to `2`,
the list becomes `[2, 0, 1]`
* If `None`, flatten(mit_pattern) is used.
Returns:
dict or Result: The corrected data in the same form as raw_data
Raises:
QiskitError: if raw_data is not in a one of the defined forms.
"""
from scipy.optimize import minimize
from scipy import linalg as la
all_states = count_keys(self.nqubits)
num_of_states = 2**self.nqubits
if meas_layout is None:
meas_layout = []
for qubits in self._mit_pattern:
meas_layout += qubits
# check forms of raw_data
if isinstance(raw_data, dict):
# counts dictionary
# convert to list
raw_data2 = [np.zeros(num_of_states, dtype=float)]
for state, count in raw_data.items():
stateidx = int(state, 2)
raw_data2[0][stateidx] = count
elif isinstance(raw_data, qiskit.result.result.Result):
# extract out all the counts, re-call the function with the
# counts and push back into the new result
new_result = deepcopy(raw_data)
new_counts_list = parallel_map(
self._apply_correction,
[resultidx for resultidx, _ in enumerate(raw_data.results)],
task_args=(raw_data, method, meas_layout),
)
for resultidx, new_counts in new_counts_list:
new_result.results[resultidx].data.counts = new_counts
return new_result
else:
raise QiskitError("Unrecognized type for raw_data.")
if method == "pseudo_inverse":
pinv_cal_matrices = []
for cal_mat in self._cal_matrices:
pinv_cal_matrices.append(la.pinv(cal_mat))
meas_layout = meas_layout[::-1] # reverse endian
qubits_to_clbits = [-1 for _ in range(max(meas_layout) + 1)]
for i, qubit in enumerate(meas_layout):
qubits_to_clbits[qubit] = i
# Apply the correction
for data_idx, _ in enumerate(raw_data2):
if method == "pseudo_inverse":
for pinv_cal_mat, pos_qubits, indices in zip(
pinv_cal_matrices, self._mit_pattern, self._indices_list
):
inv_mat_dot_x = np.zeros([num_of_states], dtype=float)
pos_clbits = [qubits_to_clbits[qubit] for qubit in pos_qubits]
for state_idx, state in enumerate(all_states):
first_index = self.compute_index_of_cal_mat(state, pos_clbits, indices)
for i in range(len(pinv_cal_mat)): # i is index of pinv_cal_mat
source_state = self.flip_state(state, i, pos_clbits)
second_index = self.compute_index_of_cal_mat(
source_state, pos_clbits, indices
)
inv_mat_dot_x[state_idx] += (
pinv_cal_mat[first_index, second_index]
* raw_data2[data_idx][int(source_state, 2)]
)
raw_data2[data_idx] = inv_mat_dot_x
elif method == "least_squares":
def fun(x):
mat_dot_x = deepcopy(x)
for cal_mat, pos_qubits, indices in zip(
self._cal_matrices, self._mit_pattern, self._indices_list
):
res_mat_dot_x = np.zeros([num_of_states], dtype=float)
pos_clbits = [qubits_to_clbits[qubit] for qubit in pos_qubits]
for state_idx, state in enumerate(all_states):
second_index = self.compute_index_of_cal_mat(state, pos_clbits, indices)
for i in range(len(cal_mat)):
target_state = self.flip_state(state, i, pos_clbits)
first_index = self.compute_index_of_cal_mat(
target_state, pos_clbits, indices
)
res_mat_dot_x[int(target_state, 2)] += (
cal_mat[first_index, second_index] * mat_dot_x[state_idx]
)
mat_dot_x = res_mat_dot_x
return sum((raw_data2[data_idx] - mat_dot_x) ** 2)
x0 = np.random.rand(num_of_states)
x0 = x0 / sum(x0)
nshots = sum(raw_data2[data_idx])
cons = {"type": "eq", "fun": lambda x: nshots - sum(x)}
bnds = tuple((0, nshots) for x in x0)
res = minimize(fun, x0, method="SLSQP", constraints=cons, bounds=bnds, tol=1e-6)
raw_data2[data_idx] = res.x
else:
raise QiskitError("Unrecognized method.")
# convert back into a counts dictionary
new_count_dict = {}
for state_idx, state in enumerate(all_states):
if raw_data2[0][state_idx] != 0:
new_count_dict[state] = raw_data2[0][state_idx]
return new_count_dict
def flip_state(self, state: str, mat_index: int, flip_poses: List[int]) -> str:
"""Flip the state according to the chosen qubit positions"""
flip_poses = [pos for i, pos in enumerate(flip_poses) if (mat_index >> i) & 1]
flip_poses = sorted(flip_poses)
new_state = ""
pos = 0
for flip_pos in flip_poses:
new_state += state[pos:flip_pos]
new_state += str(int(state[flip_pos], 2) ^ 1) # flip the state
pos = flip_pos + 1
new_state += state[pos:]
return new_state
def compute_index_of_cal_mat(self, state: str, pos_qubits: List[int], indices: dict) -> int:
"""Return the index of (pseudo inverse) calibration matrix for the input quantum state"""
sub_state = ""
for pos in pos_qubits:
sub_state += state[pos]
return indices[sub_state]
def _apply_correction(
self,
resultidx,
raw_data,
method,
meas_layout,
):
"""Wrapper to call apply with a counts dictionary."""
new_counts = self.apply(
raw_data.get_counts(resultidx), method=method, meas_layout=meas_layout
)
return resultidx, new_counts
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
q = QuantumRegister(1)
c = ClassicalRegister(1)
qc = QuantumCircuit(q, c)
qc.h(q)
qc.measure(q, c)
qc.draw(output='mpl', style={'backgroundcolor': '#EEEEEE'})
|
https://github.com/Andres8bit/IBMQ-Quantum-Qiskit
|
Andres8bit
|
%matplotlib inline
# Importing standard Qiskit libraries and configuring account
# initialization
import matplotlib.pyplot as plt
import numpy as np
from qiskit import QuantumCircuit, execute, Aer, IBMQ, BasicAer,ClassicalRegister,QuantumRegister
from qiskit.providers.ibmq import least_busy
from qiskit.compiler import transpile, assemble
from qiskit.tools.monitor import job_monitor
from qiskit.tools.jupyter import *
from qiskit.visualization import *
# Loading your IBM Q account(s)
provider = IBMQ.load_account()
# Bernstein-Vazirani Algorithm:
# Much like the Deutsch-Josza Algorithm.
# We are given a black-box funtion f,
# which takes a string of bits x.
# And returns either 0 or 1.
# Instead of the function being either balanced or constant
# the function is guaranteed to return the bitwise produc of the input
# with some string, s. That is to say:
# given an input x, f(x) = s * x%2.
# Where we are asked to find s
# ======= CLASSICAL SOLUTION: =======
# classically the oracle returns: fs(x) = s*x %2
# Given an input x. Thus, the hidden bit string s can be revealed by
# querying the oracle with the sequence of inputs:
# 1000...00, 0100...00, 0010...00, 0000...01
# Where each query revelas a different s with x = 0100...00 we can find the next least
# significant bit of s and so on.
# Therefore we would need to call fs(x), a total of n times.
# ======= Quantum Solution: =======
# Using a quantum computer, we can solve this problem with 100% confidence
# after only one call to the function f(x).
# the following is the algorithmic steps:
# 1. Initialise the imputs qubits to the |0>^(cnot n) state, and output the qubit to |->
# 2. Apply Hadamard gates to the input register. // place in superposition
# 3. Query the oracle
# 4. Apply Hadamard gates to the input register //undue super position.
# 5. Measure
n = 3
s = '011'
# we need a circuit with n qubits, plus one ancilla qubit.
bv_circuit = QuantumCircuit(n+1,n)
# put ancilla in state |->
bv_circuit.h(n)
bv_circuit.z(n)
# Apply Hadamard gates before querying the oracle
for i in range(n):
bv_circuit.h(i)
# Apply barrier
bv_circuit.barrier()
# Apply the inner-product oracle
s = s[::-1]
for q in range(n):
if s[q] == '0':
bv_circuit.i(q)
else:
bv_circuit.cx(q,n)
# Apply barrier
bv_circuit.barrier()
# Apply Hadamard gates after querying the oracle
for i in range(n):
bv_circuit.h(i)
# Measurement
for i in range(n):
bv_circuit.measure(i,i)
bv_circuit.draw()
# running our circuit on the qasm sumulator:
backend = BasicAer.get_backend('qasm_simulator')
shots = 1024
results = execute(bv_circuit,backend=backend,shots=shots).result()
answer = results.get_counts()
plot_histogram(answer)
# Load our saved IBMQ accounts and get the least busy backend device with less than or equal to 5 qubits
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q')
provider.backends()
backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits <= 5 and
x.configuration().n_qubits >= 2 and
not x.configuration().simulator and x.status().operational==True))
print("least busy backend: ", backend)
shots = 1024
job = execute(bv_circuit,backend=backend,shots=shots)
job_monitor(job,interval = 2)
results = job.result()
answer = results.get_counts()
plot_histogram(answer)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver, QAOA, SamplingVQE
from qiskit.algorithms.optimizers import COBYLA
from qiskit.circuit.library import TwoLocal
from qiskit.result import QuasiDistribution
from qiskit_aer.primitives import Sampler
from qiskit_finance.applications.optimization import PortfolioOptimization
from qiskit_finance.data_providers import RandomDataProvider
from qiskit_optimization.algorithms import MinimumEigenOptimizer
import numpy as np
import matplotlib.pyplot as plt
import datetime
# set number of assets (= number of qubits)
num_assets = 4
seed = 123
# Generate expected return and covariance matrix from (random) time-series
stocks = [("TICKER%s" % i) for i in range(num_assets)]
data = RandomDataProvider(
tickers=stocks,
start=datetime.datetime(2016, 1, 1),
end=datetime.datetime(2016, 1, 30),
seed=seed,
)
data.run()
mu = data.get_period_return_mean_vector()
sigma = data.get_period_return_covariance_matrix()
# plot sigma
plt.imshow(sigma, interpolation="nearest")
plt.show()
q = 0.5 # set risk factor
budget = num_assets // 2 # set budget
penalty = num_assets # set parameter to scale the budget penalty term
portfolio = PortfolioOptimization(
expected_returns=mu, covariances=sigma, risk_factor=q, budget=budget
)
qp = portfolio.to_quadratic_program()
qp
def print_result(result):
selection = result.x
value = result.fval
print("Optimal: selection {}, value {:.4f}".format(selection, value))
eigenstate = result.min_eigen_solver_result.eigenstate
probabilities = (
eigenstate.binary_probabilities()
if isinstance(eigenstate, QuasiDistribution)
else {k: np.abs(v) ** 2 for k, v in eigenstate.to_dict().items()}
)
print("\n----------------- Full result ---------------------")
print("selection\tvalue\t\tprobability")
print("---------------------------------------------------")
probabilities = sorted(probabilities.items(), key=lambda x: x[1], reverse=True)
for k, v in probabilities:
x = np.array([int(i) for i in list(reversed(k))])
value = portfolio.to_quadratic_program().objective.evaluate(x)
print("%10s\t%.4f\t\t%.4f" % (x, value, v))
exact_mes = NumPyMinimumEigensolver()
exact_eigensolver = MinimumEigenOptimizer(exact_mes)
result = exact_eigensolver.solve(qp)
print_result(result)
from qiskit.utils import algorithm_globals
algorithm_globals.random_seed = 1234
cobyla = COBYLA()
cobyla.set_options(maxiter=500)
ry = TwoLocal(num_assets, "ry", "cz", reps=3, entanglement="full")
vqe_mes = SamplingVQE(sampler=Sampler(), ansatz=ry, optimizer=cobyla)
vqe = MinimumEigenOptimizer(vqe_mes)
result = vqe.solve(qp)
print_result(result)
algorithm_globals.random_seed = 1234
cobyla = COBYLA()
cobyla.set_options(maxiter=250)
qaoa_mes = QAOA(sampler=Sampler(), optimizer=cobyla, reps=3)
qaoa = MinimumEigenOptimizer(qaoa_mes)
result = qaoa.solve(qp)
print_result(result)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/PacktPublishing/Quantum-Computing-in-Practice-with-Qiskit-and-IBM-Quantum-Experience
|
PacktPublishing
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created Nov 2020
@author: hassi
"""
from qiskit import QuantumRegister, ClassicalRegister
from qiskit import QuantumCircuit, Aer, execute
from qiskit.tools.visualization import plot_histogram
from IPython.core.display import display
print("Ch 4: Quantum coin toss")
print("-----------------------")
q = QuantumRegister(1)
c = ClassicalRegister(1)
qc = QuantumCircuit(q, c)
qc.h(q[0])
qc.measure(q, c)
display(qc.draw('mpl'))
print(qc)
display(qc.draw('text'))
backend = Aer.get_backend('qasm_simulator')
job = execute(qc, backend, shots=1)
result = job.result()
counts = result.get_counts(qc)
print(counts)
display(plot_histogram(counts))
|
https://github.com/unitaryfund/mitiq
|
unitaryfund
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Tests basic functionality of the transpile function"""
import copy
import io
import math
import os
import sys
import unittest
from logging import StreamHandler, getLogger
from test import combine # pylint: disable=wrong-import-order
from unittest.mock import patch
import numpy as np
import rustworkx as rx
from ddt import data, ddt, unpack
from qiskit import BasicAer, ClassicalRegister, QuantumCircuit, QuantumRegister, pulse, qasm3, qpy
from qiskit.circuit import (
Clbit,
ControlFlowOp,
ForLoopOp,
Gate,
IfElseOp,
Parameter,
Qubit,
Reset,
SwitchCaseOp,
WhileLoopOp,
)
from qiskit.circuit.classical import expr
from qiskit.circuit.delay import Delay
from qiskit.circuit.library import (
CXGate,
CZGate,
HGate,
RXGate,
RYGate,
RZGate,
SXGate,
U1Gate,
U2Gate,
UGate,
XGate,
)
from qiskit.circuit.measure import Measure
from qiskit.compiler import transpile
from qiskit.converters import circuit_to_dag
from qiskit.dagcircuit import DAGOpNode, DAGOutNode
from qiskit.exceptions import QiskitError
from qiskit.providers.backend import BackendV2
from qiskit.providers.fake_provider import (
FakeBoeblingen,
FakeMelbourne,
FakeMumbaiV2,
FakeNairobiV2,
FakeRueschlikon,
FakeSherbrooke,
FakeVigo,
)
from qiskit.providers.options import Options
from qiskit.pulse import InstructionScheduleMap
from qiskit.quantum_info import Operator, random_unitary
from qiskit.test import QiskitTestCase, slow_test
from qiskit.tools import parallel
from qiskit.transpiler import CouplingMap, Layout, PassManager, TransformationPass
from qiskit.transpiler.exceptions import TranspilerError
from qiskit.transpiler.passes import BarrierBeforeFinalMeasurements, GateDirection, VF2PostLayout
from qiskit.transpiler.passmanager_config import PassManagerConfig
from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager, level_0_pass_manager
from qiskit.transpiler.target import InstructionProperties, Target
class CustomCX(Gate):
"""Custom CX gate representation."""
def __init__(self):
super().__init__("custom_cx", 2, [])
def _define(self):
self._definition = QuantumCircuit(2)
self._definition.cx(0, 1)
def connected_qubits(physical: int, coupling_map: CouplingMap) -> set:
"""Get the physical qubits that have a connection to this one in the coupling map."""
for component in coupling_map.connected_components():
if physical in (qubits := set(component.graph.nodes())):
return qubits
raise ValueError(f"physical qubit {physical} is not in the coupling map")
@ddt
class TestTranspile(QiskitTestCase):
"""Test transpile function."""
def test_empty_transpilation(self):
"""Test that transpiling an empty list is a no-op. Regression test of gh-7287."""
self.assertEqual(transpile([]), [])
def test_pass_manager_none(self):
"""Test passing the default (None) pass manager to the transpiler.
It should perform the default qiskit flow:
unroll, swap_mapper, cx_direction, cx_cancellation, optimize_1q_gates
and should be equivalent to using tools.compile
"""
qr = QuantumRegister(2, "qr")
circuit = QuantumCircuit(qr)
circuit.h(qr[0])
circuit.h(qr[0])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[1], qr[0])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[1], qr[0])
coupling_map = [[1, 0]]
basis_gates = ["u1", "u2", "u3", "cx", "id"]
backend = BasicAer.get_backend("qasm_simulator")
circuit2 = transpile(
circuit,
backend=backend,
coupling_map=coupling_map,
basis_gates=basis_gates,
)
circuit3 = transpile(
circuit, backend=backend, coupling_map=coupling_map, basis_gates=basis_gates
)
self.assertEqual(circuit2, circuit3)
def test_transpile_basis_gates_no_backend_no_coupling_map(self):
"""Verify transpile() works with no coupling_map or backend."""
qr = QuantumRegister(2, "qr")
circuit = QuantumCircuit(qr)
circuit.h(qr[0])
circuit.h(qr[0])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[0], qr[1])
basis_gates = ["u1", "u2", "u3", "cx", "id"]
circuit2 = transpile(circuit, basis_gates=basis_gates, optimization_level=0)
resources_after = circuit2.count_ops()
self.assertEqual({"u2": 2, "cx": 4}, resources_after)
def test_transpile_non_adjacent_layout(self):
"""Transpile pipeline can handle manual layout on non-adjacent qubits.
circuit:
.. parsed-literal::
┌───┐
qr_0: ┤ H ├──■──────────── -> 1
└───┘┌─┴─┐
qr_1: ─────┤ X ├──■─────── -> 2
└───┘┌─┴─┐
qr_2: ──────────┤ X ├──■── -> 3
└───┘┌─┴─┐
qr_3: ───────────────┤ X ├ -> 5
└───┘
device:
0 - 1 - 2 - 3 - 4 - 5 - 6
| | | | | |
13 - 12 - 11 - 10 - 9 - 8 - 7
"""
qr = QuantumRegister(4, "qr")
circuit = QuantumCircuit(qr)
circuit.h(qr[0])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[1], qr[2])
circuit.cx(qr[2], qr[3])
coupling_map = FakeMelbourne().configuration().coupling_map
basis_gates = FakeMelbourne().configuration().basis_gates
initial_layout = [None, qr[0], qr[1], qr[2], None, qr[3]]
new_circuit = transpile(
circuit,
basis_gates=basis_gates,
coupling_map=coupling_map,
initial_layout=initial_layout,
)
qubit_indices = {bit: idx for idx, bit in enumerate(new_circuit.qubits)}
for instruction in new_circuit.data:
if isinstance(instruction.operation, CXGate):
self.assertIn([qubit_indices[x] for x in instruction.qubits], coupling_map)
def test_transpile_qft_grid(self):
"""Transpile pipeline can handle 8-qubit QFT on 14-qubit grid."""
qr = QuantumRegister(8)
circuit = QuantumCircuit(qr)
for i, _ in enumerate(qr):
for j in range(i):
circuit.cp(math.pi / float(2 ** (i - j)), qr[i], qr[j])
circuit.h(qr[i])
coupling_map = FakeMelbourne().configuration().coupling_map
basis_gates = FakeMelbourne().configuration().basis_gates
new_circuit = transpile(circuit, basis_gates=basis_gates, coupling_map=coupling_map)
qubit_indices = {bit: idx for idx, bit in enumerate(new_circuit.qubits)}
for instruction in new_circuit.data:
if isinstance(instruction.operation, CXGate):
self.assertIn([qubit_indices[x] for x in instruction.qubits], coupling_map)
def test_already_mapped_1(self):
"""Circuit not remapped if matches topology.
See: https://github.com/Qiskit/qiskit-terra/issues/342
"""
backend = FakeRueschlikon()
coupling_map = backend.configuration().coupling_map
basis_gates = backend.configuration().basis_gates
qr = QuantumRegister(16, "qr")
cr = ClassicalRegister(16, "cr")
qc = QuantumCircuit(qr, cr)
qc.cx(qr[3], qr[14])
qc.cx(qr[5], qr[4])
qc.h(qr[9])
qc.cx(qr[9], qr[8])
qc.x(qr[11])
qc.cx(qr[3], qr[4])
qc.cx(qr[12], qr[11])
qc.cx(qr[13], qr[4])
qc.measure(qr, cr)
new_qc = transpile(
qc,
coupling_map=coupling_map,
basis_gates=basis_gates,
initial_layout=Layout.generate_trivial_layout(qr),
)
qubit_indices = {bit: idx for idx, bit in enumerate(new_qc.qubits)}
cx_qubits = [instr.qubits for instr in new_qc.data if instr.operation.name == "cx"]
cx_qubits_physical = [
[qubit_indices[ctrl], qubit_indices[tgt]] for [ctrl, tgt] in cx_qubits
]
self.assertEqual(
sorted(cx_qubits_physical), [[3, 4], [3, 14], [5, 4], [9, 8], [12, 11], [13, 4]]
)
def test_already_mapped_via_layout(self):
"""Test that a manual layout that satisfies a coupling map does not get altered.
See: https://github.com/Qiskit/qiskit-terra/issues/2036
circuit:
.. parsed-literal::
┌───┐ ┌───┐ ░ ┌─┐
qn_0: ┤ H ├──■────────────■──┤ H ├─░─┤M├─── -> 9
└───┘ │ │ └───┘ ░ └╥┘
qn_1: ───────┼────────────┼────────░──╫──── -> 6
│ │ ░ ║
qn_2: ───────┼────────────┼────────░──╫──── -> 5
│ │ ░ ║
qn_3: ───────┼────────────┼────────░──╫──── -> 0
│ │ ░ ║
qn_4: ───────┼────────────┼────────░──╫──── -> 1
┌───┐┌─┴─┐┌──────┐┌─┴─┐┌───┐ ░ ║ ┌─┐
qn_5: ┤ H ├┤ X ├┤ P(2) ├┤ X ├┤ H ├─░──╫─┤M├ -> 4
└───┘└───┘└──────┘└───┘└───┘ ░ ║ └╥┘
cn: 2/════════════════════════════════╩══╩═
0 1
device:
0 -- 1 -- 2 -- 3 -- 4
| |
5 -- 6 -- 7 -- 8 -- 9
| |
10 - 11 - 12 - 13 - 14
| |
15 - 16 - 17 - 18 - 19
"""
basis_gates = ["u1", "u2", "u3", "cx", "id"]
coupling_map = [
[0, 1],
[0, 5],
[1, 0],
[1, 2],
[2, 1],
[2, 3],
[3, 2],
[3, 4],
[4, 3],
[4, 9],
[5, 0],
[5, 6],
[5, 10],
[6, 5],
[6, 7],
[7, 6],
[7, 8],
[7, 12],
[8, 7],
[8, 9],
[9, 4],
[9, 8],
[9, 14],
[10, 5],
[10, 11],
[10, 15],
[11, 10],
[11, 12],
[12, 7],
[12, 11],
[12, 13],
[13, 12],
[13, 14],
[14, 9],
[14, 13],
[14, 19],
[15, 10],
[15, 16],
[16, 15],
[16, 17],
[17, 16],
[17, 18],
[18, 17],
[18, 19],
[19, 14],
[19, 18],
]
q = QuantumRegister(6, name="qn")
c = ClassicalRegister(2, name="cn")
qc = QuantumCircuit(q, c)
qc.h(q[0])
qc.h(q[5])
qc.cx(q[0], q[5])
qc.p(2, q[5])
qc.cx(q[0], q[5])
qc.h(q[0])
qc.h(q[5])
qc.barrier(q)
qc.measure(q[0], c[0])
qc.measure(q[5], c[1])
initial_layout = [
q[3],
q[4],
None,
None,
q[5],
q[2],
q[1],
None,
None,
q[0],
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
]
new_qc = transpile(
qc, coupling_map=coupling_map, basis_gates=basis_gates, initial_layout=initial_layout
)
qubit_indices = {bit: idx for idx, bit in enumerate(new_qc.qubits)}
cx_qubits = [instr.qubits for instr in new_qc.data if instr.operation.name == "cx"]
cx_qubits_physical = [
[qubit_indices[ctrl], qubit_indices[tgt]] for [ctrl, tgt] in cx_qubits
]
self.assertEqual(sorted(cx_qubits_physical), [[9, 4], [9, 4]])
def test_transpile_bell(self):
"""Test Transpile Bell.
If all correct some should exists.
"""
backend = BasicAer.get_backend("qasm_simulator")
qubit_reg = QuantumRegister(2, name="q")
clbit_reg = ClassicalRegister(2, name="c")
qc = QuantumCircuit(qubit_reg, clbit_reg, name="bell")
qc.h(qubit_reg[0])
qc.cx(qubit_reg[0], qubit_reg[1])
qc.measure(qubit_reg, clbit_reg)
circuits = transpile(qc, backend)
self.assertIsInstance(circuits, QuantumCircuit)
def test_transpile_one(self):
"""Test transpile a single circuit.
Check that the top-level `transpile` function returns
a single circuit."""
backend = BasicAer.get_backend("qasm_simulator")
qubit_reg = QuantumRegister(2)
clbit_reg = ClassicalRegister(2)
qc = QuantumCircuit(qubit_reg, clbit_reg, name="bell")
qc.h(qubit_reg[0])
qc.cx(qubit_reg[0], qubit_reg[1])
qc.measure(qubit_reg, clbit_reg)
circuit = transpile(qc, backend)
self.assertIsInstance(circuit, QuantumCircuit)
def test_transpile_two(self):
"""Test transpile two circuits.
Check that the transpiler returns a list of two circuits.
"""
backend = BasicAer.get_backend("qasm_simulator")
qubit_reg = QuantumRegister(2)
clbit_reg = ClassicalRegister(2)
qubit_reg2 = QuantumRegister(2)
clbit_reg2 = ClassicalRegister(2)
qc = QuantumCircuit(qubit_reg, clbit_reg, name="bell")
qc.h(qubit_reg[0])
qc.cx(qubit_reg[0], qubit_reg[1])
qc.measure(qubit_reg, clbit_reg)
qc_extra = QuantumCircuit(qubit_reg, qubit_reg2, clbit_reg, clbit_reg2, name="extra")
qc_extra.measure(qubit_reg, clbit_reg)
circuits = transpile([qc, qc_extra], backend)
self.assertIsInstance(circuits, list)
self.assertEqual(len(circuits), 2)
for circuit in circuits:
self.assertIsInstance(circuit, QuantumCircuit)
def test_transpile_singleton(self):
"""Test transpile a single-element list with a circuit.
Check that `transpile` returns a single-element list.
See https://github.com/Qiskit/qiskit-terra/issues/5260
"""
backend = BasicAer.get_backend("qasm_simulator")
qubit_reg = QuantumRegister(2)
clbit_reg = ClassicalRegister(2)
qc = QuantumCircuit(qubit_reg, clbit_reg, name="bell")
qc.h(qubit_reg[0])
qc.cx(qubit_reg[0], qubit_reg[1])
qc.measure(qubit_reg, clbit_reg)
circuits = transpile([qc], backend)
self.assertIsInstance(circuits, list)
self.assertEqual(len(circuits), 1)
self.assertIsInstance(circuits[0], QuantumCircuit)
def test_mapping_correction(self):
"""Test mapping works in previous failed case."""
backend = FakeRueschlikon()
qr = QuantumRegister(name="qr", size=11)
cr = ClassicalRegister(name="qc", size=11)
circuit = QuantumCircuit(qr, cr)
circuit.u(1.564784764685993, -1.2378965763410095, 2.9746763177861713, qr[3])
circuit.u(1.2269835563676523, 1.1932982847014162, -1.5597357740824318, qr[5])
circuit.cx(qr[5], qr[3])
circuit.p(0.856768317675967, qr[3])
circuit.u(-3.3911273825190915, 0.0, 0.0, qr[5])
circuit.cx(qr[3], qr[5])
circuit.u(2.159209321625547, 0.0, 0.0, qr[5])
circuit.cx(qr[5], qr[3])
circuit.u(0.30949966910232335, 1.1706201763833217, 1.738408691990081, qr[3])
circuit.u(1.9630571407274755, -0.6818742967975088, 1.8336534616728195, qr[5])
circuit.u(1.330181833806101, 0.6003162754946363, -3.181264980452862, qr[7])
circuit.u(0.4885914820775024, 3.133297443244865, -2.794457469189904, qr[8])
circuit.cx(qr[8], qr[7])
circuit.p(2.2196187596178616, qr[7])
circuit.u(-3.152367609631023, 0.0, 0.0, qr[8])
circuit.cx(qr[7], qr[8])
circuit.u(1.2646005789809263, 0.0, 0.0, qr[8])
circuit.cx(qr[8], qr[7])
circuit.u(0.7517780502091939, 1.2828514296564781, 1.6781179605443775, qr[7])
circuit.u(0.9267400575390405, 2.0526277839695153, 2.034202361069533, qr[8])
circuit.u(2.550304293455634, 3.8250017126569698, -2.1351609599720054, qr[1])
circuit.u(0.9566260876600556, -1.1147561503064538, 2.0571590492298797, qr[4])
circuit.cx(qr[4], qr[1])
circuit.p(2.1899329069137394, qr[1])
circuit.u(-1.8371715243173294, 0.0, 0.0, qr[4])
circuit.cx(qr[1], qr[4])
circuit.u(0.4717053496327104, 0.0, 0.0, qr[4])
circuit.cx(qr[4], qr[1])
circuit.u(2.3167620677708145, -1.2337330260253256, -0.5671322899563955, qr[1])
circuit.u(1.0468499525240678, 0.8680750644809365, -1.4083720073192485, qr[4])
circuit.u(2.4204244021892807, -2.211701932616922, 3.8297006565735883, qr[10])
circuit.u(0.36660280497727255, 3.273119149343493, -1.8003362351299388, qr[6])
circuit.cx(qr[6], qr[10])
circuit.p(1.067395863586385, qr[10])
circuit.u(-0.7044917541291232, 0.0, 0.0, qr[6])
circuit.cx(qr[10], qr[6])
circuit.u(2.1830003849921527, 0.0, 0.0, qr[6])
circuit.cx(qr[6], qr[10])
circuit.u(2.1538343756723917, 2.2653381826084606, -3.550087952059485, qr[10])
circuit.u(1.307627685019188, -0.44686656993522567, -2.3238098554327418, qr[6])
circuit.u(2.2046797998462906, 0.9732961754855436, 1.8527865921467421, qr[9])
circuit.u(2.1665254613904126, -1.281337664694577, -1.2424905413631209, qr[0])
circuit.cx(qr[0], qr[9])
circuit.p(2.6209599970201007, qr[9])
circuit.u(0.04680566321901303, 0.0, 0.0, qr[0])
circuit.cx(qr[9], qr[0])
circuit.u(1.7728411151289603, 0.0, 0.0, qr[0])
circuit.cx(qr[0], qr[9])
circuit.u(2.4866395967434443, 0.48684511243566697, -3.0069186877854728, qr[9])
circuit.u(1.7369112924273789, -4.239660866163805, 1.0623389015296005, qr[0])
circuit.barrier(qr)
circuit.measure(qr, cr)
circuits = transpile(circuit, backend)
self.assertIsInstance(circuits, QuantumCircuit)
def test_transpiler_layout_from_intlist(self):
"""A list of ints gives layout to correctly map circuit.
virtual physical
q1_0 - 4 ---[H]---
q2_0 - 5
q2_1 - 6 ---[H]---
q3_0 - 8
q3_1 - 9
q3_2 - 10 ---[H]---
"""
qr1 = QuantumRegister(1, "qr1")
qr2 = QuantumRegister(2, "qr2")
qr3 = QuantumRegister(3, "qr3")
qc = QuantumCircuit(qr1, qr2, qr3)
qc.h(qr1[0])
qc.h(qr2[1])
qc.h(qr3[2])
layout = [4, 5, 6, 8, 9, 10]
cmap = [
[1, 0],
[1, 2],
[2, 3],
[4, 3],
[4, 10],
[5, 4],
[5, 6],
[5, 9],
[6, 8],
[7, 8],
[9, 8],
[9, 10],
[11, 3],
[11, 10],
[11, 12],
[12, 2],
[13, 1],
[13, 12],
]
new_circ = transpile(
qc, backend=None, coupling_map=cmap, basis_gates=["u2"], initial_layout=layout
)
qubit_indices = {bit: idx for idx, bit in enumerate(new_circ.qubits)}
mapped_qubits = []
for instruction in new_circ.data:
mapped_qubits.append(qubit_indices[instruction.qubits[0]])
self.assertEqual(mapped_qubits, [4, 6, 10])
def test_mapping_multi_qreg(self):
"""Test mapping works for multiple qregs."""
backend = FakeRueschlikon()
qr = QuantumRegister(3, name="qr")
qr2 = QuantumRegister(1, name="qr2")
qr3 = QuantumRegister(4, name="qr3")
cr = ClassicalRegister(3, name="cr")
qc = QuantumCircuit(qr, qr2, qr3, cr)
qc.h(qr[0])
qc.cx(qr[0], qr2[0])
qc.cx(qr[1], qr3[2])
qc.measure(qr, cr)
circuits = transpile(qc, backend)
self.assertIsInstance(circuits, QuantumCircuit)
def test_transpile_circuits_diff_registers(self):
"""Transpile list of circuits with different qreg names."""
backend = FakeRueschlikon()
circuits = []
for _ in range(2):
qr = QuantumRegister(2)
cr = ClassicalRegister(2)
circuit = QuantumCircuit(qr, cr)
circuit.h(qr[0])
circuit.cx(qr[0], qr[1])
circuit.measure(qr, cr)
circuits.append(circuit)
circuits = transpile(circuits, backend)
self.assertIsInstance(circuits[0], QuantumCircuit)
def test_wrong_initial_layout(self):
"""Test transpile with a bad initial layout."""
backend = FakeMelbourne()
qubit_reg = QuantumRegister(2, name="q")
clbit_reg = ClassicalRegister(2, name="c")
qc = QuantumCircuit(qubit_reg, clbit_reg, name="bell")
qc.h(qubit_reg[0])
qc.cx(qubit_reg[0], qubit_reg[1])
qc.measure(qubit_reg, clbit_reg)
bad_initial_layout = [
QuantumRegister(3, "q")[0],
QuantumRegister(3, "q")[1],
QuantumRegister(3, "q")[2],
]
with self.assertRaises(TranspilerError):
transpile(qc, backend, initial_layout=bad_initial_layout)
def test_parameterized_circuit_for_simulator(self):
"""Verify that a parameterized circuit can be transpiled for a simulator backend."""
qr = QuantumRegister(2, name="qr")
qc = QuantumCircuit(qr)
theta = Parameter("theta")
qc.rz(theta, qr[0])
transpiled_qc = transpile(qc, backend=BasicAer.get_backend("qasm_simulator"))
expected_qc = QuantumCircuit(qr)
expected_qc.append(RZGate(theta), [qr[0]])
self.assertEqual(expected_qc, transpiled_qc)
def test_parameterized_circuit_for_device(self):
"""Verify that a parameterized circuit can be transpiled for a device backend."""
qr = QuantumRegister(2, name="qr")
qc = QuantumCircuit(qr)
theta = Parameter("theta")
qc.rz(theta, qr[0])
transpiled_qc = transpile(
qc, backend=FakeMelbourne(), initial_layout=Layout.generate_trivial_layout(qr)
)
qr = QuantumRegister(14, "q")
expected_qc = QuantumCircuit(qr, global_phase=-1 * theta / 2.0)
expected_qc.append(U1Gate(theta), [qr[0]])
self.assertEqual(expected_qc, transpiled_qc)
def test_parameter_expression_circuit_for_simulator(self):
"""Verify that a circuit including expressions of parameters can be
transpiled for a simulator backend."""
qr = QuantumRegister(2, name="qr")
qc = QuantumCircuit(qr)
theta = Parameter("theta")
square = theta * theta
qc.rz(square, qr[0])
transpiled_qc = transpile(qc, backend=BasicAer.get_backend("qasm_simulator"))
expected_qc = QuantumCircuit(qr)
expected_qc.append(RZGate(square), [qr[0]])
self.assertEqual(expected_qc, transpiled_qc)
def test_parameter_expression_circuit_for_device(self):
"""Verify that a circuit including expressions of parameters can be
transpiled for a device backend."""
qr = QuantumRegister(2, name="qr")
qc = QuantumCircuit(qr)
theta = Parameter("theta")
square = theta * theta
qc.rz(square, qr[0])
transpiled_qc = transpile(
qc, backend=FakeMelbourne(), initial_layout=Layout.generate_trivial_layout(qr)
)
qr = QuantumRegister(14, "q")
expected_qc = QuantumCircuit(qr, global_phase=-1 * square / 2.0)
expected_qc.append(U1Gate(square), [qr[0]])
self.assertEqual(expected_qc, transpiled_qc)
def test_final_measurement_barrier_for_devices(self):
"""Verify BarrierBeforeFinalMeasurements pass is called in default pipeline for devices."""
qasm_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "qasm")
circ = QuantumCircuit.from_qasm_file(os.path.join(qasm_dir, "example.qasm"))
layout = Layout.generate_trivial_layout(*circ.qregs)
orig_pass = BarrierBeforeFinalMeasurements()
with patch.object(BarrierBeforeFinalMeasurements, "run", wraps=orig_pass.run) as mock_pass:
transpile(
circ,
coupling_map=FakeRueschlikon().configuration().coupling_map,
initial_layout=layout,
)
self.assertTrue(mock_pass.called)
def test_do_not_run_gatedirection_with_symmetric_cm(self):
"""When the coupling map is symmetric, do not run GateDirection."""
qasm_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "qasm")
circ = QuantumCircuit.from_qasm_file(os.path.join(qasm_dir, "example.qasm"))
layout = Layout.generate_trivial_layout(*circ.qregs)
coupling_map = []
for node1, node2 in FakeRueschlikon().configuration().coupling_map:
coupling_map.append([node1, node2])
coupling_map.append([node2, node1])
orig_pass = GateDirection(CouplingMap(coupling_map))
with patch.object(GateDirection, "run", wraps=orig_pass.run) as mock_pass:
transpile(circ, coupling_map=coupling_map, initial_layout=layout)
self.assertFalse(mock_pass.called)
def test_optimize_to_nothing(self):
"""Optimize gates up to fixed point in the default pipeline
See https://github.com/Qiskit/qiskit-terra/issues/2035
"""
# ┌───┐ ┌───┐┌───┐┌───┐ ┌───┐
# q0_0: ┤ H ├──■──┤ X ├┤ Y ├┤ Z ├──■──┤ H ├──■────■──
# └───┘┌─┴─┐└───┘└───┘└───┘┌─┴─┐└───┘┌─┴─┐┌─┴─┐
# q0_1: ─────┤ X ├───────────────┤ X ├─────┤ X ├┤ X ├
# └───┘ └───┘ └───┘└───┘
qr = QuantumRegister(2)
circ = QuantumCircuit(qr)
circ.h(qr[0])
circ.cx(qr[0], qr[1])
circ.x(qr[0])
circ.y(qr[0])
circ.z(qr[0])
circ.cx(qr[0], qr[1])
circ.h(qr[0])
circ.cx(qr[0], qr[1])
circ.cx(qr[0], qr[1])
after = transpile(circ, coupling_map=[[0, 1], [1, 0]], basis_gates=["u3", "u2", "u1", "cx"])
expected = QuantumCircuit(QuantumRegister(2, "q"), global_phase=-np.pi / 2)
msg = f"after:\n{after}\nexpected:\n{expected}"
self.assertEqual(after, expected, msg=msg)
def test_pass_manager_empty(self):
"""Test passing an empty PassManager() to the transpiler.
It should perform no transformations on the circuit.
"""
qr = QuantumRegister(2)
circuit = QuantumCircuit(qr)
circuit.h(qr[0])
circuit.h(qr[0])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[0], qr[1])
resources_before = circuit.count_ops()
pass_manager = PassManager()
out_circuit = pass_manager.run(circuit)
resources_after = out_circuit.count_ops()
self.assertDictEqual(resources_before, resources_after)
def test_move_measurements(self):
"""Measurements applied AFTER swap mapping."""
backend = FakeRueschlikon()
cmap = backend.configuration().coupling_map
qasm_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "qasm")
circ = QuantumCircuit.from_qasm_file(os.path.join(qasm_dir, "move_measurements.qasm"))
lay = [0, 1, 15, 2, 14, 3, 13, 4, 12, 5, 11, 6]
out = transpile(circ, initial_layout=lay, coupling_map=cmap, routing_method="stochastic")
out_dag = circuit_to_dag(out)
meas_nodes = out_dag.named_nodes("measure")
for meas_node in meas_nodes:
is_last_measure = all(
isinstance(after_measure, DAGOutNode)
for after_measure in out_dag.quantum_successors(meas_node)
)
self.assertTrue(is_last_measure)
@data(0, 1, 2, 3)
def test_init_resets_kept_preset_passmanagers(self, optimization_level):
"""Test initial resets kept at all preset transpilation levels"""
num_qubits = 5
qc = QuantumCircuit(num_qubits)
qc.reset(range(num_qubits))
num_resets = transpile(qc, optimization_level=optimization_level).count_ops()["reset"]
self.assertEqual(num_resets, num_qubits)
@data(0, 1, 2, 3)
def test_initialize_reset_is_not_removed(self, optimization_level):
"""The reset in front of initializer should NOT be removed at beginning"""
qr = QuantumRegister(1, "qr")
qc = QuantumCircuit(qr)
qc.initialize([1.0 / math.sqrt(2), 1.0 / math.sqrt(2)], [qr[0]])
qc.initialize([1.0 / math.sqrt(2), -1.0 / math.sqrt(2)], [qr[0]])
after = transpile(qc, basis_gates=["reset", "u3"], optimization_level=optimization_level)
self.assertEqual(after.count_ops()["reset"], 2, msg=f"{after}\n does not have 2 resets.")
def test_initialize_FakeMelbourne(self):
"""Test that the zero-state resets are remove in a device not supporting them."""
desired_vector = [1 / math.sqrt(2), 0, 0, 0, 0, 0, 0, 1 / math.sqrt(2)]
qr = QuantumRegister(3, "qr")
qc = QuantumCircuit(qr)
qc.initialize(desired_vector, [qr[0], qr[1], qr[2]])
out = transpile(qc, backend=FakeMelbourne())
out_dag = circuit_to_dag(out)
reset_nodes = out_dag.named_nodes("reset")
self.assertEqual(len(reset_nodes), 3)
def test_non_standard_basis(self):
"""Test a transpilation with a non-standard basis"""
qr1 = QuantumRegister(1, "q1")
qr2 = QuantumRegister(2, "q2")
qr3 = QuantumRegister(3, "q3")
qc = QuantumCircuit(qr1, qr2, qr3)
qc.h(qr1[0])
qc.h(qr2[1])
qc.h(qr3[2])
layout = [4, 5, 6, 8, 9, 10]
cmap = [
[1, 0],
[1, 2],
[2, 3],
[4, 3],
[4, 10],
[5, 4],
[5, 6],
[5, 9],
[6, 8],
[7, 8],
[9, 8],
[9, 10],
[11, 3],
[11, 10],
[11, 12],
[12, 2],
[13, 1],
[13, 12],
]
circuit = transpile(
qc, backend=None, coupling_map=cmap, basis_gates=["h"], initial_layout=layout
)
dag_circuit = circuit_to_dag(circuit)
resources_after = dag_circuit.count_ops()
self.assertEqual({"h": 3}, resources_after)
def test_hadamard_to_rot_gates(self):
"""Test a transpilation from H to Rx, Ry gates"""
qr = QuantumRegister(1)
qc = QuantumCircuit(qr)
qc.h(0)
expected = QuantumCircuit(qr, global_phase=np.pi / 2)
expected.append(RYGate(theta=np.pi / 2), [0])
expected.append(RXGate(theta=np.pi), [0])
circuit = transpile(qc, basis_gates=["rx", "ry"], optimization_level=0)
self.assertEqual(circuit, expected)
def test_basis_subset(self):
"""Test a transpilation with a basis subset of the standard basis"""
qr = QuantumRegister(1, "q1")
qc = QuantumCircuit(qr)
qc.h(qr[0])
qc.x(qr[0])
qc.t(qr[0])
layout = [4]
cmap = [
[1, 0],
[1, 2],
[2, 3],
[4, 3],
[4, 10],
[5, 4],
[5, 6],
[5, 9],
[6, 8],
[7, 8],
[9, 8],
[9, 10],
[11, 3],
[11, 10],
[11, 12],
[12, 2],
[13, 1],
[13, 12],
]
circuit = transpile(
qc, backend=None, coupling_map=cmap, basis_gates=["u3"], initial_layout=layout
)
dag_circuit = circuit_to_dag(circuit)
resources_after = dag_circuit.count_ops()
self.assertEqual({"u3": 1}, resources_after)
def test_check_circuit_width(self):
"""Verify transpilation of circuit with virtual qubits greater than
physical qubits raises error"""
cmap = [
[1, 0],
[1, 2],
[2, 3],
[4, 3],
[4, 10],
[5, 4],
[5, 6],
[5, 9],
[6, 8],
[7, 8],
[9, 8],
[9, 10],
[11, 3],
[11, 10],
[11, 12],
[12, 2],
[13, 1],
[13, 12],
]
qc = QuantumCircuit(15, 15)
with self.assertRaises(TranspilerError):
transpile(qc, coupling_map=cmap)
@data(0, 1, 2, 3)
def test_ccx_routing_method_none(self, optimization_level):
"""CCX without routing method."""
qc = QuantumCircuit(3)
qc.cx(0, 1)
qc.cx(1, 2)
out = transpile(
qc,
routing_method="none",
basis_gates=["u", "cx"],
initial_layout=[0, 1, 2],
seed_transpiler=0,
coupling_map=[[0, 1], [1, 2]],
optimization_level=optimization_level,
)
self.assertTrue(Operator(qc).equiv(out))
@data(0, 1, 2, 3)
def test_ccx_routing_method_none_failed(self, optimization_level):
"""CCX without routing method cannot be routed."""
qc = QuantumCircuit(3)
qc.ccx(0, 1, 2)
with self.assertRaises(TranspilerError):
transpile(
qc,
routing_method="none",
basis_gates=["u", "cx"],
initial_layout=[0, 1, 2],
seed_transpiler=0,
coupling_map=[[0, 1], [1, 2]],
optimization_level=optimization_level,
)
@data(0, 1, 2, 3)
def test_ms_unrolls_to_cx(self, optimization_level):
"""Verify a Rx,Ry,Rxx circuit transpile to a U3,CX target."""
qc = QuantumCircuit(2)
qc.rx(math.pi / 2, 0)
qc.ry(math.pi / 4, 1)
qc.rxx(math.pi / 4, 0, 1)
out = transpile(qc, basis_gates=["u3", "cx"], optimization_level=optimization_level)
self.assertTrue(Operator(qc).equiv(out))
@data(0, 1, 2, 3)
def test_ms_can_target_ms(self, optimization_level):
"""Verify a Rx,Ry,Rxx circuit can transpile to an Rx,Ry,Rxx target."""
qc = QuantumCircuit(2)
qc.rx(math.pi / 2, 0)
qc.ry(math.pi / 4, 1)
qc.rxx(math.pi / 4, 0, 1)
out = transpile(qc, basis_gates=["rx", "ry", "rxx"], optimization_level=optimization_level)
self.assertTrue(Operator(qc).equiv(out))
@data(0, 1, 2, 3)
def test_cx_can_target_ms(self, optimization_level):
"""Verify a U3,CX circuit can transpiler to a Rx,Ry,Rxx target."""
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
qc.rz(math.pi / 4, [0, 1])
out = transpile(qc, basis_gates=["rx", "ry", "rxx"], optimization_level=optimization_level)
self.assertTrue(Operator(qc).equiv(out))
@data(0, 1, 2, 3)
def test_measure_doesnt_unroll_ms(self, optimization_level):
"""Verify a measure doesn't cause an Rx,Ry,Rxx circuit to unroll to U3,CX."""
qc = QuantumCircuit(2, 2)
qc.rx(math.pi / 2, 0)
qc.ry(math.pi / 4, 1)
qc.rxx(math.pi / 4, 0, 1)
qc.measure([0, 1], [0, 1])
out = transpile(qc, basis_gates=["rx", "ry", "rxx"], optimization_level=optimization_level)
self.assertEqual(qc, out)
@data(
["cx", "u3"],
["cz", "u3"],
["cz", "rx", "rz"],
["rxx", "rx", "ry"],
["iswap", "rx", "rz"],
)
def test_block_collection_runs_for_non_cx_bases(self, basis_gates):
"""Verify block collection is run when a single two qubit gate is in the basis."""
twoq_gate, *_ = basis_gates
qc = QuantumCircuit(2)
qc.cx(0, 1)
qc.cx(1, 0)
qc.cx(0, 1)
qc.cx(0, 1)
out = transpile(qc, basis_gates=basis_gates, optimization_level=3)
self.assertLessEqual(out.count_ops()[twoq_gate], 2)
@unpack
@data(
(["u3", "cx"], {"u3": 1, "cx": 1}),
(["rx", "rz", "iswap"], {"rx": 6, "rz": 12, "iswap": 2}),
(["rx", "ry", "rxx"], {"rx": 6, "ry": 5, "rxx": 1}),
)
def test_block_collection_reduces_1q_gate(self, basis_gates, gate_counts):
"""For synthesis to non-U3 bases, verify we minimize 1q gates."""
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
out = transpile(qc, basis_gates=basis_gates, optimization_level=3)
self.assertTrue(Operator(out).equiv(qc))
self.assertTrue(set(out.count_ops()).issubset(basis_gates))
for basis_gate in basis_gates:
self.assertLessEqual(out.count_ops()[basis_gate], gate_counts[basis_gate])
@combine(
optimization_level=[0, 1, 2, 3],
basis_gates=[
["u3", "cx"],
["rx", "rz", "iswap"],
["rx", "ry", "rxx"],
],
)
def test_translation_method_synthesis(self, optimization_level, basis_gates):
"""Verify translation_method='synthesis' gets to the basis."""
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
out = transpile(
qc,
translation_method="synthesis",
basis_gates=basis_gates,
optimization_level=optimization_level,
)
self.assertTrue(Operator(out).equiv(qc))
self.assertTrue(set(out.count_ops()).issubset(basis_gates))
def test_transpiled_custom_gates_calibration(self):
"""Test if transpiled calibrations is equal to custom gates circuit calibrations."""
custom_180 = Gate("mycustom", 1, [3.14])
custom_90 = Gate("mycustom", 1, [1.57])
circ = QuantumCircuit(2)
circ.append(custom_180, [0])
circ.append(custom_90, [1])
with pulse.build() as q0_x180:
pulse.play(pulse.library.Gaussian(20, 1.0, 3.0), pulse.DriveChannel(0))
with pulse.build() as q1_y90:
pulse.play(pulse.library.Gaussian(20, -1.0, 3.0), pulse.DriveChannel(1))
# Add calibration
circ.add_calibration(custom_180, [0], q0_x180)
circ.add_calibration(custom_90, [1], q1_y90)
backend = FakeBoeblingen()
transpiled_circuit = transpile(
circ,
backend=backend,
layout_method="trivial",
)
self.assertEqual(transpiled_circuit.calibrations, circ.calibrations)
self.assertEqual(list(transpiled_circuit.count_ops().keys()), ["mycustom"])
self.assertEqual(list(transpiled_circuit.count_ops().values()), [2])
def test_transpiled_basis_gates_calibrations(self):
"""Test if the transpiled calibrations is equal to basis gates circuit calibrations."""
circ = QuantumCircuit(2)
circ.h(0)
with pulse.build() as q0_x180:
pulse.play(pulse.library.Gaussian(20, 1.0, 3.0), pulse.DriveChannel(0))
# Add calibration
circ.add_calibration("h", [0], q0_x180)
backend = FakeBoeblingen()
transpiled_circuit = transpile(
circ,
backend=backend,
)
self.assertEqual(transpiled_circuit.calibrations, circ.calibrations)
def test_transpile_calibrated_custom_gate_on_diff_qubit(self):
"""Test if the custom, non calibrated gate raises QiskitError."""
custom_180 = Gate("mycustom", 1, [3.14])
circ = QuantumCircuit(2)
circ.append(custom_180, [0])
with pulse.build() as q0_x180:
pulse.play(pulse.library.Gaussian(20, 1.0, 3.0), pulse.DriveChannel(0))
# Add calibration
circ.add_calibration(custom_180, [1], q0_x180)
backend = FakeBoeblingen()
with self.assertRaises(QiskitError):
transpile(circ, backend=backend, layout_method="trivial")
def test_transpile_calibrated_nonbasis_gate_on_diff_qubit(self):
"""Test if the non-basis gates are transpiled if they are on different qubit that
is not calibrated."""
circ = QuantumCircuit(2)
circ.h(0)
circ.h(1)
with pulse.build() as q0_x180:
pulse.play(pulse.library.Gaussian(20, 1.0, 3.0), pulse.DriveChannel(0))
# Add calibration
circ.add_calibration("h", [1], q0_x180)
backend = FakeBoeblingen()
transpiled_circuit = transpile(
circ,
backend=backend,
)
self.assertEqual(transpiled_circuit.calibrations, circ.calibrations)
self.assertEqual(set(transpiled_circuit.count_ops().keys()), {"u2", "h"})
def test_transpile_subset_of_calibrated_gates(self):
"""Test transpiling a circuit with both basis gate (not-calibrated) and
a calibrated gate on different qubits."""
x_180 = Gate("mycustom", 1, [3.14])
circ = QuantumCircuit(2)
circ.h(0)
circ.append(x_180, [0])
circ.h(1)
with pulse.build() as q0_x180:
pulse.play(pulse.library.Gaussian(20, 1.0, 3.0), pulse.DriveChannel(0))
circ.add_calibration(x_180, [0], q0_x180)
circ.add_calibration("h", [1], q0_x180) # 'h' is calibrated on qubit 1
transpiled_circ = transpile(circ, FakeBoeblingen(), layout_method="trivial")
self.assertEqual(set(transpiled_circ.count_ops().keys()), {"u2", "mycustom", "h"})
def test_parameterized_calibrations_transpile(self):
"""Check that gates can be matched to their calibrations before and after parameter
assignment."""
tau = Parameter("tau")
circ = QuantumCircuit(3, 3)
circ.append(Gate("rxt", 1, [2 * 3.14 * tau]), [0])
def q0_rxt(tau):
with pulse.build() as q0_rxt:
pulse.play(pulse.library.Gaussian(20, 0.4 * tau, 3.0), pulse.DriveChannel(0))
return q0_rxt
circ.add_calibration("rxt", [0], q0_rxt(tau), [2 * 3.14 * tau])
transpiled_circ = transpile(circ, FakeBoeblingen(), layout_method="trivial")
self.assertEqual(set(transpiled_circ.count_ops().keys()), {"rxt"})
circ = circ.assign_parameters({tau: 1})
transpiled_circ = transpile(circ, FakeBoeblingen(), layout_method="trivial")
self.assertEqual(set(transpiled_circ.count_ops().keys()), {"rxt"})
def test_inst_durations_from_calibrations(self):
"""Test that circuit calibrations can be used instead of explicitly
supplying inst_durations.
"""
qc = QuantumCircuit(2)
qc.append(Gate("custom", 1, []), [0])
with pulse.build() as cal:
pulse.play(pulse.library.Gaussian(20, 1.0, 3.0), pulse.DriveChannel(0))
qc.add_calibration("custom", [0], cal)
out = transpile(qc, scheduling_method="alap")
self.assertEqual(out.duration, cal.duration)
@data(0, 1, 2, 3)
def test_multiqubit_gates_calibrations(self, opt_level):
"""Test multiqubit gate > 2q with calibrations works
Adapted from issue description in https://github.com/Qiskit/qiskit-terra/issues/6572
"""
circ = QuantumCircuit(5)
custom_gate = Gate("my_custom_gate", 5, [])
circ.append(custom_gate, [0, 1, 2, 3, 4])
circ.measure_all()
backend = FakeBoeblingen()
with pulse.build(backend, name="custom") as my_schedule:
pulse.play(
pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.drive_channel(0)
)
pulse.play(
pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.drive_channel(1)
)
pulse.play(
pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.drive_channel(2)
)
pulse.play(
pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.drive_channel(3)
)
pulse.play(
pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.drive_channel(4)
)
pulse.play(
pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.ControlChannel(1)
)
pulse.play(
pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.ControlChannel(2)
)
pulse.play(
pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.ControlChannel(3)
)
pulse.play(
pulse.library.Gaussian(duration=128, amp=0.1, sigma=16), pulse.ControlChannel(4)
)
circ.add_calibration("my_custom_gate", [0, 1, 2, 3, 4], my_schedule, [])
trans_circ = transpile(circ, backend, optimization_level=opt_level, layout_method="trivial")
self.assertEqual({"measure": 5, "my_custom_gate": 1, "barrier": 1}, trans_circ.count_ops())
@data(0, 1, 2, 3)
def test_circuit_with_delay(self, optimization_level):
"""Verify a circuit with delay can transpile to a scheduled circuit."""
qc = QuantumCircuit(2)
qc.h(0)
qc.delay(500, 1)
qc.cx(0, 1)
out = transpile(
qc,
scheduling_method="alap",
basis_gates=["h", "cx"],
instruction_durations=[("h", 0, 200), ("cx", [0, 1], 700)],
optimization_level=optimization_level,
)
self.assertEqual(out.duration, 1200)
def test_delay_converts_to_dt(self):
"""Test that a delay instruction is converted to units of dt given a backend."""
qc = QuantumCircuit(2)
qc.delay(1000, [0], unit="us")
backend = FakeRueschlikon()
backend.configuration().dt = 0.5e-6
out = transpile([qc, qc], backend)
self.assertEqual(out[0].data[0].operation.unit, "dt")
self.assertEqual(out[1].data[0].operation.unit, "dt")
out = transpile(qc, dt=1e-9)
self.assertEqual(out.data[0].operation.unit, "dt")
def test_scheduling_backend_v2(self):
"""Test that scheduling method works with Backendv2."""
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
qc.measure_all()
backend = FakeMumbaiV2()
out = transpile([qc, qc], backend, scheduling_method="alap")
self.assertIn("delay", out[0].count_ops())
self.assertIn("delay", out[1].count_ops())
@data(1, 2, 3)
def test_no_infinite_loop(self, optimization_level):
"""Verify circuit cost always descends and optimization does not flip flop indefinitely."""
qc = QuantumCircuit(1)
qc.ry(0.2, 0)
out = transpile(
qc, basis_gates=["id", "p", "sx", "cx"], optimization_level=optimization_level
)
# Expect a -pi/2 global phase for the U3 to RZ/SX conversion, and
# a -0.5 * theta phase for RZ to P twice, once at theta, and once at 3 pi
# for the second and third RZ gates in the U3 decomposition.
expected = QuantumCircuit(
1, global_phase=-np.pi / 2 - 0.5 * (-0.2 + np.pi) - 0.5 * 3 * np.pi
)
expected.p(-np.pi, 0)
expected.sx(0)
expected.p(np.pi - 0.2, 0)
expected.sx(0)
error_message = (
f"\nOutput circuit:\n{out!s}\n{Operator(out).data}\n"
f"Expected circuit:\n{expected!s}\n{Operator(expected).data}"
)
self.assertEqual(out, expected, error_message)
@data(0, 1, 2, 3)
def test_transpile_preserves_circuit_metadata(self, optimization_level):
"""Verify that transpile preserves circuit metadata in the output."""
circuit = QuantumCircuit(2, metadata={"experiment_id": "1234", "execution_number": 4})
circuit.h(0)
circuit.cx(0, 1)
cmap = [
[1, 0],
[1, 2],
[2, 3],
[4, 3],
[4, 10],
[5, 4],
[5, 6],
[5, 9],
[6, 8],
[7, 8],
[9, 8],
[9, 10],
[11, 3],
[11, 10],
[11, 12],
[12, 2],
[13, 1],
[13, 12],
]
res = transpile(
circuit,
basis_gates=["id", "p", "sx", "cx"],
coupling_map=cmap,
optimization_level=optimization_level,
)
self.assertEqual(circuit.metadata, res.metadata)
@data(0, 1, 2, 3)
def test_transpile_optional_registers(self, optimization_level):
"""Verify transpile accepts circuits without registers end-to-end."""
qubits = [Qubit() for _ in range(3)]
clbits = [Clbit() for _ in range(3)]
qc = QuantumCircuit(qubits, clbits)
qc.h(0)
qc.cx(0, 1)
qc.cx(1, 2)
qc.measure(qubits, clbits)
out = transpile(qc, FakeBoeblingen(), optimization_level=optimization_level)
self.assertEqual(len(out.qubits), FakeBoeblingen().configuration().num_qubits)
self.assertEqual(len(out.clbits), len(clbits))
@data(0, 1, 2, 3)
def test_translate_ecr_basis(self, optimization_level):
"""Verify that rewriting in ECR basis is efficient."""
circuit = QuantumCircuit(2)
circuit.append(random_unitary(4, seed=1), [0, 1])
circuit.barrier()
circuit.cx(0, 1)
circuit.barrier()
circuit.swap(0, 1)
circuit.barrier()
circuit.iswap(0, 1)
res = transpile(circuit, basis_gates=["u", "ecr"], optimization_level=optimization_level)
self.assertEqual(res.count_ops()["ecr"], 9)
self.assertTrue(Operator(res).equiv(circuit))
def test_optimize_ecr_basis(self):
"""Test highest optimization level can optimize over ECR."""
circuit = QuantumCircuit(2)
circuit.swap(1, 0)
circuit.iswap(0, 1)
res = transpile(circuit, basis_gates=["u", "ecr"], optimization_level=3)
self.assertEqual(res.count_ops()["ecr"], 1)
self.assertTrue(Operator(res).equiv(circuit))
def test_approximation_degree_invalid(self):
"""Test invalid approximation degree raises."""
circuit = QuantumCircuit(2)
circuit.swap(0, 1)
with self.assertRaises(QiskitError):
transpile(circuit, basis_gates=["u", "cz"], approximation_degree=1.1)
def test_approximation_degree(self):
"""Test more approximation gives lower-cost circuit."""
circuit = QuantumCircuit(2)
circuit.swap(0, 1)
circuit.h(0)
circ_10 = transpile(
circuit,
basis_gates=["u", "cx"],
translation_method="synthesis",
approximation_degree=0.1,
)
circ_90 = transpile(
circuit,
basis_gates=["u", "cx"],
translation_method="synthesis",
approximation_degree=0.9,
)
self.assertLess(circ_10.depth(), circ_90.depth())
@data(0, 1, 2, 3)
def test_synthesis_translation_method_with_single_qubit_gates(self, optimization_level):
"""Test that synthesis basis translation works for solely 1q circuit"""
qc = QuantumCircuit(3)
qc.h(0)
qc.h(1)
qc.h(2)
res = transpile(
qc,
basis_gates=["id", "rz", "x", "sx", "cx"],
translation_method="synthesis",
optimization_level=optimization_level,
)
expected = QuantumCircuit(3, global_phase=3 * np.pi / 4)
expected.rz(np.pi / 2, 0)
expected.rz(np.pi / 2, 1)
expected.rz(np.pi / 2, 2)
expected.sx(0)
expected.sx(1)
expected.sx(2)
expected.rz(np.pi / 2, 0)
expected.rz(np.pi / 2, 1)
expected.rz(np.pi / 2, 2)
self.assertEqual(res, expected)
@data(0, 1, 2, 3)
def test_synthesis_translation_method_with_gates_outside_basis(self, optimization_level):
"""Test that synthesis translation works for circuits with single gates outside bassis"""
qc = QuantumCircuit(2)
qc.swap(0, 1)
res = transpile(
qc,
basis_gates=["id", "rz", "x", "sx", "cx"],
translation_method="synthesis",
optimization_level=optimization_level,
)
if optimization_level != 3:
self.assertTrue(Operator(qc).equiv(res))
self.assertNotIn("swap", res.count_ops())
else:
# Optimization level 3 eliminates the pointless swap
self.assertEqual(res, QuantumCircuit(2))
@data(0, 1, 2, 3)
def test_target_ideal_gates(self, opt_level):
"""Test that transpile() with a custom ideal sim target works."""
theta = Parameter("θ")
phi = Parameter("ϕ")
lam = Parameter("λ")
target = Target(num_qubits=2)
target.add_instruction(UGate(theta, phi, lam), {(0,): None, (1,): None})
target.add_instruction(CXGate(), {(0, 1): None})
target.add_instruction(Measure(), {(0,): None, (1,): None})
qubit_reg = QuantumRegister(2, name="q")
clbit_reg = ClassicalRegister(2, name="c")
qc = QuantumCircuit(qubit_reg, clbit_reg, name="bell")
qc.h(qubit_reg[0])
qc.cx(qubit_reg[0], qubit_reg[1])
result = transpile(qc, target=target, optimization_level=opt_level)
self.assertEqual(Operator.from_circuit(result), Operator.from_circuit(qc))
@data(0, 1, 2, 3)
def test_transpile_with_custom_control_flow_target(self, opt_level):
"""Test transpile() with a target and constrol flow ops."""
target = FakeMumbaiV2().target
target.add_instruction(ForLoopOp, name="for_loop")
target.add_instruction(WhileLoopOp, name="while_loop")
target.add_instruction(IfElseOp, name="if_else")
target.add_instruction(SwitchCaseOp, name="switch_case")
circuit = QuantumCircuit(6, 1)
circuit.h(0)
circuit.measure(0, 0)
circuit.cx(0, 1)
circuit.cz(0, 2)
circuit.append(CustomCX(), [1, 2], [])
with circuit.for_loop((1,)):
circuit.cx(0, 1)
circuit.cz(0, 2)
circuit.append(CustomCX(), [1, 2], [])
with circuit.if_test((circuit.clbits[0], True)) as else_:
circuit.cx(0, 1)
circuit.cz(0, 2)
circuit.append(CustomCX(), [1, 2], [])
with else_:
circuit.cx(3, 4)
circuit.cz(3, 5)
circuit.append(CustomCX(), [4, 5], [])
with circuit.while_loop((circuit.clbits[0], True)):
circuit.cx(3, 4)
circuit.cz(3, 5)
circuit.append(CustomCX(), [4, 5], [])
with circuit.switch(circuit.cregs[0]) as case_:
with case_(0):
circuit.cx(0, 1)
circuit.cz(0, 2)
circuit.append(CustomCX(), [1, 2], [])
with case_(1):
circuit.cx(1, 2)
circuit.cz(1, 3)
circuit.append(CustomCX(), [2, 3], [])
transpiled = transpile(
circuit, optimization_level=opt_level, target=target, seed_transpiler=12434
)
# Tests of the complete validity of a circuit are mostly done at the indiviual pass level;
# here we're just checking that various passes do appear to have run.
self.assertIsInstance(transpiled, QuantumCircuit)
# Assert layout ran.
self.assertIsNot(getattr(transpiled, "_layout", None), None)
def _visit_block(circuit, qubit_mapping=None):
for instruction in circuit:
qargs = tuple(qubit_mapping[x] for x in instruction.qubits)
self.assertTrue(target.instruction_supported(instruction.operation.name, qargs))
if isinstance(instruction.operation, ControlFlowOp):
for block in instruction.operation.blocks:
new_mapping = {
inner: qubit_mapping[outer]
for outer, inner in zip(instruction.qubits, block.qubits)
}
_visit_block(block, new_mapping)
# Assert unrolling ran.
self.assertNotIsInstance(instruction.operation, CustomCX)
# Assert translation ran.
self.assertNotIsInstance(instruction.operation, CZGate)
# Assert routing ran.
_visit_block(
transpiled,
qubit_mapping={qubit: index for index, qubit in enumerate(transpiled.qubits)},
)
@data(1, 2, 3)
def test_transpile_identity_circuit_no_target(self, opt_level):
"""Test circuit equivalent to identity is optimized away for all optimization levels >0.
Reproduce taken from https://github.com/Qiskit/qiskit-terra/issues/9217
"""
qr1 = QuantumRegister(3, "state")
qr2 = QuantumRegister(2, "ancilla")
cr = ClassicalRegister(2, "c")
qc = QuantumCircuit(qr1, qr2, cr)
qc.h(qr1[0])
qc.cx(qr1[0], qr1[1])
qc.cx(qr1[1], qr1[2])
qc.cx(qr1[1], qr1[2])
qc.cx(qr1[0], qr1[1])
qc.h(qr1[0])
empty_qc = QuantumCircuit(qr1, qr2, cr)
result = transpile(qc, optimization_level=opt_level)
self.assertEqual(empty_qc, result)
@data(0, 1, 2, 3)
def test_initial_layout_with_loose_qubits(self, opt_level):
"""Regression test of gh-10125."""
qc = QuantumCircuit([Qubit(), Qubit()])
qc.cx(0, 1)
transpiled = transpile(qc, initial_layout=[1, 0], optimization_level=opt_level)
self.assertIsNotNone(transpiled.layout)
self.assertEqual(
transpiled.layout.initial_layout, Layout({0: qc.qubits[1], 1: qc.qubits[0]})
)
@data(0, 1, 2, 3)
def test_initial_layout_with_overlapping_qubits(self, opt_level):
"""Regression test of gh-10125."""
qr1 = QuantumRegister(2, "qr1")
qr2 = QuantumRegister(bits=qr1[:])
qc = QuantumCircuit(qr1, qr2)
qc.cx(0, 1)
transpiled = transpile(qc, initial_layout=[1, 0], optimization_level=opt_level)
self.assertIsNotNone(transpiled.layout)
self.assertEqual(
transpiled.layout.initial_layout, Layout({0: qc.qubits[1], 1: qc.qubits[0]})
)
@combine(opt_level=[0, 1, 2, 3], basis=[["rz", "x"], ["rx", "z"], ["rz", "y"], ["ry", "x"]])
def test_paulis_to_constrained_1q_basis(self, opt_level, basis):
"""Test that Pauli-gate circuits can be transpiled to constrained 1q bases that do not
contain any root-Pauli gates."""
qc = QuantumCircuit(1)
qc.x(0)
qc.barrier()
qc.y(0)
qc.barrier()
qc.z(0)
transpiled = transpile(qc, basis_gates=basis, optimization_level=opt_level)
self.assertGreaterEqual(set(basis) | {"barrier"}, transpiled.count_ops().keys())
self.assertEqual(Operator(qc), Operator(transpiled))
@ddt
class TestPostTranspileIntegration(QiskitTestCase):
"""Test that the output of `transpile` is usable in various other integration contexts."""
def _regular_circuit(self):
a = Parameter("a")
regs = [
QuantumRegister(2, name="q0"),
QuantumRegister(3, name="q1"),
ClassicalRegister(2, name="c0"),
]
bits = [Qubit(), Qubit(), Clbit()]
base = QuantumCircuit(*regs, bits)
base.h(0)
base.measure(0, 0)
base.cx(0, 1)
base.cz(0, 2)
base.cz(0, 3)
base.cz(1, 4)
base.cx(1, 5)
base.measure(1, 1)
base.append(CustomCX(), [3, 6])
base.append(CustomCX(), [5, 4])
base.append(CustomCX(), [5, 3])
base.append(CustomCX(), [2, 4]).c_if(base.cregs[0], 3)
base.ry(a, 4)
base.measure(4, 2)
return base
def _control_flow_circuit(self):
a = Parameter("a")
regs = [
QuantumRegister(2, name="q0"),
QuantumRegister(3, name="q1"),
ClassicalRegister(2, name="c0"),
]
bits = [Qubit(), Qubit(), Clbit()]
base = QuantumCircuit(*regs, bits)
base.h(0)
base.measure(0, 0)
with base.if_test((base.cregs[0], 1)) as else_:
base.cx(0, 1)
base.cz(0, 2)
base.cz(0, 3)
with else_:
base.cz(1, 4)
with base.for_loop((1, 2)):
base.cx(1, 5)
base.measure(2, 2)
with base.while_loop((2, False)):
base.append(CustomCX(), [3, 6])
base.append(CustomCX(), [5, 4])
base.append(CustomCX(), [5, 3])
base.append(CustomCX(), [2, 4])
base.ry(a, 4)
base.measure(4, 2)
with base.switch(base.cregs[0]) as case_:
with case_(0, 1):
base.cz(3, 5)
with case_(case_.DEFAULT):
base.cz(1, 4)
base.append(CustomCX(), [2, 4])
base.append(CustomCX(), [3, 4])
return base
def _control_flow_expr_circuit(self):
a = Parameter("a")
regs = [
QuantumRegister(2, name="q0"),
QuantumRegister(3, name="q1"),
ClassicalRegister(2, name="c0"),
]
bits = [Qubit(), Qubit(), Clbit()]
base = QuantumCircuit(*regs, bits)
base.h(0)
base.measure(0, 0)
with base.if_test(expr.equal(base.cregs[0], 1)) as else_:
base.cx(0, 1)
base.cz(0, 2)
base.cz(0, 3)
with else_:
base.cz(1, 4)
with base.for_loop((1, 2)):
base.cx(1, 5)
base.measure(2, 2)
with base.while_loop(expr.logic_not(bits[2])):
base.append(CustomCX(), [3, 6])
base.append(CustomCX(), [5, 4])
base.append(CustomCX(), [5, 3])
base.append(CustomCX(), [2, 4])
base.ry(a, 4)
base.measure(4, 2)
with base.switch(expr.bit_and(base.cregs[0], 2)) as case_:
with case_(0, 1):
base.cz(3, 5)
with case_(case_.DEFAULT):
base.cz(1, 4)
base.append(CustomCX(), [2, 4])
base.append(CustomCX(), [3, 4])
return base
@data(0, 1, 2, 3)
def test_qpy_roundtrip(self, optimization_level):
"""Test that the output of a transpiled circuit can be round-tripped through QPY."""
transpiled = transpile(
self._regular_circuit(),
backend=FakeMelbourne(),
optimization_level=optimization_level,
seed_transpiler=2022_10_17,
)
# Round-tripping the layout is out-of-scope for QPY while it's a private attribute.
transpiled._layout = None
buffer = io.BytesIO()
qpy.dump(transpiled, buffer)
buffer.seek(0)
round_tripped = qpy.load(buffer)[0]
self.assertEqual(round_tripped, transpiled)
@data(0, 1, 2, 3)
def test_qpy_roundtrip_backendv2(self, optimization_level):
"""Test that the output of a transpiled circuit can be round-tripped through QPY."""
transpiled = transpile(
self._regular_circuit(),
backend=FakeMumbaiV2(),
optimization_level=optimization_level,
seed_transpiler=2022_10_17,
)
# Round-tripping the layout is out-of-scope for QPY while it's a private attribute.
transpiled._layout = None
buffer = io.BytesIO()
qpy.dump(transpiled, buffer)
buffer.seek(0)
round_tripped = qpy.load(buffer)[0]
self.assertEqual(round_tripped, transpiled)
@data(0, 1, 2, 3)
def test_qpy_roundtrip_control_flow(self, optimization_level):
"""Test that the output of a transpiled circuit with control flow can be round-tripped
through QPY."""
if optimization_level == 3 and sys.platform == "win32":
self.skipTest(
"This test case triggers a bug in the eigensolver routine on windows. "
"See #10345 for more details."
)
backend = FakeMelbourne()
transpiled = transpile(
self._control_flow_circuit(),
backend=backend,
basis_gates=backend.configuration().basis_gates
+ ["if_else", "for_loop", "while_loop", "switch_case"],
optimization_level=optimization_level,
seed_transpiler=2022_10_17,
)
# Round-tripping the layout is out-of-scope for QPY while it's a private attribute.
transpiled._layout = None
buffer = io.BytesIO()
qpy.dump(transpiled, buffer)
buffer.seek(0)
round_tripped = qpy.load(buffer)[0]
self.assertEqual(round_tripped, transpiled)
@data(0, 1, 2, 3)
def test_qpy_roundtrip_control_flow_backendv2(self, optimization_level):
"""Test that the output of a transpiled circuit with control flow can be round-tripped
through QPY."""
backend = FakeMumbaiV2()
backend.target.add_instruction(IfElseOp, name="if_else")
backend.target.add_instruction(ForLoopOp, name="for_loop")
backend.target.add_instruction(WhileLoopOp, name="while_loop")
backend.target.add_instruction(SwitchCaseOp, name="switch_case")
transpiled = transpile(
self._control_flow_circuit(),
backend=backend,
optimization_level=optimization_level,
seed_transpiler=2022_10_17,
)
# Round-tripping the layout is out-of-scope for QPY while it's a private attribute.
transpiled._layout = None
buffer = io.BytesIO()
qpy.dump(transpiled, buffer)
buffer.seek(0)
round_tripped = qpy.load(buffer)[0]
self.assertEqual(round_tripped, transpiled)
@data(0, 1, 2, 3)
def test_qpy_roundtrip_control_flow_expr(self, optimization_level):
"""Test that the output of a transpiled circuit with control flow including `Expr` nodes can
be round-tripped through QPY."""
if optimization_level == 3 and sys.platform == "win32":
self.skipTest(
"This test case triggers a bug in the eigensolver routine on windows. "
"See #10345 for more details."
)
backend = FakeMelbourne()
transpiled = transpile(
self._control_flow_expr_circuit(),
backend=backend,
basis_gates=backend.configuration().basis_gates
+ ["if_else", "for_loop", "while_loop", "switch_case"],
optimization_level=optimization_level,
seed_transpiler=2023_07_26,
)
buffer = io.BytesIO()
qpy.dump(transpiled, buffer)
buffer.seek(0)
round_tripped = qpy.load(buffer)[0]
self.assertEqual(round_tripped, transpiled)
@data(0, 1, 2, 3)
def test_qpy_roundtrip_control_flow_expr_backendv2(self, optimization_level):
"""Test that the output of a transpiled circuit with control flow including `Expr` nodes can
be round-tripped through QPY."""
backend = FakeMumbaiV2()
backend.target.add_instruction(IfElseOp, name="if_else")
backend.target.add_instruction(ForLoopOp, name="for_loop")
backend.target.add_instruction(WhileLoopOp, name="while_loop")
backend.target.add_instruction(SwitchCaseOp, name="switch_case")
transpiled = transpile(
self._control_flow_circuit(),
backend=backend,
optimization_level=optimization_level,
seed_transpiler=2023_07_26,
)
buffer = io.BytesIO()
qpy.dump(transpiled, buffer)
buffer.seek(0)
round_tripped = qpy.load(buffer)[0]
self.assertEqual(round_tripped, transpiled)
@data(0, 1, 2, 3)
def test_qasm3_output(self, optimization_level):
"""Test that the output of a transpiled circuit can be dumped into OpenQASM 3."""
transpiled = transpile(
self._regular_circuit(),
backend=FakeMelbourne(),
optimization_level=optimization_level,
seed_transpiler=2022_10_17,
)
# TODO: There's not a huge amount we can sensibly test for the output here until we can
# round-trip the OpenQASM 3 back into a Terra circuit. Mostly we're concerned that the dump
# itself doesn't throw an error, though.
self.assertIsInstance(qasm3.dumps(transpiled).strip(), str)
@data(0, 1, 2, 3)
def test_qasm3_output_control_flow(self, optimization_level):
"""Test that the output of a transpiled circuit with control flow can be dumped into
OpenQASM 3."""
backend = FakeMumbaiV2()
backend.target.add_instruction(IfElseOp, name="if_else")
backend.target.add_instruction(ForLoopOp, name="for_loop")
backend.target.add_instruction(WhileLoopOp, name="while_loop")
backend.target.add_instruction(SwitchCaseOp, name="switch_case")
transpiled = transpile(
self._control_flow_circuit(),
backend=backend,
optimization_level=optimization_level,
seed_transpiler=2022_10_17,
)
# TODO: There's not a huge amount we can sensibly test for the output here until we can
# round-trip the OpenQASM 3 back into a Terra circuit. Mostly we're concerned that the dump
# itself doesn't throw an error, though.
self.assertIsInstance(
qasm3.dumps(transpiled, experimental=qasm3.ExperimentalFeatures.SWITCH_CASE_V1).strip(),
str,
)
@data(0, 1, 2, 3)
def test_qasm3_output_control_flow_expr(self, optimization_level):
"""Test that the output of a transpiled circuit with control flow and `Expr` nodes can be
dumped into OpenQASM 3."""
backend = FakeMumbaiV2()
backend.target.add_instruction(IfElseOp, name="if_else")
backend.target.add_instruction(ForLoopOp, name="for_loop")
backend.target.add_instruction(WhileLoopOp, name="while_loop")
backend.target.add_instruction(SwitchCaseOp, name="switch_case")
transpiled = transpile(
self._control_flow_circuit(),
backend=backend,
optimization_level=optimization_level,
seed_transpiler=2023_07_26,
)
# TODO: There's not a huge amount we can sensibly test for the output here until we can
# round-trip the OpenQASM 3 back into a Terra circuit. Mostly we're concerned that the dump
# itself doesn't throw an error, though.
self.assertIsInstance(
qasm3.dumps(transpiled, experimental=qasm3.ExperimentalFeatures.SWITCH_CASE_V1).strip(),
str,
)
@data(0, 1, 2, 3)
def test_transpile_target_no_measurement_error(self, opt_level):
"""Test that transpile with a target which contains ideal measurement works
Reproduce from https://github.com/Qiskit/qiskit-terra/issues/8969
"""
target = Target()
target.add_instruction(Measure(), {(0,): None})
qc = QuantumCircuit(1, 1)
qc.measure(0, 0)
res = transpile(qc, target=target, optimization_level=opt_level)
self.assertEqual(qc, res)
def test_transpile_final_layout_updated_with_post_layout(self):
"""Test that the final layout is correctly set when vf2postlayout runs.
Reproduce from #10457
"""
def _get_index_layout(transpiled_circuit: QuantumCircuit, num_source_qubits: int):
"""Return the index layout of a transpiled circuit"""
layout = transpiled_circuit.layout
if layout is None:
return list(range(num_source_qubits))
pos_to_virt = {v: k for k, v in layout.input_qubit_mapping.items()}
qubit_indices = []
for index in range(num_source_qubits):
qubit_idx = layout.initial_layout[pos_to_virt[index]]
if layout.final_layout is not None:
qubit_idx = layout.final_layout[transpiled_circuit.qubits[qubit_idx]]
qubit_indices.append(qubit_idx)
return qubit_indices
vf2_post_layout_called = False
def callback(**kwargs):
nonlocal vf2_post_layout_called
if isinstance(kwargs["pass_"], VF2PostLayout):
vf2_post_layout_called = True
self.assertIsNotNone(kwargs["property_set"]["post_layout"])
backend = FakeVigo()
qubits = 3
qc = QuantumCircuit(qubits)
for i in range(5):
qc.cx(i % qubits, int(i + qubits / 2) % qubits)
tqc = transpile(qc, backend=backend, seed_transpiler=4242, callback=callback)
self.assertTrue(vf2_post_layout_called)
self.assertEqual([3, 2, 1], _get_index_layout(tqc, qubits))
class StreamHandlerRaiseException(StreamHandler):
"""Handler class that will raise an exception on formatting errors."""
def handleError(self, record):
raise sys.exc_info()
class TestLogTranspile(QiskitTestCase):
"""Testing the log_transpile option."""
def setUp(self):
super().setUp()
logger = getLogger()
self.addCleanup(logger.setLevel, logger.level)
logger.setLevel("DEBUG")
self.output = io.StringIO()
logger.addHandler(StreamHandlerRaiseException(self.output))
self.circuit = QuantumCircuit(QuantumRegister(1))
def assertTranspileLog(self, log_msg):
"""Runs the transpiler and check for logs containing specified message"""
transpile(self.circuit)
self.output.seek(0)
# Filter unrelated log lines
output_lines = self.output.readlines()
transpile_log_lines = [x for x in output_lines if log_msg in x]
self.assertTrue(len(transpile_log_lines) > 0)
def test_transpile_log_time(self):
"""Check Total Transpile Time is logged"""
self.assertTranspileLog("Total Transpile Time")
class TestTranspileCustomPM(QiskitTestCase):
"""Test transpile function with custom pass manager"""
def test_custom_multiple_circuits(self):
"""Test transpiling with custom pass manager and multiple circuits.
This tests created a deadlock, so it needs to be monitored for timeout.
See: https://github.com/Qiskit/qiskit-terra/issues/3925
"""
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
pm_conf = PassManagerConfig(
initial_layout=None,
basis_gates=["u1", "u2", "u3", "cx"],
coupling_map=CouplingMap([[0, 1]]),
backend_properties=None,
seed_transpiler=1,
)
passmanager = level_0_pass_manager(pm_conf)
transpiled = passmanager.run([qc, qc])
expected = QuantumCircuit(QuantumRegister(2, "q"))
expected.append(U2Gate(0, 3.141592653589793), [0])
expected.cx(0, 1)
self.assertEqual(len(transpiled), 2)
self.assertEqual(transpiled[0], expected)
self.assertEqual(transpiled[1], expected)
@ddt
class TestTranspileParallel(QiskitTestCase):
"""Test transpile() in parallel."""
def setUp(self):
super().setUp()
# Force parallel execution to True to test multiprocessing for this class
original_val = parallel.PARALLEL_DEFAULT
def restore_default():
parallel.PARALLEL_DEFAULT = original_val
self.addCleanup(restore_default)
parallel.PARALLEL_DEFAULT = True
@data(0, 1, 2, 3)
def test_parallel_multiprocessing(self, opt_level):
"""Test parallel dispatch works with multiprocessing."""
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
qc.measure_all()
backend = FakeMumbaiV2()
pm = generate_preset_pass_manager(opt_level, backend)
res = pm.run([qc, qc])
for circ in res:
self.assertIsInstance(circ, QuantumCircuit)
@data(0, 1, 2, 3)
def test_parallel_with_target(self, opt_level):
"""Test that parallel dispatch works with a manual target."""
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
qc.measure_all()
target = FakeMumbaiV2().target
res = transpile([qc] * 3, target=target, optimization_level=opt_level)
self.assertIsInstance(res, list)
for circ in res:
self.assertIsInstance(circ, QuantumCircuit)
@data(0, 1, 2, 3)
def test_parallel_dispatch(self, opt_level):
"""Test that transpile in parallel works for all optimization levels."""
backend = FakeRueschlikon()
qr = QuantumRegister(16)
cr = ClassicalRegister(16)
qc = QuantumCircuit(qr, cr)
qc.h(qr[0])
for k in range(1, 15):
qc.cx(qr[0], qr[k])
qc.measure(qr, cr)
qlist = [qc for k in range(15)]
tqc = transpile(
qlist, backend=backend, optimization_level=opt_level, seed_transpiler=424242
)
result = backend.run(tqc, seed_simulator=4242424242, shots=1000).result()
counts = result.get_counts()
for count in counts:
self.assertTrue(math.isclose(count["0000000000000000"], 500, rel_tol=0.1))
self.assertTrue(math.isclose(count["0111111111111111"], 500, rel_tol=0.1))
def test_parallel_dispatch_lazy_cal_loading(self):
"""Test adding calibration by lazy loading in parallel environment."""
class TestAddCalibration(TransformationPass):
"""A fake pass to test lazy pulse qobj loading in parallel environment."""
def __init__(self, target):
"""Instantiate with target."""
super().__init__()
self.target = target
def run(self, dag):
"""Run test pass that adds calibration of SX gate of qubit 0."""
dag.add_calibration(
"sx",
qubits=(0,),
schedule=self.target["sx"][(0,)].calibration, # PulseQobj is parsed here
)
return dag
backend = FakeMumbaiV2()
# This target has PulseQobj entries that provides a serialized schedule data
pass_ = TestAddCalibration(backend.target)
pm = PassManager(passes=[pass_])
self.assertIsNone(backend.target["sx"][(0,)]._calibration._definition)
qc = QuantumCircuit(1)
qc.sx(0)
qc_copied = [qc for _ in range(10)]
qcs_cal_added = pm.run(qc_copied)
ref_cal = backend.target["sx"][(0,)].calibration
for qc_test in qcs_cal_added:
added_cal = qc_test.calibrations["sx"][((0,), ())]
self.assertEqual(added_cal, ref_cal)
@data(0, 1, 2, 3)
def test_backendv2_and_basis_gates(self, opt_level):
"""Test transpile() with BackendV2 and basis_gates set."""
backend = FakeNairobiV2()
qc = QuantumCircuit(5)
qc.h(0)
qc.cz(0, 1)
qc.cz(0, 2)
qc.cz(0, 3)
qc.cz(0, 4)
qc.measure_all()
tqc = transpile(
qc,
backend=backend,
basis_gates=["u", "cz"],
optimization_level=opt_level,
seed_transpiler=12345678942,
)
op_count = set(tqc.count_ops())
self.assertEqual({"u", "cz", "measure", "barrier"}, op_count)
for inst in tqc.data:
if inst.operation.name not in {"u", "cz"}:
continue
qubits = tuple(tqc.find_bit(x).index for x in inst.qubits)
self.assertIn(qubits, backend.target.qargs)
@data(0, 1, 2, 3)
def test_backendv2_and_coupling_map(self, opt_level):
"""Test transpile() with custom coupling map."""
backend = FakeNairobiV2()
qc = QuantumCircuit(5)
qc.h(0)
qc.cz(0, 1)
qc.cz(0, 2)
qc.cz(0, 3)
qc.cz(0, 4)
qc.measure_all()
cmap = CouplingMap.from_line(5, bidirectional=False)
tqc = transpile(
qc,
backend=backend,
coupling_map=cmap,
optimization_level=opt_level,
seed_transpiler=12345678942,
)
op_count = set(tqc.count_ops())
self.assertTrue({"rz", "sx", "x", "cx", "measure", "barrier"}.issuperset(op_count))
for inst in tqc.data:
if len(inst.qubits) == 2:
qubit_0 = tqc.find_bit(inst.qubits[0]).index
qubit_1 = tqc.find_bit(inst.qubits[1]).index
self.assertEqual(qubit_1, qubit_0 + 1)
def test_transpile_with_multiple_coupling_maps(self):
"""Test passing a different coupling map for every circuit"""
backend = FakeNairobiV2()
qc = QuantumCircuit(3)
qc.cx(0, 2)
# Add a connection between 0 and 2 so that transpile does not change
# the gates
cmap = CouplingMap.from_line(7)
cmap.add_edge(0, 2)
with self.assertRaisesRegex(TranspilerError, "Only a single input coupling"):
# Initial layout needed to prevent transpiler from relabeling
# qubits to avoid doing the swap
transpile(
[qc] * 2,
backend,
coupling_map=[backend.coupling_map, cmap],
initial_layout=(0, 1, 2),
)
@data(0, 1, 2, 3)
def test_backend_and_custom_gate(self, opt_level):
"""Test transpile() with BackendV2, custom basis pulse gate."""
backend = FakeNairobiV2()
inst_map = InstructionScheduleMap()
inst_map.add("newgate", [0, 1], pulse.ScheduleBlock())
newgate = Gate("newgate", 2, [])
circ = QuantumCircuit(2)
circ.append(newgate, [0, 1])
tqc = transpile(
circ, backend, inst_map=inst_map, basis_gates=["newgate"], optimization_level=opt_level
)
self.assertEqual(len(tqc.data), 1)
self.assertEqual(tqc.data[0].operation, newgate)
qubits = tuple(tqc.find_bit(x).index for x in tqc.data[0].qubits)
self.assertIn(qubits, backend.target.qargs)
@ddt
class TestTranspileMultiChipTarget(QiskitTestCase):
"""Test transpile() with a disjoint coupling map."""
def setUp(self):
super().setUp()
class FakeMultiChip(BackendV2):
"""Fake multi chip backend."""
def __init__(self):
super().__init__()
graph = rx.generators.directed_heavy_hex_graph(3)
num_qubits = len(graph) * 3
rng = np.random.default_rng(seed=12345678942)
rz_props = {}
x_props = {}
sx_props = {}
measure_props = {}
delay_props = {}
self._target = Target("Fake multi-chip backend", num_qubits=num_qubits)
for i in range(num_qubits):
qarg = (i,)
rz_props[qarg] = InstructionProperties(error=0.0, duration=0.0)
x_props[qarg] = InstructionProperties(
error=rng.uniform(1e-6, 1e-4), duration=rng.uniform(1e-8, 9e-7)
)
sx_props[qarg] = InstructionProperties(
error=rng.uniform(1e-6, 1e-4), duration=rng.uniform(1e-8, 9e-7)
)
measure_props[qarg] = InstructionProperties(
error=rng.uniform(1e-3, 1e-1), duration=rng.uniform(1e-8, 9e-7)
)
delay_props[qarg] = None
self._target.add_instruction(XGate(), x_props)
self._target.add_instruction(SXGate(), sx_props)
self._target.add_instruction(RZGate(Parameter("theta")), rz_props)
self._target.add_instruction(Measure(), measure_props)
self._target.add_instruction(Delay(Parameter("t")), delay_props)
cz_props = {}
for i in range(3):
for root_edge in graph.edge_list():
offset = i * len(graph)
edge = (root_edge[0] + offset, root_edge[1] + offset)
cz_props[edge] = InstructionProperties(
error=rng.uniform(1e-5, 5e-3), duration=rng.uniform(1e-8, 9e-7)
)
self._target.add_instruction(CZGate(), cz_props)
@property
def target(self):
return self._target
@property
def max_circuits(self):
return None
@classmethod
def _default_options(cls):
return Options(shots=1024)
def run(self, circuit, **kwargs):
raise NotImplementedError
self.backend = FakeMultiChip()
@data(0, 1, 2, 3)
def test_basic_connected_circuit(self, opt_level):
"""Test basic connected circuit on disjoint backend"""
qc = QuantumCircuit(5)
qc.h(0)
qc.cx(0, 1)
qc.cx(0, 2)
qc.cx(0, 3)
qc.cx(0, 4)
qc.measure_all()
tqc = transpile(qc, self.backend, optimization_level=opt_level)
for inst in tqc.data:
qubits = tuple(tqc.find_bit(x).index for x in inst.qubits)
op_name = inst.operation.name
if op_name == "barrier":
continue
self.assertIn(qubits, self.backend.target[op_name])
@data(0, 1, 2, 3)
def test_triple_circuit(self, opt_level):
"""Test a split circuit with one circuit component per chip."""
qc = QuantumCircuit(30)
qc.h(0)
qc.h(10)
qc.h(20)
qc.cx(0, 1)
qc.cx(0, 2)
qc.cx(0, 3)
qc.cx(0, 4)
qc.cx(0, 5)
qc.cx(0, 6)
qc.cx(0, 7)
qc.cx(0, 8)
qc.cx(0, 9)
qc.ecr(10, 11)
qc.ecr(10, 12)
qc.ecr(10, 13)
qc.ecr(10, 14)
qc.ecr(10, 15)
qc.ecr(10, 16)
qc.ecr(10, 17)
qc.ecr(10, 18)
qc.ecr(10, 19)
qc.cy(20, 21)
qc.cy(20, 22)
qc.cy(20, 23)
qc.cy(20, 24)
qc.cy(20, 25)
qc.cy(20, 26)
qc.cy(20, 27)
qc.cy(20, 28)
qc.cy(20, 29)
qc.measure_all()
if opt_level == 0:
with self.assertRaises(TranspilerError):
tqc = transpile(qc, self.backend, optimization_level=opt_level, seed_transpiler=42)
return
tqc = transpile(qc, self.backend, optimization_level=opt_level, seed_transpiler=42)
for inst in tqc.data:
qubits = tuple(tqc.find_bit(x).index for x in inst.qubits)
op_name = inst.operation.name
if op_name == "barrier":
continue
self.assertIn(qubits, self.backend.target[op_name])
def test_disjoint_control_flow(self):
"""Test control flow circuit on disjoint coupling map."""
qc = QuantumCircuit(6, 1)
qc.h(0)
qc.ecr(0, 1)
qc.cx(0, 2)
qc.measure(0, 0)
with qc.if_test((qc.clbits[0], True)):
qc.reset(0)
qc.cz(1, 0)
qc.h(3)
qc.cz(3, 4)
qc.cz(3, 5)
target = self.backend.target
target.add_instruction(Reset(), {(i,): None for i in range(target.num_qubits)})
target.add_instruction(IfElseOp, name="if_else")
tqc = transpile(qc, target=target)
edges = set(target.build_coupling_map().graph.edge_list())
def _visit_block(circuit, qubit_mapping=None):
for instruction in circuit:
if instruction.operation.name == "barrier":
continue
qargs = tuple(qubit_mapping[x] for x in instruction.qubits)
self.assertTrue(target.instruction_supported(instruction.operation.name, qargs))
if isinstance(instruction.operation, ControlFlowOp):
for block in instruction.operation.blocks:
new_mapping = {
inner: qubit_mapping[outer]
for outer, inner in zip(instruction.qubits, block.qubits)
}
_visit_block(block, new_mapping)
elif len(qargs) == 2:
self.assertIn(qargs, edges)
self.assertIn(instruction.operation.name, target)
_visit_block(
tqc,
qubit_mapping={qubit: index for index, qubit in enumerate(tqc.qubits)},
)
def test_disjoint_control_flow_shared_classical(self):
"""Test circuit with classical data dependency between connected components."""
creg = ClassicalRegister(19)
qc = QuantumCircuit(25)
qc.add_register(creg)
qc.h(0)
for i in range(18):
qc.cx(0, i + 1)
for i in range(18):
qc.measure(i, creg[i])
with qc.if_test((creg, 0)):
qc.h(20)
qc.ecr(20, 21)
qc.ecr(20, 22)
qc.ecr(20, 23)
qc.ecr(20, 24)
target = self.backend.target
target.add_instruction(Reset(), {(i,): None for i in range(target.num_qubits)})
target.add_instruction(IfElseOp, name="if_else")
tqc = transpile(qc, target=target)
def _visit_block(circuit, qubit_mapping=None):
for instruction in circuit:
if instruction.operation.name == "barrier":
continue
qargs = tuple(qubit_mapping[x] for x in instruction.qubits)
self.assertTrue(target.instruction_supported(instruction.operation.name, qargs))
if isinstance(instruction.operation, ControlFlowOp):
for block in instruction.operation.blocks:
new_mapping = {
inner: qubit_mapping[outer]
for outer, inner in zip(instruction.qubits, block.qubits)
}
_visit_block(block, new_mapping)
_visit_block(
tqc,
qubit_mapping={qubit: index for index, qubit in enumerate(tqc.qubits)},
)
@slow_test
@data(2, 3)
def test_six_component_circuit(self, opt_level):
"""Test input circuit with more than 1 component per backend component."""
qc = QuantumCircuit(42)
qc.h(0)
qc.h(10)
qc.h(20)
qc.cx(0, 1)
qc.cx(0, 2)
qc.cx(0, 3)
qc.cx(0, 4)
qc.cx(0, 5)
qc.cx(0, 6)
qc.cx(0, 7)
qc.cx(0, 8)
qc.cx(0, 9)
qc.ecr(10, 11)
qc.ecr(10, 12)
qc.ecr(10, 13)
qc.ecr(10, 14)
qc.ecr(10, 15)
qc.ecr(10, 16)
qc.ecr(10, 17)
qc.ecr(10, 18)
qc.ecr(10, 19)
qc.cy(20, 21)
qc.cy(20, 22)
qc.cy(20, 23)
qc.cy(20, 24)
qc.cy(20, 25)
qc.cy(20, 26)
qc.cy(20, 27)
qc.cy(20, 28)
qc.cy(20, 29)
qc.h(30)
qc.cx(30, 31)
qc.cx(30, 32)
qc.cx(30, 33)
qc.h(34)
qc.cx(34, 35)
qc.cx(34, 36)
qc.cx(34, 37)
qc.h(38)
qc.cx(38, 39)
qc.cx(39, 40)
qc.cx(39, 41)
qc.measure_all()
tqc = transpile(qc, self.backend, optimization_level=opt_level, seed_transpiler=42)
for inst in tqc.data:
qubits = tuple(tqc.find_bit(x).index for x in inst.qubits)
op_name = inst.operation.name
if op_name == "barrier":
continue
self.assertIn(qubits, self.backend.target[op_name])
def test_six_component_circuit_level_1(self):
"""Test input circuit with more than 1 component per backend component."""
opt_level = 1
qc = QuantumCircuit(42)
qc.h(0)
qc.h(10)
qc.h(20)
qc.cx(0, 1)
qc.cx(0, 2)
qc.cx(0, 3)
qc.cx(0, 4)
qc.cx(0, 5)
qc.cx(0, 6)
qc.cx(0, 7)
qc.cx(0, 8)
qc.cx(0, 9)
qc.ecr(10, 11)
qc.ecr(10, 12)
qc.ecr(10, 13)
qc.ecr(10, 14)
qc.ecr(10, 15)
qc.ecr(10, 16)
qc.ecr(10, 17)
qc.ecr(10, 18)
qc.ecr(10, 19)
qc.cy(20, 21)
qc.cy(20, 22)
qc.cy(20, 23)
qc.cy(20, 24)
qc.cy(20, 25)
qc.cy(20, 26)
qc.cy(20, 27)
qc.cy(20, 28)
qc.cy(20, 29)
qc.h(30)
qc.cx(30, 31)
qc.cx(30, 32)
qc.cx(30, 33)
qc.h(34)
qc.cx(34, 35)
qc.cx(34, 36)
qc.cx(34, 37)
qc.h(38)
qc.cx(38, 39)
qc.cx(39, 40)
qc.cx(39, 41)
qc.measure_all()
tqc = transpile(qc, self.backend, optimization_level=opt_level, seed_transpiler=42)
for inst in tqc.data:
qubits = tuple(tqc.find_bit(x).index for x in inst.qubits)
op_name = inst.operation.name
if op_name == "barrier":
continue
self.assertIn(qubits, self.backend.target[op_name])
@data(0, 1, 2, 3)
def test_shared_classical_between_components_condition(self, opt_level):
"""Test a condition sharing classical bits between components."""
creg = ClassicalRegister(19)
qc = QuantumCircuit(25)
qc.add_register(creg)
qc.h(0)
for i in range(18):
qc.cx(0, i + 1)
for i in range(18):
qc.measure(i, creg[i])
qc.ecr(20, 21).c_if(creg, 0)
tqc = transpile(qc, self.backend, optimization_level=opt_level)
def _visit_block(circuit, qubit_mapping=None):
for instruction in circuit:
if instruction.operation.name == "barrier":
continue
qargs = tuple(qubit_mapping[x] for x in instruction.qubits)
self.assertTrue(
self.backend.target.instruction_supported(instruction.operation.name, qargs)
)
if isinstance(instruction.operation, ControlFlowOp):
for block in instruction.operation.blocks:
new_mapping = {
inner: qubit_mapping[outer]
for outer, inner in zip(instruction.qubits, block.qubits)
}
_visit_block(block, new_mapping)
_visit_block(
tqc,
qubit_mapping={qubit: index for index, qubit in enumerate(tqc.qubits)},
)
@data(0, 1, 2, 3)
def test_shared_classical_between_components_condition_large_to_small(self, opt_level):
"""Test a condition sharing classical bits between components."""
creg = ClassicalRegister(2)
qc = QuantumCircuit(25)
qc.add_register(creg)
# Component 0
qc.h(24)
qc.cx(24, 23)
qc.measure(24, creg[0])
qc.measure(23, creg[1])
# Component 1
qc.h(0).c_if(creg, 0)
for i in range(18):
qc.ecr(0, i + 1).c_if(creg, 0)
tqc = transpile(qc, self.backend, optimization_level=opt_level, seed_transpiler=123456789)
def _visit_block(circuit, qubit_mapping=None):
for instruction in circuit:
if instruction.operation.name == "barrier":
continue
qargs = tuple(qubit_mapping[x] for x in instruction.qubits)
self.assertTrue(
self.backend.target.instruction_supported(instruction.operation.name, qargs)
)
if isinstance(instruction.operation, ControlFlowOp):
for block in instruction.operation.blocks:
new_mapping = {
inner: qubit_mapping[outer]
for outer, inner in zip(instruction.qubits, block.qubits)
}
_visit_block(block, new_mapping)
_visit_block(
tqc,
qubit_mapping={qubit: index for index, qubit in enumerate(tqc.qubits)},
)
# Check that virtual qubits that interact with each other via quantum links are placed into
# the same component of the coupling map.
initial_layout = tqc.layout.initial_layout
coupling_map = self.backend.target.build_coupling_map()
components = [
connected_qubits(initial_layout[qc.qubits[23]], coupling_map),
connected_qubits(initial_layout[qc.qubits[0]], coupling_map),
]
self.assertLessEqual({initial_layout[qc.qubits[i]] for i in [23, 24]}, components[0])
self.assertLessEqual({initial_layout[qc.qubits[i]] for i in range(19)}, components[1])
# Check clbits are in order.
# Traverse the output dag over the sole clbit, checking that the qubits of the ops
# go in order between the components. This is a sanity check to ensure that routing
# doesn't reorder a classical data dependency between components. Inside a component
# we have the dag ordering so nothing should be out of order within a component.
tqc_dag = circuit_to_dag(tqc)
qubit_map = {qubit: index for index, qubit in enumerate(tqc_dag.qubits)}
input_node = tqc_dag.input_map[tqc_dag.clbits[0]]
first_meas_node = tqc_dag._multi_graph.find_successors_by_edge(
input_node._node_id, lambda edge_data: isinstance(edge_data, Clbit)
)[0]
# The first node should be a measurement
self.assertIsInstance(first_meas_node.op, Measure)
# This should be in the first component
self.assertIn(qubit_map[first_meas_node.qargs[0]], components[0])
op_node = tqc_dag._multi_graph.find_successors_by_edge(
first_meas_node._node_id, lambda edge_data: isinstance(edge_data, Clbit)
)[0]
while isinstance(op_node, DAGOpNode):
self.assertIn(qubit_map[op_node.qargs[0]], components[1])
op_node = tqc_dag._multi_graph.find_successors_by_edge(
op_node._node_id, lambda edge_data: isinstance(edge_data, Clbit)
)[0]
@data(1, 2, 3)
def test_shared_classical_between_components_condition_large_to_small_reverse_index(
self, opt_level
):
"""Test a condition sharing classical bits between components."""
creg = ClassicalRegister(2)
qc = QuantumCircuit(25)
qc.add_register(creg)
# Component 0
qc.h(0)
qc.cx(0, 1)
qc.measure(0, creg[0])
qc.measure(1, creg[1])
# Component 1
qc.h(24).c_if(creg, 0)
for i in range(23, 5, -1):
qc.ecr(24, i).c_if(creg, 0)
tqc = transpile(qc, self.backend, optimization_level=opt_level, seed_transpiler=2023)
def _visit_block(circuit, qubit_mapping=None):
for instruction in circuit:
if instruction.operation.name == "barrier":
continue
qargs = tuple(qubit_mapping[x] for x in instruction.qubits)
self.assertTrue(
self.backend.target.instruction_supported(instruction.operation.name, qargs)
)
if isinstance(instruction.operation, ControlFlowOp):
for block in instruction.operation.blocks:
new_mapping = {
inner: qubit_mapping[outer]
for outer, inner in zip(instruction.qubits, block.qubits)
}
_visit_block(block, new_mapping)
_visit_block(
tqc,
qubit_mapping={qubit: index for index, qubit in enumerate(tqc.qubits)},
)
# Check that virtual qubits that interact with each other via quantum links are placed into
# the same component of the coupling map.
initial_layout = tqc.layout.initial_layout
coupling_map = self.backend.target.build_coupling_map()
components = [
connected_qubits(initial_layout[qc.qubits[0]], coupling_map),
connected_qubits(initial_layout[qc.qubits[6]], coupling_map),
]
self.assertLessEqual({initial_layout[qc.qubits[i]] for i in range(2)}, components[0])
self.assertLessEqual({initial_layout[qc.qubits[i]] for i in range(6, 25)}, components[1])
# Check clbits are in order.
# Traverse the output dag over the sole clbit, checking that the qubits of the ops
# go in order between the components. This is a sanity check to ensure that routing
# doesn't reorder a classical data dependency between components. Inside a component
# we have the dag ordering so nothing should be out of order within a component.
tqc_dag = circuit_to_dag(tqc)
qubit_map = {qubit: index for index, qubit in enumerate(tqc_dag.qubits)}
input_node = tqc_dag.input_map[tqc_dag.clbits[0]]
first_meas_node = tqc_dag._multi_graph.find_successors_by_edge(
input_node._node_id, lambda edge_data: isinstance(edge_data, Clbit)
)[0]
# The first node should be a measurement
self.assertIsInstance(first_meas_node.op, Measure)
# This shoulde be in the first ocmponent
self.assertIn(qubit_map[first_meas_node.qargs[0]], components[0])
op_node = tqc_dag._multi_graph.find_successors_by_edge(
first_meas_node._node_id, lambda edge_data: isinstance(edge_data, Clbit)
)[0]
while isinstance(op_node, DAGOpNode):
self.assertIn(qubit_map[op_node.qargs[0]], components[1])
op_node = tqc_dag._multi_graph.find_successors_by_edge(
op_node._node_id, lambda edge_data: isinstance(edge_data, Clbit)
)[0]
@data(1, 2, 3)
def test_chained_data_dependency(self, opt_level):
"""Test 3 component circuit with shared clbits between each component."""
creg = ClassicalRegister(1)
qc = QuantumCircuit(30)
qc.add_register(creg)
# Component 0
qc.h(0)
for i in range(9):
qc.cx(0, i + 1)
measure_op = Measure()
qc.append(measure_op, [9], [creg[0]])
# Component 1
qc.h(10).c_if(creg, 0)
for i in range(11, 20):
qc.ecr(10, i).c_if(creg, 0)
measure_op = Measure()
qc.append(measure_op, [19], [creg[0]])
# Component 2
qc.h(20).c_if(creg, 0)
for i in range(21, 30):
qc.cz(20, i).c_if(creg, 0)
measure_op = Measure()
qc.append(measure_op, [29], [creg[0]])
tqc = transpile(qc, self.backend, optimization_level=opt_level, seed_transpiler=2023)
def _visit_block(circuit, qubit_mapping=None):
for instruction in circuit:
if instruction.operation.name == "barrier":
continue
qargs = tuple(qubit_mapping[x] for x in instruction.qubits)
self.assertTrue(
self.backend.target.instruction_supported(instruction.operation.name, qargs)
)
if isinstance(instruction.operation, ControlFlowOp):
for block in instruction.operation.blocks:
new_mapping = {
inner: qubit_mapping[outer]
for outer, inner in zip(instruction.qubits, block.qubits)
}
_visit_block(block, new_mapping)
_visit_block(
tqc,
qubit_mapping={qubit: index for index, qubit in enumerate(tqc.qubits)},
)
# Check that virtual qubits that interact with each other via quantum links are placed into
# the same component of the coupling map.
initial_layout = tqc.layout.initial_layout
coupling_map = self.backend.target.build_coupling_map()
components = [
connected_qubits(initial_layout[qc.qubits[0]], coupling_map),
connected_qubits(initial_layout[qc.qubits[10]], coupling_map),
connected_qubits(initial_layout[qc.qubits[20]], coupling_map),
]
self.assertLessEqual({initial_layout[qc.qubits[i]] for i in range(10)}, components[0])
self.assertLessEqual({initial_layout[qc.qubits[i]] for i in range(10, 20)}, components[1])
self.assertLessEqual({initial_layout[qc.qubits[i]] for i in range(20, 30)}, components[2])
# Check clbits are in order.
# Traverse the output dag over the sole clbit, checking that the qubits of the ops
# go in order between the components. This is a sanity check to ensure that routing
# doesn't reorder a classical data dependency between components. Inside a component
# we have the dag ordering so nothing should be out of order within a component.
tqc_dag = circuit_to_dag(tqc)
qubit_map = {qubit: index for index, qubit in enumerate(tqc_dag.qubits)}
input_node = tqc_dag.input_map[tqc_dag.clbits[0]]
first_meas_node = tqc_dag._multi_graph.find_successors_by_edge(
input_node._node_id, lambda edge_data: isinstance(edge_data, Clbit)
)[0]
self.assertIsInstance(first_meas_node.op, Measure)
self.assertIn(qubit_map[first_meas_node.qargs[0]], components[0])
op_node = tqc_dag._multi_graph.find_successors_by_edge(
first_meas_node._node_id, lambda edge_data: isinstance(edge_data, Clbit)
)[0]
while not isinstance(op_node.op, Measure):
self.assertIn(qubit_map[op_node.qargs[0]], components[1])
op_node = tqc_dag._multi_graph.find_successors_by_edge(
op_node._node_id, lambda edge_data: isinstance(edge_data, Clbit)
)[0]
self.assertIn(qubit_map[op_node.qargs[0]], components[1])
op_node = tqc_dag._multi_graph.find_successors_by_edge(
op_node._node_id, lambda edge_data: isinstance(edge_data, Clbit)
)[0]
while not isinstance(op_node.op, Measure):
self.assertIn(qubit_map[op_node.qargs[0]], components[2])
op_node = tqc_dag._multi_graph.find_successors_by_edge(
op_node._node_id, lambda edge_data: isinstance(edge_data, Clbit)
)[0]
self.assertIn(qubit_map[op_node.qargs[0]], components[2])
@data("sabre", "stochastic", "basic", "lookahead")
def test_basic_connected_circuit_dense_layout(self, routing_method):
"""Test basic connected circuit on disjoint backend"""
qc = QuantumCircuit(5)
qc.h(0)
qc.cx(0, 1)
qc.cx(0, 2)
qc.cx(0, 3)
qc.cx(0, 4)
qc.measure_all()
tqc = transpile(
qc,
self.backend,
layout_method="dense",
routing_method=routing_method,
seed_transpiler=42,
)
for inst in tqc.data:
qubits = tuple(tqc.find_bit(x).index for x in inst.qubits)
op_name = inst.operation.name
if op_name == "barrier":
continue
self.assertIn(qubits, self.backend.target[op_name])
# Lookahead swap skipped for performance
@data("sabre", "stochastic", "basic")
def test_triple_circuit_dense_layout(self, routing_method):
"""Test a split circuit with one circuit component per chip."""
qc = QuantumCircuit(30)
qc.h(0)
qc.h(10)
qc.h(20)
qc.cx(0, 1)
qc.cx(0, 2)
qc.cx(0, 3)
qc.cx(0, 4)
qc.cx(0, 5)
qc.cx(0, 6)
qc.cx(0, 7)
qc.cx(0, 8)
qc.cx(0, 9)
qc.ecr(10, 11)
qc.ecr(10, 12)
qc.ecr(10, 13)
qc.ecr(10, 14)
qc.ecr(10, 15)
qc.ecr(10, 16)
qc.ecr(10, 17)
qc.ecr(10, 18)
qc.ecr(10, 19)
qc.cy(20, 21)
qc.cy(20, 22)
qc.cy(20, 23)
qc.cy(20, 24)
qc.cy(20, 25)
qc.cy(20, 26)
qc.cy(20, 27)
qc.cy(20, 28)
qc.cy(20, 29)
qc.measure_all()
tqc = transpile(
qc,
self.backend,
layout_method="dense",
routing_method=routing_method,
seed_transpiler=42,
)
for inst in tqc.data:
qubits = tuple(tqc.find_bit(x).index for x in inst.qubits)
op_name = inst.operation.name
if op_name == "barrier":
continue
self.assertIn(qubits, self.backend.target[op_name])
@data("sabre", "stochastic", "basic", "lookahead")
def test_triple_circuit_invalid_layout(self, routing_method):
"""Test a split circuit with one circuit component per chip."""
qc = QuantumCircuit(30)
qc.h(0)
qc.h(10)
qc.h(20)
qc.cx(0, 1)
qc.cx(0, 2)
qc.cx(0, 3)
qc.cx(0, 4)
qc.cx(0, 5)
qc.cx(0, 6)
qc.cx(0, 7)
qc.cx(0, 8)
qc.cx(0, 9)
qc.ecr(10, 11)
qc.ecr(10, 12)
qc.ecr(10, 13)
qc.ecr(10, 14)
qc.ecr(10, 15)
qc.ecr(10, 16)
qc.ecr(10, 17)
qc.ecr(10, 18)
qc.ecr(10, 19)
qc.cy(20, 21)
qc.cy(20, 22)
qc.cy(20, 23)
qc.cy(20, 24)
qc.cy(20, 25)
qc.cy(20, 26)
qc.cy(20, 27)
qc.cy(20, 28)
qc.cy(20, 29)
qc.measure_all()
with self.assertRaises(TranspilerError):
transpile(
qc,
self.backend,
layout_method="trivial",
routing_method=routing_method,
seed_transpiler=42,
)
# Lookahead swap skipped for performance reasons
@data("sabre", "stochastic", "basic")
def test_six_component_circuit_dense_layout(self, routing_method):
"""Test input circuit with more than 1 component per backend component."""
qc = QuantumCircuit(42)
qc.h(0)
qc.h(10)
qc.h(20)
qc.cx(0, 1)
qc.cx(0, 2)
qc.cx(0, 3)
qc.cx(0, 4)
qc.cx(0, 5)
qc.cx(0, 6)
qc.cx(0, 7)
qc.cx(0, 8)
qc.cx(0, 9)
qc.ecr(10, 11)
qc.ecr(10, 12)
qc.ecr(10, 13)
qc.ecr(10, 14)
qc.ecr(10, 15)
qc.ecr(10, 16)
qc.ecr(10, 17)
qc.ecr(10, 18)
qc.ecr(10, 19)
qc.cy(20, 21)
qc.cy(20, 22)
qc.cy(20, 23)
qc.cy(20, 24)
qc.cy(20, 25)
qc.cy(20, 26)
qc.cy(20, 27)
qc.cy(20, 28)
qc.cy(20, 29)
qc.h(30)
qc.cx(30, 31)
qc.cx(30, 32)
qc.cx(30, 33)
qc.h(34)
qc.cx(34, 35)
qc.cx(34, 36)
qc.cx(34, 37)
qc.h(38)
qc.cx(38, 39)
qc.cx(39, 40)
qc.cx(39, 41)
qc.measure_all()
tqc = transpile(
qc,
self.backend,
layout_method="dense",
routing_method=routing_method,
seed_transpiler=42,
)
for inst in tqc.data:
qubits = tuple(tqc.find_bit(x).index for x in inst.qubits)
op_name = inst.operation.name
if op_name == "barrier":
continue
self.assertIn(qubits, self.backend.target[op_name])
@data(0, 1, 2, 3)
def test_transpile_target_with_qubits_without_ops(self, opt_level):
"""Test qubits without operations aren't ever used."""
target = Target(num_qubits=5)
target.add_instruction(XGate(), {(i,): InstructionProperties(error=0.5) for i in range(3)})
target.add_instruction(HGate(), {(i,): InstructionProperties(error=0.5) for i in range(3)})
target.add_instruction(
CXGate(), {edge: InstructionProperties(error=0.5) for edge in [(0, 1), (1, 2), (2, 0)]}
)
qc = QuantumCircuit(3)
qc.x(0)
qc.cx(0, 1)
qc.cx(0, 2)
tqc = transpile(qc, target=target, optimization_level=opt_level)
invalid_qubits = {3, 4}
self.assertEqual(tqc.num_qubits, 5)
for inst in tqc.data:
for bit in inst.qubits:
self.assertNotIn(tqc.find_bit(bit).index, invalid_qubits)
@data(0, 1, 2, 3)
def test_transpile_target_with_qubits_without_ops_with_routing(self, opt_level):
"""Test qubits without operations aren't ever used."""
target = Target(num_qubits=5)
target.add_instruction(XGate(), {(i,): InstructionProperties(error=0.5) for i in range(4)})
target.add_instruction(HGate(), {(i,): InstructionProperties(error=0.5) for i in range(4)})
target.add_instruction(
CXGate(),
{edge: InstructionProperties(error=0.5) for edge in [(0, 1), (1, 2), (2, 0), (2, 3)]},
)
qc = QuantumCircuit(4)
qc.x(0)
qc.cx(0, 1)
qc.cx(0, 2)
qc.cx(1, 3)
qc.cx(0, 3)
tqc = transpile(qc, target=target, optimization_level=opt_level)
invalid_qubits = {
4,
}
self.assertEqual(tqc.num_qubits, 5)
for inst in tqc.data:
for bit in inst.qubits:
self.assertNotIn(tqc.find_bit(bit).index, invalid_qubits)
@data(0, 1, 2, 3)
def test_transpile_target_with_qubits_without_ops_circuit_too_large(self, opt_level):
"""Test qubits without operations aren't ever used and error if circuit needs them."""
target = Target(num_qubits=5)
target.add_instruction(XGate(), {(i,): InstructionProperties(error=0.5) for i in range(3)})
target.add_instruction(HGate(), {(i,): InstructionProperties(error=0.5) for i in range(3)})
target.add_instruction(
CXGate(), {edge: InstructionProperties(error=0.5) for edge in [(0, 1), (1, 2), (2, 0)]}
)
qc = QuantumCircuit(4)
qc.x(0)
qc.cx(0, 1)
qc.cx(0, 2)
qc.cx(0, 3)
with self.assertRaises(TranspilerError):
transpile(qc, target=target, optimization_level=opt_level)
@data(0, 1, 2, 3)
def test_transpile_target_with_qubits_without_ops_circuit_too_large_disconnected(
self, opt_level
):
"""Test qubits without operations aren't ever used if a disconnected circuit needs them."""
target = Target(num_qubits=5)
target.add_instruction(XGate(), {(i,): InstructionProperties(error=0.5) for i in range(3)})
target.add_instruction(HGate(), {(i,): InstructionProperties(error=0.5) for i in range(3)})
target.add_instruction(
CXGate(), {edge: InstructionProperties(error=0.5) for edge in [(0, 1), (1, 2), (2, 0)]}
)
qc = QuantumCircuit(5)
qc.x(0)
qc.x(1)
qc.x(3)
qc.x(4)
with self.assertRaises(TranspilerError):
transpile(qc, target=target, optimization_level=opt_level)
@data(0, 1, 2, 3)
def test_transpile_does_not_affect_backend_coupling(self, opt_level):
"""Test that transpiliation of a circuit does not mutate the `CouplingMap` stored by a V2
backend. Regression test of gh-9997."""
if opt_level == 3:
raise unittest.SkipTest("unitary resynthesis fails due to gh-10004")
qc = QuantumCircuit(127)
for i in range(1, 127):
qc.ecr(0, i)
backend = FakeSherbrooke()
original_map = copy.deepcopy(backend.coupling_map)
transpile(qc, backend, optimization_level=opt_level)
self.assertEqual(original_map, backend.coupling_map)
@combine(
optimization_level=[0, 1, 2, 3],
scheduling_method=["asap", "alap"],
)
def test_transpile_target_with_qubits_without_delays_with_scheduling(
self, optimization_level, scheduling_method
):
"""Test qubits without operations aren't ever used."""
no_delay_qubits = [1, 3, 4]
target = Target(num_qubits=5, dt=1)
target.add_instruction(
XGate(), {(i,): InstructionProperties(duration=160) for i in range(4)}
)
target.add_instruction(
HGate(), {(i,): InstructionProperties(duration=160) for i in range(4)}
)
target.add_instruction(
CXGate(),
{
edge: InstructionProperties(duration=800)
for edge in [(0, 1), (1, 2), (2, 0), (2, 3)]
},
)
target.add_instruction(
Delay(Parameter("t")), {(i,): None for i in range(4) if i not in no_delay_qubits}
)
qc = QuantumCircuit(4)
qc.x(0)
qc.cx(0, 1)
qc.cx(0, 2)
qc.cx(1, 3)
qc.cx(0, 3)
tqc = transpile(
qc,
target=target,
optimization_level=optimization_level,
scheduling_method=scheduling_method,
)
invalid_qubits = {
4,
}
self.assertEqual(tqc.num_qubits, 5)
for inst in tqc.data:
for bit in inst.qubits:
self.assertNotIn(tqc.find_bit(bit).index, invalid_qubits)
if isinstance(inst.operation, Delay):
self.assertNotIn(tqc.find_bit(bit).index, no_delay_qubits)
|
https://github.com/Juan-Varela11/BNL_2020_Summer_Internship
|
Juan-Varela11
|
import warnings
from qiskit.tools.jupyter import *
from qiskit import IBMQ
from qiskit import assemble
from qiskit import pulse
from qiskit.pulse import pulse_lib
import numpy as np
import matplotlib.pyplot as plt
warnings.filterwarnings('ignore')
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q-internal',group='dev-qiskit')
backend = provider.get_backend('ibmq_johannesburg')
backend_config = backend.configuration()
assert backend_config.open_pulse, "Backend doesn't support OpenPulse"
backend_defaults = backend.defaults()
dt = backend_config.dt
print(f"Sampling time: {dt} ns") # The configuration returns dt in seconds
cmd_def = pulse.CmdDef.from_defaults(backend.defaults().cmd_def, backend.defaults().pulse_library)
qubit = 0
x_gate = cmd_def.get('u3', [qubit], P0=np.pi, P1=0.0, P2=np.pi)
measure_gate = cmd_def.get('measure', qubits=backend_config.meas_map[qubit])
drive_chan = pulse.DriveChannel(qubit)
meas_chan = pulse.MeasureChannel(qubit)
acq_chan = pulse.AcquireChannel(qubit)
measure_time = 40
# drive pulse parameters
drive_power = 0.4
drive_samples = 128
drive_sigma = 16
powers = np.linspace(0.01,0.5,60)
# creating drive pulse
schedules = []
for ii,drive_power in enumerate(powers):
schedule = pulse.Schedule(name='Qubit Rabi')
drive_pulse = pulse_lib.gaussian(duration=drive_samples, amp=drive_power,
sigma=drive_sigma, name='mydrivepulse')
drive_pulse_qubit = drive_pulse(drive_chan)
schedule += drive_pulse_qubit
schedule += measure_gate << schedule.duration
schedules.append(schedule)
schedules[-1].draw(plot_range=[0,400],channels_to_plot=[drive_chan, meas_chan], label=True, scaling=1.0)
num_shots_per_frequency =4096
rabi_sweep = assemble(schedules,
backend=backend,
meas_level=1,
meas_return='avg',
shots=num_shots_per_frequency)
job = backend.run(ground_resonator_freq_sweep)
print (job.job_id())
qubit_spec_codes = ["5e31bf1730629b0011ab3e16"] #codes for johannesburg backend
job = backend.retrieve_job("5e31bf1730629b0011ab3e16")
qubit=0
rabi_result = job.result()
rabi_data = np.ones(len(powers), dtype=np.complex_)
for i in range(len(powers)):
rabi_data[i] = rabi_result.get_memory(i)[qubit]
plt.figure(figsize=(10,5))
plt.plot(powers,rabi_data,"*--")
plt.show()
# auto-phase the output measurement signal
def get_amplitude(vec):
i_signal = np.imag(vec)
r_signal = np.real(vec)
mvec = [np.mean(r_signal), np.mean(i_signal)]
src_mat = np.vstack((r_signal - mvec[0], i_signal - mvec[1])).T
(_, _, v_mat) = np.linalg.svd(src_mat)
dvec = v_mat[0, 0:2]
if dvec.dot(mvec) < 0:
dvec = -dvec
return src_mat.dot(dvec)
from scipy.optimize import curve_fit
scale_factor = 1e-14
rabi_amp_data = get_amplitude(rabi_data)*scale_factor
fit_func = lambda x,A,B,T,phi: (A*np.cos(2*np.pi*x/T+phi)+B)
#Fit the data
fitparams, conv = curve_fit(fit_func, powers, rabi_amp_data, [2.0,0.0,0.08,0])
#get the pi amplitude
pi_amp = (np.pi-fitparams[3])*fitparams[2]/4/np.pi
plt.plot(powers, fit_func(powers, *fitparams), color='red')
plt.scatter(powers, rabi_amp_data, label='target qubit')
plt.xlim(0, 0.2)
plt.ylim(-5, 5)
plt.legend()
plt.xlabel('CR pulse amplitude, a.u.', fontsize=20)
plt.ylabel('Signal, a.u.', fontsize=20)
plt.title('CR Rabi oscillation', fontsize=20)
print(pi_amp)
# drive pulse parameters
drive_power = 0.4
drive_samples = 128
drive_sigma = 16
powers_lin = [pi_amp,pi_amp*3,pi_amp*5,pi_amp*7,pi_amp*9,pi_amp*11,pi_amp*13,pi_amp*15,pi_amp*17,pi_amp*19,pi_amp*21,pi_amp*23,pi_amp*25,pi_amp*27,pi_amp*29,pi_amp*31,pi_amp*33,pi_amp*35,pi_amp*37,pi_amp*39,pi_amp*41,pi_amp*43]
# creating drive pulse
schedules = []
for ii,drive_power in enumerate(powers_lin):
schedule = pulse.Schedule(name='Qubit Rabi')
drive_pulse = pulse_lib.gaussian(duration=drive_samples, amp=drive_power,
sigma=drive_sigma, name='mydrivepulse')
drive_pulse_qubit = drive_pulse(drive_chan)
schedule += drive_pulse_qubit
schedule += measure_gate << schedule.duration
schedules.append(schedule)
schedules[-1].draw(plot_range=[0,400],channels_to_plot=[drive_chan, meas_chan], label=True, scaling=1.0)
num_shots_per_frequency =4096
rabi_sweep = assemble(schedules,
backend=backend,
meas_level=1,
meas_return='avg',
shots=num_shots_per_frequency)
job = backend.run(ground_resonator_freq_sweep)
print (job.job_id())
job = backend.retrieve_job("5e31c52c7eba0a00115e1ca0")
qubit=0
rabi_result = job.result()
rabi_linear_data = np.ones(len(powers), dtype=np.complex_)
for i in range(len(powers)):
rabi_linear_data[i] = rabi_result.get_memory(i)[qubit]
plt.figure(figsize=(10,5))
plt.plot(powers,rabi_data,"*--")
plt.plot(powers_lin,rabi_linear_data,".")
plt.show()
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
def run_hadamard_simulator(number_of_qubits, list_of_qubits, shots):
'''
Run our amazing Hadamard simulator!
Note: this function is not designed to be efficient
Args:
number_of_qubits (integer): number of qubits in the qunatum circuit
list_of_qubits (list of integers): a list of qubits on whom Hadamard gates are applied
shots (integer): number of shots
Returns:
list of integers:
each entry in the list contains the number of shots
where the measurement result is the correspnding basis state;
basis states are ordered lexicographically
'''
# For each qubit, store whether it is manipulated by an odd number of Hadamard gates
# Example: for run_hadamard_simulator(5, [3, 1, 3, 4], 100)
# we obtain hadamard_list:
# [0, 1, 0, 0, 1]
# because qubits 1 and 4 have an odd number of Hadamard gates.
hadamard_list = [0]*number_of_qubits
for qubit in list_of_qubits:
hadamard_list[qubit] = (1 + hadamard_list[qubit])%2
# Calculate the result for each basis state
result = [0]*(2**number_of_qubits)
for i in range(2**number_of_qubits):
# Example: when i is 2,
# the basis_state is 01000
basis_state = '{0:b}'.format(i).zfill(number_of_qubits)[::-1]
for qubit in range(number_of_qubits):
if hadamard_list[qubit] == 0 and basis_state[qubit] == '1':
result[i] = 0
break
if hadamard_list[qubit] == 1:
result[i] += int(shots/(2**(1 + hadamard_list.count(1))))
return result
run_hadamard_simulator(4, [3, 1, 3, 2], 1024)
from qiskit.providers import BaseJob
class HadamardJob(BaseJob):
def __init__(self, backend):
super().__init__(backend, 1)
def result(self):
return self._result
def cancel(self):
pass
def status(self):
pass
def submit(self):
pass
from qiskit.providers import BaseBackend
from qiskit.providers.models import BackendConfiguration
from qiskit import qobj as qiskit_qobj
from qiskit.result import Result
class HadamardSimulator(BaseBackend):
'''
A wrapper backend for the Hadamard simulator
'''
def __init__(self, provider=None):
configuration = {
'backend_name': 'hadamard_simulator',
'backend_version': '0.1.0',
'url': 'http://www.i_love_hadamard.com',
'simulator': True,
'local': True,
'description': 'Simulates only Hadamard gates',
'basis_gates': ['h', 'x'], # basis_gates must contain at least two gates
'memory': True,
'n_qubits': 30,
'conditional': False,
'max_shots': 100000,
'open_pulse': False,
'gates': [
{
'name': 'TODO',
'parameters': [],
'qasm_def': 'TODO'
}
]
}
# We will explain about the provider in the next section
super().__init__(configuration=BackendConfiguration.from_dict(configuration),
provider=provider)
def run(self, qobj):
"""Run qobj
Args:
qobj (QObj): circuit description
Returns:
HadamardJob: derived from BaseJob
"""
hadamard_job = HadamardJob(None)
experiment_results = []
for circuit_index, circuit in enumerate(qobj.experiments):
number_of_qubits = circuit.config.n_qubits
shots = qobj.config.shots
list_of_qubits = []
for operation in circuit.instructions:
if getattr(operation, 'conditional', None):
raise QiskitError('conditional operations are not supported '
'by the Hadamard simulator')
if operation.name != 'h':
if operation.name == 'measure':
continue
else:
raise QiskitError('The Hadamrd simulator allows only Hadamard gates')
list_of_qubits.append(operation.qubits[0])
# Need to verify that
# all the qubits are measured, and to different classical registers.
# Raise an error otherwise.
# We skip this part here.
counts = run_hadamard_simulator(number_of_qubits, list_of_qubits, shots)
formatted_counts = {}
for i in range(2**number_of_qubits):
if counts[i] != 0:
formatted_counts[hex(i)] = counts[i]
experiment_results.append({
'name': circuit.header.name,
'success': True,
'shots': shots,
'data': {'counts': formatted_counts},
'header': circuit.header.as_dict()
})
hadamard_job._result = Result.from_dict({
'results': experiment_results,
'backend_name': 'hadamard_simulator',
'backend_version': '0.1.0',
'qobj_id': '0',
'job_id': '0',
'success': True
})
return hadamard_job
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute
from qiskit.transpiler import PassManager
qreg = QuantumRegister(4)
creg = ClassicalRegister(4)
qc = QuantumCircuit(qreg, creg)
qc.h(qreg[3])
qc.h(qreg[1])
qc.h(qreg[3])
qc.h(qreg[2])
qc.measure(qreg, creg)
hadamard_job = execute(qc, backend=HadamardSimulator(), pass_manager=PassManager(), shots=1024)
result = hadamard_job.result()
print(result.get_counts(qc))
from qiskit.providers import BaseProvider
from qiskit.providers.providerutils import filter_backends
class HadamardProvider(BaseProvider):
"""Provider for the Hadamard backend"""
def __init__(self, *args, **kwargs):
super().__init__(args, kwargs)
# Populate the list of Hadamard backends
self._backends = [HadamardSimulator(provider=self)]
def backends(self, name=None, filters=None, **kwargs):
# pylint: disable=arguments-differ
backends = self._backends
if name:
backends = [backend for backend in backends if backend.name() == name]
return filter_backends(backends, filters=filters, **kwargs)
from qiskit import execute, Aer
from qiskit.transpiler import PassManager
hadamard_provider = HadamardProvider()
new_hadamard_job = execute(qc, hadamard_provider.get_backend('hadamard_simulator'),
pass_manager=PassManager(), shots=1024)
new_hadamard_result = new_hadamard_job.result()
aer_job = execute(qc, Aer.get_backend('qasm_simulator'),
pass_manager=PassManager(), shots=1024)
aer_result = aer_job.result()
print('Hadamard simulator:')
print(new_hadamard_result.get_counts(qc))
print('Aer simulator:')
print(aer_result.get_counts(qc))
|
https://github.com/ShabaniLab/q-camp
|
ShabaniLab
|
# importing the libraries
from qiskit import *
from qiskit import IBMQ
from qiskit.compiler import transpile, assemble
from qiskit.tools.jupyter import *
from qiskit.visualization import *
import numpy as np
import math
import matplotlib.pyplot as plt
from matplotlib import style
from PIL import Image
style.use('bmh')
# A square grayscale image respresented as a numpy array
temp = Image.open('star64.jpg').convert('L')
image = np.asarray(temp).astype('float64')
image /= 256
#print(image)
# Function for plotting the image using matplotlib
def plot_image(img, title: str):
plt.title(title)
#plt.xticks(range(img.shape[0]))
#plt.yticks(range(img.shape[1]))
plt.imshow(img, extent=[0, img.shape[0], img.shape[1], 0], cmap = 'Greys')
plt.show()
plot_image(image, 'Original Image')
# Convert the raw pixel values to probability amplitudes
def amplitude_encode(img_data):
# Calculate the RMS value
rms = np.sqrt(np.sum(np.sum(img_data**2, axis=1)))
# Create normalized image
image_norm = []
for arr in img_data:
for ele in arr:
image_norm.append(ele / rms)
# Return the normalized image as a numpy array
return np.array(image_norm)
# Get the amplitude ancoded pixel values
# Horizontal: Original image
image_norm_h = amplitude_encode(image)
# Vertical: Transpose of Original image
image_norm_v = amplitude_encode(image.T)
# Initialize some global variable for number of qubits
data_qb = math.ceil(np.log(image.size) / np.log(2))
anc_qb = 1
total_qb = data_qb + anc_qb
# Initialize the decrement unitary
D2n_1 = np.roll(np.identity(2**total_qb), 1, axis=1)
# Create the circuit for horizontal scan
qc_h = QuantumCircuit(total_qb)
qc_h.initialize(image_norm_h, range(1, total_qb))
qc_h.h(0)
qc_h.unitary(D2n_1, range(total_qb))
qc_h.h(0)
display(qc_h.draw('mpl', fold=-1))
# Create the circuit for vertical scan
qc_v = QuantumCircuit(total_qb)
qc_v.initialize(image_norm_v, range(1, total_qb))
qc_v.h(0)
qc_v.unitary(D2n_1, range(total_qb))
qc_v.h(0)
display(qc_v.draw('mpl', fold=-1))
# Combine both circuits into a single list
circ_list = [qc_h, qc_v]
# Simulating the cirucits
back = Aer.get_backend('statevector_simulator')
results = execute(circ_list, backend=back).result()
sv_h = results.get_statevector(qc_h)
sv_v = results.get_statevector(qc_v)
from qiskit.visualization import array_to_latex
print('Horizontal scan statevector:')
display(array_to_latex(sv_h[:30], max_size=30))
print()
print('Vertical scan statevector:')
display(array_to_latex(sv_v[:30], max_size=30))
# Classical postprocessing for plotting the output
# Defining a lambda function for
# thresholding to binary values
threshold = lambda amp: (amp > 0.002 or amp < -0.002)
# Selecting odd states from the raw statevector and
# reshaping column vector of size 64 to an 8x8 matrix
edge_scan_h = np.abs(np.array([1 if threshold(sv_h[2*i+1].real) else 0 for i in range(2**data_qb)])).reshape(image.shape[0], image.shape[1])
edge_scan_v = np.abs(np.array([1 if threshold(sv_v[2*i+1].real) else 0 for i in range(2**data_qb)])).reshape(image.shape[0], image.shape[1]).T
# Plotting the Horizontal and vertical scans
plot_image(edge_scan_h, 'Horizontal scan output')
plot_image(edge_scan_v, 'Vertical scan output')
# Combining the horizontal and vertical component of the result
edge_scan_sim = edge_scan_h | edge_scan_v
# Plotting the original and edge-detected images
plot_image(image, 'Original image')
plot_image(edge_scan_sim, 'Edge Detected image')
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
# You can make the bars more transparent to better see the ones that are behind
# if they overlap.
import numpy as np
from qiskit.quantum_info import Statevector
from qiskit.visualization import plot_state_city
from qiskit import QuantumCircuit
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
qc = QuantumCircuit(2)
qc.h([0, 1])
qc.cz(0,1)
qc.ry(np.pi/3, 0)
qc.rx(np.pi/5, 1)
state = Statevector(qc)
plot_state_city(state, alpha=0.6)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit_nature.units import DistanceUnit
from qiskit_nature.second_q.drivers import PySCFDriver
driver = PySCFDriver(
atom="H 0 0 0; H 0 0 0.735",
basis="sto3g",
charge=0,
spin=0,
unit=DistanceUnit.ANGSTROM,
)
es_problem = driver.run()
from qiskit_nature.second_q.mappers import JordanWignerMapper
mapper = JordanWignerMapper()
from qiskit.algorithms.eigensolvers import NumPyEigensolver
numpy_solver = NumPyEigensolver(filter_criterion=es_problem.get_default_filter_criterion())
from qiskit.algorithms.minimum_eigensolvers import VQE
from qiskit.algorithms.optimizers import SLSQP
from qiskit.primitives import Estimator
from qiskit_nature.second_q.algorithms import GroundStateEigensolver, QEOM
from qiskit_nature.second_q.circuit.library import HartreeFock, UCCSD
ansatz = UCCSD(
es_problem.num_spatial_orbitals,
es_problem.num_particles,
mapper,
initial_state=HartreeFock(
es_problem.num_spatial_orbitals,
es_problem.num_particles,
mapper,
),
)
estimator = Estimator()
# This first part sets the ground state solver
# see more about this part in the ground state calculation tutorial
solver = VQE(estimator, ansatz, SLSQP())
solver.initial_point = [0.0] * ansatz.num_parameters
gse = GroundStateEigensolver(mapper, solver)
# The qEOM algorithm is simply instantiated with the chosen ground state solver and Estimator primitive
qeom_excited_states_solver = QEOM(gse, estimator, "sd")
from qiskit_nature.second_q.algorithms import ExcitedStatesEigensolver
numpy_excited_states_solver = ExcitedStatesEigensolver(mapper, numpy_solver)
numpy_results = numpy_excited_states_solver.solve(es_problem)
qeom_results = qeom_excited_states_solver.solve(es_problem)
print(numpy_results)
print("\n\n")
print(qeom_results)
import numpy as np
def filter_criterion(eigenstate, eigenvalue, aux_values):
return np.isclose(aux_values["ParticleNumber"][0], 2.0)
new_numpy_solver = NumPyEigensolver(filter_criterion=filter_criterion)
new_numpy_excited_states_solver = ExcitedStatesEigensolver(mapper, new_numpy_solver)
new_numpy_results = new_numpy_excited_states_solver.solve(es_problem)
print(new_numpy_results)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 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.
"""Isometry tests."""
import unittest
import numpy as np
from ddt import ddt, data
from qiskit.quantum_info.random import random_unitary
from qiskit import BasicAer
from qiskit import QuantumCircuit
from qiskit import QuantumRegister
from qiskit import execute
from qiskit.test import QiskitTestCase
from qiskit.compiler import transpile
from qiskit.quantum_info import Operator
from qiskit.extensions.quantum_initializer.isometry import Isometry
@ddt
class TestIsometry(QiskitTestCase):
"""Qiskit isometry tests."""
@data(
np.eye(2, 2),
random_unitary(2, seed=868540).data,
np.eye(4, 4),
random_unitary(4, seed=16785).data[:, 0],
np.eye(4, 4)[:, 0:2],
random_unitary(4, seed=660477).data,
np.eye(4, 4)[:, np.random.RandomState(seed=719010).permutation(4)][:, 0:2],
np.eye(8, 8)[:, np.random.RandomState(seed=544326).permutation(8)],
random_unitary(8, seed=247924).data[:, 0:4],
random_unitary(8, seed=765720).data,
random_unitary(16, seed=278663).data,
random_unitary(16, seed=406498).data[:, 0:8],
)
def test_isometry(self, iso):
"""Tests for the decomposition of isometries from m to n qubits"""
if len(iso.shape) == 1:
iso = iso.reshape((len(iso), 1))
num_q_output = int(np.log2(iso.shape[0]))
num_q_input = int(np.log2(iso.shape[1]))
q = QuantumRegister(num_q_output)
qc = QuantumCircuit(q)
qc.isometry(iso, q[:num_q_input], q[num_q_input:])
# Verify the circuit can be decomposed
self.assertIsInstance(qc.decompose(), QuantumCircuit)
# Decompose the gate
qc = transpile(qc, basis_gates=["u1", "u3", "u2", "cx", "id"])
# Simulate the decomposed gate
simulator = BasicAer.get_backend("unitary_simulator")
result = execute(qc, simulator).result()
unitary = result.get_unitary(qc)
iso_from_circuit = unitary[::, 0 : 2**num_q_input]
iso_desired = iso
self.assertTrue(np.allclose(iso_from_circuit, iso_desired))
@data(
np.eye(2, 2),
random_unitary(2, seed=99506).data,
np.eye(4, 4),
random_unitary(4, seed=673459).data[:, 0],
np.eye(4, 4)[:, 0:2],
random_unitary(4, seed=124090).data,
np.eye(4, 4)[:, np.random.RandomState(seed=889848).permutation(4)][:, 0:2],
np.eye(8, 8)[:, np.random.RandomState(seed=94795).permutation(8)],
random_unitary(8, seed=986292).data[:, 0:4],
random_unitary(8, seed=632121).data,
random_unitary(16, seed=623107).data,
random_unitary(16, seed=889326).data[:, 0:8],
)
def test_isometry_tolerance(self, iso):
"""Tests for the decomposition of isometries from m to n qubits with a custom tolerance"""
if len(iso.shape) == 1:
iso = iso.reshape((len(iso), 1))
num_q_output = int(np.log2(iso.shape[0]))
num_q_input = int(np.log2(iso.shape[1]))
q = QuantumRegister(num_q_output)
qc = QuantumCircuit(q)
# Compute isometry with custom tolerance
qc.isometry(iso, q[:num_q_input], q[num_q_input:], epsilon=1e-3)
# Verify the circuit can be decomposed
self.assertIsInstance(qc.decompose(), QuantumCircuit)
# Decompose the gate
qc = transpile(qc, basis_gates=["u1", "u3", "u2", "cx", "id"])
# Simulate the decomposed gate
simulator = BasicAer.get_backend("unitary_simulator")
result = execute(qc, simulator).result()
unitary = result.get_unitary(qc)
iso_from_circuit = unitary[::, 0 : 2**num_q_input]
self.assertTrue(np.allclose(iso_from_circuit, iso))
@data(
np.eye(2, 2),
random_unitary(2, seed=272225).data,
np.eye(4, 4),
random_unitary(4, seed=592640).data[:, 0],
np.eye(4, 4)[:, 0:2],
random_unitary(4, seed=714210).data,
np.eye(4, 4)[:, np.random.RandomState(seed=719934).permutation(4)][:, 0:2],
np.eye(8, 8)[:, np.random.RandomState(seed=284469).permutation(8)],
random_unitary(8, seed=656745).data[:, 0:4],
random_unitary(8, seed=583813).data,
random_unitary(16, seed=101363).data,
random_unitary(16, seed=583429).data[:, 0:8],
)
def test_isometry_inverse(self, iso):
"""Tests for the inverse of isometries from m to n qubits"""
if len(iso.shape) == 1:
iso = iso.reshape((len(iso), 1))
num_q_output = int(np.log2(iso.shape[0]))
q = QuantumRegister(num_q_output)
qc = QuantumCircuit(q)
qc.append(Isometry(iso, 0, 0), q)
qc.append(Isometry(iso, 0, 0).inverse(), q)
result = Operator(qc)
np.testing.assert_array_almost_equal(result.data, np.identity(result.dim[0]))
if __name__ == "__main__":
unittest.main()
|
https://github.com/Z-928/Bugs4Q
|
Z-928
|
from qiskit import *
qc = QuantumCircuit(2)
qc.h(i)
qc.crz (PI/4, 0, 1)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
qc = QuantumCircuit(12)
for idx in range(5):
qc.h(idx)
qc.cx(idx, idx+5)
qc.cx(1, 7)
qc.x(8)
qc.cx(1, 9)
qc.x(7)
qc.cx(1, 11)
qc.swap(6, 11)
qc.swap(6, 9)
qc.swap(6, 10)
qc.x(6)
qc.draw('mpl')
|
https://github.com/JessicaJohnBritto/Quantum-Computing-and-Information
|
JessicaJohnBritto
|
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer, IBMQ, BasicAer, assemble, transpile
from qiskit.visualization import plot_bloch_multivector,plot_bloch_vector, plot_histogram
from qiskit.quantum_info import Statevector
import numpy as np
import matplotlib
backend = BasicAer.get_backend('qasm_simulator')
shots = 1024
style = {'backgroundcolor': 'lightyellow'} # Style of the circuits
qreg = QuantumRegister(2)
creg = ClassicalRegister(1)
qc = QuantumCircuit(qreg, creg)
qc.x(1) # Applying X gate on qubit 2 to get |1>
qc.barrier()
qc.draw(output='mpl', style=style)
# Applying Hadamard Gate
for qubit in range(2):
qc.h(qubit)
qc.barrier()
qc.draw(output='mpl', style=style)
# Balanced Oracle
qc.cx(0,1)
qc.barrier()
for qubit in range(1):
qc.h(qubit)
qc.measure(0,0)
qc.draw(output='mpl', style=style)
transpiled_dj_circuit = transpile(qc, backend)
qobj = assemble(transpiled_dj_circuit)
results = backend.run(qobj).result()
answer = results.get_counts()
plot_histogram(answer)
## Re-initialising
qreg = QuantumRegister(2)
creg = ClassicalRegister(1)
qc = QuantumCircuit(qreg, creg)
qc.x(1) # Applying X gate on qubit 2 to get |1>
qc.barrier()
# qc.draw(output='mpl', style=style)
# Applying Hadamard Gate
for qubit in range(2):
qc.h(qubit)
qc.barrier()
# Constant Oracle
if qc[1]==1:
qc.x(1)
for qubit in range(1):
qc.h(qubit)
qc.measure(0,0)
qc.draw(output='mpl', style=style)
transpiled_dj_circuit = transpile(qc, backend)
qobj = assemble(transpiled_dj_circuit)
results = backend.run(qobj).result()
answer = results.get_counts()
plot_histogram(answer)
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
from random import randrange
# randomly create a 2-dimensional quantum state
def random_quantum_state():
first_entry = randrange(100)
first_entry = first_entry/100
first_entry = first_entry**0.5 # we found the first value before determining its sign
if randrange(2) == 0:
first_entry = -1 * first_entry
second_entry = 1 - (first_entry**2)
second_entry = second_entry**0.5
if randrange(2) == 0:
second_entry = -1 * second_entry
return [first_entry,second_entry]
from matplotlib.pyplot import plot, show, figure # import the useful tool for drawing figures in python
figure(figsize=(6,6), dpi=60) # size of the figure
plot(0,0,'bo') # point the origin (0,0)
for i in range(100):
quantum_state = random_quantum_state(); # random quantum state
plot(quantum_state[0],quantum_state[1],'bo') # put a point for the quantum state
show() # show the diagram
# import the useful tool for drawing figures in python
from matplotlib.pyplot import plot, show, figure, Circle, axis, gca, annotate, arrow, text
figure(figsize=(6,6), dpi=80) # size of the figure
gca().add_patch( Circle((0,0),1,color='black',fill=False) ) # define a circle
plot(-1.3,0)
plot(1.3,0)
plot(0,1.3)
plot(0,-1.3)
# axes
arrow(0,0,1.1,0,head_width=0.04, head_length=0.08)
arrow(0,0,-1.1,0,head_width=0.04, head_length=0.08)
arrow(0,0,0,-1.1,head_width=0.04, head_length=0.08)
arrow(0,0,0,1.1,head_width=0.04, head_length=0.08)
show() # show the diagram
def rotations(rotation_angle,number_of_rotations):
# 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
# import the useful tool for drawing figures in python
from matplotlib.pyplot import plot, show, figure, Circle, axis, gca, annotate, arrow, text
# import the constant pi
from math import pi
# we define a quantum circuit with one qubit and one bit
qreg1 = QuantumRegister(1) # quantum register with a single qubit
creg1 = ClassicalRegister(1) # classical register with a single bit
mycircuit1 = QuantumCircuit(qreg1,creg1) # quantum circuit with quantum and classical registers
# create the plane
figure(figsize=(6,6), dpi=80) # size of the figure
gca().add_patch( Circle((0,0),1,color='black',fill=False) ) # draw the circle
# auxiliary points
plot(-1.3,0)
plot(1.3,0)
plot(0,1.3)
plot(0,-1.3)
# axes
arrow(0,0,1.1,0,head_width=0.04, head_length=0.08)
arrow(0,0,-1.1,0,head_width=0.04, head_length=0.08)
arrow(0,0,0,-1.1,head_width=0.04, head_length=0.08)
arrow(0,0,0,1.1,head_width=0.04, head_length=0.08)
# end of create the plane
for i in range(number_of_rotations):
# iteratively apply the rotation
mycircuit1.ry(2*rotation_angle,qreg1[0])
# the following code is used to get the quantum state of the quantum register
job = execute(mycircuit1,Aer.get_backend('statevector_simulator'))
current_quantum_state=job.result().get_statevector(mycircuit1)
x_value = current_quantum_state[0].real # get the amplitude of |0>
y_value = current_quantum_state[1].real # get the amplitude of |1>
# show the quantum state as an arrow on the diagram
arrow(0,0,x_value,y_value,head_width=0.04, head_length=0.08,color='blue')
# the following code is used to indicate the rotation number
if x_value<0: text_x_value=x_value-0.1
else: text_x_value=x_value+0.1
if y_value<0: text_y_value=y_value-0.1
else: text_y_value=y_value+0.1
text(text_x_value,text_y_value,'r='+str(i+1))
# end of for-loop
show() # show the diagram
#end of function
print("function 'rotations' is defined now, and so it can be used in the following part")
# call function rotations 8 times with angle pi/4
# import the constant pi
from math import pi
rotations(pi/4,8)
#
# your code is here
#
#
# your code is here
#
#
# your code is here
#
#
# your code is here
#
#
# your code is here
#
#
# your code is here
#
|
https://github.com/rodneyosodo/variational-quantum-classifier-on-heartattack
|
rodneyosodo
|
#!/usr/bin/env python
# coding: utf-8
from qiskit import QuantumCircuit
from qiskit.aqua.components.optimizers import COBYLA, ADAM, SPSA
from qiskit.circuit.library import ZZFeatureMap, RealAmplitudes, ZFeatureMap, PauliFeatureMap
from qiskit.quantum_info import Statevector
import numpy as np
import pandas as pd
from sklearn.preprocessing import MinMaxScaler
from sklearn.model_selection import train_test_split
from sklearn.utils import shuffle
import csv
import warnings
warnings.filterwarnings("ignore")
class Benchmark:
"""
Benchmarking different optimizers, featuremaps and depth of variational circuits
"""
def __init__(self, optimizer, variational_depth, feature_map, X_train, X_test, Y_train, Y_test):
"""
Initial function
:param optimizer: The optimizer to benchmark
:param variational_depth: The depth of the variational circuit
:param feature_map: The featuremap that encodes data
:param X_train: The x data for training
:param X_test: The x data for testing
:param Y_train: The y data for training
:param Y_test: The y data for testing
"""
self.optimizer = optimizer
self.variational_depth = variational_depth
self.feature_map = feature_map
self.no_qubit = 4
self.random_state = 42
self.class_labels = ['yes', 'no']
self.circuit = None
self.var_form = RealAmplitudes(self.no_qubit, reps=self.variational_depth)
self.sv = Statevector.from_label('0' * self.no_qubit)
self.X_train, self.X_test, self.Y_train, self.Y_test = X_train, X_test, Y_train, Y_test
self.cost_list = []
def prepare_circuit(self):
"""
Prepares the circuit. Combines an encoding circuit, feature map, to a variational circuit, RealAmplitudes
:return:
"""
self.circuit = self.feature_map.combine(self.var_form)
# circuit.draw(output='mpl')
def get_data_dict(self, params, x):
"""
Assign the params to the variational circuit and the data to the featuremap
:param params: Parameter for training the variational circuit
:param x: The data
:return parameters:
"""
parameters = {}
for i, p in enumerate(self.feature_map.ordered_parameters):
parameters[p] = x[i]
for i, p in enumerate(self.var_form.ordered_parameters):
parameters[p] = params[i]
return parameters
def assign_label(self, bit_string):
"""
Based on the output from measurements assign no if it odd parity and yes if it is even parity
:param bit_string: The bit string eg 00100
:return class_label: Yes or No
"""
hamming_weight = sum([int(k) for k in list(bit_string)])
is_odd_parity = hamming_weight & 1
if is_odd_parity:
return self.class_labels[1]
else:
return self.class_labels[0]
def return_probabilities(self, counts):
"""
Calculates the probabilities of the class label after assigning the label from the bit string measured
as output
:type counts: dict
:param counts: The counts from the measurement of the quantum circuit
:return result: The probability of each class
"""
shots = sum(counts.values())
result = {self.class_labels[0]: 0, self.class_labels[1]: 0}
for key, item in counts.items():
label = self.assign_label(key)
result[label] += counts[key] / shots
return result
def classify(self, x_list, params):
"""
Assigns the x and params to the quantum circuit the runs a measurement to return the probabilities
of each class
:type params: List
:type x_list: List
:param x_list: The x data
:param params: Parameters for optimizing the variational circuit
:return probs: The probabilities
"""
qc_list = []
for x in x_list:
circ_ = self.circuit.assign_parameters(self.get_data_dict(params, x))
qc = self.sv.evolve(circ_)
qc_list += [qc]
probs = []
for qc in qc_list:
counts = qc.to_counts()
prob = self.return_probabilities(counts)
probs += [prob]
return probs
@staticmethod
def mse_cost(probs, expected_label):
"""
Calculates the mean squared error from the expected values and calculated values
:type expected_label: List
:type probs: List
:param probs: The expected values
:param expected_label: The real values
:return mse: The mean squared error
"""
p = probs.get(expected_label)
actual, pred = np.array(1), np.array(p)
mse = np.square(np.subtract(actual, pred)).mean()
return mse
def cost_function(self, X, Y, params, print_value=False):
"""
This is the cost function and returns cost for optimization
:type print_value: Boolean
:type params: List
:type Y: List
:type X: List
:param X: The x data
:param Y: The label
:param params: The parameters
:param print_value: If you want values to be printed
:return cost:
"""
# map training input to list of labels and list of samples
cost = 0
training_labels = []
training_samples = []
for sample in X:
training_samples += [sample]
for label in Y:
if label == 0:
training_labels += [self.class_labels[0]]
elif label == 1:
training_labels += [self.class_labels[1]]
probs = self.classify(training_samples, params)
# evaluate costs for all classified samples
for i, prob in enumerate(probs):
cost += self.mse_cost(prob, training_labels[i])
cost /= len(training_samples)
# print resulting objective function
if print_value:
print('%.4f' % cost)
# return objective value
self.cost_list.append(cost)
return cost
def test_model(self, X, Y, params):
"""
Test the model based on x test and y test
:type params: List
:type Y: List
:type X: List
:param X: The x test set
:param Y: The y test set
:param params: The parameters
:return:
"""
accuracy = 0
training_samples = []
for sample in X:
training_samples += [sample]
probs = self.classify(training_samples, params)
for i, prob in enumerate(probs):
if (prob.get('yes') >= prob.get('no')) and (Y[i] == 0):
accuracy += 1
elif (prob.get('no') >= prob.get('yes')) and (Y[i] == 1):
accuracy += 1
accuracy /= len(Y)
print("Test accuracy: {}".format(accuracy))
def run(self):
"""
Runs the whole code
1. Prepares the circuit
2. define the objective function
3. Initialize the paramters
4. Optimize the paramters by training the classifier
:return:
"""
self.prepare_circuit()
# define objective function for training
objective_function = lambda params: self.cost_function(self.X_train, self.Y_train, params, print_value=False)
# randomly initialize the parameters
np.random.seed(self.random_state)
init_params = 2 * np.pi * np.random.rand(self.no_qubit * self.variational_depth * 2)
# train classifier
opt_params, value, _ = self.optimizer.optimize(len(init_params), objective_function, initial_point=init_params)
# print results
# print()
# print('opt_params:', opt_params)
# print('opt_value: ', value)
self.test_model(self.X_test, self.Y_test, opt_params)
def get_cost_list(self):
"""
Return the cost list
:return cost list:
"""
return self.cost_list
def normalize_data(dataPath="../../Data/Processed/heartdata.csv"):
"""
Normalizes the data
:return X_train, X_test, Y_train, Y_test:
"""
# Reads the data
data = pd.read_csv(dataPath)
data = shuffle(data, random_state=42)
X, Y = data[['sex', 'cp', 'exang', 'oldpeak']].values, data['num'].values
# normalize the data
scaler = MinMaxScaler(feature_range=(-2 * np.pi, 2 * np.pi))
X = scaler.fit_transform(X)
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.3, random_state=42)
return X_train, X_test, Y_train, Y_test
def main():
data = {}
feature_maps = ['ZZFeatureMap(4, reps=1)', 'ZZFeatureMap(4, reps=2)', 'ZZFeatureMap(4, reps=4)',
'ZFeatureMap(4, reps=1)', 'ZFeatureMap(4, reps=2)', 'ZFeatureMap(4, reps=4)',
'PauliFeatureMap(4, reps=1)', 'PauliFeatureMap(4, reps=2)', 'PauliFeatureMap(4, reps=4)']
optimizers = ["COBYLA(maxiter=50)", "SPSA(max_trials=50)", "ADAM(maxiter=50)"]
x_train, x_test, y_train, y_test = normalize_data()
for fe in feature_maps:
for i in [1, 3, 5]:
for opt in optimizers:
print("FE: {}\tDepth: {}\tOpt: {}".format(fe, i, opt))
test_benchmark = Benchmark(optimizer=eval(opt), variational_depth=i, feature_map=eval(fe), X_train=x_train, X_test=x_test, Y_train=y_train, Y_test=y_test)
test_benchmark.run()
data_list = "{} {} vdepth {}".format(fe, opt, i)
data[data_list] = test_benchmark.get_cost_list()
w = csv.writer(open("../../Data/Processed/heartcosts.csv", "w"))
for key, val in data.items():
w.writerow([key, val])
if __name__ == "__main__":
main()
|
https://github.com/peiyong-addwater/Hackathon-QNLP
|
peiyong-addwater
|
import pandas as pd
import numpy as np
import warnings
warnings.filterwarnings('ignore')
train_df = pd.read_csv("data/preprocessed/train_new.csv", index_col=None)
dev_df = pd.read_csv("data/preprocessed/dev_new.csv", index_col=None)
print(len(train_df), len(dev_df))
train_df = train_df.dropna()
dev_df = dev_df.dropna()
print(len(train_df), len(dev_df))
train_df.info()
train_df['Text'] == train_df['Text'].astype(str)
dev_df['Text'] == dev_df['Text'].astype(str)
train_df.head()
from sklearn.feature_extraction.text import TfidfVectorizer
def whitespace_tokenizer(text: str):
return text.split()
train_texts = train_df['Text']
train_labels = train_df['Target']
dev_texts = dev_df['Text']
dev_labels = dev_df['Target']
# get tf-idf vectors
tfidf_vectorizer = TfidfVectorizer(tokenizer=whitespace_tokenizer)
train_tfidf = tfidf_vectorizer.fit_transform(train_texts)
dev_tfidf = tfidf_vectorizer.transform(dev_texts)
from sklearn.svm import LinearSVC
from sklearn.naive_bayes import MultinomialNB
from sklearn.linear_model import LogisticRegression
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import accuracy_score
for c in [0.001, 0.01, 0.1, 1, 10, 100, 1000]:
lsvc = LinearSVC(C=c)
lsvc.fit(train_tfidf, train_labels)
preds = lsvc.predict(dev_tfidf)
print(f"C={c:6}, acc: {accuracy_score(dev_labels, preds):.3f}")
for c in [0.001, 0.01, 0.1, 1, 10, 100, 1000]:
lr = LogisticRegression(C=c)
lr.fit(train_tfidf, train_labels)
preds = lr.predict(dev_tfidf)
print(f"C={c:6}, acc: {accuracy_score(dev_labels, preds):.3f}")
for a in [0.001, 0.01, 0.1, 1, 10, 100, 1000]:
nb = MultinomialNB(alpha=a)
nb.fit(train_tfidf, train_labels)
preds = nb.predict(dev_tfidf)
print(f"alpha={a: 6}, acc: {accuracy_score(dev_labels, preds):.3f}")
for n_neighbors in range(1, 10):
for weights in ['uniform', 'distance']:
knn = KNeighborsClassifier(n_neighbors=n_neighbors)
knn.fit(train_tfidf, train_labels)
preds = knn.predict(dev_tfidf)
print(f"n_neighbors={n_neighbors: 2}, weights={weights:9}, acc: {accuracy_score(dev_labels, preds):.3f}")
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.tools.visualization import circuit_drawer
q = QuantumRegister(1)
c = ClassicalRegister(1)
qc = QuantumCircuit(q, c)
qc.h(q)
qc.measure(q, c)
circuit_drawer(qc, output='mpl', style={'backgroundcolor': '#EEEEEE'})
|
https://github.com/Qiskit/feedback
|
Qiskit
|
from qiskit_cold_atom.providers import ColdAtomProvider
provider = ColdAtomProvider()
for backend in provider.backends():
print(backend)
import numpy as np
from qiskit import QuantumCircuit
backend = provider.get_backend("collective_spin_simulator")
circ_x = QuantumCircuit(1)
circ_x.rlx(np.pi/2, 0)
circ_x.measure_all()
circ_x.draw("mpl")
from qiskit.visualization import plot_histogram
job_x = backend.run(circ_x, shots = 1000, spin=20, seed=14)
plot_histogram(job_x.result().get_counts())
squeez_circ = QuantumCircuit(1, 1)
squeez_circ.rlx(-np.pi/2, 0)
squeez_circ.rlz2(0.3, 0)
squeez_circ.rlz(-np.pi/2, 0)
squeez_circ.rlx(-0.15, 0)
squeez_circ.measure(0, 0)
squeez_circ.draw(output='mpl')
job_squeez = backend.run(squeez_circ, shots = 1000, spin=20, seed=14)
plot_histogram(job_squeez.result().get_counts())
import matplotlib.pyplot as plt
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(14,5))
fig.tight_layout(pad=5.0)
ax1.set_title("spin squeezing circuit")
ax2.set_title("single rotation circuit")
plot_histogram(job_x.result().get_counts(), ax=ax2)
plot_histogram(job_squeez.result().get_counts(), ax=ax1, color="#9f1853")
from qiskit_cold_atom.applications import FermiHubbard1D
# defining the system
system = FermiHubbard1D(
num_sites = 3, # number of lattice sites
particles_up = 1, # number of spin up particles
particles_down = 1, # number of spin down particles
hop_strength = 2., # parameter J tuning the hopping
int_strength = 1, # parameter U tuning the interaction
potential = [1, 0, -1] # parameters mu tuning the local potential
)
from qiskit_cold_atom.fermions.fermion_circuit_solver import FermionicState
# One spin_up particle in the left site & one spin-down particle in the right site
initial_state = FermionicState([[1, 0, 0], [0, 0, 1]])
from qiskit_nature.operators.second_quantization import FermionicOp
spin_density = FermionicOp([('NIIIII', 1), ('IIINII', -1)])
evolution_times = np.linspace(0.1, 5, 40) # times to simulate
from qiskit_cold_atom.applications import FermionicEvolutionProblem
spin_problem = FermionicEvolutionProblem(system, initial_state, evolution_times, spin_density)
from qiskit_cold_atom.providers.fermionic_tweezer_backend import FermionicTweezerSimulator
from qiskit_cold_atom.applications import TimeEvolutionSolver
fermionic_backend = FermionicTweezerSimulator(n_tweezers=3)
fermionic_solver = TimeEvolutionSolver(backend = fermionic_backend)
from qiskit import Aer
qubit_backend = Aer.get_backend('qasm_simulator')
mapping = 'bravyi_kitaev' # or 'jordan_wigner', 'parity'
shallow_qubit_solver = TimeEvolutionSolver(backend = qubit_backend, map_type = mapping, trotter_steps = 1)
deep_qubit_solver = TimeEvolutionSolver(backend = qubit_backend, map_type = mapping, trotter_steps = 6)
spin_vals_fermions = fermionic_solver.solve(spin_problem)
spin_vals_qubits_shallow = shallow_qubit_solver.solve(spin_problem)
spin_vals_qubits_deep = deep_qubit_solver.solve(spin_problem)
plt.xlabel('evolution time')
plt.ylabel('Spin at site 1')
plt.title('evolution of spin density')
plt.plot(evolution_times, spin_vals_qubits_shallow, '--o', color='#d02670', alpha=0.5, label='qubits, 1 trotter step')
plt.plot(evolution_times, spin_vals_qubits_deep, '-o', color='#08bdba', alpha=0.8, label='qubits, 6 trotter steps')
plt.plot(evolution_times, spin_vals_fermions, '-o', color='#0f62fe', alpha=0.8, label='fermionic backend')
plt.legend()
fermion_circuit = spin_problem.circuits(fermionic_backend.initialize_circuit(initial_state.occupations))[-1]
fermion_circuit.measure_all()
fermion_circuit.draw(output='mpl')
qubit_circuit = deep_qubit_solver.construct_qubit_circuits(spin_problem)[-1]
qubit_circuit.measure_all()
qubit_circuit.decompose().decompose().draw("mpl", idle_wires=False)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
top = QuantumCircuit(1)
top.x(0);
bottom = QuantumCircuit(2)
bottom.cry(0.2, 0, 1);
tensored = bottom.tensor(top)
tensored.draw('mpl')
|
https://github.com/qiskit-community/qiskit-cold-atom
|
qiskit-community
|
from qiskit_cold_atom.providers import ColdAtomProvider
provider = ColdAtomProvider()
backend = provider.get_backend("collective_spin_simulator")
from qiskit import QuantumCircuit
from qiskit_cold_atom.spins.spins_gate_library import OATGate
from qiskit.visualization import plot_histogram
qc = QuantumCircuit(1)
qc.append(OATGate(chi=0.4, delta=-1., omega=2.), qargs=[0])
# alternatively append the OAT gate directly:
# qc.oat(chi=0.4, delta=-1., omega=2., wire=0)
qc.measure_all()
# simulate the circuit with a spin length L=5
counts = backend.run(qc, spin=5).result().get_counts()
# convert counts to integers for better formatting
plot_histogram({int(k):v for k,v in counts.items()})
from qiskit_cold_atom.spins.spins_gate_library import RLXGate, RLZGate, RLZ2Gate
print("LX generator: \n", RLXGate(0.5).generator)
print("LZ generator: \n", RLZGate(1.).generator)
print("LZ2 generator: \n", RLZ2Gate(1.5).generator)
from qiskit.circuit import Parameter
import matplotlib.pyplot as plt
import numpy as np
# lenght of spin for the simulation
spin = 20
# sample at 50 angles between 0 and 4*pi
vals = 50
angles = np.linspace(0, 4*np.pi, vals)
omega = Parameter("omega")
# create list of circuits
circuit = QuantumCircuit(1, 1)
circuit.rlx(omega, 0)
circuit.measure(0, 0)
rabi_list = [circuit.assign_parameters([angle]) for angle in angles]
job_rabi = backend.run(rabi_list, shots = 10, spin = spin, seed=5462)
result_rabi = job_rabi.result()
outcomes = np.array([np.array(result_rabi.get_memory(i), dtype=float) for i in range(vals)])
plt.errorbar(angles, np.mean(outcomes, axis=1), yerr=np.std(outcomes, axis=1), fmt='o', color="#4589ff")
plt.title(f"Rabi oscillations for a single collective spin of length L = {spin}")
plt.ylabel("measurement outcome")
plt.xlabel("angle of x-rotation")
plt.show()
# circuit with spin squeezing
squeez_circ = QuantumCircuit(1, 1)
squeez_circ.rlx(-np.pi/2, 0)
squeez_circ.rlz2(0.3, 0)
squeez_circ.rlz(-np.pi/2, 0)
squeez_circ.rlx(-0.15, 0)
squeez_circ.measure(0, 0)
job_squeez = backend.run(squeez_circ, shots = 1000, spin=20, seed=14)
squeez_circ.draw(output='mpl', style="clifford")
# for comparison: circuit with a single rotation
circ_x = QuantumCircuit(1, 1)
circ_x.rlx(np.pi/2, 0)
circ_x.measure_all()
job_x = backend.run(circ_x, shots = 1000, spin=20, seed=14)
fig, (ax1, ax2) = plt.subplots(2, figsize=(10,8))
fig.tight_layout(pad=5.0)
ax1.set_title("spin squeezing circuit")
ax2.set_title("single rotation circuit")
plot_histogram(job_squeez.result().get_counts(), ax=ax1, color="#9f1853") #, number_to_keep=10)
plot_histogram(job_x.result().get_counts(), ax=ax2) #, number_to_keep=10)
from qiskit_cold_atom.spins.spins_gate_library import RLZLZGate
qc = QuantumCircuit(2)
qc.rlx(np.pi/2, [0, 1])
qc.rlzlz(np.pi, [0, 1])
qc.rlx(np.pi/2, [0, 1])
qc.measure_all()
plot_histogram(backend.run(qc, spin=2).result().get_counts())
plot_histogram(backend.run(qc, spin=1/2).result().get_counts())
from pprint import pprint
collective_spins_configuration = backend.configuration().to_dict()
pprint(collective_spins_configuration)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/drnickallgood/simonqiskit
|
drnickallgood
|
import sys
import matplotlib.pyplot as plt
import numpy as np
import operator
from qiskit.providers.ibmq import least_busy
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute,Aer, IBMQ
#from qiskit.providers.ibmq.managed import IBMQJobManager
from qiskit.tools.visualization import plot_histogram
from qiskit.tools.visualization import circuit_drawer
from qiskit.tools.monitor import job_monitor
from sympy import Matrix, pprint, MatrixSymbol, expand, mod_inverse
from qiskit.providers.ibmq import least_busy
# hidden period string
# Goes from most-significant bit to least-significant bit (left to right)
s = "10"
n = len(s)
# Create registers
# 2^n quantum registers half for control, half for data,
# n classical registers for the output
qr = QuantumRegister(2*n)
cr = ClassicalRegister(n)
circuitName = "Simon"
simonCircuit = QuantumCircuit(qr,cr, name=circuitName)
#print(simonCircuit.name)
local_sim = Aer.get_backend('qasm_simulator')
# Apply hadamards prior to oracle
for i in range(n):
simonCircuit.h(qr[i])
# Barrier
simonCircuit.barrier()
#### Blackbox Function #####
# QP's don't care about this, we do#
#############################
# Copy first register to second by using CNOT gates
for i in range(n):
simonCircuit.cx(qr[i],qr[n+i])
# get the small index j such it's "1"
j = -1
#reverse the string so that it fixes the circuit drawing to be more normal
# to the literature where the most significant bit is on TOP and least is on BOTTOM
# IBMQ default this is reversed , LEAST is on TOP and MOST is on BOTTOM
s = s[::-1]
for i, c in enumerate(s):
if c == "1":
j = i
break
# 1-1 and 2-1 mapping with jth qubit
# x is control to xor 2nd qubit with a
for i, c in enumerate(s):
if c == "1" and j >= 0:
#simonCircuit.x(qr[j])
simonCircuit.cx(qr[j], qr[n+i]) #the i-th qubit is flipped if s_i is 1
#simonCircuit.x(qr[j])
# Random peemutation
# This part is how we can get by with 1 query of the oracle and better
# simulates quantum behavior we'd expect
perm = list(np.random.permutation(n))
# init 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 gate on qubits
init[i], init[k] = init[k], init[i] # mark the swapped qubits
else:
i += 1
# Randomly flip qubit
for i in range(n):
if np.random.random() > 0.5:
simonCircuit.x(qr[n+i])
simonCircuit.barrier()
### END OF BLACKBOX FUNCTION
# Apply hadamard gates to registers again
for i in range(n):
simonCircuit.h(qr[i])
simonCircuit.barrier(qr)
# draw circuit
#circuit_drawer(simonCircuit)
print(simonCircuit)
simonCircuit.barrier()
simonCircuit.measure(qr[0:n],cr)
'''
[<IBMQSimulator('ibmq_qasm_simulator')
<IBMQBackend('ibmqx2')
<IBMQBackend('ibmq_16_melbourne')
<IBMQBackend('ibmq_vigo') f
<IBMQBackend('ibmq_ourense')
'''
IBMQ.load_account()
qprovider = IBMQ.get_provider(hub='ibm-q')
#qprovider.backends()
# Get the least busy backend
#qbackend = least_busy(qprovider.backends(filters=lambda x: x.configuration().n_qubits == 5 and not x.configuration().simulator and x.status().operational==True))
qbackend = local_sim
backend_name = qbackend.name()
#print("least busy backend: ", qbackend)
#qbackend = qprovider.get_backend('ibmq_vigo')
#job_manager = IBMQJobManager()
# Default for this backend seems to be 1024 ibmqx2
qshots = 1024
print("Submitting to IBM Q...\n")
job = execute(simonCircuit,backend=qbackend, shots=qshots)
job_monitor(job,interval=2)
#job_set_bar = job_manager.run(simonCircuit, backend=qbackend, name='bar', max_experiments_per_job=5)
#print(job_set_bar.report())
qresults = job.result()
qcounts = qresults.get_counts()
#print("Getting Results...\n")
#print(qcounts)
#print("")
print("\nIBM Q Backend %s: Resulting Values and Probabilities" % local_sim)
print("===============================================\n")
print("Simulated Runs:",qshots,"\n")
# period, counts, prob,a0,a1,...,an
#
for key, val in qcounts.items():
prob = val / qshots
print("Observed String:", key, ", Counts:", val, ", Probability:", prob)
print("")
# Classical post processing via Guassian elimination for the linear equations
# Y a = 0
# k[::-1], we reverse the order of the bitstring
lAnswer = [ (k[::-1],v) for k,v in qcounts.items() if k != "0"*n ]
# Sort basis by 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)
Y_transformed = Y.rref(iszerofunc=lambda x: x % 2==0)
# convert rational and negatives in rref
def mod(x,modulus):
numer,denom = x.as_numer_denom()
return numer*mod_inverse(denom,modulus) % modulus
# Deal with negative and fractial values
Y_new = Y_transformed[0].applyfunc(lambda x: mod(x,2))
print("The hidden period a0, a1 ... a%d only satisfies these equations:" %(n-1))
print("===============================================================\n")
rows,cols = Y_new.shape
equations = list()
Yr = list()
for r in range(rows):
Yr = [ "a"+str(i)+"" for i,v in enumerate(list(Y_new[r,:])) if v==1]
if len(Yr) > 0:
#tStr = " + ".join(Yr)
tStr = " xor ".join(Yr)
#single value is 0, only xor period string with 0 to get
if len(tStr) == 2:
equations.append("period string xor" + " 0 " + " = 0")
else:
equations.append("period string" + " xor " + tStr + " = 0")
#tStr = u' \2295 '.join(Yr)
print(tStr, "= 0")
# Now we need to solve this system of equations to get our period string
print("")
print("Here are the system of equations to solve")
print("=========================================")
print("Format: period_string xor a_x xor ... = 0\n")
for eq in equations:
print(eq)
print()
# Sort list by value
#reverse items to display back to original inputs
# We reversed above because of how IBMQ handles "endianness"
#reverse_strings = dict()
#s = s[::-1]
"""
for k,v in qcounts.items():
k = k[::-1]
reverse_strings[k] = v
"""
sorted_x = sorted(qcounts.items(), key=operator.itemgetter(1), reverse=True)
print("Sorted list of result strings by counts")
print("======================================\n")
# Print out list of items
for i in sorted_x:
print(i)
print(str(type(i)))
#print(sorted_x)
print("")
# Now once we have our found string, we need to double-check by XOR back to the
# y value
# Look into nullspaces with numpy
# Need to get x and y values based on above.. to help out
'''
IBM Q Backend ibmqx2: Resulting Values and Probabilities
===============================================
Simulated Runs: 1024
Period: 01 , Counts: 196 , Probability: 0.19140625
Period: 11 , Counts: 297 , Probability: 0.2900390625
Period: 10 , Counts: 269 , Probability: 0.2626953125
Period: 00 , Counts: 262 , Probability: 0.255859375
'''
# Already using a sorted list, the one with the highest probability is on top
correct = 0
incorrect = 0
def verify_string(ostr, pstr):
"""
Verify string with period string
Does dot product and then mod2 addition
"""
temp_list = list()
# loop through outstring, make into numpy array
for o in ostr:
temp_list.append(int(o))
ostr_arr = np.asarray(temp_list)
temp_list.clear()
# loop through period string, make into numpy array
for p in pstr:
temp_list.append(int(p))
pstr_arr = np.asarray(temp_list)
temp_list.clear()
# Per Simosn, we do the dot product of the np arrays and then do mod 2
results = np.dot(ostr_arr, pstr_arr)
if results % 2 == 0:
return True
return False
obs_strings = list()
for x in sorted_x:
obs_strings.append(x[0])
for o in obs_strings:
# Need to re-reverse string, so it's "normal"
if verify_string(o, s[::-1]):
print("Correct Result: " + o )
correct += 1
else:
print("Incorrect Result: " + o)
incorrect += 1
print("\n===== Correct vs Incorrect Computations =====\n")
print("Total Correct: " + str(correct))
print("Total Incorrect: " + str(incorrect))
print("")
|
https://github.com/simanraj1123/n-qubit-Grover-s-search-on-IBM-Qiskit
|
simanraj1123
|
# Importing libraries
from qiskit import QuantumCircuit, execute, Aer, IBMQ, QuantumRegister, ClassicalRegister
from qiskit.compiler import transpile, assemble
from qiskit.tools.jupyter import *
from qiskit.visualization import *
import numpy as np
import matplotlib.pyplot as plt
from qiskit.converters import circuit_to_gate
from qiskit.circuit.library.standard_gates import ZGate
def oracle(n, targets):
'''
Given the number of qubits "n" and a list of target states "targets", the function returns the quantum circuit
for the oracle.
'''
qbits = QuantumRegister(n,'q')
circ = QuantumCircuit(qbits, name="Oracle")
# Creating a sequential circuit for each target state.
for target in targets:
# Each string representing a target state is reversed so that the indexing matches with the indices of
# the corresponding qubits.
target = list(target)
target.reverse()
target = ''.join(target)
# Flip zero bits
for i in range(len(target)):
if target[i]=='0':
circ.x(i)
# Apply a n-1 CZ
CZ = ZGate().control(n-1)
circ.append(CZ, qbits)
# Flip back
for i in range(len(target)):
if target[i]=='0':
circ.x(i)
# Uncomment the following line if you the circuit to be converted to a gate. This step is not essential to the
# function of the quantum circuit.
# circ = circuit_to_gate(circ)
return circ
def diffusion(n):
'''
Given the number of qubits "n", the function returns the circuit for the n-qubit diffusion operation.
'''
qbits = QuantumRegister(n,'q')
circ = QuantumCircuit(qbits, name="Diffusion")
circ.h(qbits)
# Call the oracle function with target state set to the n-qubit zero state.
circ.append(oracle(n,['0'*n]), qbits)
circ.h(qbits)
return circ
def grover(n, oracle, m,threshold=0):
'''
The "grover" function returns the quantum circuit to implement Grover's search algorithm for an "n"-qubit
system to search for "m" targets. The argument "oracle" is the quantum circuit for the Oracle for the
target state/states. The argument "threshold" is the user-given threshold on the success probability. The
default value of "threshold is zero."
'''
qbits = QuantumRegister(n,'q')
circ = QuantumCircuit(n, name="Grover")
# Initial state: Prepare equal superposition
circ.h(qbits)
# Number of iterations required
N = 2**n # Size of the database
theta = np.arcsin(np.sqrt(m/N))%(2*np.pi) # The value of theta
''' The following loop searches for the optimum value of "p" and the corresponding number of iterations
such that the success probability of the search is equal to or more than the threshold.'''
p=0 # Initialized to zero
while True:
k = (2*p+1)*np.pi/(4*theta)-0.5 # The optimal k is close to this value.
tk_down = theta*(1+2*np.floor(k)) # Final angle theta_k with k rounded down.
tk_up = theta*(1+2*np.ceil(k)) # Final angle theta_k with k rounded up.
# Condition to check if the success probability crosses the threshold.
if max(np.sin(tk_down)**2, np.sin(tk_up)**2) >= threshold:
# If tk_down satisfies the condition choose the floor of k.
if np.sin(tk_down)**2 >= threshold:
k = int(np.floor(k))
print(np.sin(tk_down)**2) # Print the value of success probability.
# If tk_up satisfies the condition choose the ceil of k.
else:
k = int(np.ceil(k))
print(np.sin(tk_up)**2) # Print the value of success probability.
print('p =',p) # Print the value of optimal p.
break # Break the loop if the optimal p is found.
p+=1
print('k =',k) # Print the value of optimal k.
# Append the oracle followed by diffusion operation k number of times.
for i in range(k):
circ.append(oracle, qbits)
circ.append(diffusion(n), qbits)
return circ
'''
Each n-qubit computational basis state is represented by its corresponding n-digit binary string. For example,
the state |001101> is represented by the string '0001101'.
'''
n= # Set the number of qubits.
form = f'{{0:0{str(n)}b}}' # Format to convert decimal number to n-digit binary string.
all_states = [form.format(i) for i in range(2**n)] # A list of all possible orthogonal states
tars = [] # "tars" is a list of binary strings for all the target states.
success_rate = # Set the threshold for success probability.
orc = oracle(n, tars) # The circuit for Oracle given the target states in the list tars.
# Construction of the circuit for Grover's search.
circuit = grover(n, orc, len(tars), success_rate)
# Applying projective measurement to each qubit at the end of the circuit.
circuit.measure_all()
# Running the "circuit" using the QASM simulator.
sim = Aer.get_backend('qasm_simulator') # Calling the qasm_simulator.
job = execute(circuit, sim, shots=1000000) # Executing the circuit with 1,000,000 shots.
result = job.result()
count = result.get_counts(circuit) # "count" is a dict of counts after the projective measurements.
''' If the count of a state is zero in the output, it is not included in the dict.
The following loop includes the absent states in the dict and sets their counts to zero. '''
for x in all_states:
if x not in count.keys():
count[x]=0
final_counts = count
''' Uncomment the following lines, if you want the collective counts of the target and non-target states.'''
# collective_count = {'Others':0, 'Target':0}
# for x in all_states:
# if x in tars:
# collective_count['Target'] += count[x]
# else:
# collective_count['Others'] += count[x]
# final_counts = collective_count
plot_histogram(final_counts) # Plot the probability histogram of the final_counts.
|
https://github.com/PabloMartinezAngerosa/QAOA-uniform-convergence
|
PabloMartinezAngerosa
|
import qiskit
import numpy as np
import networkx as nx
import matplotlib.pyplot as plt
from collections import defaultdict
from operator import itemgetter
from scipy.optimize import minimize
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer
from qiskit.aqua.algorithms import NumPyEigensolver
from qiskit.quantum_info import Pauli
from qiskit.aqua.operators import op_converter
from qiskit.aqua.operators import WeightedPauliOperator
from tsp_qaoa import marina_solution
G=nx.Graph()
i=1
G.add_node(i,pos=(i,i))
G.add_node(2,pos=(2,2))
G.add_node(3,pos=(1,0))
G.add_edge(1,2,weight=20.5)
G.add_edge(1,3,weight=9.8)
pos=nx.get_node_attributes(G,'pos')
nx.draw(G,pos)
labels = nx.get_edge_attributes(G,'weight')
nx.draw_networkx_edge_labels(G,pos,edge_labels=labels)
def append_zz_term(qc,q1,q2,gamma):
qc.cx(q1,q2)
qc.rz(2*gamma,q2)
qc.cx(q1,q2)
def get_cost_circuit(G,gamma):
N=G.number_of_nodes()
qc=QuantumCircuit(N,N)
for i,j in G.edges():
append_zz_term(qc,i,j,gamma)
return qc
#print(get_cost_circuit(G,0.5))
def append_x_term(qc,q1,beta):
qc.rx(2*beta,q1)
def get_mixer_operator(G,beta):
N=G.number_of_nodes()
qc=QuantumCircuit(N,N)
for n in G.nodes():
append_x_term(qc,n,beta)
return qc
#print(get_mixer_operator(G,0.5))
def get_QAOA_circuit(G,beta,gamma):
assert(len(beta)==len(gamma))
N=G.number_of_nodes()
qc=QuantumCircuit(N,N)
qc.h(range(N))
p=len(beta)
#aplicamos las p rotaciones
for i in range(p):
qc=qc.compose(get_cost_circuit(G,gamma[i]))
qc=qc.compose(get_mixer_operator(G,beta[i]))
qc.barrier(range(N))
qc.measure(range(N),range(N))
return qc
print(get_QAOA_circuit(G,[0.5,0,6],[0.5,0,6]))
def invert_counts(counts):
return {k[::-1] :v for k,v in counts.items()}
qc=get_QAOA_circuit(G,[0.5,0,6],[0.5,0,6])
backend=Aer.get_backend('qasm_simulator')
job=execute(qc,backend)
result=job.result()
print(invert_counts(result.get_counts()))
def maxcut_obj(x,G):
cut=0
for i,j in G.edges():
if x[i]!=x[j]:
cut = cut-1
return cut
print(maxcut_obj("00011",G))
def compute_maxcut_energy(counts,G):
energy=0
get_counts=0
total_counts=0
for meas, meas_count in counts.items():
obj_for_meas=maxcut_obj(meas,G)
energy+=obj_for_meas*meas_count
total_counts+=meas_count
return energy/total_counts
def get_black_box_objective(G,p):
backend=Aer.get_backend('qasm_simulator')
def f(theta):
beta=theta[:p]
gamma=theta[p:]
qc=get_QAOA_circuit(G,beta,gamma)
counts=execute(qc,backend,seed_simulator=10).result().get_counts()
return compute_maxcut_energy(invert_counts(counts),G)
return f
p=5
obj=get_black_box_objective(G,p)
init_point=np.array([0.8,2.2,0.83,2.15,0.37,2.4,6.1,2.2,3.8,6.1])#([2,2,1,1,1,1,1,1,1,1])
res_sample=minimize(obj, init_point,method="COBYLA",options={"maxiter":2500,"disp":True})
res_sample
from thirdParty.classical import rand_graph, classical, bitstring_to_path, calc_cost
from utils import mapeo_grafo
cantidad_ciudades = 4
pesos, conexiones = None, None
mejor_camino = None
while not mejor_camino:
pesos, conexiones = rand_graph(cantidad_ciudades)
mejor_costo, mejor_camino = classical(pesos, conexiones, loop=False)
G = mapeo_grafo(conexiones, pesos)
pos=nx.spring_layout(G)
nx.draw(G,pos)
labels = nx.get_edge_attributes(G,'weight')
nx.draw_networkx_edge_labels(G,pos,edge_labels=labels)
G
pos=nx.get_node_attributes(G,'weight')
pos
labels = nx.get_edge_attributes(G,'weight')
labels
def funcion_costo(multiplicador_lagrange, cantidad_ciudades, pesos, conexiones ):
N = G.number_of_nodes()
N_square = N^2
# restriccion 1
for i in range(cantidad_ciudades):
cur = sI(N_square)
for j in range(num_cities):
cur -= D(i, j)
ret += cur**2
# retorna el indice de qubit por conversion al problema
def quibit_indice(i, l, N):
return i * N + l
from qiskit.quantum_info.operators import Operator, Pauli
# Create an operator
XX = Operator(Pauli(label='XX'))
# Add to a circuit
circ = QuantumCircuit(2, 2)
circ.append(XX, [0, 1])
circ.measure([0,1], [0,1])
circ.draw('mpl')
# Add to a circuit
circ = QuantumCircuit(2, 2)
circ.append(a, [0])
#circ.measure([0,1], [0,1])
circ.draw('mpl')
a = I - ( 0.5*(I+ Z))**2
a = Operator(a)
a.is_unitary()
print(I @ Z)
|
https://github.com/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.
"""Randomized tests of quantum synthesis."""
import unittest
from test.python.quantum_info.test_synthesis import CheckDecompositions
from hypothesis import given, strategies, settings
import numpy as np
from qiskit import execute
from qiskit.circuit import QuantumCircuit, QuantumRegister
from qiskit.extensions import UnitaryGate
from qiskit.providers.basicaer import UnitarySimulatorPy
from qiskit.quantum_info.random import random_unitary
from qiskit.quantum_info.synthesis.two_qubit_decompose import (
two_qubit_cnot_decompose,
TwoQubitBasisDecomposer,
Ud,
)
class TestSynthesis(CheckDecompositions):
"""Test synthesis"""
seed = strategies.integers(min_value=0, max_value=2**32 - 1)
rotation = strategies.floats(min_value=-np.pi * 10, max_value=np.pi * 10)
@given(seed)
def test_1q_random(self, seed):
"""Checks one qubit decompositions"""
unitary = random_unitary(2, seed=seed)
self.check_one_qubit_euler_angles(unitary)
self.check_one_qubit_euler_angles(unitary, "U3")
self.check_one_qubit_euler_angles(unitary, "U1X")
self.check_one_qubit_euler_angles(unitary, "PSX")
self.check_one_qubit_euler_angles(unitary, "ZSX")
self.check_one_qubit_euler_angles(unitary, "ZYZ")
self.check_one_qubit_euler_angles(unitary, "ZXZ")
self.check_one_qubit_euler_angles(unitary, "XYX")
self.check_one_qubit_euler_angles(unitary, "RR")
@settings(deadline=None)
@given(seed)
def test_2q_random(self, seed):
"""Checks two qubit decompositions"""
unitary = random_unitary(4, seed=seed)
self.check_exact_decomposition(unitary.data, two_qubit_cnot_decompose)
@given(strategies.tuples(*[seed] * 5))
def test_exact_supercontrolled_decompose_random(self, seeds):
"""Exact decomposition for random supercontrolled basis and random target"""
k1 = np.kron(random_unitary(2, seed=seeds[0]).data, random_unitary(2, seed=seeds[1]).data)
k2 = np.kron(random_unitary(2, seed=seeds[2]).data, random_unitary(2, seed=seeds[3]).data)
basis_unitary = k1 @ Ud(np.pi / 4, 0, 0) @ k2
decomposer = TwoQubitBasisDecomposer(UnitaryGate(basis_unitary))
self.check_exact_decomposition(random_unitary(4, seed=seeds[4]).data, decomposer)
@given(strategies.tuples(*[rotation] * 6), seed)
def test_cx_equivalence_0cx_random(self, rnd, seed):
"""Check random circuits with 0 cx gates locally equivalent to identity."""
qr = QuantumRegister(2, name="q")
qc = QuantumCircuit(qr)
qc.u(rnd[0], rnd[1], rnd[2], qr[0])
qc.u(rnd[3], rnd[4], rnd[5], qr[1])
sim = UnitarySimulatorPy()
unitary = execute(qc, sim, seed_simulator=seed).result().get_unitary()
self.assertEqual(two_qubit_cnot_decompose.num_basis_gates(unitary), 0)
@given(strategies.tuples(*[rotation] * 12), seed)
def test_cx_equivalence_1cx_random(self, rnd, seed):
"""Check random circuits with 1 cx gates locally equivalent to a cx."""
qr = QuantumRegister(2, name="q")
qc = QuantumCircuit(qr)
qc.u(rnd[0], rnd[1], rnd[2], qr[0])
qc.u(rnd[3], rnd[4], rnd[5], qr[1])
qc.cx(qr[1], qr[0])
qc.u(rnd[6], rnd[7], rnd[8], qr[0])
qc.u(rnd[9], rnd[10], rnd[11], qr[1])
sim = UnitarySimulatorPy()
unitary = execute(qc, sim, seed_simulator=seed).result().get_unitary()
self.assertEqual(two_qubit_cnot_decompose.num_basis_gates(unitary), 1)
@given(strategies.tuples(*[rotation] * 18), seed)
def test_cx_equivalence_2cx_random(self, rnd, seed):
"""Check random circuits with 2 cx gates locally equivalent to some circuit with 2 cx."""
qr = QuantumRegister(2, name="q")
qc = QuantumCircuit(qr)
qc.u(rnd[0], rnd[1], rnd[2], qr[0])
qc.u(rnd[3], rnd[4], rnd[5], qr[1])
qc.cx(qr[1], qr[0])
qc.u(rnd[6], rnd[7], rnd[8], qr[0])
qc.u(rnd[9], rnd[10], rnd[11], qr[1])
qc.cx(qr[0], qr[1])
qc.u(rnd[12], rnd[13], rnd[14], qr[0])
qc.u(rnd[15], rnd[16], rnd[17], qr[1])
sim = UnitarySimulatorPy()
unitary = execute(qc, sim, seed_simulator=seed).result().get_unitary()
self.assertEqual(two_qubit_cnot_decompose.num_basis_gates(unitary), 2)
@given(strategies.tuples(*[rotation] * 24), seed)
def test_cx_equivalence_3cx_random(self, rnd, seed):
"""Check random circuits with 3 cx gates are outside the 0, 1, and 2 qubit regions."""
qr = QuantumRegister(2, name="q")
qc = QuantumCircuit(qr)
qc.u(rnd[0], rnd[1], rnd[2], qr[0])
qc.u(rnd[3], rnd[4], rnd[5], qr[1])
qc.cx(qr[1], qr[0])
qc.u(rnd[6], rnd[7], rnd[8], qr[0])
qc.u(rnd[9], rnd[10], rnd[11], qr[1])
qc.cx(qr[0], qr[1])
qc.u(rnd[12], rnd[13], rnd[14], qr[0])
qc.u(rnd[15], rnd[16], rnd[17], qr[1])
qc.cx(qr[1], qr[0])
qc.u(rnd[18], rnd[19], rnd[20], qr[0])
qc.u(rnd[21], rnd[22], rnd[23], qr[1])
sim = UnitarySimulatorPy()
unitary = execute(qc, sim, seed_simulator=seed).result().get_unitary()
self.assertEqual(two_qubit_cnot_decompose.num_basis_gates(unitary), 3)
if __name__ == "__main__":
unittest.main()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.dagcircuit import DAGCircuit
from qiskit.converters import circuit_to_dag
from qiskit.visualization import dag_drawer
q = QuantumRegister(3, 'q')
c = ClassicalRegister(3, 'c')
circ = QuantumCircuit(q, c)
circ.h(q[0])
circ.cx(q[0], q[1])
circ.measure(q[0], c[0])
circ.rz(0.5, q[1]).c_if(c, 2)
dag = circuit_to_dag(circ)
dag_drawer(dag)
|
https://github.com/LohitPotnuru/DeutschJozsaAlgorithm_Qiskit
|
LohitPotnuru
|
from qiskit import *
from random import randint
from qiskit_textbook.problems import dj_problem_oracle
#number of bits in function
qiskit_ex= bool(input("Enter a value if you want to test a random qiskit 4-bit oracle"))
if qiskit_ex==False:
n=int(input("Enter the number of bits in the function: "))
if (input("Is the function constant? "))=='True': constant=True
else: constant=False
print(constant)
else:
n=4
#create circuit and initialize states
circuit=QuantumCircuit(n+1,n)
circuit.x(n)
circuit.h(range(n+1))
circuit.barrier()
circuit.draw()
#generate a constant function
try:
if constant==True:
oracle=QuantumCircuit(n+1)
num=randint(0,2)
if num==0:
oracle.i(n)
if num==1:
oracle.x(n)
#test oracle for 2 qubit
if constant==False:
oracle=QuantumCircuit(n+1)
b =randint(1,2**n)
b_str = format(b, '0'+str(n)+'b')
for i in range(len(b_str)):
if b_str[i]=='1':
oracle.x(int(i))
oracle.cx(range(0,n),n)
for i in range(len(b_str)):
if b_str[i]=='1':
oracle.x(int(i))
circuit+=oracle
circuit.barrier()
except:
oracle=QuantumCircuit(n+1)
gate = dj_problem_oracle(2)
oracle.append(oracle, range(n+1))
circuit+=oracle
circuit.barrier()
circuit.draw()
#reverse initial H gates and add measurements
circuit.h(range(n))
circuit.measure(range(n),range(n))
circuit.draw()
#use Aer's qasm_simulater to execute
backend = BasicAer.get_backend('qasm_simulator')
#execute+ get results
result = execute(circuit, backend, shots = 1000).result()
#get counts of results
counts = result.get_counts()
print(counts)
constant=''
for i in range(n): constant+="0"
if max(counts)==constant: print("the function is constant")
else: print("the function is balanced")
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit
from qiskit.quantum_info import Statevector
from qiskit.visualization import plot_bloch_multivector
qc = QuantumCircuit(2)
qc.h(0)
qc.x(1)
# You can reverse the order of the qubits.
from qiskit.quantum_info import DensityMatrix
qc = QuantumCircuit(2)
qc.h([0, 1])
qc.t(1)
qc.s(0)
qc.cx(0,1)
matrix = DensityMatrix(qc)
plot_bloch_multivector(matrix, title='My Bloch Spheres', reverse_bits=True)
|
https://github.com/grossiM/Qiskit_workshop1019
|
grossiM
|
from hide_toggle import hide_toggle
#usage:
#1 create a cell with: hide_toggle(for_next=True)
#2 put the commented solution in the next cell
#import latex
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit import execute, BasicAer
import numpy as np
%matplotlib inline
#define a 2 qubit register and QuantumCircuit
hide_toggle(for_next=True)
# 2 bit registry creation.
#qr = QuantumRegister(2, 'qr')
# Circuit creation
#qc = QuantumCircuit(qr)
#solution:
#had_tr = QuantumCircuit(qr)
hide_toggle(for_next=True)
# Circuit creation of the Hadamard Transform
#had_tr = QuantumCircuit(qr)
#had_tr.h(qr[0])
#had_tr.h(qr[1])
#had_tr.barrier()
#qc = had_tr
#qc.draw(output='mpl')
#run the circuit on statevector_simulator, save result to state_superposition variable
hide_toggle(for_next=True)
# execute the quantum circuit on simulator
#backend = BasicAer.get_backend('statevector_simulator')
#job = execute(qc, backend)
#state_superposition = job.result().get_statevector(qc)
#print(state_superposition)
from qiskit.tools.visualization import plot_bloch_multivector
rho_superposition= np.outer(state_superposition, state_superposition.conj())
plot_bloch_multivector(rho_superposition)
print("\n\n\n\n===== Welcome! =====\n\n")
print(" ~~ Let's take this test ~~ ")
print("\n\n")
print("Select the winner among:")
print("a) Hearts")
print("b) Pictures")
print("c) Flowers")
print("d) Spades")
chosen = 0
while (chosen==0):
# scelta = getpass.getpass("make your choise. (a, b, c, d, e or f)\n")
scelta = input("Choose your card (a, b, c, d)\n")
if scelta == "a":
bit = "|00>"
print("Choice: a) Hearts")
if scelta == "b":
bit = "|01>"
print("Choice: b) Pictures")
if scelta == "c":
bit = "|10>"
print("Choice: c) Flowers")
if scelta == "d":
bit = "|11>"
print("Choice: d) Spades")
if scelta in ["a","b","c","d"]:
chosen = 1
print ("Linked to:", bit)
else:
print("wrong selection, retry")
#create the circuit orac
#orac = QuantumCircuit(qr)
hide_toggle(for_next=True)
#orac = QuantumCircuit(qr)
#orac.h(qr[1])
#orac.cx(qr[0],qr[1])
#orac.h(qr[1])
#orac.barrier()
#orac.draw(output='mpl')
# The Qiskit circuit object supports concatenating circuits with the addition operator.
qc = had_tr + orac
qc.draw(output='mpl')
orac = QuantumCircuit(qr)
if scelta == "a": # |00>
orac.x(qr[0])
orac.x(qr[1])
orac.h(qr[1])
orac.cx(qr[0],qr[1])
orac.h(qr[1])
orac.x(qr[0])
orac.x(qr[1])
orac.barrier()
if scelta == "b": # |01>
orac.x(qr[1])
orac.h(qr[1])
orac.cx(qr[0],qr[1])
orac.h(qr[1])
orac.x(qr[1])
orac.barrier()
if scelta == "c": # |10>
orac.x(qr[0])
orac.h(qr[1])
orac.cx(qr[0],qr[1])
orac.h(qr[1])
orac.x(qr[0])
orac.barrier()
if scelta == "d": # |11>
orac.h(qr[1])
orac.cx(qr[0],qr[1])
orac.h(qr[1])
orac.barrier()
orac.draw(output='mpl')
qc = had_tr
qc.draw(output='mpl')
backend = BasicAer.get_backend('statevector_simulator')
job = execute(qc, backend)
state = job.result().get_statevector(qc)
state
qc = had_tr + orac
qc.draw(output='mpl')
job = execute(qc, backend)
state = job.result().get_statevector(qc)
state
cphase = QuantumCircuit(qr)
cphase.x(qr[0])
cphase.x(qr[1])
cphase.h(qr[1])
cphase.cx(qr[0],qr[1])
cphase.h(qr[1])
cphase.x(qr[0])
cphase.x(qr[1])
cphase.barrier()
qc = cphase
qc.draw(output='mpl')
qc = had_tr + orac + had_tr + cphase + had_tr
qc.draw(output='mpl')
#solution:
#add classical bit register and meas, draw the circuit
hide_toggle(for_next=True)
# Create a Classical Register with 2 bits.
#cr = ClassicalRegister(2, 'cr')
# Create a Quantum Circuit
#meas = QuantumCircuit(qr, cr)
# add measurement operators
#meas.measure(qr,cr)
#qc = had_tr + orac + had_tr + cphase + had_tr + meas
#drawing the circuit
#qc.draw(output='mpl')
#solution:
#from qiskit import BasicAer
#...
#...
#print("Results : ", counts)
hide_toggle(for_next=True)
# Import Aer
#from qiskit import BasicAer
# Use Aer's qasm_simulator
#backend_sim = BasicAer.get_backend('qasm_simulator')
# Execute the circuit on the qasm simulator.
# We've set the number of repeats of the circuit
# to be 1024, which is the default.
#job = execute(qc, backend_sim)
# Grab the results from the job.
#result = job.result()
#counts = result.get_counts(qc)
#print("Results : ", counts)
from qiskit.tools.visualization import plot_histogram
plot_histogram(counts)
#1
from qiskit import IBMQ
#IBMQ.delete_accounts()
#IBMQ.save_account('API_TOKEN')
#2
provider = IBMQ.load_account()
#3
#solution:
hide_toggle(for_next=True)
#3
#print("Available backends:")
#provider.backends()
#from qiskit.tools.monitor import job_monitor, backend_monitor, backend_overview
#from qiskit.providers.ibmq import least_busy
#backend = least_busy(provider.backends(filters=lambda x: not x.configuration().simulator))
#backend.name()
#shots = 1024 # Number of shots to run the program (experiment); maximum is 8192 shots.
#max_credits = 3 # Maximum number of credits to spend on executions.
#job_exp = execute(qc, backend=backend, shots=shots, max_credits=max_credits)
#job_monitor(job_exp)
#result_real = job_exp.result()
#counts_real = result_real.get_counts(qc)
plot_histogram(counts_real)
#formulate the classical solution
hide_toggle(for_next=True)
#counter=0
#for i in ["a","b","c","d"]:
#counter=counter+1
#if i == scelta:
#print("winner found after ", counter)
import webbrowser
url_1target = 'https://www.nature.com/articles/s41467-017-01904-7/tables/1'
url_2target = 'https://www.nature.com/articles/s41467-017-01904-7/tables/2'
webbrowser.open(url_1target)
webbrowser.open(url_2target)
|
https://github.com/weiT1993/qiskit_helper_functions
|
weiT1993
|
from qiskit.providers.jobstatus import JobStatus
from qiskit.transpiler import CouplingMap
from datetime import timedelta, datetime
from pytz import timezone
import time, subprocess, os, pickle, logging, qiskit_ibm_provider
import qiskit_ibm_provider.hub_group_project
from qiskit_ibm_runtime import IBMBackend
from typing import List, Dict
import numpy as np
from qiskit_helper_functions.non_ibmq_functions import read_dict
def get_backend_info(backends: List[IBMBackend]) -> Dict:
"""
Get the IBM device information:
- Number of qubits
- Average gate error
- Current number of pending jobs
"""
backend_info = {}
for backend in backends:
if backend.simulator:
average_gate_error = 0
else:
properties = backend.properties(refresh=True).to_dict()
backend_gate_errors = []
for gate in properties["gates"]:
for parameter in gate["parameters"]:
if parameter["name"] == "gate_error":
backend_gate_errors.append(parameter["value"])
average_gate_error = np.mean(backend_gate_errors)
backend_info[backend] = {
"num_qubits": backend.num_qubits,
"average_gate_error": average_gate_error,
"num_pending_jobs": backend.status().pending_jobs,
}
return backend_info
def check_jobs(token, hub, group, project, cancel_jobs):
provider = qiskit_ibm_provider.IBMProvider(token=token)
time_now = datetime.now(timezone("EST"))
delta = timedelta(
days=1, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0
)
time_delta = time_now - delta
for x in provider.backends():
if "qasm" not in str(x):
device = provider.get_backend(str(x))
properties = device.properties()
num_qubits = len(properties.qubits)
print(
"%s: %d-qubit, max %d jobs * %d shots"
% (
x,
num_qubits,
x.configuration().max_experiments,
x.configuration().max_shots,
)
)
jobs_to_cancel = []
print("QUEUED:")
print_ctr = 0
for job in x.jobs(limit=50, status=JobStatus["QUEUED"]):
if print_ctr < 5:
print(
job.creation_date(),
job.status(),
job.queue_position(),
job.job_id(),
"ETA:",
job.queue_info().estimated_complete_time - time_now,
)
jobs_to_cancel.append(job)
print_ctr += 1
print("RUNNING:")
for job in x.jobs(limit=5, status=JobStatus["RUNNING"]):
print(job.creation_date(), job.status(), job.queue_position())
jobs_to_cancel.append(job)
print("DONE:")
for job in x.jobs(
limit=5, status=JobStatus["DONE"], start_datetime=time_delta
):
print(
job.creation_date(), job.status(), job.error_message(), job.job_id()
)
print("ERROR:")
for job in x.jobs(
limit=5, status=JobStatus["ERROR"], start_datetime=time_delta
):
print(
job.creation_date(), job.status(), job.error_message(), job.job_id()
)
if cancel_jobs and len(jobs_to_cancel) > 0:
for i in range(3):
print("Warning!!! Cancelling jobs! %d seconds count down" % (3 - i))
time.sleep(1)
for job in jobs_to_cancel:
print(
job.creation_date(),
job.status(),
job.queue_position(),
job.job_id(),
)
job.cancel()
print("cancelled")
print("-" * 100)
|
https://github.com/nicomeyer96/qiskit-torch-module
|
nicomeyer96
|
from math import sqrt, pi
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
import oracle_simple
import composed_gates
def get_circuit(n, oracles):
"""
Build the circuit composed by the oracle black box and the other quantum gates.
:param n: The number of qubits (not including the ancillas)
:param oracles: A list of black box (quantum) oracles; each of them selects a specific state
:returns: The proper quantum circuit
:rtype: qiskit.QuantumCircuit
"""
cr = ClassicalRegister(n)
## Testing
if n > 3:
#anc = QuantumRegister(n - 1, 'anc')
# n qubits for the real number
# n - 1 qubits for the ancillas
qr = QuantumRegister(n + n - 1)
qc = QuantumCircuit(qr, cr)
else:
# We don't need ancillas
qr = QuantumRegister(n)
qc = QuantumCircuit(qr, cr)
## /Testing
print("Number of qubits is {0}".format(len(qr)))
print(qr)
# Initial superposition
for j in range(n):
qc.h(qr[j])
# The length of the oracles list, or, in other words, how many roots of the function do we have
m = len(oracles)
# Grover's algorithm is a repetition of an oracle box and a diffusion box.
# The number of repetitions is given by the following formula.
print("n is ", n)
r = int(round((pi / 2 * sqrt((2**n) / m) - 1) / 2))
print("Repetition of ORACLE+DIFFUSION boxes required: {0}".format(r))
oracle_t1 = oracle_simple.OracleSimple(n, 5)
oracle_t2 = oracle_simple.OracleSimple(n, 0)
for j in range(r):
for i in range(len(oracles)):
oracles[i].get_circuit(qr, qc)
diffusion(n, qr, qc)
for j in range(n):
qc.measure(qr[j], cr[j])
return qc, len(qr)
def diffusion(n, qr, qc):
"""
The Grover diffusion operator.
Given the arry of qiskit QuantumRegister qr and the qiskit QuantumCircuit qc, it adds the diffusion operator to the appropriate qubits in the circuit.
"""
for j in range(n):
qc.h(qr[j])
# D matrix, flips state |000> only (instead of flipping all the others)
for j in range(n):
qc.x(qr[j])
# 0..n-2 control bits, n-1 target, n..
if n > 3:
composed_gates.n_controlled_Z_circuit(
qc, [qr[j] for j in range(n - 1)], qr[n - 1],
[qr[j] for j in range(n, n + n - 1)])
else:
composed_gates.n_controlled_Z_circuit(
qc, [qr[j] for j in range(n - 1)], qr[n - 1], None)
for j in range(n):
qc.x(qr[j])
for j in range(n):
qc.h(qr[j])
|
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.
"""
Exception for errors raised by Qiskit Aer simulators backends.
"""
from qiskit import QiskitError
class QrackError(QiskitError):
"""Base class for errors raised by simulators."""
def __init__(self, *message):
"""Set the error message."""
super().__init__(*message)
self.message = ' '.join(message)
def __str__(self):
"""Return the message."""
return repr(self.message)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit.algorithms.optimizers import SLSQP
from qiskit.circuit.library import TwoLocal
num_qubits = 2
ansatz = TwoLocal(num_qubits, "ry", "cz")
optimizer = SLSQP(maxiter=1000)
ansatz.decompose().draw("mpl", style="iqx")
from qiskit.primitives import Estimator
estimator = Estimator()
from qiskit.algorithms.minimum_eigensolvers import VQE
vqe = VQE(estimator, ansatz, optimizer)
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)
])
result = vqe.compute_minimum_eigenvalue(H2_op)
print(result)
from qiskit.algorithms.optimizers import SPSA
estimator = Estimator(options={"shots": 1000})
vqe.estimator = estimator
vqe.optimizer = SPSA(maxiter=100)
result = vqe.compute_minimum_eigenvalue(operator=H2_op)
print(result)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/kardashin/E91_protocol
|
kardashin
|
# Checking the version of PYTHON; we only support > 3.5
import sys
if sys.version_info < (3,5):
raise Exception('Please use Python version 3.5 or greater.')
# useful additional packages
import numpy as np
import random
import math
import re # regular expressions module
# importing the QISKit
from qiskit import QuantumCircuit, QuantumProgram
import Qconfig
# Quantum program setup
Q_program = QuantumProgram()
#Q_program.set_api(Qconfig.APItoken, Qconfig.config['url']) # set the APIToken and API url
# Creating registers
qr = Q_program.create_quantum_register("qr", 2)
cr = Q_program.create_classical_register("cr", 4)
singlet = Q_program.create_circuit('singlet', [qr], [cr])
singlet.x(qr[0])
singlet.x(qr[1])
singlet.h(qr[0])
singlet.cx(qr[0],qr[1])
## Alice's measurement circuits
# measure the spin projection of Alice's qubit onto the a_1 direction (X basis)
measureA1 = Q_program.create_circuit('measureA1', [qr], [cr])
measureA1.h(qr[0])
measureA1.measure(qr[0],cr[0])
# measure the spin projection of Alice's qubit onto the a_2 direction (W basis)
measureA2 = Q_program.create_circuit('measureA2', [qr], [cr])
measureA2.s(qr[0])
measureA2.h(qr[0])
measureA2.t(qr[0])
measureA2.h(qr[0])
measureA2.measure(qr[0],cr[0])
# measure the spin projection of Alice's qubit onto the a_3 direction (standard Z basis)
measureA3 = Q_program.create_circuit('measureA3', [qr], [cr])
measureA3.measure(qr[0],cr[0])
## Bob's measurement circuits
# measure the spin projection of Bob's qubit onto the b_1 direction (W basis)
measureB1 = Q_program.create_circuit('measureB1', [qr], [cr])
measureB1.s(qr[1])
measureB1.h(qr[1])
measureB1.t(qr[1])
measureB1.h(qr[1])
measureB1.measure(qr[1],cr[1])
# measure the spin projection of Bob's qubit onto the b_2 direction (standard Z basis)
measureB2 = Q_program.create_circuit('measureB2', [qr], [cr])
measureB2.measure(qr[1],cr[1])
# measure the spin projection of Bob's qubit onto the b_3 direction (V basis)
measureB3 = Q_program.create_circuit('measureB3', [qr], [cr])
measureB3.s(qr[1])
measureB3.h(qr[1])
measureB3.tdg(qr[1])
measureB3.h(qr[1])
measureB3.measure(qr[1],cr[1])
## Lists of measurement circuits
aliceMeasurements = [measureA1, measureA2, measureA3]
bobMeasurements = [measureB1, measureB2, measureB3]
# Define the number of singlets N
numberOfSinglets = 500
aliceMeasurementChoices = [random.randint(1, 3) for i in range(numberOfSinglets)] # string b of Alice
bobMeasurementChoices = [random.randint(1, 3) for i in range(numberOfSinglets)] # string b' of Bob
circuits = [] # the list in which the created circuits will be stored
for i in range(numberOfSinglets):
# create the name of the i-th circuit depending on Alice's and Bob's measurement choices
circuitName = str(i) + ':A' + str(aliceMeasurementChoices[i]) + '_B' + str(bobMeasurementChoices[i])
# create the joint measurement circuit
# add Alice's and Bob's measurement circuits to the singlet state curcuit
Q_program.add_circuit(circuitName,
singlet + # singlet state circuit
aliceMeasurements[aliceMeasurementChoices[i]-1] + # measurement circuit of Alice
bobMeasurements[bobMeasurementChoices[i]-1] # measurement circuit of Bob
)
# add the created circuit to the circuits list
circuits.append(circuitName)
print(circuits[0])
result = Q_program.execute(circuits, backend='local_qasm_simulator', shots=1, max_credits=5, wait=10, timeout=240)
print(result)
result.get_counts(circuits[0])
abPatterns = [
re.compile('..00$'), # search for the '..00' output (Alice obtained -1 and Bob obtained -1)
re.compile('..01$'), # search for the '..01' output
re.compile('..10$'), # search for the '..10' output (Alice obtained -1 and Bob obtained 1)
re.compile('..11$') # search for the '..11' output
]
aliceResults = [] # Alice's results (string a)
bobResults = [] # Bob's results (string a')
for i in range(numberOfSinglets):
res = list(result.get_counts(circuits[i]).keys())[0] # extract the key from the dict and transform it to str; execution result of the i-th circuit
if abPatterns[0].search(res): # check if the key is '..00' (if the measurement results are -1,-1)
aliceResults.append(-1) # Alice got the result -1
bobResults.append(-1) # Bob got the result -1
if abPatterns[1].search(res):
aliceResults.append(1)
bobResults.append(-1)
if abPatterns[2].search(res): # check if the key is '..10' (if the measurement results are -1,1)
aliceResults.append(-1) # Alice got the result -1
bobResults.append(1) # Bob got the result 1
if abPatterns[3].search(res):
aliceResults.append(1)
bobResults.append(1)
aliceKey = [] # Alice's key string k
bobKey = [] # Bob's key string k'
# comparing the stings with measurement choices
for i in range(numberOfSinglets):
# if Alice and Bob have measured the spin projections onto the a_2/b_1 or a_3/b_2 directions
if (aliceMeasurementChoices[i] == 2 and bobMeasurementChoices[i] == 1) or (aliceMeasurementChoices[i] == 3 and bobMeasurementChoices[i] == 2):
aliceKey.append(aliceResults[i]) # record the i-th result obtained by Alice as the bit of the secret key k
bobKey.append(- bobResults[i]) # record the multiplied by -1 i-th result obtained Bob as the bit of the secret key k'
keyLength = len(aliceKey) # length of the secret key
abKeyMismatches = 0 # number of mismatching bits in Alice's and Bob's keys
for j in range(keyLength):
if aliceKey[j] != bobKey[j]:
abKeyMismatches += 1
# function that calculates CHSH correlation value
def chsh_corr(result):
# lists with the counts of measurement results
# each element represents the number of (-1,-1), (-1,1), (1,-1) and (1,1) results respectively
countA1B1 = [0, 0, 0, 0] # XW observable
countA1B3 = [0, 0, 0, 0] # XV observable
countA3B1 = [0, 0, 0, 0] # ZW observable
countA3B3 = [0, 0, 0, 0] # ZV observable
for i in range(numberOfSinglets):
res = list(result.get_counts(circuits[i]).keys())[0]
# if the spins of the qubits of the i-th singlet were projected onto the a_1/b_1 directions
if (aliceMeasurementChoices[i] == 1 and bobMeasurementChoices[i] == 1):
for j in range(4):
if abPatterns[j].search(res):
countA1B1[j] += 1
if (aliceMeasurementChoices[i] == 1 and bobMeasurementChoices[i] == 3):
for j in range(4):
if abPatterns[j].search(res):
countA1B3[j] += 1
if (aliceMeasurementChoices[i] == 3 and bobMeasurementChoices[i] == 1):
for j in range(4):
if abPatterns[j].search(res):
countA3B1[j] += 1
# if the spins of the qubits of the i-th singlet were projected onto the a_3/b_3 directions
if (aliceMeasurementChoices[i] == 3 and bobMeasurementChoices[i] == 3):
for j in range(4):
if abPatterns[j].search(res):
countA3B3[j] += 1
# number of the results obtained from the measurements in a particular basis
total11 = sum(countA1B1)
total13 = sum(countA1B3)
total31 = sum(countA3B1)
total33 = sum(countA3B3)
# expectation values of XW, XV, ZW and ZV observables (2)
expect11 = (countA1B1[0] - countA1B1[1] - countA1B1[2] + countA1B1[3])/total11 # -1/sqrt(2)
expect13 = (countA1B3[0] - countA1B3[1] - countA1B3[2] + countA1B3[3])/total13 # 1/sqrt(2)
expect31 = (countA3B1[0] - countA3B1[1] - countA3B1[2] + countA3B1[3])/total31 # -1/sqrt(2)
expect33 = (countA3B3[0] - countA3B3[1] - countA3B3[2] + countA3B3[3])/total33 # -1/sqrt(2)
corr = expect11 - expect13 + expect31 + expect33 # calculate the CHSC correlation value (3)
return corr
corr = chsh_corr(result) # CHSH correlation value
# CHSH inequality test
print('CHSH correlation value: ' + str(round(corr, 3)))
# Keys
print('Length of the key: ' + str(keyLength))
print('Number of mismatching bits: ' + str(abKeyMismatches) + '\n')
# measurement of the spin projection of Alice's qubit onto the a_2 direction (W basis)
measureEA2 = Q_program.create_circuit('measureEA2', [qr], [cr])
measureEA2.s(qr[0])
measureEA2.h(qr[0])
measureEA2.t(qr[0])
measureEA2.h(qr[0])
measureEA2.measure(qr[0],cr[2])
# measurement of the spin projection of Allice's qubit onto the a_3 direction (standard Z basis)
measureEA3 = Q_program.create_circuit('measureEA3', [qr], [cr])
measureEA3.measure(qr[0],cr[2])
# measurement of the spin projection of Bob's qubit onto the b_1 direction (W basis)
measureEB1 = Q_program.create_circuit('measureEB1', [qr], [cr])
measureEB1.s(qr[1])
measureEB1.h(qr[1])
measureEB1.t(qr[1])
measureEB1.h(qr[1])
measureEB1.measure(qr[1],cr[3])
# measurement of the spin projection of Bob's qubit onto the b_2 direction (standard Z measurement)
measureEB2 = Q_program.create_circuit('measureEB2', [qr], [cr])
measureEB2.measure(qr[1],cr[3])
# lists of measurement circuits
eveMeasurements = [measureEA2, measureEA3, measureEB1, measureEB2]
# list of Eve's measurement choices
# the first and the second elements of each row represent the measurement of Alice's and Bob's qubits by Eve respectively
eveMeasurementChoices = []
for j in range(numberOfSinglets):
if random.uniform(0, 1) <= 0.5: # in 50% of cases perform the WW measurement
eveMeasurementChoices.append([0, 2])
else: # in 50% of cases perform the ZZ measurement
eveMeasurementChoices.append([1, 3])
circuits = [] # the list in which the created circuits will be stored
for j in range(numberOfSinglets):
# create the name of the j-th circuit depending on Alice's, Bob's and Eve's choices of measurement
circuitName = str(j) + ':A' + str(aliceMeasurementChoices[j]) + '_B' + str(bobMeasurementChoices[j] + 2) + '_E' + str(eveMeasurementChoices[j][0]) + str(eveMeasurementChoices[j][1] - 1)
# create the joint measurement circuit
# add Alice's and Bob's measurement circuits to the singlet state curcuit
Q_program.add_circuit(circuitName,
singlet + # singlet state circuit
eveMeasurements[eveMeasurementChoices[j][0]-1] + # Eve's measurement circuit of Alice's qubit
eveMeasurements[eveMeasurementChoices[j][1]-1] + # Eve's measurement circuit of Bob's qubit
aliceMeasurements[aliceMeasurementChoices[j]-1] + # measurement circuit of Alice
bobMeasurements[bobMeasurementChoices[j]-1] # measurement circuit of Bob
)
# add the created circuit to the circuits list
circuits.append(circuitName)
result = Q_program.execute(circuits, backend='local_qasm_simulator', shots=1, max_credits=5, wait=10, timeout=240)
print(result)
print(str(circuits[0]) + '\t' + str(result.get_counts(circuits[0])))
ePatterns = [
re.compile('00..$'), # search for the '00..' result (Eve obtained the results -1 and -1 for Alice's and Bob's qubits)
re.compile('01..$'), # search for the '01..' result (Eve obtained the results 1 and -1 for Alice's and Bob's qubits)
re.compile('10..$'),
re.compile('11..$')
]
aliceResults = [] # Alice's results (string a)
bobResults = [] # Bob's results (string a')
# list of Eve's measurement results
# the elements in the 1-st column are the results obtaned from the measurements of Alice's qubits
# the elements in the 2-nd column are the results obtaned from the measurements of Bob's qubits
eveResults = []
# recording the measurement results
for j in range(numberOfSinglets):
res = list(result.get_counts(circuits[j]).keys())[0] # extract a key from the dict and transform it to str
# Alice and Bob
if abPatterns[0].search(res): # check if the key is '..00' (if the measurement results are -1,-1)
aliceResults.append(-1) # Alice got the result -1
bobResults.append(-1) # Bob got the result -1
if abPatterns[1].search(res):
aliceResults.append(1)
bobResults.append(-1)
if abPatterns[2].search(res): # check if the key is '..10' (if the measurement results are -1,1)
aliceResults.append(-1) # Alice got the result -1
bobResults.append(1) # Bob got the result 1
if abPatterns[3].search(res):
aliceResults.append(1)
bobResults.append(1)
# Eve
if ePatterns[0].search(res): # check if the key is '00..'
eveResults.append([-1, -1]) # results of the measurement of Alice's and Bob's qubits are -1,-1
if ePatterns[1].search(res):
eveResults.append([1, -1])
if ePatterns[2].search(res):
eveResults.append([-1, 1])
if ePatterns[3].search(res):
eveResults.append([1, 1])
aliceKey = [] # Alice's key string a
bobKey = [] # Bob's key string a'
eveKeys = [] # Eve's keys; the 1-st column is the key of Alice, and the 2-nd is the key of Bob
# comparing the strings with measurement choices (b and b')
for j in range(numberOfSinglets):
# if Alice and Bob measured the spin projections onto the a_2/b_1 or a_3/b_2 directions
if (aliceMeasurementChoices[j] == 2 and bobMeasurementChoices[j] == 1) or (aliceMeasurementChoices[j] == 3 and bobMeasurementChoices[j] == 2):
aliceKey.append(aliceResults[j]) # record the i-th result obtained by Alice as the bit of the secret key k
bobKey.append(-bobResults[j]) # record the multiplied by -1 i-th result obtained Bob as the bit of the secret key k'
eveKeys.append([eveResults[j][0], -eveResults[j][1]]) # record the i-th bits of the keys of Eve
keyLength = len(aliceKey) # length of the secret skey
abKeyMismatches = 0 # number of mismatching bits in the keys of Alice and Bob
eaKeyMismatches = 0 # number of mismatching bits in the keys of Eve and Alice
ebKeyMismatches = 0 # number of mismatching bits in the keys of Eve and Bob
for j in range(keyLength):
if aliceKey[j] != bobKey[j]:
abKeyMismatches += 1
if eveKeys[j][0] != aliceKey[j]:
eaKeyMismatches += 1
if eveKeys[j][1] != bobKey[j]:
ebKeyMismatches += 1
eaKnowledge = (keyLength - eaKeyMismatches)/keyLength # Eve's knowledge of Bob's key
ebKnowledge = (keyLength - ebKeyMismatches)/keyLength # Eve's knowledge of Alice's key
corr = chsh_corr(result)
# CHSH inequality test
print('CHSH correlation value: ' + str(round(corr, 3)) + '\n')
# Keys
print('Length of the key: ' + str(keyLength))
print('Number of mismatching bits: ' + str(abKeyMismatches) + '\n')
print('Eve\'s knowledge of Alice\'s key: ' + str(round(eaKnowledge * 100, 2)) + ' %')
print('Eve\'s knowledge of Bob\'s key: ' + str(round(ebKnowledge * 100, 2)) + ' %')
|
https://github.com/Tojarieh97/VQE
|
Tojarieh97
|
import nbimporter
from typing import Dict, Tuple, List
import numpy as np
from tqdm import tqdm
QUBITS_NUM = 4
N = 16
K = 4
NUM_SHOTS = 1024
NUM_ITERATIONS = 50
w_vector = np.asarray([4,3,2,1])
from qiskit import Aer
from qiskit.utils import QuantumInstance, algorithm_globals
seed = 50
algorithm_globals.random_seed = seed
simulator_backend = Aer.get_backend('qasm_simulator')
from scipy.optimize import minimize
from utiles import *
input_states = get_first_k_eigenvectors_from_n_computational_basis(K, N)
from ansatz_circuit_item2 import get_full_variational_quantum_circuit
init_circuit_params = {
"thetas": np.random.uniform(low=0, high=2*np.pi, size=8),
"phis": np.random.uniform(low=0, high=2*np.pi, size=4),
"D1": 2,
"D2": 8
}
def prepare_circuit_params(thetas) -> Dict:
return {
"thetas": thetas[4:],
"phis": thetas[:4],
"D1": 2,
"D2": 8
}
def get_ansatz_state(circuit_params, input_state):
circuit_params_with_input_state = {**circuit_params, "input_state": input_state}
return get_full_variational_quantum_circuit(**circuit_params_with_input_state)
def transfrom_hamiltonian_into_pauli_strings(hamiltonian) -> List:
pauli_operators = hamiltonian.to_pauli_op().settings['oplist']
pauli_coeffs = list(map(lambda pauli_operator: pauli_operator.coeff, pauli_operators))
pauli_strings = list(map(lambda pauli_operator: pauli_operator.primitive, pauli_operators))
return pauli_coeffs, pauli_strings
from qiskit.circuit.library.standard_gates import HGate, SGate
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
reducing_to_pauli_z_mapping = {
'I': 'I',
'Z': 'Z',
'X': 'Z',
'Y': 'Z'
}
def reduce_pauli_matrixes_into_sigma_z(pauli_string) -> str:
reduced_pauli_string = ""
for matrix_index in range(QUBITS_NUM):
pauli_matrix = str(pauli_string[matrix_index])
reduced_pauli_matrix = reducing_to_pauli_z_mapping[pauli_matrix]
reduced_pauli_string = reduced_pauli_matrix + reduced_pauli_string
return reduced_pauli_string
def add_layer_of_gates_for_reducing_paulis_to_sigma_z(pauli_string, quantum_circuit):
quantum_registers = QuantumRegister(QUBITS_NUM, name="qubit")
additional_circuit_layer = QuantumCircuit(quantum_registers)
for quantum_register_index, pauli_matrix in enumerate(pauli_string):
if pauli_matrix == "X":
additional_circuit_layer.append(HGate(), [quantum_registers[quantum_register_index]])
if pauli_string == "Y":
additional_circuit_layer.append(HGate(), [quantum_registers[quantum_register_index]])
additional_circuit_layer.append(SGate(), [quantum_registers[quantum_register_index]])
extended_quantum_circuit = quantum_circuit.compose(additional_circuit_layer)
return extended_quantum_circuit
def get_probability_distribution(counts: Dict) -> Dict:
proba_distribution = {state: (count / NUM_SHOTS) for state, count in counts.items()}
return proba_distribution
def calculate_probabilities_of_measurments_in_computational_basis(quantum_state_circuit) -> Dict:
quantum_state_circuit.measure_all()
transpiled_quantum_state_circuit = transpile(quantum_state_circuit, simulator_backend)
Qobj = assemble(transpiled_quantum_state_circuit)
result = simulator_backend.run(Qobj).result()
counts = result.get_counts(quantum_state_circuit)
return get_probability_distribution(counts)
def sort_probas_dict_by_qubits_string_keys(proba_distribution: Dict) -> Dict:
return dict(sorted(proba_distribution.items()))
def reset_power_of_minus_1(power_of_minus_1):
power_of_minus_1 = 0
return power_of_minus_1
def convert_pauli_string_into_str(pauli_string) -> str:
return str(pauli_string)
def calculate_expectation_value_of_pauli_string_by_measurments_probas(pauli_string, ansatz_circuit):
pauli_string_expectation_value = 0
power_of_minus_1 = 0
pauli_string_str = convert_pauli_string_into_str(pauli_string)
extended_ansatz_circuit = add_layer_of_gates_for_reducing_paulis_to_sigma_z(pauli_string_str, ansatz_circuit)
probas_distribution = calculate_probabilities_of_measurments_in_computational_basis(extended_ansatz_circuit)
reduced_pauli_string = reduce_pauli_matrixes_into_sigma_z(pauli_string)
sorted_probas_distribuition = sort_probas_dict_by_qubits_string_keys(probas_distribution)
for qubits_string, proba in sorted_probas_distribuition.items():
for string_index in range(QUBITS_NUM):
if(str(qubits_string[string_index])=="1" and str(pauli_string[string_index])=="Z"):
power_of_minus_1 += 1
pauli_string_expectation_value += pow(-1, power_of_minus_1)*proba
power_of_minus_1 = reset_power_of_minus_1(power_of_minus_1)
return pauli_string_expectation_value
def get_expectation_value(ansatz_circuit, pauli_coeffs, pauli_strings):
total_expection_value = 0
for pauli_coeff, pauli_string in zip(pauli_coeffs, pauli_strings):
total_expection_value += pauli_coeff*calculate_expectation_value_of_pauli_string_by_measurments_probas(
pauli_string, ansatz_circuit)
return total_expection_value
from qiskit import assemble, transpile
def cost_function(thetas, hamiltonian):
L_w = 0
circuit_params = prepare_circuit_params(thetas)
computational_eigenvectors = get_first_k_eigenvectors_from_n_computational_basis(K, N)
pauli_coeffs, pauli_strings = transfrom_hamiltonian_into_pauli_strings(LiH_molecule_4_qubits)
for j in tqdm(range(K)):
ansatz_state = get_ansatz_state(circuit_params, computational_eigenvectors[j])
approximated_energy = get_expectation_value(ansatz_state, pauli_coeffs, pauli_strings)
insert_approximated_energy_to_list_of_all_approximated_energies(
approximated_energies_dict["approximated_eneriges_"+str(j)], approximated_energy)
L_w += w_vector[j]*approximated_energy
return L_w
def get_optimal_thetas_of_ansatz_circuit_for_hamiltonian(hamiltonian):
initial_thetas = np.random.uniform(low=0, high=360, size=12)
optimizer_result = minimize(
cost_function,
x0=initial_thetas,
args=(hamiltonian),
method="BFGS",
options={"maxiter":NUM_ITERATIONS})
optimal_thetas = prepare_circuit_params(optimizer_result.x)
return optimal_thetas
def get_approximated_k_eigenvalues_of_hamiltonian(hamiltonian):
approximated_k_eigenvalues = []
optimal_thetas = get_optimal_thetas_of_ansatz_circuit_for_hamiltonian(hamiltonian)
computational_eigenvectors = get_first_k_eigenvectors_from_n_computational_basis(K, N)
pauli_coeffs, pauli_strings = transfrom_hamiltonian_into_pauli_strings(hamiltonian)
for eigenvalue_index, eigenvector in enumerate(computational_eigenvectors):
optimal_ansatz_state = get_ansatz_state(optimal_thetas, eigenvector)
approximated_eigenvalue = get_expectation_value(optimal_ansatz_state, pauli_coeffs, pauli_strings)
approximated_k_eigenvalues.append(approximated_eigenvalue)
return approximated_k_eigenvalues
from numpy import linalg as LA
from statistics import mean
def get_mean_approximation_error(exact_k_eigenvalues, approximated_k_eigenvalues):
approximated_errors = []
for exact_eigenvalue, approximated_eigenvalue in zip(exact_k_eigenvalues, approximated_k_eigenvalues):
approximated_errors.append(abs(abs(exact_eigenvalue)-abs(approximated_eigenvalue))/abs(exact_eigenvalue))
return mean(approximated_errors)
def get_exact_k_eigenvalues_of_hamiltonian(hamiltonian, k):
eigenvalues = LA.eig(hamiltonian.to_matrix())[0]
return sorted(eigenvalues)[:k]
def compare_exact_and_approximated_eigenvectors(hamiltonian, approximated_k_eigenvalues):
exact_k_eigenvalues = get_exact_k_eigenvalues_of_hamiltonian(hamiltonian, K)
print("Exact K Eigenvalues:")
print(exact_k_eigenvalues)
print("\nApproximated K Eigenvalues:")
print(approximated_k_eigenvalues)
print("\nMean Approximation error:")
print(get_mean_approximation_error(exact_k_eigenvalues, approximated_k_eigenvalues))
approximated_energies_dict = { "approximated_eneriges_0": [],
"approximated_eneriges_1":[],
"approximated_eneriges_2": [],
"approximated_eneriges_3": []}
def initialize_approximated_energies_dict():
return { "approximated_eneriges_0": [],
"approximated_eneriges_1":[],
"approximated_eneriges_2": [],
"approximated_eneriges_3": []}
def insert_approximated_energy_to_list_of_all_approximated_energies(approximated_energies_list, energy):
approximated_energies_list.append(energy)
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
def plot_convergence_of_optimization_process(approximated_energies, hamiltonian, margin=0.02):
plt.title("convergence of optimization process to the exact eigenvalue")
plt.margins(0,margin)
base_colors_list = list(mcolors.BASE_COLORS.keys())
exact_k_eigenvalues = get_exact_k_eigenvalues_of_hamiltonian(hamiltonian, K)
print(exact_k_eigenvalues)
for energy_level, eigenvalue in enumerate(exact_k_eigenvalues):
energy_level_name = "E_{0}".format(str(energy_level))
plt.axhline(y = eigenvalue,
color = base_colors_list[energy_level],
linestyle = 'dotted', label=energy_level_name)
plt.plot(approximated_energies["approximated_eneriges_{0}".format(str(energy_level))],
color = base_colors_list[energy_level],
label="Weighted_SSVQE({0})".format(energy_level_name))
# plt.plot(approximated_energies["approximated_eneriges_0"])
# plt.plot(approximated_energies["approximated_eneriges_1"])
# plt.plot(approximated_energies["approximated_eneriges_2"])
# plt.plot(approximated_energies["approximated_eneriges_3"])
plt.xlabel("# of iterations")
plt.ylabel("Energy")
plt.legend(loc='center left', bbox_to_anchor=(1, 0.5))
def plot_fidelity():
plt.plot(LiH_approximated_energies)
plt.xlabel("# of iterations")
plt.ylabel("Energy")
from qiskit.opflow import X, Z, Y, I, H, S
LiH_molecule_4_qubits = -7.49894690201071*(I^I^I^I) + \
-0.0029329964409502266*(X^X^Y^Y) + \
0.0029329964409502266*(X^Y^Y^X) + \
0.01291078027311749*(X^Z^X^I) + \
-0.0013743761078958677*(X^Z^X^Z) + \
0.011536413200774975*(X^I^X^I) + \
0.0029329964409502266*(Y^X^X^Y) + \
-0.0029329964409502266*(Y^Y^X^X) + \
0.01291078027311749*(Y^Z^Y^I) + \
-0.0013743761078958677*(Y^Z^Y^Z) + \
0.011536413200774975*(Y^I^Y^I) + \
0.16199475388004184*(Z^I^I^I) + \
0.011536413200774975*(Z^X^Z^X) + \
0.011536413200774975*(Z^Y^Z^Y) + \
0.12444770133137588*(Z^Z^I^I) + \
0.054130445793298836*(Z^I^Z^I) + \
0.05706344223424907*(Z^I^I^Z) + \
0.012910780273117487*(I^X^Z^X) + \
-0.0013743761078958677*(I^X^I^X) + \
0.012910780273117487*(I^Y^Z^Y) + \
-0.0013743761078958677*(I^Y^I^Y) + \
0.16199475388004186*(I^Z^I^I) + \
0.05706344223424907*(I^Z^Z^I) + \
0.054130445793298836*(I^Z^I^Z) + \
-0.013243698330265966*(I^I^Z^I) + \
0.08479609543670981*(I^I^Z^Z) + \
-0.013243698330265952*(I^I^I^Z)
%%time
LiH_approximated_k_eigenvalues = get_approximated_k_eigenvalues_of_hamiltonian(LiH_molecule_4_qubits)
compare_exact_and_approximated_eigenvectors(LiH_molecule_4_qubits, LiH_approximated_k_eigenvalues)
print(approximated_energies_dict)
approximated_energies_dict = initialize_approximated_energies_dict()
LiH_approximated_energies = {'approximated_eneriges_0': [-7.562071486292104, -7.551346757429608, -7.552944523914135, -7.560116772775394, -7.565448199837231, -7.562546777411176, -7.556370586953186, -7.5674961396597515, -7.562868323640123, -7.569727297671011, -7.577241001152592, -7.569901653592553, -7.560170928569707, -7.50450294015484, -7.507421280130349, -7.513641444931524, -7.505252370983593, -7.504378338149738, -7.511089721083689, -7.492616949145766, -7.504733592874844, -7.505057286909975, -7.500944996847547, -7.510777395650015, -7.50684214460726, -7.494074441023492, -7.560548573373164, -7.562214184024206, -7.568477882703838, -7.5455461632531655, -7.564340538776625, -7.553988541052734, -7.5451955641745085, -7.5609456305954925, -7.5483501889539975, -7.556677716954072, -7.56005590213002, -7.5631439275507315, -7.553392111383577, -7.556743753345377, -7.561551788828242, -7.555342548733728, -7.556766445089764, -7.553542895341899, -7.559683391361186, -7.560925469458819, -7.563572357485119, -7.567151568002535, -7.571946591188674, -7.570142191678787, -7.557106639758928, -7.558439292968819, -7.574579104067784, -7.562883709761341, -7.543713858491556, -7.564720803456668, -7.5457497014403065, -7.558969672912834, -7.572319575797064, -7.56292452904019, -7.573479760327174, -7.562199030564257, -7.568681686528937, -7.563004496841959, -7.560909055570279, -7.563440128011368, -7.559393749815729, -7.555472180892113, -7.562844249951609, -7.558531024188177, -7.575698822248928, -7.55404084909291, -7.567979735908607, -7.557018847801117, -7.560978919569245, -7.561794829078547, -7.562143635631656, -7.566271922325941, -7.560839611270146, -7.5568033902098195, -7.58142513791027, -7.573881846816633, -7.558732728073843, -7.56231060585952, -7.551624934331701, -7.551909164866761, -7.5638131868631815, -7.549845397747916, -7.5589181330700805, -7.540495085034901, -7.577617386377836, -7.562660697312212, -7.5559425308224695, -7.561386635696937, -7.577264904915713, -7.553963097036648, -7.573178097168689, -7.580582024019519, -7.5702738283835815, -7.556843980390578, -7.559149777706205, -7.569885360295614, -7.567209735965058, -7.555616248808023, -7.568195665853206, -7.568236031253794, -7.569588764497501, -7.5469170982088745, -7.551910171848012, -7.56070080426784, -7.55777115024099, -7.559179078756845, -7.571503944007687, -7.563577336071192, -7.568322764040547, -7.570259682411341, -7.5752124577109825, -7.574351422210891, -7.568048101368627, -7.5574802857572765, -7.5698666855121735, -7.574140547848547, -7.562281537007218, -7.560887200033612, -7.561833170760727, -7.566703915939199, -7.557248337704557, -7.552393839555408, -7.564795356944313, -7.563885543697337, -7.559295993912143, -7.551819460291054, -7.558610716537125, -7.572150334020591, -7.564829143448873, -7.5649749821297005, -7.559880775892233, -7.562095014235116, -7.555258749423826, -7.563330197776976, -7.576172555094606, -7.56109702344153, -7.560220437853168, -7.563316771592021, -7.55927764982648, -7.559489229938778, -7.560311914696335, -7.5758565696485105, -7.575167851245861, -7.559661332074081, -7.570187549559718, -7.565836319171639, -7.561504371857765, -7.57023042999233, -7.557965382900609, -7.5588943241487385, -7.565503057849797, -7.566276315012363, -7.556233953236954, -7.555144578373757, -7.573777660175128, -7.559991356466428, -7.542063221770774, -7.559407920550896, -7.568143821006155, -7.563686528171099, -7.5642605095860445, -7.5618362170315825, -7.571431894796191, -7.553895503314807, -7.5582535646354065, -7.567586909130106, -7.565961202348206, -7.568978997128765, -7.559340951338928, -7.56445806146827, -7.5556876792359695, -7.56460053303355, -7.570850901726988, -7.568585489747921, -7.557607035779572, -7.564746300706346, -7.561021813150516, -7.562876730931318, -7.571504302167662, -7.561367947755987, -7.566122191231275, -7.560375807672051, -7.561596670973815, -7.557932614828941, -7.560059245807887, -7.569372561667943, -7.577526582464007, -7.565419191759633, -7.560723711434731, -7.560687793830521, -7.567853605434033, -7.5695315149905165, -7.559057395081173, -7.576396592141188, -7.569482907819277, -7.566176238781431, -7.559480733078293, -7.555440467881515, -7.5722562004117355, -7.563561051500816, -7.569102134783019, -7.5624251768939255, -7.553238644209887, -7.566688525378806, -7.57427446525249, -7.5630089364129, -7.559170646039951, -7.573016576285714, -7.584234644863586, -7.563774665710167, -7.559999708140727, -7.558618140639516, -7.55225503083047, -7.557642799541379, -7.563901866709506, -7.553289758355393, -7.558633780019458, -7.572573129411478, -7.557194844186757, -7.556664728469042, -7.559564789456388, -7.565594323797267, -7.555190264866648, -7.561624263586976, -7.569789625285521, -7.5690157809803456, -7.544118474969882, -7.561047611370386, -7.554555222654382, -7.546317221250312, -7.567349270266024, -7.5673888180098325, -7.561428441164426, -7.560936846098908, -7.583650803960547, -7.572308414798167, -7.557746434820991, -7.563764459606351, -7.5587571353624, -7.563416427888439, -7.569696456404504, -7.562540355868497, -7.560495854027838, -7.567457286444577, -7.570867740017869, -7.567086356575003, -7.560381244145666, -7.547049169199666, -7.555784321622338, -7.569474376081687, -7.5722757014839654, -7.560066374314964, -7.554831247356704, -7.549778933470774, -7.550601706977019, -7.570006340302589, -7.564876409869264, -7.564559009400159, -7.560123971954665, -7.5565573892896944, -7.5491087521206195, -7.570018687683115, -7.553176898896319, -7.5638762714361905, -7.558619243737311, -7.555619087766442, -7.564029863039117, -7.555163295228039, -7.56290446645362, -7.575012659147997, -7.552840275809348, -7.5799696493221855, -7.567475401942004, -7.56305130559502, -7.563508335327721, -7.555894563238186, -7.572075891781376, -7.555604946309137, -7.558284106172176, -7.567270751416418, -7.552151995055932, -7.573093018147093, -7.565849448615926, -7.560728523332386, -7.561475572421954, -7.557857962584839, -7.57102858041606, -7.5601827041613445, -7.5473846644268905, -7.567554019242569, -7.566923472324098, -7.571172604068238, -7.573534646914643, -7.568365397345586, -7.573096907598021, -7.568072358316656, -7.5624371348290484, -7.569334313303235, -7.569107128693299, -7.569438063580029, -7.557081199304223, -7.556793444721364, -7.565564138171619, -7.584047083603657, -7.550468510480313, -7.5721701200656755, -7.561405357628065, -7.568843499808381, -7.582132396455182, -7.56188172212797, -7.565780797594704, -7.5581809752026645, -7.563924689693823, -7.568310006966299, -7.570973966169818, -7.566526969313047, -7.556837856869171, -7.556959357100385, -7.55802539600483, -7.560157547145864, -7.558819606357595, -7.5716432114033685, -7.574679379170924, -7.558314028696738, -7.5592360010565995, -7.552304228834449, -7.567720644203105, -7.553819160843, -7.564363448769347, -7.5667092400451255, -7.558673226311031, -7.557102272988306, -7.56406445986514, -7.550601245662824, -7.5642687847953, -7.562428841944573, -7.554217816157429, -7.567761628415078, -7.559682214760878, -7.571207288584289, -7.550142299269893, -7.570586131073872, -7.5605912454613655, -7.556847794745476, -7.559811269546062, -7.570036341292319, -7.564677334894062, -7.563188252164309, -7.563738648634944, -7.562081214609168, -7.565029085996614, -7.552285855207653, -7.5587401551887785, -7.567044590000477, -7.554827834724664, -7.564142970628503, -7.570785867741189, -7.5568222014998785, -7.565658174898904, -7.56968748071879, -7.554067354326688, -7.566300026647628, -7.55845704485936, -7.551501158686343, -7.561167024505615, -7.573625008309388, -7.559870114940783, -7.565501456554783, -7.561293415371925, -7.574687001507515, -7.55926251913646, -7.563852554125366, -7.560994576121271, -7.566721437077942, -7.573291148108524, -7.562883029407168, -7.570158159077053, -7.549374795901499, -7.5640639695420075, -7.572251998484766, -7.570972389043582, -7.557080874727251, -7.5547683042560685], 'approximated_eneriges_1': [-7.640004876805808, -7.663640722664111, -7.658611929963564, -7.64932547704183, -7.646797803653223, -7.665442251078073, -7.663642689359795, -7.663556103716576, -7.664762017962395, -7.659539943254729, -7.653825233560599, -7.671736337391423, -7.655284105369079, -7.597651501673428, -7.601322561951349, -7.597295701081217, -7.5995434567321745, -7.603809864776037, -7.614372704985102, -7.603637104328402, -7.587494654856017, -7.595271793938281, -7.616879795695566, -7.589553721419916, -7.596416341830358, -7.596034796833454, -7.636209438889688, -7.640877649341832, -7.657679139320576, -7.6363317069501715, -7.634009690454076, -7.650685810199302, -7.642970968474241, -7.647171253048493, -7.649113730245329, -7.632589528503865, -7.631625548600127, -7.640657607231181, -7.637011643554965, -7.6519853787423715, -7.6346252169762785, -7.659438164187605, -7.649134794688484, -7.656067137177791, -7.656308879678295, -7.656600376216503, -7.664776501884009, -7.654613607723093, -7.664969430903149, -7.648273559419987, -7.664870709406619, -7.6469497023504225, -7.643659500147412, -7.645751102067645, -7.646286196764285, -7.6459080652210885, -7.651782113361833, -7.658184809230566, -7.646392105677173, -7.659855511304261, -7.674622701536653, -7.653690153821832, -7.657108979247705, -7.669192622856933, -7.659338187830021, -7.659255866767289, -7.642787974230109, -7.645383883879427, -7.662495541010129, -7.655440842815017, -7.669557208297275, -7.6756909723728795, -7.649491309169715, -7.652262225804263, -7.662422713416752, -7.659914401465116, -7.6639905955020815, -7.6566673637561715, -7.6586633675018625, -7.668702497209907, -7.656154354812613, -7.659014207552145, -7.665265620831511, -7.652713926513206, -7.658480326185389, -7.64981261192683, -7.654614416145373, -7.66396866337189, -7.661425047413697, -7.65942993358875, -7.658563520972784, -7.6514926583190634, -7.644135199378931, -7.642104164460429, -7.669130202549792, -7.643096426186087, -7.654953306643982, -7.662778253610977, -7.662008704804949, -7.662297656266985, -7.664652442531045, -7.662341568683591, -7.650731033972629, -7.65865575908331, -7.6594704205503, -7.652988061222755, -7.661235266653203, -7.653987188331512, -7.651868104406244, -7.651944984193438, -7.657564091355315, -7.640071623656383, -7.652522066174303, -7.662010083630387, -7.647888345260418, -7.650936792580378, -7.655897253299694, -7.653322392254577, -7.644805038244322, -7.652796357049603, -7.659324658913715, -7.650261760707197, -7.662121270587388, -7.655967589917249, -7.6517776917299845, -7.661450519934126, -7.641166197403465, -7.655404138361534, -7.648879831917093, -7.657596913720103, -7.6590897115736984, -7.64991776437358, -7.656498968379245, -7.662734745207417, -7.6513120368663055, -7.644002948397324, -7.657408606711758, -7.660792912880495, -7.660712711942249, -7.649928308881624, -7.649335433945487, -7.653650140193882, -7.652255933020255, -7.639367216167971, -7.662778846906539, -7.652260591782108, -7.650598648861375, -7.662590372653764, -7.650342710622928, -7.6501448723513725, -7.658949388846702, -7.651395906431559, -7.656810220714922, -7.6321390678820205, -7.650008411682383, -7.665943429318839, -7.659303769636394, -7.66175343609437, -7.664889400703618, -7.660941428234831, -7.655777486687101, -7.639890218869916, -7.6404586733828, -7.646546669058496, -7.641522175777968, -7.653600965386103, -7.658168313069703, -7.663408087736834, -7.64237595177724, -7.647074326535779, -7.662532146997315, -7.641935778444564, -7.664735283161793, -7.649548709483991, -7.652085538245844, -7.666668508392412, -7.639771290700313, -7.649496158587092, -7.6568362596053605, -7.655744241997743, -7.664685030863114, -7.663826007050182, -7.649790587112996, -7.64443378177775, -7.658059841719335, -7.653514123802562, -7.653854477512821, -7.646481685942946, -7.668778512368588, -7.66931149740886, -7.647086355555541, -7.641207585483791, -7.662796697913889, -7.654944710173036, -7.639670433309078, -7.662647849868859, -7.659169336973351, -7.649045024363313, -7.649902950465767, -7.660845152542733, -7.64997346217619, -7.659656505795857, -7.646712215566484, -7.653523082543233, -7.649493675081297, -7.655471393693474, -7.674354557783189, -7.649868727439205, -7.657708573676187, -7.648498237270756, -7.6535668913852035, -7.654604999387128, -7.657184118242257, -7.661015568187299, -7.647850392858409, -7.658511169027303, -7.658972301781452, -7.6627155202222905, -7.659343425662869, -7.6653726330212875, -7.644723460329305, -7.668724873820755, -7.659938937532452, -7.664237945432445, -7.652549577013326, -7.654151510415249, -7.669238815055444, -7.666681401675911, -7.669218431486016, -7.647179612366595, -7.655195040863664, -7.663883794389363, -7.656220095677754, -7.652714111757331, -7.660091731494186, -7.653382972001038, -7.649685032899117, -7.643434026734703, -7.653779360455354, -7.649040098024922, -7.650736086171822, -7.662868198158262, -7.6501933250935155, -7.64973877850863, -7.657948064113084, -7.662622266990542, -7.663076116756231, -7.650314400813861, -7.6636252982682045, -7.6493285100228166, -7.655115749146944, -7.644262568636023, -7.654237639095005, -7.6736574011945455, -7.6493474525286445, -7.647472666863004, -7.659184047322648, -7.65912277649649, -7.6654110550839665, -7.661775451342709, -7.649639297095291, -7.653073388579447, -7.655681166370746, -7.647732810883867, -7.6619795234069725, -7.639049506367911, -7.656046843463907, -7.659363290452618, -7.6565259542680195, -7.653607621717966, -7.653468958961931, -7.6646939127860305, -7.664208775193248, -7.6580143217798575, -7.640833891558509, -7.6742343740424745, -7.6368088827610965, -7.676849993512226, -7.660514920077705, -7.651583484887268, -7.668268592423068, -7.6646010667684195, -7.642075015284122, -7.662675943256403, -7.664589673885046, -7.654168128102824, -7.652899497355082, -7.656562292144806, -7.65441159181004, -7.653903217180547, -7.653699566381234, -7.65916383616381, -7.652062498055793, -7.659770782365602, -7.649973183440041, -7.658416249308681, -7.648280662215833, -7.657440584268751, -7.653280984673626, -7.654650326352021, -7.651503976021746, -7.650725270622099, -7.650953823305091, -7.663453719577422, -7.663136563134576, -7.648552058672743, -7.645717317561624, -7.661677391075099, -7.650639645207763, -7.653162448343972, -7.647940290358222, -7.65349195437921, -7.655227609743165, -7.660800320152206, -7.655876286253898, -7.653362417457495, -7.662900578450083, -7.665759889583327, -7.64850603317317, -7.64639804610784, -7.657554964336688, -7.653934318847597, -7.656989653718636, -7.654003033193125, -7.663278274501233, -7.666423380077609, -7.655046975756818, -7.66894116678348, -7.661409124458723, -7.654453806674957, -7.6498362917783425, -7.659479111374668, -7.65850880813774, -7.649723814710095, -7.668599193491497, -7.653559251181374, -7.651880099847571, -7.648275147789655, -7.652882577216799, -7.644777263225337, -7.665841694995836, -7.657295888566798, -7.650380545448417, -7.639585679978297, -7.665489676763162, -7.6548503410482525, -7.6436946240394175, -7.663573440940202, -7.649710258532595, -7.655170355908884, -7.657163682467192, -7.664515491695974, -7.654927719140413, -7.652749483894446, -7.663378842271306, -7.647988315215243, -7.662107961183042, -7.66474215776545, -7.637231085764769, -7.665794116547952, -7.659041651972093, -7.648965313349237, -7.67295614592449, -7.665980286725987, -7.652996229373012, -7.665622980515267, -7.659422815244974, -7.644928616011809, -7.658062566347961, -7.666474881683342, -7.642640171231159, -7.664938294267261, -7.662099851005686, -7.64814476099854, -7.644567976847967, -7.648680150743558, -7.655541946192065, -7.653112692719887, -7.6538334178079985, -7.675629929335296, -7.647642939973969, -7.650061824260243, -7.66209311769753, -7.653972963672962, -7.639499794912201, -7.654796842420962, -7.653923396462375, -7.6617034515694415, -7.655354344789989], 'approximated_eneriges_2': [-7.364883295491945, -7.357096546692957, -7.364955640080209, -7.366649835041585, -7.370178562738035, -7.370498295639986, -7.359850343021811, -7.369578873911706, -7.356601813997492, -7.358935651502489, -7.357796998557633, -7.369132170244881, -7.370702735100627, -7.274325050775206, -7.280474963079358, -7.281708787780506, -7.280556555262666, -7.259920023445053, -7.2785681459669185, -7.285094941009067, -7.271930987000509, -7.28050081577424, -7.268045134634672, -7.277905509462009, -7.27674183916798, -7.276019138655873, -7.349741384646146, -7.342049394958048, -7.360711308891955, -7.346157367111212, -7.335181510651091, -7.336460259713555, -7.3503315982180135, -7.343012489174863, -7.350680303032871, -7.346283858351786, -7.352005549652531, -7.336713141766783, -7.356632635936495, -7.361404363466478, -7.358421968675841, -7.354922720317311, -7.351437910086754, -7.357982322018829, -7.352521671214343, -7.355041799412635, -7.372545589228418, -7.365964181946214, -7.354378458902148, -7.351744159257381, -7.350925066165386, -7.357593585644726, -7.365417233199112, -7.373991478179518, -7.3577941933998945, -7.362401413580458, -7.341856930596256, -7.357240928256174, -7.374309349711194, -7.360958542921878, -7.371926808040107, -7.35921402377884, -7.35916547028286, -7.3550199505559, -7.366133377644873, -7.360252875959583, -7.36491881346327, -7.365101181103266, -7.359053414111484, -7.349971883701548, -7.355873314161922, -7.364197131055456, -7.349489968783213, -7.379722885394727, -7.365049225884977, -7.36513158165031, -7.3576457118603225, -7.3478126411856355, -7.359695751641573, -7.363930333905528, -7.349666773192882, -7.356555741062991, -7.355265448516789, -7.349977444810509, -7.374642461822476, -7.360300171932341, -7.359505475536327, -7.368607076371499, -7.360185531224295, -7.349101735894524, -7.357138676351334, -7.3663064895982755, -7.364408680050643, -7.3580092192110484, -7.377681633783077, -7.367018245907511, -7.367140560080904, -7.357926512249714, -7.356207859208334, -7.358837568245287, -7.374082391099257, -7.368961270707655, -7.351394731165236, -7.366897363688458, -7.366428644422809, -7.369338966260864, -7.36895670581141, -7.352156787314955, -7.356311636601875, -7.368418487568985, -7.373618062975586, -7.365514562347909, -7.356458967476127, -7.350140557450977, -7.37430744555474, -7.365384180212878, -7.352452685490337, -7.365023570169725, -7.361808388584072, -7.366480133321798, -7.370469022282186, -7.352470346207248, -7.346992599713914, -7.3754666982799115, -7.367119981302624, -7.375893544945889, -7.3740184962020905, -7.360680688128673, -7.365533613211296, -7.3730267896333705, -7.378733399096636, -7.360938272380674, -7.3500785793055465, -7.356501828157371, -7.366701043649846, -7.360983720125592, -7.358977885377021, -7.359012030942887, -7.352071018778803, -7.358936876603126, -7.361806178157059, -7.343776779523118, -7.358320360826148, -7.356750472294554, -7.376891375456355, -7.361193797092221, -7.359021412991975, -7.365210523648424, -7.371075560503611, -7.366035104467214, -7.362885977563602, -7.378921723610643, -7.372516628456746, -7.365388770096758, -7.371996227457732, -7.360685568580893, -7.355651305069363, -7.374063334270516, -7.36866991119594, -7.366995215528181, -7.345944236817251, -7.376284921962682, -7.36334282363693, -7.355108514618833, -7.372041071067884, -7.365471765439953, -7.360843606108303, -7.353623255424593, -7.362459109079309, -7.374708343638556, -7.375105765383493, -7.364208223403619, -7.345214366910676, -7.364592321183875, -7.375684202992255, -7.367155527390262, -7.369246432134271, -7.360956615963479, -7.3619580616206255, -7.360459486794811, -7.371675296672397, -7.356317658441366, -7.374757871217501, -7.354379174387812, -7.366613426064128, -7.38178307075689, -7.366224634504145, -7.3597296489938495, -7.358974064648617, -7.3707272321459705, -7.373501209369182, -7.369675184795953, -7.3600172244870885, -7.3584439569990145, -7.366941946200081, -7.360982002370062, -7.359365301566428, -7.356006337639239, -7.34400178778242, -7.373952991273524, -7.358046504039474, -7.361604134578873, -7.349473609764614, -7.349403104466897, -7.3767576363243075, -7.35830652373711, -7.36174226205589, -7.373306073689175, -7.345617022309214, -7.366876143439954, -7.366985309233789, -7.357764798093134, -7.3591288311835985, -7.370257264352036, -7.358829371334706, -7.362238737252088, -7.344988673601462, -7.372449096327162, -7.371956426469645, -7.367637030712678, -7.354838786384415, -7.362342881621784, -7.353367159874581, -7.371558090338945, -7.372199508284778, -7.35559097590597, -7.352243472769708, -7.372060080386132, -7.358686593539402, -7.3706724142617706, -7.35528444874002, -7.362738558888143, -7.355687112281264, -7.361605788363014, -7.36476037660511, -7.357733503929607, -7.363214644109992, -7.3548389973015205, -7.3624925989230015, -7.359600708446874, -7.362931574957735, -7.358987677040328, -7.35107500006582, -7.356836143359705, -7.3546345900017345, -7.365944078095171, -7.364932472499365, -7.354398522173845, -7.357521665275058, -7.3768288423220465, -7.363289402239592, -7.343251478135545, -7.360503842060538, -7.3657683868095525, -7.348601589128535, -7.379870520124686, -7.349147391443481, -7.35970074286777, -7.371717356100115, -7.3588632737725, -7.368721429055141, -7.372265570186838, -7.353054140753173, -7.3577394252567245, -7.372738937492774, -7.349981341418335, -7.362565214437743, -7.364257487214802, -7.3610516071290935, -7.369268591142921, -7.355984717690602, -7.375194815193234, -7.36660973034524, -7.360138439964464, -7.370244045912211, -7.369368625502614, -7.365497694840824, -7.3724084362573, -7.362925924196621, -7.347527321193012, -7.354291928077748, -7.35483990109757, -7.376337424603696, -7.371389952666957, -7.366761093082787, -7.372038595248641, -7.3680292245858094, -7.372723879313842, -7.363111018625149, -7.352063570845146, -7.345940916439905, -7.370254067980764, -7.360839880193324, -7.356968204531796, -7.375528971249572, -7.371525868883696, -7.366754845337612, -7.370661731668315, -7.363084430101188, -7.362918987834069, -7.345723412236612, -7.366278292894045, -7.367094020811365, -7.370071839080922, -7.355364845487074, -7.368284885887138, -7.360124877456739, -7.354994688626578, -7.3649098543665605, -7.368282072577719, -7.345924708354052, -7.380842586667604, -7.36035334136359, -7.367649143212794, -7.3468891173007576, -7.354487074423081, -7.372476545988491, -7.370300266609272, -7.358185550263161, -7.358180712409783, -7.360590387167875, -7.357973406423506, -7.357492691696578, -7.36617128229452, -7.362170473006855, -7.3702491149201705, -7.347250830941381, -7.359065286033125, -7.360842711648379, -7.378426535571467, -7.354302172414079, -7.368199657726918, -7.369243498740597, -7.3626572837470805, -7.363192801642301, -7.365984259252732, -7.359957831263764, -7.354055670115411, -7.368901208708802, -7.365499387028483, -7.362057052695473, -7.36076061134795, -7.3578582420012895, -7.371070206494654, -7.392501032402848, -7.376719315384669, -7.36192020558924, -7.360572803680353, -7.364382834805135, -7.365781587067929, -7.364656255448828, -7.380197508773036, -7.348680263515486, -7.358557567638165, -7.365514533951133, -7.366222672189137, -7.356699052111834, -7.3634482860254895, -7.373209883567622, -7.355686002369842, -7.355419510511128, -7.349642719346203, -7.369344424565576, -7.345344548791268, -7.349659686199744, -7.348036040021483, -7.357953762034859, -7.355311612895259, -7.3714317232624795, -7.368810683670823, -7.359104369519746, -7.376622354423639, -7.360661288659202, -7.358520301623136, -7.36905661413032, -7.347537418729239, -7.377781546220456, -7.346710534929065, -7.37635041750454, -7.359992541999637, -7.357895645444458, -7.3637267758526805, -7.3659965989369205, -7.361875087672914, -7.362226066535422, -7.3687739171144875, -7.365454390248908, -7.3628051566367585, -7.3732335815428875], 'approximated_eneriges_3': [-7.665565108452975, -7.644901323573956, -7.640844028472312, -7.657254406209585, -7.658112461896535, -7.6568392828816485, -7.641390104849172, -7.6495594099925075, -7.644551215257205, -7.651378183593319, -7.662443144196291, -7.660808970446244, -7.6543644719951525, -7.579787725328885, -7.581575393716733, -7.593278932861819, -7.590112185247835, -7.58835070414362, -7.583838150366188, -7.584132884149633, -7.592723154742481, -7.600588992249034, -7.592989439982904, -7.589170555867332, -7.593330942586447, -7.598103983431033, -7.647418576300137, -7.642912816923083, -7.643896476593707, -7.641910200029536, -7.647168635191645, -7.647767599627591, -7.633891335931415, -7.6451174744419985, -7.648916011463749, -7.651596453059482, -7.652658602598597, -7.64925018366965, -7.652250819847233, -7.657391563539323, -7.65628022876998, -7.654372267148436, -7.6523680940147445, -7.646153944349784, -7.652891448904207, -7.662720272184743, -7.655418609074423, -7.645235055261529, -7.652248466967251, -7.658587503126946, -7.6441011073686935, -7.6472521312812125, -7.65578417759617, -7.65404932384636, -7.659074178854031, -7.652171967879082, -7.647353474046499, -7.653043857292235, -7.663262076576875, -7.658974031516964, -7.659773413941099, -7.659877261166179, -7.650674734519757, -7.657871577038285, -7.65218856996915, -7.661315019158188, -7.6608784060476145, -7.65903856685483, -7.650325258864766, -7.657149241987326, -7.6628369554438285, -7.662751902402708, -7.645830978532802, -7.659705924776128, -7.652202748407217, -7.648512995889111, -7.656062033485538, -7.658772090432675, -7.650168027354398, -7.652133754969269, -7.655634089834825, -7.6431287117715, -7.655701260178208, -7.6587933437074955, -7.646927138838895, -7.653111758973935, -7.64804338104222, -7.653306776277115, -7.650322200330327, -7.658879834821313, -7.654179963065271, -7.656924300725593, -7.65694024588232, -7.656643964370596, -7.653438994580543, -7.649654583407108, -7.6588747071651495, -7.661711976348323, -7.657942056516167, -7.6594176679534325, -7.6528382751568715, -7.648300771051253, -7.661655766275675, -7.652026357240133, -7.65484995311952, -7.663627660016132, -7.651696269976716, -7.651471203760689, -7.652688549766444, -7.650547795465464, -7.651428913845321, -7.654107023102959, -7.657571795914727, -7.652314051456776, -7.666254772709962, -7.662168392311318, -7.659842820238239, -7.664331049356466, -7.638036033198543, -7.661709974700356, -7.662459543469471, -7.647034607710653, -7.659347907334266, -7.654787706962608, -7.654339593062118, -7.6568974256567675, -7.646013658991441, -7.653099765259573, -7.650685693922264, -7.645383824147363, -7.655803522857804, -7.655403941428183, -7.650291960134789, -7.658776048487579, -7.652609631803865, -7.659541764373261, -7.654301165389112, -7.6505070594856015, -7.659838781640751, -7.653483388689125, -7.646318468699023, -7.653631379836062, -7.656315380826935, -7.660255323117884, -7.654990375238988, -7.641225742649195, -7.66405826389239, -7.654271860620266, -7.646634129130455, -7.650510510955897, -7.658728753991629, -7.645926973626786, -7.654701123754429, -7.638272916158379, -7.656332674300085, -7.653863882992666, -7.648837320500792, -7.640387250122717, -7.649244359784344, -7.650268513395258, -7.652866967189823, -7.6523557891630265, -7.643888963175816, -7.649627701754415, -7.652111005299847, -7.655242582599543, -7.651078841908696, -7.656342772524407, -7.66086562676355, -7.654187509979265, -7.652723758952326, -7.655343044873772, -7.655318868132087, -7.6525909880558265, -7.652632307738305, -7.650951036901952, -7.669286096861051, -7.652350772420757, -7.660446851056735, -7.659401097867884, -7.658145954855402, -7.65598015342052, -7.6585818022757906, -7.658411845818654, -7.662098249242379, -7.645861239029599, -7.653301645718722, -7.648596669553275, -7.655410214618722, -7.653651454737528, -7.653108457752997, -7.668396591214985, -7.651742330838472, -7.643272221341881, -7.6480076113614475, -7.646105722075325, -7.657937872190927, -7.653099062217942, -7.666011461331249, -7.645951841928547, -7.661057330564267, -7.653346502650349, -7.6526588084091625, -7.644999760332802, -7.6563323175765365, -7.658436744764569, -7.64925880962834, -7.653645575607522, -7.6605824141138035, -7.653611273403076, -7.6650829865663574, -7.656481794249267, -7.659460169543926, -7.655210623287882, -7.651139909298326, -7.661824302406185, -7.655144998887509, -7.651534007689744, -7.655049778567794, -7.662531821531967, -7.652062408912415, -7.6496410482217065, -7.6531326977073215, -7.644136973991895, -7.650950497401372, -7.644591098573973, -7.640845855337503, -7.667905625053742, -7.650333814842865, -7.652110487139681, -7.658219757526387, -7.657240184846646, -7.650828427136131, -7.6447235080247955, -7.665394749448972, -7.65443457344851, -7.652105099851306, -7.6458841283088645, -7.655403522905685, -7.65490635816747, -7.657835046482047, -7.662772983737446, -7.65335143226066, -7.659667844314349, -7.640147172486251, -7.651921991051257, -7.659168382390267, -7.65640911857179, -7.6553638343789485, -7.65376820350458, -7.656500818406482, -7.651715189752812, -7.65047465807989, -7.643718520551659, -7.64415677869882, -7.640750294074653, -7.6557818857307725, -7.649215454235926, -7.650081251221079, -7.648162520333877, -7.655517708101543, -7.658035203433566, -7.664428731877207, -7.6592303950745215, -7.6673548627608294, -7.660020287661474, -7.659737758823862, -7.656041511655851, -7.648507404110936, -7.653022356297249, -7.6524332877791865, -7.66431697314938, -7.6591357446614, -7.646691610906157, -7.654845941828202, -7.663067482655948, -7.650470847172488, -7.649418514487242, -7.6550498390786945, -7.644420728850646, -7.654795015049781, -7.6613612317631805, -7.654767695115201, -7.657190305340891, -7.656898793921717, -7.656225144244079, -7.659931102201272, -7.660014363803615, -7.656706784957107, -7.6588121853997, -7.654888558146463, -7.656401546136769, -7.656448760186196, -7.657953392871566, -7.650173917127307, -7.651437983635304, -7.653957489710805, -7.6539667407460374, -7.653713654316644, -7.647546740343754, -7.648980644044312, -7.65162924524375, -7.651802600897182, -7.655950997843602, -7.63917570280027, -7.649099009141816, -7.6711436604566785, -7.656094119507753, -7.660916007880858, -7.660108513494201, -7.651479797787551, -7.663651296922621, -7.664209310541335, -7.65740453684123, -7.654347360013047, -7.653254337879505, -7.649771899872737, -7.650187860986575, -7.646969009287433, -7.65932833797122, -7.652473286122496, -7.657447845927712, -7.6509800843866085, -7.649501992616811, -7.649543941474777, -7.661721054157811, -7.647821688928648, -7.651366617347241, -7.655407922067553, -7.667590855500485, -7.651003389128052, -7.650856862821003, -7.6561783181319, -7.661130988595605, -7.664145920493251, -7.653897854932308, -7.656493110072739, -7.655934153959316, -7.66209502182847, -7.662816393948624, -7.655017653503092, -7.649244985283952, -7.649228279587383, -7.650190991166763, -7.6488082362955865, -7.660426607640321, -7.646744695377181, -7.658734358003759, -7.66177693097403, -7.648217405882136, -7.65853080017318, -7.664522961074313, -7.6506323811866705, -7.654226662604913, -7.652957092965678, -7.644444582882459, -7.647671035701211, -7.6580655907480715, -7.663615455151189, -7.6627857130398755, -7.654044781278339, -7.6534808648838135, -7.655449080427594, -7.647640119768702, -7.646787117057311, -7.65389292674119, -7.659977579813853, -7.646309745997252, -7.657469286538147, -7.652930968416271, -7.651680446580526, -7.656359311921744, -7.655149743938323, -7.652890918037023, -7.659366964648121, -7.657957284927965, -7.652544936737028, -7.652783155812913, -7.646343032824489, -7.654871280821122, -7.646666505815597, -7.655385050167301, -7.658785076107344, -7.652325815918973, -7.648640691745009, -7.641891329255079, -7.651861882018293, -7.644743796827444, -7.6617625043417]}
plot_convergence_of_optimization_process(LiH_approximated_energies, LiH_molecule_4_qubits, margin=0.02)
H2_molecule_Hamiltonian_4_qubits = -0.8105479805373279 * (I^I^I^I) \
+ 0.1721839326191554 * (I^I^I^Z) \
- 0.22575349222402372 * (I^I^Z^I) \
+ 0.17218393261915543 * (I^Z^I^I) \
- 0.2257534922240237 * (Z^I^I^I) \
+ 0.12091263261776627 * (I^I^Z^Z) \
+ 0.16892753870087907 * (I^Z^I^Z) \
+ 0.045232799946057826 * (Y^Y^Y^Y) \
+ 0.045232799946057826 * (X^X^Y^Y) \
+ 0.045232799946057826 * (Y^Y^X^X) \
+ 0.045232799946057826 * (X^X^X^X) \
+ 0.1661454325638241 * (Z^I^I^Z) \
+ 0.1661454325638241 * (I^Z^Z^I) \
+ 0.17464343068300453 * (Z^I^Z^I) \
+ 0.12091263261776627 * (Z^Z^I^I)
%%time
H2_approximated_k_eigenvalues = get_approximated_k_eigenvalues_of_hamiltonian(H2_molecule_Hamiltonian_4_qubits)
compare_exact_and_approximated_eigenvectors(H2_molecule_Hamiltonian_4_qubits, H2_approximated_k_eigenvalues)
print(approximated_energies_dict)
approximated_energies_dict = initialize_approximated_energies_dict()
H2_approximated_energies = {'approximated_eneriges_0': [-7.044869071845908, -7.0522159431144695, -7.045826893427681, -7.040956622016025, -7.033636336738691, -7.03852022989153, -7.043777898111554, -7.0415561599539584, -7.04037809487655, -7.0453193426832215, -7.0373470588788996, -7.044564629495382, -7.044754815788807, -7.271419323963639, -7.26052383991807, -7.247357653224691, -7.261820010307763, -7.252539342679122, -7.2626464129237, -7.245920398831287, -7.247035733098027, -7.265952097434155, -7.24887083122739, -7.2531816673861735, -7.265940705468054, -7.25270662157792, -7.102617995399945, -7.089498116849218, -7.093325799353756, -7.096365339245411, -7.094106057615053, -7.107535385025435, -7.103305126646508, -7.091948777305775, -7.086315491445892, -7.10488835709718, -7.096982206618721, -7.0914861370367435, -7.093538444908571, -7.070529105326432, -7.067462257655455, -7.076956405751454, -7.066279474520601, -7.077988558064548, -7.076544412109634, -7.0658723955821845, -7.070992951297235, -7.071491621144808, -7.072676655189868, -7.069239264907494, -7.063587778613009, -7.072326880313549, -7.0486848773571, -7.046298838670843, -7.039678113562299, -7.039188863783721, -7.053704116853223, -7.052643297569627, -7.050661731110794, -7.049192506392741, -7.0476398150257715, -7.052762124552016, -7.048855537081967, -7.044614333935807, -7.05502435737143, -7.043489946891944, -7.042594008303074, -7.04959955388164, -7.052586159600431, -7.043061527383934, -7.046022024645883, -7.041379760574117, -7.046648212461671, -7.0441824707611245, -7.057042282144841, -7.046352543121911, -7.045337153671366, -7.049256240886576, -7.0378272540055065, -7.043903009848836, -7.048608550869771, -7.045266306647011, -7.050655640764568, -7.050509397550202, -7.041908116822447, -7.0526690959587155, -7.04823317227064, -7.041721783605734, -7.035312757770234, -7.042901180491823, -7.049113078824484, -7.044285463008793, -7.049442408039912, -7.0391089748590865, -7.041672722938562, -7.043665865505559, -7.043828664033352, -7.042920025064471, -7.0351881683253135, -7.043603402727344, -7.038009268423706, -7.039775544754238, -7.040883420582434, -7.037013595341853, -7.043819792934352, -7.042331437161471, -7.0456333038019405, -7.044548802876332, -7.038415766878813, -7.042968500357833, -7.03611416952854, -7.050432628509437, -7.043515351878789, -7.0364263386893064, -7.039288303056867, -7.0388500240705225, -7.03302407685042, -7.046960020729119, -7.044408693315892, -7.046657637715488, -7.04387014614952, -7.041187930508047, -7.034713210871416, -7.0424695121866945, -7.047725410183224, -7.04449085795552, -7.040806705875413, -7.0373853952318255, -7.037261842797666, -7.047859361581846, -7.049325843393123, -7.046151544622458, -7.043904221897233, -7.030302702310242, -7.0425612319577, -7.042291201514399, -7.038413698851512, -7.038412621015808, -7.043097019878359, -7.05238144474142, -7.051651858766015, -7.043762896318504, -7.031048444158597, -7.048869918982238, -7.044173709455461, -7.044276087098426, -7.039928716467672, -7.032741262414934, -7.05603933430837, -7.047712516719079, -7.029363034832074, -7.04120882235882, -7.038705395316446, -7.047649689091099, -7.043142711638445, -7.036958086099825, -7.050891397945634, -7.046994493016472, -7.04671562212142, -7.048569346180278, -7.039243574042099, -7.04302944528067, -7.040889111732697, -7.031685888156094, -7.044950083024378, -7.051877178085004, -7.046285775831468, -7.029559524717367, -7.037978211518291, -7.041085254242691, -7.044079649685425, -7.048988611826235, -7.0451941134830465, -7.037328268668186, -7.044100448273761, -7.040943041215821, -7.03914978891461, -7.0403395482554965, -7.046453268816699, -7.041288234787106, -7.039607543354191, -7.044551042858932, -7.038310324016002, -7.051193770196858, -7.036583203999625, -7.040478694265556, -7.038582313438599, -7.038909350623601, -7.042717248325647, -7.037321574213696, -7.0432663420012664, -7.049224888190789, -7.048931789809128, -7.043676795578305, -7.039809558091586, -7.045393069382596, -7.042396631840064, -7.043114992353083, -7.038462374140121, -7.046332291321339, -7.049023458842242, -7.044788845787949, -7.048339038543747, -7.046977441282405, -7.039777148935807, -7.049540827915558, -7.036962487132982, -7.045715536366187, -7.037443056104555, -7.051385449403388, -7.050145492134935, -7.042150341522066, -7.042889221955946, -7.053242066925324, -7.0390431325064755, -7.048359051553413, -7.045260503879417, -7.043482530079498, -7.042942267042148, -7.036513410863197, -7.0381343496658895, -7.052418453147576, -7.037468024799972, -7.038186713430111, -7.032175501130874, -7.0379334092469685, -7.036915083859438, -7.047553461406044, -7.045354491189099, -7.042785624301588, -7.039709867279104, -7.037032565711176, -7.045108922652119, -7.0357582699582135, -7.050000404547161, -7.0394185138961864, -7.052271352194985, -7.045606968052456, -7.0508600642674955, -7.0470800483045855, -7.043863452789584, -7.044813802868496, -7.050687813753245, -7.0407766824904545, -7.040842182847717, -7.052102298481224, -7.046337914315711, -7.04988918779328, -7.042104013380124, -7.0469319722733035, -7.047306057723097, -7.047469147761255, -7.046029336744473, -7.050346654126879, -7.043367589488681, -7.049975440549578, -7.048946922905914, -7.052610165294072, -7.038314824375851, -7.037340964972728, -7.046981363353354, -7.040413471602155, -7.041009311282204, -7.042602559535955, -7.037646386772052, -7.042514567980215, -7.038703779632361, -7.041529832962727, -7.042962754917504, -7.048786291588932, -7.043129547677769, -7.049021041423307, -7.049427252852342, -7.043836616413532, -7.036977436292433, -7.037620010721522, -7.047413988284011, -7.042065307986255, -7.039947338526112, -7.044411758976216, -7.051060299193217, -7.037766948566103, -7.047036104805181, -7.04021122655741, -7.044036139060423, -7.039718949602695, -7.033885499930792, -7.045033617714271, -7.041839583140589, -7.042374984054234, -7.03638371604375, -7.048445891340641, -7.041104828841519, -7.043251642420818, -7.043411931462254, -7.042924916028068, -7.046542176670868, -7.049764702707561, -7.040220654757975, -7.041801890197001, -7.045555266385649, -7.0430106557869046, -7.04329818292906, -7.049868368497418, -7.034838501816597, -7.038414717010243, -7.0480144131089215, -7.041535357301606, -7.043149083278204, -7.050721236368235, -7.04596017384676], 'approximated_eneriges_1': [-7.582453604466945, -7.582164266793541, -7.579073084596599, -7.585141242550659, -7.584589532241155, -7.5804643115002825, -7.5755634547601, -7.575600434478013, -7.582806656947542, -7.576958351501415, -7.574237985466983, -7.580187288314143, -7.574665472867071, -7.474764240900405, -7.4768714938741345, -7.466319706744727, -7.476154028838411, -7.471320885644612, -7.4590599683088294, -7.465030782155778, -7.475164569508971, -7.466084866348124, -7.477792033180828, -7.472963606706828, -7.4729137232137335, -7.466637719941649, -7.566267374472306, -7.557517351122575, -7.578861463899415, -7.566194514775459, -7.572894947849101, -7.558357851874592, -7.558189255072525, -7.562854661029755, -7.565416260195606, -7.56386180495245, -7.570649313607356, -7.559866728288295, -7.5649716056514675, -7.5763901452103095, -7.583014705078407, -7.576325392379665, -7.575686394573026, -7.57676889528636, -7.5855811909597595, -7.587406552562512, -7.576413156367478, -7.581672732639491, -7.582665201268557, -7.574126783110414, -7.5754863158538654, -7.575817174214625, -7.578319929886486, -7.583771883133503, -7.579308644768669, -7.581895500553291, -7.577818977719542, -7.579518614957346, -7.578770110736305, -7.568162483375374, -7.584272685036331, -7.575275136690887, -7.576691203553333, -7.583033572271182, -7.58628746773469, -7.571964290827396, -7.578726896842633, -7.576084156249764, -7.575686515562396, -7.560371684656434, -7.5816041152504186, -7.573564449240417, -7.575200458518374, -7.578389993722628, -7.58161482344728, -7.578346057217506, -7.578660232259293, -7.578358594053784, -7.576069944068362, -7.575499263179799, -7.575665722299441, -7.580105521608364, -7.583841927288854, -7.575701281027156, -7.5841062198935845, -7.5756327381698565, -7.576836709451854, -7.582683580777152, -7.583562878721634, -7.58548958816941, -7.575365428677632, -7.570096722992203, -7.5805140100552375, -7.583156825388065, -7.572553619199591, -7.580242430803599, -7.5690600027963955, -7.577282888503016, -7.584504157301762, -7.579320594284024, -7.574417626780096, -7.577251806051585, -7.581175922601044, -7.590788730721342, -7.58804567920823, -7.586773700746227, -7.574305306136674, -7.577466703824051, -7.59078398239154, -7.582840116308093, -7.5784948990982475, -7.576210269626564, -7.582801355603316, -7.567135133247455, -7.571236423881995, -7.583674639740933, -7.575546935778369, -7.5848395672040745, -7.578637870035943, -7.584649963135558, -7.583232044906465, -7.578037588333182, -7.575037024239425, -7.5756287278912575, -7.580846000257484, -7.575445583814912, -7.587356542975101, -7.585408529325551, -7.582830703653647, -7.579318293636298, -7.5817590405493, -7.569709966305507, -7.577143170455227, -7.58073497274696, -7.578116908199861, -7.58101963106108, -7.57939904963751, -7.580963758105738, -7.580014364562649, -7.576177639110013, -7.574832867592759, -7.57927102112272, -7.57933093475304, -7.586648373131018, -7.579089318160009, -7.5798338080276455, -7.580442009939318, -7.586558474218888, -7.582250053579411, -7.578917126849361, -7.583817756705378, -7.572648552241667, -7.576379678302254, -7.582520896345737, -7.58431330909813, -7.587561934482597, -7.566361872203952, -7.577275373294726, -7.584822521801764, -7.5808706572983615, -7.572063567264936, -7.587688658973814, -7.580834791459686, -7.582333173091506, -7.5823035713246245, -7.567910673030077, -7.570894732661367, -7.578778722501105, -7.579508916605638, -7.593317374148693, -7.585992876872101, -7.582597276594122, -7.576415967860754, -7.581530719038893, -7.585877906701415, -7.576638514263477, -7.583908549161456, -7.576221470782808, -7.57457610264675, -7.5691247473035, -7.567025061528623, -7.5799132440511965, -7.579811645932212, -7.576466217680586, -7.580157052176107, -7.591757723889211, -7.577075416560062, -7.581499536346734, -7.587283564693098, -7.579319569860482, -7.574807109706868, -7.5805662193633285, -7.577700088410532, -7.583070715978398, -7.572674908218506, -7.587958766585343, -7.585377991319518, -7.579335779957175, -7.583690752501266, -7.57262557018669, -7.58173539680413, -7.580513431597053, -7.578908209498602, -7.5795595447589585, -7.589571416086194, -7.57333933173756, -7.579656159422607, -7.576491857325173, -7.591484618841956, -7.5802494050358735, -7.58025279912429, -7.571051647913349, -7.581809926808362, -7.577714960144171, -7.581061186516403, -7.581860626666353, -7.582594915261997, -7.588702606385015, -7.5790945306775095, -7.582523368849969, -7.583575483069086, -7.588331770201276, -7.577268812603097, -7.574196242707301, -7.5824750573924184, -7.571801606472999, -7.573092497452785, -7.5798386558823925, -7.58364241206435, -7.5801244052688626, -7.57982770354082, -7.573945541936829, -7.575634335717406, -7.58218695853067, -7.5759007033048595, -7.577586904429252, -7.575193803613827, -7.584128590647623, -7.579224437618458, -7.573673400413032, -7.572686457314879, -7.5840459383690675, -7.589991900192306, -7.586290509143632, -7.573550999061493, -7.580272770111241, -7.584510686575842, -7.575049963974524, -7.582204805229044, -7.581051244278404, -7.577685458503512, -7.587445625374352, -7.570632450269072, -7.5751700775202595, -7.575880914264588, -7.58347947116411, -7.576308155287932, -7.577575435972919, -7.583437648836092, -7.584723768673469, -7.580372812491347, -7.579552059571315, -7.583758447271931, -7.580809011221502, -7.576743842393656, -7.579327348826819, -7.5831290999780805, -7.580064001665567, -7.576598908787449, -7.577558175438309, -7.570824510269273, -7.57063334016653, -7.585027271313368, -7.580571213051049, -7.582500776518187, -7.581365078016107, -7.581150660839033, -7.58085070568382, -7.586978004024601, -7.574014013013721, -7.57467488043918, -7.582420973797503, -7.580881153163834, -7.584832699162254, -7.5764164566720735, -7.577680274966804, -7.584624036983542, -7.588560624890894, -7.582218309682846, -7.577681480590064, -7.585395996797304, -7.576023030690075, -7.578464152585253, -7.576905118322982, -7.581184117379984, -7.580379077320153, -7.578419406429601, -7.583076596140048, -7.582102550404386, -7.587058322895608, -7.581828240210987, -7.576371745814872, -7.579504525545559, -7.582398541784724, -7.581065563326059, -7.575945081458147, -7.578834983689569, -7.575758190188583, -7.587162611711519, -7.580555918829417, -7.567371653372916], 'approximated_eneriges_2': [-7.578683503208721, -7.5931543389554745, -7.58787591756937, -7.586178677241158, -7.5937487883184485, -7.5812938657422615, -7.583926168551136, -7.595756167275311, -7.5974486898288465, -7.587645740415491, -7.601346607578855, -7.5891448369662315, -7.59006913160856, -7.45977719337515, -7.448862333994072, -7.461556900079808, -7.483217878018406, -7.447797282426053, -7.431932943974496, -7.464254381567711, -7.463471352482962, -7.462935813299841, -7.465931905634223, -7.448255452116852, -7.4747508958780005, -7.455763001010045, -7.530266269060302, -7.528081524502602, -7.5321690336747364, -7.530959017472535, -7.51697698886829, -7.531451174945902, -7.529980896053684, -7.524371709817597, -7.5239352110700235, -7.5212444905594245, -7.524311793017027, -7.541843004880607, -7.533990152827953, -7.553149049869688, -7.562279416050736, -7.5640291567026505, -7.568078403075637, -7.571108123884351, -7.564984270022434, -7.552673669647716, -7.552740280926134, -7.555693792106207, -7.56222478138485, -7.5632920781714, -7.561590573982431, -7.55926711734161, -7.588796822338731, -7.5636836007576775, -7.586232510201079, -7.592244313257442, -7.5759085914679405, -7.571123828980992, -7.580154201386861, -7.588135289239839, -7.582040543935425, -7.585254501805902, -7.576314599232319, -7.5842473182157, -7.595091525275136, -7.59866525513457, -7.591126887054619, -7.581667253914693, -7.587038521475237, -7.593265428179274, -7.587643994555676, -7.585605237479551, -7.5956134784723, -7.572780850163217, -7.596329586806689, -7.59031257249014, -7.587392576416836, -7.5947952581852025, -7.5898692552230065, -7.596194717517874, -7.59375647307333, -7.587755371898693, -7.587864540134338, -7.589406734705377, -7.5914119949821774, -7.581735489921218, -7.588877353827273, -7.587667133064402, -7.58608180760796, -7.5867041149041645, -7.594172569272973, -7.585666463638263, -7.5789639091580785, -7.592464114072826, -7.578293938676728, -7.592789806845936, -7.586469053338829, -7.579933734110607, -7.590437661459481, -7.576388785524825, -7.588923883612902, -7.59543439530978, -7.607208292759077, -7.596212683567193, -7.589175698091523, -7.587561697745929, -7.587917871413771, -7.590133249735344, -7.603500662010661, -7.597112041411421, -7.579564226040477, -7.587718617601744, -7.589768363462059, -7.59406574087067, -7.581628846576109, -7.579358057258006, -7.593281502502604, -7.5840229914972275, -7.597497416617267, -7.5891565613493075, -7.592391949007383, -7.586960987160365, -7.582701268727566, -7.591109524330426, -7.593871106184804, -7.58670081422275, -7.597273127181576, -7.590058394940967, -7.576949413568696, -7.588214086189539, -7.577575185627234, -7.599232900348659, -7.600687504491986, -7.603895690503902, -7.58082328397254, -7.5895617397182935, -7.592016390665446, -7.581246311448488, -7.601838570150319, -7.581161622114567, -7.581216963318931, -7.586389920002494, -7.589871001285056, -7.594352768386359, -7.585220361796463, -7.588173904448901, -7.588995293596656, -7.588775317687818, -7.593709008648448, -7.602806698640034, -7.583409983732506, -7.579684843283839, -7.591426815086892, -7.600291745124925, -7.603666030955258, -7.604348279535796, -7.5812941265869735, -7.589765095275158, -7.588901241629834, -7.5989647657620845, -7.589371082992922, -7.59817174245686, -7.594760943638512, -7.584335109560736, -7.595070496757898, -7.59255621022146, -7.586281303559234, -7.595198897831456, -7.604462273913371, -7.589747204514441, -7.599720754480531, -7.589208118030887, -7.597911856281437, -7.594335070639344, -7.585435798304614, -7.600101519266743, -7.593384079838442, -7.593542894893967, -7.5992396439312415, -7.580588914380738, -7.586902020337007, -7.589325398780175, -7.59817344395894, -7.588206524610579, -7.594955810207244, -7.585952655212365, -7.583922200309872, -7.585728743882994, -7.593416363241724, -7.5850186472792736, -7.591804838309055, -7.58679639181036, -7.594228564752007, -7.595780370208559, -7.574258156035539, -7.585311376675376, -7.589748275239228, -7.594772901771665, -7.593677884534406, -7.596885307264681, -7.596568390300541, -7.594878075782579, -7.590147057631574, -7.58815739361096, -7.602797301148743, -7.588978577195758, -7.592787955406494, -7.5852562284253375, -7.587439961046042, -7.585416220467494, -7.585276739270876, -7.5890684316371475, -7.596364168995866, -7.590150493524426, -7.592868916289156, -7.588865340238179, -7.5836404907562835, -7.581043414399546, -7.590079464120367, -7.609110826697228, -7.587982827673501, -7.592423607735933, -7.581291469574334, -7.584026486758773, -7.57728545151018, -7.583021098502603, -7.589345517380353, -7.590439157933853, -7.591102451174115, -7.591402339383597, -7.587035173432067, -7.611572478963275, -7.57941623869135, -7.59118431736744, -7.589927809405088, -7.58269713196266, -7.586870789539297, -7.588005384366656, -7.597552391881702, -7.587476992006394, -7.581438443852114, -7.589947609088305, -7.57161194005379, -7.6059050150464875, -7.5990277888459, -7.583939364459699, -7.593905802421668, -7.597398550635914, -7.589290039229096, -7.59069682900358, -7.5778804541942355, -7.599690770850041, -7.5925633837158895, -7.599086271877718, -7.592539981305608, -7.5848781566749075, -7.594628009166403, -7.587636908765328, -7.5895930673544845, -7.595182463143173, -7.592240683400318, -7.592459548310302, -7.5841028945577404, -7.604178358110788, -7.577115035409604, -7.5973285307493015, -7.593461167494049, -7.593093214833803, -7.583675165930156, -7.586809917779882, -7.5793886767747995, -7.594548129042497, -7.601607222365409, -7.589341216045241, -7.580152998244252, -7.6003639206009, -7.594343229812256, -7.600510000814319, -7.581945238754744, -7.599273560053577, -7.594283692343495, -7.597170155945373, -7.583584557739755, -7.584687065933869, -7.5936734801703745, -7.5908102511187145, -7.588671872447289, -7.5967225452812945, -7.595416109819035, -7.593707789947535, -7.591066175225888, -7.595479219847797, -7.5902173059568385, -7.5947883736292745, -7.590161788335861, -7.589153336047727, -7.594678068484873, -7.583352023206614, -7.592953578600243, -7.5982744954129915, -7.567993416796616, -7.5908272761439, -7.579081380529146, -7.589306556114438, -7.5789782758982, -7.596003051063719, -7.598161307392864, -7.584442740598526, -7.595376043673961, -7.582912994652124, -7.589969762679878], 'approximated_eneriges_3': [-7.751544766698706, -7.755382759898444, -7.7588573448875655, -7.750333908006543, -7.753121069313703, -7.745037975197169, -7.750176949528647, -7.755466555172707, -7.752643946802974, -7.749987250159876, -7.759991333025901, -7.759786517853326, -7.760442160539629, -7.49917168845674, -7.51460922469903, -7.5270629338962936, -7.513706349687308, -7.5250930626997645, -7.524332497938209, -7.534953033601943, -7.51170753447545, -7.525800797473628, -7.517337960712074, -7.510326877087334, -7.522635081351605, -7.517801924800858, -7.70927400304189, -7.713844043854497, -7.710928544333142, -7.717567954486238, -7.713134977641934, -7.714384431037695, -7.7204661880501275, -7.715471831346418, -7.719100079296667, -7.711764100315897, -7.715199721442915, -7.71042016364878, -7.7176306320087225, -7.7389091668549534, -7.749636419893328, -7.731983989302067, -7.739024891794881, -7.757064530690422, -7.746985739646444, -7.742441024609884, -7.740421591108306, -7.747960868678248, -7.744418583966718, -7.739187127889024, -7.744368994113976, -7.7555923855344195, -7.7520556582607165, -7.747695042019798, -7.746814141605138, -7.756591127615103, -7.756147240786697, -7.744265594630968, -7.7417374237762955, -7.74791986433853, -7.752843121990141, -7.763714012083222, -7.747956708887576, -7.756957077924681, -7.760430788177853, -7.747765866081701, -7.7457168829447705, -7.747901586545985, -7.753169826017695, -7.748831187685429, -7.753327633570565, -7.764772380347329, -7.756011705747082, -7.756288045410007, -7.765362534384527, -7.758175657817048, -7.7635629366169265, -7.749093032339201, -7.754377963311347, -7.751601196193235, -7.753033596042808, -7.754710234040921, -7.761871549000384, -7.758893311248456, -7.74914145849716, -7.753616758210788, -7.7496211916625795, -7.757549749652293, -7.743392334924374, -7.748935920008092, -7.747325754823692, -7.755444791584788, -7.75774245565876, -7.764217291584462, -7.746653194506497, -7.7526135879025935, -7.745004100387452, -7.754499107366891, -7.748881888378319, -7.7579724190158, -7.761344325183707, -7.752397411153568, -7.753203441245434, -7.751909085006676, -7.759162741062279, -7.752814014698454, -7.740462403281628, -7.743897452754459, -7.739636099047059, -7.762329416398708, -7.745074835586486, -7.754332579686614, -7.7600549377934165, -7.756234011997059, -7.747102805651635, -7.75106072860936, -7.755383699511321, -7.754220464582435, -7.747840629573525, -7.754768087642843, -7.746377899270535, -7.754572002739135, -7.741058540006747, -7.748729379962399, -7.741510109250558, -7.756909628533724, -7.7492764720880905, -7.756346424823958, -7.7601868286729445, -7.752304753870076, -7.7427309370649695, -7.742354828828864, -7.749159233434565, -7.753228158261914, -7.751241442177317, -7.752539413248214, -7.750372183896247, -7.741269790260364, -7.759455444029633, -7.750304915541718, -7.749108739830789, -7.760562480335842, -7.754459334360625, -7.755068815153284, -7.756727705656175, -7.732813342021415, -7.748564948269735, -7.74724238911974, -7.752181364316024, -7.7516508099875505, -7.747543675647448, -7.750707935823149, -7.7498325750013874, -7.755081079704518, -7.738907854230404, -7.758268291808157, -7.756613305849402, -7.7568890212229515, -7.764388841197386, -7.74525131541767, -7.745027950053753, -7.753513540377524, -7.757401531905581, -7.764042754455379, -7.756258663882559, -7.7602043361813005, -7.753631324493896, -7.7585219414541955, -7.751573689001982, -7.750242646751869, -7.74741078293913, -7.751597292941286, -7.747948266576574, -7.748005354695472, -7.754039515280349, -7.753227501341376, -7.7462033139824475, -7.752543874354947, -7.7500473238412395, -7.756912944723444, -7.751877842165016, -7.7550847184624025, -7.754764551897824, -7.7520208398071695, -7.7543749362775305, -7.755505430317207, -7.752310940237558, -7.76451842089832, -7.75862626465743, -7.76076798371711, -7.743357828286941, -7.7501897689298485, -7.753578341637515, -7.754677607223959, -7.755404625698354, -7.748690230742172, -7.7499106220184, -7.755472871803704, -7.756300948626108, -7.749333754505335, -7.7525381679054775, -7.7611435512498606, -7.755662749095439, -7.7548763759280614, -7.7471568175459335, -7.745585122667019, -7.750749461294535, -7.750242705368079, -7.760095966583469, -7.749853320777981, -7.748009302505093, -7.749961013747658, -7.757761654393711, -7.754986361398084, -7.755269561833093, -7.758009260023531, -7.751241906107987, -7.750981388751178, -7.7408813902344535, -7.764429830860316, -7.755096133188848, -7.752531558100684, -7.749141306010813, -7.752133983829143, -7.7487289579175584, -7.762405705225251, -7.754401557563736, -7.760284061940854, -7.756247080873755, -7.75245715987267, -7.761309652107444, -7.753339838029139, -7.745391634289997, -7.754594222253378, -7.748053189758376, -7.753557061623229, -7.750627092187286, -7.748122649964763, -7.762423575668679, -7.755679242461799, -7.7574460297856564, -7.747737220507729, -7.754730340807679, -7.752579196085017, -7.734891439904187, -7.75624097434428, -7.7621720359134345, -7.749293295970083, -7.744996151805008, -7.7571943399388985, -7.735088209550487, -7.744906121710207, -7.758347305074398, -7.746903433419974, -7.756164929621239, -7.756442032015691, -7.759331329514457, -7.755619997409755, -7.751213114134945, -7.7516168512232495, -7.755702331223667, -7.759133109597966, -7.751254906461934, -7.752815491153393, -7.761482448451672, -7.753233253022574, -7.75186228857032, -7.734068368624578, -7.759382558801796, -7.754597978505958, -7.746756505521222, -7.758638484432694, -7.756973637727583, -7.750423812727322, -7.754517387774341, -7.75989701896671, -7.766149017810932, -7.761312478121986, -7.75870589097194, -7.753175555115126, -7.750617134639217, -7.761143213227473, -7.754185958220965, -7.756809261611686, -7.750129819201203, -7.7465330904915275, -7.749467251878749, -7.745649796723613, -7.749341461425736, -7.743390135233459, -7.758878184914268, -7.757025641488555, -7.757425617534648, -7.747533690006613, -7.758228094783648, -7.7657387708064025, -7.75215188674995, -7.761769851335688, -7.741851715020775, -7.748987309803324, -7.7501568220416495, -7.74282055571017, -7.754881861741329, -7.749473645298008, -7.749204889272958, -7.752169577108456, -7.750895554677058, -7.7515134889857515, -7.746818115727269, -7.754709194507684, -7.751285718255909]}
plot_convergence_of_optimization_process(H2_approximated_energies, H2_molecule_Hamiltonian_4_qubits, margin=0.01)
transverse_ising_4_qubits = 0.0 * (I^I^I^I) \
+ 0.8398088405253477 * (X^I^I^I) \
+ 0.7989496312070936 * (I^X^I^I) \
+ 0.38189710487113193 * (Z^Z^I^I) \
+ 0.057753122422666725 * (I^I^X^I) \
+ 0.5633292636970458 * (Z^I^Z^I) \
+ 0.3152740621483513 * (I^Z^Z^I) \
+ 0.07209487981989715 * (I^I^I^X) \
+ 0.17892334004292654 * (Z^I^I^Z) \
+ 0.2273896497668042 * (I^Z^I^Z) \
+ 0.09762902934216211 * (I^I^Z^Z)
%%time
TI_approximated_k_eigenvalues = get_approximated_k_eigenvalues_of_hamiltonian(transverse_ising_4_qubits)
compare_exact_and_approximated_eigenvectors(transverse_ising_4_qubits, TI_approximated_k_eigenvalues)
print(approximated_energies_dict)
approximated_energies_dict = initialize_approximated_energies_dict()
TI_approximated_energies = {'approximated_eneriges_0': [-7.230655824291587, -7.232156231813603, -7.2269118466834925, -7.224435292342758, -7.223090510850815, -7.232883464451508, -7.228534606397912, -7.219354944244936, -7.231064944404686, -7.228080867101087, -7.248782779735623, -7.245837078380108, -7.23217415595806, -7.406936545157612, -7.411831457927899, -7.430134402689202, -7.414265944626451, -7.416851880814031, -7.400408350428862, -7.427462455825711, -7.417112403651977, -7.434810143153512, -7.409863282248075, -7.427346672862717, -7.422754759252152, -7.404965523288016, -7.226943186680726, -7.230561909262265, -7.253943248477311, -7.246903128054697, -7.2376364884345, -7.230628484393112, -7.238475770984712, -7.243651868078656, -7.23567385988149, -7.240189611494555, -7.255884627062503, -7.231752576052941, -7.234520596353585, -7.239603528384539, -7.233885207667162, -7.232288789343925, -7.213622523440033, -7.225235252808737, -7.229912235896686, -7.218807050909878, -7.239032049689976, -7.220160787907363, -7.2163153136978035, -7.215508607064924, -7.217514511498871, -7.231954896099307, -7.2296714741882955, -7.232897976235796, -7.23671915877639, -7.210412586036357, -7.226610519232944, -7.217954881254602, -7.232063174593739, -7.227477410081558, -7.22418940679807, -7.227675986569633, -7.235965396635691, -7.24233631269727, -7.23379699546329, -7.234703612403967, -7.23508087823179, -7.2381244229018105, -7.242522157722863, -7.22545011836812, -7.234326155618267, -7.227091606180274, -7.236373035300872, -7.242479366897426, -7.235726190682856, -7.222299831383137, -7.23929324846661, -7.223227029274241, -7.256682736337177, -7.22755431910217, -7.234020343057368, -7.24547439399411, -7.245936366171937, -7.2448722042482165, -7.233421544314716, -7.226760703531076, -7.231403041353445, -7.223348320008962, -7.236209436597549, -7.237284228214967, -7.237086351618896, -7.2227428922274335, -7.236597662223316, -7.215213272528259, -7.2366175601210445, -7.236372515337477, -7.23378139932939, -7.239678024251709, -7.209977018523269, -7.228036674186689, -7.24120445822543, -7.227977743073735, -7.235555247511488, -7.241612289108028, -7.234355382241897, -7.237239537122246, -7.226822847088125, -7.238582037056109, -7.229715528846131, -7.229020963804856, -7.233930437028157, -7.238369981746838, -7.219061553625704, -7.248432422394126, -7.226410064889077, -7.251238789575872, -7.233621702768771, -7.230560965468209, -7.233126665159292, -7.236456409597164, -7.236985807434631, -7.209080550992588, -7.229348064880344, -7.253207894067526, -7.244851744551426, -7.222339372553338, -7.238784850816927, -7.22166865332316, -7.242762115068465, -7.222032233594889, -7.248488642944156, -7.238976567295522, -7.219009556806371, -7.238492619645845, -7.240190035190226, -7.241591759090362, -7.246143126531719, -7.223170840344449, -7.239156672984446, -7.230406176249597, -7.239779728598253, -7.236635133369277, -7.230763306589369, -7.229588430994365, -7.241729445862522, -7.217276949479711, -7.239918126486504, -7.226670667938001, -7.236228224012701, -7.226557442277676, -7.220181775697007, -7.234696495113567, -7.21866442584163, -7.221932457968856, -7.23350712090544, -7.2345189692494865, -7.217603129562463, -7.24551136255455, -7.2338363317123475, -7.229478026940409, -7.227224670906925, -7.238386476576431, -7.235947622214544, -7.2533286051484085, -7.239281164820781, -7.242676244778507, -7.2404320534315705, -7.237961914418423, -7.227765426077761, -7.238172338957211, -7.240418795584355, -7.23534521870218, -7.237472208938969, -7.23896936052762, -7.239446562558402, -7.224505532639014, -7.255045378639138, -7.2395972203564085, -7.231518858243917, -7.227586254785921, -7.243820387408635, -7.236821110961883, -7.229397814311788, -7.230458241979415, -7.2220092561007325, -7.227633519763264, -7.237948911093603, -7.223815065540219, -7.236247371937157, -7.233522867763223, -7.244506933607312, -7.228829589518504, -7.229575419310993, -7.229756751164102, -7.233194516496404, -7.240512133393528, -7.238160632291315, -7.23426508781678, -7.232962049991081, -7.2219132008464655, -7.248220236727849, -7.241637994352253, -7.2410873969477425, -7.223093799090048, -7.241487262172387, -7.227100985802835, -7.244157337271549, -7.228130258297405, -7.225592694637175, -7.230619033295259, -7.216665424362412, -7.243661109428171, -7.22352986332442, -7.236800906108402, -7.24431578174889, -7.2419659441983795, -7.249180739759378, -7.237421321661119, -7.224910782354195, -7.231841983484647, -7.241322974711623, -7.234127009283536, -7.2299625097876135, -7.230684222555189, -7.23700428772785, -7.229283613346334, -7.237321764578183, -7.230227672250537, -7.2335933695548205, -7.2365050778118984, -7.241236452552253, -7.243775317670092, -7.22639408357877, -7.23949849820077, -7.238180452840295, -7.24638119109773, -7.236256581617576, -7.212054729551554, -7.235289176899662, -7.226127665100424, -7.231602689899314, -7.23696558664305, -7.227442127044163, -7.240862399910503, -7.243898775733997, -7.227932376279429, -7.2368032897600285, -7.23054815019836, -7.220328072685952, -7.2340976972188615, -7.232601303264701, -7.2322988344501855, -7.219455639532654, -7.237211018125533, -7.224532746187833, -7.244491188531013, -7.226687934260373, -7.239541976434994, -7.233330306854079, -7.229050242331241, -7.237661542125556, -7.241127127604099, -7.237907000100805, -7.22187777336326, -7.244377641270739, -7.236358025550393, -7.233492165117918, -7.230423968851607, -7.214266446571548, -7.242337343771986, -7.237681710609208, -7.238001605199166, -7.235376459262585, -7.239170154605418, -7.2457223471380665, -7.241575636641166, -7.231149441259758, -7.23162829915286, -7.226566400063272, -7.2376870522820855, -7.23075129412491, -7.2372692965658745, -7.242438581084864, -7.229631853925922, -7.235736760163012, -7.238012607777581, -7.2207996997538615, -7.240512113021775, -7.231422839935761, -7.229856189296272, -7.2534681943734665, -7.238672033013341, -7.229692925943167, -7.240845083741161, -7.22922774464201, -7.229695535766312, -7.226610598619716, -7.235369410121787], 'approximated_eneriges_1': [-7.550683242962277, -7.538822863135065, -7.55008411662876, -7.55897796865705, -7.5632027489170826, -7.571948592178383, -7.560385446643115, -7.548556313213329, -7.557350382776294, -7.539623454091931, -7.554608404243045, -7.543805800289237, -7.552635230989461, -7.41748866035232, -7.4131605710874435, -7.414964422054285, -7.40205786354657, -7.408940043385269, -7.4192390558757255, -7.401615295588742, -7.411025352351437, -7.421010290318388, -7.401690746795952, -7.40417517482812, -7.4162558000248175, -7.397908971882198, -7.548923057644963, -7.546904128323561, -7.537370942920183, -7.560631342158139, -7.556976340568663, -7.560273628380784, -7.54430452309549, -7.543731717970082, -7.54818633166277, -7.543523800200846, -7.551414499272261, -7.5466198041360935, -7.539667932956796, -7.551645714623743, -7.538862222112098, -7.562295138781764, -7.55332466813669, -7.55641294673202, -7.556218619483761, -7.540866660026964, -7.545212656115853, -7.534946874032398, -7.542570699710828, -7.547096868400404, -7.553807940207289, -7.560199189958208, -7.561890029252995, -7.557121854128307, -7.554832078194802, -7.553704629848302, -7.555349916988187, -7.562804951811505, -7.544707827159325, -7.560204353132805, -7.55358193608607, -7.571005519951473, -7.557439496553331, -7.566095786379841, -7.55353072817666, -7.557675101533266, -7.5588578425861375, -7.546817344268718, -7.554652882560319, -7.542858506371966, -7.559609433119449, -7.5633202206735675, -7.551993438874603, -7.556593066198202, -7.556522200061691, -7.576482169720943, -7.558982153569666, -7.552108994671986, -7.544092461680996, -7.549386959976692, -7.55604436736714, -7.56663002661859, -7.557603825019027, -7.57597219383917, -7.549096241220243, -7.558338291953084, -7.569480878373801, -7.554975054877208, -7.56272165820795, -7.5538560975129, -7.556921992871783, -7.554024518465438, -7.557232533630467, -7.550615654836533, -7.564592721877621, -7.555498129722722, -7.569754026463483, -7.556325776674718, -7.561082045791271, -7.555653204839074, -7.553421577345177, -7.5638108159274156, -7.555597712756221, -7.549532088549326, -7.545794391815538, -7.54933930347947, -7.550947131685214, -7.557864130988, -7.559528132170389, -7.556113894153712, -7.54713899610519, -7.552075673500586, -7.5548836593173325, -7.562954938356408, -7.568867207428206, -7.554963719680873, -7.548680943666945, -7.552222876645382, -7.551841268146282, -7.556709155786664, -7.566096760519089, -7.569017170131674, -7.541787800400642, -7.556953061587577, -7.568509133649472, -7.56095440417102, -7.563144288945327, -7.549792402098119, -7.559501275831297, -7.5549071287459535, -7.5642991678225675, -7.551434529493169, -7.568404711014954, -7.573174050281887, -7.561251223246477, -7.555577276726262, -7.5639830990618515, -7.553438975257628, -7.553223301196071, -7.559058502220418, -7.546610118938945, -7.554150547318012, -7.5547881052282335, -7.57394668447194, -7.55581333138479, -7.544552569726852, -7.559495717543246, -7.5512159438824344, -7.556732611377398, -7.561626393637131, -7.566125278460293, -7.550860731860758, -7.547120653510534, -7.567891500009217, -7.559897056877579, -7.547229439818355, -7.554616445258716, -7.549905267646238, -7.562823620108678, -7.551832377008666, -7.556215151401625, -7.541832704185849, -7.549834009326433, -7.543759004986976, -7.556177775140475, -7.553130123896612, -7.558764599205452, -7.568678416059024, -7.536316271504655, -7.539566808598727, -7.569794118614989, -7.54826552268222, -7.563213559398289, -7.563586590532436, -7.563357946972766, -7.56449243196982, -7.551549493511942, -7.556788457208167, -7.554605845898709, -7.549301604957866, -7.549256299203932, -7.563124916479237, -7.537711191305687, -7.56084446024711, -7.559250234185563, -7.566763171451585, -7.556389915734708, -7.556562449101039, -7.5674707805078, -7.541754662855211, -7.559762193303108, -7.548460464886603, -7.554569664380687, -7.56085713240549, -7.561329665646655, -7.565231063614005, -7.552214902866351, -7.55021715047876, -7.57456741735939, -7.564551633420716, -7.543170762950222, -7.562290966614618, -7.540049075028705, -7.553530119011748, -7.544002501820431, -7.5672867103945345, -7.548030815033093, -7.548045691457346, -7.552495419599777, -7.555201363568631, -7.569751786599874, -7.548389452280374, -7.569318545520066, -7.5583551029780836, -7.564391720035807, -7.553567267215852, -7.560895124738541, -7.557424696478318, -7.567694847030491, -7.5565367220982385, -7.574118234369145, -7.561551078356445, -7.55449413546597, -7.569749979638946, -7.5489113666304, -7.556567860078667, -7.553595588280471, -7.55526180797587, -7.560393154569164, -7.5593118613025565, -7.55036790399995, -7.557962327701532, -7.562275794925345, -7.562525712648386, -7.564246148807295, -7.5551786896418625, -7.5571712986381865, -7.55258224270072, -7.553230158291084, -7.565559563874206, -7.550426796905481, -7.562155126547323, -7.537269898300711, -7.561162641385397, -7.5483183741395035, -7.5631623346616275, -7.556378903045296, -7.556801181997425, -7.550058619891834, -7.5640480149969, -7.558658917279983, -7.543861551851747, -7.547173974115072, -7.550577681045478, -7.561716440678923, -7.558409814338887, -7.552705674552182, -7.550037948010117, -7.549165761317303, -7.571757583835817, -7.564694526104574, -7.555666889939895, -7.562154738573207, -7.563277126344072, -7.56526660154923, -7.5625647680912715, -7.542881660555917, -7.554257598760987, -7.561379045441735, -7.556062561109061, -7.550863430729272, -7.550834104439993, -7.564164431198491, -7.557775005234187, -7.546211102075424, -7.554257203233912, -7.556254880533049, -7.559289364937038, -7.570457983152539, -7.5580062705260564, -7.54863397125863, -7.570783936678156, -7.56409808967914, -7.548862960439668, -7.561953452200041, -7.546232642716481, -7.551103331043392, -7.550179395728152, -7.547915363708788, -7.559735929973729, -7.548090965991739, -7.5557390949559196, -7.584170566175145, -7.557306216303866, -7.571676501223552, -7.54772621208632, -7.551036900911758, -7.552493737346103], 'approximated_eneriges_2': [-7.410444364672608, -7.415714453423059, -7.415938097126615, -7.408017966663016, -7.411926696725731, -7.410701573897746, -7.419352878341387, -7.419158949271299, -7.420415015254557, -7.424619761587982, -7.4268511180459065, -7.418024427836759, -7.404609945520007, -7.589386998779999, -7.600319421387095, -7.607455138580125, -7.599492255637303, -7.6015256592593765, -7.595930672716543, -7.58717224388028, -7.60987806854404, -7.582168037686289, -7.612525084715747, -7.611666484836461, -7.60652734066912, -7.587143701774609, -7.4837958290812105, -7.479734294459937, -7.491546169546624, -7.5111811400213115, -7.486656111152134, -7.482032814626383, -7.494604961911633, -7.494052164683773, -7.478067560055237, -7.486570495236522, -7.479730591071314, -7.4797851754636735, -7.486953928064199, -7.433142530036842, -7.4229755855042985, -7.432500450937396, -7.43294364150897, -7.414775693820271, -7.422289122079512, -7.439332189153368, -7.438893758915969, -7.413233120318137, -7.456667893399677, -7.441987027768607, -7.425008769691984, -7.454469381106106, -7.421554336127311, -7.413712774429379, -7.425844973393581, -7.402824712762297, -7.428095926295256, -7.416441753264347, -7.420259300551505, -7.399259445603592, -7.403695766936157, -7.416449591510461, -7.435755442790675, -7.414893307446768, -7.427560288995593, -7.412783417340669, -7.420330177171769, -7.427486797178415, -7.423377363706668, -7.416514061956097, -7.409451610631072, -7.438749449046901, -7.408960013709229, -7.421516106416111, -7.420611253255005, -7.413942378961346, -7.413595982264582, -7.390780588843896, -7.4084622853888735, -7.42124209464471, -7.412880469775962, -7.420777016827756, -7.427536960587946, -7.425587323265961, -7.418111470884228, -7.4143275263345165, -7.410316651774604, -7.401856447363387, -7.411822767959461, -7.431389462225188, -7.403089235376795, -7.401598556814728, -7.411348628632633, -7.414386324492143, -7.402957302521619, -7.432926701674536, -7.396649841473121, -7.415251855041303, -7.411428762397702, -7.406042320381719, -7.4145398335250325, -7.4152709291939685, -7.40658424014324, -7.405066053058349, -7.411548528475879, -7.414008371571924, -7.4123205752620835, -7.406722186984054, -7.417842283938753, -7.419830930402007, -7.400463799038998, -7.412282021683004, -7.40771656019699, -7.4192285057796425, -7.420192856399023, -7.428356692686373, -7.4114023837419865, -7.406367352937335, -7.40361213017597, -7.399731151408673, -7.403760125167092, -7.39514265976909, -7.4066343168997175, -7.416274937994275, -7.410738319182156, -7.402652742009214, -7.412648898988432, -7.411130390161757, -7.393913775543006, -7.401729989208781, -7.408164367202596, -7.410458637641345, -7.420930170929184, -7.420162114969175, -7.4193824884112995, -7.41955380606936, -7.41431645729939, -7.414111034016485, -7.427604797401894, -7.4100578315655685, -7.401925274129811, -7.408904048852081, -7.40917138906226, -7.414023819414739, -7.427551921566607, -7.428652238971265, -7.421105014760246, -7.426059034712438, -7.421227742998169, -7.384943157249668, -7.409354186033169, -7.41566556688613, -7.4214593382824505, -7.415144527375948, -7.408267821484224, -7.406554894795174, -7.402385639726274, -7.419116895868815, -7.409447232301686, -7.410747900640483, -7.403283885417719, -7.414859601277965, -7.3958330821863445, -7.4102185671681875, -7.409901753007446, -7.4349614409928675, -7.3914259123102255, -7.416534441131431, -7.408995196211471, -7.410313765251155, -7.415287726486965, -7.39998041723367, -7.4202562928892455, -7.413155506758194, -7.392766031853719, -7.410718186662607, -7.3941527335440105, -7.4140329976786, -7.410883145425181, -7.411236343181268, -7.433653854220001, -7.4124161445611065, -7.410523350736927, -7.423066054748081, -7.417395045470075, -7.405232589932642, -7.411695349205476, -7.393438544782937, -7.413070092312006, -7.411845736178486, -7.405986199902686, -7.412877320568309, -7.423637869512572, -7.417485122778937, -7.420346375249428, -7.421874620879591, -7.412471538840202, -7.408661648174666, -7.398806523365515, -7.409703274160633, -7.401502370816964, -7.415019489819521, -7.397996366552989, -7.416879606328125, -7.409568524824878, -7.412450181316362, -7.4043174398596, -7.390707254328941, -7.4144954187659415, -7.4008468406208126, -7.432212658353873, -7.417689790331265, -7.416297950401478, -7.420371265411078, -7.399711767696046, -7.418632969604109, -7.411531656365526, -7.41259101043679, -7.400612471388634, -7.4129388286238695, -7.397720546438961, -7.429951027389409, -7.428525938671341, -7.408518580725819, -7.407733315774913, -7.403006436670952, -7.403562707208992, -7.4180326153299525, -7.424593788196596, -7.42401998096983, -7.421705156615664, -7.404396708972521, -7.415199440338291, -7.411222660695321, -7.429646219900774, -7.418526018129546, -7.415979223492038, -7.3950969048259605, -7.400558588908429, -7.405183376463522, -7.404814221232868, -7.4108782549620065, -7.404578883465207, -7.397070653288616, -7.419287643385738, -7.415031097689276, -7.415169554445011, -7.420820684775902, -7.4149458976195355, -7.398974222998238, -7.4018094514863755, -7.4190927912145845, -7.40660299251048, -7.410718862777842, -7.408100477638087, -7.4251843746433055, -7.414906996945376, -7.431118038850682, -7.400281442721625, -7.4126205211633005, -7.40787768217344, -7.403092498243889, -7.409253836038857, -7.417143768118361, -7.4061200321664975, -7.400927261585105, -7.412065658573083, -7.410234665650475, -7.408906590251693, -7.426580069577404, -7.431152043071313, -7.409979137262973, -7.405085762880571, -7.405375805653347, -7.415085497284975, -7.428865699646528, -7.401761293027105, -7.412241800401161, -7.414960843288435, -7.421647163637885, -7.4154040320456165, -7.391043169754898, -7.405554611504087, -7.398829731574355, -7.408414720800373, -7.406586104670398, -7.404128438382962, -7.406072069560908, -7.40628852023641, -7.407877820661062, -7.402004918163509, -7.416688848785448, -7.402282440897539, -7.421522438989727, -7.41322314959422, -7.3976270021053905, -7.393738169656054, -7.401149522147831], 'approximated_eneriges_3': [-7.565665224802693, -7.571558557541593, -7.563488411786494, -7.5535972819342545, -7.568265658658191, -7.55764361817917, -7.549862490270664, -7.552378085418476, -7.561530453734309, -7.557885510897533, -7.550194896715531, -7.561191639341913, -7.547381220635373, -7.478847184356431, -7.493074318994978, -7.4936530929344505, -7.484656587329637, -7.4850404374973944, -7.48397222059697, -7.502882932513469, -7.497784126206931, -7.48061204741115, -7.488002033465607, -7.485254643745074, -7.482741338968084, -7.476596274780958, -7.58745351778472, -7.589352564985627, -7.604498448591276, -7.603986963079971, -7.60551920715375, -7.579345775953151, -7.594499215719384, -7.577776377931761, -7.594834362967512, -7.598861258957919, -7.614058213583621, -7.599076254034332, -7.610889082645888, -7.570468971532068, -7.565978169378039, -7.5689900582031, -7.56371558736955, -7.581395302038702, -7.569812845506195, -7.558061138578111, -7.57025094955635, -7.561662791049137, -7.559440699252352, -7.5591156104895205, -7.584113721903352, -7.569875517183606, -7.558351982919966, -7.561801548837393, -7.574467881363289, -7.549593226392686, -7.552273850283872, -7.569034967857946, -7.578802333381693, -7.566025496212142, -7.5587455859661565, -7.576459631268144, -7.561951100321032, -7.547104104469302, -7.564615613182923, -7.549965663541954, -7.5645195346878, -7.558149543969611, -7.554149140026431, -7.54245441822292, -7.5663544547300665, -7.555466278495125, -7.542851281074657, -7.552867299265858, -7.557246120884814, -7.562512200772655, -7.557729570157427, -7.548701524163326, -7.556629212603531, -7.562703070038278, -7.550158579897595, -7.557899460876809, -7.572583496985447, -7.556899857227568, -7.558109722433135, -7.543851154833375, -7.5510141824102615, -7.5736155602900626, -7.563360428348574, -7.547099219791205, -7.562822948215396, -7.566482515865028, -7.558787451469362, -7.556713812874585, -7.548583757587774, -7.562869475049058, -7.57078625456337, -7.566871254827781, -7.545176860647729, -7.571038541090749, -7.558378445475016, -7.558554328273203, -7.5640839014068035, -7.553778686511179, -7.558744848456306, -7.556879426146582, -7.539270801287508, -7.559349035216264, -7.556619401877544, -7.55933301867962, -7.558763567968391, -7.560433931647151, -7.563306035220907, -7.555059625283163, -7.556514978356334, -7.5671196377135885, -7.548457871207328, -7.574302889855866, -7.548241349502122, -7.556506780978408, -7.562947648240894, -7.557627833978751, -7.558031548956967, -7.553053133979084, -7.551161697722563, -7.557668696358851, -7.553807041628483, -7.557504336344521, -7.563768060767367, -7.559352004099949, -7.556503680915647, -7.54624800608743, -7.5678519641943085, -7.5426564498654525, -7.552297667857417, -7.559257779584226, -7.542668377833022, -7.557672004746245, -7.563448690659477, -7.559049301944132, -7.569165597455367, -7.544354950612827, -7.5499565930042705, -7.569860040564563, -7.5641490323006195, -7.550623222632321, -7.550514992597756, -7.558251804357427, -7.539828941350091, -7.55566232225068, -7.559678722135635, -7.560015820058426, -7.556801562259494, -7.566537275261356, -7.553064531028829, -7.548098479251611, -7.559985898201188, -7.565321530733754, -7.570869680141159, -7.554814630220452, -7.560505089273475, -7.565614656322719, -7.569028398909243, -7.547996809309446, -7.5664089455734, -7.550368842223157, -7.559795486797088, -7.541665676127119, -7.550089253965164, -7.5458670317836045, -7.553665967844049, -7.563936972176008, -7.560662269817603, -7.568667883986726, -7.5593734629693445, -7.5470354738758765, -7.561173656994816, -7.5424587924253155, -7.566303314591444, -7.562030367717736, -7.5560945532955275, -7.5766387156603585, -7.55790879145774, -7.558002418794064, -7.561704822479739, -7.5572186777597326, -7.565383783550966, -7.564248092630112, -7.542284617055556, -7.562128937563885, -7.547824673351669, -7.561777556251198, -7.5610090539379655, -7.552147351853727, -7.560794348824769, -7.563898039889992, -7.557013161047448, -7.573540345041206, -7.566905869413926, -7.57600834063447, -7.552371347093251, -7.555707984710987, -7.5644290606653115, -7.561914204862563, -7.559597381947844, -7.566880361745033, -7.57536927030609, -7.57056387243906, -7.565040990817158, -7.544954460939858, -7.5551845038135195, -7.56399852895941, -7.577609511622952, -7.559229812886538, -7.545124565157558, -7.550217690463665, -7.563742098340991, -7.561404415432949, -7.568860579358517, -7.570400075958647, -7.549757454804531, -7.572396927050729, -7.566226342594929, -7.553919302071998, -7.559697974169244, -7.566223465086674, -7.5390758326632525, -7.568494161923016, -7.550127108590029, -7.552933589818219, -7.563651853617645, -7.561104417454871, -7.541477275422324, -7.557756030360809, -7.55533249204703, -7.558900869064141, -7.555633514385122, -7.545413150167204, -7.554998988840136, -7.554953103488577, -7.56904469782563, -7.5571134000403655, -7.567999492576593, -7.560807573425701, -7.543779000768876, -7.565146911478062, -7.552412295678639, -7.562826424402587, -7.549464531576674, -7.568419161862177, -7.559471585349289, -7.573540563551335, -7.557952950896124, -7.555608147763329, -7.557356430298694, -7.567542313132486, -7.542182882707864, -7.565994613995024, -7.558524876948161, -7.578865973010801, -7.552717730416121, -7.572777962204683, -7.549903472783061, -7.557174238191128, -7.544273588204877, -7.55075254170614, -7.548722288848476, -7.5560627662135245, -7.554451536490434, -7.551615126174713, -7.55063467207524, -7.556887920783522, -7.554619773436095, -7.559158327825837, -7.5544038736168995, -7.557438674400187, -7.559357089605574, -7.572227309132768, -7.548021619199864, -7.561561151050764, -7.552085181079079, -7.564528582858334, -7.563319348025164, -7.56118837594011, -7.553830965704677, -7.55987891905092, -7.571607103462974, -7.568215034765017, -7.559707868972947, -7.555750141435884, -7.565404624717864, -7.550693539944269, -7.565729179048917, -7.563673079856357, -7.548448932343774, -7.548227144408689, -7.55813043032206, -7.552842495614734]}
plot_convergence_of_optimization_process(TI_approximated_energies, transverse_ising_4_qubits, )
|
https://github.com/qiskit-community/qiskit-qcgpu-provider
|
qiskit-community
|
"""
In this example a Bell state is made.
"""
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit import execute
from qiskit_qcgpu_provider import QCGPUProvider
Provider = QCGPUProvider()
# Create a Quantum Register with 2 qubits.
q = QuantumRegister(2)
# Create a Quantum Circuit with 2 Qubits
qc = QuantumCircuit(q)
# Add a H gate on qubit 0, putting this qubit in superposition.
qc.h(q[0])
# Add a CX (CNOT) gate on control qubit 0 and target qubit 1, putting
# the qubits in a Bell state.
qc.cx(q[0], q[1])
# See a list of available local simulators
print("QCGPU backends: ", Provider.backends())
backend_sim = Provider.get_backend('statevector_simulator')
# Compile and run the Quantum circuit on a simulator backend
job_sim = execute(qc, backend_sim)
result_sim = job_sim.result()
# Show the results
print("Simulation Results: ", result_sim)
print(result_sim.get_statevector(qc))
|
https://github.com/qiskit-community/prototype-entanglement-forging
|
qiskit-community
|
import warnings
warnings.filterwarnings("ignore")
from matplotlib import pyplot as plt
import numpy as np
from qiskit.circuit.library import TwoLocal
from qiskit_nature.drivers import Molecule
from qiskit_nature.drivers.second_quantization import PySCFDriver
from qiskit_nature.problems.second_quantization import ElectronicStructureProblem
from qiskit_nature.mappers.second_quantization import JordanWignerMapper
from qiskit_nature.converters.second_quantization import QubitConverter
import sys
sys.path.append("../../")
from entanglement_forging import (
EntanglementForgedConfig,
EntanglementForgedDriver,
EntanglementForgedGroundStateSolver,
)
# Coefficients that define the one-body terms of the Hamiltonain
hcore = np.array([[-1.12421758, -0.9652574], [-0.9652574, -1.12421758]])
# Coefficients that define the two-body terms of the Hamiltonian
mo_coeff = np.array([[0.54830202, 1.21832731], [0.54830202, -1.21832731]])
# Coefficients for the molecular orbitals
eri = np.array(
[
[
[[0.77460594, 0.44744572], [0.44744572, 0.57187698]],
[[0.44744572, 0.3009177], [0.3009177, 0.44744572]],
],
[
[[0.44744572, 0.3009177], [0.3009177, 0.44744572]],
[[0.57187698, 0.44744572], [0.44744572, 0.77460594]],
],
]
)
driver = EntanglementForgedDriver(
hcore=hcore,
mo_coeff=mo_coeff,
eri=eri,
num_alpha=1,
num_beta=1,
nuclear_repulsion_energy=0.7199689944489797,
)
problem = ElectronicStructureProblem(driver)
problem.second_q_ops()
converter = QubitConverter(JordanWignerMapper())
bitstrings = [[1, 0], [0, 1]]
ansatz = TwoLocal(2, [], "cry", [[0, 1], [1, 0]], reps=1)
ansatz.draw()
from qiskit import Aer
backend = Aer.get_backend("statevector_simulator")
config = EntanglementForgedConfig(
backend=backend, maxiter=200, initial_params=[0, 0.5 * np.pi]
)
calc = EntanglementForgedGroundStateSolver(
qubit_converter=converter, ansatz=ansatz, bitstrings_u=bitstrings, config=config
)
res = calc.solve(problem)
res
print("Energies (from only one paramset in each iteration):")
plt.plot([e[0] for e in res.get_energies_history()])
plt.plot([e[1] for e in res.get_energies_history()[0:-1]])
plt.show()
print("Schmidts (from only one paramset in each iteration):")
plt.plot([s[0] for s in res.get_schmidts_history()])
plt.show()
print("Parameters (from only one paramset in each iteration):")
plt.plot([p[0] for p in res.get_parameters_history()])
plt.plot([p[1] for p in res.get_parameters_history()[0:-1]])
plt.show()
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/grossiM/Qiskit_workshop1019
|
grossiM
|
# initialization
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
# importing Qiskit
from qiskit import IBMQ, BasicAer
from qiskit.providers.ibmq import least_busy
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute
# import basic plot tools
from qiskit.tools.visualization import plot_histogram
# Creating registers
# n qubits for querying the oracle and one qubit for storing the answer
qr = QuantumRegister(2,name='qr')
crsingle = ClassicalRegister(1)
deutsch = QuantumCircuit(qr,crsingle)
deutsch.x(qr[1])
deutsch.h(qr[1])
deutsch.draw(output='latex')
deutsch.h(qr[0])
deutsch.draw(output='mpl')
deutsch.cx(qr[0],qr[1])
deutsch.h(qr[0])
deutsch.measure(qr[0],crsingle[0])
deutsch.draw(output='mpl')
# use local simulator
backend = BasicAer.get_backend('qasm_simulator')
shots = 1024
results = execute(deutsch, backend=backend, shots=shots).result()
answer = results.get_counts()
plot_histogram(answer)
# set the length of the $n$-bit string.
n = 2
# set the oracle, b for balanced, c for constant
oracle = "b"
# if the oracle is balanced, set the hidden bitstring, b
if oracle == "b":
b = 3 # np.random.randint(1,2**n) uncomment for a random value
# if the oracle is constant, set c = 0 or 1 randomly.
if oracle == "c":
c = np.random.randint(2)
# Creating registers
# n qubits for querying the oracle and one qubit for storing the answer
qr = QuantumRegister(n+1)
cr = ClassicalRegister(n)
djCircuit = QuantumCircuit(qr, cr)
barriers = True
# Since all qubits are initialized to |0>, we need to flip the second register qubit to the the |1> state
djCircuit.x(qr[n])
# Apply barrier
if barriers:
djCircuit.barrier()
# Apply Hadamard gates to all qubits
djCircuit.h(qr)
# Apply barrier
if barriers:
djCircuit.barrier()
# Query the oracle
if oracle == "c": # if the oracle is constant, return c
if c == 1:
djCircuit.x(qr[n])
else:
djCircuit.iden(qr[n])
else: # otherwise, the oracle is balanced and it returns the inner product of the input with b (non-zero bitstring)
for i in range(n):
if (b & (1 << i)):
djCircuit.cx(qr[i], qr[n])
# Apply barrier
if barriers:
djCircuit.barrier()
# Apply Hadamard gates to the first register after querying the oracle
for i in range(n):
djCircuit.h(qr[i])
# Measure the first register
for i in range(n):
djCircuit.measure(qr[i], cr[i])
djCircuit.draw(output='mpl')
# use local simulator
backend = BasicAer.get_backend('qasm_simulator')
shots = 1024
results = execute(djCircuit, backend=backend, shots=shots).result()
answer = results.get_counts()
plot_histogram(answer)
# Load our saved IBMQ accounts and get the least busy backend device with less than or equal to 5 qubits
#IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q')
provider.backends()
backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits <= 5 and
not x.configuration().simulator and x.status().operational==True))
# Run our circuit on the least busy backend. Monitor the execution of the job in the queue
from qiskit.tools.monitor import job_monitor
shots = 1024
job = execute(djCircuit, backend=backend, shots=shots)
job_monitor(job, interval = 2)
# Get the results of the computation
results = job.result()
answer = results.get_counts()
plot_histogram(answer)
N = 4
qrQFT = QuantumRegister(N,'qftr')
QFT = QuantumCircuit(qrQFT)
for i in range(N):
QFT.h(qrQFT[i])
for k in range(i+1,N):
l = k-i+1
QFT.cu1(2*math.pi/(2**l),qrQFT[k],qrQFT[i])
QFT.draw(output='mpl')
import qiskit
qiskit.__qiskit_version__
|
https://github.com/Harcipan/QAI_GroverSim
|
Harcipan
|
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
class DeutschJozsa:
'''
Class to generate a DeutschJozsa object containing:
- init functions
- oracle function
- dj function
'''
def __init__(self, case, input_str):
'''
Initialization of the object:
@case: (str) type of oracle balanced or constant
@input_str: (str) string input state values
'''
self.case = case
self.number_qubit = len(input_str)
self.str_input = input_str
def oracle(self):
'''
Will create the oracle needed for the Deutsch-Jozsa algorithm
No input, the function will be used in the dj function
@return the oracle in form of a gate
'''
# Create the QuantumCircuit with n+1 qubits
self.oracle_circuit = QuantumCircuit(self.number_qubit+1)
# Balanced case
if self.case == "balanced":
# apply an X-gate to a qubit when its value is 1
for qubit in range(len(self.str_input)):
if self.str_input[qubit] == '1':
self.oracle_circuit.x(qubit)
# Apply CNOT gates on each qubit
for qubit in range(self.number_qubit):
self.oracle_circuit.cx(qubit, self.number_qubit)
# apply another set of X gates when the input qubit == 1
for qubit in range(len(self.str_input)):
if self.str_input[qubit] == '1':
self.oracle_circuit.x(qubit)
# Constant case
if self.case == "constant":
# Output 0 for a constant oracle
self.output = np.random.randint(2)
if self.output == 1:
self.oracle_circuit.x(self.number_qubit)
# convert the quantum circuit into a gate
self.oracle_gate = self.oracle_circuit.to_gate()
# name of the oracle
self.oracle_gate.name = "Oracle"
return self.oracle_gate
def dj(self):
'''
Create the Deutsch-Jozsa algorithm in the general case with n qubit
No input
@return the quantum circuit of the DJ
'''
self.dj_circuit = QuantumCircuit(self.number_qubit+1, self.number_qubit)
# Set up the output qubit:
self.dj_circuit.x(self.number_qubit)
self.dj_circuit.h(self.number_qubit)
# Psi_0
for qubit in range(self.number_qubit):
self.dj_circuit.h(qubit)
# Psi_1 + oracle
self.dj_circuit.append(self.oracle(), range(self.number_qubit+1))
# Psi_2
for qubit in range(self.number_qubit):
self.dj_circuit.h(qubit)
# Psi_3
# Let's put some measurement
for i in range(self.number_qubit):
self.dj_circuit.measure(i, i)
return self.dj_circuit
test = DeutschJozsa('constant', '0110')
#circuit = test.oracle()
dj_circuit = test.dj()
dj_circuit.draw('mpl')
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)
from qiskit import IBMQ
#TOKEN = 'paste your token here'
#IBMQ.save_account(TOKEN)
IBMQ.load_account() # Load account from disk
IBMQ.providers()
provider = IBMQ.get_provider(hub='ibm-q')
provider.backends()
provider.backends(filters=lambda x: x.configuration().n_qubits >= 5
and not x.configuration().simulator
and x.status().operational==True)
backend = provider.get_backend('ibmq_manila')
backend
mapped_circuit = transpile(dj_circuit, backend=backend)
qobj = assemble(mapped_circuit, backend=backend, shots=1024)
job = backend.run(qobj)
job.status() # 9:17 pm
result = job.result()
counts = result.get_counts()
print(counts)
plot_histogram(counts)
plot_histogram(counts,figsize=(10,8), filename='DJ.jpeg')
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""
Initialize test.
"""
import math
import unittest
import numpy as np
from ddt import ddt, data
from qiskit import QuantumCircuit
from qiskit import QuantumRegister
from qiskit import ClassicalRegister
from qiskit import transpile
from qiskit import execute, assemble, BasicAer
from qiskit.quantum_info import state_fidelity, Statevector, Operator
from qiskit.exceptions import QiskitError
from qiskit.test import QiskitTestCase
from qiskit.extensions.quantum_initializer import Initialize
@ddt
class TestInitialize(QiskitTestCase):
"""Qiskit Initialize tests."""
_desired_fidelity = 0.99
def test_uniform_superposition(self):
"""Initialize a uniform superposition on 2 qubits."""
desired_vector = [0.5, 0.5, 0.5, 0.5]
qr = QuantumRegister(2, "qr")
qc = QuantumCircuit(qr)
qc.initialize(desired_vector, [qr[0], qr[1]])
job = execute(qc, BasicAer.get_backend("statevector_simulator"))
result = job.result()
statevector = result.get_statevector()
fidelity = state_fidelity(statevector, desired_vector)
self.assertGreater(
fidelity,
self._desired_fidelity,
f"Initializer has low fidelity {fidelity:.2g}.",
)
def test_deterministic_state(self):
"""Initialize a computational-basis state |01> on 2 qubits."""
desired_vector = [0, 1, 0, 0]
qr = QuantumRegister(2, "qr")
qc = QuantumCircuit(qr)
qc.initialize(desired_vector, [qr[0], qr[1]])
job = execute(qc, BasicAer.get_backend("statevector_simulator"))
result = job.result()
statevector = result.get_statevector()
fidelity = state_fidelity(statevector, desired_vector)
self.assertGreater(
fidelity,
self._desired_fidelity,
f"Initializer has low fidelity {fidelity:.2g}.",
)
def test_statevector(self):
"""Initialize gates from a statevector."""
# ref: https://github.com/Qiskit/qiskit-terra/issues/5134 (footnote)
desired_vector = [0, 0, 0, 1]
qc = QuantumCircuit(2)
statevector = Statevector.from_label("11")
qc.initialize(statevector, [0, 1])
self.assertEqual(qc.data[0].operation.params, desired_vector)
def test_bell_state(self):
"""Initialize a Bell state on 2 qubits."""
desired_vector = [1 / math.sqrt(2), 0, 0, 1 / math.sqrt(2)]
qr = QuantumRegister(2, "qr")
qc = QuantumCircuit(qr)
qc.initialize(desired_vector, [qr[0], qr[1]])
job = execute(qc, BasicAer.get_backend("statevector_simulator"))
result = job.result()
statevector = result.get_statevector()
fidelity = state_fidelity(statevector, desired_vector)
self.assertGreater(
fidelity,
self._desired_fidelity,
f"Initializer has low fidelity {fidelity:.2g}.",
)
def test_ghz_state(self):
"""Initialize a GHZ state on 3 qubits."""
desired_vector = [1 / math.sqrt(2), 0, 0, 0, 0, 0, 0, 1 / math.sqrt(2)]
qr = QuantumRegister(3, "qr")
qc = QuantumCircuit(qr)
qc.initialize(desired_vector, [qr[0], qr[1], qr[2]])
job = execute(qc, BasicAer.get_backend("statevector_simulator"))
result = job.result()
statevector = result.get_statevector()
fidelity = state_fidelity(statevector, desired_vector)
self.assertGreater(
fidelity,
self._desired_fidelity,
f"Initializer has low fidelity {fidelity:.2g}.",
)
def test_initialize_register(self):
"""Initialize one register out of two."""
desired_vector = [1 / math.sqrt(2), 0, 0, 1 / math.sqrt(2)]
qr = QuantumRegister(2, "qr")
qr2 = QuantumRegister(2, "qr2")
qc = QuantumCircuit(qr, qr2)
qc.initialize(desired_vector, qr)
job = execute(qc, BasicAer.get_backend("statevector_simulator"))
result = job.result()
statevector = result.get_statevector()
fidelity = state_fidelity(statevector, np.kron([1, 0, 0, 0], desired_vector))
self.assertGreater(
fidelity,
self._desired_fidelity,
f"Initializer has low fidelity {fidelity:.2g}.",
)
def test_initialize_one_by_one(self):
"""Initializing qubits individually into product state same as initializing the pair."""
qubit_0_state = [1, 0]
qubit_1_state = [1 / math.sqrt(2), 1 / math.sqrt(2)]
qr = QuantumRegister(2, "qr")
qc_a = QuantumCircuit(qr)
qc_a.initialize(np.kron(qubit_1_state, qubit_0_state), qr)
qc_b = QuantumCircuit(qr)
qc_b.initialize(qubit_0_state, [qr[0]])
qc_b.initialize(qubit_1_state, [qr[1]])
job = execute([qc_a, qc_b], BasicAer.get_backend("statevector_simulator"))
result = job.result()
statevector_a = result.get_statevector(0)
statevector_b = result.get_statevector(1)
fidelity = state_fidelity(statevector_a, statevector_b)
self.assertGreater(
fidelity,
self._desired_fidelity,
f"Initializer has low fidelity {fidelity:.2g}.",
)
def test_single_qubit(self):
"""Initialize a single qubit to a weighted superposition state."""
desired_vector = [1 / math.sqrt(3), math.sqrt(2) / math.sqrt(3)]
qr = QuantumRegister(1, "qr")
qc = QuantumCircuit(qr)
qc.initialize(desired_vector, [qr[0]])
job = execute(qc, BasicAer.get_backend("statevector_simulator"))
result = job.result()
statevector = result.get_statevector()
fidelity = state_fidelity(statevector, desired_vector)
self.assertGreater(
fidelity,
self._desired_fidelity,
f"Initializer has low fidelity {fidelity:.2g}.",
)
def test_random_3qubit(self):
"""Initialize to a non-trivial 3-qubit state."""
desired_vector = [
1 / math.sqrt(16) * complex(0, 1),
1 / math.sqrt(8) * complex(1, 0),
1 / math.sqrt(16) * complex(1, 1),
0,
0,
1 / math.sqrt(8) * complex(1, 2),
1 / math.sqrt(16) * complex(1, 0),
0,
]
qr = QuantumRegister(3, "qr")
qc = QuantumCircuit(qr)
qc.initialize(desired_vector, [qr[0], qr[1], qr[2]])
job = execute(qc, BasicAer.get_backend("statevector_simulator"))
result = job.result()
statevector = result.get_statevector()
fidelity = state_fidelity(statevector, desired_vector)
self.assertGreater(
fidelity,
self._desired_fidelity,
f"Initializer has low fidelity {fidelity:.2g}.",
)
def test_random_4qubit(self):
"""Initialize to a non-trivial 4-qubit state."""
desired_vector = [
1 / math.sqrt(4) * complex(0, 1),
1 / math.sqrt(8) * complex(1, 0),
0,
0,
0,
0,
0,
0,
1 / math.sqrt(8) * complex(1, 0),
1 / math.sqrt(8) * complex(0, 1),
0,
0,
0,
0,
1 / math.sqrt(4) * complex(1, 0),
1 / math.sqrt(8) * complex(1, 0),
]
qr = QuantumRegister(4, "qr")
qc = QuantumCircuit(qr)
qc.initialize(desired_vector, [qr[0], qr[1], qr[2], qr[3]])
job = execute(qc, BasicAer.get_backend("statevector_simulator"))
result = job.result()
statevector = result.get_statevector()
fidelity = state_fidelity(statevector, desired_vector)
self.assertGreater(
fidelity,
self._desired_fidelity,
f"Initializer has low fidelity {fidelity:.2g}.",
)
def test_malformed_amplitudes(self):
"""Initializing to a vector with 3 amplitudes fails."""
desired_vector = [1 / math.sqrt(3), math.sqrt(2) / math.sqrt(3), 0]
qr = QuantumRegister(2, "qr")
qc = QuantumCircuit(qr)
self.assertRaises(QiskitError, qc.initialize, desired_vector, [qr[0], qr[1]])
def test_non_unit_probability(self):
"""Initializing to a vector with probabilities not summing to 1 fails."""
desired_vector = [1, 1]
qr = QuantumRegister(2, "qr")
qc = QuantumCircuit(qr)
self.assertRaises(QiskitError, qc.initialize, desired_vector, [qr[0], qr[1]])
def test_normalize(self):
"""Test initializing with a non-normalized vector is normalized, if specified."""
desired_vector = [1, 1]
normalized = np.asarray(desired_vector) / np.linalg.norm(desired_vector)
qc = QuantumCircuit(1)
qc.initialize(desired_vector, [0], normalize=True)
op = qc.data[0].operation
self.assertAlmostEqual(np.linalg.norm(op.params), 1)
self.assertEqual(Statevector(qc), Statevector(normalized))
def test_wrong_vector_size(self):
"""Initializing to a vector with a size different to the qubit parameter length.
See https://github.com/Qiskit/qiskit-terra/issues/2372"""
qr = QuantumRegister(2)
random_state = [
1 / math.sqrt(4) * complex(0, 1),
1 / math.sqrt(8) * complex(1, 0),
0,
1 / math.sqrt(8) * complex(1, 0),
1 / math.sqrt(8) * complex(0, 1),
0,
1 / math.sqrt(4) * complex(1, 0),
1 / math.sqrt(8) * complex(1, 0),
]
qc = QuantumCircuit(qr)
self.assertRaises(QiskitError, qc.initialize, random_state, qr[0:2])
def test_initialize_middle_circuit(self):
"""Reset + initialize gives the correct statevector."""
desired_vector = [0.5, 0.5, 0.5, 0.5]
qr = QuantumRegister(2, "qr")
cr = ClassicalRegister(2, "cr")
qc = QuantumCircuit(qr, cr)
qc.h(qr[0])
qc.cx(qr[0], qr[1])
qc.reset(qr[0])
qc.reset(qr[1])
qc.initialize(desired_vector, [qr[0], qr[1]])
qc.measure(qr, cr)
# statevector simulator does not support reset
shots = 2000
threshold = 0.005 * shots
job = execute(qc, BasicAer.get_backend("qasm_simulator"), shots=shots, seed_simulator=42)
result = job.result()
counts = result.get_counts()
target = {"00": shots / 4, "01": shots / 4, "10": shots / 4, "11": shots / 4}
self.assertDictAlmostEqual(counts, target, threshold)
def test_math_amplitudes(self):
"""Initialize to amplitudes given by math expressions"""
desired_vector = [
0,
math.cos(math.pi / 3) * complex(0, 1) / math.sqrt(4),
math.sin(math.pi / 3) / math.sqrt(4),
0,
0,
0,
0,
0,
1 / math.sqrt(8) * complex(1, 0),
1 / math.sqrt(8) * complex(0, 1),
0,
0,
0,
0,
1 / math.sqrt(4),
1 / math.sqrt(4) * complex(0, 1),
]
qr = QuantumRegister(4, "qr")
qc = QuantumCircuit(qr)
qc.initialize(desired_vector, [qr[0], qr[1], qr[2], qr[3]])
job = execute(qc, BasicAer.get_backend("statevector_simulator"))
result = job.result()
statevector = result.get_statevector()
fidelity = state_fidelity(statevector, desired_vector)
self.assertGreater(
fidelity,
self._desired_fidelity,
f"Initializer has low fidelity {fidelity:.2g}.",
)
def test_combiner(self):
"""Combining two circuits containing initialize."""
desired_vector_1 = [1.0 / math.sqrt(2), 1.0 / math.sqrt(2)]
desired_vector_2 = [1.0 / math.sqrt(2), -1.0 / math.sqrt(2)]
qr = QuantumRegister(1, "qr")
cr = ClassicalRegister(1, "cr")
qc1 = QuantumCircuit(qr, cr)
qc1.initialize(desired_vector_1, [qr[0]])
qc2 = QuantumCircuit(qr, cr)
qc2.initialize(desired_vector_2, [qr[0]])
job = execute(qc1.compose(qc2), BasicAer.get_backend("statevector_simulator"))
result = job.result()
quantum_state = result.get_statevector()
fidelity = state_fidelity(quantum_state, desired_vector_2)
self.assertGreater(
fidelity,
self._desired_fidelity,
f"Initializer has low fidelity {fidelity:.2g}.",
)
def test_equivalence(self):
"""Test two similar initialize instructions evaluate to equal."""
desired_vector = [0.5, 0.5, 0.5, 0.5]
qr = QuantumRegister(2, "qr")
qc1 = QuantumCircuit(qr, name="circuit")
qc1.initialize(desired_vector, [qr[0], qr[1]])
qc2 = QuantumCircuit(qr, name="circuit")
qc2.initialize(desired_vector, [qr[0], qr[1]])
self.assertEqual(qc1, qc2)
def test_max_number_cnots(self):
"""
Check if the number of cnots <= 2^(n+1) - 2n (arXiv:quant-ph/0406176)
"""
num_qubits = 4
_optimization_level = 0
vector = np.array(
[
0.1314346 + 0.0j,
0.32078572 - 0.01542775j,
0.13146466 + 0.0945312j,
0.21090852 + 0.07935982j,
0.1700122 - 0.07905648j,
0.15570757 - 0.12309154j,
0.18039667 + 0.04904504j,
0.22227187 - 0.05055569j,
0.23573255 - 0.09894111j,
0.27307292 - 0.10372994j,
0.24162792 + 0.1090791j,
0.3115577 + 0.1211683j,
0.1851788 + 0.08679141j,
0.36226463 - 0.09940202j,
0.13863395 + 0.10558225j,
0.30767986 + 0.02073838j,
]
)
vector = vector / np.linalg.norm(vector)
qr = QuantumRegister(num_qubits, "qr")
circuit = QuantumCircuit(qr)
circuit.initialize(vector, qr)
b = transpile(
circuit,
basis_gates=["u1", "u2", "u3", "cx"],
optimization_level=_optimization_level,
seed_transpiler=42,
)
number_cnots = b.count_ops()["cx"]
max_cnots = 2 ** (num_qubits + 1) - 2 * num_qubits
self.assertLessEqual(number_cnots, max_cnots)
def test_from_labels(self):
"""Initialize from labels."""
desired_sv = Statevector.from_label("01+-lr")
qc = QuantumCircuit(6)
qc.initialize("01+-lr", range(6))
actual_sv = Statevector.from_instruction(qc)
self.assertTrue(desired_sv == actual_sv)
def test_from_int(self):
"""Initialize from int."""
desired_sv = Statevector.from_label("110101")
qc = QuantumCircuit(6)
qc.initialize(53, range(6))
actual_sv = Statevector.from_instruction(qc)
self.assertTrue(desired_sv == actual_sv)
def _remove_resets(self, circ):
circ.data = [instr for instr in circ.data if instr.operation.name != "reset"]
def test_global_phase_random(self):
"""Test global phase preservation with random state vectors"""
from qiskit.quantum_info.random import random_statevector
repeats = 5
for n_qubits in [1, 2, 4]:
for irep in range(repeats):
with self.subTest(i=f"{n_qubits}_{irep}"):
dim = 2**n_qubits
qr = QuantumRegister(n_qubits)
initializer = QuantumCircuit(qr)
target = random_statevector(dim)
initializer.initialize(target, qr)
uninit = initializer.data[0].operation.definition
self._remove_resets(uninit)
evolve = Statevector(uninit)
self.assertEqual(target, evolve)
def test_global_phase_1q(self):
"""Test global phase preservation with some simple 1q statevectors"""
target_list = [
Statevector([1j, 0]),
Statevector([0, 1j]),
Statevector([1j / np.sqrt(2), 1j / np.sqrt(2)]),
]
n_qubits = 1
dim = 2**n_qubits
qr = QuantumRegister(n_qubits)
for target in target_list:
with self.subTest(i=target):
initializer = QuantumCircuit(qr)
initializer.initialize(target, qr)
# need to get rid of the resets in order to use the Operator class
disentangler = Operator(initializer.data[0].operation.definition.data[1].operation)
zero = Statevector.from_int(0, dim)
actual = zero & disentangler
self.assertEqual(target, actual)
@data(2, "11", [1 / math.sqrt(2), 0, 0, 1 / math.sqrt(2)])
def test_decompose_contains_stateprep(self, state):
"""Test initialize decomposes to a StatePreparation and reset"""
qc = QuantumCircuit(2)
qc.initialize(state)
decom_circ = qc.decompose()
self.assertEqual(decom_circ.data[0].operation.name, "reset")
self.assertEqual(decom_circ.data[1].operation.name, "reset")
self.assertEqual(decom_circ.data[2].operation.name, "state_preparation")
def test_mutating_params(self):
"""Test mutating Initialize params correctly updates StatePreparation params"""
init = Initialize("11")
init.params = "00"
qr = QuantumRegister(2)
qc = QuantumCircuit(qr)
qc.append(init, qr)
decom_circ = qc.decompose()
self.assertEqual(decom_circ.data[2].operation.name, "state_preparation")
self.assertEqual(decom_circ.data[2].operation.params, ["0", "0"])
class TestInstructionParam(QiskitTestCase):
"""Test conversion of numpy type parameters."""
def test_diag(self):
"""Verify diagonal gate converts numpy.complex to complex."""
# ref: https://github.com/Qiskit/qiskit-aer/issues/696
diag = np.array([1 + 0j, 1 + 0j])
qc = QuantumCircuit(1)
qc.diagonal(list(diag), [0])
params = qc.data[0].operation.params
self.assertTrue(
all(isinstance(p, complex) and not isinstance(p, np.number) for p in params)
)
qobj = assemble(qc)
params = qobj.experiments[0].instructions[0].params
self.assertTrue(
all(isinstance(p, complex) and not isinstance(p, np.number) for p in params)
)
def test_init(self):
"""Verify initialize gate converts numpy.complex to complex."""
# ref: https://github.com/Qiskit/qiskit-terra/issues/4151
qc = QuantumCircuit(1)
vec = np.array([0, 0 + 1j])
qc.initialize(vec, 0)
params = qc.data[0].operation.params
self.assertTrue(
all(isinstance(p, complex) and not isinstance(p, np.number) for p in params)
)
qobj = assemble(qc)
params = qobj.experiments[0].instructions[0].params
self.assertTrue(
all(isinstance(p, complex) and not isinstance(p, np.number) for p in params)
)
if __name__ == "__main__":
unittest.main()
|
https://github.com/acfilok96/Quantum-Computation
|
acfilok96
|
import qiskit
from qiskit import *
print(qiskit.__version__)
%matplotlib inline
from qiskit.tools.visualization import plot_histogram
secret_number = '101001'
# here work is happen like buttom to up
for position,value in enumerate(reversed(secret_number)):
if value == '1':
print(position, value)
circuit = QuantumCircuit(6+1, 6)
circuit.h([0,1,2,3,4,5])
circuit.x(6)
circuit.h(6)
circuit.barrier()
circuit.draw(output='mpl')
circuit.cx(5, 6)
circuit.cx(3, 6)
circuit.cx(0, 6)
circuit.barrier()
circuit.draw(output='mpl')
circuit.h([0,1,2,3,4,5])
circuit.draw(output='mpl')
circuit.barrier()
circuit.measure([i for i in range(5)],[i for i in range(5)])
circuit.barrier()
circuit.draw(output='mpl')
simulator = Aer.get_backend('qasm_simulator')
job = execute(circuit, backend=simulator, shots=1)
result = job.result()
counts = result.get_counts()
print(counts)
circuit = QuantumCircuit(len(secret_number)+1, len(secret_number))
circuit.h(range(len(secret_number)))
circuit.x(len(secret_number))
circuit.h(len(secret_number))
circuit.barrier()
for position,value in enumerate(reversed(secret_number)):
if value == '1':
circuit.cx(position, len(secret_number))
circuit.barrier()
circuit.h(range(len(secret_number)))
circuit.barrier()
circuit.measure(range(len(secret_number)), range(len(secret_number)))
circuit.barrier()
circuit.draw(output='mpl')
simulator = Aer.get_backend('qasm_simulator')
job = execute(circuit, backend=simulator, shots=1)
result = job.result()
counts = result.get_counts()
print(counts)
def find_secret_number(secter_number):
secret_number = str(secter_number)
# Using Bernstein Vazirani Algorithm
circuit = QuantumCircuit(len(secret_number)+1, len(secret_number))
circuit.h(range(len(secret_number)))
circuit.x(len(secret_number))
circuit.h(len(secret_number))
circuit.barrier()
for position,value in enumerate(reversed(secret_number)):
if value == '1':
circuit.cx(position, len(secret_number))
circuit.barrier()
circuit.h(range(len(secret_number)))
circuit.barrier()
circuit.measure(range(len(secret_number)), range(len(secret_number)))
circuit.barrier()
circuit.draw(output='mpl')
simulator = Aer.get_backend('qasm_simulator')
job = execute(circuit, backend=simulator, shots=1)
result = job.result()
counts = result.get_counts()
print(counts)
secret_number = int(input("enter number(digits should be 0 or 1): "))
find_secret_number(secret_number)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit.circuit.random import random_circuit
circuit = random_circuit(2, 2, seed=0, measure=True).decompose(reps=1)
display(circuit.draw("mpl"))
from qiskit.primitives import Sampler
sampler = Sampler()
job = sampler.run(circuit)
print(f">>> Job ID: {job.job_id()}")
print(f">>> Job Status: {job.status()}")
result = job.result()
print(f">>> {result}")
print(f" > Quasi-distribution: {result.quasi_dists[0]}")
circuit = random_circuit(2, 2, seed=1, measure=True).decompose(reps=1)
job = sampler.run(circuit)
result = job.result()
display(circuit.draw("mpl"))
print(f">>> Quasi-distribution: {result.quasi_dists[0]}")
circuits = (
random_circuit(2, 2, seed=0, measure=True).decompose(reps=1),
random_circuit(2, 2, seed=1, measure=True).decompose(reps=1),
)
job = sampler.run(circuits)
result = job.result()
[display(cir.draw("mpl")) for cir in circuits]
print(f">>> Quasi-distribution: {result.quasi_dists}")
from qiskit.circuit.library import RealAmplitudes
circuit = RealAmplitudes(num_qubits=2, reps=2).decompose(reps=1)
circuit.measure_all()
parameter_values = [0, 1, 2, 3, 4, 5]
job = sampler.run(circuit, parameter_values)
result = job.result()
display(circuit.draw("mpl"))
print(f">>> Parameter values: {parameter_values}")
print(f">>> Quasi-distribution: {result.quasi_dists[0]}")
from qiskit_ibm_runtime import QiskitRuntimeService
service = QiskitRuntimeService(channel="ibm_quantum")
backend = service.backend("ibmq_qasm_simulator")
from qiskit.circuit.random import random_circuit
circuit = random_circuit(2, 2, seed=0, measure=True).decompose(reps=1)
display(circuit.draw("mpl"))
from qiskit_ibm_runtime import Sampler
sampler = Sampler(session=backend)
job = sampler.run(circuit)
print(f">>> Job ID: {job.job_id()}")
print(f">>> Job Status: {job.status()}")
result = job.result()
print(f">>> {result}")
print(f" > Quasi-distribution: {result.quasi_dists[0]}")
print(f" > Metadata: {result.metadata[0]}")
from qiskit_ibm_runtime import Options
options = Options(optimization_level=3, environment={"log_level": "INFO"})
from qiskit_ibm_runtime import Options
options = Options()
options.resilience_level = 1
options.execution.shots = 2048
sampler = Sampler(session=backend, options=options)
result = sampler.run(circuit).result()
print(f">>> Metadata: {result.metadata[0]}")
sampler = Sampler(session=backend, options=options)
result = sampler.run(circuit, shots=1024).result()
print(f">>> Metadata: {result.metadata[0]}")
from qiskit_ibm_runtime import Options
# optimization_level=3 adds dynamical decoupling
# resilience_level=1 adds readout error mitigation
options = Options(optimization_level=3, resilience_level=1)
sampler = Sampler(session=backend, options=options)
result = sampler.run(circuit).result()
print(f">>> Quasi-distribution: {result.quasi_dists[0]}")
print(f">>> Metadata: {result.metadata[0]}")
from qiskit_ibm_runtime import Session, Estimator
with Session(backend=backend, max_time="1h"):
sampler = Sampler()
result = sampler.run(circuit).result()
print(f">>> Quasi-distribution from the first run: {result.quasi_dists[0]}")
result = sampler.run(circuit).result()
print(f">>> Quasi-distribution from the second run: {result.quasi_dists[0]}")
from qiskit.circuit.random import random_circuit
from qiskit.quantum_info import SparsePauliOp
estimator_circuit = random_circuit(2, 2, seed=0).decompose(reps=1)
display(estimator_circuit.draw("mpl"))
observable = SparsePauliOp("XZ")
print(f">>> Observable: {observable.paulis}")
from qiskit_ibm_runtime import Session, Sampler, Estimator
with Session(backend=backend):
sampler = Sampler()
estimator = Estimator()
result = sampler.run(circuit).result()
print(f">>> Quasi Distribution from the sampler job: {result.quasi_dists[0]}")
result = estimator.run(estimator_circuit, observable).result()
print(f">>> Expectation value from the estimator job: {result.values[0]}")
from qiskit_ibm_runtime import Session, Sampler, Estimator
with Session(backend=backend):
sampler = Sampler()
estimator = Estimator()
sampler_job = sampler.run(circuit)
estimator_job = estimator.run(estimator_circuit, observable)
print(f">>> Quasi Distribution from the sampler job: {sampler_job.result().quasi_dists[0]}")
print(f">>> Expectation value from the estimator job: {estimator_job.result().values[0]}")
from qiskit_ibm_runtime import QiskitRuntimeService, Session, Sampler, Estimator, Options
# 1. Initialize account
service = QiskitRuntimeService(channel="ibm_quantum")
# 2. Specify options, such as enabling error mitigation
options = Options(resilience_level=1)
# 3. Select a backend.
backend = service.backend("ibmq_qasm_simulator")
# 4. Create a session
with Session(backend=backend):
# 5. Create primitive instances
sampler = Sampler(options=options)
estimator = Estimator(options=options)
# 6. Submit jobs
sampler_job = sampler.run(circuit)
estimator_job = estimator.run(estimator_circuit, observable)
# 7. Get results
print(f">>> Quasi Distribution from the sampler job: {sampler_job.result().quasi_dists[0]}")
print(f">>> Expectation value from the estimator job: {estimator_job.result().values[0]}")
import qiskit_ibm_runtime
qiskit_ibm_runtime.version.get_version_info()
from qiskit.tools.jupyter import *
%qiskit_version_table
%qiskit_copyright
|
https://github.com/aryashah2k/Quantum-Computing-Collection-Of-Resources
|
aryashah2k
|
from qiskit import QuantumCircuit
# remark the coincise representation of a quantum circuit
qc = QuantumCircuit(2)
qc.h(0)
qc.h(1)
qc.draw(output='mpl',reverse_bits=True)
from qiskit import execute, Aer
job = execute(qc, Aer.get_backend('unitary_simulator'),shots=1,optimization_level=0)
current_unitary = job.result().get_unitary(qc, decimals=3)
for row in current_unitary:
column = ""
for entry in row:
column = column + str(entry.real) + " "
print(column)
from qiskit import QuantumCircuit
qc = QuantumCircuit(2)
qc.h(1)
qc.draw(output='mpl',reverse_bits=True)
from qiskit import execute, Aer
#
# your code is here
#
from qiskit import QuantumCircuit
qc = QuantumCircuit(2)
qc.h(1)
display(qc.draw(output='mpl',reverse_bits=True))
from qiskit import execute, Aer
job = execute(qc, Aer.get_backend('unitary_simulator'),shots=1,optimization_level=0)
current_unitary = job.result().get_unitary(qc, decimals=3)
for row in current_unitary:
column = ""
for entry in row:
column = column + str(round(entry.real,3)) + " "
print(column)
pairs = ['00','01','10','11']
for pair in pairs:
from qiskit import QuantumCircuit, execute, Aer
qc = QuantumCircuit(2,2)
# initialize the pair
# we follow the reading order in Qiskit
# q1-tensor-q0
if pair[1] == '1':
qc.x(0)
if pair[0] =='1':
qc.x(1)
qc.cx(1,0)
qc.measure(0,0)
qc.measure(1,1)
display(qc.draw(output='mpl',reverse_bits=True))
job = execute(qc,Aer.get_backend('qasm_simulator'),shots=1024)
counts = job.result().get_counts(qc)
print(pair,"--CNOT->",counts)
# import all necessary objects and methods for quantum circuits
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
# import randrange for random choices
from random import randrange
#
# your code is here
#
# import all necessary objects and methods for quantum circuits
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
# import randrange for random choices
from random import randrange
n = 5
m = 4
states_of_qubits = [] # we trace the state of each qubit also by ourselves
q = QuantumRegister(n,"q") # quantum register with n qubits
c = ClassicalRegister(n,"c") # classical register with n bits
qc = QuantumCircuit(q,c) # quantum circuit with quantum and classical registers
# set each qubit to |1>
for i in range(n):
qc.x(q[i]) # apply x-gate (NOT operator)
states_of_qubits.append(1) # the state of each qubit is set to 1
# randomly pick m pairs of qubits
for i in range(m):
controller_qubit = randrange(n)
target_qubit = randrange(n)
# controller and target qubits should be different
while controller_qubit == target_qubit: # if they are the same, we pick the target_qubit again
target_qubit = randrange(n)
# print our picked qubits
print("the indices of the controller and target qubits are",controller_qubit,target_qubit)
# apply cx-gate (CNOT operator)
qc.cx(q[controller_qubit],q[target_qubit])
# we also trace the results
if states_of_qubits[controller_qubit] == 1: # if the value of the controller qubit is 1,
states_of_qubits[target_qubit] = 1 - states_of_qubits[target_qubit] # then flips the value of the target qubit
# remark that 1-x gives the negation of x
# measure the quantum register
qc.barrier()
qc.measure(q,c)
# draw the circuit in reading order
display(qc.draw(output='mpl',reverse_bits=True))
# execute the circuit 100 times in the local simulator
job = execute(qc,Aer.get_backend('qasm_simulator'),shots=100)
counts = job.result().get_counts(qc)
print("the measurument result is",counts)
our_result=""
for state in states_of_qubits:
our_result = str(state) + our_result
print("our result is",our_result)
# import all necessary objects and methods for quantum circuits
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
#
# your code is here
#
# import all necessary objects and methods for quantum circuits
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
all_inputs=['00','01','10','11']
for input in all_inputs:
q = QuantumRegister(2,"q") # quantum register with 2 qubits
c = ClassicalRegister(2,"c") # classical register with 2 bits
qc = QuantumCircuit(q,c) # quantum circuit with quantum and classical registers
# initialize the inputs w.r.t the reading order of Qiskit
if input[0]=='1':
qc.x(q[1]) # set the state of the up qubit to |1>
if input[1]=='1':
qc.x(q[0]) # set the state of the down qubit to |1>
# apply h-gate to both qubits
qc.h(q[0])
qc.h(q[1])
# apply cx(up-qubit,down-qubit)
qc.cx(q[1],q[0])
# apply h-gate to both qubits
qc.h(q[0])
qc.h(q[1])
# measure both qubits
qc.barrier()
qc.measure(q,c)
# draw the circuit w.r.t the reading order of Qiskit
display(qc.draw(output='mpl',reverse_bits=True))
# execute the circuit 100 times in the local simulator
job = execute(qc,Aer.get_backend('qasm_simulator'),shots=100)
counts = job.result().get_counts(qc)
print(input,"is mapped to",counts)
# import all necessary objects and methods for quantum circuits
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
#
# your code is here
#
# import all necessary objects and methods for quantum circuits
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, execute, Aer
all_inputs=['00','01','10','11']
for input in all_inputs:
q = QuantumRegister(2,"q") # quantum register with 2 qubits
c = ClassicalRegister(2,"c") # classical register with 2 bits
qc = QuantumCircuit(q,c) # quantum circuit with quantum and classical registers
#initialize the inputs w.r.t the reading order of Qiskit
if input[0]=='1':
qc.x(q[1]) # set the state of the up qubit to |1>
if input[1]=='1':
qc.x(q[0]) # set the state of the down qubit to |1>
# apply cx(up-qubit,down-qubit)
qc.cx(q[1],q[0])
# apply cx(down-qubit,up-qubit)
qc.cx(q[0],q[1])
# apply cx(up-qubit,down-qubit)
qc.cx(q[1],q[0])
# measure both qubits
qc.barrier()
qc.measure(q,c)
# draw the circuit w.r.t the reading order of Qiskit
display(qc.draw(output='mpl',reverse_bits=True))
# execute the circuit 100 times in the local simulator
job = execute(qc,Aer.get_backend('qasm_simulator'),shots=100)
counts = job.result().get_counts(qc)
print(input,"is mapped to",counts)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, execute
from qiskit.providers.fake_provider import FakeVigoV2
from qiskit.visualization import plot_gate_map
backend = FakeVigoV2()
plot_gate_map(backend)
|
https://github.com/indian-institute-of-science-qc/qiskit-aakash
|
indian-institute-of-science-qc
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2018.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test the Unroll3qOrMore pass"""
import numpy as np
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.circuit import Qubit, Clbit
from qiskit.circuit.library import CCXGate, RCCXGate
from qiskit.transpiler.passes import Unroll3qOrMore
from qiskit.converters import circuit_to_dag, dag_to_circuit
from qiskit.quantum_info.operators import Operator
from qiskit.quantum_info.random import random_unitary
from qiskit.test import QiskitTestCase
from qiskit.extensions import UnitaryGate
from qiskit.transpiler import Target
class TestUnroll3qOrMore(QiskitTestCase):
"""Tests the Unroll3qOrMore pass, for unrolling all
gates until reaching only 1q or 2q gates."""
def test_ccx(self):
"""Test decompose CCX."""
qr1 = QuantumRegister(2, "qr1")
qr2 = QuantumRegister(1, "qr2")
circuit = QuantumCircuit(qr1, qr2)
circuit.ccx(qr1[0], qr1[1], qr2[0])
dag = circuit_to_dag(circuit)
pass_ = Unroll3qOrMore()
after_dag = pass_.run(dag)
op_nodes = after_dag.op_nodes()
self.assertEqual(len(op_nodes), 15)
for node in op_nodes:
self.assertIn(node.name, ["h", "t", "tdg", "cx"])
def test_cswap(self):
"""Test decompose CSwap (recursively)."""
qr1 = QuantumRegister(2, "qr1")
qr2 = QuantumRegister(1, "qr2")
circuit = QuantumCircuit(qr1, qr2)
circuit.cswap(qr1[0], qr1[1], qr2[0])
dag = circuit_to_dag(circuit)
pass_ = Unroll3qOrMore()
after_dag = pass_.run(dag)
op_nodes = after_dag.op_nodes()
self.assertEqual(len(op_nodes), 17)
for node in op_nodes:
self.assertIn(node.name, ["h", "t", "tdg", "cx"])
def test_decompose_conditional(self):
"""Test decompose a 3-qubit gate with a conditional."""
qr = QuantumRegister(3, "qr")
cr = ClassicalRegister(1, "cr")
circuit = QuantumCircuit(qr, cr)
circuit.ccx(qr[0], qr[1], qr[2]).c_if(cr, 0)
dag = circuit_to_dag(circuit)
pass_ = Unroll3qOrMore()
after_dag = pass_.run(dag)
op_nodes = after_dag.op_nodes()
self.assertEqual(len(op_nodes), 15)
for node in op_nodes:
self.assertIn(node.name, ["h", "t", "tdg", "cx"])
self.assertEqual(node.op.condition, (cr, 0))
def test_decompose_unitary(self):
"""Test unrolling of unitary gate over 4qubits."""
qr = QuantumRegister(4, "qr")
circuit = QuantumCircuit(qr)
unitary = random_unitary(16, seed=42)
circuit.unitary(unitary, [0, 1, 2, 3])
dag = circuit_to_dag(circuit)
pass_ = Unroll3qOrMore()
after_dag = pass_.run(dag)
after_circ = dag_to_circuit(after_dag)
self.assertTrue(Operator(circuit).equiv(Operator(after_circ)))
def test_identity(self):
"""Test unrolling of identity gate over 3qubits."""
qr = QuantumRegister(3, "qr")
circuit = QuantumCircuit(qr)
gate = UnitaryGate(np.eye(2**3))
circuit.append(gate, range(3))
dag = circuit_to_dag(circuit)
pass_ = Unroll3qOrMore()
after_dag = pass_.run(dag)
after_circ = dag_to_circuit(after_dag)
self.assertTrue(Operator(circuit).equiv(Operator(after_circ)))
def test_target(self):
"""Test target is respected by the unroll 3q or more pass."""
target = Target(num_qubits=3)
target.add_instruction(CCXGate())
qc = QuantumCircuit(3)
qc.ccx(0, 1, 2)
qc.append(RCCXGate(), [0, 1, 2])
unroll_pass = Unroll3qOrMore(target=target)
res = unroll_pass(qc)
self.assertIn("ccx", res.count_ops())
self.assertNotIn("rccx", res.count_ops())
def test_basis_gates(self):
"""Test basis_gates are respected by the unroll 3q or more pass."""
basis_gates = ["rccx"]
qc = QuantumCircuit(3)
qc.ccx(0, 1, 2)
qc.append(RCCXGate(), [0, 1, 2])
unroll_pass = Unroll3qOrMore(basis_gates=basis_gates)
res = unroll_pass(qc)
self.assertNotIn("ccx", res.count_ops())
self.assertIn("rccx", res.count_ops())
def test_target_over_basis_gates(self):
"""Test target is respected over basis_gates by the unroll 3q or more pass."""
target = Target(num_qubits=3)
basis_gates = ["rccx"]
target.add_instruction(CCXGate())
qc = QuantumCircuit(3)
qc.ccx(0, 1, 2)
qc.append(RCCXGate(), [0, 1, 2])
unroll_pass = Unroll3qOrMore(target=target, basis_gates=basis_gates)
res = unroll_pass(qc)
self.assertIn("ccx", res.count_ops())
self.assertNotIn("rccx", res.count_ops())
def test_if_else(self):
"""Test that a simple if-else over 3+ qubits unrolls correctly."""
pass_ = Unroll3qOrMore(basis_gates=["u", "cx"])
true_body = QuantumCircuit(3, 1)
true_body.h(0)
true_body.ccx(0, 1, 2)
false_body = QuantumCircuit(3, 1)
false_body.rccx(2, 1, 0)
test = QuantumCircuit(3, 1)
test.h(0)
test.measure(0, 0)
test.if_else((0, True), true_body, false_body, [0, 1, 2], [0])
expected = QuantumCircuit(3, 1)
expected.h(0)
expected.measure(0, 0)
expected.if_else((0, True), pass_(true_body), pass_(false_body), [0, 1, 2], [0])
self.assertEqual(pass_(test), expected)
def test_nested_control_flow(self):
"""Test that the unroller recurses into nested control flow."""
pass_ = Unroll3qOrMore(basis_gates=["u", "cx"])
qubits = [Qubit() for _ in [None] * 3]
clbit = Clbit()
for_body = QuantumCircuit(qubits, [clbit])
for_body.ccx(0, 1, 2)
while_body = QuantumCircuit(qubits, [clbit])
while_body.rccx(0, 1, 2)
true_body = QuantumCircuit(qubits, [clbit])
true_body.while_loop((clbit, True), while_body, [0, 1, 2], [0])
test = QuantumCircuit(qubits, [clbit])
test.for_loop(range(2), None, for_body, [0, 1, 2], [0])
test.if_else((clbit, True), true_body, None, [0, 1, 2], [0])
expected_if_body = QuantumCircuit(qubits, [clbit])
expected_if_body.while_loop((clbit, True), pass_(while_body), [0, 1, 2], [0])
expected = QuantumCircuit(qubits, [clbit])
expected.for_loop(range(2), None, pass_(for_body), [0, 1, 2], [0])
expected.if_else(range(2), pass_(expected_if_body), None, [0, 1, 2], [0])
self.assertEqual(pass_(test), expected)
def test_if_else_in_basis(self):
"""Test that a simple if-else over 3+ qubits unrolls correctly."""
pass_ = Unroll3qOrMore(basis_gates=["u", "cx", "if_else", "for_loop", "while_loop"])
true_body = QuantumCircuit(3, 1)
true_body.h(0)
true_body.ccx(0, 1, 2)
false_body = QuantumCircuit(3, 1)
false_body.rccx(2, 1, 0)
test = QuantumCircuit(3, 1)
test.h(0)
test.measure(0, 0)
test.if_else((0, True), true_body, false_body, [0, 1, 2], [0])
expected = QuantumCircuit(3, 1)
expected.h(0)
expected.measure(0, 0)
expected.if_else((0, True), pass_(true_body), pass_(false_body), [0, 1, 2], [0])
self.assertEqual(pass_(test), expected)
def test_nested_control_flow_in_basis(self):
"""Test that the unroller recurses into nested control flow."""
pass_ = Unroll3qOrMore(basis_gates=["u", "cx", "if_else", "for_loop", "while_loop"])
qubits = [Qubit() for _ in [None] * 3]
clbit = Clbit()
for_body = QuantumCircuit(qubits, [clbit])
for_body.ccx(0, 1, 2)
while_body = QuantumCircuit(qubits, [clbit])
while_body.rccx(0, 1, 2)
true_body = QuantumCircuit(qubits, [clbit])
true_body.while_loop((clbit, True), while_body, [0, 1, 2], [0])
test = QuantumCircuit(qubits, [clbit])
test.for_loop(range(2), None, for_body, [0, 1, 2], [0])
test.if_else((clbit, True), true_body, None, [0, 1, 2], [0])
expected_if_body = QuantumCircuit(qubits, [clbit])
expected_if_body.while_loop((clbit, True), pass_(while_body), [0, 1, 2], [0])
expected = QuantumCircuit(qubits, [clbit])
expected.for_loop(range(2), None, pass_(for_body), [0, 1, 2], [0])
expected.if_else(range(2), pass_(expected_if_body), None, [0, 1, 2], [0])
self.assertEqual(pass_(test), expected)
def test_custom_block_over_3q(self):
"""Test a custom instruction is unrolled in a control flow block."""
pass_ = Unroll3qOrMore(basis_gates=["u", "cx", "if_else", "for_loop", "while_loop"])
ghz = QuantumCircuit(5, 5)
ghz.h(0)
ghz.cx(0, 1)
ghz.cx(0, 2)
ghz.cx(0, 3)
ghz.cx(0, 4)
ghz.measure(0, 0)
ghz.measure(1, 1)
ghz.measure(2, 2)
ghz.measure(3, 3)
ghz.measure(4, 4)
ghz.reset(0)
ghz.reset(1)
ghz.reset(2)
ghz.reset(3)
ghz.reset(4)
for_block = QuantumCircuit(5, 5, name="ghz")
for_block.append(ghz, list(range(5)), list(range(5)))
qc = QuantumCircuit(5, 5)
qc.for_loop((1,), None, for_block, [2, 4, 1, 3, 0], [0, 1, 2, 3, 4])
result = pass_(qc)
expected = QuantumCircuit(5, 5)
expected.for_loop((1,), None, ghz, [2, 4, 1, 3, 0], [0, 1, 2, 3, 4])
self.assertEqual(result, expected)
|
https://github.com/QuCO-CSAM/Solving-Combinatorial-Optimisation-Problems-Using-Quantum-Algorithms
|
QuCO-CSAM
|
import numpy as np
from itertools import permutations
import gzip
from qiskit import*
import time
from qiskit.aqua.algorithms import VQE
from qiskit.aqua.algorithms import QAOA
from qiskit.aqua.components.optimizers import SPSA
# from qiskit.aqua.components.variational_forms import RY
from qiskit.aqua import QuantumInstance
from qiskit.aqua.components.optimizers import COBYLA
from qiskit import IBMQ
from qiskit import ClassicalRegister, QuantumRegister, QuantumCircuit
from qiskit.optimization.applications.ising.tsp import TspData
import qiskit.optimization.applications.ising.tsp as tsp
from qiskit.circuit.library import TwoLocal
from qiskit.circuit.library import RealAmplitudes
# # from qiskit import IBMQ
# # # Load account from disk
IBMQ.load_account()
IBMQ.providers()
def readInData():
"""
Output G : N by N distance matrix from Matrices1a.txt file.
"""
G = []
p = [3,4,5,6,7,8,9,10,11]
q = [i**(2) for i in p ]
m = 0
v = open("Matrices.txt" , "r")
w = v.read().split()
for i in range (len(w)):
w[i] = int(float(w[i]))
for i in range (len(q)):
G.append(np.reshape(w[m:m+q[i]] , (p[i] , p[i])))
m = m + q[i]
return G
distanceMatrix = readInData() #Array of different sized matrices
def determineIfFeasible(result):
"""
Determines if eigenstate is feasible or infeasible.
Output: arr = Infeasible if eiegenstate is infeasible or arr = binary array of feasible solution
"""
data = sorted(result['eigenstate'].items(), key=lambda item: item[1])[::-1]
for i in range(len(data)):
a = tsp.tsp_feasible(data[i][0])
arr = 'Infeasible'
if a == True:
b = str(data[i][0])
arr = [b , data[i][1]]
break
return arr
def optimal(a,b,c,f,u):
"""
Read in data of initial optimal point that will be used in the quantum algorithm
"""
openfile = open("optimal.txt" , "r")
readFile = openfile.read().split()
t = []
for i in readFile:
if i != ',':
q = len(i)
t.append(float(i[0:q-1]))
v, r, o, d, z = np.array(t[0:a]), np.array(t[a:a+b]), np.array(t[a+b : a+b+c]), np.array(t[a+b+c:a+b+c+f]), np.array(t[a+b+c+f:a+b+c+f+u])
return [v,r,o,d,z]
R = optimal(54,96,100,216,294) #Array of corresponding initial points
def quantumApproximateOptimizationAlgorithm(numIter, numShots, distanceMatrix,pValue, deviceName, initialPoint):
"""
Implementation of the QAOA
Output: classial TSP solution (total length of tour), time taken to execute algorithm
"""
# Map problem to isining hamiltonian
x = TspData('tmp',len(distanceMatrix),np.zeros((3,3)),distanceMatrix)
qubitOp = tsp.get_operator(x)
seed = 10598
spsa = SPSA(maxiter = numIter)
qaoa = QAOA(qubitOp, spsa, pValue, include_custom = False, initialPoint = initialPoint)
my_provider = IBMQ.get_provider(ibm_hub) #Replace ibm_hub with appropriate qiskit hub name
device = my_provider.get_backend(deviceName) # deviceName is the Device of IBM qunatum device in a string
quantum_instance = QuantumInstance(device, seed_simulator=seed, seed_transpiler=seed,shots = numShots,
skip_qobj_validation = False)
#Convert quantum result into its classical form and determine if feasible or infeasible
result = qaoa.run(quantum_instance)
answer = determineIfFeasible(result)
if answer == 'Infeasible':
solution = -1
else:
binarry = [int(p) for p in answer[0]]
route = tsp.get_tsp_solution(binarry)
solution = tsp.tsp_value(route,distanceMatrix)
return solution, result['optimizer_time']
## Example for 3 by 3 instance implemented using QAOA:
numIter = 1
numShots = 8192
distanceMatrix = distanceMatrix[0]
pValue = 3
deviceName = 'ibmq_manhattan'
initialPoint = R[0]
finalResult quantumApproximateOptimizationAlgorithm(numIter, numShots, distanceMatrix, pValue, deviceName, initialPoint)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, transpile
from qiskit.visualization import plot_circuit_layout
from qiskit.providers.fake_provider import FakeVigo
backend = FakeVigo()
ghz = QuantumCircuit(3, 3)
ghz.h(0)
ghz.cx(0,range(1,3))
ghz.barrier()
ghz.measure(range(3), range(3))
new_circ_lv0 = transpile(ghz, backend=backend, optimization_level=0)
plot_circuit_layout(new_circ_lv0, backend)
|
https://github.com/dimple12M/Qiskit-Certification-Guide
|
dimple12M
|
from qiskit import QuantumCircuit
from qiskit.visualization import visualize_transition,circuit_drawer
from math import pi
qc=QuantumCircuit(2)
qc.h(0)
qc.cx(0,1)
qc.draw(output="mpl")
qc=QuantumCircuit(2)
qc.h(0)
qc.cx(0,1)
circuit_drawer(qc,output="mpl")
qc=QuantumCircuit(1)
qc.h(0)
qc.draw(output="mpl")
visualize_transition(qc)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import numpy as np
from qiskit import QuantumCircuit
from qiskit.providers.fake_provider import FakeVigoV2
backend = FakeVigoV2()
qc = QuantumCircuit(2, 1)
qc.h(0)
qc.x(1)
qc.cp(np.pi/4, 0, 1)
qc.h(0)
qc.measure([0], [0])
qc.draw(output='mpl')
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import 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/DaisukeIto-ynu/KosakaQ_client
|
DaisukeIto-ynu
|
"""
Test Script
"""
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
qrx = QuantumRegister(1, 'q0')
qry = QuantumRegister(1, 'q1')
cr = ClassicalRegister(1, 'c')
qc = QuantumCircuit(qrx, qry, cr)
qc.h(qrx)
qc.x(qry)
qc.h(qry)
qc.barrier()
qc.x(qry)
qc.barrier()
qc.h(qrx)
qc.h(qry)
qc.measure(qrx, cr)
qc.draw("mpl")
from qiskit import execute
from qiskit.providers.aer import AerSimulator
from qiskit.visualization import plot_histogram
sim = AerSimulator()
job = execute(qc, backend = sim, shots = 1000)
result = job.result()
counts = result.get_counts(qc)
print("Counts: ", counts)
plot_histogram(counts)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, execute
from qiskit.providers.fake_provider import FakeVigoV2
from qiskit.visualization import plot_gate_map
backend = FakeVigoV2()
plot_gate_map(backend)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import pulse
dc = pulse.DriveChannel
d0, d1, d2, d3, d4 = dc(0), dc(1), dc(2), dc(3), dc(4)
with pulse.build(name='pulse_programming_in') as pulse_prog:
pulse.play([1, 1, 1, 0, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1], d0)
pulse.play([1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0], d1)
pulse.play([1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0], d2)
pulse.play([1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0], d3)
pulse.play([1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 0, 1, 0], d4)
pulse_prog.draw()
|
https://github.com/PabloMartinezAngerosa/QAOA-uniform-convergence
|
PabloMartinezAngerosa
|
from tsp_qaoa import test_solution
from qiskit.visualization import plot_histogram
import networkx as nx
import numpy as np
job_2, G, UNIFORM_CONVERGENCE_SAMPLE = test_solution()
plot_histogram(job_2.result().get_counts(), color='midnightblue', title="New Histogram", figsize=(30, 5))
plot_histogram(job_2.result().get_counts(), color='midnightblue', title="New Histogram", figsize=(30, 5))
G
labels = nx.get_edge_attributes(G,'weight')
labels
import json
# Array of JSON Objects
products = [{"name": "HDD", "brand": "Samsung", "price": "$100"},
{"name": "Monitor", "brand": "Dell", "price": "$120"},
{"name": "Mouse", "brand": "Logitech", "price": "$10"}]
# Print the original data
print("The original JSON data:\n{0}".format(products))
# Sort the JSON data based on the value of the brand key
products.sort(key=lambda x: x["price"])
# Print the sorted JSON data
print("The sorted JSON data based on the value of the brand:\n{0}".format(products))
_LAMBDA
UNIFORM_CONVERGENCE_SAMPLE
import json
# Array of JSON Objects
# Sort the JSON data based on the value of the brand key
UNIFORM_CONVERGENCE_SAMPLE.sort(key=lambda x: x["mean"])
# Print the sorted JSON data
UNIFORM_CONVERGENCE_SAMPLE
np.max(UNIFORM_CONVERGENCE_SAMPLE[0]["probabilities"] - UNIFORM_CONVERGENCE_SAMPLE[220]["probabilities"])
# generamos las distancias entre para la convergencia uniforme
index = -1
for sample in UNIFORM_CONVERGENCE_SAMPLE:
mean = sample["mean"]
index += 1
distance_p_ground_state = np.max(np.abs(UNIFORM_CONVERGENCE_SAMPLE[0]["probabilities"] - sample["probabilities"]))
UNIFORM_CONVERGENCE_SAMPLE[index]["distance_pgs"] = distance_p_ground_state
UNIFORM_CONVERGENCE_SAMPLE
import csv
header = ['iteration', 'state', 'probability', 'mean']
header_q = ['iteration', 'distance']
with open('qaoa_cu.csv', 'w', encoding='UTF8') as f:
with open('qaoa_distance.csv', 'w', encoding='UTF8') as q:
writer = csv.writer(f)
writer_q = csv.writer(q)
# write the header
writer.writerow(header)
writer_q.writerow(header_q)
iteration = 0
for sample in UNIFORM_CONVERGENCE_SAMPLE:
iteration += 1
mean = sample["mean"]
distance = sample["distance_pgs"]
state = 0
for probability in sample["probabilities"]:
state += 1
# write the data
data = [iteration, state, probability, mean]
writer.writerow(data)
writer_q.writerow([iteration, distance])
#plot_histogram(job_2, color='midnightblue', title=str(mean), figsize=(30, 5)).savefig(str(contador) + "_2.png")
#print(sample["mean"])
plot_histogram(job_2, color='midnightblue', title="New Histogram", figsize=(30, 5)).savefig('out.png')
|
https://github.com/urwin419/QiskitChecker
|
urwin419
|
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":
### added x gate ###
qc.x(qubit)
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/martynscn/Masters-Thesis-on-Quantum-Cryptography
|
martynscn
|
# This code has been adapted and modified from IBM Qiskit 2021 and also from https://github.com/ttlion/ShorAlgQiskit.
# It uses the implementation as contained in the work of Stephane Beauregard (https://arxiv.org/abs/quant-ph/0205095)
# Many thanks to IBM Qiskit team, Tiago Miguel (ttlion), Qubit by Qubit, Peter Shor and Stephane Beauregard.
from typing import Optional, Union, Tuple, List
import math
import array
import fractions
import logging
import numpy as np
from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister, execute, IBMQ, transpile,BasicAer, Aer, assemble
from qiskit.circuit import Gate, Instruction, ParameterVector
from qiskit.circuit.library import QFT
from qiskit.providers import BaseBackend, Backend
from qiskit.quantum_info import partial_trace
from qiskit.utils import summarize_circuits
from qiskit.utils.arithmetic import is_power
from qiskit.utils.validation import validate_min
from qiskit.utils.quantum_instance import QuantumInstance
import qiskit.visualization
from qiskit.providers.aer import QasmSimulator
from datetime import datetime
import csv
# provider = IBMQ.enable_account("PUT TOKEN HERE")
backend = QasmSimulator()
from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all" #"last_expr" or "all"
# """ Function to check if N is of type q^p"""
def check_if_power(N):
# """ Check if N is a perfect power in O(n^3) time, n=ceil(logN) """
b=2
while (2**b) <= N:
a = 1
c = N
while (c-a) >= 2:
m = int( (a+c)/2 )
if (m**b) < (N+1):
p = int( (m**b) )
else:
p = int(N+1)
if int(p) == int(N):
print('N is {0}^{1}'.format(int(m),int(b)) )
return True
if p<N:
a = int(m)
else:
c = int(m)
b=b+1
return False
def egcd(a, b):
if a == 0:
return (b, 0, 1)
else:
g, y, x = egcd(b % a, a)
return (g, x - (b // a) * y, y)
def modinv(a, m):
g, x, y = egcd(a, m)
if g != 1:
raise Exception('modular inverse does not exist')
else:
return x % m
def create_QFT(circuit,up_reg,n,with_swaps):
i=n-1
while i>=0:
circuit.h(up_reg[i])
j=i-1
while j>=0:
if (np.pi)/(pow(2,(i-j))) > 0:
circuit.cu1( (np.pi)/(pow(2,(i-j))) , up_reg[i] , up_reg[j] )
j=j-1
i=i-1
if with_swaps==1:
i=0
while i < ((n-1)/2):
circuit.swap(up_reg[i], up_reg[n-1-i])
i=i+1
def create_inverse_QFT(circuit,up_reg,n,with_swaps):
if with_swaps==1:
i=0
while i < ((n-1)/2):
circuit.swap(up_reg[i], up_reg[n-1-i])
i=i+1
i=0
while i<n:
circuit.h(up_reg[i])
if i != n-1:
j=i+1
y=i
while y>=0:
if (np.pi)/(pow(2,(j-y))) > 0:
circuit.cu1( - (np.pi)/(pow(2,(j-y))) , up_reg[j] , up_reg[y] )
y=y-1
i=i+1
def getAngle(a, N):
s=bin(int(a))[2:].zfill(N)
angle = 0
for i in range(0, N):
if s[N-1-i] == '1':
angle += math.pow(2, -(N-i))
angle *= np.pi
return angle
def getAngles(a,N):
s=bin(int(a))[2:].zfill(N)
angles=np.zeros([N])
for i in range(0, N):
for j in range(i,N):
if s[j]=='1':
angles[N-i-1]+=math.pow(2, -(j-i))
angles[N-i-1]*=np.pi
return angles
def ccphase(circuit, angle, ctl1, ctl2, tgt):
circuit.cu1(angle/2,ctl1,tgt)
circuit.cx(ctl2,ctl1)
circuit.cu1(-angle/2,ctl1,tgt)
circuit.cx(ctl2,ctl1)
circuit.cu1(angle/2,ctl2,tgt)
def phiADD(circuit, q, a, N, inv):
angle=getAngles(a,N)
for i in range(0,N):
if inv==0:
circuit.u1(angle[i],q[i])
else:
circuit.u1(-angle[i],q[i])
def cphiADD(circuit, q, ctl, a, n, inv):
angle=getAngles(a,n)
for i in range(0,n):
if inv==0:
circuit.cu1(angle[i],ctl,q[i])
else:
circuit.cu1(-angle[i],ctl,q[i])
def ccphiADD(circuit,q,ctl1,ctl2,a,n,inv):
angle=getAngles(a,n)
for i in range(0,n):
if inv==0:
ccphase(circuit,angle[i],ctl1,ctl2,q[i])
else:
ccphase(circuit,-angle[i],ctl1,ctl2,q[i])
def ccphiADDmodN(circuit, q, ctl1, ctl2, aux, a, N, n):
ccphiADD(circuit, q, ctl1, ctl2, a, n, 0)
phiADD(circuit, q, N, n, 1)
# phiADD(circuit, q, a,N, 1)
create_inverse_QFT(circuit, q, n, 0)
circuit.cx(q[n-1],aux)
create_QFT(circuit,q,n,0)
cphiADD(circuit, q, aux, N, n, 0)
# cphiADD(circuit, q, aux, a, n, 0)
ccphiADD(circuit, q, ctl1, ctl2, a, n, 1)
create_inverse_QFT(circuit, q, n, 0)
circuit.x(q[n-1])
circuit.cx(q[n-1], aux)
circuit.x(q[n-1])
create_QFT(circuit,q,n,0)
ccphiADD(circuit, q, ctl1, ctl2, a, n, 0)
def ccphiADDmodN_inv(circuit, q, ctl1, ctl2, aux, a, N, n):
ccphiADD(circuit, q, ctl1, ctl2, a, n, 1)
create_inverse_QFT(circuit, q, n, 0)
circuit.x(q[n-1])
circuit.cx(q[n-1],aux)
circuit.x(q[n-1])
create_QFT(circuit, q, n, 0)
ccphiADD(circuit, q, ctl1, ctl2, a, n, 0)
cphiADD(circuit, q, aux, N, n, 1)
# cphiADD(circuit, q, aux, a, n, 1)
create_inverse_QFT(circuit, q, n, 0)
circuit.cx(q[n-1], aux)
create_QFT(circuit, q, n, 0)
phiADD(circuit, q, N, n, 0)
# phiADD(circuit, q, a, N, 0)
ccphiADD(circuit, q, ctl1, ctl2, a, n, 1)
def cMULTmodN(circuit, ctl, q, aux, a, N, n):
# up_reg = QuantumRegister(1, name = "up_reg")
# down_reg = QuantumRegister(n, name = "down_reg")
# up_classic = ClassicalRegister(2*n, name="up_classic")
# c_aux = ClassicalRegister(1, name = "aux_classic")
# cMULTmodN_circuit = QuantumCircuit(
# up_reg ,down_reg , aux,up_classic, c_aux,
# name=r"${0}^{{{1}^{{{2}}}}} mod{3}$".format(2,2,int(math.log(math.log(a,2),2)), N)
# )
# create_QFT(cMULTmodN_circuit,aux,n+1,0)
# for i in range(0, n):
# ccphiADDmodN(cMULTmodN_circuit, aux, q[i], ctl, aux[n+1], (2**i)*a % N, N, n+1)
# create_inverse_QFT(cMULTmodN_circuit, aux, n+1, 0)
# for i in range(0, n):
# circuit.cswap(ctl,q[i],aux[i])
# cMULTmodN_circuit.cswap(ctl,q[i],aux[i])
# create_QFT(cMULTmodN_circuit, aux, n+1, 0)
# ccphiADDmodN_inv(cMULTmodN_circuit, aux, q[i], ctl, aux[n+1], math.pow(2,i)*a_inv % N, N, n+1)
# create_inverse_QFT(cMULTmodN_circuit, aux, n+1, 0)
# cMULTmodN_circuit_instruction = cMULTmodN_circuit.to_instruction()
# circuit.append(cMULTmodN_circuit_instruction, [ctl, *down_reg, *aux])
create_QFT(circuit,aux,n+1,0)
for i in range(0, n):
ccphiADDmodN(circuit, aux, q[i], ctl, aux[n+1], (2**i)*a % N, N, n+1)
create_inverse_QFT(circuit, aux, n+1, 0)
for i in range(0, n):
circuit.cswap(ctl,q[i],aux[i])
a_inv = modinv(a, N)
create_QFT(circuit, aux, n+1, 0)
i = n-1
while i >= 0:
ccphiADDmodN_inv(circuit, aux, q[i], ctl, aux[n+1], math.pow(2,i)*a_inv % N, N, n+1)
i -= 1
create_inverse_QFT(circuit, aux, n+1, 0)
def calculate_continued_fraction(b: array.array) -> int:
# """Calculate the continued fraction of x/T from the current terms of expansion b."""
x_over_T = 0
for i in reversed(range(len(b) - 1)):
x_over_T = 1 / (b[i + 1] + x_over_T)
x_over_T += b[0]
frac = fractions.Fraction(x_over_T).limit_denominator()
return frac.denominator
def get_factors(N: int, a: int, measurement: str) -> Optional[List[int]]:
# """Apply the continued fractions to find r and the gcd to find the desired factors."""
x_final = int(measurement, 2)
#print('In decimal, x_final value for this result is: {}.'.format(x_final))
if x_final <= 0:
fail_reason = 'x_final value is <= 0, there are no continued fractions.'
else:
fail_reason = None
#print('Running continued fractions for this case.')
# Calculate T and x/T
T_upper = len(measurement)
T = pow(2, T_upper)
x_over_T = x_final / T ## this is our theta
# Cycle in which each iteration corresponds to putting one more term in the
# calculation of the Continued Fraction (CF) of x/T
# Initialize the first values according to CF rule
i = 0
b = array.array('i')
t = array.array('f')
b.append(math.floor(x_over_T))
t.append(x_over_T - b[i])
exponential = 0.0
while i < N and fail_reason is None:
# From the 2nd iteration onwards, calculate the new terms of the CF based on the previous terms as the rule suggests
if i > 0:
try:
b_temp = math.floor(1 / t[i - 1])
except ZeroDivisionError as err:
b_temp = 0
b.append(b_temp)
try:
t_temp = (1 / t[i - 1]) - b[i]
except ZeroDivisionError as err:
t_temp = 0
t.append(t_temp) # type: ignore
# Calculate the denominator of the CF using the known terms
denominator = calculate_continued_fraction(b)
# Increment i for next iteration
i += 1
if denominator % 2 == 1:
#print('Odd denominator, will try next iteration of continued fractions.')
continue
# Denominator is even, try to get factors of N. Get the exponential a^(r/2)
if denominator < 1000:
try:
exponential = pow(a, denominator / 2)
except OverflowError as err:
exponential = 999999999
# Check if the value is too big or not
if exponential > 1000000:
if exponential == 999999999:
fail_reason = 'OverflowError'
else:
fail_reason = 'denominator of continued fraction is too big (> 10^3).'
else:
# The value is not too big, get the right values and do the proper gcd()
putting_plus = int(exponential + 1)
putting_minus = int(exponential - 1)
one_factor = math.gcd(putting_plus, N)
other_factor = math.gcd(putting_minus, N)
# Check if the factors found are trivial factors or are the desired factors
if any(factor in {1, N} for factor in (one_factor, other_factor)):
#print('Found just trivial factors, not good enough.')
# Check if the number has already been found, (use i - 1 because i was already incremented)
if t[i - 1] == 0:
fail_reason = 'the continued fractions found exactly x_final/(2^(2n)).'
else:
return sorted((one_factor, other_factor))
return None
def process_results(sim_result, circuit, shots, N, a, n):
counts_result = sim_result.get_counts(circuit)
total_counts = len(counts_result)
counts_result_sorted = sorted(counts_result.items(), key=lambda x: x[1], reverse=True)
counts_result_keys = list(counts_result.keys())
counts_result_values = list(counts_result.values())
prob_success=0
prob_failure=0
result_successful_counts = 0
result_failure_counts = 0
for initial_undesired_measurement, frequency in counts_result_sorted:
measurement = initial_undesired_measurement.split(" ")[1]
x_value = int(measurement, 2)
prob_this_result = 100 * frequency/shots
factors = get_factors(N, a, measurement)
if factors:
prob_success = prob_success + prob_this_result
result_successful_counts = result_successful_counts + 1
if factors not in result_factors:
result_factors.append(factors)
elif not factors:
prob_failure = prob_failure + prob_this_result
result_failure_counts = result_failure_counts + 1
return [result_factors, prob_success, prob_failure, total_counts, result_successful_counts,result_failure_counts]
def my_shor(a,N,shots):
start_time_number = datetime.now()
start_time = start_time_number.strftime("%H:%M:%S")
summary_result = dict()
validate_min('N', N, 3)
validate_min('a', a, 2)
if N < 1 or N % 2 == 0:
raise ValueError('The input needs to be an odd integer greater than 1.')
if a >= N or math.gcd(a, N) != 1:
raise ValueError('The integer a needs to satisfy a < N and gcd(a, N) = 1.')
n = math.ceil(math.log(N,2))
global result_factors
result_factors = []
tf, b, p = is_power(N, return_decomposition=True)
if tf:
print('The input integer is a power: {0}={1}^{2}.'.format(N, b, p))
result_factors.append(b)
# """auxilliary quantum register used in addition and multiplication"""
aux = QuantumRegister(size = n+2, name="aux_reg")
# """single qubit where the sequential QFT is performed"""
up_reg = QuantumRegister(1, name = "up_reg")
down_reg = QuantumRegister(n, name = "down_reg")
# """classical register where the measured values of the sequential QFT are stored"""
up_classic = ClassicalRegister(2*n, name="up_classic")
# """classical bit used to reset the state of the top qubit to 0 if the previous measurement was 1"""
c_aux = ClassicalRegister(1, name = "aux_classic")
# """ Create Quantum Circuit """
circuit = QuantumCircuit(up_reg ,down_reg , aux,up_classic, c_aux)
circuit.x(down_reg[0])
# circuit.draw(filename = "shor_semiclassical_QFT_initialization")
for i in range(0, 2*n):
circuit.x(up_reg).c_if(c_aux, 1)
circuit.h(up_reg)
cMULTmodN(circuit, up_reg[0], down_reg, aux, a**(2**(2*n-1-i)), N, n)
# later confirm if this should be up_reg[i] instead of up_reg[0]
for j in range(0, 2**i):
circuit.u1(getAngle(j, i), up_reg[0]).c_if(up_classic, j)
circuit.h(up_reg)
circuit.measure(up_reg[0], up_classic[i])
circuit.measure(up_reg[0], c_aux[0])
# circuit.draw(filename = "shor_semiclassical_QFT_final_circuit")
circuit.draw()
qc_compiled = transpile(circuit, backend, optimization_level = 3)
job_sim_1 = backend.run(qc_compiled, shots=shots)
sim_result=job_sim_1.result()
# counts_result = sim_result.get_counts(circuit)
# len(counts_result)
# measurement_plot = qiskit.visualization.plot_histogram(counts_result,figsize=(20, 12) ,number_to_keep = 30,bar_labels=True, title = "Measurement results from shor_standard_QFT circuit variant" )
# measurement_plot.savefig("shor_semiclassical_QFT_measurement_result")
# measurement_plot
processed_result = process_results(sim_result, circuit, shots, N, a, n)
end_time_number = datetime.now()
end_time = end_time_number.strftime("%H:%M:%S")
duration = end_time_number - start_time_number
print("Current Start Time =", start_time)
print(processed_result)
print("Current End Time =", end_time)
circuit_count_ops = circuit.count_ops()
circuit_decomposed = circuit.decompose()
circuit_decomposed_count_ops = circuit_decomposed.count_ops()
qc_compiled_count_ops = qc_compiled.count_ops()
summary_result["num_qubits"] = n
summary_result["Number(N)"] = N
summary_result["a"] = a
summary_result["start_time"] = start_time
summary_result["end_time"] = end_time
summary_result["duration"] = duration
summary_result["result_factors"] = processed_result[0]
summary_result["prob_success"] = processed_result[1]
summary_result["prob_failure"] = processed_result[2]
summary_result["total_counts"] = processed_result[3]
summary_result["result_successful_counts"] = processed_result[4]
summary_result["result_failure_counts"] = processed_result[5]
summary_result["circuit_width"] = circuit.width()
summary_result["circuit_depth"] = circuit.depth()
summary_result["circuit_size"] = circuit.size()
summary_result["circuit_num_nonlocal_gates"] = circuit.num_nonlocal_gates()
summary_result["circuit_num_ancillas"] = circuit.num_ancillas
summary_result["circuit_num_clbits"] = circuit.num_clbits
summary_result["circuit_num_qubits"] = circuit.num_qubits
summary_result["circuit_num_ancillas"] = circuit.num_ancillas
summary_result["circuit_num_of_count_ops"] = len(circuit_count_ops)
summary_result["circuit_num_of_x"] = circuit_count_ops.get('x')
summary_result["circuit_num_of_measure"] = circuit_count_ops.get('measure')
summary_result["circuit_num_of_h"] = circuit_count_ops.get('h')
summary_result["circuit_num_of_cswap"] = circuit_count_ops.get('cswap')
summary_result["circuit_num_of_swap"] = circuit_count_ops.get('swap')
summary_result["circuit_num_of_cx"] = circuit_count_ops.get('cx')
summary_result["circuit_num_of_toffoli"] = circuit_count_ops.get('toffoli')
summary_result["circuit_num_of_p"] = circuit_count_ops.get('p')
summary_result["circuit_num_of_t"] = circuit_count_ops.get('t')
summary_result["circuit_decomposed_width"] = circuit_decomposed.width()
summary_result["circuit_decomposed_depth"] = circuit_decomposed.depth()
summary_result["circuit_decomposed_size"] = circuit_decomposed.size()
summary_result["circuit_decomposed_num_nonlocal_gates"] = circuit_decomposed.num_nonlocal_gates()
summary_result["circuit_decomposed_num_ancillas"] = circuit_decomposed.num_ancillas
summary_result["circuit_decomposed_num_clbits"] = circuit_decomposed.num_clbits
summary_result["circuit_decomposed_num_qubits"] = circuit_decomposed.num_qubits
summary_result["circuit_decomposed_num_ancillas"] = circuit_decomposed.num_ancillas
summary_result["circuit_decomposed_num_of_count_ops"] = len(circuit_decomposed_count_ops)
summary_result["circuit_decomposed_num_of_x"] = circuit_decomposed_count_ops.get('x')
summary_result["circuit_decomposed_num_of_measure"] = circuit_decomposed_count_ops.get('measure')
summary_result["circuit_decomposed_num_of_h"] = circuit_decomposed_count_ops.get('h')
summary_result["circuit_decomposed_num_of_cswap"] = circuit_decomposed_count_ops.get('cswap')
summary_result["circuit_decomposed_num_of_swap"] = circuit_decomposed_count_ops.get('swap')
summary_result["circuit_decomposed_num_of_cx"] = circuit_decomposed_count_ops.get('cx')
summary_result["circuit_decomposed_num_of_toffoli"] = circuit_decomposed_count_ops.get('toffoli')
summary_result["circuit_decomposed_num_of_p"] = circuit_decomposed_count_ops.get('p')
summary_result["circuit_decomposed_num_of_t"] = circuit_decomposed_count_ops.get('t')
summary_result["qc_compiled_width"] = qc_compiled.width()
summary_result["qc_compiled_depth"] = qc_compiled.depth()
summary_result["qc_compiled_size"] = qc_compiled.size()
summary_result["qc_compiled_num_nonlocal_gates"] = qc_compiled.num_nonlocal_gates()
summary_result["qc_compiled_num_ancillas"] = qc_compiled.num_ancillas
summary_result["qc_compiled_num_clbits"] = qc_compiled.num_clbits
summary_result["qc_compiled_num_qubits"] = qc_compiled.num_qubits
summary_result["qc_compiled_num_ancillas"] = qc_compiled.num_ancillas
summary_result["qc_compiled_num_of_count_ops"] = len(qc_compiled_count_ops)
summary_result["qc_compiled_num_of_x"] = qc_compiled_count_ops.get('x')
summary_result["qc_compiled_num_of_measure"] = qc_compiled_count_ops.get('measure')
summary_result["qc_compiled_num_of_h"] = qc_compiled_count_ops.get('h')
summary_result["qc_compiled_num_of_cswap"] = qc_compiled_count_ops.get('cswap')
summary_result["qc_compiled_num_of_swap"] = qc_compiled_count_ops.get('swap')
summary_result["qc_compiled_num_of_cx"] = qc_compiled_count_ops.get('cx')
summary_result["qc_compiled_num_of_toffoli"] = qc_compiled_count_ops.get('toffoli')
summary_result["qc_compiled_num_of_p"] = qc_compiled_count_ops.get('p')
summary_result["qc_compiled_num_of_t"] = qc_compiled_count_ops.get('t')
return summary_result
# Run for just a single number N
%%time
N = 21
shots = 1024
global result_factors
all_summary_result_temp = []
for random_a in range(2, N):
if math.gcd(random_a,N) > 1:
continue
a = random_a
summary_result = my_shor(a,N,shots)
print("Finished running for a = {} and N = {}\n".format(a, N))
all_summary_result_temp.append(summary_result)
summary_result_list = []
for key, value in summary_result.items():
summary_result_list.append([key,value])
summary_result_list
with open("a({0})_N({1})_semiclassical.csv".format(a, N), 'a') as myfile:
write = csv.writer(myfile)
#write.writerow(fields)
write.writerows(summary_result_list)
all_summary_result_temp
# Run for many numbers N.
%%time
shots = 1024
global result_factors
all_summary_result = []
for N in [15, 21, 33, 35, 39, 51, 55, 57]:
for a in range(2, N):
if math.gcd(a,N) > 1:
continue
print("Beginning running for a = {} and N = {}".format(a, N))
summary_result = my_shor(a,N,shots)
print("Finished running for a = {} and N = {}\n\n".format(a, N))
all_summary_result.append(summary_result)
all_summary_result
%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.
"""BasicAer Backends Test."""
from qiskit import BasicAer
from qiskit.providers.basicaer import BasicAerProvider
from qiskit.providers.exceptions import QiskitBackendNotFoundError
from qiskit.test import providers
class TestBasicAerBackends(providers.ProviderTestCase):
"""Qiskit BasicAer Backends (Object) Tests."""
provider_cls = BasicAerProvider
backend_name = "qasm_simulator"
def test_deprecated(self):
"""Test that deprecated names map the same backends as the new names."""
def _get_first_available_backend(provider, backend_names):
"""Gets the first available backend."""
if isinstance(backend_names, str):
backend_names = [backend_names]
for backend_name in backend_names:
try:
return provider.get_backend(backend_name).name()
except QiskitBackendNotFoundError:
pass
return None
deprecated_names = BasicAer._deprecated_backend_names()
for oldname, newname in deprecated_names.items():
expected = (
"WARNING:qiskit.providers.providerutils:Backend '%s' is deprecated. "
"Use '%s'." % (oldname, newname)
)
with self.subTest(oldname=oldname, newname=newname):
with self.assertLogs("qiskit.providers.providerutils", level="WARNING") as context:
resolved_newname = _get_first_available_backend(BasicAer, newname)
real_backend = BasicAer.get_backend(resolved_newname)
self.assertEqual(BasicAer.backends(oldname)[0], real_backend)
self.assertEqual(context.output, [expected])
def test_aliases_fail(self):
"""Test a failing backend lookup."""
self.assertRaises(QiskitBackendNotFoundError, BasicAer.get_backend, "bad_name")
def test_aliases_return_empty_list(self):
"""Test backends() return an empty list if name is unknown."""
self.assertEqual(BasicAer.backends("bad_name"), [])
|
https://github.com/sarthag/Quantum-Algos-using-Qiskit
|
sarthag
|
import sys
sys.path.append('../')
from circuits import sampleCircuitA, sampleCircuitB1, sampleCircuitB2,\
sampleCircuitB3, sampleCircuitC, sampleCircuitD, sampleCircuitE,\
sampleCircuitF
from entanglement import Ent
import warnings
warnings.filterwarnings('ignore')
labels = [
'Circuit A', 'Circuit B1', 'Circuit B2', 'Circuit B3',
'Circuit C', 'Circuit D', 'Circuit E', 'Circuit F'
]
samplers = [
sampleCircuitA,
sampleCircuitB1,
sampleCircuitB2,
sampleCircuitB3,
sampleCircuitC,
sampleCircuitD,
sampleCircuitE,
sampleCircuitF
]
q = 4
for layer in range(1, 4):
print(f'qubtis: {q}')
print('-' * 25)
for (label, sampler) in zip(labels, samplers):
expr = Ent(sampler, layer=layer, epoch=3000)
print(f'{label}(layer={layer}): {expr}')
print()
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import numpy as np
from qiskit import QuantumCircuit
from qiskit.circuit.library.arithmetic.piecewise_chebyshev import PiecewiseChebyshev
f_x, degree, breakpoints, num_state_qubits = lambda x: np.arcsin(1 / x), 2, [2, 4], 2
pw_approximation = PiecewiseChebyshev(f_x, degree, breakpoints, num_state_qubits)
pw_approximation._build()
qc = QuantumCircuit(pw_approximation.num_qubits)
qc.h(list(range(num_state_qubits)))
qc.append(pw_approximation.to_instruction(), qc.qubits)
qc.draw(output='mpl')
|
https://github.com/pedroripper/qiskit_tutoriais
|
pedroripper
|
from qiskit import *
%matplotlib inline
# Podemos transformar o nosso circuito em apenas uma porta
circuito = QuantumCircuit(2)
circuito.x(0)
circuito.h(1)
circuito.draw(output='mpl')
# Para conseguir uma porta que represente essas operações fazemos
# Podemos ainda adicionar um titulo para a nossa porta ou apenas deixar em branco
minha_porta = circuito.to_gate(label='Minha porta')
# Agora vamos adicionar ela em outro circuito
c2 = QuantumCircuit(2)
# Para adicionar uma porta dessa forma usamos o comando append()
c2.append(minha_porta,[0,1])
c2.draw(output='mpl')
# Para conferir se essa porta realmente representa a original fazemos
c2.decompose().draw(output='mpl')
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
q = QuantumRegister(1)
c = ClassicalRegister(1)
qc = QuantumCircuit(q, c)
qc.h(q)
qc.measure(q, c)
qc.draw(output='mpl', style={'backgroundcolor': '#EEEEEE'})
|
https://github.com/renatawong/quantum-maxcut
|
renatawong
|
'''
(C) Renata Wong (NCTS-NTU) 2023
This is the accompanying code for the paper "Quantum speedup for the maximum cut problem"
for the example graph given in Fig. 1.
Note: It is impossible to execute it for graphs with more than 2 edges as the number of qubits exceeds the simulator limit.
'''
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
import numpy as np
'''
Create the quantum circuit for the 3-vertex example
num_vertices = n = number of vertices
num_enges = m = number of edges
'''
'''
PLEASE FILL IN THE EDGE LIST FOR YOUR GRAPH IN THE LINE BELOW
'''
permanent_edge_list = [[0,1], [1,2]]
num_vertices = len({x for l in permanent_edge_list for x in l})
num_edges = len(permanent_edge_list)
range_z = (((num_edges + 1) * (num_edges + 2)) / 2) - 1
range_r = 4 * (num_edges * (num_edges + 1)) / 2
range_s = 2 * (num_edges * (num_edges + 1)) / 2
aux = QuantumRegister(1, 'aux')
z_reg = QuantumRegister(range_z, 'z_reg')
s_reg = QuantumRegister(range_s, 's_reg')
r_reg = QuantumRegister(range_r, 'r_reg')
x_reg = QuantumRegister(num_vertices, 'x_reg')
readout = ClassicalRegister(num_vertices, 'out')
qc = QuantumCircuit(aux, x_reg, r_reg, s_reg, z_reg, readout)
qc.x(aux)
qc.h(aux)
# Print this variable to see the system size
system_size = qc.num_qubits
'''
Create z_matrix to store elements of z_reg
'''
z_matrix = [ [ 0 for i in range(num_edges + 1) ] for j in range(num_edges + 1) ]
zij = 0
for i in range(1, num_edges + 1):
for j in range(i + 1):
z_matrix[i][j] = zij
zij += 1
'''
Define the CFE subcircuit
'''
sq = QuantumRegister(10,'sq')
sc = QuantumCircuit(sq, name='CFE')
# EIIAC
sc.x(sq[1])
sc.ccx(sq[0], sq[1], sq[2])
sc.x(sq[0])
sc.x(sq[1])
sc.ccx(sq[0], sq[1], sq[3])
sc.x(sq[0])
sc.x(sq[2])
sc.x(sq[3])
sc.ccx(sq[2], sq[3], sq[6])
sc.x(sq[2])
sc.x(sq[3])
# EINIAC
sc.x(sq[0])
sc.x(sq[1])
sc.ccx(sq[0], sq[1], sq[4])
sc.x(sq[0])
sc.x(sq[1])
sc.ccx(sq[0], sq[1], sq[5])
sc.x(sq[4])
sc.x(sq[5])
sc.ccx(sq[4], sq[5], sq[7])
sc.x(sq[4])
sc.x(sq[5])
# CNOTS
sc.cx(sq[6], sq[9])
sc.cx(sq[7], sq[8])
cfe = sc.to_instruction()
'''
Define the CSE subcircuit
'''
cq = QuantumRegister(11,'cq')
ce = QuantumCircuit(cq, name='CSE')
# EIIAC
ce.x(cq[1])
ce.ccx(cq[0], cq[1], cq[2])
ce.x(cq[0])
ce.x(cq[1])
ce.ccx(cq[0], cq[1], cq[3])
ce.x(cq[0])
ce.x(cq[2])
ce.x(cq[3])
ce.ccx(cq[2], cq[3], cq[6])
ce.x(cq[2])
ce.x(cq[3])
# EINIAC
ce.x(cq[0])
ce.x(cq[1])
ce.ccx(cq[0], cq[1], cq[4])
ce.x(cq[0])
ce.x(cq[1])
ce.ccx(cq[0], cq[1], cq[5])
ce.x(cq[4])
ce.x(cq[5])
ce.ccx(cq[4], cq[5], cq[7])
ce.x(cq[4])
ce.x(cq[5])
# CNOTS
ce.ccx(cq[6], cq[8], cq[9])
ce.ccx(cq[7], cq[8], cq[10])
cse = ce.to_instruction()
'''
Initialize the system and set it in a uniform superpostion -> lines 1 and 2 of Algorithm 1 in paper
'''
for qubit in s_reg:
qc.x(qubit)
for qubit in x_reg:
qc.h(qubit)
qc.barrier()
'''
NOTE: There will always be an even number of solutions, since under maximum cut 101 is the same as 010.
For Fig. 1 in the paper, we set the number of solutions to 2.
YOU MAY NEED TO ADJUST THE NUMBER OF SOLUTIONS.
'''
num_solutions = 2
num_runs = int(np.ceil(np.pi * np.sqrt((2**num_vertices) / num_solutions)) / 4)
'''
Amplitude amplification
'''
for run in range(num_runs):
# Apply CFE to |psi_1> -> line 3 in Algorithm 1
# It is assumed that the two vertices in the x_reg share an edge
r = 4
s = 2
edge_list = permanent_edge_list.copy()
if len(edge_list) > 0:
index_v1 = edge_list[0][0]
index_v2 = edge_list[0][1]
edge_list.pop(0)
cfe_qubits = []
cfe_qubits += [x_reg[index_v1]]
cfe_qubits += [x_reg[index_v2]]
cfe_qubits += [r_reg[i] for i in range(4)]
cfe_qubits += [s_reg[i] for i in range(2)]
cfe_qubits += [z_reg[i] for i in range(2)]
qc.append(cfe, cfe_qubits)
# Apply CSE to |psi_2> --> line 4 in Algorithm 1
# It is assumed that the two vertices in the x_reg share an edge
for i in range(1, num_edges):
index_v1 = edge_list[0][0]
index_v2 = edge_list[0][1]
cse_qubits = []
for j in reversed(range(i+1)):
cse_qubits += [x_reg[index_v1]]
cse_qubits += [x_reg[index_v2]]
cse_qubits += [r_reg[i] for i in range(r, r+4)]
cse_qubits += [s_reg[i] for i in range(s, s+2)]
cse_qubits += [z_reg[z_matrix[i][j]]]
cse_qubits += [z_reg[z_matrix[i+1][j+1]]]
cse_qubits += [z_reg[z_matrix[i+1][j]]]
qc.append(cse, cse_qubits)
cse_qubits.clear()
r += 4
s += 2
edge_list.pop(0)
'''
Which qubit of register z_reg is used here depends on how many edges are there in the cut.
For the example in Fig. 1 we expect 2 edges, and therefore we choose qubit 2 (counting from 0, 1, 2, etc.).
This qubit should be in the state 1.
YOU MAY NEED TO ADJUST THE CONTROL QUBIT IN THE CX GATE.
'''
qc.barrier()
qc.cx(z_reg[len(z_reg)-1], aux)
qc.barrier()
'''
Uncompute CSE and CFE operations
'''
edge_list = permanent_edge_list.copy()
for i in reversed(range(1, num_edges)):
index_v1 = edge_list[len(edge_list) - 1][0]
index_v2 = edge_list[len(edge_list) - 1][1]
cse_qubits = []
for j in range(i+1):
r -= 4
s -= 2
cse_qubits += [x_reg[index_v1]]
cse_qubits += [x_reg[index_v2]]
cse_qubits += [r_reg[i] for i in range(r, r+4)]
cse_qubits += [s_reg[i] for i in range(s, s+2)]
cse_qubits += [z_reg[z_matrix[i][j]]]
cse_qubits += [z_reg[z_matrix[i+1][j+1]]]
cse_qubits += [z_reg[z_matrix[i+1][j]]]
qc.append(cse.inverse(), cse_qubits)
cse_qubits.clear()
edge_list.pop(0)
edge_list = [permanent_edge_list[0]]
if len(edge_list) > 0:
index_v1 = edge_list[0][0]
index_v2 = edge_list[0][1]
cfe_qubits = []
cfe_qubits += [x_reg[index_v1]]
cfe_qubits += [x_reg[index_v2]]
cfe_qubits += [r_reg[i] for i in range(4)]
cfe_qubits += [s_reg[i] for i in range(2)]
cfe_qubits += [z_reg[i] for i in range(2)]
qc.append(cfe.inverse(), cfe_qubits)
edge_list.pop()
'''
Diffusion operations
'''
qc.barrier()
for qubit in x_reg:
qc.h(qubit)
qc.x(qubit)
# apply CZ to x_reg
qc.h(x_reg[len(x_reg) - 1])
multiplexer = [x_reg[i] for i in range(len(x_reg) - 1)]
qc.mcx(multiplexer, x_reg[len(x_reg) - 1])
qc.h(x_reg[len(x_reg) - 1])
for qubit in x_reg:
qc.x(qubit)
qc.h(qubit)
qc.barrier()
'''
Measurement
'''
cuts = []
for i in range(len(x_reg)):
cuts.append(x_reg[i])
# Reverse the order in which the output is shown so that it can be read from left to right.
cuts.reverse()
qc.measure(cuts, readout)
from qiskit import Aer, execute
from qiskit.visualization import plot_histogram
from qiskit.providers.aer import QasmSimulator, StatevectorSimulator
simulator = Aer.get_backend('qasm_simulator')
result = execute(qc, backend = simulator, shots = 100).result()
counts = result.get_counts()
# Uncomment to save the output
#plot_histogram(counts).savefig('example.svg')
plot_histogram(counts)
# See the produced circuit
qc.draw('mpl')
|
https://github.com/swe-bench/Qiskit__qiskit
|
swe-bench
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2020, 2023.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""ExpectationFactory Class"""
import logging
from typing import Optional, Union
from qiskit import BasicAer
from qiskit.opflow.expectations.aer_pauli_expectation import AerPauliExpectation
from qiskit.opflow.expectations.expectation_base import ExpectationBase
from qiskit.opflow.expectations.matrix_expectation import MatrixExpectation
from qiskit.opflow.expectations.pauli_expectation import PauliExpectation
from qiskit.opflow.operator_base import OperatorBase
from qiskit.providers import Backend
from qiskit.utils.backend_utils import is_aer_qasm, is_statevector_backend
from qiskit.utils import QuantumInstance, optionals
from qiskit.utils.deprecation import deprecate_func
logger = logging.getLogger(__name__)
class ExpectationFactory:
"""Deprecated: factory class for convenient automatic selection of an Expectation based on the
Operator to be converted and backend used to sample the expectation value.
"""
@staticmethod
@deprecate_func(
since="0.24.0",
additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration.",
)
def build(
operator: OperatorBase,
backend: Optional[Union[Backend, QuantumInstance]] = None,
include_custom: bool = True,
) -> ExpectationBase:
"""
A factory method for convenient automatic selection of an Expectation based on the
Operator to be converted and backend used to sample the expectation value.
Args:
operator: The Operator whose expectation value will be taken.
backend: The backend which will be used to sample the expectation value.
include_custom: Whether the factory will include the (Aer) specific custom
expectations if their behavior against the backend might not be as expected.
For instance when using Aer qasm_simulator with paulis the Aer snapshot can
be used but the outcome lacks shot noise and hence does not intuitively behave
overall as people might expect when choosing a qasm_simulator. It is however
fast as long as the more state vector like behavior is acceptable.
Returns:
The expectation algorithm which best fits the Operator and backend.
Raises:
ValueError: If operator is not of a composition for which we know the best Expectation
method.
"""
backend_to_check = backend.backend if isinstance(backend, QuantumInstance) else backend
# pylint: disable=cyclic-import
primitives = operator.primitive_strings()
if primitives in ({"Pauli"}, {"SparsePauliOp"}):
if backend_to_check is None:
# If user has Aer but didn't specify a backend, use the Aer fast expectation
if optionals.HAS_AER:
from qiskit_aer import AerSimulator
backend_to_check = AerSimulator()
# If user doesn't have Aer, use statevector_simulator
# for < 16 qubits, and qasm with warning for more.
else:
if operator.num_qubits <= 16:
backend_to_check = BasicAer.get_backend("statevector_simulator")
else:
logger.warning(
"%d qubits is a very large expectation value. "
"Consider installing Aer to use "
"Aer's fast expectation, which will perform better here. We'll use "
"the BasicAer qasm backend for this expectation to avoid having to "
"construct the %dx%d operator matrix.",
operator.num_qubits,
2**operator.num_qubits,
2**operator.num_qubits,
)
backend_to_check = BasicAer.get_backend("qasm_simulator")
# If the user specified Aer qasm backend and is using a
# Pauli operator, use the Aer fast expectation if we are including such
# custom behaviors.
if is_aer_qasm(backend_to_check) and include_custom:
return AerPauliExpectation()
# If the user specified a statevector backend (either Aer or BasicAer),
# use a converter to produce a
# Matrix operator and compute using matmul
elif is_statevector_backend(backend_to_check):
if operator.num_qubits >= 16:
logger.warning(
"Note: Using a statevector_simulator with %d qubits can be very expensive. "
"Consider using the Aer qasm_simulator instead to take advantage of Aer's "
"built-in fast Pauli Expectation",
operator.num_qubits,
)
return MatrixExpectation()
# All other backends, including IBMQ, BasicAer QASM, go here.
else:
return PauliExpectation()
elif primitives == {"Matrix"}:
return MatrixExpectation()
else:
raise ValueError("Expectations of Mixed Operators not yet supported.")
|
https://github.com/farhad-abdi/InSilicoQ
|
farhad-abdi
|
import numpy as np
from qiskit import QuantumCircuit, Aer, execute
from qiskit.visualization import plot_histogram
# Importing qiskit machine learning parameters
from qiskit.circuit import Parameter, ParameterVector
from qiskit.circuit.library import TwoLocal
#first net imports
from qiskit import QuantumCircuit
from qiskit.circuit.library import EfficientSU2
from qiskit.primitives import Sampler
from qiskit_machine_learning.connectors import TorchConnector
from qiskit_machine_learning.neural_networks import SamplerQNN
# created quantum neural network in TorchConnector to make use of PyTorch-based training.
def QGenerator(num_qubits) -> TorchConnector:
qc = QuantumCircuit(num_qubits)
qc.h(qc.qubits)
ansatz = EfficientSU2(num_qubits, reps=6)
qc.compose(ansatz, inplace=True)
print(qc.num_parameters)
shots = 10000
sampler = Sampler(options={"shots": shots, "seed": algorithm_globals.random_seed})
qnn = SamplerQNN(
circuit=qc,
sampler=sampler,
input_params=[],
weight_params=qc.parameters,
sparse=False,
)
initial_weights = algorithm_globals.random.random(qc.num_parameters)
return TorchConnector(qnn, initial_weights)
#alternative qgan
class QGAN:
def __init__(self, num_qubit):
self.num_q = num_qubit
def qgenerator(self):
generator = TwoLocal(self.num_q,
# Parameterized single qubit rotations
['ry', 'rz'],
'cz', # Entangling gate
'full', # Entanglement structure: all to all
reps=2, # Number of layers
parameter_prefix='θ_g',
name='Generator')
generator = generator.decompose() # decompose into standard gates
return generator
def qdiscriminator(self):
disc_weights = ParameterVector('θ_d', 12)
discriminator = QuantumCircuit(3, name="Discriminator")
discriminator.barrier()
discriminator.h(0)
discriminator.rx(disc_weights[0], 0)
discriminator.ry(disc_weights[1], 0)
discriminator.rz(disc_weights[2], 0)
discriminator.rx(disc_weights[3], 1)
discriminator.ry(disc_weights[4], 1)
discriminator.rz(disc_weights[5], 1)
discriminator.rx(disc_weights[6], 2)
discriminator.ry(disc_weights[7], 2)
discriminator.rz(disc_weights[8], 2)
discriminator.cx(0, 2)
discriminator.cx(1, 2)
discriminator.rx(disc_weights[9], 2)
discriminator.ry(disc_weights[10], 2)
discriminator.rz(disc_weights[11], 2)
#discriminator.draw()
return discriminator
def qgan_model(self):
qgan = QuantumCircuit(self.num_q +1 )
qgan.compose(self.qgenerator(), inplace = True)
qgan.compose(self.qdiscriminator(), inplace = True)
return qgan
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import transpile, QuantumCircuit
import qiskit.quantum_info as qi
from qiskit_aer import AerSimulator
from qiskit_aer.noise import NoiseModel, amplitude_damping_error
from qiskit.tools.visualization import plot_histogram
# CNOT matrix operator with qubit-0 as control and qubit-1 as target
cx_op = qi.Operator([[1, 0, 0, 0],
[0, 0, 0, 1],
[0, 0, 1, 0],
[0, 1, 0, 0]])
# iSWAP matrix operator
iswap_op = qi.Operator([[1, 0, 0, 0],
[0, 0, 1j, 0],
[0, 1j, 0, 0],
[0, 0, 0, 1]])
# CNOT in terms of iSWAP and single-qubit gates
cx_circ = QuantumCircuit(2, name='cx<iSWAP>')
# Add gates
cx_circ.sdg(1)
cx_circ.h(1)
cx_circ.sdg(0)
cx_circ.unitary(iswap_op, [0, 1], label='iswap')
cx_circ.sdg(0)
cx_circ.h(0)
cx_circ.sdg(0)
cx_circ.unitary(iswap_op, [0, 1], label='iswap')
cx_circ.s(1)
print(cx_circ)
# Simulate the unitary for the circuit using Operator:
unitary = qi.Operator(cx_circ)
print(unitary)
f_ave = qi.average_gate_fidelity(cx_op, unitary)
print("Average Gate Fidelity: F = {:f}".format(f_ave))
'unitary' in AerSimulator().configuration().basis_gates
# Error parameters
param_q0 = 0.05 # damping parameter for qubit-0
param_q1 = 0.1 # damping parameter for qubit-1
# Construct the error
qerror_q0 = amplitude_damping_error(param_q0)
qerror_q1 = amplitude_damping_error(param_q1)
iswap_error = qerror_q1.tensor(qerror_q0)
# Build the noise model by adding the error to the "iswap" gate
noise_model = NoiseModel()
noise_model.add_all_qubit_quantum_error(iswap_error, 'iswap')
noise_model.add_basis_gates(['unitary'])
print(noise_model.basis_gates)
# Bell state circuit where iSWAPS should be inserted at barrier locations
bell_circ = QuantumCircuit(2, 2, name='bell')
bell_circ.h(0)
bell_circ.append(cx_circ, [0, 1])
bell_circ.measure([0,1], [0,1])
print(bell_circ)
# Create ideal simulator backend and transpile circuit
sim_ideal = AerSimulator()
tbell_circ = transpile(bell_circ, sim_ideal)
ideal_result = sim_ideal.run(tbell_circ).result()
ideal_counts = ideal_result.get_counts(0)
plot_histogram(ideal_counts,
title='Ideal output for iSWAP bell-state preparation')
# Create noisy simulator and transpile circuit
sim_noise = AerSimulator(noise_model=noise_model)
tbell_circ_noise = transpile(bell_circ, sim_noise)
# Run on the simulator without noise
noise_result = sim_noise.run(tbell_circ_noise).result()
noise_counts = noise_result.get_counts(bell_circ)
plot_histogram(noise_counts,
title='Noisy output for iSWAP bell-state preparation')
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/qiskit-community/qiskit-device-benchmarking
|
qiskit-community
|
import numpy as np
import rustworkx as rx
import matplotlib.pyplot as plt
from qiskit_ibm_runtime import QiskitRuntimeService
from qiskit import QuantumCircuit
from qiskit_experiments.framework import ParallelExperiment, BatchExperiment
from qiskit_experiments.library import (StateTomography, MitigatedStateTomography)
from qiskit_device_benchmarking.utilities import graph_utils as gu
#enter your device hub/group/project here
#and device
hgp = 'ibm-q/open/main'
service = QiskitRuntimeService()
backend_real=service.backend('ibm_kyiv',instance=hgp)
nq = backend_real.configuration().n_qubits
coupling_map = backend_real.configuration().coupling_map
#build a set of gates
G = gu.build_sys_graph(nq, coupling_map)
#get all length 2 paths in the device
paths = rx.all_pairs_all_simple_paths(G,2,2)
#flatten those paths into a list from the rustwork x iterator
paths = gu.paths_flatten(paths)
#remove permutations
paths = gu.remove_permutations(paths)
#convert to the coupling map of the device
paths = gu.path_to_edges(paths,coupling_map)
#make into separate sets
sep_sets = gu.get_separated_sets(G, paths, min_sep=2)
#state tomography of all the two qubit edgges in parallel
tomo_batch_list = []
#got through for each of the edge sets
for ii in range(len(sep_sets)):
tomo_exp_list = []
tomo_exp_list_b = []
twoq_circ_b = QuantumCircuit(2)
twoq_circ = QuantumCircuit(2)
if (1):
twoq_circ.h(0)
twoq_circ.cx(0,1)
if 'ecr' in backend_real.configuration().basis_gates:
twoq_gate='ecr'
elif 'cz' in backend_real.configuration().basis_gates:
twoq_gate='cz'
for two_i, two_set in enumerate(sep_sets[ii]):
tomo_exp = MitigatedStateTomography(circuit=twoq_circ, physical_qubits=two_set[0:2], backend = backend_real)
tomo_exp_list.append(tomo_exp)
tomo_exp = MitigatedStateTomography(circuit=twoq_circ_b, physical_qubits=two_set[0:2], backend = backend_real)
tomo_exp_list_b.append(tomo_exp)
tomo_exp_p = ParallelExperiment(tomo_exp_list, backend = backend_real)
tomo_exp_pb = ParallelExperiment(tomo_exp_list_b, backend = backend_real)
tomo_batch_list.append(tomo_exp_p)
tomo_batch_list.append(tomo_exp_pb)
#back all of them together
full_tomo_exp = BatchExperiment(tomo_batch_list, backend = backend_real)
full_tomo_exp.set_run_options(shots=1000)
#run
tomo_data = full_tomo_exp.run()
set_list = []
bell_err = []
id_err = []
gate_err = []
read_err = []
back_prop = backend_real.properties()
for i in range(len(sep_sets)):
for j in range(len(sep_sets[i])):
set_list.append(sep_sets[i][j])
bell_err.append(1-tomo_data.child_data()[2*i].child_data()[j].analysis_results()[1].value)
id_err.append(1-tomo_data.child_data()[2*i+1].child_data()[j].analysis_results()[1].value)
gate_err.append(back_prop.gate_error(twoq_gate,set_list[-1]))
read_err.append(1-(1-back_prop.readout_error(set_list[-1][0]))**0.5*(1-back_prop.readout_error(set_list[-1][1]))**0.5)
print('Q%s, bell error (purity) %.2e (%.2e)/ id error (purity) %.2e (%.2e)'%(sep_sets[i][j],
1-tomo_data.child_data()[2*i].child_data()[j].analysis_results()[1].value,
1-np.abs(tomo_data.child_data()[2*i].child_data()[j].analysis_results()[0].value.purity())**0.5,
1-tomo_data.child_data()[2*i+1].child_data()[j].analysis_results()[1].value,
1-np.abs(tomo_data.child_data()[2*i+1].child_data()[j].analysis_results()[0].value.purity())**0.5))
#print(backend_real.properties().gate_error(twoq_gate,sep_sets[0][i]))
#plot the data ordered by Bell state fidelity (need to run the cell above first)
plt.figure(dpi=150,figsize=[15,5])
argind = np.argsort(bell_err)
plt.semilogy(range(len(set_list)),np.array(bell_err)[argind],label='Bell', marker='.')
plt.semilogy(range(len(set_list)),np.array(id_err)[argind], label='Identity', marker='.')
plt.xticks(range(len(set_list)),np.array(set_list)[argind],rotation=90,fontsize=5);
plt.grid(True)
plt.legend()
plt.title('Bell and |0> State Tomography for %s'%backend_real.name)
import datetime
from IPython.display import HTML, display
def qiskit_copyright(line="", cell=None):
"""IBM copyright"""
now = datetime.datetime.now()
html = "<div style='width: 100%; background-color:#d5d9e0;"
html += "padding-left: 10px; padding-bottom: 10px; padding-right: 10px; padding-top: 5px'>"
html += "<p>© Copyright IBM 2017, %s.</p>" % now.year
html += "<p>This code is licensed under the Apache License, Version 2.0. You may<br>"
html += "obtain a copy of this license in the LICENSE.txt file in the root directory<br> "
html += "of this source tree or at http://www.apache.org/licenses/LICENSE-2.0."
html += "<p>Any modifications or derivative works of this code must retain this<br>"
html += "copyright notice, and modified files need to carry a notice indicating<br>"
html += "that they have been altered from the originals.</p>"
html += "</div>"
return display(HTML(html))
qiskit_copyright()
|
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.
"""Test cases for the pulse scheduler passes."""
from numpy import pi
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, schedule
from qiskit.circuit import Gate, Parameter
from qiskit.circuit.library import U1Gate, U2Gate, U3Gate
from qiskit.exceptions import QiskitError
from qiskit.pulse import (
Schedule,
DriveChannel,
AcquireChannel,
Acquire,
MeasureChannel,
MemorySlot,
Gaussian,
Play,
transforms,
)
from qiskit.pulse import build, macros, play, InstructionScheduleMap
from qiskit.providers.fake_provider import FakeBackend, FakeOpenPulse2Q, FakeOpenPulse3Q
from qiskit.test import QiskitTestCase
class TestBasicSchedule(QiskitTestCase):
"""Scheduling tests."""
def setUp(self):
super().setUp()
self.backend = FakeOpenPulse2Q()
self.inst_map = self.backend.defaults().instruction_schedule_map
def test_unavailable_defaults(self):
"""Test backend with unavailable defaults."""
qr = QuantumRegister(1)
qc = QuantumCircuit(qr)
backend = FakeBackend(None)
backend.defaults = backend.configuration
self.assertRaises(QiskitError, lambda: schedule(qc, backend))
def test_alap_pass(self):
"""Test ALAP scheduling."""
# ┌───────────────┐ ░ ┌─┐
# q0_0: ┤ U2(3.14,1.57) ├────────────────────░───■──┤M├───
# └┬──────────────┤ ░ ┌──────────────┐ ░ ┌─┴─┐└╥┘┌─┐
# q0_1: ─┤ U2(0.5,0.25) ├─░─┤ U2(0.5,0.25) ├─░─┤ X ├─╫─┤M├
# └──────────────┘ ░ └──────────────┘ ░ └───┘ ║ └╥┘
# c0: 2/═════════════════════════════════════════════╩══╩═
# 0 1
q = QuantumRegister(2)
c = ClassicalRegister(2)
qc = QuantumCircuit(q, c)
qc.append(U2Gate(3.14, 1.57), [q[0]])
qc.append(U2Gate(0.5, 0.25), [q[1]])
qc.barrier(q[1])
qc.append(U2Gate(0.5, 0.25), [q[1]])
qc.barrier(q[0], [q[1]])
qc.cx(q[0], q[1])
qc.measure(q, c)
sched = schedule(qc, self.backend)
# X pulse on q0 should end at the start of the CNOT
expected = Schedule(
(2, self.inst_map.get("u2", [0], 3.14, 1.57)),
self.inst_map.get("u2", [1], 0.5, 0.25),
(2, self.inst_map.get("u2", [1], 0.5, 0.25)),
(4, self.inst_map.get("cx", [0, 1])),
(26, self.inst_map.get("measure", [0, 1])),
)
for actual, expected in zip(sched.instructions, expected.instructions):
self.assertEqual(actual[0], expected[0])
self.assertEqual(actual[1], expected[1])
def test_single_circuit_list_schedule(self):
"""Test that passing a single circuit list to schedule() returns a list."""
q = QuantumRegister(2)
c = ClassicalRegister(2)
qc = QuantumCircuit(q, c)
sched = schedule([qc], self.backend, method="alap")
expected = Schedule()
self.assertIsInstance(sched, list)
self.assertEqual(sched[0].instructions, expected.instructions)
def test_alap_with_barriers(self):
"""Test that ALAP respects barriers on new qubits."""
q = QuantumRegister(2)
c = ClassicalRegister(2)
qc = QuantumCircuit(q, c)
qc.append(U2Gate(0, 0), [q[0]])
qc.barrier(q[0], q[1])
qc.append(U2Gate(0, 0), [q[1]])
sched = schedule(qc, self.backend, method="alap")
expected = Schedule(
self.inst_map.get("u2", [0], 0, 0), (2, self.inst_map.get("u2", [1], 0, 0))
)
for actual, expected in zip(sched.instructions, expected.instructions):
self.assertEqual(actual[0], expected[0])
self.assertEqual(actual[1], expected[1])
def test_empty_circuit_schedule(self):
"""Test empty circuit being scheduled."""
q = QuantumRegister(2)
c = ClassicalRegister(2)
qc = QuantumCircuit(q, c)
sched = schedule(qc, self.backend, method="alap")
expected = Schedule()
self.assertEqual(sched.instructions, expected.instructions)
def test_alap_aligns_end(self):
"""Test that ALAP always acts as though there is a final global barrier."""
q = QuantumRegister(2)
c = ClassicalRegister(2)
qc = QuantumCircuit(q, c)
qc.append(U3Gate(0, 0, 0), [q[0]])
qc.append(U2Gate(0, 0), [q[1]])
sched = schedule(qc, self.backend, method="alap")
expected_sched = Schedule(
(2, self.inst_map.get("u2", [1], 0, 0)), self.inst_map.get("u3", [0], 0, 0, 0)
)
for actual, expected in zip(sched.instructions, expected_sched.instructions):
self.assertEqual(actual[0], expected[0])
self.assertEqual(actual[1], expected[1])
self.assertEqual(
sched.ch_duration(DriveChannel(0)), expected_sched.ch_duration(DriveChannel(1))
)
def test_asap_pass(self):
"""Test ASAP scheduling."""
# ┌───────────────┐ ░ ┌─┐
# q0_0: ┤ U2(3.14,1.57) ├────────────────────░───■──┤M├───
# └┬──────────────┤ ░ ┌──────────────┐ ░ ┌─┴─┐└╥┘┌─┐
# q0_1: ─┤ U2(0.5,0.25) ├─░─┤ U2(0.5,0.25) ├─░─┤ X ├─╫─┤M├
# └──────────────┘ ░ └──────────────┘ ░ └───┘ ║ └╥┘
# c0: 2/═════════════════════════════════════════════╩══╩═
# 0 1
q = QuantumRegister(2)
c = ClassicalRegister(2)
qc = QuantumCircuit(q, c)
qc.append(U2Gate(3.14, 1.57), [q[0]])
qc.append(U2Gate(0.5, 0.25), [q[1]])
qc.barrier(q[1])
qc.append(U2Gate(0.5, 0.25), [q[1]])
qc.barrier(q[0], q[1])
qc.cx(q[0], q[1])
qc.measure(q, c)
sched = schedule(qc, self.backend, method="as_soon_as_possible")
# X pulse on q0 should start at t=0
expected = Schedule(
self.inst_map.get("u2", [0], 3.14, 1.57),
self.inst_map.get("u2", [1], 0.5, 0.25),
(2, self.inst_map.get("u2", [1], 0.5, 0.25)),
(4, self.inst_map.get("cx", [0, 1])),
(26, self.inst_map.get("measure", [0, 1])),
)
for actual, expected in zip(sched.instructions, expected.instructions):
self.assertEqual(actual[0], expected[0])
self.assertEqual(actual[1], expected[1])
def test_alap_resource_respecting(self):
"""Test that the ALAP pass properly respects busy resources when backwards scheduling.
For instance, a CX on 0 and 1 followed by an X on only 1 must respect both qubits'
timeline."""
q = QuantumRegister(2)
c = ClassicalRegister(2)
qc = QuantumCircuit(q, c)
qc.cx(q[0], q[1])
qc.append(U2Gate(0.5, 0.25), [q[1]])
sched = schedule(qc, self.backend, method="as_late_as_possible")
insts = sched.instructions
self.assertEqual(insts[0][0], 0)
self.assertEqual(insts[6][0], 22)
qc = QuantumCircuit(q, c)
qc.cx(q[0], q[1])
qc.append(U2Gate(0.5, 0.25), [q[1]])
qc.measure(q, c)
sched = schedule(qc, self.backend, method="as_late_as_possible")
self.assertEqual(sched.instructions[-1][0], 24)
def test_inst_map_schedules_unaltered(self):
"""Test that forward scheduling doesn't change relative timing with a command."""
q = QuantumRegister(2)
c = ClassicalRegister(2)
qc = QuantumCircuit(q, c)
qc.cx(q[0], q[1])
sched1 = schedule(qc, self.backend, method="as_soon_as_possible")
sched2 = schedule(qc, self.backend, method="as_late_as_possible")
for asap, alap in zip(sched1.instructions, sched2.instructions):
self.assertEqual(asap[0], alap[0])
self.assertEqual(asap[1], alap[1])
insts = sched1.instructions
self.assertEqual(insts[0][0], 0) # shift phase
self.assertEqual(insts[1][0], 0) # ym_d0
self.assertEqual(insts[2][0], 0) # x90p_d1
self.assertEqual(insts[3][0], 2) # cr90p_u0
self.assertEqual(insts[4][0], 11) # xp_d0
self.assertEqual(insts[5][0], 13) # cr90m_u0
def test_measure_combined(self):
"""
Test to check for measure on the same qubit which generated another measure schedule.
The measures on different qubits are combined, but measures on the same qubit
adds another measure to the schedule.
"""
q = QuantumRegister(2)
c = ClassicalRegister(2)
qc = QuantumCircuit(q, c)
qc.append(U2Gate(3.14, 1.57), [q[0]])
qc.cx(q[0], q[1])
qc.measure(q[0], c[0])
qc.measure(q[1], c[1])
qc.measure(q[1], c[1])
sched = schedule(qc, self.backend, method="as_soon_as_possible")
expected = Schedule(
self.inst_map.get("u2", [0], 3.14, 1.57),
(2, self.inst_map.get("cx", [0, 1])),
(24, self.inst_map.get("measure", [0, 1])),
(34, self.inst_map.get("measure", [0, 1]).filter(channels=[MeasureChannel(1)])),
(34, Acquire(10, AcquireChannel(1), MemorySlot(1))),
)
self.assertEqual(sched.instructions, expected.instructions)
def test_3q_schedule(self):
"""Test a schedule that was recommended by David McKay :D"""
# ┌─────────────────┐
# q0_0: ─────────■─────────┤ U3(3.14,1.57,0) ├────────────────────────
# ┌─┴─┐ └┬───────────────┬┘
# q0_1: ───────┤ X ├────────┤ U2(3.14,1.57) ├───■─────────────────────
# ┌──────┴───┴──────┐ └───────────────┘ ┌─┴─┐┌─────────────────┐
# q0_2: ┤ U2(0.778,0.122) ├───────────────────┤ X ├┤ U2(0.778,0.122) ├
# └─────────────────┘ └───┘└─────────────────┘
backend = FakeOpenPulse3Q()
inst_map = backend.defaults().instruction_schedule_map
q = QuantumRegister(3)
c = ClassicalRegister(3)
qc = QuantumCircuit(q, c)
qc.cx(q[0], q[1])
qc.append(U2Gate(0.778, 0.122), [q[2]])
qc.append(U3Gate(3.14, 1.57, 0), [q[0]])
qc.append(U2Gate(3.14, 1.57), [q[1]])
qc.cx(q[1], q[2])
qc.append(U2Gate(0.778, 0.122), [q[2]])
sched = schedule(qc, backend)
expected = Schedule(
inst_map.get("cx", [0, 1]),
(22, inst_map.get("u2", [1], 3.14, 1.57)),
(22, inst_map.get("u2", [2], 0.778, 0.122)),
(24, inst_map.get("cx", [1, 2])),
(44, inst_map.get("u3", [0], 3.14, 1.57, 0)),
(46, inst_map.get("u2", [2], 0.778, 0.122)),
)
for actual, expected in zip(sched.instructions, expected.instructions):
self.assertEqual(actual[0], expected[0])
self.assertEqual(actual[1], expected[1])
def test_schedule_multi(self):
"""Test scheduling multiple circuits at once."""
q = QuantumRegister(2)
c = ClassicalRegister(2)
qc0 = QuantumCircuit(q, c)
qc0.cx(q[0], q[1])
qc1 = QuantumCircuit(q, c)
qc1.cx(q[0], q[1])
schedules = schedule([qc0, qc1], self.backend)
expected_insts = schedule(qc0, self.backend).instructions
for actual, expected in zip(schedules[0].instructions, expected_insts):
self.assertEqual(actual[0], expected[0])
self.assertEqual(actual[1], expected[1])
def test_circuit_name_kept(self):
"""Test that the new schedule gets its name from the circuit."""
q = QuantumRegister(2)
c = ClassicalRegister(2)
qc = QuantumCircuit(q, c, name="CIRCNAME")
qc.cx(q[0], q[1])
sched = schedule(qc, self.backend, method="asap")
self.assertEqual(sched.name, qc.name)
sched = schedule(qc, self.backend, method="alap")
self.assertEqual(sched.name, qc.name)
def test_can_add_gates_into_free_space(self):
"""The scheduler does some time bookkeeping to know when qubits are free to be
scheduled. Make sure this works for qubits that are used in the future. This was
a bug, uncovered by this example:
q0 = - - - - |X|
q1 = |X| |u2| |X|
In ALAP scheduling, the next operation on qubit 0 would be added at t=0 rather
than immediately before the X gate.
"""
qr = QuantumRegister(2)
qc = QuantumCircuit(qr)
for i in range(2):
qc.append(U2Gate(0, 0), [qr[i]])
qc.append(U1Gate(3.14), [qr[i]])
qc.append(U2Gate(0, 0), [qr[i]])
sched = schedule(qc, self.backend, method="alap")
expected = Schedule(
self.inst_map.get("u2", [0], 0, 0),
self.inst_map.get("u2", [1], 0, 0),
(2, self.inst_map.get("u1", [0], 3.14)),
(2, self.inst_map.get("u1", [1], 3.14)),
(2, self.inst_map.get("u2", [0], 0, 0)),
(2, self.inst_map.get("u2", [1], 0, 0)),
)
for actual, expected in zip(sched.instructions, expected.instructions):
self.assertEqual(actual[0], expected[0])
self.assertEqual(actual[1], expected[1])
def test_barriers_in_middle(self):
"""As a follow on to `test_can_add_gates_into_free_space`, similar issues
arose for barriers, specifically.
"""
qr = QuantumRegister(2)
qc = QuantumCircuit(qr)
for i in range(2):
qc.append(U2Gate(0, 0), [qr[i]])
qc.barrier(qr[i])
qc.append(U1Gate(3.14), [qr[i]])
qc.barrier(qr[i])
qc.append(U2Gate(0, 0), [qr[i]])
sched = schedule(qc, self.backend, method="alap")
expected = Schedule(
self.inst_map.get("u2", [0], 0, 0),
self.inst_map.get("u2", [1], 0, 0),
(2, self.inst_map.get("u1", [0], 3.14)),
(2, self.inst_map.get("u1", [1], 3.14)),
(2, self.inst_map.get("u2", [0], 0, 0)),
(2, self.inst_map.get("u2", [1], 0, 0)),
)
for actual, expected in zip(sched.instructions, expected.instructions):
self.assertEqual(actual[0], expected[0])
self.assertEqual(actual[1], expected[1])
def test_parametric_input(self):
"""Test that scheduling works with parametric pulses as input."""
qr = QuantumRegister(1)
qc = QuantumCircuit(qr)
qc.append(Gate("gauss", 1, []), qargs=[qr[0]])
custom_gauss = Schedule(
Play(Gaussian(duration=25, sigma=4, amp=0.5, angle=pi / 2), DriveChannel(0))
)
self.inst_map.add("gauss", [0], custom_gauss)
sched = schedule(qc, self.backend, inst_map=self.inst_map)
self.assertEqual(sched.instructions[0], custom_gauss.instructions[0])
def test_pulse_gates(self):
"""Test scheduling calibrated pulse gates."""
q = QuantumRegister(2)
qc = QuantumCircuit(q)
qc.append(U2Gate(0, 0), [q[0]])
qc.barrier(q[0], q[1])
qc.append(U2Gate(0, 0), [q[1]])
qc.add_calibration("u2", [0], Schedule(Play(Gaussian(28, 0.2, 4), DriveChannel(0))), [0, 0])
qc.add_calibration("u2", [1], Schedule(Play(Gaussian(28, 0.2, 4), DriveChannel(1))), [0, 0])
sched = schedule(qc, self.backend)
expected = Schedule(
Play(Gaussian(28, 0.2, 4), DriveChannel(0)),
(28, Schedule(Play(Gaussian(28, 0.2, 4), DriveChannel(1)))),
)
self.assertEqual(sched.instructions, expected.instructions)
def test_calibrated_measurements(self):
"""Test scheduling calibrated measurements."""
q = QuantumRegister(2)
c = ClassicalRegister(2)
qc = QuantumCircuit(q, c)
qc.append(U2Gate(0, 0), [q[0]])
qc.measure(q[0], c[0])
meas_sched = Play(Gaussian(1200, 0.2, 4), MeasureChannel(0))
meas_sched |= Acquire(1200, AcquireChannel(0), MemorySlot(0))
qc.add_calibration("measure", [0], meas_sched)
sched = schedule(qc, self.backend)
expected = Schedule(self.inst_map.get("u2", [0], 0, 0), (2, meas_sched))
self.assertEqual(sched.instructions, expected.instructions)
def test_subset_calibrated_measurements(self):
"""Test that measurement calibrations can be added and used for some qubits, even
if the other qubits do not also have calibrated measurements."""
qc = QuantumCircuit(3, 3)
qc.measure(0, 0)
qc.measure(1, 1)
qc.measure(2, 2)
meas_scheds = []
for qubit in [0, 2]:
meas = Play(Gaussian(1200, 0.2, 4), MeasureChannel(qubit)) + Acquire(
1200, AcquireChannel(qubit), MemorySlot(qubit)
)
meas_scheds.append(meas)
qc.add_calibration("measure", [qubit], meas)
meas = macros.measure([1], FakeOpenPulse3Q())
meas = meas.exclude(channels=[AcquireChannel(0), AcquireChannel(2)])
sched = schedule(qc, FakeOpenPulse3Q())
expected = Schedule(meas_scheds[0], meas_scheds[1], meas)
self.assertEqual(sched.instructions, expected.instructions)
def test_clbits_of_calibrated_measurements(self):
"""Test that calibrated measurements are only used when the classical bits also match."""
q = QuantumRegister(2)
c = ClassicalRegister(2)
qc = QuantumCircuit(q, c)
qc.measure(q[0], c[1])
meas_sched = Play(Gaussian(1200, 0.2, 4), MeasureChannel(0))
meas_sched |= Acquire(1200, AcquireChannel(0), MemorySlot(0))
qc.add_calibration("measure", [0], meas_sched)
sched = schedule(qc, self.backend)
# Doesn't use the calibrated schedule because the classical memory slots do not match
expected = Schedule(macros.measure([0], self.backend, qubit_mem_slots={0: 1}))
self.assertEqual(sched.instructions, expected.instructions)
def test_metadata_is_preserved_alap(self):
"""Test that circuit metadata is preserved in output schedule with alap."""
q = QuantumRegister(2)
qc = QuantumCircuit(q)
qc.append(U2Gate(0, 0), [q[0]])
qc.barrier(q[0], q[1])
qc.append(U2Gate(0, 0), [q[1]])
qc.metadata = {"experiment_type": "gst", "execution_number": "1234"}
sched = schedule(qc, self.backend, method="alap")
self.assertEqual({"experiment_type": "gst", "execution_number": "1234"}, sched.metadata)
def test_metadata_is_preserved_asap(self):
"""Test that circuit metadata is preserved in output schedule with asap."""
q = QuantumRegister(2)
qc = QuantumCircuit(q)
qc.append(U2Gate(0, 0), [q[0]])
qc.barrier(q[0], q[1])
qc.append(U2Gate(0, 0), [q[1]])
qc.metadata = {"experiment_type": "gst", "execution_number": "1234"}
sched = schedule(qc, self.backend, method="asap")
self.assertEqual({"experiment_type": "gst", "execution_number": "1234"}, sched.metadata)
def test_scheduler_with_params_bound(self):
"""Test scheduler with parameters defined and bound"""
x = Parameter("x")
qc = QuantumCircuit(2)
qc.append(Gate("pulse_gate", 1, [x]), [0])
expected_schedule = Schedule()
qc.add_calibration(gate="pulse_gate", qubits=[0], schedule=expected_schedule, params=[x])
qc = qc.assign_parameters({x: 1})
sched = schedule(qc, self.backend)
self.assertEqual(sched, expected_schedule)
def test_scheduler_with_params_not_bound(self):
"""Test scheduler with parameters defined but not bound"""
x = Parameter("amp")
qc = QuantumCircuit(2)
qc.append(Gate("pulse_gate", 1, [x]), [0])
with build() as expected_schedule:
play(Gaussian(duration=160, amp=x, sigma=40), DriveChannel(0))
qc.add_calibration(gate="pulse_gate", qubits=[0], schedule=expected_schedule, params=[x])
sched = schedule(qc, self.backend)
self.assertEqual(sched, transforms.target_qobj_transform(expected_schedule))
def test_schedule_block_in_instmap(self):
"""Test schedule block in instmap can be scheduled."""
duration = Parameter("duration")
with build() as pulse_prog:
play(Gaussian(duration, 0.1, 10), DriveChannel(0))
instmap = InstructionScheduleMap()
instmap.add("block_gate", (0,), pulse_prog, ["duration"])
qc = QuantumCircuit(1)
qc.append(Gate("block_gate", 1, [duration]), [0])
qc.assign_parameters({duration: 100}, inplace=True)
sched = schedule(qc, self.backend, inst_map=instmap)
ref_sched = Schedule()
ref_sched += Play(Gaussian(100, 0.1, 10), DriveChannel(0))
self.assertEqual(sched, ref_sched)
|
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.
"""Test schedule block subroutine reference mechanism."""
import numpy as np
from qiskit import circuit, pulse
from qiskit.pulse import builder
from qiskit.pulse.transforms import inline_subroutines
from qiskit.test import QiskitTestCase
class TestReference(QiskitTestCase):
"""Test for basic behavior of reference mechanism."""
def test_append_schedule(self):
"""Test appending schedule without calling.
Appended schedules are not subroutines.
These are directly exposed to the outer block.
"""
with pulse.build() as sched_x1:
pulse.play(pulse.Constant(100, 0.1, name="x1"), pulse.DriveChannel(0))
with pulse.build() as sched_y1:
builder.append_schedule(sched_x1)
with pulse.build() as sched_z1:
builder.append_schedule(sched_y1)
self.assertEqual(len(sched_z1.references), 0)
def test_append_schedule_parameter_scope(self):
"""Test appending schedule without calling.
Parameter in the appended schedule has the scope of outer schedule.
"""
param = circuit.Parameter("name")
with pulse.build() as sched_x1:
pulse.play(pulse.Constant(100, param, name="x1"), pulse.DriveChannel(0))
with pulse.build() as sched_y1:
builder.append_schedule(sched_x1)
with pulse.build() as sched_z1:
builder.append_schedule(sched_y1)
sched_param = next(iter(sched_z1.scoped_parameters()))
self.assertEqual(sched_param.name, "root::name")
# object equality
self.assertEqual(
sched_z1.search_parameters("root::name")[0],
param,
)
def test_refer_schedule(self):
"""Test refer to schedule by name.
Outer block is only aware of its inner reference.
Nested reference is not directly exposed to the most outer block.
"""
with pulse.build() as sched_x1:
pulse.play(pulse.Constant(100, 0.1, name="x1"), pulse.DriveChannel(0))
with pulse.build() as sched_y1:
builder.reference("x1", "d0")
with pulse.build() as sched_z1:
builder.reference("y1", "d0")
sched_y1.assign_references({("x1", "d0"): sched_x1})
sched_z1.assign_references({("y1", "d0"): sched_y1})
self.assertEqual(len(sched_z1.references), 1)
self.assertEqual(sched_z1.references[("y1", "d0")], sched_y1)
self.assertEqual(len(sched_y1.references), 1)
self.assertEqual(sched_y1.references[("x1", "d0")], sched_x1)
def test_refer_schedule_parameter_scope(self):
"""Test refer to schedule by name.
Parameter in the called schedule has the scope of called schedule.
"""
param = circuit.Parameter("name")
with pulse.build() as sched_x1:
pulse.play(pulse.Constant(100, param, name="x1"), pulse.DriveChannel(0))
with pulse.build() as sched_y1:
builder.reference("x1", "d0")
with pulse.build() as sched_z1:
builder.reference("y1", "d0")
sched_y1.assign_references({("x1", "d0"): sched_x1})
sched_z1.assign_references({("y1", "d0"): sched_y1})
sched_param = next(iter(sched_z1.scoped_parameters()))
self.assertEqual(sched_param.name, "root::y1,d0::x1,d0::name")
# object equality
self.assertEqual(
sched_z1.search_parameters("root::y1,d0::x1,d0::name")[0],
param,
)
# regex
self.assertEqual(
sched_z1.search_parameters(r"\S::x1,d0::name")[0],
param,
)
def test_call_schedule(self):
"""Test call schedule.
Outer block is only aware of its inner reference.
Nested reference is not directly exposed to the most outer block.
"""
with pulse.build() as sched_x1:
pulse.play(pulse.Constant(100, 0.1, name="x1"), pulse.DriveChannel(0))
with pulse.build() as sched_y1:
builder.call(sched_x1, name="x1")
with pulse.build() as sched_z1:
builder.call(sched_y1, name="y1")
self.assertEqual(len(sched_z1.references), 1)
self.assertEqual(sched_z1.references[("y1",)], sched_y1)
self.assertEqual(len(sched_y1.references), 1)
self.assertEqual(sched_y1.references[("x1",)], sched_x1)
def test_call_schedule_parameter_scope(self):
"""Test call schedule.
Parameter in the called schedule has the scope of called schedule.
"""
param = circuit.Parameter("name")
with pulse.build() as sched_x1:
pulse.play(pulse.Constant(100, param, name="x1"), pulse.DriveChannel(0))
with pulse.build() as sched_y1:
builder.call(sched_x1, name="x1")
with pulse.build() as sched_z1:
builder.call(sched_y1, name="y1")
sched_param = next(iter(sched_z1.scoped_parameters()))
self.assertEqual(sched_param.name, "root::y1::x1::name")
# object equality
self.assertEqual(
sched_z1.search_parameters("root::y1::x1::name")[0],
param,
)
# regex
self.assertEqual(
sched_z1.search_parameters(r"\S::x1::name")[0],
param,
)
def test_append_and_call_schedule(self):
"""Test call and append schedule.
Reference is copied to the outer schedule by appending.
Original reference remains unchanged.
"""
with pulse.build() as sched_x1:
pulse.play(pulse.Constant(100, 0.1, name="x1"), pulse.DriveChannel(0))
with pulse.build() as sched_y1:
builder.call(sched_x1, name="x1")
with pulse.build() as sched_z1:
builder.append_schedule(sched_y1)
self.assertEqual(len(sched_z1.references), 1)
self.assertEqual(sched_z1.references[("x1",)], sched_x1)
# blocks[0] is sched_y1 and its reference is now point to outer block reference
self.assertIs(sched_z1.blocks[0].references, sched_z1.references)
# however the original program is protected to prevent unexpected mutation
self.assertIsNot(sched_y1.references, sched_z1.references)
# appended schedule is preserved
self.assertEqual(len(sched_y1.references), 1)
self.assertEqual(sched_y1.references[("x1",)], sched_x1)
def test_calling_similar_schedule(self):
"""Test calling schedules with the same representation.
sched_x1 and sched_y1 are the different subroutines, but same representation.
Two references shoud be created.
"""
param1 = circuit.Parameter("param")
param2 = circuit.Parameter("param")
with pulse.build() as sched_x1:
pulse.play(pulse.Constant(100, param1, name="p"), pulse.DriveChannel(0))
with pulse.build() as sched_y1:
pulse.play(pulse.Constant(100, param2, name="p"), pulse.DriveChannel(0))
with pulse.build() as sched_z1:
pulse.call(sched_x1)
pulse.call(sched_y1)
self.assertEqual(len(sched_z1.references), 2)
def test_calling_same_schedule(self):
"""Test calling same schedule twice.
Because it calls the same schedule, no duplication should occur in reference table.
"""
param = circuit.Parameter("param")
with pulse.build() as sched_x1:
pulse.play(pulse.Constant(100, param, name="x1"), pulse.DriveChannel(0))
with pulse.build() as sched_z1:
pulse.call(sched_x1, name="same_sched")
pulse.call(sched_x1, name="same_sched")
self.assertEqual(len(sched_z1.references), 1)
def test_calling_same_schedule_with_different_assignment(self):
"""Test calling same schedule twice but with different parameters.
Same schedule is called twice but with different assignment.
Two references should be created.
"""
param = circuit.Parameter("param")
with pulse.build() as sched_x1:
pulse.play(pulse.Constant(100, param, name="x1"), pulse.DriveChannel(0))
with pulse.build() as sched_z1:
pulse.call(sched_x1, param=0.1)
pulse.call(sched_x1, param=0.2)
self.assertEqual(len(sched_z1.references), 2)
def test_alignment_context(self):
"""Test nested alignment context.
Inline alignment is identical to append_schedule operation.
Thus scope is not newly generated.
"""
with pulse.build(name="x1") as sched_x1:
with pulse.align_right():
with pulse.align_left():
pulse.play(pulse.Constant(100, 0.1, name="x1"), pulse.DriveChannel(0))
self.assertEqual(len(sched_x1.references), 0)
def test_appending_child_block(self):
"""Test for edge case.
User can append blocks which is an element of another schedule block.
But this is not standard use case.
In this case, references may contain subroutines which don't exist in the context.
This is because all references within the program are centrally
managed in the most outer block.
"""
with pulse.build() as sched_x1:
pulse.play(pulse.Constant(100, 0.1, name="x1"), pulse.DriveChannel(0))
with pulse.build() as sched_y1:
pulse.play(pulse.Constant(100, 0.2, name="y1"), pulse.DriveChannel(0))
with pulse.build() as sched_x2:
builder.call(sched_x1, name="x1")
self.assertEqual(list(sched_x2.references.keys()), [("x1",)])
with pulse.build() as sched_y2:
builder.call(sched_y1, name="y1")
self.assertEqual(list(sched_y2.references.keys()), [("y1",)])
with pulse.build() as sched_z1:
builder.append_schedule(sched_x2)
builder.append_schedule(sched_y2)
self.assertEqual(list(sched_z1.references.keys()), [("x1",), ("y1",)])
# child block references point to its parent, i.e. sched_z1
self.assertIs(sched_z1.blocks[0].references, sched_z1._reference_manager)
self.assertIs(sched_z1.blocks[1].references, sched_z1._reference_manager)
with pulse.build() as sched_z2:
# Append child block
# The reference of this block is sched_z1.reference thus it contains both x1 and y1.
# However, y1 doesn't exist in the context, so only x1 should be added.
# Usually, user will append sched_x2 directly here, rather than sched_z1.blocks[0]
# This is why this situation is an edge case.
builder.append_schedule(sched_z1.blocks[0])
self.assertEqual(len(sched_z2.references), 1)
self.assertEqual(sched_z2.references[("x1",)], sched_x1)
def test_replacement(self):
"""Test nested alignment context.
Replacing schedule block with schedule block.
Removed block contains own reference, that should be removed with replacement.
New block also contains reference, that should be passed to the current reference.
"""
with pulse.build() as sched_x1:
pulse.play(pulse.Constant(100, 0.1, name="x1"), pulse.DriveChannel(0))
with pulse.build() as sched_y1:
pulse.play(pulse.Constant(100, 0.2, name="y1"), pulse.DriveChannel(0))
with pulse.build() as sched_x2:
builder.call(sched_x1, name="x1")
with pulse.build() as sched_y2:
builder.call(sched_y1, name="y1")
with pulse.build() as sched_z1:
builder.append_schedule(sched_x2)
builder.append_schedule(sched_y2)
self.assertEqual(len(sched_z1.references), 2)
self.assertEqual(sched_z1.references[("x1",)], sched_x1)
self.assertEqual(sched_z1.references[("y1",)], sched_y1)
# Define schedule to replace
with pulse.build() as sched_r1:
pulse.play(pulse.Constant(100, 0.1, name="r1"), pulse.DriveChannel(0))
with pulse.build() as sched_r2:
pulse.call(sched_r1, name="r1")
sched_z2 = sched_z1.replace(sched_x2, sched_r2)
self.assertEqual(len(sched_z2.references), 2)
self.assertEqual(sched_z2.references[("r1",)], sched_r1)
self.assertEqual(sched_z2.references[("y1",)], sched_y1)
def test_special_parameter_name(self):
"""Testcase to guarantee usage of some special symbols in parameter name.
These symbols might be often used in user code.
No conflict should occur with the default scope delimiter.
"""
param = circuit.Parameter("my.parameter_object")
with pulse.build() as sched_x1:
pulse.play(pulse.Constant(100, param, name="x1"), pulse.DriveChannel(0))
with pulse.build() as sched_y1:
pulse.reference("sub", "q0")
sched_y1.assign_references({("sub", "q0"): sched_x1})
ret_param = sched_y1.search_parameters(r"\Ssub,q0::my.parameter_object")[0]
self.assertEqual(param, ret_param)
def test_parameter_in_multiple_scope(self):
"""Testcase for scope-aware parameter getter.
When a single parameter object is used in multiple scopes,
the scoped_parameters method must return parameter objects associated to each scope,
while parameters property returns a single parameter object.
"""
param = circuit.Parameter("name")
with pulse.build() as sched_x1:
pulse.play(pulse.Constant(100, param), pulse.DriveChannel(0))
with pulse.build() as sched_y1:
pulse.play(pulse.Constant(100, param), pulse.DriveChannel(1))
with pulse.build() as sched_z1:
pulse.call(sched_x1, name="x1")
pulse.call(sched_y1, name="y1")
self.assertEqual(len(sched_z1.parameters), 1)
self.assertEqual(len(sched_z1.scoped_parameters()), 2)
self.assertEqual(sched_z1.search_parameters("root::x1::name")[0], param)
self.assertEqual(sched_z1.search_parameters("root::y1::name")[0], param)
def test_parallel_alignment_equality(self):
"""Testcase for potential edge case.
In parallel alignment context, reference instruction is broadcasted to
all channels. When new channel is added after reference, this should be
connected with reference node.
"""
with pulse.build() as subroutine:
pulse.reference("unassigned")
with pulse.build() as sched1:
with pulse.align_left():
pulse.delay(10, pulse.DriveChannel(0))
pulse.call(subroutine) # This should be broadcasted to d1 as well
pulse.delay(10, pulse.DriveChannel(1))
with pulse.build() as sched2:
with pulse.align_left():
pulse.delay(10, pulse.DriveChannel(0))
pulse.delay(10, pulse.DriveChannel(1))
pulse.call(subroutine)
self.assertNotEqual(sched1, sched2)
def test_subroutine_conflict(self):
"""Test for edge case of appending two schedule blocks having the
references with conflicting reference key.
This operation should fail because one of references will be gone after assignment.
"""
with pulse.build() as sched_x1:
pulse.play(pulse.Constant(100, 0.1), pulse.DriveChannel(0))
with pulse.build() as sched_x2:
pulse.call(sched_x1, name="conflict_name")
self.assertEqual(sched_x2.references[("conflict_name",)], sched_x1)
with pulse.build() as sched_y1:
pulse.play(pulse.Constant(100, 0.2), pulse.DriveChannel(0))
with pulse.build() as sched_y2:
pulse.call(sched_y1, name="conflict_name")
self.assertEqual(sched_y2.references[("conflict_name",)], sched_y1)
with self.assertRaises(pulse.exceptions.PulseError):
with pulse.build():
builder.append_schedule(sched_x2)
builder.append_schedule(sched_y2)
def test_assign_existing_reference(self):
"""Test for explicitly assign existing reference.
This operation should fail because overriding reference is not allowed.
"""
with pulse.build() as sched_x1:
pulse.play(pulse.Constant(100, 0.1), pulse.DriveChannel(0))
with pulse.build() as sched_y1:
pulse.play(pulse.Constant(100, 0.2), pulse.DriveChannel(0))
with pulse.build() as sched_z1:
pulse.call(sched_x1, name="conflict_name")
with self.assertRaises(pulse.exceptions.PulseError):
sched_z1.assign_references({("conflict_name",): sched_y1})
class TestSubroutineWithCXGate(QiskitTestCase):
"""Test called program scope with practical example of building fully parametrized CX gate."""
def setUp(self):
super().setUp()
# parameters of X pulse
self.xp_dur = circuit.Parameter("dur")
self.xp_amp = circuit.Parameter("amp")
self.xp_sigma = circuit.Parameter("sigma")
self.xp_beta = circuit.Parameter("beta")
# amplitude of SX pulse
self.sxp_amp = circuit.Parameter("amp")
# parameters of CR pulse
self.cr_dur = circuit.Parameter("dur")
self.cr_amp = circuit.Parameter("amp")
self.cr_sigma = circuit.Parameter("sigma")
self.cr_risefall = circuit.Parameter("risefall")
# channels
self.control_ch = circuit.Parameter("ctrl")
self.target_ch = circuit.Parameter("tgt")
self.cr_ch = circuit.Parameter("cr")
# echo pulse on control qubit
with pulse.build(name="xp") as xp_sched_q0:
pulse.play(
pulse.Drag(
duration=self.xp_dur,
amp=self.xp_amp,
sigma=self.xp_sigma,
beta=self.xp_beta,
),
channel=pulse.DriveChannel(self.control_ch),
)
self.xp_sched = xp_sched_q0
# local rotation on target qubit
with pulse.build(name="sx") as sx_sched_q1:
pulse.play(
pulse.Drag(
duration=self.xp_dur,
amp=self.sxp_amp,
sigma=self.xp_sigma,
beta=self.xp_beta,
),
channel=pulse.DriveChannel(self.target_ch),
)
self.sx_sched = sx_sched_q1
# cross resonance
with pulse.build(name="cr") as cr_sched:
pulse.play(
pulse.GaussianSquare(
duration=self.cr_dur,
amp=self.cr_amp,
sigma=self.cr_sigma,
risefall_sigma_ratio=self.cr_risefall,
),
channel=pulse.ControlChannel(self.cr_ch),
)
self.cr_sched = cr_sched
def test_lazy_ecr(self):
"""Test lazy subroutines through ECR schedule construction."""
with pulse.build(name="lazy_ecr") as sched:
with pulse.align_sequential():
pulse.reference("cr", "q0", "q1")
pulse.reference("xp", "q0")
with pulse.phase_offset(np.pi, pulse.ControlChannel(self.cr_ch)):
pulse.reference("cr", "q0", "q1")
pulse.reference("xp", "q0")
# Schedule has references
self.assertTrue(sched.is_referenced())
# Schedule is not schedulable because of unassigned references
self.assertFalse(sched.is_schedulable())
# Two references cr and xp are called
self.assertEqual(len(sched.references), 2)
# Parameters in the current scope are Parameter("cr") which is used in phase_offset
# References are not assigned yet.
params = {p.name for p in sched.parameters}
self.assertSetEqual(params, {"cr"})
# Parameter names are scoepd
scoped_params = {p.name for p in sched.scoped_parameters()}
self.assertSetEqual(scoped_params, {"root::cr"})
# Assign CR and XP schedule to the empty reference
sched.assign_references({("cr", "q0", "q1"): self.cr_sched})
sched.assign_references({("xp", "q0"): self.xp_sched})
# Check updated references
assigned_refs = sched.references
self.assertEqual(assigned_refs[("cr", "q0", "q1")], self.cr_sched)
self.assertEqual(assigned_refs[("xp", "q0")], self.xp_sched)
# Parameter added from subroutines
scoped_params = {p.name for p in sched.scoped_parameters()}
ref_params = {
# This is the cr parameter that belongs to phase_offset instruction in the root scope
"root::cr",
# This is the same cr parameter that belongs to the play instruction in a child scope
"root::cr,q0,q1::cr",
"root::cr,q0,q1::amp",
"root::cr,q0,q1::dur",
"root::cr,q0,q1::risefall",
"root::cr,q0,q1::sigma",
"root::xp,q0::ctrl",
"root::xp,q0::amp",
"root::xp,q0::beta",
"root::xp,q0::dur",
"root::xp,q0::sigma",
}
self.assertSetEqual(scoped_params, ref_params)
# Get parameter without scope, cr amp and xp amp are hit.
params = sched.get_parameters(parameter_name="amp")
self.assertEqual(len(params), 2)
# Get parameter with scope, only xp amp
params = sched.search_parameters(parameter_regex="root::xp,q0::amp")
self.assertEqual(len(params), 1)
def test_cnot(self):
"""Integration test with CNOT schedule construction."""
# echeod cross resonance
with pulse.build(name="ecr", default_alignment="sequential") as ecr_sched:
pulse.call(self.cr_sched, name="cr")
pulse.call(self.xp_sched, name="xp")
with pulse.phase_offset(np.pi, pulse.ControlChannel(self.cr_ch)):
pulse.call(self.cr_sched, name="cr")
pulse.call(self.xp_sched, name="xp")
# cnot gate, locally equivalent to ecr
with pulse.build(name="cx", default_alignment="sequential") as cx_sched:
pulse.shift_phase(np.pi / 2, pulse.DriveChannel(self.control_ch))
pulse.call(self.sx_sched, name="sx")
pulse.call(ecr_sched, name="ecr")
# get parameter with scope, full scope is not needed
xp_amp = cx_sched.search_parameters(r"\S:xp::amp")[0]
self.assertEqual(self.xp_amp, xp_amp)
# get parameter with scope, of course full scope can be specified
xp_amp_full_scoped = cx_sched.search_parameters("root::ecr::xp::amp")[0]
self.assertEqual(xp_amp_full_scoped, xp_amp)
# assign parameters
assigned_cx = cx_sched.assign_parameters(
value_dict={
self.cr_ch: 0,
self.control_ch: 0,
self.target_ch: 1,
self.sxp_amp: 0.1,
self.xp_amp: 0.2,
self.xp_dur: 160,
self.xp_sigma: 40,
self.xp_beta: 3.0,
self.cr_amp: 0.5,
self.cr_dur: 800,
self.cr_sigma: 64,
self.cr_risefall: 2,
},
inplace=True,
)
flatten_cx = inline_subroutines(assigned_cx)
with pulse.build(default_alignment="sequential") as ref_cx:
# sz
pulse.shift_phase(np.pi / 2, pulse.DriveChannel(0))
with pulse.align_left():
# sx
pulse.play(
pulse.Drag(
duration=160,
amp=0.1,
sigma=40,
beta=3.0,
),
channel=pulse.DriveChannel(1),
)
with pulse.align_sequential():
# cr
with pulse.align_left():
pulse.play(
pulse.GaussianSquare(
duration=800,
amp=0.5,
sigma=64,
risefall_sigma_ratio=2,
),
channel=pulse.ControlChannel(0),
)
# xp
with pulse.align_left():
pulse.play(
pulse.Drag(
duration=160,
amp=0.2,
sigma=40,
beta=3.0,
),
channel=pulse.DriveChannel(0),
)
with pulse.phase_offset(np.pi, pulse.ControlChannel(0)):
# cr
with pulse.align_left():
pulse.play(
pulse.GaussianSquare(
duration=800,
amp=0.5,
sigma=64,
risefall_sigma_ratio=2,
),
channel=pulse.ControlChannel(0),
)
# xp
with pulse.align_left():
pulse.play(
pulse.Drag(
duration=160,
amp=0.2,
sigma=40,
beta=3.0,
),
channel=pulse.DriveChannel(0),
)
self.assertEqual(flatten_cx, ref_cx)
|
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
from QiskitPBT.case_studies.quantum_teleportation.quantum_teleportation import quantum_teleportation
class NotTeleportedPlus(Property):
# specify the inputs that are to be generated
def get_input_generators(self):
state = RandomState(1)
return [state]
# specify the preconditions for the test
def preconditions(self, q0):
return True
# specify the operations to be performed on the input
def operations(self, q0):
# breaks if classical register is not explicitly defined?
qc = QuantumCircuit(3, 3)
qc.initialize(q0, [0])
qt = quantum_teleportation()
# stitch qc and quantum_teleportation together
qc = qc.compose(qt)
# initialise another circuit to |++> state
# breaks if classical register is not explicitly defined?
qc2 = QuantumCircuit(2, 2)
qc2.h(0)
qc2.h(1)
self.statistical_analysis.assert_equal(self, [0, 1], qc, [0, 1], qc2)
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
from qiskit import QuantumCircuit, transpile
ghz = QuantumCircuit(15)
ghz.h(0)
ghz.cx(0, range(1, 15))
ghz.draw(output='mpl')
|
https://github.com/swe-train/qiskit__qiskit
|
swe-train
|
#!/usr/bin/env python3
# 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.
"""Script to generate 'utility scale' load for profiling in a PGO context"""
import os
from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager
from qiskit.providers.fake_provider import GenericBackendV2
from qiskit.transpiler import CouplingMap
from qiskit import qasm2
QASM_DIR = os.path.join(
os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))),
"test",
"benchmarks",
"qasm",
)
def _main():
cmap = CouplingMap.from_heavy_hex(9)
cz_backend = GenericBackendV2(
cmap.size(),
["rz", "x", "sx", "cz", "id"],
coupling_map=cmap,
control_flow=True,
seed=12345678942,
)
ecr_backend = GenericBackendV2(
cmap.size(),
["rz", "x", "sx", "ecr", "id"],
coupling_map=cmap,
control_flow=True,
seed=12345678942,
)
cx_backend = GenericBackendV2(
cmap.size(),
["rz", "x", "sx", "cx", "id"],
coupling_map=cmap,
control_flow=True,
seed=12345678942,
)
cz_pm = generate_preset_pass_manager(2, cz_backend)
ecr_pm = generate_preset_pass_manager(2, ecr_backend)
cx_pm = generate_preset_pass_manager(2, cx_backend)
qft_circ = qasm2.load(
os.path.join(QASM_DIR, "qft_N100.qasm"),
include_path=qasm2.LEGACY_INCLUDE_PATH,
custom_instructions=qasm2.LEGACY_CUSTOM_INSTRUCTIONS,
custom_classical=qasm2.LEGACY_CUSTOM_CLASSICAL,
strict=False,
)
qft_circ.name = "qft_N100"
square_heisenberg_circ = qasm2.load(
os.path.join(QASM_DIR, "square_heisenberg_N100.qasm"),
include_path=qasm2.LEGACY_INCLUDE_PATH,
custom_instructions=qasm2.LEGACY_CUSTOM_INSTRUCTIONS,
custom_classical=qasm2.LEGACY_CUSTOM_CLASSICAL,
strict=False,
)
square_heisenberg_circ.name = "square_heisenberg_N100"
qaoa_circ = qasm2.load(
os.path.join(QASM_DIR, "qaoa_barabasi_albert_N100_3reps.qasm"),
include_path=qasm2.LEGACY_INCLUDE_PATH,
custom_instructions=qasm2.LEGACY_CUSTOM_INSTRUCTIONS,
custom_classical=qasm2.LEGACY_CUSTOM_CLASSICAL,
strict=False,
)
qaoa_circ.name = "qaoa_barabasi_albert_N100_3reps"
# Uncomment when this is fast enough to run during release builds
# qv_circ = QuantumVolume(100, seed=123456789)
# qv_circ.measure_all()
# qv_circ.name = "QV1267650600228229401496703205376"
for pm in [cz_pm, ecr_pm, cx_pm]:
for circ in [qft_circ, square_heisenberg_circ, qaoa_circ]:
print(f"Compiling: {circ.name}")
pm.run(circ)
if __name__ == "__main__":
_main()
|
https://github.com/daimurat/qiskit-implementation
|
daimurat
|
import sys
sys.path.append('../../')
import numpy as np
from qiskit import QuantumCircuit
from qiskit.opflow import I, X, Y, Z
import matplotlib.pyplot as plt
from volta.observables import sample_hamiltonian
from volta.hamiltonians import BCS_hamiltonian
EPSILONS = [3, 3]
V = -2
hamiltonian = BCS_hamiltonian(EPSILONS, V)
print(hamiltonian)
eigenvalues, _ = np.linalg.eigh(hamiltonian.to_matrix())
print(f"Eigenvalues: {eigenvalues}")
def create_circuit(n: int) -> list:
return [QuantumCircuit(n) for _ in range(2)]
n = hamiltonian.num_qubits
init_states = create_circuit(n)
def copy_unitary(list_states: list) -> list:
out_states = []
for state in list_states:
out_states.append(state.copy())
return out_states
import textwrap
def apply_initialization(list_states: list) -> None:
for ind, state in enumerate(list_states):
b = bin(ind)[2:]
if len(b) != n:
b = '0'*(n - len(b)) + b
spl = textwrap.wrap(b, 1)
for qubit, val in enumerate(spl):
if val == '1':
state.x(qubit)
apply_initialization(init_states)
initialization = copy_unitary(init_states)
from qiskit.circuit.library import TwoLocal
ansatz = TwoLocal(hamiltonian.num_qubits, ['ry','rz'], 'cx', reps=2)
def apply_ansatz(ansatz: QuantumCircuit, list_states: list) -> None:
for states in list_states:
states.append(ansatz, range(n))
apply_ansatz(ansatz, init_states)
init_states[1].draw('mpl')
w = np.arange(n, 0, -1)
w
def _apply_varform_params(ansatz, params: list):
"""Get an hardware-efficient ansatz for n_qubits
given parameters.
"""
# Define variational Form
var_form = ansatz
# Get Parameters from the variational form
var_form_params = sorted(var_form.parameters, key=lambda p: p.name)
# Check if the number of parameters is compatible
assert len(var_form_params) == len(params), "The number of parameters don't match"
# Create a dictionary with the parameters and values
param_dict = dict(zip(var_form_params, params))
# Assing those values for the ansatz
wave_function = var_form.assign_parameters(param_dict)
return wave_function
from qiskit import BasicAer
from qiskit.utils import QuantumInstance
def cost_function(params:list) -> float:
backend = BasicAer.get_backend('qasm_simulator')
backend = QuantumInstance(backend, shots=10000)
cost = 0
# Define Ansatz
for i, state in enumerate(init_states):
qc = _apply_varform_params(state, params)
# Hamiltonian
hamiltonian_eval = sample_hamiltonian(hamiltonian=hamiltonian,
ansatz=qc,
backend=backend)
cost += w[i] * hamiltonian_eval
return cost
from qiskit.aqua.components.optimizers import COBYLA
optimizer = COBYLA(maxiter=1000)
n_parameters = len(init_states[0].parameters)
params = np.random.rand(n_parameters)
optimal_params, mean_energy, n_iters = optimizer.optimize(num_vars=n_parameters,
objective_function=cost_function,
initial_point=params)
mean_energy
# Optimized first ansatz
ansatz_1 = _apply_varform_params(ansatz, optimal_params)
ansatz_1.name = 'U(θ)'
apply_ansatz(ansatz_1, init_states)
init_states[2].draw()
from qiskit.aqua import QuantumInstance
def cost_function_ind(ind: int, params:list) -> float:
backend = BasicAer.get_backend('qasm_simulator')
backend = QuantumInstance(backend, shots=10000)
cost = 0
# Define Ansatz
qc = _apply_varform_params(init_states[ind], params)
# Hamiltonian
hamiltonian_eval = sample_hamiltonian(hamiltonian=hamiltonian,
ansatz=qc,
backend=backend)
cost += hamiltonian_eval
return - cost
from functools import partial
cost = partial(cost_function_ind, 2)
n_parameters = len(init_states[0].parameters)
params = np.random.rand(n_parameters)
optimal_params, energy_gs, n_iters = optimizer.optimize(num_vars=n_parameters,
objective_function=cost,
initial_point=params)
energy_gs
eigenvalues
# Optimized second ansatz
ansatz_2 = _apply_varform_params(ansatz, optimal_params)
ansatz_2.name = 'V(ϕ)'
|
https://github.com/deadshot8086/quantum-grover-boolean-sat
|
deadshot8086
|
from qiskit import QuantumCircuit, Aer, execute
from math import pi, sin
from qiskit.compiler import transpile, assemble
from grover_operator import GroverOperator
def qft(n): # returns circuit for inverse quantum fourier transformation for given n
circuit = QuantumCircuit(n)
def swap_registers(circuit, n):
for qubit in range(n // 2):
circuit.swap(qubit, n - qubit - 1)
return circuit
def qft_rotations(circuit, n):
if n == 0:
return circuit
n -= 1
circuit.h(n)
for qubit in range(n):
circuit.cp(pi / 2 ** (n - qubit), qubit, n)
qft_rotations(circuit, n)
qft_rotations(circuit, n)
swap_registers(circuit, n)
return circuit
class PhaseEstimation:
def get_control_gft(self, label="QFT †"):
qft_dagger = self.qft_circuit.to_gate().inverse()
qft_dagger.label = label
return qft_dagger
def get_main_circuit(self):
qc = QuantumCircuit(self.c_bits + self.s_bits, self.c_bits) # Circuit with n+t qubits and t classical bits
# Initialize all qubits to |+>
qc.h(range(self.c_bits + self.n_bits))
qc.h(self.c_bits + self.s_bits - 1)
qc.z(self.c_bits + self.s_bits - 1)
# Begin controlled Grover iterations
iterations = 1
for qubit in range(self.c_bits):
for i in range(iterations):
qc.append(self.c_grover, [qubit] + [*range(self.c_bits, self.s_bits + self.c_bits)])
iterations *= 2
# Do inverse QFT on counting qubits
qc.append(self.c_qft, range(self.c_bits))
# Measure counting qubits
qc.measure(range(self.c_bits), range(self.c_bits))
return qc
def simulate(self):
aer_sim = Aer.get_backend('aer_simulator')
transpiled_qc = transpile(self.main_circuit, aer_sim)
qobj = assemble(transpiled_qc)
job = aer_sim.run(qobj)
hist = job.result().get_counts()
# plot_histogram(hist)
measured_int = int(max(hist, key=hist.get), 2)
theta = (measured_int / (2 ** self.c_bits)) * pi * 2
N = 2 ** self.n_bits
M = N * (sin(theta / 2) ** 2)
# print(N - M, round(N - M))
return round(N - M)
def __init__(self, grover: GroverOperator, c_bits=5):
self.c_grover = grover.get_control_circuit()
self.c_bits = c_bits
self.n_bits = grover.n_bits
self.s_bits = grover.total_bits
self.qft_circuit = qft(c_bits)
self.c_qft = self.get_control_gft()
self.main_circuit = self.get_main_circuit()
self.M = self.simulate()
|
https://github.com/matteoacrossi/oqs-jupyterbook
|
matteoacrossi
|
from qiskit import QuantumRegister, QuantumCircuit
import numpy as np
#######################
# ZZ pump on IBMQX2 #
#######################
# Quantum register
q = QuantumRegister(5, name='q')
# Quantum circuit
zz = QuantumCircuit(q)
# ZZ pump acting on system qubits
## Qubit identification
system = [2, 1]
a_zz = 0
## Define pump efficiency
## and corresponding rotation
p = 0.5
theta = 2 * np.arcsin(np.sqrt(p))
## Construct circuit
### Map information to ancilla
zz.cx(q[system[0]], q[system[1]])
zz.x(q[a_zz])
zz.cx(q[system[1]], q[a_zz])
### Conditional rotation
zz.cu3(theta, 0.0, 0.0, q[a_zz], q[system[1]])
### Inverse mapping
zz.cx(q[system[1]], q[a_zz])
zz.cx(q[system[0]], q[system[1]])
# Draw circuit
zz.draw(output='mpl')
#######################
# XX pump on IBMQX2 #
#######################
# Quantum register
q = QuantumRegister(5, name='q')
# Quantum circuit
xx = QuantumCircuit(q)
# XX pump acting on system qubits
## Qubit identification
system = [2, 1]
a_xx = 4
## Define pump efficiency
## and corresponding rotation
p = 0.5
theta = 2 * np.arcsin(np.sqrt(p))
## Construct circuit
### Map information to ancilla
xx.cx(q[system[0]], q[system[1]])
xx.h(q[system[0]])
xx.x(q[a_xx])
xx.cx(q[system[0]], q[a_xx])
### Conditional rotation
xx.cu3(theta, 0.0, 0.0, q[a_xx], q[system[0]])
### Inverse mapping
xx.cx(q[system[0]], q[a_xx])
xx.h(q[system[0]])
xx.cx(q[system[0]], q[system[1]])
# Draw circuit
xx.draw(output='mpl')
###########################
# ZZ-XX pumps on IBMQX2 #
###########################
# Quantum register
q = QuantumRegister(5, name='q')
# Quantum circuit
zz_xx = QuantumCircuit(q)
# ZZ and XX pumps acting on system qubits
## Qubit identification
system = [2, 1]
a_zz = 0
a_xx = 4
## Define pump efficiency
## and corresponding rotation
p = 0.5
theta = 2 * np.arcsin(np.sqrt(p))
## Construct circuit
## ZZ pump
### Map information to ancilla
zz_xx.cx(q[system[0]], q[system[1]])
zz_xx.x(q[a_zz])
zz_xx.cx(q[system[1]], q[a_zz])
### Conditional rotation
zz_xx.cu3(theta, 0.0, 0.0, q[a_zz], q[system[1]])
### Inverse mapping
zz_xx.cx(q[system[1]], q[a_zz])
#zz_xx.cx(q[system[0]], q[system[1]])
## XX pump
### Map information to ancilla
#zz_xx.cx(q[system[0]], q[system[1]])
zz_xx.h(q[system[0]])
zz_xx.x(q[a_xx])
zz_xx.cx(q[system[0]], q[a_xx])
### Conditional rotation
zz_xx.cu3(theta, 0.0, 0.0, q[a_xx], q[system[0]])
### Inverse mapping
zz_xx.cx(q[system[0]], q[a_xx])
zz_xx.h(q[system[0]])
zz_xx.cx(q[system[0]], q[system[1]])
# Draw circuit
zz_xx.draw(output='mpl')
def zz_pump(q, c, p, system, ancilla):
"""Returns a QuantumCircuit implementing the ZZ pump channel on the system qubits
Args:
q (QuantumRegister): the register to use for the circuit
c (ClassicalRegister): the register to use for the measurement of the system qubits
p (float): the efficiency for the channel, between 0 and 1
system (list): list of indices for the system qubits
ancilla (int): index for the ancillary qubit
Returns:
A QuantumCircuit object
"""
def xx_pump(q, c, p, system, ancilla):
"""Returns a QuantumCircuit implementing the XX pump channel on the system qubits
Args:
q (QuantumRegister): the register to use for the circuit
c (ClassicalRegister): the register to use for the measurement of the system qubits
p (float): the efficiency for the channel, between 0 and 1
system (list): list of indices for the system qubits
ancilla (int): index for the ancillary qubit
Returns:
A QuantumCircuit object
"""
def zz_xx_pump(q, c, p, system, ancillae):
"""Returns a QuantumCircuit implementing the composition channel on the system qubits
Args:
q (QuantumRegister): the register to use for the circuit
c (ClassicalRegister): the register to use for the measurement of the system qubits
p (float): the efficiency for both channels, between 0 and 1
system (list): list of indices for the system qubits
ancillae (list): list of indices for the ancillary qubits
Returns:
A QuantumCircuit object
"""
|
https://github.com/shesha-raghunathan/DATE2019-qiskit-tutorial
|
shesha-raghunathan
|
import matplotlib.pyplot as plt
import numpy as np
import sklearn
import sklearn.datasets
import sklearn.metrics
%matplotlib inline
metric = sklearn.metrics.accuracy_score
np.random.seed(0)
data, labels = sklearn.datasets.make_circles()
idx = np.arange(len(labels))
np.random.shuffle(idx)
# train on a random 2/3 and test on the remaining 1/3
idx_train = idx[:2*len(idx)//3]
idx_test = idx[2*len(idx)//3:]
X_train = data[idx_train]
X_test = data[idx_test]
y_train = 2 * labels[idx_train] - 1 # binary -> spin
y_test = 2 * labels[idx_test] - 1
scaler = sklearn.preprocessing.StandardScaler()
normalizer = sklearn.preprocessing.Normalizer()
X_train = scaler.fit_transform(X_train)
X_train = normalizer.fit_transform(X_train)
X_test = scaler.fit_transform(X_test)
X_test = normalizer.fit_transform(X_test)
plt.figure(figsize=(6, 6))
plt.subplot(111, xticks=[], yticks=[])
plt.scatter(data[labels == 0, 0], data[labels == 0, 1], color='navy')
plt.scatter(data[labels == 1, 0], data[labels == 1, 1], color='c');
from sklearn.linear_model import Perceptron
model_1 = Perceptron()
model_1.fit(X_train, y_train)
print('accuracy (train): %5.2f'%(metric(y_train, model_1.predict(X_train))))
print('accuracy (test): %5.2f'%(metric(y_test, model_1.predict(X_test))))
from sklearn.svm import SVC
model_2 = SVC(kernel='rbf')
model_2.fit(X_train, y_train)
print('accuracy (train): %5.2f'%(metric(y_train, model_2.predict(X_train))))
print('accuracy (test): %5.2f'%(metric(y_test, model_2.predict(X_test))))
from sklearn.ensemble import AdaBoostClassifier
model_3 = AdaBoostClassifier(n_estimators=3)
model_3.fit(X_train, y_train)
print('accuracy (train): %5.2f'%(metric(y_train, model_3.predict(X_train))))
print('accuracy (test): %5.2f'%(metric(y_test, model_3.predict(X_test))))
models = [model_1, model_2, model_3]
n_models = len(models)
predictions = np.array([h.predict(X_train) for h in models], dtype=np.float64)
# scale hij to [-1/N, 1/N]
predictions *= 1/n_models
λ = 1
w = np.dot(predictions, predictions.T)
wii = len(X_train) / (n_models ** 2) + λ - 2 * np.dot(predictions, y_train)
w[np.diag_indices_from(w)] = wii
W = {}
for i in range(n_models):
for j in range(i, n_models):
W[(i, j)] = w[i, j]
import dimod
sampler = dimod.SimulatedAnnealingSampler()
response = sampler.sample_qubo(W, num_reads=10)
weights = list(response.first.sample.values())
def predict(models, weights, X):
n_data = len(X)
T = 0
y = np.zeros(n_data)
for i, h in enumerate(models):
y0 = weights[i] * h.predict(X) # prediction of weak classifier
y += y0
T += np.sum(y0)
y = np.sign(y - T / (n_data*len(models)))
return y
print('accuracy (train): %5.2f'%(metric(y_train, predict(models, weights, X_train))))
print('accuracy (test): %5.2f'%(metric(y_test, predict(models, weights, X_test))))
weights
h, J, offset = dimod.qubo_to_ising(W)
from qiskit.quantum_info import Pauli
from qiskit_aqua import Operator
num_nodes = w.shape[0]
pauli_list = []
for i in range(num_nodes):
wp = np.zeros(num_nodes)
vp = np.zeros(num_nodes)
vp[i] = 1
pauli_list.append([h[i], Pauli(vp, wp)])
for j in range(i+1, num_nodes):
if w[i, j] != 0:
wp = np.zeros(num_nodes)
vp = np.zeros(num_nodes)
vp[i] = 1
vp[j] = 1
pauli_list.append([J[i, j], Pauli(vp, wp)])
ising_model = Operator(paulis=pauli_list)
from qiskit_aqua import get_aer_backend, QuantumInstance
from qiskit_aqua.algorithms import QAOA
from qiskit_aqua.components.optimizers import COBYLA
p = 1
optimizer = COBYLA()
qaoa = QAOA(ising_model, optimizer, p, operator_mode='matrix')
backend = get_aer_backend('statevector_simulator')
quantum_instance = QuantumInstance(backend, shots=100)
result = qaoa.run(quantum_instance)
k = np.argmax(result['eigvecs'][0])
weights = np.zeros(num_nodes)
for i in range(num_nodes):
weights[i] = k % 2
k >>= 1
weights
print('accuracy (train): %5.2f'%(metric(y_train, predict(models, weights, X_train))))
print('accuracy (test): %5.2f'%(metric(y_test, predict(models, weights, X_test))))
|
https://github.com/qiskit-community/qiskit-translations-staging
|
qiskit-community
|
import numpy as np
from qiskit_nature.second_q.hamiltonians import QuadraticHamiltonian
# create Hamiltonian
hermitian_part = np.array(
[
[1.0, 2.0, 0.0, 0.0],
[2.0, 1.0, 2.0, 0.0],
[0.0, 2.0, 1.0, 2.0],
[0.0, 0.0, 2.0, 1.0],
]
)
antisymmetric_part = np.array(
[
[0.0, 3.0, 0.0, 0.0],
[-3.0, 0.0, 3.0, 0.0],
[0.0, -3.0, 0.0, 3.0],
[0.0, 0.0, -3.0, 0.0],
]
)
constant = 4.0
hamiltonian = QuadraticHamiltonian(
hermitian_part=hermitian_part,
antisymmetric_part=antisymmetric_part,
constant=constant,
)
# convert it to a FermionicOp and print it
hamiltonian_ferm = hamiltonian.second_q_op()
print(hamiltonian_ferm)
# get the transformation matrix W and orbital energies {epsilon_j}
(
transformation_matrix,
orbital_energies,
transformed_constant,
) = hamiltonian.diagonalizing_bogoliubov_transform()
print(f"Shape of matrix W: {transformation_matrix.shape}")
print(f"Orbital energies: {orbital_energies}")
print(f"Transformed constant: {transformed_constant}")
from qiskit_nature.second_q.circuit.library import FermionicGaussianState
occupied_orbitals = (0, 2)
eig = np.sum(orbital_energies[list(occupied_orbitals)]) + transformed_constant
print(f"Eigenvalue: {eig}")
circuit = FermionicGaussianState(transformation_matrix, occupied_orbitals=occupied_orbitals)
circuit.draw("mpl")
from qiskit.quantum_info import Statevector
from qiskit_nature.second_q.mappers import JordanWignerMapper
# simulate the circuit to get the final state
state = np.array(Statevector(circuit))
# convert the Hamiltonian to a matrix
hamiltonian_jw = JordanWignerMapper().map(hamiltonian_ferm).to_matrix()
# check that the state is an eigenvector with the expected eigenvalue
np.testing.assert_allclose(hamiltonian_jw @ state, eig * state, atol=1e-8)
# create Hamiltonian
hermitian_part = np.array(
[
[1.0, 2.0, 0.0, 0.0],
[2.0, 1.0, 2.0, 0.0],
[0.0, 2.0, 1.0, 2.0],
[0.0, 0.0, 2.0, 1.0],
]
)
constant = 4.0
hamiltonian = QuadraticHamiltonian(
hermitian_part=hermitian_part,
constant=constant,
)
print(f"Hamiltonian conserves particle number: {hamiltonian.conserves_particle_number()}")
# get the transformation matrix W and orbital energies {epsilon_j}
(
transformation_matrix,
orbital_energies,
transformed_constant,
) = hamiltonian.diagonalizing_bogoliubov_transform()
print(f"Shape of matrix W: {transformation_matrix.shape}")
print(f"Orbital energies: {orbital_energies}")
print(f"Transformed constant: {transformed_constant}")
from qiskit_nature.second_q.circuit.library import SlaterDeterminant
occupied_orbitals = (0, 2)
eig = np.sum(orbital_energies[list(occupied_orbitals)]) + transformed_constant
print(f"Eigenvalue: {eig}")
circuit = SlaterDeterminant(transformation_matrix[list(occupied_orbitals)])
circuit.draw("mpl")
from qiskit_nature.second_q.circuit.library import BogoliubovTransform
from qiskit import QuantumCircuit, QuantumRegister
from qiskit.quantum_info import random_hermitian, random_statevector, state_fidelity
from scipy.linalg import expm
# create Hamiltonian
n_modes = 5
hermitian_part = np.array(random_hermitian(n_modes))
hamiltonian = QuadraticHamiltonian(hermitian_part=hermitian_part)
# diagonalize Hamiltonian
(
transformation_matrix,
orbital_energies,
_,
) = hamiltonian.diagonalizing_bogoliubov_transform()
# set simulation time and construct time evolution circuit
time = 1.0
register = QuantumRegister(n_modes)
circuit = QuantumCircuit(register)
bog_circuit = BogoliubovTransform(transformation_matrix)
# change to the diagonal basis of the Hamiltonian
circuit.append(bog_circuit.inverse(), register)
# perform time evolution by applying z rotations
for q, energy in zip(register, orbital_energies):
circuit.rz(-energy * time, q)
# change back to the original basis
circuit.append(bog_circuit, register)
# simulate the circuit
initial_state = random_statevector(2**n_modes)
final_state = initial_state.evolve(circuit)
# compute the correct state by direct exponentiation
hamiltonian_jw = JordanWignerMapper().map(hamiltonian.second_q_op()).to_matrix()
exact_evolution_op = expm(-1j * time * hamiltonian_jw)
expected_state = exact_evolution_op @ np.array(initial_state)
# check that the simulated state is correct
fidelity = state_fidelity(final_state, expected_state)
np.testing.assert_allclose(fidelity, 1.0, atol=1e-8)
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
|
https://github.com/askolik/quantum_gym_qiskit
|
askolik
|
import copy
import random
from collections import deque, namedtuple
import numpy as np
import matplotlib.pyplot as plt
import gym
import torch
from qiskit import Aer
from qiskit import QuantumCircuit
from qiskit.utils import QuantumInstance
from qiskit.circuit import Parameter
from qiskit.opflow import StateFn, PauliSumOp, ListOp
from qiskit_machine_learning.neural_networks import OpflowQNN
from qiskit_machine_learning.connectors import TorchConnector
from torch import Tensor
from torch.nn import Parameter as TorchParameter
from torch.optim import Adam
def build_quantum_model(n_qubits, n_layers):
circuit = QuantumCircuit(n_qubits)
data_params = [Parameter(f'x_{i}') for i in range(n_qubits)]
data_weight_params = [Parameter(f'd_{i}') for i in range(n_qubits)]
trainable_params = data_weight_params
for layer in range(n_layers):
for qubit in range(n_qubits):
circuit.rx(data_params[qubit] * data_weight_params[qubit], qubit)
var_param_y = Parameter(f't_y_{layer}_{qubit}')
var_param_z = Parameter(f't_z_{layer}_{qubit}')
trainable_params += [var_param_y, var_param_z]
circuit.ry(var_param_y, qubit)
circuit.rz(var_param_z, qubit)
for qubit in range(n_qubits):
circuit.cz(qubit, (qubit+1) % n_qubits)
circuit.barrier()
for qubit in range(n_qubits):
var_param_y = Parameter(f't_y_{n_layers}_{qubit}')
var_param_z = Parameter(f't_z_{n_layers}_{qubit}')
trainable_params += [var_param_y, var_param_z]
circuit.ry(var_param_y, qubit)
circuit.rz(var_param_z, qubit)
# circuit.draw(output='mpl', filename='my_circuit.png')
print(circuit)
return circuit, trainable_params, data_params
def build_readout_ops(agent):
action_left = PauliSumOp.from_list([('ZZII', 1.0)])
action_right = PauliSumOp.from_list([('IIZZ', 1.0)])
readout_op = ListOp([
~StateFn(action_left) @ StateFn(agent),
~StateFn(action_right) @ StateFn(agent)
])
return readout_op
def compute_q_vals(states, model, observable_weights, grad=True):
scaled_states = []
for state in states:
scaled_states.append([np.arctan(s) for s in state])
states_tensor = Tensor(states)
if grad:
print('batch size:', len(states_tensor))
res = model(states_tensor)
else:
with torch.no_grad():
res = model(states_tensor)
q_vals = (res + 1) / 2
q_vals[:, 0] *= observable_weights[0]
q_vals[:, 1] *= observable_weights[1]
# print("Q0", q_vals[:, 0], observable_weights[0])
# print("Q1", q_vals[:, 1], observable_weights[1])
return q_vals
def train_step(
memory,
model,
target_model,
batch_size,
observable_weights,
target_observable_weights,
model_optimizer,
observables_optimizer,
loss,
gamma):
model_optimizer.zero_grad()
observables_optimizer.zero_grad()
transitions = random.sample(memory, batch_size)
batch_memories = Transition(*zip(*transitions))
batch_states = batch_memories.state
batch_actions = batch_memories.action
batch_next_states = batch_memories.next_state
batch_done = batch_memories.done
batch_rewards = np.ones(batch_size)
action_masks = []
one_hot_actions = {0: [1, 0], 1: [0, 1]}
for action in batch_actions:
action_masks.append(one_hot_actions[action])
q_vals = compute_q_vals(
batch_states, model, observable_weights)
q_vals_next = compute_q_vals(
batch_next_states, target_model, target_observable_weights, grad=False)
target_q_vals = torch.Tensor(batch_rewards) + torch.Tensor(
np.ones(batch_size) * gamma) * torch.max(q_vals_next, 1).values * (1 - torch.Tensor(batch_done))
reduced_q_vals = torch.sum(q_vals * torch.Tensor(action_masks), dim=1)
error = loss(reduced_q_vals, target_q_vals)
error.backward()
model_optimizer.step()
observables_optimizer.step()
# set up Qiskit backend and Gym
backend = Aer.get_backend('statevector_simulator')
quantum_instance = QuantumInstance(backend)
env = gym.make("CartPole-v0")
# set hyperparameters for deep Q-learning
n_qubits = 4
n_layers = 5
batch_size = 16
gamma = 0.99 # Q-learning discount factor
epsilon = 1.0 # epsilon greedy policy initial value
epsilon_min = 0.01 # minimum value of epsilon
epsilon_decay = 0.99 # decay rate of epsilon
n_episodes = 3000
batch_size = 16
update_qnet_after = 1 # agent update interval
update_target_after = 1 # target network update interval
# set up replay memory
Transition = namedtuple('Transition', (
'state', 'action', 'next_state', 'done'))
max_memory_len = 10000
replay_memory = deque(maxlen=max_memory_len)
grad_method ='param_shift'
# grad_method ='fin_diff'
# set up model
agent, params, data_params = build_quantum_model(n_qubits, n_layers)
observable_weights = TorchParameter(Tensor([1, 1]))
readout_op = build_readout_ops(agent)
qnn = OpflowQNN(
readout_op, data_params, params, quantum_instance=quantum_instance)
model = TorchConnector(qnn)
# set up target model that is used to compute target Q-values
# (not trained, only updated with Q-model's parameters at fixed intervals)
target_agent, target_params, target_data_params = build_quantum_model(n_qubits, n_layers)
target_observable_weights = Tensor([1, 1])
target_readout_op = build_readout_ops(target_agent)
target_qnn = OpflowQNN(
target_readout_op, target_data_params, target_params, quantum_instance=quantum_instance)
target_model = TorchConnector(target_qnn)
target_model.load_state_dict(model.state_dict())
# set up optimizers
model_optimizer = Adam(model.parameters(), lr=0.001)
observables_optimizer = Adam([observable_weights], lr=0.1)
loss = torch.nn.SmoothL1Loss()
episode_rewards = [0]
for episode in range(n_episodes):
episode_reward = 0
state = env.reset()
for time_step in range(200):
# choose action based on epsilon greedy policy
if random.random() > epsilon:
with torch.no_grad():
q_vals = compute_q_vals([state], model, observable_weights)
action = int(torch.argmax(q_vals).numpy())
print("\tagent chose action")
else:
action = np.random.choice(2)
# take step in environment and collect reward
next_state, reward, done, _ = env.step(action)
episode_reward += 1
# store transition in memory (without reward as it is always 1)
replay_memory.append(Transition(state, action, next_state, int(done)))
# perform one step of parameter updates
if len(replay_memory) > batch_size and time_step % update_qnet_after == 0:
train_step(
replay_memory,
model,
target_model,
batch_size,
observable_weights,
target_observable_weights,
model_optimizer,
observables_optimizer,
loss,
gamma)
# update target model parameters
if time_step % update_target_after == 0:
with torch.no_grad():
target_model.load_state_dict(model.state_dict())
target_observable_weights = copy.deepcopy(observable_weights.data)
if done:
break
episode_rewards.append(episode_reward)
epsilon = max(epsilon_min, epsilon * epsilon_decay)
print(f'Episode {episode}, episode reward: {episode_reward}, average reward: {np.mean(episode_rewards[-100:])}')
plt.plot(episode_rewards)
plt.ylabel("Score")
plt.xlabel("Episode")
plt.show()
|
https://github.com/soultanis/Quantum-SAT-Solver
|
soultanis
|
import pylab
import numpy as np
from qiskit.providers.ibmq import least_busy
from qiskit import LegacySimulators, execute, IBMQ, Aer
from qiskit.tools.visualization import plot_histogram
from qiskit_aqua import QuantumInstance
from qiskit_aqua import run_algorithm
from qiskit_aqua.algorithms import Grover
from qiskit_aqua.components.oracles import SAT
satProblem = '3sat2-3.cnf'
with open(satProblem, 'r') as f:
sat_cnf = f.read()
print(sat_cnf)
sat_oracle = SAT(sat_cnf)
algorithm = Grover(sat_oracle)
backend = Aer.get_backend('qasm_simulator')
algorithm = Grover(sat_oracle)
result = algorithm.run(backend)
print(result['result'])
plot_histogram(result['measurements'])
params = {
'problem': {'name': 'search'},
'algorithm': {
'name': 'Grover'
},
'oracle': {
'name': 'SAT',
'cnf': sat_cnf
},
'backend': {
'shots': 100
}
}
result_dict = run_algorithm(params, backend=backend)
plot_histogram(result_dict['measurements'])
# Authenticate for access to remote backends
try:
import Qconfig
IBMQ.load_accounts()
except:
print("""WARNING: There's no connection with the API for remote backends.
Have you initialized a file with your personal token?
For now, there's only access to local simulator backends...""")
backend = least_busy(IBMQ.backends(simulator=False))
algorithm = Grover(sat_oracle)
result = algorithm.run(backend)
print(result['result'])
|
https://github.com/obliviateandsurrender/Quantum-Approximate-Thermalization
|
obliviateandsurrender
|
# Libraries Import
import itertools
import numpy as np
from functools import reduce, partial
from scipy.optimize import minimize
import matplotlib.pyplot as plt
%matplotlib inline
# Qiskit
from qiskit import BasicAer, QuantumRegister, QuantumCircuit, ClassicalRegister
from qiskit import execute
from qiskit.quantum_info import Pauli
from qiskit.aqua import get_aer_backend, QuantumInstance, Operator
from qiskit.aqua.components.initial_states import Custom
backend = BasicAer.get_backend('qasm_simulator')
class QAT:
def __init__(self, num_qubit, temp, weights, qaoa_step=1):
self.num_qubits = num_qubit
self.num_system = num_qubit*2
self.T = temp
self.weights = weights
self.p = qaoa_step
self.Hc = None
self.Hm = None
self.qr = None
self.cr = None
def pauli_x(self, qubit, coeff):
return Operator([[coeff, Pauli(np.zeros(self.num_qubits), np.eye((self.num_qubits))[qubit])]])
def product_pauli_z(self, q1, q2, coeff):
return Operator([[coeff, Pauli(np.eye((self.num_system))[q1], np.zeros(self.num_system)) * \
Pauli(np.eye((self.num_system))[q2], np.zeros(self.num_system))]])
def ising_hamiltonian(self):
Hc = reduce(lambda x,y:x+y,
[self.product_pauli_z(i,j, -self.weights[i,j])
for (i,j) in itertools.product(range(self.num_qubits), range(self.num_qubits))])
Hm = reduce(lambda x, y: x+y,
[self.pauli_x(i, 1) for i in range(self.num_qubits)])
Hc.to_matrix(),
Hm.to_matrix()
return Hc, Hm
def prepare_init_state(self):
self.qr = QuantumRegister(self.num_system)
self.cr = ClassicalRegister(self.num_qubits)
circuit_init = QuantumCircuit(self.qr, self.cr)
for i in range(self.num_qubits):
circuit_init.rx( 2 * np.arctan(np.exp(- 1/self.T)), self.num_qubits+i)
circuit_init.cx(self.num_qubits+i, i)
return circuit_init
def evolve(self, hamiltonian, angle, quantum_registers):
return hamiltonian.evolve(None, angle, 'circuit', 1, quantum_registers=quantum_registers,
expansion_mode='suzuki', expansion_order=3)
def evaluate_circuit(self, beta_gamma, circuit_init):
p = len(beta_gamma)//2
beta = beta_gamma[:p]; gamma = beta_gamma[p:]
#print(self.Hc, self.Hm)
circuit = circuit_init + reduce(lambda x,y: x+y, [self.evolve(self.Hc, beta[i], self.qr) + \
self.evolve(self.Hm, gamma[i], self.qr) for i in range(p)])
return np.real(self.Hc.eval("matrix", circuit, get_aer_backend('statevector_simulator'))[0])
def get_thermal_state(self):
#print(self.ising_hamiltonian())
self.Hc, self.Hm = self.ising_hamiltonian()
#print(self.Hc,self.Hm)
circuit_init = self.prepare_init_state()
beta_init = np.random.uniform(0, np.pi*2, self.p)
gamma_init = np.random.uniform(0, np.pi*2, self.p)
evaluate = partial(self.evaluate_circuit, circuit_init=circuit_init)
result = minimize(evaluate, np.concatenate([beta_init, gamma_init]), method='L-BFGS-B')
beta = result['x'][:self.p]; gamma = result['x'][self.p:]
circuit = circuit_init + reduce(lambda x,y: x+y, [self.evolve(self.Hc, beta[i], self.qr) + \
self.evolve(self.Hm, gamma[i], self.qr) for i in range(p)])
return result["fun"], circuit
def get_energy(self, spin_configuration):
x = spin_configuration.reshape(-1, 1)
return np.sum([[-self.weights[i,j] * x[i] * x[j] \
for j in range(self.num_qubits)] for i in range(self.num_qubits)])
def get_energy_distribution(self, thermal_state):
for i in range(self.num_qubits):
thermal_state.measure(self.qr[i], self.cr[i])
job = execute(thermal_state, backend, shots=1000)
results = job.result().get_counts(thermal_state)
list_spin_configs = np.array(np.concatenate([[list(spin_config)] *\
results[spin_config] \
for spin_config in results]), dtype="int")
list_spin_configs[list_spin_configs == 0] = -1
list_energy = np.array([self.get_energy(spin_config) for spin_config in list_spin_configs])
return list_energy
if __name__ == "__main__":
weights = np.array([[0,1,0],[0,0,1],[0,0,1]])
p = 5
r = QAT(3, 1000, weights, p)
cost, thermal_state = r.get_thermal_state()
hist = plt.hist(r.get_energy_distribution(thermal_state), density=True)
|
https://github.com/IlliaOvcharenko/quantum-search
|
IlliaOvcharenko
|
import sys, os
sys.path.append(os.getcwd())
import matplotlib
matplotlib.use('Agg')
import math
import numpy as np
import matplotlib.pyplot as plt
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit.primitives.sampler import Sampler
from fire import Fire
def run_quantum_search(
array_len: int | None = None,
n_grover_iterations: int | None = None,
):
np.random.seed(42)
array = np.arange(array_len)
np.random.shuffle(array)
item = np.random.choice(array)
array = array.tolist()
print(f"Input array: {array}")
print(f"Item to search: {item}")
print(f"Correct answer should be: {array.index(item)}")
n_index_qbits = math.ceil(math.log(len(array), 2))
n_value_qbits = math.ceil(math.log(max(array), 2))
to_bits = lambda i: bin(i)[2:][::-1]
to_int = lambda b: int(b[::-1], 2)
index_qbits = [i for i in range(n_index_qbits)]
value_qbits = [i + n_index_qbits for i in range(n_value_qbits)]
phase_qbit = n_index_qbits + n_value_qbits
if n_grover_iterations is None:
n_grover_iterations = math.floor(math.sqrt(len(array)))
qc = QuantumCircuit(
QuantumRegister(n_index_qbits, "index"),
QuantumRegister(n_value_qbits, "value"),
QuantumRegister(1, "phase"),
icr := ClassicalRegister(n_index_qbits, "meas-index"),
)
qc.h(index_qbits)
qc.x(phase_qbit)
qc.h(phase_qbit)
def add_oracle(global_qc):
qc = QuantumCircuit(
QuantumRegister(n_index_qbits, "index"),
QuantumRegister(n_value_qbits, "value"),
QuantumRegister(1, "phase"),
)
for array_idx in range(len(array)):
qc.barrier()
array_idx_bit = to_bits(array_idx)[:n_index_qbits]
array_idx_bit += "0" * (n_index_qbits - len(array_idx_bit))
array_item = array[array_idx]
array_item_bit = to_bits(array_item)[:n_value_qbits]
array_item_bit += "0" * (n_value_qbits - len(array_item_bit))
zeros = [index_qbits[i] for i, b in enumerate(array_idx_bit) if b == "0"]
ones = [value_qbits[i] for i, b in enumerate(array_item_bit) if b == "1"]
for value_idx in ones:
if zeros:
qc.x(zeros)
qc.mcx(index_qbits, value_idx)
if zeros:
qc.x(zeros)
global_qc = global_qc.compose(qc)
item_bit = to_bits(item)
item_bit += "0" * (n_value_qbits - len(item_bit))
zeros = [value_qbits[i] for i, b in enumerate(item_bit) if b == "0"]
if zeros:
global_qc.x(zeros)
global_qc.mcx(value_qbits, phase_qbit)
if zeros:
global_qc.x(zeros)
global_qc = global_qc.compose(qc.inverse())
return global_qc
def add_diffuser(global_qc):
qc = QuantumCircuit(
QuantumRegister(n_index_qbits, "index"),
QuantumRegister(n_value_qbits, "value"),
QuantumRegister(1, "phase"),
)
qc.h(index_qbits)
qc.x(index_qbits)
qc.mcx(index_qbits, phase_qbit)
qc.x(index_qbits)
qc.h(index_qbits)
global_qc = global_qc.compose(qc)
return global_qc
for _ in range(n_grover_iterations):
qc = add_oracle(qc)
qc = add_diffuser(qc)
qc.measure(index_qbits, icr)
sampler = Sampler()
job = sampler.run(qc, shots=64)
result = job.result()
index_dist = result.quasi_dists[0]
index_pred = max(index_dist.items(), key=lambda x: x[1])
print(f"Search result, index: {index_pred[0]}, " \
f"empirical prob to collapse in this state: {index_pred[1]}")
print(f"Prob to collapse into a correct state: {index_dist[array.index(item)]}")
print()
return index_pred
import psutil
import os
import gc
from datetime import datetime
from functools import partial
class MeasureResult:
def __init__(self, return_value, func_name = None):
self.return_value = return_value
self.measurements = {}
self.func_name = func_name
def print(self):
if self.func_name:
print(f"func: {self.func_name}")
for k, v in self.measurements.items():
print(f"\t{k} - {v}")
print()
# def __call__():
# return self.func()
def get_func_name(f):
if isinstance(f, partial):
return f.func.__name__ + " with args " + str(f.args) + " with kwargs " + str(f.keywords)
return f.__name__
def define_name(name, measurements, depth=0):
try_name = name
if depth != 0:
try_name += f"_{depth}"
if try_name in measurements:
return define_name(name, measurements, depth=depth+1)
else:
return try_name
def measure_exec_time(f):
def nested_func():
start_t = datetime.now().timestamp()
rv = f()
end_t = datetime.now().timestamp()
exec_time = end_t - start_t
if not isinstance(rv, MeasureResult):
rv = MeasureResult(rv, func_name=get_func_name(f))
measure_name = define_name("exec_time", rv.measurements)
rv.measurements[measure_name] = exec_time
return rv
return nested_func
def measure_ram_usage(f):
def nested_func():
pid = os.getpid()
current_process = psutil.Process(pid)
start_ram = current_process.memory_info().rss / (1024 * 1024)
# print(start_ram)
# exit(0)
rv = f()
end_ram = current_process.memory_info().rss / (1024 * 1024)
ram_usage = end_ram - start_ram
if not isinstance(rv, MeasureResult):
rv = MeasureResult(rv, func_name=get_func_name(f))
measure_name = define_name("ram_usage", rv.measurements)
rv.measurements[measure_name] = ram_usage
return rv
return nested_func
def apply_measurements(f, ms):
m = ms.pop()
if not ms:
return m(f)
return apply_measurements(m(f), ms)
def print_measure(f):
def nested_func():
rv = f()
if isinstance(rv, MeasureResult):
rv.print()
else:
print(f"there is nothing to print yet :(")
return rv
return nested_func
def plot_with_number_of_input_data():
array_len_param = [v for v in range(10, 71, 10)]
# array_len_param = [v for v in range(10, 31, 10)]
print(array_len_param)
measurements = []
for al in array_len_param:
run_quantum_search_with_measurements = apply_measurements(
partial(run_quantum_search, array_len=al),
[print_measure, measure_exec_time, measure_ram_usage, measure_exec_time],
)
meas = run_quantum_search_with_measurements()
measurements.append(meas)
gc.collect()
plt.figure(figsize=(15, 10))
plt.plot(array_len_param, [m.measurements["exec_time"] for m in measurements], "-*")
plt.xlabel("N, input array len")
plt.ylabel("execution time, s")
plt.grid()
plt.savefig(f"figs/n-exec-time.png", bbox_inches="tight")
plt.figure(figsize=(15, 10))
plt.plot(array_len_param, [m.measurements["ram_usage"] for m in measurements], "-*")
plt.xlabel("N, input array len")
plt.ylabel("RAM usage, s")
plt.grid()
plt.savefig(f"figs/n-ram-usage.png", bbox_inches="tight")
# for m in measurements:
# m.print()
# run_quantum_search_with_measurements = apply_measurements(
# partial(run_quantum_search, array_len=10),
# [measure_exec_time, measure_ram_usage, measure_exec_time],
# )
# m = run_quantum_search_with_measurements()
# m.print()
def plot_with_number_of_grover_iter():
array_len = 32
n_iter_param = [v for v in range(1, 8+1)]
# n_iter_param = [v for v in range(10)]
pred = []
confidence = []
for ni in n_iter_param:
print(f"num of iter: {ni}")
result = run_quantum_search(array_len=array_len, n_grover_iterations=ni)
pred.append(result[0])
confidence.append(result[1])
print(pred)
print(confidence)
plt.figure(figsize=(15, 10))
plt.plot(n_iter_param, confidence, "-*")
plt.xlabel("number of grover iterations")
plt.ylabel("prob to collapse in a correct state")
plt.axvline(math.floor(math.sqrt(array_len)), c="red")
plt.grid()
plt.savefig(f"figs/grover-iter-prob.png", bbox_inches="tight")
def plot_linear_vs_sqrt():
x = np.arange(100)
plt.figure(figsize=(15, 10))
plt.plot(x, x, "-", label="linear search", c="b")
plt.plot(x, [math.floor(math.sqrt(v)) for v in x], "-", label="quantum search", c="r")
plt.xlabel("number of input data")
plt.ylabel("number of required iterations")
plt.legend()
plt.grid()
plt.savefig(f"figs/linear-vs-sqrt.png", bbox_inches="tight")
def main():
# plot_with_number_of_input_data()
# plot_with_number_of_grover_iter()
plot_linear_vs_sqrt()
if __name__ == "__main__":
Fire(main)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.