repo
stringclasses 900
values | file
stringclasses 754
values | content
stringlengths 4
215k
|
|---|---|---|
https://github.com/qiskit-community/prototype-qrao
|
qiskit-community
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2020, 2022.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Quantum Random Access Optimizer."""
from typing import Union, List, Tuple, Optional
import time
import numpy as np
from qiskit import QuantumCircuit
from qiskit.algorithms.minimum_eigensolvers import (
MinimumEigensolver,
MinimumEigensolverResult,
NumPyMinimumEigensolver,
)
from qiskit.algorithms.minimum_eigen_solvers import (
MinimumEigensolver as LegacyMinimumEigensolver,
MinimumEigensolverResult as LegacyMinimumEigensolverResult,
NumPyMinimumEigensolver as LegacyNumPyMinimumEigensolver,
)
from qiskit_optimization.algorithms import (
OptimizationAlgorithm,
OptimizationResult,
OptimizationResultStatus,
SolutionSample,
)
from qiskit_optimization.problems import QuadraticProgram, Variable
from .encoding import QuantumRandomAccessEncoding
from .rounding_common import RoundingScheme, RoundingContext, RoundingResult
from .semideterministic_rounding import SemideterministicRounding
def _get_aux_operators_evaluated(relaxed_results):
try:
# Must be using the new "minimum_eigensolvers"
# https://github.com/Qiskit/qiskit-terra/blob/main/releasenotes/notes/0.22/add-eigensolvers-with-primitives-8b3a9f55f5fd285f.yaml
return relaxed_results.aux_operators_evaluated
except AttributeError:
# Must be using the old (deprecated) "minimum_eigen_solvers"
return relaxed_results.aux_operator_eigenvalues
class QuantumRandomAccessOptimizationResult(OptimizationResult):
"""Result of Quantum Random Access Optimization procedure."""
def __init__(
self,
*,
x: Optional[Union[List[float], np.ndarray]],
fval: Optional[float],
variables: List[Variable],
status: OptimizationResultStatus,
samples: Optional[List[SolutionSample]],
relaxed_results: Union[
MinimumEigensolverResult, LegacyMinimumEigensolverResult
],
rounding_results: RoundingResult,
relaxed_results_offset: float,
sense: int,
) -> None:
"""
Args:
x: the optimal value found by ``MinimumEigensolver``.
fval: the optimal function value.
variables: the list of variables of the optimization problem.
status: the termination status of the optimization algorithm.
min_eigen_solver_result: the result obtained from the underlying algorithm.
samples: the x values of the QUBO, the objective function value of the QUBO,
and the probability, and the status of sampling.
"""
super().__init__(
x=x,
fval=fval,
variables=variables,
status=status,
raw_results=None,
samples=samples,
)
self._relaxed_results = relaxed_results
self._rounding_results = rounding_results
self._relaxed_results_offset = relaxed_results_offset
assert sense in (-1, 1)
self._sense = sense
@property
def relaxed_results(
self,
) -> Union[MinimumEigensolverResult, LegacyMinimumEigensolverResult]:
"""Variationally obtained ground state of the relaxed Hamiltonian"""
return self._relaxed_results
@property
def rounding_results(self) -> RoundingResult:
"""Rounding results"""
return self._rounding_results
@property
def trace_values(self):
"""List of expectation values, one corresponding to each decision variable"""
trace_values = [
v[0] for v in _get_aux_operators_evaluated(self._relaxed_results)
]
return trace_values
@property
def relaxed_fval(self) -> float:
"""Relaxed function value, in the conventions of the original ``QuadraticProgram``
Restoring convertions may be necessary, for instance, if the provided
``QuadraticProgram`` represents a maximization problem, as it will be
converted to a minimization problem when phrased as a Hamiltonian.
"""
return self._sense * (
self._relaxed_results_offset + self.relaxed_results.eigenvalue.real
)
def __repr__(self) -> str:
lines = (
"QRAO Result",
"-----------",
f"relaxed function value: {self.relaxed_fval}",
super().__repr__(),
)
return "\n".join(lines)
class QuantumRandomAccessOptimizer(OptimizationAlgorithm):
"""Quantum Random Access Optimizer."""
def __init__(
self,
min_eigen_solver: Union[MinimumEigensolver, LegacyMinimumEigensolver],
encoding: QuantumRandomAccessEncoding,
rounding_scheme: Optional[RoundingScheme] = None,
):
"""
Args:
min_eigen_solver: The minimum eigensolver to use for solving the
relaxed problem (typically an instance of ``VQE`` or ``QAOA``).
encoding: The ``QuantumRandomAccessEncoding``, which must have
already been ``encode()``ed with a ``QuadraticProgram``.
rounding_scheme: The rounding scheme. If ``None`` is provided,
``SemideterministicRounding()`` will be used.
"""
self.min_eigen_solver = min_eigen_solver
self.encoding = encoding
if rounding_scheme is None:
rounding_scheme = SemideterministicRounding()
self.rounding_scheme = rounding_scheme
@property
def min_eigen_solver(self) -> Union[MinimumEigensolver, LegacyMinimumEigensolver]:
"""The minimum eigensolver."""
return self._min_eigen_solver
@min_eigen_solver.setter
def min_eigen_solver(
self, min_eigen_solver: Union[MinimumEigensolver, LegacyMinimumEigensolver]
) -> None:
"""Set the minimum eigensolver."""
if not min_eigen_solver.supports_aux_operators():
raise TypeError(
f"The provided MinimumEigensolver ({type(min_eigen_solver)}) "
"does not support auxiliary operators."
)
self._min_eigen_solver = min_eigen_solver
@property
def encoding(self) -> QuantumRandomAccessEncoding:
"""The encoding."""
return self._encoding
@encoding.setter
def encoding(self, encoding: QuantumRandomAccessEncoding) -> None:
"""Set the encoding"""
if encoding.num_qubits == 0:
raise ValueError(
"The passed encoder has no variables associated with it; you probably "
"need to call `encode()` to encode it with a `QuadraticProgram`."
)
# Instead of copying, we "freeze" the encoding to ensure it is not
# modified going forward.
encoding.freeze()
self._encoding = encoding
def get_compatibility_msg(self, problem: QuadraticProgram) -> str:
if problem != self.encoding.problem:
return (
"The problem passed does not match the problem used "
"to construct the QuantumRandomAccessEncoding."
)
return ""
def solve_relaxed(
self,
) -> Tuple[
Union[MinimumEigensolverResult, LegacyMinimumEigensolverResult], RoundingContext
]:
"""Solve the relaxed Hamiltonian given the ``encoding`` provided to the constructor."""
# Get the ordered list of operators that correspond to each decision
# variable. This line assumes the variables are numbered consecutively
# starting with 0. Note that under this assumption, the following
# range is equivalent to `sorted(self.encoding.var2op.keys())`. See
# encoding.py for more commentary on this assumption, which always
# holds when starting from a `QuadraticProgram`.
variable_ops = [self.encoding.term2op(i) for i in range(self.encoding.num_vars)]
# solve relaxed problem
start_time_relaxed = time.time()
relaxed_results = self.min_eigen_solver.compute_minimum_eigenvalue(
self.encoding.qubit_op, aux_operators=variable_ops
)
stop_time_relaxed = time.time()
relaxed_results.time_taken = stop_time_relaxed - start_time_relaxed
trace_values = [v[0] for v in _get_aux_operators_evaluated(relaxed_results)]
# Collect inputs for rounding
# double check later that there's no funny business with the
# parameter ordering.
# If the relaxed solution can be expressed as an explicit circuit
# then always express it that way - even if a statevector simulator
# was used and the actual wavefunction could be used. The only exception
# is the numpy eigensolver. If you wish to round the an explicit statevector,
# you must do so by manually rounding and passing in a QuantumCircuit
# initialized to the desired state.
if hasattr(self.min_eigen_solver, "ansatz"):
circuit = self.min_eigen_solver.ansatz.bind_parameters(
relaxed_results.optimal_point
)
elif isinstance(
self.min_eigen_solver,
(NumPyMinimumEigensolver, LegacyNumPyMinimumEigensolver),
):
statevector = relaxed_results.eigenstate
if isinstance(self.min_eigen_solver, LegacyNumPyMinimumEigensolver):
# statevector is a StateFn in this case, so we must convert it
# to a Statevector
statevector = statevector.primitive
circuit = QuantumCircuit(self.encoding.num_qubits)
circuit.initialize(statevector)
else:
circuit = None
rounding_context = RoundingContext(
encoding=self.encoding,
trace_values=trace_values,
circuit=circuit,
)
return relaxed_results, rounding_context
def solve(self, problem: Optional[QuadraticProgram] = None) -> OptimizationResult:
if problem is None:
problem = self.encoding.problem
else:
if problem != self.encoding.problem:
raise ValueError(
"The problem given must exactly match the problem "
"used to generate the encoded operator. Alternatively, "
"the argument to `solve` can be left blank."
)
# Solve relaxed problem
# ============================
(relaxed_results, rounding_context) = self.solve_relaxed()
# Round relaxed solution
# ============================
rounding_results = self.rounding_scheme.round(rounding_context)
# Process rounding results
# ============================
# The rounding classes don't have enough information to evaluate the
# objective function, so they return a RoundingSolutionSample, which
# contains only part of the information in the SolutionSample. Here we
# fill in the rest.
samples: List[SolutionSample] = []
for sample in rounding_results.samples:
samples.append(
SolutionSample(
x=sample.x,
fval=problem.objective.evaluate(sample.x),
probability=sample.probability,
status=self._get_feasibility_status(problem, sample.x),
)
)
# TODO: rewrite this logic once the converters are integrated.
# we need to be very careful about ensuring that the problem
# sense is taken into account in the relaxed solution and the rounding
# this is likely only a temporary patch while we are sticking to a
# maximization problem.
fsense = {"MINIMIZE": min, "MAXIMIZE": max}[problem.objective.sense.name]
best_sample = fsense(samples, key=lambda x: x.fval)
return QuantumRandomAccessOptimizationResult(
samples=samples,
x=best_sample.x,
fval=best_sample.fval,
variables=problem.variables,
status=OptimizationResultStatus.SUCCESS,
relaxed_results=relaxed_results,
rounding_results=rounding_results,
relaxed_results_offset=self.encoding.offset,
sense=problem.objective.sense.value,
)
|
https://github.com/qiskit-community/prototype-qrao
|
qiskit-community
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2022.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test QRAO steps on various hardware and simulator backends"""
import pytest
from docplex.mp.model import Model
from qiskit.utils import QuantumInstance
from qiskit.algorithms.minimum_eigen_solvers import VQE
from qiskit.circuit.library import RealAmplitudes
from qiskit.algorithms.optimizers import SPSA
from qiskit import BasicAer
from qiskit_aer import Aer
from qiskit_optimization.algorithms import OptimizationResultStatus
from qiskit_optimization.translators import from_docplex_mp
from qiskit_ibm_provider import IBMProvider, least_busy, IBMAccountError
from qrao import (
QuantumRandomAccessOptimizer,
QuantumRandomAccessEncoding,
MagicRounding,
)
# pylint: disable=redefined-outer-name
# TODO:
# - update these tests to include solution checking once behavior can be made
# - deterministic.
# - This might just require us to set seeds in the QuantumInstance and
# - remove that as an argument altogether.
backends = [
(BasicAer.get_backend, "qasm_simulator"),
(Aer.get_backend, "qasm_simulator"),
(Aer.get_backend, "statevector_simulator"),
(Aer.get_backend, "aer_simulator"),
(Aer.get_backend, "aer_simulator_statevector"),
(Aer.get_backend, "aer_simulator_density_matrix"),
(Aer.get_backend, "aer_simulator_matrix_product_state"),
# The following takes forever, haven't yet waited long enough to know the
# real timescale
# (Aer.get_backend, "aer_simulator_extended_stabilizer"),
]
@pytest.fixture(scope="module")
def my_encoding():
"""Fixture to construct ``my_encoding`` for use in this file"""
# Load small reference problem
elist = [(0, 1), (0, 4), (0, 3), (1, 2), (1, 5), (2, 3), (2, 4), (4, 5), (5, 3)]
num_nodes = 6
mod = Model("maxcut")
nodes = list(range(num_nodes))
var = [mod.binary_var(name="x" + str(i)) for i in nodes]
mod.maximize(mod.sum((var[i] + var[j] - 2 * var[i] * var[j]) for i, j in elist))
problem = from_docplex_mp(mod)
encoding = QuantumRandomAccessEncoding(max_vars_per_qubit=3)
encoding.encode(problem)
return encoding
@pytest.fixture(scope="module")
def my_ansatz(my_encoding):
"""Fixture to construct ``my_ansatz`` for use in this file"""
return RealAmplitudes(my_encoding.num_qubits)
@pytest.mark.parametrize("relaxed_backend", backends)
@pytest.mark.parametrize("rounding_backend", backends)
@pytest.mark.filterwarnings("ignore::PendingDeprecationWarning")
@pytest.mark.filterwarnings(
"ignore:.*statevector_simulator.*:UserWarning"
) # ignore magic rounding's UserWarning when using statevector_simulator
@pytest.mark.backend
def test_backend(relaxed_backend, rounding_backend, my_encoding, my_ansatz, shots=3):
"""Smoke test of each backend combination"""
def cb(f, *args):
"Construct backend"
return f(*args)
relaxed_qi = QuantumInstance(backend=cb(*relaxed_backend), shots=shots)
rounding_qi = QuantumInstance(backend=cb(*rounding_backend), shots=shots)
vqe = VQE(
ansatz=my_ansatz,
optimizer=SPSA(maxiter=1, learning_rate=0.01, perturbation=0.1),
quantum_instance=relaxed_qi,
)
rounding_scheme = MagicRounding(rounding_qi)
qrao = QuantumRandomAccessOptimizer(
encoding=my_encoding, min_eigen_solver=vqe, rounding_scheme=rounding_scheme
)
result = qrao.solve()
assert result.status == OptimizationResultStatus.SUCCESS
@pytest.mark.backend
def test_magic_rounding_on_hardware_backend(my_encoding, my_ansatz):
"""Test *magic rounding* on a hardware backend, if available."""
try:
provider = IBMProvider()
except IBMAccountError:
pytest.skip("No hardware backend available")
print(f"Encoding requires {my_encoding.num_qubits} qubits")
backend = least_busy(
provider.backends(
min_num_qubits=my_encoding.num_qubits,
simulator=False,
operational=True,
)
)
print(f"Using backend: {backend}")
relaxed_qi = QuantumInstance(backend=Aer.get_backend("aer_simulator"), shots=100)
rounding_qi = QuantumInstance(backend=backend, shots=32)
vqe = VQE(
ansatz=my_ansatz,
optimizer=SPSA(maxiter=1, learning_rate=0.01, perturbation=0.1),
quantum_instance=relaxed_qi,
)
rounding_scheme = MagicRounding(quantum_instance=rounding_qi)
qrao = QuantumRandomAccessOptimizer(
encoding=my_encoding, min_eigen_solver=vqe, rounding_scheme=rounding_scheme
)
result = qrao.solve()
assert result.status == OptimizationResultStatus.SUCCESS
|
https://github.com/qiskit-community/prototype-qrao
|
qiskit-community
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2021, 2022.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Tests for MagicRounding."""
import itertools
import unittest
import pytest
import numpy as np
from docplex.mp.model import Model
from qiskit import QuantumCircuit
from qiskit.utils import QuantumInstance
from qiskit.opflow import (
StateFn,
X,
Y,
Z,
)
from qiskit_aer import Aer, noise
from qiskit_optimization.translators import from_docplex_mp
from qrao import (
QuantumRandomAccessEncoding,
RoundingContext,
MagicRounding,
)
from qrao.encoding import qrac_state_prep_1q, q2vars_from_var2op
# pylint: disable=protected-access
class TestMagicRounding(unittest.TestCase):
"""Test MagicRounding Class"""
def setUp(self):
# load problem, define encoding etc
# instantiate MagicRounding
# things here don't change (often)
super().setUp()
self.gate_circ = QuantumCircuit(2)
self.gate_circ.h(0)
self.gate_circ.h(1)
self.gate_circ.z(1)
self.gate_circ.cx(0, 1)
self.gate_circ.s(0)
self.gate_circ.save_statevector()
self.deterministic_trace_vals = [
[1, 1, 1],
[1, -1, -1],
[1, -1, 1],
[1, 1, -1],
]
elist = [(0, 1), (0, 4), (0, 3), (1, 2), (1, 5), (2, 3), (2, 4), (4, 5), (5, 3)]
num_nodes = 6
mod = Model("maxcut")
nodes = list(range(num_nodes))
var = [mod.binary_var(name="x" + str(i)) for i in nodes]
mod.maximize(mod.sum((var[i] + var[j] - 2 * var[i] * var[j]) for i, j in elist))
self.problem = from_docplex_mp(mod)
self.rounding_qi = QuantumInstance(
backend=Aer.get_backend("aer_simulator"), shots=10
)
# Start test cases in order of increasing complexity
# toy problems
# harder problems w/ minimal inputs
# harder problems w/ more inputs
# negative test cases
def test_round_on_gate_and_sv_circs(self):
"""Test MagicRounding"""
ops = [X, Y, Z]
var2op = {i: (i // 3, ops[i % 3]) for i in range(3)}
qi = QuantumInstance(backend=Aer.get_backend("aer_simulator"), shots=1000)
magic = MagicRounding(
quantum_instance=qi,
basis_sampling="weighted",
)
# subtest for gate based and sv based etc
with self.subTest("Gate Based Magic Uniform Rounding"):
for m in itertools.product((0, 1), repeat=3):
qrac_gate_circ = qrac_state_prep_1q(*m).to_circuit()
magic_basis = 2 * (m[1] ^ m[2]) + (m[0] ^ m[2])
tv = self.deterministic_trace_vals[magic_basis]
rounding_context = RoundingContext(
trace_values=tv,
circuit=qrac_gate_circ,
var2op=var2op,
_vars_per_qubit=3,
)
rounding_res = magic.round(rounding_context)
self.assertEqual(rounding_res.samples[0].x.tolist(), list(m))
self.assertEqual(rounding_res.samples[0].probability, 1)
with self.subTest("SV Based Magic Uniform Rounding"):
for m in itertools.product((0, 1), repeat=3):
qrac_gate_circ = qrac_state_prep_1q(*m).to_circuit()
sv = StateFn(qrac_gate_circ).eval().primitive
qrac_sv_circ = QuantumCircuit(1)
qrac_sv_circ.initialize(sv)
magic_basis = 2 * (m[1] ^ m[2]) + (m[0] ^ m[2])
tv = self.deterministic_trace_vals[magic_basis]
rounding_context = RoundingContext(
trace_values=tv,
circuit=qrac_sv_circ,
var2op=var2op,
_vars_per_qubit=3,
)
rounding_res = magic.round(rounding_context)
self.assertEqual(rounding_res.samples[0].x.tolist(), list(m))
self.assertEqual(rounding_res.samples[0].probability, 1)
def test_evaluate_magic_bases(self):
qi = QuantumInstance(backend=Aer.get_backend("aer_simulator"), shots=1000)
magic = MagicRounding(
quantum_instance=qi,
basis_sampling="weighted",
)
for m in itertools.product((0, 1), repeat=3):
qrac_state = qrac_state_prep_1q(*m).to_circuit()
bases = [[2 * (m[1] ^ m[2]) + (m[0] ^ m[2])]]
basis_counts = magic._evaluate_magic_bases(
qrac_state, bases=bases, basis_shots=[10], vars_per_qubit=3
)
self.assertEqual(len(basis_counts), 1)
self.assertEqual(int(list(basis_counts[0].keys())[0]), m[0] ^ m[1] ^ m[2])
def test_dv_counts(self):
"""
Checks that the dv_counts method unpacks these measurement outcomes
properly. This also effectively tests `unpack_measurement_outcome`.
"""
ops = [X, Y, Z]
var2op = {i: (i // 3, ops[i % 3]) for i in range(6)}
magic = MagicRounding(self.rounding_qi)
compute_dv_counts = magic._compute_dv_counts
solns = []
for b0 in range(4):
for b1 in range(4):
for outcome in range(4):
bases = [[b0, b1]]
basis_counts = [{f"{outcome:02b}": 1}]
dv_counts = compute_dv_counts(basis_counts, bases, var2op, 3)
solns.append(list(dv_counts.keys())[0])
ref = [
"000000",
"000111",
"111000",
"111111",
"000011",
"000100",
"111011",
"111100",
"000101",
"000010",
"111101",
"111010",
"000110",
"000001",
"111110",
"111001",
"011000",
"011111",
"100000",
"100111",
"011011",
"011100",
"100011",
"100100",
"011101",
"011010",
"100101",
"100010",
"011110",
"011001",
"100110",
"100001",
"101000",
"101111",
"010000",
"010111",
"101011",
"101100",
"010011",
"010100",
"101101",
"101010",
"010101",
"010010",
"101110",
"101001",
"010110",
"010001",
"110000",
"110111",
"001000",
"001111",
"110011",
"110100",
"001011",
"001100",
"110101",
"110010",
"001101",
"001010",
"110110",
"110001",
"001110",
"001001",
]
self.assertTrue(np.all(np.array(ref) == np.array(solns)))
def test_sample_bases_weighted(self): # pylint: disable=too-many-locals
"""
There are a few settings of the trace values which
cause the magic basis sampling probabilities to be deterministic.
I pass these through (for a 2 qubit, 6 var example) and verify
that the outputs are correctly shaped and are deterministic.
Note that these input trace values are non-physical
"""
shots = 10
num_nodes = 6
num_qubits = 2
rounding_qi = QuantumInstance(
backend=Aer.get_backend("aer_simulator"), shots=shots
)
ops = [X, Y, Z]
var2op = {i: (i // 3, ops[i % 3]) for i in range(num_nodes)}
q2vars = q2vars_from_var2op(var2op)
magic = MagicRounding(quantum_instance=rounding_qi, basis_sampling="weighted")
sample_bases_weighted = magic._sample_bases_weighted
for b0, tv0 in enumerate(self.deterministic_trace_vals):
for b1, tv1 in enumerate(self.deterministic_trace_vals):
tv = tv0 + tv1
bases, basis_shots = sample_bases_weighted(q2vars, tv, 3)
self.assertTrue(np.all(np.array([b0, b1]) == bases))
self.assertEqual(basis_shots, (shots,))
self.assertEqual(bases.shape, (1, num_qubits)) # 1 == deterministic
# Both trace values and a circuit must be provided
with self.assertRaises(NotImplementedError):
magic.round(
RoundingContext(trace_values=[1.0], var2op=var2op, _vars_per_qubit=3)
)
with self.assertRaises(NotImplementedError):
magic.round(
RoundingContext(
circuit=self.gate_circ, var2op=var2op, _vars_per_qubit=3
)
)
def test_sample_bases_uniform(self):
"""
Verify that the outputs of uniform sampling are correctly shaped.
"""
num_nodes = 3
num_qubits = 1
ops = [X, Y, Z]
var2op = {i: (i // 3, ops[i % 3]) for i in range(num_nodes)}
q2vars = q2vars_from_var2op(var2op)
shots = 1000 # set high enough to "always" have four distinct results
qi = QuantumInstance(backend=Aer.get_backend("aer_simulator"), shots=shots)
magic = MagicRounding(
quantum_instance=qi,
basis_sampling="uniform",
)
bases, basis_shots = magic._sample_bases_uniform(q2vars, 3)
self.assertEqual(basis_shots.shape, (4,))
self.assertEqual(np.sum(basis_shots), shots)
self.assertEqual(bases.shape, (4, num_qubits))
# A circuit must be provided, but trace values need not be
circuit = QuantumCircuit(1)
circuit.h(0)
magic.round(RoundingContext(circuit=circuit, var2op=var2op, _vars_per_qubit=3))
with self.assertRaises(NotImplementedError):
magic.round(RoundingContext(var2op=var2op, _vars_per_qubit=3))
def test_unsupported_backend():
qi = QuantumInstance(Aer.get_backend("aer_simulator_unitary"), shots=100)
with pytest.raises(ValueError):
MagicRounding(quantum_instance=qi)
def test_unsupported_basis_sampling_method():
qi = QuantumInstance(Aer.get_backend("aer_simulator"), shots=100)
with pytest.raises(ValueError):
MagicRounding(quantum_instance=qi, basis_sampling="foo")
@pytest.mark.filterwarnings("ignore::PendingDeprecationWarning")
def test_magic_rounding_statevector_simulator():
"""Test magic rounding on the statevector simulator
... which behaves unlike the others, as the "counts" are probabilities, not
integers, and so special care is required.
"""
qi = QuantumInstance(Aer.get_backend("statevector_simulator"), shots=10)
ops = [X, Y, Z]
var2op = {i: (i // 3, ops[i % 3]) for i in range(3)}
with pytest.warns(UserWarning):
magic = MagicRounding(
quantum_instance=qi,
basis_sampling="weighted",
)
circ = QuantumCircuit(2)
circ.h(0)
circ.h(1)
circ.cx(0, 1)
ctx = RoundingContext(
circuit=circ, trace_values=[1, 1, 1], var2op=var2op, _vars_per_qubit=3
)
res = magic.round(ctx)
assert sum(s.probability for s in res.samples) == pytest.approx(1)
def test_noisy_quantuminstance():
"""Smoke test using a QuantumInstance with noise"""
noise_model = noise.NoiseModel()
# 1-qubit gates
noise_model.add_all_qubit_quantum_error(
noise.depolarizing_error(0.001, 1), ["rz", "sx", "x"]
)
# 2-qubit gate
noise_model.add_all_qubit_quantum_error(noise.depolarizing_error(0.01, 2), ["cx"])
backend = Aer.get_backend("aer_simulator")
qi = QuantumInstance(backend=backend, noise_model=noise_model, shots=100)
magic = MagicRounding(quantum_instance=qi)
ops = [X, Y, Z]
var2op = {i: (i // 3, ops[i % 3]) for i in range(3)}
circuit = qrac_state_prep_1q(0, 1, 0).to_circuit()
magic.round(
RoundingContext(
trace_values=[1, 1, 1], var2op=var2op, circuit=circuit, _vars_per_qubit=3
)
)
def test_magic_rounding_statistical():
"""Statistical test for magic rounding
to make sure each deterministic case rounds consistently
"""
shots = 1024
mr = MagicRounding(
QuantumInstance(backend=Aer.get_backend("aer_simulator"), shots=shots)
)
test_cases = (
# 3 variables encoded as a (3,1,p) QRAC
((0, 0, 0), 0, 0),
((1, 1, 1), 0, 1),
((0, 1, 1), 1, 0),
((1, 0, 0), 1, 1),
((1, 0, 1), 2, 0),
((0, 1, 0), 2, 1),
((1, 1, 0), 3, 0),
((0, 0, 1), 3, 1),
# 2 variables encoded as a (2,1,p) QRAC
((0, 0), 0, 0),
((1, 1), 0, 1),
((0, 1), 1, 0),
((1, 0), 1, 1),
# 1 variable encoded as a (1,1,1) QRAC
((0,), 0, 0),
((1,), 0, 1),
)
for (m, basis, expected) in test_cases:
encoding = QuantumRandomAccessEncoding(len(m))
encoding._add_variables(list(range(len(m))))
circuit = encoding.state_prep(m).to_circuit()
result = mr.round(RoundingContext(encoding=encoding, circuit=circuit))
deterministic_dict = result.basis_counts[basis]
assert set(deterministic_dict) == set([str(expected)])
if __name__ == "__main__":
import sys
sys.exit(pytest.main([__file__]))
|
https://github.com/quantastica/qiskit-toaster
|
quantastica
|
from qiskit import Aer, QuantumCircuit, execute
from qiskit.compiler import transpile, assemble
from quantastica.qiskit_toaster import ToasterBackend
import time
import logging
import os
backend = ToasterBackend.get_backend("qasm_simulator")
# backend = Aer.get_backend("qasm_simulator")
default_options = {
# "method": "statevector", # Force dense statevector method for benchmarks
# "truncate_enable": False, # Disable unused qubit truncation for benchmarks
# "max_parallel_threads": 1, # Disable OpenMP parallelization for benchmarks
"toaster_optimization": 3 # optimization for qubit-toaster
}
# def _execute(circuit, backend_options=None):
# experiment = transpile(circuit, backend)
# qobj = assemble(experiment, shots=1)
# qobj_aer = backend._format_qobj(qobj, backend_options, None)
# return backend._controller(qobj_aer)
def _execute(circuit, backend):
job = execute(circuit, backend=backend)
# job.result is needed in order to wait for results
job.result()
def native_execute(benchmark, circuit, backend_options=None):
# experiment = transpile(circuit, backend)
# qobj = assemble(experiment, shots=1)
# qobj_aer = backend._format_qobj(qobj, backend_options, None)
# benchmark(backend._controller, qobj_aer)
benchmark(_execute, circuit, backend)
def run_bench(benchmark, nqubits, gate, locs=(1,)):
qc = QuantumCircuit(nqubits)
getattr(qc, gate)(*locs)
native_execute(benchmark, qc, default_options)
def first_rotation(circuit, nqubits):
circuit.rx(1.0, range(nqubits))
circuit.rz(1.0, range(nqubits))
return circuit
def mid_rotation(circuit, nqubits):
circuit.rz(1.0, range(nqubits))
circuit.rx(1.0, range(nqubits))
circuit.rz(1.0, range(nqubits))
return circuit
def last_rotation(circuit, nqubits):
circuit.rz(1.0, range(nqubits))
circuit.rx(1.0, range(nqubits))
return circuit
def entangler(circuit, pairs):
for a, b in pairs:
circuit.cx(a, b)
return circuit
def generate_qcbm_circuit(nqubits, depth, pairs):
circuit = QuantumCircuit(nqubits)
first_rotation(circuit, nqubits)
entangler(circuit, pairs)
for k in range(depth - 1):
mid_rotation(circuit, nqubits)
entangler(circuit, pairs)
last_rotation(circuit, nqubits)
# circuit.measure_all()
return circuit
def test_qcbm(name, backend, nqubits, optimization_level=None):
pairs = [(i, (i + 1) % nqubits) for i in range(nqubits)]
circuit = generate_qcbm_circuit(nqubits, 9, pairs)
with open("circuit.qasm", "w") as f:
f.write(circuit.qasm())
t1 = time.time()
# test = transpile(circuit, optimization_level=0)
# qobj = assemble(circuit)
# job = backend.run(qobj, backend_options=default_options)
job = execute(
circuit,
backend=backend,
backend_options=default_options,
optimization_level=optimization_level,
)
# job.result is needed in order to wait for results
result = job.result()
t2 = time.time()
# print(result)
# counts = result.get_counts(circuit)
# print("Counts size: %d" % len(counts))
print(" %s time: %f" % (name, t2 - t1))
if __name__ == "__main__":
logging.basicConfig(
format="%(levelname)s %(asctime)s %(pathname)s - %(message)s",
level=os.environ.get("LOGLEVEL", "CRITICAL"),
)
N = int(os.environ.get("N", 20))
LOOPS = int(os.environ.get("LOOPS", 10))
for i in range(0, LOOPS):
print("Iteration #%d (of %d)" % (i, LOOPS))
test_qcbm("AER", Aer.get_backend("qasm_simulator"), N, 0)
test_qcbm(
"TOASTER", ToasterBackend.get_backend("qasm_simulator"), N, 0
)
|
https://github.com/quantastica/qiskit-toaster
|
quantastica
|
import unittest
from qiskit import QuantumRegister
from qiskit import QuantumCircuit, execute
from qiskit.providers.aer import AerSimulator
import numpy as np
import logging
import os
try:
from . import common
except Exception:
import common
@unittest.skipUnless(
os.getenv("SLOW") == "1",
"Skipping this test (environment variable SLOW must be set to 1)",
)
class TestSpeed(common.TestToasterBase):
def test_qft25_toaster(self):
logging.info("======= Starting our function =======")
qc = self.get_qft25_qc()
stats = self.execute_and_get_stats(
self.toaster_backend(),
# Aer.get_backend("qasm_simulator"),
qc,
1,
)
print("QFT25 toaster:", stats)
logging.info("======= Ending our function =======")
def test_qft25_aer(self):
logging.info("======= Starting our function =======")
qc = self.get_qft25_qc()
qc.save_state()
stats = self.execute_and_get_stats(
AerSimulator(method="statevector"), qc, 1,
)
print("QFT25 toaster:", stats)
logging.info("======= Ending our function =======")
@classmethod
def execute_and_get_stats(cls, backend, qc, shots):
job = execute(
qc,
optimization_level=0,
backend=backend,
shots=shots,
seed_simulator=1,
)
job_result = job.result()
counts = job_result.get_counts(qc)
total_counts = 0
for c in counts:
total_counts += counts[c]
ret = dict()
ret["counts"] = counts
ret["totalcounts"] = total_counts
return ret
@staticmethod
def get_qft25_qc():
qc = QuantumCircuit()
q = QuantumRegister(25, "q")
qc.add_register(q)
qc.h(q[24])
qc.crz(np.pi / 2, q[23], q[24])
qc.h(q[23])
qc.crz(np.pi / 4, q[22], q[24])
qc.crz(np.pi / 2, q[22], q[23])
qc.h(q[22])
qc.crz(np.pi / 8, q[21], q[24])
qc.crz(np.pi / 4, q[21], q[23])
qc.crz(np.pi / 2, q[21], q[22])
qc.h(q[21])
qc.crz(np.pi / 16, q[20], q[24])
qc.crz(np.pi / 8, q[20], q[23])
qc.crz(np.pi / 4, q[20], q[22])
qc.crz(np.pi / 2, q[20], q[21])
qc.h(q[20])
qc.crz(np.pi / 32, q[19], q[24])
qc.crz(np.pi / 16, q[19], q[23])
qc.crz(np.pi / 8, q[19], q[22])
qc.crz(np.pi / 4, q[19], q[21])
qc.crz(np.pi / 2, q[19], q[20])
qc.h(q[19])
qc.crz(np.pi / 64, q[18], q[24])
qc.crz(np.pi / 32, q[18], q[23])
qc.crz(np.pi / 16, q[18], q[22])
qc.crz(np.pi / 8, q[18], q[21])
qc.crz(np.pi / 4, q[18], q[20])
qc.crz(np.pi / 2, q[18], q[19])
qc.h(q[18])
qc.crz(np.pi / 128, q[17], q[24])
qc.crz(np.pi / 64, q[17], q[23])
qc.crz(np.pi / 32, q[17], q[22])
qc.crz(np.pi / 16, q[17], q[21])
qc.crz(np.pi / 8, q[17], q[20])
qc.crz(np.pi / 4, q[17], q[19])
qc.crz(np.pi / 2, q[17], q[18])
qc.h(q[17])
qc.crz(np.pi / 256, q[16], q[24])
qc.crz(np.pi / 128, q[16], q[23])
qc.crz(np.pi / 64, q[16], q[22])
qc.crz(np.pi / 32, q[16], q[21])
qc.crz(np.pi / 16, q[16], q[20])
qc.crz(np.pi / 8, q[16], q[19])
qc.crz(np.pi / 4, q[16], q[18])
qc.crz(np.pi / 2, q[16], q[17])
qc.h(q[16])
qc.crz(np.pi / 512, q[15], q[24])
qc.crz(np.pi / 256, q[15], q[23])
qc.crz(np.pi / 128, q[15], q[22])
qc.crz(np.pi / 64, q[15], q[21])
qc.crz(np.pi / 32, q[15], q[20])
qc.crz(np.pi / 16, q[15], q[19])
qc.crz(np.pi / 8, q[15], q[18])
qc.crz(np.pi / 4, q[15], q[17])
qc.crz(np.pi / 2, q[15], q[16])
qc.h(q[15])
qc.crz(np.pi / 1024, q[14], q[24])
qc.crz(np.pi / 512, q[14], q[23])
qc.crz(np.pi / 256, q[14], q[22])
qc.crz(np.pi / 128, q[14], q[21])
qc.crz(np.pi / 64, q[14], q[20])
qc.crz(np.pi / 32, q[14], q[19])
qc.crz(np.pi / 16, q[14], q[18])
qc.crz(np.pi / 8, q[14], q[17])
qc.crz(np.pi / 4, q[14], q[16])
qc.crz(np.pi / 2, q[14], q[15])
qc.h(q[14])
qc.crz(np.pi / 2048, q[13], q[24])
qc.crz(np.pi / 1024, q[13], q[23])
qc.crz(np.pi / 512, q[13], q[22])
qc.crz(np.pi / 256, q[13], q[21])
qc.crz(np.pi / 128, q[13], q[20])
qc.crz(np.pi / 64, q[13], q[19])
qc.crz(np.pi / 32, q[13], q[18])
qc.crz(np.pi / 16, q[13], q[17])
qc.crz(np.pi / 8, q[13], q[16])
qc.crz(np.pi / 4, q[13], q[15])
qc.crz(np.pi / 2, q[13], q[14])
qc.h(q[13])
qc.crz(np.pi / 4096, q[12], q[24])
qc.crz(np.pi / 2048, q[12], q[23])
qc.crz(np.pi / 1024, q[12], q[22])
qc.crz(np.pi / 512, q[12], q[21])
qc.crz(np.pi / 256, q[12], q[20])
qc.crz(np.pi / 128, q[12], q[19])
qc.crz(np.pi / 64, q[12], q[18])
qc.crz(np.pi / 32, q[12], q[17])
qc.crz(np.pi / 16, q[12], q[16])
qc.crz(np.pi / 8, q[12], q[15])
qc.crz(np.pi / 4, q[12], q[14])
qc.crz(np.pi / 2, q[12], q[13])
qc.h(q[12])
qc.crz(np.pi / 8192, q[11], q[24])
qc.crz(np.pi / 4096, q[11], q[23])
qc.crz(np.pi / 2048, q[11], q[22])
qc.crz(np.pi / 1024, q[11], q[21])
qc.crz(np.pi / 512, q[11], q[20])
qc.crz(np.pi / 256, q[11], q[19])
qc.crz(np.pi / 128, q[11], q[18])
qc.crz(np.pi / 64, q[11], q[17])
qc.crz(np.pi / 32, q[11], q[16])
qc.crz(np.pi / 16, q[11], q[15])
qc.crz(np.pi / 8, q[11], q[14])
qc.crz(np.pi / 4, q[11], q[13])
qc.crz(np.pi / 2, q[11], q[12])
qc.h(q[11])
qc.crz(np.pi / 16384, q[10], q[24])
qc.crz(np.pi / 8192, q[10], q[23])
qc.crz(np.pi / 4096, q[10], q[22])
qc.crz(np.pi / 2048, q[10], q[21])
qc.crz(np.pi / 1024, q[10], q[20])
qc.crz(np.pi / 512, q[10], q[19])
qc.crz(np.pi / 256, q[10], q[18])
qc.crz(np.pi / 128, q[10], q[17])
qc.crz(np.pi / 64, q[10], q[16])
qc.crz(np.pi / 32, q[10], q[15])
qc.crz(np.pi / 16, q[10], q[14])
qc.crz(np.pi / 8, q[10], q[13])
qc.crz(np.pi / 4, q[10], q[12])
qc.crz(np.pi / 2, q[10], q[11])
qc.h(q[10])
qc.crz(np.pi / 32768, q[9], q[24])
qc.crz(np.pi / 16384, q[9], q[23])
qc.crz(np.pi / 8192, q[9], q[22])
qc.crz(np.pi / 4096, q[9], q[21])
qc.crz(np.pi / 2048, q[9], q[20])
qc.crz(np.pi / 1024, q[9], q[19])
qc.crz(np.pi / 512, q[9], q[18])
qc.crz(np.pi / 256, q[9], q[17])
qc.crz(np.pi / 128, q[9], q[16])
qc.crz(np.pi / 64, q[9], q[15])
qc.crz(np.pi / 32, q[9], q[14])
qc.crz(np.pi / 16, q[9], q[13])
qc.crz(np.pi / 8, q[9], q[12])
qc.crz(np.pi / 4, q[9], q[11])
qc.crz(np.pi / 2, q[9], q[10])
qc.h(q[9])
qc.crz(np.pi / 65536, q[8], q[24])
qc.crz(np.pi / 32768, q[8], q[23])
qc.crz(np.pi / 16384, q[8], q[22])
qc.crz(np.pi / 8192, q[8], q[21])
qc.crz(np.pi / 4096, q[8], q[20])
qc.crz(np.pi / 2048, q[8], q[19])
qc.crz(np.pi / 1024, q[8], q[18])
qc.crz(np.pi / 512, q[8], q[17])
qc.crz(np.pi / 256, q[8], q[16])
qc.crz(np.pi / 128, q[8], q[15])
qc.crz(np.pi / 64, q[8], q[14])
qc.crz(np.pi / 32, q[8], q[13])
qc.crz(np.pi / 16, q[8], q[12])
qc.crz(np.pi / 8, q[8], q[11])
qc.crz(np.pi / 4, q[8], q[10])
qc.crz(np.pi / 2, q[8], q[9])
qc.h(q[8])
qc.crz(np.pi / 1.31072e5, q[7], q[24])
qc.crz(np.pi / 65536, q[7], q[23])
qc.crz(np.pi / 32768, q[7], q[22])
qc.crz(np.pi / 16384, q[7], q[21])
qc.crz(np.pi / 8192, q[7], q[20])
qc.crz(np.pi / 4096, q[7], q[19])
qc.crz(np.pi / 2048, q[7], q[18])
qc.crz(np.pi / 1024, q[7], q[17])
qc.crz(np.pi / 512, q[7], q[16])
qc.crz(np.pi / 256, q[7], q[15])
qc.crz(np.pi / 128, q[7], q[14])
qc.crz(np.pi / 64, q[7], q[13])
qc.crz(np.pi / 32, q[7], q[12])
qc.crz(np.pi / 16, q[7], q[11])
qc.crz(np.pi / 8, q[7], q[10])
qc.crz(np.pi / 4, q[7], q[9])
qc.crz(np.pi / 2, q[7], q[8])
qc.h(q[7])
qc.crz(np.pi / 2.62144e5, q[6], q[24])
qc.crz(np.pi / 1.31072e5, q[6], q[23])
qc.crz(np.pi / 65536, q[6], q[22])
qc.crz(np.pi / 32768, q[6], q[21])
qc.crz(np.pi / 16384, q[6], q[20])
qc.crz(np.pi / 8192, q[6], q[19])
qc.crz(np.pi / 4096, q[6], q[18])
qc.crz(np.pi / 2048, q[6], q[17])
qc.crz(np.pi / 1024, q[6], q[16])
qc.crz(np.pi / 512, q[6], q[15])
qc.crz(np.pi / 256, q[6], q[14])
qc.crz(np.pi / 128, q[6], q[13])
qc.crz(np.pi / 64, q[6], q[12])
qc.crz(np.pi / 32, q[6], q[11])
qc.crz(np.pi / 16, q[6], q[10])
qc.crz(np.pi / 8, q[6], q[9])
qc.crz(np.pi / 4, q[6], q[8])
qc.crz(np.pi / 2, q[6], q[7])
qc.h(q[6])
qc.crz(np.pi / 5.24288e5, q[5], q[24])
qc.crz(np.pi / 2.62144e5, q[5], q[23])
qc.crz(np.pi / 1.31072e5, q[5], q[22])
qc.crz(np.pi / 65536, q[5], q[21])
qc.crz(np.pi / 32768, q[5], q[20])
qc.crz(np.pi / 16384, q[5], q[19])
qc.crz(np.pi / 8192, q[5], q[18])
qc.crz(np.pi / 4096, q[5], q[17])
qc.crz(np.pi / 2048, q[5], q[16])
qc.crz(np.pi / 1024, q[5], q[15])
qc.crz(np.pi / 512, q[5], q[14])
qc.crz(np.pi / 256, q[5], q[13])
qc.crz(np.pi / 128, q[5], q[12])
qc.crz(np.pi / 64, q[5], q[11])
qc.crz(np.pi / 32, q[5], q[10])
qc.crz(np.pi / 16, q[5], q[9])
qc.crz(np.pi / 8, q[5], q[8])
qc.crz(np.pi / 4, q[5], q[7])
qc.crz(np.pi / 2, q[5], q[6])
qc.h(q[5])
qc.crz(np.pi / 1.048576e6, q[4], q[24])
qc.crz(np.pi / 5.24288e5, q[4], q[23])
qc.crz(np.pi / 2.62144e5, q[4], q[22])
qc.crz(np.pi / 1.31072e5, q[4], q[21])
qc.crz(np.pi / 65536, q[4], q[20])
qc.crz(np.pi / 32768, q[4], q[19])
qc.crz(np.pi / 16384, q[4], q[18])
qc.crz(np.pi / 8192, q[4], q[17])
qc.crz(np.pi / 4096, q[4], q[16])
qc.crz(np.pi / 2048, q[4], q[15])
qc.crz(np.pi / 1024, q[4], q[14])
qc.crz(np.pi / 512, q[4], q[13])
qc.crz(np.pi / 256, q[4], q[12])
qc.crz(np.pi / 128, q[4], q[11])
qc.crz(np.pi / 64, q[4], q[10])
qc.crz(np.pi / 32, q[4], q[9])
qc.crz(np.pi / 16, q[4], q[8])
qc.crz(np.pi / 8, q[4], q[7])
qc.crz(np.pi / 4, q[4], q[6])
qc.crz(np.pi / 2, q[4], q[5])
qc.h(q[4])
qc.crz(np.pi / 2.097152e6, q[3], q[24])
qc.crz(np.pi / 1.048576e6, q[3], q[23])
qc.crz(np.pi / 5.24288e5, q[3], q[22])
qc.crz(np.pi / 2.62144e5, q[3], q[21])
qc.crz(np.pi / 1.31072e5, q[3], q[20])
qc.crz(np.pi / 65536, q[3], q[19])
qc.crz(np.pi / 32768, q[3], q[18])
qc.crz(np.pi / 16384, q[3], q[17])
qc.crz(np.pi / 8192, q[3], q[16])
qc.crz(np.pi / 4096, q[3], q[15])
qc.crz(np.pi / 2048, q[3], q[14])
qc.crz(np.pi / 1024, q[3], q[13])
qc.crz(np.pi / 512, q[3], q[12])
qc.crz(np.pi / 256, q[3], q[11])
qc.crz(np.pi / 128, q[3], q[10])
qc.crz(np.pi / 64, q[3], q[9])
qc.crz(np.pi / 32, q[3], q[8])
qc.crz(np.pi / 16, q[3], q[7])
qc.crz(np.pi / 8, q[3], q[6])
qc.crz(np.pi / 4, q[3], q[5])
qc.crz(np.pi / 2, q[3], q[4])
qc.h(q[3])
qc.crz(np.pi / 4.194304e6, q[2], q[24])
qc.crz(np.pi / 2.097152e6, q[2], q[23])
qc.crz(np.pi / 1.048576e6, q[2], q[22])
qc.crz(np.pi / 5.24288e5, q[2], q[21])
qc.crz(np.pi / 2.62144e5, q[2], q[20])
qc.crz(np.pi / 1.31072e5, q[2], q[19])
qc.crz(np.pi / 65536, q[2], q[18])
qc.crz(np.pi / 32768, q[2], q[17])
qc.crz(np.pi / 16384, q[2], q[16])
qc.crz(np.pi / 8192, q[2], q[15])
qc.crz(np.pi / 4096, q[2], q[14])
qc.crz(np.pi / 2048, q[2], q[13])
qc.crz(np.pi / 1024, q[2], q[12])
qc.crz(np.pi / 512, q[2], q[11])
qc.crz(np.pi / 256, q[2], q[10])
qc.crz(np.pi / 128, q[2], q[9])
qc.crz(np.pi / 64, q[2], q[8])
qc.crz(np.pi / 32, q[2], q[7])
qc.crz(np.pi / 16, q[2], q[6])
qc.crz(np.pi / 8, q[2], q[5])
qc.crz(np.pi / 4, q[2], q[4])
qc.crz(np.pi / 2, q[2], q[3])
qc.h(q[2])
qc.crz(np.pi / 8.388608e6, q[1], q[24])
qc.crz(np.pi / 4.194304e6, q[1], q[23])
qc.crz(np.pi / 2.097152e6, q[1], q[22])
qc.crz(np.pi / 1.048576e6, q[1], q[21])
qc.crz(np.pi / 5.24288e5, q[1], q[20])
qc.crz(np.pi / 2.62144e5, q[1], q[19])
qc.crz(np.pi / 1.31072e5, q[1], q[18])
qc.crz(np.pi / 65536, q[1], q[17])
qc.crz(np.pi / 32768, q[1], q[16])
qc.crz(np.pi / 16384, q[1], q[15])
qc.crz(np.pi / 8192, q[1], q[14])
qc.crz(np.pi / 4096, q[1], q[13])
qc.crz(np.pi / 2048, q[1], q[12])
qc.crz(np.pi / 1024, q[1], q[11])
qc.crz(np.pi / 512, q[1], q[10])
qc.crz(np.pi / 256, q[1], q[9])
qc.crz(np.pi / 128, q[1], q[8])
qc.crz(np.pi / 64, q[1], q[7])
qc.crz(np.pi / 32, q[1], q[6])
qc.crz(np.pi / 16, q[1], q[5])
qc.crz(np.pi / 8, q[1], q[4])
qc.crz(np.pi / 4, q[1], q[3])
qc.crz(np.pi / 2, q[1], q[2])
qc.h(q[1])
qc.crz(np.pi / 1.6777216e7, q[0], q[24])
qc.crz(np.pi / 8.388608e6, q[0], q[23])
qc.crz(np.pi / 4.194304e6, q[0], q[22])
qc.crz(np.pi / 2.097152e6, q[0], q[21])
qc.crz(np.pi / 1.048576e6, q[0], q[20])
qc.crz(np.pi / 5.24288e5, q[0], q[19])
qc.crz(np.pi / 2.62144e5, q[0], q[18])
qc.crz(np.pi / 1.31072e5, q[0], q[17])
qc.crz(np.pi / 65536, q[0], q[16])
qc.crz(np.pi / 32768, q[0], q[15])
qc.crz(np.pi / 16384, q[0], q[14])
qc.crz(np.pi / 8192, q[0], q[13])
qc.crz(np.pi / 4096, q[0], q[12])
qc.crz(np.pi / 2048, q[0], q[11])
qc.crz(np.pi / 1024, q[0], q[10])
qc.crz(np.pi / 512, q[0], q[9])
qc.crz(np.pi / 256, q[0], q[8])
qc.crz(np.pi / 128, q[0], q[7])
qc.crz(np.pi / 64, q[0], q[6])
qc.crz(np.pi / 32, q[0], q[5])
qc.crz(np.pi / 16, q[0], q[4])
qc.crz(np.pi / 8, q[0], q[3])
qc.crz(np.pi / 4, q[0], q[2])
qc.crz(np.pi / 2, q[0], q[1])
qc.h(q[0])
qc.swap(q[0], q[24])
qc.swap(q[1], q[23])
qc.swap(q[2], q[22])
qc.swap(q[3], q[21])
qc.swap(q[4], q[20])
qc.swap(q[5], q[19])
qc.swap(q[6], q[18])
qc.swap(q[7], q[17])
qc.swap(q[8], q[16])
qc.swap(q[9], q[15])
qc.swap(q[10], q[14])
qc.swap(q[11], q[13])
qc.measure_all()
return qc
if __name__ == "__main__":
unittest.main()
|
https://github.com/quantastica/qiskit-toaster
|
quantastica
|
import unittest
from qiskit import QuantumRegister, ClassicalRegister
from qiskit import QuantumCircuit, execute
from qiskit.providers.aer import AerSimulator
from math import pi
try:
from . import common
except Exception:
import common
class TestToasterBackend(common.TestToasterBase):
def test_bell_counts(self):
shots = 256
qc = TestToasterBackend.get_bell_qc()
stats = TestToasterBackend.execute_and_get_stats(
self.toaster_backend(), qc, shots
)
self.assertTrue(stats["statevector"] is None)
self.assertEqual(len(stats["counts"]), 2)
self.assertEqual(stats["totalcounts"], shots)
def test_bell_counts_with_seed(self):
shots = 1024
qc = TestToasterBackend.get_bell_qc()
stats1 = TestToasterBackend.execute_and_get_stats(
self.toaster_backend(), qc, shots, seed=1
)
stats2 = TestToasterBackend.execute_and_get_stats(
self.toaster_backend(), qc, shots, seed=1
)
stats3 = TestToasterBackend.execute_and_get_stats(
self.toaster_backend(), qc, shots, seed=2
)
self.assertTrue(stats1["statevector"] is None)
self.assertEqual(len(stats1["counts"]), 2)
self.assertEqual(stats1["totalcounts"], shots)
self.assertEqual(stats1["counts"], stats2["counts"])
self.assertNotEqual(stats1["counts"], stats3["counts"])
def test_teleport_counts(self):
shots = 256
qc = TestToasterBackend.get_teleport_qc()
stats = TestToasterBackend.execute_and_get_stats(
self.toaster_backend(), qc, shots
)
self.assertTrue(stats["statevector"] is None)
self.assertEqual(stats["totalcounts"], shots)
self.assertEqual(len(stats["counts"]), 4)
def test_bell_state_vector(self):
"""
This is test for statevector which means that
even with shots > 1 it should execute only one shot
"""
shots = 256
qc = TestToasterBackend.get_bell_qc()
stats = TestToasterBackend.execute_and_get_stats(
self.toaster_backend(backend_name="statevector_simulator"),
qc,
shots,
)
self.assertEqual(len(stats["statevector"]), 4)
self.assertEqual(len(stats["counts"]), 1)
self.assertEqual(stats["totalcounts"], 1)
def test_teleport_state_vector(self):
"""
This is test for statevector which means that
even with shots > 1 it should execute only one shot
"""
shots = 256
qc = TestToasterBackend.get_teleport_qc()
"""
Let's first run the aer simulation to get statevector
and counts so we can compare those results against forest's
"""
qc_for_aer = qc.copy()
qc_for_aer.save_state()
stats_aer = TestToasterBackend.execute_and_get_stats(
AerSimulator(method="statevector"), qc_for_aer, shots
)
"""
Now execute toaster backend
"""
stats = TestToasterBackend.execute_and_get_stats(
self.toaster_backend(backend_name="statevector_simulator"),
qc,
shots,
)
self.assertEqual(len(stats["counts"]), 1)
self.assertEqual(stats["totalcounts"], 1)
self.assertEqual(
len(stats["statevector"]), len(stats_aer["statevector"])
)
"""
Let's verify that tests are working as expected
by running fail case
"""
stats = TestToasterBackend.execute_and_get_stats(
self.toaster_backend(), qc, shots
)
self.assertTrue(stats["statevector"] is None)
def test_multiple_jobs(self):
qc = self.get_bell_qc()
backend = self.toaster_backend()
jobs = []
for i in range(1, 50):
jobs.append(execute(qc, backend=backend, shots=1))
for job in jobs:
result = job.result()
counts = result.get_counts(qc)
self.assertEqual(len(counts), 1)
def test_multiple_experiments(self):
backend = self.toaster_backend()
qc_list = [self.get_bell_qc(), self.get_teleport_qc()]
job_info = backend.run(qc_list)
bell_counts = job_info.result().get_counts("Bell")
tel_counts = job_info.result().get_counts("Teleport")
self.assertEqual(len(bell_counts), 2)
self.assertEqual(len(tel_counts), 4)
def test_too_many_qubits(self):
qc = QuantumCircuit(name="TooManyQubits")
q = QuantumRegister(100, "q")
qc.add_register(q)
with self.assertRaises(RuntimeError):
TestToasterBackend.execute_and_get_stats(
self.toaster_backend(), qc, 1
)
def test_larger_circuit_statevector(self):
n = 19
qc = QuantumCircuit()
q = QuantumRegister(n, 'q')
#c = ClassicalRegister(n, 'c')
qc.add_register(q)
#qc.add_register(c)
for i in range(n):
qc.h(i)
TestToasterBackend.execute_and_get_stats(
self.toaster_backend('statevector_simulator'), qc, 1
)
@classmethod
def execute_and_get_stats(cls, backend, qc, shots, seed=None):
job = execute(qc, backend=backend, shots=shots, seed_simulator=seed)
job_result = job.result()
counts = job_result.get_counts(qc)
total_counts = 0
for c in counts:
total_counts += counts[c]
try:
state_vector = job_result.get_statevector(qc)
except Exception:
state_vector = None
ret = dict()
ret["counts"] = counts
ret["statevector"] = state_vector
ret["totalcounts"] = total_counts
return ret
@staticmethod
def get_bell_qc():
qc = QuantumCircuit(name="Bell")
q = QuantumRegister(2, "q")
c = ClassicalRegister(2, "c")
qc.add_register(q)
qc.add_register(c)
qc.h(q[0])
qc.cx(q[0], q[1])
qc.measure(q[0], c[0])
qc.measure(q[1], c[1])
return qc
@staticmethod
def get_teleport_qc():
qc = QuantumCircuit(name="Teleport")
q = QuantumRegister(3, "q")
c0 = ClassicalRegister(1, "c0")
c1 = ClassicalRegister(1, "c1")
qc.add_register(q)
qc.add_register(c0)
qc.add_register(c1)
qc.rx(pi / 4, q[0])
qc.h(q[1])
qc.cx(q[1], q[2])
qc.cx(q[0], q[1])
qc.h(q[0])
qc.measure(q[1], c1[0])
qc.x(q[2]).c_if(c1, 1)
qc.measure(q[0], c0[0])
qc.z(q[2]).c_if(c0, 1)
return qc
if __name__ == "__main__":
unittest.main()
|
https://github.com/quantastica/qiskit-toaster
|
quantastica
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2022, 2023.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test the QAOA algorithm."""
import unittest
from functools import partial
from test.python.algorithms import QiskitAlgorithmsTestCase
import numpy as np
import rustworkx as rx
from ddt import ddt, idata, unpack
from scipy.optimize import minimize as scipy_minimize
from qiskit import QuantumCircuit
from qiskit_algorithms.minimum_eigensolvers import QAOA
from qiskit_algorithms.optimizers import COBYLA, NELDER_MEAD
from qiskit.circuit import Parameter
from qiskit.primitives import Sampler
from qiskit.quantum_info import Pauli, SparsePauliOp
from qiskit.result import QuasiDistribution
from qiskit.utils import algorithm_globals
W1 = np.array([[0, 1, 0, 1], [1, 0, 1, 0], [0, 1, 0, 1], [1, 0, 1, 0]])
P1 = 1
M1 = SparsePauliOp.from_list(
[
("IIIX", 1),
("IIXI", 1),
("IXII", 1),
("XIII", 1),
]
)
S1 = {"0101", "1010"}
W2 = np.array(
[
[0.0, 8.0, -9.0, 0.0],
[8.0, 0.0, 7.0, 9.0],
[-9.0, 7.0, 0.0, -8.0],
[0.0, 9.0, -8.0, 0.0],
]
)
P2 = 1
M2 = None
S2 = {"1011", "0100"}
CUSTOM_SUPERPOSITION = [1 / np.sqrt(15)] * 15 + [0]
@ddt
class TestQAOA(QiskitAlgorithmsTestCase):
"""Test QAOA with MaxCut."""
def setUp(self):
super().setUp()
self.seed = 10598
algorithm_globals.random_seed = self.seed
self.sampler = Sampler()
@idata(
[
[W1, P1, M1, S1],
[W2, P2, M2, S2],
]
)
@unpack
def test_qaoa(self, w, reps, mixer, solutions):
"""QAOA test"""
self.log.debug("Testing %s-step QAOA with MaxCut on graph\n%s", reps, w)
qubit_op, _ = self._get_operator(w)
qaoa = QAOA(self.sampler, COBYLA(), reps=reps, mixer=mixer)
result = qaoa.compute_minimum_eigenvalue(operator=qubit_op)
x = self._sample_most_likely(result.eigenstate)
graph_solution = self._get_graph_solution(x)
self.assertIn(graph_solution, solutions)
@idata(
[
[W1, P1, S1],
[W2, P2, S2],
]
)
@unpack
def test_qaoa_qc_mixer(self, w, prob, solutions):
"""QAOA test with a mixer as a parameterized circuit"""
self.log.debug(
"Testing %s-step QAOA with MaxCut on graph with a mixer as a parameterized circuit\n%s",
prob,
w,
)
optimizer = COBYLA()
qubit_op, _ = self._get_operator(w)
num_qubits = qubit_op.num_qubits
mixer = QuantumCircuit(num_qubits)
theta = Parameter("θ")
mixer.rx(theta, range(num_qubits))
qaoa = QAOA(self.sampler, optimizer, reps=prob, mixer=mixer)
result = qaoa.compute_minimum_eigenvalue(operator=qubit_op)
x = self._sample_most_likely(result.eigenstate)
graph_solution = self._get_graph_solution(x)
self.assertIn(graph_solution, solutions)
def test_qaoa_qc_mixer_many_parameters(self):
"""QAOA test with a mixer as a parameterized circuit with the num of parameters > 1."""
optimizer = COBYLA()
qubit_op, _ = self._get_operator(W1)
num_qubits = qubit_op.num_qubits
mixer = QuantumCircuit(num_qubits)
for i in range(num_qubits):
theta = Parameter("θ" + str(i))
mixer.rx(theta, range(num_qubits))
qaoa = QAOA(self.sampler, optimizer, reps=2, mixer=mixer)
result = qaoa.compute_minimum_eigenvalue(operator=qubit_op)
x = self._sample_most_likely(result.eigenstate)
self.log.debug(x)
graph_solution = self._get_graph_solution(x)
self.assertIn(graph_solution, S1)
def test_qaoa_qc_mixer_no_parameters(self):
"""QAOA test with a mixer as a parameterized circuit with zero parameters."""
qubit_op, _ = self._get_operator(W1)
num_qubits = qubit_op.num_qubits
mixer = QuantumCircuit(num_qubits)
# just arbitrary circuit
mixer.rx(np.pi / 2, range(num_qubits))
qaoa = QAOA(self.sampler, COBYLA(), reps=1, mixer=mixer)
result = qaoa.compute_minimum_eigenvalue(operator=qubit_op)
# we just assert that we get a result, it is not meaningful.
self.assertIsNotNone(result.eigenstate)
def test_change_operator_size(self):
"""QAOA change operator size test"""
qubit_op, _ = self._get_operator(
np.array([[0, 1, 0, 1], [1, 0, 1, 0], [0, 1, 0, 1], [1, 0, 1, 0]])
)
qaoa = QAOA(self.sampler, COBYLA(), reps=1)
result = qaoa.compute_minimum_eigenvalue(operator=qubit_op)
x = self._sample_most_likely(result.eigenstate)
graph_solution = self._get_graph_solution(x)
with self.subTest(msg="QAOA 4x4"):
self.assertIn(graph_solution, {"0101", "1010"})
qubit_op, _ = self._get_operator(
np.array(
[
[0, 1, 0, 1, 0, 1],
[1, 0, 1, 0, 1, 0],
[0, 1, 0, 1, 0, 1],
[1, 0, 1, 0, 1, 0],
[0, 1, 0, 1, 0, 1],
[1, 0, 1, 0, 1, 0],
]
)
)
result = qaoa.compute_minimum_eigenvalue(operator=qubit_op)
x = self._sample_most_likely(result.eigenstate)
graph_solution = self._get_graph_solution(x)
with self.subTest(msg="QAOA 6x6"):
self.assertIn(graph_solution, {"010101", "101010"})
@idata([[W2, S2, None], [W2, S2, [0.0, 0.0]], [W2, S2, [1.0, 0.8]]])
@unpack
def test_qaoa_initial_point(self, w, solutions, init_pt):
"""Check first parameter value used is initial point as expected"""
qubit_op, _ = self._get_operator(w)
first_pt = []
def cb_callback(eval_count, parameters, mean, metadata):
nonlocal first_pt
if eval_count == 1:
first_pt = list(parameters)
qaoa = QAOA(
self.sampler,
COBYLA(),
initial_point=init_pt,
callback=cb_callback,
)
result = qaoa.compute_minimum_eigenvalue(operator=qubit_op)
x = self._sample_most_likely(result.eigenstate)
graph_solution = self._get_graph_solution(x)
with self.subTest("Initial Point"):
# If None the preferred random initial point of QAOA variational form
if init_pt is None:
self.assertLess(result.eigenvalue, -0.97)
else:
self.assertListEqual(init_pt, first_pt)
with self.subTest("Solution"):
self.assertIn(graph_solution, solutions)
def test_qaoa_random_initial_point(self):
"""QAOA random initial point"""
w = rx.adjacency_matrix(
rx.undirected_gnp_random_graph(5, 0.5, seed=algorithm_globals.random_seed)
)
qubit_op, _ = self._get_operator(w)
qaoa = QAOA(self.sampler, NELDER_MEAD(disp=True), reps=2)
result = qaoa.compute_minimum_eigenvalue(operator=qubit_op)
self.assertLess(result.eigenvalue, -0.97)
def test_optimizer_scipy_callable(self):
"""Test passing a SciPy optimizer directly as callable."""
w = rx.adjacency_matrix(
rx.undirected_gnp_random_graph(5, 0.5, seed=algorithm_globals.random_seed)
)
qubit_op, _ = self._get_operator(w)
qaoa = QAOA(
self.sampler,
partial(scipy_minimize, method="Nelder-Mead", options={"maxiter": 2}),
)
result = qaoa.compute_minimum_eigenvalue(qubit_op)
self.assertEqual(result.cost_function_evals, 5)
def _get_operator(self, weight_matrix):
"""Generate Hamiltonian for the max-cut problem of a graph.
Args:
weight_matrix (numpy.ndarray) : adjacency matrix.
Returns:
PauliSumOp: operator for the Hamiltonian
float: a constant shift for the obj function.
"""
num_nodes = weight_matrix.shape[0]
pauli_list = []
shift = 0
for i in range(num_nodes):
for j in range(i):
if weight_matrix[i, j] != 0:
x_p = np.zeros(num_nodes, dtype=bool)
z_p = np.zeros(num_nodes, dtype=bool)
z_p[i] = True
z_p[j] = True
pauli_list.append([0.5 * weight_matrix[i, j], Pauli((z_p, x_p))])
shift -= 0.5 * weight_matrix[i, j]
lst = [(pauli[1].to_label(), pauli[0]) for pauli in pauli_list]
return SparsePauliOp.from_list(lst), shift
def _get_graph_solution(self, x: np.ndarray) -> str:
"""Get graph solution from binary string.
Args:
x : binary string as numpy array.
Returns:
a graph solution as string.
"""
return "".join([str(int(i)) for i in 1 - x])
def _sample_most_likely(self, state_vector: QuasiDistribution) -> np.ndarray:
"""Compute the most likely binary string from state vector.
Args:
state_vector: Quasi-distribution.
Returns:
Binary string as numpy.ndarray of ints.
"""
values = list(state_vector.values())
n = int(np.log2(len(values)))
k = np.argmax(np.abs(values))
x = np.zeros(n)
for i in range(n):
x[i] = k % 2
k >>= 1
return x
if __name__ == "__main__":
unittest.main()
|
https://github.com/qiskit-community/qiskit-toqm
|
qiskit-community
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2022.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
import qiskit
from qiskit.transpiler import TranspilerError
import qiskit_toqm.native as toqm
from itertools import chain
def _calc_swap_durations(coupling_map, instruction_durations, basis_gates, backend_properties, target):
"""Calculates the durations of swap gates between each coupling on the target."""
# Filter for couplings that don't already have a native swap.
couplings = [
c for c in coupling_map.get_edges()
if ("swap", c) not in instruction_durations.duration_by_name_qubits
]
if not couplings:
return
backend_aware = target is not None or (basis_gates is not None and backend_properties is not None)
if not backend_aware:
raise TranspilerError(
"`target` must be specified, or both 'basis_gates' and 'backend_properties' must be specified unless"
"'instruction_durations' has durations for all swap gates."
)
def gen_swap_circuit(s, t):
# Generates a circuit with a single swap gate between src and tgt
c = qiskit.QuantumCircuit(coupling_map.size())
c.swap(s, t)
return c
# Batch transpile generated swap circuits
swap_circuits = qiskit.transpile(
[gen_swap_circuit(*pair) for pair in couplings],
basis_gates=basis_gates,
coupling_map=coupling_map,
backend_properties=backend_properties if target is None else None,
instruction_durations=instruction_durations,
target=target,
optimization_level=0,
layout_method="trivial",
scheduling_method="asap"
)
for (src, tgt), qc in zip(couplings, swap_circuits):
if instruction_durations.dt is None and qc.unit == "dt":
# TODO: should be able to convert by looking up an op in both
raise TranspilerError("Incompatible units.")
duration = qc.qubit_duration(src, tgt)
yield src, tgt, duration
def latencies_from_target(
coupling_map=None,
instruction_durations=None,
basis_gates=None,
backend_properties=None,
target=None,
normalize_scale=2
):
"""
Generate a list of native ``LatencyDescription`` objects for
the specified target device.
Args:
coupling_map (Optional[CouplingMap]): CouplingMap of the target backend.
Required unless ``target`` is specified.
instruction_durations (Optional[InstructionDurations]): Durations for gates
in the target's basis. Must include durations for all gates
that appear in input DAGs other than ``swap`` (for which
durations are calculated through decomposition if not supplied).
Required unless ``target`` is specified.
basis_gates (Optional[List[str]]): The list of basis gates for the
target. Required unless ``instruction_durations``
contains durations for all swap gates or ``target`` is specified.
backend_properties (Optional[BackendProperties]): The backend
properties of the target. Required unless
``instruction_durations`` contains durations for all swap gates
or ``target`` is specified.
target (Optional[Target]): The backend transpiler target. If specified,
overrides ``coupling_map``, ``instruction_durations``, ``basis_gates``,
and ``backend_properties``. All gates that appear in input DAG other
than ``swap`` must be supported by the target and have duration
information available therein.
normalize_scale (int): Multiple by this factor when converting
relative durations to cycle count. The conversion is:
cycles = ceil(duration * NORMALIZE_SCALE / min_duration)
where min_duration is the length of the fastest non-zero duration
instruction on the target.
"""
if target is not None:
coupling_map = target.build_coupling_map()
instruction_durations = target.durations()
basis_gates = target.operation_names
unit = "dt" if instruction_durations.dt else "s"
swap_durations = list(_calc_swap_durations(coupling_map, instruction_durations, basis_gates, backend_properties, target))
default_op_durations = [
(op_name, instruction_durations.get(op_name, [], unit))
for op_name in instruction_durations.duration_by_name
]
op_durations = [
(op_name, bits, instruction_durations.get(op_name, bits, unit))
for (op_name, bits) in instruction_durations.duration_by_name_qubits
]
non_zero_durations = [d for d in chain(
(d for (_, d) in default_op_durations),
(d for (_, _, d) in op_durations),
(d for (_, _, d) in swap_durations)
) if d > 0]
if not non_zero_durations:
raise TranspilerError("Durations must be specified for the target.")
min_duration = min(non_zero_durations)
def normalize(d):
return round(d * normalize_scale / min_duration)
# Yield latency descriptions with durations interpolated to cycles.
for op_name, duration in default_op_durations:
# We don't know if the instruction is for 1 or 2 qubits, so emit
# defaults for both.
yield toqm.LatencyDescription(1, op_name, normalize(duration))
yield toqm.LatencyDescription(2, op_name, normalize(duration))
for op_name, qubits, duration in op_durations:
yield toqm.LatencyDescription(op_name, *qubits, normalize(duration))
for src, tgt, duration in swap_durations:
yield toqm.LatencyDescription("swap", src, tgt, normalize(duration))
def latencies_from_simple(one_qubit_cycles, two_qubit_cycles, swap_cycles):
"""
Generate a list of native ``LatencyDescription`` objects for
the specified hard-coded cycle counts.
The resulting latency descriptions describe a circuit in which
all 1Q, 2Q, and SWAP gates execute in the corresponding number
of cycles, irrespective of which qubits they execute on.
Args:
one_qubit_cycles (int): The number of cycles for all 1Q gates.
two_qubit_cycles (int): The number of cycles for all 2Q gates.
swap_cycles (int): The number of cycles for all swap gates.
"""
return [
toqm.LatencyDescription(1, one_qubit_cycles),
toqm.LatencyDescription(2, two_qubit_cycles),
toqm.LatencyDescription(2, "swap", swap_cycles)
]
|
https://github.com/qiskit-community/qiskit-toqm
|
qiskit-community
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2022.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
import qiskit_toqm.native as toqm
class ToqmHeuristicStrategy:
def __init__(self, latency_descriptions, top_k, queue_target, queue_max, retain_popped=1):
"""
Constructs a TOQM strategy that aims to minimize overall circuit duration.
The priority queue used in the A* is configured to drop the worst nodes
whenever it reaches the queue size limit. Node expansion is also limited
to exploring the best ``K`` children.
Args:
latency_descriptions (List[toqm.LatencyDescription]): The latency descriptions
for all gates that will appear in the circuit, including swaps.
top_k (int): The maximum number of best child nodes that can be pushed to the
queue during expansion of any given node.
queue_target (int): When the priority queue reaches capacity, nodes are dropped
until the size reaches this value.
queue_max (int): The priority queue capacity.
retain_popped (int): Final nodes to retain.
Raises:
RuntimeError: No routing was found.
"""
# The following defaults are based on:
# https://github.com/time-optimal-qmapper/TOQM/blob/main/code/README.txt
self.mapper = toqm.ToqmMapper(
toqm.TrimSlowNodes(queue_max, queue_target),
toqm.GreedyTopK(top_k),
toqm.CXFrontier(),
toqm.Table(list(latency_descriptions)),
[toqm.GreedyMapper()],
[],
0
)
self.mapper.setRetainPopped(retain_popped)
def __call__(self, gates, num_qubits, coupling_map):
"""
Run native ToqmMapper and return the native result.
Args:
gates (List[toqm.GateOp]): The topologically ordered list of gate operations.
num_qubits (int): The number of virtual qubits used in the circuit.
coupling_map (toqm.CouplingMap): The coupling map of the target.
Returns:
toqm.ToqmResult: The native result.
"""
return self.mapper.run(gates, num_qubits, coupling_map)
class ToqmOptimalStrategy:
def __init__(self, latency_descriptions, perform_layout=True, no_swaps=False):
"""
Constructs a TOQM strategy that finds an optimal (minimal) routing
in terms of overall circuit duration.
Args:
latency_descriptions (List[toqm.LatencyDescription]): The latency descriptions
for all gates that will appear in the circuit, including swaps.
perform_layout (Boolean): If true, permutes the initial layout rather than
inserting swap gates at the start of the circuit.
no_swaps (Boolean): If true, attempts to find a routing without inserting swaps.
Raises:
RuntimeError: No routing was found.
"""
# The following defaults are based on:
# https://github.com/time-optimal-qmapper/TOQM/blob/main/code/README.txt
self.mapper = toqm.ToqmMapper(
toqm.DefaultQueue(),
toqm.NoSwaps() if no_swaps else toqm.DefaultExpander(),
toqm.CXFrontier(),
toqm.Table(latency_descriptions),
[],
[toqm.HashFilter(), toqm.HashFilter2()],
-1 if perform_layout else 0
)
def __call__(self, gates, num_qubits, coupling_map):
"""
Run native ToqmMapper and return the native result.
Args:
gates (List[toqm.GateOp]): The topologically ordered list of gate operations.
num_qubits (int): The number of virtual qubits used in the circuit.
coupling_map (toqm.CouplingMap): The coupling map of the target.
Returns:
toqm.ToqmResult: The native result.
"""
return self.mapper.run(gates, num_qubits, coupling_map)
|
https://github.com/qiskit-community/qiskit-toqm
|
qiskit-community
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2022.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
import logging
import qiskit_toqm.native as toqm
from qiskit.circuit.library.standard_gates import SwapGate
from qiskit.dagcircuit import DAGCircuit
from qiskit.transpiler.basepasses import TransformationPass
from qiskit.transpiler.exceptions import TranspilerError
logger = logging.getLogger(__name__)
class ToqmSwap(TransformationPass):
r"""Map input circuit onto a backend topology via insertion of SWAPs.
Implementation of the SWAP-based approach from Time-Optimal Qubit
Mapping paper [1].
**References:**
[1] Chi Zhang, Ari B. Hayes, Longfei Qiu, Yuwei Jin, Yanhao Chen, and Eddy Z. Zhang. 2021. Time-Optimal Qubit
Mapping. In Proceedings of the 26th ACM International Conference on Architectural Support for Programming
Languages and Operating Systems (ASPLOS ’21), April 19–23, 2021, Virtual, USA.
ACM, New York, NY, USA, 14 pages.
`<https://doi.org/10.1145/3445814.3446706>`_
"""
def __init__(
self,
coupling_map,
strategy):
"""
ToqmSwap initializer.
Args:
coupling_map (CouplingMap): CouplingMap of the target backend.
strategy (typing.Callable[[List[toqm.GateOp], int, toqm.CouplingMap], toqm.ToqmResult]):
A callable responsible for running the native ``ToqmMapper`` and
returning a native ``ToqmResult``.
"""
super().__init__()
if coupling_map is None:
# We cannot construct a proper TOQM mapper without a coupling map,
# but we gracefully handle construction without one, and then
# assert that `run` is never called on this instance.
return
if coupling_map.size() > 127:
raise TranspilerError("ToqmSwap currently supports a max of 127 qubits.")
self.coupling_map = coupling_map
self.toqm_strategy = strategy
self.toqm_result = None
def run(self, dag: DAGCircuit):
"""Run the ToqmSwap pass on `dag`.
Args:
dag (DAGCircuit): the directed acyclic graph to be mapped.
Returns:
DAGCircuit: A dag mapped to be compatible with the coupling_map.
Raises:
TranspilerError: if the coupling map or the layout are not
compatible with the DAG
"""
if self.coupling_map is None:
raise TranspilerError("TOQM swap not properly initialized.")
if len(dag.qregs) != 1 or dag.qregs.get("q", None) is None:
raise TranspilerError("TOQM swap runs on physical circuits only.")
if len(dag.qubits) > self.coupling_map.size():
raise TranspilerError("More virtual qubits exist than physical.")
reg = dag.qregs["q"]
# Generate UIDs for each gate node from the original circuit so we can
# look them up later when rebuilding the circuit.
# Note: this is still sorted by topological order from above.
uid_to_op_node = {uid: op for uid, op in enumerate(dag.topological_op_nodes())}
# Create TOQM topological gate list
def gates():
for uid, node in uid_to_op_node.items():
if len(node.qargs) == 2:
yield toqm.GateOp(uid, node.op.name, reg.index(node.qargs[0]), reg.index(node.qargs[1]))
elif len(node.qargs) == 1:
yield toqm.GateOp(uid, node.op.name, reg.index(node.qargs[0]))
else:
raise TranspilerError(f"ToqmSwap only works with 1q and 2q gates! "
f"Bad gate: {node.op.name} {node.qargs}")
gate_ops = list(gates())
edges = {e for e in self.coupling_map.get_edges()}
couplings = toqm.CouplingMap(self.coupling_map.size(), edges)
self.toqm_result = self.toqm_strategy(gate_ops, dag.num_qubits(), couplings)
# Preserve input DAG's name, regs, wire_map, etc. but replace the graph.
mapped_dag = dag.copy_empty_like()
for g in self.toqm_result.scheduledGates:
if g.gateOp.type.lower() == "swap":
mapped_dag.apply_operation_back(SwapGate(), qargs=[reg[g.physicalControl], reg[g.physicalTarget]])
continue
original_op = uid_to_op_node[g.gateOp.uid]
if g.physicalControl >= 0:
mapped_dag.apply_operation_back(original_op.op, cargs=original_op.cargs, qargs=[
reg[g.physicalControl],
reg[g.physicalTarget]
])
else:
mapped_dag.apply_operation_back(original_op.op, cargs=original_op.cargs, qargs=[
reg[g.physicalTarget]
])
self._update_layout()
return mapped_dag
def _update_layout(self):
layout = self.property_set['layout']
# Need to copy this mapping since layout updates
# might overwrite original vbits we need to read!
p2v = layout.get_physical_bits().copy()
# Update the layout if TOQM made changes.
ancilla_vbits = []
for vidx in range(self.toqm_result.numPhysicalQubits):
pidx = self.toqm_result.inferredLaq[vidx]
if pidx == -1:
# bit is not mapped to physical qubit
ancilla_vbits.append(p2v[vidx])
continue
if pidx != vidx:
# Bit was remapped!
# First, we need to get the original virtual bit from the layout.
vbit = p2v[vidx]
# Then, map updated pidx from TOQM to original virtual bit.
layout[pidx] = vbit
# Map any unmapped physical bits to ancilla.
for pidx, vidx in enumerate(self.toqm_result.inferredQal):
if vidx < 0:
# Current physical bit isn't mapped. Map it to an ancilla.
layout[pidx] = ancilla_vbits.pop(0)
|
https://github.com/qiskit-community/qiskit-toqm
|
qiskit-community
|
import unittest
import qiskit_toqm.native as toqm
class TestTOQM(unittest.TestCase):
def test_version(self):
self.assertEqual(toqm.__version__, "0.1.0")
def test_basic(self):
num_q = 4
gates = [
toqm.GateOp(0, "cx", 0, 1),
toqm.GateOp(1, "cx", 0, 2),
toqm.GateOp(2, "cx", 0, 3),
toqm.GateOp(3, "cx", 1, 2),
toqm.GateOp(4, "cx", 1, 3),
toqm.GateOp(5, "cx", 2, 3)
]
coupling = toqm.CouplingMap(5, {(0, 1), (0, 2), (1, 2), (2, 3), (2, 4), (3, 4)})
q = toqm.DefaultQueue()
exp = toqm.DefaultExpander()
cf = toqm.CXFrontier()
lat = toqm.Latency_1_2_6()
fs = [toqm.HashFilter(), toqm.HashFilter2()]
nms = []
mapper = toqm.ToqmMapper(q, exp, cf, lat, nms, fs, -1)
mapper.setRetainPopped(0)
result = mapper.run(gates, num_q, coupling)
# Print result
for g in result.scheduledGates:
print(f"{g.gateOp.type} ", end='')
if g.physicalControl >= 0:
print(f"q[{g.physicalControl}],", end='')
print(f"q[{g.physicalTarget}]; ", end='')
print(f"//cycle: {g.cycle}", end='')
if (g.gateOp.type.lower() != "swap"):
print(f" //{g.gateOp.type} ", end='')
if g.gateOp.control >= 0:
print(f"q[{g.gateOp.control}],", end='')
print(f"q[{g.gateOp.target}]; ", end='')
print()
|
https://github.com/jatin-47/QGSS-2021
|
jatin-47
|
import numpy as np
# Importing standard Qiskit libraries
from qiskit import QuantumCircuit, transpile, assemble, Aer, IBMQ, execute
from qiskit.quantum_info import Statevector
from qiskit.visualization import plot_bloch_multivector, plot_histogram
from qiskit_textbook.problems import dj_problem_oracle
def lab1_ex1():
qc = QuantumCircuit(1)
#
#
# FILL YOUR CODE IN HERE
#
#
qc.x(0)
return qc
state = Statevector.from_instruction(lab1_ex1())
plot_bloch_multivector(state)
from qc_grader import grade_lab1_ex1
# Note that the grading function is expecting a quantum circuit without measurements
grade_lab1_ex1(lab1_ex1())
def lab1_ex2():
qc = QuantumCircuit(1)
#
#
# FILL YOUR CODE IN HERE
#
#
qc.h(0)
return qc
state = Statevector.from_instruction(lab1_ex2())
plot_bloch_multivector(state)
from qc_grader import grade_lab1_ex2
# Note that the grading function is expecting a quantum circuit without measurements
grade_lab1_ex2(lab1_ex2())
def lab1_ex3():
qc = QuantumCircuit(1)
#
#
# FILL YOUR CODE IN HERE
#
#
qc.x(0)
qc.h(0)
return qc
state = Statevector.from_instruction(lab1_ex3())
plot_bloch_multivector(state)
from qc_grader import grade_lab1_ex3
# Note that the grading function is expecting a quantum circuit without measurements
grade_lab1_ex3(lab1_ex3())
def lab1_ex4():
qc = QuantumCircuit(1)
#
#
# FILL YOUR CODE IN HERE
#
#
qc.h(0)
qc.sdg(0)
return qc
state = Statevector.from_instruction(lab1_ex4())
plot_bloch_multivector(state)
from qc_grader import grade_lab1_ex4
# Note that the grading function is expecting a quantum circuit without measurements
grade_lab1_ex4(lab1_ex4())
def lab1_ex5():
qc = QuantumCircuit(2,2) # this time, we not only want two qubits, but also two classical bits for the measurement
#
#
# FILL YOUR CODE IN HERE
#
#
qc.h(0)
qc.cx(0,1)
qc.x(0)
return qc
qc = lab1_ex5()
qc.draw() # we draw the circuit
from qc_grader import grade_lab1_ex5
# Note that the grading function is expecting a quantum circuit without measurements
grade_lab1_ex5(lab1_ex5())
qc.measure(0, 0) # we perform a measurement on qubit q_0 and store the information on the classical bit c_0
qc.measure(1, 1) # we perform a measurement on qubit q_1 and store the information on the classical bit c_1
backend = Aer.get_backend('qasm_simulator') # we choose the simulator as our backend
counts = execute(qc, backend, shots = 1000).result().get_counts() # we run the simulation and get the counts
plot_histogram(counts) # let us plot a histogram to see the possible outcomes and corresponding probabilities
def lab1_ex6():
#
#
# FILL YOUR CODE IN HERE
#
#
qc = QuantumCircuit(3,3)
qc.h(0)
qc.cx(0,1)
qc.cx(1,2)
qc.y(1)
return qc
qc = lab1_ex6()
qc.draw() # we draw the circuit
from qc_grader import grade_lab1_ex6
# Note that the grading function is expecting a quantum circuit without measurements
grade_lab1_ex6(lab1_ex6())
oraclenr = 4 # determines the oracle (can range from 1 to 5)
oracle = dj_problem_oracle(oraclenr) # gives one out of 5 oracles
oracle.name = "DJ-Oracle"
def dj_classical(n, input_str):
# build a quantum circuit with n qubits and 1 classical readout bit
dj_circuit = QuantumCircuit(n+1,1)
# Prepare the initial state corresponding to your input bit string
for i in range(n):
if input_str[i] == '1':
dj_circuit.x(i)
# append oracle
dj_circuit.append(oracle, range(n+1))
# measure the fourth qubit
dj_circuit.measure(n,0)
return dj_circuit
n = 4 # number of qubits
input_str = '1111'
dj_circuit = dj_classical(n, input_str)
dj_circuit.draw() # draw the circuit
input_str = '1111'
dj_circuit = dj_classical(n, input_str)
qasm_sim = Aer.get_backend('qasm_simulator')
transpiled_dj_circuit = transpile(dj_circuit, qasm_sim)
qobj = assemble(transpiled_dj_circuit, qasm_sim)
results = qasm_sim.run(qobj).result()
answer = results.get_counts()
plot_histogram(answer)
def lab1_ex7():
min_nr_inputs = 2
max_nr_inputs = 9
return [min_nr_inputs, max_nr_inputs]
from qc_grader import grade_lab1_ex7
# Note that the grading function is expecting a list of two integers
grade_lab1_ex7(lab1_ex7())
n=4
def psi_0(n):
qc = QuantumCircuit(n+1,n)
# Build the state (|00000> - |10000>)/sqrt(2)
#
#
# FILL YOUR CODE IN HERE
#
#
qc.x(4)
qc.h(4)
return qc
dj_circuit = psi_0(n)
dj_circuit.draw()
def psi_1(n):
# obtain the |psi_0> = |00001> state
qc = psi_0(n)
# create the superposition state |psi_1>
#
#
qc.h(0)
qc.h(1)
qc.h(2)
qc.h(3)
#
#
qc.barrier()
return qc
dj_circuit = psi_1(n)
dj_circuit.draw()
def psi_2(oracle,n):
# circuit to obtain psi_1
qc = psi_1(n)
# append the oracle
qc.append(oracle, range(n+1))
return qc
dj_circuit = psi_2(oracle, n)
dj_circuit.draw()
def lab1_ex8(oracle, n): # note that this exercise also depends on the code in the functions psi_0 (In [24]) and psi_1 (In [25])
qc = psi_2(oracle, n)
# apply n-fold hadamard gate
#
#
# FILL YOUR CODE IN HERE
#
#
qc.h(0)
qc.h(1)
qc.h(2)
qc.h(3)
# add the measurement by connecting qubits to classical bits
#
#
qc.measure(0,0)
qc.measure(1,1)
qc.measure(2,2)
qc.measure(3,3)
#
#
return qc
dj_circuit = lab1_ex8(oracle, n)
dj_circuit.draw()
from qc_grader import grade_lab1_ex8
# Note that the grading function is expecting a quantum circuit with measurements
grade_lab1_ex8(lab1_ex8(dj_problem_oracle(4),n))
qasm_sim = Aer.get_backend('qasm_simulator')
transpiled_dj_circuit = transpile(dj_circuit, qasm_sim)
qobj = assemble(transpiled_dj_circuit)
results = qasm_sim.run(qobj).result()
answer = results.get_counts()
plot_histogram(answer)
|
https://github.com/jatin-47/QGSS-2021
|
jatin-47
|
import networkx as nx
import numpy as np
import plotly.graph_objects as go
import matplotlib as mpl
import pandas as pd
from IPython.display import clear_output
from plotly.subplots import make_subplots
from matplotlib import pyplot as plt
from qiskit import Aer
from qiskit import QuantumCircuit
from qiskit.visualization import plot_state_city
from qiskit.algorithms.optimizers import COBYLA, SLSQP, ADAM
from time import time
from copy import copy
from typing import List
from qc_grader.graph_util import display_maxcut_widget, QAOA_widget, graphs
mpl.rcParams['figure.dpi'] = 300
from qiskit.circuit import Parameter, ParameterVector
#Parameters are initialized with a simple string identifier
parameter_0 = Parameter('θ[0]')
parameter_1 = Parameter('θ[1]')
circuit = QuantumCircuit(1)
#We can then pass the initialized parameters as the rotation angle argument to the Rx and Ry gates
circuit.ry(theta = parameter_0, qubit = 0)
circuit.rx(theta = parameter_1, qubit = 0)
circuit.draw('mpl')
parameter = Parameter('θ')
circuit = QuantumCircuit(1)
circuit.ry(theta = parameter, qubit = 0)
circuit.rx(theta = parameter, qubit = 0)
circuit.draw('mpl')
#Set the number of layers and qubits
n=3
num_layers = 2
#ParameterVectors are initialized with a string identifier and an integer specifying the vector length
parameters = ParameterVector('θ', n*(num_layers+1))
circuit = QuantumCircuit(n, n)
for layer in range(num_layers):
#Appending the parameterized Ry gates using parameters from the vector constructed above
for i in range(n):
circuit.ry(parameters[n*layer+i], i)
circuit.barrier()
#Appending the entangling CNOT gates
for i in range(n):
for j in range(i):
circuit.cx(j,i)
circuit.barrier()
#Appending one additional layer of parameterized Ry gates
for i in range(n):
circuit.ry(parameters[n*num_layers+i], i)
circuit.barrier()
circuit.draw('mpl')
print(circuit.parameters)
#Create parameter dictionary with random values to bind
param_dict = {parameter: np.random.random() for parameter in parameters}
print(param_dict)
#Assign parameters using the assign_parameters method
bound_circuit = circuit.assign_parameters(parameters = param_dict)
bound_circuit.draw('mpl')
new_parameters = ParameterVector('Ψ',9)
new_circuit = circuit.assign_parameters(parameters = [k*new_parameters[i] for k in range(9)])
new_circuit.draw('mpl')
#Run the circuit with assigned parameters on Aer's statevector simulator
simulator = Aer.get_backend('statevector_simulator')
result = simulator.run(bound_circuit).result()
statevector = result.get_statevector(bound_circuit)
plot_state_city(statevector)
#The following line produces an error when run because 'circuit' still contains non-assigned parameters
#result = simulator.run(circuit).result()
for key in graphs.keys():
print(key)
graph = nx.Graph()
#Add nodes and edges
graph.add_nodes_from(np.arange(0,6,1))
edges = [(0,1,2.0),(0,2,3.0),(0,3,2.0),(0,4,4.0),(0,5,1.0),(1,2,4.0),(1,3,1.0),(1,4,1.0),(1,5,3.0),(2,4,2.0),(2,5,3.0),(3,4,5.0),(3,5,1.0)]
graph.add_weighted_edges_from(edges)
graphs['custom'] = graph
#Display widget
display_maxcut_widget(graphs['custom'])
def maxcut_cost_fn(graph: nx.Graph, bitstring: List[int]) -> float:
"""
Computes the maxcut cost function value for a given graph and cut represented by some bitstring
Args:
graph: The graph to compute cut values for
bitstring: A list of integer values '0' or '1' specifying a cut of the graph
Returns:
The value of the cut
"""
#Get the weight matrix of the graph
weight_matrix = nx.adjacency_matrix(graph).toarray()
size = weight_matrix.shape[0]
value = 0.
#INSERT YOUR CODE TO COMPUTE THE CUT VALUE HERE
for i in range(size):
for j in range(size):
value+= weight_matrix[i,j]*bitstring[i]*(1-bitstring[j])
return value
def plot_maxcut_histogram(graph: nx.Graph) -> None:
"""
Plots a bar diagram with the values for all possible cuts of a given graph.
Args:
graph: The graph to compute cut values for
"""
num_vars = graph.number_of_nodes()
#Create list of bitstrings and corresponding cut values
bitstrings = ['{:b}'.format(i).rjust(num_vars, '0')[::-1] for i in range(2**num_vars)]
values = [maxcut_cost_fn(graph = graph, bitstring = [int(x) for x in bitstring]) for bitstring in bitstrings]
#Sort both lists by largest cut value
values, bitstrings = zip(*sorted(zip(values, bitstrings)))
#Plot bar diagram
bar_plot = go.Bar(x = bitstrings, y = values, marker=dict(color=values, colorscale = 'plasma', colorbar=dict(title='Cut Value')))
fig = go.Figure(data=bar_plot, layout = dict(xaxis=dict(type = 'category'), width = 1500, height = 600))
fig.show()
plot_maxcut_histogram(graph = graphs['custom'])
from qc_grader import grade_lab2_ex1
bitstring = [1, 0, 1, 1, 0, 0] #DEFINE THE CORRECT MAXCUT BITSTRING HERE
# Note that the grading function is expecting a list of integers '0' and '1'
grade_lab2_ex1(bitstring)
from qiskit_optimization import QuadraticProgram
quadratic_program = QuadraticProgram('sample_problem')
print(quadratic_program.export_as_lp_string())
quadratic_program.binary_var(name = 'x_0')
quadratic_program.integer_var(name = 'x_1')
quadratic_program.continuous_var(name = 'x_2', lowerbound = -2.5, upperbound = 1.8)
quadratic = [[0,1,2],[3,4,5],[0,1,2]]
linear = [10,20,30]
quadratic_program.minimize(quadratic = quadratic, linear = linear, constant = -5)
print(quadratic_program.export_as_lp_string())
def quadratic_program_from_graph(graph: nx.Graph) -> QuadraticProgram:
"""Constructs a quadratic program from a given graph for a MaxCut problem instance.
Args:
graph: Underlying graph of the problem.
Returns:
QuadraticProgram
"""
#Get weight matrix of graph
weight_matrix = nx.adjacency_matrix(graph)
shape = weight_matrix.shape
size = shape[0]
#Build qubo matrix Q from weight matrix W
qubo_matrix = np.zeros((size, size))
qubo_vector = np.zeros(size)
for i in range(size):
for j in range(size):
qubo_matrix[i, j] -= weight_matrix[i, j]
for i in range(size):
for j in range(size):
qubo_vector[i] += weight_matrix[i,j]
#INSERT YOUR CODE HERE
quadratic_program=QuadraticProgram('sample_problem')
for i in range(size):
quadratic_program.binary_var(name='x_{}'.format(i))
quadratic_program.maximize(quadratic =qubo_matrix, linear = qubo_vector)
return quadratic_program
quadratic_program = quadratic_program_from_graph(graphs['custom'])
print(quadratic_program.export_as_lp_string())
from qc_grader import grade_lab2_ex2
# Note that the grading function is expecting a quadratic program
grade_lab2_ex2(quadratic_program)
def qaoa_circuit(qubo: QuadraticProgram, p: int = 1):
"""
Given a QUBO instance and the number of layers p, constructs the corresponding parameterized QAOA circuit with p layers.
Args:
qubo: The quadratic program instance
p: The number of layers in the QAOA circuit
Returns:
The parameterized QAOA circuit
"""
size = len(qubo.variables)
qubo_matrix = qubo.objective.quadratic.to_array(symmetric=True)
qubo_linearity = qubo.objective.linear.to_array()
#Prepare the quantum and classical registers
qaoa_circuit = QuantumCircuit(size,size)
#Apply the initial layer of Hadamard gates to all qubits
qaoa_circuit.h(range(size))
#Create the parameters to be used in the circuit
gammas = ParameterVector('gamma', p)
betas = ParameterVector('beta', p)
#Outer loop to create each layer
for i in range(p):
#Apply R_Z rotational gates from cost layer
#INSERT YOUR CODE HERE
for j in range(size):
qubo_matrix_sum_of_col = 0
for k in range(size):
qubo_matrix_sum_of_col+= qubo_matrix[j][k]
qaoa_circuit.rz(gammas[i]*(qubo_linearity[j]+qubo_matrix_sum_of_col),j)
#Apply R_ZZ rotational gates for entangled qubit rotations from cost layer
#INSERT YOUR CODE HERE
for j in range(size):
for k in range(size):
if j!=k:
qaoa_circuit.rzz(gammas[i]*qubo_matrix[j][k]*0.5,j,k)
# Apply single qubit X - rotations with angle 2*beta_i to all qubits
#INSERT YOUR CODE HERE
for j in range(size):
qaoa_circuit.rx(2*betas[i],j)
return qaoa_circuit
quadratic_program = quadratic_program_from_graph(graphs['custom'])
custom_circuit = qaoa_circuit(qubo = quadratic_program)
test = custom_circuit.assign_parameters(parameters=[1.0]*len(custom_circuit.parameters))
from qc_grader import grade_lab2_ex3
# Note that the grading function is expecting a quantum circuit
grade_lab2_ex3(test)
from qiskit.algorithms import QAOA
from qiskit_optimization.algorithms import MinimumEigenOptimizer
backend = Aer.get_backend('statevector_simulator')
qaoa = QAOA(optimizer = ADAM(), quantum_instance = backend, reps=1, initial_point = [0.1,0.1])
eigen_optimizer = MinimumEigenOptimizer(min_eigen_solver = qaoa)
quadratic_program = quadratic_program_from_graph(graphs['custom'])
result = eigen_optimizer.solve(quadratic_program)
print(result)
def plot_samples(samples):
"""
Plots a bar diagram for the samples of a quantum algorithm
Args:
samples
"""
#Sort samples by probability
samples = sorted(samples, key = lambda x: x.probability)
#Get list of probabilities, function values and bitstrings
probabilities = [sample.probability for sample in samples]
values = [sample.fval for sample in samples]
bitstrings = [''.join([str(int(i)) for i in sample.x]) for sample in samples]
#Plot bar diagram
sample_plot = go.Bar(x = bitstrings, y = probabilities, marker=dict(color=values, colorscale = 'plasma',colorbar=dict(title='Function Value')))
fig = go.Figure(
data=sample_plot,
layout = dict(
xaxis=dict(
type = 'category'
)
)
)
fig.show()
plot_samples(result.samples)
graph_name = 'custom'
quadratic_program = quadratic_program_from_graph(graph=graphs[graph_name])
trajectory={'beta_0':[], 'gamma_0':[], 'energy':[]}
offset = 1/4*quadratic_program.objective.quadratic.to_array(symmetric = True).sum() + 1/2*quadratic_program.objective.linear.to_array().sum()
def callback(eval_count, params, mean, std_dev):
trajectory['beta_0'].append(params[1])
trajectory['gamma_0'].append(params[0])
trajectory['energy'].append(-mean + offset)
optimizers = {
'cobyla': COBYLA(),
'slsqp': SLSQP(),
'adam': ADAM()
}
qaoa = QAOA(optimizer = optimizers['cobyla'], quantum_instance = backend, reps=1, initial_point = [6.2,1.8],callback = callback)
eigen_optimizer = MinimumEigenOptimizer(min_eigen_solver = qaoa)
result = eigen_optimizer.solve(quadratic_program)
fig = QAOA_widget(landscape_file=f'./resources/energy_landscapes/{graph_name}.csv', trajectory = trajectory, samples = result.samples)
fig.show()
graph_name = 'custom'
quadratic_program = quadratic_program_from_graph(graphs[graph_name])
#Create callback to record total number of evaluations
max_evals = 0
def callback(eval_count, params, mean, std_dev):
global max_evals
max_evals = eval_count
#Create empty lists to track values
energies = []
runtimes = []
num_evals=[]
#Run QAOA for different values of p
for p in range(1,10):
print(f'Evaluating for p = {p}...')
qaoa = QAOA(optimizer = optimizers['cobyla'], quantum_instance = backend, reps=p, callback=callback)
eigen_optimizer = MinimumEigenOptimizer(min_eigen_solver = qaoa)
start = time()
result = eigen_optimizer.solve(quadratic_program)
runtimes.append(time()-start)
num_evals.append(max_evals)
#Calculate energy of final state from samples
avg_value = 0.
for sample in result.samples:
avg_value += sample.probability*sample.fval
energies.append(avg_value)
#Create and display plots
energy_plot = go.Scatter(x = list(range(1,10)), y =energies, marker=dict(color=energies, colorscale = 'plasma'))
runtime_plot = go.Scatter(x = list(range(1,10)), y =runtimes, marker=dict(color=runtimes, colorscale = 'plasma'))
num_evals_plot = go.Scatter(x = list(range(1,10)), y =num_evals, marker=dict(color=num_evals, colorscale = 'plasma'))
fig = make_subplots(rows = 1, cols = 3, subplot_titles = ['Energy value', 'Runtime', 'Number of evaluations'])
fig.update_layout(width=1800,height=600, showlegend=False)
fig.add_trace(energy_plot, row=1, col=1)
fig.add_trace(runtime_plot, row=1, col=2)
fig.add_trace(num_evals_plot, row=1, col=3)
clear_output()
fig.show()
def plot_qaoa_energy_landscape(graph: nx.Graph, cvar: float = None):
num_shots = 1000
seed = 42
simulator = Aer.get_backend('qasm_simulator')
simulator.set_options(seed_simulator = 42)
#Generate circuit
circuit = qaoa_circuit(qubo = quadratic_program_from_graph(graph), p=1)
circuit.measure(range(graph.number_of_nodes()),range(graph.number_of_nodes()))
#Create dictionary with precomputed cut values for all bitstrings
cut_values = {}
size = graph.number_of_nodes()
for i in range(2**size):
bitstr = '{:b}'.format(i).rjust(size, '0')[::-1]
x = [int(bit) for bit in bitstr]
cut_values[bitstr] = maxcut_cost_fn(graph, x)
#Perform grid search over all parameters
data_points = []
max_energy = None
for beta in np.linspace(0,np.pi, 50):
for gamma in np.linspace(0, 4*np.pi, 50):
bound_circuit = circuit.assign_parameters([beta, gamma])
result = simulator.run(bound_circuit, shots = num_shots).result()
statevector = result.get_counts(bound_circuit)
energy = 0
measured_cuts = []
for bitstring, count in statevector.items():
measured_cuts = measured_cuts + [cut_values[bitstring]]*count
if cvar is None:
#Calculate the mean of all cut values
energy = sum(measured_cuts)/num_shots
else:
#raise NotImplementedError()
#INSERT YOUR CODE HERE
measured_cuts = sorted(measured_cuts, reverse = True)
for w in range(int(cvar*num_shots)):
energy += measured_cuts[w]/int((cvar*num_shots))
#Update optimal parameters
if max_energy is None or energy > max_energy:
max_energy = energy
optimum = {'beta': beta, 'gamma': gamma, 'energy': energy}
#Update data
data_points.append({'beta': beta, 'gamma': gamma, 'energy': energy})
#Create and display surface plot from data_points
df = pd.DataFrame(data_points)
df = df.pivot(index='beta', columns='gamma', values='energy')
matrix = df.to_numpy()
beta_values = df.index.tolist()
gamma_values = df.columns.tolist()
surface_plot = go.Surface(
x=gamma_values,
y=beta_values,
z=matrix,
coloraxis = 'coloraxis'
)
fig = go.Figure(data = surface_plot)
fig.show()
#Return optimum
return optimum
graph = graphs['custom']
optimal_parameters = plot_qaoa_energy_landscape(graph = graph)
print('Optimal parameters:')
print(optimal_parameters)
optimal_parameters = plot_qaoa_energy_landscape(graph = graph, cvar = 0.2)
print(optimal_parameters)
from qc_grader import grade_lab2_ex4
# Note that the grading function is expecting a python dictionary
# with the entries 'beta', 'gamma' and 'energy'
grade_lab2_ex4(optimal_parameters)
|
https://github.com/jatin-47/QGSS-2021
|
jatin-47
|
# General Imports
import numpy as np
# Visualisation Imports
import matplotlib.pyplot as plt
# Scikit Imports
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler, MinMaxScaler
# Qiskit Imports
from qiskit import Aer, execute
from qiskit.circuit import QuantumCircuit, Parameter, ParameterVector
from qiskit.circuit.library import PauliFeatureMap, ZFeatureMap, ZZFeatureMap
from qiskit.circuit.library import TwoLocal, NLocal, RealAmplitudes, EfficientSU2
from qiskit.circuit.library import HGate, RXGate, RYGate, RZGate, CXGate, CRXGate, CRZGate
from qiskit_machine_learning.kernels import QuantumKernel
# Load digits dataset
digits = datasets.load_digits(n_class=2)
# Plot example '0' and '1'
fig, axs = plt.subplots(1, 2, figsize=(6,3))
axs[0].set_axis_off()
axs[0].imshow(digits.images[0], cmap=plt.cm.gray_r, interpolation='nearest')
axs[1].set_axis_off()
axs[1].imshow(digits.images[1], cmap=plt.cm.gray_r, interpolation='nearest')
plt.show()
# Split dataset
sample_train, sample_test, label_train, label_test = train_test_split(
digits.data, digits.target, test_size=0.2, random_state=22)
# Reduce dimensions
n_dim = 4
pca = PCA(n_components=n_dim).fit(sample_train)
sample_train = pca.transform(sample_train)
sample_test = pca.transform(sample_test)
# Normalise
std_scale = StandardScaler().fit(sample_train)
sample_train = std_scale.transform(sample_train)
sample_test = std_scale.transform(sample_test)
# Scale
samples = np.append(sample_train, sample_test, axis=0)
minmax_scale = MinMaxScaler((-1, 1)).fit(samples)
sample_train = minmax_scale.transform(sample_train)
sample_test = minmax_scale.transform(sample_test)
# Select
train_size = 100
sample_train = sample_train[:train_size]
label_train = label_train[:train_size]
test_size = 20
sample_test = sample_test[:test_size]
label_test = label_test[:test_size]
print(sample_train[0], label_train[0])
print(sample_test[0], label_test[0])
# 3 features, depth 2
map_z = ZFeatureMap(feature_dimension=3, reps=2)
map_z.draw('mpl')
# 3 features, depth 1
map_zz = ZZFeatureMap(feature_dimension=3, reps=1)
map_zz.draw('mpl')
# 3 features, depth 1, linear entanglement
map_zz = ZZFeatureMap(feature_dimension=3, reps=1, entanglement='linear')
map_zz.draw('mpl')
# 3 features, depth 1, circular entanglement
map_zz = ZZFeatureMap(feature_dimension=3, reps=1, entanglement='circular')
map_zz.draw('mpl')
# 3 features, depth 1
map_pauli = PauliFeatureMap(feature_dimension=3, reps=1, paulis = ['X', 'Y', 'ZZ'])
map_pauli.draw('mpl')
def custom_data_map_func(x):
coeff = x[0] if len(x) == 1 else reduce(lambda m, n: m * n, np.sin(np.pi - x))
return coeff
map_customdatamap = PauliFeatureMap(feature_dimension=3, reps=1, paulis=['Z','ZZ'],
data_map_func=custom_data_map_func)
#map_customdatamap.draw() # qiskit isn't able to draw the circuit with np.sin in the custom data map
twolocal = TwoLocal(num_qubits=3, reps=2, rotation_blocks=['ry','rz'],
entanglement_blocks='cx', entanglement='circular', insert_barriers=True)
twolocal.draw('mpl')
twolocaln = NLocal(num_qubits=3, reps=2,
rotation_blocks=[RYGate(Parameter('a')), RZGate(Parameter('a'))],
entanglement_blocks=CXGate(),
entanglement='circular', insert_barriers=True)
twolocaln.draw('mpl')
# rotation block:
rot = QuantumCircuit(2)
params = ParameterVector('r', 2)
rot.ry(params[0], 0)
rot.rz(params[1], 1)
# entanglement block:
ent = QuantumCircuit(4)
params = ParameterVector('e', 3)
ent.crx(params[0], 0, 1)
ent.crx(params[1], 1, 2)
ent.crx(params[2], 2, 3)
nlocal = NLocal(num_qubits=6, rotation_blocks=rot, entanglement_blocks=ent,
entanglement='linear', insert_barriers=True)
nlocal.draw('mpl')
qubits = 3
repeats = 2
x = ParameterVector('x', length=qubits)
var_custom = QuantumCircuit(qubits)
for _ in range(repeats):
for i in range(qubits):
var_custom.rx(x[i], i)
for i in range(qubits):
for j in range(i + 1, qubits):
var_custom.cx(i, j)
var_custom.p(x[i] * x[j], j)
var_custom.cx(i, j)
var_custom.barrier()
var_custom.draw('mpl')
print(sample_train[0])
encode_map = ZZFeatureMap(feature_dimension=4, reps=2, entanglement='linear', insert_barriers=True)
encode_circuit = encode_map.bind_parameters(sample_train[0])
encode_circuit.draw(output='mpl')
x = [-0.1,0.2]
# YOUR CODE HERE
encode_map_x =ZZFeatureMap(feature_dimension=2, reps=4)
ex1_circuit =encode_map_x.bind_parameters(x)
ex1_circuit.draw(output='mpl')
from qc_grader import grade_lab3_ex1
# Note that the grading function is expecting a quantum circuit
grade_lab3_ex1(ex1_circuit)
zz_map = ZZFeatureMap(feature_dimension=4, reps=2, entanglement='linear', insert_barriers=True)
zz_kernel = QuantumKernel(feature_map=zz_map, quantum_instance=Aer.get_backend('statevector_simulator'))
print(sample_train[0])
print(sample_train[1])
zz_circuit = zz_kernel.construct_circuit(sample_train[0], sample_train[1])
zz_circuit.decompose().decompose().draw(output='mpl')
backend = Aer.get_backend('qasm_simulator')
job = execute(zz_circuit, backend, shots=8192,
seed_simulator=1024, seed_transpiler=1024)
counts = job.result().get_counts(zz_circuit)
counts['0000']/sum(counts.values())
matrix_train = zz_kernel.evaluate(x_vec=sample_train)
matrix_test = zz_kernel.evaluate(x_vec=sample_test, y_vec=sample_train)
fig, axs = plt.subplots(1, 2, figsize=(10, 5))
axs[0].imshow(np.asmatrix(matrix_train),
interpolation='nearest', origin='upper', cmap='Blues')
axs[0].set_title("training kernel matrix")
axs[1].imshow(np.asmatrix(matrix_test),
interpolation='nearest', origin='upper', cmap='Reds')
axs[1].set_title("testing kernel matrix")
plt.show()
x = [-0.1,0.2]
y = [0.4,-0.6]
# YOUR CODE HERE
encode_map_x2 = ZZFeatureMap(feature_dimension=2, reps=4)
zz_kernel_x2 =QuantumKernel(feature_map=encode_map_x2,quantum_instance=Aer.get_backend('statevector_simulator'))
zz_circuit_x2 =zz_kernel_x2.construct_circuit(x,y)
backend =Aer.get_backend('qasm_simulator')
job = execute(zz_circuit_x2,backend,shots=8192,
seed_simulator=1024, seed_transpiler=1024)
counts_x2 = job.result().get_counts(zz_circuit_x2)
amplitude= counts_x2['00']/sum(counts_x2.values())
from qc_grader import grade_lab3_ex2
# Note that the grading function is expecting a floating point number
grade_lab3_ex2(amplitude)
zzpc_svc = SVC(kernel='precomputed')
zzpc_svc.fit(matrix_train, label_train)
zzpc_score = zzpc_svc.score(matrix_test, label_test)
print(f'Precomputed kernel classification test score: {zzpc_score}')
zzcb_svc = SVC(kernel=zz_kernel.evaluate)
zzcb_svc.fit(sample_train, label_train)
zzcb_score = zzcb_svc.score(sample_test, label_test)
print(f'Callable kernel classification test score: {zzcb_score}')
classical_kernels = ['linear', 'poly', 'rbf', 'sigmoid']
for kernel in classical_kernels:
classical_svc = SVC(kernel=kernel)
classical_svc.fit(sample_train, label_train)
classical_score = classical_svc.score(sample_test, label_test)
print('%s kernel classification test score: %0.2f' % (kernel, classical_score))
|
https://github.com/jatin-47/QGSS-2021
|
jatin-47
|
from qiskit.circuit.library import RealAmplitudes
ansatz = RealAmplitudes(num_qubits=2, reps=1, entanglement='linear')
ansatz.draw('mpl', style='iqx')
from qiskit.opflow import Z, I
hamiltonian = Z ^ Z
from qiskit.opflow import StateFn
expectation = StateFn(hamiltonian, is_measurement=True) @ StateFn(ansatz)
import numpy as np
point = np.random.random(ansatz.num_parameters)
index = 2
from qiskit import Aer
from qiskit.utils import QuantumInstance
backend = Aer.get_backend('qasm_simulator')
q_instance = QuantumInstance(backend, shots = 8192, seed_simulator = 2718, seed_transpiler = 2718)
from qiskit.circuit import QuantumCircuit
from qiskit.opflow import Z, X
H = X ^ X
U = QuantumCircuit(2)
U.h(0)
U.cx(0, 1)
# YOUR CODE HERE
expectation = StateFn(hamiltonian, is_measurement=True) @ StateFn(U)
matmult_result =expectation.eval()
from qc_grader import grade_lab4_ex1
# Note that the grading function is expecting a complex number
grade_lab4_ex1(matmult_result)
from qiskit.opflow import CircuitSampler, PauliExpectation
sampler = CircuitSampler(q_instance)
# YOUR CODE HERE
sampler = CircuitSampler(q_instance) # q_instance is the QuantumInstance from the beginning of the notebook
expectation = StateFn(hamiltonian, is_measurement=True) @ StateFn(U)
in_pauli_basis = PauliExpectation().convert(expectation)
shots_result = sampler.convert(in_pauli_basis).eval()
from qc_grader import grade_lab4_ex2
# Note that the grading function is expecting a complex number
grade_lab4_ex2(shots_result)
from qiskit.opflow import PauliExpectation, CircuitSampler
expectation = StateFn(hamiltonian, is_measurement=True) @ StateFn(ansatz)
in_pauli_basis = PauliExpectation().convert(expectation)
sampler = CircuitSampler(q_instance)
def evaluate_expectation(x):
value_dict = dict(zip(ansatz.parameters, x))
result = sampler.convert(in_pauli_basis, params=value_dict).eval()
return np.real(result)
eps = 0.2
e_i = np.identity(point.size)[:, index] # identity vector with a 1 at index ``index``, otherwise 0
plus = point + eps * e_i
minus = point - eps * e_i
finite_difference = (evaluate_expectation(plus) - evaluate_expectation(minus)) / (2 * eps)
print(finite_difference)
from qiskit.opflow import Gradient
expectation = StateFn(hamiltonian, is_measurement=True) @ StateFn(ansatz)
shifter = Gradient('fin_diff', analytic=False, epsilon=eps)
grad = shifter.convert(expectation, params=ansatz.parameters[index])
print(grad)
value_dict = dict(zip(ansatz.parameters, point))
sampler.convert(grad, value_dict).eval().real
eps = np.pi / 2
e_i = np.identity(point.size)[:, index] # identity vector with a 1 at index ``index``, otherwise 0
plus = point + eps * e_i
minus = point - eps * e_i
finite_difference = (evaluate_expectation(plus) - evaluate_expectation(minus)) / 2
print(finite_difference)
expectation = StateFn(hamiltonian, is_measurement=True) @ StateFn(ansatz)
shifter = Gradient() # parameter-shift rule is the default
grad = shifter.convert(expectation, params=ansatz.parameters[index])
sampler.convert(grad, value_dict).eval().real
expectation = StateFn(hamiltonian, is_measurement=True) @ StateFn(ansatz)
shifter = Gradient('lin_comb') # parameter-shift rule is the default
grad = shifter.convert(expectation, params=ansatz.parameters[index])
sampler.convert(grad, value_dict).eval().real
# initial_point = np.random.random(ansatz.num_parameters)
initial_point = np.array([0.43253681, 0.09507794, 0.42805949, 0.34210341])
expectation = StateFn(hamiltonian, is_measurement=True).compose(StateFn(ansatz))
gradient = Gradient().convert(expectation)
gradient_in_pauli_basis = PauliExpectation().convert(gradient)
sampler = CircuitSampler(q_instance)
def evaluate_gradient(x):
value_dict = dict(zip(ansatz.parameters, x))
result = sampler.convert(gradient_in_pauli_basis, params=value_dict).eval() # add parameters in here!
return np.real(result)
# Note: The GradientDescent class will be released with Qiskit 0.28.0 and can then be imported as:
# from qiskit.algorithms.optimizers import GradientDescent
from qc_grader.gradient_descent import GradientDescent
gd_loss = []
def gd_callback(nfevs, x, fx, stepsize):
gd_loss.append(fx)
gd = GradientDescent(maxiter=300, learning_rate=0.01, callback=gd_callback)
x_opt, fx_opt, nfevs = gd.optimize(initial_point.size, # number of parameters
evaluate_expectation, # function to minimize
gradient_function=evaluate_gradient, # function to evaluate the gradient
initial_point=initial_point) # initial point
import matplotlib
import matplotlib.pyplot as plt
matplotlib.rcParams['font.size'] = 14
plt.figure(figsize=(12, 6))
plt.plot(gd_loss, label='vanilla gradient descent')
plt.axhline(-1, ls='--', c='tab:red', label='target')
plt.ylabel('loss')
plt.xlabel('iterations')
plt.legend();
from qiskit.opflow import NaturalGradient
expectation = StateFn(hamiltonian, is_measurement=True).compose(StateFn(ansatz))
natural_gradient = NaturalGradient(regularization='ridge').convert(expectation)
natural_gradient_in_pauli_basis = PauliExpectation().convert(natural_gradient)
sampler = CircuitSampler(q_instance, caching="all")
def evaluate_natural_gradient(x):
value_dict = dict(zip(ansatz.parameters, x))
result = sampler.convert(natural_gradient, params=value_dict).eval()
return np.real(result)
print('Vanilla gradient:', evaluate_gradient(initial_point))
print('Natural gradient:', evaluate_natural_gradient(initial_point))
qng_loss = []
def qng_callback(nfevs, x, fx, stepsize):
qng_loss.append(fx)
qng = GradientDescent(maxiter=300, learning_rate=0.01, callback=qng_callback)
x_opt, fx_opt, nfevs = qng.optimize(initial_point.size,
evaluate_expectation,
gradient_function=evaluate_natural_gradient,
initial_point=initial_point)
def plot_loss():
plt.figure(figsize=(12, 6))
plt.plot(gd_loss, 'tab:blue', label='vanilla gradient descent')
plt.plot(qng_loss, 'tab:green', label='quantum natural gradient')
plt.axhline(-1, c='tab:red', ls='--', label='target')
plt.ylabel('loss')
plt.xlabel('iterations')
plt.legend()
plot_loss()
from qc_grader.spsa import SPSA
spsa_loss = []
def spsa_callback(nfev, x, fx, stepsize, accepted):
spsa_loss.append(fx)
spsa = SPSA(maxiter=300, learning_rate=0.01, perturbation=0.01, callback=spsa_callback)
x_opt, fx_opt, nfevs = spsa.optimize(initial_point.size,
evaluate_expectation,
initial_point=initial_point)
def plot_loss():
plt.figure(figsize=(12, 6))
plt.plot(gd_loss, 'tab:blue', label='vanilla gradient descent')
plt.plot(qng_loss, 'tab:green', label='quantum natural gradient')
plt.plot(spsa_loss, 'tab:blue', ls='--', label='SPSA')
plt.axhline(-1, c='tab:red', ls='--', label='target')
plt.ylabel('loss')
plt.xlabel('iterations')
plt.legend()
plot_loss()
# Note: The QNSPSA class will be released with Qiskit 0.28.0 and can then be imported as:
# from qiskit.algorithms.optimizers import QNSPSA
from qc_grader.qnspsa import QNSPSA
qnspsa_loss = []
def qnspsa_callback(nfev, x, fx, stepsize, accepted):
qnspsa_loss.append(fx)
fidelity = QNSPSA.get_fidelity(ansatz, q_instance, expectation=PauliExpectation())
qnspsa = QNSPSA(fidelity, maxiter=300, learning_rate=0.01, perturbation=0.01, callback=qnspsa_callback)
x_opt, fx_opt, nfevs = qnspsa.optimize(initial_point.size,
evaluate_expectation,
initial_point=initial_point)
def plot_loss():
plt.figure(figsize=(12, 6))
plt.plot(gd_loss, 'tab:blue', label='vanilla gradient descent')
plt.plot(qng_loss, 'tab:green', label='quantum natural gradient')
plt.plot(spsa_loss, 'tab:blue', ls='--', label='SPSA')
plt.plot(qnspsa_loss, 'tab:green', ls='--', label='QN-SPSA')
plt.axhline(-1, c='tab:red', ls='--', label='target')
plt.ylabel('loss')
plt.xlabel('iterations')
plt.legend()
plot_loss()
autospsa_loss = []
def autospsa_callback(nfev, x, fx, stepsize, accepted):
autospsa_loss.append(fx)
autospsa = SPSA(maxiter=300, learning_rate=None, perturbation=None, callback=autospsa_callback)
x_opt, fx_opt, nfevs = autospsa.optimize(initial_point.size,
evaluate_expectation,
initial_point=initial_point)
def plot_loss():
plt.figure(figsize=(12, 6))
plt.plot(gd_loss, 'tab:blue', label='vanilla gradient descent')
plt.plot(qng_loss, 'tab:green', label='quantum natural gradient')
plt.plot(spsa_loss, 'tab:blue', ls='--', label='SPSA')
plt.plot(qnspsa_loss, 'tab:green', ls='--', label='QN-SPSA')
plt.plot(autospsa_loss, 'tab:red', label='Powerlaw SPSA')
plt.axhline(-1, c='tab:red', ls='--', label='target')
plt.ylabel('loss')
plt.xlabel('iterations')
plt.legend()
plot_loss()
H_tfi = -(Z^Z^I)-(I^Z^Z)-(X^I^I)-(I^X^I)-(I^I^X)
from qc_grader import grade_lab4_ex3
# Note that the grading function is expecting a Hamiltonian
grade_lab4_ex3(H_tfi)
from qiskit.circuit.library import EfficientSU2
efficient_su2 = EfficientSU2(3, entanglement="linear", reps=2)
tfi_sampler = CircuitSampler(q_instance)
def evaluate_tfi(parameters):
exp = StateFn(H_tfi, is_measurement=True).compose(StateFn(efficient_su2))
value_dict = dict(zip(efficient_su2.parameters, parameters))
result = tfi_sampler.convert(PauliExpectation().convert(exp), params=value_dict).eval()
return np.real(result)
# target energy
tfi_target = -3.4939592074349326
# initial point for reproducibility
tfi_init = np.array([0.95667807, 0.06192812, 0.47615196, 0.83809827, 0.89022282,
0.27140831, 0.9540853 , 0.41374024, 0.92595507, 0.76150126,
0.8701938 , 0.05096063, 0.25476016, 0.71807858, 0.85661325,
0.48311132, 0.43623886, 0.6371297 ])
tfi_result = SPSA(maxiter=300, learning_rate=None, perturbation=None)
tfi_result = tfi_result.optimize(tfi_init.size, evaluate_tfi, initial_point=tfi_init)
tfi_minimum = tfi_result[1]
print("Error:", np.abs(tfi_result[1] - tfi_target))
from qc_grader import grade_lab4_ex4
# Note that the grading function is expecting a floating point number
grade_lab4_ex4(tfi_minimum)
from qiskit_machine_learning.datasets import ad_hoc_data
training_features, training_labels, test_features, test_labels = ad_hoc_data(
training_size=20, test_size=10, n=2, one_hot=False, gap=0.5
)
# the training labels are in {0, 1} but we'll use {-1, 1} as class labels!
training_labels = 2 * training_labels - 1
test_labels = 2 * test_labels - 1
def plot_sampled_data():
from matplotlib.patches import Patch
from matplotlib.lines import Line2D
import matplotlib.pyplot as plt
plt.figure(figsize=(12,6))
for feature, label in zip(training_features, training_labels):
marker = 'o'
color = 'tab:green' if label == -1 else 'tab:blue'
plt.scatter(feature[0], feature[1], marker=marker, s=100, color=color)
for feature, label in zip(test_features, test_labels):
marker = 's'
plt.scatter(feature[0], feature[1], marker=marker, s=100, facecolor='none', edgecolor='k')
legend_elements = [
Line2D([0], [0], marker='o', c='w', mfc='tab:green', label='A', ms=15),
Line2D([0], [0], marker='o', c='w', mfc='tab:blue', label='B', ms=15),
Line2D([0], [0], marker='s', c='w', mfc='none', mec='k', label='test features', ms=10)
]
plt.legend(handles=legend_elements, bbox_to_anchor=(1, 0.6))
plt.title('Training & test data')
plt.xlabel('$x$')
plt.ylabel('$y$')
plot_sampled_data()
from qiskit.circuit.library import ZZFeatureMap
dim = 2
feature_map = ZZFeatureMap(dim, reps=1) # let's keep it simple!
feature_map.draw('mpl', style='iqx')
ansatz = RealAmplitudes(num_qubits=dim, entanglement='linear', reps=1) # also simple here!
ansatz.draw('mpl', style='iqx')
circuit = feature_map.compose(ansatz)
circuit.draw('mpl', style='iqx')
hamiltonian = Z ^ Z # global Z operators
gd_qnn_loss = []
def gd_qnn_callback(*args):
gd_qnn_loss.append(args[2])
gd = GradientDescent(maxiter=100, learning_rate=0.01, callback=gd_qnn_callback)
from qiskit_machine_learning.neural_networks import OpflowQNN
qnn_expectation = StateFn(hamiltonian, is_measurement=True) @ StateFn(circuit)
qnn = OpflowQNN(qnn_expectation,
input_params=list(feature_map.parameters),
weight_params=list(ansatz.parameters),
exp_val=PauliExpectation(),
gradient=Gradient(), # <-- Parameter-Shift gradients
quantum_instance=q_instance)
from qiskit_machine_learning.algorithms import NeuralNetworkClassifier
#initial_point = np.array([0.2, 0.1, 0.3, 0.4])
classifier = NeuralNetworkClassifier(qnn, optimizer=gd)
classifier.fit(training_features, training_labels);
predicted = classifier.predict(test_features)
def plot_predicted():
from matplotlib.lines import Line2D
plt.figure(figsize=(12, 6))
for feature, label in zip(training_features, training_labels):
marker = 'o'
color = 'tab:green' if label == -1 else 'tab:blue'
plt.scatter(feature[0], feature[1], marker=marker, s=100, color=color)
for feature, label, pred in zip(test_features, test_labels, predicted):
marker = 's'
color = 'tab:green' if pred == -1 else 'tab:blue'
if label != pred: # mark wrongly classified
plt.scatter(feature[0], feature[1], marker='o', s=500, linewidths=2.5,
facecolor='none', edgecolor='tab:red')
plt.scatter(feature[0], feature[1], marker=marker, s=100, color=color)
legend_elements = [
Line2D([0], [0], marker='o', c='w', mfc='tab:green', label='A', ms=15),
Line2D([0], [0], marker='o', c='w', mfc='tab:blue', label='B', ms=15),
Line2D([0], [0], marker='s', c='w', mfc='tab:green', label='predict A', ms=10),
Line2D([0], [0], marker='s', c='w', mfc='tab:blue', label='predict B', ms=10),
Line2D([0], [0], marker='o', c='w', mfc='none', mec='tab:red', label='wrongly classified', mew=2, ms=15)
]
plt.legend(handles=legend_elements, bbox_to_anchor=(1, 0.7))
plt.title('Training & test data')
plt.xlabel('$x$')
plt.ylabel('$y$')
plot_predicted()
qng_qnn_loss = []
def qng_qnn_callback(*args):
qng_qnn_loss.append(args[2])
gd = GradientDescent(maxiter=100, learning_rate=0.01, callback=qng_qnn_callback)
qnn = OpflowQNN(qnn_expectation,
input_params=list(feature_map.parameters),
weight_params=list(ansatz.parameters),
gradient=NaturalGradient(regularization='ridge'), # <-- using Natural Gradients!
quantum_instance=q_instance)
classifier = NeuralNetworkClassifier(qnn, optimizer=gd)#, initial_point=initial_point)
classifier.fit(training_features, training_labels);
def plot_losses():
plt.figure(figsize=(12, 6))
plt.plot(gd_qnn_loss, 'tab:blue', marker='o', label='vanilla gradients')
plt.plot(qng_qnn_loss, 'tab:green', marker='o', label='natural gradients')
plt.xlabel('iterations')
plt.ylabel('loss')
plt.legend(loc='best')
plot_losses()
from qiskit.opflow import I
def sample_gradients(num_qubits, reps, local=False):
"""Sample the gradient of our model for ``num_qubits`` qubits and ``reps`` repetitions.
We sample 100 times for random parameters and compute the gradient of the first RY rotation gate.
"""
index = num_qubits - 1
# you can also exchange this for a local operator and observe the same!
if local:
operator = Z ^ Z ^ (I ^ (num_qubits - 2))
else:
operator = Z ^ num_qubits
# real amplitudes ansatz
ansatz = RealAmplitudes(num_qubits, entanglement='linear', reps=reps)
# construct Gradient we want to evaluate for different values
expectation = StateFn(operator, is_measurement=True).compose(StateFn(ansatz))
grad = Gradient().convert(expectation, params=ansatz.parameters[index])
# evaluate for 100 different, random parameter values
num_points = 100
grads = []
for _ in range(num_points):
# points are uniformly chosen from [0, pi]
point = np.random.uniform(0, np.pi, ansatz.num_parameters)
value_dict = dict(zip(ansatz.parameters, point))
grads.append(sampler.convert(grad, value_dict).eval())
return grads
num_qubits = list(range(2, 13))
reps = num_qubits # number of layers = numbers of qubits
gradients = [sample_gradients(n, r) for n, r in zip(num_qubits, reps)]
fit = np.polyfit(num_qubits, np.log(np.var(gradients, axis=1)), deg=1)
x = np.linspace(num_qubits[0], num_qubits[-1], 200)
plt.figure(figsize=(12, 6))
plt.semilogy(num_qubits, np.var(gradients, axis=1), 'o-', label='measured variance')
plt.semilogy(x, np.exp(fit[0] * x + fit[1]), 'r--', label=f'exponential fit w/ {fit[0]:.2f}')
plt.xlabel('number of qubits')
plt.ylabel(r'$\mathrm{Var}[\partial_{\theta 1} \langle E(\theta) \rangle]$')
plt.legend(loc='best');
from qiskit.opflow import NaturalGradient
def sample_natural_gradients(num_qubits, reps):
index = num_qubits - 1
operator = Z ^ num_qubits
ansatz = RealAmplitudes(num_qubits, entanglement='linear', reps=reps)
expectation = StateFn(operator, is_measurement=True).compose(StateFn(ansatz))
grad = # TODO: ``grad`` should be the natural gradient for the parameter at index ``index``.
# Hint: Check the ``sample_gradients`` function, this one is almost the same.
grad = NaturalGradient().convert(expectation, params=ansatz.parameters[index])
num_points = 100
grads = []
for _ in range(num_points):
point = np.random.uniform(0, np.pi, ansatz.num_parameters)
value_dict = dict(zip(ansatz.parameters, point))
grads.append(sampler.convert(grad, value_dict).eval())
return grads
num_qubits = list(range(2, 13))
reps = num_qubits # number of layers = numbers of qubits
natural_gradients = [sample_natural_gradients(n, r) for n, r in zip(num_qubits, reps)]
fit = np.polyfit(num_qubits, np.log(np.var(natural_gradients, axis=1)), deg=1)
x = np.linspace(num_qubits[0], num_qubits[-1], 200)
plt.figure(figsize=(12, 6))
plt.semilogy(num_qubits, np.var(gradients, axis=1), 'o-', label='vanilla gradients')
plt.semilogy(num_qubits, np.var(natural_gradients, axis=1), 's-', label='natural gradients')
plt.semilogy(x, np.exp(fit[0] * x + fit[1]), 'r--', label=f'exponential fit w/ {float(fit[0]):.2f}')
plt.xlabel('number of qubits')
plt.ylabel(r'$\mathrm{Var}[\partial_{\theta 1} \langle E(\theta) \rangle]$')
plt.legend(loc='best');
num_qubits = list(range(2, 13))
fixed_depth_global_gradients = [sample_gradients(n, 1) for n in num_qubits]
fit = np.polyfit(num_qubits, np.log(np.var(fixed_depth_global_gradients, axis=1)), deg=1)
x = np.linspace(num_qubits[0], num_qubits[-1], 200)
plt.figure(figsize=(12, 6))
plt.semilogy(num_qubits, np.var(gradients, axis=1), 'o-', label='global cost, linear depth')
plt.semilogy(num_qubits, np.var(fixed_depth_global_gradients, axis=1), 'o-', label='global cost, constant depth')
plt.semilogy(x, np.exp(fit[0] * x + fit[1]), 'r--', label=f'exponential fit w/ {fit[0]:.2f}')
plt.xlabel('number of qubits')
plt.ylabel(r'$\mathrm{Var}[\partial_{\theta 1} \langle E(\theta) \rangle]$')
plt.legend(loc='best');
num_qubits = list(range(2, 13))
linear_depth_local_gradients = [sample_gradients(n, n, local=True) for n in num_qubits]
fit = np.polyfit(num_qubits, np.log(np.var(linear_depth_local_gradients, axis=1)), deg=1)
x = np.linspace(num_qubits[0], num_qubits[-1], 200)
plt.figure(figsize=(12, 6))
plt.semilogy(num_qubits, np.var(gradients, axis=1), 'o-', label='global cost, linear depth')
plt.semilogy(num_qubits, np.var(fixed_depth_global_gradients, axis=1), 'o-', label='global cost, constant depth')
plt.semilogy(num_qubits, np.var(linear_depth_local_gradients, axis=1), 'o-', label='local cost, linear depth')
plt.semilogy(x, np.exp(fit[0] * x + fit[1]), 'r--', label=f'exponential fit w/ {fit[0]:.2f}')
plt.xlabel('number of qubits')
plt.ylabel(r'$\mathrm{Var}[\partial_{\theta 1} \langle E(\theta) \rangle]$')
plt.legend(loc='best');
num_qubits = list(range(2, 13))
fixed_depth_local_gradients = [sample_gradients(n, 1, local=True) for n in num_qubits]
fit = np.polyfit(num_qubits, np.log(np.var(fixed_depth_local_gradients, axis=1)), deg=1)
x = np.linspace(num_qubits[0], num_qubits[-1], 200)
plt.figure(figsize=(12, 6))
plt.semilogy(num_qubits, np.var(gradients, axis=1), 'o-', label='global cost, linear depth')
plt.semilogy(num_qubits, np.var(fixed_depth_global_gradients, axis=1), 'o-', label='global cost, constant depth')
plt.semilogy(num_qubits, np.var(linear_depth_local_gradients, axis=1), 'o-', label='local cost, linear depth')
plt.semilogy(num_qubits, np.var(fixed_depth_local_gradients, axis=1), 'o-', label='local cost, constant depth')
plt.semilogy(x, np.exp(fit[0] * x + fit[1]), 'r--', label=f'exponential fit w/ {fit[0]:.2f}')
plt.xlabel('number of qubits')
plt.ylabel(r'$\mathrm{Var}[\partial_{\theta 1} \langle E(\theta) \rangle]$')
plt.legend(loc='best');
num_qubits = 6
operator = Z ^ Z ^ (I ^ (num_qubits - 4))
def minimize(circuit, optimizer):
initial_point = np.random.random(circuit.num_parameters)
exp = StateFn(operator, is_measurement=True) @ StateFn(circuit)
grad = Gradient().convert(exp)
# pauli basis
exp = PauliExpectation().convert(exp)
grad = PauliExpectation().convert(grad)
sampler = CircuitSampler(q_instance, caching="all")
def loss(x):
values_dict = dict(zip(circuit.parameters, x))
return np.real(sampler.convert(exp, values_dict).eval())
def gradient(x):
values_dict = dict(zip(circuit.parameters, x))
return np.real(sampler.convert(grad, values_dict).eval())
return optimizer.optimize(circuit.num_parameters, loss, gradient, initial_point=initial_point)
circuit = RealAmplitudes(4, reps=1, entanglement='linear')
circuit.draw('mpl', style='iqx')
circuit.reps = 5
circuit.draw('mpl', style='iqx')
def layerwise_training(ansatz, max_num_layers, optimizer):
optimal_parameters = []
fopt = None
for reps in range(1, max_num_layers):
ansatz.reps = reps
# bind already optimized parameters
values_dict = dict(zip(ansatz.parameters, optimal_parameters))
partially_bound = ansatz.bind_parameters(values_dict)
xopt, fopt, _ = minimize(partially_bound, optimizer)
print('Circuit depth:', ansatz.depth(), 'best value:', fopt)
optimal_parameters += list(xopt)
return fopt, optimal_parameters
ansatz = RealAmplitudes(4, entanglement='linear')
optimizer = GradientDescent(maxiter=50)
np.random.seed(12)
fopt, optimal_parameters = layerwise_training(ansatz, 4, optimizer)
|
https://github.com/jatin-47/QGSS-2021
|
jatin-47
|
# General tools
import numpy as np
import matplotlib.pyplot as plt
# Qiskit Circuit Functions
from qiskit import execute,QuantumCircuit, QuantumRegister, ClassicalRegister, Aer, transpile
import qiskit.quantum_info as qi
# Tomography functions
from qiskit.ignis.verification.tomography import process_tomography_circuits, ProcessTomographyFitter
from qiskit.ignis.mitigation.measurement import complete_meas_cal, CompleteMeasFitter
import warnings
warnings.filterwarnings('ignore')
target = QuantumCircuit(2)
#target = # YOUR CODE HERE
target.h(0)
target.h(1)
target.rx(np.pi/2,0)
target.rx(np.pi/2,1)
target.cx(0,1)
target.p(np.pi,1)
target.cx(0,1)
target_unitary = qi.Operator(target)
target.draw('mpl')
from qc_grader import grade_lab5_ex1
# Note that the grading function is expecting a quantum circuit with no measurements
grade_lab5_ex1(target)
simulator = Aer.get_backend('qasm_simulator')
qpt_circs = process_tomography_circuits(target,measured_qubits=[0,1])# YOUR CODE HERE
qpt_job = execute(qpt_circs,simulator,seed_simulator=3145,seed_transpiler=3145,shots=8192)
qpt_result = qpt_job.result()
# YOUR CODE HERE
qpt_tomo= ProcessTomographyFitter(qpt_result,qpt_circs)
Choi_qpt= qpt_tomo.fit(method='lstsq')
fidelity = qi.average_gate_fidelity(Choi_qpt,target_unitary)
from qc_grader import grade_lab5_ex2
# Note that the grading function is expecting a floating point number
grade_lab5_ex2(fidelity)
# T1 and T2 values for qubits 0-3
T1s = [15000, 19000, 22000, 14000]
T2s = [30000, 25000, 18000, 28000]
# Instruction times (in nanoseconds)
time_u1 = 0 # virtual gate
time_u2 = 50 # (single X90 pulse)
time_u3 = 100 # (two X90 pulses)
time_cx = 300
time_reset = 1000 # 1 microsecond
time_measure = 1000 # 1 microsecond
from qiskit.providers.aer.noise import thermal_relaxation_error
from qiskit.providers.aer.noise import NoiseModel
# QuantumError objects
errors_reset = [thermal_relaxation_error(t1, t2, time_reset)
for t1, t2 in zip(T1s, T2s)]
errors_measure = [thermal_relaxation_error(t1, t2, time_measure)
for t1, t2 in zip(T1s, T2s)]
errors_u1 = [thermal_relaxation_error(t1, t2, time_u1)
for t1, t2 in zip(T1s, T2s)]
errors_u2 = [thermal_relaxation_error(t1, t2, time_u2)
for t1, t2 in zip(T1s, T2s)]
errors_u3 = [thermal_relaxation_error(t1, t2, time_u3)
for t1, t2 in zip(T1s, T2s)]
errors_cx = [[thermal_relaxation_error(t1a, t2a, time_cx).expand(
thermal_relaxation_error(t1b, t2b, time_cx))
for t1a, t2a in zip(T1s, T2s)]
for t1b, t2b in zip(T1s, T2s)]
# Add errors to noise model
noise_thermal = NoiseModel()
for j in range(4):
noise_thermal.add_quantum_error(errors_measure[j],'measure',[j])
noise_thermal.add_quantum_error(errors_reset[j],'reset',[j])
noise_thermal.add_quantum_error(errors_u3[j],'u3',[j])
noise_thermal.add_quantum_error(errors_u2[j],'u2',[j])
noise_thermal.add_quantum_error(errors_u1[j],'u1',[j])
for k in range(4):
noise_thermal.add_quantum_error(errors_cx[j][k],'cx',[j,k])
# YOUR CODE HERE
from qc_grader import grade_lab5_ex3
# Note that the grading function is expecting a NoiseModel
grade_lab5_ex3(noise_thermal)
np.random.seed(0)
noise_qpt_circs = process_tomography_circuits(target,measured_qubits=[0,1])# YOUR CODE HERE
noise_qpt_job = execute(noise_qpt_circs,simulator,seed_simulator=3145,seed_transpiler=3145,shots=8192,noise_model=noise_thermal)
noise_qpt_result = noise_qpt_job.result()
# YOUR CODE HERE
noise_qpt_tomo= ProcessTomographyFitter(noise_qpt_result,noise_qpt_circs)
noise_Choi_qpt= noise_qpt_tomo.fit(method='lstsq')
fidelity = qi.average_gate_fidelity(noise_Choi_qpt,target_unitary)
from qc_grader import grade_lab5_ex4
# Note that the grading function is expecting a floating point number
grade_lab5_ex4(fidelity)
np.random.seed(0)
# YOUR CODE HERE
#qr = QuantumRegister(2)
qubit_list = [0,1]
meas_calibs, state_labels = complete_meas_cal(qubit_list=qubit_list)
meas_calibs_job = execute(meas_calibs,simulator,seed_simulator=3145,seed_transpiler=3145,shots=8192,noise_model=noise_thermal)
cal_results = meas_calibs_job.result()
meas_fitter = CompleteMeasFitter(cal_results, state_labels, qubit_list=qubit_list)
Cal_result = meas_fitter.filter.apply(noise_qpt_result)
# YOUR CODE HERE
Cal_qpt_tomo= ProcessTomographyFitter(Cal_result,noise_qpt_circs)
Cal_Choi_qpt= Cal_qpt_tomo.fit(method='lstsq')
fidelity = qi.average_gate_fidelity(Cal_Choi_qpt,target_unitary)
from qc_grader import grade_lab5_ex5
# Note that the grading function is expecting a floating point number
grade_lab5_ex5(fidelity)
|
https://github.com/The-Singularity-Research/QISKit-Surface-Codes
|
The-Singularity-Research
|
from collections import Counter
from typing import Tuple, List
import numpy as np
from networkx import MultiGraph
from networkx import nx
from sympy.combinatorics import Permutation
import matplotlib.pyplot as plt
# from SurfaceCodes.utilites import permlist_to_tuple
class SurfaceCodeGraph(MultiGraph):
def __init__(self, sigma: Tuple[Tuple[int]], alpha: Tuple[Tuple[int]]):
super().__init__()
self.sigma = sigma # should include singletons corresponding to fixed points
self.alpha = alpha # should include singletons corresponding to fixed points
f = self.compute_phi()
self.phi = self.permlist_to_tuple(f)
self.node_info = self.build_node_info() # print dictionary for [sigma, alpha, phi]
self.code_graph = nx.MultiGraph()
# Create black nodes for each cycle in sigma along with white nodes
# representing "half edges" around the black nodes
for cycle in self.sigma:
self.code_graph.add_node(cycle, bipartite=1)
for node in cycle:
self.code_graph.add_node(node, bipartite=0)
self.code_graph.add_edge(cycle, node)
# Create black nodes for each cycle in phi along with white nodes
# representing "half edges" around the black nodes
for cycle in self.phi:
self.code_graph.add_node(cycle, bipartite=1)
for node in cycle:
self.code_graph.add_edge(cycle, node)
# Create nodes for each cycle in alpha then
# glue the nodes corresponding to a the pairs
for pair in self.alpha:
self.code_graph.add_node(pair)
self.code_graph = nx.contracted_nodes(self.code_graph, pair[0], pair[1], self_loops=True)
# Now contract pair with pair[0] to make sure edges (white nodes) are labeled
# by the pairs in alpha to keep track of the gluing from the previous step
self.code_graph = nx.contracted_nodes(self.code_graph, pair, pair[0], self_loops=True)
def permlist_to_tuple(self, perms):
"""
convert list of lists to tuple of tuples in order to have two level iterables
that are hashable for the dictionaries used later
"""
return tuple(tuple(perm) for perm in perms)
def compute_phi(self):
"""compute the list of lists full cyclic form of phi (faces of dessin [sigma, alpha, phi])"""
s = Permutation(self.sigma)
a = Permutation(self.alpha)
f = ~(a * s)
f = f.full_cyclic_form # prints permutation as a list of lists including all singletons (fixed points)
return f
def build_node_info(self):
count = -1
self.sigma_dict = dict()
for count, cycle in enumerate(self.sigma):
self.sigma_dict[cycle] = count
self.phi_dict = dict()
for count, cycle in enumerate(self.phi, start=count + 1):
self.phi_dict[cycle] = count
self.alpha_dict = dict()
for count, pair in enumerate(self.alpha, start=count + 1):
self.alpha_dict[pair] = count
return tuple([self.sigma_dict, self.alpha_dict, self.phi_dict])
def boundary_1(self, edge):
"""
compute boundary of a single edge given by a white node (cycle in alpha)
"""
# if len(self.code_graph.neighbors(edge)) < 2:
# boundary1 = []
# else:
boundary1 = Counter([x[1] for x in self.code_graph.edges(edge) if x[1] in self.sigma_dict])
odd_boundaries = [x for x in boundary1 if boundary1[x] % 2]
# [node for node in self.code_graph.neighbors(edge) if node in self.sigma_dict]
return odd_boundaries
def del_1(self, edges: List[Tuple[int]]):
"""
boundary of a list of edges, i.e. an arbitrary 1-chain over Z/2Z
"""
boundary_list = [self.boundary_1(edge) for edge in edges]
a = Counter([y for x in boundary_list for y in x])
boundary_list = [x[0] for x in a.items() if x[1] % 2 == 1]
return boundary_list
def boundary_2(self, face):
"""
compute boundary of a single face node
"""
# boundary2 = [node for node in self.code_graph.neighbors(face) if node in self.alpha_dict]
boundary2 = Counter([x[1] for x in self.code_graph.edges(face) if x[1] in self.alpha_dict])
odd_boundaries = [x for x in boundary2 if boundary2[x] % 2]
return odd_boundaries
def del_2(self, faces: List[Tuple[int]]):
"""
boundary of a list of faces, i.e. an arbitrary 2-chain over Z/2Z
"""
boundary_list = [self.boundary_2(face) for face in faces]
a = Counter([y for x in boundary_list for y in x])
boundary_list = [x[0] for x in a.items() if x[1] % 2 == 1]
return boundary_list
def coboundary_1(self, star):
"""
compute coboundary of a single star
"""
# coboundary = self.code_graph.neighbors(star)
coboundary1 = Counter([x[1] for x in self.code_graph.edges(star)])
odd_coboundaries = [x for x in coboundary1 if coboundary1[x] % 2]
return odd_coboundaries
def delta_1(self, stars: List[Tuple[int]]):
"""
coboundary of a list of stars, i.e. an arbitrary 0-cochain over Z/2Z
"""
coboundary_list = [self.coboundary_1(star) for star in stars]
a = Counter([y for x in coboundary_list for y in x])
coboundary_list = [x[0] for x in a.items() if x[1] % 2 == 1]
return coboundary_list
def coboundary_2(self, edge):
"""
compute coboundary of a single edge given by a white node (cycle in alpha)
"""
# coboundary2 = [node for node in self.code_graph.neighbors(edge) if node in self.phi_dict]
coboundary2 = Counter([x[1] for x in self.code_graph.edges(edge) if x[1] in self.phi_dict])
odd_coboundaries = [x for x in coboundary2 if coboundary2[x] % 2]
return odd_coboundaries
def delta_2(self, edges: List[Tuple[int]]):
"""
coboundary of a list of edges, i.e. an arbitrary 1-cochain over Z/2Z
given by a list of cycles in alpha
"""
coboundary_list = [self.coboundary_2(edge) for edge in edges]
a = Counter([y for x in coboundary_list for y in x])
coboundary_list = [x[0] for x in a.items() if x[1] % 2 == 1]
return coboundary_list
def vertex_basis(self):
self.v_basis_dict = dict()
self.v_dict = dict()
A = np.eye(len(self.sigma), dtype=np.uint8)
for count, cycle in enumerate(self.sigma):
self.v_dict[cycle] = count
self.v_basis_dict[cycle] = A[count, :].T
return (self.v_basis_dict)
def edge_basis(self):
self.e_basis_dict = dict()
self.e_dict = dict()
B = np.eye(len(self.alpha), dtype=np.uint8)
for count, cycle in enumerate(self.alpha):
self.e_dict[cycle] = count
self.e_basis_dict[cycle] = B[count, :].T
return (self.e_basis_dict)
def face_basis(self):
self.f_basis_dict = dict()
self.f_dict = dict()
C = np.eye(len(self.phi), dtype=np.uint8)
for count, cycle in enumerate(self.phi):
self.f_dict[cycle] = count
self.f_basis_dict[cycle] = C[count, :].T
return (self.f_basis_dict)
def d_2(self):
self.D2 = np.zeros(len(self.e_dict), dtype=np.uint8)
for cycle in self.phi:
bd = self.boundary_2(cycle)
if bd != []:
image = sum([self.e_basis_dict[edge] for edge in bd])
else:
image = np.zeros(len(self.e_dict))
self.D2 = np.vstack((self.D2, image))
self.D2 = np.array(self.D2[1:, :]).T
return self.D2, self.D2.shape
def d_1(self):
self.D1 = np.zeros(len(self.v_dict), dtype=np.uint8)
for cycle in self.alpha:
bd = self.boundary_1(cycle)
if bd != []:
image = sum([self.v_basis_dict[vertex] for vertex in bd])
else:
bd = np.zeros(len(self.e_dict))
self.D1 = np.vstack((self.D1, image))
self.D1 = np.array(self.D1[1:, :]).T
return self.D1, self.D1.shape
def euler_characteristic(self):
"""
Compute the Euler characteristic of the surface in which the graph is embedded
"""
chi = len(self.phi) - len(self.alpha) + len(self.sigma)
return (chi)
def genus(self):
"""
Compute the genus of the surface in which the graph is embedded
"""
g = int(-(len(self.phi) - len(self.alpha) + len(self.sigma) - 2) / 2)
return (g)
def draw(self, node_type='', layout=''):
"""
Draw graph with vertices, edges, and faces labeled by colored nodes and their integer indices
corresponding to the qubit indices for the surface code
"""
if node_type not in ['cycles', 'dict']:
raise ValueError('node_type can be "cycles" or "dict"')
elif layout == 'spring':
pos = nx.spring_layout(self.code_graph)
elif layout == 'spectral':
pos = nx.spectral_layout(self.code_graph)
elif layout == 'planar':
pos = nx.planar_layout(self.code_graph)
elif layout == 'shell':
pos = nx.shell_layout(self.code_graph)
elif layout == 'circular':
pos = nx.circular_layout(self.code_graph)
elif layout == 'spiral':
pos = nx.spiral_layout(self.code_graph)
elif layout == 'random':
pos = nx.random_layout(self.code_graph)
else:
raise ValueError(
"no layout defined: try one of these: " +
"['spring','spectral','planar','shell','circular','spiral','random']")
# white nodes
nx.draw_networkx_nodes(self.code_graph, pos,
nodelist=list(self.alpha),
node_color='c',
node_size=500,
alpha=0.3)
# vertex nodes
nx.draw_networkx_nodes(self.code_graph, pos,
nodelist=list(self.sigma),
node_color='b',
node_size=500,
alpha=0.6)
# face nodes
nx.draw_networkx_nodes(self.code_graph, pos,
nodelist=list(self.phi),
node_color='r',
node_size=500,
alpha=0.6)
# edges
nx.draw_networkx_edges(self.code_graph, pos, width=1.0, alpha=0.5)
labels = {}
if node_type == 'cycles':
'''
label nodes the cycles of sigma, alpha, and phi
'''
for node in self.alpha_dict:
# stuff = self.alpha_dict[node]
labels[node] = f'$e$({node})'
for node in self.sigma_dict:
# something = self.sigma_dict[node]
labels[node] = f'$v$({node})'
for node in self.phi_dict:
# something2 = self.phi_dict[node]
labels[node] = f'$f$({node})'
nx.draw_networkx_labels(self.code_graph, pos, labels, font_size=12)
if node_type == 'dict':
'''
label nodes with v, e, f and indices given by node_dict corresponding to
qubit indices of surface code
'''
for node in self.alpha_dict:
# stuff = self.alpha_dict[node]
labels[node] = f'$e$({self.alpha_dict[node]})'
for node in self.sigma_dict:
# something = self.sigma_dict[node]
labels[node] = f'$v$({self.sigma_dict[node]})'
for node in self.phi_dict:
# something2 = self.phi_dict[node]
labels[node] = f'$f$({self.phi_dict[node]})'
nx.draw_networkx_labels(self.code_graph, pos, labels, font_size=12)
# plt.axis('off')
# plt.savefig("labels_and_colors.png") # save as png
plt.show() # display
sigma = ((0,1,2), (3,4,5), (6,7,8,9))
alpha = ((0,3),(1,4),(2,6),(5,7),(8,9))
SCG = SurfaceCodeGraph(sigma, alpha)
SCG.draw('dict', layout = 'spring')
SCG.draw('cycles', layout = 'spring')
SCG.node_info
SCG.genus()
SCG.face_basis()
SCG.vertex_basis()
SCG.edge_basis()
SCG.del_1([(0,3)])
SCG.boundary_1((0,3))
SCG.del_1([(1,4)])
SCG.boundary_1((1,4))
SCG.del_1([(2,6)])
SCG.boundary_1((2,6))
SCG.del_1([(5,7)])
SCG.boundary_1((5,7))
SCG.del_1([(8,9)])
SCG.boundary_1((8,9))
SCG.d_1()
SCG.d_2()
SCG.D1
SCG.D2
def rowSwap(A, i, j):
temp = np.copy(A[i, :])
A[i, :] = A[j, :]
A[j, :] = temp
def colSwap(A, i, j):
temp = np.copy(A[:, i])
A[:, i] = A[:, j]
A[:, j] = temp
def scaleCol(A, i, c):
A[:, i] *= int(c) * np.ones(A.shape[0], dtype=np.int64)
def scaleRow(A, i, c):
A[i, :] = np.array(A[i, :], dtype=np.float64) * c * np.ones(A.shape[1], dtype=np.float64)
def colCombine(A, addTo, scaleCol, scaleAmt):
A[:, addTo] += scaleAmt * A[:, scaleCol]
def rowCombine(A, addTo, scaleRow, scaleAmt):
A[addTo, :] += scaleAmt * A[scaleRow, :]
def simultaneousReduce(A, B):
if A.shape[1] != B.shape[0]:
raise Exception("Matrices have the wrong shape.")
numRows, numCols = A.shape
i, j = 0, 0
while True:
if i >= numRows or j >= numCols:
break
if A[i, j] == 0:
nonzeroCol = j
while nonzeroCol < numCols and A[i, nonzeroCol] == 0:
nonzeroCol += 1
if nonzeroCol == numCols:
i += 1
continue
colSwap(A, j, nonzeroCol)
rowSwap(B, j, nonzeroCol)
pivot = A[i, j]
scaleCol(A, j, 1.0 / pivot)
scaleRow(B, j, 1.0 / pivot)
for otherCol in range(0, numCols):
if otherCol == j:
continue
if A[i, otherCol] != 0:
scaleAmt = -A[i, otherCol]
colCombine(A, otherCol, j, scaleAmt)
rowCombine(B, j, otherCol, -scaleAmt)
i += 1;
j += 1
return A%2, B%2
def finishRowReducing(B):
numRows, numCols = B.shape
i, j = 0, 0
while True:
if i >= numRows or j >= numCols:
break
if B[i, j] == 0:
nonzeroRow = i
while nonzeroRow < numRows and B[nonzeroRow, j] == 0:
nonzeroRow += 1
if nonzeroRow == numRows:
j += 1
continue
rowSwap(B, i, nonzeroRow)
pivot = B[i, j]
scaleRow(B, i, 1.0 / pivot)
for otherRow in range(0, numRows):
if otherRow == i:
continue
if B[otherRow, j] != 0:
scaleAmt = -B[otherRow, j]
rowCombine(B, otherRow, i, scaleAmt)
i += 1;
j += 1
return B%2
def numPivotCols(A):
z = np.zeros(A.shape[0])
return [np.all(A[:, j] == z) for j in range(A.shape[1])].count(False)
def numPivotRows(A):
z = np.zeros(A.shape[1])
return [np.all(A[i, :] == z) for i in range(A.shape[0])].count(False)
def bettiNumber(d_k, d_kplus1):
A, B = np.copy(d_k), np.copy(d_kplus1)
simultaneousReduce(A, B)
finishRowReducing(B)
dimKChains = A.shape[1]
print("dim 1-chains:",dimKChains)
kernelDim = dimKChains - numPivotCols(A)
print("dim ker d_1:",kernelDim)
imageDim = numPivotRows(B)
print("dim im d_2:",imageDim)
return "dim homology:",kernelDim - imageDim
simultaneousReduce(SCG.D1.astype('float64'), SCG.D2.astype('float64'))
finishRowReducing(SCG.D2.astype('float64'))
numPivotCols(SCG.D2.astype('float64'))
numPivotRows(SCG.D2.astype('float64'))
bettiNumber(SCG.D1.astype('float64'), SCG.D2.astype('float64'))
|
https://github.com/The-Singularity-Research/QISKit-Surface-Codes
|
The-Singularity-Research
|
from collections import Counter
from typing import Tuple, List
from networkx import MultiGraph
from networkx import nx
from networkx.algorithms import bipartite
from sympy.combinatorics import Permutation
import matplotlib.pyplot as plt
# from SurfaceCodes.utilites import permlist_to_tuple
class SurfaceCodeGraph(MultiGraph):
def __init__(self, sigma: Tuple[Tuple[int]], alpha: Tuple[Tuple[int]]):
super().__init__()
self.sigma = sigma # should include singletons corresponding to fixed points
self.alpha = alpha # should include singletons corresponding to fixed points
f = self.compute_phi()
self.phi = self.permlist_to_tuple(f)
self.build_node_info() # print dictionary for [sigma, alpha, phi]
self.node_dict = self.sigma_dict, self.alpha_dict, self.phi_dict
self.node_info = ["sigma:", self.sigma_dict,
"alpha:", self.alpha_dict,
"phi:", self.phi_dict]
self.code_graph = nx.MultiGraph()
# Create black nodes for each cycle in sigma along with white nodes
# representing "half edges" around the black nodes
for cycle in self.sigma:
self.code_graph.add_node(cycle, bipartite=1)
for node in cycle:
self.code_graph.add_node(node, bipartite=0)
self.code_graph.add_edge(cycle, node)
# Create black nodes for each cycle in phi along with white nodes
# representing "half edges" around the black nodes
for cycle in self.phi:
self.code_graph.add_node(cycle, bipartite=1)
for node in cycle:
self.code_graph.add_edge(cycle, node)
# Create nodes for each cycle in alpha then
# glue the nodes corresponding to a the pairs
for pair in self.alpha:
self.code_graph.add_node(pair)
self.code_graph = nx.contracted_nodes(self.code_graph, pair[0], pair[1], self_loops=True)
# Now contract pair with pair[0] to make sure edges (white nodes) are labeled
# by the pairs in alpha to keep track of the gluing from the previous step
self.code_graph = nx.contracted_nodes(self.code_graph, pair, pair[0], self_loops=True)
# Define the white and black nodes. White correspond to edges labeled by
# cycles in alpha. Black correspond to nodes labeled by cycles in sigma
# (vertices) and phi (faces)
self.black_nodes, self.white_nodes = bipartite.sets(self.code_graph)
def permlist_to_tuple(self, perms):
"""
convert list of lists to tuple of tuples in order to have two level iterables
that are hashable for the dictionaries used later
"""
return tuple(tuple(perm) for perm in perms)
def compute_phi(self):
"""compute the list of lists full cyclic form of phi (faces of dessin [sigma, alpha, phi])"""
s = Permutation(self.sigma)
a = Permutation(self.alpha)
f = ~(a * s)
f = f.full_cyclic_form # prints permutation as a list of lists including all singletons (fixed points)
return f
def build_node_info(self):
count = -1
self.sigma_dict = dict()
for count, cycle in enumerate(self.sigma):
self.sigma_dict[cycle] = count
self.phi_dict = dict()
for count, cycle in enumerate(self.phi, start=count + 1):
self.phi_dict[cycle] = count
self.alpha_dict = dict()
for count, pair in enumerate(self.alpha, start=count + 1):
self.alpha_dict[pair] = count
return tuple([self.sigma_dict, self.alpha_dict, self.phi_dict])
def boundary_1(self, edge):
"""
compute boundary of a single edge given by a white node (cycle in alpha)
"""
boundary1 = [node for node in self.code_graph.neighbors(edge) if node in self.sigma_dict]
return boundary1
def del_1(self, edges: List[Tuple[int]]):
"""
boundary of a list of edges, i.e. an arbitrary 1-chain over Z/2Z
"""
boundary_list = [self.boundary_1(edge) for edge in edges]
a = Counter([y for x in boundary_list for y in x])
boundary_list = [x[0] for x in a.items() if x[1] % 2 == 1]
return boundary_list
def boundary_2(self, face):
"""
compute boundary of a single face
"""
boundary = self.code_graph.neighbors(face)
return boundary
def del_2(self, faces: List[Tuple[int]]):
"""
boundary of a list of faces, i.e. an arbitrary 2-chain over Z/2Z
"""
boundary_list = [self.boundary_2(face) for face in faces]
a = Counter([y for x in boundary_list for y in x])
boundary_list = [x[0] for x in a.items() if x[1] % 2 == 1]
return boundary_list
def coboundary_1(self, star):
"""
compute coboundary of a single star
"""
coboundary = self.code_graph.neighbors(star)
return coboundary
def delta_1(self, stars: List[Tuple[int]]):
"""
coboundary of a list of stars, i.e. an arbitrary 0-cochain over Z/2Z
"""
coboundary_list = [self.coboundary_1(star) for star in stars]
a = Counter([y for x in coboundary_list for y in x])
coboundary_list = [x[0] for x in a.items() if x[1] % 2 == 1]
return coboundary_list
def coboundary_2(self, edge):
"""
compute coboundary of a single edge given by a white node (cycle in alpha)
"""
coboundary2 = [node for node in self.code_graph.neighbors(edge) if node in self.phi_dict]
return coboundary2
def delta_2(self, edges: List[Tuple[int]]):
"""
coboundary of a list of edges, i.e. an arbitrary 1-cochain over Z/2Z
given by a list of cycles in alpha
"""
coboundary_list = [self.coboundary_2(edge) for edge in edges]
a = Counter([y for x in coboundary_list for y in x])
coboundary_list = [x[0] for x in a.items() if x[1] % 2 == 1]
return coboundary_list
def euler_characteristic(self):
"""
Compute the Euler characteristic of the surface in which the graph is embedded
"""
chi = len(self.phi) - len(self.alpha) + len(self.sigma)
return (chi)
def genus(self):
"""
Compute the genus of the surface in which the graph is embedded
"""
g = int(-(len(self.phi) - len(self.alpha) + len(self.sigma) - 2) / 2)
return (g)
def draw(self, node_type='', layout = ''):
"""
Draw graph with vertices, edges, and faces labeled by colored nodes and their integer indices
corresponding to the qubit indices for the surface code
"""
if not node_type in ['cycles', 'dict']:
raise ValueError('node_type can be "cycles" or "dict"')
if layout == 'spring':
pos=nx.spring_layout(self.code_graph)
if layout == 'spectral':
pos=nx.spectral_layout(self.code_graph)
if layout == 'planar':
pos=nx.planar_layout(self.code_graph)
if layout == 'shell':
pos=nx.shell_layout(self.code_graph)
if layout == 'circular':
pos=nx.circular_layout(self.code_graph)
if layout == 'spiral':
pos=nx.spiral_layout(self.code_graph)
if layout == 'random':
pos=nx.random_layout(self.code_graph)
# white nodes
nx.draw_networkx_nodes(self.code_graph, pos,
nodelist=list(self.alpha),
node_color='c',
node_size=500,
alpha=0.3)
# vertex nodes
nx.draw_networkx_nodes(self.code_graph, pos,
nodelist=list(self.sigma),
node_color='b',
node_size=500,
alpha=0.6)
# face nodes
nx.draw_networkx_nodes(self.code_graph, pos,
nodelist=list(self.phi),
node_color='r',
node_size=500,
alpha=0.6)
# edges
nx.draw_networkx_edges(self.code_graph, pos, width=1.0, alpha=0.5)
labels={}
if node_type == 'cycles':
'''
label nodes the cycles of sigma, alpha, and phi
'''
for node in self.alpha_dict:
# stuff = self.alpha_dict[node]
labels[node]=f'$e$({node})'
for node in self.sigma_dict:
# something = self.sigma_dict[node]
labels[node]=f'$v$({node})'
for node in self.phi_dict:
# something2 = self.phi_dict[node]
labels[node]=f'$f$({node})'
nx.draw_networkx_labels(self.code_graph, pos, labels, font_size=12)
if node_type == 'dict':
'''
label nodes with v, e, f and indices given by node_dict corresponding to
qubit indices of surface code
'''
for node in self.alpha_dict:
# stuff = self.alpha_dict[node]
labels[node]=f'$e$({self.alpha_dict[node]})'
for node in self.sigma_dict:
# something = self.sigma_dict[node]
labels[node]=f'$v$({self.sigma_dict[node]})'
for node in self.phi_dict:
# something2 = self.phi_dict[node]
labels[node]=f'$f$({self.phi_dict[node]})'
nx.draw_networkx_labels(self.code_graph, pos, labels, font_size=12)
# plt.axis('off')
# plt.savefig("labels_and_colors.png") # save as png
plt.show() # display
sigma = ((0,1,2),(3,4,5),(6,7))
alpha = ((0,3),(1,6),(2,4),(5,7))
SCG = SurfaceCodeGraph(sigma, alpha)
SCG
SCG.draw('cycles', 'spring')
SCG.phi
SCG.node_info
SCG.code_graph.nodes
bipartite.sets(SCG.code_graph)
SCG.white_nodes
SCG.black_nodes
SCG.draw('dict', 'spring')
SCG.euler_characteristic()
SCG.genus()
SCG.del_2([(1,3,7)])
SCG.del_2([(0, 4), (1,3,7)])
SCG.delta_1([(0,1,2)])
SCG.delta_1([(0,1,2), (3,4,5)])
SCG.boundary_1((0,3))
SCG.boundary_1((1,6))
SCG.del_1([(0,3), (1,6)])
SCG.coboundary_2((0,3))
SCG.coboundary_2((1,6))
SCG.delta_2([(0,3), (1,6)])
from typing import Tuple
from qiskit.circuit import QuantumCircuit, QuantumRegister, ClassicalRegister
# from SurfaceCodes.surface_code_class import SurfaceCodeGraph
# from SurfaceCodes.utilites import permlist_to_tuple
class SurfaceCodeCircuit(QuantumCircuit):
def __init__(self, sigma: Tuple[Tuple[int]], alpha: Tuple[Tuple[int]]):
super().__init__()
self.sigma = sigma
self.alpha = alpha
self.scgraph = SurfaceCodeGraph(self.sigma, self.alpha)
'''
Compute the permutation corresponding to phi and create a
'surface code circuit' based on a (multi)graph 'surface_code_graph'
given by sigma, alpha, and phi
Create quantum and classical registers based on the number of nodes in G
'''
# f = self.scgraph.compute_phi()
self.phi = self.scgraph.phi
self.qr = QuantumRegister(len(self.scgraph.code_graph.nodes))
self.cr = ClassicalRegister(len(self.scgraph.code_graph.nodes))
self.circ = QuantumCircuit(self.qr, self.cr)
self.node_info = self.scgraph.node_dict
self.sigma_dict, self.alpha_dict, self.phi_dict = self.node_info
for cycle in self.sigma:
self.circ.h(self.sigma_dict[cycle])
for cycle in self.phi:
self.circ.h(self.phi_dict[cycle])
def x_measurement(self, qubit: int, cbit: int):
"""Measure 'qubit' in the X-basis, and store the result in 'cbit'
:param qubit, cbit:
:return None
"""
# circuit.measure = measure # fix a bug in qiskit.circuit.measure
self.circ.h(qubit)
self.circ.measure(qubit, cbit)
self.circ.h(qubit)
def star_syndrome_measure(self, vertex: Tuple[int]):
"""
Applies CX gates to surrounding qubits of a star then measures star qubit in X-basis
:param vertex:
:return: self.circ, self.scgraph, self.node_info
"""
for node in self.scgraph.code_graph.neighbors(vertex):
self.circ.cx(self.sigma_dict[vertex], self.alpha_dict[node])
self.circ.barrier()
self.x_measurement(self.sigma_dict[vertex], self.sigma_dict[vertex])
self.circ.barrier()
return self.circ, self.scgraph, self.node_info
def face_syndrome_measure(self, vertex: Tuple[int]):
"""
Applies CZ gates to surrounding qubits of a face then measures face qubit in X-basis
:param vertex:
:return:
"""
for node in self.scgraph.code_graph.neighbors(vertex):
self.circ.cz(self.phi_dict[vertex], self.alpha_dict[node])
self.circ.barrier()
self.x_measurement(self.phi_dict[vertex], self.phi_dict[vertex])
self.circ.barrier()
return self.circ, self.scgraph, self.node_info
def product_Z(self, faces):
"""
Pauli product Z operator for arbitrary 2-chain boundary
"""
boundary_nodes = self.scgraph.del_2(faces)
for node in boundary_nodes:
self.circ.z(self.alpha_dict[node])
def product_X(self, stars):
"""
Pauli product X operator for arbitrary 0-cochain coboundary
"""
coboundary_nodes = self.scgraph.delta_1(stars)
for node in coboundary_nodes:
self.circ.x(self.alpha_dict[node])
def draw_graph(self, node_type='', layout = ''):
if layout == 'spring':
pos=nx.spring_layout(self.scgraph.code_graph)
if layout == 'spectral':
pos=nx.spectral_layout(self.scgraph.code_graph)
if layout == 'planar':
pos=nx.planar_layout(self.scgraph.code_graph)
if layout == 'shell':
pos=nx.shell_layout(self.scgraph.code_graph)
if layout == 'circular':
pos=nx.circular_layout(self.scgraph.code_graph)
if layout == 'spiral':
pos=nx.spiral_layout(self.scgraph.code_graph)
if layout == 'random':
pos=nx.random_layout(self.scgraph.code_graph)
if node_type == 'cycles':
self.scgraph.draw('cycles', layout)
if node_type == 'dict':
self.scgraph.draw('dict', layout)
SCC = SurfaceCodeCircuit(sigma, alpha)
SCC.circ.draw('mpl')
nx.draw(SCC.scgraph.code_graph, with_labels = True)
SCC.draw_graph('cycles', 'spring')
SCC.draw_graph('dict', 'spring')
SCC.node_info
SCC.sigma
SCC.alpha
SCC.phi
SCC.scgraph.code_graph.nodes
SCC.star_syndrome_measure(((0,1,2)))
SCC.circ.draw('mpl')
SCC.face_syndrome_measure(((2, 6, 5)))
SCC.circ.draw('mpl')
SCC.product_Z([(0, 4), (2, 6, 5)])
SCC.circ.draw('mpl')
SCC.product_X([(3, 4, 5), (6, 7)])
SCC.circ.draw('mpl')
sigma = ((0,1),(2,3,4),(5,6,7),(8,9),(10,11,12),(13,14,15,16),(17,18,19,20),(21,22,23),(24,25,26),(27,28,29,30),(31,32,33,34),(35,36,37),(38,39),(40,41,42),(43,44,45),(46,47))
alpha = ((0,2),(1,10),(3,5),(4,14),(6,8),(7,18),(9,22),(11,13),(12,24),(15,17),(16,28),(19,21),(20,32),(23,36),(25,27),(26,38),(29,31),(30,41),(33,35),(34,44),(37,47),(39,40),(42,43),(45,46))
SCG = SurfaceCodeGraph(sigma, alpha)
SCG.genus()
SCG.draw('dict', 'planar')
SCG.draw('dict', 'spectral')
len(SCG.code_graph.nodes())
len(SCG.sigma)
len(SCG.alpha)
len(SCG.phi)
SCG.phi
SCG.code_graph.nodes()
SCG.code_graph.remove_node((0, 10, 24, 38, 40, 43, 46, 37, 23, 9, 6, 3))
len(SCG.code_graph.nodes())
nx.draw_spectral(SCG.code_graph, with_labels = False)
G = nx.Graph()
pos = dict()
for x in range(7):
for y in range(7):
G.add_node((x,y))
pos[(x,y)] = (x,y)
if x>0:
G.add_edge((x-1,y),(x,y))
if y>0:
G.add_edge((x,y),(x,y-1))
nx.draw(G, pos=pos, with_labels = True)
nx.is_isomorphic(SCG.code_graph, G)
G1, G2 = SCG.code_graph, G
GM = nx.isomorphism.GraphMatcher(G1,G2)
GM.is_isomorphic()
GM.mapping
node_color = {(x[0], x[1]): 1-((x[0]+x[1])%2)/2 for x in G.nodes()}
for y in range(1,7,2):
for z in range(1,7,2):
node_color[(y,z)] = .2
node_color = [node_color[x] for x in sorted(node_color.keys())]
nx.draw(G, pos = pos, node_color = node_color)
|
https://github.com/0sophy1/Qiskit-Dev-Cert-lectures
|
0sophy1
|
a = 2 + 3j
b = 5 - 2j
print("a + b=", a+b)
print("a * b=", a*b)
a = 2 + 3j
a_bar = 2 - 3j
print("a + a_bar = ", a + a_bar)
print("a * a_bar = ", a * a_bar)
import matplotlib.pyplot as plt
import numpy as np
import math
z1 = 3 + 4j
x_min = 0
x_max = 5.0
y_min = 0
y_max = 5.0
def plot_complex_number_geometric_representation(z,x_min,x_max,y_min,y_max):
fig = plt.figure()
ax = plt.gca()
a = [0.0,0.0]
b = [z.real,z.imag]
head_length = 0.2
dx = b[0] - a[0]
dy = b[1] - a[1]
vec_ab = [dx,dy]
vec_ab_magnitude = math.sqrt(dx**2+dy**2)
dx = dx / vec_ab_magnitude
dy = dy / vec_ab_magnitude
vec_ab_magnitude = vec_ab_magnitude - head_length
ax.arrow(a[0], a[1], vec_ab_magnitude*dx, vec_ab_magnitude*dy, head_width=head_length, head_length=head_length, fc='black', ec='black')
plt.xlim(x_min,x_max)
plt.ylim(y_min,y_max)
plt.grid(True,linestyle='-')
plt.show()
plot_complex_number_geometric_representation(z1,x_min,x_max,y_min,y_max)
import numpy as np
A = np.array([[1,2,3]])
B = np.array([[7], [10], [9]])
A+B
A = np.array([[7], [10], [9]])
B = np.array([[1,2,3]])
C = np.array([[1, 2, 3], [5, 6, 7], [8,9,10]])
print("AB = ", np.matmul(A,B))
print("BA = ", np.matmul(B,A))
print("CA = ", np.matmul(C, A))
print("AC = ", np.matmul(A, C))
A = np.array([[1, 2], [3,4]])
B = np.array([[5, 6], [7,8]])
print("AB = \n", np.matmul(A,B))
print("BA = \n", np.matmul(B,A))
from scipy.linalg import orth
from numpy import linalg as LA
A = np.array([[1 + 3j, 2 - 1j], [3, 4 - 2j]])
data =orth(A)
x, y = data[:, 0], data[:, 1]
print("norm of x = %f" % LA.norm(x))
print("norm of y = %f" % LA.norm(y))
print("x dot y = ", np.vdot(x,y))
|
https://github.com/0sophy1/Qiskit-Dev-Cert-lectures
|
0sophy1
|
a = 2 + 3j
b = 5 - 2j
print("a + b=", a+b)
print("a * b=", a*b)
a = 2 + 3j
a_bar = 2 - 3j
print("a + a_bar = ", a + a_bar)
print("a * a_bar = ", a * a_bar)
import matplotlib.pyplot as plt
import numpy as np
import math
z1 = 3 + 4j
x_min = 0
x_max = 5.0
y_min = 0
y_max = 5.0
def plot_complex_number_geometric_representation(z,x_min,x_max,y_min,y_max):
fig = plt.figure()
ax = plt.gca()
a = [0.0,0.0]
b = [z.real,z.imag]
head_length = 0.2
dx = b[0] - a[0]
dy = b[1] - a[1]
vec_ab = [dx,dy]
vec_ab_magnitude = math.sqrt(dx**2+dy**2)
dx = dx / vec_ab_magnitude
dy = dy / vec_ab_magnitude
vec_ab_magnitude = vec_ab_magnitude - head_length
ax.arrow(a[0], a[1], vec_ab_magnitude*dx, vec_ab_magnitude*dy, head_width=head_length, head_length=head_length, fc='black', ec='black')
plt.xlim(x_min,x_max)
plt.ylim(y_min,y_max)
plt.grid(True,linestyle='-')
plt.show()
plot_complex_number_geometric_representation(z1,x_min,x_max,y_min,y_max)
import numpy as np
A = np.array([[1,2,3]])
B = np.array([[7], [10], [9]])
A+B
A = np.array([[7], [10], [9]])
B = np.array([[1,2,3]])
C = np.array([[1, 2, 3], [5, 6, 7], [8,9,10]])
print("AB = ", np.matmul(A,B))
print("BA = ", np.matmul(B,A))
print("CA = ", np.matmul(C, A))
print("AC = ", np.matmul(A, C))
A = np.array([[1, 2], [3,4]])
B = np.array([[5, 6], [7,8]])
print("AB = \n", np.matmul(A,B))
print("BA = \n", np.matmul(B,A))
from scipy.linalg import orth
from numpy import linalg as LA
A = np.array([[1 + 3j, 2 - 1j], [3, 4 - 2j]])
data =orth(A)
x, y = data[:, 0], data[:, 1]
print("norm of x = %f" % LA.norm(x))
print("norm of y = %f" % LA.norm(y))
print("x dot y = ", np.vdot(x,y))
|
https://github.com/0sophy1/Qiskit-Dev-Cert-lectures
|
0sophy1
|
import numpy as np
from math import sqrt
#define 0, 1, +, - state
zero = np.array([[1],[0]])
one = np.array([[0],[1]])
plus = np.array([[1/sqrt(2)],[1/sqrt(2)]])
minus = np.array([[1/sqrt(2)],[ -1/sqrt(2)]])
#define H operation
H = np.array([[1/sqrt(2), 1/sqrt(2)], [1/sqrt(2), -1/sqrt(2)]])
np.matmul(H,zero) #=plus
np.matmul(H, one) #=minus
np.matmul(H, plus) #=zero
np.matmul(H, minus) #=one
|
https://github.com/0sophy1/Qiskit-Dev-Cert-lectures
|
0sophy1
|
a = 2 + 3j
b = 5 - 2j
print("a + b=", a+b)
print("a * b=", a*b)
a = 2 + 3j
a_bar = 2 - 3j
print("a + a_bar = ", a + a_bar)
print("a * a_bar = ", a * a_bar)
import matplotlib.pyplot as plt
import numpy as np
import math
z1 = 3 + 4j
x_min = 0
x_max = 5.0
y_min = 0
y_max = 5.0
def plot_complex_number_geometric_representation(z,x_min,x_max,y_min,y_max):
fig = plt.figure()
ax = plt.gca()
a = [0.0,0.0]
b = [z.real,z.imag]
head_length = 0.2
dx = b[0] - a[0]
dy = b[1] - a[1]
vec_ab = [dx,dy]
vec_ab_magnitude = math.sqrt(dx**2+dy**2)
dx = dx / vec_ab_magnitude
dy = dy / vec_ab_magnitude
vec_ab_magnitude = vec_ab_magnitude - head_length
ax.arrow(a[0], a[1], vec_ab_magnitude*dx, vec_ab_magnitude*dy, head_width=head_length, head_length=head_length, fc='black', ec='black')
plt.xlim(x_min,x_max)
plt.ylim(y_min,y_max)
plt.grid(True,linestyle='-')
plt.show()
plot_complex_number_geometric_representation(z1,x_min,x_max,y_min,y_max)
import numpy as np
A = np.array([[1,2,3]])
B = np.array([[7], [10], [9]])
A+B
A = np.array([[7], [10], [9]])
B = np.array([[1,2,3]])
C = np.array([[1, 2, 3], [5, 6, 7], [8,9,10]])
print("AB = ", np.matmul(A,B))
print("BA = ", np.matmul(B,A))
print("CA = ", np.matmul(C, A))
print("AC = ", np.matmul(A, C))
A = np.array([[1, 2], [3,4]])
B = np.array([[5, 6], [7,8]])
print("AB = \n", np.matmul(A,B))
print("BA = \n", np.matmul(B,A))
from scipy.linalg import orth
from numpy import linalg as LA
A = np.array([[1 + 3j, 2 - 1j], [3, 4 - 2j]])
data =orth(A)
x, y = data[:, 0], data[:, 1]
print("norm of x = %f" % LA.norm(x))
print("norm of y = %f" % LA.norm(y))
print("x dot y = ", np.vdot(x,y))
|
https://github.com/sorin-bolos/QiskitCampAsia2019
|
sorin-bolos
|
# useful additional packages
import matplotlib.pyplot as plt
import matplotlib.axes as axes
%matplotlib inline
import numpy as np
import networkx as nx
from qiskit import BasicAer
from qiskit.tools.visualization import plot_histogram
from qiskit.aqua import run_algorithm
from qiskit.aqua.input import EnergyInput
from qiskit.aqua.translators.ising import max_cut, tsp
from qiskit.aqua.algorithms import VQE, ExactEigensolver
from qiskit.aqua.components.optimizers import SPSA
from qiskit.aqua.components.variational_forms import RY
from qiskit.aqua import QuantumInstance
from qiskit.quantum_info import Pauli
from qiskit.aqua.operators import WeightedPauliOperator
from collections import OrderedDict
import math
# setup aqua logging
import logging
from qiskit.aqua import set_qiskit_aqua_logging
def get_knapsack_operator(values, weights, max_weight):
if len(values) != len(weights):
raise ValueError("The values and weights must have the same length")
if any(v < 0 for v in values) or any(w < 0 for w in weights):
raise ValueError("The values and weights cannot be negative")
if all(v == 0 for v in values):
raise ValueError("The values cannot all be 0")
if max_weight < 0:
raise ValueError("max_weight cannot be negative")
y_size = int(math.log(max_weight, 2)) + 1 if max_weight > 0 else 1
print(y_size)
n = len(values)
num_values = n + y_size
pauli_list = []
shift = 0
M = 2000000 #10 * np.sum(values)
# term for sum(x_i*w_i)**2
for i in range(n):
for j in range(n):
coefficient = -1 * 0.25 * weights[i] * weights[j] * M
xp = np.zeros(num_values, dtype=np.bool)
zp = np.zeros(num_values, dtype=np.bool)
zp[j] = not zp[j]
pauli_list.append([coefficient, Pauli(zp, xp)])
shift -= coefficient
xp = np.zeros(num_values, dtype=np.bool)
zp = np.zeros(num_values, dtype=np.bool)
zp[i] = not zp[i]
pauli_list.append([coefficient, Pauli(zp, xp)])
shift -= coefficient
coefficient = -1 * coefficient
xp = np.zeros(num_values, dtype=np.bool)
zp = np.zeros(num_values, dtype=np.bool)
zp[i] = not zp[i]
zp[j] = not zp[j]
pauli_list.append([coefficient, Pauli(zp, xp)])
shift -= coefficient
# term for sum(2**j*y_j)**2
for i in range(y_size):
for j in range(y_size):
coefficient = -1 * 0.25 * (2 ** i) * (2 ** j) * M
xp = np.zeros(num_values, dtype=np.bool)
zp = np.zeros(num_values, dtype=np.bool)
zp[n + j] = not zp[n + j]
pauli_list.append([coefficient, Pauli(zp, xp)])
shift -= coefficient
xp = np.zeros(num_values, dtype=np.bool)
zp = np.zeros(num_values, dtype=np.bool)
zp[n + i] = not zp[n + i]
pauli_list.append([coefficient, Pauli(zp, xp)])
shift -= coefficient
coefficient = -1 * coefficient
xp = np.zeros(num_values, dtype=np.bool)
zp = np.zeros(num_values, dtype=np.bool)
zp[n + i] = not zp[n + i]
zp[n + j] = not zp[n + j]
pauli_list.append([coefficient, Pauli(zp, xp)])
shift -= coefficient
# term for -2*W_max*sum(x_i*w_i)
for i in range(n):
coefficient = max_weight * weights[i] * M
xp = np.zeros(num_values, dtype=np.bool)
zp = np.zeros(num_values, dtype=np.bool)
zp[i] = not zp[i]
pauli_list.append([coefficient, Pauli(zp, xp)])
shift -= coefficient
# term for -2*W_max*sum(2**j*y_j)
for j in range(y_size):
coefficient = max_weight * (2 ** j) * M
xp = np.zeros(num_values, dtype=np.bool)
zp = np.zeros(num_values, dtype=np.bool)
zp[n + j] = not zp[n + j]
pauli_list.append([coefficient, Pauli(zp, xp)])
shift -= coefficient
for i in range(n):
for j in range(y_size):
coefficient = -1 * 0.5 * weights[i] * (2 ** j) * M
xp = np.zeros(num_values, dtype=np.bool)
zp = np.zeros(num_values, dtype=np.bool)
zp[n + j] = not zp[n + j]
pauli_list.append([coefficient, Pauli(zp, xp)])
shift -= coefficient
xp = np.zeros(num_values, dtype=np.bool)
zp = np.zeros(num_values, dtype=np.bool)
zp[i] = not zp[i]
pauli_list.append([coefficient, Pauli(zp, xp)])
shift -= coefficient
coefficient = -1 * coefficient
xp = np.zeros(num_values, dtype=np.bool)
zp = np.zeros(num_values, dtype=np.bool)
zp[i] = not zp[i]
zp[n + j] = not zp[n + j]
pauli_list.append([coefficient, Pauli(zp, xp)])
shift -= coefficient
# term for sum(x_i*v_i)
for i in range(n):
coefficient = 0.5 * values[i]
xp = np.zeros(num_values, dtype=np.bool)
zp = np.zeros(num_values, dtype=np.bool)
zp[i] = not zp[i]
pauli_list.append([coefficient, Pauli(zp, xp)])
shift -= coefficient
return WeightedPauliOperator(paulis=pauli_list), shift
def get_solution(x, values):
return x[:len(values)]
def knapsack_value_weight(solution, values, weights):
value = np.sum(solution * values)
weight = np.sum(solution * weights)
return value, weight
def sample_most_likely(state_vector):
if isinstance(state_vector, dict) or isinstance(state_vector, OrderedDict):
# get the binary string with the largest count
binary_string = sorted(state_vector.items(), key=lambda kv: kv[1])[-1][0]
x = np.asarray([int(y) for y in reversed(list(binary_string))])
return x
else:
n = int(np.log2(state_vector.shape[0]))
k = np.argmax(np.abs(state_vector))
x = np.zeros(n)
for i in range(n):
x[i] = k % 2
k >>= 1
return x
# values = [680, 120, 590, 178]
# weights = [13, 6, 15, 9]
# w_max = 32
values = [8, 2]
weights = [3, 1]
w_max = 3
qubitOp, offset = get_knapsack_operator(values, weights, w_max)
algo_input = EnergyInput(qubitOp)
ee = ExactEigensolver(qubitOp, k=1)
result = ee.run()
most_lightly = result['eigvecs'][0]
x = sample_most_likely(most_lightly)
print(x)
print('result=' + str(x[:len(values)]))
seed = 10598
spsa = SPSA(max_trials=10000)
ry = RY(qubitOp.num_qubits, depth=5, entanglement='linear')
vqe = VQE(qubitOp, ry, spsa)
backend = BasicAer.get_backend('statevector_simulator')
quantum_instance = QuantumInstance(backend, seed_simulator=seed, seed_transpiler=seed)
result_statevector = vqe.run(quantum_instance)
most_lightly_sv = result_statevector['eigvecs'][0]
x_statevector = sample_most_likely(most_lightly_sv)
print(x_statevector)
print('result usig statevector_simulator =' + str(x_statevector[:len(values)]))
# run quantum algorithm with shots
seed = 10598
spsa = SPSA(max_trials=1000)
ry = RY(qubitOp.num_qubits, depth=5, entanglement='linear')
vqe = VQE(qubitOp, ry, spsa)
backend = BasicAer.get_backend('qasm_simulator')
quantum_instance = QuantumInstance(backend, shots=1024, seed_simulator=seed, seed_transpiler=seed)
result_shots = vqe.run(quantum_instance)
most_lightly_shots = result_shots['eigvecs'][0]
x_shots = sample_most_likely(most_lightly_shots)
print(x_shots)
print('result usig qasm_simulator =' + str(x_shots[:len(values)]))
math.log(8, 2)
|
https://github.com/sorin-bolos/QiskitCampAsia2019
|
sorin-bolos
|
# useful additional packages
import matplotlib.pyplot as plt
import matplotlib.axes as axes
%matplotlib inline
import numpy as np
import networkx as nx
from qiskit import BasicAer
from qiskit.tools.visualization import plot_histogram
from qiskit.aqua import run_algorithm
from qiskit.aqua.input import EnergyInput
from qiskit.aqua.translators.ising import max_cut, tsp
from qiskit.aqua.algorithms import VQE, ExactEigensolver
from qiskit.aqua.components.optimizers import SPSA
from qiskit.aqua.components.variational_forms import RY
from qiskit.aqua import QuantumInstance
from qiskit.quantum_info import Pauli
from qiskit.aqua.operators import WeightedPauliOperator
from collections import OrderedDict
# setup aqua logging
import logging
from qiskit.aqua import set_qiskit_aqua_logging
# set_qiskit_aqua_logging(logging.DEBUG) # choose INFO, DEBUG to see the log
def get_values_qubitops(values):
num_values = len(values)
pauli_list = []
shift = 0
for i in range(num_values):
xp = np.zeros(num_values, dtype=np.bool)
zp = np.zeros(num_values, dtype=np.bool)
zp[i] = True
pauli_list.append([0.5 * values[i], Pauli(zp, xp)])
shift -= 0.5 * values[i]
return WeightedPauliOperator(paulis=pauli_list), shift
values = [3, 6, -4, 8]
qubitOp, offset = get_values_qubitops(values)
algo_input = EnergyInput(qubitOp)
ee = ExactEigensolver(qubitOp, k=1)
result = ee.run()
def sample_most_likely(state_vector):
if isinstance(state_vector, dict) or isinstance(state_vector, OrderedDict):
# get the binary string with the largest count
binary_string = sorted(state_vector.items(), key=lambda kv: kv[1])[-1][0]
x = np.asarray([int(y) for y in reversed(list(binary_string))])
return x
else:
n = int(np.log2(state_vector.shape[0]))
k = np.argmax(np.abs(state_vector))
x = np.zeros(n)
for i in range(n):
x[i] = k % 2
k >>= 1
return x
most_lightly = result['eigvecs'][0]
x = sample_most_likely(most_lightly)
x
seed = 10598
spsa = SPSA(max_trials=300)
ry = RY(qubitOp.num_qubits, depth=5, entanglement='linear')
vqe = VQE(qubitOp, ry, spsa)
backend = BasicAer.get_backend('statevector_simulator')
quantum_instance = QuantumInstance(backend, seed_simulator=seed, seed_transpiler=seed)
result_statevector = vqe.run(quantum_instance)
most_lightly = result_statevector['eigvecs'][0]
x_statevector = sample_most_likely(most_lightly)
x_statevector
# run quantum algorithm with shots
seed = 10598
spsa = SPSA(max_trials=300)
ry = RY(qubitOp.num_qubits, depth=5, entanglement='linear')
vqe = VQE(qubitOp, ry, spsa)
backend = BasicAer.get_backend('qasm_simulator')
quantum_instance = QuantumInstance(backend, shots=1024, seed_simulator=seed, seed_transpiler=seed)
result_shots = vqe.run(quantum_instance)
most_lightly_shots = result_shots['eigvecs'][0]
x_shots = sample_most_likely(most_lightly_shots)
x_shots
|
https://github.com/sorin-bolos/QiskitCampAsia2019
|
sorin-bolos
|
# useful additional packages
import matplotlib.pyplot as plt
import matplotlib.axes as axes
%matplotlib inline
import numpy as np
import networkx as nx
from qiskit import BasicAer
from qiskit.tools.visualization import plot_histogram
from qiskit.aqua import run_algorithm
from qiskit.aqua.input import EnergyInput
from qiskit.aqua.translators.ising import max_cut, tsp
from qiskit.aqua.algorithms import VQE, ExactEigensolver
from qiskit.aqua.components.optimizers import SPSA
from qiskit.aqua.components.variational_forms import RY
from qiskit.aqua import QuantumInstance
from qiskit.quantum_info import Pauli
from qiskit.aqua.operators import WeightedPauliOperator
from collections import OrderedDict
import math
# setup aqua logging
import logging
from qiskit.aqua import set_qiskit_aqua_logging
# set_qiskit_aqua_logging(logging.DEBUG) # choose INFO, DEBUG to see the log
def sample_most_likely(state_vector):
if isinstance(state_vector, dict) or isinstance(state_vector, OrderedDict):
# get the binary string with the largest count
binary_string = sorted(state_vector.items(), key=lambda kv: kv[1])[-1][0]
x = np.asarray([int(y) for y in reversed(list(binary_string))])
return x
else:
n = int(np.log2(state_vector.shape[0]))
k = np.argmax(np.abs(state_vector))
x = np.zeros(n)
for i in range(n):
x[i] = k % 2
k >>= 1
return x
def get_knapsack_qubitops(values, weights, w_max, M):
ysize = int(math.log(w_max + 1, 2))
n = len(values)
num_values = n + ysize;
pauli_list = []
shift = 0
#term for sum(x_i*w_i)^2
for i in range(n):
for j in range(n):
coef = -1 * 0.25 * weights[i] * weights[j] * M
xp = np.zeros(num_values, dtype=np.bool)
zp = np.zeros(num_values, dtype=np.bool)
zp[j] = not zp[j]
pauli_list.append([coef, Pauli(zp, xp)])
shift -= coef
xp = np.zeros(num_values, dtype=np.bool)
zp = np.zeros(num_values, dtype=np.bool)
zp[i] = not zp[i]
pauli_list.append([coef, Pauli(zp, xp)])
shift -= coef
coef = -1 * coef
xp = np.zeros(num_values, dtype=np.bool)
zp = np.zeros(num_values, dtype=np.bool)
zp[i] = not zp[i]
zp[j] = not zp[j]
pauli_list.append([coef, Pauli(zp, xp)])
shift -= coef
#term for sum(2^j*y_j)^2
for i in range(ysize):
for j in range(ysize):
coef = -1 * 0.25 * (2^i) * (2^j) * M
xp = np.zeros(num_values, dtype=np.bool)
zp = np.zeros(num_values, dtype=np.bool)
zp[n+j] = not zp[n+j]
pauli_list.append([coef, Pauli(zp, xp)])
shift -= coef
xp = np.zeros(num_values, dtype=np.bool)
zp = np.zeros(num_values, dtype=np.bool)
zp[n+i] = not zp[n+i]
pauli_list.append([coef, Pauli(zp, xp)])
shift -= coef
coef = -1 * coef
xp = np.zeros(num_values, dtype=np.bool)
zp = np.zeros(num_values, dtype=np.bool)
zp[n+i] = not zp[n+i]
zp[n+j] = not zp[n+j]
pauli_list.append([coef, Pauli(zp, xp)])
shift -= coef
#term for -2*W_max*sum(x_i*w_i)
for i in range(n):
xp = np.zeros(num_values, dtype=np.bool)
zp = np.zeros(num_values, dtype=np.bool)
zp[i] = not zp[i]
coef = w_max * weights[i] * M
pauli_list.append([coef, Pauli(zp, xp)])
shift -= coef
#term for -2*W_max*sum(2^j*y_j)
for j in range(ysize):
xp = np.zeros(num_values, dtype=np.bool)
zp = np.zeros(num_values, dtype=np.bool)
zp[n+j] = not zp[n+j]
coef = w_max * (2^j) * M
pauli_list.append([coef, Pauli(zp, xp)])
shift -= coef
for i in range(n):
for j in range(ysize):
coef = -0.5 * weights[i] * (2^j) * M
xp = np.zeros(num_values, dtype=np.bool)
zp = np.zeros(num_values, dtype=np.bool)
zp[n+j] = not zp[n+j]
pauli_list.append([coef, Pauli(zp, xp)])
shift -= coef
xp = np.zeros(num_values, dtype=np.bool)
zp = np.zeros(num_values, dtype=np.bool)
zp[i] = not zp[i]
pauli_list.append([coef, Pauli(zp, xp)])
shift -= coef
coef = -1 * coef
xp = np.zeros(num_values, dtype=np.bool)
zp = np.zeros(num_values, dtype=np.bool)
zp[i] = not zp[i]
zp[n+j] = not zp[n+j]
pauli_list.append([coef, Pauli(zp, xp)])
shift -= coef
#term for sum(x_i*v_i)
for i in range(n):
xp = np.zeros(num_values, dtype=np.bool)
zp = np.zeros(num_values, dtype=np.bool)
zp[i] = not zp[i]
pauli_list.append([0.5 * values[i], Pauli(zp, xp)])
shift -= 0.5 * values[i]
return WeightedPauliOperator(paulis=pauli_list), shift
values = [680, 120, 57, 178]
weights = [3, 6, 5, 9]
w_max = 15
M = 2000000
qubitOp, offset = get_knapsack_qubitops(values, weights, w_max, M)
algo_input = EnergyInput(qubitOp)
ee = ExactEigensolver(qubitOp, k=1)
result = ee.run()
most_lightly = result['eigvecs'][0]
x = sample_most_likely(most_lightly)
print('result=' + str(x[:len(values)]))
seed = 10598
spsa = SPSA(max_trials=300)
ry = RY(qubitOp.num_qubits, depth=5, entanglement='linear')
vqe = VQE(qubitOp, ry, spsa)
backend = BasicAer.get_backend('statevector_simulator')
quantum_instance = QuantumInstance(backend, seed_simulator=seed, seed_transpiler=seed)
result_statevector = vqe.run(quantum_instance)
most_lightly_sv = result_statevector['eigvecs'][0]
x_statevector = sample_most_likely(most_lightly_sv)
print('result usig statevector_simulator =' + str(x_statevector[:len(values)]))
# run quantum algorithm with shots
seed = 10598
spsa = SPSA(max_trials=300)
ry = RY(qubitOp.num_qubits, depth=5, entanglement='linear')
vqe = VQE(qubitOp, ry, spsa)
backend = BasicAer.get_backend('qasm_simulator')
quantum_instance = QuantumInstance(backend, shots=1024, seed_simulator=seed, seed_transpiler=seed)
result_shots = vqe.run(quantum_instance)
most_lightly_shots = result_shots['eigvecs'][0]
x_shots = sample_most_likely(most_lightly_shots)
print('result usig qasm_simulator =' + str(x_shots[:len(values)]))
|
https://github.com/YPadawan/qiskit-hackathon
|
YPadawan
|
import numpy as np
import matplotlib.pyplot as plt
import torch
from torchvision import datasets, transforms
n_samples = 100
#transforms.compose receive all the types of transformation that can be done on an image
#in our case the only transformation that we do is to transform the image into a tensor, it is
#why between hook [] we just have transforms.ToTensor()
X_train = datasets.MNIST(root='./data' , train=True, download=True,
transform=transforms.Compose([transforms.ToTensor()]))
# Leaving only 8 and 9
#We select two numbers to make the classification
#I try to take characters that are alike to put the model a little in difficulty
idx = np.append(np.where(X_train.targets == 8)[0][:n_samples],
np.where(X_train.targets == 9)[0][:n_samples])
X_train.data = X_train.data = X_train.data[idx]
X_train.targets = X_train.targets[idx]
train_loader = torch.utils.data.DataLoader(X_train, batch_size=1, shuffle=True)
n_samples_show = 5
data_iter = iter(train_loader)
fig, axes = plt.subplots(nrows = 1, ncols=n_samples_show, figsize=(10, 3))
while n_samples_show > 0:
images, targets = data_iter.__next__()
axes[n_samples_show - 1].imshow(images[0].numpy().squeeze(), cmap='gray')
axes[n_samples_show - 1].set_xticks([])
axes[n_samples_show - 1].set_yticks([])
axes[n_samples_show - 1].set_title("Labeled: {}".format(targets.item()))
n_samples_show -= 1
#Half of the data is used for validation
n_samples = 50
X_test = datasets.MNIST(root='./data', train=False, download=True,
transform=transforms.Compose([transforms.ToTensor()]))
idx = np.append(np.where(X_test.targets == 5)[0][:n_samples],
np.where(X_test.targets == 6)[0][:n_samples])
X_test.data = X_test.data[idx]
X_test.targets = X_test.targets[idx]
test_loader = torch.utils.data.DataLoader(X_test, batch_size=1, shuffle=True)
|
https://github.com/YPadawan/qiskit-hackathon
|
YPadawan
|
import numpy as np
# Importing necessary quantum computing library (QISKIT)
import qiskit
from qiskit import QuantumCircuit, QuantumRegister
from qiskit.visualization import *
# Source:https://www.tensorflow.org/quantum/tutorials/qcnn
def cluster_state(qr):
"""Returns a cluster state of the qubits in the quantum register `qr`
Parameters
----------
qr: (QuantumRegister)
Qiskit quantum register
Returns
-------
qc: (QuantumCircuit)
Qiskit quantum circuit with the cluster state
"""
qc = QuantumCircuit(qr) # Creating a QuantumRegister
# Applying a Hadamard gate to qubits
for i, _ in enumerate(qr):
qc.h(i)
for this_bit, next_bit in zip(qr, qr[1:] + [qr[0]]):
c = this_bit.index
t = next_bit.index
qc.cz(c, t)
return qc
qc_cs = cluster_state(QuantumRegister(4))
qc_cs.draw('mpl')
# https://www.tensorflow.org/quantum/tutorials/qcnn
# This function is a readaptation of the tensorflow tutorial using qiskit and pytorch instead
# WARNING: I believe the function is working, but it looks like it is not possible to convert quantum gates
# and quantum circuits to pytorch tensors.
# I don't think there is an equivalent of tfq.convert_to_tensor yet.
# For the moment the function only returns a tuple of lists for train and test excitations.
def generate_data(qubits):
"""Generate training and testing data.
Parameters
----------
qubits: (Qiskit QuantumRegister)
Quantum register containing qubits to pass to the Quantum circuit
Returns
--------
train_excitations: (list)
list of excited qubits for training
train_labels: (array)
numpy array containing the labels corresponding to the train set
test_excitations: (list)
list of excited qubits to use as a testing set
test_labels: (array)
numpy array containing the labels of the test set
N.B. train_excitations and test_excitations should be a PyTorch tensor
"""
n_rounds = 20 # Produces n_rounds * n_qubits datapoints.
excitations = []
labels = []
for n in range(n_rounds):
for bit in qubits:
rng = np.random.uniform(-np.pi, np.pi)
# Creating a quantum circuit with qiskit
excitations.append(QuantumCircuit(bit.register).rx(rng, bit.register))
#excitations.append(cirq.Circuit(cirq.rx(rng)(bit))) / cirq to check if it's correct
labels.append(1 if (-np.pi / 2) <= rng <= (np.pi / 2) else -1)
split_ind = int(len(excitations) * 0.7)
train_excitations = excitations[:split_ind]
test_excitations = excitations[split_ind:]
train_labels = labels[:split_ind]
test_labels = labels[split_ind:]
return train_excitations, np.array(train_labels), \
test_excitations, np.array(test_labels)
qr = QuantumRegister(2)
train_excitations, train_labels, test_excitations, test_labels = generate_data(qr)
# Source of the function: https://www.tensorflow.org/quantum/tutorials/qcnn
# The function has been re-adapted for qiskit use
from qiskit.circuit import Parameter
def one_qubit_unitary(bit, rotation=('1', '2', '3')):
"""Make a circuit enacting a rotation of the bloch sphere about the X,
Y and Z axis, that depends on the values in `symbols`.
Parameters
-----------
bit: (QuantumRegister (qubit))
qubit to rotate
rotation: (tuple)
tuple containing the three rotation values of rotation operators for respectively, x, y and z
Returns
-------
Rotated qubit, one qubit unitary matrix
"""
x, y, z = rotation
qc = QuantumCircuit(bit)
qc.rx(Parameter(x), 0)
qc.ry(Parameter(y), 0)
qc.rz(Parameter(z), 0)
return qc
one_qubit_unitary(1, ("e1", "e2", "e3")).draw()
# Function still needs some rechecking but it might be correct.
# replace symbols later, still having an issue with symbols
def two_qubit_unitary(bits,
rotations={"q1": ("x1", "y1", "z1"),
"q2": ('x2', 'y2', 'z2'),
"rzyx":("t1", "t2", "t3")}):
"""Make a qiskit circuit that creates an arbitrary two qubit unitary.
Parameters
----------
bits: (QuantumRegister)
Qiskit quantum register which we want to pass to the circuit
rotations: (dictionary)
dictionary containing the rotation parameters for both qubits and x, y, z axis
Returns
-------
big_qc: (QuantumCircuit)
Qiskit quantum circuit representing two-qubit unitary matrix (to be confirmed)
"""
rot1 = rotations["q1"]
rot2 = rotations["q2"]
sub_circ1 = one_qubit_unitary(1, rot1)
sub_circ2 = one_qubit_unitary(1, rot2)
qr = bits
big_qc = QuantumCircuit(qr)
big_qc.append(sub_circ1.to_instruction(), [qr[0]])
big_qc.append(sub_circ2.to_instruction(), [qr[1]])
zz, yy, xx = rotations["rzyx"]
big_qc.rzz(Parameter(zz), 0, 1)
big_qc.ryy(Parameter(yy), 0, 1)
big_qc.rxx(Parameter(xx), 0, 1)
big_qc.append(sub_circ1.to_instruction(), [qr[0]])
big_qc.append(sub_circ2.to_instruction(), [qr[1]])
return big_qc
two_qubit_unitary(QuantumRegister(2)).decompose().draw('mpl')
# source: https://www.tensorflow.org/quantum/tutorials/qcnn
def two_qubit_pool(source_qubit, sink_qubit,
rotations={"q1":("x1", "y1", "z1"),
"q2": ("x2", "y2", "z2"),
"invq":("-x2", "-y2", "-z2")}): # add symbols later
"""Make a Qiskit circuit to do a parameterized 'pooling' operation, which
attempts to reduce entanglement down from two qubits to just one.
Parameters
---------
source_qubit: (QuantumRegister)
source qubit that will be the control qubit before sinking
sink_qubit: (QuantumRegister)
sink_qubit that will be the target qubit of the CNOT gate and that is supposed to be inversed
Returns
------
pool_circuit: (QuantumCircuit)
Qiskit quantum circuit making the pooling operation
"""
rot1 = rotations["q1"]
rot2 = rotations["q2"]
sink_basis_selector = one_qubit_unitary(sink_qubit, rot1)
source_basis_selector = one_qubit_unitary(source_qubit, rot2)
qr = QuantumRegister(2)
pool_circuit = QuantumCircuit(qr)
pool_circuit.append(sink_basis_selector.to_instruction(), [qr[0]])
pool_circuit.append(source_basis_selector.to_instruction(), [qr[1]])
pool_circuit.cnot(control_qubit=0, target_qubit=1)
# add sink_basis selector I don't know what is being done
inv_rot = rotations["invq"]
inv_sink_basis_selector = one_qubit_unitary(source_qubit, inv_rot)
pool_circuit.append(inv_sink_basis_selector.to_instruction(), [qr[1]])
return pool_circuit
two_qubit_pool(QuantumRegister(1), QuantumRegister(1)).decompose().draw('mpl')
def quantum_conv_circuit(bits): # Take care of rotations later
"""Quantum Convolution Layer
Parameters
----------
bits: (QuantumRegister)
Qiskit quantum register that will be used in the quantum circuit
Returns
-------
qc: (QuantumCircuit)
Qiskit circuit with the cascade of `two_qubit_unitary` applied
to all pairs of qubits in `bits`
"""
qc = QuantumCircuit(bits)
# The xyz variable below is meant as a workaround to parameter implementation and replacement
xyz = ("x", "y", "z")
k = 0 # variable to increment in order
for first, second in zip(bits[0::2], bits[1::2]):
i = first.index
j = second.index
### Creating parameters to avoid duplicate names because they raises a Circuit Error ###
k+=1
q1_val = tuple([r + str(k) for r in xyz])
q2_val = tuple([r + str(k + 1) for r in xyz])
rzyx = tuple([t + str(k) for t in ("theta", "beta", "gamma")])
k+=1
rotations = {"q1": q1_val, "q2":q2_val, "rzyx":rzyx}
qc.append(two_qubit_unitary(QuantumRegister(2), rotations).to_instruction(), [bits[i], bits[j]])
### Second loop for the second two_qubit unitary
abc = ("a", "b", "c")
p = 0
for first, second in zip(bits[1::2], bits[2::2] + [bits[0]]):
i = first.index
j = second.index
### Creating parameters to avoid duplicate names because they raises a Circuit Error ###
p+=1
q1_val = tuple([r + str(p) for r in abc])
q2_val = tuple([r + str(p + 1) for r in abc])
rzyx = tuple([t + str(p) for t in ("mu", "nu", "eps")])
p+=1
rotations = {"q1": q1_val, "q2":q2_val, "rzyx":rzyx}
qc.append(two_qubit_unitary(QuantumRegister(2), rotations).to_instruction(), [bits[i], bits[j]])
return qc
quantum_conv_circuit(QuantumRegister(8)).decompose().draw('mpl')
def quantum_pool_circuit(bits):
"""A layer that specifies a quantum pooling operation.
A Quantum pool tries to learn to pool the relevant information from two
qubits onto 1.
Parameters
----------
bits: (QuantumRegister)
Qiskit quantum register
Returns
-------
circuit: (QuantumCircuit)
Qiskit quantum circuit with the pooled qubits
"""
circuit = QuantumCircuit(bits) # instantiating of the quantum circuit
# The xyz variable below is mean't as a workaround to parameter implementation and replacement
xyz = ("x", "y", "z")
k = 0 # variable to increment in order
assert len(bits) % 2==0, "The number of qubits in the register should be even"
split = len(bits) // 2 # taking half of the quantum register's length
for source, sink in zip(bits[:split], bits[split:]):
i = source.index # getting source qubit index
j = sink.index # sink qubit index
### Creating parameters to avoid duplicate names because they raises a Circuit Error ###
k+=1
q1_val = tuple([r + str(k) for r in xyz])
invq_val = tuple(["-" + r + str(k) for r in xyz])
q2_val = tuple([r + str(k + 1) for r in xyz])
k+=1 # k is incremented twice because q2_val takes the value (k + 1) at k round
tqb = two_qubit_pool(QuantumRegister(1), QuantumRegister(1),
{"q1": q1_val, "q2":q2_val, "invq":invq_val})
circuit.append(tqb.to_instruction(),
[bits[i], bits[j]])
return circuit
test_bits = QuantumRegister(8)
quantum_pool_circuit(test_bits).decompose().draw('mpl')
|
https://github.com/stfnmangini/VQE_from_scratch
|
stfnmangini
|
import qiskit as qk
qc = qk.QuantumCircuit(2,1)
qc.barrier()
qc.cx(0,1)
qc.measure(1,0)
print("Measurement in the ZZ basis")
qc.draw(output="mpl")
qc = qk.QuantumCircuit(2,1)
qc.barrier()
qc.h(0)
qc.h(1)
qc.cx(0,1)
qc.measure(1,0)
print("Measurement in the XX basis")
qc.draw(output="mpl")
qc = qk.QuantumCircuit(2,1)
qc.barrier()
qc.sdg(0)
qc.sdg(1)
qc.h(0)
qc.h(1)
qc.cx(0,1)
qc.measure(1,0)
print("Measurement in the YY basis")
qc.draw(output="mpl")
from qiskit import Aer
import numpy as np
from scipy.optimize import minimize_scalar, minimize
from numpy import pi
sim_bknd = qk.Aer.get_backend('qasm_simulator')
def ansatz(qc, qr, theta):
"""
Builds the trial state using the ansatz: (RX I) CX (H I)|00>
Arguments
-----------
qc: is a QuantumCircuit object from Qiskit
qr: is a QuantumRegister object used in the quantum circuit qc
theta (real): is the parameter parametrizing the trial state
Return
---------
qc: returns the input quantum circuit added with the gates creating the trial state
"""
qc.h(qr[0])
qc.cx(qr[0],qr[1])
qc.rx(theta, qr[0])
return qc
def measurements(qc, qr, cr, op):
"""
Implements the quantum measurements in different basis: XX, YY and ZZ.
Arguments
-----------
qc: is a QuantumCircuit object from Qiskit
qr: is a QuantumRegister object used in the quantum circuit qc
cr: is a ClassicalRegister object used in the quantum circuit qc
op (str): is a string with possible values: XX, YY and ZZ.
Return
---------
qc: returns the input quantum circuit added with the appropriate gates to measure in the selected basis.
"""
if op == "XX":
# Change of basis, since X = HZH
qc.h(qr[0])
qc.h(qr[1])
# CNOT used to measure ZZ operator
qc.cx(qr[0],qr[1])
# Measurement of qubit 1 on classical register 0
qc.measure(qr[1],cr[0])
elif op == "YY":
# Change of basis, since Y = (HS†)Z(HS†)
qc.sdg(qr[0])
qc.sdg(qr[1])
qc.h(qr[0])
qc.h(qr[1])
# CNOT used to measure ZZ operator
qc.cx(qr[0],qr[1])
# Measurement of qubit 1 on classical register 0
qc.measure(qr[1],cr[0])
elif op == "ZZ":
# CNOT used to measure ZZ operator
qc.cx(qr[0],qr[1])
# Measurement of qubit 1 on classical register 0
qc.measure(qr[1],cr[0])
else:
print(f"WARNING: Measurement on the {op} basis not supported")
return
return qc
def hamiltonian(params):
"""
Evaulates the Energy of the trial state using the mean values of the operators XX, YY and ZZ.
Arguments
-----------
params (dict): is an dictionary containing the mean values form the measurements of the operators XX, YY, ZZ;
Return
---------
en (real): energy of the system
"""
# H = 1/2 * (Id + ZZ - XX - YY)
en = (1 + params['ZZ'] - params['XX'] - params['YY']) / 2
return en
def vqe_step(theta, verbose = True):
"""
Executes the VQE algorithm.
Creates and executes three quantum circuits (one for each of the observables XX, YY and ZZ), then evaluates the energy.
Arguments
-----------
theta (real): is the parameter parametrizing the trial state
Return
--------
energy (real): the energy of the system
qc_list (dict): a dictionary containing the three quantum circuits for the observables XX, YY and ZZ
"""
# Number of executions for each quantum circuit
shots=8192
vqe_res = dict()
qc_list = dict()
for op in ["XX", "YY", "ZZ"]:
qr = qk.QuantumRegister(2, "qr")
cr = qk.ClassicalRegister(1, "cr")
qc = qk.QuantumCircuit(qr, cr)
# Implementation of the ansatz
qc = ansatz(qc, qr, theta)
# Just for plotting purposes
qc.barrier()
# Measurements in the appropriate basis (XX, YY, ZZ) are implemented
qc = measurements(qc, qr, cr, op)
# Get the measurements results
counts = qk.execute(qc, sim_bknd, shots=shots).result().get_counts()
# Check the results, and evaluate the mean value dividing by the number of shots
if len(counts) == 1:
try:
counts['0']
mean_val = 1
except:
mean_val = -1
else:
# Evaluates the mean value of Z operator, as the difference in the number of
# 0s and 1s in the measurement outcomes
mean_val = (counts['0']-counts['1'])/shots
vqe_res[op] = mean_val
qc_list[op] = qc
energy = hamiltonian(vqe_res)
if verbose:
print("Mean values from measurement results:\n", vqe_res)
print(f"\n{'Theta':<10} {'Energy':<10} {'<XX>':<10} {'<YY>':<10} {'<ZZ>':<10}")
print(f"{theta:<10f} {energy:<10f} {vqe_res['XX']:<10f} {vqe_res['YY']:<10f} {vqe_res['ZZ']:<10f}")
return energy, qc_list
else:
return energy
# Set the value of theta
theta = 0.2
# Run the VQE step to evaluate the energy (eigenvalue of the Hamiltonian) of the state with given theta
energy, qc_list = vqe_step(theta)
# Plot the circuit used for the measurement of YY
op = 'YY'
print(f"\nQuantum circuit for the measurement of {op}")
qc_list[op].draw(output="mpl")
minimize_scalar(vqe_step, args=(False), bounds = (0, pi), method = "bounded")
lowest, _ = vqe_step(pi)
# Definition of one qubit Pauli matrices
I = np.array([[1,0],[0,1]])
X = np.array([[0,1],[1,0]])
Y = np.array([[0,-1j],[1j,0]])
Z = np.array([[1,0],[0,-1]])
# Evaluation of two qubit Pauli matrices
II = np.kron(I,I)
XX = np.kron(X,X)
YY = np.kron(Y,Y)
ZZ = np.kron(Z,Z)
# Calculation of the Hamiltonian
H = (1/2) * (II+ZZ) - (1/2) * (XX+YY)
print("Desired Hamiltionian H = \n", H)
import scipy
# Calculate eigenvalues and eigenvectors of H
eigenvalues, eigenvectors = scipy.linalg.eig(H)
print("Eigenvalues:", eigenvalues)
|
https://github.com/zapatacomputing/qe-qiskit
|
zapatacomputing
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2018.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Utils for using with Qiskit unit tests."""
import logging
import os
import unittest
from enum import Enum
from qiskit import __path__ as qiskit_path
class Path(Enum):
"""Helper with paths commonly used during the tests."""
# Main SDK path: qiskit/
SDK = qiskit_path[0]
# test.python path: qiskit/test/python/
TEST = os.path.normpath(os.path.join(SDK, '..', 'test', 'python'))
# Examples path: examples/
EXAMPLES = os.path.normpath(os.path.join(SDK, '..', 'examples'))
# Schemas path: qiskit/schemas
SCHEMAS = os.path.normpath(os.path.join(SDK, 'schemas'))
# VCR cassettes path: qiskit/test/cassettes/
CASSETTES = os.path.normpath(os.path.join(TEST, '..', 'cassettes'))
# Sample QASMs path: qiskit/test/python/qasm
QASMS = os.path.normpath(os.path.join(TEST, 'qasm'))
def setup_test_logging(logger, log_level, filename):
"""Set logging to file and stdout for a logger.
Args:
logger (Logger): logger object to be updated.
log_level (str): logging level.
filename (str): name of the output file.
"""
# Set up formatter.
log_fmt = ('{}.%(funcName)s:%(levelname)s:%(asctime)s:'
' %(message)s'.format(logger.name))
formatter = logging.Formatter(log_fmt)
# Set up the file handler.
file_handler = logging.FileHandler(filename)
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)
# Set the logging level from the environment variable, defaulting
# to INFO if it is not a valid level.
level = logging._nameToLevel.get(log_level, logging.INFO)
logger.setLevel(level)
class _AssertNoLogsContext(unittest.case._AssertLogsContext):
"""A context manager used to implement TestCase.assertNoLogs()."""
# pylint: disable=inconsistent-return-statements
def __exit__(self, exc_type, exc_value, tb):
"""
This is a modified version of TestCase._AssertLogsContext.__exit__(...)
"""
self.logger.handlers = self.old_handlers
self.logger.propagate = self.old_propagate
self.logger.setLevel(self.old_level)
if exc_type is not None:
# let unexpected exceptions pass through
return False
if self.watcher.records:
msg = 'logs of level {} or higher triggered on {}:\n'.format(
logging.getLevelName(self.level), self.logger.name)
for record in self.watcher.records:
msg += 'logger %s %s:%i: %s\n' % (record.name, record.pathname,
record.lineno,
record.getMessage())
self._raiseFailure(msg)
|
https://github.com/zapatacomputing/qe-qiskit
|
zapatacomputing
|
from qiskit import Aer, IBMQ, execute
from qiskit import transpile, assemble
from qiskit.tools.monitor import job_monitor
from qiskit.tools.monitor import job_monitor
import matplotlib.pyplot as plt
from qiskit.visualization import plot_histogram, plot_state_city
"""
Qiskit backends to execute the quantum circuit
"""
def simulator(qc):
"""
Run on local simulator
:param qc: quantum circuit
:return:
"""
backend = Aer.get_backend("qasm_simulator")
shots = 2048
tqc = transpile(qc, backend)
qobj = assemble(tqc, shots=shots)
job_sim = backend.run(qobj)
qc_results = job_sim.result()
return qc_results, shots
def simulator_state_vector(qc):
"""
Select the StatevectorSimulator from the Aer provider
:param qc: quantum circuit
:return:
statevector
"""
simulator = Aer.get_backend('statevector_simulator')
# Execute and get counts
result = execute(qc, simulator).result()
state_vector = result.get_statevector(qc)
return state_vector
def real_quantum_device(qc):
"""
Use the IBMQ essex device
:param qc: quantum circuit
:return:
"""
provider = IBMQ.load_account()
backend = provider.get_backend('ibmq_santiago')
shots = 2048
TQC = transpile(qc, backend)
qobj = assemble(TQC, shots=shots)
job_exp = backend.run(qobj)
job_monitor(job_exp)
QC_results = job_exp.result()
return QC_results, shots
def counts(qc_results):
"""
Get counts representing the wave-function amplitudes
:param qc_results:
:return: dict keys are bit_strings and their counting values
"""
return qc_results.get_counts()
def plot_results(qc_results):
"""
Visualizing wave-function amplitudes in a histogram
:param qc_results: quantum circuit
:return:
"""
plt.show(plot_histogram(qc_results.get_counts(), figsize=(8, 6), bar_labels=False))
def plot_state_vector(state_vector):
"""Visualizing state vector in the density matrix representation"""
plt.show(plot_state_city(state_vector))
|
https://github.com/zapatacomputing/qe-qiskit
|
zapatacomputing
|
################################################################################
# © Copyright 2021-2022 Zapata Computing Inc.
################################################################################
import hashlib
from typing import Dict, Iterable, List, NamedTuple, Sequence, Tuple, Union
import numpy as np
import qiskit
import sympy
from orquestra.quantum.circuits import (
_builtin_gates,
_circuit,
_gates,
_operations,
_wavefunction_operations,
)
from orquestra.quantum.circuits.symbolic.sympy_expressions import (
SYMPY_DIALECT,
expression_from_sympy,
)
from orquestra.quantum.circuits.symbolic.translations import translate_expression
from ._qiskit_expressions import QISKIT_DIALECT, expression_from_qiskit
QiskitTriplet = Tuple[
qiskit.circuit.Instruction, List[qiskit.circuit.Qubit], List[qiskit.circuit.Clbit]
]
def _import_qiskit_qubit(qubit: qiskit.circuit.Qubit) -> int:
return qubit._index
def _qiskit_expr_from_orquestra(expr):
intermediate = expression_from_sympy(expr)
return translate_expression(intermediate, QISKIT_DIALECT)
def _orquestra_expr_from_qiskit(expr):
intermediate = expression_from_qiskit(expr)
return translate_expression(intermediate, SYMPY_DIALECT)
ORQUESTRA_QISKIT_GATE_MAP = {
_builtin_gates.X: qiskit.circuit.library.XGate,
_builtin_gates.Y: qiskit.circuit.library.YGate,
_builtin_gates.Z: qiskit.circuit.library.ZGate,
_builtin_gates.S: qiskit.circuit.library.SGate,
_builtin_gates.SX: qiskit.circuit.library.SXGate,
_builtin_gates.T: qiskit.circuit.library.TGate,
_builtin_gates.H: qiskit.circuit.library.HGate,
_builtin_gates.I: qiskit.circuit.library.IGate,
_builtin_gates.CNOT: qiskit.circuit.library.CXGate,
_builtin_gates.CZ: qiskit.circuit.library.CZGate,
_builtin_gates.SWAP: qiskit.circuit.library.SwapGate,
_builtin_gates.ISWAP: qiskit.circuit.library.iSwapGate,
_builtin_gates.RX: qiskit.circuit.library.RXGate,
_builtin_gates.RY: qiskit.circuit.library.RYGate,
_builtin_gates.RZ: qiskit.circuit.library.RZGate,
_builtin_gates.PHASE: qiskit.circuit.library.PhaseGate,
_builtin_gates.CPHASE: qiskit.circuit.library.CPhaseGate,
_builtin_gates.XX: qiskit.circuit.library.RXXGate,
_builtin_gates.YY: qiskit.circuit.library.RYYGate,
_builtin_gates.ZZ: qiskit.circuit.library.RZZGate,
_builtin_gates.U3: qiskit.circuit.library.U3Gate,
_builtin_gates.Delay: qiskit.circuit.Delay,
}
def _make_gate_instance(gate_ref, gate_params) -> _gates.Gate:
"""Returns a gate instance that's applicable to qubits.
For non-parametric gate refs like X, returns just the `X`
For parametric gate factories like `RX`, returns the produced gate, like `RX(0.2)`
"""
if _gates.gate_is_parametric(gate_ref, gate_params):
return gate_ref(*gate_params)
else:
return gate_ref
def _make_controlled_gate_prototype(wrapped_gate_ref, num_control_qubits=1):
def _factory(*gate_params):
return _gates.ControlledGate(
_make_gate_instance(wrapped_gate_ref, gate_params), num_control_qubits
)
return _factory
QISKIT_ORQUESTRA_GATE_MAP = {
**{q_cls: z_ref for z_ref, q_cls in ORQUESTRA_QISKIT_GATE_MAP.items()},
qiskit.extensions.SXdgGate: _builtin_gates.SX.dagger,
qiskit.extensions.SdgGate: _builtin_gates.S.dagger,
qiskit.extensions.TdgGate: _builtin_gates.T.dagger,
qiskit.circuit.library.CSwapGate: _builtin_gates.SWAP.controlled(1),
qiskit.circuit.library.CRXGate: _make_controlled_gate_prototype(_builtin_gates.RX),
qiskit.circuit.library.CRYGate: _make_controlled_gate_prototype(_builtin_gates.RY),
qiskit.circuit.library.CRZGate: _make_controlled_gate_prototype(_builtin_gates.RZ),
}
def export_to_qiskit(circuit: _circuit.Circuit) -> qiskit.QuantumCircuit:
q_circuit = qiskit.QuantumCircuit(circuit.n_qubits)
q_register = qiskit.circuit.QuantumRegister(circuit.n_qubits, "q")
gate_op_only_circuit = _circuit.Circuit(
[op for op in circuit.operations if isinstance(op, _gates.GateOperation)]
)
custom_names = {
gate_def.gate_name
for gate_def in gate_op_only_circuit.collect_custom_gate_definitions()
}
q_triplets = []
for gate_op in circuit.operations:
if isinstance(gate_op, _gates.GateOperation):
q_triplet = _export_gate_to_qiskit(
gate_op.gate,
applied_qubit_indices=gate_op.qubit_indices,
q_register=q_register,
custom_names=custom_names,
)
elif isinstance(gate_op, _wavefunction_operations.ResetOperation):
q_triplet = (
qiskit.circuit.library.Reset(),
[q_register[gate_op.qubit_indices[0]]],
[],
)
q_triplets.append(q_triplet)
for q_gate, q_qubits, q_clbits in q_triplets:
q_circuit.append(q_gate, q_qubits, q_clbits)
return q_circuit
def _export_gate_to_qiskit(gate, applied_qubit_indices, q_register, custom_names):
try:
return _export_gate_via_mapping(
gate, applied_qubit_indices, q_register, custom_names
)
except ValueError:
pass
try:
return _export_dagger_gate(
gate, applied_qubit_indices, q_register, custom_names
)
except ValueError:
pass
try:
return _export_controlled_gate(
gate, applied_qubit_indices, q_register, custom_names
)
except ValueError:
pass
try:
return _export_custom_gate(
gate, applied_qubit_indices, q_register, custom_names
)
except ValueError:
pass
raise NotImplementedError(f"Exporting gate {gate} to Qiskit is unsupported")
def _export_gate_via_mapping(gate, applied_qubit_indices, q_register, custom_names):
try:
qiskit_cls = ORQUESTRA_QISKIT_GATE_MAP[
_builtin_gates.builtin_gate_by_name(gate.name)
]
except KeyError:
raise ValueError(f"Can't export gate {gate} to Qiskit via mapping")
qiskit_params = [_qiskit_expr_from_orquestra(param) for param in gate.params]
qiskit_qubits = [q_register[index] for index in applied_qubit_indices]
return qiskit_cls(*qiskit_params), qiskit_qubits, []
def _export_dagger_gate(
gate: _gates.Dagger,
applied_qubit_indices,
q_register,
custom_names,
):
if not isinstance(gate, _gates.Dagger):
# Raising an exception here is redundant to the type hint, but it allows us
# to handle exporting all gates in the same way, regardless of type
raise ValueError(f"Can't export gate {gate} as a dagger gate")
target_gate, qiskit_qubits, qiskit_clbits = _export_gate_to_qiskit(
gate.wrapped_gate,
applied_qubit_indices=applied_qubit_indices,
q_register=q_register,
custom_names=custom_names,
)
return target_gate.inverse(), qiskit_qubits, qiskit_clbits
def _export_controlled_gate(
gate: _gates.ControlledGate,
applied_qubit_indices,
q_register,
custom_names,
):
if not isinstance(gate, _gates.ControlledGate):
# Raising an exception here is redundant to the type hint, but it allows us
# to handle exporting all gates in the same way, regardless of type
raise ValueError(f"Can't export gate {gate} as a controlled gate")
target_indices = applied_qubit_indices[gate.num_control_qubits :]
target_gate, _, _ = _export_gate_to_qiskit(
gate.wrapped_gate,
applied_qubit_indices=target_indices,
q_register=q_register,
custom_names=custom_names,
)
controlled_gate = target_gate.control(gate.num_control_qubits)
qiskit_qubits = [q_register[index] for index in applied_qubit_indices]
return controlled_gate, qiskit_qubits, []
def _export_custom_gate(
gate: _gates.MatrixFactoryGate,
applied_qubit_indices,
q_register,
custom_names,
):
if gate.name not in custom_names:
raise ValueError(
f"Can't export gate {gate} as a custom gate, the circuit is missing its "
"definition"
)
if gate.params:
raise ValueError(
f"Can't export parametrized gate {gate}, Qiskit doesn't support "
"parametrized custom gates"
)
# At that time of writing it Qiskit doesn't support parametrized gates defined with
# a symbolic matrix.
# See https://github.com/Qiskit/qiskit-terra/issues/4751 for more info.
qiskit_qubits = [q_register[index] for index in applied_qubit_indices]
qiskit_matrix = np.array(gate.matrix)
return (
qiskit.extensions.UnitaryGate(qiskit_matrix, label=gate.name),
qiskit_qubits,
[],
)
class AnonGateOperation(NamedTuple):
gate_name: str
matrix: sympy.Matrix
qubit_indices: Tuple[int, ...]
ImportedOperation = Union[_operations.Operation, AnonGateOperation]
def _apply_custom_gate(
anon_op: AnonGateOperation, custom_defs_map: Dict[str, _gates.CustomGateDefinition]
) -> _gates.GateOperation:
gate_def = custom_defs_map[anon_op.gate_name]
# Qiskit doesn't support custom gates with parametrized matrices
# so we can assume empty params list.
gate_params: Tuple[sympy.Symbol, ...] = tuple()
gate = gate_def(*gate_params)
return gate(*anon_op.qubit_indices)
def import_from_qiskit(circuit: qiskit.QuantumCircuit) -> _circuit.Circuit:
q_ops = [_import_qiskit_triplet(triplet) for triplet in circuit.data]
anon_ops = [op for op in q_ops if isinstance(op, AnonGateOperation)]
# Qiskit doesn't support custom gates with parametrized matrices
# so we can assume empty params list.
params_ordering: Tuple[sympy.Symbol, ...] = tuple()
custom_defs = {
anon_op.gate_name: _gates.CustomGateDefinition(
gate_name=anon_op.gate_name,
matrix=anon_op.matrix,
params_ordering=params_ordering,
)
for anon_op in anon_ops
}
imported_ops = [
_apply_custom_gate(op, custom_defs) if isinstance(op, AnonGateOperation) else op
for op in q_ops
]
return _circuit.Circuit(
operations=imported_ops,
n_qubits=circuit.num_qubits,
)
def _import_qiskit_triplet(qiskit_triplet: QiskitTriplet) -> ImportedOperation:
qiskit_op, qiskit_qubits, _ = qiskit_triplet
return _import_qiskit_op(qiskit_op, qiskit_qubits)
def _import_qiskit_op(qiskit_op, qiskit_qubits) -> ImportedOperation:
# We always wanna try importing via mapping to handle complex gate structures
# represented by a single class, like CNOT (Control + X) or CSwap (Control + Swap).
try:
return _import_qiskit_op_via_mapping(qiskit_op, qiskit_qubits)
except ValueError:
pass
try:
return _import_controlled_qiskit_op(qiskit_op, qiskit_qubits)
except ValueError:
pass
try:
return _import_custom_qiskit_gate(qiskit_op, qiskit_qubits)
except AttributeError:
raise ValueError(f"Conversion of {qiskit_op.name} from Qiskit is unsupported.")
def _import_qiskit_op_via_mapping(
qiskit_gate: qiskit.circuit.Instruction,
qiskit_qubits: Iterable[qiskit.circuit.Qubit],
) -> _operations.Operation:
qubit_indices = [_import_qiskit_qubit(qubit) for qubit in qiskit_qubits]
if isinstance(qiskit_gate, qiskit.circuit.library.Reset):
return _wavefunction_operations.ResetOperation(qubit_indices[0])
try:
gate_ref = QISKIT_ORQUESTRA_GATE_MAP[type(qiskit_gate)]
except KeyError:
raise ValueError(f"Conversion of {qiskit_gate} from Qiskit is unsupported.")
# values to consider:
# - gate matrix parameters (only parametric gates)
# - gate application indices (all gates)
orquestra_params = [
_orquestra_expr_from_qiskit(param) for param in qiskit_gate.params
]
gate = _make_gate_instance(gate_ref, orquestra_params)
return _gates.GateOperation(gate=gate, qubit_indices=tuple(qubit_indices))
def _import_controlled_qiskit_op(
qiskit_gate: qiskit.circuit.ControlledGate,
qiskit_qubits: Sequence[qiskit.circuit.Qubit],
) -> _gates.GateOperation:
if not isinstance(qiskit_gate, qiskit.circuit.ControlledGate):
# Raising an exception here is redundant to the type hint, but it allows us
# to handle exporting all gates in the same way, regardless of type
raise ValueError(f"Can't import gate {qiskit_gate} as a controlled gate")
wrapped_qubits = qiskit_qubits[qiskit_gate.num_ctrl_qubits :]
wrapped_op = _import_qiskit_op(qiskit_gate.base_gate, wrapped_qubits)
qubit_indices = map(_import_qiskit_qubit, qiskit_qubits)
if isinstance(wrapped_op, _gates.GateOperation):
return wrapped_op.gate.controlled(qiskit_gate.num_ctrl_qubits)(*qubit_indices)
else:
raise NotImplementedError(
"Importing of controlled anonymous gates not yet supported."
)
def _hash_hex(bytes_):
return hashlib.sha256(bytes_).hexdigest()
def _custom_qiskit_gate_name(gate_label: str, gate_name: str, matrix: np.ndarray):
matrix_hash = _hash_hex(matrix.tobytes())
target_name = gate_label or gate_name
return f"{target_name}.{matrix_hash}"
def _import_custom_qiskit_gate(
qiskit_op: qiskit.circuit.Gate, qiskit_qubits: Iterable[qiskit.circuit.Qubit]
) -> AnonGateOperation:
value_matrix = qiskit_op.to_matrix()
return AnonGateOperation(
gate_name=_custom_qiskit_gate_name(
qiskit_op.label, qiskit_op.name, value_matrix
),
matrix=sympy.Matrix(value_matrix),
qubit_indices=tuple(_import_qiskit_qubit(qubit) for qubit in qiskit_qubits),
)
|
https://github.com/zapatacomputing/qe-qiskit
|
zapatacomputing
|
################################################################################
# © Copyright 2021-2022 Zapata Computing Inc.
################################################################################
"""Translations between Qiskit parameter expressions and intermediate expression trees.
"""
import operator
from functools import lru_cache, reduce, singledispatch
from numbers import Number
import qiskit
from orquestra.quantum.circuits.symbolic.expressions import ExpressionDialect, reduction
from orquestra.quantum.circuits.symbolic.sympy_expressions import expression_from_sympy
from ._symengine_expressions import expression_from_symengine
@singledispatch
def expression_from_qiskit(expression):
"""Parse Qiskit expression into intermediate expression tree."""
raise NotImplementedError(
f"Expression {expression} of type {type(expression)} is currently not supported"
)
@expression_from_qiskit.register
def _number_identity(number: Number):
return number
@expression_from_qiskit.register
def _expr_from_qiskit_param_expr(
qiskit_expr: qiskit.circuit.parameterexpression.ParameterExpression,
):
# At the moment of writing this the qiskit version that we use (0.23.2) as well
# as the newest version 0.23.5) does not provide a better way to access symbolic
# expression wrapped by ParameterExpression.
inner_expr = qiskit_expr._symbol_expr
try:
return expression_from_symengine(inner_expr)
except NotImplementedError:
return expression_from_sympy(inner_expr)
def integer_pow(base, exponent: int):
"""Exponentiation to the power of an integer exponent."""
if not isinstance(exponent, int):
raise ValueError(
f"Cannot convert expression {base} ** {exponent} to Qiskit. "
"Only powers with integral exponent are convertible."
)
if exponent < 0:
if base != 0:
base = 1 / base
exponent = -exponent
else:
raise ValueError(
f"Invalid power: cannot raise 0 to exponent {exponent} < 0."
)
return reduce(operator.mul, exponent * [base], 1)
@lru_cache(maxsize=None)
def _qiskit_param_from_name(name):
return qiskit.circuit.Parameter(name)
QISKIT_DIALECT = ExpressionDialect(
symbol_factory=lambda symbol: _qiskit_param_from_name(symbol.name),
number_factory=lambda number: number,
known_functions={
"add": reduction(operator.add),
"mul": reduction(operator.mul),
"div": operator.truediv,
"sub": operator.sub,
"pow": integer_pow,
},
)
"""Mapping from the intermediate expression tree into Qiskit symbolic expression atoms.
Allows translating an expression into the Qiskit dialect. Can be used with
`orquestra.quantum.circuits.symbolic.translations.translate_expression`.
"""
|
https://github.com/zapatacomputing/qe-qiskit
|
zapatacomputing
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
# pylint: disable=wrong-import-order
"""Main Qiskit public functionality."""
import pkgutil
# First, check for required Python and API version
from . import util
# qiskit errors operator
from .exceptions import QiskitError
# The main qiskit operators
from qiskit.circuit import ClassicalRegister
from qiskit.circuit import QuantumRegister
from qiskit.circuit import QuantumCircuit
# pylint: disable=redefined-builtin
from qiskit.tools.compiler import compile # TODO remove after 0.8
from qiskit.execute import execute
# The qiskit.extensions.x imports needs to be placed here due to the
# mechanism for adding gates dynamically.
import qiskit.extensions
import qiskit.circuit.measure
import qiskit.circuit.reset
# Allow extending this namespace. Please note that currently this line needs
# to be placed *before* the wrapper imports or any non-import code AND *before*
# importing the package you want to allow extensions for (in this case `backends`).
__path__ = pkgutil.extend_path(__path__, __name__)
# Please note these are global instances, not modules.
from qiskit.providers.basicaer import BasicAer
# Try to import the Aer provider if installed.
try:
from qiskit.providers.aer import Aer
except ImportError:
pass
# Try to import the IBMQ provider if installed.
try:
from qiskit.providers.ibmq import IBMQ
except ImportError:
pass
from .version import __version__
from .version import __qiskit_version__
|
https://github.com/zapatacomputing/qe-qiskit
|
zapatacomputing
|
################################################################################
# © Copyright 2020-2022 Zapata Computing Inc.
################################################################################
from typing import Dict, Optional, Tuple
import numpy as np
import qiskit.providers.aer.noise as AerNoise
from qiskit.providers.aer.noise import (
NoiseModel,
amplitude_damping_error,
pauli_error,
phase_amplitude_damping_error,
phase_damping_error,
)
from qiskit.quantum_info import Kraus
from qiskit.transpiler import CouplingMap
from .._get_provider import get_provider
def get_qiskit_noise_model(
device_name: str,
hub: str = "ibm-q",
group: str = "open",
project: str = "main",
api_token: Optional[str] = None,
) -> Tuple[NoiseModel, list]:
"""Get a qiskit noise model to use noisy simulations with a qiskit simulator
Args:
device_name: The name of the device trying to be emulated
hub: The ibmq hub (see qiskit documentation)
group: The ibmq group (see qiskit documentation)
project: The ibmq project (see qiskit documentation)
api_token: The ibmq api token (see qiskit documentation)
"""
# Get qiskit noise model from qiskit
provider = get_provider(api_token=api_token, hub=hub, group=group, project=project)
noisy_device = provider.get_backend(device_name)
noise_model = AerNoise.NoiseModel.from_backend(noisy_device)
return noise_model, noisy_device.configuration().coupling_map
def create_amplitude_damping_noise(T_1: float, t_step: float = 10e-9) -> NoiseModel:
"""Creates an amplitude damping noise model
Args:
T_1: Relaxation time (seconds)
t_step: Discretized time step over which the relaxation occurs over (seconds)
"""
gamma = 1 - pow(np.e, -1 / T_1 * t_step)
error = amplitude_damping_error(gamma)
gate_error = error.tensor(error)
noise_model = NoiseModel()
noise_model.add_all_qubit_quantum_error(error, ["id", "u3"])
noise_model.add_all_qubit_quantum_error(gate_error, ["cx"])
return noise_model
def create_phase_damping_noise(T_2: float, t_step: float = 10e-9) -> NoiseModel:
"""Creates a dephasing noise model
Args:
T_2: dephasing time (seconds)
t_step: Discretized time step over which the relaxation occurs over (seconds)
"""
gamma = 1 - pow(np.e, -1 / T_2 * t_step)
error = phase_damping_error(gamma)
gate_error = error.tensor(error)
noise_model = NoiseModel()
noise_model.add_all_qubit_quantum_error(error, ["id", "u3"])
noise_model.add_all_qubit_quantum_error(gate_error, ["cx"])
return noise_model
def create_phase_and_amplitude_damping_error(
T_1: float, T_2: float, t_step: float = 10e-9
) -> NoiseModel:
"""Creates a noise model that does both phase and amplitude damping
Args:
T_1: Relaxation time (seconds)
T_2: dephasing time (seonds)
t_step: Discretized time step over which the relaxation occurs over (seconds)
"""
param_amp = 1 - pow(np.e, -1 / T_1 * t_step)
param_phase = 1 - pow(np.e, -1 / T_2 * t_step)
error = phase_amplitude_damping_error(param_amp, param_phase)
gate_error = error.tensor(error)
noise_model = NoiseModel()
noise_model.add_all_qubit_quantum_error(error, ["id", "u3"])
noise_model.add_all_qubit_quantum_error(gate_error, ["cx"])
return noise_model
def create_pta_channel(T_1: float, T_2: float, t_step: float = 10e-9) -> NoiseModel:
"""Creates a noise model that does both phase and amplitude damping but in the
Pauli Twirling Approximation discussed the following reference
https://arxiv.org/pdf/1305.2021.pdf
Args:
T_1: Relaxation time (seconds)
T_2: dephasing time (seconds)
t_step: Discretized time step over which the relaxation occurs over (seconds)
"""
p_x = 0.25 * (1 - pow(np.e, -t_step / T_1))
p_y = 0.25 * (1 - pow(np.e, -t_step / T_1))
exp_1 = pow(np.e, -t_step / (2 * T_1))
exp_2 = pow(np.e, -t_step / T_2)
p_z = 0.5 - p_x - 0.5 * exp_1 * exp_2
p_i = 1 - p_x - p_y - p_z
errors = [("X", p_x), ("Y", p_y), ("Z", p_z), ("I", p_i)]
pta_error = pauli_error(errors)
noise_model = NoiseModel()
noise_model.add_all_qubit_quantum_error(pta_error, ["id", "u3"])
gate_error = pta_error.tensor(pta_error)
noise_model.add_all_qubit_quantum_error(gate_error, ["cx"])
return noise_model
def get_kraus_matrices_from_ibm_noise_model(noise_model: NoiseModel) -> Dict:
"""Gets the kraus operators from a pre defined noise model
Args:
noise_model: Noise model for circuit
Return
dict_of_kraus_operators: A dictionary labelled by keys which are
the basis gates and values are the list of kraus operators
"""
retrieved_quantum_error_dict = noise_model._default_quantum_errors
dict_of_kraus_operators = {
gate: Kraus(retrieved_quantum_error_dict[gate]).data
for gate in retrieved_quantum_error_dict
}
return dict_of_kraus_operators
|
https://github.com/zapatacomputing/qe-qiskit
|
zapatacomputing
|
from qiskit import QuantumCircuit, Aer, execute
from qiskit.visualization import plot_histogram
# simulate in statevector_simulator
def simulateStatevector(circuit):
backend = Aer.get_backend('statevector_simulator')
result = execute(circuit.remove_final_measurements(inplace=False), backend, shots=1).result()
counts = result.get_counts()
return result.get_statevector(circuit)
# return plot_histogram(counts, color='midnightblue', title="StateVector Histogram")
# simulate in qasm_simulator
def simulateQasm(circuit, count=1024):
backend = Aer.get_backend('qasm_simulator')
result = execute(circuit, backend, shots=count).result()
counts = result.get_counts()
return plot_histogram(counts, color='midnightblue', title="Qasm Histogram")
|
https://github.com/zapatacomputing/qe-qiskit
|
zapatacomputing
|
################################################################################
# © Copyright 2021 Zapata Computing Inc.
################################################################################
import json
import os
import subprocess
import unittest
import numpy as np
import qiskit.providers.aer.noise as AerNoise
from qeqiskit.noise.basic import (
create_amplitude_damping_noise,
get_kraus_matrices_from_ibm_noise_model,
)
from qeqiskit.utils import (
load_qiskit_noise_model,
save_kraus_operators,
save_qiskit_noise_model,
)
from zquantum.core.utils import load_noise_model, save_noise_model
class TestQiskitUtils(unittest.TestCase):
def setUp(self):
self.T_1 = 10e-7
self.t_step = 10e-9
def test_save_qiskit_noise_model(self):
# Given
noise_model = AerNoise.NoiseModel()
coherent_error = np.asarray(
[
np.asarray(
[0.87758256 - 0.47942554j, 0.0 + 0.0j, 0.0 + 0.0j, 0.0 + 0.0j]
),
np.asarray(
[0.0 + 0.0j, 0.87758256 + 0.47942554j, 0.0 + 0.0j, 0.0 + 0.0j]
),
np.asarray(
[0.0 + 0.0j, 0.0 + 0.0j, 0.87758256 + 0.47942554j, 0.0 + 0.0j]
),
np.asarray(
[0.0 + 0.0j, 0.0 + 0.0j, 0.0 + 0.0j, 0.87758256 - 0.47942554j]
),
]
)
noise_model.add_quantum_error(
AerNoise.coherent_unitary_error(coherent_error), ["cx"], [0, 1]
)
filename = "noise_model.json"
# When
save_qiskit_noise_model(noise_model, filename)
# Then
with open("noise_model.json", "r") as f:
data = json.loads(f.read())
self.assertEqual(data["module_name"], "qeqiskit.utils")
self.assertEqual(data["function_name"], "load_qiskit_noise_model")
self.assertIsInstance(data["data"], dict)
# Cleanup
subprocess.run(["rm", "noise_model.json"])
def test_noise_model_io_using_core_functions(self):
# Given
noise_model = AerNoise.NoiseModel()
coherent_error = np.asarray(
[
np.asarray(
[0.87758256 - 0.47942554j, 0.0 + 0.0j, 0.0 + 0.0j, 0.0 + 0.0j]
),
np.asarray(
[0.0 + 0.0j, 0.87758256 + 0.47942554j, 0.0 + 0.0j, 0.0 + 0.0j]
),
np.asarray(
[0.0 + 0.0j, 0.0 + 0.0j, 0.87758256 + 0.47942554j, 0.0 + 0.0j]
),
np.asarray(
[0.0 + 0.0j, 0.0 + 0.0j, 0.0 + 0.0j, 0.87758256 - 0.47942554j]
),
]
)
noise_model.add_quantum_error(
AerNoise.coherent_unitary_error(coherent_error), ["cx"], [0, 1]
)
noise_model_data = noise_model.to_dict(serializable=True)
module_name = "qeqiskit.utils"
function_name = "load_qiskit_noise_model"
filename = "noise_model.json"
# When
save_noise_model(noise_model_data, module_name, function_name, filename)
new_noise_model = load_noise_model(filename)
# Then
self.assertEqual(
noise_model.to_dict(serializable=True),
new_noise_model.to_dict(serializable=True),
)
# Cleanup
subprocess.run(["rm", "noise_model.json"])
def test_save_kraus_operators(self):
noise_model = create_amplitude_damping_noise(self.T_1, self.t_step)
kraus_dict = get_kraus_matrices_from_ibm_noise_model(noise_model)
save_kraus_operators(kraus_dict, "kraus_operators.json")
# Cleanup
os.remove("kraus_operators.json")
|
https://github.com/zapatacomputing/qe-qiskit
|
zapatacomputing
|
################################################################################
# © Copyright 2021-2022 Zapata Computing Inc.
################################################################################
import math
import os
from copy import deepcopy
import pytest
import qiskit
from qeqiskit.backend import QiskitBackend
from qeqiskit.conversions import export_to_qiskit
from qiskit.providers.exceptions import QiskitBackendNotFoundError
from zquantum.core.circuits import CNOT, Circuit, X
from zquantum.core.interfaces.backend_test import QuantumBackendTests
from zquantum.core.measurement import Measurements
@pytest.fixture(
params=[
{
"device_name": "ibmq_qasm_simulator",
"api_token": os.getenv("ZAPATA_IBMQ_API_TOKEN"),
"retry_delay_seconds": 1,
},
]
)
def backend(request):
return QiskitBackend(**request.param)
@pytest.fixture(
params=[
{
"device_name": "ibmq_qasm_simulator",
"api_token": os.getenv("ZAPATA_IBMQ_API_TOKEN"),
"readout_correction": True,
"n_samples_for_readout_calibration": 1,
"retry_delay_seconds": 1,
},
{
"device_name": "ibmq_qasm_simulator",
"api_token": os.getenv("ZAPATA_IBMQ_API_TOKEN"),
"readout_correction": True,
"n_samples_for_readout_calibration": 1,
"retry_delay_seconds": 1,
"noise_inversion_method": "pseudo_inverse",
},
],
)
def backend_with_readout_correction(request):
return QiskitBackend(**request.param)
class TestQiskitBackend(QuantumBackendTests):
def x_cnot_circuit(self):
return Circuit([X(0), CNOT(1, 2)])
def x_circuit(self):
return Circuit([X(0)])
def test_transform_circuitset_to_ibmq_experiments(self, backend):
circuit = self.x_cnot_circuit()
circuitset = (circuit,) * 2
n_samples = [backend.max_shots + 1] * 2
(
experiments,
n_samples_for_experiments,
multiplicities,
) = backend.transform_circuitset_to_ibmq_experiments(circuitset, n_samples)
assert multiplicities == [2, 2]
assert n_samples_for_experiments == [
backend.max_shots,
1,
backend.max_shots,
1,
]
assert len(set([circuit.name for circuit in experiments])) == 4
def test_batch_experiments(self, backend):
circuit = self.x_cnot_circuit()
n_circuits = backend.batch_size + 1
experiments = (export_to_qiskit(circuit),) * n_circuits
n_samples_for_ibmq_circuits = (10,) * n_circuits
batches, n_samples_for_batches = backend.batch_experiments(
experiments, n_samples_for_ibmq_circuits
)
assert len(batches) == 2
assert len(batches[0]) == backend.batch_size
assert len(batches[1]) == 1
assert n_samples_for_batches == [10, 10]
def test_aggregate_measurements(self, backend):
multiplicities = [3, 1]
circuit = export_to_qiskit(self.x_cnot_circuit())
circuit.barrier(range(3))
circuit.add_register(qiskit.ClassicalRegister(3))
circuit.measure(range(3), range(3))
batches = [
[circuit.copy("circuit1"), circuit.copy("circuit2")],
[circuit.copy("circuit3"), circuit.copy("circuit4")],
]
jobs = [
backend.execute_with_retries(
batch,
10,
)
for batch in batches
]
measurements_set = backend.aggregate_measurements(
jobs,
batches,
multiplicities,
)
assert (
measurements_set[0].bitstrings
== [
(1, 0, 0),
]
* 30
)
assert (
measurements_set[1].bitstrings
== [
(1, 0, 0),
]
* 10
)
assert len(measurements_set) == 2
def test_run_circuitset_and_measure(self, backend):
# Given
num_circuits = 10
circuit = self.x_circuit()
n_samples = 100
# When
measurements_set = backend.run_circuitset_and_measure(
[circuit] * num_circuits, [n_samples] * num_circuits
)
# Then
assert len(measurements_set) == num_circuits
for measurements in measurements_set:
assert len(measurements.bitstrings) == n_samples
counts = measurements.get_counts()
assert max(counts, key=counts.get) == "1"
def test_execute_with_retries(self, backend):
# This test has a race condition where the IBMQ server might finish
# executing the first job before the last one is submitted. The test
# will still pass in the case, but will not actually perform a retry.
# We can address in the future by using a mock provider.
# Given
circuit = export_to_qiskit(self.x_circuit())
n_samples = 10
num_jobs = backend.device.job_limit().maximum_jobs + 1
# When
jobs = [
backend.execute_with_retries([circuit], n_samples) for _ in range(num_jobs)
]
# Then
# The correct number of jobs were submitted
assert len(jobs) == num_jobs
# Each job has a unique ID
assert len(set([job.job_id() for job in jobs])) == num_jobs
def test_execute_with_retries_timeout(self, backend):
# This test has a race condition where the IBMQ server might finish
# executing the first job before the last one is submitted, causing the
# test to fail. We can address this in the future using a mock provider.
# Given
circuit = export_to_qiskit(self.x_cnot_circuit())
n_samples = 10
backend.retry_timeout_seconds = 0
# need large number here as + 1 was not enough
num_jobs = backend.device.job_limit().maximum_jobs + int(10e20)
# Then
with pytest.raises(RuntimeError):
# When
for _ in range(num_jobs):
backend.execute_with_retries([circuit], n_samples)
@pytest.mark.skip(reason="test will always succeed.")
def test_run_circuitset_and_measure_readout_correction_retries(
self, backend_with_readout_correction
):
# This test has a race condition where the IBMQ server might finish
# executing the first job before the last one is submitted. The test
# will still pass in the case, but will not actually perform a retry.
# We can address in the future by using a mock provider.
# Given
circuit = self.x_cnot_circuit()
n_samples = 10
num_circuits = (
backend_with_readout_correction.batch_size
* backend_with_readout_correction.device.job_limit().maximum_jobs
+ 1
)
# When
measurements_set = backend_with_readout_correction.run_circuitset_and_measure(
[circuit] * num_circuits, [n_samples] * num_circuits
)
# Then
assert len(measurements_set) == num_circuits
def test_run_circuitset_and_measure_split_circuits_and_jobs(self, backend):
# Given
num_circuits = 2 # Minimum number of circuits to require batching
circuit = self.x_cnot_circuit()
n_samples = backend.max_shots + 1
backend.batch_size = 2
# Verify that we are actually going to need multiple batches
assert (
num_circuits * math.ceil(n_samples / backend.max_shots) > backend.batch_size
)
# When
measurements_set = backend.run_circuitset_and_measure(
[circuit] * num_circuits, [n_samples] * num_circuits
)
# Then
assert len(measurements_set) == num_circuits
for measurements in measurements_set:
assert len(measurements.bitstrings) == n_samples or len(
measurements.bitstrings
) == backend.max_shots * math.ceil(n_samples / backend.max_shots)
# Then (since SPAM error could result in unexpected bitstrings, we make sure
# the most common bitstring is the one we expect)
counts = measurements.get_counts()
assert max(counts, key=counts.get) == "100"
def test_readout_correction_works_run_circuit_and_measure(
self, backend_with_readout_correction
):
# Given
circuit = self.x_cnot_circuit()
# When
backend_with_readout_correction.run_circuit_and_measure(circuit, n_samples=1)
# Then
assert backend_with_readout_correction.readout_correction
assert backend_with_readout_correction.readout_correction_filters is not None
def test_readout_correction_for_distributed_circuit(
self, backend_with_readout_correction
):
# Given
num_circuits = 10
circuit = self.x_circuit() + X(5)
n_samples = 100
# When
measurements_set = backend_with_readout_correction.run_circuitset_and_measure(
[circuit] * num_circuits, [n_samples] * num_circuits
)
# Then
assert backend_with_readout_correction.readout_correction
assert (
backend_with_readout_correction.readout_correction_filters.get(str([0, 5]))
is not None
)
assert len(measurements_set) == num_circuits
for measurements in measurements_set:
assert len(measurements.bitstrings) == n_samples
counts = measurements.get_counts()
assert max(counts, key=counts.get) == "11"
@pytest.mark.parametrize(
"counts, active_qubits",
[
({"100000000000000000001": 10}, [0, 20]),
({"100000000000000000100": 10}, [0, 18, 20]),
({"001000000000000000001": 10}, [2, 20]),
],
)
def test_subset_readout_correction(
self, counts, active_qubits, backend_with_readout_correction
):
# Given
copied_counts = deepcopy(counts)
# When
mitigated_counts = backend_with_readout_correction._apply_readout_correction(
copied_counts, active_qubits
)
# Then
assert backend_with_readout_correction.readout_correction
assert backend_with_readout_correction.readout_correction_filters.get(
str(active_qubits)
)
assert copied_counts == pytest.approx(mitigated_counts, 10e-5)
def test_subset_readout_correction_with_unspecified_active_qubits(
self, backend_with_readout_correction
):
# Given
counts = {"11": 10}
# When
mitigated_counts = backend_with_readout_correction._apply_readout_correction(
counts
)
# Then
assert backend_with_readout_correction.readout_correction
assert backend_with_readout_correction.readout_correction_filters.get(
str([0, 1])
)
assert counts == pytest.approx(mitigated_counts, 10e-5)
def test_must_define_n_samples_for_readout_calibration_for_readout_correction(
self, backend_with_readout_correction
):
# Given
counts, active_qubits = ({"11": 10}, None)
backend_with_readout_correction.n_samples_for_readout_calibration = None
# When/Then
with pytest.raises(TypeError):
backend_with_readout_correction._apply_readout_correction(
counts, active_qubits
)
def test_subset_readout_correction_for_multiple_subsets(
self, backend_with_readout_correction
):
# Given
counts_1, active_qubits_1 = ({"100000000000000000001": 10}, [0, 20])
counts_2, active_qubits_2 = ({"001000000000000000001": 10}, [2, 20])
# When
mitigated_counts_1 = backend_with_readout_correction._apply_readout_correction(
counts_1, active_qubits_1
)
mitigated_counts_2 = backend_with_readout_correction._apply_readout_correction(
counts_2, active_qubits_2
)
# Then
assert backend_with_readout_correction.readout_correction
assert backend_with_readout_correction.readout_correction_filters.get(
str(active_qubits_1)
)
assert backend_with_readout_correction.readout_correction_filters.get(
str(active_qubits_2)
)
assert counts_1 == pytest.approx(mitigated_counts_1, 10e-5)
assert counts_2 == pytest.approx(mitigated_counts_2, 10e-5)
def test_device_that_does_not_exist(self):
# Given/When/Then
with pytest.raises(QiskitBackendNotFoundError):
QiskitBackend("DEVICE DOES NOT EXIST")
def test_run_circuitset_and_measure_n_samples(self, backend):
# We override the base test because the qiskit integration may return
# more samples than requested due to the fact that each circuit in a
# batch must have the same number of measurements.
# Given
backend.number_of_circuits_run = 0
backend.number_of_jobs_run = 0
first_circuit = Circuit(
[
X(0),
X(0),
X(1),
X(1),
X(2),
]
)
second_circuit = Circuit(
[
X(0),
X(1),
X(2),
]
)
n_samples = [2, 3]
# When
measurements_set = backend.run_circuitset_and_measure(
[first_circuit, second_circuit], n_samples
)
counts = measurements_set[0].get_counts()
assert max(counts, key=counts.get) == "001"
counts = measurements_set[1].get_counts()
assert max(counts, key=counts.get) == "111"
assert len(measurements_set[0].bitstrings) >= n_samples[0]
assert len(measurements_set[1].bitstrings) >= n_samples[1]
assert backend.number_of_circuits_run == 2
@pytest.mark.parametrize("n_samples", [1, 2, 10])
def test_run_circuit_and_measure_correct_num_measurements_attribute(
self, backend, n_samples
):
# Overriding to reduce number of samples required
# Given
backend.number_of_circuits_run = 0
backend.number_of_jobs_run = 0
circuit = self.x_cnot_circuit()
# When
measurements = backend.run_circuit_and_measure(circuit, n_samples)
# Then
assert isinstance(measurements, Measurements)
assert len(measurements.bitstrings) == n_samples
assert backend.number_of_circuits_run == 1
assert backend.number_of_jobs_run == 1
def test_run_circuit_and_measure_correct_indexing(self, backend):
# Overriding to reduce number of samples required
# Given
backend.number_of_circuits_run = 0
backend.number_of_jobs_run = 0
circuit = self.x_cnot_circuit()
n_samples = 2 # qiskit only runs simulators, so we can use low n_samples
measurements = backend.run_circuit_and_measure(circuit, n_samples)
counts = measurements.get_counts()
assert max(counts, key=counts.get) == "100"
assert backend.number_of_circuits_run == 1
assert backend.number_of_jobs_run == 1
|
https://github.com/zapatacomputing/qe-qiskit
|
zapatacomputing
|
################################################################################
# © Copyright 2021-2022 Zapata Computing Inc.
################################################################################
import numpy as np
import pytest
import qiskit
import qiskit.circuit.random
import sympy
from orquestra.quantum.circuits import (
_builtin_gates,
_circuit,
_gates,
_wavefunction_operations,
)
from orquestra.integrations.qiskit.conversions import (
export_to_qiskit,
import_from_qiskit,
)
# --------- gates ---------
EQUIVALENT_NON_PARAMETRIC_GATES = [
(_builtin_gates.X, qiskit.circuit.library.XGate()),
(_builtin_gates.Y, qiskit.circuit.library.YGate()),
(_builtin_gates.Z, qiskit.circuit.library.ZGate()),
(_builtin_gates.H, qiskit.circuit.library.HGate()),
(_builtin_gates.I, qiskit.circuit.library.IGate()),
(_builtin_gates.S, qiskit.circuit.library.SGate()),
(_builtin_gates.SX, qiskit.circuit.library.SXGate()),
(_builtin_gates.T, qiskit.circuit.library.TGate()),
(_builtin_gates.CNOT, qiskit.circuit.library.CXGate()),
(_builtin_gates.CZ, qiskit.circuit.library.CZGate()),
(_builtin_gates.SWAP, qiskit.circuit.library.SwapGate()),
(_builtin_gates.ISWAP, qiskit.circuit.library.iSwapGate()),
(_builtin_gates.S.dagger, qiskit.circuit.library.SdgGate()),
(_builtin_gates.T.dagger, qiskit.circuit.library.TdgGate()),
]
EQUIVALENT_PARAMETRIC_GATES = [
(orquestra_cls(theta), qiskit_cls(theta))
for orquestra_cls, qiskit_cls in [
(_builtin_gates.RX, qiskit.circuit.library.RXGate),
(_builtin_gates.RY, qiskit.circuit.library.RYGate),
(_builtin_gates.RZ, qiskit.circuit.library.RZGate),
(_builtin_gates.PHASE, qiskit.circuit.library.PhaseGate),
(_builtin_gates.CPHASE, qiskit.circuit.library.CPhaseGate),
(_builtin_gates.XX, qiskit.circuit.library.RXXGate),
(_builtin_gates.YY, qiskit.circuit.library.RYYGate),
(_builtin_gates.ZZ, qiskit.circuit.library.RZZGate),
]
for theta in [0, -1, np.pi / 5, 2 * np.pi]
]
TWO_QUBIT_SWAP_MATRIX = np.array(
[
[1, 0, 0, 0],
[0, 0, 1, 0],
[0, 1, 0, 0],
[0, 0, 0, 1],
]
)
def _fix_qubit_ordering(qiskit_matrix):
"""Import qiskit matrix to Orquestra matrix convention.
Qiskit uses different qubit ordering than we do.
It causes multi-qubit matrices to look different on first sight."""
if len(qiskit_matrix) == 2:
return qiskit_matrix
if len(qiskit_matrix) == 4:
return TWO_QUBIT_SWAP_MATRIX @ qiskit_matrix @ TWO_QUBIT_SWAP_MATRIX
else:
raise ValueError(f"Unsupported matrix size: {len(qiskit_matrix)}")
class TestGateConversion:
@pytest.mark.parametrize(
"orquestra_gate,qiskit_gate",
[
*EQUIVALENT_NON_PARAMETRIC_GATES,
*EQUIVALENT_PARAMETRIC_GATES,
],
)
def test_matrices_are_equal(self, orquestra_gate, qiskit_gate):
orquestra_matrix = np.array(orquestra_gate.matrix).astype(np.complex128)
qiskit_matrix = _fix_qubit_ordering(qiskit_gate.to_matrix())
np.testing.assert_allclose(orquestra_matrix, qiskit_matrix)
class TestU3GateConversion:
@pytest.mark.parametrize(
"theta, phi, lambda_",
[
(0, 0, 0),
(0, np.pi / 5, 0),
(np.pi / 3, 0, 0),
(0, 0, np.pi / 7),
(42, -20, 30),
],
)
def test_matrices_are_equal_up_to_phase_factor(self, theta, phi, lambda_):
orquestra_matrix = np.array(
_builtin_gates.U3(theta, phi, lambda_).matrix
).astype(np.complex128)
qiskit_matrix = qiskit.circuit.library.U3Gate(theta, phi, lambda_).to_matrix()
np.testing.assert_allclose(orquestra_matrix, qiskit_matrix, atol=1e-7)
class TestCU3GateConversion:
@pytest.mark.parametrize(
"theta, phi, lambda_",
[
(0, 0, 0),
(0, np.pi / 5, 0),
(np.pi / 3, 0, 0),
(0, 0, np.pi / 7),
(42, -20, 30),
],
)
def test_matrices_are_equal_up_to_phase_factor(self, theta, phi, lambda_):
orquestra_matrix = np.array(
_builtin_gates.U3(theta, phi, lambda_).controlled(1)(0, 1).lifted_matrix(2)
).astype(np.complex128)
qiskit_matrix = (
qiskit.circuit.library.U3Gate(theta, phi, lambda_).control(1).to_matrix()
)
# Rearrange the qiskit matrix, such that it matches the endianness of orquestra
qiskit_matrix_reversed_control = _fix_qubit_ordering(qiskit_matrix)
np.testing.assert_allclose(
orquestra_matrix, qiskit_matrix_reversed_control, atol=1e-7
)
# --------- circuits ---------
# NOTE: In Qiskit, 0 is the most significant qubit,
# whereas in Orquestra, 0 is the least significant qubit.
# Thus, we need to flip the indices.
#
# See more at
# https://qiskit.org/documentation/tutorials/circuits/1_getting_started_with_qiskit.html#Visualize-Circuit
def _make_qiskit_circuit(n_qubits, commands, n_cbits=0):
qc = qiskit.QuantumCircuit(n_qubits, n_cbits)
for method_name, method_args in commands:
method = getattr(qc, method_name)
method(*method_args)
return qc
SYMPY_THETA = sympy.Symbol("theta")
SYMPY_GAMMA = sympy.Symbol("gamma")
SYMPY_LAMBDA = sympy.Symbol("lambda_")
SYMPY_PARAMETER_VECTOR = [sympy.Symbol("p[0]"), sympy.Symbol("p[1]")]
QISKIT_THETA = qiskit.circuit.Parameter("theta")
QISKIT_GAMMA = qiskit.circuit.Parameter("gamma")
QISKIT_LAMBDA = qiskit.circuit.Parameter("lambda_")
QISKIT_PARAMETER_VECTOR = qiskit.circuit.ParameterVector("p", 2)
EXAMPLE_PARAM_VALUES = {
"gamma": 0.3,
"theta": -5,
"lambda_": np.pi / 5,
"p[0]": -5,
"p[1]": 0.3,
}
EQUIVALENT_NON_PARAMETRIZED_CIRCUITS = [
(
_circuit.Circuit([], 3),
_make_qiskit_circuit(3, []),
),
(
_circuit.Circuit(
[
_builtin_gates.X(0),
_builtin_gates.Z(2),
],
6,
),
_make_qiskit_circuit(
6,
[
("x", (0,)),
("z", (2,)),
],
),
),
(
_circuit.Circuit(
[
_builtin_gates.T.dagger(0),
],
6,
),
_make_qiskit_circuit(
6,
[
("tdg", (0,)),
],
),
),
(
_circuit.Circuit(
[
_wavefunction_operations.ResetOperation(0),
],
6,
),
_make_qiskit_circuit(
6,
[
("reset", (0,)),
],
),
),
(
_circuit.Circuit(
[
_builtin_gates.X(0),
_wavefunction_operations.ResetOperation(0),
],
6,
),
_make_qiskit_circuit(
6,
[
("x", (0,)),
("reset", (0,)),
],
),
),
(
_circuit.Circuit(
[
_builtin_gates.CNOT(0, 1),
],
4,
),
_make_qiskit_circuit(
4,
[
("cnot", (0, 1)),
],
),
),
(
_circuit.Circuit(
[
_builtin_gates.RX(np.pi)(1),
],
4,
),
_make_qiskit_circuit(
4,
[
("rx", (np.pi, 1)),
],
),
),
(
_circuit.Circuit(
[_builtin_gates.SWAP.controlled(1)(2, 0, 3)],
5,
),
_make_qiskit_circuit(
5,
[
("append", (qiskit.circuit.library.SwapGate().control(1), [2, 0, 3])),
],
),
),
(
_circuit.Circuit(
[_builtin_gates.Y.controlled(2)(4, 5, 2)],
6,
),
_make_qiskit_circuit(
6,
[
("append", (qiskit.circuit.library.YGate().control(2), [4, 5, 2])),
],
),
),
(
_circuit.Circuit([_builtin_gates.U3(np.pi / 5, np.pi / 2, np.pi / 4)(2)]),
_make_qiskit_circuit(
3,
[
(
"append",
(
qiskit.circuit.library.U3Gate(np.pi / 5, np.pi / 2, np.pi / 4),
[2],
),
)
],
),
),
(
_circuit.Circuit(
[_builtin_gates.U3(np.pi / 5, np.pi / 2, np.pi / 4).controlled(1)(1, 2)]
),
_make_qiskit_circuit(
3,
[
(
"append",
(
qiskit.circuit.library.U3Gate(
np.pi / 5, np.pi / 2, np.pi / 4
).control(1),
[1, 2],
),
)
],
),
),
(
_circuit.Circuit([_builtin_gates.Delay(1)(0)]),
_make_qiskit_circuit(1, [("delay", (1, 0))]),
),
]
EQUIVALENT_PARAMETRIZED_CIRCUITS = [
(
_circuit.Circuit(
[
_builtin_gates.RX(SYMPY_THETA)(1),
],
4,
),
_make_qiskit_circuit(
4,
[
("rx", (QISKIT_THETA, 1)),
],
),
),
(
_circuit.Circuit(
[
_builtin_gates.RX(SYMPY_THETA * SYMPY_GAMMA)(1),
],
4,
),
_make_qiskit_circuit(
4,
[
("rx", (QISKIT_THETA * QISKIT_GAMMA, 1)),
],
),
),
(
_circuit.Circuit(
[_builtin_gates.U3(SYMPY_THETA, SYMPY_GAMMA, SYMPY_LAMBDA)(3)]
),
_make_qiskit_circuit(
4,
[
(
"append",
(
qiskit.circuit.library.U3Gate(
QISKIT_THETA, QISKIT_GAMMA, QISKIT_LAMBDA
),
[3],
),
)
],
),
),
(
_circuit.Circuit(
[
_builtin_gates.U3(SYMPY_THETA, SYMPY_GAMMA, SYMPY_LAMBDA).controlled(1)(
2, 3
)
]
),
_make_qiskit_circuit(
4,
[
(
"append",
(
qiskit.circuit.library.U3Gate(
QISKIT_THETA, QISKIT_GAMMA, QISKIT_LAMBDA
).control(1),
[2, 3],
),
)
],
),
),
(
_circuit.Circuit(
[
_builtin_gates.RX(
SYMPY_PARAMETER_VECTOR[0] * SYMPY_PARAMETER_VECTOR[1]
)(1),
],
4,
),
_make_qiskit_circuit(
4,
[
("rx", (QISKIT_PARAMETER_VECTOR[0] * QISKIT_PARAMETER_VECTOR[1], 1)),
],
),
),
]
UNITARY_GATE_DEF = _gates.CustomGateDefinition(
"unitary.33c11b461fe67e717e37ac34a568cd1c27a89013703bf5b84194f0732a33a26d",
sympy.Matrix([[0, 1], [1, 0]]),
tuple(),
)
CUSTOM_A2_GATE_DEF = _gates.CustomGateDefinition(
"custom.A2.33c11b461fe67e717e37ac34a568cd1c27a89013703bf5b84194f0732a33a26d",
sympy.Matrix([[0, 1], [1, 0]]),
tuple(),
)
EQUIVALENT_CUSTOM_GATE_CIRCUITS = [
(
_circuit.Circuit(
operations=[UNITARY_GATE_DEF()(1)],
n_qubits=4,
),
_make_qiskit_circuit(
4,
[
("unitary", (np.array([[0, 1], [1, 0]]), 1)),
],
),
),
(
_circuit.Circuit(
operations=[CUSTOM_A2_GATE_DEF()(3)],
n_qubits=5,
),
_make_qiskit_circuit(
5,
[
("unitary", (np.array([[0, 1], [1, 0]]), 3, "custom.A2")),
],
),
),
(
_circuit.Circuit(
operations=[UNITARY_GATE_DEF()(1), UNITARY_GATE_DEF()(1)],
n_qubits=4,
),
_make_qiskit_circuit(
4,
[
("unitary", (np.array([[0, 1], [1, 0]]), 1)),
("unitary", (np.array([[0, 1], [1, 0]]), 1)),
],
),
),
(
_circuit.Circuit(
operations=[
UNITARY_GATE_DEF()(1),
CUSTOM_A2_GATE_DEF()(1),
UNITARY_GATE_DEF()(0),
],
n_qubits=4,
),
_make_qiskit_circuit(
4,
[
("unitary", (np.array([[0, 1], [1, 0]]), 1)),
("unitary", (np.array([[0, 1], [1, 0]]), 1, "custom.A2")),
("unitary", (np.array([[0, 1], [1, 0]]), 0)),
],
),
),
]
UNSUPPORTED_CIRCUITS = [
_make_qiskit_circuit(1, [("measure", (0, 0))], n_cbits=1),
_make_qiskit_circuit(1, [("break_loop", ())]),
]
def _draw_qiskit_circuit(circuit):
return qiskit.visualization.circuit_drawer(circuit, output="text")
class TestExportingToQiskit:
@pytest.mark.parametrize(
"orquestra_circuit, qiskit_circuit", EQUIVALENT_NON_PARAMETRIZED_CIRCUITS
)
def test_exporting_circuit_gives_equivalent_circuit(
self, orquestra_circuit, qiskit_circuit
):
converted = export_to_qiskit(orquestra_circuit)
assert converted == qiskit_circuit, (
f"Converted circuit:\n{_draw_qiskit_circuit(converted)}\n isn't equal "
f"to\n{_draw_qiskit_circuit(qiskit_circuit)}"
)
@pytest.mark.parametrize(
"orquestra_circuit",
[
orquestra_circuit
for orquestra_circuit, _ in EQUIVALENT_PARAMETRIZED_CIRCUITS
],
)
def test_exporting_parametrized_circuit_doesnt_change_symbol_names(
self, orquestra_circuit
):
converted = export_to_qiskit(orquestra_circuit)
converted_names = sorted(map(str, converted.parameters))
initial_names = sorted(map(str, orquestra_circuit.free_symbols))
assert converted_names == initial_names
@pytest.mark.parametrize(
"orquestra_circuit, qiskit_circuit", EQUIVALENT_PARAMETRIZED_CIRCUITS
)
def test_exporting_and_binding_parametrized_circuit_results_in_equivalent_circuit(
self, orquestra_circuit, qiskit_circuit
):
# 1. Export
converted = export_to_qiskit(orquestra_circuit)
# 2. Bind params
converted_bound = converted.bind_parameters(
{param: EXAMPLE_PARAM_VALUES[str(param)] for param in converted.parameters}
)
# 3. Bind the ref
ref_bound = qiskit_circuit.bind_parameters(
{
param: EXAMPLE_PARAM_VALUES[str(param)]
for param in qiskit_circuit.parameters
}
)
assert converted_bound == ref_bound, (
f"Converted circuit:\n{_draw_qiskit_circuit(converted_bound)}\n isn't "
f"equal to\n{_draw_qiskit_circuit(ref_bound)}"
)
@pytest.mark.parametrize(
"orquestra_circuit, qiskit_circuit", EQUIVALENT_PARAMETRIZED_CIRCUITS
)
def test_binding_and_exporting_parametrized_circuit_results_in_equivalent_circuit(
self, orquestra_circuit, qiskit_circuit
):
# 1. Bind params
bound = orquestra_circuit.bind(
{
symbol: EXAMPLE_PARAM_VALUES[str(symbol)]
for symbol in orquestra_circuit.free_symbols
}
)
# 2. Export
bound_converted = export_to_qiskit(bound)
# 3. Bind the ref
ref_bound = qiskit_circuit.bind_parameters(
{
param: EXAMPLE_PARAM_VALUES[str(param)]
for param in qiskit_circuit.parameters
}
)
assert bound_converted == ref_bound, (
f"Converted circuit:\n{_draw_qiskit_circuit(bound_converted)}\n isn't "
f"equal to\n{_draw_qiskit_circuit(ref_bound)}"
)
@pytest.mark.parametrize(
"orquestra_circuit, qiskit_circuit", EQUIVALENT_CUSTOM_GATE_CIRCUITS
)
def test_exporting_circuit_with_custom_gates_gives_equivalent_operator(
self, orquestra_circuit, qiskit_circuit
):
exported = export_to_qiskit(orquestra_circuit)
# We can't compare the circuits directly, because the gate names can differ.
# Qiskit allows multiple gate operations with the same label. Orquestra doesn't
# allow that, so we append a matrix hash to the name.
assert qiskit.quantum_info.Operator(exported) == qiskit.quantum_info.Operator(
qiskit_circuit
)
class TestImportingFromQiskit:
@pytest.mark.parametrize(
"orquestra_circuit, qiskit_circuit", EQUIVALENT_NON_PARAMETRIZED_CIRCUITS
)
def test_importing_circuit_gives_equivalent_circuit(
self, orquestra_circuit, qiskit_circuit
):
imported = import_from_qiskit(qiskit_circuit)
assert imported == orquestra_circuit
@pytest.mark.parametrize(
"qiskit_circuit",
[q_circuit for _, q_circuit in EQUIVALENT_PARAMETRIZED_CIRCUITS],
)
def test_importing_parametrized_circuit_doesnt_change_symbol_names(
self, qiskit_circuit
):
imported = import_from_qiskit(qiskit_circuit)
assert sorted(map(str, imported.free_symbols)) == sorted(
map(str, qiskit_circuit.parameters)
)
@pytest.mark.parametrize(
"orquestra_circuit, qiskit_circuit", EQUIVALENT_PARAMETRIZED_CIRCUITS
)
def test_importing_and_binding_parametrized_circuit_results_in_equivalent_circuit(
self, orquestra_circuit, qiskit_circuit
):
# 1. Import
imported = import_from_qiskit(qiskit_circuit)
symbols_map = {
symbol: EXAMPLE_PARAM_VALUES[str(symbol)]
for symbol in imported.free_symbols
}
# 2. Bind params
imported_bound = imported.bind(symbols_map)
# 3. Bind the ref
ref_bound = orquestra_circuit.bind(symbols_map)
assert imported_bound == ref_bound
@pytest.mark.parametrize(
"orquestra_circuit, qiskit_circuit", EQUIVALENT_PARAMETRIZED_CIRCUITS
)
def test_binding_and_importing_parametrized_circuit_results_in_equivalent_circuit(
self, orquestra_circuit, qiskit_circuit
):
# 1. Bind params
bound = qiskit_circuit.bind_parameters(
{
param: EXAMPLE_PARAM_VALUES[str(param)]
for param in qiskit_circuit.parameters
}
)
# 2. Import
bound_imported = import_from_qiskit(bound)
# 3. Bind the ref
ref_bound = orquestra_circuit.bind(
{
symbol: EXAMPLE_PARAM_VALUES[str(symbol)]
for symbol in orquestra_circuit.free_symbols
}
)
assert bound_imported == ref_bound
@pytest.mark.parametrize(
"orquestra_circuit, qiskit_circuit", EQUIVALENT_CUSTOM_GATE_CIRCUITS
)
def test_importing_circuit_with_custom_gates_gives_equivalent_circuit(
self, orquestra_circuit, qiskit_circuit
):
imported = import_from_qiskit(qiskit_circuit)
assert imported == orquestra_circuit
@pytest.mark.parametrize("unsupported_circuit", UNSUPPORTED_CIRCUITS)
def test_operation_not_implemented(self, unsupported_circuit):
with pytest.raises(ValueError):
import_from_qiskit(unsupported_circuit)
|
https://github.com/zapatacomputing/qe-qiskit
|
zapatacomputing
|
################################################################################
# © Copyright 2021-2022 Zapata Computing Inc.
################################################################################
############################################################################
# Copyright 2017 Rigetti Computing, Inc.
# Modified by Zapata Computing 2020 to work for qiskit's SummedOp.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
############################################################################
import numpy as np
import pytest
from qeqiskit.conversions import qiskitpauli_to_qubitop, qubitop_to_qiskitpauli
from qiskit.opflow import PauliOp, SummedOp
from qiskit.quantum_info import Pauli
from zquantum.core.openfermion.ops import (
FermionOperator,
InteractionOperator,
InteractionRDM,
QubitOperator,
)
from zquantum.core.openfermion.transforms import jordan_wigner
from zquantum.core.openfermion.utils import hermitian_conjugated
def test_translation_type_enforcement():
"""
Make sure type check works
"""
create_one = FermionOperator("1^")
empty_one_body = np.zeros((2, 2))
empty_two_body = np.zeros((2, 2, 2, 2))
interact_one = InteractionOperator(1, empty_one_body, empty_two_body)
interact_rdm = InteractionRDM(empty_one_body, empty_two_body)
with pytest.raises(TypeError):
qubitop_to_qiskitpauli(create_one)
with pytest.raises(TypeError):
qubitop_to_qiskitpauli(interact_one)
with pytest.raises(TypeError):
qubitop_to_qiskitpauli(interact_rdm)
def test_qubitop_to_qiskitpauli():
"""
Conversion of QubitOperator; accuracy test
"""
hop_term = FermionOperator(((2, 1), (0, 0)))
term = hop_term + hermitian_conjugated(hop_term)
pauli_term = jordan_wigner(term)
qiskit_op = qubitop_to_qiskitpauli(pauli_term)
ground_truth = (
PauliOp(Pauli.from_label("XZX"), 0.5) + PauliOp(Pauli.from_label("YZY"), 0.5)
).to_pauli_op()
assert ground_truth == qiskit_op
def test_qubitop_to_qiskitpauli_zero():
zero_term = QubitOperator()
qiskit_term = qubitop_to_qiskitpauli(zero_term)
ground_truth = SummedOp([])
assert ground_truth == qiskit_term
def test_qiskitpauli_to_qubitop():
qiskit_term = SummedOp([PauliOp(Pauli.from_label("XIIIIY"), coeff=1)])
op_fermion_term = QubitOperator(((0, "X"), (5, "Y")))
test_op_fermion_term = qiskitpauli_to_qubitop(qiskit_term)
assert test_op_fermion_term.isclose(op_fermion_term)
def test_qiskitpauli_to_qubitop_type_enforced():
"""Enforce the appropriate type"""
create_one = FermionOperator("1^")
empty_one_body = np.zeros((2, 2))
empty_two_body = np.zeros((2, 2, 2, 2))
interact_one = InteractionOperator(1, empty_one_body, empty_two_body)
interact_rdm = InteractionRDM(empty_one_body, empty_two_body)
with pytest.raises(TypeError):
qiskitpauli_to_qubitop(create_one)
with pytest.raises(TypeError):
qiskitpauli_to_qubitop(interact_one)
with pytest.raises(TypeError):
qiskitpauli_to_qubitop(interact_rdm)
|
https://github.com/zapatacomputing/qe-qiskit
|
zapatacomputing
|
################################################################################
# © Copyright 2021-2022 Zapata Computing Inc.
################################################################################
import pytest
import qiskit
from orquestra.quantum.circuits.symbolic.expressions import FunctionCall, Symbol
from orquestra.quantum.circuits.symbolic.translations import translate_expression
from orquestra.integrations.qiskit.conversions._qiskit_expressions import (
QISKIT_DIALECT,
expression_from_qiskit,
integer_pow,
)
THETA = qiskit.circuit.Parameter("theta")
PHI = qiskit.circuit.Parameter("phi")
EQUIVALENT_EXPRESSIONS = [
(
FunctionCall(
name="add",
args=(1, FunctionCall(name="mul", args=(2, Symbol(name="theta")))),
),
THETA * 2 + 1,
),
(
FunctionCall(
name="add",
args=(1, FunctionCall(name="pow", args=(Symbol(name="theta"), 2))),
),
THETA * THETA + 1,
),
(
FunctionCall(
name="sub",
args=(
2,
FunctionCall(
name="mul", args=(Symbol(name="phi"), Symbol(name="theta"))
),
),
),
2 - THETA * PHI,
),
]
INTERMEDIATE_EXPRESSIONS = [expr for expr, _ in EQUIVALENT_EXPRESSIONS]
class TestParsingQiskitExpressions:
@pytest.mark.parametrize("intermediate_expr, qiskit_expr", EQUIVALENT_EXPRESSIONS)
def test_parsed_intermediate_expression_matches_equivalent_expression(
self, intermediate_expr, qiskit_expr
):
parsed_expr = expression_from_qiskit(qiskit_expr)
assert parsed_expr == intermediate_expr
@pytest.mark.parametrize("expr", INTERMEDIATE_EXPRESSIONS)
def test_translate_parse_identity(self, expr):
# NOTE: the other way round (Qiskit -> intermediate -> Qiskit) can't be done
# directly, because Qiskit expressions don't implement equality checks.
qiskit_expr = translate_expression(expr, QISKIT_DIALECT)
parsed_expr = expression_from_qiskit(qiskit_expr)
assert parsed_expr == expr
class TestIntegerPower:
def test_only_integer_exponents_are_valid(self):
with pytest.raises(ValueError):
integer_pow(2, 2.5)
@pytest.mark.parametrize("base", [10, THETA])
def test_with_exponent_0_is_equal_to_one(self, base):
assert integer_pow(base, 0) == 1
@pytest.mark.parametrize(
"base, exponent, expected_result",
[(2.5, 3, 2.5**3), (THETA, 2, THETA * THETA)],
)
def test_with_positive_exponent_is_converted_to_repeated_multiplication(
self, base, exponent, expected_result
):
assert integer_pow(base, exponent) == expected_result
def test_negative_exponent_cannot_be_used_if_base_is_zero(self):
with pytest.raises(ValueError):
integer_pow(0, -10)
@pytest.mark.parametrize(
"base, exponent, expected_result",
[(2.0, -4, 0.5**4), (THETA, -3, (1 / THETA) * (1 / THETA) * (1 / THETA))],
)
def test_with_neg_exponent_is_converted_to_repeated_multiplication_of_reciprocals(
self, base, exponent, expected_result
):
assert integer_pow(base, exponent) == expected_result
|
https://github.com/zapatacomputing/qe-qiskit
|
zapatacomputing
|
################################################################################
# © Copyright 2021-2022 Zapata Computing Inc.
################################################################################
import os
import unittest
import qiskit.providers.aer.noise as AerNoise
from orquestra.quantum.circuits.layouts import CircuitConnectivity
from qiskit.providers.exceptions import QiskitBackendNotFoundError
from orquestra.integrations.qiskit.noise.basic import (
create_amplitude_damping_noise,
create_phase_and_amplitude_damping_error,
create_phase_damping_noise,
create_pta_channel,
get_kraus_matrices_from_ibm_noise_model,
get_qiskit_noise_model,
)
class TestBasic(unittest.TestCase):
def setUp(self):
self.ibmq_api_token = os.getenv("ZAPATA_IBMQ_API_TOKEN")
self.all_devices = ["ibm_kyoto"]
self.T_1 = 10e-7
self.T_2 = 30e-7
self.t_step = 10e-9
self.t_1_t_2_models = [
create_phase_and_amplitude_damping_error,
create_pta_channel,
]
def test_get_qiskit_noise_model(self):
# Given
for device in self.all_devices:
# When
noise_model, coupling_map = get_qiskit_noise_model(
device, api_token=self.ibmq_api_token
)
# Then
self.assertIsInstance(noise_model, AerNoise.NoiseModel)
self.assertIsInstance(coupling_map, list)
def test_get_qiskit_noise_model_no_device(self):
# Given
not_real_devices = ["THIS IS NOT A REAL DEVICE", "qasm_simulator"]
for device in not_real_devices:
# When/then
self.assertRaises(
QiskitBackendNotFoundError,
lambda: get_qiskit_noise_model(device, api_token=self.ibmq_api_token),
)
def test_t_1_t_2_noise_models(self):
for noise in self.t_1_t_2_models:
self.assertIsInstance(
noise(self.T_1, self.T_2, self.t_step), AerNoise.NoiseModel
)
def test_amplitude_damping_model(self):
self.assertIsInstance(
create_amplitude_damping_noise(self.T_1, self.t_step), AerNoise.NoiseModel
)
def test_phase_damping_noise(self):
self.assertIsInstance(
create_phase_damping_noise(self.T_2, self.t_step), AerNoise.NoiseModel
)
def test_getting_kraus_matrices_from_noise_model(self):
noise_model = create_amplitude_damping_noise(self.T_1, self.t_step)
kraus_dict = get_kraus_matrices_from_ibm_noise_model(noise_model)
# Test to see if basis gates are in
self.assertEqual("id" in kraus_dict, True)
self.assertEqual("u3" in kraus_dict, True)
self.assertEqual("cx" in kraus_dict, True)
# Test to see if the number of kraus operators is right for a basis gate
self.assertEqual(len(kraus_dict["id"]), 2)
self.assertEqual(len(kraus_dict["u3"]), 2)
self.assertEqual(len(kraus_dict["cx"]), 4)
|
https://github.com/zapatacomputing/qe-qiskit
|
zapatacomputing
|
################################################################################
# © Copyright 2021-2022 Zapata Computing Inc.
################################################################################
import os
import pytest
import qiskit.providers.aer.noise as AerNoise
from qeqiskit.noise import get_qiskit_noise_model
from qeqiskit.simulator import QiskitSimulator
from zquantum.core.circuits import CNOT, Circuit, X
from zquantum.core.estimation import estimate_expectation_values_by_averaging
from zquantum.core.interfaces.backend_test import (
QuantumSimulatorGatesTest,
QuantumSimulatorTests,
)
from zquantum.core.interfaces.estimation import EstimationTask
from zquantum.core.measurement import ExpectationValues
from zquantum.core.openfermion.ops import QubitOperator
@pytest.fixture(
params=[
{
"device_name": "aer_simulator",
"api_token": os.getenv("ZAPATA_IBMQ_API_TOKEN"),
},
]
)
def backend(request):
return QiskitSimulator(**request.param)
@pytest.fixture(
params=[
{
"device_name": "aer_simulator_statevector",
},
]
)
def wf_simulator(request):
return QiskitSimulator(**request.param)
@pytest.fixture(
params=[
{
"device_name": "aer_simulator",
},
{
"device_name": "aer_simulator_statevector",
},
]
)
def sampling_simulator(request):
return QiskitSimulator(**request.param)
@pytest.fixture(
params=[
{"device_name": "aer_simulator", "optimization_level": 0},
]
)
def noisy_simulator(request):
ibmq_api_token = os.getenv("ZAPATA_IBMQ_API_TOKEN")
noise_model, connectivity = get_qiskit_noise_model(
"ibm_nairobi", api_token=ibmq_api_token
)
return QiskitSimulator(
**request.param, noise_model=noise_model, device_connectivity=connectivity
)
class TestQiskitSimulator(QuantumSimulatorTests):
def test_run_circuitset_and_measure(self, sampling_simulator):
# Given
circuit = Circuit([X(0), CNOT(1, 2)])
# When
measurements_set = sampling_simulator.run_circuitset_and_measure(
[circuit], [100]
)
# Then
assert len(measurements_set) == 1
for measurements in measurements_set:
assert len(measurements.bitstrings) == 100
assert all(bitstring == (1, 0, 0) for bitstring in measurements.bitstrings)
# When
n_circuits = 50
n_samples = 100
measurements_set = sampling_simulator.run_circuitset_and_measure(
[circuit] * n_circuits, [n_samples] * n_circuits
)
# Then
assert len(measurements_set) == n_circuits
for measurements in measurements_set:
assert len(measurements.bitstrings) == n_samples
assert all(bitstring == (1, 0, 0) for bitstring in measurements.bitstrings)
def test_setup_basic_simulators(self):
simulator = QiskitSimulator("aer_simulator")
assert isinstance(simulator, QiskitSimulator)
assert simulator.device_name == "aer_simulator"
assert simulator.noise_model is None
assert simulator.device_connectivity is None
assert simulator.basis_gates is None
simulator = QiskitSimulator("aer_simulator_statevector")
assert isinstance(simulator, QiskitSimulator)
assert simulator.device_name == "aer_simulator_statevector"
assert simulator.noise_model is None
assert simulator.device_connectivity is None
assert simulator.basis_gates is None
def test_simulator_that_does_not_exist(self):
# Given/When/Then
with pytest.raises(RuntimeError):
QiskitSimulator("DEVICE DOES NOT EXIST")
def test_expectation_value_with_noisy_simulator(self, noisy_simulator):
# Given
# Initialize in |1> state
circuit = Circuit([X(0)])
# Flip qubit an even number of times to remain in the |1> state, but allow
# decoherence to take effect
circuit += Circuit([X(0) for i in range(10)])
qubit_operator = QubitOperator("Z0")
n_samples = 8192
# When
estimation_tasks = [EstimationTask(qubit_operator, circuit, n_samples)]
expectation_values_10_gates = estimate_expectation_values_by_averaging(
noisy_simulator, estimation_tasks
)[0]
# Then
assert isinstance(expectation_values_10_gates, ExpectationValues)
assert len(expectation_values_10_gates.values) == 1
assert expectation_values_10_gates.values[0] > -1
assert expectation_values_10_gates.values[0] < 0.0
assert isinstance(noisy_simulator, QiskitSimulator)
assert noisy_simulator.device_name == "aer_simulator"
assert isinstance(noisy_simulator.noise_model, AerNoise.NoiseModel)
assert noisy_simulator.device_connectivity is not None
assert noisy_simulator.basis_gates is not None
# Given
# Initialize in |1> state
circuit = Circuit([X(0)])
# Flip qubit an even number of times to remain in the |1> state, but allow
# decoherence to take effect
circuit += Circuit([X(0) for i in range(50)])
qubit_operator = QubitOperator("Z0")
# When
estimation_tasks = [EstimationTask(qubit_operator, circuit, n_samples)]
expectation_values_50_gates = estimate_expectation_values_by_averaging(
noisy_simulator, estimation_tasks
)[0]
# Then
assert isinstance(expectation_values_50_gates, ExpectationValues)
assert len(expectation_values_50_gates.values) == 1
assert expectation_values_50_gates.values[0] > -1
assert expectation_values_50_gates.values[0] < 0.0
assert (
expectation_values_50_gates.values[0]
> expectation_values_10_gates.values[0]
)
assert isinstance(noisy_simulator, QiskitSimulator)
assert noisy_simulator.device_name == "aer_simulator"
assert isinstance(noisy_simulator.noise_model, AerNoise.NoiseModel)
assert noisy_simulator.device_connectivity is not None
assert noisy_simulator.basis_gates is not None
def test_optimization_level_of_transpiler(self):
# Given
noise_model, connectivity = get_qiskit_noise_model(
"ibm_nairobi", api_token=os.getenv("ZAPATA_IBMQ_API_TOKEN")
)
n_samples = 8192
simulator = QiskitSimulator(
"aer_simulator",
noise_model=noise_model,
device_connectivity=connectivity,
optimization_level=0,
)
qubit_operator = QubitOperator("Z0")
# Initialize in |1> state
circuit = Circuit([X(0)])
# Flip qubit an even number of times to remain in the |1> state, but allow
# decoherence to take effect
circuit += Circuit([X(0) for i in range(50)])
# When
estimation_tasks = [EstimationTask(qubit_operator, circuit, n_samples)]
expectation_values_no_compilation = estimate_expectation_values_by_averaging(
simulator, estimation_tasks
)
simulator.optimization_level = 3
expectation_values_full_compilation = estimate_expectation_values_by_averaging(
simulator, estimation_tasks
)
# Then
assert (
expectation_values_full_compilation[0].values[0]
< expectation_values_no_compilation[0].values[0]
)
def test_run_circuit_and_measure_seed(self):
# Given
circuit = Circuit([X(0), CNOT(1, 2)])
n_samples = 100
simulator1 = QiskitSimulator("aer_simulator", seed=643)
simulator2 = QiskitSimulator("aer_simulator", seed=643)
# When
measurements1 = simulator1.run_circuit_and_measure(circuit, n_samples)
measurements2 = simulator2.run_circuit_and_measure(circuit, n_samples)
# Then
for (meas1, meas2) in zip(measurements1.bitstrings, measurements2.bitstrings):
assert meas1 == meas2
def test_get_wavefunction_seed(self):
# Given
circuit = Circuit([X(0), CNOT(1, 2)])
simulator1 = QiskitSimulator("aer_simulator_statevector", seed=643)
simulator2 = QiskitSimulator("aer_simulator_statevector", seed=643)
# When
wavefunction1 = simulator1.get_wavefunction(circuit)
wavefunction2 = simulator2.get_wavefunction(circuit)
# Then
for (ampl1, ampl2) in zip(wavefunction1.amplitudes, wavefunction2.amplitudes):
assert ampl1 == ampl2
class TestQiskitSimulatorGates(QuantumSimulatorGatesTest):
gates_to_exclude = ["RH", "XY"]
pass
|
https://github.com/dkp-quantum/Tutorials
|
dkp-quantum
|
# If you already have saved IBM credentials with previous version,
# update your credentials that is stored in disk
IBMQ.update_account()
# import
from qiskit import *
import numpy as np
from qiskit.visualization import plot_histogram, plot_state_city, plot_state_paulivec
from qiskit.quantum_info import Pauli, state_fidelity, basis_state, process_fidelity
from qiskit.tools.monitor import backend_overview, backend_monitor, job_monitor
# Create a quantum register with 3 qubits
q = QuantumRegister(3,'q')
# Form a quantum circuit
# Note that the circuit name is optional
qc = QuantumCircuit(q,name="first_qc")
# Display the quantum circuit
qc.draw()
# Create a classical register with 3 bits
c = ClassicalRegister(3,'c')
meas = QuantumCircuit(q,c,name="first_m")
meas.barrier(q)
meas.measure(q[0], c[0])
meas.measure(q[1], c[1])
meas.measure(q[2], c[2])
#meas.measure(q[3], c[3])
#meas.measure(q[4], c[4])
meas.draw()
# Add a x gate on qubit 0.
qc.x(0)
# Add a Hadamard gate on qubit 1, putting this in superposition.
qc.h(1)
# Add a CX (CNOT) gate on control qubit 1
# and target qubit 2 to create an entangled state.
qc.cx(1, 2)
qc.draw()
# Quantum circuits can be added with + operations
# Add two pre-defined circuits
qc_comp=qc+meas
qc_comp.draw()
# Draw the quantum circuit in a different (slightly better) format
qc_comp.draw(output='mpl')
# Use Aer's qasm_simulator
backend_q = Aer.get_backend('qasm_simulator')
# Execute the circuit on the qasm simulator.
# We've set the number of repeats of the circuit
# to be 1024, which is default.
job_sim1 = execute(qc_comp, backend_q, shots=1024)
job_sim1.status()
# Grab the results from the job.
result_sim1 = job_sim1.result()
result_sim1
result_sim1.get_counts(qc_comp)
plot_histogram(result_sim1.get_counts(qc_comp))
# Use Aer's statevector_simulator
backend_sv = Aer.get_backend('statevector_simulator')
# Execute the circuit on the statevector simulator.
job_sim2 = execute(qc, backend_sv)
# Grab the results from the job.
result_sim2 = job_sim2.result()
# Output the entire result
job_sim2.result()
# See output state as a vector
outputstate = result_sim2.get_statevector(qc, decimals=5)
print(outputstate)
# Visualize density matrix
plot_state_city(outputstate)
# Examine state fidelity, compare with a basis state |111>
sf1=state_fidelity(basis_state('111', 3), outputstate)
# Examine state fidelity w.r.t the desired state
desired_state=[0,1,0,0,0,0,0,1]/np.sqrt(2)
sf2=state_fidelity(desired_state, outputstate)
print(sf1)
print(sf2)
# Create a simple quantum register with 2 qubit
# to examine unitary simulator
qu2 = QuantumRegister(2,'qu')
# Form a quantum circuit
# Note that the circuit name is optional
qu = QuantumCircuit(qu2,name="unitary_qc")
# Add a single qubit rotation
qu.z(0)
qu.z(1)
# Display the quantum circuit
qu.draw(output='mpl')
# Use Aer's unitary_simulator
backend_u = Aer.get_backend('unitary_simulator')
# Execute the circuit on the unitary simulator.
job_usim = execute(qu, backend_u)
# Grab the results from the job.
result_usim = job_usim.result()
result_usim
# Output the unitary matrix
unitary = result_usim.get_unitary(qu)
print('%s\n' % unitary)
# Check process fidelity
pf1=process_fidelity(Pauli(label='IX').to_matrix(), unitary)
pf2=process_fidelity(Pauli(label='ZZ').to_matrix(), unitary)
print('%s\n' % pf1)
print('%s\n' % pf2)
# Measure an expectation value of a Pauli observable
Z = np.array([[1, 0], [0, -1]])
X = np.array([[0, 1], [1, 0]])
Y = np.array([[0, -1j], [1j, 0]])
ZZ=np.kron(Z,Z)
XX=np.kron(X,X)
# Or use qiskit's built-in function to define Pauli matrices
ZI = Pauli(label='ZI').to_matrix()
XI = Pauli(label='XI').to_matrix()
YI = Pauli(label='YI').to_matrix()
# Create some functions for measuring expectation values
# For pure states
def expectation_state(state, Operator):
return np.dot(state.conj(), np.dot(Operator, state))
# For density matrices
def expectation_density(density, Operator):
return np.trace(Operator @ density)
IBMQ.enable_account('YOUR_TOKERN')
print(IBMQ.stored_account())
print(IBMQ.active_account())
my_provider=IBMQ.get_provider()
my_provider.backends()
# Retrieve IBM Quantum device information
backend_overview()
# Retrieve a specific IBM Quantum device information
# ibmq_16_melbourne as an example
backend_mel = my_provider.get_backend('ibmq_16_melbourne')
backend_monitor(backend_mel)
# Create a 3-qubit GHZ state
ghz3 = QuantumRegister(3,'q')
qc= QuantumCircuit(ghz3)
qc.h(0)
qc.cx(0,1)
qc.cx(0,2)
qghz3=qc+meas
qghz3.draw(output='mpl')
# Define backend as one of the real devices (5-qubit systems for now)
backend_qx2 = my_provider.get_backend('ibmqx2')
backend_qx4 = my_provider.get_backend('ibmqx4')
# There is a new 5-qubit backend
backend_ou = my_provider.get_backend('ibmq_ourense')
# Run 3-qubit GHZ experiment on a 5-qubit device (try ourense)
job_exp = execute(qghz3, backend=backend_ou)
job_monitor(job_exp)
# Grab experimental results
result_ou = job_exp.result()
counts_ou = result_exp.get_counts(qghz3)
plot_histogram(counts_ou)
# Run the same experiment on the other 5-qubit device as well.
job_exp2 = execute(qghz3, backend=backend_qx4)
job_monitor(job_exp2)
# Grab experimental results
result_exp2 = job_exp2.result()
counts_exp2 = result_exp2.get_counts(qghz3)
# Finally, run the same experiment on the 14-qubit device.
job_exp3 = execute(qghz3, backend=backend_mel)
job_monitor(job_exp3)
# Grab experimental results
result_mel = job_exp3.result()
counts_mel = result_mel.get_counts(qghz3)
plot_histogram(counts_mel)
# Now, compare to theory by running it on qasm_simulator
job_qasm = execute(qghz3,backend=backend_q)
result_qasm = job_qasm.result()
counts_qasm = result_qasm.get_counts(qghz3)
# Plot both experimental and ideal results
plot_histogram([counts_qasm,counts_ou,counts_mel],
color=['black','green','blue'],
legend=['QASM','Ourense','Melbourne'])
# Create a quantum register with 3 qubits
q = QuantumRegister(3,'q')
# Form a quantum circuit
qent = QuantumCircuit(q)
qent.initialize([1, 0, 0, 0, 0, 0, 0, 1] / np.sqrt(2), [q[0], q[1], q[2]])
# Display the quantum circuit
qent.draw(output='mpl')
# Use Aer's state vector simulator
backend_sv = Aer.get_backend('statevector_simulator')
# Execute and plot output state
output_ent = execute(qent, backend_sv).result().get_statevector(0, decimals=3)
plot_state_city(output_ent)
# Build a sub-circuit
# sub_ghz(n,c,t) creates a quantum circuit for creating an n-qubit GHZ state.
# n is the total number of qubits, c is an index for a control qubit, t is a vector of indices for target qubits.
def sub_ghz(n,c,t):
sub_q = QuantumRegister(n)
sub_circ = QuantumCircuit(sub_q, name='sub_ghz')
sub_circ.h(c)
for i in t:
sub_circ.cx(c,i)
return sub_circ
# Create a sub-circuit for 3-qubit GHZ state prep.
sub_ghz3 = sub_ghz(3,0,[1,2])
sub_inst3 = sub_ghz3.to_instruction()
# Create a sub-circuit consisting of T gate and cnot.
sub_tcnot = QuantumCircuit(QuantumRegister(2),name='t+cnot')
sub_tcnot.t(0)
sub_tcnot.cx(0,1)
q = QuantumRegister(5, 'q')
circ = QuantumCircuit(q)
# Now create a quantum circuit using sub-circuits.
# Apply Hadamard on all gates.
for i in range(5):
circ.h(i)
#
circ.barrier()
# Appy 2-qubit GHZ preparation on qubits 0 and 1, and on qubits 3 and 4.
circ.append(sub_tcnot, [q[0],q[1]])
circ.append(sub_tcnot, [q[3], q[4]])
#
circ.barrier()
# Apply 3-qubit GHZ preparation on all 3 neighbouring qubits.
for i in range(3):
circ.append(sub_inst3, [q[i], q[i+1],q[i+2]])
circ.draw(output='mpl')
# We can also decompose the circuit that is constructed using sub-circuits.
circ.decompose().draw(output='mpl')
from qiskit.circuit import Parameter
# Define two parameters, t1 and t2
theta1 = Parameter('t1')
theta2 = Parameter('t2')
# Build a 5-qubit circuit
qc = QuantumCircuit(5, 1)
# First parameter, t1, is used for a single qubit rotation of a controlled qubit
qc.ry(theta1,0)
for i in range(5-1):
qc.cx(i, i+1)
qc.barrier()
# Second parameter, t2, is used here
qc.rz(theta2,range(5))
qc.barrier()
for i in reversed(range(5-1)):
qc.cx(i, i+1)
qc.ry(theta1,0)
qc.measure(0, 0)
qc.draw(output='mpl')
theta1_range = np.linspace(0, np.pi/2, 2)
theta2_range = np.linspace(0, 2 * np.pi, 64)
circuits = [qc.bind_parameters({theta1: theta_val1, theta2: theta_val2})
for theta_val1 in theta1_range for theta_val2 in theta2_range ]
# Visualize several circuits to check that correct circuits are generated correctly.
circuits[0].draw(output='mpl')
# circuits[1].draw(output='mpl')
# circuits[64].draw(output='mpl')
# theta1_range = np.linspace(0, np.pi/2, 2)
# theta2_range = np.linspace(0, 2 * np.pi, 64)
# circuits = [qc.bind_parameters({theta1: theta_val1, theta2: theta_val2})
# for theta_val1 in theta1_range for theta_val2 in theta2_range ]
# Visualize several circuits to check that correct circuits are generated correctly.
# circuits[0].draw(output='mpl')
circuits[1].draw(output='mpl')
# circuits[64].draw(output='mpl')
# theta1_range = np.linspace(0, np.pi/2, 2)
# theta2_range = np.linspace(0, 2 * np.pi, 64)
# circuits = [qc.bind_parameters({theta1: theta_val1, theta2: theta_val2})
# for theta_val1 in theta1_range for theta_val2 in theta2_range ]
# Visualize several circuits to check that correct circuits are generated correctly.
# circuits[0].draw(output='mpl')
# circuits[1].draw(output='mpl')
circuits[64].draw(output='mpl')
# Execute multiple circuits
job = execute(qc, backend=Aer.get_backend('qasm_simulator'),
parameter_binds=[{theta1: theta_val1, theta2: theta_val2}
for theta_val1 in theta1_range for theta_val2 in theta2_range])
# Store all counts
counts = [job.result().get_counts(i) for i in range(len(job.result().results))]
# Plot to visualize the result
import matplotlib.pyplot as plt
plt.figure(figsize=(12,6))
plt.plot(range(len(theta1_range)*len(theta2_range)),
list(map(lambda counts: (counts.get('0',0)-counts.get('1',1))/1024,counts)))
plt.show()
# Reset operation forces the target qubit to go to |0>
q = QuantumRegister(1)
c = ClassicalRegister(1)
qc = QuantumCircuit(q, c)
qc.h(q)
qc.reset(q[0])
# qc.x(q)
qc.measure(q, c)
qc.draw(output='mpl')
# Test the result
job = execute(qc, backend=Aer.get_backend('qasm_simulator'), shots=1024)
job.result().get_counts(qc)
# Controlled qubit operation, controlled by classical bits
# This could be useful for designing a post-selection scheme of a quantum algorithm
q2 = QuantumRegister(2,'q')
cont = ClassicalRegister(1,'cont')
qc = QuantumCircuit(q2,cont)
qc.x(0)
qc.swap(q2[0],q2[1]).c_if(cont, 1)
qc.measure(q2[0],cont)
qc.draw(output='mpl')
job = execute(qc, backend=Aer.get_backend('qasm_simulator'), shots=1024)
job.result().get_counts(qc)
import random as r
qr = QuantumRegister(3)
cr1 = ClassicalRegister(1)
# Define a separate classical register for classically-controlled gate
cr2 = ClassicalRegister(1)
qtel = QuantumCircuit(qr,cr1,cr2)
# Make a reference circuit to compare
qref = QuantumCircuit(1,1)
# Prepare a 2-qubit bell state
qtel.h(1)
qtel.cx(1,2)
qtel.barrier()
# Prepare a random 1-qubit state
a1 = r.random()*np.pi
a2 = r.random()*np.pi
a3= r.random()*np.pi
qtel.u3(a1,a2,a3,0)
# Design a reference circuit for comparing to teleportation result
qref.u3(a1,a2,a3,0)
qref.measure(0,0)
print('Reference circuit:')
display(qref.draw(output='mpl'))
# Apply bell measurement on qubit 0 and 1
qtel.cx(0,1)
qtel.h(0)
qtel.barrier()
qtel.measure([0, 1],[0, 1])
qtel.z(2).c_if(cr1,1)
qtel.x(2).c_if(cr2,1)
qtel.measure(2,1)
print('Quantum teleportation circuit:')
display(qtel.draw(output='mpl'))
# n is the number of shots
n=10000
job_qtel = execute(qtel, backend_q, shots=n)
job_ref = execute(qref, backend_q, shots=n)
display(plot_histogram(job_ref.result().get_counts(qref)))
qtel_c = job_qtel.result().get_counts(qtel)
# Need some post-processing
print(qtel_c)
p1 = (qtel_c['1 0']+qtel_c['1 1'])/n
p0 = (qtel_c['0 0']+qtel_c['0 1'])/n
print('Prob. 1 from QT = %s' % p1)
print('Prob. 0 from QT = %s' % p0)
from qiskit.compiler import transpile
from qiskit.transpiler import PassManager, Layout
from qiskit.tools.visualization import plot_gate_map
# Let's take a look at the layout of physical devices with the gate directions
display(plot_gate_map(backend_qx4,plot_directed=True))
display(plot_gate_map(backend_ou,plot_directed=True))
display(plot_gate_map(backend_mel,plot_directed=True))
# Create a dummy circuit for default transpiler demonstration
qr = QuantumRegister(3)
cr = ClassicalRegister(3)
qc = QuantumCircuit(qr,cr)
qc.h(0)
qc.swap(0,1)
qc.cx(1,0)
qc.s(2)
qc.x(2)
qc.h(2)
qc.measure(qr[2],cr[2])
qc.h(0)
qc.cx(0,1)
qc.cx(0,1)
qc.h(0)
qc.measure(qr[0],cr[0])
qc.measure(qr[1],cr[1])
print('Original circuit')
display(qc.draw(output='mpl'))
# Transpile the circuit to run on ibmqx4
qt_qx4 = transpile(qc,backend_qx4)
print('Transpiled circuit for ibmqx4')
display(qt_qx4.draw(output='mpl'))
# Transpile the circuit to run on ibmq_Ourense
qt_ou = transpile(qc,backend_ou)
print('Transpiled circuit for ibmqx_Oursense')
display(qt_ou.draw(output='mpl'))
qr = QuantumRegister(3,'q')
qc = QuantumCircuit(qr)
qc.h(0)
qc.cx(0,1)
qc.cx(0,2)
qc.draw(output='mpl')
qc_t = transpile(qc, basis_gates=['u1','u2','u3','cx'])
# Display transpiled circuit
display(qc_t.draw(output='mpl'))
# Print out some circuit properties
# Total nunmber of operations
print("Number of operations = %s" % qc_t.size())
# Circuit depth
print("Circuit depth = %s" % qc_t.depth())
# Number of qubits
print("Number of qubits = %s" % qc_t.width())
# Breakdown of operations by type
print("Operations: %s" % qc_t.count_ops())
# Number of unentangled subcircuits in this circuit.
# In principle, each subcircuit can be executed on a different quantum device.
print("Number of unentangled subcircuits = %s" % qc_t.num_tensor_factors())
# Map it onto 5 qubit backend ibmqx2
qc_qx2 = transpile(qc, backend_qx2, basis_gates=['u1','u2','u3','cx'])
display(qc_qx2.draw(output='mpl'))
display(plot_gate_map(backend_qx2,plot_directed=True))
# Print out some circuit properties
# Total nunmber of operations
print("Number of operations = %s" % qc_qx2.size())
# Circuit depth
print("Circuit depth = %s" % qc_qx2.depth())
# Map it onto 5 qubit backend ibmqx4
qc_qx4 = transpile(qc, backend_qx4,basis_gates=['u1','u2','u3','cx'])
display(qc_qx4.draw(output='mpl'))
display(plot_gate_map(backend_qx4,plot_directed=True))
# Print out some circuit properties
# Total nunmber of operations
print("Number of operations = %s" % qc_qx4.size())
# Circuit depth
print("Circuit depth = %s" % qc_qx4.depth())
# Customize the layout
layout = Layout({qr[0]: 3, qr[1]: 4, qr[2]: 2})
# Map it onto 5 qubit backend ibmqx4
qc_qx4_new = transpile(qc, backend_qx4,initial_layout=layout,basis_gates=['u1','u2','u3','cx'])
display(qc_qx4_new.draw(output='mpl'))
# Print out some circuit properties
# Total nunmber of operations
print("Number of operations = %s" % qc_qx4_new.size())
# Circuit depth
print("Circuit depth = %s" % qc_qx4_new.depth())
# Test transpilation with Toffoli gate
qr = QuantumRegister(3,'q')
qccx = QuantumCircuit(qr)
qccx.ccx(0,1,2)
qccx.draw(output='mpl')
qccx_t = transpile(qccx, basis_gates=['u3','cx'])
# Display transpiled circuit
display(qccx_t.draw(output='mpl'))
# Print out some circuit properties
# Total nunmber of operations
print("Number of operations = %s" % qccx_t.size())
# Circuit depth
print("Circuit depth = %s" % qccx_t.depth())
# Number of qubits
print("Number of qubits = %s" % qccx_t.width())
# Breakdown of operations by type
print("Operations: %s" % qccx_t.count_ops())
# Number of unentangled subcircuits in this circuit.
# In principle, each subcircuit can be executed on a different quantum device.
print("Number of unentangled subcircuits = %s" % qccx_t.num_tensor_factors())
# Map it onto 5 qubit backend ibmqx2
qccx_qx2 = transpile(qccx, backend_qx2)
display(qccx_qx2.draw(output='mpl'))
display(plot_gate_map(backend_qx2,plot_directed=True))
# Print out some circuit properties
# Total nunmber of operations
print("Number of operations = %s" % qccx_qx2.size())
# Circuit depth
print("Circuit depth = %s" % qccx_qx2.depth())
# Number of cx gates
print("Number of cx operations = %s" % qccx_qx2.count_ops()['cx'])
# Map it onto 5 qubit backend ibmqx4
qccx_qx4 = transpile(qccx, backend_qx4)
display(qccx_qx4.draw(output='mpl'))
display(plot_gate_map(backend_qx4,plot_directed=True))
# Print out some circuit properties
# Total nunmber of operations
print("Number of operations = %s" % qccx_qx4.size())
# Circuit depth
print("Circuit depth = %s" % qccx_qx4.depth())
# Number of cx gates
print("Number of cx operations = %s" % qccx_qx4.count_ops()['cx'])
# Customize the layout
layout = Layout({qr[0]: 3, qr[1]: 4, qr[2]: 2})
# Map it onto 5 qubit backend ibmqx4
qccx_qx4_new = transpile(qccx, backend_qx4,initial_layout=layout)
display(qccx_qx4_new.draw(output='mpl'))
display(plot_gate_map(backend_qx4,plot_directed=True))
# Print out some circuit properties
# Total nunmber of operations
print("Number of operations = %s" % qccx_qx4_new.size())
# Circuit depth
print("Circuit depth = %s" % qccx_qx4_new.depth())
# Number of cx gates
print("Number of cx operations = %s" % qccx_qx4.count_ops()['cx'])
# The device information such as gate error and T1 and T2 also should be considered
# when customizing the layout.
backend_monitor(backend_qx2)
display(plot_gate_map(backend_ou,plot_directed=True))
# Customize the layout IBMQ Ourense
layout_ou = Layout({qr[0]: 2, qr[1]: 3, qr[2]: 1})
# Map it onto 5 qubit backend ibmqx4
qccx_ou = transpile(qccx, backend_ou,initial_layout=layout_ou)
display(qccx_ou.draw(output='mpl'))
# Print out some circuit properties
# Total nunmber of operations
print("Number of operations = %s" % qccx_ou.size())
# Circuit depth
print("Circuit depth = %s" % qccx_ou.depth())
# Number of cx gates
print("Number of cx operations = %s" % qccx_ou.count_ops()['cx'])
# Apply Toffoli among 5 qubits
qr = QuantumRegister(5,'q')
toff = QuantumCircuit(qr)
for i in range(5):
toff.h(i)
toff.ccx(0,1,2)
toff.ccx(1,2,3)
toff.ccx(2,3,4)
display(toff.draw(output='mpl'))
# Print out some circuit properties
# Total nunmber of operations
print("Number of operations = %s" % toff.size())
# Count different types of operations
print("Operation counts = %s" % toff.count_ops())
# Circuit depth
print("Circuit depth = %s" % toff.depth())
toff_t = transpile(toff, backend_mel)
display(toff_t.draw(output='latex'))
# Print out some circuit properties
# Total nunmber of operations
print("Number of operations = %s" % toff_t.size())
# Count different types of operations
print("Operation counts = %s" % toff_t.count_ops())
# Circuit depth
print("Circuit depth = %s" % toff_t.depth())
# Transpile many times (100 times in this example) and pick the best one
tcircs0 = transpile([toff]*100, backend_mel,optimization_level=0)
tcircs1 = transpile([toff]*100, backend_mel,optimization_level=1)
tcircs2 = transpile([toff]*100, backend_mel,optimization_level=2)
tcircs3 = transpile([toff]*100, backend_mel,optimization_level=3)
num_cx0 = [c.count_ops()['cx'] for c in tcircs0]
num_cx1 = [c.count_ops()['cx'] for c in tcircs1]
num_cx2 = [c.count_ops()['cx'] for c in tcircs2]
num_cx3 = [c.count_ops()['cx'] for c in tcircs3]
num_tot0 = [c.size() for c in tcircs0]
num_tot1 = [c.size() for c in tcircs1]
num_tot2 = [c.size() for c in tcircs2]
num_tot3 = [c.size() for c in tcircs3]
num_depth0 = [c.depth() for c in tcircs0]
num_depth1 = [c.depth() for c in tcircs1]
num_depth2 = [c.depth() for c in tcircs2]
num_depth3 = [c.depth() for c in tcircs3]
plt.rcParams.update({'font.size': 16})
# Plot the number of CNOT gates
plt.figure(figsize=(12,6))
plt.plot(range(len(num_cx0)),num_cx0,'r',label='level 0')
plt.plot(range(len(num_cx1)),num_cx1,'b',label='level 1')
plt.plot(range(len(num_cx2)),num_cx2,'g',label='level 2')
plt.plot(range(len(num_cx3)),num_cx3,'k',label='level 3')
plt.legend(loc='upper left')
plt.xlabel('Random trial')
plt.ylabel('# of cx gates')
plt.show()
# Plot total number of gates
plt.figure(figsize=(12,6))
plt.plot(range(len(num_cx0)),num_tot0,'r',label='level 0')
plt.plot(range(len(num_cx1)),num_tot1,'b',label='level 1')
plt.plot(range(len(num_cx2)),num_tot2,'g',label='level 2')
plt.plot(range(len(num_cx3)),num_tot3,'k',label='level 3')
plt.legend(loc='upper left')
plt.xlabel('Random trial')
plt.ylabel('# of total gates')
plt.show()
# Plot the number of CNOT gates
plt.figure(figsize=(12,6))
plt.plot(range(len(num_cx0)),num_depth0,'r',label='level 0')
plt.plot(range(len(num_cx1)),num_depth1,'b',label='level 1')
plt.plot(range(len(num_cx2)),num_depth2,'g',label='level 2')
plt.plot(range(len(num_cx3)),num_depth3,'k',label='level 3')
plt.legend(loc='upper left')
plt.xlabel('Random trial')
plt.ylabel('Circuit depth')
plt.show()
print('Opt0: Minimum # of cx gates = %s' % min(num_cx0))
print('Opt0: The best circuit is the circut %s' % num_cx0.index(min(num_cx0)))
print('Opt1: Minimum # of cx gates = %s' % min(num_cx1))
print('Opt1: The best circuit is the circut %s' % num_cx1.index(min(num_cx1)))
print('Opt2: Minimum # of cx gates = %s' % min(num_cx2))
print('Opt2: The best circuit is the circut %s' % num_cx2.index(min(num_cx2)))
print('Opt3: Minimum # of cx gates = %s' % min(num_cx3))
print('Opt3: The best circuit is the circut %s' % num_cx3.index(min(num_cx3)))
# Create a 10-qubit GHZ state
qr = QuantumRegister(10,'q')
ghz = QuantumCircuit(qr)
ghz.h(0)
for i in range(9):
ghz.cx(i,i+1)
display(ghz.draw(output='mpl'))
# Print out some circuit properties
# Total nunmber of operations
print("Number of operations = %s" % ghz.size())
# Count different types of operations
print("Operation counts = %s" % ghz.count_ops())
# Circuit depth
print("Circuit depth = %s" % ghz.depth())
ghz_t = transpile(ghz, backend_mel)
ghz_t.draw(output='latex')
# Print out some circuit properties
# Total nunmber of operations
print("Number of operations = %s" % ghz_t.size())
# Count different types of operations
print("Operation counts = %s" % ghz_t.count_ops())
# Circuit depth
print("Circuit depth = %s" % ghz_t.depth())
# Transpile 100 times and pick the best one
circs = transpile([ghz]*100, backend_mel)
num_cx = [c.count_ops()['cx'] for c in circs]
# Plot the number of CNOT gates
plt.figure(figsize=(12,6))
plt.plot(range(len(num_cx)),num_cx)
plt.show()
print('Minimum # of cx gates = %s' % min(num_cx))
print('The best circuit is the circut %s' % num_cx.index(min(num_cx)))
|
https://github.com/dkp-quantum/Tutorials
|
dkp-quantum
|
%matplotlib inline
# Importing standard Qiskit libraries and configuring account
from qiskit import *
from qiskit.visualization import *
import numpy as np
# Create a quantum register with 2 qubits
q = QuantumRegister(2,'q')
# Form a quantum circuit
# Note that the circuit name is optional
qc = QuantumCircuit(q,name="first_qc")
# Display the quantum circuit
qc.draw()
# Add a Hadamard gate on qubit 0, putting this in superposition.
qc.h(0)
# Add a CX (CNOT) gate on control qubit 0
# and target qubit 1 to create an entangled state.
qc.cx(0, 1)
qc.draw()
# Create a classical register with 2 bits
c = ClassicalRegister(2,'c')
meas = QuantumCircuit(q,c,name="first_m")
meas.barrier(q)
meas.measure(q, c)
meas.draw()
# Quantum circuits can be added with + operations
# Add two pre-defined circuits
qc_all=qc+meas
qc_all.draw()
# Draw the quantum circuit in a different (slightly better) format
qc_all.draw(output='mpl')
# Create the quantum circuit with the measurement in one go.
qc_all = QuantumCircuit(q,c,name="2q_all")
qc_all.h(0)
qc_all.cx(0,1)
qc_all.barrier()
qc_all.measure(0,0)
qc_all.measure(1,1)
qc_all.draw(output='mpl')
# Use Aer's qasm_simulator
backend_q = Aer.get_backend('qasm_simulator')
# Execute the circuit on the qasm simulator.
job_sim1 = execute(qc_all, backend_q, shots=4096)
job_sim1.status()
# Grab the results from the job.
result_sim1 = job_sim1.result()
result_sim1
result_sim1.get_counts(qc_all)
plot_histogram(result_sim1.get_counts(qc_all))
# Use Aer's statevector_simulator
backend_sv = Aer.get_backend('statevector_simulator')
# Execute the circuit on the statevector simulator.
# It is important to note that the measurement has been excluded
job_sim2 = execute(qc, backend_sv)
# Grab the results from the job.
result_sim2 = job_sim2.result()
# Output the entire result
result_sim2
# See output state as a vector
outputstate = result_sim2.get_statevector(qc, decimals=5)
print(outputstate)
# Visualize density matrix
plot_state_city(outputstate)
# Create the quantum circuit with the measurement in one go.
qc_3 = QuantumCircuit(3,3,name="qc_bloch")
qc_3.x(1)
qc_3.h(2)
qc_3.barrier()
qc_3.draw(output='mpl')
# Execute the circuit on the statevector simulator.
# It is important to note that the measurement has been excluded
job_sim_bloch = execute(qc_3, backend_sv)
# Grab the results from the job.
result_sim_bloch = job_sim_bloch.result()
# See output state as a vector
output_bloch = result_sim_bloch.get_statevector(qc_3, decimals=5)
# Draw on the Bloch sphere
plot_bloch_multivector(output_bloch)
# Use Aer's unitary_simulator
backend_u = Aer.get_backend('unitary_simulator')
# Execute the circuit on the unitary simulator.
job_usim = execute(qc, backend_u)
# Grab the results from the job.
result_usim = job_usim.result()
result_usim
# Output the unitary matrix
unitary = result_usim.get_unitary(qc)
print('%s\n' % unitary)
# Create the quantum circuit with the measurement in one go.
qc_ex1 = QuantumCircuit(q,c,name="ex1")
# Put the first qubit in equal superposition
qc_ex1.h(0)
# Rest of the circuit
qc_ex1.x(1)
qc_ex1.cx(0,1)
qc_ex1.barrier()
qc_ex1.measure(0,0)
qc_ex1.measure(1,1)
qc_ex1.draw(output='mpl')
# Execute the circuit on the qasm simulator.
job_ex1 = execute(qc_ex1, backend_q, shots=4096)
job_ex1.status()
# Grab the results from the job.
result_ex1 = job_ex1.result()
result_ex1.get_counts(qc_ex1)
plot_histogram(result_ex1.get_counts(qc_ex1))
# Or get the histogram in one go
plot_histogram(job_ex1.result().get_counts(qc_ex1))
# Create a quantum register with 3 qubits
q3 = QuantumRegister(3,'q')
# Create a classical register with 3 qubits
c3 = ClassicalRegister(3,'c')
# Create the quantum circuit with the measurement in one go.
qc_ex2 = QuantumCircuit(q3,c3,name="ex1")
qc_ex2.ry(2*np.pi/3,0)
qc_ex2.cx(0,1)
qc_ex2.cx(1,2)
qc_ex2.barrier()
qc_ex2.measure(q3,c3)
qc_ex2.draw(output='mpl')
# Execute the circuit on the qasm simulator.
job_ex2 = execute(qc_ex2, backend_q, shots=4096)
# Grab the results from the job.
result_ex2 = job_ex2.result()
plot_histogram(result_ex2.get_counts(qc_ex2))
# Create a quantum register with 3 qubits
q3 = QuantumRegister(3,'q')
# Create a classical register with 3 qubits
c3 = ClassicalRegister(3,'c')
# Create the quantum circuit without a Toffoli gate
qc_toff = QuantumCircuit(q3,c3,name="ex1")
qc_toff.ry(2*np.pi/3,0)
qc_toff.h(1)
qc_toff.h(2)
qc_toff.barrier()
qc_toff.measure(q3,c3)
qc_toff.draw(output='mpl')
# Execute the circuit on the qasm simulator.
job_toff = execute(qc_toff, backend_q, shots=4096)
# Grab the results from the job.
result_toff = job_toff.result()
plot_histogram(result_toff.get_counts(qc_toff))
# Now, add a Toffoli gate
qc_toff = QuantumCircuit(q3,c3,name="ex1")
qc_toff.ry(2*np.pi/3,0)
qc_toff.h(1)
qc_toff.h(2)
qc_toff.ccx(1,2,0)
qc_toff.barrier()
qc_toff.measure(q3,c3)
qc_toff.draw(output='mpl')
# Execute the circuit on the qasm simulator.
job_toff = execute(qc_toff, backend_q, shots=4096)
# Grab the results from the job.
result_toff = job_toff.result()
plot_histogram(result_toff.get_counts(qc_toff))
from qiskit import IBMQ
# first save your Token to disk
IBMQ.save_account('<Your Token>')
#IBMQ.load_account() # Load account from disk
from qiskit import IBMQ
# first save your Token to disk
# IBMQ.disable_account()
IBMQ.enable_account('<Your Token>')
IBMQ.providers()
open_provider = IBMQ.get_provider(hub='ibm-q', group='open')
#
default_provider = IBMQ.get_provider(hub='ibm-q-kaist', group='internal', project='default')
open_provider.backends()
default_provider.backends()
from qiskit.tools.monitor import backend_overview, backend_monitor
backend_overview()
# Open access
backend = open_provider.get_backend('ibmq_ourense')
# select a number of premium devices
backend_manhattan = default_provider.get_backend('ibmq_manhattan')
backend_toronto = default_provider.get_backend('ibmq_toronto')
backend_casablanca = default_provider.get_backend('ibmq_casablanca')
backend_monitor(default_provider.get_backend('ibmq_ourense'))
from qiskit.tools.jupyter import *
backend
from qiskit import Aer, QuantumCircuit, QuantumRegister, ClassicalRegister, execute
from qiskit.tools.visualization import plot_histogram
# Load account
#IBMQ.load_account()
# Select a backend
backend_local = Aer.get_backend('qasm_simulator')
backend_real = open_provider.get_backend('ibmq_ourense') #Simulator
print(backend_local)
print(backend_real)
# number of qubits
n = 2
# Define the Quantum and Classical Registers
q = QuantumRegister(n)
c = ClassicalRegister(n)
# Build the circuit
generalcircuit = QuantumCircuit(q, c)
generalcircuit.h(q[0])
generalcircuit.cx(q[0],q[1])
generalcircuit.measure(q, c)
generalcircuit.draw(output='mpl')
# Execute the circuit
job_local = execute(generalcircuit, backend_local, shots=8192)
job_local.status()
result=job_local.result()
print(result)
# Print the result
plot_histogram(result.get_counts())
# Execute the circuit
job_real = execute(generalcircuit, backend_real, shots=8192)
job_real.status()
# Print the result
plot_histogram(job_real.result().get_counts())
import numpy as np
from numpy import pi
# importing Qiskit
from qiskit import *
from qiskit.visualization import *
from qiskit.tools.monitor import backend_overview, backend_monitor, job_monitor
from qiskit.tools.visualization import plot_gate_map, plot_error_map
qftc = QuantumCircuit(3)
qftc.h(0)
qftc.draw(output='mpl')
qftc.cu1(2*pi/(2**2), 1, 0) # CROT from qubit 1 to qubit 0
qftc.draw(output='mpl')
qftc.cu1(2*pi/(2**3), 2, 0) # CROT from qubit 1 to qubit 0
qftc.draw(output='mpl')
qftc.h(1)
qftc.cu1(2*pi/(2**2), 2, 1) # CROT from qubit 2 to qubit 1
qftc.h(2)
qftc.draw(output='mpl')
# Complete the QFT circuit by reordering qubits (by exchanging qubit 1 and 3)
qftc.swap(0,2)
qftc.draw(output='mpl')
def qft_rotations(circuit, n):
if n == 0: # Exit function if circuit is empty
print("The number of qubits must be greater than 0")
return circuit
index = 0
circuit.h(index) # Apply the H-gate to the most significant qubit
index += 1
n -= 1
for qubit in range(n): # Apply the controlled rotations conditioned on n-1 qubits
# For each less significant qubit, we need to do a
# smaller-angled controlled rotation:
circuit.cu1(2*pi/2**(2+qubit), index + qubit, 0)
qc = QuantumCircuit(4)
qft_rotations(qc,4)
qc.draw(output = 'mpl')
def qft_rotations(circuit, n, start):
if n == 0: # Exit function if circuit is empty
return circuit
circuit.h(start) # Apply the H-gate to the most significant qubit
if start == n-1:
return circuit
for qubit in range(n-1-start): # Apply the controlled rotations conditioned on n-1 qubits
# For each less significant qubit, we need to do a
# smaller-angled controlled rotation:
circuit.cu1(2*pi/2**(2+qubit), start + 1 + qubit, start)
start += 1
circuit.barrier()
# Apply QFT recursively
qft_rotations(circuit, n, start)
qc = QuantumCircuit(5)
qft_rotations(qc,5,0)
qc.draw(output = 'mpl')
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
# Importing standard Qiskit libraries and configuring account
from qiskit import *
from qiskit.visualization import *
from qiskit.circuit import Parameter
# Simple example
# Define two parameters, t1 and t2
theta1 = Parameter('t1')
theta2 = Parameter('t2')
# Build a 1-qubit circuit
qc = QuantumCircuit(1, 1)
# First parameter, t1, is used for a single qubit rotation of a controlled qubit
qc.ry(theta1,0)
qc.rz(theta2,0)
qc.barrier()
qc.measure(0, 0)
qc.draw(output='mpl')
theta1_range = np.linspace(0, 2 * np.pi, 20)
theta2_range = np.linspace(0, np.pi, 2)
circuits = [qc.bind_parameters({theta1: theta_val1, theta2: theta_val2})
for theta_val2 in theta2_range for theta_val1 in theta1_range ]
# Visualize several circuits to check that correct circuits are generated correctly.
display(circuits[0].draw(output='mpl'))
display(circuits[1].draw(output='mpl'))
display(circuits[20].draw(output='mpl'))
# Execute multiple circuits
job = execute(qc, backend=Aer.get_backend('qasm_simulator'), shots = 8192,
parameter_binds=[{theta1: theta_val1, theta2: theta_val2}
for theta_val2 in theta2_range for theta_val1 in theta1_range])
# Store all counts
counts = [job.result().get_counts(i) for i in range(len(job.result().results))]
# Plot to visualize the result
plt.figure(figsize=(12,6))
plt.plot(range(len(theta1_range)*len(theta2_range)),
list(map(lambda counts: (counts.get('0',0)-counts.get('1',1))/8192,counts)))
plt.show()
# IBMQ.disable_account()
provider = IBMQ.enable_account('TOKEN')
from qiskit.tools.monitor import backend_overview, backend_monitor, job_monitor
from qiskit.tools.visualization import plot_gate_map, plot_error_map
# Retrieve IBM Quantum device information
backend_overview()
# Execute multiple circuits
job_exp = execute(qc, backend=provider.get_backend('ibmq_essex'), shots = 8192,
parameter_binds=[{theta1: theta_val1, theta2: theta_val2}
for theta_val2 in theta2_range for theta_val1 in theta1_range])
# Monitor job status
job_monitor(job_exp)
# Store all counts
counts_exp = [job_exp.result().get_counts(i) for i in range(len(job_exp.result().results))]
# Plot to visualize the result
plt.figure(figsize=(12,6))
plt.rcParams.update({'font.size': 16})
plt.plot(range(len(theta1_range)*len(theta2_range)),
list(map(lambda counts: (counts.get('0',0)-counts.get('1',1))/8192,counts)),'r',label='Simulation')
plt.plot(range(len(theta1_range)*len(theta2_range)),
list(map(lambda counts_exp: (counts_exp.get('0',0)-counts_exp.get('1',1))/8192,counts_exp)),
'b',label='Experiment')
plt.legend(loc='best')
plt.show()
from qiskit.compiler import transpile
from qiskit.transpiler import PassManager, Layout
display(plot_error_map(provider.get_backend('ibmqx2')))
display(plot_error_map(provider.get_backend('ibmq_burlington')))
# Create a dummy circuit for default transpiler demonstration
qc = QuantumCircuit(4)
qc.h(0)
qc.swap(0,1)
qc.cx(1,0)
qc.s(3)
qc.x(3)
qc.h(3)
qc.h(0)
qc.cx(0,2)
qc.ccx(0,1,2)
qc.h(0)
print('Original circuit')
display(qc.draw(output='mpl'))
# Transpile the circuit to run on ibmqx2
qt_qx2 = transpile(qc,provider.get_backend('ibmqx2'))
print('Transpiled circuit for ibmqx2')
display(qt_qx2.draw(output='mpl'))
# Transpile the circuit to run on ibmq_burlington
qt_bu = transpile(qc,provider.get_backend('ibmq_burlington'))
print('Transpiled circuit for ibmqx_Burlington')
display(qt_bu.draw(output='mpl'))
# Print out some circuit properties
# Total nunmber of operations
print("Number of operations for ibmqx2 = %s" % qt_qx2.size())
print("Number of operations for ibmq_burlington = %s \n" % qt_bu.size())
# Circuit depth
print("Circuit depth for ibmqx2 = %s" % qt_qx2.depth())
print("Circuit depth for ibmq_burlington = %s \n" % qt_bu.depth())
# Number of qubits
print("Number of qubits for ibmqx2 = %s" % qt_qx2.width())
print("Number of qubits for ibmq_burlington = %s \n" % qt_bu.width())
# Breakdown of operations by type
print("Operations for ibmqx2: %s" % qt_qx2.count_ops())
print("Operations for ibmq_burlington: %s \n" % qt_bu.count_ops())
# Number of unentangled subcircuits in this circuit.
# In principle, each subcircuit can be executed on a different quantum device.
print("Number of unentangled subcircuits for ibmqx2 = %s" % qt_qx2.num_tensor_factors())
print("Number of unentangled subcircuits for ibmq_burlington = %s" % qt_bu.num_tensor_factors())
qr = QuantumRegister(4,'q')
cr = ClassicalRegister(4,'c')
qc_test = QuantumCircuit(qr,cr)
qc_test.h(0)
for i in range(3):
qc_test.cx(i,i+1)
qc_test.barrier()
qc_test.measure(qr,cr)
qc_test.draw(output='mpl')
qc_t = transpile(qc_test, backend = provider.get_backend('ibmq_london'))
# Display transpiled circuit
display(qc_t.draw(output='mpl'))
# Display the qubit layout
display(plot_error_map(provider.get_backend('ibmq_london')))
# Print out some circuit properties
# Total nunmber of operations
print("Number of operations = %s" % qc_t.size())
# Circuit depth
print("Circuit depth = %s" % qc_t.depth())
# Execute the circuit on the qasm simulator.
job_test = execute(qc_test, provider.get_backend('ibmq_london'), shots=8192)
job_monitor(job_test)
# Customize the layout
layout = Layout({qr[0]: 4, qr[1]: 3, qr[2]: 1, qr[3]:0})
# Map it onto 5 qubit backend ibmqx2
qc_test_new = transpile(qc_test, backend = provider.get_backend('ibmq_london'), initial_layout=layout, basis_gates=['u1','u2','u3','cx'])
display(qc_test_new.draw(output='mpl'))
# Print out some circuit properties
# Total nunmber of operations
print("Number of operations = %s" % qc_test_new.size())
# Circuit depth
print("Circuit depth = %s" % qc_test_new.depth())
# Execute the circuit on the qasm simulator.
job_test_new = execute(qc_test_new, provider.get_backend('ibmq_london'), shots=8192)
job_monitor(job_test_new)
# Now, compare the two
result_test = job_test.result()
result_test_new = job_test_new.result()
# Plot both experimental and ideal results
plot_histogram([result_test.get_counts(qc_test),result_test_new.get_counts(qc_test_new)],
color=['green','blue'],legend=['default','custom'],figsize = [20,8])
# Apply 4-qubit controlled x gate
qr = QuantumRegister(5,'q')
qc = QuantumCircuit(qr)
qc.h(0)
qc.h(1)
qc.h(3)
qc.ccx(0,1,2)
qc.ccx(2,3,4)
qc.ccx(0,1,2)
display(qc.draw(output='mpl'))
# Print out some circuit properties
# Total nunmber of operations
print("Number of operations = %s \n" % qc.size())
# Count different types of operations
print("Operation counts = %s \n" % qc.count_ops())
# Circuit depth
print("Circuit depth = %s" % qc.depth())
qc_t = transpile(qc, provider.get_backend('ibmq_valencia'))
display(qc_t.draw(output='mpl'))
# Print out some circuit properties
# Total nunmber of operations
print("Number of operations = %s" % qc_t.size())
# Circuit depth
print("Circuit depth = %s" % qc_t.depth())
# Transpile many times (20 times in this example) and pick the best one
trial = 20
# Use ibmq_valencia for example
backend_exp = provider.get_backend('ibmq_valencia')
tcircs0 = transpile([qc]*trial, backend_exp, optimization_level=0)
tcircs1 = transpile([qc]*trial, backend_exp, optimization_level=1)
tcircs2 = transpile([qc]*trial, backend_exp, optimization_level=2)
tcircs3 = transpile([qc]*trial, backend_exp, optimization_level=3)
import matplotlib.pyplot as plt
num_cx0 = [c.count_ops()['cx'] for c in tcircs0]
num_cx1 = [c.count_ops()['cx'] for c in tcircs1]
num_cx2 = [c.count_ops()['cx'] for c in tcircs2]
num_cx3 = [c.count_ops()['cx'] for c in tcircs3]
num_tot0 = [c.size() for c in tcircs0]
num_tot1 = [c.size() for c in tcircs1]
num_tot2 = [c.size() for c in tcircs2]
num_tot3 = [c.size() for c in tcircs3]
num_depth0 = [c.depth() for c in tcircs0]
num_depth1 = [c.depth() for c in tcircs1]
num_depth2 = [c.depth() for c in tcircs2]
num_depth3 = [c.depth() for c in tcircs3]
plt.rcParams.update({'font.size': 16})
# Plot the number of CNOT gates
plt.figure(figsize=(12,6))
plt.plot(range(len(num_cx0)),num_cx0,'r',label='level 0')
plt.plot(range(len(num_cx1)),num_cx1,'b',label='level 1')
plt.plot(range(len(num_cx2)),num_cx2,'g',label='level 2')
plt.plot(range(len(num_cx3)),num_cx3,'k',label='level 3')
plt.legend(loc='upper left')
plt.xlabel('Random trial')
plt.ylabel('# of cx gates')
plt.show()
# Plot total number of gates
plt.figure(figsize=(12,6))
plt.plot(range(len(num_tot0)),num_tot0,'r',label='level 0')
plt.plot(range(len(num_tot1)),num_tot1,'b',label='level 1')
plt.plot(range(len(num_tot2)),num_tot2,'g',label='level 2')
plt.plot(range(len(num_tot3)),num_tot3,'k',label='level 3')
plt.legend(loc='upper left')
plt.xlabel('Random trial')
plt.ylabel('# of total gates')
plt.show()
# Plot the number of CNOT gates
plt.figure(figsize=(12,6))
plt.plot(range(len(num_depth0)),num_depth0,'r',label='level 0')
plt.plot(range(len(num_depth1)),num_depth1,'b',label='level 1')
plt.plot(range(len(num_depth2)),num_depth2,'g',label='level 2')
plt.plot(range(len(num_depth3)),num_depth3,'k',label='level 3')
plt.legend(loc='upper left')
plt.xlabel('Random trial')
plt.ylabel('Circuit depth')
plt.show()
print('Opt0: Minimum # of cx gates = %s' % min(num_cx0))
print('Opt0: The best circuit is the circut %s \n' % num_cx0.index(min(num_cx0)))
print('Opt1: Minimum # of cx gates = %s' % min(num_cx1))
print('Opt1: The best circuit is the circut %s \n' % num_cx1.index(min(num_cx1)))
print('Opt2: Minimum # of cx gates = %s' % min(num_cx2))
print('Opt2: The best circuit is the circut %s \n' % num_cx2.index(min(num_cx2)))
print('Opt3: Minimum # of cx gates = %s' % min(num_cx3))
print('Opt3: The best circuit is the circut %s' % num_cx3.index(min(num_cx3)))
|
https://github.com/dkp-quantum/Tutorials
|
dkp-quantum
|
# If you already have saved IBM credentials with previous version,
# update your credentials that is stored in disk
from qiskit import IBMQ
IBMQ.update_account()
# import
from qiskit import *
import numpy as np
from qiskit.visualization import plot_histogram, plot_state_city, plot_state_paulivec
from qiskit.quantum_info import Pauli, state_fidelity, basis_state, process_fidelity
from qiskit.tools.monitor import backend_overview, backend_monitor, job_monitor
# Create a quantum register with 2 qubits
q = QuantumRegister(2,'q')
# Form a quantum circuit
# Note that the circuit name is optional
qc = QuantumCircuit(q,name="first_qc")
# Display the quantum circuit
qc.draw()
# Create a classical register with 2 bits
c = ClassicalRegister(2,'c')
meas = QuantumCircuit(q,c,name="first_m")
meas.barrier(q)
meas.measure(q[0], c[0])
meas.measure(q[1], c[1])
#meas.measure(q[3], c[3])
#meas.measure(q[4], c[4])
meas.draw()
# Add a x gate on qubit 0.
qc.x(0)
# Add a Hadamard gate on qubit 0, putting this in superposition.
qc.h(0)
# Add a CX (CNOT) gate on control qubit 0
# and target qubit 1 to create an entangled state.
qc.cx(0, 1)
qc.draw()
# Quantum circuits can be added with + operations
# Add two pre-defined circuits
qc_comp=qc+meas
qc_comp.draw()
# Draw the quantum circuit in a different (slightly better) format
qc_comp.draw(output='mpl')
# Create the quantum circuit with the measurement in one go.
qc_tot = QuantumCircuit(q,c,name="2q_all")
qc_tot.x(0)
qc_tot.h(0)
qc_tot.cx(0,1)
qc_tot.barrier()
qc_tot.measure(0,0)
qc_tot.measure(1,1)
qc_tot.draw(output='mpl')
# Use Aer's qasm_simulator
backend_q = Aer.get_backend('qasm_simulator')
# Execute the circuit on the qasm simulator.
# We've set the number of repeats of the circuit
# to be 1024, which is default.
job_sim1 = execute(qc_comp, backend_q, shots=1024)
job_sim1.status()
# Grab the results from the job.
result_sim1 = job_sim1.result()
result_sim1
result_sim1.get_counts(qc_comp)
plot_histogram(result_sim1.get_counts(qc_comp))
# Use Aer's statevector_simulator
backend_sv = Aer.get_backend('statevector_simulator')
# Execute the circuit on the statevector simulator.
job_sim2 = execute(qc, backend_sv)
# Grab the results from the job.
result_sim2 = job_sim2.result()
# Output the entire result
job_sim2.result()
# See output state as a vector
outputstate = result_sim2.get_statevector(qc, decimals=5)
print(outputstate)
# Visualize density matrix
plot_state_city(outputstate)
# Examine state fidelity, compare with a basis state |111>
sf1=state_fidelity(basis_state('11', 2), outputstate)
# Examine state fidelity w.r.t the desired state
desired_state=[1,0,0,-1]/np.sqrt(2)
sf2=state_fidelity(desired_state, outputstate)
print(sf1)
print(sf2)
# Create a quantum register with 4 qubits
q4 = QuantumRegister(4,'q')
# Create classical registers for measurement
c4 = ClassicalRegister(4,'c')
# Form a quantum circuit
# Note that the circuit name is optional
ex1_qc = QuantumCircuit(q4,c4,name="ex1")
# Display the quantum circuit
ex1_qc.draw()
# Add gates to the quantum circuit
ex1_qc.h(0)
ex1_qc.cx(0,1)
ex1_qc.cx(0,2)
ex1_qc.cx(0,3)
# Measurement
ex1_qc.barrier()
ex1_qc.measure(0,0)
ex1_qc.measure(1,1)
ex1_qc.measure(2,2)
ex1_qc.measure(3,3)
ex1_qc.draw(output='mpl')
# Simpler code
ex1_qc = QuantumCircuit(q4,c4,name="first_m")
# Gates
ex1_qc.h(0)
for i in range(3):
ex1_qc.cx(0,i+1)
# Measurement
ex1_qc.barrier()
for i in range(4):
ex1_qc.measure(i,i)
ex1_qc.draw(output='mpl')
# Use Aer's qasm_simulator
backend_q = Aer.get_backend('qasm_simulator')
# Execute the circuit on the qasm simulator.
# We've set the number of repeats of the circuit
# to be 1024, which is default.
job_ex1 = execute(ex1_qc, backend_q, shots=1024)
plot_histogram(job_ex1.result().get_counts(ex1_qc))
# Create a simple quantum register with 2 qubit
# to examine unitary simulator
qu2 = QuantumRegister(2,'qu')
# Form a quantum circuit
# Note that the circuit name is optional
qu = QuantumCircuit(qu2,name="unitary_qc")
# Add a single qubit rotation
qu.z(0)
qu.z(1)
# Display the quantum circuit
qu.draw(output='mpl')
# Use Aer's unitary_simulator
backend_u = Aer.get_backend('unitary_simulator')
# Execute the circuit on the unitary simulator.
job_usim = execute(qu, backend_u)
# Grab the results from the job.
result_usim = job_usim.result()
result_usim
# Output the unitary matrix
unitary = result_usim.get_unitary(qu)
print('%s\n' % unitary)
# Check process fidelity
pf1=process_fidelity(Pauli(label='IX').to_matrix(), unitary)
pf2=process_fidelity(Pauli(label='ZZ').to_matrix(), unitary)
print('%s\n' % pf1)
print('%s\n' % pf2)
from qiskit.quantum_info import process_fidelity
def compare_qc(qc_ref,qc_test):
# Use Aer's unitary_simulator
backend_u = Aer.get_backend('unitary_simulator')
# Output the refernce unitary matrix
u_ref = execute(qc_ref,backend_u).result().get_unitary(qc_ref)
# Output the test unitary matrix
u_test = execute(qc_test,backend_u).result().get_unitary(qc_test)
return process_fidelity(u_ref,u_test)
# Create a reference circuit
swap_c_ref = QuantumCircuit(2)
swap_c_ref.swap(0,1)
display(swap_c_ref.draw(output='mpl'))
# Create a test circuit with 3 cnot gates instead of a swap gate
swap_c_test = QuantumCircuit(2)
swap_c_test.cx(0,1)
swap_c_test.cx(1,0)
swap_c_test.cx(0,1)
display(swap_c_test.draw(output='mpl'))
# Compare two unitaries
compare_qc(swap_c_ref,swap_c_test)
from qiskit.quantum_info import state_fidelity
def compare_sv(qc_ref,qc_test):
# Use Aer's unitary_simulator
backend_v = Aer.get_backend('statevector_simulator')
# Output the refernce unitary matrix
sv_ref = execute(qc_ref,backend_v).result().get_statevector(qc_ref,decimals=7)
# Output the test unitary matrix
sv_test = execute(qc_test,backend_v).result().get_statevector(qc_test,decimals=7)
return state_fidelity(sv_ref,sv_test)
import random as r
# Apply a random 1-qubit rotation around x and y
ay = r.random()*np.pi
ax = r.random()*np.pi
# Create a circuit for preparing an initial state
swap_c_init = QuantumCircuit(3)
swap_c_init.h(0)
swap_c_init.ry(ay,1)
swap_c_init.rx(ax,2)
display(swap_c_init.draw(output='mpl'))
# Create a reference circuit
cswap_c_ref = QuantumCircuit(3)
cswap_c_ref.append(swap_c_init,[0,1,2])
cswap_c_ref.cswap(0,1,2)
display(cswap_c_ref.draw(output='mpl'))
# Create a test circuit with 3 cnot gates instead of a swap gate
cswap_c_test = QuantumCircuit(3)
cswap_c_test.append(swap_c_init,[0,1,2])
cswap_c_test.cx(2,1)
cswap_c_test.ccx(0,1,2)
cswap_c_test.cx(2,1)
display(cswap_c_test.draw(output='mpl'))
# Compare two states
compare_sv(cswap_c_ref,cswap_c_test)
# Measure an expectation value of a Pauli observable
Z = np.array([[1, 0], [0, -1]])
X = np.array([[0, 1], [1, 0]])
Y = np.array([[0, -1j], [1j, 0]])
ZZ=np.kron(Z,Z)
XX=np.kron(X,X)
# Or use qiskit's built-in function to define Pauli matrices
ZI = Pauli(label='ZI').to_matrix()
XI = Pauli(label='XI').to_matrix()
YI = Pauli(label='YI').to_matrix()
# Create some functions for measuring expectation values
# For pure states
def expectation_state(state, Operator):
return np.dot(state.conj(), np.dot(Operator, state))
# For density matrices
def expectation_density(density, Operator):
return np.trace(Operator @ density)
# We'll use statevector simulator, so no need to define classical registers
q2 = QuantumRegister(2,'q')
# Create a quantum circuit for 00 + 11 state
ex2_qc1 = QuantumCircuit(q2)
ex2_qc1.h(0)
ex2_qc1.cx(0,1)
# Create a quantum circuit for 00 - 11 state
ex2_qc2 = QuantumCircuit(q2)
ex2_qc2.x(0)
ex2_qc2.h(0)
ex2_qc2.cx(0,1)
print('00+11 circuit:')
display(ex2_qc1.draw(output='mpl'))
print('00-11 circuit:')
display(ex2_qc2.draw(output='mpl'))
# Use Aer's statevector_simulator
backend_sv = Aer.get_backend('statevector_simulator')
# Execute the first circuit on the statevector simulator.
job_ex2_1 = execute(ex2_qc1, backend_sv)
output1 = job_ex2_1.result().get_statevector(ex2_qc1, decimals=5)
# Execute the second circuit on the statevector simulator.
job_ex2_2 = execute(ex2_qc2, backend_sv)
output2 = job_ex2_2.result().get_statevector(ex2_qc2, decimals=5)
# Measure the expectation values
zz1 = expectation_state(output1,ZZ)
zz2 = expectation_state(output2,ZZ)
xx1 = expectation_state(output1,XX)
xx2 = expectation_state(output2,XX)
print('<ZZ> on circuit 1 = %s' % zz1)
print('<ZZ> on circuit 2 = %s' % zz2)
print('<XX> on circuit 1 = %s' % xx1)
print('<XX> on circuit 2 = %s' % xx2)
IBMQ.enable_account('YOUR_TOKEN')
print(IBMQ.stored_account())
print(IBMQ.active_account())
my_provider=IBMQ.get_provider()
my_provider.backends()
# Retrieve IBM Quantum device information
backend_overview()
backend_qx2 = my_provider.get_backend('ibmqx2')
backend_vigo = my_provider.get_backend('ibmq_vigo')
backend_vigo.properties()
# Retrieve a specific IBM Quantum device information
# ibmq_16_melbourne as an example
backend_mel = my_provider.get_backend('ibmq_16_melbourne')
backend_monitor(backend_mel)
# Let's look at one more example
backend_qx2 = my_provider.get_backend('ibmqx2')
backend_monitor(backend_qx2)
# Create a 3-qubit GHZ state
ghz3_q = QuantumRegister(3,'q')
ghz3_c = ClassicalRegister(3,'c')
ghz3= QuantumCircuit(ghz3_q,ghz3_c)
ghz3.h(0)
ghz3.cx(0,1)
ghz3.cx(0,2)
ghz3.barrier()
for i in range(3):
ghz3.measure(i,i)
ghz3.draw(output='mpl')
# Define backend as one of the real devices (5-qubit systems for now)
backend_vigo = my_provider.get_backend('ibmq_vigo')
backend_es = my_provider.get_backend('ibmq_essex')
backend_ou = my_provider.get_backend('ibmq_ourense')
# Run 3-qubit GHZ experiment on a 5-qubit device (try vigo)
job_exp = execute(ghz3, backend=backend_vigo)
job_monitor(job_exp)
# Grab experimental results
result_vigo = job_exp.result()
counts_vigo = result_vigo.get_counts(ghz3)
plot_histogram(counts_vigo)
# Finally, run the same experiment on the 14-qubit device.
job_exp2 = execute(ghz3, backend=backend_mel)
job_monitor(job_exp2)
# Grab experimental results
result_mel = job_exp2.result()
counts_mel = result_mel.get_counts(ghz3)
plot_histogram(counts_mel)
# Now, compare to theory by running it on qasm_simulator
job_qasm = execute(ghz3,backend=backend_q)
result_qasm = job_qasm.result()
counts_qasm = result_qasm.get_counts(ghz3)
# Plot both experimental and ideal results
plot_histogram([counts_qasm,counts_vigo,counts_mel],
color=['black','green','blue'],
legend=['QASM','Vigo','Melbourne'])
import random as r
# Define a 3-qubit circuit with 3 classical registers
qtel = QuantumCircuit(3,3)
# Apply a random 1-qubit rotation around y
a1 = r.random()*np.pi
a2 = r.random()*np.pi
qtel.ry(a1,0)
qtel.rz(a2,0)
qtel.barrier()
qtel.draw(output='mpl')
# Prepare a 2-qubit bell state
qtel.h(1)
qtel.cx(1,2)
qtel.draw(output='mpl')
# Apply bell measurement on qubit 0 and 1
qtel.cx(0,1)
qtel.h(0)
qtel.barrier()
qtel.measure([0, 1],[0, 1])
qtel.draw(output='mpl')
# Apply controlled gates to complete the teleportation
qtel.barrier()
qtel.cx(1,2)
qtel.cz(0,2)
qtel.draw(output='mpl')
# Check the answer by applying the inverse unitary
qtel.rz(-a2,2)
qtel.ry(-a1,2)
qtel.measure(2,2)
print('Quantum teleportation circuit:')
qtel.draw(output='mpl')
# n is the number of shots
n=10000
job_qtel = execute(qtel, backend_q, shots=n)
display(plot_histogram(job_qtel.result().get_counts(qtel)))
qtel_c = job_qtel.result().get_counts(qtel)
print(qtel_c)
# Simple example
from qiskit.circuit import Parameter
# Define two parameters, t1 and t2
theta1 = Parameter('t1')
theta2 = Parameter('t2')
# Build a 5-qubit circuit
qc = QuantumCircuit(3, 1)
# First parameter, t1, is used for a single qubit rotation of a controlled qubit
qc.ry(theta1,0)
for i in range(2):
qc.cx(i, i+1)
qc.barrier()
# Second parameter, t2, is used here
qc.rz(theta2,range(3))
qc.barrier()
for i in reversed(range(2)):
qc.cx(i, i+1)
qc.ry(theta1,0)
qc.measure(0, 0)
qc.draw(output='mpl')
theta1_range = np.linspace(0, np.pi/2, 2)
theta2_range = np.linspace(0, 2 * np.pi, 16)
circuits = [qc.bind_parameters({theta1: theta_val1, theta2: theta_val2})
for theta_val1 in theta1_range for theta_val2 in theta2_range ]
# Visualize several circuits to check that correct circuits are generated correctly.
display(circuits[0].draw(output='mpl'))
display(circuits[1].draw(output='mpl'))
display(circuits[16].draw(output='mpl'))
# Execute multiple circuits
job = execute(qc, backend=Aer.get_backend('qasm_simulator'),
parameter_binds=[{theta1: theta_val1, theta2: theta_val2}
for theta_val1 in theta1_range for theta_val2 in theta2_range])
# Store all counts
counts = [job.result().get_counts(i) for i in range(len(job.result().results))]
# Plot to visualize the result
import matplotlib.pyplot as plt
plt.figure(figsize=(12,6))
plt.plot(range(len(theta1_range)*len(theta2_range)),
list(map(lambda counts: (counts.get('0',0)-counts.get('1',1))/1024,counts)))
plt.show()
# Exercise 4. a)
# Create the measurement circuit
m_ZZI = QuantumCircuit(4,1)
m_ZZI.h(3)
m_ZZI.cz(3,0)
m_ZZI.cz(3,1)
m_ZZI.h(3)
m_ZZI.barrier()
m_ZZI.measure(3,0)
m_ZZI.draw(output='mpl')
#
#m_ZIZ = QuantumCircuit(4,1)
#m_ZIZ.h(3)
#m_ZIZ.cz(3,0)
#m_ZIZ.cz(3,2)
#m_ZIZ.h(3)
#m_ZIZ.barrier()
#m_ZIZ.measure(3,0)
#display(m_ZIZ.draw(output='mpl'))
# Exercise 4. a)
# Create the state preparation circuit for a|000> + b|111> and a|010> + b|101>
# for various values of a & b
from qiskit.circuit import Parameter
# Define parameter t1 and t2
theta1 = Parameter('t1')
theta2 = Parameter('t2')
qs_a = QuantumCircuit(4,1)
qs_a.ry(theta1,0)
qs_a.cx(0,1)
qs_a.cx(0,2)
qs_a.ry(theta2,1)
qs_a.barrier()
display(qs_a.draw(output='mpl'))
# Add state prep. and measurement circuits
qc_ZZI = qs_a+m_ZZI
qc_ZZI.draw(output='mpl')
theta1_range = np.linspace(0, np.pi, 16)
theta2_range = np.linspace(0, np.pi, 2)
# Bind parameters and create multiple circuits
# Test for various a & b for a|000> + b|111> first,
# then vary the amplitudes for a|010> + b|101> :
# Fix theta2 first, and vary theta1:
circuits_ZZI = [qc_ZZI.bind_parameters({theta1: theta_val1, theta2: theta_val2})
for theta_val2 in theta2_range for theta_val1 in theta1_range ]
# Execute multiple circuits
job_ZZI = execute(circuits_ZZI, backend=Aer.get_backend('qasm_simulator'))
# Store all counts
counts_ZZI = [job_ZZI.result().get_counts(i) for i in range(len(job_ZZI.result().results))]
# Plot to visualize the result
import matplotlib.pyplot as plt
plt.figure(figsize=(12,6))
plt.plot(range(len(theta1_range)*len(theta2_range)),
list(map(lambda counts_ZZI: (counts_ZZI.get('0',0)-counts_ZZI.get('1',1))/1024, counts_ZZI)))
plt.show()
# Exercise 4. b)
# Create the measurement circuit
m_XXI = QuantumCircuit(4,1)
m_XXI.h(3)
m_XXI.cx(3,0)
m_XXI.cx(3,1)
m_XXI.h(3)
m_XXI.barrier()
m_XXI.measure(3,0)
m_XXI.draw(output='mpl')
#
#m_XIX = QuantumCircuit(4,1)
#m_XIX.h(3)
#m_XIX.cx(3,0)
#m_XIX.cx(3,2)
#m_XIX.h(3)
#m_XIX.barrier()
#m_XIX.measure(3,0)
#display(m_XIX.draw(output='mpl'))
# Exercise 4. b)
# Create the state preparation circuit for a|+++> + b|---> and a|+-+> + b|-+->
# for various values of a & b
qs_b = QuantumCircuit(4,1)
qs_b.ry(theta1,0)
qs_b.cx(0,1)
qs_b.cx(0,2)
for i in range(3):
qs_b.h(i)
# To flip |+> to |->, we need a phase flip gate
qs_b.rz(theta2,1)
qs_b.barrier()
display(qs_b.draw(output='mpl'))
# Add state prep. and measurement circuits
qc_XXI = qs_b+m_XXI
qc_XXI.draw(output='mpl')
# Bind parameters and create multiple circuits
# Test for various a & b for a|000> + b|111> first,
# then vary the amplitudes for a|010> + b|101> :
# Fix theta2 first, and vary theta1:
circuits_XXI = [qc_XXI.bind_parameters({theta1: theta_val1, theta2: theta_val2})
for theta_val2 in theta2_range for theta_val1 in theta1_range ]
# Execute multiple circuits
job_XXI = execute(circuits_XXI, backend=Aer.get_backend('qasm_simulator'))
# Store all counts
counts_XXI = [job_XXI.result().get_counts(i) for i in range(len(job_XXI.result().results))]
# Plot to visualize the result
plt.figure(figsize=(12,6))
plt.plot(range(len(theta1_range)*len(theta2_range)),
list(map(lambda counts_XXI: (counts_XXI.get('0',0)-counts_XXI.get('1',1))/1024, counts_XXI)))
plt.show()
# Create a quantum register with 3 qubits
q = QuantumRegister(3,'q')
# Form a quantum circuit
qent = QuantumCircuit(q)
qent.initialize([1, 0, 0, 0, 0, 0, 0, 1] / np.sqrt(2), [q[0], q[1], q[2]])
# Display the quantum circuit
qent.draw(output='mpl')
# Use Aer's state vector simulator
backend_sv = Aer.get_backend('statevector_simulator')
# Execute and plot output state
output_ent = execute(qent, backend_sv).result().get_statevector(0, decimals=3)
plot_state_city(output_ent)
# Build a sub-circuit
# sub_ghz(n,c,t) creates a quantum circuit for creating an n-qubit GHZ state.
# n is the total number of qubits, c is an index for a control qubit, t is a vector of indices for target qubits.
def sub_ghz(n,c,t):
sub_q = QuantumRegister(n)
sub_circ = QuantumCircuit(sub_q, name='sub_ghz')
sub_circ.h(c)
for i in t:
sub_circ.cx(c,i)
return sub_circ
# Create a sub-circuit for 3-qubit GHZ state prep.
sub_ghz3 = sub_ghz(3,0,[1,2])
sub_inst3 = sub_ghz3.to_instruction()
# Create a sub-circuit consisting of T gate and cnot.
sub_tcnot = QuantumCircuit(QuantumRegister(2),name='t+cnot')
sub_tcnot.t(0)
sub_tcnot.cx(0,1)
q = QuantumRegister(5, 'q')
circ = QuantumCircuit(q)
# Now create a quantum circuit using sub-circuits.
# Apply Hadamard on all gates.
for i in range(5):
circ.h(i)
#
circ.barrier()
# Appy 2-qubit GHZ preparation on qubits 0 and 1, and on qubits 3 and 4.
circ.append(sub_tcnot, [q[0],q[1]])
circ.append(sub_tcnot, [q[3], q[4]])
#
circ.barrier()
# Apply 3-qubit GHZ preparation on all 3 neighbouring qubits.
for i in range(3):
circ.append(sub_inst3, [q[i], q[i+1],q[i+2]])
circ.draw(output='mpl')
# We can also decompose the circuit that is constructed using sub-circuits.
circ.decompose().draw(output='mpl')
# Reset operation forces the target qubit to go to |0>
q = QuantumRegister(1)
c = ClassicalRegister(1)
qc = QuantumCircuit(q, c)
qc.h(q)
qc.reset(0)
qc.measure(q, c)
display(qc.draw(output='mpl'))
# Test the result
job = execute(qc, backend=Aer.get_backend('qasm_simulator'), shots=1024)
job.result().get_counts(qc)
# Controlled qubit operation, controlled by classical bits
# This could be useful for designing a post-selection scheme of a quantum algorithm
q2 = QuantumRegister(2,'q')
cont = ClassicalRegister(1,'cont')
qc = QuantumCircuit(q2,cont)
qc.x(0)
# Swap qubits 1 and 2 if the classical bit is 0
qc.swap(0,1).c_if(cont, 0)
qc.measure(0,cont)
display(qc.draw(output='mpl'))
job = execute(qc, backend=Aer.get_backend('qasm_simulator'), shots=1024)
print(job.result().get_counts(qc))
from qiskit.compiler import transpile
from qiskit.transpiler import PassManager, Layout
from qiskit.tools.visualization import plot_gate_map
# Let's take a look at the layout of physical devices with the gate directions
display(plot_gate_map(backend_qx2,plot_directed=True))
display(plot_gate_map(my_provider.get_backend('ibmq_burlington'),plot_directed=True))
display(plot_gate_map(my_provider.get_backend('ibmq_london'),plot_directed=True))
# Create a dummy circuit for default transpiler demonstration
qr = QuantumRegister(3)
cr = ClassicalRegister(3)
qc = QuantumCircuit(qr,cr)
qc.h(0)
qc.swap(0,1)
qc.cx(1,0)
qc.s(2)
qc.x(2)
qc.h(2)
qc.measure(qr[2],cr[2])
qc.h(0)
qc.cx(0,1)
qc.cx(0,1)
qc.h(0)
qc.measure(qr[0],cr[0])
qc.measure(qr[1],cr[1])
print('Original circuit')
display(qc.draw(output='mpl'))
# Transpile the circuit to run on ibmqx2
qt_qx4 = transpile(qc,backend_qx2)
print('Transpiled circuit for ibmqx2')
display(qt_qx4.draw(output='mpl'))
# Transpile the circuit to run on ibmq_burlington
qt_ou = transpile(qc,my_provider.get_backend('ibmq_burlington'))
print('Transpiled circuit for ibmqx_Burlington')
display(qt_ou.draw(output='mpl'))
qr = QuantumRegister(5,'q')
qc = QuantumCircuit(qr)
qc.h(0)
for i in range(4):
qc.cx(0,i+1)
qc.draw(output='mpl')
qc_t = transpile(qc, basis_gates=['u1','u2','u3','cx'])
# Display transpiled circuit
display(qc_t.draw(output='mpl'))
# Print out some circuit properties
# Total nunmber of operations
print("Number of operations = %s" % qc_t.size())
# Circuit depth
print("Circuit depth = %s" % qc_t.depth())
# Number of qubits
print("Number of qubits = %s" % qc_t.width())
# Breakdown of operations by type
print("Operations: %s" % qc_t.count_ops())
# Number of unentangled subcircuits in this circuit.
# In principle, each subcircuit can be executed on a different quantum device.
print("Number of unentangled subcircuits = %s" % qc_t.num_tensor_factors())
# Map it onto 5 qubit backend ibmqx2
qc_qx2 = transpile(qc, backend_qx2, basis_gates=['u1','u2','u3','cx'])
display(qc_qx2.draw(output='mpl'))
display(plot_gate_map(backend_qx2,plot_directed=True))
# Print out some circuit properties
# Total nunmber of operations
print("Number of operations = %s" % qc_qx2.size())
# Circuit depth
print("Circuit depth = %s" % qc_qx2.depth())
# Map it onto 5 qubit backend ibmq_vigo
qc_vigo = transpile(qc, backend_vigo,basis_gates=['u1','u2','u3','cx'])
display(qc_vigo.draw(output='mpl'))
display(plot_gate_map(backend_vigo,plot_directed=True))
# Print out some circuit properties
# Total nunmber of operations
print("Number of operations = %s" % qc_vigo.size())
# Circuit depth
print("Circuit depth = %s" % qc_vigo.depth())
# Customize the layout
layout = Layout({qr[0]: 2, qr[1]: 1, qr[2]: 0, qr[3]:3, qr[4]:4})
# Map it onto 5 qubit backend ibmqx2
qc_qx2_new = transpile(qc, backend_qx2, initial_layout=layout,basis_gates=['u1','u2','u3','cx'])
display(qc_qx2_new.draw(output='mpl'))
# Print out some circuit properties
# Total nunmber of operations
print("Number of operations = %s" % qc_qx2_new.size())
# Circuit depth
print("Circuit depth = %s" % qc_qx2_new.depth())
# Test transpilation with a 5-qubit circuit including a Toffoli gate
qr = QuantumRegister(5,'q')
qccx = QuantumCircuit(qr)
qccx.h(0)
qccx.ccx(1,2,3)
qccx.x(4)
qccx.cz(0,4)
display(qccx.draw(output='mpl'))
print('Decompose in terms of a one and two qubit universal gate set')
display(qccx.decompose().draw(output='mpl'))
# Check device properties.
# The device information such as gate error and T1 and T2 also should be considered
# when picking a device for a given quantum circuit.
display(plot_gate_map(my_provider.get_backend('ibmq_vigo'),plot_directed=True))
backend_monitor(my_provider.get_backend('ibmq_vigo'))
# Customize the layout 5 qubit backend ibmq_vigo
layout = Layout({qr[0]: 1, qr[1]: 2, qr[2]: 3, qr[3]:0, qr[4]:4})
# Map it onto 5 qubit backend ibmq_vigo without changing the layout
qccx_vigo_naive = transpile(qccx, backend_vigo,basis_gates=['u1','u2','u3','cx'])
# Map it onto 5 qubit backend ibmq_vigo with the above layout
qccx_vigo_layout = transpile(qccx, backend_vigo, initial_layout=layout,basis_gates=['u1','u2','u3','cx'])
display(qccx_vigo_naive.draw(output='mpl'))
# Print out some circuit properties for the circuit without layout change
print("Circuit complexity when transpiled without layout change:")
print("Number of operations = %s" % qccx_vigo_naive.size())
print("Circuit depth = %s" % qccx_vigo_naive.depth())
print("Number of cx operations = %s" % qccx_vigo_naive.count_ops()['cx'])
display(qccx_vigo_layout.draw(output='mpl'))
# Print out some circuit properties for the circuit with layout change
print("Circuit complexity when transpiled with layout change:")
print("Number of operations = %s" % qccx_vigo_layout.size())
print("Circuit depth = %s" % qccx_vigo_layout.depth())
print("Number of cx operations = %s" % qccx_vigo_layout.count_ops()['cx'])
# Apply 4-qubit controlled x gate
qr = QuantumRegister(5,'q')
c4z = QuantumCircuit(qr)
c4z.h(0)
c4z.h(1)
c4z.h(3)
c4z.ccx(0,1,2)
c4z.ccx(2,3,4)
c4z.ccx(0,1,2)
display(c4z.draw(output='mpl'))
# Print out some circuit properties
# Total nunmber of operations
print("Number of operations = %s" % c4z.size())
# Count different types of operations
print("Operation counts = %s" % c4z.count_ops())
# Circuit depth
print("Circuit depth = %s" % c4z.depth())
backend_london = my_provider.get_backend('ibmq_london')
c4z_t = transpile(c4z, backend_london)
display(c4z_t.draw(output='mpl'))
# Print out some circuit properties
# Total nunmber of operations
print("Number of operations = %s" % c4z_t.size())
# Count different types of operations
print("Operation counts = %s" % c4z_t.count_ops())
# Circuit depth
print("Circuit depth = %s" % c4z_t.depth())
# Transpile many times (100 times in this example) and pick the best one
# Use ibmq_london for example
tcircs0 = transpile([c4z]*20, backend_london,optimization_level=0)
tcircs1 = transpile([c4z]*20, backend_london,optimization_level=1)
tcircs2 = transpile([c4z]*20, backend_london,optimization_level=2)
tcircs3 = transpile([c4z]*20, backend_london,optimization_level=3)
import matplotlib.pyplot as plt
num_cx0 = [c.count_ops()['cx'] for c in tcircs0]
num_cx1 = [c.count_ops()['cx'] for c in tcircs1]
num_cx2 = [c.count_ops()['cx'] for c in tcircs2]
num_cx3 = [c.count_ops()['cx'] for c in tcircs3]
num_tot0 = [c.size() for c in tcircs0]
num_tot1 = [c.size() for c in tcircs1]
num_tot2 = [c.size() for c in tcircs2]
num_tot3 = [c.size() for c in tcircs3]
num_depth0 = [c.depth() for c in tcircs0]
num_depth1 = [c.depth() for c in tcircs1]
num_depth2 = [c.depth() for c in tcircs2]
num_depth3 = [c.depth() for c in tcircs3]
plt.rcParams.update({'font.size': 16})
# Plot the number of CNOT gates
plt.figure(figsize=(12,6))
plt.plot(range(len(num_cx0)),num_cx0,'r',label='level 0')
plt.plot(range(len(num_cx1)),num_cx1,'b',label='level 1')
plt.plot(range(len(num_cx2)),num_cx2,'g',label='level 2')
plt.plot(range(len(num_cx3)),num_cx3,'k',label='level 3')
plt.legend(loc='upper left')
plt.xlabel('Random trial')
plt.ylabel('# of cx gates')
plt.show()
# Plot total number of gates
plt.figure(figsize=(12,6))
plt.plot(range(len(num_tot0)),num_tot0,'r',label='level 0')
plt.plot(range(len(num_tot1)),num_tot1,'b',label='level 1')
plt.plot(range(len(num_tot2)),num_tot2,'g',label='level 2')
plt.plot(range(len(num_tot3)),num_tot3,'k',label='level 3')
plt.legend(loc='upper left')
plt.xlabel('Random trial')
plt.ylabel('# of total gates')
plt.show()
# Plot the number of CNOT gates
plt.figure(figsize=(12,6))
plt.plot(range(len(num_depth0)),num_depth0,'r',label='level 0')
plt.plot(range(len(num_depth1)),num_depth1,'b',label='level 1')
plt.plot(range(len(num_depth2)),num_depth2,'g',label='level 2')
plt.plot(range(len(num_depth3)),num_depth3,'k',label='level 3')
plt.legend(loc='upper left')
plt.xlabel('Random trial')
plt.ylabel('Circuit depth')
plt.show()
print('Opt0: Minimum # of cx gates = %s' % min(num_cx0))
print('Opt0: The best circuit is the circut %s' % num_cx0.index(min(num_cx0)))
print('Opt1: Minimum # of cx gates = %s' % min(num_cx1))
print('Opt1: The best circuit is the circut %s' % num_cx1.index(min(num_cx1)))
print('Opt2: Minimum # of cx gates = %s' % min(num_cx2))
print('Opt2: The best circuit is the circut %s' % num_cx2.index(min(num_cx2)))
print('Opt3: Minimum # of cx gates = %s' % min(num_cx3))
print('Opt3: The best circuit is the circut %s' % num_cx3.index(min(num_cx3)))
|
https://github.com/dkp-quantum/Tutorials
|
dkp-quantum
|
%matplotlib inline
# Importing standard Qiskit libraries and configuring account
from qiskit import *
from qiskit.visualization import *
import numpy as np
# Create a quantum register with 2 qubits
q = QuantumRegister(2,'q')
# Form a quantum circuit
# Note that the circuit name is optional
qc = QuantumCircuit(q,name="first_qc")
# Display the quantum circuit
qc.draw()
# Add a Hadamard gate on qubit 0, putting this in superposition.
qc.h(0)
# Add a CX (CNOT) gate on control qubit 0
# and target qubit 1 to create an entangled state.
qc.cx(0, 1)
qc.draw()
# Create a classical register with 2 bits
c = ClassicalRegister(2,'c')
meas = QuantumCircuit(q,c,name="first_m")
meas.barrier(q)
meas.measure(q, c)
meas.draw()
# Quantum circuits can be added with + operations
# Add two pre-defined circuits
qc_all=qc+meas
qc_all.draw()
# Draw the quantum circuit in a different (slightly better) format
qc_all.draw(output='mpl')
# Create the quantum circuit with the measurement in one go.
qc_all = QuantumCircuit(q,c,name="2q_all")
qc_all.h(0)
qc_all.cx(0,1)
qc_all.barrier()
qc_all.measure(0,0)
qc_all.measure(1,1)
qc_all.draw(output='mpl')
# Use Aer's qasm_simulator
backend_q = Aer.get_backend('qasm_simulator')
# Execute the circuit on the qasm simulator.
job_sim1 = execute(qc_all, backend_q, shots=4096)
job_sim1.status()
# Grab the results from the job.
result_sim1 = job_sim1.result()
result_sim1
result_sim1.get_counts(qc_all)
plot_histogram(result_sim1.get_counts(qc_all))
# Use Aer's statevector_simulator
backend_sv = Aer.get_backend('statevector_simulator')
# Execute the circuit on the statevector simulator.
# It is important to note that the measurement has been excluded
job_sim2 = execute(qc, backend_sv)
# Grab the results from the job.
result_sim2 = job_sim2.result()
# Output the entire result
result_sim2
# See output state as a vector
outputstate = result_sim2.get_statevector(qc, decimals=5)
print(outputstate)
# Visualize density matrix
plot_state_city(outputstate)
# Create the quantum circuit with the measurement in one go.
qc_3 = QuantumCircuit(3,3,name="qc_bloch")
qc_3.x(1)
qc_3.h(2)
qc_3.barrier()
qc_3.draw(output='mpl')
# Execute the circuit on the statevector simulator.
# It is important to note that the measurement has been excluded
job_sim_bloch = execute(qc_3, backend_sv)
# Grab the results from the job.
result_sim_bloch = job_sim_bloch.result()
# See output state as a vector
output_bloch = result_sim_bloch.get_statevector(qc_3, decimals=5)
# Draw on the Bloch sphere
plot_bloch_multivector(output_bloch)
# Use Aer's unitary_simulator
backend_u = Aer.get_backend('unitary_simulator')
# Execute the circuit on the unitary simulator.
job_usim = execute(qc, backend_u)
# Grab the results from the job.
result_usim = job_usim.result()
result_usim
# Output the unitary matrix
unitary = result_usim.get_unitary(qc)
print('%s\n' % unitary)
# Create the quantum circuit with the measurement in one go.
qc_ex1 = QuantumCircuit(q,c,name="ex1")
# Put the first qubit in equal superposition
qc_ex1.h(0)
# Rest of the circuit
qc_ex1.x(1)
qc_ex1.cx(0,1)
qc_ex1.barrier()
qc_ex1.measure(0,0)
qc_ex1.measure(1,1)
qc_ex1.draw(output='mpl')
# Execute the circuit on the qasm simulator.
job_ex1 = execute(qc_ex1, backend_q, shots=4096)
job_ex1.status()
# Grab the results from the job.
result_ex1 = job_ex1.result()
result_ex1.get_counts(qc_ex1)
plot_histogram(result_ex1.get_counts(qc_ex1))
# Or get the histogram in one go
plot_histogram(job_ex1.result().get_counts(qc_ex1))
# Create a quantum register with 3 qubits
q3 = QuantumRegister(3,'q')
# Create a classical register with 3 qubits
c3 = ClassicalRegister(3,'c')
# Create the quantum circuit with the measurement in one go.
qc_ex2 = QuantumCircuit(q3,c3,name="ex1")
qc_ex2.ry(2*np.pi/3,0)
qc_ex2.cx(0,1)
qc_ex2.cx(1,2)
qc_ex2.barrier()
qc_ex2.measure(q3,c3)
qc_ex2.draw(output='mpl')
# Execute the circuit on the qasm simulator.
job_ex2 = execute(qc_ex2, backend_q, shots=4096)
# Grab the results from the job.
result_ex2 = job_ex2.result()
plot_histogram(result_ex2.get_counts(qc_ex2))
# Create a quantum register with 3 qubits
q3 = QuantumRegister(3,'q')
# Create a classical register with 3 qubits
c3 = ClassicalRegister(3,'c')
# Create the quantum circuit without a Toffoli gate
qc_toff = QuantumCircuit(q3,c3,name="ex1")
qc_toff.ry(2*np.pi/3,0)
qc_toff.h(1)
qc_toff.h(2)
qc_toff.barrier()
qc_toff.measure(q3,c3)
qc_toff.draw(output='mpl')
# Execute the circuit on the qasm simulator.
job_toff = execute(qc_toff, backend_q, shots=4096)
# Grab the results from the job.
result_toff = job_toff.result()
plot_histogram(result_toff.get_counts(qc_toff))
# Now, add a Toffoli gate
qc_toff = QuantumCircuit(q3,c3,name="ex1")
qc_toff.ry(2*np.pi/3,0)
qc_toff.h(1)
qc_toff.h(2)
qc_toff.ccx(1,2,0)
qc_toff.barrier()
qc_toff.measure(q3,c3)
qc_toff.draw(output='mpl')
# Execute the circuit on the qasm simulator.
job_toff = execute(qc_toff, backend_q, shots=4096)
# Grab the results from the job.
result_toff = job_toff.result()
plot_histogram(result_toff.get_counts(qc_toff))
IBMQ.disable_account()
provider = IBMQ.enable_account('IBM_TOKEN')
# provider = IBMQ.get_provider(hub='ibm-q-research')
provider.backends()
from qiskit.tools.monitor import backend_overview, backend_monitor, job_monitor
from qiskit.tools.visualization import plot_gate_map, plot_error_map
# Retrieve IBM Quantum device information
backend_overview()
# Let's get two quantum devices as an example
backend_qx2 = provider.get_backend('ibmqx2')
backend_vigo = provider.get_backend('ibmq_vigo')
backend_monitor(backend_qx2)
plot_error_map(backend_qx2)
backend_monitor(backend_vigo)
plot_error_map(backend_vigo)
# Create a 5-qubit GHZ state (i.e. (|00000> + |11111>)/sqrt(2))
q5 = QuantumRegister(5,'q')
c5 = ClassicalRegister(5,'c')
ghz5= QuantumCircuit(q5,c5)
ghz5.h(0)
for i in range(1,5):
ghz5.cx(0,i)
ghz5.barrier()
ghz5.measure(q5,c5)
ghz5.draw(output='mpl')
# Run the 5-qubit GHZ experiment on a 5-qubit device (try vigo)
job_exp1 = execute(ghz5, backend=backend_vigo, shots=4096)
job_monitor(job_exp1)
# Grab experimental results
result_vigo = job_exp1.result()
counts_vigo = result_vigo.get_counts(ghz5)
# Let's also try the same experiment on the 14-qubit device.
job_exp2 = execute(ghz5, backend=provider.get_backend('ibmq_16_melbourne'), shots=4096)
job_monitor(job_exp2)
# Grab experimental results
result_mel = job_exp2.result()
counts_mel = result_mel.get_counts(ghz5)
# Now, compare to theory by running it on qasm_simulator
job_qasm = execute(ghz5,backend=backend_q)
result_qasm = job_qasm.result()
counts_qasm = result_qasm.get_counts(ghz5)
# Plot both experimental and ideal results
plot_histogram([counts_qasm,counts_vigo,counts_mel],
color=['black','green','blue'],
legend=['QASM','Vigo','Melbourne'],figsize = [20,8])
|
https://github.com/dkp-quantum/Tutorials
|
dkp-quantum
|
%matplotlib inline
# Importing standard Qiskit libraries and configuring account
from qiskit import *
from qiskit.visualization import *
import numpy as np
# Create a quantum register with 3 qubits
q3 = QuantumRegister(3,'q')
# Create a classical register with 3 qubits
c3 = ClassicalRegister(3,'c')
# Create the quantum circuit with the measurement in one go.
qc_ex2 = QuantumCircuit(q3,c3,name="ex1")
qc_ex2.ry(2*np.pi/3,0)
qc_ex2.cx(0,1)
qc_ex2.cx(1,2)
qc_ex2.barrier()
qc_ex2.measure(q3,c3)
qc_ex2.draw(output='mpl')# Now, add a Toffoli gate
qc_toff = QuantumCircuit(q3,c3,name="ex1")
backend_q = Aer.get_backend('qasm_simulator')
# Execute the circuit on the qasm simulator.
job_ex2 = execute(qc_ex2, backend_q, shots=4096)
# Grab the results from the job.
result_ex2 = job_ex2.result()
plot_histogram(result_ex2.get_counts(qc_ex2))
# Create a quantum register with 3 qubits
q3 = QuantumRegister(3,'q')
# Create a classical register with 3 qubits
c3 = ClassicalRegister(3,'c')
# Create the quantum circuit without a Toffoli gate
qc_toff = QuantumCircuit(q3,c3,name="ex1")
qc_toff.ry(2*np.pi/3,0)
qc_toff.h(1)
qc_toff.h(2)
qc_toff.barrier()
qc_toff.measure(q3,c3)
qc_toff.draw(output='mpl')
# Execute the circuit on the qasm simulator.
job_toff = execute(qc_toff, backend_q, shots=4096)
# Grab the results from the job.
result_toff = job_toff.result()
plot_histogram(result_toff.get_counts(qc_toff))
# Now, add a Toffoli gate
qc_toff = QuantumCircuit(q3,c3,name="ex1")
qc_toff.ry(2*np.pi/3,0)
qc_toff.h(1)
qc_toff.h(2)
qc_toff.ccx(1,2,0)
qc_toff.barrier()
qc_toff.measure(q3,c3)
qc_toff.draw(output='mpl')
# Execute the circuit on the qasm simulator.
job_toff = execute(qc_toff, backend_q, shots=4096)
# Grab the results from the job.
result_toff = job_toff.result()
plot_histogram(result_toff.get_counts(qc_toff))
# IBMQ.disable_account()
provider = IBMQ.enable_account('TOKEN')
provider = IBMQ.get_provider(hub='ibm-q-research')
provider.backends()
from qiskit.tools.monitor import backend_overview, backend_monitor, job_monitor
from qiskit.tools.visualization import plot_gate_map, plot_error_map
# Retrieve IBM Quantum device information
backend_overview()
# Let's get two quantum devices as an example
backend_qx2 = provider.get_backend('ibmqx2')
backend_vigo = provider.get_backend('ibmq_vigo')
backend_monitor(backend_qx2)
plot_error_map(backend_qx2)
backend_monitor(backend_vigo)
plot_error_map(backend_vigo)
# Create a 5-qubit GHZ state (i.e. (|00000> + |11111>)/sqrt(2))
q5 = QuantumRegister(5,'q')
c5 = ClassicalRegister(5,'c')
ghz5= QuantumCircuit(q5,c5)
ghz5.h(0)
for i in range(1,5):
ghz5.cx(0,i)
ghz5.barrier()
ghz5.measure(q5,c5)
ghz5.draw(output='mpl')
# Run the 5-qubit GHZ experiment on a 5-qubit device (try vigo)
job_exp1 = execute(ghz5, backend=backend_vigo, shots=4096)
job_monitor(job_exp1)
# Grab experimental results
result_vigo = job_exp1.result()
counts_vigo = result_vigo.get_counts(ghz5)
# Let's also try the same experiment on the 15-qubit device.
job_exp2 = execute(ghz5, backend=provider.get_backend('ibmq_16_melbourne'), shots=4096)
job_monitor(job_exp2)
# Grab experimental results
result_mel = job_exp2.result()
counts_mel = result_mel.get_counts(ghz5)
# Now, compare to theory by running it on qasm_simulator
job_qasm = execute(ghz5,backend=backend_q)
result_qasm = job_qasm.result()
counts_qasm = result_qasm.get_counts(ghz5)
# Plot both experimental and ideal results
plot_histogram([counts_qasm,counts_vigo,counts_mel],
color=['black','green','blue'],
legend=['QASM','Vigo','Melbourne'],figsize = [20,8])
%matplotlib inline
# Importing standard Qiskit libraries and configuring account
from qiskit import *
from qiskit.visualization import *
import numpy as np
# Define a function that takes a QuantumCircuit (qc)
# a qubit index (index) and a message string (msg)
def encoding(qc, index, msg):
if msg == 0:
pass # To send 00 we do nothing
elif msg == 1:
qc.x(index) # To send 10 we apply an X-gate
elif msg == 2:
qc.z(index) # To send 01 we apply a Z-gate
elif msg == 3:
qc.z(index) # To send 11, we apply a Z-gate
qc.x(index) # followed by an X-gate
else:
print("Invalid Message. Sending '00'.")
def decoding(qc, a, b):
qc.cx(a,b)
qc.h(a)
def qc_sdc(msg):
# Create the quantum circuit with 2 qubits
qc = QuantumCircuit(2)
# First, an entangled pair is created between Alice and Bob
# Bob has the first qubit, Alice has the second qubit.
qc.h(0)
qc.cx(0,1)
qc.barrier()
# Next, Bob encodes his message onto qubit 0.
encoding(qc, 0, msg)
qc.barrier()
# Bob then sends his qubit to Alice.
# After recieving qubit 0, Alice applies the recovery protocol:
decoding(qc, 0, 1)
# Finally, Alice measures her qubits to read Bob's message
qc.measure_all()
return qc
backend_qasm = Aer.get_backend('qasm_simulator')
rand_msg = np.random.randint(4)
qc = qc_sdc(rand_msg)
job_sim = execute(qc, backend_qasm, shots=1024)
sim_result = job_sim.result()
measurement_result = sim_result.get_counts(qc)
print(measurement_result)
plot_histogram(measurement_result)
print("The random message was: %s" % rand_msg)
qc.draw(output='mpl')
from qiskit.tools.monitor import backend_overview, backend_monitor, job_monitor
from qiskit.tools.visualization import plot_gate_map, plot_error_map
# Retrieve IBM Quantum device information
backend_overview()
# Run the superdense coding experiment on a 5-qubit device (try london)
job_sdc = execute(qc, backend=provider.get_backend('ibmq_london'), shots=4096)
job_monitor(job_sdc)
experiment_result = job_sdc.result().get_counts(qc)
print("The random message was: %s" % rand_msg)
plot_histogram(experiment_result)
def create_bell_pair(qc, a, b):
# Creates a bell pair in qc using qubits a & b
qc.h(a) # Put qubit a into state |+>
qc.cx(a,b) # CNOT with a as control and b as target
qr = QuantumRegister(3) # Protocol uses 3 qubits
cr1 = ClassicalRegister(1) # and 2 classical bits
cr2 = ClassicalRegister(1) # in 2 different registers
teleportation = QuantumCircuit(qr, cr1, cr2)
## STEP 1
# Entangle qubits q1 and q2
create_bell_pair(teleportation, 1, 2)
teleportation.barrier()
# And view the circuit so far:
teleportation.draw(output='mpl')
## STEP 2
# Bob performs his gates
teleportation.cx(0,1)
teleportation.h(0)
teleportation.barrier()
# And view the circuit so far:
teleportation.draw(output='mpl')
## STEP 3
# Bob measures his part
teleportation.measure(0,0)
teleportation.measure(1,1)
# And view the circuit so far:
teleportation.draw(output='mpl')
# This function takes a QuantumCircuit (qc), qubit index
# and ClassicalRegisters (cr1 & cr2) to decide which gates to apply
def alice_recover(qc, index, cr1, cr2):
# Here we use c_if to control our gates with a classical
# bit instead of a qubit
qc.z(index).c_if(cr1, 1) # Apply gates if the registers
qc.x(index).c_if(cr2, 1) # are in the state '1'
## STEP 4
# Alice perform recovery
alice_recover(teleportation, 2, cr1, cr2)
# And view the circuit so far:
teleportation.draw(output='mpl')
def random_init(qc,r1,r2,index):
## STEP 0
# Bob prepares a quantum state to teleport
# by applying a random rotation around y and z
qc.ry(r1,index)
qc.rz(r2,index)
qc.barrier()
def quantum_teleportation(qc):
## STEP 1
# Entangle qubits q1 and q2
create_bell_pair(qc, 1, 2)
qc.barrier()
## STEP 2
# Bob performs his gates
qc.cx(0,1)
qc.h(0)
qc.barrier()
## STEP 3
# Bob measures his part
qc.measure(0,0)
qc.measure(1,1)
## STEP 4
# Alice perform recovery
alice_recover(qc, 2, cr1, cr2)
qr = QuantumRegister(3) # Protocol uses 3 qubits
cr1 = ClassicalRegister(1) # and 2 classical bits
cr2 = ClassicalRegister(1) # in 2 different registers
qc_teleportation = QuantumCircuit(qr, cr1, cr2)
qc_ref = QuantumCircuit(qr)
r1 = np.random.random()*np.pi
r2 = np.random.random()*2*np.pi
random_init(qc_ref, r1, r2, 0)
random_init(qc_teleportation, r1, r2, 0)
quantum_teleportation(qc_teleportation)
qc_teleportation.draw(output='mpl')
backend_sv = BasicAer.get_backend('statevector_simulator')
in_vector = execute(qc_ref, backend_sv).result().get_statevector()
out_vector = execute(qc_teleportation, backend_sv).result().get_statevector()
plot_bloch_multivector(in_vector)
plot_bloch_multivector(out_vector)
|
https://github.com/dkp-quantum/Tutorials
|
dkp-quantum
|
%matplotlib inline
# Importing standard Qiskit libraries and configuring account
from qiskit import *
from qiskit.visualization import *
import numpy as np
def encoding_x(qc):
qc.cx(0,1)
qc.cx(0,2)
qc.barrier()
def decoding_x(qc):
qc.cx(0,2)
qc.cx(0,1)
qc.barrier()
def random_init(qc,theta,phi,index):
## Prepare a random single-qubit state
qc.ry(theta,index)
qc.rz(phi,index)
qc.barrier()
def random_init_inv(qc,theta,phi,index):
## Inverse of the random single-qubit state preparation
qc.rz(-phi,index)
qc.ry(-theta,index)
qc.barrier()
q = QuantumRegister(3)
c = ClassicalRegister(1)
qec = QuantumCircuit(q,c)
# Initialize the first qubit in a random state
theta = np.random.random()*np.pi
phi = np.random.random()*2*np.pi
random_init(qec,theta,phi,0)
# QEC encoding for correcting a bit-flip error
encoding_x(qec)
# QEC decoding for correcting a bit-flip error
decoding_x(qec)
# Correction
qec.ccx(1,2,0)
# Insert inverse of the random initial state preparation
# to check that the QEC has worked.
random_init_inv(qec,theta,phi,0)
qec.measure(q[0],c)
qec.draw(output='mpl')
# Use Aer's qasm_simulator
backend_q = Aer.get_backend('qasm_simulator')
# Execute the circuit on the qasm simulator.
job_qec_ref = execute(qec, backend_q, shots=4096)
# Grab the results from the job.
result_qec_ref = job_qec_ref.result()
plot_histogram(result_qec_ref.get_counts(qec))
# Define bit-flip errors with probability p
def bitflip(qc,qubit,p):
if np.random.binomial(1,p) == 1:
qc.x(qubit)
q = QuantumRegister(3)
c = ClassicalRegister(1)
qec = QuantumCircuit(q,c)
# Initialize the first qubit in a random state
theta = np.random.random()*np.pi
phi = np.random.random()*2*np.pi
random_init(qec,theta,phi,0)
# QEC encoding for correcting a bit-flip error
encoding_x(qec)
# Insert error
p=1
bitflip(qec,0,p)
# bitflip(qec,1,p)
# bitflip(qec,2,p)
qec.barrier()
# QEC decoding for correcting a bit-flip error
decoding_x(qec)
# Correction
qec.ccx(1,2,0)
# Insert inverse of the random initial state preparation
# to check that the QEC has worked.
random_init_inv(qec,theta,phi,0)
qec.measure(q[0],c)
qec.draw(output='mpl')
# Execute the circuit on the qasm simulator.
job_qec = execute(qec, backend_q, shots=4096)
# Grab the results from the job.
result_qec = job_qec.result()
plot_histogram(result_qec.get_counts(qec))
q = QuantumRegister(3)
c = ClassicalRegister(1)
qec = QuantumCircuit(q,c)
# Initialize the first qubit in a random state
theta = np.random.random()*np.pi
phi = np.random.random()*2*np.pi
random_init(qec,theta,phi,0)
# QEC encoding for correcting a bit-flip error
encoding_x(qec)
# Insert error
p=1
bitflip(qec,0,p)
bitflip(qec,1,p)
# bitflip(qec,2,p)
qec.barrier()
# QEC decoding for correcting a bit-flip error
decoding_x(qec)
# Correction
qec.ccx(1,2,0)
# Insert inverse of the random initial state preparation
# to check that the QEC has worked.
random_init_inv(qec,theta,phi,0)
qec.measure(q[0],c)
qec.draw(output='mpl')
# Execute the circuit on the qasm simulator.
job_qec = execute(qec, backend_q, shots=4096)
# Grab the results from the job.
result_qec = job_qec.result()
plot_histogram(result_qec.get_counts(qec))
q = QuantumRegister(3)
c = ClassicalRegister(1)
qec = QuantumCircuit(q,c)
# Initialize the first qubit in a random state
theta = np.random.random()*np.pi
phi = np.random.random()*2*np.pi
random_init(qec,theta,phi,0)
# QEC encoding for correcting a bit-flip error
encoding_x(qec)
# Insert error
p=1
bitflip(qec,0,p)
bitflip(qec,1,p)
bitflip(qec,2,p)
qec.barrier()
# QEC decoding for correcting a bit-flip error
decoding_x(qec)
# Correction
qec.ccx(1,2,0)
# Insert inverse of the random initial state preparation
# to check that the QEC has worked.
random_init_inv(qec,theta,phi,0)
qec.measure(q[0],c)
qec.draw(output='mpl')
# Execute the circuit on the qasm simulator.
job_qec = execute(qec, backend_q, shots=4096)
# Grab the results from the job.
result_qec = job_qec.result()
plot_histogram(result_qec.get_counts(qec))
import numpy as np
from numpy import pi
# importing Qiskit
from qiskit import *
from qiskit.visualization import *
from qiskit.tools.monitor import backend_overview, backend_monitor, job_monitor
from qiskit.tools.visualization import plot_gate_map, plot_error_map
qftc = QuantumCircuit(3)
qftc.h(0)
qftc.draw(output='mpl')
qftc.cu1(2*pi/(2**2), 1, 0) # CROT from qubit 1 to qubit 0
qftc.draw(output='mpl')
qftc.cu1(2*pi/(2**3), 2, 0) # CROT from qubit 1 to qubit 0
qftc.draw(output='mpl')
qftc.h(1)
qftc.cu1(2*pi/(2**2), 2, 1) # CROT from qubit 2 to qubit 1
qftc.h(2)
qftc.draw(output='mpl')
# Complete the QFT circuit by reordering qubits (by exchanging qubit 1 and 3)
qftc.swap(0,2)
qftc.draw(output='mpl')
def qft_rotations(circuit, n):
if n == 0: # Exit function if circuit is empty
print("The number of qubits must be greater than 0")
return circuit
index = 0
circuit.h(index) # Apply the H-gate to the most significant qubit
index += 1
n -= 1
for qubit in range(n): # Apply the controlled rotations conditioned on n-1 qubits
# For each less significant qubit, we need to do a
# smaller-angled controlled rotation:
circuit.cu1(2*pi/2**(2+qubit), index + qubit, 0)
qc = QuantumCircuit(4)
qft_rotations(qc,4)
qc.draw(output = 'mpl')
def qft_rotations(circuit, n, start):
if n == 0: # Exit function if circuit is empty
return circuit
circuit.h(start) # Apply the H-gate to the most significant qubit
if start == n-1:
return circuit
for qubit in range(n-1-start): # Apply the controlled rotations conditioned on n-1 qubits
# For each less significant qubit, we need to do a
# smaller-angled controlled rotation:
circuit.cu1(2*pi/2**(2+qubit), start + 1 + qubit, start)
start += 1
circuit.barrier()
# Apply QFT recursively
qft_rotations(circuit, n, start)
qc = QuantumCircuit(5)
qft_rotations(qc,5,0)
qc.draw(output = 'mpl')
|
https://github.com/dkp-quantum/Tutorials
|
dkp-quantum
|
%matplotlib inline
# Importing standard Qiskit libraries and configuring account
from qiskit import *
from qiskit.visualization import *
import numpy as np
# Exercise 1.
# Create the measurement circuit
ZZI = QuantumCircuit(4,1)
ZZI.h(3)
ZZI.cz(3,0)
ZZI.cz(3,1)
ZZI.h(3)
ZZI.barrier()
ZZI.measure(3,0)
ZZI.draw(output='mpl')
# Create the first test state, i.e. a|000> + b|111>
ztest1 = QuantumCircuit(4)
theta = np.random.random()*np.pi
phi = np.random.random()*2*np.pi
ztest1.ry(theta,0)
ztest1.rz(phi,0)
ztest1.cx(0,1)
ztest1.cx(0,2)
ztest1.barrier()
# Now add the measurement circuit
ztest1 = ztest1 + ZZI
ztest1.draw(output='mpl')
# Use Aer's qasm_simulator
backend_q = Aer.get_backend('qasm_simulator')
# Execute the circuit on the qasm simulator.
job_ztest1 = execute(ztest1, backend_q, shots=4096)
# Grab the results from the job.
result_ztest1 = job_ztest1.result()
plot_histogram(result_ztest1.get_counts(ztest1))
# Create the second test state, i.e. a|010> + b|101>
ztest2 = QuantumCircuit(4)
theta = np.random.random()*np.pi
phi = np.random.random()*2*np.pi
ztest2.ry(theta,0)
ztest2.rz(phi,0)
# Flip the second qubit
ztest2.x(1)
ztest2.cx(0,1)
ztest2.cx(0,2)
ztest2.barrier()
# Now add the measurement circuit
ztest2 = ztest2 + ZZI
ztest2.draw(output='mpl')
# Execute the circuit on the qasm simulator.
job_ztest2 = execute(ztest2, backend_q, shots=4096)
# Grab the results from the job.
result_ztest2 = job_ztest2.result()
plot_histogram(result_ztest2.get_counts(ztest2))
# Exercise 2.
# Create the measurement circuit
XXI = QuantumCircuit(4,1)
XXI.h(3)
XXI.cx(3,0)
XXI.cx(3,1)
XXI.h(3)
XXI.barrier()
XXI.measure(3,0)
XXI.draw(output='mpl')
# Create the first test state, i.e. a|+++> + b|--->
xtest1 = QuantumCircuit(4)
theta = np.random.random()*np.pi
phi = np.random.random()*2*np.pi
xtest1.ry(theta,0)
xtest1.rz(phi,0)
xtest1.cx(0,1)
xtest1.cx(0,2)
for i in range(3):
xtest1.h(i)
xtest1.barrier()
# Now add the measurement circuit
xtest1 = xtest1 + XXI
xtest1.draw(output='mpl')
# Execute the circuit on the qasm simulator.
job_xtest1 = execute(xtest1, backend_q, shots=4096)
# Grab the results from the job.
result_xtest1 = job_xtest1.result()
plot_histogram(result_xtest1.get_counts(xtest1))
# Create the first test state, i.e. a|+-+> + b|-+->
xtest2 = QuantumCircuit(4)
theta = np.random.random()*np.pi
phi = np.random.random()*2*np.pi
xtest2.ry(theta,0)
xtest2.rz(phi,0)
# Flip the second qubit
xtest2.x(1)
xtest2.cx(0,1)
xtest2.cx(0,2)
for i in range(3):
xtest2.h(i)
xtest2.barrier()
# Now add the measurement circuit
xtest2 = xtest2 + XXI
xtest2.draw(output='mpl')
# Execute the circuit on the qasm simulator.
job_xtest2 = execute(xtest2, backend_q, shots=4096)
# Grab the results from the job.
result_xtest2 = job_xtest2.result()
plot_histogram(result_xtest2.get_counts(xtest2))
%matplotlib inline
# Importing standard Qiskit libraries and configuring account
from qiskit import *
from qiskit.visualization import *
import numpy as np
def encoding_x(qc):
qc.cx(0,1)
qc.cx(0,2)
qc.barrier()
def measure_error(qc,error):
if error == 'x':
qc.h(3)
qc.h(4)
qc.cz(3,0)
qc.cz(3,1)
qc.cz(4,0)
qc.cz(4,2)
qc.h(3)
qc.h(4)
elif error == 'z':
qc.h(3)
qc.h(4)
qc.cx(3,0)
qc.cx(3,1)
qc.cx(4,0)
qc.cx(4,2)
qc.h(3)
qc.h(4)
qc.barrier()
# We don't need decoding for QEC,
# but we will use it for checking the answer
def decoding_x(qc):
qc.cx(0,2)
qc.cx(0,1)
qc.barrier()
def random_init(qc,theta,phi,index):
## Prepare a random single-qubit state
qc.ry(theta,index)
qc.rz(phi,index)
qc.barrier()
def random_init_inv(qc,theta,phi,index):
## Inverse of the random single-qubit state preparation
qc.rz(-phi,index)
qc.ry(-theta,index)
qc.barrier()
qec2x = QuantumCircuit(5,3)
# Initialize the first qubit in a random state
theta = np.random.random()*np.pi
qec2x.ry(theta,0)
# QEC encoding for correcting a bit-flip error
encoding_x(qec2x)
# Measurement
measure_error(qec2x,'x')
# Correction
# Correct the first qubit
qec2x.ccx(3,4,0)
# Correct the second qubit
qec2x.x(4)
qec2x.ccx(3,4,1)
qec2x.x(4)
# Correct the third qubit
qec2x.x(3)
qec2x.ccx(3,4,2)
qec2x.x(3)
qec2x.barrier()
# QEC decoding for correcting a bit-flip error
decoding_x(qec2x)
# Insert inverse of the random initial state preparation
# to check that the QEC has worked.
qec2x.ry(-theta,0)
qec2x.measure(0,0)
# Let's check the error syndrome
qec2x.measure(3,1)
qec2x.measure(4,2)
qec2x.draw(output='mpl')
# Execute the circuit on the qasm simulator.
job_qec2x_ref = execute(qec2x, backend_q, shots=4096)
# Grab the results from the job.
result_qec2x_ref = job_qec2x_ref.result()
plot_histogram(result_qec2x_ref.get_counts(qec2x))
# IBMQ.disable_account()
provider = IBMQ.enable_account('TOKEN')
from qiskit.tools.monitor import backend_overview, backend_monitor, job_monitor
from qiskit.tools.visualization import plot_gate_map, plot_error_map
# Retrieve IBM Quantum device information
backend_overview()
# Let's also try the same experiment on the 15-qubit device.
job_exp_qec2x = execute(qec2x, backend=provider.get_backend('ibmq_valencia'), shots=8192)
job_monitor(job_exp_qec2x)
# Grab experimental results
result_exp_qec2x = job_exp_qec2x.result()
plot_histogram(result_exp_qec2x.get_counts(qec2x))
# Define bit-flip errors with probability p
def bitflip(qc,qubit,p):
if np.random.binomial(1,p) == 1:
qc.x(qubit)
qec2x = QuantumCircuit(5,3)
# Initialize the first qubit in a random state
theta = np.random.random()*np.pi
qec2x.ry(theta,0)
# QEC encoding for correcting a bit-flip error
encoding_x(qec2x)
# Insert error
p=1
# bitflip(qec2x,0,p)
# bitflip(qec2x,1,p)
bitflip(qec2x,2,p)
qec2x.barrier()
# Measurement
measure_error(qec2x,'x')
# Correction
# Correct the first qubit
qec2x.ccx(3,4,0)
# Correct the second qubit
qec2x.x(4)
qec2x.ccx(3,4,1)
qec2x.x(4)
# Correct the third qubit
qec2x.x(3)
qec2x.ccx(3,4,2)
qec2x.x(3)
qec2x.barrier()
# QEC decoding for correcting a bit-flip error
decoding_x(qec2x)
# Insert inverse of the random initial state preparation
# to check that the QEC has worked.
qec2x.ry(-theta,0)
qec2x.measure(0,0)
# Let's check the error syndrome
qec2x.measure(3,1)
qec2x.measure(4,2)
qec2x.draw(output='mpl')
# Execute the circuit on the qasm simulator.
job_qec2x = execute(qec2x, backend_q, shots=4096)
# Grab the results from the job.
result_qec2x = job_qec2x.result()
plot_histogram(result_qec2x.get_counts(qec2x))
from qiskit.compiler import transpile
from qiskit.transpiler import PassManager, Layout
display(plot_error_map(provider.get_backend('ibmqx2')))
display(plot_error_map(provider.get_backend('ibmq_burlington')))
# Create a dummy circuit for default transpiler demonstration
qc = QuantumCircuit(4)
qc.h(0)
qc.swap(0,1)
qc.cx(1,0)
qc.s(3)
qc.x(3)
qc.h(3)
qc.h(0)
qc.cx(0,2)
qc.ccx(0,1,2)
qc.h(0)
print('Original circuit')
display(qc.draw(output='mpl'))
# Transpile the circuit to run on ibmqx2
qt_qx2 = transpile(qc,provider.get_backend('ibmqx2'))
print('Transpiled circuit for ibmqx2')
display(qt_qx2.draw(output='mpl'))
# Transpile the circuit to run on ibmq_burlington
qt_bu = transpile(qc,provider.get_backend('ibmq_burlington'))
print('Transpiled circuit for ibmqx_Burlington')
display(qt_bu.draw(output='mpl'))
# Print out some circuit properties
# Total nunmber of operations
print("Number of operations for ibmqx2 = %s" % qt_qx2.size())
print("Number of operations for ibmq_burlington = %s \n" % qt_bu.size())
# Circuit depth
print("Circuit depth for ibmqx2 = %s" % qt_qx2.depth())
print("Circuit depth for ibmq_burlington = %s \n" % qt_bu.depth())
# Number of qubits
print("Number of qubits for ibmqx2 = %s" % qt_qx2.width())
print("Number of qubits for ibmq_burlington = %s \n" % qt_bu.width())
# Breakdown of operations by type
print("Operations for ibmqx2: %s" % qt_qx2.count_ops())
print("Operations for ibmq_burlington: %s \n" % qt_bu.count_ops())
# Number of unentangled subcircuits in this circuit.
# In principle, each subcircuit can be executed on a different quantum device.
print("Number of unentangled subcircuits for ibmqx2 = %s" % qt_qx2.num_tensor_factors())
print("Number of unentangled subcircuits for ibmq_burlington = %s" % qt_bu.num_tensor_factors())
qr = QuantumRegister(4,'q')
cr = ClassicalRegister(4,'c')
qc_test = QuantumCircuit(qr,cr)
qc_test.h(0)
for i in range(3):
qc_test.cx(i,i+1)
qc_test.barrier()
qc_test.measure(qr,cr)
qc_test.draw(output='mpl')
qc_t = transpile(qc_test, backend = provider.get_backend('ibmq_london'))
# Display transpiled circuit
display(qc_t.draw(output='mpl'))
# Display the qubit layout
display(plot_error_map(provider.get_backend('ibmq_london')))
# Print out some circuit properties
# Total nunmber of operations
print("Number of operations = %s" % qc_t.size())
# Circuit depth
print("Circuit depth = %s" % qc_t.depth())
# Execute the circuit on the qasm simulator.
job_test = execute(qc_test, provider.get_backend('ibmq_london'), shots=8192)
job_monitor(job_test)
# Customize the layout
layout = Layout({qr[0]: 4, qr[1]: 3, qr[2]: 1, qr[3]:0})
# Map it onto 5 qubit backend ibmqx2
qc_test_new = transpile(qc_test, backend = provider.get_backend('ibmq_london'), initial_layout=layout, basis_gates=['u1','u2','u3','cx'])
display(qc_test_new.draw(output='mpl'))
# Print out some circuit properties
# Total nunmber of operations
print("Number of operations = %s" % qc_test_new.size())
# Circuit depth
print("Circuit depth = %s" % qc_test_new.depth())
# Execute the circuit on the qasm simulator.
job_test_new = execute(qc_test_new, provider.get_backend('ibmq_london'), shots=8192)
job_monitor(job_test_new)
# Now, compare the two
result_test = job_test.result()
result_test_new = job_test_new.result()
# Plot both experimental and ideal results
plot_histogram([result_test.get_counts(qc_test),result_test_new.get_counts(qc_test_new)],
color=['green','blue'],legend=['default','custom'],figsize = [20,8])
# Apply 4-qubit controlled x gate
qr = QuantumRegister(5,'q')
qc = QuantumCircuit(qr)
qc.h(0)
qc.h(1)
qc.h(3)
qc.ccx(0,1,2)
qc.ccx(2,3,4)
qc.ccx(0,1,2)
display(qc.draw(output='mpl'))
# Print out some circuit properties
# Total nunmber of operations
print("Number of operations = %s \n" % qc.size())
# Count different types of operations
print("Operation counts = %s \n" % qc.count_ops())
# Circuit depth
print("Circuit depth = %s" % qc.depth())
qc_t = transpile(qc, provider.get_backend('ibmq_valencia'))
display(qc_t.draw(output='mpl'))
# Print out some circuit properties
# Total nunmber of operations
print("Number of operations = %s" % qc_t.size())
# Circuit depth
print("Circuit depth = %s" % qc_t.depth())
# Transpile many times (20 times in this example) and pick the best one
trial = 20
# Use ibmq_valencia for example
backend_exp = provider.get_backend('ibmq_valencia')
tcircs0 = transpile([qc]*trial, backend_exp, optimization_level=0)
tcircs1 = transpile([qc]*trial, backend_exp, optimization_level=1)
tcircs2 = transpile([qc]*trial, backend_exp, optimization_level=2)
tcircs3 = transpile([qc]*trial, backend_exp, optimization_level=3)
import matplotlib.pyplot as plt
num_cx0 = [c.count_ops()['cx'] for c in tcircs0]
num_cx1 = [c.count_ops()['cx'] for c in tcircs1]
num_cx2 = [c.count_ops()['cx'] for c in tcircs2]
num_cx3 = [c.count_ops()['cx'] for c in tcircs3]
num_tot0 = [c.size() for c in tcircs0]
num_tot1 = [c.size() for c in tcircs1]
num_tot2 = [c.size() for c in tcircs2]
num_tot3 = [c.size() for c in tcircs3]
num_depth0 = [c.depth() for c in tcircs0]
num_depth1 = [c.depth() for c in tcircs1]
num_depth2 = [c.depth() for c in tcircs2]
num_depth3 = [c.depth() for c in tcircs3]
plt.rcParams.update({'font.size': 16})
# Plot the number of CNOT gates
plt.figure(figsize=(12,6))
plt.plot(range(len(num_cx0)),num_cx0,'r',label='level 0')
plt.plot(range(len(num_cx1)),num_cx1,'b',label='level 1')
plt.plot(range(len(num_cx2)),num_cx2,'g',label='level 2')
plt.plot(range(len(num_cx3)),num_cx3,'k',label='level 3')
plt.legend(loc='upper left')
plt.xlabel('Random trial')
plt.ylabel('# of cx gates')
plt.show()
# Plot total number of gates
plt.figure(figsize=(12,6))
plt.plot(range(len(num_tot0)),num_tot0,'r',label='level 0')
plt.plot(range(len(num_tot1)),num_tot1,'b',label='level 1')
plt.plot(range(len(num_tot2)),num_tot2,'g',label='level 2')
plt.plot(range(len(num_tot3)),num_tot3,'k',label='level 3')
plt.legend(loc='upper left')
plt.xlabel('Random trial')
plt.ylabel('# of total gates')
plt.show()
# Plot the number of CNOT gates
plt.figure(figsize=(12,6))
plt.plot(range(len(num_depth0)),num_depth0,'r',label='level 0')
plt.plot(range(len(num_depth1)),num_depth1,'b',label='level 1')
plt.plot(range(len(num_depth2)),num_depth2,'g',label='level 2')
plt.plot(range(len(num_depth3)),num_depth3,'k',label='level 3')
plt.legend(loc='upper left')
plt.xlabel('Random trial')
plt.ylabel('Circuit depth')
plt.show()
print('Opt0: Minimum # of cx gates = %s' % min(num_cx0))
print('Opt0: The best circuit is the circut %s \n' % num_cx0.index(min(num_cx0)))
print('Opt1: Minimum # of cx gates = %s' % min(num_cx1))
print('Opt1: The best circuit is the circut %s \n' % num_cx1.index(min(num_cx1)))
print('Opt2: Minimum # of cx gates = %s' % min(num_cx2))
print('Opt2: The best circuit is the circut %s \n' % num_cx2.index(min(num_cx2)))
print('Opt3: Minimum # of cx gates = %s' % min(num_cx3))
print('Opt3: The best circuit is the circut %s' % num_cx3.index(min(num_cx3)))
|
https://github.com/dkp-quantum/Tutorials
|
dkp-quantum
|
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
# Importing standard Qiskit libraries and configuring account
from qiskit import *
from qiskit.visualization import *
from qiskit.circuit import Parameter
# Simple example
# Define two parameters, t1 and t2
theta1 = Parameter('t1')
theta2 = Parameter('t2')
# Build a 1-qubit circuit
qc = QuantumCircuit(1, 1)
# First parameter, t1, is used for a single qubit rotation of a controlled qubit
qc.ry(theta1,0)
qc.rz(theta2,0)
qc.barrier()
qc.measure(0, 0)
qc.draw(output='mpl')
theta1_range = np.linspace(0, 2 * np.pi, 20)
theta2_range = np.linspace(0, np.pi, 2)
circuits = [qc.bind_parameters({theta1: theta_val1, theta2: theta_val2})
for theta_val2 in theta2_range for theta_val1 in theta1_range ]
# Visualize several circuits to check that correct circuits are generated correctly.
display(circuits[0].draw(output='mpl'))
display(circuits[1].draw(output='mpl'))
display(circuits[20].draw(output='mpl'))
# Execute multiple circuits
job = execute(qc, backend=Aer.get_backend('qasm_simulator'), shots = 8192,
parameter_binds=[{theta1: theta_val1, theta2: theta_val2}
for theta_val2 in theta2_range for theta_val1 in theta1_range])
# Store all counts
counts = [job.result().get_counts(i) for i in range(len(job.result().results))]
# Plot to visualize the result
plt.figure(figsize=(12,6))
plt.plot(range(len(theta1_range)*len(theta2_range)),
list(map(lambda counts: (counts.get('0',0)-counts.get('1',1))/8192,counts)))
plt.show()
# IBMQ.disable_account()
provider = IBMQ.enable_account('TOKEN')
from qiskit.tools.monitor import backend_overview, backend_monitor, job_monitor
from qiskit.tools.visualization import plot_gate_map, plot_error_map
# Retrieve IBM Quantum device information
backend_overview()
# Execute multiple circuits
job_exp = execute(qc, backend=provider.get_backend('ibmq_essex'), shots = 8192,
parameter_binds=[{theta1: theta_val1, theta2: theta_val2}
for theta_val2 in theta2_range for theta_val1 in theta1_range])
# Monitor job status
job_monitor(job_exp)
# Store all counts
counts_exp = [job_exp.result().get_counts(i) for i in range(len(job_exp.result().results))]
# Plot to visualize the result
plt.figure(figsize=(12,6))
plt.rcParams.update({'font.size': 16})
plt.plot(range(len(theta1_range)*len(theta2_range)),
list(map(lambda counts: (counts.get('0',0)-counts.get('1',1))/8192,counts)),'r',label='Simulation')
plt.plot(range(len(theta1_range)*len(theta2_range)),
list(map(lambda counts_exp: (counts_exp.get('0',0)-counts_exp.get('1',1))/8192,counts_exp)),
'b',label='Experiment')
plt.legend(loc='best')
plt.show()
def swaptest(qc,ancilla,qubit1,qubit2):
qc.h(ancilla)
qc.cswap(ancilla,qubit1,qubit2)
qc.h(ancilla)
qr = QuantumRegister(5,'q')
cr = ClassicalRegister(2,'c')
qc = QuantumCircuit(qr,cr,name='qclassifier')
# Put equal weights on the training data
qc.h(1)
# Prepare the test data quantum state
theta1 = Parameter('t1')
qc.rx(theta1,4)
# Prepare the training data quantum state
qc.h(2)
qc.rz(-np.pi,2)
qc.s(2)
qc.cz(1,2)
# Put the label
qc.cx(1,3)
qc.barrier()
# Perform swap-test
swaptest(qc,0,2,4)
qc.barrier()
# Measurement
qc.measure(0,0)
qc.measure(3,1)
qc.draw(output='mpl')
# Select the range of parameters
theta1_range = np.linspace(0, 2 * np.pi, 20)
# Execute multiple circuits
job = execute(qc, backend=Aer.get_backend('qasm_simulator'), shots = 8192,
parameter_binds=[{theta1: theta_val1} for theta_val1 in theta1_range])
# Store all counts
counts = [job.result().get_counts(i) for i in range(len(job.result().results))]
# Let's see how the 'counts' looks like
counts
# Plot to visualize the result
plt.figure(figsize=(12,6))
plt.rcParams.update({'font.size': 20})
# How to extract <ZZ>? Answer: <ZZ> = P(00) - P(01) - P(10) + P(11)
plt.plot(theta1_range,
list(map(lambda counts: (counts.get('00')-counts.get('10')-counts.get('01')+counts.get('11'))/8192,
counts)))
plt.rc('text', usetex=True)
plt.xlabel(r'$\theta$ (Parameter for test data)')
plt.ylabel(r'$ \langle Z\otimes Z \rangle $')
plt.show()
# Let's also try the same experiment on the 5-qubit device.
# Select the range of parameters
theta1_range = np.linspace(0, 2 * np.pi, 20)
# Execute multiple circuits
job_classifier = execute(qc, backend=provider.get_backend('ibmq_essex'), shots = 8192,
parameter_binds=[{theta1: theta_val1} for theta_val1 in theta1_range])
# Monitor job status
job_monitor(job_classifier)
# Store all counts
counts_exp = [job_classifier.result().get_counts(i) for i in range(len(job_classifier.result().results))]
# Plot to visualize the result
plt.figure(figsize=(12,6))
plt.rcParams.update({'font.size': 20})
# Plot theory
plt.plot(theta1_range,
list(map(lambda counts: (counts.get('00')-counts.get('10')-counts.get('01')+counts.get('11'))/8192,
counts)),'r',label='Theory')
# Plot experimental result
plt.plot(theta1_range,
list(map(lambda counts_exp: 4*(counts_exp.get('00')-counts_exp.get('10')
-counts_exp.get('01')+counts_exp.get('11'))/8192,counts_exp)),'b',
label='Exp. (scaled by a factor of 4)')
plt.rc('text', usetex=True)
plt.xlabel(r'$\theta$ (Parameter for test data)')
plt.ylabel(r'$ \langle Z\otimes Z \rangle $')
plt.legend(loc='best')
plt.show()
|
https://github.com/dkp-quantum/Tutorials
|
dkp-quantum
|
%matplotlib inline
# Importing standard Qiskit libraries and configuring account
from qiskit import *
from qiskit.visualization import *
import numpy as np
# Create a quantum register with 2 qubits
q = QuantumRegister(2,'q')
# Form a quantum circuit
# Note that the circuit name is optional
qc = QuantumCircuit(q,name="first_qc")
# Display the quantum circuit
qc.draw()
# Add a Hadamard gate on qubit 0, putting this in superposition.
qc.h(0)
# Add a CX (CNOT) gate on control qubit 0
# and target qubit 1 to create an entangled state.
qc.cx(0, 1)
qc.draw()
# Create a classical register with 2 bits
c = ClassicalRegister(2,'c')
meas = QuantumCircuit(q,c,name="first_m")
meas.barrier(q)
meas.measure(q, c)
meas.draw()
# Quantum circuits can be added with + operations
# Add two pre-defined circuits
qc_all=qc+meas
qc_all.draw()
# Draw the quantum circuit in a different (slightly better) format
qc_all.draw(output='mpl')
# Create the quantum circuit with the measurement in one go.
qc_all = QuantumCircuit(q,c,name="2q_all")
qc_all.h(0)
qc_all.cx(0,1)
qc_all.barrier()
qc_all.measure(0,0)
qc_all.measure(1,1)
qc_all.draw(output='mpl')
# Use Aer's qasm_simulator
backend_q = Aer.get_backend('qasm_simulator')
# Execute the circuit on the qasm simulator.
job_sim1 = execute(qc_all, backend_q, shots=4096)
job_sim1.status()
# Grab the results from the job.
result_sim1 = job_sim1.result()
result_sim1
result_sim1.get_counts(qc_all)
plot_histogram(result_sim1.get_counts(qc_all))
# Use Aer's statevector_simulator
backend_sv = Aer.get_backend('statevector_simulator')
# Execute the circuit on the statevector simulator.
# It is important to note that the measurement has been excluded
job_sim2 = execute(qc, backend_sv)
# Grab the results from the job.
result_sim2 = job_sim2.result()
# Output the entire result
result_sim2
# See output state as a vector
outputstate = result_sim2.get_statevector(qc, decimals=5)
print(outputstate)
# Visualize density matrix
plot_state_city(outputstate)
# Create the quantum circuit with the measurement in one go.
qc_3 = QuantumCircuit(3,3,name="qc_bloch")
qc_3.x(1)
qc_3.h(2)
qc_3.barrier()
qc_3.draw(output='mpl')
# Execute the circuit on the statevector simulator.
# It is important to note that the measurement has been excluded
job_sim_bloch = execute(qc_3, backend_sv)
# Grab the results from the job.
result_sim_bloch = job_sim_bloch.result()
# See output state as a vector
output_bloch = result_sim_bloch.get_statevector(qc_3, decimals=5)
# Draw on the Bloch sphere
plot_bloch_multivector(output_bloch)
# Use Aer's unitary_simulator
backend_u = Aer.get_backend('unitary_simulator')
# Execute the circuit on the unitary simulator.
job_usim = execute(qc, backend_u)
# Grab the results from the job.
result_usim = job_usim.result()
result_usim
# Output the unitary matrix
unitary = result_usim.get_unitary(qc)
print('%s\n' % unitary)
# Create the quantum circuit with the measurement in one go.
qc_ex1 = QuantumCircuit(q,c,name="ex1")
# Put the first qubit in equal superposition
qc_ex1.h(0)
# Rest of the circuit
qc_ex1.x(1)
qc_ex1.cx(0,1)
qc_ex1.barrier()
qc_ex1.measure(0,0)
qc_ex1.measure(1,1)
qc_ex1.draw(output='mpl')
# Execute the circuit on the qasm simulator.
job_ex1 = execute(qc_ex1, backend_q, shots=4096)
job_ex1.status()
# Grab the results from the job.
result_ex1 = job_ex1.result()
result_ex1.get_counts(qc_ex1)
plot_histogram(result_ex1.get_counts(qc_ex1))
# Or get the histogram in one go
plot_histogram(job_ex1.result().get_counts(qc_ex1))
# Create a quantum register with 3 qubits
q3 = QuantumRegister(3,'q')
# Create a classical register with 3 qubits
c3 = ClassicalRegister(3,'c')
# Create the quantum circuit with the measurement in one go.
qc_ex2 = QuantumCircuit(q3,c3,name="ex1")
qc_ex2.ry(2*np.pi/3,0)
qc_ex2.cx(0,1)
qc_ex2.cx(1,2)
qc_ex2.barrier()
qc_ex2.measure(q3,c3)
qc_ex2.draw(output='mpl')
# Execute the circuit on the qasm simulator.
job_ex2 = execute(qc_ex2, backend_q, shots=4096)
# Grab the results from the job.
result_ex2 = job_ex2.result()
plot_histogram(result_ex2.get_counts(qc_ex2))
# Create a quantum register with 3 qubits
q3 = QuantumRegister(3,'q')
# Create a classical register with 3 qubits
c3 = ClassicalRegister(3,'c')
# Create the quantum circuit without a Toffoli gate
qc_toff = QuantumCircuit(q3,c3,name="ex1")
qc_toff.ry(2*np.pi/3,0)
qc_toff.h(1)
qc_toff.h(2)
qc_toff.barrier()
qc_toff.measure(q3,c3)
qc_toff.draw(output='mpl')
# Execute the circuit on the qasm simulator.
job_toff = execute(qc_toff, backend_q, shots=4096)
# Grab the results from the job.
result_toff = job_toff.result()
plot_histogram(result_toff.get_counts(qc_toff))
# Now, add a Toffoli gate
qc_toff = QuantumCircuit(q3,c3,name="ex1")
qc_toff.ry(2*np.pi/3,0)
qc_toff.h(1)
qc_toff.h(2)
qc_toff.ccx(1,2,0)
qc_toff.barrier()
qc_toff.measure(q3,c3)
qc_toff.draw(output='mpl')
# Execute the circuit on the qasm simulator.
job_toff = execute(qc_toff, backend_q, shots=4096)
# Grab the results from the job.
result_toff = job_toff.result()
plot_histogram(result_toff.get_counts(qc_toff))
IBMQ.disable_account()
provider = IBMQ.enable_account('IBM_TOKEN')
# provider = IBMQ.get_provider(hub='ibm-q-research')
provider.backends()
from qiskit.tools.monitor import backend_overview, backend_monitor, job_monitor
from qiskit.tools.visualization import plot_gate_map, plot_error_map
# Retrieve IBM Quantum device information
backend_overview()
# Let's get two quantum devices as an example
backend_qx2 = provider.get_backend('ibmqx2')
backend_vigo = provider.get_backend('ibmq_vigo')
backend_monitor(backend_qx2)
plot_error_map(backend_qx2)
backend_monitor(backend_vigo)
plot_error_map(backend_vigo)
#
# Create a 5-qubit GHZ state (i.e. (|00000> + |11111>)/sqrt(2))
q5 = QuantumRegister(5,'q')
c5 = ClassicalRegister(5,'c')
ghz5= QuantumCircuit(q5,c5)
ghz5.h(0)
for i in range(1,5):
ghz5.cx(0,i)
ghz5.barrier()
ghz5.measure(q5,c5)
ghz5.draw(output='mpl')
# Run the 5-qubit GHZ experiment on a 5-qubit device (try vigo)
job_exp1 = execute(ghz5, backend=backend_vigo, shots=4096)
job_monitor(job_exp1)
# Grab experimental results
result_vigo = job_exp1.result()
counts_vigo = result_vigo.get_counts(ghz5)
# Let's also try the same experiment on the 14-qubit device.
job_exp2 = execute(ghz5, backend=provider.get_backend('ibmq_16_melbourne'), shots=4096)
job_monitor(job_exp2)
# Grab experimental results
result_mel = job_exp2.result()
counts_mel = result_mel.get_counts(ghz5)
# Now, compare to theory by running it on qasm_simulator
job_qasm = execute(ghz5,backend=backend_q)
result_qasm = job_qasm.result()
counts_qasm = result_qasm.get_counts(ghz5)
# Plot both experimental and ideal results
plot_histogram([counts_qasm,counts_vigo,counts_mel],
color=['black','green','blue'],
legend=['QASM','Vigo','Melbourne'],figsize = [20,8])
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
# Importing standard Qiskit libraries and configuring account
from qiskit import *
from qiskit.visualization import *
from qiskit.circuit import Parameter
# Simple example
# Define two parameters, t1 and t2
theta1 = Parameter('t1')
theta2 = Parameter('t2')
# Build a 1-qubit circuit
qc = QuantumCircuit(1, 1)
# First parameter, t1, is used for a single qubit rotation of a controlled qubit
qc.ry(theta1,0)
qc.rz(theta2,0)
qc.barrier()
qc.measure(0, 0)
qc.draw(output='mpl')
theta1_range = np.linspace(0, 2 * np.pi, 20)
theta2_range = np.linspace(0, np.pi, 2)
circuits = [qc.bind_parameters({theta1: theta_val1, theta2: theta_val2})
for theta_val2 in theta2_range for theta_val1 in theta1_range ]
# Visualize several circuits to check that correct circuits are generated correctly.
display(circuits[0].draw(output='mpl'))
display(circuits[1].draw(output='mpl'))
display(circuits[20].draw(output='mpl'))
# Execute multiple circuits
job = execute(qc, backend=Aer.get_backend('qasm_simulator'), shots = 8192,
parameter_binds=[{theta1: theta_val1, theta2: theta_val2}
for theta_val2 in theta2_range for theta_val1 in theta1_range])
# Store all counts
counts = [job.result().get_counts(i) for i in range(len(job.result().results))]
# Plot to visualize the result
plt.figure(figsize=(12,6))
plt.plot(range(len(theta1_range)*len(theta2_range)),
list(map(lambda counts: (counts.get('0',0)-counts.get('1',1))/8192,counts)))
plt.show()
# IBMQ.disable_account()
provider = IBMQ.enable_account('TOKEN')
from qiskit.tools.monitor import backend_overview, backend_monitor, job_monitor
from qiskit.tools.visualization import plot_gate_map, plot_error_map
# Retrieve IBM Quantum device information
backend_overview()
# Execute multiple circuits
job_exp = execute(qc, backend=provider.get_backend('ibmq_essex'), shots = 8192,
parameter_binds=[{theta1: theta_val1, theta2: theta_val2}
for theta_val2 in theta2_range for theta_val1 in theta1_range])
# Monitor job status
job_monitor(job_exp)
# Store all counts
counts_exp = [job_exp.result().get_counts(i) for i in range(len(job_exp.result().results))]
# Plot to visualize the result
plt.figure(figsize=(12,6))
plt.rcParams.update({'font.size': 16})
plt.plot(range(len(theta1_range)*len(theta2_range)),
list(map(lambda counts: (counts.get('0',0)-counts.get('1',1))/8192,counts)),'r',label='Simulation')
plt.plot(range(len(theta1_range)*len(theta2_range)),
list(map(lambda counts_exp: (counts_exp.get('0',0)-counts_exp.get('1',1))/8192,counts_exp)),
'b',label='Experiment')
plt.legend(loc='best')
plt.show()
from qiskit.compiler import transpile
from qiskit.transpiler import PassManager, Layout
display(plot_error_map(provider.get_backend('ibmqx2')))
display(plot_error_map(provider.get_backend('ibmq_burlington')))
# Create a dummy circuit for default transpiler demonstration
qc = QuantumCircuit(4)
qc.h(0)
qc.swap(0,1)
qc.cx(1,0)
qc.s(3)
qc.x(3)
qc.h(3)
qc.h(0)
qc.cx(0,2)
qc.ccx(0,1,2)
qc.h(0)
print('Original circuit')
display(qc.draw(output='mpl'))
# Transpile the circuit to run on ibmqx2
qt_qx2 = transpile(qc,provider.get_backend('ibmqx2'))
print('Transpiled circuit for ibmqx2')
display(qt_qx2.draw(output='mpl'))
# Transpile the circuit to run on ibmq_burlington
qt_bu = transpile(qc,provider.get_backend('ibmq_burlington'))
print('Transpiled circuit for ibmqx_Burlington')
display(qt_bu.draw(output='mpl'))
# Print out some circuit properties
# Total nunmber of operations
print("Number of operations for ibmqx2 = %s" % qt_qx2.size())
print("Number of operations for ibmq_burlington = %s \n" % qt_bu.size())
# Circuit depth
print("Circuit depth for ibmqx2 = %s" % qt_qx2.depth())
print("Circuit depth for ibmq_burlington = %s \n" % qt_bu.depth())
# Number of qubits
print("Number of qubits for ibmqx2 = %s" % qt_qx2.width())
print("Number of qubits for ibmq_burlington = %s \n" % qt_bu.width())
# Breakdown of operations by type
print("Operations for ibmqx2: %s" % qt_qx2.count_ops())
print("Operations for ibmq_burlington: %s \n" % qt_bu.count_ops())
# Number of unentangled subcircuits in this circuit.
# In principle, each subcircuit can be executed on a different quantum device.
print("Number of unentangled subcircuits for ibmqx2 = %s" % qt_qx2.num_tensor_factors())
print("Number of unentangled subcircuits for ibmq_burlington = %s" % qt_bu.num_tensor_factors())
qr = QuantumRegister(4,'q')
cr = ClassicalRegister(4,'c')
qc_test = QuantumCircuit(qr,cr)
qc_test.h(0)
for i in range(3):
qc_test.cx(i,i+1)
qc_test.barrier()
qc_test.measure(qr,cr)
qc_test.draw(output='mpl')
qc_t = transpile(qc_test, backend = provider.get_backend('ibmq_london'))
# Display transpiled circuit
display(qc_t.draw(output='mpl'))
# Display the qubit layout
display(plot_error_map(provider.get_backend('ibmq_london')))
# Print out some circuit properties
# Total nunmber of operations
print("Number of operations = %s" % qc_t.size())
# Circuit depth
print("Circuit depth = %s" % qc_t.depth())
# Execute the circuit on the qasm simulator.
job_test = execute(qc_test, provider.get_backend('ibmq_london'), shots=8192)
job_monitor(job_test)
# Customize the layout
layout = Layout({qr[0]: 4, qr[1]: 3, qr[2]: 1, qr[3]:0})
# Map it onto 5 qubit backend ibmqx2
qc_test_new = transpile(qc_test, backend = provider.get_backend('ibmq_london'), initial_layout=layout, basis_gates=['u1','u2','u3','cx'])
display(qc_test_new.draw(output='mpl'))
# Print out some circuit properties
# Total nunmber of operations
print("Number of operations = %s" % qc_test_new.size())
# Circuit depth
print("Circuit depth = %s" % qc_test_new.depth())
# Execute the circuit on the qasm simulator.
job_test_new = execute(qc_test_new, provider.get_backend('ibmq_london'), shots=8192)
job_monitor(job_test_new)
# Now, compare the two
result_test = job_test.result()
result_test_new = job_test_new.result()
# Plot both experimental and ideal results
plot_histogram([result_test.get_counts(qc_test),result_test_new.get_counts(qc_test_new)],
color=['green','blue'],legend=['default','custom'],figsize = [20,8])
# Apply 4-qubit controlled x gate
qr = QuantumRegister(5,'q')
qc = QuantumCircuit(qr)
qc.h(0)
qc.h(1)
qc.h(3)
qc.ccx(0,1,2)
qc.ccx(2,3,4)
qc.ccx(0,1,2)
display(qc.draw(output='mpl'))
# Print out some circuit properties
# Total nunmber of operations
print("Number of operations = %s \n" % qc.size())
# Count different types of operations
print("Operation counts = %s \n" % qc.count_ops())
# Circuit depth
print("Circuit depth = %s" % qc.depth())
qc_t = transpile(qc, provider.get_backend('ibmq_valencia'))
display(qc_t.draw(output='mpl'))
# Print out some circuit properties
# Total nunmber of operations
print("Number of operations = %s" % qc_t.size())
# Circuit depth
print("Circuit depth = %s" % qc_t.depth())
# Transpile many times (20 times in this example) and pick the best one
trial = 20
# Use ibmq_valencia for example
backend_exp = provider.get_backend('ibmq_valencia')
tcircs0 = transpile([qc]*trial, backend_exp, optimization_level=0)
tcircs1 = transpile([qc]*trial, backend_exp, optimization_level=1)
tcircs2 = transpile([qc]*trial, backend_exp, optimization_level=2)
tcircs3 = transpile([qc]*trial, backend_exp, optimization_level=3)
import matplotlib.pyplot as plt
num_cx0 = [c.count_ops()['cx'] for c in tcircs0]
num_cx1 = [c.count_ops()['cx'] for c in tcircs1]
num_cx2 = [c.count_ops()['cx'] for c in tcircs2]
num_cx3 = [c.count_ops()['cx'] for c in tcircs3]
num_tot0 = [c.size() for c in tcircs0]
num_tot1 = [c.size() for c in tcircs1]
num_tot2 = [c.size() for c in tcircs2]
num_tot3 = [c.size() for c in tcircs3]
num_depth0 = [c.depth() for c in tcircs0]
num_depth1 = [c.depth() for c in tcircs1]
num_depth2 = [c.depth() for c in tcircs2]
num_depth3 = [c.depth() for c in tcircs3]
plt.rcParams.update({'font.size': 16})
# Plot the number of CNOT gates
plt.figure(figsize=(12,6))
plt.plot(range(len(num_cx0)),num_cx0,'r',label='level 0')
plt.plot(range(len(num_cx1)),num_cx1,'b',label='level 1')
plt.plot(range(len(num_cx2)),num_cx2,'g',label='level 2')
plt.plot(range(len(num_cx3)),num_cx3,'k',label='level 3')
plt.legend(loc='upper left')
plt.xlabel('Random trial')
plt.ylabel('# of cx gates')
plt.show()
# Plot total number of gates
plt.figure(figsize=(12,6))
plt.plot(range(len(num_tot0)),num_tot0,'r',label='level 0')
plt.plot(range(len(num_tot1)),num_tot1,'b',label='level 1')
plt.plot(range(len(num_tot2)),num_tot2,'g',label='level 2')
plt.plot(range(len(num_tot3)),num_tot3,'k',label='level 3')
plt.legend(loc='upper left')
plt.xlabel('Random trial')
plt.ylabel('# of total gates')
plt.show()
# Plot the number of CNOT gates
plt.figure(figsize=(12,6))
plt.plot(range(len(num_depth0)),num_depth0,'r',label='level 0')
plt.plot(range(len(num_depth1)),num_depth1,'b',label='level 1')
plt.plot(range(len(num_depth2)),num_depth2,'g',label='level 2')
plt.plot(range(len(num_depth3)),num_depth3,'k',label='level 3')
plt.legend(loc='upper left')
plt.xlabel('Random trial')
plt.ylabel('Circuit depth')
plt.show()
print('Opt0: Minimum # of cx gates = %s' % min(num_cx0))
print('Opt0: The best circuit is the circut %s \n' % num_cx0.index(min(num_cx0)))
print('Opt1: Minimum # of cx gates = %s' % min(num_cx1))
print('Opt1: The best circuit is the circut %s \n' % num_cx1.index(min(num_cx1)))
print('Opt2: Minimum # of cx gates = %s' % min(num_cx2))
print('Opt2: The best circuit is the circut %s \n' % num_cx2.index(min(num_cx2)))
print('Opt3: Minimum # of cx gates = %s' % min(num_cx3))
print('Opt3: The best circuit is the circut %s' % num_cx3.index(min(num_cx3)))
|
https://github.com/dkp-quantum/Tutorials
|
dkp-quantum
|
%matplotlib inline
# Importing standard Qiskit libraries and configuring account
from qiskit import QuantumCircuit, execute, Aer, IBMQ
from qiskit.compiler import transpile, assemble
from qiskit.tools.jupyter import *
from qiskit.visualization import *
# Loading your IBM Q account(s)
provider = IBMQ.load_account()
import scipy
from scipy.stats import unitary_group
u = unitary_group.rvs(2)
print(u)
qc = QuantumCircuit(2)
qc.iso(u, [0], [])
qc = transpile(qc, basis_gates = ['u3', 'cx'], seed_transpiler=0, optimization_level=3)
circuit_drawer(qc)
import scipy
from scipy import linalg
h = scipy.linalg.hadamard(2)
import numpy as np
u1 = np.dot(h, u)
u2 = np.dot(u1, h)
c2 = []
for i in range (2):
c2.append(u2[i,i])
print(c2)
qc = QuantumCircuit(2)
qc.diagonal(c2, [0])
qc = transpile(qc, basis_gates = ['u3', 'cx'], seed_transpiler=0, optimization_level=3)
circuit_drawer(qc)
import scipy
from scipy.stats import unitary_group
u = unitary_group.rvs(4)
print(u)
qc = QuantumCircuit(4)
qc.iso(u, [0,1], [])
qc = transpile(qc, basis_gates = ['u3', 'cx'], seed_transpiler=0, optimization_level=3)
circuit_drawer(qc)
import scipy
from scipy import linalg
h = scipy.linalg.hadamard(4)/2
import numpy as np
u1 = np.dot(h, u)
u2 = np.dot(u1, h)
c2 = []
for i in range (4):
c2.append(u2[i,i])
print(c2)
qc = QuantumCircuit(4)
qc.diagonal(c2, [0, 1])
qc = transpile(qc, basis_gates = ['u3', 'cx'], seed_transpiler=0, optimization_level=3)
circuit_drawer(qc)
import scipy
from scipy.stats import unitary_group
u = unitary_group.rvs(8)
print(u)
qc = QuantumCircuit(4)
qc.iso(u, [0, 1, 2], [])
qc = transpile(qc, basis_gates = ['u3', 'cx'], seed_transpiler=0, optimization_level=3)
circuit_drawer(qc)
import scipy
from scipy import linalg
h = scipy.linalg.hadamard(8)/3
import numpy as np
u1 = np.dot(h, u)
u2 = np.dot(u1, h)
c2 = []
for i in range (8):
c2.append(u2[i,i])
print(c2)
qc = QuantumCircuit(4)
qc.diagonal(c2, [0, 1, 2])
qc = transpile(qc, basis_gates = ['u3', 'cx'], seed_transpiler=0, optimization_level=3)
circuit_drawer(qc)
import scipy
from scipy.stats import unitary_group
u = unitary_group.rvs(16)
print(u)
qc = QuantumCircuit(4)
qc.iso(u, [0, 1, 2, 3], [])
qc = transpile(qc, basis_gates = ['u3', 'cx'], seed_transpiler=0, optimization_level=3)
circuit_drawer(qc)
import scipy
from scipy import linalg
h = scipy.linalg.hadamard(16)/4
import numpy as np
u1 = np.dot(h, u)
u2 = np.dot(u1, h)
c2 = []
for i in range (16):
c2.append(u2[i,i])
print(c2)
qc = QuantumCircuit(4)
qc.diagonal(c2, [0, 1, 2, 3])
qc = transpile(qc, basis_gates = ['u3', 'cx'], seed_transpiler=0, optimization_level=3)
circuit_drawer(qc)
import scipy
from scipy.stats import unitary_group
u = unitary_group.rvs(32)
print(u)
qc = QuantumCircuit(8)
qc.iso(u, [0, 1, 2, 3, 4], [])
qc = transpile(qc, basis_gates = ['u3', 'cx'], seed_transpiler=0, optimization_level=3)
circuit_drawer(qc)
import scipy
from scipy import linalg
h = scipy.linalg.hadamard(32)/5
import numpy as np
u1 = np.dot(h, u)
u2 = np.dot(u1, h)
c2 = []
for i in range (32):
c2.append(u2[i,i])
print(c2)
qc = QuantumCircuit(8)
qc.diagonal(c2, [0, 1, 2, 3, 4])
qc = transpile(qc, basis_gates = ['u3', 'cx'], seed_transpiler=0, optimization_level=3)
circuit_drawer(qc)
import scipy
from scipy.stats import unitary_group
u = unitary_group.rvs(64)
print(u)
qc = QuantumCircuit(8)
qc.iso(u, [0, 1, 2, 3, 4, 5], [])
qc = transpile(qc, basis_gates = ['u3', 'cx'], seed_transpiler=0, optimization_level=3)
circuit_drawer(qc)
import scipy
from scipy import linalg
h = scipy.linalg.hadamard(64)/6
import numpy as np
u1 = np.dot(h, u)
u2 = np.dot(u1, h)
c2 = []
for i in range (64):
c2.append(u2[i,i])
print(c2)
qc = QuantumCircuit(8)
qc.diagonal(c2, [0, 1, 2, 3, 4, 5])
qc = transpile(qc, basis_gates = ['u3', 'cx'], seed_transpiler=0, optimization_level=3)
circuit_drawer(qc)
import scipy
from scipy.stats import unitary_group
u = unitary_group.rvs(128)
print(u)
qc = QuantumCircuit(8)
qc.iso(u, [0, 1, 2, 3, 4, 5, 6], [])
qc = transpile(qc, basis_gates = ['u3', 'cx'], seed_transpiler=0, optimization_level=3)
circuit_drawer(qc)
import scipy
from scipy import linalg
h = scipy.linalg.hadamard(128)/7
import numpy as np
u1 = np.dot(h, u)
u2 = np.dot(u1, h)
c2 = []
for i in range (128):
c2.append(u2[i,i])
print(c2)
qc = QuantumCircuit(8)
qc.diagonal(c2, [0, 1, 2, 3, 4, 5, 6])
qc = transpile(qc, basis_gates = ['u3', 'cx'], seed_transpiler=0, optimization_level=3)
circuit_drawer(qc)
import scipy
from scipy.stats import unitary_group
u = unitary_group.rvs(256)
print(u)
qc = QuantumCircuit(8)
qc.iso(u, [0, 1, 2, 3, 4, 5, 6, 7], [])
qc = transpile(qc, basis_gates = ['u3', 'cx'], seed_transpiler=0, optimization_level=3)
circuit_drawer(qc)
import scipy
from scipy import linalg
h = scipy.linalg.hadamard(256)/8
import numpy as np
u1 = np.dot(h, u)
u2 = np.dot(u1, h)
c2 = []
for i in range (256):
c2.append(u2[i,i])
print(c2)
qc = QuantumCircuit(8)
qc.diagonal(c2, [0, 1, 2, 3, 4, 5, 6, 7])
qc = transpile(qc, basis_gates = ['u3', 'cx'], seed_transpiler=0, optimization_level=3)
circuit_drawer(qc)
import scipy
from scipy.stats import unitary_group
u = unitary_group.rvs(512)
print(u)
qc = QuantumCircuit(16)
qc.iso(u, [0, 1, 2, 3, 4, 5, 6, 7, 8], [])
qc = transpile(qc, basis_gates = ['u3', 'cx'], seed_transpiler=0, optimization_level=3)
circuit_drawer(qc)
import scipy
from scipy import linalg
h = scipy.linalg.hadamard(512)/9
import numpy as np
u1 = np.dot(h, u)
u2 = np.dot(u1, h)
c2 = []
for i in range (512):
c2.append(u2[i,i])
print(c2)
qc = QuantumCircuit(16)
qc.diagonal(c2, [0, 1, 2, 3, 4, 5, 6, 7, 8])
qc = transpile(qc, basis_gates = ['u3', 'cx'], seed_transpiler=0, optimization_level=3)
circuit_drawer(qc)
import scipy
from scipy.stats import unitary_group
u = unitary_group.rvs(1024)
print(u)
qc = QuantumCircuit(16)
qc.iso(u, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [])
qc = transpile(qc, basis_gates = ['u3', 'cx'], seed_transpiler=0, optimization_level=3)
circuit_drawer(qc)
import scipy
from scipy import linalg
h = scipy.linalg.hadamard(1024)/10
import numpy as np
u1 = np.dot(h, u)
u2 = np.dot(u1, h)
c2 = []
for i in range (1024):
c2.append(u2[i,i])
print(c2)
qc = QuantumCircuit(16)
qc.diagonal(c2, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
qc = transpile(qc, basis_gates = ['u3', 'cx'], seed_transpiler=0, optimization_level=3)
circuit_drawer(qc)
|
https://github.com/dkp-quantum/Tutorials
|
dkp-quantum
|
import warnings
warnings.filterwarnings("ignore", category=DeprecationWarning)
import qiskit as qk
qr0 = qk.QuantumRegister(1,name='qb') # qb for "qubit", but the name is optional
cr0 = qk.ClassicalRegister(1,name='b') # b for "bit", but the name is optional
qc0 = qk.QuantumCircuit(qr0,cr0)
qc0.draw(output='mpl') # this is to visualize the circuit. Remove the output option for a different style.
from qiskit.tools.visualization import plot_bloch_vector
import math
theta = math.pi/2 # You can try to change the parameters theta and phi
phi = math.pi/4 # to see how the vector moves on the sphere
plot_bloch_vector([math.cos(phi)*math.sin(theta),math.sin(phi)*math.sin(theta),math.cos(theta)]) # Entries of the
# input vector are
# coordinates [x,y,z]
qc0.measure(qr0[0],cr0[0])
qc0.draw(output='mpl')
backend = qk.Aer.get_backend('qasm_simulator')
job = qk.execute(qc0, backend, shots=1024)
result = job.result()
counts = result.get_counts()
print(counts)
qc1 = qk.QuantumCircuit(qr0,cr0)
qc1.x(qr0[0]) # A X gate targeting the first (and only) qubit in register qr0
qc1.measure(qr0[0],cr0[0])
qc1.draw(output='mpl')
backend = qk.Aer.get_backend('qasm_simulator')
job1 = qk.execute(qc1, backend, shots=1024)
result1 = job1.result()
counts1 = result1.get_counts()
print(counts1)
from qiskit.tools.visualization import plot_bloch_multivector
vec_backend = qk.Aer.get_backend('statevector_simulator')
result_vec0 = qk.execute(qc0, vec_backend).result()
result_vec1 = qk.execute(qc1, vec_backend).result()
psi0 = result_vec0.get_statevector()
psi1 = result_vec1.get_statevector()
plot_bloch_multivector(psi0)
plot_bloch_multivector(psi1)
qc2 = qk.QuantumCircuit(qr0,cr0)
qc2.h(qr0[0])
qc2.measure(qr0[0],cr0[0])
qc2.draw(output='mpl')
job2 = qk.execute(qc2, backend, shots=1024)
result2 = job2.result()
counts2 = result2.get_counts()
print(counts2)
qc2_bis = qk.QuantumCircuit(qr0,cr0)
qc2_bis.h(qr0[0])
result_vec2 = qk.execute(qc2_bis, vec_backend).result()
psi2 = result_vec2.get_statevector()
plot_bloch_multivector(psi2)
qc3 = qk.QuantumCircuit(qr0,cr0)
qc3.h(qr0[0])
qc3.s(qr0[0]) # Use sdg instead of s for the adjoint
qc3.measure(qr0[0],cr0[0])
qc3.draw(output='mpl')
job3 = qk.execute(qc3, backend, shots=1024)
result3 = job3.result()
counts3 = result3.get_counts()
print(counts3)
qc3_bis = qk.QuantumCircuit(qr0,cr0)
qc3_bis.h(qr0[0])
qc3_bis.s(qr0[0])
result_vec3 = qk.execute(qc3_bis, vec_backend).result()
psi3 = result_vec3.get_statevector()
plot_bloch_multivector(psi3)
qc4 = qk.QuantumCircuit(qr0,cr0)
qc4.h(qr0[0])
qc4.t(qr0[0]) # Use tdg instead of t for the adjoint
qc4.measure(qr0[0],cr0[0])
qc4.draw(output='mpl')
job4 = qk.execute(qc4, backend, shots=1024)
result4 = job4.result()
counts4 = result4.get_counts()
print(counts4)
qc4_bis = qk.QuantumCircuit(qr0,cr0)
qc4_bis.h(qr0[0])
qc4_bis.t(qr0[0])
result_vec4 = qk.execute(qc4_bis, vec_backend).result()
psi4 = result_vec4.get_statevector()
plot_bloch_multivector(psi4)
lmbd = 1.2 # Change this value to rotate the output vector on the equator of the Bloch sphere
qc5 = qk.QuantumCircuit(qr0,cr0)
qc5.h(qr0[0])
qc5.u1(lmbd, qr0[0])
qc5.draw(output='mpl')
result_vec5 = qk.execute(qc5, vec_backend).result()
psi5 = result_vec5.get_statevector()
plot_bloch_multivector(psi5)
qc6 = qk.QuantumCircuit(qr0,cr0)
qc6.u2(0,math.pi, qr0[0])
result_vec6 = qk.execute(qc6, vec_backend).result()
psi6 = result_vec6.get_statevector()
plot_bloch_multivector(psi6)
theta = 0.5
phi = math.pi/4
lmb = math.pi/8
qc7 = qk.QuantumCircuit(qr0,cr0)
qc7.u3(theta,phi, lmb, qr0[0])
result_vec7 = qk.execute(qc7, vec_backend).result()
psi7 = result_vec7.get_statevector()
plot_bloch_multivector(psi7)
qr = qk.QuantumRegister(2,name='qr') # we need a 2-qubit register now
cr = qk.ClassicalRegister(2,name='cr')
cnot_example = qk.QuantumCircuit(qr,cr)
cnot_example.x(qr[0])
cnot_example.cx(qr[0],qr[1]) # First entry is control, the second is the target
cnot_example.measure(qr[0],cr[0])
cnot_example.measure(qr[1],cr[1])
cnot_example.draw(output='mpl')
job_cnot = qk.execute(cnot_example, backend, shots=1024)
result_cnot = job_cnot.result()
counts_cnot = result_cnot.get_counts()
print(counts_cnot)
cnot_reversed = qk.QuantumCircuit(qr,cr)
cnot_reversed.x(qr[0])
# This part uses cx(qr[1],qr[0]) but is equivalent to cx(qr[0],qr[1])
cnot_reversed.h(qr[0])
cnot_reversed.h(qr[1])
cnot_reversed.cx(qr[1],qr[0])
cnot_reversed.h(qr[0])
cnot_reversed.h(qr[1])
#
cnot_reversed.measure(qr[0],cr[0])
cnot_reversed.measure(qr[1],cr[1])
cnot_reversed.draw(output='mpl')
job_cnot_rev = qk.execute(cnot_reversed, backend, shots=1024)
result_cnot_rev = job_cnot_rev.result()
counts_cnot_rev = result_cnot_rev.get_counts()
print(counts_cnot_rev)
bell_phi_p = qk.QuantumCircuit(qr,cr)
bell_phi_p.h(qr[0])
bell_phi_p.cx(qr[0],qr[1])
bell_phi_p.measure(qr[0],cr[0])
bell_phi_p.measure(qr[1],cr[1])
bell_phi_p.draw(output='mpl')
job_bell_phi_p = qk.execute(bell_phi_p, backend, shots=1024)
result_bell_phi_p = job_bell_phi_p.result()
counts_bell_phi_p = result_bell_phi_p.get_counts()
print(counts_bell_phi_p)
cz_example = qk.QuantumCircuit(qr)
cz_example.cz(qr[0],qr[1])
cz_example.draw(output='mpl')
cz_from_cnot = qk.QuantumCircuit(qr)
cz_from_cnot.h(qr[1])
cz_from_cnot.cx(qr[0],qr[1])
cz_from_cnot.h(qr[1])
cz_from_cnot.draw(output='mpl')
delta = 0.5
cphase_test = qk.QuantumCircuit(qr)
cphase_test.cu1(delta,qr[0],qr[1])
cphase_test.draw(output='mpl')
delta = 0.5
cphase_from_cnot = qk.QuantumCircuit(qr)
cphase_from_cnot.u1(delta/2,qr[1])
cphase_from_cnot.cx(qr[0],qr[1])
cphase_from_cnot.u1(-delta/2,qr[1])
cphase_from_cnot.cx(qr[0],qr[1])
cphase_from_cnot.u1(delta/2,qr[0])
cphase_from_cnot.draw(output='mpl')
swap_test = qk.QuantumCircuit(qr)
swap_test.swap(qr[0],qr[1])
swap_test.draw(output='mpl')
swap_from_cnot = qk.QuantumCircuit(qr)
swap_from_cnot.cx(qr[0],qr[1])
swap_from_cnot.cx(qr[1],qr[0])
swap_from_cnot.cx(qr[0],qr[1])
swap_from_cnot.draw(output='mpl')
qr_many = qk.QuantumRegister(5)
control_example = qk.QuantumCircuit(qr_many)
control_example.cy(qr_many[0],qr_many[1])
control_example.ch(qr_many[1],qr_many[2])
control_example.crz(0.2,qr_many[2],qr_many[3])
control_example.cu3(0.5, 0, 0, qr_many[3],qr_many[4])
control_example.draw(output='mpl')
qrthree = qk.QuantumRegister(3)
toffoli_example = qk.QuantumCircuit(qrthree)
toffoli_example.ccx(qrthree[0],qrthree[1],qrthree[2])
toffoli_example.draw(output='mpl')
toffoli_from_cnot = qk.QuantumCircuit(qrthree)
toffoli_from_cnot.h(qrthree[2])
toffoli_from_cnot.cx(qrthree[1],qrthree[2])
toffoli_from_cnot.tdg(qrthree[2])
toffoli_from_cnot.cx(qrthree[0],qrthree[2])
toffoli_from_cnot.t(qrthree[2])
toffoli_from_cnot.cx(qrthree[1],qrthree[2])
toffoli_from_cnot.tdg(qrthree[2])
toffoli_from_cnot.cx(qrthree[0],qrthree[2])
toffoli_from_cnot.tdg(qrthree[1])
toffoli_from_cnot.t(qrthree[2])
toffoli_from_cnot.h(qrthree[2])
toffoli_from_cnot.cx(qrthree[0],qrthree[1])
toffoli_from_cnot.tdg(qrthree[1])
toffoli_from_cnot.cx(qrthree[0],qrthree[1])
toffoli_from_cnot.s(qrthree[1])
toffoli_from_cnot.t(qrthree[0])
toffoli_from_cnot.draw(output='mpl')
crsingle = qk.ClassicalRegister(1)
deutsch = qk.QuantumCircuit(qr,crsingle)
deutsch.x(qr[1])
deutsch.h(qr[1])
deutsch.draw(output='mpl')
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')
N = 4
qrQFT = qk.QuantumRegister(N,'qftr')
QFT = qk.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')
|
https://github.com/dkp-quantum/Tutorials
|
dkp-quantum
|
import qiskit as qk
import numpy as np
from scipy.linalg import expm
import matplotlib.pyplot as plt
import math
# Single qubit operators
sx = np.array([[0.0, 1.0],[1.0, 0.0]])
sy = np.array([[0.0, -1.0*1j],[1.0*1j, 0.0]])
sz = np.array([[1.0, 0.0],[0.0, -1.0]])
idt = np.array([[1.0, 0.0],[0.0, 1.0]])
import warnings
warnings.filterwarnings("ignore", category=DeprecationWarning)
psi0 = np.array([1.0, 0.0])
thetas = np.linspace(0,4*math.pi,200)
avg_sx_tot = np.zeros(len(thetas))
for i in range(len(thetas)):
psi_theta = expm(-1j*0.5*thetas[i]*(sx+sz)/math.sqrt(2)).dot(psi0)
avg_sx_tot[i] = np.real(psi_theta.conjugate().transpose().dot(sx.dot(psi_theta)))
plt.plot(thetas,avg_sx_tot)
plt.xlabel(r'$\theta$')
plt.ylabel(r'$\langle\sigma_x\rangle_\theta$')
plt.show()
avg_sx_zx = np.zeros(len(thetas))
avg_sx_xz = np.zeros(len(thetas))
for i in range(len(thetas)):
psi_theta_zx = expm(-1j*0.5*thetas[i]*(sz)/math.sqrt(2)).dot(expm(-1j*0.5*thetas[i]*(sx)/math.sqrt(2)).dot(psi0))
psi_theta_xz = expm(-1j*0.5*thetas[i]*(sx)/math.sqrt(2)).dot(expm(-1j*0.5*thetas[i]*(sz)/math.sqrt(2)).dot(psi0))
avg_sx_zx[i] = np.real(psi_theta_zx.conjugate().transpose().dot(sx.dot(psi_theta_zx)))
avg_sx_xz[i] = np.real(psi_theta_xz.conjugate().transpose().dot(sx.dot(psi_theta_xz)))
plt.plot(thetas,avg_sx_tot)
plt.plot(thetas,avg_sx_zx)
plt.plot(thetas,avg_sx_xz)
plt.xlabel(r'$\theta$')
plt.ylabel(r'$\langle\sigma_x\rangle_\theta$')
plt.legend(['Around x = z', 'x first', 'z first'],loc=1)
plt.show()
# Try this with e.g. ntrot = 1, 5, 10, 50.
# You can also try to do sx and sz slices in the reverse order: both choices will become good approximations
# for large n
ntrot = 10
avg_sx_n = np.zeros(len(thetas))
for i in range(len(thetas)):
rot = expm(-1j*0.5*thetas[i]*(sx)/(ntrot*math.sqrt(2))).dot(expm(-1j*0.5*thetas[i]*(sz)/(ntrot*math.sqrt(2))))
for j in range(ntrot-1):
rot = expm(-1j*0.5*thetas[i]*(sx)/(ntrot*math.sqrt(2))).dot(expm(-1j*0.5*thetas[i]*(sz)/(ntrot*math.sqrt(2)))).dot(rot)
psi_theta_n = rot.dot(psi0)
avg_sx_n[i] = np.real(psi_theta_n.conjugate().transpose().dot(sx.dot(psi_theta_n)))
plt.plot(thetas,avg_sx_tot)
plt.plot(thetas,avg_sx_n,'--')
plt.xlabel(r'$\theta$')
plt.ylabel(r'$\langle\sigma_x\rangle_\theta$')
plt.legend(['Exact', 'ntrot = ' + str(ntrot)],loc=1)
plt.show()
delta = 0.1
qr = qk.QuantumRegister(2,name='qr')
zz_example = qk.QuantumCircuit(qr)
zz_example.cx(qr[0],qr[1])
zz_example.u1(2*delta,qr[1])
zz_example.cx(qr[0],qr[1])
zz_example.draw(output='mpl')
J = 1
c_times = np.linspace(0,0.5*math.pi/abs(J),1000)
q_times = np.linspace(0,0.5*math.pi/abs(J),10)
### Classical simulation of the Heisenberg dimer model
psi0 = np.kron( np.array([0,1]), np.array([1,0]) )
H = J * ( np.kron(sx,sx) + np.kron(sy,sy) + np.kron(sz,sz) )
sz1_t = np.zeros(len(c_times))
sz2_t = np.zeros(len(c_times))
sz1 = np.kron(sz,idt)
sz2 = np.kron(idt,sz)
for i in range(len(c_times)):
t = c_times[i]
psi_t = expm(-1j*H*t).dot(psi0)
sz1_t[i] = np.real(psi_t.conjugate().transpose().dot(sz1.dot(psi_t)))
sz2_t[i] = np.real(psi_t.conjugate().transpose().dot(sz2.dot(psi_t)))
### Digital quantum simulation of the Heisenberg dimer model using qiskit
nshots = 1024
sz1q_t = np.zeros(len(q_times))
sz2q_t = np.zeros(len(q_times))
for k in range(len(q_times)):
delta = J*q_times[k]
qr = qk.QuantumRegister(2,name='qr')
cr = qk.ClassicalRegister(2,name='cr')
Heis2 = qk.QuantumCircuit(qr,cr)
# Initial state preparation
Heis2.x(qr[0])
# ZZ
Heis2.cx(qr[0],qr[1])
Heis2.u1(-2*delta,qr[1])
Heis2.cx(qr[0],qr[1])
# YY
Heis2.u3(math.pi/2, -math.pi/2, math.pi/2, qr[0])
Heis2.u3(math.pi/2, -math.pi/2, math.pi/2, qr[1])
Heis2.cx(qr[0],qr[1])
Heis2.u1(-2*delta,qr[1])
Heis2.cx(qr[0],qr[1])
Heis2.u3(-math.pi/2, -math.pi/2, math.pi/2, qr[0])
Heis2.u3(-math.pi/2, -math.pi/2, math.pi/2, qr[1])
# XX
Heis2.u3(-math.pi/2, 0.0, 0.0, qr[0])
Heis2.u3(-math.pi/2, 0.0, 0.0, qr[1])
Heis2.cx(qr[0],qr[1])
Heis2.u1(-2*delta,qr[1])
Heis2.cx(qr[0],qr[1])
Heis2.u3(math.pi/2, 0.0, 0.0, qr[0])
Heis2.u3(math.pi/2, 0.0, 0.0, qr[1])
# measure
Heis2.measure(qr,cr)
# Run the quantum algorithm
backend = qk.Aer.get_backend('qasm_simulator')
job = qk.execute(Heis2, backend, shots=nshots)
result = job.result()
counts = result.get_counts()
# Post processing of outcomes to get sz expectation values
sz1q = 0
sz2q = 0
for key,value in counts.items():
if key == '00':
sz1q += value
sz2q += value
elif key == '01':
sz1q -= value
sz2q += value
elif key == '10':
sz1q += value
sz2q -= value
elif key == '11':
sz1q -= value
sz2q -= value
sz1q_t[k] = sz1q/nshots
sz2q_t[k] = sz2q/nshots
plt.plot(abs(J)*c_times,0.5*sz1_t,'b--')
plt.plot(abs(J)*c_times,0.5*sz2_t,'c')
plt.plot(abs(J)*q_times,0.5*sz1q_t,'rd')
plt.plot(abs(J)*q_times,0.5*sz2q_t,'ko')
plt.legend(['sz1','sz2','sz1q','sz2q'])
plt.xlabel(r'$\delta = |J|t$')
plt.show()
# WARNING: this cell can take a few minutes to run!
ntrotter = 5
J12 = 1
J23 = 1
c_times = np.linspace(0,math.pi/abs(J12),1000)
q_times = np.linspace(0,math.pi/abs(J12),20)
### Classical simulation of the Heisenberg trimer model
psi0 = np.kron( np.kron( np.array([0,1]), np.array([1,0]) ) , np.array([1,0]) )
sxsx12 = np.kron(sx, np.kron(sx,idt))
sysy12 = np.kron(sy, np.kron(sy,idt))
szsz12 = np.kron(sz, np.kron(sz,idt))
sxsx23 = np.kron(idt, np.kron(sx,sx))
sysy23 = np.kron(idt, np.kron(sy,sy))
szsz23 = np.kron(idt, np.kron(sz,sz))
H12 = J12 * ( sxsx12 + sysy12 + szsz12 )
H23 = J23 * ( sxsx23 + sysy23 + szsz23 )
H = H12 + H23
sz1_t = np.zeros(len(c_times))
sz2_t = np.zeros(len(c_times))
sz3_t = np.zeros(len(c_times))
sz1 = np.kron(sz, np.kron(idt,idt))
sz2 = np.kron(idt, np.kron(sz,idt))
sz3 = np.kron(idt, np.kron(idt,sz))
for i in range(len(c_times)):
t = c_times[i]
psi_t = expm(-1j*H*t).dot(psi0)
sz1_t[i] = np.real(psi_t.conjugate().transpose().dot(sz1.dot(psi_t)))
sz2_t[i] = np.real(psi_t.conjugate().transpose().dot(sz2.dot(psi_t)))
sz3_t[i] = np.real(psi_t.conjugate().transpose().dot(sz3.dot(psi_t)))
### Classical simulation of the Heisenberg trimer model WITH SUZUKI TROTTER DIGITALIZATION
sz1st_t = np.zeros(len(c_times))
sz2st_t = np.zeros(len(c_times))
sz3st_t = np.zeros(len(c_times))
for i in range(len(c_times)):
t = c_times[i]
Ust = expm(-1j*H23*t/ntrotter).dot(expm(-1j*H12*t/ntrotter))
for j in range(ntrotter-1):
Ust = expm(-1j*H23*t/ntrotter).dot(expm(-1j*H12*t/ntrotter)).dot(Ust)
psi_t = Ust.dot(psi0)
sz1st_t[i] = np.real(psi_t.conjugate().transpose().dot(sz1.dot(psi_t)))
sz2st_t[i] = np.real(psi_t.conjugate().transpose().dot(sz2.dot(psi_t)))
sz3st_t[i] = np.real(psi_t.conjugate().transpose().dot(sz3.dot(psi_t)))
### Digital quantum simulation of the Heisenberg model using qiskit
nshots = 1024
sz1q_t = np.zeros(len(q_times))
sz2q_t = np.zeros(len(q_times))
sz3q_t = np.zeros(len(q_times))
for k in range(len(q_times)):
delta12n = J12*q_times[k]/ntrotter
delta23n = J23*q_times[k]/ntrotter
qr = qk.QuantumRegister(3,name='qr')
cr = qk.ClassicalRegister(3,name='cr')
Heis3 = qk.QuantumCircuit(qr,cr)
# Initial state preparation
Heis3.x(qr[0])
for n in range(ntrotter):
# 1-2 bond mapped on qubits 0 and 1 in the quantum register
# ZZ
Heis3.cx(qr[0],qr[1])
Heis3.u1(-2*delta12n,qr[1])
Heis3.cx(qr[0],qr[1])
# YY
Heis3.u3(math.pi/2, -math.pi/2, math.pi/2, qr[0])
Heis3.u3(math.pi/2, -math.pi/2, math.pi/2, qr[1])
Heis3.cx(qr[0],qr[1])
Heis3.u1(-2*delta12n,qr[1])
Heis3.cx(qr[0],qr[1])
Heis3.u3(-math.pi/2, -math.pi/2, math.pi/2, qr[0])
Heis3.u3(-math.pi/2, -math.pi/2, math.pi/2, qr[1])
# XX
Heis3.u3(-math.pi/2, 0.0, 0.0, qr[0])
Heis3.u3(-math.pi/2, 0.0, 0.0, qr[1])
Heis3.cx(qr[0],qr[1])
Heis3.u1(-2*delta12n,qr[1])
Heis3.cx(qr[0],qr[1])
Heis3.u3(math.pi/2, 0.0, 0.0, qr[0])
Heis3.u3(math.pi/2, 0.0, 0.0, qr[1])
# 2-3 bond mapped on qubits 1 and 2 in the quantum register
# ZZ
Heis3.cx(qr[1],qr[2])
Heis3.u1(-2*delta12n,qr[2])
Heis3.cx(qr[1],qr[2])
# YY
Heis3.u3(math.pi/2, -math.pi/2, math.pi/2, qr[1])
Heis3.u3(math.pi/2, -math.pi/2, math.pi/2, qr[2])
Heis3.cx(qr[1],qr[2])
Heis3.u1(-2*delta12n,qr[2])
Heis3.cx(qr[1],qr[2])
Heis3.u3(-math.pi/2, -math.pi/2, math.pi/2, qr[1])
Heis3.u3(-math.pi/2, -math.pi/2, math.pi/2, qr[2])
# XX
Heis3.u3(-math.pi/2, 0.0, 0.0, qr[1])
Heis3.u3(-math.pi/2, 0.0, 0.0, qr[2])
Heis3.cx(qr[1],qr[2])
Heis3.u1(-2*delta12n,qr[2])
Heis3.cx(qr[1],qr[2])
Heis3.u3(math.pi/2, 0.0, 0.0, qr[1])
Heis3.u3(math.pi/2, 0.0, 0.0, qr[2])
# measure
Heis3.measure(qr,cr)
# Run the quantum algorithm
backend = qk.Aer.get_backend('qasm_simulator')
job = qk.execute(Heis3, backend, shots=nshots)
result = job.result()
counts = result.get_counts()
# Post processing of outcomes to get sz expectation values
sz1q = 0
sz2q = 0
sz3q = 0
for key,value in counts.items():
if key == '000':
sz1q += value
sz2q += value
sz3q += value
elif key == '001':
sz1q -= value
sz2q += value
sz3q += value
elif key == '010':
sz1q += value
sz2q -= value
sz3q += value
elif key == '011':
sz1q -= value
sz2q -= value
sz3q += value
elif key == '100':
sz1q += value
sz2q += value
sz3q -= value
elif key == '101':
sz1q -= value
sz2q += value
sz3q -= value
elif key == '110':
sz1q += value
sz2q -= value
sz3q -= value
elif key == '111':
sz1q -= value
sz2q -= value
sz3q -= value
sz1q_t[k] = sz1q/nshots
sz2q_t[k] = sz2q/nshots
sz3q_t[k] = sz3q/nshots
fig = plt.figure()
ax = plt.subplot(111)
ax.plot(abs(J12)*c_times,0.5*sz1_t,'b', label='sz1 full')
ax.plot(abs(J12)*c_times,0.5*sz2_t,'r', label='sz2 full')
ax.plot(abs(J12)*c_times,0.5*sz3_t,'g', label='sz3 full')
ax.plot(abs(J12)*c_times,0.5*sz1st_t,'b--',label='sz1 n = ' + str(ntrotter) + ' (classical)')
ax.plot(abs(J12)*c_times,0.5*sz2st_t,'r--', label='sz2 n = ' + str(ntrotter) + ' (classical)')
ax.plot(abs(J12)*c_times,0.5*sz3st_t,'g--', label='sz3 n = ' + str(ntrotter) + ' (classical)')
ax.plot(abs(J12)*q_times,0.5*sz1q_t,'b*',label='sz1 n = ' + str(ntrotter) + ' (quantum)')
ax.plot(abs(J12)*q_times,0.5*sz2q_t,'ro', label='sz2 n = ' + str(ntrotter) + ' (quantum)')
ax.plot(abs(J12)*q_times,0.5*sz3q_t,'gd', label='sz3 n = ' + str(ntrotter) + ' (quantum)')
chartBox = ax.get_position()
ax.set_position([chartBox.x0, chartBox.y0, chartBox.width*1, chartBox.height])
ax.legend(loc='upper center', bbox_to_anchor=(1.3, 0.8), shadow=True, ncol=1)
plt.xlabel(r'$\delta_{12} = |J_{12}|t$')
plt.show()
qr = qk.QuantumRegister(1,name='qr')
cr = qk.ClassicalRegister(1,name='cr')
x_meas = qk.QuantumCircuit(qr,cr)
# Here you can add any quantum circuit generating the quantum state
# that you with to measure at the end e.g.
#
# x_meas.u3(a,b,c,qr[0])
#
# Measurement in x direction
x_meas.h(qr[0])
x_meas.measure(qr,cr)
x_meas.draw(output='mpl')
nshots = 8192
backend = qk.Aer.get_backend('qasm_simulator')
job = qk.execute(x_meas, backend, shots=nshots)
result = job.result()
counts = result.get_counts()
print(counts)
average_sigma_x = 0
for key,value in counts.items():
if key == '0':
average_sigma_x += value
elif key == '1':
average_sigma_x -= value
average_sigma_x = average_sigma_x/nshots
print('Average of sx = ', average_sigma_x)
theta_a = np.linspace(0.0, 2*math.pi, 21) # Some angles for the a vector, with respect to the z axis
theta_b = 0.0 # If the b vector is the z axis -> angle = 0
theta_c = math.pi/2 # If the vector c is the x axis -> angle = pi/2 with respect to z
# Quantum version
nshots = 1024
Pab = np.zeros(len(theta_a))
Pac = np.zeros(len(theta_a))
# Quantum circuit to measure Pbc
qr = qk.QuantumRegister(2, name='qr')
cr = qk.ClassicalRegister(2, name='cr')
qc = qk.QuantumCircuit(qr, cr)
## Initialize Bell state
qc.x(qr[0])
qc.x(qr[1])
qc.h(qr[0])
qc.cx(qr[0],qr[1])
## Pre measurement unitaries to select the basis along a (for the first qubit) and b (for the second qubit)
qc.u3(theta_b,0,0,qr[0])
qc.u3(theta_c,0,0,qr[1])
## Measures
qc.measure(qr[0], cr[0])
qc.measure(qr[1], cr[1])
## Running and saving result
backend = qk.Aer.get_backend('qasm_simulator')
job = qk.execute(qc, backend, shots=nshots)
result = job.result()
counts = result.get_counts()
out = 0
for key,value in counts.items():
if (key == '00') or (key == '11'):
out += value
elif (key == '01') or (key == '10'):
out -= value
Pbc = out/nshots
# Now we compute Pab and Pac for different a vectors
for i in range(len(theta_a)):
ta = theta_a[i]
# Quantum circuit to measure Pab with the given a
qr = qk.QuantumRegister(2, name='qr')
cr = qk.ClassicalRegister(2, name='cr')
qc = qk.QuantumCircuit(qr, cr)
## Initialize Bell state
qc.x(qr[0])
qc.x(qr[1])
qc.h(qr[0])
qc.cx(qr[0],qr[1])
## Pre measurement unitaries to select the basis along a (for the first qubit) and b (for the second qubit)
qc.u3(ta,0,0,qr[0])
qc.u3(theta_b,0,0,qr[1])
## Measures
qc.measure(qr[0], cr[0])
qc.measure(qr[1], cr[1])
## Running and saving result
backend = qk.Aer.get_backend('qasm_simulator')
job = qk.execute(qc, backend, shots=nshots)
result = job.result()
counts = result.get_counts()
out = 0
for key,value in counts.items():
if (key == '00') or (key == '11'):
out += value
elif (key == '01') or (key == '10'):
out -= value
Pab[i] = out/nshots
# Quantum circuit to measure Pac with the given a
qr = qk.QuantumRegister(2, name='qr')
cr = qk.ClassicalRegister(2, name='cr')
qc = qk.QuantumCircuit(qr, cr)
## Initialize Bell state
qc.x(qr[0])
qc.x(qr[1])
qc.h(qr[0])
qc.cx(qr[0],qr[1])
## Pre measurement unitaries to select the basis along a (for the first qubit) and c (for the second qubit)
qc.u3(ta,0,0,qr[0])
qc.u3(theta_c,0,0,qr[1])
## Measures
qc.measure(qr[0], cr[0])
qc.measure(qr[1], cr[1])
## Running and saving result
backend = qk.Aer.get_backend('qasm_simulator')
job = qk.execute(qc, backend, shots=nshots)
result = job.result()
counts = result.get_counts()
out = 0
for key,value in counts.items():
if (key == '00') or (key == '11'):
out += value
elif (key == '01') or (key == '10'):
out -= value
Pac[i] = out/nshots
quantum_outs = Pab-Pac
# Classical calculations
thetas = np.linspace(0,2*math.pi,100)
classical_outs = np.zeros(len(thetas))
b_vec = np.array([math.sin(theta_b),0.0,math.cos(theta_b)])
c_vec = np.array([math.sin(theta_c),0.0,math.cos(theta_c)])
Bell_limit = (1 - b_vec.dot(c_vec))*np.ones(len(thetas))
for k in range(len(thetas)):
a_vec = np.array([math.sin(thetas[k]),0.0,math.cos(thetas[k])])
classical_outs[k] = -a_vec.dot(b_vec) + a_vec.dot(c_vec)
fig = plt.figure()
ax = plt.subplot(111)
ax.plot(thetas,classical_outs,'b', label='classical computation')
ax.plot(theta_a,quantum_outs,'r*', label='quantum algorithm')
ax.plot(thetas,Bell_limit,'--k', label='Bell bound') # If the data go beyond these boundaries,
ax.plot(thetas,-Bell_limit,'--k', label='Bell bound') # the inequality is violated
ax.plot(thetas,(1+Pbc)*np.ones(len(thetas)),'--c', label='Bell bound (quantum)')
ax.plot(thetas,-(1+Pbc)*np.ones(len(thetas)),'--c', label='Bell bound (quantum)')
chartBox = ax.get_position()
ax.set_position([chartBox.x0, chartBox.y0, chartBox.width*1, chartBox.height])
ax.legend(loc='upper center', bbox_to_anchor=(1.3, 0.8), shadow=True, ncol=1)
plt.xlabel(r'$\theta_a$')
plt.show()
from qiskit.tools.monitor import job_monitor
my_token = ''
ibmq_provider = qk.IBMQ.enable_account(my_token)
delta = 0.5*math.pi
qr = qk.QuantumRegister(2,name='qr')
cr = qk.ClassicalRegister(2,name='cr')
Heis2 = qk.QuantumCircuit(qr,cr)
# Initial state preparation
Heis2.x(qr[0])
# ZZ
Heis2.cx(qr[0],qr[1])
Heis2.u1(-2*delta,qr[1])
Heis2.cx(qr[0],qr[1])
# YY
Heis2.u3(math.pi/2, -math.pi/2, math.pi/2, qr[0])
Heis2.u3(math.pi/2, -math.pi/2, math.pi/2, qr[1])
Heis2.cx(qr[0],qr[1])
Heis2.u1(-2*delta,qr[1])
Heis2.cx(qr[0],qr[1])
Heis2.u3(-math.pi/2, -math.pi/2, math.pi/2, qr[0])
Heis2.u3(-math.pi/2, -math.pi/2, math.pi/2, qr[1])
# XX
Heis2.u3(-math.pi/2, 0.0, 0.0, qr[0])
Heis2.u3(-math.pi/2, 0.0, 0.0, qr[1])
Heis2.cx(qr[0],qr[1])
Heis2.u1(-2*delta,qr[1])
Heis2.cx(qr[0],qr[1])
Heis2.u3(math.pi/2, 0.0, 0.0, qr[0])
Heis2.u3(math.pi/2, 0.0, 0.0, qr[1])
# measure
Heis2.measure(qr,cr)
my_backend = ibmq_provider.get_backend('ibmqx2')
job = qk.execute(Heis2, backend=my_backend, shots=1024)
job_monitor(job, interval=5)
result = job.result()
counts = result.get_counts()
print(counts)
plot_histogram(counts)
my_backend.configuration().coupling_map # In the output, the first entry in a pair [a,b] is a control, second is the
# corresponding target for a CNOT
|
https://github.com/dkp-quantum/Tutorials
|
dkp-quantum
|
# Install packages
#!pip install numpy
#!pip install matplotlib
#!pip install qiskit
#!pip install qiskit[visualization]
#!pip install qiskit[optimization]
#!pip install qiskit_machine_learning
# Load packages
## General tools
import numpy as np
import matplotlib.pyplot as plt
from math import pi
## Qiskit Circuit Functions
from qiskit import *
from qiskit.quantum_info import *
from qiskit.visualization import *
# install the latest released version of PennyLane
!pip install pennylane
from pennylane import numpy as np
import matplotlib.pyplot as plt
from math import pi
import pennylane as qml
# Setup the device using qml.device()
## Assigning the device and defining the measurement of the circuit
dev = qml.device(name = 'default.qubit', wires = 2)
@qml.qnode(dev)
def circuit():
return qml.expval(qml.PauliZ(0) @ qml.PauliZ(1))
drawer = qml.draw(circuit, show_all_wires=True)
print(drawer())
# Setup the device using qml.device()
## Assigning names to each wires
dev = qml.device(name = 'default.qubit', wires = ['a', 'b'])
@qml.qnode(dev)
def circuit(x):
return qml.expval(qml.PauliZ('a') @ qml.PauliZ('b'))
drawer = qml.draw(circuit, show_all_wires=True)
print(drawer(0.5))
# Setup the device using qml.device()
## Assigning the number of shots
shots_list = [5, 10, 1000] # number of shots for each batches
dev = qml.device("default.qubit", wires=2, shots=shots_list)
@qml.qnode(dev)
def circuit(x):
qml.RX(x, wires=0)
qml.CNOT(wires=[0, 1])
return qml.expval(qml.PauliZ(0) @ qml.PauliX(1)), qml.expval(qml.PauliZ(0))
drawer = qml.draw(circuit, show_all_wires=True)
print(drawer(x = 0.5))
## The result of the execution of the circuit.
circuit(0.5)
dev = qml.device('default.qubit', wires=['aux', 'q1', 'q2'])
# Quntum function
def my_quantum_function(x, y):
qml.RZ(x, wires='q1')
qml.CNOT(wires=['aux' ,'q1'])
qml.RY(y, wires='q2')
return qml.expval(qml.PauliZ('q2'))
circuit = qml.QNode(my_quantum_function, dev)
circuit(x = np.pi/4, y = 0.7)
# Plot the circuit
print(qml.draw(circuit)(np.pi/4, 0.7))
# Plot the circuit with matplotlib.pyplot library
import matplotlib.pyplot as plt
fig, ax = qml.draw_mpl(circuit)(x = np.pi/4, y = 0.7)
plt.show()
# Measurement 1) Sampling result from each shots
dev = qml.device("default.qubit", wires=2, shots=1000)
@qml.qnode(dev)
def circuit():
qml.Hadamard(wires=0)
qml.CNOT(wires=[0, 1])
return qml.sample(qml.PauliZ(0)), qml.sample(qml.PauliZ(1))
fig, ax = qml.draw_mpl(circuit)()
plt.show()
result_sample = circuit()
# Print out the dimension of the result
print(result_sample.shape)
# Let's look at the result
result_sample
# Measurement 2) Sampling result from each shots
dev = qml.device("default.qubit", wires=2, shots=1000)
@qml.qnode(dev)
def circuit():
qml.Hadamard(wires=0)
qml.CNOT(wires=[0, 1])
return qml.probs(wires=[0, 1])
fig, ax = qml.draw_mpl(circuit)()
plt.show()
result_prob = circuit()
# Print out the dimension of the result
print(result_prob.shape)
# Let's look at the result
result_prob
# Measurement 3) Sampling result from each shots
dev = qml.device("default.qubit", wires=3, shots=1000)
@qml.qnode(dev)
def my_quantum_function(x, y):
qml.RZ(x, wires=0)
qml.CNOT(wires=[0, 1])
qml.RY(y, wires=1)
qml.CNOT(wires=[0, 2])
return qml.expval(qml.PauliZ(0) @ qml.Identity(1) @qml.PauliX(2))
fig, ax = qml.draw_mpl(my_quantum_function)(x = pi/2, y = pi/3)
plt.show()
result_tensor = my_quantum_function(x = pi/2, y = pi/3)
# Let's look at the result
result_tensor
import pennylane as qml
from pennylane import numpy as np
from pennylane.optimize import NesterovMomentumOptimizer
dev = qml.device("default.qubit", wires=4)
def layer(W):
qml.Rot(W[0, 0], W[0, 1], W[0, 2], wires=0)
qml.Rot(W[1, 0], W[1, 1], W[1, 2], wires=1)
qml.Rot(W[2, 0], W[2, 1], W[2, 2], wires=2)
qml.Rot(W[3, 0], W[3, 1], W[3, 2], wires=3)
qml.CNOT(wires=[0, 1])
qml.CNOT(wires=[1, 2])
qml.CNOT(wires=[2, 3])
qml.CNOT(wires=[3, 0])
def statepreparation(x):
qml.BasisState(x, wires=[0, 1, 2, 3])
@qml.qnode(dev)
def circuit(weights, x):
statepreparation(x)
for W in weights:
layer(W)
return qml.expval(qml.PauliZ(0))
def variational_classifier(weights, bias, x):
return circuit(weights, x) + bias
def square_loss(labels, predictions):
loss = 0
for l, p in zip(labels, predictions):
loss = loss + (l - p) ** 2
loss = loss / len(labels)
return loss
def accuracy(labels, predictions):
loss = 0
for l, p in zip(labels, predictions):
if abs(l - p) < 1e-5:
loss = loss + 1
loss = loss / len(labels)
return loss
def cost(weights, bias, X, Y):
predictions = [variational_classifier(weights, bias, x) for x in X]
return square_loss(Y, predictions)
from pennylane import numpy as np
data = np.array([[0., 0., 0., 0., 0],
[0., 0., 0., 1., 1],
[0., 0., 1., 0., 1],
[0., 0., 1., 1., 0],
[0., 1., 0., 0., 1],
[0., 1., 0., 1., 0],
[0., 1., 1., 0., 0],
[0., 1., 1., 1., 1],
[1., 0., 0., 0., 1],
[1., 0., 0., 1., 0],
[1., 0., 1., 0., 0],
[1., 0., 1., 1., 1],
[1., 1., 0., 0., 0],
[1., 1., 0., 1., 1],
[1., 1., 1., 0., 1],
[1., 1., 1., 1., 0]])
X = np.array(data[:, :-1], requires_grad=False)
Y = np.array(data[:, -1], requires_grad=False)
Y = Y * 2 - np.ones(len(Y)) # shift label from {0, 1} to {-1, 1}
for i in range(5):
print("X = {}, Y = {: d}".format(X[i], int(Y[i])))
print("...")
np.random.seed(0)
num_qubits = 4
num_layers = 2
weights_init = 0.01 * np.random.randn(num_layers, num_qubits, 3, requires_grad=True)
bias_init = np.array(0.0, requires_grad=True)
print(weights_init, bias_init)
opt = NesterovMomentumOptimizer(0.5)
batch_size = 5
weights = weights_init
bias = bias_init
iter_num = 10
for it in range(iter_num):
# Update the weights by one optimizer step
batch_index = np.random.randint(0, len(X), (batch_size,))
X_batch = X[batch_index]
Y_batch = Y[batch_index]
weights, bias, _, _ = opt.step(cost, weights, bias, X_batch, Y_batch)
# Compute accuracy
predictions = [np.sign(variational_classifier(weights, bias, x)) for x in X]
acc = accuracy(Y, predictions)
print(
"Iter: {:5d} | Cost: {:0.7f} | Accuracy: {:0.7f} ".format(
it + 1, cost(weights, bias, X, Y), acc
)
)
dev = qml.device("default.qubit", wires=2)
def get_angles(x):
beta0 = 2 * np.arcsin(np.sqrt(x[1] ** 2) / np.sqrt(x[0] ** 2 + x[1] ** 2 + 1e-12))
beta1 = 2 * np.arcsin(np.sqrt(x[3] ** 2) / np.sqrt(x[2] ** 2 + x[3] ** 2 + 1e-12))
beta2 = 2 * np.arcsin(
np.sqrt(x[2] ** 2 + x[3] ** 2)
/ np.sqrt(x[0] ** 2 + x[1] ** 2 + x[2] ** 2 + x[3] ** 2)
)
return np.array([beta2, -beta1 / 2, beta1 / 2, -beta0 / 2, beta0 / 2])
def statepreparation(a):
qml.RY(a[0], wires=0)
qml.CNOT(wires=[0, 1])
qml.RY(a[1], wires=1)
qml.CNOT(wires=[0, 1])
qml.RY(a[2], wires=1)
qml.PauliX(wires=0)
qml.CNOT(wires=[0, 1])
qml.RY(a[3], wires=1)
qml.CNOT(wires=[0, 1])
qml.RY(a[4], wires=1)
qml.PauliX(wires=0)
x = np.array([0.53896774, 0.79503606, 0.27826503, 0.0], requires_grad=False)
ang = get_angles(x)
@qml.qnode(dev)
def test(angles):
statepreparation(angles)
return qml.expval(qml.PauliZ(0))
test(ang)
print("x : ", x)
print("angles : ", ang)
print("amplitude vector: ", np.real(dev.state))
def layer(W):
qml.Rot(W[0, 0], W[0, 1], W[0, 2], wires=0)
qml.Rot(W[1, 0], W[1, 1], W[1, 2], wires=1)
qml.CNOT(wires=[0, 1])
@qml.qnode(dev)
def circuit(weights, angles):
statepreparation(angles)
for W in weights:
layer(W)
return qml.expval(qml.PauliZ(0))
def variational_classifier(weights, bias, angles):
return circuit(weights, angles) + bias
def cost(weights, bias, features, labels):
predictions = [variational_classifier(weights, bias, f) for f in features]
return square_loss(labels, predictions)
# !pip install pandas
# !pip install sklearn
from sklearn.datasets import load_iris
import pandas as pd
import numpy as np
# visualization package
import matplotlib.pyplot as plt
import seaborn as sns
iris = load_iris() # sample data load
#print(iris) # pring out data with variable types and its description
print(iris.DESCR) # Description of the dataset
# feature_names(x variables) 와 target(y variable)을 잘 나타내도록 data frame 생성
df = pd.DataFrame(data=iris.data, columns=iris.feature_names)
df['target'] = iris.target
# 숫자형으로 기록된 target(y variable) - (0.0, 1.0, 2.0)을 문자값으로 변환
df['target'] = df['target'].map({0:"setosa", 1:"versicolor", 2:"virginica"})
print(df)
sns.pairplot(df, hue="target", height=3)
plt.show()
from pennylane import numpy as np
data = np.loadtxt("iris_classes1and2_scaled.txt")
X = data[:, 0:2]
print("First X sample (original) :", X[0])
# pad the vectors to size 2^2 with constant values
padding = 0.3 * np.ones((len(X), 1))
X_pad = np.c_[np.c_[X, padding], np.zeros((len(X), 1))]
print("First X sample (padded) :", X_pad[0])
# normalize each input
normalization = np.sqrt(np.sum(X_pad ** 2, -1))
X_norm = (X_pad.T / normalization).T
print("First X sample (normalized):", X_norm[0])
# angles for state preparation are new features
features = np.array([get_angles(x) for x in X_norm], requires_grad=False)
print("First features sample :", features[0])
Y = data[:, -1]
import matplotlib.pyplot as plt
plt.figure()
plt.scatter(X[:, 0][Y == 1], X[:, 1][Y == 1], c="b", marker="o", edgecolors="k")
plt.scatter(X[:, 0][Y == -1], X[:, 1][Y == -1], c="r", marker="o", edgecolors="k")
plt.title("Original data")
plt.show()
plt.figure()
dim1 = 0
dim2 = 1
plt.scatter(
X_norm[:, dim1][Y == 1], X_norm[:, dim2][Y == 1], c="b", marker="o", edgecolors="k"
)
plt.scatter(
X_norm[:, dim1][Y == -1], X_norm[:, dim2][Y == -1], c="r", marker="o", edgecolors="k"
)
plt.title("Padded and normalised data (dims {} and {})".format(dim1, dim2))
plt.show()
plt.figure()
dim1 = 0
dim2 = 3
plt.scatter(
features[:, dim1][Y == 1], features[:, dim2][Y == 1], c="b", marker="o", edgecolors="k"
)
plt.scatter(
features[:, dim1][Y == -1], features[:, dim2][Y == -1], c="r", marker="o", edgecolors="k"
)
plt.title("Feature vectors (dims {} and {})".format(dim1, dim2))
plt.show()
np.random.seed(0)
num_data = len(Y)
num_train = int(0.75 * num_data)
index = np.random.permutation(range(num_data))
feats_train = features[index[:num_train]]
Y_train = Y[index[:num_train]]
feats_val = features[index[num_train:]]
Y_val = Y[index[num_train:]]
# We need these later for plotting
X_train = X[index[:num_train]]
X_val = X[index[num_train:]]
num_qubits = 2
num_layers = 6
weights_init = 0.01 * np.random.randn(num_layers, num_qubits, 3, requires_grad=True)
bias_init = np.array(0.0, requires_grad=True)
opt = NesterovMomentumOptimizer(0.01)
batch_size = 50
# train the variational classifier
weights = weights_init
bias = bias_init
Iter_num = 25
for it in range(Iter_num):
# Update the weights by one optimizer step
batch_index = np.random.randint(0, num_train, (batch_size,))
feats_train_batch = feats_train[batch_index]
Y_train_batch = Y_train[batch_index]
weights, bias, _, _ = opt.step(cost, weights, bias, feats_train_batch, Y_train_batch)
# Compute predictions on train and validation set
predictions_train = [np.sign(variational_classifier(weights, bias, f)) for f in feats_train]
predictions_val = [np.sign(variational_classifier(weights, bias, f)) for f in feats_val]
# Compute accuracy on train and validation set
acc_train = accuracy(Y_train, predictions_train)
acc_val = accuracy(Y_val, predictions_val)
print(
"Iter: {:5d} | Cost: {:0.7f} | Acc train: {:0.7f} | Acc validation: {:0.7f} "
"".format(it + 1, cost(weights, bias, features, Y), acc_train, acc_val)
)
plt.figure(figsize=(12,9))
cm = plt.cm.RdBu
# make data for decision regions
xx, yy = np.meshgrid(np.linspace(0.0, 1.5, 20), np.linspace(0.0, 1.5, 20))
X_grid = [np.array([x, y]) for x, y in zip(xx.flatten(), yy.flatten())]
# preprocess grid points like data inputs above
padding = 0.3 * np.ones((len(X_grid), 1))
X_grid = np.c_[np.c_[X_grid, padding], np.zeros((len(X_grid), 1))] # pad each input
normalization = np.sqrt(np.sum(X_grid ** 2, -1))
X_grid = (X_grid.T / normalization).T # normalize each input
features_grid = np.array(
[get_angles(x) for x in X_grid]
) # angles for state preparation are new features
predictions_grid = [variational_classifier(weights, bias, f) for f in features_grid]
Z = np.reshape(predictions_grid, xx.shape)
# plot decision regions
cnt = plt.contourf(
xx, yy, Z, levels=np.arange(-1, 1.1, 0.1), cmap=cm, alpha=0.8, extend="both"
)
plt.contour(
xx, yy, Z, levels=[0.0], colors=("black",), linestyles=("--",), linewidths=(0.8,)
)
plt.colorbar(cnt, ticks=[-1, 0, 1])
# plot data
plt.scatter(
X_train[:, 0][Y_train == 1],
X_train[:, 1][Y_train == 1],
c="b",
marker="o",
edgecolors="k",
label="class 1 train",
)
plt.scatter(
X_val[:, 0][Y_val == 1],
X_val[:, 1][Y_val == 1],
c="b",
marker="^",
edgecolors="k",
label="class 1 validation",
)
plt.scatter(
X_train[:, 0][Y_train == -1],
X_train[:, 1][Y_train == -1],
c="r",
marker="o",
edgecolors="k",
label="class -1 train",
)
plt.scatter(
X_val[:, 0][Y_val == -1],
X_val[:, 1][Y_val == -1],
c="r",
marker="^",
edgecolors="k",
label="class -1 validation",
)
plt.legend()
plt.show()
# Install packages
# !pip install tensorflow
# Loading packages
import pennylane as qml
from pennylane import numpy as np
from pennylane.templates import RandomLayers
import tensorflow as tf
from tensorflow import keras
import matplotlib.pyplot as plt
n_epochs = 30 # Number of optimization epochs
n_layers = 1 # Number of random layers
n_train = 50 # Size of the train dataset
n_test = 30 # Size of the test dataset
# SAVE_PATH = "quanvolution/" # Data saving folder. Here we don't need to make saving path.
PREPROCESS = True # If False, skip quantum processing and load data from SAVE_PATH
np.random.seed(0) # Seed for NumPy random number generator
tf.random.set_seed(0) # Seed for TensorFlow random number generator
# Assigning MNIST data into train / test data
mnist_dataset = keras.datasets.mnist
(train_images, train_labels), (test_images, test_labels) = mnist_dataset.load_data()
# Reduce dataset size
## Previouslys, we set the number of train / test data in setting the hyper-parameters.
train_images = train_images[:n_train]
train_labels = train_labels[:n_train]
test_images = test_images[:n_test]
test_labels = test_labels[:n_test]
# Normalize pixel values within 0 and 1.
## We are modifying the data values between 0 and 1.
train_images = train_images / 255
test_images = test_images / 255
# Add extra dimension for convolution channels
train_images = np.array(train_images[..., tf.newaxis], requires_grad=False)
test_images = np.array(test_images[..., tf.newaxis], requires_grad=False)
# Setup the device using qml.device()
dev = qml.device("default.qubit", wires=4)
# Random circuit parameters using in rotation-Y gate
rand_params = np.random.uniform(high=2 * np.pi, size=(n_layers, 4))
@qml.qnode(dev)
def circuit(phi):
# Encoding of 4 classical input values
for j in range(4):
qml.RY(np.pi * phi[j], wires=j)
# Random quantum circuit
RandomLayers(rand_params, wires=list(range(4)))
# Measurement producing 4 classical output values
return [qml.expval(qml.PauliZ(j)) for j in range(4)]
## Assigning phi_value to plot the circuit
phi_value = [0,0,0,0]
## Plotting the quantum circuit
fig, ax = qml.draw_mpl(circuit)(phi_value)
plt.show()
def quanv(image):
"""Convolves the input image with many applications of the same quantum circuit."""
out = np.zeros((14, 14, 4))
# Loop over the coordinates of the top-left pixel of 2X2 squares
for j in range(0, 28, 2):
for k in range(0, 28, 2):
# Process a squared 2x2 region of the image with a quantum circuit
q_results = circuit(
[
image[j, k, 0],
image[j, k + 1, 0],
image[j + 1, k, 0],
image[j + 1, k + 1, 0]
]
)
# Assign expectation values to different channels of the output pixel (j/2, k/2)
for c in range(4):
out[j // 2, k // 2, c] = q_results[c]
return out
if PREPROCESS == True:
q_train_images = []
print("Quantum pre-processing of train images:")
for idx, img in enumerate(train_images):
print("{}/{} ".format(idx + 1, n_train), end="\r")
q_train_images.append(quanv(img))
q_train_images = np.asarray(q_train_images)
q_test_images = []
print("\nQuantum pre-processing of test images:")
for idx, img in enumerate(test_images):
print("{}/{} ".format(idx + 1, n_test), end="\r")
q_test_images.append(quanv(img))
q_test_images = np.asarray(q_test_images)
# # Save pre-processed images
# np.save(SAVE_PATH + "q_train_images.npy", q_train_images)
# np.save(SAVE_PATH + "q_test_images.npy", q_test_images)
# # Load pre-processed images
# q_train_images = np.load(SAVE_PATH + "q_train_images.npy")
# q_test_images = np.load(SAVE_PATH + "q_test_images.npy")
n_samples = 4
n_channels = 4
fig, axes = plt.subplots(1 + n_channels, n_samples, figsize=(10, 10))
for k in range(n_samples):
axes[0, 0].set_ylabel("Input")
if k != 0:
axes[0, k].yaxis.set_visible(False)
axes[0, k].imshow(train_images[k, :, :, 0], cmap="gray")
# Plot all output channels
for c in range(n_channels):
axes[c + 1, 0].set_ylabel("Output [ch. {}]".format(c))
if k != 0:
axes[c, k].yaxis.set_visible(False)
axes[c + 1, k].imshow(q_train_images[k, :, :, c], cmap="gray")
plt.tight_layout()
plt.show()
def MyModel():
"""Initializes and returns a custom Keras model
which is ready to be trained."""
model = keras.models.Sequential([
keras.layers.Flatten(),
keras.layers.Dense(10, activation="softmax")
])
model.compile(
optimizer='adam',
loss="sparse_categorical_crossentropy",
metrics=["accuracy"],
)
return model
q_model = MyModel()
q_history = q_model.fit(
q_train_images,
train_labels,
validation_data=(q_test_images, test_labels),
batch_size=4,
epochs=n_epochs,
verbose=2,
)
c_model = MyModel()
c_history = c_model.fit(
train_images,
train_labels,
validation_data=(test_images, test_labels),
batch_size=4,
epochs=n_epochs,
verbose=2,
)
import matplotlib.pyplot as plt
plt.style.use("seaborn")
fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(6, 9))
ax1.plot(q_history.history["val_accuracy"], "-ob", label="With quantum layer")
ax1.plot(c_history.history["val_accuracy"], "-og", label="Without quantum layer")
ax1.set_ylabel("Accuracy")
ax1.set_ylim([0, 1])
ax1.set_xlabel("Epoch")
ax1.legend()
ax2.plot(q_history.history["val_loss"], "-ob", label="With quantum layer")
ax2.plot(c_history.history["val_loss"], "-og", label="Without quantum layer")
ax2.set_ylabel("Loss")
ax2.set_ylim(top=2.5)
ax2.set_xlabel("Epoch")
ax2.legend()
plt.tight_layout()
plt.show()
|
https://github.com/anpaschool/QC-School-Fall2020
|
anpaschool
|
import numpy as np
from qiskit import(
QuantumCircuit,
execute,
Aer)
from qiskit.visualization import plot_histogram
circuit = QuantumCircuit(2, 2) # Two Qubit and 2 Classical bit (q,c)
circuit.h(0)
circuit.cx(0, 1) #Controlled-NOT Gate
circuit.measure([0,1], [0,1]) #([q,q],[c,c])
circuit.draw()
simulator = Aer.get_backend('qasm_simulator')
job = execute(circuit, simulator, shots=100)
result = job.result()
counts = result.get_counts(circuit)
print("\nTotal count for 00 and 11 are:",counts)
plot_histogram(counts)
|
https://github.com/anpaschool/QC-School-Fall2020
|
anpaschool
|
#An attempt by N Malakar
#Aug 27, 2020
# Thanks QC class, Especially Shree and Sovit
#References: https://github.com/anpaschool/QC-School-Fall2020/blob/master/Tuesday-Formal/Lecture2-QC-Fall2020.ipynb
#https://qiskit.org/textbook/ch-states/representing-qubit-states.html
from qiskit import QuantumCircuit, execute,QuantumCircuit, ClassicalRegister, QuantumRegister, Aer
from qiskit.visualization import plot_histogram, plot_bloch_vector, plot_bloch_multivector,plot_state_qsphere
from math import sqrt, pi
import numpy as np
%matplotlib inline
qc = QuantumCircuit(1) # Create a quantum circuit with one qubit
initial_state = [0,1] # Define initial_state as |1>
qc.initialize(initial_state, 0) # Apply initialisation operation to the 0th qubit
qc.draw('text') # Let's view our circuit (text drawing is required for the 'Initialize' gate due to a known bug in qiskit)
backend = Aer.get_backend('statevector_simulator') # Tell Qiskit how to simulate our circuit
job = execute(qc,backend).result() # Do the simulation, returning the state vector
print(job.get_statevector())
out_state = job.get_statevector()
qc.measure_all()
qc.draw('text')
result = execute(qc,backend).result()
counts = result.get_counts()
plot_histogram(counts)
#print(out_state) # Display the output state vector
#plot_bloch_multivector(job.get_statevector()) # Display the output state vector
initial_state = [1/sqrt(2), 1j/sqrt(2)] # Define state |q>
qc = QuantumCircuit(1) # Must redefine qc
qc.initialize(initial_state, 0) # Initialise the 0th qubit in the state `initial_state`
qc.draw('text')
state = execute(qc,backend).result().get_statevector() # Execute the circuit
print(state) # Print the result
#-------------
results = execute(qc,backend).result().get_counts()
plot_histogram(results)
state = execute(qc, backend).result().get_statevector()
print("Qubit State = " + str(state))
qc.measure_all()
qc.draw('text')
# Installed https://github.com/qiskit-community/qiskit-textbookpip
# install ./qiskit-textbook-src
from qiskit_textbook.widgets import plot_bloch_vector_spherical
coords = [0,pi/2,1] # [Theta, Phi, Radius]
plot_bloch_vector_spherical(coords) # Bloch Vector with spherical coordinates
#Use plot_bloch_vector() or plot_bloch_sphere_spherical() to plot a qubit in the states: |0>
coords = [0,0,1] # [Theta, Phi, Radius]
plot_bloch_vector_spherical(coords) # Bloch Vector with spherical coordinates
#or, use plot_bloch_vector
from qiskit.visualization import plot_bloch_vector
%matplotlib inline
plot_bloch_vector([0,0,1], title="This is $|0>$")
coords = [ pi ,0,1] # [Theta, Phi, Radius]
plot_bloch_vector_spherical(coords) # Bloch Vector with spherical coordinates
#alternatively,
plot_bloch_vector([0,0,-1], title="This is $|1>$")
# the theta is pi/2, phi is 0, r is 1
coords = [ pi/2 ,0,1] # [Theta, Phi, Radius]
plot_bloch_vector_spherical(coords) # Bloch Vector with spherical coordinates
#plot_bloch_vector([1 ,0 ,0] , title="This is $|1>$") ???
# the multivector plot is having issues in this version...see https://github.com/Qiskit/qiskit-terra/issues/4982
# https://qiskit.org/documentation/stubs/qiskit.visualization.plot_bloch_multivector.html#qiskit.visualization.plot_bloch_multivector
|
https://github.com/anpaschool/QC-School-Fall2020
|
anpaschool
|
import numpy as np
zero_ket = np.array([[1], [0]])
print("|0> ket:\n", zero_ket)
print("<0| bra:\n", zero_ket.T.conj())
zero_ket.T.conj() @ zero_ket
one_ket = np.array([[0], [1]])
zero_ket.T.conj() @ one_ket
zero_ket @ zero_ket.T.conj()
ψ = np.array([[1], [0]])/np.sqrt(2)
Π_0 = zero_ket @ zero_ket.T.conj()
ψ.T.conj() @ Π_0 @ ψ
from qiskit import QuantumCircuit, execute,QuantumCircuit, ClassicalRegister, QuantumRegister, Aer
from math import pi
import numpy as np
from qiskit.visualization import plot_bloch_multivector, plot_histogram
%matplotlib inline
q = QuantumRegister(1)
c = ClassicalRegister(1)
circuit = QuantumCircuit(q, c)
# Apply H-gate to each qubit:
circuit.h(q[0])
circuit.measure(q, c)
circuit.draw('mpl')
# Let's see the result:
backend = Aer.get_backend('qasm_simulator')
results = execute(circuit,backend, shots=1000).result()
counts = results.get_counts(circuit)
print(counts)
plot_histogram(counts)
ψ = np.array([[np.sqrt(2)/2], [np.sqrt(2)/2]])
Π_0 = zero_ket @ zero_ket.T.conj()
probability_0 = ψ.T.conj() @ Π_0 @ ψ
Π_0 @ ψ/np.sqrt(probability_0)
backend = Aer.get_backend('qasm_simulator')
q1 = QuantumRegister(1)
c1 = ClassicalRegister(2)
circuit1 = QuantumCircuit(q1, c1)
circuit1.h(q1[0])
circuit1.measure(q1[0], c1[0])
circuit1.measure(q1[0], c1[1])
circuit1.draw('mpl')
results = execute(circuit1,backend, shots=1000).result()
counts1 = results.get_counts(circuit1)
print(counts1)
plot_histogram(counts1)
q = QuantumRegister(2)
c = ClassicalRegister(2)
circuit = QuantumCircuit(q, c)
circuit.h(q[0])
circuit.measure(q, c)
job = execute(circuit, backend, shots=1000)
plot_histogram(job.result().get_counts(circuit))
q = QuantumRegister(2)
c = ClassicalRegister(2)
circuit = QuantumCircuit(q, c)
circuit.h(q[0])
circuit.cx(q[0], q[1])
circuit.measure(q, c)
circuit.draw('mpl')
job = execute(circuit, backend, shots=1000)
plot_histogram(job.result().get_counts(circuit))
ψ = np.array([[1], [1]])/np.sqrt(2)
ρ = ψ @ ψ.T.conj()
Π_0 = zero_ket @ zero_ket.T.conj()
np.trace(Π_0 @ ρ)
probability_0 = np.trace(Π_0 @ ρ)
Π_0 @ ρ @ Π_0/probability_0
zero_ket = np.array([[1], [0]])
one_ket = np.array([[0], [1]])
ψ = (zero_ket + one_ket)/np.sqrt(2)
print("Density matrix of the equal superposition")
print(ψ @ ψ.T.conj())
print("Density matrix of the equally mixed state of |0><0| and |1><1|")
print((zero_ket @ zero_ket.T.conj()+one_ket @ one_ket.T.conj())/2)
|
https://github.com/anpaschool/QC-School-Fall2020
|
anpaschool
|
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute, Aer
from qiskit.tools.visualization import plot_histogram, plot_bloch_multivector
#import numpy as np
q = QuantumRegister(2)
c = ClassicalRegister(2)
# Define Quantum circuit with 2 quantum register and 2 classical register
bell = QuantumCircuit(q,c)
# Create a Bell state
bell.x(q[0])
bell.x(q[1])
bell.h(q[0])
bell.cx(q[0], q[1])
# Draw circuit
bell.draw(output = 'mpl')
backend_statevector = Aer.get_backend('statevector_simulator')
job = execute(bell, backend_statevector)
result = job.result()
outputstate = result.get_statevector(bell, decimals = 3)
print(outputstate)
#plot_bloch_multivector(job.result().get_statevector(bell))
bell.measure(q, c)
bell.draw('mpl')
backend = Aer.get_backend('qasm_simulator')
job = execute(bell, backend)
result = job.result()
result.get_counts(bell)
plot_histogram(job.result().get_counts(bell))
import numpy as np
zero_ket = np.array([[1], [0]])
one_ket = np.array([[0], [1]])
ψ = (zero_ket + one_ket)/np.sqrt(2)
print("Density matrix of the equal superposition")
print(ψ @ ψ.T.conj())
print("Density matrix of the equally mixed state of |0><0| and |1><1|")
print((zero_ket @ zero_ket.T.conj()+one_ket @ one_ket.T.conj())/2)
def mixed_state(pure_state, visibility):
#density_matrix = pure_state @ pure_state.T.conj()
density_matrix = np.dot( pure_state, np.matrix.getH(pure_state) )
maximally_mixed_state = np.eye(4)/2**2
return visibility*density_matrix + (1-visibility)*maximally_mixed_state
ϕ = np.array([[1],[0],[0],[1]])/np.sqrt(2)
#print (array_to_latex(ϕ, pretext="$\phi$ = "))
print(f"Maximum visibility is a pure state: \n{mixed_state(ϕ, 1.0)}\n")
print(f"The state is still entangled with visibility 0.8:\n {mixed_state(ϕ, 0.8)}\n")
print(f"Entanglement is lost by 0.6:\n{mixed_state(ϕ, 0.6)}\n")
print(f"Barely any coherence remains by 0.2:\n{mixed_state(ϕ, 0.2)}\n")
import matplotlib.pyplot as plt
temperatures = [.5, 5, 2000]
energies = np.linspace(0, 20, 100)
fig, ax = plt.subplots()
for i, T in enumerate(temperatures):
probabilities = np.exp(-energies/T)
Z = probabilities.sum()
probabilities /= Z
ax.plot(energies, probabilities, linewidth=3, label = "$T_" + str(i+1)+"$="+str(T))
ax.set_xlim(0, 20)
ax.set_ylim(0, 1.2*probabilities.max())
ax.set_xticks([])
ax.set_yticks([])
ax.set_xlabel('Energy')
ax.set_ylabel('Probability')
ax.legend()
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer
cq = QuantumRegister(2,'code\_qubit\_')
lq = QuantumRegister(1,'ancilla\_qubit\_')
sb = ClassicalRegister(1,'syndrome\_bit')
qc = QuantumCircuit(cq,lq,sb)
qc.cx(cq[0],lq[0])
qc.cx(cq[1],lq[0])
qc.measure(lq,sb)
qc.draw('mpl')
qc_init = QuantumCircuit(cq)
(qc_init+qc).draw('mpl')
counts = execute( qc_init+qc, Aer.get_backend('qasm_simulator')).result().get_counts()
print('Results:',counts)
qc_init = QuantumCircuit(cq)
qc_init.x(cq)
(qc_init+qc).draw('mpl')
counts = execute(qc_init+qc, Aer.get_backend('qasm_simulator')).result().get_counts()
print('Results:',counts)
qc_init = QuantumCircuit(cq)
qc_init.h(cq[0])
qc_init.cx(cq[0],cq[1])
(qc_init+qc).draw('mpl')
counts = execute(qc_init+qc, Aer.get_backend('qasm_simulator')).result().get_counts()
print('Results:',counts)
qc_init = QuantumCircuit(cq)
qc_init.h(cq[0])
qc_init.cx(cq[0],cq[1])
qc_init.x(cq[0])
(qc_init+qc).draw('mpl')
counts = execute(qc_init+qc, Aer.get_backend('qasm_simulator')).result().get_counts()
print('Results:',counts)
|
https://github.com/anpaschool/QC-School-Fall2020
|
anpaschool
|
%matplotlib inline
# Importing standard Qiskit libraries
import random
from qiskit import execute, Aer, IBMQ
from qiskit.tools.jupyter import *
from qiskit.visualization import *
from may4_challenge.ex3 import alice_prepare_qubit, check_bits, check_key, check_decrypted, show_message
# Configuring account
provider = IBMQ.load_account()
backend = provider.get_backend('ibmq_qasm_simulator') # with this simulator it wouldn't work \
# Initial setup
random.seed(84) # do not change this seed, otherwise you will get a different key
# This is your 'random' bit string that determines your bases
numqubits = 100
bob_bases = str('{0:0100b}'.format(random.getrandbits(numqubits)))
def bb84():
print('Bob\'s bases:', bob_bases)
# Now Alice will send her bits one by one...
all_qubit_circuits = []
for qubit_index in range(numqubits):
# This is Alice creating the qubit
thisqubit_circuit = alice_prepare_qubit(qubit_index)
# This is Bob finishing the protocol below
bob_measure_qubit(bob_bases, qubit_index, thisqubit_circuit)
# We collect all these circuits and put them in an array
all_qubit_circuits.append(thisqubit_circuit)
# Now execute all the circuits for each qubit
results = execute(all_qubit_circuits, backend=backend, shots=1).result()
# And combine the results
bits = ''
for qubit_index in range(numqubits):
bits += [measurement for measurement in results.get_counts(qubit_index)][0]
return bits
# Here is your task
def bob_measure_qubit(bob_bases, qubit_index, qubit_circuit):
#
#
if bob_bases[qubit_index] == '0':
qubit_circuit.measure(0, 0)
elif bob_bases[qubit_index] == '1':
qubit_circuit.h(0)
qubit_circuit.measure(0, 0)
#
#
...
bits = bb84()
print('Bob\'s bits: ', bits)
check_bits(bits)
alice_bases = '10000000000100011111110011011001010001111101001101111110001100000110000010011000111'\
'00111010010000110' # Alice's bases bits
#
#
key = ''
for bit, alice_basis, bob_basis in zip(bits, alice_bases, bob_bases):
if alice_basis == bob_basis: key += bit
#
#
check_key(key)
m = '0011011010100011101000001100010000001000011000101110110111100111111110001111100011100101011010111010111010001'\
'1101010010111111100101000011010011011011011101111010111000101111111001010101001100101111011' # encrypted message
#
#
all_key_bits = key * 4
decrypted = ''
for key_bit, message_bit in zip(all_key_bits, m):
decrypted += str( (int(key_bit) + int(message_bit)) % 2)
#
#
check_decrypted(decrypted)
MORSE_CODE_DICT = { 'a':'.-', 'b':'-...',
'c':'-.-.', 'd':'-..', 'e':'.',
'f':'..-.', 'g':'--.', 'h':'....',
'i':'..', 'j':'.---', 'k':'-.-',
'l':'.-..', 'm':'--', 'n':'-.',
'o':'---', 'p':'.--.', 'q':'--.-',
'r':'.-.', 's':'...', 't':'-',
'u':'..-', 'v':'...-', 'w':'.--',
'x':'-..-', 'y':'-.--', 'z':'--..',
'1':'.----', '2':'..---', '3':'...--',
'4':'....-', '5':'.....', '6':'-....',
'7':'--...', '8':'---..', '9':'----.',
'0':'-----', ', ':'--..--', '.':'.-.-.-',
'?':'..--..', '/':'-..-.', '-':'-....-',
'(':'-.--.', ')':'-.--.-'}
#
#
words_decoded = []
words_encoded = decrypted.split('000')
for word_encoded in words_encoded:
letters_encoded = word_encoded.split('00')
letters_decoded = ''
for letter_encoded in letters_encoded:
dotordashes = letter_encoded.split('0')
letter_morse = ''
for dotordash in dotordashes:
if dotordash == '11':
letter_morse += '-'
elif dotordash == '1':
letter_morse += '.'
letters_decoded += next(key for key, value in MORSE_CODE_DICT.items() if value == letter_morse)
words_decoded.append(letters_decoded)
solution = ' '.join(words_decoded)
#
#
show_message(solution)
|
https://github.com/anpaschool/QC-School-Fall2020
|
anpaschool
|
#supporting package
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
from math import pi, sqrt
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute, Aer
qc = QuantumCircuit(2)
qc.h(0)
qc.cz(0, 1) #squareroot control Z-gate
qc.h(1)
qc.swap(0,1) # to make completeness in orthonormal basis
qc.draw('mpl')
s = np.array([[1,0,0,0],[0,0,1,0],[0,1,0,0],[0,0,0,1]])
s
h = np.array([[0.707,0.707,0,0],[0.707,-0.707,0,0],[0,0,0.707,0.707],[0,0,0.707,-0.707]])
h
z=np.array([[1,0,0,0],[0,1,0,0],[0,0,1,0],[0,0,0,0+1.j]])
z
QFT2 = s*h*z*h #need to do
#QFT2
qc = QuantumCircuit(3)
qc.h(2)
display( qc.draw('mpl') )
# UROT_2 gate to x1 depending on x2
qc.cu1(pi/2, 1, 2) # CROT from qubit 1 to qubit 2 hence the angle: pi/2^{2-1}
display ( qc.draw('mpl') )
qc.cu1(pi/4, 0, 2) # CROT from qubit 2 to qubit 0 hence the angle: pi/2^{2-0}
display( qc.draw('mpl') )
# Repeat the process for 1 and 0
qc.h(1) # Hadamard on 1
qc.cu1(pi/2, 0, 1) # CROT from qubit 0 to qubit 1 hence the angle: pi/2^{1-0}
qc.h(0) # Hadamard on 0
display( qc.draw('mpl') )
# Now swap the qubit 0 and 2 to complete QFT. [NOT CLEAR TO ME]
qc.swap(0,2)
display ( qc.draw('mpl') )
qc = QuantumCircuit(2)
qc.h(1)
display( qc.draw('mpl') )
# UROT_1 gate to x0 depending on x1
qc.cu1(pi/2, 0, 1) # CROT from qubit 0 to qubit 1 hence the angle: pi/2^{1-0}
display ( qc.draw('mpl') )
qc.h(0) # Hadamard on 1
# Now swap the qubit 0 and 2 to complete QFT. [To make orthonormal bais set completeness]
qc.swap(0,1)
display ( qc.draw('mpl') )
|
https://github.com/anpaschool/QC-School-Fall2020
|
anpaschool
|
References
1. https://qiskit.org/textbook/preface.html
2. https://www.youtube.com/watch?v=IT-O-KSWlaE
3. https://www.youtube.com/watch?v=m4zs_fqS0Zw
|
https://github.com/anpaschool/QC-School-Fall2020
|
anpaschool
|
#initialization
import matplotlib.pyplot as plt
import numpy as np
# importing Qiskit
from qiskit import IBMQ, Aer, QuantumCircuit, ClassicalRegister, QuantumRegister, execute
from qiskit.providers.ibmq import least_busy
from qiskit.quantum_info import Statevector
# import basic plot tools
from qiskit.visualization import plot_histogram
Circuit = QuantumCircuit(2)
Circuit.draw('mpl')
Circuit.h(0)
Circuit.h(1)
Circuit.draw('mpl')
#apply Oracle U_f
Circuit.cz(0,1)
Circuit.draw('mpl')
#apply diffuser U_S
Circuit.h(0)
Circuit.h(1)
Circuit.z(0)
Circuit.z(1)
Circuit.cz(0,1)
Circuit.h(0)
Circuit.h(1)
Circuit.draw('mpl')
sv_sim = Aer.get_backend('statevector_simulator')
job_sim = execute(Circuit, sv_sim)
statevec = job_sim.result().get_statevector()
from qiskit_textbook.tools import vector2latex
vector2latex(statevec, pretext="|\\psi\\rangle =")
Circuit.measure_all()
qasm_simulator = Aer.get_backend('qasm_simulator')
shots = 1-24
results = execute(Circuit, backend=qasm_simulator, shots=shots).result()
answer = results.get_counts()
plot_histogram(answer)
|
https://github.com/anpaschool/QC-School-Fall2020
|
anpaschool
|
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute, Aer
from qiskit.tools.visualization import plot_histogram, plot_bloch_multivector
#import numpy as np
q = QuantumRegister(2)
c = ClassicalRegister(2)
# Define Quantum circuit with 2 quantum register and 2 classical register
bell = QuantumCircuit(q,c)
# Create a Bell state
bell.x(q[0])
bell.x(q[1])
bell.h(q[0])
bell.cx(q[0], q[1])
# Draw circuit
bell.draw(output = 'mpl')
backend_statevector = Aer.get_backend('statevector_simulator')
job = execute(bell, backend_statevector)
result = job.result()
outputstate = result.get_statevector(bell, decimals = 3)
print(outputstate)
#plot_bloch_multivector(job.result().get_statevector(bell))
bell.measure(q, c)
bell.draw('mpl')
backend = Aer.get_backend('qasm_simulator')
job = execute(bell, backend)
result = job.result()
result.get_counts(bell)
plot_histogram(job.result().get_counts(bell))
import numpy as np
zero_ket = np.array([[1], [0]])
one_ket = np.array([[0], [1]])
ψ = (zero_ket + one_ket)/np.sqrt(2)
print("Density matrix of the equal superposition")
print(ψ @ ψ.T.conj())
print("Density matrix of the equally mixed state of |0><0| and |1><1|")
print((zero_ket @ zero_ket.T.conj()+one_ket @ one_ket.T.conj())/2)
def mixed_state(pure_state, visibility):
#density_matrix = pure_state @ pure_state.T.conj()
density_matrix = np.dot( pure_state, np.matrix.getH(pure_state) )
maximally_mixed_state = np.eye(4)/2**2
return visibility*density_matrix + (1-visibility)*maximally_mixed_state
ϕ = np.array([[1],[0],[0],[1]])/np.sqrt(2)
#print (array_to_latex(ϕ, pretext="$\phi$ = "))
print(f"Maximum visibility is a pure state: \n{mixed_state(ϕ, 1.0)}\n")
print(f"The state is still entangled with visibility 0.8:\n {mixed_state(ϕ, 0.8)}\n")
print(f"Entanglement is lost by 0.6:\n{mixed_state(ϕ, 0.6)}\n")
print(f"Barely any coherence remains by 0.2:\n{mixed_state(ϕ, 0.2)}\n")
import matplotlib.pyplot as plt
temperatures = [.5, 5, 2000]
energies = np.linspace(0, 20, 100)
fig, ax = plt.subplots()
for i, T in enumerate(temperatures):
probabilities = np.exp(-energies/T)
Z = probabilities.sum()
probabilities /= Z
ax.plot(energies, probabilities, linewidth=3, label = "$T_" + str(i+1)+"$="+str(T))
ax.set_xlim(0, 20)
ax.set_ylim(0, 1.2*probabilities.max())
ax.set_xticks([])
ax.set_yticks([])
ax.set_xlabel('Energy')
ax.set_ylabel('Probability')
ax.legend()
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer
cq = QuantumRegister(2,'code\_qubit\_')
lq = QuantumRegister(1,'ancilla\_qubit\_')
sb = ClassicalRegister(1,'syndrome\_bit')
qc = QuantumCircuit(cq,lq,sb)
qc.cx(cq[0],lq[0])
qc.cx(cq[1],lq[0])
qc.measure(lq,sb)
qc.draw('mpl')
qc_init = QuantumCircuit(cq)
(qc_init+qc).draw('mpl')
counts = execute( qc_init+qc, Aer.get_backend('qasm_simulator')).result().get_counts()
print('Results:',counts)
qc_init = QuantumCircuit(cq)
qc_init.x(cq)
(qc_init+qc).draw('mpl')
counts = execute(qc_init+qc, Aer.get_backend('qasm_simulator')).result().get_counts()
print('Results:',counts)
qc_init = QuantumCircuit(cq)
qc_init.h(cq[0])
qc_init.cx(cq[0],cq[1])
(qc_init+qc).draw('mpl')
counts = execute(qc_init+qc, Aer.get_backend('qasm_simulator')).result().get_counts()
print('Results:',counts)
qc_init = QuantumCircuit(cq)
qc_init.h(cq[0])
qc_init.cx(cq[0],cq[1])
qc_init.x(cq[0])
(qc_init+qc).draw('mpl')
counts = execute(qc_init+qc, Aer.get_backend('qasm_simulator')).result().get_counts()
print('Results:',counts)
|
https://github.com/anpaschool/QC-School-Fall2020
|
anpaschool
|
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer
from math import pi
from qiskit.visualization import plot_bloch_multivector, plot_state_qsphere
%matplotlib inline
qcx = QuantumCircuit(1)
qcx.draw('mpl')
backend = Aer.get_backend('statevector_simulator') # Tell Qiskit how to simulate our circuit
job = execute(qcx,backend).result() # Do the simulation, returning the state vector
plot_bloch_multivector(job.get_statevector()) # Display the output state vector
plot_state_qsphere(job.get_statevector(qcx))
# Let's do an X-gate on a |0> qubit
qcx.x(0)
qcx.draw('mpl')
job = execute(qcx,backend).result() # Do the simulation, returning the state vector
plot_bloch_multivector(job.get_statevector()) # Display the output state vector
plot_state_qsphere(job.get_statevector(qcx))
from IPython.display import YouTubeVideo
print("Install Qiskit")
YouTubeVideo("M4EkW4VwhcI")
print("Hello World!")
YouTubeVideo("RrUTwq5jKM4")
|
https://github.com/anpaschool/QC-School-Fall2020
|
anpaschool
|
import numpy as np
n_samples = 100
p_1 = 0.2
x_data = np.random.binomial(1, p_1, (n_samples,))
print(x_data)
frequency_of_zeros, frequency_of_ones = 0, 0
for x in x_data:
if x:
frequency_of_ones += 1/n_samples
else:
frequency_of_zeros += 1/n_samples
print(frequency_of_ones+frequency_of_zeros)
import matplotlib.pyplot as plt
%matplotlib inline
p_0 = np.linspace(0, 1, 100)
#print(p_0)
p_1 = 1-p_0
#print(p_1)
fig, ax = plt.subplots()
ax.set_xlim(-1.2, 1.2)
ax.set_ylim(-1.2, 1.2)
ax.spines['left'].set_position('center')
ax.spines['bottom'].set_position('center')
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.set_xlabel("$p_0$")
ax.xaxis.set_label_coords(1.0, 0.5)
ax.set_ylabel("$p_1$")
ax.yaxis.set_label_coords(0.5, 1.0)
plt.plot(p_0, p_1)
p = np.array([[0.7], [0.3]])
np.linalg.norm(p, ord=1)
Π_0 = np.array([[1, 0], [0, 0]])
np.linalg.norm(Π_0 @ p, ord=1)
Π_1 = np.array([[0, 0], [0, 1]])
np.linalg.norm(Π_1 @ p, ord=1)
p = np.array([[.5], [.5]])
M = np.array([[0.7, 0.6], [0.3, 0.4]])
np.linalg.norm(M @ p, ord=1)
ϵ = 10e-10
p_0 = np.linspace(ϵ, 1-ϵ, 100)
p_1 = 1-p_0
H = -(p_0*np.log2(p_0) + p_1*np.log2(p_1))
fig, ax = plt.subplots()
ax.set_xlim(0, 1)
ax.set_ylim(0, -np.log2(0.5))
ax.set_xlabel("$p_0$")
ax.set_ylabel("$H$")
plt.plot(p_0, H)
plt.axvline(x=0.5, color='k', linestyle='--')
from qiskit import QuantumCircuit, execute,QuantumCircuit, ClassicalRegister, QuantumRegister, Aer
from qiskit.visualization import plot_histogram, plot_bloch_vector,plot_bloch_multivector,plot_state_qsphere
from math import sqrt, pi
import numpy as np
%matplotlib inline
qc = QuantumCircuit(1) # Create a quantum circuit with one qubit
backend = Aer.get_backend('statevector_simulator') # Tell Qiskit how to simulate our circuit
job = execute(qc,backend).result() # Do the simulation, returning the state vector
plot_bloch_multivector(job.get_statevector()) # Display the output state vector
initial_state = [0,1] # Define initial_state as |1>
qc.initialize(initial_state, 0) # Apply initialisation operation to the 0th qubit
qc.draw()# Let's view our circuit
result = execute(qc,backend).result() # Do the simulation, returning the state vector
plot_bloch_multivector(result.get_statevector()) # Display the output state vector
out_state = result.get_statevector()
print(out_state) # Display the output state vector
qc.measure_all()
qc.draw()
result = execute(qc,backend).result()
counts = result.get_counts()
plot_histogram(counts)
initial_state = [1/sqrt(2), 1j/sqrt(2)] # Define state |q>
qc = QuantumCircuit(1) # Must redefine qc
qc.initialize(initial_state, 0)# Initialise the 0th qubit in the state `initial_state`
qc.h(0)
qc.draw()
state = execute(qc,backend).result().get_statevector() # Execute the circuit
print(state) # Print the result
results = execute(qc,backend).result().get_counts()
plot_histogram(results)
vector = [0,1]
qc.initialize(vector, 0)
qc = QuantumCircuit(1) # Redefine qc
initial_state = [0.+1.j/sqrt(2),1/sqrt(2)+0.j]
qc.initialize(initial_state, 0)
print(initial_state)
qc.draw()
state = execute(qc, backend).result().get_statevector()
print("Qubit State = " + str(state))
qc.measure_all()
qc.draw()
state = execute(qc, backend).result().get_statevector()
print("State of Measured Qubit = " + str(state))
π = np.pi
backend = BasicAer.get_backend('qasm_simulator')
q = QuantumRegister(1)
c = ClassicalRegister(1)
circuit = QuantumCircuit(q, c)
circuit.measure(q, c)
job = execute(circuit, backend, shots=100)
result = job.result()
result.get_counts(circuit)
backend_statevector = BasicAer.get_backend('statevector_simulator')
circuit = QuantumCircuit(q, c)
circuit.iden(q[0])
job = execute(circuit, backend_statevector)
plot_bloch_multivector(job.result().get_statevector(circuit))
circuit = QuantumCircuit(q, c)
circuit.ry(π/2, q[0])
circuit.measure(q, c)
job = execute(circuit, backend, shots=100)
plot_histogram(job.result().get_counts(circuit))
circuit = QuantumCircuit(q, c)
circuit.ry(π/2, q[0])
job = execute(circuit, backend_statevector)
plot_bloch_multivector(job.result().get_statevector(circuit))
circuit = QuantumCircuit(q, c)
circuit.x(q[0])
circuit.ry(π/2, q[0])
job = execute(circuit, backend_statevector)
plot_bloch_multivector(job.result().get_statevector(circuit))
circuit.measure(q, c)
job = execute(circuit, backend, shots=100)
plot_histogram(job.result().get_counts(circuit))
circuit = QuantumCircuit(q, c)
circuit.ry(π/2, q[0])
circuit.ry(π/2, q[0])
circuit.measure(q, c)
job = execute(circuit, backend, shots=100)
plot_histogram(job.result().get_counts(circuit))
q0 = np.array([[1], [0]])
q1 = np.array([[1], [0]])
np.kron(q0, q1)
q = QuantumRegister(2)
c = ClassicalRegister(2)
circuit = QuantumCircuit(q, c)
circuit.h(q[0])
circuit.cx(q[0], q[1])
circuit.measure(q, c)
job = execute(circuit, backend, shots=100)
plot_histogram(job.result().get_counts(circuit))
|
https://github.com/anpaschool/QC-School-Fall2020
|
anpaschool
|
from qiskit import *
from math import pi
import numpy as np
from qiskit.quantum_info import Statevector
from qiskit_textbook.tools import array_to_latex
from qiskit.visualization import plot_bloch_multivector, plot_histogram, plot_state_city,plot_state_qsphere
%matplotlib inline
qc1 = QuantumCircuit(2)
qc1.draw('mpl')
backend = Aer.get_backend('statevector_simulator') # Tell Qiskit how to simulate our circuit
final_state = execute(qc1,backend).result().get_statevector()
job = execute(qc1,backend).result() # Do the simulation, returning the state vector
print(final_state)
array_to_latex(final_state, pretext="\\text{Statevector} = ")
plot_state_qsphere(job.get_statevector(qc1))
qc1 = QuantumCircuit(2)
qc1.x(0)
qc1.draw('mpl')
backend = Aer.get_backend('statevector_simulator') # Tell Qiskit how to simulate our circuit
final_state = execute(qc1,backend).result().get_statevector()
job = execute(qc1,backend).result() # Do the simulation, returning the state vector
print(final_state)
array_to_latex(final_state, pretext="\\text{Statevector} = ")
plot_state_qsphere(job.get_statevector(qc1))
qc1 = QuantumCircuit(2)
qc1.x(1)
qc1.draw('mpl')
backend = Aer.get_backend('statevector_simulator') # Tell Qiskit how to simulate our circuit
final_state = execute(qc1,backend).result().get_statevector()
job = execute(qc1,backend).result() # Do the simulation, returning the state vector
print(final_state)
array_to_latex(final_state, pretext="\\text{Statevector = }")
plot_state_qsphere(job.get_statevector(qc1))
qc1 = QuantumCircuit(2)
qc1.x(0)
qc1.x(1)
qc1.draw('mpl')
backend = Aer.get_backend('statevector_simulator') # Tell Qiskit how to simulate our circuit
final_state = execute(qc1,backend).result().get_statevector()
job = execute(qc1,backend).result() # Do the simulation, returning the state vector
print(final_state)
array_to_latex(final_state, pretext="\\text{Statevector} = ")
plot_state_qsphere(job.get_statevector(qc1))
sv = Statevector.from_label('00')
# Bell State |Ψ+>
qcb = QuantumCircuit(2)
qcb.h(0)
qcb.cx(0, 1)
qcb.draw('mpl')
new_sv = sv.evolve(qcb)
print(new_sv)
plot_state_qsphere(new_sv.data)
qc = QuantumCircuit(2)
# Apply H-gate to the first:
qc.h(0)
# Apply a CNOT:
qc.cx(0,1)
qc.draw('mpl')
backend = Aer.get_backend('statevector_simulator')
final_state = execute(qc,backend).result().get_statevector()
job = execute(qc,backend).result() # Do the simulation, returning the state vector
print(np.round(final_state,10))
array_to_latex(final_state, pretext="\\text{Statevector} = ")
plot_state_qsphere(job.get_statevector(qc))
sv = Statevector.from_label('01')
# Bell State |Ψ+>
qcx = QuantumCircuit(2)
qcx.h(0)
qcx.cx(0, 1)
qcx.draw('mpl')
new_sv = sv.evolve(qcx)
print(new_sv)
plot_state_qsphere(new_sv.data)
qc = QuantumCircuit(2)
# Apply H-gate to the first:
qc.x(0)
qc.h(0)
# Apply a CNOT:
qc.cx(0,1)
qc.draw('mpl')
backend = Aer.get_backend('statevector_simulator')
final_state = execute(qc,backend).result().get_statevector()
job = execute(qc,backend).result() # Do the simulation, returning the state vector
print(np.round(final_state,10))
array_to_latex(final_state, pretext="\\text{Statevector} = ")
plot_state_qsphere(job.get_statevector(qc))
sv = Statevector.from_label('10')
# Bell State |Ψ+>
qcx = QuantumCircuit(2)
qcx.h(0)
qcx.cx(0, 1)
qcx.draw('mpl')
new_sv = sv.evolve(qcx)
print(new_sv)
plot_state_qsphere(new_sv.data)
qc = QuantumCircuit(2)
# Apply H-gate to the first:
qc.x(1)
qc.h(0)
# Apply a CNOT:
qc.cx(0,1)
qc.draw('mpl')
backend = Aer.get_backend('statevector_simulator')
final_state = execute(qc,backend).result().get_statevector()
job = execute(qc,backend).result() # Do the simulation, returning the state vector
print(np.round(final_state,10))
array_to_latex(final_state, pretext="\\text{Statevector} = ")
plot_state_qsphere(job.get_statevector(qc))
sv = Statevector.from_label('11')
# Bell State |Ψ+>
qcx = QuantumCircuit(2)
qcx.h(0)
qcx.cx(0, 1)
qcx.draw('mpl')
new_sv = sv.evolve(qcx)
print(new_sv)
plot_state_qsphere(new_sv.data)
qc = QuantumCircuit(2)
# Apply H-gate to the first:
qc.x(0)
qc.x(1)
qc.h(0)
# Apply a CNOT:
qc.cx(0,1)
qc.draw('mpl')
backend = Aer.get_backend('statevector_simulator')
final_state = execute(qc,backend).result().get_statevector()
job = execute(qc,backend).result() # Do the simulation, returning the state vector
print(np.round(final_state,10))
array_to_latex(final_state, pretext="\\text{Statevector} = ")
plot_state_qsphere(job.get_statevector(qc))
|
https://github.com/anpaschool/QC-School-Fall2020
|
anpaschool
|
from qiskit import QuantumCircuit, execute,QuantumCircuit, ClassicalRegister, QuantumRegister, Aer
from math import pi
import numpy as np
from qiskit.visualization import plot_bloch_multivector, plot_histogram
%matplotlib inline
qc = QuantumCircuit(3)
# Apply H-gate to each qubit:
for qubit in range(3):
qc.h(qubit)
# See the circuit:
qc.draw('mpl')
# Let's see the result
def final_state(circuit):
backend = Aer.get_backend('statevector_simulator')
final_state = execute(circuit,backend).result().get_statevector()
return final_state
fs=final_state(qc)
fs
# In Jupyter Notebooks we can display this nicely using Latex.
# If not using Jupyter Notebooks you may need to remove the
# array_to_latex function and use print(final_state) instead.
from qiskit_textbook.tools import array_to_latex
array_to_latex(fs, pretext="\\text{Statevector} = ")
qchx = QuantumCircuit(2)
qchx.h(0)
qchx.x(1)
qchx.draw('mpl')
backend = Aer.get_backend('unitary_simulator')
unitary = execute(qchx,backend).result().get_unitary()
# In Jupyter Notebooks we can display this nicely using Latex.
# If not using Jupyter Notebooks you may need to remove the
# array_to_latex function and use print(unitary) instead.
from qiskit_textbook.tools import array_to_latex
array_to_latex(unitary, pretext="\\text{Circuit = }\n")
qci = QuantumCircuit(2)
qci.x(1)
qci.draw('mpl')
# Simulate the unitary
backend = Aer.get_backend('unitary_simulator')
unitary = execute(qci,backend).result().get_unitary()
# Display the results:
array_to_latex(unitary, pretext="\\text{Circuit = } ")
qcn = QuantumCircuit(2)
# Apply CNOT
qcn.cx(0,1)
# See the circuit:
qcn.draw('mpl')
qch = QuantumCircuit(2)
# Apply H-gate to the first:
qch.h(0)
qch.draw('mpl')
# # Let's see the result:
# backend = Aer.get_backend('statevector_simulator')
# final_state = execute(qch,backend).result().get_statevector()
fs1 = final_state(qch)
fs1
# # Print the statevector neatly:
array_to_latex(fs1, pretext="\\text{Statevector = }")
qchn = QuantumCircuit(2)
# Apply H-gate to the first:
qchn.h(0)
# Apply a CNOT:
qchn.cx(0,1)
qchn.draw('mpl')
# Let's see the result:
fs2 = final_state(qchn)
# Print the statevector neatly:
array_to_latex(fs2, pretext="\\text{Statevector = }")
qcu = QuantumCircuit(2)
# Apply H-gate to the first:
qcu.h(0)
qcu.draw('mpl')
# Let's see the result:
backend = Aer.get_backend('unitary_simulator')
final_state = execute(qcu,backend).result().get_unitary()
# Print the statevector neatly:
array_to_latex(final_state, pretext="\\text{Circuit = }")
qcm = QuantumCircuit(2,2)
# Apply H-gate to the first:
qcm.h(0)
qcm.draw('mpl')
qcm.cx(0,1)
qcm.measure([0,1],[0,1])
qcm.draw('mpl')
# Let's see the result:
backend = Aer.get_backend('qasm_simulator')
results = execute(qcm,backend, shots=1000).result()
counts = results.get_counts(qcm)
print(counts)
plot_histogram(counts)
import qiskit
qiskit.__qiskit_version__
|
https://github.com/anpaschool/QC-School-Fall2020
|
anpaschool
|
#!pip install git+https://github.com/qiskit-community/qiskit-textbook.git#subdirectory=qiskit-textbook-src
import numpy as np
from qiskit_textbook.tools import array_to_latex
Y=np.array([[0,complex(0,-1)],[complex(0,1),0]])
#print ('Y:',Y)
print (array_to_latex(Y,pretext="\\text{Y = } "))
Y_dag= Y.conj().transpose()
print (array_to_latex(Y_dag, pretext="\\text{Y_dag = } "))
A=np.dot(Y,Y_dag)
#print ('A:',A)
print (array_to_latex(A,pretext="\\text{A = } "))
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit import execute
from qiskit import Aer
from qiskit.tools.visualization import circuit_drawer
# Calling a simulator to see what happened after applying the gate
backend_statevector = Aer.get_backend('statevector_simulator')
# create a quantum register and a classical register
q = QuantumRegister(1)
c = ClassicalRegister(1) #used to measure the result
circuit = QuantumCircuit(q, c) # Now we created a circuit
circuit.x(q[0]) # Applied a Pauli X-gate to q0
job = execute(circuit, backend_statevector)
print(array_to_latex(job.result().get_statevector(circuit),pretext="\\text{Psi after X-gate is applied = } "))
circuit.x(q[0]) # Apllied another Pauli X-gate to q
print(circuit.draw(style='mpl'))
job1 = execute(circuit, backend_statevector) # ran the job
#print("Psi after X-gate applied again:",job1.result().get_statevector(circuit))
print(array_to_latex(job1.result().get_statevector(circuit),pretext="\\text{Psi after X-gate is applied again = } "))
np.eye(4) # Creates an identity matrix of 4 X 4
def mixed_state(pure_state, visibility):
density_matrix = pure_state @ pure_state.T.conj()
maximally_mixed_state = np.eye(4)/2**2
return visibility*density_matrix + (1-visibility)*maximally_mixed_state
ϕ = np.array([[1],[0],[0],[1]])/np.sqrt(2)
#####################
print(array_to_latex(ϕ,pretext="\\text{ϕ = } "))
d_m= ϕ @ ϕ.T.conj()
print ('Density_matrix')
print (d_m)
###############################
print("Maximum visibility is a pure state:")
print(mixed_state(ϕ, 1.0))
#############################
print("The state is still entangled with visibility 0.8:")
print(mixed_state(ϕ, 0.8))
################################
print("Entanglement is lost by 0.6:")
print(mixed_state(ϕ, 0.6))
############################
print("Barely any coherence remains by 0.2:")
print(mixed_state(ϕ, 0.2))
import matplotlib.pyplot as plt
temperatures = [.5, 5, 200]
energies = np.linspace(0, 20, 100) # Creating uniform energy levels
fig, ax = plt.subplots()
for i, T in enumerate(temperatures):
probabilities = np.exp(-energies/T)
Z = probabilities.sum()
probabilities /= Z
ax.plot(energies, probabilities, linewidth=3, label = "$T_" + str(i+1)+"$="+str(T))
ax.set_xlim(0, 20)
ax.set_ylim(0, 1.2*probabilities.max())
#ax.set_xticks([])
#ax.set_yticks([])
ax.set_xlabel('Energy')
ax.set_ylabel('Probability')
ax.legend()
from qiskit.providers.aer.noise import NoiseModel
from qiskit.providers.aer.noise.errors import pauli_error, depolarizing_error
def get_noise(p_meas,p_gate):
error_meas = pauli_error([('X',p_meas), ('I', 1 - p_meas)])
error_gate1 = depolarizing_error(p_gate, 1)
error_gate2 = error_gate1.tensor(error_gate1)
noise_model = NoiseModel()
# measurement error is applied to measurements
noise_model.add_all_qubit_quantum_error(error_meas, "measure")
# single qubit gate error is applied to x gates
noise_model.add_all_qubit_quantum_error(error_gate1, ["x"])
# two qubit gate error is applied to cx gates
noise_model.add_all_qubit_quantum_error(error_gate2, ["cx"])
return noise_model
#Create noise_model with a probability of 1% for each type of error
noise_model=get_noise(0.01,0.01)
# initialize circuit with three qubits in the 0 state
qc0 = QuantumCircuit(3,3,name='0')
# measure the qubits
qc0.measure(qc0.qregs[0],qc0.cregs[0])
print(qc0.draw(style='mpl'))
# run the circuit with th noise model and extract the counts
counts_noise = execute( qc0, Aer.get_backend('qasm_simulator'),noise_model=noise_model).result().get_counts()
counts = execute( qc0, Aer.get_backend('qasm_simulator')).result().get_counts()
print(' No noise:',counts,'\n','Noise:',counts_noise)
n =1024 # number of shots
#Running same with '111' this time!
qc1 = QuantumCircuit(3, 3, name='0')
qc1.x(qc1.qregs[0]) # flip each 0 to 1
qc1.measure(qc1.qregs[0],qc1.cregs[0]) # measure the qubits
print(qc1.draw(style='mpl'))
# run the circuit with th noise model and extract the counts
counts_noise = execute( qc1, Aer.get_backend('qasm_simulator'),noise_model=noise_model,shots=n).result().get_counts()
counts = execute( qc1, Aer.get_backend('qasm_simulator'),shots=n).result().get_counts()
print(' No noise:',counts,'\n','Noise:',counts_noise)
#Increase measurement_noise probability
noise_model = get_noise(0.5,0.0)
counts = execute(qc1, Aer.get_backend('qasm_simulator'),noise_model=noise_model).result().get_counts()
print(counts)
|
https://github.com/anpaschool/QC-School-Fall2020
|
anpaschool
|
import numpy as np
import matplotlib.pylab as plt
import seaborn as sns
np.sign(2*np.random.rand(10)-1).astype('int')
class Ising2D():
def __init__(self, N=10, seed=8848):
self.N = N
self.seed = seed
np.random.seed(self.seed)
# construct a lattice with random spins (+1, -1)
self.Lattice = np.array([ np.sign(2*np.random.rand(self.N)-1).astype('int') for i in range(self.N)] )
def Print_lattice(self):
for row in self.Lattice:
print (row)
def Plot_lattice(self):
fig,ax=plt.subplots(1,1, figsize=(6,6))
sns.heatmap(self.Lattice, linecolor='white', cbar=True, ax=ax,\
square=True, cmap='viridis', xticklabels=[], yticklabels=[]);
plt.show()
def Energy(self, J=1):
# one liner using list comprehension
ene = np.sum([ -1.0*J*self.Lattice[i,j] *( self.Lattice[ (i+1)%self.N, j ] + self.Lattice[ (i-1)%self.N, j ] +\
self.Lattice[ i, (j+1)%self.N ] + self.Lattice[ i, (j-1)%self.N ] ) \
for i in range(self.N) for j in range(self.N) ])
return ene
def Magnetization(self):
return np.sum(self.Lattice)
model = Ising2D(N=10, seed=1) # seed 0, N=12
model.Plot_lattice()
#model.Print_lattice()
Ene = model.Energy()
M = model.Magnetization()
print ( f"Energy of given configuration: {Ene} and Magnetization: {M}")
def calculate_energy(J, σ, h=[0]):
energy = -sum(J_ij*σ[i]*σ[i+1] for i, J_ij in enumerate(J))
energy += -sum(h_i*σ_i for h_i, σ_i in zip(h, σ))
return energy
J = [1.0, -1.0]
σ = [+1, -1, +1]
calculate_energy(J, σ)
import itertools
for σ in itertools.product(*[{+1, -1}, {+1, -1}, {+1, -1}]):
#for σ in itertools.product(*[{+1,-1} for _ in range(3)]):
print(f"Spin configuration:\t{σ} \tEnergy: \t {calculate_energy(J, σ)}")
J = [1., 1.]
σ = [+1, -1, +1]
h = [0.5, 0.5, 0.4]
print ( f"J={J} \tEnergy= {calculate_energy(J, σ, h)}")
J = [-1., -1.]
σ = [+1, -1, +1]
h = [0.5, 0.5, 0.4]
print ( f"J={J} \tEnergy= {calculate_energy(J, σ, h)}")
import itertools
J = [-1, -1]
h = [0, 0, 0]
minimum_energy = 0
for σ_c in itertools.product(*[{+1,-1} for _ in range(3)]):
energy = calculate_energy(J, σ_c, h)
if energy < minimum_energy:
minimum_energy = energy
σ = σ_c
σ, minimum_energy
#!pip3 install dimod
import dimod
J = {(0, 1): 1.0, (1, 2): -1.0}
h = {0:0, 1:0, 2:0}
model = dimod.BinaryQuadraticModel(h, J, 0.0, dimod.SPIN) # syntax (linear, quadratic, offset, vartype)
sampler = dimod.SimulatedAnnealingSampler()
response = sampler.sample(model, num_reads=10)
all_ene = [solution.energy for solution in response.data()]
print (f"All energies: {all_ene} with total count: {all_ene.count(-2.)}")
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit import execute
from qiskit import Aer
from qiskit.visualization import plot_state_qsphere
from qiskit_textbook.tools import array_to_latex
np.set_printoptions(precision=3, suppress=True)
backend = Aer.get_backend('statevector_simulator')
q = QuantumRegister(1)
c = ClassicalRegister(1)
circuit = QuantumCircuit(q, c)
display ( circuit.draw('mpl') )
def get_statevector(qc):
return execute(qc, backend = Aer.get_backend('statevector_simulator') ).result().get_statevector()
circuit.z(q[0])
state = get_statevector(circuit)
array_to_latex ( state, pretext="\\text{ State : }\n" )
plot_state_qsphere(state.data)
circuit = QuantumCircuit(q, c)
circuit.z(q[0])
circuit.x(q[0])
state = get_statevector(circuit)
array_to_latex ( state, pretext="\\text{ State : }\n" )
plot_state_qsphere(state.data)
def calculate_energy_expectation(state, hamiltonian):
return np.squeeze(np.dot(np.matrix.getH(state), np.dot(hamiltonian, state) ))
#return float((state.T.conj() @ hamiltonian @ state).real)
#return float((state.T.conj() @ hamiltonian @ state).real)
# built-in operators
from qiskit.quantum_info import Operator, Pauli
array_to_latex ( Operator(Pauli(label='X')).data, pretext="\\text{ Pauli-X operator : }\n" )
array_to_latex ( Operator(Pauli(label='XZ')).data, pretext="\\text{ XZ operator : }\n" )
PauliZ = np.array([[1, 0], [0, -1]])
I2 = np.eye(2)
IZ = np.kron(I2, PauliZ);
ZI = np.kron(PauliZ, I2);
ZZ = np.kron(PauliZ, PauliZ);
H = -ZZ + -0.5*(ZI+IZ);
ψ = np.kron([[1], [0]], [[1], [0]]) ;
ψ_H_ψ = calculate_energy_expectation(ψ, H);
array_to_latex ( IZ, pretext="\\text{ IZ = }\n" )
array_to_latex ( ZI, pretext="\\text{ ZI = }\n" )
array_to_latex ( ZZ, pretext="\\text{ ZZ = }\n" )
array_to_latex ( H, pretext="\\text{ H = }\n" )
array_to_latex ( ψ, pretext="\\text{ ψ = }\n" )
print (f"Energy expectetation value: {ψ_H_ψ}")
circuit = QuantumCircuit(q, c)
circuit.x(q[0]);
circuit.z(q[0])
state = get_statevector(circuit)
op = Operator(circuit)
array_to_latex ( op.data, pretext="\\text{ Pauli-X, then Pauli-Z, Circuit as operator : }\n" )
array_to_latex ( state, pretext="\\text{ Statevector : }\n" )
circuit = QuantumCircuit(q, c)
circuit.z(q[0]);
circuit.x(q[0])
state = get_statevector(circuit)
op = Operator(circuit)
array_to_latex ( op.data, pretext="\\text{ Pauli-Z, then Pauli-X, Circuit as operator : }\n" )
array_to_latex ( state, pretext="\\text{ Statevector: }\n" )
X = np.array([[0, 1], [1, 0]])
IX = np.kron(I2, X)
XI = np.kron(X, I2)
H = H - XI - IX
H
ψ = np.kron([[1], [0]], [[1], [0]])
calculate_energy_expectation(ψ, H)
eigenvalues, eigenvectors = np.linalg.eigh(H)
ψ = eigenvectors[:, 0:1]
energy_expectation_value = calculate_energy_expectation(ψ, H)
energy_expectation_value
from qiskit.providers.aer.noise import NoiseModel
from qiskit.providers.aer.noise.errors import pauli_error, depolarizing_error
from qiskit import ignis
from qiskit.visualization import plot_histogram
# Construct a 5% single-qubit Bit-flip error
p_error = 0.05
bit_flip = pauli_error([('X', p_error), ('I', 1 - p_error)])
phase_flip = pauli_error([('Z', p_error), ('I', 1 - p_error)])
print(bit_flip)
print(phase_flip)
def get_noise(p):
# flip the bit with a given p
error_meas = pauli_error([('X',p), ('I', 1 - p)])
noise_model = NoiseModel()
noise_model.add_all_qubit_quantum_error(error_meas, "measure")
# measurement error is applied to measurements
return noise_model
noise_model = get_noise(0.01)
noise_model
qc = QuantumCircuit(2,2)
qc.x(0)
qc.h(1)
qc.measure(0, 1)
display( qc.draw('mpl') )
backend = Aer.get_backend('qasm_simulator')
noises = np.array([0.01, 0.1, .5])
noises_label = ['noise='+str(n) for n in noises]
all_counts =[]
for noise in noises:
noise_model = get_noise(noise)
job = execute(qc, backend=backend, noise_model=noise_model, shots=10000)
counts = job.result().get_counts()
all_counts.append(counts)
plot_histogram(all_counts, legend=noises_label, figsize=(6, 4))
noise_model = get_noise(0.01)
qc = QuantumCircuit(2,2)
for state in ['00','01','10','11']:
if state[0]=='1':
qc.x(1)
if state[1]=='1':
qc.x(0)
qc.measure(qc.qregs[0],qc.cregs[0])
backend = Aer.get_backend('qasm_simulator')
job = execute(qc, backend=backend, noise_model=noise_model, shots=10000)
counts = job.result().get_counts()
print ( f"Pure State: {state}, mixed states counts: {counts}" )
def Get_matrix():
M = np.zeros((2**2, 2**2), dtype=float)
for i, state in enumerate(['00','01','10','11']):
qc = QuantumCircuit(2,2)
if state[0]=='1': qc.x(1)
if state[1]=='1': qc.x(0)
qc.measure(qc.qregs[0],qc.cregs[0])
backend = Aer.get_backend('qasm_simulator')
job = execute(qc, backend=backend, noise_model=noise_model, shots=10000)
counts = job.result().get_counts()
M[i] = np.array([counts.get(s, 0) for s in ['00','01','10','11'] ])/10000
return M
M = Get_matrix()
array_to_latex(M, pretext="M=")
C_ideal = np.array([0, 5000, 5000, 0] )
C_noisy = np.dot(M, C_ideal)
print (f"C_ideal: {C_ideal}")
print (f"C_Noisy: {C_noisy}")
C_mitigated = np.dot(np.linalg.inv(M), C_noisy)
print (f"C_mitigated: {C_mitigated}")
from qiskit.ignis.mitigation.measurement import (complete_meas_cal, CompleteMeasFitter)
qr = QuantumRegister(2)
meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal')
print ("The basis states: ", state_labels)
for circuit in meas_calibs:
print ("Circuit:",circuit.name)
display(circuit.draw('mpl'))
# Execute the calibration circuits without noise
backend = Aer.get_backend('qasm_simulator')
job = execute(meas_calibs, backend=backend, shots=1000)
cal_results = job.result()
#cal_results
meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal')
print(meas_fitter.cal_matrix)
noise_model = get_noise(0.1)
backend = Aer.get_backend('qasm_simulator')
job = execute(meas_calibs, backend=backend, shots=1000, noise_model=noise_model)
cal_results = job.result()
meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal')
print(meas_fitter.cal_matrix)
qc = QuantumCircuit(2,2)
qc.h(0)
qc.cx(0,1)
display ( qc.draw('mpl') )
qc.measure(qc.qregs[0],qc.cregs[0])
job = execute(qc, backend=backend, shots=10000, noise_model=noise_model)
results = job.result()
noisy_counts = results.get_counts()
print("Noisy Counts:",noisy_counts)
# Get the filter object
meas_filter = meas_fitter.filter
# Results with mitigation
mitigated_results = meas_filter.apply(results)
mitigated_counts = mitigated_results.get_counts(0)
print ("mitigated counts:\n", mitigated_counts)
print ( noisy_counts)
print ( mitigated_counts )
%config InlineBackend.figure_format = 'svg' # Makes the images look nice
plot_histogram([noisy_counts, mitigated_counts], legend=['noisy', 'mitigated'], figsize=(6, 4))
|
https://github.com/anpaschool/QC-School-Fall2020
|
anpaschool
|
import numpy as np
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, BasicAer, IBMQ,Aer
from qiskit.visualization import plot_histogram, plot_bloch_multivector
from qiskit.extensions import Initialize
from qiskit_textbook.tools import random_state, array_to_latex
#Create a circuit
qr = QuantumRegister(3) # Protocol uses 3 qubits
crz = ClassicalRegister(1) # and 2 classical bits
crx = ClassicalRegister(1) # in 2 different registers
teleportation_circuit = QuantumCircuit(qr, crz, crx)
def create_bell_pair(qc, a, b):
"""Creates a bell pair in qc using qubits a & b"""
qc.h(a) # Put qubit a into state |+>
qc.cx(a,b) # CNOT with a as control and b as target
## SETUP
# Protocol uses 3 qubits and 2 classical bits in 2 different registers
qr = QuantumRegister(3,name='q')
crz, crx = ClassicalRegister(1,name='crz'),ClassicalRegister(1,name='crx')
teleportation_circuit = QuantumCircuit(qr, crz, crx)
## STEP 1
# In our case, Telamon entangles qubits q1 and q2
# Let's apply this to our circuit:
create_bell_pair(teleportation_circuit, 1, 2)
# And view the circuit so far:
teleportation_circuit.draw('mpl')
def alice_gates(qc, psi, a):
qc.cx(psi, a)
qc.h(psi)
## STEP 2
teleportation_circuit.barrier() # Use barrier to separate steps
alice_gates(teleportation_circuit, 0, 1)
teleportation_circuit.draw(output='mpl')
def measure_and_send(qc, a, b):
"""Measures qubits a & b and 'sends' the results to Bob"""
qc.barrier()
qc.measure(a,0)
qc.measure(b,1)
measure_and_send(teleportation_circuit, 0 ,1)
teleportation_circuit.draw('mpl')
# This function takes a QuantumCircuit (qc), integer (qubit)
# and ClassicalRegisters (crz & crx) to decide which gates to apply
def bob_gates(qc, qubit, crz, crx):
# Here we use c_if to control our gates with a classical
# bit instead of a qubit
qc.x(qubit).c_if(crx, 1) # Apply gates if the registers
qc.z(qubit).c_if(crz, 1) # are in the state '1'
## STEP 4
## Complete Circuit Again
# Protocol uses 3 qubits and 2 classical bits in 2 different registers
qr = QuantumRegister(3, name="q")
crz, crx = ClassicalRegister(1, name="crz"), ClassicalRegister(1, name="crx")
teleportation_circuit = QuantumCircuit(qr, crz, crx)
## STEP 1
create_bell_pair(teleportation_circuit, 1, 2)
## STEP 2
teleportation_circuit.barrier() # Use barrier to separate steps
alice_gates(teleportation_circuit, 0, 1)
## STEP 3
measure_and_send(teleportation_circuit, 0, 1)
## STEP 4
teleportation_circuit.barrier() # Use barrier to separate steps
bob_gates(teleportation_circuit, 2, crz, crx)
teleportation_circuit.draw('mpl')
psi=random_state(1)
array_to_latex(psi, pretext="|\\psi\\rangle =")
plot_bloch_multivector(psi)
#Create initialization gate to create psi from |0>
init_gate=Initialize(psi)
init_gate.label='init'
## SETUP
qr = QuantumRegister(3, name="q") # Protocol uses 3 qubits
crz = ClassicalRegister(1, name="crz") # and 2 classical registers
crx = ClassicalRegister(1, name="crx")
qc = QuantumCircuit(qr, crz, crx)
## STEP 0
# First, let's initialize Alice's q0
qc.append(init_gate, [0])
qc.barrier()
## STEP 1
# Now begins the teleportation protocol
create_bell_pair(qc, 1, 2)
qc.barrier()
## STEP 2
# Send q1 to Alice and q2 to Bob
alice_gates(qc, 0, 1)
## STEP 3
# Alice then sends her classical bits to Bob
measure_and_send(qc, 0, 1)
## STEP 4
# Bob decodes qubits
bob_gates(qc, 2, crz, crx)
# Display the circuit
qc.draw('mpl')
backend = BasicAer.get_backend('statevector_simulator')
out_vector = execute(qc, backend).result().get_statevector()
plot_bloch_multivector(out_vector)
inverse_init_gate = init_gate.gates_to_uncompute()
## SETUP
qr = QuantumRegister(3, name="q") # Protocol uses 3 qubits
crz = ClassicalRegister(1, name="crz") # and 2 classical registers
crx = ClassicalRegister(1, name="crx")
qc = QuantumCircuit(qr, crz, crx)
## STEP 0
# First, let's initialize Alice's q0
qc.append(init_gate, [0])
qc.barrier()
## STEP 1
# Now begins the teleportation protocol
create_bell_pair(qc, 1, 2)
qc.barrier()
## STEP 2
# Send q1 to Alice and q2 to Bob
alice_gates(qc, 0, 1)
## STEP 3
# Alice then sends her classical bits to Bob
measure_and_send(qc, 0, 1)
## STEP 4
# Bob decodes qubits
bob_gates(qc, 2, crz, crx)
## STEP 5
# reverse the initialization process
qc.append(inverse_init_gate, [2])
# Display the circuit
qc.draw('mpl')
# Need to add a new ClassicalRegister
# to see the result
cr_result = ClassicalRegister(1)
qc.add_register(cr_result)
qc.measure(2,2)
qc.draw('mpl')
backend = BasicAer.get_backend('qasm_simulator')
counts = execute(qc, backend, shots=1024).result().get_counts()
plot_histogram(counts)
|
https://github.com/anpaschool/QC-School-Fall2020
|
anpaschool
|
import numpy as np
import pylab as plt
from numpy import pi
from qiskit import QuantumCircuit, execute, Aer, IBMQ
from qiskit.visualization import plot_histogram, plot_bloch_multivector
qc = QuantumCircuit(3)
qc = QuantumCircuit(3)
qc.h(2)
display( qc.draw('mpl') )
# UROT_2 gate to x1 depending on x2
qc.cu1(pi/2, 1, 2) # CROT from qubit 1 to qubit 2 hence the angle: pi/2^{2-1}
display ( qc.draw('mpl') )
qc.cu1(pi/4, 0, 2) # CROT from qubit 2 to qubit 0 hence the angle: pi/2^{2-0}
display( qc.draw('mpl') )
# Repeat the process for 2 and 3
qc.h(1) # Hadamard on 1
qc.cu1(pi/2, 0, 1) # CROT from qubit 0 to qubit 1 hence the angle: pi/2^{1-0}
qc.h(0) # Hadamard on 0
display( qc.draw('mpl') )
# Now swap the qubit 0 and 2 to complete QFT. [NOT CLEAR TO ME]
qc.swap(0,2)
display ( qc.draw('mpl') )
def qft_rotations(ckt, n):
if n == 0:
return ckt
n -= 1
ckt.h(n)
for qubit in range(n):
ckt.cu1( pi/2**(n-qubit), qubit, n )
qc = QuantumCircuit(4)
qft_rotations(qc,4)
qc.draw('mpl')
def qft_rotations(ckt, n):
if n == 0:
return ckt
n -= 1
ckt.h(n)
for qubit in range(n):
ckt.cu1( pi/2**(n-qubit), qubit, n )
qft_rotations(ckt, n)
qc = QuantumCircuit(4)
qft_rotations(qc,4)
qc.draw('mpl')
from qiskit_textbook.widgets import scalable_circuit
scalable_circuit(qft_rotations)
def swap_registers(ckt, n):
for qubit in range(n//2):
ckt.swap(qubit, n-qubit-1)
return ckt
def qft(ckt, n):
qft_rotations(ckt, n)
swap_registers(ckt, n)
return ckt
qc = QuantumCircuit(4)
qft(qc, 4)
qc.draw('mpl')
print (f"5 and it's binary: {bin(5)}")
#bin(9)
qc = QuantumCircuit(3)
qc.x(0)
qc.x(2)
display(qc.draw('mpl'))
backend = Aer.get_backend('statevector_simulator')
sv = execute(qc, backend=backend).result().get_statevector()
plot_bloch_multivector(sv)
print (sv.real)
qft(qc, 3)
qc.draw('mpl')
sv = execute(qc, backend=backend).result().get_statevector()
plot_bloch_multivector(sv)
print ('The statevectors are:\n', sv.round(1))
print ('Angle subtended by each states (as a factor of pi):\n',(np.angle(sv)/np.pi).round(2))
# 10
qc = QuantumCircuit(2)
qc.x(0)
qc.draw('mpl')
backend = Aer.get_backend('statevector_simulator')
sv = execute(qc, backend=backend).result().get_statevector()
plot_bloch_multivector(sv)
qft(qc, 2)
qc.draw('mpl')
backend = Aer.get_backend('statevector_simulator')
sv = execute(qc, backend=backend).result().get_statevector()
plot_bloch_multivector(sv)
def inverse_qft(circuit, n):
"""Does the inverse QFT on the first n qubits in circuit"""
# First we create a QFT circuit of the correct size:
qft_circ = qft(QuantumCircuit(n), n)
# Then we take the inverse of this circuit
invqft_circ = qft_circ.inverse()
# And add it to the first n qubits in our existing circuit
circuit.append(invqft_circ, circuit.qubits[:n])
# use .decompose() which allows us to see the individual gates
return circuit.decompose()
nqubits = 3
number = 6
qc = QuantumCircuit(nqubits)
for qubit in range(nqubits):
qc.h(qubit)
qc.u1(number*pi/4,0)
qc.u1(number*pi/2,1)
qc.u1(number*pi,2)
qc.draw('mpl')
backend = Aer.get_backend("statevector_simulator")
sv = execute(qc, backend=backend).result().get_statevector()
plot_bloch_multivector(sv)
print ('The statevectors are:\n', sv.round(1))
print ('Angle subtended by each states (as a factor of pi):\n',(np.angle(sv)/np.pi).round(2))
qc = inverse_qft(qc,nqubits)
qc.measure_all()
qc.draw('mpl')
backend = Aer.get_backend("qasm_simulator")
shots = 2048
job = execute(qc, backend=backend, shots=shots, optimization_level=3)
counts = job.result().get_counts()
plot_histogram(counts)
|
https://github.com/anpaschool/QC-School-Fall2020
|
anpaschool
|
import numpy as np
from qiskit import QuantumCircuit, execute, Aer, IBMQ, QuantumRegister, ClassicalRegister
from qiskit import IBMQ, BasicAer
from IPython.core.display import Image, display
simulator = Aer.get_backend('qasm_simulator')
# Alice prepares the qubits
input_register = QuantumRegister(1, "x")
output_register = QuantumRegister(1, "f(x)")
classical_register = ClassicalRegister(1, "c")
circuit_Deutsch = QuantumCircuit(input_register, output_register, classical_register)
# Prepare the qubit in the output register in the |1> state
circuit_Deutsch.x(output_register[0])
# Hadamard gates applied on input and output registers
circuit_Deutsch.h(input_register[0])
circuit_Deutsch.h(output_register[0])
# Add a barrier
circuit_Deutsch.barrier()
# Draw the circuit
circuit_Deutsch.draw(output="mpl")
# Bob's four functions/circuits
# The first option: constant f(0) = f(1) = 0
circuit_Bob1 = QuantumCircuit(input_register, output_register)
circuit_Bob1.barrier()
# The second option: constant f(0) = f(1) = 1
circuit_Bob2 = QuantumCircuit(input_register, output_register)
circuit_Bob2.cx(input_register[0], output_register)
circuit_Bob2.x(input_register[0])
circuit_Bob2.cx(input_register[0], output_register)
circuit_Bob2.x(input_register[0])
circuit_Bob2.barrier()
# The third option: balanced f(0) = 0 & f(1) = 1
circuit_Bob3 = QuantumCircuit(input_register, output_register)
circuit_Bob3.cx(input_register[0], output_register)
circuit_Bob3.barrier()
# The fourth option: balanced f(0) = 1 & f(1) = 0
circuit_Bob4 = QuantumCircuit(input_register, output_register)
circuit_Bob4.x(input_register[0])
circuit_Bob4.cx(input_register[0], output_register)
circuit_Bob4.x(input_register[0])
circuit_Bob4.barrier()
import random
list_options_Bob = [circuit_Bob2,circuit_Bob2, circuit_Bob3, circuit_Bob4]
circuit_Bob_choice = random.choice(list_options_Bob)
# Add the chosen circuit to the main circuit
circuit_Deutsch += circuit_Bob_choice
# Draw the circuit
print("The circuit with Bob's chosen function")
circuit_Deutsch.draw(output="mpl")
# Alice's final operations
circuit_Deutsch.h(input_register[0])
circuit_Deutsch.measure(input_register[0], classical_register[0])
# Draw the final version of the circuit
print("The final version of the circuit")
circuit_Deutsch.draw(output="mpl")
# The execution of the circuit
counts = execute(circuit_Deutsch, simulator, shots=1).result().get_counts()
# Finding the only key/measurement outcome
measurement_result = list(counts.keys())[0]
print("The results of the measurements: {}".format(counts))
print("The final result is: {}".format(measurement_result))
# From the final measurement result, Alice understands if
# the Bob's chosen function balanced or constant
if measurement_result == '0':
print("Bob's chosen function was constant")
elif measurement_result == '1':
print("Bob's chosen function was balanced")
# Alice: qubit preparation
input_register = QuantumRegister(3, "x")
output_register = QuantumRegister(1, "f(x)")
classical_register = ClassicalRegister(3, "c")
circuit_Deutsch_Jozsa = QuantumCircuit(input_register, output_register, classical_register)
# Prepare the qubit in the output register in the |1> state
circuit_Deutsch_Jozsa.x(output_register[0])
# Hadamard gates on both input and output registers
circuit_Deutsch_Jozsa.h(input_register) # Hadamard gate is applied to all qubits in the input_register
circuit_Deutsch_Jozsa.h(output_register[0])
# Add a barrier
circuit_Deutsch_Jozsa.barrier()
circuit_Deutsch_Jozsa.draw('mpl')
# Circuit for the constant function
circtuit_Deutsch_Jozsa_constant = QuantumCircuit(input_register, output_register, classical_register)
circtuit_Deutsch_Jozsa_constant += circuit_Deutsch_Jozsa
# Implementing the f(x) = 1 constant function
circtuit_Deutsch_Jozsa_constant.x(output_register[0])
# Add a barrier
circtuit_Deutsch_Jozsa_constant.barrier()
# Final Hadamard gates applied on all qubits in the input register
circtuit_Deutsch_Jozsa_constant.h(input_register)
# Measurements executed for all qubits in the input register
circtuit_Deutsch_Jozsa_constant.measure(input_register, classical_register)
# Draw the circuit
circtuit_Deutsch_Jozsa_constant.draw(output="mpl")
# A function that will help Alice to define if
# the chosen function was balanced or constant
def is_balanced_or_constant(circuit, bakend):
# The execution of the circuit
counts = execute(circuit, bakend, shots=1).result().get_counts()
# Finding the only key/measurement outcome
measurement_result = list(counts.keys())[0]
print("The results of the measurements: {}".format(counts))
print("The final result is: {}".format(measurement_result))
# Alice checks if Bob's function was constant or balanced
if '000' in counts:
print("Bob's chosen function was constant")
else:
print("Bob's chosen function was balanced")
# Alice uses is_balanced_or_constant() function
is_balanced_or_constant(circtuit_Deutsch_Jozsa_constant, simulator)
# Circuit for the balanced case
circtuit_Deutsch_Jozsa_balanced = QuantumCircuit(input_register, output_register, classical_register)
circtuit_Deutsch_Jozsa_balanced += circuit_Deutsch_Jozsa
# implementing the balanced function
circtuit_Deutsch_Jozsa_balanced.cx(input_register[0], output_register[0])
circtuit_Deutsch_Jozsa_balanced.cx(input_register[1], output_register[0])
circtuit_Deutsch_Jozsa_balanced.cx(input_register[2], output_register[0])
# add a barrier
circtuit_Deutsch_Jozsa_balanced.barrier()
# final Hadamard gates applied on all qubits in the input register
circtuit_Deutsch_Jozsa_balanced.h(input_register)
# measurements executed for all qubits in the input register
circtuit_Deutsch_Jozsa_balanced.measure(input_register, classical_register)
# draw the circuit
circtuit_Deutsch_Jozsa_balanced.draw(output="mpl")
# Alice uses is_balanced_or_constant() function
simulator = Aer.get_backend('qasm_simulator')
is_balanced_or_constant(circtuit_Deutsch_Jozsa_balanced, simulator)
|
https://github.com/anpaschool/QC-School-Fall2020
|
anpaschool
|
from google.colab import drive
drive.mount('/content/drive')
!pip install pylatexenc
!pip install qiskit
# the output will be cleared after installation
from IPython.display import clear_output
clear_output()
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
plt.style.use('seaborn-notebook')
from scipy.fft import fft
def periodfind(x,I,N): # find period a of function f(x)=x^a mod N
arr=[]
for i in range(N):
f= (x**i)%(I)
arr.append(f)
return arr
N=16
I=15
a=11
y=np.array(periodfind(a,I,N))
x=np.arange(N)
print('f(x) = ',y) # Values of f(x)
# plotting
plt.style.use('seaborn-whitegrid')
def plot_fig(xvals,yvals,a,I): # to make the plot nice
yvals=list(yvals)
fig, ax = plt.subplots()
ax.plot(xvals, yvals, linewidth=1, linestyle='--', marker='o')
ax.set(xlabel='$x$', ylabel='f(x)=${a}^x$(mod {I})'.format(a=a,I=I),
title='Period of function f(x)=${a}^x$(mod {I})'.format(a=a,I=I))
try: # plot r on the graph
r = yvals[1:].index(1) +1
plt.annotate(s='', xy=(0,1), xytext=(r,1), arrowprops=dict(arrowstyle='<->'))
plt.annotate(s='$r=%i$' % r, xy=(r/3,1.5))
except:
print('Could not find period, check a < N and have no common factors.')
display(plt.show())
plot_fig(x,y,a,I)
z=fft(y) #Apply Fast fourier Transform
plt.style.use('seaborn-whitegrid')
plt.title('Fast Fourier transform of function f(x)=$3^x$(mod 16)')
plt.bar(x,np.abs(z),width=0.5)
display(plt.show())
print('Period is 1/(a/N) is ',2)
%matplotlib inline
import matplotlib.pyplot as plt
from qiskit import IBMQ
# Importing standard Qiskit libraries and configuring account
from qiskit.compiler import transpile, assemble
# Loading your IBM Q account(s)
# provider = IBMQ.load_account() # uncomment to run on quantum computerr
import numpy as np
import math
import qiskit
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, Aer, execute
from qiskit.tools.monitor import job_monitor
from qiskit.visualization import plot_histogram, plot_bloch_multivector, plot_state_hinton
from qiskit import Aer
def measure(circuit,n,c):
for i in range(n):
circuit.measure(i,i)
return circuit
pi = np.pi
qc_q = QuantumRegister(4, 'input') #Initialize the Working Register
qc_c = QuantumRegister(2, 'period') #Initialize the Control Register
c = ClassicalRegister(4) #Register which will eventually hold measurements
Shor = QuantumCircuit(qc_q, qc_c,c)
Shor.x(4) # It is common convention to add a not gate before Modular Exponentiation
Shor.h(qc_q[0:4]) #Initialize 4 Hadamard Gates to allow for all possibilities
Shor.barrier()
Shor.draw('mpl')
#This is a compiled version of modular exponentiation that will not generalize outside of fermat primes.
Shor.cx(qc_q[0],qc_c[0])
Shor.cx(qc_q[0],qc_c[1])
Shor.barrier()
Shor.draw(output='mpl')
#This can be ommited by classically swapping the order of measurments if noise is an issue.
Shor.swap(qc_q[0],qc_q[3])
Shor.swap(qc_q[1],qc_q[2])
#The Inverse Quantum Fourier Transform
Shor.h(0)
Shor.crz(-pi/2,qc_q[0],qc_q[1])
Shor.h(1)
Shor.crz(-pi/2,qc_q[1],qc_q[2])
Shor.crz(-pi/4,qc_q[0],qc_q[2])
Shor.h(2)
Shor.crz(-pi/2,qc_q[2],qc_q[3])
Shor.crz(-pi/4,qc_q[1],qc_q[3])
Shor.crz(-pi/8,qc_q[0],qc_q[3])
Shor.h(3)
Shor.barrier()
Shor.draw(output='mpl')
#Measure Working Register
Shor.measure(qc_q[3],3)
Shor.measure(qc_q[2],2)
Shor.measure(qc_q[1],1)
Shor.measure(qc_q[0],0)
Shor.draw(output='mpl')
import pandas as pd
df=pd.read_csv("/content/drive/My Drive/QC-project/SHor code/shor_format_15_11.csv")
print(df.head(16))
plt.plot(df["input_reg_value"],df["period_reg_value"])
plt.show()
# # Load our saved IBMQ accounts and get the least busy backend device with less than or equal to nqubits
# provider = IBMQ.get_provider(hub='ibm-q')
# from qiskit.providers.ibmq import least_busy
# backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= N
# and not x.configuration().simulator
# and x.status().operational==True))
# print("least busy backend: ", backend)
simulator = Aer.get_backend('qasm_simulator')
# backend = provider.get_backend("ibmq_16_melbourne") # to run in the actual quantum computer
# Replace simulator in execute function with 'backend' to run on a quantum computer
job = execute(Shor, simulator, shots=8192)
result = job.result()
counts = result.get_counts(Shor)
plot_histogram(counts)
output=[]
for keys in list(counts.keys()):
output.append(int(keys,2))
print('The values with maximum probabilities are: {}'.format(output))
# Classical analysis of result(classical)
print(output)
y_over_N=[out/N for out in output[1:] ]
print('y over N is',y_over_N)
def find_period(output):
y_over_N=[out/N for out in output[1:] ]
from fractions import Fraction
temp=[]
num=len(y_over_N)
for i in range(num):
temp.append(Fraction(y_over_N[i]).limit_denominator(N))
temp[i]=Fraction(temp[i].denominator,temp[i].numerator)
return temp[i].numerator
a= find_period(output)
print('The period of the function is ',a)
# find factors by taking GCD
from math import gcd
factors=[]
if (a/2)-(a//2)==0: # test if (a/2) is integer
p=int(a/2)
factors.append(gcd(11**p+1,15))
factors.append(gcd(11**p-1,15))
print(factors)
# General Implementation of Shor's Algorithm
# Using Qiskit library
from qiskit.aqua import QuantumInstance
from qiskit.aqua.algorithms import Shor
n=63 # n is the number to be factored.
factors= Shor(n) # Shor() is a function in qiskit.aqua.algorithms that performs shor's algorithm
simulator = Aer.get_backend('qasm_simulator')
result_dict = factors.run(QuantumInstance(simulator))
result = result_dict['factors']
result
qc_shor=factors.construct_circuit()
qc_shor.draw('mpl')
import qiskit
qiskit.__qiskit_version__
|
https://github.com/anpaschool/QC-School-Fall2020
|
anpaschool
|
#Create the random probability Vector
import numpy as np
np.random.seed(999999)
target_distr = np.random.rand(2)
#print (target_distr)
# We now convert the random vector into a valid probability vector
target_distr /= sum(target_distr)
print (target_distr) #This is our original state, we want our result close to this
#This block of code is to make a function that takes the parameters of our single U3 variational form as argument
#and returns the corresponding quantum circuit
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
def get_var_form(params):
qr = QuantumRegister(1, name="q")
cr = ClassicalRegister(1, name='c')
qc = QuantumCircuit(qr, cr)
qc.u3(params[0], params[1], params[2], qr[0])
qc.measure(qr, cr[0])
return qc
#Now specify the objective function which takes as input a list of the variational form's parameter and returns
#the cost associated with those parameters(how much the final state is differ from intial state)
from qiskit import Aer, execute
backend = Aer.get_backend("qasm_simulator")
NUM_SHOTS = 10000
def get_probability_distribution(counts):
output_distr = [v / NUM_SHOTS for v in counts.values()]
#print("Counts",counts)
print ("Count Values",counts.values())
#print("Output_distr",output_distr)
#print("Target_distr",target_distr)
if len(output_distr) == 1:
output_distr.append(0)
return output_distr
def objective_function(params):
# Obtain a quantum circuit instance from the paramters
qc = get_var_form(params)
# Execute the quantum circuit to obtain the probability distribution associated with the current parameters
result = execute(qc, backend, shots=NUM_SHOTS).result()
print("Results",result.get_counts(qc))
# Obtain the counts for each measured state, and convert those counts into a probability vector
output_distr = get_probability_distribution(result.get_counts(qc))
# Calculate the cost as the distance between the output distribution and the target distribution
cost = sum([np.abs(output_distr[i] - target_distr[i]) for i in range(2)])
#display(qc.draw('mpl'))
print('Input_distr:',target_distr)
print('Output_distr:',output_distr)
print('Cost',cost)
print('-------------')
return cost #This step is similar as to get the minimum energy state using variational principle
#Finally COBYLA optimizer is used and run the algorithm.
from qiskit.aqua.components.optimizers import COBYLA
# Constrained Optimization by Linear Approximation optimizer (COBYLA)
# Initialize the COBYLA optimizer
optimizer = COBYLA(maxiter=500, disp=True,tol=0.0001)
# Create the initial parameters (noting that our single qubit variational form has 3 parameters)
params = np.random.rand(3)
print ('Input parameters:->',params)
ret = optimizer.optimize(num_vars=3, objective_function=objective_function, initial_point=params)
#print("ret==>",ret)
# Obtain the output distribution using the final parameters
qc = get_var_form(ret[0])
counts = execute(qc, backend, shots=NUM_SHOTS).result().get_counts(qc)
output_distr = get_probability_distribution(counts)
print("Target Distribution:", target_distr)
print("Obtained Distribution:", output_distr)
print("Output Error (Manhattan Distance):", ret[1])
print("Parameters Found:", ret[0])
from qiskit.aqua.algorithms import VQE, NumPyEigensolver
import matplotlib.pyplot as plt
import numpy as np
from qiskit.chemistry.components.variational_forms import UCCSD
from qiskit.chemistry.components.initial_states import HartreeFock
from qiskit.circuit.library import EfficientSU2
from qiskit.aqua.components.optimizers import COBYLA, SPSA, SLSQP
from qiskit.aqua.operators import Z2Symmetries
from qiskit import IBMQ, BasicAer, Aer
from qiskit.chemistry.drivers import PySCFDriver, UnitsType
from qiskit.chemistry import FermionicOperator
from qiskit import IBMQ
from qiskit.aqua import QuantumInstance
from qiskit.ignis.mitigation.measurement import CompleteMeasFitter
from qiskit.providers.aer.noise import NoiseModel
def get_qubit_op(dist):
#Step 1: Define a molecule
#Here, we use LiH in the sto3g basis with the PySCF driver as an example.
#The molecule object records the information from the PySCF driver.
driver = PySCFDriver(atom="Li .0 .0 .0; H .0 .0 " + str(dist), unit=UnitsType.ANGSTROM,
charge=0, spin=0, basis='sto3g')
#sto3g-> small toy model
molecule = driver.run()
#ferOp_nofreeze=FermionicOperator(h1=molecule.one_body_integrals, h2=molecule.two_body_integrals)
freeze_list = [0]
remove_list = [-3, -2]
repulsion_energy = molecule.nuclear_repulsion_energy
#under Born Opperhiemer Approximation all the nuclei are stationary
#so their contribution to the ground state energy is only nuclear repulsion.
#print(repulsion_energy) #in Hatree Unit
num_particles = molecule.num_alpha + molecule.num_beta #number of electrons in the system
#print("number of particles==>",num_particles) #4
num_spin_orbitals = molecule.num_orbitals * 2 #number of spin orbital is twice of that space orbitals
print("number of spin orbitals",num_spin_orbitals)
#as spin degeneracy is 2
remove_list = [x % molecule.num_orbitals for x in remove_list]
#% in interpreted language: Reminder=dividend-divisor*floor(quotient)
#==> R_0 = -3 -6*(-1) = +3 and R_1= -2-6*(-1) = +4
#print ('freeze_list=>',freeze_list) #[0]
#print ('Remove list=>',remove_list) #[3,4]
freeze_list = [x % molecule.num_orbitals for x in freeze_list]
remove_list = [x - len(freeze_list) for x in remove_list]
#print ('freeze_list=>',freeze_list) #[0]
#print ('Remove list=>',remove_list) #[2,3]
remove_list += [x + molecule.num_orbitals - len(freeze_list) for x in remove_list]
freeze_list += [x + molecule.num_orbitals for x in freeze_list]
print ('Remove list=>',remove_list) #[2,3,7,8]
print ('freeze_list=>',freeze_list) #[0,6]
#Define Fermionic Operator
ferOp = FermionicOperator(h1=molecule.one_body_integrals, h2=molecule.two_body_integrals)
ferOp, energy_shift = ferOp.fermion_mode_freezing(freeze_list)# the frozen electron(2 inner electron from Li+)
#do not interact with other electrons but contribute by a constant term to the total ground state energy
num_spin_orbitals -= len(freeze_list) #rescale num_spin_orbiatls after freeze list
num_particles -= len(freeze_list)
print("number of particles==>",num_particles) #print=>2
ferOp = ferOp.fermion_mode_elimination(remove_list)
h1=molecule.one_body_integrals
h2=molecule.two_body_integrals
#print('one body integral=>')
#print (ferOp_nofreeze.h1) #intialially it has 12
#print('one body integral after freezeing and removing')
#print(ferOp.h1) # after applying freeze and remove it drop down to 6
#print('-------------------------------------------')
#print('two body integrals=>')
#print(ferOp.h2)
#print ('------------------------------')
num_spin_orbitals -= len(remove_list)
#print("========================Fermionic Operator After applying freezing and removing list==================")
#print (ferOp)
#Create a Qubit Operator
qubitOp = ferOp.mapping(map_type='parity', threshold=0.00000001)
#print ("=====Qubit Operator berfore applying parity========")
print(qubitOp) # qubits is 6 which is same as fermionic operator after applying freezing and removing list
print(Z2Symmetries.find_Z2_symmetries(qubitOp))#Show spin and charge symmetries, so two conserved quantities
#which will further helps to reduce the qubitOp
qubitOp = Z2Symmetries.two_qubit_reduction(qubitOp, num_particles)
shift = energy_shift + repulsion_energy
#shift is the enegy comming from repulsion energy of two nuclei under Born–Oppenheimer approximation and
#and freezing two electrons
#print("-----------------Qubit Operator after appying parity---------------------")
#print (qubitOp) # give type of operator(paulis) working on number of qubits(6) and number of paulis operator
#print(qubitOp.print_details())
return qubitOp, num_particles, num_spin_orbitals, shift
backend = BasicAer.get_backend("statevector_simulator")
#distances=[1.6]
distances = np.arange(0.5, 4.0, 0.1)
exact_energies = []
vqe_energies = []
optimizer = SLSQP(maxiter=5)
#Sequential Least SQuares Programming optimizer (SLSQP)
for dist in distances:
qubitOp, num_particles, num_spin_orbitals, shift = get_qubit_op(dist) #Returing multiple values in python function
result = NumPyEigensolver(qubitOp).run() #Just to check with result obtained from VQE
exact_energies.append(np.real(result.eigenvalues) + shift)
#Create initial Guess state(Ansatz)
initial_state = HartreeFock(
num_spin_orbitals,
num_particles,
qubit_mapping='parity'
)
print(initial_state.bitstr)
HF_circuit=initial_state.construct_circuit('circuit')
display(HF_circuit.decompose().draw(output='mpl')) #inital Hatree Fock state
#UCCSD is used as problem has one and two body integral
var_form = UCCSD(
num_orbitals=num_spin_orbitals,
num_particles=num_particles,
initial_state=initial_state,
qubit_mapping='parity'
)
#print(var_form.single_excitations)
print("Number of Parameters",var_form.num_parameters)
#var_circuit=var_form.construct_circuit([2])
#display(var_circuit.decompose().draw('mpl'))
vqe = VQE(qubitOp, var_form, optimizer)
vqe_result = np.real(vqe.run(backend)['eigenvalue'] + shift)
vqe_energies.append(vqe_result)
print("Interatomic Distance:", np.round(dist, 2), "VQE Result:", vqe_result, "Exact Energy:", exact_energies[-1])
print("All energies have been calculated")
plt.plot(distances, exact_energies, label="Exact Energy")
#plt.plot(distances, vqe_energies, label="VQE Energy")
plt.xlabel('Atomic distance (Angstrom)')
plt.ylabel('Energy')
plt.legend()
plt.show()
init_state=HartreeFock(num_orbitals=4,num_particles=2,qubit_mapping='jordan_wigner')
print(init_state.bitstr) #give fermionic mode on which particle are occupied
HF_circuit=init_state.construct_circuit('circuit')
display(HF_circuit.decompose().draw('mpl'))
UCCSD_var_form=UCCSD(num_orbitals=4,num_particles=2,qubit_mapping='jordan_wigner',excitation_type='s',
method_singles='beta',initial_state=init_state,two_qubit_reduction=False,reps=1)
var_circuit=UCCSD_var_form.construct_circuit([1])
var_circuit.decompose().draw(output='mpl')
#print(UCCSD_var_form.single_excitations)
|
https://github.com/anpaschool/QC-School-Fall2020
|
anpaschool
|
import numpy as np
from qiskit import QuantumCircuit, execute, Aer, IBMQ, QuantumRegister, ClassicalRegister
from qiskit import IBMQ, BasicAer
from qiskit.circuit.library import QFT
from IPython.core.display import Image, display
#INITIALISE THE QUANTUM AND CLASSICAL REGISTERS
q = QuantumRegister(4,'q')
c = ClassicalRegister(3,'c')
circuit1 = QuantumCircuit(q,c)
#PUT THE COUNTING QUBITS IN TO SUPERPOSITION
circuit1.h(q[0])
circuit1.h(q[1])
circuit1.h(q[2])
circuit1.x(q[3]) # Flips Q[3] to 1
circuit1.draw('mpl')
pi= np.pi
angle = 2*pi/3 #The phase angle we wish to encode
actual_phase = angle/(2*pi) # This is the actual phase rotation ie 0.5 would be half a rotation.
#Our expected rotation will be 0.33.
circuit1.cu1(angle, q[0], q[3]);#where angle is the rotation amount, q[0] is the control qubit and q[3] is the target qubit
circuit1.cu1(angle, q[1], q[3]);
circuit1.cu1(angle, q[1], q[3]);
circuit1.cu1(angle, q[2], q[3]);
circuit1.cu1(angle, q[2], q[3]);
circuit1.cu1(angle, q[2], q[3]);
circuit1.cu1(angle, q[2], q[3]);
circuit1.barrier()
circuit1.draw('mpl')
circuit1.swap(q[0],q[2])
circuit1.h(q[0])
circuit1.cu1(-pi/2, q[0], q[1]);
circuit1.h(q[1])
circuit1.cu1(-pi/4, q[0], q[2]);
circuit1.cu1(-pi/2, q[1], q[2]);
circuit1.h(q[2])
circuit1.barrier()
circuit1.draw('mpl')
#### Measuring counting qubits ####
circuit1.measure(q[0],0)
circuit1.measure(q[1],1)
circuit1.measure(q[2],2)
from qiskit.visualization import plot_histogram
simulator = Aer.get_backend('qasm_simulator')
counts = execute(circuit1, backend=simulator, shots=1000).result().get_counts(circuit1)
plot_histogram(counts)
maxcounts = max(counts, key=counts.get) # take the most often obtaned result
print(maxcounts)
a=int(maxcounts, 2)#convert to decimal
print(a)
print('Most frequent measurement: ',a,'\n')
n=3
phase = a/(2**n)# The calculation used to estimate the phase
print('Actual phase is: ',actual_phase)
print('Estimated phase is: ',phase)
|
https://github.com/anpaschool/QC-School-Fall2020
|
anpaschool
|
import numpy as np
from random import random
from qiskit import *
from qiskit.aqua.utils.controlled_circuit import get_controlled_circuit
num_bits_estimate = 3
# For 2x2 matrix one qubit is enough
q = QuantumRegister(1, name="q")
# In QPE we use n ancillas to estimate n bits from the phase
a = QuantumRegister(num_bits_estimate, name="a")
# For n ancillary qubit measurment we need n cllasical bits
c = ClassicalRegister(num_bits_estimate, name="c")
# Create a quantum circuit
circuit = QuantumCircuit(q, a, c)
# |1> eigenstate initialization
circuit.x(q[0])
circuit.draw('mpl')
E_1, E_2 = (2 * np.pi * random(), 2 * np.pi * random())
print("We are going to estimate E_2 via QPE algorithm \nE_2 = {}".format(E_2))
# circuit for unitary operator exp(iHt)
t = 1
unitary = QuantumCircuit(q)
unitary.u1(E_2 * t, q[0]) # q[0] is the only qubit in q register
unitary.x(q[0])
unitary.u1(E_1 * t, q[0])
unitary.x(q[0])
unitary.draw('mpl')
for ancillary in a:
circuit.h(ancillary)
for n in range(a.size):
for m in range(2**n):
get_controlled_circuit(unitary, a[n], circuit)
# inverse QFT without SWAP gates
for n in reversed(range(a.size)):
circuit.h(a[n])
if n != 0:
for m in reversed(range(n)):
angle = -2*np.pi / (2**(n - m + 1))
circuit.cu1(angle, a[n], a[m])
# measurements on the ancillary qubits stored in c classical register
for n in reversed(range(a.size)):
circuit.measure(a[n],c[n])
circuit.draw('mpl')
backend = BasicAer.get_backend('qasm_simulator')
shots = 1024 # how many time execute the algorithm
job = execute(circuit, backend, shots=shots)
result = job.result()
counts = result.get_counts()
phase_bits = max(counts, key=counts.get) # take the most often obtaned result
phase = 0
for index, bit in enumerate(reversed(phase_bits)):
phase += int(bit) / 2**(index + 1)
estimated_E_2 = 2 * np.pi * phase / t
print("Eigenvalue of the Hamiltonian: {}".format(E_2))
print("Estimated eigenvalue of the Hamiltonian: {}".format(estimated_E_2))
|
https://github.com/anpaschool/QC-School-Fall2020
|
anpaschool
|
#101
000 -put AND gate ->010
--- 3 step
# initialization
import matplotlib.pyplot as plt
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.visualization import plot_histogram
n = 5# number of qubits used to represent s
s = '10011' # the hidden binary string
# We need a circuit with n qubits, plus one ancilla qubit
# Also need n classical bits to write the output to
bv_circuit = QuantumCircuit(n+1, n)
# put ancilla in state |->
bv_circuit.h(n)
bv_circuit.z(n)
# Apply Hadamard gates before querying the oracle
for i in range(n):
bv_circuit.h(i)
# Apply barrier
bv_circuit.barrier()
# Apply the inner-product oracle
s = s[::-1] # reverse s to fit qiskit's qubit ordering
for q in range(n):
if s[q] == '0':
bv_circuit.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()
# use local simulator
backend = BasicAer.get_backend('qasm_simulator')
shots = 1024
results = execute(bv_circuit, backend=backend, shots=shots).result()
answer = results.get_counts()
plot_histogram(answer)
|
https://github.com/anpaschool/QC-School-Fall2020
|
anpaschool
|
# importing Qiskit
from qiskit import IBMQ, BasicAer
from qiskit.providers.ibmq import least_busy
from qiskit import QuantumCircuit, execute
# import basic plot tools
from qiskit.visualization import plot_histogram
from qiskit_textbook.tools import simon_oracle
%matplotlib inline
b = '111'
n = len(b)
simon_circuit = QuantumCircuit(n*2, n)
# Apply Hadamard gates before querying the oracle
simon_circuit.h(range(n))
# Apply barrier for visual separation
simon_circuit.barrier()
simon_circuit += simon_oracle(b)
# Apply barrier for visual separation
simon_circuit.barrier()
# Apply Hadamard gates to the input register
simon_circuit.h(range(n))
# Measure qubits
simon_circuit.measure(range(n), range(n))
simon_circuit.draw()
# use local simulator
backend = BasicAer.get_backend('qasm_simulator')
shots = 1024
results = execute(simon_circuit, backend=backend, shots=shots).result()
counts = results.get_counts()
plot_histogram(counts)
print(counts)
# Calculate the dot product of the results
def bdotz(b, z):
accum = 0
for i in range(len(b)):
accum += int(b[i]) * int(z[i])
return (accum % 2)
for z in counts:
print( '{}.{} = {} (mod 2)'.format(b, z, bdotz(b,z)) )
b = '10'
n = len(b)
simon_circuit_2 = QuantumCircuit(n*2, n)
# Apply Hadamard gates before querying the oracle
simon_circuit_2.h(range(n))
# Apply barrier for visual separation
simon_circuit_2.barrier()
# Query oracle
simon_circuit_2 += simon_oracle(b)
# Apply barrier for visual separation
simon_circuit_2.barrier()
# Apply Hadamard gates to the input register
simon_circuit_2.h(range(n))
# Measure qubits
simon_circuit_2.measure(range(n), range(n))
simon_circuit_2.draw()
# 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')
backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= n and
not x.configuration().simulator and x.status().operational==True))
print("least busy backend: ", backend)
# Execute and monitor the job
from qiskit.tools.monitor import job_monitor
shots = 1024
job = execute(simon_circuit_2, backend=backend, shots=shots, optimization_level=3)
job_monitor(job, interval = 2)
# Get results and plot counts
device_counts = job.result().get_counts()
plot_histogram(device_counts)
# Calculate the dot product of the results
def bdotz(b, z):
accum = 0
for i in range(len(b)):
accum += int(b[i]) * int(z[i])
return (accum % 2)
print('b = ' + b)
for z in device_counts:
print( '{}.{} = {} (mod 2) ({:.1f}%)'.format(b, z, bdotz(b,z), device_counts[z]*100/shots))
|
https://github.com/7enTropy7/Shor-s-Algorithm_Quantum
|
7enTropy7
|
import numpy as np
import math
import gmpy2
from gmpy2 import powmod,mpz,isqrt,invert
from qiskit.aqua.algorithms import Shor
from qiskit.aqua import QuantumInstance
from qiskit import Aer,execute,QuantumCircuit
from qiskit.tools.visualization import plot_histogram
from qiskit.providers.ibmq import least_busy
from qiskit import IBMQ, execute
def generate_keys():
# prime number of 3 digits i.e 7 bits
random1 = np.random.randint(3,40)
random2 = np.random.randint(3,40)
p = int(gmpy2.next_prime(random1))
q = int(gmpy2.next_prime(random2))
n = p*q
while (n<100 or n>127):
random1 = np.random.randint(3,40)
random2 = np.random.randint(3,40)
p = int(gmpy2.next_prime(random1))
q = int(gmpy2.next_prime(random2))
n = p*q
phi = (p-1)*(q-1)
e = 2
while True:
if gmpy2.gcd(phi,e) != 1:
e = e + 1
else :
break
d = gmpy2.invert(e,phi)
return n,e,d
def encrypt(plain_text_blocks,public_keys):
cipher_text_blocks = []
n,e = public_keys
for plain_text in plain_text_blocks:
cipher_text = (gmpy2.powmod(plain_text,e,n))
cipher_text_blocks.append(cipher_text)
return cipher_text_blocks
def decrypt(cipher_text_blocks,secret_key,public_keys):
n,e = public_keys
d = secret_key
decypted_plain_text_blocks = []
for cipher_text in cipher_text_blocks:
plain_text = (gmpy2.powmod(cipher_text,d,n))
decypted_plain_text_blocks.append(plain_text)
return decypted_plain_text_blocks
def get_factors(public_keys):
n,e = public_keys
# backend = Aer.get_backend('qasm_simulator')
provider = IBMQ.load_account()
backend = provider.get_backend('ibmq_qasm_simulator')
quantum_instance = QuantumInstance(backend,shots=2500)
find_factors = Shor(n,a=2,quantum_instance=quantum_instance)
factors = Shor.run(find_factors)
p = ((factors['factors'])[0])[0]
q = ((factors['factors'])[0])[1]
print('Factors of',n,'are :',p,q)
return p,q
# taken in 'Hello World!!!' returns ['Hello World!','!!']
def get_blocks(PT,block_size):
blocks = []
i = 0
while i<len(PT):
temp_str=''
if i+block_size-1 < len(PT):
temp_str=temp_str+PT[i:i+block_size]
else :
temp_str=temp_str+PT[i::]
blocks.append(temp_str)
i=i+block_size
return blocks
# covert plain_text block from characters to the numbers
def format_plain_text(PT):
plain_text_blocks = []
for block in PT:
plain_text = 0
for i in range(len(block)):
# for 'd'
if ord(block[i]) == 100:
plain_text = plain_text*100 + 28
# between (101,127)
elif ord(block[i])>100:
plain_text = plain_text*100 + (ord(block[i])-100)
else :
plain_text = plain_text*100 + (ord(block[i]))
plain_text_blocks.append(plain_text)
return plain_text_blocks
# convert numeric decypted_plain_text_blocks into a single plain text of characters
def format_decrypted_plain_text(decypted_plain_text_blocks):
plain_text_blocks = []
for dc_pt in decypted_plain_text_blocks:
plain_text = ''
temp = dc_pt
# for 'd' temp = 28
while temp > 0:
if temp%100 == 28:
plain_text = plain_text + 'd'
elif (temp%100) in range(0,27):
plain_text = plain_text + chr((temp%100)+100)
else :
plain_text = plain_text + chr((temp%100))
temp = temp//100
plain_text = plain_text[::-1]
plain_text_blocks.append(plain_text)
final_plain_text = ''
for plain_text_block in plain_text_blocks:
final_plain_text = final_plain_text + plain_text_block
return final_plain_text
n,e,d = generate_keys()
public_keys = (n,e)
secret_key = d
print("\nPublic Key :")
print('n :',n)
print('e :',e)
print("Secret Key :\nd :",d)
PT = input("\nEnter Plain Text to encrypt : ")
original_plain_text = PT
block_size = 1
PT = get_blocks(PT,block_size)
print('\nPlain Text after converting to blocks',PT)
plain_text_blocks = format_plain_text(PT)
print('\nPlain text blocks after formatting to numbers:',plain_text_blocks)
cipher_text_blocks = encrypt(plain_text_blocks,public_keys)
print("\nCipher Text Blocks After RSA encryption :",cipher_text_blocks)
p,q = get_factors(public_keys)
phi = (p-1)*(q-1)
broken_d = gmpy2.invert(e,phi)
compromised_PT = decrypt(cipher_text_blocks,broken_d,public_keys)
compromised_PT = format_decrypted_plain_text(compromised_PT)
compromised_PT = '!!!Your message has been attacked!!! ' + compromised_PT
compromised_PT = get_blocks(compromised_PT,block_size)
compromised_PT = format_plain_text(compromised_PT)
compromised_CT = encrypt(compromised_PT,public_keys)
cipher_text_blocks = compromised_CT
decypted_plain_text_blocks = decrypt(cipher_text_blocks,secret_key,public_keys)
print("\nPlain Text blocks after decryption of Cipher Text blocks :",decypted_plain_text_blocks)
plain_text_after_decryption = format_decrypted_plain_text(decypted_plain_text_blocks)
print("\nAfter decryption Plain Text :",plain_text_after_decryption)
if (original_plain_text == plain_text_after_decryption):
print("\nHurrayyy!!!\n\nDecrypted plain_text is same as original plain_text! :) ")
else :
print('RSA was attacked!!! :(')
|
https://github.com/7enTropy7/Shor-s-Algorithm_Quantum
|
7enTropy7
|
from math import gcd,log
from random import randint
import numpy as np
from qiskit import *
qasm_sim = qiskit.Aer.get_backend('qasm_simulator')
def period(a,N):
available_qubits = 16
r=-1
if N >= 2**available_qubits:
print(str(N)+' is too big for IBMQX')
qr = QuantumRegister(available_qubits)
cr = ClassicalRegister(available_qubits)
qc = QuantumCircuit(qr,cr)
x0 = randint(1, N-1)
x_binary = np.zeros(available_qubits, dtype=bool)
for i in range(1, available_qubits + 1):
bit_state = (N%(2**i)!=0)
if bit_state:
N -= 2**(i-1)
x_binary[available_qubits-i] = bit_state
for i in range(0,available_qubits):
if x_binary[available_qubits-i-1]:
qc.x(qr[i])
x = x0
while np.logical_or(x != x0, r <= 0):
r+=1
qc.measure(qr, cr)
for i in range(0,3):
qc.x(qr[i])
qc.cx(qr[2],qr[1])
qc.cx(qr[1],qr[2])
qc.cx(qr[2],qr[1])
qc.cx(qr[1],qr[0])
qc.cx(qr[0],qr[1])
qc.cx(qr[1],qr[0])
qc.cx(qr[3],qr[0])
qc.cx(qr[0],qr[1])
qc.cx(qr[1],qr[0])
result = execute(qc,backend = qasm_sim, shots=1024).result()
counts = result.get_counts()
print(qc)
results = [[],[]]
for key,value in counts.items(): #the result should be deterministic but there might be some quantum calculation error so we take the most reccurent output
results[0].append(key)
results[1].append(int(value))
s = results[0][np.argmax(np.array(results[1]))]
return r
def shors_breaker(N):
N = int(N)
while True:
a=randint(0,N-1)
g=gcd(a,N)
if g!=1 or N==1:
return g,N//g
else:
r=period(a,N)
if r % 2 != 0:
continue
elif pow(a,r//2,N)==-1:
continue
else:
p=gcd(pow(a,r//2)+1,N)
q=gcd(pow(a,r//2)-1,N)
if p==N or q==N:
continue
return p,q
N=int(input("Enter a number:"))
assert N>0,"Input must be positive"
print(shors_breaker(N))
|
https://github.com/7enTropy7/Shor-s-Algorithm_Quantum
|
7enTropy7
|
import RSA_module
bit_length = int(input("Enter bit_length: "))
public, private = RSA_module.generate_keypair(2**bit_length)
msg = input("\nWrite message: ")
encrypted_msg, encryption_obj = RSA_module.encrypt(msg, public)
print("\nEncrypted message: " + encrypted_msg)
decrypted_msg = RSA_module.decrypt(encryption_obj, private)
print("\nDecrypted message using RSA Algorithm: " + decrypted_msg)
from math import gcd,log
from random import randint
import numpy as np
from qiskit import *
qasm_sim = qiskit.Aer.get_backend('qasm_simulator')
def period(a,N):
available_qubits = 16
r=-1
if N >= 2**available_qubits:
print(str(N)+' is too big for IBMQX')
qr = QuantumRegister(available_qubits)
cr = ClassicalRegister(available_qubits)
qc = QuantumCircuit(qr,cr)
x0 = randint(1, N-1)
x_binary = np.zeros(available_qubits, dtype=bool)
for i in range(1, available_qubits + 1):
bit_state = (N%(2**i)!=0)
if bit_state:
N -= 2**(i-1)
x_binary[available_qubits-i] = bit_state
for i in range(0,available_qubits):
if x_binary[available_qubits-i-1]:
qc.x(qr[i])
x = x0
while np.logical_or(x != x0, r <= 0):
r+=1
qc.measure(qr, cr)
for i in range(0,3):
qc.x(qr[i])
qc.cx(qr[2],qr[1])
qc.cx(qr[1],qr[2])
qc.cx(qr[2],qr[1])
qc.cx(qr[1],qr[0])
qc.cx(qr[0],qr[1])
qc.cx(qr[1],qr[0])
qc.cx(qr[3],qr[0])
qc.cx(qr[0],qr[1])
qc.cx(qr[1],qr[0])
result = execute(qc,backend = qasm_sim, shots=1024).result()
counts = result.get_counts()
#print(qc)
results = [[],[]]
for key,value in counts.items():
results[0].append(key)
results[1].append(int(value))
s = results[0][np.argmax(np.array(results[1]))]
return r
def shors_breaker(N):
N = int(N)
while True:
a=randint(0,N-1)
g=gcd(a,N)
if g!=1 or N==1:
return g,N//g
else:
r=period(a,N)
if r % 2 != 0:
continue
elif pow(a,r//2,N)==-1:
continue
else:
p=gcd(pow(a,r//2)+1,N)
q=gcd(pow(a,r//2)-1,N)
if p==N or q==N:
continue
return p,q
def modular_inverse(a,m):
a = a % m;
for x in range(1, m) :
if ((a * x) % m == 1) :
return x
return 1
N_shor = public[1]
assert N_shor>0,"Input must be positive"
p,q = shors_breaker(N_shor)
phi = (p-1) * (q-1)
d_shor = modular_inverse(public[0], phi)
decrypted_msg = RSA_module.decrypt(encryption_obj, (d_shor,N_shor))
print('\nMessage Cracked using Shors Algorithm: ' + decrypted_msg + "\n")
|
https://github.com/VedDharkar/IBM_QISKIT_EXAM_C1000-112
|
VedDharkar
|
import numpy as np
# Importing standard Qiskit libraries
from qiskit import QuantumCircuit, transpile, Aer, IBMQ
from qiskit.tools.jupyter import *
from qiskit.visualization import *
from ibm_quantum_widgets import *
from qiskit import *
# Loading your IBM Q account(s)
#provider = IBMQ.load_account()
q = QuantumRegister(2) #Defining qubits
c = ClassicalRegister(2) #Defining bits
qc = QuantumCircuit(q, c) #Making a Circuit
#Entanglement
qc.h(q[0]) #Hadamard Gate
qc.cx(q[0], q[1]) #CNOT Gate (Control on 1st qubit and target on 2nd qubit)
qc.measure(q, c) #Measure qubits to bits
qc.draw('mpl')
qc.draw('text')
qc.draw('latex')
|
https://github.com/VedDharkar/IBM_QISKIT_EXAM_C1000-112
|
VedDharkar
|
import numpy as np
# Importing standard Qiskit libraries
from qiskit import QuantumCircuit, transpile, Aer, IBMQ
from qiskit.tools.jupyter import *
from qiskit.visualization import *
from ibm_quantum_widgets import *
from qiskit import *
# Loading your IBM Q account(s)
#provider = IBMQ.load_account()
q = QuantumRegister(1)
c = ClassicalRegister(1)
qc = QuantumCircuit(q, c)
qc.h(q[0])
from qiskit.quantum_info import *
Density_Matrix = DensityMatrix.from_instruction(qc)
plot_state_hinton(Density_Matrix) #Hinton plot tells the imaginary and real part of the circuit
|
https://github.com/VedDharkar/IBM_QISKIT_EXAM_C1000-112
|
VedDharkar
|
import numpy as np
# Importing standard Qiskit libraries
from qiskit import QuantumCircuit, transpile, Aer, IBMQ
from qiskit.tools.jupyter import *
from qiskit.visualization import *
from ibm_quantum_widgets import *
from qiskit import *
# Loading your IBM Q account(s)
#provider = IBMQ.load_account()
q = QuantumRegister(2)
c = ClassicalRegister(2)
qc = QuantumCircuit(q, c)
qc.h(q[0])
qc.measure(q, c)
sim = Aer.get_backend('qasm_simulator')
job = execute(qc, sim, shots=1024)
result = job.result()
counts = result.get_counts()
counts
#THERE ARE 3 WAYS TO CHECK MONITOR YOUR JOB
#MONITOR JOB STATUS:-
job.status()
from qiskit.tools import *
job_monitor(job)
import qiskit.tools.jupyter
%qiskit_job_watcher
|
https://github.com/VedDharkar/IBM_QISKIT_EXAM_C1000-112
|
VedDharkar
|
import numpy as np
# Importing standard Qiskit libraries
from qiskit import QuantumCircuit, transpile, Aer, IBMQ
from qiskit.tools.jupyter import *
from qiskit.visualization import *
from ibm_quantum_widgets import *
from qiskit import *
# Loading your IBM Q account(s)
provider = IBMQ.load_account()
backend = provider.get_backend('ibmq_belem')
plot_gate_map(backend) #Tells us the way the qubits are arranged in a quantum system
plot_error_map(backend) #Also tell us the error rate of the qubits
#THERE ARE 2 WAYS TO SEE THE VERSION OF QISKIT:-
qiskit.__qiskit_version__ #TELLS US ABOUT THE VERSION OF QISKIT
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_backend_overview #TELLS US ABOUT THE HARDWARE PART OF EACH AVAILABLE QUANTUM SYSTEM.
#T1 = RELAXATION TIME | T2 = DECOHERNECE TIME | Avg. CX Err = Gate error rate | Avg. Meas.Er = Measurement error rate
|
https://github.com/VedDharkar/IBM_QISKIT_EXAM_C1000-112
|
VedDharkar
|
import numpy as np
# Importing standard Qiskit libraries
from qiskit import QuantumCircuit, transpile, Aer, IBMQ, QuantumRegister
from qiskit.tools.jupyter import *
from qiskit.visualization import *
from ibm_quantum_widgets import *
from qiskit import *
# Loading your IBM Q account(s)
#provider = IBMQ.load_account()
q = QuantumRegister(2)
c = ClassicalRegister(2)
qc = QuantumCircuit(q, c)
qc.h(q[0])
qc.cx(q[0], q[1])
qc.measure(q, c)
#you can also use
#qc.measure_all() OR
#qc.measure([0], [0])
qc.draw('mpl')
sim = Aer.get_backend('qasm_simulator')
job = execute(qc, sim, shots=1024)
result = job.result()
counts = result.get_counts()
plot_histogram(counts)
#QASM SIMULATOR NEEDS MEASUREMENT AND COUNTS AS INPUT NOT STATE
|
https://github.com/VedDharkar/IBM_QISKIT_EXAM_C1000-112
|
VedDharkar
|
import numpy as np
# Importing standard Qiskit libraries
from qiskit import QuantumCircuit, transpile, Aer, IBMQ
from qiskit.tools.jupyter import *
from qiskit.visualization import *
from ibm_quantum_widgets import *
from qiskit import *
# Loading your IBM Q account(s)
#provider = IBMQ.load_account()
q = QuantumRegister(1)
c = ClassicalRegister(1)
qc = QuantumCircuit(q, c)
qc.h(q[0])
qc.x(q[0])
qc.measure(q, c)
#To convert into qasm use:-
qc.qasm(formatted=True, filename='my_circuit.qasm')
#To get circuit from qasm file use:-
qc = QuantumCircuit.from_qasm_file('my_circuit.qam')
|
https://github.com/VedDharkar/IBM_QISKIT_EXAM_C1000-112
|
VedDharkar
|
import numpy as np
# Importing standard Qiskit libraries
from qiskit import QuantumCircuit, transpile, Aer, IBMQ
from qiskit.tools.jupyter import *
from qiskit.visualization import *
from ibm_quantum_widgets import *
from qiskit import *
# Loading your IBM Q account(s)
#provider = IBMQ.load_account()
q = QuantumRegister(2)
c = ClassicalRegister(2)
qc = QuantumCircuit(q, c)
qc.h(q[0])
qc.cx(q[0], q[1])
qc.draw('mpl')
sim = Aer.get_backend('statevector_simulator')
qobj = assemble(qc)
final_state = sim.run(qobj).result().get_statevector()
plot_state_qsphere(final_state)
|
https://github.com/VedDharkar/IBM_QISKIT_EXAM_C1000-112
|
VedDharkar
|
import numpy as np
# Importing standard Qiskit libraries
from qiskit import QuantumCircuit, transpile, Aer, IBMQ
from qiskit.tools.jupyter import *
from qiskit.visualization import *
from ibm_quantum_widgets import *
from qiskit import *
# Loading your IBM Q account(s)
#provider = IBMQ.load_account()
q = QuantumRegister(2)
c = ClassicalRegister(2)
qc = QuantumCircuit(q, c)
qc.h(q[0])
qc.cx(q[0], q[1])
qc.draw('mpl')
sim = Aer.get_backend('statevector_simulator')
qobj = assemble(qc)
final_state = sim.run(qobj).result().get_statevector()
final_state
#BLOCH SPHERE
"""
THERE ARE 2 TYPES OF BLOCH SPHERE:-
1. plot_bloch_multivector
2.plot_bloch_vector
"""
plot_bloch_multivector(final_state, "Entanglement")
#FOR BLOCH_MULTIVECTOR YOU NEED A STATE
#FOR BLOCH_VECTOR YOU NEED COORDINATE POINTS
coords = [1, 1, 1]
plot_bloch_vector(coords, coord_type='cartesian')
#THERE IS ANOTHER COORD_TYPE THAT IS "SPHERICAL"
coords1 = [1, np.pi, np.pi]
plot_bloch_vector(coords1, coord_type='spherical')
|
https://github.com/VedDharkar/IBM_QISKIT_EXAM_C1000-112
|
VedDharkar
|
import numpy as np
# Importing standard Qiskit libraries
from qiskit import QuantumCircuit, transpile, Aer, IBMQ
from qiskit.tools.jupyter import *
from qiskit.visualization import *
from ibm_quantum_widgets import *
from qiskit import *
# Loading your IBM Q account(s)
#provider = IBMQ.load_account()
q = QuantumRegister(2)
c = ClassicalRegister(2)
qc = QuantumCircuit(q, c)
qc.h(q[0])
qc.x(q[0])
sim = Aer.get_backend('unitary_simulator')
job = execute(qc, sim)
unitary = job.result().get_unitary()
unitary
unitary = array_to_latex(unitary)
unitary
|
https://github.com/bagmk/Quantum_Machine_Learning_Express
|
bagmk
|
import random
from random import seed
from random import random
from numpy import where
from collections import Counter
from sklearn.datasets import make_blobs
from matplotlib import pyplot
import numpy as np
import matplotlib.pyplot as plt
from sklearn import mixture
from sklearn.neighbors import KernelDensity
import random
def my_circle(center, rx, ry, Nmax):
#This function generate the random number inside of the circle
#center is the location of the circle. input : [x,y]
# rx is the radius of the eplicipe in x-axis. input : rx
# ry is the radius of the eplicipe in y-axis. input : ry
# Total number of the data. input: Nmax
# Output will generate the data in array{[[x1,y1],[x2,y2]....[xn,yn]]}
x2=[]
y2=[]
for i in range(Nmax):
r2=np.sqrt(random.random())
theta2=2 * np.pi * random.random()
x2.append(rx*r2 * np.cos(theta2) + center[0])
y2.append(ry*r2 * np.sin(theta2) + center[1])
return np.transpose([x2,y2])
def my_plot(data,lab,counter):
#This function generate the plot of the labeled data
for label, _ in counter.items():
row_ix = where(lab == label)[0]
pyplot.scatter(data[row_ix, 0], data[row_ix, 1], label=str(label))
pyplot.legend()
pyplot.xlim([0, 1])
pyplot.ylim([0, 1])
pyplot.show()
#Seeding is defined inside of the function
#Those functions will generate dataset, and lableing and the number of the counters of each label.
#label are {0,1}, and they are equally divided into 1:1 ratio.
def data0test():
seed(30)
X1=my_circle([0.24,0.5],0.2,0.4,750)
X2=my_circle([0.76,0.5],0.2,0.4,750)
y1=[0] * 750
y2=[1] * 750
X_1=np.concatenate((X1,X2))
y_1=np.concatenate((y1, y2))
# Generate uniform noise
counter = Counter(y_1)
return X_1, y_1, counter
def data1a():
seed(30)
X1=my_circle([0.3,0.5],0.25,0.4,750)
X2=my_circle([0.7,0.5],0.25,0.4,750)
y1=[0] * 750
y2=[1] * 750
X_1=np.concatenate((X1,X2))
y_1=np.concatenate((y1, y2))
# Generate uniform noise
counter = Counter(y_1)
return X_1, y_1, counter
def data1b():
seed(30)
X1=my_circle([0.4,0.2],0.25,0.15,375)
X2=my_circle([0.6,0.5],0.25,0.15,750)
X3=my_circle([0.4,0.8],0.25,0.15,375)
y1=[0] * 375
y2=[1] * 750
y3=[0] * 375
X_1=np.concatenate((X1,X2,X3))
y_1=np.concatenate((y1, y2,y3))
# Generate uniform noise
counter = Counter(y_1)
return X_1, y_1, counter
def data1c():
seed(30)
X1=my_circle([0.3,0.2],0.25,0.12,375)
X2=my_circle([0.7,0.4],0.25,0.12,375)
X3=my_circle([0.3,0.6],0.25,0.12,375)
X4=my_circle([0.7,0.8],0.25,0.12,375)
y1=[0] * 375
y2=[1] * 375
y3=[0] * 375
y4=[1] * 375
X_1=np.concatenate((X1,X2,X3,X4))
y_1=np.concatenate((y1, y2,y3,y4))
# Generate uniform noise
counter = Counter(y_1)
return X_1, y_1, counter
def data2a():
seed(30)
X1=my_circle([0.25,0.25],0.2,0.2,375)
X2=my_circle([0.25,0.75],0.2,0.2,375)
X3=my_circle([0.75,0.75],0.2,0.2,375)
X4=my_circle([0.75,0.25],0.2,0.2,375)
y1=[0] * 375
y2=[1] * 375
y3=[0] * 375
y4=[1] * 375
X_1=np.concatenate((X1,X2,X3,X4))
y_1=np.concatenate((y1, y2,y3,y4))
# Generate uniform noise
counter = Counter(y_1)
return X_1, y_1, counter
def data2b():
seed(30)
r=0.12
n=166
X1=my_circle([0.2,0.2],r,r,n)
X2=my_circle([0.5,0.2],r,r,n)
X3=my_circle([0.8,0.2],r,r,n)
X4=my_circle([0.2,0.5],r,r,n)
X5=my_circle([0.5,0.5],r,r,n)
X6=my_circle([0.8,0.5],r,r,n)
X7=my_circle([0.2,0.8],r,r,n)
X8=my_circle([0.5,0.8],r,r,n)
X9=my_circle([0.8,0.8],r,r,n)
y1=[0] * n
y2=[1] * n
y3=[0] * n
y4=[1] * n
y5=[0] * n
y6=[1] * n
y7=[0] * n
y8=[1] * n
y9=[0] * n
X_1=np.concatenate((X1,X2,X3,X4,X5,X6,X7,X8,X9))
y_1=np.concatenate((y1, y2,y3,y4,y5,y6,y7,y8,y9))
# Generate uniform noise
counter = Counter(y_1)
return X_1, y_1, counter
def data2c():
seed(30)
r=0.1
n=93
X1=my_circle([0.15,0.15],r,r,n)
X2=my_circle([0.38,0.15],r,r,n)
X3=my_circle([0.62,0.15],r,r,n)
X4=my_circle([0.85,0.15],r,r,n)
X5=my_circle([0.15,0.38],r,r,n)
X6=my_circle([0.38,0.38],r,r,n)
X7=my_circle([0.62,0.38],r,r,n)
X8=my_circle([0.85,0.38],r,r,n)
X9=my_circle([0.15,0.62],r,r,n)
X10=my_circle([0.38,0.62],r,r,n)
X11=my_circle([0.62,0.62],r,r,n)
X12=my_circle([0.85,0.62],r,r,n)
X13=my_circle([0.15,0.85],r,r,n)
X14=my_circle([0.38,0.85],r,r,n)
X15=my_circle([0.62,0.85],r,r,n)
X16=my_circle([0.85,0.85],r,r,n)
y1=[0] * n
y2=[1] * n
y3=[0] * n
y4=[1] * n
y5=[1] * n
y6=[0] * n
y7=[1] * n
y8=[0] * n
y9=[0] * n
y10=[1] * n
y11=[0] * n
y12=[1] * n
y13=[1] * n
y14=[0] * n
y15=[1] * n
y16=[0] * n
X_1=np.concatenate((X1,X2,X3,X4,X5,X6,X7,X8,X9,X10,X11,X12,X13,X14,X15,X16))
y_1=np.concatenate((y1, y2,y3,y4,y5,y6,y7,y8,y9,y10,y11,y12,y13,y14,y15,y16))
# Generate uniform noise
counter = Counter(y_1)
return X_1, y_1, counter
def data3a():
seed(30)
X1 = []
radius = 0.25
n=750
index = 0
while index < n:
x=random.random()
y=random.random()
if (x-0.5)**2 + (y-0.5)**2 > radius**2:
X1 = X1 + [[x,y]]
index = index + 1
y1=[1] *750
X2=my_circle([0.5,0.5],radius,radius,750)
y2=[0] *750
X_1=np.concatenate((X1,X2))
y_1=np.concatenate((y1, y2))
# Generate uniform noise
counter = Counter(y_1)
# Generate uniform noise
counter = Counter(y_1)
return X_1, y_1, counter
def data3b():
seed(30)
X1 = []
radius = 0.15
n=750
index = 0
while index < n:
x=random.random()
y=random.random()
if ((x-0.25)**2 + (y-0.25)**2 > radius**2 and (x-0.75)**2 + (y-0.75)**2 > radius**2):
X1 = X1 + [[x,y]]
index = index + 1
y1=[1] *750
X2=my_circle([0.25,0.25],radius,radius,375)
X3=my_circle([0.75,0.75],radius,radius,375)
y2=[0] *750
X_1=np.concatenate((X1,X2,X3))
y_1=np.concatenate((y1, y2))
# Generate uniform noise
counter = Counter(y_1)
return X_1, y_1, counter
def data3c():
seed(30)
X1 = []
radius = 0.15
n=750
n2=187
index = 0
while index < n:
x=random.random()
y=random.random()
if ((x-0.25)**2 + (y-0.25)**2 > radius**2 and (x-0.75)**2 + (y-0.75)**2 > radius**2 and (x-0.75)**2 + (y-0.25)**2 > radius**2 and (x-0.25)**2 + (y-0.75)**2 > radius**2 ):
X1 = X1 + [[x,y]]
index = index + 1
y1=[1] *748
X2=my_circle([0.25,0.25],radius,radius,n2)
X3=my_circle([0.75,0.75],radius,radius,n2)
X4=my_circle([0.75,0.25],radius,radius,n2)
X5=my_circle([0.25,0.75],radius,radius,n2)
y2=[0] *748
X_1=np.concatenate((X1,X2,X3,X4,X5))
y_1=np.concatenate((y1, y2))
# Generate uniform noise
counter = Counter(y_1)
# Generate uniform noise
counter = Counter(y_1)
return X_1, y_1, counter
# Plot
my_plot(data1a()[0],data1a()[1],data1a()[2])
# Plot
my_plot(data0test()[0],data0test()[1],data0test()[2])
# Plot
my_plot(data1a()[0],data1a()[1],data1a()[2])
# Plot
my_plot(data1b()[0],data1b()[1],data1b()[2])
# Plot
my_plot(data1c()[0],data1c()[1],data1c()[2])
# Plot
my_plot(data2a()[0],data2a()[1],data2a()[2])
# Plot
my_plot(data2b()[0],data2b()[1],data2b()[2])
# Plot
my_plot(data2c()[0],data2c()[1],data2c()[2])
# Plot
my_plot(data3a()[0],data3a()[1],data3a()[2])
# Plot
my_plot(data3b()[0],data3b()[1],data3b()[2])
# Plot
my_plot(data3c()[0],data3c()[1],data3c()[2])
print(data1a()[2])
print(data1b()[2])
print(data1c()[2])
print(data2a()[2])
print(data2b()[2])
print(data2c()[2])
print(data3a()[2])
print(data3b()[2])
print(data3c()[2])
import sys
import numpy
numpy.set_printoptions(threshold=sys.maxsize)
np.savetxt("data0test.txt",data0test()[0],fmt='%.2f')
np.savetxt("data0testlabel.txt",data0test()[1],fmt='%.2f')
import sys
import numpy
numpy.set_printoptions(threshold=sys.maxsize)
np.savetxt("data1a.txt",data1a()[0],fmt='%.2f')
np.savetxt("data1b.txt",data1b()[0],fmt='%.2f')
np.savetxt("data1c.txt",data1c()[0],fmt='%.2f')
np.savetxt("data2a.txt",data2a()[0],fmt='%.2f')
np.savetxt("data2b.txt",data2b()[0],fmt='%.2f')
np.savetxt("data2c.txt",data2c()[0],fmt='%.2f')
np.savetxt("data3a.txt",data3a()[0],fmt='%.2f')
np.savetxt("data3b.txt",data3b()[0],fmt='%.2f')
np.savetxt("data3c.txt",data3c()[0],fmt='%.2f')
np.savetxt("data1alabel.txt",data1a()[1],fmt='%.2f')
np.savetxt("data1blabel.txt",data1b()[1],fmt='%.2f')
np.savetxt("data1clabel.txt",data1c()[1],fmt='%.2f')
np.savetxt("data2alabel.txt",data2a()[1],fmt='%.2f')
np.savetxt("data2blabel.txt",data2b()[1],fmt='%.2f')
np.savetxt("data2clabel.txt",data2c()[1],fmt='%.2f')
np.savetxt("data3alabel.txt",data3a()[1],fmt='%.2f')
np.savetxt("data3blabel.txt",data3b()[1],fmt='%.2f')
np.savetxt("data3clabel.txt",data3c()[1],fmt='%.2f')
import sys
import numpy
numpy.set_printoptions(threshold=sys.maxsize)
np.savetxt("data1a.txt",data1a()[0],fmt='%.2f')
np.savetxt("data1b.txt",data1b()[0],fmt='%.2f')
np.savetxt("data1c.txt",data1c()[0],fmt='%.2f')
np.savetxt("data2a.txt",data2a()[0],fmt='%.2f')
np.savetxt("data2b.txt",data2b()[0],fmt='%.2f')
np.savetxt("data2c.txt",data2c()[0],fmt='%.2f')
np.savetxt("data3a.txt",data3a()[0],fmt='%.2f')
np.savetxt("data3b.txt",data3b()[0],fmt='%.2f')
np.savetxt("data3c.txt",data3c()[0],fmt='%.2f')
np.savetxt("data1alabel.txt",data1a()[1],fmt='%.2f')
np.savetxt("data1blabel.txt",data1b()[1],fmt='%.2f')
np.savetxt("data1clabel.txt",data1c()[1],fmt='%.2f')
np.savetxt("data2alabel.txt",data2a()[1],fmt='%.2f')
np.savetxt("data2blabel.txt",data2b()[1],fmt='%.2f')
np.savetxt("data2clabel.txt",data2c()[1],fmt='%.2f')
np.savetxt("data3alabel.txt",data3a()[1],fmt='%.2f')
np.savetxt("data3blabel.txt",data3b()[1],fmt='%.2f')
np.savetxt("data3clabel.txt",data3c()[1],fmt='%.2f')
import sys
import numpy
numpy.set_printoptions(threshold=sys.maxsize)
def readfile(name):
f = open (name , 'r')
l = []
l = [line.split() for line in f]
l = np.array(l)
return l
data1a = readfile("data1a.txt")
data1alabel = readfile("data1alabel.txt")
data1alabel[0]
data[0]
f = eval(open('data1a.txt').read().
array = np.array
|
https://github.com/bagmk/Quantum_Machine_Learning_Express
|
bagmk
|
import random
from random import seed
from random import random
from numpy import where
from collections import Counter
from sklearn.datasets import make_blobs
from matplotlib import pyplot
import numpy as np
import matplotlib.pyplot as plt
from sklearn import mixture
from sklearn.neighbors import KernelDensity
import random
def my_circle(center, rx, ry, Nmax):
R = 1
x2=[]
y2=[]
for i in range(Nmax):
r2=np.sqrt(random.random())
theta2=2 * np.pi * random.random()
x2.append(rx*r2 * np.cos(theta2) + center[0])
y2.append(ry*r2 * np.sin(theta2) + center[1])
return np.transpose([x2,y2])
def my_plot(data,lab,counter):
for label, _ in counter.items():
row_ix = where(lab == label)[0]
pyplot.scatter(data[row_ix, 0], data[row_ix, 1], label=str(label))
pyplot.legend()
pyplot.xlim([0, 1])
pyplot.ylim([0, 1])
pyplot.show()
def data1a():
seed(30)
X1=my_circle([0.3,0.5],0.25,0.4,750)
X2=my_circle([0.7,0.5],0.25,0.4,750)
y1=[0] * 750
y2=[1] * 750
X_1=np.concatenate((X1,X2))
y_1=np.concatenate((y1, y2))
# Generate uniform noise
counter = Counter(y_1)
return X_1, y_1, counter
def data1b():
seed(30)
X1=my_circle([0.4,0.2],0.25,0.15,375)
X2=my_circle([0.6,0.5],0.25,0.15,750)
X3=my_circle([0.4,0.8],0.25,0.15,375)
y1=[0] * 375
y2=[1] * 750
y3=[0] * 375
X_1=np.concatenate((X1,X2,X3))
y_1=np.concatenate((y1, y2,y3))
# Generate uniform noise
counter = Counter(y_1)
return X_1, y_1, counter
def data1c():
seed(30)
X1=my_circle([0.3,0.2],0.25,0.12,375)
X2=my_circle([0.7,0.4],0.25,0.12,375)
X3=my_circle([0.3,0.6],0.25,0.12,375)
X4=my_circle([0.7,0.8],0.25,0.12,375)
y1=[0] * 375
y2=[1] * 375
y3=[0] * 375
y4=[1] * 375
X_1=np.concatenate((X1,X2,X3,X4))
y_1=np.concatenate((y1, y2,y3,y4))
# Generate uniform noise
counter = Counter(y_1)
return X_1, y_1, counter
def data2a():
seed(30)
X1=my_circle([0.25,0.25],0.2,0.2,375)
X2=my_circle([0.25,0.75],0.2,0.2,375)
X3=my_circle([0.75,0.75],0.2,0.2,375)
X4=my_circle([0.75,0.25],0.2,0.2,375)
y1=[0] * 375
y2=[1] * 375
y3=[0] * 375
y4=[1] * 375
X_1=np.concatenate((X1,X2,X3,X4))
y_1=np.concatenate((y1, y2,y3,y4))
# Generate uniform noise
counter = Counter(y_1)
return X_1, y_1, counter
def data2b():
seed(30)
r=0.12
n=166
X1=my_circle([0.2,0.2],r,r,n)
X2=my_circle([0.5,0.2],r,r,n)
X3=my_circle([0.8,0.2],r,r,n)
X4=my_circle([0.2,0.5],r,r,n)
X5=my_circle([0.5,0.5],r,r,n)
X6=my_circle([0.8,0.5],r,r,n)
X7=my_circle([0.2,0.8],r,r,n)
X8=my_circle([0.5,0.8],r,r,n)
X9=my_circle([0.8,0.8],r,r,n)
y1=[0] * n
y2=[1] * n
y3=[0] * n
y4=[1] * n
y5=[0] * n
y6=[1] * n
y7=[0] * n
y8=[1] * n
y9=[0] * n
X_1=np.concatenate((X1,X2,X3,X4,X5,X6,X7,X8,X9))
y_1=np.concatenate((y1, y2,y3,y4,y5,y6,y7,y8,y9))
# Generate uniform noise
counter = Counter(y_1)
return X_1, y_1, counter
def data2c():
seed(30)
r=0.1
n=93
X1=my_circle([0.15,0.15],r,r,n)
X2=my_circle([0.38,0.15],r,r,n)
X3=my_circle([0.62,0.15],r,r,n)
X4=my_circle([0.85,0.15],r,r,n)
X5=my_circle([0.15,0.38],r,r,n)
X6=my_circle([0.38,0.38],r,r,n)
X7=my_circle([0.62,0.38],r,r,n)
X8=my_circle([0.85,0.38],r,r,n)
X9=my_circle([0.15,0.62],r,r,n)
X10=my_circle([0.38,0.62],r,r,n)
X11=my_circle([0.62,0.62],r,r,n)
X12=my_circle([0.85,0.62],r,r,n)
X13=my_circle([0.15,0.85],r,r,n)
X14=my_circle([0.38,0.85],r,r,n)
X15=my_circle([0.62,0.85],r,r,n)
X16=my_circle([0.85,0.85],r,r,n)
y1=[0] * n
y2=[1] * n
y3=[0] * n
y4=[1] * n
y5=[1] * n
y6=[0] * n
y7=[1] * n
y8=[0] * n
y9=[0] * n
y10=[1] * n
y11=[0] * n
y12=[1] * n
y13=[1] * n
y14=[0] * n
y15=[1] * n
y16=[0] * n
X_1=np.concatenate((X1,X2,X3,X4,X5,X6,X7,X8,X9,X10,X11,X12,X13,X14,X15,X16))
y_1=np.concatenate((y1, y2,y3,y4,y5,y6,y7,y8,y9,y10,y11,y12,y13,y14,y15,y16))
# Generate uniform noise
counter = Counter(y_1)
return X_1, y_1, counter
def data3a():
seed(30)
X1 = []
radius = 0.25
n=750
index = 0
while index < n:
x=random.random()
y=random.random()
if (x-0.5)**2 + (y-0.5)**2 > radius**2:
X1 = X1 + [[x,y]]
index = index + 1
y1=[1] *750
X2=my_circle([0.5,0.5],radius,radius,750)
y2=[0] *750
X_1=np.concatenate((X1,X2))
y_1=np.concatenate((y1, y2))
# Generate uniform noise
counter = Counter(y_1)
# Generate uniform noise
counter = Counter(y_1)
return X_1, y_1, counter
def data3b():
seed(30)
X1 = []
radius = 0.15
n=750
index = 0
while index < n:
x=random.random()
y=random.random()
if ((x-0.25)**2 + (y-0.25)**2 > radius**2 and (x-0.75)**2 + (y-0.75)**2 > radius**2):
X1 = X1 + [[x,y]]
index = index + 1
y1=[1] *750
X2=my_circle([0.25,0.25],radius,radius,375)
X3=my_circle([0.75,0.75],radius,radius,375)
y2=[0] *750
X_1=np.concatenate((X1,X2,X3))
y_1=np.concatenate((y1, y2))
# Generate uniform noise
counter = Counter(y_1)
return X_1, y_1, counter
def data3c():
seed(30)
X1 = []
radius = 0.15
n=750
n2=187
index = 0
while index < n:
x=random.random()
y=random.random()
if ((x-0.25)**2 + (y-0.25)**2 > radius**2 and (x-0.75)**2 + (y-0.75)**2 > radius**2 and (x-0.75)**2 + (y-0.25)**2 > radius**2 and (x-0.25)**2 + (y-0.75)**2 > radius**2 ):
X1 = X1 + [[x,y]]
index = index + 1
y1=[1] *750
X2=my_circle([0.25,0.25],radius,radius,n2)
X3=my_circle([0.75,0.75],radius,radius,n2)
X4=my_circle([0.75,0.25],radius,radius,n2)
X5=my_circle([0.25,0.75],radius,radius,n2)
y2=[0] *748
X_1=np.concatenate((X1,X2,X3,X4,X5))
y_1=np.concatenate((y1, y2))
# Generate uniform noise
counter = Counter(y_1)
# Generate uniform noise
counter = Counter(y_1)
return X_1, y_1, counter
# Plot
my_plot(data1a()[0],data1a()[1],data1a()[2])
# Plot
my_plot(data1b()[0],data1b()[1],data1b()[2])
# Plot
my_plot(data1c()[0],data1c()[1],data1c()[2])
# Plot
my_plot(data2a()[0],data2a()[1],data2a()[2])
# Plot
my_plot(data2b()[0],data2b()[1],data2b()[2])
# Plot
my_plot(data2c()[0],data2c()[1],data2c()[2])
# Plot
my_plot(data3a()[0],data3a()[1],data3a()[2])
# Plot
my_plot(data3b()[0],data3b()[1],data3b()[2])
# Plot
my_plot(data3c()[0],data3c()[1],data3c()[2])
|
https://github.com/bagmk/Quantum_Machine_Learning_Express
|
bagmk
|
from qiskit import *
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit import IBMQ, Aer, execute,assemble,QuantumCircuit
from qiskit.visualization import plot_histogram, plot_bloch_vector, plot_bloch_multivector
from qiskit.quantum_info import Statevector
from qiskit.extensions import *
from qiskit.quantum_info import random_unitary
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
import math
from math import pi, sqrt
from scipy.special import rel_entr
from random import seed
from random import random
import cmath
import os
from qiskit.circuit import Parameter
import sys
sys.path.append('../Pyfiles')
from circuits import *
#Possible Bin
bins_list=[];
for i in range(76):
bins_list.append((i)/75)
#Center of the Bean
bins_x=[]
for i in range(75):
bins_x.append(bins_list[1]+bins_list[i])
def P_harr(l,u,N):
return (1-l)**(N-1)-(1-u)**(N-1)
#Harr historgram
P_harr_hist=[]
for i in range(75):
P_harr_hist.append(P_harr(bins_list[i],bins_list[i+1],16))
#Imaginary
j=(-1)**(1/2)
backend = Aer.get_backend('qasm_simulator')
nshot=1000
nparam=2000
fidelity=[]
for x in range(nparam):
qr = QuantumRegister(4)
cr = ClassicalRegister(4)
qc = QuantumCircuit(qr, cr)
theta=[];
for y in range(80):
theta.append(2*pi*random())
qc=circuit9(qc,qr,theta,3,1)
qc.measure(qr[:],cr[:])
job = execute(qc, backend, shots=nshot)
result = job.result()
count =result.get_counts()
if '0000' in count and '1' in count:
ratio=count['0000']/nshot
elif '0000' in count and '1' not in count:
ratio=count['0000']/nshot
else:
ratio=0
fidelity.append(ratio)
weights = np.ones_like(fidelity)/float(len(fidelity))
plt.hist(fidelity, bins=bins_list, weights=weights, range=[0, 1], label='Circuit 1')
plt.plot(bins_x, P_harr_hist, label='Harr')
plt.legend(loc='upper right')
plt.show()
# example of calculating the kl divergence (relative entropy) with scipy
P_1_hist=np.histogram(fidelity, bins=bins_list, weights=weights, range=[0, 1])[0]
kl_pq = rel_entr(P_1_hist, P_harr_hist)
print('KL(P || Q): %.3f nats' % sum(kl_pq))
list_of_circuit = [circuit1,circuit2,circuit3,circuit4,circuit5,circuit6,circuit7,circuit8,circuit9,circuit10,circuit11,circuit12,circuit13,circuit14,circuit15,circuit16,circuit17,circuit18,circuit19]
backend = Aer.get_backend('qasm_simulator')
arr = []
for kk in range(19):
arr.append([])
for lo in [1,2,3,4,5]:
nshot=1000
nparam=2000
fidelity=[]
for x in range(nparam):
qr = QuantumRegister(4)
cr = ClassicalRegister(4)
qc = QuantumCircuit(qr, cr)
theta=[];
for y in range(500):
theta.append(2*pi*random())
qc=list_of_circuit[kk](qc,qr,theta,lo,1)
qc.measure(qr[:],cr[:])
job = execute(qc, backend, shots=nshot)
result = job.result()
count =result.get_counts()
if '0000' in count and '1' in count:
ratio=count['0000']/nshot
elif '0000' in count and '1' not in count:
ratio=count['0000']/nshot
else:
ratio=0
fidelity.append(ratio)
weights = np.ones_like(fidelity)/float(len(fidelity))
# example of calculating the kl divergence (relative entropy) with scipy
P_hist=np.histogram(fidelity, bins=bins_list, weights=weights, range=[0, 1])[0]
kl_pq = rel_entr(P_hist, P_harr_hist)
arr[kk].append(sum(kl_pq))
print(kk,'cir',lo,'lay')
import sys
import numpy
numpy.set_printoptions(threshold=sys.maxsize)
np.savetxt("express_nshot1000_nparam2000.txt",express)
express
import pandas as pd
import matplotlib.pyplot as plt
#loading dataset
x = [i+1 for i in range(19)]
y = [i[0] for i in arr]
plt.plot(x, y, 'o', color='red', label='L=1');
x = [i+1 for i in range(19)]
y = [i[1] for i in arr]
plt.plot(x, y, 'o', color='blue', label='L=2');
x = [i+1 for i in range(19)]
y = [i[2] for i in arr]
plt.plot(x, y, 'o', color='black', label='L=3');
x = [i+1 for i in range(19)]
y = [i[3] for i in arr]
plt.plot(x, y, 'o', color='green', label='L=4');
x = [i+1 for i in range(19)]
y = [i[3] for i in arr]
plt.plot(x, y, 'o', color='purple', label='L=5');
plt.legend(loc='upper right')
plt.yscale('log',base=10)
plt.xlabel('Circuit ID')
plt.ylabel('Expressibility')
# Create names on the x axis
plt.xticks([i+1 for i in range(19)])
plt.show()
x = [str(i+1) for i in range(19)]
x_ticks_labels = ['9','1','2','16','3','18','10','12','15','17','4','11','7','8','19','5','13','14','6']
xarr = np.array(x)
ind = np.where(xarr.reshape(xarr.size, 1) == np.array(x_ticks_labels))[1]
fig, ax = plt.subplots(1,1)
y = [i[0] for i in arr]
ax.scatter(ind,y, marker="o", color='red', label='L=1')
y = [i[1] for i in arr]
ax.scatter(ind,y, marker="o", color='blue', label='L=2')
y = [i[2] for i in arr]
ax.scatter(ind,y, marker="o", color='black', label='L=3')
y = [i[3] for i in arr]
ax.scatter(ind,y, marker="o", color='green', label='L=4')
y = [i[4] for i in arr]
ax.scatter(ind,y, marker="o", color='purple', label='L=5')
ax.set_yscale('log',base=10)
ax.set_xlabel('Circuit ID')
ax.set_ylabel('Expressibility')
ax.legend(loc='upper right')
ax.set_xticks(range(len(x_ticks_labels)))
ax.set_xticklabels(x_ticks_labels)
plt.show()
fig
from matplotlib import pyplot as plt
fig.savefig('express_nshot1000_nparam2000.png')
list_of_circuit = [circuit1,circuit2,circuit3,circuit4,circuit5,circuit6,circuit7,circuit8,circuit9,circuit10,circuit11,circuit12,circuit13,circuit14,circuit15,circuit16,circuit17,circuit18,circuit19]
backend = Aer.get_backend('qasm_simulator')
arr = []
for kk in range(19):
arr.append([])
for lo in [1,2,3,4,5]:
nshot=10000
nparam=1000
fidelity=[]
for x in range(nparam):
qr = QuantumRegister(4)
cr = ClassicalRegister(4)
qc = QuantumCircuit(qr, cr)
theta=[];
for y in range(500):
theta.append(2*pi*random())
qc=list_of_circuit[kk](qc,qr,theta,lo,1)
qc.measure(qr[:],cr[:])
job = execute(qc, backend, shots=nshot)
result = job.result()
count =result.get_counts()
if '0000' in count and '1' in count:
ratio=count['0000']/nshot
elif '0000' in count and '1' not in count:
ratio=count['0000']/nshot
else:
ratio=0
fidelity.append(ratio)
weights = np.ones_like(fidelity)/float(len(fidelity))
# example of calculating the kl divergence (relative entropy) with scipy
P_hist=np.histogram(fidelity, bins=bins_list, weights=weights, range=[0, 1])[0]
kl_pq = rel_entr(P_hist, P_harr_hist)
arr[kk].append(sum(kl_pq))
print(kk,'cir',lo,'lay')
express
express=[[0.32952413239340933,
0.2160076560690873,
0.21764729834615873,
0.2473835588095912,
0.24225112795339898],
[0.32696068662224353,
0.02882892743034554,
0.016267808316341933,
0.011239533562489743,
0.014454756871595335],
[0.2724963267277256,
0.09297432646189611,
0.05316589878004338,
0.015713919742898073,
0.024985709696968308],
[0.13368059415831227,
0.04064900653499141,
0.010705050297397748,
0.013853567790054458,
0.005871642903255154],
[0.06736311068291166,
0.018156334236215592,
0.01063201904450228,
0.013316433532184285,
0.007592151156475834],
[0.009458920213652083,
0.008379672440371308,
0.010342492342456355,
0.006491253689230598,
0.006360265144835441],
[0.11252639719416441,
0.048734485611284246,
0.02917920621977864,
0.021220914498718095,
0.011322409296335365],
[0.07799698630987113,
0.03461538963835257,
0.02645406983833787,
0.009609047546796293,
0.010314541867701806],
[0.7416977310427298,
0.4023390066678401,
0.04364507668153466,
0.0120927672656568,
0.01312193911083145],
[0.2568922048986469,
0.159877856023638,
0.14981483475374258,
0.11517099082521957,
0.14284391643493405],
[0.15798258034579774,
0.015098001400060396,
0.011383645396280426,
0.010105335417854225,
0.005632643410627778],
[0.19446925387256803,
0.031175656437504834,
0.02084429521271306,
0.01343313112097519,
0.00768059915246622],
[0.09061768972578448,
0.011526900417017642,
0.008189880893093129,
0.0060108893015350506,
0.011751397567911099],
[0.018799262840916854,
0.007136143406884642,
0.007623092145230341,
0.009053624288535378,
0.007663290417292582],
[0.19746628980579164,
0.15281958598891646,
0.1355063400118548,
0.15111662634669093,
0.11741954724324753],
[0.2684937151020319,
0.09697128618178347,
0.05370640870529413,
0.032238736633842385,
0.023082433062011888],
[0.14026071817411356,
0.047939490546422714,
0.021117783500337883,
0.015818882293649358,
0.008967458429476547],
[0.21391972052843847,
0.07307155307919132,
0.02627846142683268,
0.020869197694583997,
0.010954254599580318],
[0.07137805144811141,
0.01173518527289049,
0.014645535174778783,
0.008417810099715662,
0.006455244968957593]]
import sys
import numpy
numpy.set_printoptions(threshold=sys.maxsize)
np.savetxt("express_nshot10000_nparam1000.txt",express)
x = [str(i+1) for i in range(19)]
x_ticks_labels = ['9','1','2','16','3','18','10','12','15','17','4','11','7','8','19','5','13','14','6']
xarr = np.array(x)
ind = np.where(xarr.reshape(xarr.size, 1) == np.array(x_ticks_labels))[1]
fig, ax = plt.subplots(1,1)
y = [i[0] for i in arr]
ax.scatter(ind,y, marker="o", color='red', label='L=1')
y = [i[1] for i in arr]
ax.scatter(ind,y, marker="o", color='blue', label='L=2')
y = [i[2] for i in arr]
ax.scatter(ind,y, marker="o", color='black', label='L=3')
y = [i[3] for i in arr]
ax.scatter(ind,y, marker="o", color='green', label='L=4')
y = [i[4] for i in arr]
ax.scatter(ind,y, marker="o", color='purple', label='L=5')
ax.set_yscale('log',base=10)
ax.set_xlabel('Circuit ID')
ax.set_ylabel('Expressibility')
ax.legend(loc='upper right')
ax.set_xticks(range(len(x_ticks_labels)))
ax.set_xticklabels(x_ticks_labels)
plt.show()
plt.plot(express[12], marker="o")
plt.ylim(0,0.1)
plt.plot(express[14], marker="o")
plt.ylim(0,0.21)
from matplotlib import pyplot as plt
fig.savefig('express_nshot10000_nparam1000.png')
|
https://github.com/bagmk/Quantum_Machine_Learning_Express
|
bagmk
|
from matplotlib import pyplot
from qiskit import *
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit import IBMQ, Aer, execute,assemble,QuantumCircuit, aqua
from qiskit.visualization import plot_histogram, plot_bloch_vector, plot_bloch_multivector
from qiskit.quantum_info import Statevector
from qiskit.extensions import *
provider = IBMQ.load_account()
from qiskit.quantum_info import random_unitary
from qiskit.providers.aer import QasmSimulator, StatevectorSimulator, UnitarySimulator
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
import math
from math import pi, sqrt
from scipy.special import rel_entr
from random import seed
from random import random
import cmath
import sys
sys.path.append('../Pyfiles')
from circuits import *
#Possible Bin
bins_list=[];
for i in range(76):
bins_list.append((i)/75)
#Center of the Bean
bins_x=[]
for i in range(75):
bins_x.append(bins_list[1]+bins_list[i])
def P_harr(l,u,N):
return (1-l)**(N-1)-(1-u)**(N-1)
#Harr historgram
P_harr_hist=[]
for i in range(75):
P_harr_hist.append(P_harr(bins_list[i],bins_list[i+1],2))
#Imaginary
j=(-1)**(1/2)
from qiskit import IBMQ
IBMQ.load_account()
provider = IBMQ.get_provider(hub='ibm-q')
provider.backends()
backend = 'ibmq_valencia'# you may choice here a different backend
fidelity_dic = {'ibmq_athens': 0.925110, 'ibmq_valencia': 0.809101, 'ibmq_ourense': 0.802380,
"ibmqx2": 0.627392, 'ibmq_santiago': 0.919399, 'ibmq_vigo': 0.908840, 'ideal_device': 1.0}
QV_dic = {'ibmq_athens': 32.0, 'ibmq_valencia': 16.0, 'ibmq_ourense': 8.0,
"ibmqx2": 8.0, 'ibmq_santiago': 32.0, 'ibmq_vigo': 16.0, 'ideal_device': np.inf}
dev_dic = {'ibmq_santiago': "San",'ibmq_athens': "Ath", 'ibmq_valencia': "Val", 'ibmq_vigo': 'Vig','ibmq_ourense': "Our",
"ibmqx2": 'Yor', 'ideal_device': "Ide"}
backend = provider.get_backend('ibmq_vigo')
for x in range(1,20,1):
print()
arr = []
for nsh in range(1,20,1):
arr.append([])
for lp in range(1,10,1):
nshot=int(round(1000*(nsh)**1.5,0))
nparam=1000*lp
fidelity=[]
for x in range(nparam):
qr = QuantumRegister(1)
cr = ClassicalRegister(1)
qc = QuantumCircuit(qr, cr)
u13=UnitaryGate(random_unitary(2))
qc.append(u13, [qr[0]] )
u13=UnitaryGate(random_unitary(2))
qc.append(u13, [qr[0]] )
qc.measure(qr[0],cr[0])
job = execute(qc, backend, shots=nshot)
result = job.result()
count =result.get_counts()
if '0' in count and '1' in count:
ratio=count['0']/nshot
elif '0' in count and '1' not in count:
ratio=count['0']/nshot
else:
ratio=0
fidelity.append(ratio)
#Kullback Leibler divergence
weights = np.ones_like(fidelity)/float(len(fidelity))
P_U_hist=np.histogram(fidelity, bins=bins_list, weights=weights, range=[0, 1])[0];
#Kullback Leibler divergence
print(nshot,'shots per simulation',nparam,'distribution size')
arr[nsh-1].append(sum(rel_entr(P_U_hist, P_harr_hist)))
import sys
import numpy
qasm=arr
numpy.set_printoptions(threshold=sys.maxsize)
np.savetxt("KLDivg_qasm.txt",qasm,fmt='%.2f')
import random
for nsh in range(1,20,1):
print(int(round(1000*(nsh)**1.5,0)))
backend = Aer.get_backend('statevector_simulator')
for x in range(1,20,1):
print()
arr = []
for nsh in range(1,20,1):
arr.append([])
for lp in range(1,10,1):
nshot=int(round(1000*(nsh)**1.5,0))
nparam=1000*lp
fidelity=[]
for x in range(nparam):
qr = QuantumRegister(1)
cr = ClassicalRegister(1)
qc = QuantumCircuit(qr, cr)
u13=UnitaryGate(random_unitary(2))
qc.append(u13, [qr[0]] )
u13=UnitaryGate(random_unitary(2))
qc.append(u13, [qr[0]] )
qc.measure(qr[0],cr[0])
job = execute(qc, backend, shots=nshot)
result = job.result()
count =result.get_counts()
if '0' in count and '1' in count:
ratio=count['0']/nshot
elif '0' in count and '1' not in count:
ratio=count['0']/nshot
else:
ratio=0
fidelity.append(ratio)
#Kullback Leibler divergence
weights = np.ones_like(fidelity)/float(len(fidelity))
P_U_hist=np.histogram(fidelity, bins=bins_list, weights=weights, range=[0, 1])[0];
#Kullback Leibler divergence
print(nshot,'shots per simulation',nparam,'distribution size')
arr[nsh-1].append(sum(rel_entr(P_U_hist, P_harr_hist)))
import sys
import numpy
statevector=arr
numpy.set_printoptions(threshold=sys.maxsize)
np.savetxt("KLDivg_statevector.txt",statevector,fmt='%.2f')
##Plot
import pandas as pd
import matplotlib.pyplot as plt
#loading dataset
x = [i+1 for i in range(19)]
y = [i[0] for i in arr]
plt.plot(x, y, 'o', color='red', label='L=1');
x = [i+1 for i in range(19)]
y = [i[1] for i in arr]
plt.plot(x, y, 'o', color='blue', label='L=2');
x = [i+1 for i in range(19)]
y = [i[2] for i in arr]
plt.plot(x, y, 'o', color='black', label='L=3');
x = [i+1 for i in range(19)]
y = [i[3] for i in arr]
plt.plot(x, y, 'o', color='green', label='L=4');
x = [i+1 for i in range(19)]
y = [i[3] for i in arr]
plt.plot(x, y, 'o', color='purple', label='L=5');
plt.legend(loc='upper right')
plt.yscale('log',base=10)
plt.xlabel('Circuit ID')
plt.ylabel('Expressibility')
# Create names on the x axis
plt.xticks([i+1 for i in range(19)])
plt.show()
|
https://github.com/bagmk/Quantum_Machine_Learning_Express
|
bagmk
|
from matplotlib import pyplot
from qiskit import *
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit import IBMQ, Aer, execute,assemble,QuantumCircuit, aqua
from qiskit.visualization import plot_histogram, plot_bloch_vector, plot_bloch_multivector
from qiskit.quantum_info import Statevector
from qiskit.extensions import *
provider = IBMQ.load_account()
from qiskit.quantum_info import random_unitary
from qiskit.providers.aer import QasmSimulator, StatevectorSimulator, UnitarySimulator
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
import math
from math import pi, sqrt
from scipy.special import rel_entr
from random import seed
from random import random
import cmath
import sys
sys.path.append('../Pyfiles')
from circuits import *
#Possible Bin
bins_list=[];
for i in range(76):
bins_list.append((i)/75)
#Center of the Bean
bins_x=[]
for i in range(75):
bins_x.append(bins_list[1]+bins_list[i])
def P_harr(l,u,N):
return (1-l)**(N-1)-(1-u)**(N-1)
#Harr historgram
P_harr_hist=[]
for i in range(75):
P_harr_hist.append(P_harr(bins_list[i],bins_list[i+1],2))
#Imaginary
j=(-1)**(1/2)
backend = Aer.get_backend('qasm_simulator')
for x in range(1,20,1):
print()
arr = []
for nsh in range(1,20,1):
arr.append([])
for lp in range(1,10,1):
nshot=int(round(1000*(nsh)**1.5,0))
nparam=1000*lp
fidelity=[]
for x in range(nparam):
qr = QuantumRegister(1)
cr = ClassicalRegister(1)
qc = QuantumCircuit(qr, cr)
u13=UnitaryGate(random_unitary(2))
qc.append(u13, [qr[0]] )
u13=UnitaryGate(random_unitary(2))
qc.append(u13, [qr[0]] )
qc.measure(qr[0],cr[0])
job = execute(qc, backend, shots=nshot)
result = job.result()
count =result.get_counts()
if '0' in count and '1' in count:
ratio=count['0']/nshot
elif '0' in count and '1' not in count:
ratio=count['0']/nshot
else:
ratio=0
fidelity.append(ratio)
#Kullback Leibler divergence
weights = np.ones_like(fidelity)/float(len(fidelity))
P_U_hist=np.histogram(fidelity, bins=bins_list, weights=weights, range=[0, 1])[0];
#Kullback Leibler divergence
print(nshot,'shots per simulation',nparam,'distribution size')
arr[nsh-1].append(sum(rel_entr(P_U_hist, P_harr_hist)))
import sys
import numpy
numpy.set_printoptions(threshold=sys.maxsize)
np.savetxt("KLDivg_qasm.txt",qasm)
qasm
backend = QasmSimulator(method='density_matrix')
for x in range(1,20,1):
print()
arr = []
for nsh in range(1,20,1):
arr.append([])
for lp in range(1,10,1):
nshot=int(round(1000*(nsh)**1.5,0))
nparam=1000*lp
fidelity=[]
for x in range(nparam):
qr = QuantumRegister(1)
cr = ClassicalRegister(1)
qc = QuantumCircuit(qr, cr)
u13=UnitaryGate(random_unitary(2))
qc.append(u13, [qr[0]] )
u13=UnitaryGate(random_unitary(2))
qc.append(u13, [qr[0]] )
qc.measure(qr[0],cr[0])
job = execute(qc, backend, shots=nshot)
result = job.result()
count =result.get_counts()
if '0' in count and '1' in count:
ratio=count['0']/nshot
elif '0' in count and '1' not in count:
ratio=count['0']/nshot
else:
ratio=0
fidelity.append(ratio)
#Kullback Leibler divergence
weights = np.ones_like(fidelity)/float(len(fidelity))
P_U_hist=np.histogram(fidelity, bins=bins_list, weights=weights, range=[0, 1])[0];
#Kullback Leibler divergence
arr[nsh-1].append(sum(rel_entr(P_U_hist, P_harr_hist)))
print(nshot,'shots per simulation',nparam,'distribution size KL=',sum(rel_entr(P_U_hist, P_harr_hist)))
import sys
import numpy
density_mat=arr
numpy.set_printoptions(threshold=sys.maxsize)
np.savetxt("KLDivg_density_mat.txt",density_mat)
density_mat
backend = QasmSimulator(method='statevector')
for x in range(1,20,1):
print()
arr = []
for nsh in range(1,20,1):
arr.append([])
for lp in range(1,10,1):
nshot=int(round(1000*(nsh)**1.5,0))
nparam=1000*lp
fidelity=[]
for x in range(nparam):
qr = QuantumRegister(1)
cr = ClassicalRegister(1)
qc = QuantumCircuit(qr, cr)
u13=UnitaryGate(random_unitary(2))
qc.append(u13, [qr[0]] )
u13=UnitaryGate(random_unitary(2))
qc.append(u13, [qr[0]] )
qc.measure(qr[0],cr[0])
job = execute(qc, backend, shots=nshot)
result = job.result()
count =result.get_counts()
if '0' in count and '1' in count:
ratio=count['0']/nshot
elif '0' in count and '1' not in count:
ratio=count['0']/nshot
else:
ratio=0
fidelity.append(ratio)
#Kullback Leibler divergence
weights = np.ones_like(fidelity)/float(len(fidelity))
P_U_hist=np.histogram(fidelity, bins=bins_list, weights=weights, range=[0, 1])[0];
#Kullback Leibler divergence
arr[nsh-1].append(sum(rel_entr(P_U_hist, P_harr_hist)))
print(nshot,'shots per simulation',nparam,'distribution size KL=',sum(rel_entr(P_U_hist, P_harr_hist)))
import sys
import numpy
statevector1=arr
numpy.set_printoptions(threshold=sys.maxsize)
np.savetxt("KLDivg_statevector.txt",statevector1)
statevector1
backend = QasmSimulator(method='matrix_product_state')
for x in range(1,20,1):
print()
arr = []
for nsh in range(1,20,1):
arr.append([])
for lp in range(1,10,1):
nshot=int(round(1000*(nsh)**1.5,0))
nparam=1000*lp
fidelity=[]
for x in range(nparam):
qr = QuantumRegister(1)
cr = ClassicalRegister(1)
qc = QuantumCircuit(qr, cr)
u13=UnitaryGate(random_unitary(2))
qc.append(u13, [qr[0]] )
u13=UnitaryGate(random_unitary(2))
qc.append(u13, [qr[0]] )
qc.measure(qr[0],cr[0])
job = execute(qc, backend, shots=nshot)
result = job.result()
count =result.get_counts()
if '0' in count and '1' in count:
ratio=count['0']/nshot
elif '0' in count and '1' not in count:
ratio=count['0']/nshot
else:
ratio=0
fidelity.append(ratio)
#Kullback Leibler divergence
weights = np.ones_like(fidelity)/float(len(fidelity))
P_U_hist=np.histogram(fidelity, bins=bins_list, weights=weights, range=[0, 1])[0];
#Kullback Leibler divergence
arr[nsh-1].append(sum(rel_entr(P_U_hist, P_harr_hist)))
print(nshot,'shots per simulation',nparam,'distribution size KL=',sum(rel_entr(P_U_hist, P_harr_hist)))
import sys
import numpy
matrix_product1=arr
numpy.set_printoptions(threshold=sys.maxsize)
np.savetxt("KLDivg_matrix_product1.txt",matrix_product1)
matrix_product1
def plotdata(i,data):
klll=np.transpose(data)
x=[];
y=[];
for nsh in range(0,9,1):
x.append(int(round(1000*(nsh)**1.5,0)))
y.append(klll[nsh][i])
return [x,y]
#loading dataset
fig, axes = plt.subplots(nrows=1, ncols=4, figsize=(20, 5))
datalist=[density_mat,statevector1,matrix_product1,qasm]
datalistn=['density_mat','statevector','matrix_product','qasm']
indx=0;
for indx in range(4):
data=datalist[indx];
axes[indx].plot(plotdata(0,data)[0],plotdata(0,data)[1], color='red', label='npram=1000');
axes[indx].plot(plotdata(1,data)[0],plotdata(1,data)[1], color='blue', label='npram=2000');
axes[indx].plot(plotdata(2,data)[0],plotdata(2,data)[1], color='black', label='npram=3000');
axes[indx].plot(plotdata(3,data)[0],plotdata(3,data)[1], color='green', label='npram=4000');
axes[indx].plot(plotdata(4,data)[0],plotdata(4,data)[1], color='purple', label='npram=5000');
axes[indx].plot(plotdata(5,data)[0],plotdata(5,data)[1], color='gray', label='npram=6000');
axes[indx].plot(plotdata(6,data)[0],plotdata(6,data)[1], color='black', label='npram=7000');
axes[indx].plot(plotdata(7,data)[0],plotdata(7,data)[1], color='yellow', label='npram=8000');
axes[indx].plot(plotdata(8,data)[0],plotdata(8,data)[1], color='pink', label='npram=9000');
axes[indx].set_ylim([0.003, 0.05])
axes[indx].legend(loc='upper right')
axes[indx].set_title(datalistn[indx])
axes[indx].set_yscale('log',base=10)
axes[indx].set_ylabel('Expressibility')
from matplotlib import pyplot as plt
fig.savefig('ExpressibilitybySimulator.png')
fig, axes = plt.subplots(nrows=1, ncols=4, figsize=(20, 5))
indx=0
for indx in range(4):
data=density_mat;
axes[indx].plot(plotdata(indx,data)[0],plotdata(indx,data)[1], color='red', label='density_mat');
data=statevector1;
axes[indx].plot(plotdata(indx,data)[0],plotdata(indx,data)[1], color='blue', label='statevector');
data=matrix_product1;
axes[indx].plot(plotdata(indx,data)[0],plotdata(indx,data)[1], color='green', label='matrix_product1');
data=qasm;
axes[indx].plot(plotdata(indx,data)[0],plotdata(indx,data)[1], color='pink', label='qasm');
axes[indx].set_title('nparam='+str((indx+1)*1000))
axes[indx].set_yscale('log',base=10)
axes[indx].set_ylim([0.003, 0.05])
axes[indx].set_ylabel('Expressibility')
axes[indx].legend(['density_mat','statevector','matrix_product1','qasm'])
axes[indx].set_xlabel('iteration')
fig.savefig('ExpressibilitybySimulatornparam1.png')
fig, axes = plt.subplots(nrows=1, ncols=4, figsize=(20, 5))
indx=0
for indx1 in range(4,8,1):
indx=indx1-4
data=density_mat;
axes[indx].plot(plotdata(indx1,data)[0],plotdata(indx1,data)[1], color='red', label='density_mat');
data=statevector1;
axes[indx].plot(plotdata(indx1,data)[0],plotdata(indx1,data)[1], color='blue', label='statevector');
data=matrix_product1;
axes[indx].plot(plotdata(indx1,data)[0],plotdata(indx1,data)[1], color='green', label='matrix_product1');
data=qasm;
axes[indx].plot(plotdata(indx1,data)[0],plotdata(indx1,data)[1], color='pink', label='qasm');
axes[indx].set_title('nparam='+str((indx1+1)*1000))
axes[indx].set_yscale('log',base=10)
axes[indx].set_ylabel('Expressibility')
axes[indx].set_ylim([0.003, 0.05])
axes[indx].legend(['density_mat','statevector','matrix_product1','qasm'])
axes[indx].set_xlabel('iteration')
fig.savefig('ExpressibilitybySimulatornparam2.png')
|
https://github.com/bagmk/Quantum_Machine_Learning_Express
|
bagmk
|
import numpy as np
from qiskit.quantum_info import state_fidelity, Statevector
def getStatevector(circuit):
return Statevector(circuit).data
import warnings
warnings.filterwarnings('ignore')
def P_haar(N, F):
if F == 1:
return 0
else:
return (N - 1) * ((1 - F) ** (N - 2))
def KL(P, Q):
epsilon = 1e-8
kl_divergence = 0.0
for p, q in zip(P, Q):
kl_divergence += p * np.log( (p + epsilon) / (q + epsilon) )
return abs(kl_divergence)
def expressibility(qubits, sampler, *, bins=100, epoch=3000, layer=1, encode=False, return_detail=False):
unit = 1 / bins
limits = []
probabilities = np.array([0] * bins)
for i in range(1, bins + 1):
limits.append(unit * i)
for i in range(epoch):
circuit_1 = sampler(layer=layer, qubits=qubits)
circuit_2 = sampler(layer=layer, qubits=qubits)
f = state_fidelity(
getStatevector(circuit_1),
getStatevector(circuit_2)
)
for j in range(bins):
if f <= limits[j]:
probabilities[j] += 1
break
pHaar_vqc = [ P_haar(2 ** qubits, f - (unit/2)) / bins for f in limits]
probabilities = [ p / epoch for p in probabilities ]
if return_detail:
return pHaar_vqc, probabilities
else:
return KL(probabilities, pHaar_vqc)
|
https://github.com/bagmk/Quantum_Machine_Learning_Express
|
bagmk
|
from qiskit import *
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit import IBMQ, Aer, execute,assemble,QuantumCircuit, aqua
from qiskit.visualization import plot_histogram, plot_bloch_vector, plot_bloch_multivector
from qiskit.quantum_info import Statevector
from qiskit.extensions import *
provider = IBMQ.load_account()
from qiskit.quantum_info import random_unitary
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
import math
from math import pi, sqrt
from qiskit.circuit import Parameter
from random import seed
from random import random
import cmath
#circuit 1
qr = QuantumRegister(4)
qc = QuantumCircuit(qr)
theta=[]
for i in range(8):
theta.append((Parameter('θ'+str(i))))
for i in range(4):
qc.rx(theta[i],qr[i])
for i in range(4):
qc.rz(theta[i+4],qr[i])
qc.draw('mpl')
#circuit 2
qr = QuantumRegister(4)
qc = QuantumCircuit(qr)
theta=[]
for i in range(8):
theta.append((Parameter('θ'+str(i))))
for i in range(4):
qc.rx(theta[i],qr[i])
for i in range(4):
qc.rz(theta[i+4],qr[i])
qc.cx(qr[3],qr[2])
qc.cx(qr[2],qr[1])
qc.cx(qr[1],qr[0])
qc.draw('mpl')
#circuit 3
qr = QuantumRegister(4)
qc = QuantumCircuit(qr)
theta=[]
for i in range(11):
theta.append((Parameter('θ'+str(i))))
for i in range(4):
qc.rx(theta[i],qr[i])
for i in range(4):
qc.rz(theta[i+4],qr[i])
qc.crz(theta[8],qr[3],qr[2])
qc.crz(theta[9],qr[2],qr[1])
qc.crz(theta[10],qr[1],qr[0])
qc.draw('mpl')
#circuit 4
qr = QuantumRegister(4)
qc = QuantumCircuit(qr)
theta=[]
for i in range(11):
theta.append((Parameter('θ'+str(i))))
for i in range(4):
qc.rx(theta[i],qr[i])
for i in range(4):
qc.rz(theta[i+4],qr[i])
qc.crx(theta[8],qr[3],qr[2])
qc.crx(theta[9],qr[2],qr[1])
qc.crx(theta[10],qr[1],qr[0])
qc.draw('mpl')
#circuit 5
qr = QuantumRegister(4)
qc = QuantumCircuit(qr)
theta=[]
for i in range(28):
theta.append((Parameter('θ'+str(i))))
count=0
for i in range(4):
qc.rx(theta[count],qr[i])
count=count+1
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
qc.barrier(qr)
for j in range(4):
for i in range(4):
if i!=j:
qc.crz(theta[count],qr[3-j],qr[3-i])
count=count+1
qc.barrier(qr)
for i in range(4):
qc.rx(theta[count],qr[i])
count=count+1
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
qc.draw('mpl')
#circuit 6
qr = QuantumRegister(4)
qc = QuantumCircuit(qr)
theta=[]
for i in range(28):
theta.append((Parameter('θ'+str(i))))
count=0
for i in range(4):
qc.rx(theta[count],qr[i])
count=count+1
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
qc.barrier(qr)
for j in range(4):
for i in range(4):
if i!=j:
qc.crx(theta[count],qr[3-j],qr[3-i])
count=count+1
qc.barrier(qr)
for i in range(4):
qc.rx(theta[count],qr[i])
count=count+1
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
qc.draw('mpl')
#circuit 7
qr = QuantumRegister(4)
qc = QuantumCircuit(qr)
theta=[]
for i in range(28):
theta.append((Parameter('θ'+str(i))))
count=0
for i in range(4):
qc.rx(theta[count],qr[i])
count=count+1
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
qc.barrier(qr)
qc.crz(theta[count],qr[1],qr[0])
count=count+1
qc.crz(theta[count],qr[3],qr[2])
count=count+1
qc.barrier(qr)
for i in range(4):
qc.rx(theta[count],qr[i])
count=count+1
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
qc.barrier(qr)
qc.crz(theta[count],qr[2],qr[1])
qc.draw('mpl')
#circuit 8
qr = QuantumRegister(4)
qc = QuantumCircuit(qr)
theta=[]
for i in range(28):
theta.append((Parameter('θ'+str(i))))
count=0
for i in range(4):
qc.rx(theta[count],qr[i])
count=count+1
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
qc.barrier(qr)
qc.crx(theta[count],qr[1],qr[0])
count=count+1
qc.crx(theta[count],qr[3],qr[2])
count=count+1
qc.barrier(qr)
for i in range(4):
qc.rx(theta[count],qr[i])
count=count+1
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
qc.barrier(qr)
qc.crx(theta[count],qr[2],qr[1])
qc.draw('mpl')
#circuit 9
qr = QuantumRegister(4)
qc = QuantumCircuit(qr)
theta=[]
for i in range(28):
theta.append((Parameter('θ'+str(i))))
count=0
for i in range(4):
qc.h(qr[i])
qc.barrier(qr)
qc.cz(qr[3],qr[2])
qc.cz(qr[2],qr[1])
qc.cz(qr[1],qr[0])
qc.barrier(qr)
for i in range(4):
qc.rx(theta[count],qr[i])
count=count+1
qc.draw('mpl')
#circuit 10
qr = QuantumRegister(4)
qc = QuantumCircuit(qr)
theta=[]
for i in range(28):
theta.append((Parameter('θ'+str(i))))
count=0
for i in range(4):
qc.ry(theta[count],qr[i])
count=count+1
qc.barrier(qr)
qc.cz(qr[3],qr[2])
qc.cz(qr[2],qr[1])
qc.cz(qr[1],qr[0])
qc.cz(qr[3],qr[0])
qc.barrier(qr)
for i in range(4):
qc.ry(theta[count],qr[i])
count=count+1
qc.draw('mpl')
#circuit 11
qr = QuantumRegister(4)
qc = QuantumCircuit(qr)
theta=[]
for i in range(28):
theta.append((Parameter('θ'+str(i))))
count=0
for i in range(4):
qc.ry(theta[count],qr[i])
count=count+1
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
qc.barrier(qr)
qc.cx(qr[1],qr[0])
qc.cx(qr[3],qr[2])
qc.barrier(qr)
qc.ry(theta[count],qr[1])
count=count+1
qc.ry(theta[count],qr[2])
count=count+1
qc.rz(theta[count],qr[1])
count=count+1
qc.rz(theta[count],qr[2])
qc.cx(qr[2],qr[1])
qc.draw('mpl')
#circuit 12
qr = QuantumRegister(4)
qc = QuantumCircuit(qr)
theta=[]
for i in range(28):
theta.append((Parameter('θ'+str(i))))
count=0
for i in range(4):
qc.ry(theta[count],qr[i])
count=count+1
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
qc.barrier(qr)
qc.cz(qr[1],qr[0])
qc.cz(qr[3],qr[2])
qc.barrier(qr)
qc.ry(theta[count],qr[1])
count=count+1
qc.ry(theta[count],qr[2])
count=count+1
qc.rz(theta[count],qr[1])
count=count+1
qc.rz(theta[count],qr[2])
qc.cz(qr[2],qr[1])
qc.draw('mpl')
#circuit 13
qr = QuantumRegister(4)
qc = QuantumCircuit(qr)
theta=[]
for i in range(28):
theta.append((Parameter('θ'+str(i))))
count=0
for i in range(4):
qc.ry(theta[count],qr[i])
count=count+1
qc.barrier(qr)
qc.crz(theta[count],qr[3],qr[0])
count=count+1
qc.crz(theta[count],qr[2],qr[3])
count=count+1
qc.crz(theta[count],qr[1],qr[2])
count=count+1
qc.crz(theta[count],qr[0],qr[1])
count=count+1
qc.barrier(qr)
for i in range(4):
qc.ry(theta[count],qr[i])
count=count+1
qc.barrier(qr)
qc.crz(theta[count],qr[3],qr[2])
count=count+1
qc.crz(theta[count],qr[0],qr[3])
count=count+1
qc.crz(theta[count],qr[1],qr[0])
count=count+1
qc.crz(theta[count],qr[2],qr[1])
qc.draw('mpl')
#circuit 14
qr = QuantumRegister(4)
qc = QuantumCircuit(qr)
theta=[]
for i in range(28):
theta.append((Parameter('θ'+str(i))))
count=0
for i in range(4):
qc.ry(theta[count],qr[i])
count=count+1
qc.barrier(qr)
qc.crx(theta[count],qr[3],qr[0])
count=count+1
qc.crx(theta[count],qr[2],qr[3])
count=count+1
qc.crx(theta[count],qr[1],qr[2])
count=count+1
qc.crx(theta[count],qr[0],qr[1])
count=count+1
qc.barrier(qr)
for i in range(4):
qc.ry(theta[count],qr[i])
count=count+1
qc.barrier(qr)
qc.crx(theta[count],qr[3],qr[2])
count=count+1
qc.crx(theta[count],qr[0],qr[3])
count=count+1
qc.crx(theta[count],qr[1],qr[0])
count=count+1
qc.crx(theta[count],qr[2],qr[1])
qc.draw('mpl')
#circuit 15
qr = QuantumRegister(4)
qc = QuantumCircuit(qr)
theta=[]
for i in range(28):
theta.append((Parameter('θ'+str(i))))
count=0
for i in range(4):
qc.ry(theta[count],qr[i])
count=count+1
qc.barrier(qr)
qc.cx(qr[3],qr[0])
count=count+1
qc.cx(qr[2],qr[3])
count=count+1
qc.cx(qr[1],qr[2])
count=count+1
qc.cx(qr[0],qr[1])
count=count+1
qc.barrier(qr)
for i in range(4):
qc.ry(theta[count],qr[i])
count=count+1
qc.barrier(qr)
qc.cx(qr[3],qr[2])
count=count+1
qc.cx(qr[0],qr[3])
count=count+1
qc.cx(qr[1],qr[0])
count=count+1
qc.cx(qr[2],qr[1])
qc.draw('mpl')
#circuit 16
qr = QuantumRegister(4)
qc = QuantumCircuit(qr)
theta=[]
for i in range(28):
theta.append((Parameter('θ'+str(i))))
count=0
for i in range(4):
qc.rx(theta[count],qr[i])
count=count+1
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
qc.barrier(qr)
qc.crz(theta[count],qr[1],qr[0])
count=count+1
qc.crz(theta[count],qr[3],qr[2])
count=count+1
qc.crz(theta[count],qr[2],qr[1])
qc.draw('mpl')
#circuit 17
qr = QuantumRegister(4)
qc = QuantumCircuit(qr)
theta=[]
for i in range(28):
theta.append((Parameter('θ'+str(i))))
count=0
for i in range(4):
qc.rx(theta[count],qr[i])
count=count+1
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
qc.barrier(qr)
qc.crx(theta[count],qr[1],qr[0])
count=count+1
qc.crx(theta[count],qr[3],qr[2])
count=count+1
qc.crx(theta[count],qr[2],qr[1])
qc.draw('mpl')
#circuit 18
qr = QuantumRegister(4)
qc = QuantumCircuit(qr)
theta=[]
for i in range(28):
theta.append((Parameter('θ'+str(i))))
count=0
for i in range(4):
qc.rx(theta[count],qr[i])
count=count+1
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
qc.barrier(qr)
qc.crz(theta[count],qr[3],qr[0])
count=count+1
qc.crz(theta[count],qr[2],qr[3])
count=count+1
qc.crz(theta[count],qr[1],qr[2])
count=count+1
qc.crz(theta[count],qr[0],qr[1])
qc.draw('mpl')
#circuit 19
qr = QuantumRegister(4)
qc = QuantumCircuit(qr)
theta=[]
for i in range(28):
theta.append((Parameter('θ'+str(i))))
count=0
for i in range(4):
qc.rx(theta[count],qr[i])
count=count+1
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
qc.barrier(qr)
qc.crx(theta[count],qr[3],qr[0])
count=count+1
qc.crx(theta[count],qr[2],qr[3])
count=count+1
qc.crx(theta[count],qr[1],qr[2])
count=count+1
qc.crx(theta[count],qr[0],qr[1])
qc.draw('mpl')
|
https://github.com/bagmk/Quantum_Machine_Learning_Express
|
bagmk
|
from qiskit import *
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit import IBMQ, Aer, execute,assemble,QuantumCircuit, aqua
from qiskit.visualization import plot_histogram, plot_bloch_vector, plot_bloch_multivector
from qiskit.quantum_info import Statevector
from qiskit.extensions import *
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
import math
from math import pi, sqrt
from qiskit.quantum_info import random_unitary
from random import seed
from random import random
import cmath
from qiskit.circuit import Parameter
import numpy as np
import scipy.linalg as la
from qiskit.exceptions import QiskitError
from qiskit.quantum_info.states.densitymatrix import DensityMatrix, Statevector
from qiskit.quantum_info.states.utils import (partial_trace, shannon_entropy,_format_state, _funm_svd, partial_trace)
from qiskit.quantum_info.states.measures import partial_trace, _format_state
qr = QuantumRegister(2)
qc = QuantumCircuit(qr)
qc.h(qr[0])
qc.h(qr[1])
qc.cz(qr[0],qr[1])
svsim = Aer.get_backend('statevector_simulator')
def entange_measure2(qc,n):
qobj = assemble(qc)
state = svsim.run(qobj).result().get_statevector()
dm=DensityMatrix(state)
partial=[]
for i in range(n):
pt=partial_trace(dm,[i]).to_operator().data
partial.append((1/2)*np.dot(pt,pt).trace())
return 2*(1-(sum(partial)))
def entange_measure4(qc,n):
qobj = assemble(qc)
state = svsim.run(qobj).result().get_statevector()
dm=DensityMatrix(state)
partial=[]
for i in range(4):
for j in range(4):
for k in range(4):
if i>j>k:
pt=partial_trace(dm,[i,j,k]).data
partial.append(np.dot(pt,pt).trace())
return 2*(1-(1/16)*(sum(partial)))
entange_measure(qc,2)
ll=0;
for i in range(4):
for j in range(4):
for k in range(4):
if i>j and j>k:
ll=ll+1
ll
qr = QuantumRegister(4)
qc = QuantumCircuit(qr)
theta=[];
for y in range(500):
theta.append(2*pi*random())
qc=circuit1(qc,qr,theta,1,0)
qobj = assemble(qc)
state = svsim.run(qobj).result().get_statevector()
dm=DensityMatrix(state)
pt=partial_trace(dm,[0,1,2]).data
pt
backend = Aer.get_backend('qasm_simulator')
nshot=1000
m=[];
qr = QuantumRegister(4)
cr = ClassicalRegister(4)
qc = QuantumCircuit(qr, cr)
theta=[];
for y in range(80):
theta.append(2*pi*random())
qc=circuit1(qc,qr,theta,1,0)
qc.measure(qr[:],cr[:])
job = execute(qc, bWackend, shots=nshot)
result = job.result()
count =result.get_counts()
count
Q=Q+0.5**(u[i]*v[j]-u[j]*v[i])**2
Q
def circuit1(qc,qr,theta,L,repeat):
#circuit 1
#theta is list of the parameters
#theta length is 8L
#L is the number of repeatation
# repeat will conjugate the first part and add next the the circuit for expressibility
# 0:No, 1: Repeat
count=0
for l in range(L):
for i in range(4):
qc.rx(theta[count],qr[i])
count=count+1
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
if repeat!=0:
qc.barrier(qr)
for l in range(L):
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
for i in range(4):
qc.rx(theta[count],qr[i])
count=count+1
return qc
def circuit2(qc,qr,theta,L,repeat):
#circuit 2
#theta is list of the parameters
#theta length is 8L
#L is the number of repeatation
# repeat will conjugate the first part and add next the the circuit for expressibility
# 0:No, 1: Repeat
count=0
for l in range(L):
for i in range(4):
qc.rx(theta[count],qr[i])
count=count+1
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
qc.cx(qr[3],qr[2])
qc.cx(qr[2],qr[1])
qc.cx(qr[1],qr[0])
if repeat!=0:
qc.barrier(qr)
for l in range(L):
qc.cx(qr[1],qr[0])
qc.cx(qr[2],qr[1])
qc.cx(qr[3],qr[2])
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
for i in range(4):
qc.rx(theta[count],qr[i])
count=count+1
return qc
def circuit3(qc,qr,theta,L,repeat):
#circuit 3
#theta is list of the parameters
#theta length is (11)L
#L is the number of repeatation
# repeat will conjugate the first part and add next the the circuit for expressibility
# 0:No, 1: Repeat
count=0
for l in range(L):
for i in range(4):
qc.rx(theta[count],qr[i])
count=count+1
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
qc.crz(theta[count],qr[3],qr[2])
count=count+1
qc.crz(theta[count],qr[2],qr[1])
count=count+1
qc.crz(theta[count],qr[1],qr[0])
count=count+1
if repeat!=0:
qc.barrier(qr)
for l in range(L):
qc.crz(theta[count],qr[1],qr[0])
count=count+1
qc.crz(theta[count],qr[2],qr[1])
count=count+1
qc.crz(theta[count],qr[3],qr[2])
count=count+1
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
for i in range(4):
qc.rx(theta[count],qr[i])
count=count+1
return qc
def circuit4(qc,qr,theta,L,repeat):
#circuit 4
#theta is list of the parameters
#theta length is (11)L
#L is the number of repeatation
# repeat will conjugate the first part and add next the the circuit for expressibility
# 0:No, 1: Repeat
count=0
for l in range(L):
for i in range(4):
qc.rx(theta[count],qr[i])
count=count+1
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
qc.crx(theta[count],qr[3],qr[2])
count=count+1
qc.crx(theta[count],qr[2],qr[1])
count=count+1
qc.crx(theta[count],qr[1],qr[0])
count=count+1
if repeat!=0:
qc.barrier(qr)
for l in range(L):
qc.crx(theta[count],qr[1],qr[0])
count=count+1
qc.crx(theta[count],qr[2],qr[1])
count=count+1
qc.crx(theta[count],qr[3],qr[2])
count=count+1
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
for i in range(4):
qc.rx(theta[count],qr[i])
count=count+1
return qc
def circuit5(qc,qr,theta,L,repeat):
#circuit 5
#theta is list of the parameters
#theta length is (28)L
#L is the number of repeatation
# repeat will conjugate the first part and add next the the circuit for expressibility
# 0:No, 1: Repeat
count=0
for l in range(L):
for i in range(4):
qc.rx(theta[count],qr[i])
count=count+1
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
for j in range(4):
for i in range(4):
if i!=j:
qc.crz(theta[count],qr[3-j],qr[3-i])
count=count+1
for i in range(4):
qc.rx(theta[count],qr[i])
count=count+1
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
if repeat!=0:
qc.barrier(qr)
for l in range(L):
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
for i in range(4):
qc.rx(theta[count],qr[i])
count=count+1
for j in range(4):
for i in range(4):
if i!=j:
qc.crz(theta[count],qr[j],qr[i])
count=count+1
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
for i in range(4):
qc.rx(theta[count],qr[i])
count=count+1
return qc
def circuit6(qc,qr,theta,L,repeat):
#circuit 6
#theta is list of the parameters
#theta length is (28)L
#L is the number of repeatation
# repeat will conjugate the first part and add next the the circuit for expressibility
# 0:No, 1: Repeat
count=0
for l in range(L):
for i in range(4):
qc.rx(theta[count],qr[i])
count=count+1
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
for j in range(4):
for i in range(4):
if i!=j:
qc.crx(theta[count],qr[3-j],qr[3-i])
count=count+1
for i in range(4):
qc.rx(theta[count],qr[i])
count=count+1
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
if repeat!=0:
qc.barrier(qr)
for l in range(L):
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
for i in range(4):
qc.rx(theta[count],qr[i])
count=count+1
for j in range(4):
for i in range(4):
if i!=j:
qc.crx(theta[count],qr[j],qr[i])
count=count+1
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
for i in range(4):
qc.rx(theta[count],qr[i])
count=count+1
return qc
def circuit7(qc,qr,theta,L,repeat):
#circuit 7
#theta is list of the parameters
#theta length is (19)L
#L is the number of repeatation
# repeat will conjugate the first part and add next the the circuit for expressibility
# 0:No, 1: Repeat
count=0
for l in range(L):
for i in range(4):
qc.rx(theta[count],qr[i])
count=count+1
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
qc.crz(theta[count],qr[1],qr[0])
count=count+1
qc.crz(theta[count],qr[3],qr[2])
count=count+1
for i in range(4):
qc.rx(theta[count],qr[i])
count=count+1
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
qc.crz(theta[count],qr[2],qr[1])
count=count+1
if repeat!=0:
qc.barrier(qr)
for l in range(L):
qc.crz(theta[count],qr[2],qr[1])
count=count+1
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
for i in range(4):
qc.rx(theta[count],qr[i])
count=count+1
qc.crz(theta[count],qr[3],qr[2])
count=count+1
qc.crz(theta[count],qr[1],qr[0])
count=count+1
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
for i in range(4):
qc.rx(theta[count],qr[i])
count=count+1
return qc
def circuit8(qc,qr,theta,L,repeat):
#circuit 8
#theta is list of the parameters
#theta length is (19)L
#L is the number of repeatation
# repeat will conjugate the first part and add next the the circuit for expressibility
# 0:No, 1: Repeat
count=0
for l in range(L):
for i in range(4):
qc.rx(theta[count],qr[i])
count=count+1
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
qc.crx(theta[count],qr[1],qr[0])
count=count+1
qc.crx(theta[count],qr[3],qr[2])
count=count+1
for i in range(4):
qc.rx(theta[count],qr[i])
count=count+1
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
qc.crx(theta[count],qr[2],qr[1])
count=count+1
if repeat!=0:
qc.barrier(qr)
for l in range(L):
qc.crx(theta[count],qr[2],qr[1])
count=count+1
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
for i in range(4):
qc.rx(theta[count],qr[i])
count=count+1
qc.crx(theta[count],qr[3],qr[2])
count=count+1
qc.crx(theta[count],qr[1],qr[0])
count=count+1
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
for i in range(4):
qc.rx(theta[count],qr[i])
count=count+1
return qc
def circuit9(qc,qr,theta,L,repeat):
#circuit 9
#theta is list of the parameters
#theta length is (4)L
#L is the number of repeatation
# repeat will conjugate the first part and add next the the circuit for expressibility
# 0:No, 1: Repeat
count=0
for l in range(L):
for i in range(4):
qc.h(qr[i])
qc.cz(qr[3],qr[2])
qc.cz(qr[2],qr[1])
qc.cz(qr[1],qr[0])
for i in range(4):
qc.rx(theta[count],qr[i])
count=count+1
if repeat!=0:
qc.barrier(qr)
for l in range(L):
for i in range(4):
qc.rx(theta[count],qr[i])
count=count+1
qc.cz(qr[1],qr[0])
qc.cz(qr[2],qr[1])
qc.cz(qr[3],qr[2])
for i in range(4):
qc.h(qr[i])
return qc
def circuit10(qc,qr,theta,L,repeat):
#circuit 10
#theta is list of the parameters
#theta length is (4)L+4
#L is the number of repeatation
# repeat will conjugate the first part and add next the the circuit for expressibility
# 0:No, 1: Repeat
count=0
for i in range(4):
qc.ry(theta[count],qr[i])
count=count+1
for l in range(L):
qc.cz(qr[3],qr[2])
qc.cz(qr[2],qr[1])
qc.cz(qr[1],qr[0])
qc.cz(qr[3],qr[0])
for i in range(4):
qc.ry(theta[count],qr[i])
count=count+1
if repeat!=0:
qc.barrier(qr)
for l in range(L):
for i in range(4):
qc.ry(theta[count],qr[i])
count=count+1
qc.cz(qr[3],qr[0])
qc.cz(qr[1],qr[0])
qc.cz(qr[2],qr[1])
qc.cz(qr[3],qr[2])
for i in range(4):
qc.ry(theta[count],qr[i])
count=count+1
return qc
def circuit11(qc,qr,theta,L,repeat):
#circuit 11
#theta is list of the parameters
#theta length is (12)L
#L is the number of repeatation
# repeat will conjugate the first part and add next the the circuit for expressibility
# 0:No, 1: Repeat
count=0
for l in range(L):
for i in range(4):
qc.ry(theta[count],qr[i])
count=count+1
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
qc.cx(qr[1],qr[0])
qc.cx(qr[3],qr[2])
qc.ry(theta[count],qr[1])
count=count+1
qc.ry(theta[count],qr[2])
count=count+1
qc.rz(theta[count],qr[1])
count=count+1
qc.rz(theta[count],qr[2])
count=count+1
qc.cx(qr[2],qr[1])
if repeat!=0:
qc.barrier(qr)
for l in range(L):
qc.cx(qr[2],qr[1])
qc.rz(theta[count],qr[2])
count=count+1
qc.rz(theta[count],qr[1])
count=count+1
qc.ry(theta[count],qr[2])
count=count+1
qc.ry(theta[count],qr[1])
count=count+1
qc.cx(qr[3],qr[2])
qc.cx(qr[1],qr[0])
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
for i in range(4):
qc.ry(theta[count],qr[i])
count=count+1
return qc
def circuit12(qc,qr,theta,L,repeat):
#circuit 12
#theta is list of the parameters
#theta length is (12)L
#L is the number of repeatation
# repeat will conjugate the first part and add next the the circuit for expressibility
# 0:No, 1: Repeat
count=0
for l in range(L):
for i in range(4):
qc.ry(theta[count],qr[i])
count=count+1
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
qc.cz(qr[1],qr[0])
qc.cz(qr[3],qr[2])
qc.ry(theta[count],qr[1])
count=count+1
qc.ry(theta[count],qr[2])
count=count+1
qc.rz(theta[count],qr[1])
count=count+1
qc.rz(theta[count],qr[2])
count=count+1
qc.cz(qr[2],qr[1])
if repeat!=0:
qc.barrier(qr)
for l in range(L):
qc.cz(qr[2],qr[1])
qc.rz(theta[count],qr[2])
count=count+1
qc.rz(theta[count],qr[1])
count=count+1
qc.ry(theta[count],qr[2])
count=count+1
qc.ry(theta[count],qr[1])
count=count+1
qc.cz(qr[3],qr[2])
qc.cz(qr[1],qr[0])
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
for i in range(4):
qc.ry(theta[count],qr[i])
count=count+1
return qc
def circuit13(qc,qr,theta,L,repeat):
#circuit 13
#theta is list of the parameters
#theta length is (16)L
#L is the number of repeatation
# repeat will conjugate the first part and add next the the circuit for expressibility
# 0:No, 1: Repeat
count=0
for l in range(L):
for i in range(4):
qc.ry(theta[count],qr[i])
count=count+1
qc.crz(theta[count],qr[3],qr[0])
count=count+1
qc.crz(theta[count],qr[2],qr[3])
count=count+1
qc.crz(theta[count],qr[1],qr[2])
count=count+1
qc.crz(theta[count],qr[0],qr[1])
count=count+1
for i in range(4):
qc.ry(theta[count],qr[i])
count=count+1
qc.crz(theta[count],qr[3],qr[2])
count=count+1
qc.crz(theta[count],qr[0],qr[3])
count=count+1
qc.crz(theta[count],qr[1],qr[0])
count=count+1
qc.crz(theta[count],qr[2],qr[1])
count=count+1
if repeat!=0:
qc.barrier(qr)
for l in range(L):
qc.crz(theta[count],qr[2],qr[1])
count=count+1
qc.crz(theta[count],qr[1],qr[0])
count=count+1
qc.crz(theta[count],qr[0],qr[3])
count=count+1
qc.crz(theta[count],qr[3],qr[2])
count=count+1
for i in range(4):
qc.ry(theta[count],qr[i])
count=count+1
qc.crz(theta[count],qr[0],qr[1])
count=count+1
qc.crz(theta[count],qr[1],qr[2])
count=count+1
qc.crz(theta[count],qr[2],qr[3])
count=count+1
qc.crz(theta[count],qr[3],qr[0])
count=count+1
for i in range(4):
qc.ry(theta[count],qr[i])
count=count+1
return qc
def circuit14(qc,qr,theta,L,repeat):
#circuit 14
#theta is list of the parameters
#theta length is (16)L
#L is the number of repeatation
# repeat will conjugate the first part and add next the the circuit for expressibility
# 0:No, 1: Repeat
count=0
for l in range(L):
for i in range(4):
qc.ry(theta[count],qr[i])
count=count+1
qc.crx(theta[count],qr[3],qr[0])
count=count+1
qc.crx(theta[count],qr[2],qr[3])
count=count+1
qc.crx(theta[count],qr[1],qr[2])
count=count+1
qc.crx(theta[count],qr[0],qr[1])
count=count+1
for i in range(4):
qc.ry(theta[count],qr[i])
count=count+1
qc.crx(theta[count],qr[3],qr[2])
count=count+1
qc.crx(theta[count],qr[0],qr[3])
count=count+1
qc.crx(theta[count],qr[1],qr[0])
count=count+1
qc.crx(theta[count],qr[2],qr[1])
count=count+1
if repeat!=0:
qc.barrier(qr)
for l in range(L):
qc.crx(theta[count],qr[2],qr[1])
count=count+1
qc.crx(theta[count],qr[1],qr[0])
count=count+1
qc.crx(theta[count],qr[0],qr[3])
count=count+1
qc.crx(theta[count],qr[3],qr[2])
count=count+1
for i in range(4):
qc.ry(theta[count],qr[i])
count=count+1
qc.crx(theta[count],qr[0],qr[1])
count=count+1
qc.crx(theta[count],qr[1],qr[2])
count=count+1
qc.crx(theta[count],qr[2],qr[3])
count=count+1
qc.crx(theta[count],qr[3],qr[0])
count=count+1
for i in range(4):
qc.ry(theta[count],qr[i])
count=count+1
return qc
def circuit15(qc,qr,theta,L,repeat):
#circuit 15
#theta is list of the parameters
#theta length is (8)L
#L is the number of repeatation
# repeat will conjugate the first part and add next the the circuit for expressibility
# 0:No, 1: Repeat
count=0
for l in range(L):
for i in range(4):
qc.ry(theta[count],qr[i])
count=count+1
qc.cx(qr[3],qr[0])
qc.cx(qr[2],qr[3])
qc.cx(qr[1],qr[2])
qc.cx(qr[0],qr[1])
for i in range(4):
qc.ry(theta[count],qr[i])
count=count+1
qc.cx(qr[3],qr[2])
qc.cx(qr[0],qr[3])
qc.cx(qr[1],qr[0])
qc.cx(qr[2],qr[1])
if repeat!=0:
qc.barrier(qr)
for l in range(L):
qc.cx(qr[2],qr[1])
qc.cx(qr[1],qr[0])
qc.cx(qr[0],qr[3])
qc.cx(qr[3],qr[2])
for i in range(4):
qc.ry(theta[count],qr[i])
count=count+1
qc.cx(qr[0],qr[1])
qc.cx(qr[1],qr[2])
qc.cx(qr[2],qr[3])
qc.cx(qr[3],qr[0])
for i in range(4):
qc.ry(theta[count],qr[i])
count=count+1
return qc
def circuit16(qc,qr,theta,L,repeat):
#circuit 16
#theta is list of the parameters
#theta length is (11)L
#L is the number of repeatation
# repeat will conjugate the first part and add next the the circuit for expressibility
# 0:No, 1: Repeat
count=0
for l in range(L):
for i in range(4):
qc.rx(theta[count],qr[i])
count=count+1
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
qc.crz(theta[count],qr[1],qr[0])
count=count+1
qc.crz(theta[count],qr[3],qr[2])
count=count+1
qc.crz(theta[count],qr[2],qr[1])
count=count+1
if repeat!=0:
qc.barrier(qr)
for l in range(L):
qc.crz(theta[count],qr[2],qr[1])
count=count+1
qc.crz(theta[count],qr[3],qr[2])
count=count+1
qc.crz(theta[count],qr[1],qr[0])
count=count+1
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
for i in range(4):
qc.rx(theta[count],qr[i])
count=count+1
return qc
def circuit17(qc,qr,theta,L,repeat):
#circuit 17
#theta is list of the parameters
#theta length is (11)L
#L is the number of repeatation
# repeat will conjugate the first part and add next the the circuit for expressibility
# 0:No, 1: Repeat
count=0
for l in range(L):
for i in range(4):
qc.rx(theta[count],qr[i])
count=count+1
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
qc.crx(theta[count],qr[1],qr[0])
count=count+1
qc.crx(theta[count],qr[3],qr[2])
count=count+1
qc.crx(theta[count],qr[2],qr[1])
count=count+1
if repeat!=0:
qc.barrier(qr)
for l in range(L):
qc.crx(theta[count],qr[2],qr[1])
count=count+1
qc.crx(theta[count],qr[3],qr[2])
count=count+1
qc.crx(theta[count],qr[1],qr[0])
count=count+1
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
for i in range(4):
qc.rx(theta[count],qr[i])
count=count+1
return qc
def circuit18(qc,qr,theta,L,repeat):
#circuit 18
#theta is list of the parameters
#theta length is (12)L
#L is the number of repeatation
# repeat will conjugate the first part and add next the the circuit for expressibility
# 0:No, 1: Repeat
count=0
for l in range(L):
for i in range(4):
qc.rx(theta[count],qr[i])
count=count+1
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
qc.crz(theta[count],qr[3],qr[0])
count=count+1
qc.crz(theta[count],qr[2],qr[3])
count=count+1
qc.crz(theta[count],qr[1],qr[2])
count=count+1
qc.crz(theta[count],qr[0],qr[1])
count=count+1
if repeat!=0:
qc.barrier(qr)
for l in range(L):
qc.crz(theta[count],qr[0],qr[1])
count=count+1
qc.crz(theta[count],qr[1],qr[2])
count=count+1
qc.crz(theta[count],qr[2],qr[3])
count=count+1
qc.crz(theta[count],qr[3],qr[0])
count=count+1
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
for i in range(4):
qc.rx(theta[count],qr[i])
count=count+1
return qc
def circuit19(qc,qr,theta,L,repeat):
#circuit 1
#theta is list of the parameters
#theta length is (12)L
#L is the number of repeatation
# repeat will conjugate the first part and add next the the circuit for expressibility
# 0:No, 1: Repeat
count=0
for l in range(L):
for i in range(4):
qc.rx(theta[count],qr[i])
count=count+1
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
qc.crx(theta[count],qr[3],qr[0])
count=count+1
qc.crx(theta[count],qr[2],qr[3])
count=count+1
qc.crx(theta[count],qr[1],qr[2])
count=count+1
qc.crx(theta[count],qr[0],qr[1])
count=count+1
if repeat!=0:
qc.barrier(qr)
for l in range(L):
qc.crx(theta[count],qr[0],qr[1])
count=count+1
qc.crx(theta[count],qr[1],qr[2])
count=count+1
qc.crx(theta[count],qr[2],qr[3])
count=count+1
qc.crx(theta[count],qr[3],qr[0])
count=count+1
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
for i in range(4):
qc.rx(theta[count],qr[i])
count=count+1
return qc
|
https://github.com/bagmk/Quantum_Machine_Learning_Express
|
bagmk
|
from qiskit import *
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit import IBMQ, Aer, execute,assemble,QuantumCircuit, aqua
from qiskit.visualization import plot_histogram, plot_bloch_vector, plot_bloch_multivector
from qiskit.quantum_info import Statevector
from qiskit.extensions import *
provider = IBMQ.load_account()
from qiskit.quantum_info import random_unitary
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
import math
from math import pi, sqrt
from scipy.special import rel_entr
from random import seed
from random import random
import cmath
import os
from qiskit.circuit import Parameter
#Possible Bin
bins_list=[];
for i in range(76):
bins_list.append((i)/75)
#Center of the Bean
bins_x=[]
for i in range(75):
bins_x.append(bins_list[1]+bins_list[i])
def P_harr(l,u,N):
return (1-l)**(N-1)-(1-u)**(N-1)
#Harr historgram
P_harr_hist=[]
for i in range(75):
P_harr_hist.append(P_harr(bins_list[i],bins_list[i+1],16))
#Imaginary
j=(-1)**(1/2)
backend = Aer.get_backend('qasm_simulator')
nshot=1000
nparam=2000
fidelity=[]
for x in range(nparam):
qr = QuantumRegister(4)
cr = ClassicalRegister(4)
qc = QuantumCircuit(qr, cr)
theta=[];
for y in range(80):
theta.append(2*pi*random())
qc=circuit9(qc,qr,theta,3,1)
qc.measure(qr[:],cr[:])
job = execute(qc, backend, shots=nshot)
result = job.result()
count =result.get_counts()
if '0000' in count and '1' in count:
ratio=count['0000']/nshot
elif '0000' in count and '1' not in count:
ratio=count['0000']/nshot
else:
ratio=0
fidelity.append(ratio)
weights = np.ones_like(fidelity)/float(len(fidelity))
plt.hist(fidelity, bins=bins_list, weights=weights, range=[0, 1], label='Circuit 1')
plt.plot(bins_x, P_harr_hist, label='Harr')
plt.legend(loc='upper right')
plt.show()
# example of calculating the kl divergence (relative entropy) with scipy
P_1_hist=np.histogram(fidelity, bins=bins_list, weights=weights, range=[0, 1])[0]
kl_pq = rel_entr(P_1_hist, P_harr_hist)
print('KL(P || Q): %.3f nats' % sum(kl_pq))
list_of_circuit = [circuit1,circuit2,circuit3,circuit4,circuit5,circuit6,circuit7,circuit8,circuit9,circuit10,circuit11,circuit12,circuit13,circuit14,circuit15,circuit16,circuit17,circuit18,circuit19]
backend = Aer.get_backend('qasm_simulator')
arr = []
for kk in range(19):
arr.append([])
for lo in [1,2,3,4,5]:
nshot=1000
nparam=2000
fidelity=[]
for x in range(nparam):
qr = QuantumRegister(4)
cr = ClassicalRegister(4)
qc = QuantumCircuit(qr, cr)
theta=[];
for y in range(500):
theta.append(2*pi*random())
qc=list_of_circuit[kk](qc,qr,theta,lo,1)
qc.measure(qr[:],cr[:])
job = execute(qc, backend, shots=nshot)
result = job.result()
count =result.get_counts()
if '0000' in count and '1' in count:
ratio=count['0000']/nshot
elif '0000' in count and '1' not in count:
ratio=count['0000']/nshot
else:
ratio=0
fidelity.append(ratio)
weights = np.ones_like(fidelity)/float(len(fidelity))
# example of calculating the kl divergence (relative entropy) with scipy
P_hist=np.histogram(fidelity, bins=bins_list, weights=weights, range=[0, 1])[0]
kl_pq = rel_entr(P_hist, P_harr_hist)
arr[kk].append(sum(kl_pq))
print(kk,'cir',lo,'lay')
import sys
import numpy
numpy.set_printoptions(threshold=sys.maxsize)
np.savetxt("express_nshot1000_nparam2000.txt",express)
express
import pandas as pd
import matplotlib.pyplot as plt
#loading dataset
x = [i+1 for i in range(19)]
y = [i[0] for i in arr]
plt.plot(x, y, 'o', color='red', label='L=1');
x = [i+1 for i in range(19)]
y = [i[1] for i in arr]
plt.plot(x, y, 'o', color='blue', label='L=2');
x = [i+1 for i in range(19)]
y = [i[2] for i in arr]
plt.plot(x, y, 'o', color='black', label='L=3');
x = [i+1 for i in range(19)]
y = [i[3] for i in arr]
plt.plot(x, y, 'o', color='green', label='L=4');
x = [i+1 for i in range(19)]
y = [i[3] for i in arr]
plt.plot(x, y, 'o', color='purple', label='L=5');
plt.legend(loc='upper right')
plt.yscale('log',base=10)
plt.xlabel('Circuit ID')
plt.ylabel('Expressibility')
# Create names on the x axis
plt.xticks([i+1 for i in range(19)])
plt.show()
x = [str(i+1) for i in range(19)]
x_ticks_labels = ['9','1','2','16','3','18','10','12','15','17','4','11','7','8','19','5','13','14','6']
xarr = np.array(x)
ind = np.where(xarr.reshape(xarr.size, 1) == np.array(x_ticks_labels))[1]
fig, ax = plt.subplots(1,1)
y = [i[0] for i in arr]
ax.scatter(ind,y, marker="o", color='red', label='L=1')
y = [i[1] for i in arr]
ax.scatter(ind,y, marker="o", color='blue', label='L=2')
y = [i[2] for i in arr]
ax.scatter(ind,y, marker="o", color='black', label='L=3')
y = [i[3] for i in arr]
ax.scatter(ind,y, marker="o", color='green', label='L=4')
y = [i[4] for i in arr]
ax.scatter(ind,y, marker="o", color='purple', label='L=5')
ax.set_yscale('log',base=10)
ax.set_xlabel('Circuit ID')
ax.set_ylabel('Expressibility')
ax.legend(loc='upper right')
ax.set_xticks(range(len(x_ticks_labels)))
ax.set_xticklabels(x_ticks_labels)
plt.show()
fig
from matplotlib import pyplot as plt
fig.savefig('express_nshot1000_nparam2000.png')
list_of_circuit = [circuit1,circuit2,circuit3,circuit4,circuit5,circuit6,circuit7,circuit8,circuit9,circuit10,circuit11,circuit12,circuit13,circuit14,circuit15,circuit16,circuit17,circuit18,circuit19]
backend = Aer.get_backend('qasm_simulator')
arr = []
for kk in range(19):
arr.append([])
for lo in [1,2,3,4,5]:
nshot=10000
nparam=1000
fidelity=[]
for x in range(nparam):
qr = QuantumRegister(4)
cr = ClassicalRegister(4)
qc = QuantumCircuit(qr, cr)
theta=[];
for y in range(500):
theta.append(2*pi*random())
qc=list_of_circuit[kk](qc,qr,theta,lo,1)
qc.measure(qr[:],cr[:])
job = execute(qc, backend, shots=nshot)
result = job.result()
count =result.get_counts()
if '0000' in count and '1' in count:
ratio=count['0000']/nshot
elif '0000' in count and '1' not in count:
ratio=count['0000']/nshot
else:
ratio=0
fidelity.append(ratio)
weights = np.ones_like(fidelity)/float(len(fidelity))
# example of calculating the kl divergence (relative entropy) with scipy
P_hist=np.histogram(fidelity, bins=bins_list, weights=weights, range=[0, 1])[0]
kl_pq = rel_entr(P_hist, P_harr_hist)
arr[kk].append(sum(kl_pq))
print(kk,'cir',lo,'lay')
express
import sys
import numpy
numpy.set_printoptions(threshold=sys.maxsize)
np.savetxt("express_nshot10000_nparam1000.txt",express)
x = [str(i+1) for i in range(19)]
x_ticks_labels = ['9','1','2','16','3','18','10','12','15','17','4','11','7','8','19','5','13','14','6']
xarr = np.array(x)
ind = np.where(xarr.reshape(xarr.size, 1) == np.array(x_ticks_labels))[1]
fig, ax = plt.subplots(1,1)
y = [i[0] for i in arr]
ax.scatter(ind,y, marker="o", color='red', label='L=1')
y = [i[1] for i in arr]
ax.scatter(ind,y, marker="o", color='blue', label='L=2')
y = [i[2] for i in arr]
ax.scatter(ind,y, marker="o", color='black', label='L=3')
y = [i[3] for i in arr]
ax.scatter(ind,y, marker="o", color='green', label='L=4')
y = [i[4] for i in arr]
ax.scatter(ind,y, marker="o", color='purple', label='L=5')
ax.set_yscale('log',base=10)
ax.set_xlabel('Circuit ID')
ax.set_ylabel('Expressibility')
ax.legend(loc='upper right')
ax.set_xticks(range(len(x_ticks_labels)))
ax.set_xticklabels(x_ticks_labels)
plt.show()
from matplotlib import pyplot as plt
fig.savefig('express_nshot10000_nparam1000.png')
def circuit1(qc,qr,theta,L,repeat):
#circuit 1
#theta is list of the parameters
#theta length is 8L
#L is the number of repeatation
# repeat will conjugate the first part and add next the the circuit for expressibility
# 0:No, 1: Repeat
count=0
for l in range(L):
for i in range(4):
qc.rx(theta[count],qr[i])
count=count+1
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
if repeat!=0:
qc.barrier(qr)
for l in range(L):
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
for i in range(4):
qc.rx(theta[count],qr[i])
count=count+1
return qc
def circuit2(qc,qr,theta,L,repeat):
#circuit 2
#theta is list of the parameters
#theta length is 8L
#L is the number of repeatation
# repeat will conjugate the first part and add next the the circuit for expressibility
# 0:No, 1: Repeat
count=0
for l in range(L):
for i in range(4):
qc.rx(theta[count],qr[i])
count=count+1
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
qc.cx(qr[3],qr[2])
qc.cx(qr[2],qr[1])
qc.cx(qr[1],qr[0])
if repeat!=0:
qc.barrier(qr)
for l in range(L):
qc.cx(qr[1],qr[0])
qc.cx(qr[2],qr[1])
qc.cx(qr[3],qr[2])
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
for i in range(4):
qc.rx(theta[count],qr[i])
count=count+1
return qc
def circuit3(qc,qr,theta,L,repeat):
#circuit 3
#theta is list of the parameters
#theta length is (11)L
#L is the number of repeatation
# repeat will conjugate the first part and add next the the circuit for expressibility
# 0:No, 1: Repeat
count=0
for l in range(L):
for i in range(4):
qc.rx(theta[count],qr[i])
count=count+1
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
qc.crz(theta[count],qr[3],qr[2])
count=count+1
qc.crz(theta[count],qr[2],qr[1])
count=count+1
qc.crz(theta[count],qr[1],qr[0])
count=count+1
if repeat!=0:
qc.barrier(qr)
for l in range(L):
qc.crz(theta[count],qr[1],qr[0])
count=count+1
qc.crz(theta[count],qr[2],qr[1])
count=count+1
qc.crz(theta[count],qr[3],qr[2])
count=count+1
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
for i in range(4):
qc.rx(theta[count],qr[i])
count=count+1
return qc
def circuit4(qc,qr,theta,L,repeat):
#circuit 4
#theta is list of the parameters
#theta length is (11)L
#L is the number of repeatation
# repeat will conjugate the first part and add next the the circuit for expressibility
# 0:No, 1: Repeat
count=0
for l in range(L):
for i in range(4):
qc.rx(theta[count],qr[i])
count=count+1
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
qc.crx(theta[count],qr[3],qr[2])
count=count+1
qc.crx(theta[count],qr[2],qr[1])
count=count+1
qc.crx(theta[count],qr[1],qr[0])
count=count+1
if repeat!=0:
qc.barrier(qr)
for l in range(L):
qc.crx(theta[count],qr[1],qr[0])
count=count+1
qc.crx(theta[count],qr[2],qr[1])
count=count+1
qc.crx(theta[count],qr[3],qr[2])
count=count+1
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
for i in range(4):
qc.rx(theta[count],qr[i])
count=count+1
return qc
def circuit5(qc,qr,theta,L,repeat):
#circuit 5
#theta is list of the parameters
#theta length is (28)L
#L is the number of repeatation
# repeat will conjugate the first part and add next the the circuit for expressibility
# 0:No, 1: Repeat
count=0
for l in range(L):
for i in range(4):
qc.rx(theta[count],qr[i])
count=count+1
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
for j in range(4):
for i in range(4):
if i!=j:
qc.crz(theta[count],qr[3-j],qr[3-i])
count=count+1
for i in range(4):
qc.rx(theta[count],qr[i])
count=count+1
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
if repeat!=0:
qc.barrier(qr)
for l in range(L):
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
for i in range(4):
qc.rx(theta[count],qr[i])
count=count+1
for j in range(4):
for i in range(4):
if i!=j:
qc.crz(theta[count],qr[j],qr[i])
count=count+1
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
for i in range(4):
qc.rx(theta[count],qr[i])
count=count+1
return qc
def circuit6(qc,qr,theta,L,repeat):
#circuit 6
#theta is list of the parameters
#theta length is (28)L
#L is the number of repeatation
# repeat will conjugate the first part and add next the the circuit for expressibility
# 0:No, 1: Repeat
count=0
for l in range(L):
for i in range(4):
qc.rx(theta[count],qr[i])
count=count+1
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
for j in range(4):
for i in range(4):
if i!=j:
qc.crx(theta[count],qr[3-j],qr[3-i])
count=count+1
for i in range(4):
qc.rx(theta[count],qr[i])
count=count+1
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
if repeat!=0:
qc.barrier(qr)
for l in range(L):
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
for i in range(4):
qc.rx(theta[count],qr[i])
count=count+1
for j in range(4):
for i in range(4):
if i!=j:
qc.crx(theta[count],qr[j],qr[i])
count=count+1
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
for i in range(4):
qc.rx(theta[count],qr[i])
count=count+1
return qc
def circuit7(qc,qr,theta,L,repeat):
#circuit 7
#theta is list of the parameters
#theta length is (19)L
#L is the number of repeatation
# repeat will conjugate the first part and add next the the circuit for expressibility
# 0:No, 1: Repeat
count=0
for l in range(L):
for i in range(4):
qc.rx(theta[count],qr[i])
count=count+1
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
qc.crz(theta[count],qr[1],qr[0])
count=count+1
qc.crz(theta[count],qr[3],qr[2])
count=count+1
for i in range(4):
qc.rx(theta[count],qr[i])
count=count+1
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
qc.crz(theta[count],qr[2],qr[1])
count=count+1
if repeat!=0:
qc.barrier(qr)
for l in range(L):
qc.crz(theta[count],qr[2],qr[1])
count=count+1
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
for i in range(4):
qc.rx(theta[count],qr[i])
count=count+1
qc.crz(theta[count],qr[3],qr[2])
count=count+1
qc.crz(theta[count],qr[1],qr[0])
count=count+1
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
for i in range(4):
qc.rx(theta[count],qr[i])
count=count+1
return qc
def circuit8(qc,qr,theta,L,repeat):
#circuit 8
#theta is list of the parameters
#theta length is (19)L
#L is the number of repeatation
# repeat will conjugate the first part and add next the the circuit for expressibility
# 0:No, 1: Repeat
count=0
for l in range(L):
for i in range(4):
qc.rx(theta[count],qr[i])
count=count+1
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
qc.crx(theta[count],qr[1],qr[0])
count=count+1
qc.crx(theta[count],qr[3],qr[2])
count=count+1
for i in range(4):
qc.rx(theta[count],qr[i])
count=count+1
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
qc.crx(theta[count],qr[2],qr[1])
count=count+1
if repeat!=0:
qc.barrier(qr)
for l in range(L):
qc.crx(theta[count],qr[2],qr[1])
count=count+1
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
for i in range(4):
qc.rx(theta[count],qr[i])
count=count+1
qc.crx(theta[count],qr[3],qr[2])
count=count+1
qc.crx(theta[count],qr[1],qr[0])
count=count+1
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
for i in range(4):
qc.rx(theta[count],qr[i])
count=count+1
return qc
def circuit9(qc,qr,theta,L,repeat):
#circuit 9
#theta is list of the parameters
#theta length is (4)L
#L is the number of repeatation
# repeat will conjugate the first part and add next the the circuit for expressibility
# 0:No, 1: Repeat
count=0
for l in range(L):
for i in range(4):
qc.h(qr[i])
qc.cz(qr[3],qr[2])
qc.cz(qr[2],qr[1])
qc.cz(qr[1],qr[0])
for i in range(4):
qc.rx(theta[count],qr[i])
count=count+1
if repeat!=0:
qc.barrier(qr)
for l in range(L):
for i in range(4):
qc.rx(theta[count],qr[i])
count=count+1
qc.cz(qr[1],qr[0])
qc.cz(qr[2],qr[1])
qc.cz(qr[3],qr[2])
for i in range(4):
qc.h(qr[i])
return qc
def circuit10(qc,qr,theta,L,repeat):
#circuit 10
#theta is list of the parameters
#theta length is (4)L+4
#L is the number of repeatation
# repeat will conjugate the first part and add next the the circuit for expressibility
# 0:No, 1: Repeat
count=0
for i in range(4):
qc.ry(theta[count],qr[i])
count=count+1
for l in range(L):
qc.cz(qr[3],qr[2])
qc.cz(qr[2],qr[1])
qc.cz(qr[1],qr[0])
qc.cz(qr[3],qr[0])
for i in range(4):
qc.ry(theta[count],qr[i])
count=count+1
if repeat!=0:
qc.barrier(qr)
for l in range(L):
for i in range(4):
qc.ry(theta[count],qr[i])
count=count+1
qc.cz(qr[3],qr[0])
qc.cz(qr[1],qr[0])
qc.cz(qr[2],qr[1])
qc.cz(qr[3],qr[2])
for i in range(4):
qc.ry(theta[count],qr[i])
count=count+1
return qc
def circuit11(qc,qr,theta,L,repeat):
#circuit 11
#theta is list of the parameters
#theta length is (12)L
#L is the number of repeatation
# repeat will conjugate the first part and add next the the circuit for expressibility
# 0:No, 1: Repeat
count=0
for l in range(L):
for i in range(4):
qc.ry(theta[count],qr[i])
count=count+1
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
qc.cx(qr[1],qr[0])
qc.cx(qr[3],qr[2])
qc.ry(theta[count],qr[1])
count=count+1
qc.ry(theta[count],qr[2])
count=count+1
qc.rz(theta[count],qr[1])
count=count+1
qc.rz(theta[count],qr[2])
count=count+1
qc.cx(qr[2],qr[1])
if repeat!=0:
qc.barrier(qr)
for l in range(L):
qc.cx(qr[2],qr[1])
qc.rz(theta[count],qr[2])
count=count+1
qc.rz(theta[count],qr[1])
count=count+1
qc.ry(theta[count],qr[2])
count=count+1
qc.ry(theta[count],qr[1])
count=count+1
qc.cx(qr[3],qr[2])
qc.cx(qr[1],qr[0])
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
for i in range(4):
qc.ry(theta[count],qr[i])
count=count+1
return qc
def circuit12(qc,qr,theta,L,repeat):
#circuit 12
#theta is list of the parameters
#theta length is (12)L
#L is the number of repeatation
# repeat will conjugate the first part and add next the the circuit for expressibility
# 0:No, 1: Repeat
count=0
for l in range(L):
for i in range(4):
qc.ry(theta[count],qr[i])
count=count+1
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
qc.cz(qr[1],qr[0])
qc.cz(qr[3],qr[2])
qc.ry(theta[count],qr[1])
count=count+1
qc.ry(theta[count],qr[2])
count=count+1
qc.rz(theta[count],qr[1])
count=count+1
qc.rz(theta[count],qr[2])
count=count+1
qc.cz(qr[2],qr[1])
if repeat!=0:
qc.barrier(qr)
for l in range(L):
qc.cz(qr[2],qr[1])
qc.rz(theta[count],qr[2])
count=count+1
qc.rz(theta[count],qr[1])
count=count+1
qc.ry(theta[count],qr[2])
count=count+1
qc.ry(theta[count],qr[1])
count=count+1
qc.cz(qr[3],qr[2])
qc.cz(qr[1],qr[0])
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
for i in range(4):
qc.ry(theta[count],qr[i])
count=count+1
return qc
def circuit13(qc,qr,theta,L,repeat):
#circuit 13
#theta is list of the parameters
#theta length is (16)L
#L is the number of repeatation
# repeat will conjugate the first part and add next the the circuit for expressibility
# 0:No, 1: Repeat
count=0
for l in range(L):
for i in range(4):
qc.ry(theta[count],qr[i])
count=count+1
qc.crz(theta[count],qr[3],qr[0])
count=count+1
qc.crz(theta[count],qr[2],qr[3])
count=count+1
qc.crz(theta[count],qr[1],qr[2])
count=count+1
qc.crz(theta[count],qr[0],qr[1])
count=count+1
for i in range(4):
qc.ry(theta[count],qr[i])
count=count+1
qc.crz(theta[count],qr[3],qr[2])
count=count+1
qc.crz(theta[count],qr[0],qr[3])
count=count+1
qc.crz(theta[count],qr[1],qr[0])
count=count+1
qc.crz(theta[count],qr[2],qr[1])
count=count+1
if repeat!=0:
qc.barrier(qr)
for l in range(L):
qc.crz(theta[count],qr[2],qr[1])
count=count+1
qc.crz(theta[count],qr[1],qr[0])
count=count+1
qc.crz(theta[count],qr[0],qr[3])
count=count+1
qc.crz(theta[count],qr[3],qr[2])
count=count+1
for i in range(4):
qc.ry(theta[count],qr[i])
count=count+1
qc.crz(theta[count],qr[0],qr[1])
count=count+1
qc.crz(theta[count],qr[1],qr[2])
count=count+1
qc.crz(theta[count],qr[2],qr[3])
count=count+1
qc.crz(theta[count],qr[3],qr[0])
count=count+1
for i in range(4):
qc.ry(theta[count],qr[i])
count=count+1
return qc
def circuit14(qc,qr,theta,L,repeat):
#circuit 14
#theta is list of the parameters
#theta length is (16)L
#L is the number of repeatation
# repeat will conjugate the first part and add next the the circuit for expressibility
# 0:No, 1: Repeat
count=0
for l in range(L):
for i in range(4):
qc.ry(theta[count],qr[i])
count=count+1
qc.crx(theta[count],qr[3],qr[0])
count=count+1
qc.crx(theta[count],qr[2],qr[3])
count=count+1
qc.crx(theta[count],qr[1],qr[2])
count=count+1
qc.crx(theta[count],qr[0],qr[1])
count=count+1
for i in range(4):
qc.ry(theta[count],qr[i])
count=count+1
qc.crx(theta[count],qr[3],qr[2])
count=count+1
qc.crx(theta[count],qr[0],qr[3])
count=count+1
qc.crx(theta[count],qr[1],qr[0])
count=count+1
qc.crx(theta[count],qr[2],qr[1])
count=count+1
if repeat!=0:
qc.barrier(qr)
for l in range(L):
qc.crx(theta[count],qr[2],qr[1])
count=count+1
qc.crx(theta[count],qr[1],qr[0])
count=count+1
qc.crx(theta[count],qr[0],qr[3])
count=count+1
qc.crx(theta[count],qr[3],qr[2])
count=count+1
for i in range(4):
qc.ry(theta[count],qr[i])
count=count+1
qc.crx(theta[count],qr[0],qr[1])
count=count+1
qc.crx(theta[count],qr[1],qr[2])
count=count+1
qc.crx(theta[count],qr[2],qr[3])
count=count+1
qc.crx(theta[count],qr[3],qr[0])
count=count+1
for i in range(4):
qc.ry(theta[count],qr[i])
count=count+1
return qc
def circuit15(qc,qr,theta,L,repeat):
#circuit 15
#theta is list of the parameters
#theta length is (8)L
#L is the number of repeatation
# repeat will conjugate the first part and add next the the circuit for expressibility
# 0:No, 1: Repeat
count=0
for l in range(L):
for i in range(4):
qc.ry(theta[count],qr[i])
count=count+1
qc.cx(qr[3],qr[0])
qc.cx(qr[2],qr[3])
qc.cx(qr[1],qr[2])
qc.cx(qr[0],qr[1])
for i in range(4):
qc.ry(theta[count],qr[i])
count=count+1
qc.cx(qr[3],qr[2])
qc.cx(qr[0],qr[3])
qc.cx(qr[1],qr[0])
qc.cx(qr[2],qr[1])
if repeat!=0:
qc.barrier(qr)
for l in range(L):
qc.cx(qr[2],qr[1])
qc.cx(qr[1],qr[0])
qc.cx(qr[0],qr[3])
qc.cx(qr[3],qr[2])
for i in range(4):
qc.ry(theta[count],qr[i])
count=count+1
qc.cx(qr[0],qr[1])
qc.cx(qr[1],qr[2])
qc.cx(qr[2],qr[3])
qc.cx(qr[3],qr[0])
for i in range(4):
qc.ry(theta[count],qr[i])
count=count+1
return qc
def circuit16(qc,qr,theta,L,repeat):
#circuit 16
#theta is list of the parameters
#theta length is (11)L
#L is the number of repeatation
# repeat will conjugate the first part and add next the the circuit for expressibility
# 0:No, 1: Repeat
count=0
for l in range(L):
for i in range(4):
qc.rx(theta[count],qr[i])
count=count+1
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
qc.crz(theta[count],qr[1],qr[0])
count=count+1
qc.crz(theta[count],qr[3],qr[2])
count=count+1
qc.crz(theta[count],qr[2],qr[1])
count=count+1
if repeat!=0:
qc.barrier(qr)
for l in range(L):
qc.crz(theta[count],qr[2],qr[1])
count=count+1
qc.crz(theta[count],qr[3],qr[2])
count=count+1
qc.crz(theta[count],qr[1],qr[0])
count=count+1
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
for i in range(4):
qc.rx(theta[count],qr[i])
count=count+1
return qc
def circuit17(qc,qr,theta,L,repeat):
#circuit 17
#theta is list of the parameters
#theta length is (11)L
#L is the number of repeatation
# repeat will conjugate the first part and add next the the circuit for expressibility
# 0:No, 1: Repeat
count=0
for l in range(L):
for i in range(4):
qc.rx(theta[count],qr[i])
count=count+1
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
qc.crx(theta[count],qr[1],qr[0])
count=count+1
qc.crx(theta[count],qr[3],qr[2])
count=count+1
qc.crx(theta[count],qr[2],qr[1])
count=count+1
if repeat!=0:
qc.barrier(qr)
for l in range(L):
qc.crx(theta[count],qr[2],qr[1])
count=count+1
qc.crx(theta[count],qr[3],qr[2])
count=count+1
qc.crx(theta[count],qr[1],qr[0])
count=count+1
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
for i in range(4):
qc.rx(theta[count],qr[i])
count=count+1
return qc
def circuit18(qc,qr,theta,L,repeat):
#circuit 18
#theta is list of the parameters
#theta length is (12)L
#L is the number of repeatation
# repeat will conjugate the first part and add next the the circuit for expressibility
# 0:No, 1: Repeat
count=0
for l in range(L):
for i in range(4):
qc.rx(theta[count],qr[i])
count=count+1
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
qc.crz(theta[count],qr[3],qr[0])
count=count+1
qc.crz(theta[count],qr[2],qr[3])
count=count+1
qc.crz(theta[count],qr[1],qr[2])
count=count+1
qc.crz(theta[count],qr[0],qr[1])
count=count+1
if repeat!=0:
qc.barrier(qr)
for l in range(L):
qc.crz(theta[count],qr[0],qr[1])
count=count+1
qc.crz(theta[count],qr[1],qr[2])
count=count+1
qc.crz(theta[count],qr[2],qr[3])
count=count+1
qc.crz(theta[count],qr[3],qr[0])
count=count+1
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
for i in range(4):
qc.rx(theta[count],qr[i])
count=count+1
return qc
def circuit19(qc,qr,theta,L,repeat):
#circuit 1
#theta is list of the parameters
#theta length is (12)L
#L is the number of repeatation
# repeat will conjugate the first part and add next the the circuit for expressibility
# 0:No, 1: Repeat
count=0
for l in range(L):
for i in range(4):
qc.rx(theta[count],qr[i])
count=count+1
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
qc.crx(theta[count],qr[3],qr[0])
count=count+1
qc.crx(theta[count],qr[2],qr[3])
count=count+1
qc.crx(theta[count],qr[1],qr[2])
count=count+1
qc.crx(theta[count],qr[0],qr[1])
count=count+1
if repeat!=0:
qc.barrier(qr)
for l in range(L):
qc.crx(theta[count],qr[0],qr[1])
count=count+1
qc.crx(theta[count],qr[1],qr[2])
count=count+1
qc.crx(theta[count],qr[2],qr[3])
count=count+1
qc.crx(theta[count],qr[3],qr[0])
count=count+1
for i in range(4):
qc.rz(theta[count],qr[i])
count=count+1
for i in range(4):
qc.rx(theta[count],qr[i])
count=count+1
return qc
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.