text
stringlengths 4
4.46M
| id
stringlengths 13
126
| metadata
dict | __index_level_0__
int64 0
415
|
---|---|---|---|
---
deprecations_providers:
- |
The abstract base classes ``Provider`` and ``ProviderV1`` are now deprecated and will be removed in Qiskit 2.0.0.
The abstraction provided by these interface definitions were not providing a huge value. solely just the attributes
``name``, ``backends``, and a ``get_backend()``. A _provider_, as a concept, will continue existing as a collection
of backends. If you're implementing a provider currently you can adjust your
code by simply removing ``ProviderV1`` as the parent class of your
implementation. As part of this you probably would want to add an
implementation of ``get_backend`` for backwards compatibility. For example::
def get_backend(self, name=None, **kwargs):
backend = self.backends(name, **kwargs)
if len(backends) > 1:
raise QiskitBackendNotFoundError("More than one backend matches the criteria")
if not backends:
raise QiskitBackendNotFoundError("No backend matches the criteria")
return backends[0]
| qiskit/releasenotes/notes/1.1/deprecate_providerV1-ba17d7b4639d1cc5.yaml/0 | {
"file_path": "qiskit/releasenotes/notes/1.1/deprecate_providerV1-ba17d7b4639d1cc5.yaml",
"repo_id": "qiskit",
"token_count": 342
} | 300 |
---
fixes:
- |
Fixed a performance issue in the :func:`.qpy.load` function when
deserializing QPY payloads with large numbers of qubits or clbits in
a circuit.
| qiskit/releasenotes/notes/1.1/fix-performance-scaling-num-bits-qpy-37b5109a40cccc54.yaml/0 | {
"file_path": "qiskit/releasenotes/notes/1.1/fix-performance-scaling-num-bits-qpy-37b5109a40cccc54.yaml",
"repo_id": "qiskit",
"token_count": 59
} | 301 |
---
fixes:
- |
Fixed `qiskit.primitives.containers.observables_array.ObservablesArray.coerce()`
so that it returns a 0-d array when the input is a single, unnested observable.
Previously, it erroneously upgraded to a single dimension, with shape `(1,)`. | qiskit/releasenotes/notes/1.1/obs-array-coerce-0d-28b192fb3d004d4a.yaml/0 | {
"file_path": "qiskit/releasenotes/notes/1.1/obs-array-coerce-0d-28b192fb3d004d4a.yaml",
"repo_id": "qiskit",
"token_count": 87
} | 302 |
---
fixes:
- |
The internal handling of custom circuit calibrations and :class:`.InstructionDurations`
has been offloaded from the :func:`.transpile` function to the individual transpiler passes:
:class:`qiskit.transpiler.passes.scheduling.DynamicalDecoupling`,
:class:`qiskit.transpiler.passes.scheduling.padding.DynamicalDecoupling`. Before,
instruction durations from circuit calibrations would not be taken into account unless
they were manually incorporated into `instruction_durations` input argument, but the passes
that need it now analyze the circuit and pick the most relevant duration value according
to the following priority order: target > custom input > circuit calibrations.
- |
Fixed a bug in :func:`.transpile` where the ``num_processes`` argument would only be used
if ``dt`` or ``instruction_durations`` were provided. | qiskit/releasenotes/notes/1.1/rework-inst-durations-passes-28c78401682e22c0.yaml/0 | {
"file_path": "qiskit/releasenotes/notes/1.1/rework-inst-durations-passes-28c78401682e22c0.yaml",
"repo_id": "qiskit",
"token_count": 256
} | 303 |
---
features_circuits:
- |
:class:`.CircuitInstruction` and :class:`.DAGOpNode` each have new methods to query various
properties of their internal :class:`.Operation`, without necessarily needing to access it.
These methods are:
* :meth:`.CircuitInstruction.is_standard_gate` and :meth:`.DAGOpNode.is_standard_gate`,
* :meth:`.CircuitInstruction.is_controlled_gate` and :meth:`.DAGOpNode.is_controlled_gate`,
* :meth:`.CircuitInstruction.is_directive` and :meth:`.DAGOpNode.is_directive`,
* :meth:`.CircuitInstruction.is_control_flow` and :meth:`.DAGOpNode.is_control_flow`, and
* :meth:`.CircuitInstruction.is_parameterized` and :meth:`.DAGOpNode.is_parameterized`.
If applicable, using any of these methods is significantly faster than querying
:attr:`.CircuitInstruction.operation` or :attr:`.DAGOpNode.op` directly, especially if the
instruction or node represents a Qiskit standard gate. This is because the standard gates are
stored natively in Rust, and their Python representation is only created when requested.
| qiskit/releasenotes/notes/avoid-op-creation-804c0bed6c408911.yaml/0 | {
"file_path": "qiskit/releasenotes/notes/avoid-op-creation-804c0bed6c408911.yaml",
"repo_id": "qiskit",
"token_count": 353
} | 304 |
---
features_circuits:
- |
The `random_circuit` function from `qiskit.circuit.random.utils` has a new feature where
users can specify a distribution `num_operand_distribution` (a dict) that specifies the
ratio of 1-qubit, 2-qubit, 3-qubit, and 4-qubit gates in the random circuit. For example,
if `num_operand_distribution = {1: 0.25, 2: 0.25, 3: 0.25, 4: 0.25}` is passed to the function
then the generated circuit will have approximately 25% of 1-qubit, 2-qubit, 3-qubit, and
4-qubit gates (The order in which the dictionary is passed does not matter i.e. you can specify
`num_operand_distribution = {3: 0.5, 1: 0.0, 4: 0.3, 2: 0.2}` and the function will still work
as expected). Also it should be noted that the if `num_operand_distribution` is not specified
then `max_operands` will default to 4 and a random circuit with a random gate distribution will
be generated. If both `num_operand_distribution` and `max_operands` are specified at the same
time then `num_operand_distribution` will be used to generate the random circuit.
Example usage::
from qiskit.circuit.random import random_circuit
circ = random_circuit(num_qubits=6, depth=5, num_operand_distribution = {1: 0.25, 2: 0.25, 3: 0.25, 4: 0.25})
circ.draw(output='mpl')
| qiskit/releasenotes/notes/extended-random-circuits-049b67cce39003f4.yaml/0 | {
"file_path": "qiskit/releasenotes/notes/extended-random-circuits-049b67cce39003f4.yaml",
"repo_id": "qiskit",
"token_count": 472
} | 305 |
---
fixes:
- |
The :attr:`.QuantumCircuit.parameters` attribute will now correctly be empty
when using :meth:`.QuantumCircuit.copy_empty_like` on a parametric circuit.
Previously, an internal cache would be copied over without invalidation.
Fix `#12617 <https://github.com/Qiskit/qiskit/issues/12617>`__.
| qiskit/releasenotes/notes/fix-parameter-cache-05eac2f24477ccb8.yaml/0 | {
"file_path": "qiskit/releasenotes/notes/fix-parameter-cache-05eac2f24477ccb8.yaml",
"repo_id": "qiskit",
"token_count": 109
} | 306 |
---
features_transpiler:
- |
A new argument ``qubits_initially_zero`` has been added to :func:`qiskit.compiler.transpile`,
:func:`.generate_preset_pass_manager`, and to :class:`~.PassManagerConfig`.
If set to ``True``, the qubits are assumed to be initially in the state :math:`|0\rangle`,
potentially allowing additional optimization opportunities for individual transpiler passes.
- |
The constructor for :class:`.HighLevelSynthesis` transpiler pass now accepts an
additional argument ``qubits_initially_zero``. If set to ``True``, the pass assumes that the
qubits are initially in the state :math:`|0\rangle`. In addition, the pass keeps track of
clean and dirty auxiliary qubits throughout the run, and passes this information to plugins
via kwargs ``num_clean_ancillas`` and ``num_dirty_ancillas``.
upgrade_transpiler:
- |
The :func:`~qiskit.compiler.transpile` now assumes that the qubits are initially in the state
:math:`|0\rangle`. To avoid this assumption, one can set the argument ``qubits_initially_zero``
to ``False``.
| qiskit/releasenotes/notes/hls-with-ancillas-d6792b41dfcf4aac.yaml/0 | {
"file_path": "qiskit/releasenotes/notes/hls-with-ancillas-d6792b41dfcf4aac.yaml",
"repo_id": "qiskit",
"token_count": 343
} | 307 |
---
features_circuits:
- |
The :meth:`~.QuantumCircuit.count_ops` method in :class:`.QuantumCircuit`
has been re-written in Rust. It now runs between 3 and 9 times faster.
| qiskit/releasenotes/notes/port-countops-method-3ad362c20b13182c.yaml/0 | {
"file_path": "qiskit/releasenotes/notes/port-countops-method-3ad362c20b13182c.yaml",
"repo_id": "qiskit",
"token_count": 67
} | 308 |
---
features:
- |
Implemented :class:`.UniformSuperpositionGate` class, which allows
the creation of a uniform superposition state using
the Shukla-Vedula algorithm. This feature facilitates the
creation of quantum circuits that produce a uniform superposition
state :math:`\frac{1}{\sqrt{M}} \sum_{j=0}^{M-1} |j\rangle`, where
:math:`M` is a positive integer representing the number of
computational basis states with an amplitude of
:math:`\frac{1}{\sqrt{M}}`. This implementation supports the
efficient creation of uniform superposition states,
requiring only :math:`O(\log_2 (M))` qubits and
:math:`O(\log_2 (M))` gates. Usage example:
.. code-block:: python
from qiskit import QuantumCircuit
from qiskit.circuit.library.data_preparation import UniformSuperpositionGate
M = 5
num_qubits = 3
usp_gate = UniformSuperpositionGate(M, num_qubits)
qc = QuantumCircuit(num_qubits)
qc.append(usp_gate, list(range(num_qubits)))
qc.draw()
| qiskit/releasenotes/notes/uniform-superposition-gate-3bd95ffdf05ef18c.yaml/0 | {
"file_path": "qiskit/releasenotes/notes/uniform-superposition-gate-3bd95ffdf05ef18c.yaml",
"repo_id": "qiskit",
"token_count": 389
} | 309 |
// Name of Experiment: pea_3*pi/8 v3
OPENQASM 2.0;
include "qelib1.inc";
qreg q[5];
creg c[4];
gate cu1fixed (a) c,t {
u1 (-a) t;
cx c,t;
u1 (a) t;
cx c,t;
}
gate cu c,t {
cu1fixed (3*pi/8) c,t;
}
h q[0];
h q[1];
h q[2];
h q[3];
cu q[3],q[4];
cu q[2],q[4];
cu q[2],q[4];
cu q[1],q[4];
cu q[1],q[4];
cu q[1],q[4];
cu q[1],q[4];
cu q[0],q[4];
cu q[0],q[4];
cu q[0],q[4];
cu q[0],q[4];
cu q[0],q[4];
cu q[0],q[4];
cu q[0],q[4];
cu q[0],q[4];
h q[0];
cu1(-pi/2) q[0],q[1];
h q[1];
cu1(-pi/4) q[0],q[2];
cu1(-pi/2) q[1],q[2];
h q[2];
cu1(-pi/8) q[0],q[3];
cu1(-pi/4) q[1],q[3];
cu1(-pi/2) q[2],q[3];
h q[3];
measure q[0] -> c[0];
measure q[1] -> c[1];
measure q[2] -> c[2];
measure q[3] -> c[3];
| qiskit/test/benchmarks/qasm/pea_3_pi_8.qasm/0 | {
"file_path": "qiskit/test/benchmarks/qasm/pea_3_pi_8.qasm",
"repo_id": "qiskit",
"token_count": 463
} | 310 |
# This code is part of Qiskit.
#
# (C) Copyright IBM 2023
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
# pylint: disable=invalid-name,missing-docstring
# pylint: disable=attribute-defined-outside-init
from qiskit import transpile
from qiskit.circuit.library.standard_gates import XGate
from qiskit.transpiler import CouplingMap, PassManager
from qiskit.transpiler import InstructionDurations
from qiskit.transpiler.passes import (
TimeUnitConversion,
ASAPScheduleAnalysis,
ALAPScheduleAnalysis,
PadDynamicalDecoupling,
)
from qiskit.converters import circuit_to_dag
from .utils import random_circuit
class SchedulingPassBenchmarks:
params = ([5, 10, 20], [500, 1000])
param_names = ["n_qubits", "depth"]
timeout = 300
def setup(self, n_qubits, depth):
seed = 42
self.circuit = random_circuit(
n_qubits, depth, measure=True, conditional=False, reset=False, seed=seed, max_operands=2
)
self.basis_gates = ["rz", "sx", "x", "cx", "id", "reset"]
self.cmap = [
[0, 1],
[1, 0],
[1, 2],
[1, 6],
[2, 1],
[2, 3],
[3, 2],
[3, 4],
[3, 8],
[4, 3],
[5, 6],
[5, 10],
[6, 1],
[6, 5],
[6, 7],
[7, 6],
[7, 8],
[7, 12],
[8, 3],
[8, 7],
[8, 9],
[9, 8],
[9, 14],
[10, 5],
[10, 11],
[11, 10],
[11, 12],
[11, 16],
[12, 7],
[12, 11],
[12, 13],
[13, 12],
[13, 14],
[13, 18],
[14, 9],
[14, 13],
[15, 16],
[16, 11],
[16, 15],
[16, 17],
[17, 16],
[17, 18],
[18, 13],
[18, 17],
[18, 19],
[19, 18],
]
self.coupling_map = CouplingMap(self.cmap)
self.transpiled_circuit = transpile(
self.circuit,
basis_gates=self.basis_gates,
coupling_map=self.coupling_map,
optimization_level=1,
)
self.dag = circuit_to_dag(self.transpiled_circuit)
self.durations = InstructionDurations(
[
("rz", None, 0),
("id", None, 160),
("sx", None, 160),
("x", None, 160),
("cx", None, 800),
("measure", None, 3200),
("reset", None, 3600),
],
dt=1e-9,
)
def time_time_unit_conversion_pass(self, _, __):
TimeUnitConversion(self.durations).run(self.dag)
def time_alap_schedule_pass(self, _, __):
dd_sequence = [XGate(), XGate()]
pm = PassManager(
[
ALAPScheduleAnalysis(self.durations),
PadDynamicalDecoupling(self.durations, dd_sequence),
]
)
pm.run(self.transpiled_circuit)
def time_asap_schedule_pass(self, _, __):
dd_sequence = [XGate(), XGate()]
pm = PassManager(
[
ASAPScheduleAnalysis(self.durations),
PadDynamicalDecoupling(self.durations, dd_sequence),
]
)
pm.run(self.transpiled_circuit)
| qiskit/test/benchmarks/scheduling_passes.py/0 | {
"file_path": "qiskit/test/benchmarks/scheduling_passes.py",
"repo_id": "qiskit",
"token_count": 2081
} | 311 |
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test adder circuits."""
import unittest
import numpy as np
from ddt import ddt, data, unpack
from qiskit.circuit import QuantumCircuit
from qiskit.quantum_info import Statevector
from qiskit.circuit.library import CDKMRippleCarryAdder, DraperQFTAdder, VBERippleCarryAdder
from test import QiskitTestCase # pylint: disable=wrong-import-order
@ddt
class TestAdder(QiskitTestCase):
"""Test the adder circuits."""
def assertAdditionIsCorrect(
self, num_state_qubits: int, adder: QuantumCircuit, inplace: bool, kind: str
):
"""Assert that adder correctly implements the summation.
This test prepares a equal superposition state in both input registers, then performs
the addition on the superposition and checks that the output state is the expected
superposition of all possible additions.
Args:
num_state_qubits: The number of bits in the numbers that are added.
adder: The circuit performing the addition of two numbers with ``num_state_qubits``
bits.
inplace: If True, compare against an inplace addition where the result is written into
the second register plus carry qubit. If False, assume that the result is written
into a third register of appropriate size.
kind: TODO
"""
circuit = QuantumCircuit(*adder.qregs)
# create equal superposition
if kind == "full":
num_superpos_qubits = 2 * num_state_qubits + 1
else:
num_superpos_qubits = 2 * num_state_qubits
circuit.h(range(num_superpos_qubits))
# apply adder circuit
circuit.compose(adder, inplace=True)
# obtain the statevector and the probabilities, we don't trace out the ancilla qubits
# as we verify that all ancilla qubits have been uncomputed to state 0 again
statevector = Statevector(circuit)
probabilities = statevector.probabilities()
pad = "0" * circuit.num_ancillas # state of the ancillas
# compute the expected results
expectations = np.zeros_like(probabilities)
num_bits_sum = num_state_qubits + 1
# iterate over all possible inputs
for x in range(2**num_state_qubits):
for y in range(2**num_state_qubits):
# compute the sum
if kind == "full":
additions = [x + y, 1 + x + y]
elif kind == "half":
additions = [x + y]
else:
additions = [(x + y) % (2**num_state_qubits)]
# compute correct index in statevector
bin_x = bin(x)[2:].zfill(num_state_qubits)
bin_y = bin(y)[2:].zfill(num_state_qubits)
for i, addition in enumerate(additions):
bin_res = bin(addition)[2:].zfill(num_bits_sum)
if kind == "full":
cin = str(i)
bin_index = (
pad + bin_res + bin_x + cin
if inplace
else pad + bin_res + bin_y + bin_x + cin
)
else:
bin_index = (
pad + bin_res + bin_x if inplace else pad + bin_res + bin_y + bin_x
)
index = int(bin_index, 2)
expectations[index] += 1 / 2**num_superpos_qubits
np.testing.assert_array_almost_equal(expectations, probabilities)
@data(
(3, CDKMRippleCarryAdder, True),
(5, CDKMRippleCarryAdder, True),
(3, CDKMRippleCarryAdder, True, "fixed"),
(5, CDKMRippleCarryAdder, True, "fixed"),
(1, CDKMRippleCarryAdder, True, "full"),
(3, CDKMRippleCarryAdder, True, "full"),
(5, CDKMRippleCarryAdder, True, "full"),
(3, DraperQFTAdder, True),
(5, DraperQFTAdder, True),
(3, DraperQFTAdder, True, "fixed"),
(5, DraperQFTAdder, True, "fixed"),
(1, VBERippleCarryAdder, True, "full"),
(3, VBERippleCarryAdder, True, "full"),
(5, VBERippleCarryAdder, True, "full"),
(1, VBERippleCarryAdder, True),
(2, VBERippleCarryAdder, True),
(5, VBERippleCarryAdder, True),
(1, VBERippleCarryAdder, True, "fixed"),
(2, VBERippleCarryAdder, True, "fixed"),
(4, VBERippleCarryAdder, True, "fixed"),
)
@unpack
def test_summation(self, num_state_qubits, adder, inplace, kind="half"):
"""Test summation for all implemented adders."""
adder = adder(num_state_qubits, kind=kind)
self.assertAdditionIsCorrect(num_state_qubits, adder, inplace, kind)
@data(CDKMRippleCarryAdder, DraperQFTAdder, VBERippleCarryAdder)
def test_raises_on_wrong_num_bits(self, adder):
"""Test an error is raised for a bad number of qubits."""
with self.assertRaises(ValueError):
_ = adder(-1)
if __name__ == "__main__":
unittest.main()
| qiskit/test/python/circuit/library/test_adders.py/0 | {
"file_path": "qiskit/test/python/circuit/library/test_adders.py",
"repo_id": "qiskit",
"token_count": 2526
} | 312 |
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Tests for LinearFunction class."""
import unittest
import numpy as np
from ddt import ddt, data
from qiskit.circuit import QuantumCircuit
from qiskit.quantum_info import Clifford
from qiskit.circuit.library.standard_gates import CXGate, SwapGate
from qiskit.circuit.library.generalized_gates import LinearFunction, PermutationGate
from qiskit.circuit.exceptions import CircuitError
from qiskit.synthesis.linear import random_invertible_binary_matrix
from qiskit.quantum_info.operators import Operator
from test import QiskitTestCase # pylint: disable=wrong-import-order
def random_linear_circuit(
num_qubits,
num_gates,
seed=None,
barrier=False,
delay=False,
permutation=False,
linear=False,
clifford=False,
recursion_depth=0,
):
"""Generate a pseudo random linear circuit."""
if num_qubits == 0:
raise CircuitError("Cannot construct a random linear circuit with 0 qubits.")
circ = QuantumCircuit(num_qubits)
instructions = ["cx", "swap"] if num_qubits >= 2 else []
if barrier:
instructions.append("barrier")
if delay:
instructions.append("delay")
if permutation:
instructions.append("permutation")
if linear:
instructions.append("linear")
if clifford:
instructions.append("clifford")
if recursion_depth > 0:
instructions.append("nested")
if not instructions:
# Return the empty circuit if there are no instructions to choose from.
return circ
if isinstance(seed, np.random.Generator):
rng = seed
else:
rng = np.random.default_rng(seed)
name_samples = rng.choice(instructions, num_gates)
for name in name_samples:
if name == "cx":
qargs = rng.choice(range(num_qubits), 2, replace=False).tolist()
circ.cx(*qargs)
elif name == "swap":
qargs = rng.choice(range(num_qubits), 2, replace=False).tolist()
circ.swap(*qargs)
elif name == "barrier":
nqargs = rng.choice(range(1, num_qubits + 1))
qargs = rng.choice(range(num_qubits), nqargs, replace=False).tolist()
circ.barrier(qargs)
elif name == "delay":
qarg = rng.choice(range(num_qubits))
circ.delay(100, qarg)
elif name == "linear":
nqargs = rng.choice(range(1, num_qubits + 1))
qargs = rng.choice(range(num_qubits), nqargs, replace=False).tolist()
seed = rng.integers(100000, size=1, dtype=np.uint64)[0]
mat = random_invertible_binary_matrix(nqargs, seed=seed)
circ.append(LinearFunction(mat), qargs)
elif name == "permutation":
nqargs = rng.choice(range(1, num_qubits + 1))
pattern = list(np.random.permutation(range(nqargs)))
qargs = rng.choice(range(num_qubits), nqargs, replace=False).tolist()
circ.append(PermutationGate(pattern), qargs)
elif name == "clifford":
# In order to construct a Clifford that corresponds to a linear function,
# we construct a small random linear circuit, and convert it to Clifford.
nqargs = rng.choice(range(1, num_qubits + 1))
qargs = rng.choice(range(num_qubits), nqargs, replace=False).tolist()
subcirc = random_linear_circuit(
nqargs,
num_gates=5,
seed=rng,
barrier=False,
delay=False,
permutation=False,
linear=False,
clifford=False,
recursion_depth=0,
)
cliff = Clifford(subcirc)
circ.append(cliff, qargs)
elif name == "nested":
nqargs = rng.choice(range(1, num_qubits + 1))
qargs = rng.choice(range(num_qubits), nqargs, replace=False).tolist()
subcirc = random_linear_circuit(
nqargs,
num_gates=5,
seed=rng,
barrier=False,
delay=False,
permutation=False,
linear=False,
clifford=False,
recursion_depth=recursion_depth - 1,
)
circ.append(subcirc, qargs)
return circ
@ddt
class TestLinearFunctions(QiskitTestCase):
"""Tests for clifford append gate functions."""
@data(2, 3, 4, 5, 6, 7, 8)
def test_conversion_to_matrix_and_back(self, num_qubits):
"""Test correctness of first constructing a linear function from a linear quantum circuit,
and then synthesizing this linear function to a quantum circuit."""
rng = np.random.default_rng(1234)
for num_gates in [0, 5, 5 * num_qubits]:
seeds = rng.integers(100000, size=10, dtype=np.uint64)
for seed in seeds:
# create a random linear circuit
linear_circuit = random_linear_circuit(num_qubits, num_gates, seed=seed)
self.assertIsInstance(linear_circuit, QuantumCircuit)
# convert it to a linear function
linear_function = LinearFunction(linear_circuit, validate_input=True)
# check that the internal matrix has right dimensions
self.assertEqual(linear_function.linear.shape, (num_qubits, num_qubits))
# synthesize linear function
synthesized_linear_function = linear_function.definition
self.assertIsInstance(synthesized_linear_function, QuantumCircuit)
# check that the synthesized linear function only contains CX and SWAP gates
for instruction in synthesized_linear_function.data:
self.assertIsInstance(instruction.operation, (CXGate, SwapGate))
# check equivalence to the original function
self.assertEqual(Operator(linear_circuit), Operator(synthesized_linear_function))
@data(2, 3, 4, 5, 6, 7, 8)
def test_conversion_to_linear_function_and_back(self, num_qubits):
"""Test correctness of first synthesizing a linear circuit from a linear function,
and then converting this linear circuit to a linear function."""
rng = np.random.default_rng(5678)
seeds = rng.integers(100000, size=10, dtype=np.uint64)
for seed in seeds:
# create a random invertible binary matrix
binary_matrix = random_invertible_binary_matrix(num_qubits, seed=seed)
# create a linear function with this matrix
linear_function = LinearFunction(binary_matrix, validate_input=True)
self.assertTrue(np.all(linear_function.linear == binary_matrix))
# synthesize linear function
synthesized_circuit = linear_function.definition
self.assertIsInstance(synthesized_circuit, QuantumCircuit)
# check that the synthesized linear function only contains CX and SWAP gates
for instruction in synthesized_circuit.data:
self.assertIsInstance(instruction.operation, (CXGate, SwapGate))
# construct a linear function out of this linear circuit
synthesized_linear_function = LinearFunction(synthesized_circuit, validate_input=True)
# check equivalence of the two linear matrices
self.assertTrue(np.all(synthesized_linear_function.linear == binary_matrix))
def test_patel_markov_hayes(self):
"""Checks the explicit example from Patel-Markov-Hayes's paper."""
# This code is adapted from test_cnot_phase_synthesis.py
binary_matrix = [
[1, 1, 0, 0, 0, 0],
[1, 0, 0, 1, 1, 0],
[0, 1, 0, 0, 1, 0],
[1, 1, 1, 1, 1, 1],
[1, 1, 0, 1, 1, 1],
[0, 0, 1, 1, 1, 0],
]
# Construct linear function from matrix: here, we copy a matrix
linear_function_from_matrix = LinearFunction(binary_matrix, validate_input=True)
# Create the circuit displayed above:
linear_circuit = QuantumCircuit(6)
linear_circuit.cx(4, 3)
linear_circuit.cx(5, 2)
linear_circuit.cx(1, 0)
linear_circuit.cx(3, 1)
linear_circuit.cx(4, 2)
linear_circuit.cx(4, 3)
linear_circuit.cx(5, 4)
linear_circuit.cx(2, 3)
linear_circuit.cx(3, 2)
linear_circuit.cx(3, 5)
linear_circuit.cx(2, 4)
linear_circuit.cx(1, 2)
linear_circuit.cx(0, 1)
linear_circuit.cx(0, 4)
linear_circuit.cx(0, 3)
# Construct linear function from matrix: we build a matrix
linear_function_from_circuit = LinearFunction(linear_circuit, validate_input=True)
# Compare the matrices
self.assertTrue(
np.all(linear_function_from_circuit.linear == linear_function_from_matrix.linear)
)
self.assertTrue(
Operator(linear_function_from_matrix.definition) == Operator(linear_circuit)
)
def test_bad_matrix_non_rectangular(self):
"""Tests that an error is raised if the matrix is not rectangular."""
mat = [[1, 1, 0, 0], [1, 0, 0], [0, 1, 0, 0], [1, 1, 1, 1]]
with self.assertRaises(CircuitError):
LinearFunction(mat)
def test_bad_matrix_non_square(self):
"""Tests that an error is raised if the matrix is not square."""
mat = [[1, 1, 0], [1, 0, 0], [0, 1, 0], [1, 1, 1]]
with self.assertRaises(CircuitError):
LinearFunction(mat)
def test_bad_matrix_non_two_dimensional(self):
"""Tests that an error is raised if the matrix is not two-dimensional."""
mat = [1, 0, 0, 1, 0]
with self.assertRaises(CircuitError):
LinearFunction(mat)
def test_bad_matrix_non_invertible(self):
"""Tests that an error is raised if the matrix is not invertible."""
mat = [[1, 0, 0], [0, 1, 1], [1, 1, 1]]
with self.assertRaises(CircuitError):
LinearFunction(mat, validate_input=True)
def test_bad_circuit_non_linear(self):
"""Tests that an error is raised if a circuit is not linear."""
non_linear_circuit = QuantumCircuit(4)
non_linear_circuit.cx(0, 1)
non_linear_circuit.swap(2, 3)
non_linear_circuit.h(2)
non_linear_circuit.swap(1, 2)
non_linear_circuit.cx(1, 3)
with self.assertRaises(CircuitError):
LinearFunction(non_linear_circuit)
def test_is_permutation(self):
"""Tests that a permutation is detected correctly."""
mat = [[1, 0, 0, 0], [0, 0, 0, 1], [0, 1, 0, 0], [0, 0, 1, 0]]
linear_function = LinearFunction(mat)
self.assertTrue(linear_function.is_permutation())
def test_permutation_pattern(self):
"""Tests that a permutation pattern is returned correctly when
the linear function is a permutation."""
mat = [[1, 0, 0, 0], [0, 0, 0, 1], [0, 1, 0, 0], [0, 0, 1, 0]]
linear_function = LinearFunction(mat)
pattern = linear_function.permutation_pattern()
self.assertIsInstance(pattern, np.ndarray)
def test_is_not_permutation(self):
"""Tests that a permutation is detected correctly."""
mat = [[1, 0, 0, 0], [0, 0, 0, 1], [0, 1, 0, 1], [0, 0, 1, 0]]
linear_function = LinearFunction(mat)
self.assertFalse(linear_function.is_permutation())
def test_no_permutation_pattern(self):
"""Tests that an error is raised when when
the linear function is not a permutation."""
mat = [[1, 0, 0, 0], [0, 0, 0, 1], [0, 1, 0, 1], [0, 0, 1, 0]]
linear_function = LinearFunction(mat)
with self.assertRaises(CircuitError):
linear_function.permutation_pattern()
def test_original_definition(self):
"""Tests that when a linear function is constructed from
a QuantumCircuit, it saves the original definition."""
linear_circuit = QuantumCircuit(4)
linear_circuit.cx(0, 1)
linear_circuit.cx(1, 2)
linear_circuit.cx(2, 3)
linear_function = LinearFunction(linear_circuit)
self.assertIsNotNone(linear_function.original_circuit)
def test_no_original_definition(self):
"""Tests that when a linear function is constructed from
a matrix, there is no original definition."""
mat = [[1, 0, 0, 0], [0, 0, 0, 1], [0, 1, 0, 0], [0, 0, 1, 0]]
linear_function = LinearFunction(mat)
self.assertIsNone(linear_function.original_circuit)
def test_barriers(self):
"""Test constructing linear functions from circuits with barriers."""
linear_circuit_1 = QuantumCircuit(4)
linear_circuit_1.cx(0, 1)
linear_circuit_1.cx(1, 2)
linear_circuit_1.cx(2, 3)
linear_function_1 = LinearFunction(linear_circuit_1)
linear_circuit_2 = QuantumCircuit(4)
linear_circuit_2.barrier()
linear_circuit_2.cx(0, 1)
linear_circuit_2.cx(1, 2)
linear_circuit_2.barrier()
linear_circuit_2.cx(2, 3)
linear_circuit_2.barrier()
linear_function_2 = LinearFunction(linear_circuit_2)
self.assertTrue(np.all(linear_function_1.linear == linear_function_2.linear))
self.assertEqual(linear_function_1, linear_function_2)
def test_delays(self):
"""Test constructing linear functions from circuits with delays."""
linear_circuit_1 = QuantumCircuit(4)
linear_circuit_1.cx(0, 1)
linear_circuit_1.cx(1, 2)
linear_circuit_1.cx(2, 3)
linear_function_1 = LinearFunction(linear_circuit_1)
linear_circuit_2 = QuantumCircuit(4)
linear_circuit_2.delay(500, 1)
linear_circuit_2.cx(0, 1)
linear_circuit_2.cx(1, 2)
linear_circuit_2.delay(100, 0)
linear_circuit_2.cx(2, 3)
linear_circuit_2.delay(200, 2)
linear_function_2 = LinearFunction(linear_circuit_2)
self.assertTrue(np.all(linear_function_1.linear == linear_function_2.linear))
self.assertEqual(linear_function_1, linear_function_2)
def test_eq(self):
"""Test that checking equality between two linear functions only depends on matrices."""
linear_circuit_1 = QuantumCircuit(3)
linear_circuit_1.cx(0, 1)
linear_circuit_1.cx(0, 2)
linear_function_1 = LinearFunction(linear_circuit_1)
linear_circuit_2 = QuantumCircuit(3)
linear_circuit_2.cx(0, 2)
linear_circuit_2.cx(0, 1)
linear_function_2 = LinearFunction(linear_circuit_1)
self.assertTrue(np.all(linear_function_1.linear == linear_function_2.linear))
self.assertEqual(linear_function_1, linear_function_2)
def test_extend_with_identity(self):
"""Test extending linear function with identity."""
lf = LinearFunction([[1, 1, 1], [0, 1, 1], [0, 0, 1]])
extended1 = lf.extend_with_identity(4, [0, 1, 2])
expected1 = LinearFunction([[1, 1, 1, 0], [0, 1, 1, 0], [0, 0, 1, 0], [0, 0, 0, 1]])
self.assertEqual(extended1, expected1)
extended2 = lf.extend_with_identity(4, [1, 2, 3])
expected2 = LinearFunction([[1, 0, 0, 0], [0, 1, 1, 1], [0, 0, 1, 1], [0, 0, 0, 1]])
self.assertEqual(extended2, expected2)
extended3 = lf.extend_with_identity(4, [3, 2, 1])
expected3 = LinearFunction([[1, 0, 0, 0], [0, 1, 0, 0], [0, 1, 1, 0], [0, 1, 1, 1]])
self.assertEqual(extended3, expected3)
def test_from_nested_quantum_circuit(self):
"""Test constructing a linear function from a quantum circuit with
nested linear quantum circuits."""
qc1 = QuantumCircuit(3)
qc1.swap(1, 2)
qc2 = QuantumCircuit(3)
qc2.append(qc1, [2, 1, 0]) # swaps 0 and 1
qc2.swap(1, 2) # cycles 0->2->1->0
qc3 = QuantumCircuit(4)
qc3.append(qc2, [0, 1, 3]) # cycles 0->3->1->0, 2 untouched
linear_function = LinearFunction(qc3)
expected = LinearFunction([[0, 1, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0], [1, 0, 0, 0]])
self.assertEqual(linear_function, expected)
def test_from_clifford_when_possible(self):
"""Test constructing a linear function from a clifford which corresponds to a valid
linear function."""
qc = QuantumCircuit(3)
qc.cx(0, 1)
qc.swap(1, 2)
# Linear function constructed from qc
linear_from_qc = LinearFunction(qc)
# Linear function constructed from clifford
cliff = Clifford(qc)
linear_from_clifford = LinearFunction(cliff)
self.assertEqual(linear_from_qc, linear_from_clifford)
def test_to_clifford_and_back(self):
"""Test converting linear function to clifford and back."""
linear = LinearFunction([[1, 1, 1], [0, 1, 1], [0, 0, 1]])
cliff = Clifford(linear)
linear_from_clifford = LinearFunction(cliff)
self.assertEqual(linear, linear_from_clifford)
def test_from_clifford_when_impossible(self):
"""Test that constructing a linear function from a clifford that does not correspond
to a linear function produces a circuit error."""
qc = QuantumCircuit(3)
qc.cx(0, 1)
qc.h(0)
qc.swap(1, 2)
with self.assertRaises(CircuitError):
LinearFunction(qc)
def test_from_permutation_gate(self):
"""Test constructing a linear function from a permutation gate."""
pattern = [1, 2, 0, 3]
perm_gate = PermutationGate(pattern)
linear_from_perm = LinearFunction(perm_gate)
self.assertTrue(linear_from_perm.is_permutation())
extracted_pattern = linear_from_perm.permutation_pattern()
self.assertTrue(np.all(pattern == extracted_pattern))
def test_from_linear_function(self):
"""Test constructing a linear function from another linear function."""
linear_function1 = LinearFunction([[1, 1, 1], [0, 1, 1], [0, 0, 1]])
linear_function2 = LinearFunction(linear_function1)
self.assertEqual(linear_function1, linear_function2)
def test_from_quantum_circuit_with_linear_functions(self):
"""Test constructing a linear function from a quantum circuit with
linear functions."""
qc1 = QuantumCircuit(3)
qc1.swap(1, 2)
linear1 = LinearFunction(qc1)
qc2 = QuantumCircuit(2)
qc2.swap(0, 1)
linear2 = LinearFunction(qc2)
qc3 = QuantumCircuit(4)
qc3.append(linear1, [0, 1, 2])
qc3.append(linear2, [2, 3])
linear3 = LinearFunction(qc3)
# linear3 is a permutation: 1->3->2, 0 unchanged
expected = LinearFunction([[1, 0, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1], [0, 1, 0, 0]])
self.assertEqual(linear3, expected)
@data(2, 3, 4, 5, 6, 7, 8)
def test_clifford_linear_function_equivalence(self, num_qubits):
"""Pseudo-random tests for constructing a random linear circuit,
converting this circuit both to a linear function and to a clifford,
and checking that the two are equivalent as Cliffords and as LinearFunctions.
"""
qc = random_linear_circuit(
num_qubits,
100,
seed=0,
barrier=True,
delay=True,
permutation=True,
linear=True,
clifford=True,
recursion_depth=2,
)
qc_to_linear_function = LinearFunction(qc)
qc_to_clifford = Clifford(qc)
self.assertEqual(Clifford(qc_to_linear_function), qc_to_clifford)
self.assertEqual(qc_to_linear_function, LinearFunction(qc_to_clifford))
@data(2, 3)
def test_repeat_method(self, num_qubits):
"""Test the repeat() method."""
rng = np.random.default_rng(127)
for num_gates, seed in zip(
[0, 5, 5 * num_qubits], rng.integers(100000, size=10, dtype=np.uint64)
):
# create a random linear circuit
linear_circuit = random_linear_circuit(num_qubits, num_gates, seed=seed)
operator = Operator(linear_circuit)
linear_function = LinearFunction(linear_circuit)
self.assertTrue(Operator(linear_function.repeat(2)), operator @ operator)
if __name__ == "__main__":
unittest.main()
| qiskit/test/python/circuit/library/test_linear_function.py/0 | {
"file_path": "qiskit/test/python/circuit/library/test_linear_function.py",
"repo_id": "qiskit",
"token_count": 9311
} | 313 |
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 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 library of weighted adder circuits."""
import unittest
from collections import defaultdict
from ddt import ddt, data
import numpy as np
from qiskit.circuit import QuantumCircuit
from qiskit.circuit.library import WeightedAdder
from qiskit.quantum_info import Statevector
from test import QiskitTestCase # pylint: disable=wrong-import-order
@ddt
class TestWeightedAdder(QiskitTestCase):
"""Test the weighted adder circuit."""
def assertSummationIsCorrect(self, adder):
"""Assert that ``adder`` correctly implements the summation w.r.t. its set weights."""
circuit = QuantumCircuit(adder.num_qubits)
circuit.h(list(range(adder.num_state_qubits)))
circuit.append(adder.to_instruction(), list(range(adder.num_qubits)))
statevector = Statevector(circuit)
probabilities = defaultdict(float)
for i, statevector_amplitude in enumerate(statevector):
i = bin(i)[2:].zfill(circuit.num_qubits)[adder.num_ancillas :]
probabilities[i] += np.real(np.abs(statevector_amplitude) ** 2)
expectations = defaultdict(float)
for x in range(2**adder.num_state_qubits):
bits = np.array(list(bin(x)[2:].zfill(adder.num_state_qubits)), dtype=int)
summation = bits.dot(adder.weights[::-1])
entry = bin(summation)[2:].zfill(adder.num_sum_qubits) + bin(x)[2:].zfill(
adder.num_state_qubits
)
expectations[entry] = 1 / 2**adder.num_state_qubits
for state, probability in probabilities.items():
self.assertAlmostEqual(probability, expectations[state])
@data([0], [1, 2, 1], [4], [1, 2, 1, 1, 4])
def test_summation(self, weights):
"""Test the weighted adder on some examples."""
adder = WeightedAdder(len(weights), weights)
self.assertSummationIsCorrect(adder)
def test_mutability(self):
"""Test the mutability of the weighted adder."""
adder = WeightedAdder()
with self.subTest(msg="missing number of state qubits"):
with self.assertRaises(AttributeError):
_ = str(adder.draw())
with self.subTest(msg="default weights"):
adder.num_state_qubits = 3
default_weights = 3 * [1]
self.assertListEqual(adder.weights, default_weights)
with self.subTest(msg="specify weights"):
adder.weights = [3, 2, 1]
self.assertSummationIsCorrect(adder)
with self.subTest(msg="mismatching number of state qubits and weights"):
with self.assertRaises(ValueError):
adder.weights = [0, 1, 2, 3]
_ = str(adder.draw())
with self.subTest(msg="change all attributes"):
adder.num_state_qubits = 4
adder.weights = [2, 0, 1, 1]
self.assertSummationIsCorrect(adder)
if __name__ == "__main__":
unittest.main()
| qiskit/test/python/circuit/library/test_weighted_adder.py/0 | {
"file_path": "qiskit/test/python/circuit/library/test_weighted_adder.py",
"repo_id": "qiskit",
"token_count": 1388
} | 314 |
# This code is part of Qiskit.
#
# (C) Copyright IBM 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
# pylint: disable=missing-function-docstring
"""Test operations on the builder interfaces for control flow in dynamic QuantumCircuits."""
import copy
import math
import ddt
from qiskit.circuit import (
ClassicalRegister,
Clbit,
Measure,
Parameter,
QuantumCircuit,
QuantumRegister,
Qubit,
Store,
)
from qiskit.circuit.classical import expr, types
from qiskit.circuit.controlflow import ForLoopOp, IfElseOp, WhileLoopOp, SwitchCaseOp, CASE_DEFAULT
from qiskit.circuit.controlflow.if_else import IfElsePlaceholder
from qiskit.circuit.exceptions import CircuitError
from test import QiskitTestCase # pylint: disable=wrong-import-order
from test.utils._canonical import canonicalize_control_flow # pylint: disable=wrong-import-order
class SentinelException(Exception):
"""An exception that we know was raised deliberately."""
@ddt.ddt
class TestControlFlowBuilders(QiskitTestCase):
"""Test that the control-flow builder interfaces work, and manage resources correctly."""
def test_if_simple(self):
"""Test a simple if statement builds correctly, in the midst of other instructions."""
qubits = [Qubit(), Qubit()]
clbits = [Clbit(), Clbit()]
test = QuantumCircuit(qubits, clbits)
test.h(0)
test.measure(0, 0)
with test.if_test((clbits[0], 0)):
test.x(0)
test.h(0)
test.measure(0, 1)
with test.if_test((clbits[1], 0)):
test.h(1)
test.cx(1, 0)
if_true0 = QuantumCircuit([qubits[0], clbits[0]])
if_true0.x(qubits[0])
if_true1 = QuantumCircuit([qubits[0], qubits[1], clbits[1]])
if_true1.h(qubits[1])
if_true1.cx(qubits[1], qubits[0])
expected = QuantumCircuit(qubits, clbits)
expected.h(qubits[0])
expected.measure(qubits[0], clbits[0])
expected.if_test((clbits[0], 0), if_true0, [qubits[0]], [clbits[0]])
expected.h(qubits[0])
expected.measure(qubits[0], clbits[1])
expected.if_test((clbits[1], 0), if_true1, [qubits[0], qubits[1]], [clbits[1]])
self.assertEqual(canonicalize_control_flow(test), canonicalize_control_flow(expected))
def test_if_register(self):
"""Test a simple if statement builds correctly, when using a register as the condition.
This requires the builder to unpack all the bits from the register to use as resources."""
qr = QuantumRegister(2)
cr = ClassicalRegister(2)
test = QuantumCircuit(qr, cr)
test.measure(qr, cr)
with test.if_test((cr, 0)):
test.x(0)
if_true0 = QuantumCircuit([qr[0]], cr)
if_true0.x(qr[0])
expected = QuantumCircuit(qr, cr)
expected.measure(qr, cr)
expected.if_test((cr, 0), if_true0, [qr[0]], cr)
self.assertEqual(canonicalize_control_flow(test), canonicalize_control_flow(expected))
def test_if_expr(self):
"""Test a simple if statement builds correctly, when using an expression as the condition.
This requires the builder to unpack all the bits from contained registers to use as
resources."""
qr = QuantumRegister(2)
cr1 = ClassicalRegister(2)
cr2 = ClassicalRegister(2)
test = QuantumCircuit(qr, cr1, cr2)
test.measure(qr, cr1)
test.measure(qr, cr2)
with test.if_test(expr.less(cr1, expr.bit_not(cr2))):
test.x(0)
if_true0 = QuantumCircuit([qr[0]], cr1, cr2)
if_true0.x(qr[0])
expected = QuantumCircuit(qr, cr1, cr2)
expected.measure(qr, cr1)
expected.measure(qr, cr2)
expected.if_test(
expr.less(cr1, expr.bit_not(cr2)), if_true0, [qr[0]], list(cr1) + list(cr2)
)
self.assertEqual(canonicalize_control_flow(test), canonicalize_control_flow(expected))
def test_register_condition_in_nested_block(self):
"""Test that nested blocks can use registers of the outermost circuits as conditions, and
they get propagated through all the blocks."""
qr = QuantumRegister(2)
clbits = [Clbit(), Clbit(), Clbit()]
cr1 = ClassicalRegister(3)
# Try aliased classical registers as well, to catch potential overlap bugs.
cr2 = ClassicalRegister(bits=clbits[:2])
cr3 = ClassicalRegister(bits=clbits[1:])
cr4 = ClassicalRegister(bits=clbits)
with self.subTest("for/if"):
test = QuantumCircuit(qr, clbits, cr1, cr2, cr3, cr4)
with test.for_loop(range(3)):
with test.if_test((cr1, 0)):
test.x(0)
with test.if_test((cr2, 0)):
test.y(0)
with test.if_test((cr3, 0)):
test.z(0)
true_body1 = QuantumCircuit([qr[0]], cr1)
true_body1.x(0)
true_body2 = QuantumCircuit([qr[0]], cr2)
true_body2.y(0)
true_body3 = QuantumCircuit([qr[0]], cr3)
true_body3.z(0)
for_body = QuantumCircuit([qr[0]], clbits, cr1, cr2, cr3) # but not cr4.
for_body.if_test((cr1, 0), true_body1, [qr[0]], cr1)
for_body.if_test((cr2, 0), true_body2, [qr[0]], cr2)
for_body.if_test((cr3, 0), true_body3, [qr[0]], cr3)
expected = QuantumCircuit(qr, clbits, cr1, cr2, cr3, cr4)
expected.for_loop(range(3), None, for_body, [qr[0]], clbits + list(cr1))
self.assertEqual(canonicalize_control_flow(test), canonicalize_control_flow(expected))
with self.subTest("for/while"):
test = QuantumCircuit(qr, clbits, cr1, cr2, cr3, cr4)
with test.for_loop(range(3)):
with test.while_loop((cr1, 0)):
test.x(0)
with test.while_loop((cr2, 0)):
test.y(0)
with test.while_loop((cr3, 0)):
test.z(0)
while_body1 = QuantumCircuit([qr[0]], cr1)
while_body1.x(0)
while_body2 = QuantumCircuit([qr[0]], cr2)
while_body2.y(0)
while_body3 = QuantumCircuit([qr[0]], cr3)
while_body3.z(0)
for_body = QuantumCircuit([qr[0]], clbits, cr1, cr2, cr3)
for_body.while_loop((cr1, 0), while_body1, [qr[0]], cr1)
for_body.while_loop((cr2, 0), while_body2, [qr[0]], cr2)
for_body.while_loop((cr3, 0), while_body3, [qr[0]], cr3)
expected = QuantumCircuit(qr, clbits, cr1, cr2, cr3, cr4)
expected.for_loop(range(3), None, for_body, [qr[0]], clbits + list(cr1))
self.assertEqual(canonicalize_control_flow(test), canonicalize_control_flow(expected))
with self.subTest("if/c_if"):
test = QuantumCircuit(qr, clbits, cr1, cr2, cr3, cr4)
with test.if_test((cr1, 0)):
test.x(0).c_if(cr2, 0)
test.z(0).c_if(cr3, 0)
true_body = QuantumCircuit([qr[0]], clbits, cr1, cr2, cr3)
true_body.x(0).c_if(cr2, 0)
true_body.z(0).c_if(cr3, 0)
expected = QuantumCircuit(qr, clbits, cr1, cr2, cr3, cr4)
expected.if_test((cr1, 0), true_body, [qr[0]], clbits + list(cr1))
self.assertEqual(canonicalize_control_flow(test), canonicalize_control_flow(expected))
with self.subTest("while/else/c_if"):
test = QuantumCircuit(qr, clbits, cr1, cr2, cr3, cr4)
with test.while_loop((cr1, 0)):
with test.if_test((cr2, 0)) as else_:
test.x(0).c_if(cr3, 0)
with else_:
test.z(0).c_if(cr4, 0)
true_body = QuantumCircuit([qr[0]], cr2, cr3, cr4)
true_body.x(0).c_if(cr3, 0)
false_body = QuantumCircuit([qr[0]], cr2, cr3, cr4)
false_body.z(0).c_if(cr4, 0)
while_body = QuantumCircuit([qr[0]], clbits, cr1, cr2, cr3, cr4)
while_body.if_else((cr2, 0), true_body, false_body, [qr[0]], clbits)
expected = QuantumCircuit(qr, clbits, cr1, cr2, cr3, cr4)
expected.while_loop((cr1, 0), while_body, [qr[0]], clbits + list(cr1))
self.assertEqual(canonicalize_control_flow(test), canonicalize_control_flow(expected))
with self.subTest("switch/if"):
test = QuantumCircuit(qr, clbits, cr1, cr2, cr3, cr4)
with test.switch(cr1) as case_:
with case_(0):
with test.if_test((cr2, 0)):
test.x(0)
with case_(1, 2):
with test.if_test((cr3, 0)):
test.y(0)
with case_(case_.DEFAULT):
with test.if_test((cr4, 0)):
test.z(0)
true_body1 = QuantumCircuit([qr[0]], cr2)
true_body1.x(0)
case_body1 = QuantumCircuit([qr[0]], clbits, cr1, cr2, cr3, cr4)
case_body1.if_test((cr2, 0), true_body1, [qr[0]], cr2)
true_body2 = QuantumCircuit([qr[0]], cr3)
true_body2.y(0)
case_body2 = QuantumCircuit([qr[0]], clbits, cr1, cr2, cr3, cr4)
case_body2.if_test((cr3, 0), true_body2, [qr[0]], cr3)
true_body3 = QuantumCircuit([qr[0]], cr4)
true_body3.z(0)
case_body3 = QuantumCircuit([qr[0]], clbits, cr1, cr2, cr3, cr4)
case_body3.if_test((cr4, 0), true_body3, [qr[0]], cr4)
expected = QuantumCircuit(qr, clbits, cr1, cr2, cr3, cr4)
expected.switch(
cr1,
[
(0, case_body1),
((1, 2), case_body2),
(CASE_DEFAULT, case_body3),
],
[qr[0]],
clbits + list(cr1),
)
self.assertEqual(canonicalize_control_flow(test), canonicalize_control_flow(expected))
with self.subTest("switch/while"):
test = QuantumCircuit(qr, clbits, cr1, cr2, cr3, cr4)
with test.switch(cr1) as case_:
with case_(0):
with test.while_loop((cr2, 0)):
test.x(0)
with case_(1, 2):
with test.while_loop((cr3, 0)):
test.y(0)
with case_(case_.DEFAULT):
with test.while_loop((cr4, 0)):
test.z(0)
loop_body1 = QuantumCircuit([qr[0]], cr2)
loop_body1.x(0)
case_body1 = QuantumCircuit([qr[0]], clbits, cr1, cr2, cr3, cr4)
case_body1.while_loop((cr2, 0), loop_body1, [qr[0]], cr2)
loop_body2 = QuantumCircuit([qr[0]], cr3)
loop_body2.y(0)
case_body2 = QuantumCircuit([qr[0]], clbits, cr1, cr2, cr3, cr4)
case_body2.while_loop((cr3, 0), loop_body2, [qr[0]], cr3)
loop_body3 = QuantumCircuit([qr[0]], cr4)
loop_body3.z(0)
case_body3 = QuantumCircuit([qr[0]], clbits, cr1, cr2, cr3, cr4)
case_body3.while_loop((cr4, 0), loop_body3, [qr[0]], cr4)
expected = QuantumCircuit(qr, clbits, cr1, cr2, cr3, cr4)
expected.switch(
cr1,
[
(0, case_body1),
((1, 2), case_body2),
(CASE_DEFAULT, case_body3),
],
[qr[0]],
clbits + list(cr1),
)
def test_expr_condition_in_nested_block(self):
"""Test that nested blocks can use expressions with registers of the outermost circuits as
conditions, and they get propagated through all the blocks."""
qr = QuantumRegister(2)
clbits = [Clbit(), Clbit(), Clbit()]
cr1 = ClassicalRegister(3)
# Try aliased classical registers as well, to catch potential overlap bugs.
cr2 = ClassicalRegister(bits=clbits[:2])
cr3 = ClassicalRegister(bits=clbits[1:])
cr4 = ClassicalRegister(bits=clbits)
with self.subTest("for/if"):
test = QuantumCircuit(qr, clbits, cr1, cr2, cr3, cr4)
with test.for_loop(range(3)):
with test.if_test(expr.equal(cr1, 0)):
test.x(0)
with test.if_test(expr.less(expr.bit_or(cr2, 1), 2)):
test.y(0)
with test.if_test(expr.cast(expr.bit_not(cr3), types.Bool())):
test.z(0)
true_body1 = QuantumCircuit([qr[0]], cr1)
true_body1.x(0)
true_body2 = QuantumCircuit([qr[0]], cr2)
true_body2.y(0)
true_body3 = QuantumCircuit([qr[0]], cr3)
true_body3.z(0)
for_body = QuantumCircuit([qr[0]], clbits, cr1, cr2, cr3) # but not cr4.
for_body.if_test(expr.equal(cr1, 0), true_body1, [qr[0]], cr1)
for_body.if_test(expr.less(expr.bit_or(cr2, 1), 2), true_body2, [qr[0]], cr2)
for_body.if_test(expr.cast(expr.bit_not(cr3), types.Bool()), true_body3, [qr[0]], cr3)
expected = QuantumCircuit(qr, clbits, cr1, cr2, cr3, cr4)
expected.for_loop(range(3), None, for_body, [qr[0]], clbits + list(cr1))
self.assertEqual(canonicalize_control_flow(test), canonicalize_control_flow(expected))
with self.subTest("for/while"):
test = QuantumCircuit(qr, clbits, cr1, cr2, cr3, cr4)
with test.for_loop(range(3)):
with test.while_loop(expr.equal(cr1, 0)):
test.x(0)
with test.while_loop(expr.less(expr.bit_or(cr2, 1), 2)):
test.y(0)
with test.while_loop(expr.cast(expr.bit_not(cr3), types.Bool())):
test.z(0)
while_body1 = QuantumCircuit([qr[0]], cr1)
while_body1.x(0)
while_body2 = QuantumCircuit([qr[0]], cr2)
while_body2.y(0)
while_body3 = QuantumCircuit([qr[0]], cr3)
while_body3.z(0)
for_body = QuantumCircuit([qr[0]], clbits, cr1, cr2, cr3)
for_body.while_loop(expr.equal(cr1, 0), while_body1, [qr[0]], cr1)
for_body.while_loop(expr.less(expr.bit_or(cr2, 1), 2), while_body2, [qr[0]], cr2)
for_body.while_loop(
expr.cast(expr.bit_not(cr3), types.Bool()), while_body3, [qr[0]], cr3
)
expected = QuantumCircuit(qr, clbits, cr1, cr2, cr3, cr4)
expected.for_loop(range(3), None, for_body, [qr[0]], clbits + list(cr1))
self.assertEqual(canonicalize_control_flow(test), canonicalize_control_flow(expected))
with self.subTest("switch/if"):
test = QuantumCircuit(qr, clbits, cr1, cr2, cr3, cr4)
with test.switch(expr.lift(cr1)) as case_:
with case_(0):
with test.if_test(expr.less(expr.bit_or(cr2, 1), 2)):
test.x(0)
with case_(1, 2):
with test.if_test(expr.cast(expr.bit_not(cr3), types.Bool())):
test.y(0)
with case_(case_.DEFAULT):
with test.if_test(expr.not_equal(cr4, 0)):
test.z(0)
true_body1 = QuantumCircuit([qr[0]], cr2)
true_body1.x(0)
case_body1 = QuantumCircuit([qr[0]], clbits, cr1, cr2, cr3, cr4)
case_body1.if_test(expr.less(expr.bit_or(cr2, 1), 2), true_body1, [qr[0]], cr2)
true_body2 = QuantumCircuit([qr[0]], cr3)
true_body2.y(0)
case_body2 = QuantumCircuit([qr[0]], clbits, cr1, cr2, cr3, cr4)
case_body2.if_test(expr.cast(expr.bit_not(cr3), types.Bool()), true_body2, [qr[0]], cr3)
true_body3 = QuantumCircuit([qr[0]], cr4)
true_body3.z(0)
case_body3 = QuantumCircuit([qr[0]], clbits, cr1, cr2, cr3, cr4)
case_body3.if_test(expr.not_equal(cr4, 0), true_body3, [qr[0]], cr4)
expected = QuantumCircuit(qr, clbits, cr1, cr2, cr3, cr4)
expected.switch(
expr.lift(cr1),
[
(0, case_body1),
((1, 2), case_body2),
(CASE_DEFAULT, case_body3),
],
[qr[0]],
clbits + list(cr1),
)
self.assertEqual(canonicalize_control_flow(test), canonicalize_control_flow(expected))
def test_if_else_simple(self):
"""Test a simple if/else statement builds correctly, in the midst of other instructions.
This test has paired if and else blocks the same natural width."""
qubits = [Qubit(), Qubit()]
clbits = [Clbit(), Clbit()]
test = QuantumCircuit(qubits, clbits)
test.h(0)
test.measure(0, 0)
with test.if_test((clbits[0], 0)) as else_:
test.x(0)
with else_:
test.z(0)
test.h(0)
test.measure(0, 1)
with test.if_test((clbits[1], 0)) as else_:
test.h(1)
test.cx(1, 0)
with else_:
test.h(0)
test.h(1)
# Both the if and else blocks in this circuit are the same natural width to begin with.
if_true0 = QuantumCircuit([qubits[0], clbits[0]])
if_true0.x(qubits[0])
if_false0 = QuantumCircuit([qubits[0], clbits[0]])
if_false0.z(qubits[0])
if_true1 = QuantumCircuit([qubits[0], qubits[1], clbits[1]])
if_true1.h(qubits[1])
if_true1.cx(qubits[1], qubits[0])
if_false1 = QuantumCircuit([qubits[0], qubits[1], clbits[1]])
if_false1.h(qubits[0])
if_false1.h(qubits[1])
expected = QuantumCircuit(qubits, clbits)
expected.h(qubits[0])
expected.measure(qubits[0], clbits[0])
expected.if_else((clbits[0], 0), if_true0, if_false0, [qubits[0]], [clbits[0]])
expected.h(qubits[0])
expected.measure(qubits[0], clbits[1])
expected.if_else((clbits[1], 0), if_true1, if_false1, [qubits[0], qubits[1]], [clbits[1]])
self.assertEqual(canonicalize_control_flow(test), canonicalize_control_flow(expected))
def test_if_else_expr_simple(self):
"""Test a simple if/else statement builds correctly, in the midst of other instructions.
This test has paired if and else blocks the same natural width."""
qubits = [Qubit(), Qubit()]
clbits = [Clbit(), Clbit()]
test = QuantumCircuit(qubits, clbits)
test.h(0)
test.measure(0, 0)
with test.if_test(expr.lift(clbits[0])) as else_:
test.x(0)
with else_:
test.z(0)
test.h(0)
test.measure(0, 1)
with test.if_test(expr.logic_not(clbits[1])) as else_:
test.h(1)
test.cx(1, 0)
with else_:
test.h(0)
test.h(1)
# Both the if and else blocks in this circuit are the same natural width to begin with.
if_true0 = QuantumCircuit([qubits[0], clbits[0]])
if_true0.x(qubits[0])
if_false0 = QuantumCircuit([qubits[0], clbits[0]])
if_false0.z(qubits[0])
if_true1 = QuantumCircuit([qubits[0], qubits[1], clbits[1]])
if_true1.h(qubits[1])
if_true1.cx(qubits[1], qubits[0])
if_false1 = QuantumCircuit([qubits[0], qubits[1], clbits[1]])
if_false1.h(qubits[0])
if_false1.h(qubits[1])
expected = QuantumCircuit(qubits, clbits)
expected.h(qubits[0])
expected.measure(qubits[0], clbits[0])
expected.if_else(expr.lift(clbits[0]), if_true0, if_false0, [qubits[0]], [clbits[0]])
expected.h(qubits[0])
expected.measure(qubits[0], clbits[1])
expected.if_else(
expr.logic_not(clbits[1]), if_true1, if_false1, [qubits[0], qubits[1]], [clbits[1]]
)
self.assertEqual(canonicalize_control_flow(test), canonicalize_control_flow(expected))
def test_if_else_resources_expand_true_superset_false(self):
"""Test that the resources of the if and else bodies come out correctly if the true body
needs a superset of the resources of the false body."""
qubits = [Qubit(), Qubit()]
clbits = [Clbit(), Clbit()]
test = QuantumCircuit(qubits, clbits)
test.h(0)
test.measure(0, 0)
with test.if_test((clbits[0], 0)) as else_:
test.x(0)
test.measure(1, 1)
with else_:
test.z(0)
if_true0 = QuantumCircuit(qubits, clbits)
if_true0.x(qubits[0])
if_true0.measure(qubits[1], clbits[1])
# The false body doesn't actually use qubits[1] or clbits[1], but it still needs to contain
# them so the bodies match.
if_false0 = QuantumCircuit(qubits, clbits)
if_false0.z(qubits[0])
expected = QuantumCircuit(qubits, clbits)
expected.h(qubits[0])
expected.measure(qubits[0], clbits[0])
expected.if_else((clbits[0], 0), if_true0, if_false0, qubits, clbits)
self.assertEqual(canonicalize_control_flow(test), canonicalize_control_flow(expected))
def test_if_else_resources_expand_false_superset_true(self):
"""Test that the resources of the if and else bodies come out correctly if the false body
needs a superset of the resources of the true body. This requires that the manager
correctly adds resources to the true body after it has been created."""
qubits = [Qubit(), Qubit()]
clbits = [Clbit(), Clbit()]
test = QuantumCircuit(qubits, clbits)
test.h(0)
test.measure(0, 0)
with test.if_test((clbits[0], 0)) as else_:
test.x(0)
with else_:
test.z(0)
test.measure(1, 1)
# The true body doesn't actually use qubits[1] or clbits[1], but it still needs to contain
# them so the bodies match.
if_true0 = QuantumCircuit(qubits, clbits)
if_true0.x(qubits[0])
if_false0 = QuantumCircuit(qubits, clbits)
if_false0.z(qubits[0])
if_false0.measure(qubits[1], clbits[1])
expected = QuantumCircuit(qubits, clbits)
expected.h(qubits[0])
expected.measure(qubits[0], clbits[0])
expected.if_else((clbits[0], 0), if_true0, if_false0, qubits, clbits)
self.assertEqual(canonicalize_control_flow(test), canonicalize_control_flow(expected))
def test_if_else_resources_expand_true_false_symmetric_difference(self):
"""Test that the resources of the if and else bodies come out correctly if the sets of
resources for the true body and the false body have some overlap, but neither is a subset of
the other. This tests that the flow of resources from block to block is simultaneously
bidirectional."""
qubits = [Qubit(), Qubit()]
clbits = [Clbit(), Clbit()]
test = QuantumCircuit(qubits, clbits)
test.h(0)
test.measure(0, 0)
with test.if_test((clbits[0], 0)) as else_:
test.x(0)
with else_:
test.z(1)
# The true body doesn't use qubits[1] and the false body doesn't use qubits[0].
if_true0 = QuantumCircuit(qubits, [clbits[0]])
if_true0.x(qubits[0])
if_false0 = QuantumCircuit(qubits, [clbits[0]])
if_false0.z(qubits[1])
expected = QuantumCircuit(qubits, clbits)
expected.h(qubits[0])
expected.measure(qubits[0], clbits[0])
expected.if_else((clbits[0], 0), if_true0, if_false0, qubits, [clbits[0]])
self.assertEqual(canonicalize_control_flow(test), canonicalize_control_flow(expected))
def test_if_else_empty_branches(self):
"""Test that the context managers can cope with a body being empty."""
qubits = [Qubit()]
clbits = [Clbit()]
cond = (clbits[0], 0)
test = QuantumCircuit(qubits, clbits)
# Sole empty if.
with test.if_test(cond):
pass
# Normal if with an empty else body.
with test.if_test(cond) as else_:
test.x(0)
with else_:
pass
# Empty if with a normal else body.
with test.if_test(cond) as else_:
pass
with else_:
test.x(0)
# Both empty.
with test.if_test(cond) as else_:
pass
with else_:
pass
empty_with_qubit = QuantumCircuit([qubits[0], clbits[0]])
empty = QuantumCircuit([clbits[0]])
only_x = QuantumCircuit([qubits[0], clbits[0]])
only_x.x(qubits[0])
expected = QuantumCircuit(qubits, clbits)
expected.if_test(cond, empty, [], [clbits[0]])
expected.if_else(cond, only_x, empty_with_qubit, [qubits[0]], [clbits[0]])
expected.if_else(cond, empty_with_qubit, only_x, [qubits[0]], [clbits[0]])
expected.if_else(cond, empty, empty, [], [clbits[0]])
self.assertEqual(canonicalize_control_flow(test), canonicalize_control_flow(expected))
def test_if_else_tracks_registers(self):
"""Test that classical registers used in both branches of if statements are tracked
correctly."""
qr = QuantumRegister(2)
cr = [ClassicalRegister(2) for _ in [None] * 4]
test = QuantumCircuit(qr, *cr)
with test.if_test((cr[0], 0)) as else_:
test.h(0).c_if(cr[1], 0)
# Test repetition.
test.h(0).c_if(cr[1], 0)
with else_:
test.h(0).c_if(cr[2], 0)
true_body = QuantumCircuit([qr[0]], cr[0], cr[1], cr[2])
true_body.h(qr[0]).c_if(cr[1], 0)
true_body.h(qr[0]).c_if(cr[1], 0)
false_body = QuantumCircuit([qr[0]], cr[0], cr[1], cr[2])
false_body.h(qr[0]).c_if(cr[2], 0)
expected = QuantumCircuit(qr, *cr)
expected.if_else(
(cr[0], 0), true_body, false_body, [qr[0]], list(cr[0]) + list(cr[1]) + list(cr[2])
)
self.assertEqual(canonicalize_control_flow(test), canonicalize_control_flow(expected))
def test_if_else_nested(self):
"""Test that the if and else context managers can be nested, and don't interfere with each
other."""
qubits = [Qubit(), Qubit(), Qubit()]
clbits = [Clbit(), Clbit(), Clbit()]
outer_cond = (clbits[0], 0)
inner_cond = (clbits[2], 1)
with self.subTest("if (if) else"):
test = QuantumCircuit(qubits, clbits)
with test.if_test(outer_cond) as else_:
with test.if_test(inner_cond):
test.h(0)
with else_:
test.h(1)
inner_true = QuantumCircuit([qubits[0], clbits[2]])
inner_true.h(qubits[0])
outer_true = QuantumCircuit([qubits[0], qubits[1], clbits[0], clbits[2]])
outer_true.if_test(inner_cond, inner_true, [qubits[0]], [clbits[2]])
outer_false = QuantumCircuit([qubits[0], qubits[1], clbits[0], clbits[2]])
outer_false.h(qubits[1])
expected = QuantumCircuit(qubits, clbits)
expected.if_else(
outer_cond, outer_true, outer_false, [qubits[0], qubits[1]], [clbits[0], clbits[2]]
)
self.assertEqual(canonicalize_control_flow(test), canonicalize_control_flow(expected))
with self.subTest("if (if else) else"):
test = QuantumCircuit(qubits, clbits)
with test.if_test(outer_cond) as outer_else:
with test.if_test(inner_cond) as inner_else:
test.h(0)
with inner_else:
test.h(2)
with outer_else:
test.h(1)
inner_true = QuantumCircuit([qubits[0], qubits[2], clbits[2]])
inner_true.h(qubits[0])
inner_false = QuantumCircuit([qubits[0], qubits[2], clbits[2]])
inner_false.h(qubits[2])
outer_true = QuantumCircuit(qubits, [clbits[0], clbits[2]])
outer_true.if_else(
inner_cond, inner_true, inner_false, [qubits[0], qubits[2]], [clbits[2]]
)
outer_false = QuantumCircuit(qubits, [clbits[0], clbits[2]])
outer_false.h(qubits[1])
expected = QuantumCircuit(qubits, clbits)
expected.if_else(outer_cond, outer_true, outer_false, qubits, [clbits[0], clbits[2]])
self.assertEqual(canonicalize_control_flow(test), canonicalize_control_flow(expected))
def test_if_else_expr_nested(self):
"""Test that the if and else context managers can be nested, and don't interfere with each
other."""
qubits = [Qubit(), Qubit(), Qubit()]
clbits = [Clbit(), Clbit(), Clbit()]
cr = ClassicalRegister(2, "c")
outer_cond = expr.logic_not(clbits[0])
inner_cond = expr.logic_and(clbits[2], expr.greater(cr, 1))
with self.subTest("if (if) else"):
test = QuantumCircuit(qubits, clbits, cr)
with test.if_test(outer_cond) as else_:
with test.if_test(inner_cond):
test.h(0)
with else_:
test.h(1)
inner_true = QuantumCircuit([qubits[0], clbits[2]], cr)
inner_true.h(qubits[0])
outer_true = QuantumCircuit([qubits[0], qubits[1], clbits[0], clbits[2]], cr)
outer_true.if_test(inner_cond, inner_true, [qubits[0]], [clbits[2]] + list(cr))
outer_false = QuantumCircuit([qubits[0], qubits[1], clbits[0], clbits[2]], cr)
outer_false.h(qubits[1])
expected = QuantumCircuit(qubits, clbits, cr)
expected.if_else(
outer_cond,
outer_true,
outer_false,
[qubits[0], qubits[1]],
[clbits[0], clbits[2]] + list(cr),
)
self.assertEqual(canonicalize_control_flow(test), canonicalize_control_flow(expected))
with self.subTest("if (if else) else"):
test = QuantumCircuit(qubits, clbits, cr)
with test.if_test(outer_cond) as outer_else:
with test.if_test(inner_cond) as inner_else:
test.h(0)
with inner_else:
test.h(2)
with outer_else:
test.h(1)
inner_true = QuantumCircuit([qubits[0], qubits[2], clbits[2]], cr)
inner_true.h(qubits[0])
inner_false = QuantumCircuit([qubits[0], qubits[2], clbits[2]], cr)
inner_false.h(qubits[2])
outer_true = QuantumCircuit(qubits, [clbits[0], clbits[2]], cr)
outer_true.if_else(
inner_cond, inner_true, inner_false, [qubits[0], qubits[2]], [clbits[2]] + list(cr)
)
outer_false = QuantumCircuit(qubits, [clbits[0], clbits[2]], cr)
outer_false.h(qubits[1])
expected = QuantumCircuit(qubits, clbits, cr)
expected.if_else(
outer_cond, outer_true, outer_false, qubits, [clbits[0], clbits[2]] + list(cr)
)
self.assertEqual(canonicalize_control_flow(test), canonicalize_control_flow(expected))
def test_switch_simple(self):
"""Individual labels switch test."""
qubits = [Qubit(), Qubit(), Qubit()]
creg = ClassicalRegister(2)
test = QuantumCircuit(qubits, creg)
with test.switch(creg) as case:
with case(0):
test.x(0)
with case(1):
test.x(2)
with case(2):
test.h(0)
with case(3):
test.h(2)
body0 = QuantumCircuit([qubits[0], qubits[2]], creg)
body0.x(qubits[0])
body1 = QuantumCircuit([qubits[0], qubits[2]], creg)
body1.x(qubits[2])
body2 = QuantumCircuit([qubits[0], qubits[2]], creg)
body2.h(qubits[0])
body3 = QuantumCircuit([qubits[0], qubits[2]], creg)
body3.h(qubits[2])
expected = QuantumCircuit(qubits, creg)
expected.switch(
creg,
[(0, body0), (1, body1), (2, body2), (3, body3)],
[qubits[0], qubits[2]],
list(creg),
)
self.assertEqual(canonicalize_control_flow(test), canonicalize_control_flow(expected))
def test_switch_expr_simple(self):
"""Individual labels switch test."""
qubits = [Qubit(), Qubit(), Qubit()]
creg = ClassicalRegister(2)
test = QuantumCircuit(qubits, creg)
with test.switch(expr.bit_and(creg, 2)) as case:
with case(0):
test.x(0)
with case(1):
test.x(2)
with case(2):
test.h(0)
with case(3):
test.h(2)
body0 = QuantumCircuit([qubits[0], qubits[2]], creg)
body0.x(qubits[0])
body1 = QuantumCircuit([qubits[0], qubits[2]], creg)
body1.x(qubits[2])
body2 = QuantumCircuit([qubits[0], qubits[2]], creg)
body2.h(qubits[0])
body3 = QuantumCircuit([qubits[0], qubits[2]], creg)
body3.h(qubits[2])
expected = QuantumCircuit(qubits, creg)
expected.switch(
expr.bit_and(creg, 2),
[(0, body0), (1, body1), (2, body2), (3, body3)],
[qubits[0], qubits[2]],
list(creg),
)
self.assertEqual(canonicalize_control_flow(test), canonicalize_control_flow(expected))
def test_switch_nested(self):
"""Individual labels switch test."""
qubits = [Qubit(), Qubit(), Qubit()]
cr1 = ClassicalRegister(2, "c1")
cr2 = ClassicalRegister(2, "c2")
cr3 = ClassicalRegister(3, "c3")
loose = Clbit()
test = QuantumCircuit(qubits, cr1, cr2, cr3, [loose])
with test.switch(cr1) as case_outer:
with case_outer(0), test.switch(loose) as case_inner, case_inner(False):
test.x(0)
with case_outer(1), test.switch(cr2) as case_inner, case_inner(0):
test.x(1)
body0_0 = QuantumCircuit([qubits[0]], [loose])
body0_0.x(qubits[0])
body0 = QuantumCircuit([qubits[0], qubits[1]], cr1, cr2, [loose])
body0.switch(
loose,
[(False, body0_0)],
[qubits[0]],
[loose],
)
body1_0 = QuantumCircuit([qubits[1]], cr2)
body1_0.x(qubits[1])
body1 = QuantumCircuit([qubits[0], qubits[1]], cr1, cr2, [loose])
body1.switch(
cr2,
[(0, body1_0)],
[qubits[1]],
list(cr2),
)
expected = QuantumCircuit(qubits, cr1, cr2, cr3, [loose])
expected.switch(
cr1,
[(0, body0), (1, body1)],
[qubits[0], qubits[1]],
list(cr1) + list(cr2) + [loose],
)
self.assertEqual(canonicalize_control_flow(test), canonicalize_control_flow(expected))
def test_switch_expr_nested(self):
"""Individual labels switch test."""
qubits = [Qubit(), Qubit(), Qubit()]
cr1 = ClassicalRegister(2, "c1")
cr2 = ClassicalRegister(2, "c2")
cr3 = ClassicalRegister(3, "c3")
loose = Clbit()
test = QuantumCircuit(qubits, cr1, cr2, cr3, [loose])
with test.switch(expr.bit_and(cr1, 2)) as case_outer:
with case_outer(0), test.switch(expr.lift(loose)) as case_inner, case_inner(False):
test.x(0)
with case_outer(1), test.switch(expr.bit_and(cr2, 2)) as case_inner, case_inner(0):
test.x(1)
body0_0 = QuantumCircuit([qubits[0]], [loose])
body0_0.x(qubits[0])
body0 = QuantumCircuit([qubits[0], qubits[1]], cr1, cr2, [loose])
body0.switch(
expr.lift(loose),
[(False, body0_0)],
[qubits[0]],
[loose],
)
body1_0 = QuantumCircuit([qubits[1]], cr2)
body1_0.x(qubits[1])
body1 = QuantumCircuit([qubits[0], qubits[1]], cr1, cr2, [loose])
body1.switch(
expr.bit_and(cr2, 2),
[(0, body1_0)],
[qubits[1]],
list(cr2),
)
expected = QuantumCircuit(qubits, cr1, cr2, cr3, [loose])
expected.switch(
expr.bit_and(cr1, 2),
[(0, body0), (1, body1)],
[qubits[0], qubits[1]],
list(cr1) + list(cr2) + [loose],
)
self.assertEqual(canonicalize_control_flow(test), canonicalize_control_flow(expected))
def test_switch_several_labels(self):
"""Several labels pointing to the same body."""
qubits = [Qubit(), Qubit(), Qubit()]
creg = ClassicalRegister(2)
test = QuantumCircuit(qubits, creg)
with test.switch(creg) as case:
with case(0, 1):
test.x(0)
with case(2):
test.h(0)
body0 = QuantumCircuit([qubits[0]], creg)
body0.x(qubits[0])
body1 = QuantumCircuit([qubits[0]], creg)
body1.h(qubits[0])
expected = QuantumCircuit(qubits, creg)
expected.switch(creg, [((0, 1), body0), (2, body1)], [qubits[0]], list(creg))
self.assertEqual(canonicalize_control_flow(test), canonicalize_control_flow(expected))
def test_switch_default(self):
"""Allow a default case."""
qubits = [Qubit(), Qubit(), Qubit()]
creg = ClassicalRegister(2)
test = QuantumCircuit(qubits, creg)
with test.switch(creg) as case:
with case(case.DEFAULT):
test.x(0)
# Additional test that the exposed `case.DEFAULT` object is referentially identical to
# the general `CASE_DEFAULT` as well, to avoid subtle equality bugs.
self.assertIs(case.DEFAULT, CASE_DEFAULT)
body = QuantumCircuit([qubits[0]], creg)
body.x(qubits[0])
expected = QuantumCircuit(qubits, creg)
expected.switch(creg, [(CASE_DEFAULT, body)], [qubits[0]], list(creg))
self.assertEqual(canonicalize_control_flow(test), canonicalize_control_flow(expected))
def test_break_continue_expand_to_match_arguments_simple(self):
"""Test that ``break`` and ``continue`` statements expand to include all resources in the
containing loop for simple cases with unconditional breaks."""
qubits = [Qubit(), Qubit()]
clbits = [Clbit(), Clbit()]
with self.subTest("for"):
test = QuantumCircuit(qubits, clbits)
with test.for_loop(range(2)):
test.break_loop()
test.h(0)
test.continue_loop()
test.measure(1, 0)
body = QuantumCircuit(qubits, [clbits[0]])
body.break_loop()
body.h(qubits[0])
body.continue_loop()
body.measure(qubits[1], clbits[0])
expected = QuantumCircuit(qubits, clbits)
expected.for_loop(range(2), None, body, qubits, [clbits[0]])
self.assertEqual(canonicalize_control_flow(test), canonicalize_control_flow(expected))
with self.subTest("while"):
cond = (clbits[0], 0)
test = QuantumCircuit(qubits, clbits)
with test.while_loop(cond):
test.break_loop()
test.h(0)
test.continue_loop()
test.measure(1, 0)
body = QuantumCircuit(qubits, [clbits[0]])
body.break_loop()
body.h(qubits[0])
body.continue_loop()
body.measure(qubits[1], clbits[0])
expected = QuantumCircuit(qubits, clbits)
expected.while_loop(cond, body, qubits, [clbits[0]])
self.assertEqual(canonicalize_control_flow(test), canonicalize_control_flow(expected))
@ddt.data(QuantumCircuit.break_loop, QuantumCircuit.continue_loop)
def test_break_continue_accept_c_if(self, loop_operation):
"""Test that ``break`` and ``continue`` statements accept :meth:`.Instruction.c_if` calls,
and that these propagate through correctly."""
qubits = [Qubit(), Qubit()]
clbits = [Clbit(), Clbit()]
with self.subTest("for"):
test = QuantumCircuit(qubits, clbits)
with test.for_loop(range(2)):
test.h(0)
loop_operation(test).c_if(1, 0)
body = QuantumCircuit([qubits[0]], [clbits[1]])
body.h(qubits[0])
loop_operation(body).c_if(clbits[1], 0)
expected = QuantumCircuit(qubits, clbits)
expected.for_loop(range(2), None, body, [qubits[0]], [clbits[1]])
self.assertEqual(canonicalize_control_flow(test), canonicalize_control_flow(expected))
with self.subTest("while"):
cond = (clbits[0], 0)
test = QuantumCircuit(qubits, clbits)
with test.while_loop(cond):
test.h(0)
loop_operation(test).c_if(1, 0)
body = QuantumCircuit([qubits[0]], clbits)
body.h(qubits[0])
loop_operation(body).c_if(clbits[1], 0)
expected = QuantumCircuit(qubits, clbits)
expected.while_loop(cond, body, [qubits[0]], clbits)
self.assertEqual(canonicalize_control_flow(test), canonicalize_control_flow(expected))
@ddt.data(QuantumCircuit.break_loop, QuantumCircuit.continue_loop)
def test_break_continue_only_expand_to_nearest_loop(self, loop_operation):
"""Test that a ``break`` or ``continue`` nested in more than one loop only expands as far as
the inner loop scope, not further."""
qubits = [Qubit(), Qubit(), Qubit()]
clbits = [Clbit(), Clbit(), Clbit()]
cond_inner = (clbits[0], 0)
cond_outer = (clbits[1], 0)
with self.subTest("for for"):
test = QuantumCircuit(qubits, clbits)
with test.for_loop(range(2)):
test.measure(1, 1)
with test.for_loop(range(2)):
test.h(0)
loop_operation(test)
loop_operation(test)
inner_body = QuantumCircuit([qubits[0]])
inner_body.h(qubits[0])
loop_operation(inner_body)
outer_body = QuantumCircuit([qubits[0], qubits[1], clbits[1]])
outer_body.measure(qubits[1], clbits[1])
outer_body.for_loop(range(2), None, inner_body, [qubits[0]], [])
loop_operation(outer_body)
expected = QuantumCircuit(qubits, clbits)
expected.for_loop(range(2), None, outer_body, [qubits[0], qubits[1]], [clbits[1]])
self.assertEqual(canonicalize_control_flow(test), canonicalize_control_flow(expected))
with self.subTest("for while"):
test = QuantumCircuit(qubits, clbits)
with test.for_loop(range(2)):
test.measure(1, 1)
with test.while_loop(cond_inner):
test.h(0)
loop_operation(test)
loop_operation(test)
inner_body = QuantumCircuit([qubits[0], clbits[0]])
inner_body.h(qubits[0])
loop_operation(inner_body)
outer_body = QuantumCircuit([qubits[0], qubits[1], clbits[0], clbits[1]])
outer_body.measure(qubits[1], clbits[1])
outer_body.while_loop(cond_inner, inner_body, [qubits[0]], [clbits[0]])
loop_operation(outer_body)
expected = QuantumCircuit(qubits, clbits)
expected.for_loop(
range(2), None, outer_body, [qubits[0], qubits[1]], [clbits[0], clbits[1]]
)
self.assertEqual(canonicalize_control_flow(test), canonicalize_control_flow(expected))
with self.subTest("while for"):
test = QuantumCircuit(qubits, clbits)
with test.while_loop(cond_outer):
test.measure(1, 1)
with test.for_loop(range(2)):
test.h(0)
loop_operation(test)
loop_operation(test)
inner_body = QuantumCircuit([qubits[0]])
inner_body.h(qubits[0])
loop_operation(inner_body)
outer_body = QuantumCircuit([qubits[0], qubits[1], clbits[1]])
outer_body.measure(qubits[1], clbits[1])
outer_body.for_loop(range(2), None, inner_body, [qubits[0]], [])
loop_operation(outer_body)
expected = QuantumCircuit(qubits, clbits)
expected.while_loop(cond_outer, outer_body, [qubits[0], qubits[1]], [clbits[1]])
self.assertEqual(canonicalize_control_flow(test), canonicalize_control_flow(expected))
with self.subTest("while while"):
test = QuantumCircuit(qubits, clbits)
with test.while_loop(cond_outer):
test.measure(1, 1)
with test.while_loop(cond_inner):
test.h(0)
loop_operation(test)
loop_operation(test)
inner_body = QuantumCircuit([qubits[0], clbits[0]])
inner_body.h(qubits[0])
loop_operation(inner_body)
outer_body = QuantumCircuit([qubits[0], qubits[1], clbits[0], clbits[1]])
outer_body.measure(qubits[1], clbits[1])
outer_body.while_loop(cond_inner, inner_body, [qubits[0]], [clbits[0]])
loop_operation(outer_body)
expected = QuantumCircuit(qubits, clbits)
expected.while_loop(
cond_outer, outer_body, [qubits[0], qubits[1]], [clbits[0], clbits[1]]
)
self.assertEqual(canonicalize_control_flow(test), canonicalize_control_flow(expected))
with self.subTest("for (for, for)"):
# This test is specifically to check that multiple inner loops with different numbers of
# variables to each ``break`` still expand correctly.
test = QuantumCircuit(qubits, clbits)
with test.for_loop(range(2)):
test.measure(1, 1)
with test.for_loop(range(2)):
test.h(0)
loop_operation(test)
with test.for_loop(range(2)):
test.h(2)
loop_operation(test)
loop_operation(test)
inner_body1 = QuantumCircuit([qubits[0]])
inner_body1.h(qubits[0])
loop_operation(inner_body1)
inner_body2 = QuantumCircuit([qubits[2]])
inner_body2.h(qubits[2])
loop_operation(inner_body2)
outer_body = QuantumCircuit([qubits[0], qubits[1], qubits[2], clbits[1]])
outer_body.measure(qubits[1], clbits[1])
outer_body.for_loop(range(2), None, inner_body1, [qubits[0]], [])
outer_body.for_loop(range(2), None, inner_body2, [qubits[2]], [])
loop_operation(outer_body)
expected = QuantumCircuit(qubits, clbits)
expected.for_loop(range(2), None, outer_body, qubits, [clbits[1]])
self.assertEqual(canonicalize_control_flow(test), canonicalize_control_flow(expected))
@ddt.data(QuantumCircuit.break_loop, QuantumCircuit.continue_loop)
def test_break_continue_nested_in_if(self, loop_operation):
"""Test that ``break`` and ``continue`` work correctly when inside an ``if`` block within a
loop. This includes testing that multiple different ``if`` statements with and without
``break`` expand to the correct number of arguments.
This is a very important case; it requires that the :obj:`.IfElseOp` is not built until the
loop builds, and that the width expands to include everything that the loop knows about, not
just the inner context. We test both ``if`` and ``if/else`` paths separately, because the
chaining of the context managers allows lots of possibilities for super weird edge cases.
There are several tests that build up in complexity to aid debugging if something goes
wrong; the aim is that there will be more information available depending on which of the
subtests pass and which fail.
"""
qubits = [Qubit(), Qubit(), Qubit()]
clbits = [Clbit(), Clbit(), Clbit(), Clbit()]
cond_inner = (clbits[0], 0)
cond_outer = (clbits[1], 0)
with self.subTest("for/if"):
test = QuantumCircuit(qubits, clbits)
with test.for_loop(range(2)):
with test.if_test(cond_inner):
loop_operation(test)
# The second empty `if` is to test that only blocks that _need_ to expand to be the
# full width of the loop do so.
with test.if_test(cond_inner):
pass
test.h(0).c_if(2, 0)
true_body1 = QuantumCircuit([qubits[0], clbits[0], clbits[2]])
loop_operation(true_body1)
true_body2 = QuantumCircuit([clbits[0]])
loop_body = QuantumCircuit([qubits[0], clbits[0], clbits[2]])
loop_body.if_test(cond_inner, true_body1, [qubits[0]], [clbits[0], clbits[2]])
loop_body.if_test(cond_inner, true_body2, [], [clbits[0]])
loop_body.h(qubits[0]).c_if(clbits[2], 0)
expected = QuantumCircuit(qubits, clbits)
expected.for_loop(range(2), None, loop_body, [qubits[0]], [clbits[0], clbits[2]])
self.assertEqual(canonicalize_control_flow(test), canonicalize_control_flow(expected))
with self.subTest("for/else"):
test = QuantumCircuit(qubits, clbits)
with test.for_loop(range(2)):
with test.if_test(cond_inner) as else_:
test.h(1)
with else_:
loop_operation(test)
with test.if_test(cond_inner) as else_:
pass
with else_:
pass
test.h(0).c_if(2, 0)
true_body1 = QuantumCircuit([qubits[0], qubits[1], clbits[0], clbits[2]])
true_body1.h(qubits[1])
false_body1 = QuantumCircuit([qubits[0], qubits[1], clbits[0], clbits[2]])
loop_operation(false_body1)
true_body2 = QuantumCircuit([clbits[0]])
false_body2 = QuantumCircuit([clbits[0]])
loop_body = QuantumCircuit([qubits[0], qubits[1], clbits[0], clbits[2]])
loop_body.if_else(
cond_inner, true_body1, false_body1, [qubits[0], qubits[1]], [clbits[0], clbits[2]]
)
loop_body.if_else(cond_inner, true_body2, false_body2, [], [clbits[0]])
loop_body.h(qubits[0]).c_if(clbits[2], 0)
expected = QuantumCircuit(qubits, clbits)
expected.for_loop(
range(2), None, loop_body, [qubits[0], qubits[1]], [clbits[0], clbits[2]]
)
self.assertEqual(canonicalize_control_flow(test), canonicalize_control_flow(expected))
with self.subTest("while/if"):
test = QuantumCircuit(qubits, clbits)
with test.while_loop(cond_outer):
with test.if_test(cond_inner):
loop_operation(test)
with test.if_test(cond_inner):
pass
test.h(0).c_if(2, 0)
true_body1 = QuantumCircuit([qubits[0], clbits[0], clbits[1], clbits[2]])
loop_operation(true_body1)
true_body2 = QuantumCircuit([clbits[0]])
loop_body = QuantumCircuit([qubits[0], clbits[0], clbits[1], clbits[2]])
loop_body.if_test(
cond_inner, true_body1, [qubits[0]], [clbits[0], clbits[1], clbits[2]]
)
loop_body.if_test(cond_inner, true_body2, [], [clbits[0]])
loop_body.h(qubits[0]).c_if(clbits[2], 0)
expected = QuantumCircuit(qubits, clbits)
expected.while_loop(
cond_outer, loop_body, [qubits[0]], [clbits[0], clbits[1], clbits[2]]
)
self.assertEqual(canonicalize_control_flow(test), canonicalize_control_flow(expected))
with self.subTest("while/else"):
test = QuantumCircuit(qubits, clbits)
with test.while_loop(cond_outer):
with test.if_test(cond_inner) as else_:
test.h(1)
with else_:
loop_operation(test)
with test.if_test(cond_inner) as else_:
pass
with else_:
pass
test.h(0).c_if(2, 0)
true_body1 = QuantumCircuit([qubits[0], qubits[1], clbits[0], clbits[1], clbits[2]])
true_body1.h(qubits[1])
false_body1 = QuantumCircuit([qubits[0], qubits[1], clbits[0], clbits[1], clbits[2]])
loop_operation(false_body1)
true_body2 = QuantumCircuit([clbits[0]])
false_body2 = QuantumCircuit([clbits[0]])
loop_body = QuantumCircuit([qubits[0], qubits[1], clbits[0], clbits[1], clbits[2]])
loop_body.if_else(
cond_inner,
true_body1,
false_body1,
[qubits[0], qubits[1]],
[clbits[0], clbits[1], clbits[2]],
)
loop_body.if_else(cond_inner, true_body2, false_body2, [], [clbits[0]])
loop_body.h(qubits[0]).c_if(clbits[2], 0)
expected = QuantumCircuit(qubits, clbits)
expected.while_loop(
cond_outer, loop_body, [qubits[0], qubits[1]], [clbits[0], clbits[1], clbits[2]]
)
self.assertEqual(canonicalize_control_flow(test), canonicalize_control_flow(expected))
@ddt.data(QuantumCircuit.break_loop, QuantumCircuit.continue_loop)
def test_break_continue_nested_in_switch(self, loop_operation):
"""Similar to the nested-in-if case, we have to ensure that `break` and `continue` inside a
`switch` expand in size to the containing loop."""
qubits = [Qubit(), Qubit(), Qubit()]
clbits = [Clbit(), Clbit(), Clbit(), Clbit()]
test = QuantumCircuit(qubits, clbits)
with test.for_loop(range(2)):
with test.switch(clbits[0]) as case:
with case(0):
loop_operation(test)
with case(1):
pass
# The second empty `switch` is to test that only blocks that _need_ to expand to be the
# full width of the loop do so.
with test.switch(clbits[0]) as case:
with case(case.DEFAULT):
pass
test.h(0).c_if(clbits[2], 0)
body0 = QuantumCircuit([qubits[0], clbits[0], clbits[2]])
loop_operation(body0)
body1 = QuantumCircuit([qubits[0], clbits[0], clbits[2]])
body2 = QuantumCircuit([clbits[0]])
loop_body = QuantumCircuit([qubits[0], clbits[0], clbits[2]])
loop_body.switch(clbits[0], [(0, body0), (1, body1)], [qubits[0]], [clbits[0], clbits[2]])
loop_body.switch(clbits[0], [(CASE_DEFAULT, body2)], [], [clbits[0]])
loop_body.h(qubits[0]).c_if(clbits[2], 0)
expected = QuantumCircuit(qubits, clbits)
expected.for_loop(range(2), None, loop_body, [qubits[0]], [clbits[0], clbits[2]])
self.assertEqual(canonicalize_control_flow(test), canonicalize_control_flow(expected))
@ddt.data(QuantumCircuit.break_loop, QuantumCircuit.continue_loop)
def test_break_continue_nested_in_multiple_switch(self, loop_operation):
"""Similar to the nested-in-if case, we have to ensure that `break` and `continue` inside
more than one `switch` in a loop expand in size to the containing loop."""
qubits = [Qubit(), Qubit(), Qubit()]
clbits = [Clbit(), Clbit(), Clbit()]
test = QuantumCircuit(qubits, clbits)
with test.for_loop(range(2)):
test.measure(1, 1)
with test.switch(1) as case:
with case(False):
test.h(0)
loop_operation(test)
with case(True):
pass
with test.switch(1) as case:
with case(False):
pass
with case(True):
test.h(2)
loop_operation(test)
loop_operation(test)
case1_f = QuantumCircuit([qubits[0], qubits[1], qubits[2], clbits[1]])
case1_f.h(qubits[0])
loop_operation(case1_f)
case1_t = QuantumCircuit([qubits[0], qubits[1], qubits[2], clbits[1]])
case2_f = QuantumCircuit([qubits[0], qubits[1], qubits[2], clbits[1]])
case2_t = QuantumCircuit([qubits[0], qubits[1], qubits[2], clbits[1]])
case2_t.h(qubits[2])
loop_operation(case2_t)
body = QuantumCircuit([qubits[0], qubits[1], qubits[2], clbits[1]])
body.measure(qubits[1], clbits[1])
body.switch(clbits[1], [(False, case1_f), (True, case1_t)], body.qubits, body.clbits)
body.switch(clbits[1], [(False, case2_f), (True, case2_t)], body.qubits, body.clbits)
loop_operation(body)
expected = QuantumCircuit(qubits, clbits)
expected.for_loop(range(2), None, body, qubits, [clbits[1]])
self.assertEqual(canonicalize_control_flow(test), canonicalize_control_flow(expected))
@ddt.data(QuantumCircuit.break_loop, QuantumCircuit.continue_loop)
def test_break_continue_deeply_nested(self, loop_operation):
"""Test that ``break`` and ``continue`` work correctly when inside more than one block
within a loop. This includes testing that multiple different statements with and without
``break`` expand to the correct number of arguments.
These are the deepest tests, hitting all parts of the deferred builder scopes. We test
``if``, ``if/else`` and ``switch`` paths at various levels of the scoping to try and account
for as many weird edge cases with the deferred behavior as possible. We try to make sure,
particularly in the most complicated examples, that there are resources added before and
after every single scope, to try and catch all possibilities of where resources may be
missed.
There are several tests that build up in complexity to aid debugging if something goes
wrong; the aim is that there will be more information available depending on which of the
subtests pass and which fail.
"""
# These are deliberately more than is absolutely needed so we can detect if extra resources
# are being erroneously included as well.
qubits = [Qubit() for _ in [None] * 20]
clbits = [Clbit() for _ in [None] * 20]
cond_inner = (clbits[0], 0)
cond_outer = (clbits[1], 0)
cond_loop = (clbits[2], 0)
with self.subTest("for/if/if"):
test = QuantumCircuit(qubits, clbits)
with test.for_loop(range(2)):
# outer true 1
with test.if_test(cond_outer):
# inner true 1
with test.if_test(cond_inner):
loop_operation(test)
# inner true 2
with test.if_test(cond_inner):
test.h(0).c_if(3, 0)
test.h(1).c_if(4, 0)
# outer true 2
with test.if_test(cond_outer):
test.h(2).c_if(5, 0)
test.h(3).c_if(6, 0)
inner_true_body1 = QuantumCircuit(qubits[:4], clbits[:2], clbits[3:7])
loop_operation(inner_true_body1)
inner_true_body2 = QuantumCircuit([qubits[0], clbits[0], clbits[3]])
inner_true_body2.h(qubits[0]).c_if(clbits[3], 0)
outer_true_body1 = QuantumCircuit(qubits[:4], clbits[:2], clbits[3:7])
outer_true_body1.if_test(
cond_inner, inner_true_body1, qubits[:4], clbits[:2] + clbits[3:7]
)
outer_true_body1.if_test(
cond_inner, inner_true_body2, [qubits[0]], [clbits[0], clbits[3]]
)
outer_true_body1.h(qubits[1]).c_if(clbits[4], 0)
outer_true_body2 = QuantumCircuit([qubits[2], clbits[1], clbits[5]])
outer_true_body2.h(qubits[2]).c_if(clbits[5], 0)
loop_body = QuantumCircuit(qubits[:4], clbits[:2] + clbits[3:7])
loop_body.if_test(cond_outer, outer_true_body1, qubits[:4], clbits[:2] + clbits[3:7])
loop_body.if_test(cond_outer, outer_true_body2, [qubits[2]], [clbits[1], clbits[5]])
loop_body.h(qubits[3]).c_if(clbits[6], 0)
expected = QuantumCircuit(qubits, clbits)
expected.for_loop(range(2), None, loop_body, qubits[:4], clbits[:2] + clbits[3:7])
self.assertEqual(canonicalize_control_flow(test), canonicalize_control_flow(expected))
with self.subTest("for/if/else"):
test = QuantumCircuit(qubits, clbits)
with test.for_loop(range(2)):
# outer 1
with test.if_test(cond_outer):
# inner 1
with test.if_test(cond_inner) as inner1_else:
test.h(0).c_if(3, 0)
with inner1_else:
loop_operation(test).c_if(4, 0)
# inner 2
with test.if_test(cond_inner) as inner2_else:
test.h(1).c_if(5, 0)
with inner2_else:
test.h(2).c_if(6, 0)
test.h(3).c_if(7, 0)
# outer 2
with test.if_test(cond_outer) as outer2_else:
test.h(4).c_if(8, 0)
with outer2_else:
test.h(5).c_if(9, 0)
test.h(6).c_if(10, 0)
inner1_true = QuantumCircuit(qubits[:7], clbits[:2], clbits[3:11])
inner1_true.h(qubits[0]).c_if(clbits[3], 0)
inner1_false = QuantumCircuit(qubits[:7], clbits[:2], clbits[3:11])
loop_operation(inner1_false).c_if(clbits[4], 0)
inner2_true = QuantumCircuit([qubits[1], qubits[2], clbits[0], clbits[5], clbits[6]])
inner2_true.h(qubits[1]).c_if(clbits[5], 0)
inner2_false = QuantumCircuit([qubits[1], qubits[2], clbits[0], clbits[5], clbits[6]])
inner2_false.h(qubits[2]).c_if(clbits[6], 0)
outer1_true = QuantumCircuit(qubits[:7], clbits[:2], clbits[3:11])
outer1_true.if_else(
cond_inner, inner1_true, inner1_false, qubits[:7], clbits[:2] + clbits[3:11]
)
outer1_true.if_else(
cond_inner,
inner2_true,
inner2_false,
qubits[1:3],
[clbits[0], clbits[5], clbits[6]],
)
outer1_true.h(qubits[3]).c_if(clbits[7], 0)
outer2_true = QuantumCircuit([qubits[4], qubits[5], clbits[1], clbits[8], clbits[9]])
outer2_true.h(qubits[4]).c_if(clbits[8], 0)
outer2_false = QuantumCircuit([qubits[4], qubits[5], clbits[1], clbits[8], clbits[9]])
outer2_false.h(qubits[5]).c_if(clbits[9], 0)
loop_body = QuantumCircuit(qubits[:7], clbits[:2], clbits[3:11])
loop_body.if_test(cond_outer, outer1_true, qubits[:7], clbits[:2] + clbits[3:11])
loop_body.if_else(
cond_outer,
outer2_true,
outer2_false,
qubits[4:6],
[clbits[1], clbits[8], clbits[9]],
)
loop_body.h(qubits[6]).c_if(clbits[10], 0)
expected = QuantumCircuit(qubits, clbits)
expected.for_loop(range(2), None, loop_body, qubits[:7], clbits[:2] + clbits[3:11])
self.assertEqual(canonicalize_control_flow(test), canonicalize_control_flow(expected))
with self.subTest("for/else/else/switch"):
# Look on my works, ye Mighty, and despair!
# (but also hopefully this is less hubristic pretension and more a useful stress test)
test = QuantumCircuit(qubits, clbits)
with test.for_loop(range(2)):
test.h(0).c_if(3, 0)
# outer 1
with test.if_test(cond_outer) as outer1_else:
test.h(1).c_if(4, 0)
with outer1_else:
test.h(2).c_if(5, 0)
# outer 2 (nesting the inner condition in the 'if')
with test.if_test(cond_outer) as outer2_else:
test.h(3).c_if(6, 0)
# inner 21
with test.if_test(cond_inner) as inner21_else:
loop_operation(test)
with inner21_else:
test.h(4).c_if(7, 0)
# inner 22
with test.if_test(cond_inner) as inner22_else:
test.h(5).c_if(8, 0)
with inner22_else:
loop_operation(test)
# inner 23
with test.switch(cond_inner[0]) as inner23_case:
with inner23_case(True):
test.h(5).c_if(8, 0)
with inner23_case(False):
loop_operation(test)
test.h(6).c_if(9, 0)
with outer2_else:
test.h(7).c_if(10, 0)
# inner 24
with test.if_test(cond_inner) as inner24_else:
test.h(8).c_if(11, 0)
with inner24_else:
test.h(9).c_if(12, 0)
# outer 3 (nesting the inner condition in an 'else' branch)
with test.if_test(cond_outer) as outer3_else:
test.h(10).c_if(13, 0)
with outer3_else:
test.h(11).c_if(14, 0)
# inner 31
with test.if_test(cond_inner) as inner31_else:
loop_operation(test)
with inner31_else:
test.h(12).c_if(15, 0)
# inner 32
with test.if_test(cond_inner) as inner32_else:
test.h(13).c_if(16, 0)
with inner32_else:
loop_operation(test)
# inner 33
with test.if_test(cond_inner) as inner33_else:
test.h(14).c_if(17, 0)
with inner33_else:
test.h(15).c_if(18, 0)
test.h(16).c_if(19, 0)
# End of test "for" loop.
# No `clbits[2]` here because that's only used in `cond_loop`, for while loops.
loop_qubits = qubits[:17]
loop_clbits = clbits[:2] + clbits[3:20]
loop_bits = loop_qubits + loop_clbits
outer1_true = QuantumCircuit([qubits[1], qubits[2], clbits[1], clbits[4], clbits[5]])
outer1_true.h(qubits[1]).c_if(clbits[4], 0)
outer1_false = QuantumCircuit([qubits[1], qubits[2], clbits[1], clbits[4], clbits[5]])
outer1_false.h(qubits[2]).c_if(clbits[5], 0)
inner21_true = QuantumCircuit(loop_bits)
loop_operation(inner21_true)
inner21_false = QuantumCircuit(loop_bits)
inner21_false.h(qubits[4]).c_if(clbits[7], 0)
inner22_true = QuantumCircuit(loop_bits)
inner22_true.h(qubits[5]).c_if(clbits[8], 0)
inner22_false = QuantumCircuit(loop_bits)
loop_operation(inner22_false)
inner23_true = QuantumCircuit(loop_bits)
inner23_true.h(qubits[5]).c_if(clbits[8], 0)
inner23_false = QuantumCircuit(loop_bits)
loop_operation(inner23_false)
inner24_true = QuantumCircuit(qubits[8:10], [clbits[0], clbits[11], clbits[12]])
inner24_true.h(qubits[8]).c_if(clbits[11], 0)
inner24_false = QuantumCircuit(qubits[8:10], [clbits[0], clbits[11], clbits[12]])
inner24_false.h(qubits[9]).c_if(clbits[12], 0)
outer2_true = QuantumCircuit(loop_bits)
outer2_true.h(qubits[3]).c_if(clbits[6], 0)
outer2_true.if_else(cond_inner, inner21_true, inner21_false, loop_qubits, loop_clbits)
outer2_true.if_else(cond_inner, inner22_true, inner22_false, loop_qubits, loop_clbits)
outer2_true.switch(
cond_inner[0],
[(True, inner23_true), (False, inner23_false)],
loop_qubits,
loop_clbits,
)
outer2_true.h(qubits[6]).c_if(clbits[9], 0)
outer2_false = QuantumCircuit(loop_bits)
outer2_false.h(qubits[7]).c_if(clbits[10], 0)
outer2_false.if_else(
cond_inner,
inner24_true,
inner24_false,
[qubits[8], qubits[9]],
[clbits[0], clbits[11], clbits[12]],
)
inner31_true = QuantumCircuit(loop_bits)
loop_operation(inner31_true)
inner31_false = QuantumCircuit(loop_bits)
inner31_false.h(qubits[12]).c_if(clbits[15], 0)
inner32_true = QuantumCircuit(loop_bits)
inner32_true.h(qubits[13]).c_if(clbits[16], 0)
inner32_false = QuantumCircuit(loop_bits)
loop_operation(inner32_false)
inner33_true = QuantumCircuit(qubits[14:16], [clbits[0], clbits[17], clbits[18]])
inner33_true.h(qubits[14]).c_if(clbits[17], 0)
inner33_false = QuantumCircuit(qubits[14:16], [clbits[0], clbits[17], clbits[18]])
inner33_false.h(qubits[15]).c_if(clbits[18], 0)
outer3_true = QuantumCircuit(loop_bits)
outer3_true.h(qubits[10]).c_if(clbits[13], 0)
outer3_false = QuantumCircuit(loop_bits)
outer3_false.h(qubits[11]).c_if(clbits[14], 0)
outer3_false.if_else(cond_inner, inner31_true, inner31_false, loop_qubits, loop_clbits)
outer3_false.if_else(cond_inner, inner32_true, inner32_false, loop_qubits, loop_clbits)
outer3_false.if_else(
cond_inner,
inner33_true,
inner33_false,
qubits[14:16],
[clbits[0], clbits[17], clbits[18]],
)
loop_body = QuantumCircuit(loop_bits)
loop_body.h(qubits[0]).c_if(clbits[3], 0)
loop_body.if_else(
cond_outer,
outer1_true,
outer1_false,
qubits[1:3],
[clbits[1], clbits[4], clbits[5]],
)
loop_body.if_else(cond_outer, outer2_true, outer2_false, loop_qubits, loop_clbits)
loop_body.if_else(cond_outer, outer3_true, outer3_false, loop_qubits, loop_clbits)
loop_body.h(qubits[16]).c_if(clbits[19], 0)
expected = QuantumCircuit(qubits, clbits)
expected.for_loop(range(2), None, loop_body, loop_qubits, loop_clbits)
self.assertEqual(canonicalize_control_flow(test), canonicalize_control_flow(expected))
# And now we repeat everything for "while" loops... Trying to parameterize the test over
# 'for/while' mostly just ends up in it being a bit illegible, because so many parameters
# vary in the explicit construction form. These tests are just copies of the above tests,
# but with `while_loop(cond_loop)` instead of `for_loop(range(2))`, and the corresponding
# clbit ranges updated to include `clbits[2]` from the condition.
with self.subTest("while/if/if"):
test = QuantumCircuit(qubits, clbits)
with test.while_loop(cond_loop):
# outer true 1
with test.if_test(cond_outer):
# inner true 1
with test.if_test(cond_inner):
loop_operation(test)
# inner true 2
with test.if_test(cond_inner):
test.h(0).c_if(3, 0)
test.h(1).c_if(4, 0)
# outer true 2
with test.if_test(cond_outer):
test.h(2).c_if(5, 0)
test.h(3).c_if(6, 0)
inner_true_body1 = QuantumCircuit(qubits[:4], clbits[:7])
loop_operation(inner_true_body1)
inner_true_body2 = QuantumCircuit([qubits[0], clbits[0], clbits[3]])
inner_true_body2.h(qubits[0]).c_if(clbits[3], 0)
outer_true_body1 = QuantumCircuit(qubits[:4], clbits[:7])
outer_true_body1.if_test(cond_inner, inner_true_body1, qubits[:4], clbits[:7])
outer_true_body1.if_test(
cond_inner, inner_true_body2, [qubits[0]], [clbits[0], clbits[3]]
)
outer_true_body1.h(qubits[1]).c_if(clbits[4], 0)
outer_true_body2 = QuantumCircuit([qubits[2], clbits[1], clbits[5]])
outer_true_body2.h(qubits[2]).c_if(clbits[5], 0)
loop_body = QuantumCircuit(qubits[:4], clbits[:7])
loop_body.if_test(cond_outer, outer_true_body1, qubits[:4], clbits[:7])
loop_body.if_test(cond_outer, outer_true_body2, [qubits[2]], [clbits[1], clbits[5]])
loop_body.h(qubits[3]).c_if(clbits[6], 0)
expected = QuantumCircuit(qubits, clbits)
expected.while_loop(cond_loop, loop_body, qubits[:4], clbits[:7])
self.assertEqual(canonicalize_control_flow(test), canonicalize_control_flow(expected))
with self.subTest("while/if/else"):
test = QuantumCircuit(qubits, clbits)
with test.while_loop(cond_loop):
# outer 1
with test.if_test(cond_outer):
# inner 1
with test.if_test(cond_inner) as inner1_else:
test.h(0).c_if(3, 0)
with inner1_else:
loop_operation(test).c_if(4, 0)
# inner 2
with test.if_test(cond_inner) as inner2_else:
test.h(1).c_if(5, 0)
with inner2_else:
test.h(2).c_if(6, 0)
test.h(3).c_if(7, 0)
# outer 2
with test.if_test(cond_outer) as outer2_else:
test.h(4).c_if(8, 0)
with outer2_else:
test.h(5).c_if(9, 0)
test.h(6).c_if(10, 0)
inner1_true = QuantumCircuit(qubits[:7], clbits[:11])
inner1_true.h(qubits[0]).c_if(clbits[3], 0)
inner1_false = QuantumCircuit(qubits[:7], clbits[:11])
loop_operation(inner1_false).c_if(clbits[4], 0)
inner2_true = QuantumCircuit([qubits[1], qubits[2], clbits[0], clbits[5], clbits[6]])
inner2_true.h(qubits[1]).c_if(clbits[5], 0)
inner2_false = QuantumCircuit([qubits[1], qubits[2], clbits[0], clbits[5], clbits[6]])
inner2_false.h(qubits[2]).c_if(clbits[6], 0)
outer1_true = QuantumCircuit(qubits[:7], clbits[:11])
outer1_true.if_else(cond_inner, inner1_true, inner1_false, qubits[:7], clbits[:11])
outer1_true.if_else(
cond_inner,
inner2_true,
inner2_false,
qubits[1:3],
[clbits[0], clbits[5], clbits[6]],
)
outer1_true.h(qubits[3]).c_if(clbits[7], 0)
outer2_true = QuantumCircuit([qubits[4], qubits[5], clbits[1], clbits[8], clbits[9]])
outer2_true.h(qubits[4]).c_if(clbits[8], 0)
outer2_false = QuantumCircuit([qubits[4], qubits[5], clbits[1], clbits[8], clbits[9]])
outer2_false.h(qubits[5]).c_if(clbits[9], 0)
loop_body = QuantumCircuit(qubits[:7], clbits[:11])
loop_body.if_test(cond_outer, outer1_true, qubits[:7], clbits[:11])
loop_body.if_else(
cond_outer,
outer2_true,
outer2_false,
qubits[4:6],
[clbits[1], clbits[8], clbits[9]],
)
loop_body.h(qubits[6]).c_if(clbits[10], 0)
expected = QuantumCircuit(qubits, clbits)
expected.while_loop(cond_loop, loop_body, qubits[:7], clbits[:11])
self.assertEqual(canonicalize_control_flow(test), canonicalize_control_flow(expected))
with self.subTest("while/else/else"):
test = QuantumCircuit(qubits, clbits)
with test.while_loop(cond_loop):
test.h(0).c_if(3, 0)
# outer 1
with test.if_test(cond_outer) as outer1_else:
test.h(1).c_if(4, 0)
with outer1_else:
test.h(2).c_if(5, 0)
# outer 2 (nesting the inner condition in the 'if')
with test.if_test(cond_outer) as outer2_else:
test.h(3).c_if(6, 0)
# inner 21
with test.if_test(cond_inner) as inner21_else:
loop_operation(test)
with inner21_else:
test.h(4).c_if(7, 0)
# inner 22
with test.if_test(cond_inner) as inner22_else:
test.h(5).c_if(8, 0)
with inner22_else:
loop_operation(test)
test.h(6).c_if(9, 0)
with outer2_else:
test.h(7).c_if(10, 0)
# inner 23
with test.if_test(cond_inner) as inner23_else:
test.h(8).c_if(11, 0)
with inner23_else:
test.h(9).c_if(12, 0)
# outer 3 (nesting the inner condition in an 'else' branch)
with test.if_test(cond_outer) as outer3_else:
test.h(10).c_if(13, 0)
with outer3_else:
test.h(11).c_if(14, 0)
# inner 31
with test.if_test(cond_inner) as inner31_else:
loop_operation(test)
with inner31_else:
test.h(12).c_if(15, 0)
# inner 32
with test.if_test(cond_inner) as inner32_else:
test.h(13).c_if(16, 0)
with inner32_else:
loop_operation(test)
# inner 33
with test.if_test(cond_inner) as inner33_else:
test.h(14).c_if(17, 0)
with inner33_else:
test.h(15).c_if(18, 0)
test.h(16).c_if(19, 0)
# End of test "for" loop.
# No `clbits[2]` here because that's only used in `cond_loop`, for while loops.
loop_qubits = qubits[:17]
loop_clbits = clbits[:20]
loop_bits = loop_qubits + loop_clbits
outer1_true = QuantumCircuit([qubits[1], qubits[2], clbits[1], clbits[4], clbits[5]])
outer1_true.h(qubits[1]).c_if(clbits[4], 0)
outer1_false = QuantumCircuit([qubits[1], qubits[2], clbits[1], clbits[4], clbits[5]])
outer1_false.h(qubits[2]).c_if(clbits[5], 0)
inner21_true = QuantumCircuit(loop_bits)
loop_operation(inner21_true)
inner21_false = QuantumCircuit(loop_bits)
inner21_false.h(qubits[4]).c_if(clbits[7], 0)
inner22_true = QuantumCircuit(loop_bits)
inner22_true.h(qubits[5]).c_if(clbits[8], 0)
inner22_false = QuantumCircuit(loop_bits)
loop_operation(inner22_false)
inner23_true = QuantumCircuit(qubits[8:10], [clbits[0], clbits[11], clbits[12]])
inner23_true.h(qubits[8]).c_if(clbits[11], 0)
inner23_false = QuantumCircuit(qubits[8:10], [clbits[0], clbits[11], clbits[12]])
inner23_false.h(qubits[9]).c_if(clbits[12], 0)
outer2_true = QuantumCircuit(loop_bits)
outer2_true.h(qubits[3]).c_if(clbits[6], 0)
outer2_true.if_else(cond_inner, inner21_true, inner21_false, loop_qubits, loop_clbits)
outer2_true.if_else(cond_inner, inner22_true, inner22_false, loop_qubits, loop_clbits)
outer2_true.h(qubits[6]).c_if(clbits[9], 0)
outer2_false = QuantumCircuit(loop_bits)
outer2_false.h(qubits[7]).c_if(clbits[10], 0)
outer2_false.if_else(
cond_inner,
inner23_true,
inner23_false,
[qubits[8], qubits[9]],
[clbits[0], clbits[11], clbits[12]],
)
inner31_true = QuantumCircuit(loop_bits)
loop_operation(inner31_true)
inner31_false = QuantumCircuit(loop_bits)
inner31_false.h(qubits[12]).c_if(clbits[15], 0)
inner32_true = QuantumCircuit(loop_bits)
inner32_true.h(qubits[13]).c_if(clbits[16], 0)
inner32_false = QuantumCircuit(loop_bits)
loop_operation(inner32_false)
inner33_true = QuantumCircuit(qubits[14:16], [clbits[0], clbits[17], clbits[18]])
inner33_true.h(qubits[14]).c_if(clbits[17], 0)
inner33_false = QuantumCircuit(qubits[14:16], [clbits[0], clbits[17], clbits[18]])
inner33_false.h(qubits[15]).c_if(clbits[18], 0)
outer3_true = QuantumCircuit(loop_bits)
outer3_true.h(qubits[10]).c_if(clbits[13], 0)
outer3_false = QuantumCircuit(loop_bits)
outer3_false.h(qubits[11]).c_if(clbits[14], 0)
outer3_false.if_else(cond_inner, inner31_true, inner31_false, loop_qubits, loop_clbits)
outer3_false.if_else(cond_inner, inner32_true, inner32_false, loop_qubits, loop_clbits)
outer3_false.if_else(
cond_inner,
inner33_true,
inner33_false,
qubits[14:16],
[clbits[0], clbits[17], clbits[18]],
)
loop_body = QuantumCircuit(loop_bits)
loop_body.h(qubits[0]).c_if(clbits[3], 0)
loop_body.if_else(
cond_outer,
outer1_true,
outer1_false,
qubits[1:3],
[clbits[1], clbits[4], clbits[5]],
)
loop_body.if_else(cond_outer, outer2_true, outer2_false, loop_qubits, loop_clbits)
loop_body.if_else(cond_outer, outer3_true, outer3_false, loop_qubits, loop_clbits)
loop_body.h(qubits[16]).c_if(clbits[19], 0)
expected = QuantumCircuit(qubits, clbits)
expected.while_loop(cond_loop, loop_body, loop_qubits, loop_clbits)
self.assertEqual(canonicalize_control_flow(test), canonicalize_control_flow(expected))
with self.subTest("if/while/if/switch"):
test = QuantumCircuit(qubits, clbits)
with test.if_test(cond_outer): # outer_t
test.h(0).c_if(3, 0)
with test.while_loop(cond_loop): # loop
test.h(1).c_if(4, 0)
with test.if_test(cond_inner): # inner_t
test.h(2).c_if(5, 0)
with test.switch(5) as case_:
with case_(False): # case_f
test.h(3).c_if(6, 0)
with case_(True): # case_t
loop_operation(test)
test.h(4).c_if(7, 0)
# exit inner_t
test.h(5).c_if(8, 0)
# exit loop
test.h(6).c_if(9, 0)
# exit outer_t
test.h(7).c_if(10, 0)
case_f = QuantumCircuit(qubits[1:6], [clbits[0], clbits[2]] + clbits[4:9])
case_f.h(qubits[3]).c_if(clbits[6], 0)
case_t = QuantumCircuit(qubits[1:6], [clbits[0], clbits[2]] + clbits[4:9])
loop_operation(case_t)
inner_t = QuantumCircuit(qubits[1:6], [clbits[0], clbits[2]] + clbits[4:9])
inner_t.h(qubits[2]).c_if(clbits[5], 0)
inner_t.switch(
clbits[5],
[(False, case_f), (True, case_t)],
qubits[1:6],
[clbits[0], clbits[2]] + clbits[4:9],
)
inner_t.h(qubits[4]).c_if(clbits[7], 0)
loop = QuantumCircuit(qubits[1:6], [clbits[0], clbits[2]] + clbits[4:9])
loop.h(qubits[1]).c_if(clbits[4], 0)
loop.if_test(cond_inner, inner_t, qubits[1:6], [clbits[0], clbits[2]] + clbits[4:9])
loop.h(qubits[5]).c_if(clbits[8], 0)
outer_t = QuantumCircuit(qubits[:7], clbits[:10])
outer_t.h(qubits[0]).c_if(clbits[3], 0)
outer_t.while_loop(cond_loop, loop, qubits[1:6], [clbits[0], clbits[2]] + clbits[4:9])
outer_t.h(qubits[6]).c_if(clbits[9], 0)
expected = QuantumCircuit(qubits, clbits)
expected.if_test(cond_outer, outer_t, qubits[:7], clbits[:10])
expected.h(qubits[7]).c_if(clbits[10], 0)
self.assertEqual(canonicalize_control_flow(test), canonicalize_control_flow(expected))
with self.subTest("switch/for/switch/else"):
test = QuantumCircuit(qubits, clbits)
with test.switch(0) as case_outer:
with case_outer(False): # outer_case_f
test.h(0).c_if(3, 0)
with test.for_loop(range(2)): # loop
test.h(1).c_if(4, 0)
with test.switch(1) as case_inner:
with case_inner(False): # inner_case_f
test.h(2).c_if(5, 0)
with test.if_test((2, True)) as else_: # if_t
test.h(3).c_if(6, 0)
with else_: # if_f
loop_operation(test)
test.h(4).c_if(7, 0)
with case_inner(True): # inner_case_t
loop_operation(test)
test.h(5).c_if(8, 0)
# exit loop1
test.h(6).c_if(9, 0)
with case_outer(True): # outer_case_t
test.h(7).c_if(10, 0)
test.h(8).c_if(11, 0)
if_t = QuantumCircuit(qubits[1:6], clbits[1:3] + clbits[4:9])
if_t.h(qubits[3]).c_if(clbits[6], 0)
if_f = QuantumCircuit(qubits[1:6], clbits[1:3] + clbits[4:9])
loop_operation(if_f)
inner_case_f = QuantumCircuit(qubits[1:6], clbits[1:3] + clbits[4:9])
inner_case_f.h(qubits[2]).c_if(clbits[5], 0)
inner_case_f.if_else(
(clbits[2], True), if_t, if_f, qubits[1:6], clbits[1:3] + clbits[4:9]
)
inner_case_f.h(qubits[4]).c_if(clbits[7], 0)
inner_case_t = QuantumCircuit(qubits[1:6], clbits[1:3] + clbits[4:9])
loop_operation(inner_case_t)
loop = QuantumCircuit(qubits[1:6], clbits[1:3] + clbits[4:9])
loop.h(qubits[1]).c_if(clbits[4], 0)
loop.switch(
clbits[1],
[(False, inner_case_f), (True, inner_case_t)],
qubits[1:6],
clbits[1:3] + clbits[4:9],
)
loop.h(qubits[5]).c_if(clbits[8], 0)
outer_case_f = QuantumCircuit(qubits[:8], clbits[:11])
outer_case_f.h(qubits[0]).c_if(clbits[3], 0)
outer_case_f.for_loop(range(2), None, loop, qubits[1:6], clbits[1:3] + clbits[4:9])
outer_case_f.h(qubits[6]).c_if(clbits[9], 0)
outer_case_t = QuantumCircuit(qubits[:8], clbits[:11])
outer_case_t.h(qubits[7]).c_if(clbits[10], 0)
expected = QuantumCircuit(qubits, clbits)
expected.switch(
clbits[0], [(False, outer_case_f), (True, outer_case_t)], qubits[:8], clbits[:11]
)
expected.h(qubits[8]).c_if(clbits[11], 0)
self.assertEqual(canonicalize_control_flow(test), canonicalize_control_flow(expected))
def test_for_handles_iterables_correctly(self):
"""Test that the ``indexset`` in ``for`` loops is handled the way we expect. In general,
this means all iterables are consumed into a tuple on first access, except for ``range``
which is passed through as-is."""
bits = [Qubit(), Clbit()]
expected_indices = (3, 9, 1)
with self.subTest("list"):
test = QuantumCircuit(bits)
with test.for_loop(list(expected_indices)):
pass
instruction = test.data[-1].operation
self.assertIsInstance(instruction, ForLoopOp)
indices, _, _ = instruction.params
self.assertEqual(indices, expected_indices)
with self.subTest("tuple"):
test = QuantumCircuit(bits)
with test.for_loop(tuple(expected_indices)):
pass
instruction = test.data[-1].operation
self.assertIsInstance(instruction, ForLoopOp)
indices, _, _ = instruction.params
self.assertEqual(indices, expected_indices)
with self.subTest("consumable"):
def consumable():
yield from expected_indices
test = QuantumCircuit(bits)
with test.for_loop(consumable()):
pass
instruction = test.data[-1].operation
self.assertIsInstance(instruction, ForLoopOp)
indices, _, _ = instruction.params
self.assertEqual(indices, expected_indices)
with self.subTest("range"):
range_indices = range(0, 8, 2)
test = QuantumCircuit(bits)
with test.for_loop(range_indices):
pass
instruction = test.data[-1].operation
self.assertIsInstance(instruction, ForLoopOp)
indices, _, _ = instruction.params
self.assertEqual(indices, range_indices)
def test_for_returns_a_given_parameter(self):
"""Test that the ``for``-loop manager returns the parameter that we gave it."""
parameter = Parameter("x")
test = QuantumCircuit(1, 1)
with test.for_loop((0, 1), parameter) as test_parameter:
pass
self.assertIs(test_parameter, parameter)
def test_for_binds_parameter_to_op(self):
"""Test that the ``for`` manager binds a parameter to the resulting :obj:`.ForLoopOp` if a
user-generated one is given, or if a generated parameter is used. Generated parameters that
are not used should not be bound."""
parameter = Parameter("x")
with self.subTest("passed and used"):
circuit = QuantumCircuit(1, 1)
with circuit.for_loop((0, 0.5 * math.pi), parameter) as received_parameter:
circuit.rx(received_parameter, 0)
self.assertIs(parameter, received_parameter)
instruction = circuit.data[-1].operation
self.assertIsInstance(instruction, ForLoopOp)
_, bound_parameter, _ = instruction.params
self.assertIs(bound_parameter, parameter)
with self.subTest("passed and unused"):
circuit = QuantumCircuit(1, 1)
with circuit.for_loop((0, 0.5 * math.pi), parameter) as received_parameter:
circuit.x(0)
self.assertIs(parameter, received_parameter)
instruction = circuit.data[-1].operation
self.assertIsInstance(instruction, ForLoopOp)
_, bound_parameter, _ = instruction.params
self.assertIs(parameter, received_parameter)
with self.subTest("generated and used"):
circuit = QuantumCircuit(1, 1)
with circuit.for_loop((0, 0.5 * math.pi)) as received_parameter:
circuit.rx(received_parameter, 0)
self.assertIsInstance(received_parameter, Parameter)
instruction = circuit.data[-1].operation
self.assertIsInstance(instruction, ForLoopOp)
_, bound_parameter, _ = instruction.params
self.assertIs(bound_parameter, received_parameter)
with self.subTest("generated and used in deferred-build if"):
circuit = QuantumCircuit(1, 1)
with circuit.for_loop((0, 0.5 * math.pi)) as received_parameter:
with circuit.if_test((0, 0)):
circuit.rx(received_parameter, 0)
circuit.break_loop()
self.assertIsInstance(received_parameter, Parameter)
instruction = circuit.data[-1].operation
self.assertIsInstance(instruction, ForLoopOp)
_, bound_parameter, _ = instruction.params
self.assertIs(bound_parameter, received_parameter)
with self.subTest("generated and used in deferred-build else"):
circuit = QuantumCircuit(1, 1)
with circuit.for_loop((0, 0.5 * math.pi)) as received_parameter:
with circuit.if_test((0, 0)) as else_:
pass
with else_:
circuit.rx(received_parameter, 0)
circuit.break_loop()
self.assertIsInstance(received_parameter, Parameter)
instruction = circuit.data[-1].operation
self.assertIsInstance(instruction, ForLoopOp)
_, bound_parameter, _ = instruction.params
self.assertIs(bound_parameter, received_parameter)
def test_for_does_not_bind_generated_parameter_if_unused(self):
"""Test that the ``for`` manager does not bind a generated parameter into the resulting
:obj:`.ForLoopOp` if the parameter was not used."""
test = QuantumCircuit(1, 1)
with test.for_loop(range(2)) as generated_parameter:
pass
instruction = test.data[-1].operation
self.assertIsInstance(instruction, ForLoopOp)
_, bound_parameter, _ = instruction.params
self.assertIsNot(generated_parameter, None)
self.assertIs(bound_parameter, None)
def test_for_allocates_parameters(self):
"""Test that the ``for``-loop manager allocates a parameter if it is given ``None``, and
that it always allocates new parameters."""
test = QuantumCircuit(1, 1)
with test.for_loop(range(2)) as outer_parameter:
with test.for_loop(range(2)) as inner_parameter:
pass
with test.for_loop(range(2)) as final_parameter:
pass
self.assertIsInstance(outer_parameter, Parameter)
self.assertIsInstance(inner_parameter, Parameter)
self.assertIsInstance(final_parameter, Parameter)
self.assertNotEqual(outer_parameter, inner_parameter)
self.assertNotEqual(outer_parameter, final_parameter)
self.assertNotEqual(inner_parameter, final_parameter)
def test_access_of_resources_from_direct_append(self):
"""Test that direct calls to :obj:`.QuantumCircuit.append` within a builder block still
collect all the relevant resources."""
qubits = [Qubit(), Qubit()]
clbits = [Clbit(), Clbit()]
cond = (clbits[0], 0)
with self.subTest("if"):
test = QuantumCircuit(qubits, clbits)
with test.if_test(cond):
test.append(Measure(), [qubits[1]], [clbits[1]])
true_body = QuantumCircuit([qubits[1]], clbits)
true_body.measure(qubits[1], clbits[1])
expected = QuantumCircuit(qubits, clbits)
expected.if_test(cond, true_body, [qubits[1]], clbits)
self.assertEqual(canonicalize_control_flow(test), canonicalize_control_flow(expected))
with self.subTest("else"):
test = QuantumCircuit(qubits, clbits)
with test.if_test(cond) as else_:
pass
with else_:
test.append(Measure(), [qubits[1]], [clbits[1]])
true_body = QuantumCircuit([qubits[1]], clbits)
false_body = QuantumCircuit([qubits[1]], clbits)
false_body.measure(qubits[1], clbits[1])
expected = QuantumCircuit(qubits, clbits)
expected.if_else(cond, true_body, false_body, [qubits[1]], clbits)
self.assertEqual(canonicalize_control_flow(test), canonicalize_control_flow(expected))
with self.subTest("for"):
test = QuantumCircuit(qubits, clbits)
with test.for_loop(range(2)):
test.append(Measure(), [qubits[1]], [clbits[1]])
body = QuantumCircuit([qubits[1]], [clbits[1]])
body.measure(qubits[1], clbits[1])
expected = QuantumCircuit(qubits, clbits)
expected.for_loop(range(2), None, body, [qubits[1]], [clbits[1]])
self.assertEqual(canonicalize_control_flow(test), canonicalize_control_flow(expected))
with self.subTest("while"):
test = QuantumCircuit(qubits, clbits)
with test.while_loop(cond):
test.append(Measure(), [qubits[1]], [clbits[1]])
body = QuantumCircuit([qubits[1]], clbits)
body.measure(qubits[1], clbits[1])
expected = QuantumCircuit(qubits, clbits)
expected.while_loop(cond, body, [qubits[1]], clbits)
self.assertEqual(canonicalize_control_flow(test), canonicalize_control_flow(expected))
with self.subTest("switch"):
test = QuantumCircuit(qubits, clbits)
with test.switch(cond[0]) as case:
with case(0):
test.append(Measure(), [qubits[1]], [clbits[1]])
body = QuantumCircuit([qubits[1]], clbits)
body.measure(qubits[1], clbits[1])
expected = QuantumCircuit(qubits, clbits)
expected.switch(cond[0], [(0, body)], [qubits[1]], clbits)
self.assertEqual(canonicalize_control_flow(test), canonicalize_control_flow(expected))
def test_access_of_clbit_from_c_if(self):
"""Test that resources added from a call to :meth:`.InstructionSet.c_if` propagate through
the context managers correctly."""
qubits = [Qubit(), Qubit()]
clbits = [Clbit(), Clbit()]
bits = qubits + clbits
cond = (clbits[0], 0)
with self.subTest("if"):
test = QuantumCircuit(bits)
with test.if_test(cond):
test.h(0).c_if(1, 0)
body = QuantumCircuit([qubits[0]], clbits)
body.h(qubits[0]).c_if(clbits[1], 0)
expected = QuantumCircuit(bits)
expected.if_test(cond, body, [qubits[0]], clbits)
with self.subTest("else"):
test = QuantumCircuit(bits)
with test.if_test(cond) as else_:
pass
with else_:
test.h(0).c_if(1, 0)
true_body = QuantumCircuit([qubits[0]], clbits)
false_body = QuantumCircuit([qubits[0]], clbits)
false_body.h(qubits[0]).c_if(clbits[1], 0)
expected = QuantumCircuit(bits)
expected.if_else(cond, true_body, false_body, [qubits[0]], clbits)
with self.subTest("for"):
test = QuantumCircuit(bits)
with test.for_loop(range(2)):
test.h(0).c_if(1, 0)
body = QuantumCircuit([qubits[0]], clbits)
body.h(qubits[0]).c_if(clbits[1], 0)
expected = QuantumCircuit(bits)
expected.for_loop(range(2), None, body, [qubits[0]], clbits)
with self.subTest("while"):
test = QuantumCircuit(bits)
with test.while_loop(cond):
test.h(0).c_if(1, 0)
body = QuantumCircuit([qubits[0]], clbits)
body.h(qubits[0]).c_if(clbits[1], 0)
expected = QuantumCircuit(bits)
expected.while_loop(cond, body, [qubits[0]], clbits)
with self.subTest("switch"):
test = QuantumCircuit(bits)
with test.switch(cond[0]) as case, case(False):
test.h(0).c_if(1, 0)
body = QuantumCircuit([qubits[0]], clbits)
body.h(qubits[0]).c_if(clbits[1], 0)
expected = QuantumCircuit(bits)
expected.switch(cond[0], [(False, body)], [qubits[0]], clbits)
with self.subTest("if inside for"):
test = QuantumCircuit(bits)
with test.for_loop(range(2)):
with test.if_test(cond):
test.h(0).c_if(1, 0)
true_body = QuantumCircuit([qubits[0]], clbits)
true_body.h(qubits[0]).c_if(clbits[1], 0)
body = QuantumCircuit([qubits[0]], clbits)
body.if_test(cond, body, [qubits[0]], clbits)
expected = QuantumCircuit(bits)
expected.for_loop(range(2), None, body, [qubits[0]], clbits)
with self.subTest("switch inside for"):
test = QuantumCircuit(bits)
with test.for_loop(range(2)), test.switch(cond[0]) as case, case(False):
test.h(0).c_if(1, 0)
body = QuantumCircuit([qubits[0]], clbits)
body.h(qubits[0]).c_if(clbits[1], 0)
body = QuantumCircuit([qubits[0]], clbits)
body.switch(cond[0], [(False, body)], [qubits[0]], clbits)
expected = QuantumCircuit(bits)
expected.for_loop(range(2), None, body, [qubits[0]], clbits)
def test_access_of_classicalregister_from_c_if(self):
"""Test that resources added from a call to :meth:`.InstructionSet.c_if` propagate through
the context managers correctly."""
qubits = [Qubit(), Qubit()]
creg = ClassicalRegister(2)
clbits = [Clbit()]
all_clbits = list(clbits) + list(creg)
cond = (clbits[0], 0)
with self.subTest("if"):
test = QuantumCircuit(qubits, clbits, creg)
with test.if_test(cond):
test.h(0).c_if(creg, 0)
body = QuantumCircuit([qubits[0]], clbits, creg)
body.h(qubits[0]).c_if(creg, 0)
expected = QuantumCircuit(qubits, clbits, creg)
expected.if_test(cond, body, [qubits[0]], all_clbits)
with self.subTest("else"):
test = QuantumCircuit(qubits, clbits, creg)
with test.if_test(cond) as else_:
pass
with else_:
test.h(0).c_if(1, 0)
true_body = QuantumCircuit([qubits[0]], clbits, creg)
false_body = QuantumCircuit([qubits[0]], clbits, creg)
false_body.h(qubits[0]).c_if(creg, 0)
expected = QuantumCircuit(qubits, clbits, creg)
expected.if_else(cond, true_body, false_body, [qubits[0]], all_clbits)
with self.subTest("for"):
test = QuantumCircuit(qubits, clbits, creg)
with test.for_loop(range(2)):
test.h(0).c_if(1, 0)
body = QuantumCircuit([qubits[0]], clbits, creg)
body.h(qubits[0]).c_if(creg, 0)
expected = QuantumCircuit(qubits, clbits, creg)
expected.for_loop(range(2), None, body, [qubits[0]], all_clbits)
with self.subTest("while"):
test = QuantumCircuit(qubits, clbits, creg)
with test.while_loop(cond):
test.h(0).c_if(creg, 0)
body = QuantumCircuit([qubits[0]], clbits, creg)
body.h(qubits[0]).c_if(creg, 0)
expected = QuantumCircuit(qubits, clbits, creg)
expected.while_loop(cond, body, [qubits[0]], all_clbits)
with self.subTest("switch"):
test = QuantumCircuit(qubits, clbits, creg)
with test.switch(cond[0]) as case, case(False):
test.h(0).c_if(creg, 0)
body = QuantumCircuit([qubits[0]], clbits, creg)
body.h(qubits[0]).c_if(creg, 0)
expected = QuantumCircuit(qubits, clbits, creg)
expected.switch(cond[0], [(False, body)], [qubits[0]], all_clbits)
with self.subTest("if inside for"):
test = QuantumCircuit(qubits, clbits, creg)
with test.for_loop(range(2)):
with test.if_test(cond):
test.h(0).c_if(creg, 0)
true_body = QuantumCircuit([qubits[0]], clbits, creg)
true_body.h(qubits[0]).c_if(creg, 0)
body = QuantumCircuit([qubits[0]], clbits, creg)
body.if_test(cond, body, [qubits[0]], all_clbits)
expected = QuantumCircuit(qubits, clbits, creg)
expected.for_loop(range(2), None, body, [qubits[0]], all_clbits)
with self.subTest("switch inside for"):
test = QuantumCircuit(qubits, clbits, creg)
with test.for_loop(range(2)):
with test.switch(cond[0]) as case, case(False):
test.h(0).c_if(creg, 0)
case = QuantumCircuit([qubits[0]], clbits, creg)
case.h(qubits[0]).c_if(creg, 0)
body = QuantumCircuit([qubits[0]], clbits, creg)
body.switch(cond[0], [(False, case)], [qubits[0]], all_clbits)
expected = QuantumCircuit(qubits, clbits, creg)
expected.for_loop(range(2), None, body, [qubits[0]], all_clbits)
def test_accept_broadcast_gates(self):
"""Test that the context managers accept gates that are broadcast during their addition to
the scope."""
qubits = [Qubit(), Qubit(), Qubit()]
clbits = [Clbit(), Clbit(), Clbit()]
cond = (clbits[0], 0)
with self.subTest("if"):
test = QuantumCircuit(qubits, clbits)
with test.if_test(cond):
test.measure([0, 1], [0, 1])
body = QuantumCircuit([qubits[0], qubits[1], clbits[0], clbits[1]])
body.measure(qubits[0], clbits[0])
body.measure(qubits[1], clbits[1])
expected = QuantumCircuit(qubits, clbits)
expected.if_test(cond, body, [qubits[0], qubits[1]], [clbits[0], clbits[1]])
self.assertEqual(canonicalize_control_flow(test), canonicalize_control_flow(expected))
with self.subTest("else"):
test = QuantumCircuit(qubits, clbits)
with test.if_test(cond) as else_:
pass
with else_:
test.measure([0, 1], [0, 1])
true_body = QuantumCircuit([qubits[0], qubits[1], clbits[0], clbits[1]])
false_body = QuantumCircuit([qubits[0], qubits[1], clbits[0], clbits[1]])
false_body.measure(qubits[0], clbits[0])
false_body.measure(qubits[1], clbits[1])
expected = QuantumCircuit(qubits, clbits)
expected.if_else(
cond, true_body, false_body, [qubits[0], qubits[1]], [clbits[0], clbits[1]]
)
self.assertEqual(canonicalize_control_flow(test), canonicalize_control_flow(expected))
with self.subTest("for"):
test = QuantumCircuit(qubits, clbits)
with test.for_loop(range(2)):
test.measure([0, 1], [0, 1])
body = QuantumCircuit([qubits[0], qubits[1], clbits[0], clbits[1]])
body.measure(qubits[0], clbits[0])
body.measure(qubits[1], clbits[1])
expected = QuantumCircuit(qubits, clbits)
expected.for_loop(range(2), None, body, [qubits[0], qubits[1]], [clbits[0], clbits[1]])
self.assertEqual(canonicalize_control_flow(test), canonicalize_control_flow(expected))
with self.subTest("while"):
test = QuantumCircuit(qubits, clbits)
with test.while_loop(cond):
test.measure([0, 1], [0, 1])
body = QuantumCircuit([qubits[0], qubits[1], clbits[0], clbits[1]])
body.measure(qubits[0], clbits[0])
body.measure(qubits[1], clbits[1])
expected = QuantumCircuit(qubits, clbits)
expected.while_loop(cond, body, [qubits[0], qubits[1]], [clbits[0], clbits[1]])
self.assertEqual(canonicalize_control_flow(test), canonicalize_control_flow(expected))
with self.subTest("switch"):
test = QuantumCircuit(qubits, clbits)
with test.switch(cond[0]) as case, case(True):
test.measure([0, 1], [0, 1])
body = QuantumCircuit([qubits[0], qubits[1], clbits[0], clbits[1]])
body.measure(qubits[0], clbits[0])
body.measure(qubits[1], clbits[1])
expected = QuantumCircuit(qubits, clbits)
expected.switch(cond[0], [(True, body)], [qubits[0], qubits[1]], [clbits[0], clbits[1]])
self.assertEqual(canonicalize_control_flow(test), canonicalize_control_flow(expected))
with self.subTest("if inside for"):
test = QuantumCircuit(qubits, clbits)
with test.for_loop(range(2)):
with test.if_test(cond):
test.measure([0, 1], [0, 1])
true_body = QuantumCircuit([qubits[0], qubits[1], clbits[0], clbits[1]])
true_body.measure(qubits[0], clbits[0])
true_body.measure(qubits[1], clbits[1])
for_body = QuantumCircuit([qubits[0], qubits[1], clbits[0], clbits[1]])
for_body.if_test(cond, true_body, [qubits[0], qubits[1]], [clbits[0], clbits[1]])
expected = QuantumCircuit(qubits, clbits)
expected.for_loop(
range(2), None, for_body, [qubits[0], qubits[1]], [clbits[0], clbits[1]]
)
self.assertEqual(canonicalize_control_flow(test), canonicalize_control_flow(expected))
with self.subTest("switch inside for"):
test = QuantumCircuit(qubits, clbits)
with test.for_loop(range(2)), test.switch(cond[0]) as case, case(True):
test.measure([0, 1], [0, 1])
case_body = QuantumCircuit([qubits[0], qubits[1], clbits[0], clbits[1]])
case_body.measure(qubits[0], clbits[0])
case_body.measure(qubits[1], clbits[1])
for_body = QuantumCircuit([qubits[0], qubits[1], clbits[0], clbits[1]])
for_body.switch(cond[0], [(True, body)], [qubits[0], qubits[1]], [clbits[0], clbits[1]])
expected = QuantumCircuit(qubits, clbits)
expected.for_loop(
range(2), None, for_body, [qubits[0], qubits[1]], [clbits[0], clbits[1]]
)
self.assertEqual(canonicalize_control_flow(test), canonicalize_control_flow(expected))
def test_labels_propagated_to_instruction(self):
"""Test that labels given to the circuit-builder interface are passed through."""
bits = [Qubit(), Clbit()]
cond = (bits[1], 0)
label = "sentinel_label"
with self.subTest("if"):
test = QuantumCircuit(bits)
with test.if_test(cond, label=label):
pass
instruction = test.data[-1].operation
self.assertIsInstance(instruction, IfElseOp)
self.assertEqual(instruction.label, label)
with self.subTest("if else"):
test = QuantumCircuit(bits)
with test.if_test(cond, label=label) as else_:
pass
with else_:
pass
instruction = test.data[-1].operation
self.assertIsInstance(instruction, IfElseOp)
self.assertEqual(instruction.label, label)
with self.subTest("for"):
test = QuantumCircuit(bits)
with test.for_loop(range(2), label=label):
pass
instruction = test.data[-1].operation
self.assertIsInstance(instruction, ForLoopOp)
self.assertEqual(instruction.label, label)
with self.subTest("while"):
test = QuantumCircuit(bits)
with test.while_loop(cond, label=label):
pass
instruction = test.data[-1].operation
self.assertIsInstance(instruction, WhileLoopOp)
self.assertEqual(instruction.label, label)
with self.subTest("switch"):
test = QuantumCircuit(bits)
with test.switch(cond[0], label=label) as case:
with case(False):
pass
instruction = test.data[-1].operation
self.assertIsInstance(instruction, SwitchCaseOp)
self.assertEqual(instruction.label, label)
# The tests of blocks inside 'for' are to ensure we're hitting the paths where the scope is
# built lazily at the completion of the 'for'.
with self.subTest("if inside for"):
test = QuantumCircuit(bits)
with test.for_loop(range(2)):
with test.if_test(cond, label=label):
# Use break to ensure that we're triggering the lazy building of 'if'.
test.break_loop()
instruction = test.data[-1].operation.blocks[0].data[-1].operation
self.assertIsInstance(instruction, IfElseOp)
self.assertEqual(instruction.label, label)
with self.subTest("else inside for"):
test = QuantumCircuit(bits)
with test.for_loop(range(2)):
with test.if_test(cond, label=label) as else_:
# Use break to ensure that we're triggering the lazy building of 'if'.
test.break_loop()
with else_:
test.break_loop()
instruction = test.data[-1].operation.blocks[0].data[-1].operation
self.assertIsInstance(instruction, IfElseOp)
self.assertEqual(instruction.label, label)
with self.subTest("switch inside for"):
test = QuantumCircuit(bits)
with test.for_loop(range(2)):
with test.switch(cond[0], label=label) as case:
with case(False):
# Use break to ensure that we're triggering the lazy building
test.break_loop()
instruction = test.data[-1].operation.blocks[0].data[-1].operation
self.assertIsInstance(instruction, SwitchCaseOp)
self.assertEqual(instruction.label, label)
def test_copy_of_circuits(self):
"""Test that various methods of copying a circuit made with the builder interface works."""
test = QuantumCircuit(5, 5)
cond = (test.clbits[2], False)
with test.if_test(cond) as else_:
test.cx(0, 1)
with else_:
test.h(2)
with test.for_loop(range(5)):
with test.if_test(cond):
test.x(3)
with test.while_loop(cond):
test.measure(0, 4)
self.assertEqual(test, test.copy())
self.assertEqual(test, copy.copy(test))
self.assertEqual(test, copy.deepcopy(test))
def test_copy_of_instructions(self):
"""Test that various methods of copying the actual instructions created by the builder
interface work."""
qubits = [Qubit() for _ in [None] * 3]
clbits = [Clbit() for _ in [None] * 3]
cond = (clbits[1], False)
with self.subTest("if"):
test = QuantumCircuit(qubits, clbits)
with test.if_test(cond):
test.cx(0, 1)
test.measure(2, 2)
if_instruction = test.data[0].operation
self.assertEqual(if_instruction, if_instruction.copy())
self.assertEqual(if_instruction, copy.copy(if_instruction))
self.assertEqual(if_instruction, copy.deepcopy(if_instruction))
with self.subTest("if/else"):
test = QuantumCircuit(qubits, clbits)
with test.if_test(cond) as else_:
test.cx(0, 1)
test.measure(2, 2)
with else_:
test.cx(1, 0)
test.measure(2, 2)
if_instruction = test.data[0].operation
self.assertEqual(if_instruction, if_instruction.copy())
self.assertEqual(if_instruction, copy.copy(if_instruction))
self.assertEqual(if_instruction, copy.deepcopy(if_instruction))
with self.subTest("for"):
test = QuantumCircuit(qubits, clbits)
with test.for_loop(range(4)):
test.cx(0, 1)
test.measure(2, 2)
for_instruction = test.data[0].operation
self.assertEqual(for_instruction, for_instruction.copy())
self.assertEqual(for_instruction, copy.copy(for_instruction))
self.assertEqual(for_instruction, copy.deepcopy(for_instruction))
with self.subTest("while"):
test = QuantumCircuit(qubits, clbits)
with test.while_loop(cond):
test.cx(0, 1)
test.measure(2, 2)
while_instruction = test.data[0].operation
self.assertEqual(while_instruction, while_instruction.copy())
self.assertEqual(while_instruction, copy.copy(while_instruction))
self.assertEqual(while_instruction, copy.deepcopy(while_instruction))
with self.subTest("switch"):
creg = ClassicalRegister(4)
test = QuantumCircuit(qubits, creg)
with test.switch(creg) as case:
with case(0):
test.h(0)
with case(1, 2, 3):
test.z(1)
with case(case.DEFAULT):
test.cx(0, 1)
test.measure(2, 2)
switch_instruction = test.data[0].operation
self.assertEqual(switch_instruction, switch_instruction.copy())
self.assertEqual(switch_instruction, copy.copy(switch_instruction))
self.assertEqual(switch_instruction, copy.deepcopy(switch_instruction))
def test_copy_of_instruction_parameters(self):
"""Test that various methods of copying the parameters inside instructions created by the
builder interface work. Regression test of gh-7367."""
qubits = [Qubit() for _ in [None] * 3]
clbits = [Clbit() for _ in [None] * 3]
cond = (clbits[1], False)
with self.subTest("if"):
test = QuantumCircuit(qubits, clbits)
with test.if_test(cond):
test.cx(0, 1)
test.measure(2, 2)
if_instruction = test.data[0].operation
(true_body,) = if_instruction.blocks
self.assertEqual(true_body, true_body.copy())
self.assertEqual(true_body, copy.copy(true_body))
self.assertEqual(true_body, copy.deepcopy(true_body))
with self.subTest("if/else"):
test = QuantumCircuit(qubits, clbits)
with test.if_test(cond) as else_:
test.cx(0, 1)
test.measure(2, 2)
with else_:
test.cx(1, 0)
test.measure(2, 2)
if_instruction = test.data[0].operation
true_body, false_body = if_instruction.blocks
self.assertEqual(true_body, true_body.copy())
self.assertEqual(true_body, copy.copy(true_body))
self.assertEqual(true_body, copy.deepcopy(true_body))
self.assertEqual(false_body, false_body.copy())
self.assertEqual(false_body, copy.copy(false_body))
self.assertEqual(false_body, copy.deepcopy(false_body))
with self.subTest("for"):
test = QuantumCircuit(qubits, clbits)
with test.for_loop(range(4)):
test.cx(0, 1)
test.measure(2, 2)
for_instruction = test.data[0].operation
(for_body,) = for_instruction.blocks
self.assertEqual(for_body, for_body.copy())
self.assertEqual(for_body, copy.copy(for_body))
self.assertEqual(for_body, copy.deepcopy(for_body))
with self.subTest("while"):
test = QuantumCircuit(qubits, clbits)
with test.while_loop(cond):
test.cx(0, 1)
test.measure(2, 2)
while_instruction = test.data[0].operation
(while_body,) = while_instruction.blocks
self.assertEqual(while_body, while_body.copy())
self.assertEqual(while_body, copy.copy(while_body))
self.assertEqual(while_body, copy.deepcopy(while_body))
with self.subTest("switch"):
test = QuantumCircuit(qubits, clbits)
with test.switch(cond[0]) as case, case(0):
test.cx(0, 1)
test.measure(2, 2)
case_instruction = test.data[0].operation
(case_body,) = case_instruction.blocks
self.assertEqual(case_body, case_body.copy())
self.assertEqual(case_body, copy.copy(case_body))
self.assertEqual(case_body, copy.deepcopy(case_body))
def test_inplace_compose_within_builder(self):
"""Test that QuantumCircuit.compose used in-place works as expected within control-flow
scopes."""
inner = QuantumCircuit(1)
inner.x(0)
base = QuantumCircuit(1, 1)
base.h(0)
base.measure(0, 0)
with self.subTest("if"):
outer = base.copy()
with outer.if_test((outer.clbits[0], 1)):
outer.compose(inner, inplace=True)
expected = base.copy()
with expected.if_test((expected.clbits[0], 1)):
expected.x(0)
self.assertEqual(canonicalize_control_flow(outer), canonicalize_control_flow(expected))
with self.subTest("else"):
outer = base.copy()
with outer.if_test((outer.clbits[0], 1)) as else_:
outer.compose(inner, inplace=True)
with else_:
outer.compose(inner, inplace=True)
expected = base.copy()
with expected.if_test((expected.clbits[0], 1)) as else_:
expected.x(0)
with else_:
expected.x(0)
self.assertEqual(canonicalize_control_flow(outer), canonicalize_control_flow(expected))
with self.subTest("for"):
outer = base.copy()
with outer.for_loop(range(3)):
outer.compose(inner, inplace=True)
expected = base.copy()
with expected.for_loop(range(3)):
expected.x(0)
self.assertEqual(canonicalize_control_flow(outer), canonicalize_control_flow(expected))
with self.subTest("while"):
outer = base.copy()
with outer.while_loop((outer.clbits[0], 0)):
outer.compose(inner, inplace=True)
expected = base.copy()
with expected.while_loop((outer.clbits[0], 0)):
expected.x(0)
self.assertEqual(canonicalize_control_flow(outer), canonicalize_control_flow(expected))
with self.subTest("switch"):
outer = base.copy()
with outer.switch(outer.clbits[0]) as case, case(False):
outer.compose(inner, inplace=True)
expected = base.copy()
with expected.switch(outer.clbits[0]) as case, case(False):
expected.x(0)
self.assertEqual(canonicalize_control_flow(outer), canonicalize_control_flow(expected))
def test_global_phase_of_blocks(self):
"""It should be possible to set a global phase of a scope independently of the containing
scope and other sibling scopes."""
qr = QuantumRegister(3)
cr = ClassicalRegister(3)
qc = QuantumCircuit(qr, cr, global_phase=math.pi)
with qc.if_test((qc.clbits[0], False)):
# This scope's phase shouldn't be affected by the outer scope.
self.assertEqual(qc.global_phase, 0.0)
qc.global_phase += math.pi / 2
self.assertEqual(qc.global_phase, math.pi / 2)
# Back outside the scope, the phase shouldn't have changed...
self.assertEqual(qc.global_phase, math.pi)
# ... but we still should be able to see the phase in the built block definition.
self.assertEqual(qc.data[-1].operation.blocks[0].global_phase, math.pi / 2)
with qc.while_loop((qc.clbits[1], False)):
self.assertEqual(qc.global_phase, 0.0)
qc.global_phase = 1 * math.pi / 7
with qc.for_loop(range(3)):
self.assertEqual(qc.global_phase, 0.0)
qc.global_phase = 2 * math.pi / 7
with qc.if_test((qc.clbits[2], False)) as else_:
self.assertEqual(qc.global_phase, 0.0)
qc.global_phase = 3 * math.pi / 7
with else_:
self.assertEqual(qc.global_phase, 0.0)
qc.global_phase = 4 * math.pi / 7
with qc.switch(cr) as case:
with case(0):
self.assertEqual(qc.global_phase, 0.0)
qc.global_phase = 5 * math.pi / 7
with case(case.DEFAULT):
self.assertEqual(qc.global_phase, 0.0)
qc.global_phase = 6 * math.pi / 7
while_body = qc.data[-1].operation.blocks[0]
for_body = while_body.data[0].operation.blocks[0]
if_body, else_body = while_body.data[1].operation.blocks
case_0_body, case_default_body = while_body.data[2].operation.blocks
# The setter should respect exact floating-point equality since the values are in the
# interval [0, pi).
self.assertEqual(
[
while_body.global_phase,
for_body.global_phase,
if_body.global_phase,
else_body.global_phase,
case_0_body.global_phase,
case_default_body.global_phase,
],
[i * math.pi / 7 for i in range(1, 7)],
)
def test_can_capture_input(self):
a = expr.Var.new("a", types.Bool())
b = expr.Var.new("b", types.Bool())
base = QuantumCircuit(inputs=[a, b])
with base.for_loop(range(3)):
base.store(a, expr.lift(True))
self.assertEqual(set(base.data[-1].operation.blocks[0].iter_captured_vars()), {a})
def test_can_capture_declared(self):
a = expr.Var.new("a", types.Bool())
b = expr.Var.new("b", types.Bool())
base = QuantumCircuit(declarations=[(a, expr.lift(False)), (b, expr.lift(True))])
with base.if_test(expr.lift(False)):
base.store(a, expr.lift(True))
self.assertEqual(set(base.data[-1].operation.blocks[0].iter_captured_vars()), {a})
def test_can_capture_capture(self):
# It's a bit wild to be manually building an outer circuit that's intended to be a subblock,
# but be using the control-flow builder interface internally, but eh, it should work.
a = expr.Var.new("a", types.Bool())
b = expr.Var.new("b", types.Bool())
base = QuantumCircuit(captures=[a, b])
with base.while_loop(expr.lift(False)):
base.store(a, expr.lift(True))
self.assertEqual(set(base.data[-1].operation.blocks[0].iter_captured_vars()), {a})
def test_can_capture_from_nested(self):
a = expr.Var.new("a", types.Bool())
b = expr.Var.new("b", types.Bool())
c = expr.Var.new("c", types.Bool())
base = QuantumCircuit(inputs=[a, b])
with base.switch(expr.lift(False)) as case, case(case.DEFAULT):
base.add_var(c, expr.lift(False))
with base.if_test(expr.lift(False)):
base.store(a, c)
outer_block = base.data[-1].operation.blocks[0]
inner_block = outer_block.data[-1].operation.blocks[0]
self.assertEqual(set(inner_block.iter_captured_vars()), {a, c})
# The containing block should have captured it as well, despite not using it explicitly.
self.assertEqual(set(outer_block.iter_captured_vars()), {a})
self.assertEqual(set(outer_block.iter_declared_vars()), {c})
def test_can_manually_capture(self):
a = expr.Var.new("a", types.Bool())
b = expr.Var.new("b", types.Bool())
base = QuantumCircuit(inputs=[a, b])
with base.while_loop(expr.lift(False)):
# Why do this? Who knows, but it clearly has a well-defined meaning.
base.add_capture(a)
self.assertEqual(set(base.data[-1].operation.blocks[0].iter_captured_vars()), {a})
def test_later_blocks_do_not_inherit_captures(self):
"""Neither 'if' nor 'switch' should have later blocks inherit the captures from the earlier
blocks, and the earlier blocks shouldn't be affected by later ones."""
a = expr.Var.new("a", types.Bool())
b = expr.Var.new("b", types.Bool())
c = expr.Var.new("c", types.Bool())
base = QuantumCircuit(inputs=[a, b, c])
with base.if_test(expr.lift(False)) as else_:
base.store(a, expr.lift(False))
with else_:
base.store(b, expr.lift(False))
blocks = base.data[-1].operation.blocks
self.assertEqual(set(blocks[0].iter_captured_vars()), {a})
self.assertEqual(set(blocks[1].iter_captured_vars()), {b})
base = QuantumCircuit(inputs=[a, b, c])
with base.switch(expr.lift(False)) as case:
with case(0):
base.store(a, expr.lift(False))
with case(case.DEFAULT):
base.store(b, expr.lift(False))
blocks = base.data[-1].operation.blocks
self.assertEqual(set(blocks[0].iter_captured_vars()), {a})
self.assertEqual(set(blocks[1].iter_captured_vars()), {b})
def test_blocks_have_independent_declarations(self):
"""The blocks of if and switch should be separate scopes for declarations."""
b1 = expr.Var.new("b", types.Bool())
b2 = expr.Var.new("b", types.Bool())
self.assertNotEqual(b1, b2)
base = QuantumCircuit()
with base.if_test(expr.lift(False)) as else_:
base.add_var(b1, expr.lift(False))
with else_:
base.add_var(b2, expr.lift(False))
blocks = base.data[-1].operation.blocks
self.assertEqual(set(blocks[0].iter_declared_vars()), {b1})
self.assertEqual(set(blocks[1].iter_declared_vars()), {b2})
base = QuantumCircuit()
with base.switch(expr.lift(False)) as case:
with case(0):
base.add_var(b1, expr.lift(False))
with case(case.DEFAULT):
base.add_var(b2, expr.lift(False))
blocks = base.data[-1].operation.blocks
self.assertEqual(set(blocks[0].iter_declared_vars()), {b1})
self.assertEqual(set(blocks[1].iter_declared_vars()), {b2})
def test_can_shadow_outer_name(self):
outer = expr.Var.new("a", types.Bool())
inner = expr.Var.new("a", types.Bool())
base = QuantumCircuit(inputs=[outer])
with base.if_test(expr.lift(False)):
base.add_var(inner, expr.lift(True))
block = base.data[-1].operation.blocks[0]
self.assertEqual(set(block.iter_declared_vars()), {inner})
self.assertEqual(set(block.iter_captured_vars()), set())
def test_iterators_run_over_scope(self):
a = expr.Var.new("a", types.Bool())
b = expr.Var.new("b", types.Bool())
c = expr.Var.new("c", types.Bool())
d = expr.Var.new("d", types.Bool())
base = QuantumCircuit(inputs=[a, b, c])
self.assertEqual(set(base.iter_input_vars()), {a, b, c})
self.assertEqual(set(base.iter_declared_vars()), set())
self.assertEqual(set(base.iter_captured_vars()), set())
with base.switch(expr.lift(3)) as case:
with case(0):
# Nothing here.
self.assertEqual(set(base.iter_vars()), set())
self.assertEqual(set(base.iter_input_vars()), set())
self.assertEqual(set(base.iter_declared_vars()), set())
self.assertEqual(set(base.iter_captured_vars()), set())
# Capture a variable.
base.store(a, expr.lift(False))
self.assertEqual(set(base.iter_captured_vars()), {a})
# Declare a variable.
base.add_var(d, expr.lift(False))
self.assertEqual(set(base.iter_declared_vars()), {d})
self.assertEqual(set(base.iter_vars()), {a, d})
with case(1):
# We should have reset.
self.assertEqual(set(base.iter_vars()), set())
self.assertEqual(set(base.iter_input_vars()), set())
self.assertEqual(set(base.iter_declared_vars()), set())
self.assertEqual(set(base.iter_captured_vars()), set())
# Capture a variable.
base.store(b, expr.lift(False))
self.assertEqual(set(base.iter_captured_vars()), {b})
# Capture some more in another scope.
with base.while_loop(expr.lift(False)):
self.assertEqual(set(base.iter_vars()), set())
base.store(c, expr.lift(False))
self.assertEqual(set(base.iter_captured_vars()), {c})
self.assertEqual(set(base.iter_captured_vars()), {b, c})
self.assertEqual(set(base.iter_vars()), {b, c})
# And back to the outer scope.
self.assertEqual(set(base.iter_input_vars()), {a, b, c})
self.assertEqual(set(base.iter_declared_vars()), set())
self.assertEqual(set(base.iter_captured_vars()), set())
def test_get_var_respects_scope(self):
outer = expr.Var.new("a", types.Bool())
inner = expr.Var.new("a", types.Bool())
base = QuantumCircuit(inputs=[outer])
self.assertEqual(base.get_var("a"), outer)
with base.if_test(expr.lift(False)) as else_:
# Before we've done anything, getting the variable should get the outer one.
self.assertEqual(base.get_var("a"), outer)
# If we shadow it, we should get the shadowed one after.
base.add_var(inner, expr.lift(False))
self.assertEqual(base.get_var("a"), inner)
with else_:
# In a new scope, we should see the outer one again.
self.assertEqual(base.get_var("a"), outer)
# ... until we shadow it.
base.add_var(inner, expr.lift(False))
self.assertEqual(base.get_var("a"), inner)
self.assertEqual(base.get_var("a"), outer)
def test_has_var_respects_scope(self):
outer = expr.Var.new("a", types.Bool())
inner = expr.Var.new("a", types.Bool())
base = QuantumCircuit(inputs=[outer])
self.assertEqual(base.get_var("a"), outer)
with base.if_test(expr.lift(False)) as else_:
self.assertFalse(base.has_var("b"))
# Before we've done anything, we should see the outer one.
self.assertTrue(base.has_var("a"))
self.assertTrue(base.has_var(outer))
self.assertFalse(base.has_var(inner))
# If we shadow it, we should see the shadowed one after.
base.add_var(inner, expr.lift(False))
self.assertTrue(base.has_var("a"))
self.assertFalse(base.has_var(outer))
self.assertTrue(base.has_var(inner))
with else_:
# In a new scope, we should see the outer one again.
self.assertTrue(base.has_var("a"))
self.assertTrue(base.has_var(outer))
self.assertFalse(base.has_var(inner))
# ... until we shadow it.
base.add_var(inner, expr.lift(False))
self.assertTrue(base.has_var("a"))
self.assertFalse(base.has_var(outer))
self.assertTrue(base.has_var(inner))
self.assertTrue(base.has_var("a"))
self.assertTrue(base.has_var(outer))
self.assertFalse(base.has_var(inner))
def test_store_to_clbit_captures_bit(self):
base = QuantumCircuit(1, 2)
with base.if_test(expr.lift(False)):
base.store(expr.lift(base.clbits[0]), expr.lift(True))
expected = QuantumCircuit(1, 2)
body = QuantumCircuit([expected.clbits[0]])
body.store(expr.lift(expected.clbits[0]), expr.lift(True))
expected.if_test(expr.lift(False), body, [], [0])
self.assertEqual(base, expected)
def test_store_to_register_captures_register(self):
cr1 = ClassicalRegister(2, "cr1")
cr2 = ClassicalRegister(2, "cr2")
base = QuantumCircuit(cr1, cr2)
with base.if_test(expr.lift(False)):
base.store(expr.lift(cr1), expr.lift(3))
body = QuantumCircuit(cr1)
body.store(expr.lift(cr1), expr.lift(3))
expected = QuantumCircuit(cr1, cr2)
expected.if_test(expr.lift(False), body, [], cr1[:])
self.assertEqual(base, expected)
def test_rebuild_captures_variables_in_blocks(self):
"""Test that when the separate blocks of a statement cause it to require a full rebuild of
the circuit objects during builder resolution, the variables are all moved over
correctly."""
a = expr.Var.new("🐍🐍🐍", types.Uint(8))
qc = QuantumCircuit(3, 1, inputs=[a])
qc.measure(0, 0)
b_outer = qc.add_var("b", False)
with qc.switch(a) as case:
with case(0):
qc.cx(1, 2)
qc.store(b_outer, True)
with case(1):
qc.store(qc.clbits[0], False)
with case(2):
# Explicit shadowing.
b_inner = qc.add_var("b", True)
with case(3):
qc.store(a, expr.lift(1, a.type))
with case(case.DEFAULT):
qc.cx(2, 1)
# (inputs, captures, declares) for each block of the `switch`.
expected = [
([], [b_outer], []),
([], [], []),
([], [], [b_inner]),
([], [a], []),
([], [], []),
]
actual = [
(
list(block.iter_input_vars()),
list(block.iter_captured_vars()),
list(block.iter_declared_vars()),
)
for block in qc.data[-1].operation.blocks
]
self.assertEqual(expected, actual)
@ddt.ddt
class TestControlFlowBuildersFailurePaths(QiskitTestCase):
"""Tests for the failure paths of the control-flow builders."""
def test_if_rejects_break_continue_if_not_in_loop(self):
"""Test that the ``if`` and ``else`` context managers raise a suitable exception if you try
to use a ``break`` or ``continue`` within them without being inside a loop. This is for
safety; without the loop context, the context manager will cause the wrong resources to be
assigned to the ``break``, so if you want to make a manual loop, you have to use manual
``if`` as well. That way the onus is on you."""
qubits = [Qubit()]
clbits = [Clbit()]
cond = (clbits[0], 0)
message = r"The current builder scope cannot take a '.*' because it is not in a loop\."
with self.subTest("if break"):
test = QuantumCircuit(qubits, clbits)
with test.if_test(cond):
with self.assertRaisesRegex(CircuitError, message):
test.break_loop()
with self.subTest("if continue"):
test = QuantumCircuit(qubits, clbits)
with test.if_test(cond):
with self.assertRaisesRegex(CircuitError, message):
test.continue_loop()
with self.subTest("else break"):
test = QuantumCircuit(qubits, clbits)
with test.if_test(cond) as else_:
pass
with else_:
with self.assertRaisesRegex(CircuitError, message):
test.break_loop()
with self.subTest("else continue"):
test = QuantumCircuit(qubits, clbits)
with test.if_test(cond) as else_:
pass
with else_:
with self.assertRaisesRegex(CircuitError, message):
test.continue_loop()
def test_for_rejects_reentry(self):
"""Test that the ``for``-loop context manager rejects attempts to re-enter it. Since it
holds some forms of state during execution (the loop variable, which may be generated), we
can't safely re-enter it and get the expected behavior."""
for_manager = QuantumCircuit(2, 2).for_loop(range(2))
with for_manager:
pass
with self.assertRaisesRegex(
CircuitError, r"A for-loop context manager cannot be re-entered."
):
with for_manager:
pass
def test_cannot_enter_else_context_incorrectly(self):
"""Test that various forms of using an 'else_' context manager incorrectly raise
exceptions."""
bits = [Qubit(), Clbit()]
cond = (bits[1], 0)
with self.subTest("not the next instruction"):
test = QuantumCircuit(bits)
with test.if_test(cond) as else_:
pass
test.h(0)
with self.assertRaisesRegex(CircuitError, "The 'if' block is not the most recent"):
with else_:
test.h(0)
with self.subTest("inside the attached if"):
test = QuantumCircuit(bits)
with test.if_test(cond) as else_:
with self.assertRaisesRegex(
CircuitError, r"Cannot attach an 'else' branch to an incomplete 'if' block\."
):
with else_:
test.h(0)
with self.subTest("inner else"):
test = QuantumCircuit(bits)
with test.if_test(cond) as else1:
with test.if_test(cond):
pass
with self.assertRaisesRegex(
CircuitError, r"Cannot attach an 'else' branch to an incomplete 'if' block\."
):
with else1:
test.h(0)
with self.subTest("reused else"):
test = QuantumCircuit(bits)
with test.if_test(cond) as else_:
pass
with else_:
pass
with self.assertRaisesRegex(CircuitError, r"Cannot re-use an 'else' context\."):
with else_:
pass
with self.subTest("else from an inner block"):
test = QuantumCircuit(bits)
with test.if_test(cond):
with test.if_test(cond) as else_:
pass
with self.assertRaisesRegex(CircuitError, "The 'if' block is not the most recent"):
with else_:
pass
def test_if_placeholder_rejects_c_if(self):
"""Test that the :obj:`.IfElsePlaceholder" class rejects attempts to use
:meth:`.Instruction.c_if` on it.
It *should* be the case that you need to use private methods to get access to one of these
placeholder objects at all, because they're appended to a scope at the exit of a context
manager, so not returned from a method call. Just in case, here's a test that it correctly
rejects the dangerous method that can overwrite ``condition``.
"""
bits = [Qubit(), Clbit()]
with self.subTest("if"):
test = QuantumCircuit(bits)
with test.for_loop(range(2)):
with test.if_test((bits[1], 0)):
test.break_loop()
# These tests need to be done before the 'for' context exits so we don't trigger the
# "can't add conditions from out-of-scope" handling.
placeholder = test._peek_previous_instruction_in_scope().operation
self.assertIsInstance(placeholder, IfElsePlaceholder)
with self.assertRaisesRegex(
NotImplementedError,
r"IfElseOp cannot be classically controlled through Instruction\.c_if",
):
placeholder.c_if(bits[1], 0)
with self.subTest("else"):
test = QuantumCircuit(bits)
with test.for_loop(range(2)):
with test.if_test((bits[1], 0)) as else_:
pass
with else_:
test.break_loop()
# These tests need to be done before the 'for' context exits so we don't trigger the
# "can't add conditions from out-of-scope" handling.
placeholder = test._peek_previous_instruction_in_scope().operation
self.assertIsInstance(placeholder, IfElsePlaceholder)
with self.assertRaisesRegex(
NotImplementedError,
r"IfElseOp cannot be classically controlled through Instruction\.c_if",
):
placeholder.c_if(bits[1], 0)
def test_switch_rejects_operations_outside_cases(self):
"""It shouldn't be permissible to try and put instructions inside a switch but outside a
case."""
circuit = QuantumCircuit(1, 1)
with circuit.switch(0) as case:
with case(0):
pass
with self.assertRaisesRegex(CircuitError, r"Cannot have instructions outside a case"):
circuit.x(0)
def test_switch_rejects_entering_case_after_close(self):
"""It shouldn't be possible to enter a case within another case."""
circuit = QuantumCircuit(1, 1)
with circuit.switch(0) as case, case(0):
pass
with self.assertRaisesRegex(CircuitError, r"Cannot add .* to a completed switch"), case(1):
pass
def test_switch_rejects_reentering_case(self):
"""It shouldn't be possible to enter a case within another case."""
circuit = QuantumCircuit(1, 1)
with circuit.switch(0) as case, case(0), self.assertRaisesRegex(
CircuitError, r"Cannot enter more than one case at once"
), case(1):
pass
@ddt.data("1", 1.0, None, (1, 2))
def test_switch_rejects_bad_case_value(self, value):
"""Only well-typed values should be accepted."""
circuit = QuantumCircuit(1, 1)
with circuit.switch(0) as case:
with case(0):
pass
with self.assertRaisesRegex(CircuitError, "Case values must be"), case(value):
pass
def test_case_rejects_duplicate_labels(self):
"""Using duplicates in the same `case` should raise an error."""
circuit = QuantumCircuit(1, 2)
with circuit.switch(circuit.cregs[0]) as case:
with case(0):
pass
with self.assertRaisesRegex(CircuitError, "duplicate"), case(1, 1):
pass
with self.assertRaisesRegex(CircuitError, "duplicate"), case(1, 2, 3, 1):
pass
def test_switch_rejects_duplicate_labels(self):
"""Using duplicates in different `case`s should raise an error."""
circuit = QuantumCircuit(1, 2)
with circuit.switch(circuit.cregs[0]) as case:
with case(0):
pass
with case(1):
pass
with self.assertRaisesRegex(CircuitError, "duplicate"), case(1):
pass
def test_switch_accepts_label_after_failure(self):
"""If one case causes an exception that's caught, subsequent cases should still be possible
using labels that were "used" by the failing case."""
qreg = QuantumRegister(1, "q")
creg = ClassicalRegister(2, "c")
test = QuantumCircuit(qreg, creg)
with test.switch(creg) as case:
with case(0):
pass
# assertRaises here is an extra test that the exception is propagated through the
# context manager, and acts as an `except` clause for the exception so control will
# continue beyond.
with self.assertRaises(SentinelException), case(1):
raise SentinelException
with case(1):
test.x(0)
expected = QuantumCircuit(qreg, creg)
with expected.switch(creg) as case:
with case(0):
pass
with case(1):
expected.x(0)
self.assertEqual(canonicalize_control_flow(test), canonicalize_control_flow(expected))
def test_reject_c_if_from_outside_scope(self):
"""Test that the context managers reject :meth:`.InstructionSet.c_if` calls if they occur
after their scope has completed."""
bits = [Qubit(), Clbit()]
cond = (bits[1], 0)
with self.subTest("if"):
test = QuantumCircuit(bits)
with test.if_test(cond):
instructions = test.h(0)
with self.assertRaisesRegex(
CircuitError, r"Cannot add resources after the scope has been built\."
):
instructions.c_if(*cond)
with self.subTest("else"):
test = QuantumCircuit(bits)
with test.if_test(cond) as else_:
pass
with else_:
instructions = test.h(0)
with self.assertRaisesRegex(
CircuitError, r"Cannot add resources after the scope has been built\."
):
instructions.c_if(*cond)
with self.subTest("for"):
test = QuantumCircuit(bits)
with test.for_loop(range(2)):
instructions = test.h(0)
with self.assertRaisesRegex(
CircuitError, r"Cannot add resources after the scope has been built\."
):
instructions.c_if(*cond)
with self.subTest("while"):
test = QuantumCircuit(bits)
with test.while_loop(cond):
instructions = test.h(0)
with self.assertRaisesRegex(
CircuitError, r"Cannot add resources after the scope has been built\."
):
instructions.c_if(*cond)
with self.subTest("switch"):
test = QuantumCircuit(bits)
with test.switch(bits[1]) as case, case(0):
instructions = test.h(0)
with self.assertRaisesRegex(
CircuitError, r"Cannot add resources after the scope has been built\."
):
instructions.c_if(*cond)
with self.subTest("if inside for"):
# As a side-effect of how the lazy building of 'if' statements works, we actually
# *could* add a condition to the gate after the 'if' block as long as we were still
# within the 'for' loop. It should actually manage the resource correctly as well, but
# it's "undefined behavior" than something we specifically want to forbid or allow.
test = QuantumCircuit(bits)
with test.for_loop(range(2)):
with test.if_test(cond):
instructions = test.h(0)
with self.assertRaisesRegex(
CircuitError, r"Cannot add resources after the scope has been built\."
):
instructions.c_if(*cond)
with self.subTest("switch inside for"):
# `switch` has the same lazy building as `if`, so is subject to the same considerations
# as the above subtest.
test = QuantumCircuit(bits)
with test.for_loop(range(2)):
with test.switch(bits[1]) as case:
with case(0):
instructions = test.h(0)
with self.assertRaisesRegex(
CircuitError, r"Cannot add resources after the scope has been built\."
):
instructions.c_if(*cond)
def test_raising_inside_context_manager_leave_circuit_usable(self):
"""Test that if we leave a builder by raising some sort of exception, the circuit is left in
a usable state, and extra resources have not been added to the circuit."""
x, y = Parameter("x"), Parameter("y")
with self.subTest("for"):
test = QuantumCircuit(1, 1)
test.h(0)
with self.assertRaises(SentinelException):
with test.for_loop(range(2), x) as bound_x:
test.x(0)
test.rx(bound_x, 0)
test.ry(y, 0)
raise SentinelException
test.z(0)
expected = QuantumCircuit(1, 1)
expected.h(0)
expected.z(0)
self.assertEqual(test, expected)
# We don't want _either_ the loop variable or the loose variable to be in the circuit.
self.assertEqual(set(), set(test.parameters))
with self.subTest("while"):
bits = [Qubit(), Clbit()]
test = QuantumCircuit(bits)
test.h(0)
with self.assertRaises(SentinelException):
with test.while_loop((bits[1], 0)):
test.x(0)
test.rx(x, 0)
raise SentinelException
test.z(0)
expected = QuantumCircuit(bits)
expected.h(0)
expected.z(0)
self.assertEqual(test, expected)
self.assertEqual(set(), set(test.parameters))
with self.subTest("if"):
bits = [Qubit(), Clbit()]
test = QuantumCircuit(bits)
test.h(0)
with self.assertRaises(SentinelException):
with test.if_test((bits[1], 0)):
test.x(0)
test.rx(x, 0)
raise SentinelException
test.z(0)
expected = QuantumCircuit(bits)
expected.h(0)
expected.z(0)
self.assertEqual(test, expected)
self.assertEqual(set(), set(test.parameters))
with self.subTest("else"):
bits = [Qubit(), Clbit()]
test = QuantumCircuit(bits)
test.h(0)
with test.if_test((bits[1], 0)) as else_:
test.rx(x, 0)
with self.assertRaises(SentinelException):
with else_:
test.x(0)
test.rx(y, 0)
raise SentinelException
test.z(0)
# Note that we expect the "else" manager to restore the "if" block if something errors
# out during "else" block.
true_body = QuantumCircuit(bits)
true_body.rx(x, 0)
expected = QuantumCircuit(bits)
expected.h(0)
expected.if_test((bits[1], 0), true_body, [0], [0])
expected.z(0)
self.assertEqual(test, expected)
self.assertEqual({x}, set(test.parameters))
with self.subTest("switch"):
test = QuantumCircuit(1, 1)
with self.assertRaises(SentinelException), test.switch(0) as case:
with case(False):
pass
with case(True):
pass
raise SentinelException
test.h(0)
expected = QuantumCircuit(1, 1)
expected.h(0)
self.assertEqual(test, expected)
def test_can_reuse_else_manager_after_exception(self):
"""Test that the "else" context manager is usable after a first attempt to construct it
raises an exception. Normally you cannot re-enter an "else" block, but we want the user to
be able to recover from errors if they so try."""
bits = [Qubit(), Clbit()]
test = QuantumCircuit(bits)
test.h(0)
with test.if_test((bits[1], 0)) as else_:
test.x(0)
with self.assertRaises(SentinelException):
with else_:
test.y(0)
raise SentinelException
with else_:
test.h(0)
test.z(0)
true_body = QuantumCircuit(bits)
true_body.x(0)
false_body = QuantumCircuit(bits)
false_body.h(0)
expected = QuantumCircuit(bits)
expected.h(0)
expected.if_else((bits[1], 0), true_body, false_body, [0], [0])
expected.z(0)
self.assertEqual(test, expected)
@ddt.data((None, [0]), ([0], None), ([0], [0]))
def test_context_managers_reject_passing_qubits(self, resources):
"""Test that the context-manager forms of the control-flow circuit methods raise exceptions
if they are given explicit qubits or clbits."""
test = QuantumCircuit(1, 1)
qubits, clbits = resources
with self.subTest("for"):
with self.assertRaisesRegex(
CircuitError,
r"When using 'for_loop' as a context manager, you cannot pass qubits or clbits\.",
):
test.for_loop(range(2), None, body=None, qubits=qubits, clbits=clbits)
with self.subTest("while"):
with self.assertRaisesRegex(
CircuitError,
r"When using 'while_loop' as a context manager, you cannot pass qubits or clbits\.",
):
test.while_loop((test.clbits[0], 0), body=None, qubits=qubits, clbits=clbits)
with self.subTest("if"):
with self.assertRaisesRegex(
CircuitError,
r"When using 'if_test' as a context manager, you cannot pass qubits or clbits\.",
):
test.if_test((test.clbits[0], 0), true_body=None, qubits=qubits, clbits=clbits)
with self.subTest("switch"):
with self.assertRaisesRegex(CircuitError, r"When using 'switch' as a context manager"):
test.switch(test.clbits[0], cases=None, qubits=qubits, clbits=clbits)
@ddt.data((None, [0]), ([0], None), (None, None))
def test_non_context_manager_calling_states_reject_missing_resources(self, resources):
"""Test that the non-context-manager forms of the control-flow circuit methods raise
exceptions if they are not given explicit qubits or clbits."""
test = QuantumCircuit(1, 1)
body = QuantumCircuit(1, 1)
qubits, clbits = resources
with self.subTest("for"):
with self.assertRaisesRegex(
CircuitError,
r"When using 'for_loop' with a body, you must pass qubits and clbits\.",
):
test.for_loop(range(2), None, body=body, qubits=qubits, clbits=clbits)
with self.subTest("while"):
with self.assertRaisesRegex(
CircuitError,
r"When using 'while_loop' with a body, you must pass qubits and clbits\.",
):
test.while_loop((test.clbits[0], 0), body=body, qubits=qubits, clbits=clbits)
with self.subTest("if"):
with self.assertRaisesRegex(
CircuitError,
r"When using 'if_test' with a body, you must pass qubits and clbits\.",
):
test.if_test((test.clbits[0], 0), true_body=body, qubits=qubits, clbits=clbits)
with self.subTest("switch"):
with self.assertRaisesRegex(
CircuitError,
r"When using 'switch' with cases, you must pass qubits and clbits\.",
):
test.switch(test.clbits[0], [(False, body)], qubits=qubits, clbits=clbits)
def test_compose_front_inplace_invalid_within_builder(self):
"""Test that `QuantumCircuit.compose` raises a sensible error when called within a
control-flow builder block."""
inner = QuantumCircuit(1)
inner.x(0)
outer = QuantumCircuit(1, 1)
outer.measure(0, 0)
outer.compose(inner, front=True, inplace=True)
with outer.if_test((outer.clbits[0], 1)):
with self.assertRaisesRegex(CircuitError, r"Cannot compose to the front.*"):
outer.compose(inner, front=True, inplace=True)
def test_compose_new_invalid_within_builder(self):
"""Test that `QuantumCircuit.compose` raises a sensible error when called within a
control-flow builder block if trying to emit a new circuit."""
inner = QuantumCircuit(1)
inner.x(0)
outer = QuantumCircuit(1, 1)
outer.measure(0, 0)
with outer.if_test((outer.clbits[0], 1)):
with self.assertRaisesRegex(CircuitError, r"Cannot emit a new composed circuit.*"):
outer.compose(inner, inplace=False)
def test_cannot_capture_variable_not_in_scope(self):
a = expr.Var.new("a", types.Bool())
base = QuantumCircuit(1, 1)
with base.if_test((0, True)) as else_, self.assertRaisesRegex(CircuitError, "not in scope"):
base.store(a, expr.lift(False))
with else_, self.assertRaisesRegex(CircuitError, "not in scope"):
base.store(a, expr.lift(False))
base.add_input(a)
with base.while_loop((0, True)), self.assertRaisesRegex(CircuitError, "not in scope"):
base.store(expr.Var.new("a", types.Bool()), expr.lift(False))
with base.for_loop(range(3)):
with base.switch(base.clbits[0]) as case, case(0):
with self.assertRaisesRegex(CircuitError, "not in scope"):
base.store(expr.Var.new("a", types.Bool()), expr.lift(False))
def test_cannot_add_existing_variable(self):
a = expr.Var.new("a", types.Bool())
base = QuantumCircuit()
with base.if_test(expr.lift(False)) as else_:
base.add_var(a, expr.lift(False))
with self.assertRaisesRegex(CircuitError, "already present"):
base.add_var(a, expr.lift(False))
with else_:
base.add_var(a, expr.lift(False))
with self.assertRaisesRegex(CircuitError, "already present"):
base.add_var(a, expr.lift(False))
def test_cannot_shadow_in_same_scope(self):
a = expr.Var.new("a", types.Bool())
base = QuantumCircuit()
with base.switch(expr.lift(3)) as case:
with case(0):
base.add_var(a, expr.lift(False))
with self.assertRaisesRegex(CircuitError, "its name shadows"):
base.add_var(a.name, expr.lift(False))
with case(case.DEFAULT):
base.add_var(a, expr.lift(False))
with self.assertRaisesRegex(CircuitError, "its name shadows"):
base.add_var(a.name, expr.lift(False))
def test_cannot_shadow_captured_variable(self):
"""It shouldn't be possible to shadow a variable that has already been captured into the
block."""
outer = expr.Var.new("a", types.Bool())
inner = expr.Var.new("a", types.Bool())
base = QuantumCircuit(inputs=[outer])
with base.while_loop(expr.lift(True)):
# Capture the outer.
base.store(outer, expr.lift(True))
# Attempt to shadow it.
with self.assertRaisesRegex(CircuitError, "its name shadows"):
base.add_var(inner, expr.lift(False))
def test_cannot_use_outer_variable_after_shadow(self):
"""If we've shadowed a variable, the outer one shouldn't be visible to us for use."""
outer = expr.Var.new("a", types.Bool())
inner = expr.Var.new("a", types.Bool())
base = QuantumCircuit(inputs=[outer])
with base.for_loop(range(3)):
# Shadow the outer.
base.add_var(inner, expr.lift(False))
with self.assertRaisesRegex(CircuitError, "cannot use.*shadowed"):
base.store(outer, expr.lift(True))
def test_cannot_use_beyond_outer_shadow(self):
outer = expr.Var.new("a", types.Bool())
inner = expr.Var.new("a", types.Bool())
base = QuantumCircuit(inputs=[outer])
with base.while_loop(expr.lift(True)):
# Shadow 'outer'
base.add_var(inner, expr.lift(True))
with base.switch(expr.lift(3)) as case, case(0):
with self.assertRaisesRegex(CircuitError, "not in scope"):
# Attempt to access the shadowed variable.
base.store(outer, expr.lift(False))
def test_exception_during_initialisation_does_not_add_variable(self):
uint_var = expr.Var.new("a", types.Uint(16))
bool_expr = expr.Value(False, types.Bool())
with self.assertRaises(CircuitError):
Store(uint_var, bool_expr)
base = QuantumCircuit()
with base.while_loop(expr.lift(False)):
# Should succeed.
b = base.add_var("b", expr.lift(False))
try:
base.add_var(uint_var, bool_expr)
except CircuitError:
pass
# Should succeed.
c = base.add_var("c", expr.lift(False))
local_vars = set(base.iter_vars())
self.assertEqual(local_vars, {b, c})
def test_cannot_use_old_var_not_in_circuit(self):
base = QuantumCircuit()
with base.if_test(expr.lift(False)) as else_:
with self.assertRaisesRegex(CircuitError, "not present"):
base.store(expr.lift(Clbit()), expr.lift(False))
with else_:
with self.assertRaisesRegex(CircuitError, "not present"):
with base.if_test(expr.equal(ClassicalRegister(2, "c"), 3)):
pass
def test_cannot_add_input_in_scope(self):
base = QuantumCircuit()
with base.for_loop(range(3)):
with self.assertRaisesRegex(CircuitError, "cannot add an input variable"):
base.add_input("a", types.Bool())
def test_cannot_add_uninitialized_in_scope(self):
base = QuantumCircuit()
with base.for_loop(range(3)):
with self.assertRaisesRegex(CircuitError, "cannot add an uninitialized variable"):
base.add_uninitialized_var(expr.Var.new("a", types.Bool()))
| qiskit/test/python/circuit/test_control_flow_builders.py/0 | {
"file_path": "qiskit/test/python/circuit/test_control_flow_builders.py",
"repo_id": "qiskit",
"token_count": 85761
} | 315 |
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 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 piecewise polynomial Pauli rotations."""
import unittest
from collections import defaultdict
import numpy as np
from ddt import ddt, data, unpack
from qiskit.circuit import QuantumCircuit
from qiskit.circuit.library.arithmetic.piecewise_polynomial_pauli_rotations import (
PiecewisePolynomialPauliRotations,
)
from qiskit.quantum_info import Statevector
from test import QiskitTestCase # pylint: disable=wrong-import-order
@ddt
class TestPiecewisePolynomialRotations(QiskitTestCase):
"""Test the piecewise polynomial Pauli rotations."""
def assertFunctionIsCorrect(self, function_circuit, reference):
"""Assert that ``function_circuit`` implements the reference function ``reference``."""
num_state_qubits = function_circuit.num_state_qubits
num_ancilla_qubits = function_circuit.num_ancillas
circuit = QuantumCircuit(num_state_qubits + 1 + num_ancilla_qubits)
circuit.h(list(range(num_state_qubits)))
circuit.append(function_circuit.to_instruction(), list(range(circuit.num_qubits)))
statevector = Statevector(circuit)
probabilities = defaultdict(float)
for i, statevector_amplitude in enumerate(statevector):
i = bin(i)[2:].zfill(circuit.num_qubits)[num_ancilla_qubits:]
probabilities[i] += np.real(np.abs(statevector_amplitude) ** 2)
unrolled_probabilities = []
unrolled_expectations = []
for i, probability in probabilities.items():
x, last_qubit = int(i[1:], 2), i[0]
if last_qubit == "0":
expected_amplitude = np.cos(reference(x)) / np.sqrt(2**num_state_qubits)
else:
expected_amplitude = np.sin(reference(x)) / np.sqrt(2**num_state_qubits)
unrolled_probabilities += [probability]
unrolled_expectations += [np.real(np.abs(expected_amplitude) ** 2)]
np.testing.assert_almost_equal(unrolled_probabilities, unrolled_expectations)
@data(
(1, [0], [[1]]),
(2, [0, 2], [[2], [-0.5, 1]]),
(3, [0, 2, 5], [[1, 0, -1], [2, 1], [1, 1, 1]]),
(4, [2, 5, 7, 16], [[1, -1], [1, 2, 3], [1, 2, 3, 4]]),
(3, [0, 1], [[1, 0], [1, -2]]),
)
@unpack
def test_piecewise_polynomial_function(self, num_state_qubits, breakpoints, coeffs):
"""Test the piecewise linear rotations."""
def pw_poly(x):
for i, point in enumerate(reversed(breakpoints[: len(coeffs)])):
if x >= point:
# Rescale the coefficients to take into account the 2 * theta argument from the
# rotation gates
rescaled_c = [coeff / 2 for coeff in coeffs[-(i + 1)][::-1]]
return np.poly1d(rescaled_c)(x)
return 0
pw_polynomial_rotations = PiecewisePolynomialPauliRotations(
num_state_qubits, breakpoints, coeffs
)
self.assertFunctionIsCorrect(pw_polynomial_rotations, pw_poly)
def test_piecewise_polynomial_rotations_mutability(self):
"""Test the mutability of the linear rotations circuit."""
def pw_poly(x):
for i, point in enumerate(reversed(breakpoints[: len(coeffs)])):
if x >= point:
# Rescale the coefficients to take into account the 2 * theta argument from the
# rotation gates
rescaled_c = [coeff / 2 for coeff in coeffs[-(i + 1)][::-1]]
return np.poly1d(rescaled_c)(x)
return 0
pw_polynomial_rotations = PiecewisePolynomialPauliRotations()
with self.subTest(msg="missing number of state qubits"):
with self.assertRaises(AttributeError): # no state qubits set
_ = str(pw_polynomial_rotations.draw())
with self.subTest(msg="default setup, just setting number of state qubits"):
pw_polynomial_rotations.num_state_qubits = 2
self.assertFunctionIsCorrect(pw_polynomial_rotations, lambda x: 1 / 2)
with self.subTest(msg="setting non-default values"):
breakpoints = [0, 2]
coeffs = [[0, -2 * 1.2], [-2 * 1, 2 * 1, 2 * 3]]
pw_polynomial_rotations.breakpoints = breakpoints
pw_polynomial_rotations.coeffs = coeffs
self.assertFunctionIsCorrect(pw_polynomial_rotations, pw_poly)
with self.subTest(msg="changing all values"):
pw_polynomial_rotations.num_state_qubits = 4
breakpoints = [1, 3, 6]
coeffs = [[0, -2 * 1.2], [-2 * 1, 2 * 1, 2 * 3], [-2 * 2]]
pw_polynomial_rotations.breakpoints = breakpoints
pw_polynomial_rotations.coeffs = coeffs
self.assertFunctionIsCorrect(pw_polynomial_rotations, pw_poly)
if __name__ == "__main__":
unittest.main()
| qiskit/test/python/circuit/test_piecewise_polynomial.py/0 | {
"file_path": "qiskit/test/python/circuit/test_piecewise_polynomial.py",
"repo_id": "qiskit",
"token_count": 2353
} | 316 |
# This code is part of Qiskit.
#
# (C) Copyright IBM 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
# pylint: disable=missing-function-docstring, undefined-variable
"""These are bad examples and raise errors in in the classicalfunction compiler"""
from qiskit.circuit.classicalfunction.types import Int1, Int2
def id_no_type_arg(a) -> Int1:
return a
def id_no_type_return(a: Int1):
return a
def id_bad_return(a: Int1) -> Int2:
return a
def out_of_scope(a: Int1) -> Int1:
return a & c
def bit_not(a: Int1) -> Int1:
# Bitwise not does not operate on booleans (aka, bits), but int
return ~a
| qiskit/test/python/classical_function_compiler/bad_examples.py/0 | {
"file_path": "qiskit/test/python/classical_function_compiler/bad_examples.py",
"repo_id": "qiskit",
"token_count": 325
} | 317 |
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Assembler Test.
FULLY REMOVE ONCE Qobj, assemble AND disassemble ARE REMOVED.
"""
import unittest
import numpy as np
from numpy.testing import assert_allclose
from qiskit import pulse
from qiskit.compiler.assembler import assemble
from qiskit.assembler.disassemble import disassemble
from qiskit.assembler.run_config import RunConfig
from qiskit.circuit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.circuit import Gate, Instruction, Parameter
from qiskit.circuit.library import RXGate, Isometry
from qiskit.pulse.transforms import target_qobj_transform
from qiskit.providers.fake_provider import FakeOpenPulse2Q
import qiskit.quantum_info as qi
from test import QiskitTestCase # pylint: disable=wrong-import-order
def _parametric_to_waveforms(schedule):
instructions = list(schedule.instructions)
for i, time_instruction_tuple in enumerate(schedule.instructions):
time, instruction = time_instruction_tuple
if not isinstance(instruction.pulse, pulse.library.Waveform):
new_inst = pulse.Play(instruction.pulse.get_waveform(), instruction.channel)
instructions[i] = (time, new_inst)
return tuple(instructions)
class TestQuantumCircuitDisassembler(QiskitTestCase):
"""Tests for disassembling circuits to qobj."""
def test_disassemble_single_circuit(self):
"""Test disassembling a single circuit."""
qr = QuantumRegister(2, name="q")
cr = ClassicalRegister(2, name="c")
circ = QuantumCircuit(qr, cr, name="circ")
circ.h(qr[0])
circ.cx(qr[0], qr[1])
circ.measure(qr, cr)
qubit_lo_freq = [5e9, 5e9]
meas_lo_freq = [6.7e9, 6.7e9]
with self.assertWarns(DeprecationWarning):
qobj = assemble(
circ,
shots=2000,
memory=True,
qubit_lo_freq=qubit_lo_freq,
meas_lo_freq=meas_lo_freq,
)
circuits, run_config_out, headers = disassemble(qobj)
run_config_out = RunConfig(**run_config_out)
self.assertEqual(run_config_out.n_qubits, 2)
self.assertEqual(run_config_out.memory_slots, 2)
self.assertEqual(run_config_out.shots, 2000)
self.assertEqual(run_config_out.memory, True)
self.assertEqual(run_config_out.qubit_lo_freq, qubit_lo_freq)
self.assertEqual(run_config_out.meas_lo_freq, meas_lo_freq)
self.assertEqual(len(circuits), 1)
self.assertEqual(circuits[0], circ)
self.assertEqual({}, headers)
def test_disassemble_multiple_circuits(self):
"""Test disassembling multiple circuits, all should have the same config."""
qr0 = QuantumRegister(2, name="q0")
qc0 = ClassicalRegister(2, name="c0")
circ0 = QuantumCircuit(qr0, qc0, name="circ0")
circ0.h(qr0[0])
circ0.cx(qr0[0], qr0[1])
circ0.measure(qr0, qc0)
qr1 = QuantumRegister(3, name="q1")
qc1 = ClassicalRegister(3, name="c1")
circ1 = QuantumCircuit(qr1, qc1, name="circ0")
circ1.h(qr1[0])
circ1.cx(qr1[0], qr1[1])
circ1.cx(qr1[0], qr1[2])
circ1.measure(qr1, qc1)
with self.assertWarns(DeprecationWarning):
qobj = assemble([circ0, circ1], shots=100, memory=False, seed=6)
circuits, run_config_out, headers = disassemble(qobj)
run_config_out = RunConfig(**run_config_out)
self.assertEqual(run_config_out.n_qubits, 3)
self.assertEqual(run_config_out.memory_slots, 3)
self.assertEqual(run_config_out.shots, 100)
self.assertEqual(run_config_out.memory, False)
self.assertEqual(run_config_out.seed, 6)
self.assertEqual(len(circuits), 2)
for circuit in circuits:
self.assertIn(circuit, [circ0, circ1])
self.assertEqual({}, headers)
def test_disassemble_no_run_config(self):
"""Test disassembling with no run_config, relying on default."""
qr = QuantumRegister(2, name="q")
qc = ClassicalRegister(2, name="c")
circ = QuantumCircuit(qr, qc, name="circ")
circ.h(qr[0])
circ.cx(qr[0], qr[1])
circ.measure(qr, qc)
with self.assertWarns(DeprecationWarning):
qobj = assemble(circ)
circuits, run_config_out, headers = disassemble(qobj)
run_config_out = RunConfig(**run_config_out)
self.assertEqual(run_config_out.n_qubits, 2)
self.assertEqual(run_config_out.memory_slots, 2)
self.assertEqual(len(circuits), 1)
self.assertEqual(circuits[0], circ)
self.assertEqual({}, headers)
def test_disassemble_initialize(self):
"""Test disassembling a circuit with an initialize."""
q = QuantumRegister(2, name="q")
circ = QuantumCircuit(q, name="circ")
circ.initialize([1 / np.sqrt(2), 0, 0, 1 / np.sqrt(2)], q[:])
with self.assertWarns(DeprecationWarning):
qobj = assemble(circ)
circuits, run_config_out, header = disassemble(qobj)
run_config_out = RunConfig(**run_config_out)
self.assertEqual(run_config_out.n_qubits, 2)
self.assertEqual(run_config_out.memory_slots, 0)
self.assertEqual(len(circuits), 1)
self.assertEqual(circuits[0], circ)
self.assertEqual({}, header)
def test_disassemble_isometry(self):
"""Test disassembling a circuit with an isometry."""
q = QuantumRegister(2, name="q")
circ = QuantumCircuit(q, name="circ")
circ.append(Isometry(qi.random_unitary(4).data, 0, 0), circ.qubits)
with self.assertWarns(DeprecationWarning):
qobj = assemble(circ)
circuits, run_config_out, header = disassemble(qobj)
run_config_out = RunConfig(**run_config_out)
self.assertEqual(run_config_out.n_qubits, 2)
self.assertEqual(run_config_out.memory_slots, 0)
self.assertEqual(len(circuits), 1)
# params array
assert_allclose(circuits[0]._data[0].operation.params[0], circ._data[0].operation.params[0])
# all other data
self.assertEqual(
circuits[0]._data[0].operation.params[1:], circ._data[0].operation.params[1:]
)
self.assertEqual(circuits[0]._data[0].qubits, circ._data[0].qubits)
self.assertEqual(circuits[0]._data[0].clbits, circ._data[0].clbits)
self.assertEqual(circuits[0]._data[1:], circ._data[1:])
self.assertEqual({}, header)
def test_opaque_instruction(self):
"""Test the disassembler handles opaque instructions correctly."""
opaque_inst = Instruction(name="my_inst", num_qubits=4, num_clbits=2, params=[0.5, 0.4])
q = QuantumRegister(6, name="q")
c = ClassicalRegister(4, name="c")
circ = QuantumCircuit(q, c, name="circ")
circ.append(opaque_inst, [q[0], q[2], q[5], q[3]], [c[3], c[0]])
with self.assertWarns(DeprecationWarning):
qobj = assemble(circ)
circuits, run_config_out, header = disassemble(qobj)
run_config_out = RunConfig(**run_config_out)
self.assertEqual(run_config_out.n_qubits, 6)
self.assertEqual(run_config_out.memory_slots, 4)
self.assertEqual(len(circuits), 1)
self.assertEqual(circuits[0], circ)
self.assertEqual({}, header)
def test_circuit_with_conditionals(self):
"""Verify disassemble sets conditionals correctly."""
qr = QuantumRegister(2)
cr1 = ClassicalRegister(1)
cr2 = ClassicalRegister(2)
qc = QuantumCircuit(qr, cr1, cr2)
qc.measure(qr[0], cr1) # Measure not required for a later conditional
qc.measure(qr[1], cr2[1]) # Measure required for a later conditional
qc.h(qr[1]).c_if(cr2, 3)
with self.assertWarns(DeprecationWarning):
qobj = assemble(qc)
circuits, run_config_out, header = disassemble(qobj)
run_config_out = RunConfig(**run_config_out)
self.assertEqual(run_config_out.n_qubits, 2)
self.assertEqual(run_config_out.memory_slots, 3)
self.assertEqual(len(circuits), 1)
self.assertEqual(circuits[0], qc)
self.assertEqual({}, header)
def test_circuit_with_simple_conditional(self):
"""Verify disassemble handles a simple conditional on the only bits."""
qr = QuantumRegister(1)
cr = ClassicalRegister(1)
qc = QuantumCircuit(qr, cr)
qc.h(qr[0]).c_if(cr, 1)
with self.assertWarns(DeprecationWarning):
qobj = assemble(qc)
circuits, run_config_out, header = disassemble(qobj)
run_config_out = RunConfig(**run_config_out)
self.assertEqual(run_config_out.n_qubits, 1)
self.assertEqual(run_config_out.memory_slots, 1)
self.assertEqual(len(circuits), 1)
self.assertEqual(circuits[0], qc)
self.assertEqual({}, header)
def test_circuit_with_single_bit_conditions(self):
"""Verify disassemble handles a simple conditional on a single bit of a register."""
# This circuit would fail to perfectly round-trip if 'cr' below had only one bit in it.
# This is because the format of QasmQobj is insufficient to disambiguate single-bit
# conditions from conditions on registers with only one bit. Since single-bit conditions are
# mostly a hack for the QasmQobj format at all, `disassemble` always prefers to return the
# register if it can. It would also fail if registers overlap.
qr = QuantumRegister(1)
cr = ClassicalRegister(2)
qc = QuantumCircuit(qr, cr)
qc.h(qr[0]).c_if(cr[0], 1)
with self.assertWarns(DeprecationWarning):
qobj = assemble(qc)
circuits, run_config_out, header = disassemble(qobj)
run_config_out = RunConfig(**run_config_out)
self.assertEqual(run_config_out.n_qubits, len(qr))
self.assertEqual(run_config_out.memory_slots, len(cr))
self.assertEqual(len(circuits), 1)
self.assertEqual(circuits[0], qc)
self.assertEqual({}, header)
def test_circuit_with_mcx(self):
"""Verify disassemble handles mcx gate - #6271."""
qr = QuantumRegister(5)
cr = ClassicalRegister(5)
qc = QuantumCircuit(qr, cr)
qc.mcx([0, 1, 2], 4)
with self.assertWarns(DeprecationWarning):
qobj = assemble(qc)
circuits, run_config_out, header = disassemble(qobj)
run_config_out = RunConfig(**run_config_out)
self.assertEqual(run_config_out.n_qubits, 5)
self.assertEqual(run_config_out.memory_slots, 5)
self.assertEqual(len(circuits), 1)
self.assertEqual(circuits[0], qc)
self.assertEqual({}, header)
def test_multiple_conditionals_multiple_registers(self):
"""Verify disassemble handles multiple conditionals and registers."""
qr = QuantumRegister(3)
cr1 = ClassicalRegister(3)
cr2 = ClassicalRegister(5)
cr3 = ClassicalRegister(6)
cr4 = ClassicalRegister(1)
qc = QuantumCircuit(qr, cr1, cr2, cr3, cr4)
qc.x(qr[1])
qc.h(qr)
qc.cx(qr[1], qr[0]).c_if(cr3, 14)
qc.ccx(qr[0], qr[2], qr[1]).c_if(cr4, 1)
qc.h(qr).c_if(cr1, 3)
with self.assertWarns(DeprecationWarning):
qobj = assemble(qc)
circuits, run_config_out, header = disassemble(qobj)
run_config_out = RunConfig(**run_config_out)
self.assertEqual(run_config_out.n_qubits, 3)
self.assertEqual(run_config_out.memory_slots, 15)
self.assertEqual(len(circuits), 1)
self.assertEqual(circuits[0], qc)
self.assertEqual({}, header)
def test_circuit_with_bit_conditional_1(self):
"""Verify disassemble handles conditional on a single bit."""
qr = QuantumRegister(2)
cr = ClassicalRegister(2)
qc = QuantumCircuit(qr, cr)
qc.h(qr[0]).c_if(cr[1], True)
with self.assertWarns(DeprecationWarning):
qobj = assemble(qc)
circuits, run_config_out, header = disassemble(qobj)
run_config_out = RunConfig(**run_config_out)
self.assertEqual(run_config_out.n_qubits, 2)
self.assertEqual(run_config_out.memory_slots, 2)
self.assertEqual(len(circuits), 1)
self.assertEqual(circuits[0], qc)
self.assertEqual({}, header)
def test_circuit_with_bit_conditional_2(self):
"""Verify disassemble handles multiple single bit conditionals."""
qr = QuantumRegister(2)
cr = ClassicalRegister(2)
cr1 = ClassicalRegister(2)
qc = QuantumCircuit(qr, cr, cr1)
qc.h(qr[0]).c_if(cr1[1], False)
qc.h(qr[1]).c_if(cr[0], True)
qc.cx(qr[0], qr[1]).c_if(cr1[0], False)
with self.assertWarns(DeprecationWarning):
qobj = assemble(qc)
circuits, run_config_out, header = disassemble(qobj)
run_config_out = RunConfig(**run_config_out)
self.assertEqual(run_config_out.n_qubits, 2)
self.assertEqual(run_config_out.memory_slots, 4)
self.assertEqual(len(circuits), 1)
self.assertEqual(circuits[0], qc)
self.assertEqual({}, header)
def assertCircuitCalibrationsEqual(self, in_circuits, out_circuits):
"""Verify circuit calibrations are equivalent pre-assembly and post-disassembly"""
self.assertEqual(len(in_circuits), len(out_circuits))
for in_qc, out_qc in zip(in_circuits, out_circuits):
in_cals = in_qc.calibrations
out_cals = out_qc.calibrations
self.assertEqual(in_cals.keys(), out_cals.keys())
for gate_name in in_cals:
self.assertEqual(in_cals[gate_name].keys(), out_cals[gate_name].keys())
for gate_params, in_sched in in_cals[gate_name].items():
out_sched = out_cals[gate_name][gate_params]
self.assertEqual(*map(_parametric_to_waveforms, (in_sched, out_sched)))
def test_single_circuit_calibrations(self):
"""Test that disassembler parses single circuit QOBJ calibrations (from QOBJ-level)."""
theta = Parameter("theta")
qc = QuantumCircuit(2)
qc.h(0)
qc.rx(np.pi, 0)
qc.rx(theta, 1)
qc = qc.assign_parameters({theta: np.pi})
with pulse.build() as h_sched:
pulse.play(pulse.library.Drag(1, 0.15, 4, 2), pulse.DriveChannel(0))
with pulse.build() as x180:
pulse.play(pulse.library.Gaussian(1, 0.2, 5), pulse.DriveChannel(0))
qc.add_calibration("h", [0], h_sched)
qc.add_calibration(RXGate(np.pi), [0], x180)
with self.assertWarns(DeprecationWarning):
qobj = assemble(qc, FakeOpenPulse2Q())
output_circuits, _, _ = disassemble(qobj)
self.assertCircuitCalibrationsEqual([qc], output_circuits)
def test_parametric_pulse_circuit_calibrations(self):
"""Test that disassembler parses parametric pulses back to pulse gates."""
with pulse.build() as h_sched:
pulse.play(pulse.library.Drag(50, 0.15, 4, 2), pulse.DriveChannel(0))
qc = QuantumCircuit(2)
qc.h(0)
qc.add_calibration("h", [0], h_sched)
with self.assertWarns(DeprecationWarning):
backend = FakeOpenPulse2Q()
backend.configuration().parametric_pulses = ["drag"]
qobj = assemble(qc, backend)
output_circuits, _, _ = disassemble(qobj)
out_qc = output_circuits[0]
self.assertCircuitCalibrationsEqual([qc], output_circuits)
self.assertTrue(
all(
qc_sched.instructions == out_qc_sched.instructions
for (_, qc_gate), (_, out_qc_gate) in zip(
qc.calibrations.items(), out_qc.calibrations.items()
)
for qc_sched, out_qc_sched in zip(qc_gate.values(), out_qc_gate.values())
),
)
def test_multi_circuit_uncommon_calibrations(self):
"""Test that disassembler parses uncommon calibrations (stored at QOBJ experiment-level)."""
with pulse.build() as sched:
pulse.play(pulse.library.Drag(50, 0.15, 4, 2), pulse.DriveChannel(0))
qc_0 = QuantumCircuit(2)
qc_0.h(0)
qc_0.append(RXGate(np.pi), [1])
qc_0.add_calibration("h", [0], sched)
qc_0.add_calibration(RXGate(np.pi), [1], sched)
qc_1 = QuantumCircuit(2)
qc_1.h(0)
circuits = [qc_0, qc_1]
with self.assertWarns(DeprecationWarning):
qobj = assemble(circuits, FakeOpenPulse2Q())
output_circuits, _, _ = disassemble(qobj)
self.assertCircuitCalibrationsEqual(circuits, output_circuits)
def test_multi_circuit_common_calibrations(self):
"""Test that disassembler parses common calibrations (stored at QOBJ-level)."""
with pulse.build() as sched:
pulse.play(pulse.library.Drag(1, 0.15, 4, 2), pulse.DriveChannel(0))
qc_0 = QuantumCircuit(2)
qc_0.h(0)
qc_0.append(RXGate(np.pi), [1])
qc_0.add_calibration("h", [0], sched)
qc_0.add_calibration(RXGate(np.pi), [1], sched)
qc_1 = QuantumCircuit(2)
qc_1.h(0)
qc_1.add_calibration(RXGate(np.pi), [1], sched)
circuits = [qc_0, qc_1]
with self.assertWarns(DeprecationWarning):
qobj = assemble(circuits, FakeOpenPulse2Q())
output_circuits, _, _ = disassemble(qobj)
self.assertCircuitCalibrationsEqual(circuits, output_circuits)
def test_single_circuit_delay_calibrations(self):
"""Test that disassembler parses delay instruction back to delay gate."""
qc = QuantumCircuit(2)
qc.append(Gate("test", 1, []), [0])
test_sched = pulse.Delay(64, pulse.DriveChannel(0)) + pulse.Delay(
160, pulse.DriveChannel(0)
)
qc.add_calibration("test", [0], test_sched)
with self.assertWarns(DeprecationWarning):
qobj = assemble(qc, FakeOpenPulse2Q())
output_circuits, _, _ = disassemble(qobj)
self.assertEqual(len(qc.calibrations), len(output_circuits[0].calibrations))
self.assertEqual(qc.calibrations.keys(), output_circuits[0].calibrations.keys())
self.assertTrue(
all(
qc_cal.keys() == out_qc_cal.keys()
for qc_cal, out_qc_cal in zip(
qc.calibrations.values(), output_circuits[0].calibrations.values()
)
)
)
self.assertEqual(
qc.calibrations["test"][((0,), ())], output_circuits[0].calibrations["test"][((0,), ())]
)
class TestPulseScheduleDisassembler(QiskitTestCase):
"""Tests for disassembling pulse schedules to qobj."""
def setUp(self):
super().setUp()
with self.assertWarns(DeprecationWarning):
self.backend = FakeOpenPulse2Q()
self.backend_config = self.backend.configuration()
self.backend_config.parametric_pulses = ["constant", "gaussian", "gaussian_square", "drag"]
def test_disassemble_single_schedule(self):
"""Test disassembling a single schedule."""
d0 = pulse.DriveChannel(0)
d1 = pulse.DriveChannel(1)
with pulse.build(self.backend) as sched:
with pulse.align_right():
pulse.play(pulse.library.Constant(10, 1.0), d0)
pulse.set_phase(1.0, d0)
pulse.shift_phase(3.11, d0)
pulse.set_frequency(1e9, d0)
pulse.shift_frequency(1e7, d0)
pulse.delay(20, d0)
pulse.delay(10, d1)
pulse.play(pulse.library.Constant(8, 0.1), d1)
pulse.measure_all()
with self.assertWarns(DeprecationWarning):
qobj = assemble(sched, backend=self.backend, shots=2000)
scheds, run_config_out, _ = disassemble(qobj)
run_config_out = RunConfig(**run_config_out)
self.assertEqual(run_config_out.memory_slots, 2)
self.assertEqual(run_config_out.shots, 2000)
self.assertEqual(run_config_out.memory, False)
self.assertEqual(run_config_out.meas_level, 2)
self.assertEqual(run_config_out.meas_lo_freq, self.backend.defaults().meas_freq_est)
self.assertEqual(run_config_out.qubit_lo_freq, self.backend.defaults().qubit_freq_est)
self.assertEqual(run_config_out.rep_time, 99)
self.assertEqual(len(scheds), 1)
self.assertEqual(scheds[0], target_qobj_transform(sched))
def test_disassemble_multiple_schedules(self):
"""Test disassembling multiple schedules, all should have the same config."""
d0 = pulse.DriveChannel(0)
d1 = pulse.DriveChannel(1)
with pulse.build(self.backend) as sched0:
with pulse.align_right():
pulse.play(pulse.library.Constant(10, 1.0), d0)
pulse.set_phase(1.0, d0)
pulse.shift_phase(3.11, d0)
pulse.set_frequency(1e9, d0)
pulse.shift_frequency(1e7, d0)
pulse.delay(20, d0)
pulse.delay(10, d1)
pulse.play(pulse.library.Constant(8, 0.1), d1)
pulse.measure_all()
with pulse.build(self.backend) as sched1:
with pulse.align_right():
pulse.play(pulse.library.Constant(8, 0.1), d0)
pulse.play(pulse.library.Waveform([0.0, 1.0]), d1)
pulse.set_phase(1.1, d0)
pulse.shift_phase(3.5, d0)
pulse.set_frequency(2e9, d0)
pulse.shift_frequency(3e7, d1)
pulse.delay(20, d1)
pulse.delay(10, d0)
pulse.play(pulse.library.Constant(8, 0.4), d1)
pulse.measure_all()
with self.assertWarns(DeprecationWarning):
qobj = assemble([sched0, sched1], backend=self.backend, shots=2000)
scheds, run_config_out, _ = disassemble(qobj)
run_config_out = RunConfig(**run_config_out)
self.assertEqual(run_config_out.memory_slots, 2)
self.assertEqual(run_config_out.shots, 2000)
self.assertEqual(run_config_out.memory, False)
self.assertEqual(len(scheds), 2)
self.assertEqual(scheds[0], target_qobj_transform(sched0))
self.assertEqual(scheds[1], target_qobj_transform(sched1))
def test_disassemble_parametric_pulses(self):
"""Test disassembling multiple schedules all should have the same config."""
d0 = pulse.DriveChannel(0)
with pulse.build(self.backend) as sched:
with pulse.align_right():
pulse.play(pulse.library.Constant(10, 1.0), d0)
pulse.play(pulse.library.Gaussian(10, 1.0, 2.0), d0)
pulse.play(pulse.library.GaussianSquare(10, 1.0, 2.0, 3), d0)
pulse.play(pulse.library.Drag(10, 1.0, 2.0, 0.1), d0)
with self.assertWarns(DeprecationWarning):
qobj = assemble(sched, backend=self.backend, shots=2000)
scheds, _, _ = disassemble(qobj)
self.assertEqual(scheds[0], target_qobj_transform(sched))
def test_disassemble_schedule_los(self):
"""Test disassembling schedule los."""
d0 = pulse.DriveChannel(0)
m0 = pulse.MeasureChannel(0)
d1 = pulse.DriveChannel(1)
m1 = pulse.MeasureChannel(1)
sched0 = pulse.Schedule()
sched1 = pulse.Schedule()
schedule_los = [
{d0: 4.5e9, d1: 5e9, m0: 6e9, m1: 7e9},
{d0: 5e9, d1: 4.5e9, m0: 7e9, m1: 6e9},
]
with self.assertWarns(DeprecationWarning):
qobj = assemble([sched0, sched1], backend=self.backend, schedule_los=schedule_los)
_, run_config_out, _ = disassemble(qobj)
run_config_out = RunConfig(**run_config_out)
self.assertEqual(run_config_out.schedule_los, schedule_los)
if __name__ == "__main__":
unittest.main(verbosity=2)
| qiskit/test/python/compiler/test_disassembler.py/0 | {
"file_path": "qiskit/test/python/compiler/test_disassembler.py",
"repo_id": "qiskit",
"token_count": 11723
} | 318 |
# This code is part of Qiskit.
#
# (C) Copyright IBM 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test for the DAGDependency object"""
import unittest
from qiskit.dagcircuit import DAGDependency
from qiskit.circuit import QuantumRegister, ClassicalRegister, QuantumCircuit, Qubit, Clbit
from qiskit.circuit import Measure
from qiskit.circuit import Instruction
from qiskit.circuit.library.standard_gates.h import HGate
from qiskit.dagcircuit.exceptions import DAGDependencyError
from qiskit.converters import circuit_to_dagdependency
from test import QiskitTestCase # pylint: disable=wrong-import-order
try:
import rustworkx as rx
except ImportError:
pass
def raise_if_dagdependency_invalid(dag):
"""Validates the internal consistency of a DAGDependency._multi_graph.
Intended for use in testing.
Raises:
DAGDependencyError: if DAGDependency._multi_graph is inconsistent.
"""
multi_graph = dag._multi_graph
if not rx.is_directed_acyclic_graph(multi_graph):
raise DAGDependencyError("multi_graph is not a DAG.")
# Every node should be of type op.
for node in dag.get_nodes():
if node.type != "op":
raise DAGDependencyError(f"Found node of unexpected type: {node.type}")
class TestDagRegisters(QiskitTestCase):
"""Test qreg and creg inside the dag"""
def test_add_qreg_creg(self):
"""add_qreg() and add_creg() methods"""
dag = DAGDependency()
dag.add_qreg(QuantumRegister(2, "qr"))
dag.add_creg(ClassicalRegister(1, "cr"))
self.assertDictEqual(dag.qregs, {"qr": QuantumRegister(2, "qr")})
self.assertDictEqual(dag.cregs, {"cr": ClassicalRegister(1, "cr")})
def test_dag_get_qubits(self):
"""get_qubits() method"""
dag = DAGDependency()
dag.add_qreg(QuantumRegister(1, "qr1"))
dag.add_qreg(QuantumRegister(1, "qr10"))
dag.add_qreg(QuantumRegister(1, "qr0"))
dag.add_qreg(QuantumRegister(1, "qr3"))
dag.add_qreg(QuantumRegister(1, "qr4"))
dag.add_qreg(QuantumRegister(1, "qr6"))
self.assertListEqual(
dag.qubits,
[
QuantumRegister(1, "qr1")[0],
QuantumRegister(1, "qr10")[0],
QuantumRegister(1, "qr0")[0],
QuantumRegister(1, "qr3")[0],
QuantumRegister(1, "qr4")[0],
QuantumRegister(1, "qr6")[0],
],
)
def test_add_reg_duplicate(self):
"""add_qreg with the same register twice is not allowed."""
dag = DAGDependency()
qr = QuantumRegister(2)
dag.add_qreg(qr)
self.assertRaises(DAGDependencyError, dag.add_qreg, qr)
def test_add_reg_duplicate_name(self):
"""Adding quantum registers with the same name is not allowed."""
dag = DAGDependency()
qr1 = QuantumRegister(3, "qr")
dag.add_qreg(qr1)
qr2 = QuantumRegister(2, "qr")
self.assertRaises(DAGDependencyError, dag.add_qreg, qr2)
def test_add_reg_bad_type(self):
"""add_qreg with a classical register is not allowed."""
dag = DAGDependency()
cr = ClassicalRegister(2)
self.assertRaises(DAGDependencyError, dag.add_qreg, cr)
def test_add_registerless_bits(self):
"""Verify we can add are retrieve bits without an associated register."""
qubits = [Qubit() for _ in range(5)]
clbits = [Clbit() for _ in range(3)]
dag = DAGDependency()
dag.add_qubits(qubits)
dag.add_clbits(clbits)
self.assertEqual(dag.qubits, qubits)
self.assertEqual(dag.clbits, clbits)
def test_add_duplicate_registerless_bits(self):
"""Verify we raise when adding a bit already present in the circuit."""
qubits = [Qubit() for _ in range(5)]
clbits = [Clbit() for _ in range(3)]
dag = DAGDependency()
dag.add_qubits(qubits)
dag.add_clbits(clbits)
with self.assertRaisesRegex(DAGDependencyError, r"duplicate qubits"):
dag.add_qubits(qubits[:1])
with self.assertRaisesRegex(DAGDependencyError, r"duplicate clbits"):
dag.add_clbits(clbits[:1])
class TestDagNodeEdge(QiskitTestCase):
"""Test adding nodes and edges to a dag and related functions."""
def setUp(self):
super().setUp()
self.dag = DAGDependency()
self.qreg = QuantumRegister(2, "qr")
self.creg = ClassicalRegister(2, "cr")
self.dag.add_qreg(self.qreg)
self.dag.add_creg(self.creg)
def test_node(self):
"""Test the methods add_op_node(), get_node() and get_nodes()"""
circuit = QuantumCircuit(self.qreg, self.creg)
circuit.h(self.qreg[0])
self.dag.add_op_node(
circuit.data[0].operation, circuit.data[0].qubits, circuit.data[0].clbits
)
self.assertIsInstance(self.dag.get_node(0).op, HGate)
circuit.measure(self.qreg[0], self.creg[0])
self.dag.add_op_node(
circuit.data[1].operation, circuit.data[1].qubits, circuit.data[1].clbits
)
self.assertIsInstance(self.dag.get_node(1).op, Measure)
nodes = list(self.dag.get_nodes())
self.assertEqual(len(list(nodes)), 2)
for node in nodes:
self.assertIsInstance(node.op, Instruction)
node_1 = nodes.pop()
node_2 = nodes.pop()
self.assertIsInstance(node_1.op, Measure)
self.assertIsInstance(node_2.op, HGate)
def test_add_edge(self):
"""Test that add_edge(), get_edges(), get_all_edges(),
get_in_edges() and get_out_edges()."""
circuit = QuantumCircuit(self.qreg, self.creg)
circuit.h(self.qreg[0])
circuit.x(self.qreg[1])
circuit.cx(self.qreg[1], self.qreg[0])
circuit.measure(self.qreg[0], self.creg[0])
self.dag = circuit_to_dagdependency(circuit)
second_edge = self.dag.get_edges(1, 2)
self.assertEqual(second_edge[0]["commute"], False)
all_edges = self.dag.get_all_edges()
self.assertEqual(len(all_edges), 3)
for edges in all_edges:
self.assertEqual(edges[2]["commute"], False)
in_edges = self.dag.get_in_edges(2)
self.assertEqual(len(list(in_edges)), 2)
out_edges = self.dag.get_out_edges(2)
self.assertEqual(len(list(out_edges)), 1)
class TestDagNodeSelection(QiskitTestCase):
"""Test methods that select successors and predecessors"""
def setUp(self):
super().setUp()
self.dag = DAGDependency()
self.qreg = QuantumRegister(2, "qr")
self.creg = ClassicalRegister(2, "cr")
self.dag.add_qreg(self.qreg)
self.dag.add_creg(self.creg)
def test_successors_predecessors(self):
"""Test the method direct_successors."""
circuit = QuantumCircuit(self.qreg, self.creg)
circuit.h(self.qreg[0])
circuit.x(self.qreg[0])
circuit.h(self.qreg[0])
circuit.x(self.qreg[1])
circuit.h(self.qreg[0])
circuit.measure(self.qreg[0], self.creg[0])
self.dag = circuit_to_dagdependency(circuit)
dir_successors_second = self.dag.direct_successors(1)
self.assertEqual(dir_successors_second, [2, 4])
dir_successors_fourth = self.dag.direct_successors(3)
self.assertEqual(dir_successors_fourth, [])
successors_second = self.dag.successors(1)
self.assertEqual(successors_second, [2, 4, 5])
successors_fourth = self.dag.successors(3)
self.assertEqual(successors_fourth, [])
dir_predecessors_sixth = self.dag.direct_predecessors(5)
self.assertEqual(dir_predecessors_sixth, [2, 4])
dir_predecessors_fourth = self.dag.direct_predecessors(3)
self.assertEqual(dir_predecessors_fourth, [])
predecessors_sixth = self.dag.predecessors(5)
self.assertEqual(predecessors_sixth, [0, 1, 2, 4])
predecessors_fourth = self.dag.predecessors(3)
self.assertEqual(predecessors_fourth, [])
def test_option_create_preds_and_succs_is_false(self):
"""Test that when the option ``create_preds_and_succs`` is False,
direct successors and predecessors still get constructed, but
transitive successors and predecessors do not."""
circuit = QuantumCircuit(self.qreg, self.creg)
circuit.h(self.qreg[0])
circuit.x(self.qreg[0])
circuit.h(self.qreg[0])
circuit.x(self.qreg[1])
circuit.h(self.qreg[0])
circuit.measure(self.qreg[0], self.creg[0])
self.dag = circuit_to_dagdependency(circuit, create_preds_and_succs=False)
self.assertEqual(self.dag.direct_predecessors(1), [0])
self.assertEqual(self.dag.direct_successors(1), [2, 4])
self.assertEqual(self.dag.predecessors(1), [])
self.assertEqual(self.dag.successors(1), [])
self.assertEqual(self.dag.direct_predecessors(3), [])
self.assertEqual(self.dag.direct_successors(3), [])
self.assertEqual(self.dag.predecessors(3), [])
self.assertEqual(self.dag.successors(3), [])
self.assertEqual(self.dag.direct_predecessors(5), [2, 4])
self.assertEqual(self.dag.direct_successors(5), [])
self.assertEqual(self.dag.predecessors(5), [])
self.assertEqual(self.dag.successors(5), [])
class TestDagProperties(QiskitTestCase):
"""Test the DAG properties."""
def setUp(self):
# ┌───┐ ┌───┐
# q0_0: ┤ H ├────────────────┤ X ├──────────
# └───┘ └─┬─┘ ┌───┐
# q0_1: ───────────────────────┼───────┤ H ├
# ┌───┐ │ ┌───┐└─┬─┘
# q0_2: ──■───────┤ H ├────────┼──┤ T ├──■──
# ┌─┴─┐┌────┴───┴─────┐ │ └───┘
# q0_3: ┤ X ├┤ U(0,0.1,0.2) ├──┼────────────
# └───┘└──────────────┘ │
# q1_0: ───────────────────────■────────────
# │
# q1_1: ───────────────────────■────────────
super().setUp()
qr1 = QuantumRegister(4)
qr2 = QuantumRegister(2)
circ = QuantumCircuit(qr1, qr2)
circ.h(qr1[0])
circ.cx(qr1[2], qr1[3])
circ.h(qr1[2])
circ.t(qr1[2])
circ.ch(qr1[2], qr1[1])
circ.u(0.0, 0.1, 0.2, qr1[3])
circ.ccx(qr2[0], qr2[1], qr1[0])
self.dag = circuit_to_dagdependency(circ)
def test_size(self):
"""Test total number of operations in dag."""
self.assertEqual(self.dag.size(), 7)
def test_dag_depth(self):
"""Test dag depth."""
self.assertEqual(self.dag.depth(), 2)
def test_dag_depth_empty(self):
"""Empty circuit DAG is zero depth"""
q = QuantumRegister(5, "q")
qc = QuantumCircuit(q)
dag = circuit_to_dagdependency(qc)
self.assertEqual(dag.depth(), 0)
def test_default_metadata_value(self):
"""Test that the default DAGDependency metadata is valid QuantumCircuit metadata."""
qc = QuantumCircuit(1)
qc.metadata = self.dag.metadata
self.assertEqual(qc.metadata, {})
if __name__ == "__main__":
unittest.main()
| qiskit/test/python/dagcircuit/test_dagdependency.py/0 | {
"file_path": "qiskit/test/python/dagcircuit/test_dagdependency.py",
"repo_id": "qiskit",
"token_count": 5526
} | 319 |
# This code is part of Qiskit.
#
# (C) Copyright IBM 2024.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test SamplerPub class"""
import ddt
import numpy as np
from qiskit.circuit import QuantumCircuit, Parameter
from qiskit.primitives.containers.sampler_pub import SamplerPub
from qiskit.primitives.containers.bindings_array import BindingsArray
from test import QiskitTestCase # pylint: disable=wrong-import-order
@ddt.ddt
class SamplerPubTestCase(QiskitTestCase):
"""Test the SamplerPub class."""
def test_properties(self):
"""Test SamplerPub properties."""
params = (Parameter("a"), Parameter("b"))
circuit = QuantumCircuit(2)
circuit.rx(params[0], 0)
circuit.ry(params[1], 1)
circuit.measure_all()
parameter_values = BindingsArray(data={params: np.ones((10, 2))})
shots = 1000
pub = SamplerPub(
circuit=circuit,
parameter_values=parameter_values,
shots=shots,
)
self.assertEqual(pub.circuit, circuit, msg="incorrect value for `circuit` property")
self.assertEqual(
pub.parameter_values,
parameter_values,
msg="incorrect value for `parameter_values` property",
)
self.assertEqual(pub.shots, shots, msg="incorrect value for `shots` property")
def test_invalidate_circuit(self):
"""Test validation of circuit argument"""
# Invalid circuit, it is an instruction
circuit = QuantumCircuit(3).to_instruction()
with self.assertRaises(TypeError):
SamplerPub(circuit)
@ddt.data(100.0, True, False, 100j, 1e5)
def test_invalidate_shots_type(self, shots):
"""Test validation of shots argument type"""
with self.assertRaises(TypeError, msg=f"shots type {type(shots)} should raise TypeError"):
SamplerPub(QuantumCircuit(), shots=shots)
@ddt.data(-1, 0)
def test_invalidate_shots_value(self, shots):
"""Test invalid shots argument value"""
with self.assertRaises(ValueError, msg="non-positive shots should raise ValueError"):
SamplerPub(QuantumCircuit(), shots=shots)
@ddt.idata(range(5))
def test_validate_no_parameters(self, num_params):
"""Test unparameterized circuit raises for parameter values"""
circuit = QuantumCircuit(2)
parameter_values = BindingsArray(
{(f"a{idx}" for idx in range(num_params)): np.zeros((2, num_params))}, shape=2
)
if num_params == 0:
SamplerPub(circuit, parameter_values=parameter_values)
return
with self.assertRaises(ValueError):
SamplerPub(circuit, parameter_values=parameter_values)
@ddt.idata(range(5))
def test_validate_num_parameters(self, num_params):
"""Test unparameterized circuit raises for parameter values"""
params = (Parameter("a"), Parameter("b"))
circuit = QuantumCircuit(2)
circuit.rx(params[0], 0)
circuit.ry(params[1], 1)
circuit.measure_all()
parameter_values = BindingsArray(
{(f"a{idx}" for idx in range(num_params)): np.zeros((2, num_params))}, shape=2
)
if num_params == len(params):
SamplerPub(circuit, parameter_values=parameter_values)
return
with self.assertRaises(ValueError):
SamplerPub(circuit, parameter_values=parameter_values)
@ddt.data((), (3,), (2, 3))
def test_shaped_zero_parameter_values(self, shape):
"""Test Passing in a shaped array with no parameters works"""
circuit = QuantumCircuit(2)
parameter_values = BindingsArray({(): np.zeros((*shape, 0))}, shape=shape)
pub = SamplerPub(circuit, parameter_values=parameter_values)
self.assertEqual(pub.shape, shape)
def test_coerce_circuit(self):
"""Test coercing an unparameterized circuit"""
circuit = QuantumCircuit(10)
circuit.measure_all()
pub = SamplerPub.coerce(circuit)
self.assertEqual(pub.circuit, circuit, msg="incorrect value for `circuit` property")
self.assertEqual(pub.shots, None, msg="incorrect value for `shots` property")
# Check bindings array, this is more cumbersome since the class doesn't have an eq method
self.assertIsInstance(
pub.parameter_values,
BindingsArray,
msg="incorrect type for `parameter_values` property",
)
self.assertEqual(
pub.parameter_values.shape, (), msg="incorrect shape for `parameter_values` property"
)
self.assertEqual(
pub.parameter_values.num_parameters,
0,
msg="incorrect num parameters for `parameter_values` property",
)
def test_invalid_coerce_circuit(self):
"""Test coercing parameterized circuit raises"""
params = (Parameter("a"), Parameter("b"))
circuit = QuantumCircuit(10)
circuit.rx(params[0], 0)
circuit.ry(params[1], 1)
circuit.measure_all()
with self.assertRaises(ValueError):
SamplerPub.coerce(circuit)
@ddt.data(1, 10, 100, 1000)
def test_coerce_pub_with_shots(self, shots):
"""Test coercing a SamplerPub"""
params = (Parameter("a"), Parameter("b"))
circuit = QuantumCircuit(2)
circuit.rx(params[0], 0)
circuit.ry(params[1], 1)
circuit.measure_all()
pub1 = SamplerPub(
circuit=circuit,
parameter_values=BindingsArray(data={params: np.ones((10, 2))}),
shots=1000,
)
pub2 = SamplerPub.coerce(pub1, shots=shots)
self.assertEqual(pub1, pub2)
@ddt.data(1, 10, 100, 1000)
def test_coerce_pub_without_shots(self, shots):
"""Test coercing a SamplerPub"""
params = (Parameter("a"), Parameter("b"))
circuit = QuantumCircuit(2)
circuit.rx(params[0], 0)
circuit.ry(params[1], 1)
circuit.measure_all()
pub1 = SamplerPub(
circuit=circuit,
parameter_values=BindingsArray(data={params: np.ones((10, 2))}),
shots=None,
)
pub2 = SamplerPub.coerce(pub1, shots=shots)
self.assertEqual(pub1.circuit, pub2.circuit, msg="incorrect value for `circuit` property")
self.assertEqual(
pub1.parameter_values,
pub2.parameter_values,
msg="incorrect value for `parameter_values` property",
)
self.assertEqual(pub2.shots, shots, msg="incorrect value for `shots` property")
@ddt.data(None, 1, 100)
def test_coerce_tuple_1(self, shots):
"""Test coercing circuit and parameter values"""
circuit = QuantumCircuit(2)
circuit.measure_all()
pub = SamplerPub.coerce((circuit,), shots=shots)
self.assertEqual(pub.circuit, circuit, msg="incorrect value for `circuit` property")
self.assertEqual(pub.shots, shots, msg="incorrect value for `shots` property")
# Check bindings array, this is more cumbersome since the class doesn't have an eq method
self.assertIsInstance(
pub.parameter_values,
BindingsArray,
msg="incorrect type for `parameter_values` property",
)
self.assertEqual(
pub.parameter_values.shape, (), msg="incorrect shape for `parameter_values` property"
)
self.assertEqual(
pub.parameter_values.num_parameters,
0,
msg="incorrect num parameters for `parameter_values` property",
)
@ddt.data(None, 1, 100)
def test_coerce_tuple_2(self, shots):
"""Test coercing circuit and parameter values"""
params = (Parameter("a"), Parameter("b"))
circuit = QuantumCircuit(2)
circuit.rx(params[0], 0)
circuit.ry(params[1], 1)
circuit.measure_all()
parameter_values = np.zeros((4, 3, 2))
pub = SamplerPub.coerce((circuit, parameter_values), shots=shots)
self.assertEqual(pub.circuit, circuit, msg="incorrect value for `circuit` property")
self.assertEqual(pub.shots, shots, msg="incorrect value for `shots` property")
# Check bindings array, this is more cumbersome since the class doesn't have an eq method
self.assertIsInstance(
pub.parameter_values,
BindingsArray,
msg="incorrect type for `parameter_values` property",
)
self.assertEqual(
pub.parameter_values.shape,
(4, 3),
msg="incorrect shape for `parameter_values` property",
)
self.assertEqual(
pub.parameter_values.num_parameters,
2,
msg="incorrect num parameters for `parameter_values` property",
)
@ddt.data(None, 1, 100)
def test_coerce_tuple_2_trivial_params(self, shots):
"""Test coercing circuit and parameter values"""
circuit = QuantumCircuit(2)
circuit.measure_all()
pub = SamplerPub.coerce((circuit, None), shots=shots)
self.assertEqual(pub.circuit, circuit, msg="incorrect value for `circuit` property")
self.assertEqual(pub.shots, shots, msg="incorrect value for `shots` property")
# Check bindings array, this is more cumbersome since the class doesn't have an eq method
self.assertIsInstance(
pub.parameter_values,
BindingsArray,
msg="incorrect type for `parameter_values` property",
)
self.assertEqual(
pub.parameter_values.shape, (), msg="incorrect shape for `parameter_values` property"
)
self.assertEqual(
pub.parameter_values.num_parameters,
0,
msg="incorrect num parameters for `parameter_values` property",
)
@ddt.data(None, 1, 100)
def test_coerce_tuple_3(self, shots):
"""Test coercing circuit and parameter values"""
params = (Parameter("a"), Parameter("b"))
circuit = QuantumCircuit(2)
circuit.rx(params[0], 0)
circuit.ry(params[1], 1)
circuit.measure_all()
parameter_values = np.zeros((4, 3, 2))
pub = SamplerPub.coerce((circuit, parameter_values, 1000), shots=shots)
self.assertEqual(pub.circuit, circuit, msg="incorrect value for `circuit` property")
self.assertEqual(pub.shots, 1000, msg="incorrect value for `shots` property")
# Check bindings array, this is more cumbersome since the class doesn't have an eq method
self.assertIsInstance(
pub.parameter_values,
BindingsArray,
msg="incorrect type for `parameter_values` property",
)
self.assertEqual(
pub.parameter_values.shape,
(4, 3),
msg="incorrect shape for `parameter_values` property",
)
self.assertEqual(
pub.parameter_values.num_parameters,
2,
msg="incorrect num parameters for `parameter_values` property",
)
@ddt.data(None, 1, 100)
def test_coerce_tuple_3_trivial_shots(self, shots):
"""Test coercing circuit and parameter values"""
params = (Parameter("a"), Parameter("b"))
circuit = QuantumCircuit(2)
circuit.rx(params[0], 0)
circuit.ry(params[1], 1)
circuit.measure_all()
parameter_values = np.zeros((4, 3, 2))
pub = SamplerPub.coerce((circuit, parameter_values, None), shots=shots)
self.assertEqual(pub.circuit, circuit, msg="incorrect value for `circuit` property")
self.assertEqual(pub.shots, shots, msg="incorrect value for `shots` property")
# Check bindings array, this is more cumbersome since the class doesn't have an eq method
self.assertIsInstance(
pub.parameter_values,
BindingsArray,
msg="incorrect type for `parameter_values` property",
)
self.assertEqual(
pub.parameter_values.shape,
(4, 3),
msg="incorrect shape for `parameter_values` property",
)
self.assertEqual(
pub.parameter_values.num_parameters,
2,
msg="incorrect num parameters for `parameter_values` property",
)
@ddt.data(None, 1, 100)
def test_coerce_tuple_3_trivial_params_shots(self, shots):
"""Test coercing circuit and parameter values"""
circuit = QuantumCircuit(2)
circuit.measure_all()
pub = SamplerPub.coerce((circuit, None, None), shots=shots)
self.assertEqual(pub.circuit, circuit, msg="incorrect value for `circuit` property")
self.assertEqual(pub.shots, shots, msg="incorrect value for `shots` property")
# Check bindings array, this is more cumbersome since the class doesn't have an eq method
self.assertIsInstance(
pub.parameter_values,
BindingsArray,
msg="incorrect type for `parameter_values` property",
)
self.assertEqual(
pub.parameter_values.shape, (), msg="incorrect shape for `parameter_values` property"
)
self.assertEqual(
pub.parameter_values.num_parameters,
0,
msg="incorrect num parameters for `parameter_values` property",
)
def test_coerce_pub_with_exact_types(self):
"""Test coercing a SamplerPub with exact types."""
params = (Parameter("a"), Parameter("b"))
circuit = QuantumCircuit(2)
circuit.rx(params[0], 0)
circuit.ry(params[1], 1)
params = BindingsArray(data={params: np.ones((10, 2))})
pub = SamplerPub.coerce((circuit, params))
self.assertIs(pub.circuit, circuit)
self.assertIs(pub.parameter_values, params)
| qiskit/test/python/primitives/containers/test_sampler_pub.py/0 | {
"file_path": "qiskit/test/python/primitives/containers/test_sampler_pub.py",
"repo_id": "qiskit",
"token_count": 6109
} | 320 |
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 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.
"""BasicProvider Backends Test."""
from qiskit.providers.basic_provider.basic_provider import BasicProvider
from qiskit.providers.exceptions import QiskitBackendNotFoundError
from test import QiskitTestCase # pylint: disable=wrong-import-order
class TestBasicProviderBackends(QiskitTestCase):
"""Qiskit BasicProvider Backends (Object) Tests."""
def setUp(self):
super().setUp()
with self.assertWarns(DeprecationWarning):
self.provider = BasicProvider()
self.backend_name = "basic_simulator"
def test_backends(self):
"""Test the provider has backends."""
backends = self.provider.backends()
self.assertTrue(len(backends) > 0)
def test_get_backend(self):
"""Test getting a backend from the provider."""
with self.assertWarns(DeprecationWarning):
backend = self.provider.get_backend(name=self.backend_name)
self.assertEqual(backend.name, self.backend_name)
def test_aliases_fail(self):
"""Test a failing backend lookup."""
with self.assertWarns(DeprecationWarning):
self.assertRaises(QiskitBackendNotFoundError, BasicProvider().get_backend, "bad_name")
| qiskit/test/python/providers/basic_provider/test_basic_provider_backends.py/0 | {
"file_path": "qiskit/test/python/providers/basic_provider/test_basic_provider_backends.py",
"repo_id": "qiskit",
"token_count": 595
} | 321 |
# This code is part of Qiskit.
#
# (C) Copyright IBM 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
# pylint: disable=missing-class-docstring,missing-function-docstring
# pylint: disable=missing-module-docstring
import copy
import pickle
from qiskit.providers import Options
from qiskit.qobj.utils import MeasLevel
from test import QiskitTestCase # pylint: disable=wrong-import-order
class TestOptions(QiskitTestCase):
def test_no_validators(self):
options = Options(shots=1024, method="auto", meas_level=MeasLevel.KERNELED)
self.assertEqual(options.shots, 1024)
options.update_options(method="statevector")
self.assertEqual(options.method, "statevector")
def test_no_validators_str(self):
options = Options(shots=1024, method="auto", meas_level=MeasLevel.KERNELED)
self.assertEqual(
str(options), "Options(shots=1024, method='auto', meas_level=<MeasLevel.KERNELED: 1>)"
)
def test_range_bound_validator(self):
options = Options(shots=1024)
options.set_validator("shots", (1, 4096))
with self.assertRaises(ValueError):
options.update_options(shots=8192)
def test_range_bound_string(self):
options = Options(shots=1024)
options.set_validator("shots", (1, 1024))
expected = """Options(shots=1024)
Where:
\tshots is >= 1 and <= 1024\n"""
self.assertEqual(str(options), expected)
def test_list_choice(self):
options = Options(method="auto")
options.set_validator("method", ["auto", "statevector", "mps"])
with self.assertRaises(ValueError):
options.update_options(method="stabilizer")
options.update_options(method="mps")
self.assertEqual(options.method, "mps")
def test_list_choice_string(self):
options = Options(method="auto")
options.set_validator("method", ["auto", "statevector", "mps"])
expected = """Options(method='auto')
Where:
\tmethod is one of ['auto', 'statevector', 'mps']\n"""
self.assertEqual(str(options), expected)
def test_type_validator(self):
options = Options(meas_level=MeasLevel.KERNELED)
options.set_validator("meas_level", MeasLevel)
with self.assertRaises(TypeError):
options.update_options(meas_level=2)
options.update_options(meas_level=MeasLevel.CLASSIFIED)
self.assertEqual(2, options.meas_level.value)
def test_type_validator_str(self):
options = Options(meas_level=MeasLevel.KERNELED)
options.set_validator("meas_level", MeasLevel)
expected = """Options(meas_level=<MeasLevel.KERNELED: 1>)
Where:
\tmeas_level is of type <enum 'MeasLevel'>\n"""
self.assertEqual(str(options), expected)
def test_range_bound_validator_multiple_fields(self):
options = Options(shots=1024, method="auto", meas_level=MeasLevel.KERNELED)
options.set_validator("shots", (1, 1024))
options.set_validator("method", ["auto", "statevector", "mps"])
options.set_validator("meas_level", MeasLevel)
with self.assertRaises(ValueError):
options.update_options(shots=2048, method="statevector")
options.update_options(shots=512, method="statevector")
self.assertEqual(options.shots, 512)
self.assertEqual(options.method, "statevector")
def test_range_bound_validator_multiple_fields_string(self):
options = Options(shots=1024, method="auto", meas_level=MeasLevel.KERNELED)
options.set_validator("shots", (1, 1024))
options.set_validator("method", ["auto", "statevector", "mps"])
options.set_validator("meas_level", MeasLevel)
expected = """Options(shots=1024, method='auto', meas_level=<MeasLevel.KERNELED: 1>)
Where:
\tshots is >= 1 and <= 1024
\tmethod is one of ['auto', 'statevector', 'mps']
\tmeas_level is of type <enum 'MeasLevel'>\n"""
self.assertEqual(str(options), expected)
def test_hasattr(self):
options = Options(shots=1024)
self.assertTrue(hasattr(options, "shots"))
self.assertFalse(hasattr(options, "method"))
def test_copy(self):
options = Options(opt1=1, opt2=2)
cpy = copy.copy(options)
cpy.update_options(opt1=10, opt3=20)
self.assertEqual(options.opt1, 1)
self.assertEqual(options.opt2, 2)
self.assertNotIn("opt3", options)
self.assertEqual(cpy.opt1, 10)
self.assertEqual(cpy.opt2, 2)
self.assertEqual(cpy.opt3, 20)
def test_iterate(self):
options = Options(opt1=1, opt2=2, opt3="abc")
options_dict = dict(options)
self.assertEqual(options_dict, {"opt1": 1, "opt2": 2, "opt3": "abc"})
def test_iterate_items(self):
options = Options(opt1=1, opt2=2, opt3="abc")
items = list(options.items())
self.assertEqual(items, [("opt1", 1), ("opt2", 2), ("opt3", "abc")])
def test_mutate_mapping(self):
options = Options(opt1=1, opt2=2, opt3="abc")
options["opt4"] = "def"
self.assertEqual(options.opt4, "def")
options_dict = dict(options)
self.assertEqual(options_dict, {"opt1": 1, "opt2": 2, "opt3": "abc", "opt4": "def"})
def test_mutate_mapping_validator(self):
options = Options(shots=1024)
options.set_validator("shots", (1, 2048))
options["shots"] = 512
self.assertEqual(options.shots, 512)
with self.assertRaises(ValueError):
options["shots"] = 3096
self.assertEqual(options.shots, 512)
class TestOptionsSimpleNamespaceBackwardCompatibility(QiskitTestCase):
"""Tests that SimpleNamespace-like functionality that qiskit-experiments relies on for Options
still works."""
def test_unpacking_dict(self):
kwargs = {"hello": "world", "a": "b"}
options = Options(**kwargs)
self.assertEqual(options.__dict__, kwargs)
self.assertEqual({**options.__dict__}, kwargs)
def test_setting_attributes(self):
options = Options()
options.hello = "world"
options.a = "b"
self.assertEqual(options.get("hello"), "world")
self.assertEqual(options.get("a"), "b")
self.assertEqual(options.__dict__, {"hello": "world", "a": "b"})
def test_overriding_instance_attributes(self):
"""Test that setting instance attributes and methods does not interfere with previously
defined attributes and methods. This produces an inconsistency where
>>> options = Options()
>>> options.validators = "hello"
>>> options.validators
{}
>>> options.get("validators")
"hello"
"""
options = Options(get="a string")
options.validator = "another string"
setattr(options, "update_options", "not a method")
options.update_options(_fields="not a dict")
options.__dict__ = "also not a dict"
self.assertEqual(
options.__dict__,
{
"get": "a string",
"validator": "another string",
"update_options": "not a method",
"_fields": "not a dict",
"__dict__": "also not a dict",
},
)
self.assertEqual(
options._fields,
{
"get": "a string",
"validator": "another string",
"update_options": "not a method",
"_fields": "not a dict",
"__dict__": "also not a dict",
},
)
self.assertEqual(options.validator, {})
self.assertEqual(options.get("_fields"), "not a dict")
def test_copy(self):
options = Options(shots=1024, method="auto", meas_level=MeasLevel.KERNELED)
options.set_validator("shots", (1, 1024))
options.set_validator("method", ["auto", "statevector", "mps"])
options.set_validator("meas_level", MeasLevel)
expected = """Options(shots=1024, method='auto', meas_level=<MeasLevel.KERNELED: 1>)
Where:
\tshots is >= 1 and <= 1024
\tmethod is one of ['auto', 'statevector', 'mps']
\tmeas_level is of type <enum 'MeasLevel'>\n"""
self.assertEqual(str(options), expected)
self.assertEqual(str(copy.copy(options)), expected)
def test_pickle(self):
options = Options(shots=1024, method="auto", meas_level=MeasLevel.KERNELED)
options.set_validator("shots", (1, 1024))
options.set_validator("method", ["auto", "statevector", "mps"])
options.set_validator("meas_level", MeasLevel)
expected = """Options(shots=1024, method='auto', meas_level=<MeasLevel.KERNELED: 1>)
Where:
\tshots is >= 1 and <= 1024
\tmethod is one of ['auto', 'statevector', 'mps']
\tmeas_level is of type <enum 'MeasLevel'>\n"""
self.assertEqual(str(options), expected)
self.assertEqual(str(pickle.loads(pickle.dumps(options))), expected)
| qiskit/test/python/providers/test_options.py/0 | {
"file_path": "qiskit/test/python/providers/test_options.py",
"repo_id": "qiskit",
"token_count": 3934
} | 322 |
# This code is part of Qiskit.
#
# (C) Copyright IBM 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test schedule block subroutine reference mechanism."""
import numpy as np
from qiskit import circuit, pulse
from qiskit.pulse import ScheduleBlock, builder
from qiskit.pulse.transforms import inline_subroutines
from test import QiskitTestCase # pylint: disable=wrong-import-order
class TestReference(QiskitTestCase):
"""Test for basic behavior of reference mechanism."""
def test_append_schedule(self):
"""Test appending schedule without calling.
Appended schedules are not subroutines.
These are directly exposed to the outer block.
"""
with pulse.build() as sched_x1:
pulse.play(pulse.Constant(100, 0.1, name="x1"), pulse.DriveChannel(0))
with pulse.build() as sched_y1:
builder.append_schedule(sched_x1)
with pulse.build() as sched_z1:
builder.append_schedule(sched_y1)
self.assertEqual(len(sched_z1.references), 0)
def test_refer_schedule(self):
"""Test refer to schedule by name.
Outer block is only aware of its inner reference.
Nested reference is not directly exposed to the most outer block.
"""
with pulse.build() as sched_x1:
pulse.play(pulse.Constant(100, 0.1, name="x1"), pulse.DriveChannel(0))
with pulse.build() as sched_y1:
builder.reference("x1", "d0")
with pulse.build() as sched_z1:
builder.reference("y1", "d0")
sched_y1.assign_references({("x1", "d0"): sched_x1})
sched_z1.assign_references({("y1", "d0"): sched_y1})
self.assertEqual(len(sched_z1.references), 1)
self.assertEqual(sched_z1.references[("y1", "d0")], sched_y1)
self.assertEqual(len(sched_y1.references), 1)
self.assertEqual(sched_y1.references[("x1", "d0")], sched_x1)
def test_refer_schedule_parameter_scope(self):
"""Test refer to schedule by name.
Parameter in the called schedule has the scope of called schedule.
"""
param = circuit.Parameter("name")
with pulse.build() as sched_x1:
pulse.play(pulse.Constant(100, param, name="x1"), pulse.DriveChannel(0))
with pulse.build() as sched_y1:
builder.reference("x1", "d0")
with pulse.build() as sched_z1:
builder.reference("y1", "d0")
sched_y1.assign_references({("x1", "d0"): sched_x1})
sched_z1.assign_references({("y1", "d0"): sched_y1})
self.assertEqual(sched_z1.parameters, sched_x1.parameters)
self.assertEqual(sched_z1.parameters, sched_y1.parameters)
def test_refer_schedule_parameter_assignment(self):
"""Test assigning to parameter in referenced schedule"""
param = circuit.Parameter("name")
with pulse.build() as sched_x1:
pulse.play(pulse.Constant(100, param, name="x1"), pulse.DriveChannel(0))
with pulse.build() as sched_y1:
builder.reference("x1", "d0")
with pulse.build() as sched_z1:
builder.reference("y1", "d0")
sched_y1.assign_references({("x1", "d0"): sched_x1})
sched_z1.assign_references({("y1", "d0"): sched_y1})
assigned_z1 = sched_z1.assign_parameters({param: 0.5}, inplace=False)
assigned_x1 = sched_x1.assign_parameters({param: 0.5}, inplace=False)
ref_assigned_y1 = ScheduleBlock()
ref_assigned_y1.append(assigned_x1)
ref_assigned_z1 = ScheduleBlock()
ref_assigned_z1.append(ref_assigned_y1)
# Test that assignment was successful and resolved references
self.assertEqual(assigned_z1, ref_assigned_z1)
# Test that inplace=False for sched_z1 also did not modify sched_z1 or subroutine sched_x1
self.assertEqual(sched_z1.parameters, {param})
self.assertEqual(sched_x1.parameters, {param})
self.assertEqual(assigned_z1.parameters, set())
# Now test inplace=True
sched_z1.assign_parameters({param: 0.5}, inplace=True)
self.assertEqual(sched_z1, assigned_z1)
# assign_references copies the subroutine, so the original subschedule
# is still not modified here:
self.assertNotEqual(sched_x1, assigned_x1)
def test_call_schedule(self):
"""Test call schedule.
Outer block is only aware of its inner reference.
Nested reference is not directly exposed to the most outer block.
"""
with pulse.build() as sched_x1:
pulse.play(pulse.Constant(100, 0.1, name="x1"), pulse.DriveChannel(0))
with pulse.build() as sched_y1:
builder.call(sched_x1, name="x1")
with pulse.build() as sched_z1:
builder.call(sched_y1, name="y1")
self.assertEqual(len(sched_z1.references), 1)
self.assertEqual(sched_z1.references[("y1",)], sched_y1)
self.assertEqual(len(sched_y1.references), 1)
self.assertEqual(sched_y1.references[("x1",)], sched_x1)
def test_call_schedule_parameter_scope(self):
"""Test call schedule.
Parameter in the called schedule has the scope of called schedule.
"""
param = circuit.Parameter("name")
with pulse.build() as sched_x1:
pulse.play(pulse.Constant(100, param, name="x1"), pulse.DriveChannel(0))
with pulse.build() as sched_y1:
builder.call(sched_x1, name="x1")
with pulse.build() as sched_z1:
builder.call(sched_y1, name="y1")
self.assertEqual(sched_z1.parameters, sched_x1.parameters)
self.assertEqual(sched_z1.parameters, sched_y1.parameters)
def test_append_and_call_schedule(self):
"""Test call and append schedule.
Reference is copied to the outer schedule by appending.
Original reference remains unchanged.
"""
with pulse.build() as sched_x1:
pulse.play(pulse.Constant(100, 0.1, name="x1"), pulse.DriveChannel(0))
with pulse.build() as sched_y1:
builder.call(sched_x1, name="x1")
with pulse.build() as sched_z1:
builder.append_schedule(sched_y1)
self.assertEqual(len(sched_z1.references), 1)
self.assertEqual(sched_z1.references[("x1",)], sched_x1)
# blocks[0] is sched_y1 and its reference is now point to outer block reference
self.assertIs(sched_z1.blocks[0].references, sched_z1.references)
# however the original program is protected to prevent unexpected mutation
self.assertIsNot(sched_y1.references, sched_z1.references)
# appended schedule is preserved
self.assertEqual(len(sched_y1.references), 1)
self.assertEqual(sched_y1.references[("x1",)], sched_x1)
def test_calling_similar_schedule(self):
"""Test calling schedules with the same representation.
sched_x1 and sched_y1 are the different subroutines, but same representation.
Two references should be created.
"""
param1 = circuit.Parameter("param")
param2 = circuit.Parameter("param")
with pulse.build() as sched_x1:
pulse.play(pulse.Constant(100, param1, name="p"), pulse.DriveChannel(0))
with pulse.build() as sched_y1:
pulse.play(pulse.Constant(100, param2, name="p"), pulse.DriveChannel(0))
with pulse.build() as sched_z1:
pulse.call(sched_x1)
pulse.call(sched_y1)
self.assertEqual(len(sched_z1.references), 2)
def test_calling_same_schedule(self):
"""Test calling same schedule twice.
Because it calls the same schedule, no duplication should occur in reference table.
"""
param = circuit.Parameter("param")
with pulse.build() as sched_x1:
pulse.play(pulse.Constant(100, param, name="x1"), pulse.DriveChannel(0))
with pulse.build() as sched_z1:
pulse.call(sched_x1, name="same_sched")
pulse.call(sched_x1, name="same_sched")
self.assertEqual(len(sched_z1.references), 1)
def test_calling_same_schedule_with_different_assignment(self):
"""Test calling same schedule twice but with different parameters.
Same schedule is called twice but with different assignment.
Two references should be created.
"""
param = circuit.Parameter("param")
with pulse.build() as sched_x1:
pulse.play(pulse.Constant(100, param, name="x1"), pulse.DriveChannel(0))
with pulse.build() as sched_z1:
pulse.call(sched_x1, param=0.1)
pulse.call(sched_x1, param=0.2)
self.assertEqual(len(sched_z1.references), 2)
def test_alignment_context(self):
"""Test nested alignment context.
Inline alignment is identical to append_schedule operation.
Thus scope is not newly generated.
"""
with pulse.build(name="x1") as sched_x1:
with pulse.align_right():
with pulse.align_left():
pulse.play(pulse.Constant(100, 0.1, name="x1"), pulse.DriveChannel(0))
self.assertEqual(len(sched_x1.references), 0)
def test_appending_child_block(self):
"""Test for edge case.
User can append blocks which is an element of another schedule block.
But this is not standard use case.
In this case, references may contain subroutines which don't exist in the context.
This is because all references within the program are centrally
managed in the most outer block.
"""
with pulse.build() as sched_x1:
pulse.play(pulse.Constant(100, 0.1, name="x1"), pulse.DriveChannel(0))
with pulse.build() as sched_y1:
pulse.play(pulse.Constant(100, 0.2, name="y1"), pulse.DriveChannel(0))
with pulse.build() as sched_x2:
builder.call(sched_x1, name="x1")
self.assertEqual(list(sched_x2.references.keys()), [("x1",)])
with pulse.build() as sched_y2:
builder.call(sched_y1, name="y1")
self.assertEqual(list(sched_y2.references.keys()), [("y1",)])
with pulse.build() as sched_z1:
builder.append_schedule(sched_x2)
builder.append_schedule(sched_y2)
self.assertEqual(list(sched_z1.references.keys()), [("x1",), ("y1",)])
# child block references point to its parent, i.e. sched_z1
self.assertIs(sched_z1.blocks[0].references, sched_z1._reference_manager)
self.assertIs(sched_z1.blocks[1].references, sched_z1._reference_manager)
with pulse.build() as sched_z2:
# Append child block
# The reference of this block is sched_z1.reference thus it contains both x1 and y1.
# However, y1 doesn't exist in the context, so only x1 should be added.
# Usually, user will append sched_x2 directly here, rather than sched_z1.blocks[0]
# This is why this situation is an edge case.
builder.append_schedule(sched_z1.blocks[0])
self.assertEqual(len(sched_z2.references), 1)
self.assertEqual(sched_z2.references[("x1",)], sched_x1)
def test_replacement(self):
"""Test nested alignment context.
Replacing schedule block with schedule block.
Removed block contains own reference, that should be removed with replacement.
New block also contains reference, that should be passed to the current reference.
"""
with pulse.build() as sched_x1:
pulse.play(pulse.Constant(100, 0.1, name="x1"), pulse.DriveChannel(0))
with pulse.build() as sched_y1:
pulse.play(pulse.Constant(100, 0.2, name="y1"), pulse.DriveChannel(0))
with pulse.build() as sched_x2:
builder.call(sched_x1, name="x1")
with pulse.build() as sched_y2:
builder.call(sched_y1, name="y1")
with pulse.build() as sched_z1:
builder.append_schedule(sched_x2)
builder.append_schedule(sched_y2)
self.assertEqual(len(sched_z1.references), 2)
self.assertEqual(sched_z1.references[("x1",)], sched_x1)
self.assertEqual(sched_z1.references[("y1",)], sched_y1)
# Define schedule to replace
with pulse.build() as sched_r1:
pulse.play(pulse.Constant(100, 0.1, name="r1"), pulse.DriveChannel(0))
with pulse.build() as sched_r2:
pulse.call(sched_r1, name="r1")
sched_z2 = sched_z1.replace(sched_x2, sched_r2)
self.assertEqual(len(sched_z2.references), 2)
self.assertEqual(sched_z2.references[("r1",)], sched_r1)
self.assertEqual(sched_z2.references[("y1",)], sched_y1)
def test_parameter_in_multiple_scope(self):
"""Test that using parameter in multiple scopes causes no error"""
param = circuit.Parameter("name")
with pulse.build() as sched_x1:
pulse.play(pulse.Constant(100, param), pulse.DriveChannel(0))
with pulse.build() as sched_y1:
pulse.play(pulse.Constant(100, param), pulse.DriveChannel(1))
with pulse.build() as sched_z1:
pulse.call(sched_x1, name="x1")
pulse.call(sched_y1, name="y1")
self.assertEqual(len(sched_z1.parameters), 1)
self.assertEqual(sched_z1.parameters, {param})
def test_parallel_alignment_equality(self):
"""Testcase for potential edge case.
In parallel alignment context, reference instruction is broadcasted to
all channels. When new channel is added after reference, this should be
connected with reference node.
"""
with pulse.build() as subroutine:
pulse.reference("unassigned")
with pulse.build() as sched1:
with pulse.align_left():
pulse.delay(10, pulse.DriveChannel(0))
pulse.call(subroutine) # This should be broadcasted to d1 as well
pulse.delay(10, pulse.DriveChannel(1))
with pulse.build() as sched2:
with pulse.align_left():
pulse.delay(10, pulse.DriveChannel(0))
pulse.delay(10, pulse.DriveChannel(1))
pulse.call(subroutine)
self.assertNotEqual(sched1, sched2)
def test_subroutine_conflict(self):
"""Test for edge case of appending two schedule blocks having the
references with conflicting reference key.
This operation should fail because one of references will be gone after assignment.
"""
with pulse.build() as sched_x1:
pulse.play(pulse.Constant(100, 0.1), pulse.DriveChannel(0))
with pulse.build() as sched_x2:
pulse.call(sched_x1, name="conflict_name")
self.assertEqual(sched_x2.references[("conflict_name",)], sched_x1)
with pulse.build() as sched_y1:
pulse.play(pulse.Constant(100, 0.2), pulse.DriveChannel(0))
with pulse.build() as sched_y2:
pulse.call(sched_y1, name="conflict_name")
self.assertEqual(sched_y2.references[("conflict_name",)], sched_y1)
with self.assertRaises(pulse.exceptions.PulseError):
with pulse.build():
builder.append_schedule(sched_x2)
builder.append_schedule(sched_y2)
def test_assign_existing_reference(self):
"""Test for explicitly assign existing reference.
This operation should fail because overriding reference is not allowed.
"""
with pulse.build() as sched_x1:
pulse.play(pulse.Constant(100, 0.1), pulse.DriveChannel(0))
with pulse.build() as sched_y1:
pulse.play(pulse.Constant(100, 0.2), pulse.DriveChannel(0))
with pulse.build() as sched_z1:
pulse.call(sched_x1, name="conflict_name")
with self.assertRaises(pulse.exceptions.PulseError):
sched_z1.assign_references({("conflict_name",): sched_y1})
class TestSubroutineWithCXGate(QiskitTestCase):
"""Test called program scope with practical example of building fully parametrized CX gate."""
def setUp(self):
super().setUp()
# parameters of X pulse
self.xp_dur = circuit.Parameter("dur")
self.xp_amp = circuit.Parameter("amp")
self.xp_sigma = circuit.Parameter("sigma")
self.xp_beta = circuit.Parameter("beta")
# amplitude of SX pulse
self.sxp_amp = circuit.Parameter("amp")
# parameters of CR pulse
self.cr_dur = circuit.Parameter("dur")
self.cr_amp = circuit.Parameter("amp")
self.cr_sigma = circuit.Parameter("sigma")
self.cr_risefall = circuit.Parameter("risefall")
# channels
self.control_ch = circuit.Parameter("ctrl")
self.target_ch = circuit.Parameter("tgt")
self.cr_ch = circuit.Parameter("cr")
# echo pulse on control qubit
with pulse.build(name="xp") as xp_sched_q0:
pulse.play(
pulse.Drag(
duration=self.xp_dur,
amp=self.xp_amp,
sigma=self.xp_sigma,
beta=self.xp_beta,
),
channel=pulse.DriveChannel(self.control_ch),
)
self.xp_sched = xp_sched_q0
# local rotation on target qubit
with pulse.build(name="sx") as sx_sched_q1:
pulse.play(
pulse.Drag(
duration=self.xp_dur,
amp=self.sxp_amp,
sigma=self.xp_sigma,
beta=self.xp_beta,
),
channel=pulse.DriveChannel(self.target_ch),
)
self.sx_sched = sx_sched_q1
# cross resonance
with pulse.build(name="cr") as cr_sched:
pulse.play(
pulse.GaussianSquare(
duration=self.cr_dur,
amp=self.cr_amp,
sigma=self.cr_sigma,
risefall_sigma_ratio=self.cr_risefall,
),
channel=pulse.ControlChannel(self.cr_ch),
)
self.cr_sched = cr_sched
def test_lazy_ecr(self):
"""Test lazy subroutines through ECR schedule construction."""
with pulse.build(name="lazy_ecr") as sched:
with pulse.align_sequential():
pulse.reference("cr", "q0", "q1")
pulse.reference("xp", "q0")
with pulse.phase_offset(np.pi, pulse.ControlChannel(self.cr_ch)):
pulse.reference("cr", "q0", "q1")
pulse.reference("xp", "q0")
# Schedule has references
self.assertTrue(sched.is_referenced())
# Schedule is not schedulable because of unassigned references
self.assertFalse(sched.is_schedulable())
# Two references cr and xp are called
self.assertEqual(len(sched.references), 2)
# Parameters in the current scope are Parameter("cr") which is used in phase_offset
# References are not assigned yet.
params = {p.name for p in sched.parameters}
self.assertSetEqual(params, {"cr"})
# Assign CR and XP schedule to the empty reference
sched.assign_references({("cr", "q0", "q1"): self.cr_sched})
sched.assign_references({("xp", "q0"): self.xp_sched})
# Check updated references
assigned_refs = sched.references
self.assertEqual(assigned_refs[("cr", "q0", "q1")], self.cr_sched)
self.assertEqual(assigned_refs[("xp", "q0")], self.xp_sched)
# Parameter added from subroutines
ref_params = {self.cr_ch} | self.cr_sched.parameters | self.xp_sched.parameters
self.assertSetEqual(sched.parameters, ref_params)
# Get parameter without scope, cr amp and xp amp are hit.
params = sched.get_parameters(parameter_name="amp")
self.assertEqual(len(params), 2)
def test_cnot(self):
"""Integration test with CNOT schedule construction."""
# echoed cross resonance
with pulse.build(name="ecr", default_alignment="sequential") as ecr_sched:
pulse.call(self.cr_sched, name="cr")
pulse.call(self.xp_sched, name="xp")
with pulse.phase_offset(np.pi, pulse.ControlChannel(self.cr_ch)):
pulse.call(self.cr_sched, name="cr")
pulse.call(self.xp_sched, name="xp")
# cnot gate, locally equivalent to ecr
with pulse.build(name="cx", default_alignment="sequential") as cx_sched:
pulse.shift_phase(np.pi / 2, pulse.DriveChannel(self.control_ch))
pulse.call(self.sx_sched, name="sx")
pulse.call(ecr_sched, name="ecr")
# assign parameters
assigned_cx = cx_sched.assign_parameters(
value_dict={
self.cr_ch: 0,
self.control_ch: 0,
self.target_ch: 1,
self.sxp_amp: 0.1,
self.xp_amp: 0.2,
self.xp_dur: 160,
self.xp_sigma: 40,
self.xp_beta: 3.0,
self.cr_amp: 0.5,
self.cr_dur: 800,
self.cr_sigma: 64,
self.cr_risefall: 2,
},
inplace=True,
)
flatten_cx = inline_subroutines(assigned_cx)
with pulse.build(default_alignment="sequential") as ref_cx:
# sz
pulse.shift_phase(np.pi / 2, pulse.DriveChannel(0))
with pulse.align_left():
# sx
pulse.play(
pulse.Drag(
duration=160,
amp=0.1,
sigma=40,
beta=3.0,
),
channel=pulse.DriveChannel(1),
)
with pulse.align_sequential():
# cr
with pulse.align_left():
pulse.play(
pulse.GaussianSquare(
duration=800,
amp=0.5,
sigma=64,
risefall_sigma_ratio=2,
),
channel=pulse.ControlChannel(0),
)
# xp
with pulse.align_left():
pulse.play(
pulse.Drag(
duration=160,
amp=0.2,
sigma=40,
beta=3.0,
),
channel=pulse.DriveChannel(0),
)
with pulse.phase_offset(np.pi, pulse.ControlChannel(0)):
# cr
with pulse.align_left():
pulse.play(
pulse.GaussianSquare(
duration=800,
amp=0.5,
sigma=64,
risefall_sigma_ratio=2,
),
channel=pulse.ControlChannel(0),
)
# xp
with pulse.align_left():
pulse.play(
pulse.Drag(
duration=160,
amp=0.2,
sigma=40,
beta=3.0,
),
channel=pulse.DriveChannel(0),
)
self.assertEqual(flatten_cx, ref_cx)
| qiskit/test/python/pulse/test_reference.py/0 | {
"file_path": "qiskit/test/python/pulse/test_reference.py",
"repo_id": "qiskit",
"token_count": 11569
} | 323 |
# This code is part of Qiskit.
#
# (C) Copyright IBM 2023
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
# pylint: disable=missing-module-docstring,missing-class-docstring,missing-function-docstring
import ddt
import qiskit.qasm2
from test import QiskitTestCase # pylint: disable=wrong-import-order
@ddt.ddt
class TestLexer(QiskitTestCase):
# Most of the lexer is fully exercised in the parser tests. These tests here are really mopping
# up some error messages and whatnot that might otherwise be missed.
def test_pathological_formatting(self):
# This is deliberately _terribly_ formatted, included multiple blanks lines in quick
# succession and comments in places you really wouldn't expect to see comments.
program = """
OPENQASM
// do we really need a comment here?
2.0//and another comment very squished up
;
include // this line introduces a file import
"qelib1.inc" // this is the file imported
; // this is a semicolon
gate // we're making a gate
bell( // void, with loose parenthesis in comment )
) a,//
b{h a;cx a //,,,,
,b;}
qreg // a quantum register
q
[ // a square bracket
2];bell q[0],//
q[1];creg c[2];measure q->c;"""
parsed = qiskit.qasm2.loads(program)
expected_unrolled = qiskit.QuantumCircuit(
qiskit.QuantumRegister(2, "q"), qiskit.ClassicalRegister(2, "c")
)
expected_unrolled.h(0)
expected_unrolled.cx(0, 1)
expected_unrolled.measure([0, 1], [0, 1])
self.assertEqual(parsed.decompose(), expected_unrolled)
@ddt.data("0.25", "00.25", "2.5e-1", "2.5e-01", "0.025E+1", ".25", ".025e1", "25e-2")
def test_float_lexes(self, number):
program = f"qreg q[1]; U({number}, 0, 0) q[0];"
parsed = qiskit.qasm2.loads(program)
self.assertEqual(list(parsed.data[0].operation.params), [0.25, 0, 0])
def test_no_decimal_float_rejected_in_strict_mode(self):
with self.assertRaisesRegex(
qiskit.qasm2.QASM2ParseError,
r"\[strict\] all floats must include a decimal point",
):
qiskit.qasm2.loads("OPENQASM 2.0; qreg q[1]; U(25e-2, 0, 0) q[0];", strict=True)
@ddt.data("", "qre", "cre", ".")
def test_non_ascii_bytes_error(self, prefix):
token = f"{prefix}\xff"
with self.assertRaisesRegex(qiskit.qasm2.QASM2ParseError, "encountered a non-ASCII byte"):
qiskit.qasm2.loads(token)
def test_integers_cannot_start_with_zero(self):
with self.assertRaisesRegex(
qiskit.qasm2.QASM2ParseError, "integers cannot have leading zeroes"
):
qiskit.qasm2.loads("0123")
@ddt.data("", "+", "-")
def test_float_exponents_must_have_a_digit(self, sign):
token = f"12.34e{sign}"
with self.assertRaisesRegex(
qiskit.qasm2.QASM2ParseError, "needed to see an integer exponent"
):
qiskit.qasm2.loads(token)
def test_non_builtins_cannot_be_capitalised(self):
with self.assertRaisesRegex(
qiskit.qasm2.QASM2ParseError, "identifiers cannot start with capital"
):
qiskit.qasm2.loads("Qubit")
def test_unterminated_filename_is_invalid(self):
with self.assertRaisesRegex(
qiskit.qasm2.QASM2ParseError, "unexpected end-of-file while lexing string literal"
):
qiskit.qasm2.loads('include "qelib1.inc')
def test_filename_with_linebreak_is_invalid(self):
with self.assertRaisesRegex(
qiskit.qasm2.QASM2ParseError, "unexpected line break while lexing string literal"
):
qiskit.qasm2.loads('include "qe\nlib1.inc";')
def test_strict_single_quoted_path_rejected(self):
with self.assertRaisesRegex(
qiskit.qasm2.QASM2ParseError, r"\[strict\] paths must be in double quotes"
):
qiskit.qasm2.loads("OPENQASM 2.0; include 'qelib1.inc';", strict=True)
def test_version_must_have_word_boundary_after(self):
with self.assertRaisesRegex(
qiskit.qasm2.QASM2ParseError, r"expected a word boundary after a version"
):
qiskit.qasm2.loads("OPENQASM 2a;")
with self.assertRaisesRegex(
qiskit.qasm2.QASM2ParseError, r"expected a word boundary after a version"
):
qiskit.qasm2.loads("OPENQASM 2.0a;")
def test_no_boundary_float_in_version_position(self):
with self.assertRaisesRegex(
qiskit.qasm2.QASM2ParseError, r"expected a word boundary after a float"
):
qiskit.qasm2.loads("OPENQASM .5a;")
with self.assertRaisesRegex(
qiskit.qasm2.QASM2ParseError, r"expected a word boundary after a float"
):
qiskit.qasm2.loads("OPENQASM 0.2e1a;")
def test_integers_must_have_word_boundaries_after(self):
with self.assertRaisesRegex(
qiskit.qasm2.QASM2ParseError, r"expected a word boundary after an integer"
):
qiskit.qasm2.loads("OPENQASM 2.0; qreg q[2a];")
def test_floats_must_have_word_boundaries_after(self):
with self.assertRaisesRegex(
qiskit.qasm2.QASM2ParseError, r"expected a word boundary after a float"
):
qiskit.qasm2.loads("OPENQASM 2.0; qreg q[1]; U(2.0a, 0, 0) q[0];")
def test_single_equals_is_rejected(self):
with self.assertRaisesRegex(
qiskit.qasm2.QASM2ParseError, r"single equals '=' is never valid"
):
qiskit.qasm2.loads("if (a = 2) U(0, 0, 0) q[0];")
def test_bare_dot_is_not_valid_float(self):
with self.assertRaisesRegex(
qiskit.qasm2.QASM2ParseError, r"expected a numeric fractional part"
):
qiskit.qasm2.loads("qreg q[0]; U(2 + ., 0, 0) q[0];")
def test_invalid_token(self):
with self.assertRaisesRegex(
qiskit.qasm2.QASM2ParseError, r"encountered '!', which doesn't match"
):
qiskit.qasm2.loads("!")
| qiskit/test/python/qasm2/test_lexer.py/0 | {
"file_path": "qiskit/test/python/qasm2/test_lexer.py",
"repo_id": "qiskit",
"token_count": 3061
} | 324 |
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Tests for quantum channel representation class."""
import numpy as np
from qiskit.quantum_info.operators.channel import SuperOp
from ..test_operator import OperatorTestCase
class ChannelTestCase(OperatorTestCase):
"""Tests for Channel representations."""
# Pauli-matrix superoperators
sopI = np.eye(4)
sopX = np.kron(OperatorTestCase.UX.conj(), OperatorTestCase.UX)
sopY = np.kron(OperatorTestCase.UY.conj(), OperatorTestCase.UY)
sopZ = np.kron(OperatorTestCase.UZ.conj(), OperatorTestCase.UZ)
sopH = np.kron(OperatorTestCase.UH.conj(), OperatorTestCase.UH)
# Choi-matrices for Pauli-matrix unitaries
choiI = np.array([[1, 0, 0, 1], [0, 0, 0, 0], [0, 0, 0, 0], [1, 0, 0, 1]])
choiX = np.array([[0, 0, 0, 0], [0, 1, 1, 0], [0, 1, 1, 0], [0, 0, 0, 0]])
choiY = np.array([[0, 0, 0, 0], [0, 1, -1, 0], [0, -1, 1, 0], [0, 0, 0, 0]])
choiZ = np.array([[1, 0, 0, -1], [0, 0, 0, 0], [0, 0, 0, 0], [-1, 0, 0, 1]])
choiH = np.array([[1, 1, 1, -1], [1, 1, 1, -1], [1, 1, 1, -1], [-1, -1, -1, 1]]) / 2
# Chi-matrices for Pauli-matrix unitaries
chiI = np.diag([2, 0, 0, 0])
chiX = np.diag([0, 2, 0, 0])
chiY = np.diag([0, 0, 2, 0])
chiZ = np.diag([0, 0, 0, 2])
chiH = np.array([[0, 0, 0, 0], [0, 1, 0, 1], [0, 0, 0, 0], [0, 1, 0, 1]])
# PTM-matrices for Pauli-matrix unitaries
ptmI = np.diag([1, 1, 1, 1])
ptmX = np.diag([1, 1, -1, -1])
ptmY = np.diag([1, -1, 1, -1])
ptmZ = np.diag([1, -1, -1, 1])
ptmH = np.array([[1, 0, 0, 0], [0, 0, 0, 1], [0, 0, -1, 0], [0, 1, 0, 0]])
def simple_circuit_no_measure(self):
"""Return a unitary circuit and the corresponding unitary array."""
# Override OperatorTestCase to return a SuperOp
circ, target = super().simple_circuit_no_measure()
return circ, SuperOp(target)
# Depolarizing channels
def depol_kraus(self, p):
"""Depolarizing channel Kraus operators"""
return [
np.sqrt(1 - p * 3 / 4) * self.UI,
np.sqrt(p / 4) * self.UX,
np.sqrt(p / 4) * self.UY,
np.sqrt(p / 4) * self.UZ,
]
def depol_sop(self, p):
"""Depolarizing channel superoperator matrix"""
return (1 - p) * self.sopI + p * np.array(
[[1, 0, 0, 1], [0, 0, 0, 0], [0, 0, 0, 0], [1, 0, 0, 1]]
) / 2
def depol_choi(self, p):
"""Depolarizing channel Choi-matrix"""
return (1 - p) * self.choiI + p * np.eye(4) / 2
def depol_chi(self, p):
"""Depolarizing channel Chi-matrix"""
return 2 * np.diag([1 - 3 * p / 4, p / 4, p / 4, p / 4])
def depol_ptm(self, p):
"""Depolarizing channel PTM"""
return np.diag([1, 1 - p, 1 - p, 1 - p])
def depol_stine(self, p):
"""Depolarizing channel Stinespring matrix"""
kraus = self.depol_kraus(p)
basis = np.eye(4).reshape((4, 4, 1))
return np.sum([np.kron(k, b) for k, b in zip(kraus, basis)], axis=0)
def rand_kraus(self, input_dim, output_dim, n):
"""Return a random (non-CPTP) Kraus operator map"""
return [self.rand_matrix(output_dim, input_dim) for _ in range(n)]
| qiskit/test/python/quantum_info/operators/channel/channel_test_case.py/0 | {
"file_path": "qiskit/test/python/quantum_info/operators/channel/channel_test_case.py",
"repo_id": "qiskit",
"token_count": 1703
} | 325 |
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Tests for PauliList utility functions."""
import unittest
from qiskit.quantum_info import PauliList, pauli_basis
from test import QiskitTestCase # pylint: disable=wrong-import-order
class TestPauliBasis(QiskitTestCase):
"""Test pauli_basis function"""
def test_standard_order_1q(self):
"""Test 1-qubit pauli_basis function."""
labels = ["I", "X", "Y", "Z"]
target = PauliList(labels)
self.assertEqual(pauli_basis(1), target)
def test_weight_order_1q(self):
"""Test 1-qubit pauli_basis function with weight=True."""
labels = ["I", "X", "Y", "Z"]
target = PauliList(labels)
self.assertEqual(pauli_basis(1, weight=True), target)
def test_standard_order_2q(self):
"""Test 2-qubit pauli_basis function."""
labels = [
"II",
"IX",
"IY",
"IZ",
"XI",
"XX",
"XY",
"XZ",
"YI",
"YX",
"YY",
"YZ",
"ZI",
"ZX",
"ZY",
"ZZ",
]
target = PauliList(labels)
self.assertEqual(pauli_basis(2), target)
def test_weight_order_2q(self):
"""Test 2-qubit pauli_basis function with weight=True."""
labels = [
"II",
"IX",
"IY",
"IZ",
"XI",
"YI",
"ZI",
"XX",
"XY",
"XZ",
"YX",
"YY",
"YZ",
"ZX",
"ZY",
"ZZ",
]
target = PauliList(labels)
self.assertEqual(pauli_basis(2, weight=True), target)
def test_standard_order_3q(self):
"""Test 3-qubit pauli_basis function."""
labels = [
"III",
"IIX",
"IIY",
"IIZ",
"IXI",
"IXX",
"IXY",
"IXZ",
"IYI",
"IYX",
"IYY",
"IYZ",
"IZI",
"IZX",
"IZY",
"IZZ",
"XII",
"XIX",
"XIY",
"XIZ",
"XXI",
"XXX",
"XXY",
"XXZ",
"XYI",
"XYX",
"XYY",
"XYZ",
"XZI",
"XZX",
"XZY",
"XZZ",
"YII",
"YIX",
"YIY",
"YIZ",
"YXI",
"YXX",
"YXY",
"YXZ",
"YYI",
"YYX",
"YYY",
"YYZ",
"YZI",
"YZX",
"YZY",
"YZZ",
"ZII",
"ZIX",
"ZIY",
"ZIZ",
"ZXI",
"ZXX",
"ZXY",
"ZXZ",
"ZYI",
"ZYX",
"ZYY",
"ZYZ",
"ZZI",
"ZZX",
"ZZY",
"ZZZ",
]
target = PauliList(labels)
self.assertEqual(pauli_basis(3), target)
def test_weight_order_3q(self):
"""Test 3-qubit pauli_basis function with weight=True."""
labels = [
"III",
"IIX",
"IIY",
"IIZ",
"IXI",
"IYI",
"IZI",
"XII",
"YII",
"ZII",
"IXX",
"IXY",
"IXZ",
"IYX",
"IYY",
"IYZ",
"IZX",
"IZY",
"IZZ",
"XIX",
"XIY",
"XIZ",
"XXI",
"XYI",
"XZI",
"YIX",
"YIY",
"YIZ",
"YXI",
"YYI",
"YZI",
"ZIX",
"ZIY",
"ZIZ",
"ZXI",
"ZYI",
"ZZI",
"XXX",
"XXY",
"XXZ",
"XYX",
"XYY",
"XYZ",
"XZX",
"XZY",
"XZZ",
"YXX",
"YXY",
"YXZ",
"YYX",
"YYY",
"YYZ",
"YZX",
"YZY",
"YZZ",
"ZXX",
"ZXY",
"ZXZ",
"ZYX",
"ZYY",
"ZYZ",
"ZZX",
"ZZY",
"ZZZ",
]
target = PauliList(labels)
self.assertEqual(pauli_basis(3, weight=True), target)
if __name__ == "__main__":
unittest.main()
| qiskit/test/python/quantum_info/operators/symplectic/test_pauli_utils.py/0 | {
"file_path": "qiskit/test/python/quantum_info/operators/symplectic/test_pauli_utils.py",
"repo_id": "qiskit",
"token_count": 3440
} | 326 |
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Tests quaternion conversion"""
import math
import numpy as np
from numpy.testing import assert_allclose
import scipy.linalg as la
from qiskit.quantum_info.quaternion import Quaternion
from test import QiskitTestCase # pylint: disable=wrong-import-order
class TestQuaternions(QiskitTestCase):
"""Tests qiskit.quantum_info.operators.quaternion"""
def setUp(self):
super().setUp()
self.rnd_array = np.array([0.5, 0.8, 0.9, -0.3])
self.quat_unnormalized = Quaternion(self.rnd_array)
axes = ["x", "y", "z"]
rnd = np.array([-0.92545003, -2.19985357, 6.01761209])
idx = np.array([0, 2, 1])
self.mat1 = rotation_matrix(rnd[0], axes[idx[0]]).dot(
rotation_matrix(rnd[1], axes[idx[1]]).dot(rotation_matrix(rnd[2], axes[idx[2]]))
)
axes_str = "".join(axes[i] for i in idx)
quat = Quaternion.from_euler(rnd, axes_str)
self.mat2 = quat.to_matrix()
def test_str(self):
"""Quaternion should have a correct string representation."""
self.assertEqual(self.quat_unnormalized.__str__(), self.rnd_array.__str__())
def test_repr(self):
"""Quaternion should have a correct string representation."""
self.assertEqual(self.quat_unnormalized.__repr__(), self.rnd_array.__str__())
def test_norm(self):
"""Quaternions should give correct norm."""
norm = la.norm(self.rnd_array)
self.assertEqual(norm, self.quat_unnormalized.norm())
def test_normalize(self):
"""Quaternions should be normalizable"""
self.assertAlmostEqual(self.quat_unnormalized.normalize().norm(), 1, places=5)
def test_random_euler(self):
"""Quaternion from Euler rotations."""
assert_allclose(self.mat1, self.mat2)
def test_orthogonality(self):
"""Quaternion rotation matrix orthogonality"""
assert_allclose(self.mat2.dot(self.mat2.T), np.identity(3, dtype=float), atol=1e-8)
def test_det(self):
"""Quaternion det = 1"""
assert_allclose(la.det(self.mat2), 1)
def test_equiv_quaternions(self):
"""Different Euler rotations give same quaternion, up to sign."""
# Check if Euler angles from to_zyz return same quaternion
# up to a sign (2pi rotation)
rot = ["xyz", "xyx", "xzy", "xzx", "yzx", "yzy", "yxz", "yxy", "zxy", "zxz", "zyx", "zyz"]
for value in rot:
rnd = np.array([-1.57657536, 5.66384302, 2.91532185])
quat1 = Quaternion.from_euler(rnd, value)
euler = quat1.to_zyz()
quat2 = Quaternion.from_euler(euler, "zyz")
assert_allclose(abs(quat1.data.dot(quat2.data)), 1)
def test_mul_by_quat(self):
"""Quaternions should multiply correctly."""
# multiplication of quaternions is equivalent to the
# multiplication of corresponding rotation matrices.
other_quat = Quaternion(np.array([0.4, 0.2, -0.7, 0.8]))
other_mat = other_quat.to_matrix()
product_quat = self.quat_unnormalized * other_quat
product_mat = (self.quat_unnormalized.to_matrix()).dot(other_mat)
assert_allclose(product_quat.to_matrix(), product_mat)
def test_mul_by_array(self):
"""Quaternions cannot be multiplied with an array."""
other_array = np.array([0.1, 0.2, 0.3, 0.4])
with self.assertRaises(TypeError):
_ = self.quat_unnormalized * other_array
def test_mul_by_scalar(self):
"""Quaternions cannot be multiplied with a scalar."""
other_scalar = 0.123456789
with self.assertRaises(TypeError):
_ = self.quat_unnormalized * other_scalar
def test_rotation(self):
"""Multiplication by -1 should give the same rotation."""
neg_quat = Quaternion(self.quat_unnormalized.data * -1)
assert_allclose(neg_quat.to_matrix(), self.quat_unnormalized.to_matrix())
def test_one_euler_angle(self):
"""Quaternion should return a correct sequence of zyz representation
in the case of rotations when there is only one non-zero Euler angle."""
rand_rot_angle = 0.123456789
some_quat = Quaternion.from_axis_rotation(rand_rot_angle, "z")
assert_allclose(some_quat.to_zyz(), np.array([rand_rot_angle, 0, 0]))
def test_two_euler_angle_0123456789(self):
"""Quaternion should return a correct sequence of zyz representation
in the case of rotations when there are only two non-zero Euler angle.
angle = 0.123456789"""
rand_rot_angle = 0.123456789
some_quat = Quaternion.from_axis_rotation(
rand_rot_angle, "z"
) * Quaternion.from_axis_rotation(np.pi, "y")
assert_allclose(some_quat.to_zyz(), np.array([rand_rot_angle, np.pi, 0]))
def test_two_euler_angle_0987654321(self):
"""Quaternion should return a correct sequence of zyz representation
in the case of rotations when there are only two non-zero Euler angle.
angle = 0.987654321"""
rand_rot_angle = 0.987654321
some_quat = Quaternion.from_axis_rotation(
rand_rot_angle, "z"
) * Quaternion.from_axis_rotation(np.pi, "y")
assert_allclose(some_quat.to_zyz(), np.array([rand_rot_angle, np.pi, 0]))
def test_quaternion_from_rotation_invalid_axis(self):
"""Cannot generate quaternion from rotations around invalid axis."""
rand_axis = "a"
rand_angle = 0.123456789
self.assertRaises(ValueError, Quaternion.from_axis_rotation, rand_angle, rand_axis)
def rotation_matrix(angle, axis):
"""Generates a rotation matrix for a given angle and axis.
Args:
angle (float): Rotation angle in radians.
axis (str): Axis for rotation: 'x', 'y', 'z'
Returns:
ndarray: Rotation matrix.
Raises:
ValueError: Invalid input axis.
"""
direction = np.zeros(3, dtype=float)
if axis == "x":
direction[0] = 1
elif axis == "y":
direction[1] = 1
elif axis == "z":
direction[2] = 1
else:
raise ValueError("Invalid axis.")
direction = np.asarray(direction, dtype=float)
sin_angle = math.sin(angle)
cos_angle = math.cos(angle)
rot = np.diag([cos_angle, cos_angle, cos_angle])
rot += np.outer(direction, direction) * (1.0 - cos_angle)
direction *= sin_angle
rot += np.array(
[
[0, -direction[2], direction[1]],
[direction[2], 0, -direction[0]],
[-direction[1], direction[0], 0],
]
)
return rot
| qiskit/test/python/quantum_info/test_quaternions.py/0 | {
"file_path": "qiskit/test/python/quantum_info/test_quaternions.py",
"repo_id": "qiskit",
"token_count": 3061
} | 327 |
# This code is part of Qiskit.
#
# (C) Copyright IBM 2022.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""
Tests for Layer1Q implementation.
"""
import unittest
from random import randint
import numpy as np
import qiskit.synthesis.unitary.aqc.fast_gradient.layer as lr
from qiskit.synthesis.unitary.aqc.fast_gradient.pmatrix import PMatrix
from test import QiskitTestCase # pylint: disable=wrong-import-order
import test.python.synthesis.aqc.fast_gradient.utils_for_testing as tut # pylint: disable=wrong-import-order
class TestLayer1q(QiskitTestCase):
"""
Tests for Layer1Q class.
"""
max_num_qubits = 5 # maximum number of qubits in tests
num_repeats = 50 # number of repetitions in tests
def setUp(self):
super().setUp()
np.random.seed(0x0696969)
def test_layer1q_matrix(self):
"""
Tests: (1) the correctness of Layer2Q matrix construction;
(2) matrix multiplication interleaved with permutations.
"""
mat_kind = "complex"
eps = 100.0 * np.finfo(float).eps
max_rel_err = 0.0
for n in range(2, self.max_num_qubits + 1):
dim = 2**n
iden = tut.eye_int(n)
for k in range(n):
m_mat = tut.rand_matrix(dim=dim, kind=mat_kind)
t_mat, g_mat = tut.make_test_matrices2x2(n=n, k=k, kind=mat_kind)
lmat = lr.Layer1Q(num_qubits=n, k=k, g2x2=g_mat)
g2, perm, inv_perm = lmat.get_attr()
self.assertTrue(m_mat.dtype == t_mat.dtype == g_mat.dtype == g2.dtype)
self.assertTrue(np.all(g_mat == g2))
self.assertTrue(np.all(iden[perm].T == iden[inv_perm]))
g_mat = np.kron(tut.eye_int(n - 1), g_mat)
# T == P^t @ G @ P.
err = tut.relative_error(t_mat, iden[perm].T @ g_mat @ iden[perm])
self.assertLess(err, eps, f"err = {err:0.16f}")
max_rel_err = max(max_rel_err, err)
# Multiplication by permutation matrix of the left can be
# replaced by row permutations.
tm = t_mat @ m_mat
err1 = tut.relative_error(iden[perm].T @ g_mat @ m_mat[perm], tm)
err2 = tut.relative_error((g_mat @ m_mat[perm])[inv_perm], tm)
# Multiplication by permutation matrix of the right can be
# replaced by column permutations.
mt = m_mat @ t_mat
err3 = tut.relative_error(m_mat @ iden[perm].T @ g_mat @ iden[perm], mt)
err4 = tut.relative_error((m_mat[:, perm] @ g_mat)[:, inv_perm], mt)
self.assertTrue(
err1 < eps and err2 < eps and err3 < eps and err4 < eps,
f"err1 = {err1:f}, err2 = {err2:f}, " f"err3 = {err3:f}, err4 = {err4:f}",
)
max_rel_err = max(max_rel_err, err1, err2, err3, err4)
def test_pmatrix_class(self):
"""
Test the class PMatrix.
"""
_eps = 100.0 * np.finfo(float).eps
mat_kind = "complex"
max_rel_err = 0.0
for n in range(2, self.max_num_qubits + 1):
dim = 2**n
tmp1 = np.ndarray((dim, dim), dtype=np.complex128)
tmp2 = tmp1.copy()
for _ in range(self.num_repeats):
k0 = randint(0, n - 1)
k1 = randint(0, n - 1)
k2 = randint(0, n - 1)
k3 = randint(0, n - 1)
k4 = randint(0, n - 1)
t0, g0 = tut.make_test_matrices2x2(n=n, k=k0, kind=mat_kind)
t1, g1 = tut.make_test_matrices2x2(n=n, k=k1, kind=mat_kind)
t2, g2 = tut.make_test_matrices2x2(n=n, k=k2, kind=mat_kind)
t3, g3 = tut.make_test_matrices2x2(n=n, k=k3, kind=mat_kind)
t4, g4 = tut.make_test_matrices2x2(n=n, k=k4, kind=mat_kind)
c0 = lr.Layer1Q(num_qubits=n, k=k0, g2x2=g0)
c1 = lr.Layer1Q(num_qubits=n, k=k1, g2x2=g1)
c2 = lr.Layer1Q(num_qubits=n, k=k2, g2x2=g2)
c3 = lr.Layer1Q(num_qubits=n, k=k3, g2x2=g3)
c4 = lr.Layer1Q(num_qubits=n, k=k4, g2x2=g4)
m_mat = tut.rand_matrix(dim=dim, kind=mat_kind)
ttmtt = t0 @ t1 @ m_mat @ np.conj(t2).T @ np.conj(t3).T
pmat = PMatrix(n)
pmat.set_matrix(m_mat)
pmat.mul_left_q1(layer=c1, temp_mat=tmp1)
pmat.mul_left_q1(layer=c0, temp_mat=tmp1)
pmat.mul_right_q1(layer=c2, temp_mat=tmp1, dagger=True)
pmat.mul_right_q1(layer=c3, temp_mat=tmp1, dagger=True)
alt_ttmtt = pmat.finalize(temp_mat=tmp1)
err1 = tut.relative_error(alt_ttmtt, ttmtt)
self.assertLess(err1, _eps, f"relative error: {err1:f}")
prod = np.complex128(np.trace(ttmtt @ t4))
alt_prod = pmat.product_q1(layer=c4, tmp1=tmp1, tmp2=tmp2)
err2 = abs(alt_prod - prod) / abs(prod)
self.assertLess(err2, _eps, f"relative error: {err2:f}")
max_rel_err = max(max_rel_err, err1, err2)
if __name__ == "__main__":
unittest.main()
| qiskit/test/python/synthesis/aqc/fast_gradient/test_layer1q.py/0 | {
"file_path": "qiskit/test/python/synthesis/aqc/fast_gradient/test_layer1q.py",
"repo_id": "qiskit",
"token_count": 3052
} | 328 |
# 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 permutation synthesis functions."""
import unittest
import numpy as np
from ddt import ddt, data
from qiskit.quantum_info.operators import Operator
from qiskit.circuit.library import LinearFunction, PermutationGate
from qiskit.synthesis.permutation import (
synth_permutation_acg,
synth_permutation_depth_lnn_kms,
synth_permutation_basic,
synth_permutation_reverse_lnn_kms,
)
from qiskit.synthesis.permutation.permutation_utils import (
_inverse_pattern,
_validate_permutation,
)
from test import QiskitTestCase # pylint: disable=wrong-import-order
@ddt
class TestPermutationSynthesis(QiskitTestCase):
"""Test the permutation synthesis functions."""
@data(4, 5, 10, 15, 20)
def test_inverse_pattern(self, width):
"""Test _inverse_pattern function produces correct index map."""
np.random.seed(1)
for _ in range(5):
pattern = np.random.permutation(width)
inverse = _inverse_pattern(pattern)
for ii, jj in enumerate(pattern):
self.assertTrue(inverse[jj] == ii)
@data(10, 20)
def test_invalid_permutations(self, width):
"""Check that _validate_permutation raises exceptions when the
input is not a permutation."""
np.random.seed(1)
for _ in range(5):
pattern = np.random.permutation(width)
pattern_out_of_range = np.copy(pattern)
pattern_out_of_range[0] = -1
with self.assertRaises(ValueError) as exc:
_validate_permutation(pattern_out_of_range)
self.assertIn("input contains a negative number", str(exc.exception))
pattern_out_of_range = np.copy(pattern)
pattern_out_of_range[0] = width
with self.assertRaises(ValueError) as exc:
_validate_permutation(pattern_out_of_range)
self.assertIn(f"input has length {width} and contains {width}", str(exc.exception))
pattern_duplicate = np.copy(pattern)
pattern_duplicate[-1] = pattern[0]
with self.assertRaises(ValueError) as exc:
_validate_permutation(pattern_duplicate)
self.assertIn(f"input contains {pattern[0]} more than once", str(exc.exception))
@data(4, 5, 10, 15, 20)
def test_synth_permutation_basic(self, width):
"""Test synth_permutation_basic function produces the correct
circuit."""
np.random.seed(1)
for _ in range(5):
pattern = np.random.permutation(width)
qc = synth_permutation_basic(pattern)
# Check that the synthesized circuit consists of SWAP gates only.
for instruction in qc.data:
self.assertEqual(instruction.operation.name, "swap")
# Construct a linear function from the synthesized circuit, and
# check that its permutation pattern matches the original pattern.
synthesized_pattern = LinearFunction(qc).permutation_pattern()
self.assertTrue(np.array_equal(synthesized_pattern, pattern))
@data(4, 5, 10, 15, 20)
def test_synth_permutation_acg(self, width):
"""Test synth_permutation_acg function produces the correct
circuit."""
np.random.seed(1)
for _ in range(5):
pattern = np.random.permutation(width)
qc = synth_permutation_acg(pattern)
# Check that the synthesized circuit consists of SWAP gates only.
for instruction in qc.data:
self.assertEqual(instruction.operation.name, "swap")
# Check that the depth of the circuit (measured in terms of SWAPs) is at most 2.
self.assertLessEqual(qc.depth(), 2)
# Construct a linear function from the synthesized circuit, and
# check that its permutation pattern matches the original pattern.
synthesized_pattern = LinearFunction(qc).permutation_pattern()
self.assertTrue(np.array_equal(synthesized_pattern, pattern))
@data(4, 5, 10, 15, 20)
def test_synth_permutation_depth_lnn_kms(self, width):
"""Test synth_permutation_depth_lnn_kms function produces the correct
circuit."""
np.random.seed(1)
for _ in range(5):
pattern = np.random.permutation(width)
qc = synth_permutation_depth_lnn_kms(pattern)
# Check that the synthesized circuit consists of SWAP gates only,
# and that these SWAPs adhere to the LNN connectivity.
for instruction in qc.data:
self.assertEqual(instruction.operation.name, "swap")
q0 = qc.find_bit(instruction.qubits[0]).index
q1 = qc.find_bit(instruction.qubits[1]).index
dist = abs(q0 - q1)
self.assertEqual(dist, 1)
# Check that the depth of the circuit (measured in #SWAPs)
# does not exceed the number of qubits.
self.assertLessEqual(qc.depth(), width)
# Construct a linear function from the synthesized circuit, and
# check that its permutation pattern matches the original pattern.
synthesized_pattern = LinearFunction(qc).permutation_pattern()
self.assertTrue(np.array_equal(synthesized_pattern, pattern))
@data(1, 2, 3, 4, 5, 10, 15, 20)
def test_synth_permutation_reverse_lnn_kms(self, num_qubits):
"""Test synth_permutation_reverse_lnn_kms function produces the correct
circuit."""
pattern = list(reversed(range(num_qubits)))
qc = synth_permutation_reverse_lnn_kms(num_qubits)
self.assertListEqual((LinearFunction(qc).permutation_pattern()).tolist(), pattern)
# Check that the CX depth of the circuit is at 2*n+2
self.assertTrue(qc.depth() <= 2 * num_qubits + 2)
# Check that the synthesized circuit consists of CX gates only,
# and that these CXs adhere to the LNN connectivity.
for instruction in qc.data:
self.assertEqual(instruction.operation.name, "cx")
q0 = qc.find_bit(instruction.qubits[0]).index
q1 = qc.find_bit(instruction.qubits[1]).index
dist = abs(q0 - q1)
self.assertEqual(dist, 1)
@data(4, 5, 6, 7)
def test_permutation_matrix(self, width):
"""Test that the unitary matrix constructed from permutation pattern
is correct."""
np.random.seed(1)
for _ in range(5):
pattern = np.random.permutation(width)
qc = synth_permutation_depth_lnn_kms(pattern)
expected = Operator(qc)
constructed = Operator(PermutationGate(pattern))
self.assertEqual(expected, constructed)
if __name__ == "__main__":
unittest.main()
| qiskit/test/python/synthesis/test_permutation_synthesis.py/0 | {
"file_path": "qiskit/test/python/synthesis/test_permutation_synthesis.py",
"repo_id": "qiskit",
"token_count": 3059
} | 329 |
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2018.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
# pylint: disable=invalid-name,super-init-not-called
"""Dummy passes used by Transpiler testing"""
import logging
from qiskit.transpiler.passes import FixedPoint
from qiskit.transpiler import TransformationPass, AnalysisPass
logger = "LocalLogger"
class DummyTP(TransformationPass):
"""A dummy transformation pass."""
def run(self, dag):
logging.getLogger(logger).info("run transformation pass %s", self.name())
return dag
class DummyAP(AnalysisPass):
"""A dummy analysis pass."""
def run(self, dag):
logging.getLogger(logger).info("run analysis pass %s", self.name())
class PassA_TP_NR_NP(DummyTP):
"""A dummy pass without any requires/preserves.
TP: Transformation Pass
NR: No requires
NP: No preserves
"""
def __init__(self):
super().__init__()
self.preserves.append(self) # preserves itself (idempotence)
class PassB_TP_RA_PA(DummyTP):
"""A dummy pass that requires PassA_TP_NR_NP and preserves it.
TP: Transformation Pass
RA: Requires PassA
PA: Preserves PassA
"""
def __init__(self):
super().__init__()
self.requires.append(PassA_TP_NR_NP())
self.preserves.append(PassA_TP_NR_NP())
self.preserves.append(self) # preserves itself (idempotence)
class PassC_TP_RA_PA(DummyTP):
"""A dummy pass that requires PassA_TP_NR_NP and preserves it.
TP: Transformation Pass
RA: Requires PassA
PA: Preserves PassA
"""
def __init__(self):
super().__init__()
self.requires.append(PassA_TP_NR_NP())
self.preserves.append(PassA_TP_NR_NP())
self.preserves.append(self) # preserves itself (idempotence)
class PassD_TP_NR_NP(DummyTP):
"""A dummy transformation pass that takes an argument.
TP: Transformation Pass
NR: No Requires
NP: No Preserves
"""
def __init__(self, argument1=None, argument2=None):
super().__init__()
self.argument1 = argument1
self.argument2 = argument2
self.preserves.append(self) # preserves itself (idempotence)
def run(self, dag):
super().run(dag)
logging.getLogger(logger).info("argument %s", self.argument1)
return dag
class PassE_AP_NR_NP(DummyAP):
"""A dummy analysis pass that takes an argument.
AP: Analysis Pass
NR: No Requires
NP: No Preserves
"""
def __init__(self, argument1):
super().__init__()
self.argument1 = argument1
def run(self, dag):
super().run(dag)
self.property_set["property"] = self.argument1
logging.getLogger(logger).info("set property as %s", self.property_set["property"])
class PassF_reduce_dag_property(DummyTP):
"""A dummy transformation pass that (sets and) reduces a property in the DAG.
NI: Non-idempotent transformation pass
NR: No Requires
NP: No Preserves
"""
def run(self, dag):
super().run(dag)
if dag.duration is None:
dag.duration = 8
dag.duration = round(dag.duration * 0.8)
logging.getLogger(logger).info("dag property = %i", dag.duration)
return dag
class PassG_calculates_dag_property(DummyAP):
"""A dummy transformation pass that "calculates" property in the DAG.
AP: Analysis Pass
NR: No Requires
NP: No Preserves
"""
def run(self, dag):
super().run(dag)
if dag.duration is not None:
self.property_set["property"] = dag.duration
else:
self.property_set["property"] = 8
logging.getLogger(logger).info(
"set property as %s (from dag.property)", self.property_set["property"]
)
class PassH_Bad_TP(DummyTP):
"""A dummy transformation pass tries to modify the property set.
NR: No Requires
NP: No Preserves
"""
def run(self, dag):
super().run(dag)
self.property_set["property"] = "value"
logging.getLogger(logger).info("set property as %s", self.property_set["property"])
return dag
class PassI_Bad_AP(DummyAP):
"""A dummy analysis pass tries to modify the dag.
NR: No Requires
NP: No Preserves
"""
def run(self, dag):
super().run(dag)
cx_runs = dag.collect_runs(["cx"])
# Convert to ID so that can be checked if in correct order
cx_runs_ids = set()
for run in cx_runs:
curr = []
for node in run:
curr.append(node._node_id)
cx_runs_ids.add(tuple(curr))
logging.getLogger(logger).info("cx_runs: %s", cx_runs_ids)
dag.remove_op_node(cx_runs.pop()[0])
logging.getLogger(logger).info("done removing")
class PassJ_Bad_NoReturn(DummyTP):
"""A bad dummy transformation pass that does not return a DAG.
NR: No Requires
NP: No Preserves
"""
def run(self, dag):
super().run(dag)
return "Something else than DAG"
class PassK_check_fixed_point_property(DummyAP, FixedPoint):
"""A dummy analysis pass that checks if a property reached a fixed point. The results is saved
in property_set['fixed_point'][<property>] as a boolean
AP: Analysis Pass
R: PassG_calculates_dag_property()
"""
def __init__(self):
FixedPoint.__init__(self, "property")
self.requires.append(PassG_calculates_dag_property())
def run(self, dag):
for base in PassK_check_fixed_point_property.__bases__:
base.run(self, dag)
class PassM_AP_NR_NP(DummyAP):
"""A dummy analysis pass that modifies internal state at runtime
AP: Analysis Pass
NR: No Requires
NP: No Preserves
"""
def __init__(self, argument1):
super().__init__()
self.argument1 = argument1
def run(self, dag):
super().run(dag)
self.argument1 *= 2
logging.getLogger(logger).info("self.argument1 = %s", self.argument1)
class PassN_AP_NR_NP(DummyAP):
"""A dummy analysis pass that deletes and nones properties.
AP: Analysis Pass
NR: No Requires
NP: No Preserves
"""
def __init__(self, to_delete, to_none):
super().__init__()
self.to_delete = to_delete
self.to_none = to_none
def run(self, dag):
super().run(dag)
del self.property_set[self.to_delete]
logging.getLogger(logger).info("property %s deleted", self.to_delete)
self.property_set[self.to_none] = None
logging.getLogger(logger).info("property %s noned", self.to_none)
| qiskit/test/python/transpiler/_dummy_passes.py/0 | {
"file_path": "qiskit/test/python/transpiler/_dummy_passes.py",
"repo_id": "qiskit",
"token_count": 2818
} | 330 |
# 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.
"""Commutation analysis and transformation pass testing"""
import unittest
from qiskit.circuit import QuantumRegister, QuantumCircuit, Qubit
from qiskit.transpiler import PropertySet
from qiskit.transpiler.passes import CommutationAnalysis
from qiskit.converters import circuit_to_dag
from test import QiskitTestCase # pylint: disable=wrong-import-order
class TestCommutationAnalysis(QiskitTestCase):
"""Test the Commutation pass."""
def setUp(self):
super().setUp()
self.pass_ = CommutationAnalysis()
self.pset = self.pass_.property_set = PropertySet()
def assertCommutationSet(self, result, expected):
"""Compares the result of propertyset["commutation_set"] with a dictionary of the form
{'q[0]': [ [node_id, ...], [node_id, ...] ]}
"""
result_to_compare = {}
for qbit, sets in result.items():
if not isinstance(qbit, Qubit):
continue
result_to_compare[qbit] = []
for commutation_set in sets:
result_to_compare[qbit].append(sorted(node._node_id for node in commutation_set))
for qbit, sets in expected.items():
for commutation_set in sets:
commutation_set.sort()
self.assertDictEqual(result_to_compare, expected)
def test_commutation_set_property_is_created(self):
"""Test property is created"""
qr = QuantumRegister(3, "qr")
circuit = QuantumCircuit(qr)
circuit.h(qr)
dag = circuit_to_dag(circuit)
self.assertIsNone(self.pset["commutation_set"])
self.pass_.run(dag)
self.assertIsNotNone(self.pset["commutation_set"])
def test_all_gates(self):
"""Test all gates on 1 and 2 qubits
qr0:----[H]---[x]---[y]---[t]---[s]---[rz]---[p]---[u]---[u]---.---.---.--
| | |
qr1:----------------------------------------------------------(+)-(Y)--.--
"""
qr = QuantumRegister(2, "qr")
circuit = QuantumCircuit(qr)
circuit.h(qr[0])
circuit.x(qr[0])
circuit.y(qr[0])
circuit.t(qr[0])
circuit.s(qr[0])
circuit.rz(0.5, qr[0])
circuit.p(0.5, qr[0])
circuit.u(1.57, 0.5, 0.6, qr[0])
circuit.u(0.5, 0.6, 0.7, qr[0])
circuit.cx(qr[0], qr[1])
circuit.cy(qr[0], qr[1])
circuit.cz(qr[0], qr[1])
dag = circuit_to_dag(circuit)
self.pass_.run(dag)
expected = {
qr[0]: [[0], [4], [5], [6], [7, 8, 9, 10], [11], [12], [13], [14], [15], [1]],
qr[1]: [[2], [13], [14], [15], [3]],
}
self.assertCommutationSet(self.pset["commutation_set"], expected)
def test_non_commutative_circuit(self):
"""A simple circuit where no gates commute
qr0:---[H]---
qr1:---[H]---
qr2:---[H]---
"""
qr = QuantumRegister(3, "qr")
circuit = QuantumCircuit(qr)
circuit.h(qr)
dag = circuit_to_dag(circuit)
self.pass_.run(dag)
expected = {qr[0]: [[0], [6], [1]], qr[1]: [[2], [7], [3]], qr[2]: [[4], [8], [5]]}
self.assertCommutationSet(self.pset["commutation_set"], expected)
def test_non_commutative_circuit_2(self):
"""A simple circuit where no gates commute
qr0:----.-------------
|
qr1:---(+)------.-----
|
qr2:---[H]-----(+)----
"""
qr = QuantumRegister(3, "qr")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[1])
circuit.h(qr[2])
circuit.cx(qr[1], qr[2])
dag = circuit_to_dag(circuit)
self.pass_.run(dag)
expected = {
qr[0]: [[0], [6], [1]],
qr[1]: [[2], [6], [8], [3]],
qr[2]: [[4], [7], [8], [5]],
}
self.assertCommutationSet(self.pset["commutation_set"], expected)
def test_commutative_circuit(self):
"""A simple circuit where two CNOTs commute
qr0:----.------------
|
qr1:---(+)-----(+)---
|
qr2:---[H]------.----
"""
qr = QuantumRegister(3, "qr")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[1])
circuit.h(qr[2])
circuit.cx(qr[2], qr[1])
dag = circuit_to_dag(circuit)
self.pass_.run(dag)
expected = {qr[0]: [[0], [6], [1]], qr[1]: [[2], [6, 8], [3]], qr[2]: [[4], [7], [8], [5]]}
self.assertCommutationSet(self.pset["commutation_set"], expected)
def test_commutative_circuit_2(self):
"""A simple circuit where a CNOT and a Z gate commute,
and a CNOT and a CNOT commute
qr0:----.-----[Z]-----
|
qr1:---(+)----(+)----
|
qr2:---[H]-----.----
"""
qr = QuantumRegister(3, "qr")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[1])
circuit.z(qr[0])
circuit.h(qr[2])
circuit.cx(qr[2], qr[1])
dag = circuit_to_dag(circuit)
self.pass_.run(dag)
expected = {
qr[0]: [[0], [6, 7], [1]],
qr[1]: [[2], [6, 9], [3]],
qr[2]: [[4], [8], [9], [5]],
}
self.assertCommutationSet(self.pset["commutation_set"], expected)
def test_commutative_circuit_3(self):
"""A simple circuit where multiple gates commute
qr0:----.-----[Z]-----.----[z]-----
| |
qr1:---(+)----(+)----(+)----.------
| |
qr2:---[H]-----.-----[x]---(+)-----
"""
qr = QuantumRegister(3, "qr")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[1])
circuit.h(qr[2])
circuit.z(qr[0])
circuit.cx(qr[2], qr[1])
circuit.cx(qr[0], qr[1])
circuit.x(qr[2])
circuit.z(qr[0])
circuit.cx(qr[1], qr[2])
dag = circuit_to_dag(circuit)
self.pass_.run(dag)
expected = {
qr[0]: [[0], [6, 8, 10, 12], [1]],
qr[1]: [[2], [6, 9, 10], [13], [3]],
qr[2]: [[4], [7], [9], [11, 13], [5]],
}
self.assertCommutationSet(self.pset["commutation_set"], expected)
def test_jordan_wigner_type_circuit(self):
"""A Jordan-Wigner type circuit where consecutive CNOTs commute
qr0:----.-------------------------------------------------------------.----
| |
qr1:---(+)----.-------------------------------------------------.----(+)---
| |
qr2:---------(+)----.-------------------------------------.----(+)---------
| |
qr3:---------------(+)----.-------------------------.----(+)---------------
| |
qr4:---------------------(+)----.-------------.----(+)---------------------
| |
qr5:---------------------------(+)----[z]----(+)---------------------------
"""
qr = QuantumRegister(6, "qr")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[1])
circuit.cx(qr[1], qr[2])
circuit.cx(qr[2], qr[3])
circuit.cx(qr[3], qr[4])
circuit.cx(qr[4], qr[5])
circuit.z(qr[5])
circuit.cx(qr[4], qr[5])
circuit.cx(qr[3], qr[4])
circuit.cx(qr[2], qr[3])
circuit.cx(qr[1], qr[2])
circuit.cx(qr[0], qr[1])
dag = circuit_to_dag(circuit)
self.pass_.run(dag)
expected = {
qr[0]: [[0], [12, 22], [1]],
qr[1]: [[2], [12], [13, 21], [22], [3]],
qr[2]: [[4], [13], [14, 20], [21], [5]],
qr[3]: [[6], [14], [15, 19], [20], [7]],
qr[4]: [[8], [15], [16, 18], [19], [9]],
qr[5]: [[10], [16], [17], [18], [11]],
}
self.assertCommutationSet(self.pset["commutation_set"], expected)
def test_all_commute_circuit(self):
"""Test circuit with that all commute"""
# ┌───┐
# qr_0: ──■──┤ Z ├──■────────────
# ┌─┴─┐├───┤┌─┴─┐┌───┐
# qr_1: ┤ X ├┤ X ├┤ X ├┤ X ├─────
# └───┘└─┬─┘└───┘└─┬─┘
# qr_2: ───────■────■────■────■──
# ┌───┐ ┌─┴─┐┌───┐┌─┴─┐
# qr_3: ┤ X ├─────┤ X ├┤ X ├┤ X ├
# └─┬─┘┌───┐└───┘└─┬─┘└───┘
# qr_4: ──■──┤ Z ├───────■───────
# └───┘
qr = QuantumRegister(5, "qr")
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[1])
circuit.cx(qr[2], qr[1])
circuit.cx(qr[4], qr[3])
circuit.cx(qr[2], qr[3])
circuit.z(qr[0])
circuit.z(qr[4])
circuit.cx(qr[0], qr[1])
circuit.cx(qr[2], qr[1])
circuit.cx(qr[4], qr[3])
circuit.cx(qr[2], qr[3])
dag = circuit_to_dag(circuit)
self.pass_.run(dag)
expected = {
qr[0]: [[0], [10, 14, 16], [1]],
qr[1]: [[2], [10, 11, 16, 17], [3]],
qr[2]: [[4], [11, 13, 17, 19], [5]],
qr[3]: [[6], [12, 13, 18, 19], [7]],
qr[4]: [[8], [12, 15, 18], [9]],
}
self.assertCommutationSet(self.pset["commutation_set"], expected)
if __name__ == "__main__":
unittest.main()
| qiskit/test/python/transpiler/test_commutation_analysis.py/0 | {
"file_path": "qiskit/test/python/transpiler/test_commutation_analysis.py",
"repo_id": "qiskit",
"token_count": 5575
} | 331 |
# This code is part of Qiskit.
#
# (C) Copyright IBM 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test dynamical decoupling insertion pass."""
import unittest
import numpy as np
from numpy import pi
from ddt import ddt, data
from qiskit import pulse
from qiskit.circuit import Gate, QuantumCircuit, Delay, Measure, Reset, Parameter
from qiskit.circuit.library import XGate, YGate, RXGate, UGate, CXGate, HGate
from qiskit.quantum_info import Operator
from qiskit.transpiler.instruction_durations import InstructionDurations
from qiskit.transpiler.passes import (
ASAPScheduleAnalysis,
ALAPScheduleAnalysis,
PadDynamicalDecoupling,
)
from qiskit.transpiler.passmanager import PassManager
from qiskit.transpiler.exceptions import TranspilerError
from qiskit.transpiler.target import Target, InstructionProperties
from test import QiskitTestCase # pylint: disable=wrong-import-order
@ddt
class TestPadDynamicalDecoupling(QiskitTestCase):
"""Tests PadDynamicalDecoupling pass."""
def setUp(self):
"""Circuits to test DD on.
┌───┐
q_0: ┤ H ├──■────────────
└───┘┌─┴─┐
q_1: ─────┤ X ├──■───────
└───┘┌─┴─┐
q_2: ──────────┤ X ├──■──
└───┘┌─┴─┐
q_3: ───────────────┤ X ├
└───┘
┌──────────┐
q_0: ──■──┤ U(π,0,π) ├──────────■──
┌─┴─┐└──────────┘ ┌─┴─┐
q_1: ┤ X ├─────■───────────■──┤ X ├
└───┘ ┌─┴─┐ ┌─┐┌─┴─┐└───┘
q_2: ────────┤ X ├────┤M├┤ X ├─────
└───┘ └╥┘└───┘
c: 1/══════════════════╩═══════════
0
"""
super().setUp()
self.ghz4 = QuantumCircuit(4)
self.ghz4.h(0)
self.ghz4.cx(0, 1)
self.ghz4.cx(1, 2)
self.ghz4.cx(2, 3)
self.midmeas = QuantumCircuit(3, 1)
self.midmeas.cx(0, 1)
self.midmeas.cx(1, 2)
self.midmeas.u(pi, 0, pi, 0)
self.midmeas.measure(2, 0)
self.midmeas.cx(1, 2)
self.midmeas.cx(0, 1)
self.durations = InstructionDurations(
[
("h", 0, 50),
("cx", [0, 1], 700),
("cx", [1, 2], 200),
("cx", [2, 3], 300),
("x", None, 50),
("y", None, 50),
("u", None, 100),
("rx", None, 100),
("measure", None, 1000),
("reset", None, 1500),
]
)
def test_insert_dd_ghz(self):
"""Test DD gates are inserted in correct spots.
┌───┐ ┌────────────────┐ ┌───┐ »
q_0: ──────┤ H ├─────────■──┤ Delay(100[dt]) ├──────┤ X ├──────»
┌─────┴───┴─────┐ ┌─┴─┐└────────────────┘┌─────┴───┴─────┐»
q_1: ┤ Delay(50[dt]) ├─┤ X ├────────■─────────┤ Delay(50[dt]) ├»
├───────────────┴┐└───┘ ┌─┴─┐ └───────────────┘»
q_2: ┤ Delay(750[dt]) ├───────────┤ X ├───────────────■────────»
├────────────────┤ └───┘ ┌─┴─┐ »
q_3: ┤ Delay(950[dt]) ├─────────────────────────────┤ X ├──────»
└────────────────┘ └───┘ »
« ┌────────────────┐ ┌───┐ ┌────────────────┐
«q_0: ┤ Delay(200[dt]) ├──────┤ X ├───────┤ Delay(100[dt]) ├─────────────────
« └─────┬───┬──────┘┌─────┴───┴──────┐└─────┬───┬──────┘┌───────────────┐
«q_1: ──────┤ X ├───────┤ Delay(100[dt]) ├──────┤ X ├───────┤ Delay(50[dt]) ├
« └───┘ └────────────────┘ └───┘ └───────────────┘
«q_2: ───────────────────────────────────────────────────────────────────────
«
«q_3: ───────────────────────────────────────────────────────────────────────
«
"""
dd_sequence = [XGate(), XGate()]
pm = PassManager(
[
ALAPScheduleAnalysis(self.durations),
PadDynamicalDecoupling(self.durations, dd_sequence),
]
)
ghz4_dd = pm.run(self.ghz4)
expected = self.ghz4.copy()
expected = expected.compose(Delay(50), [1], front=True)
expected = expected.compose(Delay(750), [2], front=True)
expected = expected.compose(Delay(950), [3], front=True)
expected = expected.compose(Delay(100), [0])
expected = expected.compose(XGate(), [0])
expected = expected.compose(Delay(200), [0])
expected = expected.compose(XGate(), [0])
expected = expected.compose(Delay(100), [0])
expected = expected.compose(Delay(50), [1])
expected = expected.compose(XGate(), [1])
expected = expected.compose(Delay(100), [1])
expected = expected.compose(XGate(), [1])
expected = expected.compose(Delay(50), [1])
self.assertEqual(ghz4_dd, expected)
def test_insert_dd_ghz_with_target(self):
"""Test DD gates are inserted in correct spots.
┌───┐ ┌────────────────┐ ┌───┐ »
q_0: ──────┤ H ├─────────■──┤ Delay(100[dt]) ├──────┤ X ├──────»
┌─────┴───┴─────┐ ┌─┴─┐└────────────────┘┌─────┴───┴─────┐»
q_1: ┤ Delay(50[dt]) ├─┤ X ├────────■─────────┤ Delay(50[dt]) ├»
├───────────────┴┐└───┘ ┌─┴─┐ └───────────────┘»
q_2: ┤ Delay(750[dt]) ├───────────┤ X ├───────────────■────────»
├────────────────┤ └───┘ ┌─┴─┐ »
q_3: ┤ Delay(950[dt]) ├─────────────────────────────┤ X ├──────»
└────────────────┘ └───┘ »
« ┌────────────────┐ ┌───┐ ┌────────────────┐
«q_0: ┤ Delay(200[dt]) ├──────┤ X ├───────┤ Delay(100[dt]) ├─────────────────
« └─────┬───┬──────┘┌─────┴───┴──────┐└─────┬───┬──────┘┌───────────────┐
«q_1: ──────┤ X ├───────┤ Delay(100[dt]) ├──────┤ X ├───────┤ Delay(50[dt]) ├
« └───┘ └────────────────┘ └───┘ └───────────────┘
«q_2: ───────────────────────────────────────────────────────────────────────
«
«q_3: ───────────────────────────────────────────────────────────────────────
«
"""
target = Target(num_qubits=4, dt=1)
target.add_instruction(HGate(), {(0,): InstructionProperties(duration=50)})
target.add_instruction(
CXGate(),
{
(0, 1): InstructionProperties(duration=700),
(1, 2): InstructionProperties(duration=200),
(2, 3): InstructionProperties(duration=300),
},
)
target.add_instruction(
XGate(), {(x,): InstructionProperties(duration=50) for x in range(4)}
)
target.add_instruction(
YGate(), {(x,): InstructionProperties(duration=50) for x in range(4)}
)
target.add_instruction(
UGate(Parameter("theta"), Parameter("phi"), Parameter("lambda")),
{(x,): InstructionProperties(duration=100) for x in range(4)},
)
target.add_instruction(
RXGate(Parameter("theta")),
{(x,): InstructionProperties(duration=100) for x in range(4)},
)
target.add_instruction(
Measure(), {(x,): InstructionProperties(duration=1000) for x in range(4)}
)
target.add_instruction(
Reset(), {(x,): InstructionProperties(duration=1500) for x in range(4)}
)
target.add_instruction(Delay(Parameter("t")), {(x,): None for x in range(4)})
dd_sequence = [XGate(), XGate()]
pm = PassManager(
[
ALAPScheduleAnalysis(target=target),
PadDynamicalDecoupling(target=target, dd_sequence=dd_sequence),
]
)
ghz4_dd = pm.run(self.ghz4)
expected = self.ghz4.copy()
expected = expected.compose(Delay(50), [1], front=True)
expected = expected.compose(Delay(750), [2], front=True)
expected = expected.compose(Delay(950), [3], front=True)
expected = expected.compose(Delay(100), [0])
expected = expected.compose(XGate(), [0])
expected = expected.compose(Delay(200), [0])
expected = expected.compose(XGate(), [0])
expected = expected.compose(Delay(100), [0])
expected = expected.compose(Delay(50), [1])
expected = expected.compose(XGate(), [1])
expected = expected.compose(Delay(100), [1])
expected = expected.compose(XGate(), [1])
expected = expected.compose(Delay(50), [1])
self.assertEqual(ghz4_dd, expected)
def test_insert_dd_ghz_one_qubit(self):
"""Test DD gates are inserted on only one qubit.
┌───┐ ┌────────────────┐ ┌───┐ »
q_0: ──────┤ H ├─────────■──┤ Delay(100[dt]) ├──────┤ X ├───────»
┌─────┴───┴─────┐ ┌─┴─┐└────────────────┘┌─────┴───┴──────┐»
q_1: ┤ Delay(50[dt]) ├─┤ X ├────────■─────────┤ Delay(300[dt]) ├»
├───────────────┴┐└───┘ ┌─┴─┐ └────────────────┘»
q_2: ┤ Delay(750[dt]) ├───────────┤ X ├───────────────■─────────»
├────────────────┤ └───┘ ┌─┴─┐ »
q_3: ┤ Delay(950[dt]) ├─────────────────────────────┤ X ├───────»
└────────────────┘ └───┘ »
meas: 4/═══════════════════════════════════════════════════════════»
»
« ┌────────────────┐┌───┐┌────────────────┐ ░ ┌─┐
« q_0: ┤ Delay(200[dt]) ├┤ X ├┤ Delay(100[dt]) ├─░─┤M├─────────
« └────────────────┘└───┘└────────────────┘ ░ └╥┘┌─┐
« q_1: ──────────────────────────────────────────░──╫─┤M├──────
« ░ ║ └╥┘┌─┐
« q_2: ──────────────────────────────────────────░──╫──╫─┤M├───
« ░ ║ ║ └╥┘┌─┐
« q_3: ──────────────────────────────────────────░──╫──╫──╫─┤M├
« ░ ║ ║ ║ └╥┘
«meas: 4/═════════════════════════════════════════════╩══╩══╩══╩═
« 0 1 2 3
"""
dd_sequence = [XGate(), XGate()]
pm = PassManager(
[
ALAPScheduleAnalysis(self.durations),
PadDynamicalDecoupling(self.durations, dd_sequence, qubits=[0]),
]
)
ghz4_dd = pm.run(self.ghz4.measure_all(inplace=False))
expected = self.ghz4.copy()
expected = expected.compose(Delay(50), [1], front=True)
expected = expected.compose(Delay(750), [2], front=True)
expected = expected.compose(Delay(950), [3], front=True)
expected = expected.compose(Delay(100), [0])
expected = expected.compose(XGate(), [0])
expected = expected.compose(Delay(200), [0])
expected = expected.compose(XGate(), [0])
expected = expected.compose(Delay(100), [0])
expected = expected.compose(Delay(300), [1])
expected.measure_all()
self.assertEqual(ghz4_dd, expected)
def test_insert_dd_ghz_everywhere(self):
"""Test DD gates even on initial idle spots.
┌───┐ ┌────────────────┐┌───┐┌────────────────┐┌───┐»
q_0: ──────┤ H ├─────────■──┤ Delay(100[dt]) ├┤ Y ├┤ Delay(200[dt]) ├┤ Y ├»
┌─────┴───┴─────┐ ┌─┴─┐└────────────────┘└───┘└────────────────┘└───┘»
q_1: ┤ Delay(50[dt]) ├─┤ X ├───────────────────────────────────────────■──»
├───────────────┴┐├───┤┌────────────────┐┌───┐┌────────────────┐┌─┴─┐»
q_2: ┤ Delay(162[dt]) ├┤ Y ├┤ Delay(326[dt]) ├┤ Y ├┤ Delay(162[dt]) ├┤ X ├»
├────────────────┤├───┤├────────────────┤├───┤├────────────────┤└───┘»
q_3: ┤ Delay(212[dt]) ├┤ Y ├┤ Delay(426[dt]) ├┤ Y ├┤ Delay(212[dt]) ├─────»
└────────────────┘└───┘└────────────────┘└───┘└────────────────┘ »
« ┌────────────────┐
«q_0: ┤ Delay(100[dt]) ├─────────────────────────────────────────────
« ├───────────────┬┘┌───┐┌────────────────┐┌───┐┌───────────────┐
«q_1: ┤ Delay(50[dt]) ├─┤ Y ├┤ Delay(100[dt]) ├┤ Y ├┤ Delay(50[dt]) ├
« └───────────────┘ └───┘└────────────────┘└───┘└───────────────┘
«q_2: ────────■──────────────────────────────────────────────────────
« ┌─┴─┐
«q_3: ──────┤ X ├────────────────────────────────────────────────────
« └───┘
"""
dd_sequence = [YGate(), YGate()]
pm = PassManager(
[
ALAPScheduleAnalysis(self.durations),
PadDynamicalDecoupling(self.durations, dd_sequence, skip_reset_qubits=False),
]
)
ghz4_dd = pm.run(self.ghz4)
expected = self.ghz4.copy()
expected = expected.compose(Delay(50), [1], front=True)
expected = expected.compose(Delay(162), [2], front=True)
expected = expected.compose(YGate(), [2], front=True)
expected = expected.compose(Delay(326), [2], front=True)
expected = expected.compose(YGate(), [2], front=True)
expected = expected.compose(Delay(162), [2], front=True)
expected = expected.compose(Delay(212), [3], front=True)
expected = expected.compose(YGate(), [3], front=True)
expected = expected.compose(Delay(426), [3], front=True)
expected = expected.compose(YGate(), [3], front=True)
expected = expected.compose(Delay(212), [3], front=True)
expected = expected.compose(Delay(100), [0])
expected = expected.compose(YGate(), [0])
expected = expected.compose(Delay(200), [0])
expected = expected.compose(YGate(), [0])
expected = expected.compose(Delay(100), [0])
expected = expected.compose(Delay(50), [1])
expected = expected.compose(YGate(), [1])
expected = expected.compose(Delay(100), [1])
expected = expected.compose(YGate(), [1])
expected = expected.compose(Delay(50), [1])
self.assertEqual(ghz4_dd, expected)
def test_insert_dd_with_pulse_gate_calibrations(self):
"""Test DD gates are inserted without error when circuit calibrations are used
┌───┐ ┌───────────────┐ ┌───┐ »
q_0: ──────┤ H ├─────────■──┤ Delay(75[dt]) ├──────┤ X ├───────»
┌─────┴───┴─────┐ ┌─┴─┐└───────────────┘┌─────┴───┴──────┐»
q_1: ┤ Delay(50[dt]) ├─┤ X ├────────■────────┤ Delay(300[dt]) ├»
├───────────────┴┐└───┘ ┌─┴─┐ └────────────────┘»
q_2: ┤ Delay(750[dt]) ├───────────┤ X ├──────────────■─────────»
├────────────────┤ └───┘ ┌─┴─┐ »
q_3: ┤ Delay(950[dt]) ├────────────────────────────┤ X ├───────»
└────────────────┘ └───┘ »
meas: 4/══════════════════════════════════════════════════════════»
»
« ┌────────────────┐┌───┐┌───────────────┐ ░ ┌─┐
« q_0: ┤ Delay(150[dt]) ├┤ X ├┤ Delay(75[dt]) ├─░─┤M├─────────
« └────────────────┘└───┘└───────────────┘ ░ └╥┘┌─┐
« q_1: ─────────────────────────────────────────░──╫─┤M├──────
« ░ ║ └╥┘┌─┐
« q_2: ─────────────────────────────────────────░──╫──╫─┤M├───
« ░ ║ ║ └╥┘┌─┐
« q_3: ─────────────────────────────────────────░──╫──╫──╫─┤M├
« ░ ║ ║ ║ └╥┘
«meas: 4/════════════════════════════════════════════╩══╩══╩══╩═
« 0 1 2 3
"""
dd_sequence = [XGate(), XGate()]
pm = PassManager(
[
ALAPScheduleAnalysis(self.durations),
PadDynamicalDecoupling(self.durations, dd_sequence, qubits=[0]),
]
)
# Change duration to 100 from the 50 in self.durations to make sure
# gate duration is used correctly.
with pulse.builder.build() as x_sched:
pulse.builder.delay(100, pulse.DriveChannel(0))
circ_in = self.ghz4.measure_all(inplace=False)
circ_in.add_calibration(XGate(), (0,), x_sched)
ghz4_dd = pm.run(circ_in)
expected = self.ghz4.copy()
expected = expected.compose(Delay(50), [1], front=True)
expected = expected.compose(Delay(750), [2], front=True)
expected = expected.compose(Delay(950), [3], front=True)
# Delays different from those of the default case using self.durations
expected = expected.compose(Delay(75), [0])
expected = expected.compose(XGate(), [0])
expected = expected.compose(Delay(150), [0])
expected = expected.compose(XGate(), [0])
expected = expected.compose(Delay(75), [0])
expected = expected.compose(Delay(300), [1])
expected.measure_all()
expected.add_calibration(XGate(), (0,), x_sched)
self.assertEqual(ghz4_dd, expected)
def test_insert_dd_with_pulse_gate_calibrations_with_parmas(self):
"""Test DD gates are inserted without error when parameterized circuit calibrations are used
┌───┐ ┌───────────────┐ ┌───┐ »
q_0: ──────┤ H ├─────────■──┤ Delay(75[dt]) ├──────┤ X ├───────»
┌─────┴───┴─────┐ ┌─┴─┐└───────────────┘┌─────┴───┴──────┐»
q_1: ┤ Delay(50[dt]) ├─┤ X ├────────■────────┤ Delay(300[dt]) ├»
├───────────────┴┐└───┘ ┌─┴─┐ └────────────────┘»
q_2: ┤ Delay(750[dt]) ├───────────┤ X ├──────────────■─────────»
├────────────────┤ └───┘ ┌─┴─┐ »
q_3: ┤ Delay(950[dt]) ├────────────────────────────┤ X ├───────»
└────────────────┘ └───┘ »
meas: 4/══════════════════════════════════════════════════════════»
»
« ┌────────────────┐┌───┐┌───────────────┐ ░ ┌─┐
« q_0: ┤ Delay(150[dt]) ├┤ X ├┤ Delay(75[dt]) ├─░─┤M├─────────
« └────────────────┘└───┘└───────────────┘ ░ └╥┘┌─┐
« q_1: ─────────────────────────────────────────░──╫─┤M├──────
« ░ ║ └╥┘┌─┐
« q_2: ─────────────────────────────────────────░──╫──╫─┤M├───
« ░ ║ ║ └╥┘┌─┐
« q_3: ─────────────────────────────────────────░──╫──╫──╫─┤M├
« ░ ║ ║ ║ └╥┘
«meas: 4/════════════════════════════════════════════╩══╩══╩══╩═
« 0 1 2 3
"""
# Change duration to 100 from the 50 in self.durations to make sure
# gate duration is used correctly.
amp = Parameter("amp")
with pulse.builder.build() as sched:
pulse.builder.play(
pulse.Gaussian(100, amp=amp, sigma=10.0),
pulse.DriveChannel(0),
)
class Echo(Gate):
"""Dummy Gate subclass for testing
In this test, we use a non-standard gate so we can add parameters
to it, in order to test the handling of parameters by
PadDynamicalDecoupling. PadDynamicalDecoupling checks that the DD
sequence is equivalent to the identity, so we can not use Gate
directly. Here we subclass Gate and add the identity as its matrix
representation to satisfy PadDynamicalDecoupling's check.
"""
def __array__(self, dtype=None, copy=None):
if copy is False:
raise ValueError("cannot produce matrix without calculation")
return np.eye(2, dtype=dtype)
# A gate with one unbound and one bound parameter to leave in the final
# circuit.
echo = Echo("echo", 1, [amp, 10.0])
circ_in = self.ghz4.measure_all(inplace=False)
circ_in.add_calibration(echo, (0,), sched)
dd_sequence = [echo, echo]
pm = PassManager(
[
ALAPScheduleAnalysis(self.durations),
PadDynamicalDecoupling(self.durations, dd_sequence, qubits=[0]),
]
)
ghz4_dd = pm.run(circ_in)
expected = self.ghz4.copy()
expected = expected.compose(Delay(50), [1], front=True)
expected = expected.compose(Delay(750), [2], front=True)
expected = expected.compose(Delay(950), [3], front=True)
# Delays different from those of the default case using self.durations
expected = expected.compose(Delay(75), [0])
expected = expected.compose(echo, [0])
expected = expected.compose(Delay(150), [0])
expected = expected.compose(echo, [0])
expected = expected.compose(Delay(75), [0])
expected = expected.compose(Delay(300), [1])
expected.measure_all()
expected.add_calibration(echo, (0,), sched)
self.assertEqual(ghz4_dd, expected)
def test_insert_dd_ghz_xy4(self):
"""Test XY4 sequence of DD gates.
┌───┐ ┌───────────────┐ ┌───┐ ┌───────────────┐»
q_0: ──────┤ H ├─────────■──┤ Delay(37[dt]) ├──────┤ X ├──────┤ Delay(75[dt]) ├»
┌─────┴───┴─────┐ ┌─┴─┐└───────────────┘┌─────┴───┴─────┐└─────┬───┬─────┘»
q_1: ┤ Delay(50[dt]) ├─┤ X ├────────■────────┤ Delay(12[dt]) ├──────┤ X ├──────»
├───────────────┴┐└───┘ ┌─┴─┐ └───────────────┘ └───┘ »
q_2: ┤ Delay(750[dt]) ├───────────┤ X ├──────────────■─────────────────────────»
├────────────────┤ └───┘ ┌─┴─┐ »
q_3: ┤ Delay(950[dt]) ├────────────────────────────┤ X ├───────────────────────»
└────────────────┘ └───┘ »
« ┌───┐ ┌───────────────┐ ┌───┐ ┌───────────────┐»
«q_0: ──────┤ Y ├──────┤ Delay(76[dt]) ├──────┤ X ├──────┤ Delay(75[dt]) ├»
« ┌─────┴───┴─────┐└─────┬───┬─────┘┌─────┴───┴─────┐└─────┬───┬─────┘»
«q_1: ┤ Delay(25[dt]) ├──────┤ Y ├──────┤ Delay(26[dt]) ├──────┤ X ├──────»
« └───────────────┘ └───┘ └───────────────┘ └───┘ »
«q_2: ────────────────────────────────────────────────────────────────────»
« »
«q_3: ────────────────────────────────────────────────────────────────────»
« »
« ┌───┐ ┌───────────────┐
«q_0: ──────┤ Y ├──────┤ Delay(37[dt]) ├─────────────────
« ┌─────┴───┴─────┐└─────┬───┬─────┘┌───────────────┐
«q_1: ┤ Delay(25[dt]) ├──────┤ Y ├──────┤ Delay(12[dt]) ├
« └───────────────┘ └───┘ └───────────────┘
«q_2: ───────────────────────────────────────────────────
«
«q_3: ───────────────────────────────────────────────────
"""
dd_sequence = [XGate(), YGate(), XGate(), YGate()]
pm = PassManager(
[
ALAPScheduleAnalysis(self.durations),
PadDynamicalDecoupling(self.durations, dd_sequence),
]
)
ghz4_dd = pm.run(self.ghz4)
expected = self.ghz4.copy()
expected = expected.compose(Delay(50), [1], front=True)
expected = expected.compose(Delay(750), [2], front=True)
expected = expected.compose(Delay(950), [3], front=True)
expected = expected.compose(Delay(37), [0])
expected = expected.compose(XGate(), [0])
expected = expected.compose(Delay(75), [0])
expected = expected.compose(YGate(), [0])
expected = expected.compose(Delay(76), [0])
expected = expected.compose(XGate(), [0])
expected = expected.compose(Delay(75), [0])
expected = expected.compose(YGate(), [0])
expected = expected.compose(Delay(37), [0])
expected = expected.compose(Delay(12), [1])
expected = expected.compose(XGate(), [1])
expected = expected.compose(Delay(25), [1])
expected = expected.compose(YGate(), [1])
expected = expected.compose(Delay(26), [1])
expected = expected.compose(XGate(), [1])
expected = expected.compose(Delay(25), [1])
expected = expected.compose(YGate(), [1])
expected = expected.compose(Delay(12), [1])
self.assertEqual(ghz4_dd, expected)
def test_insert_midmeas_hahn_alap(self):
"""Test a single X gate as Hahn echo can absorb in the downstream circuit.
global phase: 3π/2
┌────────────────┐ ┌───┐ ┌────────────────┐»
q_0: ────────■─────────┤ Delay(625[dt]) ├───────┤ X ├───────┤ Delay(625[dt]) ├»
┌─┴─┐ └────────────────┘┌──────┴───┴──────┐└────────────────┘»
q_1: ──────┤ X ├───────────────■─────────┤ Delay(1000[dt]) ├────────■─────────»
┌─────┴───┴──────┐ ┌─┴─┐ └───────┬─┬───────┘ ┌─┴─┐ »
q_2: ┤ Delay(700[dt]) ├──────┤ X ├───────────────┤M├──────────────┤ X ├───────»
└────────────────┘ └───┘ └╥┘ └───┘ »
c: 1/═════════════════════════════════════════════╩═══════════════════════════»
0 »
« ┌───────────────┐
«q_0: ┤ U(0,π/2,-π/2) ├───■──
« └───────────────┘ ┌─┴─┐
«q_1: ──────────────────┤ X ├
« ┌────────────────┐└───┘
«q_2: ┤ Delay(700[dt]) ├─────
« └────────────────┘
«c: 1/═══════════════════════
"""
dd_sequence = [XGate()]
pm = PassManager(
[
ALAPScheduleAnalysis(self.durations),
PadDynamicalDecoupling(self.durations, dd_sequence),
]
)
midmeas_dd = pm.run(self.midmeas)
combined_u = UGate(0, 0, 0)
expected = QuantumCircuit(3, 1)
expected.cx(0, 1)
expected.delay(625, 0)
expected.x(0)
expected.delay(625, 0)
expected.compose(combined_u, [0], inplace=True)
expected.delay(700, 2)
expected.cx(1, 2)
expected.delay(1000, 1)
expected.measure(2, 0)
expected.cx(1, 2)
expected.cx(0, 1)
expected.delay(700, 2)
expected.global_phase = pi
self.assertEqual(midmeas_dd, expected)
# check the absorption into U was done correctly
self.assertEqual(Operator(combined_u), Operator(XGate()) & Operator(XGate()))
def test_insert_midmeas_hahn_asap(self):
"""Test a single X gate as Hahn echo can absorb in the upstream circuit.
┌──────────────────┐ ┌────────────────┐┌─────────┐»
q_0: ────────■─────────┤ U(3π/4,-π/2,π/2) ├─┤ Delay(600[dt]) ├┤ Rx(π/4) ├»
┌─┴─┐ └──────────────────┘┌┴────────────────┤└─────────┘»
q_1: ──────┤ X ├────────────────■──────────┤ Delay(1000[dt]) ├─────■─────»
┌─────┴───┴──────┐ ┌─┴─┐ └───────┬─┬───────┘ ┌─┴─┐ »
q_2: ┤ Delay(700[dt]) ├───────┤ X ├────────────────┤M├───────────┤ X ├───»
└────────────────┘ └───┘ └╥┘ └───┘ »
c: 1/═══════════════════════════════════════════════╩════════════════════»
0 »
« ┌────────────────┐
«q_0: ┤ Delay(600[dt]) ├──■──
« └────────────────┘┌─┴─┐
«q_1: ──────────────────┤ X ├
« ┌────────────────┐└───┘
«q_2: ┤ Delay(700[dt]) ├─────
« └────────────────┘
«c: 1/═══════════════════════
«
"""
dd_sequence = [RXGate(pi / 4)]
pm = PassManager(
[
ASAPScheduleAnalysis(self.durations),
PadDynamicalDecoupling(self.durations, dd_sequence),
]
)
midmeas_dd = pm.run(self.midmeas)
combined_u = UGate(3 * pi / 4, -pi / 2, pi / 2)
expected = QuantumCircuit(3, 1)
expected.cx(0, 1)
expected.compose(combined_u, [0], inplace=True)
expected.delay(600, 0)
expected.rx(pi / 4, 0)
expected.delay(600, 0)
expected.delay(700, 2)
expected.cx(1, 2)
expected.delay(1000, 1)
expected.measure(2, 0)
expected.cx(1, 2)
expected.cx(0, 1)
expected.delay(700, 2)
self.assertEqual(midmeas_dd, expected)
# check the absorption into U was done correctly
self.assertTrue(
Operator(XGate()).equiv(
Operator(UGate(3 * pi / 4, -pi / 2, pi / 2)) & Operator(RXGate(pi / 4))
)
)
def test_insert_ghz_uhrig(self):
"""Test custom spacing (following Uhrig DD [1]).
[1] Uhrig, G. "Keeping a quantum bit alive by optimized π-pulse sequences."
Physical Review Letters 98.10 (2007): 100504.
┌───┐ ┌──────────────┐ ┌───┐ ┌──────────────┐┌───┐»
q_0: ──────┤ H ├─────────■──┤ Delay(3[dt]) ├──────┤ X ├───────┤ Delay(8[dt]) ├┤ X ├»
┌─────┴───┴─────┐ ┌─┴─┐└──────────────┘┌─────┴───┴──────┐└──────────────┘└───┘»
q_1: ┤ Delay(50[dt]) ├─┤ X ├───────■────────┤ Delay(300[dt]) ├─────────────────────»
├───────────────┴┐└───┘ ┌─┴─┐ └────────────────┘ »
q_2: ┤ Delay(750[dt]) ├──────────┤ X ├──────────────■──────────────────────────────»
├────────────────┤ └───┘ ┌─┴─┐ »
q_3: ┤ Delay(950[dt]) ├───────────────────────────┤ X ├────────────────────────────»
└────────────────┘ └───┘ »
« ┌───────────────┐┌───┐┌───────────────┐┌───┐┌───────────────┐┌───┐┌───────────────┐»
«q_0: ┤ Delay(13[dt]) ├┤ X ├┤ Delay(16[dt]) ├┤ X ├┤ Delay(20[dt]) ├┤ X ├┤ Delay(16[dt]) ├»
« └───────────────┘└───┘└───────────────┘└───┘└───────────────┘└───┘└───────────────┘»
«q_1: ───────────────────────────────────────────────────────────────────────────────────»
« »
«q_2: ───────────────────────────────────────────────────────────────────────────────────»
« »
«q_3: ───────────────────────────────────────────────────────────────────────────────────»
« »
« ┌───┐┌───────────────┐┌───┐┌──────────────┐┌───┐┌──────────────┐
«q_0: ┤ X ├┤ Delay(13[dt]) ├┤ X ├┤ Delay(8[dt]) ├┤ X ├┤ Delay(3[dt]) ├
« └───┘└───────────────┘└───┘└──────────────┘└───┘└──────────────┘
«q_1: ────────────────────────────────────────────────────────────────
«
«q_2: ────────────────────────────────────────────────────────────────
«
«q_3: ────────────────────────────────────────────────────────────────
«
"""
n = 8
dd_sequence = [XGate()] * n
# uhrig specifies the location of the k'th pulse
def uhrig(k):
return np.sin(np.pi * (k + 1) / (2 * n + 2)) ** 2
# convert that to spacing between pulses (whatever finite duration pulses have)
spacing = []
for k in range(n):
spacing.append(uhrig(k) - sum(spacing))
spacing.append(1 - sum(spacing))
pm = PassManager(
[
ALAPScheduleAnalysis(self.durations),
PadDynamicalDecoupling(self.durations, dd_sequence, qubits=[0], spacing=spacing),
]
)
ghz4_dd = pm.run(self.ghz4)
expected = self.ghz4.copy()
expected = expected.compose(Delay(50), [1], front=True)
expected = expected.compose(Delay(750), [2], front=True)
expected = expected.compose(Delay(950), [3], front=True)
expected = expected.compose(Delay(3), [0])
expected = expected.compose(XGate(), [0])
expected = expected.compose(Delay(8), [0])
expected = expected.compose(XGate(), [0])
expected = expected.compose(Delay(13), [0])
expected = expected.compose(XGate(), [0])
expected = expected.compose(Delay(16), [0])
expected = expected.compose(XGate(), [0])
expected = expected.compose(Delay(20), [0])
expected = expected.compose(XGate(), [0])
expected = expected.compose(Delay(16), [0])
expected = expected.compose(XGate(), [0])
expected = expected.compose(Delay(13), [0])
expected = expected.compose(XGate(), [0])
expected = expected.compose(Delay(8), [0])
expected = expected.compose(XGate(), [0])
expected = expected.compose(Delay(3), [0])
expected = expected.compose(Delay(300), [1])
self.assertEqual(ghz4_dd, expected)
def test_asymmetric_xy4_in_t2(self):
"""Test insertion of XY4 sequence with unbalanced spacing.
global phase: π
┌───┐┌───┐┌────────────────┐┌───┐┌────────────────┐┌───┐┌────────────────┐»
q_0: ┤ H ├┤ X ├┤ Delay(450[dt]) ├┤ Y ├┤ Delay(450[dt]) ├┤ X ├┤ Delay(450[dt]) ├»
└───┘└───┘└────────────────┘└───┘└────────────────┘└───┘└────────────────┘»
« ┌───┐┌────────────────┐┌───┐
«q_0: ┤ Y ├┤ Delay(450[dt]) ├┤ H ├
« └───┘└────────────────┘└───┘
"""
dd_sequence = [XGate(), YGate()] * 2
spacing = [0] + [1 / 4] * 4
pm = PassManager(
[
ALAPScheduleAnalysis(self.durations),
PadDynamicalDecoupling(self.durations, dd_sequence, spacing=spacing),
]
)
t2 = QuantumCircuit(1)
t2.h(0)
t2.delay(2000, 0)
t2.h(0)
expected = QuantumCircuit(1)
expected.h(0)
expected.x(0)
expected.delay(450, 0)
expected.y(0)
expected.delay(450, 0)
expected.x(0)
expected.delay(450, 0)
expected.y(0)
expected.delay(450, 0)
expected.h(0)
expected.global_phase = pi
t2_dd = pm.run(t2)
self.assertEqual(t2_dd, expected)
# check global phase is correct
self.assertEqual(Operator(t2), Operator(expected))
def test_dd_after_reset(self):
"""Test skip_reset_qubits option works.
┌─────────────────┐┌───┐┌────────────────┐┌───┐┌─────────────────┐»
q_0: ─|0>─┤ Delay(1000[dt]) ├┤ H ├┤ Delay(190[dt]) ├┤ X ├┤ Delay(1710[dt]) ├»
└─────────────────┘└───┘└────────────────┘└───┘└─────────────────┘»
« ┌───┐┌───┐
«q_0: ┤ X ├┤ H ├
« └───┘└───┘
"""
dd_sequence = [XGate(), XGate()]
spacing = [0.1, 0.9]
pm = PassManager(
[
ALAPScheduleAnalysis(self.durations),
PadDynamicalDecoupling(
self.durations, dd_sequence, spacing=spacing, skip_reset_qubits=True
),
]
)
t2 = QuantumCircuit(1)
t2.reset(0)
t2.delay(1000)
t2.h(0)
t2.delay(2000, 0)
t2.h(0)
expected = QuantumCircuit(1)
expected.reset(0)
expected.delay(1000)
expected.h(0)
expected.delay(190, 0)
expected.x(0)
expected.delay(1710, 0)
expected.x(0)
expected.h(0)
t2_dd = pm.run(t2)
self.assertEqual(t2_dd, expected)
def test_insert_dd_bad_sequence(self):
"""Test DD raises when non-identity sequence is inserted."""
dd_sequence = [XGate(), YGate()]
pm = PassManager(
[
ALAPScheduleAnalysis(self.durations),
PadDynamicalDecoupling(self.durations, dd_sequence),
]
)
with self.assertRaises(TranspilerError):
pm.run(self.ghz4)
@data(0.5, 1.5)
def test_dd_with_calibrations_with_parameters(self, param_value):
"""Check that calibrations in a circuit with parameters work fine."""
circ = QuantumCircuit(2)
circ.x(0)
circ.cx(0, 1)
circ.rx(param_value, 1)
rx_duration = int(param_value * 1000)
with pulse.build() as rx:
pulse.play(pulse.Gaussian(rx_duration, 0.1, rx_duration // 4), pulse.DriveChannel(1))
circ.add_calibration("rx", (1,), rx, params=[param_value])
durations = InstructionDurations([("x", None, 100), ("cx", None, 300)])
dd_sequence = [XGate(), XGate()]
pm = PassManager(
[ALAPScheduleAnalysis(durations), PadDynamicalDecoupling(durations, dd_sequence)]
)
self.assertEqual(pm.run(circ).duration, rx_duration + 100 + 300)
def test_insert_dd_ghz_xy4_with_alignment(self):
"""Test DD with pulse alignment constraints.
┌───┐ ┌───────────────┐ ┌───┐ ┌───────────────┐»
q_0: ──────┤ H ├─────────■──┤ Delay(40[dt]) ├──────┤ X ├──────┤ Delay(70[dt]) ├»
┌─────┴───┴─────┐ ┌─┴─┐└───────────────┘┌─────┴───┴─────┐└─────┬───┬─────┘»
q_1: ┤ Delay(50[dt]) ├─┤ X ├────────■────────┤ Delay(20[dt]) ├──────┤ X ├──────»
├───────────────┴┐└───┘ ┌─┴─┐ └───────────────┘ └───┘ »
q_2: ┤ Delay(750[dt]) ├───────────┤ X ├──────────────■─────────────────────────»
├────────────────┤ └───┘ ┌─┴─┐ »
q_3: ┤ Delay(950[dt]) ├────────────────────────────┤ X ├───────────────────────»
└────────────────┘ └───┘ »
« ┌───┐ ┌───────────────┐ ┌───┐ ┌───────────────┐»
«q_0: ──────┤ Y ├──────┤ Delay(70[dt]) ├──────┤ X ├──────┤ Delay(70[dt]) ├»
« ┌─────┴───┴─────┐└─────┬───┬─────┘┌─────┴───┴─────┐└─────┬───┬─────┘»
«q_1: ┤ Delay(20[dt]) ├──────┤ Y ├──────┤ Delay(20[dt]) ├──────┤ X ├──────»
« └───────────────┘ └───┘ └───────────────┘ └───┘ »
«q_2: ────────────────────────────────────────────────────────────────────»
« »
«q_3: ────────────────────────────────────────────────────────────────────»
« »
« ┌───┐ ┌───────────────┐
«q_0: ──────┤ Y ├──────┤ Delay(50[dt]) ├─────────────────
« ┌─────┴───┴─────┐└─────┬───┬─────┘┌───────────────┐
«q_1: ┤ Delay(20[dt]) ├──────┤ Y ├──────┤ Delay(20[dt]) ├
« └───────────────┘ └───┘ └───────────────┘
«q_2: ───────────────────────────────────────────────────
«
«q_3: ───────────────────────────────────────────────────
«
"""
dd_sequence = [XGate(), YGate(), XGate(), YGate()]
pm = PassManager(
[
ALAPScheduleAnalysis(self.durations),
PadDynamicalDecoupling(
self.durations,
dd_sequence,
pulse_alignment=10,
extra_slack_distribution="edges",
),
]
)
ghz4_dd = pm.run(self.ghz4)
expected = self.ghz4.copy()
expected = expected.compose(Delay(50), [1], front=True)
expected = expected.compose(Delay(750), [2], front=True)
expected = expected.compose(Delay(950), [3], front=True)
expected = expected.compose(Delay(40), [0])
expected = expected.compose(XGate(), [0])
expected = expected.compose(Delay(70), [0])
expected = expected.compose(YGate(), [0])
expected = expected.compose(Delay(70), [0])
expected = expected.compose(XGate(), [0])
expected = expected.compose(Delay(70), [0])
expected = expected.compose(YGate(), [0])
expected = expected.compose(Delay(50), [0])
expected = expected.compose(Delay(20), [1])
expected = expected.compose(XGate(), [1])
expected = expected.compose(Delay(20), [1])
expected = expected.compose(YGate(), [1])
expected = expected.compose(Delay(20), [1])
expected = expected.compose(XGate(), [1])
expected = expected.compose(Delay(20), [1])
expected = expected.compose(YGate(), [1])
expected = expected.compose(Delay(20), [1])
self.assertEqual(ghz4_dd, expected)
def test_dd_can_sequentially_called(self):
"""Test if sequentially called DD pass can output the same circuit.
This test verifies:
- if global phase is properly propagated from the previous padding node.
- if node_start_time property is properly updated for new dag circuit.
"""
dd_sequence = [XGate(), YGate(), XGate(), YGate()]
pm1 = PassManager(
[
ALAPScheduleAnalysis(self.durations),
PadDynamicalDecoupling(self.durations, dd_sequence, qubits=[0]),
PadDynamicalDecoupling(self.durations, dd_sequence, qubits=[1]),
]
)
circ1 = pm1.run(self.ghz4)
pm2 = PassManager(
[
ALAPScheduleAnalysis(self.durations),
PadDynamicalDecoupling(self.durations, dd_sequence, qubits=[0, 1]),
]
)
circ2 = pm2.run(self.ghz4)
self.assertEqual(circ1, circ2)
def test_respect_target_instruction_constraints(self):
"""Test if DD pass does not pad delays for qubits that do not support delay instructions
and does not insert DD gates for qubits that do not support necessary gates.
See: https://github.com/Qiskit/qiskit-terra/issues/9993
"""
qc = QuantumCircuit(3)
qc.cx(0, 1)
qc.cx(1, 2)
target = Target(dt=1)
# Y is partially supported (not supported on qubit 2)
target.add_instruction(
XGate(), {(q,): InstructionProperties(duration=100) for q in range(2)}
)
target.add_instruction(
CXGate(),
{
(0, 1): InstructionProperties(duration=1000),
(1, 2): InstructionProperties(duration=1000),
},
)
# delays are not supported
# No DD instructions nor delays are padded due to no delay support in the target
pm_xx = PassManager(
[
ALAPScheduleAnalysis(target=target),
PadDynamicalDecoupling(dd_sequence=[XGate(), XGate()], target=target),
]
)
scheduled = pm_xx.run(qc)
self.assertEqual(qc, scheduled)
# Fails since Y is not supported in the target
with self.assertRaises(TranspilerError):
PassManager(
[
ALAPScheduleAnalysis(target=target),
PadDynamicalDecoupling(
dd_sequence=[XGate(), YGate(), XGate(), YGate()], target=target
),
]
)
# Add delay support to the target
target.add_instruction(Delay(Parameter("t")), {(q,): None for q in range(3)})
# No error but no DD on qubit 2 (just delay is padded) since X is not supported on it
scheduled = pm_xx.run(qc)
expected = QuantumCircuit(3)
expected.delay(1000, [2])
expected.cx(0, 1)
expected.cx(1, 2)
expected.delay(200, [0])
expected.x([0])
expected.delay(400, [0])
expected.x([0])
expected.delay(200, [0])
self.assertEqual(expected, scheduled)
def test_paramaterized_global_phase(self):
"""Test paramaterized global phase in DD circuit.
See:https://github.com/Qiskit/qiskit-terra/issues/10569
"""
dd_sequence = [XGate(), YGate()] * 2
qc = QuantumCircuit(1, 1)
qc.h(0)
qc.delay(1700, 0)
qc.y(0)
qc.global_phase = Parameter("a")
pm = PassManager(
[
ALAPScheduleAnalysis(self.durations),
PadDynamicalDecoupling(self.durations, dd_sequence),
]
)
self.assertEqual(qc.global_phase + np.pi, pm.run(qc).global_phase)
def test_misalignment_at_boundaries(self):
"""Test the correct error message is raised for misalignments at In/Out nodes."""
# a circuit where the previous node is DAGInNode, and the next DAGOutNode
circuit = QuantumCircuit(1)
circuit.delay(101)
dd_sequence = [XGate(), XGate()]
pm = PassManager(
[
ALAPScheduleAnalysis(self.durations),
PadDynamicalDecoupling(self.durations, dd_sequence, pulse_alignment=2),
]
)
with self.assertRaises(TranspilerError):
_ = pm.run(circuit)
if __name__ == "__main__":
unittest.main()
| qiskit/test/python/transpiler/test_dynamical_decoupling.py/0 | {
"file_path": "qiskit/test/python/transpiler/test_dynamical_decoupling.py",
"repo_id": "qiskit",
"token_count": 25576
} | 332 |
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test KAK over optimization"""
import unittest
import numpy as np
from qiskit import QuantumCircuit, QuantumRegister, transpile
from qiskit.circuit.library import CU1Gate
from test import QiskitTestCase # pylint: disable=wrong-import-order
class TestKAKOverOptim(QiskitTestCase):
"""Tests to verify that KAK decomposition
does not over optimize.
"""
def test_cz_optimization(self):
"""Test that KAK does not run on a cz gate"""
qr = QuantumRegister(2)
qc = QuantumCircuit(qr)
qc.cz(qr[0], qr[1])
cz_circ = transpile(
qc,
None,
coupling_map=[[0, 1], [1, 0]],
basis_gates=["u1", "u2", "u3", "id", "cx"],
optimization_level=3,
)
ops = cz_circ.count_ops()
self.assertEqual(ops["u2"], 2)
self.assertEqual(ops["cx"], 1)
self.assertFalse("u3" in ops.keys())
def test_cu1_optimization(self):
"""Test that KAK does run on a cu1 gate and
reduces the cx count from two to one.
"""
qr = QuantumRegister(2)
qc = QuantumCircuit(qr)
qc.append(CU1Gate(np.pi), [qr[0], qr[1]])
cu1_circ = transpile(
qc,
None,
coupling_map=[[0, 1], [1, 0]],
basis_gates=["u1", "u2", "u3", "id", "cx"],
optimization_level=3,
)
ops = cu1_circ.count_ops()
self.assertEqual(ops["cx"], 1)
if __name__ == "__main__":
unittest.main()
| qiskit/test/python/transpiler/test_kak_over_optimization.py/0 | {
"file_path": "qiskit/test/python/transpiler/test_kak_over_optimization.py",
"repo_id": "qiskit",
"token_count": 883
} | 333 |
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test calling passes (passmanager-less)"""
from qiskit import QuantumRegister, QuantumCircuit
from qiskit.transpiler import PropertySet
from ._dummy_passes import PassD_TP_NR_NP, PassE_AP_NR_NP, PassN_AP_NR_NP
from test import QiskitTestCase # pylint: disable=wrong-import-order
class TestPassCall(QiskitTestCase):
"""Test calling passes (passmanager-less)."""
def assertMessageLog(self, context, messages):
"""Checks the log messages"""
self.assertEqual([record.message for record in context.records], messages)
def test_transformation_pass(self):
"""Call a transformation pass without a scheduler"""
qr = QuantumRegister(1, "qr")
circuit = QuantumCircuit(qr, name="MyCircuit")
pass_d = PassD_TP_NR_NP(argument1=[1, 2])
with self.assertLogs("LocalLogger", level="INFO") as cm:
result = pass_d(circuit)
self.assertMessageLog(cm, ["run transformation pass PassD_TP_NR_NP", "argument [1, 2]"])
self.assertEqual(circuit, result)
def test_analysis_pass_dict(self):
"""Call an analysis pass without a scheduler (property_set dict)"""
qr = QuantumRegister(1, "qr")
circuit = QuantumCircuit(qr, name="MyCircuit")
property_set = {"another_property": "another_value"}
pass_e = PassE_AP_NR_NP("value")
with self.assertLogs("LocalLogger", level="INFO") as cm:
result = pass_e(circuit, property_set)
self.assertMessageLog(cm, ["run analysis pass PassE_AP_NR_NP", "set property as value"])
self.assertEqual(property_set, {"another_property": "another_value", "property": "value"})
self.assertIsInstance(property_set, dict)
self.assertEqual(circuit, result)
def test_analysis_pass_property_set(self):
"""Call an analysis pass without a scheduler (PropertySet dict)"""
qr = QuantumRegister(1, "qr")
circuit = QuantumCircuit(qr, name="MyCircuit")
property_set = PropertySet({"another_property": "another_value"})
pass_e = PassE_AP_NR_NP("value")
with self.assertLogs("LocalLogger", level="INFO") as cm:
result = pass_e(circuit, property_set)
self.assertMessageLog(cm, ["run analysis pass PassE_AP_NR_NP", "set property as value"])
self.assertEqual(
property_set, PropertySet({"another_property": "another_value", "property": "value"})
)
self.assertIsInstance(property_set, PropertySet)
self.assertEqual(circuit, result)
def test_analysis_pass_remove_property(self):
"""Call an analysis pass that removes a property without a scheduler"""
qr = QuantumRegister(1, "qr")
circuit = QuantumCircuit(qr, name="MyCircuit")
property_set = {"to remove": "value to remove", "to none": "value to none"}
pass_e = PassN_AP_NR_NP("to remove", "to none")
with self.assertLogs("LocalLogger", level="INFO") as cm:
result = pass_e(circuit, property_set)
self.assertMessageLog(
cm,
[
"run analysis pass PassN_AP_NR_NP",
"property to remove deleted",
"property to none noned",
],
)
self.assertEqual(property_set, PropertySet({"to none": None}))
self.assertIsInstance(property_set, dict)
self.assertEqual(circuit, result)
| qiskit/test/python/transpiler/test_pass_call.py/0 | {
"file_path": "qiskit/test/python/transpiler/test_pass_call.py",
"repo_id": "qiskit",
"token_count": 1518
} | 334 |
# This code is part of Qiskit.
#
# (C) Copyright IBM 2023.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test the SabrePreLayout pass"""
from qiskit.circuit import QuantumCircuit
from qiskit.transpiler import TranspilerError, CouplingMap, PassManager
from qiskit.transpiler.passes.layout.sabre_pre_layout import SabrePreLayout
from qiskit.converters import circuit_to_dag
from test import QiskitTestCase # pylint: disable=wrong-import-order
class TestSabrePreLayout(QiskitTestCase):
"""Tests the SabrePreLayout pass."""
def test_no_constraints(self):
"""Test we raise at runtime if no target or coupling graph are provided."""
qc = QuantumCircuit(2)
empty_pass = SabrePreLayout(coupling_map=None)
with self.assertRaises(TranspilerError):
empty_pass.run(circuit_to_dag(qc))
def test_starting_layout_created(self):
"""Test the case that no perfect layout exists and SabrePreLayout can find a
starting layout."""
qc = QuantumCircuit(4)
qc.cx(0, 1)
qc.cx(1, 2)
qc.cx(2, 3)
qc.cx(3, 0)
coupling_map = CouplingMap.from_ring(5)
pm = PassManager([SabrePreLayout(coupling_map=coupling_map)])
pm.run(qc)
# SabrePreLayout should discover a single layout.
self.assertIn("sabre_starting_layouts", pm.property_set)
layouts = pm.property_set["sabre_starting_layouts"]
self.assertEqual(len(layouts), 1)
layout = layouts[0]
self.assertEqual([layout[q] for q in qc.qubits], [2, 1, 0, 4])
def test_perfect_layout_exists(self):
"""Test the case that a perfect layout exists."""
qc = QuantumCircuit(4)
qc.cx(0, 1)
qc.cx(1, 2)
qc.cx(2, 3)
qc.cx(3, 0)
coupling_map = CouplingMap.from_ring(4)
pm = PassManager([SabrePreLayout(coupling_map=coupling_map)])
pm.run(qc)
# SabrePreLayout should not create starting layouts when a perfect layout exists.
self.assertNotIn("sabre_starting_layouts", pm.property_set)
def test_max_distance(self):
"""Test the ``max_distance`` option to SabrePreLayout."""
qc = QuantumCircuit(6)
qc.cx(0, 1)
qc.cx(0, 2)
qc.cx(0, 3)
qc.cx(0, 4)
qc.cx(0, 5)
coupling_map = CouplingMap.from_ring(6)
# It is not possible to map a star-graph with 5 leaves into a ring with 6 nodes,
# so that all nodes are distance-2 apart.
pm = PassManager([SabrePreLayout(coupling_map=coupling_map, max_distance=2)])
pm.run(qc)
self.assertNotIn("sabre_starting_layouts", pm.property_set)
# But possible with distance-3.
pm = PassManager([SabrePreLayout(coupling_map=coupling_map, max_distance=3)])
pm.run(qc)
self.assertIn("sabre_starting_layouts", pm.property_set)
def test_call_limit_vf2(self):
"""Test the ``call_limit_vf2`` option to SabrePreLayout."""
qc = QuantumCircuit(4)
qc.cx(0, 1)
qc.cx(1, 2)
qc.cx(2, 3)
qc.cx(3, 0)
coupling_map = CouplingMap.from_ring(5)
pm = PassManager(
[SabrePreLayout(coupling_map=coupling_map, call_limit_vf2=1, max_distance=3)]
)
pm.run(qc)
self.assertNotIn("sabre_starting_layouts", pm.property_set)
| qiskit/test/python/transpiler/test_sabre_pre_layout.py/0 | {
"file_path": "qiskit/test/python/transpiler/test_sabre_pre_layout.py",
"repo_id": "qiskit",
"token_count": 1648
} | 335 |
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
# Copyright 2019 Andrew M. Childs, Eddie Schoute, Cem M. Unsal
#
# 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.
"""Test cases for the permutation.complete package"""
import itertools
import rustworkx as rx
from numpy import random
from qiskit.transpiler.passes.routing.algorithms import ApproximateTokenSwapper
from qiskit.transpiler.passes.routing.algorithms import util
from test import QiskitTestCase # pylint: disable=wrong-import-order
class TestGeneral(QiskitTestCase):
"""The test cases"""
def setUp(self) -> None:
"""Set up test cases."""
super().setUp()
random.seed(0)
def test_simple(self) -> None:
"""Test a simple permutation on a path graph of size 4."""
graph = rx.generators.path_graph(4)
permutation = {0: 0, 1: 3, 3: 1, 2: 2}
swapper = ApproximateTokenSwapper(graph) # type: ApproximateTokenSwapper[int]
out = list(swapper.map(permutation))
self.assertEqual(3, len(out))
util.swap_permutation([out], permutation)
self.assertEqual({i: i for i in range(4)}, permutation)
def test_small(self) -> None:
"""Test an inverting permutation on a small path graph of size 8"""
graph = rx.generators.path_graph(8)
permutation = {i: 7 - i for i in range(8)}
swapper = ApproximateTokenSwapper(graph) # type: ApproximateTokenSwapper[int]
out = list(swapper.map(permutation))
util.swap_permutation([out], permutation)
self.assertEqual({i: i for i in range(8)}, permutation)
def test_bug1(self) -> None:
"""Tests for a bug that occurred in happy swap chains of length >2."""
graph = rx.PyGraph()
graph.extend_from_edge_list(
[(0, 1), (0, 2), (0, 3), (0, 4), (1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4), (3, 6)]
)
permutation = {0: 4, 1: 0, 2: 3, 3: 6, 4: 2, 6: 1}
swapper = ApproximateTokenSwapper(graph) # type: ApproximateTokenSwapper[int]
out = list(swapper.map(permutation))
util.swap_permutation([out], permutation)
self.assertEqual({i: i for i in permutation}, permutation)
def test_partial_simple(self) -> None:
"""Test a partial mapping on a small graph."""
graph = rx.generators.path_graph(4)
mapping = {0: 3}
swapper = ApproximateTokenSwapper(graph) # type: ApproximateTokenSwapper[int]
out = list(swapper.map(mapping))
self.assertEqual(3, len(out))
util.swap_permutation([out], mapping, allow_missing_keys=True)
self.assertEqual({3: 3}, mapping)
def test_partial_small(self) -> None:
"""Test an partial inverting permutation on a small path graph of size 5"""
graph = rx.generators.path_graph(4)
permutation = {i: 3 - i for i in range(2)}
swapper = ApproximateTokenSwapper(graph) # type: ApproximateTokenSwapper[int]
out = list(swapper.map(permutation))
self.assertEqual(5, len(out))
util.swap_permutation([out], permutation, allow_missing_keys=True)
self.assertEqual({i: i for i in permutation.values()}, permutation)
def test_large_partial_random(self) -> None:
"""Test a random (partial) mapping on a large randomly generated graph"""
size = 100
# Note that graph may have "gaps" in the node counts, i.e. the numbering is noncontiguous.
graph = rx.undirected_gnm_random_graph(size, size**2 // 10)
for i in graph.node_indexes():
try:
graph.remove_edge(i, i) # Remove self-loops.
except rx.NoEdgeBetweenNodes:
continue
# Make sure the graph is connected by adding C_n
graph.add_edges_from_no_data([(i, i + 1) for i in range(len(graph) - 1)])
swapper = ApproximateTokenSwapper(graph) # type: ApproximateTokenSwapper[int]
# Generate a randomized permutation.
rand_perm = random.permutation(graph.nodes())
permutation = dict(zip(graph.nodes(), rand_perm))
mapping = dict(itertools.islice(permutation.items(), 0, size, 2)) # Drop every 2nd element.
out = list(swapper.map(mapping, trials=40))
util.swap_permutation([out], mapping, allow_missing_keys=True)
self.assertEqual({i: i for i in mapping.values()}, mapping)
| qiskit/test/python/transpiler/test_token_swapper.py/0 | {
"file_path": "qiskit/test/python/transpiler/test_token_swapper.py",
"repo_id": "qiskit",
"token_count": 2064
} | 336 |
# This code is part of Qiskit.
#
# (C) Copyright IBM 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test for unit conversion functions."""
from ddt import ddt, data
from qiskit.utils import apply_prefix, detach_prefix
from test import QiskitTestCase # pylint: disable=wrong-import-order
@ddt
class TestUnitConversion(QiskitTestCase):
"""Test the unit conversion utilities."""
def test_apply_prefix(self):
"""Test applying prefix to value."""
ref_values = [
([1.0, "THz"], 1e12),
([1.0, "GHz"], 1e9),
([1.0, "MHz"], 1e6),
([1.0, "kHz"], 1e3),
([1.0, "mHz"], 1e-3),
([1.0, "µHz"], 1e-6),
([1.0, "uHz"], 1e-6),
([1.0, "nHz"], 1e-9),
([1.0, "pHz"], 1e-12),
]
for args, ref_ret in ref_values:
self.assertEqual(apply_prefix(*args), ref_ret)
def test_not_convert_meter(self):
"""Test not apply prefix to meter."""
self.assertEqual(apply_prefix(1.0, "m"), 1.0)
def test_detach_prefix(self):
"""Test detach prefix from the value."""
ref_values = [
(1e12, (1.0, "T")),
(1e11, (100.0, "G")),
(1e10, (10.0, "G")),
(1e9, (1.0, "G")),
(1e8, (100.0, "M")),
(1e7, (10.0, "M")),
(1e6, (1.0, "M")),
(1e5, (100.0, "k")),
(1e4, (10.0, "k")),
(1e3, (1.0, "k")),
(100, (100.0, "")),
(10, (10.0, "")),
(1.0, (1.0, "")),
(0.1, (100.0, "m")),
(0.01, (10.0, "m")),
(1e-3, (1.0, "m")),
(1e-4, (100.0, "µ")),
(1e-5, (10.0, "µ")),
(1e-6, (1.0, "µ")),
(1e-7, (100.0, "n")),
(1e-8, (10.0, "n")),
(1e-9, (1.0, "n")),
(1e-10, (100.0, "p")),
(1e-11, (10.0, "p")),
(1e-12, (1.0, "p")),
]
for arg, ref_rets in ref_values:
self.assertTupleEqual(detach_prefix(arg), ref_rets)
def test_detach_prefix_with_zero(self):
"""Test detach prefix by input zero."""
self.assertTupleEqual(detach_prefix(0.0), (0.0, ""))
def test_detach_prefix_with_negative(self):
"""Test detach prefix by input negative values."""
self.assertTupleEqual(detach_prefix(-1.234e7), (-12.34, "M"))
def test_detach_prefix_with_value_too_large(self):
"""Test detach prefix by input too large value."""
with self.assertRaises(Exception):
self.assertTupleEqual(detach_prefix(1e20), (1e20, ""))
def test_detach_prefix_with_value_too_small(self):
"""Test detach prefix by input too small value."""
with self.assertRaises(Exception):
self.assertTupleEqual(detach_prefix(1e-20), (1e-20, ""))
def test_rounding(self):
"""Test detach prefix with decimal specification."""
ret = detach_prefix(999_999.991)
self.assertTupleEqual(ret, (999.999991, "k"))
ret = detach_prefix(999_999.991, decimal=4)
self.assertTupleEqual(ret, (1.0, "M"))
ret = detach_prefix(999_999.991, decimal=5)
self.assertTupleEqual(ret, (999.99999, "k"))
@data(
-20.791378538739863,
9.242757760406565,
2.7366806276451543,
9.183776167253349,
7.658091886606501,
-12.21553566621071,
8.914055281578145,
1.2518807770035825,
-6.652899195646036,
-4.647159596697976,
)
def test_get_same_value_after_attach_detach(self, value: float):
"""Test if same value can be obtained."""
unit = "Hz"
for prefix in ["P", "T", "G", "k", "m", "µ", "n", "p", "f"]:
scaled_val = apply_prefix(value, prefix + unit)
test_val, ret_prefix = detach_prefix(scaled_val)
self.assertAlmostEqual(test_val, value)
self.assertEqual(prefix, ret_prefix)
def test_get_symbol_mu(self):
"""Test if µ is returned rather than u."""
_, prefix = detach_prefix(3e-6)
self.assertEqual(prefix, "µ")
| qiskit/test/python/utils/test_units.py/0 | {
"file_path": "qiskit/test/python/utils/test_units.py",
"repo_id": "qiskit",
"token_count": 2343
} | 337 |
\documentclass[border=2px]{standalone}
\usepackage[braket, qm]{qcircuit}
\usepackage{graphicx}
\begin{document}
\scalebox{1.0}{
\Qcircuit @C=1.0em @R=0.2em @!R { \\
\nghost{{q}_{0} : } & \lstick{{q}_{0} : } & \gate{\mathrm{X}} & \ctrl{1} & \ctrl{1} & \ctrlo{1} & \ctrl{1} & \qw & \qw\\
\nghost{{q}_{1} : } & \lstick{{q}_{1} : } & \qw & \targ & \ctrl{1} & \targ & \ctrlo{1} & \qw & \qw\\
\nghost{{q}_{2} : } & \lstick{{q}_{2} : } & \qw & \qw & \targ & \ctrlo{-1} & \ctrl{2} & \qw & \qw\\
\nghost{{q}_{3} : } & \lstick{{q}_{3} : } & \qw & \qw & \qw & \ctrl{-1} & \qw & \qw & \qw\\
\nghost{{q}_{4} : } & \lstick{{q}_{4} : } & \qw & \qw & \qw & \qw & \targ & \qw & \qw\\
\\ }}
\end{document} | qiskit/test/python/visualization/references/test_latex_cnot.tex/0 | {
"file_path": "qiskit/test/python/visualization/references/test_latex_cnot.tex",
"repo_id": "qiskit",
"token_count": 406
} | 338 |
\documentclass[border=2px]{standalone}
\usepackage[braket, qm]{qcircuit}
\usepackage{graphicx}
\begin{document}
\scalebox{1.0}{
\Qcircuit @C=1.0em @R=0.2em @!R { \\
\nghost{{0} : } & \lstick{{0} : } & \gate{\mathrm{X}} & \meter & \qw & \qw\\
\nghost{{1} : } & \lstick{{1} : } & \qw & \qw & \qw & \qw\\
\nghost{{0} : } & \lstick{{0} : } & \cw & \cw & \cw & \cw\\
\nghost{{1} : } & \lstick{{1} : } & \cw & \cw \ar @{<=} [-3,0] & \cw & \cw\\
\nghost{{cr}_{0} : } & \lstick{{cr}_{0} : } & \cw & \cw & \cw & \cw\\
\nghost{{cr}_{1} : } & \lstick{{cr}_{1} : } & \cw & \cw & \cw & \cw\\
\nghost{{4} : } & \lstick{{4} : } & \cw & \cw & \cw & \cw\\
\nghost{{cs}_{0} : } & \lstick{{cs}_{0} : } & \cw & \cw & \cw & \cw\\
\nghost{{cs}_{1} : } & \lstick{{cs}_{1} : } & \controlo \cw^(0.0){^{\mathtt{}}} \cwx[-8] & \cw & \cw & \cw\\
\nghost{{cs}_{2} : } & \lstick{{cs}_{2} : } & \cw & \cw & \cw & \cw\\
\\ }}
\end{document} | qiskit/test/python/visualization/references/test_latex_meas_cond_bits_false.tex/0 | {
"file_path": "qiskit/test/python/visualization/references/test_latex_meas_cond_bits_false.tex",
"repo_id": "qiskit",
"token_count": 556
} | 339 |
\documentclass[border=2px]{standalone}
\usepackage[braket, qm]{qcircuit}
\usepackage{graphicx}
\begin{document}
\scalebox{1.0}{
\Qcircuit @C=1.0em @R=0.2em @!R { \\
\nghost{{q}_{0} : } & \lstick{{q}_{0} : } & \gate{\mathrm{R}\,(\mathrm{\frac{3\pi}{4},\frac{3\pi}{8}})} & \multigate{1}{\mathrm{R_{XX}}\,(\mathrm{\frac{\pi}{2}})}_<<<{0} & \multigate{1}{\mathrm{R_{ZX}}\,(\mathrm{\frac{-\pi}{2}})}_<<<{0} & \qw & \qw & \qw & \qw & \qw\\
\nghost{{q}_{1} : } & \lstick{{q}_{1} : } & \gate{\mathrm{R_X}\,(\mathrm{\frac{\pi}{2}})} & \ghost{\mathrm{R_{XX}}\,(\mathrm{\frac{\pi}{2}})}_<<<{1} & \ghost{\mathrm{R_{ZX}}\,(\mathrm{\frac{-\pi}{2}})}_<<<{1} & \qw & \qw & \qw & \qw & \qw\\
\nghost{{q}_{2} : } & \lstick{{q}_{2} : } & \gate{\mathrm{R_Y}\,(\mathrm{\frac{-\pi}{2}})} & \multigate{1}{\mathrm{R_{YY}}\,(\mathrm{\frac{3\pi}{4}})}_<<<{0} & \ctrl{1} & \dstick{\hspace{2.0em}\mathrm{ZZ}\,(\mathrm{\frac{\pi}{2}})} \qw & \qw & \qw & \qw & \qw\\
\nghost{{q}_{3} : } & \lstick{{q}_{3} : } & \gate{\mathrm{R_Z}\,(\mathrm{\frac{3\pi}{4}})} & \ghost{\mathrm{R_{YY}}\,(\mathrm{\frac{3\pi}{4}})}_<<<{1} & \control \qw & \qw & \qw & \qw & \qw & \qw\\
\\ }}
\end{document} | qiskit/test/python/visualization/references/test_latex_r_gates.tex/0 | {
"file_path": "qiskit/test/python/visualization/references/test_latex_r_gates.tex",
"repo_id": "qiskit",
"token_count": 634
} | 340 |
# This code is part of Qiskit.
#
# (C) Copyright IBM 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Tests for pass manager visualization tool."""
import unittest
import os
from qiskit.transpiler import CouplingMap, Layout
from qiskit.transpiler.passmanager import PassManager
from qiskit import QuantumRegister
from qiskit.passmanager.flow_controllers import ConditionalController, DoWhileController
from qiskit.transpiler.passes import GateDirection, BasisTranslator
from qiskit.transpiler.passes import CheckMap
from qiskit.transpiler.passes import SetLayout
from qiskit.transpiler.passes import TrivialLayout
from qiskit.transpiler.passes import BarrierBeforeFinalMeasurements
from qiskit.transpiler.passes import FullAncillaAllocation
from qiskit.transpiler.passes import EnlargeWithAncilla
from qiskit.transpiler.passes import RemoveResetInZeroState
from qiskit.utils import optionals
from qiskit.circuit.library.standard_gates.equivalence_library import (
StandardEquivalenceLibrary as std_eqlib,
)
from .visualization import QiskitVisualizationTestCase, path_to_diagram_reference
@unittest.skipUnless(optionals.HAS_GRAPHVIZ, "Graphviz not installed.")
@unittest.skipUnless(optionals.HAS_PYDOT, "pydot not installed")
@unittest.skipUnless(optionals.HAS_PIL, "Pillow not installed")
class TestPassManagerDrawer(QiskitVisualizationTestCase):
"""Qiskit pass manager drawer tests."""
maxDiff = None
def setUp(self):
super().setUp()
coupling = [[0, 1], [1, 2], [2, 3], [3, 4], [4, 5], [5, 6]]
coupling_map = CouplingMap(couplinglist=coupling)
basis_gates = ["u1", "u3", "u2", "cx"]
qr = QuantumRegister(7, "q")
layout = Layout({qr[i]: i for i in range(coupling_map.size())})
# Create a pass manager with a variety of passes and flow control structures
self.pass_manager = PassManager()
self.pass_manager.append(SetLayout(layout))
self.pass_manager.append(
ConditionalController(TrivialLayout(coupling_map), condition=lambda x: True)
)
self.pass_manager.append(FullAncillaAllocation(coupling_map))
self.pass_manager.append(EnlargeWithAncilla())
self.pass_manager.append(BasisTranslator(std_eqlib, basis_gates))
self.pass_manager.append(CheckMap(coupling_map))
self.pass_manager.append(
DoWhileController(BarrierBeforeFinalMeasurements(), do_while=lambda x: False)
)
self.pass_manager.append(GateDirection(coupling_map))
self.pass_manager.append(RemoveResetInZeroState())
def test_pass_manager_drawer_basic(self):
"""Test to see if the drawer draws a normal pass manager correctly"""
filename = "current_standard.dot"
self.pass_manager.draw(filename=filename, raw=True)
try:
self.assertFilesAreEqual(
filename, path_to_diagram_reference("pass_manager_standard.dot")
)
finally:
os.remove(filename)
def test_pass_manager_drawer_style(self):
"""Test to see if the colours are updated when provided by the user"""
# set colours for some passes, but leave others to take the default values
style = {
SetLayout: "cyan",
CheckMap: "green",
EnlargeWithAncilla: "pink",
RemoveResetInZeroState: "grey",
}
filename = "current_style.dot"
self.pass_manager.draw(filename=filename, style=style, raw=True)
try:
self.assertFilesAreEqual(filename, path_to_diagram_reference("pass_manager_style.dot"))
finally:
os.remove(filename)
if __name__ == "__main__":
unittest.main(verbosity=2)
| qiskit/test/python/visualization/test_pass_manager_drawer.py/0 | {
"file_path": "qiskit/test/python/visualization/test_pass_manager_drawer.py",
"repo_id": "qiskit",
"token_count": 1545
} | 341 |
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Randomized tests of Clifford operator class."""
import unittest
from hypothesis import given, strategies, settings
from qiskit.quantum_info.random import random_clifford
from qiskit.quantum_info import Clifford
class TestClifford(unittest.TestCase):
"""Test random_clifford"""
def assertValidClifford(self, value, num_qubits):
"""Assertion from test/python/quantum_info/operators/test_random.py:
TestRandomClifford:test_valid"""
self.assertIsInstance(value, Clifford)
self.assertEqual(value.num_qubits, num_qubits)
@given(
strategies.integers(min_value=0, max_value=2**32 - 1),
strategies.integers(min_value=1, max_value=211),
)
@settings(deadline=None)
def test_random_clifford_valid(self, seed, num_qubits):
"""Test random_clifford."""
value = random_clifford(num_qubits, seed=seed)
self.assertValidClifford(value, num_qubits=num_qubits)
if __name__ == "__main__":
unittest.main()
| qiskit/test/randomized/test_clifford.py/0 | {
"file_path": "qiskit/test/randomized/test_clifford.py",
"repo_id": "qiskit",
"token_count": 521
} | 342 |
#!/usr/bin/env python3
# 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.
"""Utility script to verify qiskit copyright file headers"""
import argparse
import multiprocessing
import subprocess
import sys
import re
# release notes regex
reno = re.compile(r"releasenotes\/notes")
# exact release note regex
exact_reno = re.compile(r"^releasenotes\/notes")
def discover_files():
"""Find all .py, .pyx, .pxd files in a list of trees"""
cmd = ["git", "ls-tree", "-r", "--name-only", "HEAD"]
res = subprocess.run(cmd, capture_output=True, check=True, encoding="UTF8")
files = res.stdout.split("\n")
return files
def validate_path(file_path):
"""Validate a path in the git tree."""
if reno.search(file_path) and not exact_reno.search(file_path):
return file_path
return None
def _main():
parser = argparse.ArgumentParser(description="Find any stray release notes.")
_args = parser.parse_args()
files = discover_files()
with multiprocessing.Pool() as pool:
res = pool.map(validate_path, files)
failed_files = [x for x in res if x is not None]
if len(failed_files) > 0:
for failed_file in failed_files:
sys.stderr.write(f"{failed_file} is not in the correct location.\n")
sys.exit(1)
sys.exit(0)
if __name__ == "__main__":
_main()
| qiskit/tools/find_stray_release_notes.py/0 | {
"file_path": "qiskit/tools/find_stray_release_notes.py",
"repo_id": "qiskit",
"token_count": 622
} | 343 |
"""Working with parameterized gates in Cirq."""
# Imports
import matplotlib.pyplot as plt
import sympy
import cirq
# Get a qubit and a circuit
qbit = cirq.LineQubit(0)
circ = cirq.Circuit()
# Get a symbol
symbol = sympy.Symbol("t")
# Add a parameterized gate
circ.append(cirq.XPowGate(exponent=symbol)(qbit))
# Measure
circ.append(cirq.measure(qbit, key="z"))
# Display the circuit
print("Circuit:")
print(circ)
# Get a sweep over parameter values
sweep = cirq.Linspace(key=symbol.name, start=0.0, stop=2.0, length=100)
# Execute the circuit for all values in the sweep
sim = cirq.Simulator()
res = sim.run_sweep(circ, sweep, repetitions=1000)
# Plot the measurement outcomes at each value in the sweep
angles = [x[0][1] for x in sweep.param_tuples()]
zeroes = [res[i].histogram(key="z")[0] / 1000 for i in range(len(res))]
plt.plot(angles, zeroes, "--", linewidth=3)
# Plot options and formatting
plt.ylabel("Frequency of 0 Measurements")
plt.xlabel("Exponent of X gate")
plt.grid()
plt.savefig("param-sweep-cirq.pdf", format="pdf")
| quantumcomputingbook/chapter06/cirq/cirq-parameters.py/0 | {
"file_path": "quantumcomputingbook/chapter06/cirq/cirq-parameters.py",
"repo_id": "quantumcomputingbook",
"token_count": 392
} | 344 |
"""Bernstein-Vazirani algorithm in Cirq."""
# Imports
import random
import cirq
def main():
"""Executes the BV algorithm."""
# Number of qubits
qubit_count = 8
# Number of times to sample from the circuit
circuit_sample_count = 3
# Choose qubits to use
input_qubits = [cirq.GridQubit(i, 0) for i in range(qubit_count)]
output_qubit = cirq.GridQubit(qubit_count, 0)
# Pick coefficients for the oracle and create a circuit to query it
secret_bias_bit = random.randint(0, 1)
secret_factor_bits = [random.randint(0, 1) for _ in range(qubit_count)]
oracle = make_oracle(input_qubits,
output_qubit,
secret_factor_bits,
secret_bias_bit)
print('Secret function:\nf(x) = x*<{}> + {} (mod 2)'.format(
', '.join(str(e) for e in secret_factor_bits),
secret_bias_bit))
# Embed the oracle into a special quantum circuit querying it exactly once
circuit = make_bernstein_vazirani_circuit(
input_qubits, output_qubit, oracle)
print('\nCircuit:')
print(circuit)
# Sample from the circuit a couple times
simulator = cirq.Simulator()
result = simulator.run(circuit, repetitions=circuit_sample_count)
frequencies = result.histogram(key='result', fold_func=bitstring)
print('\nSampled results:\n{}'.format(frequencies))
# Check if we actually found the secret value.
most_common_bitstring = frequencies.most_common(1)[0][0]
print('\nMost common matches secret factors:\n{}'.format(
most_common_bitstring == bitstring(secret_factor_bits)))
def make_oracle(input_qubits,
output_qubit,
secret_factor_bits,
secret_bias_bit):
"""Gates implementing the function f(a) = a*factors + bias (mod 2)."""
if secret_bias_bit:
yield cirq.X(output_qubit)
for qubit, bit in zip(input_qubits, secret_factor_bits):
if bit:
yield cirq.CNOT(qubit, output_qubit)
def make_bernstein_vazirani_circuit(input_qubits, output_qubit, oracle):
"""Solves for factors in f(a) = a*factors + bias (mod 2) with one query."""
c = cirq.Circuit()
# Initialize qubits
c.append([
cirq.X(output_qubit),
cirq.H(output_qubit),
cirq.H.on_each(*input_qubits),
])
# Query oracle
c.append(oracle)
# Measure in X basis
c.append([
cirq.H.on_each(*input_qubits),
cirq.measure(*input_qubits, key='result')
])
return c
def bitstring(bits):
"""Creates a bit string out of an iterable of bits."""
return ''.join(str(int(b)) for b in bits)
if __name__ == '__main__':
main()
| quantumcomputingbook/chapter08/cirq/bernstein-vazirani.py/0 | {
"file_path": "quantumcomputingbook/chapter08/cirq/bernstein-vazirani.py",
"repo_id": "quantumcomputingbook",
"token_count": 1172
} | 345 |
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp2.0</TargetFramework>
<PlatformTarget>x64</PlatformTarget>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Quantum.Canon" Version="0.5.1902.2802" />
<PackageReference Include="Microsoft.Quantum.Development.Kit" Version="0.5.1902.2802" />
</ItemGroup>
</Project>
| quantumcomputingbook/korean/chapter06/qdk/Simple.csproj/0 | {
"file_path": "quantumcomputingbook/korean/chapter06/qdk/Simple.csproj",
"repo_id": "quantumcomputingbook",
"token_count": 151
} | 346 |
<jupyter_start><jupyter_text>Textbook Algorithms in CirqIn this notebook we'll run through some Cirq implementations of some of the standard algorithms that one encounters in an introductory quantum computing course. The discussion here is expanded from examples found in the [Cirq examples](https://github.com/quantumlib/Cirq/tree/master/examples) directory. InstructionsGo to File --> Save Copy in Drive to get your own copy to play with.<jupyter_code># install cirq
!pip install cirq==0.5 --quiet<jupyter_output>[K |████████████████████████████████| 716kB 2.7MB/s
[K |████████████████████████████████| 12.8MB 45.0MB/s
[31mERROR: albumentations 0.1.12 has requirement imgaug<0.2.7,>=0.2.5, but you'll have imgaug 0.2.9 which is incompatible.[0m
[?25h<jupyter_text>To verify that Cirq is installed in your environment, try to `import cirq` and print out a diagram of the Bristlecone device.<jupyter_code>import cirq
import numpy as np
import random
print(cirq.google.Bristlecone)<jupyter_output>(0, 5)────(0, 6)
│ │
│ │
(1, 4)───(1, 5)────(1, 6)────(1, 7)
│ │ │ │
│ │ │ │
(2, 3)───(2, 4)───(2, 5)────(2, 6)────(2, 7)───(2, 8)
│ │ │ │ │ │
│ │ │ │ │ │
(3, 2)───(3, 3)───(3, 4)───(3, 5)────(3, 6)────(3, 7)───(3, 8)───(3, 9)
│ │ │ │ │ │ │ │
│ │ │ │ │ │ │ │
(4, 1)───(4, 2)───(4, 3)───(4, 4)───(4, 5)────(4, 6)────(4, 7)───(4, 8)───(4, 9)───(4, 10)
│ │ [...]<jupyter_text>Quantum Teleportation Quantum Teleportation is a process by which a quantum state can be transmittedby sending only two classical bits of information. This is accomplished bypre-sharing an entangled state between the sender (Alice) and the receiver(Bob). This entangled state allows the receiver (Bob) of the two classicalbits of information to possess a qubit with the same state as the one held bythe sender (Alice).In the following example output, qubit 0 (the Message) is set to a random stateby applying X and Y gates. By sending two classical bits of information afterqubit 0 (the Message) and qubit 1 (Alice's entangled qubit) are measured, thefinal state of qubit 2 (Bob's entangled qubit) will be identical to theoriginal random state of qubit 0 (the Message). This is only possible giventhat an entangled state is pre-shared between Alice and Bob.=== REFERENCES ===https://en.wikipedia.org/wiki/Quantum_teleportationhttps://journals.aps.org/prl/abstract/10.1103/PhysRevLett.70.1895<jupyter_code>def make_quantum_teleportation_circuit(gate):
circuit = cirq.Circuit()
msg, alice, bob = cirq.LineQubit.range(3)
# Creates Bell state to be shared between Alice and Bob
circuit.append([cirq.H(alice), cirq.CNOT(alice, bob)])
# Creates a random state for the Message
circuit.append(gate(msg))
# Bell measurement of the Message and Alice's entangled qubit
circuit.append([cirq.CNOT(msg, alice), cirq.H(msg)])
circuit.append(cirq.measure(msg, alice))
# Uses the two classical bits from the Bell measurement to recover the
# original quantum Message on Bob's entangled qubit
circuit.append([cirq.CNOT(alice, bob), cirq.CZ(msg, bob)])
return circuit
gate = cirq.SingleQubitMatrixGate(cirq.testing.random_unitary(2))
circuit = make_quantum_teleportation_circuit(gate)
print("Circuit:")
print(circuit)
sim = cirq.Simulator()
# Create qubits.
q0 = cirq.LineQubit
# Produces the message using random unitary
message = sim.simulate(cirq.Circuit.from_ops(gate(q0)))
print("Bloch Vector of Message After Random Unitary:")
# Prints the Bloch vector of the Message after the random gate
b0X, b0Y, b0Z = cirq.bloch_vector_from_state_vector(
message.final_state, 0)
print("x: ", np.around(b0X, 4),
"y: ", np.around(b0Y, 4),
"z: ", np.around(b0Z, 4))
# Records the final state of the simulation
final_results = sim.simulate(circuit)
print("Bloch Sphere of Qubit 2 at Final State:")
# Prints the Bloch Sphere of Bob's entangled qubit at the final state
b2X, b2Y, b2Z = cirq.bloch_vector_from_state_vector(
final_results.final_state, 2)
print("x: ", np.around(b2X, 4),
"y: ", np.around(b2Y, 4),
"z: ", np.around(b2Z, 4))<jupyter_output>Circuit:
┌ ┐
0: ───│0.23 +0.039j 0.146+0.961j│───────@───H───M───────@───
│0.405+0.884j 0.171-0.159j│ │ │ │
└ ┘ │ │ │
│ │ │
1: ───H─────────────────────────────@───X───────M───@───┼───
│ │ │
2: ─────────────────────────────────X───────────────X───@───
Bloch Vector of Message After Random Unitary:
x: 0.2552 y: 0.3752 z: -0.8911
Bloch Sphere of Qubit 2 at Final State:
x: 0.2552 y: 0.3752 z: -0.8911<jupyter_text>Deutsch's AlgorithmDeutsch's algorithm is one of the simplest demonstrations of quantum parallelismand interference. It takes a black-box oracle implementing a Boolean functionf(x), and determines whether f(0) and f(1) have the same parity using just onequery. This version of Deutsch's algorithm is a simplified and improved versionfrom Nielsen and Chuang's textbook.=== REFERENCE ===https://en.wikipedia.org/wiki/Deutsch–Jozsa_algorithmDeutsch, David. "Quantum theory, the Church-Turing Principle and the universalquantum computer." Proc. R. Soc. Lond. A, 400:97, 1985.<jupyter_code>def make_oracle(q0, q1, secret_function):
""" Gates implementing the secret function f(x)."""
# coverage: ignore
if secret_function[0]:
yield [cirq.CNOT(q0, q1), cirq.X(q1)]
if secret_function[1]:
yield cirq.CNOT(q0, q1)
def make_deutsch_circuit(q0, q1, oracle):
c = cirq.Circuit()
# Initialize qubits.
c.append([cirq.X(q1), cirq.H(q1), cirq.H(q0)])
# Query oracle.
c.append(oracle)
# Measure in X basis.
c.append([cirq.H(q0), cirq.measure(q0, key='result')])
return c
# Choose qubits to use.
q0, q1 = cirq.LineQubit.range(2)
# Pick a secret 2-bit function and create a circuit to query the oracle.
secret_function = [random.randint(0,1) for _ in range(2)]
oracle = make_oracle(q0, q1, secret_function)
print('Secret function:\nf(x) = <{}>'.format(
', '.join(str(e) for e in secret_function)))
# Embed the oracle into a quantum circuit querying it exactly once.
circuit = make_deutsch_circuit(q0, q1, oracle)
print('Circuit:')
print(circuit)
# Simulate the circuit.
simulator = cirq.Simulator()
result = simulator.run(circuit)
print('Result of f(0)⊕f(1):')
print(result)<jupyter_output>Secret function:
f(x) = <0, 0>
Circuit:
0: ───H───H───M('result')───
1: ───X───H─────────────────
Result of f(0)⊕f(1):
result=0<jupyter_text>Quantum Fourier Transform and Phase EstimationThis section provides an overview of the quantum Fourier transform and its use in the Phase Estimation algorithm in Cirq. Quantum Fourier Transform: OverviewWe'll start out by reminding ourselves what the [quantum Fourier transform](https://en.wikipedia.org/wiki/Quantum_Fourier_transform) does, and how it should be constructed. Suppose we have $n$ qubits in the state $|x\rangle$, where $x$ is an integer in the range $0$ to $2^{n-1}$. The quantum Fourier transform (QFT) performs the following operation:$$\text{QFT}|x\rangle = \frac{1}{2^{n/2}} \sum_{y=0}^{2^n-1} e^{2\pi i y x/2^n} |y\rangle.$$When $x=0$, this is the same as the action of $H^{\otimes n}$ (this is an important sanity check). Though it may not be obvious at first glance, the QFT is actually a unitary transformation. As a matrix, the QFT is given by$$\text{QFT} = \begin{bmatrix}1 & 1 & 1& \cdots &1 \\1 & \omega & \omega^2& \cdots &\omega^{2^n-1} \\1 & \omega^2 & \omega^4& \cdots &\omega^{2(2^n-1)}\\\vdots &\vdots &\vdots &\ddots &\vdots \\1 &\omega^{2^n-1} &\omega^{2(2^n-1)} &\cdots &\omega^{(2^n-1)(2^n-1)},\end{bmatrix}$$where $\omega = e^{2\pi i /2^n}$. If you believe that the QFT is unitary, then you'll also notice from the matrix form that its inverse is given by a similar expression but with complex-conjugated coefficients:$$\text{QFT}^{-1}|x\rangle = \frac{1}{2^{n/2}} \sum_{y=0}^{2^n-1} e^{-2\pi i y x/2^n} |y\rangle.$$ The construction of the QFT as a circuit follows a simple recursive form, though fully justifying it will take us too far from the main goal of this notebook. We really only need to know what the circuit looks like, and for that we can look at this picture from the Wikipedia article:> We just need to understand the notation a little bit. $x_j$ on the left-hand side represents one of the binary digits of the input $x$. $x_1$ is the most significant bit and $x_n$ the least significant bit:$$x = \sum_{j=0}^{n-1} x_{j+1}2^j.$$$H$ is the Hadamard gate, as usual. The Controlled-$R_j$ gates are phase gates similar to the Controlled-$Z$ gate. In fact, for us it will be useful to just think of them as fractional powers of Controlled-$Z$ gates:$$CR_j = CZ^{\large 1/2^{j-1}}$$Finally, on the far right we have the output representing the bts of $y$. The only difference between the left and right side is that the output bits are in a different order: the most significant bit of $y$ is on the bottom and the least significant bit is on the top. Quantum Fourier Transform as a Circuit Let's define a generator which produces the QFT circuit. It should accept a list of qubits as input and `yield`s the gates to construct the QFT in the right order. A useful observation is that the the QFT circuit "repeats" smaller versions of itself as you move from left to right across the diagram.<jupyter_code>def make_qft(qubits):
"""Generator for the QFT on an arbitrary number of qubits. With four qubits
the answer is
---H--@-------@--------@---------------------------------------------
| | |
------@^0.5---+--------+---------H--@-------@------------------------
| | | |
--------------@^0.25---+------------@^0.5---+---------H--@-----------
| | |
-----------------------@^0.125--------------@^0.25-------@^0.5---H---
"""
# YOUR CODE HERE<jupyter_output><empty_output><jupyter_text>Solution<jupyter_code>def make_qft(qubits):
"""Generator for the QFT on an arbitrary number of qubits. With four qubits
the answer is
---H--@-------@--------@---------------------------------------------
| | |
------@^0.5---+--------+---------H--@-------@------------------------
| | | |
--------------@^0.25---+------------@^0.5---+---------H--@-----------
| | |
-----------------------@^0.125--------------@^0.25-------@^0.5---H---
"""
qubits = list(qubits)
while len(qubits) > 0:
q_head = qubits.pop(0)
yield cirq.H(q_head)
for i, qubit in enumerate(qubits):
yield (cirq.CZ**(1/2**(i+1)))(qubit, q_head)
num_qubits = 4
qubits = cirq.LineQubit.range(num_qubits)
qft = cirq.Circuit.from_ops(make_qft(qubits))
print(qft)<jupyter_output>┌───────┐ ┌────────────┐ ┌───────┐
0: ───H───@────────@───────────@───────────────────────────────────────
│ │ │
1: ───────@^0.5────┼─────H─────┼──────@─────────@──────────────────────
│ │ │ │
2: ────────────────@^0.25──────┼──────@^0.5─────┼─────H────@───────────
│ │ │
3: ────────────────────────────@^(1/8)──────────@^0.25─────@^0.5───H───
└───────┘ └────────────┘ └───────┘<jupyter_text>Quantum Fourier Transform as a Gate For later convenience, it will be useful to encapsulate the QFT construction into a single gate. We can inherit from `cirq.Gate` to define a gate which acts on an unspecified number of qubits, and then use the same strategy as for `make_qft` in the `_decompose_` method of the gate. Fill in the following code block to make a QFT gate.<jupyter_code>class QFT(cirq.Gate):
"""Gate for the Quantum Fourier Transformation
"""
def __init__(self, n_qubits):
self.n_qubits = n_qubits
def num_qubits(self):
return self.n_qubits
def _decompose_(self, qubits):
# YOUR CODE HERE
# How should the gate look in ASCII diagrams?
def _circuit_diagram_info_(self, args):
return tuple('QFT{}'.format(i) for i in range(self.n_qubits))<jupyter_output><empty_output><jupyter_text>Solution A copy/paste is all that's required here:<jupyter_code>class QFT(cirq.Gate):
"""Gate for the Quantum Fourier Transformation
"""
def __init__(self, n_qubits):
self.n_qubits = n_qubits
def num_qubits(self):
return self.n_qubits
def _decompose_(self, qubits):
"""Implements the QFT on an arbitrary number of qubits. The circuit
for num_qubits = 4 is given by
---H--@-------@--------@---------------------------------------------
| | |
------@^0.5---+--------+---------H--@-------@------------------------
| | | |
--------------@^0.25---+------------@^0.5---+---------H--@-----------
| | |
-----------------------@^0.125--------------@^0.25-------@^0.5---H---
"""
qubits = list(qubits)
while len(qubits) > 0:
q_head = qubits.pop(0)
yield cirq.H(q_head)
for i, qubit in enumerate(qubits):
yield (cirq.CZ**(1/2**(i+1)))(qubit, q_head)
# How should the gate look in ASCII diagrams?
def _circuit_diagram_info_(self, args):
return tuple('QFT{}'.format(i) for i in range(self.n_qubits))<jupyter_output><empty_output><jupyter_text>Test the Circuit We should confirm that the gate we've defined is actually doing the same thing as the `make_qft` function from before. We can do that with the following test:<jupyter_code>num_qubits = 4
qubits = cirq.LineQubit.range(num_qubits)
circuit = cirq.Circuit.from_ops(QFT(num_qubits).on(*qubits))
print(circuit)
qft_test = cirq.Circuit.from_ops(make_qft(qubits))
print(qft_test)
np.testing.assert_allclose(cirq.unitary(qft_test), cirq.unitary(circuit))<jupyter_output>0: ───QFT0───
│
1: ───QFT1───
│
2: ───QFT2───
│
3: ───QFT3───
┌───────┐ ┌────────────┐ ┌───────┐
0: ───H───@────────@───────────@───────────────────────────────────────
│ │ │
1: ───────@^0.5────┼─────H─────┼──────@─────────@──────────────────────
│ │ │ │
2: ────────────────@^0.25──────┼──────@^0.5─────┼─────H────@───────────
│ │ │
3: ────────────────────────────@^(1/8)──────────@^0.25─────@^0.5───H───
└───────┘ └────────────┘ └───────┘<jupyter_text>Inverse QFTWe also want to implement the inverse QFT, which we'll do with a completely separate gate. Modify the `QFT` gate from above to create a `QFT_inv` gate:<jupyter_code>class QFT_inv(cirq.Gate):
"""Gate for the inverse Quantum Fourier Transformation
"""
# YOUR CODE HERE<jupyter_output><empty_output><jupyter_text>Solution Compared to the `QFT` code above, we just have to add in a few minus signs. You can convince yourself that this is the same as complex-conjugating the associated unitary matrix of the QFT, which gives us the inverse QFT.<jupyter_code>class QFT_inv(cirq.Gate):
"""Gate for the inverse Quantum Fourier Transformation
"""
def __init__(self, n_qubits):
self.n_qubits = n_qubits
def num_qubits(self):
return self.n_qubits
def _decompose_(self, qubits):
"""Implements the inverse QFT on an arbitrary number of qubits. The circuit
for num_qubits = 4 is given by
---H--@-------@--------@---------------------------------------------
| | |
------@^-0.5--+--------+---------H--@-------@------------------------
| | | |
--------------@^-0.25--+------------@^-0.5--+---------H--@-----------
| | |
-----------------------@^-0.125-------------@^-0.25------@^-0.5--H---
"""
qubits = list(qubits)
while len(qubits) > 0:
q_head = qubits.pop(0)
yield cirq.H(q_head)
for i, qubit in enumerate(qubits):
yield (cirq.CZ**(-1/2**(i+1)))(qubit, q_head)
def _circuit_diagram_info_(self, args):
return tuple('QFT{}^-1'.format(i) for i in range(self.n_qubits))<jupyter_output><empty_output><jupyter_text>Is the QFT_inv gate the inverse of the QFT Circuit?We chose not to define the `QFT_inv` as literally the inverse of the `QFT` gate. Why was that? What would you get if you concetenated the `QFT` and `QFT_inv` gates as defined? (Try it!) Can you put together `QFT` and `QFT_inv` in such a way that one undoes the action of the other? This exercise doubles as a test of the `QFT_inv` implementation. Solution The QFT and QFT_inv circuits we have defined are not literal inverses of each other because the both reverse the order of the bits when going from input to output. We can explicitly see this in the following code block:<jupyter_code>num_qubits = 2
qubits = cirq.LineQubit.range(num_qubits)
circuit = cirq.Circuit.from_ops(QFT(num_qubits).on(*qubits),
QFT_inv(num_qubits).on(*qubits))
print(circuit)
cirq.unitary(circuit).round(2)<jupyter_output>0: ───QFT0───QFT0^-1───
│ │
1: ───QFT1───QFT1^-1───<jupyter_text>If `QFT` and `QFT_inv` were really inverses then we would have gotten the identity matrix here. There are a couple of ways to fix this. One is to change the implementations of these two gates in such a way that the outputs are "rightside-up." A different solution is to turn the qubits around in between acting with `QFT` and `QFT_inv`. In other words, we can insert the `QFT_inv` gate "upside-down" as follows:<jupyter_code>num_qubits = 2
qubits = cirq.LineQubit.range(num_qubits)
circuit = cirq.Circuit.from_ops(QFT(num_qubits).on(*qubits),
QFT_inv(num_qubits).on(*qubits[::-1])) # qubit order reversed
print(circuit)
cirq.unitary(circuit)<jupyter_output>0: ───QFT0───QFT1^-1───
│ │
1: ───QFT1───QFT0^-1───<jupyter_text>We find the identity matrix, as desired (up to finite-precision numerical errors). Notice that the `QFT_inv` gate is upside-down relative to the `QFT` gate in the diagram. This is why we included the extra digits in the `wire_symobls`! Phase EstimationAs an application of our quantum Fourier transform circuit, we'll implement the [phase estimation](https://en.wikipedia.org/wiki/Quantum_phase_estimation_algorithm) algorithm. The phase estimation algorithm uses the inverse QFT to give an estimate of the eigenvalue of a unitary operator. The total circuit that we are going to implement is given by > Suppose we have a unitary operator $U$ with eigenvactor $|\psi\rangle$ and eigenvalue $\exp(2\pi i \theta)$. Our objective is to get an $n$-bit approximation to $\theta$. The first step is to construct the state$$|\Phi\rangle = \frac{1}{2^{n/2}}\sum_{y=0}^{2^{n-1}} e^{2\pi i y \theta}|y\rangle.$$This looks very similar to the output of the QFT applied to the state $|2^n\theta\rangle$, except for the fact that $2^n\theta$ may not be an integer. If $2^n\theta$ *were* an integer, then we would apply the inverse QFT and measure the qubits to read off the binary representation of $2^n\theta$. Even if $2^n\theta$ is not an integer, we can still perform the same procedure and the result will be a sequence of bits that, with high probility, gives an $n$-bit approximation to $\theta$. We just have to repeat the procedure a few times to be sure of the answer. Since we've already constructed the inverse QFT, all we really have to do is figure out how to construct the magic state $|\Phi\rangle$. This is accomplished by the first part of the circuit picutred above. We begin by applying $H^{\otimes n}$ to the state $|0\rangle$, creating an equal superposition over all basis states:$$H^{\otimes n} |0\rangle = \frac{1}{2^{n/2}}\sum_{y=0}^{2^n-1}|y\rangle.$$Now we need to insert the correct phase coefficients. This is done by a sequence of Controlled-$U^k$ operations, where the qubits of $y$ are the controls and the $U^k$ operations act on $|\psi \rangle$.Let's try to implement this part of the procedure in Cirq, and then put it together with our `QFT_inv` from above. For the gate $U$ we'll pick the single-qubit operation$$U = Z^{2\theta} = \begin{bmatrix}1 & 0 \\0 & e^{2\pi i \theta }\end{bmatrix}$$for $\theta \in [0,1)$. This is just for simplicity and ease of testing. You are invited to write an implementation that accepts an arbitrary $U$.<jupyter_code>theta = 0.234 # Try your own
n_bits = 3 # Accuracy of the estimate for theta. Try different values.
qubits = cirq.LineQubit.range(n_bits)
u_bit = cirq.NamedQubit('u')
U = cirq.Z**(2*theta)
phase_estimator = cirq.Circuit()
phase_estimator.append(cirq.H.on_each(*qubits))
for i, bit in enumerate(qubits):
phase_estimator.append(cirq.ControlledGate(U).on(bit,u_bit)**(2**(n_bits-1-i)))
print(phase_estimator)<jupyter_output>0: ───H───@──────────────────────────────
│
1: ───H───┼──────────@───────────────────
│ │
2: ───H───┼──────────┼─────────@─────────
│ │ │
u: ───────Z^-0.128───Z^0.936───Z^0.468───<jupyter_text>The next step is to perform the inverse QFT on estimation qubits:<jupyter_code>phase_estimator.append(QFT_inv(n_bits).on(*qubits))
print(phase_estimator)<jupyter_output>0: ───H───@──────────────────────────────QFT0^-1───
│ │
1: ───H───┼──────────@───────────────────QFT1^-1───
│ │ │
2: ───H───┼──────────┼─────────@─────────QFT2^-1───
│ │ │
u: ───────Z^-0.128───Z^0.936───Z^0.468─────────────<jupyter_text>At this point we are almost ready to measure the estimation qubits. But we should also specify an initial state for the `u_bit`. By default it will be the state $|0\rangle$, but the phase for that state is trivial with the operator we chose. Inserting a Pauli $X$ operator at the begining of the circuit changes this to the $|1\rangle$ state, which has the nontrivial $\theta$ phase.<jupyter_code># Add measurements to the end of the circuit
phase_estimator.append(cirq.measure(*qubits, key='m'))
# Add gate to change initial state to |1>
phase_estimator.insert(0,cirq.X(u_bit))
print(phase_estimator)<jupyter_output>0: ───H───@──────────────────────────────QFT0^-1───M('m')───
│ │ │
1: ───H───┼──────────@───────────────────QFT1^-1───M────────
│ │ │ │
2: ───H───┼──────────┼─────────@─────────QFT2^-1───M────────
│ │ │
u: ───X───Z^-0.128───Z^0.936───Z^0.468──────────────────────<jupyter_text>Now we can intstantiate a simulator and make measurements of the estimation qubits. Let the values of these qubits be $a_j$. Then our $n$-bit approximation for $\theta$ is given by$$\theta \approx \sum_{j=0}^n a_j2^{-j}.$$We'll perform this conversion from bit values to $\theta$-values and then print the results:<jupyter_code>sim = cirq.Simulator()
result = sim.run(phase_estimator, repetitions=10)
theta_estimates = np.sum(2**np.arange(n_bits)*result.measurements['m'], axis=1)/2**n_bits
print(theta_estimates)<jupyter_output>[0.25 0.25 0.25 0.25 0.25 0.25 0.25 0.25 0.25 0.25]<jupyter_text>When `n_bits` is small, we don't get a very accurate estimate. You can go back and increase `n_bits` and rerun the cells if you like. To make experimentation easier, let's pack all this up into a single function that lets us specify $\theta$, the number of bits of of accuracy we want in our approxmation, and the number of repetitions of the algorithm to perform. You could just copy/paste from the previous cells, but it might be a useful exercise to write the whole thing from scratch without peeking.<jupyter_code>def phase_estimation(theta, n_bits, n_reps=10):
# YOUR CODE HERE
return theta_estimates<jupyter_output><empty_output><jupyter_text>Solution Here is a solution that just consists of what we did in previous cells all put together.<jupyter_code>def phase_estimation(theta, n_bits, n_reps=10):
qubits = cirq.LineQubit.range(n_bits)
u_bit = cirq.NamedQubit('u')
U = cirq.Z**(2*theta) # Try out a different gate if you like
phase_estimator = cirq.Circuit()
phase_estimator.append(cirq.H.on_each(*qubits))
for i, bit in enumerate(qubits):
phase_estimator.append(cirq.ControlledGate(U).on(bit,u_bit)**(2**(n_bits-1-i)))
phase_estimator.append(QFT_inv(n_bits).on(*qubits))
# Measurement gates
phase_estimator.append(cirq.measure(*qubits, key='m'))
# Gates to choose initial state for the u_bit. Placing X here chooses the |1> state
phase_estimator.insert(0,cirq.X(u_bit))
# Code to simulate measurements
sim = cirq.Simulator()
result = sim.run(phase_estimator, repetitions=n_reps)
# Convert measurements into estimates of theta
theta_estimates = np.sum(2**np.arange(n_bits)*result.measurements['m'], axis=1)/2**n_bits
return theta_estimates
phase_estimation(0.234, 10)<jupyter_output><empty_output><jupyter_text>Phase Estimation Without an EigenstateWe can modify our `phase_estimation` method to explore other interesting aspects of the algorithm. Suppose the input to the circuit was not an eigenstate of $U$ at all? You could modify the case we analyzed above by putting an arbitrary single-qubit state on the `u_bit`, or you could replace $Z^{2\theta}$ with something like $X^{2\theta}$ while still passing in a computational basis state. What is the result? Solution Suppose the operator $U$ has eigenstate $|u_j\rangle$ with eigenvalues $e^{2\pi i \theta_j}$. Then in general if we pass in a state of the form$$\sum_j \alpha_j|u_j\rangle$$then each time we run the circuit we will get an $n$-bit estimate of one of the $\theta_j$ chosen at random, and the probability of choosing a particular $\theta_j$ is given by $|\alpha_j|^2$. One simple test of this is to modify our above code to pass the state$$\frac{|0\rangle + |1\rangle}{\sqrt{2}}$$into the phase estimator for $Z^{2\theta}$. The state $|1\rangle$ has eigenvalue $e^{2\pi i \theta_j}$ while the state $|0\rangle$ has eigenvalue $1$.<jupyter_code>def phase_estimation(theta, n_bits, n_reps=10):
qubits = cirq.LineQubit.range(n_bits)
u_bit = cirq.NamedQubit('u')
U = cirq.Z**(2*theta)
phase_estimator = cirq.Circuit()
phase_estimator.append(cirq.H.on_each(*qubits))
for i, bit in enumerate(qubits):
phase_estimator.append(cirq.ControlledGate(U).on(bit,u_bit)**(2**(n_bits-1-i))) # Could have used CZ in this example
phase_estimator.append(QFT_inv(n_bits).on(*qubits))
phase_estimator.append(cirq.measure(*qubits, key='m'))
# Changed the X gate here to an H
phase_estimator.insert(0,cirq.H(u_bit))
sim = cirq.Simulator()
result = sim.run(phase_estimator, repetitions=n_reps)
theta_estimates = np.sum(2**np.arange(n_bits)*result.measurements['m'], axis=1)/2**n_bits
return theta_estimates
phase_estimation(0.234,10)<jupyter_output><empty_output><jupyter_text>Notice that half of the measurements yielded the estimate $0$, which corresponds to the eigenvaule $1$. If you experiment with different gates and input states you should see the more general behavior.Often we won't be able to prepare an exact eigenstate of the operator $U$ we are interested in, so it's very useful to know about this feature of phase estimation. This is crucial for understanding [Shor's algorithm](https://en.wikipedia.org/wiki/Shor%27s_algorithm), for instance. Exercise: Quantum Fourier Transform with Unreversed OutputIt may be convenient to have an alternative form of the QFT where the output bits are not in the opposite order of the input bits. Can you make an alternative implementation which does that automatically? You may want to consider using SWAP gates. Exercise: Phase Estimation with Arbitrary $U$Try to implement the phase estimation algorithm in a way that an arbitrary gate $U$ can be supplied and tested. After you've done that, you can test the algorithm on some of your favorite two- or three-qubit gates. Exercise: QFT and Phase Estimation with Adjacency ConstraintsOften on a real machine we can't execute two-qubit gates between qubits that are not right next to each other. You'll have noticed that the circuits we defined above involves connections between many different pairs of qubits, which will likely not all be near each other when we try to run the circuit on an actual chip. See if you can modify the examples we went through above in such a way that Cirq validates them for use on the Foxtail or Bristlecone chips. How bit of an example can you handle? Grover's AlgorithmThe Grover algorithm takes a black-box oracle implementing a function$f(x) = 1\text{ if }x=x',~ f(x) = 0 \text{ if } x\neq x'$ and finds $x'$ within a randomly ordered sequence of $N$ items using $O(\sqrt{N}$) operations and $O(N\, \text{log}N$) gates,with the probability $p \geq 2/3$.At the moment, only 2-bit sequences (for which one pass through Grover operatoris enough) are considered.=== REFERENCE ===Coles, Eidenbenz et al. Quantum Algorithm Implementations for Beginnershttps://arxiv.org/abs/1804.03719<jupyter_code>def set_io_qubits(qubit_count):
"""Add the specified number of input and output qubits."""
input_qubits = [cirq.GridQubit(i, 0) for i in range(qubit_count)]
output_qubit = cirq.GridQubit(qubit_count, 0)
return (input_qubits, output_qubit)
def make_oracle(input_qubits, output_qubit, x_bits):
"""Implement function {f(x) = 1 if x==x', f(x) = 0 if x!= x'}."""
# Make oracle.
# for (1, 1) it's just a Toffoli gate
# otherwise negate the zero-bits.
yield(cirq.X(q) for (q, bit) in zip(input_qubits, x_bits) if not bit)
yield(cirq.TOFFOLI(input_qubits[0], input_qubits[1], output_qubit))
yield(cirq.X(q) for (q, bit) in zip(input_qubits, x_bits) if not bit)
def make_grover_circuit(input_qubits, output_qubit, oracle):
"""Find the value recognized by the oracle in sqrt(N) attempts."""
# For 2 input qubits, that means using Grover operator only once.
c = cirq.Circuit()
# Initialize qubits.
c.append([
cirq.X(output_qubit),
cirq.H(output_qubit),
cirq.H.on_each(*input_qubits),
])
# Query oracle.
c.append(oracle)
# Construct Grover operator.
c.append(cirq.H.on_each(*input_qubits))
c.append(cirq.X.on_each(*input_qubits))
c.append(cirq.H.on(input_qubits[1]))
c.append(cirq.CNOT(input_qubits[0], input_qubits[1]))
c.append(cirq.H.on(input_qubits[1]))
c.append(cirq.X.on_each(*input_qubits))
c.append(cirq.H.on_each(*input_qubits))
# Measure the result.
c.append(cirq.measure(*input_qubits, key='result'))
return c
def bitstring(bits):
return ''.join(str(int(b)) for b in bits)
qubit_count = 2
circuit_sample_count = 10
#Set up input and output qubits.
(input_qubits, output_qubit) = set_io_qubits(qubit_count)
#Choose the x' and make an oracle which can recognize it.
x_bits = [random.randint(0, 1) for _ in range(qubit_count)]
print('Secret bit sequence: {}'.format(x_bits))
# Make oracle (black box)
oracle = make_oracle(input_qubits, output_qubit, x_bits)
# Embed the oracle into a quantum circuit implementing Grover's algorithm.
circuit = make_grover_circuit(input_qubits, output_qubit, oracle)
print('Circuit:')
print(circuit)
# Sample from the circuit a couple times.
simulator = cirq.Simulator()
result = simulator.run(circuit, repetitions=circuit_sample_count)
frequencies = result.histogram(key='result', fold_func=bitstring)
print('Sampled results:\n{}'.format(frequencies))
# Check if we actually found the secret value.
most_common_bitstring = frequencies.most_common(1)[0][0]
print('Most common bitstring: {}'.format(most_common_bitstring))
print('Found a match: {}'.format(
most_common_bitstring == bitstring(x_bits)))<jupyter_output>Secret bit sequence: [0, 1]
Circuit:
(0, 0): ───H───X───@───X───H───X───@───X───H───────M('result')───
│ │ │
(1, 0): ───H───────@───H───X───H───X───H───X───H───M─────────────
│
(2, 0): ───X───H───X─────────────────────────────────────────────
Sampled results:
Counter({'01': 10})
Most common bitstring: 01
Found a match: True | quantumcomputingbook/notebooks/textbook_algos_hands_on_pub.ipynb/0 | {
"file_path": "quantumcomputingbook/notebooks/textbook_algos_hands_on_pub.ipynb",
"repo_id": "quantumcomputingbook",
"token_count": 13303
} | 347 |
// Copyright 2019-2024 Cambridge Quantum Computing
//
// 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.
#pragma once
#include <cstdint>
#include <set>
#include <vector>
#include "ExactMappingLookup.hpp"
namespace tket {
namespace tsa_internal {
/** This is the same as ExactMappingLookup, except that we allow vertices not to
* have tokens. It works simply by going through possible permutations of empty
* vertices and doing an exact permutation lookup (limiting the number of
* permutations to avoid excessive slowdown).
*/
class PartialMappingLookup {
public:
/** Parameters controlling the partial mapping lookup. Sensible defaults,
* found by experimentation. */
struct Parameters {
/** To speed up, don't try all permutations if there are many empty
* vertices; limit them to this number. */
unsigned max_number_of_empty_vertex_permutations;
Parameters();
};
/** If desired, change some internal parameters.
* @return Internal parameters object, to be changed if desired.
*/
Parameters& get_parameters();
/** The result is stored internally. The same format as ExactMappingLookup.
* @param desired_mapping A (source vertex) -> (target vertex) permutation.
* @param edges Edges which exist between the vertices (equivalently, the
* swaps which we are permitted to use). Edges with vertices not appearing in
* desired_mapping will simply be ignored.
* @param vertices_with_tokens_at_start Every vertex mentioned within
* desired_mapping which has a token, just BEFORE the swaps are performed to
* enact the desired_mapping, must be mentioned here. Other vertices not
* mentioned in the mapping are allowed; they will simply be ignored.
* @param max_number_of_swaps Stop looking if every sequence of swaps in the
* table which enacts the desired mapping exceeds this length (or doesn't
* exist at all).
*/
const ExactMappingLookup::Result& operator()(
const VertexMapping& desired_mapping, const std::vector<Swap>& edges,
const std::set<std::size_t>& vertices_with_tokens_at_start,
unsigned max_number_of_swaps = 16);
private:
Parameters m_parameters;
ExactMappingLookup m_exact_mapping_lookup;
std::vector<std::size_t> m_empty_source_vertices;
std::vector<std::size_t> m_empty_target_vertices;
VertexMapping m_altered_mapping;
};
} // namespace tsa_internal
} // namespace tket
| tket/libs/tktokenswap/include/tktokenswap/PartialMappingLookup.hpp/0 | {
"file_path": "tket/libs/tktokenswap/include/tktokenswap/PartialMappingLookup.hpp",
"repo_id": "tket",
"token_count": 847
} | 348 |
// Copyright 2019-2024 Cambridge Quantum Computing
//
// 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.
#include "CyclesCandidateManager.hpp"
#include <algorithm>
#include <boost/functional/hash.hpp>
#include <stdexcept>
#include <tkassert/Assert.hpp>
#include "VertexSwapResult.hpp"
using std::vector;
namespace tket {
namespace tsa_internal {
std::size_t CyclesCandidateManager::fill_initial_cycle_ids(
const Cycles& cycles) {
m_cycle_with_vertex_hash.clear();
m_cycles_to_keep.clear();
std::size_t cycle_length = 0;
for (auto id_opt = cycles.front_id(); id_opt;
id_opt = cycles.next(id_opt.value())) {
const auto& cycle = cycles.at(id_opt.value());
const auto& vertices = cycle.vertices;
if (cycle_length == 0) {
cycle_length = vertices.size();
TKET_ASSERT(cycle_length >= 2);
} else {
TKET_ASSERT(cycle_length == vertices.size());
}
TKET_ASSERT(cycle.decrease > 0);
// We want 50*(decrease)/(num swaps) >= min_candidate_power_percentage.
// (We multiply by 50 because a swap can change L by 2, not 1).
if (50 * static_cast<unsigned>(cycle.decrease) <
(m_options.min_candidate_power_percentage * cycle_length)) {
continue;
}
CycleData cycle_data;
cycle_data.id = id_opt.value();
cycle_data.first_vertex_index = 0;
for (std::size_t ii = 1; ii < vertices.size(); ++ii) {
if (vertices[ii] < vertices[cycle_data.first_vertex_index]) {
cycle_data.first_vertex_index = ii;
}
}
std::size_t hash = static_cast<std::size_t>(cycle.decrease);
for (std::size_t ii = 0; ii < cycle_length; ++ii) {
boost::hash_combine(
hash, vertices[(ii + cycle_data.first_vertex_index) % cycle_length]);
}
const auto prev_cycle_citer = m_cycle_with_vertex_hash.find(hash);
if (prev_cycle_citer == m_cycle_with_vertex_hash.cend()) {
m_cycle_with_vertex_hash[hash] = cycle_data;
} else {
// A previous cycle with this hash; but is it equal?
const auto& previous_cycle_data = prev_cycle_citer->second;
const auto& previous_cycle = cycles.at(previous_cycle_data.id);
if (previous_cycle.decrease == cycle.decrease) {
bool equal_vertices = true;
for (std::size_t ii = 0; ii < cycle_length; ++ii) {
if (previous_cycle.vertices
[(ii + previous_cycle_data.first_vertex_index) %
cycle_length] !=
cycle.vertices
[(ii + cycle_data.first_vertex_index) % cycle_length]) {
equal_vertices = false;
break;
}
}
if (equal_vertices) {
// This new cycle is just the previous cycle repeated,
// but starting from a different vertex
continue;
}
}
}
m_cycles_to_keep.push_back(cycle_data.id);
}
return cycle_length;
}
void CyclesCandidateManager::discard_lower_power_solutions(
const Cycles& cycles) {
int highest_decrease = 0;
for (auto id : m_cycles_to_keep) {
highest_decrease = std::max(highest_decrease, cycles.at(id).decrease);
}
TKET_ASSERT(highest_decrease > 0);
for (std::size_t ii = 0; ii < m_cycles_to_keep.size();) {
if (cycles.at(m_cycles_to_keep[ii]).decrease < highest_decrease) {
// This cycle is not good enough.
// Erase this ID, by swapping with the back
m_cycles_to_keep[ii] = m_cycles_to_keep.back();
m_cycles_to_keep.pop_back();
continue;
}
// Keep this ID. Onto the next!
++ii;
}
}
void CyclesCandidateManager::sort_candidates(const Cycles& cycles) {
// Greedy heuristic: we want the maximal number of disjoint cycles.
// So, choose those which touch few others first.
// Experimentation is needed with other algorithms!
m_touching_data.clear();
for (std::size_t ii = 0; ii < m_cycles_to_keep.size(); ++ii) {
// Automatically set to zero on first use.
m_touching_data[m_cycles_to_keep[ii]];
for (std::size_t jj = ii + 1; jj < m_cycles_to_keep.size(); ++jj) {
bool touches = false;
// For short cycles, not much slower than using sets
// or sorted vectors.
for (auto v1 : cycles.at(m_cycles_to_keep[ii]).vertices) {
if (touches) {
break;
}
for (auto v2 : cycles.at(m_cycles_to_keep[jj]).vertices) {
if (v1 == v2) {
touches = true;
break;
}
}
}
if (touches) {
++m_touching_data[m_cycles_to_keep[ii]];
++m_touching_data[m_cycles_to_keep[jj]];
}
}
}
// Now, sort...
auto& touching_data = m_touching_data;
std::sort(
m_cycles_to_keep.begin(), m_cycles_to_keep.end(),
[&touching_data](Cycles::ID lhs, Cycles::ID rhs) {
const auto lhs_touch_number = touching_data.at(lhs);
const auto rhs_touch_number = touching_data.at(rhs);
// Don't JUST sort on the touch number, because then the order
// of equal-touch-number elements would be implementation dependent
// (i.e., not a "stable" sort across all platforms/compilers).
return (lhs_touch_number < rhs_touch_number) ||
(lhs_touch_number == rhs_touch_number && lhs < rhs);
});
}
bool CyclesCandidateManager::should_add_swaps_for_candidate(
const Cycles& cycles, Cycles::ID id) {
const auto& cycle = cycles.at(id);
const auto& vertices = cycle.vertices;
for (auto v : vertices) {
if (m_vertices_used.count(v) != 0) {
return false;
}
}
for (auto v : vertices) {
m_vertices_used.insert(v);
}
return true;
}
void CyclesCandidateManager::append_partial_solution(
const CyclesGrowthManager& growth_manager, SwapList& swaps,
VertexMapping& vertex_mapping) {
const auto& cycles = growth_manager.get_cycles();
const std::size_t cycle_size = fill_initial_cycle_ids(cycles);
if (m_cycles_to_keep.empty()) {
return;
}
const bool keep_lower_power_solutions =
(cycle_size == 2)
? m_options.return_all_good_single_swaps
: m_options.return_lower_power_solutions_for_multiswap_candidates;
if (!keep_lower_power_solutions) {
discard_lower_power_solutions(cycles);
}
sort_candidates(cycles);
m_vertices_used.clear();
// It's the final function, so don't bother erasing
// elements in m_cycles_to_keep.
for (auto id : m_cycles_to_keep) {
if (!should_add_swaps_for_candidate(cycles, id)) {
continue;
}
const auto& vertices = cycles.at(id).vertices;
for (std::size_t ii = vertices.size() - 1; ii > 0; --ii) {
VertexSwapResult(vertices[ii], vertices[ii - 1], vertex_mapping, swaps);
}
}
}
} // namespace tsa_internal
} // namespace tket
| tket/libs/tktokenswap/src/CyclesCandidateManager.cpp/0 | {
"file_path": "tket/libs/tktokenswap/src/CyclesCandidateManager.cpp",
"repo_id": "tket",
"token_count": 2978
} | 349 |
// Copyright 2019-2024 Cambridge Quantum Computing
//
// 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.
#include "tktokenswap/VertexSwapResult.hpp"
namespace tket {
namespace tsa_internal {
VertexSwapResult::VertexSwapResult(
std::size_t v1, std::size_t v2, VertexMapping& vertex_mapping,
SwapList& swap_list)
: VertexSwapResult(v1, v2, vertex_mapping) {
if (tokens_moved != 0) {
swap_list.push_back(get_swap(v1, v2));
}
}
VertexSwapResult::VertexSwapResult(
const Swap& swap, VertexMapping& vertex_mapping)
: VertexSwapResult(swap.first, swap.second, vertex_mapping) {}
VertexSwapResult::VertexSwapResult(
std::size_t v1, std::size_t v2, VertexMapping& vertex_mapping) {
if (vertex_mapping.count(v1) == 0) {
if (vertex_mapping.count(v2) == 0) {
tokens_moved = 0;
return;
}
// No token on the first.
vertex_mapping[v1] = vertex_mapping[v2];
vertex_mapping.erase(v2);
tokens_moved = 1;
return;
}
// A token on the first.
if (vertex_mapping.count(v2) == 0) {
vertex_mapping[v2] = vertex_mapping[v1];
vertex_mapping.erase(v1);
tokens_moved = 1;
return;
}
// Tokens on both.
std::swap(vertex_mapping[v1], vertex_mapping[v2]);
tokens_moved = 2;
}
} // namespace tsa_internal
} // namespace tket
| tket/libs/tktokenswap/src/TSAUtils/VertexSwapResult.cpp/0 | {
"file_path": "tket/libs/tktokenswap/src/TSAUtils/VertexSwapResult.cpp",
"repo_id": "tket",
"token_count": 688
} | 350 |
// Copyright 2019-2024 Cambridge Quantum Computing
//
// 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.
#pragma once
#include <map>
#include <string>
#include <vector>
namespace tket {
namespace tsa_internal {
namespace tests {
/** These store complete solutions to fixed token swapping problems.
* This is similar to FixedSwapSequences.
* However, it is different in several ways:
*
* (1) The solutions have not been processed further (thus, we
* do not expect the swap sequences to be irreducible).
* In particular, we did not relabel the vertices of the solutions,
* so they will not be contiguous.
*
* (2) The full set of edges passed into the original solver is preserved
* (thus, we expect more variety in possible solutions; there may be
* more shortcuts making use of different edges).
* In particular, all architectures are connected, so there should be
* NO errors when running our TSA.
*
* (3) Several real architectures are included.
*
* I have tried to include a reasonable range of architectures
* and problem sizes.
*
* Thus, this allows a direct comparison between our TSA
* and the one used to generate these solutions, and hopefully will show
* improvements more clearly over time.
* These are also hopefully more realistic problems.
* However, as noted also in FixedSwapSequences, we must remember that:
*
* (a) relabelling vertices will, in most cases, give different solutions
* [even though the problems are "isomorphic"]; this is just an unavoidable
* consequence of the token swapping problem being hard and, presumably,
* often having many "nonisomorphic" optimal solutions [although this hasn't
* been precisely defined]. Thus, we can never REALLY do a direct comparison
* because we're always going to get small differences just by "chance",
* depending upon our vertex labelling;
*
* (b) Many algorithms involve an RNG and hence do not give the same solution
* each time (although, our TSAs are careful always to reset the RNG seed,
* so should actually be deterministic).
*/
struct FixedCompleteSolutions {
// KEY: the architecture name
// VALUE: the problems, encoded as strings; the first element
// encodes the complete collection of edges (which cannot be deduced from the
// solution swaps because, of course, some edges might be unused). The
// remaining elements are the calculated solutions to actual problems, with
// the same encoding as in FixedSwapSequences. Thus the tokens are given, but
// the vertex mapping is not, since it can be deduced from the swaps as
// usual.
std::map<std::string, std::vector<std::string>> solutions;
// Fill in all the problem data upon construction.
FixedCompleteSolutions();
};
} // namespace tests
} // namespace tsa_internal
} // namespace tket
| tket/libs/tktokenswap/test/src/Data/FixedCompleteSolutions.hpp/0 | {
"file_path": "tket/libs/tktokenswap/test/src/Data/FixedCompleteSolutions.hpp",
"repo_id": "tket",
"token_count": 862
} | 351 |
// Copyright 2019-2024 Cambridge Quantum Computing
//
// 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.
#pragma once
#include <tkrng/RNG.hpp>
#include "tkwsm/Searching/ValueOrdering.hpp"
#include "tkwsm/Searching/VariableOrdering.hpp"
namespace tket {
namespace WeightedSubgraphMonomorphism {
struct SearchComponents {
// The newly created search-specific components follow.
ValueOrdering value_ordering;
VariableOrdering variable_ordering;
RNG rng;
};
} // namespace WeightedSubgraphMonomorphism
} // namespace tket
| tket/libs/tkwsm/include/tkwsm/EndToEndWrappers/SearchComponents.hpp/0 | {
"file_path": "tket/libs/tkwsm/include/tkwsm/EndToEndWrappers/SearchComponents.hpp",
"repo_id": "tket",
"token_count": 296
} | 352 |
// Copyright 2019-2024 Cambridge Quantum Computing
//
// 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.
#pragma once
#include <optional>
#include <tkrng/RNG.hpp>
#include "tkwsm/GraphTheoretic/GeneralStructs.hpp"
namespace tket {
namespace WeightedSubgraphMonomorphism {
namespace InitialPlacement {
struct MonteCarloManagerParameters {
// How many iterations do we demand as a minimum before we can reset?
unsigned min_iterations_for_change = 20;
// There are 2 types of progress possible
// (i.e., a changed solution is accepted):
// "weak progress" means that we have just decreased the current cost,
// EVEN THOUGH the cost might still be higher than the
// best one found so far.
// "record breaker" means that we really have found a new cost lower than
// the previous all-time lowest cost.
// The "per kilo fractions" are x/1024 for an integer x
// (i.e., "per 1024" rather than "per 100", for percentages).
// This is because dividing by 1024 might be a bit faster than
// dividing by 100 (and definitely won't be slower!)
// (Apparently int division can be surprisingly slower than
// int multiplication or addition).
// How many extra iterations without any progress do we allow,
// as a fraction of the existing number, before we demand a reset?
unsigned per_kilo_fraction_of_allowed_extra_iterations_without_weak_progress =
500;
// How many extra iterations without any new reocrd breaker do we allow,
// as a fraction of the existing number, before we demand a reset?
unsigned
per_kilo_fraction_of_allowed_extra_iterations_without_record_breakers =
1000;
unsigned max_runs_without_record_breaking = 10;
unsigned max_runs_without_progress = 10;
};
/** For use in MonteCarloCompleteTargetSolution.
* Even for a simplified jumping algorithm, simpler than simulated annealing
* because we only allow improving moves, it's still unclear how to choose
* the best parameters.
* The difficulty of simulated annealing and other similar random jumping
* algorithms is NOT in the algorithm itself; it is in the fully automatic
* selection of parameter values and termination criteria,
* which still doesn't seem to have a fully satisfactory solution.
*/
class MonteCarloManager {
public:
/** It should be clear by now that all these values are rather arbitrary!
* We need to do more experiments to find the best values.
*/
explicit MonteCarloManager(
const MonteCarloManagerParameters& parameters =
MonteCarloManagerParameters());
enum class Action {
CONTINUE_WITH_CURRENT_SOLUTION,
RESET_TO_NEW_SOLUTION,
TERMINATE
};
/** We've just improved upon our current solution
* (which may or may not be a new record breaker).
* What should we do now?
*/
Action register_progress(WeightWSM new_cost, unsigned iteration);
/** At this iteration number, we have not made any progress
* (weak progress OR record breaking).
*/
Action register_failure(unsigned iteration);
private:
const MonteCarloManagerParameters m_parameters;
unsigned m_runs_without_record_breaking;
unsigned m_runs_without_progress;
// What is the lowest weight found so far?
WeightWSM m_best_cost;
unsigned m_next_iteration_to_reset_if_no_progress;
unsigned m_next_iteration_to_reset_if_no_record_breaker;
void update_after_reset(unsigned iteration);
void update_after_weak_progress(unsigned iteration);
};
} // namespace InitialPlacement
} // namespace WeightedSubgraphMonomorphism
} // namespace tket
| tket/libs/tkwsm/include/tkwsm/InitPlacement/MonteCarloManager.hpp/0 | {
"file_path": "tket/libs/tkwsm/include/tkwsm/InitPlacement/MonteCarloManager.hpp",
"repo_id": "tket",
"token_count": 1131
} | 353 |
// Copyright 2019-2024 Cambridge Quantum Computing
//
// 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.
#pragma once
#include <optional>
#include "../GraphTheoretic/GeneralStructs.hpp"
namespace tket {
namespace WeightedSubgraphMonomorphism {
class DomainsAccessor;
class NeighboursData;
/** Can we get a good guaranteed lower bound on the extra weight
* to be added from all unassigned pattern vertices,
* HOWEVER it's done?
* If so, and if this extra weight would take the total weight
* above the constraint value (i.e., the imposed upper bound
* on the weight), then we can prune immediately (backtrack).
*
* We want something fast enough not to slow the
* calculation down too much, but accurate enough (i.e. giving
* large lower bounds on the extra weight) to be useful,
* i.e. actually detect weight nogoods sometimes.
* A delicate balancing act!
*
* The ACTUAL optimal lower bound can only be found, presumably, by solving
* a complete WSM problem. More accurate estimates can be obtained
* by weighted bipartite matching, etc. etc., but take longer.
*/
class WeightNogoodDetector {
public:
/** The detector needs to know all target vertices which are possible.
* But note that this
* need not be done at the START of the search; it can be delayed
* until needed, when search progress may have cut down some
* possibilities, and hence reduced the domains slightly,
* giving better estimates.
*/
WeightNogoodDetector(
const NeighboursData& pattern_neighbours_data,
const NeighboursData& target_neighbours_data,
std::set<VertexWSM> initial_used_target_vertices,
std::set<VertexWSM>& invalid_target_vertices);
/** Return a guaranteed lower bound for the scalar product increase
* if the current partial solution could be extended to a complete
* valid solution, or null if in fact we can prove that it's impossible
* (EITHER for graph theoretic reasons - maybe the graphs simply aren't
* compatible, regardless of weights - OR because it would exceed
* the allowed maximum).
* @param accessor An object to retrieve information about domains.
* @param max_extra_scalar_product The maximum extra weight we allow (the
* whole point of this nogood detection attempt).
* @return Information about the min possible scalar product increase (null if
* it's a nogood)
*/
std::optional<WeightWSM> get_extra_scalar_product_lower_bound(
const DomainsAccessor& accessor, WeightWSM max_extra_scalar_product);
/** How many target vertices are still valid (i.e., could possibly
* be mapped to by some PV)?
* @return the size of m_valid_target_vertices
*/
std::size_t get_number_of_possible_tv() const;
private:
const NeighboursData& m_pattern_neighbours_data;
const NeighboursData& m_target_neighbours_data;
mutable std::set<VertexWSM> m_valid_target_vertices;
// As soon as a TV is newly discovered to be invalid,
// meaning that no p-vertex could ever be assigned to it
// (quite a rare event), store it here.
//
// This of course is even stronger than a normal impossible
// assignment PV->TV.
//
// Moreover (in case the caller ever tries parallel searches, etc.)
// the TV was ALWAYS invalid, so can be erased from ALL data.
std::set<VertexWSM>& m_invalid_target_vertices;
// There are many mutable data members.
// Even though this class is "logically" const,
// it's not "physically" const because of lazy evaluation,
// as well as work data to avoid memory reallocation.
// KEY: a target vertex TV.
// VALUE: the smallest t-edge weight which can arise
// from an edge containing TV.
// Excludes target edges, if any, which can never arise
// (i.e. containing at least one vertex which no pattern vertex
// can ever map to).
//
// Mutable because it's lazily initialised.
mutable std::map<VertexWSM, WeightWSM> m_minimum_t_weights_from_tv;
// Calculated only on first use, and cached;
// if non-null, the minimum edge weight of any target edge
// containing the target vertex tv.
std::optional<WeightWSM> get_min_weight_for_tv(VertexWSM tv) const;
// This really is mutable, to avoid reallocation.
// In each pair: the FIRST is an UNASSIGNED pattern vertex pv.
// The second is a guaranteed lower bound for the t-weight which will be
// matched to any p-edge containing pv. (The p-edge therefore must necessarily
// be unassigned; but BEWARE: the other vertex could be assigned already).
//
// It just so happens, from the way it's created, that it's ALWAYS sorted!
// Thus, we can use a sorted vector instead of a map.
mutable std::vector<std::pair<VertexWSM, WeightWSM>>
m_t_weight_lower_bounds_for_p_edges_containing_pv;
// Fills m_t_weight_lower_bounds_for_p_edges_containing_pv,
// relevant for this current search node only.
// Returns false if it found we're already at a nogood.
bool fill_t_weight_lower_bounds_for_p_edges_containing_pv(
const DomainsAccessor& accessor) const;
// Simply looks up and returns the weight in
// m_t_weight_lower_bounds_for_p_edges_containing_pv.
// So, out of all t-edges which could possibly contain
// F(pv), for any valid mapping F from this current node,
// this is the lowest weight.
// We're GUARANTEED that it exists, because
// m_t_weight_lower_bounds_for_p_edges_containing_pv was already filled
// with EVERY pv, except when there were no valid t-edges,
// in which case it was a nogood and we should already have returned.
WeightWSM get_t_weight_lower_bound(VertexWSM pv) const;
};
} // namespace WeightedSubgraphMonomorphism
} // namespace tket
| tket/libs/tkwsm/include/tkwsm/WeightPruning/WeightNogoodDetector.hpp/0 | {
"file_path": "tket/libs/tkwsm/include/tkwsm/WeightPruning/WeightNogoodDetector.hpp",
"repo_id": "tket",
"token_count": 1834
} | 354 |
// Copyright 2019-2024 Cambridge Quantum Computing
//
// 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.
#include "tkwsm/InitPlacement/EndToEndIQP.hpp"
#include <chrono>
#include <sstream>
#include <tkassert/Assert.hpp>
#include "tkwsm/Common/GeneralUtils.hpp"
#include "tkwsm/EndToEndWrappers/MainSolver.hpp"
#include "tkwsm/GraphTheoretic/NeighboursData.hpp"
#include "tkwsm/GraphTheoretic/VertexRelabelling.hpp"
#include "tkwsm/InitPlacement/InputStructs.hpp"
#include "tkwsm/InitPlacement/MonteCarloCompleteTargetSolution.hpp"
#include "tkwsm/InitPlacement/PrunedTargetEdges.hpp"
#include "tkwsm/InitPlacement/UtilsIQP.hpp"
namespace tket {
namespace WeightedSubgraphMonomorphism {
namespace InitialPlacement {
typedef std::chrono::steady_clock Clock;
namespace {
// Gets an initial placement using MCCT (Monte Carlo complete target graph),
// and also contains intermediate
// objects needed for other calculations.
struct MCCTData {
MCCTData(
const GraphEdgeWeights& pattern_graph_weights,
const GraphEdgeWeights& target_architecture_with_error_weights,
WeightWSM& scalar_product, unsigned& number_of_iterations)
: pattern_relabelling(pattern_graph_weights),
relabelled_pattern_ndata(pattern_relabelling.new_edges_and_weights),
target_relabelling(target_architecture_with_error_weights),
expanded_target_graph_data(target_architecture_with_error_weights),
relabelled_explicit_target_ndata(get_relabelled_graph_data(
expanded_target_graph_data.explicit_target_graph_weights,
target_relabelling))
{
const MonteCarloCompleteTargetSolution mcct_solution(
relabelled_pattern_ndata, relabelled_explicit_target_ndata,
expanded_target_graph_data.implicit_weight);
number_of_iterations = mcct_solution.iterations();
scalar_product = mcct_solution.get_best_scalar_product();
new_label_assignments = mcct_solution.get_best_assignments();
}
// The below data is needed later, for target pruning
// (MCCT, of course, does NOT use target edge pruning).
// We need to relabel the pattern vertices for neighbours data.
// TODO refactor: MainSolver also does this internally,
// which is inelegent wasted duplication
// (although completely negligible impact).
const VertexRelabelling pattern_relabelling;
const NeighboursData relabelled_pattern_ndata;
// We also need to relabel the target vertices for neighbours data.
/// TODO Again, refactor: MainSolver also does this internally.
// Note that this includes ALL TV (although relabelled).
// This is the same relabelling for both the original and expanded
// target graphs (as expansion only adds edges, not vertices).
const VertexRelabelling target_relabelling;
const TargetGraphData expanded_target_graph_data;
// We've expanded the target; this contains all the explicit weights.
const NeighboursData relabelled_explicit_target_ndata;
// Element[PV] = TV, using the relabelled PV, TV.
std::vector<unsigned> new_label_assignments;
};
} // namespace
IQPResult::IQPResult(
const GraphEdgeWeights& pattern_graph_weights,
const GraphEdgeWeights& target_architecture_with_error_weights,
unsigned timeout_ms, const IQPParameters& iqp_parameters) {
const auto start = Clock::now();
const MCCTData mcct_data(
pattern_graph_weights, target_architecture_with_error_weights,
mcct_scalar_product, mcct_iterations);
mcct_time_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
Clock::now() - start)
.count();
TKET_ASSERT(
mcct_data.new_label_assignments.size() ==
mcct_data.pattern_relabelling.number_of_vertices);
initial_qubit_placement.reserve(
mcct_data.pattern_relabelling.number_of_vertices);
for (unsigned new_pv = 0;
new_pv < mcct_data.pattern_relabelling.number_of_vertices; ++new_pv) {
initial_qubit_placement.emplace_back(
mcct_data.pattern_relabelling.get_old_label(new_pv),
mcct_data.target_relabelling.get_old_label(
mcct_data.new_label_assignments[new_pv]));
}
if (mcct_time_ms >= timeout_ms || mcct_scalar_product == 0) {
// (Unless we've got many zero weights, which is extremely unusual):
// we're out of time - no WSM.
total_time_ms = mcct_time_ms;
std::sort(initial_qubit_placement.begin(), initial_qubit_placement.end());
return;
}
// Prune the complete target edges.
// This uses the same new TV labels as in MCCT.
// But beware: some new TV might not appear in this data,
// because we've deliberately cut it down to make WSM solving fast
// (otherwise, we'd just retain the complete target graph).
const GraphEdgeWeights relabelled_pruned_wsm_target_graph_data =
get_new_target_graph_data(
mcct_data.relabelled_pattern_ndata,
mcct_data.relabelled_explicit_target_ndata,
mcct_data.expanded_target_graph_data.implicit_weight,
mcct_data.new_label_assignments);
wsm_number_of_pruned_tv =
get_number_of_vertices(relabelled_pruned_wsm_target_graph_data);
wsm_number_of_pruned_t_edges = relabelled_pruned_wsm_target_graph_data.size();
// Be paranoid and recalculate the scalar product...
// this can be removed when it's been thoroughly tested
// (although it does no harm - negligible extra time)
{
auto old_pv_new_tv_assignments = initial_qubit_placement;
for (auto& entry : old_pv_new_tv_assignments) {
entry.second = mcct_data.target_relabelling.get_new_label(entry.second);
}
TKET_ASSERT(
mcct_scalar_product == get_checked_scalar_product(
pattern_graph_weights,
relabelled_pruned_wsm_target_graph_data,
old_pv_new_tv_assignments));
}
MainSolverParameters wsm_solver_parameters;
// We already checked that there is positive time remaining.
wsm_solver_parameters.timeout_ms = timeout_ms - mcct_time_ms;
wsm_solver_parameters.iterations_timeout = iqp_parameters.max_wsm_iterations;
// We must strictly improve on our MCCT solution, otherwise no point.
wsm_solver_parameters.weight_upper_bound_constraint = mcct_scalar_product - 1;
const MainSolver wsm_solver(
pattern_graph_weights, relabelled_pruned_wsm_target_graph_data,
wsm_solver_parameters);
const SolutionData& wsm_solution = wsm_solver.get_solution_data();
wsm_init_time_ms = wsm_solution.initialisation_time_ms;
wsm_solve_time_ms = wsm_solution.search_time_ms;
total_time_ms = wsm_init_time_ms + wsm_solve_time_ms + mcct_time_ms;
wsm_iterations = wsm_solution.iterations;
if (wsm_solution.solutions.empty()) {
return;
}
TKET_ASSERT(wsm_solution.solutions.size() == 1);
TKET_ASSERT(wsm_solution.solutions[0].scalar_product <= mcct_scalar_product);
wsm_scalar_product_opt = wsm_solution.solutions[0].scalar_product;
initial_qubit_placement = wsm_solution.solutions[0].assignments;
// Care: the WSM problem used new TV labels.
for (auto& entry : initial_qubit_placement) {
entry.second = mcct_data.target_relabelling.get_old_label(entry.second);
}
}
} // namespace InitialPlacement
} // namespace WeightedSubgraphMonomorphism
} // namespace tket
| tket/libs/tkwsm/src/InitPlacement/EndToEndIQP.cpp/0 | {
"file_path": "tket/libs/tkwsm/src/InitPlacement/EndToEndIQP.cpp",
"repo_id": "tket",
"token_count": 2891
} | 355 |
// Copyright 2019-2024 Cambridge Quantum Computing
//
// 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.
#include "tkwsm/Searching/SearchBranch.hpp"
#include <algorithm>
#include <tkassert/Assert.hpp>
#include "tkwsm/Common/GeneralUtils.hpp"
#include "tkwsm/EndToEndWrappers/SolutionData.hpp"
#include "tkwsm/GraphTheoretic/NeighboursData.hpp"
#include "tkwsm/Reducing/DistancesReducer.hpp"
#include "tkwsm/WeightPruning/WeightChecker.hpp"
namespace tket {
namespace WeightedSubgraphMonomorphism {
SearchBranch::SearchBranch(
const DomainInitialiser::InitialDomains& initial_domains,
const NeighboursData& pattern_ndata, NearNeighboursData& pattern_near_ndata,
const NeighboursData& target_ndata, NearNeighboursData& target_near_ndata,
unsigned max_distance_reduction_value, ExtraStatistics& extra_statistics)
: m_pattern_ndata(pattern_ndata),
m_target_ndata(target_ndata),
m_extra_statistics(extra_statistics),
m_derived_graphs_reducer(m_pattern_ndata, m_target_ndata),
m_nodes_raw_data_wrapper(
initial_domains, m_target_ndata.get_number_of_nonisolated_vertices()),
m_domains_accessor(m_nodes_raw_data_wrapper),
m_node_list_traversal(m_nodes_raw_data_wrapper) {
m_extra_statistics.number_of_pattern_vertices =
m_pattern_ndata.get_number_of_nonisolated_vertices();
m_extra_statistics.number_of_target_vertices =
m_target_ndata.get_number_of_nonisolated_vertices();
m_extra_statistics.initial_number_of_possible_assignments = 0;
for (const boost::dynamic_bitset<>& domain : initial_domains) {
m_extra_statistics.initial_number_of_possible_assignments += domain.count();
}
// In what order should we do reduction/checks?
// The simplest/cheapest first? Most powerful?
// Seems a difficult question...
m_reducer_wrappers.reserve(max_distance_reduction_value + 1);
/// m_reducer_wrappers.emplace_back(m_neighbours_reducer);
m_reducer_wrappers.emplace_back(m_derived_graphs_reducer);
m_distance_reducers.reserve(max_distance_reduction_value);
for (unsigned distance = 1; distance <= max_distance_reduction_value;
++distance) {
m_distance_reducers.emplace_back(
pattern_near_ndata, target_near_ndata, distance);
}
// Now that all the reducer objects are stored
// (the vector will not be resized),
// we can safely take references to them.
for (DistancesReducer& reducer : m_distance_reducers) {
m_reducer_wrappers.emplace_back(reducer);
}
}
const DomainsAccessor& SearchBranch::get_domains_accessor() const {
return m_domains_accessor;
}
DomainsAccessor& SearchBranch::get_domains_accessor_nonconst() {
return m_domains_accessor;
}
boost::dynamic_bitset<> SearchBranch::get_used_target_vertices() const {
return m_node_list_traversal.get_used_target_vertices();
}
const ExtraStatistics& SearchBranch::get_updated_extra_statistics() {
if (m_weight_checker_ptr) {
const auto weight_checker_data_opt =
m_weight_checker_ptr->get_tv_data_opt();
if (weight_checker_data_opt) {
m_extra_statistics.n_tv_initially_passed_to_weight_nogood_detector =
weight_checker_data_opt->initial_number_of_tv;
m_extra_statistics.n_tv_still_valid_in_weight_nogood_detector =
weight_checker_data_opt->final_number_of_tv;
}
}
m_extra_statistics.total_number_of_assignments_tried = 0;
for (const auto& entry : m_checked_assignments) {
m_extra_statistics.total_number_of_assignments_tried += entry.second.size();
}
return m_extra_statistics;
}
void SearchBranch::activate_weight_checker(WeightWSM total_p_edge_weights) {
m_weight_checker_ptr = std::make_unique<WeightChecker>(
m_pattern_ndata, m_target_ndata, *this, total_p_edge_weights,
m_impossible_target_vertices);
TKET_ASSERT(m_weight_checker_ptr);
}
bool SearchBranch::perform_single_assignment_checks_in_reduce_loop(
std::size_t num_assignments_alldiff_processed) {
const std::vector<std::pair<VertexWSM, VertexWSM>>& new_assignments =
m_domains_accessor.get_new_assignments();
for (auto ii = num_assignments_alldiff_processed; ii < new_assignments.size();
++ii) {
if (m_checked_assignments[new_assignments[ii].first].count(
new_assignments[ii].second) != 0) {
continue;
}
for (auto& reducer_wrapper : m_reducer_wrappers) {
if (!reducer_wrapper.check(new_assignments[ii])) {
// The whole point is, the check for PV->TV does NOT depend on
// the other domains; since it's failed the check, it was ALWAYS
// invalid, so we remove it completely from ALL data.
m_node_list_traversal.erase_impossible_assignment(new_assignments[ii]);
// The current node is a nogood, so we'll move up from it shortly;
// no point in further checks or reductions, this node is doomed!
++m_extra_statistics.total_number_of_impossible_assignments;
return false;
}
}
}
return true;
}
bool SearchBranch::check_and_update_scalar_product_in_reduce_loop(
const ReductionParameters& parameters,
std::size_t num_assignments_alldiff_processed) {
const auto weight_result_opt = m_weight_calculator(
m_pattern_ndata, m_target_ndata, m_domains_accessor,
num_assignments_alldiff_processed, parameters.max_weight);
if (!weight_result_opt) {
return false;
}
m_domains_accessor.set_scalar_product(weight_result_opt->scalar_product)
.set_total_p_edge_weights(
weight_result_opt->total_extra_p_edge_weights +
m_domains_accessor.get_total_p_edge_weights());
return true;
}
bool SearchBranch::perform_weight_nogood_check_in_reduce_loop(
const ReductionParameters& parameters) {
if (is_maximum(parameters.max_weight)) {
// No scalar product constraint, so nothing to check.
return true;
}
const auto scalar_product = m_domains_accessor.get_scalar_product();
if (scalar_product > parameters.max_weight) {
return false;
}
if (m_weight_checker_ptr) {
m_impossible_target_vertices.clear();
const WeightWSM max_extra_scalar_product =
parameters.max_weight - scalar_product;
bool node_is_valid = m_weight_checker_ptr->check(
m_domains_accessor, max_extra_scalar_product);
const auto number_of_pv =
m_domains_accessor.get_number_of_pattern_vertices();
for (VertexWSM tv : m_impossible_target_vertices) {
// This is rare. Crudely treat as a list of assignments.
// We want to pass them all in now, though, even if we're at a nogood;
// they might not be detected again.
m_extra_statistics.impossible_target_vertices.emplace_back(tv);
for (unsigned pv = 0; pv < number_of_pv; ++pv) {
m_node_list_traversal.erase_impossible_assignment(
std::make_pair(pv, tv));
}
// Detecting an invalid TV is separate from whether
// the current node is a nogood.
node_is_valid &= m_domains_accessor.current_node_is_valid();
}
return node_is_valid;
}
return true;
}
ReductionResult SearchBranch::perform_reducers_in_reduce_loop() {
for (auto& reducer_wrapper : m_reducer_wrappers) {
const auto reduction_result =
reducer_wrapper.reduce(m_domains_accessor, m_work_set_for_reducers);
if (reduction_result != ReductionResult::SUCCESS) {
return reduction_result;
}
}
return ReductionResult::SUCCESS;
}
bool SearchBranch::perform_main_reduce_loop(
const ReductionParameters& parameters) {
// Within the loop, we reduce; we break out when it stops changing,
// so is valid and fully reduced.
// At the start of each new loop, this tells us how many initial elements
// of new_assignments have been processed by the alldiff reducer.
std::size_t num_assignments_alldiff_processed = 0;
// We will not change this directly. The reference will remain valid,
// but it will change indirectly due to other actions (reducing, etc.).
const std::vector<std::pair<VertexWSM, VertexWSM>>& new_assignments =
m_domains_accessor.get_new_assignments();
for (;;) {
if (!(m_domains_accessor.alldiff_reduce_current_node(
num_assignments_alldiff_processed) &&
// Checks/updates which don't alter domains follow.
perform_single_assignment_checks_in_reduce_loop(
num_assignments_alldiff_processed) &&
check_and_update_scalar_product_in_reduce_loop(
parameters, num_assignments_alldiff_processed))) {
return false;
}
num_assignments_alldiff_processed = new_assignments.size();
if (!perform_weight_nogood_check_in_reduce_loop(parameters)) {
return false;
}
// It's rare, but possible, that the weight nogood check found an impossible
// TV, in which case it was erased, and the domains DID change...
if (num_assignments_alldiff_processed != new_assignments.size()) {
// Jump back to start!
continue;
}
// Now do REDUCTIONS, which do alter domains.
// The scalar product updates etc. have all been completed.
// If we detect that a new assignment has occurred,
// we jump back to the start of the loop. (Since the node reductions
// and assignment checking should be faster
// than these more complicated reductions).
{
const auto reducers_result = perform_reducers_in_reduce_loop();
if (reducers_result == ReductionResult::NOGOOD) {
return false;
}
if (reducers_result == ReductionResult::NEW_ASSIGNMENTS) {
// Jump back to start of loop.
TKET_ASSERT(num_assignments_alldiff_processed < new_assignments.size());
continue;
}
TKET_ASSERT(num_assignments_alldiff_processed == new_assignments.size());
}
// It is reasonable that the final reduction is the Hall set reducer,
// because it alone benefits from smaller domains
// (i.e., is more likely to detect a possible reduction).
// The standard reducers ONLY work with actual ASSIGNMENTS;
// it makes no difference if a domain has size 2 or 100.
//*
const auto hall_set_result =
m_hall_set_reduction.reduce(m_domains_accessor);
if (hall_set_result == ReductionResult::NOGOOD) {
return false;
}
TKET_ASSERT(num_assignments_alldiff_processed <= new_assignments.size());
if (num_assignments_alldiff_processed == new_assignments.size()) {
TKET_ASSERT(hall_set_result == ReductionResult::SUCCESS);
// No further assignments from reductions.
break;
}
// Will jump back to start of loop.
TKET_ASSERT(hall_set_result == ReductionResult::NEW_ASSIGNMENTS);
TKET_ASSERT(num_assignments_alldiff_processed < new_assignments.size());
}
return true;
}
bool SearchBranch::reduce_current_node(const ReductionParameters& parameters) {
for (auto& reducer_wrapper : m_reducer_wrappers) {
reducer_wrapper.clear();
}
m_hall_set_reduction.clear();
if (!perform_main_reduce_loop(parameters)) {
return false;
}
// Now that we've processed all the assignments,
// we don't need them.
m_domains_accessor.clear_new_assignments();
return true;
}
bool SearchBranch::backtrack(const ReductionParameters& parameters) {
do {
if (!m_node_list_traversal.move_up()) {
return false;
}
} while (!reduce_current_node(parameters));
return true;
}
void SearchBranch::move_down(VertexWSM p_vertex, VertexWSM t_vertex) {
m_node_list_traversal.move_down(p_vertex, t_vertex);
}
} // namespace WeightedSubgraphMonomorphism
} // namespace tket
| tket/libs/tkwsm/src/Searching/SearchBranch.cpp/0 | {
"file_path": "tket/libs/tkwsm/src/Searching/SearchBranch.cpp",
"repo_id": "tket",
"token_count": 4551
} | 356 |
// Copyright 2019-2024 Cambridge Quantum Computing
//
// 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.
#include <catch2/catch_test_macros.hpp>
#include <stdexcept>
#include <tkwsm/Common/GeneralUtils.hpp>
#include <tkwsm/Common/TemporaryRefactorCode.hpp>
#include <tkwsm/GraphTheoretic/NearNeighboursData.hpp>
#include <tkwsm/GraphTheoretic/NeighboursData.hpp>
namespace tket {
namespace WeightedSubgraphMonomorphism {
SCENARIO("test neighbours_data on cycles") {
const unsigned cycle_length = 5;
const std::vector<std::size_t> deg_seqs{2, 2};
GraphEdgeWeights edge_weights;
std::vector<VertexWSM> neighbours_recalc(2);
for (VertexWSM ii = 0; ii < cycle_length; ++ii) {
const VertexWSM jj = (ii + 1) % cycle_length;
edge_weights[get_edge(ii, jj)] = ii + jj;
}
const NeighboursData ndata(edge_weights);
// VertexWSM funcs
for (VertexWSM ii = 0; ii < cycle_length; ++ii) {
CHECK(ndata.get_degree(ii) == 2);
CHECK(ndata.get_sorted_degree_sequence_expensive(ii) == deg_seqs);
const auto neighbours = ndata.get_neighbours_expensive(ii);
CHECK(neighbours.size() == 2);
CHECK(is_sorted_and_unique(neighbours));
neighbours_recalc[0] = ((ii + cycle_length) - 1) % cycle_length;
neighbours_recalc[1] = (ii + 1) % cycle_length;
std::sort(neighbours_recalc.begin(), neighbours_recalc.end());
CHECK(neighbours_recalc == neighbours);
}
const auto number_of_vertices = ndata.get_number_of_nonisolated_vertices();
CHECK(number_of_vertices == cycle_length);
// Now, edge functions
for (VertexWSM ii = 0; ii < cycle_length; ++ii) {
for (VertexWSM jj = 0; jj < cycle_length; ++jj) {
const auto edge_weight_opt = ndata.get_edge_weight_opt(ii, jj);
// Is i-j == +/-1 (mod cycle length)??
const auto diff = ((ii + cycle_length) - jj) % cycle_length;
if (diff == 1 || diff + 1 == cycle_length) {
CHECK(edge_weight_opt);
CHECK(edge_weight_opt.value() == ii + jj);
} else {
CHECK(!edge_weight_opt);
}
}
}
// Nonexistent vertices
for (VertexWSM ii = 0; ii < cycle_length + 5; ++ii) {
for (VertexWSM jj = cycle_length; jj < cycle_length + 10; ++jj) {
CHECK(!ndata.get_edge_weight_opt(ii, jj));
}
}
// Also, test near neighbours.
NearNeighboursData near_neighbours_data(ndata);
for (VertexWSM ii = 0; ii < cycle_length; ++ii) {
for (unsigned distance = 0; distance <= 8; ++distance) {
const auto count_within_d =
near_neighbours_data.get_n_vertices_up_to_distance(ii, distance);
switch (distance) {
case 0:
CHECK(count_within_d == 0);
break;
case 1:
CHECK(count_within_d == 2);
break;
default:
CHECK(count_within_d == 4);
break;
}
if (distance < 2) {
continue;
}
const auto& v_at_distance =
near_neighbours_data.get_vertices_at_exact_distance(ii, distance);
REQUIRE(v_at_distance.size() == number_of_vertices);
if (distance > 2) {
CHECK(v_at_distance.none());
continue;
}
std::set<VertexWSM> v_set_at_distance;
TemporaryRefactorCode::set_domain_from_bitset(
v_set_at_distance, v_at_distance);
CHECK(v_set_at_distance.size() == 2);
for (auto v : v_set_at_distance) {
const unsigned route1_dist = ((cycle_length + ii) - v) % cycle_length;
const unsigned route2_dist =
(cycle_length - route1_dist) % cycle_length;
const unsigned shortest_distance = std::min(route1_dist, route2_dist);
CHECK(shortest_distance == 2);
}
}
}
}
static std::string to_string(const NeighboursData& ndata) {
std::stringstream ss;
const auto number_of_vertices = ndata.get_number_of_nonisolated_vertices();
ss << number_of_vertices << " vertices. Neighbours and weights:";
for (unsigned vv = 0; vv < number_of_vertices; ++vv) {
ss << "\nv=" << vv << ": [ ";
const std::vector<std::pair<VertexWSM, WeightWSM>>& data =
ndata.get_neighbours_and_weights(vv);
for (const std::pair<VertexWSM, WeightWSM>& entry : data) {
ss << entry.first << ";" << entry.second << " ";
}
ss << "]";
}
return ss.str();
}
SCENARIO("neighbours_data with invalid and simple input data") {
GraphEdgeWeights edge_weights;
CHECK_THROWS_AS(NeighboursData(edge_weights), std::runtime_error);
edge_weights[std::make_pair<VertexWSM, VertexWSM>(0, 0)] = 1;
CHECK_THROWS_AS(NeighboursData(edge_weights), std::runtime_error);
edge_weights.clear();
edge_weights[get_edge(0, 1)] = 1;
// v1>v2 is allowed...
edge_weights[std::make_pair<VertexWSM, VertexWSM>(2, 0)] = 2;
const NeighboursData ndata1(edge_weights);
const auto ndata1_str = to_string(ndata1);
CHECK(
ndata1_str ==
"3 vertices. Neighbours and weights:"
"\nv=0: [ 1;1 2;2 ]"
"\nv=1: [ 0;1 ]"
"\nv=2: [ 0;2 ]");
// Inconsistent edge weights are not allowed...
edge_weights[std::make_pair<VertexWSM, VertexWSM>(0, 2)] = 3;
REQUIRE(edge_weights.size() == 3);
CHECK_THROWS_AS(NeighboursData(edge_weights), std::runtime_error);
//...but duplicate data IS allowed, as long as it's not inconsistent
edge_weights[std::make_pair<VertexWSM, VertexWSM>(0, 2)] = 2;
const NeighboursData ndata2(edge_weights);
CHECK(ndata1_str == to_string(ndata2));
}
} // namespace WeightedSubgraphMonomorphism
} // namespace tket
| tket/libs/tkwsm/test/src/GraphTheoretic/test_NeighboursData.cpp/0 | {
"file_path": "tket/libs/tkwsm/test/src/GraphTheoretic/test_NeighboursData.cpp",
"repo_id": "tket",
"token_count": 2438
} | 357 |
// Copyright 2019-2024 Cambridge Quantum Computing
//
// 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.
#include <catch2/catch_test_macros.hpp>
#include <stdexcept>
#include <tkwsm/Searching/NodesRawData.hpp>
namespace tket {
namespace WeightedSubgraphMonomorphism {
SCENARIO("Test search node string functions") {
DomainInitialiser::InitialDomains initial_domains(4);
for (auto& domain_bitset : initial_domains) {
domain_bitset.resize(100);
}
initial_domains[0].set(0);
initial_domains[0].set(1);
initial_domains[3].set(2);
CHECK_THROWS_AS(NodesRawData(initial_domains, 100), std::runtime_error);
initial_domains[1].set(17);
initial_domains[2].set(77);
initial_domains[2].set(88);
NodesRawData nodes_raw_data(initial_domains, 100);
auto& node_data = nodes_raw_data.nodes_data[0];
node_data.new_assignments.emplace_back(0, 0);
CHECK(
node_data.str() ==
"Has 3 ass.: [ 1:17 3:2 0:0 ]; sc.prod 0; p-edge weight 0");
CHECK(
nodes_raw_data.domains_data.at(3).str() ==
"\n node_index=0, Dom: [ 2 ]\n");
node_data.nogood = true;
CHECK(
node_data.str() ==
"##NOGOOD!## Has 3 ass.: [ 1:17 3:2 0:0 ]; sc.prod 0; p-edge weight 0");
}
} // namespace WeightedSubgraphMonomorphism
} // namespace tket
| tket/libs/tkwsm/test/src/Searching/test_NodesRawData.cpp/0 | {
"file_path": "tket/libs/tkwsm/test/src/Searching/test_NodesRawData.cpp",
"repo_id": "tket",
"token_count": 646
} | 358 |
// Copyright 2019-2024 Cambridge Quantum Computing
//
// 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.
#include "ProblemGeneration.hpp"
#include <catch2/catch_test_macros.hpp>
#include "SquareGridGeneration.hpp"
namespace tket {
namespace WeightedSubgraphMonomorphism {
GraphEdgeWeights ProblemGeneration::get_target_graph_for_encoded_square_grid(
const EncodedSquareGrid& encoding) {
REQUIRE(encoding.size() >= 4);
for (unsigned ii = 1; ii <= 3; ++ii) {
// force the edge weights to be strictly increasing.
REQUIRE(encoding[ii] > 1);
if (ii > 1) {
REQUIRE(encoding[ii] > encoding[ii - 1]);
}
}
// Make everything comfortably small for 32 bits, etc.
REQUIRE(encoding[3] <= 100000);
SquareGrid grid;
grid.width = 4;
grid.height = 4;
std::uint_fast64_t edges_encoding = encoding[0];
const auto set_weights = [&edges_encoding,
&encoding](std::vector<WeightWSM>& weights) {
weights.resize(20);
for (unsigned ii = 0; ii < weights.size(); ++ii) {
const auto code = edges_encoding & 3;
const WeightWSM weight = (code == 0) ? 1 : encoding[code];
weights[ii] = weight;
edges_encoding >>= 2;
}
};
set_weights(grid.horiz_weights);
set_weights(grid.vert_weights);
return grid.get_graph_edge_weights();
}
} // namespace WeightedSubgraphMonomorphism
} // namespace tket
| tket/libs/tkwsm/test/src/TestUtils/ProblemGeneration.cpp/0 | {
"file_path": "tket/libs/tkwsm/test/src/TestUtils/ProblemGeneration.cpp",
"repo_id": "tket",
"token_count": 647
} | 359 |
[project]
name = "examples"
version = "0.0.1"
dependencies = ["pytket"]
[project.scripts]
entanglement = "examples.basic_circuits:entanglement_circuit"
teleport = "examples.basic_circuits:teleport_circuit"
| tket/nix-support/example-flake-project/pyproject.toml/0 | {
"file_path": "tket/nix-support/example-flake-project/pyproject.toml",
"repo_id": "tket",
"token_count": 77
} | 360 |
// Copyright 2019-2024 Cambridge Quantum Computing
//
// 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.
#define STR(x) #x
#include <pybind11/pybind11.h>
#include <bitset>
#include <utility>
#include "UnitRegister.hpp"
#include "add_gate.hpp"
#include "tket/Circuit/Circuit.hpp"
#include "tket/Ops/ClassicalOps.hpp"
#include "typecast.hpp"
namespace py = pybind11;
namespace tket {
static void apply_classical_op_to_registers(
Circuit &circ, const std::shared_ptr<const ClassicalEvalOp> &op,
const std::vector<BitRegister> ®isters, const py::kwargs &kwargs) {
unsigned n_op_args = registers.size();
const unsigned n_bits = std::min_element(
registers.begin(), registers.end(),
[](const BitRegister &i, const BitRegister &j) {
return i.size() < j.size();
})
->size();
std::vector<Bit> args(n_bits * n_op_args);
for (unsigned i = 0; i < n_bits; i++) {
for (unsigned j = 0; j < n_op_args; j++) {
args[n_op_args * i + j] = registers[j][i];
}
}
std::shared_ptr<MultiBitOp> mbop = std::make_shared<MultiBitOp>(op, n_bits);
add_gate_method<Bit>(&circ, mbop, args, kwargs);
}
void init_circuit_add_classical_op(
py::class_<Circuit, std::shared_ptr<Circuit>> &c) {
c.def(
"add_c_transform",
[](Circuit &circ, const py::tket_custom::SequenceVec<_tket_uint_t> &values,
const py::tket_custom::SequenceVec<unsigned> &args, const std::string &name,
const py::kwargs &kwargs) {
unsigned n_args = args.size();
std::shared_ptr<ClassicalTransformOp> op =
std::make_shared<ClassicalTransformOp>(n_args, values, name);
return add_gate_method<unsigned>(&circ, op, args, kwargs);
},
"Appends a purely classical transformation, defined by a table of "
"values, to "
"the end of the circuit."
"\n\n:param values: table of values: bit :math:`j` (in little-endian "
"order) of the "
"term indexed by :math:`sum_i a_i 2^i` is output :math:`j` of the "
"transform "
"applied to inputs :math:`(a_i)`."
"\n:param args: bits to which the transform is applied"
"\n:param name: operation name"
"\n:param kwargs: additional arguments passed to `add_gate_method` ."
" Allowed parameters are `opgroup`, `condition` , `condition_bits`,"
" `condition_value`"
"\n:return: the new :py:class:`Circuit`",
py::arg("values"), py::arg("args"),
py::arg("name") = "ClassicalTransform")
.def(
"add_c_transform",
[](Circuit &circ, const py::tket_custom::SequenceVec<_tket_uint_t> &values,
const py::tket_custom::SequenceVec<Bit> &args, const std::string &name,
const py::kwargs &kwargs) {
unsigned n_args = args.size();
std::shared_ptr<ClassicalTransformOp> op =
std::make_shared<ClassicalTransformOp>(n_args, values, name);
return add_gate_method<Bit>(&circ, op, args, kwargs);
},
"See :py:meth:`add_c_transform`.", py::arg("values"), py::arg("args"),
py::arg("name") = "ClassicalTransform")
.def(
"_add_wasm",
[](Circuit &circ, const std::string &funcname,
const std::string &wasm_uid,
const py::tket_custom::SequenceVec<unsigned> &width_i_parameter,
const py::tket_custom::SequenceVec<unsigned> &width_o_parameter,
const py::tket_custom::SequenceVec<unsigned> &args,
const py::tket_custom::SequenceVec<unsigned> &wasm_wire_args,
const py::kwargs &kwargs) -> Circuit * {
unsigned n_args = args.size();
unsigned ww_n = wasm_wire_args.size();
std::shared_ptr<WASMOp> op = std::make_shared<WASMOp>(
n_args, ww_n, width_i_parameter, width_o_parameter, funcname, wasm_uid);
std::vector<UnitID> new_args;
for (auto i : args) {
new_args.push_back(Bit(i));
}
for (auto i : wasm_wire_args) {
new_args.push_back(WasmState(i));
}
return add_gate_method<UnitID>(&circ, op, new_args, kwargs);
},
"Add a classical function call from a wasm file to the circuit. "
"\n\n:param funcname: name of the function that is called"
"\n:param wasm_uid: unit id to identify the wasm file"
"\n:param width_i_parameter: list of the number of bits in the input "
"variables"
"\n:param width_o_parameter: list of the number of bits in the output "
"variables"
"\n:param args: vector of circuit bits the wasm op should be added to"
"\n:param wasm_wire_args: vector of circuit wasmwires the wasm op should be added to"
"\n:param kwargs: additional arguments passed to `add_gate_method` ."
" Allowed parameters are `opgroup`, `condition` , `condition_bits`,"
" `condition_value`"
"\n:return: the new :py:class:`Circuit`",
py::arg("funcname"), py::arg("wasm_uid"), py::arg("width_i_parameter"),
py::arg("width_o_parameter"), py::arg("args"), py::arg("wasm_wire_args"))
.def(
"_add_wasm",
[](Circuit &circ, const std::string &funcname,
const std::string &wasm_uid,
const py::tket_custom::SequenceVec<unsigned> &width_i_parameter,
const py::tket_custom::SequenceVec<unsigned> &width_o_parameter,
const py::tket_custom::SequenceVec<Bit> &args,
const py::tket_custom::SequenceVec<unsigned> &wasm_wire_args,
const py::kwargs &kwargs) -> Circuit * {
unsigned n_args = args.size();
unsigned ww_n = wasm_wire_args.size();
std::shared_ptr<WASMOp> op = std::make_shared<WASMOp>(
n_args, ww_n, width_i_parameter, width_o_parameter, funcname, wasm_uid);
std::vector<UnitID> new_args;
for (const auto& b : args) {
new_args.push_back(b);
}
for (auto i : wasm_wire_args) {
new_args.push_back(WasmState(i));
}
return add_gate_method<UnitID>(&circ, op, new_args, kwargs);
},
"Add a classical function call from a wasm file to the circuit. "
"\n\n:param funcname: name of the function that is called"
"\n:param wasm_uid: unit id to identify the wasm file"
"\n:param width_i_parameter: list of the number of bits in the input "
"variables"
"\n:param width_o_parameter: list of the number of bits in the output "
"variables"
"\n:param args: vector of circuit bits the wasm op should be added to"
"\n:param kwargs: additional arguments passed to `add_gate_method` ."
" Allowed parameters are `opgroup`, `condition` , `condition_bits`,"
" `condition_value`"
"\n:return: the new :py:class:`Circuit`",
py::arg("funcname"), py::arg("wasm_uid"), py::arg("width_i_parameter"),
py::arg("width_o_parameter"), py::arg("args"), py::arg("wasm_wire_args"))
.def(
"_add_wasm",
[](Circuit &circ, const std::string &funcname,
const std::string &wasm_uid,
const py::tket_custom::SequenceVec<BitRegister> &list_reg_in,
const py::tket_custom::SequenceVec<BitRegister> &list_reg_out,
const py::tket_custom::SequenceVec<unsigned> &wasm_wire_args,
const py::kwargs &kwargs) -> Circuit * {
unsigned n_args = 0;
unsigned ww_n = wasm_wire_args.size();
for (const auto& r : list_reg_in) {
n_args += r.size();
}
for (const auto& r : list_reg_out) {
n_args += r.size();
}
std::vector<Bit> args(n_args);
std::vector<unsigned> width_i_parameter(list_reg_in.size());
std::vector<unsigned> width_o_parameter(list_reg_out.size());
unsigned i = 0;
unsigned j = 0;
for (const auto& r : list_reg_in) {
width_i_parameter[i] = r.size();
for (unsigned k = 0; k < r.size(); ++k) {
args[j] = r[k];
++j;
}
++i;
}
i = 0;
for (const auto& r : list_reg_out) {
width_o_parameter[i] = r.size();
for (unsigned k = 0; k < r.size(); ++k) {
args[j] = r[k];
++j;
}
++i;
}
std::shared_ptr<WASMOp> op = std::make_shared<WASMOp>(
n_args, ww_n, width_i_parameter, width_o_parameter, funcname, wasm_uid);
std::vector<UnitID> new_args;
new_args.reserve(args.size());
for (const auto& b : args) {
new_args.push_back(b);
}
for (auto ii : wasm_wire_args) {
new_args.push_back(WasmState(ii));
}
return add_gate_method<UnitID>(&circ, op, new_args, kwargs);
},
"Add a classical function call from a wasm file to the circuit. "
"\n\n:param funcname: name of the function that is called"
"\n:param wasm_uid: unit id to identify the wasm file"
"\n:param list_reg_in: list of the classical registers in the "
"circuit used as inputs"
"\n:param list_reg_out: list of the classical registers in the "
"circuit used as outputs"
"\n:param kwargs: additional arguments passed to `add_gate_method` ."
" Allowed parameters are `opgroup`, `condition` , `condition_bits`,"
" `condition_value`"
"\n:return: the new :py:class:`Circuit`",
py::arg("funcname"), py::arg("wasm_uid"), py::arg("list_reg_in"),
py::arg("list_reg_out"), py::arg("wasm_wire_args"))
.def(
"add_c_setbits",
[](Circuit &circ, const py::tket_custom::SequenceVec<bool> &values,
const py::tket_custom::SequenceVec<unsigned>& args, const py::kwargs &kwargs) {
std::shared_ptr<SetBitsOp> op = std::make_shared<SetBitsOp>(values);
return add_gate_method<unsigned>(&circ, op, args, kwargs);
},
"Appends an operation to set some bit values."
"\n\n:param values: values to set"
"\n:param args: bits to set"
"\n:param kwargs: additional arguments passed to `add_gate_method` ."
" Allowed parameters are `opgroup`, `condition` , `condition_bits`,"
" `condition_value`"
"\n:return: the new :py:class:`Circuit`",
py::arg("values"), py::arg("args"))
.def(
"add_c_setbits",
[](Circuit &circ, const py::tket_custom::SequenceVec<bool> &values,
const py::tket_custom::SequenceVec<Bit>& args, const py::kwargs &kwargs) {
std::shared_ptr<SetBitsOp> op = std::make_shared<SetBitsOp>(values);
return add_gate_method<Bit>(&circ, op, args, kwargs);
},
"See :py:meth:`add_c_setbits`.", py::arg("values"), py::arg("args"))
.def(
"add_c_setreg",
[](Circuit &circ, const _tket_uint_t value, const BitRegister ®,
const py::kwargs &kwargs) {
if (reg.size() < _TKET_REG_WIDTH && value >> reg.size() != 0) {
throw std::runtime_error("Value " + std::to_string(value) + " cannot be held on a " + std::to_string(reg.size()) + "-bit register.");
}
auto bs = std::bitset<_TKET_REG_WIDTH>(value);
std::vector<Bit> args(reg.size());
std::vector<bool> vals(reg.size());
for (unsigned i = 0; i < reg.size(); i++) {
args[i] = reg[i];
vals[i] = (i < _TKET_REG_WIDTH) && bs[i];
}
std::shared_ptr<SetBitsOp> op = std::make_shared<SetBitsOp>(vals);
return add_gate_method<Bit>(&circ, op, args, kwargs);
},
"Set a classical register to an unsigned integer value. The "
"little-endian bitwise representation of the integer is truncated to "
"the register size, up to " STR(_TKET_REG_WIDTH) " bit width. It is "
"zero-padded if the width of the register is greater than " STR(_TKET_REG_WIDTH) ".",
py::arg("value"), py::arg("arg"))
.def(
"add_c_copybits",
[](Circuit &circ, const py::tket_custom::SequenceVec<unsigned> &args_in,
const py::tket_custom::SequenceVec<unsigned> &args_out, const py::kwargs &kwargs) {
unsigned n_args_in = args_in.size();
std::shared_ptr<CopyBitsOp> op =
std::make_shared<CopyBitsOp>(n_args_in);
std::vector<unsigned> args = args_in;
args.insert(args.end(), args_out.begin(), args_out.end());
return add_gate_method<unsigned>(&circ, op, args, kwargs);
},
"Appends a classical copy operation"
"\n\n:param args_in: source bits"
"\n:param args_out: destination bits"
"\n:param kwargs: additional arguments passed to `add_gate_method` ."
" Allowed parameters are `opgroup`, `condition` , `condition_bits`,"
" `condition_value`"
"\n:return: the new :py:class:`Circuit`",
py::arg("args_in"), py::arg("args_out"))
.def(
"add_c_copybits",
[](Circuit &circ, const py::tket_custom::SequenceVec<Bit> &args_in,
const py::tket_custom::SequenceVec<Bit> &args_out, const py::kwargs &kwargs) {
unsigned n_args_in = args_in.size();
std::shared_ptr<CopyBitsOp> op =
std::make_shared<CopyBitsOp>(n_args_in);
std::vector<Bit> args = args_in;
args.insert(args.end(), args_out.begin(), args_out.end());
return add_gate_method<Bit>(&circ, op, args, kwargs);
},
"See :py:meth:`add_c_copybits`.", py::arg("args_in"),
py::arg("args_out"))
.def(
"add_c_copyreg",
[](Circuit &circ, const BitRegister &input_reg,
const BitRegister &output_reg, const py::kwargs &kwargs) {
const unsigned width =
std::min(input_reg.size(), output_reg.size());
std::shared_ptr<CopyBitsOp> op =
std::make_shared<CopyBitsOp>(width);
std::vector<Bit> args(width * 2);
for (unsigned i = 0; i < width; i++) {
args[i] = input_reg[i];
args[i + width] = output_reg[i];
}
return add_gate_method<Bit>(&circ, op, args, kwargs);
},
"Copy a classical register to another. Copying is truncated to the "
"size of the smaller of the two registers.",
py::arg("input_reg"), py::arg("output_reg"))
.def(
"add_c_predicate",
[](Circuit &circ, const py::tket_custom::SequenceVec<bool> &values,
const py::tket_custom::SequenceVec<unsigned> &args_in, unsigned arg_out,
const std::string &name, const py::kwargs &kwargs) {
unsigned n_args_in = args_in.size();
std::shared_ptr<ExplicitPredicateOp> op =
std::make_shared<ExplicitPredicateOp>(n_args_in, values, name);
std::vector<unsigned> args = args_in;
args.push_back(arg_out);
return add_gate_method<unsigned>(&circ, op, args, kwargs);
},
"Appends a classical predicate, defined by a truth table, to the end "
"of the "
"circuit."
"\n\n:param values: table of values: the term indexed by "
":math:`sum_i a_i 2^i` "
"is the value of the predicate for inputs :math:`(a_i)`."
"\n:param args_in: input bits for the predicate"
"\n:param arg_out: output bit, distinct from all inputs",
"\n:param name: operation name"
"\n:param kwargs: additional arguments passed to `add_gate_method` ."
" Allowed parameters are `opgroup`, `condition` , `condition_bits`,"
" `condition_value`"
"\n:return: the new :py:class:`Circuit`",
py::arg("values"), py::arg("args_in"), py::arg("arg_out"),
py::arg("name") = "ExplicitPredicate")
.def(
"add_c_predicate",
[](Circuit &circ, const py::tket_custom::SequenceVec<bool> &values,
const py::tket_custom::SequenceVec<Bit> &args_in, const Bit& arg_out,
const std::string &name, const py::kwargs &kwargs) {
unsigned n_args_in = args_in.size();
std::shared_ptr<ExplicitPredicateOp> op =
std::make_shared<ExplicitPredicateOp>(n_args_in, values, name);
std::vector<Bit> args = args_in;
args.push_back(arg_out);
return add_gate_method<Bit>(&circ, op, args, kwargs);
},
"See :py:meth:`add_c_predicate`.", py::arg("values"),
py::arg("args_in"), py::arg("arg_out"),
py::arg("name") = "ExplicitPredicate")
.def(
"add_c_modifier",
[](Circuit &circ, const py::tket_custom::SequenceVec<bool> &values,
const py::tket_custom::SequenceVec<unsigned> &args_in, unsigned arg_inout,
const std::string &name, const py::kwargs &kwargs) {
unsigned n_args_in = args_in.size();
std::shared_ptr<ExplicitModifierOp> op =
std::make_shared<ExplicitModifierOp>(n_args_in, values, name);
std::vector<unsigned> args = args_in;
args.push_back(arg_inout);
return add_gate_method<unsigned>(&circ, op, args, kwargs);
},
"Appends a classical modifying operation, defined by a truth table, "
"to the "
"end of the circuit."
"\n\n:param values: table of values: the term indexed by "
":math:`sum_i a_i 2^i` "
"is the value of the predicate for inputs :math:`(a_i)`, where the "
"modified "
"bit is the last of the :math:`a_i`."
"\n:param args_in: input bits, excluding the modified bit"
"\n:param arg_out: modified bit",
"\n:param name: operation name"
"\n:param kwargs: additional arguments passed to `add_gate_method` ."
" Allowed parameters are `opgroup`, `condition` , `condition_bits`,"
" `condition_value`"
"\n:return: the new :py:class:`Circuit`",
py::arg("values"), py::arg("args_in"), py::arg("arg_inout"),
py::arg("name") = "ExplicitModifier")
.def(
"add_c_modifier",
[](Circuit &circ, const py::tket_custom::SequenceVec<bool> &values,
const py::tket_custom::SequenceVec<Bit> &args_in, const Bit& arg_inout,
const std::string &name, const py::kwargs &kwargs) {
unsigned n_args_in = args_in.size();
std::shared_ptr<ExplicitModifierOp> op =
std::make_shared<ExplicitModifierOp>(n_args_in, values, name);
std::vector<Bit> args = args_in;
args.push_back(arg_inout);
return add_gate_method<Bit>(&circ, op, args, kwargs);
},
"See :py:meth:`add_c_modifier`.", py::arg("values"),
py::arg("args_in"), py::arg("arg_inout"),
py::arg("name") = "ExplicitModifier")
.def(
"add_c_and",
[](Circuit &circ, unsigned arg0_in, unsigned arg1_in,
unsigned arg_out, const py::kwargs &kwargs) {
Op_ptr op;
std::vector<unsigned> args;
if (arg0_in == arg_out) {
op = AndWithOp();
args = {arg1_in, arg_out};
} else if (arg1_in == arg_out) {
op = AndWithOp();
args = {arg0_in, arg_out};
} else {
op = AndOp();
args = {arg0_in, arg1_in, arg_out};
}
return add_gate_method<unsigned>(&circ, op, args, kwargs);
},
"Appends a binary AND operation to the end of the circuit."
"\n\n:param arg0_in: first input bit"
"\n:param arg1_in: second input bit"
"\n:param arg_out: output bit"
"\n:param kwargs: additional arguments passed to `add_gate_method` ."
" Allowed parameters are `opgroup`, `condition` , `condition_bits`,"
" `condition_value`"
"\n:return: the new :py:class:`Circuit`",
py::arg("arg0_in"), py::arg("arg1_in"), py::arg("arg_out"))
.def(
"add_c_and",
[](Circuit &circ, const Bit& arg0_in, const Bit& arg1_in, const Bit& arg_out,
const py::kwargs &kwargs) {
Op_ptr op;
std::vector<Bit> args;
if (arg0_in == arg_out) {
op = AndWithOp();
args = {arg1_in, arg_out};
} else if (arg1_in == arg_out) {
op = AndWithOp();
args = {arg0_in, arg_out};
} else {
op = AndOp();
args = {arg0_in, arg1_in, arg_out};
}
return add_gate_method<Bit>(&circ, op, args, kwargs);
},
"See :py:meth:`add_c_and`.", py::arg("arg0_in"), py::arg("arg1_in"),
py::arg("arg_out"))
.def(
"add_c_or",
[](Circuit &circ, unsigned arg0_in, unsigned arg1_in,
unsigned arg_out, const py::kwargs &kwargs) {
Op_ptr op;
std::vector<unsigned> args;
if (arg0_in == arg_out) {
op = OrWithOp();
args = {arg1_in, arg_out};
} else if (arg1_in == arg_out) {
op = OrWithOp();
args = {arg0_in, arg_out};
} else {
op = OrOp();
args = {arg0_in, arg1_in, arg_out};
}
return add_gate_method<unsigned>(&circ, op, args, kwargs);
},
"Appends a binary OR operation to the end of the circuit."
"\n\n:param arg0_in: first input bit"
"\n:param arg1_in: second input bit"
"\n:param arg_out: output bit"
"\n:param kwargs: additional arguments passed to `add_gate_method` ."
" Allowed parameters are `opgroup`, `condition` , `condition_bits`,"
" `condition_value`"
"\n:return: the new :py:class:`Circuit`",
py::arg("arg0_in"), py::arg("arg1_in"), py::arg("arg_out"))
.def(
"add_c_or",
[](Circuit &circ, const Bit& arg0_in, const Bit& arg1_in, const Bit& arg_out,
const py::kwargs &kwargs) {
Op_ptr op;
std::vector<Bit> args;
if (arg0_in == arg_out) {
op = OrWithOp();
args = {arg1_in, arg_out};
} else if (arg1_in == arg_out) {
op = OrWithOp();
args = {arg0_in, arg_out};
} else {
op = OrOp();
args = {arg0_in, arg1_in, arg_out};
}
return add_gate_method<Bit>(&circ, op, args, kwargs);
},
"See :py:meth:`add_c_or`.", py::arg("arg0_in"), py::arg("arg1_in"),
py::arg("arg_out"))
.def(
"add_c_xor",
[](Circuit &circ, unsigned arg0_in, unsigned arg1_in,
unsigned arg_out, const py::kwargs &kwargs) {
Op_ptr op;
std::vector<unsigned> args;
if (arg0_in == arg_out) {
op = XorWithOp();
args = {arg1_in, arg_out};
} else if (arg1_in == arg_out) {
op = XorWithOp();
args = {arg0_in, arg_out};
} else {
op = XorOp();
args = {arg0_in, arg1_in, arg_out};
}
return add_gate_method<unsigned>(&circ, op, args, kwargs);
},
"Appends a binary XOR operation to the end of the circuit."
"\n\n:param arg0_in: first input bit"
"\n:param arg1_in: second input bit"
"\n:param arg_out: output bit"
"\n:param kwargs: additional arguments passed to `add_gate_method` ."
" Allowed parameters are `opgroup`, `condition` , `condition_bits`,"
" `condition_value`"
"\n:return: the new :py:class:`Circuit`",
py::arg("arg0_in"), py::arg("arg1_in"), py::arg("arg_out"))
.def(
"add_c_xor",
[](Circuit &circ, const Bit& arg0_in, const Bit& arg1_in, const Bit& arg_out,
const py::kwargs &kwargs) {
Op_ptr op;
std::vector<Bit> args;
if (arg0_in == arg_out) {
op = XorWithOp();
args = {arg1_in, arg_out};
} else if (arg1_in == arg_out) {
op = XorWithOp();
args = {arg0_in, arg_out};
} else {
op = XorOp();
args = {arg0_in, arg1_in, arg_out};
}
return add_gate_method<Bit>(&circ, op, args, kwargs);
},
"See :py:meth:`add_c_xor`.", py::arg("arg0_in"), py::arg("arg1_in"),
py::arg("arg_out"))
.def(
"add_c_not",
[](Circuit &circ, unsigned arg_in, unsigned arg_out,
const py::kwargs &kwargs) {
return add_gate_method<unsigned>(
&circ, NotOp(), {arg_in, arg_out}, kwargs);
},
"Appends a NOT operation to the end of the circuit."
"\n\n:param arg_in: input bit"
"\n:param arg_out: output bit"
"\n:param kwargs: additional arguments passed to `add_gate_method` ."
" Allowed parameters are `opgroup`, `condition` , `condition_bits`,"
" `condition_value`"
"\n:return: the new :py:class:`Circuit`",
py::arg("arg_in"), py::arg("arg_out"))
.def(
"add_c_not",
[](Circuit &circ, Bit arg_in, Bit arg_out, const py::kwargs &kwargs) {
return add_gate_method<Bit>(
&circ, NotOp(), {std::move(arg_in), std::move(arg_out)}, kwargs);
},
"See :py:meth:`add_c_not`.", py::arg("arg_in"), py::arg("arg_out"))
.def(
"add_c_range_predicate",
[](Circuit &circ, _tket_uint_t a, _tket_uint_t b,
const py::tket_custom::SequenceVec<unsigned> &args_in, unsigned arg_out,
const py::kwargs &kwargs) {
unsigned n_args_in = args_in.size();
std::shared_ptr<RangePredicateOp> op =
std::make_shared<RangePredicateOp>(n_args_in, a, b);
std::vector<unsigned> args = args_in;
args.push_back(arg_out);
return add_gate_method<unsigned>(&circ, op, args, kwargs);
},
"Appends a range-predicate operation to the end of the circuit."
"\n\n:param minval: lower bound of input in little-endian encoding"
"\n:param maxval: upper bound of input in little-endian encoding"
"\n:param args_in: input bits"
"\n:param arg_out: output bit (distinct from input bits)"
"\n:param kwargs: additional arguments passed to `add_gate_method` ."
" Allowed parameters are `opgroup`, `condition` , `condition_bits`,"
" `condition_value`"
"\n:return: the new :py:class:`Circuit`",
py::arg("minval"), py::arg("maxval"), py::arg("args_in"),
py::arg("arg_out"))
.def(
"add_c_range_predicate",
[](Circuit &circ, _tket_uint_t a, _tket_uint_t b,
const py::tket_custom::SequenceVec<Bit> &args_in, const Bit& arg_out,
const py::kwargs &kwargs) {
unsigned n_args_in = args_in.size();
std::shared_ptr<RangePredicateOp> op =
std::make_shared<RangePredicateOp>(n_args_in, a, b);
std::vector<Bit> args = args_in;
args.push_back(arg_out);
return add_gate_method<Bit>(&circ, op, args, kwargs);
},
"Appends a range-predicate operation to the end of the circuit."
"\n\n:param minval: lower bound of input in little-endian encoding"
"\n:param maxval: upper bound of input in little-endian encoding"
"\n:param args_in: input bits"
"\n:param arg_out: output bit (distinct from input bits)"
"\n:param kwargs: additional arguments passed to `add_gate_method` ."
" Allowed parameters are `opgroup`, `condition` , `condition_bits`,"
" `condition_value`"
"\n:return: the new :py:class:`Circuit`",
py::arg("minval"), py::arg("maxval"), py::arg("args_in"),
py::arg("arg_out"))
.def(
"add_c_and_to_registers",
[](Circuit &circ, const BitRegister ®0_in,
const BitRegister ®1_in, const BitRegister ®_out,
const py::kwargs &kwargs) {
if (reg0_in == reg_out) {
apply_classical_op_to_registers(
circ, AndWithOp(), {reg1_in, reg_out}, kwargs);
} else if (reg1_in == reg_out) {
apply_classical_op_to_registers(
circ, AndWithOp(), {reg0_in, reg_out}, kwargs);
} else {
apply_classical_op_to_registers(
circ, AndOp(), {reg0_in, reg1_in, reg_out}, kwargs);
}
return circ;
},
"Applies bitwise AND to linear registers."
"\n\nThe operation is applied to the bits with indices 0, 1, 2, ... "
"in "
"each register, up to the size of the smallest register."
"\n\n:param reg0_in: first input register"
"\n:param reg1_in: second input register"
"\n:param reg_out: output register"
"\n:param kwargs: additional arguments passed to `add_gate_method` ."
" Allowed parameters are `opgroup`, `condition` , `condition_bits`,"
" `condition_value`"
"\n:return: the new :py:class:`Circuit`",
py::arg("reg0_in"), py::arg("reg1_in"), py::arg("reg_out"))
.def(
"add_c_or_to_registers",
[](Circuit &circ, const BitRegister ®0_in,
const BitRegister ®1_in, const BitRegister ®_out,
const py::kwargs &kwargs) {
if (reg0_in == reg_out) {
apply_classical_op_to_registers(
circ, OrWithOp(), {reg1_in, reg_out}, kwargs);
} else if (reg1_in == reg_out) {
apply_classical_op_to_registers(
circ, OrWithOp(), {reg0_in, reg_out}, kwargs);
} else {
apply_classical_op_to_registers(
circ, OrOp(), {reg0_in, reg1_in, reg_out}, kwargs);
}
return circ;
},
"Applies bitwise OR to linear registers."
"\n\nThe operation is applied to the bits with indices 0, 1, 2, ... "
"in "
"each register, up to the size of the smallest register."
"\n\n:param reg0_in: first input register"
"\n:param reg1_in: second input register"
"\n:param reg_out: output register"
"\n:param kwargs: additional arguments passed to `add_gate_method` ."
" Allowed parameters are `opgroup`, `condition` , `condition_bits`,"
" `condition_value`"
"\n:return: the new :py:class:`Circuit`",
py::arg("reg0_in"), py::arg("reg1_in"), py::arg("reg_out"))
.def(
"add_c_xor_to_registers",
[](Circuit &circ, const BitRegister ®0_in,
const BitRegister ®1_in, const BitRegister ®_out,
const py::kwargs &kwargs) {
if (reg0_in == reg_out) {
apply_classical_op_to_registers(
circ, XorWithOp(), {reg1_in, reg_out}, kwargs);
} else if (reg1_in == reg_out) {
apply_classical_op_to_registers(
circ, XorWithOp(), {reg0_in, reg_out}, kwargs);
} else {
apply_classical_op_to_registers(
circ, XorOp(), {reg0_in, reg1_in, reg_out}, kwargs);
}
return circ;
},
"Applies bitwise XOR to linear registers."
"\n\nThe operation is applied to the bits with indices 0, 1, 2, ... "
"in "
"each register, up to the size of the smallest register."
"\n\n:param reg0_in: first input register"
"\n:param reg1_in: second input register"
"\n:param reg_out: output register"
"\n:param kwargs: additional arguments passed to `add_gate_method` ."
" Allowed parameters are `opgroup`, `condition` , `condition_bits`,"
" `condition_value`"
"\n:return: the new :py:class:`Circuit`",
py::arg("reg0_in"), py::arg("reg1_in"), py::arg("reg_out"))
.def(
"add_c_not_to_registers",
[](Circuit &circ, const BitRegister ®_in,
const BitRegister ®_out, const py::kwargs &kwargs) {
apply_classical_op_to_registers(
circ, NotOp(), {reg_in, reg_out}, kwargs);
return circ;
},
"Applies bitwise NOT to linear registers."
"\n\nThe operation is applied to the bits with indices 0, 1, 2, ... "
"in "
"each register, up to the size of the smallest register."
"\n\n:param reg_in: input register"
"\n:param reg_out: name of output register"
"\n:param kwargs: additional arguments passed to `add_gate_method` ."
" Allowed parameters are `opgroup`, `condition` , `condition_bits`,"
" `condition_value`"
"\n:return: the new :py:class:`Circuit`",
py::arg("reg_in"), py::arg("reg_out"));
}
} // namespace tket
| tket/pytket/binders/circuit/Circuit/add_classical_op.cpp/0 | {
"file_path": "tket/pytket/binders/circuit/Circuit/add_classical_op.cpp",
"repo_id": "tket",
"token_count": 17113
} | 361 |
// Copyright 2019-2024 Cambridge Quantum Computing
//
// 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.
#include <pybind11/pybind11.h>
#include <tklog/TketLog.hpp>
namespace py = pybind11;
namespace tket {
PYBIND11_MODULE(logging, m) {
py::enum_<LogLevel>(m, "level")
.value("trace", LogLevel::Trace, "all logs")
.value("debug", LogLevel::Debug, "debug logs and above")
.value("info", LogLevel::Info, "informational logs and above")
.value("warn", LogLevel::Warn, "warnings and above")
.value("err", LogLevel::Err, "error and critical logs only (default)")
.value("critical", LogLevel::Critical, "critical logs only")
.value("off", LogLevel::Off, "no logs");
m.def(
"set_level", [](LogLevel level) { tket_log()->set_level(level); },
"Set the global logging level."
"\n\n:param log_level: Desired logging level",
py::arg("log_level"));
}
} // namespace tket
| tket/pytket/binders/logging.cpp/0 | {
"file_path": "tket/pytket/binders/logging.cpp",
"repo_id": "tket",
"token_count": 485
} | 362 |
# Makefile for Sphinx documentation
#
# You can set these variables from the command line.
SPHINXOPTS =
SPHINXBUILD = sphinx-build
SOURCEDIR = .
BUILDDIR = build
# Put it first so that "make" without argument is like "make help".
help:
@$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
.PHONY: help Makefile
# Catch-all target: route all unknown targets to Sphinx using the new
# "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS).
%: Makefile
@$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
find build/html/ -type f -name "*.html" | xargs sed -i 's/pytket._tket/pytket/g'
sed -i 's/pytket._tket/pytket/g' build/html/searchindex.js
# for local builds on mac (mac sed is slightly different)
html-mac:
@$(SPHINXBUILD) -M html "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
find build/html/ -type f -name "*.html" | xargs sed -e 's/pytket._tket/pytket/g' -i ""
sed -e 's/pytket._tket/pytket/g' -i "" build/html/searchindex.js
| tket/pytket/docs/Makefile/0 | {
"file_path": "tket/pytket/docs/Makefile",
"repo_id": "tket",
"token_count": 436
} | 363 |
pytket
======
``pytket`` is a python module for interfacing with tket, a quantum computing toolkit and optimising compiler developed by `Quantinuum`_. We currently support circuits and device architectures from
`numerous providers <https://tket.quantinuum.com/api-docs/extensions>`_, allowing the
tket tools to be used in conjunction with projects on their platforms.
``pytket`` is available for Python 3.10, 3.11 and 3.12, on Linux, MacOS and
Windows. To install, run
::
pip install pytket
.. admonition:: Known issue installing pytket (Added 2nd August 2024)
:class: attention
Due to the removal of the `types-pkg_resources` package from pypi there will likely be issues when installing old versions of pytket. It is recommend to use pytket `>=1.31` where possible.
If you require using a version of pytket older than 1.31 then you can try the following.
`pip install types-pkg-resources==0.1.3 pytket==<set version>`
If you have issues installing ``pytket`` please visit the `installation troubleshooting <https://tket.quantinuum.com/api-docs/install.html>`_ page.
To use ``pytket``, you can simply import the appropriate modules into your python code or in an interactive Python notebook. We can build circuits directly using the ``pytket`` interface by creating a blank circuit and adding gates in the order we want to apply them.
See the `Getting Started`_ page for a basic tutorial on using
``pytket``. To get more in depth on features, see the `examples`_. See the `pytket user manual <https://tket.quantinuum.com/user-manual/index.html>`_ for an extensive introduction to ``pytket`` functionality and how to use it.
Extensions
~~~~~~~~~~
To use pytket in conjunction with other software libraries you must install a
separate python package for the relevant pytket extension.
Each extension adds either some new methods to the ``pytket`` package to convert between the circuit
representations, or some new backends to submit circuits to within ``pytket``.
Extensions are separate python packages can be installed using ``pip``. The installation command is ``pip install pytket-X`` where ``X`` is the name of the extension.
To install the ``pytket-quantinuum`` package use the following command.
::
pip install pytket-quantinuum
The extensions supported by tket are described
`here <https://tket.quantinuum.com/api-docs/extensions>`_.
How to cite
~~~~~~~~~~~
If you wish to cite tket in any academic publications, we generally recommend citing our `software overview paper <https://doi.org/10.1088/2058-9565/ab8e92>`_ for most cases.
If your work is on the topic of specific compilation tasks, it may be more appropriate to cite one of our other papers:
- `"On the qubit routing problem" <https://doi.org/10.4230/LIPIcs.TQC.2019.5>`_ for qubit placement (aka allocation, mapping) and routing (aka swap network insertion, connectivity solving).
- `"Phase Gadget Synthesis for Shallow Circuits" <https://doi.org/10.4204/EPTCS.318.13>`_ for representing exponentiated Pauli operators in the ZX calculus and their circuit decompositions.
- `"A Generic Compilation Strategy for the Unitary Coupled Cluster Ansatz" <https://arxiv.org/abs/2007.10515>`_ for sequencing of terms in Trotterisation and Pauli diagonalisation.
We are also keen for others to benchmark their compilation techniques against us. We recommend checking our `benchmark repository <https://github.com/CQCL/tket_benchmarking>`_ for examples on how to run basic benchmarks with the latest version of ``pytket``. Please list the release version of ``pytket`` with any benchmarks you give, and feel free to get in touch for any assistance needed in setting up fair and representative tests.
User Support
~~~~~~~~~~~~
If you have problems with the use of tket or you think that you have found a bug there are several ways to contact us:
- You can write an issue on `github <https://github.com/CQCL/tket/issues>`_ with details of the problem and we will pick that up. Github issues are the preferred way to report bugs with tket or request features. You can also have a look on that page to see if your problem has already been reported by someone else.
- We have a slack channel for community discussion and support. You can join by following `this link <https://tketusers.slack.com/join/shared_invite/zt-18qmsamj9-UqQFVdkRzxnXCcKtcarLRA#/shared-invite/email>`_
- Write an email to [email protected] and ask for help with your problem.
- There is also a tag on `quantum computing stack exchange <https://quantumcomputing.stackexchange.com/questions/tagged/pytket>`_ for questions relating to pytket.
We are really thankful for all help to fix bugs in tket. Usually you will get an answer from someone in the development team of tket soon.
LICENCE
~~~~~~~
Licensed under the `Apache 2 License <http://www.apache.org/licenses/LICENSE-2.0>`_.
.. _Getting Started: getting_started.html
.. _examples: https://tket.quantinuum.com/examples
.. _Quantinuum: https://www.quantinuum.com/
.. toctree::
:caption: Overview:
:maxdepth: 1
getting_started.rst
changelog.rst
install.rst
faqs.rst
.. toctree::
:caption: pytket extensions:
extensions.rst
.. toctree::
:caption: API Reference:
:maxdepth: 2
backends.rst
circuit.rst
unit_id.rst
pauli.rst
passes.rst
predicates.rst
partition.rst
qasm.rst
quipper.rst
architecture.rst
placement.rst
mapping.rst
tableau.rst
transform.rst
tailoring.rst
wasm.rst
zx.rst
utils.rst
logging.rst
config.rst
Indices and tables
==================
* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`
| tket/pytket/docs/index.rst/0 | {
"file_path": "tket/pytket/docs/index.rst",
"repo_id": "tket",
"token_count": 1738
} | 364 |
pytket.transform
==================================
.. automodule:: pytket._tket.transform
:members:
:special-members: __init__
| tket/pytket/docs/transform.rst/0 | {
"file_path": "tket/pytket/docs/transform.rst",
"repo_id": "tket",
"token_count": 42
} | 365 |
from __future__ import annotations
import pytket._tket.circuit
import pytket._tket.pauli
import typing
__all__ = ['GraphColourMethod', 'MeasurementBitMap', 'MeasurementSetup', 'PauliPartitionStrat', 'measurement_reduction', 'term_sequence']
class GraphColourMethod:
"""
Enum for available methods to perform graph colouring.
Members:
Lazy : Does not build the graph before performing the colouring; partitions while iterating through the Pauli tensors in the input order.
LargestFirst : Builds the graph and then greedily colours by iterating through the vertices, with the highest degree first.
Exhaustive : Builds the graph and then systematically checks all possibilities until it finds a colouring with the minimum possible number of colours. Such colourings need not be unique. Exponential time in the worst case, but often runs much faster.
"""
Exhaustive: typing.ClassVar[GraphColourMethod] # value = <GraphColourMethod.Exhaustive: 2>
LargestFirst: typing.ClassVar[GraphColourMethod] # value = <GraphColourMethod.LargestFirst: 1>
Lazy: typing.ClassVar[GraphColourMethod] # value = <GraphColourMethod.Lazy: 0>
__members__: typing.ClassVar[dict[str, GraphColourMethod]] # value = {'Lazy': <GraphColourMethod.Lazy: 0>, 'LargestFirst': <GraphColourMethod.LargestFirst: 1>, 'Exhaustive': <GraphColourMethod.Exhaustive: 2>}
def __eq__(self, other: typing.Any) -> bool:
...
def __getstate__(self) -> int:
...
def __hash__(self) -> int:
...
def __index__(self) -> int:
...
def __init__(self, value: int) -> None:
...
def __int__(self) -> int:
...
def __ne__(self, other: typing.Any) -> bool:
...
def __repr__(self) -> str:
...
def __setstate__(self, state: int) -> None:
...
def __str__(self) -> str:
...
@property
def name(self) -> str:
...
@property
def value(self) -> int:
...
class MeasurementBitMap:
"""
Maps Pauli tensors to Clifford circuit indices and bits required for measurement. A MeasurementBitMap belongs to a MeasurementSetup object, and dictates which bits are to be included in the measurement. As Clifford circuits may flip the parity of the corresponding Pauli tensor, the MeasurementBitMap optionally inverts the result.
"""
@staticmethod
def from_dict(arg0: dict) -> MeasurementBitMap:
"""
Construct MeasurementBitMap instance from dict representation.
"""
def __init__(self, circ_index: int, bits: typing.Sequence[int], invert: bool = False) -> None:
"""
Constructs a MeasurementBitMap for some Clifford circuit index and bits, with an option to invert the result.
:param circ_index: which measurement circuit the measurement map refers to
:param bits: which bits are included in the measurement
:param invert: whether to flip the parity of the result
"""
def __repr__(self) -> str:
...
def to_dict(self) -> dict:
"""
JSON-serializable dict representation of the MeasurementBitMap.
:return: dict representation of the MeasurementBitMap
"""
@property
def bits(self) -> list[int]:
"""
Bits to measure
"""
@property
def circ_index(self) -> int:
"""
Clifford circuit index
"""
@property
def invert(self) -> bool:
"""
Whether result is inverted or not
"""
class MeasurementSetup:
"""
Encapsulates an experiment in which the expectation value of an operator is to be measured via decomposition into QubitPauliStrings. Each tensor expectation value can be measured using shots. These values are then summed together with some weights to retrieve the desired operator expctation value.
"""
@staticmethod
def from_dict(arg0: dict) -> MeasurementSetup:
"""
Construct MeasurementSetup instance from dict representation.
"""
def __init__(self) -> None:
"""
Constructs an empty MeasurementSetup object
"""
def __repr__(self) -> str:
...
def add_measurement_circuit(self, circ: pytket._tket.circuit.Circuit) -> None:
"""
Add a Clifford circuit that rotates into some Pauli basis
"""
def add_result_for_term(self, term: pytket._tket.pauli.QubitPauliString, result: MeasurementBitMap) -> None:
"""
Add a new Pauli string with a corresponding BitMap
"""
def to_dict(self) -> dict:
"""
JSON-serializable dict representation of the MeasurementSetup.
:return: dict representation of the MeasurementSetup
"""
def verify(self) -> bool:
"""
Checks that the strings to be measured correspond to the correct strings generated by the measurement circs. Checks for parity by comparing to the `invert` flag.
:return: True or False
"""
@property
def measurement_circs(self) -> list[pytket._tket.circuit.Circuit]:
"""
Clifford measurement circuits.
"""
@property
def results(self) -> dict[pytket._tket.pauli.QubitPauliString, list[MeasurementBitMap]]:
"""
Map from Pauli strings to MeasurementBitMaps
"""
class PauliPartitionStrat:
"""
Enum for available strategies to partition Pauli tensors.
Members:
NonConflictingSets : Build sets of Pauli tensors in which each qubit has the same Pauli or Pauli.I. Requires no additional CX gates for diagonalisation.
CommutingSets : Build sets of mutually commuting Pauli tensors. Requires O(n^2) CX gates to diagonalise.
"""
CommutingSets: typing.ClassVar[PauliPartitionStrat] # value = <PauliPartitionStrat.CommutingSets: 1>
NonConflictingSets: typing.ClassVar[PauliPartitionStrat] # value = <PauliPartitionStrat.NonConflictingSets: 0>
__members__: typing.ClassVar[dict[str, PauliPartitionStrat]] # value = {'NonConflictingSets': <PauliPartitionStrat.NonConflictingSets: 0>, 'CommutingSets': <PauliPartitionStrat.CommutingSets: 1>}
def __eq__(self, other: typing.Any) -> bool:
...
def __getstate__(self) -> int:
...
def __hash__(self) -> int:
...
def __index__(self) -> int:
...
def __init__(self, value: int) -> None:
...
def __int__(self) -> int:
...
def __ne__(self, other: typing.Any) -> bool:
...
def __repr__(self) -> str:
...
def __setstate__(self, state: int) -> None:
...
def __str__(self) -> str:
...
@property
def name(self) -> str:
...
@property
def value(self) -> int:
...
def measurement_reduction(strings: typing.Sequence[pytket._tket.pauli.QubitPauliString], strat: PauliPartitionStrat, method: GraphColourMethod = GraphColourMethod.Lazy, cx_config: pytket._tket.circuit.CXConfigType = pytket._tket.circuit.CXConfigType.Snake) -> MeasurementSetup:
"""
Automatically performs graph colouring and diagonalisation to reduce measurements required for Pauli strings.
:param strings: A list of `QubitPauliString` objects to be partitioned.
:param strat: The `PauliPartitionStrat` to use.
:param method: The `GraphColourMethod` to use.
:param cx_config: Whenever diagonalisation is required, use this configuration of CX gates
:return: a :py:class:`MeasurementSetup` object
"""
def term_sequence(strings: typing.Sequence[pytket._tket.pauli.QubitPauliString], strat: PauliPartitionStrat = PauliPartitionStrat.CommutingSets, method: GraphColourMethod = GraphColourMethod.Lazy) -> list[list[pytket._tket.pauli.QubitPauliString]]:
"""
Takes in a list of QubitPauliString objects and partitions them into mutually commuting sets according to some PauliPartitionStrat, then sequences in an arbitrary order.
:param tensors: A list of `QubitPauliString` objects to be sequenced. Assumes that each Pauli tensor is unique, and does not combine equivalent tensors.
:param strat: The `PauliPartitionStrat` to use. Defaults to `CommutingSets`.
:param method: The `GraphColourMethod` to use.
:return: a list of lists of :py:class:`QubitPauliString` s
"""
| tket/pytket/pytket/_tket/partition.pyi/0 | {
"file_path": "tket/pytket/pytket/_tket/partition.pyi",
"repo_id": "tket",
"token_count": 3099
} | 366 |
# Copyright 2019-2024 Cambridge Quantum Computing
#
# 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.
"""`BackendResult` class and associated methods."""
from typing import (
Optional,
Any,
Sequence,
Iterable,
List,
Tuple,
Dict,
Counter,
NamedTuple,
Collection,
Type,
TypeVar,
cast,
)
import operator
from functools import reduce
import warnings
import numpy as np
from pytket.circuit import (
BasisOrder,
Bit,
Circuit,
Qubit,
UnitID,
_DEBUG_ZERO_REG_PREFIX,
_DEBUG_ONE_REG_PREFIX,
)
from pytket.utils.distribution import EmpiricalDistribution, ProbabilityDistribution
from pytket.utils.results import (
probs_from_state,
get_n_qb_from_statevector,
permute_basis_indexing,
permute_rows_cols_in_unitary,
)
from pytket.utils.outcomearray import OutcomeArray, readout_counts
from .backend_exceptions import InvalidResultType
class StoredResult(NamedTuple):
"""NamedTuple with optional fields for all result types."""
counts: Optional[Counter[OutcomeArray]] = None
shots: Optional[OutcomeArray] = None
state: Optional[np.ndarray] = None
unitary: Optional[np.ndarray] = None
density_matrix: Optional[np.ndarray] = None
class BackendResult:
"""Encapsulate generic results from pytket Backend instances.
In the case of a real quantum device or a shots-based simulator
a BackendResult will typically be a collection of measurements (shots and counts).
Results can also be the output of ideal simulations of circuits.
These can take the form of statevectors, unitary arrays or density matrices.
:param q_bits: Sequence of qubits.
:param c_bits: Sequence of classical bits.
:param counts: The counts in the result.
:param shots: The shots in the result.
:param state: The resulting statevector (from a statevector simulation).
:param unitary: The resulting unitary operator (from a unitary simulation).
:param density_matrix: The resulting density matrix
(from a density-matrix simulator).
:param ppcirc: If provided, classical postprocessing to be applied to all measured
results (i.e. shots and counts).
"""
def __init__(
self,
*,
q_bits: Optional[Sequence[Qubit]] = None,
c_bits: Optional[Sequence[Bit]] = None,
counts: Optional[Counter[OutcomeArray]] = None,
shots: Optional[OutcomeArray] = None,
state: Any = None,
unitary: Any = None,
density_matrix: Any = None,
ppcirc: Optional[Circuit] = None,
):
# deal with mutable defaults
if q_bits is None:
q_bits = []
if c_bits is None:
c_bits = []
self._counts = counts
self._shots = shots
self._state = state
self._unitary = unitary
self._density_matrix = density_matrix
self._ppcirc = ppcirc
self.c_bits: Dict[Bit, int] = dict()
self.q_bits: Dict[Qubit, int] = dict()
def _process_unitids(
var: Sequence[UnitID], attr: str, lent: int, uid: Type[UnitID]
) -> None:
if var:
setattr(self, attr, dict((unit, i) for i, unit in enumerate(var)))
if lent != len(var):
raise ValueError(
(
f"Length of {attr} ({len(var)}) does not"
f" match input data dimensions ({lent})."
)
)
else:
setattr(self, attr, dict((uid(i), i) for i in range(lent))) # type: ignore
if self.contains_measured_results:
_bitlength = 0
if self._counts is not None:
if shots is not None:
raise ValueError(
"Provide either counts or shots, both is not valid."
)
try:
_bitlength = next(self._counts.elements()).width
except StopIteration:
_bitlength = len(c_bits)
if self._shots is not None:
_bitlength = self._shots.width
_process_unitids(c_bits, "c_bits", _bitlength, Bit)
if self.contains_state_results:
_n_qubits = 0
if self._unitary is not None:
_n_qubits = int(np.log2(self._unitary.shape[-1]))
elif self._state is not None:
_n_qubits = get_n_qb_from_statevector(self._state)
elif self._density_matrix is not None:
_n_qubits = int(np.log2(self._density_matrix.shape[-1]))
_process_unitids(q_bits, "q_bits", _n_qubits, Qubit)
def __repr__(self) -> str:
return (
"BackendResult(q_bits={s.q_bits},c_bits={s.c_bits},counts={s._counts},"
"shots={s._shots},state={s._state},unitary={s._unitary},"
"density_matrix={s._density_matrix})".format(s=self)
)
@property
def contains_measured_results(self) -> bool:
"""Whether measured type results (shots or counts) are stored"""
return (self._counts is not None) or (self._shots is not None)
@property
def contains_state_results(self) -> bool:
"""Whether state type results (state vector or unitary or density_matrix)
are stored"""
return (
(self._state is not None)
or (self._unitary is not None)
or (self._density_matrix is not None)
)
def __eq__(self, other: object) -> bool:
if not isinstance(other, BackendResult):
return NotImplemented
return (
self.q_bits == other.q_bits
and self.c_bits == other.c_bits
and (
(self._shots is None and other._shots is None)
or cast(OutcomeArray, self._shots) == cast(OutcomeArray, other._shots)
)
and self._counts == other._counts
and np.array_equal(self._state, other._state)
and np.array_equal(self._unitary, other._unitary)
and np.array_equal(self._density_matrix, other._density_matrix)
)
def get_bitlist(self) -> List[Bit]:
"""Return list of Bits in internal storage order.
:raises AttributeError: BackendResult does not include a Bits list.
:return: Sorted list of Bits.
:rtype: List[Bit]
"""
return _sort_keys_by_val(self.c_bits)
def get_qbitlist(self) -> List[Qubit]:
"""Return list of Qubits in internal storage order.
:raises AttributeError: BackendResult does not include a Qubits list.
:return: Sorted list of Qubits.
:rtype: List[Qubit]
"""
return _sort_keys_by_val(self.q_bits)
def _get_measured_res(
self, bits: Sequence[Bit], ppcirc: Optional[Circuit] = None
) -> StoredResult:
vals: Dict[str, Any] = {}
if not self.contains_measured_results:
raise InvalidResultType("shots/counts")
if self._ppcirc is not None:
if ppcirc is None:
ppcirc = self._ppcirc
else:
raise ValueError("Postprocessing circuit already provided.")
try:
chosen_readouts = [self.c_bits[bit] for bit in bits]
except KeyError:
raise ValueError("Requested Bit not in result.")
if self._counts is not None:
if ppcirc is not None:
# Modify self._counts:
new_counts: Counter[OutcomeArray] = Counter()
for oa, n in self._counts.items():
readout = oa.to_readout()
values = {bit: bool(readout[i]) for bit, i in self.c_bits.items()}
new_values = ppcirc._classical_eval(values)
new_oa = OutcomeArray.from_readouts(
[[int(new_values[bit]) for bit in bits]]
)
new_counts[new_oa] += n
else:
new_counts = self._counts
vals["counts"] = reduce(
operator.add,
(
Counter({outcome.choose_indices(chosen_readouts): count})
for outcome, count in new_counts.items()
),
Counter(),
)
if self._shots is not None:
if ppcirc is not None:
# Modify self._shots:
readouts = self._shots.to_readouts()
new_readouts = []
for i in range(self._shots.n_outcomes):
readout = readouts[i, :]
values = {bit: bool(readout[i]) for bit, i in self.c_bits.items()}
new_values = ppcirc._classical_eval(values)
new_readout = [0] * self._shots.width
for bit, i in self.c_bits.items():
if new_values[bit]:
new_readout[i] = 1
new_readouts.append(new_readout)
new_shots = OutcomeArray.from_readouts(new_readouts)
else:
new_shots = self._shots
vals["shots"] = new_shots.choose_indices(chosen_readouts)
return StoredResult(**vals)
def _permute_statearray_qb_labels(
self,
array: np.ndarray,
relabling_map: Dict[Qubit, Qubit],
) -> np.ndarray:
"""Permute statevector/unitary according to a relabelling of Qubits.
:param array: The statevector or unitary
:type array: np.ndarray
:param relabling_map: Map from original Qubits to new.
:type relabling_map: Dict[Qubit, Qubit]
:return: Permuted array.
:rtype: np.ndarray
"""
original_labeling: Sequence["Qubit"] = self.get_qbitlist()
n_labels = len(original_labeling)
permutation = [0] * n_labels
for i, orig_qb in enumerate(original_labeling):
permutation[i] = original_labeling.index(relabling_map[orig_qb])
if permutation == list(range(n_labels)):
# Optimization: nothing to do; return original array.
return array
permuter = (
permute_basis_indexing
if len(array.shape) == 1
else permute_rows_cols_in_unitary
)
return permuter(array, tuple(permutation))
def _get_state_res(self, qubits: Sequence[Qubit]) -> StoredResult:
vals: Dict[str, Any] = {}
if not self.contains_state_results:
raise InvalidResultType("state/unitary/density_matrix")
if not _check_permuted_sequence(qubits, self.q_bits):
raise ValueError(
"For state/unitary/density_matrix results only a permutation of"
" all qubits can be requested."
)
qb_mapping = {selfqb: qubits[index] for selfqb, index in self.q_bits.items()}
if self._state is not None:
vals["state"] = self._permute_statearray_qb_labels(self._state, qb_mapping)
if self._unitary is not None:
vals["unitary"] = self._permute_statearray_qb_labels(
self._unitary, qb_mapping
)
if self._density_matrix is not None:
vals["density_matrix"] = self._permute_statearray_qb_labels(
self._density_matrix, qb_mapping
)
return StoredResult(**vals)
def get_result(
self,
request_ids: Optional[Sequence[UnitID]] = None,
basis: BasisOrder = BasisOrder.ilo,
ppcirc: Optional[Circuit] = None,
) -> StoredResult:
"""Retrieve all results, optionally according to a specified UnitID ordering
or subset.
:param request_ids: Ordered set of either Qubits or Bits for which to
retrieve results, defaults to None in which case all results are returned.
For statevector/unitary/density_matrix results some permutation of all
qubits must be requested.
For measured results (shots/counts), some subset of the relevant bits must
be requested.
:type request_ids: Optional[Sequence[UnitID]], optional
:param basis: Toggle between ILO (increasing lexicographic order of bit ids) and
DLO (decreasing lexicographic order) for column ordering if request_ids is
None. Defaults to BasisOrder.ilo.
:param ppcirc: Classical post-processing circuit to apply to measured results
:raises ValueError: Requested UnitIds (request_ids) contain a mixture of qubits
and bits.
:raises RuntimeError: Classical bits not set.
:raises ValueError: Requested (Qu)Bit not in result.
:raises RuntimeError: "Qubits not set."
:raises ValueError: For state/unitary/density_matrix results only a permutation
of all qubits can be requested.
:return: All stored results corresponding to requested IDs.
:rtype: StoredResult
"""
if request_ids is None:
if self.contains_measured_results:
request_ids = sorted(
self.c_bits.keys(), reverse=(basis == BasisOrder.dlo)
)
elif self.contains_state_results:
request_ids = sorted(
self.q_bits.keys(), reverse=(basis == BasisOrder.dlo)
)
else:
raise InvalidResultType("No results stored.")
if all(isinstance(i, Bit) for i in request_ids):
return self._get_measured_res(request_ids, ppcirc) # type: ignore
if all(isinstance(i, Qubit) for i in request_ids):
return self._get_state_res(request_ids) # type: ignore
raise ValueError(
"Requested UnitIds (request_ids) contain a mixture of qubits and bits."
)
def get_shots(
self,
cbits: Optional[Sequence[Bit]] = None,
basis: BasisOrder = BasisOrder.ilo,
ppcirc: Optional[Circuit] = None,
) -> np.ndarray:
"""Return shots if available.
:param cbits: ordered subset of Bits, returns all results by default, defaults
to None
:type cbits: Optional[Sequence[Bit]], optional
:param basis: Toggle between ILO (increasing lexicographic order of bit ids) and
DLO (decreasing lexicographic order) for column ordering if cbits is None.
Defaults to BasisOrder.ilo.
:param ppcirc: Classical post-processing circuit to apply to measured results
:raises InvalidResultType: Shot results are not available
:return: 2D array of readouts, each row a separate outcome and each column a
bit value.
:rtype: np.ndarray
The order of the columns follows the order of `cbits`, if provided.
"""
if cbits is None:
cbits = sorted(self.c_bits.keys(), reverse=(basis == BasisOrder.dlo))
res = self.get_result(cbits, ppcirc=ppcirc)
if res.shots is not None:
return res.shots.to_readouts()
raise InvalidResultType("shots")
def get_counts(
self,
cbits: Optional[Sequence[Bit]] = None,
basis: BasisOrder = BasisOrder.ilo,
ppcirc: Optional[Circuit] = None,
) -> Counter[Tuple[int, ...]]:
"""Return counts of outcomes if available.
:param cbits: ordered subset of Bits, returns all results by default, defaults
to None
:type cbits: Optional[Sequence[Bit]], optional
:param basis: Toggle between ILO (increasing lexicographic order of bit ids) and
DLO (decreasing lexicographic order) for column ordering if cbits is None.
Defaults to BasisOrder.ilo.
:param ppcirc: Classical post-processing circuit to apply to measured results
:raises InvalidResultType: Counts are not available
:return: Counts of outcomes
:rtype: Counter[Tuple(int)]
"""
if cbits is None:
cbits = sorted(self.c_bits.keys(), reverse=(basis == BasisOrder.dlo))
res = self.get_result(cbits, ppcirc=ppcirc)
if res.counts is not None:
return readout_counts(res.counts)
if res.shots is not None:
return readout_counts(res.shots.counts())
raise InvalidResultType("counts")
def get_state(
self,
qbits: Optional[Sequence[Qubit]] = None,
basis: BasisOrder = BasisOrder.ilo,
) -> np.ndarray:
"""Return statevector if available.
:param qbits: permutation of Qubits, defaults to None
:type qbits: Optional[Sequence[Qubit]], optional
:param basis: Toggle between ILO (increasing lexicographic order of qubit ids)
and DLO (decreasing lexicographic order) for column ordering if qbits is
None. Defaults to BasisOrder.ilo.
:raises InvalidResultType: Statevector not available
:return: Statevector, (complex 1-D numpy array)
:rtype: np.ndarray
"""
if qbits is None:
qbits = sorted(self.q_bits.keys(), reverse=(basis == BasisOrder.dlo))
res = self.get_result(qbits)
if res.state is not None:
return res.state
if res.unitary is not None:
state: np.ndarray = res.unitary[:, 0]
return state
raise InvalidResultType("state")
def get_unitary(
self,
qbits: Optional[Sequence[Qubit]] = None,
basis: BasisOrder = BasisOrder.ilo,
) -> np.ndarray:
"""Return unitary if available.
:param qbits: permutation of Qubits, defaults to None
:type qbits: Optional[Sequence[Qubit]], optional
:param basis: Toggle between ILO (increasing lexicographic order of qubit ids)
and DLO (decreasing lexicographic order) for column ordering if qbits is
None. Defaults to BasisOrder.ilo.
:raises InvalidResultType: Statevector not available
:return: Unitary, (complex 2-D numpy array)
:rtype: np.ndarray
"""
if qbits is None:
qbits = sorted(self.q_bits.keys(), reverse=(basis == BasisOrder.dlo))
res = self.get_result(qbits)
if res.unitary is not None:
return res.unitary
raise InvalidResultType("unitary")
def get_density_matrix(
self,
qbits: Optional[Sequence[Qubit]] = None,
basis: BasisOrder = BasisOrder.ilo,
) -> np.ndarray:
"""Return density_matrix if available.
:param qbits: permutation of Qubits, defaults to None
:type qbits: Optional[Sequence[Qubit]], optional
:param basis: Toggle between ILO (increasing lexicographic order of qubit ids)
and DLO (decreasing lexicographic order) for column ordering if qbits is
None. Defaults to BasisOrder.ilo.
:raises InvalidResultType: Statevector not available
:return: density_matrix, (complex 2-D numpy array)
:rtype: np.ndarray
"""
if qbits is None:
qbits = sorted(self.q_bits.keys(), reverse=(basis == BasisOrder.dlo))
res = self.get_result(qbits)
if res.density_matrix is not None:
return res.density_matrix
raise InvalidResultType("density_matrix")
def get_distribution(
self, units: Optional[Sequence[UnitID]] = None
) -> Dict[Tuple[int, ...], float]:
"""Calculate an exact or approximate probability distribution over outcomes.
If the exact statevector is known, the exact probability distribution is
returned. Otherwise, if measured results are available the distribution
is estimated from these results.
This method is deprecated. Please use :py:meth:`get_empirical_distribution` or
:py:meth:`get_probability_distribution` instead.
DEPRECATED: will be removed after pytket 1.32.
:param units: Optionally provide the Qubits or Bits
to marginalise the distribution over, defaults to None
:type units: Optional[Sequence[UnitID]], optional
:return: A distribution as a map from bitstring to probability.
:rtype: Dict[Tuple[int, ...], float]
"""
warnings.warn(
"The `BackendResult.get_distribution()` method is deprecated: "
"please use `get_empirical_distribution()` or "
"`get_probability_distribution()` instead.",
DeprecationWarning,
)
try:
state = self.get_state(units) # type: ignore
return probs_from_state(state)
except InvalidResultType:
counts = self.get_counts(units) # type: ignore
total = sum(counts.values())
dist = {outcome: count / total for outcome, count in counts.items()}
return dist
def get_empirical_distribution(
self, bits: Optional[Sequence[Bit]] = None
) -> EmpiricalDistribution[Tuple[int, ...]]:
"""Convert to a :py:class:`pytket.utils.distribution.EmpiricalDistribution`
where the observations are sequences of 0s and 1s.
:param bits: Optionally provide the :py:class:`Bit` s over which to
marginalize the distribution.
:return: A distribution where the observations are sequences of 0s and 1s.
"""
if not self.contains_measured_results:
raise InvalidResultType(
"Empirical distribution only available for measured result types."
)
return EmpiricalDistribution(self.get_counts(bits))
def get_probability_distribution(
self, qubits: Optional[Sequence[Qubit]] = None, min_p: float = 0.0
) -> ProbabilityDistribution[Tuple[int, ...]]:
"""Convert to a :py:class:`pytket.utils.distribution.ProbabilityDistribution`
where the possible outcomes are sequences of 0s and 1s.
:param qubits: Optionally provide the :py:class:`Qubit` s over which to
marginalize the distribution.
:param min_p: Optional probability below which to ignore values (for
example to avoid spurious values due to rounding errors in
statevector computations). Default 0.
:return: A distribution where the possible outcomes are tuples of 0s and 1s.
"""
if not self.contains_state_results:
raise InvalidResultType(
"Probability distribution only available for statevector result types."
)
state = self.get_state(qubits)
return ProbabilityDistribution(probs_from_state(state), min_p=min_p)
def get_debug_info(self) -> Dict[str, float]:
"""Calculate the success rate of each assertion averaged across shots.
Each assertion in pytket is decomposed into a sequence of transformations
and measurements. An assertion is successful if and only if all its associated
measurements yield the correct results.
:return: The debug results as a map from assertion to average success rate.
:rtype: Dict[str, float]
"""
_tket_debug_zero_prefix = _DEBUG_ZERO_REG_PREFIX + "_"
_tket_debug_one_prefix = _DEBUG_ONE_REG_PREFIX + "_"
debug_bit_dict: Dict[str, Dict[str, Any]] = {}
for bit in self.c_bits:
if bit.reg_name.startswith(_tket_debug_zero_prefix):
expectation = 0
assertion_name = bit.reg_name.split(_tket_debug_zero_prefix, 1)[1]
elif bit.reg_name.startswith(_tket_debug_one_prefix):
expectation = 1
assertion_name = bit.reg_name.split(_tket_debug_one_prefix, 1)[1]
else:
continue
if assertion_name not in debug_bit_dict:
debug_bit_dict[assertion_name] = {"bits": [], "expectations": []}
debug_bit_dict[assertion_name]["bits"].append(bit)
debug_bit_dict[assertion_name]["expectations"].append(expectation)
debug_result_dict: Dict[str, float] = {}
for assertion_name, bits_info in debug_bit_dict.items():
counts = self.get_counts(bits_info["bits"])
debug_result_dict[assertion_name] = counts[
tuple(bits_info["expectations"])
] / sum(counts.values())
return debug_result_dict
def to_dict(self) -> Dict[str, Any]:
"""Generate a dictionary serialized representation of BackendResult,
suitable for writing to JSON.
:return: JSON serializable dictionary.
:rtype: Dict[str, Any]
"""
outdict: Dict[str, Any] = dict()
outdict["qubits"] = [q.to_list() for q in self.get_qbitlist()]
outdict["bits"] = [c.to_list() for c in self.get_bitlist()]
if self._shots is not None:
outdict["shots"] = self._shots.to_dict()
if self._counts is not None:
outdict["counts"] = [
{"outcome": oc.to_dict(), "count": count}
for oc, count in self._counts.items()
]
if self._state is not None:
outdict["state"] = _complex_ar_to_dict(self._state)
if self._unitary is not None:
outdict["unitary"] = _complex_ar_to_dict(self._unitary)
if self._density_matrix is not None:
outdict["density_matrix"] = _complex_ar_to_dict(self._density_matrix)
return outdict
@classmethod
def from_dict(cls, res_dict: Dict[str, Any]) -> "BackendResult":
"""Construct BackendResult object from JSON serializable dictionary
representation, as generated by BackendResult.to_dict.
:return: Instance of BackendResult constructed from dictionary.
:rtype: BackendResult
"""
init_dict = dict.fromkeys(
(
"q_bits",
"c_bits",
"shots",
"counts",
"state",
"unitary",
"density_matrix",
)
)
if "qubits" in res_dict:
init_dict["q_bits"] = [Qubit.from_list(tup) for tup in res_dict["qubits"]]
if "bits" in res_dict:
init_dict["c_bits"] = [Bit.from_list(tup) for tup in res_dict["bits"]]
if "shots" in res_dict:
init_dict["shots"] = OutcomeArray.from_dict(res_dict["shots"])
if "counts" in res_dict:
init_dict["counts"] = Counter(
{
OutcomeArray.from_dict(elem["outcome"]): elem["count"]
for elem in res_dict["counts"]
}
)
if "state" in res_dict:
init_dict["state"] = _complex_ar_from_dict(res_dict["state"])
if "unitary" in res_dict:
init_dict["unitary"] = _complex_ar_from_dict(res_dict["unitary"])
if "density_matrix" in res_dict:
init_dict["density_matrix"] = _complex_ar_from_dict(
res_dict["density_matrix"]
)
return BackendResult(**init_dict)
T = TypeVar("T")
def _sort_keys_by_val(dic: Dict[T, int]) -> List[T]:
if not dic:
return []
vals, _ = zip(*sorted(dic.items(), key=lambda x: x[1]))
return list(cast(Iterable[T], vals))
def _check_permuted_sequence(first: Collection[Any], second: Collection[Any]) -> bool:
return len(first) == len(second) and set(first) == set(second)
def _complex_ar_to_dict(ar: np.ndarray) -> Dict[str, List]:
"""Dictionary of real, imaginary parts of complex array, each in list form."""
return {"real": ar.real.tolist(), "imag": ar.imag.tolist()}
def _complex_ar_from_dict(dic: Dict[str, List]) -> np.ndarray:
"""Construct complex array from dictionary of real and imaginary parts"""
out = np.array(dic["real"], dtype=complex)
out.imag = np.array(dic["imag"], dtype=float)
return out
| tket/pytket/pytket/backends/backendresult.py/0 | {
"file_path": "tket/pytket/pytket/backends/backendresult.py",
"repo_id": "tket",
"token_count": 12701
} | 367 |
# Copyright 2019-2024 Cambridge Quantum Computing
#
# 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.
from typing import TYPE_CHECKING, Dict, Optional, Tuple, List
import numpy as np
from pytket.circuit import Circuit, Qubit
from pytket.pauli import QubitPauliString
from pytket.partition import (
measurement_reduction,
PauliPartitionStrat,
GraphColourMethod,
)
from .measurements import _all_pauli_measurements, append_pauli_measurement
from .results import KwargTypes
from .operators import QubitPauliOperator
if TYPE_CHECKING:
from pytket.backends.backend import Backend
def expectation_from_shots(shot_table: np.ndarray) -> float:
"""Estimates the expectation value of a circuit from its shots.
Computes the parity of '1's across all bits to determine a +1 or -1 contribution
from each row, and returns the average.
:param shot_table: The table of shots to interpret.
:type shot_table: np.ndarray
:return: The expectation value in the range [-1, 1].
:rtype: float
"""
aritysum = 0.0
for row in shot_table:
aritysum += np.sum(row) % 2
return -2 * aritysum / len(shot_table) + 1
def expectation_from_counts(counts: Dict[Tuple[int, ...], int]) -> float:
"""Estimates the expectation value of a circuit from shot counts.
Computes the parity of '1's across all bits to determine a +1 or -1 contribution
from each readout, and returns the weighted average.
:param counts: Counts of each measurement outcome observed.
:type counts: Dict[Tuple[int, ...], int]
:return: The expectation value in the range [-1, 1].
:rtype: float
"""
aritysum = 0.0
total_shots = 0
for row, count in counts.items():
aritysum += count * (sum(row) % 2)
total_shots += count
return -2 * aritysum / total_shots + 1
def _default_index(q: Qubit) -> int:
if q.reg_name != "q" or len(q.index) != 1:
raise ValueError("Non-default qubit register")
return int(q.index[0])
def get_pauli_expectation_value(
state_circuit: Circuit,
pauli: QubitPauliString,
backend: "Backend",
n_shots: Optional[int] = None,
) -> complex:
"""Estimates the expectation value of the given circuit with respect to the Pauli
term by preparing measurements in the appropriate basis, running on the backend and
interpreting the counts/statevector
:param state_circuit: Circuit that generates the desired state
:math:`\\left|\\psi\\right>`.
:type state_circuit: Circuit
:param pauli: Pauli operator
:type pauli: QubitPauliString
:param backend: pytket backend to run circuit on.
:type backend: Backend
:param n_shots: Number of shots to run if backend supports shots/counts. Set to None
to calculate using statevector if supported by the backend. Defaults to None
:type n_shots: Optional[int], optional
:return: :math:`\\left<\\psi | P | \\psi \\right>`
:rtype: float
"""
if not n_shots:
if not backend.valid_circuit(state_circuit):
state_circuit = backend.get_compiled_circuit(state_circuit)
if backend.supports_expectation:
return backend.get_pauli_expectation_value(state_circuit, pauli)
state = backend.run_circuit(state_circuit).get_state()
return complex(pauli.state_expectation(state))
measured_circ = state_circuit.copy()
append_pauli_measurement(pauli, measured_circ)
measured_circ = backend.get_compiled_circuit(measured_circ)
if backend.supports_counts:
counts = backend.run_circuit(measured_circ, n_shots=n_shots).get_counts()
return expectation_from_counts(counts)
elif backend.supports_shots:
shot_table = backend.run_circuit(measured_circ, n_shots=n_shots).get_shots()
return expectation_from_shots(shot_table)
else:
raise ValueError("Backend does not support counts or shots")
def get_operator_expectation_value(
state_circuit: Circuit,
operator: QubitPauliOperator,
backend: "Backend",
n_shots: Optional[int] = None,
partition_strat: Optional[PauliPartitionStrat] = None,
colour_method: GraphColourMethod = GraphColourMethod.LargestFirst,
**kwargs: KwargTypes,
) -> complex:
"""Estimates the expectation value of the given circuit with respect to the operator
based on its individual Pauli terms. If the QubitPauliOperator has symbolic values
the expectation value will also be symbolic. The input circuit must belong to the
default qubit register and have contiguous qubit ordering.
:param state_circuit: Circuit that generates the desired state
:math:`\\left|\\psi\\right>`
:type state_circuit: Circuit
:param operator: Operator :math:`H`. Currently does not support free symbols for the
purpose of obtaining expectation values.
:type operator: QubitPauliOperator
:param backend: pytket backend to run circuit on.
:type backend: Backend
:param n_shots: Number of shots to run if backend supports shots/counts. None will
force the backend to give the full state if available. Defaults to None
:type n_shots: Optional[int], optional
:param partition_strat: If retrieving shots, can perform measurement reduction using
a chosen strategy
:type partition_strat: Optional[PauliPartitionStrat], optional
:return: :math:`\\left<\\psi | H | \\psi \\right>`
:rtype: complex
"""
if not n_shots:
if not backend.valid_circuit(state_circuit):
state_circuit = backend.get_compiled_circuit(state_circuit)
try:
coeffs: List[complex] = [complex(v) for v in operator._dict.values()]
except TypeError:
raise ValueError("QubitPauliOperator contains unevaluated symbols.")
if backend.supports_expectation and (
backend.expectation_allows_nonhermitian or all(z.imag == 0 for z in coeffs)
):
return backend.get_operator_expectation_value(state_circuit, operator)
result = backend.run_circuit(state_circuit)
state = result.get_state()
return operator.state_expectation(state)
energy: complex
id_string = QubitPauliString()
if id_string in operator._dict:
energy = complex(operator[id_string])
else:
energy = 0
if not partition_strat:
operator_without_id = QubitPauliOperator(
{p: c for p, c in operator._dict.items() if (p != id_string)}
)
coeffs = [complex(c) for c in operator_without_id._dict.values()]
pauli_circuits = list(
_all_pauli_measurements(operator_without_id, state_circuit)
)
handles = backend.process_circuits(
backend.get_compiled_circuits(pauli_circuits),
n_shots,
valid_check=True,
**kwargs,
)
results = backend.get_results(handles)
if backend.supports_counts:
for result, coeff in zip(results, coeffs):
counts = result.get_counts()
energy += coeff * expectation_from_counts(counts)
for handle in handles:
backend.pop_result(handle)
return energy
elif backend.supports_shots:
for result, coeff in zip(results, coeffs):
shots = result.get_shots()
energy += coeff * expectation_from_shots(shots)
for handle in handles:
backend.pop_result(handle)
return energy
else:
raise ValueError("Backend does not support counts or shots")
else:
qubit_pauli_string_list = [p for p in operator._dict.keys() if (p != id_string)]
measurement_expectation = measurement_reduction(
qubit_pauli_string_list, partition_strat, colour_method
)
# note: this implementation requires storing all the results
# in memory simultaneously to filter through them.
measure_circs = []
for pauli_circ in measurement_expectation.measurement_circs:
circ = state_circuit.copy()
circ.append(pauli_circ)
measure_circs.append(circ)
handles = backend.process_circuits(
backend.get_compiled_circuits(measure_circs),
n_shots=n_shots,
valid_check=True,
**kwargs,
)
results = backend.get_results(handles)
for pauli_string in measurement_expectation.results:
bitmaps = measurement_expectation.results[pauli_string]
string_coeff = operator[pauli_string]
for bm in bitmaps:
index = bm.circ_index
aritysum = 0.0
if backend.supports_counts:
counts = results[index].get_counts()
total_shots = 0
for row, count in counts.items():
aritysum += count * (sum(row[i] for i in bm.bits) % 2)
total_shots += count
e = (
((-1) ** bm.invert)
* string_coeff
* (-2 * aritysum / total_shots + 1)
)
energy += complex(e)
elif backend.supports_shots:
shots = results[index].get_shots()
for row in shots:
aritysum += sum(row[i] for i in bm.bits) % 2
e = (
((-1) ** bm.invert)
* string_coeff
* (-2 * aritysum / len(shots) + 1)
)
energy += complex(e)
else:
raise ValueError("Backend does not support counts or shots")
for handle in handles:
backend.pop_result(handle)
return energy
| tket/pytket/pytket/utils/expectations.py/0 | {
"file_path": "tket/pytket/pytket/utils/expectations.py",
"repo_id": "tket",
"token_count": 4313
} | 368 |
# Copyright 2019-2024 Cambridge Quantum Computing
#
# 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 multiprocessing
import os
import subprocess
import json
import shutil
import setuptools # type: ignore
from setuptools import setup, Extension
from setuptools.command.build_ext import build_ext # type: ignore
from sysconfig import get_config_var
from wheel.bdist_wheel import bdist_wheel as _bdist_wheel
class CMakeExtension(Extension):
def __init__(self, name, sourcedir=""):
Extension.__init__(self, name, sources=[])
self.sourcedir = os.path.abspath(sourcedir)
binders = [
"logging",
"utils_serialization",
"circuit",
"circuit_library",
"unit_id",
"passes",
"predicates",
"partition",
"pauli",
"mapping",
"transform",
"tailoring",
"tableau",
"zx",
"placement",
"architecture",
]
class CMakeBuild(build_ext):
def run(self):
self.check_extensions_list(self.extensions)
extdir = os.path.abspath(
os.path.dirname(self.get_ext_fullpath(self.extensions[0].name))
)
extsource = self.extensions[0].sourcedir
build_dir = os.path.join(extsource, "build")
shutil.rmtree(build_dir, ignore_errors=True)
os.mkdir(build_dir)
install_dir = os.getenv("INSTALL_DIR")
subprocess.run(
["cmake", f"-DCMAKE_INSTALL_PREFIX={install_dir}", os.pardir], cwd=build_dir
)
subprocess.run(
[
"cmake",
"--build",
os.curdir,
f"-j{os.getenv('PYTKET_CMAKE_N_THREADS', multiprocessing.cpu_count())}",
],
cwd=build_dir,
)
subprocess.run(["cmake", "--install", os.curdir], cwd=build_dir)
lib_folder = os.path.join(install_dir, "lib")
lib_names = ["libtklog.so", "libtket.so"]
ext_suffix = get_config_var("EXT_SUFFIX")
lib_names.extend(f"{binder}{ext_suffix}" for binder in binders)
# TODO make the above generic
os.makedirs(extdir, exist_ok=True)
for lib_name in lib_names:
shutil.copy(os.path.join(lib_folder, lib_name), extdir)
class ConanBuild(build_ext):
def run(self):
self.check_extensions_list(self.extensions)
extdir = os.path.abspath(
os.path.dirname(self.get_ext_fullpath(self.extensions[0].name))
)
extsource = self.extensions[0].sourcedir
jsonstr = subprocess.check_output(
[
"conan",
"create",
".",
"--build=missing",
"-o",
"boost/*:header_only=True",
"-o",
"tket/*:shared=True",
"-o",
"tklog/*:shared=True",
"--format",
"json",
],
cwd=extsource,
)
# Collect the paths to the libraries to package together
conaninfo = json.loads(jsonstr)
nodes = conaninfo["graph"]["nodes"]
os.makedirs(extdir, exist_ok=True)
for comp in ["tklog", "tket", "pytket"]:
compnodes = [
node for _, node in nodes.items() if node["ref"].startswith(comp + "/")
]
assert len(compnodes) == 1
compnode = compnodes[0]
lib_folder = os.path.join(compnode["package_folder"], "lib")
for lib in os.listdir(lib_folder):
libpath = os.path.join(lib_folder, lib)
# Don't copy the `cmake` directory.
if not os.path.isdir(libpath):
shutil.copy(libpath, extdir)
class NixBuild(build_ext):
def run(self):
self.check_extensions_list(self.extensions)
extdir = os.path.abspath(
os.path.dirname(self.get_ext_fullpath(self.extensions[0].name))
)
if os.path.exists(extdir):
shutil.rmtree(extdir)
os.makedirs(extdir)
nix_ldflags = os.environ["NIX_LDFLAGS"].split()
build_inputs = os.environ["propagatedBuildInputs"].split()
binders = [f"{l}/lib" for l in build_inputs if "-binders" in l]
for binder in binders:
for lib in os.listdir(binder):
libpath = os.path.join(binder, lib)
if not os.path.isdir(libpath):
shutil.copy(libpath, extdir)
for interface_file in os.listdir("pytket/_tket"):
if interface_file.endswith(".pyi") or interface_file.endswith(".py"):
shutil.copy(os.path.join("pytket/_tket", interface_file), extdir)
plat_name = os.getenv("WHEEL_PLAT_NAME")
def get_build_ext():
if os.getenv("USE_NIX"):
return NixBuild
elif os.getenv("NO_CONAN"):
return CMakeBuild
else:
return ConanBuild
class bdist_wheel(_bdist_wheel):
def finalize_options(self):
_bdist_wheel.finalize_options(self)
if plat_name is not None:
print(f"Overriding plat_name to {plat_name}")
self.plat_name = plat_name
self.plat_name_supplied = True
setup(
name="pytket",
author="TKET development team",
author_email="[email protected]",
python_requires=">=3.10",
project_urls={
"Documentation": "https://tket.quantinuum.com/api-docs/index.html",
"Source": "https://github.com/CQCL/tket",
"Tracker": "https://github.com/CQCL/tket/issues",
},
description="Quantum computing toolkit and interface to the TKET compiler",
long_description=open("package.md", "r").read(),
long_description_content_type="text/markdown",
license="Apache 2",
packages=setuptools.find_packages() + ["pytket.qasm.includes"],
install_requires=[
"sympy >= 1.12.1",
"numpy >= 1.26.4",
"lark >= 1.1.9",
"scipy >= 1.13.1",
"networkx >= 2.8.8",
"graphviz >= 0.20.3",
"jinja2 >= 3.1.4",
"typing-extensions >= 4.12.2",
"qwasm >= 1.0.1",
],
extras_require={
"ZX": [
"numba >= 0.60.0",
"quimb >= 1.8.2",
"autoray >= 0.6.12",
],
},
ext_modules=[
CMakeExtension("pytket._tket.{}".format(binder)) for binder in binders
],
cmdclass={
"build_ext": get_build_ext(),
"bdist_wheel": bdist_wheel,
},
classifiers=[
"Environment :: Console",
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11",
"Programming Language :: Python :: 3.12",
"License :: OSI Approved :: Apache Software License",
"Operating System :: MacOS :: MacOS X",
"Operating System :: POSIX :: Linux",
"Operating System :: Microsoft :: Windows",
"Intended Audience :: Developers",
"Intended Audience :: Science/Research",
"Topic :: Scientific/Engineering",
],
include_package_data=True,
package_data={"pytket": ["py.typed"]},
zip_safe=False,
)
| tket/pytket/setup.py/0 | {
"file_path": "tket/pytket/setup.py",
"repo_id": "tket",
"token_count": 3606
} | 369 |
# Copyright 2019-2024 Cambridge Quantum Computing
#
# 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.
from collections import Counter
from numpy import isclose
from pytket.utils import (
ProbabilityDistribution,
EmpiricalDistribution,
convex_combination,
)
import pytest
def test_probability_distribution() -> None:
pd = ProbabilityDistribution({"a": 1 / 3, "b": 2 / 3})
with pytest.raises(ValueError):
pd = ProbabilityDistribution({"a": 1 / 3, "b": 1, "c": -1 / 3})
pd1 = ProbabilityDistribution(
{"a": 1 / 3, "b": 2 / 3 - 1e-15, "c": 1e-15}, min_p=1e-10
)
assert pd1.support == set(["a", "b"])
assert isclose(pd1["a"], 1 / 3)
assert pd1["c"] == 0.0
assert pd == pd1
with pytest.warns(UserWarning):
pd2 = ProbabilityDistribution({"a": 2 / 3, "b": 4 / 3})
pd3 = ProbabilityDistribution({"a": 2 / 9, "b": 4 / 9, "c": 1 / 3})
pd4 = convex_combination([(pd, 1 / 3), (pd3, 2 / 3)])
assert pd4 == ProbabilityDistribution({"a": 7 / 27, "b": 14 / 27, "c": 2 / 9})
def test_empirical_distribution() -> None:
ed1 = EmpiricalDistribution(Counter({"a": 1, "b": 2}))
ed2 = EmpiricalDistribution(Counter({"b": 1, "c": 3, "d": 0}))
assert ed2.support == set(["b", "c"])
assert ed2["b"] == 1
assert ed2["d"] == 0
ed3 = EmpiricalDistribution(Counter({"a": 2, "c": 0, "e": 4}))
ed4 = ed1 + ed2 + ed3
assert ed4 == EmpiricalDistribution(Counter({"a": 3, "b": 3, "c": 3, "e": 4}))
ed0: EmpiricalDistribution[str] = EmpiricalDistribution(Counter())
with pytest.raises(ValueError):
pd6 = ProbabilityDistribution.from_empirical_distribution(ed0)
pd6 = ProbabilityDistribution.from_empirical_distribution(ed4)
assert isclose(pd6.as_dict()["a"], ed4.as_counter()["a"] / ed4.total)
rv, X = pd6.as_rv_discrete()
for i, x in enumerate(X):
assert isclose(pd6[x], rv.pmf(i))
def test_marginalization() -> None:
ed = EmpiricalDistribution(Counter({(0, 0): 3, (0, 1): 2, (1, 0): 4, (1, 1): 0}))
ed0_ = ed.condition(lambda x: x[0] == 0)
ed1_ = ed.condition(lambda x: x[0] == 1)
ed_0 = ed.condition(lambda x: x[1] == 0)
ed_1 = ed.condition(lambda x: x[1] == 1)
assert ed0_.total == 5
assert ed1_.total == 4
assert ed_0.total == 7
assert ed_1.total == 2
pd = ProbabilityDistribution.from_empirical_distribution(ed)
pd0 = pd.condition(lambda x: x[0] == x[1])
pd1 = pd.condition(lambda x: x[0] != x[1])
assert pd0.support == set([(0, 0)])
assert isclose(pd1[(0, 1)], 1 / 3)
def test_representation() -> None:
ed = EmpiricalDistribution(Counter({"a": 1, "b": 3, 7: 0, (1, 1): 3}))
assert ed == eval(repr(ed))
pd = ProbabilityDistribution({"a": 1 / 7, "b": 2 / 7, 7: 0, (1, 1): 4 / 7})
assert pd == eval(repr(pd))
def test_mapping() -> None:
ed = EmpiricalDistribution(Counter({(0, 0): 3, (0, 1): 2, (1, 0): 4, (1, 1): 0}))
ed0 = ed.map(lambda x: x[0])
ed1 = ed.map(lambda x: x[1])
assert ed0 == EmpiricalDistribution(Counter({0: 5, 1: 4}))
assert ed1 == EmpiricalDistribution(Counter({0: 7, 1: 2}))
pd = ProbabilityDistribution({(0, 0): 0.3, (0, 1): 0.3, (1, 0): 0.4, (1, 1): 0.0})
pd0 = pd.map(lambda x: sum(x))
assert pd0 == ProbabilityDistribution({0: 0.3, 1: 0.7})
def test_expectation_and_variance() -> None:
ed = EmpiricalDistribution(Counter({(0, 0): 3, (0, 1): 2, (1, 0): 4, (1, 1): 0}))
assert isclose(ed.sample_mean(sum), 2 / 3)
assert isclose(ed.sample_variance(sum), 1 / 4)
pd = ProbabilityDistribution.from_empirical_distribution(ed)
assert isclose(pd.expectation(sum), 2 / 3)
assert isclose(pd.variance(sum), 2 / 9)
| tket/pytket/tests/distribution_test.py/0 | {
"file_path": "tket/pytket/tests/distribution_test.py",
"repo_id": "tket",
"token_count": 1766
} | 370 |
OPENQASM 2.0;
include "qelib1.inc";
qreg q[23];
creg c[23];
rz(0.0*pi) q[0];
rz(0.0*pi) q[1];
rz(0.0*pi) q[2];
rz(0.0*pi) q[3];
rz(0.0*pi) q[4];
rz(0.0*pi) q[5];
rz(0.0*pi) q[6];
rz(0.0*pi) q[7];
rz(0.0*pi) q[8];
rz(0.0*pi) q[9];
rz(0.0*pi) q[10];
rz(0.0*pi) q[11];
rz(0.0*pi) q[12];
rz(0.0*pi) q[13];
rz(0.0*pi) q[14];
rz(0.0*pi) q[15];
rz(0.0*pi) q[16];
rz(0.0*pi) q[17];
rz(0.0*pi) q[18];
rz(0.0*pi) q[19];
rz(0.0*pi) q[20];
rz(0.0*pi) q[21];
rz(0.0*pi) q[22];
sx q[0];
sx q[1];
sx q[2];
sx q[3];
sx q[4];
sx q[5];
sx q[6];
sx q[7];
sx q[8];
sx q[9];
sx q[10];
sx q[11];
sx q[12];
sx q[13];
sx q[14];
sx q[15];
sx q[16];
sx q[17];
sx q[18];
sx q[19];
sx q[20];
sx q[21];
sx q[22];
rz(3.000944375976313*pi) q[0];
rz(2.99336695582533*pi) q[1];
rz(2.99921112872811*pi) q[2];
rz(2.99954979623797*pi) q[3];
rz(3.008471591328462*pi) q[4];
rz(2.99730737303035*pi) q[5];
rz(3.006092019613779*pi) q[6];
rz(3.000062203424661*pi) q[7];
rz(3.011189884083554*pi) q[8];
rz(2.98911327925043*pi) q[9];
rz(2.99995790244453*pi) q[10];
rz(3.003930569637459*pi) q[11];
rz(3.002265230577037*pi) q[12];
rz(2.9982459978761*pi) q[13];
rz(2.9962230500357503*pi) q[14];
rz(2.99496933952251*pi) q[15];
rz(3.009817175987404*pi) q[16];
rz(2.98488417200537*pi) q[17];
rz(2.99216768627906*pi) q[18];
rz(2.99502568371605*pi) q[19];
rz(2.99491984238575*pi) q[20];
rz(2.99205645782764*pi) q[21];
rz(3.013919800284479*pi) q[22];
sx q[0];
sx q[1];
sx q[2];
sx q[3];
sx q[4];
sx q[5];
sx q[6];
sx q[7];
sx q[8];
sx q[9];
sx q[10];
sx q[11];
sx q[12];
sx q[13];
sx q[14];
sx q[15];
sx q[16];
sx q[17];
sx q[18];
sx q[19];
sx q[20];
sx q[21];
sx q[22];
rz(1.0*pi) q[0];
rz(1.0*pi) q[1];
rz(1.0*pi) q[2];
rz(1.0*pi) q[3];
rz(1.0*pi) q[4];
rz(1.0*pi) q[5];
rz(1.0*pi) q[6];
rz(1.0*pi) q[7];
rz(1.0*pi) q[8];
rz(1.0*pi) q[9];
rz(1.0*pi) q[10];
rz(1.0*pi) q[11];
rz(1.0*pi) q[12];
rz(1.0*pi) q[13];
rz(1.0*pi) q[14];
rz(1.0*pi) q[15];
rz(1.0*pi) q[16];
rz(1.0*pi) q[17];
rz(1.0*pi) q[18];
rz(1.0*pi) q[19];
rz(1.0*pi) q[20];
rz(1.0*pi) q[21];
rz(1.0*pi) q[22];
cx q[0],q[1];
cx q[2],q[3];
cx q[4],q[5];
cx q[6],q[7];
cx q[8],q[9];
cx q[10],q[11];
cx q[12],q[13];
cx q[14],q[15];
cx q[16],q[17];
cx q[18],q[19];
cx q[20],q[21];
rz(0.0*pi) q[0];
cx q[1],q[2];
cx q[3],q[4];
cx q[5],q[6];
cx q[7],q[8];
cx q[9],q[10];
cx q[11],q[12];
cx q[13],q[14];
cx q[15],q[16];
cx q[17],q[18];
cx q[19],q[20];
cx q[21],q[22];
sx q[0];
rz(0.0*pi) q[1];
rz(0.0*pi) q[2];
rz(0.0*pi) q[3];
rz(0.0*pi) q[4];
rz(0.0*pi) q[5];
rz(0.0*pi) q[6];
rz(0.0*pi) q[7];
rz(0.0*pi) q[8];
rz(0.0*pi) q[9];
rz(0.0*pi) q[10];
rz(0.0*pi) q[11];
rz(0.0*pi) q[12];
rz(0.0*pi) q[13];
rz(0.0*pi) q[14];
rz(0.0*pi) q[15];
rz(0.0*pi) q[16];
rz(0.0*pi) q[17];
rz(0.0*pi) q[18];
rz(0.0*pi) q[19];
rz(0.0*pi) q[20];
rz(0.0*pi) q[21];
rz(0.0*pi) q[22];
rz(3.476807861242427*pi) q[0];
sx q[1];
sx q[2];
sx q[3];
sx q[4];
sx q[5];
sx q[6];
sx q[7];
sx q[8];
sx q[9];
sx q[10];
sx q[11];
sx q[12];
sx q[13];
sx q[14];
sx q[15];
sx q[16];
sx q[17];
sx q[18];
sx q[19];
sx q[20];
sx q[21];
sx q[22];
sx q[0];
rz(3.472256237319963*pi) q[1];
rz(3.47599915465964*pi) q[2];
rz(3.463712675928812*pi) q[3];
rz(3.479036818202335*pi) q[4];
rz(3.473688555149687*pi) q[5];
rz(3.4736279155028837*pi) q[6];
rz(3.470696205817909*pi) q[7];
rz(3.468144168964389*pi) q[8];
rz(3.470175296305337*pi) q[9];
rz(3.470700818954446*pi) q[10];
rz(3.471044721602178*pi) q[11];
rz(3.462198781352418*pi) q[12];
rz(3.479879823573195*pi) q[13];
rz(3.471639937265919*pi) q[14];
rz(3.46384948881209*pi) q[15];
rz(3.485148232536909*pi) q[16];
rz(3.460032611267675*pi) q[17];
rz(3.500533861665719*pi) q[18];
rz(3.490836057611597*pi) q[19];
rz(3.467694037257083*pi) q[20];
rz(3.5008046949519622*pi) q[21];
rz(3.481000724835637*pi) q[22];
rz(1.0*pi) q[0];
sx q[1];
sx q[2];
sx q[3];
sx q[4];
sx q[5];
sx q[6];
sx q[7];
sx q[8];
sx q[9];
sx q[10];
sx q[11];
sx q[12];
sx q[13];
sx q[14];
sx q[15];
sx q[16];
sx q[17];
sx q[18];
sx q[19];
sx q[20];
sx q[21];
sx q[22];
measure q[0] -> c[0];
rz(1.0*pi) q[1];
rz(1.0*pi) q[2];
rz(1.0*pi) q[3];
rz(1.0*pi) q[4];
rz(1.0*pi) q[5];
rz(1.0*pi) q[6];
rz(1.0*pi) q[7];
rz(1.0*pi) q[8];
rz(1.0*pi) q[9];
rz(1.0*pi) q[10];
rz(1.0*pi) q[11];
rz(1.0*pi) q[12];
rz(1.0*pi) q[13];
rz(1.0*pi) q[14];
rz(1.0*pi) q[15];
rz(1.0*pi) q[16];
rz(1.0*pi) q[17];
rz(1.0*pi) q[18];
rz(1.0*pi) q[19];
rz(1.0*pi) q[20];
rz(1.0*pi) q[21];
rz(1.0*pi) q[22];
measure q[1] -> c[1];
measure q[2] -> c[2];
measure q[3] -> c[3];
measure q[4] -> c[4];
measure q[5] -> c[5];
measure q[6] -> c[6];
measure q[7] -> c[7];
measure q[8] -> c[8];
measure q[9] -> c[9];
measure q[10] -> c[10];
measure q[11] -> c[11];
measure q[12] -> c[12];
measure q[13] -> c[13];
measure q[14] -> c[14];
measure q[15] -> c[15];
measure q[16] -> c[16];
measure q[17] -> c[17];
measure q[18] -> c[18];
measure q[19] -> c[19];
measure q[20] -> c[20];
measure q[21] -> c[21];
measure q[22] -> c[22];
| tket/pytket/tests/qasm_test_files/test13.qasm/0 | {
"file_path": "tket/pytket/tests/qasm_test_files/test13.qasm",
"repo_id": "tket",
"token_count": 3374
} | 371 |
OPENQASM 2.0;
include "qelib1.inc";
//Test controlled rotation gates
qreg q[4];
crz(0.3 * pi) q[0],q[1];
crx(0.5 * pi) q[2],q[1];
cry(0.5 * pi) q[3],q[0];
| tket/pytket/tests/qasm_test_files/test9.qasm/0 | {
"file_path": "tket/pytket/tests/qasm_test_files/test9.qasm",
"repo_id": "tket",
"token_count": 86
} | 372 |
Inputs: 0:Qbit
QGate["H"](0)
QGate["S"](0)
Outputs: 0:Qbit
| tket/pytket/tests/quipper_test_files/test4-2.quip/0 | {
"file_path": "tket/pytket/tests/quipper_test_files/test4-2.quip",
"repo_id": "tket",
"token_count": 34
} | 373 |
Inputs: 0:Qbit, 1:Qbit, 2:Qbit
QGate["H"](2) with controls=[+0,+1]
Outputs: 0:Qbit, 1:Qbit, 2:Qbit
| tket/pytket/tests/quipper_test_files/test5.quip/0 | {
"file_path": "tket/pytket/tests/quipper_test_files/test5.quip",
"repo_id": "tket",
"token_count": 54
} | 374 |
Ways to compile wasm from C/C++ are:
Using emcc:
```
emcc <filename>.c -o <filename>.html
```
This will generate an wasm file and a html file. You can ignore the html.
Using clang, this should work in all clang vesions.
```
clang --target=wasm32 --no-standard-libraries -Wl,--export-all -Wl,--no-entry -o <filename>.wasm <filename>.c
```
If you want to compile wasm files that contains function which return more than one int you need to give some more parameters, this only works with > clang 16
```
clang --target=wasm32 -mmultivalue -Xclang -target-abi -Xclang experimental-mv --no-standard-libraries -Wl,--export-all -Wl,--no-entry -o <filename>.wasm <filename>.c
```
After generating the wasm file you can then run:
```
wasm2wat <filename>.wasm -o <filename>.wast
```
to convert the WASM to human-readable text format.
| tket/pytket/tests/wasm-generation/wasmfromcpp/README.md/0 | {
"file_path": "tket/pytket/tests/wasm-generation/wasmfromcpp/README.md",
"repo_id": "tket",
"token_count": 281
} | 375 |
# Copyright 2019-2024 Cambridge Quantum Computing
#
# 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.
from math import pow, isclose
import numpy as np
import pytest
from pytket import Qubit, Circuit, OpType
from pytket.passes import AutoRebase
from pytket.pauli import Pauli, QubitPauliString
from pytket.utils.results import compare_unitaries
from pytket.zx import (
ZXDiagram,
ZXType,
QuantumType,
ZXWireType,
ZXGen,
Rewrite,
circuit_to_zx,
PhasedGen,
CliffordGen,
DirectedGen,
ZXBox,
)
from sympy import sympify
from typing import Tuple
have_quimb: bool = True
try:
import quimb.tensor # type: ignore
from pytket.zx.tensor_eval import (
unitary_from_quantum_diagram,
fix_boundaries_to_binary_states,
fix_inputs_to_binary_state,
fix_outputs_to_binary_state,
tensor_from_quantum_diagram,
tensor_from_mixed_diagram,
unitary_from_classical_diagram,
density_matrix_from_cptp_diagram,
)
except ModuleNotFoundError:
have_quimb = False
def test_generator_creation() -> None:
diag = ZXDiagram(1, 0, 0, 0)
in_v = diag.get_boundary()[0]
gen = diag.get_vertex_ZXGen(in_v)
assert repr(gen) == "Q-Input"
z_spid = diag.add_vertex(ZXType.ZSpider, 0.3)
spid_gen = diag.get_vertex_ZXGen(z_spid)
assert repr(spid_gen) == "Q-Z(0.3)"
pytest.raises(RuntimeError, diag.add_vertex, ZXType.Triangle, 0.3)
tri = diag.add_vertex(ZXType.Triangle, QuantumType.Classical)
tri_gen = diag.get_vertex_ZXGen(tri)
assert repr(tri_gen) == "C-Tri"
def test_diagram_creation() -> None:
diag = ZXDiagram(1, 1, 0, 0)
z_spid = diag.add_vertex(ZXType.ZSpider, 0.1)
x_spid = diag.add_vertex(ZXType.XSpider, 3.4)
z_spid2 = diag.add_vertex(ZXType.ZSpider, 6.7, QuantumType.Classical)
pytest.raises(RuntimeError, diag.add_vertex, ZXType.ZXBox, 3.0)
with pytest.raises(RuntimeError) as errorinfo:
diag.check_validity()
assert "Boundary vertex does not have degree 1" in str(errorinfo.value)
diag.add_wire(diag.get_boundary()[0], z_spid)
diag.add_wire(diag.get_boundary()[1], x_spid)
diag.add_wire(z_spid, x_spid)
diag.add_wire(x_spid, z_spid, ZXWireType.H)
extra = diag.add_wire(diag.get_boundary()[1], z_spid)
with pytest.raises(RuntimeError) as errorinfo:
diag.check_validity()
assert "Boundary vertex does not have degree 1" in str(errorinfo.value)
diag.remove_wire(extra)
diag.check_validity()
wrong_port = diag.add_wire(u=z_spid2, v=x_spid, u_port=0)
with pytest.raises(RuntimeError) as errorinfo:
diag.check_validity()
assert "Wire at a named port of an undirected vertex" in str(errorinfo.value)
diag.remove_wire(wrong_port)
tri = diag.add_vertex(ZXType.Triangle)
diag.add_wire(u=tri, v=z_spid, u_port=0)
with pytest.raises(RuntimeError) as errorinfo:
diag.check_validity()
assert "Not all ports of a directed vertex have wires connected" in str(
errorinfo.value
)
no_port = diag.add_wire(z_spid, tri)
with pytest.raises(RuntimeError) as errorinfo:
diag.check_validity()
assert "Wire at an unnamed port of a directed vertex" in str(errorinfo.value)
diag.remove_wire(no_port)
diag.add_wire(u=z_spid, v=tri, v_port=1)
diag.check_validity()
extra_port = diag.add_wire(u=tri, v=z_spid, u_port=1)
with pytest.raises(RuntimeError) as errorinfo:
diag.check_validity()
assert "Multiple wires on the same port of a vertex" in str(errorinfo.value)
diag.remove_wire(extra_port)
inner = ZXDiagram(1, 2, 1, 0)
inner_spid = inner.add_vertex(ZXType.ZSpider, 0.6, QuantumType.Classical)
inner.add_wire(inner_spid, inner.get_boundary()[0])
inner.add_wire(inner_spid, inner.get_boundary()[1])
inner.add_wire(inner_spid, inner.get_boundary()[2], ZXWireType.H)
inner.add_wire(inner_spid, inner.get_boundary()[3], qtype=QuantumType.Classical)
box = diag.add_zxbox(inner)
diag.add_wire(u=box, v=z_spid2, u_port=0)
diag.add_wire(u=box, v=z_spid2, u_port=1)
diag.add_wire(u=box, v=x_spid, u_port=2)
wrong_qtype = diag.add_wire(u=box, v=z_spid2, u_port=3)
with pytest.raises(RuntimeError) as errorinfo:
diag.check_validity()
assert "QuantumType of wire is incompatible with the given port" in str(
errorinfo.value
)
diag.set_wire_qtype(wrong_qtype, QuantumType.Classical)
diag.check_validity()
@pytest.mark.skipif(not have_quimb, reason="quimb not installed")
def test_known_tensors() -> None:
# A single basic edge
diag = ZXDiagram(1, 1, 0, 0)
w = diag.add_wire(diag.get_boundary()[0], diag.get_boundary()[1])
correct = np.asarray([[1, 0], [0, 1]])
evaluated = unitary_from_quantum_diagram(diag)
assert np.allclose(evaluated, correct)
# A single H edge
diag.set_wire_type(w, ZXWireType.H)
diag.multiply_scalar(0.5)
correct = np.asarray([[1, 1], [1, -1]]) * np.sqrt(0.5)
evaluated = unitary_from_quantum_diagram(diag)
assert np.allclose(evaluated, correct)
# A triangle
diag.remove_wire(w)
diag.multiply_scalar(2.0)
tri = diag.add_vertex(ZXType.Triangle)
diag.add_wire(u=diag.get_boundary()[0], v=tri, v_port=0)
diag.add_wire(u=diag.get_boundary()[1], v=tri, v_port=1)
correct = np.asarray([[1, 0], [1, 1]], dtype=complex)
evaluated = unitary_from_quantum_diagram(diag)
assert np.allclose(evaluated, correct)
# A pair of edges to test endianness
diag = ZXDiagram(2, 2, 0, 0)
ins = diag.get_boundary(ZXType.Input)
outs = diag.get_boundary(ZXType.Output)
diag.add_wire(ins[0], outs[0])
diag.add_wire(ins[1], outs[1], type=ZXWireType.H)
correct = np.asarray([[1, 1, 0, 0], [1, -1, 0, 0], [0, 0, 1, 1], [0, 0, 1, -1]])
evaluated = unitary_from_quantum_diagram(diag)
assert np.allclose(evaluated, correct)
initialised = fix_inputs_to_binary_state(diag, [0, 1])
simulated = unitary_from_quantum_diagram(initialised)
assert np.allclose(simulated.T, correct[:, 1])
# A Bell effect
diag = ZXDiagram(2, 0, 0, 0)
ins = diag.get_boundary()
diag.add_wire(ins[0], ins[1])
correct = np.asarray([[1, 0, 0, 1]])
evaluated = unitary_from_quantum_diagram(diag)
assert np.allclose(evaluated, correct)
initialised = fix_inputs_to_binary_state(diag, [0, 1])
simulated = unitary_from_quantum_diagram(initialised)
assert np.allclose(simulated, correct[0, 1])
initialised = fix_inputs_to_binary_state(diag, [1, 1])
simulated = unitary_from_quantum_diagram(initialised)
assert np.allclose(simulated, correct[0, 3])
# A single Z spider
diag = ZXDiagram(2, 3, 0, 0)
ins = diag.get_boundary(ZXType.Input)
outs = diag.get_boundary(ZXType.Output)
spid = diag.add_vertex(ZXType.ZSpider, 0.3)
diag.add_wire(spid, ins[0])
diag.add_wire(spid, ins[1])
diag.add_wire(spid, outs[0])
diag.add_wire(spid, outs[1])
diag.add_wire(spid, outs[2])
correct = np.zeros((8, 4), dtype=complex)
correct[0, 0] = 1
correct[7, 3] = np.exp(1j * np.pi * 0.3)
evaluated = unitary_from_quantum_diagram(diag)
assert np.allclose(evaluated, correct)
initialised = fix_inputs_to_binary_state(diag, [1, 1])
simulated = unitary_from_quantum_diagram(initialised)
assert np.allclose(simulated.T, correct[:, 3])
# Adding a self-loop
self_loop = diag.add_wire(spid, spid)
evaluated = unitary_from_quantum_diagram(diag)
assert np.allclose(evaluated, correct)
diag.set_wire_type(self_loop, ZXWireType.H)
correct[7, 3] = np.exp(1j * np.pi * 1.3)
evaluated = unitary_from_quantum_diagram(diag)
assert np.allclose(evaluated, correct)
# A single X spider
diag.remove_wire(self_loop)
diag.set_vertex_ZXGen(spid, ZXGen.create(ZXType.XSpider, 0.3))
phase = np.exp(1j * np.pi * 0.3)
p = 1.0 + phase
m = 1.0 - phase
correct = np.asarray(
[
[p, m, m, p],
[m, p, p, m],
[m, p, p, m],
[p, m, m, p],
[m, p, p, m],
[p, m, m, p],
[p, m, m, p],
[m, p, p, m],
]
)
correct = correct * pow(0.5, 2.5)
evaluated = unitary_from_quantum_diagram(diag)
assert np.allclose(evaluated, correct)
diag.set_vertex_ZXGen(spid, ZXGen.create(ZXType.ZSpider, 0.3))
for w in diag.adj_wires(spid):
diag.set_wire_type(w, ZXWireType.H)
evaluated = unitary_from_quantum_diagram(diag)
correct = correct * pow(2.0, 2.5)
assert np.allclose(evaluated, correct)
initialised = fix_inputs_to_binary_state(diag, [0, 1])
simulated = unitary_from_quantum_diagram(initialised)
assert np.allclose(simulated.T, correct[:, 1])
# Bialgebra example
diag = ZXDiagram(2, 2, 0, 0)
ins = diag.get_boundary(ZXType.Input)
outs = diag.get_boundary(ZXType.Output)
z = diag.add_vertex(ZXType.ZSpider)
x = diag.add_vertex(ZXType.XSpider)
diag.add_wire(z, ins[0])
diag.add_wire(z, ins[1])
diag.add_wire(x, outs[0])
diag.add_wire(x, outs[1])
diag.add_wire(z, x)
correct = np.asarray([[1, 0, 0, 0], [0, 0, 0, 1], [0, 0, 0, 1], [1, 0, 0, 0]])
correct = correct * pow(0.5, 0.5)
evaluated = unitary_from_quantum_diagram(diag)
assert np.allclose(evaluated, correct)
other = ZXDiagram(2, 2, 0, 0)
oth_ins = other.get_boundary(ZXType.Input)
oth_outs = other.get_boundary(ZXType.Output)
x0 = other.add_vertex(ZXType.XSpider)
x1 = other.add_vertex(ZXType.XSpider)
z0 = other.add_vertex(ZXType.ZSpider)
z1 = other.add_vertex(ZXType.ZSpider)
other.add_wire(x0, oth_ins[0])
other.add_wire(x1, oth_ins[1])
other.add_wire(z0, oth_outs[0])
other.add_wire(z1, oth_outs[1])
other.add_wire(x0, z0)
other.add_wire(x0, z1)
other.add_wire(x1, z0)
other.add_wire(x1, z1)
evaluated = unitary_from_quantum_diagram(other)
evaluated = evaluated * pow(2.0, 0.5)
assert np.allclose(evaluated, correct)
# A CX gate
diag = ZXDiagram(2, 2, 0, 0)
ins = diag.get_boundary(ZXType.Input)
outs = diag.get_boundary(ZXType.Output)
c = diag.add_vertex(ZXType.ZSpider)
t = diag.add_vertex(ZXType.XSpider)
diag.add_wire(ins[0], c)
diag.add_wire(c, outs[0])
diag.add_wire(ins[1], t)
diag.add_wire(t, outs[1])
diag.add_wire(c, t)
correct = np.asarray([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]])
evaluated = unitary_from_quantum_diagram(diag)
evaluated = evaluated * pow(2.0, 0.5)
assert np.allclose(evaluated, correct)
# A ZXBox containing a CX gate
diag2 = ZXDiagram(2, 2, 0, 0)
ins = diag2.get_boundary(ZXType.Input)
outs = diag2.get_boundary(ZXType.Output)
b = diag2.add_zxbox(diag)
diag2.add_wire(u=ins[0], v=b, v_port=0)
diag2.add_wire(u=ins[1], v=b, v_port=1)
diag2.add_wire(u=outs[0], v=b, v_port=2)
diag2.add_wire(u=outs[1], v=b, v_port=3)
evaluated = tensor_from_mixed_diagram(diag2)
evaluated *= 2.0
correct = correct.reshape((2, 2, 2, 2))
correct = np.kron(correct, correct).reshape((2, 2, 2, 2, 2, 2, 2, 2))
assert np.allclose(evaluated, correct)
# A Pauli gadget
diag = ZXDiagram(4, 4, 0, 0)
ins = diag.get_boundary(ZXType.Input)
outs = diag.get_boundary(ZXType.Output)
v = diag.add_vertex(ZXType.XSpider, 0.5)
vdg = diag.add_vertex(ZXType.XSpider, -0.5)
z = diag.add_vertex(ZXType.ZSpider)
x = diag.add_vertex(ZXType.ZSpider)
y = diag.add_vertex(ZXType.ZSpider)
axis = diag.add_vertex(ZXType.XSpider)
phase = diag.add_vertex(ZXType.ZSpider, 0.3)
diag.add_wire(ins[0], v)
diag.add_wire(v, y)
diag.add_wire(y, vdg)
diag.add_wire(vdg, outs[0])
diag.add_wire(ins[1], outs[1])
diag.add_wire(ins[2], z)
diag.add_wire(z, outs[2])
diag.add_wire(ins[3], x, ZXWireType.H)
diag.add_wire(x, outs[3], ZXWireType.H)
diag.add_wire(x, axis)
diag.add_wire(y, axis)
diag.add_wire(z, axis)
diag.add_wire(phase, axis)
correct = (
np.cos(0.15 * np.pi) * np.eye(16)
- 1j
* np.sin(0.15 * np.pi)
* QubitPauliString(
[Qubit(i) for i in range(4)], [Pauli.Y, Pauli.I, Pauli.Z, Pauli.X]
).to_sparse_matrix()
)
evaluated = unitary_from_quantum_diagram(diag)
evaluated = evaluated * np.exp(-1j * 0.15 * np.pi)
assert np.allclose(evaluated, correct)
initialised = fix_inputs_to_binary_state(diag, [0, 1, 0, 1])
simulated = unitary_from_quantum_diagram(initialised)
simulated = simulated * np.exp(-1j * 0.15 * np.pi)
assert np.allclose(simulated, correct[:, 5])
postselected = fix_outputs_to_binary_state(diag, [1, 1, 0, 0])
postsimulated = unitary_from_quantum_diagram(postselected)
postsimulated = postsimulated * np.exp(-1j * 0.15 * np.pi)
assert np.allclose(postsimulated, correct[12, :])
# A scalar
diag = ZXDiagram(0, 0, 0, 0)
red_one = diag.add_vertex(ZXType.XSpider, 1.0)
green_one = diag.add_vertex(ZXType.ZSpider, 0.3)
diag.add_wire(red_one, green_one)
red_three = diag.add_vertex(ZXType.XSpider)
green_three = diag.add_vertex(ZXType.ZSpider)
diag.add_wire(red_three, green_three)
diag.add_wire(red_three, green_three)
diag.add_wire(red_three, green_three)
evaluated = tensor_from_quantum_diagram(diag)
assert np.allclose(evaluated, np.exp(1j * 0.3 * np.pi))
@pytest.mark.skipif(not have_quimb, reason="quimb not installed")
def test_classical_and_cptp() -> None:
# A single classical spider in a classical diagram
diag = ZXDiagram(0, 0, 1, 2)
ins = diag.get_boundary(ZXType.Input)
outs = diag.get_boundary(ZXType.Output)
spid = diag.add_vertex(ZXType.ZSpider, qtype=QuantumType.Classical)
diag.add_wire(ins[0], spid, qtype=QuantumType.Classical)
diag.add_wire(outs[0], spid, qtype=QuantumType.Classical)
diag.add_wire(outs[1], spid, qtype=QuantumType.Classical)
correct = np.asarray([[1, 0], [0, 0], [0, 0], [0, 1]])
evaluated = unitary_from_classical_diagram(diag)
assert np.allclose(evaluated, correct)
# Compare a classical spider to a quantum spider in CPTP
diag = ZXDiagram(1, 2, 0, 0)
ins = diag.get_boundary(ZXType.Input)
outs = diag.get_boundary(ZXType.Output)
spid = diag.add_vertex(ZXType.ZSpider, 1.0, QuantumType.Classical)
diag.add_wire(ins[0], spid)
diag.add_wire(outs[0], spid)
diag.add_wire(outs[1], spid)
correct = np.zeros((8, 8))
correct[0, 0] = 1.0
correct[7, 7] = -1.0
evaluated = density_matrix_from_cptp_diagram(diag)
assert np.allclose(evaluated, correct)
# Change classical spider to quantum spider
diag.set_vertex_ZXGen(spid, ZXGen.create(ZXType.ZSpider, 1.0, QuantumType.Quantum))
correct[0, 7] = -1.0
correct[7, 0] = -1.0
correct[7, 7] = 1.0
evaluated = density_matrix_from_cptp_diagram(diag)
assert np.allclose(evaluated, correct)
# Add discard by connecting to a classical spider
disc = diag.add_vertex(ZXType.ZSpider, 0.0, QuantumType.Classical)
diag.add_wire(spid, disc)
correct[0, 7] = 0.0
correct[7, 0] = 0.0
evaluated = density_matrix_from_cptp_diagram(diag)
assert np.allclose(evaluated, correct)
# Quantum teleportation
diag = ZXDiagram(3, 1, 0, 0)
ins = diag.get_boundary(ZXType.Input)
outs = diag.get_boundary(ZXType.Output)
bell_cx_ctrl = diag.add_vertex(ZXType.ZSpider)
bell_cx_trgt = diag.add_vertex(ZXType.XSpider)
meas_cx_ctrl = diag.add_vertex(ZXType.ZSpider)
meas_cx_trgt = diag.add_vertex(ZXType.XSpider)
meas_z = diag.add_vertex(ZXType.ZSpider, qtype=QuantumType.Classical)
meas_x = diag.add_vertex(ZXType.XSpider, qtype=QuantumType.Classical)
init_z = diag.add_vertex(ZXType.ZSpider, qtype=QuantumType.Classical)
init_x = diag.add_vertex(ZXType.XSpider, qtype=QuantumType.Classical)
corr_z = diag.add_vertex(ZXType.ZSpider)
corr_x = diag.add_vertex(ZXType.XSpider)
# Prepare Bell state
diag.add_wire(ins[1], bell_cx_ctrl, ZXWireType.H)
diag.add_wire(ins[2], bell_cx_trgt)
diag.add_wire(bell_cx_ctrl, bell_cx_trgt)
# Perform Bell measurement
diag.add_wire(ins[0], meas_cx_ctrl)
diag.add_wire(bell_cx_ctrl, meas_cx_trgt)
diag.add_wire(meas_cx_ctrl, meas_cx_trgt)
diag.add_wire(meas_cx_ctrl, meas_x)
diag.add_wire(meas_cx_trgt, meas_z)
# Apply corrections
diag.add_wire(meas_x, init_x, qtype=QuantumType.Classical)
diag.add_wire(meas_z, init_z, qtype=QuantumType.Classical)
diag.add_wire(init_x, corr_z)
diag.add_wire(init_z, corr_x)
diag.add_wire(bell_cx_trgt, corr_x)
diag.add_wire(corr_x, corr_z)
diag.add_wire(corr_z, outs[0])
correct = np.zeros((16, 16))
# Correct [0,0] initialisation of Bell state
correct[0, 0] = 1.0
correct[0, 9] = 1.0
correct[9, 0] = 1.0
correct[9, 9] = 1.0
# [0,1] initialisation of Bell state applies X
correct[10, 10] = 1.0
correct[10, 3] = 1.0
correct[3, 10] = 1.0
correct[3, 3] = 1.0
# [1,0] initialisation of Bell state applies Z
correct[4, 4] = 1.0
correct[4, 13] = -1.0
correct[13, 4] = -1.0
correct[13, 13] = 1.0
# [1,1] initialisation of Bell state applies Y
correct[14, 14] = 1.0
correct[14, 7] = -1.0
correct[7, 14] = -1.0
correct[7, 7] = 1.0
evaluated = density_matrix_from_cptp_diagram(diag)
evaluated = evaluated * 8.0
assert np.allclose(evaluated, correct)
# Simulate for different input states
initialised = fix_inputs_to_binary_state(diag, [0, 0, 0])
simulated = density_matrix_from_cptp_diagram(initialised)
assert np.allclose(simulated, np.asarray([[1, 0], [0, 0]]))
initialised = fix_inputs_to_binary_state(diag, [1, 0, 0])
simulated = density_matrix_from_cptp_diagram(initialised)
assert np.allclose(simulated, np.asarray([[0, 0], [0, 1]]))
@pytest.mark.skipif(not have_quimb, reason="quimb not installed")
def test_tensor_errors() -> None:
# A symbolic generator
diag = ZXDiagram(0, 1, 0, 0)
v = diag.add_vertex(ZXType.XSpider, sympify("2*a"))
diag.add_wire(v, diag.get_boundary()[0])
with pytest.raises(ValueError) as exc_info:
tensor_from_quantum_diagram(diag)
assert "symbolic expression" in exc_info.value.args[0]
# A symbolic scalar
diag.set_vertex_ZXGen(v, PhasedGen(ZXType.XSpider, 0.5))
diag.multiply_scalar(sympify("2*a"))
with pytest.raises(ValueError) as exc_info:
tensor_from_quantum_diagram(diag)
assert "symbolic scalar" in exc_info.value.args[0]
# Non-quantum components in tensor_from_quantum_diagram
diag = ZXDiagram(0, 1, 0, 0)
v = diag.add_vertex(ZXType.XSpider, 0.3, QuantumType.Classical)
diag.add_wire(v, diag.get_boundary()[0], qtype=QuantumType.Classical)
with pytest.raises(ValueError) as exc_info:
tensor_from_quantum_diagram(diag)
assert "Non-quantum vertex" in exc_info.value.args[0]
diag.set_vertex_ZXGen(v, PhasedGen(ZXType.XSpider, 0.3))
with pytest.raises(ValueError) as exc_info:
tensor_from_quantum_diagram(diag)
assert "Non-quantum wire" in exc_info.value.args[0]
# Mixed boundaries when expecting just one qtype
diag = ZXDiagram(0, 1, 0, 1)
v = diag.add_vertex(ZXType.XSpider, 0.0, QuantumType.Classical)
diag.add_wire(v, diag.get_boundary()[0])
diag.add_wire(v, diag.get_boundary()[1], qtype=QuantumType.Classical)
with pytest.raises(ValueError) as exc_info:
unitary_from_classical_diagram(diag)
assert "Non-classical boundary vertex" in exc_info.value.args[0]
with pytest.raises(ValueError) as exc_info:
density_matrix_from_cptp_diagram(diag)
assert "Non-quantum boundary vertex" in exc_info.value.args[0]
# Errors in fixing boundaries
with pytest.raises(ValueError) as exc_info:
fix_boundaries_to_binary_states(diag, {v: 0})
assert "boundary vertices" in exc_info.value.args[0]
with pytest.raises(ValueError) as exc_info:
fix_boundaries_to_binary_states(diag, {diag.get_boundary()[0]: 2})
assert "|0> and |1>" in exc_info.value.args[0]
# Wrong length of vector to fix inputs/outputs
with pytest.raises(ValueError) as exc_info:
fix_inputs_to_binary_state(diag, [0, 1, 0])
assert "3 values for 0 inputs" in exc_info.value.args[0]
with pytest.raises(ValueError) as exc_info:
fix_outputs_to_binary_state(diag, [])
assert "0 values for 2 outputs" in exc_info.value.args[0]
@pytest.mark.skipif(not have_quimb, reason="quimb not installed")
def test_graph_like_reduction() -> None:
# Diagram on https://arxiv.org/pdf/1902.03178.pdf, Figure 2
# We have added an extra input/output pair for testing purposes
diag = ZXDiagram(5, 5, 0, 0)
ins = diag.get_boundary(ZXType.Input)
outs = diag.get_boundary(ZXType.Output)
z1 = diag.add_vertex(ZXType.ZSpider)
z2 = diag.add_vertex(ZXType.ZSpider)
z3 = diag.add_vertex(ZXType.ZSpider)
ph1 = diag.add_vertex(ZXType.ZSpider, 0.5)
ph2 = diag.add_vertex(ZXType.ZSpider, 1.0)
x1 = diag.add_vertex(ZXType.XSpider)
x2 = diag.add_vertex(ZXType.XSpider)
x3 = diag.add_vertex(ZXType.XSpider)
diag.add_wire(ins[0], z1)
diag.add_wire(z1, ph1)
diag.add_wire(ph1, z2)
diag.add_wire(z2, outs[0], ZXWireType.H)
diag.add_wire(z1, x1)
diag.add_wire(z2, x2)
diag.add_wire(ins[1], x1, ZXWireType.H)
diag.add_wire(x1, z3)
diag.add_wire(z3, x2)
diag.add_wire(x2, ph2)
diag.add_wire(ph2, outs[1])
diag.add_wire(z3, x3)
diag.add_wire(ins[2], x3, ZXWireType.H)
diag.add_wire(x3, outs[2])
diag.add_wire(ins[3], outs[3], ZXWireType.H)
diag.add_wire(ins[4], outs[4])
diag.check_validity()
original = unitary_from_quantum_diagram(diag)
# Replace X with Z spiders
assert Rewrite.red_to_green().apply(diag)
assert diag.count_vertices(ZXType.XSpider) == 0
assert diag.count_vertices(ZXType.ZSpider) == 8
# Spider fusion
assert Rewrite.spider_fusion().apply(diag)
assert diag.count_vertices(ZXType.ZSpider) == 6
# Parallel edge pair removal
assert not Rewrite.parallel_h_removal().apply(diag)
# Remove hadamard edges connected directly to the boundaries
assert Rewrite.io_extension().apply(diag)
assert diag.count_vertices(ZXType.ZSpider) == 10
# Boundary vertices sharing spiders
# Deal with directly connected in/outputs
assert Rewrite.separate_boundaries().apply(diag)
assert diag.count_vertices(ZXType.ZSpider) == 13
diag.check_validity()
final = unitary_from_quantum_diagram(diag)
final = final * pow(2.0, -3.5)
assert np.allclose(original, final)
@pytest.mark.skipif(not have_quimb, reason="quimb not installed")
def test_spider_fusion() -> None:
diag = ZXDiagram(2, 1, 0, 0)
ins = diag.get_boundary(ZXType.Input)
outs = diag.get_boundary(ZXType.Output)
s1 = diag.add_vertex(ZXType.ZSpider, 0.1)
s2 = diag.add_vertex(ZXType.ZSpider, 0.3)
s3 = diag.add_vertex(ZXType.ZSpider)
s4 = diag.add_vertex(ZXType.ZSpider, 0.5)
s5 = diag.add_vertex(ZXType.ZSpider)
diag.add_wire(ins[0], s1)
diag.add_wire(ins[1], s5, ZXWireType.H)
diag.add_wire(s1, s2, ZXWireType.H)
diag.add_wire(s2, s3)
diag.add_wire(s3, s2, ZXWireType.H)
diag.add_wire(s3, s4, ZXWireType.H)
diag.add_wire(s4, s5)
diag.add_wire(s5, s1)
diag.add_wire(s3, outs[0])
diag.add_wire(s3, s3)
diag.add_wire(s3, s3, ZXWireType.H)
diag.check_validity()
original = unitary_from_quantum_diagram(diag)
assert Rewrite.self_loop_removal().apply(diag)
assert Rewrite.spider_fusion().apply(diag)
assert diag.count_vertices(ZXType.ZSpider) == 2
assert Rewrite.self_loop_removal().apply(diag)
assert Rewrite.parallel_h_removal().apply(diag)
assert Rewrite.io_extension().apply(diag)
diag.check_validity()
final = unitary_from_quantum_diagram(diag)
assert np.allclose(original, final)
# Now with a scalar diagram
diag = ZXDiagram(0, 0, 0, 0)
v1 = diag.add_vertex(ZXType.ZSpider)
v2 = diag.add_vertex(ZXType.ZSpider)
v3 = diag.add_vertex(ZXType.ZSpider, 3.22)
v4 = diag.add_vertex(ZXType.ZSpider)
v5 = diag.add_vertex(ZXType.ZSpider)
v6 = diag.add_vertex(ZXType.ZSpider)
diag.add_wire(v1, v4, ZXWireType.H)
diag.add_wire(v4, v5)
diag.add_wire(v5, v4, ZXWireType.H)
diag.add_wire(v5, v6)
diag.add_wire(v6, v3, ZXWireType.H)
diag.add_wire(v3, v2)
diag.add_wire(v2, v3, ZXWireType.H)
diag.add_wire(v2, v1)
diag.check_validity()
assert not Rewrite.self_loop_removal().apply(diag)
assert Rewrite.spider_fusion().apply(diag)
assert diag.count_vertices(ZXType.ZSpider) == 2
assert Rewrite.self_loop_removal().apply(diag)
assert Rewrite.parallel_h_removal().apply(diag)
assert not Rewrite.io_extension().apply(diag)
assert not Rewrite.separate_boundaries().apply(diag)
assert diag.count_vertices(ZXType.ZSpider) == 2
diag.check_validity()
@pytest.mark.skipif(not have_quimb, reason="quimb not installed")(
not have_quimb, reason="quimb not installed"
)
def test_simplification() -> None:
# This diagram follows from section A of https://arxiv.org/pdf/1902.03178.pdf
diag = ZXDiagram(4, 4, 0, 0)
ins = diag.get_boundary(ZXType.Input)
outs = diag.get_boundary(ZXType.Output)
v11 = diag.add_vertex(ZXType.ZSpider, 1.5)
v12 = diag.add_vertex(ZXType.ZSpider, 0.5)
v13 = diag.add_vertex(ZXType.ZSpider)
v14 = diag.add_vertex(ZXType.XSpider)
v15 = diag.add_vertex(ZXType.ZSpider, 0.25)
v21 = diag.add_vertex(ZXType.ZSpider, 0.5)
v22 = diag.add_vertex(ZXType.ZSpider)
v23 = diag.add_vertex(ZXType.ZSpider)
v24 = diag.add_vertex(ZXType.ZSpider, 0.25)
v25 = diag.add_vertex(ZXType.ZSpider)
v31 = diag.add_vertex(ZXType.XSpider)
v32 = diag.add_vertex(ZXType.XSpider)
v33 = diag.add_vertex(ZXType.ZSpider, 0.5)
v34 = diag.add_vertex(ZXType.ZSpider, 0.5)
v35 = diag.add_vertex(ZXType.XSpider)
v41 = diag.add_vertex(ZXType.ZSpider)
v42 = diag.add_vertex(ZXType.ZSpider)
v43 = diag.add_vertex(ZXType.ZSpider, 1.5)
v44 = diag.add_vertex(ZXType.XSpider, 1.0)
v45 = diag.add_vertex(ZXType.ZSpider, 0.5)
v46 = diag.add_vertex(ZXType.XSpider, 1.0)
diag.add_wire(ins[0], v11)
diag.add_wire(v11, v12, ZXWireType.H)
diag.add_wire(v12, v13)
diag.add_wire(v13, v41, ZXWireType.H)
diag.add_wire(v13, v14)
diag.add_wire(v14, v42)
diag.add_wire(v14, v15, ZXWireType.H)
diag.add_wire(v15, outs[0], ZXWireType.H)
diag.add_wire(ins[1], v21)
diag.add_wire(v21, v22)
diag.add_wire(v22, v31)
diag.add_wire(v22, v23, ZXWireType.H)
diag.add_wire(v23, v32)
diag.add_wire(v23, v24)
diag.add_wire(v24, v25, ZXWireType.H)
diag.add_wire(v25, v35)
diag.add_wire(outs[1], v25)
diag.add_wire(ins[2], v31)
diag.add_wire(v31, v32)
diag.add_wire(v32, v33)
diag.add_wire(v33, v34, ZXWireType.H)
diag.add_wire(v34, v35)
diag.add_wire(v35, outs[2])
diag.add_wire(ins[3], v41, ZXWireType.H)
diag.add_wire(v41, v42)
diag.add_wire(v42, v43, ZXWireType.H)
diag.add_wire(v43, v44)
diag.add_wire(v44, v45)
diag.add_wire(v45, v46)
diag.add_wire(v46, outs[3])
diag.check_validity()
original = unitary_from_quantum_diagram(diag)
# Transform into graph-like form
Rewrite.red_to_green().apply(diag)
Rewrite.spider_fusion().apply(diag)
Rewrite.parallel_h_removal().apply(diag)
Rewrite.io_extension().apply(diag)
Rewrite.separate_boundaries().apply(diag)
# Graph simplification via Pauli & Clifford removal
Rewrite.remove_interior_cliffords().apply(diag)
Rewrite.extend_at_boundary_paulis().apply(diag)
Rewrite.remove_interior_paulis().apply(diag)
diag.check_validity()
final = unitary_from_quantum_diagram(diag)
final = final * 0.5 * 1j
assert np.allclose(original, final)
@pytest.mark.skipif(not have_quimb, reason="quimb not installed")
def test_converting_from_circuit() -> None:
c = Circuit(4)
c.CZ(0, 1)
c.CX(1, 2)
c.H(1)
c.X(0)
c.Rx(0.7, 0)
c.Rz(0.2, 1)
c.X(3)
c.H(2)
diag, _ = circuit_to_zx(c)
# Check the unitaries are equal up to a global phase
v = unitary_from_quantum_diagram(diag)
u = c.get_unitary()
m = v.dot(u.conj().T)
phase = m[0][0]
assert isclose(abs(phase), 1)
assert np.allclose(m * (1 / phase), np.eye(16))
def test_constructors() -> None:
phased_gen = PhasedGen(ZXType.ZSpider, 0.5, QuantumType.Quantum)
assert phased_gen.param == 0.5
clifford_gen = CliffordGen(ZXType.PX, True, QuantumType.Quantum)
assert clifford_gen.param == True
directed_gen = DirectedGen(ZXType.Triangle, QuantumType.Quantum)
assert directed_gen.signature == [QuantumType.Quantum] * 2
diag = ZXDiagram(4, 4, 0, 0)
zx_box = ZXBox(diag)
assert zx_box.diagram.scalar == diag.scalar
def joint_normalise_tensor(
a: np.ndarray, b: np.ndarray
) -> Tuple[np.ndarray, np.ndarray]:
a_linear = a.reshape((a.size))
b_linear = b.reshape((b.size))
max_i = 0
max_val = 0
for i in range(a.size):
if abs(a_linear[i]) > max_val:
max_i = i
max_val = abs(a_linear[i])
return (a * (1 / a_linear[max_i]), b * (1 / b_linear[max_i]))
@pytest.mark.skipif(not have_quimb, reason="quimb not installed")
def test_XY_extraction() -> None:
# Identical to the diagram in test_ZXExtraction.cpp
diag = ZXDiagram(3, 3, 0, 0)
ins = diag.get_boundary(ZXType.Input)
outs = diag.get_boundary(ZXType.Output)
v00 = diag.add_vertex(ZXType.XY, 0.7)
v01 = diag.add_vertex(ZXType.XY, 0.2)
v02 = diag.add_vertex(ZXType.XY, 1.9)
v10 = diag.add_vertex(ZXType.XY, 0.56)
v11 = diag.add_vertex(ZXType.XY, 1.2)
v12 = diag.add_vertex(ZXType.XY, 0.9)
o0 = diag.add_vertex(ZXType.PX)
o1 = diag.add_vertex(ZXType.PX)
o2 = diag.add_vertex(ZXType.PX)
diag.add_wire(ins[0], v00)
diag.add_wire(ins[1], v01)
diag.add_wire(ins[2], v02)
diag.add_wire(v00, v10, ZXWireType.H)
diag.add_wire(v00, v12, ZXWireType.H)
diag.add_wire(v01, v10, ZXWireType.H)
diag.add_wire(v01, v11, ZXWireType.H)
diag.add_wire(v01, v12, ZXWireType.H)
diag.add_wire(v02, v11, ZXWireType.H)
diag.add_wire(v02, v12, ZXWireType.H)
diag.add_wire(v10, o0, ZXWireType.H)
diag.add_wire(v10, o2, ZXWireType.H)
diag.add_wire(v11, o0, ZXWireType.H)
diag.add_wire(v11, o1, ZXWireType.H)
diag.add_wire(v11, o2, ZXWireType.H)
diag.add_wire(v12, o1, ZXWireType.H)
diag.add_wire(v12, o2, ZXWireType.H)
diag.add_wire(o0, outs[0])
diag.add_wire(o1, outs[1])
diag.add_wire(o2, outs[2])
diag.check_validity()
circ, _ = diag.to_circuit()
assert circ.n_qubits == 3
diag_u = unitary_from_quantum_diagram(diag)
circ_u = circ.get_unitary()
assert compare_unitaries(diag_u, circ_u)
@pytest.mark.skipif(not have_quimb, reason="quimb not installed")
def test_XY_YZ_extraction() -> None:
# Almost identical to the diagram in test_ZXExtraction.cpp
# Gadgets g3 and g8 removed as they made tensor evaluation real slow
diag = ZXDiagram(5, 5, 0, 0)
ins = diag.get_boundary(ZXType.Input)
outs = diag.get_boundary(ZXType.Output)
i0 = diag.add_vertex(ZXType.XY)
i1 = diag.add_vertex(ZXType.XY)
i2 = diag.add_vertex(ZXType.XY, 0.25)
i3ext = diag.add_vertex(ZXType.XY)
i3 = diag.add_vertex(ZXType.XY, 0.25)
i4 = diag.add_vertex(ZXType.XY)
inter0 = diag.add_vertex(ZXType.XY, -0.25)
inter1 = diag.add_vertex(ZXType.XY, -0.25)
o0 = diag.add_vertex(ZXType.XY)
o0ext = diag.add_vertex(ZXType.PX)
o1 = diag.add_vertex(ZXType.XY)
o1ext = diag.add_vertex(ZXType.PX)
o2 = diag.add_vertex(ZXType.XY)
o2ext = diag.add_vertex(ZXType.PX)
o3 = diag.add_vertex(ZXType.PX)
o4 = diag.add_vertex(ZXType.XY)
o4ext = diag.add_vertex(ZXType.PX)
g0 = diag.add_vertex(ZXType.YZ, -0.25)
g1 = diag.add_vertex(ZXType.YZ, 0.25)
g2 = diag.add_vertex(ZXType.YZ, 0.25)
g4 = diag.add_vertex(ZXType.YZ, 0.25)
g5 = diag.add_vertex(ZXType.YZ, 0.25)
g6 = diag.add_vertex(ZXType.YZ, -0.25)
g7 = diag.add_vertex(ZXType.YZ, -0.25)
g9 = diag.add_vertex(ZXType.YZ, -0.25)
# Input wires
diag.add_wire(ins[0], i0)
diag.add_wire(ins[1], i1)
diag.add_wire(ins[2], i2)
diag.add_wire(ins[3], i3ext)
diag.add_wire(ins[4], i4)
diag.add_wire(i3ext, i3, ZXWireType.H)
# Interior wires
diag.add_wire(i0, i1, ZXWireType.H)
diag.add_wire(i0, i3, ZXWireType.H)
diag.add_wire(i0, i4, ZXWireType.H)
diag.add_wire(i0, inter1, ZXWireType.H)
diag.add_wire(i0, o0, ZXWireType.H)
diag.add_wire(i1, o1, ZXWireType.H)
diag.add_wire(i2, o2, ZXWireType.H)
diag.add_wire(i3, inter0, ZXWireType.H)
diag.add_wire(i3, o3, ZXWireType.H)
diag.add_wire(i3, o4, ZXWireType.H)
diag.add_wire(i4, inter0, ZXWireType.H)
diag.add_wire(inter0, inter1, ZXWireType.H)
diag.add_wire(inter1, o4, ZXWireType.H)
# Gadget wires
diag.add_wire(g0, i0, ZXWireType.H)
diag.add_wire(g0, i1, ZXWireType.H)
diag.add_wire(g0, inter0, ZXWireType.H)
diag.add_wire(g1, i1, ZXWireType.H)
diag.add_wire(g1, inter0, ZXWireType.H)
diag.add_wire(g2, i0, ZXWireType.H)
diag.add_wire(g2, inter0, ZXWireType.H)
diag.add_wire(g4, i3, ZXWireType.H)
diag.add_wire(g4, inter1, ZXWireType.H)
diag.add_wire(g5, i2, ZXWireType.H)
diag.add_wire(g5, inter1, ZXWireType.H)
diag.add_wire(g6, i2, ZXWireType.H)
diag.add_wire(g6, i3, ZXWireType.H)
diag.add_wire(g6, inter1, ZXWireType.H)
diag.add_wire(g7, i1, ZXWireType.H)
diag.add_wire(g7, o4, ZXWireType.H)
diag.add_wire(g9, i2, ZXWireType.H)
diag.add_wire(g9, i3, ZXWireType.H)
# Output wires
diag.add_wire(o0, o0ext, ZXWireType.H)
diag.add_wire(o1, o1ext, ZXWireType.H)
diag.add_wire(o2, o2ext, ZXWireType.H)
diag.add_wire(o4, o4ext, ZXWireType.H)
diag.add_wire(o0ext, outs[0])
diag.add_wire(o1ext, outs[1])
diag.add_wire(o2ext, outs[2])
diag.add_wire(o3, outs[3])
diag.add_wire(o4ext, outs[4])
diag.check_validity()
circ, _ = diag.to_circuit()
assert circ.n_qubits == 5
diag_u = unitary_from_quantum_diagram(diag)
circ_u = circ.get_unitary()
assert compare_unitaries(diag_u, circ_u)
@pytest.mark.skipif(not have_quimb, reason="quimb not installed")
def test_ZX_rebase() -> None:
diag = ZXDiagram(2, 1, 0, 1)
ins = diag.get_boundary(ZXType.Input)
outs = diag.get_boundary(ZXType.Output)
h0 = diag.add_vertex(ZXType.Hbox)
h1 = diag.add_vertex(ZXType.Hbox, -3.7, QuantumType.Classical)
xy = diag.add_vertex(ZXType.XY, 0.4)
xz = diag.add_vertex(ZXType.XZ, 0.7, QuantumType.Classical)
yz = diag.add_vertex(ZXType.YZ, 1.2)
px = diag.add_vertex(ZXType.PX, False, QuantumType.Classical)
py = diag.add_vertex(ZXType.PY, True, QuantumType.Classical)
pz = diag.add_vertex(ZXType.PZ, True)
zspid = diag.add_vertex(ZXType.ZSpider, 0.9)
xspid = diag.add_vertex(ZXType.XSpider, 1.8, QuantumType.Classical)
diag.add_wire(ins[0], h0)
diag.add_wire(h0, xy)
diag.add_wire(xy, yz)
diag.add_wire(pz, outs[0])
diag.add_wire(yz, zspid)
diag.add_wire(ins[1], xspid)
diag.add_wire(xspid, xz, ZXWireType.Basic, QuantumType.Classical)
diag.add_wire(xz, px, ZXWireType.Basic, QuantumType.Classical)
diag.add_wire(xz, py, ZXWireType.Basic, QuantumType.Classical)
diag.add_wire(py, h1, ZXWireType.Basic, QuantumType.Classical)
diag.add_wire(h1, h1)
diag.add_wire(h1, outs[1], ZXWireType.Basic, QuantumType.Classical)
diag.check_validity()
t0 = tensor_from_mixed_diagram(diag)
# Rebasing to ZX
Rewrite.rebase_to_zx().apply(diag)
diag.check_validity()
assert diag.count_vertices(ZXType.Hbox) == 0
assert diag.count_vertices(ZXType.XY) == 0
assert diag.count_vertices(ZXType.XZ) == 0
assert diag.count_vertices(ZXType.YZ) == 0
assert diag.count_vertices(ZXType.PX) == 0
assert diag.count_vertices(ZXType.PY) == 0
assert diag.count_vertices(ZXType.PZ) == 0
assert diag.count_vertices(ZXType.Triangle) == 0
assert diag.count_vertices(ZXType.ZXBox) == 0
t1 = tensor_from_mixed_diagram(diag)
(t0, t1) = joint_normalise_tensor(t0, t1)
assert np.allclose(t0, t1)
# Rebasing to MBQC
Rewrite.rebase_to_mbqc().apply(diag)
diag.check_validity()
assert diag.count_vertices(ZXType.Hbox) == 0
assert diag.count_vertices(ZXType.ZSpider) == 0
assert diag.count_vertices(ZXType.XSpider) == 0
assert diag.count_vertices(ZXType.Triangle) == 0
assert diag.count_vertices(ZXType.ZXBox) == 0
t2 = tensor_from_mixed_diagram(diag)
(t0, t2) = joint_normalise_tensor(t0, t2)
assert np.allclose(t0, t2)
@pytest.mark.skipif(not have_quimb, reason="quimb not installed")
def test_internalise_gadgets() -> None:
for axis_basis, axis_angle in [
(ZXType.XY, 0.25),
(ZXType.PX, False),
(ZXType.PX, True),
(ZXType.PY, False),
(ZXType.PY, True),
]:
for gadget_basis, gadget_angle in [
(ZXType.XY, 0.25),
(ZXType.XZ, 0.25),
(ZXType.YZ, 0.25),
(ZXType.PX, False),
(ZXType.PX, True),
(ZXType.PY, False),
(ZXType.PY, True),
(ZXType.PZ, False),
(ZXType.PZ, True),
]:
diag = ZXDiagram(1, 1, 0, 0)
ins = diag.get_boundary(ZXType.Input)
outs = diag.get_boundary(ZXType.Output)
in_v = diag.add_vertex(ZXType.PX, False)
out_v = diag.add_vertex(ZXType.PX, False)
axis = diag.add_vertex(axis_basis, axis_angle)
gadget = diag.add_vertex(gadget_basis, gadget_angle)
diag.add_wire(ins[0], in_v)
diag.add_wire(in_v, axis, ZXWireType.H)
diag.add_wire(axis, out_v, ZXWireType.H)
diag.add_wire(out_v, outs[0])
diag.add_wire(axis, gadget, ZXWireType.H)
t = tensor_from_quantum_diagram(diag)
Rewrite.internalise_gadgets().apply(diag)
if (axis_basis == ZXType.XY) and (gadget_basis in [ZXType.XY, ZXType.XZ]):
assert diag.n_vertices == 6
else:
assert diag.n_vertices == 5
t2 = tensor_from_quantum_diagram(diag)
(t, t2) = joint_normalise_tensor(t, t2)
assert np.allclose(t, t2)
def test_round_trip() -> None:
circ = Circuit(5)
circ.CCX(0, 1, 4)
circ.CCX(2, 4, 3)
circ.CCX(0, 1, 4)
AutoRebase(
{OpType.Rx, OpType.Rz, OpType.X, OpType.Z, OpType.H, OpType.CX, OpType.CZ}
).apply(circ)
diag, _ = circuit_to_zx(circ)
Rewrite.to_graphlike_form().apply(diag)
Rewrite.reduce_graphlike_form().apply(diag)
Rewrite.to_MBQC_diag().apply(diag)
c, _ = diag.to_circuit()
assert compare_unitaries(circ.get_unitary(), c.get_unitary())
if __name__ == "__main__":
test_generator_creation()
test_diagram_creation()
test_known_tensors()
test_classical_and_cptp()
test_tensor_errors()
test_graph_like_reduction()
test_spider_fusion()
test_simplification()
test_converting_from_circuit()
test_constructors()
test_XY_extraction()
test_XY_YZ_extraction()
test_ZX_rebase()
test_internalise_gadgets()
test_round_trip()
| tket/pytket/tests/zx_diagram_test.py/0 | {
"file_path": "tket/pytket/tests/zx_diagram_test.py",
"repo_id": "tket",
"token_count": 19296
} | 376 |
get_filename_component(TKET_CMAKE_DIR "${CMAKE_CURRENT_LIST_FILE}" PATH)
include(CMakeFindDependencyMacro)
if(NOT TARGET tket::tket)
include("${TKET_CMAKE_DIR}/tketTargets.cmake")
endif()
set(TKET_lIBRARIES tket::tket)
| tket/tket/cmake/tketConfig.cmake.in/0 | {
"file_path": "tket/tket/cmake/tketConfig.cmake.in",
"repo_id": "tket",
"token_count": 105
} | 377 |
// Copyright 2019-2024 Cambridge Quantum Computing
//
// 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.
#pragma once
#include <boost/uuid/uuid.hpp>
#include <boost/uuid/uuid_generators.hpp>
#include <boost/uuid/uuid_io.hpp>
#include <memory>
#include <optional>
#include "tket/Circuit/Simulation/CircuitSimulator.hpp"
#include "tket/OpType/OpTypeInfo.hpp"
#include "tket/Ops/Op.hpp"
#include "tket/Utils/BiMapHeaders.hpp"
#include "tket/Utils/EigenConfig.hpp"
#include "tket/Utils/Json.hpp"
#include "tket/Utils/MatrixAnalysis.hpp"
#include "tket/Utils/UnitID.hpp"
namespace tket {
class Circuit;
/**
* Abstract class for an operation from which a circuit can be extracted
*/
class Box : public Op {
public:
explicit Box(const OpType &type, const op_signature_t &signature = {})
: Op(type), signature_(signature), circ_(), id_(idgen()) {
if (!is_box_type(type)) throw BadOpType(type);
}
Box(const Box &other)
: Op(other.get_type()),
signature_(other.signature_),
circ_(other.circ_),
id_(other.id_) {}
/** Number of Quantum inputs */
unsigned n_qubits() const override;
/** Number of Boolean inputs */
unsigned n_boolean() const;
/** Number of Classical inputs */
unsigned n_classical() const;
op_signature_t get_signature() const override;
nlohmann::json serialize() const override;
static Op_ptr deserialize(const nlohmann::json &j);
/** Circuit represented by box */
std::shared_ptr<Circuit> to_circuit() const {
if (circ_ == nullptr) generate_circuit();
return circ_;
};
/**
* If meaningful and implemented, return the numerical unitary matrix
* (in ILO-BE convention) which this Box represents.
*
* @return unitary matrix (ILO-BE) which this Box represents
*/
virtual std::optional<Eigen::MatrixXcd> get_box_unitary() const {
return std::nullopt;
}
Eigen::MatrixXcd get_unitary() const override {
std::optional<Eigen::MatrixXcd> u = get_box_unitary();
if (u.has_value()) {
return *u;
}
return tket_sim::get_unitary(*to_circuit());
}
/** Unique identifier (preserved on copy) */
boost::uuids::uuid get_id() const { return id_; }
template <typename BoxT>
friend Op_ptr set_box_id(BoxT &b, boost::uuids::uuid newid);
protected:
static boost::uuids::uuid idgen() {
static boost::uuids::random_generator gen = {};
return gen();
}
op_signature_t signature_;
mutable std::shared_ptr<Circuit> circ_;
boost::uuids::uuid id_;
virtual void generate_circuit() const = 0;
};
// json for base Box attributes
nlohmann::json core_box_json(const Box &box);
/**
* @brief Set explicit ID on a box
*
* This is used for deserialization.
*
* @param b box
* @param[in] newid new ID
*
* @tparam BoxT concrete box type
*
* @return box with desired ID
*/
template <typename BoxT>
Op_ptr set_box_id(BoxT &b, boost::uuids::uuid newid) {
b.id_ = newid;
return std::make_shared<BoxT>(b);
}
/**
* Operation defined as a circuit.
*/
class CircBox : public Box {
public:
/**
* Construct from a given circuit.
*/
explicit CircBox(const Circuit &circ);
/**
* Construct from the empty circuit
*/
CircBox();
/**
* Copy constructor
*/
CircBox(const CircBox &other);
~CircBox() override {}
bool is_clifford() const override;
Op_ptr symbol_substitution(
const SymEngine::map_basic_basic &sub_map) const override;
void symbol_substitution_in_place(const symbol_map_t &sub_map);
SymSet free_symbols() const override;
/**
* Equality check between two CircBox instances
*/
bool is_equal(const Op &op_other) const override;
Op_ptr dagger() const override;
Op_ptr transpose() const override;
static Op_ptr from_json(const nlohmann::json &j);
static nlohmann::json to_json(const Op_ptr &op);
/**
* Get the name of the inner circuit.
*
* @return name
*/
std::optional<std::string> get_circuit_name() const;
/**
* Set the name of the inner circuit
*
* @param _name name string
*/
void set_circuit_name(const std::string _name);
protected:
void generate_circuit() const override {} // Already set by constructor
};
/**
* One-qubit operation defined as a unitary matrix
*/
class Unitary1qBox : public Box {
public:
/**
* Construct from a given 2x2 unitary matrix
*
* @param m unitary matrix
*/
explicit Unitary1qBox(const Eigen::Matrix2cd &m);
/**
* Construct from the identity matrix
*/
Unitary1qBox();
/**
* Copy constructor
*/
Unitary1qBox(const Unitary1qBox &other);
~Unitary1qBox() override {}
Op_ptr symbol_substitution(
const SymEngine::map_basic_basic &) const override {
return std::make_shared<Unitary1qBox>(*this);
}
SymSet free_symbols() const override { return {}; }
/**
* Equality check between two Unitary1qBox instances
*/
bool is_equal(const Op &op_other) const override;
/** Get the unitary matrix correspnding to this operation */
Eigen::Matrix2cd get_matrix() const { return m_; }
std::optional<Eigen::MatrixXcd> get_box_unitary() const override {
return m_;
}
Op_ptr dagger() const override;
Op_ptr transpose() const override;
bool is_clifford() const override;
static Op_ptr from_json(const nlohmann::json &j);
static nlohmann::json to_json(const Op_ptr &op);
protected:
void generate_circuit() const override;
private:
const Eigen::Matrix2cd m_;
};
/**
* Two-qubit operation defined as a unitary matrix (ILO-BE)
*/
class Unitary2qBox : public Box {
public:
/**
* Construct from a given 4x4 unitary matrix
*
* @param m unitary matrix
* @param basis basis order convention for matrix
*/
explicit Unitary2qBox(
const Eigen::Matrix4cd &m, BasisOrder basis = BasisOrder::ilo);
/**
* Construct from the identity matrix
*/
Unitary2qBox();
/**
* Copy constructor
*/
Unitary2qBox(const Unitary2qBox &other);
~Unitary2qBox() override {}
Op_ptr symbol_substitution(
const SymEngine::map_basic_basic &) const override {
return std::make_shared<Unitary2qBox>(*this);
}
SymSet free_symbols() const override { return {}; }
/**
* Equality check between two Unitary2qBox instances
*/
bool is_equal(const Op &op_other) const override;
/** Get the unitary matrix correspnding to this operation */
Eigen::Matrix4cd get_matrix() const { return m_; }
std::optional<Eigen::MatrixXcd> get_box_unitary() const override {
return m_;
}
Op_ptr dagger() const override;
Op_ptr transpose() const override;
static Op_ptr from_json(const nlohmann::json &j);
static nlohmann::json to_json(const Op_ptr &op);
protected:
void generate_circuit() const override;
private:
const Eigen::Matrix4cd m_;
};
/**
* Three-qubit operation defined as a unitary matrix (ILO-BE)
*/
class Unitary3qBox : public Box {
public:
/**
* Construct from a given 8x8 unitary matrix
*
* @param m unitary matrix
* @param basis basis order convention for matrix
*/
explicit Unitary3qBox(const Matrix8cd &m, BasisOrder basis = BasisOrder::ilo);
/**
* Construct from the identity matrix
*/
Unitary3qBox();
/**
* Copy constructor
*/
Unitary3qBox(const Unitary3qBox &other);
~Unitary3qBox() override {}
Op_ptr symbol_substitution(
const SymEngine::map_basic_basic &) const override {
return std::make_shared<Unitary3qBox>(*this);
}
SymSet free_symbols() const override { return {}; }
/**
* Equality check between two Unitary3qBox instances
*/
bool is_equal(const Op &op_other) const override;
/** Get the unitary matrix correspnding to this operation */
Matrix8cd get_matrix() const { return m_; }
std::optional<Eigen::MatrixXcd> get_box_unitary() const override {
return m_;
}
Op_ptr dagger() const override;
Op_ptr transpose() const override;
static Op_ptr from_json(const nlohmann::json &j);
static nlohmann::json to_json(const Op_ptr &op);
protected:
void generate_circuit() const override;
private:
const Matrix8cd m_;
};
/**
* Two-qubit operation defined in terms of a hermitian matrix and a phase.
*
* The unitary corresponding to the matrix A and phase t is exp(i*t*A).
* Matrix A is stored in ILO-BE form.
*/
class ExpBox : public Box {
public:
/**
* Construct from a given 4x4 hermitian matrix and optional phase.
*
* @param A hermitian matrix
* @param t phase to apply
* @param basis basis order convention for matrix
*/
ExpBox(
const Eigen::Matrix4cd &A, double t = 1.,
BasisOrder basis = BasisOrder::ilo);
/**
* Construct from the zero matrix (resulting in the identity)
*/
ExpBox();
/**
* Copy constructor
*/
ExpBox(const ExpBox &other);
~ExpBox() override {}
Op_ptr symbol_substitution(
const SymEngine::map_basic_basic &) const override {
return std::make_shared<ExpBox>(*this);
}
SymSet free_symbols() const override { return {}; }
/**
* Equality check between two ExpBox instances
*/
bool is_equal(const Op &op_other) const override;
/** Get the hermitian matrix and phase parameter */
std::pair<Eigen::Matrix4cd, double> get_matrix_and_phase() const {
return std::make_pair(A_, t_);
}
Op_ptr dagger() const override;
Op_ptr transpose() const override;
std::optional<Eigen::MatrixXcd> get_box_unitary() const override;
static Op_ptr from_json(const nlohmann::json &j);
static nlohmann::json to_json(const Op_ptr &op);
protected:
void generate_circuit() const override;
private:
const Eigen::Matrix4cd A_;
double t_;
};
class CompositeGateDef;
typedef std::shared_ptr<CompositeGateDef> composite_def_ptr_t;
// CompositeGateDef
JSON_DECL(composite_def_ptr_t)
class CompositeGateDef : public std::enable_shared_from_this<CompositeGateDef> {
public:
CompositeGateDef(
const std::string &name, const Circuit &def,
const std::vector<Sym> &args);
static composite_def_ptr_t define_gate(
const std::string &name, const Circuit &def,
const std::vector<Sym> &args);
Circuit instance(const std::vector<Expr> ¶ms) const;
std::string get_name() const { return name_; }
std::vector<Sym> get_args() const { return args_; }
std::shared_ptr<Circuit> get_def() const { return def_; }
unsigned n_args() const { return args_.size(); }
op_signature_t signature() const;
bool operator==(const CompositeGateDef &other) const;
private:
std::string name_;
std::shared_ptr<Circuit> def_;
std::vector<Sym> args_;
CompositeGateDef() {}
};
class CustomGate : public Box {
public:
CustomGate(const composite_def_ptr_t &gate, const std::vector<Expr> ¶ms);
CustomGate(const CustomGate &other);
SymSet free_symbols() const override;
composite_def_ptr_t get_gate() const { return gate_; }
std::vector<Expr> get_params() const override { return params_; }
std::string get_name(bool latex = false) const override;
Op_ptr symbol_substitution(
const SymEngine::map_basic_basic &sub_map) const override;
/**
* Equality check between two CustomGate instances.
* This does more than simply checking id_.
*/
bool is_equal(const Op &op_other) const override;
static Op_ptr from_json(const nlohmann::json &j);
static nlohmann::json to_json(const Op_ptr &op);
bool is_clifford() const override;
protected:
void generate_circuit() const override;
CustomGate() : Box(OpType::CustomGate), gate_(), params_() {}
private:
composite_def_ptr_t gate_;
const std::vector<Expr> params_;
};
/**
* Wraps another quantum op, adding control qubits
*/
class QControlBox : public Box {
public:
/**
* Construct from a given op and number of controls
*
* @param op op to control
* @param n_controls number of qubit controls to add
* @param control_state control state expressed as a bit vector.
* If control_state is non-empty, its size should match n_controls.
* An empty vector is converted to an all-1s vector of length n_controls.
*/
explicit QControlBox(
const Op_ptr &op, unsigned n_controls = 1,
const std::vector<bool> &control_state = {});
/**
* Copy constructor
*/
QControlBox(const QControlBox &other);
~QControlBox() override {}
Op_ptr symbol_substitution(
const SymEngine::map_basic_basic &sub_map) const override;
SymSet free_symbols() const override;
/**
* Equality check between two QControlBox instances
*/
bool is_equal(const Op &op_other) const override;
std::string get_command_str(const unit_vector_t &args) const override;
Op_ptr dagger() const override;
Op_ptr transpose() const override;
std::optional<Eigen::MatrixXcd> get_box_unitary() const override;
Op_ptr get_op() const { return op_; }
unsigned get_n_controls() const { return n_controls_; }
std::vector<bool> get_control_state() const { return control_state_; }
static Op_ptr from_json(const nlohmann::json &j);
static nlohmann::json to_json(const Op_ptr &op);
protected:
void generate_circuit() const override;
QControlBox()
: Box(OpType::QControlBox),
op_(),
n_controls_(0),
n_inner_qubits_(0),
control_state_() {}
private:
const Op_ptr op_;
const unsigned n_controls_;
unsigned n_inner_qubits_;
const std::vector<bool> control_state_;
};
class ProjectorAssertionBox : public Box {
public:
/**
* Construct from a given 2x2, 4x4 or 8x8 projector matrix
*
* @param m projector matrix
* @param basis basis order convention for matrix
*/
explicit ProjectorAssertionBox(
const Eigen::MatrixXcd &m, BasisOrder basis = BasisOrder::ilo);
/**
* Copy constructor
*/
ProjectorAssertionBox(const ProjectorAssertionBox &other);
~ProjectorAssertionBox() override {}
Op_ptr symbol_substitution(
const SymEngine::map_basic_basic &) const override {
return std::make_shared<ProjectorAssertionBox>(*this);
}
SymSet free_symbols() const override { return {}; }
/**
* Equality check between two ProjectorAssertionBox instances
*/
bool is_equal(const Op &op_other) const override;
/** Get the unitary matrix correspnding to this operation */
Eigen::MatrixXcd get_matrix() const { return m_; }
std::vector<bool> get_expected_readouts() const { return expected_readouts_; }
Op_ptr dagger() const override;
Op_ptr transpose() const override;
op_signature_t get_signature() const override;
static Op_ptr from_json(const nlohmann::json &j);
static nlohmann::json to_json(const Op_ptr &op);
protected:
void generate_circuit() const override;
private:
const Eigen::MatrixXcd m_;
// expected readouts the debug bits
// false -> 0
// true -> 1
mutable std::vector<bool> expected_readouts_;
};
class StabiliserAssertionBox : public Box {
public:
/**
* Construct from a set of stabiliser Pauli strings
*
* @param paulis a set of stabiliser Pauli strings
*/
explicit StabiliserAssertionBox(const PauliStabiliserVec &paulis);
/**
* Copy constructor
*/
StabiliserAssertionBox(const StabiliserAssertionBox &other);
~StabiliserAssertionBox() override {}
Op_ptr symbol_substitution(
const SymEngine::map_basic_basic &) const override {
return std::make_shared<StabiliserAssertionBox>(*this);
}
SymSet free_symbols() const override { return {}; }
/**
* Equality check between two StabiliserAssertionBox instances
*/
bool is_equal(const Op &op_other) const override;
/** Get the pauli stabilisers */
PauliStabiliserVec get_stabilisers() const { return paulis_; }
std::vector<bool> get_expected_readouts() const { return expected_readouts_; }
Op_ptr dagger() const override;
Op_ptr transpose() const override;
static Op_ptr from_json(const nlohmann::json &j);
static nlohmann::json to_json(const Op_ptr &op);
op_signature_t get_signature() const override;
protected:
void generate_circuit() const override;
private:
const PauliStabiliserVec paulis_;
// expected readouts the debug bits
// false -> 0
// true -> 1
mutable std::vector<bool> expected_readouts_;
};
} // namespace tket
| tket/tket/include/tket/Circuit/Boxes.hpp/0 | {
"file_path": "tket/tket/include/tket/Circuit/Boxes.hpp",
"repo_id": "tket",
"token_count": 5666
} | 378 |
// Copyright 2019-2024 Cambridge Quantum Computing
//
// 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.
#pragma once
#include <memory>
#include "Boxes.hpp"
#include "Circuit.hpp"
#include "tket/Utils/Json.hpp"
namespace tket {
/**
* Box to synthesise a statevector
*/
class StatePreparationBox : public Box {
public:
/**
* Construct a circuit that prepares the given statevector
*
* @param statevector a normalised statevector
* @param is_inverse whether to output the inverse of the preparation circuit
* @param with_initial_reset whether to explicitly reset the qubits to the
* zero state of the computational basis before preparing the state
* (by default it is assumed that the initial state is zero and no explicit
* reset is applied)
*/
explicit StatePreparationBox(
const Eigen::VectorXcd &statevector, bool is_inverse = false,
bool with_initial_reset = false);
/**
* Copy constructor
*/
StatePreparationBox(const StatePreparationBox &other);
~StatePreparationBox() override {}
Op_ptr symbol_substitution(
const SymEngine::map_basic_basic &) const override {
return std::make_shared<StatePreparationBox>(*this);
}
SymSet free_symbols() const override { return {}; }
/**
* Equality check between two StatePreparationBox instances
*/
bool is_equal(const Op &op_other) const override;
Op_ptr dagger() const override;
op_signature_t get_signature() const override;
static Op_ptr from_json(const nlohmann::json &j);
static nlohmann::json to_json(const Op_ptr &op);
Eigen::VectorXcd get_statevector() const;
bool is_inverse() const;
bool with_initial_reset() const;
protected:
/**
* @brief Generate the state preparation circuit using
* multiplexed-Ry gates and multiplexed-Rz gates
*
*/
void generate_circuit() const override;
StatePreparationBox()
: Box(OpType::StatePreparationBox),
statevector_(),
is_inverse_(false),
with_initial_reset_(false),
n_qubits_(0) {}
private:
const Eigen::VectorXcd statevector_;
const bool is_inverse_;
const bool with_initial_reset_;
const unsigned n_qubits_;
};
} // namespace tket
| tket/tket/include/tket/Circuit/StatePreparation.hpp/0 | {
"file_path": "tket/tket/include/tket/Circuit/StatePreparation.hpp",
"repo_id": "tket",
"token_count": 856
} | 379 |
// Copyright 2019-2024 Cambridge Quantum Computing
//
// 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.
#pragma once
#include <stdexcept>
#include <string>
namespace tket {
/** We do not wish to couple tightly to exception classes elsewhere.
* Let the caller catch this and decide what to do,
* based upon the cause of the error.
*/
struct GateUnitaryMatrixError : public std::runtime_error {
enum class Cause {
SYMBOLIC_PARAMETERS,
GATE_NOT_IMPLEMENTED,
// The matrix would be too big
TOO_MANY_QUBITS,
NON_FINITE_PARAMETER,
// The routines were passed invalid input
// (wrong number of qubits/arguments/etc.) somehow.
INPUT_ERROR
};
const Cause cause;
explicit GateUnitaryMatrixError(const std::string& message, Cause cause);
};
} // namespace tket
| tket/tket/include/tket/Gate/GateUnitaryMatrixError.hpp/0 | {
"file_path": "tket/tket/include/tket/Gate/GateUnitaryMatrixError.hpp",
"repo_id": "tket",
"token_count": 386
} | 380 |
// Copyright 2019-2024 Cambridge Quantum Computing
//
// 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.
#pragma once
#include <boost/graph/breadth_first_search.hpp>
#include <boost/graph/depth_first_search.hpp>
#include <boost/graph/properties.hpp>
#include <boost/graph/visitors.hpp>
#include <boost/property_map/property_map.hpp>
#include <boost/range/iterator_range_core.hpp>
#include <numeric>
#include <type_traits>
#include <utility>
#include <vector>
#include "tket/Graphs/Utils.hpp"
// implementation details of `TreeSearch.hpp`
namespace tket::graphs {
// ::detail includes all internal implementation-specific details
namespace detail {
/* Helpers `run_bfs` and `run_dfs` return instances of TreeSearchBase
* subclasses. These provide a host of useful member functions to obtain the
* relevant results from the tree search.
*
* Note that run() must have been called before
* using the member functions to retrieve results.
* This is done automatically by the utility functions in `TreeSearch.hpp`
*
* First template argument is Graph type, second is the boost property map type
* that should be used as a vertex index.
*/
template <typename Graph, typename BoostPMap>
class TreeSearchBase {
protected:
using vertex = utils::vertex<Graph>;
using parent_vec = std::vector<vertex>;
using color_vec = std::vector<boost::default_color_type>;
using index_pmap_t = BoostPMap;
using dist_pmap_t =
boost::iterator_property_map<typename dist_vec::iterator, index_pmap_t>;
using parent_pmap_t =
boost::iterator_property_map<typename parent_vec::iterator, index_pmap_t>;
using color_pmap_t =
boost::iterator_property_map<typename color_vec::iterator, index_pmap_t>;
using visitor_t = std::pair<
boost::distance_recorder<dist_pmap_t, boost::on_tree_edge>,
boost::predecessor_recorder<parent_pmap_t, boost::on_tree_edge>>;
public:
/* Constructor: search through Graph g with root v, using index map pmap */
TreeSearchBase(vertex v, Graph&& g, BoostPMap pmap)
: root(v),
to_index(pmap),
graph(g),
dists(boost::num_vertices(g)),
parents(boost::num_vertices(g)),
color_map(boost::num_vertices(g)),
visitor{
boost::record_distances(
boost::make_iterator_property_map(dists.begin(), to_index),
boost::on_tree_edge()),
boost::record_predecessors(
boost::make_iterator_property_map(parents.begin(), to_index),
boost::on_tree_edge())} {
// for every vertex, assign self as parent
for (auto v : boost::make_iterator_range(boost::vertices(graph))) {
parents[to_index[v]] = v;
}
}
/* Get results from tree search */
/* vector of vertex predecessor in search */
const parent_vec& get_parents() const& { return parents; }
const parent_vec&& get_parents() const&& { return std::move(parents); }
/* vector of distances from the root */
const dist_vec& get_dists() const& { return dists; }
const dist_vec&& get_dists() const&& { return std::move(dists); }
std::size_t get_dist(const vertex& v) const { return dists[to_index[v]]; }
/* Rebase tree search from some new root */
void change_root(vertex v) {
// naive implementation
// This might be made more efficient in the subclasses
vertex old_root = root;
root = v;
if (root != old_root) {
std::fill(dists.begin(), dists.end(), 0);
std::iota(parents.begin(), parents.end(), 0);
run();
}
}
/* Vector from target to root (following reverse edges) */
parent_vec path_to_root(vertex target) const {
std::vector<vertex> path;
vertex current = target;
path.push_back(target);
while (current != root) {
vertex parent = parents[to_index[current]];
if (parent == current) {
// graph is disconnected and there is no path to root
return {};
}
current = parent;
path.push_back(current);
}
return path;
}
/* Vector from root to target along graph edges */
parent_vec path_from_root(vertex target) const {
parent_vec out = path_to_root(target);
std::reverse(out.begin(), out.end());
return out;
}
/* Depth of tree search */
std::size_t max_depth() const {
auto it = std::max_element(dists.cbegin(), dists.cend());
if (it == dists.cend()) {
throw std::invalid_argument(
"TreeSearch::max_depth: There is no entry in distance "
"vector");
}
return *it;
}
/* Vertex of max depth
* if more than one exist, returns first found */
vertex max_depth_vertex() const {
const std::size_t target_depth = max_depth();
for (vertex v : boost::make_iterator_range(boost::vertices(this->graph))) {
if (get_dist(v) == target_depth) {
return v;
}
}
throw std::runtime_error("max_depth_vertex: No vertex has maximal depth");
}
/* Path from root to deepest vertex */
parent_vec longest_path() const { return path_from_root(max_depth_vertex()); }
/* Run tree search */
virtual void run() = 0;
protected:
template <typename Visitor>
auto get_default_named_params(Visitor& vis) {
return boost::visitor(vis).color_map(
boost::make_iterator_property_map(color_map.begin(), to_index));
}
vertex root; // root of tree search
index_pmap_t to_index; // vertex index pmap
Graph graph; // graph to be searched
dist_vec dists; // distance from root
parent_vec parents; // parent towards root
color_vec color_map; // color used by tree search algorithm
visitor_t visitor; // visitor passed to boost tree search alg
};
/* A vertex index map, mapping boost vertex descriptors to unsigned
* is required for tree searches (to index the parents and dists vectors).
*
* The TreeSearch class accepts a std::map-like PMap argument to define such a
* mapping. This is converted to a boost property map using
* boost::associative_property_map. If none is provided, the default
* boost::vertex_index is used (by default, this is available on boost graphs
* using the vecS underlying EdgeOutList type
*/
/* Note on the implementation:
* The third template argument (a bool) should always be left to its
* default value. It is used to flag whether the Graph type considered
* has an implicit integer vertex index.
* This flag is used in the template specialisation below to change
* the template definition when `HasImplicitIndex == True`,
* i.e. the first definition of `TreeSearch` is for the case `HasImplicitIndex
* == False` while the template partial specialisation below is for the case
* `HasImplicitIndex == True`.
*/
template <
typename Graph, typename PMap = void,
bool HasImplicitIndex = utils::detail::has_integral_index<Graph>>
class TreeSearch
: public TreeSearchBase<Graph, boost::associative_property_map<PMap>> {
private:
using Base = TreeSearchBase<Graph, boost::associative_property_map<PMap>>;
using vertex = typename Base::vertex;
public:
TreeSearch(vertex v, Graph&& g, PMap& pmap)
: Base(v, std::forward<Graph>(g), boost::make_assoc_property_map(pmap)) {}
};
template <typename Graph>
class TreeSearch<Graph, void, true>
: public TreeSearchBase<
Graph,
decltype(boost::get(boost::vertex_index, std::declval<Graph>()))> {
private:
using PMap = decltype(boost::get(boost::vertex_index, std::declval<Graph>()));
using Base = TreeSearchBase<Graph, PMap>;
using vertex = typename Base::vertex;
public:
TreeSearch(vertex v, Graph&& g)
: Base(v, std::forward<Graph>(g), boost::get(boost::vertex_index, g)) {}
};
} // namespace detail
/* Return type of `run_bfs`.
*
* For each vertex, computes the BFS distance to the root
* as well as the next node on the path towards root (parent).
* These are stored in the base class TreeSearchBase and can
* be retrieved through one of the member functions defined therein
*/
template <typename... Args>
class BFS : public detail::TreeSearch<Args...> {
private:
using Base = detail::TreeSearch<Args...>;
public:
// inherit constructors
using Base::Base;
using parent_vec = typename Base::parent_vec;
/* Run bfs */
void run() override {
auto vis = boost::make_bfs_visitor(this->visitor);
boost::breadth_first_search(
this->graph, this->root, this->get_default_named_params(vis));
}
};
/* Return type of `run_dfs`.
*
* For each vertex, computes the DFS distance to the root
* as well as the next node on the path towards root (parent).
* These are stored in the base class TreeSearchBase and can
* be retrieved through one of the member functions defined therein
*/
template <typename... Args>
class DFS : public detail::TreeSearch<Args...> {
private:
using Base = detail::TreeSearch<Args...>;
public:
// inherit constructors
using Base::Base;
using parent_vec = typename Base::parent_vec;
/* Run dfs */
void run() override {
auto vis = boost::make_dfs_visitor(this->visitor);
boost::depth_first_search(
this->graph,
this->get_default_named_params(vis).root_vertex(this->root));
}
};
} // namespace tket::graphs
| tket/tket/include/tket/Graphs/TreeSearch_impl.hpp/0 | {
"file_path": "tket/tket/include/tket/Graphs/TreeSearch_impl.hpp",
"repo_id": "tket",
"token_count": 3283
} | 381 |
// Copyright 2019-2024 Cambridge Quantum Computing
//
// 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.
#pragma once
#include "tket/Architecture/Architecture.hpp"
#include "tket/Circuit/Circuit.hpp"
namespace tket {
/**
* Check that the circuit respects architectural constraints
*
* @param circ circuit to check
* @param arch architecture
* @param directed if true, disallow two-qubit gates except for CX
* @param bridge_allowed whether 3-qubit \ref OpType::BRIDGE operations are
* allowed
*/
bool respects_connectivity_constraints(
const Circuit& circ, const Architecture& arch, bool directed,
bool bridge_allowed = false);
} // namespace tket
| tket/tket/include/tket/Mapping/Verification.hpp/0 | {
"file_path": "tket/tket/include/tket/Mapping/Verification.hpp",
"repo_id": "tket",
"token_count": 321
} | 382 |
// Copyright 2019-2024 Cambridge Quantum Computing
//
// 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.
#pragma once
#include <fstream>
#include <stdexcept>
#include "tket/Clifford/UnitaryTableau.hpp"
#include "tket/Utils/Expression.hpp"
#include "tket/Utils/GraphHeaders.hpp"
#include "tket/Utils/PauliTensor.hpp"
#include "tket/Utils/SequencedContainers.hpp"
namespace tket {
class Gate;
struct PauliGadgetProperties {
SpPauliStabiliser tensor_;
Expr angle_;
};
struct DependencyEdgeProperties {};
typedef boost::adjacency_list<
boost::listS, boost::listS, boost::bidirectionalS,
// indexing needed for algorithms such as topological sort
boost::property<boost::vertex_index_t, int, PauliGadgetProperties>,
DependencyEdgeProperties>
PauliDAG;
typedef boost::graph_traits<PauliDAG>::vertex_descriptor PauliVert;
typedef boost::graph_traits<PauliDAG>::edge_descriptor PauliEdge;
typedef sequence_set_t<PauliVert> PauliVertSet;
typedef sequence_set_t<PauliEdge> PauliEdgeSet;
typedef boost::adj_list_vertex_property_map<
PauliDAG, int, int &, boost::vertex_index_t>
PauliVIndex;
typedef std::list<std::pair<OpType, qubit_vector_t>> Conjugations;
class Circuit;
class MidCircuitMeasurementNotAllowed : public std::logic_error {
public:
explicit MidCircuitMeasurementNotAllowed(const std::string &message)
: std::logic_error(message) {}
};
/**
* Dependency graph of a circuit wrt Pauli Gadgets.
* Constructed by effectively commuting all non-Clifford gates to the front
* of the circuit and determining their dependencies based on commutation
* of the Pauli strings.
* The Clifford effect of a circuit is maintained as a tableau, thought of as
* being applied after all of the gadgets.
*/
class PauliGraph {
public:
/** Construct an empty dependency graph for the identity over n qubits. */
explicit PauliGraph(unsigned n);
/** Construct an empty dependency graph for the identity over given qubits. */
explicit PauliGraph(const qubit_vector_t &qbs, const bit_vector_t &bits = {});
/**
* Applies the given gate to the end of the circuit.
* Clifford gates transform the tableau.
* Non-Clifford gates are transformed into gadgets by the tableau and added
* to the graph.
*/
void apply_gate_at_end(const Gate &gate, const unit_vector_t &args);
/** Visualisation of the dependency graph */
void to_graphviz_file(const std::string &filename) const;
void to_graphviz(std::ostream &out) const;
const UnitaryRevTableau &get_clifford_ref() { return cliff_; }
unsigned n_vertices() const { return boost::num_vertices(this->graph_); }
/**
* All vertices of the DAG, topologically sorted.
*
* This method is "morally" const, but it sets the vertex indices in the DAG.
*
* @return vector of vertices in a topological (causal) order
*/
std::vector<PauliVert> vertices_in_order() const;
/**
* Perform a simple sanity check on the DAG.
*/
void sanity_check() const;
friend PauliGraph circuit_to_pauli_graph(const Circuit &circ);
friend Circuit pauli_graph_to_pauli_exp_box_circuit_individually(
const PauliGraph &pg, CXConfigType cx_config);
friend Circuit pauli_graph_to_pauli_exp_box_circuit_pairwise(
const PauliGraph &pg, CXConfigType cx_config);
friend Circuit pauli_graph_to_pauli_exp_box_circuit_sets(
const PauliGraph &pg, CXConfigType cx_config);
private:
/**
* The dependency graph of Pauli gadgets
*
* This is mutated by \ref vertices_in_order which indexes the vertices
* without changing the structure.
*/
mutable PauliDAG graph_;
/** The tableau of the Clifford effect of the circuit */
UnitaryRevTableau cliff_;
/** The record of measurements at the very end of the circuit */
boost::bimap<Qubit, Bit> measures_;
bit_vector_t bits_;
/**
* Caches of the set of Pauli gadgets that can be commuted to the start
* or the end of the circuit.
*/
PauliVertSet start_line_;
PauliVertSet end_line_;
PauliVertSet get_successors(const PauliVert &vert) const;
PauliVertSet get_predecessors(const PauliVert &vert) const;
PauliEdgeSet get_in_edges(const PauliVert &vert) const;
PauliEdgeSet get_out_edges(const PauliVert &vert) const;
PauliVert source(const PauliEdge &edge) const;
PauliVert target(const PauliEdge &edge) const;
/**
* Appends a pauli gadget at the end of the dependency graph.
* Assumes this is the result AFTER pushing it through the Clifford
* tableau.
*/
void apply_pauli_gadget_at_end(
const SpPauliStabiliser &pauli, const Expr &angle);
};
} // namespace tket
| tket/tket/include/tket/PauliGraph/PauliGraph.hpp/0 | {
"file_path": "tket/tket/include/tket/PauliGraph/PauliGraph.hpp",
"repo_id": "tket",
"token_count": 1690
} | 383 |
// Copyright 2019-2024 Cambridge Quantum Computing
//
// 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.
#pragma once
#include "Transform.hpp"
#include "tket/Circuit/Circuit.hpp"
namespace tket {
namespace Transforms {
namespace GreedyPauliSimp {
/**
* @brief Types of 2-qubit entangled Clifford gates
*
*/
enum class TQEType : unsigned {
XX,
XY,
XZ,
YX,
YY,
YZ,
ZX,
ZY,
ZZ,
};
/**
* @brief Local Clifford
*
*/
enum class LocalCliffordType {
H,
S,
V,
};
/**
* @brief Type for 2-qubit entangled Clifford gates
*
*/
using TQE = std::tuple<TQEType, unsigned, unsigned>;
/**
* @brief A Pauli exponential described by its commutation relations
* with the rows in a reference Clifford tableau.
* We store the commutation relations using an n-dimensional
* vector with entries in {0,1,2,3}, where
* 0: commute with ith Z row and ith X row
* 1: commute with ith Z row and anti-commute with ith X row
* 2: anti-commute with ith Z row and commute with ith X row
* 3: anti-commute with ith Z row and anti-commute with ith X row
* We call such vector a support vector
*/
class PauliExpNode {
public:
/**
* @brief Construct a new PauliExpNode object.
*
* @param support_vec the support vector
* @param theta the rotation angle in half-turns
*/
PauliExpNode(std::vector<unsigned> support_vec, Expr theta);
/**
* @brief Number of TQEs required to reduce the weight to 1
*
* @return unsigned
*/
unsigned tqe_cost() const { return tqe_cost_; }
/**
* @brief Number of TQEs would required to reduce the weight to 1
* after the given TQE is applied
*
* @return unsigned
*/
int tqe_cost_increase(const TQE& tqe) const;
/**
* @brief Update the support vector with a TQE gate
*
* @param tqe
*/
void update(const TQE& tqe);
Expr theta() const { return theta_; };
/**
* @brief Return all possible TQE gates that will reduce the tqe cost by 1
*
* @return std::vector<std::tuple<TQEType, unsigned, unsigned>>
*/
std::vector<TQE> reduction_tqes() const;
/**
* @brief Return the index and value of the first support
*
* @return std::pair<unsigned, unsigned>
*/
std::pair<unsigned, unsigned> first_support() const;
private:
std::vector<unsigned> support_vec_;
Expr theta_;
unsigned tqe_cost_;
};
/**
* @brief Each row of a Clifford tableau consists a pair of anti-commuting
* Pauli strings (p0,p1). Similar to the PauliExpNode, such pairs can be
* alternatively described by their commutation relations with the rows in a
* reference Clifford tableau. Let Xi and Zi be the ith X row and the ith Z row
* in a reference Tableau T, then the commutation relation between (p0, p1) and
* the ith row of T is defined by how p0, p1 commute with Xi and Zi. That's 4
* bits of information. We store such information using an n-dimensional vector
* with entries in {0,1,2,...,15}. The 4 bits from the most significant to the
* least are: f(p0, Xi), f(p0,Zi), f(q,Xi), f(q,Zi) where f(p,q)==1 if p,q
* anti-commute and 0 otherwise
*/
class TableauRowNode {
public:
/**
* @brief Construct a new TableauRowNode object.
*
* @param support_vec the support vector
*/
TableauRowNode(std::vector<unsigned> support_vec);
/**
* @brief Number of TQEs required to reduce the weight to 1
*
* @return unsigned
*/
unsigned tqe_cost() const { return tqe_cost_; };
/**
* @brief Number of TQEs would required to reduce the weight to 1
* after the given TQE is applied
*
* @return unsigned
*/
int tqe_cost_increase(const TQE& tqe) const;
/**
* @brief Update the support vector with a TQE gate
*
* @param tqe
*/
void update(const TQE& tqe);
/**
* @brief Return all possible TQE gates that will reduce the tqe cost
*
* @return std::vector<std::pair<unsigned, unsigned>>
*/
std::vector<TQE> reduction_tqes() const;
/**
* @brief Return the index and value of the first support
*/
std::pair<unsigned, unsigned> first_support() const;
private:
std::vector<unsigned> support_vec_;
unsigned n_weaks_;
unsigned n_strongs_;
unsigned tqe_cost_;
};
/**
* @brief The commutation relation between a TableauRowNode (p0,p1) and the ith
* row of the reference Tableau can be further classified as Strong, Weak or
* No-support.
*/
enum class SupportType : unsigned {
Strong,
Weak,
No,
};
/**
* @brief Given a circuit consists of PauliExpBoxes followed by clifford gates,
* and end-of-circuit measurements, implement the PauliExpBoxes and the final
* clifford subcircuit by applying Clifford gates and single qubit rotations in
* a greedy fashion.
*
* @param circ
* @param discount_rate
* @param depth_weight
* @return Circuit
*/
Circuit greedy_pauli_graph_synthesis(
const Circuit& circ, double discount_rate = 0.7, double depth_weight = 0.3);
/**
* @brief Synthesise a set of unordered Pauli exponentials by applying Clifford
* gates and single qubit rotations in a greedy fashion. Assume all Pauli
* strings have the same length.
*
* @param unordered_set
* @param depth_weight
* @return Circuit
*/
Circuit greedy_pauli_set_synthesis(
const std::vector<SymPauliTensor>& unordered_set,
double depth_weight = 0.3);
} // namespace GreedyPauliSimp
Transform greedy_pauli_optimisation(
double discount_rate = 0.7, double depth_weight = 0.3);
} // namespace Transforms
} // namespace tket
| tket/tket/include/tket/Transformations/GreedyPauliOptimisation.hpp/0 | {
"file_path": "tket/tket/include/tket/Transformations/GreedyPauliOptimisation.hpp",
"repo_id": "tket",
"token_count": 1998
} | 384 |
// Copyright 2019-2024 Cambridge Quantum Computing
//
// 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.
#pragma once
/**
* @file
* @brief Generally useful typedefs and constants
*/
#include <complex>
namespace tket {
// Typedefs
/** Complex number */
typedef std::complex<double> Complex;
// Numeric constants
/** A fixed square root of -1 */
constexpr Complex i_(0, 1);
/** Complex zero */
constexpr Complex czero(0, 0);
/** Default tolerance for floating-point comparisons */
constexpr double EPS = 1e-11;
/** \f$ \pi \f$ */
constexpr double PI =
3.141'592'653'589'793'238'462'643'383'279'502'884'197'169'399'375'105'820'974;
/**
* Enum for readout basis and ordering
*
* Readouts are viewed in increasing lexicographic order (ILO) of the bit's
* UnitID. This is our default convention for column indexing for ALL readout
* forms (shots, counts, statevector, and unitaries). e.g. |abc> corresponds to
* the readout: ('c', 0) --> a, ('c', 1) --> b, ('d', 0) --> c
*
* For statevector and unitaries, the string abc is interpreted as an index
* in a big-endian (BE) fashion.
* e.g. the statevector (a_{00}, a_{01}, a_{10}, a_{11})
*
* Some backends (Qiskit, ProjectQ, Quest, etc.) use a DLO-BE
* (decreasing lexicographic order, big-endian) convention. This is the same
* as ILO-LE (little-endian) for statevectors and unitaries, but gives shot
* tables/readouts in a counter-intuitive manner.
*
* Every backend and matrix-based box should have a BasisOrder option which
* can toggle between ILO-BE (ilo) and DLO-BE (dlo).
*/
enum class BasisOrder {
ilo, /**< increasing lexicographic order (big-endian) */
dlo /**< decreasing lexicographic order (big-endian) */
};
} // namespace tket
| tket/tket/include/tket/Utils/Constants.hpp/0 | {
"file_path": "tket/tket/include/tket/Utils/Constants.hpp",
"repo_id": "tket",
"token_count": 692
} | 385 |
// Copyright 2019-2024 Cambridge Quantum Computing
//
// 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.
#pragma once
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/graph_traits.hpp>
#include "tket/Utils/SequencedContainers.hpp"
#include "tket/ZX/ZXGenerator.hpp"
/**
* This header contains the implementation-specific type definitions for the
* ZXDiagram class. Currently, Boost is used for the underlying graph structure.
* The interface can be found in ZXDiagram.hpp.
*
* A ZX diagram is implemented as a directed graph with labels for its vertices
* and edges. Although edges in a ZX diagram are ultimately undirected, some
* vertices are directed or otherwise non-commutative. That is, the permutation
* in which the edges are connected to the vertex matters, either to
* distinguish between inputs and outputs of the vertex or operands with
* different semantics. We refer to such vertices as "directed".
*
* To represent these diagrams with undirected edges but some directed vertices
* we use a directed underlying graph.
*
* - The vertex information (e.g. generator type and properties) is represented
* by a `ZXGen_ptr` object (equivalent to `Op_ptr` from circuits) containing
* the relevant information. In ZX diagrams, the `ZXGenerator` object pointed
* to is guaranteed to be exactly one subtype based on its `ZXType`.
* - For directed vertices, we have a `DirectedZXGenerator` object which
* captures the information about the ports. The mapping of ports to semantic
* meaning is dictated by the particular `ZXType`. In general, ports are
* optional unsigned integers, taking values for directed vertices and
* `std::nullopt` for undirected.
* - The edges store information including its type (ZXWireType is either Basic
* or H), its quantum-ness (QuantumType is either Quantum or Classical), and
* the ports it connects to on both ends (as a map from WireEnd::Source/
* Target to a the port it connects to on a directed vertex). This
* differentiation between source and target vertices is to allow a unique
* representation of the edge's connectivity in case of connecting between
* two directed vertices.
*/
namespace tket {
namespace zx {
// ZXVert information - each vertex just captures a ZX generator
struct ZXVertProperties {
ZXGen_ptr op;
};
/**
* Wire properties:
* `type`: ZXWireType::Basic or H, whether the wire is an identity / Hadamard
* `qtype`: QuantumType::Quantum or Classical, whether the wire is doubled or
* not under the CPM construction `source_port`, `target_port`: the ports the
* wire connects to on the source and target vertices if they are directed, and
* `nullopt` if they are undirected
*/
struct WireProperties {
ZXWireType type;
QuantumType qtype;
std::optional<unsigned> source_port;
std::optional<unsigned> target_port;
WireProperties();
WireProperties(
ZXWireType type, QuantumType qtype,
std::optional<unsigned> source_port = std::nullopt,
std::optional<unsigned> target_port = std::nullopt);
// Use default copy and move constructors
bool operator==(const WireProperties& other) const;
};
/**
* A ZX diagram is semantically undirected, but the implementation uses a
* directed graph in order to represent directed and non-commutative vertices.
*
* `listS` is used for both the edge and vertex lists as these maintain
* descriptor / pointer stability:
* https://www.boost.org/doc/libs/1_54_0/libs/graph/doc/adjacency_list.html
*
* See TKET Wiki entry: "Boost & igraph C++ Graphical Libraries Benchmarks"
* for earlier BGL tests.
*/
typedef boost::adjacency_list<
boost::listS, boost::listS, boost::bidirectionalS, ZXVertProperties,
WireProperties>
ZXGraph;
typedef boost::graph_traits<ZXGraph>::vertex_descriptor ZXVert;
typedef std::vector<ZXVert> ZXVertVec;
typedef sequence_set_t<ZXVert> ZXVertSeqSet;
typedef boost::graph_traits<ZXGraph>::edge_descriptor Wire;
typedef std::vector<Wire> WireVec;
// (convenience) vertex and edge iterators
typedef boost::graph_traits<ZXGraph>::vertex_iterator ZXVertIterator;
// Iterator over vertex neighbourhoods
typedef boost::graph_traits<ZXGraph>::adjacency_iterator NeighbourIterator;
// Iterator over *undirected* edges
typedef boost::graph_traits<ZXGraph>::edge_iterator WireIterator;
// Iterator over *directed* edges
typedef boost::graph_traits<ZXGraph>::out_edge_iterator OutWireIterator;
typedef boost::graph_traits<ZXGraph>::in_edge_iterator InWireIterator;
} // namespace zx
} // namespace tket
| tket/tket/include/tket/ZX/ZXDiagramImpl.hpp/0 | {
"file_path": "tket/tket/include/tket/ZX/ZXDiagramImpl.hpp",
"repo_id": "tket",
"token_count": 1466
} | 386 |
// Copyright 2019-2024 Cambridge Quantum Computing
//
// 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.
#include "tket/Characterisation/Cycles.hpp"
#include <numeric>
namespace tket {
class CycleError : public std::logic_error {
public:
explicit CycleError(const std::string& message) : std::logic_error(message) {}
};
unsigned Cycle::size() const { return boundary_edges_.size(); }
void Cycle::add_vertex_pair(const std::pair<Vertex, Vertex>& verts) {
frame_vertices.push_back(verts);
}
std::vector<std::pair<Vertex, Vertex>> Cycle::get_frame() const {
return frame_vertices;
}
UnitID CycleFinder::unitid_from_unit_frontier(
const std::shared_ptr<unit_frontier_t>& u_frontier, const Edge& e) const {
for (const std::pair<UnitID, Edge>& pair : u_frontier->get<TagKey>()) {
if (pair.second == e) {
return pair.first;
}
}
throw CycleError(std::string("Edge not in unit_frontier_t object."));
}
void CycleFinder::update_cycle_out_edges(const UnitID& uid, const Edge& e) {
for (std::pair<const Edge, UnitID>& pair : cycle_out_edges) {
if (pair.second == uid) {
cycle_out_edges.erase(pair.first);
cycle_out_edges[e] = uid;
return;
}
}
throw CycleError(std::string(
"UnitID " + uid.repr() + " not in std::map<Edge, UnitID> object."));
return;
}
void Cycle::update_boundary(
const Edge& source_edge, const Edge& replacement_edge) {
for (unsigned i = 0; i < boundary_edges_.size(); i++) {
if (boundary_edges_[i].second == source_edge) {
boundary_edges_[i].second = replacement_edge;
return;
}
}
throw CycleError("Source Edge matches no edges in boundary to cycle.");
return;
}
void CycleFinder::erase_keys(
const unsigned& to_erase, std::set<unsigned>& erase_from) const {
std::set<unsigned> all_erased;
for (const unsigned& key : erase_from) {
if (key <= to_erase) {
all_erased.insert(key);
}
}
for (const unsigned& key : all_erased) erase_from.erase(key);
}
// Adds a new cycle to this->cycle_history.key_to_cycle
std::pair<unsigned, std::set<unsigned>> CycleFinder::make_cycle(
const Vertex& v, const EdgeVec& out_edges, const CutFrontier& cut) {
// Make a new boundary, add it to "all_boundaries", update "boundary_key" map
std::vector<edge_pair_t> new_cycle_boundary;
std::set<UnitID> new_boundary_uids;
std::set<unsigned> old_boundary_keys;
std::set<unsigned> not_mergeable_keys;
std::set<UnitID> not_mergeable_uids;
// Get UnitID, add to uids for new boundary, keep note of all old boundary
// keys for merging set new boundary key, add new edges to new boundary update
// cycle out edges if the edge can't be found
for (const Edge& e : out_edges) {
UnitID uid = unitid_from_unit_frontier(cut.u_frontier, e);
new_boundary_uids.insert(uid);
old_boundary_keys.insert(this->cycle_history.uid_to_key[uid]);
// boundary key associated with given edge e not included
// i.e. e's associated in edge isn't a cycle out edge
// i.e. some other non-cycle gate has been passed
// if the edge going into the vertex is not in a previous cycle
// then it can't be merged with that cycle
if (cycle_out_edges.find(circ.get_last_edge(v, e)) ==
cycle_out_edges.end()) {
not_mergeable_keys.insert(this->cycle_history.uid_to_key[uid]);
}
this->cycle_history.uid_to_key[uid] = this->cycle_history.key;
new_cycle_boundary.push_back({circ.get_last_edge(v, e), e});
update_cycle_out_edges(uid, e);
}
for (const unsigned& key : old_boundary_keys) {
for (const UnitID& uid : this->cycle_history.history[key]) {
if (not_mergeable_uids.find(uid) != not_mergeable_uids.end()) {
not_mergeable_keys.insert(key);
break;
}
}
}
std::vector<unsigned> op_indices(out_edges.size());
std::iota(op_indices.begin(), op_indices.end(), 0);
// Edges in port ordering
Cycle new_cycle(
new_cycle_boundary, {{circ.get_OpType_from_Vertex(v), op_indices, v}});
this->cycle_history.key_to_cycle[this->cycle_history.key] = {new_cycle};
this->cycle_history.history.push_back(
std::vector<UnitID>(new_boundary_uids.begin(), new_boundary_uids.end()));
for (const unsigned& key : not_mergeable_keys) {
erase_keys(key, old_boundary_keys);
}
not_mergeable_keys.clear();
// For each candidate cycle "cycle" given as an unsigned key
// For all UnitID "uid" in "v" that are not in "cycle"
// For all cycles between cycle_history.uid_to_key[uid] and "cycle"
// If a cycle contains both "uid" and any "uid" from "cycle"
// Set the key as not to be merged
for (const unsigned& candidate_cycle_key : old_boundary_keys) {
std::vector<UnitID> candidate_cycle_uid =
this->cycle_history.history[candidate_cycle_key];
std::set<UnitID> not_present_uids;
for (const UnitID& candidate_uids : new_boundary_uids) {
if (std::find(
candidate_cycle_uid.begin(), candidate_cycle_uid.end(),
candidate_uids) == candidate_cycle_uid.end()) {
not_present_uids.insert(candidate_uids);
}
}
// not_present_uids now contains UnitID in the new cycle that are not in the
// cycle represented by "candidate_cycle_key"
// We now iterate through all cycles between these UnitIDs' most recent
// cycles and our target cycle
// If any of these cycles have both a non-present uid and any uid in the
// target cycle then this key is not mergeable and would lead to a "cycle in
// the DAG" (different type of cycle)
for (const UnitID& not_present_uid : not_present_uids) {
for (unsigned i = candidate_cycle_key;
i < this->cycle_history.uid_to_key[not_present_uid]; i++) {
std::vector<UnitID> history_uids = this->cycle_history.history[i];
if (std::find(
history_uids.begin(), history_uids.end(), not_present_uid) !=
history_uids.end()) {
std::vector<UnitID> intersection;
std::vector<UnitID> candidates =
cycle_history.history[candidate_cycle_key];
std::set_intersection(
candidates.begin(), candidates.end(), history_uids.begin(),
history_uids.end(), std::back_inserter(intersection));
if (!intersection.empty()) {
not_mergeable_keys.insert(candidate_cycle_key);
break;
}
}
}
}
}
for (const unsigned& key : not_mergeable_keys) {
erase_keys(key, old_boundary_keys);
}
std::pair<unsigned, std::set<unsigned>> return_keys = {
this->cycle_history.key, old_boundary_keys};
this->cycle_history.key++;
return return_keys;
}
// "old_keys" returned gives keys for boundaries to be merged together
// these "old_keys" are keys corresponding to boundaries UnitIDs in new boundary
// were in previously if two keys in passed old_keys have overlapping UnitIDs,
// then they cannot be merged in this case, remove the 'earlier' boundary from
// keys to be merged
void CycleFinder::order_keys(
unsigned& new_key, std::set<unsigned>& old_keys) const {
std::set<unsigned> bad_keys;
for (std::set<unsigned>::iterator it = old_keys.begin(); it != old_keys.end();
++it) {
std::set<unsigned>::iterator jt = it;
std::advance(jt, 1);
// if either std::vector<UnitID> has common UnitIDs then one is causally
// blocked. remove smaller key from keys from set as not a candidate for
// merging into
for (; jt != old_keys.end(); ++jt)
for (const UnitID& u0 : this->cycle_history.history[*it])
for (const UnitID& u1 : this->cycle_history.history[*jt])
if (u0 == u1) {
bad_keys.insert(*it);
goto new_loop;
}
new_loop: {}
}
for (const unsigned& key : bad_keys) old_keys.erase(key);
old_keys.insert(new_key);
}
void Cycle::update_coms_indices(
const std::map<unsigned, unsigned>& new_indices) {
for (CycleCom& com : coms_) {
for (unsigned& index : com.indices) {
index = new_indices.at(index);
}
}
}
// new cycle is made
// it may need to be immediately merged into other cycles
// 1) check for overlap of UnitID between cycles of "old_keys"
// if overlap, remove lowest value key from set
// 2) add "new_key" to "old_keys", merge all boundaries into corresponding
// boundary to highest value "old_key"
void Cycle::merge(Cycle& new_cycle) {
// iterate through edges in boundary of new_cycle
std::map<unsigned, unsigned> new_indices;
for (unsigned i = 0; i < new_cycle.boundary_edges_.size(); i++) {
bool match = false;
for (unsigned j = 0; j < boundary_edges_.size(); j++) {
// if in edge of boundary of new_cycle matches out of edge *this, update
// *this out edge
if (boundary_edges_[j].second == new_cycle.boundary_edges_[i].first) {
boundary_edges_[j].second = new_cycle.boundary_edges_[i].second;
// As CycleCom are labelled by basic indexing system, where indexing is
// related to position edge has in boundary Update CycleCom in new_cycle
// s.t. edges with index i now have index j update commands in new_cycle
// to match edgesindexing of *this for now, store new indexing
new_indices[i] = j;
match = true;
break;
}
}
if (!match) {
boundary_edges_.push_back(new_cycle.boundary_edges_[i]);
new_indices[i] = boundary_edges_.size() - 1;
}
}
// update CycleCom indices in new_cycle
new_cycle.update_coms_indices(new_indices);
coms_.insert(coms_.end(), new_cycle.coms_.begin(), new_cycle.coms_.end());
}
void CycleFinder::merge_cycles(unsigned new_key, std::set<unsigned>& old_keys) {
// boundary_keys is a std::set<unsigned> so is ordered
order_keys(new_key, old_keys);
// all cycles corresponding to keys in boundary_keys should be merged into
// boundary with smallest value
std::set<unsigned>::iterator it = old_keys.begin();
unsigned base_key = *it;
std::advance(it, 1);
for (; it != old_keys.end(); ++it) {
unsigned merge_key = *it;
this->cycle_history.key_to_cycle[base_key].merge(
this->cycle_history.key_to_cycle[merge_key]);
this->cycle_history.key_to_cycle.erase(merge_key);
// update this->cycle_history.history for "base_key"
for (const UnitID& u0 : this->cycle_history.history[merge_key]) {
this->cycle_history.uid_to_key[u0] = base_key;
for (const UnitID& u1 : this->cycle_history.history[base_key])
if (u0 == u1) break;
this->cycle_history.history[base_key].push_back(u0);
}
}
}
void CycleFinder::extend_cycles(const CutFrontier& cut) {
// For each vertex in slice
// Make a new "cycle"
// If any in edge to new cycle matches an out edge to a previous cycle,
// attempt to merge cycles together
for (const Vertex& v : *cut.slice) {
EdgeVec out_edges = circ.get_out_edges_of_type(v, EdgeType::Quantum);
// Compare EdgeType::Quantum "in_edges" of vertex in slice to collection of
// out edges from "active" boundaries If an "in_edge" is not equivalent to
// an out edge from "active" boundary, implies vertex needs to start a new
// boundary
std::pair<unsigned, std::set<unsigned>> all_keys =
make_cycle(v, out_edges, cut);
if (all_keys.second.size() > 0) {
merge_cycles(all_keys.first, all_keys.second);
}
}
}
std::vector<Cycle> CycleFinder::get_cycles() {
std::function<bool(Op_ptr)> skip_func = [&](Op_ptr op) {
return (cycle_types_.find(op->get_type()) == cycle_types_.end());
};
Circuit::SliceIterator slice_iter(circ, skip_func);
this->cycle_history.key = 0;
// initialization
if (!(*slice_iter).empty()) {
for (const std::pair<UnitID, Edge>& pair :
slice_iter.cut_.u_frontier->get<TagKey>()) {
Edge in_edge = pair.second;
if (circ.get_edgetype(in_edge) != EdgeType::Classical) {
Vertex in_vert = circ.source(pair.second);
// if vertex is type from types, then vertex is in slice and need
// in_edge. else can ignore.
if (cycle_types_.find(circ.get_OpType_from_Vertex(in_vert)) !=
cycle_types_.end()) {
in_edge = circ.get_last_edge(in_vert, pair.second);
}
cycle_out_edges.insert({in_edge, pair.first});
this->cycle_history.uid_to_key.insert(
{pair.first, this->cycle_history.key});
Cycle new_cycle({{in_edge, in_edge}}, {{}});
this->cycle_history.key_to_cycle[this->cycle_history.key] = new_cycle;
this->cycle_history.history.push_back({pair.first});
this->cycle_history.key++;
}
}
// extend cycles automatically merges cycles that can be merge due to
// overlapping multi-qubit gates
this->extend_cycles(slice_iter.cut_);
cycle_out_edges = {};
for (const std::pair<UnitID, Edge>& pair :
slice_iter.cut_.u_frontier->get<TagKey>()) {
cycle_out_edges.insert({pair.second, pair.first});
}
}
while (!slice_iter.finished()) {
slice_iter.cut_ = circ.next_cut(
slice_iter.cut_.u_frontier, slice_iter.cut_.b_frontier, skip_func);
if (!(*slice_iter).empty()) {
this->extend_cycles(slice_iter.cut_);
}
}
// Skim Cycle type from CycleHistory.key_to_cycle
// Discard any Cycles with only Input Gates
std::vector<Cycle> output_cycles;
for (std::pair<unsigned, Cycle> entry : this->cycle_history.key_to_cycle) {
if (entry.second.coms_.size() == 0) {
throw CycleError(std::string("Cycle with no internal gates."));
}
if (entry.second.boundary_edges_[0].first ==
entry.second.boundary_edges_[0].second) {
continue;
}
if (entry.second.size() > circ.n_qubits()) {
throw CycleError(
std::string("Cycle has a larger frame than Circuit has qubits."));
}
output_cycles.push_back(entry.second);
}
return output_cycles;
}
} // namespace tket
| tket/tket/src/Characterisation/Cycles.cpp/0 | {
"file_path": "tket/tket/src/Characterisation/Cycles.cpp",
"repo_id": "tket",
"token_count": 5513
} | 387 |
// Copyright 2019-2024 Cambridge Quantum Computing
//
// 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.
#include "tket/Circuit/DummyBox.hpp"
#include <boost/lexical_cast.hpp>
#include "Circuit/ResourceData.hpp"
#include "tket/Ops/OpJsonFactory.hpp"
namespace tket {
DummyBox::DummyBox(
unsigned n_qubits_, unsigned n_bits_, const ResourceData &resource_data_)
: Box(OpType::DummyBox),
n_qubits(n_qubits_),
n_bits(n_bits_),
resource_data(resource_data_) {}
DummyBox::DummyBox(const DummyBox &other)
: Box(other),
n_qubits(other.n_qubits),
n_bits(other.n_bits),
resource_data(other.resource_data) {}
bool DummyBox::is_equal(const Op &op_other) const {
const DummyBox &other = dynamic_cast<const DummyBox &>(op_other);
if (id_ == other.get_id()) return true;
return resource_data == other.resource_data;
}
unsigned DummyBox::get_n_qubits() const { return n_qubits; }
unsigned DummyBox::get_n_bits() const { return n_bits; }
ResourceData DummyBox::get_resource_data() const { return resource_data; }
op_signature_t DummyBox::get_signature() const {
op_signature_t sig(n_qubits, EdgeType::Quantum);
op_signature_t bits(n_bits, EdgeType::Classical);
sig.insert(sig.end(), bits.begin(), bits.end());
return sig;
}
nlohmann::json DummyBox::to_json(const Op_ptr &op) {
const auto &box = static_cast<const DummyBox &>(*op);
nlohmann::json j = core_box_json(box);
j["n_qubits"] = box.get_n_qubits();
j["n_bits"] = box.get_n_bits();
j["resource_data"] = box.get_resource_data();
return j;
}
Op_ptr DummyBox::from_json(const nlohmann::json &j) {
DummyBox box = DummyBox(
j.at("n_qubits").get<unsigned>(), j.at("n_bits").get<unsigned>(),
j.at("resource_data").get<ResourceData>());
return set_box_id(
box,
boost::lexical_cast<boost::uuids::uuid>(j.at("id").get<std::string>()));
}
REGISTER_OPFACTORY(DummyBox, DummyBox)
void DummyBox::generate_circuit() const { throw DummyBoxNotDecomposable(); }
} // namespace tket
| tket/tket/src/Circuit/DummyBox.cpp/0 | {
"file_path": "tket/tket/src/Circuit/DummyBox.cpp",
"repo_id": "tket",
"token_count": 937
} | 388 |
// Copyright 2019-2024 Cambridge Quantum Computing
//
// 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.
#include <algorithm>
#include <boost/graph/transitive_closure.hpp>
#include <cstddef>
#include <iterator>
#include <memory>
#include <optional>
#include <tkassert/Assert.hpp>
#include <vector>
#include "tket/Circuit/Circuit.hpp"
#include "tket/Circuit/DAGDefs.hpp"
#include "tket/OpType/EdgeType.hpp"
namespace tket {
// Representation of a connected convex subcircuit.
typedef struct {
VertexSet verts; // all vertices in the subcircuit
VertexSet preds; // all predecessors of vertices in the subcircuit that are
// not themselves in it
VertexSet succs; // all successors of vertices in the subcircuit that are not
// themselves in it
} subcircuit_info_t;
// Test whether the union of two connected convex subcircuits is connected.
static bool union_is_connected(
const subcircuit_info_t &subcircuit_info0,
const subcircuit_info_t &subcircuit_info1) {
const VertexSet &verts0 = subcircuit_info0.verts;
const VertexSet &verts1 = subcircuit_info1.verts;
for (const Vertex &v : subcircuit_info0.succs) {
if (verts1.contains(v)) {
return true;
}
}
for (const Vertex &v : subcircuit_info1.succs) {
if (verts0.contains(v)) {
return true;
}
}
return false;
}
static VertexSet set_diff(const VertexSet &A, const VertexSet &B) {
VertexSet C;
for (const Vertex &v : A) {
if (!B.contains(v)) {
C.insert(v);
}
}
return C;
}
// Return the union of two disjoint convex connected subcircuits, assuming that
// the union is convex and connected.
static subcircuit_info_t convex_union(
const subcircuit_info_t &subcircuit_info0,
const subcircuit_info_t &subcircuit_info1) {
const VertexSet &verts0 = subcircuit_info0.verts;
const VertexSet &preds0 = subcircuit_info0.preds;
const VertexSet &succs0 = subcircuit_info0.succs;
const VertexSet &verts1 = subcircuit_info1.verts;
const VertexSet &preds1 = subcircuit_info1.preds;
const VertexSet &succs1 = subcircuit_info1.succs;
// verts = verts0 ∪ verts1
VertexSet verts = verts0;
verts.insert(verts1.begin(), verts1.end());
// preds = (preds0 ∪ preds1) ∖ verts
VertexSet preds01 = preds0;
preds01.insert(preds1.begin(), preds1.end());
VertexSet preds = set_diff(preds01, verts);
// succs = (succs0 ∪ succs1) ∖ verts
VertexSet succs01 = succs0;
succs01.insert(succs1.begin(), succs1.end());
VertexSet succs = set_diff(succs01, verts);
return {verts, preds, succs};
}
static std::set<std::pair<Vertex, Vertex>> order_relations(
Circuit *circ /*const*/) {
// Put the vertices in reverse topological order:
VertexVec verts;
boost::topological_sort(circ->dag, std::back_inserter(verts));
// Construct a map v --> {all vertices in the future of v}:
std::map<Vertex, VertexSet> futures;
for (const Vertex &v : verts) {
VertexSet v_futures = {v};
for (const Vertex &w : circ->get_successors(v)) {
const VertexSet &w_futures = futures[w];
v_futures.insert(w_futures.begin(), w_futures.end());
}
futures[v] = v_futures;
}
// Construct the set of order relations:
std::set<std::pair<Vertex, Vertex>> rels;
for (const auto &v_ws : futures) {
const Vertex &v = v_ws.first;
for (const Vertex &w : v_ws.second) {
rels.insert({v, w});
}
}
return rels;
}
// Helper class for finding connected convex subcircuits.
class SubcircuitFinder {
public:
SubcircuitFinder(Circuit *circ /*const*/)
: circ_(circ), order_relations_(order_relations(circ)) {}
std::vector<VertexSet> find_subcircuits(
std::function<bool(Op_ptr)> criterion) {
// Find a maximal partition of the vertices satisfying the criterion into
// connected convex subcircuits. We use a greedy algorithm, beginning with
// the trivial partition into singletons, and then repeatedly looking for a
// pair that we can merge.
std::vector<subcircuit_info_t> subcircuit_infos;
// Form a trivial partition, one node per subcircuit:
BGL_FORALL_VERTICES(v, circ_->dag, DAG) {
if (criterion(circ_->get_Op_ptr_from_Vertex(v))) {
VertexVec preds = circ_->get_predecessors(v);
VertexVec succs = circ_->get_successors(v);
subcircuit_infos.push_back(
{{v}, {preds.begin(), preds.end()}, {succs.begin(), succs.end()}});
}
}
while (true) {
// If possible, find a mergeable pair of subcircuits and merge them.
std::optional<std::pair<std::size_t, std::size_t>> indices =
find_mergeable_pair(subcircuit_infos);
if (!indices.has_value()) {
break;
} else {
std::size_t i0 = indices->first;
std::size_t i1 = indices->second;
TKET_ASSERT(i0 < i1);
subcircuit_info_t subcircuit_info0 = subcircuit_infos[i0];
subcircuit_info_t subcircuit_info1 = subcircuit_infos[i1];
// Must erase in this order, since i0 < i1:
subcircuit_infos.erase(subcircuit_infos.begin() + i1);
subcircuit_infos.erase(subcircuit_infos.begin() + i0);
subcircuit_infos.push_back(
convex_union(subcircuit_info0, subcircuit_info1));
}
}
std::vector<VertexSet> subcircuits;
for (const subcircuit_info_t &subcircuit_info : subcircuit_infos) {
subcircuits.push_back(subcircuit_info.verts);
}
return subcircuits;
}
private:
// Test whether the union of two disjoint connected convex subcircuits is
// convex.
bool union_is_convex(
const subcircuit_info_t &subcircuit_info0,
const subcircuit_info_t &subcircuit_info1) {
const VertexSet &preds0 = subcircuit_info0.preds;
const VertexSet &succs0 = subcircuit_info0.succs;
const VertexSet &preds1 = subcircuit_info1.preds;
const VertexSet &succs1 = subcircuit_info1.succs;
for (const Vertex &v0 : succs0) {
for (const Vertex &v1 : preds1) {
if (order_relations_.contains({v0, v1})) {
return false;
}
}
}
for (const Vertex &v1 : succs1) {
for (const Vertex &v0 : preds0) {
if (order_relations_.contains({v1, v0})) {
return false;
}
}
}
return true;
}
// Given a vector of disjoint connected convex subcircuits, look for a pair
// whose union is connected and convex, and return the indices of such a pair
// if it exists.
std::optional<std::pair<std::size_t, std::size_t>> find_mergeable_pair(
const std::vector<subcircuit_info_t> &subcircuit_infos) {
std::size_t n_subcircuits = subcircuit_infos.size();
for (std::size_t i0 = 0; i0 < n_subcircuits; i0++) {
for (std::size_t i1 = i0 + 1; i1 < n_subcircuits; i1++) {
const subcircuit_info_t &subcircuit_info0 = subcircuit_infos[i0];
const subcircuit_info_t &subcircuit_info1 = subcircuit_infos[i1];
if (union_is_connected(subcircuit_info0, subcircuit_info1) &&
union_is_convex(subcircuit_info0, subcircuit_info1)) {
return std::pair<std::size_t, std::size_t>{i0, i1};
}
}
}
return std::nullopt;
}
const Circuit *circ_;
std::set<std::pair<Vertex, Vertex>> order_relations_;
};
std::vector<VertexSet> Circuit::get_subcircuits(
std::function<bool(Op_ptr)> criterion) /*const*/ {
index_vertices();
SubcircuitFinder finder(this);
return finder.find_subcircuits(criterion);
}
Subcircuit Circuit::make_subcircuit(VertexSet verts) const {
const std::map<Edge, UnitID> unitmap = edge_unit_map();
EdgeSet q_ins, q_outs, c_ins, c_outs;
for (const Vertex &v : verts) {
for (const Edge &v_in : get_in_edges(v)) {
if (!verts.contains(source(v_in))) {
switch (get_edgetype(v_in)) {
case EdgeType::Quantum:
q_ins.insert(v_in);
break;
case EdgeType::Classical:
c_ins.insert(v_in);
break;
default:
// Boolean and WASM edges ignored.
// TODO What to do? Throw?
break;
}
}
}
for (const Edge &v_out : get_all_out_edges(v)) {
if (!verts.contains(target(v_out))) {
switch (get_edgetype(v_out)) {
case EdgeType::Quantum:
q_outs.insert(v_out);
break;
case EdgeType::Classical:
c_outs.insert(v_out);
break;
default:
// Boolean and WASM edges ignored.
// TODO What to do? Throw?
break;
}
}
}
}
EdgeSet crs;
for (const Edge &e : c_outs) {
Vertex v = source(e);
for (const Edge &b_out : get_out_edges_of_type(v, EdgeType::Boolean)) {
crs.insert(b_out);
}
}
// Convert to vectors, taking care of order:
TKET_ASSERT(q_ins.size() == q_outs.size());
TKET_ASSERT(c_ins.size() == c_outs.size());
EdgeVec q_ins_vec{q_ins.begin(), q_ins.end()};
EdgeVec q_outs_vec{q_outs.begin(), q_outs.end()};
EdgeVec c_ins_vec{c_ins.begin(), c_ins.end()};
EdgeVec c_outs_vec{c_outs.begin(), c_outs.end()};
EdgeVec crs_vec{crs.begin(), crs.end()};
std::sort(
q_ins_vec.begin(), q_ins_vec.end(),
[&unitmap](const Edge &e0, const Edge &e1) {
return unitmap.at(e0) < unitmap.at(e1);
});
std::sort(
q_outs_vec.begin(), q_outs_vec.end(),
[&unitmap](const Edge &e0, const Edge &e1) {
return unitmap.at(e0) < unitmap.at(e1);
});
std::sort(
c_ins_vec.begin(), c_ins_vec.end(),
[&unitmap](const Edge &e0, const Edge &e1) {
return unitmap.at(e0) < unitmap.at(e1);
});
std::sort(
c_outs_vec.begin(), c_outs_vec.end(),
[&unitmap](const Edge &e0, const Edge &e1) {
return unitmap.at(e0) < unitmap.at(e1);
});
return {q_ins_vec, q_outs_vec, c_ins_vec, c_outs_vec, crs_vec, verts};
}
} // namespace tket
| tket/tket/src/Circuit/SubcircuitFinder.cpp/0 | {
"file_path": "tket/tket/src/Circuit/SubcircuitFinder.cpp",
"repo_id": "tket",
"token_count": 4475
} | 389 |
// Copyright 2019-2024 Cambridge Quantum Computing
//
// 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.
#include <stdexcept>
#include "tket/Converters/Converters.hpp"
namespace tket {
UnitaryTableau circuit_to_unitary_tableau(const Circuit& circ) {
UnitaryTableau tab(circ.all_qubits());
for (const Command& com : circ) {
auto args = com.get_args();
qubit_vector_t qbs = {args.begin(), args.end()};
tab.apply_gate_at_end(com.get_op_ptr()->get_type(), qbs);
}
return tab;
}
Circuit unitary_tableau_to_circuit(const UnitaryTableau& tab) {
SymplecticTableau tabl(tab.tab_);
unsigned size = tabl.get_n_qubits();
Circuit c(size);
/*
* Aaronson-Gottesman: Improved Simulation of Stabilizer Circuits, Theorem 8
* Any unitary stabilizer circuit has an equivalent circuit in canonical form
* (H-C-P-C-P-C-H-P-C-P-C).
* Produces a circuit realising the tableau, but consumes the tableau in the
* process.
*/
/*
* Step 1: Use Hadamards (in our case, Vs) to make C (z rows of xmat_) have
* full rank
*/
MatrixXb echelon = tabl.xmat.block(size, 0, size, size);
std::map<unsigned, unsigned> leading_val_to_col;
for (unsigned i = 0; i < size; i++) {
for (unsigned j = 0; j < size; j++) {
if (echelon(j, i)) {
if (leading_val_to_col.find(j) == leading_val_to_col.end()) {
leading_val_to_col.insert({j, i});
break;
} else {
unsigned l = leading_val_to_col.at(j);
for (unsigned k = 0; k < size; k++) {
echelon(k, i) ^= echelon(k, l);
}
}
}
}
if (leading_val_to_col.size() > i)
continue; // Independent of previous cols
c.add_op<unsigned>(OpType::V, {i});
tabl.apply_V(i);
tabl.apply_X(i);
echelon.col(i) = tabl.zmat.block(size, i, size, 1);
for (unsigned j = 0; j < size; j++) {
if (echelon(j, i)) {
if (leading_val_to_col.find(j) == leading_val_to_col.end()) {
leading_val_to_col.insert({j, i});
break;
} else {
unsigned l = leading_val_to_col.at(j);
for (unsigned k = 0; k < size; k++) {
echelon(k, i) ^= echelon(k, l);
}
}
}
}
if (leading_val_to_col.size() == i)
throw std::invalid_argument("Stabilisers are not mutually independent");
}
/*
* Step 2: Use CXs to perform Gaussian elimination on C (zpauli_x), producing
* / A B \
* \ I D /
*/
MatrixXb to_reduce = tabl.xmat.block(size, 0, size, size);
for (const std::pair<unsigned, unsigned>& qbs :
gaussian_elimination_col_ops(to_reduce)) {
c.add_op<unsigned>(OpType::CX, {qbs.first, qbs.second});
tabl.apply_CX(qbs.first, qbs.second);
}
/*
* Step 3: Commutativity of the stabilizer implies that ID^T is symmetric,
* therefore D is symmetric, and we can apply phase (S) gates to add a
* diagonal matrix to D and use Lemma 7 to convert D to the form D = MM^T
* for some invertible M.
*/
std::pair<MatrixXb, MatrixXb> zp_z_llt =
binary_LLT_decomposition(tabl.zmat.block(size, 0, size, size));
for (unsigned i = 0; i < size; i++) {
if (zp_z_llt.second(i, i)) {
c.add_op<unsigned>(OpType::S, {i});
tabl.apply_S(i);
tabl.apply_Z(i);
}
}
/*
* Step 4: Use CXs to produce
* / A B \
* \ M M /
* Note that when we map I to IM, we also map D to D(M^T)^{-1} = M.
*/
std::vector<std::pair<unsigned, unsigned>> m_to_i =
gaussian_elimination_col_ops(zp_z_llt.first);
for (std::vector<std::pair<unsigned, unsigned>>::reverse_iterator it =
m_to_i.rbegin();
it != m_to_i.rend(); it++) {
c.add_op<unsigned>(OpType::CX, {it->first, it->second});
tabl.apply_CX(it->first, it->second);
}
/*
* Step 5: Apply phases to all n qubits to obtain
* / A B \
* \ M 0 /
* Since M is full rank, there exists some subset S of qubits such that
* applying two phases in succession (Z) to every a \in S will preserve
* the tableau, but set r_{n+1} = ... = r_{2n} = 0 (zpauli_phase = 0^n).
* Apply two phases (Z) to every a \in S. DELAYED UNTIL END
*/
for (unsigned i = 0; i < size; i++) {
c.add_op<unsigned>(OpType::S, {i});
tabl.apply_S(i);
tabl.apply_Z(i);
}
/*
* Step 6: Use CXs to perform Gaussian elimination on M, producing
* / A B \
* \ I 0 /
* By commutativity relations, IB^T = A0^T + I, therefore B = I.
*/
to_reduce = tabl.xmat.block(size, 0, size, size);
for (const std::pair<unsigned, unsigned>& qbs :
gaussian_elimination_col_ops(to_reduce)) {
c.add_op<unsigned>(OpType::CX, {qbs.first, qbs.second});
tabl.apply_CX(qbs.first, qbs.second);
}
/*
* Step 7: Use Hadamards to produce
* / I A \
* \ 0 I /
*/
for (unsigned i = 0; i < size; i++) {
c.add_op<unsigned>(OpType::H, {i});
tabl.apply_H(i);
}
/*
* Step 8: Now commutativity of the destabilizer implies that A is symmetric,
* therefore we can again use phase (S) gates and Lemma 7 to make A = NN^T for
* some invertible N.
*/
std::pair<MatrixXb, MatrixXb> xp_z_llt =
binary_LLT_decomposition(tabl.zmat.block(0, 0, size, size));
for (unsigned i = 0; i < size; i++) {
if (xp_z_llt.second(i, i)) {
c.add_op<unsigned>(OpType::S, {i});
tabl.apply_S(i);
tabl.apply_Z(i);
}
}
/*
* Step 9: Use CXs to produce
* / N N \
* \ 0 C /
*/
std::vector<std::pair<unsigned, unsigned>> n_to_i =
gaussian_elimination_col_ops(xp_z_llt.first);
for (std::vector<std::pair<unsigned, unsigned>>::reverse_iterator it =
n_to_i.rbegin();
it != n_to_i.rend(); it++) {
c.add_op<unsigned>(OpType::CX, {it->first, it->second});
tabl.apply_CX(it->first, it->second);
}
/*
* Step 10: Use phases (S) to produce
* / N 0 \
* \ 0 C /
* then by commutativity relations NC^T = I. Next apply two phases (Z) each to
* some subset of qubits in order to preserve the above tableau, but set
* r_1 = ... = r_n = 0 (xpauli_phase = 0^n). DELAYED UNTIL END
*/
for (unsigned i = 0; i < size; i++) {
c.add_op<unsigned>(OpType::S, {i});
tabl.apply_S(i);
tabl.apply_Z(i);
}
/*
* Step 11: Use CXs to produce
* / I 0 \
* \ 0 I /
*/
for (const std::pair<unsigned, unsigned>& qbs :
gaussian_elimination_col_ops(tabl.xmat.block(0, 0, size, size))) {
c.add_op<unsigned>(OpType::CX, {qbs.first, qbs.second});
tabl.apply_CX(qbs.first, qbs.second);
}
/*
* DELAYED STEPS: Set all phases to 0 by applying Z or X gates
*/
for (unsigned i = 0; i < size; i++) {
if (tabl.phase(i)) {
c.add_op<unsigned>(OpType::Z, {i});
tabl.apply_Z(i);
}
if (tabl.phase(i + size)) {
c.add_op<unsigned>(OpType::X, {i});
tabl.apply_X(i);
}
}
/*
* Rename qubits
*/
unit_map_t rename_map;
for (boost::bimap<Qubit, unsigned>::const_iterator iter = tab.qubits_.begin(),
iend = tab.qubits_.end();
iter != iend; ++iter) {
rename_map.insert({Qubit(iter->right), iter->left});
}
c.rename_units(rename_map);
return c.transpose();
}
UnitaryRevTableau circuit_to_unitary_rev_tableau(const Circuit& circ) {
UnitaryRevTableau result(0);
result.tab_ = circuit_to_unitary_tableau(circ).dagger();
return result;
}
Circuit unitary_rev_tableau_to_circuit(const UnitaryRevTableau& tab) {
return unitary_tableau_to_circuit(tab.tab_.dagger());
}
} // namespace tket
| tket/tket/src/Converters/UnitaryTableauConverters.cpp/0 | {
"file_path": "tket/tket/src/Converters/UnitaryTableauConverters.cpp",
"repo_id": "tket",
"token_count": 3472
} | 390 |
// Copyright 2019-2024 Cambridge Quantum Computing
//
// 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.
#pragma once
#include "tket/Utils/MatrixAnalysis.hpp"
namespace tket {
class Gate;
namespace internal {
/** For getting sparse unitary matrices directly for specific gates,
* without constructing the dense matrices.
*/
struct GateUnitarySparseMatrix {
/** If the gate is an unknown type, returns an empty vector.
* (However, that only means that there is no specific sparse function.
* It may still be possible to get a dense unitary matrix
* from other functions).
*
* Return the unitary matrix of the gate in sparse format, i.e.
* a collection of (i,j,z) tuples, meaning that U(i,j) = z.
*
* @param gate unitary quantum gate
* @param abs_epsilon Used to decide whether an entry should be treated
* as zero. If std::abs(z) <= abs_epsilon then we treat z as
* zero exactly and so don't include it in the triplets.
* @return The triplets in the sparse representation.
*/
static std::vector<TripletCd> get_unitary_triplets(
const Gate& gate, double abs_epsilon = EPS);
};
} // namespace internal
} // namespace tket
| tket/tket/src/Gate/GateUnitarySparseMatrix.hpp/0 | {
"file_path": "tket/tket/src/Gate/GateUnitarySparseMatrix.hpp",
"repo_id": "tket",
"token_count": 515
} | 391 |
// Copyright 2019-2024 Cambridge Quantum Computing
//
// 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.
#include "tket/Mapping/LexiLabelling.hpp"
namespace tket {
std::pair<bool, unit_map_t> LexiLabellingMethod::routing_method(
MappingFrontier_ptr& mapping_frontier,
const ArchitecturePtr& architecture) const {
LexiRoute lr(architecture, mapping_frontier);
return {lr.solve_labelling(), {}};
}
nlohmann::json LexiLabellingMethod::serialize() const {
nlohmann::json j;
j["name"] = "LexiLabellingMethod";
return j;
}
LexiLabellingMethod LexiLabellingMethod::deserialize(
const nlohmann::json& /*j*/) {
return LexiLabellingMethod();
}
} // namespace tket
| tket/tket/src/Mapping/LexiLabelling.cpp/0 | {
"file_path": "tket/tket/src/Mapping/LexiLabelling.cpp",
"repo_id": "tket",
"token_count": 366
} | 392 |
// Copyright 2019-2024 Cambridge Quantum Computing
//
// 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.
#include "tket/Ops/BarrierOp.hpp"
#include <typeinfo>
#include "tket/OpType/EdgeType.hpp"
#include "tket/OpType/OpType.hpp"
#include "tket/Utils/Json.hpp"
namespace tket {
BarrierOp::BarrierOp(op_signature_t signature, const std::string& _data)
: Op(OpType::Barrier), signature_(signature), data_(_data) {}
Op_ptr BarrierOp::symbol_substitution(const SymEngine::map_basic_basic&) const {
return Op_ptr();
}
SymSet BarrierOp::free_symbols() const { return {}; }
unsigned BarrierOp::n_qubits() const {
return std::count(signature_.begin(), signature_.end(), EdgeType::Quantum);
}
op_signature_t BarrierOp::get_signature() const { return signature_; }
nlohmann::json BarrierOp::serialize() const {
nlohmann::json j;
j["type"] = get_type();
j["signature"] = get_signature();
j["data"] = get_data();
return j;
}
Op_ptr BarrierOp::deserialize(const nlohmann::json& j) {
op_signature_t sig = j.at("signature").get<op_signature_t>();
std::string data;
try {
data = j.at("data").get<std::string>();
} catch (const nlohmann::json::out_of_range& e) {
data = "";
}
return std::make_shared<BarrierOp>(sig, data);
}
bool BarrierOp::is_clifford() const { return true; }
BarrierOp::~BarrierOp() {}
bool BarrierOp::is_equal(const Op& op_other) const {
const BarrierOp& other = dynamic_cast<const BarrierOp&>(op_other);
return (
get_signature() == other.get_signature() &&
get_data() == other.get_data());
}
} // namespace tket
| tket/tket/src/Ops/BarrierOp.cpp/0 | {
"file_path": "tket/tket/src/Ops/BarrierOp.cpp",
"repo_id": "tket",
"token_count": 720
} | 393 |
// Copyright 2019-2024 Cambridge Quantum Computing
//
// 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.
#pragma once
#include <stdexcept>
#include <tkassert/Assert.hpp>
#include <tkwsm/Common/GeneralUtils.hpp>
#include <tkwsm/GraphTheoretic/GeneralStructs.hpp>
#include "tket/Placement/Placement.hpp"
namespace tket {
namespace WeightedSubgraphMonomorphism {
/** Intended for use with Architecture and QubitGraph, which are similar
* but different types. Calculate new VertexWSM vertex labels.
*/
template <class VertexType, class GraphType>
class RelabelledGraphWSM {
public:
explicit RelabelledGraphWSM(const GraphType& graph) {
// Get the new vertex integer labels.
m_original_vertices.reserve(boost::num_vertices(graph));
{
const auto vertex_iter_pair = boost::vertices(graph);
for (auto citer = vertex_iter_pair.first;
citer != vertex_iter_pair.second; ++citer) {
// Add the vertex to the map keys.
m_old_to_new_vertex_map[graph[*citer]];
}
// Now add the new vertex labels.
for (auto& entry : m_old_to_new_vertex_map) {
entry.second = m_original_vertices.size();
m_original_vertices.emplace_back(entry.first);
}
}
// Get the newly labelled edges.
const auto edge_iter_pair = boost::edges(graph);
for (auto citer = edge_iter_pair.first; citer != edge_iter_pair.second;
++citer) {
auto edge = get_edge(
get_relabelled_vertex(graph[boost::source(*citer, graph)]),
get_relabelled_vertex(graph[boost::target(*citer, graph)]));
m_relabelled_edges_and_weights[edge] = unsigned(graph[*citer].weight);
}
// Now, classify the vertices into isolated and nonisolated categories
for (const auto& relabelled_edge_entry : m_relabelled_edges_and_weights) {
const auto& relabelled_edge = relabelled_edge_entry.first;
m_relabelled_nonisolated_vertices.insert(relabelled_edge.first);
m_relabelled_nonisolated_vertices.insert(relabelled_edge.second);
}
for (const auto& entry : m_old_to_new_vertex_map) {
if (m_relabelled_nonisolated_vertices.count(entry.second) == 0) {
m_relabelled_isolated_vertices.insert(entry.second);
}
}
TKET_ASSERT(
m_old_to_new_vertex_map.size() ==
m_relabelled_isolated_vertices.size() +
m_relabelled_nonisolated_vertices.size());
}
const GraphEdgeWeights& get_relabelled_edges_and_weights() const {
return m_relabelled_edges_and_weights;
}
const std::set<VertexWSM>& get_relabelled_isolated_vertices() const {
return m_relabelled_isolated_vertices;
}
const std::set<VertexWSM>& get_relabelled_nonisolated_vertices() const {
return m_relabelled_nonisolated_vertices;
}
// element [i] is the vertex which has been relabelled i.
const std::vector<VertexType>& get_original_vertices() const {
return m_original_vertices;
}
VertexWSM get_relabelled_vertex(const VertexType& original_vertex) const {
const auto v_opt =
get_optional_value(m_old_to_new_vertex_map, original_vertex);
if (!v_opt) {
throw std::runtime_error("Original vertex has no new label");
}
return v_opt.value();
}
private:
std::vector<VertexType> m_original_vertices;
std::map<VertexType, VertexWSM> m_old_to_new_vertex_map;
std::set<VertexWSM> m_relabelled_isolated_vertices;
std::set<VertexWSM> m_relabelled_nonisolated_vertices;
// All edge weights will be 1, since we're only considering
// unweighted problems.
GraphEdgeWeights m_relabelled_edges_and_weights;
};
} // namespace WeightedSubgraphMonomorphism
} // namespace tket
| tket/tket/src/Placement/RelabelledGraphWSM.hpp/0 | {
"file_path": "tket/tket/src/Placement/RelabelledGraphWSM.hpp",
"repo_id": "tket",
"token_count": 1564
} | 394 |
// Copyright 2019-2024 Cambridge Quantum Computing
//
// 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.
#include "tket/Transformations/PQPSquash.hpp"
#include <memory>
#include "tket/Circuit/DAGDefs.hpp"
#include "tket/Gate/Rotation.hpp"
#include "tket/OpType/OpTypeInfo.hpp"
#include "tket/Transformations/BasicOptimisation.hpp"
#include "tket/Transformations/Decomposition.hpp"
#include "tket/Transformations/Transform.hpp"
#include "tket/Utils/Expression.hpp"
namespace tket::Transforms {
static bool fixup_angles(
Expr &angle_p1, Expr &angle_q, Expr &angle_p2, bool reversed = false);
static Rotation merge_rotations(
OpType r, const std::vector<Gate_ptr> &chain,
std::vector<Gate_ptr>::const_iterator &iter);
PQPSquasher::PQPSquasher(OpType p, OpType q, bool smart_squash, bool reversed)
: p_(p),
q_(q),
smart_squash_(smart_squash),
reversed_(reversed),
rotation_chain() {
if (!(p == OpType::Rx || p == OpType::Ry || p == OpType::Rz) ||
!(q == OpType::Rx || q == OpType::Ry || q == OpType::Rz)) {
throw std::logic_error("Can only reduce chains of single qubit rotations");
}
if (p == q) {
throw std::logic_error(
"Requires two different bases to perform single qubit "
"rotations");
}
}
bool PQPSquasher::accepts(Gate_ptr gp) const {
OpType type = gp->get_type();
return type == p_ || type == q_;
}
void PQPSquasher::append(Gate_ptr gp) {
if (!accepts(gp)) {
throw BadOpType("PQPSquasher: cannot append OpType", gp->get_type());
}
rotation_chain.push_back(gp);
}
std::pair<Circuit, Gate_ptr> PQPSquasher::flush(
std::optional<Pauli> commutation_colour) const {
bool commute_through = false;
OpType p = p_, q = q_;
if (smart_squash_ && commutation_colour.has_value()) {
// Using an arbitrary non-zero angle to obtain the commutation for p_/q_.
Gate P(p_, {0.123}, 1);
Gate Q(q_, {0.123}, 1);
if (P.commutes_with_basis(commutation_colour, 0)) {
commute_through = true;
} else if (Q.commutes_with_basis(commutation_colour, 0)) {
commute_through = true;
p = q_;
q = p_;
}
}
// Construct list of merged rotations
std::list<Rotation> rots;
auto iter = rotation_chain.cbegin();
while (iter != rotation_chain.cend()) {
// Merge next q rotations
rots.push_back(merge_rotations(q, rotation_chain, iter));
// Merge next p rotations
rots.push_back(merge_rotations(p, rotation_chain, iter));
}
// Perform any cancellations
std::list<Rotation>::iterator r = rots.begin();
while (r != rots.end()) {
if (r->is_id()) {
r = rots.erase(r);
if (r != rots.begin() && r != rots.end()) {
std::prev(r)->apply(*r);
r = rots.erase(r);
r--;
}
} else
r++;
}
// Extract any P rotations from the beginning and end of the list
Expr p1 = 0, p2 = 0;
std::list<Rotation>::iterator i1 = rots.begin();
if (i1 != rots.end()) {
std::optional<Expr> a = i1->angle(p);
if (a) {
p1 = a.value();
rots.pop_front();
}
}
std::list<Rotation>::reverse_iterator i2 = rots.rbegin();
if (i2 != rots.rend()) {
std::optional<Expr> a = i2->angle(p);
if (a) {
p2 = a.value();
rots.pop_back();
}
}
// Finish up:
Rotation R = {};
for (auto rot : rots) {
R.apply(rot);
}
std::tuple<Expr, Expr, Expr> angles = R.to_pqp(p, q);
Expr angle_p1 = std::get<0>(angles) + p1;
Expr angle_q = std::get<1>(angles);
Expr angle_p2 = std::get<2>(angles) + p2;
fixup_angles(angle_p1, angle_q, angle_p2, reversed_);
Circuit replacement(1);
Gate_ptr left_over_gate = nullptr;
if (!equiv_0(angle_p1, 4)) {
if (equiv_0(angle_q, 4) && equiv_0(angle_p2, 4) && commute_through) {
left_over_gate =
std::make_shared<Gate>(p, std::vector<Expr>{angle_p1}, 1);
} else {
replacement.add_op<unsigned>(p, angle_p1, {0});
}
}
if (!equiv_0(angle_q, 4)) {
replacement.add_op<unsigned>(q, angle_q, {0});
}
if (!equiv_0(angle_p2, 4)) {
if (commute_through) {
left_over_gate =
std::make_shared<Gate>(p, std::vector<Expr>{angle_p2}, 1);
} else {
replacement.add_op<unsigned>(p, angle_p2, {0});
}
}
redundancy_removal(replacement);
return {replacement, left_over_gate};
}
void PQPSquasher::clear() { rotation_chain.clear(); }
std::unique_ptr<AbstractSquasher> PQPSquasher::clone() const {
return std::make_unique<PQPSquasher>(*this);
}
static Rotation merge_rotations(
OpType r, const std::vector<Gate_ptr> &chain,
std::vector<Gate_ptr>::const_iterator &iter) {
Expr total_angle(0);
while (iter != chain.end()) {
const Gate_ptr rot_op = *iter;
if (rot_op->get_type() != r) {
break;
}
total_angle += rot_op->get_params()[0];
iter++;
}
return Rotation(r, total_angle);
}
static bool squash_to_pqp(
Circuit &circ, OpType q, OpType p, bool strict = false) {
bool reverse = true;
auto squasher = std::make_unique<PQPSquasher>(p, q, !strict, reverse);
return SingleQubitSquash(std::move(squasher), circ, reverse).squash();
}
Transform squash_1qb_to_pqp(const OpType &q, const OpType &p, bool strict) {
return Transform(
[=](Circuit &circ) { return squash_to_pqp(circ, q, p, strict); });
}
// To squash to TK1:
// - we first decompose to ZYZ. Doing this was found to reduce the size of
// symbolic expressions
// - we then redecompose to ZXZ, so that we can commute Rz or Rx rotation past
// multi-qubit gates (most usual multi-qb gates commute with X or Z)
// - Rz and Rx rotations can then be straight-forwardly combined into TK1s.
Transform squash_1qb_to_tk1() {
return Transforms::decompose_ZY() >>
squash_1qb_to_pqp(OpType::Ry, OpType::Rz, true) >>
Transforms::decompose_ZX() >>
squash_1qb_to_pqp(OpType::Rx, OpType::Rz, true) >>
Transforms::decompose_ZXZ_to_TK1();
}
static bool fixup_angles(
Expr &angle_p1, Expr &angle_q, Expr &angle_p2, bool reversed) {
bool success = false;
if (reversed) {
std::swap(angle_p1, angle_p2);
angle_p1 *= -1;
angle_q *= -1;
angle_p2 *= -1;
}
if (equiv_val(angle_q, 1., 2) && !equiv_0(angle_p2, 4)) {
// Prefer --P(p1-p2)--Q(...)--P(0)--
// Only occurs if angle_q is pi or 3pi and angle_p2 is non-zero
angle_p1 -= angle_p2;
angle_p2 = 0;
success = true;
} else if (equiv_val(angle_p2, 1., 4)) {
// Then prefer --P(p1+p2)--Q(-q)--P(0)--
// Only occurs if angle_p2 is pi
angle_p1 += 1;
angle_q *= -1;
angle_p2 = 0;
success = true;
} else if (equiv_val(angle_p2, 3., 4)) {
// Then prefer --P(p1+p2)--Q(-q)--P(0)--
// Only occurs if angle_p2 is 3pi
angle_p1 += 3;
angle_q *= -1;
angle_p2 = 0;
success = true;
} else if (equiv_val(angle_p1, 1., 4) && !equiv_0(angle_p2, 4)) {
// Then prefer --P(0)--Q(-q)--P(p1+p2)--
// Only occurs if angle_p1 is pi and angle_p2 is non-zero
angle_q *= -1;
angle_p2 += 1;
angle_p1 = 0;
success = true;
} else if (equiv_val(angle_p1, 3., 4) && !equiv_0(angle_p2, 4)) {
// Then prefer --P(0)--Q(-q)--P(p1+p2)--
// Only occurs if angle_p1 is 3pi and angle_p2 is non-zero
angle_q *= -1;
angle_p2 += 3;
angle_p1 = 0;
success = true;
}
if (reversed) {
std::swap(angle_p1, angle_p2);
angle_p1 *= -1;
angle_q *= -1;
angle_p2 *= -1;
}
return success;
}
} // namespace tket::Transforms
| tket/tket/src/Transformations/PQPSquash.cpp/0 | {
"file_path": "tket/tket/src/Transformations/PQPSquash.cpp",
"repo_id": "tket",
"token_count": 3392
} | 395 |
// Copyright 2019-2024 Cambridge Quantum Computing
//
// 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.
#include "tket/Utils/PauliTensor.hpp"
#include <tkassert/Assert.hpp>
namespace tket {
void to_json(nlohmann::json &, const no_coeff_t &) {}
void from_json(const nlohmann::json &, no_coeff_t &) {}
template <>
no_coeff_t default_coeff<no_coeff_t>() {
return {};
}
template <>
quarter_turns_t default_coeff<quarter_turns_t>() {
return 0;
}
template <>
Complex default_coeff<Complex>() {
return 1.;
}
template <>
Expr default_coeff<Expr>() {
return 1;
}
template <>
QubitPauliMap cast_container<QubitPauliMap, QubitPauliMap>(
const QubitPauliMap &cont) {
return cont;
}
template <>
QubitPauliMap cast_container<DensePauliMap, QubitPauliMap>(
const DensePauliMap &cont) {
QubitPauliMap res;
for (unsigned i = 0; i < cont.size(); ++i) {
Pauli pi = cont.at(i);
if (pi != Pauli::I) res.insert({Qubit(i), cont.at(i)});
}
return res;
}
template <>
DensePauliMap cast_container<QubitPauliMap, DensePauliMap>(
const QubitPauliMap &cont) {
if (cont.empty()) return {};
unsigned max_index = 0;
for (const std::pair<const Qubit, Pauli> &pair : cont) {
if (pair.first.reg_info() != register_info_t{UnitType::Qubit, 1} ||
pair.first.reg_name() != q_default_reg())
throw std::logic_error(
"Cannot cast a QubitPauliMap with non-default register qubits to a "
"DensePauliMap");
unsigned i = pair.first.index().front();
if (i > max_index) max_index = i;
}
DensePauliMap res(max_index + 1, Pauli::I);
for (const std::pair<const Qubit, Pauli> &pair : cont) {
res.at(pair.first.index().front()) = pair.second;
}
return res;
}
template <>
DensePauliMap cast_container<DensePauliMap, DensePauliMap>(
const DensePauliMap &cont) {
return cont;
}
template <>
no_coeff_t cast_coeff<no_coeff_t, no_coeff_t>(const no_coeff_t &) {
return {};
}
template <>
quarter_turns_t cast_coeff<no_coeff_t, quarter_turns_t>(const no_coeff_t &) {
return 0;
}
template <>
Complex cast_coeff<no_coeff_t, Complex>(const no_coeff_t &) {
return 1.;
}
template <>
Expr cast_coeff<no_coeff_t, Expr>(const no_coeff_t &) {
return 1.;
}
template <>
no_coeff_t cast_coeff<quarter_turns_t, no_coeff_t>(const quarter_turns_t &) {
return {};
}
template <>
quarter_turns_t cast_coeff<quarter_turns_t, quarter_turns_t>(
const quarter_turns_t &coeff) {
return coeff;
}
template <>
Complex cast_coeff<quarter_turns_t, Complex>(const quarter_turns_t &coeff) {
switch (coeff % 4) {
case 0: {
return 1.;
}
case 1: {
return i_;
}
case 2: {
return -1.;
}
default: {
return -i_;
}
}
}
template <>
Expr cast_coeff<quarter_turns_t, Expr>(const quarter_turns_t &coeff) {
switch (coeff % 4) {
case 0: {
return Expr(1);
}
case 1: {
return Expr(SymEngine::I);
}
case 2: {
return Expr(-1);
}
default: {
return -Expr(SymEngine::I);
}
}
}
template <>
no_coeff_t cast_coeff<Complex, no_coeff_t>(const Complex &) {
return {};
}
template <>
quarter_turns_t cast_coeff<Complex, quarter_turns_t>(const Complex &coeff) {
if (std::abs(coeff - 1.) < EPS)
return 0;
else if (std::abs(coeff - i_) < EPS)
return 1;
else if (std::abs(coeff + 1.) < EPS)
return 2;
else if (std::abs(coeff + i_) < EPS)
return 3;
else
throw std::logic_error(
"Could not cast PauliTensor coefficient to quarter turns: not a power "
"of i.");
}
template <>
Complex cast_coeff<Complex, Complex>(const Complex &coeff) {
return coeff;
}
template <>
Expr cast_coeff<Complex, Expr>(const Complex &coeff) {
return Expr(SymEngine::make_rcp<const SymEngine::ComplexDouble>(coeff));
}
template <>
no_coeff_t cast_coeff<Expr, no_coeff_t>(const Expr &) {
return {};
}
template <>
quarter_turns_t cast_coeff<Expr, quarter_turns_t>(const Expr &coeff) {
std::optional<Complex> ev = eval_expr_c(coeff);
if (ev)
return cast_coeff<Complex, quarter_turns_t>(*ev);
else
throw std::logic_error(
"Could not cast symbolic PauliTensor to quarter turns.");
}
template <>
Complex cast_coeff<Expr, Complex>(const Expr &coeff) {
std::optional<Complex> ev = eval_expr_c(coeff);
if (ev)
return *ev;
else
throw std::logic_error(
"Could not cast symbolic PauliTensor to complex coefficient.");
}
template <>
Expr cast_coeff<Expr, Expr>(const Expr &coeff) {
return coeff;
}
template <>
int compare_containers<QubitPauliMap>(
const QubitPauliMap &first, const QubitPauliMap &second) {
QubitPauliMap::const_iterator p1_it = first.begin();
QubitPauliMap::const_iterator p2_it = second.begin();
while (p1_it != first.end()) {
if (p1_it->second == Pauli::I) {
++p1_it;
continue;
}
while (p2_it != second.end() && p2_it->second == Pauli::I) {
++p2_it;
}
if (p2_it == second.end()) return 1;
// QubitPauliMap order should reflect ILO
// i.e. IZ < ZI (Zq1 < Zq0)
// Hence we first order by reverse of leading qubit
if (p1_it->first < p2_it->first) return 1;
if (p2_it->first < p1_it->first) return -1;
// and then by increasing order of Pauli letter on the same qubit
if (p1_it->second < p2_it->second) return -1;
if (p1_it->second > p2_it->second) return 1;
++p1_it;
++p2_it;
}
while (p2_it != second.end() && p2_it->second == Pauli::I) {
++p2_it;
}
return (p2_it == second.end()) ? 0 : -1;
}
template <>
int compare_containers<DensePauliMap>(
const DensePauliMap &first, const DensePauliMap &second) {
DensePauliMap::const_iterator p1_it = first.begin();
DensePauliMap::const_iterator p2_it = second.begin();
while (p1_it != first.end() && p2_it != second.end()) {
if (*p1_it == Pauli::I) {
if (*p2_it != Pauli::I) return -1;
} else if (*p2_it == Pauli::I)
return 1;
else if (*p1_it < *p2_it)
return -1;
else if (*p1_it > *p2_it)
return 1;
++p1_it;
++p2_it;
}
while (p1_it != first.end() && *p1_it == Pauli::I) ++p1_it;
if (p1_it != first.end()) return 1;
while (p2_it != second.end() && *p2_it == Pauli::I) ++p2_it;
return (p2_it == second.end()) ? 0 : -1;
}
template <>
int compare_coeffs<no_coeff_t>(const no_coeff_t &, const no_coeff_t &) {
return 0;
}
template <>
int compare_coeffs<quarter_turns_t>(
const quarter_turns_t &first, const quarter_turns_t &second) {
if (first % 4 < second % 4) return -1;
return (first % 4 == second % 4) ? 0 : 1;
}
template <>
int compare_coeffs<Complex>(const Complex &first, const Complex &second) {
if (first.real() < second.real()) return -1;
if (first.real() > second.real()) return 1;
if (first.imag() < second.imag()) return -1;
return (first.imag() == second.imag()) ? 0 : 1;
}
template <>
int compare_coeffs<Expr>(const Expr &first, const Expr &second) {
// Comparison of SymEngine expressions will distinguish between e.g. integer
// 1, double 1., and complex 1., so only use for actual symbolic expressions
std::optional<Complex> reduced_first = eval_expr_c(first);
std::optional<Complex> reduced_second = eval_expr_c(second);
if (reduced_first && reduced_second)
return compare_coeffs<Complex>(*reduced_first, *reduced_second);
else
return first.get_basic()->compare(second);
}
std::set<Qubit> common_qubits(
const QubitPauliMap &first, const QubitPauliMap &second) {
std::set<Qubit> common;
for (const std::pair<const Qubit, Pauli> &p : first) {
if (p.second == Pauli::I) continue;
QubitPauliMap::const_iterator found = second.find(p.first);
if (found != second.end() && found->second == p.second)
common.insert(p.first);
}
return common;
}
std::set<unsigned> common_indices(
const DensePauliMap &first, const DensePauliMap &second) {
std::set<unsigned> common;
unsigned min_size = std::min(first.size(), second.size());
for (unsigned i = 0; i < min_size; ++i) {
Pauli p = first.at(i);
if (p != Pauli::I && p == second.at(i)) common.insert(i);
}
return common;
}
std::set<Qubit> own_qubits(
const QubitPauliMap &first, const QubitPauliMap &second) {
std::set<Qubit> own;
for (const std::pair<const Qubit, Pauli> &p : first) {
if (p.second == Pauli::I) continue;
QubitPauliMap::const_iterator found = second.find(p.first);
if (found == second.end() || found->second == Pauli::I) own.insert(p.first);
}
return own;
}
std::set<unsigned> own_indices(
const DensePauliMap &first, const DensePauliMap &second) {
std::set<unsigned> own;
unsigned min_size = std::min(first.size(), second.size());
for (unsigned i = 0; i < min_size; ++i) {
if (first.at(i) != Pauli::I && second.at(i) == Pauli::I) own.insert(i);
}
for (unsigned i = min_size; i < first.size(); ++i) {
if (first.at(i) != Pauli::I) own.insert(i);
}
return own;
}
std::set<Qubit> conflicting_qubits(
const QubitPauliMap &first, const QubitPauliMap &second) {
std::set<Qubit> conflicts;
for (const std::pair<const Qubit, Pauli> &p : first) {
if (p.second == Pauli::I) continue;
QubitPauliMap::const_iterator found = second.find(p.first);
if (found != second.end() && found->second != Pauli::I &&
found->second != p.second)
conflicts.insert(p.first);
}
return conflicts;
}
std::set<unsigned> conflicting_indices(
const DensePauliMap &first, const DensePauliMap &second) {
std::set<unsigned> conflicts;
unsigned min_size = std::min(first.size(), second.size());
for (unsigned i = 0; i < min_size; ++i) {
Pauli p = first.at(i);
Pauli p2 = second.at(i);
if (p != Pauli::I && p2 != Pauli::I && p != p2) conflicts.insert(i);
}
return conflicts;
}
template <>
bool commuting_containers<QubitPauliMap>(
const QubitPauliMap &first, const QubitPauliMap &second) {
return (conflicting_qubits(first, second).size() % 2) == 0;
}
template <>
bool commuting_containers<DensePauliMap>(
const DensePauliMap &first, const DensePauliMap &second) {
return (conflicting_indices(first, second).size() % 2) == 0;
}
template <>
void print_paulis<QubitPauliMap>(
std::ostream &os, const QubitPauliMap &paulis) {
os << "(";
QubitPauliMap::const_iterator i = paulis.begin();
while (i != paulis.end()) {
switch (i->second) {
case Pauli::I: {
os << "I";
break;
}
case Pauli::X: {
os << "X";
break;
}
case Pauli::Y: {
os << "Y";
break;
}
case Pauli::Z: {
os << "Z";
break;
}
}
os << i->first.repr();
++i;
if (i != paulis.end()) os << ", ";
}
os << ")";
}
template <>
void print_paulis<DensePauliMap>(
std::ostream &os, const DensePauliMap &paulis) {
for (const Pauli &p : paulis) {
switch (p) {
case Pauli::I: {
os << "I";
break;
}
case Pauli::X: {
os << "X";
break;
}
case Pauli::Y: {
os << "Y";
break;
}
case Pauli::Z: {
os << "Z";
break;
}
}
}
}
template <>
void print_coeff<no_coeff_t>(std::ostream &, const no_coeff_t &) {}
template <>
void print_coeff<quarter_turns_t>(
std::ostream &os, const quarter_turns_t &coeff) {
switch (coeff % 4) {
case 1: {
os << "i*";
break;
}
case 2: {
os << "-";
break;
}
case 3: {
os << "-i*";
break;
}
default: {
break;
}
}
}
template <>
void print_coeff<Complex>(std::ostream &os, const Complex &coeff) {
if (coeff == -1.) {
os << "-";
} else if (coeff != 1.) {
os << coeff << "*";
}
}
template <>
void print_coeff<Expr>(std::ostream &os, const Expr &coeff) {
// Expressions distinguish integers from floating-points
if (coeff == -1. || coeff == -1) {
os << "-";
} else if (coeff != 1. && coeff != 1) {
os << "(" << coeff << ")*";
}
}
template <>
void hash_combine_paulis<QubitPauliMap>(
std::size_t &seed, const QubitPauliMap &paulis) {
for (const std::pair<const Qubit, Pauli> &qp : paulis) {
if (qp.second != Pauli::I) {
boost::hash_combine(seed, qp.first);
boost::hash_combine(seed, qp.second);
}
}
}
template <>
void hash_combine_paulis<DensePauliMap>(
std::size_t &seed, const DensePauliMap &paulis) {
DensePauliMap::const_reverse_iterator i = paulis.rbegin();
while (i != paulis.rend() && *i == Pauli::I) {
++i;
}
while (i != paulis.rend()) {
boost::hash_combine(seed, *i);
++i;
}
}
template <>
void hash_combine_coeff<no_coeff_t>(std::size_t &, const no_coeff_t &) {}
template <>
void hash_combine_coeff<quarter_turns_t>(
std::size_t &seed, const quarter_turns_t &coeff) {
boost::hash_combine(seed, coeff % 4);
}
template <>
void hash_combine_coeff<Complex>(std::size_t &seed, const Complex &coeff) {
boost::hash_combine(seed, coeff);
}
template <>
void hash_combine_coeff<Expr>(std::size_t &seed, const Expr &coeff) {
boost::hash_combine(seed, coeff.get_basic()->hash());
}
template <>
unsigned n_ys<QubitPauliMap>(const QubitPauliMap &paulis) {
unsigned n = 0;
for (const std::pair<const Qubit, Pauli> &qp : paulis) {
if (qp.second == Pauli::Y) ++n;
}
return n;
}
template <>
unsigned n_ys<DensePauliMap>(const DensePauliMap &paulis) {
unsigned n = 0;
for (const Pauli &p : paulis) {
if (p == Pauli::Y) ++n;
}
return n;
}
const std::map<std::pair<Pauli, Pauli>, std::pair<quarter_turns_t, Pauli>> &
get_mult_matrix() {
static const std::map<
std::pair<Pauli, Pauli>, std::pair<quarter_turns_t, Pauli>>
mult_matrix{
{{Pauli::I, Pauli::I}, {0, Pauli::I}},
{{Pauli::I, Pauli::X}, {0, Pauli::X}},
{{Pauli::I, Pauli::Y}, {0, Pauli::Y}},
{{Pauli::I, Pauli::Z}, {0, Pauli::Z}},
{{Pauli::X, Pauli::I}, {0, Pauli::X}},
{{Pauli::X, Pauli::X}, {0, Pauli::I}},
{{Pauli::X, Pauli::Y}, {1, Pauli::Z}},
{{Pauli::X, Pauli::Z}, {3, Pauli::Y}},
{{Pauli::Y, Pauli::I}, {0, Pauli::Y}},
{{Pauli::Y, Pauli::X}, {3, Pauli::Z}},
{{Pauli::Y, Pauli::Y}, {0, Pauli::I}},
{{Pauli::Y, Pauli::Z}, {1, Pauli::X}},
{{Pauli::Z, Pauli::I}, {0, Pauli::Z}},
{{Pauli::Z, Pauli::X}, {1, Pauli::Y}},
{{Pauli::Z, Pauli::Y}, {3, Pauli::X}},
{{Pauli::Z, Pauli::Z}, {0, Pauli::I}},
};
return mult_matrix;
}
template <>
std::pair<quarter_turns_t, QubitPauliMap> multiply_strings<QubitPauliMap>(
const QubitPauliMap &first, const QubitPauliMap &second) {
quarter_turns_t total_turns = 0;
QubitPauliMap result;
QubitPauliMap::const_iterator fi = first.begin();
QubitPauliMap::const_iterator si = second.begin();
while (fi != first.end()) {
while (si != second.end() && si->first < fi->first) {
result.insert(*si);
++si;
}
if (si != second.end() && si->first == fi->first) {
// Pauli in the same position, so need to multiply
const std::pair<quarter_turns_t, Pauli> &prod =
get_mult_matrix().at({fi->second, si->second});
total_turns += prod.first;
if (prod.second != Pauli::I) {
result.insert({fi->first, prod.second});
}
++si;
} else {
result.insert(*fi);
}
++fi;
}
while (si != second.end()) {
result.insert(*si);
++si;
}
return {total_turns, result};
}
template <>
std::pair<quarter_turns_t, DensePauliMap> multiply_strings<DensePauliMap>(
const DensePauliMap &first, const DensePauliMap &second) {
quarter_turns_t total_turns = 0;
DensePauliMap result;
DensePauliMap::const_iterator fi = first.begin();
DensePauliMap::const_iterator si = second.begin();
while (fi != first.end() && si != second.end()) {
const std::pair<quarter_turns_t, Pauli> &prod =
get_mult_matrix().at({*fi, *si});
total_turns += prod.first;
result.push_back(prod.second);
++fi;
++si;
}
while (fi != first.end()) {
result.push_back(*fi);
++fi;
}
while (si != second.end()) {
result.push_back(*si);
++si;
}
return {total_turns, result};
}
template <>
no_coeff_t multiply_coeffs<no_coeff_t>(const no_coeff_t &, const no_coeff_t &) {
return {};
}
template <>
quarter_turns_t multiply_coeffs<quarter_turns_t>(
const quarter_turns_t &first, const quarter_turns_t &second) {
return (first + second) % 4;
}
template <>
Complex multiply_coeffs<Complex>(const Complex &first, const Complex &second) {
return first * second;
}
template <>
Expr multiply_coeffs<Expr>(const Expr &first, const Expr &second) {
return first * second;
}
static const CmplxSpMat const_2x2_matrix(
Complex tl, Complex tr, Complex bl, Complex br) {
CmplxSpMat m(2, 2);
if (tl != czero) {
m.insert(0, 0) = tl;
}
if (tr != czero) {
m.insert(0, 1) = tr;
}
if (bl != czero) {
m.insert(1, 0) = bl;
}
if (br != czero) {
m.insert(1, 1) = br;
}
return m;
}
static const CmplxSpMat &pauli_sparse_mat(Pauli p) {
static const CmplxSpMat I_mat = const_2x2_matrix(1, 0, 0, 1);
static const CmplxSpMat X_mat = const_2x2_matrix(0, 1, 1, 0);
static const CmplxSpMat Y_mat = const_2x2_matrix(0, -i_, i_, 0);
static const CmplxSpMat Z_mat = const_2x2_matrix(1, 0, 0, -1);
switch (p) {
case Pauli::X:
return X_mat;
case Pauli::Y:
return Y_mat;
case Pauli::Z:
return Z_mat;
default:
TKET_ASSERT(p == Pauli::I);
return I_mat;
}
}
template <>
CmplxSpMat to_sparse_matrix<QubitPauliMap>(const QubitPauliMap &paulis) {
DensePauliMap matrix_paulis;
for (const std::pair<const Qubit, Pauli> &pair : paulis)
matrix_paulis.push_back(pair.second);
return to_sparse_matrix<DensePauliMap>(matrix_paulis);
}
template <>
CmplxSpMat to_sparse_matrix<DensePauliMap>(const DensePauliMap &paulis) {
CmplxSpMat result = CmplxSpMat(1, 1);
result.insert(0, 0) = 1.;
for (Pauli p : paulis) {
const CmplxSpMat pauli_mat = pauli_sparse_mat(p);
result = Eigen::KroneckerProductSparse(result, pauli_mat).eval();
}
return result;
}
template <>
CmplxSpMat to_sparse_matrix<QubitPauliMap>(
const QubitPauliMap &paulis, unsigned n_qubits) {
qubit_vector_t qubits(n_qubits);
for (unsigned i = 0; i < n_qubits; ++i) qubits.at(i) = Qubit(i);
return to_sparse_matrix<QubitPauliMap>(paulis, qubits);
}
template <>
CmplxSpMat to_sparse_matrix<DensePauliMap>(
const DensePauliMap &paulis, unsigned n_qubits) {
if (n_qubits < paulis.size())
throw std::logic_error(
"Called to_sparse_matrix for fewer qubits than in the Pauli string.");
DensePauliMap matrix_paulis = paulis;
for (unsigned i = paulis.size(); i < n_qubits; ++i)
matrix_paulis.push_back(Pauli::I);
return to_sparse_matrix<DensePauliMap>(matrix_paulis);
}
template <>
CmplxSpMat to_sparse_matrix<QubitPauliMap>(
const QubitPauliMap &paulis, const qubit_vector_t &qubits) {
DensePauliMap matrix_paulis(qubits.size(), Pauli::I);
std::map<Qubit, unsigned> index_map;
for (const Qubit &q : qubits)
index_map.insert({q, (unsigned)index_map.size()});
if (index_map.size() != qubits.size())
throw std::logic_error(
"Qubit list given to to_sparse_matrix contains repeats.");
for (const std::pair<const Qubit, Pauli> &pair : paulis) {
std::map<Qubit, unsigned>::iterator found = index_map.find(pair.first);
if (found == index_map.end())
throw std::logic_error(
"Qubit list given to to_sparse_matrix doesn't contain " +
pair.first.repr());
matrix_paulis.at(found->second) = pair.second;
}
return to_sparse_matrix<DensePauliMap>(matrix_paulis);
}
template <>
CmplxSpMat to_sparse_matrix<DensePauliMap>(
const DensePauliMap &paulis, const qubit_vector_t &qubits) {
return to_sparse_matrix<QubitPauliMap>(
cast_container<DensePauliMap, QubitPauliMap>(paulis), qubits);
}
} // namespace tket
| tket/tket/src/Utils/PauliTensor.cpp/0 | {
"file_path": "tket/tket/src/Utils/PauliTensor.cpp",
"repo_id": "tket",
"token_count": 8966
} | 396 |
// Copyright 2019-2024 Cambridge Quantum Computing
//
// 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.
#include "tket/ZX/Rewrite.hpp"
namespace tket {
namespace zx {
Rewrite Rewrite::to_graphlike_form() {
return Rewrite::sequence(
{Rewrite::rebase_to_zx(), Rewrite::red_to_green(),
Rewrite::spider_fusion(), Rewrite::parallel_h_removal(),
Rewrite::io_extension(), Rewrite::separate_boundaries()});
}
Rewrite Rewrite::reduce_graphlike_form() {
Rewrite reduce = Rewrite::sequence(
{Rewrite::repeat(Rewrite::remove_interior_cliffords()),
Rewrite::extend_at_boundary_paulis(),
Rewrite::repeat(Rewrite::remove_interior_paulis()),
Rewrite::gadgetise_interior_paulis()});
return Rewrite::sequence(
{reduce, Rewrite::repeat_while(Rewrite::merge_gadgets(), reduce)});
}
Rewrite Rewrite::to_MBQC_diag() {
return Rewrite::sequence(
{Rewrite::rebase_to_mbqc(), Rewrite::extend_for_PX_outputs(),
Rewrite::repeat(Rewrite::internalise_gadgets())});
}
} // namespace zx
} // namespace tket
| tket/tket/src/ZX/ZXRWSequences.cpp/0 | {
"file_path": "tket/tket/src/ZX/ZXRWSequences.cpp",
"repo_id": "tket",
"token_count": 546
} | 397 |
// Copyright 2019-2024 Cambridge Quantum Computing
//
// 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.
#pragma once
#include "tket/Circuit/Circuit.hpp"
namespace tket {
/** These circuits are not necessarily fundamentally significant,
* but they do appear in multiple places in the tests.
*/
struct CircuitsForTesting {
Circuit uccsd;
/** This is often accompanied by the comment
* "add some arbitrary rotations to get away from |00> state".
*/
Circuit prepend_2qb_circuit;
/** The same initial ops as for "prepend_2qb_circuit",
* which is the case N=2, but for N >= 2 qubits.
* @param qubits The number of qubits in the circuit; must be >= 2.
* @return A circuit with rotations to get away from |00> state.
*/
static Circuit get_prepend_circuit(unsigned qubits);
/** Adds the same ops as get_prepend_circuit and prepend_2qb_circuit
* to an already constructed circuit.
*/
static void add_initial_prepend_ops(Circuit& circ);
/** Constructed once and shared between tests.
* The caller need not make a copy if not required.
*/
static const CircuitsForTesting& get();
CircuitsForTesting();
};
} // namespace tket
| tket/tket/test/src/CircuitsForTesting.hpp/0 | {
"file_path": "tket/tket/test/src/CircuitsForTesting.hpp",
"repo_id": "tket",
"token_count": 493
} | 398 |
// Copyright 2019-2024 Cambridge Quantum Computing
//
// 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.
#include <boost/graph/adjacency_list.hpp>
#include <catch2/catch_test_macros.hpp>
#include <iostream>
#include <vector>
#include "boost/range/iterator_range_core.hpp"
#include "tket/Graphs/DirectedGraph.hpp"
#include "tket/Utils/UnitID.hpp"
namespace tket {
namespace graphs {
namespace tests {
namespace test_DirectedGraph {
SCENARIO("Correct creation of DirectedGraph graphs") {
GIVEN("Construct empty graph of nodes") {
std::vector<Node> nodes{Node(3), Node(2), Node(5), Node(1)};
DirectedGraph<Node> uidgraph(nodes);
CHECK(uidgraph.n_nodes() == 4);
CHECK(uidgraph.n_connected() == 0);
CHECK(uidgraph.node_exists(Node(3)));
CHECK(uidgraph.node_exists(Node(1)));
CHECK(uidgraph.node_exists(Node(5)));
CHECK(uidgraph.node_exists(Node(2)));
CHECK(!uidgraph.node_exists(Node(4)));
CHECK(!uidgraph.node_exists(Node(0)));
}
GIVEN("Construct Qubit graph from edges") {
using Conn = DirectedGraph<Qubit>::Connection;
std::vector<Conn> edges{
{Qubit(0), Qubit(2)},
{Qubit(3), Qubit(6)},
{Qubit(6), Qubit(2)},
{Qubit(2), Qubit(1)},
{Qubit(1), Qubit(0)}};
DirectedGraph<Qubit> uidgraph(edges);
CHECK(uidgraph.n_nodes() == 5);
CHECK(uidgraph.n_connected() == 5);
CHECK(uidgraph.edge_exists(Qubit(0), Qubit(2)));
CHECK(uidgraph.edge_exists(Qubit(3), Qubit(6)));
CHECK(uidgraph.edge_exists(Qubit(6), Qubit(2)));
CHECK(uidgraph.edge_exists(Qubit(2), Qubit(1)));
CHECK(uidgraph.edge_exists(Qubit(1), Qubit(0)));
}
GIVEN("Construct qubit graph with invalid edges.") {
using Conn = DirectedGraph<Qubit>::Connection;
std::vector<Conn> edges{{Qubit(0), Qubit(0)}};
CHECK_THROWS(DirectedGraph<Qubit>(edges));
edges = {{Qubit(0), Qubit(1)}};
DirectedGraph<Qubit> uidgraph(edges);
CHECK_THROWS(uidgraph.add_connection(Qubit(0), Qubit(0)));
}
GIVEN("Construct graph using member functions") {
std::vector<Node> uids = {Node(4), Node(1), Node(0), Node(1231)};
DirectedGraph<Node> uidgraph;
for (auto u : uids) uidgraph.add_node(u);
uidgraph.add_connection(uids[0], uids[3], 3);
uidgraph.add_connection(uids[2], uids[3], 0);
CHECK(uidgraph.edge_exists(uids[0], uids[3]));
CHECK(uidgraph.edge_exists(uids[2], uids[3]));
CHECK(uidgraph.n_connections() == 2);
CHECK(uidgraph.get_connection_weight(uids[0], uids[3]) == 3);
CHECK(uidgraph.n_nodes() == 4);
uidgraph.remove_connection(uids[0], uids[3]);
uidgraph.remove_stray_nodes();
CHECK(uidgraph.n_nodes() == 2);
CHECK(uidgraph.n_connections() == 1);
}
}
SCENARIO("Access underlying undirected connectivity") {
GIVEN("some directed graph") {
using Conn = DirectedGraph<Node>::Connection;
std::vector<Conn> edges{{Node(0), Node(2)}, {Node(0), Node(4)},
{Node(3), Node(6)}, {Node(6), Node(3)},
{Node(6), Node(2)}, {Node(2), Node(1)},
{Node(1), Node(0)}};
DirectedGraph<Node> uidgraph(edges);
CHECK(uidgraph.n_connections() == edges.size());
auto& g = uidgraph.get_undirected_connectivity();
CHECK(boost::num_edges(g) == edges.size() - 1);
}
}
SCENARIO("Disconnected graphs") {
// TKET-1425
GIVEN("a disconnected graph") {
using Conn = DirectedGraph<Node>::Connection;
std::vector<Conn> edges{{Node(0), Node(1)}, {Node(2), Node(3)}};
DirectedGraph<Node> uidgraph(edges);
CHECK(uidgraph.get_distance(Node(0), Node(0)) == 0);
CHECK(uidgraph.get_distance(Node(2), Node(3)) == 1);
CHECK_THROWS(uidgraph.get_distance(Node(0), Node(2)));
}
}
} // namespace test_DirectedGraph
} // namespace tests
} // namespace graphs
} // namespace tket
| tket/tket/test/src/Graphs/test_DirectedGraph.cpp/0 | {
"file_path": "tket/tket/test/src/Graphs/test_DirectedGraph.cpp",
"repo_id": "tket",
"token_count": 1850
} | 399 |
Subsets and Splits